用ClaudeCode从0搭建一个优雅的CR助手 - claude_12

CR助手当真实场景,从空仓库开始把 CLAUDE.md / rule / skill / agent / command / hook / MCP 逐个堆上去,最后是一个能跑的最小系统。

写到这一篇,前 11 篇讲的东西全都是拆开的零碎知识------Command 长什么样、Skill 怎么组织、Subagent 怎么和 hook 联动、MCP 怎么接、memory 怎么分层......每一篇都是一个独立视角。

但真动起手来之前,所有人都会面对同一个问题------

"这些东西我都看懂了,但我自己的项目要怎么从零配起来?"

这一篇不讲新概念,也不讲新字段。就老老实实演一遍------挑一个真实的使用场景 ,从空仓库开始,一步一步把前 11 篇的东西落到一个能跑的最小系统里。

挑的场景是:Code Review Copilot。每天我改完代码提 PR 之前,让 Claude 按我团队的规范做一次 review------挑格式问题、指出可读性问题、查重复代码。


目录概要

  1. 为什么挑"Code Review Copilot"这个例子
  2. 从零规划------这东西到底要由几个零件组成
  3. Step 1:写一个 CLAUDE.md(员工入职文档)
  4. Step 2:加一个 rule 文件(Glob 驱动的章节手册)
  5. Step 3:一个 review skill(核心工具)
  6. Step 4:一个 reviewer agent(隔离的专业员工)
  7. Step 5:一个 /review command(入口按钮)
  8. Step 6:挂 hook 做通知
  9. Step 7:接一个 MCP 查外部规范
  10. 跑一遍 + 踩到的坑
  11. 小结 + 对你自己项目的迁移建议

一、为什么挑这个例子

先讲清楚选型。挑"Code Review Copilot"有几个理由------

理由 1:真需求。前面 03 篇的 release-notes 生成器已经贴近实战,time 那三份是教学用例------但 release-notes 终归是每版本跑一次的低频活。Code review 是绝大多数工程师每天都做、每次做都烦的事,频次和真实度都更高一档。

理由 2:能用上所有零件 。这个例子刚好能同时用到 Command(/review 入口)、Agent(独立 context 的 reviewer)、Skill(具体的检查规则)、Hook(review 完触发通知)、MCP(查外部 style guide)、Memory(项目约定)------一个例子串起整条链

理由 3:边界清楚。任务不需要真改代码,只需要"读+评论"------降低副作用风险,更适合演示。


二、规划------几个零件怎么配合

动手之前先画图。这比"想到哪写到哪"稳得多:

graph TB U[用户敲 /review] --> C[review Command] C --> QC[问用户:review 哪个范围?
e.g. HEAD~1、PR 分支] QC --> AG[reviewer Agent
独立 context、只读工具] subgraph AgentScope[Reviewer Agent 上下文] AG --> SK1[预加载 code-review-checklist Skill] AG --> RC[读被 review 的代码] AG --> G[Grep 相关模式] AG --> MCP[context7 MCP
查最新规范] end AG --> OUT[返回结构化 review 报告] OUT --> RP[review.md 文件] subgraph Hooks[Hook 触发] RP --> H1[PostToolUse: 写 review.md 后
播放完成提示音] OUT --> H2[Stop: agent 结束时
播放提示音] end style C fill:#afa style AG fill:#ff9 style SK1 fill:#aaf style MCP fill:#fcc

几条设计原则(这些是从前 11 篇反复强调的)------

  1. Command 做入口,只负责问用户"要 review 什么",不做任何 review 逻辑
  2. Agent 做隔离工作,review 涉及大量代码阅读,独立 context 防污染主会话
  3. Skill 做知识,review 的 checklist 放 skill 里,预加载到 agent
  4. MCP 做外部查询,查最新的 TypeScript / Python style guide
  5. Hook 做通知,review 写完了响一下声音、上报 Slack

三、Step 1:写 CLAUDE.md

员工入职第一天要读的文档。对这个场景里的 Claude,关键知识是------

项目用什么语言?什么框架? 代码风格约定是什么? 测试覆盖要求? 特别要避免什么?

写一个极简版:

markdown 复制代码
# CLAUDE.md

This is a TypeScript Node.js project using:
- Framework: Fastify v4
- Testing: Vitest (tests in `__tests__/` next to source)
- Lint: ESLint + Prettier
- Commit: Conventional commits (feat/fix/docs/chore)

## Code Review Rules

When reviewing code, flag these as errors (not warnings):

1. Any `any` type (strict mode is on)
2. Missing error handling in async functions
3. Console.log left in source (outside test files)
4. Hardcoded secrets or API keys
5. Imports from deprecated modules (see `docs/deprecated.md`)

## Code Review Style

