cortex

module
v2.4.11 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 8, 2026 License: MIT

README ΒΆ

🧠 Cortex: Autonomous AI Memory & Project Knowledge Graph

English | EspaΓ±ol

Cortex Architecture

CI status Go Reference

Go Version Next.js Self-Hosted Postgres MCP Protocol Zero CGO

πŸ“– Documentation site: https://lleontor705.github.io/cortex/

Cortex is a self-hosted platform for autonomous episodic memory, project governance, and a code knowledge graph built for AI agents (Cursor, Claude Code, Cline, Windsurf) and development teams.

It combines Zero-CGO static AST code extraction (.NET C#/F#/VB, Java, Kotlin, Rust, C/C++, PHP, Ruby, Swift, Go, TS/JS, Python, SQL), community clustering (Louvain/Leiden), blast-radius analysis, project governance, hybrid search (BM25 + vectors), and secure persistence backed by single-instance self-hosted PostgreSQL and local SQLite.


⚑ Key Capabilities

1. 🌐 Per-Project Code & Knowledge Graph (Graphify-style)
  • Native Polyglot AST Extractor (Zero-CGO): Analyzes code in pure Go for .NET (.cs, .fs, .vb), Java/Kotlin (.java, .kt), Rust (.rs), C/C++ (.c, .cpp, .h, .hpp), PHP (.php), Ruby (.rb), Swift (.swift), TypeScript/JavaScript (.ts, .tsx, .js), Python (.py), Go (.go), and SQL (.sql) without sending code to external LLMs or spending API tokens.
  • Community Clustering (Louvain/Hubs): Automatically groups the functional subsystems of a project and labels architectural hubs.
  • God Nodes & Cycle Detection: Identifies bottlenecks (in_degree/out_degree) and circular dependencies (Tarjan SCC).
  • Blast Radius: Measures the percentage impact and lists the affected files/functions when any component changes.
  • Incremental Reconciliation on Refactors: If file A previously depended on B and now depends on B and C, Cortex updates and reconciles the relationships instantly.
  • Obsidian Vault Exporter: Downloads interlinked Markdown notes with [[WikiLinks]].

Cortex Graph Workflow

2. 🧠 Episodic Memory & Continuous Learning
  • Records architecture decisions, bug fixes, patterns, and technical discoveries.
  • Smart Hybrid Search: Combines full-text BM25 with vector similarity (OpenAI, Ollama, pgvector, Qdrant) plus freshness/importance weighting.
  • Autonomous Background Workers: Periodic graph reorganization, contradiction detection, and conflict resolution (supersedes).

Cortex Memory Lifecycle

3. πŸ›‘οΈ Project Governance & Self-Hosting
  • Self-Hosted PostgreSQL (Single-Instance RLS): The single-tenant server pins tenant_id and workspace_id from configuration and runs every operation under forced RLS.
  • Project Rules & System Prompts: Dynamic injection of corporate rules and skills into every agent query.

πŸ“¦ Installation

Every channel installs the same cortex binary. The full channel matrix β€” Homebrew, Go toolchain, checksum-verified release binaries, source builds, and the multi-arch container image β€” is documented in docs/distribution.md.

Homebrew (macOS / Linux)
brew install lleontor705/tap/cortex
Go Install (Cross-platform)
go install github.com/lleontor705/cortex/v2/cmd/cortex@latest
Prebuilt Binaries & Source Builds

Download prebuilt binaries (Windows, macOS, Linux) from GitHub Releases, or build locally from source (see docs/distribution.md):

git clone https://github.com/lleontor705/cortex.git
cd cortex
make build

πŸš€ Quick Start

1. Local Mode (SQLite, CLI & TUI)
# Set up automatic integration with modular profiles (dev, minimal, agent)
cortex setup claude-code --profile=dev
cortex setup opencode --profile=agent

# Show the operating mode (local, hybrid, server)
cortex status

# Diagnose the database and indexes
cortex doctor

# Adaptive search with complexity classification
cortex search "architecture decision" --mode=auto

# Index a repository once (AST symbols and relations)
cortex ingest ./internal --project cortex

# Keep the index fresh with the continuous file watcher daemon
cortex watch . --project cortex

# Snapshot the local SQLite database before risky operations
cortex backup ~/backups/cortex.db

# Check for a newer release without installing it
cortex update --check

# Launch the interactive terminal UI (with an integrated profile selector)
cortex tui
2. Embedded Web UI & Server Mode

The web UI is compiled into the cortex binary and served on the same host and port as the HTTP API. There is no separate web container or second port: the UI ships inside the server image.

Local (single binary, SQLite)
cortex serve

On the first boot Cortex prints the web access key once. Open http://localhost:7438, paste the key into the UI, and it is remembered in the browser. Later rotations use:

cortex web key show        # location, presence, and prefix (never the plaintext)
cortex web key regenerate  # mint a replacement and print it once

See Embedded Web UI for the at-rest key format (0600, prefix + HMAC digest), rotation semantics, runtime /config.js endpoint injection, and the per-mode (local/hybrid/server) capabilities.

The local serve mux also serves the five web-critical parity endpoints (/api/me, /api/stats, /api/projects, /api/agent/projects, /api/graph/project-graph) behind the same http.token gate.

Server mode (self-hosted, single-tenant PostgreSQL)
cortex --mode server

--mode server runs the self-hosted single-tenant composition: a PostgreSQL 16+ backing store with one static bearer (http.token) authenticating a synthetic constant principal assembled from server.tenant_id, server.workspace_id, and server.principal_subject. It serves the same embedded UI at /, the authenticated REST API at /api/, and Streamable HTTP MCP at /mcp; the web access key stays an independent UI credential.

The official image runs the same binary. The bundled Compose stack brings up PostgreSQL plus the server (UI and API on :7438):

# 1. Configure environment variables (optional)
cp .env.example .env

# 2. Start PostgreSQL + Cortex server
docker compose up -d

[!TIP] On first boot the server prints the web access key once; paste it into the UI. To read it from the container logs run:

docker compose logs cortex-server

πŸ”Œ MCP Agent Integration (Cursor, Claude Code, Cline)

Add Cortex as an MCP server in your editor or agent:

MCP configuration (Streamable HTTP):
{
  "mcpServers": {
    "cortex": {
      "url": "https://your-cortex-server.railway.app/mcp",
      "headers": {
        "Authorization": "Bearer YOUR_BEARER_TOKEN"
      }
    }
  }
}
Modular Profiles and MCP Tools:

Cortex organizes its catalog into modular profiles (--tools=agent|dev|minimal):

  • Episodic Memory & Search: cortex_save, cortex_update, cortex_get_observation, cortex_context, cortex_session_summary, cortex_search (FTS5 + Vectors + HippoRAG + Adaptive-RAG), cortex_get_agent_context.
  • Knowledge Graph & Lineage: cortex_relate, cortex_graph, cortex_graph_path, cortex_revision_history, cortex_handoff (idempotent handoff between agents).
  • AST Code Intelligence (Zero-CGO): cortex_ingest_code (native polyglot static extraction), cortex_get_code_symbols, cortex_code_map (PageRank repo map), cortex_code_tests (Fast-TDD test impact), cortex_get_blast_radius, cortex_detect_cycles, cortex_analyze_architecture.
  • Governance & Status: cortex_get_rules, cortex_save_rule, cortex_get_status (SQLite/Postgres mode and capabilities). In Server mode also: cortex_get_project_context, cortex_list_skills, cortex_get_skill, cortex_resolve_query.

πŸ“š Documentation

πŸ“š Docs site: https://lleontor705.github.io/cortex/


πŸ› οΈ Development Commands

# Download dependencies and build the binary
go mod download
make build

# Run the unit and integration test suite
go test -v -count=1 ./...

# Official linter
golangci-lint run ./...

# Build and embed the web assets BEFORE make build (see docs/embedded-web.md)
make web-build

Cortex 2.0 β€’ Built to make AI-assisted software development durable and reliable.
Also available in EspaΓ±ol.

Directories ΒΆ

Path Synopsis
bench
common
Package common β€” LLM-as-Judge evaluator (Ollama-only).
Package common β€” LLM-as-Judge evaluator (Ollama-only).
cortex
Package cortex captures retrieval evidence from the currently shipped Cortex application path without reimplementing search, filtering, or ranking.
Package cortex captures retrieval evidence from the currently shipped Cortex application path without reimplementing search, filtering, or ranking.
cortex/cmd/baseline command
Command baseline validates and materializes Cortex-native retrieval evidence.
Command baseline validates and materializes Cortex-native retrieval evidence.
dmr
Package dmr implements the Deep Memory Retrieval benchmark runner for Cortex.
Package dmr implements the Deep Memory Retrieval benchmark runner for Cortex.
locomo
Package locomo implements the LOCOMO benchmark runner for Cortex.
Package locomo implements the LOCOMO benchmark runner for Cortex.
longmemeval
Package longmemeval implements the LongMemEval benchmark runner for Cortex.
Package longmemeval implements the LongMemEval benchmark runner for Cortex.
vectorhydration/cmd/runner command
Command runner is the deliberately small, strict entry point for collection.
Command runner is the deliberately small, strict entry point for collection.
cmd
cortex command
internal
api
Package api exposes the HTTP handlers shared by the server mux (internal/platform/server) and the local serve mux (internal/http).
Package api exposes the HTTP handlers shared by the server mux (internal/platform/server) and the local serve mux (internal/http).
app
authz
Package authz contains the server authorization port.
Package authz contains the server authorization port.
cli
database
Package database provides SQLite connection management with optimized pragmas.
Package database provides SQLite connection management with optimized pragmas.
domain
Package domain defines the core domain models and business rules for Cortex.
Package domain defines the core domain models and business rules for Cortex.
domain/agent
Package agent implements the transport-neutral, read-only conversational RAG domain.
Package agent implements the transport-neutral, read-only conversational RAG domain.
domain/ast
Package ast provides zero-CGO static code analysis, rich symbol extraction, and cross-file call graph resolution for Go, TypeScript/JavaScript, Python, Rust, SQL, and polyglot codebases.
Package ast provides zero-CGO static code analysis, rich symbol extraction, and cross-file call graph resolution for Go, TypeScript/JavaScript, Python, Rust, SQL, and polyglot codebases.
domain/code
Package code defines domain entities, ports, and analytics for static code graphs, symbol indexes, and architectural insights.
Package code defines domain entities, ports, and analytics for static code graphs, symbol indexes, and architectural insights.
domain/dna
Package dna generates Project DNA β€” a structured summary of a project's key decisions, patterns, tech stack, and gotchas extracted from observations.
Package dna generates Project DNA β€” a structured summary of a project's key decisions, patterns, tech stack, and gotchas extracted from observations.
domain/entity
Package entity implements entity extraction and linking for Cortex.
Package entity implements entity extraction and linking for Cortex.
domain/extraction
Package extraction provides automated extraction and synthesis of observations, entities, and knowledge-graph relationships from raw text, code notes, and session logs.
Package extraction provides automated extraction and synthesis of observations, entities, and knowledge-graph relationships from raw text, code notes, and session logs.
domain/graph
Package graph provides graph analytics, clustering, and structural code intelligence algorithms inspired by Graphify, ported natively to Go with zero-CGO.
Package graph provides graph analytics, clustering, and structural code intelligence algorithms inspired by Graphify, ported natively to Go with zero-CGO.
domain/lifecycle
Package lifecycle implements auto-archival and lifecycle management for Cortex.
Package lifecycle implements auto-archival and lifecycle management for Cortex.
domain/memory
Package memory provides the business logic layer for observation management.
Package memory provides the business logic layer for observation management.
domain/observability
Package observability provides metrics and quality evaluation for the Cortex memory system.
Package observability provides metrics and quality evaluation for the Cortex memory system.
domain/projectprotocol
Package projectprotocol defines the Project Context Protocol domain contract: skill and rule artifacts, immutable revisions, activation compare-and-swap (CAS) pointers, idempotency DTOs, canonical hashing and the deterministic effective protocol resolution with its approved limits.
Package projectprotocol defines the Project Context Protocol domain contract: skill and rule artifacts, immutable revisions, activation compare-and-swap (CAS) pointers, idempotency DTOs, canonical hashing and the deterministic effective protocol resolution with its approved limits.
domain/scoring
Package scoring implements the importance scoring business logic for Cortex.
Package scoring implements the importance scoring business logic for Cortex.
domain/search
Package search provides FTS5-based full-text search business logic for Cortex.
Package search provides FTS5-based full-text search business logic for Cortex.
domain/session
Package session provides business logic for session management.
Package session provides business logic for session management.
domain/temporal
Package temporal provides temporal graph semantics and evolution tracking for the knowledge graph in Cortex.
Package temporal provides temporal graph semantics and evolution tracking for the knowledge graph in Cortex.
embedding
Package embedding provides text-to-vector embedding for Cortex.
Package embedding provides text-to-vector embedding for Cortex.
http
Package http implements the REST API server for Cortex.
Package http implements the REST API server for Cortex.
httpauth
Package httpauth centralizes the bearer credential contract shared by the local HTTP plane (internal/http) and the server plane (internal/platform/server).
Package httpauth centralizes the bearer credential contract shared by the local HTTP plane (internal/http) and the server plane (internal/platform/server).
identity
Package identity provides Principal and TenantContext types and nil-safe constructors for threading authenticated identity through the Cortex platform.
Package identity provides Principal and TenantContext types and nil-safe constructors for threading authenticated identity through the Cortex platform.
integration/astindex/cmd/benchgate command
Command benchgate: versioned fail-closed evaluator for exact BenchmarkASTE2E pairs (AST plan A0.2; cortex:observation/1691).
Command benchgate: versioned fail-closed evaluator for exact BenchmarkASTE2E pairs (AST plan A0.2; cortex:observation/1691).
mcp
Package mcp implements the Model Context Protocol server for Cortex.
Package mcp implements the Model Context Protocol server for Cortex.
mcp/memorycontract
Package memorycontract is the shared, pure MCP contract for the durable memory write surface (design RD6, REM-SAVE-001, REM-MCP-001).
Package memorycontract is the shared, pure MCP contract for the durable memory write surface (design RD6, REM-SAVE-001, REM-MCP-001).
migration
Package migration provides a database migration framework for SQLite.
Package migration provides a database migration framework for SQLite.
ollama
Package ollama manages the Ollama process lifecycle for Cortex.
Package ollama manages the Ollama process lifecycle for Cortex.
platform/server
Package server is the PostgreSQL composition root.
Package server is the PostgreSQL composition root.
projection/obsidian
Package obsidian implements a one-way, deterministic Markdown projection.
Package obsidian implements a one-way, deterministic Markdown projection.
retrieval
Package retrieval implements hybrid, multi-signal, and adaptive retrieval pipelines for Cortex.
Package retrieval implements hybrid, multi-signal, and adaptive retrieval pipelines for Cortex.
server/external
Package external: provider health aggregation (W8.4, REQ-VEC-002).
Package external: provider health aggregation (W8.4, REQ-VEC-002).
setup
Package setup installs Cortex integrations for AI coding agents.
Package setup installs Cortex integrations for AI coding agents.
store/bundle
Package bundle provides the Stores struct that bundles all store dependencies.
Package bundle provides the Stores struct that bundles all store dependencies.
store/entity
Package entity implements the SQLite entity link store for Cortex.
Package entity implements the SQLite entity link store for Cortex.
store/graph
dna_batch.go implements the optional DNA batch edge-count capability on the local SQLite graph store.
dna_batch.go implements the optional DNA batch edge-count capability on the local SQLite graph store.
store/postgres
Package postgres contains the server-mode repositories.
Package postgres contains the server-mode repositories.
store/prompt
Package prompt implements the SQLite prompt store for Cortex.
Package prompt implements the SQLite prompt store for Cortex.
store/scoring
Package scoring implements the SQLite scoring store for Cortex.
Package scoring implements the SQLite scoring store for Cortex.
store/search
Package search implements the SQLite search store for Cortex.
Package search implements the SQLite search store for Cortex.
store/session
Package session implements the SQLite session store for Cortex.
Package session implements the SQLite session store for Cortex.
store/sqlite
Package sqlite provides SQLite persistence for Cortex.
Package sqlite provides SQLite persistence for Cortex.
sync
Package sync provides git-friendly memory synchronization via compressed chunks.
Package sync provides git-friendly memory synchronization via compressed chunks.
transportpolicy
Package transportpolicy defines the shared transport security policy for every client that sends Bearer credentials to an HTTP(S) destination (REM-TRANSPORT-001): HTTPS is required for non-loopback destinations, plain HTTP is only allowed on strict loopback, and redirects must never downgrade the scheme or change the origin before the Authorization header is forwarded.
Package transportpolicy defines the shared transport security policy for every client that sends Bearer credentials to an HTTP(S) destination (REM-TRANSPORT-001): HTTPS is required for non-loopback destinations, plain HTTP is only allowed on strict loopback, and redirects must never downgrade the scheme or change the origin before the Authorization header is forwarded.
tui
Package tui implements the BubbleTea terminal UI for Cortex.
Package tui implements the BubbleTea terminal UI for Cortex.
update
Package update provides version checking and self-updating against GitHub releases.
Package update provides version checking and self-updating against GitHub releases.
vector/conformance
Package conformance provides the shared VectorIndex conformance suite (REQ-VEC-002, ADR-05, W8.4).
Package conformance provides the shared VectorIndex conformance suite (REQ-VEC-002, ADR-05, W8.4).
vector/pgvector
Package pgvector implements the second external VectorIndex adapter (ADR-05, REQ-VEC-001/002).
Package pgvector implements the second external VectorIndex adapter (ADR-05, REQ-VEC-001/002).
vector/purego
Package purego provides a zero-CGO, pure Go VectorIndex implementation.
Package purego provides a zero-CGO, pure Go VectorIndex implementation.
vector/qdrant
Package qdrant implements the first external VectorIndex adapter (ADR-05, REQ-VEC-001/002).
Package qdrant implements the first external VectorIndex adapter (ADR-05, REQ-VEC-001/002).
vector/sqlite_blob
Package sqlite_blob implements the always-available zero-CGO VectorIndex adapter (ADR-05, REQ-VEC-001).
Package sqlite_blob implements the always-available zero-CGO VectorIndex adapter (ADR-05, REQ-VEC-001).
web
Package web serves the compiled Next.js export of the Cortex web UI from inside the Go binary.
Package web serves the compiled Next.js export of the Cortex web UI from inside the Go binary.
webkey
Package webkey manages the dedicated web-surface access credential for the embedded web UI.
Package webkey manages the dedicated web-surface access credential for the embedded web UI.
migrations
v2
Package v2 embeds the Cortex v2 baseline SQL migration bundle.
Package v2 embeds the Cortex v2 baseline SQL migration bundle.
plugin
opencode
Package opencode embeds the canonical OpenCode plugin in Cortex binaries.
Package opencode embeds the canonical OpenCode plugin in Cortex binaries.
Package testutil provides testing utilities for Cortex tests.
Package testutil provides testing utilities for Cortex tests.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL