Skip to main content

Cheat Sheet

Quick reference for the most common Cortex operations. Copy-paste ready!


Setup

Import

import { Cortex } from "@cortexmemory/sdk";
import type { MemoryEntry, UserProfile, Context } from "@cortexmemory/sdk";

Initialize

const cortex = new Cortex({
convexUrl: process.env.CONVEX_URL,
});

Core Namespaces

cortex.memory.*          // Layer 4: Memory convenience API (primary interface)
cortex.memorySpaces.* // Memory space management (Hive/Collaboration)
cortex.conversations.* // Layer 1a: ACID conversations (memorySpace-scoped)
cortex.immutable.* // Layer 1b: Shared versioned data (NO memorySpace)
cortex.mutable.* // Layer 1c: Shared live data (NO memorySpace)
cortex.vector.* // Layer 2: Vector index (memorySpace-scoped)
cortex.facts.* // Layer 3: Facts store (memorySpace-scoped, LLM extraction)
cortex.users.* // User profiles + GDPR (shared across all spaces)
cortex.contexts.* // Workflow coordination (cross-space support)
cortex.a2a.* // Inter-agent messaging
cortex.governance.* // Retention policies & compliance
cortex.sessions.* // Session lifecycle management
cortex.agents.* // Agent metadata registry (optional analytics/discovery)

Memory Operations

The most commonly used API - handles Layers 1-3 automatically.

// Store conversation (ACID + Vector)
await cortex.memory.remember({
memorySpaceId,
participantId, // Optional: Hive Mode tracking
conversationId,
userMessage,
agentResponse,
userId,
userName,
});

// Store system memory
await cortex.memories.store(memorySpaceId, {
content: "System announcement",
contentType: "raw",
embedding: await embed("System announcement"),
source: { type: "system" },
metadata: { importance: 50, tags: [] },
});

// Search
await cortex.memory.search(memorySpaceId, query, {
embedding,
userId,
minImportance,
limit,
participantId, // Optional: Filter by participant
});

// Get
await cortex.memory.get(memorySpaceId, memoryId, { includeConversation: true });

// Update
await cortex.memory.update(memorySpaceId, memoryId, { content, metadata });

// Delete (preserves ACID)
await cortex.memory.delete(memorySpaceId, memoryId);

// Count
await cortex.memory.count(memorySpaceId, filters);

// List
await cortex.memory.list(memorySpaceId, { limit, offset, sortBy });

// Export
await cortex.memory.export(memorySpaceId, { userId, format: "json" });

User Operations

// Create/update
await cortex.users.update(userId, {
displayName: 'Alex Johnson',
email: 'alex@example.com',
preferences: { theme: 'dark' },
});

// Get
await cortex.users.get(userId);

// Delete (Cloud Mode - cascade across all stores)
await cortex.users.delete(userId, { cascade: true });

// Search
await cortex.users.search({ displayName: 'Alex' });

// Count
await cortex.users.count({ createdAfter: new Date("2025-01-01") });

Context Operations

// Create workflow
const ctx = await cortex.contexts.create({
purpose,
memorySpaceId, // Which memory space
userId,
parentId, // Cross-space parent allowed
data,
});

// Get with chain (supports cross-space traversal)
await cortex.contexts.get(contextId, {
includeChain: true,
});

// Update status
await cortex.contexts.update(contextId, { status: "completed", data });

// Delete with children
await cortex.contexts.delete(contextId, { cascadeChildren: true });

// Search
await cortex.contexts.search({
memorySpaceId,
status: "active",
userId: "user-456",
});

A2A Communication

// Send message
await cortex.a2a.send({ from, to, message, importance, userId, contextId });

// Request-response (requires pub/sub)
const response = await cortex.a2a.request({ from, to, message, timeout });

// Broadcast
await cortex.a2a.broadcast({ from, to: [agent1, agent2, agent3], message });

// Get conversation
await cortex.a2a.getConversation(agent1, agent2, {
since,
minImportance,
tags,
});

Immutable Store

// Store versioned data
await cortex.immutable.store({ type, id, data, userId, metadata });

// Get current version
await cortex.immutable.get(type, id);

// Get specific version
await cortex.immutable.getVersion(type, id, version);

