Blog

Claude Code memory: how CLAUDE.md, rules and auto memory work, with templates and what they cost in tokens

Ramashankar S · · Updated · 16 min read

Claude Code memory is two systems. CLAUDE.md files are instructions you write, at organization, user, project and local level, and Claude Code loads them into every session. Auto memory is a folder of notes Claude writes for itself in ~/.claude/projects/<project>/memory/, and the first 200 lines or 25KB of its MEMORY.md index load at every session start too.

Around those two sit .claude/rules/ files, which load at launch or only when Claude touches matching files, and @path imports, which pull other files into a CLAUDE.md. Everything that loads at launch rides along on every request, so a bloated memory file costs tokens on every turn. This guide covers Claude Code 2.1.322, the latest release on npm on 10 November 2026 (the stable channel is on 2.1.311).

How Claude Code memory works

Each session starts with an empty context window. Before you type anything, Claude Code adds the memory layers below, and Claude treats all of them as context it should follow, not as configuration Claude Code enforces. The memory docs point to hooks for anything that must happen every time.

LayerWho writes itWhere it livesWhen it loads
Managed CLAUDE.mdIT or platform team/Library/Application Support/ClaudeCode/CLAUDE.md (macOS), /etc/claude-code/CLAUDE.md (Linux, WSL), C:\Program Files\ClaudeCode\CLAUDE.mdEvery session, can't be excluded
User CLAUDE.mdYou~/.claude/CLAUDE.mdEvery session, every project
Project CLAUDE.mdThe team, committed./CLAUDE.md or ./.claude/CLAUDE.mdEvery session in the repo
Local CLAUDE.mdYou, gitignored./CLAUDE.local.mdEvery session in the repo
Unscoped rulesTeam or you.claude/rules/*.md, ~/.claude/rules/*.mdAt launch
Path-scoped rulesTeam or youSame folders, with paths: frontmatterWhen Claude reads, writes or edits a matching file
Subdirectory CLAUDE.mdTeamsrc/billing/CLAUDE.md and so onWhen Claude touches a file in that folder
Auto memoryClaude~/.claude/projects/<project>/memory/MEMORY.mdFirst 200 lines or 25KB, every session
The Claude Code memory layers in load order, with when each loads and whether it survives /compact

Three facts shape everything else:

  • Files are joined, not overridden. Content runs from the filesystem root down to your working directory, and CLAUDE.local.md comes after CLAUDE.md in each folder, so the most specific notes are read last. If two lines contradict each other, the docs warn that Claude "may pick one arbitrarily".
  • CLAUDE.md arrives as a user message after the system prompt, not inside the system prompt. For system-prompt-level text in scripts, use --append-system-prompt.
  • Project-root CLAUDE.md, unscoped rules and auto memory are re-read from disk after /compact. Subdirectory CLAUDE.md files and path-scoped rules are summarized away and load again only when Claude next touches a matching file, per the context window docs.

To see what actually loaded, run /context all and look under Memory files. /memory lists every CLAUDE.md location, toggles auto memory, and opens the memory folder.

CLAUDE.md levels and load order

Run Claude Code in foo/bar/ and it loads foo/CLAUDE.md, foo/bar/CLAUDE.md and any CLAUDE.local.md beside them at launch. Files below the working directory wait until Claude reads, writes or edits a file in their folder; since 2.1.293 that includes a single-file cat, head, tail, sed -n or grep in Bash.

Size limits differ by how a file loads:

  • A file that loads at launch arrives whole up to 4 MiB. Over 4 MiB, Claude Code skips it entirely.
  • Files that load on demand (subdirectory CLAUDE.md, their imports, path-scoped rules) are cut at 40,000 characters in a 200K context window and 150,000 characters in a 1M window on current models. Claude gets the start plus a note to read the rest. This limit arrived in 2.1.309; check a file with wc -m.
  • The docs recommend under 200 lines per CLAUDE.md. Claude Code warns at startup and in /status when one file passes the recommended length, or when several files add up past a combined limit.

claudeMdExcludes in any settings file skips other teams' CLAUDE.md files by glob, for example "**/monorepo/CLAUDE.md"; it can't exclude the managed file. Organizations can also put managed instructions straight into managed-settings.json with a claudeMd key.

HTML comments are free. Block-level <!-- notes for humans --> in a CLAUDE.md are stripped before Claude sees them (since 2.1.72), so maintainer notes cost no tokens. Comments inside code blocks are kept.

Don't edit CLAUDE.md mid-task and expect a change. The prompt caching docs say project-root and user files are read once at session start; an edit applies only after /clear, /compact or a restart. The edit doesn't break the prompt cache either.

Imports with @path

