<!-- title: Claude Code Skills开发：从零创建到评测发布 -->

# Claude Code Skills 开发：从零创建到评测发布

## 概述

本教程面向已具备 Claude Code 基础使用经验的开发者，系统讲解如何从零创建一个自定义 Skill（技能），涵盖 SKILL.md 文件格式、YAML frontmatter 全字段解析、自定义命令（Custom Commands）与 Skills 的区别、调试测试方法、以及通过 Plugin 机制发布分享的完整流程。学完后，你将能够为自己的团队或社区构建生产级 Claude Code 扩展能力。

**适用人群**：已安装并使用过 Claude Code 的开发者、团队技术负责人、AI 工具链维护者。

**学习目标**：
- 理解 Skills 与 Custom Commands 的架构差异和适用场景
- 独立编写包含完整 frontmatter 的 SKILL.md 文件
- 掌握 skill-creator 内置的评测（Eval）与基准测试（Benchmark）流程
- 将 Skill 打包为可分发的 Plugin

---

## 前置条件

| 条件 | 说明 |
|------|------|
| Claude Code CLI | 已安装并完成首次认证（`claude` 命令可用） |
| Node.js ≥ 18 | Claude Code 运行时依赖 |
| Git | 项目版本管理 |
| 基础 Markdown 能力 | 能编写格式化文档 |
| 一个测试项目 | 用于验证 Skill 效果的真实代码仓库 |

---

## 一、概念澄清：Skill、Command、Plugin 的关系

在动手之前，必须理解 Claude Code 扩展体系中的三个核心概念，它们容易混淆但职责完全不同。

```mermaid
graph TB
    subgraph "Claude Code 扩展体系"
        A[用户输入] --> B{路由判断}
        B -->|/command-name| C[Custom Command]
        B -->|自然语言匹配| D[Skill - SKILL.md]
        C --> E[.claude/commands/*.md<br/>手动触发 / 模板替换]
        D --> F[.claude/skills/*/SKILL.md<br/>自动触发 / 上下文感知]
        E --> G[注入为提示词]
        F --> G
        G --> H[Claude 执行]

        I[Plugin] --> C
        I --> D
        I --> J[MCP Server]
        I --> K[Hooks]
        J --> H
        K --> H
    end

    style C fill:#4CAF50,color:#fff
    style D fill:#2196F3,color:#fff
    style I fill:#FF9800,color:#fff
```

### 1.1 Custom Command（自定义命令）

**存放位置**：`.claude/commands/*.md`（项目级）或 `~/.claude/commands/*.md`（用户级）

**核心特征**：
- **手动触发**：用户输入 `/命令名` 显式调用
- **模板替换**：支持 `$ARGUMENTS` 占位符接收参数
- **轻量级**：本质上就是一个 Markdown 提示词模板
- **无 frontmatter**：纯 Markdown 内容，不需要 YAML 头部

**示例**：创建文件 `.claude/commands/review.md`

```markdown
Review the current staged changes in git. Focus on:
- Potential bugs or logic errors
- Code style and best practices
- Security concerns
- Performance implications

Target files: $ARGUMENTS
```

在 Claude Code 中输入 `/review src/auth/` 即可触发。

### 1.2 Skill（技能）

**存放位置**：`.claude/skills/<skill-name>/SKILL.md`（项目级）或通过 Plugin 安装

**核心特征**：
- **自动触发**：Claude 根据上下文自动判断何时使用
- **YAML frontmatter**：包含 name、description、trigger 等元数据
- **上下文感知**：Claude 在对话中识别到相关场景时自动加载
- **也可手动调用**：用户同样可以通过 `/skill-name` 触发

**示例**：`.claude/skills/api-review/SKILL.md`

```markdown
---
name: api-review
description: |
  Reviews REST API endpoint code for correctness, security,
  and RESTful best practices. Analyzes route handlers, 
  middleware chains, and request/response schemas.
---

# API Endpoint Review Skill

## When to Use
When the user is writing or modifying REST API endpoints,
route handlers, or middleware.

## Instructions
1. Check that all endpoints have proper input validation
2. Verify authentication/authorization middleware is applied
3. Ensure consistent error response format
4. Validate HTTP method semantics (GET = idempotent, etc.)
5. Check for proper status code usage
6. Review pagination patterns for list endpoints
```

### 1.3 Plugin（插件）

Plugin 是**分发容器**，可以包含一个或多个 Skills、Custom Commands、MCP Servers 和 Hooks。它通过 `claude plugin add <source>` 安装，是分享 Skill 给团队或社区的标准方式。

