本教程面向有一定Claude Code使用经验、想将日常重复操作封装为可复用Skill的开发者。通过一个真实的代码审查场景,演示Skill从原始Prompt到生产级完整交付物的五个演进阶段。学完后,你将掌握渐进披露设计、上下文隔离、工具权限控制和Skill质量验证的核心技法。
适用人群:已安装Claude Code、有基本命令行经验的开发者。预计学习时长90分钟。
| 条件 | 说明 |
|---|---|
| Claude Code | 已安装v1.0.28+版本(claude --version 验证) |
| 终端环境 | macOS / Linux / WSL2 |
| Node.js | v18+(部分Skill依赖) |
| Git | 用于版本管理演示 |
| 基础知识 | 了解YAML语法、Markdown写作 |
很多开发者拿到一个需求后,直接动手写SKILL.md,结果往往遇到三类问题:
正确的做法是渐进式演进:先用Prompt验证思路,再逐步结构化为可复用的Skill。这就像TDD——先写测试再写代码,而不是一上来就写实现。
flowchart LR
A["Step 1<br/>原始Prompt"] --> B["Step 2<br/>CLAUDE.md指令"]
B --> C["Step 3<br/>基础SKILL.md"]
C --> D["Step 4<br/>渐进披露优化"]
D --> E["Step 5<br/>生产级交付"]
style A fill:#f9e2ae,stroke:#d4a017
style B fill:#a8d8ea,stroke:#4a90a4
style C fill:#c3e6cb,stroke:#28a745
style D fill:#d4b8f0,stroke:#7b2d8e
style E fill:#f5c6aa,stroke:#d35400
我们的目标是构建一个自动化代码审查Skill,它能: - 分析Git diff输出 - 识别潜在的安全漏洞、性能问题和代码异味 - 生成结构化的审查报告 - 给出具体的修复建议
这个场景具有典型的Skill价值:重复执行、需要专业知识、有明确的输入输出。
在构建任何Skill之前,先用原始Prompt验证你的想法是否可行。这一步的成本最低——如果Claude无法完成你的Prompt描述的任务,封装成Skill也不会有本质改善。
# 在你的项目中启动Claude Code
claude
输入以下Prompt:
请对当前项目的最近一次commit进行代码审查。要求:
1. 运行 git diff HEAD~1 HEAD 获取变更内容
2. 从安全漏洞、性能问题、代码异味三个维度分析
3. 每个问题标注严重程度(Critical/Warning/Info)
4. 给出具体的修复建议和代码示例
5. 输出Markdown格式的审查报告
Claude会执行git diff命令,分析代码变更,并输出类似这样的报告:
## 代码审查报告
### Commit: abc1234 - feat: add user authentication
#### Critical
- **SQL注入风险** (`src/auth/login.ts:42`)
- 直接拼接用户输入到SQL查询
- 修复:使用参数化查询
#### Warning
- **密码未加盐** (`src/auth/hash.ts:15`)
- 使用裸SHA-256
- 修复:使用bcrypt,cost factor >= 12
#### Info
- **缺少输入验证** (`src/auth/register.ts:28`)
- email字段未验证格式
| 问题 | 原因 | 解决方案 |
|---|---|---|
| Claude拒绝执行git命令 | 沙箱限制 | 在项目根目录启动,或使用--allowedTools |
| 输出格式不稳定 | Prompt不够具体 | 增加示例输出 |
| 分析深度不够 | 没有明确审查维度 | 列出具体的检查清单 |
Step 1核心判断:如果这个Prompt的效果已经很好,说明思路可行,继续演进。如果效果很差,需要先优化Prompt再继续。
当你在Step 1验证了Prompt有效后,下一步是将其固化到项目的CLAUDE.md中。这样每次在该项目中对话时,Claude都会自动遵循这个指令。
# 在项目根目录创建或编辑 .claude/CLAUDE.md
mkdir -p .claude
在.claude/CLAUDE.md中添加:
# 项目代码审查规范
当被要求进行代码审查时,遵循以下流程:
## 审查维度
| 维度 | 检查项 |
|------|--------|
| 安全 | SQL注入、XSS、认证绕过、敏感数据泄露 |
| 性能 | N+1查询、内存泄漏、不必要的同步操作 |
| 代码质量 | 命名规范、函数复杂度、重复代码 |
## 输出格式
每个问题必须包含:
- 文件路径和行号
- 严重程度标签:🔴 Critical / 🟡 Warning / 🔵 Info
- 问题描述(一句话)
- 修复建议(附代码示例)
为什么放在CLAUDE.md而不是直接跳到Skill?
| 问题 | 解决方案 |
|---|---|
| CLAUDE.md太长,影响token | 只放核心规则,详细内容留给Skill |
| 多项目共享规则 | 放在~/.claude/CLAUDE.md全局生效 |
| 规则被忽略 | 用明确的触发词:"当被要求进行代码审查时" |
现在进入核心环节:将审查能力封装为独立的Skill。
mkdir -p ~/.claude/skills/code-reviewer
创建 ~/.claude/skills/code-reviewer/SKILL.md:
---
name: code-reviewer
description: Use when the user asks for code review, asks to review a PR, or says "review my code". Analyzes git diffs for security vulnerabilities, performance issues, and code smells with structured reports.
---
# Code Review Skill
You are a senior security-aware code reviewer. When invoked, follow this workflow:
## Step 1: Gather Changes
Run the appropriate git command based on what the user specifies:
- `git diff HEAD~1 HEAD` — review last commit
- `git diff main...HEAD` — review all changes vs main branch
- `git diff --staged` — review staged changes
- `git diff <file>` — review specific file changes
If the user doesn't specify, default to reviewing staged changes.
## Step 2: Analyze
For each changed file, check these dimensions:
### Security
- SQL injection, XSS, CSRF vulnerabilities
- Hardcoded secrets or credentials
- Insecure authentication/authorization patterns
- Sensitive data exposure
### Performance
- N+1 database queries
- Memory leaks (unbounded collections, missing cleanup)
- Synchronous operations that should be async
- Unnecessary re-renders or computations
### Code Quality
- Function complexity (cyclomatic > 10)
- Code duplication
- Poor naming conventions
- Missing error handling
## Step 3: Output Report
Format as follows:
## Code Review Report
### Summary
- Files changed: N
- Issues found: X Critical, Y Warning, Z Info
### Critical Issues 🔴
> **[file.ts:L42]** Issue description
>
> **Fix:** ```lang
> // corrected code
> ```
### Warnings 🟡
> ...
### Info 🔵
> ...
### Positive Observations ✅
> Note good patterns found in the code.
# 重新启动Claude Code,测试触发
claude
输入:帮我审查一下最近的代码变更
预期行为:Claude应该自动识别并加载code-reviewer Skill,按照SKILL.md中定义的流程执行。
| 问题 | 原因 | 解决方案 |
|---|---|---|
| Skill未被触发 | description写得太窄 | 加更多触发短语:review、审查、检查代码 |
| 输出格式不对 | Markdown正文指令不够具体 | 增加完整的输出模板 |
| Skill加载了但没执行 | 缺少明确的"follow this workflow"指令 | 在正文开头写明"You are..."角色定义 |
---
name: code-reviewer # Skill标识,kebab-case命名
description: Use when... # 触发条件描述,最重要!决定Claude何时调用此Skill
---
description是整个Skill最重要的字段。Claude用它判断"什么时候该用这个Skill"。写法原则:
基础Skill能用,但存在一个问题:每次触发都加载全部内容。如果你的审查规则有几百行,这就浪费了大量token。
渐进披露(Progressive Disclosure)的核心思想是:只加载当前需要的层级内容。
flowchart TB
subgraph "Layer 1: 始终加载"
A["frontmatter<br/>name + description<br/>~50 tokens"]
end
subgraph "Layer 2: 触发后加载"
B["SKILL.md正文<br/>工作流定义<br/>~300 tokens"]
end
subgraph "Layer 3: 执行时加载"
C["辅助文件<br/>详细规则/模板<br/>~1000 tokens"]
end
A -->|"Claude判断需要此Skill"| B
B -->|"执行具体步骤时"| C
style A fill:#f9e2ae,stroke:#d4a017
style B fill:#c3e6cb,stroke:#28a745
style C fill:#d4b8f0,stroke:#7b2d8e
# 重新组织目录结构
mkdir -p ~/.claude/skills/code-reviewer
更新 SKILL.md(精简为流程骨架):
---
name: code-reviewer
description: Use when the user asks for code review, asks to review a PR, or says "review my code". Analyzes git diffs for security vulnerabilities, performance issues, and code smells with structured reports.
---
# Code Review Skill
You are a senior security-aware code reviewer.
## Workflow
1. Run `cat rules/checklist.md` to load the full review checklist
2. Determine the appropriate git diff command based on user input
3. Execute the diff and analyze each change against the checklist
4. Run `cat templates/report-template.md` to load the report format
5. Generate the structured report following the template
## Quick Reference
If user says "review last commit" → `git diff HEAD~1 HEAD`
If user says "review PR" → `git diff main...HEAD`
If user says "review staged" → `git diff --staged`
Default (no specification) → `git diff --staged`
创建 rules/checklist.md(详细规则,按需加载):
# Code Review Checklist
## Security Checks
- [ ] SQL injection: parameterized queries used?
- [ ] XSS: output encoding applied?
- [ ] CSRF: anti-forgery tokens present?
- [ ] Auth: proper authentication checks?
- [ ] Secrets: no hardcoded credentials/API keys?
- [ ] Input validation: all user inputs validated?
- [ ] Error handling: no sensitive data in error messages?
## Performance Checks
- [ ] Database: no N+1 queries?
- [ ] Memory: no unbounded collections?
- [ ] Async: I/O operations properly async?
- [ ] Caching: frequently accessed data cached?
- [ ] Indexing: database indexes for common queries?
## Code Quality Checks
- [ ] Complexity: cyclomatic complexity < 10?
- [ ] Duplication: DRY principle followed?
- [ ] Naming: clear and consistent naming?
- [ ] Error handling: all edge cases covered?
- [ ] Tests: changes covered by tests?
- [ ] Documentation: public APIs documented?
创建 templates/report-template.md(报告模板,按需加载):
# Code Review Report
## Summary
- **Scope**: [what was reviewed]
- **Files Changed**: N files
- **Issues Found**: X 🔴 Critical | Y 🟡 Warning | Z 🔵 Info
---
## 🔴 Critical Issues
### 1. [Issue Title]
- **Location**: `file.ts:L42`
- **Category**: Security / Performance / Quality
- **Description**: [what's wrong]
- **Impact**: [what could happen]
- **Fix**:
```lang
// corrected code here
[Same format as Critical]
[Same format, lower priority]
### 最终目录结构
~/.claude/skills/code-reviewer/ ├── SKILL.md # 入口:流程骨架 + frontmatter ├── rules/ │ └── checklist.md # Layer 3: 详细审查清单 └── templates/ └── report-template.md # Layer 3: 报告格式模板
### Token节省对比
| 阶段 | 加载内容 | 估算Token |
|------|----------|-----------|
| Step 3(无分层) | 全部内容一次性加载 | ~800 tokens |
| Step 4(三层) | Layer 1: ~50, Layer 2: ~200, Layer 3: ~550 | ~350 tokens(平均) |
节省约56%的token消耗,且随着规则复杂度增长,节省比例会更高。
---
## Step 5:生产级交付——安全、隔离与可维护性
到Step 4为止,你的Skill已经可以日常使用了。但如果要分享给团队或发布到社区,还需要考虑三个生产级问题。
### 5.1 工具权限控制
默认情况下,Skill可以使用Claude的所有工具。对于代码审查Skill,我们只需要Git命令和文件读取,不需要写入或执行任意命令。
更新SKILL.md的frontmatter:
```yaml
---
name: code-reviewer
description: Use when the user asks for code review, asks to review a PR, or says "review my code". Analyzes git diffs for security vulnerabilities, performance issues, and code smells with structured reports.
model: sonnet
allowed-tools:
- Bash(git diff*)
- Bash(git log*)
- Bash(git show*)
- Read
- Grep
- Glob
---
关键字段说明:
| 字段 | 值 | 作用 |
|---|---|---|
model |
sonnet |
审查任务不需要Opus的推理能力,Sonnet足够且更快 |
allowed-tools |
Bash(git diff*) |
只允许执行git diff相关命令,禁止rm、curl等 |
allowed-tools |
Read |
允许读取文件内容进行深度分析 |
当Skill执行复杂分析时,会产生大量中间输出(git diff内容、分析过程等),这些会污染主会话的上下文窗口。使用context: fork让Skill在子Agent中运行:
---
name: code-reviewer
description: Use when the user asks for code review, asks to review a PR, or says "review my code". Analyzes git diffs for security vulnerabilities, performance issues, and code smells with structured reports.
model: sonnet
context: fork
allowed-tools:
- Bash(git diff*)
- Bash(git log*)
- Bash(git show*)
- Read
- Grep
- Glob
---
context: fork的效果:
sequenceDiagram
participant U as 用户
participant M as 主Agent
participant S as 子Agent(Fork)
participant G as Git
U->>M: 审查我的代码
M->>S: Fork上下文, 加载Skill
S->>G: git diff HEAD~1 HEAD
G-->>S: 返回diff内容
S->>S: 分析安全/性能/质量
S->>S: 生成报告
S-->>M: 返回最终报告
M-->>U: 展示审查结果
Note over M: 主上下文保持干净<br/>只有最终报告
Note over S: 子上下文可丢弃<br/>包含所有中间分析
什么时候用context: fork?
| 场景 | 建议 |
|---|---|
| Skill会产生大量中间输出 | 用fork |
| Skill需要独立工具权限 | 用fork |
| Skill结果需要后续对话 | 不用fork |
| Skill执行时间短(<30秒) | 不用fork |
---
name: code-reviewer
description: >
Use when the user asks for code review, asks to review a PR,
or says "review my code". Analyzes git diffs for security
vulnerabilities, performance issues, and code smells with
structured reports. Also trigger when user mentions "代码审查",
"检查代码", "review", "PR review".
model: sonnet
context: fork
allowed-tools:
- Bash(git diff*)
- Bash(git log*)
- Bash(git show*)
- Read
- Grep
- Glob
---
# Code Review Skill
<SUBAGENT-STOP>
This skill is designed to run as a forked subagent. Do not attempt
to delegate further. Execute all steps directly.
</SUBAGENT-STOP>
You are a senior security-aware code reviewer with 15 years of
experience in web application development.
## Workflow
1. **Determine scope**: Parse user input to identify what to review
2. **Load checklist**: Run `cat rules/checklist.md`
3. **Load template**: Run `cat templates/report-template.md`
4. **Execute diff**: Run the appropriate git command
5. **Analyze**: Check each change against the checklist
6. **Report**: Generate output following the template
## Scope Detection
| User Input | Git Command |
|-----------|-------------|
| "last commit" / "最近提交" | `git diff HEAD~1 HEAD` |
| "PR" / "pull request" | `git diff main...HEAD` |
| "staged" / "暂存区" | `git diff --staged` |
| "file X" / "文件X" | `git diff <file>` |
| No specification | `git diff --staged` |
## Analysis Guidelines
- **Be specific**: Always include file path and line number
- **Be actionable**: Every issue must have a fix with code
- **Be proportional**: Don't flag minor style issues as Critical
- **Be positive**: Note good patterns, not just problems
- **Prioritize**: Security > Performance > Code Quality
## Output Rules
- Maximum 10 issues per report (prioritize by severity)
- If no issues found, clearly state "No issues found" and list positives
- Always include a "Recommendations Priority" section at the end
- Use emojis consistently: 🔴 🟡 🔵 ✅
创建完成后,验证Skill是否正常工作:
# 验证Skill被识别
claude /skills list | grep code-reviewer
# 手动触发测试
claude
> /code-reviewer 审查我最近的提交
# 使用非交互模式测试
claude -p "review my last commit" --allowedTools "Bash(git*)"
将Skill发布为Git仓库,团队成员可以一键安装:
# 发布到内部Git仓库
cd ~/.claude/skills/code-reviewer
git init
git remote add origin [email protected]:your-org/claude-skills.git
# 团队成员安装
claude skills add https://github.com/your-org/claude-skills
flowchart TB
subgraph "Step 1: Prompt验证"
P1["在Claude Code中<br/>输入原始Prompt"]
P2["验证效果是否可接受"]
P1 --> P2
end
subgraph "Step 2: 规则固定化"
Q1["提取审查规则<br/>写入CLAUDE.md"]
Q2["区分项目规则vs能力"]
Q1 --> Q2
end
subgraph "Step 3: 首次封装"
R1["创建SKILL.md<br/>frontmatter + 正文"]
R2["测试触发和执行"]
R1 --> R2
end
subgraph "Step 4: 渐进披露"
S1["拆分为三层结构<br/>入口+规则+模板"]
S2["验证token节省"]
S1 --> S2
end
subgraph "Step 5: 生产级交付"
T1["添加工具权限<br/>context:fork<br/>model选择"]
T2["团队发布与文档"]
T1 --> T2
end
P2 -->|"效果OK"| Q1
P2 -->|"效果差"| P1
Q2 --> R1
R2 -->|"功能正确"| S1
R2 -->|"触发不准"| R1
S2 --> T1
T2 --> DONE["✅ 生产就绪"]
style DONE fill:#28a745,color:#fff
在每个步骤之间,你都需要做出"继续演进还是回头优化"的决策:
| 决策点 | 继续条件 | 回退条件 |
|---|---|---|
| Step 1 → 2 | Prompt输出质量稳定 | 输出格式不一致 |
| Step 2 → 3 | 规则清晰可文档化 | 规则模糊,需要频繁调整 |
| Step 3 → 4 | 触发准确,执行正确 | 经常误触发或不触发 |
| Step 4 → 5 | 单人使用效果满意 | 分析深度不够 |
核心原则:每一步都是对上一步的增量改进。如果某一步效果不好,不要急于进入下一步,先解决当前步骤的问题。
不同复杂度的审查可以使用不同模型:
# 快速审查(日常提交)
model: haiku # 快速、低成本
# 深度审查(发布前)
model: sonnet # 平衡质量和速度
# 安全审计(合规要求)
model: opus # 最高质量
可以在SKILL.md正文中根据用户指令动态选择:
## Model Selection
- If user says "快速审查" or "quick review" → use haiku
- If user says "深度审查" or "thorough review" → use sonnet
- If user says "安全审计" or "security audit" → use opus
在Skill执行前后自动触发操作:
在.claude/settings.json中配置:
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash(git diff*)",
"command": "echo '[Code Reviewer] Analyzing changes...'"
}
],
"PostToolUse": [
{
"matcher": "Bash(git diff*)",
"command": "echo '[Code Reviewer] Diff collected, starting analysis'"
}
]
}
}
代码审查Skill可以调用其他Skill增强能力:
## Extended Workflow (Optional)
If the user requests a comprehensive review:
1. Run this skill's core analysis
2. Invoke the `security-best-practices` skill for deeper security analysis
3. Invoke the `test-driven-development` skill to suggest test coverage
4. Merge all reports into a unified output
当Skill表现不如预期时,按以下步骤排查:
flowchart TD
START["Skill不工作"] --> Q1{"能被触发吗?"}
Q1 -->|"否"| A1["检查description字段"]
A1 --> A2["添加更多触发短语"]
A2 --> A3["确认description中有Use when"]
Q1 -->|"是"| Q2{"执行正确吗?"}
Q2 -->|"否"| B1["检查正文指令清晰度"]
B1 --> B2["添加明确的Step编号"]
B2 --> B3["增加示例输出"]
Q2 -->|"是"| Q3{"输出质量好吗?"}
Q3 -->|"否"| C1["检查规则文件完整性"]
C1 --> C2["补充checklist细节"]
C2 --> C3["增加更多代码示例"]
Q3 -->|"是"| DONE["✅ Skill正常"]
# 查看Skill是否被正确加载
claude /skills list
# 查看Skill的详细内容
claude /skills show code-reviewer
# 使用verbose模式查看Skill加载过程
claude --verbose -p "review my code"
# 直接用Skill名称触发(跳过自动发现)
claude /code-reviewer 审查代码
| 维度 | 评估 |
|---|---|
| 适合训练营类型 | 企业内部开发者培训、AI工具链工作坊 |
| 教学时长 | 90分钟(含动手练习) |
| 难度曲线 | 平缓——每步都可独立验证 |
| 所需基础设施 | 仅需开发者笔记本+网络 |
| 学员前提 | 基本Git操作、命令行使用经验 |
| 推荐分组方式 | 2人结对,一人操作一人Review |
| 课后作业 | 将自己日常的一个重复任务封装为Skill |
[!tip] 51学通信知识星球 星主:爱卫生(微信:gprshome201101)——公众号「51学通信」创办者,19 年通信行业运维与讲师经验,著有《GPRS网络信令实例详解》《EPC原理与实践》《5G核心网原理与实践》三本纸质书(各大电商平台有售)。 星球定位:深耕 5G 核心网、IMS、NFV/AI、云原生等 ICT 领域,主打运维岗位与信令分析。 当前规模:5200 篇主题 / 990 个回答,198 元/年。 加入福利:加入星球后请加爱卫生微信,拉您进知识星球年度陪伴与答疑群——不限量回复您的各种问题,另有群内分享。 AI 加持:51学通信知识星球已作为 skill 接入 WorkBuddy,使用 deepseek-4-flash 在海量星球帖子中精准找贴、找视频、找 FAQ 和案例,做总结、找文档和 PPT 等场景全覆盖。