A line such as See @README.md for the overview expands that file into context alongside the CLAUDE.md that names it. Paths are relative to the importing file, absolute paths work, and imported files can import others up to four hops deep.

  • Escape spaces with a backslash: @Design\ Docs/api.md. A quoted path isn't imported at all.
  • Imports are skipped inside backticks and code blocks, so ` @README ` stays literal text.
  • An import that resolves outside the working directory in a project file triggers a one-time approval dialog. Decline it and those imports stay off for that project.
  • Imports organize; they don't save anything. An imported file costs exactly what it would cost pasted in.

The most useful import is personal: a gitignored CLAUDE.local.md exists only in the worktree where you made it, so for notes that follow you across worktrees, import a file from your home folder with @~/.claude/my-project-notes.md.

Claude Code rules: .claude/rules/

Claude Code rules are Markdown files in .claude/rules/ (subfolders included). A rule without frontmatter loads at launch with the same priority as .claude/CLAUDE.md. A rule with a paths: list loads only when Claude reads, writes or edits a matching file, which is the main way to keep area-specific instructions out of every request.

---
paths:
  - "src/api/**/*.ts"
  - "src/**/*.{ts,tsx}"
---

# API rules
- Validate request bodies with the zod schemas in src/api/schemas/
- Every new endpoint needs an entry in openapi.yaml; CI fails without it

What the rules section of the docs adds:

  • paths is the only frontmatter field Claude Code reads. Anything else is ignored silently, and YAML that doesn't parse makes the rule load as if it had no paths (run claude --debug to see why).
  • Patterns are relative to the folder that holds .claude. **/*.ts matches anywhere, /*.md only the top level. Brace groups multiply: {a,b}/{c,d}/*.{ts,tsx} is eight patterns, and one rule's list is capped at 1,000 expanded patterns.
  • ~/.claude/rules/ holds personal rules for every project. They load before project rules, and neither set wins a conflict.
  • Path-scoped rules don't survive /compact until a matching file is touched again. If a rule must hold through a long session, drop paths: or move it into the root CLAUDE.md.

Rules aren't the only option. Procedures (how to release, how to write a migration) belong in a skill, which costs only its name and description until used. Rules with zero exceptions belong in a hook or a deny rule, covered in the Claude Code hooks guide.

Auto memory and MEMORY.md

Auto memory, added in 2.1.59 (25 February 2026), is on by default in local sessions. As it works, Claude saves notes of four types, recorded in each file's type frontmatter: user (your role and preferences), feedback (corrections you gave and approaches you confirmed), project (deadlines and decisions not in the code or git history) and reference (where outside information lives, such as a dashboard). It skips anything it can derive from the code, and anything your CLAUDE.md already says.

The folder holds a MEMORY.md index, one line per memory, plus one topic file per memory:

~/.claude/projects/<project>/memory/
├── MEMORY.md            # index, first 200 lines or 25KB load every session
├── user_role.md         # read only when Claude needs it
├── feedback_testing.md
└── project_launch.md

How it behaves in 2.1.322:

  • The project key comes from the git repository, so every worktree and subfolder of one repo shares one memory folder. It is machine-local: nothing syncs to another computer or to cloud sessions.
  • Only the index loads at startup. Topic files are read with normal file tools when relevant, which shows in the terminal as "Recalled 2 memories"; writes show as "Saved 2 memories".
  • When an index write nears 200 lines or 25KB, Claude Code tells Claude to shorten it. Over the limit, the write succeeds but returns an error, because the excess is dropped at the next load.
  • Each memory write gets a modified ISO 8601 timestamp in its frontmatter, so Claude can judge how fresh a note is.
  • Saying "remember that the API tests need a local Redis" goes to auto memory. Saying "add this to CLAUDE.md" edits CLAUDE.md. The old # quick-memory shortcut was removed in 2.0.70.

To turn it off, use the toggle in /memory (it writes autoMemoryEnabled to ~/.claude/settings.json), set "autoMemoryEnabled": false in one project's settings, or export CLAUDE_CODE_DISABLE_AUTO_MEMORY=1. autoMemoryDirectory moves the folder; the value must be absolute or start with ~/.

Subagents get their own memory. A custom subagent with memory: project in its frontmatter keeps notes in .claude/agent-memory/<name>/ (committable), memory: local in .claude/agent-memory-local/<name>/, and memory: user in ~/.claude/agent-memory/<name>/. The main conversation's auto memory isn't loaded into subagents, except forks, per the subagents docs.

AGENTS.md and other tools

Since 2.1.277 (18 September 2026), Claude Code reads AGENTS.md when there is no CLAUDE.md, .claude/CLAUDE.md or CLAUDE.local.md in the working directory or above it. Note the trap: adding a personal CLAUDE.local.md to an AGENTS.md repo stops Claude reading AGENTS.md. Set Project instructions in /config to claude-md-and-agents-md to read both, or import it as in the templates below. /init also pulls in .cursorrules, .cursor/rules/ and .github/copilot-instructions.md when it writes a starter file. The cheat sheet has the rest of the setup commands.

Claude Code templates for CLAUDE.md and rules

These follow the docs' guidance: commands Claude can run, conventions it can't infer, and gotchas, with no architecture tour Claude could read from the code. Replace the commands with yours.

Project CLAUDE.md, committed at the repo root:

# Commands
- Install: pnpm install
- Test one file: pnpm vitest run path/to/file.test.ts
- Typecheck: pnpm tsc --noEmit
- Lint and fix: pnpm eslint --fix <files>

# Conventions
- Use the error helpers in src/lib/errors.ts; never throw raw strings
- src/legacy/ is live, but don't copy its patterns into new code
- New database columns need a migration in db/migrations/ and a review

# Gotchas
- Integration tests need DATABASE_URL; see .env.example
- The payments sandbox rate-limits at 10 requests per second

# Compact instructions
When compacting, keep test output, file paths changed and open TODOs.

<!-- Maintainers: keep this under 60 lines. Area rules go in .claude/rules/. -->

Local notes, CLAUDE.local.md, listed in .gitignore:

- Local API runs at http://localhost:4010 with seed user test@example.test
- @~/.claude/notes/acme-api.md

User CLAUDE.md, ~/.claude/CLAUDE.md, for every project:

- Explain a plan in three lines before editing more than three files
- Prefer small commits with messages in the imperative mood
- Ask before adding a new dependency

A path-scoped testing rule, .claude/rules/testing.md:

---
paths:
  - "**/*.test.ts"
  - "tests/**/*"
