-
Notifications
You must be signed in to change notification settings - Fork 59
Cortex V2 Overview
Cortex V2 is Drift's intelligent memory system β a living knowledge base that learns from your codebase and interactions to provide contextual guidance during development.
# Run the interactive setup wizard (recommended)
drift memory setup
# Or initialize manually
drift memory init
# Add institutional knowledge
drift memory add tribal "Always use bcrypt for passwords" --importance critical
# Get context for a task
drift memory why "authentication"
# Check system health
drift memory healthCortex V2 replaces static AGENTS.md files with a dynamic memory system that:
- Learns continuously β Extracts knowledge from corrections and feedback
- Decays naturally β Unused memories lose confidence over time
- Retrieves intelligently β Returns context based on intent and focus
- Validates automatically β Identifies stale or conflicting memories
- Compresses efficiently β Minimizes token usage with hierarchical compression
- Detects contradictions β Identifies and resolves conflicting information
- Tracks causality β Understands "why" decisions were made
| Static AGENTS.md | Cortex Memory |
|---|---|
| Written once, forgotten | Learns continuously from corrections |
| Gets stale immediately | Confidence decays on unused memories |
| Manual updates required | Self-correcting through feedback |
| One-size-fits-all dump | Intent-aware retrieval |
| No way to know if accurate | Validation and health monitoring |
| Clutters your repo | Stored in .drift/memory/
|
# 1. Run the setup wizard
drift memory setup
# 2. Or add knowledge manually
drift memory add tribal "Always use bcrypt for passwords" --importance critical
drift memory add tribal "Services should not call controllers directly" --topic Architecture
# 3. Delete your AGENTS.md
rm AGENTS.md # π
# 4. AI now gets context dynamically
drift memory why "authentication"Cortex V2 supports 23 memory types across three categories:
| Type | Icon | Half-Life | Purpose |
|---|---|---|---|
core |
π | β (never) | Project identity, preferences, critical constraints |
tribal |
365 days | Institutional knowledge, gotchas, warnings | |
procedural |
π | 180 days | How-to knowledge, step-by-step procedures |
semantic |
π‘ | 90 days | Consolidated knowledge from episodic memories |
episodic |
π | 7 days | Raw interaction records (auto-consolidated) |
decision |
βοΈ | 180 days | Standalone decisions with context |
insight |
π | 90 days | Learned observations and discoveries |
reference |
π | 60 days | External references and documentation |
preference |
β | 120 days | User/team preferences |
| Type | Icon | Half-Life | Purpose |
|---|---|---|---|
pattern_rationale |
π― | 180 days | Why patterns exist in the codebase |
constraint_override |
β | 90 days | Approved exceptions to constraints |
decision_context |
π | 180 days | Human context for architectural decisions |
code_smell |
π« | 90 days | Anti-patterns to avoid |
| Type | Icon | Half-Life | Purpose |
|---|---|---|---|
agent_spawn |
π€ | 365 days | Reusable agent configurations |
entity |
π¦ | 180 days | Projects, products, teams, systems |
goal |
π― | 90 days | Objectives with progress tracking |
feedback |
π | 120 days | Corrections and learning signals |
workflow |
π | 180 days | Step-by-step processes |
conversation |
π¬ | 30 days | Summarized past discussions |
incident |
π¨ | 365 days | Postmortems and lessons learned |
meeting |
π | 60 days | Meeting notes and action items |
skill |
π§ | 180 days | Knowledge domains and proficiency |
environment |
π | 90 days | Environment configurations |
Confidence decays exponentially based on age:
effective_confidence = base_confidence Γ 2^(-age_days / half_life)
Example: A tribal memory with 100% confidence after 365 days has ~50% effective confidence.
Usage boosts confidence β frequently accessed memories decay slower.
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β CORTEX V2 β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β βββββββββββββββ βββββββββββββββ βββββββββββββββ βββββββββββββββ β
β β Storage β β Embeddings β β Retrieval β βConsolidationβ β
β β (SQLite) β β (Local/API) β β Engine β β Engine β β
β βββββββββββββββ βββββββββββββββ βββββββββββββββ βββββββββββββββ β
β βββββββββββββββ βββββββββββββββ βββββββββββββββ βββββββββββββββ β
β β Validation β β Decay β βContradictionβ β Causal β β
β β Engine β β Calculator β β Detector β β Graph β β
β βββββββββββββββ βββββββββββββββ βββββββββββββββ βββββββββββββββ β
β βββββββββββββββ βββββββββββββββ βββββββββββββββ βββββββββββββββ β
β β Learning β β Prediction β β Generation β β Session β β
β βOrchestrator β β Engine β βOrchestrator β β Manager β β
β βββββββββββββββ βββββββββββββββ βββββββββββββββ βββββββββββββββ β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β SQLite Storage Backend β
β .drift/memory/cortex.db β
β β
β Tables: memories, causal_links, embeddings, sessions, β
β predictions, validation_history, consolidation_log β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
| Component | Responsibility |
|---|---|
| Storage | SQLite-based persistence with sqlite-vec for vector search |
| Embeddings | Generates embeddings (local Transformers.js, OpenAI, or Ollama) |
| Retrieval Engine | Intent-aware memory retrieval with compression and ranking |
| Consolidation Engine | Merges episodic memories into semantic knowledge |
| Validation Engine | Identifies stale, conflicting, or invalid memories |
| Decay Calculator | Computes effective confidence based on age and usage |
| Contradiction Detector | Finds and resolves conflicting memories |
| Causal Graph | Tracks relationships between memories (derived_from, supersedes, etc.) |
| Learning Orchestrator | Extracts knowledge from corrections and feedback |
| Prediction Engine | Pre-fetches likely-needed memories |
| Generation Orchestrator | Provides context for code generation with provenance |
| Session Manager | Tracks what's been sent to avoid duplication |
The easiest way to initialize Cortex:
drift memory setupThe wizard walks you through 7 optional sections:
- Core Identity β Project name, tech stack, preferences
- Tribal Knowledge β Gotchas, warnings, institutional knowledge
- Workflows β Deploy, code review, release processes
- Agent Spawns β Reusable agent configurations
- Entities β Projects, teams, services
- Skills β Knowledge domains and proficiency
- Environments β Production, staging, dev configs
All sections are optional β skip any with 'n'.
Memories are linked with causal relationships:
βββββββββββββββββββ derived_from βββββββββββββββββββ
β Security Audit β βββββββββββββββββββΆ β Use bcrypt for β
β (2024-01) β β passwords β
βββββββββββββββββββ βββββββββββββββββββ
β
β supersedes
βΌ
βββββββββββββββββββ
β Use MD5 for β
β passwords β
βββββββββββββββββββ
Relationship types:
-
derived_fromβ Memory was created based on another -
supersedesβ Memory replaces an older one -
supportsβ Memory provides evidence for another -
contradictsβ Memory conflicts with another -
ownsβ Entity owns Entity/Goal/Workflow -
affectsβ Incident affects Entity/Environment -
blocksβ Incident blocks Goal -
requiresβ Workflow requires Skill/Environment -
learned_fromβ Tribal learned from Incident
Retrieval adapts based on what you're trying to do:
| Intent | Prioritizes |
|---|---|
add_feature |
Pattern rationales, procedural knowledge, workflows |
fix_bug |
Code smells, tribal knowledge, error patterns, incidents |
refactor |
Structural patterns, coupling analysis |
security_audit |
Security patterns, constraint overrides |
understand_code |
Decision context, pattern rationales |
add_test |
Test patterns, coverage requirements |
Cortex automatically detects conflicting memories:
interface ContradictionResult {
type: ContradictionType; // direct, temporal, scope, confidence
existingMemoryId: string;
similarity: number;
explanation: string;
}When contradictions are found:
- Reduces confidence of older memory
- Propagates confidence changes through relationship graph
- Alerts you to resolve conflicts
Cortex learns from corrections automatically:
# AI suggests using MD5
# You correct it
drift memory learn "Use bcrypt instead of MD5 for password hashing"
# Cortex creates:
# 1. New tribal memory: "Use bcrypt, not MD5"
# 2. Code smell memory: "MD5 is insecure"
# 3. Causal link: correction β new memoriesHierarchical compression minimizes token usage:
| Level | Description | Tokens |
|---|---|---|
| 0 | IDs only | ~50 |
| 1 | One-line summaries | ~200 |
| 2 | With examples | ~500 |
| 3 | Full detail | ~1000+ |
Session-based deduplication prevents sending the same memory twice.
Episodic memories (7-day half-life) are automatically consolidated:
βββββββββββββββββββ βββββββββββββββββββ βββββββββββββββββββ
β Episodic: Fixed β β Episodic: Fixed β β Episodic: Fixed β
β auth bug #123 β β auth bug #456 β β auth bug #789 β
ββββββββββ¬βββββββββ ββββββββββ¬βββββββββ ββββββββββ¬βββββββββ
β β β
βββββββββββββββββββββββββΌββββββββββββββββββββββββ
β
βΌ consolidation
βββββββββββββββββββββββββββ
β Semantic: Auth bugs β
β often caused by token β
β validation issues β
βββββββββββββββββββββββββββ
# Setup
drift memory setup # Interactive wizard (recommended)
drift memory init # Initialize memory system
# Add memories
drift memory add tribal "..." --importance critical
drift memory add procedural "Deploy: 1) Test 2) Build 3) Push"
# Universal memory types
drift memory agent-spawn add # Add agent configuration
drift memory workflow add # Add workflow
drift memory entity add # Add entity
drift memory skill add # Add skill
drift memory environment add # Add environment
drift memory goal add # Add goal
drift memory incident add # Add incident
drift memory meeting add # Add meeting notes
drift memory conversation add # Add conversation summary
# Query
drift memory list
drift memory search "authentication"
drift memory why "user registration" --intent add_feature
# Feedback
drift memory feedback <id> confirm
drift memory feedback <id> reject --details "Outdated"
# Maintenance
drift memory validate --scope stale
drift memory consolidate
drift memory health
# Export/Import
drift memory export backup.json
drift memory import backup.jsonCortex V2 exposes 25 MCP tools for AI agents:
| Tool | Description |
|---|---|
drift_memory_status |
Memory system health and statistics |
drift_memory_add |
Add new memory with causal inference |
drift_memory_search |
Search memories by text/embedding |
drift_memory_get |
Get memory by ID |
drift_memory_validate |
Validate memory integrity |
drift_memory_for_context |
Get memories for current context |
drift_memory_learn |
Learn from corrections |
drift_why |
Explain why something is the way it is |
| Tool | Description |
|---|---|
drift_memory_explain |
Comprehensive explanation with causal chain |
drift_memory_feedback |
Record feedback for learning |
drift_memory_health |
Detailed health metrics |
drift_memory_predict |
Predict what context will be needed |
drift_memory_conflicts |
Find conflicting memories |
drift_memory_graph |
Visualize memory relationships |
drift_memory_query |
Rich graph queries (MGQL) |
drift_memory_contradictions |
Detect and resolve contradictions |
| Tool | Description |
|---|---|
drift_agent_spawn |
Create/invoke agent configurations |
drift_goal |
Track objectives with progress |
drift_incident |
Record postmortems |
drift_workflow |
Store step-by-step processes |
drift_entity |
Track projects/teams/systems |
drift_conversation |
Store conversation summaries |
drift_meeting |
Record meeting notes |
drift_skill |
Track knowledge domains |
drift_environment |
Store environment configs |
import { getCortex } from 'driftdetect-cortex';
// Get Cortex instance
const cortex = await getCortex();
// Get context for a task
const context = await cortex.retrieval.retrieve({
intent: 'add_feature',
focus: 'authentication',
maxTokens: 2000,
});
// Learn from a correction
await cortex.learning.learnFromCorrection({
original: 'Use MD5 for hashing',
correction: 'MD5 is insecure. Use bcrypt.',
correctCode: 'const hash = await bcrypt.hash(password, 10);',
context: { activeFile: 'src/auth.ts', intent: 'fix_bug' }
});
// Get "why" explanation
const why = await cortex.why.getWhy({
intent: 'understand_code',
focus: 'authentication',
maxDepth: 3
});
console.log(why.narrative);
// Add a memory
await cortex.storage.add({
type: 'tribal',
summary: 'Always use bcrypt for passwords',
knowledge: { topic: 'Security', severity: 'critical' },
importance: 'high'
});
// Search memories
const results = await cortex.storage.search({
query: 'password hashing',
types: ['tribal', 'pattern_rationale'],
minConfidence: 0.5,
limit: 10
});import { getCortex } from 'driftdetect-cortex';
const cortex = await getCortex({
storage: {
type: 'sqlite',
sqlitePath: '.drift/memory/cortex.db'
},
embeddings: {
type: 'local', // or 'openai', 'ollama', 'hybrid'
model: 'all-MiniLM-L6-v2'
},
consolidation: {
minEpisodes: 3,
similarityThreshold: 0.8
}
});Cortex supports multiple embedding providers:
| Provider | Description | Configuration |
|---|---|---|
local |
Transformers.js (default) | No API key needed |
openai |
OpenAI embeddings | Requires OPENAI_API_KEY
|
ollama |
Local Ollama server | Requires Ollama running |
hybrid |
Local + fallback to OpenAI | Best of both worlds |
# Use local embeddings (default)
drift memory init
# Use OpenAI embeddings
OPENAI_API_KEY=sk-... drift memory init
# Use Ollama
OLLAMA_HOST=http://localhost:11434 drift memory initCheck memory system health:
drift memory healthOutput:
π₯ Memory Health Report
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
π Overall Health
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Score: 85/100 (healthy)
π Statistics
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Total Memories: 47
Avg Confidence: 85%
Low Confidence: 3
Recently Accessed: 12
β οΈ Issues
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β 3 memories have low confidence
β Review and validate these memories
π‘ Recommendations
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β’ Run `drift memory validate` to clean up low-confidence memories
β’ Use `drift memory feedback` to confirm accurate memories
# Run the interactive wizard
drift memory setup
# The wizard guides you through:
# 1. Core identity (project name, tech stack, preferences)
# 2. Tribal knowledge (gotchas, warnings)
# 3. Workflows (deploy, review, release)
# 4. Agent spawns (code reviewer, security auditor)
# 5. Entities (projects, teams, services)
# 6. Skills (knowledge domains)
# 7. Environments (prod, staging, dev)# Get context before starting work
drift memory why "feature area" --intent add_feature
# After code review, learn from feedback
drift memory learn "Always validate input before processing"# Check health
drift memory health
# Validate stale memories
drift memory validate --scope stale
# Consolidate episodic memories
drift memory consolidate
# Export backup
drift memory export backup-$(date +%Y%m%d).json# Show team knowledge
drift memory list --type tribal --importance high
# Show active warnings
drift memory warnings
# Get context for a feature area
drift memory why "authentication"- Memory CLI Reference β Full CLI command reference
- Memory Setup Wizard β Detailed setup guide
- Universal Memory Types β Agent spawns, workflows, entities
- Cortex Learning System β How Cortex learns from corrections
- Cortex Token Efficiency β Compression and deduplication
- Cortex Causal Graphs β Memory relationships and "why" explanations
- Cortex Code Generation β Context for AI code generation
- Cortex Predictive Retrieval β Anticipating memory needs
- MCP Tools Reference β All MCP memory tools
- Cortex V2 Overview
- Memory Setup Wizard
- Memory CLI
- Universal Memory Types
- Learning System
- Token Efficiency
- Causal Graphs
- Code Generation
- Predictive Retrieval
- Architecture
- Call Graph Analysis
- Impact Analysis
- Security Analysis
- Data Boundaries
- Test Topology
- Coupling Analysis
- Error Handling Analysis
- Wrappers Detection
- Environment Variables
- Constants Analysis
- Styling DNA
- Constraints
- Contracts
- Decision Mining
- Speculative Execution
- Watch Mode
- Trends Analysis
- Projects Management
- Package Context
- Monorepo Support
- Reports & Export
- Dashboard
- 10 Languages
- 21 Frameworks
- 16 ORMs
- 400+ Detectors
- 50+ MCP Tools
- 60+ CLI Commands
- 23 Memory Types