Claude Code Memory and Context Persistence

Claude Code Memory allows context to persist across sessions through a hierarchical system of CLAUDE.md files and auto memory. The hierarchy includes managed policy, project memory, user memory, and local instructions, each with specific purposes and priority levels.

Project memory contains team-wide conventions and is shared through git, while user memory holds personal preferences. Auto memory is automatically generated by Claude to store patterns and insights. Files can be created using /init, updated with /memory, and scoped to specific directories using path-based rules.

Claude Code Memory — Understanding Claude Code memory is key to consistent results. This guide explains the CLAUDE.md hierarchy, project rules, user memory, and how context persists across sessions.

Claude Code Memory and Context Persistence — title card

Claude Code Memory: What You’ll Learn

In this guide to Claude Code Memory, you’ll work through practical, hands-on steps with real examples. Claude Code Memory is explained from the ground up so you can apply it immediately in your own projects.

In Claude Code, “memory” refers to context that carries over between sessions. While the conversation window resets each time you start fresh, memory files are loaded automatically every time Claude Code launches. This lesson explains the hierarchy of memory files, how to create and update them, and how auto memory operates in the background.

The Claude Code Memory Hierarchy

Claude Code has two main memory systems: CLAUDE.md files that you write, and auto memory that Claude writes for itself. The officially documented CLAUDE.md locations include managed policy (org-wide), project instructions (CLAUDE.md or .claude/CLAUDE.md), user instructions (~/.claude/CLAUDE.md), and local instructions (./CLAUDE.local.md — personal project-specific, gitignored).

Project memory is the one you’ll use most. It’s a markdown file committed to git and shared with your team. Put your tech stack, naming conventions, common commands, and non-obvious gotchas here. User memory is for personal preferences that apply across all your projects — your preferred patterns, how you like code explained, tools you always use.

In practice: Use project memory for everything a teammate would need to understand the codebase — setup steps, testing commands, architecture decisions. Use user memory for how you personally like to work, not what the project does. When a project memory entry only matters to you (for example, a custom alias or local shortcut), put it in CLAUDE.local.md instead so it stays private.

For larger projects, split instructions into .claude/rules/*.md files. Rules can be global to the project or scoped to paths with frontmatter. A rule with paths: src/api/**/*.ts only activates when Claude works with matching files:

---
paths: src/api/**/*.ts
---
All API endpoints must validate input with Zod. Return 400 with field-level errors on validation failure.

Creating and Updating Claude Code Memory

The fastest way to start is /init. Run it in your project directory and Claude analyzes the codebase to generate a starter CLAUDE.md. Use CLAUDE_CODE_NEW_INIT=1 claude for an interactive multi-phase setup flow.

For larger edits, /memory opens your memory files in your system editor. Make changes, save, and Claude reloads them automatically. If you want Claude to remember something automatically, ask it naturally, like “remember that the API tests require Redis.” If you want it written into CLAUDE.md, ask Claude explicitly to add it there. The @path/to/file import syntax lets you reference existing documentation rather than duplicating it:

# Project Standards

@README.md
@docs/architecture.md
@package.json

Imports support a maximum depth of four hops. First-time imports from external paths trigger an approval dialog.

Auto Memory

Auto memory is a directory where Claude writes its own notes during sessions — patterns it discovers, project-specific behaviors, debugging insights. The first 200 lines or 25KB of ~/.claude/projects/<project>/memory/MEMORY.md, whichever comes first, load automatically at session start. Additional topic files (debugging.md, api-conventions.md) are loaded on demand.

Subagents can also maintain their own auto memory. See the subagent configuration documentation for details.

You don’t need to maintain auto memory manually; Claude handles writes itself. You can read and edit the files if you want to correct or add to Claude’s notes. You can toggle it in /memory, disable it for a session with CLAUDE_CODE_DISABLE_AUTO_MEMORY=1 claude, or set autoMemoryEnabled in settings. To move the directory to a synced location or a custom path, set autoMemoryDirectory in user settings (not project or local settings — project and local settings can redirect writes to sensitive locations and are not accepted):

{
  "autoMemoryEnabled": true,
  "autoMemoryDirectory": "/path/to/shared/memory"
}

