Agent memory in Claude Code is a set of plain Markdown files that load into every session, because each session otherwise starts with an empty context window. There are two kinds. CLAUDE.md files hold instructions that you write, and auto memory holds notes that Claude writes for itself about your preferences, your corrections and project facts it cannot read from the code. Subagents can keep a third, separate memory of their own. None of it is a vector database or a hidden model feature: it is text on your disk that you can open, edit and delete.

Below: how each layer works in Claude Code, what goes where, the limits that catch people out, and the same idea in your own agent on the Claude API. Everything below comes from Anthropic's Claude Code memory docs, its subagent docs and the memory tool reference, checked on October 28, 2026, when the current Claude Code release on npm was 2.1.312.

Agent memory in Claude Code at a glance

ItemCLAUDE.md filesAuto memorySubagent memory
Who writes itYouClaudeThe subagent
What it holdsRules, commands, conventionsPreferences, corrections, project contextWhat that subagent learns over time
Where it livesRepo, home folder or a managed policy path~/.claude/projects/<project>/memory/agent-memory folder at user, project or local scope
What loads at startThe whole file (up to 4 MiB)First 200 lines or 25KB of MEMORY.mdFirst 200 lines or 25KB of its own MEMORY.md
Shared with the teamYes, if committedNo, it stays on your machineOnly at project scope, through Git

The short version: CLAUDE.md is how you guide Claude, and auto memory is how Claude learns from you without you writing anything down.

Layer one: CLAUDE.md, the memory you write

CLAUDE.md is the instruction file Claude reads at the start of every session. It can sit in four places, loaded from broadest to most specific: a managed policy file that IT deploys to every machine, your personal ~/.claude/CLAUDE.md, the project's ./CLAUDE.md (or ./.claude/CLAUDE.md), and a gitignored ./CLAUDE.local.md for your own notes on one project. Claude also loads every CLAUDE.md in the folders above where you started it, and picks up ones in subfolders only when it starts working with files there.

Files don't override each other. They are joined together, so if two of them disagree, Claude may follow either one. Anthropic suggests keeping each file under 200 lines, writing rules concrete enough to check ("Run npm test before committing", not "test your changes"), and moving rules that only matter for one part of the codebase into .claude/rules/ files with a paths field so they load only when Claude touches matching files.

If your repository already uses AGENTS.md for other coding agents, Claude Code can read it in place of CLAUDE.md. Our AGENTS.md guide covers that choice and the one line import that lets both tools share a file, so we won't repeat it here.

Layer two: auto memory, the memory Claude writes

Auto memory is the part most people mean when they ask about agent memory in Claude Code. It is on by default in local sessions. As Claude works, it decides what is worth keeping and saves it in four types, recorded in each note's frontmatter:

  • user: your role, expertise and working preferences
  • feedback: corrections you give and approaches you confirm
  • project: ongoing work, deadlines and decisions that the code and Git history don't show
  • reference: where to find outside information, such as an issue tracker or a dashboard

Claude deliberately skips anything it can work out from the codebase (architecture, file paths, debugging fixes) and anything your CLAUDE.md already says. It does not save something every session. When you see "Saved 2 memories" or "Recalled 2 memories" in the interface, it is reading or writing its memory folder.

Where auto memory lives

Each project gets a folder at ~/.claude/projects/<project>/memory/. The project name comes from the Git repository, so every worktree and subfolder of one repo shares a single memory. Inside is a MEMORY.md index, one line per memory, plus one topic file per memory, such as feedback_testing.md.

Auto memory is local to the machine: it does not follow you to a laptop or a cloud environment. It also survives cleanup. Claude Code deletes old session transcripts after the cleanupPeriodDays setting, but it leaves the memory files alone until you or Claude edits or removes them. Claude also stamps a modified timestamp on each note it writes, so both of you can see how fresh a fact is.

The 200 line limit

Only the first 200 lines or 25KB of MEMORY.md, whichever comes first, load at the start of a session. Topic files don't load at startup at all; Claude opens them with its normal file tools when it needs them. That is why the index stays short and the detail lives in topic files. When MEMORY.md gets close to a limit, Claude Code tells Claude to tighten it, and when it goes over, the write still succeeds but Claude is told to rewrite the index, because anything past the limit is dropped on the next load.

This limit applies to MEMORY.md only. A CLAUDE.md that loads at launch is read in full as long as it is 4 MiB or smaller.

Turn it on, off or inspect it

Type /memory in a session to see every memory file location, open any of them in your editor, toggle auto memory, or open the auto memory folder. The toggle writes autoMemoryEnabled to your user settings. You can also turn it off for one project by setting autoMemoryEnabled to false in that project's settings, or everywhere with the environment variable CLAUDE_CODE_DISABLE_AUTO_MEMORY=1. To move the folder, set autoMemoryDirectory to an absolute path or one starting with ~/.

Saying "remember that the API tests need a local Redis instance" puts the fact in auto memory. Saying "add this to CLAUDE.md" puts it in the shared instruction file instead. Pick based on who should see it: auto memory is yours alone, while a committed CLAUDE.md reaches the whole team.

Layer three: memory for subagents

The main conversation's auto memory does not load into subagents. A fork is the exception, since it inherits the parent conversation. If you want a subagent to learn across sessions, give it its own memory with the memory field in its definition file:

---
name: code-reviewer
description: Reviews code for quality and best practices
memory: project
---
As you review code, record recurring issues in your agent memory.

The scope sets where the folder lives. user uses ~/.claude/agent-memory/<agent>/ for lessons across every project, project uses .claude/agent-memory/<agent>/ so the team can share it through Git, and local uses .claude/agent-memory-local/<agent>/ for project notes that stay out of version control. With memory on, the subagent's system prompt gets instructions for using the folder plus the first 200 lines or 25KB of its own MEMORY.md, and the Read, Write and Edit tools are enabled for it. Subagent memory is part of auto memory, so turning auto memory off disables it too.

