# CortexDB: full documentation > Every CortexDB v2 documentation page, concatenated for LLM consumption. Server target: v0.16.1. > Canonical HTML: https://cortexdb.ai/docs · Curated index: https://cortexdb.ai/llms.txt ========================================================================================== # What is CortexDB? _The long-term memory layer for AI agents: durable memory, connected context, and practical ways to integrate memory into real workflows._ Source: https://cortexdb.ai/docs/index **CortexDB is the long-term memory layer for AI agents.** It helps teams give agents and AI applications durable memory, connected context, and practical ways to integrate memory into real workflows. Whether you are building an internal copilot, a support assistant, an engineering knowledge layer, a voice agent for a contact center, or a companion-style application, CortexDB is designed to help memory become a first-class part of the product. > **Note: Start on CortexDB Cloud** [CortexDB Cloud](https://cortexdb.ai/docs/cloud) runs this release at `https://api-v1.cortexdb.ai`: sign up, create a token and store your first memory in two minutes, free to start ([Plans and limits](https://cortexdb.ai/docs/cloud/plans)). If you need CortexDB on-prem or on your own infrastructure, [talk to us](https://cortexdb.ai/contact) and we will provide a self-host license ([Self-Hosting](https://cortexdb.ai/docs/self-hosting)). ## Why CortexDB? AI systems often struggle with continuity. They lose context between sessions, forget important prior decisions, and cannot easily draw from the full working memory of a team, product, or organization. Teams use CortexDB when they want to: - give agents durable memory beyond a single conversation - give a phone or voice agent memory during a live call, in milliseconds ([Voice Mode](https://cortexdb.ai/docs/features/voice-mode)) - connect knowledge across tools like Slack, GitHub, and Jira - provide richer context to workflows, copilots, and assistants - support multi-tenant and enterprise use cases - make memory accessible through SDKs, APIs, and MCP-compatible tools ## Key advantages - **Cloud or your own infrastructure**: start on CortexDB Cloud with nothing to run, or, with a self-host license, run the same server yourself and control where your data is stored and processed. - **Built for AI memory**: designed around memory workflows: storing context, retrieving it later, and connecting related information across sessions. - **Integration ready**: use CortexDB with popular agent frameworks, SDKs, connectors, and MCP-compatible tools. - **Connected context**: work with relationships, history, and related context instead of isolated text fragments. - **Operational workflows**: power developer tools, support workflows, research assistants, copilots, and customer-facing AI products from one memory layer. - **Multi-tenant and governed**: organize memory by tenant, team, or application and support enterprise operational requirements. - **Shared memory with access control**: one memory for a company's sources, applications and team brain, where every read is checked against who is asking, private spaces stay private, and access changes are previewed before they apply ([Shared Memory](https://cortexdb.ai/docs/shared-memory)). ## How CortexDB fits into your stack CortexDB sits between your applications and the knowledge they need to retain and retrieve. It commonly works with application events and user interactions; chat, ticketing, and collaboration systems; code and engineering systems; agent frameworks and orchestration layers; and API/SDK/MCP tool environments. **Connect → Capture → Retrieve → Operate:** connect via SDKs, APIs, connectors, or MCP; capture the interactions, events, documents, and decisions your AI system should remember; retrieve relevant context during prompts, workflows, and agent runs; operate as part of production AI systems that need persistent memory and cross-tool context. ## Integrations and connectors CortexDB ships **37 framework integrations** and **18 connectors**. - **Agent frameworks (17)**: AG2 · AutoGen · Agno · BeeAI · CAMEL-AI · ControlFlow · CrewAI · Eliza OS · Google ADK · Hermes Agent · LangGraph · Letta · Mastra · OpenAI Agents SDK · OpenClaw · PydanticAI · Smolagents - **LLM app and RAG frameworks (5)**: LangChain · LlamaIndex · DSPy · Instructor · Vercel AI SDK - **Safety (1)**: NeMo Guardrails - **Workflow and orchestration (3)**: Temporal · Prefect · Apache Airflow - **No-code and low-code (5)**: n8n · Zapier · Make · Flowise · Dify - **Model backends (6)**: Ollama · vLLM · Groq · Together AI · Fireworks AI · DeepInfra - **Data Connectors (18)**: Slack · GitHub · GitLab · Jira · Freshdesk · tl;dv · Linear · Confluence · Notion · PagerDuty · Discord · Microsoft Teams · Google Workspace · Salesforce · HubSpot · Zendesk · Intercom · ServiceNow > **Note:** Every connector runs with the `cortexdb-sync` CLI against CortexDB Cloud or your own server (a managed sync worker is also available). See [Connectors](https://cortexdb.ai/docs/connectors). ## Access surfaces | Artifact | Install package / command | Import or executable | |---|---|---| | Python SDK | `pip install cortexdbai` | `from cortexdb.v1 import V1Client` | | TypeScript SDK | `npm install cortexdbai` | `import { V1Client } from "cortexdbai/v1"` | | CLI | `pip install cortexdb-cli` | `cortexdb` | | MCP server | `pip install cortexdb-mcp` | `cortexdb-mcp` (local); the server also serves remote MCP at `/mcp` ([Connecting AI Assistants](https://cortexdb.ai/docs/connect-assistants)) | | REST API | none | `http://localhost:3141` (self-hosted) · `https://api-v1.cortexdb.ai` ([CortexDB Cloud](https://cortexdb.ai/docs/cloud)) | The install package names are intentionally artifact-specific: **`cortexdbai`** for the SDKs, **`cortexdb-cli`** for the CLI, and **`cortexdb-mcp`** for MCP clients. ## Quick example On [CortexDB Cloud](https://cortexdb.ai/docs/cloud), with the API token and actor from your [dashboard](https://cortexdb.ai/dashboard): ```python import os from cortexdb.v1 import V1Client client = V1Client( api_url="https://api-v1.cortexdb.ai", actor="user:acct_42", # your actor, from the dashboard bearer=os.environ["CORTEXDB_TOKEN"], # your API token ) scope = "org:acct_42/user:acct_42" # Capture an experience client.experience( scope=scope, text="We decided to migrate from PostgreSQL to CockroachDB for the payments service. Timeline is Q2 2026.", observed_at="2026-05-16T10:42:00Z", idempotency_key="decision-payments-001", wait="indexed", ) # Recall a stratified pack (events + episodes + facts + beliefs + understanding) pack = client.recall( scope=scope, query="What database are we using for payments?", view="holistic", include=["events", "beliefs", "facts", "episodes"], ) print(pack.get("context_block", "")) ``` Running a [licensed server](https://cortexdb.ai/docs/self-hosting/quickstart) yourself? Point `api_url` at `http://localhost:3141` with `actor="user:local"`, and pass your server's key as `bearer=` (or no bearer on a dev server started with `CORTEX_INSECURE_NO_AUTH=1`). The [CortexDB Cloud Quickstart](https://cortexdb.ai/docs/cloud) has the full walkthrough. ## Next steps - [Self-Hosting Quickstart](https://cortexdb.ai/docs/self-hosting/quickstart): **start here:** one `docker run` to a running server. - [Python Quickstart](https://cortexdb.ai/docs/quickstart/python) · [TypeScript Quickstart](https://cortexdb.ai/docs/quickstart/typescript): the SDKs against your instance. - [Integrations](https://cortexdb.ai/docs/integrations): CortexDB in popular agent and application frameworks. - [Connecting AI Assistants](https://cortexdb.ai/docs/connect-assistants): Claude, ChatGPT, Cursor and other assistants over MCP. - [Shared Memory](https://cortexdb.ai/docs/shared-memory): org trees, change sets, per-person tokens and operator modes. - [REST API](https://cortexdb.ai/docs/sdks/rest-api): direct HTTP reference with curl examples. ========================================================================================== # Getting Started _The fastest paths to a stored-and-recalled memory. Start on CortexDB Cloud (or your own licensed server), then pick the Python or TypeScript quickstart._ Source: https://cortexdb.ai/docs/quickstart Two steps get you from nothing to a working memory: run a server, then talk to it from your language. ## 1. Run a server > **Note: Start on CortexDB Cloud** The [CortexDB Cloud Quickstart](https://cortexdb.ai/docs/cloud) gets you an endpoint (`https://api-v1.cortexdb.ai`) and an API token in two minutes, with nothing to run. The quickstarts below work the same against it: use that base URL, your token as the bearer and your actor from the dashboard. If you need CortexDB on-prem or on your own infrastructure, [talk to us](https://cortexdb.ai/contact) and we will provide a self-host license; licensed servers start from the [Self-Hosting Quickstart](https://cortexdb.ai/docs/self-hosting/quickstart). ## 2. Pick your language | Quickstart | Package | Best for | |---|---|---| | [Python](https://cortexdb.ai/docs/quickstart/python) | `pip install cortexdbai` | Agents, notebooks, backend services | | [TypeScript](https://cortexdb.ai/docs/quickstart/typescript) | `npm install cortexdbai` | Node and browser apps | Both quickstarts assume a server from step 1 and cover the same three calls: `experience` (write), `recall` (read a stratified pack), and `answer` (cited natural-language Q&A). ## Other ways in - [REST API](https://cortexdb.ai/docs/sdks/rest-api): direct HTTP with curl, if you're not using an SDK. - [CLI](https://cortexdb.ai/docs/sdks/cli): `pip install cortexdb-cli` for a shell-native workflow. - [MCP Server](https://cortexdb.ai/docs/sdks/mcp-server): give Claude Code, Cursor or any MCP client persistent memory. - [CortexDB for AI coding agents](https://cortexdb.ai/docs/coding-agents): have your coding assistant generate correct CortexDB code. ## Once it's running - [Core Concepts](https://cortexdb.ai/docs/concepts): the five memory layers, scopes, and the bi-temporal model. - [Self-hosting defaults](https://cortexdb.ai/docs/self-hosting/defaults): what's on out of the box and what's opt-in. ========================================================================================== # Python Quickstart _Get from zero to a working stratified pack in under 5 minutes with the Python SDK._ Source: https://cortexdb.ai/docs/quickstart/python > **Note: Your own server instead of the cloud?** This page uses [CortexDB Cloud](https://cortexdb.ai/docs/cloud). Against your own server, construct the client with `api_url="http://localhost:3141"`, `actor="user:local"` and a scope such as `SCOPE = "org:demo/user:local"` (a dev server started with `CORTEX_INSECURE_NO_AUTH=1` needs no token; on a keyed server pass `bearer=""`), and jump to step 4. ## 1. Install ```bash pip install cortexdbai ``` | Package | Name | |---|---| | PyPI package | `cortexdbai` | | Python import | `cortexdb.v1` | Requires Python 3.10+. The HTTP dependencies (`requests`, `httpx`) are installed automatically with the package. ## 2. Get a token Sign up at [cortexdb.ai/signup/free](https://cortexdb.ai/signup/free) (free, no card), then open your [dashboard](https://cortexdb.ai/dashboard) and choose **Create an API token**. The dashboard shows your actor and your default scope next to it. ```bash export CORTEXDB_TOKEN='' # PASETO v4 bearer, valid 90 days ``` ```python import os TOKEN = os.environ["CORTEXDB_TOKEN"] ACTOR = "user:acct_42" # your actor, from the dashboard SCOPE = "org:acct_42/user:acct_42" # your default scope, from the dashboard ``` The token reaches only your own account (`org:acct_42` and the [tenants](https://cortexdb.ai/docs/cloud/tenants) under it). Create a new one from the dashboard at any time; an operator running their own identity provider mints tokens the same way with [`POST /v1/auth/tokens`](https://cortexdb.ai/docs/api-reference/auth). ## 3. Open a client ```python from cortexdb.v1 import V1Client client = V1Client( api_url="https://api-v1.cortexdb.ai", actor=ACTOR, bearer=TOKEN, ) print(client.whoami()["effective_capabilities"]) ``` > **Note:** `api_url` defaults to `http://localhost:3141` (a locally running server). Pass the cloud URL explicitly, as above, when using CortexDB Cloud. ## 4. Capture an experience ```python result = client.experience( scope=SCOPE, text="Just got off a call with Priya at Acme. They upgraded to 200 seats.", role="user", observed_at="2026-05-16T10:42:00Z", idempotency_key="alice-chat-001", ) print(result["event_id"]) # "evt_01HX..." print(result["status"]) # "captured" ``` > **Note:** Pass `role=` and the SDK builds the right envelope; `modality` defaults to `conversation`. You may also pass an optional `modality=` label. Returns `202 Accepted` as soon as the WAL append succeeds. Pass `wait="indexed"` to block until BM25 + HNSW indexes have the event (30 s ceiling). `wait` is sent as `?wait=indexed` and works from every SDK and from raw REST; for longer waits use `GET /v1/lifecycle/stream?event_id=evt_…` (see [Lifecycle](https://cortexdb.ai/docs/concepts/lifecycle)). ## 5. Recall a stratified pack ```python pack = client.recall( scope=SCOPE, view="holistic", query="What did we decide about Acme's renewal?", include=["events", "beliefs", "facts", "episodes"], budgets={"max_tokens": 4000}, diagnostics="none", # cloud tokens don't hold diagnostics.read ) print(pack.get("context_block", "")) for fact in pack["layers"].get("facts", []): print(fact["predicate"], "=", fact["object"]["value"]) ``` **Cloud token capabilities.** `diagnostics="summary"`/`"full"` require the `diagnostics.read` capability, which a CortexDB Cloud token doesn't include: pass `diagnostics="none"` on the cloud. **Views.** Cloud tokens hold `scope.read.local`, `scope.read.holistic`, and `scope.read.descend`, so `view="holistic"` works out of the box. The accepted recall views are **`raw`, `granular` (alias `local`), `holistic`, `descend`, `lineage`, `structured`**: `local` is accepted and normalizes to `granular`. ## 6. Recall + LLM in one call ```python answer = client.answer( scope=SCOPE, question="Did Acme renew?", view="holistic", temporal={"natural": "last 30 days"}, diagnostics="none", ) print(answer["answer"]) for c in answer["citations"]: print(f" {c['marker']} → {c['layer']}:{c['id']}") ``` `answer()` is natural-language Q&A with full citations back to the events that supported the answer: build your UI around this. ## 7. Inspect why a belief exists > **Note:** Facts populate within ~5 to 30 s of a write (LLM-extracted; requires enrichment configured: on a bare self-hosted instance the Facts/Beliefs layers stay empty, see [Self-hosting defaults](https://cortexdb.ai/docs/self-hosting/defaults)). Beliefs and Understanding are synthesized async (minutes+). Use `client.facts(scope=…)` as a smoke-test that extraction is running. ```python beliefs = client.beliefs(scope=SCOPE) if beliefs["items"]: top = beliefs["items"][0] trail = client.belief_why(top["id"]) # belief items key their id as `id`, not `belief_id` print(trail["narrative"]) ``` ## What's next - [The Experience Envelope](https://cortexdb.ai/docs/concepts/experience-envelope): full shape, content kinds, directives - [The Five Memory Layers](https://cortexdb.ai/docs/concepts/layers): when to read which layer - [Scopes](https://cortexdb.ai/docs/concepts/scopes) · [Bi-temporal queries](https://cortexdb.ai/docs/concepts/bi-temporal) · [Lifecycle](https://cortexdb.ai/docs/concepts/lifecycle) - [Python SDK reference](https://cortexdb.ai/docs/sdks/python) ## Async variant ```python import asyncio from cortexdb.v1 import AsyncV1Client async def main(): async with AsyncV1Client( api_url="https://api-v1.cortexdb.ai", actor=ACTOR, bearer=TOKEN, ) as client: pack = await client.recall(scope=SCOPE, view="holistic", diagnostics="none") print(pack.get("context_block", "")) asyncio.run(main()) ``` ========================================================================================== # TypeScript Quickstart _Get from zero to stored-and-retrieved memory in three lines with the TypeScript SDK._ Source: https://cortexdb.ai/docs/quickstart/typescript > **Note: Your own server instead of the cloud?** This page uses [CortexDB Cloud](https://cortexdb.ai/docs/cloud). Against your own **dev** server (started with `CORTEX_INSECURE_NO_AUTH=1`) you need no token: construct `new V1Client({ apiUrl: "http://localhost:3141", actor: "user:local" })` and use a scope such as `org:demo/user:local`. On a keyed server pass `bearer: ""`. ## 1. Install ```bash npm install cortexdbai # or: pnpm add cortexdbai / yarn add cortexdbai ``` > **Note:** The npm package is **`cortexdbai`**, not `cortexdb`. The bare `cortexdb` name on npm is a **different, unaffiliated package**: installing it will not give you this SDK. Always `cortexdbai`. (If your AI coding agent autocompletes `cortexdb`, correct it.) Requires Node 18+ (or any runtime with `fetch` and `AbortController`). ## 2. Connect to CortexDB Cloud Sign up at [cortexdb.ai/signup/free](https://cortexdb.ai/signup/free) (free, no card), then choose **Create an API token** on your [dashboard](https://cortexdb.ai/dashboard), which also shows your actor and default scope. ```typescript import { V1Client } from "cortexdbai/v1"; const scope = "org:acct_42/user:acct_42"; // your default scope, from the dashboard const client = new V1Client({ apiUrl: "https://api-v1.cortexdb.ai", actor: "user:acct_42", // your actor, from the dashboard bearer: process.env.CORTEXDB_TOKEN!, // your API token (valid 90 days) }); await client.experience(scope, { text: "Just got off a call with Priya at Acme. They upgraded to 200 seats.", observedAt: new Date().toISOString(), idempotencyKey: "alice-chat-001", }, { wait: "indexed" }); const pack = await client.recall(scope, { query: "What did we decide about Acme?", diagnostics: "none", }); console.log(pack.context_block); ``` The token reaches only your own account (`org:acct_42` and the [tenants](https://cortexdb.ai/docs/cloud/tenants) under it); keep it out of browser code. Every call counts against your [plan](https://cortexdb.ai/docs/cloud/plans). ## 3. SDK call signatures The TypeScript SDK takes **camelCase** fields and flattens common cases: ```typescript // Capture await client.experience(scope, { text: "Acme upgraded to 200 seats.", role: "user", // optional, default "user" observedAt: new Date().toISOString(), idempotencyKey: "alice-chat-002", labels: ["acme", "renewal"], }); // Recall const pack = await client.recall(scope, { view: "holistic", // raw | granular (alias local) | holistic | descend | lineage | structured query: "What did we decide?", include: ["beliefs", "facts", "episodes"], budgets: { max_tokens: 4000 }, // budgets use the wire (snake_case) names diagnostics: "none", // "summary" needs diagnostics.read (not on a cloud token) }); // Recall + LLM answer const ans = await client.answer(scope, { question: "Did Acme renew?", view: "holistic", temporal: { natural: "last 30 days" }, diagnostics: "none", }); ``` The **wire format** (raw JSON `POST /v1/experience` accepts) uses snake_case and a nested `content`/`context` envelope: see the [Experience Envelope](https://cortexdb.ai/docs/concepts/experience-envelope) reference if you're building a raw-fetch client. ## 4. Explicit auth ```typescript import { V1Client } from "cortexdbai/v1"; const client = new V1Client({ apiUrl: "https://api-v1.cortexdb.ai", actor: "user:acct_42", bearer: process.env.CORTEXDB_TOKEN!, }); const me = await client.whoami(); console.log(me.effective_capabilities); // snake_case on the whoami response ``` For service accounts that mint additional tokens via `POST /v1/auth/tokens`, see the Auth API reference. ## 5. The `wait` parameter Default is async: `experience()` returns `202 Accepted` as soon as the WAL append succeeds. Pass `wait` to block until a later stage: ```typescript await client.experience(scope, { text: "...", observedAt: now, idempotencyKey: "k" }, { wait: "indexed" }); // returns once BM25 + HNSW have the event ``` Accepted values: `"accepted"` (alias for the omitted default) · `"captured"` · `"indexed"` · `"consolidated"` (30 s ceiling). For longer waits use `GET /v1/lifecycle/stream?event_id=…`. ## 6. Inspecting derived layers ```typescript const facts = await client.facts(scope); const beliefs = await client.beliefs(scope); const concepts = await client.understanding(scope); ``` Facts populate within ~5 to 30 s of a write (requires enrichment configured: see [Self-hosting defaults](https://cortexdb.ai/docs/self-hosting/defaults)); Beliefs/Understanding are eventually consistent. Use Facts for read-after-write sanity checks. ## What's next - [The Experience Envelope](https://cortexdb.ai/docs/concepts/experience-envelope) · [The Five Memory Layers](https://cortexdb.ai/docs/concepts/layers) - [Scopes](https://cortexdb.ai/docs/concepts/scopes) · [Bi-temporal queries](https://cortexdb.ai/docs/concepts/bi-temporal) · [Lifecycle](https://cortexdb.ai/docs/concepts/lifecycle) - [TypeScript SDK reference](https://cortexdb.ai/docs/sdks/typescript) ## Cancellation + timeouts ```typescript const client = new V1Client({ apiUrl: "https://api-v1.cortexdb.ai", actor: "user:alice", bearer: process.env.CORTEXDB_TOKEN!, timeoutMs: 30_000, }); // Supply your own fetch (tracing, retries): new V1Client({ apiUrl: "...", actor: "user:alice", fetch: myInstrumentedFetch }); ``` ========================================================================================== # CortexDB Cloud Quickstart _Sign up, create an API token and store and recall your first memory on CortexDB Cloud (api-v1.cortexdb.ai), in curl, Python or TypeScript._ Source: https://cortexdb.ai/docs/cloud **CortexDB Cloud** is CortexDB run for you at `https://api-v1.cortexdb.ai`: the same server these docs describe, with nothing to install. Every account gets its own isolated space; the Free plan needs no card. This page takes you from nothing to a stored and recalled memory in about two minutes. ## 1. Create an account Sign up at [cortexdb.ai/signup/free](https://cortexdb.ai/signup/free) with Google, or with an email and a password (then open the link in the confirmation email). Your account starts on the [Free plan](https://cortexdb.ai/docs/cloud/plans); paid plans are on [cortexdb.ai/pricing](https://cortexdb.ai/pricing). ## 2. Create an API token Open your [dashboard](https://cortexdb.ai/dashboard) and choose **Create an API token**. The dashboard shows everything a client needs: | | Example | What it is | |---|---|---| | Endpoint | `https://api-v1.cortexdb.ai` | Where every request goes. | | Token | `v4.public.…` | Send it as `Authorization: Bearer `. Valid 90 days; create a new one at any time. Keep it secret. | | Actor | `user:acct_42` | Who you are; send it as `X-Cortex-Actor` with every request. | | Scope | `org:acct_42/user:acct_42` | Where your memories live. Everything under `org:acct_42` is yours ([Tenants](https://cortexdb.ai/docs/cloud/tenants)). | The token works only inside your own account: it can never read or write another account's memories. ## 3. Store and recall a memory Replace `acct_42` with the account id your dashboard shows. ```bash export CORTEXDB_TOKEN='' export CORTEXDB_ACTOR='user:acct_42' SCOPE='org:acct_42/user:acct_42' # Write a memory and wait until it can be recalled curl -sS -X POST 'https://api-v1.cortexdb.ai/v1/experience?wait=indexed' \ -H "Authorization: Bearer $CORTEXDB_TOKEN" -H "X-Cortex-Actor: $CORTEXDB_ACTOR" \ -H 'Content-Type: application/json' \ -d '{"scope":"'"$SCOPE"'","modality":"conversation","content":{"kind":"message","role":"user","text":"Priya at Acme signed for 200 seats."}}' # Recall it curl -sS -X POST 'https://api-v1.cortexdb.ai/v1/recall' \ -H "Authorization: Bearer $CORTEXDB_TOKEN" -H "X-Cortex-Actor: $CORTEXDB_ACTOR" \ -H 'Content-Type: application/json' \ -d '{"scope":"'"$SCOPE"'","query":"How many seats did Acme sign for?"}' ``` The recall answers with a stratified pack whose `context_block` is ready to paste into a prompt ([POST /v1/recall](https://cortexdb.ai/docs/api-reference/recall)). ### Python ```python # pip install cortexdbai import os from cortexdb import Cortex scope = "org:acct_42/user:acct_42" with Cortex("https://api-v1.cortexdb.ai", actor="user:acct_42", bearer=os.environ["CORTEXDB_TOKEN"]) as c: c.experience(scope, text="Priya at Acme signed for 200 seats.", wait="indexed") print(c.recall(scope, query="How many seats did Acme sign for?")["context_block"]) ``` ### TypeScript `npm install cortexdbai`, then follow the [TypeScript quickstart](https://cortexdb.ai/docs/quickstart/typescript) with `https://api-v1.cortexdb.ai` as the base URL, your token as the bearer and your actor. ## 4. Ask for an answer `POST /v1/answer` writes a cited reply from your memories with a language model. Answers have their own monthly allowance on every plan ([Plans and limits](https://cortexdb.ai/docs/cloud/plans)). ```bash curl -sS -X POST 'https://api-v1.cortexdb.ai/v1/answer' \ -H "Authorization: Bearer $CORTEXDB_TOKEN" -H "X-Cortex-Actor: $CORTEXDB_ACTOR" \ -H 'Content-Type: application/json' \ -d '{"scope":"'"$SCOPE"'","question":"How many seats did Acme sign for?"}' ``` ## Next - [Plans and limits](https://cortexdb.ai/docs/cloud/plans): what each plan allows, what counts, and what a refusal looks like. - [Tenants on the cloud](https://cortexdb.ai/docs/cloud/tenants): keep your apps' and customers' memories apart under your account. - [MCP Server](https://cortexdb.ai/docs/sdks/mcp-server): give Claude Code, Cursor or another MCP client memory on the cloud. - [Core Concepts](https://cortexdb.ai/docs/concepts): memory layers, scopes and time. > **Note: Running CortexDB on your own servers** If you need CortexDB on-prem or on your own infrastructure, [talk to us](https://cortexdb.ai/contact) and we will provide a self-host license; licensed releases come from the [customer portal](https://customer.cortexdb.ai). Self-hosted servers have no plan limits: the [Self-Hosting](https://cortexdb.ai/docs/self-hosting) pages cover them. ========================================================================================== # Plans and limits _What each CortexDB Cloud plan allows (memories, recalls, answers, tenants, request rate), what counts against it, and the 402 and 429 answers past a limit._ Source: https://cortexdb.ai/docs/cloud/plans Every CortexDB Cloud account is on a plan. The server enforces it: past a limit a request is refused and nothing is done, so a limit is never a surprise bill. Prices are on [cortexdb.ai/pricing](https://cortexdb.ai/pricing); you change plans from your [dashboard](https://cortexdb.ai/dashboard). | | Free | Starter | Pro | Enterprise | |---|---|---|---|---| | Memories | 10,000 | 100,000 | 1,000,000 | Custom | | Recalls a month | 1,000 | 25,000 | 150,000 | Custom | | Answers a month | 100 | 2,500 | 15,000 | Custom | | Tenants | 1 | 5 | 20 | Custom | | Requests | 60 a minute | 300 a minute | about 1,000 a minute | about 5,000 a minute, or custom | Self-hosted servers have no plan and no limits; everything on this page is about the cloud. ## What counts - **Memories** are the memories your account stores, each up to **2,000 characters** of its text (a memory's `text`, a blob's `transcript`, otherwise its serialized content). A longer memory counts once per started 2,000 characters: 5,000 characters count 3. Writes (`/v1/experience`, each item of `/v1/experience/bulk`) add to the count; forgetting or erasing memories gives the room back. - **Recalls** are `POST /v1/recall` and `/v1/recall/stream` requests, one each however many passes they make (and a `/v1/answer` sent with `skip_answer_llm`, which never reaches the model). - **Answers** are `POST /v1/answer` and `POST /v1/compose`, the requests that reach the answer model. They count against their own allowance, never against recalls. - **Tenants** are the scopes one level under your account, such as `org:acct_42/user:acct_42` or `org:acct_42/app:support` ([Tenants on the cloud](https://cortexdb.ai/docs/cloud/tenants)). Your first is the one your account starts with. - Listing memories, reading one by id, and the account's own plan (`GET /v1/plan`) count against none. Recalls and answers count per calendar month in UTC and start again on the first. ## Your plan and usage `GET /v1/plan` answers your account's plan, its limits (`null` is unlimited) and what you have used: ```bash curl -sS https://api-v1.cortexdb.ai/v1/plan \ -H "Authorization: Bearer $CORTEXDB_TOKEN" -H "X-Cortex-Actor: $CORTEXDB_ACTOR" ``` ```json { "subtree": "org:acct_42", "plan": "free", "limits": {"max_memories": 10000, "max_recalls_month": 1000, "max_answers_month": 100, "max_tenants": 1, "read_per_second": 1.0, "read_burst": 20.0, "write_per_second": 1.0, "write_burst": 20.0}, "usage": {"memories": 1234, "recalls_this_month": 56, "answers_this_month": 3, "tenants": 1}, "memory_unit_chars": 2000, "month": "2026-10", "resets_at": "2026-11-01T00:00:00+00:00", "upgrade_url": "https://cortexdb.ai/pricing" } ``` Your dashboard shows the same numbers. Every response to your token also carries the month's recall budget: `X-RateLimit-Monthly-Limit`, `X-RateLimit-Monthly-Remaining` and `X-RateLimit-Monthly-Reset` (none on an unlimited plan). ## Past a limit: `402 PLAN_LIMIT_REACHED` A request past a limit is refused before anything is done, with HTTP 402 and this body: ```json { "error_code": "PLAN_LIMIT_REACHED", "message": "the free plan of org:acct_42 allows 10000 stored memories; 10000 used. Upgrade at https://cortexdb.ai/pricing", "details": {"limit": "memories", "used": 10000, "max": 10000, "plan": "free", "subtree": "org:acct_42", "upgrade_url": "https://cortexdb.ai/pricing"}, "retriable": false, "request_id": "req_…" } ``` | `details.limit` | Refused | What to do | |---|---|---| | `memories` | A write that would pass the memory limit. A bulk is refused whole (nothing in it is written). | Forget memories you no longer need, or upgrade. | | `recalls_month` | A recall past the month's recalls. `resets_at` says when the count starts again. | Wait for `resets_at`, or upgrade. | | `answers_month` | An answer or compose past the month's answers, with `resets_at`. Plain recalls keep working. | Recall instead, wait for `resets_at`, or upgrade. | | `tenants` | The first write to a new tenant past the plan's count. Existing tenants keep working. | Write into an existing tenant, or upgrade. | `retriable` is `false`: the same request succeeds only after an upgrade, room is freed, or the month turns. ## Too fast: `429 SUBTREE_RATE_LIMITED` Each plan has a request rate for your whole account, reads and writes counted apart (Free: 1 a second with bursts of 20; Starter: 5 with 50; Pro: 17 with 100; Enterprise: 83 with 500). Recalls, answers and compose count as reads; each written memory counts as a write. Past it a request answers `429 SUBTREE_RATE_LIMITED` with `Retry-After` (whole seconds) and `retriable: true`, and nothing was done: wait that long and send it again. ## Changing plans Upgrade from your [dashboard](https://cortexdb.ai/dashboard) or [cortexdb.ai/pricing](https://cortexdb.ai/pricing); the new limits apply within a minute. A cancelled plan keeps its limits until the paid period ends, then moves to Free, and your data stays. Above Free's limits nothing is deleted: writes and new tenants are refused until there is room again. For limits beyond Pro, [talk to us](https://cortexdb.ai/contact). ## Taking your data out or deleting it The token from your dashboard writes, recalls, answers and forgets within your account, on every plan. It does not cover JSONL export or import (`POST /v1/export`, `POST /v1/import/jsonl`) or full erasure (`/v1/erasures`): those answer `403 POLICY_DENIED`. - **Remove particular memories** yourself with [`POST /v1/forget`](https://cortexdb.ai/docs/api-reference/forget), naming the events in its selector. - **Get a copy of all your data**, or **delete everything and close your account**: email [help@cortexdb.ai](mailto:help@cortexdb.ai) from your account's address. ========================================================================================== # Tenants on the cloud _Keep apps, teams and your own customers apart under one CortexDB Cloud account with tenant scopes, and read across them on purpose._ Source: https://cortexdb.ai/docs/cloud/tenants Your account is a scope subtree of its own, `org:acct_` (your dashboard shows the id). Everything your token writes or reads lies under it, and nothing outside it is reachable: another account's memories answer `403 POLICY_DENIED`, whatever scope you send. A **tenant** is a scope one level under your account. Use one per application, team or end customer whose memories must stay apart: ```text org:acct_42 your account (the plan applies here) ├── org:acct_42/user:acct_42 your first tenant: where the quickstart writes ├── org:acct_42/app:support a support assistant ├── org:acct_42/app:sales a sales copilot └── org:acct_42/user:cust_981 one of your own customers ``` Scope segments are `type:id` pairs ([Scopes](https://cortexdb.ai/docs/concepts/scopes)); the types an account can create are `user`, `agent`, `app`, `team`, `project` and `ws`. A tenant is created by the first write to it, and each plan allows a number of them ([Plans and limits](https://cortexdb.ai/docs/cloud/plans)): past it, the first write to a new tenant answers `402 PLAN_LIMIT_REACHED` with `limit: "tenants"`. Scopes deeper inside a tenant (`org:acct_42/app:support/user:alice`) don't count as tenants. ## Keeping tenants apart A recall reads the scope you send ([views](https://cortexdb.ai/docs/api-reference/recall#views) decide whether it includes the scope's ancestors or descendants). So a recall in `org:acct_42/app:support` never returns what `org:acct_42/app:sales` stored. Your account token can read every tenant; when you build on top of CortexDB for your own customers, send each customer's requests with that customer's tenant scope. ## Reading several on purpose: `extra_scopes` To answer from a tenant plus shared knowledge (for example an app's own memories and a shared `app:handbook`), list up to 40 more scopes of your account in `extra_scopes`. They are read in the same ranked pass, and each `context_block` line from one of them carries its last segment as a tag: ```bash curl -sS -X POST 'https://api-v1.cortexdb.ai/v1/recall' \ -H "Authorization: Bearer $CORTEXDB_TOKEN" -H "X-Cortex-Actor: $CORTEXDB_ACTOR" \ -H 'Content-Type: application/json' \ -d '{"scope":"org:acct_42/app:support","extra_scopes":["org:acct_42/app:handbook"],"query":"refund policy"}' ``` Each extra scope must lie in your account; one outside it, or more than 40, answers `422 INVALID_EXTRA_SCOPES`. Details: [POST /v1/recall](https://cortexdb.ai/docs/api-reference/recall#reading-several-scopes-extra_scopes). ## Usage per tenant `GET /v1/plan` reports your whole account. `GET /v1/usage?scope=` reports one scope: the memories stored under it (`storage`) and, for your account, its reads and writes ([Plans and usage](https://cortexdb.ai/docs/api-reference/plans-usage)). ========================================================================================== # Self-Hosting _Running CortexDB on-prem or on your own infrastructure under a self-host license. The same server the cloud runs. Start here._ Source: https://cortexdb.ai/docs/self-hosting > **Note: Start on CortexDB Cloud** We recommend starting on [CortexDB Cloud](https://cortexdb.ai/docs/cloud): sign up on cortexdb.ai and you have an endpoint and a token in two minutes, with nothing to run. If you need CortexDB on-prem or on your own infrastructure, [talk to us](https://cortexdb.ai/contact) and we will provide a self-host license. Licensed releases then come from the [customer portal](https://customer.cortexdb.ai), and these pages cover running them. **Self-hosting is for teams that need CortexDB on-prem or on their own infrastructure**, under a self-host license from CortexDB. The server you run yourself is the same one the cloud runs: the identical `cortexdb/cortexdb` image and the identical v1 API. Hosting it yourself means: - **You control where data is processed and stored.** External embedding, answer, enrichment or storage providers may receive data outside your network. For a fully local deployment, configure local providers and storage and verify outbound connections for every enabled component. - **No per-token or per-seat cost**: current releases run under a company license whose terms are agreed separately with your CortexDB contact. Beyond the license you pay only for the compute you run and the model APIs you choose to wire in (or none, if you run models locally). - **Full control**: pick your embedding and answer models, your storage backend, your auth and compliance posture. - **One binary**: a single Rust process; single-node handles ~10M events on commodity hardware. ## Start here > **Note: Five minutes to a running server** The [Self-Hosting Quickstart](https://cortexdb.ai/docs/self-hosting/quickstart) takes you from nothing to a stored-and- recalled memory with one `docker run`. Start there once you have a self-host license. ## The self-hosting path 1. **[Quickstart](https://cortexdb.ai/docs/self-hosting/quickstart)**: `docker run`, point at `localhost:3141`, first write + recall. 2. **[Defaults & prerequisites](https://cortexdb.ai/docs/self-hosting/defaults)**: what runs out of the box (content-only: capture, BM25 + vector recall) vs what's opt-in (blob extraction, Facts/Beliefs/ Understanding, the knowledge graph, cross-encoder rerank, and `/v1/answer`), and how to turn each on. 3. **[Configuration](https://cortexdb.ai/docs/operations/configuration)**: how config resolves (defaults → `cortex.toml` → env → CLI), and the ~100 `CORTEX_*` knobs. 4. **[Profiles & Presets](https://cortexdb.ai/docs/operations/profiles)**: copy-paste configs for common shapes, including a full Enterprise profile. ## Wire in the pieces you need - **[Embeddings](https://cortexdb.ai/docs/operations/embeddings)**: required for vector recall; OpenAI, Cohere, or a fully local Ollama. - **[LLM & Answer generation](https://cortexdb.ai/docs/operations/llm-answer)**: the answer lane (`CORTEX_ANSWER_*`) that powers `/v1/answer`, plus the extraction and enrichment lanes. - **[Storage & Cluster](https://cortexdb.ai/docs/operations/storage-cluster)**: WAL durability, HNSW shape, blob backends. - **[Media ingestion](https://cortexdb.ai/docs/features/media-ingestion)** · **[Code Intelligence Plane](https://cortexdb.ai/docs/features/code-plane)**. ## Operate it - **[Security & Compliance](https://cortexdb.ai/docs/operations/security-compliance)**: auth, TLS/mTLS, RBAC, audit, SIEM, GDPR erasure. - **[Backups & Disaster Recovery](https://cortexdb.ai/docs/enterprise/backups-dr)**: the verified cold-backup procedure. - **[Deployment Presets](https://cortexdb.ai/docs/enterprise/deployment-presets)**: `dev_local` / `on_prem_enterprise` / cloud postures. ## Self-hosted vs Cloud Both expose the **same v1 API**. Changing the base URL connects an application to a different server; it does not move existing data, scopes or access configuration. | | Self-hosted (licensed) | CortexDB Cloud | |---|---|---| | **Where data lives** | Your configured storage; external providers may receive data | CortexDB's infrastructure | | **Model API keys** | Yours; you choose the providers (or run models locally, so model calls stay on your machine) | Managed for you | | **Cost model** | Company license (terms agreed separately with your CortexDB contact) + your compute + whatever model APIs you wire in ($0 in model APIs with local models) | Tiered subscription | | **Who runs it** | You (one Docker container; single-node handles ~10M events) | CortexDB | | **Upgrades / ops** | You load new releases from the customer portal ([Upgrading](https://cortexdb.ai/docs/self-hosting/upgrading)) and run backups | Handled for you | | **Auth** | You set `CORTEX_API_KEY` (or your OIDC/IdP) | Provisioned tokens | | **Best when** | Data residency, cost control, air-gapped or regulated environments, full control | You'd rather not operate a server and want zero ops | Not sure? **Start on [CortexDB Cloud](https://cortexdb.ai/docs/cloud)**: free to start, nothing to run. If you need CortexDB on-prem or on your own infrastructure, [talk to us](https://cortexdb.ai/contact) and we will provide a self-host license. To move existing data to your own server later, plan and validate the data and access migration separately. ## Connectors, self-hosted Every one of the [18 connectors](https://cortexdb.ai/docs/connectors) runs against your own instance with the `cortexdb-sync` CLI: no dashboard required. Point it at `http://localhost:3141` and it ingests Slack, GitHub, Jira, and the rest into your scopes. > **Note: Moving between self-hosted and cloud** Point an application at `http://localhost:3141` (self-hosted) or `https://api-v1.cortexdb.ai` (cloud) with the appropriate credentials. An endpoint change does not transfer memories, scopes, credentials, permissions or derived state. Before cutover, establish a supported transfer path for your plan, verify data and access at the destination, and plan rollback. Contact support if the available route is unclear. ========================================================================================== # Self-Hosting Quickstart _Run your licensed CortexDB server with one docker run, then store and recall your first memory against localhost._ Source: https://cortexdb.ai/docs/self-hosting/quickstart > **Note: Start on CortexDB Cloud** We recommend starting on [CortexDB Cloud](https://cortexdb.ai/docs/cloud): sign up on cortexdb.ai and you have an endpoint and a token in two minutes, with nothing to run. If you need CortexDB on-prem or on your own infrastructure, [talk to us](https://cortexdb.ai/contact) and we will provide a self-host license. Licensed releases then come from the [customer portal](https://customer.cortexdb.ai), and these pages cover running them. **This page is for running a licensed CortexDB release yourself.** You control the server and storage; configured external model or storage providers may receive data outside your infrastructure. This page takes you from nothing to a running server with a stored-and-recalled memory in about five minutes. ## The quickest path The installer. On [customer.cortexdb.ai](https://customer.cortexdb.ai/releases), open the newest release and pick where it runs (x86-64 or ARM64; Docker or the plain binary, which needs glibc 2.39 or later on x86-64, for example Ubuntu 24.04), the embeddings (an OpenAI-compatible key, or local Ollama) and who connects (this machine only, or other machines with an API key). You get one command: ```bash export CORTEXDB_KEY='' # from the portal's Agent keys page export OPENAI_API_KEY='' # not with local Ollama curl -fsSL -H "Authorization: Bearer $CORTEXDB_KEY" -o cortexdb-install.sh \ "https://customer.cortexdb.ai/install.sh?version=latest&arch=amd64&kind=docker&provider=openai&auth=local" \ && bash cortexdb-install.sh ``` The installer carries your company's license, so there is nothing to paste: treat the downloaded script like a secret and delete it once the server is up. It checks the machine first (Docker, architecture, a free port, the embedding provider, the license), downloads the release into a fresh folder, verifies its SHA-256, installs, and then writes one memory and recalls it. It stops at the first failure with a sentence saying why, and never replaces or stops a container or install it didn't create. `CORTEXDB_PORT`, `CORTEXDB_NAME` and `CORTEXDB_DIR` move the port, the container name and the install folder. Read it before you run it: open the same address in a browser where you're signed in. The rest of this page is the same install by hand, and what to do with the server next. > **Note: Licensed images come from the portal** A licensed release's image is a file you `docker load` from customer.cortexdb.ai, tagged with its exact version, and it runs with your company's license ([Your license](https://cortexdb.ai/docs/self-hosting/license)). There is no public image to `docker pull`. ## Prerequisites - **A container runtime**: Docker (or Podman). CortexDB ships as a single image, `cortexdb/cortexdb`. - **An embedding provider**: vector recall needs one. Either an **OpenAI-compatible API key** (used *only* for embeddings) or a local **[Ollama](https://cortexdb.ai/docs/integrations/ollama)** (embedding calls stay on your machine; see [Local embeddings](#local-embeddings-no-provider-keys) below). Both are equally supported: use the **OpenAI key on modest hardware** (a laptop, no GPU, limited RAM or disk) or for the simplest setup, and **local Ollama on a high-end machine** or when vectors must stay on the box. Decide before your first write; the choice is [pinned to the data directory](https://cortexdb.ai/docs/operations/embeddings#the-provider-pin) and switching later is an offline rebuild. A container with an embedding endpoint configured but no credential **refuses to start** (`FATAL: an explicit CORTEX_EMBEDDING_URL requires CORTEX_EMBEDDING_API_KEY, OPENAI_API_KEY, or LLM_API_KEY`) instead of silently serving meaningless mock vectors; the image sets an OpenAI embedding URL by default, so the plain `docker run` needs a key. `CORTEX_EMBEDDING_PROVIDER=mock` is the explicit opt-in for control-path tests. - **~2 GB RAM and a data volume.** A single node handles ~10M events on commodity hardware; everything persists under `/data`. - **Optional, only if you want them:** an **answer lane** (`CORTEX_ANSWER_*`) to enable `/v1/answer`, and **enrichment** to populate the Facts/Beliefs/Understanding layers; both off by default. See [Self-hosting defaults](https://cortexdb.ai/docs/self-hosting/defaults). ## 1. Start the server Load the image from the release page first (its "Run the steps by hand" block downloads it, checks the SHA-256 and runs `docker load`). `docker images cortexdb/cortexdb` shows the tag it loaded. ```bash export CORTEX_LICENSE='' # in the release page's commands CORTEXDB_IMAGE=cortexdb/cortexdb:v0.16.1 # the tag docker load printed docker run -d \ --name cortexdb \ --restart unless-stopped \ --stop-timeout 120 \ -p 127.0.0.1:3141:3141 \ -v cortexdb-data:/data \ -e CORTEX_LICENSE \ -e CORTEX_INSECURE_NO_AUTH=1 \ -e CORTEX_EMBEDDING_API_KEY=$OPENAI_API_KEY \ "$CORTEXDB_IMAGE" ``` That's the whole install. The container ships with every field at its compiled default: single-node, the v1 API on `:3141`, data persisted to the `cortexdb-data` volume. `--restart unless-stopped` brings the server back after a console restart (which exits with code 75) or a crash, and `--stop-timeout 120` gives it the 120 seconds the server needs for a graceful stop (Docker's default is 10 seconds; see [Upgrading](https://cortexdb.ai/docs/self-hosting/upgrading)). > **Note: Why an OpenAI key, and why as CORTEX_EMBEDDING_API_KEY?** It's used **only for embeddings** (vector recall needs a real embedding provider; the server exits at startup rather than run on meaningless mock vectors). Passing it as `CORTEX_EMBEDDING_API_KEY` keeps it embeddings-only. Passed as plain `OPENAI_API_KEY`, the image's baked defaults also switch on entity extraction (a `gpt-4o-mini` call per write) and the `gpt-4.1` verifier lane, which you may not want on a first run. Prefer to keep everything local? Point embeddings at a local Ollama instead: see [Local embeddings, no provider keys](#local-embeddings-no-provider-keys) below. > **Note: Auth: CORTEX_INSECURE_NO_AUTH is dev-only** `CORTEX_INSECURE_NO_AUTH=1` makes the server serve requests with **no token** (as `user:local`, or as the named `X-Cortex-Actor`); the frictionless path for local development. The flag does not restrict the bind; the `-p 127.0.0.1:...` mapping is what keeps it on loopback only. **Before exposing the port**, drop that flag and set **`-e CORTEX_API_KEY=`** instead; the value itself becomes your bearer credential (`Authorization: Bearer `). Note: if you set **neither** on a network-exposed bind, the server refuses to serve open; it auto-generates a key and prints it in the boot log, and every request needs it. See [Security & Compliance](https://cortexdb.ai/docs/operations/security-compliance). > **Note: On a network, send the key with every request** Every deployment preset requires the key: a request carrying only an `X-Cortex-Actor` header gets `401 MISSING_TOKEN`. ## 2. Confirm it's healthy ```bash curl http://localhost:3141/v1/admin/health # {"status":"healthy","version":"vX.Y.Z"} <- the release you installed, e.g. the one on your Download page curl http://localhost:3141/v1/admin/ready # ... "degraded": false → the embedding provider is neither mock nor failing. On a fresh server # it is still UNPROVEN: checks.embeddings.unproven stays true (ok_count 0) until the first real # provider call succeeds. Step 3's write + recall is that proof; GET /v1/admin/ready?deep=1 makes # one real call without a write. ``` If `ready` reports `"degraded": true`, the embedding provider is failing (for example a dead key returning `401`) or you opted into mock embeddings: check the `embeddings` block for the provider's error text. A container with no embedding credential at all does not get this far: it exits at startup (see Prerequisites). > **Note: Readiness is outcome-based: gate deploys on it, not health** `/v1/admin/ready` reports what real provider calls actually did. Its `embeddings` check distinguishes **mock**, **failing** (a configured key returning `401` on every call), and healthy, so a dead key marks the server `degraded` and surfaces the provider's error text instead of silently returning empty recall. `health` only tells you the process is up; always gate container healthchecks and deploys on `ready`. ## 3. Store and recall your first memory No token is needed because the server was started with `CORTEX_INSECURE_NO_AUTH=1` (dev mode). Pick your surface: on a keyed server, add `-H "Authorization: Bearer $CORTEX_API_KEY"` (curl) or `bearer=…` (SDK): ### curl ```bash # Capture. ?wait=indexed returns once the event is searchable, so the recall below can't race the write. # Keep the "id" in the answer: it is the original event ID. curl -sfS -X POST "http://localhost:3141/v1/experience?wait=indexed" \ -H "X-Cortex-Actor: user:local" -H "Content-Type: application/json" \ -d '{ "scope": "org:demo/user:local", "modality": "conversation", "content": { "kind": "message", "role": "user", "text": "We migrated the payments service to CockroachDB. Timeline is Q2 2026." }, "context": { "observed_at": "2026-05-16T10:42:00Z" }, "idempotency_key": "decision-payments-001" }' # Recall curl -sfS -X POST http://localhost:3141/v1/recall \ -H "X-Cortex-Actor: user:local" -H "Content-Type: application/json" \ -d '{ "scope": "org:demo/user:local", "view": "holistic", "query": "What database are we using for payments?", "diagnostics": "none" }' ``` ### Python ```bash pip install cortexdbai ``` ```python from cortexdb.v1 import V1Client # Point at your self-hosted server. In local no-auth mode, no bearer token is needed. client = V1Client(api_url="http://localhost:3141", actor="user:local") scope = "org:demo/user:local" client.experience( scope=scope, text="We migrated the payments service to CockroachDB. Timeline is Q2 2026.", observed_at="2026-05-16T10:42:00Z", idempotency_key="decision-payments-001", wait="indexed", # block until it's searchable, for a clean first recall ) pack = client.recall(scope=scope, view="holistic", query="What database are we using for payments?", diagnostics="none") print(pack.get("context_block", "")) ``` ### TypeScript ```bash npm install cortexdbai ``` ```ts import { V1Client } from "cortexdbai/v1"; const client = new V1Client({ apiUrl: "http://localhost:3141", actor: "user:local" }); const scope = "org:demo/user:local"; await client.experience(scope, { text: "We migrated the payments service to CockroachDB. Timeline is Q2 2026.", role: "user", observedAt: "2026-05-16T10:42:00Z", idempotencyKey: "decision-payments-001", }, { wait: "indexed" }); const pack = await client.recall(scope, { view: "holistic", query: "What database are we using for payments?", diagnostics: "none" }); console.log(pack.context_block); ``` ## 4. Verify it, and where things live A quick "did it actually work?" checklist: 1. **Readiness, not liveness, and not proof by itself.** `curl http://localhost:3141/v1/admin/ready` → `"degraded": false` says the embedding provider is neither mocked nor failing; on a fresh server `checks.embeddings.unproven` is still `true` until a real provider call succeeds (the step-3 write + recall flips it, as does `GET /v1/admin/ready?deep=1`). If `degraded` is `true`, the provider is failing or mocked. Fix that before trusting recall. 2. **Read-your-writes.** The recall in step 3 should return your text in `context_block`. (It used `wait="indexed"`, so the event is searchable by the time the write returns.) 3. **Where your data lives.** Everything (WAL, RocksDB, indexes, blobs) is under `/data`, persisted to the `cortexdb-data` Docker volume. Back it up with a [verified cold backup](https://cortexdb.ai/docs/enterprise/backups-dr). 4. **Boot diagnostics / logs.** `docker logs cortexdb` shows the pinned embedding provider, the auth posture, and the `config_lint` dump (what actually loaded). Grep it when something's off: ```bash docker logs cortexdb 2>&1 | grep -iE "embedding|auth|answer|degraded" ``` 5. **The Admin Console.** Open **`http://localhost:3141/`** in a browser: CortexDB ships a built-in operator UI (Overview, Memories, Observability, Logs, Settings, …). See [Admin Console](https://cortexdb.ai/docs/operations/admin-console). > **Note: Common first-run issues** `degraded: true` → no real embedding provider (set a key or point at Ollama). `401 MISSING_TOKEN` on a write → the server isn't in no-auth mode; start it with `CORTEX_INSECURE_NO_AUTH=1` (dev) or send `Authorization: Bearer $CORTEX_API_KEY`. Empty `facts()` / no `/v1/answer` → expected on a content-only instance; enable enrichment / the answer lane ([defaults](https://cortexdb.ai/docs/self-hosting/defaults)). ## What you get by default Your instance runs in **content-only mode** out of the box: event capture, episodes, and BM25 + vector + RRF recall are on. Blob extraction (it needs content processors configured), the LLM-derived layers (Facts, Beliefs, Understanding), the knowledge graph, cross-encoder rerank, and `/v1/answer` are **opt-in**: see [Self-hosting defaults](https://cortexdb.ai/docs/self-hosting/defaults) for exactly what's on and how to enable the rest. ## Local embeddings, no provider keys To keep **embedding requests local**, point embeddings at a local [Ollama](https://cortexdb.ai/docs/integrations/ollama). Check every other enabled provider, storage backend and outbound connection separately before treating a deployment as fully local. This option suits a high-end machine (spare CPU and RAM, ideally a GPU); on a modest machine the OpenAI key above is the lighter option, and the two are otherwise equivalent. Start Ollama and pull the model before the first write, because the provider is pinned to the data directory on first boot: ```bash # On the host: ollama pull nomic-embed-text docker run -d --name cortexdb --restart unless-stopped --stop-timeout 120 \ --network host -e CORTEX_V1_API_ADDR=127.0.0.1:3141 -v cortexdb-data:/data \ -e CORTEX_LICENSE \ -e CORTEX_INSECURE_NO_AUTH=1 \ -e CORTEX_EMBEDDING_PROVIDER=ollama \ -e CORTEX_EMBEDDING_URL=http://127.0.0.1:11434 \ -e CORTEX_EMBEDDING_MODEL=nomic-embed-text \ -e CORTEX_EMBEDDING_DIMS=768 \ -e CORTEX_EMBEDDING_API_KEY=ollama \ "$CORTEXDB_IMAGE" ``` Ollama listens on `127.0.0.1` by default, which a container on Docker's own network can't reach, so the container shares the host's network (`--network host`, Linux) and `CORTEX_V1_API_ADDR` keeps CortexDB on this machine only. `CORTEX_INSECURE_NO_AUTH=1` is the same local-only choice as above: without it, or an API key, the first write is refused. The installer's "Local Ollama" option sets all of this and checks the model is pulled. To also get natural-language answers (`/v1/answer`) and the Facts/Beliefs layers locally, wire the answer lane and enrichment to Ollama too: see [LLM & Answer](https://cortexdb.ai/docs/operations/llm-answer) and [Self-hosting defaults](https://cortexdb.ai/docs/self-hosting/defaults). ## Upgrading An upgrade starts the new release on the **same data** with the old server's exact settings: stop the server with a 120-second grace, back it up with the release it runs, then start the new one. Don't re-run the installer for this; it only installs. [Upgrading](https://cortexdb.ai/docs/self-hosting/upgrading) has the steps for Docker and the binary (they carry your settings over), what each release changes, and how to roll back. ## Next steps - [Self-hosting defaults & prerequisites](https://cortexdb.ai/docs/self-hosting/defaults): default vs opt-in, per feature - [Configuration](https://cortexdb.ai/docs/operations/configuration): the file / env / CLI model - [Profiles & Presets](https://cortexdb.ai/docs/operations/profiles): copy-paste configs (incl. an Enterprise profile) - [Backups & Disaster Recovery](https://cortexdb.ai/docs/enterprise/backups-dr) · [Security & Compliance](https://cortexdb.ai/docs/operations/security-compliance) - [Python](https://cortexdb.ai/docs/sdks/python) · [TypeScript](https://cortexdb.ai/docs/sdks/typescript) · [CLI](https://cortexdb.ai/docs/sdks/cli) · [MCP server](https://cortexdb.ai/docs/sdks/mcp-server) ========================================================================================== # Your License _How a CortexDB server holds its license, renews it by itself, and what happens near the end of it. Usually there is nothing to do._ Source: https://cortexdb.ai/docs/self-hosting/license > **Note: Start on CortexDB Cloud** We recommend starting on [CortexDB Cloud](https://cortexdb.ai/docs/cloud): sign up on cortexdb.ai and you have an endpoint and a token in two minutes, with nothing to run. If you need CortexDB on-prem or on your own infrastructure, [talk to us](https://cortexdb.ai/contact) and we will provide a self-host license. Licensed releases then come from the [customer portal](https://customer.cortexdb.ai), and these pages cover running them. Every CortexDB release runs under your company's license. **Usually there is nothing to do after initial setup:** the install commands on [customer.cortexdb.ai](https://customer.cortexdb.ai/releases) already carry your company's license, so the installer and the manual steps pass it to the server for you. The server keeps it with its data and renews it when your CortexDB contact extends it. The token is also shown in the release page's License section, and agents read it from `GET /api/license` with their agent key. Because the commands carry the license, treat a downloaded `cortexdb-install.sh` like a secret: run it, then delete it, and keep it out of chats, tickets and logs. ## How it gets to your server The release page's commands set the license for you. Run by hand, the server takes it from `CORTEX_LICENSE`: ```bash export CORTEX_LICENSE='cdbl1.…' # your company's license, from the release page's License section docker run -d --name cortexdb … -e CORTEX_LICENSE … cortexdb/cortexdb:v0.16.1 ``` On its first start the server saves the license in its data directory (`license.json`), so later upgrades and restarts find it there even without `CORTEX_LICENSE`. One license covers every server your company runs. Agents can fetch it too: `GET https://customer.cortexdb.ai/api/license` with an agent key, or the MCP tool `get_license`. ## Renewals arrive by themselves The server asks `customer.cortexdb.ai` for the newest version of its license: every few hours, hourly in the last two weeks, and every 15 minutes once it has ended. When your license is extended or your plan changes, your servers pick that up without a restart or anything from you. A renewal request carries the license itself, a random id for the server and its version, and nothing else. ## A server that can't reach the portal Air-gapped servers, or ones behind a strict proxy, keep the license they have. Nothing breaks when the portal can't be reached. To renew such a server, copy the license from the portal (Releases → a release → **License**) and either: - paste it on the server's console, **License** page (takes effect at once), or - set `CORTEX_LICENSE` again and restart. `CORTEX_LICENSE_URL=off` stops the server from asking the portal at all. ## Near the end of a license | When | What happens | |---|---| | Two weeks before the last day | A notice in the console and the log. Everything works. | | After the last day | The **grace period** (7 days for pilots, 14 for customers): everything works, with notices. | | After the grace period | Reads and writes answer `402 LICENSE_EXPIRED`. **Your data is safe and unchanged.** | Dates are UTC calendar days, and both the last day and the last day of grace are included. A pilot whose last day is 12 November works with notices through 19 November and answers `402` from 20 November. The customer portal stays open to you through the same grace period. While a license has ended, health checks, the console, export (`POST /v1/export`) and adding a license keep working, so you can always take your data out. As soon as the license is renewed, the server serves again; nothing to restart. A server that has never had a license serves for 14 days (time to add one after an upgrade), then answers `402 LICENSE_REQUIRED` in the same way. ## Clusters Each data node of a [cluster](https://cortexdb.ai/docs/operations/storage-cluster) holds the license itself. Put it in the node config's `[engine]` table, like any engine setting (`CORTEX_LICENSE = "cdbl1.…"`, or `CORTEX_LICENSE_FILE` naming a file on the node). Each node keeps and renews it in its own data directory. ## Settings | Variable | What it does | |---|---| | `CORTEX_LICENSE` | The license. Needed once; the server keeps it. | | `CORTEX_LICENSE_FILE` | A file holding the license instead (a mounted secret). | | `CORTEX_LICENSE_URL` | Where renewals come from (default `https://customer.cortexdb.ai/api/license/refresh`); `off` stops them. | The console's **License** page, and `GET /internal/ui/license`, show the company, plan, last day, grace, how long the server serves, and when it last renewed. ========================================================================================== # Keys and Credentials _The five credentials a CortexDB pilot or customer handles, what each one is for, and where it comes from._ Source: https://cortexdb.ai/docs/self-hosting/credentials > **Note: Start on CortexDB Cloud** We recommend starting on [CortexDB Cloud](https://cortexdb.ai/docs/cloud): sign up on cortexdb.ai and you have an endpoint and a token in two minutes, with nothing to run. If you need CortexDB on-prem or on your own infrastructure, [talk to us](https://cortexdb.ai/contact) and we will provide a self-host license. Licensed releases then come from the [customer portal](https://customer.cortexdb.ai), and these pages cover running them. A self-hosted CortexDB involves five different credentials. They are not interchangeable: each one is refused where another is expected. | Credential | Usually in | Where it comes from | What it is for | |---|---|---|---| | **Agent key** | `CORTEXDB_KEY` | customer.cortexdb.ai, Agent keys (a signed-in person makes it; see [Agent keys](https://cortexdb.ai/docs/portal/agent-keys)) | Downloading releases and reading the docs, CortexHelper and MCP on the portal. Never sent to your CortexDB server: a server refuses it. | | **Company license** | `CORTEX_LICENSE` | The release page's commands, or `GET /api/license` with an agent key | Letting your server run. Needed once; the server keeps it and renews it ([Your license](https://cortexdb.ai/docs/self-hosting/license)). | | **Server API key** | `CORTEX_API_KEY` | You choose it (the installer makes one when you pick an API key) | The operator credential for a networked server: `Authorization: Bearer ` on every request. Not needed on a server that only listens on its own machine with `CORTEX_INSECURE_NO_AUTH=1`. | | **Application credentials** | Your application's config | Minted by your server, one per application or user | What your applications send instead of the server API key, narrowed to their scopes and capabilities ([Security & Compliance](https://cortexdb.ai/docs/operations/security-compliance)). | | **Provider key** | `OPENAI_API_KEY` or `CORTEX_EMBEDDING_API_KEY` | Your embedding provider | Embeddings only. It stays on your server. Not needed with local Ollama. | **Never share any of them** in a chat, a ticket, a screenshot or a log. When you send diagnostics to CortexDB, replace each value with ``; we never need one to help. ## Downloading with scripts and agents Any HTTP client works with the portal if it sends `Authorization: Bearer `: curl, wget, Python `requests`, Node `fetch`. The portal's own answers carry the header `X-CortexDB-Origin: portal`, and its errors are JSON with a `code` to branch on: | `code` | Meaning | |---|---| | `AUTH_REQUIRED` (401) | No key, or the key isn't valid or was revoked. | | `NO_ACCESS` (403) | The key is valid but the account's access has ended. | | `RETIRED` (410) | A release from before licenses; download a newer one. | | `NOT_FOUND` (404), `RATE_LIMITED` (429), `UNAVAILABLE` (503) | As named; `UNAVAILABLE` is worth retrying. | A refusal **without** `X-CortexDB-Origin` came from the network between you and the portal, not from your key. Python's `urllib` is the usual case: its default `User-Agent` is turned away. Set one that names your tool, and follow redirects (downloads answer `302` to a short-lived link): ```python import urllib.request req = urllib.request.Request( "https://customer.cortexdb.ai/d/latest/linux-amd64", headers={"Authorization": f"Bearer {key}", "User-Agent": "my-agent/1.0"}, ) ``` ========================================================================================== # Upgrading _Move a self-hosted server, its clients and its connectors to a newer release, what each upgrade does to existing data, and how to roll back._ Source: https://cortexdb.ai/docs/self-hosting/upgrading > **Note: Start on CortexDB Cloud** We recommend starting on [CortexDB Cloud](https://cortexdb.ai/docs/cloud): sign up on cortexdb.ai and you have an endpoint and a token in two minutes, with nothing to run. If you need CortexDB on-prem or on your own infrastructure, [talk to us](https://cortexdb.ai/contact) and we will provide a self-host license. Licensed releases then come from the [customer portal](https://customer.cortexdb.ai), and these pages cover running them. The rest of these docs describe the current release. This page is the one place that lists what changes when you move an existing deployment forward, and how to do it without losing settings or data. The steps below were run end to end on a licensed 0.14.2 server upgraded to 0.15.2, for both a Docker install and a Linux binary install. ## Before you start 1. **Find the version you run:** `curl -s http://127.0.0.1:3141/v1/admin/version` (use your port). 2. **Find how it was installed.** The portal installer makes either a Docker container (named `cortexdb` unless you set `CORTEXDB_NAME`) or a Linux binary under `~/cortexdb` (or `CORTEXDB_DIR`). 3. **Find your path** in the table below and read its section before you stop anything. | From | To | Kind of upgrade | Read | |---|---|---|---| | 0.15.x | 0.16.1 | Drop-in, not one way: a 0.15.x release still opens the directory, unless it was moved to the built-in embedding model | [From 0.15.x to 0.16.1](#from-015x-to-0161) | | 0.15.0 or 0.15.1 | 0.15.2 | Drop-in: an older 0.15 release still opens the directory | The steps below | | 0.14.x | 0.15.x | **One way** (data format 11): back up first | [From 0.14.x to 0.15.x](#from-014x-to-015x) | | 0.14.0 or 0.14.1 | 0.14.2 | Drop-in | The steps below | | 0.13.x | 0.14.x | **One way** (data format 10): back up first | [From 0.13.x to 0.14.0](#from-013x-to-0140) | | 0.12.x | 0.13.x | Drop-in; a single node can go back by changing the image again | The steps below | | 0.11.x | 0.12.x | Drop-in; from 0.12.1 the server needs your license | The license note below | | 0.10.x | 0.11.0 or later | **One way** (data migration) | [From 0.10.x to 0.11.0 or later](#from-010x-to-0110-or-later) | | 0.9.x | 0.10.x | Changes for existing deployments | [From v0.9.13 to v0.10.1](#from-v0913-to-v0101), [From v0.9.9 or earlier](#from-v099-or-earlier) | Each release's notes describe its one-way step from the release just before it. To cross more than one one-way release in a single upgrade (for example from 0.13.x straight to 0.15.2), check the path with your CortexDB contact first. > **Note: What not to do (people and agents alike)** - **Don't re-run the installer.** It installs; it never upgrades. On a machine that already has a `cortexdb` container or install folder it stops, by design. - **Don't `docker rm -f` the server, and don't `docker pull`.** There is no public image to pull: licensed images come from the portal as a file you `docker load`. - **Don't retype the `docker run` from memory or from an example.** Start the new release with the old one's exact settings (the steps below do this for you). A different embedding provider or model stops the server at start, and a missing `CORTEX_API_KEY` locks out every client. - **Don't delete a file or record that an error names** until you have read the release notes. Some records are meant to be there (see [From 0.14.x to 0.15.x](#from-014x-to-015x)). - **Don't upgrade from the console's Updates page.** Its update check doesn't see licensed releases, and its one-click updater cannot install them. New releases are on the portal's Releases page. - **An agent doing the upgrade stops and asks a person** before the first start of a one-way release, and shows that the backup verified. > **Note: Moving to 0.12.1 or later from an earlier release: add your license once** From 0.12.1 a server runs under your company's license. Add `-e CORTEX_LICENSE` to the new container after `export CORTEX_LICENSE=''` (copy it from the release page's License section), or paste the license on the console's License page afterwards. Without one the server keeps serving for 14 days. After that first time the server keeps the license itself. See [Your license](https://cortexdb.ai/docs/self-hosting/license). > **Note: Installer scripts contain your license** A `cortexdb-install.sh` downloaded from the portal carries your company license. Delete it from the folder you ran the installer in, along with any other saved copy, and check anything that logged it. Deleting a copy does not affect the license itself. If a copy leaked, ask your CortexDB contact about rotating it. ## Upgrade a Docker install **1. Load the new image.** On the new release's page on [customer.cortexdb.ai](https://customer.cortexdb.ai/releases), take the "Docker image, x86-64" file and its SHA-256 (or download it with your agent key), check it and load it. Run only these three steps: the release page's own `docker run` creates a new, empty server. ```bash export CORTEXDB_KEY='' # from the portal's Keys page curl -fL -H "Authorization: Bearer $CORTEXDB_KEY" -o cortexdb-0.16.1-image-linux-amd64.tar.gz \ https://customer.cortexdb.ai/d/0.16.1/image-linux-amd64 echo " cortexdb-0.16.1-image-linux-amd64.tar.gz" | sha256sum -c - docker load -i cortexdb-0.16.1-image-linux-amd64.tar.gz # prints: Loaded image: cortexdb/cortexdb:v0.16.1 ``` **2. Stop the server and back it up with the release it runs now.** The backup is your way back from a one-way upgrade, and it must be made with the old release. ```bash NAME=cortexdb # your container (CORTEXDB_NAME if you set one) OLD_IMAGE="$(docker inspect -f '{{.Config.Image}}' "$NAME")" VOLUME="$(docker inspect -f '{{range .Mounts}}{{if eq .Destination "/data"}}{{if .Name}}{{.Name}}{{else}}{{.Source}}{{end}}{{end}}{{end}}' "$NAME")" docker stop -t 120 "$NAME" # graceful stop: never docker rm -f a running server docker run --rm -v "$VOLUME":/data -v "$PWD":/backup --entrypoint cortexdb "$OLD_IMAGE" \ backup /data /backup/cortexdb-$(date +%F).tar.gz docker run --rm -v "$PWD":/backup --entrypoint cortexdb "$OLD_IMAGE" \ backup-verify /backup/cortexdb-$(date +%F).tar.gz # prints: archive verified: … ``` **3. Start the new release with the same settings,** in the same shell as step 2. This keeps the old container (renamed `cortexdb-previous`, stopped) and starts the new image with its network, ports, volumes and your own environment settings: license, API key, embedding provider, everything you passed with `-e`, but not the defaults the old image set itself. The settings are read through `<( … )`, so no file with your keys is written. Run it with `bash`. ```bash NEW=cortexdb/cortexdb:v0.16.1 # the tag docker load printed NET="$(docker inspect -f '{{.HostConfig.NetworkMode}}' "$NAME")" PORTS="$(docker inspect -f '{{range $p, $b := .HostConfig.PortBindings}}{{range $b}}-p {{if .HostIp}}{{.HostIp}}:{{end}}{{.HostPort}}:{{$p}} {{end}}{{end}}' "$NAME")" VOLUMES="$(docker inspect -f '{{range .Mounts}}-v {{if .Name}}{{.Name}}{{else}}{{.Source}}{{end}}:{{.Destination}} {{end}}' "$NAME")" docker rename "$NAME" "$NAME-previous" docker run -d --name "$NAME" --restart unless-stopped --stop-timeout 120 \ --network "$NET" $PORTS $VOLUMES \ --env-file <(docker inspect -f '{{range .Config.Env}}{{println .}}{{end}}' "$NAME-previous" \ | grep -vxF -f <(docker image inspect -f '{{range .Config.Env}}{{println .}}{{end}}' "$OLD_IMAGE")) \ "$NEW" ``` **4. Check it** ([Check the upgrade](#check-the-upgrade)). When you trust the new release, remove the old container with `docker rm "$NAME-previous"`; the volume stays. For a drop-in release you can go back until then: stop the new container, rename it aside, rename `cortexdb-previous` back and `docker start` it. With **Docker Compose**, load the image and take the backup as above, then change the image tag in the Compose file and run `docker compose up -d`: Compose keeps the file's settings. Set `stop_grace_period: 120s` on the service. ## Upgrade a Linux binary install The Linux binary needs glibc 2.39 or later (for example Ubuntu 24.04 or Debian 13); on an older host it stops at once with `` version `GLIBC_2.39' not found ``. Use the Docker image there. **1. Download and unpack the new release into its own folder**, next to the old one. Don't run the release page's binary commands: they start the new server straight away. ```bash DIR="${CORTEXDB_DIR:-$HOME/cortexdb}" export CORTEXDB_KEY='' curl -fL -H "Authorization: Bearer $CORTEXDB_KEY" -o cortexdb-0.16.1-linux-amd64.tar.gz \ https://customer.cortexdb.ai/d/0.16.1/linux-amd64 echo " cortexdb-0.16.1-linux-amd64.tar.gz" | sha256sum -c - NEW_DIR="$DIR/cortexdb-0.16.1-linux-amd64" mkdir "$NEW_DIR" && tar -xzf cortexdb-0.16.1-linux-amd64.tar.gz -C "$NEW_DIR" --strip-components=1 ``` **2. Read the running server's settings, stop it and back it up with the old binary.** Find the server by its process name: the `cortexdb.pid` file the installer writes names the shell that started it, not the server, so `kill $(cat cortexdb.pid)` does not stop CortexDB. ```bash PID="$(pgrep -u "$(id -u)" -x cortexdb)" # one server on this machine OLD_BIN="$(readlink -f /proc/$PID/exe)" PORT="$(tr '\0' '\n' < /proc/$PID/cmdline | sed -n 2p)" mapfile -t SETTINGS < <(tr '\0' '\n' < /proc/$PID/environ | grep '^CORTEX_') kill "$PID"; while kill -0 "$PID" 2>/dev/null; do sleep 1; done # waits for a graceful stop "$OLD_BIN" backup "$DIR/data" "$DIR/cortexdb-backup-$(date +%F).tar.gz" "$OLD_BIN" backup-verify "$DIR/cortexdb-backup-$(date +%F).tar.gz" ``` **3. Start the new binary with the same settings** (in the same shell, so it still has them): ```bash (cd "$NEW_DIR"; nohup env "${SETTINGS[@]}" "$NEW_DIR/cortexdb" "$PORT" "$DIR/data" \ >> "$DIR/cortexdb.log" 2>&1 & echo $! > "$DIR/cortexdb.pid") ``` This `cortexdb.pid` names the server itself. A server run by **systemd** upgrades by pointing `ExecStart` at the new folder's `cortexdb` (with `TimeoutStopSec=120`) and restarting the unit, after the same backup. ## Check the upgrade ```bash curl -s http://127.0.0.1:3141/v1/admin/version # the new version curl -s 'http://127.0.0.1:3141/v1/admin/ready?deep=1' # ready, with one real embedding call curl -s -H "Authorization: Bearer $CORTEX_API_KEY" http://127.0.0.1:3141/internal/ui/license # "state":"active" curl -s -H "Authorization: Bearer $CORTEX_API_KEY" \ "http://127.0.0.1:3141/v1/events/?scope=" # your memory, 200 ``` Leave out the `Authorization` header if the server runs with `CORTEX_INSECURE_NO_AUTH=1`. After a one-way release, the data directory records the format it was armed for: `docker exec cortexdb cat /data/format_armed.json` (or `cat ~/cortexdb/data/format_armed.json`) shows `{"format":11}` on 0.15.x. ## If something goes wrong | What you see | Why | What to do | |---|---|---| | `FATAL: embedding provider mismatch: data dir /data is pinned to '…' but the configured provider resolves to '…'` | The new server has different embedding settings from the old one | Start it with the old settings (step 3). Nothing was changed. To change provider on purpose, see [Embeddings](https://cortexdb.ai/docs/operations/embeddings#the-provider-pin) | | `FATAL: an explicit CORTEX_EMBEDDING_URL requires CORTEX_EMBEDDING_API_KEY, OPENAI_API_KEY, or LLM_API_KEY` | The embedding key was not passed | The same | | Every client gets `401 MISSING_TOKEN` | `CORTEX_API_KEY` was not passed, so the server made a key of its own | Start it with the old settings. The installer keeps the key in `~/.cortexdb/cortexdb.api-key` | | `Conflict. The container name "/cortexdb" is already in use` | Install commands were run instead of upgrade steps | Follow [Upgrade a Docker install](#upgrade-a-docker-install) | | The installer stops: `A container named cortexdb already exists` | The installer never upgrades | The same. Don't remove the container to make it run | | `FATAL [SHARD_FORMAT_UNSUPPORTED]: … armed for shard apply format 11 … this binary applies format 10 at most` (exit 78) | An older release was started on an upgraded directory | Run the new release, or go back from the backup ([Rolling back](#rolling-back)) | | `503 ACCESS_RESTORE_PENDING` on reads | The server runs on a restored backup and waits for an access acknowledgement | Before its first start, mark it with `restore-check --access-state unchanged` if access did not change ([Backups & DR](https://cortexdb.ai/docs/enterprise/backups-dr)) | | `503 FORMAT_UPGRADE_PENDING` on governed-memory routes | `CORTEX_FORMAT_CEILING=10` is set, or the server runs 0.15.0 on a directory holding unit companions | Remove the ceiling and restart; on 0.15.0, upgrade to 0.15.1 or later | | `402 LICENSE_REQUIRED` | No license yet (an upgrade from before 0.12.1) | Add your license (the note above) | | Binary: the new server cannot use its port, or the old one keeps running | `kill $(cat cortexdb.pid)` stopped the installer's shell, not the server | Stop it by name: `kill "$(pgrep -u "$(id -u)" -x cortexdb)"` | | Binary: `` version `GLIBC_2.39' not found `` | The host's C library is older than the binary needs | A newer host, or the Docker image | | The console's Updates page says there is nothing new | It doesn't see licensed releases | Releases are on the portal's Releases page | ## From 0.15.x to 0.16.1 0.16.1 adds [voice mode](https://cortexdb.ai/docs/features/voice-mode), a built-in embedding model that runs inside the server, voice call sessions and the [online re-embed](https://cortexdb.ai/docs/api-reference/admin#online-re-embed). A deployment that does not turn voice mode on serves as before, and recalls get faster for every deployment. (0.16.0 was not published; 0.16.1 is the release.) - **A drop-in upgrade, not one way.** 0.16.1 keeps data format 11, so a 0.15.x release still opens a directory 0.16.1 ran. Upgrade with the steps above; the backup is still worth taking. - **The exception: a directory moved to the built-in model** (`CORTEX_EMBEDDING_PROVIDER=local`, which voice mode sets). Only 0.16.1 and later know that provider, so an older release refuses the directory at its embedding check and changes nothing. To go back to 0.15.x, move it to an API provider with the online re-embed first, or restore the backup taken before the move. - **Voice mode on existing data.** A directory embedded through an API does not switch to voice mode by a setting: the start is refused with `VOICE_PROFILE_CONFIG`. Move it with the online re-embed first ([Moving an existing store to voice mode](https://cortexdb.ai/docs/features/voice-mode#moving-an-existing-store-to-voice-mode)). - **A graceful stop can take 0.15 to 0.2 s longer** than on 0.15.x; keep the 120 s stop timeout. - **Clients.** The voice calls, commands and tools come with the client releases made for 0.16.1 ([Clients](#clients)). ## From 0.14.x to 0.15.x 0.15.0 is the governed memory formation release, and its first start **upgrades the data directory one way**, for data format 11: it writes `format_armed.json` (`{"format":11}`) and logs `shard armed for apply format 11: this is one-way`. From then on a 0.14.x release refuses the directory (`SHARD_FORMAT_UNSUPPORTED`, exit 78), and the only way back is the backup taken before the upgrade. 1. **Back up with the 0.14.x release** and keep the archive with that image or binary (step 2 of [Docker](#upgrade-a-docker-install) or [binary](#upgrade-a-linux-binary-install)), and rehearse on a restored copy first if you can. 2. **Go straight to 0.15.1 or later, not 0.15.0.** On 0.15.0, a directory that holds unit companions (`/attrs:unit` records, which change sets write for org roots, application roots and teams) stays at format 10, and the governed-memory routes answer `503 FORMAT_UPGRADE_PENDING` with `details.reason: "reserved_path_in_use"`. **Do not delete those records**: they hold the unit's heads, grants and members. 0.15.1 and later arm over them. 3. **To upgrade now and arm later**, start 0.15.x with `CORTEX_FORMAT_CEILING=10` (`format_ceiling = 10` in every cluster member's `[engine]` table). It then serves what 0.14.2 served, `format_armed.json` stays `{"format":10}`, and the routes that need format 11 answer `503 FORMAT_UPGRADE_PENDING`. Remove the setting and restart to arm format 11. Holding at 10 is not a way back to 0.14.x: the backup is. 4. **Upgrade by hand**, with the steps above. The one-click updater cannot install 0.15.x. What 0.14.2 served that 0.15.x changes: - **`directives.extract` derives only the stages it names.** `["entities"]` no longer produces facts, `["facts"]` builds no belief unless the list also names `beliefs`, and `[]` derives nothing. An event with a list joins episodes only when it names `episodes`. An omitted list still derives everything. - **A write that names a directive nothing acts on** carries `directive_not_enforced:` in its acknowledgement's `warnings`. - **A change set's `attrs:unit` put that leaves `enrich` out keeps it**; send `"inherit"` to clear it. - **Entity-extraction calls are priced** on `CORTEX_LLM_MODEL`. If the price book does not know that model, declare its rate in `CORTEX_MODEL_PRICES`: until then the backfill that turning a scope's `enrich` on starts waits, and the cost estimates read unpriced. - **Imports are idempotent**: a row is keyed by its source id, and a row changed under the same id is refused alone. - **On a cluster**, data nodes no longer run the fact sweeper or the fact consolidator. - **The default answer model is `claude-opus-5-5`** (0.15.2) for a deployment that does not set `CORTEX_ANSWER_MODEL`. Its thinking counts against `CORTEX_ANSWER_MAX_TOKENS` (1,500): raise it if the server log shows the stop reason `max_tokens`. Without a derivation policy, subject settings or correction, 0.15.x serves the same recall packs, answers and default reads as 0.14.2, apart from the changes above. Upgrade the clients too ([Clients](#clients)); against a server before 0.15.0 their new calls answer `404`, so check the capability first. ## From 0.13.x to 0.14.0 0.14.0 is the shared-memory release, and **the one upgrade that cannot be undone in place**. Its first start arms the data directory for the new record formats, before it serves: it writes `format_armed.json` (`{"format": 10}`) and logs `SHARD_ARMED_ONE_WAY`. From then on a 0.13.x binary refuses the directory, and the only way back is the backup you took before. Nothing stored is lost by the upgrade, but several requests 0.13.x served are refused by default. Work through this list first. ### Before the first start 1. **Take a cold backup with the 0.13.x image, and keep it with that image.** Stop the server with its 120-second grace, then `cortexdb backup` and `cortexdb backup-verify` ([Backups & DR](https://cortexdb.ai/docs/enterprise/backups-dr)). 2. **Rehearse on a copy.** Restore the backup into a new, empty volume and start 0.14.0 on it with your real environment. Point a client of each kind at it and note what is refused. 3. **The operator key on `cloud_shared_saas`.** Its operator mode is now `deny` there: reads of stored memories, registrations and the other in-band actions need a break-glass header. If an application reads, writes or mints with the operator key, set `CORTEX_OPERATOR_DATA_READS=allow`, or `audit` to count what `deny` would refuse, until it uses per-person tokens ([Operator Modes](https://cortexdb.ai/docs/shared-memory/operator-modes)). The other presets keep `allow`. 4. **Tokens.** On 0.14.0 a token this server's minter signed lives at most 7 days for a person or an agent, 30 for a service, 24 hours with a chain claim; a longer one answers `401 INVALID_TOKEN_CLAIM` (`lifetime_over_ceiling`) from the first request, tokens minted before the upgrade included. 0.14.1 and later make these settings (`CORTEX_MINT_MAX_LIFETIME_*`) with 90 days for a person by default. A token that carries `scopes` holds only the families its entries name. Every mint names its tenant root (`scope`, `tenant` or `scopes`), and a minted token reaches no more than its minter ([Identity and Tokens](https://cortexdb.ai/docs/shared-memory/identity#minting-tokens)). 5. **A deployment that mints account tokens through its own service** (a website minter): list that principal in the issuers file's `deployment_minters`, and mint its own token again so that it holds `auth.mint` and every family the account tokens carry, each as `:*` in `scopes`, and names those capabilities in each account mint's `caps`. 6. **Callers.** These are now refused where 0.13.x served them: - forget and erasure selector fields a route does not apply (`422 INVALID_BODY`, `unknown_selector_field`), and a forget's misspelt `layers` (`unknown_layer`); - `tree.display_name` in a registry write (`422 INVALID_SCOPE_TREE`): names go to the [directory](https://cortexdb.ai/docs/shared-memory/identity#the-directory); - `/v1/understanding` and `/v1/concepts` without `understanding.read` in an explicit `caps` list; - a decimal offset as `GET /v1/events`'s `cursor` (it pages newest first with an opaque cursor now); - a few error codes changed status or `retriable` flag (a client that reads `retriable` needs no change). 7. **Clients.** Upgrade them with the server (below, [Clients](#clients)); the earlier releases predate shared memory. ### The switches Most checks that refuse what 0.13.x served have a switch, on by default. `off` serves what the check refuses and counts it in `GET /v1/admin/access/report?scope=` instead, so you can see when it is safe to turn it back on. Any other value refuses the start (exit 78). | Set | When | |---|---| | `CORTEX_OPERATOR_DATA_READS=allow` (or `audit`) | `cloud_shared_saas`, and an application uses the operator key for data | | `CORTEX_MINT_LIFETIME_ENFORCE=off` | Clients hold minted tokens past the lifetime ceilings | | `CORTEX_TOKEN_CONFINEMENT_ENFORCE=off` | Clients hold tokens whose `scopes` do not name every family they use | | `CORTEX_MINT_REACH_ENFORCE=off` | A minter's mints name no tenant root, or more than the minter holds | | `CORTEX_PERSON_DISPLAY_NAME_ENFORCE=off`, `CORTEX_DISPLAY_NAME_IN_RECORD_ENFORCE=off` | A client writes `tree.display_name` | | `CORTEX_AUDIT_RETENTION_ENFORCE=off`, or `CORTEX_AUDIT_RETENTION=off` | The deployment names its preset and must keep audit rows older than the preset's period: a daily sweep, five minutes after the first start, deletes them | | `CORTEX_DELIVERY_GATE_ENFORCE=off` | A reader reads rows (lifecycle frames, exports) at homes where it holds no Reader role | Leave `CORTEX_FORMAT_CEILING` unset. `7` keeps the directory unarmed, and the new features then answer `503 FORMAT_UPGRADE_PENDING`; it is not a way back either. ### After the first start - `GET /v1/admin/version` reports `0.14.0` and the new capabilities; `GET /v1/admin/metrics` `auth.enforce` shows each switch as you set it. - A memory you know is found by `GET /v1/events/{id}` and by `/v1/recall`, and each kind of client token answers `GET /v1/auth/whoami`; a `401 lifetime_over_ceiling` names a token to mint again. - Mint the long-lived tokens again, move display names to the directory, and remove each `off` once its count in the access report stays at zero. - A copy restored from a 0.14.0 backup waits for an acknowledgement before it serves ([Backups & DR](https://cortexdb.ai/docs/enterprise/backups-dr)). ## From 0.10.x to 0.11.0 or later 0.11.0's first start **migrates the data directory one way**: it keeps a copy of the event log as it was (`pre_stage2/` in the data directory), then moves the derived rows, idempotency records, vocabularies, temporal phrases and retention policies into the replicated log. Every later release does the same on a 0.10.x directory. - **Don't use a 0.10.x server's one-click updater for this upgrade.** It does not know the upgrade is one way. Upgrade by hand. - **Disk:** the first start takes longer on a large directory and needs up to two to three times the event log's size while `pre_stage2/` is kept. - **The legacy dual WAL is gone:** `CORTEX_UNIFIED_WAL=0`, or a directory that still holds `v1_wal/`, stops the server at start (exit 78, `LEGACY_WAL_RETIRED`). Run `cortexdb migrate-unified-wal --data-dir DIR --confirm` first. - **A storage or fsync error stops the process** (exit 74, `WAL_FATAL`): run the server under a supervisor that restarts it (Docker `--restart unless-stopped`, systemd `Restart=always`). - **Retired variables:** `CORTEX_BULK_DEFER_VECTORS` (ignored with a warning), `CORTEX_DRAIN_EMBED_CONCURRENCY` and `CORTEX_V1_MIRROR_MAX_IN_FLIGHT` (ignored). Any `CORTEX_CLUSTER_*` variable on a single server exits 78 (`CLUSTER_MODE_UNSUPPORTED`). - **After the upgrade**, `GET /v1/admin/metrics` reports `vectors.embed_inputs` 0 before any write: the upgrade re-embeds nothing. Once you trust the release, delete `pre_stage2/`: until then it holds the event log as it was, erased events included, and erasures report that copy as pending. ## From v0.9.13 to v0.10.1 v0.10.1 opens a v0.9.13 data directory with no migration step and does its one-time work in the background: - **Erasure index backfill.** The first start files every existing event into a new erasure index. Until `erasure_index.wal.ready` is `true` on `GET /v1/admin/metrics`, erasures still work but read the whole store. - **Belief rebuild** (only with incremental layers, `CORTEX_V1_LAYERS_INCREMENTAL`). Beliefs whose topic key changed are swept and rebuilt; they are missing until `GET /v1/admin/layers/stats` reports `belief_reconcile.done: true`. Without incremental layers, old beliefs stay until you run `POST /v1/beliefs/build` for each scope. Belief ids are now stable across rebuilds; earlier builds minted new ids on every build. - **Code plane** (only with `CORTEX_CODE_PLANE` on): every registered repository re-indexes once. Repository access is now checked against the repository's scope, not only the tenant: a repository bound under a scope no roster governs answers `404 REPO_NOT_FOUND` to per-actor tokens until you register that scope (`POST /v1/scopes`) and seat its members. After the upgrade: - **Capabilities.** `GET /v1/admin/version` lists ten `capabilities`. Gate the new request fields (`language`, `scripts`, `query_variants`, and the others) on that list: an older server refuses them with `422 INVALID_BODY`. - **Blob links for older events.** Events written before the upgrade carry no `source_blob_ids`, so erasing them does not delete their blobs. Run the backfill once: `POST /v1/admin/index-audit/source-blob-links` (dry run by default; see [Admin](https://cortexdb.ai/docs/api-reference/admin)). - **Derived data from enrichment-on stores.** Earlier builds could store facts with a lost negation, merge different people into one entity, and count opposite-polarity facts in beliefs. v0.10.1 stops new damage; `POST /v1/admin/derived/rederive` repairs what is stored, from the event log ([Admin](https://cortexdb.ai/docs/api-reference/admin)). Take a cold backup before an apply. - **Entity ids.** Names with non-ASCII characters now get hashed ids (`ent_jose-0f66606aa13f1258`). Ids stored earlier (such as `ent_Jos_`) still resolve on reads. - **Error codes.** A capture that waits on a running forget gets the retriable `409 DESTRUCTIVE_OPERATION_IN_PROGRESS` (was `403 POLICY_DENIED`). Forgetting an id stored in another scope answers `200` with zero counts (was `502 FORGET_BACKEND_FAILED`). A `?wait=indexed` capture that a concurrent forget blanked is no longer reported as `502 INDEXING_FAILED`. Cancelling a finished erasure answers `404 NOT_FOUND` (was `405`). - **Usage ledger.** Streamed answers now book their input tokens, so the recorded answer cost rises if your clients stream. ## From v0.9.9 or earlier Several v0.9.10 to v0.9.12 changes affect a deployment that was set up earlier. Check each before upgrading: - **The key is required on every preset.** A request with only `X-Cortex-Actor` and no bearer now gets `401` on every deployment preset, including the default `dev_local`. See [Authorization](https://cortexdb.ai/docs/concepts/authorization). - **Retention is enforced.** A sweeper erases events older than the deployment's `default_retention_ttl_secs` or a per-scope policy. Check both **before** upgrading, because expiry is irreversible. See [Retention & WAL](https://cortexdb.ai/docs/operations/retention-wal). - **Scope types are validated** when a scope is created (`422 UNREGISTERED_SCOPE_TYPE`), following `allowed_scope_types`. See [Scopes](https://cortexdb.ai/docs/concepts/scopes). - **No silent mock embeddings.** A configured embedding endpoint without a credential refuses to boot. Earlier images booted on mock embeddings and pinned the data directory to them; such a store needs a fresh volume or the offline rebuild in [Embeddings](https://cortexdb.ai/docs/operations/embeddings#changing-the-embedding-model-on-an-existing-store). - **Cluster flags are refused** at boot (exit 78, `CLUSTER_MODE_UNSUPPORTED`). Earlier images started independent single-node servers. Remove the flags. See [Storage & Cluster](https://cortexdb.ai/docs/operations/storage-cluster). - **The extraction cache is retired.** A boot measures the old `/extraction_cache` and deletes nothing; set `CORTEX_EXTRACTION_CACHE_PURGE=1` once to remove it. - **Usage figures.** The durable usage ledger uses one price book for every lane; re-check any cost figures taken from an older server. ## Rolling back **Within a drop-in upgrade** (0.15.0 to 0.15.2, 0.14.0 to 0.14.2 and the like), start the older release again on the same directory: for Docker, stop the new container, rename it aside, rename `cortexdb-previous` back and `docker start` it. **From 0.15.x to 0.14.x, only from the backup.** Stop 0.15.x and keep its directory aside. Restore the backup into a new, empty volume with the 0.14.x image's `cortexdb restore`, then, before its first start, run `cortexdb restore-check --data-dir /data --access-state unchanged` with the same image if access has not changed since the backup (otherwise reads answer `503 ACCESS_RESTORE_PENDING` until the access sources acknowledge it; see [Backups & DR](https://cortexdb.ai/docs/enterprise/backups-dr)). Start 0.14.x on that volume. Every write made after the upgrade is lost. Never start 0.14.x on the upgraded directory: it refuses it. **From 0.14.0, only from the backup.** Stop 0.14.0 and keep its directory aside. Restore the backup you took before the upgrade into a new, empty volume with the 0.13.x image's `cortexdb restore`, and start 0.13.x on that volume. Every write made after the upgrade is lost. Never start 0.13.x on the upgraded directory: it refuses it. The one-click updater treats 0.14.0 as a one-way upgrade (it asks for `accept_one_way` and the backup) and never rolls back onto an armed directory. **From v0.10.1 to v0.9.13.** A v0.9.13 image opens and serves a data directory v0.10.1 has used. Stop v0.10.1 with the 120-second grace, then start the older image on the same volume. During the rollback window v0.9.13 ignores the new event fields (`language`, `scripts`, `context.timezone`, `context.refers_to`, `source_blob_ids`), deletes no blobs on erasure, and builds beliefs without claim keys. **After a derived-data repair apply, roll back only by restoring the cold backup taken before it.** The v0.10.1 release notes have the full list and the steps for upgrading again. ## Clients Keep every client on its current release; the table in [Versioning and SDK compatibility](https://cortexdb.ai/docs/sdks/rest-api#versioning-and-sdk-compatibility) lists them. With 0.16.1 they are the Python SDK `cortexdbai` 0.15.0, the TypeScript SDK `cortexdbai` 0.13.0, `cortexdb-cli` 0.9.0, `cortexdb-mcp` 0.11.0 and `cortexdb-connectors` 0.3.0; they add the voice mode and online re-embed calls, commands and tools (`client.sessions`, `cortexdb session`, `cortexdb voice`, `cortexdb reembed`, the MCP `call_brief` tool). With 0.15.2 they were `cortexdbai` 0.14.0 (Python) and 0.12.0 (TypeScript), `cortexdb-cli` 0.8.0 and `cortexdb-mcp` 0.10.1. Coming from clients older than 0.14.0's, these are the breaking changes 0.14.0's client releases made; the earlier ones predate shared memory and reach none of its routes: | Package | With 0.14.0 | Breaking changes | |---|---|---| | `cortexdbai` (Python) | 0.13.0 | Every refusal raises the class of its error code; a token bearer with no `actor` sends the token's `sub` as `X-Cortex-Actor`; `recall`, `recall_stream`, `answer` and `compose` send `view` only when you pass it | | `cortexdbai` (TypeScript) | 0.11.0 | Error codes come back as their own classes; forget and erasure selectors are two types; no default view; TypeScript 5.0 or later | | `cortexdb-mcp` | 0.9.0 | A tool refuses an argument it does not take; the default profile no longer lists `publish` and `forget_by_key` (use `--tool-profile write`); the recall tools send `view` only when `CORTEXDB_VIEW` is set; `X-Cortex-Actor` comes from the token when `CORTEXDB_ACTOR` is unset | | `cortexdb-cli` | 0.7.0 | `/forget QUERY` and `cortexdb forget --query` resolve the query to event ids you confirm; `--cascade none` is gone; names go to the directory (`cortexdb directory put`) | | `cortexdb-connectors` | 0.3.0 | Nothing breaks without a container root: container mode is opt-in (`CORTEXDB_CONTAINER_ROOT`) | `cortexdb-cli` 0.6.0's interactive `/forget` is refused by 0.14.0's strict selectors; 0.7.0 fixes it. Points that matter when you upgrade from an older client: - **`cortexdb-mcp` 0.2.x** used retired endpoints (`/v1/remember`, `/v1/recall_memories`) and gets `404` on every call. Releases 0.7.3 and 0.7.4 have tool failures; use the current release. - **`cortexdbai` (Python)** 0.10.0 and earlier default to port `3142`; current releases default to `3141`. Pass the URL explicitly either way. - **`cortexdb-cli`**: `cortexdb auth tokens --scope` no longer confines a token (0.5.4 sent it as `scopes`). Use `--confine CAP:PREFIX`; see [CLI](https://cortexdb.ai/docs/sdks/cli). ## Connectors - **GitHub.** Connector releases before 0.2.22 stored most GitHub content empty (pull requests without a description, pushes without commits, comments cut at 200 characters, no inline review comments), and 0.2.22 re-keys GitHub records. Events written earlier stay as they were; re-sync to get the full text. See [GitHub](https://cortexdb.ai/docs/connectors/github). - **Wire keys.** From 0.2.21 the key sent to CortexDB is a derived `cxsrc:` value, so `GET /v1/experience/status?idempotency_key=` needs the `cxsrc:` value from the connector log. - **Freshdesk 0.2.19 or earlier** stopped ingesting tickets after 10 conversations. Backfill after upgrading; re-ingest is safe, unchanged records converge on the events already stored: ```bash cortexdb-sync status # note the current cursor first cortexdb-sync sync freshdesk --since 2020-01-01T00:00:00Z ``` - **Teams 0.2.20 or earlier** deduplicated an edited message against its first ingest instead of keeping it as a new version. Current releases keep edits. ========================================================================================== # Self-Hosting Defaults & Prerequisites _What a default self-hosted CortexDB instance does out of the box, and which features are opt-in: enrichment, cross-encoder rerank, and the knowledge graph._ Source: https://cortexdb.ai/docs/self-hosting/defaults The hosted platform ships with the LLM-derived layers, cross-encoder reranking, and the knowledge graph switched **on**. A **default self-hosted instance does not**: several capabilities the docs describe as part of CortexDB's *full* feature set are **opt-in** and stay off until you configure a provider. This page is the single reference for that gap. Many other pages link here. > **Note: Why the split exists** CortexDB self-hosts in **content-only mode** by default: it captures, embeds, and retrieves your content without calling any LLM lane. Embedding (for vector recall) is always on and needs a provider (OpenAI or a local Ollama, below). Blob extraction (Tika / vision / whisper) is **not** on by default: it needs its content processors configured. The *derived* layers (Facts, Beliefs, Understanding) and graph/rerank retrieval channels require you to wire up a model or an external service. This keeps a bare instance cheap and dependency-free; you turn on what you need. ## What runs by default On a fresh self-hosted `cortexdb/cortexdb` instance, with only an embedding provider configured: | Capability | Default | Notes | |---|---|---| | **Event capture (WAL)** | ✅ on | The append-only source of truth. Every `experience` lands here. | | **Episodes** | ✅ on | Consolidated from events; no LLM required. | | **Vector recall (HNSW)** | ✅ on | Needs an embedding provider (below). Quantization defaults to **`TQ2`**. | | **Keyword recall (BM25)** | ✅ on | Tantivy full-text index. | | **RRF fusion** | ✅ on | BM25 + vector results fused with Reciprocal Rank Fusion. | | **Blob extraction** | ⛔ opt-in | Configure `CORTEX_DOCUMENT_*` (Tika), `CORTEX_IMAGE_*` (vision), `CORTEX_AUDIO_*` (whisper). Until then blobs are stored but nothing is extracted; `/v1/admin/ready` reports `content_processors.configured: []`. Not gated on enrichment. | | **Facts layer** | ⛔ opt-in | Needs an entity LLM / enrichment. Empty otherwise. | | **Beliefs layer** | ⛔ opt-in | Synthesized from Facts. Empty otherwise. | | **Understanding layer** | ⛔ opt-in | Same enrichment prerequisite. | | **Knowledge-graph retrieval** | ⛔ opt-in | Needs `CORTEX_ENTITY_GRAPH=1` **and** enrichment. | | **Cross-encoder rerank** | ⛔ opt-in | Needs a reranker: a Cohere `rerank-v3.5` key or a local model (see [Recall Tuning](https://cortexdb.ai/docs/operations/recall-tuning)). | | **`/v1/answer` (LLM Q&A)** | ⛔ opt-in | Needs the **answer lane** configured (see below). | | **Shared-memory access checks** | ✅ on | Every read is checked against the reader at each memory's home, and the token rules (lifetimes, confinement) are enforced. See [Shared Memory](https://cortexdb.ai/docs/shared-memory). | | **Remote MCP (`/mcp`)** | ⛔ opt-in | `CORTEX_MCP=on` serves MCP over HTTP; see [Connecting AI Assistants](https://cortexdb.ai/docs/connect-assistants). | > **Note: '4-channel hybrid retrieval' is the full capability, not the default** The concepts pages describe **4-channel hybrid retrieval** (BM25 + HNSW vectors + graph traversal + cross-encoder reranking). On a default self-hosted instance, recall runs **BM25 + vector + RRF fusion only**: `diagnostics: "full"` shows `recall.bm25_search`, `recall.vector_search`, and `recall.fusion`, with **no graph or rerank channel**. Graph traversal and reranking are the two opt-in channels described below. ## Embedding (required for vector recall) Vector recall needs an embedding provider. Two setups are equally supported; they differ only in where the embedding model runs, and the choice is made **once, before the first write** (see the pin below). | | **OpenAI API** (`text-embedding-3-small`, 1536 dims) | **Local Ollama** (`nomic-embed-text`, 768 dims) | |---|---|---| | Runs | Nothing extra; the image's default endpoint | An Ollama daemon plus a ~275 MB model, on your hardware | | Cost / privacy | Fractions of a cent per 1k tokens; text to embed is sent to OpenAI | Free per call; text never leaves the box | | **Choose it when** | The machine is **modest** (a laptop, no GPU, limited RAM or disk), or you want the fewest moving parts | The machine is **high-end** (spare CPU/RAM, ideally a GPU) or the vectors must stay on-premises | **OpenAI API** (the image default, so only the key is needed): ```bash CORTEX_EMBEDDING_API_KEY=sk-... # text-embedding-3-small at 1536 dims is implied ``` **Local Ollama:** ```bash CORTEX_EMBEDDING_PROVIDER=ollama CORTEX_EMBEDDING_URL=http://ollama:11434 CORTEX_EMBEDDING_MODEL=nomic-embed-text CORTEX_EMBEDDING_DIMS=768 CORTEX_EMBEDDING_API_KEY=ollama # must be non-empty even for Ollama CORTEX_EMBEDDING_HTTP_TIMEOUT_SECS=30 ``` > **Note: The embedding provider is pinned to the data directory** On first boot CortexDB writes an `embedding_provider.pin` file (e.g. `ollama:nomic-embed-text:768` or `openai-http:text-embedding-3-small:1536`). Starting later with a different model or dimensions against the same data directory is refused at boot, so pick the provider before you ingest anything. Changing your mind later is supported as a deliberate offline rebuild (`CORTEX_EMBEDDING_ALLOW_REPIN=1` + `CORTEX_EMBEDDING_REBUILD_VECTORS=1`, then a per-scope vector refill); see [Changing the embedding model on an existing store](https://cortexdb.ai/docs/operations/embeddings#changing-the-embedding-model-on-an-existing-store). On earlier images the only path is a fresh volume. `CORTEX_EMBEDDING_API_KEY` must be **non-empty even for Ollama** (which ignores the value): an empty key fails the readiness check, and a configured endpoint with no credential refuses to boot rather than fall back to mock vectors. ## Enrichment (required for Facts / Beliefs / Understanding) The Facts, Beliefs, and Understanding layers are **LLM-derived**. Without an enrichment model configured, a self-hosted instance boots in content-only mode and those layers stay **empty**, boot logs a WARN like *"legacy fact pipeline not configured, facts+beliefs will stay empty."* > **Note: Triple captures write facts without enrichment** A `triple` capture writes its fact directly, with no LLM call, so it is on `GET /v1/facts` as soon as a `?wait=indexed` write returns, and `POST /v1/beliefs/build` can build beliefs from it. Facts extracted from free text, and the Graph Memory and Entity Extraction examples elsewhere in the docs, need enrichment and return empty on a content-only instance. To turn enrichment on, configure the enrichment router (it has its **own** key: it does not reuse the answer lane's): ```bash CORTEX_ENRICHMENT_DELAY_SECONDS=5 # enables the async enrichment scanner CORTEX_ENRICHMENT_MODEL=gpt-4o-mini # the LLM used for fact augmentation CORTEX_ENRICHMENT_URL=... # falls back to CORTEX_LLM_URL if unset CORTEX_ENRICHMENT_API_KEY=... # falls back to OPENAI_API_KEY / LLM_API_KEY ``` Boot confirms success with *"Enrichment LLM router enabled for fact augmentation."* Facts populate within ~5 to 30 s of a write; Beliefs and Understanding are synthesized asynchronously (minutes+). With `gpt-4o-mini`, enrichment costs about $0.40 per 1,000 events; see [Cost Planning](https://cortexdb.ai/docs/operations/cost-planning). ## The answer lane (`/v1/answer`) `/v1/answer` (natural-language Q&A with citations) routes through a **separate** LLM lane from entity extraction. Setting `CORTEX_LLM_*` alone is **not enough**: that configures the entity-extraction lane. Without `CORTEX_ANSWER_*` (or a bare `ANTHROPIC_API_KEY`, which enables the baked `claude-opus-5-5`), `/v1/answer` returns `503 ANSWER_UNAVAILABLE` ("no answer LLM is configured on this deployment"). Recommended hosted setup (about 2 to 4 cents per answer; `gpt-5.6-luna` for about a tenth of that, or `claude-opus-5-5` when accuracy matters more than cost; see [Choosing an answer model](https://cortexdb.ai/docs/operations/llm-answer#choosing-an-answer-model)): ```bash CORTEX_ANSWER_PROVIDER=openai CORTEX_ANSWER_URL=https://api.openai.com/v1 CORTEX_ANSWER_API_KEY=sk-... CORTEX_ANSWER_MODEL=gpt-5.6-terra ``` Fully local, on hardware that can run a capable model (see [Ollama](https://cortexdb.ai/docs/integrations/ollama)): ```bash CORTEX_ANSWER_PROVIDER=ollama CORTEX_ANSWER_URL=http://ollama:11434 CORTEX_ANSWER_API_KEY=ollama CORTEX_ANSWER_MODEL=llama3.1 ``` > **Note: Cloud-default model names are overridden self-hosted** The image bakes `CORTEX_ANSWER_PROVIDER=anthropic` and `CORTEX_ANSWER_MODEL=claude-opus-5-5` as the cloud defaults. Self-hosted, set the four `CORTEX_ANSWER_*` vars to your own provider: the baked-in model name does not apply. Content-only recall and capture work fine without the answer lane; only `/v1/answer` needs it. ## Cross-encoder rerank (Cohere) Cross-encoder reranking uses Cohere `rerank-v3.5` (an external service). It is off by default; supply a Cohere key via the reranker settings (`CORTEX_RERANKER_*`) to enable the rerank channel. Recall works without it: RRF fusion of BM25 + vector is the default ranking. ## Knowledge graph Graph-fused retrieval is gated behind `CORTEX_ENTITY_GRAPH=1` **and** enrichment (the graph is built from extracted entities/Facts). `config_lint` notes the cost: *"~3x write / ~4x recall cost."* > **Note: Graph traversal is not a recall request parameter** Graph traversal is an **internal fused channel**, not an API surface. There is no `graph` field in the `/v1/recall` body: sending one returns `422 "unknown field graph"` even with `CORTEX_ENTITY_GRAPH=1`. See [Knowledge Graph](https://cortexdb.ai/docs/concepts/knowledge-graph). ## Quick reference: default vs opt-in - **Always on (with embedding configured):** event capture, episodes, BM25 + vector + RRF recall. - **Needs content processors:** blob extraction (Tika / vision / whisper). - **Needs enrichment:** Facts, Beliefs, Understanding, and the knowledge graph (graph also needs `CORTEX_ENTITY_GRAPH=1`). - **Needs its own provider:** `/v1/answer` (answer lane), cross-encoder rerank (Cohere). ========================================================================================== # Customer Portal _What the customer portal at customer.cortexdb.ai is for, how you get access, and what each part of it does._ Source: https://cortexdb.ai/docs/portal The customer portal, [customer.cortexdb.ai](https://customer.cortexdb.ai), is where pilots and customers with a self-host license get CortexDB and help with it: releases and their install commands, agent keys, CortexHelper, Scope Studio, billing and support. It holds none of your memories: those stay on your own CortexDB server. > **Note: Not a customer yet?** We recommend starting on [CortexDB Cloud](https://cortexdb.ai/docs/cloud), which needs no portal and nothing to run. If you need CortexDB on-prem or on your own infrastructure, [talk to us](https://cortexdb.ai/contact) and we will provide a self-host license and portal access. ## Getting access 1. **You receive an invite link** from your CortexDB contact. It adds you to your company's license. 2. **Open it and sign in** with Google or with an email address and password. Sign in as the address the invite was sent to: an invite only applies to that address. 3. **You land on Overview**, which shows the newest release and a suggested next step. Everyone your company invites shares the company's license, releases and Scope Studio projects. When your pilot or subscription period is over, the portal says your access has ended: releases, docs and tools are no longer available, and agent keys are refused with `403 NO_ACCESS`. A license that has ended keeps the portal open through its grace period ([Your license](https://cortexdb.ai/docs/self-hosting/license)). Your servers keep your data either way. ## What each part does | Section | What it is for | |---|---| | **Overview** | The newest release, with a link to download it, and the next step for your account. | | **Releases** | Every release, newest first: Linux programs, Docker image files and a private registry. A release's page has its downloads with their SHA-256, the install command (see below), your company's license, the client package versions it was tested with, and its release notes. | | **Changelog** | Every release's notes in one feed. | | **Docs** | These docs, for the newest release. | | **CortexHelper** | Ask questions about installing, configuring and using CortexDB, or about memory for your product. See [CortexHelper](https://cortexdb.ai/docs/portal/cortexhelper). | | **Scope Studio** | Design the memory for a product or use case and get a handover pack your coding agent builds from. See [Scope Studio](https://cortexdb.ai/docs/portal/scope-studio). | | **Agent keys** | Keys that let your coding agents, scripts and pipelines use the portal: downloads, docs, CortexHelper, Scope Studio and the portal's MCP server. See [Agent keys](https://cortexdb.ai/docs/portal/agent-keys). | | **Billing** | Your plan, company and the date your access runs until. Customers are billed by invoice: for copies or plan changes, email your CortexDB contact or help@cortexdb.ai. | | **Support** | Report a problem and get the reply in the same place, with the whole history kept. | ## Installing from a release page A release's page builds the install command from four choices: | Choice | Options | |---|---| | **Machine** | x86-64 (most servers and PCs) or ARM64 (Graviton, Apple silicon VMs, Ampere) | | **Run it with** | Docker (recommended) or the plain binary (Linux with glibc 2.39 or later) | | **Embeddings** | An OpenAI-compatible key (`OPENAI_API_KEY`), or a local Ollama with `nomic-embed-text` | | **Who connects** | This machine only (no auth, for a first try), or other machines (the installer makes and keeps a server API key) | The command downloads the installer with your [agent key](https://cortexdb.ai/docs/portal/agent-keys) and runs it. The installer checks the machine, downloads and verifies the release, installs it, then writes one memory and recalls it. The page also has the same steps by hand. The [Self-Hosting Quickstart](https://cortexdb.ai/docs/self-hosting/quickstart) walks through both, and [Your license](https://cortexdb.ai/docs/self-hosting/license) covers how the license reaches the server. To move an existing server to a newer release, follow [Upgrading](https://cortexdb.ai/docs/self-hosting/upgrading) instead of running the installer again. ## Getting help - **CortexHelper** answers most questions straight away, from the docs and code of the newest release. - **Support** is for problems: paste the error as it is, the server version (`GET /v1/admin/version`) and what you tried. Leave out secrets: API keys, agent keys and your license never belong in a request, and we never need one to help. - **Billing questions** go to help@cortexdb.ai. ## See also - [Agent keys](https://cortexdb.ai/docs/portal/agent-keys) · [CortexHelper](https://cortexdb.ai/docs/portal/cortexhelper) · [Scope Studio](https://cortexdb.ai/docs/portal/scope-studio) - [Keys and Credentials](https://cortexdb.ai/docs/self-hosting/credentials): every credential a customer handles, and which is which. ========================================================================================== # Agent Keys _Keys that let your coding agents, scripts and pipelines use the customer portal: how to create and revoke them, what they reach, and the portal's MCP tools._ Source: https://cortexdb.ai/docs/portal/agent-keys An **agent key** lets a coding agent, a script or a pipeline do what you do in the portal without a browser: download releases, run the installer, read the docs, ask CortexHelper, use Scope Studio and connect to the portal's MCP server. It starts with `cdbk_` and is sent as `Authorization: Bearer `. An agent key is for the portal only. **Never send it to your CortexDB server**: a server refuses it. Your server uses its own credentials ([Keys and Credentials](https://cortexdb.ai/docs/self-hosting/credentials)). ## Create a key 1. In the portal, open **Agent keys**. 2. Give the key a name that says who or what uses it (up to 60 characters), for example "Priya's Claude Code" or "CI pipeline", and press **Create key**. 3. **Copy the key now.** It is shown once and the portal keeps only a hash of it, so it can't be shown again. The page also gives you the two commands below with the key filled in. Make one key for each person, agent or pipeline, so you can revoke one without affecting the others. An account can hold up to 20 keys at a time. The list shows each key's name, its first characters, when it was made and when it was last used. A key has exactly your account's access, checked on every request. It stops working when it is revoked or when your account's access ends. ## Use a key Keep the key in `CORTEXDB_KEY` and send it as a bearer token: ```bash export CORTEXDB_KEY='' curl -fsS -H "Authorization: Bearer $CORTEXDB_KEY" https://customer.cortexdb.ai/agent/SKILL.md ``` To connect Claude Code to the portal's MCP server: ```bash claude mcp add --transport http cortexdb https://customer.cortexdb.ai/mcp \ --header "Authorization: Bearer $CORTEXDB_KEY" ``` Other MCP clients (Cursor, Codex and others) take the same address, `https://customer.cortexdb.ai/mcp`, with the same header. ## What a key reaches | What | Address | For | |---|---|---| | MCP server | `https://customer.cortexdb.ai/mcp` | Connecting Claude Code, Cursor, Codex and other agents ([tools below](#the-portals-mcp-tools)) | | Agent instructions | `https://customer.cortexdb.ai/agent/SKILL.md` | How an agent installs and uses CortexDB | | Agent manifest | `https://customer.cortexdb.ai/agent/manifest.json` | The newest release, its files and SHA-256, install commands, credentials and client versions, as JSON | | Docs for agents | `https://customer.cortexdb.ai/llms.txt` | A short docs index; `/llms-full.txt` has the full text | | Downloads | `https://customer.cortexdb.ai/d//` | A release file; `` can be `latest`. Assets: `linux-amd64`, `linux-arm64`, `image-linux-amd64`, `image-linux-arm64` | | Installer | `https://customer.cortexdb.ai/install.sh?version=latest` | Checks the machine, installs and verifies a server ([Self-Hosting Quickstart](https://cortexdb.ai/docs/self-hosting/quickstart)) | | License | `https://customer.cortexdb.ai/api/license` | Your company's license ([Your license](https://cortexdb.ai/docs/self-hosting/license)) | Downloads answer `302` to a short-lived link, so follow redirects (`curl -L`). ## The portal's MCP tools | Tool | What it does | |---|---| | `latest_release` | The newest release: version, date, highlights, downloads with SHA-256, and Docker install steps. | | `list_releases` | Releases newest first, with version, date and title (`limit`). | | `get_release` | One release's full notes, downloads and install steps (`version`). | | `get_license` | Your company's license, with its plan and last day. | | `search_docs` | Search the docs for the newest release; returns page paths, titles and snippets (`query`, `limit`). | | `get_doc` | One docs page as text, by path, for example `self-hosting/quickstart` (`path`). | | `ask` | Ask [CortexHelper](https://cortexdb.ai/docs/portal/cortexhelper) a question (`question`). | | `studio_create_project` | Start a [Scope Studio](https://cortexdb.ai/docs/portal/scope-studio) project (`name`). | | `studio_add_input` | Add a description, document or file to a project: text in `text`, or a file in `base64` with its `filename` and `media_type`. | | `studio_run` | Start designing from the project's inputs (`project_id`, optional `comment`). A run takes a few minutes. | | `studio_get_design` | A project's latest run: its status and, when done, the design as JSON (`project_id`). Poll it after `studio_run`. | The portal's MCP server reads releases, docs and your Scope Studio projects. It holds none of your memories: to give an agent memory, connect it to your own CortexDB server ([MCP Server](https://cortexdb.ai/docs/sdks/mcp-server)). ## If a request is refused Every answer from the portal carries the header `X-CortexDB-Origin: portal` and, on an error, a JSON `code`: `AUTH_REQUIRED` (401) for a missing, wrong or revoked key, and `NO_ACCESS` (403) when your account's access has ended. A refusal **without** that header came from the network between you and the portal: set a `User-Agent` that names your tool and try again. The full list is in [Keys and Credentials](https://cortexdb.ai/docs/self-hosting/credentials#downloading-with-scripts-and-agents). ## Keep keys safe - Never paste a key into a chat, a ticket, a screenshot or a log, and keep it out of git. - If a key may have been seen by someone else, **revoke it** on the Agent keys page (Revoke, then confirm) and create a new one. Revoking one key leaves the others working. - When someone leaves or a pipeline is retired, revoke its key. ========================================================================================== # CortexHelper _The customer portal's assistant for installing, configuring and using CortexDB, and for designing memory for your product. What it answers from, its limits, and how to use it from an agent._ Source: https://cortexdb.ai/docs/portal/cortexhelper **CortexHelper** answers questions about installing, configuring and using CortexDB, and about how your product should use memory. Its answers come from the docs and the code of the newest release, and an answer that rests on a release says which one. Open it from the portal's sidebar (**CortexHelper**), or ask it from a coding agent through the portal's MCP server ([below](#from-a-coding-agent)). ## What to ask it Anything you would ask an engineer who knows CortexDB well, for example: - "How do I keep each customer's memory separate?" - "How do I upgrade my CortexDB server?" - "Which settings turn on cited answers, and what do they cost?" - "Why does my recall come back empty?" (paste the request and the response, without keys) - "How should my AI product use memory?" It explains in plain language unless you go technical, leads with the answer and gives commands you can paste. It names only what customers use: API routes and fields, `CORTEX_*` settings, CLI commands and SDK methods. It doesn't show CortexDB's source code. ## Commands in answers Commands in an answer are written from the docs for your release and checked before you see them, for example that a server start includes your license and that a recall asks only for access your credential has. **CortexHelper doesn't run them against your server**, and each answer with commands says so. Read a command before you run it, and try it on a test server first when it changes data. ## Conversations - Your conversations are kept under **Recent conversations**; **New conversation** starts a fresh one. - A question keeps running on the server if you reload or lose the connection, and the page picks up the answer when you come back. - **Talking about** sets what a conversation is about: CortexDB in general, or one of your [Scope Studio](https://cortexdb.ai/docs/portal/scope-studio) projects. What you discuss about a project is remembered on that project, and Scope Studio's Discovery and Design read it. - **Start a project** turns the conversation into a Scope Studio project, with the conversation carried along, when you are ready to design your memory. **Open project** goes to the one it is about. ## Limits - Up to **60 questions an hour** per account, from the portal and from agents together. Past that, it asks you to try again a little later. - A question can be up to 2,000 characters from an agent. - Never paste a key, a license or a token into a question. Replace each with ``; CortexHelper never needs one. ## From a coding agent With an [agent key](https://cortexdb.ai/docs/portal/agent-keys), connect your coding agent to `https://customer.cortexdb.ai/mcp` and use the `ask` tool with your `question`: ```bash claude mcp add --transport http cortexdb https://customer.cortexdb.ai/mcp \ --header "Authorization: Bearer $CORTEXDB_KEY" ``` The agent then gets the same answers you would in the portal, with the release they are based on. The same server's `search_docs` and `get_doc` tools read the docs themselves. ## When it can't help If an answer doesn't fix the problem, or something looks broken, open **Support** in the portal with the error as it is, your server version and what you tried ([Getting help](https://cortexdb.ai/docs/portal#getting-help)). ========================================================================================== # Scope Studio _Design the memory for your product in the customer portal, from a PRD, a repository, a website or a short brief, and get a handover pack your coding agent builds from._ Source: https://cortexdb.ai/docs/portal/scope-studio **Scope Studio** designs the memory for a product or use case: what your product remembers, for whom, how clients are kept apart, who reads what and how long it stays. You give it what you have; it gives you the design and a **handover pack** that your coding agent builds from. Nothing is deployed until you choose to build it. Open it from the portal's sidebar (**Scope Studio**). ## Projects Make one project for each product or use case. A project belongs to your company: everyone at your company can see it, add to it and run it. Start a project in any of these ways: - **Start from an example**: marketing analytics, a support copilot, a team brain, memory for coding agents or an AI tutor. Each fills in a description you can edit. - **PRD / files**: drop a PRD or other documents. - **GitHub**: paste a public repository (or a folder in one). Reading it can take a minute. - **Website**: paste your site's address. Discovery follows its links when it needs more. - **Describe**: say what you're building, typed or spoken: who uses it, what it should remember, what must stay private. Messy is fine. The project's name comes from what you give it. [CortexHelper](https://cortexdb.ai/docs/portal/cortexhelper) can also start a project from a conversation, with the conversation carried along. ## What you can give it | Input | Limits | |---|---| | Files | PDF, Word (`.docx`), Markdown, CSV, JSON, text or images (PNG, JPEG, GIF, WebP), up to 25 MB each | | A description | Up to 200,000 characters; upload anything longer as a file | | **Where it goes wrong** | A real moment where your AI forgot or mixed something up: what happened, and what should have happened. Up to 20,000 characters each. These make the design much better. | | A GitHub repository or a website | Read when you add it and kept as text | A project holds up to 20 inputs and 100 MB in all. One input is enough to start; more makes the design sharper. What you type is kept on your device until it is saved, so a dropped connection doesn't lose it. Leave out keys, passwords and personal data you don't need to share. ## The three stages ### 1. Discover Press **Understand**. Discovery reads everything you added, remembers it and writes up what it understood: the product, the problems memory has to solve and where memory would help. It takes about 2 minutes. Added something later? The write-up says the material changed; press **Update understanding** so the design sees it. ### 2. Design **Design my memory** first asks anything the write-up left open. Answer, and add any requirements of your own (for example "Keep each customer fully separate" or "Make deleting one person's data easy to prove"). The design then runs for 5 to 10 minutes; you can leave the page and come back. The design covers where memory lives (the scopes), what is written and by whom, who reads it, what is asked of it, how long it stays, and why. To change it, describe the change and run it again: every finished design is kept, so you can go back to an earlier one. ### 3. Handover When a design is ready, **Handover** gives you the pack and the prompt for your coding agent: 1. **Download the pack.** 2. **Unzip it at the root of your project**: your current repository, or a new folder if you are starting fresh. You get `AGENTS.md` and a `cortexdb/` folder next to your code. If the project already has an `AGENTS.md`, add the new lines to it. For Claude Code, add the line `@AGENTS.md` to your `CLAUDE.md`. 3. **Ask your agent to build it**: open the project in Claude Code, Cursor, Codex or similar and paste the prompt from the page (**Copy the prompt**). It has the agent work through the plan in order and show you where the memory fits in your codebase before it writes code. What's in the pack: | File | What it is | |---|---| | `AGENTS.md` | At the root: the CortexDB rules your coding agent loads every session | | `cortexdb/README.md` | Start here: what the pack is and how to hand it to your agent | | `cortexdb/BRIEF.md` | What you asked for: the product, the problem, what memory has to get right | | `cortexdb/DESIGN.md` | The design, and why | | `cortexdb/PLAN.md` | The build, task by task; each task says when it is done | | `cortexdb/CONVENTIONS.md` | The project's rules for every memory call | | `cortexdb/design.json` | The whole design, machine-readable; it wins if a file disagrees | | `cortexdb/docker-compose.yml`, `cortexdb/.env.example` | CortexDB on your own server | | `cortexdb/setup.sh` | Sets the design up on a new server: scopes, access and, where the design needs them, application tokens | Have these ready, because the agent will ask for them: - the CortexDB release and your company's license (portal, **Releases**); - an embedding provider key (an OpenAI-compatible API), or a local Ollama; - access to the data the product will remember, so the agent can build the pipeline and check the design on it. Keys go in `cortexdb/.env`, which the pack's `.gitignore` keeps out of git. ## From a coding agent With an [agent key](https://cortexdb.ai/docs/portal/agent-keys), an agent connected to `https://customer.cortexdb.ai/mcp` can run Scope Studio itself: 1. `studio_create_project` with a `name`. 2. `studio_add_input` for each input: text in `text`, or a file in `base64` with its `filename` and `media_type`. 3. `studio_run` to start designing (optionally with a `comment`). 4. `studio_get_design` every so often until the run is done; it then returns the design as JSON. Projects made this way appear in the portal like any other, so you can review the design and download the handover pack there. ========================================================================================== # CortexDB for AI Coding Agents _Make Claude Code, Codex, Grok, Hermes, OpenClaw and other AI coding assistants use CortexDB correctly: a drop-in rules file, the MCP server, and machine-readable docs._ Source: https://cortexdb.ai/docs/coding-agents If you build with an AI coding assistant (**Claude Code, OpenAI Codex, Grok, Hermes, OpenClaw**, Cursor, and the like) the fastest way to add CortexDB is to give the agent the right context so it generates correct code the first time. This page gives you three ways to do that, easiest first. > **Note: What agents get wrong without context** Left to guess, coding assistants reliably make the same handful of mistakes: they install the wrong package (`cortexdb` instead of **`cortexdbai`**), pass a `modality=` argument older SDKs don't take, and read `fact["fact_id"]` / `fact["subject"]["name"]` (the real fields are `fact["id"]` / `fact["subject"]["id"]`). The rules block below eliminates all of them. ## Option 1: The MCP server (Claude Code, Cursor, VS Code) The most seamless path: run the [CortexDB MCP server](https://cortexdb.ai/docs/sdks/mcp-server) and the agent gets memory tools (`memory_store`, `memory_search`, …) directly, with no code to write. ```bash # Claude Code, on CortexDB Cloud (the server's name comes first): claude mcp add cortexdb \ -e CORTEXDB_URL=https://api-v1.cortexdb.ai \ -e CORTEXDB_API_KEY= \ -e CORTEXDB_ACTOR=user:acct_ \ -e CORTEXDB_SCOPE=org:acct_/user:acct_ \ -- cortexdb-mcp ``` On a self-hosted server, set `CORTEXDB_URL=http://localhost:3141`, `CORTEXDB_ACTOR=user:local` and `CORTEXDB_SCOPE=org:demo/user:local`, plus `CORTEXDB_API_KEY=` on a keyed server. Cursor, Windsurf, and VS Code use the same binary via a JSON config: see the [MCP Server](https://cortexdb.ai/docs/sdks/mcp-server) page. A self-hosted server can also serve remote MCP itself (`/mcp`), which connector apps such as ChatGPT and Claude reach by URL: see [Connecting AI Assistants](https://cortexdb.ai/docs/connect-assistants). ## Option 2: A drop-in rules file (any agent) Coding agents read a conventions file from your repo: **Claude Code** reads `CLAUDE.md`, **Codex** and most others read `AGENTS.md`. Paste this block into that file (or your agent's system prompt) and it will use CortexDB correctly: ```markdown ## Using CortexDB (long-term memory for AI agents) - SDK install: `pip install cortexdbai` (Python) or `npm install cortexdbai` (TypeScript). Do NOT install `cortexdb`: that is an unrelated package. CLI: `pip install cortexdb-cli`. - Imports: Python `from cortexdb.v1 import V1Client`; TypeScript `import { V1Client } from "cortexdbai/v1"`. - Default to CortexDB Cloud: the person signs up on https://cortexdb.ai and creates an API token on the dashboard. Construct the client with it: client = V1Client(api_url="https://api-v1.cortexdb.ai", actor="user:acct_", bearer="") Keep every scope under org:acct_/. On the cloud, enrichment and /v1/answer are on. - Self-hosting needs a self-host license from CortexDB. Install with the customer portal's installer (`/install.sh`, it verifies a write and a recall), or by hand: load the image from customer.cortexdb.ai, then start a local dev server (no token needed) with the company license: docker run -d -p 127.0.0.1:3141:3141 -v cortexdb-data:/data -e CORTEX_LICENSE \ -e CORTEX_INSECURE_NO_AUTH=1 -e CORTEX_EMBEDDING_API_KEY=$OPENAI_API_KEY cortexdb/cortexdb:v0.16.1 client = V1Client(api_url="http://localhost:3141", actor="user:local") For a secured/shared server, drop CORTEX_INSECURE_NO_AUTH, set CORTEX_API_KEY=, and pass it as `bearer=` (`Authorization: Bearer `). A keyless, network-exposed server auto-generates a key and requires it. - scope is a hierarchical `type:name` path, e.g. "org:acme/user:alice". - Write memory: client.experience(scope=scope, text="...", role="user", observed_at="", idempotency_key="", wait="indexed") Don't pass `modality=` unless you need a non-default label: it defaults to `conversation`. The raw REST body DOES take `modality`. - Read memory: pack = client.recall(scope=scope, view="holistic", query="...", include=["events","facts","beliefs","episodes"], diagnostics="none") Use pack.get("context_block", ""). Views: raw | granular (alias local) | holistic | descend | lineage | structured. - Q&A with citations: client.answer(scope=scope, question="...", diagnostics="none") The field is `question`, not `query`. - Fact fields are: fact["id"], fact["subject"]["id"], fact["object"]["value"]; there is NO fact["fact_id"] and no fact["subject"]["name"]. Belief/episode/etc. ids are also keyed as "id". - On a default self-host (content-only) the Facts/Beliefs/Understanding layers are EMPTY and /v1/answer is disabled until enrichment / the answer lane (CORTEX_ANSWER_*) is configured. events + vector recall work. - Writes return `captured` (~10 ms, WAL append) BEFORE extraction; pass wait="indexed" for read-after-write. - Full docs: https://cortexdb.ai/docs · machine index: https://cortexdb.ai/llms.txt ``` > **Note: Plan limits on CortexDB Cloud** On the cloud every request counts against your [plan](https://cortexdb.ai/docs/cloud/plans): past a limit the server answers `402 PLAN_LIMIT_REACHED`, and `429 SUBTREE_RATE_LIMITED` means wait `Retry-After` seconds. The API token comes from your [dashboard](https://cortexdb.ai/dashboard). > **Note: Why this works** Every line above is a correction for a mistake real agents make, drawn from the same verification that produced these docs. Keeping it in `AGENTS.md` / `CLAUDE.md` means the agent re-reads it every session. ## Option 3: Point the agent at the docs The whole doc set is published in an LLM-friendly form: - **`https://cortexdb.ai/llms.txt`**: a curated index (titles + one-line descriptions + links) an agent can crawl to find the right page. - **`https://cortexdb.ai/llms-full.txt`**: every page concatenated into one file, for pasting the entire reference into a long-context model. Tell your agent: *"Use CortexDB. Read https://cortexdb.ai/llms.txt for the docs."* ### Task router `llms.txt` opens with a **by-task** block so an agent can resolve a task to the one page that answers it without reading the corpus. The same routes, for humans: | I want to… | Read this page | Why this one | |---|---|---| | Run a server on my machine | [Self-Hosting Quickstart](https://cortexdb.ai/docs/self-hosting/quickstart) | One `docker run`, first write and recall. The overview is orientation; [Defaults](https://cortexdb.ai/docs/self-hosting/defaults) is what is off by default. | | Store a memory | [POST /v1/experience](https://cortexdb.ai/docs/api-reference/experience) | Required fields, `?wait=` modes, idempotency, bulk. The [envelope concept](https://cortexdb.ai/docs/concepts/experience-envelope) explains the shape, not the request. | | Get context for a prompt | [POST /v1/recall](https://cortexdb.ai/docs/api-reference/recall) | Views, `include`, budgets, `context_block`. [Recall Tuning](https://cortexdb.ai/docs/operations/recall-tuning) is the env knobs. | | Ask a question, get a cited answer | [POST /v1/answer](https://cortexdb.ai/docs/api-reference/answer) | Self-hosted, the answer lane is opt-in: configure it per [LLM & Answer](https://cortexdb.ai/docs/operations/llm-answer) first. | | Delete one person's data (GDPR) | [Erasures](https://cortexdb.ai/docs/api-reference/erasures) | The selector-driven path that removes WAL rows (retention sweeps also remove them by age). [`/v1/forget`](https://cortexdb.ai/docs/api-reference/forget) is selective, not erasure. | | Remove something stored by mistake | [POST /v1/forget](https://cortexdb.ai/docs/api-reference/forget) | Preview, then execute with `from_preview_id`; audited. | | Understand request authentication | [Authorization](https://cortexdb.ai/docs/concepts/authorization) | `CORTEX_API_KEY` as bearer, `CORTEX_INSECURE_NO_AUTH=1` for loopback dev. Minting tokens is [Auth](https://cortexdb.ai/docs/api-reference/auth). | | Name scopes for a tenant or app | [Scopes](https://cortexdb.ai/docs/concepts/scopes) | `type:id` segments, allowed types. Registering them is [/v1/scopes](https://cortexdb.ai/docs/api-reference/scopes). | | Facts / Beliefs are empty | [Defaults & prerequisites](https://cortexdb.ai/docs/self-hosting/defaults) | Enrichment is opt-in on self-host. If it is on and layers lag, poll [Derivation status](https://cortexdb.ai/docs/api-reference/derivation-status). | | Change the embedding model | [Embeddings](https://cortexdb.ai/docs/operations/embeddings) | The pin, why a dimension change is refused, the offline `CORTEX_EMBEDDING_REBUILD_VECTORS` migration. | | Give Claude Code / Cursor memory | [MCP Server](https://cortexdb.ai/docs/sdks/mcp-server) | Install, per-client config, env vars, tool list. | | Connect ChatGPT, Claude or another connector app | [Connecting AI Assistants](https://cortexdb.ai/docs/connect-assistants) | Remote MCP on your server with OAuth. | | Share one memory across a team, with private spaces | [Shared Memory](https://cortexdb.ai/docs/shared-memory) | Org trees, change sets, per-person tokens, operator modes. | | Sync Slack, Jira, GitHub, Notion | [Connectors](https://cortexdb.ai/docs/connectors) | `cortexdb-sync`, `--scope-template`, credentials; then the per-source page. | | Expire old data / reclaim WAL space | [Retention & WAL](https://cortexdb.ai/docs/operations/retention-wal) | Per-scope rules, dry-run sweeps, compaction. | | Ingest PDFs, images, audio | [Media Ingestion](https://cortexdb.ai/docs/features/media-ingestion) | Upload a blob and reference it with its text (`content.transcript`). | | Index a code repository | [Code Plane](https://cortexdb.ai/docs/features/code-plane) | `CORTEX_CODE_PLANE=1`, mount the repo, `/v1/code/*`. | | Estimate cost / pick models | [Cost Planning](https://cortexdb.ai/docs/operations/cost-planning) | Recommended models, per-event and per-answer costs, monthly estimates. | | See what the LLM lanes actually cost | [Token & Cost Ledger](https://cortexdb.ai/docs/operations/usage-ledger) | `GET /v1/admin/usage`; set `CORTEX_MODEL_PRICES` for GPT-5.6 models. | | Isolate customers on one server | [Multi-Tenancy](https://cortexdb.ai/docs/enterprise/multi-tenancy) | Tenant = token audience, `cloud_shared_saas` preset. | | Back up or restore | [Backups & DR](https://cortexdb.ai/docs/enterprise/backups-dr) | Cold backup of the data directory. [Export](https://cortexdb.ai/docs/api-reference/export) is a per-scope JSONL dump, not a backup. | ## Per-agent notes | Agent | Recommended path | |---|---| | **Claude Code** | MCP server (`claude mcp add`, Option 1) **or** a `CLAUDE.md` rules block (Option 2). | | **OpenAI Codex** | `AGENTS.md` rules block (Option 2). | | **Grok** | Paste the rules block into context, or point it at `llms.txt` (Option 3). | | **Hermes** | Use the [Hermes integration](https://cortexdb.ai/docs/integrations/hermes) (`CortexDBMemoryProvider`) for runtime memory; the rules block helps the coding agent wire it. | | **OpenClaw** | Use the [OpenClaw recipe](https://cortexdb.ai/docs/integrations/openclaw) (SDK/REST); rules block for correct calls. | | **Cursor / Windsurf / VS Code** | MCP server (Option 1). | | **ChatGPT** | A connector app: it reaches a remote MCP server by URL with OAuth, not a local package. See [Connecting AI Assistants](https://cortexdb.ai/docs/connect-assistants). | ## A correct starting snippet If you'd rather hand the agent working code to adapt: ```python from cortexdb.v1 import V1Client client = V1Client( api_url="https://api-v1.cortexdb.ai", # self-hosted: "http://localhost:3141" actor="user:acct_42", # your actor, from the dashboard (self-hosted: "user:local") bearer="", # omit on a self-hosted dev server with CORTEX_INSECURE_NO_AUTH=1 ) scope = "org:acct_42/user:acct_42" client.experience( scope=scope, text="User prefers Python over JavaScript.", role="user", observed_at="2026-05-16T10:42:00Z", idempotency_key="pref-001", wait="indexed", ) pack = client.recall(scope=scope, view="holistic", query="What language does the user prefer?", diagnostics="none") print(pack.get("context_block", "")) ``` ## See also - [Self-Hosting Quickstart](https://cortexdb.ai/docs/self-hosting/quickstart) · [Python SDK](https://cortexdb.ai/docs/sdks/python) · [TypeScript SDK](https://cortexdb.ai/docs/sdks/typescript) - [MCP Server](https://cortexdb.ai/docs/sdks/mcp-server) · [Integrations](https://cortexdb.ai/docs/integrations) ========================================================================================== # Connecting AI Assistants _Give Claude, ChatGPT, Cursor and other AI assistants CortexDB memory, through the local MCP package or remote MCP served by your own server with OAuth sign-in._ Source: https://cortexdb.ai/docs/connect-assistants AI assistants reach CortexDB over the **Model Context Protocol** (MCP). There are two ways to connect one, depending on where the assistant runs and who signs in: | The assistant | Connect it with | Credential | |---|---|---| | A desktop or coding tool that starts local MCP servers: Claude Desktop, Claude Code, Cursor, Windsurf, VS Code | The local package, [`cortexdb-mcp`](https://cortexdb.ai/docs/sdks/mcp-server) | A token or key in its config | | Any MCP client that connects to a server over HTTP, including connector apps such as ChatGPT and Claude | [Remote MCP on your server](#remote-mcp-on-your-server): `/mcp`, served by CortexDB itself | Each person's own signed token, usually from your identity provider through OAuth | ## The local MCP package `cortexdb-mcp` (PyPI) is a small process the assistant starts on the same computer. It speaks MCP over stdio and calls your CortexDB server's REST API with the credential in its environment. It has the widest tool set: memory, access checks, conflicts, rollups, notices, the directory and the four code tools. It takes a person's or an agent's token as its credential, and its `--tool-profile` chooses `all` (the default), `read`, `write` (adds `publish` and `forget_by_key`) or `code`. Install and per-client setup: [MCP Server](https://cortexdb.ai/docs/sdks/mcp-server). Use it when the assistant runs on someone's computer and can start a command. A connector app that runs in a vendor's cloud, such as ChatGPT, cannot start a local process; it needs a remote server. ## Remote MCP on your server The CortexDB server can serve MCP itself at `/mcp`: streamable HTTP, stateless, one JSON-RPC message per `POST`, JSON answers. It is an **OAuth 2.1 resource server**: every call carries a principal's own signed token, and each tool call runs as the REST request that token would make, with the same checks. The operator key is not an MCP credential. It is off by default. ### Turn it on | Setting | Default | Set it to | |---|---|---| | `CORTEX_MCP` | off | `on` serves `/mcp` and its metadata | | `CORTEX_MCP_PROFILE` | `read` | `write` adds the `remember`, `forget` and `correct` tools | | `CORTEX_MCP_RESOURCE` | the request's origin + `/mcp` | The public URL clients use, such as `https://memory.acme.example/mcp`. Set it behind a proxy | | `CORTEX_MCP_SCOPES` | `org:{tenant}/{principal}/*` | The scopes the tools may act in, comma-separated; `{tenant}` and `{principal}` are filled from the caller's token. It only narrows: each scope's own access checks still decide | | `CORTEX_MCP_AUTHORIZATION_SERVERS` | every issuers-file `iss` that is an http(s) URL | The authorization servers the metadata names | | `CORTEX_MCP_ALLOWED_ORIGINS` | none | Browser origins admitted (requests with no `Origin`, as from server-side clients, are not checked) | A setting that does not parse refuses the start (exit 78, `MCP_CONFIG_INVALID`). Clients reach the server through HTTPS: put `/mcp` behind your reverse proxy and set `CORTEX_MCP_RESOURCE` to the URL they use. `GET /v1/admin/version` lists `mcp_http_v1` while the server serves `/mcp`. ### The tools | Tool | Profile | Runs | |---|---|---| | `recall` | read | `POST /v1/recall`: `query`, optional `since`/`until` or `when` (a phrase such as `last week`), `max_tokens`, `scope`, `session`, and `profile: "voice"` for a live voice turn | | `decision_history` | read | How a decision or belief changed: `about` (words in its claim) or `belief_id`, with `limit` and `scope` | | `explain` | read | `POST /v1/access/explain` for a `memory_id` (optional `role`, `scope`): why it can or cannot be read | | `memory_why` | read | Why CortexDB holds a memory and how it was made, for a `memory_id` such as a fact's id: its claim, whether it was learned or declared, and its sources | | `memory_about` | read | [`GET /v1/memory/about`](https://cortexdb.ai/docs/api-reference/memory-about): the current facts and beliefs about a scope's subject (by default the caller's own region), with the memories each rests on; `include_corrections`, `limit`, `cursor` | | `call_brief` | read | [`POST /v1/sessions`](https://cortexdb.ai/docs/api-reference/sessions): opens a live voice call and returns the caller's brief (`session`, optional `query`, `max_tokens`, `idle_timeout_s`, `scope`). A server not in [voice mode](https://cortexdb.ai/docs/features/voice-mode) answers `VOICE_SESSIONS_DISABLED`; voice recalls still work there without a session | | `remember` | write | `POST /v1/experience`: `text`, `scope` | | `forget` | write | `POST /v1/forget` by `memory_ids` (1 to 100), with `preview: true` for a dry run and `from_preview_id` to execute it; answers the receipt | | `correct` | write | [`POST /v1/corrections`](https://cortexdb.ai/docs/api-reference/corrections): reject, replace, pin or confirm a learned claim (`action`, `target`, `value`, `reason`) | A tool that names no `scope` uses the first allowlist entry; a scope outside the allowlist is refused inside the result (`isError: true`, `SCOPE_NOT_ALLOWLISTED`). Each tool carries MCP annotations (`readOnlyHint`, `destructiveHint`), so a client can ask before a destructive call. ### Try it On a server set up for tenant `acme` as in [Org Trees](https://cortexdb.ai/docs/shared-memory/org-trees#set-one-up), with Alice's region registered, and started with `CORTEX_MCP=on`, `CORTEX_MCP_PROFILE=write` and `CORTEX_MCP_RESOURCE=https://memory.acme.example/mcp`, mint a person's token (here with the server's own minter; in production your identity provider issues it): ```bash ALICE_TOKEN=$(curl -sS -X POST "$CORTEXDB_URL/v1/auth/tokens" \ -H "Authorization: Bearer $CORTEX_API_KEY" -H "Content-Type: application/json" \ -d '{"subject": "user:alice", "scope": "org:acme", "ttl_seconds": 3600}' | jq -r .token) ``` Initialize, list the tools, then call them: ```bash mcp() { curl -sS -X POST "$CORTEXDB_URL/mcp" \ -H "Authorization: Bearer $ALICE_TOKEN" -H "Content-Type: application/json" \ -H "Accept: application/json, text/event-stream" -d "$1"; } mcp '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"curl","version":"1.0"}}}' # {"id":1,"jsonrpc":"2.0","result":{"capabilities":{"tools":{"listChanged":false}},"instructions":"CortexDB long-term memory: …", # "protocolVersion":"2025-06-18","serverInfo":{"name":"cortexdb","version":"v0.16.1"}}} mcp '{"jsonrpc":"2.0","id":2,"method":"tools/list"}' # recall, decision_history, explain, memory_why, memory_about, call_brief, remember, forget, correct (the write profile) mcp '{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"remember","arguments":{"text":"We decided to move the payments service to Postgres 17 in Q1."}}}' # {"id":3,"jsonrpc":"2.0","result":{"content":[{"type":"text","text":"Remembered at org:acme/user:alice: evt_01a186b11cec73f09f0a03ca1b944dd0"}], # "isError":false,"structuredContent":{"event_id":"evt_01a186b11cec73f09f0a03ca1b944dd0","status":"captured",…},"cacheScope":"private"}} mcp '{"jsonrpc":"2.0","id":4,"method":"tools/call","params":{"name":"recall","arguments":{"query":"what did we decide about the payments database?"}}}' # {"id":4,"jsonrpc":"2.0","result":{"content":[{"type":"text","text":"[2026-10-29 08:05 UTC] We decided to move the payments service to Postgres 17 in Q1."}],"isError":false,…}} ``` The default allowlist, `org:{tenant}/{principal}/*`, is the caller's own region (`org:acme/user:alice` for Alice in tenant `acme`), so `remember` wrote there. A server-side client such as this one sends `notifications/initialized` after `initialize` (answered `202`); no session id is issued or needed. ### Sign-in with OAuth Without a token, `/mcp` answers `401` with a pointer to its protected-resource metadata (RFC 9728), which names the authorization servers a client signs the person in with: ```bash curl -sS -i -X POST "$CORTEXDB_URL/mcp" -H "Content-Type: application/json" -d '{"jsonrpc":"2.0","id":1,"method":"ping"}' # HTTP/1.1 401 Unauthorized # www-authenticate: Bearer resource_metadata="https://memory.acme.example/.well-known/oauth-protected-resource/mcp" curl -sS "$CORTEXDB_URL/.well-known/oauth-protected-resource/mcp" # {"authorization_servers":["https://login.acme.example"],"bearer_methods_supported":["header"], # "resource":"https://memory.acme.example/mcp","resource_name":"CortexDB"} ``` The authorization server is your identity provider, trusted through an [issuers-file entry](https://cortexdb.ai/docs/shared-memory/identity#external-issuers). For an access token that names the MCP resource as its audience, give the entry an alias from that audience to the tenant, and map people with `directory` mode so each token resolves to the person's principal: ```toml [[issuer]] id = "acme-idp" iss = "https://login.acme.example" format = "jwt" algorithms = ["RS256"] keys = ["keys/idp.pem"] # the provider's public key; or jwks_url = "" max_lifetime_s = 3600 [issuer.subject] mode = "directory" kinds = ["user"] [issuer.tenants] allowed = ["acme"] aliases = [{ aud = "https://memory.acme.example/mcp", tenant = "acme" }] ``` With that entry, an access token from `https://login.acme.example` whose `aud` is the MCP resource and whose subject is listed on Dana's directory entry calls `/mcp` as `user:dana` in tenant `acme`, and the default allowlist is `org:acme/user:dana/*`. A token with another audience is `401 WRONG_TENANT`; the `401` carries `error="invalid_token"` when a credential was presented. ### Connector apps: ChatGPT, Claude and others A connector app that runs in its vendor's cloud connects to a remote MCP server by URL and signs the person in with OAuth. What it needs from you: 1. `/mcp` reachable at a public HTTPS URL, with `CORTEX_MCP_RESOURCE` set to that URL; 2. an identity provider that signs the person in for that app and issues an access token CortexDB accepts (the issuers-file entry above, its alias naming the resource); 3. each person in the tenant's directory, with the sign-in account their tokens carry. ChatGPT's connectors and Claude's custom connectors use remote MCP over HTTPS with OAuth, the shape `/mcp` serves. CortexDB has not yet been run end to end with ChatGPT against `/mcp`, so treat a direct ChatGPT connection to your own server as untested. A browser-based MCP client is not supported yet (`/mcp` allows no MCP header in CORS). ### Limits - `/mcp` runs on a plain node: a cluster ingress answers `501 CLUSTER_ROUTE_UNSUPPORTED`, and a cluster data node refuses `CORTEX_MCP=on`. - It is stateless and answers JSON only: `GET` and `DELETE /mcp` answer `405`, and no event stream is opened. - Check a server before you point an app at it: it serves `/mcp` only while `GET /v1/admin/version` lists `mcp_http_v1`. CortexDB Cloud's API does not list it today; use the local package there. ## The customer portal's MCP server The [customer portal](https://cortexdb.ai/docs/portal) serves an MCP endpoint of its own, `https://customer.cortexdb.ai/mcp`, for your coding agents to read releases and docs, ask CortexHelper and run Scope Studio. It takes an agent key from the portal's Agent keys page (`Authorization: Bearer `); it holds none of your memories. Its tools are listed on [Agent keys](https://cortexdb.ai/docs/portal/agent-keys#the-portals-mcp-tools). ## See also - [MCP Server](https://cortexdb.ai/docs/sdks/mcp-server) · [CortexDB for AI Coding Agents](https://cortexdb.ai/docs/coding-agents) - [Identity and Tokens](https://cortexdb.ai/docs/shared-memory/identity) · [Shared Memory](https://cortexdb.ai/docs/shared-memory) ========================================================================================== # Core Concepts _The architecture behind CortexDB: five memory layers, event sourcing, bi-temporal time, scopes, and hybrid retrieval._ Source: https://cortexdb.ai/docs/concepts CortexDB is built on a small set of ideas that fit together. Read these in order for the full model, or jump to what you need. - **[The Five Memory Layers](https://cortexdb.ai/docs/concepts/layers)**: Events → Episodes → Facts → Beliefs → Understanding. Only Events are not derived. - **[Event Sourcing](https://cortexdb.ai/docs/concepts/event-sourcing)**: the immutable event log is the source of truth; every other store is a rebuildable cache. - **[Bi-temporal Model](https://cortexdb.ai/docs/concepts/bi-temporal)**: two time axes: when something was true, and when CortexDB learned it. - **[Scopes](https://cortexdb.ai/docs/concepts/scopes)**: the single hierarchical namespace primitive that carries ACLs, quotas, and audit. - **[The Experience Envelope](https://cortexdb.ai/docs/concepts/experience-envelope)**: one payload shape for every kind of ingest. - **[Lifecycle & Async Writes](https://cortexdb.ai/docs/concepts/lifecycle)**: the six atomic operations and the SSE stream; writes are async by default. - **[Authorization](https://cortexdb.ai/docs/concepts/authorization)**: PASETO tokens and the four-tier capability stack. - **[Knowledge Graph](https://cortexdb.ai/docs/concepts/knowledge-graph)**: an entity graph emergent from Facts and Beliefs (opt-in). - **[Hybrid Retrieval](https://cortexdb.ai/docs/concepts/hybrid-retrieval)**: BM25 + vectors + graph + rerank, fused with RRF. > **Note:** Running CortexDB yourself? Several capabilities (Facts/Beliefs extraction, graph traversal, cross-encoder rerank) are **opt-in** and off by default self-hosted. See [Self-hosting defaults](https://cortexdb.ai/docs/self-hosting/defaults). ========================================================================================== # The Five Memory Layers _How CortexDB models memory across Events, Episodes, Facts, Beliefs, and Understanding: and why single-layer systems fail._ Source: https://cortexdb.ai/docs/concepts/layers The five memory layers organize memory into strictly addressable tiers (**Events, Episodes, Facts, Beliefs, Understanding**) isolating raw observations from probabilistic derivations. CortexDB queries all five simultaneously during recall to return a unified **StratifiedPack**, over a lossless, event-sourced foundation. ## Why memory layers matter Memory systems typically rely on a single flat layer of LLM-rewritten summaries. Single-layer designs collapse raw observations ("the user clicked cancel") and probabilistic conclusions ("the user dislikes the UI") into the same vector space, which destroys confidence as a first-class metric. CortexDB preserves the "why" behind every piece of information by separating **lossless capture** (Events) from **structured assertions** (Facts), **probabilistic claims** (Beliefs), and **conceptual synthesis** (Understanding). Agents can traverse from a high-level belief down to the exact immutable events that generated it. ## The derivation graph CortexDB treats memory as a derivation graph starting from raw, immutable **Events**. Bounded spans of interaction group into **Episodes**. Extraction pipelines identify triple-shaped, bi-temporal **Facts**. Facts can conflict, so consolidation produces **Beliefs** (probabilistic claims that carry a `supports` chain back to the underlying evidence). **Understanding** synthesizes higher-level summaries, lagging real-time by minutes to hours. ## What each layer holds | Layer | Shape | Derived from | Confidence | Typical retrieval use | |---|---|---|---|---| | **Events** | Immutable append-only records (`id`, `content`, `scope`, `context.observed_at`, `context.recorded_at`) | Ingest (write path) | 1.0 (raw) | Verbatim quotes; audit trail; replay | | **Episodes** | Bounded sequences of related events (`id`, `events`, `summary`) | Events (async) | 1.0 (structural) | Session / conversation context | | **Facts** | Triple-shaped bi-temporal claims (`subject`, `predicate`, `object`, validity window) | Episodes + extraction (async) | 0.0 to 1.0 per extraction | Structured Q&A; timelines | | **Beliefs** | Probabilistic claims with a `supports` chain to Facts | Facts (async consolidation) | 0.0 to 1.0 per consolidation | "What do you currently think about X?" | | **Understanding** | Higher-order synthesized summaries, versioned | Facts + Beliefs (async, lagging) | implicit | Long-horizon overviews; briefings | **Only Events are not derived.** Every derived record carries a `supports` chain back through the layers to the immutable events that produced it: that chain is what makes evidence traceable and forgetting honest. > **Note: Derived layers require enrichment** Facts, Beliefs, and Understanding are produced by an LLM extraction/synthesis pipeline. On a **content-only self-hosted instance with no enrichment configured, these layers stay empty**: Events and vector search still work. See [Self-hosting defaults](https://cortexdb.ai/docs/self-hosting/defaults). ## What five layers enable - **Evidence traceability**: every Belief points to Facts, every Fact to Episodes and Events; agents can audit *why* they believe something by following the chain. - **Safe schema evolution**: CortexDB can rebuild Facts, Beliefs, and Understanding from raw Events if extraction models improve later. - **Deep temporal reasoning**: reconstruct historical state across deep history (see [Bi-temporal](https://cortexdb.ai/docs/concepts/bi-temporal)). ## Governing what the derived layers learn What enrichment learns into the derived layers is governed by data you control (see [Governed Memory](https://cortexdb.ai/docs/features/governed-memory)): - **A derivation policy** decides, per scope subtree, which events are read, which stages run (`facts`, `entities`, `beliefs`, `episodes`, `understanding`), which topics and sensitive values are never kept, and what waits for review. Every candidate is judged before it reaches a layer, and denied content is never stored. - **Every derived fact records how it was made**: the policy rule that admitted it, the policy's hash, the models and the prompt version (`include=derivation`). - **Corrections** reject, replace, pin or confirm a claim, and the layers built on it follow: a rejected claim's facts are deleted with the beliefs and concepts built from them, and nothing learns it again. - **Layers built across scopes** honour every input scope's restrictions, and never blend a sealed compartment with its siblings. Events stay outside all of this: a policy governs what is *learned* from an event, never the event itself. The event is still stored, indexed and searchable. ## Retrieval across layers Recall reads across the layers and fuses the results. The **full** retrieval architecture is hybrid, BM25 + HNSW vectors + graph traversal + cross-encoder reranking, but not every channel is on by default: > **Note: Default vs full capability** A **default self-hosted instance runs BM25 + vector + RRF fusion only** (visible with `diagnostics=full`). **Graph traversal** needs a knowledge graph (`CORTEX_ENTITY_GRAPH=1` + enrichment); **cross-encoder rerank** needs a reranker (a Cohere `rerank-v3.5` key or a local model; see Recall Tuning). On managed cloud the fuller stack is configured for you. See [Hybrid Retrieval](https://cortexdb.ai/docs/concepts/hybrid-retrieval) and [Self-hosting defaults](https://cortexdb.ai/docs/self-hosting/defaults). ## FAQ **What are the five memory layers?** Events (raw immutable observations), Episodes (bounded sequences), Facts (triple-shaped assertions), Beliefs (probabilistic claims), and Understanding (synthesized summaries). **How are Beliefs different from Facts?** Facts are triple-shaped bi-temporal assertions extracted from events. Beliefs consolidate correlated Facts and carry a `supports` chain to the underlying Facts. **Does the five-layer model slow down writes?** No: there is no LLM on the write path. A write appends an Event and returns immediately (`202`); Facts, Beliefs, and Understanding are derived asynchronously. **What is a StratifiedPack?** The unified output returned by recall: relevant context across all five layers merged into one structured response. See [`POST /v1/recall`](https://cortexdb.ai/docs/api-reference/recall). ## See also - [Event Sourcing](https://cortexdb.ai/docs/concepts/event-sourcing): why CortexDB stores raw events, not summaries. - [Bi-temporal Model](https://cortexdb.ai/docs/concepts/bi-temporal): validity windows and supersession. ========================================================================================== # Event Sourcing _Why CortexDB stores raw, immutable events as the source of truth instead of LLM-rewritten summaries._ Source: https://cortexdb.ai/docs/concepts/event-sourcing Event sourcing means storing every interaction as an **immutable, append-only event** (the raw message, the timestamp, the actor, the scope) and never overwriting or rewriting it on the write path. Summaries, embeddings, and knowledge graphs are **derived artifacts**: built asynchronously, replaceable, and never on the write path. ## Why it matters The common fix for lost context is to compress past conversations into LLM summaries. That's lossy: every rewrite drops information, and by the third conversation the agent recalls an interpretation of an interpretation. CortexDB keeps the **raw event as the source of truth**. If a better embedding model ships next year, CortexDB re-embeds from raw events: a summary-based system can't, because the original is gone. ## The log is the source of truth A write does exactly one durable thing: it appends an event to the **WAL** (`fsync`'d by default, so an acked event survives power loss; ~10 ms at the durable accept point with `?wait=captured`). Everything else (embedding, extraction, consolidation, synthesis) runs asynchronously off the log. Because the log is immutable, derived views are deterministic functions of `(events, derivation_version)`, which unlocks: - **Reproducibility**: same log + same extractor version → byte-identical derived state. - **Reversibility**: fix a bad consolidation by dropping the derived view and replaying; no data loss. - **Auditability**: every fact/belief/paragraph carries a `supports` chain back to raw events. - **Compliance**: GDPR erasure redacts or hard-deletes events, then re-derives downstream. See [Erasures](https://cortexdb.ai/docs/api-reference/erasures). A read never blocks on extraction: if the consolidator is behind, recall returns from the indices that are caught up. ## A write on the wire ```http POST /v1/experience Authorization: Bearer X-Cortex-Actor: user:alice Content-Type: application/json { "scope": "org:acme/dept:eng/user:alice", "modality": "conversation", "content": { "kind": "message", "role": "user", "text": "Priya from Acme wants to renew next quarter." }, "idempotency_key": "slack:C123:T456:1747293720" } ``` The server appends one event and returns **`202`** with `event_id`, `status`, `wal_offset`, and a **`lifecycle_stream`** URL you can subscribe to. (The `lifecycle_id` appears in the SSE event *data*, not in the write response.) The idempotency record survives restarts, so a retry after a crash replays the same `event_id` (`replayed_from_idempotency: true`). The original text is preserved verbatim, not summarized. ## What it enables - **Replay**: ship a better embedder/extractor and rebuild derived state from the log. - **Audit**: walk the `supports` chain to the immutable messages behind any claim. - **Honest forgetting**: [`/v1/erasures`](https://cortexdb.ai/docs/api-reference/erasures) deletes/redacts source events and re-derives downstream, so deleted content is provably absent from derived views (no residue in summaries). ## FAQ **Does event sourcing make writes slow?** No: a write appends to the WAL and returns an `fsync`'d ack in ~10 ms (`?wait=captured`), flat in payload size. Extraction/embedding/consolidation run asynchronously. **Can derived views be rebuilt from the log?** Yes: derived views are deterministic functions of the log + extractor version, so vectors, BM25 indices, facts, beliefs, and understanding can all be rebuilt by replay. **How does it relate to bi-temporal memory?** The log records *when CortexDB learned* a claim (recorded time); [bi-temporal facts](https://cortexdb.ai/docs/concepts/bi-temporal) additionally record *when it was true* (validity time). ## See also - [The Five Memory Layers](https://cortexdb.ai/docs/concepts/layers) · [Bi-temporal Model](https://cortexdb.ai/docs/concepts/bi-temporal) - [Lifecycle](https://cortexdb.ai/docs/concepts/lifecycle) · [Authorization](https://cortexdb.ai/docs/concepts/authorization) ========================================================================================== # Bi-temporal Model _How CortexDB tracks two independent time axes: when something was true in the world, and when the system learned it._ Source: https://cortexdb.ai/docs/concepts/bi-temporal CortexDB records **two** time axes on every derived record, so you can ask both "what was true on 2026-04-15?" and "what did we *know* on 2026-04-15?" - **Valid time**: `valid_from` / `valid_to`: when the fact was true in the world. - **Recorded time**: `recorded_from` / `recorded_to`: when CortexDB learned it. `null` on a `*_to` field means "open / still current." Events carry only `observed_at` and `recorded_at`; the four-field bi-temporal shape appears on derived layers (Facts, Beliefs, …). ## Querying a point in time Pass a `temporal` block to `/v1/recall`, `/v1/answer`, or the layer-read endpoints: ```json { "scope": "org:acme/dept:eng/user:alice", "query": "seat count", "temporal": { "as_of": "2026-04-15T00:00:00Z", "natural": "last 30 days", "reference_date": "2026-05-01T00:00:00Z" } } ``` `as_of` pins **both** axes at once (known by then, and true then). To pin one axis alone, use **`as_of_valid`** (records true at that instant) or **`as_of_recorded`** (records known at that instant); both are accepted (the meaning is from the pinned `temporal_block` schema). > **Note: valid_during / recorded_during are 2-element arrays** Range filters take a **two-element array `[start, end]`**, not an object. This is enforced: an object returns `422 INVALID_BODY: "invalid type: map, expected an array of length 2"`. ```json // correct "valid_during": ["2026-04-01T00:00:00Z", "2026-04-30T00:00:00Z"] // WRONG → 422 "valid_during": { "from": "2026-04-01", "to": "2026-04-30" } ``` Dates may be RFC-3339 datetimes or `YYYY-MM-DD` (end date inclusive). Applies to `recorded_during` too. > **Note: On recall, valid_during filters events by capture time** In a `/v1/recall` or `/v1/answer` `temporal` block, `valid_during` keeps the events whose `observed_at` falls in the window. It is not the facts' valid time. To favour memories by the dates they *talk about*, capture `context.refers_to` and recall with `temporal.refers_during`; see [Languages & Multilingual Memory](https://cortexdb.ai/docs/features/languages#time-phrases-and-time-zones). ## Supersession When a newer fact arrives for the same `(subject, predicate)`, the prior fact's `valid_to` (or `recorded_to`) closes rather than being overwritten: the full history is retained. Walk it with [`GET /v1/facts/timeline`](https://cortexdb.ai/docs/api-reference/facts). > **Note: Accepted temporal fields** `temporal.as_of`, `temporal.natural` and `temporal.reference_date` are all accepted, and range filters take the two-element array form shown above. ========================================================================================== # Scopes _Hierarchical scopes are CortexDB's single namespace primitive: precise memory partitions as delimited paths of type:id segments._ Source: https://cortexdb.ai/docs/concepts/scopes A **scope** is a `/`-delimited path of `type:id` segments (e.g. `org:acme/dept:eng/user:alice`). Scopes are CortexDB's single namespace primitive, replacing the separate "tenant", "namespace", and "workspace" concepts of older systems with one hierarchical model that carries ACLs, quotas, and audit uniformly. ## What scopes do - **Partition data.** All writes carry a scope; all reads address a scope. - **Form a hierarchy.** A read at `org:acme/dept:eng` with `view=descend` traverses into `org:acme/dept:eng/user:alice`; a read at `…/user:alice` with `view=holistic` walks up to ancestors. - **Carry policy.** A scope can declare retention, default view, members, and ACLs that compose with tenant and deployment policy. - **Auto-provision.** A write to a path that doesn't exist creates the scope (`auto_provisioned: true`). Explicit registration via [`POST /v1/scopes`](https://cortexdb.ai/docs/api-reference/scopes) sets members and policies. ## Scope path shape A scope is one or more `type:id` segments joined by `/`. Each segment must contain a `:`: a bare word is rejected (`422 INVALID_BODY`). Left-most is outermost. ``` org:acme/user:alice # personal scope under an org org:acme/dept:eng/team:platform # team scope org:acme/ws:q3-launch # workspace scope (cross-functional) agent:planner_v3 # an agent's own scope (no org tier) ``` > **Note: Scope types are validated on creation; depth and length are not** The first write into a **new** scope segment whose type is outside the deployment's `defaults.allowed_scope_types` is refused with **`422 UNREGISTERED_SCOPE_TYPE`** ("scope type banana is not in deployment defaults.allowed_scope_types"). Existing scopes are unaffected: the check runs only when a scope is created. Which types are allowed depends on the deployment preset (table below). If your self-hosted integration mints scopes of another type, add it to `allowed_scope_types` in the [deployment policy](https://cortexdb.ai/docs/api-reference/policy) first. A scope has at most **32 segments** and **4,096 characters** in all. Shorter is easier to read: about 8 segments of up to 64 characters each covers most designs. ## Allowed scope types | Deployment | Preset | Allowed scope types | |---|---|---| | **Hosted CortexDB cloud** | `cloud_shared_saas` | `org`, `dept`, `team`, `app`, `user`, `agent`, `service`, `ws`, `project`, `source`, `employee`, `chat`, `role`, `group`, `aud` (15) | | Self-hosted, one organization | `on_prem_enterprise` | the 15 above plus `global` and `system` (17) | | Dedicated single-tenant cloud | `cloud_private` | the 15 above plus `global` and `system` (17) | | Local development and evaluation (the default preset) | `dev_local` | the 17 above plus `debug` and `temp` (19) | | Self-hosted, many tenants | `cloud_shared_saas` | the same 15 as the hosted cloud | Every preset also allows the access-record types `container`, `set`, `hold`, `policy` and `attrs` (`GET /v1/policy/deployment` lists them). A `container` holds a source's memories ([Applications and Sources](https://cortexdb.ai/docs/shared-memory/applications-sources#sources-and-containers)); `set`, `hold`, `policy` and `attrs` hold none and are written only through [change sets](https://cortexdb.ai/docs/shared-memory/change-sets). See [Deployment Presets](https://cortexdb.ai/docs/enterprise/deployment-presets) for how to choose one (`CORTEX_DEPLOYMENT_PRESET`). - **`source`** is there because every connector writes into a `/source:` segment. On the hosted cloud a `source:` scope is created by the first write into it; registering one by hand with `POST /v1/scopes` is not allowed there (it needs `scope.create.custom`). - **`group`** and **`aud`** are the [org tree](https://cortexdb.ai/docs/shared-memory/org-trees) segments: a group across teams (`/group:`) and an audience compartment (`/team:/aud:pub`). - **`employee`**, **`chat`** and **`role`** hold an AI employee's memory, a person's conversations and a project role's memory (`/employee:`, `/user:

/chat:`, `/project:/role:`). - **`global`** (a cross-tenant pool) and **`system`** are not available on the hosted cloud. - A type outside the list, such as `channel:` or `repo:`, is refused on the first write into a new scope. Put the name under an allowed type instead: `org:acme/source:slack/project:general`. ## Recall views and traversal | View | Reads from | Traversal capability | |---|---|---| | `raw`, `granular` (alias `local`), `structured` | just the scope | none | | `holistic` | scope + ancestors | `scope.read.holistic` | | `descend` | scope + descendants | `scope.read.descend` | | `lineage` | supported (specialized) | none | - The default for **layer reads** (`facts()`, `beliefs()`, …) is `local` (no traversal). - The default for **`/v1/recall`** and **`/v1/answer`** is `holistic`. - On `/v1/recall`, `view: "local"` is accepted and normalizes to `granular`. - In an [org tree](https://cortexdb.ai/docs/shared-memory/org-trees), a shared scope (an org, a team, a group or a compartment) refuses the walking views (`422 VIEW_NOT_ALLOWED_AT_SCOPE`) and a read naming no view reads `granular` there; name the scopes to read with `extra_scopes` instead. No walk enters a private region it did not start in. ## What scopes enable - **Unified security**: the four-tier capability stack (Deployment → Tenant → Scope → Actor) enforces "outer deny is final": no descendant can override an ancestor's denial. See [Authorization](https://cortexdb.ai/docs/concepts/authorization). - **Dynamic context traversal**: a `holistic` recall pulls ancestor context without switching keys. - **Native multi-tenancy**: hierarchy and isolation are built into the database, not app middleware. ## FAQ **What is a scope?** A `type:id`-segment path that defines a partitioned memory boundary: the single namespace primitive, replacing tenant/workspace models. **How do scopes interact with the capability stack?** Scopes are the third tier (Deployment, Tenant, Scope, Actor); policy is evaluated hierarchically with "outer deny is final." **What is a holistic recall view?** It queries the current scope **and all ancestors** simultaneously, blending personal memory with organizational knowledge. **Can agents access memory outside their scope?** No: access is enforced at the storage level; agents cannot traverse hierarchy edges without explicit capabilities. ## See also - [Authorization](https://cortexdb.ai/docs/concepts/authorization): the four-tier capability stack. - [Lifecycle](https://cortexdb.ai/docs/concepts/lifecycle): how writes flow through scopes asynchronously. ========================================================================================== # The Experience Envelope _The single structured payload for everything CortexDB ingests: messages, observations, tool results, documents, and triples._ Source: https://cortexdb.ai/docs/concepts/experience-envelope The **Experience Envelope** is one structured shape used to ingest all forms of agent experience (messages, observations, tool results, documents, and raw triples) into lossless event-sourced memory. One shape covers every data type, so ingestion isn't fragmented across formats. CortexDB separates the payload into functional slots: **identity** (who), **content** (the data), **context** (temporal/spatial grounding), and operational **directives** (how to process it). ## Minimal envelope ```json { "scope": "org:acme/dept:eng/user:alice", "modality": "conversation", "content": { "kind": "message", "role": "user", "text": "Just got off a call with Priya at Acme." } } ``` > **Note: Required fields** Only **`scope`, `modality`, and `content`** are required. `context` (and `context.observed_at`) and `idempotency_key` are **optional**: a write without them returns `202`. (Older docs marked `observed_at` and `idempotency_key` as required; they are not.) ## Identity slots Up to three identities; each defaults to the previous for the common "narrating yourself" case. | Slot | Default | Capability needed when set explicitly | |---|---|---| | Caller | Implicit (from token) | always | | Observed actor | = caller | `scope.write.on_behalf_of` when ≠ caller | | Subject | = observed_actor | `scope.write.about_other` when ≠ observed_actor | This supports bots writing **on behalf of** a user (`observed_actor`) and writing memories **about** other entities (`subject`). ## Content kinds `content` is a discriminated union: pick the shape that matches your data: | Kind | Shape | Use for | |---|---|---| | `message` | `{ role, text, media[] }` | Conversational turns | | `text` | `{ text }` | Free-form text observations | | `json` | `{ data }` | Structured tool outputs, sensor readings | | `blob_ref` | `{ blob_id }` | Reference an already-uploaded blob | | `triple` | `{ triple: { subject, predicate, object } }` | Direct fact insertion (`object` needs `type`+`datatype`+`value`) | The **`role` enum is enforced**: `user`, `assistant`, `tool`, `system` (anything else → `422`). ## Modalities | Modality | Typical use | |---|---| | `conversation` | Chat turns, meeting transcripts | | `document` | Documents and long text | | `tool_result` | Structured tool output | | `observation` | Sensor readings, generic observations | | `feedback` | Ratings, corrections, thumbs up/down | | `imported` | Records written by `/v1/import/*` | The value is an **open-set label**: it is stored verbatim and echoed by reads, and values outside the list above are accepted too (`banana` writes `202` and reads back unchanged). Modality does **not** gate extraction: with enrichment configured, every event is enriched the same way, `feedback` and other values included. Extraction into Facts/Beliefs requires enrichment to be configured at all: see [Self-hosting defaults](https://cortexdb.ai/docs/self-hosting/defaults). > **Note: Per-event opt-out: directives.extract: []** To skip enrichment for one event, send `directives: { "extract": [] }` on `POST /v1/experience` or on a `POST /v1/experience/bulk` item: both honor it, and the event stays searchable. ## Context ```json { "observed_at": "2026-05-15T10:42:00Z", "source_recorded_at": "2026-05-15T10:41:58Z", "location": { "city": "Bangalore" }, "preceded_by": ["evt_01HX..."], "intent": "deal_status_update", "labels": ["acme", "renewal"] } ``` All context fields are optional. `preceded_by` chains experiences by **CortexDB event id** (`evt_…`) so the episode builder recognizes a sequence. > **Note: Keep labels within these limits** Keep each memory's `labels` within these limits: at most 4,096 labels per memory, each at most 262,144 UTF-8 bytes, none empty or only whitespace, and no ASCII control character other than tab, line feed and carriage return. The server checks them when the operator sets `CORTEX_LABEL_LIMITS=on`, and they are planned to become the default; while they are checked, a write that breaks one is refused with `422` (`LABELS_TOO_MANY`, `LABEL_TOO_LONG`, `LABEL_EMPTY`, `LABEL_INVALID_CHARACTER`). Check that your integrations send no empty labels. ## Language, script and time zone Three optional hints, each gated on a capability in `GET /v1/admin/version` → `capabilities[]` (a server that doesn't list it refuses the field with `422 INVALID_BODY`): | Field | Where | Example | Capability | |---|---|---|---| | `language` | top level | `"hi-Latn"` (BCP-47) | `capture_language_v1` | | `scripts` | top level | `["Deva"]` (ISO 15924, at most 8) | `capture_language_v1` | | `context.timezone` | `context` | `"Asia/Kolkata"` (exact IANA name) | `capture_language_v1` | | `context.refers_to` | `context` | `[{ "from": "2026-09-26", "precision": "day" }]` | `refers_to_v1` | Without hints the server still tags non-English text by detection (`und-Deva`, `hi-Latn`); English stores no tag. None of these is part of the write identity. The full rules are on [Languages & Multilingual Memory](https://cortexdb.ai/docs/features/languages). ## Source descriptor `source` is an optional, provenance-bound description of the **authoritative source** this envelope represents and the exact fragments of it: which document, which page or turn, and a strong digest of the bytes. It is stored verbatim on the event and returned by `GET /v1/events` and recall (the key is absent on events written without one), so a citation can point past the event to the original artifact. The descriptor is optional. ```json { "source": { "schema_version": 2, "source_id": "doc:policies/refunds.md", "modality": "text", "content_kind": "markdown", "language": "en", "source_fingerprint": "sha256:b493bf8a…", "fragments": [ { "fragment_id": "f1", "locator": { "kind": "document", "page": 1, "section_path": ["Refunds"] }, "content_fingerprint": "sha256:b493bf8a…" } ] } } ``` - Required: `schema_version` (always `2`), `source_id`, `modality`, `content_kind`, `source_fingerprint`, `fragments` (1 to 1024). `language` is optional. - Fingerprints are algorithm-qualified digests of exact bytes: `sha256:` or `blake3:` plus 64 hex chars. - Each fragment needs `fragment_id`, `content_fingerprint` and a `locator` whose `kind` is one of `conversation` (`session_id`, `turn_index`, optional `speaker`, `message_id`), `document` (`page`, `section_path`, `block_index`), `json` (`pointer`), `table` (`table`, `sheet`, `row`, `column`, `field`), `code` (`file`, optional `symbol`, `lines`), `log`, `media` (`page`, `frame_index`, `time_range`, `region`, `track`) or `generic` (`path`, `ordinal`). An unknown locator field or a malformed fingerprint is `422 INVALID_BODY` with the offending `field_path`. - `source.modality` must equal the envelope `modality`; a mismatch is `422 INVALID_ENVELOPE` (`source modality "image" does not match envelope modality "text"`). CortexDB does not fetch the source. It does check one thing: a fragment's `content_fingerprint` must be the digest of the envelope's own text bytes, or the write is `422 INVALID_ENVELOPE` (`source fragment "f1" fingerprint does not match envelope text bytes`). `source_fingerprint`, the digest of the whole source, is not checked. Otherwise the descriptor is a claim you make about where the content came from, kept immutable alongside the event. ## Idempotency `idempotency_key` (≤ 64 chars) is **optional but recommended** for safe retries. Same key + same body → no-op; same key + **different** body → **`409 IDEMPOTENCY_CONFLICT`**. Use a deterministic key per source-system message (e.g. `slack:C123:T456:1747293720`). Idempotency records persist across restarts, so a retry after a crash replays the same `event_id` (`replayed_from_idempotency: true`) rather than duplicating. Keys are **per scope**: the same key in two different scopes creates two events. They expire after ~24 h. ## Operational directives ```json { "directives": { "extract": ["facts", "beliefs"], "consolidate_into": "org:acme/dept:eng", "confidence_floor": 0.7, "ttl_for_belief_layer": "P30D", "embed": "eager" } } ``` | Field | Notes | |---|---| | `extract` | A **list**: a subset of `facts, entities, beliefs, episodes, understanding`. Omitted or `null` runs every stage; `[]` opts the event out of enrichment, on single and bulk writes since server 0.10.3 (see [Modalities](#modalities)). It is not an on/off flag: `"extract": false` or `"none"` → `422 INVALID_BODY` | | `consolidate_into` | Merge derived layers into a different scope (requires `scope.write` on both) | | `confidence_floor` | Drop derived records below this confidence | | `ttl_for_belief_layer` | ISO-8601 duration, stored with the event; derived records don't expire from it (use [retention](https://cortexdb.ai/docs/operations/retention-wal) for expiry) | | `embed` | `eager` / `lazy` / `none` | ## FAQ **Does the envelope block the write path?** No: it returns `202` after the capture phase; extraction and consolidation run asynchronously. **Can it handle tool outputs?** Yes: the `json` content kind ingests structured tool outputs / sensor readings. **How does it handle identity?** Three slots (caller, observed actor, subject) let bots act on behalf of a user or write about other entities. ## See also - [Lifecycle](https://cortexdb.ai/docs/concepts/lifecycle): the six atomic operations of memory. - [Scopes](https://cortexdb.ai/docs/concepts/scopes): how scopes partition memory. - [`POST /v1/experience`](https://cortexdb.ai/docs/api-reference/experience): the full API reference. ========================================================================================== # Lifecycle & Async Writes _The six atomic operations of memory and how to observe them via the SSE lifecycle stream._ Source: https://cortexdb.ai/docs/concepts/lifecycle CortexDB keeps heavy derivation **off the write path**: capture is durable within milliseconds, while extraction and consolidation run asynchronously. Writes are async by default, and you observe progress via a Server-Sent Events (SSE) lifecycle stream. A write appends an event to the WAL (acknowledgments are `fsync`'d by default, so an acked event survives power loss) and can return at the durable capture point in ~10 ms. The heavier work of extracting entities and consolidating beliefs happens strictly in the background. ## The six atomic operations These are **observable lifecycle events**, not separate endpoints. (Retrieve is *not* in the list: recall is a request/response operation.) | Operation | Fires when | Visible via | |---|---|---| | Capture | WAL append succeeds | `event: captured`; `wait=captured` returns | | Index | Event indexed in BM25 + HNSW | `event: indexed`; `wait=indexed` returns | | Update | Fact ADD / UPDATE / NOOP decision | `event: extracted` / `event: consolidated` | | Consolidate | Beliefs revised; Understanding touched | `event: consolidated`; `wait=consolidated` returns | | Forget | Records deleted | `event: forgotten` | | Compress | Episodes sealed; Understanding versions bumped | `event: compressed` | ## Choosing a write barrier: `?wait=` Pass `?wait=` to `POST /v1/experience` to pick the stage the connection is held for: | Value | Returns when | Typical latency | |---|---|---| | **(omitted)** | at **capture**: status `captured` (`202`). Read-your-writes holds: `/v1/recall` sees the **event** immediately, but BM25/HNSW indexing may still be in progress. | ~10 ms | | `captured` | Durable accept point (WAL `fsync`'d): same as omitted, made explicit | ~10 ms, flat in payload size | | `indexed` | BM25 + HNSW insert confirmed | ~100 to 500 ms | | `consolidated` | Beliefs / Understanding touched | ~500 to 3000 ms | > **Note: Omitted ≠ fully indexed** Omitting `?wait=` returns at **`captured`**, not "fully indexed". The event is durable and immediately visible to recall, but vector/BM25 search may lag briefly. If you need the event to be search-indexed before you return, pass **`?wait=indexed`**. `accepted` is an alias for the omitted default. A waiting capture has one budget of about 30 s (a waiting bulk, `min(30 s + 1 s per item, 600 s)`); when it runs out the server answers `408 WAIT_TIMEOUT` and the event keeps processing: see [Experience](https://cortexdb.ai/docs/api-reference/experience#wait-deadline-and-408-wait_timeout). ## Subscribing to the lifecycle stream The recommended pattern for UIs/agents is fire-and-forget writes + an SSE subscription: ```http GET /v1/lifecycle/stream?scope=org:acme/dept:eng&events=indexed,consolidated Accept: text/event-stream Authorization: Bearer ... X-Cortex-Actor: user:alice event: indexed data: { "event": "indexed", "scope": "...", "data": { "event_id": "evt_01HX...", "layers_indexed": ["events"] } } ``` Use the `Last-Event-ID` header (or `?since_lifecycle_id=`) to resume after a disconnect: the server replays missed events. ## Async jobs Lifecycle events cover async jobs too: | Job | Events | Status endpoint | |---|---|---| | Bulk write | `captured` per item + aggregate | none | | Import | `import_progress`, `import_complete`, `import_error` | `GET /v1/import/{id}` | | Erasure | none; poll the status endpoint | `GET /v1/erasures/{id}` | | Synthesize | `synthesis_progress`, `synthesis_complete` | `GET /v1/understanding/synthesize/{id}` | | Export | none: `POST /v1/export` is synchronous and returns the data inline | none (`GET /v1/export/{id}` is `404`) | A `lagging` event fires when the consolidator queue depth exceeds a configurable threshold: surface it to detect index drift. ## FAQ **How fast is a write?** `?wait=captured` (or omitted) returns at the durable accept point in ~10 ms, flat in payload size. Pass `?wait=indexed` to additionally block until search indexes have the event. **Does CortexDB include Retrieve in the lifecycle?** No: retrieve is a synchronous request/response, not a background stage. **Why async by default?** So the agent stays responsive while extraction/consolidation run in the background instead of blocking on an LLM. ## See also - [The Experience Envelope](https://cortexdb.ai/docs/concepts/experience-envelope): the payload that enters the lifecycle. - [The Five Memory Layers](https://cortexdb.ai/docs/concepts/layers): where data lands after consolidation. ========================================================================================== # Authorization _PASETO tokens, the four-tier capability stack, and how CortexDB evaluates authorization._ Source: https://cortexdb.ai/docs/concepts/authorization CortexDB authorizes every request through a **four-tier capability stack** and identifies callers with **PASETO v4 public tokens**. Authorization is enforced at the storage layer, not in application code. ## The four-tier stack Decisions cascade from outer to inner. An **allow** at an inner tier can override an outer allow (be more specific), but an **outer deny is final**. ``` 1. Deployment policy ← preset-defined floor (cannot be overridden by tenant/scope) 2. Tenant policy ← per-tenant defaults 3. Scope policy ← per-scope ACLs and members 4. Actor policy ← per-actor overrides ``` ## Deployment presets Set with `CORTEX_DEPLOYMENT_PRESET`. These four values are the complete set. | Preset | Notes | |---|---| | `dev_local` | **Default.** Experimentals enabled. Local development only. A keyed server rejects actor-only requests with `401`. | | `on_prem_enterprise` | Most permissive production preset; cross-workspace GDPR erasure allowed by default. | | `cloud_shared_saas` | Shared-cloud preset; experimentals gated; cross-workspace GDPR denied by default. | | `cloud_private` | Single-tenant cloud preset; experimentals gated. | ## Authenticating an agent Every request in a secured deployment carries: ```http Authorization: Bearer X-Cortex-Actor: user:alice ``` > **Note: Self-hosted auth modes** With **`CORTEX_API_KEY`** set, the key value itself is a working Bearer credential (constant-time compared), alongside PASETO/JWT bearers. To run **unauthenticated** for local dev, start with **`CORTEX_INSECURE_NO_AUTH=1`**: requests are served without a token (served as `user:local`, or as whatever `X-Cortex-Actor` names; it does **not** restrict the bind, so publish the port on loopback only, `-p 127.0.0.1:3141:3141`). With neither on a network-exposed bind, the server **auto-generates a key and requires it**. > **Note: On a network, send the key with every request** Every deployment preset requires the key: a request carrying only an `X-Cortex-Actor` header gets `401 MISSING_TOKEN`. ### Pick your auth path | You want to… | Use | Get a token by | |---|---|---| | Try the API in 60 s (prototype, AI self-install) | Anonymous sign-up | `POST /v1/auth/signup {}` → token + actor + scope. Self-hosted, the in-binary minter is **off by default on a keyed server** (`503 NOT_CONFIGURED`): enable with `CORTEX_V1_MINTER_ENABLE=1`; under `CORTEX_INSECURE_NO_AUTH=1` signup is served. Off on CortexDB Cloud (`CORTEX_DISABLE_ANON_SIGNUP=1`): cloud accounts sign up at cortexdb.ai and create tokens on the dashboard. | | Run a service account | Server-side mint | Token with `auth.mint`, then `POST /v1/auth/tokens` with subject/ttl/scopes. In-binary minter is dev-only. | | Production with permanent identities | Your IdP issues JWT or PASETO tokens | List it in the issuers file (`CORTEX_AUTH_ISSUERS_FILE`); CortexDB verifies its tokens and maps their subjects. See [Identity and Tokens](https://cortexdb.ai/docs/shared-memory/identity#external-issuers). | | Dashboard / MCP server | `cx_live_…` API key from the dashboard | A separate credential format the BFF exchanges for PASETO server-side. | ## Token claims ```json { "iss": "https://idp.acme.com/realms/main", "sub": "user:alice", "aud": "cortexdb:tenant:acme", "exp": 1763212929, "jti": "j_01HX...", "deployment": "cloud_shared_saas", "caps": ["scope.read.local", "scope.write"], "scopes": ["scope.read:org:acme/dept:eng/*", "scope.write:org:acme/dept:eng/user:alice"] } ``` `X-Cortex-Actor` must match `sub`. A token can only **narrow** what policy already allows: it cannot grant a capability the deployment denies. - **`caps`** narrows the token to the listed capabilities (empty inherits the deployment and tenant defaults). - **`scopes`** confines capabilities to scope subtrees. Each entry is `:[/*]`: an exact capability or a prefix (`scope.read` covers `scope.read.local`, `scope.read.holistic`, …), then the subtree it is confined to. A capability no entry names stays unconfined. A bare path such as `"org:acme/dept:eng"` is refused at mint with `422 INVALID_BODY` ("expected `:[/*]`"). - Neither claim makes the caller a **member** of a scope. Reading or writing a registered scope also needs a seat on its [scope roster](https://cortexdb.ai/docs/api-reference/scopes); a freshly minted agent that holds the right capabilities but no seat is refused with `403 POLICY_DENIED`. ## Application tokens on your own server An application usually gets its own token instead of the operator key: minted by the server, confined to the scopes it uses. Three settings decide whether those tokens work with scopes the operator registered: - **Turn the minter on.** `CORTEX_V1_MINTER_ENABLE=1`. With a key set and the minter off, `POST /v1/auth/tokens` answers `503 NOT_CONFIGURED`. - **Put the tokens in the operator's tenant.** The operator key acts in tenant `default`. A minted token acts in the tenant of the server's audience, `CORTEX_V1_AUDIENCE`, which is `cortexdb:tenant:dev` unless set. A scope belongs to the tenant that registered it, so with the default audience an app token is refused (`403`) on every scope the operator key registered. Start the server with `CORTEX_V1_AUDIENCE=cortexdb:tenant:default` and both share one tenant. - **Give the token a seat.** Register the scope with the token's subject among its `members` (`writer` to write, `reader` to read), or add it with `PUT /v1/scopes/members`. ```bash docker run -d … -e CORTEX_API_KEY -e CORTEX_V1_MINTER_ENABLE=1 \ -e CORTEX_V1_AUDIENCE=cortexdb:tenant:default cortexdb/cortexdb: curl -fsS --fail-with-body -X POST "$CORTEXDB_URL/v1/scopes" -H "Authorization: Bearer $CORTEX_API_KEY" \ -H "Content-Type: application/json" \ -d '{"path":"org:acme","members":[{"actor":"agent:assistant","role":"writer"}]}' APP_TOKEN=$(curl -fsS --fail-with-body -X POST "$CORTEXDB_URL/v1/auth/tokens" -H "Authorization: Bearer $CORTEX_API_KEY" \ -H "Content-Type: application/json" \ -d '{"subject":"agent:assistant","ttl_seconds":86400,"caps":["scope.write","scope.read.local","scope.read.holistic"],"scopes":["scope.write:org:acme/*","scope.read:org:acme/*"]}' \ | jq -r .token) ``` The app then sends `Authorization: Bearer $APP_TOKEN` with `X-Cortex-Actor: agent:assistant`. `caps` entries are exact capability names, so list each one a call checks: recall's default view, `holistic`, needs `scope.read.holistic`, and a read at one scope `scope.read.local`. In `scopes`, a prefix such as `scope.read` covers every `scope.read.*`. Tokens the server mints keep working across a restart: the minter's keys live in the data directory (or `CORTEX_V1_MINTER_KEY_DIR`). > **Note: Token rules** A minted token lives at most 90 days for a `user:` subject, 7 days for an `agent:` and 30 days for a `service:` subject by default (`CORTEX_MINT_MAX_LIFETIME_*` changes these); a token that carries `scopes` holds only the capabilities its entries name; and every mint names its tenant root (`scope`, `tenant` or `scopes` within one root). See [Identity and Tokens](https://cortexdb.ai/docs/shared-memory/identity#minting-tokens). On `cloud_shared_saas` the operator key's own reads of memories need a break-glass header ([Operator Modes](https://cortexdb.ai/docs/shared-memory/operator-modes)). ## Denials A `403` names the capability and the tier that denied it, and its `message` says why: ```json { "error_code": "POLICY_DENIED", "message": "scope.write is required for this write (denied_by_tier=Actor)", "details": { "capability": "scope.write", "denied_by_tier": "actor", "link": "confinement" }, "retriable": false, "request_id": "req_01a1cbfe-4d72-71e2-b888-30fc654d4e96" } ``` A denial also names the link that failed in `details.link` where one applies: `confinement` (the token's `scopes` name no such capability), `tenant` (another tenant's scope) or `minter` (the token's minter could not act there). `POST /v1/access/explain` shows every link of a decision ([Shared Memory](https://cortexdb.ai/docs/shared-memory#ask-the-server-who-may-read-what)). > **Note:** Introspect the allow/deny surface with **`GET /v1/policy/effective?actor=…&scope=…`**. That endpoint returns `allowed`/`denied` as **flat capability-name arrays** (plus `deployment_preset`, `rate_limits`): the per-entry `tier`/`reason` shown in the denial body is not returned there. See the [Policy API reference](https://cortexdb.ai/docs/api-reference/policy). ## Common capabilities | Capability | Gates | |---|---| | `scope.read.local` / `.holistic` / `.descend` | read at scope / traverse ancestors / traverse descendants | | `scope.write` / `.elevated` / `.on_behalf_of` / `.about_other` | write / write above natural scope / set observed_actor / set subject | | `forget.cascade.derived_only` / `.redact_events` | selective forget / blank event payloads | | `forget.gdpr` / `.cross_workspace` | true event deletion via `/v1/erasures` / propagate into co-owned workspaces | | `llm.invoke` | call `/v1/answer` | | `diagnostics.read` | request `diagnostics ≠ "none"` | | `understanding.synthesize` | trigger `/v1/understanding/synthesize` | ## FAQ **Can an inner policy override an outer one?** An inner **allow** can be more specific; an outer **deny** is always final. **Does CortexDB use flat tenant identifiers?** No: hierarchical scopes, so policy inherits down the hierarchy. ## See also - [Scopes](https://cortexdb.ai/docs/concepts/scopes) · [Lifecycle](https://cortexdb.ai/docs/concepts/lifecycle) - [Auth API](https://cortexdb.ai/docs/api-reference/auth) · [Policy API](https://cortexdb.ai/docs/api-reference/policy) ========================================================================================== # Knowledge Graph _How CortexDB constructs an entity graph natively from the event log, connecting isolated fragments into connected context._ Source: https://cortexdb.ai/docs/concepts/knowledge-graph The **Knowledge Graph** is an entity graph constructed natively from CortexDB's lossless, event-sourced memory: **nodes** are entities (people, projects, customers, incidents, …) and **edges** are the relationships between them. It is not a separate store: it is an emergent view of Facts and Beliefs. ## Why connected context matters Pure vector search treats facts as isolated text fragments and breaks down on relationship questions like "who owns this service?" or "what changed before this incident?" A graph lets an agent traverse relationships and surface implicit workflows and ownership that span multiple isolated conversations. ## How CortexDB models graph memory The entity graph is derived entirely from the event stream. Entities emerge as records are observed, and relationship edges form as predicates are ingested. Edges carry the same **bi-temporal validity window** as Facts, and traversal respects **hierarchical scopes**: an agent can't traverse edges it isn't authorized to see. ``` (person: Priya Rao) ──[works_at, valid 2024-01→ ]──→ (org: Acme Corp) │ └─[owns, valid 2026-02→ ]──→ (project: Q3 Renewal) ─[has_status, "negotiating"] ``` > **Note: Graph traversal is an internal channel, not a request parameter** There is **no client-supplied `graph` block on `/v1/recall`**. Passing a `graph: { seed_entities, max_hops, predicates, as_of }` body → **`422 "unknown field graph"`**. Graph traversal, when active, is an **internal fused retrieval channel**: you don't drive it per-request. The diagram above illustrates what the graph *encodes*, not a request you send. > **Note: Off by default (self-hosted)** The entity graph is **opt-in**: enable it with `CORTEX_ENTITY_GRAPH=1` (it also needs enrichment/an entity LLM to populate). `config_lint` notes the cost (~3× write / ~4× recall). On a default self-hosted instance the graph channel does not run: recall is BM25 + vector + RRF fusion. See [Self-hosting defaults](https://cortexdb.ai/docs/self-hosting/defaults) and [Hybrid Retrieval](https://cortexdb.ai/docs/concepts/hybrid-retrieval). ## What the Knowledge Graph enables - **Connected context**: traverse from a customer record to related tickets, decisions, and system logs. - **Relationship discovery**: surface ownership graphs and implicit workflows across conversations. - **Contextual grounding**: graph signal is fused with vector + BM25 during recall. ## FAQ **Does CortexDB use Neo4j internally?** No: it implements its own traversal directly over the event-sourced log. **Can agents traverse unauthorized edges?** No: traversal respects hierarchical scopes and bi-temporal validity; agents only see edges and entities their policy permits. ## See also - [Facts](https://cortexdb.ai/docs/api-reference/facts): the triples the graph is built from. - [Hybrid Retrieval](https://cortexdb.ai/docs/concepts/hybrid-retrieval): how graph fits with the other channels. ========================================================================================== # Hybrid Retrieval _How CortexDB combines BM25, HNSW vectors, graph traversal, and cross-encoder reranking through Reciprocal Rank Fusion._ Source: https://cortexdb.ai/docs/concepts/hybrid-retrieval Hybrid retrieval queries multiple complementary indexes in parallel and fuses the results, so an agent's context is leveraged fully regardless of the query's shape. The **full** architecture is four channels fused with **Reciprocal Rank Fusion (RRF)**. ## Why single-channel retrieval falls short Pure vector retrieval flattens identifiers (a query about a specific customer returns churn discussions instead of the literal record); pure lexical retrieval misses paraphrases. Agent queries never announce their shape in advance, so a single channel is limiting. ## The four channels - **BM25 (Tantivy)**: exact terms, identifiers, tokens (`SOC2` survives lexically but smears in vectors). - **HNSW vectors**: conceptual similarity; captures paraphrases. - **Graph traversal**: connected context across entities. - **Cross-encoder reranking**: re-scores top candidates against the literal query (Cohere `rerank-v3.5`). **RRF** combines the ranked lists into one StratifiedPack: no per-channel weight tuning, and it tolerates channels with different score distributions. > **Note: Default vs configured (self-hosted)** A **default self-hosted instance runs BM25 + HNSW vectors + RRF fusion only** (you can see this with `diagnostics=full`). The other two channels are opt-in: - **Graph traversal** needs the knowledge graph (`CORTEX_ENTITY_GRAPH=1` + enrichment). - **Cross-encoder reranking** needs a Cohere `rerank-v3.5` API key (`CORTEX_RERANKER_PROVIDER=cohere`). On managed cloud the fuller stack is configured for you. The "4-channel" framing describes the full capability; see [Self-hosting defaults](https://cortexdb.ai/docs/self-hosting/defaults) to enable the rest. ## What each channel contributes For the query *"what did Priya say about the SOC2 audit last week?"*: | Channel | Hit | Why it matters | |---|---|---| | BM25 (Tantivy) | literal terms `Priya`, `SOC2`, `audit` | identifiers/acronyms survive lexically | | HNSW vectors | "the compliance review with Priya last Tuesday" | captures paraphrases | | Graph traversal | entity `Priya` → `mentioned`/`owns` → recent compliance episodes | connected context that mentions neither term | | Cross-encoder rerank | re-scores top candidates | resolves close-but-wrong matches | The temporal phrase "last week" is resolved by the bi-temporal layer **before** retrieval runs, clipping every channel to the correct validity window. ## What it enables - **Comprehensive recall**: identifiers and abstract concepts in the same prompt. - **Graceful degradation**: BM25 + graph still contribute if the vector channel returns nothing useful. - **Strict boundaries**: results are filtered across hierarchical scopes and respect bi-temporal validity. ## How CortexDB compares | System | Lexical | Vector | Entity graph | Reranking | Fusion | |---|---|---|---|---|---| | CortexDB | BM25 (Tantivy) | HNSW | Native traversal (opt-in) | Cross-encoder (Cohere, opt-in) | RRF | | Mem0 | None | Single dense vector | None | None | N/A | | Zep | Partial | Dense vector | Coupled to write path | None | Custom | | Pinecone | None | Dense vector | None | None | N/A | ## FAQ **What is Reciprocal Rank Fusion?** A rank-aggregation method that combines ranked lists into one without per-channel score normalization. **Does hybrid retrieval block the write path?** No: the retrieval indices are populated asynchronously from the event log. ## See also - [The Five Memory Layers](https://cortexdb.ai/docs/concepts/layers) · [Knowledge Graph](https://cortexdb.ai/docs/concepts/knowledge-graph) - [Recall Tuning](https://cortexdb.ai/docs/operations/recall-tuning): the knobs behind these channels. ========================================================================================== # Shared Memory and the Access Model _One CortexDB for a tenant's sources, applications and org brain. Every memory has a home, every read is decided against it, and the access API says who may read what and why._ Source: https://cortexdb.ai/docs/shared-memory **Shared memory**: one server holds a tenant's **sources** (Slack channels, Drive folders, tickets), its **applications'** memories (one home per person in each application) and its **org brain** (teams, groups, rollups), and one access model decides every read and write across all three. The model fits in three sentences. Every memory has a **home**: the scope it was written to. Every request is made by a **principal** (a person, an agent acting for a person, a service), carried by a signed token. Every route that returns stored memories checks each one against that principal at its home, so a memory you may not read is never returned, whichever route you ask through. ## When to use it Use the shared-memory features when several people, agents and applications use one memory and they must not all see everything: a company brain, a support desk with per-agent notes, an application that keeps each customer's memory apart and still shares reference material. A single application that writes and reads its users' scopes with one key needs none of these features, but on `cloud_shared_saas` the operator key's reads of memories need a break-glass header: see [Operator Modes and Break-Glass](https://cortexdb.ai/docs/shared-memory/operator-modes). | You want to… | Read | |---|---| | Model teams, people and private spaces | [Org Trees](https://cortexdb.ai/docs/shared-memory/org-trees) | | Change who may read what, safely and in one step | [Change Sets](https://cortexdb.ai/docs/shared-memory/change-sets) | | Give each person and agent their own token, or use your identity provider | [Identity and Tokens](https://cortexdb.ai/docs/shared-memory/identity) | | Decide what the operator key may read | [Operator Modes and Break-Glass](https://cortexdb.ai/docs/shared-memory/operator-modes) | | Give applications per-person homes, sync sources with their permissions, handle agent writes | [Applications and Sources](https://cortexdb.ai/docs/shared-memory/applications-sources) | | Erase a person, an outside party or a tenant, or keep data under a legal hold | [Erasure and Legal Holds](https://cortexdb.ai/docs/shared-memory/erasure-holds) | | Connect ChatGPT, Claude, Cursor or another assistant | [Connecting AI Assistants](https://cortexdb.ai/docs/connect-assistants) | | Upgrade an existing server | [Upgrading](https://cortexdb.ai/docs/self-hosting/upgrading) | ## Who may read and write what A scope's record holds its **roster**: who holds which role there. There are four roles: | Role | Can | |---|---| | **Owner** | Administer the record: its roster, its tree attributes, its children | | **Writer** | Write memories there | | **Reader** | Read the memories there | | **Summary** | Read only rollup totals and items marked `summary_safe` | A roster entry can name a person, an agent, a service or a **set** (a named group of principals), and can carry an end date (`until`) or a condition (`when`), such as a purpose the read must declare. Sets, `summary`, `until` and `when` are written through [change sets](https://cortexdb.ai/docs/shared-memory/change-sets); the older registry routes (`POST /v1/scopes`, `PUT /v1/scopes/members`) take only `owner`, `writer` and `reader` entries for one principal each. Capabilities still come first: the deployment preset and the token's `caps` and `scopes` decide what kind of request a credential may make at all, and the roster decides where. See [Authorization](https://cortexdb.ai/docs/concepts/authorization) for the capability stack. ## Sensitivity labels Label a space `none`, `confidential` or `restricted` with `tree.label` on its record. A memory takes the strictest label of where it lives and where its sources live, and a grant can stop at a label with a `max_label` condition in its `when`. Admins set labels; they are not detected from content. An access explanation reports a memory's `label` as `{effective, cap, allowed}`. Example: the auditors' grant stops at `confidential`, so restricted legal items never reach them. ## Private regions A record marked `private` starts a **private region**: a person's own memory, a confidential group, a private channel. A private region is read only by name, by the people its roster names. No read that starts elsewhere walks into it, whatever view it asks for, and nothing CortexDB synthesizes outside it draws on it. Under the `deny` operator mode even the operator key needs a break-glass header to read one, and the region's people are told first ([Operator Modes](https://cortexdb.ai/docs/shared-memory/operator-modes)). ## The delivery gate Every route that returns stored rows (recall, answer, compose, events, facts, beliefs, exports, the lifecycle stream) checks each row's home for the reader, and, for a memory an agent wrote or CortexDB derived, every source it was made from. A row the reader may not read is left out; a read of it by id answers `404`, the same answer as an id that does not exist. A fact derived from a private conversation is therefore never served to someone who could not read that conversation. ## Ask the server who may read what The access API answers access questions and reads no memory: | Route | Answers | |---|---| | `POST /v1/access/check` | May this principal read, write or administer this scope, or read this one memory? | | `POST /v1/access/explain` | Why: each link that decided, with the path of records and entries it used | | `POST /v1/access/lookup/scopes` | Which scopes under a prefix may this principal read? | | `POST /v1/access/lookup/principals` | Who may read this scope? | | `GET /v1/access/limits?scope=` | The limits the server enforces for a tenant | | `POST /access/v1/evaluation`, `POST /access/v1/search/resource` | The same decisions over **AuthZEN 1.0**, for a policy enforcement point you already run; `GET /.well-known/authzen-configuration` describes them | A caller asks about its own token by default. An Owner of the scope, or the operator key, can ask about another principal by naming it in `chain`. A caller that holds no role at the scope gets one uniform denial (`not_authorized`), so the API never tells it whether the scope exists or is private. ```bash # Alice's own token: may she write to the engineering team's scope? curl -sS -X POST "$CORTEXDB_URL/v1/access/check" \ -H "Authorization: Bearer $ALICE_TOKEN" -H "X-Cortex-Actor: user:alice" \ -H "Content-Type: application/json" \ -d '{"scope": "org:acme/team:eng", "role": "writer"}' ``` ```json { "allowed": false, "denied_by": "person", "links": { "capability": {"allowed": true, "via": [{"kind": "capability", "field": "deployment.allow"}]}, "confinement": {"allowed": true}, "tenant": {"allowed": true, "via": [{"kind": "tenant", "record": "org:acme/team:eng", "field": "billing_tenant"}]}, "person": {"allowed": false, "reason": "insufficient_role", "via": [{"kind": "entry", "record": "org:acme/team:eng", "field": "members", "index": 2, "who": "user:alice", "role": "reader"}]} }, "names": {"user:alice": "Alice Kim"}, "role": "writer", "scope": "org:acme/team:eng", "until": null } ``` Alice is a Reader of `org:acme/team:eng`, so a write there is refused by the `person` link, and the answer names the roster entry that decided it. The same question over AuthZEN, asked with the operator key: ```bash curl -sS -X POST "$CORTEXDB_URL/access/v1/evaluation" \ -H "Authorization: Bearer $CORTEX_API_KEY" -H "Content-Type: application/json" \ -d '{"subject": {"type": "user", "id": "alice"}, "action": {"name": "write"}, "resource": {"type": "scope", "id": "org:acme/team:eng"}}' # {"context":{"denied_by":"person"},"decision":false} ``` ## Reading several scopes at once In an org tree a read does not walk the tree from a shared scope; it names what it reads. The four read routes (`/v1/recall`, `/v1/recall/stream`, `/v1/answer`, `/v1/compose`) take: - `extra_scopes`: up to 40 more scopes, searched in parallel in the same pass; - `coverage: true`: report which scopes were searched and any gap (a bound, a deadline, a private scope left out, a source whose last sync is old); - `mounts: "default"`: add the scopes your application mounts ([Applications and Sources](https://cortexdb.ai/docs/shared-memory/applications-sources)); - `beliefs: "merged"`: rebuild the pack's beliefs across the whole read set for this reader; - `purpose`: what the read is for (1 to 64 characters of `[a-z0-9_-]`). A roster entry whose `when` is `{"purpose": ""}` admits a read only when it declares that purpose. ```bash curl -sS -X POST "$CORTEXDB_URL/v1/recall" \ -H "Authorization: Bearer $ALICE_TOKEN" -H "X-Cortex-Actor: user:alice" \ -H "Content-Type: application/json" \ -d '{"scope": "org:acme/user:alice", "extra_scopes": ["org:acme/team:eng"], "query": "payments migration", "coverage": true}' ``` The pack's `coverage` lists the scopes searched (`org:acme/user:alice`, `org:acme/team:eng`) and its `gaps` (none here). ## Consistency tokens A write can return a **consistency token**, and a later read can demand it, so the read sees the write on whichever node serves it. Add `?consistency=1` to a write (a change set's activation always returns one), then send `"consistency": {"at_least": ""}` on a read, or `?at_least=` on a GET read. The read waits until the node has caught up, up to `CORTEX_CONSISTENCY_WAIT_MS` (10 s by default, 30 s at most), and answers `408 WAIT_TIMEOUT` past it. ```bash curl -sS -X POST "$CORTEXDB_URL/v1/experience?consistency=1" \ -H "Authorization: Bearer $BOB_TOKEN" -H "X-Cortex-Actor: user:bob" \ -H "Content-Type: application/json" \ -d '{"scope": "org:acme/team:eng", "modality": "conversation", "content": {"kind": "message", "role": "user", "text": "The payments migration starts on 12 January."}, "idempotency_key": "eng-decision-0001"}' # {"event_id":"evt_…","status":"captured",…,"consistency_token":"ct1.eyJy…"} ``` ## How to turn it on Shared memory is always on; there is nothing to switch on. `GET /v1/admin/version` lists each feature under its capability (`access_check_v1`, `access_changesets_v1`, `authzen_v1`, `org_tree_v1`, `directory_v1`, `scim_v1`, …): gate a client on the capability, not on the version. Upgrading a server from a release before shared memory is a one-way step: see [Upgrading](https://cortexdb.ai/docs/self-hosting/upgrading#from-013x-to-0140). ## See also - [Scopes](https://cortexdb.ai/docs/concepts/scopes) · [Authorization](https://cortexdb.ai/docs/concepts/authorization) · [Multi-Tenancy](https://cortexdb.ai/docs/enterprise/multi-tenancy) - [Connecting AI Assistants](https://cortexdb.ai/docs/connect-assistants) ========================================================================================== # Org Trees _Model a company's memory as an org tree, with teams, groups, people, compartments and private regions, and know the rules a shared scope follows._ Source: https://cortexdb.ai/docs/shared-memory/org-trees An **org tree** is a tenant whose root scope is registered with `"tree": {"kind": "org"}`. Its scopes carry a **kind** (a team, a group, a person), a **parent** (where it sits in the chart) and optionally `private`. The tree decides who reads what by default, and a few rules keep shared material from mixing with private material. A tenant without an org tree is unaffected by anything on this page. ## When to use it Use an org tree for a company or team brain: several people, their AI assistants and the company's sources in one memory, with team spaces, cross-team groups and each person's own private memory. For an application that only keeps each end user's memory apart, plain scopes under one root (`org:/user:`) are enough; see [Scopes](https://cortexdb.ai/docs/concepts/scopes). ## Kinds | `tree.kind` | Use it for | Notes | |---|---|---| | `org` | The tenant root | No parent | | `team` | A team or a department | Units are flat siblings under the root; `tree.parent` gives the chart, so a reorg changes `parent` and moves no memories | | `group` | A project, a committee, a meeting series, a 1:1 pair | Cross-team, read by its roster | | `person` | One person's own memory | Usually private | | `employee` | An AI employee's own working memory | Usually private | | `compartment` | An audience compartment of a unit or a person: `aud:pub`, `aud:lead`, `aud:roll`, `aud:work` | Published material, the unit's leads, rollups, and the part of a person's work that rolls up | A path's kind is the kind of the nearest registered record at or above it, so an unregistered path under a person's scope answers as that person's. ## Private regions `"private": true` on a record makes it, and everything under it, a **private region**: read only by name, by the people on its roster; never through an ancestor or a descendant; never an input to anything CortexDB synthesizes outside it. `"private": false` reopens a part of a private region (for example a person's `aud:work`, the part of their work that rolls up to their team). Left out, a record is private when its nearest registered ancestor that says so is. ## What changes at a shared scope An `org`, `team`, `group` or `compartment` scope is **shared**. Four rules hold there: - **No walking views.** `holistic`, `descend`, `structured` and `lineage` answer `422 VIEW_NOT_ALLOWED_AT_SCOPE` (`details.allowed_views: ["granular", "raw"]`). A read that names no view reads `granular`, the scope's own memories. To read across scopes, name them with `extra_scopes` (up to 40). A person's or employee's own scope keeps the default views. - **No auto-registration.** A first write to an unregistered path under a shared scope answers `403 SCOPE_REGISTRATION_REQUIRED`. Register every scope of the tree before anyone writes to it. - **Private stays private.** No walk enters a private region it did not start in, whatever a roster says, the operator key included. An export of a shared scope reads that scope's own rows. - **No implicit blending.** CortexDB never homes a synthesis of two scopes at a shared scope, and never homes a private scope's material outside its region. Names belong in the [directory](https://cortexdb.ai/docs/shared-memory/identity#the-directory), not in records: a registry write that sets `tree.display_name` answers `422 INVALID_SCOPE_TREE` (the records are kept for ever in the log; a directory entry can be erased). ## Set one up Tokens and records must belong to the same tenant. For an org tree, make the tenant's id the root's id: `org:acme` is tenant `acme`. On a server that holds one organization and mints its own tokens, start it with: ```bash CORTEX_API_KEY= CORTEX_V1_MINTER_ENABLE=1 CORTEX_V1_AUDIENCE=cortexdb:tenant:acme # minted tokens belong to tenant acme CORTEX_OPERATOR_INHERIT_TENANT=on # the operator key's registrations take the root's tenant ``` Tokens from your identity provider name their tenant through the issuers file instead ([Identity and Tokens](https://cortexdb.ai/docs/shared-memory/identity#external-issuers)). Register the root, bound to its tenant, and make it an org: ```bash curl -sS -X POST "$CORTEXDB_URL/v1/admin/access/tenant-binding?scope=org:acme" \ -H "Authorization: Bearer $CORTEX_API_KEY" -H "X-Cortex-Actor: user:admin" \ -H "Content-Type: application/json" -d '{"from": "default", "dry_run": false}' # {"scope":"org:acme","from":"default","to":"acme","root_registered":true,…} curl -sS -X PUT "$CORTEXDB_URL/v1/scopes/tree?path=org:acme" \ -H "Authorization: Bearer $CORTEX_API_KEY" -H "Content-Type: application/json" \ -d '{"kind": "org"}' ``` The binding call registers `org:acme` for tenant `acme` with `user:admin` (the `X-Cortex-Actor`) as its Owner. Under the `deny` operator mode (the default on `cloud_shared_saas`) the operator key's registrations need a break-glass header ([Operator Modes](https://cortexdb.ai/docs/shared-memory/operator-modes)). Then register the people and units. A person's private region: ```bash curl -sS -X POST "$CORTEXDB_URL/v1/scopes" \ -H "Authorization: Bearer $CORTEX_API_KEY" -H "X-Cortex-Actor: user:admin" \ -H "Content-Type: application/json" \ -d '{"path": "org:acme/user:alice", "members": [{"actor": "user:alice", "role": "owner"}], "tree": {"kind": "person", "parent": "org:acme", "private": true}}' ``` A team, with a reorg's worth of people or more, is best added as a [change set](https://cortexdb.ai/docs/shared-memory/change-sets), which previews who gains and loses access before anything changes. `POST /v1/scopes` with a `tree` works for a single record: ```bash curl -sS -X POST "$CORTEXDB_URL/v1/scopes" \ -H "Authorization: Bearer $CORTEX_API_KEY" -H "X-Cortex-Actor: user:admin" \ -H "Content-Type: application/json" \ -d '{"path": "org:acme/group:payments", "members": [{"actor": "user:alice", "role": "writer"}, {"actor": "user:bob", "role": "writer"}], "tree": {"kind": "group", "parent": "org:acme"}}' ``` Then give each person their own token ([Identity and Tokens](https://cortexdb.ai/docs/shared-memory/identity)), and name people, teams and groups in the directory: ```bash curl -sS -X PUT "$CORTEXDB_URL/v1/directory/user:alice?scope=org:acme" \ -H "Authorization: Bearer $CORTEX_API_KEY" -H "Content-Type: application/json" \ -d '{"display_name": "Alice Kim", "emails": ["alice@acme.example"], "title": "Engineering manager"}' ``` ## Reading in an org tree A read at a team scope reads that team's memories. A person who reads a team and their own memory names both: ```bash curl -sS -X POST "$CORTEXDB_URL/v1/recall" \ -H "Authorization: Bearer $ALICE_TOKEN" -H "X-Cortex-Actor: user:alice" \ -H "Content-Type: application/json" \ -d '{"scope": "org:acme/user:alice", "extra_scopes": ["org:acme/team:eng"], "query": "payments migration", "coverage": true}' ``` Asking for a walking view at the team scope is refused: ```json {"error_code": "VIEW_NOT_ALLOWED_AT_SCOPE", "details": {"allowed_views": ["granular", "raw"], "field": "view", "scope_kind": "team", "view": "holistic"}, "retriable": false} ``` ## Publish and rollups Agents draft; people publish. `POST /v1/publish` is how a person widens a memory: it copies an event (or a rollup) the person is served into a scope they write, with the original as its provenance, so erasing the original erases the copy. Only a person's own token publishes; an agent's token, a service and the operator key get `403 PUBLISH_PERSON_REQUIRED`. ```bash curl -sS -X POST "$CORTEXDB_URL/v1/publish" \ -H "Authorization: Bearer $ALICE_TOKEN" -H "X-Cortex-Actor: user:alice" \ -H "Content-Type: application/json" \ -d '{"target": "org:acme/group:payments", "source": {"scope": "org:acme/user:alice", "event_id": "evt_01a186bd6fa679d3be8735fa0d80ffd6"}}' # 202 {"event_id":"evt_…","status":"captured","published_from":{"scope":"org:acme/user:alice","event_id":"evt_01a186bd…"},…} ``` A unit (a team, or the org) whose `aud:roll` compartment is registered with the rollup audience gets **rollups**: typed monthly totals of its inputs and, where the background LLM stages run, synthesis items, built on a cadence within a daily budget (`CORTEX_ROLLUP_CADENCE`, `CORTEX_ROLLUP_BUDGET_USD`). `GET /v1/rollups?scope=/aud:roll` serves them, each only to a reader of every input it was built from. ## See also - [Change Sets](https://cortexdb.ai/docs/shared-memory/change-sets) · [Identity and Tokens](https://cortexdb.ai/docs/shared-memory/identity) - [Shared Memory and the Access Model](https://cortexdb.ai/docs/shared-memory) ========================================================================================== # Change Sets _Stage access changes, preview who gains and loses access, and activate them at once or on a date, with the tenant's own assertions as a guard._ Source: https://cortexdb.ai/docs/shared-memory/change-sets A **change set** rewrites a tenant's access records as one change. You stage it in parts (nothing is visible yet), preview its effect (which records change, who gains and who loses access), and activate it with the preview's hash, now or on a date. Activation applies every part at once, or nothing. ## When to use it Use a change set for anything bigger than one roster edit: a reorg, onboarding a team, a new application's admissions, a legal hold, a policy record. It is also how you write the newer record types (sets, holds, policies, companion records) and roster fields (`summary`, `until`, `when`, a set as a member), which the older registry routes do not take. Those routes (`POST /v1/scopes`, `PUT /v1/scopes/members`, `PUT /v1/scopes/tree`) still work and make one-part changes with no preview. ## The lifecycle | Step | Route | What happens | |---|---|---| | Stage | `POST /v1/access/changes` (more parts: `POST /v1/access/changes/{id}/parts`) | The parts are stored, not applied. The `id` is yours, unique per tenant root and caller, so a retry finds the first attempt | | Preview | `POST /v1/access/changes/{id}/preview` | The access diff against the records as they are now, with a structural `preview_hash` | | Activate | `POST /v1/access/changes/{id}/activate` | Applies every part, if the hash still matches and every check passes. Returns a consistency token | | Status | `GET /v1/access/changes/{id}?scope=` | `staged`, `scheduled`, `activated` or `discarded` | | Discard | `DELETE /v1/access/changes/{id}?scope=` | Drops a staged or scheduled change set | Activation refuses, and changes nothing, when: - the structure moved since the preview: `409 PREVIEW_CHANGED`, with the current hash; - a record it writes changed since it was staged: `409 CHANGESET_STALE` (discard it and stage again); - a change that widens access breaks one of the tenant's assertions: `409 ACCESS_ASSERTION_FAILED`; - it would pass a deployment limit: `409 ACCESS_LIMIT_REACHED`; - the caller no longer has the authority to make it: `403 POLICY_DENIED`. **Who may call.** For every record a change set writes, the caller is an Owner of it with `policy.administer.scope` there; a new record needs `scope.create.` and Ownership of its parent. An Owner of the tenant root covers everything in the tenant. The operator key may always stage; under the `deny` operator mode its activation of a change that registers a record, names a new `service:` principal or widens a private region needs a [break-glass header](https://cortexdb.ai/docs/shared-memory/operator-modes). A change set never reaches another tenant. ## Example: add a team Stage a change set that registers `org:acme/team:eng` with Bob as Owner and Alice as Reader: ```bash curl -sS -X POST "$CORTEXDB_URL/v1/access/changes" \ -H "Authorization: Bearer $CORTEX_API_KEY" -H "Content-Type: application/json" \ -d '{ "scope": "org:acme", "id": "add-eng-team", "reason": "Add the engineering team", "parts": [{"part": 0, "records": [ {"path": "org:acme/team:eng", "op": "put", "record": { "members": [ {"actor": "user:bob", "role": "owner"}, {"actor": "user:alice", "role": "reader", "reason": "reads engineering decisions"} ], "policies": {}, "auto_provisioned": false, "created_at": "2026-10-29T00:00:00Z", "tree": {"kind": "team", "parent": "org:acme"} }} ]}] }' # {"id":"add-eng-team","scope":"org:acme","state":"staged","parts":1,"parts_total":1,…} ``` Each record is the stored record, in the shape `GET /v1/scopes?path=` returns: `members`, `policies`, `auto_provisioned` and `created_at` are required, and the server sets `created_at`, `auto_provisioned` and `billing_tenant` itself. A record with `"op": "delete"` and no `record` removes one. A `reason` (on the change set or on an entry) is at most 256 bytes and holds no personal data. Preview it, with the people: ```bash curl -sS -X POST "$CORTEXDB_URL/v1/access/changes/add-eng-team/preview" \ -H "Authorization: Bearer $CORTEX_API_KEY" -H "Content-Type: application/json" \ -d '{"scope": "org:acme", "people": true}' ``` ```json { "id": "add-eng-team", "preview_hash": "sha256:02d20b6c98b20ab0feeadc721fb76b9912418ae8c3375ded6dc5d8517f735f73", "widens": true, "narrows": false, "summary": {"records_written": 1, "units": 1, "people_gaining": 2, "people_losing": 0, "rollups_hidden": 0}, "units": [{"unit": "org:acme/team:eng", "records": ["org:acme/team:eng"], "people": [ {"principal": "user:alice", "gains": [{"scope": "org:acme/team:eng", "before": null, "after": "reader"}], "losses": []}, {"principal": "user:bob", "gains": [{"scope": "org:acme/team:eng", "before": null, "after": "owner"}], "losses": []}]}], "assertions": {"evaluated": 0, "failed": []}, "stale_paths": [], "in_band": true, "in_band_parts": [{"part": 0, "path": "org:acme/team:eng", "reason": "registers"}], "has_more": false, "next_cursor": null } ``` (The response also lists each record's structural change, trimmed here.) `in_band: true` says that an activation of this change set by the operator key is an in-band action, which needs a break-glass header under the `deny` mode. Activate with the hash you reviewed: ```bash curl -sS -X POST "$CORTEXDB_URL/v1/access/changes/add-eng-team/activate" \ -H "Authorization: Bearer $CORTEX_API_KEY" -H "Content-Type: application/json" \ -d '{"scope": "org:acme", "preview_hash": "sha256:02d20b6c98b20ab0feeadc721fb76b9912418ae8c3375ded6dc5d8517f735f73"}' # {"id":"add-eng-team","state":"activated","revision":3,…,"consistency_token":"ct1.eyJy…"} ``` A wrong or out-of-date hash is refused, and nothing is activated: ```json {"error_code": "PREVIEW_CHANGED", "message": "the change set's structural effect is not the one approved", "details": {"preview_hash": "sha256:02d20b6c…"}, "retriable": false} ``` The hash covers the structure only (kinds, parents, privacy, audiences, labels, admissions), not the people on rosters, so roster churn inside the touched units does not invalidate an approval; the preview's `people` show who those changes reach. ## Assertions: who must never see what A **policy record** holds the tenant's assertions: cases of "this principal at this scope must, or must never, hold this role". Stage it alone, in a change set of its own: ```bash curl -sS -X POST "$CORTEXDB_URL/v1/access/changes" \ -H "Authorization: Bearer $CORTEX_API_KEY" -H "Content-Type: application/json" \ -d '{ "scope": "org:acme", "id": "privacy-assertions", "parts": [{"part": 0, "records": [ {"path": "org:acme/policy:privacy", "op": "put", "record": { "members": [{"actor": "user:admin", "role": "owner"}], "policies": {}, "auto_provisioned": false, "created_at": "2026-10-29T00:00:00Z", "tree": {"kind": "policy", "parent": "org:acme"}, "policy": {"cases": [ {"principal": {"actor": "user:bob"}, "scope": "org:acme/user:alice", "role": "reader", "expect": "deny", "note": "Bob never reads Alice private memory"} ]} }} ]}] }' ``` Preview and activate it as above. From then on a change set that would give Bob Reader on Alice's private region previews with the case under `assertions.failed`, and its activation is refused: ```json {"error_code": "ACCESS_ASSERTION_FAILED", "message": "the change widens access past the tenant's assertions", "details": {"failed": [{"case": "0", "policy": "org:acme/policy:privacy", "widening": true}]}, "retriable": false} ``` A change is blocked only when it widens access and breaks a case that held before it. A change that does not widen activates, and `watch` lists the cases it breaks. ## Dated activation Add `activate_at` (RFC 3339, at most 90 days ahead) when you stage. Activating it before the date records your approval and answers `202` with state `scheduled`; the server activates it at the date, running every check again, and leaves it `staged` with a `refusal` if a check fails then. ```bash curl -sS -X POST "$CORTEXDB_URL/v1/access/changes" \ -H "Authorization: Bearer $CORTEX_API_KEY" -H "Content-Type: application/json" \ -d '{"scope": "org:acme", "id": "add-sales-team", "activate_at": "2026-11-15T09:00:00Z", "parts": [{"part": 0, "records": [{"path": "org:acme/team:sales", "op": "put", "record": { "members": [{"actor": "user:admin", "role": "owner"}], "policies": {}, "auto_provisioned": false, "created_at": "2026-10-29T00:00:00Z", "tree": {"kind": "team", "parent": "org:acme"}}}]}]}' # then preview and activate as above: # 202 {"id":"add-sales-team","state":"scheduled","activate_at":"2026-11-15T09:00:00Z","approved_preview_hash":"sha256:…",…} ``` A staged or scheduled change set that is never activated is discarded 7 days after its date (or its staging, when undated). ## Derivation policies A change set also carries **derivation policies**: the rules for what CortexDB's enrichment may learn under a scope, as a record at `/attrs:derive`. The body and its fields are on [Derivation Policies](https://cortexdb.ai/docs/api-reference/derivation-policy). - **Written alone.** A change set that writes a derive record writes nothing else, in any part (`422 INVALID_ACCESS_RECORD`, `details.reason: derive_with_access_records`). A `resync` never names one: a policy is not access state, so no access source can drop it. - **Previewed.** The preview adds a `derivation` section: each record's rules before and after, each governed scope's effective policy hash before and after with the rules that move, whether the change only tightens, the texts it names, and `unsynced_impact`, what was learned under the old policy. An access change set's preview has no `derivation` key. - **Approved together.** The `preview_hash` binds the `derivation` section too: an ancestor's policy, a subject's settings or a named text that changes before activation is `409 PREVIEW_CHANGED`. A derivation record never enters an access change set's hash, so editing a policy never voids a pending access approval. - **Who.** An Owner of the governed scope or of the tenant root, with `derivation.administer.scope` or `policy.administer.scope` there. - **Narrowing.** A derivation change set staged with `narrowing: true` must only tighten (stricter restrictions, steering unchanged; a deletion never tightens). ## Narrowing change sets `"narrowing": true` declares that a change set only removes access; one whose records would widen access is refused at staging (`422 INVALID_BODY`, `not_narrowing`, naming the first record that widens). Narrowing change sets have a staging quota of their own, so a removal is never held back behind someone else's large staging, and they are admitted even while the disk is critical. ## See also - [Org Trees](https://cortexdb.ai/docs/shared-memory/org-trees) · [Erasure and Legal Holds](https://cortexdb.ai/docs/shared-memory/erasure-holds) (a hold is a change set too) - `GET /v1/access/watch?scope=` lists a root's registry changes, change-set events and notices from a position, for an audit feed or a cache that must follow access. ========================================================================================== # Identity and Tokens _The principal chain, what a minted token may carry and how long it lives, tokens from your own identity provider, the tenant directory, and SCIM provisioning._ Source: https://cortexdb.ai/docs/shared-memory/identity Shared memory decides every request by **who** is asking, so each person and each agent should carry a token of its own rather than one shared key. Tokens carry a principal chain, a minted token's reach is limited, tokens from your identity provider are accepted, and a directory holds names and sign-in accounts, which an identity provider can keep up to date over SCIM. ## The principal chain A token names its subject in `sub` (`user:alice`, `agent:triage`, `service:sync`). It may also say **what is acting for that subject**: | Claim | Says | |---|---| | `act` | The agent acting for the subject: `{"sub": "agent:assistant"}` | | `run` | The agent's run, `run_start` when it began | | `app` | The application the request comes through: `service:` | | `client` | `person` or `agent` | | `taint` | Tags carried from what the chain read, such as `["external"]` | | `auth_time` | When the person last signed in | | `minter` | Who minted the token (`operator`, or a principal) | A token with `act` or `run`, or whose `client` resolves to `agent`, is an **agent chain token**: it holds only what its `scopes` entries name, and lives at most 24 hours. A token with `act` writes only within a run (`403 RUN_REQUIRED` without one), and its writes are stored with the agent as `observed_actor`. `GET /v1/auth/whoami` shows the chain: ```json {"caller": "user:alice", "tenant_id": "acme", "deployment_preset": "on_prem_enterprise", "token": {"jti": "jti_01a186c0cbb876d1bb3e447ce6391a8f", "iss": "https://cortexdb.local/issuer", "exp": 1793265744}, "effective_capabilities": [], "chain": {"act": "agent:assistant", "client": "agent", "run": "run-42", "run_start": 1793262144, "minter": "operator", "issuer": "minter"}} ``` (`effective_capabilities` lists only families a `:*` entry names; this token's entries are confined to `org:acme`.) An agent's write also carries what its run read, and is redirected to the person's private space when it cannot show that safely: see [Applications and Sources](https://cortexdb.ai/docs/shared-memory/applications-sources#agent-writes-and-redirects). An AI employee acts under its own token (`sub` the employee, no `act`); a mint whose `act` names one is refused. ## Minting tokens `POST /v1/auth/tokens` mints a token with this server's minter (`CORTEX_V1_MINTER_ENABLE=1` on a keyed server). Four rules hold, each on by default: | Rule | What it refuses | |---|---| | **Lifetime ceiling** | A token living longer than its subject's ceiling: by default 90 days for a `user:` subject, 7 days for an `agent:`, 30 days for a `service:` or `system:` subject, and 24 hours when it carries a chain field (set with `CORTEX_MINT_MAX_LIFETIME_PERSON`, `_AGENT`, `_SERVICE` and `_CHAIN`; lowering one ends longer tokens at the next start). At the mint: `422 INVALID_BODY`, `ttl_too_long`; at every use of an older token past its ceiling: `401 INVALID_TOKEN_CLAIM`, `lifetime_over_ceiling`. The default lifetime is one hour | | **Total confinement** | On a token that carries `scopes`, any capability no entry names: `403 POLICY_DENIED`, `details.link: "confinement"`. Name every family the token uses; `:*` names one at every scope, and checks made without a scope (`audit.read`, `blob.upload`, `lifecycle.subscribe`, …) need it | | **The mint's reach** | A mint that names no tenant root (`scope`, `tenant` or `scopes`), unless the operator key mints a `service:` or `system:` token; a token wider than its minter; a mint by a token another principal minted | | **The minter link** | A token another principal minted, used where that minter could not act | The operator key mints a person's token for one tenant like this: ```bash curl -sS -X POST "$CORTEXDB_URL/v1/auth/tokens" \ -H "Authorization: Bearer $CORTEX_API_KEY" -H "Content-Type: application/json" \ -d '{"subject": "user:alice", "scope": "org:acme", "ttl_seconds": 3600}' # {"token":"v4.public.…","jti":"jti_…","expires_at":"2026-10-29T09:04:53+00:00"} ``` And an agent working for Alice in one run, confined to her tenant: ```bash curl -sS -X POST "$CORTEXDB_URL/v1/auth/tokens" \ -H "Authorization: Bearer $CORTEX_API_KEY" -H "Content-Type: application/json" \ -d '{"subject": "user:alice", "scope": "org:acme", "ttl_seconds": 3600, "act": "agent:assistant", "run": "run-42", "caps": ["scope.read.local", "scope.read.holistic", "scope.write"], "scopes": ["scope.read:org:acme/*", "scope.write:org:acme/*"]}' # {"token":"v4.public.….eyJjZGIiOiJjaGFpbjEifQ","jti":"jti_…","expires_at":"…", # "chain":{"act":"agent:assistant","run":"run-42","run_start":1793261247,"minter":"operator"}} ``` What the rules answer when a mint goes past them: ```json {"error_code": "INVALID_BODY", "details": {"reason": "ttl_too_long", "field": "ttl_seconds", "lifetime_s": 2592000, "ceiling_s": 604800}, "retriable": false} ``` ```json {"error_code": "POLICY_DENIED", "message": "a mint that names no tenant root is deployment-wide, the trusted operator's alone and only for a service: or system: subject: name the root with scope, tenant or scopes", "details": {"reason": "deployment_mint_requires_operator"}, "retriable": false} ``` Each rule has a switch (`CORTEX_MINT_LIFETIME_ENFORCE`, `CORTEX_TOKEN_CONFINEMENT_ENFORCE`, `CORTEX_MINT_REACH_ENFORCE`, `CORTEX_MINTER_LINK_ENFORCE`). `off` serves what the rule would refuse and counts it in `GET /v1/admin/access/report` instead: a way to find the clients to fix after an upgrade, not a setting to keep. ## External issuers Production deployments usually let their identity provider (Okta, Microsoft Entra ID, Auth0, Keycloak) issue the tokens. `CORTEX_AUTH_ISSUERS_FILE` names a TOML file of trusted issuers: **JWT** (RS256 or ES256, with pinned keys or a JWKS URL) and **PASETO v4** (pinned keys). Each entry says how a token's subject maps to a principal, which tenants it may name, which chain claims its tokens may carry and how long they may live. ```toml version = 1 [[issuer]] id = "acme-idp" iss = "https://login.acme.example" format = "jwt" algorithms = ["RS256"] keys = ["keys/idp.pem"] # or jwks_url = "https://login.acme.example/.well-known/jwks.json" max_lifetime_s = 3600 [issuer.subject] mode = "directory" # the person whose directory entry holds this sign-in account kinds = ["user"] [issuer.tenants] allowed = ["acme"] aliases = [{ aud = "https://memory.acme.example/mcp", tenant = "acme" }] ``` | `subject.mode` | Maps the token's subject to | |---|---| | `directory` | The principal whose [directory](#the-directory) entry lists the account (`{system, account}`; the system is the entry's `iss` unless set) | | `actor` | The value itself, which is already a principal id (`user:alice`) | | `prefix` | `:.`, such as `user:acme.00u1abcd` | | `hash` | `:.<32 hex digits>`, an HMAC of the value | > **Note: Use directory mode for people** A `prefix` or `hash` principal id holds a `.`, which a scope path cannot. Such a person cannot have a scope named after them (their own region `org:acme/user:`), and the MCP server's default allowlist, which is built from the principal id, names no scope for them. Map people with `directory` (or `actor`) mode. A token of a `directory`, `prefix` or `hash` entry may be sent without `X-Cortex-Actor`, since its client cannot know the principal it maps to; `GET /v1/auth/whoami` answers it: ```bash curl -sS "$CORTEXDB_URL/v1/auth/whoami" -H "Authorization: Bearer $IDP_ACCESS_TOKEN" # {"caller":"user:dana","tenant_id":"acme","token":{"jti":"acme-idp:7dca…","iss":"https://login.acme.example",…},…} ``` `tenants.aliases` maps an audience that is not `cortexdb:tenant:`, such as the MCP server's resource URL, to a tenant: that is how an identity provider's access token for the [MCP server](https://cortexdb.ai/docs/connect-assistants#remote-mcp-on-your-server) works. A token past `max_lifetime_s` is `401 INVALID_TOKEN_CLAIM` (`lifetime_over_maximum`), one whose audience the entry does not admit `401 WRONG_TENANT`. `POST /v1/admin/auth/reload` (operator key) re-reads the file without a restart; a file that breaks a rule is refused and the running entries kept. An issuer's token never mints. ## The directory The directory holds each tenant's principals (names, emails, titles, sign-in accounts) and the names of its scopes, sets and applications. Names live here rather than in scope records, because records are kept for ever in the log and a directory entry can be erased. ```bash curl -sS -X PUT "$CORTEXDB_URL/v1/directory/user:alice?scope=org:acme" \ -H "Authorization: Bearer $CORTEX_API_KEY" -H "Content-Type: application/json" \ -d '{"display_name": "Alice Kim", "emails": ["alice@acme.example"], "title": "Engineering manager"}' # 200, ETag: "1" # {"id":"user:alice","display_name":"Alice Kim","title":"Engineering manager","status":"active", # "emails":["alice@acme.example"],"accounts":[],"version":1} curl -sS "$CORTEXDB_URL/v1/directory?scope=org:acme&q=ali" \ -H "Authorization: Bearer $ALICE_TOKEN" -H "X-Cortex-Actor: user:alice" ``` - Any principal of the tenant reads names and titles; emails, accounts and attributes only the tenant root's Owners, the operator and the principal itself. A private scope's name only its readers. - A scope or set is named by its path, with `/` sent as `%2F`: `PUT /v1/directory/org:acme%2Fteam:eng?scope=org:acme` `{"display_name": "Engineering"}`. - `"status": "deactivated"` stops every credential of the person at its next request, whichever issuer signed it (`401 SUBJECT_UNMAPPED`, `deactivated`), until the entry is active again. Their memberships are kept. - `If-Match` with the entry's version makes a write conditional (`412 DIRECTORY_VERSION_CHANGED`). - Register the tenant root first: until a record registers it, only the operator key administers the tenant's directory. ## SCIM An identity provider provisions a tenant's people and groups at `/scim/v2/Users` and `/scim/v2/Groups` (SCIM 2.0, with `ServiceProviderConfig`, `ResourceTypes` and `Schemas`). Users are directory entries; Groups are sets, whose membership changes are applied as change sets. `active: false` deactivates the person as above. The caller is the tenant's SCIM client: a token whose subject is `service:scim-` with the tenant's audience, which must be an Owner of the tenant root. SCIM needs the default one-segment tenant roots (`CORTEX_TENANT_DEPTH` 1): deeper roots answer `501 SCIM_UNSUPPORTED`. ## See also - [Authorization](https://cortexdb.ai/docs/concepts/authorization) · [Auth API](https://cortexdb.ai/docs/api-reference/auth) - [Operator Modes and Break-Glass](https://cortexdb.ai/docs/shared-memory/operator-modes) · [Connecting AI Assistants](https://cortexdb.ai/docs/connect-assistants) ========================================================================================== # Operator Modes and Break-Glass _What the static operator key may read under allow, audit and deny, the presets' defaults, the break-glass header, a tenant's own mode, and the access report that shows when it is safe to tighten._ Source: https://cortexdb.ai/docs/shared-memory/operator-modes The static operator key (`CORTEX_API_KEY`) is the deployment's own credential. Its **operator mode** decides whether it can also read the memories it stores for others: `CORTEX_OPERATOR_DATA_READS` is `allow`, `audit` or `deny`. The mode governs only requests the operator key makes (and a deployment minter's mints); no other token is affected. ## The three modes | Operator-key action | `allow` | `audit` | `deny` | |---|---|---|---| | Operator routes: health, version, the console, minting tokens without data capabilities, the registry's reads, the access API and AuthZEN, erasures, audit, admin routes that return no content | served | served | served | | Reading stored memories (`/v1/recall`, `/v1/answer`, `/v1/export`, `/v1/events`, layer reads, a forget preview by query) | served | served, counted | needs the header | | Admin routes that return content (`/v1/admin/events/{id}/chunks`, …) | served | served, counted | needs the header | | Reading a scope in a private region | served | served, counted | needs the header, and the region's people are told first | | In-band actions: registering scopes (a first write that registers one included), writing into a private region or a shared org-tree scope, minting a token that carries a data capability, a change-set activation that registers records or widens a private region, lowering a tenant's mode from `deny` | served | served, counted | needs the header | | Other writes, imports, forgets and erasures | served | served | served | "Counted" means the access report counts what `deny` would refuse (check `operator_access`), so `audit` shows when an application has stopped depending on the key. "Needs the header" means `403 BREAK_GLASS_REQUIRED` unless the request carries a break-glass header. ## The presets' defaults Unset, the mode is the deployment preset's (`CORTEX_DEPLOYMENT_PRESET`): | Preset | Default operator mode | |---|---| | `cloud_shared_saas` (with auth on) | `deny` | | `on_prem_enterprise` | `allow` | | `cloud_private` | `allow` | | `dev_local` (the binary's default) | `allow` | | any preset with auth disabled | `allow` (`audit` and `deny` refuse to start) | So a multi-tenant deployment keeps the operator key out of its tenants' memories unless an operator says why, and a single-organization deployment behaves as before. Set the variable to choose otherwise; any other value refuses the start (exit 78). ## Break-glass Under `deny`, an operator-key request that needs the header sends: ```text X-Cortex-Break-Glass: reason=support; ticket=SUP-1142 ``` `reason` is one of `incident`, `legal`, `support`, `security`, `migration`, `restore` or `other`; `ticket` is your case reference (1 to 64 characters of `[A-Za-z0-9._:-]`, no personal data); an optional `note` (percent-encoded, at most 256 bytes) goes to the decision log only. Each such request is audited with its reason and ticket. A read of a private region tells the region's people first (a notice they read at `GET /v1/access/notices`), and is not served until that notice is stored. The header is checked for its form, not its truth: it is an accountable override, not an authentication. ```bash # A cloud_shared_saas server, the operator key, no header: curl -sS -X POST "$CORTEXDB_URL/v1/recall" \ -H "Authorization: Bearer $CORTEX_API_KEY" -H "Content-Type: application/json" \ -d '{"scope": "org:acme/user:alice", "query": "standups"}' ``` ```json {"error_code": "BREAK_GLASS_REQUIRED", "message": "the operator key's stored_rows action on /v1/recall needs X-Cortex-Break-Glass under the tenant's operator mode deny", "details": {"class": "stored_rows", "mode": "deny", "route": "/v1/recall"}, "retriable": false} ``` ```bash # The same request with the header is served: curl -sS -X POST "$CORTEXDB_URL/v1/recall" \ -H "Authorization: Bearer $CORTEX_API_KEY" -H "Content-Type: application/json" \ -H "X-Cortex-Break-Glass: reason=support; ticket=SUP-1142" \ -d '{"scope": "org:acme/user:alice", "query": "standups"}' ``` A malformed header is `400 INVALID_HEADER` in every mode, naming what is wrong (an unknown reason, a ticket outside its grammar, a repeated header). The embedded console asks the operator for a reason and a ticket only after a request answers `403 BREAK_GLASS_REQUIRED`. ## A tenant's own mode A tenant can be stricter, or, with a break-glass header, looser than the deployment: ```bash curl -sS "$CORTEXDB_URL/v1/admin/access/tenant-settings?scope=org:acme" \ -H "Authorization: Bearer $CORTEX_API_KEY" # {"scope":"org:acme","operator_data_reads":{"mode":"deny","source":"deployment"},"deployment_mode":"deny"} curl -sS -X PUT "$CORTEXDB_URL/v1/admin/access/tenant-settings?scope=org:acme" \ -H "Authorization: Bearer $CORTEX_API_KEY" -H "Content-Type: application/json" \ -H "X-Cortex-Break-Glass: reason=migration; ticket=OPS-1142" \ -d '{"operator_data_reads": "audit"}' # {"scope":"org:acme","operator_data_reads":{"mode":"audit","source":"tenant"},"deployment_mode":"deny",…} ``` Lowering a tenant from `deny` is itself an in-band action and needs the header; raising it back needs none. ## Moving an application off the operator key An application that reads, writes or mints with the operator key on a `cloud_shared_saas` deployment is refused under `deny`. To move it without an outage: 1. Set `CORTEX_OPERATOR_DATA_READS=audit` (or the tenant's own mode to `audit`). Everything is served as under `allow`, and each request `deny` would refuse is counted. 2. Move the application to per-person tokens ([Identity and Tokens](https://cortexdb.ai/docs/shared-memory/identity)). While it still uses the key, `X-Cortex-Subject-Token: ` on its requests evaluates each decision for that person too and counts the result (check `subject_shadow`), without changing any answer: a dry run of the move. 3. Read the counts, then set `deny` once `operator_access` stays at zero: ```bash curl -sS "$CORTEXDB_URL/v1/admin/access/report?scope=org:acme" -H "Authorization: Bearer $CORTEX_API_KEY" ``` ```json {"scope": "org:acme", "checks": [{"check": "operator_access", "requests": 1, "outcomes": {"match": 0, "would_deny": 1}, "routes": [{"method": "POST", "route": "/v1/recall", "requests": 1, "would_deny": 1, "reasons": {"stored_rows": 1}, "…": "…"}], "classes": {"stored_rows": 1}}, "…"], "tenant_settings": {"scope": "org:acme", "operator_data_reads": {"mode": "audit", "source": "tenant"}, "deployment_mode": "deny"}} ``` The report's counts are in memory and restart with the process (`counting_since`). Every refused request also writes one line under the log target `cortex_api::decision` (`CORTEX_DECISION_LOG`, default `denials`), naming the link that failed. ## See also - [Deployment Presets](https://cortexdb.ai/docs/enterprise/deployment-presets) · [Multi-Tenancy](https://cortexdb.ai/docs/enterprise/multi-tenancy) - [Upgrading](https://cortexdb.ai/docs/self-hosting/upgrading#from-013x-to-0140): the operator key on `cloud_shared_saas` ========================================================================================== # Applications and Sources _Register applications with a home per person and mounted sources, sync sources into containers that follow each source's own sharing, and see how agent writes carry what they read._ Source: https://cortexdb.ai/docs/shared-memory/applications-sources A tenant's memory comes from three places: its **sources** (Slack, Teams, Drive, Confluence, Notion, Discord), its **applications** (a support desk, a sales assistant) and the people and agents that work in them. Each of them has a place in the access model. ## Applications An **application record** registers one application in one tenant: the memory kinds it writes, a home for each person, the sources it mounts, and its limits. `PUT /v1/apps/{id}?scope=` (an Owner of the tenant root, or the operator key) writes it: ```bash curl -sS -X PUT "$CORTEXDB_URL/v1/apps/support?scope=org:acme" \ -H "Authorization: Bearer $CORTEX_API_KEY" -H "Content-Type: application/json" \ -d '{"kinds": ["note", "decision"], "limits": {"requests_per_minute": 600}}' ``` ```json {"id": "support", "path": "org:acme/app:support", "members": [{"actor": "service:support", "role": "owner"}], "home": "org:acme/app:support/user:{person}", "kinds": ["note", "decision"], "mounts": [], "limits": {"requests_per_minute": 600}, "consistency_token": "ct1.eyJy…"} ``` - **Homes.** Each person's memory in the application lives at `org:acme/app:support/user:`. A person's first write there registers it as their own private region, admitting the application: ```bash curl -sS -X POST "$CORTEXDB_URL/v1/experience?wait=indexed" \ -H "Authorization: Bearer $ALICE_TOKEN" -H "X-Cortex-Actor: user:alice" \ -H "Content-Type: application/json" \ -d '{"scope": "org:acme/app:support/user:alice", "modality": "conversation", "content": {"kind": "message", "role": "user", "text": "Customer 4411 asked for a refund on the annual plan."}}' ``` - **Mounts.** `mounts` lists scopes (`{"scope": …}`) or prefixes of source containers (`{"prefix": …}`) the application reads beside the person's home. A read with `mounts: "default"` adds them to its read set. Every mount must be outside private regions and already admitted for the application. - **Admission.** In a tenant whose root companion sets `apps_enforced`, a token that names an application (`app: "service:support"`) reads and writes only where that application is admitted (`403 APP_NOT_ADMITTED` elsewhere). Admissions are written with [change sets](https://cortexdb.ai/docs/shared-memory/change-sets). - **Names** live in the directory: `display_name` on the record is refused. Name the application with `PUT /v1/directory/org:acme%2Fapp:support?scope=org:acme` `{"display_name": "Support desk"}`. - **Limits.** `requests_per_minute` limits the application's chains in the tenant (`429` past it). A tenant holds at most 8 application records by default (`CORTEX_LIMIT_APPS`). - **Reference material.** An application's reference root, `app:` registered with `"reference": true` by the operator key, holds documents every chain of that application reads, from any tenant: product docs shared by every customer's assistant, for example. Only the application's own principal writes there. ## Sources and containers A connector in **container mode** writes each permission unit of its source (a channel, a folder, a space) into its own container, `/source:/container:`, and each direct or group conversation into a private group, so the memory follows the source's own sharing: - each container's roster is built from the source's members, resolved to directory principals (`POST /v1/access/accounts/resolve`); an account the directory does not know grants nothing; - when an item's sharing changes, `POST /v1/access/rehome` moves its events to the right container without erasing them; - after each sync, the connector records how far it got (`PUT /v1/access/watermarks`), and a read with `coverage: true` reports a source whose last sync is older than `CORTEX_SOURCE_WATERMARK_MAX_AGE_S` (a day by default) as a gap. `cortexdb-connectors` 0.3.0 adds container mode for Slack, Teams, Discord, Google Drive, Confluence and Notion: set `CORTEXDB_CONTAINER_ROOT` to an org-tree tenant's root. Without it every connector writes exactly as before. `cortexdb-sync migrate-containers [--dry-run]` moves a tenant's existing items onto containers. See [Connectors](https://cortexdb.ai/docs/connectors). ## Agent writes and redirects An agent's write is only as shareable as what it read. The server keeps a read record per agent chain and run, and a write by an [agent chain token](https://cortexdb.ai/docs/shared-memory/identity#the-principal-chain) carries the homes of what its run was served. The written memory is then served only to readers of all of those homes, and erasing any memory it was made from erases it too. A caller can also declare `provenance` (up to 1,024 event ids) on a write. When a write cannot carry that safely (the run read a private region, carries a `taint`, read from more than 16 homes, or its read record is unknown, as after a restart), it is **redirected** to the writer's own private space, and the answer says where it landed: ```bash # An agent working for Alice, in run run-42, after reading her private region, # writes to a group she is a Writer of: curl -sS -X POST "$CORTEXDB_URL/v1/experience" \ -H "Authorization: Bearer $AGENT_TOKEN" -H "X-Cortex-Actor: user:alice" \ -H "Content-Type: application/json" \ -d '{"scope": "org:acme/group:payments", "modality": "conversation", "content": {"kind": "message", "role": "assistant", "text": "Draft: migration checklist for Postgres 17."}, "idempotency_key": "agent-draft-0001"}' # 202 {"event_id":"evt_…","status":"captured",…,"redirected_to":"org:acme/user:alice"} ``` The draft stays with Alice. To share it, Alice herself [publishes](https://cortexdb.ai/docs/shared-memory/org-trees#publish-and-rollups) it: agents draft, people publish. ## See also - [Shared Memory and the Access Model](https://cortexdb.ai/docs/shared-memory) · [Identity and Tokens](https://cortexdb.ai/docs/shared-memory/identity) - [Connectors](https://cortexdb.ai/docs/connectors) · [Connecting AI Assistants](https://cortexdb.ai/docs/connect-assistants) ========================================================================================== # Erasure and Legal Holds _Erase a person, an outside party or a whole tenant with one job and one receipt, keep data under a legal hold, and forget by the keys a client already holds._ Source: https://cortexdb.ai/docs/shared-memory/erasure-holds This page covers three erasures that span a tenant (a **person**, an **outside party**, a whole **tenant**), **legal holds** that keep what they name from every forget, erasure and retention sweep, and a **forget by key** that deletes what a client wrote without reading anything first. Each erasure is one job with one receipt of ids, counts and hashes, which `GET /v1/erasures/{id}/verify` checks against every store. The single-scope erasure (`POST /v1/erasures`) uses the strict selectors below; see [Erasures](https://cortexdb.ai/docs/api-reference/erasures). ## Erase a person `POST /v1/erasures/person` (operator key) erases what one person holds in a tenant, in order: their own region and everything under it, their homes in every application, their own messages in the tenant's groups, and last their directory entry. ```bash curl -sS -X POST "$CORTEXDB_URL/v1/erasures/person" \ -H "Authorization: Bearer $CORTEX_API_KEY" -H "Content-Type: application/json" \ -d '{"scope": "org:acme", "person": "user:bob", "confirm": true, "reason": "DSR-1234"}' ``` ```json {"erasure_id": "erasure_01a186b653c371038d48c0c3610f13a8", "status": "completed", "manifest_url": "/v1/erasures/erasure_01a186b653c371038d48c0c3610f13a8", "receipt_url": "/v1/erasures/erasure_01a186b653c371038d48c0c3610f13a8/receipt", "verify_url": "/v1/erasures/erasure_01a186b653c371038d48c0c3610f13a8/verify", "lifecycle_stream": "/v1/lifecycle/stream?erasure_id=erasure_01a186b653c371038d48c0c3610f13a8", "audit_id": "audit_01a186b653ca79628fbf69a2ea382270"} ``` The receipt (`kind: "person"`) counts what went per scope, and lists under `review` the scopes outside those parts that still hold events about the person, for you to decide. `reason` (at most 256 bytes, no personal data) is checked and written nowhere. While one person's erasure runs, a second for the same person answers `409 DESTRUCTIVE_OPERATION_IN_PROGRESS`, naming the running job. ## Erase an outside party A customer or contact who is not a principal of the tenant is erased by email address, through the `party:

` labels your writers put on events that concern them: ```bash curl -sS -X POST "$CORTEXDB_URL/v1/erasures" \ -H "Authorization: Bearer $CORTEX_API_KEY" -H "Content-Type: application/json" \ -d '{"scope": "org:acme", "subject": {"email": "jane@example.com"}, "confirm": true}' ``` Every labelled event in every scope of the tenant goes, archived and expired ones included. Only labelled events are found, never one that names the address in its text alone, so label at capture (`"context": {"labels": ["party:jane@example.com"]}`). The receipt (`kind: "party"`) names the address only by a hash, counts the events per scope and says `coverage: "labelled_only"`. ## Delete a tenant `POST /v1/erasures/tenant` (operator key) deletes a tenant: its memory, its directory and its registry. It is a dry run unless you send `"dry_run": false` with `"confirm": true`: ```bash curl -sS -X POST "$CORTEXDB_URL/v1/erasures/tenant" \ -H "Authorization: Bearer $CORTEX_API_KEY" -H "Content-Type: application/json" \ -d '{"scope": "org:acme"}' # {"scope":"org:acme","dry_run":true,"counts":{"records":7,"events":3,"directory_entries":1,…},"holds":[]} ``` From the deletion's first step every credential of the tenant answers `410 TENANT_DELETED`, and its `/verify` proves it as a whole-scope erasure. While any legal hold of the tenant is in force the route answers `409 HOLD_IN_FORCE`, dry run or not: release the holds first. ## Legal holds A **hold** record (`/hold:`, an opaque id that never names the matter) keeps the events of the scopes it names and, for each person it names, the events that person wrote, observed or is the subject of, within an optional window (`from` inclusive, `until` exclusive). What was derived from a held event (facts, beliefs, episodes, rollups) stays with it. A hold is written with a change set: ```bash curl -sS -X POST "$CORTEXDB_URL/v1/access/changes" \ -H "Authorization: Bearer $CORTEX_API_KEY" -H "Content-Type: application/json" \ -d '{ "scope": "org:acme", "id": "hold-m-2026-114", "reason": "Legal hold", "parts": [{"part": 0, "records": [ {"path": "org:acme/hold:m-2026-114", "op": "put", "record": { "members": [{"actor": "user:admin", "role": "owner"}], "policies": {}, "auto_provisioned": false, "created_at": "2026-10-29T00:00:00Z", "tree": {"kind": "hold", "parent": "org:acme"}, "hold": {"matter": "Matter 2026-114", "people": [{"actor": "user:bob", "from": "2026-01-01T00:00:00Z"}]} }} ]}] }' # then preview and activate it (Change Sets) ``` The `matter` text is stored apart from the record and can be erased on its own (`POST /v1/access/texts/erase`); the record keeps only a reference. Add `"scopes": ["org:acme/team:sales"]` to hold whole scopes. While the hold is in force: - an erasure or forget keeps every held event and lists it in its receipt (`held_event_ids`), never among what was erased; a person's erasure also keeps the held person's directory entry; - the previews count what a hold keeps (`events_under_legal_hold`, `derived_under_legal_hold`); - retention sweeps keep held events; - a tenant's deletion is refused (`409 HOLD_IN_FORCE`). A hold is released only by a change to its record (a change set that deletes or narrows it), never by a date passing. Once released, the server runs the erasures it kept pending, as their jobs asked. The receipt of Bob's erasure while a hold on Bob was in force (trimmed): the hold kept his two events and his directory entry, pending until its release. ```json {"kind": "person", "person_erasure": {"parts": {}, "review": {"org:acme/team:eng": 1}, "held": ["org:acme/user:bob", "person"], "directory_erased": false}, "held_event_ids": ["evt_01a186b653477111a1c70eee5fa6a761", "evt_01a186b6535b7ab1a2ebfc1496cda862"]} ``` ## Forget by key A client that wrote with idempotency keys can forget those writes without reading anything first: `selector.idempotency_keys` (up to 1,024 `{key, caller?}`; a key's claim lasts 24 hours) and `selector.capture_keys` (up to 64 capture labels such as `cap:`). The capability `forget.by_key` admits such a forget alone, so a clean-up service's token needs no read capability (like every forget by a token, it needs the Owner role where it forgets). It reads nothing, so under the `deny` operator mode the operator key needs no break-glass header for it. ```bash curl -sS -X POST "$CORTEXDB_URL/v1/forget" \ -H "Authorization: Bearer $CORTEX_API_KEY" -H "Content-Type: application/json" \ -d '{"scope": "org:acme/team:eng", "selector": {"idempotency_keys": [{"key": "eng-0001", "caller": "user:bob"}]}, "audit_note": "withdrawn"}' # {"deleted":{"events":1,"episodes":0,"facts":0,"beliefs":0,"understanding":0},"requested":1,"matched":1,…} ``` `caller` is whose write the key was (the request's own principal when left out). `/v1/forget/preview` takes the same selector. The erasure routes take neither key selector (`422`, `key_selector_not_supported`). ## Strict selectors A forget or erasure refuses a selector field it does not apply (`422 INVALID_BODY`, `unknown_selector_field`), so a misspelt field can't widen what is deleted. A forget's `layers` outside `events`, `episodes`, `facts`, `beliefs`, `understanding` and `code` is `unknown_layer`. ## See also - [Forget](https://cortexdb.ai/docs/api-reference/forget) · [Erasures](https://cortexdb.ai/docs/api-reference/erasures) · [Retention & WAL](https://cortexdb.ai/docs/operations/retention-wal) - [Change Sets](https://cortexdb.ai/docs/shared-memory/change-sets) · [Backups & DR](https://cortexdb.ai/docs/enterprise/backups-dr) ========================================================================================== # Governed Memory _Decide what CortexDB learns from your events: derivation policies, recorded decisions, corrections that stay corrected, review before commit and re-derivation._ Source: https://cortexdb.ai/docs/features/governed-memory CortexDB's background enrichment reads the events you write and learns from them: facts, entities, beliefs, episodes. **Governed memory** puts that learning under your rules. You write a **derivation policy** as data, test it on real events, and activate it. From then on every candidate memory the extraction model proposes is judged against the policy, and the verdict is recorded with the rule that decided it. When something wrong is learned anyway, a **correction** removes it and keeps it from coming back. Your logic enters as data, never as code inside CortexDB. Work that needs your own code runs on your compute, reading a [change feed](https://cortexdb.ai/docs/api-reference/derivation-feed) and writing its results back. > **Note: Experimental** Every governed-memory route answers with `X-Cortex-Stability: experimental`. Check `GET /v1/admin/version` for the route's capability before you call it: a server without it answers `404`, which reads like "not found". Most routes need data format 11; a server held at format 10 (`CORTEX_FORMAT_CEILING=10`) answers `503 FORMAT_UPGRADE_PENDING` on them ([Upgrading](https://cortexdb.ai/docs/self-hosting/upgrading#from-014x-to-015x)). ## Without a policy, nothing changes A deployment that sets no derivation policy, writes no subject settings and makes no correction learns and answers with every stage on. Provenance is stored on every fact enrichment derives, and served only when a read asks for it (`include=derivation`). ## How a candidate memory is judged 1. **An event is written.** The policy decides first whether enrichment reads it at all: its `mode` (`off`, `explicit`, `review`, `automatic`), its `stages`, and its `sources` rules (roles, actors, labels, intents). Detectors can mask sensitive values before the model sees the text, or skip the event. 2. **The extraction model proposes candidates.** The policy's instructions and examples steer what it looks for. 3. **The deny rules run first.** Topics, detectors and grounding rules judge each candidate before anything else sees it. Denied content is never stored, never embedded and never logged. Only the rule's id and a count are kept. 4. **The routing rules run last.** Writer rules (who may set a field), cardinality and conflict rules, and review rules decide whether a candidate is stored, held for review, or rejected. 5. **The verdict is recorded.** Every accepted fact carries how it was made: the rule, the policy's hash, the models and the prompt version. `GET /v1/derivation/decisions` answers what became of one event. ## What is exact, and what is a model's judgment | Control | How it decides | |---|---| | Detectors (payment cards, IBANs, national ids, secrets, contact details, precise locations) | Exact. Checksummed formats are verified, not guessed | | Stages, sources, grounding, writer rules, modes | Exact. They read the event's own fields and the candidate's claim | | Topics (the 20-category sensitive-topic taxonomy and your own topics) | **Model-judged.** The extraction model labels each candidate's topic, so a denied topic can leak when the model labels a candidate otherwise | Measure a topic policy with the [test sandbox](https://cortexdb.ai/docs/api-reference/derivation-policy#test-a-draft) before you rely on it: it shows each candidate's verdict on your own events, and how many candidates had no topic label. ## The controls | You want to | Use | Page | |---|---|---| | Set what may be learned, from which sources, about which topics | A derivation policy, staged through a change set | [Derivation Policies](https://cortexdb.ai/docs/api-reference/derivation-policy) | | Try a policy before activating it | `POST /v1/derivation/policy/test` | [Derivation Policies](https://cortexdb.ai/docs/api-reference/derivation-policy#test-a-draft) | | Let a user turn memory off, deny a topic, or give a consent | Subject settings, `PUT /v1/derivation/settings` | [Derivation Policies](https://cortexdb.ai/docs/api-reference/derivation-policy#subject-settings) | | Fix a wrong memory, and keep it fixed | `POST /v1/corrections`: reject, replace, pin, confirm, undo | [Corrections](https://cortexdb.ai/docs/api-reference/corrections) | | Approve memories before they are stored | A policy's `review` rules and the review queue | [Review](https://cortexdb.ai/docs/api-reference/review) | | Apply a changed policy to what was learned before | `regate` (free) or `reextract` (priced, capped) | [Re-derivation](https://cortexdb.ai/docs/api-reference/derivation-rederive) | | See why a fact exists | `include=derivation` and `GET /v1/derivation/decisions` | [Facts](https://cortexdb.ai/docs/api-reference/facts), [Derivation status](https://cortexdb.ai/docs/api-reference/derivation-status) | | Derive on your own compute | The change feed, `derived_by`, declared episodes | [Change Feed](https://cortexdb.ai/docs/api-reference/derivation-feed) | | Show a person what is known about them | `GET /v1/memory/about` | [Memory About](https://cortexdb.ai/docs/api-reference/memory-about) | | Report what was derived over a period | `GET /v1/derivation/report` | [Re-derivation](https://cortexdb.ai/docs/api-reference/derivation-rederive#the-report) | ## Guarantees - **Policies are layered.** Restrictions accumulate down the scope tree and along the org chart: a child can only tighten what an ancestor sets, and a staged child that would widen it is refused (`422 DERIVATION_POLICY_WIDENS`). Steering (instructions, examples, models, conflict rules) takes the nearest scope's value. Nothing widens what the server's own settings allow. - **A policy changes only through a change set**, with a preview of each scope's policy before and after, so it is reviewed and approved like an access change. - **Corrections converge.** A rejected memory stays rejected through re-enrichment, rebuilds, failovers and scope moves, on every replica, whatever order the replicas learn in. - **Held candidates are invisible.** A candidate held for review is in no store and no index: no recall, answer or read sees it until it is approved. - **Erasure reaches all of it.** Erasing an event erases what was learned from it, and the corrections, held candidates, review decisions, declared episodes and policy examples that cite it. A person's erasure also erases the corrections about that person. - **Spend is bounded.** A policy's daily budget defers its extraction to the next UTC midnight once spent; a policy test and a re-extraction run under caps you set. ## Which duties the controls help with CortexDB provides controls; whether a deployment meets a law depends on how it uses them. The controls map to common duties like this: | Duty | Controls that help | |---|---| | Data minimization, purpose limitation | `mode: explicit`, stages, source rules, topic and detector denials | | Consent for sensitive categories (for example GDPR Article 9, Washington's consumer health data) | `deny_unless_consent` topics and a subject's recorded consents, audited as `derivation_consent` | | A user's right to limit sensitive data (California's "limit the use") | `limit_spi` in subject settings | | Objection, and turning memory off | `objection` and `mode: off` in subject settings | | Rectification | Corrections (`replace`, `reject`) that stay applied | | Access and portability requests | `GET /v1/memory/about`, the export | | Erasure | Erasure reaches every governed record; receipts name the feed consumers that may hold a copy | | Risk assessments, answering a regulator | `GET /v1/derivation/report`, the audit trail | | New York's General Business Law Article 48 (users not established as adults) | The opt-in read-time [use rule](https://cortexdb.ai/docs/api-reference/derivation-policy#read-time-use-rules); CortexDB verifies no age | ## Getting started 1. Read the templates: `GET /v1/derivation/templates` (`consumer@1`, `minimal@1`, `enterprise@1`, `minor@1`, `health_app@1`). 2. Test one on your events: `POST /v1/derivation/policy/test` with the template's body as the draft. 3. Stage it at your application's scope in a change set, preview it, and activate it. 4. Watch `GET /v1/derivation/status?scope=…`: its `governance` block counts what was learned under an older policy. Run a `regate` dry run to see what the new policy would retire. 5. Give users a way to correct what was learned: `POST /v1/corrections`. ========================================================================================== # Voice Mode _Run CortexDB as the memory of a live voice agent with one setting at install, a built-in embedding model, a brief at call start and in-call recall from the caller's memories held for the call._ Source: https://cortexdb.ai/docs/features/voice-mode **Voice mode** sets up CortexDB as the memory engine of a live voice agent. It is one setting chosen at install. With it on, CortexDB: - **embeds in the server process** with a model the release ships, so recall makes no call to an embedding API and no memory text leaves the machine to be embedded; - **serves voice turns on a short read path:** a recall marked `profile: "voice"` skips the stages a live turn cannot wait for; - **holds each caller's memories in memory for the call:** starting a call session returns a brief of who the caller is and what happened before, and the call's recalls are then served from that caller's memories held for the call. Erasure, forget, the access rules and tenant isolation hold exactly as in a standard deployment: a recall that starts after a removal never serves the removed memory. ### Measured Our own measurements, on one machine: an AWS m7i.4xlarge (Intel Xeon Platinum 8488C, 16 vCPU), the server pinned to 6 cores and their hyperthreads, the default model in process, latency measured at the client over loopback, one request at a time. | | p50 | p95 | p99 | |---|---:|---:|---:| | In-call recall, a caller with about 500 memories | 1.43 ms | 1.68 ms | 1.81 ms | | Call start (the brief) | 28 ms | 37 ms | 39 ms | | A shared 100,000-document scope held in memory, vector search only | 2.1 to 2.2 ms | 2.5 ms | 2.7 ms | | The same, hybrid search (the default) | 2.6 to 2.7 ms | 3.1 to 3.2 ms | 3.3 to 3.5 ms | On that 100,000-document scope, the first query after a restart took 4.5 ms with vector search only and 6.8 ms hybrid. Ranges are the spread of two runs. Under load on the same machine, 6 cores served 500 voice questions a second with 99 in 100 answered in under 6 ms and no errors. Your numbers depend on your hardware, your data and the network between your agent and CortexDB. > **Note: Experimental** Voice mode is experimental. Self-hosted CortexDB comes from the [customer portal](https://customer.cortexdb.ai), with a license ([talk to us](https://cortexdb.ai/contact) to get one). The call-session routes answer with `X-Cortex-Stability: experimental`. Check `GET /v1/admin/version` before you rely on them: `recall_profile_voice_v1` (the voice read path, served by every server, in voice mode or not) and `voice_sessions_v1` (call sessions, listed only by a server in voice mode). ## Turning it on Pick one of these at install. Settings you set yourself always win over what the profile sets. | Where | How | |---|---| | Environment | `CORTEX_PROFILE=voice`, in the container's environment, a systemd `EnvironmentFile` or Compose | | Command line | `cortexdb --profile voice 3141 /data` (or `--profile=voice`) | | Console | **Settings › Deployment profile › Voice**, applied at the next start. Like every console setting, it wins over the environment and the command line. | | Cluster | `[engine] profile = "voice"` on every data node. All data nodes must carry the same profile. | Leave it unset for a standard deployment. Any value other than `voice` stops the server at start with `VOICE_PROFILE_CONFIG`. When the server is up, `GET /v1/admin/ready` answers `200` once the model has loaded and the node can serve its first voice turn. Its `local_embedding` check names the model in use. `cortexdb voice status` and the console's **System › Voice mode** page report the profile, the model, readiness, the call sessions and the pinned scopes; the console page also runs a latency check from your browser. ### What the profile changes - **Embedding moves in process** (`CORTEX_EMBEDDING_PROVIDER=local`), with the [default model](#choosing-the-model). No embedding API key is needed. - **Capacity is set for many short reads:** more concurrent recalls, and background indexing kept to a share of the CPUs so queries keep theirs. - **Search indexes are opened at start**, not on first use, so the first call after a start is not the slow one. Unchanged: the answer model, enrichment (off on a fresh install, as always), the vector quantization, the memory limits and the authorization setup. Voice agents call `/v1/recall` during a turn, never `/v1/answer`. The profile cannot set `TOKIO_WORKER_THREADS`, because the runtime starts before the profile is read. Set it in the server's environment, and pin the server's cores with the container's cpuset, so the runtime stays off the cores the embedding model uses. Every value the profile set is printed at start in the `config_lint` dump (`profile:voice`). ### What stops a start, and what it warns about The server refuses to start, naming the cause, when: - the data folder was written with **another embedding model or provider**: see [Moving an existing store to voice mode](#moving-an-existing-store-to-voice-mode); - the model does not load (a missing or altered model file), or the chosen model cannot run correctly on this CPU ([below](#choosing-the-model)); - a remote embedding provider is configured. Set `CORTEX_VOICE_REMOTE_EMBEDDING=accept` to run voice mode with it anyway; every new query then waits for the provider. It warns, without stopping, when a configured feature does not apply to voice turns: a reranker or the entity graph (voice recalls skip both), or a transformer model on a CPU too small or without the instructions it needs. ## Choosing the model The release ships two multilingual models with the server, in the image and in the release tarballs. Nothing is downloaded at run time. | Model | Choose it for | Set | |---|---|---| | `potion-multilingual-128M` | The default. A static model: very light on CPU and memory, the same results on every CPU. | nothing (the profile's default) | | `granite-embedding-107m-multilingual` | Better retrieval on Hindi and romanised Hinglish, for more CPU per query. | `CORTEX_LOCAL_EMBEDDING_MODEL=granite-embedding-107m-multilingual` | `granite-embedding-107m-multilingual` needs an Arm CPU or an x86 CPU with VNNI or AMX (Intel Cascade Lake or later, AMD Zen 4 or later). On older x86 CPUs the server refuses it; use the default. Both models understand many languages. In our tests with a synthetic voice, questions spoken over phone-quality audio were found as well as typed ones. For Hindi, choose `granite-embedding-107m-multilingual`. **The model is part of the data folder's identity.** A folder is tied to the model it was first written with. Changing the model later is a [migration](#moving-an-existing-store-to-voice-mode), not a setting change. ## The call flow A call has four steps. The examples use the Python SDK (`cortexdbai`); the TypeScript SDK has the same calls in camelCase, and the [Sessions](https://cortexdb.ai/docs/api-reference/sessions) reference has the HTTP routes. ```python from cortexdb import V1Client c = V1Client(api_url="https://cortexdb.internal:3141", actor="user:voice-agent", bearer=TOKEN) caller, call = "ws:acme/caller:9f2c1e", "call_01JF8M2Q7R" # 1. Start: the brief, before the first word started = c.sessions.start(caller, call, query="billing question") system_context = started["brief"]["context_block"] # 2. Each turn: recall on the voice path pack = c.recall(caller, query="what did I order last time", profile="voice", session=call) # 3. Write what the caller said, tagged with the call c.experience(caller, text="Change my delivery address to Pune.", wait="captured", labels=[f"session:{call}"]) # 4. End c.sessions.end(caller, call) ``` 1. **Start the session** when the call connects (`POST /v1/sessions`). The answer carries the **brief**: the caller's current values where enrichment derives them, their most relevant memories for the reason of the call (`query`) and their newest ones, rendered as one `context_block` within a token budget (400 by default). It also says whether the caller has called before (`prior_sessions`, `last_session_at`, `no_prior_history`). The brief makes no model call, and a `deadline_ms` (300 by default) caps how long it may take: past it you get what is ready, marked `partial`. Meanwhile CortexDB loads the caller's memories for the call. 2. **Recall each turn** with `profile: "voice"` and the call's `session`. A voice recall reads the caller's own scope (`granular`), returns events unless `include` asks for more, and skips query expansion, reranking and the entity graph. Optional `alpha`, from 0.0 to 1.0, weighs meaning (vector search) against exact words (keyword search); leave it out for the balanced default. 3. **Write each turn** with `/v1/experience`, labelled `session:`. With `wait=captured` a write joins the call's memories at once, so the next turn's recall finds it. 4. **End the session** when the call ends (`POST /v1/sessions/{session}/end`). Where enrichment is on, the call's events are enriched afterwards, as any events are. A session is its caller's own: another principal naming the same call id gets a session of its own, and cannot see or end yours. Sessions live in the serving node's memory only. After a restart the next voice recall naming the session opens it again, and recalls are answered in the meantime. ### Rules for the agent - **Fail open.** A slow or failed start must never block a call, and a slow or failed recall must never block a turn. Use a short timeout of your own, then answer without memory for that turn. Treat any session error as "no memories held for this call" and carry on: recalls still work without a session. - **Expect `429 RECALL_OVERLOADED`.** A voice recall waits only briefly for capacity, then says so. It is retriable; answer this turn without memory. - **Look up early.** Start a voice recall on the words heard so far (the speech-to-text partial transcript), then recall again on the full sentence. In our tests the best match had usually been found already, so the lookup is done before the caller finishes speaking. - **One memory slot.** Put the brief in the context once, and replace one memory block each turn rather than appending a new one per turn. - **Memory is content, not instructions.** Put recalled text in a block marked as memory, never in a trusted system instruction. - **Redact before you write.** Remove card numbers and other secrets a caller reads out loud before the write. - **Co-locate** CortexDB with the voice agent: the same host, or at least the same zone. ## Integrations Voice mode is plain HTTP, so it fits any voice stack. Where each step plugs in: | Platform | Start (brief) | Each turn (recall) | Writes | |---|---|---|---| | **Pipecat** | At pipeline start; put the brief in the system or developer message | A frame processor after the user context aggregator, before the LLM, replacing one memory message | After each new turn, in the background | | **LiveKit Agents** | In the entrypoint before connecting, keyed from the SIP participant or job metadata; put the brief in the initial instructions | When the user's turn completes; change the turn context only when the recall adds something | After each turn, in the background; end the session on disconnect | | **Vapi** | The `assistant-request` webhook, returning the brief as assistant variables | A custom knowledge-base endpoint that returns the recall as documents | The end-of-call report, written as one batch | | **Retell** | The inbound call webhook, returning the brief as dynamic variables | A custom function | The post-call webhook | | **ElevenLabs** | The conversation-initiation webhook, returning the brief as dynamic variables | A server tool | The post-call webhook | The hosted platforms call your endpoints over the network and give webhooks a fixed time to answer, so keep CortexDB close to the service that answers them, and fail open as above. ## Limits - **Sessions.** A node holds up to 10,000 sessions (`CORTEX_SESSION_MAX_SESSIONS`), a tenant a quarter of them and a principal a tenth. A start past a limit still returns its brief, with `working_set.state: "refused"` and a `session_not_held` warning; that call's recalls are answered from the index as usual. - **Memory.** All the memories held for calls together stay within a budget (`CORTEX_SESSION_MAX_BYTES`, a tenth of the memory limit by default, at most 8 GiB), and one call takes at most a quarter of it. A caller with more than 20,000 stored events (`CORTEX_SESSION_MAX_EVENTS`) is served from the index. While memory is high, no new caller's memories are loaded. - **Idle sessions** end after 900 seconds without a recall (`idle_timeout_s` per session, from 30 to 14,400). - **A voice recall reads one scope.** Filters, temporal fields, extra scopes, mounts and other multi-scope reads are answered by the standard path. - **Shared knowledge.** Scopes listed in `CORTEX_VOICE_PINNED_SCOPES` (for an agent's shared knowledge base) are loaded at start and kept. - **Bulk imports share the CPU.** A voice recall served from the index competes with a running bulk import: on our test machine its p99 went from 3.3 ms to 8.1 ms while one ran. Recalls during a call, served from the caller's memories held for the call, search in memory. Run large imports outside call hours, or on another node. - **Integrations are by HTTP.** There are no framework adapters or hosted-platform examples yet: wire the calls in as the [Integrations](#integrations) table shows. ## Moving an existing store to voice mode A data folder is tied to the embedding model it was first written with. A folder embedded through an API does not switch to voice mode silently: the start is refused with `VOICE_PROFILE_CONFIG`, naming what differs. An **online re-embed** moves it: CortexDB builds the new index beside the live one while the live one keeps serving at full quality, and a restart swaps them. Recall never falls back to keyword search only. 1. **Estimate.** A dry run (the default) answers what the move would take, without starting it: ```bash curl -X POST localhost:3141/v1/admin/reembed \ -H 'content-type: application/json' \ -d '{"to": {"provider": "local", "model": "potion-multilingual-128M"}}' ``` The answer names the current and target models, the rows to embed, an estimate of time, disk, memory and cost (`0` for a built-in model), the settings to restart with (`restart_with`) and any `blockers` that would stop the job. 2. **Start** the same request with `"dry_run": false` (`202`). The job builds the new index in the background; recall keeps using the current one, and new writes are added to both. 3. **Follow it** with `GET /v1/admin/reembed`: `progress`, `rate_per_s` and `eta_s`. When `state` is `ready`, the new index is complete and kept current. 4. **Restart with the target configured:** `CORTEX_PROFILE=voice` (or the console's Deployment profile), or exactly the settings `restart_with` names. That restart swaps the index (`swapped`). - **Changed your mind?** `POST /v1/admin/reembed/cancel` while the job is `building` or `ready` deletes the new index and leaves everything as it was. - **Keeping the old index:** start with `"retain_old_index": true` to keep it after the swap, and delete it later with `POST /v1/admin/reembed/cleanup`. - **Restarting too early:** a start with the target configured while the job is not yet `ready` is refused (`REEMBED_NOT_READY`), naming the job's progress. Restart on the current settings, or cancel the job. - **The console** offers the same move (**Move this store to voice mode**), also when you change the deployment profile or the embedding model: once a job is `ready`, saving the change schedules the swap for the next restart. The CLI (`cortexdb reembed`) and both SDKs drive the same job. - The same flow moves a store between the two built-in models, or back to an API provider (a remote model's key comes from the server's own settings, never from the request). The [admin reference](https://cortexdb.ai/docs/api-reference/admin#online-re-embed) has every field and code. **Measured:** a store of 467,123 events (1,021,568 vectors from a 1,536-dimension API model) moved to the default built-in model in 342 s to `ready`, with the job on its default 3 threads and no calls to an embedding API; the swap restart was ready in 28 s with every row present. Measured on one AWS m7i.4xlarge (16 vCPU Intel Xeon Platinum 8488C, server on 12 vCPUs), November 2026. Your time depends on your hardware and the size of your store. While a re-embed to the Granite model ran on that store, the p99 of a recall during a call went from 2.62 ms to 2.99 ms, so calls can go on during the move. - **Clusters** move by copying: export from the old cluster and import into a new one whose data nodes all carry `[engine] profile = "voice"`. The online re-embed runs on a single node only. - **Going back to an older release:** a folder in voice mode opens only on a release that has voice mode. Move it back to an API provider first. ## See also - [Sessions](https://cortexdb.ai/docs/api-reference/sessions): the call routes - [Recall](https://cortexdb.ai/docs/api-reference/recall#voice-turns-profile-voice): `profile`, `alpha` and `server_timing` - [Error codes](https://cortexdb.ai/docs/api-reference/errors) ========================================================================================== # Code Intelligence Plane _Index a repository into CortexDB and retrieve task-scoped, cited code context._ Source: https://cortexdb.ai/docs/features/code-plane The **Code Intelligence Plane** indexes a code repository into CortexDB and answers "what code is relevant to this task?" with **cited snippets**: each pinned to `repo:path@#Lx-Ly`. It's a separate surface from the memory layers, gated behind a flag and its own `/v1/code/*` routes. > **Note: Off by default; enable with CORTEX_CODE_PLANE=1** The code plane is disabled unless `CORTEX_CODE_PLANE=1` is set (or **Code memory** is switched on in the [Admin Console](https://cortexdb.ai/docs/operations/admin-console) Features page, which takes effect on restart). With the flag off, every `/v1/code/*` route returns **`503 CODE_PLANE_DISABLED`**. Most `/v1/code/*` routes are **not** in `/v1/openapi.json`: they're a separate surface; the spec does list `POST/GET /v1/code/repos`, `GET/DELETE /v1/code/repos/{name}` (delete de-registers **and frees the bytes**), `POST /v1/code/certify` (a certified answer over compiler-tier SCIP evidence only), `POST /v1/code/import/scip` and `POST /v1/code/import/coverage` (lcov). The full route reference ships inside the server image as `/opt/cortexdb/docs/CODE_PLANE.md`. The CLI mirrors the main routes as `cortexdb code add/status/remove/import-scip/import-coverage`. ## Enable and mount a repository The server can only index paths it can read, so mount the repo into the container, and tell the server which directories repositories may be registered from: ```bash docker run -d --name cortexdb \ -p 127.0.0.1:3141:3141 \ -v cortexdb-data:/data \ -v /host/path/to/myrepo:/repos/myrepo:ro \ -e CORTEX_CODE_PLANE=1 \ -e CORTEX_CODE_REPO_ROOTS=/repos \ -e OPENAI_API_KEY=$OPENAI_API_KEY \ -e CORTEX_LICENSE \ cortexdb/cortexdb:v0.16.1 ``` `CORTEX_CODE_REPO_ROOTS` is recommended rather than required: without it the server logs a startup warning that any readable directory may be registered. See [Where repositories may live](#where-repositories-may-live). ## Register a repository ```bash curl -X POST http://localhost:3141/v1/code/repos \ -H "Authorization: Bearer $CORTEXDB_TOKEN" \ -H "X-Cortex-Actor: $CORTEXDB_ACTOR" \ -H "Content-Type: application/json" \ -d '{ "name": "myrepo", "path": "/repos/myrepo", "scope": "org:acme/team:eng" }' ``` Returns `201` with parse statistics (files parsed, symbols extracted) and the **bound scope**. The `path` is the **in-container** path you mounted, not a host path. `scope` names the parent the repository is bound under; the server appends `repo:-<12 hex>`, where the leaf comes from the repository **name** (so two names registered from one checkout bind to two different scopes). Omit `scope` to bind under the tenant root. ## Retrieve task-scoped context ```bash curl -X POST http://localhost:3141/v1/code/context \ -H "Authorization: Bearer $CORTEXDB_TOKEN" \ -H "X-Cortex-Actor: $CORTEXDB_ACTOR" \ -H "Content-Type: application/json" \ -d '{ "repo": "myrepo", "task": "where is the recall pack assembled?", "token_budget": 4000 }' ``` The response is a set of **cited snippets** with a reason code explaining why each was selected, plus `snapshot` and `generation`. Feed that context straight into a coding agent's prompt. > **Note: What a citation hash is (and isn't)** A citation looks like `hiredis:net.c@f0a1c85552da9fe4#L458-L485`. The hash after `@` is a hash of the **snippet** it cites, so you can verify a citation against its text. It is **not** a git commit, blob or tree id: `git show` won't find it. The commit the index was built from is the response's separate `snapshot` field (the checkout's `HEAD` when it was last indexed, the same value as `git rev-parse HEAD`). The index follows the working tree, uncommitted edits included, so a snippet can come from a file edited since that commit. ## Where repositories may live The requested `path` is resolved first (`..` segments and symlinked directories become their real target) and then checked. Refusals are `422 REPO_PATH_NOT_ALLOWED` with a `details.reason`: | Path | `reason` | |---|---| | `/` | `filesystem_root` | | `/proc`, `/proc/self`, `/sys`, `/etc` (also `/dev`, `/run`, `/boot`) | `system_path` | | the server's data directory or anything inside it: directly, via `/tmp/../data`, or via a symlink to it | `data_directory` | | outside `CORTEX_CODE_REPO_ROOTS` when it is set, including a symlink inside a root that points out of it | `outside_allowed_roots` | A relative path is refused (`422 REGISTRATION_FAILED` without the roots variable). With `CORTEX_CODE_REPO_ROOTS` set (a `:`-separated list on Linux), the resolved path must lie inside one of the roots; set but naming no existing directory refuses every registration (per the server reference). Registration never follows the server into its own storage. ## What gets indexed - **A git checkout** indexes every file `.gitignore` doesn't exclude, minus built-in vendor and generated skips (`node_modules/`, `target/`, `dist/`, …). - **Any other directory** indexes only files with a recognised source extension and **skips hidden files and directories** (a leading `.`): a plain folder holding `src/add.c`, `.env`, `.env.example` and `server.pem` indexes only `src/add.c`. To index more, `git init` it and describe it with a `.gitignore`. - **Credential files are never read, in either mode** (the full list is in the server's `CODE_PLANE.md`): dotenv files (`.env`, `.env.*`, `*.env`, except the templates `.env.example` / `.env.sample` / `.env.template`, which are indexed in a git checkout), private keys and key stores (`*.pem`, `*.key`, `*.p12`, `id_rsa`, …), credential files (`.netrc`, `.npmrc`, `.git-credentials`, `credentials*.json`, …), Terraform state, and everything under `.ssh/`, `.aws/`, `.kube/` and similar. - **A secret embedded in a source file is not detected**: an API key hard-coded in `config.py` is indexed like the rest of the file. Keep secrets out of source. - **Symbolic links inside the checkout are not followed**. The server reference adds that files over 4 MiB and binary files are skipped. ## Who can read a repository A repository is **bound to a scope** and every read or change is authorized against it: the caller needs the capability, a seat on that scope's roster, and (if the token carries `scopes`) confinement that reaches it. For example, with two agent tokens minted by the operator (on `dev_local` or `on_prem_enterprise`): team A registered the repository under `org:dev/team:a`, which made it the owner of that scope (the first registrant claims an unregistered team scope); team B has no seat there: | Team B's call on team A's repository | Result | |---|---| | `GET /v1/code/repos` | the repository is **omitted** from the listing | | `POST /v1/code/context`, `POST /v1/code/graph/query`, `GET /v1/code/repos/{name}` | `404 REPO_NOT_FOUND` | | `DELETE /v1/code/repos/{name}` | `404 REPO_NOT_FOUND` (team A's repository survives) | | `POST /v1/code/repos` with `scope: org:dev/team:a` | `403 POLICY_DENIED` | The `404` never confirms that a name exists. Another tenant's repository is equally invisible. The static operator key (and no-auth mode) skips per-scope rosters and sees every repository in its tenant; under the `deny` operator mode (the default on `cloud_shared_saas`) its code reads need a [break-glass header](https://cortexdb.ai/docs/shared-memory/operator-modes). ## The call graph and SCIP `POST /v1/code/graph/query` walks `calls` edges from exact indexed roots (`direction`: `outgoing`, `incoming` or `both`). Out of the box the edges come from parsing (`tier: syntax`, `status: Unresolved`, matched by name). On C and C++ code: - C functions returning pointers carry their outgoing calls, and callers are attributed to the calling function, not to the file. - C++ members can be named by their **qualified** name: `buffered_file::close` and `file::close` resolve separately. A bare name (`close`) returns **every** identity carrying it: ambiguity is returned, never collapsed. - Calls inside gtest `TEST(...)` bodies are attributed to the test, so impact analysis sees tests that call a function. For exact cross-references, import a compiler-tier index. For C/C++ that means running [scip-clang](https://github.com/sourcegraph/scip-clang) over a `compile_commands.json`, then: ```bash curl -X POST "http://localhost:3141/v1/code/import/scip?repo=myrepo" \ -H "Authorization: Bearer $CORTEXDB_TOKEN" \ -H "X-Cortex-Actor: $CORTEXDB_ACTOR" \ -H "Content-Type: application/octet-stream" \ --data-binary @index.scip ``` The response reports `accepted`, `rejected` and `derived_calls`; afterwards the graph carries `tier: compiler, status: Exact` edges beside the syntax ones (every answer spells a tier in lower case). `POST /v1/code/certify` answers `count-call-sites` or `list-implementations` **only** from compiler-tier evidence. It covers every code file in the symbol's language family, so if parts of the repository were not compiled (examples, optional adapters), narrow it with `paths` (repo-relative prefixes): ```json { "repo": "hiredis", "question": "count-call-sites", "symbol": "cxx . . $ redisConnectWithOptions(45dbf3ccfa7760d5).", "paths": ["hiredis.c", "async.c", "test.c"] } ``` The answer is exact for the code **as compiled**: calls inside a disabled `#ifdef` don't exist for the compiler and aren't counted. Without full coverage the response is `incomplete` and lists the files that lack compiler-tier evidence; docs, config and scripts in other languages never block it. ## The CLI The [`cortexdb` CLI](https://cortexdb.ai/docs/sdks/cli) wraps the plane under `cortexdb code`: ```bash cortexdb code add # register + index a repo cortexdb code status # list repos and index state cortexdb code remove ``` Run `cortexdb code --help` for the full set (`add`, `remove`, `status`, `import-scip`, `import-coverage`, `export-index`, `import-index`, `pin`, `gc`, `matrix`, `watch`). > **Note: What the plane stores** Registering a repo parses it into symbols and indexes them alongside CortexDB's other indexes in the same data directory, so a [cold backup](https://cortexdb.ai/docs/enterprise/backups-dr) covers the code plane too. Snippets are kept by content hash, and each `context` response names the commit it was built from (`snapshot`). Deleting a repository frees its directory; while a repository is registered, content of files removed from it may stay on disk until garbage collection but is never served. ========================================================================================== # Media & Blob Ingestion _Store documents, images, audio, and video as blobs together with their text, so recall can search them._ Source: https://cortexdb.ai/docs/features/media-ingestion CortexDB stores binary content (PDFs and other documents, images, audio, video) as **blobs**. Recall searches **text**, so write each file together with its text: upload the bytes, then write an experience that references the blob and carries the text. | What you write | What recall searches | |---|---| | A text blob (`text/plain`, Markdown, JSON, …) | The file's text, as soon as the write returns. The server decodes it into the event's text | | Any blob plus a `transcript` | Your transcript, as soon as the write returns. The server uses it and skips its own processor | Either way the event keeps its link to the file in `source_blob_ids`, and erasing the event also deletes the blob once no other event uses it (see [Forget](https://cortexdb.ai/docs/api-reference/forget)). ## 1. Upload the bytes ```bash curl -X POST http://localhost:3141/v1/blobs \ -H "Authorization: Bearer $CORTEXDB_TOKEN" \ -H "X-Cortex-Actor: $CORTEXDB_ACTOR" \ -H "Content-Type: application/pdf" \ --data-binary @report.pdf # → { "blob_id": "blob_01HX...", "size_bytes": 48211, "content_type": "application/pdf", "sha256": "..." } ``` The body **is** the file (any `Content-Type` is accepted as raw bytes). The size cap is **32 MiB**: larger uploads return `413`. See [Blobs API](https://cortexdb.ai/docs/api-reference/blobs) for the full shape. ## 2. Get the text - **Documents (PDF, docx, xlsx, …):** run them through a text extractor. If you run the Apache Tika sidecar, ask it directly. Tika usually has no host port, so run `curl` on its Docker network (replace `cortexnet` with yours): ```bash docker run --rm --network cortexnet -v "$PWD:/w" curlimages/curl -s \ -T /w/report.pdf -H "Accept: text/plain" http://tika:9998/tika > report.txt ``` - **Images:** OCR output, a caption, or alt text. - **Audio and video:** a transcript you already have, or one from your ASR service. - **Plain-text files:** nothing to do. Upload them with `Content-Type: text/plain; charset=utf-8` and skip the `transcript` in step 3. ## 3. Reference the blob with its text ```bash curl -X POST "http://localhost:3141/v1/experience?wait=indexed" \ -H "Authorization: Bearer $CORTEXDB_TOKEN" \ -H "X-Cortex-Actor: $CORTEXDB_ACTOR" \ -H "Content-Type: application/json" \ -d '{ "scope": "org:acme/user:alice", "modality": "document", "content": { "kind": "blob_ref", "blob_id": "blob_01HX...", "transcript": "The Kestrel contract renews on 1 February." }, "context": { "observed_at": "2026-05-15T10:42:00Z" } }' ``` The stored event reads back as `content.kind: "text"` with your transcript as its text, and recall finds it as soon as the write returns. With the Python SDK, pass `transcript=` next to `blob_id=`: ```python blob = cx.upload_blob(open("report.pdf", "rb").read(), content_type="application/pdf") cx.experience("org:acme/user:alice", blob_id=blob["blob_id"], transcript=open("report.txt").read(), wait="indexed") ``` ## Server-side processors A blob written **without** a transcript is handed to the matching content processor in the background, once processors are configured (`CORTEX_IMAGE_*`, `CORTEX_AUDIO_*`, `CORTEX_DOCUMENT_*`, `CORTEX_VIDEO_*`; see [Storage & Cluster](https://cortexdb.ai/docs/operations/storage-cluster)). Until then `/v1/admin/ready` reports `content_processors.configured: []` and blobs are stored without text. | Modality | Processor (once configured) | Needs a key? | |---|---|---| | Document (PDF, docx, …) | Tika / unstructured | No (a Tika sidecar) | | Image | GPT-4o vision | Yes (OpenAI) | | Audio | Whisper | Yes (OpenAI) | | Video | ffmpeg keyframes → image processor | Yes (for the frames) | Processing runs on a separate pipeline: `?wait=indexed` returns once the *event* is indexed, not when processing finishes. The server log shows `content processing complete ... derived_text_len=N` for each blob. It runs even on a content-only instance, since it is not gated behind enrichment (see [Self-hosting defaults](https://cortexdb.ai/docs/self-hosting/defaults)). For text you want recall to find, send it with the blob as in step 3. A supplied `transcript` also skips the processor call, which saves the vision or Whisper cost for images and audio. ## Deleting a blob ```bash curl -X DELETE http://localhost:3141/v1/blobs/blob_01HX... \ -H "Authorization: Bearer $CORTEXDB_TOKEN" -H "X-Cortex-Actor: $CORTEXDB_ACTOR" ``` Blob storage backends (local / S3 / GCS / Azure) are configured under `[blob_store]`: see [Storage & Cluster](https://cortexdb.ai/docs/operations/storage-cluster). ========================================================================================== # Languages & Multilingual Memory _Store memories in any language and script, tag them, and recall across languages: what works, what doesn't, and how to gate it._ Source: https://cortexdb.ai/docs/features/languages CortexDB **never translates** your memories. You store the original text, optionally with hints about its language, script and time zone, and the server keeps both. The original text is what recall returns and what answers cite. The server also tags every event with a language, can use hints on recall, and keeps non-Latin names apart. > **Note: Gate these fields on capabilities, not on the version** Each feature below has a capability name in `GET /v1/admin/version` → `capabilities[]`. A server that doesn't list a capability refuses its request fields with `422 INVALID_BODY`. Check the list once at start-up and only send what it names. | Capability | Adds | |---|---| | `capture_language_v1` | `language`, `scripts[]`, `context.timezone` on captures; language tags on events | | `refers_to_v1` | `context.refers_to[]` on captures; `temporal.refers_during` on recall and answer | | `recall_language_v1` | `language`, `scripts[]` on `/v1/recall` and `/v1/recall/stream` | | `query_variants_v1` | `query_variants[]` on `/v1/recall` and `/v1/recall/stream` | | `temporal_lenient_v1` | `temporal.natural_mode`, `temporal.timezone` | | `blob_text_decode_v1` | Charset-safe decoding of non-UTF-8 text blobs | ## Capture ```json POST /v1/experience?wait=indexed { "scope": "org:acme/team:support", "modality": "text", "content": { "kind": "text", "text": "kal mera dentist appointment hai" }, "language": "hi-Latn", "scripts": ["Latn"], "context": { "observed_at": "2026-09-23T20:30:00Z", "timezone": "Asia/Kolkata" } } ``` - **`language`** is a BCP-47 tag (`hi-Latn`, `ta`, `ar`) and **`scripts[]`** are ISO 15924 codes (at most 8). Values are canonicalized: `HI-latn` is stored as `hi-Latn`, `latn` as `Latn`. - **`context.timezone`** is an exact IANA name. `Asia/Kolkata` and its older alias `Asia/Calcutta` work; `IST`, `+05:30` and `Asia/Mumbai` are refused. - **`context.refers_to[]`** records the dates the memory talks about (local dates or date-times with no offset, with an optional `zone` and `precision`), so recall can favour them later. See [Experience](https://cortexdb.ai/docs/api-reference/experience#language-time-zone-and-referenced-times). - A malformed value in any of these → `422 INVALID_ENVELOPE`. **Every event is classified**, even without hints. Your `language` wins; then a `lang:` label in `context.labels`; then detection from the text. For example: | Text | Stored `language` | `language_source` | |---|---|---| | "कल ऑफिस में मीटिंग है" (Devanagari) | `und-Deva` | `detected` | | "yaar kal office nahi aana hai mujhe" (Hinglish) | `hi-Latn` | `detected` | | any text with `"language": "HI-latn"` | `hi-Latn` | `hint` | | any text with label `lang:ta` | `ta` | `label` | | "the meeting is tomorrow" | *(no tag)* | *(none)* | An event that is English by default stores no tag, so it reads back unchanged; an explicit `"language": "en"` is stored. Tags come back as `language`, `scripts` and `language_source` on `GET /v1/events/{id}`, on recall `layers.events` items and in exports. The hints are **not part of the write identity**. Retrying with the same `idempotency_key` and body but different hints replays the first write (its hints win) and adds a `conflicting_hint_on_replay` warning to the response. An erasure clears `context.timezone` and `context.refers_to`; the language tag stays. ## Recall ### Language and script hints `/v1/recall` and `/v1/recall/stream` take `language` and `scripts[]`, validated like the capture hints (a malformed value → `422 INVALID_BODY` with `details.field`). They choose the **query stoplist** for keyword search: English words are stripped with no hint or an `en`, `hi` or `hi-Latn` hint, and nothing is stripped for other languages or a `scripts` hint without `Latn`. The query text alone never changes the stoplist. ### Query variants: bridge scripts yourself ```json POST /v1/recall { "scope": "org:acme/team:support", "query": "Does Priya like tea?", "query_variants": [ { "text": "प्रिया चाय पसंद", "language": "hi", "script": "Deva" } ] } ``` - Up to **4** variants of `{ text, language?, script? }`, each at most **4,096 bytes**. More entries, an empty `text` or a longer one → `422 INVALID_BODY` with `details { field, max_items, max_text_bytes }`. A variant that repeats the query or an earlier variant is dropped silently. - Each variant runs its own vector and keyword search, merged with the question's results (question first), and reranking still scores against the question only. With `diagnostics: "full"`, each returned item shows its rank per variant and `matched_via` (for example `["primary", "variant:0"]`). - Two variants add about 100 ms at p50, in one embedding call. > **Note: Add a variant in the memories' script** Recall doesn't translate the question. For a Latin-script question over memories written in Devanagari (or another script), send a variant in the memories' script, as above, for the best results. ### Entity grounding keeps non-English packs When a question names an entity that no retrieved memory mentions, recall normally empties the pack rather than return memories about someone else. That still happens for English questions over an all-English scope. The pack is **kept, with a warning**, when the question or a variant has a non-English hint, a retrieved memory is in a script the question lacks, or the scope holds at least two non-English memories: ```json "warnings": ["entity_grounding_advisory: query entities [\"zorblax\"] not found in retrieved memories; pack kept (script_mismatch) - results may be about a different entity"] ``` With `diagnostics: "summary"` or `"full"`, `diagnostics.filters_applied` also lists `entity_grounding:advisory:`. ### Local time in the context A non-English event captured with `context.timezone` gets a local-time bracket after its UTC one in `context_block`, so the model reads the day the user meant: ```text [2026-09-23 20:30 UTC] [2026/09/24 (Thu) 02:00 Asia/Kolkata] प्रिया को चाय बहुत पसंद है ``` English events render exactly as before. ## Time phrases and time zones - **`temporal.timezone`** (IANA) makes calendar phrases such as `today`, `yesterday` and `last month` resolve on that zone's calendar; without it they resolve in UTC. `IST` → `422 INVALID_BODY` with `details.field: "temporal.timezone"`. - **`temporal.natural_mode: "lenient"`** drops a phrase the server can't parse instead of failing with `422 UNPARSEABLE_TEMPORAL`, and adds a `temporal_natural_ignored: …` warning; no time filter is applied. - **`temporal.refers_during { from, to, zone? }`** is a boost, not a filter: memories whose `refers_to` (or capture time) falls in the window move to the front; nothing is added or removed. A malformed window → `422 INVALID_BODY`. These work on `/v1/recall` and `/v1/answer`; `/v1/answer` does not return the pack's `warnings[]`. ## Answers `/v1/answer` has no `language` or `scripts` field. It accepts and ignores any field it doesn't know, so sending `language` there changes nothing. Put the hints and variants on a `/v1/recall` call if you need them, and the question in the user's language. ## Names, facts and enrichment of non-Latin text These apply when [enrichment](https://cortexdb.ai/docs/self-hosting/defaults) is on: - **Entity ids keep non-Latin names apart.** A name with any non-ASCII character gets a hashed id: José → `ent_jose-0f66606aa13f1258`, प्रिया → `ent_u-0133576006acc0d5`, so different people in one script never share an id. Ids stored by earlier releases still resolve on reads and forgets. See [Facts](https://cortexdb.ai/docs/api-reference/facts#entity-ids). - **Facts keep the original wording.** Subjects and objects stay in the source script; a non-English fact gets an English `gloss` used only as a search key, never shown in the context or citations. - **`CORTEX_ENRICHMENT_SKIP_NON_EN=1`** (off by default) skips LLM enrichment for text in a non-Latin script; those events stay searchable as raw events. Latin-script Hinglish is always enriched. - `GET /v1/admin/metrics` → `enrichment_multilingual` reports `non_en_script_events_enriched`, `non_en_script_events_skipped`, `triples_rejected` and the `fact_surface` counters. ## Text files in other encodings A text blob in a legacy encoding (Windows-1252, Shift-JIS, UTF-16) must say so on upload (`Content-Type: text/plain; charset=windows-1252`); otherwise a capture that uses it fails with `422 BLOB_TEXT_ENCODING_UNKNOWN` rather than storing garbled text. See [Experience](https://cortexdb.ai/docs/api-reference/experience#text-blobs). ## From the SDKs The Python SDK passes these through: `experience()` takes `language=`, `scripts=`, `timezone=` and `refers_to=`; `recall()` takes `language=`, `scripts=` and `query_variants=`; `capabilities()` returns the list to gate on. See [Python SDK](https://cortexdb.ai/docs/sdks/python#method-index). ========================================================================================== # Across your customers _Questions about all the customers under one parent space: exact counts and lists, one ranked search across customers, and themes with customer counts._ Source: https://cortexdb.ai/docs/features/across-customers For a company whose customers each have their own memory space under one parent (`org:acme/user:c42`, `org:acme/user:c43`, ...), three lanes answer questions about **all** of them. They are experimental and off by default; your admin turns each part on. | Lane | What you get | Model call | |---|---|---| | **Exact counts and lists** | Exact answers to counts, lists, "top" and funnel questions over the labels and kinds on every customer's memories. Not a sample. | None | | **Search across customers** | One ranked search across every customer space the caller may read, with a few memories from each customer. | None (the search model only) | | **Themes across customers** | For "what do customers say about X?": themes, the number of customers behind each, checked examples, and how much was read. | Yes, and it can take up to a minute | Example questions: "Which customers cancelled an order last week?" returns an exact list, or "0 of 240". "Which customers asked about financing in chat?" is a search across customers. "What do customers ask about EMI?" returns themes with customer counts and "read 212 of 212". ## Turn it on | Setting | What it turns on | |---|---| | `CORTEX_COHORT=on` | The exact lane (`POST /v1/cohort/query`, `GET /v1/cohort/vocabulary`) and the `cohort` field on `/v1/answer`. Off, they answer `409 COHORT_DISABLED`. | | `CORTEX_SUBTREE_RECALL=request` | The ranked search (`subtree` on `/v1/recall`) and the themes lane. Counts and lists keep working without it. | Every lane needs `scope.read.descend` on the parent scope, and answers only over the customers the caller may read, deciding each customer's space on its own. It reports nothing about the ones left out. ## Ask for an exact count or list `POST /v1/cohort/query` takes exactly one of a `plan` or a `question`, and calls no model: ```json { "scope": "org:acme", "plan": {"op": "top", "where": {"labels_all": ["etype:view"]}, "group_by": "label:model", "metric": "subjects", "n": 5} } ``` `GET /v1/cohort/vocabulary?scope=org:acme` lists the labels and kinds a plan can use. The answer is exact over the labels and kinds your app saved, so label memories consistently (for example `etype:order_cancelled`) for these questions to work. ## Search across customers Add `subtree` to a recall at the parent scope with the walking view `descend`: ```json { "scope": "org:acme", "view": "descend", "query": "financing and EMI questions", "subtree": {"per_subject": 2, "max_subjects": 40} } ``` Without `subtree`, a recall at a parent scope reads the spaces under it in storage order, not by relevance, and the pack says so. ## Themes across customers Ask `/v1/answer` at the parent scope with a `cohort` field. The same field also routes counts and lists asked in plain words to the exact lane: ```json { "scope": "org:acme", "question": "What do customers ask about EMI?", "cohort": {"naming": "alias", "anchor": "data_end", "max_listed": 50} } ``` For a themes question, CortexDB reads every matching conversation, counts the customers behind each theme, checks examples before citing them, and says how much it read. It calls your answer model on each question, within `CORTEX_COHORT_ANSWER_BUDGET_MS`. ## Check support first These lanes are experimental. Probe a server before you rely on them: a server without them answers an unknown `cohort` field on `/v1/answer` from its ordinary parent-scope pack, so treat an answer without a `cohort` field as "no cohort lanes here", never as a cohort answer. ## See also - [POST /v1/recall](https://cortexdb.ai/docs/api-reference/recall): views, `extra_scopes` and the `descend` view. - [Multi-Tenancy](https://cortexdb.ai/docs/enterprise/multi-tenancy): one space per customer under a parent. ========================================================================================== # Python SDK _Reference for cortexdbai: V1Client, AsyncV1Client, and the typed exception hierarchy._ Source: https://cortexdb.ai/docs/sdks/python The official Python client for CortexDB v1. `V1Client` is the client, and `AsyncV1Client` is its async twin with the same methods: see [Async variant](#async-variant). ```bash pip install cortexdbai ``` Requires Python 3.10+. PyPI package: **`cortexdbai`**. Python module: `cortexdb.v1`. The SDK version is independent of the server version; see [Versioning and SDK compatibility](https://cortexdb.ai/docs/sdks/rest-api#versioning-and-sdk-compatibility). ## Construction ```python from cortexdb.v1 import V1Client client = V1Client( api_url="https://api-v1.cortexdb.ai", actor="user:alice", bearer="v4.public.eyJpc3MiOi...", timeout=30.0, ) ``` | Argument | Default | Notes | |---|---|---| | `api_url` | `http://localhost:3141` | v1 surface URL. Defaults to a local server; pass `https://api-v1.cortexdb.ai` for cloud. | | `actor` | `"user:default"` | Sent as `X-Cortex-Actor`; must match the token's `sub`. | | `bearer` | `None` | PASETO v4 public token: or, self-hosted, the server's `CORTEX_API_KEY` value. Optional only when the server runs with `CORTEX_INSECURE_NO_AUTH=1`. | | `timeout` | 60 s | Per-request timeout. | Use it as a context manager so the underlying `requests.Session` is cleaned up: ```python with V1Client(api_url="...", actor="user:alice", bearer=tok) as client: pack = client.recall(scope="org:acme/user:alice") ``` ## Auth ```python client.whoami() # → { caller, tenant_id, deployment_preset, effective_capabilities, token } client.mint_token( subject="user:alice", scope="org:acme", # the tenant root the token belongs to ttl_seconds=3600, scopes=["scope.read:org:acme/user:alice/*", "scope.write:org:acme/user:alice/*"], # optional: confine it ) # → { "token": "v4.public...", "jti": "jti_...", "expires_at": "2026-05-15T11:42:00Z" } ``` > **Note: whoami key is effective_capabilities** The capability list is returned under `effective_capabilities` (snake_case). `mint_token` accepts `scopes` (plural) and `caps` alongside the singular `scope`. ## Write path ```python client.experience( scope="org:acme/user:alice", text="Acme upgraded to 200 seats.", role="user", observed_at="2026-05-15T10:42:00Z", idempotency_key="alice-chat-001", wait=None, ) ``` > **Note: experience() modality is optional** Pass the content with `text=`, `json_data=`, `transcript=`, `blob_id=`, or `triple=` (plus `role=`). `modality=` (an open-set label) and `source=` are optional keywords: if `modality` is omitted it is taken from `source=`, else defaults to `conversation`. ```python client.experience_bulk( scope="org:acme/user:alice", items=[ {"text": "Acme upgraded to 200 seats.", "role": "user", "observed_at": "2026-05-15T10:42:00Z", "idempotency_key": "k1"}, {"text": "Renewal is due in March.", "role": "user", "observed_at": "2026-05-15T10:43:00Z", "idempotency_key": "k2"}, ], ) ``` > **Note: experience_bulk() takes no ordering= parameter** `experience_bulk(scope, items, *, wait=None)` is the full signature: there is **no `ordering=` keyword**. Items are ingested in list order; encode temporal order in each item's `observed_at`. Each item is a flat dict with exactly one of `text` / `json_data` / `blob_id` / `triple`, plus optional `role`, `observed_at`, `labels`, `idempotency_key`, `modality`, `source` (not a wire envelope). `wait` ∈ `None` | `"accepted"` | `"captured"` | `"indexed"` | `"consolidated"` (`"accepted"` is an explicit alias for the `None` default). With `wait` omitted, a write returns **`captured`** (202) as soon as the WAL append succeeds: it is **not** fully indexed yet; pass `wait="indexed"` to block until BM25 + HNSW have the event. For full envelope shape (subjects, directives, blob refs, triples) see [Experience Envelope](https://cortexdb.ai/docs/concepts/experience-envelope). ## Read path ```python client.recall( scope="org:acme/user:alice", view="holistic", query="What did we decide about Acme?", include=["events", "beliefs", "facts", "episodes"], budgets={"max_tokens": 4000}, temporal={"natural": "last 30 days"}, ) # → StratifiedPack: layers, context_block, provenance, diagnostics, pack_id client.answer( scope="org:acme/user:alice", question="Did Acme renew?", view="holistic", temporal={"natural": "last 30 days"}, ) # → { answer, citations, provenance, diagnostics, pack_id, as_of } ``` > **Note: answer_model is a cloud default** `claude-opus-5-5` is the **cloud** default model. Self-hosted, `/v1/answer` routes through whatever you configure in the answer lane (`CORTEX_ANSWER_*`). An `answer_model=` argument is only echoed in `diagnostics.answer_model`; the configured model answers ([details](https://cortexdb.ai/docs/operations/llm-answer#diagnostics)). `/v1/answer` is disabled on a self-hosted instance until that lane is set. See [Self-hosting defaults](https://cortexdb.ai/docs/self-hosting/defaults). ## Layer reads ```python client.events(scope="org:acme/user:alice", view="local", limit=50) client.episodes(scope="org:acme/user:alice", view="local") client.facts(scope="org:acme/user:alice", subject="ent_acme_corp", predicate="deal_stage") client.beliefs(scope="org:acme/user:alice", view="local") client.belief_why(belief_id="belief_01HX...") client.understanding(scope="org:acme/user:alice", view="local") ``` > **Note: facts() takes as_of= and the other fact filters** `facts(scope, *, view='local', subject=None, predicate=None, limit=None, cursor=None, as_of=None, min_confidence=None, include_superseded=False, include_vectors=False, include=None, at_least=None)` is the full signature. `as_of` (RFC 3339) reads the facts valid then, `min_confidence` keeps those at or above a confidence, and `include_superseded=True` keeps superseded facts too; each page ends with `next_cursor` (or use `pages()`). A claim's values over time are `facts_timeline(subject, predicate, scope=…)`, and one fact by id is `fact(fact_id, scope=…)`. > **Note: Facts / Beliefs need enrichment on self-host** On a content-only self-hosted instance the Facts and Beliefs layers stay **empty**: they are LLM-derived and require enrichment configured. `events`/`episodes`/`recall` work regardless. See [Self-hosting defaults](https://cortexdb.ai/docs/self-hosting/defaults). Trigger an async synthesis pass: ```python client.build_episodes(scope="org:acme/user:alice") client.build_beliefs(scope="org:acme/user:alice") client.synthesize(scope="org:acme/dept:eng", topics=["sales_process"]) ``` > **Note: synthesize() signature** `synthesize(scope, *, topics=None)` is the full signature. ## Forget ```python client.forget( scope="org:acme/user:alice", layers=["beliefs"], predicate="is_likely_to_renew", cascade="derived_only", reason="User retracted speculation", ) ``` > **Note: forget() targets by field** `forget()` takes explicit targeting fields: ``` forget(scope, *, layers=None, about_subject=None, about_entity=None, predicate=None, memory_ids=None, cascade='derived_only', confirm_all=False, reason=None, from_preview_id=None) ``` Target with `predicate=`, `about_subject=`, `about_entity=`, or `memory_ids=[…]`. The audit note goes in **`reason`**. `forget()` takes no idempotency key. To purge specific records, pass their ids: ```python client.forget(scope="org:acme/user:alice", memory_ids=["evt_01HX...", "fact_01HX..."]) ``` If a storage backend fails mid-delete the server returns `502 FORGET_BACKEND_FAILED` rather than reporting success: deletes are idempotent, so retry the same call. For GDPR reference-counted erasure use the `/v1/erasures` family directly: see [Erasures](https://cortexdb.ai/docs/api-reference/erasures). ## Governed memory [Governed memory](https://cortexdb.ai/docs/features/governed-memory) lets an application decide what CortexDB's background enrichment learns from its events, and correct what it learned wrongly. Each method below is on both `V1Client` and `AsyncV1Client` (also exported as `Cortex` and `AsyncCortex`): on the async client you `await` the calls, and `feed_iter` is an async iterator. > **Note: Check the capability first** These methods need a server that lists their capability, and none of them checks for you. Against a server without it, each route answers `404`, which reads like "not found". Before the first call, look the route's capability up in `client.capabilities()` (`GET /v1/admin/version`): `derivation_policy_v1`, `corrections_v1`, `derivation_review_v1`, `derivation_rederive_v1`, `derivation_feed_v1`, `derived_by_v1`, `declared_episodes_v1`, `derivation_use_rules_v1` or `derivation_provenance_v1` (`cortexdb.v1` exports most of them as constants, such as `CORRECTIONS_V1`). They are experimental, and a server held at data format 10 answers `503 FORMAT_UPGRADE_PENDING` on most of these routes. | Area | Methods | |---|---| | Policies and settings (`derivation_policy_v1`) | `derivation_policy(scope)`: the policy in force, where each rule was set, its hash · `derivation_templates()` · `derivation_taxonomy()` · `derivation_policy_test(scope, policy=draft, sample=20, max_cost_usd=0.5)`: a draft run over your own events, writing nothing (its model calls are priced) · `changeset_apply(root, id, [derive_record(scope, body)])` stages, previews and activates a policy for `scope` (`root` is your tenant root) · `derivation_settings`, `put_derivation_settings(scope, **fields)` (a subject's own settings and consents; a put replaces the whole record), `delete_derivation_settings` · `derivation_texts`, `erase_derivation_texts(scope, ids, reason=)` | | Corrections (`corrections_v1`) | `correct(scope, action, target)` and its shorthands `reject(scope, target, bind=)`, `replace(scope, target, value, valid_from=)`, `pin(scope, target)` and `confirm(scope, target, valid=)`; a target is a fact id or a claim · `corrections(scope)` · `correction(scope, id)` · `undo_correction(scope, id)` · `resolve_conflict` also records its resolution as corrections (`correction_ids`; `loser="wrong"` rejects the losers) | | Review (`derivation_review_v1`) | `review(scope)`: the candidates a policy held · `review_decide(scope, decisions)`, 1 to 100 at once · `approve(scope, held_id)` · `reject_held(scope, held_id, bind=)` | | Re-derivation (`derivation_rederive_v1`) | `rederive(scope, "regate")`: the policy re-applied to what is stored, with no model call · `rederive(scope, "reextract")`: the dry run prices a sample and returns an `estimate_id`; apply with `dry_run=False, estimate_id=…, cap_usd=…` · `rederive_job`, `rederive_wait`, `rederive_cancel` · `derivation_report(scope, since=, until=, csv=)` | | The feed and write-backs (`derivation_feed_v1`, `derived_by_v1`, `declared_episodes_v1`) | `derivation_feed(scope, consumer, cursor=)` · `feed_iter(scope, consumer)`, which follows `next_cursor` (`follow=True` keeps polling) · `erased_matches(item, held_ids)`: an erasure item names its events only by hash · `feed_consumers(scope)` · `derived_by="name@version"` on a typed triple (`experience(…, triple=…)`) and on `create_belief` · `derivation_status(scope, derived_by=[name])` · `declare_episode(scope, name, summary, events)`, `delete_episode(scope, id)` | | What is known (`corrections_v1`) | `memory_about(scope)`: the subject's facts and beliefs, each with its sources, and by default the scope's corrections and its candidates held for review (`include=("corrections", "held")`); `include=()` asks for neither | | How it was made (`derivation_provenance_v1`) | `include=["derivation"]` on `facts`, `fact`, `facts_timeline`, `beliefs` and `belief_why` · `derivation_decisions(scope, event_id)`: what became of one event | | The use rule (`derivation_use_rules_v1`) | `session=` on `recall`, `recall_stream`, `answer`, `answer_stream` and `compose`. Where an opt-in read-time use rule is in force, memory from other sessions, or older than the rule's window, is withheld and the read's `warnings` count it; without `session`, every memory counts as another session's. A server without that capability refuses `session` on `recall` and `recall_stream` with `422 INVALID_BODY`, since those routes deny unknown fields, and ignores it on `answer`, `answer_stream` and `compose`: send it only to a server whose `GET /v1/admin/version` lists `derivation_use_rules_v1` | A topic rule depends on the extraction model's topic labels, so a denied topic can still be learned when the model labels a candidate otherwise. Detectors and the structural rules (stages, sources, grounding, writer rules) are exact. Measure a draft with `derivation_policy_test` before you activate it. To fix a wrong memory, correct it rather than `forget()` it: what a `derived_only` forget removes can be learned again from the events that are kept, while a corrected claim stays corrected. This replaces a wrong value, then undoes the replacement: ```python from cortexdb.v1 import CORRECTIONS_V1 home = "org:acme/user:alice" if CORRECTIONS_V1 in client.capabilities(): # an older server answers 404 fact = client.facts(home, predicate="lives_in")["items"][0] fixed = client.replace(home, fact["id"], "Denver", idempotency_key="alice-moved") print(fixed["state"], fixed["replacement"]["claim"]["object"]) # applied Denver undone = client.undo_correction(home, fixed["correction_id"]) print(undone["state"]) # undone ``` Pass an `idempotency_key` with each correction: the same call sent again answers the first attempt instead of making a second correction. **The reference worker.** `cortexdb.workers.DerivationWorker` derives on your own compute from the change feed. Subclass it with a `name` and a `version`, a `derive(event)` that returns `Triple` objects to write back, and a `purge(event_ids)` that deletes your own copies, then call `run()` (`run(follow=True)` keeps polling). It takes a `V1Client`. Each result is written back citing its source event, with your `derived_by` stamp and a deterministic idempotency key, so a page delivered again replays instead of duplicating; `purge` is called with the events an erasure took; and the cursor (`FileCursor(path)` keeps it on disk) is saved only after a page's writes commit. **A Claude memory tool.** `cortexdb.memory_tool.CortexMemoryTool(client, scope)` carries out Anthropic's memory tool (`memory_20250818`) on a CortexDB scope: each file is an event CortexDB derives nothing from. It subclasses the Anthropic SDK's `BetaAbstractMemoryTool`, so it goes in the `tools` of the Anthropic client's `beta.messages.tool_runner(...)`. It needs the extra: `pip install 'cortexdbai[anthropic]'` (anthropic 0.69 or later). An `on_write(path, text)` hook runs before anything is written and can rewrite the text or refuse the write. `CortexMemoryFiles` is the same handler without the Anthropic SDK, for your own tool loop. Give the agent a scope of its own: a directory view lists the scope's events. The routes in full: [Derivation Policies](https://cortexdb.ai/docs/api-reference/derivation-policy), [Corrections](https://cortexdb.ai/docs/api-reference/corrections), [Review](https://cortexdb.ai/docs/api-reference/review), [Re-derivation](https://cortexdb.ai/docs/api-reference/derivation-rederive), [Change Feed](https://cortexdb.ai/docs/api-reference/derivation-feed) and [Memory About](https://cortexdb.ai/docs/api-reference/memory-about). ## Voice calls On a server in [voice mode](https://cortexdb.ai/docs/features/voice-mode), `client.sessions` opens a live call, and `recall()` takes the voice read path with `profile="voice"`: ```python caller, call = "ws:acme/caller:9f2c1e", "call_01JF8M2Q7R" started = client.sessions.start(caller, call, query="billing question") # POST /v1/sessions system_context = started["brief"]["context_block"] pack = client.recall(caller, query="what did I order last time", profile="voice", session=call) client.experience(caller, text="Change my delivery address to Pune.", wait="captured", labels=[f"session:{call}"]) client.sessions.get(caller, call) # the session and whether its memories are held client.sessions.end(caller, call) # optional enrich=True ``` `sessions.start(scope, session, *, query=, max_tokens=, include=, deadline_ms=, idle_timeout_s=)` takes the same fields as [POST /v1/sessions](https://cortexdb.ai/docs/api-reference/sessions). `recall()` also takes `alpha=` (0.0 to 1.0, vector search against keyword search) on any recall. A voice recall that finds no capacity raises `RecallOverloadedError` (retriable: answer that turn without memory); a session the caller does not hold raises `SessionNotFoundError`, and a server not in voice mode `VoiceSessionsDisabledError`. ## Audit ```python client.audit_list(actor="user:alice", capability="forget.gdpr", limit=100) client.audit_verify(audit_id="audit_01HX...", body="") ``` ## Admin ```python client.layer_stats() # GET /v1/admin/layers/stats (experimental) # Online re-embed (trusted operator; single node): a dry run by default client.admin_reembed("local:potion-multilingual-128M") # the estimate client.admin_reembed("local:potion-multilingual-128M", dry_run=False) # start the job client.admin_reembed_status() # {"job": {...}}: state, progress, eta_s, restart_with client.admin_reembed_cancel() # while building or ready client.admin_reembed_cleanup() # after a swap that kept the old index ``` The target is `"provider:model"`, `"provider"` alone, or a mapping with `provider` and `model`; `dims=` sets the target's width. See [Online re-embed](https://cortexdb.ai/docs/api-reference/admin#online-re-embed). ## Exception hierarchy All HTTP errors raise a subclass of `cortexdb.v1.V1Error`: ```python from cortexdb.v1 import ( V1Error, # base V1APIError, # generic API error envelope V1AuthError, # 401 V1PolicyDeniedError, # 403 V1RateLimitError, # 429 V1NotConfiguredError, # 503 V1ConnectionError, # network failure V1TimeoutError, # timeout ) try: client.experience(scope="...", text="...", observed_at="...", idempotency_key="...") except V1PolicyDeniedError as e: print(f"denied: {e.error_code}: {e.message}") print(e.details) # capability/tier context, when the server provides it except V1RateLimitError: time.sleep(1.0) ``` > **Note: API error attributes** `V1APIError` and its subclasses carry `status`, `error_code`, `message`, `request_id`, `details`, and `retriable`. Read policy context on `V1PolicyDeniedError` from `error_code` and `details`. > **Note: Two errors to handle on writes and deletes** - A `wait="indexed"` (or `"consolidated"`) write that runs out of the server's wait budget raises **`WaitTimeoutError`** (a `V1ServerTimeoutError`, in `cortexdb.v1.errors`) after about 30 s, before the client's own 60 s timeout, with `status` 408, `error_code` `WAIT_TIMEOUT`, `retriable` True and `details.status_url` (`details.event_ids` from `experience_bulk`). The write is durable: poll `write_status`, or re-send with the same `idempotency_key` (see [Experience](https://cortexdb.ai/docs/api-reference/experience#wait-deadline-and-408-wait_timeout)). - A `forget` (or erasure) that meets `409 AUTHORIZATION_STATE_CHANGED` raises **`AuthorizationStateChangedError`** (a `V1ConflictError`), `retriable` True. Nothing was deleted; retry after a second. - `event(event_id, scope=…)` reads one event and takes the route's `?scope=` filter (see [Events](https://cortexdb.ai/docs/api-reference/events#reading-one-event-in-one-scope)). ## Async variant `AsyncV1Client` is backed by `httpx.AsyncClient`. It mirrors `V1Client`: the same methods, with the same names and parameters, and you `await` each call. ```python import asyncio from cortexdb.v1 import AsyncV1Client async def main(): async with AsyncV1Client( api_url="https://api-v1.cortexdb.ai", actor="user:alice", bearer=tok, ) as client: pack = await client.recall(scope="org:acme/user:alice", view="holistic") ans = await client.answer(scope="org:acme/user:alice", question="Did Acme renew?") asyncio.run(main()) ``` > **Note: The async client mirrors the sync one** Both clients have the same public methods with the same parameters. The layer reads, the retention and other operator methods, and `recall()`'s full argument set (`include=`, `budgets=`, `temporal=`, `filters=`) are on both. The one difference is closing: the async client has **`aclose()`** instead of `close()` (or use `async with`, as above). There `pages()` and `feed_iter()` are async iterators. ## Method index > **Note: Capabilities, chunks and language fields** - **`version()`** returns `{version, crate_version, …, capabilities}` and **`capabilities()`** returns just the capability list (`GET /v1/admin/version`). Gate every new request field on it: a server that doesn't list a capability refuses its fields with `422 INVALID_BODY`. - **`event_chunks(event_id)`** shows how a long event was chunked (`GET /v1/admin/events/{id}/chunks`): `chunk_count`, `chunker_version`, `chunks`, `language`, `scripts`, `source_blob_ids`, `stored_text_bytes`. - **`iter_matched_fragments(pack)`** and **`fragment_text(text, fragment)`** (import from `cortexdb.v1`, not the package top level) walk a recall pack's `matched_fragments` and slice each span out of the event's text; an excerpted item yields no span. - **`experience()`** takes `language=`, `scripts=`, `timezone=` and `refers_to=`; **`recall()`** takes `language=`, `scripts=` and `query_variants=`: see [Languages & Multilingual Memory](https://cortexdb.ai/docs/features/languages), [Experience](https://cortexdb.ai/docs/api-reference/experience) and [Recall](https://cortexdb.ai/docs/api-reference/recall). - **`delete_blob(blob_id, missing_ok=True)`** returns `{…, "already_deleted": true}` for a blob that is already gone instead of raising `404 NOT_FOUND`. > **Note: Retention and WAL operator methods** `retention_policy_get` / `retention_policy_set` / `retention_policy_delete` / `retention_status` / `retention_sweep` / `wal_status` / `wal_compact` wrap the operator routes `/v1/admin/retention`, `/v1/admin/retention/policies`, `/v1/admin/retention/sweep`, `/v1/admin/wal` and `/v1/admin/wal/compact`. Expiry is irreversible erasure, so the server defaults `dry_run` to true on each of them. They are on both clients. The sections above cover the common paths. The full `V1Client` surface also includes these, several of which map to endpoints documented elsewhere in this reference: | Area | Methods | |---|---| | Compose | `compose` → [POST /v1/compose](https://cortexdb.ai/docs/api-reference/compose) | | Bi-temporal records | `query_claims` · `claim_history` · `list_conflicts` · `get_conflict` · `resolve_conflict` → [Claims & Conflicts](https://cortexdb.ai/docs/api-reference/claims-conflicts) | | Layer history | `belief_history` · `concept_history` | | Erasure | `erase` · `erasure_preview` · `forget_preview` → [/v1/erasures](https://cortexdb.ai/docs/api-reference/erasures) | | Import | `import_data` · `import_status` → [/v1/import](https://cortexdb.ai/docs/api-reference/import) | | Blobs | `upload_blob` · `delete_blob` → [/v1/blobs](https://cortexdb.ai/docs/api-reference/blobs) | | Beliefs (write) | `create_belief` | | Vocabularies | `update_vocabulary` → [/v1/vocabularies](https://cortexdb.ai/docs/api-reference/vocabularies) | | Auth | `signup` · `mint_token(subject=, scope=, caps=, scopes=)` · `whoami` → [/v1/auth](https://cortexdb.ai/docs/api-reference/auth) | | Server | `version` · `capabilities` → [/v1/admin/version](https://cortexdb.ai/docs/api-reference/admin) | | Documents | `event_chunks` → `GET /v1/admin/events/{id}/chunks` | | Audit | `audit_chain` · `audit_chain_verify` | | Write status | `write_status`: "did my write land?" by `idempotency_key` or `event_id` | | Voice calls | `sessions.start` · `sessions.get` · `sessions.end` → [/v1/sessions](https://cortexdb.ai/docs/api-reference/sessions) | | Re-embed | `admin_reembed` · `admin_reembed_status` · `admin_reembed_cancel` · `admin_reembed_cleanup` → [Online re-embed](https://cortexdb.ai/docs/api-reference/admin#online-re-embed) | | Lifecycle | `close` (sync) · `aclose` (async) | ========================================================================================== # TypeScript SDK _Reference for cortexdbai: V1Client and typed errors._ Source: https://cortexdb.ai/docs/sdks/typescript The official TypeScript / JavaScript client for CortexDB v1. Single `V1Client` class, isomorphic (Node + browser). ```bash npm install cortexdbai ``` Requires Node 18+ or any runtime with `fetch` + `AbortController`. npm package: **`cortexdbai`** Module: `cortexdbai/v1`. The SDK version is independent of the server version: see [Versioning and SDK compatibility](https://cortexdb.ai/docs/sdks/rest-api#versioning-and-sdk-compatibility). > **Note: Install cortexdbai, not the bare cortexdb name** An **unrelated, unaffiliated package** squats the bare `cortexdb` name on npm (it self-describes as an "official" client but is not published by the CortexDB project). Always install **`cortexdbai`**. ## Connect ```ts import { V1Client } from "cortexdbai/v1"; const client = new V1Client({ apiUrl: "https://api-v1.cortexdb.ai", // self-hosted: "http://localhost:3141" actor: "user:acct_42", // your actor, from the dashboard bearer: process.env.CORTEXDB_TOKEN!, // your API token timeoutMs: 30_000, }); await client.experience("org:acct_42/user:acct_42", { text: "hello memory", observedAt: new Date().toISOString(), idempotencyKey: "first-001", }, { wait: "indexed" }); const pack = await client.recall("org:acct_42/user:acct_42", { query: "hello", diagnostics: "none" }); ``` On CortexDB Cloud the API token and actor come from your [dashboard](https://cortexdb.ai/dashboard). On a self-hosted server, pass its key as `bearer`, or leave `bearer` out on a dev server started with `CORTEX_INSECURE_NO_AUTH=1`. **`V1Client.signup()`** is for a self-hosted server whose minter is on (`CORTEX_V1_MINTER_ENABLE=1`): it posts to `/v1/auth/signup`, gets a token, actor and scope, and returns a client wired with them, for example `await V1Client.signup({ apiUrl: "http://localhost:3141" })`. CortexDB Cloud doesn't offer it: its accounts come from signing up on [cortexdb.ai](https://cortexdb.ai/signup/free). | Option | Default | Notes | |---|---|---| | `apiUrl` | none (required) | v1 surface URL. | | `actor` | none (required) | Sent as `X-Cortex-Actor`; must match the token's `sub`. | | `bearer` | `undefined` | PASETO v4 public token: or, self-hosted, the server's `CORTEX_API_KEY` value. Optional only when the server runs with `CORTEX_INSECURE_NO_AUTH=1`. | | `timeoutMs` | `60000` | Per-request timeout. | | `fetch` | `globalThis.fetch` | Override for tracing / retries / custom transport. | ## Auth ```ts const me = await client.whoami(); // → { caller, tenant_id, deployment_preset, effective_capabilities, token } const minted = await client.mintToken({ subject: "user:alice", scope: "org:acme", // the tenant root the token belongs to ttlSeconds: 3600, scopes: ["scope.read:org:acme/user:alice/*", "scope.write:org:acme/user:alice/*"], // optional: confine it }); // → { token: "v4.public...", jti: "jti_...", expires_at: "2026-05-15T11:42:00Z" } ``` The capability list is returned under `effective_capabilities` (snake_case). ## Write path ```ts const r = await client.experience( "org:acme/user:alice", { text: "Acme upgraded to 200 seats.", role: "user", observedAt: "2026-05-15T10:42:00Z", idempotencyKey: "alice-chat-001", }, { wait: "indexed" }, // optional: "captured" | "indexed" | "consolidated" ); const bulk = await client.experienceBulk( "org:acme/user:alice", [ { text: "Acme upgraded to 200 seats.", role: "user", observedAt: "2026-05-15T10:42:00Z", idempotencyKey: "k1" }, { text: "Renewal is due in March.", role: "user", observedAt: "2026-05-15T10:43:00Z", idempotencyKey: "k2" }, ], ); ``` > **Note: experienceBulk options are { wait? } only** The options object is `{ wait? }`: there is **no `ordering`** field (passing one is a TS type error). Items are ingested in list order; encode temporal order in each item's `observedAt`. `ordering` is a REST body field, not an SDK option. Items are `ExperienceItem`s: camelCase flattened fields (exactly one of `text` / `jsonData` / `blobId` / `triple`, plus optional `role`, `observedAt`, `idempotencyKey`, `labels`, `modality`, `source`); the SDK builds the snake_case wire envelope. Passing `content` / `context` is a type error and throws at runtime; `ordering` in the options is a type error too. With `wait` omitted, a write returns **`captured`** (202) once the WAL append succeeds, not fully indexed; pass `{ wait: "indexed" }` to block on indexing. For full envelope shape see [Experience Envelope](https://cortexdb.ai/docs/concepts/experience-envelope). ## Read path ```ts const pack = await client.recall("org:acme/user:alice", { view: "holistic", query: "What did we decide about Acme?", include: ["beliefs", "facts", "episodes"], budgets: { max_tokens: 4000 }, temporal:{ natural: "last 30 days" }, }); // pack is a fully-typed StratifiedPack const ans = await client.answer("org:acme/user:alice", { question: "Did Acme renew?", view: "holistic", answerModel: "gpt-5.6-terra", // echoed in diagnostics only; the configured model answers (see below) temporal: { natural: "last 30 days" }, }); // ans is a fully-typed AnswerResponse ``` > **Note: answer_model is a cloud default** `claude-opus-5-5` is the **cloud** default. Self-hosted, `/v1/answer` routes through the configured answer lane (`CORTEX_ANSWER_*`) and is disabled until that lane is set. The field is `answerModel` (camelCase; in plain JavaScript an `answer_model` key is dropped). The configured model answers and `diagnostics.answer_model` echoes the request ([details](https://cortexdb.ai/docs/operations/llm-answer#diagnostics)). See [Self-hosting defaults](https://cortexdb.ai/docs/self-hosting/defaults). ## Layer reads ```ts await client.events("org:acme/user:alice", { view: "local", limit: 50 }); await client.episodes("org:acme/user:alice", "local"); await client.facts("org:acme/user:alice"); await client.beliefs("org:acme/user:alice"); await client.beliefWhy("belief_01HX..."); await client.understanding("org:acme/user:alice"); await client.buildEpisodes("org:acme/user:alice"); await client.buildBeliefs("org:acme/user:alice"); await client.synthesize("org:acme/dept:eng", ["sales_process"]); ``` > **Note: Facts / Beliefs need enrichment on self-host** On a content-only self-hosted instance the Facts and Beliefs layers stay **empty**: they are LLM-derived. See [Self-hosting defaults](https://cortexdb.ai/docs/self-hosting/defaults). ## Forget ```ts await client.forget("org:acme/user:alice", { layers: ["beliefs"], selector: { predicate: "is_likely_to_renew" }, cascade: "derived_only", reason: "User retracted speculation", }); ``` > **Note: The audit-note field is reason** `ForgetParams` = `{ layers, selector, cascade, confirmAll, reason, fromPreviewId }`. The audit note goes in **`reason`**. A `selector` of `{ memory_ids: [...] }` purges every listed id. If a storage backend fails mid-delete the server returns `502 FORGET_BACKEND_FAILED` rather than reporting success: deletes are idempotent, so retry the same call. > **Note: The two SDKs' forget APIs differ** The TypeScript `forget` takes a `selector` object; the **Python** `forget` does not: it targets by flat keyword (`predicate=`, `memory_ids=`, `about_subject=`). See the [Python SDK](https://cortexdb.ai/docs/sdks/python#forget). ## Governed memory [Governed memory](https://cortexdb.ai/docs/features/governed-memory) lets an application decide what CortexDB's background enrichment learns from its events, and correct what it learned wrongly. The calls below are the Python SDK's methods in camelCase on `V1Client`, plus ports of its reference worker and its Claude memory-tool handler. > **Note: Check the capability first** These calls need a server that lists their capability, and none of them checks for you. Against a server without it, each route answers `404`, which reads like "not found". Before the first call, look the route's capability up in `await client.capabilities()` (`GET /v1/admin/version`): `derivation_policy_v1`, `corrections_v1`, `derivation_review_v1`, `derivation_rederive_v1`, `derivation_feed_v1`, `derived_by_v1`, `declared_episodes_v1`, `derivation_use_rules_v1` or `derivation_provenance_v1` (most are exported as constants, such as `CORRECTIONS_V1`). They are experimental, and a server held at data format 10 answers `503 FORMAT_UPGRADE_PENDING` on most of these routes. | Area | Methods | |---|---| | Policies and settings (`derivation_policy_v1`) | `derivationPolicy(scope, { includeTexts })`: the policy in force, where each rule was set, its hash · `derivationTemplates()` · `derivationTaxonomy()` · `derivationPolicyTest(scope, { policy, sample, maxCostUsd })`: a draft run over your own events, writing nothing (its model calls are priced) · `changes.apply({ scope: root, id, ops: [deriveRecord(scope, body)] })` stages, previews and activates a policy for `scope` (`root` is your tenant root) · `derivationSettings`, `putDerivationSettings(scope, fields)` (a subject's own settings and consents; a put replaces the whole record, and `settingsFields(record)` gives the fields to send back), `deleteDerivationSettings` · `derivationTexts`, `eraseDerivationTexts(scope, ids, reason)` | | Corrections (`corrections_v1`) | `correct(scope, action, target, params)` and its shorthands `reject(scope, target, { bind })`, `replace(scope, target, value)`, `pin(scope, target)` and `confirm(scope, target, { valid })`; a target is a fact id, `{ fact_id }` or `{ claim }` · `corrections(scope, filters)` · `correction(scope, id)` · `undoCorrection(scope, id)` · `resolveConflict()` answers the corrections its resolution made (`correction_ids`); it has no `loser` option, which only the REST route takes | | Review (`derivation_review_v1`) | `review(scope, filters)`: the candidates a policy held · `reviewDecide(scope, decisions)`, 1 to 100 at once · `approve(scope, heldId)` · `rejectHeld(scope, heldId, { bind })` | | Re-derivation (`derivation_rederive_v1`) | `rederive(scope, "regate")`: the policy re-applied to what is stored, with no model call · `rederive(scope, "reextract")`: the dry run prices a sample and returns an `estimate_id`; apply with `{ dryRun: false, estimateId, capUsd }` · `rederiveJob`, `rederiveWait`, `rederiveCancel` · `derivationReport(scope, { from, to })`, `derivationReportCsv` | | The feed and write-backs (`derivation_feed_v1`, `derived_by_v1`, `declared_episodes_v1`) | `derivationFeed(scope, { consumer, cursor })` · `feedIter(scope, { consumer, follow })`, an async iterator whose `cursor` never skips an item you have not handled · `erasedMatches(item, eventIds)`: an erasure item names its events only by hash · `feedConsumers(scope)` · `derivedBy: { name, version }` on a typed triple (`experience()`, an `experienceBulk()` item) and in `createBelief()` · `derivationStatus(scope, { derivedBy })` · `declareEpisode(scope, name, summary, events)`, `deleteEpisode(scope, id)` | | What is known (`corrections_v1`) | `memoryAbout(scope)`: the subject's facts and beliefs, each with its id and sources, and by default the scope's corrections and its candidates held for review (`include: ["corrections", "held"]`); `{ include: [] }` asks for neither | | How it was made (`derivation_provenance_v1`) | `include: ["derivation"]` on `facts`, `fact`, `factsTimeline`, `beliefs` and `beliefWhy` · `derivationDecisions(scope, eventId)`: what became of one event | | The use rule (`derivation_use_rules_v1`) | `session` in the parameters of `recall`, `recallStream`, `answer` and `compose`. Where an opt-in read-time use rule is in force, memory from other sessions, or older than the rule's window, is withheld and the read's `warnings` count it; without `session`, every memory counts as another session's. A server without that capability refuses `session` on `recall` and `recallStream` with `422 INVALID_BODY`, since those routes deny unknown fields, and ignores it on `answer` and `compose`: send it only to a server whose `GET /v1/admin/version` lists `derivation_use_rules_v1` | A topic rule depends on the extraction model's topic labels, so a denied topic can still be learned when the model labels a candidate otherwise. Detectors and the structural rules (stages, sources, grounding, writer rules) are exact. Measure a draft with `derivationPolicyTest()` before you activate it. To fix a wrong memory, correct it rather than forget it: what a `derived_only` forget removes can be learned again from the events that are kept, while a corrected claim stays corrected. A correction can also hold a right value in place. This pins a fact so no extracted value supersedes it, then undoes the pin: ```ts import { CORRECTIONS_V1 } from "cortexdbai/v1"; const home = "org:acme/user:alice"; if ((await client.capabilities()).includes(CORRECTIONS_V1)) { // an older server answers 404 const about = await client.memoryAbout(home); // facts and beliefs with ids and sources, plus corrections and held items const fact = about.items.find((item) => item.kind === "fact"); if (fact) { const pin = await client.pin(home, fact.id, { idempotencyKey: `pin-${fact.id}` }); console.log(pin.correction_id, pin.effects?.pinned); // cor_… true const undone = await client.undoCorrection(home, pin.correction_id); console.log(undone.state, undone.effects.unpinned); // undone true } } ``` Pass an `idempotencyKey` with each correction: the same call sent again answers the first attempt (`replayed: true`) instead of making a second correction. **The reference worker.** `DerivationWorker` is the TypeScript port of the Python SDK's worker: `new DerivationWorker(client, { name, version, scope, cursor: new FileCursor("level.cursor"), derive, purge })`, then `await worker.run()` (`{ follow: true }` keeps polling; `stop()` ends it). `derive(event)` returns `Triple`s to write back and `purge(eventIds)` deletes your own copies. Each result is written back citing its source event, with the `derivedBy` stamp and a deterministic idempotency key, so a page delivered again replays instead of duplicating; `purge` is called with the events an erasure took; and the cursor is saved only after a page's writes commit. `FileCursor` loads `node:fs/promises` only when first used, so the SDK still loads in a browser. **A Claude memory tool.** `new CortexMemoryTool(client, { scope })` carries out Anthropic's memory tool (`memory_20250818`) on a CortexDB scope: each file is an event CortexDB derives nothing from. Its methods are the handlers the Anthropic TypeScript SDK's `betaMemoryTool(handlers)` takes (from `@anthropic-ai/sdk/helpers/beta/memory`), so pass `betaMemoryTool(memory)` in the `tools` of the Anthropic client's `beta.messages.toolRunner(...)`; `cortexdbai` itself does not depend on that SDK. An `onWrite(path, text)` hook runs before anything is written and can rewrite the text or refuse the write (answer `null`); `handle(input)` runs a `tool_use` block's input in your own loop. Give the agent a scope of its own: a directory view lists the scope's events. The routes in full: [Derivation Policies](https://cortexdb.ai/docs/api-reference/derivation-policy), [Corrections](https://cortexdb.ai/docs/api-reference/corrections), [Review](https://cortexdb.ai/docs/api-reference/review), [Re-derivation](https://cortexdb.ai/docs/api-reference/derivation-rederive), [Change Feed](https://cortexdb.ai/docs/api-reference/derivation-feed) and [Memory About](https://cortexdb.ai/docs/api-reference/memory-about). ## Voice calls On a server in [voice mode](https://cortexdb.ai/docs/features/voice-mode), `client.sessions` opens a live call, and `recall()` takes the voice read path with `profile: "voice"`: ```ts const caller = "ws:acme/caller:9f2c1e", call = "call_01JF8M2Q7R"; const started = await client.sessions.start(caller, call, { query: "billing question" }); const systemContext = started.brief.context_block; const pack = await client.recall(caller, { query: "what did I order last time", profile: "voice", session: call }); await client.experience(caller, { text: "Change my delivery address to Pune.", labels: [`session:${call}`] }, { wait: "captured" }); await client.sessions.get(caller, call); // the session and whether its memories are held await client.sessions.end(caller, call); // optional { enrich: true } ``` `sessions.start(scope, session, { query, maxTokens, include, deadlineMs, idleTimeoutS })` takes the same fields as [POST /v1/sessions](https://cortexdb.ai/docs/api-reference/sessions). `recall()` also takes `alpha` (0.0 to 1.0, vector search against keyword search) on any recall. A voice recall that finds no capacity throws `V1RecallOverloadedError` (retriable: answer that turn without memory); a session the caller does not hold throws `V1SessionNotFoundError`, and a server not in voice mode `V1VoiceSessionsDisabledError`. ## Audit + Admin ```ts await client.audit({ actor: "user:alice", capability: "forget.gdpr", limit: 100 }); await client.layerStats(); // experimental // Online re-embed (trusted operator; single node): a dry run by default await client.admin.reembed({ to: "local:potion-multilingual-128M" }); // the estimate await client.admin.reembed({ to: "local:potion-multilingual-128M", dry_run: false }); // start the job await client.admin.reembedStatus(); // { job: { state, progress, eta_s, restart_with, … } } await client.admin.reembedCancel(); // while building or ready await client.admin.reembedCleanup(); // after a swap that kept the old index ``` A refused start throws `V1ReembedBlockedError` (or a subclass such as `V1ReembedUnsupportedOnClusterError`), carrying every blocker. See [Online re-embed](https://cortexdb.ai/docs/api-reference/admin#online-re-embed). ## Typed errors ```ts import { V1Error, V1APIError, V1AuthError, V1PolicyDeniedError, V1RateLimitError, V1NotConfiguredError, V1InvalidRequestError, V1ConnectionError, V1TimeoutError, } from "cortexdbai/v1"; try { await client.experience("org:acme/user:alice", { ... }); } catch (e) { if (e instanceof V1PolicyDeniedError) { console.error(`policy denied: ${e.message}`); } else if (e instanceof V1RateLimitError) { await new Promise(r => setTimeout(r, 1000)); } else { throw e; } } ``` > **Note: Two errors to handle on writes and deletes** A `{ wait: "indexed" }` write that runs out of the server's wait budget rejects with **`V1WaitTimeoutError`** after about 30 s, before the client's own 60 s timeout, with `status` 408, `errorCode` `WAIT_TIMEOUT`, `retriable` true and `details.status_url` (`details.event_ids` from a bulk). The write is durable: poll its status, or re-send with the same `idempotencyKey` (see [Experience](https://cortexdb.ai/docs/api-reference/experience#wait-deadline-and-408-wait_timeout)). A forget or erasure answered `409 AUTHORIZATION_STATE_CHANGED` rejects with **`V1AuthorizationStateChangedError`**, retriable: nothing was deleted, retry after a second. `client.event(eventId, { scope })` reads one event with the route's `?scope=` filter. ## Types The SDK exports the full type set used by the v1 surface: ```ts import type { StratifiedPack, AnswerResponse, ExperienceItem, RecallParams, AnswerParams, ForgetParams, } from "cortexdbai/v1"; // Citation / Provenance are not exported; derive them if needed, // e.g. type Citation = AnswerResponse["citations"][number]; // RecallDiagnostics and RecallItemDiagnostics are exported. ``` `tsc --noEmit` reports zero errors in the v1 surface: the SDK is suitable for strict TypeScript projects (`strict: true`, `skipLibCheck: false`). ## Method index > **Note: Capabilities, chunks and language fields** - **`version()`** and **`capabilities()`** (`GET /v1/admin/version`). Gate new request fields on the capability list: an older server refuses them with `422 INVALID_BODY`. - **`eventChunks(eventId)`**: how a long event was chunked (`GET /v1/admin/events/{id}/chunks`). - Exported helpers **`matchedFragments(pack)`** and **`fragmentText(...)`** read the new `matched_fragments` spans of long documents in a recall pack. - `ExperienceItem` takes `language`, `scripts`, `timezone` and `refersTo`; `RecallParams` takes `language`, `scripts` and `query_variants` (snake_case, like the rest of `RecallParams`, which mirrors the REST body), and its `temporal` block takes `natural_mode`, `timezone` and `refers_during`. - `deleteBlob(id, { missingOk: true })` tolerates a blob that's already gone. Beyond the paths shown above, the client also exposes: | Area | Methods | |---|---| | Compose | `compose` → [POST /v1/compose](https://cortexdb.ai/docs/api-reference/compose) | | Bi-temporal records | `queryClaims` · `claimHistory` · `listConflicts` · `getConflict` · `resolveConflict` → [Claims & Conflicts](https://cortexdb.ai/docs/api-reference/claims-conflicts) | | Layer history | `beliefHistory` · `conceptHistory` | | Erasure | `erasurePreview` · `forgetPreview` → [/v1/erasures](https://cortexdb.ai/docs/api-reference/erasures) | | Import | `importData` → [/v1/import](https://cortexdb.ai/docs/api-reference/import) | | Blobs | `uploadBlob` · `deleteBlob` → [/v1/blobs](https://cortexdb.ai/docs/api-reference/blobs) | | Beliefs (write) | `createBelief` | | Vocabularies | `patchVocabulary` → [/v1/vocabularies](https://cortexdb.ai/docs/api-reference/vocabularies) | | Audit | `audit` · `auditChain` · `verifyAuditChain` | | Server | `version` · `capabilities` → [/v1/admin/version](https://cortexdb.ai/docs/api-reference/admin) | | Documents | `eventChunks` → `GET /v1/admin/events/{id}/chunks` | | Write status | `writeStatus`: "did my write land?" by idempotency key or event id | > **Note: The TypeScript surface is not identical to Python** Beyond the obvious snake_case to camelCase shift, three methods are **named differently**: Python's `audit_list`, `audit_chain_verify` and `update_vocabulary` are **`audit`**, **`verifyAuditChain`** and **`patchVocabulary`** here. Twelve Python methods have **no TypeScript equivalent**: `erase` (the execute step; TypeScript ships `erasurePreview` only), `import_status`, `audit_verify`, `index_audit`, `close`, and the retention / WAL operator methods (`retention_*`, `wal_status`, `wal_compact`). Use the [REST endpoints](https://cortexdb.ai/docs/sdks/rest-api) for those. `signup()` is a **static** on `V1Client`, not an instance method. ========================================================================================== # Command-Line Interface _cortexdb: a fast, full-coverage CLI for the v1 memory API._ Source: https://cortexdb.ai/docs/sdks/cli `cortexdb-cli` is a Click + Rich CLI that wraps the v1 HTTP API in a small, fast binary. It works against [CortexDB Cloud](https://cortexdb.ai/docs/cloud) or any self-hosted CortexDB deployment. ```bash pip install cortexdb-cli ``` Requires Python 3.10+. The `cortexdb-cli` version line is independent of the CortexDB server version; see [Versioning and SDK compatibility](https://cortexdb.ai/docs/sdks/rest-api#versioning-and-sdk-compatibility). ## The happy path on CortexDB Cloud Create an API token on your [dashboard](https://cortexdb.ai/dashboard) (it shows your actor and default scope too), put the four values in the environment, and go: ```bash export CORTEXDB_URL=https://api-v1.cortexdb.ai export CORTEXDB_API_KEY='' export CORTEXDB_ACTOR=user:acct_42 export CORTEXDB_SCOPE=org:acct_42/user:acct_42 cortexdb experience "Q3 revenue: $2.4M, $10M ARR target" # store cortexdb recall "Q3 revenue?" # retrieve ``` `cortexdb init` signs up anonymously instead (`POST /v1/auth/signup`) and persists the identity to `~/.cortexdb/state.json` (mode `0600` on POSIX). That needs a server whose minter allows anonymous signup, such as a self-hosted dev server started with `CORTEX_V1_MINTER_ENABLE=1`; CortexDB Cloud has it off, since its accounts come from [cortexdb.ai](https://cortexdb.ai/signup/free). ## Commands > **Note: This table is a curated subset** The CLI ships more commands than are listed here. The full set also includes `audit`, `claims`, `code`, `compose`, `concepts`, `conflicts`, and `wire`: run `cortexdb --help` for the authoritative list. `code` is the [Code Intelligence Plane](https://cortexdb.ai/docs/features/code-plane) CLI. | Command | What it does | v1 endpoint | |---|---|---| | `cortexdb init` | Anonymous signup; persist `state.json` | `POST /v1/auth/signup` | | `cortexdb preflight` | Read-only environment checks | `GET /v1/admin/health` | | `cortexdb plan` | What `apply` would do; writes nothing | (local) | | `cortexdb apply / resume / status` | Run onboarding, checkpointed | `/v1/auth/signup`, `/v1/admin/ready` | | `cortexdb doctor` | Diagnose an existing install | `/v1/admin/{health,ready}`, `/v1/auth/whoami` | | `cortexdb verify` | Prove write → recall → cleanup | `/v1/experience`, `/v1/recall`, `/v1/forget` | | `cortexdb cleanup` | Remove what `verify`/`apply` created | `POST /v1/forget` | | `cortexdb experience "..."` | Store a memory | `POST /v1/experience` | | `cortexdb experience bulk file.jsonl` | Bulk-load envelopes | `POST /v1/experience/bulk` | | `cortexdb recall "..."` | Stratified context pack | `POST /v1/recall` (holistic) | | `cortexdb search "..."` | Granular event hits | `POST /v1/recall` (granular) | | `cortexdb answer "..."` | Recall + LLM answer | `POST /v1/answer` | | `cortexdb forget --memory-id ... --reason ...` | Delete with audit | `POST /v1/forget` | | `cortexdb episodes {list,get,delete}` | Episode + event ops | `/v1/episodes`, `/v1/events/{id}` | | `cortexdb entities {list,get,link}` | Entity rollups | `/v1/facts` | | `cortexdb facts {list,timeline}` | Typed triples + bi-temporal lineage | `/v1/facts`, `/v1/facts/timeline` | | `cortexdb beliefs {list,why,build}` | Aggregated beliefs + provenance | `/v1/beliefs*` | | `cortexdb understanding {list,coverage,synthesize}` | Synthesized concepts | `/v1/concepts`, `/v1/concepts/coverage`, `/v1/understanding/synthesize` | | `cortexdb scopes {list,register,members}` | Hierarchical scopes | `/v1/scopes*` | | `cortexdb auth {whoami,signup,tokens,revoke}` | Identity + mint + revoke | `/v1/auth*` | | `cortexdb policy {effective,deployment}` | What can this actor do, where? | `/v1/policy*` | | `cortexdb admin {health,usage,layers}` | Diagnostics | `/v1/auth/whoami`, `/v1/admin/layers/stats` | | `cortexdb admin retention {show,set,sweep,delete}` | Retention rules and the expiry sweep | `/v1/admin/retention`, `/v1/admin/retention/policies`, `/v1/admin/retention/sweep`: see [Retention & WAL](https://cortexdb.ai/docs/operations/retention-wal) | | `cortexdb admin wal {status,compact}` | Unified WAL census and dead-row compaction | `/v1/admin/wal`, `/v1/admin/wal/compact` | | `cortexdb audit {status,verify}` | Audit hash-chain integrity | `/v1/audit*` | | `cortexdb claims / conflicts` | Bi-temporal record history; contradiction detection | `/v1/claims/history`, `/v1/conflicts` | | `cortexdb concepts` | LLM-synthesized concepts and themes | `/v1/concepts` | | `cortexdb code {...}` | Code-plane repos, imports, bundles | `/v1/code/*` | | `cortexdb compose` | Structured markdown document from memory | `POST /v1/compose` | | `cortexdb wire` | Wire an agent harness to CortexDB, and prove it | (local) | | `cortexdb voice status` | Voice mode's readiness, the in-process model and the call sessions | `/v1/admin/ready`, `/v1/admin/version` | | `cortexdb session {start,status,end} SESSION` | A live voice call's session and its brief | `/v1/sessions*` | | `cortexdb reembed {estimate,start,status,cancel,cleanup}` | Move a single node to another embedding model while it serves | `/v1/admin/reembed*` | | `cortexdb import data.{json,jsonl,csv,txt}` | Bulk ingest | `POST /v1/experience` per row (or one `POST /v1/import` with the server-side option) | | `cortexdb export -o backup.json` | Export memories | `POST /v1/export` | | `cortexdb config {show,set}` | Edit `~/.cortexdb/config.toml` | (local) | | `cortexdb` (no args) | Interactive REPL | (wraps the above) | > **Note: cortexdb auth tokens: --scope does not confine** `cortexdb auth tokens --scope PATH` only says **where your own `auth.mint` is checked**; it does not confine the token. To confine it, pass `--confine CAP:PREFIX` (repeatable), which is sent as the token's `scopes` claim: ```bash cortexdb auth tokens --subject agent:b --ttl 3600 --confine 'scope.read:org:acme/team:b/*' ``` The CLI refuses a `--scope` value that looks like a `CAP:PREFIX` entry and points you at `--confine`. See [Auth](https://cortexdb.ai/docs/api-reference/auth) for how `scope`, `scopes` and `caps` differ. `cortexdb remember "..."` is a hidden alias for `experience`: kept so old scripts and muscle memory keep working. > **Note: --wait indexed and the 30-second budget** The CLI's HTTP timeout is 30 s, the same as the server's wait budget, so `cortexdb experience --wait indexed "…"` against a server that can't index in time ends with the CLI's own `Request timed out.` (exit code 2) after about 30 s, not the server's `408 WAIT_TIMEOUT`. The write is captured and durable either way. The CLI derives each write's `idempotency_key` from the scope and the text, so re-running the same command replays that write instead of storing it twice. ## Voice mode On a server in [voice mode](https://cortexdb.ai/docs/features/voice-mode), check it is ready, open a call and recall on the voice path: ```bash cortexdb voice status cortexdb session start call_01JF8M2Q7R --scope ws:acme/caller:9f2c1e --query "billing question" cortexdb recall "what did I order last time" --scope ws:acme/caller:9f2c1e \ --profile voice --session call_01JF8M2Q7R cortexdb session end call_01JF8M2Q7R --scope ws:acme/caller:9f2c1e ``` `session start` also takes `--max-tokens`, `--include`, `--deadline-ms` and `--idle-timeout-s`; `recall` takes `--alpha` (0.0 to 1.0, vector search against keyword search) on any recall. To move an existing store to voice mode, or to any other embedding model, run the online re-embed: ```bash cortexdb reembed estimate --to local:potion-multilingual-128M # what the move would take cortexdb reembed start --to local:potion-multilingual-128M cortexdb reembed status --watch # until the state is ready ``` Then restart with the settings the estimate names. `reembed cancel` and `reembed cleanup` match the [admin routes](https://cortexdb.ai/docs/api-reference/admin#online-re-embed); `--to` also takes `openai:text-embedding-3-large --dims 3072`. ## Governed memory [Governed memory](https://cortexdb.ai/docs/features/governed-memory) lets you decide what CortexDB's background enrichment learns from your events, and correct what it learned wrongly. The commands below need a server that lists the matching capability in `GET /v1/admin/version`. > **Note: Check the capability first** Against a server without the capability each route answers `404`, which reads like "not found" (for most of these routes the CLI's hint then names the capability the server lacks). Check that `GET /v1/admin/version` lists the capability first: `derivation_policy_v1`, `corrections_v1`, `derivation_review_v1`, `derivation_rederive_v1`, `derivation_feed_v1`, `derived_by_v1`, `declared_episodes_v1`, `derivation_use_rules_v1` or `derivation_provenance_v1`. They are experimental, and a server held at data format 10 answers `503 FORMAT_UPGRADE_PENDING` on most of these routes. | Command | What it does | v1 endpoint | |---|---|---| | `cortexdb derivation policy SCOPE [--texts]` | The policy in force at a scope, where each rule was set, its hash | `GET /v1/derivation/policy` | | `cortexdb derivation templates [NAME]` · `derivation taxonomy` | The templates (`NAME` prints one body as JSON) · the sensitive-topic taxonomy and detectors | `GET /v1/derivation/templates`, `/taxonomy` | | `cortexdb derivation test SCOPE --file F [--recent N] [--max-cost USD]` | Run a draft over a sample of your events: each candidate's verdict and the rule that decided it. Needs enrichment on (a server with it off answers `409 ENRICHMENT_OFF`). Writes nothing; its model calls are priced | `POST /v1/derivation/policy/test` | | `cortexdb derivation stage SCOPE (--file F \| --template NAME)` | Stage, preview and activate a policy as a change set (asks before it activates) | `/v1/access/changes*` | | `cortexdb derivation settings SCOPE [--mode M] [--deny-topic T] [--consent CAT:PURPOSE] [--delete]` | Show or change a subject's own settings and consents; they take effect at once | `/v1/derivation/settings` | | `cortexdb derivation texts SCOPE [--erase ID]` | A policy's instructions and examples, and their erasure | `/v1/derivation/texts*` | | `cortexdb corrections add SCOPE (--reject \| --replace \| --pin \| --confirm) FACT` | Fix a wrong memory: `--value` and `--valid-from` with `--replace`, `--bind` with `--reject` | `POST /v1/corrections` | | `cortexdb corrections {list,show,undo} SCOPE [ID]` | List, read or undo corrections | `/v1/corrections*` | | `cortexdb review list SCOPE` · `review {approve,reject} SCOPE HELD…` | The candidates a policy held for review · decide them | `/v1/review*` | | `cortexdb derivation rederive SCOPE --mode regate\|reextract [--apply]` | Bring what was learned in line with the policy in force: a dry run unless `--apply` (a `reextract` apply also names `--estimate` and `--cap`) | `POST /v1/derivation/rederive` | | `cortexdb derivation {job,cancel} SCOPE JOB_ID` · `derivation report SCOPE [--csv]` | Follow or stop a job · what was derived over a period, counts and ids only | `/v1/derivation/rederive/*`, `/report` | | `cortexdb derivation feed SCOPE --consumer NAME [--follow] [--cursor-file F]` · `derivation consumers SCOPE` | The change feed as JSON lines, for a worker of your own · who reads it | `GET /v1/derivation/feed`, `/feed/consumers` | | `cortexdb episodes declare SCOPE --file F` · `episodes delete SCOPE ID` | Declare an episode over events you name, or delete one | `POST`, `DELETE /v1/episodes` | | `--derived-by NAME@VERSION` on `experience write --triple`, `beliefs create` and `episodes declare` | Stamp a write-back with the pipeline that made it | (a field of the write) | | `cortexdb memory about SCOPE [--corrections]` | What is known about a subject, each item with its sources and its fact id | `GET /v1/memory/about` | | `cortexdb derivation status SCOPE` · `derivation decisions SCOPE EVENT` · `--include derivation` on `facts` and `beliefs` reads | How memories were made, and what became of one event | `/v1/derivation/status`, `/decisions` | | `--session ID` on `recall`, `search`, `answer` and `compose` | The session a read is made in: where an opt-in read-time use rule is in force, memory from other sessions is withheld. A server without that capability refuses it on `recall` and `search` with `422 INVALID_BODY` (an unknown field) and ignores it on `answer` and `compose`: pass it only to a server whose `GET /v1/admin/version` lists `derivation_use_rules_v1` | (a field of the read) | Test a template on your own events, then stage it: ```bash SCOPE=org:acme/app:companion cortexdb derivation templates consumer > policy.json # a template's body, to edit cortexdb derivation test "$SCOPE" --file policy.json --recent 20 --max-cost 0.25 cortexdb derivation stage "$SCOPE" --file policy.json --reason "consumer defaults" cortexdb derivation policy "$SCOPE" # the policy in force, and its hash ``` `--max-cost` caps the test's model spend, which is reserved from the tenant's daily budget of tests and dry runs. A topic rule depends on the extraction model's topic labels, so a denied topic can still be learned when the model labels a candidate otherwise; detectors and the structural rules (stages, sources, grounding, writer rules) are exact. To fix a wrong memory, use `cortexdb corrections add` rather than `cortexdb forget`: what a forget of derived memory removes can be learned again from the events that are kept, while a corrected claim stays corrected. `corrections add --reject`, `corrections undo` and `review reject` ask first on a terminal; a script passes `--yes`. The routes in full: [Derivation Policies](https://cortexdb.ai/docs/api-reference/derivation-policy), [Corrections](https://cortexdb.ai/docs/api-reference/corrections), [Review](https://cortexdb.ai/docs/api-reference/review), [Re-derivation](https://cortexdb.ai/docs/api-reference/derivation-rederive), [Change Feed](https://cortexdb.ai/docs/api-reference/derivation-feed) and [Memory About](https://cortexdb.ai/docs/api-reference/memory-about). ## Onboarding and diagnostics Eight commands exist specifically so a coding agent can install, verify and diagnose CortexDB without guessing. They share one output envelope and one exit-code contract. ```bash cortexdb preflight # can this machine talk to CortexDB at all? cortexdb plan # what would apply do? (no writes) cortexdb apply # do it, checkpointing after each stage cortexdb resume # continue after an interruption cortexdb doctor # why is my existing install unhappy? cortexdb verify # prove write -> recall -> cleanup end to end cortexdb cleanup # remove what verify/apply created ``` ### One envelope Every one of them emits the same document, so you parse one shape rather than eight. `--json` works before or after the subcommand, and is implied when stdout is not a TTY. ```json { "schema": "cortexdb.cli.diagnostic/v1", "command": "doctor", "ok": false, "exit_code": 11, "outcome": "failure", "first_failing_stage": "authenticated", "counts": { "pass": 4, "fail": 1, "skip": 0, "blocked": 1 }, "stages": [ { "id": "authenticated", "title": "Token is accepted", "state": "fail", "detail": "HTTP 401: token expired", "retriable": false, "remediation": "The token is missing, expired or revoked. Run `cortexdb init`.", "doc_url": "https://cortexdb.ai/docs/api-reference/auth" } ] } ``` Every stage that is not `pass` carries `retriable`, `remediation` and `doc_url`. ### Exit codes Branch on these instead of parsing the message: | Code | Meaning | What to do | |---|---|---| | `0` | Everything passed | Continue | | `2` | Usage error | Fix the command line | | `10` | A stage failed transiently | Retry | | `11` | A stage failed permanently | Act on `remediation` | | `12` | Blocked: a prerequisite is absent, nothing was attempted | Satisfy the prerequisite | | `1` | Unexpected internal error | Report the JSON | `blocked` is deliberately distinct from `fail`: "you have no credentials" and "your credentials were rejected" need different responses. ### Stages are idempotent Each stage probes before it acts, so a stage that is already satisfied reports `skip` with the reason. Re-running a partial onboarding is safe, `apply` never mints a second identity, and `resume` is simply `apply` reading the checkpoint at `~/.cortexdb/onboarding.json`. `apply` stops at the first failing stage rather than continuing. ### verify is safe against a real deployment `verify` writes one synthetic marker with `?wait=indexed`, so read-your-writes is guaranteed by the time the write returns. Everything it writes goes into a `cortexdb-cli-verify` leaf subtree of your scope, and `cleanup` removes exactly that subtree: it cannot reach your real data. Pass `--keep` to leave the marker in place for inspection. ## Pipe-friendly Auto-detects when stdout isn't a TTY and switches to JSON: ```bash cortexdb recall "Q3 revenue" | jq .context_block cortexdb facts list | jq '.items[] | {predicate, object}' echo "remember this" | cortexdb experience - cat envelopes.jsonl | cortexdb experience bulk - ``` Force JSON any time with `--json`. ## Configuration Three layers, in precedence order (high to low): 1. **CLI flags**: `--api-key`, `--endpoint`, `--actor`, `--scope`, `--profile` 2. **Environment**: `CORTEXDB_API_KEY`, `CORTEXDB_URL`, `CORTEXDB_ACTOR`, `CORTEXDB_SCOPE` 3. **Persisted state:** - `~/.cortexdb/config.toml`: endpoint, profile names (human-editable) - `~/.cortexdb/state.json`: token, actor, scope, expiry (managed by `init`; `0600` on POSIX) > **Note: state.json is not a drop-in copy to the MCP server** The CLI and connectors use `~/.cortexdb/state.json`, while `cortexdb-mcp` reads `/cortexdb-mcp/state.json`: and the **key names differ**: the CLI writes `{ token, user_id, scope, expires_at }`, the MCP server reads `{ token, actor, scope }`. Reusing one anonymous identity across both tools means copying the file to the other tool's path **and renaming `user_id` ↔ `actor`**; a straight copy leaves the MCP server without an actor, so its calls fail the actor-vs-token check. Also available: `--config-dir` (env `CORTEXDB_HOME`) isolates one project's identity and checkpoints from another's; `--profile` alone does not. ## Auth notes Against the cloud (and any server with `CORTEX_API_KEY` set), authenticated requests carry both `Authorization: Bearer ` and `X-Cortex-Actor`: the bearer is a PASETO v4 token, or the `CORTEX_API_KEY` value itself on self-hosted servers. The CLI stamps both for you. > **Note: Local no-auth mode is opt-in** A self-hosted server started with **`CORTEX_INSECURE_NO_AUTH=1`** serves everything as `user:local`: no headers required (and `/v1/admin/health` / `ready` never need auth). Otherwise the CLI sends the `CORTEX_API_KEY` value as the bearer for you; a keyless, network-exposed server auto-generates a key and requires it. - 401s show the specific error code (`EXPIRED_TOKEN`, `ACTOR_MISMATCH`, `INVALID_TOKEN_SIGNATURE`) and the remediation: on CortexDB Cloud, a new token from your dashboard. - 403s cite the missing capability and the policy tier that denied. If a recall returns `diagnostics.read` denied, pass `--diagnostics none`: CortexDB Cloud tokens don't carry `diagnostics.read` (the CLI defaults to `none`). - On CortexDB Cloud, `402 PLAN_LIMIT_REACHED` and `429 SUBTREE_RATE_LIMITED` mean a plan limit ([Plans and limits](https://cortexdb.ai/docs/cloud/plans)). - Every authenticated response carries `X-RateLimit-Limit`, `X-RateLimit-Reset`, `X-Cortex-Token-Expires-In`, and `X-Cortex-Token-Expires-At`; `cortexdb admin usage` surfaces them. ## Profiles Run against multiple deployments by passing `--profile`: ```bash cortexdb --profile prod --endpoint https://api-v1.cortexdb.ai --api-key "$PROD_TOKEN" --actor user:acct_42 auth whoami cortexdb --profile staging init --endpoint https://staging.cortexdb.example cortexdb --profile staging experience "test memory" ``` Each profile gets its own block in `~/.cortexdb/config.toml`. The `state.json` is shared: if you need separate identities per profile, run `cortexdb auth signup --save` after switching, or isolate with `--config-dir`. ## See also - [Python SDK](https://cortexdb.ai/docs/sdks/python): programmatic access from Python. - [TypeScript SDK](https://cortexdb.ai/docs/sdks/typescript): programmatic access from JS/TS. - [MCP Server](https://cortexdb.ai/docs/sdks/mcp-server): same v1 surface exposed to Claude / Cursor / VS Code Copilot. - [Auth](https://cortexdb.ai/docs/api-reference/auth): how tokens, actors, and capabilities fit together. ========================================================================================== # REST API _Direct HTTP examples for the CortexDB v1 surface._ Source: https://cortexdb.ai/docs/sdks/rest-api CortexDB exposes a v1 REST API. Every endpoint accepts and returns JSON unless noted (`/v1/blobs` is binary; SSE endpoints are `text/event-stream`). [CortexDB Cloud](https://cortexdb.ai/docs/cloud) serves it at `https://api-v1.cortexdb.ai`; a [self-hosted](https://cortexdb.ai/docs/self-hosting/quickstart) server serves it at `http://localhost:3141`. For full endpoint shapes and field-by-field reference, browse the [API Reference](https://cortexdb.ai/docs/api-reference/recall) section. > **Note: Self-hosted auth: a key is required unless you opt out** A self-hosted server started with **`CORTEX_INSECURE_NO_AUTH=1`** serves every request as `user:local` with no headers, so the examples below reduce to the URL and JSON body. Otherwise pass `Authorization: Bearer ` (+ `X-Cortex-Actor`) as shown. A keyless, network-exposed server auto-generates a key and requires it. See the [Self-Hosting Quickstart](https://cortexdb.ai/docs/self-hosting/quickstart). ## 30-second cold start The shortest copy-paste path from "I have nothing" to "I stored a memory and asked about it", on [CortexDB Cloud](https://cortexdb.ai/docs/cloud). Sign up at [cortexdb.ai](https://cortexdb.ai/signup/free) and create an API token on the dashboard, which also shows your actor and default scope: ```bash # 1. Your credentials, from the dashboard export CORTEXDB_TOKEN='' export CORTEXDB_ACTOR=user:acct_42 # your actor export CORTEXDB_SCOPE=org:acct_42/user:acct_42 # your default scope # 2. Store a memory curl -sfS -X POST "https://api-v1.cortexdb.ai/v1/experience?wait=indexed" -H "Authorization: Bearer $CORTEXDB_TOKEN" -H "X-Cortex-Actor: $CORTEXDB_ACTOR" -H 'Content-Type: application/json' -d "{ \"scope\": \"$CORTEXDB_SCOPE\", \"modality\": \"conversation\", \"content\": { \"kind\": \"message\", \"role\": \"user\", \"text\": \"Q3 revenue exceeded \$2.4M, up 34% YoY\" }, \"context\": { \"observed_at\": \"$(date -u +%Y-%m-%dT%H:%M:%SZ)\" }, \"idempotency_key\": \"cold-start-001\" }" # 3. Ask a question (the answer endpoint, with citations) curl -sfS -X POST https://api-v1.cortexdb.ai/v1/answer -H "Authorization: Bearer $CORTEXDB_TOKEN" -H "X-Cortex-Actor: $CORTEXDB_ACTOR" -H 'Content-Type: application/json' -d "{ \"scope\": \"$CORTEXDB_SCOPE\", \"question\": \"What was Q3 revenue?\", \"view\": \"holistic\", \"diagnostics\": \"none\" }" ``` On a self-hosted server, use `http://localhost:3141` and its key as the token (`CORTEXDB_ACTOR=user:local`, `CORTEXDB_SCOPE=org:demo/user:local`); `/v1/answer` there needs the answer lane configured ([Self-hosting defaults](https://cortexdb.ai/docs/self-hosting/defaults)). A self-hosted server whose minter is on (`CORTEX_V1_MINTER_ENABLE=1`) also takes `POST /v1/auth/signup` with `{}`, which returns a token, its `user_id` and `scope`; CortexDB Cloud doesn't, since its accounts come from the website. Every authenticated response carries `X-RateLimit-Limit`, `X-RateLimit-Reset`, `X-Cortex-Token-Expires-In`, and `X-Cortex-Token-Expires-At`: surface them in your client to back off and refresh ahead of expiry. ## Variables in the examples The shell examples across these docs use one set of variables. Export them once and the examples run as written: | Variable | Set it to | |---|---| | `CORTEXDB_URL` | `https://api-v1.cortexdb.ai` on CortexDB Cloud, or your own server (`http://localhost:3141`) | | `CORTEXDB_TOKEN` | Your API token: from the Cloud dashboard, or one your server minted | | `CORTEXDB_ACTOR` | The actor the token belongs to, sent as `X-Cortex-Actor` | | `CORTEXDB_SCOPE` | The scope you read and write by default | | `CORTEX_API_KEY` | Self-hosted only: the operator key, the same value the server was started with | The [CLI](https://cortexdb.ai/docs/sdks/cli), the [MCP server](https://cortexdb.ai/docs/sdks/mcp-server) and the [connectors](https://cortexdb.ai/docs/connectors) read `CORTEXDB_URL`, `CORTEXDB_ACTOR` and `CORTEXDB_SCOPE` from the environment themselves, and take the token as `CORTEXDB_API_KEY`. Examples that name people and teams use `user:alice` as the actor and scopes under `org:acme/`. On CortexDB Cloud, send your own actor and keep every scope under `org:acct_/`. ## Authentication Every authenticated request carries a bearer token (a PASETO v4 token this server minted, or a JWT or PASETO token from an issuer the server trusts) plus the `X-Cortex-Actor` header: ```bash curl https://api-v1.cortexdb.ai/v1/auth/whoami \ -H "Authorization: Bearer $CORTEXDB_TOKEN" \ -H "X-Cortex-Actor: user:alice" ``` `X-Cortex-Actor` must match the token's `sub` claim: otherwise the server returns `401 ACTOR_MISMATCH`. Two callers may leave it out: a token from an identity provider whose issuers-file entry maps the subject itself, and a call of the HTTP MCP server (`/mcp`). Self-hosted servers: if started with `CORTEX_API_KEY=`, that value itself is a working bearer (`Authorization: Bearer `). To run **unauthenticated** for local dev, start with `CORTEX_INSECURE_NO_AUTH=1`: every request is served as `user:local` and no headers are needed. With neither set on a network-exposed bind, the server auto-generates a key and requires it (printed in the boot log). Ways to get a token (full decision table at [Authorization](https://cortexdb.ai/docs/concepts/authorization)): | You want to… | Endpoint | Notes | |---|---|---| | Use CortexDB Cloud | Your [dashboard](https://cortexdb.ai/dashboard) | Sign up on cortexdb.ai and create an API token; valid 90 days. | | Try a self-hosted server | `POST /v1/auth/signup` | On a server whose minter is on: an anonymous token for its own `user:u_…` region, valid 7 days. Not on CortexDB Cloud. | | Run a service account | `POST /v1/auth/tokens` | Requires `auth.mint` capability. `ttl_seconds`, clamped to a 60 s minimum; by default at most 90 days for a `user:` subject, 7 for an `agent:` and 30 for a `service:` one (`CORTEX_MINT_MAX_LIFETIME_*`). Name the tenant root (`scope`). | | Use your own IdP in production | The issuers file (`CORTEX_AUTH_ISSUERS_FILE`) | Your IdP issues JWT or PASETO tokens; CortexDB verifies them. See [Identity and Tokens](https://cortexdb.ai/docs/shared-memory/identity#external-issuers). | ## Base URL | Environment | URL | |---|---| | CortexDB Cloud | `https://api-v1.cortexdb.ai` | | Self-hosted | `http://localhost:3141` | ## Capture an experience ```bash curl -X POST https://api-v1.cortexdb.ai/v1/experience \ -H "Authorization: Bearer $CORTEXDB_TOKEN" \ -H "X-Cortex-Actor: user:alice" \ -H "Content-Type: application/json" \ -d '{ "scope": "org:acme/dept:eng/user:alice", "modality": "conversation", "content": { "kind": "message", "role": "user", "text": "Just got off a call with Priya at Acme." }, "context": { "observed_at": "2026-05-15T10:42:00Z" }, "idempotency_key": "alice-chat-001" }' ``` > **Note: Required fields and wait semantics** Only **`scope`, `modality`, `content`** are required; `context`, `observed_at`, and `idempotency_key` are optional. With `?wait=` **omitted** the write returns **`202` `captured`** with an `event_id` and a `lifecycle_stream` URL: the event is in the WAL but **not yet indexed**. Pass `?wait=indexed` (or `captured` / `consolidated`) to block until that stage completes (returns `200`). `?wait=accepted` is an explicit alias for the omitted default; any other value `422`s listing the valid values. ## Recall a stratified pack ```bash curl -X POST https://api-v1.cortexdb.ai/v1/recall \ -H "Authorization: Bearer $CORTEXDB_TOKEN" \ -H "X-Cortex-Actor: user:alice" \ -H "Content-Type: application/json" \ -d '{ "scope": "org:acme/dept:eng/user:alice", "view": "holistic", "query": "What did we decide about the Q3 launch?", "include": ["beliefs", "facts", "episodes"], "budgets": { "max_tokens": 4000 }, "citation_mode": "inline_with_markers" }' ``` ## Recall + LLM answer ```bash curl -X POST https://api-v1.cortexdb.ai/v1/answer \ -H "Authorization: Bearer $CORTEXDB_TOKEN" \ -H "X-Cortex-Actor: user:alice" \ -H "Content-Type: application/json" \ -d '{ "scope": "org:acme/dept:eng/user:alice", "view": "holistic", "question": "Did Acme renew?", "temporal": { "natural": "last 30 days" } }' ``` > **Note: The answer field is question; the model is a cloud default** The answer endpoint's field is **`question`** (not `query`). `claude-opus-5-5` is the cloud default model; self-hosted, `/v1/answer` routes through the configured answer lane (`CORTEX_ANSWER_*`) and is disabled until it's set: see [Self-hosting defaults](https://cortexdb.ai/docs/self-hosting/defaults). ## Layer reads ```bash # Events curl "https://api-v1.cortexdb.ai/v1/events?scope=org:acme/dept:eng/user:alice&since=2026-04-01T00:00:00Z" \ -H "Authorization: Bearer $CORTEXDB_TOKEN" \ -H "X-Cortex-Actor: user:alice" # Facts (with bi-temporal as_of) curl "https://api-v1.cortexdb.ai/v1/facts?scope=org:acme/dept:eng&subject=ent_acme_corp&predicate=deal_stage&as_of=2026-04-15T00:00:00Z" \ -H "Authorization: Bearer $CORTEXDB_TOKEN" \ -H "X-Cortex-Actor: user:alice" # Fact timeline (supersession chain) curl "https://api-v1.cortexdb.ai/v1/facts/timeline?scope=org:acme/dept:eng&subject=ent_acme_corp&predicate=deal_stage" \ -H "Authorization: Bearer $CORTEXDB_TOKEN" \ -H "X-Cortex-Actor: user:alice" # Beliefs + why curl "https://api-v1.cortexdb.ai/v1/beliefs?scope=org:acme/dept:eng&about=ent_acme_corp" \ -H "Authorization: Bearer $CORTEXDB_TOKEN" -H "X-Cortex-Actor: user:alice" curl "https://api-v1.cortexdb.ai/v1/beliefs/why?belief_id=belief_01HX..." \ -H "Authorization: Bearer $CORTEXDB_TOKEN" -H "X-Cortex-Actor: user:alice" ``` > **Note: REST as_of works; the Python SDK facts() does not wrap it** The REST `GET /v1/facts?as_of=…` bi-temporal query works. Note the Python SDK's `facts()` wraps only `subject`/`predicate`: for as-of queries from Python, call this endpoint directly. On a content-only self-hosted instance the Facts/Beliefs layers are empty (need enrichment): see [Self-hosting defaults](https://cortexdb.ai/docs/self-hosting/defaults). ## Selective forget ```bash curl -X POST https://api-v1.cortexdb.ai/v1/forget \ -H "Authorization: Bearer $CORTEXDB_TOKEN" \ -H "X-Cortex-Actor: user:alice" \ -H "Content-Type: application/json" \ -d '{ "scope": "org:acme/dept:eng/user:alice", "layers": ["beliefs"], "selector": { "predicate": "is_likely_to_renew" }, "cascade": "derived_only", "audit_note": "User retracted speculation" }' ``` A selector of `{"memory_ids": [...]}` purges every listed id. If a storage backend fails mid-delete the server returns `502 FORGET_BACKEND_FAILED` instead of reporting success: deletes are idempotent, so retry the same call. > **Note: REST forget uses selector/audit_note; the SDKs rename these** The **REST** body accepts `selector` and `audit_note` as shown. The **SDKs** use different names for the same request: the [Python SDK](https://cortexdb.ai/docs/sdks/python#forget) targets by flat keyword (`predicate=`, `memory_ids=`, `reason=`, no `selector`); the [TypeScript SDK](https://cortexdb.ai/docs/sdks/typescript#forget) keeps `selector` but renames `audit_note` → `reason`. ## GDPR erasure (preview → execute) ```bash # Preview (the same confirmation you will execute with) curl -X POST https://api-v1.cortexdb.ai/v1/erasures/preview \ -H "Authorization: Bearer $CORTEXDB_TOKEN" \ -H "X-Cortex-Actor: user:alice" \ -H "Content-Type: application/json" \ -d '{ "scope": "org:acme/user:alice", "confirm_all": true, "audit_note": "DSR #1234 - preview" }' # Execute (202 on acceptance) curl -X POST https://api-v1.cortexdb.ai/v1/erasures \ -H "Authorization: Bearer $CORTEXDB_TOKEN" \ -H "X-Cortex-Actor: user:alice" \ -H "Content-Type: application/json" \ -d '{ "scope": "org:acme/user:alice", "confirm_all": true, "from_preview_id": "ervw_01HX...", "idempotency_key": "erasure-dsr-1234", "audit_note": "DSR #1234" }' ``` An erasure with no `selector.memory_ids` erases the whole scope, so it needs `confirm_all: true` (`422 EMPTY_SELECTOR_WITHOUT_CONFIRMATION` otherwise), and a `from_preview_id` matches only a preview of the same operation. A person's, an outside party's or a whole tenant's erasure has routes of its own: [Erasure and Legal Holds](https://cortexdb.ai/docs/shared-memory/erasure-holds). Backend failures surface as `502 ERASURE_BACKEND_FAILED` (retriable: erasure is idempotent), and an accepted job can still end in status `"failed"` with an `error` field: poll the job status rather than assuming acceptance means completion. ## Lifecycle stream (SSE) ```bash curl -N https://api-v1.cortexdb.ai/v1/lifecycle/stream?scope=org:acme/dept:eng \ -H "Authorization: Bearer $CORTEXDB_TOKEN" \ -H "X-Cortex-Actor: user:alice" \ -H "Accept: text/event-stream" ``` Use the `Last-Event-ID` header on reconnect to resume from where you left off. ## Shared memory routes These are the routes behind [shared memory](https://cortexdb.ai/docs/shared-memory). Each family is listed on `GET /v1/admin/version` under its capability; the guides show each with examples. | Routes | What they do | Guide | |---|---|---| | `POST /v1/access/check`, `/explain`, `/lookup/scopes`, `/lookup/principals`, `GET /v1/access/limits` | Who may read, write or administer what, and why | [Shared Memory](https://cortexdb.ai/docs/shared-memory#ask-the-server-who-may-read-what) | | `POST /access/v1/evaluation`, `/access/v1/search/resource`, `GET /.well-known/authzen-configuration` | The same decisions over AuthZEN 1.0 | [Shared Memory](https://cortexdb.ai/docs/shared-memory#ask-the-server-who-may-read-what) | | `POST /v1/access/changes`, `…/{id}/parts`, `…/{id}/preview`, `…/{id}/activate`, `GET` and `DELETE …/{id}` | Change sets: stage, preview, activate | [Change Sets](https://cortexdb.ai/docs/shared-memory/change-sets) | | `GET /v1/access/watch`, `GET /v1/access/notices`, `POST /v1/access/notices/ack` | Access changes and notices as a feed | [Change Sets](https://cortexdb.ai/docs/shared-memory/change-sets) | | `PUT`, `GET`, `DELETE /v1/directory/{id}`, `GET /v1/directory`, `/scim/v2/*` | The tenant directory and SCIM 2.0 | [Identity and Tokens](https://cortexdb.ai/docs/shared-memory/identity) | | `PUT` and `GET /v1/apps/{id}` | Application records | [Applications and Sources](https://cortexdb.ai/docs/shared-memory/applications-sources) | | `POST /v1/access/rehome`, `PUT` and `GET /v1/access/watermarks`, `POST /v1/access/accounts/resolve` | Source containers | [Applications and Sources](https://cortexdb.ai/docs/shared-memory/applications-sources#sources-and-containers) | | `POST /v1/publish`, `GET /v1/rollups`, `/v1/rollups/{id}`, `/v1/rollups/totals` | Publish and rollups | [Org Trees](https://cortexdb.ai/docs/shared-memory/org-trees#publish-and-rollups) | | `POST /v1/erasures/person`, `POST /v1/erasures/tenant`, `subject` on `POST /v1/erasures` | A person's, a tenant's and an outside party's erasure | [Erasure and Legal Holds](https://cortexdb.ai/docs/shared-memory/erasure-holds) | | `GET /v1/admin/access/report`, `GET` and `PUT /v1/admin/access/tenant-settings`, `POST /v1/admin/access/tenant-binding`, `POST /v1/admin/auth/reload`, `POST /v1/admin/access/restore` | Operator routes | [Operator Modes](https://cortexdb.ai/docs/shared-memory/operator-modes) | | `POST /mcp`, `GET /.well-known/oauth-protected-resource/mcp` | The HTTP MCP server, behind `CORTEX_MCP` | [Connecting AI Assistants](https://cortexdb.ai/docs/connect-assistants#remote-mcp-on-your-server) | The read routes also take `extra_scopes` (up to 40), `coverage`, `mounts`, `purpose` and consistency tokens, and writes take `?consistency=1` to answer a consistency token. ## Capability matrix lookup ```bash curl "https://api-v1.cortexdb.ai/v1/policy/effective?actor=user:alice&scope=org:acme/dept:eng/user:alice" \ -H "Authorization: Bearer $CORTEXDB_TOKEN" \ -H "X-Cortex-Actor: user:alice" ``` > **Note: policy/effective returns flat capability strings** `policy/effective` returns a flat list of granted capability strings: it does not attach a per-capability tier or reason. See [Policy](https://cortexdb.ai/docs/api-reference/policy). ## Versioning and SDK compatibility The **API surface is the contract, not the server build.** Every route lives under **`/v1`**, and the clients are versioned **independently** of the server: their release numbers do not track the server's. A current client works against older servers and the managed cloud, because they all speak the same `/v1` surface. New request fields are the exception: each belongs to a **capability** listed by `GET /v1/admin/version`, and a server that doesn't list it refuses the field with `422 INVALID_BODY`. Gate on the capability list, never on the version string. The releases below are the ones made for 0.16.1. Releases older than those made for 0.14.0 predate shared memory and reach none of its routes. | Client | Package | Current release | Speaks | |---|---|---|---| | [Python SDK](https://cortexdb.ai/docs/sdks/python) | `cortexdbai` | 0.15.0 | `/v1` | | [TypeScript SDK](https://cortexdb.ai/docs/sdks/typescript) | `cortexdbai` (npm) | 0.13.0 | `/v1` | | [CLI](https://cortexdb.ai/docs/sdks/cli) | `cortexdb-cli` | 0.9.0 | `/v1` | | [MCP server](https://cortexdb.ai/docs/sdks/mcp-server) | `cortexdb-mcp` | 0.11.0 | `/v1` (38 tools in the default profile) | | [Connectors](https://cortexdb.ai/docs/connectors) | `cortexdb-connectors` (`cortexdb-sync`) | 0.3.0 | `/v1` | The Python SDK, the CLI and the connectors need Python 3.10 or newer; the TypeScript SDK runs on Node.js 18 and newer. The SDKs, the CLI and the connectors are Apache-2.0; `cortexdb-mcp` is MIT. The Python package is `cortexdbai`: a package named `cortexdb` belongs to an unrelated project. > **Note: The one real cliff: pre-v1 client releases** Client releases from **before the v1 cutover** call retired v0 routes (`POST /v1/remember`, `POST /v1/recall_memories`), which answer `404`. The worst offender is `cortexdb-mcp` **0.2.x** (mapped to `/v1/remember` / `/v1/recall_memories`); use a release made for 0.14.0 or later. In the other direction a newer client against an older server is fine, as long as you don't send fields or call routes the server lacks: an older server refuses newer fields (for example `language`, `scripts`, `query_variants`) as unknown fields with `422 INVALID_BODY`, and answers a route it does not serve with `404`. To see exactly what a server is running, call **`GET /v1/admin/version`**: it returns the release `version`, the `crate_version`, the `git_sha`, and the `built_at` timestamp: ```bash curl https://api-v1.cortexdb.ai/v1/admin/version # {"built_at":"2026-09-28T23:39:36+04:00","capabilities":["blob_text_decode_v1", …],"crate_version":"X.Y.Z","git_sha":"b12cf75…","version":"vX.Y.Z"} ``` ## Health ```bash curl https://api-v1.cortexdb.ai/v1/admin/health # {"status":"healthy","version":"vX.Y.Z"} ``` (Unauthenticated.) Health is a pure liveness check: it always returns `200` while the process is up, and returns only `status` and `version` (with a `v` prefix). Containers and orchestrators should probe **readiness** instead: `GET /v1/admin/ready` returns `200` when the data dir and storage handles are usable and `503` otherwise, and reports `degraded: true` plus the pinned `embedding_provider` when the server is running on mock embeddings. Unprefixed aliases **`GET /v1/health`** and **`GET /v1/ready`** exist and return the same bodies as the `/v1/admin/*` versions: handy if your probe config can't reach the admin path. ========================================================================================== # MCP Server _The local CortexDB MCP package for Claude, Cursor, Windsurf, VS Code Copilot and any MCP client that starts a local server; the CortexDB server itself also serves remote MCP over HTTP._ Source: https://cortexdb.ai/docs/sdks/mcp-server `cortexdb-mcp` is a small bridge process that exposes CortexDB to any Model Context Protocol client that starts a local server: Claude Desktop, Claude Code, Cursor, Windsurf, VS Code Copilot. It speaks MCP over stdio on the person's computer and calls your CortexDB server's REST API. > **Note: Remote MCP: the server serves /mcp itself** For an MCP client that connects to a server by URL instead, including connector apps such as ChatGPT and Claude, the CortexDB server serves MCP over HTTP at `/mcp`, with OAuth sign-in (`CORTEX_MCP=on`, off by default). See [Connecting AI Assistants](https://cortexdb.ai/docs/connect-assistants). > **Note:** Requires Python 3.10+. `cortexdb-mcp` doesn't install on Python 3.9: pip refuses with "Requires-Python >=3.10". macOS users on Apple's bundled Python 3.9 need a newer interpreter first: `brew install python@3.11` (then `python3.11 -m pip install …`), or use `pipx` / `uv` which manage their own Python. ## Installation ```bash # pip (any Python 3.10+ venv) pip install 'cortexdb-mcp>=0.11.0' # pipx: recommended on macOS/Linux; auto-isolates the install pipx install --python python3.11 'cortexdb-mcp>=0.11.0' # uv: fastest; pulls its own Python if needed uvx --python 3.11 cortexdb-mcp --help ``` The PyPI package is **`cortexdb-mcp`**. The current release is listed in [Versioning and SDK compatibility](https://cortexdb.ai/docs/sdks/rest-api#versioning-and-sdk-compatibility); if you run an older one, see [Upgrading](https://cortexdb.ai/docs/self-hosting/upgrading#clients). Verify it's on your PATH: ```bash cortexdb-mcp --version # cortexdb-mcp 0.11.0 cortexdb-mcp --help ``` The binary takes two options. `--transport` accepts only `stdio`: this package runs next to the assistant (for an HTTP endpoint, use the server's own [`/mcp`](https://cortexdb.ai/docs/connect-assistants#remote-mcp-on-your-server)). `--tool-profile all|read|write|code` (or `CORTEXDB_TOOL_PROFILE`) selects the tool surface; see [Tool profiles](#tool-profiles). Against a server that lacks a tool's route, that tool answers `404`. > **Note: Windows: use the full .exe path** On Windows, use the full path to `cortexdb-mcp.exe` (e.g. `%LOCALAPPDATA%\Programs\Python\Python313\Scripts\cortexdb-mcp.exe`) in the MCP config: Windows MCP clients don't resolve bare command names through PATH reliably. ## Setup Every MCP client uses a JSON config file. The structure is the same everywhere, only the file path differs. There are three ways to set it up. ### Option A: CortexDB Cloud Create an API token on your [dashboard](https://cortexdb.ai/dashboard), which also shows your actor and default scope, and give the server all four: ```json { "mcpServers": { "cortexdb": { "command": "cortexdb-mcp", "env": { "CORTEXDB_URL": "https://api-v1.cortexdb.ai", "CORTEXDB_API_KEY": "", "CORTEXDB_ACTOR": "user:acct_42", "CORTEXDB_SCOPE": "org:acct_42/user:acct_42" } } } } ``` The token lasts 90 days; replace it with a new one from the dashboard. Every tool call counts against your [plan](https://cortexdb.ai/docs/cloud/plans). With no `CORTEXDB_API_KEY` the server tries an anonymous `POST /v1/auth/signup` against `CORTEXDB_URL` instead; CortexDB Cloud has signup off (its accounts come from cortexdb.ai), and a self-hosted server only allows it with its dev minter on, so set the key. ### Option B: Bring your own token (your own IdP) Set these env vars so the server skips signup and uses the credentials you supply: - **`CORTEXDB_API_KEY`**: The bearer credential: a person's or an agent's token minted via `POST /v1/auth/tokens`, or a token from your identity provider through the server's [issuers file](https://cortexdb.ai/docs/shared-memory/identity#external-issuers). - **`CORTEXDB_ACTOR`**: Sent as `X-Cortex-Actor`. Optional: left unset, it is the token's `sub` when that names an actor (`user:`, `agent:`, `service:`, `system:`). Set `CORTEXDB_ACTOR=-` for an identity provider's token whose issuer maps the subject itself; the server takes it alone. - **`CORTEXDB_SCOPE`**: The default scope path tools use when one isn't passed explicitly. Optional when signup supplied one; otherwise required (a tool call without a scope fails with `no scope configured`; it does not fall back to the actor). ### Option C: Self-hosted server Point `CORTEXDB_URL` at your server and supply the server's key as the bearer. `CORTEXDB_SCOPE` is required here (a self-hosted server normally has no signup to derive one from); a tool call without a scope fails with `no scope configured`. ```json { "mcpServers": { "cortexdb": { "command": "cortexdb-mcp", "env": { "CORTEXDB_URL": "http://localhost:3141", "CORTEXDB_API_KEY": "", "CORTEXDB_ACTOR": "user:alice", "CORTEXDB_SCOPE": "user:alice" } } } } ``` On a server started with `CORTEX_INSECURE_NO_AUTH=1`, omit `CORTEXDB_API_KEY` (no `Authorization` header is sent; the server serves each request as the `X-Cortex-Actor` the MCP server sends from `CORTEXDB_ACTOR`, or `user:local` without one) but keep `CORTEXDB_SCOPE`. See [Self-hosting defaults](https://cortexdb.ai/docs/self-hosting/defaults) and the [authorization note on presets](https://cortexdb.ai/docs/concepts/authorization#deployment-presets). > **Note: The operator key under the deny mode** On a `cloud_shared_saas` server the operator key's reads of memories need a break-glass header ([Operator Modes](https://cortexdb.ai/docs/shared-memory/operator-modes)), and every tool that reads answers `BREAK_GLASS_REQUIRED` without one. Prefer a person's own token. For genuine operator work, set `CORTEXDB_BREAK_GLASS_REASON` (`incident`, `legal`, `support`, `security`, `migration`, `restore` or `other`) and `CORTEXDB_BREAK_GLASS_TICKET` (your case reference); every request then carries the header and is audited. ## Local state The server stores its credentials (and only its credentials) under: - **macOS / Linux:** `$XDG_CONFIG_HOME/cortexdb-mcp/state.json` (default `~/.config/cortexdb-mcp/state.json`) - **Windows:** `%APPDATA%\cortexdb-mcp\state.json` The file is mode `0600` on POSIX. Contents: `{ "token", "actor", "scope", "expires_at" }`; the values `POST /v1/auth/signup` returned (`user_id` is stored as `actor`; `expires_at` when the mint reported one, used to sign up again on expiry). No memories are stored locally. It is only read when `CORTEXDB_API_KEY` is unset; an explicit env key always wins. Delete the file to force a re-signup on the next call. > **Note: This path and key set differ from the CLI's state file** The MCP server reads `/cortexdb-mcp/state.json`, while the CLI and connectors use `~/.cortexdb/state.json`: and the CLI writes the actor under `user_id`, not `actor`. Reusing one anonymous identity across both tools means copying the file to the other tool's path **and renaming `user_id` ↔ `actor`**: see [CLI configuration](https://cortexdb.ai/docs/sdks/cli#configuration). ## Per-client configuration The JSON blocks below show a token in the `env` block (Options A and B). For a self-hosted server use the Option C env block instead. ### Claude Desktop macOS: `~/Library/Application Support/Claude/claude_desktop_config.json` Windows: `%APPDATA%\Claude\claude_desktop_config.json` ```json { "mcpServers": { "cortexdb": { "command": "cortexdb-mcp", "env": { "CORTEXDB_API_KEY": "v4.public.eyJpc3MiOi...", "CORTEXDB_ACTOR": "user:acct_", "CORTEXDB_SCOPE": "org:acct_/user:acct_" } } } } ``` ### Claude Code (CLI) ```bash claude mcp add cortexdb \ -e CORTEXDB_URL=https://api-v1.cortexdb.ai \ -e CORTEXDB_API_KEY=v4.public... \ -e CORTEXDB_ACTOR=user:acct_ \ -e CORTEXDB_SCOPE=org:acct_/user:acct_ \ -- cortexdb-mcp ``` The server's name comes first: `-e` takes several values, so a name written after the `-e` flags is read as one more variable (and the command fails with `missing required argument 'commandOrUrl'`). Everything after `--` is the server's own command line, so `-- cortexdb-mcp --tool-profile write` adds the write tools. Add `--scope user` to make the server available in every project, or `--scope project` to write it to a shareable `.mcp.json` in the repository root. Without `--scope`, Claude Code stores the entry in `~/.claude.json` (local scope, this project only). To edit by hand, put the same `mcpServers` block into `.mcp.json` (project) or `~/.claude.json` (user/local). For the server's own remote MCP endpoint, Claude Code takes the URL and a header instead: `claude mcp add --transport http cortexdb https://memory.acme.example/mcp --header "Authorization: Bearer "` ([Connecting AI Assistants](https://cortexdb.ai/docs/connect-assistants#remote-mcp-on-your-server)). ### Cursor Edit `~/.cursor/mcp.json`: ```json { "mcpServers": { "cortexdb": { "command": "cortexdb-mcp", "env": { "CORTEXDB_URL": "https://api-v1.cortexdb.ai", "CORTEXDB_API_KEY": "v4.public...", "CORTEXDB_ACTOR": "user:acct_", "CORTEXDB_SCOPE": "org:acct_/user:acct_" } } } } ``` ### Windsurf Edit `~/.codeium/windsurf/mcp_config.json` (same `mcpServers` block as Cursor). ### VS Code (GitHub Copilot) Add to `.vscode/mcp.json` (project) or `~/.vscode/mcp.json` (global). Note the key is `servers`, not `mcpServers`: ```json { "servers": { "cortexdb": { "command": "cortexdb-mcp", "env": { "CORTEXDB_URL": "https://api-v1.cortexdb.ai", "CORTEXDB_API_KEY": "v4.public...", "CORTEXDB_ACTOR": "user:acct_", "CORTEXDB_SCOPE": "org:acct_/user:acct_" } } } } ``` ## Tools exposed The default profile, `all`, lists **38 tools**; `write` lists 43, `read` 31 and `code` 4. The server also registers 3 resources (`cortexdb://health`, `cortexdb://episodes`, `cortexdb://insights`) and 5 prompts. A tool refuses an argument it does not take, and every tool carries MCP annotations (`readOnlyHint`, `destructiveHint`, `idempotentHint`), so a client can ask before a destructive call. > **Note: Matched spans and code citations** - **`memory_search` shows matched document spans.** For a long (chunked) document the reply ends with `--- N matched document span(s) ---`: one line per chunk a retrieval channel matched, with the event id, the channel (`bm25` or `vector`) and the section path, for example `evt_… [bm25] Handbook > VPN troubleshooting: …`. Needs server capability `matched_fragments_v1`; short memories, and servers without that capability, show nothing extra. When the server serves an excerpt of the document, the span line names the section but carries no span text. - **Code tools** describe citations as `repo:path@#Lstart-Lend` (the hash covers the snippet, not a git commit) and label call-graph nodes by their qualified C++ name (`buffered_file::close`). Every tool that takes a scope accepts it as `tenant_id` (a legacy name: it is a v1 scope path) and falls back to `CORTEXDB_SCOPE`. ### Memory | MCP tool | v1 endpoint | Notes | |---|---|---| | `memory_store` | `POST /v1/experience` | Wraps free-form text in a `conversation` envelope with a fresh `idempotency_key` (or the one you pass); `source` / `episode_type` become `source:` / `type:` labels; `namespace` appends `/ns:` to the scope; `provenance` names the events it was made from; `consistency` returns a token to read the write back with. `ttl_seconds` is accepted but **ignored** (the reply says so). Returns `captured` immediately, it does not wait for indexing, and names where a redirected write landed (`redirected_to`). | | `memory_status` | `GET /v1/experience/status` | Did a store land? Check by `event_id` or `idempotency_key` (keys are kept 24 h) after a timeout. | | `memory_search` | `POST /v1/recall` | Sends `view` only when `CORTEXDB_VIEW` is set, so the server picks (holistic, or granular at a shared org-tree scope); `diagnostics="none"` so free-tier tokens succeed. Takes `extra_scopes` (up to 40), `coverage`, `at_least`, `purpose` and `session`. On a live voice call, pass `profile="voice"` and the call's `session` (see [Voice calls](#voice-calls)). Shows the first `max_results` memories from the pack's `context_block`, falling back to derived facts. | | `get_context` | `POST /v1/recall` | Same call, rendered as memories + facts + beliefs for "what should I know before I respond". `include_graph` only adds a hint line. | | `advanced_search` | `POST /v1/recall` | `time_range_start` / `time_range_end` become a `temporal` window; `source` / `episode_type` filter on labels; `limit` / `offset` page the results. | | `memory_list` | `GET /v1/events` | Scope-aware list of raw events, newest first; pages by `cursor` (each page ends with `More: cursor=`); `episode_type` filters on the `type:` label. | | `memory_get` | `GET /v1/events/{id}` | Single event by id; `tenant_id` is sent as `?scope=`, the event's exact scope. | ### Deleting | MCP tool | v1 endpoint | Notes | |---|---|---| | `forget_preview` | `POST /v1/forget/preview` | Dry run: per-layer estimated counts plus a `fpvw_…` preview id. Same selector rules as the delete tools. | | `memory_forget` | `POST /v1/forget` | `query` → `selector.about_subject`; no `query` → whole-scope `confirm_all=true`. Pass `from_preview_id` from `forget_preview` for the two-phase flow. Always `cascade: derived_only`: it deletes derived records (facts, beliefs, episodes, understanding) and keeps the memories; use `memory_delete` or `forget_by_key` to delete memories. | | `memory_bulk_delete` | `POST /v1/forget` (+ `/v1/forget/preview` when `dry_run=true`) | Subject-targeted delete by `query`; `dry_run` previews instead. | | `memory_delete` | `POST /v1/forget` | Selector preset for one `memory_ids=[…]`. | ### Knowledge graph and beliefs | MCP tool | v1 endpoint | Notes | |---|---|---| | `entity_list` | `GET /v1/facts` | Distinct fact subjects in the scope (synthetic subjects filtered out). | | `entity_get` | `GET /v1/facts?subject=` | Facts filtered to one subject (`predicate -> object` lines). | | `entity_edges` | `GET /v1/facts?subject=` | Same query, rendered as `subject --[predicate]--> object`. | | `entity_link` | `POST /v1/experience` | Records a "X relates to Y" sentence for the LLM extractor to turn into a fact. | | `belief_declare` | `POST /v1/beliefs` | Writes a belief record directly (`statement`, `confidence`, optional `supports` event/fact ids, `subject`, `predicate`). A newer belief on the same subject+predicate closes the previous one. | | `list_conflicts` | `GET /v1/conflicts` | Detected contradictions for a scope (`status=open` default, or `all`). | | `resolve_conflict` | `POST /v1/conflicts/{id}/resolve` | `pick` (needs `winner`) / `split` (`boundary`, `earlier`, `later`) / `new_information` (`record`) / `dismiss`. Wrong or missing fields are rejected client-side with the expected list. | | `claim_history` | `GET /v1/claims/history` | Full bi-temporal change-log of one subject+predicate claim, with any conflicts on it. | ### Access, rollups, notices and the directory | MCP tool | Profile | v1 endpoint | Notes | |---|---|---|---| | `access_check` | all, read, write | `POST /v1/access/check` | Can a principal read, write or own a scope or a memory? ALLOWED or DENIED with the link that decided. Your own token by default, or another principal for an Owner of the scope | | `access_explain` | all, read, write | `POST /v1/access/explain` | Why, link by link | | `rollups` | all, read, write | `GET /v1/rollups` | A team's rollups: typed totals and synthesis items | | `notices` | all, read, write | `GET /v1/access/notices?mine=true` | Your own unacknowledged notices: who read what of yours, when and why | | `acknowledge_notices` | all, read, write | `POST /v1/access/notices/ack` | Acknowledges them; changes no memory | | `directory_lookup` | all, read, write | `GET /v1/directory` | People and named scopes by name or email prefix, with only the fields you may read | | `publish` | write | `POST /v1/publish` | A person copies a memory they are served into a wider scope they write | | `forget_by_key` | write | `POST /v1/forget` | Forgets memories by their idempotency keys or capture labels, reading nothing first, with a preview | ### Governed memory Seven tools cover [governed memory](https://cortexdb.ai/docs/features/governed-memory): why a memory is held, what CortexDB may learn, and fixing what it learned wrongly. The four read tools are in every profile but `code`. The three write tools are opt-in (`--tool-profile write`) and annotated destructive, so a client asks before it calls them. | MCP tool | Profile | v1 endpoint | Notes | |---|---|---|---| | `memory_why` | all, read, write | `GET /v1/facts/{id}?include=derivation`, `GET /v1/beliefs/why?include=derivation`, `GET /v1/derivation/decisions` | Why a fact or belief is held and how it was made, or what CortexDB learned from one memory (`fact_…`, `belief_…` or `evt_…`). A rejected candidate is only counted, by the rule that rejected it | | `derivation_policy` | all, read, write | `GET /v1/derivation/policy` | What CortexDB learns at a scope and what it will not, and who set each rule; `include_texts` adds the instructions and examples, for an Owner | | `memory_about` | all, read, write | `GET /v1/memory/about` | What is known about a subject: each fact and belief with its id and sources; `include_corrections` adds the scope's corrections | | `review_list` | all, read, write | `GET /v1/review` | The candidates a policy held for review: what each states, the rule that held it, when it lapses | | `memory_correct` | write | `POST /v1/corrections` | `action` `reject`, `replace` (with `value` and `valid_from`), `pin` or `confirm` on a `fact_id`; `bind` widens a `reject`. The way to fix a wrong memory: a forget of derived memory can be learned again | | `correction_undo` | write | `DELETE /v1/corrections/{id}` | Undoes a correction, for its author, an Owner of its scope or the operator | | `review_decide` | write | `POST /v1/review/decisions` | `approve` or `reject` up to 100 `held_ids`; a rejection leaves a correction that keeps the claim from being learned | `memory_search`, `get_context` and `advanced_search` also take `session`, the conversation session a read is made in: where an opt-in read-time use rule is in force, memory from other sessions is withheld. All three send it to `/v1/recall`, which on a server without the capability answers `422 INVALID_BODY`, so pass `session` only to a server whose `GET /v1/admin/version` lists `derivation_use_rules_v1`. Of these seven, all but `memory_why` take the scope as `scope`, not `tenant_id`, unlike the other tools. An agent that fixes a memory and then undoes the fix sends these two calls (each object is a `tools/call` request's `params`): ```json [ {"name": "memory_correct", "arguments": {"action": "replace", "fact_id": "fact_0196…", "value": "Denver", "valid_from": "2026-03-01"}}, {"name": "correction_undo", "arguments": {"correction_id": "cor_0196…"}} ] ``` > **Note: Check the capability first** Against a server without these routes `derivation_policy`, `memory_about`, `review_list` and the three write tools answer `404`, which reads like a missing record; the error's "What to do" line says the server lacks the route. `memory_why` still answers there, without how a fact was made. Check that `GET /v1/admin/version` lists `derivation_provenance_v1`, `derivation_policy_v1`, `corrections_v1` and `derivation_review_v1` (and `derivation_use_rules_v1` before you rely on `session`). A server held at data format 10 answers `503 FORMAT_UPGRADE_PENDING` on most of these routes. The server's own [`/mcp` endpoint](https://cortexdb.ai/docs/connect-assistants#remote-mcp-on-your-server) has `memory_why` and `memory_about` in its `read` profile and `correct` in its `write` profile (`CORTEX_MCP_PROFILE=write`), and its `recall` tool takes `session`; send `session` only where `GET /v1/admin/version` lists `derivation_use_rules_v1`. It has no undo tool: `correct`'s answer names the `DELETE /v1/corrections/{id}` route that undoes it. The routes in full: [Derivation Policies](https://cortexdb.ai/docs/api-reference/derivation-policy), [Corrections](https://cortexdb.ai/docs/api-reference/corrections), [Review](https://cortexdb.ai/docs/api-reference/review), [Re-derivation](https://cortexdb.ai/docs/api-reference/derivation-rederive), [Change Feed](https://cortexdb.ai/docs/api-reference/derivation-feed) and [Memory About](https://cortexdb.ai/docs/api-reference/memory-about). ### Status, usage and helpers | MCP tool | v1 endpoint | Notes | |---|---|---| | `health_check` | `GET /v1/auth/whoami` | Auth + reachability in one call: caller, tenant, preset, capabilities. | | `get_usage` | `GET /v1/auth/whoami` | Same call plus the `X-RateLimit-Limit` and `X-Cortex-Token-Expires-*` response headers. | | `get_insights` | `GET /v1/events`, `/v1/facts`, `/v1/beliefs` (up to 500 each) | Heuristic pass over the scope: contradictions, low-confidence beliefs, key entities, activity spikes, new sources. No recall and no LLM involved. | | `cortexdb_check_call` | none (offline) | Validates a planned HTTP call or SDK snippet before you make it: catches `POST /v1/memories`, `client.remember(...)`, a scope missing its `type:` prefix, a selector combined with `confirm_all`, and returns the correction. | ### Voice calls One tool opens a live voice call on a server in [voice mode](https://cortexdb.ai/docs/features/voice-mode). It is in every profile but `code`, and it changes no memory. | MCP tool | v1 endpoint | Notes | |---|---|---| | `call_brief` | `POST /v1/sessions` | Call once when the call starts, with the call's own id as `session` and, when known, the reason for the call as `query`; also `max_tokens` (default 400) and `idle_timeout_s`. Returns the caller's brief. Then pass the same `session` to `memory_search` with `profile="voice"` on each turn. A server not in voice mode refuses it (`409 VOICE_SESSIONS_DISABLED`); voice searches work there without a session. | ### Code memory Four read-only tools for the [code memory plane](https://cortexdb.ai/docs/features/code-plane); the server must run with `CORTEX_CODE_PLANE=1` or every call returns `503 CODE_PLANE_DISABLED`. Repository registration is an operator action through the API/CLI, not an MCP tool. | MCP tool | v1 endpoint | Notes | |---|---|---| | `code_explore` | `POST /v1/code/context` (one repo) or `POST /v1/code/workspace/context` (several) | Token-budgeted evidence envelope of cited snippets (`repo:path@hash#Lx-Ly`). | | `code_impact` | `GET /v1/code/impact` | Reverse dependency closure of a symbol, `depth` 1 to 6. | | `code_inventory` | `POST /v1/code/symbol/search` or `POST /v1/code/inventory` | `kind` is required: a symbol-prefix search, or a bounded structural inventory (`stats`, files, …). | | `code_graph` | `POST /v1/code/graph/query` | Bounded graph traversal from `roots`, with node/edge budgets. | > **Note: Code tools need the code plane** The four `code_*` tools answer `503 CODE_PLANE_DISABLED` on a server without `CORTEX_CODE_PLANE=1`. > **Note: Entity/Facts tools need enrichment on self-host** `entity_list` / `entity_get` / `entity_edges` / `list_conflicts` / `claim_history` read the Facts layer, which is **empty on a content-only self-hosted instance**: those layers need enrichment configured. `memory_store` / `memory_search` / `memory_list` / `belief_declare` work regardless. See [Self-hosting defaults](https://cortexdb.ai/docs/self-hosting/defaults). ### Resources and prompts The server also registers three MCP **resources**: `cortexdb://health` (`GET /v1/auth/whoami`), `cortexdb://episodes` (the scope's last 50 raw events via `GET /v1/events`) and `cortexdb://insights` (the same heuristic pass as `get_insights`), and five **prompts**: `investigate_incident(topic)`, `summarize_knowledge(topic)`, `deployment_review(service)`, `onboard_to_codebase(repo)` and `weekly_digest(tenant_id?)`. The prompts are plain instruction templates; they make no API calls themselves. ### Tool profiles | Profile | Tools | |---|---| | `all` (default) | Every memory, access, voice and code tool but the opt-in writes (38) | | `write` | `all`, plus the opt-in writes `publish`, `forget_by_key`, `memory_correct`, `correction_undo` and `review_decide` (43) | | `read` | Only the tools that write no memory (31; `acknowledge_notices` changes only your notices and `call_brief` only opens a call) | | `code` | `code_explore`, `code_impact`, `code_inventory`, `code_graph` (4) | Select one with `--tool-profile` or `CORTEXDB_TOOL_PROFILE`. A tool outside the profile is removed from the listing and cannot be called. Resources and prompts are registered under every profile. ## Configuration Reference | Environment variable | Default | Notes | |---|---|---| | `CORTEXDB_URL` | `https://api-v1.cortexdb.ai` | v1 endpoint. With no `CORTEXDB_API_KEY`, anonymous signup is attempted against this URL (any host). | | `CORTEXDB_API_KEY` | (none) | Any bearer: a person's or an agent's token, an identity provider's token, or, self-hosted, the server's `CORTEX_API_KEY` value. Unset → the cached state file, then anonymous signup. | | `CORTEXDB_ACTOR` | the token's `sub` | Sent as `X-Cortex-Actor`; must match the token's `sub`. `-` sends none (an identity provider's token whose issuer maps the subject). | | `CORTEXDB_SCOPE` | (none) | Default scope for tools that don't take an explicit one; set automatically by signup. Required otherwise. | | `CORTEXDB_VIEW` | (unset: the server's default) | Recall reach for `memory_search` / `get_context` / `advanced_search`: `holistic`, `descend`, or `granular`. At a shared org-tree scope only `granular` and `raw` are allowed. | | `CORTEXDB_TOOL_PROFILE` | `all` | `all`, `read`, `write` or `code`, as `--tool-profile`. | | `CORTEXDB_SUBJECT_TOKEN` | (none) | With the operator key: a person's token, sent as `X-Cortex-Subject-Token`, so the server counts what that person would be refused (a dry run of moving off the key). | | `CORTEXDB_BREAK_GLASS_REASON`, `CORTEXDB_BREAK_GLASS_TICKET`, `CORTEXDB_BREAK_GLASS_NOTE` | (none) | With the operator key under the `deny` mode: every request carries `X-Cortex-Break-Glass` built from them. | | `CORTEXDB_PURPOSE` | (none) | The `purpose` reads declare unless a call names its own. | | `CORTEXDB_TENANT_ID` | (none) | Legacy tenant id (v0 callers only). | | `CORTEXDB_TIMEOUT` | `30.0` | HTTP request timeout (seconds). | The wheel also carries a small FastAPI app (`uvicorn cortexdb_mcp.api:app`) that serves the insights pass as `GET /api/insights` for a dashboard. It is not part of the MCP surface. ## Architecture ```text Your Machine CortexDB ┌──────────┐ stdio ┌───────────┐ HTTPS ┌──────────┐ │ Cursor / │ ◄─────────► │ cortexdb- │ ◄─────────► │ v1 API │ │ Claude / │ MCP JSON │ mcp │ REST │ server │ │ VS Code │ │ (bridge) │ │ │ └──────────┘ └───────────┘ └──────────┘ ``` The bridge process holds the bearer token in memory, injects `Authorization` and `X-Cortex-Actor` headers on every call, and translates MCP tool invocations into v1 HTTP requests. Nothing is stored locally except the credentials. ## Next steps - [Python SDK](https://cortexdb.ai/docs/sdks/python): programmatic access, `V1Client` + `AsyncV1Client`. - [TypeScript SDK](https://cortexdb.ai/docs/sdks/typescript): Node.js and browser apps. - [Auth](https://cortexdb.ai/docs/api-reference/auth): how tokens, actors, and capabilities fit together. - [API Reference](https://cortexdb.ai/docs/api-reference/recall): endpoint-by-endpoint reference. ========================================================================================== # POST /v1/experience _Capture an experience envelope: the single write path for events._ Source: https://cortexdb.ai/docs/api-reference/experience (Request/response shapes are generated from the pinned OpenAPI spec on the live site.) ## Required fields > **Note: Only scope, modality, content are required** The three required fields are **`scope`, `modality`, `content`**. `context`, `context.observed_at`, and `idempotency_key` are **optional**: the server returns `202` without them (omitting any of the three required fields → `422`). ## Wait semantics > **Note: Omitted ?wait= returns captured, not fully indexed** With `?wait=` omitted the write returns **`status: captured` (202)**: the event is in the WAL and read-your-writes holds on recall, but it is **not yet indexed**. Pass `?wait=indexed` to block until BM25 + HNSW have the event, `?wait=consolidated` to block on consolidation. `?wait=accepted` is an explicit alias for the omitted default, and `?wait=captured` blocks only until the WAL append; any other value `422`s listing the valid set (`accepted, captured, indexed, consolidated, settled`). Every response includes `replayed_from_idempotency`; the `lifecycle_stream` URL comes only with the async `202` response, not with a waited `200`. > **Note: Use wait=indexed on a single-node server** `wait=settled` needs a coordinator process with artifact workers; the default single-node server answers it with `503 SETTLEMENT_UNAVAILABLE`. Use `wait=indexed`. The same release added a second request body shape on this route, `NativeCaptureRequestV1`, plus `POST /v1/experience/resume` and a `POST` form of `/v1/experience/status`; all three belong to the **native memory host** profile. On the default router `POST /v1/experience/resume` is `404` and `POST /v1/experience/status` is `405` (the `GET` form above is served): see [Native memory host](https://cortexdb.ai/docs/api-reference/admin#native-memory-host). ## Wait deadline and 408 WAIT_TIMEOUT A waiting capture has **one** budget. When it runs out the server answers **`408 WAIT_TIMEOUT`** (`retriable: true`). The event is already captured and durable, and indexing carries on in the background. - **Single capture** (`?wait=indexed` or `consolidated`): about **30 s**, shared by the wait for the indexer to reach the event and the wait for the requested stage after it. `details` says what it waited for: ```json { "error_code": "WAIT_TIMEOUT", "retriable": true, "details": { "event_id": "evt_01a0e9fbdebf7d50bbacdfa90dcab9fc", "status_url": "/v1/experience/status?event_id=evt_01a0e9fbdebf7d50bbacdfa90dcab9fc", "target_stage": "indexed", "waited_ms": 30004, "waiting_on": "indexer" } } ``` `waiting_on` is `indexer` (the indexer had not reached the event) or `stage` (indexed, but not yet at the requested stage). - **Bulk** (`/v1/experience/bulk?wait=indexed|consolidated`): **`min(30 s + 1 s per item, 600 s)`**, and it covers the batch's own inline indexing as well. A two-item batch answers after 32 s with `details { batch_id, target_stage, waited_ms, waiting_on: "indexing", items, event_ids }`; `waiting_on: "stage"` carries `accepted` instead of `items`. **`event_ids`** lists the batch's events in item order, the same list a `200` returns. - **After a 408**, poll `status_url`, or `GET /v1/experience/status?event_id=` for each id in `event_ids`. Don't re-send blindly: a re-send replays (never duplicates) only a capture or bulk item that carried its **own `idempotency_key`**. One sent without a key gets a key the server mints and never returns, so re-sending it writes it again. **Send an `idempotency_key` on every capture that waits**, bulk items included. > **Note: No status is not proof the write was lost** A status lookup that has no record of a write (for example `found: false` after a timeout and a restart) means the server no longer holds its **receipt**, not that the event is missing: the write can be stored and recallable all the same. Before re-sending, look for the event itself: 1. `GET /v1/events/{event_id}?scope=` with the `event_id` the write returned (see [GET /v1/events](https://cortexdb.ai/docs/api-reference/events#reading-one-event-in-one-scope)), or, if you never got an id, recall something only that write contains. 2. Re-send only when the event isn't there. A re-send with the write's own `idempotency_key` replays instead of writing twice; one without a key writes again. The status answer says it outright in `resend`, and a lookup by `event_id` reads the stored write, so it answers the same after a restart: | `resend` | When | What to do | |---|---|---| | `no` | the write is stored | Never re-send. | | `new_key` | `status: "failed"` | Re-send the data under a new idempotency key. | | `if_sent_within_24h` | `found: false` by `idempotency_key` | Receipts last 24 hours: re-sending is safe for a write sent within them; for an older one, look the write up first. | | `check_first` | `found: false` by `event_id` | No stored write you can see under that id (erased, forgotten or not visible). Don't re-send on this answer. | - A bulk sent with no `wait` has no deadline, as before: it still indexes its batch before it answers `202`, so a slow embedding provider delays that answer by as long as its calls take. ## Source descriptor An optional `source` object (schema version 2) records the authoritative source and exact fragments the envelope represents: `source_id`, `content_kind`, a `sha256:`/`blake3:` fingerprint of the bytes, and per-fragment locators (`document` page, `conversation` turn, `code` file and lines, and so on). It is stored verbatim and echoed on reads. `source.modality` must equal the envelope `modality` or the write is `422 INVALID_ENVELOPE`; unknown locator fields are `422 INVALID_BODY`. Field reference and example: [Experience Envelope](https://cortexdb.ai/docs/concepts/experience-envelope#source-descriptor). ## Content kinds `content.kind` is one of `message`, `text`, `json`, `blob_ref`, `triple`. A **triple** is nested under `content.triple` (a flat `subject`/`predicate`/`object` directly in `content` → `422 "missing field triple"`), and its `object` is a full struct: `type` + `datatype` + `value`: ```json { "kind": "triple", "triple": { "subject": { "type": "entity", "id": "ent_acme" }, "predicate": "seats", "object": { "type": "literal", "datatype": "string", "value": "200" } } } ``` Omitting `datatype` → `422 "missing field datatype"`. A triple capture writes its fact directly, with no enrichment and no LLM call: the extraction model never sees it, whatever `directives.extract` says. With `?wait=indexed` the fact is on [`GET /v1/facts`](https://cortexdb.ai/docs/api-reference/facts) as soon as the write returns, with or without enrichment. ## Language, time zone and referenced times Three optional hints, each gated on a capability in [`GET /v1/admin/version`](https://cortexdb.ai/docs/api-reference/admin) `capabilities[]`: - **`language`** (BCP-47, e.g. `hi-Latn`) and **`scripts[]`** (ISO 15924, at most 8), capability `capture_language_v1`. Values are canonicalized (`HI-latn` is stored as `hi-Latn`, `latn` as `Latn`). A malformed tag or more than 8 scripts → `422 INVALID_ENVELOPE`. - **Every event gets one language tag.** Your `language` wins, then a `lang:` label in `context.labels`, then detection: Devanagari text is stored as `und-Deva`, and Latin-script Hinglish as `hi-Latn`. Event reads and recall items return `language`, `scripts` and `language_source` (`hint`, `source`, `label` or `detected`). An event that is English by default stores no tag, so it reads back exactly as before; an explicit `"language": "en"` is stored. - **`context.timezone`**: an exact IANA zone name. `Asia/Kolkata` and the older alias `Asia/Calcutta` work; `IST`, `+05:30` and `Asia/Mumbai` → `422 INVALID_ENVELOPE`. - **`context.refers_to[]`** (capability `refers_to_v1`): the dates or times the memory talks about, as local dates (`YYYY-MM-DD`) or date-times without an offset, in `from`, `to` or `candidates[]`, with an optional `zone` and `precision`. Recall can boost them with `temporal.refers_during`. A phrase such as `"next friday"` → `422 INVALID_ENVELOPE`. None of these is part of the write identity. A retry with the same `idempotency_key` and body but different hints replays the first write (the first write's hints win) and adds `warnings: ["conflicting_hint_on_replay: …"]` to both the `202` and a waited `200`. > **Note: Gate new fields on capabilities, not on the version** A server that does not list a capability refuses its fields with `422 INVALID_BODY` (as unknown fields). Check `capabilities[]` before sending `language`, `scripts`, `context.timezone` or `context.refers_to`. ## Text blobs A `blob_ref` capture of a text blob decodes the bytes by byte-order mark, a declared `charset=`, or strict UTF-8 (capability `blob_text_decode_v1`). Bytes that are none of these fail the write with **`422 BLOB_TEXT_ENCODING_UNKNOWN`** (`retriable: false`; `details { blob_id, content_type, reason, charset }`, e.g. `reason: "undeclared_non_utf8"`). Declare the charset on upload (`Content-Type: text/plain; charset=windows-1252`) and the same bytes decode correctly. In `/v1/experience/bulk` one such blob fails the whole batch, and none of its items is stored. The event records the blob it came from in `source_blob_ids`; forgetting or erasing the event deletes the blob unless another live event still uses it (see [Blobs](https://cortexdb.ai/docs/api-reference/blobs)). ## Errors > **Note: Error codes are UPPERCASE** Error codes are uppercase: `INVALID_BODY` (e.g. a bad scope: must be `type:name` like `org:acme`), `IDEMPOTENCY_CONFLICT` (same key + different body: `409`, `retriable: no`), `POLICY_DENIED`, `RATE_LIMITED`. The error body is flat: `{ "error_code", "message", "retriable", "request_id", "details": { "field_path", "reason", "schema" } }`. `details` is present only when the error has any: `INVALID_BODY` carries it, `INVALID_ENVELOPE` does not. A capture that would register a **new** scope inside a running forget or erasure waits for it (up to `CORTEX_DESTRUCTIVE_LEASE_WAIT_SECS`, default 120 s) and then gets `409 DESTRUCTIVE_OPERATION_IN_PROGRESS` (`retriable: true`, `Retry-After: 5`); nothing was written, so re-sending is safe. Captures into existing scopes never wait. ## Notes - Idempotency keys are scoped to the **scope, actor and key**, with `/v1/experience` and `/v1/experience/bulk` sharing one bucket (a bulk item replays a single write with the same key and body). The same key and body sent to another scope, or by another actor, writes a new event. Keys are at most 64 characters (a longer one → `422 INVALID_ENVELOPE`) and **expire after 24 hours**; a repeat within the window with the same body replays (`replayed_from_idempotency: true`). - An unknown `modality` is stored verbatim (`202`): the field is a free string, not an enum. - **Bulk ingest:** `POST /v1/experience/bulk` (in the spec above) and its alias `POST /v1/experiences` share one handler, with identical validation and response. The body takes `items` (or the alias `experiences`), an array of the same envelopes, plus an optional **`ordering`** string (`strict_temporal` | `batch_throughput`); a non-string value → `422`. An empty array → `422`; the only accepted top-level fields are `experiences`, `items`, and `ordering` (anything else → `422`). The response is a batch envelope: `{ batch_id, accepted, lifecycle_stream, event_ids, results: [{ index, event_id, replayed_from_idempotency }] }`; with `?wait=indexed` it is a `200` that adds `stage: "indexed"`, or a [`408 WAIT_TIMEOUT`](#wait-deadline-and-408-wait_timeout) listing the batch's `event_ids`. - Facts/Beliefs/Understanding extracted from text are derived asynchronously and require enrichment: on a content-only self-host they stay empty (triple captures, above, are the exception). See [Self-hosting defaults](https://cortexdb.ai/docs/self-hosting/defaults). - **`directives.extract` is honored on `POST /v1/experience` and `/v1/experience/bulk`**: the stages are stored on the event and applied when its derived layers are built. `extract` is a list of stage names, not a flag: omitted or `null` runs every stage, `extract: ["beliefs"]` or `["understanding"]` run enrichment, `extract: []` turns it off for the event, and `extract: false` or `"none"` → `422 INVALID_BODY`. `directives.embed` is validated but doesn't change how the event is embedded. ## Governed writes - **`directives.extract` limits learning to the stages it names.** Each stage yields only its own outputs: `entities` gives entities and no facts; `facts` gives facts and no entities; `beliefs` gives facts too, since beliefs are built from them; `understanding` alone extracts nothing; `[]` learns nothing, and the event stays indexed and searchable. An event with a list joins episodes only when the list names `episodes`. An omitted list learns everything. For facts from an entities pass, name both: `["entities", "facts"]`. - **A directive nothing reads says so.** `consolidate_into`, `confidence_floor`, `ttl_for_belief_layer`, `embed` and `async` are accepted, but nothing acts on them: an ack that names one carries `directive_not_enforced:` in its `warnings`. - **`memory:remember`.** Under a [derivation policy](https://cortexdb.ai/docs/api-reference/derivation-policy) in `explicit` mode, enrichment learns only from events labelled `memory:remember` or carrying a non-empty `directives.extract`. - **`derived_by`** (capability `derived_by_v1`): a typed triple written back by your own pipeline carries `derived_by: {name, version}`, served under `include=derivation` and reported by [`GET /v1/derivation/status?derived_by=`](https://cortexdb.ai/docs/api-reference/derivation-status). It is accepted on typed triples only (`422 DERIVED_BY_INVALID` elsewhere). - **Writer rules.** A policy may reserve a field for certain writers: a typed triple, a bulk item or an import row that a writer rule refuses is `409 WRITER_NOT_ALLOWED`, and nothing is stored (in a bulk, only that item fails). See [Writer rules](https://cortexdb.ai/docs/api-reference/derivation-policy#writer-rules). - **Sessions.** Label an event `session:`, or give its source a session locator, when a [read-time use rule](https://cortexdb.ai/docs/api-reference/derivation-policy#read-time-use-rules) may apply: the rule compares each event's session with the read's `session`. ========================================================================================== # POST /v1/recall _Read a stratified pack: layers, context block, provenance, and diagnostics._ Source: https://cortexdb.ai/docs/api-reference/recall (Request/response shapes are generated from the pinned OpenAPI spec on the live site.) ## Views | view | traversal | notes | |---|---|---| | `raw` | single scope | full event payloads | | `granular` (alias `local`) | single scope | all layers, exact scope only | | `holistic` (default) | scope **+ ancestors** | requires `scope.read.holistic` | | `descend` | scope **+ descendants** | requires `scope.read.descend` | | `lineage` | none | supported (was undocumented in v1) | | `structured` | single scope | facts + beliefs only | > **Note: local is accepted** `view: "local"` is accepted on recall and behaves as **`granular`**. ## Behavior notes > **Note: Recall is not cached by idempotency_key** Recall always runs fresh: repeated calls return a new `pack_id` each time, whatever `idempotency_key` you send. Keep a `pack_id` yourself if you need to refer back to a pack. - **Filters** take exactly one field, `metadata`, with attributes `observed_actor`, `caller`, `modality`, `labels`, `intent` (ANDed; values ORed). Unknown attributes → `422`. No confidence filter. - **`exclude_content: true`** nulls large `content`/`summary` strings. - **`budgets.per_layer_limits`** hard-caps each layer (`events: 0` drops the layer). - **`diagnostics`** = `none` (default) / `summary` / `full`. **Timings are reported only for `summary` and `full`**: `time_ms` holds about 47 phase-named keys (`coordinator_recall`, `wal_hydrate`, `recall_total`, …); with `none` it is an empty object. With capability `recall_diagnostics_v1`, `full` also returns per-item ranks, `items[] = { event_id, final_rank, fused_rank, channels: { bm25: {rank, score}, vector: {rank, score} }, matched_via }`, and `channel_lists[] = { channel, len }`, plus `knapsack_evictions`. - **`provenance.trail`** entries are `{ phase, elapsed_ms }` (+ a `context_contributors` list; see [the context receipt](#the-context-receipt-which-events-the-block-renders)). - A body field easy to miss: **`prefer_exhaustive`** (exhaustive candidate sweep). The **`order`** field has its own section below. - Streaming: **`POST /v1/recall/stream`** emits `plan → layer(×N) → context_block → provenance → diagnostics → done` (the `done` event carries `pack_id`). - `pack_id` can be reused by [`POST /v1/answer`](https://cortexdb.ai/docs/api-reference/answer) via `use_pack_id` (same-scope only; cross-scope → `404`). ## Names nothing mentions When a question names a person or company that no memory in the scope mentions, recall returns nothing rather than someone else's memories. It checks names written with a capital letter. So "What did Initrode order?" comes back empty when Initrode is unknown, instead of returning Acme's orders. ## Context block, budgets and long events `context_block` is the text an LLM would see. With capability `budget_excerpt_v1`, **no entry takes it past `budgets.max_tokens`**. Events are placed whole in rank order while they fit; an event that doesn't fit is skipped, and each skipped event then gets the room still free at its rank position: whole if it now fits, otherwise as an **excerpt** of its best-matching chunks. The default budget is **4,000 tokens**, about 14,000 bytes of context (`CORTEX_RECALL_DEFAULT_MAX_TOKENS` changes it). For example, a 15,637-byte document queried for its second section gives a 3,320-byte block at `max_tokens: 1000`, with the excerpt starting at the matched section, and a 13,992-byte block at the default budget. An excerpted event's `layers.events` item carries the same excerpt, marked as a partial view: ```json "content": { "kind": "text", "text": "[…] # Section 2: VPN troubleshooting … […]", "_partial": true, "_partial_reason": "budget_excerpt", "_original_bytes": 15637, "_excerpt_ranges": [{ "start": 3013, "end": 6219 }, { "start": 15564, "end": 15636 }] } ``` Treat `content.text` as the whole text only when `_partial` is absent; `GET /v1/events/{id}` always returns the whole event. Slices are joined with `[…]` markers; `_excerpt_ranges` are byte ranges into the stored text. `CORTEX_RECALL_BUDGET_EXCERPTS=0` (or `off`, `false`) turns excerpts off (the pack then renders whole events). The server then leaves `budget_excerpt_v1` out of [`capabilities[]`](https://cortexdb.ai/docs/api-reference/admin#version-and-capabilities) and logs `RECALL_BUDGET_EXCERPTS_DISABLED` at startup, so a client that gates on the name knows excerpts are off. For every language, English included: an assistant turn's `In reply to user: …` echo is dropped when that user turn is rendered in the same block; an event too large for the remaining budget does not end the block; and the first-ranked event gets no exception: it is excerpted like any other when it does not fit. ### Matched fragments For a long (chunked) event, `layers.events[].matched_fragments[]` (capability `matched_fragments_v1`) says which chunks matched: `{ chunk_id, byte_range: {start, end}, matched_via: "bm25" | "vector", locator: { kind: "document", section_path: [title, heading] }, language, text_source }`. Byte ranges index the stored text, not an excerpt. `section_path` holds the Markdown headings in force where the chunk starts: the first `#` heading acts as the document title and later headings follow it. `GET /v1/admin/events/{id}/chunks` shows how any event was chunked. ### The context receipt: which events the block renders The provenance entry `{ "phase": "context_contributors", "context_contributors": [{ "event_id", "rank" }] }` names every event `context_block` renders, including one the cross-layer knapsack evicted from `layers.events` (that row carries `evicted_from_layers: true` and is the only place the response names it). > **Note: Converting receipt ids** `context_contributors[].event_id` is a hyphenated UUID (`01a0e70c-81fd-7cc2-b687-4e42ed600f50`), while `layers.events[].id` and the event routes use `evt_01a0e70c81fd7cc2b6874e42ed600f50`. To match an entry or fetch the event, strip the hyphens and prefix `evt_`. ## Who said it: recalled event identity Every `layers.events` item carries the identity its event was captured with: `caller`, `observed_actor`, `subject`, `scope_key`, `scope` and `wal_offset` are the values [`GET /v1/events/{id}`](https://cortexdb.ai/docs/api-reference/events) returns, in every view: - A `filters.metadata.observed_actor` recall keeps events captured on someone else's behalf. - `scope_key` is the billing partition the event was captured under (`default` for the static operator key), not its scope. Compare `scope` when you need the scope. A capture cancelled with [`POST /v1/lifecycle/memory-event/{id}/cancel`](https://cortexdb.ai/docs/api-reference/lifecycle#per-event-summary-and-cancel) is left out of every view: `granular`, `raw`, `holistic`, `descend`, `prefer_exhaustive` and `order: "recency"`. ## Ordering: relevance vs recency The `order` field switches how the **events layer** is selected and rendered: | `order` | Selection | Rendering | |---|---|---| | `relevance` (default) | ranked retrieval (BM25 + vector + RRF), scored against the query | ranked order | | `recency` | the scope's **newest** eligible events by `observed_at`: a timeline tail | **newest-first** | `recency` replaces ranked retrieval for the events layer with a timeline tail: the newest eligible events by `observed_at`, capped by `budgets.per_layer_limits.events` (else `CORTEX_RECENCY_TAIL_EVENTS`, default `100`). Eligibility (scope/tenant, filters, temporal) is identical to ranked mode: only *selection* changes. It's built for "recent/latest X" questions, where relevance ranking surfaces the most-*repeated* items and can drop the newest ones. An unknown `order` value → `422`. > **Note: Use the holistic view for recency** `order: "recency"` applies in the **`holistic`** view (the recall default): `holistic` + `recency` + `{ events: 3 }` returns the three *newest* events, newest first. The `granular` and `raw` views keep relevance order (ascending `observed_at` for events, and a `per_layer_limits.events` cap keeps the oldest). Use the default `holistic` view for "latest / most recent" reads. `/v1/answer` forwards `order` and **auto-infers `recency`** for recency-shaped questions: see [POST /v1/answer](https://cortexdb.ai/docs/api-reference/answer). The tuning knobs (`CORTEX_RECENCY_TAIL_EVENTS` / `_ORDER` / `_INFERENCE`) live in [Recall Tuning](https://cortexdb.ai/docs/operations/recall-tuning#recency-ordering). ## Current values and corrections: `newest_of_kinds` Ranked recall returns every past statement that matches the query. For something with one current value (a preference, a setting, a status) that means a late correction comes back *beside* the statements it corrects, and they can outnumber it: ```text [2026-01-05] Nigel prefers morning meetings, ideally 9am. [2026-09-20] Correction from Nigel: he now prefers afternoon meetings after 2pm. [2026-03-01] Nigel said again he likes early morning meetings at 9am. ``` Give each such thing a stable kind in `context.intent` when you write it, corrections included, and ask recall for the newest of that kind (capability `memory_kinds_v1`): ```bash # Every statement of the preference, the correction too, carries the same intent curl -fsS -X POST "$CORTEXDB_URL/v1/experience?wait=indexed" -H "$AUTH" -H 'Content-Type: application/json' -d '{ "scope": "org:acme/user:nigel", "modality": "observation", "content": { "kind": "text", "text": "Correction from Nigel: he now prefers afternoon meetings after 2pm." }, "context": { "intent": "preference.meeting_time" } }' curl -fsS -X POST "$CORTEXDB_URL/v1/recall" -H "$AUTH" -H 'Content-Type: application/json' -d '{ "scope": "org:acme/user:nigel", "query": "What meeting time does Nigel prefer?", "newest_of_kinds": ["preference.meeting_time", "preference.seat"] }' ``` For each kind listed, the pack holds the **newest** eligible event of that kind, first, whether or not the query matched it, and **none of the older ones**: the example returns only the correction. Older events stay listable (`GET /v1/events?intent=preference.meeting_time`) and erasable. Blank and repeated entries are dropped; more than 16 kinds is `422 INVALID_BODY`; it can't be combined with `subtree`. When the scope can't be read whole in one bounded listing, the newest of each kind among the recalled events is kept and `warnings` carries `newest_of_kinds_partial`. Use one kind per thing that has a single current value (`preference.meeting_time`, not `preference`): a kind serves exactly one event. Leave history questions ("what did Nigel prefer before?") on ranked recall. ## Reading several scopes: `extra_scopes` `extra_scopes` (capabilities `extra_scopes_v1` and `extra_scopes_40_v1`) adds up to **40** more scopes to the same ranked pass as `scope`: for example an application's own scope plus a shared `source:slack` and `source:jira`. `/v1/recall/stream`, `/v1/answer` and `/v1/compose` take the same field for every recall they make. ```bash curl -fsS -X POST "$CORTEXDB_URL/v1/recall" -H "$AUTH" -H 'Content-Type: application/json' -d '{ "scope": "org:acme/app:support", "extra_scopes": ["org:acme/source:slack", "org:acme/source:jira"], "query": "What did we promise Globex about the export bug?" }' ``` - Each extra scope is read **exactly** (its own events, no ancestors or descendants) and authorized as a direct `granular` recall of it would be: one the caller can't read refuses the whole request with that recall's 403. - Each contributes its own vector and BM25 candidates, and all of them meet in one fusion and one rerank. Their facts, beliefs, episodes and concepts join too. - Events keep their real scope in `layers.events[].scope`, and `context_block` lines from an extra scope carry its last segment after the time bracket: `[2026-06-15 08:30 UTC] [source:slack] ...`. - Every extra scope must lie in the **tenant subtree** of `scope` (its root by default; `CORTEX_TENANT_DEPTH=2` makes it the first two segments). One outside it, or more than 40 (8 on a server that doesn't list `extra_scopes_40_v1`), answers `422 INVALID_EXTRA_SCOPES`. Repeats and `scope` itself are dropped; it can't be combined with `subtree`. Answers that use it are not cached. On [CortexDB Cloud](https://cortexdb.ai/docs/cloud/tenants) the tenant subtree is your account, so `extra_scopes` can name any of your tenants and none of another account's. ## The read's session: `session` `session` (capability `derivation_use_rules_v1`) names the conversation session the read belongs to. It is read only where a [read-time use rule](https://cortexdb.ai/docs/api-reference/derivation-policy#read-time-use-rules) is in force, which then withholds memory from other sessions and says so in `warnings`. A server without that capability answers `422 INVALID_BODY` to the field, so send it only to a server whose `GET /v1/admin/version` lists `derivation_use_rules_v1`. ## Voice turns: `profile: "voice"` Three fields, capability `recall_profile_voice_v1` (experimental), serve live voice agents. Every server accepts them, in [voice mode](https://cortexdb.ai/docs/features/voice-mode) or not. | Field | Meaning | |---|---| | `profile` | `"standard"` (the default) or `"voice"`: the short read path of a live voice turn. It reads `granular` (naming another view is `422 INVALID_BODY`), returns events unless `include` asks for more, and skips query classification, query expansion, reranking and the entity graph. A write made in the last fraction of a second may be found by its meaning before its words. It waits only briefly for capacity, then answers `429 RECALL_OVERLOADED` (retriable): answer that turn without memory. With `session` naming a call [session](https://cortexdb.ai/docs/api-reference/sessions), it is served from the caller's memories held for the call. | | `alpha` | From 0.0 to 1.0: the weight of vector search against keyword search when the two lists are fused. `1.0` runs vector search only, `0.0` keyword search only. Absent: the two count equally. Works on any recall. | | `server_timing` | `true`: the `200` carries a `Server-Timing` header with the request's stages, for a caller holding `diagnostics.read` on the scope (or the operator). A voice recall carries it without asking. Works on any recall. | > **Note: Self-hosted default retrieval** On a default self-hosted instance recall runs **BM25 + vector + RRF fusion** only. Graph traversal needs a knowledge graph (`CORTEX_ENTITY_GRAPH=1` + enrichment); cross-encoder rerank needs a Cohere key. See [Self-hosting defaults](https://cortexdb.ai/docs/self-hosting/defaults). ========================================================================================== # /v1/sessions _Voice call sessions. Start a call with the caller's brief, serve its voice recalls from the caller's memories held for the call, and end it._ Source: https://cortexdb.ai/docs/api-reference/sessions (Request/response shapes are generated from the pinned OpenAPI spec on the live site.) A voice call opens a **session** at its caller's scope. The start returns a **brief** of the caller, and the server loads the caller's memories for the call, the call's **working set**, which then serves the call's [voice recalls](https://cortexdb.ai/docs/api-reference/recall#voice-turns-profile-voice). The [Voice Mode](https://cortexdb.ai/docs/features/voice-mode) guide has the call flow and the integration notes. > **Note: Voice mode only** Capability `voice_sessions_v1` (experimental). A server not in voice mode answers every route below `409 VOICE_SESSIONS_DISABLED` and does not list the capability on `GET /v1/admin/version`. **A session is its principal's.** It is keyed by its scope, its id and the principal that started it. Another caller naming the same id holds a session of its own, and the status and end routes answer `404 SESSION_NOT_FOUND` for a session the caller did not start (an Owner of the scope and the operator may end anyone's). Sessions live in the serving node's memory only: after a restart the status and end routes answer `404 SESSION_NOT_FOUND` (retriable), and the next voice recall naming the session opens it again. ## `POST /v1/sessions` Start a call. Needs the same access as a `granular` recall of `scope`. ```json { "scope": "ws:acme/caller:9f2c1e", "session": "call_01JF8M2Q7R", "profile": "voice", "brief": { "max_tokens": 400, "query": "billing question", "include": ["events", "facts", "beliefs", "episodes"] }, "deadline_ms": 300, "idle_timeout_s": 900 } ``` | Field | Meaning | |---|---| | `scope` | The caller's scope. | | `session` | The call's id, 1 to 256 bytes with no control character. Name it in the call's voice recalls (`session`) and label the call's writes `session:`. | | `profile` | Optional; `"voice"` is the only profile. | | `brief.max_tokens` | The brief's budget, 1 to 4,000 (default 400). | | `brief.query` | The reason for the call: its most relevant memories join the brief. | | `brief.include` | `events`, `facts`, `beliefs`, `episodes` (default all four); facts, beliefs and episodes only where enrichment derives them. | | `deadline_ms` | 1 to 10,000 (default 300). Past it the start answers with what it has, `brief.partial: true`. | | `idle_timeout_s` | 30 to 14,400 (default 900): the session ends after this long without a recall or a start naming it. | The brief makes no model call, and every memory in it passes the same access checks as a recall. Answer `201`, or `200` for a start repeated with the same scope, session and principal (which keeps the session and reads the brief again) or one past the [limits](#limits): ```json { "session": "call_01JF8M2Q7R", "scope": "ws:acme/caller:9f2c1e", "started_at": "2026-11-12T15:05:00Z", "expires_at": "2026-11-12T15:20:00Z", "last_used_at": "2026-11-12T15:05:00Z", "working_set": { "state": "ready", "pinned": false }, "brief": { "no_prior_history": false, "prior_sessions": 47, "last_session": "call_01JE…", "last_session_at": "2026-11-10T14:02:11Z", "context_block": "[2026-11-10 14:02 UTC] [user] …", "items": [ { "id": "evt_…", "kind": "event", "text": "…", "observed_at": "…", "session": "call_01JE…", "role": "user", "source": "ranked" } ], "current_values": [], "partial": false }, "warnings": ["current_values_need_enrichment: …"] } ``` - `context_block` is ready to put in the agent's context: current values first, then each item as a recall renders it, within `brief.max_tokens`. Items found for `brief.query` come first (`source: "ranked"`), then the newest (`"recent"`). - `current_values` lists current facts and beliefs where enrichment derives them; otherwise it is empty and `warnings` names `current_values_need_enrichment`. - `prior_sessions`, `last_session`, `last_session_at` and `no_prior_history` describe the caller's earlier calls, counted over what the caller may be served. - `working_set.state` says whether the caller's memories are held for the call. `warnings` names `working_set_not_loading: ` when they are not (the call's recalls are then answered from the index as usual) and `session_not_held: ` when a limit was reached. **Errors:** `403 POLICY_DENIED`, `409 VOICE_SESSIONS_DISABLED`, `422 INVALID_BODY` (`details.field`), `429 RECALL_OVERLOADED` and `503 MEMORY_PRESSURE` (both retriable). A brief past its deadline and a start past the limits are not errors. ## `GET /v1/sessions/{session}?scope=` The caller's own session and whether its memories are held, never a memory: `200` with the start's fields without the brief. `404 SESSION_NOT_FOUND` (retriable), also for a session another principal started; `409 VOICE_SESSIONS_DISABLED`; `422 INVALID_QUERY` when `scope` is missing. ## `POST /v1/sessions/{session}/end?scope=` End the caller's own session. Its memories are released when no other session holds them. An optional body `{"post_call": {"enrich": true}}` is accepted; where enrichment is on, the call's events are enriched in the background either way. `204`; `404 SESSION_NOT_FOUND`; `409 VOICE_SESSIONS_DISABLED`; `422 INVALID_QUERY`, `INVALID_BODY`. ## Limits - A node holds up to 10,000 sessions (`CORTEX_SESSION_MAX_SESSIONS`), a tenant a quarter of them (`CORTEX_SESSION_MAX_PER_TENANT`) and a principal a tenth (`CORTEX_SESSION_MAX_PER_PRINCIPAL`). - The memories held for all calls stay within `CORTEX_SESSION_MAX_BYTES` (a tenth of the memory limit by default, at most 8 GiB); one call takes at most a quarter of it. A caller with more than 20,000 stored events (`CORTEX_SESSION_MAX_EVENTS`) is served from the index. - A start past a limit still returns its brief, with `working_set.state: "refused"`. ## Writes and removals during a call A write labelled with the call and acknowledged with `wait=captured` joins the call's memories at once, so the next voice recall finds it. A forget, an erasure, a redaction or a retention sweep reaches the call's memories before their next read: **a recall that starts after a removal answered never serves the removed memory.** ========================================================================================== # POST /v1/answer _Recall a pack and answer a natural-language question over it, with citations._ Source: https://cortexdb.ai/docs/api-reference/answer (Request/response shapes are generated from the pinned OpenAPI spec on the live site.) > **Note: 503 ANSWER_UNAVAILABLE without an answer lane** On a self-hosted server with no `CORTEX_ANSWER_*` lane configured, `POST /v1/answer` returns `503 ANSWER_UNAVAILABLE` ("no answer LLM is configured on this deployment; set CORTEX_ANSWER_API_KEY …"). It is deployment-wide and scope-independent. See [LLM & Answer](https://cortexdb.ai/docs/operations/llm-answer). ## The question field > **Note: The field is question, not query** `/v1/answer` requires **`question`** (not `query`). Sending `{ "query": … }` → `422 "missing field question"`. It shares `view`, `include`, `temporal`, `budgets`, and `citation_mode` semantics with [recall](https://cortexdb.ai/docs/api-reference/recall). > **Note: question_type is ignored** The server picks its retrieval route and question shape from the `question` itself. A `question_type` field is accepted and discarded so older clients keep working; the spec marks it deprecated: `"multi-session"`, `"temporal-reasoning"`, `"single-session-user"` and no `question_type` all give the same `inferred_question_shape` for the same question. ## Retrieval without the LLM > **Note: skip_answer_llm returns an empty answer with citations** `skip_answer_llm: true` returns `200` with `answer: ""` and `diagnostics.answer_llm_skipped_by_request: true`: it runs recall + citation shaping but skips the LLM. Use it when you want the answer endpoint's citation shaping without paying for generation. `cite_sources` (top-level) is accepted but has no observable effect on a content-only instance. ## Response diagnostics The response is `{ pack_id, answer, citations[{ marker, layer, id, support_strength }], provenance, diagnostics, as_of }`. `as_of` is a **top-level** field here (unlike recall, where it does not exist). > **Note: diagnostics fields** `diagnostics` carries `recall_ms`, `llm_ms`, `total_ms`, `answer_model`, `answer_llm_skipped_by_request`, `tokens_input`, `tokens_output`, and a `time_ms` phase-map (with a long list of `artifact_*` and `wal_*` counters, and `inferred_question_shape` / `question_shape_applied` when the server infers a question shape from the question). Token counts are **flat** `tokens_input` / `tokens_output`. The model used is at `diagnostics.answer_model`. **The token keys are omitted (absent, not `null`)** when the answer came from the multi-session executor lane (`question_type: "multi-session"`) and on any path that does not call the answer model. The SSE stream's `diagnostics` event carries both `tokens_input` and `tokens_output`, and omits a count it does not know instead of sending `null`. ### Degraded runs and abstentions - **`diagnostics.degraded_sources`** appears when the answer ran without part of its evidence, as stable codes only (never error text): `coordinator_recall`, `wal_supplement`, `derived_` (e.g. `derived_facts`), `artifact_search`, `index_divergence`, `derived_backfill`, `facet_plan_unavailable`, `facet_recall_failed`, `ms_executor_fallback`, else `unknown`. The answer is still returned; read a non-empty list as "this answer saw less evidence than a healthy run would" and check the server log. On a healthy server it is absent. - **Abstentions** ("The memories contain no such information.") are detected as such. When the question names things the context never mentions, **`diagnostics.premise_unsupported_terms`** lists them (for example, a question about a Singapore office's wifi password over IT tickets lists `Singapore`, `office`, `wifi`, `password`, `branch`). General nouns such as "issue" or "problem" don't count as unsupported premises, so "How was the VPN issue fixed?" is answered. When an extractive retry runs, diagnostics also carry `extractive_retry_outcome` (`answered`, `still_abstained` or `premise_ungrounded`). - A request carrying the evaluation-only `facet_plan_override` is refused with `422 EVAL_OVERRIDE_DISABLED` unless the server runs with `CORTEX_EVAL_FACET_PLAN_OVERRIDE=1`. Never set a `CORTEX_EVAL_` variable on a production server. - `/v1/answer` merges several recall passes; an event served whole by one pass and as a [budget excerpt](https://cortexdb.ai/docs/api-reference/recall#context-block-budgets-and-long-events) by another appears once, whole. ## Model and streaming > **Note: answer_model default is env-driven; streaming is not token-SSE self-hosted** The `claude-opus-5-5` default is a **managed-cloud** value; self-hosted, `answer_model` resolves to whatever the answer lane (`CORTEX_ANSWER_*`) is configured with, and `/v1/answer` is **disabled until that lane is set**. Streaming is selected by the **body field** `"stream": true`, which returns `text/event-stream` with the events `token` (`{ text }`), `citations`, `provenance`, `diagnostics` (a reduced set: `answer_model`, `recall_ms`, `llm_ms`, `total_ms`, `tokens_input`, `tokens_output`) and `done` (`{ pack_id, as_of }`). The **query parameter** `?stream=true` is ignored and returns the normal JSON object. See [Self-hosting defaults](https://cortexdb.ai/docs/self-hosting/defaults). ## Answer cache With `CORTEX_ANSWER_CACHE=1`, a repeated question from the same caller gets the stored answer at once, without running recall and the answer model again, but only while that answer is still current: any new save, deletion or access change clears the cache. An entry lasts `CORTEX_ANSWER_CACHE_TTL_SECS` (300 by default, 540 at most), and the cache holds up to `CORTEX_ANSWER_CACHE_MAX` entries (1,000 by default). Answers that read `extra_scopes` are not cached. It's off by default. Example: many agents ask "What is our refund policy?" and only the first call runs the model. ## Notes - `session` (capability `derivation_use_rules_v1`) is the read's conversation session, read only where a [read-time use rule](https://cortexdb.ai/docs/api-reference/derivation-policy#read-time-use-rules) is in force. A server without that capability ignores it here (recall refuses it with `422 INVALID_BODY`), so send it only to a server that lists `derivation_use_rules_v1`. - `use_pack_id` reuses a [recall](https://cortexdb.ai/docs/api-reference/recall) pack (same-scope only; a pack from a different scope → `404`). - Temporal questions trigger internal "question shaping": `diagnostics.inferred_question_shape` / `question_shape_applied` reflect it; no request field controls it. - **`order` (`relevance` | `recency`)** is forwarded to recall. When you omit it, **recency-shaped questions** ("recent…", "latest…", "currently…", "next best step…") **auto-infer `recency`**; an explicit value always wins. As with recall, the recency timeline tail is observable in the default **`holistic`** view (see [POST /v1/recall](https://cortexdb.ai/docs/api-reference/recall#ordering-relevance-vs-recency)). Kill-switches: `CORTEX_RECENCY_INFERENCE=0` (disable the inference), `CORTEX_RECENCY_ORDER=0` (disable the mode); see [Recall Tuning](https://cortexdb.ai/docs/operations/recall-tuning#recency-ordering). ========================================================================================== # POST /v1/compose _Compose a structured markdown document from a scope's memory, with inline citations._ Source: https://cortexdb.ai/docs/api-reference/compose (Request/response shapes are generated from the pinned OpenAPI spec on the live site.) > **Note: 503 ANSWER_UNAVAILABLE without an answer lane** `/v1/compose` runs on the same answer lane as `/v1/answer`; without `CORTEX_ANSWER_*` it returns `503 ANSWER_UNAVAILABLE`. See [LLM & Answer](https://cortexdb.ai/docs/operations/llm-answer). ## What it does `/v1/compose` is **recall composed with an LLM writing pass**: it retrieves a pack for the `scope`, then asks the answer model to write a **structured markdown document** that fulfils your `brief`, with inline citation markers back to the evidence. Think of it as `/v1/answer` for long-form output: a briefing, dossier, or summary rather than a single answer. The response is `{ pack_id, document, citations, provenance, diagnostics }`: - **`document`**: the composed markdown, with inline markers like `[S1]`, `[S2]`. - **`citations`**: `[{ marker, layer, id, support_strength }]` mapping each marker in `document` to the memory it came from (markers resolve to `layer: "event"` ids with a `support_strength`). - **`provenance`** / **`diagnostics`**: the same recall provenance contract as [recall](https://cortexdb.ai/docs/api-reference/recall) and [answer](https://cortexdb.ai/docs/api-reference/answer). ## Shaping the document | Field | Effect | |---|---| | `brief` (required) | The instruction: what the document should cover. | | `length` | `brief` · `standard` · `deep`: overall length target. | | `depth` | `standard` · `exhaustive`: how hard recall works to gather evidence. | | `structure` | An array of section headings to force a specific outline. | | `citations` | Toggle inline citation markers on/off. | | `filters` | Same recall `filters.metadata` shape as [recall](https://cortexdb.ai/docs/api-reference/recall). | | `max_tokens` | Output ceiling for the composed document. | | `include_context` | Return the recalled context block alongside the document. | | `session` | Needs capability `derivation_use_rules_v1`: the read's conversation session, read only where a [read-time use rule](https://cortexdb.ai/docs/api-reference/derivation-policy#read-time-use-rules) is in force. A server without that capability ignores it here (recall refuses it with `422 INVALID_BODY`), so send it only to a server that lists the capability. | > **Note: Needs the answer lane: same as /v1/answer** Composition runs the LLM, so self-hosted it requires the **answer lane** (`CORTEX_ANSWER_*`) to be configured and is **disabled until it's set**: the `claude-*` default is a managed-cloud value. On a content-only instance with no answer lane, use [recall](https://cortexdb.ai/docs/api-reference/recall) for retrieval without generation. See [Self-hosting defaults](https://cortexdb.ai/docs/self-hosting/defaults). > **Note: Composition is not instant** Like `/v1/answer`, a compose call blocks on the LLM: a multi-paragraph document can take tens of seconds depending on `length`/`depth` and your answer model. Budget your client timeout accordingly. ========================================================================================== # POST /v1/forget _Selective deletion: remove derived layers or redact events, with an audit record._ Source: https://cortexdb.ai/docs/api-reference/forget (Request/response shapes are generated from the pinned OpenAPI spec on the live site.) ## Accepted fields > **Note: Only scope is required; idempotency_key is not a forget field** The accepted body is exactly `scope, layers, selector, cascade, confirm_all, audit_note, reason, from_preview_id`. - **Only `scope` is required.** The others default: `layers` empty means every layer, `selector` empty means the whole scope (and then needs `confirm_all: true`), and `cascade` is `derived_only`. `{ "scope": …, "confirm_all": true }` is a complete request. - **`idempotency_key` is not a forget field** → `422` with a plain-text body ("unknown field `idempotency_key`, expected one of …"). An unknown `cascade` value gets the same plain-text `422`. - **`reason`** is another name for `audit_note` (the SDKs use `reason`). Send one of them: both together → `422` "duplicate field `audit_note`". - **`from_preview_id`** executes exactly the operation a `POST /v1/forget/preview` described. An id the server did not issue for this caller, scope, layers, selector, cascade and confirmation → `422 UNKNOWN_PREVIEW_ID`. Preview ids live in the server's memory, so a restart invalidates them (same `422`). A forget of specific events: ```json POST /v1/forget { "scope": "org:acme/user:alice", "layers": ["events"], "selector": { "memory_ids": ["evt_01HX..."] }, "reason": "user request" } ``` ## What gets deleted > **Note: The default cascade keeps your memories** A forget that names no `cascade` runs **`derived_only`**, on every deployment, the hosted cloud included (its `cloud_shared_saas` preset sets `forget.cascade.default: derived_only`). `derived_only` removes derived data only (facts, beliefs, episodes, understanding): the memories you wrote stay, and recall, answers and `GET /v1/events` keep returning them. A whole-scope forget (`confirm_all: true`, no selector) under the default therefore deletes **no memory**; its `warnings` say so. To delete memories: - **Named memories:** put their event ids in `selector.memory_ids`, with `layers` empty or including `events`. They are deleted under either cascade, the default included. - **Every memory in a scope:** [`POST /v1/erasures`](https://cortexdb.ai/docs/api-reference/erasures), or `"cascade": "redact_events"` with `"confirm_all": true`, which blanks every event in the scope. **Retry keys.** A `memory_ids` forget and an erasure free the deleted memories' `idempotency_key`s: re-sending a deleted write with its old key stores it again. A scope-wide `redact_events` forget does not. Its blanked events keep their keys (a key lasts up to 24 hours from its write), so a re-send with an old key answers with the blanked event (`replayed_from_idempotency: true`) and stores nothing. Send new keys to write that content again. - **A selector deletes what it names.** `selector.memory_ids` naming events, with `layers` empty or including `events`, deletes those events under **either** `cascade` value: they disappear from `GET /v1/events`, `GET /v1/events/{id}` answers `404`, and recall no longer returns them. - With `layers` that leave `events` out (for example `["facts"]`), the event ids select only their derived records; the events stay and a warning says so. - **`cascade`** matters for the **scope-wide** shape (empty selector + `confirm_all: true`): - `derived_only` (default) removes the derived layers and keeps every raw event; the response warns that no raw event was deleted. - `redact_events` blanks every event in the scope; they no longer appear on `GET /v1/events` or in recall. `redact_events` with a selector deletes only the named events and warns that the cascade is scope-wide. - **One cutoff.** A scope-wide forget takes one server cutoff before it reads anything. Captures the server stamped before it are removed; captures stamped after it are never removed. A capture sent after the forget returns is stored and recalled normally. - **Blobs.** An event made from an uploaded text blob (`content.kind: "blob_ref"`) records the blob in `source_blob_ids`. Forgetting the event deletes the blob unless another live event still uses it: `deleted.blobs: 1` and `GET /v1/blobs/{id}` → `404`, or `deleted.retained_shared_blobs: 1` and the blob stays. Capability `erasure_blob_cascade_v1`. - **Entity ids.** `about_entity`, `about_subject`, or an `ent_…` id in `memory_ids` (under `derived_only`) delete the facts whose subject that id names, in the scope and its descendants, plus the beliefs and understanding they support. These selectors act on facts, which come from enrichment or triple captures. ## Guards and errors - An **empty selector** requires `confirm_all: true`, else `422 EMPTY_SELECTOR_WITHOUT_CONFIRMATION`. - A **selector together with `confirm_all: true`** is refused as ambiguous → `400 AMBIGUOUS_SELECTOR_CONFIRM_ALL` ("confirm_all authorizes a scope-wide operation and would ignore the selector"). Send `confirm_all: false` (or omit it) to delete exactly the selection, or an empty selector with `confirm_all: true` for a scope-wide forget. - A storage backend failing mid-deletion → `502 FORGET_BACKEND_FAILED` (`retriable: true`); nothing is reported as deleted. The same code on `/v1/forget/preview` means a derived store could not answer the dry run. - **Retriable refusals.** Nothing was changed in any of these; retry after `Retry-After`: | Status | Code | When | |---|---|---| | `409` | `AUTHORIZATION_STATE_CHANGED` | Scopes were registered or removed inside the forget's footprint (the scope, and its subtree for a whole-scope forget) on each of 5 attempts to authorize it (`Retry-After: 1`, `details.retry_after_seconds: 1`) | | `409` | `REDERIVE_IN_PROGRESS` | A derived-data repair job holds the scope (`Retry-After: 30`) | | `503` | `SERVER_SHUTTING_DOWN` | A graceful stop has begun (`Retry-After: 5`) | **Scope registrations elsewhere don't matter.** A forget and its preview check the caller's authorization, then lock their footprint. A scope registered outside the footprint (any capture, from any tenant, that creates a brand-new scope) does not affect them. A scope registered or removed **inside** the footprint makes the forget re-check and try again, up to 5 times, before the `409` above. While new child scopes keep appearing inside the forgotten scope (dozens a second), many attempts end in that `409`: pause those captures, or retry after them. While a forget runs it holds a lease on its scope footprint. Captures into existing scopes and reads never wait, but a capture that would register a **new** scope inside the footprint waits up to `CORTEX_DESTRUCTIVE_LEASE_WAIT_SECS` (default 120) and then gets `409 DESTRUCTIVE_OPERATION_IN_PROGRESS` (`Retry-After: 5`), and `/v1/scopes` register, member edits and delete inside it get `409 SCOPE_STATE_CHANGED`. Forgets usually finish in well under a second, so these are rare. - A forget runs detached from the HTTP request: if the client disconnects it still completes and still writes its audit row. Retrying the identical request is safe. - **Request ids.** Send an `X-Request-Id` header: the response echoes it, and the forget's `gdpr: true` [audit row](https://cortexdb.ai/docs/enterprise/audit-trail) and the request's [log line](https://cortexdb.ai/docs/operations/configuration#request-log-and-request-ids) carry the same id, so the three can be joined. > **Note: Send one kind of selector per request** A request that combines `memory_ids` with `about_subject` is accepted (`200`) and deletes the named events. Keep each request to one kind of selector so its effect is clear. Error codes are uppercase (`POLICY_DENIED`, `FORGET_BACKEND_FAILED`). ## Response The response is `{ deleted, requested?, matched?, audit_id, warnings?, purge }`: - **`deleted`**: per-layer counts (`events`, `episodes`, `facts`, `beliefs`, `understanding`), plus `blobs` / `retained_shared_blobs` only when they are non-zero. - **`requested`** / **`matched`**: present for a `memory_ids` selector: how many ids you sent and how many records the selector hit. - **`purge`**: the storage engine's own counts for this request: `events`, `documents`, `edges`, `blobs`, `retained_shared_blobs`, `twins_redacted`, `bitemporal_records_erased`, `wal_rows_redacted`, `artifacts_cascaded`. Every count is something this request changed, so repeating a forget reports `matched: 0` and all zeros, and a scope-wide `redact_events` forget counts each event once. - **`warnings`**: present only when there is something to say: the selector matched nothing, `layers` did not name `events`, `redact_events` was sent with a selector, or a scope-wide `derived_only` forget kept the raw events (pointing to `redact_events` or [`/v1/erasures`](https://cortexdb.ai/docs/api-reference/erasures)). On a **scope-wide** forget of an enrichment-on scope, `purge.events` also counts derived content rows (a fact, gloss or question-key row stored under the scope); use `deleted.events` for the event count. ```json { "deleted": { "events": 1, "episodes": 0, "facts": 0, "beliefs": 0, "understanding": 0, "blobs": 1 }, "requested": 1, "matched": 1, "audit_id": "audit_01HX...", "purge": { "events": 1, "documents": 1, "edges": 0, "blobs": 1, "retained_shared_blobs": 0, "twins_redacted": 1, "bitemporal_records_erased": 0, "wal_rows_redacted": 0, "artifacts_cascaded": 0 } } ``` **Ids outside the scope.** An id stored in another scope and an id that does not exist get the same answer: `200`, every count `0`, `matched: 0` and the "selector matched no records" warning. The event in the other scope is untouched. > **Note: A wrong memory: correct it, don't forget it** A `derived_only` forget removes derived rows, and enrichment can learn them again from the same events: a later re-enrichment, re-derivation or rebuild brings them back. Fix a wrong memory with a [correction](https://cortexdb.ai/docs/api-reference/corrections) (`reject` or `replace`), which stays applied. To keep a whole topic or field from being learned at all, use a [derivation policy](https://cortexdb.ai/docs/api-reference/derivation-policy) or the subject's settings. ## Preview `POST /v1/forget/preview` takes the same body and returns `{ preview_id, scope, estimated_deleted, requested?, matched? }` without changing anything. `requested` / `matched` appear only for an event-id selector. It counts only events not yet blanked, so a preview after a scope-wide `redact_events` forget reports `0`. Pass `preview_id` as `from_preview_id` to execute exactly that operation; any change to the body → `422 UNKNOWN_PREVIEW_ID`. > **Note: Forget vs erasures** `/v1/forget` is for operational deletion (derived layers, event redaction). For GDPR reference-counted **WAL deletion** with a preview → execute → status lifecycle, use [`/v1/erasures`](https://cortexdb.ai/docs/api-reference/erasures). The SDKs rename forget's fields: see the [Python](https://cortexdb.ai/docs/sdks/python#forget) and [TypeScript](https://cortexdb.ai/docs/sdks/typescript#forget) SDK pages. ========================================================================================== # /v1/erasures _GDPR reference-counted erasure: preview, execute, and poll the job. The path that deletes the stored events themselves._ Source: https://cortexdb.ai/docs/api-reference/erasures Erasures are CortexDB's **reference-counted GDPR deletion** path: the sanctioned exception to the append-only WAL. Unlike [forget](https://cortexdb.ai/docs/api-reference/forget) (which redacts or drops derived layers), a completed erasure **deletes events from the WAL**. The flow is preview → execute → poll. ## Preview `POST /v1/erasures/preview` with the **same selector and confirmation you will execute with**, e.g. `{ scope, confirm_all: true, audit_note }` → `200`. A preview is bound to that exact operation: executing with a different selector or confirmation (for example previewing `{ scope, audit_note }` and then executing with `confirm_all: true`) → `422 UNKNOWN_PREVIEW_ID`. `from_preview_id` is optional; an execute without it also works. Preview ids live in the server's memory, so a restart invalidates them (same `422`). ```json { "preview_id": "ervw_01HX...", "scope": "org:acme/user:alice", "estimated_affected": { "events": 5, "episodes": 0, "facts": 0, "beliefs": 0, "understanding": 0 }, "refcount_breakdown": { "in_scope_events": 5, "events_to_delete": 5, "events_to_redact": 0, "events_under_legal_hold": 0 }, "estimated_duration_ms": 650 } ``` - `estimated_affected` adds `blobs` when the erasure would delete uploaded blobs (see [Blobs](#blobs-and-leftover-bytes)). - `estimated_duration_ms` is a planning figure for choosing a client timeout: 250 ms plus 80 ms per in-scope event. Real erasures are usually much faster. - Erasing a **parent** scope counts the events stored in its child scopes under `refcount_breakdown.events_to_redact` (and `estimated_affected.events` then reads `0`). Those events are removed completely all the same, so read `refcount_breakdown.in_scope_events` for the total. > **Note: What a self-hosted preview contains** Self-hosted previews carry the fields above. The preview can also carry a top-level `code_repos_to_delete` count (Code Intelligence Plane repositories bound to the scope that execute would remove); it is **absent when zero**, so a deployment without the code plane sees the body above unchanged. ## Execute `POST /v1/erasures` → `202`: ```json { "erasure_id": "erasure_01HX...", "status": "completed", "manifest_url": "/v1/erasures/erasure_01HX...", "lifecycle_stream": "/v1/lifecycle/stream?erasure_id=erasure_01HX..." } ``` A small scope often reports `"status": "completed"` already in this response; a larger one reports `"running"`. Either way, poll `manifest_url` (`GET /v1/erasures/{id}`) for progress and the result. The `lifecycle_stream` URL is the general capture and indexing stream; it doesn't report erasure progress. > **Note: Execute requires confirm_all or an explicit selector** Without `selector.memory_ids`, execute → `422 EMPTY_SELECTOR_WITHOUT_CONFIRMATION`, even with `from_preview_id` set: an erasure with no selector erases the **entire scope**, so you must pass **`confirm_all: true`** (or a `selector.memory_ids` list to erase specific records). The `manifest_url` in the response is `/v1/erasures/{id}` (no `/manifest` suffix). ```json { "scope": "org:acme/user:alice", "from_preview_id": "ervw_01HX...", "confirm_all": true, "audit_note": "DSR #1234" } ``` An execute takes **one server cutoff** before it reads anything: captures the server stamped before it are erased, captures stamped after it are kept (and are erased by a later execute). Send the captures you need to keep after the erasure returns. Like forget, an execute runs detached from the HTTP request, so a client disconnect does not stop it. ### Early answer for a whole-scope erasure With `"respond": "accepted"` (capability `erasure_early_answer_v1`), `POST /v1/erasures` for a whole scope answers `202` with status `running` as soon as the erasure is authorized and holds its lease, instead of waiting for it to finish. From that answer on, this node no longer serves the scope's events recorded before it, and the erasure finishes in the background under the same `erasure_id`, whose status, receipt and proof answer as for any job. The hiding is held in memory for as long as the job runs: if the process dies mid-job, send the request again with the same `idempotency_key`. ## Status `GET /v1/erasures/{id}` → the job record: ```json { "erasure_id": "erasure_01HX...", "status": "completed", "phase": "audit", "summary": { "deleted_events": 3, "redacted_events": 0, "demoted_beliefs": 0, "deleted_facts": 0, "deleted_episodes": 0, "deleted_concepts": 0, "deleted_artifacts": 0, "artifacts_pending_reevaluation": 0, "purge": { "events": 3, "documents": 3, "edges": 0, "blobs": 0, "retained_shared_blobs": 0, "twins_redacted": 3, "bitemporal_records_erased": 0, "wal_rows_redacted": 0, "artifacts_cascaded": 0 } }, "log_residual_cleared_at": null, "log_residual_pending": { "reason": "pass_pending" } } ``` > **Note: Reading the job record** The record is `{ erasure_id, status, phase, summary, log_residual_cleared_at, log_residual_pending }`. Progress and results are in **`summary`**; `phase` runs `enumerate → refcount → categorize → delete → demote → audit`. `summary.deleted_events` is the count of events this job removed. Jobs are kept in the server's memory: after a restart, or for an unknown id, `GET /v1/erasures/{id}` → `404 NOT_FOUND` ("erasure job not found"). Re-submitting an erasure is safe. Backend failures surface as `502 ERASURE_BACKEND_FAILED` (retriable: erasure is idempotent), and an accepted job can still finish with `status: "failed"` and an `error` field: always poll rather than assuming acceptance means completion. ## Blobs and leftover bytes - **Blobs** (capability `erasure_blob_cascade_v1`). An event made from an uploaded text blob records it in `source_blob_ids`. Erasing the event deletes the blob unless another live event still uses it, reported as `summary.purge.blobs` and `summary.purge.retained_shared_blobs`; afterwards `GET /v1/blobs/{id}` answers `404`. Events written before an upgrade carry no link until an operator backfills it with `POST /v1/admin/index-audit/source-blob-links`; `GET /v1/admin/index-audit/orphan-blobs` then lists blobs nothing links (see [Admin](https://cortexdb.ai/docs/api-reference/admin)). - **Leftover bytes.** A delete in the storage engines leaves older copies of the bytes in their files until they are compacted. After an erasure a throttled background pass compacts them out. The status reports `log_residual_cleared_at` once the pass has covered the job (seconds for a small job; `log_residual_pending` is then `null`). While it is still `null` on a completed job, `log_residual_pending.reason` says why: | `reason` | Meaning | |---|---| | `pass_pending` | The pass has not finished this job's work yet | | `fulltext_segment_over_budget` | A full-text segment larger than the per-pass budget still holds erased documents; on a store whose segments exceed the budget it may never clear | | `not_covered` | No pass covers this job: `CORTEX_ERASURE_RESIDUAL=0`, or the legacy dual WAL (`CORTEX_UNIFIED_WAL=0`) | A graceful stop drains the pass for up to `CORTEX_ERASURE_RESIDUAL_SHUTDOWN_SECS` (default 20) and resumes the rest at the next start. `CORTEX_ERASURE_PERIODIC_COMPACTION_SECS` sets a periodic compaction backstop. `GET /v1/admin/metrics` reports the pass under `erasure_residual`. - **Erased facts stay erased after a crash.** An erased fact id is recorded in a synced fence before it leaves memory, and every start drops fenced ids, so a hard kill cannot bring an erased fact back. ## Speed and the erasure index An erasure's cost follows what it erases, not the size of the store: the server keeps an erasure index beside the event log (a one-id erasure on a 1M-event store takes well under a second). The first start after the upgrade backfills the index; until `erasure_index.wal.ready` is `true` on `GET /v1/admin/metrics`, erasures read the whole store. `CORTEX_ERASURE_INDEX=0` keeps the index maintained but unread, and `CORTEX_ERASURE_INDEX_BACKFILL=0` skips the backfill. ## Concurrency and shutdown Nothing is changed in any of these cases; retry after `Retry-After`. Erasures usually finish in well under a second, so these are rare. | Status | Code | When | |---|---|---| | `409` | `AUTHORIZATION_STATE_CHANGED` | Scopes were registered or removed inside the erasure's footprint on each of 5 attempts to authorize a preview, execute, status read or cancel (`Retry-After: 1`, `details.retry_after_seconds: 1`) | | `409` | `DESTRUCTIVE_OPERATION_IN_PROGRESS` | A capture that would register a **new** scope inside a running erasure's footprint waited `CORTEX_DESTRUCTIVE_LEASE_WAIT_SECS` (default 120) (`Retry-After: 5`) | | `409` | `SCOPE_STATE_CHANGED` | `/v1/scopes` register, member edit or delete inside the footprint | | `409` | `REDERIVE_IN_PROGRESS` | A derived-data repair job holds the scope (`Retry-After: 30`) | | `503` | `SERVER_SHUTTING_DOWN` | A graceful stop has begun (`Retry-After: 5`); running erasures get up to `CORTEX_SHUTDOWN_DESTRUCTIVE_WAIT_SECS` (default 60) to finish | Captures into existing scopes and reads never wait for an erasure. A scope registered **outside** the footprint (any capture, from any tenant, that creates a brand-new scope) does not affect an erasure. While new child scopes keep appearing inside the erased scope, retry after them. ## Governed memory Erasure reaches everything [governed memory](https://cortexdb.ai/docs/features/governed-memory) keeps about people: - **What goes with an event:** the [corrections](https://cortexdb.ai/docs/api-reference/corrections) whose last cited event it is, the candidates held for [review](https://cortexdb.ai/docs/api-reference/review) and their decisions, [declared episodes](https://cortexdb.ai/docs/api-reference/episodes#declared-episodes) that name it, and policy examples copied from it. - **What goes with a scope or a tenant:** subject settings, policy texts and feed consumers' records go with the scope's or the tenant's erasure. A person's erasure (`POST /v1/erasures/person`) also erases the corrections about that person. - **The receipt** lists the corrections and held candidates the erasure took, and, in `feed_consumers`, every [change-feed](https://cortexdb.ai/docs/api-reference/derivation-feed) consumer that may hold a copy of an erased event outside CortexDB: those copies are the consumer's to delete. The list may name a consumer that holds no copy; it never misses one that does. - **`/verify`** also checks that no governed record citing an erased event is left (`governed_records`), and lists the feed consumers (`feed_consumers`). A receipt is kept by the node that ran the erasure; on a cluster, another node answers `404` for it. ## Things to know - On a whole-scope erasure of an enrichment-on scope, `summary.purge.events` also counts derived content rows (facts, glosses, question keys); use `summary.deleted_events` and `redacted_events` for the event count. - **Preview again if the scope changed.** An execute with a `from_preview_id` erases what is in the scope when it runs, including events captured after the preview. Preview right before you execute when the preview itself is your record of what was erased. - **Cancel** applies to a job that is still running. A finished job can't be cancelled (`POST /v1/erasures/{id}/cancel` → `404 NOT_FOUND`); read its result with `GET /v1/erasures/{id}`. ========================================================================================== # GET /v1/events _List raw events: the append-only record that every other layer is derived from._ Source: https://cortexdb.ai/docs/api-reference/events (Request/response shapes are generated from the pinned OpenAPI spec on the live site.) ## Event item shape > **Note: Item shape: id, subject object, nested context** Each event is `{ id, scope, caller, observed_actor, subject: { id, type }, scope_key, modality, content, context: { observed_at, recorded_at, intent, labels }, wal_offset }`. The key is **`id`**; `subject` is an **object** `{ id, type }`; and `observed_at` / `recorded_at` / `labels` / `intent` are nested under **`context`**. This is the same shape recall and `GET /v1/events/{id}` return. Events written with a [`source` descriptor](https://cortexdb.ai/docs/concepts/experience-envelope#source-descriptor) carry it back verbatim as `source`; the key is absent otherwise. An event can also carry `language`, `scripts` and `language_source` (a non-English or explicitly tagged event; an event that is English by default has none), `context.timezone` and `context.refers_to` (when the capture sent them), and `source_blob_ids` (the uploaded blob a `blob_ref` event was made from). See [Experience](https://cortexdb.ai/docs/api-reference/experience#language-time-zone-and-referenced-times). `scope_key` is the billing partition the event was captured under: the capturing credential's billing tenant, `default` for the static operator key (`CORTEX_API_KEY`), not the event's scope, which is `scope`. ## Listing by kind: `intent` `GET /v1/events?scope=…&intent=handover,skill` (capability `memory_kinds_v1`) lists only the events whose `context.intent` is exactly one of the comma-separated values. It is how you list every statement of a memory kind whose newest one recall serves with [`newest_of_kinds`](https://cortexdb.ai/docs/api-reference/recall#current-values-and-corrections-newest_of_kinds). ## Reading one event in one scope `GET /v1/events/{id}?scope=` (capability `event_scope_filter_v1`) returns the event only when its own scope is **exactly** ``: - An event stored in a sibling, an ancestor or a descendant of `` gets the same `404 NOT_FOUND` body as an unknown id (`"event not found"`), so the filter never tells you where an event lives. - An empty, blank or malformed value (`?scope=`, `?scope=%20`, `?scope=nocolon`) → `422 INVALID_SCOPE_GRAMMAR`. Sending `scope` twice → a plain-text `400` ("duplicate field `scope`"). Neither falls back to a read without the filter. - Without the parameter nothing changes. Use it with operator-wide credentials: the static operator key (`CORTEX_API_KEY`) and an auth-disabled server read every scope of every tenant by id. - A server without the capability ignores the parameter and returns the event. Send it only when [`capabilities[]`](https://cortexdb.ai/docs/api-reference/admin#version-and-capabilities) lists `event_scope_filter_v1`, or compare the returned `scope` with the one you expect. - It applies to this route only; `GET /v1/facts/{id}` has no `scope` filter. ## Behavior notes > **Note: Content is always included** `GET /v1/events` always returns each event's full `content`. To leave content out, use [recall](https://cortexdb.ai/docs/api-reference/recall) with `exclude_content: true`. - Envelope: `{ items: [...], next_cursor, has_more }`; `next_cursor` is omitted on the last page. Items are **newest first** by the server's `context.recorded_at`, whatever their `observed_at`. Default `view` is **`local`**; the enum is `local / granular / raw / structured / holistic / descend` (anything else → `422`). - Filters that work: `labels` (comma-separated, any-match), `observed_actor`, `modality`, and `since` (RFC 3339). **`since` compares `context.recorded_at`** (when the server stored the event), not `observed_at`: an event observed in 2020 but written today passes `since=2024-01-01`. - **There is no `until` filter**: to bound the end of a time range, filter on `context.recorded_at` on your side. - `GET /v1/events/{id}` returns a single event, always with its full text (even when a recall served it as an excerpt); a missing, unknown, forgotten or [cancelled](https://cortexdb.ai/docs/api-reference/lifecycle#per-event-summary-and-cancel) id → `404`. Every recalled `layers.events` item carries the same `caller`, `observed_actor`, `subject`, `scope_key`, `scope` and `wal_offset` as this route (see [Recall](https://cortexdb.ai/docs/api-reference/recall#who-said-it-recalled-event-identity)). - `limit` is clamped rather than rejected: `limit=0` returns one item, and `limit=5000` returns `200`. A missing `scope` query param → `400` (query-string validation returns `400`; body validation returns `422`). - **Embedding-provider outages:** an event accepted while the embedding endpoint is down stays `captured` until the provider returns, and is then indexed automatically with no operator action. During an outage the indexer holds rather than drops, so `?wait=indexed` waits until the provider is back or its wait budget runs out (`408 WAIT_TIMEOUT` after about 30 s; see [Experience](https://cortexdb.ai/docs/api-reference/experience#wait-deadline-and-408-wait_timeout)). ========================================================================================== # GET /v1/facts _Query the Facts layer: typed subject/predicate/object triples with bi-temporal validity._ Source: https://cortexdb.ai/docs/api-reference/facts (Request/response shapes are generated from the pinned OpenAPI spec on the live site.) > **Note: Facts from text need enrichment; triple captures do not** Facts extracted from text are **LLM-derived**, so that part of the layer fills once you configure enrichment (see [Self-hosting defaults](https://cortexdb.ai/docs/self-hosting/defaults)). A [triple capture](https://cortexdb.ai/docs/api-reference/experience#content-kinds) writes its fact directly, with or without enrichment, and the fact is on this endpoint as soon as a `?wait=indexed` write returns. ## Fact item shape A fact is `{ id, scope, subject: { type, id }, predicate, object: { type, datatype, value }, supports, valid_from, valid_to, recorded_from, recorded_to, confidence, stance, polarity }`: - The key is **`id`**; `subject` is `{ type, id }`; `object` includes its **`type`**. - **`stance`** is e.g. `"supported"`; **`polarity`** is `affirmative`, `negated` or `ceased`. - A superseded fact adds `superseded_by` and a closed `valid_to`. Facts can also carry these optional fields (additive; rely on them once the capability `fact_surface_v1` appears in [`GET /v1/admin/version`](https://cortexdb.ai/docs/api-reference/admin)): | Field | What it holds | |---|---| | `quote` | The exact span of the capture's own text the fact came from | | `language` | The source's language tag, e.g. `und-Deva`, `hi-Latn` | | `gloss` | For a non-English fact, a derived English key: `{ text_en?, object_en?, derived: true, model, prompt_version }`. It is used for search only and never appears in `context_block` or citations | | `date_basis` | How a dated fact got its date: `refers_to`, `verbatim`, `extractor` or `ambiguous` | | `date_candidates` | Every reading of an ambiguous day word (the fact is then stamped with none) | Subjects and objects stay in the source script ("प्रिया … चाय"); predicates are English snake_case. Each captured sentence also yields a `states` fact whose subject is `ent_fact_subject_…` and whose object is the whole sentence. ## Entity ids A subject's id is `ent_` plus its name when the name is pure ASCII (`ent_Priya`, case-sensitive). A name with any non-ASCII character gets a hashed id: `ent_-<16 hex>` when it has ASCII letters (José → `ent_jose-0f66606aa13f1258`) or `ent_u-<16 hex>` when it has none (प्रिया → `ent_u-0133576006acc0d5`). Ids stored by earlier releases still resolve on reads and forgets (see [Upgrading](https://cortexdb.ai/docs/self-hosting/upgrading)). ## Negation, cessation and supersession (enrichment on) - **A denial of another value retires nothing.** "Meera eats fish" and "Meera doesn't eat non-veg", or "Amit works at Acme" and "Amit does not work at Globex", stay live side by side (the denial is stored with `polarity: "negated"`, e.g. `works_at | not Globex`). - **A change of state is an update.** "Kavya doesn't work at Acme anymore" closes the earlier fact (`valid_to` set, `superseded_by` filled) and leaves its belief `deprecated`. - **A denial of the current value is a contradiction.** When the extraction model reads a statement as a denial of the same value (for example "Priya lives in Delhi", then a later statement stored as `lives_in | not Delhi`), both facts stay, the belief becomes `contradicted`, and a conflict opens on [`/v1/conflicts`](https://cortexdb.ai/docs/api-reference/claims-conflicts), where you can resolve it. How a change is phrased, and the extraction model you use, decide which of the two it becomes. Facts written wrongly by earlier releases with enrichment on can be repaired with the [derived-data repair routes](https://cortexdb.ai/docs/api-reference/admin). ## Filters | Filter | What it does | |---|---| | `predicate` | Only facts with that predicate (`predicate=lives_in`). | | `subject` | Only that subject's facts (`subject=ent_Priya`). | | `min_confidence` | Only facts at or above that confidence (0 to 1). | | `as_of` | Bi-temporal as-of: the value valid at that instant. | | `include_superseded` | `true` adds superseded facts. | To narrow by object, filter the results on your side. `summary_embedding` is not returned on this GET; `POST /v1/beliefs/build` returns embeddings for beliefs. ## How a fact was made (`include=derivation`) Needs capability `derivation_provenance_v1`. Every fact enrichment learns is stamped with how it was made. `include=derivation` on `GET /v1/facts`, `/v1/facts/{id}` and `/v1/facts/timeline` adds a `derivation` object to each row; without it no response changes, and no recall pack or answer ever carries it. ```json "derivation": {"verdict": "accepted", "rule": "accept.default", "policy_hash": "dp1:4be1c0d29a7e3f5b6c8d0e1f2a3b4c5d", "model": "claude-haiku-5-5", "entity_model": "gpt-4o-mini", "prompt_version": "kx-default-batch:9c1e44a0", "gate_version": 1, "topic": "food", "derived_by": null, "pinned": false, "confirmed": false, "unsynced": false} ``` | Field | Meaning | |---|---| | `verdict` | `accepted` for a fact enrichment learned; `declared` for your own write-back stamped with `derived_by`; `null` for a fact with no stamp (written before provenance was recorded, or a typed triple without `derived_by`) | | `rule` | The [derivation policy](https://cortexdb.ai/docs/api-reference/derivation-policy) rule that admitted it (`accept.default`, `accept.consent.health`, `review.approved.`, …); `null` under no policy | | `policy_hash` | The effective policy it was learned under; `dp1:none` when no policy applied | | `model`, `entity_model`, `prompt_version` | The models and the exact prompt version that made it | | `topic` | The taxonomy topic the policy labelled it with, where the policy uses topics | | `derived_by` | A write-back's `{name, version}` stamp | | `pinned`, `confirmed` | A [correction](https://cortexdb.ai/docs/api-reference/corrections) pins or confirms its claim | | `unsynced` | It was learned under another policy than the one in force at its scope now; see [Re-derivation](https://cortexdb.ai/docs/api-reference/derivation-rederive) | What became of one event (learned, nothing admitted, held for review, skipped and why) is [`GET /v1/derivation/decisions`](https://cortexdb.ai/docs/api-reference/derivation-status#what-became-of-one-event). ## Correcting a fact A wrong fact is fixed with a [correction](https://cortexdb.ai/docs/api-reference/corrections) (`reject`, `replace`, `pin`, `confirm`), which stays applied when enrichment runs again. `POST /v1/forget` with `derived_only` removes a fact but lets it be learned again from the same events. ## Notes - Envelope: `{ items, next_cursor, has_more }`. - `GET /v1/facts/timeline?scope=&subject=&predicate=` returns `{ subject, predicate, timeline[] }`, the supersession chain; `subject` there is `{ id }` only, and each entry is `{ fact_id, value, valid_from, valid_to }` (note `fact_id` here, not `id`). - A triple capture takes only `subject`, `predicate` and `object`, and stores the fact as `affirmative`. Negated facts come from extraction. ========================================================================================== # Claims & Conflicts _The bi-temporal record store: point/interval claim queries, per-claim change-logs, and the conflict queue with manual resolution._ Source: https://cortexdb.ai/docs/api-reference/claims-conflicts The **bi-temporal record store** exposes the two-axis history behind the [Facts](https://cortexdb.ai/docs/api-reference/facts) layer: what was true in the world (`valid`) and when CortexDB knew it (`recorded`). It's the query surface over triple-derived facts, plus the queue of detected contradictions. > **Note: Mode-gated, and derived: empty on a content-only self-host** The engine is gated by **`CORTEX_BITEMPORAL_MODE`** = `off` · `shadow` (default) · `enforce`. In **shadow** (the default) it runs on every triple-derived fact, persists `BITEMPORAL` WAL events, and detects conflicts without changing legacy `Fact` fields; in **enforce**, stated dates ground `valid_from`/`valid_to`. Because the records derive from facts, they fill once enrichment is on; on a content-only instance `/v1/claims` returns `{ records: [] }` and `/v1/conflicts` returns `{ conflicts: [], next_cursor: null, total: 0 }`. See [Self-hosting defaults](https://cortexdb.ai/docs/self-hosting/defaults). ## Claim queries **`GET /v1/claims?scope=&subject=&predicate=&valid_as_of=&known_as_of=`**: the two-axis **point** query ("what was true at X, as known at Y"). Swap to **interval-overlap** mode with `valid_during=start..end` and/or `recorded_during=start..end`. Response envelope: `{ records: [...] }`. `scope` alone is accepted; `subject`/`predicate` narrow to one claim. **`GET /v1/claims/history?scope=&subject=&predicate=`**: the full change-log of one claim: every valid interval and every record-time correction, plus the conflicts touching it. Response: ```json { "claim": { "scope": "…", "subject": "…", "predicate": "…" }, "history": [], "conflicts": [] } ``` > **Note: Every validity boundary carries a basis** A finite `valid_from`/`valid_to` is either **`stated`** (the source asserted the world date: render "on/since <date>") or **`observed`** (bounded by when CortexDB learned it: render "by <date>", never "on"). This is how undated state changes stay honest. ## Conflict queue **`GET /v1/conflicts?scope=&status=open|all`**: the queue of competing values for the same claim. Paginated envelope: `{ conflicts: [...], next_cursor, total }`. **`GET /v1/conflicts/{id}`**: one conflict. **`POST /v1/conflicts/{id}/resolve`**: manual resolution with mode **`pick`** (choose a value), **`split`** (both hold over different validity windows), **`new_information`** (a later value supersedes), or **`dismiss`**. Every resolution is an **audited, append-only WAL event**: the record store never mutates in place. See [Audit Trail](https://cortexdb.ai/docs/enterprise/audit-trail). ## See also - [Bi-temporal Model](https://cortexdb.ai/docs/concepts/bi-temporal): the two time axes and supersession. - [GET /v1/facts](https://cortexdb.ai/docs/api-reference/facts): the derived Facts layer these records track. - The MCP tools `list_conflicts` / `resolve_conflict` / `claim_history` wrap these routes: see [MCP Server](https://cortexdb.ai/docs/sdks/mcp-server). ========================================================================================== # GET /v1/beliefs _Query the Beliefs layer: confidence-weighted, evidence-backed claims aggregated from facts._ Source: https://cortexdb.ai/docs/api-reference/beliefs (Request/response shapes are generated from the pinned OpenAPI spec on the live site.) > **Note: Beliefs need facts** The Beliefs layer is derived from [Facts](https://cortexdb.ai/docs/api-reference/facts), so it fills once enrichment produces facts. Facts written by triple captures count too: `POST /v1/beliefs/build` builds one belief per triple topic, with or without enrichment. See [Self-hosting defaults](https://cortexdb.ai/docs/self-hosting/defaults). ## Belief item shape ```json { "id": "belief_894c2d0b44946269313446561724778f", "scope": "org:acme/team:support", "claim": { "subject": { "type": "entity", "id": "ent_Amit", "name": "ent_Amit" }, "predicate": "eats", "object": { "type": "literal", "datatype": "string", "value": "fish" } }, "claim_key": { "subject": "ent_amit", "predicate": "eats", "value": "fish", "polarity": "affirmative", "rules_version": 4 }, "stance": "supported", "confidence": 1.0, "confidence_interval": { "lower": 0.27, "upper": 1.0, "method": "wilson", "level": 0.9 }, "supports": [{ "type": "fact", "id": "fact_01HX...", "weight": 1.0, "polarity": "supports" }], "revision_policy": { "trigger": "new_supporting_evidence_or_contradiction", "min_evidence_delta": 0.05, "cooldown": "PT5M", "max_revisions_per_hour": 12 }, "valid_from": "…", "valid_to": null, "recorded_from": "…", "recorded_to": null, "last_revised_at": "…", "revision_count": 1, "supporting_evidence_redacted": false, "supporting_evidence_redacted_fraction": 0.0 } ``` - The key is **`id`**. The subject is inside `claim.subject`. - **`claim`** is a triple object; **`confidence_interval`** is `{ lower, upper, method, level }`. - **`supports`** is a list of `{ type, id, weight, polarity }`, where `polarity` is **`supports`** or **`against`**. ## Claim keys and stable ids - **`claim_key`** is the form a belief groups and compares on: `{ subject, predicate, value, polarity, rules_version }`, with subject and value folded (lowercase, NFC; `ent_Amit` → `ent_amit`, `José` → `josé`) and the predicate in the built-in ontology's canonical form (a Hindi "पसंद है" fact extracted as `prefers` becomes a `likes` belief). `claim` keeps the latest supporting fact's own words. - **Belief ids are deterministic**: derived from the scope and topic, so rebuilding gives the same ids. ## Stances - **`supported`**: the evidence backs the claim (a belief built from one uncontested fact). - **`contradicted`**: an affirmative fact and a denial of the same value ("lives in Delhi" / "not Delhi"); the denial is listed in `supports` with `polarity: "against"`. - **`deprecated`**: the claim ended ("doesn't work at Acme anymore" closed the fact it updates). A denial of **another** value ("works at Acme" and "does not work at Globex") is listed as `against` (weight 0.5) on the first belief and leaves it `supported` at full confidence. ## Filters and sub-endpoints - Envelope: `{ items, next_cursor, has_more }`. **`about`** narrows to one subject (`about=ent_Priya`); `min_confidence`, `as_of` and `limit` are accepted. - `GET /v1/beliefs/why?belief_id=` → `{ belief, support_graph: { nodes, edges }, narrative, narrative_model }`. Self-hosted, `narrative_model` is the configured answer LLM (e.g. `gpt-4o-mini-2024-07-18`), not the cloud default. - `POST /v1/beliefs/build { scope }` → `{ built: N, items: [...] }` forces a build pass and returns each belief's `summary_embedding`. `GET /v1/beliefs` does not return embeddings; use the build response when you need them. ## Governed beliefs - **How it was made.** `include=derivation` on `GET /v1/beliefs` and `GET /v1/beliefs/why` adds the same `derivation` object [facts](https://cortexdb.ai/docs/api-reference/facts#how-a-fact-was-made-includederivation) carry, read from the belief's latest supporting fact (`unsynced` when any of them is). A declared belief written with a `derived_by` stamp reads `verdict: "declared"`. - **Corrections.** A belief whose claim a [correction](https://cortexdb.ai/docs/api-reference/corrections) pins or confirms reads `supported`, not `contradicted`, and belief refinement never moves it off `supported`. A rejected claim's facts are deleted, and the beliefs built from them with them. - **Writer rules.** A [derivation policy](https://cortexdb.ai/docs/api-reference/derivation-policy#writer-rules) can refuse a declared belief on a field it reserves: `409 WRITER_NOT_ALLOWED`, nothing stored. - **Policies reach the builder.** Beliefs are built only from facts the policy admitted, and a sealed compartment is never blended with its siblings. ========================================================================================== # Episodes _List episodes, narrative spans built from raw events, and declare your own over events a worker read._ Source: https://cortexdb.ai/docs/api-reference/episodes (Request/response shapes are generated from the pinned OpenAPI spec on the live site.) ## Episode item shape An episode is `{ id, scope, summary, events, started_at, ended_at, valid_from, valid_to, recorded_from, recorded_to, sealed }`: `summary` is text such as "Session of N events starting with: …", `events` lists the member events, and `sealed` says whether it is closed. Episodes carry no `actors` field, so filter by actor through the member events rather than an `actor` parameter. The **`causal_chain`** appears with `with_causal_chain=true`, as an ordered list `[{ event_id }]`. ## Behavior notes - Envelope: `{ items, next_cursor, has_more }`. `overlapping=..` filters (`200`). - `POST /v1/episodes/build { scope }` → `{ built: N, items: [...] }` forces a consolidation pass. - Episodes are **sealed once consolidated**: their `events[]` becomes immutable (append-only model). > **Note: Read episodes from the list** There is no single-episode read: list episodes with `GET /v1/episodes` and take the item you need from the list (`GET /v1/episodes/{id}` answers `404`). ## Which events join an episode An event that carries a `directives.extract` list joins episodes only when the list names `episodes`; an event with no list joins as before. A reference root builds no episodes. A [derivation policy](https://cortexdb.ai/docs/api-reference/derivation-policy)'s `episodes` field steers the builder: `session_gap` (instead of two hours), `group_by_label` (never mix events whose label of that key differs), and `builder: off` (build none at the scope, for example because your own worker declares them). ## Declared episodes Needs capability `declared_episodes_v1` (experimental) and data format 11. A worker that groups events itself (a call, a session, a case) stores its own episode over the events it read with `POST /v1/episodes`. It is listed beside the built episodes with `"declared": true`, no rebuild touches it, and **erasing any of its events erases it**. ```bash curl -sS -X POST "$CORTEXDB_URL/v1/episodes" \ -H "Authorization: Bearer $CORTEXDB_TOKEN" -H "Content-Type: application/json" \ -d '{"scope": "org:acme/team:support", "name": "Checkout outage call", "summary": "The checkout service failed for an hour.", "events": ["evt_0196f2a0c1d27b3e9a4f5d6c7b8a9e02", "evt_0196f2a0c1d27b3e9a4f5d6c7b8a9e03"], "derived_by": {"name": "acme-sessionizer", "version": "2.1.0"}, "idempotency_key": "outage-0196"}' # 201 {"id":"ep_0196f2a1…","scope":"org:acme/team:support","name":"Checkout outage call",…,"declared":true} ``` | Field | Notes | |---|---| | `scope` | Required. The episode's scope | | `events` | Required. 1 to 1,024 event ids in the episode's order, each in the tenant and readable by the caller (`422 PROVENANCE_UNKNOWN` otherwise; `409 PROVENANCE_ERASED` for an erased one) | | `name`, `summary` | Required: at most 256 bytes and 4 KiB | | `started_at`, `ended_at` | Default to the first and the last event's times | | `actors_involved` | At most 64 actor ids | | `derived_by` | Your worker's `{name, version}` stamp, served on every read of the episode | | `idempotency_key` | A retry with the same key answers the first episode; another body is `409 IDEMPOTENCY_CONFLICT` | It needs a Writer of the scope with `scope.write`. `DELETE /v1/episodes/{id}?scope=…` erases a declared episode; a built episode belongs to the builder and answers `404`. See the [change feed](https://cortexdb.ai/docs/api-reference/derivation-feed) for the worker that reads the events. ========================================================================================== # GET /v1/understanding _Query the Understanding layer: synthesized, versioned concepts and themes across a scope._ Source: https://cortexdb.ai/docs/api-reference/understanding (Request/response shapes are generated from the pinned OpenAPI spec on the live site.) > **Note: Understanding needs enrichment** The Understanding layer is synthesized by an LLM and is **empty on a content-only self-hosted instance**. See [Self-hosting defaults](https://cortexdb.ai/docs/self-hosting/defaults). ## Concept item shape > **Note: Item shape** A concept is `{ id, scope, ..., supported_by: { events: [...] }, version, stance, staleness_score, support_loss_fraction, coverage_score, synthesis_inputs: { layers, filters, as_of, synthesizer, synthesizer_version }, last_synthesized_at }`. The key is **`id`** (prefix `concept_`); **`supported_by`** is an object keyed by layer; a concept's relations come from the `/related` sub-endpoint. Concepts are **versioned** (`version`). ## Behavior notes - List envelope is `{ items, has_more }`. - `GET /v1/understanding/{id}` → `200` (with or without `?scope`); `GET /v1/understanding/{id}/related` → `{ items, has_more }` (relation enum `specializes / generalizes / contrasts / co_occurs / causes`). - `GET /v1/understanding/coverage` → `{ scope, concept_count, avg_confidence, avg_coverage_score, avg_staleness_score, synthesis_lag, _partial }`: **flat averages** across the scope. - Concepts are also reachable directly: **`GET /v1/concepts?scope=`** returns the same paginated list envelope `{ items, has_more }`, and **`GET /v1/concepts/{id}/history`** returns a concept's semantic-delta **version history**; superseded versions carry `temporal.recorded_to` closed. - `POST /v1/understanding/synthesize { scope, topics }` → `202` `{ job_id, status: "running", lifecycle_stream }` (job id prefix `job_`). Self-hosted, the synthesizer is the configured answer/synth model (e.g. `gpt-5.6-terra`). Synthesis is costly: scope it. > **Note: Where embeddings appear** The list GETs (`GET /v1/understanding`, `GET /v1/facts`, `GET /v1/beliefs`) don't return `summary_embedding`; the `*/build` and `*/synthesize` responses do. ========================================================================================== # /v1/scopes _Register, inspect, and manage hierarchical scopes and their members._ Source: https://cortexdb.ai/docs/api-reference/scopes (Request/response shapes are generated from the pinned OpenAPI spec on the live site.) ## The full scope surface | Route | Result | |---|---| | `POST /v1/scopes` | `201` register a scope (duplicate → `409 SCOPE_REGISTRATION_EXISTS`). | | `GET /v1/scopes?path=` | `{ path, billing_tenant, members, policies, auto_provisioned, created_at }`. `billing_tenant` is server-derived and read-only (`"default"` on a single-tenant self-host; supplying it on registration is not allowed). | | `GET /v1/scopes/list?prefix=` | `{ items: [...] }`: each item is the **full** record, not a minimal subset. | | `PUT /v1/scopes/members?path=` | Replaces the member list (`200`). | | `POST /v1/scopes/prune { older_than, dry_run }` | `{ candidates: [...] }`. | | `DELETE /v1/scopes?path=` | Detaches the scope registration (see below). | ## Behavior notes > **Note: DELETE detaches the registration and keeps the records** Deleting a scope returns **`204`**: it **detaches the registration** (a later `GET /v1/scopes?path=` → `404 "scope not registered"`) and **leaves its events intact**, as with `records=keep`. To remove the data itself, use [forget](https://cortexdb.ai/docs/api-reference/forget) or [erasures](https://cortexdb.ai/docs/api-reference/erasures). > **Note: Ownership** The caller is auto-added as an `owner` member on create. Delete is **owner-gated**: after a `PUT members` that drops your actor, `DELETE` → `403 POLICY_DENIED "owner role required to delete a scope"`. The operator key and no-auth mode are not bound by membership (their `DELETE` returns `204`), so control who holds the operator key rather than relying on membership. > **Note: Scope policies** A scope's `policies` is the server's own `{ children: { auto_register: true } }`; keys such as `retention`, `default_view` or `diagnostics_allowed` sent on create are not stored. Set retention with the [retention routes](https://cortexdb.ai/docs/operations/retention-wal). See [Scopes](https://cortexdb.ai/docs/concepts/scopes) for the hierarchy model and view semantics. ========================================================================================== # /v1/lifecycle _Observe the processing lifecycle of an event: list, per-event summary, SSE stream, and cancel._ Source: https://cortexdb.ai/docs/api-reference/lifecycle The lifecycle API exposes how an event moves through the pipeline: `captured → extracted → indexed → consolidated → …`. See [Lifecycle](https://cortexdb.ai/docs/concepts/lifecycle) for the model. ## List `GET /v1/lifecycle` → `{ items: [...], next_offset, has_more }` (offset pagination). Each item: ```json { "lifecycle_id": "lce_01HX...", "ts": "2026-05-15T10:42:01Z", "scope": "org:acme", "event": "indexed", "data": { "event_id": "evt_01HX...", "layers_indexed": ["events"] } } ``` > **Note: Item field names** The type field is **`event`**, the body is **`data`**, and the **`event_id` lives inside `data`**. ## SSE stream `GET /v1/lifecycle/stream?scope=…` (with `Accept: text/event-stream`). Real frame `data` shapes: | Frame | `data` | |---|---| | `captured` | `{ event_id, wal_offset, actor, modality }` | | `extracted` | `{ event_id, derived: {} }` | | `indexed` | `{ event_id, layers_indexed: ["events"] }` | | `consolidated` | `{ event_id, beliefs_updated, conflicts_resolved }` | > **Note: Two extra event types** Live also emits **`synthesis_progress`** and **`synthesis_complete`** (from `/understanding/synthesize`), in addition to `captured / extracted / indexed / consolidated / compressed / forgotten`. Use `Last-Event-ID` (or the `since_lifecycle_id` filter) to resume. Stream filters: `scope`, `event_id`, `events`, `since_lifecycle_id`. ## Per-event summary and cancel - `GET /v1/lifecycle/event/{lce_id}` → the single lifecycle event. - `GET /v1/lifecycle/memory-event/{id}` → `{ event_id, stages_completed, lifecycle_event_ids, derived }`. On a self-host the sync `derived` came back `{}` even for events that later produced facts: facts arrive via the async enrichment router and are not linked into this summary. - `POST /v1/lifecycle/memory-event/{id}/cancel` (send no body, or `{}` as JSON; an empty body labelled `Content-Type: application/json` → `400`, and `curl -d ''`, which labels it a form, → `415`) → `200` `{ event_id, stages_cancelled, stages_already_completed, excluded_from_recall: true }`. The event leaves `GET /v1/events`, `GET /v1/events/{id}` answers `404`, and it is gone from every recall view (`granular`, `raw`, the default `holistic`, `descend`, `prefer_exhaustive` and `order: "recency"`) and from the `/v1/answer` context. The event is still stored (a later [forget](https://cortexdb.ai/docs/api-reference/forget) by id reports it deleted); use forget or [erasures](https://cortexdb.ai/docs/api-reference/erasures) to delete it. After a cancel, `GET /v1/experience/status` reports the event as `failed` ("excluded from recall after indexing failed terminally"): that is the cancel, not an indexing failure, so don't re-send the write. (Unlike this cancel, an erasure's cancel only reaches a job that is still running.) > **Note: Retry a cancel that answers 404** While other captures are creating new scopes, anywhere on the server, a cancel can answer a spurious `404 NOT_FOUND` and cancel nothing (14 of 30 cancels beside 12 such writers in one test). Unlike forgets and erasures, this route still checks against the scope registry it started with. Retry it; most retries succeed. ========================================================================================== # Derivation status _How far behind a scope's async derived layers are (a catch-up probe for extraction, episodes, beliefs and concepts) and what became of one event._ Source: https://cortexdb.ai/docs/api-reference/derivation-status (Request/response shapes are generated from the pinned OpenAPI spec on the live site.) ## What it answers Writes return `202 captured` and the [derived layers](https://cortexdb.ai/docs/concepts/layers) (episodes, beliefs, concepts) are built **asynchronously** by a background scheduler. `/v1/derivation/status?scope=` tells you whether that catch-up has finished for a scope: the read-your-derived-writes probe. The response (`DerivationStatus`) is flat: | Field | Meaning | |---|---| | `scope` | The scope you asked about. | | `caught_up` | `true` **only** when a write has happened, nothing is queued, ingest has been idle ~60 s, **and** the scheduler rebuilt after the last write. | | `dirty` | Work is currently queued for this scope. | | `idle_seconds` | Seconds since the last write to the scope (`null` if never written). | | `last_write_at` / `last_built_at` / `last_tick_at` | Timestamps of the last write, last successful build, and last scheduler tick (`null` until they occur). | | `built` | Counts produced so far: `{ episodes, beliefs, concepts, errors }`. | `scope` is a **required query parameter**: omitting it returns `400` (plain text: "Failed to deserialize query string: missing field `scope`"), like other query-string validation. > **Note: Use it to gate reads after bulk ingest** After a batch import or a burst of writes, poll until `caught_up: true` (or `dirty: false` with an `idle_seconds` past your threshold) before relying on the Facts/Beliefs/Understanding layers or on `order`-sensitive recall. For a single event, prefer `?wait=indexed` on the [write](https://cortexdb.ai/docs/api-reference/experience) instead of polling here. ## Extraction, governance and write-backs The top-level fields above are the auto-layer scheduler's. Facts are learned separately, by the background enrichment, and three new parts report on it: - **`extraction`** (capability `derivation_provenance_v1`): the scope's events by what enrichment did with them (`learned`, `nothing_admitted`, `held_only`, `failed`), how many are still `pending`, and its own `caught_up`. The top-level `caught_up`, which `cortexdb-sync --wait-derivation` polls, keeps its meaning. - **`governance`** (capability `derivation_rederive_v1`): how much of the subtree was learned under the [derivation policy](https://cortexdb.ai/docs/api-reference/derivation-policy) in force (`current`) and under another (`unsynced`), with open held candidates, corrections in force and open re-derivation jobs. `facts.stale_restrictions` is what the last `regate` dry run counted. See [Re-derivation](https://cortexdb.ai/docs/api-reference/derivation-rederive). - **`derived_by`**: with `?derived_by=[,…]` (at most 8 pipelines or importers, such as `acme-level` or `import:mem0`), the latest version each wrote, and how many rows were written under older versions (`unsynced`): the rows your pipeline should write again. ```json "extraction": {"caught_up": false, "pending": 1820, "learned": 51022, "nothing_admitted": 912, "held_only": 0, "failed": 3, "last_learned_at": "2026-10-27T09:13:40Z"}, "governance": {"policy_hash": "dp1:4be1c0d29a7e3f5b6c8d0e1f2a3b4c5d", "events": {"current": 48211, "unsynced": 3711}, "facts": {"current": 47002, "unsynced": 4020, "stale_restrictions": null}, "held_open": 14, "corrections": 37, "jobs_open": []}, "derived_by": [{"name": "acme-level", "latest": "1.1.0", "current": 992, "unsynced": 211, "complete": true}] ``` ## What became of one event `GET /v1/derivation/decisions?scope=…&event_id=evt_…` (capability `derivation_provenance_v1`) answers whether enrichment learned something from one event, nothing, or has not got to it yet, and why. ```json {"event_id": "evt_0196f2a0c1d27b3e9a4f5d6c7b8a9e01", "outcome": "nothing_admitted", "policy_hash": "dp1:none", "prompt_version": "kx-default-batch:9c1e44a0", "models": {"knowledge": "claude-haiku-5-5", "entity": "gpt-4o-mini"}, "accepted": 0, "held": 0, "rejected": {}, "at": "2026-11-07T10:05:00Z", "computed": false} ``` | `outcome` | Meaning | |---|---| | `learned` | At least one candidate was accepted (`accepted` counts them) | | `nothing_admitted` | Derived, and nothing was accepted or produced | | `held_only` | Candidates were held for [review](https://cortexdb.ai/docs/api-reference/review), none accepted | | `failed` | The attempt failed; `retrying` says whether a retry is queued | | `pending` | Enrichment has not reached the event yet | | `skipped` | Enrichment does not take it now; `reason` says why: `enrich_off`, `reference_root`, `extract_none`, `typed_triple`, `no_content`, `budget` (a policy's daily budget is spent until the next UTC midnight), `mode_off`, `not_explicit`, `detector` or `source_rule` | Rejected candidates are counted by rule in `rejected`, never described. A Reader of the event's scope may call it; any event the caller may not read answers the same `404`. > **Note: built stays 0 without enrichment** `built.beliefs` / `built.concepts` only advance when the LLM-derived layers are enabled: on a content-only instance `built` stays `{ episodes: 0, beliefs: 0, concepts: 0, errors: 0 }` because enrichment is off by default. `caught_up` still reflects the scheduler state regardless. See [Self-hosting defaults](https://cortexdb.ai/docs/self-hosting/defaults). ========================================================================================== # Derivation Policies _Typed rules for what CortexDB's enrichment may learn under a scope: staged through change sets, tested on real events, layered down the scope tree, with subject settings, templates and a sensitive-topic taxonomy._ Source: https://cortexdb.ai/docs/api-reference/derivation-policy (Request/response shapes are generated from the pinned OpenAPI spec on the live site.) A **derivation policy** is a set of typed rules for what CortexDB's background enrichment may learn under a scope: which events it reads, which topics and sensitive values it never keeps, how a field's values replace each other, who may set a field, what waits for review, which model it runs and what it may spend. It is data, stored as a record at `/attrs:derive`, and it governs the scope's whole subtree. For the concept and the guarantees, see [Governed Memory](https://cortexdb.ai/docs/features/governed-memory). Needs capability `derivation_policy_v1`; experimental. The policy read, the templates, the taxonomy and the test work at any data format; staging a policy, subject settings and policy texts need data format 11 (`503 FORMAT_UPGRADE_PENDING` on a server held at format 10). ## Stage a policy A policy changes only through a [change set](https://cortexdb.ai/docs/shared-memory/change-sets): stage, preview, activate. A change set that writes a derive record writes nothing else. ```bash curl -sS -X POST "$CORTEXDB_URL/v1/access/changes" \ -H "Authorization: Bearer $CORTEX_API_KEY" -H "Content-Type: application/json" \ -d '{ "id": "derive-companion-v1", "scope": "org:acme", "reason": "Consumer defaults for the companion app", "parts": [{"part": 0, "records": [ {"path": "org:acme/app:companion/attrs:derive", "op": "put", "record": {"tree": {"kind": "derive"}, "derive": {"v": 1, "from_template": "consumer@1", "mode": "automatic", "topics": {"deny": ["payment_data", "government_ids", "secrets"], "deny_unless_consent": ["gdpr_art9"], "on_unknown": "accept"}, "detectors": {"deny": ["payment_card", "iban", "government_id", "secret"], "action": "drop", "source_action": "redact"}, "on_unlisted_predicate": "contest", "instructions": [{"text": "Keep what helps the user plan meals and trips."}], "examples": [ {"input": "I am vegetarian and I hate early flights.", "memories": ["User is vegetarian", "User dislikes early flights"], "synthetic": true}, {"input": "lol ok whatever", "memories": [], "synthetic": true}]}}}]}] }' ``` The preview of a derivation change set has a `derivation` section: each record's rules before and after, each governed scope's effective policy hash before and after with the rules that move, whether the change only tightens (`narrowing`), the texts it names, and `unsynced_impact`, how many events and facts were learned under the old policy and will read as unsynced once it activates (see [Re-derivation](https://cortexdb.ai/docs/api-reference/derivation-rederive)). The approval binds that section: if an ancestor's policy, a subject's settings or a named text changes before activation, activation is refused with `409 PREVIEW_CHANGED`. **Who may stage one:** an Owner of the governed scope or of the tenant root, with `derivation.administer.scope` (or `policy.administer.scope`) there. `derivation.administer.scope` governs learning only; it grants no access administration. ## The policy body The body is strict: an unknown key or a value out of range is `422 DERIVATION_POLICY_INVALID`, with the field named in `details.field`. | Field | Values | Kind | |---|---|---| | `mode` | `off`; `explicit` (only events labelled `memory:remember` or carrying a non-empty `directives.extract`); `review` (every candidate held for review); `automatic` | Restriction | | `stages` | A subset of `facts`, `entities`, `beliefs`, `episodes`, `understanding`; `[]` learns nothing | Restriction | | `topics.deny`, `topics.deny_unless_consent` | Taxonomy categories or groups, or your own topics' ids (at most 64 each) | Restriction | | `topics.allow` | `null`, or at most 64 ids: everything else is denied | Restriction | | `topics.custom` | Your own topics: `{id, label, description}` (at most 64) | Steering | | `topics.on_unknown` | `accept`, `hold` or `drop`, for a candidate with no topic label | Restriction | | `detectors.deny` | Detector ids or packs (at most 64) | Restriction | | `detectors.action` | `drop`, `redact_value` or `hold`, for a candidate a detector matches | Restriction | | `detectors.source_action` | `send`, `redact` (mask the matches before the model sees the text) or `skip` (no model call for the event) | Restriction | | `detectors.apply_to_declared` | Also refuse your own declared writes (typed triples, declared beliefs) a detector matches | Restriction | | `sources.roles`, `sources.actors` | Which messages are read: `user`, `assistant`, `system`, `tool`; `person`, `agent`, `service` | Restriction | | `sources.exclude_labels`, `sources.exclude_intents` | Events to leave out (at most 64 each) | Restriction | | `sources.fenced_context` | `ignore` (the default in every template) or `allow`: whether recall packs quoted back into a conversation are read | Restriction | | `grounding.quotes` | `required` (each memory must quote its source) or `preferred` | Restriction | | `grounding.reject` | Any of `hypothetical`, `planned`, `joke`, `reported` | Restriction | | `predicates` | Per field (at most 256): `cardinality` (`single` or `multi`), `on_conflict` (`latest_wins`, `contest`, `keep_first`), `synonyms`, and the writer rules `writers` and `requires` | Steering; writer rules are restrictions | | `on_unlisted_predicate` | `contest`, `latest_wins`, `hold` or `drop`, for a field the policy does not list | Steering | | `entity_types` | `allow`: `null` or a subset of the built-in entity types; `strict`: drop the others | Restriction | | `review.hold` | Hold candidates by `topics`, `predicates`, `refused_writers` (hold rather than drop what a writer rule refuses), `confidence_below` (0 to 1) | Restriction | | `review.lapse_days` | 1 to 90 (default 30): an undecided candidate lapses | Restriction | | `review.reviewers` | Principals or sets who may decide; empty means the scope's Writers | Steering | | `episodes` | `session_gap` (1 minute to 7 days), `group_by_label`, `builder` (`on`, or `off` when your own worker declares episodes) | Steering | | `compartment` | `open` or `sealed`: summaries across scopes never blend a sealed subtree with its siblings | Restriction | | `model`, `entity_model` | `null` (the server's own model) or a model the operator allows | Steering | | `output_language` | `source`, or a language tag | Steering | | `budget_usd_per_day` | 0 to 1,000 US dollars a UTC day for extraction under the policy | Restriction | | `instructions`, `examples` | Up to 8 instructions and 32 examples (see [Policy texts](#policy-texts)) | Steering | | `use` | [Read-time use rules](#read-time-use-rules) | Restriction | ## How policies combine A scope's **effective policy** comes from the derive records along its path and its org chart, and from subject settings: - **Restrictions accumulate.** Deny lists are joined, allow lists intersected, the strictest value wins, budgets and lapse days take the smallest. A rule set on an org-chart parent still binds: a person's scope under a team cannot escape an application's denial. - **Steering is nearest-wins.** Instructions, examples, models, output language, episodes, reviewers, and each field's cardinality and conflict rule come from the nearest scope that sets them. - **A child cannot widen an ancestor.** Staging a looser rule (an `allow` naming what an ancestor denies, a looser `mode`, a higher budget) is refused with `422 DERIVATION_POLICY_WIDENS`, naming the rule and the ancestor. - **The server's own settings come first.** With enrichment off, a scope outside the enrichment allowlist, an effective `enrich: off` or a reference root, nothing is learned whatever a policy says. - **No policy anywhere** is the empty policy, `dp1:none`: enrichment derives every stage. `GET /v1/derivation/policy?scope=…` answers the effective policy: each restriction with every scope that sets it (`set_at`), each steering field with the one scope that set it, the values set on the path that have no effect there and why (`ineffective`), and the policy's hash (`dp1:` and 32 hex digits). Every fact learned under a policy is stamped with that hash. `include=texts` adds the instructions' and examples' text, for an Owner with `derivation.administer.scope`. ## Templates and the taxonomy `GET /v1/derivation/templates` serves ready-made policies: | Template | For | |---|---| | `consumer@1` | Protective defaults for consumer and companion apps | | `minimal@1` | Remember only what the user asks | | `enterprise@1` | Work memory over chat, tickets and documents | | `minor@1` | Apps used by minors; carries the [read-time use rule](#read-time-use-rules) | | `health_app@1` | Health apps | Applying a template copies its body into your record (`from_template` only names where it came from), so upgrading CortexDB never changes a stored policy. `GET /v1/derivation/taxonomy` serves the sensitive-topic taxonomy: 20 categories (`health`, `sex_life_orientation`, `gender_identity`, `religion_belief`, `political_opinion`, `union_membership`, `racial_ethnic_origin`, `genetic`, `biometric`, `neural`, `precise_geolocation`, `government_id`, `financial_account`, `payment_card`, `credentials`, `criminal_record`, `immigration_status`, `communications_content`, `minor_status`, `personal_matters`), the groups that name them (`gdpr_art9`, `cpra_spi`, `wa_consumer_health`, `ny_art48_personal`, `government_ids`, `payment_data`, `secrets`), and the detector catalogue with each detector's precision and locales. > **Note: Topic labels are a model's judgment** A candidate's topic is labelled by the extraction model, so a denied topic can leak when the model labels a candidate otherwise. Detectors and the structural rules (stages, sources, grounding, writer rules) are exact. Test a topic policy on your own events before you rely on it. ## Test a draft `POST /v1/derivation/policy/test` runs extraction and the policy over up to 200 of your events under a draft, and answers each candidate's verdict and rule, beside the active policy's. **It writes nothing.** ```bash curl -sS -X POST "$CORTEXDB_URL/v1/derivation/policy/test" \ -H "Authorization: Bearer $CORTEXDB_TOKEN" -H "Content-Type: application/json" \ -d '{"scope": "org:acme/app:companion", "policy": {"v": 1, "topics": {"deny": ["gdpr_art9"]}, "on_unlisted_predicate": "contest"}, "sample": {"recent": 50}, "compare_with_active": true, "max_cost_usd": 1.00}' ``` ```json {"policy_hash": "dp1:9a14c0d29a7e3f5b6c8d0e1f2a3b4c5d", "active_policy_hash": "dp1:none", "events": [{"event_id": "evt_0196…", "outcome": "learned", "candidates": [ {"kind": "triple", "subject": "user", "predicate": "diet", "object": "vegetarian", "topic": "food", "verdict": "accepted", "rule": "accept.default", "active": "accepted"}, {"kind": "triple", "subject": "user", "predicate": "has_condition", "object": "asthma", "topic": "health", "verdict": "rejected", "rule": "topic.deny.health", "active": "accepted"}]}], "summary": {"events": 50, "accepted": 61, "held": 0, "rejected": {"topic.deny.health": 4, "detector.payment_card": 1}, "unlabelled": 3}, "diff": {"added": 0, "removed": 5, "changed_conflict_rule": 2}, "cost": {"calls": 12, "usd": 0.31, "model": "claude-haiku-5-5"}} ``` - **The draft** is a policy body (`policy`), which takes the place of the scope's own record while every ancestor's restrictions still apply, or `changeset: {id, scope}`, your own staged change set. - **The sample** is `sample.recent` (1 to 200 of the newest events you can read) or `sample.event_ids` (at most 200). - **Rejected candidates are shown with their text.** The answer goes only to a caller who can read the sample events, and nothing of it is stored or logged. `unlabelled` counts candidates with no topic label. - **Cost.** `max_cost_usd` (default 1) caps the run and is reserved from the tenant's daily budget for tests and dry runs (`CORTEX_DERIVATION_BUDGET_USD`, 5 US dollars by default). Events past the cap answer `not_run`. A model the price book cannot price is refused. It needs an Owner with `derivation.administer.scope` and `llm.invoke`, and a server with enrichment on (`409 ENRICHMENT_OFF` otherwise). ## Writer rules A field's `writers` say who may set it: `extraction`, `triple` (a typed triple you write), `declared_belief`, `correction` (a correction's replacement), `review` (an approved review decision), `derived_by:` (a write-back stamped with that name), `app:service:`, or `source: cortexdb-sync serve --port 8081 ``` Then in Freshdesk → Admin → Workflows → Automations, add a **Trigger webhook** action pointing at `POST https:///webhooks/freshdesk/events` with `Authorization: Bearer `. The webhook path uses the same normalizer as polling, so running both `serve` and `sync` is safe. ## Run it yourself ```bash pip install cortexdb-connectors pip install cortexdb-cli && cortexdb init export FRESHDESK_DOMAIN=acme.freshdesk.com # required export FRESHDESK_API_KEY=... # required export FRESHDESK_INCLUDE_CONVERSATIONS=1 # 0 = tickets only, bodies still ingested export FRESHDESK_INCLUDE_ATTACHMENTS=1 # 0 = skip attachment blobs cortexdb-sync --api-url http://localhost:3141 sync freshdesk cortexdb-sync --api-url http://localhost:3141 watch freshdesk --interval 300 ``` > **Note:** `FRESHDESK_INCLUDE_CONVERSATIONS=0` drops only the reply and note episodes: the ticket description is always ingested. ## Limits and behaviour worth knowing - Attachments over **32 MiB** are recorded metadata-only: the filename survives, the bytes are not uploaded. - Rate limits are handled: requests retry `429`/`5xx` with `Retry-After`, up to 5 attempts. - A ticket that cannot be fetched holds the cursor and is retried; after 5 consecutive failed cycles it is dead-lettered and `cortexdb-sync status` reports it. - **Deletions are not propagated** from the poll path: a deleted reply remains as retained history. ## See also - [Connectors overview](https://cortexdb.ai/docs/connectors) · [Zendesk](https://cortexdb.ai/docs/connectors/zendesk) · [Intercom](https://cortexdb.ai/docs/connectors/intercom) - [POST /v1/experience](https://cortexdb.ai/docs/api-reference/experience) ========================================================================================== # tl;dv Connector _Ingest tl;dv meeting recordings and speaker-segmented transcripts into CortexDB._ Source: https://cortexdb.ai/docs/connectors/tldv Captures tl;dv meetings and their speaker-segmented transcripts as CortexDB experiences: one episode per meeting, stamped with the meeting's real time so your meeting timeline is queryable alongside everything else. > **Note: Two ways to run this connector** **Run it yourself**: `pip install cortexdb-connectors` then `cortexdb-sync sync tldv`. **Managed**: CortexDB runs the same connector as a worker. See the [Connectors overview](https://cortexdb.ai/docs/connectors). ## 1. Prepare credentials in tl;dv tl;dv → Settings → API. Copy the API key. The connector sends it as the **`x-api-key`** header. ## 2. Configure (managed dashboard) Settings → Connectors → Add Connector → tl;dv. Paste the API key, set the scope template (default `org:/source:tldv`), and Start sync. ## What gets written One **episode per meeting**, `episode_type = meeting`, whose content is the meeting name followed by the transcript rendered as speaker-attributed turns. | Field | Value | |---|---| | `occurred_at` | The meeting's real `happenedAt` time, not ingest time | | `actor` | The organizer's display name and email | | `thread_id` | `tldv:meeting:` | | `entities` | One meeting entity, so you can scope by `{entity.meeting}` | | `metadata` | `meeting_id`, `name`, and the tl;dv url | ## Visibility Derived per meeting from tl;dv's own privacy signals, explicit private/visibility flags and invitee count, rather than a fixed level: | Signal | Visibility | |---|---| | Marked private, or a 1:1 | `private`, with invitees as the allow-list | | Limited invitee set | `restricted`, with invitees as the allow-list | | Otherwise | `organization` | For hard per-meeting isolation, use a scope template containing `{entity.meeting}`. ## Idempotency and history ```text tldv:: ``` The key is **content-versioned**, which matters more here than for most sources: a meeting is often listed before its transcript is ready. When the transcript later arrives, or the meeting is re-transcribed or renamed, the content changes, so a new key is minted and the corrected version lands as retained history. A key based on the meeting id alone would reject it and error on every subsequent sync. > **Note: The key on the wire is derived** The key format above is this connector's internal record identity: it decides which source record an event belongs to. The `idempotency_key` actually sent to CortexDB is a derived `cxsrc:<56 hex>` value that also hashes the content, labels, observed time and actor, so an unchanged redelivery converges on the same event while any edit lands as a new one, even where the key format itself is not content-versioned. Every event also carries a `source` descriptor with the record's fingerprint. See [Source identity and keys](https://cortexdb.ai/docs/connectors#source-identity-and-keys). ## Real-time delivery (webhook) tl;dv **does not sign its payloads**, so the receiver authenticates on a static header: ```bash pip install 'cortexdb-connectors[webhooks]' # serve needs starlette + uvicorn export TLDV_WEBHOOK_SECRET= cortexdb-sync serve --port 8081 ``` Point tl;dv's **MeetingReady** / **TranscriptReady** webhooks at `POST https:///webhooks/tldv/events` with `Authorization: Bearer `. The webhook path builds its episode through the same builder as polling, so a meeting seen by both paths dedupes to one stored copy. ## Run it yourself ```bash pip install cortexdb-connectors pip install cortexdb-cli && cortexdb init export TLDV_API_KEY=... # required cortexdb-sync --api-url http://localhost:3141 sync tldv cortexdb-sync --api-url http://localhost:3141 watch tldv --interval 300 ``` Cursor state persists in `~/.cortexdb/sync_state.json`. ## Behaviour worth knowing - **Late transcripts are handled**: the connector re-lists a 24-hour window behind its stored cursor, so a meeting whose transcript becomes ready after a newer meeting advanced the cursor is still picked up. - Rate limits and outages are retried with backoff on `429`/`5xx`, honouring `Retry-After`. - A failed transcript fetch is logged loudly rather than silently ingesting an empty body. - **Deletions are not propagated**: a meeting deleted in tl;dv remains in CortexDB as retained history (the [append-only model](https://cortexdb.ai/docs/concepts/event-sourcing)). ## See also - [Connectors overview](https://cortexdb.ai/docs/connectors) · [Slack](https://cortexdb.ai/docs/connectors/slack) · [Microsoft Teams](https://cortexdb.ai/docs/connectors/teams) - [POST /v1/recall](https://cortexdb.ai/docs/api-reference/recall) ========================================================================================== # Linear Connector _Ingest Linear issues and comments into CortexDB._ Source: https://cortexdb.ai/docs/connectors/linear Tails Linear issues and their comments and writes them to CortexDB as experiences. > **Note: Two ways to run this connector** **Run it yourself**: `pip install 'cortexdb-connectors[linear]'` then `cortexdb-sync sync linear`. **Managed**: CortexDB runs the connector as a worker. See the [Connectors overview](https://cortexdb.ai/docs/connectors). ## 1. Prepare credentials Linear → Settings → API → Personal API keys → create a key and copy it. ## What gets written Each issue and comment becomes a `POST /v1/experience` on the resolved scope (default `org:/source:linear/team:{team}`), with the author resolved and the body as `content`, plus an entity reference to the issue. > **Note: Record keys and threads** - The **`idempotency_key`** uses the **`linear:`** prefix (not `lin:`). - Comments link to their issue via a **`thread=…` label**, not `context.preceded_by`. > **Note: The key on the wire is derived** The key format above is this connector's internal record identity: it decides which source record an event belongs to. The `idempotency_key` actually sent to CortexDB is a derived `cxsrc:<56 hex>` value that also hashes the content, labels, observed time and actor, so an unchanged redelivery converges on the same event while any edit lands as a new one, even where the key format itself is not content-versioned. Every event also carries a `source` descriptor with the record's fingerprint. See [Source identity and keys](https://cortexdb.ai/docs/connectors#source-identity-and-keys). ## Run it yourself ```bash pip install 'cortexdb-connectors[linear]' pip install cortexdb-cli && cortexdb init export LINEAR_API_KEY=lin_api_... # required cortexdb-sync --api-url http://localhost:3141 sync linear cortexdb-sync --api-url http://localhost:3141 watch linear --interval 120 ``` ### Optional settings Set these as environment variables (or the matching keys in the `cortexdb-sync` YAML config). Lists are comma-separated. For on/off settings, `1`, `true`, `yes` or `on` turns the setting on and any other value turns it off. | Setting | What it does | Default | |---|---|---| | `LINEAR_TEAMS` | Team IDs to sync | Every team the API key can see | ## See also - [Connectors overview](https://cortexdb.ai/docs/connectors) · [Jira](https://cortexdb.ai/docs/connectors/jira) · [GitHub](https://cortexdb.ai/docs/connectors/github) - [POST /v1/experience](https://cortexdb.ai/docs/api-reference/experience) ========================================================================================== # Confluence Connector _Ingest Confluence pages and comments into CortexDB._ Source: https://cortexdb.ai/docs/connectors/confluence Tails Confluence pages (and their versions) and comments, and writes them to CortexDB as experiences. > **Note: Two ways to run this connector** **Run it yourself**: `pip install 'cortexdb-connectors[confluence]'` then `cortexdb-sync sync confluence`. **Managed**: CortexDB runs the connector as a worker. See the [Connectors overview](https://cortexdb.ai/docs/connectors). ## 1. Prepare credentials Create an API token at `id.atlassian.com/manage-profile/security/api-tokens`. You need your Confluence site URL, the account email, and the token (HTTP Basic `email:token`). ## What gets written Each page (as a `document`) and comment (as a `conversation`) becomes a `POST /v1/experience` on the resolved scope (default `org:/source:confluence/ws:{space}`), with an entity reference to the page. > **Note: Record keys and threads** - The comment **`idempotency_key`** is `comment:{comment_id}:v{version}`: there is **no `conf:` prefix**. - Comments link to their page via a **`thread=…` label**, not `context.preceded_by`. > **Note: The key on the wire is derived** The key format above is this connector's internal record identity: it decides which source record an event belongs to. The `idempotency_key` actually sent to CortexDB is a derived `cxsrc:<56 hex>` value that also hashes the content, labels, observed time and actor, so an unchanged redelivery converges on the same event while any edit lands as a new one, even where the key format itself is not content-versioned. Every event also carries a `source` descriptor with the record's fingerprint. See [Source identity and keys](https://cortexdb.ai/docs/connectors#source-identity-and-keys). ## Run it yourself ```bash pip install 'cortexdb-connectors[confluence]' pip install cortexdb-cli && cortexdb init export CONFLUENCE_URL=https://acme.atlassian.net # required export CONFLUENCE_EMAIL=you@acme.com # required export CONFLUENCE_API_TOKEN=... # required cortexdb-sync --api-url http://localhost:3141 sync confluence cortexdb-sync --api-url http://localhost:3141 watch confluence --interval 300 ``` ### Optional settings Set these as environment variables (or the matching keys in the `cortexdb-sync` YAML config). Lists are comma-separated. For on/off settings, `1`, `true`, `yes` or `on` turns the setting on and any other value turns it off. | Setting | What it does | Default | |---|---|---| | `CONFLUENCE_SPACES` | Space keys to sync | Every space the account can see | ## See also - [Connectors overview](https://cortexdb.ai/docs/connectors) · [Jira](https://cortexdb.ai/docs/connectors/jira) · [Notion](https://cortexdb.ai/docs/connectors/notion) - [POST /v1/experience](https://cortexdb.ai/docs/api-reference/experience) ========================================================================================== # Notion Connector _Ingest Notion pages and comments into CortexDB._ Source: https://cortexdb.ai/docs/connectors/notion Tails Notion pages and comments and writes them to CortexDB as experiences, polling on `last_edited_time`. > **Note: Two ways to run this connector** **Run it yourself**: `pip install 'cortexdb-connectors[notion]'` then `cortexdb-sync sync notion`. **Managed**: CortexDB runs the connector as a worker. See the [Connectors overview](https://cortexdb.ai/docs/connectors). ## 1. Prepare credentials Create an internal integration at `notion.so/my-integrations`, copy its token, and **share the pages / databases** you want ingested with the integration (Notion integrations only see explicitly shared content). ## What gets written Each page (as a `document`) and comment becomes a `POST /v1/experience` on the resolved scope (default `org:/source:notion`), with an entity reference to the page. > **Note: Record keys and threads** - The **`idempotency_key`** is `notion::` (a re-edit lands as a new version). - Comments link to their page via a **`thread=…` label**, not `context.preceded_by`. > **Note: The key on the wire is derived** The key format above is this connector's internal record identity: it decides which source record an event belongs to. The `idempotency_key` actually sent to CortexDB is a derived `cxsrc:<56 hex>` value that also hashes the content, labels, observed time and actor, so an unchanged redelivery converges on the same event while any edit lands as a new one, even where the key format itself is not content-versioned. Every event also carries a `source` descriptor with the record's fingerprint. See [Source identity and keys](https://cortexdb.ai/docs/connectors#source-identity-and-keys). ## Run it yourself ```bash pip install 'cortexdb-connectors[notion]' pip install cortexdb-cli && cortexdb init export NOTION_TOKEN=secret_... # required (shared with the pages you want ingested) cortexdb-sync --api-url http://localhost:3141 sync notion cortexdb-sync --api-url http://localhost:3141 watch notion --interval 300 ``` ### Optional settings Set these as environment variables (or the matching keys in the `cortexdb-sync` YAML config). Lists are comma-separated. For on/off settings, `1`, `true`, `yes` or `on` turns the setting on and any other value turns it off. | Setting | What it does | Default | |---|---|---| | `NOTION_DATABASES` | Database IDs whose entries to sync | None | | `NOTION_PAGES` | Page IDs to sync, including after they are archived | None | | `NOTION_LEDGER_PATH` | File that records pages seen in earlier syncs | `~/.cortexdb/notion_pages_ledger.json` | Recently edited pages shared with the integration are always searched; the two lists add specific databases and pages on top. ## See also - [Connectors overview](https://cortexdb.ai/docs/connectors) · [Confluence](https://cortexdb.ai/docs/connectors/confluence) - [POST /v1/experience](https://cortexdb.ai/docs/api-reference/experience) ========================================================================================== # PagerDuty Connector _Ingest PagerDuty incidents and notes into CortexDB._ Source: https://cortexdb.ai/docs/connectors/pagerduty Tails PagerDuty incidents and their log entries / notes and writes them to CortexDB as experiences. > **Note: Two ways to run this connector** **Run it yourself**: `pip install 'cortexdb-connectors[pagerduty]'` then `cortexdb-sync sync pagerduty`. **Managed**: CortexDB runs the connector as a worker. See the [Connectors overview](https://cortexdb.ai/docs/connectors). ## 1. Prepare credentials PagerDuty → Integrations → API Access Keys → create a read-only REST API key and copy it. ## What gets written Each incident (as an `issue`/`observation`) and note becomes a `POST /v1/experience` on the resolved scope (default `org:/source:pagerduty`), with an entity reference to the incident and metadata (status, urgency, service). > **Note: Record keys and threads** - The internal **`idempotency_key`** is the raw PagerDuty incident id or log-entry id (no `pd:` prefix); `pd:incident:` is the thread id that links log entries to their incident. - Notes link to their incident via a **`thread=…` label**, not `context.preceded_by`. > **Note: The key on the wire is derived** The key format above is this connector's internal record identity: it decides which source record an event belongs to. The `idempotency_key` actually sent to CortexDB is a derived `cxsrc:<56 hex>` value that also hashes the content, labels, observed time and actor, so an unchanged redelivery converges on the same event while any edit lands as a new one, even where the key format itself is not content-versioned. Every event also carries a `source` descriptor with the record's fingerprint. See [Source identity and keys](https://cortexdb.ai/docs/connectors#source-identity-and-keys). ## Run it yourself ```bash pip install 'cortexdb-connectors[pagerduty]' pip install cortexdb-cli && cortexdb init export PAGERDUTY_API_KEY=... # required cortexdb-sync --api-url http://localhost:3141 sync pagerduty cortexdb-sync --api-url http://localhost:3141 watch pagerduty --interval 120 ``` ### Optional settings Set these as environment variables (or the matching keys in the `cortexdb-sync` YAML config). Lists are comma-separated. For on/off settings, `1`, `true`, `yes` or `on` turns the setting on and any other value turns it off. | Setting | What it does | Default | |---|---|---| | `PAGERDUTY_SERVICES` | Service IDs to sync | Every service | ## See also - [Connectors overview](https://cortexdb.ai/docs/connectors) · [Freshdesk](https://cortexdb.ai/docs/connectors/freshdesk) - [POST /v1/experience](https://cortexdb.ai/docs/api-reference/experience) ========================================================================================== # Discord Connector _Ingest Discord channel messages into CortexDB._ Source: https://cortexdb.ai/docs/connectors/discord Tails Discord channel messages and writes them to CortexDB as conversation experiences. > **Note: Two ways to run this connector** **Run it yourself**: `pip install 'cortexdb-connectors[discord]'` then `cortexdb-sync sync discord`. **Managed**: CortexDB runs the connector as a worker. See the [Connectors overview](https://cortexdb.ai/docs/connectors). ## 1. Prepare credentials Discord Developer Portal → New Application → Bot → copy the bot token. Enable the **Message Content Intent**, and invite the bot to your server with **Read Messages / View Channels** + **Read Message History** permissions. ## What gets written Each message becomes a `POST /v1/experience` on the resolved scope (default `org:/source:discord/team:{guild}/project:{channel}`), author resolved to a username, body as `content`. > **Note: Record keys and threads** - The **`idempotency_key`** is `discord:` (not a `dc:::` composite). - Thread replies attach a **`thread=…` label**, not `context.preceded_by`. > **Note: The key on the wire is derived** The key format above is this connector's internal record identity: it decides which source record an event belongs to. The `idempotency_key` actually sent to CortexDB is a derived `cxsrc:<56 hex>` value that also hashes the content, labels, observed time and actor, so an unchanged redelivery converges on the same event while any edit lands as a new one, even where the key format itself is not content-versioned. Every event also carries a `source` descriptor with the record's fingerprint. See [Source identity and keys](https://cortexdb.ai/docs/connectors#source-identity-and-keys). ## Run it yourself ```bash pip install 'cortexdb-connectors[discord]' pip install cortexdb-cli && cortexdb init export DISCORD_BOT_TOKEN=... # required cortexdb-sync --api-url http://localhost:3141 sync discord cortexdb-sync --api-url http://localhost:3141 watch discord --interval 60 ``` ### Optional settings Set these as environment variables (or the matching keys in the `cortexdb-sync` YAML config). Lists are comma-separated. For on/off settings, `1`, `true`, `yes` or `on` turns the setting on and any other value turns it off. | Setting | What it does | Default | |---|---|---| | `DISCORD_CHANNELS` | Channel IDs to sync (takes precedence over guilds) | None | | `DISCORD_GUILDS` | Guild (server) IDs; their text channels are synced | None | Set `DISCORD_CHANNELS` or `DISCORD_GUILDS`: with neither, there is nothing to sync. ## See also - [Connectors overview](https://cortexdb.ai/docs/connectors) · [Slack](https://cortexdb.ai/docs/connectors/slack) - [POST /v1/experience](https://cortexdb.ai/docs/api-reference/experience) ========================================================================================== # Microsoft Teams Connector _Ingest Microsoft Teams channel messages, threaded replies, and 1:1/group chats into CortexDB._ Source: https://cortexdb.ai/docs/connectors/teams Captures Teams channel and chat messages via the Microsoft Graph v1.0 API, polled incrementally on `lastModifiedDateTime`. > **Note: Two ways to run this connector** **Run it yourself**: `pip install 'cortexdb-connectors[teams]'` then `cortexdb-sync sync teams`. **Managed**: CortexDB runs the connector as a worker. See the [Connectors overview](https://cortexdb.ai/docs/connectors). > **Note: Polling only: several capabilities are not ingested** Meeting transcripts, file/attachment contents, Graph change notifications (webhooks), and delta queries are **not ingested**: messages are collected by polling only. See [What is not ingested](#what-is-not-ingested): it also determines which Graph permissions you need. ## 1. Prepare credentials in Microsoft Entra (Azure AD) Azure portal → App registrations → New registration. Add Microsoft Graph **application** permissions: | Permission | Why | |---|---| | `ChannelMessage.Read.All` | Read channel messages and threaded replies | | `Chat.Read.All` | Read 1:1 and group chat messages (only if `TEAMS_INCLUDE_CHATS=1`) | | `User.Read.All` | Resolve message authors to names/emails | | `TeamMember.Read.All` | Resolve channel membership for visibility mapping | Have an admin grant tenant-wide consent, then create a client secret and copy it. > **Note: Grant only these four permissions** Earlier revisions listed `OnlineMeetingTranscript.Read.All`: the connector never calls the transcript API, so that consent is not required and should not be requested. ## 2. Configure (managed dashboard) Settings → Connectors → Add Connector → Microsoft Teams. Paste the tenant ID, client ID, and client secret; pick the teams to sync; set the scope template (default `org:/source:teams/team:{team_id}/project:{channel_id}`); Start sync. ## What gets written Every episode's content is the message body, with HTML stripped to plain text. | Event | Episode type | Notes | |---|---|---| | Channel message | `message` | Author resolved to display name + `userPrincipalName` | | Reply in thread | `message` | `parent_id` and `thread_id` link it to the parent message | | 1:1 / group chat message | `message` | Only when `TEAMS_INCLUDE_CHATS=1` | | Message in a meeting chat | `meeting` | The chat message, not a transcript | | Message with an attachment | `document` | Tagged `file_share` with `metadata.attachment_count`; the file is not fetched | `@`-mentions are recorded in `metadata.mentions`; high-importance messages are tagged `high_importance`. The **`idempotency_key` is the stable external id**: ```text teams:channel::: teams:chat:: ``` > **Note: The key itself is not version-aware** The key is stable rather than content-versioned. The wire key also hashes the content, so an edited message that the poller returns again lands as a new event. The connector also sets `--source-instance-id` automatically to the Azure directory (tenant) id, so two Microsoft 365 tenants synced into one scope keep distinct source identities without any extra flag; an explicit `CORTEXDB_SOURCE_INSTANCE_ID` still overrides it. > **Note: The key on the wire is derived** The key format above is this connector's internal record identity: it decides which source record an event belongs to. The `idempotency_key` actually sent to CortexDB is a derived `cxsrc:<56 hex>` value that also hashes the content, labels, observed time and actor, so an unchanged redelivery converges on the same event while any edit lands as a new one, even where the key format itself is not content-versioned. Every event also carries a `source` descriptor with the record's fingerprint. See [Source identity and keys](https://cortexdb.ai/docs/connectors#source-identity-and-keys). ## Visibility | Source | Visibility | |---|---| | Standard (public) channel | `organization` | | Private channel | `restricted` | | 1:1 / group chat | `private`, with the chat's member ids as the allow-list | ## What is not ingested What the connector does not ingest, whatever the configuration: | Capability | Status | |---|---| | Meeting transcripts | Not implemented (meeting-chat messages are captured; the transcript is not) | | File / attachment contents | Not implemented (typed `document` and counted, but no bytes uploaded) | | Graph change notifications (webhooks) | Not implemented (no Teams webhook receiver) | | Delta queries | Not implemented (uses the `lastModifiedDateTime` filter with `@odata.nextLink` paging) | For attachment contents today, the [Jira](https://cortexdb.ai/docs/connectors/jira), [Slack](https://cortexdb.ai/docs/connectors/slack), and [Freshdesk](https://cortexdb.ai/docs/connectors/freshdesk) connectors ingest attachments through the blob pipeline. ## Run it yourself ```bash pip install 'cortexdb-connectors[teams]' pip install cortexdb-cli && cortexdb init export TEAMS_TENANT_ID=... # required export TEAMS_CLIENT_ID=... # required export TEAMS_CLIENT_SECRET=... # required export TEAMS_TEAM_IDS=team-a,team-b # required for channel ingestion export TEAMS_INCLUDE_CHATS=0 # 1 to also sync 1:1 / group chats cortexdb-sync --api-url http://localhost:3141 sync teams cortexdb-sync --api-url http://localhost:3141 watch teams --interval 60 ``` The connector honours `Retry-After` on Graph `429`s (up to 5 retries), refreshes its token on a mid-sync `401`, and paces requests at 1 req/sec. The first run backfills `backfill_days` (default 30). ## See also - [Connectors overview](https://cortexdb.ai/docs/connectors) · [Slack](https://cortexdb.ai/docs/connectors/slack) - [POST /v1/experience](https://cortexdb.ai/docs/api-reference/experience) ========================================================================================== # Google Workspace Connector _Ingest Gmail, Drive, and Calendar activity into CortexDB._ Source: https://cortexdb.ai/docs/connectors/google-workspace Tails Gmail messages, Drive documents and comments, and Calendar events, and writes them to CortexDB as experiences. > **Note: Two ways to run this connector** **Run it yourself**: `pip install 'cortexdb-connectors[google-workspace]'` then `cortexdb-sync sync google-workspace`. **Managed**: CortexDB runs the connector as a worker. See the [Connectors overview](https://cortexdb.ai/docs/connectors). ## 1. Prepare credentials Create a **service account** in Google Cloud, enable domain-wide delegation, and grant it the Gmail / Drive / Calendar read scopes in the Workspace admin console. Download the service-account key JSON, and choose a user to impersonate (delegated access). ## What gets written Gmail threads, Drive docs + comments, and Calendar events each become a `POST /v1/experience` on the resolved scope (default `org:/source:google-workspace`), with entity references and metadata (`source_url`, thread / document / event ids). > **Note: Record keys and threads** - The internal **`idempotency_key`** is the record id, not version-aware: `gmail:`, `drive::`, `calendar::`. Edits still land as new events because the wire key hashes the content (see below). - Drive comments link to their document via a **`thread=…` label**, not `context.preceded_by`. > **Note: The key on the wire is derived** The key format above is this connector's internal record identity: it decides which source record an event belongs to. The `idempotency_key` actually sent to CortexDB is a derived `cxsrc:<56 hex>` value that also hashes the content, labels, observed time and actor, so an unchanged redelivery converges on the same event while any edit lands as a new one, even where the key format itself is not content-versioned. Every event also carries a `source` descriptor with the record's fingerprint. See [Source identity and keys](https://cortexdb.ai/docs/connectors#source-identity-and-keys). ## Run it yourself ```bash pip install 'cortexdb-connectors[google-workspace]' pip install cortexdb-cli && cortexdb init export GW_SERVICE_ACCOUNT_KEY=/path/to/service-account.json # required export GW_DELEGATED_USER=you@acme.com # required (impersonated user) cortexdb-sync --api-url http://localhost:3141 sync google-workspace cortexdb-sync --api-url http://localhost:3141 watch google-workspace --interval 300 ``` `GW_SERVICE_ACCOUNT_KEY` may be a path to the JSON key file (or its contents). Cursor state persists in `~/.cortexdb/sync_state.json`. ### Optional settings Set these as environment variables (or the matching keys in the `cortexdb-sync` YAML config). Lists are comma-separated. For on/off settings, `1`, `true`, `yes` or `on` turns the setting on and any other value turns it off. | Setting | What it does | Default | |---|---|---| | `GW_GMAIL` | Sync Gmail | On | | `GW_DRIVE` | Sync Drive | On | | `GW_CALENDAR` | Sync Calendar | On | | `GW_SHARED_DRIVES` | Shared drive IDs to include | None | | `GW_CALENDARS` | Calendar IDs to sync | `primary` | ## See also - [Connectors overview](https://cortexdb.ai/docs/connectors) · [Notion](https://cortexdb.ai/docs/connectors/notion) - [POST /v1/experience](https://cortexdb.ai/docs/api-reference/experience) ========================================================================================== # Salesforce Connector _Ingest Salesforce records and Chatter into CortexDB._ Source: https://cortexdb.ai/docs/connectors/salesforce Tails Salesforce objects (accounts, opportunities, cases, …) and Chatter feed activity, and writes them to CortexDB as experiences. > **Note: Two ways to run this connector** **Run it yourself**: `pip install 'cortexdb-connectors[salesforce]'` then `cortexdb-sync sync salesforce`. **Managed**: CortexDB runs the connector as a worker. See the [Connectors overview](https://cortexdb.ai/docs/connectors). ## 1. Prepare credentials > **Note: Self-host and dashboard use different auth** The **managed dashboard** uses an OAuth **refresh token**. The **self-hosted** connector uses the **username-password OAuth flow**: a Connected App's consumer key/secret plus a Salesforce username and password (append the security token to the password if required). Both are listed below. Create a Connected App with the API scope enabled, and note the consumer key and secret. ## What gets written Each record and Chatter post becomes a `POST /v1/experience` on the resolved scope (default `org:/source:salesforce`), with an entity reference to the record and metadata (object type, id, a `source_url`). > **Note: Record keys and threads** - The internal **`idempotency_key`** uses the **`sf:`** prefix: `sf::` (not `sfdc:`, and no `system_modstamp` segment; edits are versioned by the derived wire key, see below). - Chatter replies link to their parent via a **`thread=…` label**, not `context.preceded_by`. > **Note: The key on the wire is derived** The key format above is this connector's internal record identity: it decides which source record an event belongs to. The `idempotency_key` actually sent to CortexDB is a derived `cxsrc:<56 hex>` value that also hashes the content, labels, observed time and actor, so an unchanged redelivery converges on the same event while any edit lands as a new one, even where the key format itself is not content-versioned. Every event also carries a `source` descriptor with the record's fingerprint. See [Source identity and keys](https://cortexdb.ai/docs/connectors#source-identity-and-keys). ## Run it yourself ```bash pip install 'cortexdb-connectors[salesforce]' pip install cortexdb-cli && cortexdb init export SF_INSTANCE_URL=https://acme.my.salesforce.com # required export SF_CLIENT_ID=... # required (Connected App consumer key) export SF_CLIENT_SECRET=... # required (consumer secret) export SF_USERNAME=you@acme.com # required export SF_PASSWORD=... # required (+ security token if needed) cortexdb-sync --api-url http://localhost:3141 sync salesforce cortexdb-sync --api-url http://localhost:3141 watch salesforce --interval 300 ``` ### Optional settings Set these as environment variables (or the matching keys in the `cortexdb-sync` YAML config). Lists are comma-separated. For on/off settings, `1`, `true`, `yes` or `on` turns the setting on and any other value turns it off. | Setting | What it does | Default | |---|---|---| | `SF_OBJECTS` | Object types to sync | `Case`, `Opportunity`, `Account`, `Task`, `FeedItem`, `Note` | ## See also - [Connectors overview](https://cortexdb.ai/docs/connectors) · [HubSpot](https://cortexdb.ai/docs/connectors/hubspot) · [ServiceNow](https://cortexdb.ai/docs/connectors/servicenow) - [POST /v1/experience](https://cortexdb.ai/docs/api-reference/experience) ========================================================================================== # HubSpot Connector _Ingest HubSpot CRM objects and engagements into CortexDB._ Source: https://cortexdb.ai/docs/connectors/hubspot Tails HubSpot CRM objects (contacts, companies, deals) and engagements (notes, emails, calls) and writes them to CortexDB as experiences. > **Note: Two ways to run this connector** **Run it yourself**: `pip install 'cortexdb-connectors[hubspot]'` then `cortexdb-sync sync hubspot`. **Managed**: CortexDB runs the connector as a worker. See the [Connectors overview](https://cortexdb.ai/docs/connectors). ## 1. Prepare credentials Create a **private app** in HubSpot (Settings → Integrations → Private Apps) with CRM read scopes, and copy its access token. ## What gets written Each object and engagement becomes a `POST /v1/experience` on the resolved scope (default `org:/source:hubspot`), with an entity reference to the record and metadata (object type, id, a `source_url`). > **Note: Idempotency key** The **`idempotency_key`** uses the `hs:` prefix (`hs:{object}:{id}`). This connector does **not** use `context.preceded_by`. > **Note: The key on the wire is derived** The key format above is this connector's internal record identity: it decides which source record an event belongs to. The `idempotency_key` actually sent to CortexDB is a derived `cxsrc:<56 hex>` value that also hashes the content, labels, observed time and actor, so an unchanged redelivery converges on the same event while any edit lands as a new one, even where the key format itself is not content-versioned. Every event also carries a `source` descriptor with the record's fingerprint. See [Source identity and keys](https://cortexdb.ai/docs/connectors#source-identity-and-keys). ## Run it yourself ```bash pip install 'cortexdb-connectors[hubspot]' pip install cortexdb-cli && cortexdb init export HUBSPOT_TOKEN=pat-... # required (private-app access token) cortexdb-sync --api-url http://localhost:3141 sync hubspot cortexdb-sync --api-url http://localhost:3141 watch hubspot --interval 300 ``` ### Optional settings Set these as environment variables (or the matching keys in the `cortexdb-sync` YAML config). Lists are comma-separated. For on/off settings, `1`, `true`, `yes` or `on` turns the setting on and any other value turns it off. | Setting | What it does | Default | |---|---|---| | `HUBSPOT_OBJECTS` | Object types to sync | `contacts`, `companies`, `deals`, `tickets`, `notes`, `emails`, `calls`, `tasks` | ## See also - [Connectors overview](https://cortexdb.ai/docs/connectors) · [Salesforce](https://cortexdb.ai/docs/connectors/salesforce) - [POST /v1/experience](https://cortexdb.ai/docs/api-reference/experience) ========================================================================================== # Zendesk Connector _Ingest Zendesk tickets, comments, and help-center articles into CortexDB._ Source: https://cortexdb.ai/docs/connectors/zendesk Tails Zendesk tickets (and their comments) and Help Center articles, and writes them to CortexDB as experiences. > **Note: Two ways to run this connector** **Run it yourself**: `pip install 'cortexdb-connectors[zendesk]'` then `cortexdb-sync sync zendesk`. **Managed**: CortexDB runs the connector as a worker. See the [Connectors overview](https://cortexdb.ai/docs/connectors). ## 1. Prepare credentials Zendesk → Admin Center → Apps and integrations → Zendesk API → enable token access and create an API token. The connector authenticates as HTTP Basic (`email/token:`). You also need your Zendesk subdomain (e.g. `acme` for `acme.zendesk.com`). ## What gets written Each ticket, ticket comment (as a `conversation`), and Help Center article (as a `document`) becomes a `POST /v1/experience` on the resolved scope (default `org:/source:zendesk`), with an entity reference and metadata (`status`, `priority`, a `source_url`). > **Note: Idempotency key** The internal **`idempotency_key`** is `zd:ticket:` for tickets and the raw `article:` for Help Center articles (`zd:article:` is the article's thread id). This connector does **not** use `context.preceded_by`. > **Note: The key on the wire is derived** The key format above is this connector's internal record identity: it decides which source record an event belongs to. The `idempotency_key` actually sent to CortexDB is a derived `cxsrc:<56 hex>` value that also hashes the content, labels, observed time and actor, so an unchanged redelivery converges on the same event while any edit lands as a new one, even where the key format itself is not content-versioned. Every event also carries a `source` descriptor with the record's fingerprint. See [Source identity and keys](https://cortexdb.ai/docs/connectors#source-identity-and-keys). ## Run it yourself ```bash pip install 'cortexdb-connectors[zendesk]' pip install cortexdb-cli && cortexdb init export ZENDESK_SUBDOMAIN=acme # required export ZENDESK_EMAIL=you@acme.com # required export ZENDESK_TOKEN=... # required (API token) cortexdb-sync --api-url http://localhost:3141 sync zendesk cortexdb-sync --api-url http://localhost:3141 watch zendesk --interval 300 ``` ### Optional settings Set these as environment variables (or the matching keys in the `cortexdb-sync` YAML config). Lists are comma-separated. For on/off settings, `1`, `true`, `yes` or `on` turns the setting on and any other value turns it off. | Setting | What it does | Default | |---|---|---| | `ZENDESK_HELP_CENTER` | Also sync Help Center articles | Off | ## See also - [Connectors overview](https://cortexdb.ai/docs/connectors) · [Freshdesk](https://cortexdb.ai/docs/connectors/freshdesk) · [Intercom](https://cortexdb.ai/docs/connectors/intercom) - [POST /v1/experience](https://cortexdb.ai/docs/api-reference/experience) ========================================================================================== # Intercom Connector _Ingest Intercom conversations into CortexDB._ Source: https://cortexdb.ai/docs/connectors/intercom Tails Intercom conversations (and their parts) and writes them to CortexDB as conversation experiences. > **Note: Two ways to run this connector** **Run it yourself**: `pip install 'cortexdb-connectors[intercom]'` then `cortexdb-sync sync intercom`. **Managed**: CortexDB runs the connector as a worker. See the [Connectors overview](https://cortexdb.ai/docs/connectors). ## 1. Prepare credentials Intercom → Settings → Developers → create an app (or use your workspace access token) and copy the access token. ## What gets written Each conversation and conversation part becomes a `POST /v1/experience` on the resolved scope (default `org:/source:intercom`), author resolved (contact or admin), body as `content`, with an entity reference to the conversation. > **Note: Idempotency key** The **`idempotency_key`** uses the **`ic:`** prefix (`ic:conv:`, not `intercom:…`). This connector does **not** use `context.preceded_by`. > **Note: The key on the wire is derived** The key format above is this connector's internal record identity: it decides which source record an event belongs to. The `idempotency_key` actually sent to CortexDB is a derived `cxsrc:<56 hex>` value that also hashes the content, labels, observed time and actor, so an unchanged redelivery converges on the same event while any edit lands as a new one, even where the key format itself is not content-versioned. Every event also carries a `source` descriptor with the record's fingerprint. See [Source identity and keys](https://cortexdb.ai/docs/connectors#source-identity-and-keys). ## Run it yourself ```bash pip install 'cortexdb-connectors[intercom]' pip install cortexdb-cli && cortexdb init export INTERCOM_TOKEN=... # required (access token) cortexdb-sync --api-url http://localhost:3141 sync intercom cortexdb-sync --api-url http://localhost:3141 watch intercom --interval 300 ``` ### Optional settings Set these as environment variables (or the matching keys in the `cortexdb-sync` YAML config). Lists are comma-separated. For on/off settings, `1`, `true`, `yes` or `on` turns the setting on and any other value turns it off. | Setting | What it does | Default | |---|---|---| | `INTERCOM_ARTICLES` | Also sync Help Center articles | Off | ## See also - [Connectors overview](https://cortexdb.ai/docs/connectors) · [Zendesk](https://cortexdb.ai/docs/connectors/zendesk) · [Freshdesk](https://cortexdb.ai/docs/connectors/freshdesk) - [POST /v1/experience](https://cortexdb.ai/docs/api-reference/experience) ========================================================================================== # ServiceNow Connector _Ingest ServiceNow incidents, problems, and their work notes into CortexDB._ Source: https://cortexdb.ai/docs/connectors/servicenow Tails ServiceNow records (incidents, problems, changes) and their comments / work notes, and writes them to CortexDB as experiences. > **Note: Two ways to run this connector** **Run it yourself**: `pip install 'cortexdb-connectors[servicenow]'` then `cortexdb-sync sync servicenow`. **Managed**: CortexDB runs the connector as a worker. See the [Connectors overview](https://cortexdb.ai/docs/connectors). ## 1. Prepare credentials > **Note: Self-host and dashboard use different auth** The **managed dashboard** uses OAuth (client id/secret). The **self-hosted** connector uses **basic auth**: a ServiceNow instance name plus a username and password (a dedicated integration user with read access to the tables you want is recommended). ## What gets written Each record and work note becomes a `POST /v1/experience` on the resolved scope (default `org:/source:servicenow`), with an entity reference to the record and metadata (table, `sys_id`, `state`, a `source_url`). > **Note: Record keys and threads** - The **`idempotency_key`** is `snow:{table}:{sys_id}`. - A problem's linked incidents are carried via a **`thread=…` label**, not `context.preceded_by`. > **Note: The key on the wire is derived** The key format above is this connector's internal record identity: it decides which source record an event belongs to. The `idempotency_key` actually sent to CortexDB is a derived `cxsrc:<56 hex>` value that also hashes the content, labels, observed time and actor, so an unchanged redelivery converges on the same event while any edit lands as a new one, even where the key format itself is not content-versioned. Every event also carries a `source` descriptor with the record's fingerprint. See [Source identity and keys](https://cortexdb.ai/docs/connectors#source-identity-and-keys). ## Run it yourself ```bash pip install 'cortexdb-connectors[servicenow]' pip install cortexdb-cli && cortexdb init export SNOW_INSTANCE=acme # required (e.g. acme for acme.service-now.com) export SNOW_USERNAME=integration.user # required export SNOW_PASSWORD=... # required cortexdb-sync --api-url http://localhost:3141 sync servicenow cortexdb-sync --api-url http://localhost:3141 watch servicenow --interval 300 ``` ### Optional settings Set these as environment variables (or the matching keys in the `cortexdb-sync` YAML config). Lists are comma-separated. For on/off settings, `1`, `true`, `yes` or `on` turns the setting on and any other value turns it off. | Setting | What it does | Default | |---|---|---| | `SNOW_TABLES` | Tables to sync | `incident`, `change_request`, `problem`, `kb_knowledge`, `sc_task` | ## See also - [Connectors overview](https://cortexdb.ai/docs/connectors) · [Salesforce](https://cortexdb.ai/docs/connectors/salesforce) · [PagerDuty](https://cortexdb.ai/docs/connectors/pagerduty) - [POST /v1/experience](https://cortexdb.ai/docs/api-reference/experience) ========================================================================================== # Integrations _37 framework integrations and 18 data connectors._ Source: https://cortexdb.ai/docs/integrations CortexDB ships **37 framework integrations** and **18 data connectors**. Each integration is a small adapter that makes CortexDB the memory, the retriever or the tool set inside the framework you already use. Every recipe works the same against [CortexDB Cloud](https://cortexdb.ai/docs/cloud) (`https://api-v1.cortexdb.ai`) or a [self-hosted](https://cortexdb.ai/docs/self-hosting/quickstart) server (`http://localhost:3141`); just change the base URL. Data connectors ingest from third-party systems on a schedule, run with the `cortexdb-sync` CLI you run yourself or as a managed worker. | Kind | Count | Integrations | |---|---|---| | Agent frameworks | 17 | AG2, AutoGen, Agno, BeeAI (IBM), CAMEL-AI, ControlFlow, CrewAI, Eliza OS (npm), Google ADK, Hermes Agent, LangGraph, Letta, Mastra (npm), OpenAI Agents SDK, OpenClaw (npm), PydanticAI, Smolagents (Hugging Face) | | LLM app and RAG frameworks | 5 | LangChain, LlamaIndex, DSPy, Instructor, Vercel AI SDK (npm) | | Safety | 1 | NeMo Guardrails (NVIDIA) | | Workflow and orchestration | 3 | Temporal, Prefect (PyPI), Apache Airflow | | No-code and low-code | 5 | n8n (npm), Zapier (npm), Make (an app you import), Flowise, Dify | | Model backends | 6 | Ollama, vLLM, Groq, Together AI, Fireworks AI, DeepInfra | | Data connectors | **18** | Run with the `cortexdb-sync` CLI, or as managed sync workers ([Connectors](https://cortexdb.ai/docs/connectors)) | Most integrations ship inside the Python SDK: `pip install "cortexdbai[langchain]"`. Those marked npm or PyPI are their own packages, and Make is an app you import; they follow their own release schedule. Model-backend pages set which models CortexDB uses for answers and synthesis, and so far are tested with stand-in models. These are adapters, not partnerships or certifications. Give each integration its own memory space: clearing an integration's memory clears its whole space. ## AI assistants Claude, ChatGPT, Cursor, Windsurf, VS Code Copilot and other assistants connect over the Model Context Protocol: the local [`cortexdb-mcp`](https://cortexdb.ai/docs/sdks/mcp-server) package for tools that start a local server, or the server's own remote MCP endpoint (`/mcp`, OAuth sign-in) for connector apps that reach a server by URL. [Connecting AI Assistants](https://cortexdb.ai/docs/connect-assistants) shows which to use for each assistant. ## Agent frameworks 22 frameworks. Every page is a self-contained recipe: a memory adapter, a retriever class, or a tool wrapper that talks to CortexDB via `V1Client`. Install the matching extra, e.g. `pip install cortexdbai[langchain]`. LangChain · LangGraph · LlamaIndex · CrewAI · AG2 (AutoGen) · AutoGen · Agno · DSPy · Smolagents · CAMEL-AI · PydanticAI · OpenAI Agents · Google ADK · Letta · BeeAI · NeMo Guardrails · Instructor · ControlFlow · Eliza OS · Hermes · OpenClaw · Mastra ## Orchestration Temporal · n8n · Prefect · Airflow · Zapier · Make.com ## No-code platforms Vercel AI SDK · Flowise · Dify ## Inference backends Server-side deployment guides: they configure which model CortexDB's `/v1/answer` route and Understanding synthesizer call. Use these if you self-host or run an enterprise deployment. Ollama · Groq · Together AI · Fireworks AI · vLLM · DeepInfra > **Note:** These pages configure the **answer lane** (`CORTEX_ANSWER_*`), not just `CORTEX_LLM_*` (which is entity extraction). Setting `CORTEX_LLM_*` alone leaves `/v1/answer` disabled (`503 ANSWER_UNAVAILABLE`) on a self-hosted server. See each page. ## Data connectors 18 third-party systems. A connector can run as a **managed** sync worker (provisioned from your account dashboard) or **self-hosted** with the `cortexdb-sync` CLI: point it at your Slack workspace / GitHub org / Jira project once and it continuously ingests into your scope as conversation / document experiences. | System | Doc | |---|---| | Slack | `/docs/connectors/slack` | | GitHub | `/docs/connectors/github` | | GitLab | `/docs/connectors/gitlab` | | Jira | `/docs/connectors/jira` | | Freshdesk | `/docs/connectors/freshdesk` | | tl;dv | `/docs/connectors/tldv` | | Linear | `/docs/connectors/linear` | | Confluence | `/docs/connectors/confluence` | | Notion | `/docs/connectors/notion` | | PagerDuty | `/docs/connectors/pagerduty` | | Discord | `/docs/connectors/discord` | | Microsoft Teams | `/docs/connectors/teams` | | Google Workspace | `/docs/connectors/google-workspace` | | Salesforce | `/docs/connectors/salesforce` | | HubSpot | `/docs/connectors/hubspot` | | Zendesk | `/docs/connectors/zendesk` | | Intercom | `/docs/connectors/intercom` | | ServiceNow | `/docs/connectors/servicenow` | > **Note:** Self-hosting connectors yourself? See the [Self-hosted connectors overview](https://cortexdb.ai/docs/connectors) for the `cortexdb-sync` CLI, credential precedence, `--scope-template`, and the `serve` webhook receiver. ## Not in this list? The Python, TypeScript, and REST interfaces work everywhere `fetch` does. If you have a framework, orchestrator, or pipeline that isn't listed, the SDK/REST path works, and for a new managed connector, contact the team. ========================================================================================== # AG2 (AutoGen) _Wrap an AG2 conversable agent with CortexDB long-term memory._ Source: https://cortexdb.ai/docs/integrations/ag2 AG2 (the community fork of AutoGen) gets persistent memory through a CortexDB-backed agent wrapper. ## Install ```bash pip install cortexdbai[ag2] ``` ## Memory-backed agent ```python from cortexdb import Cortex from cortexdb.integrations.ag2 import CortexDBAgent client = Cortex(api_url="https://api-v1.cortexdb.ai", actor="agent:assistant", bearer=os.environ["CORTEXDB_TOKEN"]) agent = CortexDBAgent( name="assistant", cortex_client=client, scope="org:acme/agent:assistant", llm_config={"model": "gpt-4o"}, ) ``` The wrapper recalls context before each reply and captures the turn afterward: your `llm_config` model is independent of the model CortexDB uses internally for `/v1/answer`. ## See also - [AutoGen](https://cortexdb.ai/docs/integrations/autogen) · [CrewAI](https://cortexdb.ai/docs/integrations/crewai) · [Python SDK](https://cortexdb.ai/docs/sdks/python) ========================================================================================== # AutoGen _Wrap a Microsoft AutoGen agent with CortexDB long-term memory._ Source: https://cortexdb.ai/docs/integrations/autogen AutoGen-style agents get persistent, cross-session memory through a CortexDB-backed wrapper. Note that `cortexdbai[autogen]` installs **AG2** (the community fork that keeps the `autogen` import name), and the wrapper is the same code as the [AG2](https://cortexdb.ai/docs/integrations/ag2) page; Microsoft AutoGen 0.4+ (`autogen-agentchat`) is not covered. ## Install ```bash pip install cortexdbai[autogen] ``` ## Memory-backed agent ```python from cortexdb import Cortex from cortexdb.integrations.autogen import CortexDBAgent client = Cortex(api_url="https://api-v1.cortexdb.ai", actor="agent:assistant", bearer=os.environ["CORTEXDB_TOKEN"]) agent = CortexDBAgent( name="assistant", cortex_client=client, scope="org:acme/agent:assistant", llm_config={"model": "gpt-4o"}, ) ``` The wrapper recalls before replying and captures the turn afterward. For the community fork, see [AG2](https://cortexdb.ai/docs/integrations/ag2). ## See also - [AG2](https://cortexdb.ai/docs/integrations/ag2) · [Python SDK](https://cortexdb.ai/docs/sdks/python) · [POST /v1/recall](https://cortexdb.ai/docs/api-reference/recall) ========================================================================================== # Agno _Give Agno agents CortexDB-backed memory and tools._ Source: https://cortexdb.ai/docs/integrations/agno CortexDB provides Agno agents with a persistent memory and a tool kit for search/store/forget. ## Install ```bash pip install cortexdbai[agno] ``` ## Memory + tools ```python from cortexdb import Cortex from cortexdb.integrations.agno import CortexDBMemory, CortexDBTools client = Cortex(api_url="https://api-v1.cortexdb.ai", actor="user:alice", bearer=os.environ["CORTEXDB_TOKEN"]) scope = "org:acme/user:alice" agent = Agent( model=..., memory=CortexDBMemory(client=client, scope=scope), tools=[CortexDBTools(client=client, scope=scope)], ) ``` ## See also - [Python SDK](https://cortexdb.ai/docs/sdks/python) · [Experience Envelope](https://cortexdb.ai/docs/concepts/experience-envelope) ========================================================================================== # BeeAI _Give BeeAI agents CortexDB memory and tools._ Source: https://cortexdb.ai/docs/integrations/beeai CortexDB provides BeeAI agents a persistent memory plus search/store/forget tools. ## Install ```bash pip install cortexdbai[beeai] ``` ## Memory + tools ```python from cortexdb import Cortex from cortexdb.integrations.beeai import ( CortexDBMemory, CortexDBSearchTool, CortexDBStoreTool, CortexDBForgetTool, ) client = Cortex(api_url="https://api-v1.cortexdb.ai", actor="agent:bee", bearer=os.environ["CORTEXDB_TOKEN"]) scope = "org:acme/agent:bee" memory = CortexDBMemory(client=client, scope=scope) tools = [CortexDBSearchTool(client=client, scope=scope), CortexDBStoreTool(client=client, scope=scope)] ``` ## See also - [Python SDK](https://cortexdb.ai/docs/sdks/python) · [POST /v1/recall](https://cortexdb.ai/docs/api-reference/recall) ========================================================================================== # CAMEL-AI _Back CAMEL-AI agents with CortexDB long-term memory._ Source: https://cortexdb.ai/docs/integrations/camel CortexDB provides CAMEL-AI agents a persistent `AgentMemory`-compatible memory backend. ## Install ```bash pip install cortexdbai[camel] ``` ## Memory ```python from cortexdb import Cortex from cortexdb.integrations.camel import CortexDBMemory client = Cortex(api_url="https://api-v1.cortexdb.ai", actor="user:alice", bearer=os.environ["CORTEXDB_TOKEN"]) memory = CortexDBMemory(client=client, scope="org:acme/user:alice") # pass memory= into a ChatAgent ``` ## See also - [Python SDK](https://cortexdb.ai/docs/sdks/python) · [Experience Envelope](https://cortexdb.ai/docs/concepts/experience-envelope) ========================================================================================== # ControlFlow _Give ControlFlow tasks and agents CortexDB-backed memory._ Source: https://cortexdb.ai/docs/integrations/controlflow CortexDB provides ControlFlow a persistent memory and a task store for durable agent context. ## Install ```bash pip install cortexdbai[controlflow] ``` ## Memory + task store ```python from cortexdb import Cortex from cortexdb.integrations.controlflow import CortexDBMemory, CortexDBTaskStore client = Cortex(api_url="https://api-v1.cortexdb.ai", actor="agent:planner", bearer=os.environ["CORTEXDB_TOKEN"]) scope = "org:acme/agent:planner" memory = CortexDBMemory(client=client, scope=scope) task_store = CortexDBTaskStore(client=client, scope=scope) ``` ## See also - [Python SDK](https://cortexdb.ai/docs/sdks/python) · [Prefect](https://cortexdb.ai/docs/integrations/prefect) · [POST /v1/recall](https://cortexdb.ai/docs/api-reference/recall) ========================================================================================== # CrewAI _Give CrewAI agents shared long-term memory and CortexDB-backed tools._ Source: https://cortexdb.ai/docs/integrations/crewai CortexDB gives a CrewAI crew a shared, persistent memory and search/store tools. ## Install ```bash pip install cortexdbai[crewai] ``` ## Crew memory + tools ```python from cortexdb import Cortex from cortexdb.integrations.crewai import CortexDBCrewMemory, CortexDBSearchTool, CortexDBStoreTool client = Cortex(api_url="https://api-v1.cortexdb.ai", actor="agent:researcher", bearer=os.environ["CORTEXDB_TOKEN"]) scope = "org:acme/agent:researcher" memory = CortexDBCrewMemory(client=client, scope=scope) tools = [CortexDBSearchTool(client=client, scope=scope), CortexDBStoreTool(client=client, scope=scope)] crew = Crew(agents=[...], tasks=[...], memory=memory) ``` > **Note: modality= when capturing manually** If you capture with the SDK directly, use `text=` / `role=`; `modality` defaults to `conversation`. `experience(modality="tool_result")` sets an open-set label. See the [Python SDK](https://cortexdb.ai/docs/sdks/python#write-path). ## See also - [AutoGen](https://cortexdb.ai/docs/integrations/autogen) · [Python SDK](https://cortexdb.ai/docs/sdks/python) · [Experience Envelope](https://cortexdb.ai/docs/concepts/experience-envelope) ========================================================================================== # Eliza OS _Give Eliza OS agents long-term memory via the CortexDB TypeScript SDK._ Source: https://cortexdb.ai/docs/integrations/eliza Eliza OS is a TypeScript agent framework. There is no dedicated adapter: wire CortexDB in through the [TypeScript SDK](https://cortexdb.ai/docs/sdks/typescript) inside a provider or action. ## Install ```bash npm install cortexdbai ``` ## Recall in a provider ```ts import { V1Client } from "cortexdbai/v1"; const client = new V1Client({ apiUrl: "https://api-v1.cortexdb.ai", actor: "agent:eliza", bearer: process.env.CORTEXDB_TOKEN!, }); const scope = "org:acme/agent:eliza"; // In a provider: pull long-term context before the model runs const pack = await client.recall(scope, { view: "holistic", query: message.content.text, diagnostics: "none" }); const context = pack.context_block ?? ""; // In an action / evaluator: capture the turn await client.experience(scope, { text: message.content.text, role: "user", observedAt: new Date().toISOString(), idempotencyKey: `eliza-${message.id}`, }); ``` ## See also - [TypeScript SDK](https://cortexdb.ai/docs/sdks/typescript) · [Mastra](https://cortexdb.ai/docs/integrations/mastra) · [Vercel AI SDK](https://cortexdb.ai/docs/integrations/vercel-ai) ========================================================================================== # Google ADK _Add CortexDB memory tools to Google's Agent Development Kit._ Source: https://cortexdb.ai/docs/integrations/google-adk CortexDB exposes memory to Google's Agent Development Kit (ADK) as function tools. ## Install ```bash pip install cortexdbai[google-adk] ``` ## Tools ```python from cortexdb import Cortex from cortexdb.integrations.google_adk import ( cortexdb_store_tool, cortexdb_search_tool, cortexdb_forget_tool, get_cortexdb_tools, ) client = Cortex(api_url="https://api-v1.cortexdb.ai", actor="agent:assistant", bearer=os.environ["CORTEXDB_TOKEN"]) scope = "org:acme/agent:assistant" tools = get_cortexdb_tools(client=client, scope=scope) agent = LlmAgent(name="assistant", model="gemini-2.0-flash", tools=tools) ``` ## See also - [Python SDK](https://cortexdb.ai/docs/sdks/python) · [OpenAI Agents SDK](https://cortexdb.ai/docs/integrations/openai-agents) · [POST /v1/recall](https://cortexdb.ai/docs/api-reference/recall) ========================================================================================== # Hermes _Back Hermes agents with a CortexDB memory provider._ Source: https://cortexdb.ai/docs/integrations/hermes CortexDB implements a memory provider for the Hermes agent framework. ## Install ```bash pip install cortexdbai[hermes] ``` ## Memory provider ```python import os from cortexdb.integrations.hermes import CortexDBMemoryProvider # The provider builds its own client (it takes no client= argument) provider = CortexDBMemoryProvider(api_url="https://api-v1.cortexdb.ai", actor="agent:hermes", bearer=os.environ["CORTEXDB_TOKEN"], scope="org:acme/agent:hermes") # register the provider with your Hermes agent ``` ## See also - [Python SDK](https://cortexdb.ai/docs/sdks/python) · [POST /v1/recall](https://cortexdb.ai/docs/api-reference/recall) ========================================================================================== # LangGraph _Persist LangGraph agent state and long-term memory in CortexDB._ Source: https://cortexdb.ai/docs/integrations/langgraph CortexDB backs LangGraph both as a **checkpointer** (durable graph state) and as a recall source for long-term memory across runs. ## Install ```bash pip install cortexdbai[langgraph] ``` ## Checkpointer ```python from cortexdb import Cortex from cortexdb.integrations.langgraph import CortexDBCheckpointer client = Cortex(api_url="https://api-v1.cortexdb.ai", actor="user:alice", bearer=os.environ["CORTEXDB_TOKEN"]) checkpointer = CortexDBCheckpointer(client=client, scope="org:acme/user:alice") graph = builder.compile(checkpointer=checkpointer) ``` ## Recall inside a node Use the SDK directly in any node to pull long-term context: ```python def retrieve_node(state): pack = client.recall(scope="org:acme/user:alice", view="holistic", query=state["input"], include=["events", "facts", "episodes"], budgets={"max_tokens": 3000}, diagnostics="none") return {"context": pack.get("context_block", "")} ``` > **Note: context_block may be empty** On a fresh scope (or a content-only self-host where derived layers are empty) `context_block` can be empty: check for it before injecting. Use `wait="indexed"` on the capture in the same turn if you need read-after-write. See [Self-hosting defaults](https://cortexdb.ai/docs/self-hosting/defaults). ## See also - [LangChain](https://cortexdb.ai/docs/integrations/langchain) · [Python SDK](https://cortexdb.ai/docs/sdks/python) · [POST /v1/recall](https://cortexdb.ai/docs/api-reference/recall) ========================================================================================== # Letta _Use CortexDB as archival storage for Letta (MemGPT) agents._ Source: https://cortexdb.ai/docs/integrations/letta CortexDB backs Letta's archival memory and storage connector, giving agents durable, bi-temporal recall. ## Install ```bash pip install cortexdbai[letta] ``` ## Storage connector ```python from cortexdb import Cortex from cortexdb.integrations.letta import CortexDBStorageConnector, CortexDBArchivalStorage client = Cortex(api_url="https://api-v1.cortexdb.ai", actor="agent:memgpt", bearer=os.environ["CORTEXDB_TOKEN"]) scope = "org:acme/agent:memgpt" archival = CortexDBArchivalStorage(client=client, scope=scope) # wire archival storage into the Letta agent config ``` ## See also - [Python SDK](https://cortexdb.ai/docs/sdks/python) · [Core Concepts](https://cortexdb.ai/docs/concepts) · [POST /v1/recall](https://cortexdb.ai/docs/api-reference/recall) ========================================================================================== # Mastra _Give Mastra agents long-term memory via the CortexDB TypeScript SDK._ Source: https://cortexdb.ai/docs/integrations/mastra Mastra is a TypeScript agent framework. Wire CortexDB in through the [TypeScript SDK](https://cortexdb.ai/docs/sdks/typescript) as a tool or in an agent's memory hooks. ## Install ```bash npm install cortexdbai ``` ## As a tool ```ts import { V1Client } from "cortexdbai/v1"; import { createTool } from "@mastra/core"; import { z } from "zod"; const client = new V1Client({ apiUrl: "https://api-v1.cortexdb.ai", actor: "agent:mastra", bearer: process.env.CORTEXDB_TOKEN!, }); const scope = "org:acme/agent:mastra"; export const recallMemory = createTool({ id: "recall-memory", description: "Recall long-term memory from CortexDB", inputSchema: z.object({ query: z.string() }), execute: async ({ context }) => { const pack = await client.recall(scope, { view: "holistic", query: context.query, diagnostics: "none" }); return { context: pack.context_block ?? "" }; }, }); ``` ## See also - [TypeScript SDK](https://cortexdb.ai/docs/sdks/typescript) · [Eliza OS](https://cortexdb.ai/docs/integrations/eliza) · [Vercel AI SDK](https://cortexdb.ai/docs/integrations/vercel-ai) ========================================================================================== # OpenAI Agents SDK _Add CortexDB memory tools to the OpenAI Agents SDK._ Source: https://cortexdb.ai/docs/integrations/openai-agents CortexDB exposes memory to the OpenAI Agents SDK as function tools created from a client + scope. ## Install ```bash pip install cortexdbai[openai-agents] ``` ## Tools ```python from cortexdb import Cortex from cortexdb.integrations.openai_agents import ( create_cortexdb_search_tool, create_cortexdb_store_tool, create_cortexdb_forget_tool, get_cortexdb_tools, ) client = Cortex(api_url="https://api-v1.cortexdb.ai", actor="agent:assistant", bearer=os.environ["CORTEXDB_TOKEN"]) scope = "org:acme/agent:assistant" tools = get_cortexdb_tools(client=client, scope=scope) # search + store + forget # or build them individually: search = create_cortexdb_search_tool(client=client, scope=scope) agent = Agent(name="assistant", tools=tools) ``` ## See also - [Python SDK](https://cortexdb.ai/docs/sdks/python) · [Google ADK](https://cortexdb.ai/docs/integrations/google-adk) · [POST /v1/recall](https://cortexdb.ai/docs/api-reference/recall) ========================================================================================== # OpenClaw _Give OpenClaw agents long-term memory via the CortexDB SDK or REST API._ Source: https://cortexdb.ai/docs/integrations/openclaw OpenClaw has no dedicated adapter: integrate CortexDB through the [Python](https://cortexdb.ai/docs/sdks/python) / [TypeScript](https://cortexdb.ai/docs/sdks/typescript) SDKs or the [REST API](https://cortexdb.ai/docs/sdks/rest-api). The pattern is recall-before, capture-after around each agent turn. ## Install ```bash pip install cortexdbai # or: npm install cortexdbai ``` ## Recall + capture ```python from cortexdb.v1 import V1Client client = V1Client(api_url="https://api-v1.cortexdb.ai", actor="agent:claw", bearer=os.environ["CORTEXDB_TOKEN"]) scope = "org:acme/agent:claw" # Before the turn pack = client.recall(scope=scope, view="holistic", query=user_input, diagnostics="none") context = pack.get("context_block", "") # After the turn client.experience(scope=scope, text=user_input, role="user", observed_at=_now(), idempotency_key=_idem(user_input)) ``` ## See also - [Python SDK](https://cortexdb.ai/docs/sdks/python) · [REST API](https://cortexdb.ai/docs/sdks/rest-api) ========================================================================================== # PydanticAI _Inject CortexDB memory into PydanticAI agents via dependencies._ Source: https://cortexdb.ai/docs/integrations/pydanticai PydanticAI passes CortexDB into an agent through its typed dependencies (`deps`). ## Install ```bash pip install cortexdbai[pydanticai] ``` ## Dependencies ```python from cortexdb import Cortex from cortexdb.integrations.pydanticai import CortexDBDeps client = Cortex(api_url="https://api-v1.cortexdb.ai", actor="user:alice", bearer=os.environ["CORTEXDB_TOKEN"]) deps = CortexDBDeps(client=client, scope="org:acme/user:alice") agent = Agent("openai:gpt-4o", deps_type=CortexDBDeps) @agent.tool async def recall_memory(ctx, query: str) -> str: pack = ctx.deps.client.recall(scope=ctx.deps.scope, view="holistic", query=query, diagnostics="none") return pack.get("context_block", "") ``` ## See also - [Python SDK](https://cortexdb.ai/docs/sdks/python) · [POST /v1/recall](https://cortexdb.ai/docs/api-reference/recall) ========================================================================================== # Smolagents _Give Hugging Face smolagents CortexDB search, store, and forget tools._ Source: https://cortexdb.ai/docs/integrations/smolagents CortexDB exposes memory to smolagents as three tools the agent can call. ## Install ```bash pip install cortexdbai[smolagents] ``` ## Tools ```python from cortexdb import Cortex from cortexdb.integrations.smolagents import ( CortexDBSearchTool, CortexDBStoreTool, CortexDBForgetTool, ) client = Cortex(api_url="https://api-v1.cortexdb.ai", actor="agent:worker", bearer=os.environ["CORTEXDB_TOKEN"]) scope = "org:acme/agent:worker" tools = [ CortexDBSearchTool(client=client, scope=scope), CortexDBStoreTool(client=client, scope=scope), CortexDBForgetTool(client=client, scope=scope), ] agent = CodeAgent(tools=tools, model=...) ``` ## See also - [Python SDK](https://cortexdb.ai/docs/sdks/python) · [POST /v1/recall](https://cortexdb.ai/docs/api-reference/recall) · [POST /v1/forget](https://cortexdb.ai/docs/api-reference/forget) ========================================================================================== # LangChain _Use CortexDB as a long-term memory provider for LangChain agents._ Source: https://cortexdb.ai/docs/integrations/langchain CortexDB plugs into LangChain as a persistent, hybrid-retrieval memory layer. The pattern is the same as any custom LangChain memory: recall from CortexDB to build context, and capture experiences on each turn. ## Install ```bash pip install cortexdbai[langchain] ``` > **Note: Your LangChain model is independent of CortexDB's** The example uses `ChatOpenAI` (needs `OPENAI_API_KEY`). CortexDB is provider-agnostic: its own LLM calls (entity extraction and enrichment on the server's `CORTEX_LLM_*` / `CORTEX_ENRICHMENT_*` lanes, answers on `CORTEX_ANSWER_*`; see [LLM & Answer Generation](https://cortexdb.ai/docs/operations/llm-answer)) are configured on the server and are unrelated to your `llm=` choice. ## Retriever ```python import os from cortexdb import Cortex from cortexdb.integrations.langchain import CortexDBRetriever client = Cortex( api_url="https://api-v1.cortexdb.ai", actor="user:alice", bearer=os.environ["CORTEXDB_TOKEN"], ) retriever = CortexDBRetriever(client=client, scope="org:acme/user:alice") docs = retriever.invoke("What did we decide about caching?") ``` The adapter also exports `CortexDBChatMessageHistory(client=client, scope=...)` for chat memory and `CortexDBSearchTool` / `CortexDBStoreTool` / `CortexDBForgetTool` (each `(client=client, scope=...)`) as agent tools. ## Prefer manual control? ```python from typing import Any, Dict, List from langchain.memory.chat_memory import BaseChatMemory from cortexdb.v1 import V1Client class CortexMemory(BaseChatMemory): """LangChain memory backed by CortexDB v1.""" def __init__(self, client: V1Client, scope: str, **kwargs): super().__init__(**kwargs) self._client = client self._scope = scope @property def memory_variables(self) -> List[str]: return ["history"] def load_memory_variables(self, inputs: Dict[str, Any]) -> Dict[str, Any]: pack = self._client.recall( scope=self._scope, view="holistic", query=inputs.get("input", ""), include=["events", "beliefs", "facts", "episodes"], budgets={"max_tokens": 3000}, ) return {"history": pack.get("context_block", "")} def save_context(self, inputs: Dict[str, Any], outputs: Dict[str, str]) -> None: self._client.experience( scope=self._scope, text=inputs["input"], role="user", observed_at=_now(), idempotency_key=_idem("user", inputs["input"]), ) self._client.experience( scope=self._scope, text=outputs["output"], role="assistant", observed_at=_now(), idempotency_key=_idem("assistant", outputs["output"]), ) ``` `_now()` / `_idem()` are small helpers: `datetime.utcnow().isoformat() + "Z"` and an MD5 or `f"chat-{uuid4()}"` respectively. ## Retriever variant For `RetrievalQA`-style chains, expose CortexDB's recall as a `BaseRetriever`: ```python from langchain_core.retrievers import BaseRetriever from langchain_core.documents import Document class CortexRetriever(BaseRetriever): def __init__(self, client: V1Client, scope: str, k: int = 8): super().__init__() self._client, self._scope, self._k = client, scope, k def _get_relevant_documents(self, query: str) -> List[Document]: pack = self._client.recall( scope=self._scope, view="holistic", query=query, include=["facts", "episodes"], budgets={"max_tokens": 4000}, ) docs = [] for fact in pack["layers"].get("facts", []): docs.append(Document( page_content=f"{fact['subject']['id']} {fact['predicate']} {fact['object']['value']}", metadata={"layer": "fact", "id": fact["id"], "confidence": fact["confidence"]}, )) return docs[: self._k] ``` > **Note: Fact fields: id and subject.id** Live facts are `{ id, subject: { type, id }, object: { type, datatype, value }, … }`; there is **no `fact_id`** and `subject` has **no `name`**. Use `fact["id"]` and `fact["subject"]["id"]` (older snippets showed `fact["fact_id"]` / `fact["subject"]["name"]`, which raise `KeyError`). Facts require enrichment on a self-host: see [Self-hosting defaults](https://cortexdb.ai/docs/self-hosting/defaults). ## Tips - **Scope per user.** A common shape is `org:/user:` for end-user memory, or `org:/agent:` for agent-scoped memory. - Use `wait="indexed"` if you need read-after-write within the same chain invocation. - **Citations.** `pack["provenance"]["citations"]` maps each derived record id to the events it came from (empty until enrichment is on). For UI citation markers, use the `citations` list returned by `client.answer()`. ## See also - [Python SDK](https://cortexdb.ai/docs/sdks/python) · [Experience Envelope](https://cortexdb.ai/docs/concepts/experience-envelope) · [Bi-temporal queries](https://cortexdb.ai/docs/concepts/bi-temporal) ========================================================================================== # LlamaIndex _Use CortexDB as a retriever and chat memory buffer for LlamaIndex._ Source: https://cortexdb.ai/docs/integrations/llamaindex CortexDB plugs into LlamaIndex as a **retriever** and as a **chat memory buffer** backed by hybrid recall. ## Install ```bash pip install cortexdbai[llamaindex] ``` ## Retriever ```python from cortexdb import Cortex from cortexdb.integrations.llamaindex import CortexDBRetriever client = Cortex(api_url="https://api-v1.cortexdb.ai", actor="user:alice", bearer=os.environ["CORTEXDB_TOKEN"]) retriever = CortexDBRetriever(client=client, scope="org:acme/user:alice") nodes = retriever.retrieve("What did we decide about caching?") ``` ## Chat memory buffer ```python from cortexdb.integrations.llamaindex import CortexDBChatMemoryBuffer memory = CortexDBChatMemoryBuffer(client=client, scope="org:acme/user:alice") # pass memory= into a ChatEngine / AgentRunner ``` > **Note: Fact fields: id and subject.id** If you render facts yourself, live facts are `{ id, subject: { type, id }, object: { type, datatype, value } }`; use `fact["id"]` and `fact["subject"]["id"]` (there is no `fact_id` / `subject.name`). Facts need enrichment on a self-host: see [Self-hosting defaults](https://cortexdb.ai/docs/self-hosting/defaults). ## See also - [LangChain](https://cortexdb.ai/docs/integrations/langchain) · [Python SDK](https://cortexdb.ai/docs/sdks/python) · [POST /v1/recall](https://cortexdb.ai/docs/api-reference/recall) ========================================================================================== # DSPy _Use CortexDB as a retriever and memory for DSPy programs._ Source: https://cortexdb.ai/docs/integrations/dspy CortexDB backs DSPy programs as a retriever (`dspy.Retrieve`-style) and a persistent memory. ## Install ```bash pip install cortexdbai[dspy] ``` ## Retriever + memory ```python from cortexdb import Cortex from cortexdb.integrations.dspy import CortexDBRetriever, CortexDBMemory client = Cortex(api_url="https://api-v1.cortexdb.ai", actor="user:alice", bearer=os.environ["CORTEXDB_TOKEN"]) scope = "org:acme/user:alice" retriever = CortexDBRetriever(client=client, scope=scope, k=8) memory = CortexDBMemory(client=client, scope=scope) ``` > **Note: Fact fields: id and subject.id** If you render facts yourself, use `fact["id"]` and `fact["subject"]["id"]`; live facts are `{ id, subject: { type, id }, object: { type, datatype, value } }` (no `fact_id` / `subject.name`). Facts need enrichment on a self-host: see [Self-hosting defaults](https://cortexdb.ai/docs/self-hosting/defaults). ## See also - [LlamaIndex](https://cortexdb.ai/docs/integrations/llamaindex) · [Python SDK](https://cortexdb.ai/docs/sdks/python) · [POST /v1/recall](https://cortexdb.ai/docs/api-reference/recall) ========================================================================================== # Instructor _Use CortexDB as a semantic cache for Instructor structured extractions._ Source: https://cortexdb.ai/docs/integrations/instructor CortexDB serves as a semantic cache for Instructor: recall a prior structured extraction instead of re-calling the LLM when a similar input has been seen. ## Install ```bash pip install cortexdbai[instructor] ``` ## Cache ```python from cortexdb import Cortex from cortexdb.integrations.instructor import CortexDBCache client = Cortex(api_url="https://api-v1.cortexdb.ai", actor="service:extractor", bearer=os.environ["CORTEXDB_TOKEN"]) cache = CortexDBCache(client=client, scope="org:acme/service:extractor") # wrap your instructor-patched client's calls with the cache ``` ## See also - [Python SDK](https://cortexdb.ai/docs/sdks/python) · [POST /v1/recall](https://cortexdb.ai/docs/api-reference/recall) ========================================================================================== # Vercel AI SDK _Add CortexDB memory to Vercel AI SDK apps with the TypeScript client._ Source: https://cortexdb.ai/docs/integrations/vercel-ai The Vercel AI SDK integrates via the [TypeScript SDK](https://cortexdb.ai/docs/sdks/typescript): isomorphic, so it runs in edge and Node runtimes. ## Install ```bash npm install cortexdbai ``` ## Recall + capture around a chat ```ts import { V1Client } from "cortexdbai/v1"; import { streamText } from "ai"; import { openai } from "@ai-sdk/openai"; const client = new V1Client({ apiUrl: "https://api-v1.cortexdb.ai", actor: "user:alice", bearer: process.env.CORTEXDB_TOKEN!, }); const scope = "org:acme/user:alice"; export async function POST(req: Request) { const { messages } = await req.json(); const last = messages.at(-1).content; const pack = await client.recall(scope, { view: "holistic", query: last, diagnostics: "none" }); const result = streamText({ model: openai("gpt-4o"), system: `Relevant memory:\n${pack.context_block ?? ""}`, messages, }); await client.experience(scope, { text: last, role: "user", observedAt: new Date().toISOString(), idempotencyKey: `chat-${crypto.randomUUID()}`, }); return result.toDataStreamResponse(); } ``` > **Note: TS SDK items are flattened and camelCase** `experience()` takes an `ExperienceItem` with camelCase fields (`text`, `role`, `observedAt`, `idempotencyKey`, …) and the SDK builds the snake_case wire envelope; passing `content` / `context` is a type error and throws at runtime. See the [TypeScript SDK](https://cortexdb.ai/docs/sdks/typescript). ## See also - [TypeScript SDK](https://cortexdb.ai/docs/sdks/typescript) · [Mastra](https://cortexdb.ai/docs/integrations/mastra) · [Eliza OS](https://cortexdb.ai/docs/integrations/eliza) ========================================================================================== # NeMo Guardrails _Use CortexDB as a knowledge base for NVIDIA NeMo Guardrails._ Source: https://cortexdb.ai/docs/integrations/nemo-guardrails CortexDB backs NeMo Guardrails as a retrieval knowledge base, so guardrail flows can ground responses in your memory. ## Install ```bash pip install cortexdbai[nemo-guardrails] ``` ## Knowledge base ```python from cortexdb import Cortex from cortexdb.integrations.nemo_guardrails import CortexDBKnowledgeBase client = Cortex(api_url="https://api-v1.cortexdb.ai", actor="user:alice", bearer=os.environ["CORTEXDB_TOKEN"]) kb = CortexDBKnowledgeBase(client=client, scope="org:acme/user:alice") # register kb with your RailsConfig / LLMRails instance ``` ## See also - [Python SDK](https://cortexdb.ai/docs/sdks/python) · [POST /v1/recall](https://cortexdb.ai/docs/api-reference/recall) ========================================================================================== # Temporal _Capture and recall CortexDB memory from Temporal workflows and activities._ Source: https://cortexdb.ai/docs/integrations/temporal CortexDB integrates with Temporal as **activities** (durable capture/recall steps) and an **interceptor** that records workflow events automatically. ## Install ```bash pip install cortexdbai[temporal] ``` ## Activities + interceptor ```python from cortexdb import Cortex from cortexdb.integrations.temporal import CortexDBActivities, CortexDBInterceptor client = Cortex(api_url="https://api-v1.cortexdb.ai", actor="service:worker", bearer=os.environ["CORTEXDB_TOKEN"]) scope = "org:acme/service:worker" activities = CortexDBActivities(client=client, scope=scope) worker = Worker( client=temporal_client, task_queue="memory", activities=activities.get_activities(), # remember, recall, forget interceptors=[CortexDBInterceptor(client=client, scope=scope)], ) ``` The bundled `remember` activity sets no idempotency key, so a retried activity writes again. For exactly-once capture, write your own activity that calls `client.experience(..., idempotency_key=f"{info.workflow_run_id}-{info.activity_id}")` (keys are at most 64 characters). ## See also - [Python SDK](https://cortexdb.ai/docs/sdks/python) · [Prefect](https://cortexdb.ai/docs/integrations/prefect) · [POST /v1/experience](https://cortexdb.ai/docs/api-reference/experience) ========================================================================================== # Prefect _Capture and recall CortexDB memory from Prefect flows via a configuration Block._ Source: https://cortexdb.ai/docs/integrations/prefect CortexDB ships a Prefect **Block** so flows and tasks can capture and recall memory with managed credentials. ## Install ```bash pip install cortexdbai[prefect] ``` ## Block ```python from cortexdb.integrations.prefect import CortexDBBlock # Register once (or via the Prefect UI) block = CortexDBBlock( api_url="https://api-v1.cortexdb.ai", actor="service:etl", bearer=os.environ["CORTEXDB_TOKEN"], scope="org:acme/service:etl", ) block.save("cortexdb-prod") ``` ```python from prefect import flow from cortexdb.integrations.prefect import CortexDBBlock @flow def ingest(records): block = CortexDBBlock.load("cortexdb-prod") client = block.get_client() for r in records: client.experience(scope=block.scope, text=r["text"], role="user", observed_at=r["ts"], idempotency_key=r["id"]) ``` ## See also - [Python SDK](https://cortexdb.ai/docs/sdks/python) · [Temporal](https://cortexdb.ai/docs/integrations/temporal) · [Airflow](https://cortexdb.ai/docs/integrations/airflow) ========================================================================================== # Apache Airflow _Capture and recall CortexDB memory from Airflow DAGs using the Python SDK._ Source: https://cortexdb.ai/docs/integrations/airflow Airflow has no dedicated adapter: use the [Python SDK](https://cortexdb.ai/docs/sdks/python) directly inside a `PythonOperator` or `@task`. ## Install ```bash pip install cortexdbai apache-airflow ``` ## A capture task ```python from airflow.decorators import dag, task from cortexdb.v1 import V1Client import hashlib, os, pendulum @dag(schedule="@daily", start_date=pendulum.datetime(2026, 1, 1), catchup=False) def cortexdb_ingest(): @task def ingest(**ctx): client = V1Client(api_url="https://api-v1.cortexdb.ai", actor="service:etl", bearer=os.environ["CORTEXDB_TOKEN"]) for row in fetch_rows(): client.experience( scope="org:acme/service:etl", text=row["text"], role="user", observed_at=row["ts"], # idempotent across retries; hashed because keys are capped at 64 characters idempotency_key=hashlib.sha256(f"{ctx['run_id']}-{row['id']}".encode()).hexdigest()[:48], ) ingest() cortexdb_ingest() ``` Keying `idempotency_key` off the Airflow `run_id` makes a retried task replay rather than duplicate. ## See also - [Python SDK](https://cortexdb.ai/docs/sdks/python) · [Prefect](https://cortexdb.ai/docs/integrations/prefect) · [POST /v1/experience](https://cortexdb.ai/docs/api-reference/experience) ========================================================================================== # n8n _Capture and recall CortexDB memory from n8n workflows via the HTTP Request node._ Source: https://cortexdb.ai/docs/integrations/n8n n8n talks to CortexDB through the **HTTP Request** node: no package required. Use the [REST API](https://cortexdb.ai/docs/sdks/rest-api) directly. ## Capture an experience HTTP Request node → `POST https://api-v1.cortexdb.ai/v1/experience`, headers `Authorization: Bearer {{$env.CORTEXDB_TOKEN}}` + `X-Cortex-Actor: user:alice`, JSON body: ```json { "scope": "org:acme/user:alice", "modality": "conversation", "content": { "kind": "text", "text": "={{ $json.message }}" }, "context": { "observed_at": "={{ $now.toISO() }}" }, "idempotency_key": "={{ $json.id }}" } ``` > **Note: modality is valid in the REST body** The **REST body takes a `modality` field** (the Python SDK's `experience()` fills it for you, or takes an optional `modality=`): the n8n envelope above is correct as written. ## Recall HTTP Request node → `POST /v1/recall` with body `{ "scope": "org:acme/user:alice", "view": "holistic", "query": "={{ $json.query }}", "diagnostics": "none" }`, then read `{{ $json.context_block }}` downstream. ## See also - [REST API](https://cortexdb.ai/docs/sdks/rest-api) · [Zapier](https://cortexdb.ai/docs/integrations/zapier) · [Make.com](https://cortexdb.ai/docs/integrations/make) ========================================================================================== # Zapier _Capture CortexDB memory from Zapier Zaps via a Webhooks action._ Source: https://cortexdb.ai/docs/integrations/zapier Zapier talks to CortexDB through the **Webhooks by Zapier** action (Custom Request): no package required. Use the [REST API](https://cortexdb.ai/docs/sdks/rest-api). ## Capture step Add a **Webhooks by Zapier → Custom Request** action: - **Method:** `POST` - **URL:** `https://api-v1.cortexdb.ai/v1/experience` - **Headers:** `Authorization: Bearer `, `X-Cortex-Actor: user:alice`, `Content-Type: application/json` - **Data (JSON):** ```json { "scope": "org:acme/user:alice", "modality": "conversation", "content": { "kind": "text", "text": "{{message}}" }, "context": { "observed_at": "{{zap_meta_human_now}}" }, "idempotency_key": "{{id}}" } ``` Map the Zap's trigger fields into `text` and `idempotency_key`. The `modality` field is valid in the REST body. ## See also - [REST API](https://cortexdb.ai/docs/sdks/rest-api) · [Make.com](https://cortexdb.ai/docs/integrations/make) · [n8n](https://cortexdb.ai/docs/integrations/n8n) ========================================================================================== # Make.com _Capture CortexDB memory from Make.com scenarios via an HTTP module._ Source: https://cortexdb.ai/docs/integrations/make Make.com (formerly Integromat) talks to CortexDB through the **HTTP → Make a request** module: no package required. Use the [REST API](https://cortexdb.ai/docs/sdks/rest-api). ## Capture module - **URL:** `https://api-v1.cortexdb.ai/v1/experience` - **Method:** `POST` - **Headers:** `Authorization: Bearer `, `X-Cortex-Actor: user:alice` - **Body type:** Raw / JSON: ```json { "scope": "org:acme/user:alice", "modality": "conversation", "content": { "kind": "text", "text": "{{1.message}}" }, "context": { "observed_at": "{{now}}" }, "idempotency_key": "{{1.id}}" } ``` Map earlier-module fields into `text` and `idempotency_key`. `modality` is valid in the REST body. ## See also - [REST API](https://cortexdb.ai/docs/sdks/rest-api) · [Zapier](https://cortexdb.ai/docs/integrations/zapier) · [n8n](https://cortexdb.ai/docs/integrations/n8n) ========================================================================================== # Flowise _Add CortexDB memory to Flowise flows with the CortexDB node._ Source: https://cortexdb.ai/docs/integrations/flowise CortexDB ships a Flowise node so you can add persistent memory to a flow visually. ## Install The node is bundled in the `cortexdbai[flowise]` integration (`CortexDBNode`); install it into your Flowise environment, then add the **CortexDB** node from the node palette. ```bash pip install cortexdbai[flowise] ``` ## Configure the node The package ships a node definition, not a Flowise palette plugin: `get_node_definition()` returns the JSON for a **CortexDB Memory** node, which you import into Flowise, and `CortexDBNode` executes it. The node's inputs are **API URL**, **Scope**, **Operation** (Auto / Store / Recall / Search / Forget), **Input** and **Reason**, plus an **Output**. The bearer token and actor are not node inputs; set them on `CortexDBNode(api_url=..., scope=..., bearer=..., actor=...)`. It is an operation node: each run performs the chosen operation on its input (Auto decides between store and recall), rather than acting as a memory input that recalls and captures around the model. ## See also - [Dify](https://cortexdb.ai/docs/integrations/dify) · [Python SDK](https://cortexdb.ai/docs/sdks/python) · [POST /v1/recall](https://cortexdb.ai/docs/api-reference/recall) ========================================================================================== # Dify _Add CortexDB search and store tools to Dify apps._ Source: https://cortexdb.ai/docs/integrations/dify CortexDB exposes memory to Dify as **store** and **search** tools you can add to an agent or workflow app. ## Install ```bash pip install cortexdbai[dify] ``` ## Tools ```python import os from cortexdb.integrations.dify import CortexDBStoreTool, CortexDBSearchTool scope = "org:acme/user:alice" conn = dict(api_url="https://api-v1.cortexdb.ai", actor="user:alice", bearer=os.environ["CORTEXDB_TOKEN"], scope=scope) # The Dify tools build their own client from these fields (they take no client= argument) store = CortexDBStoreTool(**conn) search = CortexDBSearchTool(**conn) # register the tools with your Dify custom-tool provider ``` ## See also - [Flowise](https://cortexdb.ai/docs/integrations/flowise) · [Python SDK](https://cortexdb.ai/docs/sdks/python) · [POST /v1/recall](https://cortexdb.ai/docs/api-reference/recall) ========================================================================================== # Ollama _Use a locally-hosted Ollama model as the answer model and entity-extraction LLM for CortexDB._ Source: https://cortexdb.ai/docs/integrations/ollama CortexDB routes its LLM calls through configured routers. Point them at an Ollama instance to keep all inference local: no data leaves your network. > **Note: Two lanes: extraction (CORTEX_LLM_*) and answer (CORTEX_ANSWER_*)** `CORTEX_LLM_*` configures the **entity-extraction** lane. `/v1/answer` uses the **separate `CORTEX_ANSWER_*` lane**, which defaults to `provider=anthropic` / `claude-opus-5-5` (baked into the image). **Setting `CORTEX_LLM_*` alone leaves `/v1/answer` on the disabled Anthropic default**: you must set both lanes. See [Self-hosting defaults](https://cortexdb.ai/docs/self-hosting/defaults). ## Deployment configuration Set these on the cortex server: ```bash # Entity-extraction lane CORTEX_LLM_URL=http://localhost:11434/v1 CORTEX_LLM_MODEL=llama3.1:70b CORTEX_ENTITY_API_KEY=ollama # placeholder, but must be non-empty or extraction is disabled # Answer lane: REQUIRED for /v1/answer to route through Ollama CORTEX_ANSWER_PROVIDER=ollama CORTEX_ANSWER_URL=http://localhost:11434 CORTEX_ANSWER_MODEL=llama3.1:70b CORTEX_ANSWER_API_KEY=ollama # placeholder # Embedding (for vector recall) CORTEX_EMBEDDING_PROVIDER=ollama CORTEX_EMBEDDING_MODEL=nomic-embed-text CORTEX_EMBEDDING_DIMS=768 CORTEX_EMBEDDING_API_KEY=ollama # non-empty required even for Ollama ``` Restart the service to pick up the new config, then confirm `/v1/answer` is live: ```bash curl -s http://localhost:3141/v1/admin/ready # degraded:false = provider not mock and not failing ``` `degraded: false` is not yet proof the provider works: after each boot `embeddings.unproven` stays `true` until the first real provider call succeeds. Make one (a write, or `curl -s "http://localhost:3141/v1/admin/ready?deep=1"`) before calling the provider verified. ## Choosing the model The answer model is the one in `CORTEX_ANSWER_MODEL`. A per-request `answer_model` on `/v1/answer` is only echoed in `diagnostics.answer_model`; the configured model answers. To serve a different model, change `CORTEX_ANSWER_MODEL` or run a second deployment. See [LLM & Answer Generation](https://cortexdb.ai/docs/operations/llm-answer#diagnostics). ## Pulling models ```bash ollama pull llama3.1:70b ollama pull nomic-embed-text ``` For benchmark-grade accuracy use the largest model your GPU fits (Llama 3.1 70B or Qwen 2.5 72B); smaller models lose 5 to 15 pp on multi-session reasoning. > **Note: Embeddings can stay on Ollama or go to OpenAI; pick by hardware** The embedding lane is independent of the answer and extraction lanes. On a high-end machine (spare CPU and RAM, ideally a GPU) or when text must never leave the box, keep `nomic-embed-text` on Ollama as above. On modest hardware (a laptop, no GPU, limited RAM or disk) it is fine, and simpler, to leave embeddings on OpenAI's `text-embedding-3-small` (just set `CORTEX_EMBEDDING_API_KEY` and drop the four `CORTEX_EMBEDDING_*` lines above) while the LLM lanes stay on Ollama. Decide before the first write: the embedding provider is pinned to the data directory, and switching later is an offline rebuild (see [Embeddings](https://cortexdb.ai/docs/operations/embeddings#changing-the-embedding-model-on-an-existing-store)). ## See also - [LLM & Answer Generation](https://cortexdb.ai/docs/operations/llm-answer) · [Embeddings](https://cortexdb.ai/docs/operations/embeddings) - [POST /v1/answer](https://cortexdb.ai/docs/api-reference/answer) · [Python SDK](https://cortexdb.ai/docs/sdks/python) ========================================================================================== # vLLM _Route CortexDB's answer and extraction LLM calls through a self-hosted vLLM server._ Source: https://cortexdb.ai/docs/integrations/vllm vLLM serves any Hugging Face model behind an OpenAI-compatible endpoint, so CortexDB can keep all inference on your own hardware. > **Note: Set both the extraction and answer lanes** `CORTEX_LLM_*` is the **entity-extraction** lane; `/v1/answer` uses the **separate `CORTEX_ANSWER_*` lane** (default `anthropic`/`claude-opus-5-5`). Set both. See [Self-hosting defaults](https://cortexdb.ai/docs/self-hosting/defaults). ## Start vLLM ```bash python -m vllm.entrypoints.openai.api_server \ --model meta-llama/Llama-3.3-70B-Instruct \ --port 8000 \ --api-key local-secret ``` ## Deployment configuration ```bash # Extraction lane CORTEX_LLM_URL=http://localhost:8000/v1 CORTEX_LLM_MODEL=meta-llama/Llama-3.3-70B-Instruct CORTEX_ENTITY_API_KEY=local-secret # matches --api-key; must be non-empty even if vLLM has none # Answer lane (OpenAI-compatible) CORTEX_ANSWER_PROVIDER=openai CORTEX_ANSWER_URL=http://localhost:8000/v1 CORTEX_ANSWER_MODEL=meta-llama/Llama-3.3-70B-Instruct CORTEX_ANSWER_API_KEY=local-secret ``` Keep `CORTEX_EMBEDDING_*` on a local Ollama or an embedding-serving vLLM instance. See [Embeddings](https://cortexdb.ai/docs/operations/embeddings). ## Choosing the model The answer model is the one in `CORTEX_ANSWER_MODEL`. A per-request `answer_model` on `/v1/answer` is only echoed in `diagnostics.answer_model`; the configured model answers. To serve a different model, change `CORTEX_ANSWER_MODEL` or run a second deployment. See [LLM & Answer Generation](https://cortexdb.ai/docs/operations/llm-answer#diagnostics). ## See also - [LLM & Answer Generation](https://cortexdb.ai/docs/operations/llm-answer) · [POST /v1/answer](https://cortexdb.ai/docs/api-reference/answer) ========================================================================================== # Groq _Route CortexDB's answer and extraction LLM calls through Groq's fast inference API._ Source: https://cortexdb.ai/docs/integrations/groq Groq exposes an OpenAI-compatible API, so CortexDB's LLM routers point straight at it for very low-latency answer generation. > **Note: Set both the extraction and answer lanes** `CORTEX_LLM_*` is the **entity-extraction** lane; `/v1/answer` uses the **separate `CORTEX_ANSWER_*` lane** (default `anthropic`/`claude-opus-5-5`). Setting `CORTEX_LLM_*` alone leaves `/v1/answer` on the disabled default: set both. See [Self-hosting defaults](https://cortexdb.ai/docs/self-hosting/defaults). ## Deployment configuration ```bash # Extraction lane CORTEX_LLM_URL=https://api.groq.com/openai/v1 CORTEX_LLM_MODEL=llama-3.3-70b-versatile CORTEX_ENTITY_API_KEY=$GROQ_API_KEY # Answer lane: Groq is OpenAI-compatible, so use the openai provider + Groq URL CORTEX_ANSWER_PROVIDER=openai CORTEX_ANSWER_URL=https://api.groq.com/openai/v1 CORTEX_ANSWER_MODEL=llama-3.3-70b-versatile CORTEX_ANSWER_API_KEY=$GROQ_API_KEY ``` > **Note: Embeddings run elsewhere** Groq does not serve embeddings: keep `CORTEX_EMBEDDING_*` on OpenAI or a local Ollama (`nomic-embed-text`). See [Embeddings](https://cortexdb.ai/docs/operations/embeddings). Restart the service, then confirm the boot log shows `Answer LLM router enabled for /v1/answer` with the Groq model, and check a test answer in Groq's own usage dashboard (`diagnostics.answer_model` echoes the configured or requested name and does not prove routing). ## Choosing the model The answer model is the one in `CORTEX_ANSWER_MODEL`. A per-request `answer_model` on `/v1/answer` is only echoed in `diagnostics.answer_model`; the configured model answers. To serve a different model, change `CORTEX_ANSWER_MODEL` or run a second deployment. See [LLM & Answer Generation](https://cortexdb.ai/docs/operations/llm-answer#diagnostics). ## See also - [LLM & Answer Generation](https://cortexdb.ai/docs/operations/llm-answer) · [POST /v1/answer](https://cortexdb.ai/docs/api-reference/answer) ========================================================================================== # Together AI _Route CortexDB's answer and extraction LLM calls through Together AI's OpenAI-compatible API._ Source: https://cortexdb.ai/docs/integrations/together Together AI exposes an OpenAI-compatible API, so CortexDB's LLM routers point straight at it. > **Note: Set both the extraction and answer lanes** `CORTEX_LLM_*` is the **entity-extraction** lane; `/v1/answer` uses the **separate `CORTEX_ANSWER_*` lane** (default `anthropic`/`claude-opus-5-5`). Set both: `CORTEX_LLM_*` alone leaves `/v1/answer` on the disabled default. See [Self-hosting defaults](https://cortexdb.ai/docs/self-hosting/defaults). ## Deployment configuration ```bash # Extraction lane CORTEX_LLM_URL=https://api.together.xyz/v1 CORTEX_LLM_MODEL=meta-llama/Llama-3.3-70B-Instruct-Turbo CORTEX_ENTITY_API_KEY=$TOGETHER_API_KEY # Answer lane (OpenAI-compatible) CORTEX_ANSWER_PROVIDER=openai CORTEX_ANSWER_URL=https://api.together.xyz/v1 CORTEX_ANSWER_MODEL=meta-llama/Llama-3.3-70B-Instruct-Turbo CORTEX_ANSWER_API_KEY=$TOGETHER_API_KEY ``` Together also serves embeddings (e.g. `togethercomputer/m2-bert-80M-8k-retrieval`) if you'd rather keep those local to the same provider: otherwise keep `CORTEX_EMBEDDING_*` on OpenAI or Ollama. See [Embeddings](https://cortexdb.ai/docs/operations/embeddings). ## Choosing the model The answer model is the one in `CORTEX_ANSWER_MODEL`. A per-request `answer_model` on `/v1/answer` is only echoed in `diagnostics.answer_model`; the configured model answers. To serve a different model, change `CORTEX_ANSWER_MODEL` or run a second deployment. See [LLM & Answer Generation](https://cortexdb.ai/docs/operations/llm-answer#diagnostics). ## See also - [LLM & Answer Generation](https://cortexdb.ai/docs/operations/llm-answer) · [POST /v1/answer](https://cortexdb.ai/docs/api-reference/answer) ========================================================================================== # Fireworks AI _Route CortexDB's answer and extraction LLM calls through Fireworks AI's OpenAI-compatible API._ Source: https://cortexdb.ai/docs/integrations/fireworks Fireworks AI exposes an OpenAI-compatible API, so CortexDB's LLM routers point straight at it. > **Note: Set both the extraction and answer lanes** `CORTEX_LLM_*` is the **entity-extraction** lane; `/v1/answer` uses the **separate `CORTEX_ANSWER_*` lane** (default `anthropic`/`claude-opus-5-5`). Set both. See [Self-hosting defaults](https://cortexdb.ai/docs/self-hosting/defaults). ## Deployment configuration ```bash # Extraction lane CORTEX_LLM_URL=https://api.fireworks.ai/inference/v1 CORTEX_LLM_MODEL=accounts/fireworks/models/llama-v3p3-70b-instruct CORTEX_ENTITY_API_KEY=$FIREWORKS_API_KEY # Answer lane (OpenAI-compatible) CORTEX_ANSWER_PROVIDER=openai CORTEX_ANSWER_URL=https://api.fireworks.ai/inference/v1 CORTEX_ANSWER_MODEL=accounts/fireworks/models/llama-v3p3-70b-instruct CORTEX_ANSWER_API_KEY=$FIREWORKS_API_KEY ``` Keep `CORTEX_EMBEDDING_*` on OpenAI or a local Ollama unless you're using a Fireworks embedding model. See [Embeddings](https://cortexdb.ai/docs/operations/embeddings). ## Choosing the model The answer model is the one in `CORTEX_ANSWER_MODEL`. A per-request `answer_model` on `/v1/answer` is only echoed in `diagnostics.answer_model`; the configured model answers. To serve a different model, change `CORTEX_ANSWER_MODEL` or run a second deployment. See [LLM & Answer Generation](https://cortexdb.ai/docs/operations/llm-answer#diagnostics). ## See also - [LLM & Answer Generation](https://cortexdb.ai/docs/operations/llm-answer) · [POST /v1/answer](https://cortexdb.ai/docs/api-reference/answer) ========================================================================================== # DeepInfra _Route CortexDB's answer and extraction LLM calls through DeepInfra's OpenAI-compatible API._ Source: https://cortexdb.ai/docs/integrations/deepinfra DeepInfra exposes an OpenAI-compatible API, so CortexDB's LLM routers point straight at it. > **Note: Set both the extraction and answer lanes** `CORTEX_LLM_*` is the **entity-extraction** lane; `/v1/answer` uses the **separate `CORTEX_ANSWER_*` lane** (default `anthropic`/`claude-opus-5-5`). Set both. See [Self-hosting defaults](https://cortexdb.ai/docs/self-hosting/defaults). ## Deployment configuration ```bash # Extraction lane CORTEX_LLM_URL=https://api.deepinfra.com/v1/openai CORTEX_LLM_MODEL=meta-llama/Meta-Llama-3.1-70B-Instruct CORTEX_ENTITY_API_KEY=$DEEPINFRA_API_KEY # Answer lane (OpenAI-compatible) CORTEX_ANSWER_PROVIDER=openai CORTEX_ANSWER_URL=https://api.deepinfra.com/v1/openai CORTEX_ANSWER_MODEL=meta-llama/Meta-Llama-3.1-70B-Instruct CORTEX_ANSWER_API_KEY=$DEEPINFRA_API_KEY ``` DeepInfra also serves embedding models; otherwise keep `CORTEX_EMBEDDING_*` on OpenAI or Ollama. See [Embeddings](https://cortexdb.ai/docs/operations/embeddings). ## Choosing the model The answer model is the one in `CORTEX_ANSWER_MODEL`. A per-request `answer_model` on `/v1/answer` is only echoed in `diagnostics.answer_model`; the configured model answers. To serve a different model, change `CORTEX_ANSWER_MODEL` or run a second deployment. See [LLM & Answer Generation](https://cortexdb.ai/docs/operations/llm-answer#diagnostics). ## See also - [LLM & Answer Generation](https://cortexdb.ai/docs/operations/llm-answer) · [POST /v1/answer](https://cortexdb.ai/docs/api-reference/answer) ========================================================================================== # CortexDB on the public memory benchmarks _CortexDB 0.14.2 scores 95.4% on LongMemEval-S and 92.8% on LoCoMo. Methodology, per-category results, performance and cost from the same run, and how it compares with published results._ Source: https://cortexdb.ai/docs/integrations/benchmark-paper > **Note: Results: CortexDB 0.14.2, November 2026** LongMemEval-S **95.4%** (477/500), run blind and scored with LongMemEval's own evaluator (GPT-4o judge). LoCoMo categories 1 to 4 **92.8%** (1,429/1,540), scored by a gpt-4.1 binary LLM judge with the Memori/Mem0 prompt. The configuration and commands are on [Benchmarking](https://cortexdb.ai/docs/operations/benchmarking), and the sources for every other system's figure are at [cortexdb.ai/benchmarks](https://cortexdb.ai/benchmarks). ## Abstract We report CortexDB's scores on the two public, standardized long-term-memory benchmarks for conversational AI: **LongMemEval-S** (ICLR 2025; 500 questions across six question types) and **LoCoMo** (NAACL 2024; 1,540 questions in categories 1 to 4). On LongMemEval-S, CortexDB 0.14.2 answers **95.4%** correctly (477/500), run blind under the benchmark's own judge; on LoCoMo categories 1 to 4, **92.8%** (1,429/1,540). Both runs used the released 0.14.2 image, a single attempt per question, and a configuration we hand to anyone who wants to rerun them. The same LongMemEval run was instrumented end to end, so its write latency, memory and disk footprint and cost are reported here too. ## 1. Why benchmark at all A long-term memory layer is easy to demo and hard to verify. The interesting questions (does it work across hundreds of sessions, answer questions about time correctly, find the right turn out of thousands) only show up at scale, on test sets the author didn't design. Two public benchmarks serve this role: - **LongMemEval-S** (Wu et al., 2025): 500 questions about long chat histories (facts the user stated, what changed, what happened when, what the assistant said, what the user prefers); each history averages about 115k tokens. - **LoCoMo** (Maharana et al., 2024): questions about ten very long conversations, each about 600 turns over up to 32 sessions. We use the official datasets and the official evaluator, and the same write and read paths that ship in the product. ## 2. Headline numbers | Benchmark | Score | Detail | Release | Date | |---|---|---|---|---| | LongMemEval-S | 95.4% | 477 / 500 | 0.14.2, run blind, LongMemEval's own evaluator (GPT-4o judge) | November 2026 | | LoCoMo (categories 1 to 4) | 92.8% | 1,429 / 1,540 | 0.14.2, gpt-4.1 binary LLM judge, Memori/Mem0 prompt | November 5, 2026 | ## 3. Methodology - **Run blind.** The harness strips question types, ids and answers before anything reaches the server, and hashes the scope names. No gold answer, question type or question id reaches CortexDB. - **The benchmark's own judge.** LongMemEval's `evaluate_qa.py` with GPT-4o (`gpt-4o-2024-08-06`), not a custom or friendlier grader. - **Released software.** The 0.14.2 image customers and CortexDB Cloud run, every memory written through `POST /v1/experience` and every answer read through `/v1/recall` and `/v1/answer`. - **Reproducible.** The configuration, the harness and the outputs are ready for a third-party rerun ([Benchmarking](https://cortexdb.ai/docs/operations/benchmarking)). | Role | Model | |---|---| | Answers (the reader) | Claude Opus 5.5 (`claude-opus-5-5`), thinking effort high | | Embeddings | OpenAI `text-embedding-3-small`, 1,536 dimensions | | Reranking | Cohere `rerank-v3.5` | | Query expansion | `gpt-4o-mini` | | Verifier | `gpt-4.1` | | Fact extraction by the harness | `gpt-4o-mini`, the same way for every question | | Judge | LongMemEval's evaluator with `gpt-4o` | Each LongMemEval question gets its own memory space, so background work that summarizes across a space is switched off for the run. ## 4. LongMemEval-S results CortexDB 0.14.2, Claude Opus 5.5 reader, all 500 questions, run blind. | Question type | Questions | Correct | |---|---:|---:| | Facts the user stated (single-session-user) | 70 | 100% | | What the assistant said (single-session-assistant) | 56 | 100% | | Knowledge that changed (knowledge-update) | 78 | 100% | | User preferences (single-session-preference) | 30 | 93.3% | | Across many sessions (multi-session) | 133 | 93.2% | | Reasoning about time (temporal-reasoning) | 133 | 91.0% | | **All questions** | **500** | **95.4%** | The previous release, 0.14.1, scored 95.8% under the same judge a day earlier. ### Published results on LongMemEval-S All 500 questions, accuracy in percent. Every other figure is that vendor's own published result. Readers (the model that writes the answer) and judges differ between vendors, as marked. | System | LongMemEval-S | Reader | Judge | |---|---:|---|---| | CortexDB 0.14.2 | 95.4 | Claude Opus 5.5 | Official judge, run blind | | Mem0 Platform | 94.8 | Not disclosed | Not disclosed | | EverOS (EverMind) | 94.0 | Method not stated | Method not stated | | Mastra Observational Memory | 93.6 | gpt-5-mini | Official judge | | Backboard | 93.4 | Not stated | Best of 4 judges | | MemMachine | 93.0 | gpt-5-mini | gpt-4o-mini | | Honcho | 92.6 | Gemini 3 Pro | Not named | | Lumetra Engram | 91.6 | GPT-5 | gpt-4o | | Hindsight (Vectorize) | 91.4 | Gemini 3 Pro | Open-model judge | | Zep | 90.2 | gpt-5.4 | gpt-5.4 | | Supermemory | 85.2 | Gemini 3 Pro | Official judge | | Full chat history in GPT-4o, no memory system | 60.6 | GPT-4o | Official judge | Mastra's headline 94.87% averages its category scores; 93.6% is its overall accuracy from its published counts. Experimental and retrieval-only claims are not listed. The sources for each figure are at [cortexdb.ai/benchmarks](https://cortexdb.ai/benchmarks). ## 5. LoCoMo results All 1,540 questions in categories 1 to 4, run label-blind: every question gets the same prompt, and no category reaches the server. Category 5 (adversarial questions) is not scored, as in Mem0's protocol, because its score depends on the refusal prompt rather than on memory. | Category | Questions | Correct | |---|---:|---:| | Single-hop | 841 | 95.6% | | Temporal | 321 | 92.2% | | Multi-hop | 282 | 87.9% | | Open-domain | 96 | 84.4% | | **All of categories 1 to 4** | **1,540** | **92.8%** | CortexDB 0.14.2 answering with Claude Opus 5.5, scored by a gpt-4.1 binary LLM judge using the Memori/Mem0 prompt, November 5, 2026. ## 6. Performance and cost The same LongMemEval run, instrumented end to end: 466,283 memories (1.02 million indexed chunks) written into 500 separate memory spaces and 500 questions answered, on one 16-core server. | Measure | Value | |---|---| | Durable write | 12 ms median to commit a batch of about 880 memories to the replicated log (p99 19 ms) | | Memory footprint | 11 KB of RAM per memory: 5.3 GB peak for all 466K memories | | Disk footprint | 19 KB per memory, everything included: log, vectors, text index, layers | | CPU | 0.54 cores on average over the whole run (1.4 peak): the work waits on the model APIs, not on CortexDB | Latency, in milliseconds: | Stage | p50 | p95 | p99 | |---|---:|---:|---:| | Durable write (batch of about 880) | 12 | 15 | 19 | | Admission | 7 | 10 | 16 | | Searchable, including remote embedding | 12,142 | 18,550 | 23,141 | | Recall for an answer | 2,356 | 8,830 | 12,752 | | Answer generation (Opus 5.5) | 2,983 | 15,262 | 21,037 | | Full answer, end to end | 5,615 | 23,246 | 29,073 | A write is durable as soon as the log commits it. It becomes searchable once its embeddings come back from the embedding provider, which is where nearly all of that time goes. Recall here includes the parallel sub-queries and reranking an answer runs. Where the 8.9 GB on disk goes: | Part | Size | |---|---:| | Vector index | 6.74 GB | | Replicated and derived logs | 0.98 GB | | Content, history and layers | 0.84 GB | | Text index | 0.33 GB | **What a question costs:** $0.095 in answer-model tokens per question with Claude Opus 5.5 at high effort, every call included (21.8K input tokens on average), and $1.59 to embed all 80 million tokens of the 500 histories. You choose the models; CortexDB's [usage ledger](https://cortexdb.ai/docs/operations/usage-ledger) records the tokens and cost of every call. Setup: the CortexDB 0.14.2 release image on one AWS `m7i.4xlarge` (16 vCPU, 64 GB), embeddings from OpenAI `text-embedding-3-small`, reranking with Cohere `rerank-v3.5`, eight questions in flight at once. RAM is the server process's resident memory; disk is the whole data directory after the run. ## 7. Threats to validity - **Benchmark coverage.** Both benchmarks are conversational; these scores may not carry over to other kinds of memory. - **Readers and judges.** The model that writes the answer and the judge that scores it move results by several points, and they differ between the published results above. Compare like with like, and note both for every number. - **Run-to-run variance.** Expect about a point of movement between runs: model sampling and provider-side model updates change individual answers. 0.14.1 scored 95.8% under the same setup. - **Commercial models.** Claude Opus 5.5, OpenAI embeddings and Cohere reranking are commercial services; a self-hosted model stack will score differently. ## 8. References Wu et al. (2025), *LongMemEval*, ICLR 2025 · Maharana et al. (2024), *LoCoMo*, NAACL 2024 · Chhikara et al. (2025), *Mem0* · Lewis et al. (2020), *RAG*, NeurIPS 2020. See [Benchmarking](https://cortexdb.ai/docs/operations/benchmarking) for the reproduction steps. ========================================================================================== # CortexDB v1 Architecture: The Experience Layer for AI Agents _How CortexDB v1 stores, derives, and serves long-term memory: five layers, bi-temporal records, hierarchical scopes, capability-based auth, and an async lifecycle._ Source: https://cortexdb.ai/docs/integrations/architecture-whitepaper ## Abstract CortexDB v1 treats every interaction, document, event, or observation as an **immutable experience** appended to a write-ahead log, then asynchronously derives five layered views (Events, Episodes, Facts, Beliefs, Understanding) that recall and answer endpoints query against. Every record is **bi-temporal** (carries both when it was true and when the system learned it). Every request is scoped to a hierarchical path and gated by a four-tier capability stack with PASETO v4 public-token identity. ## 1. Design constraints 1. **No information loss on the write path**: captured bytes are retained verbatim; summarization, dedup, and structuring happen downstream and can be re-run. 2. **Bi-temporal correctness**: answer both "what is true now" and "what did we know yesterday." 3. **Scope as a first-class concept**: multi-tenant, multi-user, and multi-agent all reduce to one primitive: a hierarchical path with ancestor/descendant semantics. 4. **Capability-based authorization**: every denial cites the deciding tier and the missing capability. 5. **Async-by-default, synchronously-completable**: writes return `202` in under 10 ms; clients can opt into `wait=indexed`. ## 2. The surface The daily-driver API is five endpoints: ```text POST /v1/auth/signup anonymous PASETO (dev_local, no API key set) POST /v1/experience append an experience (the only write) POST /v1/recall return a StratifiedPack (retrieval) POST /v1/answer recall + LLM answer + citations POST /v1/forget delete with an audit note (selective or GDPR) ``` Layer-direct reads (`/v1/events`, `/v1/facts`, …) exist for inspection; `/v1/recall` is the standard read path because it merges across layers. Identity is PASETO v4 public tokens; every request carries `Authorization: Bearer` + `X-Cortex-Actor` (must equal the token's `sub`, else `401 actor_mismatch`). ## 3. The five layers | Layer | Built by | Stored as | Latency | |---|---|---|---| | Events | sync write | WAL (append-only) | under 10 ms | | Episodes | segmenter | RocksDB + secondary index | seconds | | Facts | LLM extractor | Typed FactStore (bi-temporal) | ~5 to 30 s | | Beliefs | aggregator | Confidence-weighted store | ~minutes | | Understanding | LLM synthesizer | Concept store (per topic) | ~minutes to hours | - **Events**: the WAL; every `POST /v1/experience` becomes one immutable event (`{ id, scope, modality, content, context, observed_actor }`), idempotency-keyed so a resubmit replays the original response. - **Episodes**: the segmenter's chronologically-contiguous spans (a meeting, a thread, an incident). - **Facts**: subject/predicate/object triples, each with `valid_from`/`valid_to` (true in the world) and `recorded_from`/`recorded_to` (when the system knew). The largest single contributor to the benchmark scores (−22 pp if disabled). - **Beliefs**: facts aggregated into confidence-weighted claims, explainable via `GET /v1/beliefs/why`. - **Understanding**: the synthesized concept layer (named concepts, themes, relationships); the slowest and most expensive, gated by `understanding.synthesize`. ## 4. The five-stage lifecycle ```text CAPTURE → POST /v1/experience returns 202 + id once the WAL append commits. EXTRACT → LLM extractor pulls triples into Facts on the next scheduler tick. RECONCILE → Conflicts resolve under bi-temporal supersession (newest valid_from wins; the older record's valid_to is set to the new one's valid_from). FORGET → Selective forget across derived layers (derived_only / redact_events / gdpr). Audited. CONSOLIDATE → Synthesizer builds Understanding concepts per topic per scope. ``` Stage 1 is synchronous (the `202` means durable in the WAL); stages 2 to 5 are async: pass `?wait=indexed` (or `consolidated`) to block on a specific stage. ## 5. Bi-temporal storage Every record carries `valid_from`/`valid_to` (true in the world) and `recorded_from`/`recorded_to` (when the system learned it), supporting four query modes from the same data as **direct typed-store lookups** (no LLM, no scan): **Now** (`valid_to` and `recorded_to` null), **As-of** (`valid_from <= t < valid_to`), **As-known** (`recorded_from <= t < recorded_to`), and **History** (the full supersession chain). Most memory systems omit the `recorded_*` axis and cannot answer "what did we believe at the time." ## 6. Scopes A scope is a hierarchical path (`org:acme/dept:eng/team:platform/user:alice`) with three semantics: **addressing** (every experience is written to one scope), **read** (`holistic` traverses up, `descend` down, `granular`/`local` the named scope only), and **policy** (capabilities granted at any node inherit down the path). There is no flat `tenant_id` field in the v1 envelope. ## 7. The four-tier capability stack Evaluated outer-to-inner: **Deployment → Tenant → Scope → Actor**. A more-specific inner `allow` can override an outer `allow`; an outer `deny` is final. Anonymous signup tokens carry the standard read/write set but not `diagnostics.read`, `auth.mint`, or `forget.gdpr`. Denials are explicit (`error_code` `POLICY_DENIED` with `details.denied_by_tier` and the capability), and `GET /v1/policy/effective?actor=&scope=` returns the allow/deny sets for any actor-scope pair. ## 8. The auth model | Path | Use case | TTL | |---|---|---| | `POST /v1/auth/signup` | Anonymous "try it in 60 seconds" (dev_local, no API key) | 7 days | | `POST /v1/auth/tokens` | Service accounts via the in-binary minter (dev-only); needs `auth.mint` | 1 to 24 h | | Bring your own IdP | Production: register your Ed25519 public key; your IdP mints, CortexDB verifies | Your IdP's | ## 9. Storage and durability | Layer | Backing store | Crash semantics | |---|---|---| | Events (WAL) | append-only file + checksum chain | fsync'd once `202` returns | | Episodes / Facts / Beliefs / Understanding | RocksDB column families | rebuildable from the WAL (replayable) | | Blobs | content-addressed by SHA-256 | direct file storage | The WAL is the system of record; every derived layer can be rebuilt from it: a corrupted index is an operational annoyance, not data loss. ## 10. Observability Every authenticated response carries `X-RateLimit-Limit` / `-Reset`, `X-Cortex-Token-Expires-In` / `-At`, `X-Request-Id` (the caller's own id when it sent one), and a `Warning` header when token expiry ≤ 72h. The same request id is on a per-request log line (`CORTEX_REQUEST_LOG`, which by default logs failed and slow requests with the time spent in each stage) and on the audit rows the request writes; see [Configuration](https://cortexdb.ai/docs/operations/configuration#request-log-and-request-ids). `GET /v1/lifecycle/stream` (SSE) emits a payload per stage transition, with `Last-Event-ID` catchup. ## 11. Trade-offs - **Storage cost**: the raw event stream is ~1.3× the storage of a rewrite-based memory layer; the price of bi-temporal correctness. - **Read latency**: holistic recall p50 ~500 ms (the hybrid BM25 + HNSW + graph + reranker stage); `granular` skips half the pipeline (~80 ms) for a single-scope lookup. - **Async derivation**: Facts in seconds, Beliefs/Understanding minutes-to-hours; a recall right after a write returns the raw event but may not yet reflect derived knowledge (`?wait=indexed`). - **LLM dependency on the read path**: `/v1/answer` and synthesis need an LLM, but `/v1/recall` degrades gracefully and still returns the stratified pack. ## 12. What ships in v1 vs what comes next | Capability | v1 (shipped) | v2 (roadmap) | |---|---|---| | Capture (WAL append) | ✓ | none | | Extract (Facts via LLM) | ✓ | + multi-modal extractors | | Reconcile (bi-temporal supersession) | ✓ | + conflict-detection for human review | | Forget (selective + GDPR) | ✓ | none | | Consolidate (Understanding) | ✓ (basic) | + cross-scope generalization, procedure formation | | Recall (hybrid + rerank + graph) | ✓ | + learned-retrieval ranking | | Auth (PASETO + 4-tier policy) | ✓ | + per-record cell-level redaction | ## 13. Conclusion CortexDB v1 is a shipped, benchmarked production memory layer for AI agents: five derived layers from one source of truth, bi-temporal across both axes, scoped hierarchically, gated by an explicit capability stack, callable in one anonymous-signup `curl`. See [Core Concepts](https://cortexdb.ai/docs/concepts) for the reference treatment of each component.