Skip to content
hurttlockerPublic

About

Import-first, zero-dependency, observable memory layer for AI agents

Resources

Contributing

Stars

30 stars

Watchers

0 watching

Forks

Repository files navigation

Cortex

Cortex

The open memory primitive for AI agents — the one that proposes, never writes.

CI Release License: MIT


Two kinds of memory, one binary. Directives — explicit rules you author ("always X", "never Y"), pinned above every retrieval, never decay. The ledger — implicit outcomes your agents record as they work. Facts, hybrid search, and Ebbinghaus decay sit underneath both.

And the part every other agent-memory tool gets wrong: cortex never writes its own memory. It watches the ledger, notices a fix pattern recurring, and proposes a rule — you accept or dismiss. A bad proposal costs a dismiss, never a bad write.

No API keys. No Docker. No config. A single 12MB binary and a SQLite file.

Install (pick one)

# Homebrew (macOS)
brew install hurttlocker/cortex/cortex-memory

# MCP server (any platform — no install needed)
npx @cortex-ai/mcp

# Binary (macOS Apple Silicon)
curl -sSL https://github.com/hurttlocker/cortex/releases/latest/download/cortex-darwin-arm64.tar.gz | tar xz
sudo mv cortex /usr/local/bin/

# Go
go install github.com/hurttlocker/cortex/cmd/cortex@latest
Other platforms
Platform Command
macOS Intel curl -sSL .../cortex-darwin-amd64.tar.gz | tar xz && sudo mv cortex /usr/local/bin/
Linux x86_64 curl -sSL .../cortex-linux-amd64.tar.gz | tar xz && sudo mv cortex /usr/local/bin/
Linux ARM64 curl -sSL .../cortex-linux-arm64.tar.gz | tar xz && sudo mv cortex /usr/local/bin/
Windows Download from Releases

Replace ... with https://github.com/hurttlocker/cortex/releases/latest/download

Quick start (60 seconds)

# 1. Setup (auto-detects your LLM keys + Ollama)
cortex init

# 2. Import your files
cortex import ~/notes/ --recursive --extract

# 3. Search your knowledge
cortex search "what did I decide about the API design"

# 4. Connect to your agent (Claude Code, Codex CLI, Cursor, Windsurf, etc.)
claude mcp add cortex -- cortex mcp

That's it. Your agent now has persistent memory with 21 MCP tools.

No LLM keys? Cortex works fully offline — import, search (BM25), and MCP all work without any API keys. Add an LLM provider later for enrichment, classification, and semantic search.

The governance loop (v2)

# Author a rule your agent can never lose to retrieval noise
cortex directive add "Never commit secrets to any repository"

# Agents record outcomes as they work (CLI or the cortex_ledger_record MCP tool)
cortex ledger record --summary "fixed the auth gate" --outcome success --pattern "auth-gate-missing"

# cortex notices patterns and proposes; only YOU write
cortex propose scan       # "auth-gate-missing — seen 3x in 14d"
cortex propose accept 1   # NOW it's a directive, pinned in every retrieval

The scan path contains no code that writes a directive — that's tested, not promised. Proposals carry their evidence (the ledger rows that triggered them), so you always see why before you accept.

Verify your setup

cortex doctor    # Checks DB, config, embeddings, connectors, version

OpenClaw users (canonical setup path)

Use one setup flow from zero → plugin enabled → health verified:

The canonical flow includes actionable openclaw cortex setup checks for binary drift, config placement, doctor next steps, and HNSW rebuild health.

Next steps

# Connect external sources — GitHub, Gmail, Slack, Calendar, Drive
cortex connect add github --config '{"token": "ghp_...", "repos": ["owner/repo"]}'
cortex connect sync --all --extract   # Import + extract facts in one step

# Add semantic search (requires Ollama)
ollama pull nomic-embed-text
cortex embed ollama/nomic-embed-text --status
cortex embed ollama/nomic-embed-text --watch --interval 30m
cortex search "API design" --mode hybrid   # BM25 + semantic

