Claude Code Memory: CLAUDE.md, Auto Memory & Persistent Memory
< BlogGuides
October 19, 2026
19 minutes read

Claude Code Memory: CLAUDE.md, Auto Memory & Persistent Memory

Cognee Editorial Team
Cognee Editorial TeamCognee team

Claude Code memory is a practical problem: every session opens with a fresh context window, and the only built-in mechanisms that carry knowledge forward are CLAUDE.md files (including CLAUDE.local.md and the AGENTS.md alternative) and Auto Memory, the notes Claude writes from corrections and preferences through the /memory and /init commands. This guide is written for engineers using Claude Code day to day and tech leads standardizing agent memory across teams. It covers how the native surface works, where it breaks down for cross-session and cross-project work, and how to add persistent memory with an MCP server such as Cognee, a graph-native memory layer with a Claude Code plugin.

Core Components Required for Claude Code Memory to Work at Scale

Claude Code memory is the set of mechanisms that carry knowledge across sessions, because every new session begins with a fresh, empty context window. Natively, two mechanisms do that work: CLAUDE.md files (and the alternative AGENTS.md) that engineers write by hand, and Auto Memory, which captures corrections and preferences into ~/.claude/projects//memory/ with MEMORY.md as the index and topic files loaded on demand. CLAUDE.md and CLAUDE.local.md are concatenated as Claude walks up the directory tree, across four scopes. The /memory command manages all of it. Cognee extends these components as a graph-native memory layer through a Model Context Protocol (MCP) server and a Claude Code plugin, so any engineer who otherwise re-briefs Claude every session gets persistent, queryable memory.

How to Think About Claude Code Memory in Modern Engineering Systems

As Claude Code runs longer agentic loops with finite context windows, memory design decides whether an agent recalls last week's refactor or restarts cold. Each claude invocation begins fresh unless a CLAUDE.md is hand-maintained, and Auto Memory captures session learnings into a per-repo MEMORY.md that can be truncated past roughly 200 lines. A minimum viable setup pairs that flat file with Auto Memory and accepts lossy compaction. A mature setup, which Cognee works on with teams, exposes a shared temporal knowledge graph through one MCP endpoint that Claude Code, Cursor, Cline, and Zed read and write together, with contradiction handling built in.

Common Challenges Teams Face With Claude Code Memory

Claude Code gives developers two built-in persistence mechanisms, CLAUDE.md and Auto Memory, and both operate inside tight limits. Teams working on long-running codebases, multi-repo platforms, or multi-week refactors quickly discover that session boundaries, file size caps, and automatic context compaction can quietly discard the context an agent just built up. The result is repeated re-briefing, inconsistent agent behavior across repositories, and loss of hard-won decisions. The failure modes below show up most often in production use and shape how teams decide whether a persistent memory backend is worth adding to the stack.

Key Challenges and Failure Modes in Claude Code Memory

  • No cross-session memory beyond CLAUDE.md and Auto Memory. Each Claude Code session starts with a fresh context window. The official feature-request thread confirms that every claude invocation begins completely fresh, with no memory of previous decisions unless the user manually maintains CLAUDE.md files.
  • MEMORY.md truncation past roughly 200 lines. MEMORY.md is written by the agent across sessions to record recurring patterns, corrected errors, and observed preferences. Once it grows past about 200 lines, content may be truncated, so older learnings silently drop out of the loaded context.
  • Per-repository scope by default. Both CLAUDE.md and Auto Memory are scoped to the repository where they live. Auto Memory's automatic captures write to ~/.claude/projects//memory/ and do not propagate to the cross-project ~/.claude/CLAUDE.md, so lessons learned in one repo stay invisible to agents working in another.
  • Context compaction erases in-session knowledge. When the context window fills, Claude Code compacts history to free tokens. Any detail the agent inferred during the session but never wrote to CLAUDE.md or Auto Memory is lost before it can reach persistent storage.

