The Problem: Why Claude Code Keeps Forgetting Your Rules

Imagine this scenario: It's Monday morning, and you fire up Claude Code to finish a feature you started 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 code. But as you scan it, your frown deepens—it's using a basic ArrayList for-loop with individual SQL queries, one at a time. Yet your project already has a well-encapsulated batchQuery() method ready to use.

You correct it: "Use batchQuery(), don't write manual loops to query the database."

Claude responds: "Okay, I'll use batchQuery() instead." Then it regenerates the code—only this time, it forgets your exception handling conventions: don't swallow exceptions, and don't just call e.printStackTrace(). Instead, use log.error and throw business exceptions.

You add another correction: "Wrap exceptions with BusinessException, use log from Lombok's @Slf4j, not System.out."

After four or five rounds of back-and-forth, ten minutes have passed. The code finally runs, barely. You exhale in relief—task completed.

Tuesday arrives. You open a new terminal window, launch Claude Code, and enter an almost identical requirement: "Add a batch query method to UserService."

Claude once again produces that "standard answer"—manual for-loop with individual SQL queries, no batch utilities, no exception wrapping, no logging standards.

You take a deep breath and start typing again: "Use batchQuery, wrap exceptions with BusinessException, log with log..."

By Wednesday, you start wondering if you're trapped in a time loop. You taught it all of this yesterday, yet today it remembers nothing.

By Thursday, you interrupt Claude before it even finishes generating code: "Use Spring Boot 3.2, Java 21, MyBatis-Plus, batch operations with batchQuery, exceptions with BusinessException, logging with Lombok's @Slf4j, no e.printStackTrace(), no System.out..."

Claude replies: "Understood, I'll follow these specifications."

But you know the truth: next time you launch it, it will remember nothing at all.

The Root Cause: Stateless Sessions

The problem lies in how Claude Code operates. Each time you launch it, you're starting a completely fresh session. 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 code. It's like a new colleague arriving on their first day of work—you have to teach them everything from scratch: "Our project is called XXX, we use Java 21, our Spring Boot version is..."

This cycle continues until you discover CLAUDE.md.

What Is CLAUDE.md?

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 give them an onboarding document—project goals, tech stack, code structure, daily commands, coding standards, all written out clearly.

CLAUDE.md serves exactly that purpose, except the "colleague" is Claude Code—highly capable but prone to frequent memory loss. So before each task, it needs to read this document first.

Place it in your project root directory, and Claude Code will automatically read it every time it starts a session. Write your tech stack, standards, commands, and conventions into it once—and from then on, you'll never have to teach it everything from scratch in every conversation.

The Four-Layer Configuration System

Anthropic has designed a four-tier configuration system that progresses from personal preferences to project specifications:

Layer 1: User Root Directory (~/.claude/CLAUDE.md)

Store your personal preferences here—such as "respond in Chinese," "use English for code comments," or "follow Conventional Commits for commit messages." All projects inherit these settings, forming Claude's basic understanding of you as a user.

Layer 2: Project Root Directory (/your-project/CLAUDE.md)

Store the current project's tech stack and coding conventions here. For example: "Java 21 + Spring Boot 3.2, logging uses lombok, exceptions use BusinessException." Claude will automatically follow these when working within this project.

Layer 3: Project Local Directory (/your-project/CLAUDE.local.md)

This is for 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 special configurations for a specific project. Claude merges this with CLAUDE.md, with higher priority—perfect for content that "only you need, without affecting your colleagues."

Layer 4: Subdirectory Level (/your-project/src/legacy/CLAUDE.md)

Used for local exceptions with progressive disclosure, loaded only when needed. For example, if you don't want to refactor an old module according to new specifications, place a supplementary instruction file in that folder telling Claude: "Only fix bugs here, don't touch the structure."

Loading Order: User level → Project level (CLAUDE.md) → Project local (CLAUDE.local.md) → Subdirectory level. Later layers override conflicting items from earlier layers.

Spend just ten minutes writing these layers clearly, and Claude will never ask those blood-pressure-raising questions again, no matter which corner of which project it's working in.

