Skip to content

Latest commit

 

History

History
269 lines (179 loc) · 23.3 KB

File metadata and controls

269 lines (179 loc) · 23.3 KB

The Complete Guide to CLAUDE.md Files in Claude Code

CLAUDE.md is a special memory file that Claude Code automatically loads at session start, serving as persistent project context across all interactions. It functions as a "constitution" for your AI assistant, defining project standards, workflows, and technical patterns. The file is officially documented by Anthropic and represents the most effective way to help Claude Code understand your codebase, though it requires explicit prompting to be consistently effective. Based on research across official documentation, 65+ real-world examples, and production usage experiences, well-crafted CLAUDE.md files should be concise (50-150 lines), specific rather than generic, and iteratively refined based on Claude's actual mistakes.

The feature works through a hierarchical memory system spanning enterprise policies, user preferences, and project-specific context, with all files automatically loaded into Claude's context window when launching a session. However, developers consistently report that Claude doesn't automatically adhere to CLAUDE.md instructions without explicit prompting—making deliberate workflow patterns essential for effectiveness.

What CLAUDE.md actually does and why it matters

Claude Code reads CLAUDE.md files automatically when starting any conversation, prepending the content to every prompt throughout the session. This creates persistent, authoritative context that remains active across the entire interaction, fundamentally different from one-off instructions in chat prompts. The file serves multiple critical functions: documenting frequently-used commands so Claude doesn't need to search repeatedly, recording project-specific conventions and architectural patterns, maintaining coding standards that persist across sessions, and providing repository etiquette like branch naming and commit message formats.

Anthropic's own teams demonstrate the value internally. New data scientists on their Infrastructure team "feed Claude Code their entire codebase to get productive quickly," with Claude reading CLAUDE.md files to identify relevant documentation, explain data pipeline dependencies, and show which upstream sources feed dashboards. According to Anthropic's internal blog: "The more comprehensive the Claude.md files, the better Claude Code performs."

The technical implementation treats CLAUDE.md instructions with strict hierarchical authority—as immutable system rules rather than flexible suggestions. This contrasts with user prompts, which Claude interprets as requests that must work within CLAUDE.md boundaries. This "constitutional" approach prevents Claude from drifting off-specification as conversations extend, though this benefit only materializes when you explicitly direct Claude to review the file.

The hierarchical memory system and when files load

Claude Code implements a four-tier memory hierarchy that loads automatically at session start. Enterprise policy memory sits at the system level (/Library/Application Support/ClaudeCode/CLAUDE.md on macOS, /etc/claude-code/CLAUDE.md on Linux, C:\ProgramData\ClaudeCode\CLAUDE.md on Windows), providing organization-wide instructions managed by IT teams for company coding standards, security policies, and compliance requirements.

User memory at ~/.claude/CLAUDE.md applies personal preferences globally across all projects—your individual coding style, preferred tooling shortcuts, and personal workflows. Project memory exists at ./CLAUDE.md or ./.claude/CLAUDE.md in your repository, containing team-shared instructions for project architecture, coding standards, and common workflows that get committed to version control.

Files higher in the hierarchy take precedence and load first, creating a foundation that more specific memories build upon. When Claude Code launches in a directory, it recursively searches upward from the current working directory to root (but not including /), reading all CLAUDE.md files it encounters. For example, running from /project/src/feature/ automatically loads /project/CLAUDE.md, /project/src/CLAUDE.md, and /project/src/feature/CLAUDE.md.

An important technical detail: CLAUDE.md files in subdirectories are supposed to load lazily—only when Claude accesses files within those directories—to optimize token usage for large monorepos. However, GitHub Issue #2571 reports this feature doesn't work reliably in current implementations. The previously supported CLAUDE.local.md for git-ignored local preferences is now deprecated in favor of the @import syntax for modular file loading.

How Claude processes these files and manages persistence

Every CLAUDE.md file gets parsed as standard Markdown with one special feature: @path/to/file syntax for importing additional files. Both relative and absolute paths work, enabling hierarchical organization. The system allows recursive imports with a maximum depth of 5 hops, and imports are ignored inside markdown code spans and code blocks to prevent accidental activation.

The content integrates into Claude's context by being prepended to every prompt during the session. This means CLAUDE.md content consumes your token budget continuously—approximately 1,000 tokens per 750 words. With context limits ranging from 200K tokens for standard plans to 500K for Enterprise Sonnet 4, token efficiency matters significantly. Best practice suggests keeping individual CLAUDE.md files under 50KB, ideally under 100KB, to avoid parsing delays.

Persistence works at two levels: Within a single session, CLAUDE.md content remains loaded throughout the entire conversation, maintaining consistent execution of defined patterns. Across multiple sessions, files are re-loaded fresh at each new claude CLI invocation—there's no persistent model memory. The files themselves persist on disk (in git or your file system), and changes take effect immediately in the next session. This means you can edit CLAUDE.md, save it, restart Claude Code, and see the updates instantly.

