How to Write CLAUDE.md for Claude Code: Turn Project Rules into Instructions It Can Act On

Spell out project commands, code boundaries, and verification standards, check whether CLAUDE.md is loaded, and handle rule conflicts and path scoping.

7 分钟阅读
How to Write CLAUDE.md for Claude Code: Turn Project Rules into Instructions It Can Act On

Claude Code can already edit code, but every time you start a new session, you still have to remind it which package manager to use, how to run tests, and which files it shouldn't edit directly. When that happens, start by collecting the rules you keep re-explaining into a CLAUDE.md.

This file gives Claude persistent project instructions. What makes it effective is that it tells Claude exactly what to do, why, and how to judge the work as done. If you only write "ensure code quality," Claude still doesn't know what quality means in your project.

The examples below use local Claude Code to show where the file goes, how to write it, and how to verify it. The feature descriptions are based on the official documentation as of October 10, 2026. The sample project and commands are for demonstration and need to be adjusted for your repository. I did not run end-to-end tests on Claude Code.Official project memory documentation

First, know where project rules and setup configuration belong

CLAUDE.md is a good place for instructions a project needs long term, such as test entry points, conventions that differ from default habits, and pitfalls people hit repeatedly. API endpoints, keys, and permission settings belong in the settings layer. Don't put real keys in an instruction file shared with the team.

If you haven't connected Claude Code yet, first complete the third-party API setup tutorial. Once the model responds normally, use this article to organize your project rules. Editing CLAUDE.md does not switch your API endpoint or billing channel for you.

One more boundary: Claude treats these instructions as context and can't guarantee it follows each one strictly. If you must forbid a certain kind of action, enforce it with client permission settings or a suitable hook. A single line saying "never do this" isn't enough.Official documentation

Where the file lives determines which projects it affects

Start with one file at the project root, then split it up once that's no longer enough.

LocationGood for
~/.claude/CLAUDE.mdPersonal habits you use across projects
The project root's CLAUDE.md, or .claude/CLAUDE.mdProject rules shared with the team
The project's CLAUDE.local.mdInstructions that apply only to your machine for this project; add it to .gitignore
A subdirectory's CLAUDE.mdInstructions relevant only to that part of the code

At startup, Claude Code loads instruction files from the working directory and its parent directories. Files in subdirectories below the working directory load on demand: their instructions enter the context only when Claude reads or edits files in that directory. Multiple instruction files all go into the context together, so don't read this as "subdirectory rules automatically override parent rules."How files are loaded

For example, say you work in the frontend directory but write the whole team's rules into your personal ~/.claude/CLAUDE.md. Other members won't get those rules through the repository. Conversely, putting your local test URL in a shared file can mislead teammates' environments.

Generate a skeleton first, then turn vague language into concrete actions

In an installed and logged-in Claude Code, start a session from the project root and enter:

markdown
/init

Per the official docs, this command analyzes the codebase and generates a starter CLAUDE.md; if the file already exists, it suggests improvements instead of overwriting it.Initialization docs

After generating it, focus on checking the paths, commands, and conventions in it. A tool being able to read package.json doesn't mean it knows which testing approach your team actually endorses. Add the things you keep correcting, and delete redundant notes it could already infer from the code.

These rewrites are easier to verify:

Original instructionRewritten instruction
Keep code qualityAfter changing business logic, run the relevant tests and type checks; if they fail, report the specific errors and don't present a failure as a success
Follow the project architecturePut new billing logic in src/billing/, have the API layer call existing services, and don't recompute amounts in route handlers
Don't mess with filessrc/generated/ is a generated artifact; edit the corresponding source file and run the generation command
Test thoroughlyWhen fixing a bug, add a test case that reproduces it; run the relevant tests first, and run the full suite when shared logic is involved

The paths in the table are hypothetical examples and shouldn't be treated as your repository's real structure. An effective rule answers three questions: when to act, what exactly to do, and how to check the result.

A CLAUDE.md you can adapt to your repo

Suppose the project uses pnpm, TypeScript, and Vitest. The instructions below can serve as a starting point. First check package.json: if there is no typecheck, test or generate script, replace it with the real command, or delete the rules that don't apply.

markdown
# 项目工作约定

