一、CLAUDE.md规则最佳实践
1.1 规则设计原则
规则数量控制:研究表明12条规则、200行以内是最佳配置:
python
class RuleOptimizer:
def __init__(self):
self.optimal_rule_count = (8, 15)
self.max_length = 200
def validate_rules(self, rules: list) -> dict:
count = len(rules)
total_length = sum(len(r) for r in rules)
if count < self.optimal_rule_count[0]:
return {"status": "warning", "message": "规则不足,约束不够"}
elif count > self.optimal_rule_count[1]:
return {"status": "warning", "message": "规则过多,执行率下降"}
elif total_length > self.max_length:
return {"status": "warning", "message": "规则太长,难以执行"}
else:
return {"status": "optimal", "message": "规则配置最佳"}
1.2 规则分类模板
markdown
# CLAUDE.md - 规则分类模板
## 禁止操作(绝对不要)
- 绝对不要重构、重命名或清理无关代码
- 绝对不要 force push,会覆盖共享历史
- 绝对不要修改 package-lock.json 或 pnpm-lock.yaml
## 架构约束(必须遵守)
- 所有数据库查询走 services/,不要写在组件里
- 状态管理只用 Zustand,不要混用其他库
- API调用必须通过 src/lib/api 封装
## 质量检查(改完必做)
- 每次改完代码运行 npx tsc --noEmit
- 每次改完跑测试,失败了先修好再继续
- 先跑 migration 再跑测试,顺序不能反
## 代码规范(风格统一)
- 提交前缀规范:feat:、fix:、docs:、refactor:、test:、chore:
- 绝对不用 enum,用字面量联合类型代替
- 使用 TypeScript strict 模式,禁止 any 类型
## 从错误中学到的
- 不要在 packages/ui 里装本该装在 apps/web 的包
- 不要把两种现有模式平均一下,选一种跟到底
- 不确定文件夹结构时,先查现有文件
1.3 规则更新流程
每次纠正Claude后,必须执行以下步骤:
bash
# 1. 在对话末尾添加
更新你的CLAUDE.md,这样你就不会再犯这个错了。
# 2. 定期审查规则
grep -E "^- " CLAUDE.md | wc -l # 检查数量
wc -l CLAUDE.md # 检查长度
# 3. 清理过时规则
# 删除不再适用的规则,保持规则库精简
二、钩子配置最佳实践
2.1 PostToolUse钩子配置
推荐配置:
json
{
"PostToolUse": [
{
"matcher": "Write(*.ts)",
"hooks": [
{ "type": "command", "command": "npx prettier --write $file" },
{ "type": "command", "command": "npx tsc --noEmit 2>&1 | head -20" }
]
},
{
"matcher": "Write(*.tsx)",
"hooks": [
{ "type": "command", "command": "npx prettier --write $file" },
{ "type": "command", "command": "npx eslint --fix $file" },
{ "type": "command", "command": "npx tsc --noEmit 2>&1 | head -20" }
]
},
{
"matcher": "Write(*.css)",
"hooks": [
{ "type": "command", "command": "npx stylelint --fix $file" }
]
},
{
"matcher": "Write(*.md)",
"hooks": [
{ "type": "command", "command": "npx markdownlint --fix $file" }
]
}
]
}
2.2 Stop钩子配置
关键注意事项 :必须检查stop_hook_active防止无限循环
json
{
"Stop": [
{
"hooks": [
{
"type": "command",
"command": "if [ \"$stop_hook_active\" = \"true\" ]; then exit 0; fi; npm test 2>&1 | tail -10; echo \"Exit: $?\""
}
]
}
]
}
高级配置(带Prompt验证):
json
{
"Stop": [
{
"hooks": [
{
"type": "command",
"command": "if [ \"$stop_hook_active\" = \"true\" ]; then exit 0; fi; npm test 2>&1 | tail -10; echo \"Exit: $?\""
},
{
"type": "prompt",
"prompt": "检查所有任务是否已完成。检查代码改动中是否有bug、遗漏的边界情况和测试覆盖。如果有未完成或有问题的地方,继续工作。如果一切正常,确认完成。"
}
]
}
]
}
2.3 PreToolUse钩子配置
安全拦截规则:
json
{
"PreToolUse": [
{
"matcher": "Bash(cat *log*)",
"hooks": [
{ "type": "command", "command": "grep -n 'ERROR\\|WARN' $file | head -50" }
]
},
{
"matcher": "Write(**/.env*)",
"hooks": [
{ "type": "command", "command": "echo 'BLOCKED: Cannot write to .env files' && exit 1" }
]
},
{
"matcher": "Bash(rm -rf *)",
"hooks": [
{ "type": "command", "command": "echo 'BLOCKED: rm -rf is not allowed' && exit 1" }
]
},
{
"matcher": "Bash(git push *)",
"hooks": [
{ "type": "command", "command": "echo 'BLOCKED: git push is not allowed' && exit 1" }
]
}
]
}
三、权限配置最佳实践
3.1 最小权限原则
json
{
"permissions": {
"allow": [
"Read", "Glob", "Grep", "LS",
"Edit", "MultiEdit",
"Write(src/**)", "Write(tests/**)", "Write(docs/**)",
"Bash(npm test *)", "Bash(npx tsc *)", "Bash(npx prettier *)",
"Bash(npx eslint *)", "Bash(git status)", "Bash(git diff)",
"Bash(git add *)", "Bash(git commit *)"
],
"deny": [
"Read(**/.env*)", "Write(**/.env*)",
"Read(**/secrets*)", "Write(**/secrets*)",
"Bash(rm -rf *)", "Bash(git push *)",
"Bash(sudo *)", "Bash(chmod *)"
],
"defaultMode": "acceptEdits"
}
}
3.2 权限配置策略
| 权限类型 | 配置原则 | 示例 |
|---|---|---|
| 读取 | 允许大部分文件 | Read, Glob, Grep |
| 写入 | 限制到特定目录 | Write(src/**), Write(tests/**) |
| 命令 | 允许安全命令 | npm test, npx tsc |
| 危险操作 | 明确拒绝 | rm -rf, git push |
| 敏感文件 | 完全禁止 | .env, secrets |
四、自动重试最佳实践
4.1 重试策略配置
修复这些失败的测试。最多尝试3次。
每次尝试之后:
1. 跑测试
2. 如果通过,完成
3. 如果失败,读错误信息,换一种思路
4. 如果3次都失败,说明你尝试了什么、还有什么没修好
不要尝试同一个修法两次。
4.2 重试次数设置
| 场景 | 建议重试次数 | 原因 |
|---|---|---|
| 简单功能 | 2-3次 | 快速修复 |
| 复杂功能 | 3-5次 | 需要多轮调试 |
| 测试不稳定 | 2次 | 避免浪费资源 |
| CI环境 | 3次 | 平衡效率与成功率 |
4.3 重试策略代码实现
python
class RetryStrategy:
def __init__(self, max_retries: int = 3):
self.max_retries = max_retries
self.attempts = 0
self.previous_approaches = []
def should_retry(self) -> bool:
return self.attempts < self.max_retries
def record_attempt(self, approach: str):
self.attempts += 1
self.previous_approaches.append(approach)
def get_suggestion(self) -> str:
if self.attempts == 0:
return "开始第一次尝试"
elif self.attempts < self.max_retries:
return f"第{self.attempts+1}次尝试,之前尝试过:{', '.join(self.previous_approaches)}"
else:
return f"已尝试{self.max_retries}次,停止重试"
五、跨会话记忆最佳实践
5.1 记忆管理策略
bash
# 添加记忆的时机
/memory add "这个项目用 pnpm,不是 npm"
/memory add "auth 模块在5月15日重构了,新模式在 src/lib/auth/v2/"
/memory add "数据库连接字符串在 secrets.json 中"
# 记忆分类
/memory add "[配置] 使用 pnpm 管理依赖"
/memory add "[架构] auth模块已重构到 src/lib/auth/v2"
/memory add "[安全] 数据库密码在 secrets.json"
5.2 Dreaming功能配置
bash
# 开启Dreaming
/dreaming enable
# 配置Dreaming参数
/dreaming config --min-sessions 10 # 最少分析会话数
/dreaming config --max-hours 24 # 最大回溯时间
# 检查Dreaming状态
/dreaming status
5.3 三层记忆组合策略
| 层级 | 内容类型 | 更新频率 | 维护方式 |
|---|---|---|---|
| CLAUDE.md | 项目级规则 | 每次错误后 | 手动添加 |
| /memory | 会话级学习 | 随时 | 手动/自动 |
| Dreaming | 后台分析 | 每晚 | 自动 |
六、常见陷阱与避坑指南
6.1 陷阱清单
| 陷阱 | 现象 | 原因 | 解决方案 |
|---|---|---|---|
| 无限循环 | Claude一直重复修复 | Stop钩子未检查stop_hook_active |
添加检查逻辑 |
| 钩子不生效 | 命令没有执行 | 配置格式错误 | 验证JSON格式 |
| 权限不足 | 命令无法执行 | 权限配置过严 | 调整allow列表 |
| 规则太多 | 执行率下降 | 超过15条规则 | 精简到8-15条 |
| 规则太复杂 | Claude理解困难 | 规则描述不清晰 | 使用简单明确的语言 |
| 测试不稳定 | 重试多次仍失败 | 测试本身有问题 | 先修复不稳定测试 |
6.2 调试技巧
bash
# 1. 检查配置文件格式
cat .claude/config.json | jq .
# 2. 检查Claude版本
claude --version
# 3. 测试钩子命令
npx prettier --write test.ts
npx tsc --noEmit
npm test
# 4. 检查权限配置
cat .claude/config.json | jq '.permissions'
# 5. 查看钩子执行日志
# 在Claude对话中观察钩子输出
6.3 性能优化
bash
# 1. 缓存优化
# 配置中添加缓存策略
{
"performance": {
"enable_cache": true,
"cache_ttl_minutes": 30,
"max_cache_size": 1000
}
}
# 2. 命令超时设置
{
"hooks": {
"PostToolUse": [
{
"matcher": "Write(*.ts)",
"hooks": [
{ "type": "command", "command": "timeout 30 npx tsc --noEmit" }
]
}
]
}
}
# 3. 并行执行
# 对于多个钩子动作,可以并行执行
七、团队协作最佳实践
7.1 配置共享策略
bash
# 创建团队配置仓库
mkdir team-claude-config
cd team-claude-config
# 添加配置文件
cp your-project/.claude/config.json .
cp your-project/.claude/CLAUDE.md .
# 创建README说明
cat > README.md << 'EOF'
# 团队Claude配置
## 使用方法
1. 克隆仓库
git clone https://github.com/your-team/claude-config.git ~/.claude/team-config
2. 复制配置
cp ~/.claude/team-config/* ~/.claude/
## 更新配置
git -C ~/.claude/team-config pull
cp ~/.claude/team-config/* ~/.claude/
EOF
# 推送到Git
git init
git add .
git commit -m "Initial team config"
git remote add origin https://github.com/your-team/claude-config.git
git push origin main
7.2 CI/CD集成
yaml
# .github/workflows/claude-check.yml
name: Claude Config Check
on: [pull_request]
jobs:
check-config:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Check config format
run: cat .claude/config.json | jq .
- name: Validate CLAUDE.md
run: |
RULE_COUNT=$(grep -E "^- " .claude/CLAUDE.md | wc -l)
echo "规则数量: $RULE_COUNT"
if [ $RULE_COUNT -gt 15 ]; then
echo "警告:规则数量超过15条"
exit 1
fi
八、企业级集成最佳实践
8.1 API聚合平台接入
python
from openai import OpenAI
# 企业级API客户端
client = OpenAI(
base_url="https://api.weelinking.com/v1",
api_key="YOUR_API_KEY"
)
# 获取企业级配置
response = client.chat.completions.create(
model="claude-3-opus",
messages=[
{"role": "user", "content": "根据以下企业规范生成CLAUDE.md规则:\n- 使用微服务架构\n- 遵循企业编码标准\n- 使用指定的技术栈"}
]
)
# 保存配置
with open('.claude/CLAUDE.md', 'w') as f:
f.write(response.choices[0].message.content)
8.2 配置监控
python
class ConfigMonitor:
def __init__(self):
self.alert_thresholds = {
'rule_count': 15,
'file_size': 200,
'execution_time': 30 # 秒
}
def check_config(self, config_path: str) -> list:
alerts = []
# 检查规则数量
with open(config_path, 'r') as f:
rules = f.read()
rule_count = len([line for line in rules.split('\n') if line.startswith('- ')])
if rule_count > self.alert_thresholds['rule_count']:
alerts.append(f"规则数量超过阈值: {rule_count} > {self.alert_thresholds['rule_count']}")
# 检查文件大小
file_size = len(rules.split('\n'))
if file_size > self.alert_thresholds['file_size']:
alerts.append(f"文件大小超过阈值: {file_size} > {self.alert_thresholds['file_size']}")
return alerts
九、配置前后对比
9.1 配置前
• Claude写代码,你跑测试,4个失败
• 你逐一解释每个失败
• Claude修了3个,顺带又引入1个新bug
• 你再次解释
• 每个功能来回45分钟
• 同样的错误明天还会出现
9.2 配置后
• Claude写代码,钩子自动格式化并检查每个文件
• Claude说完成,测试自动跑
• 测试失败,Claude读错误继续修
• CLAUDE.md阻止昨天的错误重演
• 记忆系统阻止上周的错误重演
• 每个功能10分钟,大部分时间不需要盯着
十、总结
掌握这些最佳实践,可以让Claude的自动修复能力发挥到极致:
| 实践领域 | 关键要点 |
|---|---|
| 规则设计 | 8-15条规则,200行以内 |
| 钩子配置 | 必须检查stop_hook_active |
| 权限控制 | 最小权限原则 |
| 重试策略 | 3次重试上限 |
| 记忆管理 | 三层记忆组合 |
| 团队协作 | 共享配置仓库 |
这套机制的核心价值在于将开发者从重复的错误解释中解放出来,让AI真正学会从错误中学习。
#ClaudeCode #自动修复 #最佳实践 #开发效率
📖 推荐阅读
如果这篇对你有帮助,以下文章你也会喜欢: