writing-claude-md-files
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseWriting CLAUDE.md Files
编写CLAUDE.md文件
REQUIRED BACKGROUND: Read ed3d-extending-claude:writing-claude-directives for foundational guidance on token efficiency, compliance techniques, and directive structure.
必备背景知识: 阅读ed3d-extending-claude:writing-claude-directives,获取关于令牌效率、合规技巧和指令结构的基础指导。
Core Principle
核心原则
CLAUDE.md files bridge Claude's statelessness. They preserve context so humans don't re-explain architectural intent every session.
Key distinction:
- Top-level: HOW to work in this codebase (commands, conventions)
- Subdirectory: WHY this piece exists and what it PROMISES (contracts, intent)
CLAUDE.md文件弥补了Claude的无状态特性。它们保留上下文,让人类无需在每次会话中重复解释架构意图。
关键区别:
- 顶层:如何在这个代码库中工作(命令、约定)
- 子目录:这部分代码存在的原因及其承诺(契约、意图)
File Hierarchy
文件层级
Claude automatically reads CLAUDE.md files from current directory up to root:
project/
├── CLAUDE.md # Project-wide: tech stack, commands, conventions
└── src/
└── domains/
├── auth/
│ ├── CLAUDE.md # Auth domain: purpose, contracts, invariants
│ └── oauth2/
│ └── CLAUDE.md # OAuth2 subdomain (rare, only when needed)
└── billing/
└── CLAUDE.md # Billing domain: purpose, contracts, invariantsDepth guideline: Typically one level (domain). Occasionally two (subdomain like ). Rarely more.
auth/oauth2Claude会自动从当前目录向上读取到根目录的CLAUDE.md文件:
project/
├── CLAUDE.md # 项目全局:技术栈、命令、约定
└── src/
└── domains/
├── auth/
│ ├── CLAUDE.md # 认证域:用途、契约、不变量
│ └── oauth2/
│ └── CLAUDE.md # OAuth2子域(少见,仅在需要时使用)
└── billing/
└── CLAUDE.md # 计费域:用途、契约、不变量深度指南: 通常为一级(域)。偶尔为两级(如这样的子域)。很少超过两级。
auth/oauth2Top-Level CLAUDE.md
顶层CLAUDE.md
Focuses on project-wide WHAT and HOW.
聚焦于项目全局的内容与操作方式。
What to Include
应包含内容
| Section | Purpose |
|---|---|
| Tech Stack | Framework, language, key dependencies |
| Commands | Build, test, run commands |
| Project Structure | Directory overview with purposes |
| Conventions | Naming, patterns used project-wide |
| Boundaries | What Claude can/cannot edit |
| 章节 | 用途 |
|---|---|
| 技术栈 | 框架、语言、关键依赖 |
| 命令 | 构建、测试、运行命令 |
| 项目结构 | 带用途说明的目录概览 |
| 约定 | 项目全局使用的命名、模式 |
| 边界 | Claude可编辑/不可编辑的内容 |
Template
模板
markdown
undefinedmarkdown
undefined[Project Name]
[项目名称]
Last verified: [DATE - use ]
date +%Y-%m-%dLast verified: [日期 - 使用 ]
date +%Y-%m-%dTech Stack
技术栈
- Language: TypeScript 5.x
- Framework: Next.js 14
- Database: PostgreSQL
- Testing: Vitest
- Language: TypeScript 5.x
- Framework: Next.js 14
- Database: PostgreSQL
- Testing: Vitest
Commands
命令
- - Start dev server
npm run dev - - Run tests
npm run test - - Production build
npm run build
- - 启动开发服务器
npm run dev - - 运行测试
npm run test - - 生产环境构建
npm run build
Project Structure
项目结构
- - Domain modules (auth, billing, etc.)
src/domains/ - - Cross-cutting utilities
src/shared/ - - External adapters (DB, APIs)
src/infrastructure/
- - 域模块(认证、计费等)
src/domains/ - - 跨领域工具
src/shared/ - - 外部适配器(数据库、API)
src/infrastructure/
Conventions
约定
- Functional Core / Imperative Shell pattern
- Domain modules are self-contained
- See domain CLAUDE.md files for domain-specific guidance
- 功能核心/命令式外壳模式
- 域模块是自包含的
- 查看域级CLAUDE.md文件获取域特定指导
Boundaries
边界
- Safe to edit:
src/ - Never touch: (immutable),
migrations/files*.lock
undefined- 可安全编辑:
src/ - 禁止修改:(不可变)、
migrations/文件*.lock
undefinedWhat NOT to Include
不应包含内容
- Code style rules (use linters)
- Exhaustive command lists (reference package.json)
- Content that belongs in domain-level files
- Sensitive information (keys, credentials)
- 代码风格规则(使用代码检查工具)
- 详尽的命令列表(参考package.json)
- 属于域级文件的内容
- 敏感信息(密钥、凭证)
Subdirectory CLAUDE.md (Domain-Level)
子目录CLAUDE.md(域级)
Focuses on WHY and CONTRACTS. The code shows WHAT; these files explain intent.
聚焦于存在原因与契约。代码展示了做什么;这些文件解释意图。
What to Include
应包含内容
| Section | Purpose |
|---|---|
| Purpose | WHY this domain exists (not what it does) |
| Contracts | What this domain PROMISES to others |
| Dependencies | What it uses, what uses it, boundaries |
| Key Decisions | ADR-lite: decisions and rationale |
| Invariants | Things that must ALWAYS be true |
| Gotchas | Non-obvious traps |
| 章节 | 用途 |
|---|---|
| 用途 | 这个域存在的原因(不是它做什么) |
| 契约 | 这个域对其他部分的承诺 |
| 依赖 | 它使用的内容、使用它的内容、边界 |
| 关键决策 | 轻量级ADR:决策及其理由 |
| 不变量 | 必须始终成立的规则 |
| 注意事项 | 不明显的陷阱 |
Template
模板
markdown
undefinedmarkdown
undefined[Domain Name]
[域名称]
Last verified: [DATE - use ]
date +%Y-%m-%dLast verified: [日期 - 使用 ]
date +%Y-%m-%dPurpose
用途
[1-2 sentences: WHY this domain exists, what problem it solves]
[1-2句话:这个域存在的原因,解决的问题]
Contracts
契约
- Exposes: [public interfaces - what callers can use]
- Guarantees: [promises this domain keeps]
- Expects: [what callers must provide]
- Exposes: [公共接口 - 调用方可以使用的内容]
- Guarantees: [这个域做出的承诺]
- Expects: [调用方必须提供的内容]
Dependencies
依赖
- Uses: [domains/services this depends on]
- Used by: [what depends on this domain]
- Boundary: [what should NOT be imported here]
- Uses: [此域依赖的域/服务]
- Used by: [依赖此域的内容]
- Boundary: [不应从此处导入的内容]
Key Decisions
关键决策
Invariants
不变量
- [Thing that must always be true]
- [必须始终成立的规则]
Key Files
关键文件
- - Public exports
index.ts - - Domain types
types.ts - - Main service implementation
service.ts
- - 公共导出
index.ts - - 域类型
types.ts - - 主要服务实现
service.ts
Gotchas
注意事项
- [Non-obvious thing that will bite you]
undefined- [不明显的易踩坑点]
undefinedExample: Auth Domain
示例:认证域
markdown
undefinedmarkdown
undefinedAuth Domain
Auth Domain
Last verified: 2025-12-17
Last verified: 2025-12-17
Purpose
用途
Ensures user identity is verified exactly once at the system edge.
All downstream services trust the auth token without re-validating.
确保用户身份在系统边缘仅验证一次。所有下游服务信任认证令牌,无需重新验证。
Contracts
契约
- Exposes: ,
validateToken(token) → User | nullcreateSession(credentials) → Token - Guarantees: Tokens expire after 24h. User objects always include roles.
- Expects: Valid JWT format. Database connection available.
- Exposes: ,
validateToken(token) → User | nullcreateSession(credentials) → Token - Guarantees: 令牌24小时后过期。用户对象始终包含角色信息。
- Expects: 有效的JWT格式。数据库连接可用。
Dependencies
依赖
- Uses: Database (users table), Redis (session cache)
- Used by: All API routes, billing domain (user identity only)
- Boundary: Do NOT import from billing, notifications, or other domains
- Uses: Database(用户表)、Redis(会话缓存)
- Used by: 所有API路由、计费域(仅用户身份)
- Boundary: 请勿从计费、通知或其他域导入内容
Key Decisions
关键决策
- JWT over session cookies: Stateless auth for horizontal scaling
- bcrypt cost 12: Legacy decision, migration to argon2 tracked in ADR-007
- JWT替代会话Cookie:无状态认证支持水平扩展
- bcrypt成本12:遗留决策,迁移到argon2的进度在ADR-007中追踪
Invariants
不变量
- Every user has exactly one primary email
- Deleted users are soft-deleted (is_deleted), never hard deleted
- User IDs are UUIDs, never sequential
- 每个用户恰好有一个主邮箱
- 删除的用户是软删除(is_deleted),绝不硬删除
- 用户ID是UUID,绝不使用自增ID
Key Files
关键文件
- - AuthService implementation
service.ts - - JWT creation/validation
tokens.ts - - User, Token, Session types
types.ts
- - AuthService实现
service.ts - - JWT创建/验证
tokens.ts - - User、Token、Session类型
types.ts
Gotchas
注意事项
- Token validation returns null on invalid (doesn't throw)
- Never return raw password hashes in User objects
undefined- 令牌验证失败时返回null(不抛出异常)
- 绝不要在User对象中返回原始密码哈希
undefinedFreshness Dates: MANDATORY
更新日期:必填项
Every CLAUDE.md MUST include a "Last verified" date.
CRITICAL: Use Bash to get the actual date. Do NOT hallucinate dates.
bash
date +%Y-%m-%dInclude in file:
markdown
Last verified: 2025-12-17Why mandatory: Stale CLAUDE.md files are worse than none. The date signals when contracts were last confirmed accurate.
每个CLAUDE.md必须包含“Last verified”日期。
重要提示: 使用Bash获取实际日期。请勿虚构日期。
bash
date +%Y-%m-%d在文件中添加:
markdown
Last verified: 2025-12-17必填原因: 过时的CLAUDE.md文件比没有更糟。日期表明契约最后被确认准确的时间。
Referencing Files
引用文件
You can reference key files in CLAUDE.md:
markdown
undefined你可以在CLAUDE.md中引用关键文件:
markdown
undefinedKey Files
关键文件
- - Public exports
index.ts - - Main implementation
service.ts
**Do NOT use @ syntax** (e.g., `@./service.ts`). This force-loads files into context, burning tokens. Just name the files; Claude can read them when needed.- - 公共导出
index.ts - - 主要实现
service.ts
**请勿使用@语法**(如`@./service.ts`)。这会强制将文件加载到上下文中,消耗令牌。只需命名文件;Claude需要时会读取它们。Heuristics: Top-Level vs Subdirectory
顶层与子目录的判断准则
| Question | Top-level | Subdirectory |
|---|---|---|
| Applies project-wide? | ✓ | |
| New engineer needs on day 1? | ✓ | |
| About commands/conventions? | ✓ | |
| About WHY a component exists? | ✓ | |
| About contracts between parts? | ✓ | |
| Changes when the domain changes? | ✓ |
Rule of thumb:
- Top-level = "How to work here"
- Subdirectory = "Why this exists and what it promises"
| 问题 | 顶层 | 子目录 |
|---|---|---|
| 适用于项目全局? | ✓ | |
| 新工程师第一天需要了解? | ✓ | |
| 关于命令/约定? | ✓ | |
| 关于组件存在的原因? | ✓ | |
| 关于各部分之间的契约? | ✓ | |
| 随域变化而变化? | ✓ |
经验法则:
- 顶层 = “如何在此工作”
- 子目录 = “此内容存在的原因及其承诺”
When to Create Subdirectory CLAUDE.md
何时创建子目录CLAUDE.md
Create when:
- Domain has non-obvious contracts with other parts
- Architectural decisions affect how code should evolve
- Invariants exist that aren't obvious from code
- New sessions consistently need the same context re-explained
Don't create for:
- Trivial utility folders
- Implementation details that change frequently
- Content better captured in code comments
在以下情况创建:
- 域与其他部分存在不明显的契约
- 架构决策影响代码的演进方式
- 存在从代码中无法明显看出的不变量
- 新会话持续需要重复解释相同的上下文
无需创建的情况:
- 简单的工具文件夹
- 频繁变化的实现细节
- 更适合在代码注释中体现的内容
Updating CLAUDE.md Files
更新CLAUDE.md文件
When updating any CLAUDE.md:
- Update the freshness date using Bash
date +%Y-%m-%d - Verify contracts still hold - read the code, check invariants
- Remove stale content - better short and accurate than long and wrong
- Keep token-efficient - <300 lines top-level, <100 lines subdirectory
更新任何CLAUDE.md时:
- 更新日期 使用Bash
date +%Y-%m-%d - 验证契约仍然有效 - 阅读代码,检查不变量
- 删除过时内容 - 简短准确比冗长错误更好
- 保持令牌效率 - 顶层文件<300行,子目录文件<100行
Common Mistakes
常见错误
| Mistake | Fix |
|---|---|
| Describing WHAT code does | Focus on WHY it exists, contracts it keeps |
| Missing freshness date | Always include, always use Bash for real date |
| Using @ to reference files | Just name files, let Claude read on demand |
| Too much detail | Subdirectory files should be <100 lines |
| Duplicating parent content | Subdirectory inherits parent; don't repeat |
| Stale contracts | Update when domain changes; verify dates |
| 错误 | 修复方案 |
|---|---|
| 描述代码做什么 | 聚焦于代码存在的原因、它遵守的契约 |
| 缺少更新日期 | 始终包含,且始终使用Bash获取真实日期 |
| 使用@引用文件 | 只需命名文件,让Claude按需读取 |
| 内容过于详细 | 子目录文件应少于100行 |
| 重复父级内容 | 子目录继承父级内容;不要重复 |
| 契约过时 | 域变化时更新;验证日期 |
Checklist
检查清单
Top-level:
- Tech stack listed
- Key commands documented
- Project structure overview
- Freshness date (from )
date +%Y-%m-%d
Subdirectory:
- Purpose explains WHY (not what)
- Contracts: exposes, guarantees, expects
- Dependencies and boundaries clear
- Key decisions with rationale
- Invariants documented
- Freshness date (from )
date +%Y-%m-%d - Under 100 lines
顶层:
- 列出技术栈
- 记录关键命令
- 项目结构概览
- 更新日期(来自)
date +%Y-%m-%d
子目录:
- 用途解释了存在原因(不是做什么)
- 契约:暴露内容、承诺、要求
- 依赖与边界清晰
- 带理由的关键决策
- 记录不变量
- 更新日期(来自)
date +%Y-%m-%d - 少于100行