S1哥 今日赠品 · 2026-11-01
配套教程:待补
来源:Anthropic 官方文档《Best practices for Claude Code》后半部分。配置示例照官方原样,带“模板”的是 S1哥 按官方思路整理,把 <> 里换成你自己的。
一、什么规矩该写成钩子或禁止规则(官方原则)
CLAUDE.md 是指南,Claude 可以判断某条这次不适用。每次都必须发生的事,做成 hook、deny 规则或托管设置。
钩子只用于零例外的规矩;“优先用具名导出”这类例外很多的,留在 CLAUDE.md。
二、改完文件自动格式化(官方示例,放 .claude/settings.json)
{
"hooks": {
"PostToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{ "type": "command", "command": "npx prettier --write --ignore-unknown \"$(jq -r '.tool_input.file_path')\"" }
]
}
]
}
}
验证:让 Claude 往 Prettier 管的文件里加一行缩进错误的代码,保存后应被自动改正。
三、不许读密钥文件(官方示例)
{
"permissions": {
"allow": ["Bash(pnpm tsc --noEmit)"],
"ask": ["Bash(git push *)"],
"deny": ["Read(./.env)", "Read(./.env.local)", "Read(./secrets/**)"]
}
}
验证:问 Claude .env 里有什么,用 Read 和 cat .env 都应失败。
边界:拦不住自己打开文件的脚本;WebFetch 的域名禁止规则管不到 curl,除非开了沙盒。
四、让它自己写拦截钩子(官方说法)
write a hook that blocks edits to the migrations folder
写完用 /hooks 查看结果。要真强制,用 command 或 http 钩子,并加 onFailure 为 block。
五、沙盒
会话里输入 /sandbox;安全相关的事,禁止规则和沙盒两个都要。严格沙盒模式在 /sandbox 的 Overrides 标签里。
六、只读审阅者子代理(官方示例,放 .claude/agents/reviewer.md)
---
name: reviewer
description: Reviews changed files against the spec they were built from. Use after implementing a feature, before opening the PR.
tools: Read, Grep, Glob
---
You're reviewing code you didn't write. Compare the changed files against the spec you're given,
check that every requirement is implemented and the listed edge cases have tests,
and report only the gaps that affect correctness. Skip style.
用法:have the reviewer compare the rate limiter against SPEC.md
七、无人值守前的五问(官方)
1. 它知道什么叫做完吗?(目标条件、规格文件、必须变绿的失败测试)
2. 它能检查自己的工作吗?(测试、Stop 钩子、审阅步骤)
3. 它被允许碰什么?(权限规则、dontAsk、沙盒、worktree、唯一能推的分支)
4. 什么会让它停下?(--max-turns、--max-budget-usd、花费上限)
5. 结果去哪里、谁签字?(PR、评论、摘要,再由人批准合并或部署)
八、脚本里跑(官方示例)
for file in $(cat files.txt); do
claude --bare -p "Migrate $file to the new logger API and commit. Reply OK or FAIL." \
--allowedTools "Read,Edit,Bash(git add *),Bash(git commit *)" \
--permission-mode dontAsk \
--max-turns 20
done
先拿三个文件试,再跑剩下的。
九、省钱和跑偏急救
/usage 看钱花在哪;不相关的任务之间 /clear;/compact keep the API changes and the test commands
跑偏按 Esc;/rewind 回滚;纠正两次还不对就 /clear 重写提示词