# cdeust/Cortex [Health: Active]

**Category:** 🧠 Knowledge & Memory  
**Repository:** https://github.com/cdeust/Cortex  
**GitHub Stars:** 78  
**Views:** 6  
**Installs:** 0  
**Upvotes:** 0  
**Directory Page:** https://allmcps.com/mcp/cdeust-cortex

## Description
Persistent memory for Claude Code grounded in computational neuroscience (41 cited papers). Thermodynamic decay, hippocampal-cortical consolidation, predictive-coding write gate, WRRF retrieval. PostgreSQL + pgvector, 33 MCP tools, 7 lifecycle hooks. Benchmarked 97.8% R@10 on LongMemEval. claude plugin marketplace add cdeust/Cortex

## Tools
Capabilities this server exposes over MCP:

- **query_methodology** — Read the user's cognitive profile for the current domain from the cached profiles.json and enrich it with hot memories + any fired prospective triggers matching the current cwd / first_message. Profile fields: thinking style (Felder-Silverman), entry patterns, recurring patterns, blind spots, cross-domain bridges, behavioral feature activations. MANDATORY at session start so subsequent reasoning is calibrated to the user's tendencies. Distinct from `rebuild_profiles` (full rescan from JSONL transcripts, much slower), `detect_domain` (just classifies, no profile body), and `list_domains` (overview across all domains). Read-only on profiles.json; mutates triggered_count for any prospective triggers that fire. Latency <50ms (cached). Returns the full profile dict + hotMemories + firedTriggers, or coldStart=true if no profile exists yet (then call `rebuild_profiles`).
- **detect_domain** — Classify the current working directory + first message into one of the known cognitive domains via a 3-signal weighted score: (1) path tokens (last 3 segments + git root), (2) project ID match against known profiles, (3) keyword overlap with stored domain vocabularies. Returns the best-matching domain plus confidence and the runner-up alternatives. Use this when switching codebases or contexts to recalibrate, or as a cheap preflight before `query_methodology` / `recall`. Distinct from `query_methodology` (returns the FULL profile body, not just the domain id), `list_domains` (enumerates ALL domains), and `rebuild_profiles` (rescans, doesn't classify). Read-only. Latency <20ms. Returns {domain, confidence, alternativeDomains, signals}.
- **rebuild_profiles** — Full rescan of Claude Code and Codex session data to rebuild methodology profiles. Walks ~/.claude/projects/ and Codex rollouts under $CODEX_HOME/sessions/ (default ~/.codex/sessions/), parses the JSONL transcripts, groups both by project (a Codex rollout's working directory names its project), and re-derives per-domain cognitive style (Felder-Silverman), entry patterns, blind spots, and cross-domain bridges via the profile_assembler pipeline. Use this on first install, after a major workflow change, or when `query_methodology` returns coldStart=true. Skipped automatically if profiles are <1h old unless force=true, which only bypasses that freshness check and never replaces a profile. A present but unparseable or timezone-naive updatedAt raises an error; rerun with force=true to bypass freshness metadata. Transcripts on disk are a sliding window (Claude Code deletes old ones) while a stored profile accumulates one session per `record_session_end`, so a domain whose scan sees fewer sessions than its stored profile records is KEPT unchanged and reported; only replace_accumulated_profiles=true replaces it with the smaller scan. Distinct from `query_methodology` (read the cached profile, no rescan), `record_session_end` (incremental EMA update for one session, no full rebuild), and `detect_domain` (just classifies, doesn't rebuild). Mutates ~/.claude/methodology/profiles.json. Latency <10s on typical histories. Returns {domains, totalSessions, totalMemories, duration, domainOutcomes: [{domain, action (created|rebuilt|kept|replaced), storedSessions, scannedSessions, resultingSessions}]}.
- **list_domains** — Read profiles.json and emit an overview row for every cognitive domain Cortex has profiled, sorted by session count. Per domain: id, human label, sessionCount, confidence, lastActive, top-3 work categories with ratios, and dominantMode from the session shape. Use this to discover what domains exist before scoping `recall`, `narrate`, or `rebuild_profiles`. Distinct from `query_methodology` (deep profile for ONE domain), `detect_domain` (classifies the current context, no enumeration), and `memory_stats` (memory-system counts, not domain profiles). Read-only. Takes no arguments. Latency <10ms. Returns {domains: [{id, label, sessionCount, confidence, lastActive, topCategories, dominantMode}], totalDomains, globalStyle}.
- **record_session_end** — Record session-end signals (tools used, duration, turns, keywords) and apply an incremental EMA update to the matching domain's cognitive profile. Also stores an episodic session-summary memory, runs a session self-critique (overall score + top improvement suggestions — each non-empty suggestion is ALSO persisted as its own 'lesson-candidate'-tagged memory, M-D6, so it is never lost the moment this call returns), and creates prospective triggers from any TODO/decision keywords detected in the message stream. Normally invoked automatically by the SessionEnd hook — call manually only when reconstructing offline sessions. Distinct from `rebuild_profiles` (full rescan; keeps a stored profile that records more sessions than the scan sees) and `query_methodology` (read-only profile retrieval). Mutates profiles.json + session-log.json + memories table. Latency <200ms. Returns {domain, profile_updated, session_score, critique, lessonCandidatesStored, memory_id?}.
- **explore_features** — Inspect the user's cognitive profile through one of four interpretability lenses (mechanistic-interpretability inspired, Bricken et al. 2023): `features` returns the sparse behavioral feature dictionary and the cross-domain persistent features; `attribution` perturbation-traces which input signals drove the domain's profile, sampling up to 20 of that domain's own recent sessions from disk (empty graph if the domain has no indexed sessions -- run rebuild_profiles first); `persona` returns the 9D persona vector of one domain, or of every domain with their session-weighted composition; `crosscoder` compares two domains (shared and unique active features), or without both returns the features persistent across all domains. Use this when facing an unfamiliar pattern and you want a behavioral explanation. Distinct from `query_methodology` (full profile, not the interpretability internals) and `list_domains` (overview, no analysis). Read-only on profiles.json. Latency <100ms. Every response carries `mode` and `status`. status=ok adds the lens's keys: features → dictionary, persistentFeatures; attribution → domain, graph; persona → domain, persona, dimensions (or domains, global, dimensions without domain); crosscoder → comparison (or persistentFeatures, domainCount without both domains). status=no_data or error adds only message. An unknown mode is rejected as invalid input.
- **remember** — Store a memory through the flat 4-signal predictive-coding write gate (embedding, entity, temporal, and structural novelty — Friston-inspired prediction-error gating). Novel surprising content passes; redundant content is rejected or merged with the most-similar existing memory via active curation. After write: thermodynamic tagging, knowledge-graph entity extraction, neuromodulation (DA/NE/ACh/5-HT), engram allocation. FOR A DURABLE CLAIM (a fact, decision, or lesson meant to outlive this session), include a checkable reference in `content` — a file path, a git commit SHA, a URL, or a content-addressed artifact digest — so it can grade above 'unverifiable' (see the `provenance` response field and coding-standards.md §8, 'no source, no implementation'); testimony without one is still stored, just graded accordingly. Use this after any non-trivial discovery, fix, decision, or lesson — if it would surprise a future session, store it. Distinct from `anchor` (pins an EXISTING memory, doesn't create), `wiki_write` (creates an .md page, not a memory row), `validate_memory` (re-grades EXISTING memories with network-verified checks, not a write path), and `add_rule` (recall-time filter, not stored content). Mutates memories + entities + relationships tables. Latency ~50-100ms. Returns {stored, memory_id, action: stored|merged|rejected, reason, provenance}.
- **recall** — Retrieve memories from the Cortex store using intent-adaptive PG recall (server-side fusion of vector + FTS + trigram + heat + recency: a weighted sum on PostgreSQL, rank-based WRRF on SQLite) followed by FlashRank cross-encoder reranking and production enrichments (prospective memory injection, Hebbian co-activation strengthening, neuro-symbolic rules, strategic ordering to mitigate Lost-in-the-Middle, Liu et al. 2023). Use this before any non-trivial work to check what Cortex already knows; running blind is unacceptable when recall takes ~200ms. Distinct from `recall_hierarchical` (returns the L0/L1/L2 cluster topology, not a flat ranked list), `navigate_memory` (graph BFS over co-access edges from one seed memory), and `get_causal_chain` (entity-graph traversal, not memory recall). Not read-only: every returned memory is recorded as a hippocampal replay event — access_count/replay_count increment and hippocampal_dependency decays (CLS-B, Ketz et al. 2023) — so repeat calls are not idempotent (`track_replay_event`, `replay_tracking.py`). Returns ranked memories with scores, heat, and source. Bare ADR-NNNN queries resolve the canonical wiki page before semantic retrieval; project_root explicitly selects a tracked project wiki. Page longer decisions with the same query and content_offset.
- **unified_search** — Unified search across Cortex memories and the automatised-pipeline code graph. Runs cortex.recall and ap.search_codebase in parallel, then merges via Reciprocal Rank Fusion (k=60). Returns a single ranked list with ``source_ranks`` on every record so the UI can explain where each hit came from. Falls back to Cortex-only when AP is disabled (CORTEX_MEMORY_AP_ENABLED=0) or unreachable (status=partial). An explicit project_root adds authored wiki pages matching every query token. Bare ADR-NNNN or exact_id queries resolve only the canonical wiki page, before memory/AP calls.
- **memory_stats** — Aggregate population diagnostics for the memory system: total / episodic / semantic / active / archived / stale / protected memory counts, average heat, entity and relationship totals, active prospective triggers, last consolidation timestamp, and vector-search availability (pgvector). Use this for health checks, dashboards, or before/after a `consolidate` run to verify cycles fired. Distinct from `assess_coverage` (scored 0-100 with recommendations, this is raw counts), `detect_gaps` (enumerates specific missing things), and `list_domains` (per-domain profile rows, not memory counts). Read-only. Takes no arguments. Latency ~75ms (includes the grooming-staleness ages below). Returns {total_memories, episodic_count, semantic_count, active_count, archived_count, stale_count, protected_count, avg_heat, total_entities, total_relationships, active_triggers, last_consolidation, has_vector_search, grooming_staleness, abandoned_workers}. `grooming_staleness` carries last-run age (days) for the three judgment-level grooming kinds (wiki/distillation/promotion) against a sourced threshold -- ages only, no backlog counts (those cost ~1s combined; call `get_grooming_health` for the full picture). `abandoned_workers` reports, per tool, the workers of this server process still running after their caller was cancelled (`in_flight`) and how abandoned workers ended since the process started (`ended`: completed / raised / cancelled): an abandoned mutating call that completed applied its writes although its caller never received the result.
- **checkpoint** — Hippocampal-replay-style save/restore of whole working state across context compaction events (McClelland 1995). `save` writes a checkpoint row capturing current task, files-being-edited, key decisions, open questions, planned next steps, and active errors, tied to the current epoch. `restore` reconstructs post-compaction context by fusing the latest checkpoint with anchored + hot + directory-relevant memories. Use `save` before risking compaction; use `restore` immediately after. Distinct from `anchor` (per-memory pinning, no task state), `remember` (creates one memory, no whole-state snapshot), and `query_methodology` (cognitive profile, not session state). Mutates the checkpoints table on save; read-only on restore. Latency ~50ms (save) / ~100ms (restore). Returns {action, checkpoint_id, restored_context?, memories_attached}.
- **narrative** — Generate a coherent project narrative from stored memories for a directory or domain. Clusters memories by topic + time, identifies the through-line, and renders either a multi-section story or (when `brief=true`) a one-paragraph executive summary. Use this for status updates, README seeds, or to onboard a new contributor with the project's actual history. Distinct from `get_project_story` (period-bucketed chronological chapters with explicit time ranges), `assess_coverage` (numeric score, no prose), and `recall` (raw ranked memories). Read-only. Latency ~300-800ms. Returns {narrative, memory_count, themes}.
- **consolidate** — Run scheduled memory-system maintenance cycles: thermodynamic heat decay, scoped exact-replay consolidation (exact_duplicates counters), full-text → gist → tag compression, episodic→semantic CLS transfer, synaptic plasticity LTP/LTD, microglial pruning of orphan edges, homeostatic scaling, cascade stage advancement, and optional deep-sleep replay. Each cycle is delegated to a focused sub-module under handlers/consolidation/; durations are tracked per stage with partial-failure rollup. Use this on a daily/weekly cadence (or after large ingest bursts) to keep recall fast and the heat distribution healthy. Distinct from `wiki_consolidate` (operates on wiki PAGES not memories) and `forget` (one-off deletion, no lifecycle). Mutates memories + entities + relationships tables. Latency varies (~5-60s typical, deep mode minutes). Returns per-cycle counters, duration_ms per stage, status (ok|partial), and failed_stages list. The `cls` and `memify` stages include `reason_for_zero` / `reason_for_inaction` when the cycle produces no mutations, distinguishing early-return from a genuine quiet-store pass.
- **import_sessions** — Import Claude Code conversation history from ~/.claude/projects/ into the memory store. Walks JSONL session files, extracts memorable items (decisions, errors-and-fixes, architecture notes, key insights) via session_extractor, and routes each through the `remember` write gate (thermodynamics, hierarchical predictive coding, knowledge graph, engram allocation). Supports project / domain filtering and dry-run preview. Use this for an initial bootstrap or to ingest sessions from another machine. Distinct from `backfill_memories` (preferred for incremental, hash-tracked re-runs over the same source), `seed_project` (codebase structure), and `codebase_analyze` (source files). Mutates memories + entities + relationships tables. Latency varies (~1-30min depending on history size). Returns {sessions_processed, memories_imported, dry_run, errors}.
- **get_telemetry** — Return the in-process telemetry snapshot: per-operation call counts, latency, byte volume, success/failure split, and computed read/write ratio. Counters reset on process restart; the durable record is the JSONL at ~/.claude/methodology/telemetry.jsonl.
- **get_grooming_health** — Backlog size and staleness age for the three judgment-level grooming planners (curate_wiki, curate_distill, lesson_promotion) — distinct from `consolidate`'s mechanical wiki maintenance (purge/backfill/dashboards, which already self-reports and needs no staleness alarm). For each kind, returns the exact eligible-backlog count and how long ago that kind of grooming last actually executed (None = never). `stale=true` when a kind has gone longer than `threshold_days` (sourced from measured session cadence, see core.grooming_health) without running, or has never run at all. Read-only. Latency ~1s (curate_distill + curate_wiki are themselves bounded-scan planners, not indexed aggregates — this tool is meant for explicit on-demand health checks, not the SessionStart hot path).
- **forget** — Delete a memory by integer ID via direct DELETE on the memories table (hard) or by setting is_stale=true + heat=0 (soft, recoverable via SQL). Protected/anchored memories are refused unless force=true. Use this to remove genuinely-wrong memories or accidental captures. Distinct from `rate_memory(useful=false)` (downweights without removing — prefer for low-value memories), `anchor` (protect from deletion), and `validate_memory` (mark stale based on filesystem refs, not user verdict). Mutates the memories table; hard delete is irreversible. Latency ~10ms. Returns {deleted, method, memory_id, content_preview, reason?}.
- **validate_memory** — Graded provenance verifier (I6-D6): checks every reference a memory makes — file paths, git commit SHAs, URLs (bounded HEAD sample), content-addressed artifact digests (sha256[:16] recomputation) — and citations (DOI/arXiv, recognized but never auto-verified). Writes two things: (1) is_stale, from FILE PATHS ONLY (URLs/commits/digests never feed the staleness score — a dead URL does not invalidate a historical fact); bidirectional since I6-D6, a stale memory whose file refs all resolve again is rehabilitated back to is_stale=false. (2) source_attribution, a provenance grade in {verified, verifiable, unverifiable} — the worst outcome among the memory's checkable references. This handler is the sole writer of that grade; it overwrites any prior value on each verification pass. All-memories scope is cursor-paginated via after_id, 1000 per call (below the full active-store size on large corpora — page with the returned next_after_id). Use this after large refactors, file moves, or before a recall that must not return dead links. Scope to one memory, a domain, a directory, or all memories. Distinct from `forget` (deletes memories outright), `rate_memory` (user verdict on usefulness, not filesystem reality), and `wiki_consolidate` (wiki pages, not memories). Mutates is_stale and source_attribution unless dry_run=true. Latency varies (~100ms-30s depending on scope, ref count, and URL sample size). Returns {validated, stale_found, stale_updated, destaled, graded, dry_run, next_after_id, reports: per-memory breakdown}.
- **rate_memory** — Record a usefulness verdict for a memory that just surfaced in recall: increments useful_count when helpful and recomputes metamemory confidence as useful_count / access_count (Nelson & Narens 1990 framework). High-confidence memories resist heat decay and rank higher in future recalls; persistently unhelpful memories drift toward archival. Use this whenever a recalled memory either solved the problem or wasted attention — the feedback loop is what keeps recall accurate. Distinct from `forget` (deletes), `anchor` (pins, doesn't score), and `validate_memory` (filesystem-ref staleness, not user verdict). Mutates the memories table (access_count, useful_count, confidence). Latency ~20ms. Returns {rated, memory_id, useful, access_count, useful_count, confidence, content_preview}.
- **seed_project** — Bootstrap the memory store from an existing codebase via a five-stage structural sweep — each discovery is stored through the standard `remember` write gate. Distinct from `codebase_analyze` (tree-sitter AST per file, much deeper, slower), `backfill_memories` (Claude Code conversation transcripts, not the codebase itself), `wiki_seed_codebase` (seeds the wiki tree from existing markdown, not memories), and `ingest_codebase` (downstream consumer of analyzer output). Latency varies (~5-60s depending on tree size). Stages: (1) config extraction (package.json, pyproject.toml, Cargo.toml, go.mod...), (2) documentation harvesting (README, CLAUDE.md, docs/, ADRs, changelogs), (3) entry-point scan (main.py, index.js, cmd/, __main__.py), (4) CI/CD detection (.github/workflows, Makefile, Dockerfile, tox.ini), and (5) structural summary (top-level layout, language detection, module map). Each discovery is stored via remember (subject to the write gate). Use this on first onboarding to a project. Returns counts and stored memory IDs.
- **anchor** — Mark a memory as compaction-resistant by setting heat=1.0, is_protected=true, importance=1.0, and adding an `_anchor` tag — so the memory survives context compaction, heat decay, and consolidation pruning, and cannot be deleted without force=true. The optional reason is stored as an `[ANCHOR: ...]` content prefix for audit. Use this for critical facts, active architectural decisions, and operating principles that must persist across session boundaries. Distinct from `rate_memory` (raises confidence via metamemory, doesn't pin), `remember` (creates memories, doesn't pin), and `checkpoint` (whole-state snapshot, not per-memory). Mutates the memories table. Latency ~20ms. Returns {anchored, memory_id, content_preview} or {error}.
- **backfill_memories** — Import prior Claude Code conversations from ~/.claude/projects/ into the memory store. Walks JSONL session transcripts, extracts memorable items (decisions, lessons, errors-and-fixes) via the session_extractor, stores them with `backfill` tags via `remember(force=True)` — which BYPASSES the predictive-coding write gate, not the standard write path — and links each to the auto-discovered core concepts of the originating project. Idempotent only at the file level: hashes tracked in backfill_log so a plain re-run skips already-processed files. NOT idempotent overall — `force_reprocess=true` re-imports a file's items with the gate still bypassed, which can create duplicate memory rows. Use this on first install, after long absences, or when migrating to a new machine. Distinct from `import_sessions` (more granular control, manual file selection), `seed_project` (codebase structure, not conversation history), and `codebase_analyze` (source files, not transcripts). Mutates memories + backfill_log tables. Latency varies (~30s-10min depending on history size). Returns {sessions_processed, sessions_skipped, memories_imported, errors}.
- **codebase_analyze** — Walk a codebase and store its structure as memories using tree-sitter AST parsing (with regex fallback for unsupported languages). One memory per file, with symbols as entities and imports as relationships; then cross-file symbol resolution, call-graph extraction, and community detection over the call graph. Incremental — only re-processes files whose content hash changed since last run (tracked via HASH_TAG_PREFIX tags). Use this on first onboarding to a serious codebase, or after a major refactor that invalidates symbol assumptions. Distinct from `seed_project` (5-stage shallow structural sweep, no AST), `backfill_memories` (Claude Code conversations, not source files), `wiki_seed_codebase` (seeds wiki pages from .md docs), and `ingest_codebase` (downstream PRD-generator consumer, and the PRIMARY ingestion path when the ai-architect-mcp-codebase upstream is reachable — this tool is its explicit fallback, per ADR-0052 sec 2; every written memory carries a src:native provenance tag, and the response states fallback_status so a run made while AP is reachable is never silent). Mutates memories + entities + relationships tables. Latency varies (~10s-10min depending on tree size). Returns {files_analyzed, files_skipped, memories_written, entities_created, relationships_created, fallback_status}.
- **check_setup** — Verify the local Cortex installation before first interactive use. Runs the identical check functions as `python -m mcp_server.doctor` (no duplicated logic), backend-aware. PostgreSQL backend: Python >= 3.11, psycopg/psycopg_pool/pgvector driver imports, DATABASE_URL set, live PostgreSQL connection, pgvector + pg_trgm extensions, ~/.claude/methodology writability, auto-capture health (judged from the telemetry log and the capture spool: fails when captures have been skipped with none processed, or a run of skips follows the last processed one, or spooled captures are not being drained), I10 pool-capacity invariant, and an optional ai-architect-mcp-codebase codebase-tool probe. SQLite backend (zero-config default): the PG checks are replaced by a store-open check and a vector-search check that requires sqlite-vec to be loaded (it ships in every install's base package set; absence or a load failure blocks readiness); the auto-capture check applies to both backends. Both backends report historical fallback failures as optional warnings (component, count and last error, for this process lifetime only). These counters do not measure current health and never block readiness. Checks run in doctor's own dependency order, so an early failure (e.g. missing DATABASE_URL) explains later ones (e.g. no PG connection) -- fix in list order. Call this once before first session, or whenever diagnosing a setup problem. Read-only but reaches outside the DB (env vars, filesystem, a live connection attempt). Takes no arguments. Returns {ready, summary, fixes_needed, checks: [{name, ok, optional, detail, fix_command}]}. `ready` is true iff every non-optional check passed; the codebase-pipeline probe is optional and never blocks readiness.
- **recall_hierarchical** — Retrieve memories via the fractal three-level hierarchy (L0=individual memories, L1=topic clusters, L2=root clusters), with adaptive level weighting from query length: short queries weight toward broader L2 clusters (you're scanning a topic), long queries toward specific L0 memories (you have a precise question). REQUIRES either `domain` or `memory_ids` to bound the tree build. Use this instead of `recall` when you want the topology of the memory space, not just a flat ranked list. Distinct from `recall` (flat WRRF result, no hierarchy), `drill_down` (consumer of this tool's output, navigates one level deeper into a returned cluster), and `navigate_memory` (graph traversal, not cluster tree). Not read-only: every surfaced memory is recorded as a hippocampal replay event — access_count/replay_count increment and hippocampal_dependency decays — so repeat calls are not idempotent (`track_replay_event`, `replay_tracking.py`). Latency ~150-300ms on domain-scoped calls. Returns {hierarchy: [{cluster_id, level, label, score, members?}], total_clusters}.
- **drill_down** — Descend one level into a fractal memory cluster previously returned by `recall_hierarchical`: an L2 root cluster expands to its L1 sub-clusters; an L1 cluster expands to the individual memories it contains (full content, heat, tags). Cluster IDs use the form `L<level>-<index>`. Use this for interactive top-down exploration — start broad with `recall_hierarchical`, then drill the most-relevant cluster repeatedly until you reach memories. Distinct from `recall` (flat ranked list, no hierarchy), `navigate_memory` (graph BFS via co-access edges, not cluster tree), and `recall_hierarchical` (entry point that builds the tree). Not read-only: every surfaced memory is recorded as a hippocampal replay event — access_count/replay_count increment and hippocampal_dependency decays — so repeat calls are not idempotent (`track_replay_event`, `replay_tracking.py`). Latency <100ms. Returns {cluster_id, level, children: [{id, label, members?, content?}]}.
- **navigate_memory** — Traverse the memory space via a Successor Representation graph (Dayan 1993) built from temporal co-access — pairs of memories accessed within `window_hours` of each other become weighted edges. Starting from a seed memory_id, BFS outward up to `max_depth` (capped at 4) and return neighbors with SR distances. Use this to follow a thread of thinking, explore latent associations, or discover what a topic touches that you didn't know about. Distinct from `recall` (semantic vector + lexical search, no temporal-proximity edges), `get_causal_chain` (entity knowledge-graph BFS, not memory-level co-access), and `drill_down` (fractal cluster tree, not graph). Not read-only: every returned memory (the seed plus each traversed neighbor) is recorded as a hippocampal replay event — access_count/replay_count increment and hippocampal_dependency decays (CLS-B, Ketz et al. 2023) — so repeat calls are not idempotent (`track_replay_event`, `replay_tracking.py`). Latency ~100-300ms depending on depth + 2D-map flag. Returns {seed, neighbors: [{memory_id, distance, content_preview}], map_2d?: [{x, y, id}]}.
- **get_causal_chain** — Walk the Cortex knowledge graph (entities + typed relationships extracted from memory content) via bounded BFS from a seed entity or from every entity in a given memory. Returns chains of causation, dependency, and resolution — useful for understanding why a bug occurred, tracing the origin of a decision, or following imports across modules. Use this when you have a symptom and want the upstream cause, or a cause and want all downstream impact. Distinct from `navigate_memory` (memory-level co-access SR graph, not entity relationships), `recall` (no graph traversal), and `drill_down` (cluster tree, not graph). Read-only. Latency ~100-300ms depending on max_depth/edges. Returns {nodes, edges, paths} capped at max_edges.
- **detect_gaps** — Surface knowledge gaps across four axes: isolated entities (referenced in memories but with zero relationships, cap 10), sparse domains (entity count under 50% of the cross-domain average, cap 5), temporal drift (domains whose most-recently-accessed memory — sampled from up to 10 per domain — exceeds `stale_threshold_days`, cap 5), and cognitive blind spots (per-domain category/tool/pattern gaps from the profile-based blindspot detector, capped to the first 5 domains and 3 spots each). Does not detect duplicates, contradictions, or domainless/sourceless memories. Use this when planning research priorities or auditing coverage. Distinct from `assess_coverage` (numeric coverage SCORE 0-100 per axis, no specific gap list), and `memory_stats` (population counts only, no gap interpretation). Read-only. Latency ~500ms-2s depending on store size. Returns {total_gaps, gaps: [{gap_type, ...}], by_type: {gap_type: count}, domain_filter}.
- **recall_skills** — Retrieve learned procedures (recurring successful tool-use sequences) that apply to the current situation — domain, working directory, and recent actions. Procedural memory is retrieved by SITUATION, not by content similarity, which is what distinguishes it from recall_memories (episodic/semantic). Read-only; returns each skill's action sequence, proficiency, use count, and a human-readable rationale. Additive surface — does not alter declarative recall.
- **why** — Blame path resolver: turn the ⟦rcpt:N⟧ markers visible in the current context into presence-in-context evidence — which memories each injection channel (recall, session_start, auto_recall, agent_briefing) put into the context, when, at which persisted rank and score. This is evidence of PRESENCE, never causality. Protocol: collect the ⟦rcpt:N⟧ markers that were in context BEFORE the answer being questioned; EXCLUDE the marker injected alongside the current prompt's own memory block (self-pollution guard) — then pass the ids here. To correct a wrong memory surfaced by the evidence, store a superseding memory with remember. Deterministic entry point: the /why slash command. Distinct from `get_causal_chain` (entity-graph traversal over inferred relations) and `recall` (similarity retrieval): why replays RECORDED injection receipts only.
- **predict** — Record a falsifiable prediction before its outcome is known: the claim it belongs to, what is expected to happen, the test that would settle it, and the confidence held right now (0 to 1). The row stays open until `resolve_prediction` settles it against an observation, and `calibration` then scores the confidence against what actually happened. Write the prediction BEFORE running the test: a confidence stated afterwards measures nothing. Distinct from `remember` (stores what happened, not what is expected) and from `ingest_findings` (consumes another tool's findings run). Mutates the predictions table. Returns {prediction_id, status}.
- **resolve_prediction** — Settle an open prediction: what was observed, the verdict (confirmed, refuted, or abandoned when the test was never run), the kind of source that settled it (review, ci, test, manual) and a reference to that source, such as a review-comment URL or a CI run id. Cortex does not fetch the evidence and knows nothing about your host or repository: the caller maps its own convention onto these fields, so the same contract works in any repository. A resolution carrying no reference is refused, and a prediction resolves once. `calibration` scores the resolved rows. Mutates the predictions table. Returns {prediction_id, verdict, resolved}.
- **calibration** — Score the confidences of resolved predictions. Returns the Brier score (mean squared distance between stated confidence and outcome, Brier 1950) with its reference point: a forecaster who always says 0.5 scores 0.25, so anything above that carries less information than a coin, and perfect certainty that holds scores 0. Also returns the reliability breakdown per confidence band, which the mean cannot show: a well-calibrated band around 0.7 is confirmed about seventy percent of the time. Abandoned predictions are counted apart and scored nowhere. Read-only. Returns {scored, abandoned, brier, uninformative_brier, confirmed, refuted, reliability, open}.
- **sync_instructions** — Render the project's top hot memories (decisions, patterns, conventions, lessons) as bullets and write them into CLAUDE.md between `<!-- cortex:memory-insights:start -->` markers — adding the section if absent, refreshing it in-place if present. Closes the loop between Cortex's thermodynamic memory and the Claude Code instruction file loaded at every session start, so the next session begins informed without manual querying. Use this after a productive session, or on a periodic schedule. Distinct from `recall` (transient API response, not persisted to file), `narrative` (prose summary, not actionable bullets), and `anchor` (per-memory pinning, no CLAUDE.md write). Mutates the CLAUDE.md file in `directory`. Latency ~200ms. Returns {written, path, insight_count, dry_run, preview?}.
- **create_trigger** — Create a prospective-memory trigger that Cortex auto-fires when its condition matches future context (Einstein & McDaniel 2005). Trigger types: `keyword` (fires when user message contains string), `time` (fires after ISO datetime), `file` (fires when path is accessed/modified), `domain` (fires when that cognitive domain becomes active). Triggers are checked at session start (via `query_methodology`) and on demand. Use this to leave instructions for a future session — `next time we touch X, remember Y` — that you would otherwise forget. Distinct from `add_rule` (passive recall filter applied to ALL queries, no context-match firing), `anchor` (pins a memory but doesn't fire), and `remember` (records a fact, doesn't activate on context). Mutates the prospective_memories table. Latency ~30ms. Returns {trigger_id, trigger_type, trigger_condition, content_preview}.
- **add_rule** — Insert a neuro-symbolic rule into memory_rules so the `apply_rules` engine applies it on every subsequent recall — hard rules EXCLUDE matching memories, soft rules boost/penalize their rank, tag rules attach a tag. condition is '<field> <operator> <value>' (operators: ==, !=, contains, not_contains, >, <, >=, <=, matches — field may be a memory attribute like importance/heat, or 'tag'/'tags' to match against the tags list). action is 'filter' (hard only), 'boost:<float>' or 'penalty:<float>' (soft only), or 'tag:<name>' (tag only). Rejected outright (created=False) if the condition or action does not parse, or if the action's mechanism does not match rule_type. Scopes: global, domain, directory; resolved by priority then specificity. Use this to encode operating principles like `never surface deprecated memories` (condition='tag contains deprecated', action='filter', rule_type='hard') or `boost lessons in the recall pipeline` (condition='tag contains lesson', action='boost:0.3', rule_type='soft'). Distinct from `create_trigger` (proactive prospective memory, fires on context match — not a recall filter), and from `anchor` (per-memory pin, not a population rule). Mutates the memory_rules table; effect is visible at the next `recall` call. Latency ~20ms. Returns {rule_id, condition, action, scope, priority}.
- **get_rules** — Enumerate active neuro-symbolic rules in the memory_rules table, optionally filtered by scope (global/domain/directory) or rule_type (hard=filter, soft=rerank, tag=attach metadata). Use this to audit which rules are shaping recall before adding a new one or debugging unexpected results. Distinct from `add_rule` (creates) and `forget` (deletes a memory, not a rule). Read-only. Latency ~30ms. Returns {rules: [{id, scope, scope_value, rule_type, condition, action, priority, active, created_at, source_memory_id}]}. source_memory_id (M-D6) is the lesson memory a rule was promoted from via `lesson_promotion`, or null for directly-created rules.
- **get_project_story** — Generate a period-based autobiographical narrative by bucketing memories chronologically into chapters within a time window (day / week / month / all) — produces a timeline of what actually happened, in order. Use this for retrospectives, status updates, sprint reports, or to brief a collaborator on what they missed. Distinct from `narrative` (generic project summary, no time buckets, no chronology), `assess_coverage` (numeric score, no story), and `recall` (raw memory list, no narrative synthesis). Read-only. Latency ~300-800ms depending on memory count and period. Returns {period, chapters: [{time_range, theme, key_decisions, memory_ids, summary}]}.
- **assess_coverage** — Score the memory store itself across five signals: quantity (scoped memory count vs a 100-memory reference), age distribution (fresh vs stale), entity density (total store entities / scoped memory count — a corpus-wide ratio, not a true per-memory measure), domain balance (distribution of scoped memories across domains), and compression ratio (penalty for compressed content). There is no axis scoring which project source files are remembered. Emits actionable recommendations (e.g., `run validate_memory`, `run consolidate`). Use this as a memory-store health check. Distinct from `detect_gaps` (lists specific missing connections, no aggregate score), `memory_stats` (raw counts, no scoring), and `narrative`. Read-only. Latency ~500ms-1s. Returns {coverage_score, total_memories, age_distribution, entity_density, compression, domain_balance, recommendations, directory, domain}.
- **curate_wiki** — Auto-curator: returns structured authoring jobs the in-session LLM (Opus 4.7) consumes to author curated wiki pages from PG memory clusters. Each job carries one cluster's memories, the suggested wiki path, a list of existing related pages for cross-linking, and a complete structured prompt that encodes the wiki documentation conventions (frontmatter, lead, diagrams, 'why this not the alternatives', 'what can go wrong', 'see also', primary sources). The conversational LLM reads each job, authors the page in Markdown, and writes it via `wiki_write`. No external Anthropic API key required — the user's existing Claude Code session is the authoring LLM. Distinct from `wiki_write` (the writer; this is the planner), `narrative` (one summary; this is N pages), and `consolidate` (memory maintenance; this is documentation production). Read-only with respect to PG and wiki. Latency ~300ms for k=5 jobs. Returns {jobs: [{cluster, prompt, suggested_path, related_pages}], total_clusters_eligible, instructions}.
- **lesson_promotion** — Propose promotion jobs for lessons (memories tagged 'lesson' or 'lesson-candidate') that have demonstrated usage evidence (recalled or rated useful at least once). Each job carries the lesson's memory_id, content, and a heuristic suggested_kind ('rule'|'trigger'|'wiki') the in-session LLM may follow or override. The server NEVER calls add_rule/create_trigger/wiki_write itself — a rule reshapes every future recall, so the decision stays with the reviewer. Distinct from `curate_wiki` (wiki authoring jobs from memory clusters, not lesson promotion), `add_rule`/`create_trigger`/`wiki_write` (the actual promotion actions this handler only proposes), and `assess_coverage`/`detect_gaps` (read-only audits with no actionable job queue). Read-only. Latency ~30ms. Returns {jobs: [{memory_id, content, suggested_kind, tags, useful_count, access_count}], candidate_count, instructions}.
- **curate_distill** — Auto-distiller: returns structured jobs the in-session LLM consumes to author understanding-level 'lesson' memories from PG memory dossiers (error->success pairs, recurring co-access families, entity-cohesive clusters). Each job carries a dossier's memory_ids, a marker tag for idempotence, and a complete prompt naming the required `remember` call shape (tags=['lesson', <marker>, 'derived-src:<id>', ...], write_class='deliberate'). The conversational LLM reads each job, decides whether the sources justify a durable lesson, and writes it via `remember` — or skips the dossier. No server-side write happens here. Distinct from `curate_wiki` (wiki PAGES; this is memory-level LESSONS) and `consolidate`'s `memify` stage (memify_derive synthesizes templated inventory facts server-side with no LLM judgment; this delegates judgment to the LLM, per M-D8). Also returns `memify_derive_usage`: a read-only snapshot (count/access/useful) of memify_derive's existing 'derived'-tagged output, for the 30-day keep/retire measurement M-D8 requires. Read-only. Latency ~200-500ms. Returns {jobs: [{job_type, dossier_kind, memory_ids, marker, prompt}], total_dossiers_eligible, memify_derive_usage, instructions}.
- **wiki_write** — Author a new wiki page or append/replace content on an existing one (kind inferred from the first path segment: adr, specs, files, notes, lessons, conventions, guides, reference, journal). Pages live under ~/.claude/methodology/wiki/, written atomically via tmp+rename. After a successful write, registers a protected PG pointer memory tagged `wiki` so the page surfaces in `recall`. Use this for any document that should outlive the session — lessons, conventions, runbooks, anything you might link from a future ADR. Distinct from `wiki_adr` (auto-numbered ADRs from structured Context/Decision/Consequences), `wiki_compile` (publishes already-curated drafts), and `remember` (no markdown page, just a memory). Mutates the wiki/ tree, the memories table, wiki.pages (synced synchronously so the page has a resolvable id immediately), and — when `memory_ids` is passed — wiki.citations (one deduplicated row per memory actually used to author the page; how a curate_wiki job's memory cluster becomes durable, queryable provenance). Latency ~50ms. Returns {path, mode, created, bytes_written, root, citations_written} or {error}.
- **wiki_read** — Fetch the raw markdown source of one wiki page by its wiki-relative path. Path resolution is sandboxed under the wiki root — absolute paths and `../` traversal are rejected at the storage layer. When the page is a redirect stub (frontmatter ``redirect_to:`` or ``redirect_id:``) the chain is followed transparently up to 5 hops; cycles and dangling targets surface as errors. Pass ``follow_redirects: false`` to read the stub itself. Page content is filesystem-only and always returned even if PostgreSQL is unreachable. As an explicit side effect, a successful read within a known Claude Code session records one deduplicated wiki.citations row (page, session) — the primary authority-earning signal driving page heat/citation_count; best-effort, never blocks or fails the read (no window session, PG down, or a page never compiled into PG all degrade to 'read succeeds, no citation'). Distinct from `wiki_list` which enumerates available pages, and from `wiki_export` which renders a page through Pandoc to PDF/DOCX/HTML. Latency <10ms. Returns {path, content, content_length, offset, root, redirect_chain} or {error}. Pages larger than the response budget come back with ``content_truncated: true`` — page via the ``offset`` argument.
- **wiki_list** — Enumerate every authored wiki page under ~/.claude/methodology/wiki/, filesystem-walked from the wiki root. Optionally restrict by kind (adr, specs, guides, reference, conventions, lessons, notes, journal, files). Two filters are applied by default and can be opted out of: (1) redirect stubs (frontmatter ``redirect_to:`` or ``redirect_id:``) are excluded — pass ``include_redirects: true`` to see them; (2) auto-generated pages (frontmatter ``provenance: auto-generated``, produced by ``codebase_analyze``) are excluded — pass ``include_auto_generated: true`` to see them. Read-only; never modifies anything. Distinct from `wiki_reindex` which generates the .generated/INDEX.md from the same enumeration, and from `wiki_read` which fetches one page's content. Latency <200ms on a 9000-page wiki. Returns {root, count, pages, redirect_count, auto_generated_count}.
- **wiki_link** — Add a bidirectional link between two wiki pages: write the forward relation into the `## Related` section of the source page and the inverse relation into the target page, in one idempotent operation. Use this to record dependencies, derivations, supersession chains, or free-form `see also` connections between knowledge artefacts. Distinct from `wiki_write` (authors a page, doesn't link), `wiki_compile` (publishes drafts, doesn't link), and graph-relationship tools (this writes markdown sections, not DB edges). Mutates two .md files atomically. Latency ~30ms. Returns {from_path, to_path, forward_relation, inverse_relation}.
- **wiki_adr** — Create a numbered ADR (Architecture Decision Record) from structured Context/Decision/Consequences fields. Atomically: computes the next free ADR number, renders the standard template, writes wiki/adr/<NNNN>-<slug>.md under the wiki root, and registers a protected pointer memory tagged `wiki`+`adr` so the decision surfaces in `recall`. Use this whenever a non-trivial architectural choice is made — the resulting page is the single citable source of truth. Distinct from `wiki_write` (raw markdown, no auto-numbering, no template), and from `remember` (memory only, no .md file). Mutates the wiki/ tree and the memories table; refuses if the target file already exists. Latency ~50ms. Returns {path, number, title, status, created, bytes_written, root} or {error}.
- **wiki_reindex** — Regenerate the wiki table of contents at <wiki_root>/.generated/INDEX.md by enumerating every authored page and grouping it by kind (adr, specs, guides, reference, conventions, lessons, notes, journal, files). Redirect stubs are excluded; auto-generated pages (``provenance: auto-generated``) are surfaced in a separate ``Auto-generated reference`` section after the human-authored content. Output is deterministic — sorted by kind then path so unchanged wikis yield byte-identical INDEX files. Authored pages are never touched. INDEX.md and the exact decision map are refreshed; project mode also updates docs/adr. Use this after bulk wiki edits, imports, or `wiki_compile` runs. Distinct from `wiki_list` (returns the listing in the response, no file write) and from `wiki_consolidate` (heat decay / staleness, not ToC rebuild). An explicit project_root isolates project publication. Latency <500ms on a 9000-page wiki. Returns {path, total_pages, by_kind, auto_generated_by_kind, redirect_count, root}.
- **wiki_purge** — Purge wiki pages that no longer earn their place. Two reject axes: (1) the page no longer passes the current classifier (`core/wiki_classifier`) — used after tightening rules or a polluting backfill; (2) the page is a stub — body is majority placeholder markers (_(to be filled)_ / _To be written._ / _(none identified)_), produced by the groomer or by template_v1 synthesis. Stubs masquerade as content but carry none. Memories remain in the store (still surface via `recall`); only the wiki markdown files are removed from disk. Distinct from `wiki_consolidate` (heat decay + lifecycle, doesn't delete based on classifier), `forget` (deletes a memory, not a wiki page), and `wiki_compile` (publishes drafts, doesn't purge). Defaults to dry-run; pass apply=true to actually delete. Latency ~200-500ms. Returns {kept, purged, purged_paths, purged_reasons, dry_run} plus the scan accounting — {wiki_pages_total, scanned, unscanned, errored, unrecognised_dirs} — so a caller can tell a full sweep from one that reached only part of the wiki. A page that failed to read counts as scanned, not unscanned: an I/O fault shows up in `errored`, never as a coverage gap.
- **wiki_verify** — Verify that code symbols cited by wiki pages still resolve in the AST (via the ai-architect-mcp-codebase MCP server, ADR-0046 Phase 2). Takes an optional path (verify one page) or no args (verify every authored page) and returns per-page verdicts: {page, symbol_refs, missing_refs, is_symbol_stale, rationale}. Requires AP enabled (CORTEX_MEMORY_AP_ENABLED=1, the default); when disabled the handler returns status=skipped and never produces a stale verdict. Read-only — never mutates wiki or memory state.
- **wiki_rename** — Move a wiki page from ``from_path`` to ``to_path`` and leave a redirect stub at the old location pointing to the new one. ``wiki_read`` follows redirect stubs transparently. Refuses to operate on pages without a stable ``id`` field (run ``scripts/wiki_backfill_ids.py`` first) or on existing redirect stubs. Returns {from_path, to_path, page_id, stub_created}.
- **wiki_migrate** — One-shot idempotent sync of the filesystem wiki (~/.claude/methodology/wiki/) into wiki.pages / wiki.links / wiki.page_sources. Walks every PAGE_KINDS directory, upserts each page keyed on rel_path (body_hash guards no-op re-writes), re-resolves [[slug]] links, then reconciles: any wiki.pages row whose rel_path no longer exists on disk (deleted file, rename, or a wiki_purge run — which only touches the FS, never PG) is purged from wiki.pages, cascading via FK ON DELETE CASCADE to wiki.links and wiki.page_sources. The `_`-prefixed kind dirs (_kinds/_rules/_views/_bibliography/_dashboards) and the root README.md are outside the scan entirely on both phases, so they are never upserted and never purged. Defaults to dry_run=true (report the ghost rel_paths without deleting); pass dry_run=false to actually purge. Distinct from `wiki_purge` (deletes FS files that fail the classifier, never touches PG) — this tool never touches the FS, only reconciles PG to match it. A frontmatter status outside wiki.pages' DB CHECK union falls back to 'seedling' and is reported in warnings (never blocks the page write). Returns {pages_processed, pages_written, pages_unchanged, links_written, links_resolved_pass3, purge: {dry_run, ghost_count, ghost_paths, purged}, errors, error_count, warnings, warning_count}.
- **wiki_get_draft** — Fetch a draft + its source claims + the kind contract so the caller (LLM) can refine it, or list the pending drafts. Phase 2.3 (Path B): `wiki_synthesize` fills wiki.drafts from routed claims, this hands one to the caller, and `wiki_refine_draft` takes the prose back. Read-only.
- **wiki_refine_draft** — Submit a refined draft (lead, sections, optional title). Updates wiki.drafts in place; records an audit memo, one row per call. The draft's confidence is left as its source claims set it (ADR-1065), so refining never moves a draft past `wiki_curate`'s approve threshold. Sections are refused unless they satisfy the kind contract returned by `wiki_get_draft`. A call carrying none of title/lead/sections/frontmatter is refused whole, and so is one whose value for any of them is empty: blanking a field is not a refinement (ADR-1068, ADR-1069). A refused call writes neither the draft nor a memo. Phase 2.3 (Path B).
- **ingest_findings** — Ingest an ai-architect-mcp-codebase (AP) findings run into Cortex's store. Reads runs/<run_id>/ artifacts directly off disk (no network call to AP — AP never pushes, ADR-0052 D1). Verified findings (stage-2 verified:true) get a wiki page under reference/findings/, file-source links (wiki.page_sources, link_kind='finding' for code files the finding is ABOUT — run AP's stage-4 `prepare_prd_input` on the finding BEFORE ingesting if you want this anchoring, otherwise it is empty, not guessed; link_kind='extracted_from' for the source document the finding was extracted FROM, when stage-1's source_path is present — independent of stage-4), one wiki.memos row per stage-2/6/8 receipt (raw-bytes sha256 digest, re-verifiable, plus AP's own transcript_digest copied verbatim from stage-2.verified.json when present — two independent anchors: byte-exact vs AP's semantic claim), and a memory tagged finding,verified. Non-verified findings get a memory only, tagged finding,hypothesis, at low confidence — a hypothesis is not documentation. Idempotent: re-ingesting the same run does not duplicate memories, pages, page_sources, or memos. Distinct from `ingest_codebase` (symbols/files, not findings) and `ingest_prd` (a PRD document, not a findings run). Mutates memories + wiki.pages/page_sources/memos. Returns {ingested, findings_total, verified_count, hypothesis_count, results, errors}.
- **ingest_document** — Ingest a document (.docx or a Confluence storage-format XHTML export) into Cortex's memory/wiki store. Unpacks the container (docx = OOXML zip; Confluence = XHTML file), extracts heading structure + paragraph text + tables into a wiki reference page under documents/<slug>.md, and writes one protected summary memory plus one memory per section — every page and memory stamped with provenance (source path + content version) so documents ride the same staleness/validation path as code references. Embedded images are skipped with an explicit notice (no OCR). Re-ingesting the same document version resumes missing components without duplicating successful writes; summary/section memories this version wrote for a different normalized output (another title override) are marked stale and listed in retired_receipt_ids. ingested is true only when wiki, summary and every section are complete; partial results include expected_components, completed_components and failures. Malformed zip/XML fails loudly, writing nothing. Distinct from `ingest_prd` (markdown PRDs with decision/requirement extraction), `ingest_codebase` (code symbols), and `wiki_write` (manual single page). Returns {ingested, status ('complete'|'partial'), reason, idempotent_skip, wiki_path (null when the wiki write failed), summary_memory_id, section_count (sections written), section_memory_ids, expected_components, completed_components, failures, retired_receipt_ids, images_skipped, attachments ([{ordinal, reference, section_index, state, part, digest, size}] per embedded image: docx part, sha256 and byte size of its bytes when the reference resolves, else empty; state 'unsupported' until extraction exists), section_headings (heading of each parsed section, indexed by section_index), notices, title, source, source_kind, version}.

## Claude Desktop Quick Installation
Install path detected from listing signals. Uses `uvx` (confidence: high):

```json
"mcpServers": {
  "cortex": {
    "command": "uvx",
    "args": ["--from","hypermnesia-mcp[sqlite]","hypermnesia-mcp"]
  }
}
```

## Documentation

## What cdeust/Cortex does

cdeust/Cortex gives coding agents a persistent, local memory store that survives individual sessions. It can retain decisions, lessons, errors and fixes, project structure, session summaries, cognitive profiles, and whole-task checkpoints. Memories can be searched semantically and lexically, inspected through their graph relationships, ranked with replay and usefulness signals, and checked for stale file references or provenance.

The server supports SQLite as the zero-configuration backend and PostgreSQL with pgvector and pg_trgm when a PostgreSQL setup is selected. Claude Code and Codex can share the same store when they use the same configuration root and backend. The system also includes a per-project wiki workflow, codebase ingestion, profile analysis, and maintenance routines for aging, consolidating, and pruning stored information.

## How it works

Memory writes pass through a novelty-oriented gate that considers embedding, entity, temporal, and structural signals. Accepted content can receive tags, extracted entities, relationships, and provenance information; similar content may be merged or rejected. Retrieval combines vector, full-text, trigram, heat, and recency signals, followed by reranking and additional context such as prospective triggers and related graph activity.

Cortex builds cognitive profiles by scanning Claude Code and Codex JSONL session data. `detect_domain` identifies the likely working domain, while `query_methodology` loads its cached profile and relevant hot memories. Session-end processing updates profiles incrementally, records a session summary, and can create lesson candidates and prospective triggers.

Working state can be saved before context compaction and restored afterward. For broader exploration, hierarchical recall exposes topic clusters, memory navigation follows temporal co-access links, and causal-chain queries traverse entities and typed relationships. Maintenance tools handle decay, consolidation, compression, semantic transfer, pruning, and health reporting.

## Setup and configuration

For Claude Code, add the marketplace and install the `hypermnesia-mcp` plugin, then initialize it before the first session:

```bash
claude plugin marketplace add cdeust/Cortex
claude plugin install hypermnesia-mcp
claude --init-only
```

The initialization step installs the runtime, semantic-search dependencies, and embedding model. The repository also provides a Claude Desktop MCPB bundle. Codex users can install the Python package with the SQLite extra and add the Codex marketplace plugin. Gemini CLI, Cursor, Windsurf, and VS Code can launch the same stdio server as other MCP hosts.

A fresh installation normally creates a local store beneath `~/.claude/methodology/`. On supported macOS and Linux systems, initialization can provide a managed local PostgreSQL instance; Windows uses SQLite. An explicitly configured PostgreSQL connection takes precedence. `check_setup` reports backend readiness, dependencies, storage access, vector search, and capture health.

## Tools and capabilities

The tool set covers several distinct workflows:

- Profile and session context: `detect_domain`, `query_methodology`, `list_domains`, `rebuild_profiles`, `record_session_end`, and `explore_features`.
- Memory operations: `remember`, `recall`, `rate_memory`, `forget`, `anchor`, `validate_memory`, and `memory_stats`.
- Context recovery: `checkpoint` saves and restores task state around compaction.
- Search and exploration: `unified_search`, `recall_hierarchical`, `drill_down`, `navigate_memory`, `get_causal_chain`, and `recall_skills`.
- Project ingestion: `seed_project`, `codebase_analyze`, `import_sessions`, and `backfill_memories`.
- Maintenance and diagnostics: `consolidate`, `get_telemetry`, `get_grooming_health`, `detect_gaps`, and `check_setup`.
- Narrative output: `narrative` turns stored project history into a multi-section account or a short summary.

## Limitations and notes

The Claude Desktop bundle includes MCP tools but not lifecycle hooks. Automatic capture and project-context behavior therefore differs between native Claude Code or Codex plugins and a plain MCP host. PostgreSQL support depends on the platform and local setup; SQLite is the fallback in supported configurations.

Retrieval is not read-only in every case: `recall`, hierarchical recall, drilling, and graph navigation record replay activity and update related counters. Hard deletion through `forget` is irreversible, while protected or anchored memories require an explicit force option. Session transcript imports can take from seconds to minutes, and full codebase analysis can take substantially longer than the shallow project seeding pass.

The server runs locally by default, but optional integrations, remote PostgreSQL, and telemetry can use the network when configured. Its neuroscience-inspired mechanisms describe implementation choices; retrieval improvements should be evaluated against the workload being served.

_Full upstream README: https://allmcps.com/mcp/cdeust-cortex/readme_