---
- Use the factories in tests/factories/, not inline fixtures
- Mock the clock with vi.useFakeTimers(); never sleep in tests
- One behavior per test; name tests "does X when Y"

A repo shared with Codex, Cursor or Gemini CLI, CLAUDE.md next to AGENTS.md:

@AGENTS.md

## Claude Code
Use plan mode for changes under src/billing/.

A reviewer subagent with its own project memory, .claude/agents/reviewer.md:

---
name: reviewer
description: Reviews diffs for bugs and this repo's conventions
memory: project
model: sonnet
---
Before reviewing, read your memory for patterns seen before.
After reviewing, save new recurring issues to your memory.

For ready-made components, the community claude-code-templates project (MIT, about 33,200 GitHub stars, npm version 1.33.1 on 10 November 2026) installs agents, commands, hooks, settings, MCP configs and 14 templates with npx claude-code-templates@latest. Read each file before you install it: anything it adds to CLAUDE.md or rules joins every request, and hooks run commands on your machine. /init is the other starting point; set CLAUDE_CODE_NEW_INIT=1 first for an interactive version that also proposes skills and hooks.

What Claude Code memory costs in tokens

Every launch-time memory file is sent with every request. Claude Code puts CLAUDE.md, auto memory and unscoped rules in a cached block right after the system prompt, so on most turns those tokens bill at the cache-read rate, and you pay the cache-write rate again whenever that block is rebuilt: a new session, /clear, /compact, or an idle gap longer than the cache lifetime (five minutes on an API key, one hour for the main conversation on a subscription).

Anthropic's pricing page on 10 November 2026, per million tokens:

ModelCache read5-minute cache writeInput
Claude Opus 5.5$0.20$5.00$4.00
Claude Sonnet 5.5$0.10$2.50$2.00

Anthropic's glossary puts a token at about 3.5 English characters on older models and says Claude 4.7 and later produce about 30% more tokens for the same text, so about 2.7 characters per token. The table below uses that ratio, 300 requests a day for 20 days (the daily scenario in the Claude Code pricing breakdown) and eight rebuilds a day.

Memory loaded at launchCharactersAbout tokensOpus 5.5 per monthSonnet 5.5 per month
Lean CLAUDE.md, 60 lines2,7001,000$2.01$1.00
CLAUDE.md at the 200-line guideline10,0003,700$7.43$3.71
Full MEMORY.md index, 25KB25,0009,300$18.57$9.29
Bloated CLAUDE.md, 1,000 lines50,00018,600$37.14$18.57
The docs' /usage example, 49k tokensabout 132,00049,000$98.00$49.00
Monthly cost of Claude Code memory files by size on Opus 5.5 and Sonnet 5.5

Per request the numbers look tiny: a 200-line file is $0.00074 per Opus 5.5 turn and $0.019 per rebuild. Over a month it adds up, and four things multiply it:

  • Subagents. Built-in subagents other than Explore and Plan, and custom ones, load your CLAUDE.md files too, each in its own context and its own cache. Set omitClaudeMd: true (2.1.271 and later) on a custom subagent that gets everything from its prompt.
  • Agent teams. Every teammate loads CLAUDE.md, MCP servers and skills, per the costs docs; see the agent teams guide.
  • Auto memory stacks on top. A full index plus a 200-line CLAUDE.md is about 13,000 tokens before your first word.
  • Long gaps. On an API key, every coffee break past five minutes rewrites the whole prefix at the write rate. promptCacheTtl: "1h" stretches that, at $8.00 per million for Opus 5.5 writes.

