首页 › tutorials › Claude Code Skill机制深潜:渐进披露到Hook闭环

Claude Code Skill机制深潜:渐进披露到Hook闭环

概述

本教程深入剖析Claude Code Skill的内部工作机制——渐进式披露(Progressive Disclosure)如何决定Skill的加载与激活,以及如何在Skill内集成Hook实现自动化闭环。适合已具备基本Claude Code使用经验、希望构建高质量自定义Skill的开发者。你将理解Skill从磁盘到执行的完整数据流,掌握精准触发的设计技巧,并完成一个具备Hook自动化的生产级Skill。

前置条件


第一步:理解渐进式披露架构

Claude Code 的 Skill 系统不是简单地把 Markdown 文件扔给 LLM,而是一个精心设计的两阶段加载架构。理解这个架构是写出高质量 Skill 的前提。

1.1 两阶段加载模型

sequenceDiagram
    participant User as 用户输入
    participant CC as Claude Code运行时
    participant FS as 文件系统
    participant LLM as Claude LLM

    Note over CC: 阶段一:元数据扫描(启动时)
    CC->>FS: 扫描 skills/ 目录
    FS-->>CC: 返回所有 SKILL.md 的 frontmatter
    CC->>LLM: 注入 <available_skills> 列表(仅name+description)

    Note over CC: 阶段二:按需加载(触发时)
    User->>CC: "帮我创建一个React组件"
    CC->>LLM: 匹配可用Skill
    LLM-->>CC: 选择 frontend-design Skill
    CC->>FS: 读取完整 SKILL.md + 辅助文件
    FS-->>CC: 返回完整指令内容
    CC->>LLM: 注入完整Skill上下文
    LLM-->>User: 按Skill指令执行任务

阶段一:元数据扫描。Claude Code 启动时扫描所有已安装的 Skill 目录,但只提取每个 SKILL.md 的 YAML frontmatter——即 name、description、trigger 等字段。这些信息被组装成一个精简的 <available_skills> 列表,注入到系统提示中。这意味着你的 Skill 在启动时只占用了极少的上下文窗口。

阶段二:按需加载。当用户的请求与某个 Skill 的描述匹配时,Claude Code 才会读取该 Skill 的完整 Markdown 内容、辅助脚本和模板文件,并将其注入到当前对话上下文中。

1.2 为什么要这样设计

这种设计的核心目标:在有限的上下文窗口中支持数百个 Skill。如果一次性加载所有 Skill 的完整内容,每个对话会消耗数万 Token,严重影响推理质量。渐进式披露让 100 个 Skill 的元数据只需要约 2000 Token,而完整内容仅在需要时才占用上下文。

关键推论:你的 description 字段是决定 Skill 能否被正确匹配的第一道关卡。它必须精确描述 Skill 的功能边界,既不能过于宽泛(导致误触发),也不能过于狭窄(导致漏触发)。


第二步:Skill 文件结构全景

一个完整的 Skill 可以是单文件,也可以是多文件包。以下是一个生产级 Skill 的推荐目录结构:

my-skill/
├── SKILL.md              # 主指令文件(必须)
├── helpers/              # 辅助脚本(可选)
│   ├── validate.sh       # 验证脚本
│   └── generate.py       # 生成脚本
├── templates/            # 模板文件(可选)
│   └── component.tsx.tpl # 代码模板
└── examples/             # 示例文件(可选)
    └── output-sample.ts  # 预期输出样例

2.1 SKILL.md 解剖

SKILL.md 由两部分组成:YAML frontmatter(元数据)和 Markdown body(指令内容)。

---
name: react-component-gen
description: >
  Generates production-ready React components with TypeScript,
  proper prop typing, and follows the team's design system.
  Use when the user asks to create, scaffold, or generate React
  components or UI elements.
trigger: 
  - "create react component"
  - "new react component"
  - "generate component"
  - "scaffold component"
---

# React Component Generator

## Instructions

You are a React component generator following our team conventions.

### Step 1: Analyze Requirements
- Parse the user's component description
- Identify required and optional props
- Determine if it needs state management