Teams mitigate these failure modes with standardized CLAUDE.md hygiene, explicit scope rules for project versus user versus local files, and a persistent memory backend that lives outside the session. Cognee addresses the compaction gap directly: its Claude Code plugin uses a PreCompact hook to bridge session data into the permanent knowledge graph before the context window is cleared, alongside SessionStart initialization, PostToolUse capture of significant actions, UserPromptSubmit injection of relevant graph context, and SessionEnd bridging. The outcome is continuity across sessions and repositories without the manual re-briefing that CLAUDE.md and Auto Memory alone require.

How to Define a Winning Strategy for Claude Code Memory

A Claude Code memory strategy depends on three decisions, not on tool selection alone: what to persist, where it lives, and how it is retrieved. CLAUDE.md and the auto memory directory solve the small case, curated notes and short-lived session state, but they do not survive compaction, cross teammates, or answer time-scoped questions. A durable strategy treats memory as an engineering surface with capture, storage, retrieval, and conflict rules defined up front. The sections below name the capabilities that make that surface work, so the choice of MCP server is a consequence of the strategy rather than its starting point.

Must-Have Capabilities for a Scalable Claude Code Memory Strategy

  • Automatic capture of prompts, tool traces, and responses. Engineers should not hand-curate memory. The memory layer records user prompts, significant tool calls, and assistant responses as they happen, so nothing depends on remembering to write it down.
  • Context injection on every prompt. Each user message is enriched with relevant prior facts pulled from the memory store before the model sees it, so recall is not gated on the user asking for it.
  • Durable storage that survives compaction and session end. Session buffers are bridged into a permanent store before Claude Code clears its context window, and again when the session closes, so continuity does not reset with the chat.
  • Temporal awareness. Dates in ingested content become first-class graph attributes, which lets the agent answer before/after/between questions from facts dated inside that window instead of from embedding similarity alone.
  • Contradiction handling that preserves history. When a new fact disagrees with an older one, the system records the conflict with both texts, a reason, and a confidence score rather than silently overwriting, the old fact remains inspectable.

Cognee maps directly to these requirements. Its Claude Code plugin wires into SessionStart to initialize memory, PostToolUse to capture significant agent actions, UserPromptSubmit to inject relevant graph context into every prompt, PreCompact to preserve memory before Claude Code's context window is cleared, and SessionEnd to sync session data into the permanent knowledge graph. The graph is temporal by default, so time-scoped recall works without extra configuration. Opt-in contradiction detection, enabled with CONTRADICTION_DETECTION=true, writes a contradicts edge carrying both fact texts, the reason, and a confidence score after each run, history stays intact, and the session layer tracks which graph elements each answer used.

How to Choose the Right Memory Tools and Architecture for Claude Code

Engineering teams and solo developers who live inside Claude Code, often with Cursor or Codex open in another window, hit the memory question quickly. CLAUDE.md and Auto Memory cover prompts and preferences, but anything learned mid-session evaporates once context compacts or the session ends. The pressure to add persistent memory grows with repository size, number of contributors, and the number of MCP clients in rotation. Picking the right tool is less about features on a comparison page and more about matching the capture, storage, and retrieval layers to how the team actually works day to day.

Tool Selection Criteria That Matter Most

Five criteria decide the fit. Scalability covers whether storage holds up as the graph of files, decisions, and conversations grows beyond a single repo. Interoperability across MCP clients matters when Cursor, Claude Code, Cline, Continue, Windsurf, Roo, and Zed all need to read and write the same memory, a single HTTP MCP endpoint prevents each client from rebuilding context independently. Cost model splits into token-based (pay for what the agent processes) versus seat-based. Security and self-hosting determine whether proprietary code leaves the network. Operational overhead decides who maintains the backend.

Build vs Buy Tradeoffs