## 工具和验证
- 使用 pnpm。修改依赖时同步 pnpm-lock.yaml。
- pnpm typecheck:类型检查。
- pnpm test --run:完整测试。
- pnpm test --run 路径/用例.test.ts:运行相关测试。
- 修改业务逻辑后先跑相关测试及类型检查。
  涉及共享基础逻辑时,再跑完整测试。
- 命令失败时报告错误和影响,不将“未运行”或“失败”写成通过。

## 代码边界
- src/generated/ 是生成代码,不直接编辑。
  修改源定义后运行 pnpm generate。
- 新功能优先复用现有服务;增加依赖前说明现有实现为何不够。
- 不在接口层重复计费计算;复用 src/billing/ 的公共逻辑。

## 修复和交付
- 修复 bug 时,先用一个测试或可复现步骤说明原问题。
- 保持修改范围与任务一致。发现其他问题,单独列出。
- 完成后说明行为变化、验证结果,以及尚未解决的问题。

This example deliberately doesn't list a full directory tree, and it doesn't repeat "readability, maintainability, extensibility" over and over. Different projects can have different standards, but each line should ideally change Claude's actual decisions.

If an instruction is useful only to one submodule, move it to that directory's instruction file or to a path rule. Multi-step workflows that only run occasionally are better as a Skill, so you don't load a whole procedure in every session.Official writing practices

Once you have more rules, split them by path

Large repositories can use .claude/rules/ to organize rules by topic. For example, API conventions only need to load when you're editing backend TypeScript:

File location:.claude/rules/api.md

markdown
---
paths:
  - "src/api/**/*.ts"
---

# API 约定
- 使用项目现有的错误处理方式,不新增另一套响应格式。
- 新增输入字段时,同时检查校验和对应测试。

A rule with paths loads when Claude's work touches matching files; rules without path restrictions load in every session. For the exact matching syntax, see the official path rules documentation.

Another way to organize is to import instructions with @docs/project-rules.md. It's easier to maintain, but imported files also expand into the context, so splitting into multiple imports won't reduce loading cost. If the goal is to cut irrelevant rules, path scoping or an on-demand Skill is a better fit.File import docs

How to confirm Claude actually loaded and used the rules

After saving the file, restart a session at the project root and enter:

markdown
/context

Check whether Memory files lists the root instructions you expect. That confirms the file was loaded, but it doesn't prove Claude's later actions will follow the rules. Subdirectory instructions load on demand and may not appear in the startup list.

Then watch its behavior on a small task, for example:

markdown
先不要修改代码。检查这个仓库的项目说明和 package.json,
列出当前包管理器、类型检查命令和测试命令,说明各自来自哪里。
若项目说明中的命令不存在,明确指出,不要假设它可运行。

Check that the commands it gives actually exist and match your conventions. Next, pick a small change that's easy to undo and see whether it picks tests according to the rules and reports real results. Replying "I'll follow them" doesn't count as behavioral verification.

/memory lets you view and edit instruction files. When rules don't take effect, check the load location first, then the wording and conflicts. Don't just append "must strictly follow" to the file ten times.Official verification and troubleshooting

Why does Claude still drift even though I wrote rules?

A common problem is that the file is loaded, but its rules are too broad, contradict each other, or no longer apply to the current repository.

If your personal instructions require npm and the project instructions require pnpm, reconcile them first. If you wrote "run all tests after any change," but a full run takes a long time, state which changes only need the related tests and which need full verification. Don't ask for both "always run everything" and "avoid running the full suite," leaving Claude to guess your priority.

The official recommendation is to keep each CLAUDE.md under 200 lines. That number is a maintenance guideline, not a hard limit where line 201 stops loading. When trimming, remove common programming knowledge, duplicate rules, and stale paths first, and keep the conventions that actually affect how work gets done.Writing effective instructions

If the repository already has an AGENTS.md, don't maintain two files with identical content that slowly diverge. The current official docs say some newer versions can read AGENTS.md directly, but when it coexists with CLAUDE.md, there are loading-selection and version limits. If you need to support different tools, you can use the line below in CLAUDE.md to import it, then verify loading:

markdown
@AGENTS.md

The @AGENTS.md line must go in the body of the actual file, not inside a code fence. Per the official docs, import syntax inside code fences isn't expanded.AGENTS.md support and compatibility

Start by writing down the few rules you've already explained over and over, then test them on a small task. When something goes wrong, edit the specific rule responsible and check whether the behavior changes. Once the file reliably saves you a few corrections, consider extending it to more directories.