### 1.4 决策矩阵

| 维度 | Custom Command | Skill | Plugin |
|------|---------------|-------|--------|
| 触发方式 | 手动 `/name` | 自动+手动 | 包含的组件决定 |
| 配置复杂度 | 低（纯 Markdown） | 中（frontmatter + 指令） | 高（完整包结构） |
| 上下文感知 | ❌ | ✅ | ✅ |
| 分发方式 | Git 仓库共享 | Git / Plugin | Plugin 市场 / GitHub |
| 适用场景 | 固定流程的快捷入口 | 领域知识注入 | 团队/社区工具包 |

---

## 二、实战第一步：创建你的第一个 Custom Command

从最简单的 Command 开始，理解 Claude Code 扩展的基本工作方式。

### 2.1 创建目录结构

```bash
# 在你的项目根目录下
mkdir -p .claude/commands
```

### 2.2 编写命令文件

创建 `.claude/commands/test-gen.md`：

```markdown
Generate a comprehensive test suite for the following file: $ARGUMENTS

Requirements:
- Use the project's existing test framework (detect from package.json / pyproject.toml)
- Cover happy path, edge cases, and error scenarios
- Follow the naming convention of existing test files
- Mock external dependencies appropriately
- Aim for >80% code coverage on the target file

After writing tests, run them and fix any failures.
```

### 2.3 调用验证

```bash
# 启动 Claude Code
claude

# 在会话中输入
/test-gen src/utils/validator.ts
```

**预期行为**：Claude 会读取 `$ARGUMENTS` 替换为 `src/utils/validator.ts`，然后按照指令生成测试文件并自动运行。

### 2.4 常见问题

| 问题 | 原因 | 解决方案 |
|------|------|----------|
| 输入 `/test-gen` 无反应 | 文件名或路径错误 | 确认文件位于 `.claude/commands/` 下，扩展名为 `.md` |
| `$ARGUMENTS` 未被替换 | 命令名后未跟参数 | 使用 `/test-gen 文件路径` 格式 |
| 中文路径乱码 | 终端编码问题 | 确保终端使用 UTF-8 编码 |

---

## 三、核心实战：编写完整的 SKILL.md

现在进入本教程的核心——创建一个具有自动触发能力的 Skill。

### 3.1 Skill 文件结构

```
.claude/skills/
└── db-migration-review/
    ├── SKILL.md          # 必需 - 技能定义文件
    ├── examples/          # 可选 - 参考示例
    │   └── good-migration.ts
    └── templates/         # 可选 - 模板文件
        └── migration-template.ts
```

### 3.2 YAML Frontmatter 全字段解析

SKILL.md 的 YAML 头部是 Claude 理解和调度 Skill 的关键元数据。以下是目前支持的全部字段：

```yaml
---
# === 必需字段 ===
name: db-migration-review          # 技能标识符，用于 /name 调用和日志追踪
description: |                      # 技能描述，Claude 用它判断是否自动触发
  Reviews database migration files for safety,
  performance implications, and rollback feasibility.
  Analyzes schema changes, index operations, and data migrations.

# === 触发控制 ===
# Claude 会根据 description 和以下字段决定何时激活此 Skill

# === 输入定义 ===
input:                              # 定义 Skill 接受的输入参数
  - name: migration_file
    description: Path to the migration file to review
    required: true
  - name: strictness
    description: Review strictness level (normal|strict|paranoid)
    required: false

# === 行为控制 ===
disable-model-invocation: false     # true = 仅注入上下文，不触发 Claude 响应
                                    # false = 正常触发（默认）

# === 模型偏好 ===
model:                              # 指定执行此 Skill 时使用的模型
  preference: sonnet                # sonnet | opus | haiku

# === 子代理 ===
subagent_type: general-purpose      # 使用哪种子代理类型执行

# === Hook 集成 ===
hooks:                              # Skill 生命周期钩子
  before:                           # 执行前钩子
    - command: "npm run lint --quiet $FILE"
      description: "Run linter on target file first"
  after:                            # 执行后钩子
    - command: "echo 'Review complete' >> .claude/review-log.txt"
      description: "Log review completion"
---
```

### 3.3 Markdown 指令体编写规范

frontmatter 之后的 Markdown 内容是 Claude 的执行指令。编写质量直接影响 Skill 的表现。

