Skip to content

第二章:CLAUDE.md 与记忆系统 ​

学习目标 ​

  • 理解 CLAUDE.md 为什么是你项目中最重要的文件(对 Claude Code 而言)
  • 写一份生产级 CLAUDE.md,参考 gstack(68k stars)等真实项目的模式
  • 搭建四层配置体系:项目级、本地级、用户级、路径规则
  • 体验跨会话的自动记忆
  • 用路径规则实现精准控制

核心概念 ​

CLAUDE.md 解决什么问题 ​

没有 CLAUDE.md,每次会话都是从零开始。Claude 不知道你的技术栈、命名规范、分支策略,也不知道你们团队会打回任何用 var 代替 const 的 PR。

没有 CLAUDE.md:
  你: "写一个组件"
  Claude: (用了 class 组件 -- 你的项目全是 hooks)
  你: "不对,用 hooks"
  Claude: (用了 CSS modules -- 你用 Tailwind)
  你: "不对,Tailwind"
  你: (第三次终于对了,但浪费了 10 分钟)

有了 CLAUDE.md:
  CLAUDE.md 写着: "React 函数组件 + hooks。Tailwind CSS。禁止 class 组件。"
  你: "写一个组件"
  Claude: (hooks + Tailwind,一次到位)

一天下来,这个差距是巨大的。

四层配置体系 ​

Claude Code 从四个地方读取配置,按以下优先级排列:

