Skip to content

somarakis/Cortex

Repository files navigation

Cortex

License: MIT Node.js >= 18 GitHub stars

A cognitive layer for Claude Code — inspired by how brains actually work.

Cortex is an open-source Claude Code plugin that observes your tool usage, learns your patterns, routes prompts to the right capabilities, preserves memory across sessions, and consolidates what you learned before you leave. It turns Claude Code from a stateless tool into a system that gets better the more you use it.


Installation

npx @cortex-cc/cli init

This will:

  1. Create ~/.cortex/ with directory structure (registry, learning, sessions, hooks, mcp-server, domain-packs)
  2. Install 3 starter hooks (session start, tool observation, prompt routing) — the full system uses 8
  3. Set up a 4-tool MCP server (digest, search, lookup, status) — zero dependencies, raw JSON-RPC
  4. Compile a starter capability registry (5 entries — grows as you add your own)
  5. Back up your existing settings.json before modifying it (non-destructive, appends only)

Options:

npx @cortex-cc/cli init --dry-run          # Preview without changes
npx @cortex-cc/cli init --force            # Reinitialize (idempotent)
npx @cortex-cc/cli init --no-hooks         # Skip hook installation
npx @cortex-cc/cli init --no-mcp           # Skip MCP server
npx @cortex-cc/cli init --cortex-home=/custom/path
npx @cortex-cc/cli init --claude-home=/custom/path

After init, use Claude Code normally. Cortex observes and learns in the background.

Uninstall:

npx @cortex-cc/cli init --force  # then manually:
# 1. Remove cortex entries from ~/.claude/settings.json (hooks + mcpServers.cortex)
# 2. rm -rf ~/.cortex
# 3. Restore backup: cp ~/.claude/settings.json.cortex-backup ~/.claude/settings.json

Requirements

  • Claude Code (latest)
  • Node.js >= 18
  • macOS or Linux (Windows via WSL — untested)

The Question That Started It

I just installed Claude Code, a handful of MCP servers, some plugins, a few hooks. Now what? Is there a controller to help guide and use the right tools?

There wasn't. So I built one.

What It Became

Cortex started as a routing table and evolved into something closer to a nervous system. The name isn't marketing — it's the literal design metaphor. Every component maps to a brain structure.

The core loop:

  You use Claude Code normally
           │
           ▼
  Cortex observes your tool patterns (PostToolUse)
           │
           ▼
  Patterns scored by confidence
  (7-day rolling window, frequency × consistency × recency)
           │
           ▼  confidence >= 90%, seen 5+ times
           │
  Auto-promoted to Claude Code rules
  (loaded every session — your Claude teaches itself)

How It Learns

Before Cortex: You notice Claude keeps reading files with cat instead of the Read tool. You add a note to CLAUDE.md. Weeks later you notice another pattern. You add another note. Your CLAUDE.md grows manually, slowly, and you miss most patterns.

After Cortex: The PostToolUse hook logs every tool call. After 7 days, the analyzer finds "Bash(cat)→Read→Edit seen 45 times." Confidence hits 93%. The pattern auto-promotes to a Claude Code rule: "Prefer Read tool over cat." Next session, Claude follows it automatically. You didn't do anything.

See docs/learning-loop/ for the full pipeline.

Skills and Lifecycle

Cortex implements a cognitive cycle — three chapters inspired by how brains actually work.

Chapter 1: Wake (Synergatis)

The hardest part is starting. The Synergatis agent reads your session state and presents 3 pre-warmed tasks by effort level — zero cold-start cognitive load. Like a reticular activating system waking the cortex with oriented attention.

Chapter 2: Work (Hooks + Routing)

During your session, 8 hooks fire at precise lifecycle moments. The prompt router triages domains and detects exit signals. The observation hook logs tool usage. The Cortex registry routes intent to the right skill, MCP server, or agent.

Chapter 3: Sleep (/bye)

The crown jewel. When you say "bye" (or "done", "save", "exit"), /bye triggers session consolidation:

  • Structured summary of what was accomplished
  • Pattern promotion from observations
  • Memory persistence to cross-session storage
  • State archival for next session's activation

This is the sleep cycle. The brain doesn't just stop — it consolidates. Hippocampal replay, noise pruning, episodic-to-semantic migration. /bye does the same thing for your Claude Code sessions.

See docs/skills/ for the full catalog.

Hooks

8 hooks across the full Claude Code lifecycle:

SessionStart ──► UserPromptSubmit ──► PreToolUse ──► [Tool Runs]
     │                  │                  │
  • git sync        • domain           • strategic
  • recompile         triage             compact
  • activate        • exit detect
                    • duo inbox
                         │
PostToolUse ◄────────────┘──────────► PreCompact ──► Stop
     │                                    │            │
  • observe                           • snapshot    • analyze
  • validate                          • mini-bye    • archive

See docs/hooks/ for the deep dive.

The Brain Metaphor

This isn't decoration. It's the architecture.

In November 2025, Buschman et al. at Princeton showed that the primate prefrontal cortex maintains reusable orthogonal subspaces that snap together compositionally. The brain's trick isn't learning faster. It's not starting from scratch.

That's exactly the problem Cortex solves. Every Claude Code session starts from zero. Your CLAUDE.md helps, but it's static. Cortex makes it grow.

