CLAUDE.md Mastery
CLAUDE.md is your AI's operating system, not documentation.
Most advice about CLAUDE.md gets the job of the file wrong. You'll read that it should onboard Claude to your codebase. List the tech stack. Drop in the key commands. Sketch the folder layout. Some guides push the file under 60 lines while they're at it.
That framing misreads what the file is actually for.
Think of CLAUDE.md as a control file that governs Claude's behavior. It sets how the model runs, how a conversation gets managed, and how work moves between the central agent and its helpers. The facts about your stack belong somewhere else. Skills are that somewhere. They load on demand, bring exactly what's needed, and step back out when the job is done.
Two Paradigms: Onboarding vs. Orchestration
The Inferior Approach: Project Onboarding
The conventional read is that CLAUDE.md should "onboard Claude to your codebase." You answer three questions for the model: WHAT the tech stack is, WHY the project exists, and HOW to run it. A few guides push the whole file under 60 lines.
Several things break when you do it that way:
Priority saturation: Anything inside CLAUDE.md rides at high priority in the context window. The model treats the whole file as authoritative. Stuff every rule into it and every line is now fighting every other line for that same top slot. Your React notes collide with your API conventions while you're busy on a database migration. When everything is high priority, nothing is.
Context waste: A CLAUDE.md full of React patterns for your React app still loads on every single session. Even the ones where the work is a deployment script or a schema change.
No behavioral control: Listing the tech stack says nothing about how Claude should approach a problem. Nothing about handing work off. Nothing about pacing a multi-step job.
Repetition across projects: Every new repo spawns a new CLAUDE.md, and every new CLAUDE.md drifts from the last one. The AI ends up acting differently from project to project.
Static knowledge: Project docs rot. An API pattern you wrote half a year ago may have nothing to do with how the code works today.
Onboarding frames Claude like a contractor getting briefed on the morning's job. Orchestration frames Claude like a running system that needs its parameters set.
The Superior Approach: Orchestration Layer
CLAUDE.md should define:
- Operational workflows - The sequence Claude follows for every request
- Context management strategy - How to conserve and allocate context effectively
- Delegation patterns - When to use sub-agents vs. handle directly
- Quality standards - Coding practices, error handling, security requirements
- Coordination protocols - How to manage parallel vs. sequential work
Your stack, your patterns, your conventions live inside skills that load dynamically when they're relevant. Splitting things up that way buys you:
- Consistent AI behavior across all projects
- Efficient context usage - domain knowledge loads only when needed
- Portable expertise - skills transfer between projects
- Maintainable knowledge - update a skill once, benefit everywhere
Structuring Your CLAUDE.md
Core Principles Section
Start with the fundamental behaviors you want from your AI. These should apply universally, regardless of what project or task you're working on.
## Core Principles
### Skills-First Workflow
**EVERY user request follows this sequence:**
Request → Load Skills → Gather Context → Execute
Skills contain critical workflows and protocols not in base context.
Loading them first prevents missing key instructions.
### Context Management Strategy
**Central AI should conserve context to extend pre-compaction capacity**:
- Delegate file explorations and low-lift tasks to sub-agents
- Reserve context for coordination, user communication, and strategic decisions
- For straightforward tasks with clear scope: skip heavy orchestration, execute directly
**Sub-agents should maximize context collection**:
- Sub-agent context windows are temporary
- After execution, unused capacity = wasted opportunity
- Instruct sub-agents to read all relevant files, load skills, and gather examplesThese are the behaviors that fire on every interaction. Not project trivia that may or may not matter today.
Routing and Delegation Logic
Define when Claude should handle work directly versus delegate to specialists:
### Routing Decision
**Direct Execution**:
- Simple/bounded task with clear scope
- Single-component changes
- Quick fixes and trivial modifications
**Sub-Agent Delegation**:
- Complex/multi-phase implementations
- Tasks requiring specialized domain expertise
- Work that benefits from isolated context
**Lead Orchestrator**:
- Ambiguous requirements needing research
- Architectural decisions with wide impact
- Multi-day features requiring session managementWith routing written down, Claude makes real calls about who does what. No more doing everything alone. No more farming out work for the sake of it.
Operational Protocols
Define how Claude should coordinate work, especially when parallelism is possible:
## Operational Protocols
### Agent Coordination
**Parallel** (REQUIRED when applicable):
- Multiple Task tool invocations in single message
- Independent tasks execute simultaneously
- Bash commands run in parallel
**Sequential** (ENFORCE for dependencies):
- Database → API → Frontend
- Research → Planning → Implementation
- Implementation → Testing → Security
### Quality Self-Checks
Before finalizing code, verify:
- All inputs have validation
- Authentication/authorization checks exist
- All external calls have error handling
- Import paths verified against existing codebase examplesCoding Standards and Practices
Include universal coding principles that should govern all work:
## Coding Best Practices
**Priority Order** (when trade-offs arise):
Correctness > Maintainability > Performance > Brevity
### Task Complexity Assessment
Before starting, classify:
- **Trivial** (single file, obvious fix) → execute directly
- **Moderate** (2-5 files, clear scope) → brief planning then execute
- **Complex** (architectural impact, ambiguous requirements) → full research first
Match effort to complexity. Don't over-engineer trivial tasks or under-plan complex ones.
### Integration Safety
Before modifying any feature:
- Identify all downstream consumers using codebase search
- Validate changes against all consumers
- Test integration points to prevent breakageThe Rules Directory: Modular Instructions
As of Claude Code v2.0.64, you have another option for organizing instructions: the .claude/rules/ directory. Rules fix the saturation trap by letting you spread top-priority instructions across files with a narrow scope.
Key insight from Anthropic: A rules file rides at the same high priority as a CLAUDE.md file. What changes is that you can aim that priority with a path pattern. The rule only activates while matching files are in scope.
When Rules Beat CLAUDE.md
Rules pay off the moment your instructions have domain boundaries:
.claude/rules/
├── api-guidelines.md # Only relevant for API work
├── react-patterns.md # Only relevant for frontend
├── testing-rules.md # Only relevant for test files
└── security-rules.md # Only relevant for auth/payment codeEach file lives in project memory. The difference is you can pin a rule to a file pattern:
---
paths: src/api/**/*.ts
---
# API Development Rules
- All endpoints must validate input with Zod
- Return consistent error shapesThat rule only fires when Claude touches an API file. On the frontend, your API conventions stay quiet.
The Instruction Priority Hierarchy
Picture it as layers. Each layer pairs a priority level with a loading rule:
| Layer | Priority | Contains | Loads |
|---|---|---|---|
| CLAUDE.md | High | Operational workflows, routing logic | Always |
| Rules Directory | High | Domain-specific guidelines | Always (filtered by path) |
| Skills | Medium | Reusable procedures, cross-project expertise | On-demand |
| File contents | Standard | Code, documentation | When read |
CLAUDE.md holds the universal behavior you want at constant high priority. Rules hold the domain-specific stuff, and they get that priority only while the right files are open. Skills hold portable expertise at medium priority, loaded on demand.
Want the deep version, including path targeting and migration tactics? Read the Rules Directory guide.
Loading CLAUDE.md from Additional Directories
Since Claude Code v2.1.20, Claude can pull CLAUDE.md files in from directories outside your active project. Useful for monorepos, shared team conventions, and multi-project setups.
How it works:
# Enable the feature and specify additional directories
CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD=1 claude --add-dir ../shared-standards
# Multiple directories work too
CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD=1 claude --add-dir ../shared-config ../team-rulesWith the flag turned on, Claude pulls these files from each extra directory:
CLAUDE.mdfiles.claude/CLAUDE.mdfiles.claude/rules/*.mdfiles
Why this beats verbally pointing Claude at a file:
| Approach | Loads Automatically | Persists Across Sessions | Context Efficient |
|---|---|---|---|
--add-dir with env var | Yes | Yes | Yes (system memory) |
| "Read that CLAUDE.md" | No | No | No (costs tokens each time) |
Through --add-dir, external CLAUDE.md files become real system memory instead of conversation filler. They load on their own, survive session restarts, and sit inside the priority hierarchy.
Practical use cases:
Monorepo with shared standards:
company/
├── shared-standards/
│ └── CLAUDE.md # Company coding guidelines
├── apps/
│ ├── web/
│ │ └── CLAUDE.md # Web-specific rules
│ └── api/
│ └── CLAUDE.md # API-specific rulesFrom the web/ directory:
CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD=1 claude --add-dir ../../shared-standards
Cross-project consistency: Drop your personal development standards into one central folder and pull them into any project. No copied files.
Team onboarding: New teammates point at a shared directory of team conventions. That kills the "every project has a slightly different CLAUDE.md" problem.
Updated priority hierarchy:
| Layer | Priority | Contains | Loads |
|---|---|---|---|
| CLAUDE.md | High | Operational workflows, routing logic | Always |
| Rules Directory | High | Domain-specific guidelines | Always (filtered by path) |
| Additional Directories | High | Shared/external CLAUDE.md files | When --add-dir specified |
| Skills | Medium | Reusable procedures, cross-project expertise | On-demand |
| File contents | Standard | Code, documentation | When read |
Note: The feature only kicks in when CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD=1 is set. On its own, the --add-dir flag just grants file access to those directories. It does not load the CLAUDE.md files sitting inside them.
@import Syntax: A Simpler Alternative
--add-dir hands you an entire external directory. For pulling in one file at a time, there's a lighter option. CLAUDE.md files support @path/to/import syntax for composable memory:
See @README for project overview and @package.json for available npm commands.
# Standards
- coding guidelines @docs/coding-standards.md
- git workflow @docs/git-instructions.mdRelative and absolute paths both work. A relative path resolves from the file doing the importing, not from your working directory.
How this differs from --add-dir:
| Approach | Granularity | Loads | Requires env var |
|---|---|---|---|
@import | Individual files | Specified files only | No |
--add-dir | Entire directory | All CLAUDE.md + rules | Yes |
First-time approval: The first time Claude Code hits imports inside a project, an approval dialog appears that lists each file. It's a one-time call per project. Decline it and the dialog never comes back. Those imports stay off.
Recursive imports: An imported file can import more files, with a max-depth of 5 hops. This is how you build layered instruction sets:
# CLAUDE.md imports standards.md
@.claude/standards.md
# standards.md imports sub-files
@.claude/standards/api.md
@.claude/standards/testing.mdImports are skipped inside markdown code spans and fenced code blocks. A code example that mentions @path won't accidentally fire off a load.
CLAUDE.local.md: Personal Project Preferences
For preferences you don't want on the team's shared tree, use CLAUDE.local.md. The file is added to .gitignore automatically and loads right next to CLAUDE.md at the same priority.
Good fits:
- Your local dev server URLs and sandbox endpoints
- Personal test data preferences
- Branch naming conventions you prefer
- Editor and tool configurations specific to your setup
Git worktree tip: CLAUDE.local.md only lives in a single worktree. Pull in an import from your home directory and the same personal instructions ride along in every worktree you spin up:
# CLAUDE.local.md
@~/.claude/my-project-instructions.mdViewing Loaded Memory with /memory
Run /memory to list the files currently sitting in Claude's context, or to pop any loaded memory file open in your editor. Reach for this when an instruction seems missing from the model's behavior. Reach for it again when you want proof that an import chain and your rules are landing correctly.
Skills: Where Domain Knowledge Lives
Skills are the other half of the picture. CLAUDE.md defines how Claude operates. Skills supply what Claude knows about a specific domain.
The Skills Architecture
Anthropic frames the distinction directly: "Projects say 'here's what you need to know.' Skills say 'here's how to do things.'"
Skills use progressive disclosure:
- Metadata loads first (~100 tokens) - enough to know when the skill is relevant
- Full instructions load when needed (
<5k tokens) - Bundled files/scripts load only as required
Because of that design, you can keep dozens of skills on hand without blowing up the context window. Claude reaches for exactly the piece it needs, at the moment it needs it.
What Belongs in Skills
Technology patterns:
- Framework conventions (React patterns, API design)
- Database operations and migrations
- Testing strategies and utilities
Domain workflows:
- Payment processing integrations
- Authentication implementations
- Deployment procedures
Project-specific context:
- Codebase navigation guides
- Architecture documentation
- Team conventions
Example: Separating Concerns
Instead of putting this in CLAUDE.md:
## About This Project
FastAPI REST API for user authentication.
Uses SQLAlchemy for database operations.
## Commands
uvicorn app.main:app --reload
pytest tests/ -vCreate a backend-api skill:
# Backend API Development Skill
## Framework
FastAPI with SQLAlchemy ORM, Pydantic validation.
## Development Commands
- `uvicorn app.main:app --reload` - Start dev server
- `pytest tests/ -v` - Run test suite
- `alembic upgrade head` - Apply migrations
## Patterns
[Detailed patterns, examples, conventions...]Your CLAUDE.md references the skill system:
### Key Skills
`backend-api`, `frontend-react`, `database-ops`, `deployment`
Load relevant skills before beginning domain-specific work.Now the backend details only show up during backend work. Context stays free for the rest of the job. ClaudeFast's Code Kit already ships a production CLAUDE.md in this shape. Skills-first routing, a 5-tier complexity assessment, and context min-maxing are wired in by default.
The Line Count Debate
A popular take says CLAUDE.md should live under 60 lines, because Claude allegedly "ignores" anything longer. That read on how Claude handles context is wrong.
The reality: Anthropic recommends skill files stay under 500 lines. If a skill that only loads on demand can put 500 lines to good use, an always-loaded CLAUDE.md can certainly absorb 200 to 400 lines of operational detail.
Brevity isn't the thing to optimize for. Relevance is. Sixty lines of project trivia that doesn't apply to today's task eats more effective context than 300 lines of universal operational rules.
The sweet spot is 200-400 lines of:
- Operational workflows (always relevant)
- Routing logic (always relevant)
- Quality standards (always relevant)
- Coordination protocols (always relevant)
Sixty lines of project specifics, half of which are dead weight on any given request, is the worst of both worlds.
Framework Evolution
Bake instructions for self-improvement into the file:
### Framework Improvement
**Recognize patterns that warrant updates:**
**Update existing skill when**:
- A workaround was needed for something the skill should have covered
- New library version changes established patterns
- A better approach was discovered during implementation
**Create new skill when**:
- Same domain-specific context needed across 2+ sessions
- A payment processor, API, or tool integration was figured out
- Reusable patterns emerged that will apply to future projects
**Action**: Prompt user with: "This [pattern/workaround/integration] seems
reusable. Should I update [skill] or create a new skill to capture this?"The result is a self-improving system. Claude flags the moments that are worth turning into a new skill or an upgrade to an existing one.
Why This Approach Works
Multi-Agent Orchestration
Modern Claude Code work leans more and more on sub-agents: specialized instances running discrete jobs. Your CLAUDE.md is what tells the central model how to run that team.
Per Anthropic, Opus 4.5 was trained specifically to run a team of sub-agents. Put that training to work inside your CLAUDE.md by spelling out:
- When to delegate vs. handle directly
- How to construct sub-agent prompts
- How sub-agent results flow back to the main conversation
Context Economics
Your context window has a ceiling. Every byte of project documentation you pour into CLAUDE.md is a byte that can't be spent on the actual work. Orchestration is how you spend that budget well:
- CLAUDE.md: Operational instructions (always needed)
- Skills: Domain knowledge (loaded on demand)
- Sub-agents: Fresh context for specialized work
Consistency Across Projects
When the file codifies behavior rather than project trivia, the AI behaves the same way across every job. Routing, quality bars, and coordination habits all carry over. A React app gets the same treatment as a Python CLI tool.
Quick Reference
Request → Load Skills → Route Decision → Execute
Routing:
- Simple/bounded task → Direct execution
- Complex/multi-phase → Sub-agent delegation or session management
CLAUDE.md Contains:
- Operational workflows
- Context management strategy
- Routing and delegation logic
- Quality standards
- Coordination protocols
Skills Contain:
- Tech stack specifics
- Framework patterns
- Project conventions
- Domain workflows
Next Steps
-
Audit your current CLAUDE.md: Is it project documentation or operational instructions?
-
Extract domain knowledge to skills: Move tech stack, patterns, and conventions out of CLAUDE.md
-
Define your operational workflows: How should Claude approach every request?
-
Establish routing logic: When should Claude delegate vs. handle directly?
-
Set quality standards: What practices should govern all work?
Remember: CLAUDE.md is not a document Claude reads. It is the system Claude runs on. Define the behavior, push the knowledge out to skills, and let the whole thing keep improving itself over time.
Want the full playbook on top of these principles? Read our 5 Claude Code best practices that separate top developers.
Stop configuring. Start building.