create-rule

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Create Rule

创建规则

Guide for creating effective
.claude/rules
files with contrastive examples that improve agent accuracy.
本指南介绍如何使用对比示例创建有效的
.claude/rules
文件,以提升Agent的准确性。

Overview

概述

Core principle: Effective rules use contrastive examples (Incorrect vs Correct) to eliminate ambiguity.
REQUIRED BACKGROUND: Rules are behavioral guardrails, that load into every session and shapes how agents behave across all tasks. Skills load on-demand. If guidance is task-specific, create a skill instead.
核心原则: 有效的规则使用对比示例(错误示例 vs 正确示例)来消除歧义。
必备背景知识: 规则是行为护栏,会加载到每个会话中,指导Agent在所有任务中的行为。技能是按需加载的。如果指导内容是特定任务相关的,请创建技能而非规则。

About Rules

关于规则

Rules are modular, always-loaded instructions placed in
.claude/rules/
that enforce consistent behavior. They act as "standing orders" — every agent session inherits them automatically.
规则是模块化的、始终加载的指令,存放在
.claude/rules/
目录中,用于强制一致的行为。它们相当于“常规指令”——每个Agent会话都会自动继承这些规则。

What Rules Provide

规则的作用

  1. Behavioral constraints — What to do and what NOT to do
  2. Code standards — Formatting, patterns, architecture decisions
  3. Quality gates — Conditions that must be met before proceeding
  4. Domain conventions — Project-specific terminology and practices
  1. 行为约束 —— 规定应该做什么和不应该做什么
  2. 代码标准 —— 格式、模式、架构决策
  3. 质量门槛 —— 执行前必须满足的条件
  4. 领域约定 —— 项目特定的术语和实践

Rules vs Skills vs CLAUDE.md

规则 vs 技能 vs CLAUDE.md