Three reference points cover most of the decision space. claude-mem is a Claude Code plugin, not an MCP server; it hooks into session lifecycle events, compresses tool-call output into structured observations, and stores everything in a local SQLite database at ~/.claude-mem/claude-mem.db, enough for a single developer on one machine. Mem0 connects as an MCP server at mcp.mem0.ai/mcp with eleven tools, but recall is manual: the user must explicitly tell the agent what to remember and when to search, and action-level events like file edits are not auto-captured. Cognee is a graph-backed MCP server; the open-source build is Apache-2.0 and self-hostable on a single Postgres instance when buying a managed service is off the table.

Reference Architectures by Team Size

A solo developer can usually stop at CLAUDE.md plus Auto Memory, adding claude-mem locally if cross-session recall of tool output matters. A small team benefits from a shared MCP endpoint pointed at a single dataset so pair-programmed decisions survive across machines. A larger org tends toward self-hosted Cognee with Neo4j or Kuzu for the graph and LanceDB or Qdrant for vectors, scaling backends as the knowledge base grows. Per-agent datasets keep concerns separated: Cursor auto-connects to cursor_vscode_memory and Claude Code to claude_code_memory, so agents do not unintentionally share memory unless configured to.

Tool Categories Required for a Complete Stack

A complete memory stack has five layers, independent of vendor. The capture layer uses hooks or plugins to record session events and tool outputs. The storage layer combines a graph store for relationships with a vector index for semantic search. The retrieval layer injects the right slice back into the next session or prompt. A contradiction and temporal layer time-stamps facts so stale decisions can be superseded rather than silently overwritten. A shared MCP endpoint sits on top so every client, Claude Code, Cursor, Codex, and others, reads and writes the same source of truth.

Step-by-Step Guide to Implementing Persistent Memory in Claude Code

A reliable Claude Code memory setup is best built in phases rather than all at once. Start with the native primitives that ship in the CLI, CLAUDE.md scopes and Auto Memory, so there is a baseline of per-repository context that survives restarts. Then layer an MCP-based memory server on top to get true cross-session, cross-project persistence backed by a knowledge graph. Finally, verify that hooks fire at the right lifecycle points and reconcile any overlap between native Auto Memory and the MCP plugin. The six steps below walk through that path end to end using Cognee as the persistence layer.

Implementing Claude Code Memory End to End

1. Set Up CLAUDE.md Scopes. Create the project-level CLAUDE.md at the repository root, a user-level file at ~/.claude/CLAUDE.md for personal conventions that apply everywhere, and a local override where needed. Claude Code concatenates these files into context as it walks up the directory tree, so more specific scopes layer on top of broader ones. Run /memory inside a session to review exactly which files are loaded and confirm the final merged content matches expectations.

2. Enable and Review Auto Memory. Auto Memory writes session learnings to ~/.claude/projects//memory/, with a MEMORY.md index loaded at startup and topic files pulled in on demand. Both CLAUDE.md and Auto Memory are per-repository by default, which means automatic captures stay scoped to the project where they happened and do not propagate to the cross-project ~/.claude/CLAUDE.md. Inspect the directory after a working session to see what Claude Code chose to retain.

3. Install the Cognee Claude Code Plugin. Add the Cognee marketplace and install the memory plugin with two commands:

This registers the hooks and slash commands used by the rest of the setup. The plugin is the bridge between Claude Code's session lifecycle and the Cognee knowledge graph.

4. Register the Cognee MCP Server. For Cognee Cloud, point Claude Code at the hosted MCP endpoint and authenticate:

Then run /mcp → cognee → Authenticate in a session. For a self-hosted deployment running on the default port, register it at the project scope instead:

5. Verify Hook Capture and Injection. Confirm the plugin's hooks are firing at each lifecycle point: SessionStart initializes memory, UserPromptSubmit injects relevant graph context into every prompt, PostToolUse captures significant agent actions, PreCompact bridges session data into the permanent graph before the context window is cleared, and SessionEnd syncs the full session into the knowledge graph. A quick way to verify is to ask about something discussed in a previous session and check that the recalled facts appear in the injected context.

