首页 › tutorials › Claude Code Skill调试六层诊断实战

概述

本教程面向已具备基础 Skill 编写经验的 Claude Code 用户,系统性讲解 Skill 调试的六层诊断框架——从 YAML 语法校验、触发发现、上下文加载、Token 预算、行为验证到集成交互。学完后,你将能独立定位并修复 Skill 在开发、部署、运行阶段的各类疑难问题。适用人群:Claude Code 日常使用者、Skill 开发者、团队工具链维护者。

前置条件


第零步:建立调试心智模型

在动手修复之前,先理解 Skill 在 Claude Code 内部的完整生命周期。一次 Skill 调用经过六个阶段,每个阶段都可能出错:

flowchart TD
    A[用户输入消息] --> B{Skill 发现与匹配}
    B -->|匹配成功| C[解析 YAML Frontmatter]
    B -->|匹配失败| X1[❌ Layer 2: 触发诊断]
    C -->|语法正确| D[加载 Skill 指令到上下文]
    C -->|语法错误| X2[❌ Layer 1: 结构诊断]
    D -->|Token 预算充足| E[模型执行 Skill 逻辑]
    D -->|超出预算| X3[❌ Layer 3/4: 上下文诊断]
    E -->|输出符合预期| F[Skill 执行完成]
    E -->|输出异常| X4[❌ Layer 5: 行为诊断]
    F --> G{是否与其他 Skill/MCP 交互?}
    G -->|是且正常| H[✅ 全链路通过]
    G -->|是且异常| X5[❌ Layer 6: 集成诊断]
    G -->|否| H

核心原则:逐层排查,从最底层的语法到最高层的集成。不要跳层——90% 的"Skill 不工作"问题都出在前三层。


Layer 1:语法与结构校验

1.1 常见错误清单

YAML frontmatter 是 Skill 的"身份证",任何一个字段拼写错误都会导致静默失败:

错误类型 症状 诊断方法
name 字段缺失 Skill 不被发现 Claude Code 启动时无任何提示
description 过长(>200字符) 匹配精度下降 对比相似 Skill 的描述长度
--- 分隔符缺失 整个文件被视为指令 Skill 列表中不出现
YAML 缩进错误 解析失败或字段丢失 使用 yamllint 验证
特殊字符未转义 部分内容截断 检查 description 中的 :, #

1.2 快速校验脚本

创建一个 Shell 脚本,在每次保存 Skill 后自动检查语法:

#!/bin/bash
# skill-lint.sh - Skill 语法校验工具
SKILL_DIR="${1:-$HOME/.claude/skills}"

echo "=== Skill 语法校验 ==="
errors=0

