<!-- title: SKILL.md规范精解：字段到指令设计全实战 -->

# SKILL.md规范精解：YAML字段到指令设计全实战

## 概述

**学习目标**：掌握Claude Code Skill的核心文件格式SKILL.md，理解全部YAML frontmatter字段的语义和用法，学会编写高质量指令的五大设计原则，并通过一个完整的代码审查Skill实战项目，打通从规范理解到可发布Skill的全流程。

**适用人群**：已具备Claude Code基本使用经验，希望构建高质量、可复用、可分发自定义Skill的开发者和团队负责人。

## 前置条件

- Claude Code ≥ 1.0.25（支持SKILL.md格式）
- 基本了解Markdown语法和YAML格式
- 一个可用的Claude Code项目目录
- 终端环境（macOS/Linux/WSL）

---

## 第一章 SKILL.md文件格式全景

### 1.1 什么是SKILL.md

SKILL.md是Claude Code Skill的核心载体——一个纯文本Markdown文件，通过YAML frontmatter声明元数据，通过Markdown正文定义行为指令。它不依赖任何API、SDK或编译步骤，本质上就是**结构化的自然语言程序**。

Claude Code在启动时会扫描特定目录下的SKILL.md文件，将其内容加载到上下文窗口中，作为Claude行为的持久化知识层。这意味着Skill的效果完全取决于文件内容的精确度。

### 1.2 文件位置与加载路径

Skill文件有三个存放层级，对应不同的作用域：

```
~/.claude/skills/          ← 全局级：所有项目可用
├── code-review/
│   └── SKILL.md
└── security-scan/
    └── SKILL.md

your-project/.claude/skills/   ← 项目级：仅当前项目
├── api-style/
│   └── SKILL.md
└── db-migration/
    └── SKILL.md

your-project/.claude/commands/ ← 自定义命令（旧格式，仍兼容）
├── deploy.md
└── test-all.md
```

**加载优先级**：项目级 > 全局级。当两个层级的Skill名称冲突时，项目级覆盖全局级。

### 1.3 SKILL.md基本骨架

一个最小的SKILL.md只需要两个字段：

```markdown
---
name: hello-reviewer
description: A simple code review skill that checks for common issues.
---

# Hello Reviewer

When reviewing code, always check for:
1. Missing error handling
2. Unused imports
3. Hardcoded secrets
```

但生产级Skill需要充分利用全部字段。下面逐一拆解。

---

## 第二章 YAML Frontmatter全字段精解

### 2.1 字段总览表

当前SKILL.md规范定义了15个YAML frontmatter字段。按功能分为四组：

| 分组 | 字段 | 必填 | 类型 | 作用 |
|------|------|------|------|------|
| **身份** | `name` | 是 | string | Skill唯一标识符 |
| | `description` | 是 | string | 向Agent说明何时激活 |
| | `version` | 否 | string | 语义化版本号 |
| **行为控制** | `instructions` | 否 | string | 指令正文（也可写在Markdown body中） |
| | `disable-model-invocation` | 否 | boolean | 是否禁止模型自主调用 |
| | `auto-activate` | 否 | boolean | 是否自动检测激活 |
| **工具权限** | `tools` | 否 | list | 允许使用的工具列表 |
| | `allowed-tools` | 否 | list | 工具白名单（与tools互补） |
| | `blocked-tools` | 否 | list | 工具黑名单 |
| **输入输出** | `variables` | 否 | object | 模板变量定义 |
| | `input` | 否 | object | 输入参数schema |
| | `output` | 否 | object | 输出格式定义 |
| **生命周期** | `hooks` | 否 | object | 前后置钩子 |
| | `dependencies` | 否 | list | 依赖的其他Skill或MCP服务器 |
| | `metadata` | 否 | object | 自定义扩展元数据 |

### 2.2 身份字段

#### `name`（必填）

Skill的唯一标识符，**必须与所在文件夹名称完全一致**。这是Claude Code查找和加载Skill的依据。

```yaml
# 如果文件路径是 .claude/skills/api-reviewer/SKILL.md
name: api-reviewer    # ✓ 正确：与文件夹名一致
name: api_reviewer    # ✗ 错误：下划线不匹配
name: API-Reviewer    # ✗ 错误：大小写不匹配
```

命名规范：
- 使用kebab-case（短横线分隔）
- 长度3-40个字符
- 只允许小写字母、数字和短横线
- 避免使用`claude`、`anthropic`等保留前缀

#### `description`（必填）

这不是给人看的描述，而是**给Agent看的路由指令**。Agent根据description字段判断当前任务是否应该激活此Skill。因此description需要精确描述Skill的触发条件和适用场景。

```yaml
# ✗ 差的描述：太模糊
description: A helpful tool for developers.

# ✓ 好的描述：精确的触发条件
description: >
  Use when reviewing Python REST API code for security vulnerabilities.
  Triggers on files matching routes/*.py, views/*.py, or api/*.py.
  Activates for tasks mentioning "API review", "security audit", or "endpoint check".
```

description的最佳实践：
- 包含**何时使用**（When to use）
- 包含**适用文件模式**（File patterns）
- 包含**触发关键词**（Trigger keywords）
- 控制在2-4行以内

#### `version`

遵循语义化版本规范（SemVer），用于插件市场版本管理和依赖解析：

```yaml
version: 1.2.0
```

### 2.3 行为控制字段

#### `auto-activate`

控制Skill是否被自动检测并激活。默认为`true`。

```yaml
# 只有用户明确 /skill-name 时才激活
auto-activate: false
```

适用场景：
- 重量级Skill（消耗大量上下文）
- 专用Skill（只在特定情况下需要）
- 调试中的Skill

#### `disable-model-invocation`

禁止模型在后台自动调用此Skill。与`auto-activate`不同，这个字段完全阻止Skill被执行，除非用户通过斜杠命令显式触发。

```yaml
disable-model-invocation: true
```

典型用途：将Skill作为参考文档而非可执行指令。

### 2.4 工具权限字段

#### `tools` / `allowed-tools` / `blocked-tools`

这三个字段形成完整的工具权限矩阵：

```yaml
# 模式一：白名单——只允许指定工具
allowed-tools:
  - Read
  - Grep
  - Glob

# 模式二：黑名单——禁止指定工具
blocked-tools:
  - Bash           # 禁止执行shell命令
  - Write          # 禁止写入文件（只读模式）

# 模式三：混合——允许大部分但排除危险操作
tools:
  - Read
  - Grep
  - Glob
  - Edit
blocked-tools:
  - Bash
```

可用工具列表：

| 工具 | 用途 | 风险等级 |
|------|------|----------|
| Read | 读取文件 | 低 |
| Glob | 文件搜索 | 低 |
| Grep | 内容搜索 | 低 |
| Edit | 编辑文件 | 中 |
| Write | 创建文件 | 中 |
| Bash | Shell命令 | 高 |
| Task | 子Agent | 中 |
| WebSearch | 网络搜索 | 低 |

### 2.5 输入输出字段

#### `variables`

定义模板变量，使Skill可以参数化复用。使用`{{variable_name}}`语法在正文中引用：

```yaml
variables:
  framework:
    description: Target framework name
    default: react
    type: string
  style-guide:
    description: URL to the team style guide
    type: string
    required: false
  max-complexity:
    description: Maximum cyclomatic complexity allowed
    default: 10
    type: integer
```

在Markdown正文中引用：

```markdown
# {{framework}} Code Review

Review all code against the style guide at {{style-guide}}.
Flag any function with cyclomatic complexity > {{max-complexity}}.
```

变量类型支持：`string`、`integer`、`boolean`、`enum`、`list`。

#### `input` / `output`

定义结构化的输入参数schema和输出格式，为Skill之间的组合调用提供类型安全：

```yaml
input:
  type: object
  properties:
    file_path:
      type: string
      description: Path to the file to review
    severity_threshold:
      type: enum
      values: [low, medium, high, critical]
      default: medium

output:
  type: object
  properties:
    issues:
      type: list
      description: List of found issues
    summary:
      type: string
      description: Brief review summary
    score:
      type: integer
      description: Code quality score (0-100)
```

### 2.6 生命周期字段

#### `hooks`

定义Skill执行前后的钩子函数，用于数据准备和结果处理：

```yaml
hooks:
  pre-invoke:
    - name: validate-project
      description: Ensure the project has the required structure
  post-invoke:
    - name: cleanup-temp-files
      description: Remove temporary files created during skill execution
```

#### `dependencies`

声明Skill运行所需的外部依赖：

```yaml
dependencies:
  skills:
    - name: security-scanner
      version: ">=1.0.0"
    - name: test-runner
  mcp-servers:
    - name: filesystem
    - name: github
```

#### `metadata`

自定义扩展字段，不参与Skill执行逻辑，但可用于插件市场展示和分类：

```yaml
metadata:
  author: your-team
  tags: [security, code-review, python]
  license: MIT
  repository: https://github.com/your-org/claude-skills
  min-claude-version: 1.0.25
```

---

## 第三章 指令工程五原则

拥有完整的YAML字段知识只是基础。Skill的效果90%取决于正文中的指令质量。以下是从分析数百个社区Skill中提炼出的五大设计原则。

### 原则一：场景锚定——精确到触发边界

差指令告诉Claude"做什么"，好指令告诉Claude"在什么条件下做什么、在什么条件下不做"。

```markdown
<!-- ✗ 模糊指令 -->
Review the code and find issues.

<!-- ✓ 锚定指令 -->
## Activation Conditions
Activate this skill ONLY when:
- User explicitly asks for a code review, OR
- The file being edited is in src/api/ directory

DO NOT activate when:
- User is writing tests
- User is making documentation changes

## Review Scope
For each file under review, check:
1. **Error handling**: Every async function must have try/catch
2. **Input validation**: All external inputs must be validated with zod schemas
3. **SQL injection**: Parameterized queries only in database calls
```

### 原则二：结构分层——指令金字塔

将指令分为三个层级：**必做（MUST）**、**应该（SHOULD）**、**可选（MAY）**。这避免了指令全部被当作同等重要而导致的优先级混乱。

```markdown
## Review Rules

### MUST (Block on violation)
- [SECURITY] No hardcoded secrets or API keys
- [SECURITY] All user inputs sanitized before database operations
- [CRASH] No unhandled promise rejections in async code

### SHOULD (Warn but don't block)
- [STYLE] Consistent naming conventions per file
- [PERF] Avoid N+1 database queries in loops
- [MAINT] Functions should not exceed 50 lines

### MAY (Suggest as improvement)
- [DX] Consider extracting repeated logic into utility functions
- [TEST] Missing test coverage for edge cases
```

### 原则三：示例驱动——给出输入/输出对

大语言模型对示例的理解远超抽象描述。每个关键行为都应该附带完整的输入输出示例。

```markdown
## Output Format

When reporting issues, use this exact format:

### Example Output
```
⚠️ SECURITY [HIGH] src/api/users.ts:42
  Issue: SQL injection via string concatenation
  Code:   `query('SELECT * FROM users WHERE id = ' + userId)`
  Fix:    `query('SELECT * FROM users WHERE id = $1', [userId])`

ℹ️ STYLE [LOW] src/api/users.ts:78
  Issue: Function name doesn't match convention
  Code:   `function getUserData()`
  Fix:    `function fetchUser()` (use 'fetch' for API calls)
```
```

### 原则四：否定约束——明确禁止行为

告诉Claude不该做什么，和告诉它该做什么同样重要。否定约束可以防止常见的"过度热情"问题。

```markdown
## Constraints (DO NOT)

- DO NOT modify files outside the review scope
- DO NOT add new dependencies without explicit approval
- DO NOT rewrite working code to match personal style preferences
- DO NOT suggest changes that would break existing tests
- DO NOT output more than 20 issues per file (prioritize by severity)
```

### 原则五：变量外化——配置与逻辑分离

将所有可变参数集中到YAML variables中，使指令正文保持稳定和通用。

```yaml
variables:
  severity-threshold:
    type: enum
    values: [info, warn, error, critical]
    default: warn
    description: Minimum severity level to report
  max-issues-per-file:
    type: integer
    default: 20
    description: Maximum number of issues to report per file
  ignore-patterns:
    type: list
    default: ["*.test.ts", "*.spec.ts", "**/generated/**"]
    description: File patterns to exclude from review
```

```markdown
## Configuration
- Report severity: {{severity-threshold}} and above
- Max issues per file: {{max-issues-per-file}}
- Skip files matching: {{ignore-patterns}}
```

---

## 第四章 实战：构建API安全审查Skill

现在将上述全部知识应用到一个完整的实战项目中。我们将构建一个`api-security-reviewer` Skill，用于审查REST API端点的安全漏洞。

### 4.1 项目结构

```
~/.claude/skills/api-security-reviewer/
├── SKILL.md           # 主文件
└── references/
    └── owasp-top10.md  # 参考资料（可选）
```

### 4.2 完整SKILL.md

```markdown
---
name: api-security-reviewer
description: >
  Activate when reviewing API endpoint code for security vulnerabilities.
  Triggers on files in routes/, controllers/, api/, endpoints/ directories.
  Keywords: "security review", "API audit", "vulnerability scan", "pen test".
version: 1.0.0
auto-activate: true
allowed-tools:
  - Read
  - Grep
  - Glob
  - Edit
blocked-tools:
  - Bash
variables:
  language:
    description: Primary programming language of the API
    type: enum
    values: [typescript, python, go, java]
    default: typescript
  framework:
    description: Web framework being used
    type: string
    default: express
  severity-floor:
    description: Minimum severity level to report
    type: enum
    values: [info, low, medium, high, critical]
    default: medium
  report-format:
    description: Output format for findings
    type: enum
    values: [table, markdown, json]
    default: markdown
metadata:
  author: security-team
  tags: [security, api, owasp, review]
  license: MIT
---

# API Security Reviewer

## Activation Conditions

Activate this skill ONLY when:
- User explicitly requests a security review of API code
- User is editing files in routes/, controllers/, api/, or endpoints/ directories
- User mentions "security", "vulnerability", "OWASP", or "penetration test"

DO NOT activate when:
- User is writing frontend code
- User is modifying configuration files (docker-compose, CI/CD)
- User is working on documentation

## Review Checklist

### MUST Check (Block on finding)
1. **Injection (OWASP A03)**: All database queries use parameterized statements
2. **Authentication (OWASP A07)**: Every endpoint validates auth token before processing
3. **Access Control (OWASP A01)**: Role-based checks present for sensitive operations
4. **Input Validation**: Request body/params validated with schema (zod/joi/pydantic)

### SHOULD Check (Warn on finding)
5. **Rate Limiting**: Endpoints have appropriate rate limiting configured
6. **CORS**: Cross-origin headers are restrictive, not using wildcard `*`
7. **Error Handling**: Error responses don't leak stack traces or internal details
8. **Logging**: Security-relevant events are logged (auth failures, access denied)

### MAY Check (Suggest if time permits)
9. **HTTPS Enforcement**: API only accessible over HTTPS
10. **Response Headers**: Security headers present (X-Content-Type-Options, etc.)

## Language-Specific Rules

{{#if (eq language "typescript")}}
- Check for `any` type casts in request handlers
- Verify `express.json()` has size limits: `express.json({ limit: '10kb' })`
- Ensure `helmet` middleware is configured
{{/if}}

{{#if (eq language "python")}}
- Verify SQLAlchemy uses `text()` with parameters, not f-strings
- Check Flask/Django decorators for `@login_required` or `@permission_required`
- Ensure `CORS` configuration is restrictive
{{/if}}

{{#if (eq language "go")}}
- Check `sql.Query` uses `$1, $2` placeholders, not `fmt.Sprintf`
- Verify `jwt` token validation middleware is applied
- Ensure `http.Error` doesn't expose internal details
{{/if}}

## Output Format

{{#if (eq report-format "markdown")}}
### Example Output
```
## Security Review Report

**File**: `src/api/users.ts`
**Reviewed**: 2026-05-22
**Framework**: {{framework}}

### Findings

| # | Severity | Category | Line | Issue | Status |
|---|----------|----------|------|-------|--------|
| 1 | 🔴 CRITICAL | Injection | 42 | Raw SQL query via string concat | MUST FIX |
| 2 | 🟡 HIGH | Auth | 15 | Missing auth middleware | MUST FIX |
| 3 | 🟠 MEDIUM | Validation | 78 | No request body schema | SHOULD FIX |
| 4 | 🔵 LOW | CORS | 3 | Wildcard CORS header | SUGGESTED |

### Summary
- **Critical**: 1 | **High**: 1 | **Medium**: 1 | **Low**: 1
- **Security Score**: 45/100
- **Recommendation**: DO NOT deploy until critical and high issues are resolved.
```
{{/if}}

## Constraints (DO NOT)
- DO NOT modify production configuration files
- DO NOT add new npm/pip packages (only suggest)
- DO NOT write fixes automatically — present findings and let user decide
- DO NOT report issues below severity level: {{severity-floor}}
- DO NOT skip endpoints marked with `@skip-security-review` comment

## Severity Definitions
- **CRITICAL**: Exploitable remotely, no authentication required
- **HIGH**: Exploitable with valid user credentials
- **MEDIUM**: Requires specific conditions or internal access
- **LOW**: Best practice violation, limited attack surface
- **INFO**: Informational, no direct security impact
```

### 4.3 安装与验证

将Skill安装到项目中：

```bash
# 创建目录结构
mkdir -p your-project/.claude/skills/api-security-reviewer

# 将上面的SKILL.md内容写入文件
# 方式一：直接复制
cp SKILL.md your-project/.claude/skills/api-security-reviewer/

# 方式二：通过curl从远程仓库安装
mkdir -p your-project/.claude/skills
curl -sL https://example.com/skills/api-security-reviewer.tar.gz | tar xz -C your-project/.claude/skills/
```

验证Skill是否被加载：

```bash
# 在Claude Code中执行
claude

# 使用斜杠命令触发
/api-security-reviewer

# 或者让Claude自动检测
# 打开一个routes/目录下的文件，输入 "review this API endpoint for security issues"
```

### 4.4 预期效果

当你编辑`src/api/users.ts`并请求安全审查时，Skill会：

1. **自动激活**（因为文件在api/目录下）
2. **扫描整个文件**（使用Read工具）
3. **检查每个端点**对照OWASP清单
4. **按严重性排序输出**结果表格
5. **给出安全评分**和部署建议

### 4.5 常见问题

**Q: Skill没有被自动激活？**

检查以下几点：
1. `description`是否包含当前文件的路径模式
2. `auto-activate`是否设为`true`（默认值）
3. 文件夹名与`name`字段是否完全一致
4. SKILL.md是否在正确的目录层级

**Q: Skill没有使用限制的工具？**

`allowed-tools`和`blocked-tools`只是建议性约束，在当前版本中Claude会尽量遵守但不是强制的。如果需要严格限制，配合Claude Code的`--allowedTools`参数使用。

**Q: 变量默认值如何覆盖？**

通过对话中直接指定：
```
/api-security-reviewer language=python severity-floor=high
```

---

## 第五章 Skill测试方法论

### 5.1 三层测试框架

```mermaid
graph TB
    A[Skill测试金字塔] --> B[Layer 1: 加载验证]
    A --> C[Layer 2: 触发测试]
    A --> D[Layer 3: 行为验证]

    B --> B1[SKILL.md语法检查]
    B --> B2[文件夹名与name字段一致]
    B --> B3[YAML字段完整性]

    C --> C1[关键词触发测试]
    C --> C2[文件路径触发测试]
    C --> C3[显式命令触发测试]

    D --> D1[输出格式合规性]
    D --> D2[工具权限遵守]
    D --> D3[否定约束验证]
```

### 5.2 具体测试步骤

**第一层：加载验证**

```bash
# 检查Skill是否被Claude Code识别
claude --list-skills

# 手动验证YAML语法
python3 -c "
import yaml, sys
with open('.claude/skills/api-security-reviewer/SKILL.md') as f:
    content = f.read()
    parts = content.split('---')
    if len(parts) < 3:
        sys.exit('Missing YAML frontmatter')
    frontmatter = yaml.safe_load(parts[1])
    assert 'name' in frontmatter, 'Missing name field'
    assert 'description' in frontmatter, 'Missing description field'
    print('✓ YAML frontmatter valid')
    print(f'  name: {frontmatter[\"name\"]}')
    print(f'  description: {frontmatter[\"description\"][:50]}...')
"
```

**第二层：触发测试**

准备一个测试用例文件，然后验证Skill是否能被正确激活：

```bash
# 创建测试用例
cat > /tmp/test-api-route.ts << 'EOF'
import express from 'express';
const router = express.Router();

// This endpoint has intentional security issues for testing
router.post('/users', async (req, res) => {
  const { name, email } = req.body;
  const result = await db.query(
    `SELECT * FROM users WHERE email = '${email}'`
  );
  res.json(result);
});
EOF

# 在Claude Code中测试
claude
> Review /tmp/test-api-route.ts for security issues
# 预期：api-security-reviewer Skill被自动激活
```

**第三层：行为验证**

验证Skill的输出是否符合预期：
- 是否按严重性排序
- 是否使用了正确的输出格式
- 是否遵守了否定约束（如不自动修复）
- 是否检查了所有MUST级别的规则

### 5.3 反模式检测清单

| 反模式 | 表现 | 修复 |
|--------|------|------|
| 描述过长 | description超过5行 | 精简为2-3行，聚焦触发条件 |
| 指令过宽 | "Review all code" | 限定到具体文件类型和目录 |
| 缺少示例 | 只有抽象规则 | 每个关键行为附带输入/输出对 |
| 无否定约束 | Claude过度修改代码 | 添加DO NOT清单 |
| 变量硬编码 | 框架名写在正文里 | 提取到variables中 |

---

## 第六章 Skill分发与团队共享

### 6.1 三种分发路径

```mermaid
graph LR
    A[Skill开发完成] --> B{分发方式}
    B --> C[npm包]
    B --> D[Git仓库]
    B --> E[插件市场]

    C --> F[npm publish]
    C --> G[团队npm install]

    D --> H[Git submodule]
    D --> I[install脚本]

    E --> J[Plugin Marketplace]
    E --> K[一键安装]
```

### 6.2 方式一：npm包分发

适用于需要在多个项目间共享Skill的团队：

```json
// package.json
{
  "name": "@your-org/claude-skill-security",
  "version": "1.0.0",
  "files": [".claude/skills/**/SKILL.md"],
  "keywords": ["claude-code", "skill", "security"],
  "scripts": {
    "postinstall": "node scripts/install-skills.js"
  }
}
```

```javascript
// scripts/install-skills.js
const fs = require('fs');
const path = require('path');

const source = path.join(__dirname, '..', '.claude', 'skills');
const target = path.join(process.cwd(), '.claude', 'skills');

if (!fs.existsSync(target)) {
  fs.mkdirSync(target, { recursive: true });
}

fs.cpSync(source, target, { recursive: true });
console.log('✓ Skills installed to .claude/skills/');
```

安装：
```bash
npm install @your-org/claude-skill-security
```

### 6.3 方式二：Git仓库+安装脚本

适用于私有团队，无需发布到npm：

```bash
# 方式A：Git Submodule
git submodule add https://github.com/your-org/claude-skills.git .claude/skills-shared
ln -s .claude/skills-shared/api-security-reviewer .claude/skills/api-security-reviewer

# 方式B：curl一键安装
mkdir -p .claude/skills
curl -sL https://raw.githubusercontent.com/your-org/claude-skills/main/install.sh | bash
```

### 6.4 方式三：插件市场发布

Anthropic在2026年推出了官方插件市场，支持一键安装和版本管理：

```bash
# 发布到市场
claude plugin publish --skill api-security-reviewer

# 从市场安装
claude plugin install api-security-reviewer

# 搜索市场
claude plugin search "security review"
```

插件市场的Skill需要满足额外要求：
- 必须包含`version`字段
- 必须包含`metadata.license`
- 必须通过安全审核
- 必须有完整的description和示例

---

## 第七章 Skill生命周期全流程

```mermaid
flowchart TD
    A[需求分析] --> B[确定触发条件]
    B --> C[编写YAML frontmatter]
    C --> D[编写指令正文]
    D --> E[本地测试]
    E --> F{测试通过?}
    F -->|否| G[调试修复]
    G --> D
    F -->|是| H[团队Review]
    H --> I{Review通过?}
    I -->|否| J[根据反馈修改]
    J --> D
    I -->|是| K[选择分发方式]
    K --> L[npm / Git / 市场]
    L --> M[版本管理与迭代]

    style A fill:#4A90D9,color:#fff
    style E fill:#F5A623,color:#fff
    style K fill:#7ED321,color:#fff
    style M fill:#BD10E0,color:#fff
```

### 关键节点说明

**需求分析阶段**：明确三个问题——
1. 这个Skill解决什么问题？
2. 什么时候需要触发？
3. 需要哪些工具权限？

**本地测试阶段**：至少覆盖三种场景——
1. 正向触发（应该激活时是否激活）
2. 反向触发（不应该激活时是否沉默）
3. 边界条件（空输入、超长输入、无效参数）

**版本管理**：遵循SemVer——
- PATCH（1.0.x）：修Bug、优化指令措辞
- MINOR（1.x.0）：新增检查规则、新增变量
- MAJOR（x.0.0）：改变输出格式、删除检查规则

---

## 第八章 高级技巧与最佳实践

### 8.1 组合Skill

一个Skill可以依赖另一个Skill，形成链式调用：

```yaml
# .claude/skills/full-audit/SKILL.md
dependencies:
  skills:
    - name: api-security-reviewer
      version: ">=1.0.0"
    - name: performance-analyzer
```

```markdown
## Execution Flow
1. Run `api-security-reviewer` first
2. Collect security findings
3. Run `performance-analyzer` next
4. Merge results into unified audit report
```

### 8.2 条件化指令

利用变量实现条件化指令分支：

```yaml
variables:
  environment:
    type: enum
    values: [development, staging, production]
    default: development
```

```markdown
{{#if (eq environment "production")}}
## Production-Specific Rules
- ALL endpoints must have authentication
- ALL database queries must use connection pooling
- ALL responses must have security headers
{{else}}
## Development Relaxations
- Authentication may be optional for health check endpoints
- Detailed error messages are acceptable
{{/if}}
```

### 8.3 上下文窗口优化

Skill内容会被加载到上下文窗口中，因此控制Skill大小至关重要：

| 字段/段落 | 建议长度 | 原因 |
|-----------|---------|------|
| description | ≤200字符 | 避免触发判断延迟 |
| MUST规则 | ≤10条 | 过多规则降低遵守率 |
| 每条规则描述 | ≤2行 | 简洁才有执行力 |
| 示例 | 1-2个 | 过多示例浪费上下文 |
| 总SKILL.md | ≤3KB | 超过3KB考虑拆分 |

### 8.4 团队Skill治理

在企业环境中，建议建立Skill治理流程：

```
.claude/skills/
├── _registry.md       # Skill注册表（谁维护、最后更新时间）
├── api-security/
│   └── SKILL.md
├── code-style/
│   └── SKILL.md
└── test-coverage/
    └── SKILL.md
```

`_registry.md`示例：

```markdown
# Team Skill Registry

| Skill | Owner | Last Updated | Status | Version |
|-------|-------|-------------|--------|---------|
| api-security | @security-team | 2026-05-20 | Active | 1.2.0 |
| code-style | @frontend-team | 2026-05-15 | Active | 2.0.1 |
| test-coverage | @qa-team | 2026-05-10 | Beta | 0.3.0 |
```

---

## 延伸阅读

1. [Anthropic官方Skill文档](https://code.claude.com/docs/en/skills) — SKILL.md规范和创建指南的权威来源
2. [Anthropic Skill构建完整指南（PDF）](https://resources.anthropic.com/hubfs/The-Complete-Guide-to-Building-Skill-for-Claude.pdf) — 从规划到发布的官方完整教程
3. [anthropics/skills GitHub仓库](https://deepwiki.com/anthropics/skills/2.2-skill.md-format-specification) — 官方Skill格式规范与示例集合
4. [Claude Code Plugin Marketplace文档](https://code.claude.com/docs/en/plugin-marketplaces) — 插件市场创建和分发指南
5. [self.md Skill编写教程](https://self.md/guides/writing-skills-tutorial/) — 社区高质量的Skill编写实践指南

## 训练营适用性评估

| 维度 | 评估 |
|------|------|
| **适用训练营** | AI工具进阶营、DevSecOps训练营、团队效能提升营 |
| **教学时长** | 3-4小时（含实战） |
| **难度等级** | 中级（需先完成Claude Code入门） |
| **实操占比** | 60%（第五章实战为核心环节） |
| **前置课程** | Claude Code基础操作、Markdown/YAML基础 |
| **后续课程** | MCP服务器开发、多Agent编排、Skill组合设计模式 |

## 参考来源

1. [Extend Claude with skills — Claude Code Docs](https://code.claude.com/docs/en/skills) — Anthropic官方Skill文档，包含SKILL.md规范和完整API参考
2. [How to Build Claude Code Skills: 5 Examples — fp8.co](https://fp8.co/articles/Claude-Code-Skills-Complete-Developer-Guide) — 5个实战Skill示例，覆盖安全控制与插件分发
3. [SKILL.md Format Specification — DeepWiki/anthropics/skills](https://deepwiki.com/anthropics/skills/2.2-skill.md-format-specification) — 官方仓库的格式规范详解
4. [Claude Code Skill Frontmatter: Every YAML Option Explained — Allahabadi.dev](https://allahabadi.dev/blogs/ai/claude-code-skills-frontmatter-complete-guide/) — 15个YAML字段逐一解析，附示例和最佳实践
5. [How to Write Skills for Claude Code and Cowork — Sherlock](https://sherlock.xyz/post/how-to-write-skills-for-claude-code-and-cowork) — 实用的Skill编写教程，含frontmatter和工具权限示例

> [!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)
