cortex

module
v2.2.4 Latest Latest
Warning

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

Go to latest
Published: Aug 23, 2026 License: MIT

README

🧠 Cortex: Autonomous AI Memory & Project Knowledge Graph

Cortex Architecture

Go Version Next.js Postgres RLS MCP Protocol Zero CGO

Cortex es una plataforma enterprise de memoria episódica autónoma, gobernanza de proyectos y grafo de conocimiento de código diseñada para agentes de IA (Cursor, Claude Code, Cline, Windsurf) y equipos de desarrollo.

Combina extracción estática de código AST Zero-CGO (.NET C#/F#/VB, Java, Kotlin, Rust, C/C++, PHP, Ruby, Swift, Go, TS/JS, Python, SQL), clustering de comunidades (Louvain/Leiden), análisis de blast radius, gobernanza corporativa, búsqueda híbrida (BM25 + Vectores) y persistencia segura Multi-Tenant respaldada por PostgreSQL con Row-Level Security (RLS) y SQLite local.


⚡ Capacidades Principales

1. 🌐 Grafo de Código & Conocimiento por Proyecto (Estilo Graphify)
  • Extractor AST Nativo Políglota (Zero-CGO): Analiza código en Go puro para .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) y SQL (.sql) sin enviar código a LLMs externos ni gastar tokens de API.
  • Clustering de Comunidades (Louvain/Hubs): Agrupa automáticamente los subsistemas funcionales del proyecto y etiqueta los hubs arquitectónicos.
  • God Nodes & Detección de Ciclos: Identifica cuellos de botella (in_degree/out_degree) y dependencias circulares (Tarjan SCC).
  • Cálculo de Blast Radius: Mide el impacto porcentual y lista los archivos/funciones afectados al modificar cualquier componente.
  • Reconciliación Incremental en Refactorizaciones: Si el archivo A antes dependía de B y ahora depende de B y C, Cortex actualiza y reconcilia las relaciones de forma instantánea.
  • Exportador a Obsidian Vault: Descarga notas Markdown interconectadas con enlaces [[WikiLinks]].

Cortex Graph Workflow

2. 🧠 Memoria Episódica & Aprendizaje Continuo
  • Registra decisiones de arquitectura, correcciones de bugs, patrones y descubrimientos técnicos.
  • Búsqueda Híbrida Inteligente: Combina BM25 de texto completo con similitud vectorial (Gemini, OpenAI, Ollama, pgvector, Qdrant) y ponderación de frescura/importancia.
  • Workers Autónomos en Background: Reorganización periódica de grafos, detección de contradicciones y resolución de conflictos (supersedes).

Cortex Memory Lifecycle

3. 🛡️ Gobernanza Corporativa & Multi-Tenancy
  • PostgreSQL RLS (Row-Level Security): Aislamiento estricto por Tenant, Workspace y Proyecto.
  • Reglas de Proyecto & Prompts del Sistema: Inyección dinámica de reglas corporativas y skills en cada consulta de los agentes.

📦 Instalación

Homebrew (macOS / Linux)
brew install lleontor705/tap/cortex
Go Install (Multiplataforma)
go install github.com/lleontor705/cortex/v2/cmd/cortex@latest
Binarios Precompilados & Compilación desde Fuente

Descarga directa de binarios (Windows, macOS, Linux) desde GitHub Releases, o compila localmente desde el código fuente:

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

🚀 Inicio Rápido

1. Modo Local (SQLite, CLI & TUI)
# Configurar integración automática con tu agente preferido
cortex setup claude-code
cortex setup opencode

# Diagnóstico de base de datos e índices
cortex doctor

# Búsqueda semántica e híbrida
cortex search "decisión de arquitectura"

# Lanzar interfaz interactiva en terminal
cortex tui
2. Modo Servidor con Docker (Recomendado para Equipos & Multi-Tenant)
# Iniciar PostgreSQL y Cortex Server
docker compose up --build -d

Inicia el servidor autenticado en el puerto 7438 con soporte MCP Streamable HTTP en /mcp y API REST en /api/*.

3. Interfaz Web (Control Room Next.js 15)
cd web
npm install
npm run dev

Abre http://localhost:3000 e ingresa la URL del servidor y el Bearer Token.


🔌 Integración con Agentes MCP (Cursor, Claude Code, Cline)

Agrega Cortex como servidor MCP en tu editor o agente:

Configuración MCP (Streamable HTTP):
{
  "mcpServers": {
    "cortex": {
      "url": "https://tu-servidor-cortex.railway.app/mcp",
      "headers": {
        "Authorization": "Bearer TU_BEARER_TOKEN"
      }
    }
  }
}
Herramientas MCP Disponibles:
  • cortex_ingest_code: Escanea e ingesta repositorios o archivos modificados tras refactorizaciones.
  • cortex_get_blast_radius: Calcula los archivos y funciones impactados por un cambio.
  • cortex_analyze_architecture: Diagnostica comunidades funcionales, God nodes y anomalías.
  • cortex_detect_cycles: Detecta dependencias e importaciones circulares.
  • cortex_save / cortex_handoff: Guarda observaciones y handoffs con idempotencia.
  • cortex_search / cortex_relate: Búsqueda híbrida y creación de aristas de grafo.
  • cortex_get_project_context: Obtiene reglas corporativas y skills del proyecto.

📚 Documentación Técnica


🛠️ Comandos de Desarrollo

# Descargar dependencias y compilar binario
go mod download
make build

# Ejecutar suite de pruebas unitarias y de integración
go test -v -count=1 ./...

# Linter oficial
golangci-lint run ./...

# Compilar frontend Web
cd web && npm run build

Cortex 2.0 • Diseñado para potenciar el desarrollo de software asistido por IA de forma duradera y confiable.

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
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/ast
Package ast provides zero-CGO static code analysis and symbol extraction for Go, TypeScript/JavaScript, Python, and SQL files, building deterministic code knowledge graphs.
Package ast provides zero-CGO static code analysis and symbol extraction for Go, TypeScript/JavaScript, Python, and SQL files, building deterministic code knowledge graphs.
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.
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.
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 provides shared retrieval-pipeline orchestration that bridges the domain.VectorIndex port (W8.1, ADR-05) to the full search-result types that MCP, bench, CLI, and TUI consumers require.
Package retrieval provides shared retrieval-pipeline orchestration that bridges the domain.VectorIndex port (W8.1, ADR-05) to the full search-result types that MCP, bench, CLI, and TUI consumers require.
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 implements the SQLite memory store for Cortex.
Package sqlite implements the SQLite memory store 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).
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