- Be specific: cite line numbers
- Be actionable: suggest fixes, don't just criticize
- Be proportionate: don't nitpick style when there are bugs
- Group findings: group by severity (critical > major > minor)

## Git Commit Rules

One file per commit. Separate commits for code vs. docs vs. config.

遵守前几篇的原则------

  • 200 行以内(这份连 50 行都不到)
  • 做什么比不做什么清晰
  • 具体规则带例子
  • 列出 severity 分级(让 agent 有结构化参考)

四、Step 2:加一个 rule 文件

CLAUDE.md 是"一上来就念的"------适合全局性的规则。但有些规则只在改特定文件时才需要。

比如"migration 文件不能删列,只能加 "------这条只在读/写 migrations/** 时才相关。

.claude/rules/migrations.md

markdown 复制代码
# Glob: migrations/**

## Migration Safety Rules

- Migrations are append-only: NEVER drop columns, tables, or indexes in a migration
- Always add with a default value for NOT NULL columns
- Always test migrations on a copy of production data before approving

## When reviewing migrations

Flag these immediately:
- Any DROP statement
- NOT NULL without DEFAULT
- Rename operations (should be add-new + backfill + deprecate-old)

只有当 Claude 读到 migrations/ 下的文件时,这份 rule 才会被注入上下文------其他时候它不占 context。

这就是 08 篇讲的 Glob 驱动 rules 的典型用法。


五、Step 3:review skill

这是整个系统的核心知识载体

创建 .claude/skills/code-review-checklist/SKILL.md

markdown 复制代码
---
name: code-review-checklist
description: Review code changes against the team's standards. Invoke
  this skill when asked to review a PR, diff, or file changes. Follows
  a structured checklist covering correctness, security, performance,
  and style.
allowed-tools: Read, Grep, Glob
---

# Code Review Checklist

## Step 1: Classify the change

First, determine what kind of change this is:
- Feature: new functionality
- Bugfix: correcting existing behavior
- Refactor: restructuring without behavior change
- Chore: config, docs, deps

Different types get different review weights.

## Step 2: Walk the checklist

For each changed file, check:

### Correctness (Critical)
- [ ] Does the code do what the PR description says?
- [ ] Are all error paths handled?
- [ ] Are all async functions awaited?
- [ ] Any off-by-one, boundary conditions?

### Security (Critical)
- [ ] No hardcoded secrets, tokens, or keys
- [ ] All user input validated before use
- [ ] No SQL concatenation (use parameterized queries)
- [ ] No `eval`, `Function()`, or `innerHTML` with user input

### Performance (Major)
- [ ] N+1 queries avoided (batch / eager load)
- [ ] No sync I/O in hot paths
- [ ] Loops don't hide O(n²) or worse

### Style (Minor)
- [ ] Naming is consistent with project conventions
- [ ] No dead code, commented-out blocks
- [ ] Comments explain "why" not "what"

## Step 3: Write the report

Use this structure:

---
## Critical
<issues blocking merge>

## Major
<issues that should be fixed before merge>

## Minor
<style / preference suggestions>

## Positive
<things done well>
---

Include: file path, line range, the problem, and a suggested fix.

设计要点------

  • 明确的 description:Claude 要能自动匹配"review" 意图
  • 结构化 checklist:分 severity 让 agent 有章法
  • allowed-tools 限制 :只给 Read / Grep / Glob------review 不应该能改代码
  • 输出模板:固定报告格式,方便后续自动化处理

六、Step 4:reviewer agent

skill 有了,但我们不希望 review 这件事污染主会话的 context------一个 PR 可能有几十个文件上千行代码,全塞主会话直接爆。

所以包一层 agent------独立 context 去读代码,返回精简 summary。

.claude/agents/pr-reviewer.md

yaml 复制代码
---
name: pr-reviewer
description: Reviews a git diff or pull request. Use this agent PROACTIVELY
  when the user asks for a code review, PR review, or diff review.
tools: Read, Grep, Glob, Bash(git *)
model: sonnet
skills:
  - code-review-checklist
memory: project
permissionMode: plan
color: yellow
---

You are a senior code reviewer for this TypeScript project.

When invoked:

1. If given a git ref (e.g., "HEAD~1", "main..feature/x"), run
   `git diff <ref>` to get the changes.
2. If given a list of files, read them directly.
3. Follow the `code-review-checklist` skill step-by-step.
4. Write the report to `review.md` in the current directory.
5. Return a 3-sentence summary to the caller.

Never modify any code. Review only.

几个关键设计选择------

  • tools 限制 :只给 Read / Grep / Glob / git * Bash------没有 Edit、Write
  • permissionMode: plan:更严格的权限模式,无法 edit,保险双重
  • memory: project:让这个 agent 记住项目的历史 review 决策------下次遇到类似问题不用重新解释
  • skills: [code-review-checklist]:预加载,agent 随身带着规范
  • description 带 PROACTIVELY:让 Claude 在检测到"review" 意图时自动触发这个 agent

七、Step 5:/review command

现在把入口做出来。.claude/commands/review.md

markdown 复制代码
---
description: Run a code review against the current diff
argument-hint: [<git-ref-or-file-paths>]
allowed-tools: Agent(pr-reviewer), Read
model: haiku
---

You are orchestrating a code review.

Step 1: Parse $ARGUMENTS
- If empty, default to `git diff HEAD`
- If looks like a git ref (HEAD~n, branch names), use `git diff <ref>`
- If looks like file paths, pass the list directly

Step 2: Invoke the reviewer
Agent(subagent_type="pr-reviewer",
      description="Review the specified diff/files",
      prompt=<the parsed argument>)

Step 3: After the agent returns, read `review.md` and present:
- A 3-sentence summary
- The full report in a collapsible block

使用方式

bash 复制代码
/review              # 默认 review 当前 diff
/review HEAD~1       # review 上一个 commit
/review src/**/*.ts  # review 指定文件