最高优先级
  |
  1. CLAUDE.md          (项目根目录)    -- 团队规范,提交到 git
  2. CLAUDE.local.md    (项目根目录)    -- 你的本地覆盖,gitignore 掉
  3. ~/.claude/CLAUDE.md (home 目录)    -- 你在所有项目通用的个人默认设置
  4. .claude/rules/*.md  (项目)         -- 按路径按需加载的规则
  |
最低优先级
文件范围提交到 Git?示例
CLAUDE.md团队是"用 pnpm。Conventional Commits。禁止 default export。"
CLAUDE.local.md你个人否"我本地 API 在 3001 端口。用中文回复。"
~/.claude/CLAUDE.md你个人,全局否"我喜欢函数式风格。解释简短一点。"
.claude/rules/*.md团队,按路径是"API 文件必须包含限流。"

CLAUDE.md 作为项目级宪法

这种分层系统和 Anthropic 的宪法 AI(Constitutional AI)研究异曲同工。在 CAI 中,模型通过一组原则("宪法")来引导其行为。CLAUDE.md 将这个概念扩展到项目层面:你在编写一部局部宪法,用来塑造 Claude 在你特定代码库和团队规范中的行为方式。层级关系的工作方式完全一样 -- 项目级规则覆盖个人默认值,就像宪法原则覆盖个人偏好一样。详见 附录 A08:宪法 AI 与 CLAUDE.md。

什么样的 CLAUDE.md 是好的 ​

根据生产环境中的实际效果(不是理论):

  1. 具体且可执行 -- "用 pnpm" 而不是 "用合适的包管理器"
  2. 200 行以内 -- 太长会降低遵从率
  3. 用标题组织结构 -- Claude 会解析 markdown 结构,利用好它
  4. 加一条人格/语气规则 -- 这是秘密武器

gstack 项目(68k stars)有一个 24KB 的 CLAUDE.md。最有效的部分之一?语气规则:

"不要用破折号。不要用 AI 味的词汇如'深入探讨'或'充分利用'。就像在 Slack 里快速打字的感觉,不是在写论文。"

这一条规则就能让 Claude 的输出变得非常自然。我们的 CLAUDE.md 里也会加类似的。

记忆系统的工作机制 ​

Claude Code 有一套记忆系统,能在会话之间持久化信息。理解记忆存在哪里、如何被加载,有助于你调试问题和管理配置栈。

记忆存储位置:

记忆类型位置范围
用户记忆~/.claude/memory/适用于你所有的项目
项目记忆~/.claude/projects/<project-hash>/memory/特定于某一个项目目录

什么会触发记忆创建:

  • 明确请求:你说"记住我们用 pnpm"或"把这个保存为偏好"
  • 自动检测纠正:当你纠正 Claude("不对,始终用具名导出"),它会识别出这是一个持久偏好并自动保存
  • 模式识别:对同一话题的重复纠正会加速自动保存

记忆文件格式:

每条记忆以带 YAML 前置元数据的 markdown 文件存储:

yaml
---
type: preference
name: jsdoc-requirement
description: Always add JSDoc with @param and @returns tags
created: 2026-05-15T10:30:00Z
---

The team requires JSDoc comments with @param and @returns tags on all
exported functions. This was corrected during a session working on
src/utils/validators.ts.

会话启动时记忆的加载流程:

会话启动
  |
  1. 加载 ~/.claude/CLAUDE.md(用户级规则)
  2. 加载 CLAUDE.md(项目级规则)
  3. 加载 CLAUDE.local.md(本地覆盖)
  4. 加载 ~/.claude/memory/ 下所有记忆文件(用户记忆)
  5. 加载 ~/.claude/projects/<hash>/memory/ 下所有记忆文件(项目记忆)
  |
  所有这些在你发出第一条消息之前就注入到了 Claude 的系统上下文中

记忆的优先级和限制:

  • 记忆是叠加的 -- 不会互相覆盖,而是累积
  • 有一个实际限制:记忆太多会消耗上下文 token,留给实际对话的空间就少了
  • 过时或矛盾的记忆应该手动清理(详见下方"常见问题排查")
  • 同一话题上存在冲突时,项目记忆优先于用户记忆

关于上下文如何组装和排优先级的深入讲解,详见 附录 A02:上下文工程。


Demo 3:写一份生产级 CLAUDE.md ​

3
Write a Production-Grade CLAUDE.md
Beginner~10 min

目标 ​

创建一份在真实生产项目中不会违和的 CLAUDE.md。我们会参考 gstack、Everything Claude Code(ECC)和 GSD 使用的模式。

步骤 ​

1. 创建项目 ​

bash
mkdir -p ~/claude-demos/demo-03 && cd ~/claude-demos/demo-03
git init && npm init -y
mkdir -p src/{api,services,models} tests

2. 先试试 /init ​

bash
claude
/init

你应该看到类似这样的输出:

terminal
$ claude
╭──────────────────────────────────────╮
│ Claude Code v1.0.23                  │
│ /help for commands                   │
╰──────────────────────────────────────╯

 > /init

  I'll scan your project and create a CLAUDE.md file.

  Scanning project structure...
  Found: package.json, src/, tests/
  Detected: Node.js project with TypeScript

  Created CLAUDE.md with:
  - Project overview (auto-detected)
  - Directory structure
  - Available scripts from package.json

  ✓ CLAUDE.md created (42 lines)

看看它生成了什么:

bash
cat CLAUDE.md

/init 通过扫描项目给你一个起点。但它总是很泛泛的。我们来替换成一份真正有用的。

3. 写一份真正的 CLAUDE.md ​

退出会话(Ctrl+C),创建一份正经的:

bash
cat > CLAUDE.md << 'CLAUDE_EOF'
# TaskFlow API

## Key Commands
- Install: `pnpm install`
- Dev server: `pnpm dev`
- Test: `pnpm test`
- Lint: `pnpm lint`
- Type check: `pnpm tsc --noEmit`
- Single test: `pnpm test -- --grep "test name"`

## Architecture
- `src/api/` -- REST routes and controllers (Express + Zod validation)
- `src/services/` -- Business logic, no framework dependencies
- `src/models/` -- Prisma models and database access
- `src/middleware/` -- Auth, rate limiting, error handling
- `tests/` -- Mirrors src/ structure, co-located test utils

## Tech Stack
- Runtime: Node.js 22 LTS
- Language: TypeScript 5.x (strict mode, no `any`)
- Package manager: pnpm (do NOT use npm or yarn)
- Framework: Express 5
- ORM: Prisma
- Validation: Zod
- Testing: Vitest
- Linting: Biome

## Branching & Commits
- Never push directly to `main` or `develop`
- Feature branches: `feature/<ticket-id>-<short-desc>`
- Bugfix branches: `fix/<ticket-id>-<short-desc>`
- Commits: Conventional Commits (`feat:`, `fix:`, `refactor:`, `test:`, `docs:`)
- One logical change per commit. If you need "and" in the commit message, split it.

## Code Standards
- ES modules only (import/export). Never CommonJS (require).
- `const` and `let` only. Never `var`.
- Single quotes for strings.
- 2-space indent.
- Arrow functions unless you need `this` binding.
- Every exported function needs a JSDoc comment.
- No default exports. Named exports only.
- Error messages in English (even if replies are in another language).

## API Endpoint Rules
- Every endpoint: Zod input validation + try/catch + structured error response
- Response format: `{ success: boolean, data?: T, error?: { code: string, message: string } }`
- All mutations need auth middleware
- Rate limiting on all public endpoints

## Testing Requirements
- Every service function needs unit tests
- Every API endpoint needs integration tests
- Use describe/it blocks. One assertion per `it` where practical.
- AAA pattern: Arrange, Act, Assert
- Mock external services, never mock internal modules

## Voice & Style
- Be direct. No filler phrases like "Great question!" or "I'd be happy to help!"
- No em dashes. Use -- or just break the sentence.
- No AI vocabulary: avoid "leverage", "utilize", "delve", "comprehensive", "robust"
- Sound like a senior engineer writing in Slack, not a generated document.
- When you finish a task, just say "Done." Don't write a paragraph about it.
CLAUDE_EOF

注意顶部的 Key Commands 部分。这是受 Everything Claude Code(ECC,148k stars)启发的模式,把可执行命令放在最显眼的位置,让 Claude 准确知道如何构建、测试和 lint 你的项目。

底部的 Voice & Style 部分受 gstack 的做法启发。这不只是美观问题。当 Claude 去掉 AI 腔调时,输出真的更有用,因为它匹配了你团队实际的沟通风格。

4. 验证 Claude 遵守规则 ​

启动新会话:

bash
claude
Create a user registration endpoint at src/api/register.ts with a corresponding service at src/services/auth-service.ts

你应该看到 Claude 请求创建文件的权限:

terminal
 > Create a user registration endpoint at src/api/register.ts with a
   corresponding service at src/services/auth-service.ts

  I'll create both files following the project conventions from CLAUDE.md.

  ╭─ Write src/services/auth-service.ts ─────────────────────────────╮
  │ (47 lines)                                                       │
  ╰──────────────────────────────────────────────────────────────────╯

  Allow? (y/n/a):

逐项检查:

  • [ ] 用了 TypeScript 严格类型(没有 any)?
  • [ ] import/export 而不是 require?
  • [ ] const/let,没有 var?
  • [ ] 单引号?
  • [ ] 端点有 Zod 校验?
  • [ ] 结构化错误响应格式?
  • [ ] 导出函数有 JSDoc?
  • [ ] 具名导出,没有 default export?

5. 测试冲突 ​

在同一会话中:

Rewrite the imports to use require() instead of import

Claude 应该反对。它知道 CLAUDE.md 规定了 ES modules。如果它直接照做而不提醒冲突,你的 CLAUDE.md 可能没正确加载 -- 用 /context 检查。

terminal
 > Rewrite the imports to use require() instead of import

  I need to flag a conflict with the project conventions. The CLAUDE.md
  specifies "ES modules only (import/export). Never CommonJS (require)."

  If you want me to proceed anyway, I can, but this would violate the
  team's coding standards. Would you like me to:

  1. Keep the ES module imports (recommended)
  2. Switch to require() despite the convention

刚才发生了什么? ​

以下是 Claude 在这个 Demo 中使用的工具调用序列,以及它为什么选择每个工具:

1
Read
CLAUDE.md
↓
2
Read
package.json
↓
3
Write
src/services/auth-service.ts
↓
4
Write
src/api/register.ts

关键要点:

  • CLAUDE.md 是自动读取的 -- 你不需要告诉 Claude 去看它
  • Claude 先创建 service 再创建 route,因为存在依赖顺序
  • CLAUDE.md 中的每条代码标准都被应用了:具名导出、JSDoc、Zod、错误格式
  • 被要求违反规则时,Claude 指出了冲突而不是默默服从

原理 ​

CLAUDE.md 在每一轮对话开始时加载到 Claude 的上下文中,作为持久化指令。当你的请求和规则冲突时,Claude 通常会指出冲突而不是默默服从。这是设计意图 -- 就像宪法原则一样,CLAUDE.md 中的规则在比单个提示更深的层面上塑造行为。


Demo 4:自动记忆实战 ​

4
Auto-Memory in Action
Beginner~10 min

目标 ​

体验 Claude 如何自动记住你的纠正,跨会话生效。场景:你正在入职新团队的代码库,逐步建立你的偏好。

步骤 ​

1. 第一个会话:建立模式 ​

bash
cd ~/claude-demos/demo-03
claude

自然地在工作中提出纠正:

Create a utility module at src/utils/validators.ts with email and phone validation functions

等 Claude 创建完后,纠正它的做法:

Always add JSDoc comments with @param and @returns tags. This is a team requirement.

你应该看到 Claude 确认并保存:

terminal
 > Always add JSDoc comments with @param and @returns tags. This is a
   team requirement.

  Got it. I'll remember that all exported functions need JSDoc comments
  with @param and @returns tags. I've saved this as a project preference.

  Let me update the validators.ts file to add the missing JSDoc:

  ╭─ Edit src/utils/validators.ts ───────────────────────────────────╮
  │ + /** Validate an email address format.                          │
  │ +  * @param email - The email string to validate                 │
  │ +  * @returns Object with valid boolean and optional error        │
  │ +  */                                                            │
  │   export const validateEmail = ...                               │
  ╰──────────────────────────────────────────────────────────────────╯

再来一个纠正:

For validation functions, always return { valid: boolean, error?: string } instead of throwing. We don't use exceptions for validation.

退出(Ctrl+C)。

2. 检查 Claude 记住了什么 ​

bash
# 查看记忆目录
ls ~/.claude/projects/*/memory/ 2>/dev/null || echo "Memory directory may be in a different location"

# 查看记忆索引
cat ~/.claude/projects/*/memory/MEMORY.md 2>/dev/null

你应该看到类似这样的内容:

terminal
$ ls ~/.claude/projects/*/memory/
feedback_jsdoc.md  feedback_validation.md

$ cat ~/.claude/projects/a3f2b1c/memory/feedback_jsdoc.md
---
type: preference
name: jsdoc-requirement
description: Always add JSDoc with @param and @returns tags
created: 2026-05-27T14:22:00Z
---

All exported functions need JSDoc comments with @param and @returns tags.
This is a team requirement. Corrected during work on src/utils/validators.ts.

你应该能看到 Claude 把你的纠正保存成了记忆文件。

3. 第二个会话:验证记忆生效 ​

bash
cd ~/claude-demos/demo-03
claude
Create another utility at src/utils/sanitizers.ts with functions to sanitize user input (strip HTML, normalize whitespace, trim)

验证 Claude 自动做了:

  • 加了 JSDoc,包含 @param 和 @returns(记住了)
  • 返回 { valid: boolean, error?: string } 风格的对象(记住了)
  • 验证逻辑没有抛异常(记住了)

刚才发生了什么? ​

1
Read
CLAUDE.md
↓
2
Read
memory/feedback_jsdoc.md
↓
3
Read
memory/feedback_validation.md
↓
4
Write
src/utils/sanitizers.ts

关键要点:

  • 记忆文件在会话启动时静默加载 -- 不需要你提示
  • 会话 1 中的纠正在会话 2 中自动应用
  • CLAUDE.md 规则 + 记忆文件的组合让 Claude 对你团队的期望有了完整的认知
  • 这就是 Claude 如何在一个项目中随着时间推移变得更好,而不需要你重复自己

自动记忆的工作原理 ​

会话 1:
  你纠正 Claude:"都要加 JSDoc"
  Claude: 保存到 ~/.claude/projects/<hash>/memory/feedback_jsdoc.md

  你纠正 Claude:"返回对象,不要抛异常"
  Claude: 保存到 ~/.claude/projects/<hash>/memory/feedback_validation.md

会话 2:
  Claude 启动时加载所有记忆文件
  Claude 自动应用之前的纠正

关键特性:

  • 自动触发 -- Claude 检测到纠正就自己保存,不需要你手动操作
  • 持久化 -- 存在磁盘上,重启后依然有效
  • 项目隔离 -- 不同项目有不同的记忆
  • 可管理 -- 你可以直接编辑或删除记忆文件,或在会话中用 /memory

Demo 5:路径规则 ​

5
Path-Specific Rules
Beginner~15 min

目标 ​

设置 .claude/rules/,让 API 文件、前端组件和数据库迁移各自拥有独立的规范。规则只在 Claude 操作匹配文件时加载,节省上下文空间。

步骤 ​

1. 搭建项目结构 ​

bash
mkdir -p ~/claude-demos/demo-05/{src/api,src/components,src/db/migrations,tests}
cd ~/claude-demos/demo-05
git init

2. 创建路径规则 ​

bash
mkdir -p .claude/rules

# API 端点规则
cat > .claude/rules/api-endpoints.md << 'EOF'
---
paths:
  - "src/api/**/*.ts"
