Mastering CLAUDE.md: The Complete Guide to Persistent AI Assistant Configuration
This is the third installment in our comprehensive Claude Code Mastery series. In the previous article, we successfully configured permission settings to enable Claude Code to access your files safely and controllably. Today, we will take this a significant step further by leveraging CLAUDE.md to grant the AI assistant long-term memory capabilities, effectively eliminating the frustrating need to repeatedly explain your technology stack with each new conversation.
The All-Too-Familiar Scenario
Let me paint a scenario that you may find all too familiar. Picture this: it's Monday morning, and you open your terminal to launch Claude Code. You're eager to wrap up a feature that was left incomplete last week. You type in your request: "Add a batch query method to OrderService that returns order details based on a list of order IDs."
Claude quickly generates a piece of code. You glance at it, and immediately your brow furrows. The AI has used an ArrayList with a for-loop, executing single SQL queries one by one. However, your project has already encapsulated a batchQuery() method specifically designed for this purpose.
You type a correction: "Use batchQuery(), don't write manual loops to query the database."
Claude responds: "Okay, I'll switch to using batchQuery()." It then regenerates the code—only this time, it forgets your agreed-upon exception handling conventions. Your team's policy states: never swallow exceptions, and never use e.printStackTrace() directly. Instead, you should use log.error() and throw business exceptions.
You add another clarification: "Wrap exceptions using BusinessException, use log from @Slf4j for logging, and avoid System.out."
After four or five rounds of back-and-forth exchanges, ten minutes have slipped by. The code finally runs—barely. You exhale in relief, thinking the task is complete.
Tuesday arrives. You open a fresh terminal window and launch Claude Code again. You input an almost identical requirement: "Add a batch query method to UserService for retrieving user information."
Once again, Claude presents that same "standard answer"—manual for-loops with single SQL queries, no batch utilities, no exception wrapping, no logging conventions.
You take a deep breath and begin typing again: "Use batchQuery, wrap exceptions with BusinessException, use log for logging..."
By Wednesday, you begin to wonder if you've somehow stepped into a time loop. You clearly taught the AI these conventions yesterday, yet today it has forgotten everything.
Thursday comes, and you find yourself interrupting Claude before it even finishes generating code: "Use Spring Boot 3.2, Java 21, MyBatis-Plus, use batchQuery for batch operations, wrap exceptions with BusinessException, use Lombok's @Slf4j for logging, prohibit e.printStackTrace(), prohibit System.out..."
Claude replies: "Understood. I will complete the functionality following the above specifications."
But deep down, you know that the next time you launch a new session, it will remember nothing.
Identifying the Root Problem
What exactly is going wrong here? The fundamental issue is that Claude Code starts each session as a completely fresh conversation. It cannot see the conventions you typed in your previous session, nor can it read your pom.xml, application.yml, or the @Service annotations in your codebase. It's like having a new colleague arrive on their first day of work—you must teach them everything from scratch: "Our project is called XXX, we're using Java 21, the Spring Boot version is..."
This cycle continues until you discover CLAUDE.md.
With CLAUDE.md, you simply create a file in your project's root directory containing all those phrases you've repeated countless times each week. From that moment forward, Claude automatically reads this file every time it starts. When it opens your project, it's like flipping open a notebook filled with your habits and conventions—the framework version, utility classes, exception handling, logging standards, all documented in one place.
In this article, we will thoroughly explain everything you need to know about CLAUDE.md.
Understanding CLAUDE.md in One Sentence
CLAUDE.md is essentially a "project handover document" written specifically for Claude Code.
Think of it this way: when a new colleague joins your team, you provide them with an onboarding document that outlines the project objectives, technology stack, code structure, daily commands, and coding conventions—all clearly documented.
CLAUDE.md serves exactly this purpose. The only difference is that this "colleague" is Claude Code—an exceptionally capable assistant that unfortunately suffers from frequent memory loss. Therefore, before each task, it needs to read through this document first.
By placing CLAUDE.md in your project's root directory, Claude Code will automatically read it every time it initiates a session. You write your technology stack, conventions, commands, and agreements once—and from then on, you never have to teach everything from scratch with each conversation.
Location Matters: The Four-Tier Configuration System
Anthropic has designed a sophisticated four-layer configuration system that progresses from personal preferences to project-wide standards:
Tier 1: User Root Directory (~/.claude/CLAUDE.md)
This file stores your personal preferences—such as responding in Chinese, writing code comments in English, or following Conventional Commits for commit messages. All projects inherit these settings, forming Claude's basic understanding of you as a user.
Tier 2: Project Root Directory (/your-project/CLAUDE.md)
This file contains the current project's technology stack, coding standards, and commonly used commands. For example: "Java 21 + Spring Boot 3.2, use Lombok for logging, wrap exceptions with BusinessException." Claude automatically adheres to these conventions when working within this specific project.
Tier 3: Project Local Configuration (/your-project/CLAUDE.local.md)
This file stores project-level personal preferences that should not be committed to Git (remember to add it to .gitignore). For instance, you might have personal debugging habits or local-specific configurations for a particular project. Claude merges this file with CLAUDE.md, giving it higher priority—making it ideal for content that "only you need and don't want to affect your colleagues."
Tier 4: Subdirectory Configuration (/your-project/src/legacy/CLAUDE.md)
This file is used for local exceptions with progressive disclosure, loaded only when needed. For example, if you have a legacy module that you don't want to refactor according to new conventions, you can place a supplementary instruction file in that folder telling Claude: "Only fix bugs here, don't modify the structure."
Loading Order: User-level → Project-level (CLAUDE.md) → Project-level Local (CLAUDE.local.md) → Subdirectory-level. Later configurations override conflicting earlier ones.
You only need to spend about ten minutes clarifying these four layers, and thereafter, no matter which corner of which project Claude is working in, it will never again ask those questions that make your blood pressure rise.
What to Write and What to Avoid
CLAUDE.md is not a project manual—it's an "action guide" for AI. Writing too much wastes tokens, while writing too little is equivalent to writing nothing at all.
What to Write ✅
1. Technology Stack and Version Numbers
Stating "Java 21, Spring Boot 3.2, MyBatis-Plus 3.1.0" is sufficient. There's no need to copy the entire Spring documentation. Claude already knows how to use these frameworks—it just needs to know "which version you want me to use."
2. Key Differences in Coding Conventions
There's no need to copy the Java Style Guide or Alibaba's Java Manual into CLAUDE.md—Claude has already memorized those. You only need to document what differs from the standard conventions. For example: "Prohibit e.printStackTrace(), uniformly throw BusinessException," "Wrap return values using Result
3. Encapsulated Utility Classes and Common Methods
"Use JDBCTemplate.batchQuery() for batch queries, use CacheService.getOrLoad() for caching, use log from @Slf4j for logging."
These are unique to your project—things Claude doesn't know by default. But once you tell it, it will dutifully use them.
4. Commonly Used Commands
"Compile: mvn clean compile," "Run tests: mvn test," "Start locally: mvn spring-boot:run." Claude can proactively execute these commands when performing tasks. Knowing them in advance saves considerable explanation time.
5. Project-Specific Pitfalls
For example: "Don't directly modify the status field for order status transitions—call OrderService.transferStatus() instead. Obtain user IDs from UserContextHolder, don't pass them as parameters."
Write these historical lessons into CLAUDE.md, and Claude will help you avoid these pitfalls.
What NOT to Write ❌
1. General Knowledge
"How to configure a DataSource in Spring Boot" or "How to use Java's Optional."
Claude knows these better than you do. Writing them in wastes tokens and drowns out the truly important instructions.
2. Frequently Changing Content
For example: "Current iteration's requirement documents" or "Temporary test environment IP addresses."
These things change daily, and CLAUDE.md is not meant to be modified every day. Changing information should be communicated directly to Claude in each conversation.
3. Conflicting Instructions
Don't have both "Use BatchUtils for batch queries" and "Prefer MyBatis-Plus's selectBatchIds" appearing simultaneously. Claude will become confused and randomly choose one—forcing you to correct it later.
4. Vague Requirements
Phrases like "Write code as elegantly as possible" or "Ensure sufficient performance" are useless to AI. Instead, be specific: "Paginate batch operations exceeding 1000 records," "Keep individual methods under 80 lines."
Core Principle: Imagine you're writing a project handover document for a senior engineer who knows everything but just isn't familiar with this specific project. You only need to document special cases, not teach fundamental knowledge.
Rule of Thumb: Keep it between 100-200 lines. Research shows that AI models can stably follow approximately 150-200 instructions. Once you exceed this range, instruction compliance rates drop significantly. Rather than writing a comprehensive ten-thousand-character essay, create a refined guide where every line carries substantial weight.
Complete Implementation: Writing CLAUDE.md for Your Project
Analyzing Your Project and Generating a Draft
Navigate to your project directory, launch Claude Code, and input:
"Analyze the complete structure of this project and help me generate a CLAUDE.md draft, including project overview, technology stack, directory structure, coding conventions, and commonly used commands."
Alternatively, there's an even simpler approach: Claude Code has a built-in command:
/initThis command scans your project and generates an initial CLAUDE.md draft automatically.
Manual Refinement for the Final Version
The CLAUDE.md generated by Claude Code should only be considered a first draft reference. Project-specific coding conventions, technical constraints, team agreements, and discovered technical challenges all require manual supplementation and continuous refinement.
Testing the Effectiveness
After completing your CLAUDE.md file, open a brand new session to test it. Now input the following: "Add a method to OrderService to query order details by order ID and implement caching functionality."
At this point, you need no additional explanation. Claude Code will automatically recognize that the project uses the MyBatis-Plus framework and will employ Redis for caching.
This is the magic of CLAUDE.md—write once, and it takes effect automatically with every session.
Advanced Topic 1: Global Configuration for Personal Preferences
In addition to project-level CLAUDE.md, you should also maintain a global ~/.claude/CLAUDE.md that defines your universal preferences across all projects.
Here's a global CLAUDE.md template you can reference:
Language and Communication
- Respond to questions and write comments in Chinese
- Use Chinese for variable names, function names, and commit messages in code
- Prioritize analogies and examples when explaining technical concepts
Code Style
- Indentation: 2 spaces
- Quotes: Single quotes for strings
- Prefer named imports over default imports
Git Habits
- Commit message format: type(scope): description
- Don't automatically push—wait for my confirmation after committing
Response Preferences
- Provide solutions directly, reduce preamble
- When modifying code, explain "why" you're changing it, not just "what" you're changing
- When multiple solutions exist, list pros and cons for me to choose
Advanced Topic 2: Auto Memory—Claude Code's Own Notes
Claude Code features a capability called Auto Memory, which complements CLAUDE.md:
- CLAUDE.md: Instructions you write to Claude ("You must follow these conventions")
- Auto Memory: Notes that Claude takes itself ("I discovered a pitfall in this project...")
Storage Location: ~/.claude/projects/
You can directly edit the MEMORY.md file using the /memory command, or use interactive commands to have Claude Code remember certain things:
"Remember that this project's test database connection string is jdbc:mysql://test-db:3306/order"
What's the Difference Between CLAUDE.md and MEMORY.md?
| Aspect | CLAUDE.md | MEMORY.md |
|---|---|---|
| Content | Technology stack, coding conventions, common commands | Scattered preferences, debugging experience, daily discoveries |
| Creation | Manually edited | Automatically captured |
| Sharing | Team-shared | Personal-only |
Auto Memory won't transform Claude into a project expert overnight, but it addresses a very specific yet frustrating pain point—repetitive explanations. The longer you use it, the more it remembers, and the less you need to explain each time you start a session.
Advanced Topic 3: Modular Rules with .claude/rules/
After discussing CLAUDE.md and Auto Memory, let's explore the most flexible and team-collaboration-friendly component of Claude Code's memory system: modular rules via .claude/rules/.
If you've used CLAUDE.md in a team environment, you've likely encountered this problem: the file keeps growing longer and becomes increasingly difficult to maintain. Technical specifications, testing conventions, security requirements, API design guidelines—all crammed into a single file. Changing one line takes forever to find, and you often accidentally affect other content.
The solution is simple: break CLAUDE.md into multiple smaller files, each managing a separate concern.
You only need to create a .claude/rules/ folder in your project's root directory and place your rule files inside. Claude will automatically read all .md files within it.
Directory Structure
your-project/
├── .claude/
│ ├── CLAUDE.md # Master guide (optional)
│ └── rules/
│ ├── code-style.md # Code style conventions
│ ├── database.md # Database operation standards
│ ├── exception.md # Exception handling and logging
│ ├── transaction.md # Transaction management standards
│ ├── legacy.md # Legacy module special rules (path-limited)
│ ├── testing.md # Testing conventions
│ ├── security.md # Security requirements
│ ├── api-design.md # API design guidelines
│ └── git-workflow.md # Git workflow standardsEach file represents an independent concern. Need to modify code style? Simply edit code-style.md without affecting other rules. In team collaboration, different members can maintain rule files in their areas of expertise without conflicts.
Content Specifications
Simply place your rule files into .claude/rules/, and Claude Code will automatically load them on startup. If you want rules to apply only to specific files, add a YAML frontmatter with paths: at the top of the file:
---
paths:
- "src/main/java/**/*.java"
- "!src/main/java/**/legacy/**/*.java"
---
# Java Code Style Conventions
1. **Class Naming**: PascalCase, clear Service/Controller/DAO suffixes
2. **Method Length**: Individual methods should not exceed 50 lines; split if they do
3. **Dependency Injection**: Use constructor injection; prohibit @Autowired field injection
4. **Comments**: All public methods must have JavaDoc describing parameters, return values, and exceptions
5. **IDE Formatting**: Use Google Java Format plugin; format before committingThis configuration applies to all Java files but excludes those under the legacy package.
Loading Order
Rule files without paths restrictions are unconditionally loaded into system prompts when Claude Code starts.
Rule files that declare a paths field are loaded on-demand. Related rules are dynamically loaded into context only when Claude reads or processes files matching that path.
This is the key mechanism for balancing context usage and precisely controlling the scope of rule application.
Team Collaboration
The .claude/rules/ folder can be committed to Git for team-wide sharing. After each team member runs git pull, Claude Code automatically receives the latest rules.
If you have personal local preferences (such as connecting to a local database during testing), you can create .claude/rules.local/ (not committed to Git). It functions the same as .claude/rules/ but only takes effect on your local machine.
Using the /rules Command
Within a Claude Code session, type /rules. It will list all currently active rule files and their path restrictions. This is an excellent method for quickly checking "exactly which instructions Claude is following."
Advanced Topic 4: Maintenance Strategy
- Start Minimal: Only write the technology stack, project-specific tools, and most common pitfalls. Drive by pain points, don't aim for perfection from the start.
- Regular Audits: Monthly, check for outdated, useless, or redundant rules. Use
/initto compare against a newly generated draft. - Act as an Index, Not an Encyclopedia: Include references to detailed documentation (such as
@docs/api.md), and split specific conventions into.claude/rules/. Three Strategies to Prevent Bloat:
- Split into
rules/once exceeding 200 lines - Use
pathsto limit rule application scope - Delegate scattered preferences to Auto Memory (
/memory)
- Split into
- Reuse with @include: Use
@path/to/fileto import external documents, avoiding duplication. - Test After Changes: Verify that Claude correctly understands each new rule using a real task.
Core Philosophy: CLAUDE.md grows organically—it's not written all at once. It evolves naturally and requires regular pruning.
By implementing CLAUDE.md following these guidelines, you transform your AI assistant from a forgetful newcomer into a knowledgeable team member who understands your project's conventions from day one. The investment of time in creating and maintaining this document pays dividends in productivity, consistency, and reduced frustration across all your development sessions.