command 的工作只有 orchestrate------解析参数、派 agent、读结果、展示。没有 review 逻辑。

Model 选 haiku:orchestration 任务不需要大模型,haiku 足够、快、省 token。


八、Step 6:挂 hook

review 完成要有反馈------响个声音、或者推送到 Slack。

.claude/settings.json 里加:

json 复制代码
{
  "hooks": {
    "PostToolUse": [{
      "matcher": "Write",
      "hooks": [{
        "type": "command",
        "command": "python3 ${CLAUDE_PROJECT_DIR}/.claude/hooks/review-done.py",
        "timeout": 3000,
        "async": true,
        "if": "Write(review.md)"
      }]
    }]
  }
}

设计点------

  • matcher: "Write":只关心 Write 操作
  • if: "Write(review.md)":只在写 review.md 时触发(07 篇讲过的 if 条件)
  • async: true:不阻塞主流程
  • timeout: 3000:3 秒内必须跑完

review-done.py 做什么随你------播放声音、curl 推 Slack、发桌面通知。

8.1 加一个 agent 级 hook

reviewer 结束时也想响一下声?在 agent frontmatter 里加:

yaml 复制代码
---
name: pr-reviewer
...
hooks:
  Stop:
    - type: command
      command: python3 ${CLAUDE_PROJECT_DIR}/.claude/hooks/reviewer-done.py
      timeout: 2000
      async: true
      statusMessage: "Review complete"
---

这个 hook 只在 pr-reviewer 跑完时触发 ,不影响其他 agent。记住 07 篇讲的------agent frontmatter 的 Stop 实际收到的 hook_event_nameSubagentStop,脚本要兼容。


九、Step 7:接一个 MCP

最后加一点外部查询能力。如果 reviewer 不确定"某个新版 TypeScript feature 到底有没有 stable"------可以查 Context7。

.mcp.json

json 复制代码
{
  "mcpServers": {
    "context7": {
      "command": "npx",
      "args": ["-y", "@upstash/context7-mcp"]
    }
  }
}

然后 .claude/agents/pr-reviewer.md 里加:

yaml 复制代码
mcpServers:
  - context7

这样 reviewer 在 review 时就能自己调 mcp__context7__* 系列工具,查最新 TypeScript / Fastify / Vitest 官方文档。

注意权限------settings.json 里要 allow:

json 复制代码
"permissions": {
  "allow": [
    "mcp__context7__*"
  ]
}

十、跑一遍

全配完,来做个 smoke test:

shell 复制代码
# 在项目里改两行代码,不提交
$ vim src/api.ts
# 加一行 console.log('debug')

# 跑 review
> /review

Claude 会:

  1. command 解析无参数,默认 git diff HEAD
  2. 派 pr-reviewer agent
  3. agent 预加载 code-review-checklist skill
  4. agent 跑 git diff HEAD,拿到 diff
  5. agent 按 checklist 逐条走------检测到 console.log ,命中 checklist 里的"console.log left in source"
  6. agent 写 review.md
  7. PostToolUse hook 触发,播放完成提示音
  8. agent 返回主会话一段 3 句话的 summary
  9. command 读 review.md,展示报告

整个链条跑通了------Command + Agent + Skill + Hook + Memory + MCP + Permission,7 个零件全用上。

10.1 踩过的坑

实践这个 demo 时踩到了几个坑,记下来:

坑 1 :agent 预加载 skill 之后,Claude 有时会"忘记"skill 的存在------尤其是 context 被 diff 撑大之后。解决:在 agent 的 prompt 里显式提"follow the checklist"------强制它去看那段 preload 的内容。