```markdown
---
name: db-migration-review
description: |
  Reviews database migration files for safety and performance.
---

# Database Migration Review

## Role
You are a senior database engineer reviewing migration scripts.
Your goal is to catch dangerous operations BEFORE they reach production.

## Trigger Conditions
Activate this skill when:
- User creates or modifies a migration file (*.migration.ts, *.sql in migrations/)
- User asks to review a database schema change
- User mentions "migration", "schema change", "DDL", "ALTER TABLE"

## Review Checklist

### Critical (Must Fix)
1. **Destructive operations without rollback**
   - DROP TABLE / DROP COLUMN without corresponding CREATE in down()
   - Data deletion without backup strategy

2. **Locking risks**
   - ALTER TABLE on high-traffic tables during peak hours
   - Large batch operations without chunking
   - Missing statement timeouts

3. **Data integrity**
   - NOT NULL constraint added without DEFAULT value on populated table
   - Foreign key added without corresponding index

### Warning (Should Fix)
4. **Performance**
   - Missing indexes for new foreign keys
   - Full table scans in data migration loops
   - Unnecessary column type changes

5. **Naming conventions**
   - Migration file naming doesn't follow project convention
   - Inconsistent column naming (snake_case vs camelCase)

### Info (Nice to Have)
6. **Documentation**
   - Complex migration lacks inline comments
   - No JSDoc on new model methods

## Output Format

For each issue found, output:
- **Severity**: 🔴 Critical / 🟡 Warning / 🔵 Info
- **File & Line**: `path/to/file.ts:L42`
- **Issue**: One-sentence description
- **Fix**: Concrete code suggestion

End with a summary:
- Total issues: X Critical, Y Warning, Z Info
- Overall verdict: APPROVE / APPROVE_WITH_NOTES / REJECT

## Context Files
When reviewing, also read:
- `prisma/schema.prisma` or equivalent ORM schema
- `src/models/` for model definitions
- Previous migration files for pattern consistency
```

### 3.4 编写要点总结

| 要点 | 说明 | 反模式（避免） |
|------|------|---------------|
| 角色定义 | 开头明确 Claude 扮演什么角色 | 模糊的 "help me review" |
| 触发条件 | 列出具体的激活场景 | 依赖 Claude 自行猜测 |
| 分级输出 | Critical/Warning/Info 分层 | 所有问题同等优先级 |
| 具体指令 | 给出精确的操作步骤 | 笼统的 "check everything" |
| 输出格式 | 规定结构化的输出模板 | 让 Claude 自由发挥 |
| 上下文文件 | 列出需要参考的额外文件 | 仅分析用户指定的文件 |

---

## 四、进阶：构建一个完整的数据库迁移审查 Skill

现在我们用上面的知识，构建一个可以直接使用的完整 Skill。

### 4.1 初始化 Skill 目录

```bash
# 在项目根目录
mkdir -p .claude/skills/db-migration-review/examples
```

### 4.2 创建参考示例文件

`.claude/skills/db-migration-review/examples/good-migration.ts`：

```typescript
// ✅ Good migration example: Safe column addition with rollback
import { Migration } from '../migrator';

export class AddUserAvatarUrl1700000000000 extends Migration {
  // Descriptive class name with timestamp
  // ✅ up() adds column safely with DEFAULT value
  async up(): Promise<void> {
    await this.query(`
      ALTER TABLE users 
      ADD COLUMN avatar_url VARCHAR(512) NULL 
      DEFAULT NULL;
    `);
    // ✅ Index added separately for large tables
    await this.query(`
      CREATE INDEX CONCURRENTLY idx_users_avatar_url 
      ON users (avatar_url);
    `);
  }

  // ✅ down() provides clean rollback
  async down(): Promise<void> {
    await this.query(`DROP INDEX CONCURRENTLY idx_users_avatar_url;`);
    await this.query(`ALTER TABLE users DROP COLUMN avatar_url;`);
  }
}
```

### 4.3 完整的 SKILL.md

将第三节的 frontmatter 和指令体组合，创建 `.claude/skills/db-migration-review/SKILL.md`：

```markdown
---
name: db-migration-review
description: |
  Reviews database migration files for safety, performance,
  and rollback feasibility. Triggered when creating or modifying
  migration scripts. Checks for destructive operations, locking
  risks, data integrity issues, and naming conventions.
input:
  - name: migration_file
    description: Path to the migration file to review
    required: true
model:
  preference: sonnet
---

# Database Migration Safety Review

## Role
You are a senior database reliability engineer (DBRE) who has 
witnessed one too many production incidents caused by careless 
migrations. You review every migration with the paranoia it deserves.

## Activation
This skill activates when the user:
- Creates or edits files matching `*migration*`, `migrations/**`
- Asks to review schema changes, DDL, or ALTER statements
- Uses phrases: "migration review", "schema change check", "is this migration safe"

## Reference
See `examples/good-migration.ts` for an example of a well-structured migration.

## Review Process

### Step 1: Parse the Migration
- Identify all DDL operations (CREATE, ALTER, DROP, RENAME)
- Identify all DML operations (INSERT, UPDATE, DELETE in data migrations)
- Map each operation to its rollback counterpart in down()

### Step 2: Critical Checks
Run these checks in order. ANY failure = immediate 🔴 flag:

| Check | Description | Example Violation |
|-------|-------------|-------------------|
| Rollback completeness | Every up() operation has a corresponding down() | `ADD COLUMN` without `DROP COLUMN` in down() |
| Safe defaults | NOT NULL columns have DEFAULT or are added nullable first | `ALTER TABLE ADD col VARCHAR NOT NULL` on populated table |
| Lock scope | No long-running DDL on large tables without CONCURRENTLY | `CREATE INDEX` instead of `CREATE INDEX CONCURRENTLY` |
| Batch limits | Data migrations process in batches ≤ 1000 rows | `UPDATE users SET ... WHERE ...` without LIMIT |

### Step 3: Performance Checks
- Estimate table size (check row count from schema comments)
- Flag operations that hold AccessExclusiveLock > 5 seconds
- Verify foreign key columns have indexes
- Check if new indexes can use CONCURRENTLY

### Step 4: Convention Checks
- File naming matches project pattern
- Column naming follows existing convention (check schema file)
- Migration class has descriptive name with timestamp

## Output Template

```
## Migration Review: [filename]

### Summary
- Verdict: [APPROVE ✅ | NEEDS CHANGES ⚠️ | REJECT ❌]
- Critical: X  |  Warning: Y  |  Info: Z

### Findings

🔴 **[C1] Missing rollback for ADD COLUMN**
File: `src/migrations/001.ts:12`
Issue: `ALTER TABLE users ADD COLUMN avatar_url TEXT` has no DROP COLUMN in down()
Fix:
```sql
-- In down():
ALTER TABLE users DROP COLUMN IF EXISTS avatar_url;
```

🟡 **[W1] Non-concurrent index creation**
...
```

## Auto-fix
After review, if the user agrees with findings, offer to apply fixes directly.
Always create a new migration file for fixes rather than modifying the original.
```

### 4.4 验证 Skill 加载

```bash
# 启动 Claude Code 并检查 Skill 是否被识别
claude

# 在会话中输入
# 方式1：自然语言触发
> "帮我审查一下 src/migrations/002_add_email_index.ts 这个迁移文件"

# 方式2：手动调用
> /db-migration-review src/migrations/002_add_email_index.ts
```

**预期结果**：Claude 自动加载 Skill 的指令，按照定义的审查流程输出结构化的审查报告。

---

## 五、Skill 调试与排障

### 5.1 常见问题诊断

```mermaid
flowchart TD
    A[Skill 未被触发] --> B{手动 /name 可用?}
    B -->|否| C[检查文件路径和命名]
    B -->|是| D{description 是否匹配场景?}

    C --> C1[路径: .claude/skills/name/SKILL.md]
    C --> C2[文件名必须大写: SKILL.md]
    C --> C3[YAML 语法是否正确]

    D -->|不匹配| E[优化 description 关键词]
    D -->|匹配| F[检查是否被更高优先级 Skill 截获]

    E --> E1[包含用户可能使用的自然语言词汇]
    E --> E2[列出具体的文件模式/操作类型]

    F --> F1[使用 /skills 查看所有已加载 Skill]
    F --> F2[检查 YAML 语法是否导致解析失败]

    G[Skill 输出质量差] --> H{指令是否具体?}
    H -->|模糊| I[添加结构化的输出模板]
    H -->|具体| J[增加参考示例文件]

    J --> J1[在 Skill 目录下添加 examples/]
    J --> J2[在 SKILL.md 中引用示例路径]
```

### 5.2 调试命令

```bash
# 查看当前项目所有已加载的 Skills
claude /skills

# 使用 verbose 模式观察 Skill 加载过程
claude --verbose

# 测试特定 Skill 的触发
claude -p "review this migration file: src/migrations/001.ts" --verbose
```

### 5.3 YAML 语法校验

YAML frontmatter 是最常见的出错点。推荐使用在线校验工具或命令行工具验证：

```bash
# 使用 Python 快速校验 YAML 语法
python3 -c "
import yaml, sys
with open('.claude/skills/db-migration-review/SKILL.md') as f:
    content = f.read()
    parts = content.split('---', 2)
    if len(parts) >= 3:
        try:
            meta = yaml.safe_load(parts[1])
            print('✅ YAML valid')
            print(f'Fields: {list(meta.keys())}')
        except yaml.YAMLError as e:
            print(f'❌ YAML error: {e}')
    else:
        print('❌ No frontmatter found')
"
```

---

## 六、Skill 评测与质量保证

Anthropic 在 2026 年 3 月为 skill-creator 增加了内置评测（Eval）和基准测试（Benchmark）功能，这是确保 Skill 质量的关键工具。

### 6.1 评测（Eval）机制

Eval 的核心思想：为 Skill 准备一组**测试用例**，每个用例包含输入和期望输出，然后让 Claude 自动执行并评分。

```yaml
# .claude/skills/db-migration-review/evals.yaml
evals:
  - name: "catch-destructive-drop"
    input: |
      Review this migration:
      ```sql
      ALTER TABLE orders DROP COLUMN discount_code;
      ```
    expected_behavior: |
      Must flag as Critical: DROP COLUMN without backup strategy.
      Must suggest adding a down() migration with ADD COLUMN.
    scoring:
      - criterion: "flags DROP COLUMN as critical"
        weight: 0.5
      - criterion: "suggests rollback"
        weight: 0.3
      - criterion: "proposes specific fix code"
        weight: 0.2

  - name: "approve-safe-migration"
    input: |
      Review this migration:
      ```sql
      ALTER TABLE users ADD COLUMN avatar_url TEXT NULL DEFAULT NULL;
      CREATE INDEX CONCURRENTLY idx_users_avatar ON users(avatar_url);
      ```
    expected_behavior: |
      Should APPROVE this migration. No critical issues expected.
    scoring:
      - criterion: "verdict is APPROVE"
        weight: 0.6
      - criterion: "no false positives"
        weight: 0.4
```

### 6.2 运行评测

```bash
# 使用 skill-creator 的 eval 命令
claude /skill-creator eval db-migration-review

# 查看详细评测报告
claude /skill-creator eval db-migration-review --verbose
```

### 6.3 基准测试（Benchmark）与 A/B 对比

当你迭代优化 Skill 时，需要验证新版本是否真的更好：

```bash
# 对比两个版本的 Skill
claude /skill-creator benchmark \
  --skill-a db-migration-review \
  --skill-b db-migration-review-v2 \
  --evals-file evals.yaml \
  --rounds 5

# 输出示例：
# ╔══════════════════════════════════════════╗
# ║  Benchmark Results (5 rounds each)      ║
# ╠══════════════════════════════════════════╣
# ║  Skill A (v1): 78% avg score            ║
# ║  Skill B (v2): 91% avg score            ║
# ║  Winner: Skill B (+13pp)                ║
# ║  p-value: 0.031 (significant)           ║
# ╚══════════════════════════════════════════╝
```

### 6.4 评测质量提升策略

```mermaid
flowchart LR
    A[编写初始 Skill] --> B[创建 Eval 测试集]
    B --> C[运行首轮评测]
    C --> D{评分 ≥ 85%?}
    D -->|否| E[分析失败用例]
    E --> F[优化指令措辞]
    F --> G[增加参考示例]
    G --> C
    D -->|是| H[进行 A/B 基准测试]
    H --> I{新版更优?}
    I -->|是| J[发布新版本]
    I -->|否| K[保留当前版本]
    K --> L[收集边缘案例]
    L --> B
```

**评测数据集设计原则**：

| 原则 | 说明 | 示例 |
|------|------|------|
| 正例覆盖 | 包含应该通过的正常场景 | 安全的迁移文件应获得 APPROVE |
| 反例覆盖 | 包含应该拒绝的异常场景 | DROP TABLE 无 rollback 应获得 REJECT |
| 边缘案例 | 模糊地带的边界情况 | 可空列的 NOT NULL 迁移（大表 vs 空表） |
| 多样性 | 不同语言/框架的迁移文件 | TypeORM / Prisma / Raw SQL 各一个 |

---

## 七、打包为 Plugin 发布

当你想把 Skill 分享给团队或社区时，需要将其打包为 Plugin。

### 7.1 Plugin 目录结构

```
db-migration-review-plugin/
├── plugin.yaml              # Plugin 元数据（必需）
├── SKILL.md                 # 单 Skill 可直接放根目录
├── examples/
│   └── good-migration.ts
├── README.md                # 安装说明
└── LICENSE
```

如果是多 Skill 插件：

```
my-team-toolkit/
├── plugin.yaml
├── skills/
│   ├── db-migration-review/
│   │   └── SKILL.md
│   ├── api-review/
│   │   └── SKILL.md
│   └── deploy-check/
│       └── SKILL.md
├── commands/
│   ├── sprint-review.md
│   └── release-notes.md
├── README.md
└── LICENSE
```

### 7.2 plugin.yaml 配置

```yaml
# plugin.yaml
name: db-migration-review
version: 1.2.0
description: |
  Automated database migration safety review for Claude Code.
  Catches destructive operations, locking risks, and rollback issues.
author: your-name
repository: https://github.com/your-org/db-migration-review-plugin
license: MIT

# 最低 Claude Code 版本要求
min_claude_version: "1.0.0"

# 依赖的 MCP 服务器（可选）
# mcp_servers:
#   - name: db-analyzer
#     command: npx
#     args: ["-y", "db-analyzer-mcp"]
```

### 7.3 安装与分发

```bash
# 从本地路径安装
claude plugin add ./db-migration-review-plugin

# 从 GitHub 仓库安装
claude plugin add github:your-org/db-migration-review-plugin

# 从 URL 安装
claude plugin add https://example.com/plugins/db-migration-review-1.2.0.tar.gz

# 查看已安装插件
claude plugin list

# 更新插件
claude plugin update db-migration-review

# 卸载
claude plugin remove db-migration-review
```

### 7.4 发布到社区

```bash
# 1. 确保测试通过
claude /skill-creator eval db-migration-review --all

# 2. 推送到 GitHub
git remote add origin https://github.com/your-org/db-migration-review-plugin.git
git push -u origin main

# 3. 提交到 Claude Code Plugin 发现页面
# 访问 https://code.claude.com/plugins/submit 填写提交表单
```

---

## 八、高级技巧与最佳实践

### 8.1 触发精准度优化

description 是 Claude 判断是否自动激活 Skill 的核心依据。优化技巧：

```yaml
# ❌ 模糊描述 — 触发范围太广或太窄
description: "Review code for issues"

# ✅ 精准描述 — 包含具体的场景关键词
description: |
  Reviews database migration files (.sql, .ts migration scripts)
  for safety hazards. Triggers when user creates or modifies
  files in migrations/ directories, or mentions schema changes,
  DDL operations, ALTER TABLE, CREATE INDEX, or data migrations.
```

### 8.2 多层级 Skills 协作

复杂场景可以拆分为多个 Skill，通过 description 形成层次关系：

```
skills/
├── code-review/              # 通用代码审查
│   └── SKILL.md              # description: "general code review..."
├── db-migration-review/      # 数据库迁移专用（优先级高于通用）
│   └── SKILL.md              # description: "database migration review..."
└── security-review/          # 安全审查
    └── SKILL.md              # description: "security vulnerability review..."
```

Claude 会根据上下文选择最具体的匹配 Skill。

### 8.3 与 CLAUDE.md 配合

在项目的 `CLAUDE.md` 中可以引导 Claude 优先使用特定 Skill：

```markdown
# CLAUDE.md
## Database Changes
When reviewing any file in `src/migrations/`, always use the 
`db-migration-review` skill before proceeding with changes.
Never approve a migration that hasn't been reviewed.
```

### 8.4 输入参数高级用法

```yaml
input:
  - name: files
    description: "Files to review (space-separated)"
    required: true
  - name: strictness
    description: "Review level: normal | strict | paranoid"
    required: false
    default: "normal"
  - name: focus
    description: "Specific area to focus on: safety | performance | naming"
    required: false
```

在 Markdown 指令体中引用：

```markdown
Review the following files with $strictness level strictness.
Focus area: $focus (if not specified, review all areas).
Files: $files
```

### 8.5 条件逻辑与分支

SKILL.md 的指令体支持通过自然语言描述实现条件逻辑：

```markdown
## Conditional Behavior

If the target file is a TypeScript migration:
- Parse TypeScript class structure
- Look for up() and down() methods

If the target file is raw SQL:
- Parse SQL statements directly
- Verify each statement has a corresponding rollback statement

If no down() or rollback is found:
- Automatically flag as Critical severity
```

---

## 九、完整实战项目：API 安全审查 Skill

将所有知识整合，创建一个实用的 API 安全审查 Skill。

### 9.1 目录结构

```
.claude/skills/api-security-review/
├── SKILL.md
└── examples/
    ├── secure-endpoint.ts
    └── vulnerable-endpoint.ts
```

### 9.2 SKILL.md 完整内容

```markdown
---
name: api-security-review
description: |
  Security-focused review for REST API endpoints and route handlers.
  Detects authentication bypasses, injection vulnerabilities,
  insecure defaults, missing rate limiting, and CORS misconfigurations.
  Activates when user writes or modifies API route files, controllers,
  or middleware. Keywords: API, endpoint, route, handler, controller,
  authentication, authorization, middleware.
input:
  - name: endpoint_file
    description: Path to the API endpoint file to review
    required: true
  - name: framework
    description: "Framework: express | fastify | nestjs | koa | hono"
    required: false
model:
  preference: sonnet
---

# API Security Review Skill

## Role
You are a security engineer specializing in web API vulnerabilities.
You follow OWASP API Security Top 10 and have deep knowledge of
Node.js/TypeScript web frameworks.

## Activation
Trigger when user:
- Creates or modifies files matching: routes/**, controllers/**, api/**, endpoints/**
- Uses phrases: "API security", "endpoint review", "is this endpoint secure"
- Mentions: authentication, authorization, CORS, rate limiting, input validation

## Security Checklist

### 🔴 Critical — Immediate Exploits

| # | Check | OWASP Ref | Detection Pattern |
|---|-------|-----------|-------------------|
| 1 | **Auth bypass** | API1:2023 | Endpoint without auth middleware |
| 2 | **SQL/NoSQL injection** | API8:2023 | String concatenation in queries |
| 3 | **Mass assignment** | API3:2023 | req.body directly passed to model |
| 4 | **Broken object-level auth** | API1:2023 | ID from user input without ownership check |

### 🟡 Warning — Configuration Risks

| # | Check | Detection Pattern |
|---|-------|-------------------|
| 5 | **CORS wildcard** | `origin: '*'` with credentials |
| 6 | **Missing rate limiting** | No rate limiter on login/signup |
| 7 | **Verbose errors** | Stack traces exposed to client |
| 8 | **Missing HTTPS** | HTTP URLs in production config |

### 🔵 Info — Hardening Opportunities

| # | Check | Detection Pattern |
|---|-------|-------------------|
| 9 | **Helmet.js** | No security headers middleware |
| 10 | **Request size limit** | No body parser size limit |
| 11 | **Input sanitization** | No HTML encoding on user input |

## Analysis Steps

1. **Detect Framework** — Check imports for express/fastify/nestjs/koa/hono
2. **Map Routes** — Identify all HTTP method handlers and their middleware chains
3. **Trace Auth** — For each route, verify authentication middleware is applied
4. **Check Input Handling** — Trace user input from request to database query
5. **Review Output** — Check response for sensitive data leakage

## Output Format

```markdown
## 🔒 API Security Review: [filename]

**Framework detected**: Express.js
**Endpoints analyzed**: 5
**Overall risk**: 🔴 HIGH

### Findings

#### 🔴 [C1] Authentication bypass on DELETE /api/users/:id
- **File**: src/routes/users.ts:45
- **Issue**: No auth middleware on DELETE endpoint
- **Exploit**: Any unauthenticated user can delete accounts
- **Fix**:
  ```typescript
  router.delete('/users/:id', authMiddleware, authorize('admin'), async (req, res) => {
  ```

#### 🟡 [W1] CORS allows all origins with credentials
...

### Summary
| Severity | Count |
|----------|-------|
| 🔴 Critical | 2 |
| 🟡 Warning | 3 |
| 🔵 Info | 1 |

**Recommendation**: DO NOT deploy until Critical issues are resolved.
```

## Post-Review Actions
1. Ask user if they want to auto-fix Critical issues
2. Generate a security test case for each Critical finding
3. Update the project's CLAUDE.md with security conventions if not present
```

### 9.3 测试用例

```typescript
// examples/vulnerable-endpoint.ts
import express from 'express';
const router = express.Router();

// 🔴 No auth middleware — anyone can access
router.get('/admin/users', async (req, res) => {
  // 🔴 SQL injection — string concatenation
  const query = `SELECT * FROM users WHERE name = '${req.query.name}'`;
  const users = await db.query(query);
  
  // 🟡 Exposing internal IDs
  res.json({ users, total: users.length });
});

// 🔴 Mass assignment — entire body passed to DB
router.post('/users', async (req, res) => {
  const user = await db.users.create({
    data: req.body  // ⚠️ could include role: 'admin'
  });
  res.json(user);
});

export default router;
```

### 9.4 运行评测

```bash
# 创建评测文件
# .claude/skills/api-security-review/evals.yaml

# 运行
claude /skill-creator eval api-security-review

# 预期输出：
# ✅ catch-auth-bypass: PASS (scored 0.95)
# ✅ catch-sql-injection: PASS (scored 1.00)
# ✅ catch-mass-assignment: PASS (scored 0.90)
# ⚠️ catch-cors-issue: PARTIAL (scored 0.65) — missed wildcard origin
# ✅ no-false-positive: PASS (scored 0.88)
#
# Overall: 87.6% — Good, optimize CORS detection
```

---

## 十、Skill 开发全流程总览

```mermaid
flowchart TB
    subgraph "Phase 1: 设计"
        A[确定 Skill 目标与场景] --> B[收集参考示例<br/>好的/坏的]
        B --> C[设计输出格式与分级标准]
    end

    subgraph "Phase 2: 开发"
        C --> D[编写 SKILL.md<br/>frontmatter + 指令体]
        D --> E[添加参考示例文件]
        E --> F[本地测试<br/>手动触发 + 自然语言触发]
    end

    subgraph "Phase 3: 评测"
        F --> G[编写 Eval 测试集<br/>正例/反例/边缘案例]
        G --> H[运行评测<br/>目标 ≥ 85% 通过率]
        H --> I{评分达标?}
        I -->|否| D
        I -->|是| J[A/B 基准测试]
    end

    subgraph "Phase 4: 发布"
        J --> K[打包为 Plugin<br/>plugin.yaml + README]
        K --> L[推送到 GitHub]
        L --> M[团队安装验证]
        M --> N[提交到 Plugin 市场]
    end

    subgraph "Phase 5: 迭代"
        N --> O[收集用户反馈]
        O --> P[补充边缘案例到 Eval]
        P --> Q[优化 Skill 指令]
        Q --> H
    end

    style A fill:#E3F2FD
    style D fill:#FFF3E0
    style H fill:#E8F5E9
    style K fill:#FCE4EC
    style O fill:#F3E5F5
```

### 时间估算

| 阶段 | 预估时间 | 说明 |
|------|---------|------|
| 设计 | 30-60 分钟 | 明确目标、收集示例、设计输出格式 |
| 开发 | 1-2 小时 | 编写 SKILL.md 和参考文件 |
| 评测 | 1-3 小时 | 创建测试集、运行评测、迭代优化 |
| 发布 | 30 分钟 | 打包、文档、推送 |
| 迭代 | 持续 | 根据反馈持续优化 |

---

## 训练营适用性评估

| 维度 | 评估 |
|------|------|
| **适合训练营类型** | AI 工具链训练营、开发者效率训练营、团队工程化训练营 |
| **教学时长** | 3-4 小时（含动手实践） |
| **难度级别** | 中级（需 Claude Code 基础使用经验） |
| **实验环境** | 每人需一个 Node.js 项目 + Claude Code CLI |
| **考核方式** | 学员独立创建一个 Skill 并通过 Eval 测试 |
| **分组建议** | 2-3 人一组，每组选择不同场景（安全审查、代码规范、文档生成等） |

---

## 参考来源

1. [Extend Claude with skills - Claude Code Docs](https://code.claude.com/docs/en/skills) — Anthropic 官方 Skill 开发文档，涵盖 SKILL.md 格式和最佳实践
2. [How to Build Custom Claude Code Skills That Actually Work - DEV Community](https://dev.to/alanwest/how-to-build-custom-claude-code-skills-that-actually-work-2e1f) — 实战经验分享，包含触发优化和常见踩坑
3. [Claude Code Skill Frontmatter: Every YAML Option Explained](https://allahabadi.dev/blogs/ai/claude-code-skills-frontmatter-complete-guide/) — 15 个 frontmatter 字段的逐一详解
4. [Improving skill-creator: Test, measure, and refine Agent Skills - Claude Blog](https://claude.com/blog/improving-skill-creator-test-measure-and-refine-agent-skills) — Anthropic 官方 Eval 与 Benchmark 功能介绍
5. [Claude Code Skills: The Complete Guide (2026) - Duet](https://duet.so/guides/claude-code-skills-complete-guide) — 综合指南，覆盖 SKILL.md、MCP、Subagents 全栈扩展

> [!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 等场景全覆盖。

![51学通信知识星球海报-扫码加入](https://wiki.500nian.com/images/zhixingqiu_qrcode.png)