### Step 2: Generate Component
- Use TypeScript with strict typing
- Follow the template in templates/component.tsx.tpl
- Include proper JSDoc comments

### Step 3: Validate
- Run helpers/validate.sh to check the output
- Ensure all props are typed
- Verify naming conventions match `PascalCase`

2.2 Frontmatter 字段详解

根据 Anthropic 官方规范和社区实践,以下是最关键的字段及其用法:

字段 是否必须 作用 最佳实践
name 是 Skill 的唯一标识符 使用 kebab-case,如 react-component-gen
description 是 描述 Skill 功能,用于匹配触发 用自然语言描述触发场景,50-150字符
trigger 否 显式触发关键词列表 列出用户可能使用的短语,3-8个
disable-model-invocation 否 禁止自动激活 仅用于 /skill-name 手动调用的 Skill
hooks 否 定义生命周期钩子 用于 PreToolUse/PostToolUse 自动化
version 否 版本号 语义化版本,如 1.2.0
author 否 作者信息 用于市场展示
tags 否 分类标签 用于搜索和过滤

description 的写作公式:

好的 description 遵循这个模式:[做什么] + [技术栈/领域] + [何时触发]。

✅ 好:Generates production-ready React components with TypeScript.
     Use when creating or scaffolding React UI elements.

❌ 差:A skill for React.(过于宽泛,会在任何 React 相关对话中触发)

❌ 差:Creates a Button component with primary color variant.(过于具体,
     只有完全匹配的请求才会触发)

第三步:从零构建一个实战 Skill

我们将构建一个 Git Commit 规范守护 Skill——它会在每次提交前自动校验 commit message 是否符合 Conventional Commits 规范,如果不符合则给出修改建议。

3.1 创建 Skill 目录

# 在用户级 Skill 目录创建
mkdir -p ~/.claude/skills/commit-guard
cd ~/.claude/skills/commit-guard

Claude Code 的 Skill 发现路径按优先级排列:

  1. .claude/skills/ — 项目级(最高优先级)
  2. ~/.claude/skills/ — 用户级
  3. 通过 Plugin Marketplace 安装的 Skill

3.2 编写 SKILL.md

创建 ~/.claude/skills/commit-guard/SKILL.md:

---
name: commit-guard
description: >
  Enforces Conventional Commits specification for all git commits.
  Validates commit messages against type(scope): description format.
  Automatically activates when user asks to commit code or create
  a git commit message.
trigger:
  - "commit"
  - "git commit"
  - "create commit"
  - "commit message"
  - "make a commit"
hooks:
  PreToolUse:
    - match: "Bash"
      command: "echo 'Commit guard active: will validate message format'"
---

# Commit Guard — Conventional Commits Enforcer

## Overview

This skill ensures all commit messages follow the Conventional Commits
specification (v1.0.0). It validates messages before they are committed
and provides corrective suggestions when messages don't conform.

## Commit Message Format

All commit messages MUST follow this format:

():

[optional body]

[optional footer(s)]

## Allowed Types

| Type | Usage |
|------|-------|
| `feat` | A new feature |
| `fix` | A bug fix |
| `docs` | Documentation only changes |
| `style` | Changes that don't affect code meaning |
| `refactor` | Code change that neither fixes a bug nor adds a feature |
| `perf` | Performance improvement |
| `test` | Adding or correcting tests |
| `chore` | Build process or auxiliary tool changes |
| `ci` | CI/CD configuration changes |

## Validation Rules

When the user asks to commit, apply these checks IN ORDER:

1. **Format check**: Message matches `<type>(<scope>): <description>` pattern
2. **Type check**: Type is one of the allowed types listed above
3. **Case check**: Description starts with lowercase, no trailing period
4. **Length check**: First line is 72 characters or fewer
5. **Body check** (if present): Blank line separates subject from body

## Instructions

When creating or reviewing a commit message:

1. Analyze the staged changes using `git diff --staged`
2. Determine the most appropriate type based on the nature of changes
3. Auto-detect scope from affected file paths (e.g., `auth`, `api`, `ui`)
4. Generate a commit message following the format above
5. If the user provides their own message, validate it against all rules
6. If validation fails, explain the specific rule violated and suggest a fix
7. Never proceed with a non-conforming commit message