6. Decide on Auto Memory Interaction. In cloud mode the Cognee plugin turns off Claude Code's own autoMemoryEnabled setting in ~/.claude/settings.json from the next session onward, unless the user explicitly sets it back. Teams that want both systems running in parallel should re-enable the flag and accept some duplication between native Auto Memory files and the graph. Teams that prefer a single source of truth can leave the plugin's default behavior in place and rely on Cognee for persistence.

Best Practices for Operating Claude Code Memory Long Term

Running Claude Code memory in production is less about clever prompts and more about disciplined operations: keeping instruction files lean, isolating what each agent sees, and letting a temporal knowledge graph carry the long tail of facts. Cognee is positioned as the persistent memory layer behind Claude Code, so most of the practices below assume the Cognee MCP server is handling cross-session recall, contradiction tracking, and temporal reasoning while CLAUDE.md stays small and declarative. The goal is a setup where sessions can end, agents can switch, and the useful knowledge still survives.

Keep CLAUDE.md focused and small. Treat CLAUDE.md as a short, high-signal brief: project conventions, build commands, non-obvious constraints. Push running observations into the memory layer instead. MEMORY.md in particular accumulates recurring patterns, corrected errors, and observed preferences as the agent works, and once it grows past roughly 200 lines content can be truncated, so prune aggressively and use project, user, and local scopes for what actually belongs in each.

Separate agent datasets by default. Each MCP client gets its own auto-named dataset: Cursor connects to cursor_vscode_memory and Claude Code to claude_code_memory. That isolation prevents one agent from quietly polluting another's recall. Keep it that way unless there is a specific reason to share, and when sharing is intended, point both clients at the same named dataset explicitly rather than merging everything into one bucket.

Enable contradiction detection. Set CONTRADICTION_DETECTION=true so that when a new fact conflicts with an existing one, Cognee writes a contradicts edge carrying both fact texts, the reason, and a confidence score, nothing is overwritten or deleted. Pair this with close_node() and is_valid() to retire stale facts explicitly, and lean on temporal superseding so recent statements win without erasing history.

Use temporal queries for time-scoped questions. Cognee builds a temporal knowledge graph by default, with dates from the ingested content becoming part of the graph. For questions phrased as before, after, or between two points in time, route them through temporal search rather than embedding similarity alone, the answer is drawn from content actually dated inside that window, which matters for changelogs, incident timelines, and decisions that evolved.

Review PreCompact behavior. Context compaction is where session knowledge usually disappears. Confirm the PreCompact hook is active so it bridges session data into the permanent graph before Claude Code clears the window. Without it, continuity has to be rebuilt by hand on every long session; with it, the next session resumes against a graph that already knows what happened.

How Cognee Simplifies and Scales Claude Code Memory

Cognee ships a Claude Code plugin that captures prompts, tool traces, and assistant responses automatically. Hooks do the work: SessionStart initializes memory, PostToolUse records significant agent actions, UserPromptSubmit injects relevant graph context into every prompt, PreCompact preserves state before Claude Code clears its context window, and SessionEnd syncs the session into a permanent knowledge graph. One HTTP MCP endpoint serves every client at once, so Cursor, Claude Code, Cline, Roo, Continue, Windsurf, and Zed read and write the same graph. The result is a single source of truth for project memory, with no redundant re-briefing between tools or sessions.

Under the hood, Cognee exposes 14 specialized tools, including cognify, codify, remember, recall, and search, and runs in standalone, API, and MCP modes. The graph is temporal by default, so time-scoped questions (before, after, between) resolve against dated content rather than embedding similarity alone. Contradiction handling preserves history: an opt-in contradicts edge, temporal superseding by recency, and close_node()/is_valid() retire stale facts without deleting them. Cognee has 32k+ GitHub stars, 80+ contributors, and is in production at 70+ companies. Cognee Cloud pricing is $1.00 per 1M tokens processed, plus $5 per additional workspace; the free workspace includes 1M tokens, unlimited users, and unlimited API calls.