# Explore your knowledge graph
cortex graph --serve --port 8090      # Opens interactive 2D explorer

# Check health of your knowledge base
cortex stale --days 30                # What's fading?
cortex conflicts                      # Any contradictions?
cortex stats                          # Memory/fact/source counts

# Multi-agent? Scope facts by agent
cortex import notes.md --agent mister --extract
cortex search "config" --agent mister

See docs/connectors.md for full connector setup.

Shell completions

# Bash
cortex completion bash > /etc/bash_completion.d/cortex

# Zsh (add to your .zshrc)
cortex completion zsh > "${fpath[1]}/_cortex"

# Fish
cortex completion fish > ~/.config/fish/completions/cortex.fish

Why Cortex

Human-gated memory. Directives are yours; the ledger is your agents'; the proposer bridges them only through your explicit accept. Memory you can trust because a human gated every rule in it.

Memory that fades like yours. Facts decay over time using Ebbinghaus curves — identity facts last years, temporal facts fade in days. When you search, stale facts rank lower. Reinforce what matters; let the rest go.

Import-first. Start with the files you already have — MEMORY.md, JSON configs, YAML, CSV, conversation logs. Every other tool says "start fresh." Cortex says "bring everything."

Zero dependencies. No API keys required, no Docker, no database server. A single Go binary + SQLite. LLM enrichment is optional — dramatically improves fact quality when enabled, but rules work fine offline.

Observable. cortex stats shows what your agent knows. cortex stale shows what's fading. cortex conflicts finds contradictions. cortex alerts notifies you proactively.

How it works

Your files ──→ Import ──→ Fact extraction ──→ SQLite + FTS5
                                                   │
                              ┌─────────┬──────────┼──────────┐
                              ▼         ▼          ▼          ▼
                           Search    Observe    Graph      MCP Server
                          (hybrid)  (stats,    (2D         (21 tools,
                                    stale,     explorer)    any agent)
                                    conflicts)

