Skip to main content

API Reference Overview

Welcome to the Cortex API Reference! This guide explains how to navigate the documentation and use Cortex effectively.

What is Cortex?

Cortex is a persistent memory system for AI agents built on Convex. It provides:

Four-Layer Architecture

ACID stores + Vector index + Facts store + Convenience API

Memory Space Isolation

Flexible boundaries (per user, team, or project)

Multi-Tenancy

Built-in tenantId for SaaS platform isolation

Hive Mode

Multiple tools share one memory space (zero duplication)

Infinite Context

Never run out of context via retrieval

Automatic Versioning

Track how information changes over time

Belief Revision System

Intelligent fact management with conflict resolution

GDPR Compliance

Built-in cascade deletion (Cloud Mode)

Universal Filters

Same filters work across all operations

Embedding-Agnostic

Bring your own embeddings or use Cloud Mode


Documentation Structure

The API Reference is organized by architectural layers:

Core Memory System (Start Here)

  • Memory Operations - The main API you'll use
    • Layer 4 convenience (cortex.memory.*)
    • Full orchestration: remember(), rememberStream(), recall()
    • Search, get, update, delete operations
    • Orchestration Observer for real-time monitoring
  • Memory Space Operations - Memory space management
    • Fundamental isolation boundary in Cortex
    • Explicit registration for production deployments
    • Hive Mode participant tracking
    • register(), get(), list(), archive(), delete(), getStats()
  • Conversation Operations - Layer 1a (ACID)
    • Immutable conversation threads (memorySpace-scoped)
    • Source of truth for all messages
    • create(), get(), addMessage(), getHistory(), list(), search(), delete()

User & Coordination

  • User Operations - User profiles + GDPR
    • Shared user data across all memory spaces
    • GDPR cascade deletion by userId (SDK + Cloud Mode)
    • Version history and time-travel queries
    • get(), update(), delete(), search(), list(), export()
  • Sessions Operations - Session lifecycle management
    • Multi-session support (web, mobile, API)
    • Activity tracking and idle detection
    • Configurable timeouts via Governance API
    • create(), get(), getOrCreate(), touch(), end(), getActive(), expireIdle()
  • Auth Integration - Authentication context
    • Framework-agnostic auth integration
    • Multi-tenancy support (tenantId auto-injection)
    • Works with Auth0, Clerk, NextAuth, Firebase, custom JWT
  • Agent Management - Optional agent metadata registry (analytics, discovery)
    • Optional metadata registration for discovery/analytics
    • Cascade deletion by participantId across all spaces
    • Use cortex.memorySpaces.* for production isolation
  • Context Operations - Workflow coordination
    • Hierarchical task tracking (parent/child chains)
    • Multi-agent collaboration
    • Cross-memorySpace delegation
    • create(), get(), update(), delete(), getChain(), getChildren()
  • A2A Communication - Inter-agent messaging
    • Helper API built on memory system (source.type='a2a')
    • Bidirectional storage (sender + receiver)
    • send(), request() (requires pub/sub), broadcast(), getConversation()

Advanced Storage

  • Immutable Store - Layer 1b
    • TRULY shared (no memorySpace scoping), versioned, immutable data
    • KB articles, policies, audit logs
    • store(), get(), getVersion(), getHistory(), purge()
  • Mutable Store - Layer 1c
    • TRULY shared (no memorySpace scoping), mutable, current-value data
    • ACID transactions, atomic operations
    • set(), get(), update(), increment(), transaction(), delete()
  • Facts Operations - Layer 3 Facts Store
    • Structured knowledge with versioning and confidence
    • Belief Revision System (v0.24.0+): revise(), checkConflicts(), supersede()
    • Enriched extraction (v0.15.0+): searchAliases, semanticContext, entities, relations
    • store(), get(), update(), delete(), search(), queryBySubject(), history()

Platform & Governance

  • Governance Policies - Retention rules & compliance
    • Per-layer, per-type, importance-based retention rules
    • Compliance templates: GDPR, HIPAA, SOC2, FINRA
    • Session lifecycle policies
    • setPolicy(), getPolicy(), enforce(), simulate()
  • Graph Operations - Graph database integration (v0.7.0+)
    • Optional integration with Neo4j, Memgraph
    • Real-time sync via GraphSyncWorker
    • Multi-hop traversal and orphan cleanup
    • Automatic sync when CORTEX_GRAPH_SYNC=true (v0.29.0+)