In large monorepos with many CLAUDE.md files, use claudeMdExcludes in settings to skip irrelevant ones:

{
  "claudeMdExcludes": ["packages/legacy-app/CLAUDE.md", "vendors/**/CLAUDE.md"]
}

Claude also loads CLAUDE.md files it finds above your current working directory, and it loads subdirectory CLAUDE.md files on demand when Claude reads files in those directories. In monorepos, claudeMdExcludes helps keep unrelated instructions out of context.


Real-World Code Examples: Claude Code Memory Configuration

Example 1: Project CLAUDE.md

A comprehensive project configuration file that defines architecture, standards, and conventions:

# Project Configuration

## Project Overview
- Name: E-commerce Platform
- Tech Stack: Node.js, PostgreSQL, React 18, Docker
- Team Size: 5 developers

## Architecture
@docs/architecture.md
@docs/api-standards.md
@docs/database-schema.md

## Development Standards

### Code Style
- Use Prettier for formatting
- Use ESLint with airbnb config
- Maximum line length: 100 characters

### Naming Conventions
- Files: kebab-case (user-controller.js)
- Classes: PascalCase (UserService)
- Functions/Variables: camelCase (getUserById)

### Git Workflow
- Branch names: feature/description or fix/description
- Commit messages: Follow conventional commits
- PR required before merge

Example 2: Personal CLAUDE.local.md (Not Committed to Git)

Personal preferences that stay local and are never shared with the team:

# My Development Preferences

## About Me
- Experience Level: 8 years full-stack development
- Preferred Languages: TypeScript, Python
- Communication Style: Direct, with examples

## Code Preferences

### Error Handling
I prefer explicit error handling with try-catch blocks.
Avoid generic errors. Always log errors for debugging.

### Testing
I prefer TDD (test-driven development).
Write tests first, then implementation.

### Architecture
I prefer modular, loosely-coupled design.
Use dependency injection for testability.

Example 3: Directory-Scoped Rules for src/api/

A CLAUDE.md file placed in src/api/ that overrides root settings for that directory:

# API Module Standards

This file overrides root CLAUDE.md for everything in /src/api/

### Request Validation
- Use Zod for schema validation
- Always validate input
- Return 400 with validation errors

### Authentication
- All endpoints require JWT token
- Token in Authorization header
- Token expires after 24 hours

### Response Format
{
  "success": true,
  "data": {},
  "timestamp": "2025-11-06T10:30:00Z",
  "version": "1.0"
}

### Rate Limiting
- 1000 requests per hour for authenticated users
- 100 requests per hour for public endpoints

Pro Tips

  • Keep CLAUDE.md under 300 lines (ideally under 100). LLMs are stateless — CLAUDE.md is the only file loaded into every conversation. Large files waste context. Use @imports for the rest.
  • Never store secrets in CLAUDE.md. API keys, passwords, tokens, and credentials must never appear in memory files — especially project-level files committed to git.
  • Use the right memory level for the job. Managed policy for company-wide rules, project memory for team standards (git-tracked), user memory for personal preferences, and directory-specific files for module overrides.
  • Be specific, not vague. Write “Use 2-space indentation for all JavaScript files” — not “follow best practices.” Concrete rules produce consistent behaviour; generic statements are ignored.
  • Use @imports to avoid duplication. Instead of copying README content into CLAUDE.md, write @README.md or @docs/api-standards.md. Imports support up to 5 levels of recursion and load automatically.

Hands-On Challenge: Set Up a Multi-Layer Memory System

Task: Create a three-tier memory hierarchy — project-level CLAUDE.md, a directory-specific override, and personal user preferences — then verify each is loaded correctly.

Steps

  1. Run /init in a project to generate a root CLAUDE.md with project overview, tech stack, and coding conventions
  2. Add an @docs/architecture.md import to reference existing documentation without duplicating it
  3. Create src/api/CLAUDE.md with API-specific rules (e.g., “all endpoints must use Zod validation and return a standard JSON envelope”)
  4. Create ~/.claude/CLAUDE.md with personal preferences (e.g., preferred indentation, testing framework, communication style)
  5. Start a new Claude Code session and ask: “What conventions should I follow for the API module?” — Claude should pull from both the project and directory-specific memory files