Key Takeaways and How to Get Started

Claude Code's native memory, CLAUDE.md files, Auto Memory, MEMORY.md, and the /memory command, covers single-repo basics but resets on compaction and does not share state across sessions or agents. Persistent, contradiction-aware, team-wide memory needs an MCP backend. Teams running multi-agent setups, long-lived projects, temporal queries, or anyone losing context on compaction should consider Cognee. Start free with the Apache-2.0 open-source package on a single Postgres instance, or spin up Cognee Cloud with a free workspace that includes 1M tokens, unlimited users, and unlimited API calls. See Cognee pricing for Standard at $1.00 per 1M tokens processed, plus $5 per additional workspace.

Frequently Asked Questions

What is Claude Code memory and how does it work across sessions?

Claude Code starts every session with a fresh context window and keeps nothing from previous invocations by default. Only two built-in mechanisms carry knowledge forward: CLAUDE.md files that developers write by hand, and Auto Memory, where Claude records corrections and preferences it observed during a session. Both are per-repository by default, and anything that was only in the prior conversation disappears once the session ends. To get real cross-session recall of decisions, tool traces, and file edits, teams add an MCP memory server such as Cognee, which captures those events and injects them back on the next prompt.

What is the difference between CLAUDE.md, Auto Memory, and MEMORY.md?

CLAUDE.md is written by the user and loaded from four scopes as Claude walks up the directory tree, concatenated into context at session start; AGENTS.md can stand in for it. Auto Memory is written by Claude itself to ~/.claude/projects//memory/, capturing session learnings like recurring patterns and corrected errors. MEMORY.md is the index file inside that directory, loaded at startup to anchor the auto-memory topic files that get pulled in on demand; beyond roughly 200 lines its contents may be truncated. Cognee sits alongside these as a graph-backed store that avoids the truncation limit.

How do you add persistent cross-session memory to Claude Code?

The fastest path is the Cognee plugin, installed with two commands:

The plugin hooks into Claude Code's session lifecycle, captures prompts, tool traces, and assistant responses into session memory, injects relevant context on each prompt, and syncs the session into a permanent knowledge graph at session end. Teams that prefer no local install can register the hosted Cognee Cloud MCP server with claude mcp add --scope user --transport http cognee https://mcp.aws.cognee.ai/mcp and authenticate through /mcp → cognee → Authenticate.

How does Cognee compare to Mem0 and claude-mem?

Mem0 runs as a hosted MCP server at mcp.mem0.ai/mcp, requires a Mem0 Platform account, exposes eleven tools, and expects the user to explicitly instruct what to remember and when to search, automatic capture of file edits or command execution is out of scope. claude-mem is a Claude Code plugin, not an MCP server, that compresses tool-call outputs into observations and stores them in a local SQLite database at ~/.claude-mem/claude-mem.db, specific to Claude Code. Cognee is graph-native, auto-captures through session hooks, and serves one HTTP endpoint that Cursor, Claude Code, Cline, Roo, Continue, Windsurf, and Zed can all read and write.

How much does Cognee cost for Claude Code memory?

The Cognee open-source package is Apache-2.0 licensed and free for commercial use, so teams that self-host pay nothing for the software itself. Cognee Cloud is $1.00 per 1M tokens processed, plus $5 per additional workspace, with a free workspace that includes 1M tokens, unlimited users, and unlimited API calls, and supports the agentic integrations including Claude Code, Codex, and MCP. Enterprise adds a dedicated support engineer, BYO cloud deployment, and SLAs for organizations that need isolation or contractual commitments beyond the Standard tier.

Get started

Cognee is the fastest way to start building reliable Al agent memory.

Cognee Cloud
Latest
ChatGPT Memory: How It Works, What It Can't Do, and How to Build Your Own
Knowledge Graphs for LLMs: How They Work Together and When You Need One
Temporal Knowledge Graphs: What They Are and Why AI Memory Needs Them