---

## API Endpoint Standards
- Every endpoint must include rate limiting middleware
- Input validation with Zod schemas (define schema in the same file)
- Wrap handler body in try/catch, return structured errors
- Response format: { success: boolean, data?: T, error?: { code: string, message: string } }
- Add request/response logging via middleware
- Include OpenAPI JSDoc annotations (@summary, @param, @returns)
EOF

# 数据库迁移规则
cat > .claude/rules/db-migrations.md << 'EOF'
---
paths:
  - "src/db/migrations/**/*.ts"
---

## Migration Standards
- Every migration MUST have a rollback plan (down function)
- Include a comment block at the top explaining what changes and why
- Never drop a column directly -- deprecate first, remove in a future migration
- Test both up() and down() before committing
- Migration filenames: YYYYMMDD_HHMMSS_description.ts
EOF

# 组件规则
cat > .claude/rules/components.md << 'EOF'
---
paths:
  - "src/components/**/*.tsx"
---

## Component Standards
- Function components only, no class components
- Props interface defined and exported (named `<Component>Props`)
- Include displayName for debugging
- Tailwind CSS for styling, no CSS modules or styled-components
- Co-locate component tests in __tests__/ subdirectory
EOF

3. 添加全局 CLAUDE.md ​

bash
cat > CLAUDE.md << 'EOF'
# Project Config