for skill_file in $(find "$SKILL_DIR" -name "SKILL.md" -type f); do
    skill_name=$(basename $(dirname "$skill_file"))

    # 检查1: frontmatter 分隔符
    if ! head -1 "$skill_file" | grep -q "^---"; then
        echo "❌ [$skill_name] 缺少 YAML frontmatter 分隔符 ---"
        errors=$((errors + 1))
        continue
    fi

    # 检查2: 提取并验证 frontmatter
    fm_end=$(grep -n "^---" "$skill_file" | sed -n '2p' | cut -d: -f1)
    if [ -z "$fm_end" ]; then
        echo "❌ [$skill_name] frontmatter 未闭合(缺少第二个 ---)"
        errors=$((errors + 1))
        continue
    fi

    # 提取 frontmatter 内容
    fm_content=$(head -n $((fm_end - 1)) "$skill_file" | tail -n +2)

    # 检查3: 必填字段
    for field in "name" "description"; do
        if ! echo "$fm_content" | grep -q "^${field}:"; then
            echo "❌ [$skill_name] 缺少必填字段: $field"
            errors=$((errors + 1))
        fi
    done

    # 检查4: description 长度
    desc=$(echo "$fm_content" | grep "^description:" | sed 's/^description: *//' | tr -d '"')
    if [ ${#desc} -gt 200 ]; then
        echo "⚠️  [$skill_name] description 过长 (${#desc} 字符),建议 < 200"
    fi

    # 检查5: name 命名规范(小写+连字符)
    name=$(echo "$fm_content" | grep "^name:" | sed 's/^name: *//' | tr -d '"')
    if ! echo "$name" | grep -qE "^[a-z0-9][a-z0-9-]*$"; then
        echo "⚠️  [$skill_name] name '$name' 不符合命名规范(小写+连字符)"
    fi

    # 检查6: YAML 语法(需要 python)
    if command -v python3 &>/dev/null; then
        if ! echo "$fm_content" | python3 -c "import sys, yaml; yaml.safe_load(sys.stdin)" 2>/dev/null; then
            echo "❌ [$skill_name] YAML 语法错误"
            errors=$((errors + 1))
        fi
    fi

    echo "✅ [$skill_name] 基础校验通过"
done

echo ""
echo "=== 校验完成,发现 $errors 个错误 ==="
exit $errors

运行方式:

chmod +x skill-lint.sh
./skill-lint.sh ~/.claude/skills

1.3 一个典型的 frontmatter 错误案例

错误文件:

---
name: Code Reviewer
description: 这是一个代码审查工具,它可以帮助你:1. 发现潜在bug 2. 检查代码风格 3. 评估架构设计 4. 生成改进建议 5. 追踪技术债务。支持多种编程语言,包括 JavaScript、TypeScript、Python、Go、Rust 等。
# 以上 description 超过 200 字符,且包含冒号和句号
trigger: when user mentions code review, PR review, or pull request
---

修复后:

---
name: code-reviewer
description: Review code for bugs, style issues, and architectural concerns across multiple languages
---

诊断要点: - name 应使用小写连字符格式(code-reviewer 而非 Code Reviewer) - description 精简到一句话,把细节留给 Skill 正文 - trigger 不是标准 frontmatter 字段,描述中的关键词就是触发器


Layer 2:触发与发现调试

Skill 写好了但不被激活,是最常见的问题。理解发现机制是解决它的关键。

2.1 发现机制详解

Claude Code 的 Skill 发现遵循三层匹配:

flowchart LR
    A[用户输入] --> B[关键词扫描]
    B --> C[description 语义匹配]
    C --> D[trigger 条件评估]
    D --> E[激活 Skill]

    B -->|失败| F[Skill 未触发]
    C -->|失败| F
    D -->|失败| F

    style F fill:#ff6b6b,color:#fff
    style E fill:#51cf66,color:#fff

第一层:关键词扫描 — Claude 从用户输入中提取关键短语,与 Skill 的 name 和 description 做子串匹配。

第二层:语义匹配 — 如果关键词扫描没有直接命中,Claude 会理解用户意图,判断哪个 Skill 的 description 最匹配。

第三层:条件评估 — 检查 Skill 是否有额外的激活条件(如文件类型、项目结构等)。

2.2 触发失败的五种模式及修复

模式一:Description 太宽泛

# ❌ 太宽泛 - 几乎任何编码请求都会模糊匹配
description: Help with code

# ✅ 精确描述 - 只在特定场景激活
description: Analyze Python type hints and suggest improvements using mypy

模式二:Description 太窄

# ❌ 太窄 - 用户几乎不会原样说出这个短语
description: Execute the mypy static type checker on Python files with strict mode

# ✅ 覆盖自然表达
description: Check Python type annotations and fix type errors

模式三:Name 和 Description 语义重复

# ❌ 语义重复 - 浪费了宝贵的描述空间
name: python-type-checker
description: Check Python types

# ✅ Name 用标识符,Description 用自然语言描述行为
name: python-type-checker
description: Analyze Python type annotations, run mypy, and suggest fixes for type errors

模式四:多 Skill 竞争同一触发词

当两个 Skill 的 description 高度相似时,Claude 可能选错。解决方法是在 description 中加入区分性关键词:

# Skill A
name: api-test-runner
description: Run and debug HTTP API tests using pytest with response validation

# Skill B(修改前会与 A 竞争)
name: api-doc-generator
description: Generate OpenAPI documentation from HTTP API endpoint code  # 明确是"生成文档"而非"运行测试"

模式五:Skill 文件位置错误

Skill 必须放在正确路径才能被发现:

# ✅ 正确位置
~/.claude/skills/my-skill/SKILL.md           # 全局 Skill
.claude/skills/my-skill/SKILL.md             # 项目级 Skill

# ❌ 错误位置
~/.claude/skills/my-skill.md                 # 缺少目录层级
~/.claude/skills/SKILL.md                    # 不能直接放在 skills/ 下
.claude/my-skill/SKILL.md                    # 不在 skills/ 子目录

2.3 触发验证四步法

当你不确定 Skill 是否能被正确触发时:

步骤1:列出已发现的 Skill

# 在 Claude Code 会话中输入
/skills

如果 Skill 不在列表中,说明发现阶段就失败了——回到 Layer 1 检查文件结构和位置。

步骤2:使用显式触发

# 直接用 /skill-name 调用
/my-skill

# 或在消息中明确提及 Skill 描述中的关键词
请帮我分析 Python 类型标注问题

步骤3:检查竞争 Skill

# 列出所有与 "python" 相关的 Skill
ls ~/.claude/skills/ | grep python
ls .claude/skills/ | grep python

如果有多个相关 Skill,它们的 description 区分度够吗?

步骤4:查看加载日志

# 启动 Claude Code 时带 verbose 标志
claude --verbose

# 或在会话中检查
/debug

Layer 3:上下文加载分析

Skill 被触发了,但 Claude 的行为不像预期——可能是指令没有被正确加载到上下文。

3.1 上下文窗口中的 Skill 位置

理解 Skill 在上下文窗口中的位置至关重要:

graph TD
    subgraph "上下文窗口 (200K tokens)"
        A["System Prompt<br/>(Claude Code 核心指令)"]
        B["CLAUDE.md<br/>(项目/全局配置)"]
        C["活跃 Skill 指令<br/>(最近加载的 Skill 正文)"]
        D["对话历史<br/>(用户与 Claude 的交互)"]
        E["工具调用结果<br/>(Read/Grep/Bash 输出)"]
    end

    A --> B --> C --> D --> E

    style C fill:#ffd43b,stroke:#e67700

关键洞察:Skill 指令在上下文中的位置是"底部优先"的——最近加载的内容在模型注意力的高权重区域。但这意味着:

  1. 长对话中 Skill 可能被"推远" — 如果对话很长,早期的 Skill 指令可能离当前交互很远,模型对它的遵从度下降
  2. 多 Skill 同时激活会互相稀释 — 每个 Skill 都要争抢注意力,指令越精练越好
  3. 上下文压缩可能丢失 Skill 细节 — 当对话接近上下文限制时,系统会压缩早期内容

3.2 渐进披露的正确用法

渐进披露(Progressive Disclosure)是解决上下文争抢的核心模式。它把 Skill 内容分为三层:

---
name: api-security-scanner
description: Scan API endpoints for security vulnerabilities
---

# API Security Scanner

## Overview
Scans REST and GraphQL endpoints for OWASP Top 10 vulnerabilities.
Produces a prioritized report with remediation steps.

<details>
<summary>Scan Methodology</summary>

## Phase 1: Endpoint Discovery
- Parse OpenAPI/Swagger specs
- Scan route definitions in framework code
- Identify authentication boundaries

## Phase 2: Vulnerability Testing
- SQL injection patterns
- XSS payload vectors
- Authentication bypass scenarios
- Rate limiting gaps

## Phase 3: Report Generation
- Severity: Critical/High/Medium/Low
- CVE references where applicable
- Code-level fix suggestions

</details>

<details>
<summary>Advanced Configuration</summary>

## Custom Rules
Add custom scan rules in `.claude/security-rules.yaml`:
```yaml
rules:
  - name: custom-injection
    pattern: "eval\\(.*user_input.*\\)"
    severity: critical

CI/CD Integration

The scanner can output SARIF format for GitHub Code Scanning.

**诊断要点**:
- 概述层(`<details>` 之外)控制在 **5-8 行**,只包含核心行为描述
- 中间层(第一个 `<details>`)包含主要工作流程,**50-100 行**
- 详细层(嵌套 `<details>`)包含配置和扩展内容,**不限长度**
- 模型按需"展开",只有当任务需要时才消耗 Token

### 3.3 上下文冲突的诊断信号

| 信号 | 可能原因 | 修复方向 |
|------|---------|---------|
| Skill 只在对话开始时工作 | 上下文压缩导致指令丢失 | 缩短指令、使用渐进披露 |
| Skill 有时工作有时不工作 | 与其他 Skill/MCP 指令冲突 | 检查 description 区分度 |
| Skill 输出格式不稳定 | 指令中有模糊表述 | 使用更严格的输出模板 |
| Skill 忽略关键步骤 | 指令过长,关键信息被淹没 | 精简指令,突出关键步骤 |

---

## Layer 4:Token 预算与性能分析

### 4.1 Token 预算计算

每个 Skill 激活都会消耗上下文窗口的 Token 预算。粗略估算:

Skill Token 消耗 ≈ frontmatter Token + 正文 Token + 加载开销 ≈ (30-50) + (正文行数 × 3-5) + (100-200)

一个 100 行的 Skill 大约消耗 500-700 Tokens。当多个 Skill 同时激活时,这可能快速累积。

### 4.2 优化策略:从冗长到精练

**Before(280 Tokens)**:

```markdown
# Code Review Skill

When the user asks you to review code, you should follow these steps carefully:

1. First, read the file or files that need to be reviewed
2. Analyze the code for potential bugs, including null pointer exceptions,
   off-by-one errors, resource leaks, and race conditions
3. Check the code style against common conventions for the language
4. Look for security vulnerabilities following the OWASP Top 10 guidelines
5. Evaluate the overall architecture and design patterns used
6. Generate a comprehensive review report with the following sections:
   - Summary: A brief overview of the code quality
   - Critical Issues: Bugs and security issues that must be fixed
   - Suggestions: Style and architecture improvements
   - Positive Notes: Things done well in the code
7. Prioritize issues by severity: Critical > High > Medium > Low
8. Provide specific code suggestions for each issue found

After(90 Tokens,减少 68%):

# Code Review

## Steps
1. Read target files
2. Check: bugs, style, security (OWASP), architecture
3. Output report with sections: Summary | Critical | Suggestions | Positives

## Rules
- Severity: Critical > High > Medium > Low
- Every issue needs a code fix suggestion

精练原则: - 删除所有"你应当"、"请确保"等指令性废话——模型已经知道要执行 - 用管道符 | 替代列表结构 - 用冒号 : 后直接跟值替代独立行 - 合并同质步骤

4.3 使用 Token 分析工具

# 估算 Skill 的 Token 消耗(使用 Claude tokenizer)
function skill-tokens() {
    local skill_file="$1"
    if [ ! -f "$skill_file" ]; then
        echo "Usage: skill-tokens <path-to-SKILL.md>"
        return 1
    fi

    # 粗略估算:英文约 4 字符 = 1 token,中文约 1.5 字符 = 1 token
    local chars=$(wc -c < "$skill_file")
    local lines=$(wc -l < "$skill_file")
    local estimated=$((chars / 4))

    echo "文件: $skill_file"
    echo "字符数: $chars"
    echo "行数: $lines"
    echo "预估 Token: $estimated"
    echo ""

    if [ $estimated -gt 2000 ]; then
        echo "⚠️  Token 预算偏高,建议使用渐进披露优化"
    elif [ $estimated -gt 500 ]; then
        echo "⚠️  Token 消耗中等,检查是否可以精简"
    else
        echo "✅ Token 消耗合理"
    fi
}

# 批量分析所有 Skill
function skill-audit() {
    local total=0
    for f in $(find ~/.claude/skills -name "SKILL.md" 2>/dev/null); do
        local chars=$(wc -c < "$f")
        local tokens=$((chars / 4))
        total=$((total + tokens))
        local name=$(basename $(dirname "$f"))
        printf "%-30s %5d tokens\n" "$name" "$tokens"
    done
    echo "----------------------------------------"
    printf "%-30s %5d tokens\n" "TOTAL" "$total"
    echo ""
    echo "上下文窗口 ≈ 200,000 tokens"
    echo "Skill 占比: $(echo "scale=2; $total * 100 / 200000" | bc)%"
}

Layer 5:行为输出验证

Skill 不报错但输出不对——这是最棘手的问题。

5.1 行为偏离的四种类型

类型一:步骤跳过

期望行为:读取文件 → 分析代码 → 生成报告
实际行为:直接生成报告(跳过了分析步骤)

根因:指令中的步骤描述不够强制性。修复方法:

# ❌ 软性指令
Consider analyzing the code before generating the report.

# ✅ 强制指令
## Workflow (MANDATORY - execute every step in order)
1. Use Read tool to examine each target file
2. Run Grep to search for patterns listed in the checklist
3. ONLY AFTER completing steps 1-2, generate the report

类型二:格式偏离

期望:JSON 格式输出
实际:Markdown 格式输出

修复:使用输出模板锁定格式。

## Output Format
Return EXACTLY this JSON structure (no markdown, no explanation):

```json
{"findings": [{"severity": "HIGH", "file": "...", "line": N, "issue": "..."}]}
**类型三:幻觉/编造**

期望:只报告实际发现的问题 实际:报告了不存在的"问题"

**修复**:加入验证约束。

```markdown
## Critical Rule
- ONLY report issues you have DIRECTLY OBSERVED in the code
- Every finding MUST include: exact file path, exact line number, verbatim code snippet
- If you cannot find the exact line, do NOT report the issue

类型四:过度执行

期望:只分析指定的 3 个文件
实际:分析了整个项目

修复:使用边界约束。

## Scope
- ONLY analyze files explicitly listed by the user
- Do NOT scan directories or expand scope
- If user says "these 3 files", stop at exactly 3 files

5.2 行为测试模板

创建 eval.json 文件来系统性测试 Skill 行为:

{
  "skill": "api-security-scanner",
  "evals": [
    {
      "name": "detects-sql-injection",
      "input": "Scan routes/user.py for security issues",
      "assertions": [
        {"type": "contains", "value": "SQL injection"},
        {"type": "contains", "value": "routes/user.py"},
        {"type": "not_contains", "value": "I couldn't find any issues"}
      ]
    },
    {
      "name": "respects-file-scope",
      "input": "Only scan src/api/auth.ts",
      "assertions": [
        {"type": "contains", "value": "src/api/auth.ts"},
        {"type": "not_contains", "value": "src/api/users.ts"}
      ]
    },
    {
      "name": "output-format-correct",
      "input": "Check src/utils/sanitize.js and output JSON",
      "assertions": [
        {"type": "matches_regex", "value": "\\{\"findings\":\\[.*\\]\\}"}
      ]
    }
  ]
}

使用 skill-creator 内置的 eval 命令运行测试:

# 运行评估
claude /skill-creator eval --skill api-security-scanner --file eval.json

# 查看结果
# PASS: detects-sql-injection (3/3 assertions)
# PASS: respects-file-scope (2/2 assertions)
# FAIL: output-format-correct (0/1 assertions)
#   Expected: regex match {"findings":[...]}
#   Actual: Output was in markdown format

Layer 6:集成与交互调试

6.1 Skill 间的冲突模式

当多个 Skill 同时激活时,可能出现指令冲突:

sequenceDiagram
    participant U as 用户
    participant C as Claude Code
    participant S1 as Skill A: code-reviewer
    participant S2 as Skill B: test-generator

    U->>C: 审查这段代码并生成测试
    C->>S1: 激活 code-reviewer
    C->>S2: 激活 test-generator

    Note over S1,S2: 冲突!两个 Skill 都想控制输出格式

    S1-->>C: 输出格式 = Markdown 报告
    S2-->>C: 输出格式 = 测试代码文件

    Note over C: 指令矛盾,行为不确定
    C-->>U: 混合格式输出(不稳定)

修复策略:为 Skill 定义优先级和互斥关系。

# code-reviewer SKILL.md
---
name: code-reviewer
description: Review code for quality and security issues
---
# Code Reviewer

## Priority
When activated alongside test-generator, this skill handles REVIEW only.
Test generation is delegated to test-generator.

## Output
- This skill ONLY produces review reports
- Does NOT generate test code

6.2 Skill 与 MCP 的交互

Skill 调用 MCP 工具时的常见问题:

问题:MCP 工具在 Skill 指令中被引用但不可用

# ❌ 假设 MCP 工具一定存在
Use the figma_use tool to fetch design data.

# ✅ 防御性编程
If the figma_use MCP tool is available, use it to fetch design data.
Otherwise, ask the user to install the Figma MCP server first.

问题:Skill 指令与 MCP 工具行为冲突

# ❌ Skill 指令要求读取文件,但 MCP 也想读取
Read all Python files and analyze them.
Then use the codebase_search MCP tool to find related files.

# ✅ 明确分工
## File Reading
- Use Claude's built-in Read tool for files the user specifies
- Use MCP codebase_search tool only for finding additional related files
- Do NOT use both tools on the same file

6.3 集成测试检查清单

## Integration Checklist
- [ ] Skill 不依赖特定的 MCP 工具(或有 fallback)
- [ ] Skill 的输出不会与另一个 Skill 的输入冲突
- [ ] Skill 在没有其他 Skill 激活时仍然正常工作
- [ ] Skill 不会触发无限循环(A 触发 B,B 又触发 A)
- [ ] Skill 的文件操作不与其他 Skill 竞争同一文件

实战案例:调试一个"不工作"的 API 文档生成器 Skill

让我们完整走一遍六层诊断流程,修复一个真实的 Skill。

初始(有问题的)Skill

---
name: API Doc Generator
description: 这是一个API文档生成工具可以帮助开发者自动生成API文档
---

# API Documentation Generator

你是一个 API 文档生成专家。

当用户请求生成 API 文档时,你需要:

首先,扫描项目中的所有 API 路由文件。对于 Node.js 项目,查找 routes/ 目录。对于 Python 项目,查找 urls.py 和 views.py 文件。对于 Go 项目,查找 handler.go 和 router.go 文件。

然后,分析每个路由的 HTTP 方法、路径、请求参数、响应格式。

接着,检查是否有现有的 OpenAPI 或 Swagger 文档,如果有则基于它们进行更新。

之后,生成完整的 API 文档,包括:
- 每个端点的描述
- 请求参数表格
- 响应格式示例
- 错误码列表
- 认证要求

最后,将文档保存到 docs/api.md 文件中。

如果用户指定了特定格式(如 OpenAPI YAML),则按该格式输出。

注意事项:
- 确保文档中包含所有端点
- 使用清晰的表格格式
- 包含示例请求和响应
- 标注已废弃的端点

诊断过程

Layer 1 检查:

❌ name: "API Doc Generator" → 应为 "api-doc-generator"(小写连字符)
❌ description: 中文 + 过于简短 + 包含重复的"API文档"
❌ 正文:没有渐进披露,全部平铺,约 400+ Tokens

Layer 2 检查:

❌ description 中没有英文关键词,语义匹配效率低
❌ 与其他文档类 Skill 区分度不够

Layer 3 检查:

❌ 指令太长且无结构,容易被上下文压缩
❌ 没有使用 <details> 分层

Layer 4 检查:

⚠️ 预估 500+ Tokens,精简后可降到 200 以下

Layer 5 检查:

❌ 没有输出格式锁定
❌ 没有边界约束(可能扫描整个项目)
❌ 没有验证约束(可能编造不存在的端点)

Layer 6 检查:

⚠️ 硬编码写入 docs/api.md,可能与项目约定冲突
⚠️ 没有 fallback 机制

修复后的 Skill

---
name: api-doc-generator
description: Generate API documentation from route definitions in Node.js, Python, or Go projects
---

# API Doc Generator

## Scan Strategy
- Node.js: `routes/` directory
- Python: `urls.py`, `views.py`
- Go: `*handler*.go`, `*router*.go`
- Only scan directories the user specifies; do NOT scan entire project

## Output Template
Generate documentation in this exact structure:

Endpoint: {METHOD} {PATH}

Auth Required: Yes/No Deprecated: Yes/No

Parameters

Name Type Required Description
... ... ... ...

Response (200)

{response example}

Errors

Code Description
... ...
## Rules
- ONLY document endpoints DIRECTLY found in code
- Every endpoint MUST include: file path, line number reference
- Save to path specified by user (default: `docs/api.md`)
- If OpenAPI/Swagger spec exists, merge and update it

<details>
<summary>Advanced: Custom Templates</summary>

## Per-Framework Templates

### Express.js
Extract from `router.METHOD(path, ...middleware, handler)` patterns.

### FastAPI
Read decorator `@router.METHOD(path, response_model=...)` metadata.

### Django REST Framework
Parse `Serializer` classes linked to `ViewSets`.

</details>

验证修复效果

# 1. 语法校验
./skill-lint.sh
# ✅ [api-doc-generator] 基础校验通过

# 2. Token 分析
skill-tokens ~/.claude/skills/api-doc-generator/SKILL.md
# 预估 Token: 280
# ✅ Token 消耗合理

# 3. 触发测试
# 在 Claude Code 中输入:
> 帮我为这个 Express 项目生成 API 文档
# 预期:Skill 被激活,扫描 routes/ 目录

# 4. 行为测试
# 在 Claude Code 中输入:
> 只为 routes/auth.js 生成文档
# 预期:只分析 auth.js,不扫描其他文件

# 5. 输出格式测试
# 预期:输出包含表格格式的端点文档

调试工具箱:七把利器

工具1:/skills 命令

在 Claude Code 会话中直接使用,查看所有已发现的 Skill 及其状态。

工具2:skill-lint.sh

上文提供的语法校验脚本,保存到 ~/.claude/bin/skill-lint.sh 并加入 PATH。

工具3:skill-tokens / skill-audit

上文的 Token 分析函数,加入 .bashrc 或 .zshrc。

工具4:--verbose 启动模式

claude --verbose
# 显示 Skill 加载、匹配、激活的详细日志

工具5:eval.json 行为测试

使用 skill-creator 的内置 eval 框架,为每个 Skill 编写行为断言。

工具6:A/B 对比

# 修改 Skill 前,先保存当前输出的 baseline
# 修改后,对比输出差异
# 使用 /skill-creator benchmark 进行自动化 A/B 测试

工具7:渐进式隔离

当不确定是哪个 Skill 出了问题时:

# 1. 只保留目标 Skill,移走其他 Skill
mkdir ~/.claude/skills-disabled
mv ~/.claude/skills/other-skill ~/.claude/skills-disabled/

# 2. 测试目标 Skill 是否正常
# 3. 逐个恢复其他 Skill,找出冲突源
mv ~/.claude/skills-disabled/other-skill ~/.claude/skills/

高级模式:Skill 调试工作流自动化

将六层诊断整合为一个可复现的调试流程:

flowchart TB
    START([Skill 问题报告]) --> L1{Layer 1: 语法?}
    L1 -->|失败| F1[修复 frontmatter]
    L1 -->|通过| L2{Layer 2: 触发?}
    F1 --> RECHECK([重新校验])
    RECHECK --> L1

    L2 -->|失败| F2[优化 description<br/>检查文件位置]
    L2 -->|通过| L3{Layer 3: 上下文?}
    F2 --> RECHECK

    L3 -->|失败| F3[添加渐进披露<br/>精简指令]
    L3 -->|通过| L4{Layer 4: Token?}
    F3 --> RECHECK

    L4 -->|超标| F4[压缩正文<br/>提取到 details]
    L4 -->|合理| L5{Layer 5: 行为?}
    F4 --> RECHECK

    L5 -->|偏离| F5[锁定输出格式<br/>添加验证约束]
    L5 -->|正确| L6{Layer 6: 集成?}
    F5 --> RECHECK

    L6 -->|冲突| F6[定义优先级<br/>添加互斥规则]
    L6 -->|正常| DONE([✅ 全部通过])
    F6 --> RECHECK

    style DONE fill:#51cf66,color:#fff
    style START fill:#339af0,color:#fff
    style RECHECK fill:#ffd43b,color:#000

建议将此流程保存为 ~/.claude/skills/skill-debugger/SKILL.md,形成一个"用 Skill 调试 Skill"的元循环。


总结:六层诊断速查表

层级 问题 快速检查 耗时
L1 语法 Skill 不被发现 skill-lint.sh 1 分钟
L2 触发 Skill 不被激活 /skills 列表 + 显式调用 3 分钟
L3 上下文 行为不稳定/部分忽略 检查指令长度 + 渐进披露 5 分钟
L4 Token 上下文溢出/成本高 skill-audit 统计 2 分钟
L5 行为 输出格式/内容不对 eval.json 断言测试 10 分钟
L6 集成 多 Skill/MCP 冲突 隔离测试 + 检查优先级 15 分钟

黄金法则:永远从 L1 开始,逐层向上。不要跳层诊断——80% 的"高级问题"根源在前两层。


参考来源

  1. Extend Claude with skills - Claude Code Docs — Anthropic 官方 Skill 开发文档
  2. SKILL.md Format Specification | DeepWiki — SKILL.md 格式规范详解
  3. Progressive Disclosure: How Claude Code Cut Token Usage by 98% — 渐进披露模式原理与效果
  4. Claude Code Skills 2.0: Evals, Benchmarks Guide — Skill 评估与基准测试方法
  5. Skill authoring best practices - Claude API Docs — Anthropic 官方 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学通信知识星球海报-扫码加入