Expected Outcome

Claude should apply project-wide conventions from the root CLAUDE.md, override them with the more specific API rules from src/api/CLAUDE.md, and also respect your personal preferences from ~/.claude/CLAUDE.md — demonstrating the hierarchical memory system in action.

Hint: Use the @ import syntax to reference files like @README.md or @package.json inside your CLAUDE.md. This avoids duplication — Claude reads the referenced file at load time.


Knowledge Check: Claude Code Memory System

Test your understanding with these quiz questions. Try to answer each question before revealing the answer.

1. How many levels does the Claude Code memory hierarchy have, and what has the highest priority?

  1. 5 levels, User Memory is highest
  2. 7 levels, Managed Policy is highest
  3. 3 levels, Project Memory is highest
  4. 7 levels, Auto Memory is highest

Correct Answer: B. The hierarchy has 7 levels: Managed Policy > Project Memory > Project Rules > User Memory > User Rules > Local Project Memory > Auto Memory. Managed Policy (set by admins) has the highest priority.

2. How do you quickly add a new rule to memory during a conversation?

  1. Use the /memory slash command or ask conversationally
  2. Prefix your message with # (e.g., # always use TypeScript)
  3. Type /rule “rule text”
  4. Use @add-memory “rule text”

Correct Answer: A. The recommended ways to add memory are the /memory command (opens memory files in your editor) or asking Claude conversationally. The # prefix was discontinued.

3. What is the maximum depth for @path/to/file imports in CLAUDE.md?

  1. 3 levels deep
  2. 5 levels deep
  3. 10 levels deep
  4. Unlimited

Correct Answer: B. The @import syntax supports recursive imports up to a maximum depth of 5 to prevent infinite loops.