What to Write (and What Not to Write)

CLAUDE.md is not a project manual—it's an "action guide" for AI. Write too much, and you waste tokens; write too little, and it's as if you wrote nothing at all.

What to Write ✅

1. Tech Stack and Version Numbers

"Java 21, Spring Boot 3.2, MyBatis-Plus 3.1.0" is sufficient—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 Standards

No need to copy the Java Style Guide or Alibaba Java Manual—Claude has already memorized those. Only write what differs from general standards: for example, "禁止 e.printStackTrace(), uniformly throw BusinessException," "wrap return values with Result," "no underscores in field naming."

3. Encapsulated Utility Classes and Common Methods

"Use JDBCTemplate.batchQuery() for batch queries, CacheService.getOrLoad() for caching, log from @Slf4j for logging."

These are unique to your project—Claude doesn't know them by default, but once you tell it, it will use them faithfully.

4. Common Commands

"Compile: mvn clean compile," "Run tests: mvn test," "Start locally: mvn spring-boot:run." Claude can proactively run these commands when executing tasks, and knowing them in advance saves a lot of explanation time.

5. Project-Specific Pitfalls

For example: "Don't directly modify the status field for order status transitions—call OrderService.transferStatus() instead," or "Get user IDs from UserContextHolder, don't pass them as parameters."

Write these historical lessons into the file, and Claude will help you avoid these pitfalls.

What Not to Write ❌

1. General Knowledge

"How to configure data sources in Spring Boot," "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

Such as "current iteration requirements" or "temporary test environment IP addresses." These change daily, and CLAUDE.md is not meant for daily edits. Variable information should be told to Claude directly in each conversation.

3. Conflicting Instructions

Don't have both "Use BatchUtils for batch queries" and "Prioritize MyBatis-Plus's selectBatchIds" appearing simultaneously. Claude will get confused and randomly pick one—you'll have to come back and correct it again.

4. Vague Requirements

"Write elegant code" or "Ensure good performance"—such phrases are useless to AI. Replace them with specifics: "Paginate batch operations exceeding 1000 items," "Keep individual methods under 80 lines."

Core Principle: Imagine you're writing a project handover document for a senior engineer who knows everything—they just don't know this particular project yet. Write only the special cases, not the fundamentals.

Rule of Thumb: Keep it under 100-200 lines. Research shows AI models can stably follow approximately 150-200 instructions. Beyond that range, compliance rates drop significantly. Rather than writing a comprehensive 10,000-character essay, craft a concise guide where every line carries weight.

Practical Implementation: Writing CLAUDE.md for Your Project

Analyze and Generate a Draft

Navigate to your project directory, launch Claude Code, and enter:

"Analyze the complete structure of this project and generate a CLAUDE.md draft for me, including project overview, tech stack, directory structure, coding standards, and common commands."

Or there's an even simpler operation—Claude Code has a built-in command:

/init

This command scans your project and generates an initial CLAUDE.md draft.

Manual Supplementation for the Final Version

The CLAUDE.md generated by Claude Code serves only as a reference draft. Project-specific coding standards, technical constraints, team agreements, and discovered technical challenges all require manual supplementation and continuous improvement.

Testing the Results

After completing the CLAUDE.md file, open a brand new session to test it. Now enter the following: "Add a method to OrderService that queries 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 MyBatis-Plus framework and will use Redis for caching.

This is the magic of CLAUDE.md—write once, and it takes effect automatically in every session.

Advanced Feature 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 for reference:

## Language and Communication
- Answer questions and write comments in Chinese
- Use Chinese for variable names, function names, and commit messages
- 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 auto-push; wait for my confirmation after committing

## Response Preferences
- Give solutions directly, minimize preamble
- When modifying code, explain "why" not just "what changed"
- When multiple approaches exist, list pros and cons for me to choose

Advanced Feature 2: Auto Memory—Claude Code's Own Notes

Claude Code includes a feature called Auto Memory (automatic memory). It complements CLAUDE.md:

  • CLAUDE.md: Instructions you write for Claude ("You must follow these standards")
  • Auto Memory: Notes Claude takes itself ("I discovered a pitfall in this project...")