## Tech Stack
- TypeScript + Node.js
- Testing: Vitest

## General Rules
- Named exports only
- File names in kebab-case
- No AI vocabulary in comments or docs
EOF

4. 验证规则按路径激活 ​

bash
claude

测试 API 规则:

Create a user lookup endpoint at src/api/get-user.ts

验证 -- 应该包含:限流、Zod schema、try/catch、结构化响应、日志

terminal
 > Create a user lookup endpoint at src/api/get-user.ts

  I'll create this following the API endpoint standards.

  ╭─ Write src/api/get-user.ts ──────────────────────────────────────╮
  │ import { z } from 'zod';                                         │
  │ import { rateLimit } from '../middleware/rate-limit';             │
  │ import { logger } from '../middleware/logger';                    │
  │                                                                  │
  │ /** @summary Look up a user by ID */                             │
  │ const GetUserSchema = z.object({                                 │
  │   id: z.string().uuid()                                          │
  │ });                                                              │
  │ ...                                                              │
  ╰──────────────────────────────────────────────────────────────────╯

  Allow? (y/n/a):

测试迁移规则:

Create a migration at src/db/migrations/20260410_120000_add_user_roles.ts that adds a roles column to the users table

验证 -- 应该包含:回滚函数(down)、注释块、没有直接删列

测试没有特定规则的路径:

Create a helper at src/utils/hash.ts

验证 -- 只有全局 CLAUDE.md 的规则生效(具名导出、kebab-case)

刚才发生了什么? ​

1
Read
CLAUDE.md
↓
2
Read
.claude/rules/api-endpoints.md
↓
3
Write
src/api/get-user.ts
↓
4
Read
.claude/rules/db-migrations.md
↓
5
Write
src/db/migrations/20260410_120000_add_user_roles.ts
↓
6
Write
src/utils/hash.ts

关键要点:

  • 路径规则根据 glob 模式按需加载 -- 不是一次全部加载
  • 每个文件只获得与其位置相关的规则,节省上下文 token
  • 全局 CLAUDE.md 规则仍然适用于所有地方,叠加在路径规则之下
  • 不匹配任何路径 glob 的文件只看到全局规则

路径规则的工作原理 ​

.claude/rules/api-endpoints.md
  paths: ["src/api/**/*.ts"]
    |
    只在 Claude 操作匹配这个 glob 的文件时加载
    |
    src/api/ 之外的文件看不到这些规则
    = 不浪费上下文 token

这对大型项目非常强大。API 团队的规范不会渗透到前端,反之亦然。


常见问题排查 ​

即使配置良好的 CLAUDE.md 也可能产生意外行为。以下是最常见的问题和解决方法。

CLAUDE.md 太大 ​