Brain Structure Function Cortex Component
Prefrontal cortex Working memory, orchestration CLAUDE.md + rules/
Thalamus Signal routing to correct processor Cortex registry + routing engine
Cerebellum Motor learning, pattern acquisition Learning loop (observe → analyze → promote)
Hippocampus Fast episodic memory claude-mem (persistent cross-session DB)
Neocortex Slow semantic knowledge RAG pipeline (FTS5 + sqlite-vec)
Brainstem Reflexes, automatic responses Hooks (8 across full lifecycle)
Default mode network Self-observation, meta-learning Homunculus observer
Reticular activating system Wake-up, oriented attention Synergatis agent
Sleep cycle Consolidation, pruning, reset /bye skill
Corpus callosum Inter-hemispheric communication Duo MCP (cross-machine messaging)

"The system doesn't sleep. It just stops. Every organ suffers." — The diagnosis that led to /bye.

What's Inside

Component What It Does Status
Hook Pipeline 8 hooks across the full Claude Code lifecycle (3 packaged, 5 extracting) Partial
Cortex Engine Capability registry + 4-tool MCP server (60+ entries in production; 5 starter) Packaged
Learning Loop Observes tool usage, extracts patterns, auto-promotes to rules Extracting
Federated Search RRF fusion across memory, RAG, and registry with temporal decay Extracting
Session Management CURRENT.md state tracking, rotation, archival Packaged
Domain Packs Installable bundles of professional expertise Extracting
Dashboard 16-section monitoring with keyboard shortcuts Extracting
Synergatis AuDHD body-double agent for session initiation Extracting
/bye Session consolidation — the sleep cycle Extracting

Total: ~9,000 lines running in daily production. "Packaged" = available in this repo. "Extracting" = working in the author's private system, being ported to the open-source packages. "Partial" = partially available.

Designed for Neurodivergent Minds

This isn't an afterthought. The architecture was designed by someone with AuDHD, for someone with AuDHD.

The contract: System initiates, remembers, and tracks. Human recognizes, decides, and creates.

  • Activation Bridge: The hardest part is starting. Synergatis reduces activation energy to near-zero.
  • /bye ritual: Time-boxed (30s-3min), save-point framing, genuine celebration (dopamine-aware).
  • Progressive disclosure: Registry entries use a 3-tier token budget (80 always-loaded / 60 contextual / 800 on-demand) — like neurons that stay dormant until their pattern fires.
  • Context-switching protection: Domain rules loaded on-demand, not always. Saves ~550 tokens/turn.

How Is This Different?

Cortex Claudeception claude-self-reflect OpenClaw
Approach Full cognitive layer (hooks + learning + routing + memory) Meta-prompting (Claude calls Claude) Post-response reflection Rule generation from chat history
Learns automatically Yes (PostToolUse → patterns → rules) No No Partially (needs manual review)
Session lifecycle Full (wake/work/sleep) None None None
MCP server Yes (4 tools) No No No
Hooks 8, full lifecycle 0 0 0
Domain packs Yes (installable expertise) No No No
Zero runtime deps Yes (Node.js 18 stdlib only) Varies Varies Varies

Architecture

┌──────────────────────────────────────────────┐
│                 Claude Code                    │
│      (hooks, MCP, skills, CLAUDE.md)           │
└─────────────────────┬────────────────────────┘
                      │
┌─────────────────────▼────────────────────────┐
│              Hook Pipeline                     │
│  SessionStart → PromptSubmit → PreToolUse      │
│  PostToolUse ─── PreCompact ──── Stop         │
└─────────────────────┬────────────────────────┘
                      │
       ┌──────────────┼──────────────┐
       │              │              │
┌──────▼──────┐ ┌─────▼─────┐ ┌─────▼──────┐
│   Cortex    │ │ Learning  │ │ Federated  │
│   Engine    │ │ Loop      │ │ Search     │
│             │ │           │ │            │
│ 60+ entries │ │ observe   │ │ RRF k=60   │
│ 4 MCP tools │ │ analyze   │ │ MMR λ=0.7  │
│ auto-       │ │ promote   │ │ temporal   │
│ recompile   │ │ decay     │ │ decay      │
└──────┬──────┘ └─────┬─────┘ └─────┬──────┘
       │              │              │
       └──────────────┼──────────────┘
                      │
       ┌──────────────▼──────────────┐
       │        Domain Packs          │
       │  rules + skills + libs +     │
       │  registry entries            │
       └──────────────────────────────┘

Where This Came From

I'm Manos. Greek lawyer, Heraklion Bar. Not a software engineer. I started using Claude Code for legal work and kept hitting the same walls: re-explaining context, watching Claude pick the wrong MCP server, losing session state, starting cold every morning.

So I started building fixes. A hook here, a routing table there. Months later, I had a nervous system — 14 MCP servers coordinated by a registry, patterns auto-promoting to rules, federated search across 5 memory layers, domain-specific tools for Greek law, a monitoring dashboard. It works. It's been my daily driver for 100+ sessions.

This is my first open-source project. The code needs cleanup, the package structure needs rethinking, and there are rough edges everywhere. I'm putting it out here because the ideas work in practice, and I think other Claude Code power users will recognize the problems.

I Could Use Help With

  • Node.js developers — The learning loop (analyze.py, ~970 lines) needs porting to Node.js. Single runtime matters.
  • Testing — Zero tests. For something that auto-modifies rules, that's not great.
  • Linux/WSL validation — Built on macOS M1, untested elsewhere.
  • Domain pack creators — If you're a professional who uses Claude Code daily, your expertise could become a pack.
  • Architecture feedback — Is the hook pipeline right? Would you actually install this?

Open an issue, send a PR, or just tell me what doesn't make sense.

License

MIT


First open-source project. Lawyer who codes with Claude Code. The architecture is battle-tested; the repo is fresh. Feedback welcome — honest is better than polite.

Releases

No releases published

Packages

 
 
 

Contributors