Reference


By Use Case

I want to...

Store conversation messages:Memory Operations - cortex.memory.remember()

Search agent memories:Memory Operations - cortex.memory.search()

Manage user profiles:User Operations - cortex.users.*

Delete user data (GDPR):User Operations - cortex.users.delete({ cascade: true })

Track multi-agent workflows:Context Operations - cortex.contexts.*

Send agent-to-agent messages:A2A Communication - cortex.a2a.send()

Store shared knowledge:Immutable Store - cortex.immutable.store()

Store live data (inventory, config):Mutable Store - cortex.mutable.set()

Set retention policies:Governance Policies - cortex.governance.*

Manage user sessions:Sessions Operations - cortex.sessions.*

Store and query facts:Facts Operations - cortex.facts.*

Integrate graph database:Graph Operations - GraphAdapter and GraphSyncWorker

See all TypeScript types:Types & Interfaces

Debug an error:Error Handling

By Layer

Layer 1a (ACID Conversations):Conversation Operations

Layer 1b (Immutable Store):Immutable Store

Layer 1c (Mutable Store):Mutable Store

Layer 2 (Vector Index):Memory Operations - cortex.vector.*

Layer 3 (Facts Store):Facts Operations - cortex.facts.*

Layer 4 (Convenience API):Memory Operations - cortex.memory.*

Sessions:Sessions Operations - cortex.sessions.*


Key Concepts

The Four-Layer Architecture

Cortex separates storage (immutable source) from search (optimized index):

Four-Layer Architecture
Layer 1: ACID Stores

1a: Conversations � 1b: Immutable (KB) � 1c: Mutable (config)

Layer 2: Vector Index

Semantic search � References Layer 1 via conversationRef

Layer 3: Facts Store

LLM-extracted facts � Belief Revision � 60-90% token savings

Layer 4: Convenience API

cortex.memory.* � Primary developer interface

Each layer serves a specific purpose
Tip

Most developers use Layer 4 (cortex.memory.*) - it handles Layers 1, 2, and 3 automatically.

Benefits of layered architecture:

  • Retention on Vector doesn't lose ACID source
  • Facts provide 60-90% token savings for infinite context
  • Can always retrieve full context from conversation source
  • Fast search + complete audit trail

References Over Duplication

Data is linked, not duplicated:

// Vector memory references ACID conversation
{
id: 'mem-123',
content: 'User password is Blue',
conversationRef: {
conversationId: 'conv-456',
messageIds: ['msg-001'], // ← Link to source
}
}

// Can always get full context
const conversation = await cortex.conversations.get('conv-456');
const originalMessage = conversation.messages.find(m => m.id === 'msg-001');

Universal Filters

Key Design Principle: The same filters work across ALL operations.

// Define filters once
const filters = {
userId: "user-123",
tags: ["preferences"],
minImportance: 50,
createdAfter: new Date("2025-10-01"),
};

// Use everywhere
await cortex.memory.search(memorySpaceId, query, filters);
await cortex.memory.count(memorySpaceId, filters);
await cortex.memory.list(memorySpaceId, filters);
await cortex.memory.updateMany(memorySpaceId, filters, updates);
await cortex.memory.deleteMany(memorySpaceId, filters);
await cortex.memory.export(memorySpaceId, filters);

Supported Filters: userId, tags, importance, createdBefore/After, accessCount, version, source.type, and any metadata.* field.

Importance Scale (0-100)

Granular importance for filtering and retention:

RangeLevelExamples
90-100CriticalPasswords, security credentials
70-89HighUser preferences, decisions
40-69MediumConversation context (default: 50)
10-39LowCasual observations
0-9TrivialDebug logs

Automatic Versioning

Updates don't overwrite - they create new versions:

// v1
await cortex.memory.store('user-123-personal', { content: 'Password is Blue', ... });

// v2 (v1 preserved in history)
await cortex.memory.update('user-123-personal', memoryId, { content: 'Password is Red' });

// Access history
const memory = await cortex.memory.get('user-123-personal', memoryId);
console.log(memory.version); // 2
console.log(memory.previousVersions[0].content); // "Password is Blue"