坑 2allowed-tools: Agent(pr-reviewer), Read 里,一开始写成 Agent("pr-reviewer")------引号让解析失败。正确写法是不带引号

坑 3 :hook 的 if 条件没生效------原因是我写成 "if": "PostToolUse(Write(review.md))"------if 只接受权限规则语法 ,不是 hook 事件 + matcher 组合。正确:"if": "Write(review.md)"

坑 4 :pr-reviewer 的 memory 一开始设的 memory: user------结果我的所有项目都共享了"上次 review 的结果"。改成 memory: project 后正常了。08 篇讲过这个。

坑 5 :Context7 MCP 第一次启动要装 npm 包,导致 agent 第一次跑超时。解决:在项目 onboarding 文档里加一步 npx -y @upstash/context7-mcp --install-only 预热。


十一、小结 + 对你自己项目的迁移建议

这个 demo 里最重要的不是"review 做得多好 ",而是这套架构每个零件都做了它最擅长的事

零件 做了什么 为什么
CLAUDE.md 基础规则 每次都要用的知识
rules/migrations.md 专题规则 只在特定文件触发
skill checklist + 报告模板 可被预加载,可被多处复用
agent 隔离 context 执行 读大量代码不污染主会话
command 用户入口 + orchestration 让人能一键启动
hook 完成通知 关键时刻的反馈
MCP 外部文档查询 防止过期知识导致误判

迁移到你自己项目的步骤------

  1. 先写 CLAUDE.md(15 分钟)------把项目的基本约定列出来
  2. 挑一个重复率最高的任务------不是 review,也可以是 "写测试"、"生成 migration"、"更新 changelog"
  3. 按顺序做:skill → agent → command → hook → MCP(按需)
  4. 跑通最小版本再加料。不要一开始就堆 feature
  5. .claude/ 目录提交到 git------让团队都能用

一条核心的心智纪律

从 "让它能跑 " 开始,不从 "设计完美" 开始。跑起来之后踩坑、改、再跑------这才是真正学会 Claude Code 的路径。


这套系列的终点

这是 12 篇系列的最后一篇。从 01 的概念速览开始,到 12 的亲手搭建------Claude Code 的内部机械和外部接口都摸过一遍了

读到这里,你该能回答这些问题:

  • 为什么要拆成 Command / Skill / Subagent 三种?
  • 一个任务该写成 skill 还是 agent?
  • agent 的 memory 跟 CLAUDE.md 有什么区别?
  • hook 和 permission 什么时候该用哪个?
  • MCP 解决了什么问题?为什么不能直接写 plugin?
  • 多层编排(command → agent → skill)的数据流怎么设计?
  • Claude Code 的优先级系统(managed > CLI > local > project > user)怎么玩?

如果上面这些问题你能用自己的话讲出来------那这 12 篇就没白写。

剩下的只是练习 。挑一个项目,把这套模板迁过去、跑坏几次、修回来、再跑坏------半年之后你会发现:Claude Code 已经变成你日常工作流里默认的一环,不再是一个新鲜玩具

这是我写这套系列最想达到的效果------不是教你"用 Claude Code",是让 Claude Code 自然长进你的工作里


参考资料

本篇没有新的 sources。所有字段、机制、配置示例都来自前 11 篇的原始资料。

外部链接

相关推荐
该用户已不存在2 小时前
用 Claude Code Agents 与 CI/CD 搭建自动化研发团队(Part 3)
后端·ai编程·claude
皮皮学姐分享-ppx2 小时前
上市公司数字技术风险暴露数据(2010-2024)|《经济研究》同款大模型测算
大数据·网络·数据库·人工智能·chatgpt·制造
Jay-r2 小时前
ChatGPT 官网入口(2026 年最新版)——简明指南
人工智能·语言模型·chatgpt·ai助手·chatgpt5.5
DigitalOcean3 小时前
AI 成本太高怎么办?用推理路由自动分配 Claude、Qwen、DeepSeek
agent·claude·deepseek
m0_535817553 小时前
Claude Code国内直连教程:从0到1安装配置(附API中转方案,亲测跑通)
windows·gpt·ai·api·claude·claudecode·88api
一点一木3 小时前
2026 终端 AI 编码 Agent 六大工具深度横评
前端·人工智能·claude
云天AI实战派4 小时前
ChatGPT/API 调用故障排查指南:Realtime 音频、智能体浏览器操作与 AI 编码代理全流程修复手册
人工智能·chatgpt·音视频
常威正在打来福4 小时前
【omc】Claude Code 必备神器:Oh-My-ClaudeCode 让你的 AI 编程效率翻倍
aigc·ai编程·claude
Jamie笔记5 小时前
认识 Claude Code:你的终端 AI 编程助手——从入门到高效使用
claude