What to put where

Memory is context, not configuration. Anthropic's docs are clear that Claude reads CLAUDE.md and auto memory and tries to follow them, with no guarantee of strict compliance. So match each kind of knowledge to the right mechanism:

You want Claude to...Use
Follow a team rule in every sessionProject CLAUDE.md
Remember your personal habits on one repoAuto memory or CLAUDE.local.md
Follow a rule only in one folder or file typeA .claude/rules/ file with paths
Run a multistep procedure when it is neededA skill
Never do something, no matter whatA hook or a permissions.deny setting

The last row is the one that bites. If an instruction must hold every time, such as blocking edits to a production config, write a PreToolUse hook or a deny rule. Memory can remind Claude, but only a hook or setting enforces.

The same idea in your own agent: the memory tool

When you build an agent on the Claude API instead of using Claude Code, Anthropic offers a memory tool that follows the same pattern: a folder of files the model reads and edits. You add {"type": "memory_20250818", "name": "memory"} to your request's tools, and Claude then asks to view, create, str_replace, insert, delete or rename files under a /memories path. The tool is client side, which means your code carries out each command against storage you control, whether that is a folder or a database. The API also adds a short system prompt instruction telling Claude to check its memory folder before it starts and to record progress as it goes. Anthropic lists it for all Claude 4 and later models.

Because your code runs every file operation, path safety is your job. A path like /memories/../../secrets.env must be rejected. Here is a minimal Python handler for three of the commands that we ran on Python 3.13; it resolves each path and refuses anything that escapes the memory root:

from pathlib import Path

ROOT = Path("agent_memory").resolve()
ROOT.mkdir(exist_ok=True)

def safe(path: str) -> Path:
    if path != "/memories" and not path.startswith("/memories/"):
        raise ValueError("path must be inside /memories")
    real = (ROOT / path.removeprefix("/memories").lstrip("/")).resolve()
    real.relative_to(ROOT)  # raises ValueError if the path escapes
    return real

def handle(cmd: dict) -> str:
    c = cmd["command"]
    if c == "view":
        p = safe(cmd["path"])
        if p.is_dir():
            return "\n".join(str(f.relative_to(ROOT)) for f in sorted(p.rglob("*")))
        return p.read_text()
    if c == "create":
        p = safe(cmd["path"])
        p.parent.mkdir(parents=True, exist_ok=True)
        p.write_text(cmd["file_text"])
        return f"File created successfully at: {cmd['path']}"
    if c == "str_replace":
        p = safe(cmd["path"])
        text = p.read_text()
        if text.count(cmd["old_str"]) != 1:
            return "Error: old_str must appear exactly once"
        p.write_text(text.replace(cmd["old_str"], cmd.get("new_str", "")))
        return "The memory file has been edited."
    return f"Error: unsupported command {c}"

In our test, creating and editing /memories/prefs.md worked, and /memories/../../etc/passwd and /etc/passwd were both refused. Pass the string this function returns back to Claude as the content of a tool_result block. The reference also covers insert, delete, rename and view with a line range, and suggests capping file sizes and deleting stale files. If you would rather skip a framework entirely, our guide on building an AI agent from scratch shows the tool loop this handler plugs into.

How this compares with memory layers like Mem0 or Letta

Claude Code's memory is small, readable and local. It works because a coding agent mostly needs a few dozen durable facts about a project and its owner, and Markdown files load cheaply. A product that serves thousands of users with long histories has different needs: search across many memories, per user separation, and a record of how facts change over time. That is the job of memory layers such as Mem0, Letta and Zep, which we compare in AI agent memory: Mem0 vs Letta vs Zep.

A useful rule: if a human should be able to open the memory and fix it by hand, files are the better fit. If the agent needs to search thousands of past conversations, reach for a memory layer or a vector database.

Common problems and fixes

  • Claude ignores a rule. Run /context and check the Memory files list. If the file isn't there, Claude can't see it. If it is, make the rule more specific and look for a conflicting rule elsewhere.
  • An instruction vanished after /compact. The project root CLAUDE.md is reread from disk after compaction. Instructions given only in chat are not, so move lasting ones into CLAUDE.md.
  • You don't know what Claude saved. Open /memory, choose the auto memory folder and read the files. Delete anything wrong.
  • Memory differs between machines. That is expected: auto memory is local. Put shared facts in a committed CLAUDE.md.

FAQ

Does Claude Code remember between sessions?

Yes. Each session starts with a fresh context window, but CLAUDE.md files and the first 200 lines or 25KB of the auto memory index load at the start of every session, so what you and Claude wrote down carries over.

Where does Claude Code store its memory?

Auto memory lives in ~/.claude/projects/<project>/memory/ on your machine, with a MEMORY.md index and one file per memory. CLAUDE.md files live in your repository, in ~/.claude/, or at a managed policy path. Subagent memory lives in an agent-memory folder at the scope you choose.

How do I turn off auto memory in Claude Code?

Use the toggle in /memory, set autoMemoryEnabled to false in user or project settings, or set the environment variable CLAUDE_CODE_DISABLE_AUTO_MEMORY=1. Turning it off also turns off subagent memory.

Is auto memory shared with my team?

No. Auto memory stays on the machine where it was written and is not synced to other machines or cloud environments. Share team knowledge through a committed CLAUDE.md, or give a subagent project scope memory, which lives in the repository.

Is Claude Code memory the same as the Claude API memory tool?

They share a design, a folder of files the model reads and edits, but they are separate. Claude Code manages its memory for you. The API memory tool hands each file command to your own code, so you choose the storage and must guard against unsafe paths.