You can manually manage memory during sessions using the # shortcut (beginning input with # to quickly add memories) or the /memory command (opens CLAUDE.md in your system editor for extensive edits). Changes made via # take effect immediately; manual file edits require a session restart.

Best practices for helping Claude understand your project

The golden rule from Anthropic's engineering blog: "Keep them concise and human-readable." There's no required format, but effectiveness comes from specificity. "Use 2-space indentation" beats "format code neatly" every time. Organize content with clear markdown headers and format individual instructions as bullet points under descriptive headings.

Start with the /init command, which generates a basic CLAUDE.md by analyzing your codebase. Then customize iteratively. The recommended content structure includes:

Commands section documenting all development workflows—build, test, lint, database migrations, deployment. Claude won't guess these; explicit documentation prevents repeated searches. Code style with specific, enforceable rules like "Use ES modules (import/export) syntax, not CommonJS (require)" or "Destructure imports when possible." Project structure mapping key directories, but avoid obvious explanations—if a folder is named "components," don't explain it contains components.

Include workflow guidelines for branching strategy, commit message format, merge vs. rebase preferences, and PR requirements. Document environment setup specifics like "Python 3.11 required (use pyenv)" or compiler requirements. Add warnings and gotchas about unexpected behaviors particular to your project, like "NEVER modify files in src/generated—they are auto-generated."

Multiple senior engineers recommend a review process checklist:

## Review Process
Before submitting code:
1. Run all lint, check and test commands
2. Review outputs and iterate until resolved
3. Assess compliance with each standard

Anthropic specifically notes they "occasionally run CLAUDE.md files through the prompt improver and often tune instructions (e.g. adding emphasis with 'IMPORTANT' or 'YOU MUST') to improve adherence."

Techniques that make development dramatically easier

Think of CLAUDE.md as a living document, not set-and-forget configuration. When Claude makes preventable mistakes, immediately ask: "How can you modify CLAUDE.md to prevent this issue in future?" Let Claude propose the update, review it, refine to concise bullet points, and accept. This creates a continuously improving feedback loop that transforms Claude from generic assistant to project-aware partner.

Use XML tags for critical rules that must persist. Developers report that standard markdown sometimes leads to "instruction bleeding" where Claude forgets rules after 4-5 interactions. XML structure improves adherence:

<critical_notes>
- **MUST** follow these rules
- **NEVER** do these things
</critical_notes>

<paved_path>
The canonical way to do things - battle-tested patterns that MUST be followed
</paved_path>

Create nested CLAUDE.md files for large codebases. A root-level file covers organization standards, while frontend/CLAUDE.md addresses React patterns and backend/CLAUDE.md covers API conventions. This optimizes token usage by providing only relevant context and prevents conflicting instructions across different system areas.

Use file pointers instead of duplication. Rather than pasting example code into CLAUDE.md (consuming tokens), point to examples:

<example>
Lazy-loaded value - /app/features/chart.tsx, search:`getChartData`
Custom-rendered value - /app/components/table.tsx, search:`renderCell`
</example>

Combine CLAUDE.md with custom slash commands in .claude/commands/ for reusable workflows. A /review command might trigger comprehensive code review steps, while /fix-github-issue $ARGUMENTS automates the entire fix-test-commit-PR cycle for GitHub issues.

Critically, explicitly prompt Claude to reference CLAUDE.md. Multiple production developers confirm that automatic adherence "hasn't been as reliable as advertised." Use prompts like "Review our CLAUDE.md file before proceeding" or "Follow the review process described in CLAUDE.md" to ensure compliance.

Common mistakes that undermine effectiveness

The most frequent mistake is excessive verbosity. Long narrative paragraphs waste tokens and confuse Claude. "The components directory is where we keep our reusable UI components that can be imported throughout the application..." should be "components/ - Reusable UI components." Keep total length under 150-200 lines when possible. Multiple developers report Claude struggles with files exceeding 300 lines due to context window competition.

Vague instructions provide no value. "Write clean code," "follow best practices," and "use good naming conventions" are meaningless. Compare to specific rules: "Use React.FC type annotations for all components," "Prefer arrow functions over function declarations," "Name test files as ComponentName.test.tsx."

A critical but widespread error: assuming automatic compliance. The Maxitect engineering blog documents this clearly: "I asked Claude to review my code, and it didn't run any linter at all. Only when I specifically asked, 'what does it say in the CLAUDE.md file about code review?' did it suddenly remember." The reality is that CLAUDE.md provides context but requires deliberate reinforcement through explicit prompting.

Conflicting requirements across different sections confuse Claude. Saying "use TypeScript strict mode" in one section but "any is acceptable for external libraries" elsewhere creates ambiguity. Review the entire file for contradictions before saving.