症状: Claude 忽略 CLAUDE.md 靠后的规则。底部的指令比顶部的遵循率明显低。

原因: CLAUDE.md 被注入到系统上下文中。超过大约 200 行后,由于注意力机制在大上下文中的工作方式,后面的规则获得的关注会减少。这不是硬性截断,但遵从率会逐步下降。

解决:

  • 保持 CLAUDE.md 在 200 行以内
  • 将详细参考资料移到单独文件中,用 @import 引入
  • 将路径相关规则移到 .claude/rules/ 中按需加载
  • 最关键的规则(key commands、底线标准)放在最前面
bash
# 检查你的 CLAUDE.md 行数
wc -l CLAUDE.md
# 目标:200 行以内

不同层级之间的规则冲突 ​

症状: Claude 表现不一致 -- 有时用一种风格,有时用另一种。或者 Claude 提到不确定该遵循哪种规范。

原因: 你在不同层级有矛盾的规则。比如 ~/.claude/CLAUDE.md 说"用 4 空格缩进",但项目 CLAUDE.md 说"2 空格缩进"。

解决:

  • 在会话中用 /context 检查所有层级,看看加载了什么
  • 项目 CLAUDE.md 覆盖用户级 ~/.claude/CLAUDE.md
  • CLAUDE.local.md 覆盖项目 CLAUDE.md
  • 直接消除矛盾,而不是依赖优先级系统 -- 明确的比隐式的好

CLAUDE.md 没被读取 ​

症状: Claude 完全忽略你的规则。/context 中看不到你的 CLAUDE.md 内容。

常见原因:

  • 文件名错误:必须是 CLAUDE.md(全大写,无空格)
  • 位置错误:必须在项目根目录(你启动 claude 的那个目录)
  • 文件编码问题:用 UTF-8,无 BOM
  • 你从子目录而不是项目根目录运行了 claude

解决:

bash
# 确认文件存在于你期望的位置
ls -la CLAUDE.md

# 确认你在正确的目录
pwd

# 在会话中检查
# /context

记忆文件过期或矛盾 ​

症状: Claude 应用了过时的偏好。或者 Claude 看起来很困惑,因为两个记忆文件给出了矛盾的指导(比如一个说"用 Tailwind",另一个说"用 CSS modules",因为你改主意了)。

解决:

bash
# 列出当前项目的所有记忆文件
ls ~/.claude/projects/*/memory/

# 查看特定记忆是否还有效
cat ~/.claude/projects/*/memory/feedback_*.md

# 删除过时的记忆
rm ~/.claude/projects/<hash>/memory/feedback_old_preference.md

# 或者在会话中交互式管理
# /memory

最佳实践:每隔几周审查一次记忆文件,尤其在项目发生重大变更(新框架、新团队规范等)之后。


深入探索 ​

@import 引入外部文档 ​

CLAUDE.md 支持引入外部文件:

markdown
# CLAUDE.md

## Project Basics
...

@import docs/api-design-guide.md
@import docs/database-conventions.md

这让你的 CLAUDE.md 保持精简,同时在需要时让 Claude 访问详细的参考文档。

调试:Claude 读到了我的 CLAUDE.md 吗? ​

bash
# 在会话中:
/context

这显示当前上下文中的所有内容,包括 CLAUDE.md 和已加载的规则。如果规则没显示出来,检查文件路径和 glob 模式。

记忆管理 ​