AspectRules (
.claude/rules/
)
Skills (
skills/
)
CLAUDE.md
LoadingEvery session (or path-scoped)On-demand when triggeredEvery session
PurposeBehavioral constraintsProcedural knowledgeProject overview
ScopeNarrow, focused topicsComplete workflowsBroad project context
SizeSmall (50-200 words each)Medium (200-2000 words)Medium (project summary)
FormatContrastive examplesStep-by-step guidesKey-value / bullet points
方面规则(
.claude/rules/
技能(
skills/
CLAUDE.md
加载方式每个会话(或按路径范围)按需触发加载每个会话
用途行为约束流程知识项目概览
范围狭窄、聚焦特定主题完整工作流广泛的项目上下文
篇幅简短(每个50-200词)中等(200-2000词)中等(项目摘要)
格式对比示例分步指南键值对/项目符号

When to Create a Rule

何时创建规则

Create when:
  • A behavior must apply to ALL agent sessions, not just specific tasks
  • Agents repeatedly make the same mistake despite corrections
  • A convention has clear right/wrong patterns (contrastive examples possible)
  • Path-specific guidance is needed for certain file types
Do NOT create for:
  • Task-specific workflows (use a skill instead)
  • One-time instructions (put in the prompt)
  • Broad project context (put in CLAUDE.md)
  • Guidance that requires multi-step procedures (use a skill)
创建规则的场景:
  • 某一行为必须适用于所有Agent会话,而非仅特定任务
  • 尽管多次纠正,Agent仍重复犯相同错误
  • 某一约定有明确的对错模式(可提供对比示例)
  • 特定文件类型需要路径相关的指导
请勿创建规则的场景:
  • 特定任务的工作流(改用技能)
  • 一次性指令(直接放入提示词)
  • 广泛的项目上下文(放入CLAUDE.md)
  • 需要多步骤流程的指导(改用技能)

Rule Types

规则类型

Global Rules (no
paths
frontmatter)

全局规则(无
paths
前置元数据)

Load every session. Use for universal constraints.
markdown
undefined
会加载到每个会话中,用于通用约束。
markdown
undefined

Error Handling

错误处理

All error handlers must log the error before rethrowing. Never silently swallow exceptions.
undefined
所有错误处理程序必须在重新抛出错误前记录错误。 切勿静默吞掉异常。
undefined

Path-Scoped Rules (
paths
frontmatter)

路径范围规则(含
paths
前置元数据)

Load only when agent works with matching files. Use for file-type-specific guidance.
markdown
---
paths:
  - "src/api/**/*.ts"
---
仅当Agent处理匹配文件时加载,用于特定文件类型的指导。
markdown
---
paths:
  - "src/api/**/*.ts"
---

API Development Rules

API开发规则

All API endpoints must include input validation. Use the standard error response format.
undefined
所有API端点必须包含输入验证。 使用标准错误响应格式。
undefined

Priority Rules (evaluator/judge guidance)

优先级规则(评估者/裁判指导)

Explicit high-level rules that set evaluation priorities.
markdown
undefined
明确的高级规则,用于设定评估优先级。
markdown
undefined

Evaluation Priorities

评估优先级

Prioritize correctness over style. Do not reward hallucinated detail. Penalize confident wrong answers more than uncertain correct ones.
undefined
优先考虑正确性而非风格。 不奖励虚构的细节。 对自信的错误答案的惩罚要比对不确定的正确答案更重。
undefined

Rule Structure: The Contrastive Pattern

规则结构:对比模式

Every rule MUST follow the Description-Incorrect-Correct template. This structure eliminates ambiguity by showing both what NOT to do and what TO do.
每个规则必须遵循“描述-错误示例-正确示例”的模板。这种结构通过展示错误做法和正确做法来消除歧义。

Required Sections

必填部分

markdown
---
title: Short Rule Name
paths:                          # Optional but preferable: when it is possible to define, use it!
  - "src/**/*.ts"
---
markdown
---
title: 简短规则名称
paths:                          # 可选但推荐:如果可以定义,请使用!
  - "src/**/*.ts"
---

Rule Name

规则名称

[1-2 sentence description of what the rule enforces and WHY it matters.]
[1-2句话描述规则的约束内容及其重要性。]

Incorrect

错误示例

[Description of what is wrong with this pattern.]
```language // Anti-pattern code or behavior example ```
[描述该模式的问题所在。]
```language // 反模式代码或行为示例 ```

Correct

正确示例

[Description of why this pattern is better.]
```language // Recommended code or behavior example ```
[描述该模式更优的原因。]
```language // 推荐的代码或行为示例 ```

Reference

参考

[Optional: links to documentation, papers, or related rules.]
undefined
[可选:文档、论文或相关规则的链接。]
undefined

Why Contrastive Examples Work

对比示例为何有效

Researches shows that rules with both positive and negative examples are significantly more discriminative than rules with only positive guidance. The Incorrect/Correct pairing:
  1. Eliminates ambiguity — the agent sees the exact boundary between acceptable and unacceptable
  2. Prevents rationalization — harder to argue "this is close enough" when the wrong pattern is explicitly shown
  3. Enables self-correction — agents can compare their output against both patterns
研究表明,同时包含正面和负面示例的规则比仅包含正面指导的规则具有更高的区分度。错误/正确示例配对:
  1. 消除歧义 —— Agent可以清楚看到可接受与不可接受行为的边界
  2. 防止合理化 —— 当错误模式被明确展示时,Agent更难辩解“这样已经足够接近”
  3. 实现自我修正 —— Agent可以将自己的输出与两种模式进行对比

Writing Effective Rules

编写有效的规则

Rule Description Principles

规则描述原则

Explicit, high-level guidance:
PrincipleExample
Prioritize correctness over style"A functionally correct but ugly solution is better than an elegant but broken one"
Do not reward hallucinated detail"Extra information not grounded in the codebase should be penalized, not rewarded"
Penalize confident errors"A confidently stated wrong answer is worse than an uncertain correct one"
Be specific, not vague"Functions must not exceed 50 lines" not "Keep functions short"
State the WHY"Use early returns to reduce nesting — deeply nested code increases cognitive load"
明确、高级的指导:
原则示例
优先考虑正确性而非风格“功能正确但丑陋的解决方案比优雅但失效的方案更好”
不奖励虚构的细节“未基于代码库的额外信息应受到惩罚,而非奖励”
惩罚自信的错误“自信陈述的错误答案比不确定的正确答案更糟糕”
具体而非模糊“函数长度不得超过50行”而非“保持函数简短”
说明原因“使用提前返回减少嵌套——深度嵌套的代码会增加认知负担”

Incorrect Examples: What to Show

错误示例:应展示什么

The Incorrect section must show a pattern the agent would plausibly produce. Abstract or contrived bad examples provide no value.
Effective Incorrect examples:
  • Show the most common mistake agents make for this scenario
  • Include the rationalization an agent might use ("this is simpler")
  • Mirror real code patterns found in the codebase
Ineffective Incorrect examples:
  • Obviously broken code no agent would produce
  • Syntax errors (agents already avoid these)
  • Patterns unrelated to the rule's concern
错误示例部分必须展示Agent可能会产生的模式。抽象或刻意构造的糟糕示例毫无价值。
有效的错误示例:
  • 展示Agent在该场景下最常犯的错误
  • 包含Agent可能会使用的合理化理由(“这样更简单”)
  • 镜像代码库中真实存在的代码模式
无效的错误示例:
  • 明显错误的代码,Agent根本不会产生
  • 语法错误(Agent已经会避免这些)
  • 与规则关注点无关的模式

Correct Examples: What to Show

正确示例:应展示什么

The Correct section must show the minimal change needed to fix the Incorrect pattern. Large rewrites obscure the actual lesson.
Effective Correct examples:
  • Show the same scenario as Incorrect, fixed
  • Highlight the specific change that matters
  • Include a brief comment explaining WHY this is better
Ineffective Correct examples:
  • Completely different code from the Incorrect example
  • Over-engineered solutions that add unnecessary complexity
  • Patterns that require additional context not shown
正确示例部分必须展示修复错误示例所需的最小改动。大幅重写会掩盖实际要传达的要点。
有效的正确示例:
  • 展示与错误示例相同的场景,但已修复
  • 突出显示关键的改动
  • 包含简短注释说明为何这样更优
无效的正确示例:
  • 与错误示例完全不同的代码
  • 过度设计的解决方案,增加了不必要的复杂性
  • 需要额外上下文才能理解的模式

Token Efficiency

令牌效率

Rules load every session. Every token counts.
  • Target: 50-200 words per rule file (excluding code examples)
  • One rule per file — do not bundle unrelated constraints
  • Use path scoping to avoid loading irrelevant rules
  • Code examples: Keep under 20 lines each (Incorrect and Correct)
规则会加载到每个会话中,每个令牌都很重要。
  • 目标: 每个规则文件50-200词(不含代码示例)
  • 一个文件一个规则 —— 不要将无关约束捆绑在一起
  • 使用路径范围 避免加载无关规则
  • 代码示例: 每个示例不超过20行(错误示例和正确示例)

Directory Structure

目录结构

.claude/
├── CLAUDE.md                    # Project overview (broad)
└── rules/
    ├── code-style.md            # Global: code formatting rules
    ├── error-handling.md        # Global: error handling patterns
    ├── testing.md               # Global: testing conventions
    ├── security.md              # Global: security requirements
    ├── evaluation-priorities.md # Global: judge/evaluator priorities
    ├── frontend/
    │   ├── components.md        # Path-scoped: React component rules
    │   └── state-management.md  # Path-scoped: state management rules
    └── backend/
        ├── api-design.md        # Path-scoped: API patterns
        └── database.md          # Path-scoped: database conventions
Naming conventions:
  • Use lowercase with hyphens:
    error-handling.md
    , not
    ErrorHandling.md
  • Name by the concern, not the solution:
    error-handling.md
    , not
    try-catch-patterns.md
  • One topic per file for modularity
  • Use subdirectories to group related rules by domain
.claude/
├── CLAUDE.md                    # 项目概览(广泛)
└── rules/
    ├── code-style.md            # 全局:代码格式规则
    ├── error-handling.md        # 全局:错误处理模式
    ├── testing.md               # 全局:测试约定
    ├── security.md              # 全局:安全要求
    ├── evaluation-priorities.md # 全局:裁判/评估者优先级
    ├── frontend/
    │   ├── components.md        # 路径范围:React组件规则
    │   └── state-management.md  # 路径范围:状态管理规则
    └── backend/
        ├── api-design.md        # 路径范围:API模式
        └── database.md          # 路径范围:数据库约定
命名约定:
  • 使用小写连字符:
    error-handling.md
    ,而非
    ErrorHandling.md
  • 按关注点命名,而非解决方案:
    error-handling.md
    ,而非
    try-catch-patterns.md
  • 每个文件一个主题,保证模块化
  • 使用子目录按领域分组相关规则

Rule Creation Process

规则创建流程

Follow these steps in order, skipping only when a step is clearly not applicable.
按以下步骤依次执行,仅当步骤明显不适用时可跳过。

Step 1: Identify the Behavioral Gap

步骤1:识别行为漏洞

Before writing any rule, identify the specific agent behavior that needs correction. This understanding can come from:
  • Observed failures — the agent repeatedly makes a specific mistake
  • Codebase analysis — the project has conventions not obvious from code alone
  • Evaluation findings — a judge/meta-judge identified a quality gap
  • User feedback — explicit correction of agent behavior
Document the gap as a concrete statement: "The agent does X, but should do Y."
Conclude this step when there is a clear, specific behavior to correct.
在编写任何规则之前,先确定需要纠正的具体Agent行为。这种认知可来自:
  • 观察到的失败 —— Agent反复犯特定错误
  • 代码库分析 —— 项目有仅从代码中无法明显看出的约定
  • 评估结果 —— 裁判/元裁判发现质量漏洞
  • 用户反馈 —— 对Agent行为的明确纠正
将漏洞记录为具体陈述:“Agent当前做X,但应该做Y。”
当有明确、具体的行为需要纠正时,完成此步骤。

Step 2: Determine Rule Scope

步骤2:确定规则范围

Decide whether this rule should be:
  1. Global (no
    paths
    frontmatter) — applies to all work in the project
  2. Path-scoped (
    paths
    frontmatter with glob patterns) — applies only when working with matching files
  3. User-level (
    ~/.claude/rules/
    ) — applies across all projects for personal preferences
Decision guide:
Is this project-specific?
  No  → User-level rule (~/.claude/rules/)
  Yes → Is it relevant to ALL files?
    Yes → Global rule (.claude/rules/rule-name.md)
    No  → Path-scoped rule (.claude/rules/rule-name.md with paths: frontmatter)
决定该规则应该是:
  1. 全局规则(无
    paths
    前置元数据)—— 适用于项目中的所有工作
  2. 路径范围规则(含
    paths
    前置元数据和通配符模式)—— 仅适用于处理匹配文件时
  3. 用户级规则
    ~/.claude/rules/
    )—— 适用于所有项目,满足个人偏好
决策指南:
这是项目特定的吗?
  否 → 用户级规则(~/.claude/rules/)
  是 → 是否与所有文件相关?
    是 → 全局规则(.claude/rules/rule-name.md)
    否 → 路径范围规则(.claude/rules/rule-name.md,含paths:前置元数据)

Step 3: Write Contrastive Examples

步骤3:编写对比示例

This is the most critical step. Write the Incorrect and Correct examples BEFORE writing the description.
  1. Start with the Incorrect pattern — write the exact code or behavior the agent produces that needs correction
  2. Write the Correct pattern — show the minimal fix that addresses the issue
  3. Verify contrast is clear — the difference between Incorrect and Correct must be obvious and focused on exactly one concept
Quality check for contrastive examples:
CheckPass Criteria
PlausibilityWould an agent actually produce the Incorrect pattern?
MinimalityDoes the Correct pattern change only what is necessary?
ClarityCan a reader identify the difference in under 5 seconds?
SpecificityDoes each example demonstrate exactly one concept?
GroundednessAre the examples drawn from real codebase patterns?
这是最关键的步骤。先编写错误示例和正确示例,再编写描述。
  1. 从错误模式开始 —— 写出Agent产生的需要纠正的具体代码或行为
  2. 编写正确模式 —— 展示解决问题所需的最小改动
  3. 验证对比清晰度 —— 错误示例和正确示例之间的差异必须明显,且聚焦于同一个概念
对比示例质量检查:
检查项通过标准
合理性Agent真的会产生该错误模式吗?
最小化正确示例是否仅改动必要部分?
清晰度读者能否在5秒内识别出差异?
针对性每个示例是否仅展示一个概念?
关联性示例是否来自真实的代码库模式?

Step 4: Write the Rule Description

步骤4:编写规则描述

Now write the 1-2 sentence description that connects the contrastive examples. The description must:
  • State WHAT the rule enforces
  • State WHY it matters (the impact or consequence)
  • Use imperative form ("Use early returns" not "You should use early returns")
现在编写1-2句话的描述,连接对比示例。描述必须:
  • 说明规则约束的内容
  • 说明其重要性(影响或后果)
  • 使用祈使语气(“使用提前返回”而非“你应该使用提前返回”)

Step 5: Assemble the Rule File

步骤5:组装规则文件

Create the rule file following the structure template:
  1. Add YAML frontmatter with
    title
    ,
    impact
    ,
    tags
    , and optionally
    paths
  2. Write the heading and description
  3. Add the Incorrect section with description and code
  4. Add the Correct section with description and code
  5. Optionally add a Reference section with links
Place the file in
.claude/rules/
with a descriptive filename.
按照结构模板创建规则文件:
  1. 添加YAML前置元数据,包含
    title
    impact
    tags
    ,可选
    paths
  2. 编写标题和描述
  3. 添加错误示例部分,包含描述和代码
  4. 添加正确示例部分,包含描述和代码
  5. 可选添加参考部分,包含链接
将文件放入
.claude/rules/
目录,使用描述性文件名。

Step 6: Validate the Rule

步骤6:验证规则

Before finishing, verify:
  1. File location — rule exists at
    .claude/rules/<rule-name>.md
  2. Frontmatter — contains at minimum
    title
    and
    impact
  3. Contrastive examples — both Incorrect and Correct sections present with code blocks
  4. Token budget — description is 50-200 words (excluding code)
  5. Path scoping — if
    paths
    is set, glob patterns match intended files
  6. No overlap — rule does not duplicate guidance in CLAUDE.md or other rules
完成前,验证以下内容:
  1. 文件位置 —— 规则存在于
    .claude/rules/<rule-name>.md
  2. 前置元数据 —— 至少包含
    title
    impact
  3. 对比示例 —— 同时包含错误示例和正确示例部分,且带有代码块
  4. 令牌预算 —— 描述部分为50-200词(不含代码)
  5. 路径范围 —— 如果设置了
    paths
    ,通配符模式匹配目标文件
  6. 无重叠 —— 规则未重复CLAUDE.md或其他规则中的指导内容

Step 7: Iterate Based on Feedback or Observations

步骤7:根据反馈或观察迭代优化

After a rule is written, apply a Decompose → Filter → Reweight refinement cycle before finalizing:
规则编写完成后,在最终确定前应用“分解→过滤→重新加权”的优化循环:

7.1 Decompose Check

7.1 分解检查

Consider splitting complex rules into multiple focused rules.
For rules that your written, ask yourself: "Is this rule trying to cover more than one concept?"
  • If YES, split it into multiple focused rules, each addressing exactly one concept
  • If the Incorrect example shows multiple distinct anti-patterns, create separate rules for each
考虑将复杂规则拆分为多个聚焦的规则。
对于你编写的规则,问自己:“这条规则是否试图涵盖多个概念?”
  • 如果是,将其拆分为多个聚焦的规则,每个规则仅解决一个概念
  • 如果错误示例展示了多个不同的反模式,为每个反模式创建单独的规则

7.2 Misalignment Filter

7.2 不一致性过滤

For rules that your written, ask yourself: "Could this rule penalize acceptable variations or reward behaviors the prompt does not ask for?"
  • If YES, narrow the scope or rewrite the contrastive examples
  • Verify: would an agent actually produce the Incorrect pattern? (If not, the rule is contrived)
对于你编写的规则,问自己:“这条规则是否会惩罚可接受的变体,或奖励提示词未要求的行为?”
  • 如果是,缩小范围或重写对比示例
  • 验证:Agent真的会产生该错误模式吗?(如果不会,这条规则是刻意构造的)

7.3 Redundancy Filter

7.3 冗余过滤

Check all existing
.claude/rules/
files for overlap:
  • If already exists a rule that covers the same concept, update the existing rule instead and remove the duplicate rule that you just created
  • If two rules substantially overlap (enforcing the same behavioral boundary), merge them
  • Use:
    ls -R .claude/rules/
    and
    grep -r "relevant-keyword"
    to find potential overlaps
检查所有现有
.claude/rules/
文件是否存在重叠:
  • 如果已有规则涵盖相同概念,更新现有规则,删除你刚创建的重复规则
  • 如果两条规则大幅重叠(强制相同的行为边界),合并它们
  • 使用:
    ls -R .claude/rules/
    grep -r "相关关键词"
    查找潜在重叠

7.4 Impact Reweight

7.4 影响重新加权

Assign or reassign the
impact
frontmatter field based on:
  • CRITICAL: Anti-pattern causes data loss, security vulnerabilities, or system failures
  • HIGH: Anti-pattern causes broken functionality, incorrect behavior, or hard-to-debug issues
  • MEDIUM: Anti-pattern degrades quality, readability, or maintainability
  • LOW: Anti-pattern is a minor style or convention issue
根据以下标准分配或重新分配
impact
前置元数据字段:
  • CRITICAL(严重):反模式导致数据丢失、安全漏洞或系统故障
  • HIGH(高):反模式导致功能失效、行为错误或难以调试的问题
  • MEDIUM(中):反模式降低质量、可读性或可维护性
  • LOW(低):反模式是轻微的风格或约定问题

7.5 Iterate Based on Feedback

7.5 根据反馈迭代

After the refinement cycle, ask the user for feedback on the rule.
  • If the user says that the rule is good, you can stop the refinement cycle.
  • If the user says that the rule is bad, you should update the rule to close gaps.
You should continue to iterate until the rule is good.
优化循环后,向用户征求对规则的反馈。
  • 如果用户认为规则良好,可停止优化循环。
  • 如果用户认为规则不佳,应更新规则以填补漏洞。
你应该持续迭代,直到规则完善。

Complete Rule Example

完整规则示例

markdown
---
title: Use Early Returns to Reduce Nesting
paths:
  - "**/*.ts"
---
markdown
---
title: 使用提前返回减少嵌套
paths:
  - "**/*.ts"
---

Use Early Returns to Reduce Nesting

使用提前返回减少嵌套

Handle error conditions and edge cases at the top of functions using early returns. Deeply nested code increases cognitive load and makes logic harder to follow.
在函数顶部使用提前返回处理错误条件和边缘情况。深度嵌套的代码会增加认知负担,使逻辑更难理解。

Incorrect

错误示例

Guard clauses are buried inside nested conditionals, making the happy path hard to find.
```typescript function processOrder(order: Order) { if (order) { if (order.items.length > 0) { if (order.status === 'pending') { // actual logic buried 3 levels deep const total = calculateTotal(order.items) return submitOrder(order, total) } else { throw new Error('Order not pending') } } else { throw new Error('No items') } } else { throw new Error('No order') } } ```
守卫子句被埋在嵌套条件中,使主逻辑难以找到。
```typescript function processOrder(order: Order) { if (order) { if (order.items.length > 0) { if (order.status === 'pending') { // 实际逻辑被埋在3层嵌套中 const total = calculateTotal(order.items) return submitOrder(order, total) } else { throw new Error('订单未处于待处理状态') } } else { throw new Error('无商品') } } else { throw new Error('无订单') } } ```

Correct

正确示例

Error conditions are handled first with early returns, keeping the happy path at the top level.
```typescript function processOrder(order: Order) { if (!order) throw new Error('No order') if (order.items.length === 0) throw new Error('No items') if (order.status !== 'pending') throw new Error('Order not pending')
const total = calculateTotal(order.items) return submitOrder(order, total) } ```
错误条件通过提前返回优先处理,主逻辑保持在顶层。
```typescript function processOrder(order: Order) { if (!order) throw new Error('无订单') if (order.items.length === 0) throw new Error('无商品') if (order.status !== 'pending') throw new Error('订单未处于待处理状态')
const total = calculateTotal(order.items) return submitOrder(order, total) } ```

Reference

参考

Complete Path-Scoped Rule Example

完整路径范围规则示例

markdown
---
title: API Endpoints Must Validate Input
paths:
  - "src/api/**/*.ts"
  - "src/routes/**/*.ts"
---
markdown
---
title: API端点必须验证输入
paths:
  - "src/api/**/*.ts"
  - "src/routes/**/*.ts"
---

API Endpoints Must Validate Input

API端点必须验证输入

Every API endpoint must validate request input before processing. Unvalidated input leads to runtime errors, security vulnerabilities, and data corruption.
每个API端点必须在处理前验证请求输入。未验证的输入会导致运行时错误、安全漏洞和数据损坏。

Incorrect

错误示例

The handler trusts the request body without validation, allowing malformed data through.
```typescript export async function POST(req: Request) { const body = await req.json() const user = await db.users.create({ email: body.email, name: body.name, }) return Response.json(user) } ```
处理程序信任请求体而不进行验证,允许格式错误的数据通过。
```typescript export async function POST(req: Request) { const body = await req.json() const user = await db.users.create({ email: body.email, name: body.name, }) return Response.json(user) } ```

Correct

正确示例

Input is validated with a schema before use. Invalid requests receive a 400 response.
```typescript import { z } from 'zod'
const CreateUserSchema = z.object({ email: z.string().email(), name: z.string().min(1).max(100), })
export async function POST(req: Request) { const parsed = CreateUserSchema.safeParse(await req.json()) if (!parsed.success) { return Response.json({ error: parsed.error.flatten() }, { status: 400 }) } const user = await db.users.create(parsed.data) return Response.json(user) } ```
undefined
输入在使用前通过模式验证。无效请求会收到400响应。
```typescript import { z } from 'zod'
const CreateUserSchema = z.object({ email: z.string().email(), name: z.string().min(1).max(100), })
export async function POST(req: Request) { const parsed = CreateUserSchema.safeParse(await req.json()) if (!parsed.success) { return Response.json({ error: parsed.error.flatten() }, { status: 400 }) } const user = await db.users.create(parsed.data) return Response.json(user) } ```
undefined

Anti-Patterns

反模式

Vague Rules Without Examples

无示例的模糊规则

markdown
undefined
markdown
undefined

Bad: No contrastive examples, too vague

错误示例:无对比示例,过于模糊

Keep functions short and readable. Use meaningful variable names.

**Why bad:** No concrete boundary. "Short" means different things to different agents. No Incorrect/Correct to calibrate behavior.
保持函数简短易读。 使用有意义的变量名。

**为何不好:** 没有明确的边界。“简短”对不同Agent有不同含义。没有错误/正确示例来校准行为。

Rules That Should Be Skills

应作为技能的规则

markdown
undefined
markdown
undefined

Bad: Multi-step procedure in a rule

错误示例:规则中包含多步骤流程

When deploying to production:
  1. Run all tests
  2. Check coverage thresholds
  3. Build the project
  4. Run integration tests
  5. Deploy to staging first ...

**Why bad:** Rules should be constraints, not workflows. This belongs in a skill.
部署到生产环境时:
  1. 运行所有测试
  2. 检查覆盖率阈值
  3. 构建项目
  4. 运行集成测试
  5. 先部署到预发布环境 ...

**为何不好:** 规则应该是约束,而非工作流。这属于技能的范畴。

Duplicate Rules

重复规则

markdown
undefined
markdown
undefined

Bad: Same guidance in two places

错误示例:同一指导内容出现在两个地方

.claude/rules/formatting.md says "use 2-space indent"

.claude/rules/formatting.md 说“使用2空格缩进”

CLAUDE.md also says "use 2-space indent"

CLAUDE.md 也说“使用2空格缩进”


**Why bad:** When guidance conflicts, the agent cannot determine which takes precedence. Keep each piece of guidance in exactly one location.

**为何不好:** 当指导内容冲突时,Agent无法确定哪个优先级更高。每个指导内容应仅存放在一个位置。

Overly Broad Path Scoping

过于宽泛的路径范围

markdown
---
paths:
  - "**/*"
---
Why bad: Equivalent to a global rule but with the overhead of path matching. Remove the
paths
field entirely for global rules.
markdown
---
paths:
  - "**/*"
---
为何不好: 等同于全局规则,但增加了路径匹配的开销。全局规则应完全移除
paths
字段。

Rule Creation Checklist

规则创建检查清单

  • Behavioral gap identified with concrete "does X, should do Y" statement
  • Rule type determined: global, path-scoped, or user-level
  • Contrastive examples written: Incorrect shows plausible agent mistake
  • Contrastive examples written: Correct shows minimal fix
  • Description states WHAT the rule enforces and WHY
  • Frontmatter includes
    title
    and
    impact
  • Token budget: 50-200 words (excluding code examples)
  • One topic per rule file
  • No overlap with CLAUDE.md or other rule files
  • Path scoping uses correct glob patterns (if applicable)
  • File placed in
    .claude/rules/
    with descriptive hyphenated name
  • 已识别行为漏洞,并有具体的“当前做X,应该做Y”陈述
  • 已确定规则类型:全局、路径范围或用户级
  • 已编写对比示例:错误示例展示了Agent可能犯的错误
  • 已编写对比示例:正确示例展示了最小改动
  • 描述说明了规则约束的内容及其重要性
  • 前置元数据包含
    title
    impact
  • 令牌预算:描述部分50-200词(不含代码示例)
  • 一个文件一个主题
  • 与CLAUDE.md或其他规则文件无重叠
  • 路径范围使用了正确的通配符模式(如适用)
  • 文件已放入
    .claude/rules/
    目录,使用描述性连字符命名

The Bottom Line

核心要点

Effective rules show, they do not just tell. The Incorrect/Correct contrastive pattern eliminates ambiguity that prose descriptions leave open. When an agent can see both what to avoid and what to produce, compliance improves dramatically.
Every rule should answer three questions:
  1. What behavior does this enforce?
  2. Why does it matter?
  3. How does right differ from wrong? (shown through contrastive examples)
有效的规则是展示,而非仅仅告知。 错误/正确的对比模式消除了文字描述留下的歧义。当Agent既能看到要避免的行为,又能看到要生成的行为时,合规性会大幅提升。
每条规则都应回答三个问题:
  1. 是什么:这条规则约束什么行为?
  2. 为什么:它为何重要?
  3. 如何区分:正确与错误的区别是什么?(通过对比示例展示)

Claude Code Official Rules Guidlines

Claude Code官方规则指南

For larger projects, you can organize instructions into multiple files using the
.claude/rules/
directory. This keeps instructions modular and easier for teams to maintain. Rules can also be scoped to specific file paths, so they only load into context when Claude works with matching files, reducing noise and saving context space.
<Note> Rules load into context every session or when matching files are opened. For task-specific instructions that don't need to be in context all the time, use [skills](/en/skills) instead, which only load when you invoke them or when Claude determines they're relevant to your prompt. </Note>
对于大型项目,你可以使用
.claude/rules/
目录将指令组织到多个文件中。这使指令保持模块化,更易于团队维护。规则还可以限定到特定文件路径,因此仅当Claude处理匹配文件时才会加载到上下文中,减少干扰并节省上下文空间。
<Note> 规则会在每个会话或打开匹配文件时加载到上下文中。对于不需要始终处于上下文的特定任务指令,请改用[技能](/en/skills),技能仅在你调用它们或Claude确定它们与你的提示词相关时才会加载。 </Note>

Set up rules

设置规则

Place markdown files in your project's
.claude/rules/
directory. Each file should cover one topic, with a descriptive filename like
testing.md
or
api-design.md
. All
.md
files are discovered recursively, so you can organize rules into subdirectories like
frontend/
or
backend/
:
text
your-project/
├── .claude/
│   ├── CLAUDE.md           # Main project instructions
│   └── rules/
│       ├── code-style.md   # Code style guidelines
│       ├── testing.md      # Testing conventions
│       └── security.md     # Security requirements
Rules without
paths
frontmatter
are loaded at launch with the same priority as
.claude/CLAUDE.md
.
将Markdown文件放在项目的
.claude/rules/
目录中。每个文件应涵盖一个主题,使用描述性文件名,如
testing.md
api-design.md
。所有
.md
文件会被递归发现,因此你可以将规则组织到子目录中,如
frontend/
backend/
text
your-project/
├── .claude/
│   ├── CLAUDE.md           # 主项目指令
│   └── rules/
│       ├── code-style.md   # 代码风格指南
│       ├── testing.md      # 测试约定
│       └── security.md     # 安全要求
没有
paths
前置元数据
的规则会在启动时加载,优先级与
.claude/CLAUDE.md
相同。

Path-specific rules

路径范围规则

Rules can be scoped to specific files using YAML frontmatter with the
paths
field. These conditional rules only apply when Claude is working with files matching the specified patterns.
markdown
---
paths:
  - "src/api/**/*.ts"
---
可以使用带有
paths
字段的YAML前置元数据将规则限定到特定文件。这些条件规则仅在Claude处理匹配指定模式的文件时适用。
markdown
---
paths:
  - "src/api/**/*.ts"
---

API Development Rules

API开发规则

  • All API endpoints must include input validation
  • Use the standard error response format
  • Include OpenAPI documentation comments

Rules without a `paths` field are loaded unconditionally and apply to all files. Path-scoped rules trigger when Claude reads files matching the pattern, not on every tool use.

Use glob patterns in the `paths` field to match files by extension, directory, or any combination:

| Pattern                | Matches                                  |
| ---------------------- | ---------------------------------------- |
| `**/*.ts`              | All TypeScript files in any directory    |
| `src/**/*`             | All files under `src/` directory         |
| `*.md`                 | Markdown files in the project root       |
| `src/components/*.tsx` | React components in a specific directory |

You can specify multiple patterns and use brace expansion to match multiple extensions in one pattern:

```markdown  theme={null}
---
paths:
  - "src/**/*.{ts,tsx}"
  - "lib/**/*.ts"
  - "tests/**/*.test.ts"
---
  • 所有API端点必须包含输入验证
  • 使用标准错误响应格式
  • 包含OpenAPI文档注释

没有`paths`字段的规则会无条件加载,适用于所有文件。路径范围规则在Claude读取匹配模式的文件时触发,而非在每次使用工具时触发。

在`paths`字段中使用通配符模式按扩展名、目录或任意组合匹配文件:

| 模式                | 匹配对象                                  |
| ---------------------- | ---------------------------------------- |
| `**/*.ts`              | 所有目录中的TypeScript文件    |
| `src/**/*`             | `src/`目录下的所有文件         |
| `*.md`                 | 项目根目录中的Markdown文件       |
| `src/components/*.tsx` | 特定目录中的React组件 |

你可以指定多个模式,并使用大括号扩展在一个模式中匹配多个扩展名:

```markdown  theme={null}
---
paths:
  - "src/**/*.{ts,tsx}"
  - "lib/**/*.ts"
  - "tests/**/*.test.ts"
---

Share rules across projects with symlinks

使用符号链接跨项目共享规则

The
.claude/rules/
directory supports symlinks, so you can maintain a shared set of rules and link them into multiple projects. Symlinks are resolved and loaded normally, and circular symlinks are detected and handled gracefully.
This example links both a shared directory and an individual file:
bash
ln -s ~/shared-claude-rules .claude/rules/shared
ln -s ~/company-standards/security.md .claude/rules/security.md
.claude/rules/
目录支持符号链接,因此你可以维护一套共享规则,并将其链接到多个项目中。符号链接会被正常解析和加载,循环符号链接会被检测并妥善处理。
以下示例链接了一个共享目录和一个单独文件:
bash
ln -s ~/shared-claude-rules .claude/rules/shared
ln -s ~/company-standards/security.md .claude/rules/security.md

User-level rules

用户级规则

Personal rules in
~/.claude/rules/
apply to every project on your machine. Use them for preferences that aren't project-specific:
text
~/.claude/rules/
├── preferences.md    # Your personal coding preferences
└── workflows.md      # Your preferred workflows
User-level rules are loaded before project rules, giving project rules higher priority.
~/.claude/rules/
中的个人规则适用于你机器上的所有项目。用于非项目特定的偏好设置:
text
~/.claude/rules/
├── preferences.md    # 你的个人编码偏好
└── workflows.md      # 你偏好的工作流
用户级规则会在项目规则之前加载,因此项目规则具有更高优先级。