## Examples

### Valid commits:

feat(auth): add OAuth2 login support fix(api): handle null response from user endpoint docs: update API reference for v2 endpoints refactor(core): extract validation logic into shared module

### Invalid commits (do NOT allow):

Added new feature → Missing type prefix Feat: add login → Type must be lowercase fix(auth): Add login support. → Description starts uppercase + period fix: this is a very long description that exceeds the seventy-two character limit → Too long


3.3 预期行为

安装后,当你在 Claude Code 中说 "commit these changes" 或 "帮我提交代码",Skill 将被自动激活:

> 帮我提交代码

[commit-guard skill activated]

Analyzing staged changes...
- modified: src/auth/oauth.ts (+45, -3)
- modified: src/auth/types.ts (+12, -0)
- new file: tests/auth/oauth.test.ts (+87, -0)

Suggested commit message:
  feat(auth): add OAuth2 login support with PKCE flow

Changes include:
- OAuth2 authorization code flow with PKCE
- Token refresh mechanism
- Unit tests for auth module

3.4 常见问题

Q: Skill 安装后没有自动激活?

这是最常见的问题。排查步骤:

  1. 检查文件位置:确认 SKILL.md 在正确的 skills 目录中
  2. 检查 frontmatter 格式:YAML 必须严格遵循缩进规则,用 --- 包裹
  3. 验证 description 质量:用自然语言描述触发场景,包含 "when" 语句
  4. 手动测试:使用 /commit-guard 手动调用,确认 Skill 能被加载
  5. 查看日志:运行 claude --debug 查看Skill加载日志

Q: 多个 Skill 同时匹配怎么办?

Claude Code 会根据 description 与用户意图的语义相似度选择最匹配的 Skill。你可以在 description 中添加排除性描述来减少误触发,例如 "Use ONLY when... Do NOT use for..."。


第四步:Hook 集成——构建自动化闭环

Skill 的 Hook 机制是 2026 年初引入的强大功能,它让 Skill 能够在特定工具调用前后自动执行逻辑,实现真正的自动化闭环。

4.1 Hook 工作原理

flowchart LR
    A[用户请求] --> B[Claude Code 解析]
    B --> C{匹配到 Skill?}
    C -->|Yes| D[加载 Skill 指令]
    D --> E[LLM 决定调用工具]
    E --> F{工具匹配 Hook?}
    F -->|PreToolUse| G[执行前置 Hook]
    G --> H[执行工具]
    H --> I{PostToolUse Hook?}
    I -->|Yes| J[执行后置 Hook]
    J --> K[返回结果给 LLM]
    F -->|No| H
    I -->|No| K
    C -->|No| L[正常处理]

Hook 分为两种类型:

4.2 为 Commit Guard 添加 Hook

让我们升级 commit-guard Skill,添加自动格式检查 Hook:

---
name: commit-guard
description: >
  Enforces Conventional Commits specification for all git commits.
  Validates commit messages and prevents non-conforming commits.
  Automatically activates when user commits code or writes commit messages.
trigger:
  - "commit"
  - "git commit"
  - "create commit"
  - "commit message"
hooks:
  PreToolUse:
    - match: "Bash"
      command: |
        # 拦截 git commit 命令并校验消息格式
        INPUT="$CLAUDE_TOOL_INPUT"
        if echo "$INPUT" | grep -q "git commit"; then
          MSG=$(echo "$INPUT" | grep -oP '(?<=-m\s["\x27])[^\x27"]*' | head -1)
          if [ -n "$MSG" ]; then
            # 校验 Conventional Commits 格式
            if ! echo "$MSG" | grep -qP '^(feat|fix|docs|style|refactor|perf|test|chore|ci|build|revert)(\(.+\))?:\s.{1,72}'; then
              echo "BLOCK: Commit message does not follow Conventional Commits format."
              echo "Expected: <type>(<scope>): <description>"
              echo "Got: $MSG"
              exit 2
            fi
          fi
        fi
---

Hook 的环境变量:

Hook 执行时可以访问以下关键环境变量:

变量 内容 用途
CLAUDE_TOOL_INPUT 工具调用的输入参数 解析用户意图
CLAUDE_TOOL_NAME 被调用的工具名称 过滤特定工具
CLAUDE_SESSION_ID 当前会话 ID 跟踪上下文

4.3 Hook 的退出码语义

这个退出码设计使得 Hook 既能做"守门员"(拦截不合规操作),也能做"质检员"(验证执行结果)。


第五步:构建辅助文件体系

高质量的 Skill 通常包含辅助文件——模板、脚本、示例——它们在 SKILL.md 中被引用,在阶段二加载时一同注入上下文。

5.1 模板文件

创建 templates/commit-msg.tpl:

# <type>(<scope>): <short summary>
# 
# <longer description if needed>
#
# Allowed types: feat, fix, docs, style, refactor, perf, test, chore, ci
# Scope: module or component name (optional)
# Subject: lowercase, imperative mood, no period, ≤72 chars
# 
# Breaking changes: add BREAKING CHANGE: in footer
# Issues: add Refs: #123 in footer

5.2 验证脚本

创建 helpers/validate-commit.sh:

#!/usr/bin/env bash
# validate-commit.sh — 校验 commit message 是否符合 Conventional Commits 规范
set -euo pipefail

MSG="${1:?Usage: validate-commit.sh <commit-message>}"
ALLOWED_TYPES="feat|fix|docs|style|refactor|perf|test|chore|ci|build|revert"

# 规则1: 格式检查
if ! echo "$MSG" | head -1 | grep -qP "^($ALLOWED_TYPES)(\([^)]+\))?:\s.+"; then
  echo "FAIL: Invalid format. Expected <type>(<scope>): <description>"
  echo "  Allowed types: $ALLOWED_TYPES"
  exit 1
fi