bash
# 列出当前项目的所有记忆
ls ~/.claude/projects/*/memory/

# 删除特定记忆
rm ~/.claude/projects/<hash>/memory/feedback_jsdoc.md

# 在会话中:
/memory    # 交互式记忆管理

生产环境 CLAUDE.md 的常见模式 ​

生态中最好的 CLAUDE.md 文件都有这些共同模式:

模式示例为什么有效
Key Commands 放在顶部Test: pnpm testClaude 不用猜就知道怎么运行
语气/人格规则"不要用破折号,不要废话"输出匹配团队沟通风格
否定规则"永远不要用 default export"防止特定的已知坏模式
架构地图"src/api/ -- 路由, src/services/ -- 逻辑"Claude 能准确导航代码库
提交规范"Conventional Commits, 每次提交一个逻辑变更"Git 历史保持整洁

练习:搭建你自己的配置栈 ​

任务 ​

为一个 Web 项目搭建完整的四层配置:

  1. 用户级 ~/.claude/CLAUDE.md -- 你的个人默认值:

    • 偏好的回复语言
    • 代码风格偏好(函数式 vs OOP 等)
    • 一条语气规则("解释简短一点"之类的)
  2. 项目级 CLAUDE.md -- 团队规范:

    • 技术栈(选你喜欢的)
    • 编码规范(命名、导入、错误处理)
    • Key Commands(构建、测试、lint)
  3. 本地级 CLAUDE.local.md -- 你的机器:

    • 本地 API URL
    • 个人开发偏好
    • 加到 .gitignore
  4. 路径规则 .claude/rules/ -- 至少 2 个路径规则文件

然后启动 Claude 会话,让它在不同路径下创建文件,验证正确的规则应用到了正确的位置。

成功标准 ​

  • [ ] ~/.claude/CLAUDE.md 存在且包含个人默认值
  • [ ] 项目 CLAUDE.md 包含适合团队的规范
  • [ ] CLAUDE.local.md 存在且已 gitignore
  • [ ] .claude/rules/ 中至少有 2 个规则文件,使用不同的路径 glob
  • [ ] Claude 的输出明显遵循了每个路径对应的规则
提示

在不同层级设置略有不同的规则(比如不同的注释风格),这样你能看出哪个层级在生效。有问题就用 /context 检查。


知识检测 ​

在四层配置体系中,哪个文件的优先级最高?
~/.claude/CLAUDE.md(用户级)
CLAUDE.md(项目根目录)
CLAUDE.local.md(本地覆盖)
.claude/rules/*.md(路径规则)
你在会话 1 中纠正了 Claude 的代码风格。在会话 2 中,Claude 自动应用了这个纠正。纠正被存储在哪里?
在 CLAUDE.md 文件中,追加到底部
在 Anthropic API 服务器上,关联到你的账号
在 ~/.claude/projects/memory/ 下的记忆文件中
在对话历史文件中
你的 CLAUDE.md 写着'只用具名导出',但 src/db/migrations/ 的路径规则没有提到导出风格。当 Claude 创建迁移文件时会怎样?
路径规则覆盖一切 -- Claude 忽略 CLAUDE.md
Claude 同时应用两者:CLAUDE.md 规则加上迁移特定规则
Claude 只应用 CLAUDE.md 规则,因为它优先级更高
Claude 会询问该遵循哪套规则
你的 CLAUDE.md 有 350 行,Claude 总是忽略底部的测试规则。最可能的解决方法是什么?
把测试规则移到 CLAUDE.md 顶部
重复测试规则三次以强调
将 CLAUDE.md 精简到 200 行以内,详细规则移到 .claude/rules/ 或 @import 文件中
创建一个只包含测试规则的 CLAUDE.local.md

本章小结 ​

  • CLAUDE.md 是你能做的最有影响力的配置。它把 Claude 从通用助手变成了解项目规范的团队协作者。
  • 四个层级:项目 CLAUDE.md(团队)> CLAUDE.local.md(你)> ~/.claude/CLAUDE.md(你,全局)> .claude/rules/(按路径)
  • 语气规则真的有效。 "不要用破折号、不要用 AI 词汇"能让 Claude 的输出质量跳一个台阶。
  • 自动记忆会捕获你的纠正,自动在未来的会话中应用。记忆以带 YAML 前置元数据的 markdown 文件存储在本地。
  • 路径规则让你实现精准控制,不膨胀上下文。规则根据 glob 模式按需加载。
  • 好的 CLAUDE.md:200 行以内,具体,可执行,结构化,顶部放 Key Commands。
  • CLAUDE.md 是项目级宪法 -- 它塑造 Claude 行为的方式,和 Anthropic 的宪法 AI 原则塑造基础模型的方式一样。详见 附录 A08:宪法 AI 与 CLAUDE.md。
  • 上下文工程很重要 -- 你如何组织 CLAUDE.md、记忆和路径规则,决定了 Claude 输出的质量。详见 附录 A02:上下文工程。

下一章:第三章:上下文窗口管理。这是大多数人撞墙的地方。Claude 开始时很强,但随着对话变长会越来越差。第三章解释原因,并告诉你怎么解决。GSD 把这个叫做"上下文腐烂(Context Rot)",它是真实存在的。

基于 MIT 许可发布