Storage Location: ~/.claude/projects//memory/

You can edit the MEMORY.md file directly via the /memory command, or use interactive commands to let Claude Code remember certain things:

"Remember that this project's test database connection string is jdbc:mysql://test-db:3306/order"

CLAUDE.md vs MEMORY.md: What's the Difference?

AspectCLAUDE.mdMEMORY.md
ContentTech stack, coding standards, common commandsScattered preferences, debugging experiences, daily discoveries
CreationManually editedAutomatically captured
SharingTeam-sharedPersonal only

Auto Memory won't turn Claude into a project expert overnight, but it solves a very specific yet annoying pain point—repeated explanations. The longer you use it, the more it remembers, and the less you need to explain each time you launch.

Advanced Feature 3: Modular Rules with .claude/rules/

After discussing CLAUDE.md and Auto Memory, let's explore the most flexible and team-collaboration-friendly part of Claude Code's memory system—the .claude/rules/ modular rules.

If you've used CLAUDE.md in a team environment, you've probably encountered this problem: the file grows longer and longer, becoming increasingly difficult to maintain. Technical standards, testing conventions, security requirements, API design principles—all crammed into one file. Changing one line takes forever to find, and you often accidentally break other content.

The solution is simple: split CLAUDE.md into multiple small files, managed separately by topic.

Simply create a .claude/rules/ folder in your project root directory and place your rule files inside. Claude will automatically read all .md files within it.

Directory Structure:

your-project/
├── .claude/
│   ├── CLAUDE.md           # Main guidelines (optional)
│   └── rules/
│       ├── code-style.md   # Code style standards
│       ├── database.md     # Database operation standards
│       ├── exception.md    # Exception handling and logging
│       ├── transaction.md  # Transaction management standards
│       ├── legacy.md       # Special rules for legacy modules (path-limited)
│       ├── testing.md      # Testing standards
│       ├── security.md     # Security requirements
│       ├── api-design.md   # API design principles
│       └── git-workflow.md # Git workflow standards

Each file represents an independent concern. Need to modify code style? Directly edit code-style.md without affecting other rules. During team collaboration, different members can maintain rule files in their areas of expertise without conflicts.

Content Explanation

Simply place them in .claude/rules/, and Claude Code will automatically load them at startup. If you need rules to apply only to specific files, add YAML frontmatter with paths: at the top of the file.

Note: paths supports glob patterns and ! for exclusions. For example:

---
paths:
  - "src/main/java/**/*.java"
  - "!src/main/java/**/legacy/**/*.java"
---

# Java Code Style Standards
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 committing

This means the rules apply to all Java files but exclude those under the legacy package.

Loading Order

Rule files without paths limitations are unconditionally loaded into the system prompt when Claude Code starts.

Any rule files declaring 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 everyone 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), which functions the same as .claude/rules/ but only takes effect locally.

Use the /rules Command to View Currently Loaded Rules

In a Claude Code session, type /rules, and it will list all currently effective rule files along with their path limitations. This is an excellent way to quickly check "which instructions is Claude actually listening to?"

Maintenance Strategy

  • Start Minimal: Write only the tech stack, project-specific tools, and most common pitfalls. Drive by pain points, don't pre-plan for perfection.
  • Regular Audits: Monthly checks for outdated/useless/redundant rules. Compare with drafts generated using /init.
  • Index, Not Encyclopedia: Place references to detailed documentation (such as @docs/api.md); split specific standards into .claude/rules/.
  • Three Tactics to Prevent Bloat:

    • Split into rules/ when exceeding 200 lines
    • Use paths to limit rule application scope
    • Delegate scattered preferences to Auto Memory (/memory)
  • Include Reuse: Use @path/to/file to import external documents, avoiding repetition.
  • Test After Changes: Validate every new rule with a real task to ensure Claude understands it correctly.

Core Philosophy: CLAUDE.md grows organically, it's not written in one go—evolve naturally, prune regularly.