On a Pro, Max or Ultra plan the dollar figure isn't your bill, but the tokens still count. /usage flags this directly: the docs' own example recommendation reads Trim ~/code/api/CLAUDE.md · 49k tokens per request, and pressing f (2.1.305 and later) asks Claude to apply the fixes it can. To price a different file size, paste it into Aight's token cost calculator; for per-token rates on every Claude model, see the Claude API pricing guide.

The bigger cost is attention, not dollars. The docs say longer files "reduce adherence", and the best-practices page says a line that needs IMPORTANT to be followed is either lost in a long file or a rule that belongs in a hook.

How to keep memory small and followed

  1. Run /init, then cut. The best-practices page says the work after /init is mostly removing lines.
  2. Keep four kinds of lines: commands to check work, places where the code misleads, decisions not in the repo, and anything you've corrected twice.
  3. Move area rules to .claude/rules/ with paths:, and procedures to skills.
  4. Move must-never rules to configuration. A Read(./.env) deny rule or a PreToolUse hook holds every time; a CLAUDE.md line holds almost every time.
  5. Run /doctor for proposed trims of content Claude can derive from the code, and /doctor prompt-audit (2.1.283 and later) to find instructions written for older models, missing files and contradictions. Nothing changes until you approve.
  6. Open the memory folder with /memory every few weeks and delete stale notes. Check /context all after big edits.
  7. Log loads with the InstructionsLoaded hook when a path-scoped rule doesn't seem to fire.
A full Claude Code setup walkthrough, including CLAUDE.md and memoryTech With Tim · 48:21 · YouTube
Configures a project from scratch on a current version, with chapters on CLAUDE.md, memory and settings.

What developers report

  • One user asked for a configurable index cap: with about 500 memory files, their MEMORY.md sat near 17KB in only 41 lines, so the 25KB byte limit binds first (GitHub issue #79217, 19 Jul 2026, link).
  • Another found a months-old MEMORY.md describing a project that no longer existed in that form, loading into every session with no sign of its age (GitHub issue #85075, 8 Aug 2026, link). The modified timestamps help Claude, but pruning is still on you.
  • A Windows user on Opus 5.5 logged 25 hook blocks in one session, 22 of them real violations of CLAUDE.md or memory rules, including rule one of a 58-line file skipped about six times (GitHub issue #106330, 31 Oct 2026, link). That is the case for hooks over prose.
  • On compressing CLAUDE.md, a Hacker News commenter noted "Claude tokenizer handles markdown pretty efficiently, like a ## header is like 1-2 tokens", so stripping formatting saves less than character counts suggest (Hacker News, 25 Feb 2026, link).
  • When AGENTS.md support shipped, the Hacker News thread drew 741 points, and two commenters said they could now delete their CLAUDE.md symlinks to AGENTS.md (Hacker News, 18 Sep 2026, link).

FAQ

Where is Claude Code memory stored?

CLAUDE.md files live where you put them: ~/.claude/CLAUDE.md for you, ./CLAUDE.md or ./.claude/CLAUDE.md for the project, ./CLAUDE.local.md for private project notes. Auto memory lives in ~/.claude/projects/<project>/memory/, one folder per git repository, on your machine only.

Does Claude Code remember between sessions?

Not the conversation itself. Each session starts with an empty context, then loads your CLAUDE.md files and the first 200 lines or 25KB of the auto memory index. To pick up an old conversation, use claude -c or claude -r <name>.

How do you turn off Claude Code auto memory?

Use the toggle in /memory, set "autoMemoryEnabled": false in a project's .claude/settings.json, or set CLAUDE_CODE_DISABLE_AUTO_MEMORY=1. Turning it off also disables the memory field on subagents.

How long should CLAUDE.md be?

Anthropic's docs recommend under 200 lines per file, and Claude Code warns at startup when a file or the combined set runs long. The example in Anthropic's best-practices page is 12 lines. Area-specific rules can go to .claude/rules/ with paths: so they load only when needed.

What's the difference between CLAUDE.md and .claude/rules?

Both are Markdown instructions Claude reads. A rule without frontmatter behaves like CLAUDE.md and loads at launch; a rule with paths: loads only when Claude touches a matching file, so it costs nothing in sessions that never go near that code.

Why does Claude ignore CLAUDE.md instructions?

Usually the file didn't load (check /context all), two files contradict each other, the instruction is vague, or the file is long enough that the line gets lost. If a rule must hold every time, make it a hook or a deny rule, since CLAUDE.md is guidance Claude can judge doesn't apply.


Sources

Checked on 10 November 2026.