// Get history
await cortex.immutable.getHistory(type, id);

// Purge
await cortex.immutable.purge(type, id);

Mutable Store

// Set value
await cortex.mutable.set(namespace, key, value, userId);

// Get value
await cortex.mutable.get(namespace, key);

// Atomic update
await cortex.mutable.update(namespace, key, (current) => current + 1);

// Transaction
await cortex.mutable.transaction([
{ op: 'decrement', namespace: 'inventory', key: 'product-a', amount: 1 },
{ op: 'increment', namespace: 'counters', key: 'sales', amount: 1 },
]);

// Delete
await cortex.mutable.delete(namespace, key);

Sessions

// Create session
const session = await cortex.sessions.create({
userId,
metadata: { deviceType: 'web' },
});

// Get or create
const session = await cortex.sessions.getOrCreate(userId, { deviceType: 'web' });

// Touch (update activity)
await cortex.sessions.touch(sessionId);

// End session
await cortex.sessions.end(sessionId);

// Get active sessions
await cortex.sessions.getActive(userId);

// Expire idle sessions
await cortex.sessions.expireIdle({ idleTimeout: 30 * 60 * 1000 });

Facts

// Store fact
await cortex.facts.store(memorySpaceId, {
fact: "User prefers dark mode",
subject: userId,
predicate: "preference",
object: "dark mode",
confidence: 95,
});

// Search facts
await cortex.facts.search(memorySpaceId, query, { userId });

// Belief revision with conflict resolution
const result = await cortex.facts.revise({
memorySpaceId,
newFacts: [{
fact: "User prefers light mode",
factType: "preference",
subject: userId,
confidence: 90,
}],
});

// Get fact history
await cortex.facts.getHistory(memorySpaceId, factId);

Universal Filters

Filter Support Varies

Not all filters are supported by all operations. Check the specific API documentation for each namespace to see which filters are available.

Common filters that work across memory operations:

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.export(memorySpaceId, filters);

Supported Filters:

FilterTypeDescriptionSupported Operations
userIdstringFilter by usermemory., contexts., facts.*
tagsstring[]Filter by tags (AND)memory.*
minImportancenumberMinimum importance (0-100)memory., facts.
maxImportancenumberMaximum importance (0-100)memory., facts.
createdBeforeDateCreated before datememory., contexts.
createdAfterDateCreated after datememory., contexts.
accessCountnumberMinimum access countmemory.*
versionnumberSpecific versionimmutable.*
source.typestringSource type filtermemory.*
metadata.*anyAny metadata fieldmemory., contexts.

Most Used Operations

Quick copy-paste for the 5 most common operations:

// 1. Remember conversation
await cortex.memory.remember({
memorySpaceId,
participantId, // Optional: Hive Mode tracking
conversationId,
userMessage,
agentResponse,
userId,
userName,
});

// 2. Search memories (infinite context pattern)
await cortex.memory.search(memorySpaceId, query, { embedding, filters });

// 3. Update user profile
await cortex.users.update(userId, { data });

// 4. Send inter-space message (Collaboration Mode)
await cortex.a2a.send({ from, to, message });

// 5. Create context
await cortex.contexts.create({ purpose, memorySpaceId, userId });

API Conventions

Naming Patterns

PatternExampleDescription
Operationscreate, get, update, delete, searchVerb-based
Namespacesconversations, users, contextsPlural nouns
OptionsSearchOptions, DeleteOptions*Options suffix
ResultsRememberResult, DeleteResult*Result suffix
FiltersUniversalFilters, UserFilters*Filters suffix

Return Values

PatternTypeExample
Single itemEntity | nullcortex.users.get()
Multiple itemsEntity[]cortex.users.search()
Paginated{ items, total, hasMore }cortex.memory.list()
Operations*Resultcortex.memory.remember()

Async/Await

// 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

import { MemoryValidationError, CircuitOpenError } from "@cortexmemory/sdk";

try {
await cortex.memory.store("agent-1", data);
} catch (error) {
if (error instanceof MemoryValidationError) {
console.error(`Validation error: ${error.message}`);
} else if (error instanceof CircuitOpenError) {
console.error(`Service temporarily unavailable`);
}
}