本教程面向已经掌握SKILL.md基础写法的Claude Code用户,系统讲解五种经过生产验证的Skill设计模式——Chain、Fan-Out、Aggregator、Pipeline、Singleton,并通过一个完整的「代码审查→安全扫描→文档生成→PR创建」四阶段自动化流水线,演示多Skill可组合编排的工程实践。学完后,你将具备构建可复用、可嵌套、可并行调度的高阶Skill系统的能力。
适用人群:已有Claude Code Skill基础开发经验,希望构建复杂多步骤自动化工作流的中高级开发者。
前置条件:
- 已安装Claude Code CLI(npm install -g @anthropic-ai/claude-code)
- 熟悉SKILL.md的YAML frontmatter基本字段(name、description、instructions)
- 了解Markdown格式和基本Shell命令
单个Skill解决单个问题——写代码、做审查、生成文档。但真实工程场景中,任务往往是多步骤、多依赖的:
代码提交 → Lint检查 → 单元测试 → 安全扫描 → 生成Changelog → 创建PR
如果把这些全部写进一个巨型SKILL.md,会面临三个问题:
设计模式的核心思想是原子化:每个Skill只做一件事,做好一件事,通过模式组合成复杂流程。
graph TB
A[用户输入: "审查这段代码并创建PR"] --> B{Skill Router}
B --> C[Lint Skill]
B --> D[Security Scan Skill]
C --> E[Aggregator: 汇总结果]
D --> E
E --> F[Doc Gen Skill]
F --> G[PR Creator Skill]
G --> H[输出: PR链接 + 审查报告]
style A fill:#e1f5fe
style H fill:#c8e6c9
style B fill:#fff9c4
经过对100+开源Skill的分析和Anthropic官方33页Skill构建指南的提炼,五种高频设计模式如下:
| 模式 | 核心思想 | 适用场景 | Token开销 |
|---|---|---|---|
| Chain | 顺序执行,前一个输出作为后一个输入 | 多步骤流水线 | 低(每步只加载一个) |
| Fan-Out | 并行分发同一输入到多个Skill | 同时执行多种检查 | 中(同时加载多个) |
| Aggregator | 收集多个输出,合并为统一结果 | 汇总审查报告 | 低 |
| Pipeline | Chain + 条件分支,带错误处理 | 完整CI/CD流程 | 中 |
| Singleton | 全局唯一,提供共享基础设施 | 日志、配置管理 | 极低 |
graph LR
subgraph Chain模式
A1[Step 1] --> A2[Step 2] --> A3[Step 3]
end
subgraph Fan-Out模式
B1[Input] --> B2[Skill A]
B1 --> B3[Skill B]
B1 --> B4[Skill C]
end
subgraph Aggregator模式
C1[Skill A] --> C4[Aggregator]
C2[Skill B] --> C4
C3[Skill C] --> C4
end
subgraph Pipeline模式
D1[Input] --> D2{条件判断}
D2 -->|通过| D3[Step A]
D2 -->|失败| D4[Step B]
end
Chain模式是最基础也最常用的模式。每个Skill在完成后,通过instructions字段明确指定"下一步应该做什么",形成单向链表结构。
关键设计原则: - 每个Skill的输出格式必须是结构化的(JSON或Markdown section),便于下游解析 - 每个Skill必须包含错误状态,让下游知道是否应跳过 - 链条长度建议不超过5个节点(超过5个应拆分为子Pipeline)
第一步:创建项目结构
mkdir -p ~/.claude/skills/code-pipeline
cd ~/.claude/skills/code-pipeline
第二步:创建格式化Skill(链头)
创建文件 ~/.claude/skills/code-pipeline/01-format/SKILL.md:
---
name: code-format
description: "Format code using project's configured formatter (Prettier, Black, gofmt). Runs format check and applies fixes."
instructions: |
You are a code formatting specialist. Your workflow:
1. Detect the project's formatter from package.json / pyproject.toml / go.mod
2. Run the formatter on staged files only (use `git diff --name-only --cached`)
3. Report results in this EXACT format:
## Format Result
- Status: PASS | FAIL
- Files formatted: [count]
- Errors: [details or "none"]
4. If Status is PASS, tell the user: "Format check passed. Next step: Run /code-typecheck to continue the pipeline."
5. If Status is FAIL, stop and show the errors. Do NOT proceed.
---
第三步:创建类型检查Skill(链中)
创建文件 ~/.claude/skills/code-pipeline/02-typecheck/SKILL.md:
---
name: code-typecheck
description: "Run type checking (TypeScript tsc, Python mypy, Go vet) on the project. Part of the code quality pipeline."
instructions: |
You are a type checking specialist. Your workflow:
1. Detect the project's type checker from config files
2. Run type checking on the entire project
3. Report results in this EXACT format:
## TypeCheck Result
- Status: PASS | FAIL
- Errors: [count] errors found
- Details: [error list or "none"]
4. If Status is PASS, tell the user: "Type check passed. Next step: Run /code-test to continue the pipeline."
5. If Status is FAIL, list each error with file:line and suggested fix. Do NOT proceed.
IMPORTANT: This skill is part of a pipeline. The previous step (code-format) must have passed before running this.
---
第四步:创建测试Skill(链尾)
创建文件 ~/.claude/skills/code-pipeline/03-test/SKILL.md:
---
name: code-test
description: "Run unit tests and report coverage. Final step in the code quality pipeline."
instructions: |
You are a test execution specialist. Your workflow:
1. Detect the test framework from project config
2. Run tests with coverage enabled
3. Report results in this EXACT format:
## Test Result
- Status: PASS | FAIL
- Tests run: [count]
- Coverage: [percentage]%
- Failures: [details or "none"]
4. If ALL pipeline steps passed (format → typecheck → test), summarize:
"Pipeline complete. All 3 steps passed. Safe to commit."
5. If any test failed, show failure details and suggest fixes.
---
在Claude Code中,按链式顺序依次调用:
> /code-format
(格式化通过后)
> /code-typecheck
(类型检查通过后)
> /code-test
| 问题 | 原因 | 解决方案 |
|---|---|---|
| 下游Skill拿不到上游结果 | Claude Code的Skill是无状态的 | 在instructions中要求用户确认上游结果,或使用CLAUDE.md记录中间状态 |
| 链条中途断裂 | 错误处理不够明确 | 在每个Skill中加"FAIL时停止"的硬性指令 |
| Skill没有自动激活 | description缺少关键词 | 确保description包含触发关键词如"format"、"typecheck"、"test" |
Fan-Out模式将同一个输入同时发送到多个独立Skill并行处理。这是提升效率的关键模式——原本需要依次执行的多个检查,现在可以同时运行。
Claude Code中实现Fan-Out有两种方式: 1. Router Skill:一个专门的编排Skill,在instructions中指示Claude并行调用多个子Skill 2. 用户触发:用户在一次对话中同时请求多个操作
创建文件 ~/.claude/skills/code-review-router/SKILL.md:
---
name: code-review-router
description: "Comprehensive code review router. Dispatches parallel checks for lint, security, performance, and accessibility. Use when reviewing code changes."
instructions: |
You are a code review orchestrator. When activated, you must perform ALL of the following checks IN PARALLEL using the Task tool with subagents:
## Check 1: Lint & Style
- Run the project's linter (ESLint/Ruff/golangci-lint)
- Check for style violations
- Report: "## Lint Result\n- Status: PASS|FAIL\n- Issues: [list]"
## Check 2: Security Scan
- Check for hardcoded secrets/credentials
- Look for SQL injection, XSS patterns
- Check dependency vulnerabilities (npm audit / pip audit)
- Report: "## Security Result\n- Status: PASS|FAIL\n- Issues: [list]"
## Check 3: Performance Review
- Identify N+1 query patterns
- Check for unnecessary re-renders (React) or missing indexes
- Look for memory leak patterns (unclosed connections, missing cleanup)
- Report: "## Performance Result\n- Status: PASS|FAIL\n- Issues: [list]"
## Check 4: Accessibility (if UI code)
- Check for missing alt attributes
- Verify ARIA labels
- Check color contrast issues
- Report: "## A11y Result\n- Status: PASS|FAIL|N/A\n- Issues: [list]"
## Final Report
After ALL checks complete, compile a unified report:
# Code Review Summary
| Check | Status | Issues |
|-------|--------|--------|
| Lint | ? | ? |
| Security | ? | ? |
| Performance | ? | ? |
| A11y | ? | ? |
**Overall**: PASS only if ALL checks pass.
CRITICAL: Use the Task tool to run checks in parallel. Do NOT run them sequentially.
---
Aggregator模式是Fan-Out的天然搭档。它不执行具体任务,而是收集多个来源的结果,去重、排序、按优先级输出统一报告。
创建文件 ~/.claude/skills/security-aggregator/SKILL.md:
---
name: security-report
description: "Aggregate security findings from multiple scanners into a unified prioritized report. Combines SAST, DAST, dependency audit results."
instructions: |
You are a security report aggregator. Your job is to collect security findings and produce a single prioritized report.
## Input Sources
Collect results from these sources (run each if not already available):
1. Static analysis: Check source code for vulnerability patterns
2. Dependency audit: Run `npm audit` / `pip audit` / `cargo audit`
3. Secret scan: Check for hardcoded credentials, API keys, tokens
## Aggregation Rules
1. Deduplicate: Same finding from multiple sources = one entry
2. Severity mapping:
- CRITICAL: RCE, credential exposure, SQL injection
- HIGH: XSS, CSRF, auth bypass
- MEDIUM: info leakage, misconfiguration
- LOW: style issues, missing headers
3. Sort by severity (Critical → Low)
4. Group by file/module
## Output Format
# Security Report
**Generated**: [date]
**Scope**: [files scanned]
**Summary**: [X Critical, Y High, Z Medium, W Low]
## Critical Findings
### [CVE-ID or Finding Title]
- **File**: path/to/file:line
- **Source**: SAST | Dependency | Secret Scan
- **Description**: [what's wrong]
- **Fix**: [specific code change needed]
## High Findings
[same format]
## Medium Findings
[same format]
## Recommended Actions (Priority Order)
1. [Most urgent fix]
2. [Second most urgent]
...
IMPORTANT: Every finding MUST have a specific fix suggestion. Do not report findings without remediation guidance.
---
src/components/Form.tsx:42使用DOMPurify.sanitize()对userInput进行消毒"Pipeline是Chain的升级版,增加了条件分支和错误恢复。它像一个状态机,根据每步的输出决定下一步走哪条路径。
stateDiagram-v2
[*] --> Format: 用户触发
Format --> TypeCheck: PASS
Format --> ErrorReport: FAIL
TypeCheck --> Test: PASS
TypeCheck --> ErrorReport: FAIL
Test --> SecurityScan: PASS
Test --> ErrorReport: FAIL
SecurityScan --> GenerateReport: PASS
SecurityScan --> WarnAndContinue: LOW_RISK
ErrorReport --> [*]: 修复后重新运行
GenerateReport --> [*]
WarnAndContinue --> GenerateReport
创建文件 ~/.claude/skills/ci-pipeline/SKILL.md:
---
name: ci-pipeline
description: "Full CI pipeline with conditional branching. Runs format check, type check, tests, security scan, and generates reports. Handles failures gracefully."
instructions: |
You are a CI pipeline orchestrator. Execute the following stages in order, with conditional branching:
## Stage 1: Pre-flight Checks
1. Check `git status` — are there uncommitted changes? Warn if yes.
2. Check if required tools are installed (node/python/go, linter, test runner)
3. If pre-flight fails → STOP and report missing dependencies
## Stage 2: Format & Lint
1. Run formatter on all staged files
2. Run linter
- If PASS → proceed to Stage 3
- If FAIL → generate a `.claude/lint-fixes.md` file with auto-fix commands, then STOP
## Stage 3: Type Check
1. Run type checker
- If PASS → proceed to Stage 4
- If FAIL with <5 errors → attempt auto-fix, then re-check once
- If FAIL with >=5 errors → STOP and list all errors
## Stage 4: Tests
1. Run unit tests with coverage
- If PASS → proceed to Stage 5
- If FAIL → run only failed tests again (flaky test detection)
- If still FAIL → STOP and generate test failure report
## Stage 5: Security Scan
1. Run dependency audit
2. Scan for hardcoded secrets
- If CRITICAL findings → STOP and alert
- If only LOW/MEDIUM → proceed but include warnings in final report
## Stage 6: Report Generation
Generate `CI_REPORT.md` with:
- Pipeline status (PASS/FAIL/WARN)
- Per-stage results
- Test coverage summary
- Security findings (if any)
- Time elapsed per stage
## Error Recovery
If the user says "fix and retry":
1. Read the error report from the failed stage
2. Apply fixes automatically where possible
3. Re-run from the FAILED stage (not from the beginning)
---
一个关键技巧是将Pipeline分为控制层和执行层:
这样设计的好处是执行层Skill可以独立使用,也可以被不同的Pipeline复用。
Singleton模式提供全局共享的服务——日志、配置、错误码表等。它不直接产生业务输出,而是被其他Skill引用。
创建文件 ~/.claude/skills/project-config/SKILL.md:
---
name: project-config
description: "Project configuration singleton. Provides shared settings, conventions, and constants for all other skills. Always load this first."
instructions: |
You are the project configuration provider. When any other skill or the user asks for project settings, provide them from this canonical source.
## Project Conventions
### Code Style
- Language: [auto-detect from project]
- Indent: 2 spaces (JS/TS) or 4 spaces (Python)
- Quotes: single (JS/TS) or double (Python)
- Max line length: 100 characters
### Testing
- Framework: [auto-detect]
- Coverage threshold: 80%
- Test file pattern: `*.test.ts` or `test_*.py`
### Git
- Branch naming: `feat/`, `fix/`, `chore/`, `docs/`
- Commit format: Conventional Commits
- PR template: `.github/PULL_REQUEST_TEMPLATE.md`
### Security
- Secret scanning: enabled
- Allowed licenses: MIT, Apache-2.0, BSD-3-Clause
- Max dependency age: 2 years
## Usage by Other Skills
Other skills should reference this configuration by including in their instructions:
"Load project settings from /project-config before proceeding."
## Dynamic Detection
If settings are not explicitly defined, auto-detect:
1. Read package.json / pyproject.toml / go.mod for language and tools
2. Read .eslintrc / ruff.toml for style rules
3. Read tsconfig.json / mypy.ini for type checking config
4. Read jest.config / pytest.ini for test config
---
在其他Skill的instructions中引用Singleton:
instructions: |
Before starting any work, invoke /project-config to load project conventions.
Then follow the detected settings (indent style, test framework, etc.) for all operations.
现在将五种模式组合成一个完整的端到端工作流。
graph TB
subgraph "Stage 1: Fan-Out 并行检查"
A[输入: Git Diff] --> B[Lint Check]
A --> C[Security Scan]
A --> D[Performance Review]
end
subgraph "Stage 2: Aggregator 汇总"
B --> E[Review Aggregator]
C --> E
D --> E
end
subgraph "Stage 3: Chain 顺序执行"
E --> F[Generate Review Report]
F --> G[Generate Doc Changes]
end
subgraph "Stage 4: Pipeline 条件输出"
G --> H{Quality Gate}
H -->|Score >= 80| I[Auto-create PR]
H -->|Score < 80| J[Output Fix List]
end
subgraph "Singleton (贯穿全程)"
K[Project Config]
K -.-> B
K -.-> C
K -.-> D
K -.-> F
end
style A fill:#e1f5fe
style I fill:#c8e6c9
style J fill:#ffebee
style K fill:#f3e5f5
创建文件 ~/.claude/skills/auto-review/SKILL.md:
---
name: auto-review
description: "Automated code review pipeline. Runs parallel checks, aggregates results, generates report, and creates PR if quality gate passes. Trigger: after code changes are ready for review."
instructions: |
You are an automated code review pipeline. Execute the following workflow:
## Step 0: Load Configuration
Invoke /project-config to load project conventions. Use these settings throughout.
## Step 1: Gather Context
1. Run `git diff --name-only HEAD~1` to get changed files
2. Run `git diff HEAD~1` to get the actual changes
3. Identify changed file types and modules
## Step 2: Parallel Analysis (Fan-Out)
Use the Task tool to run these analyses IN PARALLEL:
### 2a: Code Quality Check
- Run linter on changed files
- Check for code smells (duplicate code, long functions, deep nesting)
- Score: 0-100
### 2b: Security Analysis
- Scan changed code for vulnerability patterns
- Check for secret exposure
- Run dependency audit if package files changed
- Score: 0-100
### 2c: Performance Impact
- Check for N+1 queries in changed code
- Analyze bundle size impact (if frontend)
- Check for unnecessary re-renders or re-computations
- Score: 0-100
## Step 3: Aggregate Results
Combine all check results into a unified review:
| Category | Score | Status | Critical Issues |
|----------|-------|--------|----------------|
| Quality | ?/100 | ? | ? |
| Security | ?/100 | ? | ? |
| Performance | ?/100 | ? | ? |
| **Overall** | **?/100** | **?** | **?** |
## Step 4: Quality Gate
- Overall score >= 80: PASS → proceed to PR creation
- Overall score 60-79: WARN → create PR with warnings
- Overall score < 60: FAIL → output fix list only
## Step 5: Output
### If PASS or WARN:
1. Generate review summary in Markdown
2. Suggest PR title following Conventional Commits
3. Generate PR body with review findings
4. Run `gh pr create` with the generated title and body
### If FAIL:
1. Generate prioritized fix list
2. Group fixes by file
3. Suggest specific code changes for each issue
4. Save to `.claude/review-fixes.md`
---
在完成代码修改后,只需一条命令:
> /auto-review
Claude Code会自动执行所有步骤,从并行分析到质量门禁判断,最终输出审查报告或自动创建PR。
# Automated Code Review Report
**Date**: 2026-05-21
**Commit**: abc1234
**Files Changed**: 5
## Parallel Analysis Results
| Category | Score | Status | Critical Issues |
|----------|-------|--------|----------------|
| Quality | 92/100 | PASS | None |
| Security | 85/100 | PASS | 1 medium: missing input validation |
| Performance | 88/100 | PASS | None |
| **Overall** | **88/100** | **PASS** | **1** |
## Recommendations
1. Add input validation in `src/api/users.ts:45` (sanitize email field)
## PR Created
✓ PR #42: "feat: add user registration endpoint"
https://github.com/org/repo/pull/42
基于对650+次Skill激活测试和100+社区Skill验证的总结:
Skill的description字段直接决定Claude是否能正确匹配和激活。社区实测数据显示,精心设计的description可以达到88%的激活率,而模糊描述只有20-30%。
好的description包含三类信息: - 动作词:format、scan、review、generate、deploy - 触发场景:when committing code、after test failure、for PR creation - 技术栈关键词:TypeScript、React、PostgreSQL、Docker
# 差的 description
description: "Code review tool"
# 好的 description
description: "Automated code review for TypeScript/React projects. Runs lint, type check, security scan, and generates review report. Use when reviewing pull requests or before committing changes."
每个Skill的输出应该使用固定的Markdown结构,便于下游Skill解析:
## [Skill Name] Result
- Status: PASS | FAIL | WARN
- [Metric]: [Value]
- Issues: [List or "none"]
Anthropic官方指南建议SKILL.md控制在500行以内。超过这个长度,考虑拆分为多个Skill并用Router或Pipeline模式组合。
每个Skill必须定义FAIL状态的行为。没有错误处理的Skill在Pipeline中会成为断链点。
使用以下方法测试Skill是否能被正确触发:
# 在Claude Code中测试
> "帮我检查一下代码安全性" # 应触发security相关Skill
> "格式化代码" # 应触发format Skill
> "运行完整的代码审查" # 应触发auto-review
如果某个关键词组合未能触发正确的Skill,修改该Skill的description添加缺失的触发词。
Skill的Token消耗取决于其被加载的时机:
| 策略 | Token消耗 | 适用场景 |
|---|---|---|
| 全部放入CLAUDE.md | 每次100%加载 | 3个以内的小型Skill集 |
| 独立SKILL.md按需加载 | 仅激活时加载 | 5个以上的Skill库 |
| Router + 子Skill | Router常驻,子Skill按需 | 10个以上的大型Skill系统 |
对于复杂的Skill,使用分层结构减少Token消耗:
instructions: |
# Quick Reference (always loaded)
Run `npm test` for tests, `npm run lint` for linting.
# Detailed Instructions (loaded on demand)
<details>
<summary>Advanced configuration</summary>
## Custom test runner
If package.json has "test:ci" script, use that instead.
For coverage, add --coverage flag.
## Parallel execution
Use `npm run test -- --workers=4` for parallel test execution.
</details>
| 优化手段 | Token节省 | 实施难度 |
|---|---|---|
| 500行限制 | 30-50% | 低 |
| 渐进披露 | 20-40% | 中 |
| 拆分为子Skill | 40-60% | 中 |
| Singleton共享配置 | 15-25% | 低 |
1. description是否包含触发关键词? → 添加场景描述词
2. SKILL.md是否在正确的目录? → 检查 ~/.claude/skills/ 或 .claude/skills/
3. YAML frontmatter格式是否正确? → 检查缩进和引号
4. 是否被其他更高优先级的Skill拦截? → 减少Skill数量或优化description区分度
5. instructions是否太模糊? → 添加具体的触发条件
根据对100+社区Skill的验证结果,最常见的错误模式:
| # | 反模式 | 问题 | 修复 |
|---|---|---|---|
| 1 | 上帝Skill | 一个Skill做所有事 | 拆分为Chain或Fan-Out |
| 2 | 隐式依赖 | Skill B假设Skill A已运行 | 在instructions中显式声明前置条件 |
| 3. | 模糊description | "Helper for developers" | 写具体的动作+场景+技术栈 |
| 4 | 无错误处理 | 只写成功路径 | 每个分支都有FAIL处理 |
| 5 | 硬编码路径 | /Users/john/project |
使用相对路径或自动检测 |
| 6 | 输出格式不统一 | 每次输出结构不同 | 固定Markdown模板 |
| 7 | 过度嵌套 | Skill调用Skill再调用Skill | 最多2层嵌套 |
当你的Skill组合成熟后,可以打包为Claude Code Plugin,通过一个plugin.json统一管理:
{
"name": "code-quality-pipeline",
"version": "1.2.0",
"description": "Multi-stage code quality pipeline with 5 design patterns",
"skills": [
"skills/01-format/SKILL.md",
"skills/02-typecheck/SKILL.md",
"skills/03-test/SKILL.md",
"skills/code-review-router/SKILL.md",
"skills/security-aggregator/SKILL.md",
"skills/ci-pipeline/SKILL.md",
"skills/project-config/SKILL.md",
"skills/auto-review/SKILL.md"
],
"commands": {
"review": "Run the full automated code review pipeline",
"check": "Run quick format + lint check",
"security": "Run security scan and generate report"
}
}
| 渠道 | 适合 | 方式 |
|---|---|---|
| GitHub仓库 | 开源Skill集 | git clone 到 ~/.claude/skills/ |
| npm包 | Node生态 | npm install -g your-skill-pack |
| Claude Plugin Marketplace | 官方生态 | 提交到Anthropic官方目录 |
| 企业内部Registry | 私有Skill | Git Submodule同步到100+仓库 |
| 维度 | 评估 |
|---|---|
| 适合训练营 | 中高级AI工程训练营、DevOps自动化训练营 |
| 教学时长 | 4-5小时(含动手实验) |
| 实验环境 | 需要一个包含lint/test配置的代码仓库 |
| 难度等级 | 中级偏上(需要Skill基础) |
| 最佳分组 | 2-3人小组,每组选择一种模式实现并交叉Review |
[!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 等场景全覆盖。