# 规则2: 长度检查
FIRST_LINE=$(echo "$MSG" | head -1)
if [ ${#FIRST_LINE} -gt 72 ]; then
  echo "FAIL: First line exceeds 72 characters (${#FIRST_LINE} chars)"
  exit 1
fi

# 规则3: 大小写检查
DESC=$(echo "$MSG" | head -1 | sed 's/^[^:]*:\s*//')
if echo "$DESC" | grep -qP '^[A-Z]'; then
  echo "WARN: Description starts with uppercase (convention: lowercase)"
fi

if echo "$DESC" | grep -qP '\.$'; then
  echo "WARN: Description ends with period (convention: no trailing period)"
fi

echo "PASS: Commit message conforms to Conventional Commits v1.0.0"

5.3 在 SKILL.md 中引用辅助文件

在 SKILL.md 的指令部分添加引用:

## Validation Process

After generating a commit message, validate it by running:

\`\`\`bash
bash ~/.claude/skills/commit-guard/helpers/validate-commit.sh "<message>"
\`\`\`

Use the template at `~/.claude/skills/commit-guard/templates/commit-msg.tpl`
as the starting point for interactive commit message editing.

注意:辅助文件的路径在 SKILL.md 中引用时,Claude Code 会在需要时读取这些文件。建议使用绝对路径或相对于 Skill 目录的路径。


第六步:测试与迭代——Eval 驱动开发

Skill 开发的最大挑战不是写代码,而是验证 Skill 是否真的按预期工作。Anthropic 在 2026 年 3 月推出了 Skill Evals 系统,让这个过程变得可测量。

6.1 创建 Eval 文件

在 Skill 目录中创建 evals.json:

{
  "skill": "commit-guard",
  "evals": [
    {
      "name": "valid-feat-commit",
      "user_message": "commit these changes - I added a new login page",
      "expected_behavior": "Generates a commit message starting with 'feat' type",
      "should_trigger": true
    },
    {
      "name": "valid-fix-commit",
      "user_message": "fix the null pointer exception in user service",
      "expected_behavior": "Generates a commit message starting with 'fix' type",
      "should_trigger": true
    },
    {
      "name": "reject-bad-format",
      "user_message": "commit with message: added new feature",
      "expected_behavior": "Rejects the message and suggests Conventional Commits format",
      "should_trigger": true
    },
    {
      "name": "no-trigger-unrelated",
      "user_message": "explain how React hooks work",
      "expected_behavior": "Does NOT activate commit-guard skill",
      "should_trigger": false
    },
    {
      "name": "scope-detection",
      "user_message": "commit the auth module changes",
      "expected_behavior": "Includes 'auth' scope in commit message like feat(auth):",
      "should_trigger": true
    }
  ]
}

6.2 运行 Eval 测试

使用 Claude Code 内置的 Skill Creator 工具运行评估:

# 方法1:通过 Skill Creator 运行
claude "Use the skill-creator skill to evaluate commit-guard"

# 方法2:通过 /skill-creator 斜杠命令
# 在 Claude Code 交互模式中:
# /skill-creator evaluate commit-guard

6.3 Eval 驱动的迭代循环

flowchart TD
    A[编写初始 Skill] --> B[创建 Eval 测试集]
    B --> C[运行 Eval]
    C --> D{通过率 ≥ 90%?}
    D -->|No| E[分析失败案例]
    E --> F[优化 description / trigger / 指令]
    F --> C
    D -->|Yes| G[发布 Skill]
    G --> H[收集用户反馈]
    H --> I{有回归或新需求?}
    I -->|Yes| B
    I -->|No| J[维护模式]

关键指标:

社区数据显示,经过 3-5 轮 Eval 迭代的 Skill,触发准确率可以从初始的 40-50% 提升到 85-90%。

6.4 常见 Eval 失败模式与修复

失败模式 原因分析 修复方法
不触发 description 不够具体 添加 "Use when..." 语句
误触发 description 过于宽泛 添加 "Do NOT use for..." 排除语句
执行偏差 指令不够明确 添加分步骤的 Instructions
忽略规则 规则太多太复杂 精简到 5-7 条核心规则
上下文溢出 Skill 内容太长 拆分为多个 Skill 或精简内容

第七步:发布与分发

当你完成 Skill 开发和测试后,有三种主要的分发方式。

7.1 GitHub 仓库分发

最简单的方式——将 Skill 放在 GitHub 仓库中:

# 创建仓库
mkdir commit-guard-skill && cd commit-guard-skill
git init
# 复制 Skill 文件
cp -r ~/.claude/skills/commit-guard/* .
git add . && git commit -m "feat: initial commit-guard skill"
git remote add origin https://github.com/YOUR_USERNAME/commit-guard-skill.git
git push -u origin main

用户安装方式:

# 克隆到本地 skills 目录
git clone https://github.com/YOUR_USERNAME/commit-guard-skill.git \
  ~/.claude/skills/commit-guard

7.2 Plugin Marketplace 分发

通过 marketplace.json 配置文件创建插件市场:

{
  "name": "my-team-skills",
  "description": "Team skills for project XYZ",
  "skills": [
    {
      "name": "commit-guard",
      "source": "git+https://github.com/YOUR_USERNAME/commit-guard-skill.git",
      "path": "/"
    }
  ]
}

用户通过在项目中创建 .claude/marketplace.json 来订阅:

{
  "sources": [
    {
      "type": "git",
      "url": "https://github.com/YOUR_TEAM/skill-marketplace.git"
    }
  ]
}

7.3 npm 包分发

对于更复杂的 Skill(包含 Node.js 依赖),可以发布为 npm 包:

{
  "name": "@your-org/claude-skill-commit-guard",
  "version": "1.0.0",
  "description": "Conventional Commits enforcement skill for Claude Code",
  "main": "SKILL.md",
  "files": ["SKILL.md", "helpers/**", "templates/**"],
  "keywords": ["claude-code", "skill", "conventional-commits", "git"]
}

安装方式:

npm install @your-org/claude-skill-commit-guard --prefix ~/.claude/skills/commit-guard

完整工作流总览

flowchart TB
    subgraph 设计阶段
        A[确定 Skill 功能边界] --> B[编写 description + trigger]
        B --> C[设计 frontmatter 元数据]
    end

    subgraph 开发阶段
        C --> D[编写 SKILL.md 指令]
        D --> E[创建辅助文件]
        E --> F[集成 Hook 自动化]
    end

    subgraph 测试阶段
        F --> G[编写 Eval 测试集]
        G --> H[运行 Eval 评估]
        H --> I{通过率达标?}
        I -->|No| J[分析失败→优化 Skill]
        J --> H
        I -->|Yes| K[准备发布]
    end

    subgraph 发布阶段
        K --> L{分发方式?}
        L -->|GitHub| M[推送到仓库]
        L -->|Marketplace| N[创建 marketplace.json]
        L -->|npm| O[发布 npm 包]
    end

    subgraph 维护阶段
        M --> P[收集反馈]
        N --> P
        O --> P
        P --> Q{需要更新?}
        Q -->|Yes| G
        Q -->|No| R[稳定运行]
    end

进阶技巧

技巧一:Description 的"黄金三角"写法

最有效的 description 同时覆盖三个维度:

description: >
  [功能] Enforces Conventional Commits for git commits.
  [技术] Validates against type(scope): description format with 
         configurable allowed types.
  [触发] Use when committing code or writing commit messages.
         Do NOT use for git operations other than committing.

技巧二:利用 <SUBAGENT-STOP> 控制执行边界

当 Skill 被子 Agent(subagent)调度执行时,你可能不希望它被重复激活。使用 <SUBAGENT-STOP> 标签:

---
name: commit-guard
description: Enforces Conventional Commits.
---

<SUBAGENT-STOP>
If you were dispatched as a subagent to execute a specific task,
skip this skill and proceed with the task directly.
</SUBAGENT-STOP>

# Main Skill Instructions...

技巧三:多 Skill 协作时的优先级控制

当多个 Skill 可能同时匹配时,通过 description 的精确性来控制优先级:

# 优先级高(精确匹配)
description: >
  Generates React Native mobile components. Use ONLY when the user
  explicitly mentions React Native or mobile app UI.

# 优先级低(宽泛匹配)
description: >
  Generates React components for web applications. Use when creating
  any React component not specifically for React Native.

技巧四:Skill 内引用外部文档

对于需要大量参考内容的 Skill,不要把所有内容塞进 SKILL.md,而是引用外部文件:

## Reference Documentation

When working with authentication flows, refer to:
- OAuth2 spec: `~/.claude/skills/auth-guard/ref/oauth2-flows.md`
- Team conventions: `~/.claude/skills/auth-guard/ref/team-auth-standards.md`

Load these files ONLY when the specific topic is relevant to the task.

实战案例:完整的 commit-guard Skill 目录

最终的项目结构如下:

commit-guard/
├── SKILL.md                          # 主指令文件
├── helpers/
│   └── validate-commit.sh            # 格式校验脚本
├── templates/
│   └── commit-msg.tpl                # Commit 消息模板
├── examples/
│   ├── valid-commits.txt             # 有效 commit 示例
│   └── invalid-commits.txt           # 无效 commit 示例(附说明)
├── evals/
│   └── evals.json                    # Eval 测试集
└── README.md                         # 安装说明(可选)

安装验证:

# 1. 复制到 skills 目录
cp -r commit-guard ~/.claude/skills/

# 2. 重启 Claude Code 或新开对话
claude

# 3. 测试手动激活
> /commit-guard

# 4. 测试自动激活
> 帮我提交当前的代码变更
# 预期:Skill 自动激活,生成 Conventional Commits 格式的消息

# 5. 测试 Hook 拦截
> 用 git commit -m "added new feature" 提交
# 预期:Hook 拦截,提示格式不正确

延伸阅读


参考来源

  1. Skills Overview — Anthropic 官方文档 — Skill 系统架构和渐进式披露机制的权威说明
  2. Improving Skill Creator — Anthropic Blog — Skill Eval 测试系统的设计与使用方法
  3. Inside Claude Code Skills — Mikhail Shilkov — Skill 发现、加载和调用的内部技术分析
  4. Claude Code Skill Frontmatter 完整指南 — Allahabadi.dev — 15 个 YAML frontmatter 字段的逐一解析
  5. Build a Claude Skill: YAML Frontmatter — SJRamblings — SKILL.md 结构和测试的实战教程

[!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学通信知识星球海报-扫码加入