Cortex for Claude Code

repository·master·Indexed 41 days ago

https://github.com/hjertefolger/cortex

Persistent, local-first memory plugin for Claude Code (v2.1.4) that enables long-term recall across sessions. It uses a hybrid vector and keyword search approach with a local SQLite database to ensure 100% data privacy. Features include MCP tools for automated memory management, a real-time statusline for context usage, and configurable presets for automation and awareness.

Tokens
13.6K
Snippets
56
Records
65
Agent score
50%

What's inside Cortex

  1. Understand the Cortex data storage structure

    master

    Cortex stores all data locally in the ~/.cortex/ directory. This ensures a 'Zero cloud' and 'No telemetry' security model where no data leaves your machine.

    Key files include:

    • memory.db: The SQLite database containing all memories (~2-3MB per 1000 memories).
    • memory.db.backup.*: Up to 5 rotated backups for recovery.
    • config.json: User configuration.
    • analytics.json: Session tracking.
    • autoSaveState.json: Transient state.
  2. How Cortex search works

    master

    Cortex uses a hybrid search algorithm to recall relevant memories by combining three signals using RRF (Reciprocal Rank Fusion):

    1. Vector Search (60%): Uses cosine distance on 768-dimensional embeddings (Nomic Embed v1.5).
    2. FTS5 Keyword Search (40%): Uses BM25 ranking via SQLite full-text search.
    3. Recency Decay: Applies a 7-day half-life to weight recent memories higher.

    The results are aggregated using RRF with k=60 to produce the final ranked list.

  3. Understand the Cortex Statusline

    master

    The statusline provides real-time feedback on memory and context usage. It is automatically configured by /cortex-setup.

    Format: Ψ 47 ●●○○○ 45% ✓ 5m

    • Ψ: Cortex identifier.
    • 47: Memory fragment count (compact notation like 1.1K or 10.2M is supported).
    • ●●○○○: Visual representation of context usage (filled/empty circles, color-coded).
    • 45%: Current context percentage.
    • ⠋ Saving: Animated spinner during background saves.
    • ✓ Autosaved: Success indicator (visible for ~5s after a save).
    • ✓ 5m: Time elapsed since the last save.
  4. Safety rules for destructive memory actions

    master

    When performing destructive actions (deleting or forgetting memories), you must adhere to these strict safety protocols:

    1. Preview First: Always call the delete/forget tool without the confirm flag first to see the impact.
    2. Show Impact: Explicitly display to the user exactly what will be affected (e.g., content, project, or number of items).
    3. Explicit Confirmation: Ask the user a direct question like "Are you sure you want to delete X?".
    4. Never Assume: Do not proceed with a deletion based on inferred intent; wait for explicit approval.
    5. Be Clear: Clearly state that the data will be permanently lost.
  5. Update Cortex to the latest version

    master

    To update Cortex while preserving your memories and configuration in ~/.cortex/, follow these steps:

    1. Update the marketplace: /plugin marketplace update cortex
    2. Update the plugin: /plugin update cortex
    3. Run the setup wizard: Ask Claude to run /cortex-setup to install new dependencies and models.
    4. Restart Claude Code to load the new version.

    Important: Always update the marketplace first to avoid known Claude Code issues.

    /plugin marketplace update cortex
    /plugin update cortex
    # Then run setup
    /cortex-setup
  6. Initialize Cortex for first-time use

    master

    To set up Cortex for the first time, you must initialize the system to create the necessary directories and database. This is done by running the setup command via the main entry point.

    Note: ${CLAUDE_PLUGIN_ROOT} is an environment variable representing the root directory of the Claude plugin.

    node ${CLAUDE_PLUGIN_ROOT}/dist/index.js setup
  7. Run E2E tests with real transcripts

    master

    While npm test uses synthetic data, you can run End-to-End (E2E) tests using real production transcripts from Claude Code.

    1. Locate a large .jsonl file in your ~/.claude/ directory.
    2. Copy it to the tests/ directory as sample_transcript.jsonl.
    3. Execute the E2E test script using Node.

    This validates database CRUD, hybrid search (Vector + Keyword), archive parsing, and MCP tool handlers.

    # 1. Copy real transcript
    cp ~/.claude/your-session-id.jsonl tests/sample_transcript.jsonl
    
    # 2. Run E2E test
    node --test tests/e2e_transcript.test.js
  8. Configure Cortex using presets

    master

    You can quickly apply common configuration profiles using the configure command with a preset name. This is useful for setting up different operational modes without manual tuning.

    Available presets:

    • Full: Enables all features, including Statusline, Auto-archive, Awareness, and sets the Auto-save threshold to 70%.
    • Essential: Enables core features (Statusline, Auto-archive) and sets the Auto-save threshold to 75%.
    • Minimal: Disables Statusline and Auto-archive, setting the Auto-save threshold to 85%.
    node dist/index.js configure <preset>
  9. Build Cortex from source

    master

    Use the following commands to build the project components. The build process generates the dist/ directory containing the main entry point, the MCP server, and the SQLite WebAssembly binary.

    npm install            # Install dependencies
    npm run build          # Build index.js + mcp-server.js + copy WASM
    npm run build:index    # Build main entry only
    npm run build:mcp      # Build MCP server only
    npm run typecheck      # TypeScript strict check
  10. Configure Cortex behavior presets

    master

    After initialization, you can configure how Cortex behaves using the configure command followed by a preset name. There are three available presets:

    1. full (Full Automation): Recommended. Saves every 5% context change, automatically saves backups before clearing context, and shows "Saved" notifications.
    2. essential (Balanced): Saves every 10% context change, automatically saves backups before clearing context, and uses a standard status bar.
    3. minimal (Silent Mode): Manual saving only, automatically saves backups before clearing context, and hides the status bar.
    # For Full Automation
    node ${CLAUDE_PLUGIN_ROOT}/dist/index.js configure full
    
    # For Balanced mode
    node ${CLAUDE_PLUGIN_ROOT}/dist/index.js configure essential
    
    # For Silent Mode
    node ${CLAUDE_PLUGIN_ROOT}/dist/index.js configure minimal
  11. Install Cortex in Claude Code

    master

    Cortex is a persistent local memory plugin for Claude Code. Follow these steps to install it:

    1. Add the marketplace: Run /plugin marketplace add hjertefolger/cortex inside a Claude Code instance.
    2. Install the plugin: Run /plugin install cortex.

    Linux Users Fix: If you encounter EXDEV: cross-device link not permitted (common when /tmp is a separate filesystem), set TMPDIR to a local directory before launching Claude:

    mkdir -p ~/.cache/tmp && TMPDIR=~/.cache/tmp claude
    1. Run the setup wizard: Ask Claude to run the setup skill to initialize the database, download the embedding model, and configure the statusline:
    Please setup Cortex (or run /cortex-setup manually)
    1. Customize settings: Ask Claude to configure your preferences:
    Please configure Cortex (or run /cortex-configure manually)

    Note: Restart Claude Code after setup to activate the statusline.

    /plugin marketplace add hjertefolger/cortex
    /plugin install cortex
  12. Configure Cortex settings

    master

    Cortex configuration is stored in ~/.cortex/config.json. You can apply presets using /cortex-configure <preset> or customize specific keys.

    Presets

    • full: Enables all features (statusline, auto-archive, warnings).
    • essential: Enables statusline and auto-archive only.
    • minimal: Commands only; no automation.

    Key Configuration Keys

    SettingDefaultDescription
    autosave.contextStep.step5% context increase to trigger auto-save
    autosave.onPreCompacttrueArchive session before /compact or /clear
    autosave.onSessionEndtrueArchive session on exit (Ctrl+C x2)
    restoration.tokenBudget2000Max tokens for key decision restoration
    restoration.turnCount3Number of raw conversation turns to restore
    awareness.enabledfalseInject user/date/time at session start
    awareness.userNamenullUser name shown in awareness context
    awareness.timezonenullIANA timezone (null = auto-detect)
    {
      "statusline": {
        "enabled": true,
        "showFragments": true,
        "showLastArchive": true,
        "showContext": true
      },
      "archive": {
        "projectScope": true,
        "minContentLength": 50
      },
      "autosave": {
        "onSessionEnd": true,
        "onPreCompact": true,
        "contextStep": {
           "enabled": true,
           "step": 5
        }
      },
      "restoration": {
        "tokenBudget": 2000,
        "messageCount": 5,
        "turnCount": 3
      },
      "awareness": {
        "enabled": false,
        "userName": null,
        "timezone": null
      }
    }