Directives (yours) ──────→ pinned above every search result, never decay
Session ledger (agents') ─→ propose scan ──→ YOU accept/dismiss ──→ directive

Search: BM25 keyword + optional semantic embeddings, fused with Weighted Score Fusion (default hybrid) or Reciprocal Rank Fusion (--mode rrf). Facts: Extracted as subject-predicate-object triples with type-aware decay rates. Graph: Interactive 2D knowledge graph explorer with cluster visualization. Connect: Sync from GitHub, Gmail, Calendar, Drive, Slack, Discord, Telegram, Notion — extract facts on import.

Feature highlights

Feature What it does
Hybrid + RRF search BM25 + semantic with weighted score fusion (hybrid) or rank fusion (--mode rrf).
Ebbinghaus decay 7 decay rates by fact type. Identity lasts 693 days, temporal fades in 7.
Fact extraction Rule-based + LLM enrichment (v0.9.0). Finds entities, decisions, preferences, relationships. Auto-classifies facts.
Conflict detection Same subject + predicate, different object → alert. Real-time on ingest.
Import filters --ext md,txt / --exclude-ext log,tmp — control exactly what gets imported.
Auto-infer --extract on import runs fact extraction + edge inference automatically.
Knowledge graph cortex graph --serve — interactive 2D cluster explorer in your browser.
Recursive reasoning cortex reason --recursive — LLM loops: search → reason → search deeper.
Connectors GitHub, Gmail, Calendar, Drive, Slack, Discord, Telegram, Notion. Import + extract facts in one step.
Provenance Every fact tracks source file, line, section, timestamp. Full audit trail.
Export JSON, Markdown, CSV. Your memory is yours. No lock-in.
MCP server cortex mcp — stdio or HTTP. Works with Claude Code, Codex CLI, Cursor, any MCP client.

vs. alternatives

Cortex Mem0 Zep Letta
Import existing files ✅ ❌ ❌ ❌
Works without LLM ✅ ❌ ❌ ❌
Confidence decay ✅ ❌ ❌ ❌
Conflict detection ✅ ❌ ❌ ❌
Knowledge graph explorer ✅ ❌ ❌ ❌
External connectors ✅ ❌ ❌ ❌
Recursive reasoning ✅ ❌ ❌ ❌
Self-hosted (single binary) ✅ 🟡 🟡 🟡
Works offline ✅ ❌ ❌ ❌
Export / portability ✅ ❌ ❌ ❌

LLM-powered features (v0.9.0)

LLM features are optional — Cortex works fully offline with rule-based extraction. When you add an API key, facts get smarter automatically.

Without LLM (default for new users)

Rule-based extraction handles structured text well (key-value pairs, dates, emails, locations). The governor caps extraction at 10 facts per memory with minimum quality thresholds, preventing garbage accumulation.

cortex import ~/notes/ --recursive --extract           # Rules only — works offline
cortex import ~/notes/ --recursive --extract --no-enrich  # Explicit: skip LLM even if key exists

With LLM (recommended)

Set one or both API keys for dramatically better fact quality:

export OPENROUTER_API_KEY="sk-or-..."    # For enrichment + classification
export GEMINI_API_KEY="AI..."             # For query expansion (free tier)
Feature Model Cost What it does
Enrichment Grok 4.1 Fast (via OpenRouter) ~$0.01/file Finds decisions, relationships, implicit facts rules miss
Classification DeepSeek V3.2 (via OpenRouter) ~$0.50/20K facts Reclassifies generic kv facts → decision, config, state, etc.
Query expansion Gemini 2.0 Flash Free Expands vague queries into better search terms
Conflict resolution Any OpenRouter model ~$0.01/batch Auto-resolves contradictory facts
# Import with enrichment (default when OPENROUTER_API_KEY is set)
cortex import ~/notes/ --recursive --extract

# Bulk reclassify existing kv facts (one-time sweep, ~55 min for 20K facts)
cortex classify --limit 25000 --batch-size 20 --concurrency 5

# Expand search queries through LLM
cortex search "what was that trading thing" --expand

# Auto-resolve conflicts
cortex conflicts --resolve llm

Cost: <$1/month at typical usage. Full corpus reimport: ~$2-3.

Upgrading from older versions

⚠️ Critical fix in v0.9.0: Versions prior to v0.9.0 had a bug where cortex import --extract would re-extract facts on all recent memories — not just newly imported ones. If you've been running periodic syncs, your database likely has duplicate facts (we saw 74K facts from 1.6K memories drop to 2.5K after fixing). A clean reimport is strongly recommended.

# Step 1: Clean reimport (wipes DB, re-imports from your files)
cortex reimport ~/your-notes/ --recursive --extract --no-enrich --force

# Step 2 (optional): Add LLM enrichment for the core files you care about most
export OPENROUTER_API_KEY="sk-or-..."
cortex import ~/your-notes/MEMORY.md --extract    # Full enrichment on key files

# Step 3 (optional): Reclassify generic kv facts with LLM
cortex classify --limit 50000 --batch-size 20 --concurrency 5

What changed: Import now tracks exactly which memories were newly created and only runs extraction/enrichment/classification on those — not the 1000 most recent. Repeated syncs no longer accumulate duplicate facts.

Expected fact counts after reimport:

  • ~1-3 facts per memory (rule-only, no LLM)
  • ~3-8 facts per memory (with LLM enrichment)
  • Governor cap: 10 facts per memory maximum

If your database has >10 facts per memory on average, you have the duplication bug. Reimport to fix it.

Choosing models

We benchmarked 6 models across enrichment and classification. Results:

Task Best Model Why
Enrichment Grok 4.1 Fast Only model that reliably finds new facts (+26 across 3 test files vs ≤9 for others)
Classification DeepSeek V3.2 76% reclassification, 0 errors, $0.50/20K facts. Batch-size 20 optimal.
Query expansion Gemini 2.0 Flash Free tier, 2.3x faster than alternatives, adequate quality for search

Models that didn't work: MiniMax M2.5 (80% error rate), Codex Mini (8% success), Gemini thinking models (consume JSON in reasoning phase).

CLI reference

cortex import <path> [--recursive] [--extract]  # Import files or directories
  [--no-enrich] [--no-classify]                 #   Skip LLM enrichment/classification
  [--ext md,txt] [--exclude-ext log,tmp]        #   Filter by file extension
cortex search <query> [--mode hybrid|bm25|semantic|rrf]  # Search memories
  [--expand] [--llm google/gemini-2.0-flash]    #   LLM query expansion
cortex classify [--limit N] [--batch-size 20]   # Reclassify kv facts with LLM
  [--concurrency 5] [--dry-run]                 #   Parallel batches, preview mode
cortex conflicts [--resolve llm] [--dry-run]    # Detect/resolve contradictions
cortex summarize [--cluster N]                  # Consolidate fact clusters
cortex reason <query> [--recursive]             # LLM reasoning over memory
cortex graph [--serve --port 8090]              # Knowledge graph explorer
cortex stats                                    # What your agent knows
cortex stale [--days 30]                        # Fading facts
cortex reinforce <fact-id>                      # Reset decay timer
cortex connect add <provider> --config '{...}'  # Add external connector
cortex connect sync --all [--extract]           # Sync + extract facts
cortex connect status                           # Connector health
cortex export [--format json|markdown|csv]      # Take your memory anywhere
cortex mcp [--embed ollama/nomic-embed-text]    # MCP server for agents
cortex cleanup --prune-temporal-noise           # Remove "Current time" fact pollution
cortex embed <provider/model>                   # Generate/watch embeddings
cortex embed --status                           # Coverage + remaining memories

Semantic search (optional)

BM25 keyword search works out of the box. For semantic search, add an embedding model:

ollama pull nomic-embed-text
cortex embed ollama/nomic-embed-text --batch-size 10
cortex embed --status
cortex search "conceptually related query" --mode hybrid --embed ollama/nomic-embed-text
cortex search "conceptually related query" --mode rrf --embed ollama/nomic-embed-text

Once an embed provider is configured, cortex import ... will automatically start a detached background embed worker if one is not already running. New memories stay import-fast and are embedded asynchronously.

Supports Ollama (free/local), OpenAI, DeepSeek, OpenRouter, or any OpenAI-compatible endpoint.

Architecture

  • Language: Go 1.24+ — single binary, no runtime dependencies
  • Storage: SQLite + FTS5 (pure Go, zero CGO) — ~/.cortex/cortex.db
  • Search: BM25 keyword + optional HNSW ANN for semantic, plus hybrid (WSF) and RRF fusion modes
  • Extraction: Rule-based pipeline + optional LLM assist, auto-infer on import
  • Graph: Interactive 2D knowledge graph explorer with cluster visualization
  • Connectors: GitHub, Gmail, Calendar, Drive, Slack, Discord, Telegram, Notion — with fact extraction
  • MCP: stdio + HTTP/SSE transport — 17 tools, 4 resources
  • Tests: 1,081 across 15 packages

Documentation

Doc What's in it
Getting started Zero to searching in 5 minutes
Deep dive Full technical documentation
Architecture Package structure and data flow
Connectors guide All 8 provider setup guides
Migration guide Upgrading from any version to v1.0
Release notes Changelog for each version
Full feature reference Benchmarks, presets, chunking details
Local LLM guide Hardware recommendations for local reasoning
Ops runbook Database growth monitoring
Contributing How to contribute
Brand assets Logo and visual identity

cortex and o8

cortex is the open-source memory core. If you want governed multi-agent approvals, audit, and an operator surface built on the same philosophy, that's o8 — the closed superset. Community PRs here are reviewed publicly through o8's own approval surface; the repo is also the demo.

License

MIT — LICENSE. Issues and PRs welcome; response not guaranteed. No roadmap promises.


Built by hurttlocker

About

Import-first, zero-dependency, observable memory layer for AI agents

Resources

Contributing

Stars

30 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages