<!-- title: Skill质量工程：描述优化到触发率全实战 -->

# Claude Code Skill质量工程：从描述优化到触发率评估全实战

## 概述

本教程面向已有 Claude Code 基础使用经验的开发者，系统讲解如何构建高质量的 Skill——不只是能跑起来，而是能稳定触发、精准执行、低 Token 消耗。你将掌握 description 字段的触发工程、frontmatter 的七个控制维度、动态上下文注入的 `!` 语法、子代理隔离执行、支持文件的分层组织，以及一套可量化的 Skill 质量评估方法。学完后，你能让每个 Skill 的触发率从模糊的"偶尔命中"提升到可预测、可度量、可优化的工程化水平。

**适用人群**：已使用 Claude Code 超过一周、写过至少一个 SKILL.md 文件的开发者。

**前置条件**：
- Claude Code ≥ v2.1.145（`claude --version` 可查）
- 一个 Git 仓库（用于实战演练）
- 基本了解 YAML frontmatter 语法

---

## 第一章：为什么你的 Skill 总是不触发

### 1.1 渐进披露架构：理解 Skill 的加载机制

Claude Code 的 Skill 系统采用**渐进披露（Progressive Disclosure）**架构——这是理解所有后续优化策略的基础。

```mermaid
flowchart TD
    A[会话启动] --> B[扫描 Skill 目录]
    B --> C[仅加载 name + description<br/>~100 tokens/skill]
    C --> D[用户发送消息]
    D --> E{Claude 匹配 description<br/>与用户意图?}
    E -->|匹配| F[加载完整 SKILL.md 内容<br/>~1000-5000 tokens]
    E -->|不匹配| G[不加载任何内容<br/>0 tokens 消耗]
    F --> H[按需加载支持文件<br/>references/scripts]
    H --> I[执行 Skill 指令]

    style E fill:#f9f,stroke:#333,stroke-width:2px
    style G fill:#9f9,stroke:#333
```

这意味着：**description 字段是 Skill 的唯一入口**。Claude 在决策阶段只看到 description，不看正文。一个模糊的 description 意味着你的 Skill 永远不会被加载，无论正文写得多好。

### 1.2 最常见的五个触发失败原因

| 问题 | 错误示例 | 正确做法 |
|------|----------|----------|
| 描述是标签不是触发器 | `A skill for working with tests` | `Run the project's pytest suite when the user asks to run tests, check tests, or verify the test suite` |
| 缺少触发动词 | `Test helper` | `Execute, run, or check unit tests when asked about test results or coverage` |
| 描述太短 | `Code review` | `Review pull request changes for security vulnerabilities, performance issues, and code quality when the user asks to review, check PR, or audit code` |
| 包含营销语言 | `The ultimate powerful skill for amazing commits` | `Generate conventional commit messages when the user asks to commit, create a commit message, or stage changes` |
| 与已有 Skill 撞车 | 多个 Skill 描述中都含"code" | 用 `when_to_use` 字段区分触发场景 |

**诊断命令**：在 Claude Code 中输入 `/skills`，查看所有已注册 Skill 的 description 是否清晰。如果你的 Skill 没出现在列表中，说明路径或文件名有问题。

---

## 第二章：Frontmatter 七字段精准控制

### 2.1 完整字段一览

SKILL.md 的 YAML frontmatter 支持以下字段，每个字段控制 Skill 行为的不同维度：

```yaml
---
name: my-skill                    # 显示名称（默认取目录名）
description: >                    # 触发描述（最重要）
  What this skill does and when.
when_to_use: >                    # 补充触发上下文
  Additional trigger phrases.
argument-hint: "[issue-number]"   # 自动补全提示
arguments: [issue, branch]        # 命名参数映射
disable-model-invocation: true    # 禁止 Claude 自动触发
user-invocable: false             # 从 / 菜单隐藏
allowed-tools: Read Grep Bash     # 预授权工具列表
model: claude-sonnet-4-6          # Skill 执行时使用的模型
effort: high                      # 推理深度覆盖
context: fork                     # 在子代理中运行
agent: Explore                    # 指定子代理类型
hooks: {}                         # Skill 生命周期钩子
paths: "src/**/*.py"              # 路径匹配激活
shell: bash                       # Shell 类型
---
```

### 2.2 三条决策规则覆盖 90% 场景

```mermaid
flowchart LR
    A{谁决定何时运行?} -->|"我决定"| B["disable-model-invocation: true<br/>如 /deploy, /commit"]
    A -->|"Claude 决定"| C["默认行为<br/>如 lint-after-edit"]
    A -->|"纯背景知识"| D["user-invocable: false<br/>如 legacy-system-context"]

    style B fill:#f96,stroke:#333
    style C fill:#6f9,stroke:#333
    style D fill:#69f,stroke:#333
```

### 2.3 实战：一个带完整控制的部署 Skill

```bash
mkdir -p .claude/skills/deploy-prod
```

创建 `.claude/skills/deploy-prod/SKILL.md`：

```yaml
---
name: deploy-prod
description: >
  Deploy the application to production environment.
  Use ONLY when the user explicitly asks to deploy to production,
  push to prod, or release to production.
when_to_use: >
  Triggers on: "deploy to production", "push to prod",
  "release to production", "deploy prod"
disable-model-invocation: true
allowed-tools: Bash(docker *) Bash(kubectl *) Bash(git push *)
argument-hint: "[version-tag]"
---

## Deploy Production Workflow

Deploy version $ARGUMENTS to production:

1. **Pre-flight checks**
   Run `git status --porcelain` and abort if uncommitted changes exist.
   Run `docker build --dry-run .` to validate the build.

2. **Build and tag**
   Build the Docker image:
   ```bash
   docker build -t myapp:$ARGUMENTS .
   docker tag myapp:$ARGUMENTS myapp:latest
   ```

3. **Push to registry**
   ```bash
   docker push myapp:$ARGUMENTS
   docker push myapp:latest
   ```

4. **Deploy**
   ```bash
   kubectl set image deployment/myapp myapp=myapp:$ARGUMENTS
   kubectl rollout status deployment/myapp --timeout=300s
   ```

5. **Verify**
   Check health endpoint and report status.
   If rollout fails, run `kubectl rollout undo deployment/myapp`.
```

**关键设计**：
- `disable-model-invocation: true` — 防止 Claude 看到"代码看起来准备好了"就自动部署
- `allowed-tools` — 仅授权 docker/kubectl/git push 三类命令，其他操作需额外确认
- `$ARGUMENTS` — 版本号参数直接注入到指令中

---

## 第三章：Description 触发工程

### 3.1 触发器公式

一个高效的 description 遵循**三段式公式**：

```
[动词] + [任务描述] + [触发条件]
```

**动词**：Run, Generate, Create, Analyze, Review, Format, Deploy, Migrate
**任务描述**：具体做什么，涉及哪些文件/工具
**触发条件**：用户实际会输入的短语

### 3.2 Before/After 对比实验

以下是一个真实的优化过程。左侧是初始版本，右侧是优化后版本：

**版本 A（触发率约 30%）**：

```yaml
description: "A helpful skill for working with pull requests"
```

**版本 B（触发率约 75%）**：

```yaml
description: >
  Summarize pull request changes and generate PR descriptions.
  Use when the user asks to create a PR, write a PR description,
  summarize a pull request, or generate a PR body.
when_to_use: >
  Also triggers on: "pr summary", "pull request", "what changed",
  "describe this branch", "review my changes"
```

**版本 C（触发率约 90%+，使用动态注入）**：

```yaml
description: >
  Summarize pull request changes with live diff data and generate
  PR descriptions. Use when the user asks to create a PR, write
  a PR description, summarize changes, or review a pull request.
when_to_use: >
  Triggers on: "pr summary", "pull request", "what changed",
  "describe this branch", "review my changes", "pr body"
context: fork
agent: Explore
allowed-tools: Bash(gh pr *)
---
## PR Context
- Diff: !`gh pr diff`
- Files: !`gh pr diff --name-only`
- Comments: !`gh pr view --comments`

Generate a PR summary with:
- One paragraph overview
- Bullet list of changes
- Test plan checklist
```

### 3.3 when_to_use 的正确用法

`when_to_use` 是 description 的扩展字段，它被追加到 description 后面共同参与匹配。它的最佳用途是**列举触发短语**——用户实际会输入的自然语言：

```yaml
when_to_use: >
  Triggers when user says: "run tests", "check if tests pass",
  "run the test suite", "verify tests", "are tests green",
  "test coverage", "run pytest"
```

注意：description + when_to_use 合计在 Skill 列表中被截断至 **1,536 字符**。超出部分被丢弃，所以关键触发词必须放在前面。

---

## 第四章：动态上下文注入 — `!` 语法详解

### 4.1 工作原理

`!` 语法是 Skill 系统最强大的特性之一。它允许你在 Skill 加载前**预执行 Shell 命令**，将输出直接注入到 Skill 内容中。Claude 看到的是命令的**输出结果**，而非命令本身。

```mermaid
sequenceDiagram
    participant U as 用户
    participant CC as Claude Code
    participant S as Shell
    participant C as Claude

    U->>CC: /pr-summary
    CC->>CC: 匹配 Skill description
    CC->>S: 执行 !`gh pr diff`
    S-->>CC: 返回 diff 输出
    CC->>S: 执行 !`gh pr view --comments`
    S-->>CC: 返回评论内容
    CC->>C: 发送渲染后的 SKILL.md<br/>（含实际 diff 数据）
    C-->>U: 基于 live 数据的 PR 总结
```

### 4.2 内联语法 vs 代码块语法

**内联语法**（单行命令）：

```markdown
当前工作区差异：
!`git diff HEAD`

当前分支名：
!`git branch --show-current`
```

注意：`!` 必须出现在行首或紧跟在空格之后。`KEY=!`cmd`` 不会被识别为命令。

**代码块语法**（多行命令）：

````markdown
```!
node --version
npm --version
git status --short
git log --oneline -5
```
````

### 4.3 实战：构建实时代码审查 Skill

```bash
mkdir -p ~/.claude/skills/live-review
```

创建 `~/.claude/skills/live-review/SKILL.md`：

```yaml
---
name: live-review
description: >
  Perform a real-time code review of current uncommitted changes.
  Use when the user asks to review changes, check their code,
  review the diff, or asks "does this look right?"
allowed-tools: Read Grep Bash(git *)
---

## Current Working Tree

### Changed files
!`git diff --name-only`

### Full diff
!`git diff HEAD`

### Recent commits for context
!`git log --oneline -10`

## Review Instructions

Review the changes above across these five dimensions:

### 1. Correctness (CRITICAL)
- Logic errors or off-by-one bugs
- Null/undefined handling
- Edge case coverage

### 2. Security (CRITICAL)
- Input validation gaps
- SQL injection / XSS risks
- Hardcoded secrets or credentials

### 3. Performance (MAJOR)
- Algorithm complexity issues
- N+1 query patterns
- Unnecessary re-renders or computations

### 4. Code Quality (MINOR)
- Naming conventions
- Function length
- DRY violations

### 5. Suggestions (INFO)
- Alternative approaches
- Documentation improvements

## Output Format

For each finding, provide:
- **[SEVERITY]** Title
- File: `path/to/file:line_number`
- Issue: description
- Fix: code example

If no issues found, highlight good practices observed.
```

**效果**：每次你输入 `/live-review` 或说"review my changes"，Claude 会先获取实时 diff、最近提交历史，然后基于真实数据给出审查结果——而非基于猜测。

### 4.4 安全注意事项

`!` 语法会执行任意 Shell 命令。企业环境中，管理员可通过 `settings.json` 设置全局禁用：

```json
{
  "disableSkillShellExecution": true
}
```

启用后，所有 `!` 命令被替换为 `[shell command execution disabled by policy]`。

---

## 第五章：支持文件分层组织

### 5.1 目录结构规范

一个成熟的 Skill 不只是一个 SKILL.md。合理的文件组织能降低 Token 消耗、提升可维护性：

```
my-skill/
├── SKILL.md              # 核心指令（必需，≤500行）
├── reference.md          # 详细参考文档（按需加载）
├── examples.md           # 输出示例（按需加载）
├── templates/
│   └── output.html       # 输出模板
├── scripts/
│   ├── validate.sh       # 可执行脚本
│   └── analyze.py        # 数据分析脚本
└── tests/
    └── test-cases.md     # 测试场景描述
```

### 5.2 在 SKILL.md 中引用支持文件

关键是**告诉 Claude 每个文件的用途和何时加载**：

```markdown
## Additional Resources

- For complete API parameter reference, see [reference.md](reference.md)
- For example outputs showing expected format, see [examples.md](examples.md)
- For the validation script, run `bash ${CLAUDE_SKILL_DIR}/scripts/validate.sh`
```

`${CLAUDE_SKILL_DIR}` 变量解析为 Skill 目录的绝对路径，无论 Skill 安装在哪个层级（个人/项目/插件）都能正确引用。

### 5.3 Token 预算管理

当 Skill 被触发后，其内容在整个会话中持续占用 Token。自动压缩（Auto-compaction）时，系统会保留每个最近触发 Skill 的前 5,000 tokens，所有 Skill 共享 25,000 tokens 的总预算。

**优化策略**：

1. **SKILL.md 保持精简**：核心指令 ≤ 200 行，详细参考移到 `reference.md`
2. **使用 `context: fork`**：对于重量级 Skill（如全项目搜索），在子代理中运行，不占用主会话 Token
3. **避免重复触发**：一个 Skill 在会话中只需触发一次，后续 Claude 记得其内容
4. **大文件延迟加载**：只在 SKILL.md 中写引导，实际内容通过支持文件按需提供

---

## 第六章：`context: fork` — 子代理隔离执行

### 6.1 适用场景

并非所有 Skill 都需要在主会话中运行。当任务满足以下条件时，使用 `context: fork`：

| 特征 | 主会话运行 | 子代理运行 (fork) |
|------|-----------|-------------------|
| 任务类型 | 交互式、需要用户确认 | 自包含、可独立完成 |
| 上下文依赖 | 需要对话历史 | 只需 Skill 内容 |
| Token 消耗 | 持续占用主会话 | 执行完即释放 |
| 输出形式 | 流式、可中断 | 完成后一次性返回 |
| 典型场景 | 提交消息、代码审查 | 项目搜索、数据分析、文档生成 |

### 6.2 内置子代理类型

Claude Code 提供三种内置子代理：

- **`Explore`**：只读工具（Glob/Grep/Read），适合代码搜索和分析。**注意：Explore 代理不加载 CLAUDE.md**，保持上下文最小化
- **`Plan`**：架构规划代理，用于设计实现方案。同样不加载 CLAUDE.md
- **`general-purpose`**：通用代理，拥有所有工具，加载 CLAUDE.md

### 6.3 实战：构建深度研究 Skill

```bash
mkdir -p ~/.claude/skills/deep-research
```

创建 `~/.claude/skills/deep-research/SKILL.md`：

```yaml
---
name: deep-research
description: >
  Research a topic thoroughly across the codebase using file search,
  code analysis, and cross-reference. Use when the user asks to
  research, investigate, analyze architecture, or understand how
  something works in the codebase.
context: fork
agent: Explore
argument-hint: "[topic]"
allowed-tools: Read Glob Grep
---

## Research Task

Research the following topic thoroughly: $ARGUMENTS

## Research Methodology

1. **Discovery Phase**
   - Use Glob to find all relevant files matching the topic
   - Use Grep to search for key terms and patterns
   - Identify the core modules and their relationships

2. **Analysis Phase**
   - Read the most relevant files completely
   - Trace data flow and control flow
   - Identify design patterns and architectural decisions

3. **Synthesis Phase**
   - Summarize findings with specific file references
   - Map component dependencies
   - Identify potential issues or improvement areas

## Output Format

### Summary
2-3 sentence overview of findings.

### Key Files
- `path/to/file:line` — what this file does

### Architecture
Description of how components relate.

### Recommendations
Any issues or improvements discovered.
```

**运行方式**：`/deep-research "authentication flow"` — Claude 会创建一个隔离的 Explore 子代理，在独立上下文中搜索整个代码库，完成后将结果摘要返回主会话。

---

## 第七章：参数传递与变量替换

### 7.1 四种变量类型

Skill 支持四种变量替换机制，在 Skill 内容被发送给 Claude 之前完成替换：

| 变量 | 说明 | 示例 |
|------|------|------|
| `$ARGUMENTS` | 所有参数 | `/fix 123` → `123` |
| `$N` / `$ARGUMENTS[N]` | 按位置取参数 | `/migrate SearchBar React Vue` → `$0`=SearchBar |
| `$name` | 命名参数（需 frontmatter 声明） | `arguments: [issue, branch]` |
| `${CLAUDE_*}` | 系统变量 | `${CLAUDE_SESSION_ID}`、`${CLAUDE_SKILL_DIR}` |

### 7.2 实战：Issue 修复 Skill

```bash
mkdir -p ~/.claude/skills/fix-issue
```

创建 `~/.claude/skills/fix-issue/SKILL.md`：

```yaml
---
name: fix-issue
description: >
  Fix a GitHub issue by number. Use when the user asks to fix,
  resolve, or address a GitHub issue.
disable-model-invocation: true
argument-hint: "[issue-number]"
allowed-tools: Bash(gh *) Read Grep Edit Write
---

## Fix GitHub Issue $ARGUMENTS

### Step 1: Read the issue

```bash
gh issue view $ARGUMENTS
```

Understand the problem, expected behavior, and any reproduction steps.

### Step 2: Locate relevant code

Search the codebase for files related to the issue description.
Use Grep and Glob to find the relevant modules.

### Step 3: Implement the fix

- Read the relevant files completely before making changes
- Make minimal, targeted changes to address the issue
- Do not refactor surrounding code unless directly related

### Step 4: Write tests

Add or update tests that verify the fix:
- Test the specific scenario described in the issue
- Cover edge cases mentioned in the issue
- Ensure existing tests still pass

### Step 5: Commit and link

Create a commit with message:
`fix: resolve #$ARGUMENTS — [brief description]`
```

**调用**：`/fix-issue 42` — 参数 `42` 替换所有 `$ARGUMENTS` 占位符。

**多参数示例**：`/migrate SearchBar React Vue` — 需要 frontmatter 中声明 `arguments: [component, from, to]`，然后 `$component` = SearchBar、`$from` = React、`$to` = Vue。

---

## 第八章：路径匹配与条件激活

### 8.1 `paths` 字段

`paths` 字段允许你限定 Skill 仅在操作特定路径的文件时激活。这对 monorepo 或多语言项目特别有用：

```yaml
---
name: python-linter
description: Run Python linter on modified files
paths: "src/**/*.py, tests/**/*.py"
allowed-tools: Bash(ruff *) Read
---
```

当用户编辑的文件匹配 `src/**/*.py` 或 `tests/**/*.py` 时，Claude 才会考虑触发此 Skill。编辑 `.ts` 文件时，此 Skill 完全不可见。

### 8.2 `skillOverrides` 精细控制

在 `settings.json` 或 `.claude/settings.local.json` 中，可以用 `skillOverrides` 覆盖 Skill 的可见性：

```json
{
  "skillOverrides": {
    "legacy-context": "name-only",
    "deploy-prod": "off",
    "code-reviewer": "user-invocable-only"
  }
}
```

| 值 | Claude 可见 | / 菜单可见 | 说明 |
|----|------------|-----------|------|
| `"on"` | 完整 description | 是 | 默认行为 |
| `"name-only"` | 仅名称 | 是 | 降低 Token 消耗 |
| `"user-invocable-only"` | 隐藏 | 是 | 仅手动触发 |
| `"off"` | 隐藏 | 隐藏 | 完全禁用 |

---

## 第九章：完整实战项目 — Git 工作流 Skill 套件

### 9.1 项目结构

以下是一套三个协作 Skill，覆盖日常 Git 工作流：

```
.claude/skills/
├── smart-commit/
│   └── SKILL.md          # 智能提交
├── pr-ready/
│   └── SKILL.md          # PR 就绪检查 + 描述生成
└── branch-status/
    └── SKILL.md          # 分支状态报告
```

### 9.2 Skill 1：Smart Commit

```yaml
# .claude/skills/smart-commit/SKILL.md
---
name: smart-commit
description: >
  Generate a conventional commit message from staged changes and
  create the commit. Use when the user asks to commit, create a
  commit message, stage and commit, or make a commit.
disable-model-invocation: true
allowed-tools: Bash(git add *) Bash(git commit *) Bash(git status *) Bash(git diff *)
---

## Staged Changes Analysis

### Status
!`git status --short`

### Staged Diff
!`git diff --cached`

### Recent Commit Style
!`git log --oneline -5`

## Instructions

1. Analyze the staged diff above
2. Determine the commit type:
   - `feat:` new feature
   - `fix:` bug fix
   - `refactor:` code restructuring
   - `docs:` documentation only
   - `test:` test additions
   - `chore:` build/tooling changes
3. Identify the scope (module or component affected)
4. Generate commit message following these rules:
   - Subject: `<type>(<scope>): <imperative description>` (≤50 chars)
   - Body: explain WHY, not what (wrap at 72 chars)
   - Footer: breaking changes, issue references
5. Create the commit with the generated message
6. Report what was committed

If no changes are staged, run `git status` and ask the user
what to stage before proceeding.
```

### 9.3 Skill 2：PR Ready

```yaml
# .claude/skills/pr-ready/SKILL.md
---
name: pr-ready
description: >
  Check if the current branch is ready for a pull request and
  generate the PR description. Use when the user asks to create
  a PR, check PR readiness, or generate a PR body.
disable-model-invocation: true
allowed-tools: Bash(git *) Bash(gh pr *)
---

## Branch Context

### Branch name
!`git branch --show-current`

### Commits since main
!`git log main..HEAD --oneline`

### Full diff against main
!`git diff main...HEAD --stat`

### Test status
!`npm test 2>&1 | tail -20 || echo "No test command found"`

## PR Readiness Checklist

Check each item and report status:

1. [ ] All commits follow conventional format
2. [ ] No debug code or console.log remaining
3. [ ] Tests are passing
4. [ ] No merge conflicts with main
5. [ ] No large files accidentally committed

## PR Description Template

Generate the PR description:

## Summary
[One paragraph, no marketing language]

## Changes
- [One bullet per logical change, not per commit]

## Test plan
- [ ] [Specific test a reviewer can run]

## Screenshots (if applicable)

## Breaking changes
[None / List any breaking changes]
```

### 9.4 Skill 3：Branch Status

```yaml
# .claude/skills/branch-status/SKILL.md
---
name: branch-status
description: >
  Show current branch status including uncommitted changes,
  commits ahead/behind main, and stashed changes. Use when the
  user asks about branch status, what changed, or current state.
allowed-tools: Bash(git *)
---

## Branch Status Report

### Current branch
!`git branch --show-current`

### Uncommitted changes
!`git status --short`

### Ahead/behind main
!`git rev-list --left-right --count main...HEAD`

### Stashed changes
!`git stash list`

### Recent commits
!`git log --oneline -10 --decorate --graph`

## Instructions

Provide a concise status summary:
1. Which branch you're on
2. How many uncommitted changes (staged vs unstaged)
3. How far ahead/behind main
4. Any stashes
5. Recent commit activity

Highlight anything that needs attention:
- Uncommitted changes in critical files
- Branch significantly behind main
- Stale branches
```

### 9.5 三个 Skill 的协作流程

```mermaid
flowchart LR
    A[编码完成] --> B["/branch-status<br/>查看当前状态"]
    B --> C["/smart-commit<br/>生成规范提交"]
    C --> D[更多修改?]
    D -->|是| A
    D -->|否| E["/pr-ready<br/>PR就绪检查"]
    E --> F[创建 Pull Request]

    style A fill:#69f,stroke:#333
    style C fill:#f96,stroke:#333
    style E fill:#9f6,stroke:#333
```

---

## 第十章：Skill 质量评估框架

### 10.1 五维度质量评估

一个高质量的 Skill 需要在以下五个维度达标：

| 维度 | 评估方法 | 达标标准 |
|------|----------|----------|
| **触发率** | 用 10 条不同措辞的用户输入测试 | ≥ 8/10 命中 |
| **执行精度** | 检查输出是否符合 Skill 指令 | 核心步骤 100% 执行 |
| **Token 效率** | 检查 SKILL.md 行数和加载频率 | ≤ 200 行核心内容 |
| **边界处理** | 测试空输入、无效参数、异常场景 | 不崩溃、有明确错误提示 |
| **隔离性** | 与其他 Skill 同时触发是否冲突 | 无相互干扰 |

### 10.2 触发率测试方法

```mermaid
flowchart TD
    A[编写 Skill] --> B[准备 10 条测试输入]
    B --> C{每条输入<br/>是否触发?}
    C -->|是| D[记录命中]
    C -->|否| E[记录失败]
    D --> F{命中率 ≥ 80%?}
    E --> F
    F -->|是| G[✅ 通过]
    F -->|否| H[优化 description]
    H --> B

    style G fill:#6f9,stroke:#333
    style H fill:#f96,stroke:#333
```

**以 `smart-commit` Skill 为例，准备 10 条测试输入**：

| # | 用户输入 | 预期结果 | 实际结果 |
|---|----------|----------|----------|
| 1 | "commit these changes" | ✅ 触发 | 记录 |
| 2 | "create a commit" | ✅ 触发 | 记录 |
| 3 | "commit message for this" | ✅ 触发 | 记录 |
| 4 | "stage and commit" | ✅ 触发 | 记录 |
| 5 | "make a git commit" | ✅ 触发 | 记录 |
| 6 | "write a commit message" | ✅ 触发 | 记录 |
| 7 | "save my work" | ❌ 不应触发 | 记录 |
| 8 | "push to remote" | ❌ 不应触发 | 记录 |
| 9 | "what did I change" | ❌ 不应触发 | 记录 |
| 10 | "git add all and commit" | ✅ 触发 | 记录 |

如果测试 7-9 触发了，说明 description 过于宽泛，需要收窄。如果测试 1-6 有未触发的，说明 description 需要补充更多触发短语。

### 10.3 常见质量问题速查表

| 症状 | 根因 | 修复方案 |
|------|------|----------|
| Skill 从不触发 | description 太模糊或为空 | 用三段式公式重写 |
| Skill 触发了但不按指令执行 | 正文太长，Claude 忽略了后半段 | 精简到 200 行以内 |
| 触发了错误的 Skill | description 与其他 Skill 重叠 | 加 `when_to_use` 区分 |
| Skill 只在手动 `/name` 时触发 | 缺少触发动词或 `disable-model-invocation: true` | 检查 frontmatter |
| 执行后 Skill 效果在后续轮次消失 | 内容被 auto-compaction 截断 | 精简内容或重新触发 |
| 添加新 Skill 后旧 Skill 失效 | 目录名冲突或 Skill 路径错误 | 检查优先级：project > personal |
| `!` 命令不执行 | 语法错误（`!` 未在行首） | 确保 `!` 出现在行首或空格后 |
| `$ARGUMENTS` 未替换 | Skill 未接收参数 | 检查调用方式是否传参 |

---

## 第十一章：企业级分发策略

### 11.1 四层分发层级

```mermaid
flowchart TB
    A[Enterprise<br/>企业级<br/>全员强制] --> B[Plugin<br/>插件级<br/>按需安装]
    B --> C[Personal<br/>个人级<br/>~/.claude/skills/]
    C --> D[Project<br/>项目级<br/>.claude/skills/]

    A -.- E["Managed Settings<br/>组织管理员配置"]
    B -.- F["/plugin install<br/>或 curl 安装"]
    C -.- G["个人目录<br/>跨项目可用"]
    D -.- H["Git 版本控制<br/>团队共享"]
```

**优先级规则**：Enterprise > Personal > Project。同名 Skill 高层级覆盖低层级。插件 Skill 使用 `plugin-name:skill-name` 命名空间，不会冲突。

### 11.2 团队共享最佳实践

1. **项目 Skill 提交到 Git**：`.claude/skills/` 下的文件天然适合版本控制，让每个团队成员自动获得
2. **敏感操作加 `disable-model-invocation: true`**：防止 Claude 未经确认执行部署等操作
3. **用 `allowed-tools` 限制权限**：项目 Skill 在用户信任工作区后才生效，但仍建议显式声明所需工具
4. **通过 `skillOverrides` 管理冲突**：团队成员可在 `.claude/settings.local.json` 中覆盖全局 Skill 的可见性

### 11.3 插件分发

将 Skill 打包为插件可以实现跨项目、跨团队的标准化分发：

```bash
# 从插件市场安装
/plugin install frontend-design@anthropic-agent-skills

# 添加第三方市场
/plugin marketplace add agensi

# curl 一键安装
mkdir -p ~/.claude/skills && curl -sL https://www.agensi.io/api/install/SKILL_SLUG | tar xz -C ~/.claude/skills/
```

---

## 延伸阅读

- [Anthropic 官方 Skills 文档](https://code.claude.com/docs/en/skills) — 最权威的 SKILL.md 规范和 frontmatter 字段参考
- [fp8.co: How to Build Claude Code Skills](https://fp8.co/articles/Claude-Code-Skills-Complete-Developer-Guide) — 5 个完整 Skill 示例，覆盖提交、测试、文档、审查
- [DEV.to: Claude Code Skills Practical Guide 2026](https://dev.to/muhammad_moeed/claude-code-skills-a-practical-guide-for-2026-3f6p) — Skills vs Slash Commands vs Subagents 的清晰对比
- [BuildFast with AI: Claude Skills Complete 2026 Guide](https://www.buildfastwithai.com/blogs/claude-skills-complete-guide-2026) — 安装方法、10 大推荐 Skill、MCP 对比
- [Anthropic Hooks 文档](https://code.claude.com/docs/en/hooks) — Skill 生命周期钩子的完整配置参考

---

## 训练营适用性评估

| 维度 | 评估 |
|------|------|
| **适合训练营类型** | Claude Code 进阶训练营、AI 工程化工作坊 |
| **预计教学时长** | 4-5 小时（含实操演练） |
| **学员基础要求** | 已完成 Claude Code 基础入门，至少创建过 1 个 Skill |
| **实操占比** | 60%（7 个动手练习：描述优化、动态注入、子代理、参数传递、路径匹配、完整套件、质量测试） |
| **所需环境** | 每人一个 Git 仓库 + Claude Code v2.1.145+ + gh CLI |

## 参考来源
1. [Extend Claude with skills — Anthropic 官方文档](https://code.claude.com/docs/en/skills) — SKILL.md 规范、frontmatter 字段、动态注入、子代理执行等核心参考
2. [How to Build Claude Code Skills: 5 Examples — fp8.co](https://fp8.co/articles/Claude-Code-Skills-Complete-Developer-Guide) — 完整 Skill 示例（提交、测试、文档、审查）及最佳实践
3. [Claude Code Skills: A Practical Guide for 2026 — DEV.to](https://dev.to/muhammad_moeed/claude-code-skills-a-practical-guide-for-2026-3f6p) — Skills 架构解析、触发机制、与 Subagent 对比
4. [Claude Skills: The Complete 2026 Guide — BuildFast with AI](https://www.buildfastwithai.com/blogs/claude-skills-complete-guide-2026) — 安装方法、Skill Creator 工具、市场生态、MCP 对比
5. [Hooks Reference — Anthropic 官方文档](https://code.claude.com/docs/en/hooks) — 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 等场景全覆盖。

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