Retention: Default 10 versions (configurable per agent)

GDPR Cascade Deletion

Tip

Available in SDK: Full cascade deletion is implemented in the open-source SDK. Cloud Mode adds legal guarantees, certificates, and managed graph integration.

One call deletes from ALL stores with userId:

// SDK (Free) & Cloud Mode: One call deletes from ALL stores with userId
await cortex.users.delete("user-123", { cascade: true });

// Automatically deletes from:
// ✅ User profile (immutable store, type='user')
// ✅ Layer 1a (conversations.*) - All conversations with userId
// ✅ Layer 1b (immutable.*) - All records with userId
// ✅ Layer 1c (mutable.*) - All keys with userId
// ✅ Layer 2 (vector.*) - All memories with userId (across ALL memory spaces)
// ✅ Layer 3 (facts.*) - All facts referencing userId
// ✅ Graph (if adapter configured) - All nodes with userId property

See: User Operations API for complete GDPR cascade documentation.

Belief Revision System (v0.24.0+)

Tip

New in v0.24.0: Intelligent fact management that prevents duplicates and maintains knowledge consistency.

When facts are extracted from conversations, the Belief Revision System automatically:

  1. Detects conflicts using slot matching (fast) and semantic matching (accurate)
  2. Resolves conflicts using LLM-based decision making
  3. Takes appropriate action: CREATE, UPDATE, SUPERSEDE, or skip
  4. Logs all changes for audit trails
Belief Revision Flow
New Fact

Incoming fact to process

Slot Match?

Fast matching by subject/predicate

Semantic Match?

Accurate matching by meaning

LLM Decision

UPDATE � SUPERSEDE � NONE

How conflicts are detected and resolved

See: Facts Operations API - Belief Revision


API Conventions

Naming Patterns

  • Operations: Verb-based (create, get, update, delete, search)
  • Namespaces: Plural (conversations, users, contexts, agents)
  • Options: *Options suffix (SearchOptions, DeleteOptions)
  • Results: *Result suffix (RememberResult, DeleteResult)
  • Filters: *Filters suffix (UniversalFilters, UserFilters)

Return Values

  • Single item: Entity | null
  • Multiple items: Entity[]
  • With pagination: { items: Entity[], total: number, hasMore: boolean }
  • Operations: *Result interface with details

Async/Await

All Cortex operations are async:

// ✅ Always use await
const memory = await cortex.memory.get("agent-1", memoryId);

// ❌ Don't forget await
const memory = cortex.memory.get("agent-1", memoryId); // Returns Promise!

Error Handling

All errors are catchable with type information:

try {
await cortex.memory.store("agent-1", data);
} catch (error) {
if (error instanceof CortexError) {
console.log(`Error: ${error.code}`);
// Type-safe error handling
}
}

Direct Mode vs Cloud Mode

Direct Mode (Free, Open Source)

What you get:

Full Storage APIs

All layers available

All Memory Operations

Complete memory management

Universal Filters

Same filters work everywhere

Automatic Versioning

Track all changes

Complete Flexibility

Full control over your setup

What you provide:

  • Your Convex instance
  • Your embeddings (OpenAI, Cohere, local)
  • Agent execution infrastructure
  • Pub/sub for A2A (optional)

Cloud Mode (Managed, Premium)

Additional features:

GDPR Cascade

One-click deletion across all stores

Auto-Embeddings

No API keys needed

Managed Pub/Sub

Real-time A2A without infrastructure

Smart Store AI

Automatic update detection

Analytics Dashboard

Usage insights

Governance Policies

Automatic retention rules


Getting Help

Documentation

Practical Guides

Community

  • GitHub Discussions - Ask questions, share patterns

Found a Bug?

  1. Check Error Handling for known issues
  2. Search GitHub Issues for existing reports
  3. Open new issue with minimal reproduction

Next Steps

New to Cortex? → Start with Memory Operations - the main API

Building multi-agent systems? → Read Context Operations and A2A Communication

Need GDPR compliance? → Check User Operations for cascade deletion

Working with facts and knowledge? → Explore Facts Operations and the Belief Revision System

Want code examples? → See Patterns & Practices and Cheat Sheet



Questions? Ask in GitHub Discussions.