Developers also report problems with placeholder code patterns. Without explicit prohibition, Claude generates mock functions and TODO comments instead of complete implementations. Add to your CLAUDE.md: "NO PARTIAL IMPLEMENTATIONS: Eliminate mocks, stubs, TODOs, or placeholder functions. All code must be production-ready."

Not iterating based on effectiveness wastes effort. Adding extensive content without testing if it improves Claude's behavior bloats your token budget. Add rules incrementally, observe results, and refine. If a rule doesn't change Claude's behavior after explicit testing, remove it.

Ignoring token budget implications causes context window issues. CLAUDE.md content appears in every prompt, competing with conversation history, file reads, and tool results. When approaching context limits, Claude automatically compacts conversation history, potentially losing important details. Solution: ruthlessly trim unnecessary content.

Finally, static files that never update become outdated and misleading. CLAUDE.md should evolve alongside your project. Outdated rules are worse than no rules, as they actively mislead Claude about current project state.

Examples of effective structures and content

The minimal structure (50-75 lines) works for small projects and prototypes:

# [Project Name]
[2-line description]

## Stack
- Next.js 14, TypeScript 5.2, Tailwind CSS

## Commands
- Dev: npm run dev
- Test: npm test
- Build: npm run build

## Code Style
- Use ES modules (import/export)
- Destructure imports when possible
- Prefer arrow functions

## Workflow
- Branch: feature/TICKET-description
- Commits: Conventional Commits format

The standard structure (100-150 lines) suits most production applications. Anthropic's own example demonstrates this approach:

# Bash commands
- npm run build: Build the project
- npm run typecheck: Run the typechecker

# Code style
- Use ES modules (import/export) syntax, not CommonJS (require)
- Destructure imports when possible (eg. import { foo } from 'bar')

# Repository etiquette
- Branch naming: feature/description or fix/description
- Never commit directly to main
- Squash and merge PRs

# Project structure
- src/app: Next.js App Router pages
- src/components: Reusable React components
- src/lib: Core utilities and API clients

# Review process
Before submitting:
1. Run all lint and test commands
2. Ensure 100% test pass rate
3. Check TypeScript has no errors

Real-world examples from the community show framework-specific patterns work exceptionally well. From a Svelte 5 project:

## Svelte 5 Runes (New Features)
- Use `$props()` rune: `let { task } = $props<{ task: Task }>();`
- Use `$state()` for mutable: `let count = $state(0);`
- Use `$derived` for computed: `let doubled = $derived(count * 2);`
- Use `$effect()` for side effects, NOT `onMount`

The enterprise structure (150-250 lines) includes advanced sections like anti-pattern elimination, quality assurance metrics, and metacognitive processing instructions for complex systems requiring high reliability.

A particularly effective pattern from Tyler Burnam at Netflix uses marker comments for code navigation:

## Key Code Sections
- `CLAUDE-note-data-structs: Core data structures (~30 lines)`
- `CLAUDE-note-api-client: HTTP client configuration (~50 lines)`
- `CLAUDE-note-error-handling: Custom error classes (~40 lines)`

Line count hints help Claude understand scope and locate relevant code sections efficiently.

Official Anthropic documentation and resources

Anthropic provides comprehensive official documentation across multiple sources. The primary resource is the engineering blog post at anthropic.com/engineering/claude-code-best-practices, covering recommended structure, content guidelines, and practical examples from internal Anthropic usage.

The official memory documentation at docs.claude.com/en/docs/claude-code/memory details the four-tier hierarchy, file locations for each operating system, import syntax specifications, and quick memory addition methods. This documentation explicitly states: "All memory files are automatically loaded into Claude Code's context when launched."

Anthropic's internal usage blog at anthropic.com/news/how-anthropic-teams-use-claude-code describes how their own teams leverage CLAUDE.md files, providing real-world validation of the approach. The company reports that new data scientists use Claude Code with comprehensive CLAUDE.md files to "get productive quickly," replacing traditional data catalog tools.

The settings reference at docs.claude.com/en/docs/claude-code/settings documents how CLAUDE.md integrates with the broader Claude Code configuration system alongside JSON settings files, slash commands, MCP servers, and plugins.

Official bootstrap instructions recommend using the /init command to automatically generate a starter CLAUDE.md by analyzing your codebase. Anthropic's guidance: "Bootstrap a CLAUDE.md for your codebase with the following command," then customize by adding frequently-used commands, documenting code style preferences, and including important architectural patterns.

The official feature set includes file imports using @path/to/import syntax, with both relative and absolute paths supported and recursive imports allowed up to 5 levels deep. The # shortcut provides the fastest way to add memories by beginning input with the # character, while the /memory command opens any memory file in your system editor for extensive modifications.

