Cortex
Cortex is a local-first persistent-memory MCP server for AI coding agents, providing memory storage/retrieval, project context, consolidation, navigation, visualization, and wiki/ADR management.
Store, recall, rate, validate, anchor, and forget memories, with exact-duplicate handling and provenance/heat-based ranking.
Query or rebuild cognitive/methodology profiles, detect domains, and generate a methodology graph or 3D visualization.
Save and restore working state across context compaction with checkpoints, plus consolidate memory via decay/compression/CLS cycles.
Import or backfill Claude Code sessions, seed project memory from a codebase, and analyze code structure with tree-sitter.
Use hierarchical recall, drill into memory clusters, navigate co-access neighbors, trace causal chains, and detect knowledge gaps/coverage.
Create prospective-memory triggers, neuro-symbolic recall rules, project narratives, and period-based project stories.
Author and manage wiki pages, link pages bidirectionally, create numbered ADRs, and reindex the wiki table of contents.
Sync top memory insights into CLAUDE.md and inspect memory diagnostics, heat distribution, entities, and triggers.
Run locally with SQLite by default or PostgreSQL/pgvector, with shared memory across Claude Code and Codex plugins when configured.
Integrates CodeMirror 6 as an inline editor for the Cortex wiki system, providing live preview editing of structured markdown content with LaTeX math support and BibTeX citations.
Supports Docker deployment with a provided Dockerfile for containerized Cortex runtime environments, enabling portable installation and execution.
Enables git-diffable markdown files in the Cortex wiki system, maintaining interoperability with version control while providing enhanced editing and export capabilities.
Hosted on GitHub with CI/CD workflows, badges, and companion projects for retrieval abstention models and specialist Claude Code agents.
Provides LaTeX math rendering in the Cortex wiki editor via KaTeX, supporting inline math ($...$) and display math ($$...$$) blocks with equation auto-numbering and cross-references.
Uses markdown as the underlying format for Cortex wiki pages, maintaining grep-able, diffable source files while adding rendering, editing, and Pandoc export capabilities.
Uses PostgreSQL with pgvector extension as the primary database for Cortex's memory storage, enabling vector similarity search and structured memory management.
Built with Python 3.10+ as the implementation language, with setup scripts and cross-platform installation options.
Integrates with Redis for session state management, with Cortex's memory system capable of recalling and analyzing Redis-related debugging sessions and architectural decisions.
Supports SQLite as an alternative database option through Cortex-cowork for Claude Cowork users, providing PostgreSQL-free deployment.
Sovereign is what it is today. Everything runs on your machine: a local SQLite file by default, or PostgreSQL + pgvector if you prefer. No LLM in the retrieval loop, and nothing leaves localhost unless you configure an integration that does. Your project's memory is a file you own and can delete.
Claude Code and Codex share Cortex memory. Both native plugins provide the same memory tools and 11 lifecycle hook modules for automatic capture, recall and project context. Use either agent on a project and keep its memory when you switch. Verified with real Claude and Codex sessions on macOS. The same stdio MCP server also supplies memory tools to Claude Desktop, Claude Cowork and other local MCP hosts.
Eco-responsible is what we are aiming at. Work that never reaches a datacenter is work nobody has to power, and an agent that finds the right context first time re-reads fewer files. We hold that intent to the Green Software Foundation's SCI method, and we publish no CO₂ or energy figure, because we have not measured one. What we do and do not claim ↓
36 implemented, inspectable neuroscience-inspired mechanisms · 57 memory tools · 11 lifecycle hooks · a self-curating per-project wiki — all local, all open-source, MIT.
The committed ablations do not establish that these 36 mechanisms improve retrieval collectively or individually. Published neuroscience references explain their design; retrieval benefits require measurements in Cortex. See Verification.
Install
Claude Code — add the marketplace and install the plugin:
claude plugin marketplace add cdeust/Cortex
claude plugin install hypermnesia-mcp
claude --init-onlyclaude --init-only runs the plugin's Setup hook, which installs Cortex's runtime (base
dependencies, semantic search and its embedding model) before your first session. It prints
nothing and exits 0 even when the install fails (Claude Code discards a Setup hook's output), so
to watch the progress and get a failing exit code, run scripts/init_plugin.py from the installed
plugin instead (its path is installPath in claude plugin list --json).
Update the same way, one command, then initialise again:
claude plugin update hypermnesia-mcp
claude --init-onlyClaude Desktop — download hypermnesia-mcp.mcpb from
Releases and open it, or use
Settings → Extensions. The bundle carries the tools but no hooks; the MCPB format has none.
Claude Cowork is detected automatically (CLAUDE_ENVIRONMENT=cowork) and uses the local
SQLite store. No PostgreSQL required.
For Codex, install the native plugin for memory tools and automatic hooks:
uv tool install "hypermnesia-mcp[sqlite]"
codex plugin marketplace add cdeust/Cortex
codex plugin add hypermnesia-mcp-codex@cortex-codex-pluginsOpen /hooks in Codex to review and trust the Cortex hooks, then start a fresh
session. Changed hook definitions require renewed trust after an update. The
plugin uses the same saved backend selection as Claude Code; both hosts share
memory when they use the same configuration root and store.
Codex setup details.
Other stdio MCP hosts (Gemini CLI, Cursor, Windsurf, VS Code) launch the same server and get the same tools. See launch commands. WSL, TLS client certificates and corporate proxies are covered in deployment scenarios.
Cortex's dependencies live in the plugin's data directory, one directory per locked
dependency set (sets/<key>), so an update that does not change the locked dependencies (most
releases: 21 of 29 from v4.9.0 to v4.23.5) finds its set installed. A background job removes the
sets no installed version references; it makes no network call. When a set is missing (the first
session after an install, or after an update that changes the locked dependencies, when
claude --init-only did not run first), no hook installs: SessionStart says
Cortex is installing its dependencies (about 2 minutes, about 5 with semantic search); memory is available when it is done, the Edit/Write guards let edits through and say that the Cortex gate is
inactive until then, and the MCP server installs the set in the background; the next session (or
the same one, once done) shows Cortex ready: <store>, <n> memories; <how recall ranks>.
claude --init-only (or python3 scripts/init_plugin.py, which shows progress) installs
everything before the first session; only with it does that session start ready. To work
without Cortex, offline or not, run claude plugin disable hypermnesia-mcp@cortex-plugins.
On macOS and Linux (glibc 2.36 or later, x86_64 or arm64: Ubuntu 24.04 and 26.04, Debian 12 and
later; not Ubuntu 22.04 or RHEL 9), claude --init-only on a fresh install also gives the plugin its own
PostgreSQL server with pgvector and pg_trgm: pinned, sha256-checked binaries (about 13 MB on macOS,
40 MB on Linux, where they bundle their libraries; pgvector is compiled by Cortex's CI, with build
provenance attested) on 127.0.0.1, with no Homebrew or system PostgreSQL needed. Its data lives in
~/.claude/methodology/managed-pg/, so uninstalling the plugin never deletes your memories. It
becomes the store only after it has started and its schema exists; if it cannot start (a Linux
distribution with glibc older than 2.36, for example) the SQLite store is used, as it is on Windows,
and the session start says why (SQLite fallback: ...). A store already on that server is never
switched to SQLite: Setup fails and names the cause. The Codex
plugin on the same account attaches to the same server. An existing SQLite store is not moved
(ADR-1114).
Otherwise the first use creates a local SQLite store under ~/.claude/methodology/. Models are downloaded
once when needed and then run offline. The embedding and reranking model files are both fetched
on first use. Optional integrations, remote PostgreSQL, and OTLP telemetry use the network only
when explicitly configured. PRIVACY.md lists the exact scope.
An existing PostgreSQL setup is kept: a configured database_url option (or DATABASE_URL),
or the backend marker install-plugin.sh --postgres writes, always wins over the plugin's own
server and the SQLite default. An install that ran before on the local cortex database with nothing configured
keeps it: on its first launch Cortex moves to SQLite only when nothing listens on
localhost:5432 and no PG* variable configures PostgreSQL, records the choice, and prints it. A fresh install never connects to a database nothing configured.
The plugin was renamed hypermnesia-mcp in v4.15.0, after a community-directory collision
with an unrelated cortex plugin. Memories, configuration and storage paths are untouched.
claude plugin uninstall cortex
claude plugin install hypermnesia-mcpThe visualization companion, hypermnesia-mcp-viz, was renamed the same way:
claude plugin uninstall cortex-viz@cortex-plugins
claude plugin marketplace update cortex-plugins
claude plugin install hypermnesia-mcp-viz@cortex-pluginsThe retained cortex-viz@cortex-plugins entry is a frozen shim that only prints this notice
and exposes no server or tools.
Allowlists, hooks, skills and agents must migrate both composed tool names:
mcp__plugin_cortex-viz_cortex-viz__open_visualization becomes
mcp__plugin_hypermnesia-mcp-viz_hypermnesia-mcp-viz__open_visualization, and
mcp__plugin_cortex-viz_cortex-viz__get_methodology_graph becomes
mcp__plugin_hypermnesia-mcp-viz_hypermnesia-mcp-viz__get_methodology_graph.
Related MCP server: Claude Soul
Keep context useful
Across sessions, agents need to remember decisions, bring prior fixes back when a similar problem returns, and show you which sources support a memory so you can correct it. Cortex keeps that context available while making its status visible.
Cortex does this with local quality checks: what is written, whether its references resolve, what happens when a decision changes, and what can fade over time.
What gets in
The remember handler and automatic capture check for exact replays after hardening
and redaction. Matching domain, directory, agent topic, source, write class, capture origin,
and global/team flags produce reason: "exact_duplicate" with the existing memory id.
Forced writes retain this check; explicit supersedes_id corrections retain their atomic
supersession path. Benchmark rows are isolated, and memory-replica block replicas keep
their path identity. Direct store inserts do not use this handler check.
Consolidation supersedes existing exact duplicates within that scope and preserves their rows
and protection flags. This differs from the optional normalized-text maintenance pass.
Near-duplicate curation uses the thresholds in core/curation.py; deliberate writes bypass
the novelty threshold and can be stored separately when curation does not merge them.
// Illustrative project decision:
remember({ content: "Keep session state in Redis so TTL expiry is handled consistently." })
// → { stored: true, action: "stored" }Deliberate writes can be refused as exact replays; novelty alone does not reject them. Unattended capture must also pass the novelty check, which keeps automatic capture from burying the memories you meant to keep.
Whether it can be checked
Every memory is graded at write time, locally, with no network call. The grade is not a confidence score: it is whether the claims carry references that resolve on this machine.
// → provenance: { grade: "unverifiable",
// reason: "dead_refs: deps/numpy/_core/_multiarray_umath.cpython-313-darwin.so",
// hint: "1 of 9 checkable reference(s) could not be resolved" }That memory named a file that no longer existed, so it was stored and labelled unverifiable
instead of being silently presented as verified. Rewritten against paths that resolve, the same
memory grades verified. A recalled memory tells you which kind it is; a verified grade still
means that the references resolve locally, not that the claim has been independently proven true.
When it turns out wrong
Corrections supersede rather than overwrite. The new memory records what it replaces, the old one is demoted in recall, and the chain stays readable.
remember({ content: "...", supersedes_id: 4360411 })
// → { action: "superseded", memory_id: 4360412, superseded_id: 4360411 }Whether it was right
A memory records what happened. A prediction records what was expected before the outcome
was known, so that Cortex can later find out it was wrong. predict writes a falsifiable
claim with the confidence held at the time; resolve_prediction settles it against an
observation the caller supplies, naming the verdict, the kind of source that decided it and
a reference to that source; calibration scores the resolved set.
predict({ claim: "The p90 of the SQLite job is under 6 minutes",
prediction: "a 20-minute budget leaves headroom", test: "21 attempts of 2026-09-16",
confidence: 0.8 })
// → { prediction_id: 12, status: "open" }
resolve_prediction({ prediction_id: 12, verdict: "confirmed",
observed: "p90 348 s over 18 successes",
source_kind: "ci", source_ref: "cdeust/Cortex actions, 2026-09-16" })
// → { prediction_id: 12, verdict: "confirmed", resolved: true }
calibration()
// → { scored: 9, brier: 0.11, uninformative_brier: 0.25, confirmed: 7, refuted: 2,
// reliability: [{ band: [0.6, 0.8], resolved: 4, mean_confidence: 0.78,
// observed_frequency: 0.75 }, ...] }brier is the mean squared distance between confidence and outcome; 0.25 is what a constant
0.5 forecast earns, so a score above it means the confidences carried less information than
saying nothing. Cortex never fetches the evidence itself: the verdict, the observation and
the source reference come from the caller, which is what lets the same contract hold in any
repository and under any review convention.
What fades
Memories carry heat that decays unless replay reinforces them, and episodic traces can consolidate into semantic ones. A specific debugging session may compress to the principle it taught; the commands can fade while the lesson survives. This lifecycle is designed to keep the store useful as it grows, though it is not a promise of a fixed size or guaranteed semantic compression.
What it feels like in use
Here is an illustrative workflow: decisions, prior fixes, and source checks becoming useful again.
Monday. An hour debugging a webhook handler ends in a race condition: TTL expiry firing between the auth check and the permission lookup. You agree on a fix, implement it, close the session.
Thursday. In another session, a user reports intermittent logouts. Cortex surfaces relevant prior analysis, the Redis decision, and the TTL lesson when their content matches the new work.
Three weeks later. The sessions can consolidate into a pattern about authentication and TTL-based caches; some details may fade while the principle remains useful.
In Claude Code and Codex alike that is automatic: 11 lifecycle hooks inject context at session
start, recall per prompt, capture as you work, checkpoint before compaction, and run a wiki that
curates itself. In any other stdio MCP host you call the same 57 tools yourself, or 60 when
the optional ai-architect-mcp-codebase and ai-architect-mcp-spec integrations are present.
Does the retrieval work
Measured against a published benchmark, retrieval only. No LLM reader in the loop: the question is whether the right memory surfaces, not whether a model can write a good answer from it.
LongMemEval: 500 human-curated questions buried in about 40 sessions of history.
v4.14.1 (historical) | v4.20.0 (current release) | |
Recall@10 | 98.2% | 97.8% |
MRR | 0.9167 | 0.905 |
Both are single runs: n=500, consolidation disabled, retrieval only. Both describe the
PostgreSQL store with the cross-encoder reranker: the harness (benchmarks/lib/bench_db.py)
always builds a PgMemoryStore and calls core.pg_recall, and both artifacts record
"reranker_state": "loaded". The v4.20.0 run used a clean database in the ephemeral
pgvector/pgvector:pg16 container of benchmarks/reproduce.sh (its manifest records that
pg_image); the v4.14.1 run did not use that container and ran against the live PostgreSQL
store (CHANGELOG 4.14.1, "Verified").
The default SQLite store has no comparable run yet (n=500, reranker loaded;
#708), so these figures do not describe it.
The best SQLite LongMemEval-S result is a bounded run without the reranker (n=50,
sentence-transformers embeddings: MRR 0.609, Recall@10 94.0%,
benchmarks/results/semantic-fallback-169).
v4.14.1, 2026-07-14: artifact JSON; code SHA. This is the run the ablation campaign in Verification was built around.
v4.20.0, 2026-09-09: artifact JSON and its
manifest; code SHA,
dirty=false. A single run of the LongMemEval-S leg alone (benchmarks/reproduce.sh --only longmemeval --no-ablation) in an isolated ephemeral PostgreSQL container, reranker loaded, consolidation
disabled. Against v4.14.1 the change is 0.4 points of Recall@10 and 0.012 of MRR. The run's own
floor check reports Recall@10 within the 0.005 tolerance of the July floor (0.982) and MRR
0.0093 below its floor (0.914), which the script treats as non-blocking by design. The same
tree has no LoCoMo or BEAM figure yet.
Reproduce with benchmarks/reproduce.sh, which runs in an isolated ephemeral container, never
against a live store.
Recall@10 is the share of questions whose answer-bearing session appears in the first ten retrieved sessions. MRR (mean reciprocal rank) rewards finding that session near the top. These numbers describe retrieval only; they do not measure whether an LLM writes a correct answer.
Retrieval fuses vector similarity, full-text search, trigram match, heat and recency, then reranks with a cross-encoder. PostgreSQL combines the signals as a weighted sum; SQLite uses weighted reciprocal-rank fusion and has no trigram signal. LoCoMo and BEAM results, the ablations and the floor gates are in benchmarks/.
Storage
SQLite by default, or the plugin's own PostgreSQL server on a fresh macOS or Linux install (see Install). Your own PostgreSQL is one configuration field, worth it for very large stores or a database shared across a team.
bash <plugin-dir>/scripts/install-plugin.sh --postgresSQLite (default) | PostgreSQL 15+ | |
Setup | none | pgvector >= 0.8.0, pg_trgm |
All 57 tools | yes | yes |
Retrieval tool interface | identical | identical |
Published retrieval quality | n=50 without reranker only (#708) | LongMemEval-S n=500 above |
Fusion | in-process | server-side PL/pgSQL |
ANN index | none | pgvector HNSW |
Cross-agent team decisions, preemptive context, pipeline heat bumps | no-op | active |
Three hook enrichments are PostgreSQL-only and degrade to silent no-ops on SQLite. Session banners, auto-recall, auto-capture, checkpoints and every memory tool work on both.
Cortex in Codex and Claude Code
Both plugins expose the complete memory tool profile and use the same 11 Cortex hook modules. They share project-associated memories when connected to the same store, so a decision saved in Claude can be recalled in Codex and vice versa.
With the native Codex plugin installed and its hooks trusted, Cortex:
Restores project context when a session starts and recalls relevant memories as you submit prompts.
Captures significant tool results automatically, keeping useful work available across sessions.
Preserves session state through compaction checkpoints and durable session-end recording.
Briefs subagents with project and role context.
Provides the full memory toolset for decisions, lessons, wiki pages, ADRs, predictions, calibration, triggers, rules and codebase ingestion.
Shares memories with Claude Code when both use the same store and project association. You can switch agents and retrieve what the other saved.
Claude Code uses the same Cortex memory tools and hook modules. Both plugins support the autonomous wiki cycle, SQLite storage and optional PostgreSQL.
Verified on installed hosts: Claude wrote a random test payload and Codex retrieved it; Codex wrote another and a fresh Claude session retrieved it. Neither read prompt supplied the expected payload. Both hosts excluded the test record when recalling from another project, and both delivered Cortex context through native startup hooks. Read the verification and tool traces.
Hook trust is part of Codex setup: review /hooks after installation or a changed
hook definition, then start a fresh session. Event mapping, task-context handling
and session-end delivery are documented in the Codex integration guide.
Cognitive profiles are shared too; the current profile builder derives them from
Claude Code session logs, so that historical input must exist for either host to
retrieve a populated profile.
Every other MCP host
Any host that can launch the stdio server gets the complete memory tool profile,
with SQLite by default and PostgreSQL as an option. A direct MCP registration,
including codex mcp add, provides explicit remember and recall tools.
Automatic lifecycle behavior comes with the native Claude Code or Codex plugin.
The Claude Desktop bundle provides tools without hooks. ChatGPT web would require
a remote deployment; this repository ships a local stdio server.
The launch command on every host is the PyPI package. The [sqlite] extra enables
sqlite-vec vector search; without it the store still works, with vector search disabled.
uvx --from "hypermnesia-mcp[sqlite]" hypermnesia-mcpGemini CLI ships as an extension (gemini-extension.json is in this repository):
gemini extensions install https://github.com/cdeust/CortexCodex and ChatGPT desktop have a native plugin with the full tool surface and the same
11 lifecycle hooks the Claude Code plugin installs. It reads the
same saved backend selection as the Claude Code launcher (~/.claude/methodology/backend.json),
so both hosts write to one store (since 4.23.0); explicit CORTEX_MEMORY_STORE_BACKEND, CORTEX_BACKEND or a database URL
still wins. Pre-install
the package once so the plugin's first uvx handshake reuses the local uv cache instead of
spending its startup budget downloading a Python environment:
uv tool install "hypermnesia-mcp[sqlite]"
codex plugin marketplace add cdeust/Cortex
codex plugin add hypermnesia-mcp-codex@cortex-codex-pluginsThe direct fallback registers the executable without the plugin:
codex mcp add cortex --env CORTEX_MEMORY_STORE_BACKEND=sqlite -- hypermnesia-mcpThe host boundary, the measured startup ceiling and the public-directory requirements Cortex deliberately does not claim are in docs/codex-plugin.md.
Green software engineering
Cortex runs a standing efficiency programme, gated by the same evidence rule as the retrieval work: no unsourced efficiency claim ships. Waste is treated as a defect with a reproduction, not as a virtue to advertise.
The measurement harness — and what it does not establish
benchmarks/energy/ implements the Green Software Foundation SCI
specification: operational emissions
O = E × I, embodied allocation M = TE × TS × RS, reported per functional
unit. For the embedding path the functional unit is 1000 model input tokens,
counted from the tokenizer's own attention_mask — never estimated from
characters.
Read benchmarks/energy/README.md before quoting anything from it. Its own
first paragraph is the important one: the automated fixtures exercise arithmetic
and failure paths, they do not measure device energy and do not establish an
energy improvement. Further, by design:
No default carbon factors.
--carbon-intensity(gCO2eq/kWh) and--embodied(gCO2eq/s, an already allocated rate) are mandatory operator inputs, validated before any model import. The harness records the values and their units; it does not vouch for their provenance. You supply the region, observation period, lifecycle assessment and reservation assumptions.A stated boundary.
raw_system_energy_jis the sensor's combined CPU+GPU+ANE estimate. It is neither wall-plug energy nor a complete device SCI score: memory, storage, screen, power-supply losses, model warm-up and token counting are all excluded.Artifacts or it did not happen. A successful run preserves
results.json, aMANIFEST.jsonof commit and source hashes, and the exact analyzedpowermetrics.txtsnapshot.
Energy results measured on real benchmark runs are now committed, under
benchmarks/results/energy/, each with its raw powermetrics.txt, its phase
timeline and its manifest. A committed figure is a measurement on one
operator's machine, region and duty cycle, not a property of the software,
and is always quoted with those limits: the whole-run figure per query is an
upper bound (it includes ingestion, embedding and database work), no energy
spent on the model side is claimed, and the carbon intensity is an operator
input quoted with its source. See benchmarks/energy/README.md, Benchmark
phases.
What has actually shipped
Efficiency work lands as ordinary reviewed PRs. Two workstreams are merged:
Workstream | Change | PR |
CI / build | run pytest once, on the coverage leg, instead of twice | |
build runtime images only on Docker changes + a weekly validation | ||
cache pinned dependency and actionlint downloads | ||
sdist under 5 MB, with a byte-identical wheel | ||
measured job timeouts; cancel superseded PR runs | ||
bound the local Docker build context | ||
stop exporting an unreadable layer cache on every PR run | ||
Runtime | defer unused pipeline hook imports | |
route PostToolUse hooks by the tool names they handle | ||
audit and clean orphan plugin dependencies | ||
rotate telemetry and detached-worker logs | ||
persist hook cascade cadence; cool down misses | ||
pinned CPU-only Torch on Linux — no CUDA payload pulled |
The hook work is the load-bearing one, because hooks run on every tool event.
Deferring the handler/store stack keeps hook boot at ~0.05 s against
~0.6 s for the full registry import (measured 2026-07-28; the constant is
cited in mcp_server/hooks/auto_recall.py at its call sites, per the
no-invented-constants rule).
Demand reduction is the primary lever
The largest efficiency term in an LLM-assisted workflow is not this server's own
CPU — it is the tokens a model must process because the right context was not
found the first time. That makes retrieval quality an energy property, and it is
why the benchmark tables above and this section are the same programme:
response_budget.py bounds a payload and keeps ids so truncation stays
resumable, the reranker degrades to first-stage scores rather than fetching a
model, and CORTEX_RERANKER_OFFLINE=1 refuses the download outright.
This paragraph is a design rationale, not a measurement. Cortex publishes no token-savings or CO2 figure for end-to-end agent sessions, because it has not measured one.
Verification
The retrieval scores above describe particular runs of the integrated system. They do not establish a causal retrieval benefit from the 36 mechanisms. The committed evidence is mixed:
LongMemEval-S, 17 rows, n=500 — report and summary CSV. Spreading activation has the same reported MRR and R@10 as baseline; ablating adaptive decay raises MRR from 0.9124 to 0.9138. Several mechanisms have identical scores. These isolated-haystack runs do not establish benefits from longitudinal state.
LoCoMo, 14 rows, n=1986 — pre-fix report and run manifest. Some rows favor a mechanism and others favor its ablation; this is not evidence that every mechanism helps. The post-fix report is explicitly unverified because its named result artifacts are not committed.
BEAM decay sweep — the June 11 control summary reports MRR 0.694 for both lambda 0.95 and 1.0. This run shows no retrieval gain from decay.
Mechanisms remain available for inspection and evaluation. A claim that they improve retrieval requires a longitudinal evaluation on real data, with per-mechanism ablations and per-question results; that work is tracked in #343. A null result under these conditions neither proves general benefit nor proves a mechanism cannot help in another setting.
The thermodynamic paper (§6.3–6.4) discusses these experiments, including a negative decay result after a dirty-store confound. Its design rationale does not replace empirical evidence. Thermodynamic Memory vs. Flat-Importance Stores (PDF, 34 pages) · Stage-Aware Context Assembly (PDF, 39 pages).
Under the hood
The mechanisms above are implemented as 36 system mechanisms spanning encoding, consolidation, retrieval and forgetting. Each is cited to published work and exposed as a live system vital. The bibliography is the check: its entry count is what the references badge reports, and a gate fails the build if the two disagree.
Clean Architecture, concentric layers: server → handlers → core ← shared, and
infrastructure → shared. Core is pure and testable without mocks.
docs/agent-guidance.md is the map;
docs/mcp-tools.md is the tool reference.
Where Claude's memories go follows a memory from the hook that captures it to the recall that brings it back, and a decision from its ADR file to the session that reads it, with every claim linked to the lines of the v4.22.0 release (en français).
Limits worth knowing before you install
Automatic capture and context injection are provided by the native Claude Code and Codex plugins. Direct MCP connections use explicit memory tools.
SQLite fusion is in-process and unindexed. Fine at personal scale, slower at very large one.
The retrieval scores above are retrieval-only. They say nothing about answer quality.
Provenance grading is local and structural. It checks that a reference resolves, not that a claim is true; a DOI or arXiv link is never auto-verified.
No energy or carbon figure is published, for the reasons stated above.
First use downloads both the embedding and reranking model files. Optional integrations, remote PostgreSQL and OTLP telemetry add network activity only when explicitly configured; see PRIVACY.md.
Security
Runs 100% locally — MCP over stdio, the storage backend (SQLite file or PostgreSQL on localhost) never leaves your machine (the optional hypermnesia-mcp-viz companion binds its server to 127.0.0.1). No data leaves your machine. SafeSkill scan: 94/100 (code 97, content 88 — docs/safeskill-report.json).
Privacy Policy
Cortex is local-first: your memories, conversations, and profiles stay on your machine — stored in a local SQLite database (~/.claude/methodology/memory.db) by default, or in a PostgreSQL database you control. Cortex sends no memories, content, or telemetry to the author, Anthropic, or any third party. The only outbound network activity is a one-time download of open-source embedding/reranking models from Hugging Face (model files only), plus any integrations you explicitly configure. Full policy: PRIVACY.md.
Support
Issues & bug reports: GitHub Issues
Security disclosures: see SECURITY.md
Contact: admin@ai-architect.tools
Development
pytest # full suite; assets/badge-tests.svg carries the current count
ruff check . && ruff format --check . # lint and format, both enforced in CI
python scripts/check_doc_claims.py # advertised counts must match the repo
python scripts/check_craftsmanship.py # file and method caps, layer whitelist, sourced constantsCONTRIBUTING.md describes the gates a change has to clear. GOVERNANCE.md says who decides and what happens if the maintainer stops. docs/ROADMAP.md says where the project is going, and docs/ASSURANCE-CASE.md states the security argument and its limits. CHANGELOG.md is the complete release history.
License
MIT — see LICENSE.
This software is the independent work of Clément Deust. It was developed outside any employment relationship and is not affiliated with, endorsed by, or owned by any past or present employer. It is part of the ai-architect ecosystem (zetetic-team-subagents, ai-architect-mcp-codebase, ai-architect-mcp-spec).
The neuroscience and information-retrieval algorithms encoded in this software are derived
from published academic work cited in
docs/papers/bibliography.md and inline in the source via
# source: annotations (Friston on predictive coding, Anderson & Lebiere on rate-distortion
forgetting, Nader et al. on retrieval-induced lability, McClelland et al. on consolidation,
and others). The MIT license covers this implementation; it does not assert ownership over
the underlying mechanisms, which remain attributable to their original authors and
publications.
Citation
The paper PDFs on main are the canonical artefacts (arXiv IDs forthcoming, endorsement in
progress):
@software{cortex2026,
title={Cortex: Persistent Memory for Claude Code},
author={Deust, Clement},
year={2026},
url={https://github.com/cdeust/Cortex}
}
@unpublished{deust2026thermodynamic,
title={Thermodynamic Memory vs. Flat-Importance Stores:
Why Long-Term Retrieval Collapses Without Decay},
author={Deust, Clement},
year={2026},
note={arXiv ID forthcoming, endorsement in progress},
url={https://github.com/cdeust/Cortex/blob/main/docs/arxiv-thermodynamic/main.pdf}
}
@unpublished{deust2026context,
title={Stage-Aware Context Assembly for Long-Context Memory Retrieval},
author={Deust, Clement},
year={2026},
note={arXiv ID forthcoming, endorsement in progress},
url={https://github.com/cdeust/Cortex/blob/main/docs/arxiv-context-assembly/main.pdf}
}Available Tools
40 toolsadd_ruleC
Add a neuro-symbolic rule to the memory store. Rules hard-filter or soft-rerank recall results based on conditions.
Inputs: condition (required), action (required), rule_type, scope, +2 more. Returns: result
anchorA
Mark a memory as compaction-resistant. Anchored memories survive context compaction, heat decay, and cannot be deleted without force. Use for critical facts and active decisions.
Inputs: memory_id (required), reason. Returns: result
assess_coverageC
Evaluate knowledge coverage completeness for a project directory. Returns a 0-100 coverage score and actionable recommendations.
Inputs: directory, domain, stale_days. Returns: result
backfill_memoriesA
Auto-import prior Claude Code conversations into the memory store. Idempotent -- tracks already-processed session files by hash. Links historical work to core concepts automatically.
Inputs: project, max_files, min_importance, dry_run, +1 more. Returns: result
checkpointC
Hippocampal replay: save/restore working state across context compaction events.
Inputs: action (required), directory, current_task, files_being_edited, +6 more. Returns: result
codebase_analyzeA
Analyze a codebase and store its structure as Cortex memories. Uses tree-sitter AST for cross-file resolution, call graphs, and community detection. Incremental: only processes changed files.
Inputs: directory, languages, max_files, max_file_size_kb, +3 more. Returns: result
consolidateB
Run memory maintenance: heat decay, compression, and CLS consolidation cycles.
Inputs: decay, compress, cls, memify, +1 more. Returns: result
create_triggerB
Create a prospective memory trigger: a future-oriented reminder that fires when a condition is met (keyword, time, file, or domain).
Inputs: content (required), trigger_condition (required), trigger_type, target_directory. Returns: result
detect_domainB
Lightweight domain classification from cwd, project, or first message. <20ms.
Inputs: cwd, project, first_message. Returns: result
detect_gapsB
Identify knowledge gaps in the memory store: isolated entities, sparse domains, temporal drift, and low-heat topic clusters.
Inputs: domain, include_entity_gaps, include_domain_gaps, include_temporal_gaps, +1 more. Returns: result
drill_downC
Navigate into a fractal memory cluster. L2 cluster → shows L1 child clusters. L1 cluster → shows individual memories.
Inputs: cluster_id (required), domain, min_heat. Returns: result
explore_featuresC
Explore interpretability features: dictionary features, attribution graphs, persona vectors, and cross-domain behavioral persistence. Inspired by Anthropic's mechanistic interpretability research.
Inputs: mode (required), domain, compare_domain. Returns: result
forgetA
Delete a memory by ID. Supports soft (mark stale) or hard (permanent) deletion. Protected memories require force=True.
Inputs: memory_id (required), soft, force. Returns: result
get_causal_chainC
Trace entity relationships through the knowledge graph. Returns causal/dependency chains from a starting entity or memory.
Inputs: entity_name, memory_id, relationship_types, max_depth, +1 more. Returns: result
get_methodology_graphB
Returns methodology map as graph data for 3D visualization. <100ms.
Inputs: domain. Returns: result
get_project_storyC
Generate a period-based autobiographical narrative of project activity. Returns chronological 'chapters' of what happened during a time period.
Inputs: directory, domain, period, max_chapters. Returns: result
get_rulesB
List active neuro-symbolic rules in the memory store, optionally filtered by scope or rule type.
Inputs: scope, rule_type, include_inactive. Returns: result
import_sessionsB
Import conversation history from ~/.claude/projects/ into the memory store. Extracts decisions, errors, architecture notes, and key insights from JSONL sessions.
Inputs: project, domain, min_importance, max_sessions, +2 more. Returns: result
list_domainsB
Overview of all detected cognitive domains. <10ms.
Inputs: no named parameters. Returns: result
memory_statsC
Memory system diagnostics: counts, heat distribution, entities, triggers.
Inputs: no named parameters. Returns: result
narrativeC
Generate a project narrative/story from stored memories for a directory or domain.
Inputs: directory, domain, brief. Returns: result
open_visualizationB
Launch the unified 3D neural graph in the browser. Combines methodology profiles, memories, and knowledge graph.
Inputs: domain. Returns: result
query_methodologyA
Returns the user's cognitive profile for the current domain. Pre-computed, <50ms. Use at session start for context injection.
Inputs: cwd, project, first_message. Returns: result
rate_memoryB
Rate a memory as useful or not. Drives metamemory confidence which affects decay resistance and recall ranking.
Inputs: memory_id (required), useful (required). Returns: result
rebuild_profilesB
Full rescan of all session data to rebuild methodology profiles. <10s.
Inputs: domain, force. Returns: result
recallC
Retrieve memories using intent-adaptive PG recall with production enrichments.
Inputs: query (required), domain, directory, max_results, +2 more. Returns: result
recall_hierarchicalA
Retrieve memories using the fractal hierarchy (L0/L1/L2 clusters). Adaptive weighting based on query length — short queries search broad, long queries search specific.
Inputs: query (required), domain, max_results, min_heat, +1 more. Returns: result
record_session_endC
Incremental profile update after a session ends. <200ms.
Inputs: session_id (required), domain, tools_used, duration, +4 more. Returns: result
rememberD
Store a memory through the predictive coding write gate.
Inputs: content (required), tags, directory, domain, +3 more. Returns: result
run_pipelineC
Drive the ai-architect pipeline end-to-end: discovery -> impact -> strategy -> PRD -> verification -> implementation -> PR. Connects to ai-architect MCP server over stdio.
Inputs: codebase_path (required), task_path (required), context_path, github_repo, +2 more. Returns: result
seed_projectC
Bootstrap memory from an existing codebase. Analyzes structure, config, docs, entry points, and CI/CD. Stores key discoveries as memories.
Inputs: directory, domain, max_file_size_kb, dry_run. Returns: result
sync_instructionsB
Sync top memory insights into CLAUDE.md for the project directory. Adds or refreshes a '## Memory Insights' section.
Inputs: directory, max_insights, min_heat, dry_run. Returns: result
validate_memoryB
Validate memories against current filesystem state. Marks stale memories whose referenced files no longer exist.
Inputs: memory_id, domain, directory, base_dir, +2 more. Returns: result
wiki_adrC
Create a numbered ADR (architecture decision record) from structured fields. Auto-increments the ADR number.
Inputs: title (required), context (required), decision (required), consequences (required), +2 more. Returns: result
wiki_linkA
Add a bidirectional link between two wiki pages. Updates the Related section of both files. Idempotent.
Inputs: from_path (required), to_path (required), relation (required). Returns: result
wiki_listB
List authored wiki pages. Optionally filter by kind (adr/specs/files/notes).
Inputs: kind. Returns: result
wiki_readA
Read the raw markdown of a wiki page by its relative path.
Inputs: path (required). Returns: result
wiki_reindexA
Regenerate the wiki table of contents at .generated/INDEX.md. Authored pages are never touched.
Inputs: no named parameters. Returns: result
wiki_writeA
Author a wiki page (adr/specs/files/notes) or append/replace an existing one. Pages live under ~/.claude/methodology/wiki/ and are indexed in PostgreSQL as protected pointer memories for recall.
Inputs: path (required), content (required), mode, tags. Returns: result
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 40 tools
The tools cover distinct functional areas (memory management, wiki operations, methodology analysis, etc.), but there is some overlap that could cause confusion. For example, 'recall' and 'recall_hierarchical' both retrieve memories with different algorithms, and 'backfill_memories' and 'import_sessions' both import conversation history, which might lead to misselection by an agent without careful reading of descriptions.
Most tools follow a consistent verb_noun or verb_adjective_noun pattern (e.g., 'add_rule', 'anchor', 'assess_coverage'), with clear and descriptive names. However, there are minor deviations like 'wiki_adr' (which mixes a prefix with an acronym) and 'run_pipeline' (which is less structured), slightly reducing consistency.
With 40 tools, the count is excessive for a single server, making it heavy and potentially overwhelming for agents to navigate. While the domain (cognitive memory and project management) is broad, the toolset feels bloated with many specialized operations that could have been grouped or streamlined, indicating poor scoping.
The tool set provides comprehensive coverage for memory storage, retrieval, maintenance, wiki management, and project analysis, with clear CRUD and lifecycle operations (e.g., 'remember', 'recall', 'forget', 'validate_memory'). There are no obvious gaps; it supports end-to-end workflows from data ingestion to visualization and narrative generation.
Maintenance
Related MCP Connectors
Persistent memory and cross-session learning for AI coding assistants (hosted remote MCP).
Persistent AI memory shared across Claude, ChatGPT, coding agents, and compatible MCP clients.
Private persistent memory for Claude, ChatGPT & Gemini via MCP - semantic search, zero-code setup.
Persistent cross-session memory shared by Codex, Claude Code, ChatGPT, and other AI agents.
Related MCP Servers
- AlicenseNot gradedqualityAmaintenanceGives Claude Code persistent cross-session memory with semantic search, automatic detection and classification of user corrections, and evolving behavioral frameworks that develop over time. Runs fully locally through Claude Code's hooks and 15 MCP tools, requiring no API key or cloud service.6 npmMIT
- AlicenseNot gradedqualityAmaintenanceGives Claude Code persistent memory across sessions, detecting and classifying user corrections, and evolving behavioral frameworks from accumulated evidence. Exposes 15 MCP tools for semantic memory search, signal recording, self-evaluation, and reflection cycles that run locally alongside automatic hooks.6 npmMIT
- FlicenseNot gradedqualityAmaintenanceEnables Claude Code to store, search, update, and delete persistent memories across sessions, backed by self-hosted Qdrant vector storage, an optional Neo4j knowledge graph, and Ollama embeddings, with Anthropic or Ollama as the main LLM. Exposes 11 MCP tools plus session hooks and a CLAUDE.md guide so context is injected at startup and saved automatically at session end.-
- AlicenseNot gradedqualityAmaintenanceGives Claude Code persistent cross-session memory with semantic search over facts, decisions, and lessons, plus automatic tracking of user corrections and behavioral patterns. Enables a Claude that evolves reusable frameworks over time — promoting what works and retiring what doesn't — all locally through MCP tools and hooks.6 npmMIT