4. How do you scope a rule file to only apply to files in src/api/?

  1. Put the rule in src/api/CLAUDE.md
  2. Add paths: src/api/** YAML frontmatter to a .claude/rules/*.md file
  3. Name the file .claude/rules/api.md
  4. Use @scope: src/api in the rule file

Correct Answer: B. Files in .claude/rules/ support a paths: frontmatter field with glob patterns to scope rules to specific directories.

5. How do you disable Auto Memory completely?

  1. Delete the ~/.claude/projects directory
  2. Set CLAUDE_CODE_DISABLE_AUTO_MEMORY=1
  3. Add auto-memory: false to CLAUDE.md
  4. Use /memory disable auto

Correct Answer: B. Setting CLAUDE_CODE_DISABLE_AUTO_MEMORY=1 disables auto memory. Value 0 forces it on. Unset = default on.

Test Your Knowledge

/5

Lesson 3 Quiz: Memory System

Test your knowledge of Claude Code's memory hierarchy, CLAUDE.md, and memory management.

1 / 5

You want personal project preferences that are NOT committed to git. Which file should you use?

2 / 5

What is the maximum depth for @path/to/file imports in CLAUDE.md?

3 / 5

How do you quickly add a new rule to memory during a conversation?

4 / 5

How many levels does the Claude Code memory hierarchy have, and what has the highest priority?

5 / 5

What does the /init command do?

Your score is

0%

Additional Resources

ResourceTypeLink
Claude Code — Memory DocumentationOfficial Docscode.claude.com/docs/en/memory
Claude Code — Settings & ConfigurationOfficial Docscode.claude.com/docs/en/settings
Claude Code — Interactive Mode (/init, /memory)Official Docscode.claude.com/docs/en/interactive-mode
Claude Code — CLI ReferenceOfficial Docscode.claude.com/docs/en/cli-reference
Anthropic Settings GuideAnthropic Docsdocs.anthropic.com — settings

What is the difference between project and user memory?

Project memory is committed and shared with the team; user memory holds personal, machine-specific notes that never get pushed.

How often should I review memory?

Every few weeks. Delete stale facts so the assistant is never steered by outdated rules.

Can rules conflict?

Yes, and the more specific, more trusted layer wins. Path-specific rules beat repository-wide ones.

Putting It All Together

Strong project memory is less about writing more and more about writing the right things in the right place. When the committed file captures the conventions everyone shares and the local layers hold personal detail, the assistant behaves consistently for the whole team without anyone having to repeat themselves each session.

Think of the memory file as a living contract between you and the assistant. It states how the project is built, how it is tested, and the handful of rules that matter most. Keep that contract short, specific, and current, and the assistant will follow it closely instead of guessing at conventions you never wrote down.

The payoff compounds over time. Every rule you record once is a correction you never have to make again, every recorded command is work the assistant can verify on its own, and every pruned stale note is one less chance for the assistant to act on something that is no longer true.

Claude Code Memory: Frequently Asked Questions

Why does it matter at all?

Claude Code Memory is the system of CLAUDE.md files and settings that let the assistant persist project conventions, commands, and rules across sessions, so you never have to re-explain your stack or standards every time you start a new session.

What should go in a committed CLAUDE.md file versus local settings?

Durable, team-wide conventions belong in the committed file everyone shares. Machine-specific paths and personal preferences belong in local, uncommitted settings — mixing the two breaks the file for every other teammate who checks it out.

How are conflicts between memory layers resolved?

The more specific and more trusted layer wins: an organisation-managed policy overrides a project file, a project file overrides personal preferences, and a path-specific rule overrides a broad repository-wide one.

How often should I review or prune CLAUDE.md?

Review it every few weeks and delete anything that is no longer true. Stale facts left unpruned quietly steer the assistant toward outdated behavior, which is one of the most common causes of confusing results.

What makes a memory rule effective instead of vague?

Short, imperative, checkable statements work best — “never edit files in the build output folder” is concrete, while “write clean code” gives the assistant nothing reliable to act on.

Claude Code Memory gives you a solid, repeatable workflow. Bookmark this Claude Code Memory guide and revisit the steps whenever you need them.

Claude Code Memory and Context Persistence — key concepts card

Claude Code Memory: Common Mistakes to Avoid

Even experienced developers trip over the same issues when they start with Claude Code Memory. Watch for these and you will save real debugging time.

  • Putting machine-specific paths into the committed CLAUDE.md, which then breaks for every other teammate.
  • Writing long, vague rules the assistant cannot follow literally instead of short imperative statements.
  • Never pruning memory, so stale facts accumulate and quietly steer the assistant toward outdated behavior.
  • Duplicating the same rule across project and user memory, which makes conflicts hard to track down.

How the Hierarchy Resolves Conflicts

When two layers disagree, the more specific and more trusted layer wins. A managed policy set by an organisation overrides a project file, a project file overrides personal preferences, and a path-specific rule overrides a broad repository-wide one. Knowing this order saves you from chasing “why is it ignoring my rule” bugs.

Keep each layer doing the job it is best at. Put durable, team-wide conventions where everyone shares them, and keep machine-specific paths or personal style notes in a layer that never gets committed. That separation keeps the shared file clean and stops one developer’s local quirks from leaking into everyone else’s sessions.

A Practical Project-File Example

A strong project file is short and scannable. Open with one or two sentences describing the product, then list the exact build, test, and lint commands so the assistant can verify its own work. Follow that with a handful of imperative rules, each on its own line, written so they can be followed literally.

Resist the urge to write an essay. A wall of vague guidance is harder for the assistant to apply than five sharp, high-signal rules. Review the file every few weeks, delete anything that is no longer true, and treat it like code: small, reviewed changes beat a sprawling document nobody trusts.

Finally, write rules as outcomes rather than wishes. “Use tabs for indentation” and “never edit files in the build output folder” are concrete and checkable. “Write clean code” is not, and it quietly trains you to expect results the assistant has no reliable way to deliver.

Claude Code Memory: Best Practices

  • Keep project-wide rules in CLAUDE.md at the repo root; keep machine-specific notes in local memory.
  • Use path-specific rules so subfolders get their own conventions without bloating the root file.
  • Write rules as short imperative statements the assistant can follow literally.
  • Review memory periodically and delete stale facts so context stays accurate.
  • Prefer a few high-signal rules over a long wall of low-value text.
Claude Code Memory and Context Persistence — best practices card