Anthropic explicitly states recommended content: "There's no required format for CLAUDE.md files. We recommend keeping them concise and human-readable." They suggest including repository etiquette, developer environment setup, unexpected behaviors or warnings, frequently-used bash commands, code style preferences, and naming conventions—but only what's "essential for every session."

Key official resources summary

Understanding when and how to leverage CLAUDE.md

The optimal mental model treats CLAUDE.md as a constitution rather than documentation. Documentation teaches; constitutions constrain and guide. Your CLAUDE.md defines the boundaries within which Claude operates, not comprehensive project knowledge. Save detailed explanations for actual documentation files that Claude can read when needed.

Combine CLAUDE.md with complementary Claude Code features for maximum effectiveness. Use MCP (Model Context Protocol) servers for dynamic external data while CLAUDE.md provides static rules. Create custom slash commands for specific workflows while CLAUDE.md defines general patterns. Configure permissions (via /permissions command) for security boundaries while CLAUDE.md addresses code quality standards.

The token efficiency equation matters significantly. With 200K-500K token limits and CLAUDE.md content prepended to every prompt, a 100-line CLAUDE.md consuming ~2,000 tokens seems reasonable until you realize that's 2,000 tokens on every single interaction. Over a 50-message session, that's 100,000 tokens—half your context budget—for repeated content. This explains why developers consistently recommend extreme brevity.

Modular organization through imports optimizes this tradeoff. Your main CLAUDE.md might be just 30-40 lines pointing to specific files:

# Core project context
@README.md
@docs/architecture.md

# Development workflows
@docs/git-workflow.md
@docs/testing-strategy.md

# Personal preferences
@~/.claude/personal-style.md

This structure keeps the base memory lean while providing access to detailed context when needed, though the recursive import feature has a practical limit of 5 hops to prevent circular references.

The feedback loop workflow transforms CLAUDE.md from static configuration to adaptive system. When Claude generates placeholder code, update CLAUDE.md: "NO PARTIAL IMPLEMENTATIONS." When Claude modifies protected files, add: "NEVER modify: node_modules/, .git/, dist/, .env." When Claude skips tests, specify: "ALL business logic requires unit tests; ALL API endpoints require integration tests."

Harper Reed, describing his experience with CLAUDE.md-driven development, reports completing "greenfield projects in 30-45 minutes regardless of complexity" by combining test-driven development with iteratively-refined CLAUDE.md files that capture project patterns as they emerge.

Practical implementation checklist

Getting Started:

  1. Install Claude Code and run /init in your project root
  2. Review auto-generated CLAUDE.md and trim verbose sections
  3. Add your most critical commands explicitly (build, test, lint, deploy)
  4. Document code style in specific, enforceable bullet points
  5. Include review process checklist
  6. Commit CLAUDE.md to version control
  7. Add CLAUDE.local.md to .gitignore for personal preferences (though deprecated)

Optimization Loop:

  1. Claude makes a preventable mistake
  2. Ask: "How can you modify CLAUDE.md to prevent this issue in future?"
  3. Review Claude's proposed update
  4. Refine into concise bullet points
  5. Test that the new rule works in practice
  6. Remove rules that don't change behavior

Prompting Patterns for Consistency:

  • Setup: "Before starting, review @CLAUDE.md to understand project standards"
  • Verification: "What specific standards from CLAUDE.md apply to this task?"
  • Review: "Follow the review process described in CLAUDE.md"
  • Learning: "Based on this error, what should we add to CLAUDE.md?"

Conclusion: Making CLAUDE.md work in practice

CLAUDE.md files represent the most effective mechanism for giving Claude Code persistent project context, but effectiveness requires deliberate use rather than passive configuration. The three critical success factors are: extreme brevity focusing only on essential rules, specific instructions rather than vague guidelines, and explicit prompting to remind Claude to reference the file.

Start with Anthropic's /init command to bootstrap a basic file, then customize based on your framework and project specifics. Document commands exhaustively—Claude won't guess, and searching wastes time. Add framework-specific patterns with concrete examples. Include a review process checklist that you explicitly invoke. Keep total length under 150 lines.

Most importantly, establish the workflow pattern of explicitly directing Claude to review CLAUDE.md when starting tasks: "Review our CLAUDE.md before proceeding." When Claude makes preventable mistakes, immediately ask how to update CLAUDE.md to prevent recurrence. This creates a self-improving system where the file continuously adapts to your project's actual patterns and challenges.

The difference between mediocre and exceptional AI-assisted development often comes down to this single file—not because CLAUDE.md is magic, but because it forces you to articulate project standards clearly, provides consistent context across sessions, and creates a framework for continuous improvement. Well-crafted CLAUDE.md files, combined with deliberate prompting patterns, transform Claude Code from a generic chatbot into a project-aware development partner that gets more effective over time.