building-skills

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Building Skills

技能构建

Read LEARNED.md before building or reviewing any skill.
在构建或审核任何技能前,请阅读LEARNED.md

Core Principles

核心原则

1. Context Window is Sacred

1. 上下文窗口至关重要

Skills share context with system prompt, conversation history, other skills, and the user's request. Only add what Claude doesn't already know.
For every line ask: Does this justify its token cost? If Claude knows it, cut it.
技能会与系统提示词、对话历史、其他技能以及用户请求共享上下文。仅添加Claude尚不了解的内容。
对每一行都要问自己: 它是否值得消耗对应的token?如果Claude已经知道,就删掉。

2. Progressive Disclosure

2. 渐进式披露

Skills load in three stages. Design for this.
StageWhat loadsBudgetContains
Discovery
name
+
description
~100 tokensTrigger keywords, when to use
ActivationSKILL.md body<5000 tokensInstructions, workflows, quick start
Executionreferences/, scripts/As neededDetailed docs, executable code
Critical: The
description
field is the trigger mechanism. All "when to use" info goes there, not the body. The body only loads AFTER triggering.
技能分三个阶段加载,请据此进行设计。
阶段加载内容Token预算包含信息
发现阶段
name
+
description
~100 tokens触发关键词、适用场景
激活阶段SKILL.md主体内容<5000 tokens操作说明、工作流、快速入门
执行阶段references/、scripts/按需加载详细文档、可执行代码
关键提示:
description
字段是触发机制。所有“何时使用”的信息都应放在这里,而非主体内容中。主体内容仅在触发后才会加载。

3. Degrees of Freedom

3. 自由度层级

Match instruction specificity to how fragile the task is:
  • High freedom (text guidance): Creative tasks, multiple valid approaches. "Write a blog post following these guidelines."
  • Medium freedom (parameterized scripts): Preferred pattern exists but adapts. "Run the audit script, interpret results."
  • Low freedom (exact scripts, few params): Fragile operations, API calls, deploys. "Run exactly:
    python scripts/deploy.py --env prod
    "
指令的具体程度应与任务的脆弱性相匹配:
  • 高自由度(文本指引):创意类任务、存在多种有效方案的场景。例如:“遵循以下指南撰写博客文章。”
  • 中自由度(参数化脚本):存在首选模式但可灵活调整的场景。例如:“运行审计脚本并解读结果。”
  • 低自由度(精确脚本、少量参数):脆弱性操作、API调用、部署等场景。例如:“严格执行:
    python scripts/deploy.py --env prod

4. Self-Learning is Mandatory

4. 自学习是强制要求

Every skill MUST have
LEARNED.md
with consolidation rules. No exceptions.
每个技能都必须包含带有整合规则的
LEARNED.md
文件,无例外。

Required Structure

必需结构

skill-name/
├── SKILL.md           # Required. <500 lines. Core instructions.
├── LEARNED.md         # Required. <50 lines. Dated entries + consolidation.
├── scripts/           # Executable code. Runs but never loaded into context.
├── references/        # Detailed docs. Loaded into context on demand (costs tokens).
├── setup/             # Credential templates, setup instructions.
└── assets/            # Files used in output (templates, icons). Never loaded into context.
Key distinction:
references/
costs tokens when read.
scripts/
and
assets/
don't - scripts execute and return output, assets are used in generated files. Put large docs, templates, and data in assets/ not references/.
skill-name/
├── SKILL.md           # 必填项。<500行。核心操作说明。
├── LEARNED.md         # 必填项。<50行。带日期的记录+整合规则。
├── scripts/           # 可执行代码。仅运行,不会加载到上下文中。
├── references/        # 详细文档。按需加载到上下文(消耗token)。
├── setup/             # 凭证模板、设置说明。
└── assets/            # 输出中使用的文件(模板、图标)。不会加载到上下文中。
核心区别:
references/
在读取时会消耗token。
scripts/
assets/
则不会——脚本执行后返回输出,资产用于生成文件。大型文档、模板和数据应放在assets/而非references/中。

Frontmatter

前置元数据

yaml
---
name: skill-name
description: |
  Third person. WHAT it does + WHEN to use it + trigger keywords.
  This is the primary trigger. Max 1024 chars. No angle brackets.
allowed-tools: Bash Read Write
---
name: kebab-case, max 64 chars, no consecutive/leading/trailing hyphens. Must match directory name.
description: The most important field. Claude reads ALL descriptions to decide which skill to trigger. Front-load trigger conditions. Include keywords users would actually say. Bad: "Manages Google Ads." Good: "Control Google Ads via official API. Create, pause, optimize campaigns, ads, keywords, bids. Run audits. Use when user mentions Google Ads, PPC, AdWords, Quality Score, or ad performance."
allowed-tools: Only tools the skill needs. Common:
Bash Read Write Edit
.
Allowed keys:
name
,
description
,
license
,
allowed-tools
,
metadata
,
compatibility
. Nothing else.
yaml
---
name: skill-name
description: |
  第三人称表述。说明技能功能+适用场景+触发关键词。
  这是主要触发依据。最多1024字符,不使用尖括号。
allowed-tools: Bash Read Write
---
name: 短横线命名格式,最多64字符,无连续/开头/结尾短横线。必须与目录名称一致。
description: 最重要的字段。Claude会读取所有技能的描述来决定触发哪一个。前置触发条件,包含用户实际会使用的关键词。反面示例:“管理Google Ads。” 正面示例:“通过官方API控制Google Ads。创建、暂停、优化广告系列、广告、关键词、出价。运行审计。当用户提及Google Ads、PPC、AdWords、质量得分或广告效果时使用。”
allowed-tools: 仅列出技能所需的工具。常见工具:
Bash Read Write Edit
允许的键:
name
description
license
allowed-tools
metadata
compatibility
。不允许其他键。

Creating a New Skill

创建新技能

1. Define trigger examples

1. 定义触发示例

Write 3-5 user requests this skill should fire on. These become description keywords and test cases.
编写3-5个该技能应触发的用户请求。这些将成为描述中的关键词和测试用例。

2. Scaffold

2. 生成脚手架

bash
python3 ~/.claude/skills/building-skills/scripts/init_skill.py my-skill --path ~/.claude/skills
This creates SKILL.md, LEARNED.md, scripts/, references/, setup/, and assets/ with guided TODOs.
bash
python3 ~/.claude/skills/building-skills/scripts/init_skill.py my-skill --path ~/.claude/skills
此命令会创建SKILL.md、LEARNED.md、scripts/、references/、setup/和assets/目录,并包含带指引的待办事项。

3. Write the description FIRST

3. 先编写描述

Before the body. The description determines if the skill ever triggers.
Pattern: [What it does] + [How/via what] + [Specific actions] + [Trigger keywords]
Example: "Local semantic search for markdown knowledge bases using qmd (tobi/qmd). Indexes markdown with BM25 keyword search, vector embeddings, and hybrid reranked queries. Auto-indexes on edits via Claude Code hooks. Use when searching project docs, knowledge bases, meeting notes, or any indexed markdown collection."
在编写主体内容前先完成描述。描述决定了技能是否会被触发。
模板: [功能] + [实现方式] + [具体操作] + [触发关键词]
示例:“使用qmd (tobi/qmd) 对Markdown知识库进行本地语义搜索。通过BM25关键词搜索、向量嵌入和混合重排查询为Markdown建立索引。通过Claude Code钩子在编辑时自动索引。适用于搜索项目文档、知识库、会议记录或任何已索引的Markdown集合。”

4. Write SKILL.md body

4. 编写SKILL.md主体内容

markdown
undefined
markdown
undefined

Skill Name

技能名称

Quick Start

快速入门

[Minimal working example - simplest successful use]
[最简可运行示例——最简单的成功使用场景]

Core Operations

核心操作

[Brief list. Link to references/ for detail if >100 lines.]
[简要列表。若内容超过100行,链接至references/查看详情。]

Workflows

工作流

[Checklists for multi-step tasks. Conditional routing for different paths.]
[多步骤任务的检查清单。针对不同路径的条件路由。]

Error Reference

错误参考

[Common errors and fixes. Keep actionable, not exhaustive.]
[常见错误及修复方案。保持可操作性,无需面面俱到。]

Self-Learning

自学习

[LEARNED.md link + what to record + consolidation rules]

**Stay under 500 lines.** If approaching 300, start splitting to references/.
[LEARNED.md链接 + 需记录的内容 + 整合规则]

**保持在500行以内。** 若接近300行,开始拆分至references/目录。

5. Add self-learning

5. 添加自学习功能

Create LEARNED.md:
markdown
undefined
创建LEARNED.md:
markdown
undefined

skill-name - Learned

skill-name - Learned

<!-- Keep under 50 lines. Consolidate before adding. -->
<!-- 保持在50行以内。添加新内容前先整合。 -->

[Category]

[分类]

  • (YYYY-MM-DD) Observation here

Add Self-Learning section to SKILL.md (see [template below](#self-learning-template)).
  • (YYYY-MM-DD) 观察记录

在SKILL.md中添加自学习章节(见下方[自学习模板](#self-learning-template))。

6. Add scripts with dependency checking

6. 添加带依赖检查的脚本

Scripts must detect missing deps and guide setup, not fail silently:
python
import os, sys
required = ['MY_API_KEY']
missing = [v for v in required if not os.environ.get(v)]
if missing:
    print(f"Missing: {', '.join(missing)}")
    print("Add to ~/.claude/settings.json under \"env\"")
    sys.exit(1)
脚本必须检测缺失的依赖并引导设置,而非静默失败:
python
import os, sys
required = ['MY_API_KEY']
missing = [v for v in required if not os.environ.get(v)]
if missing:
    print(f"Missing: {', '.join(missing)}")
    print("Add to ~/.claude/settings.json under \"env\"")
    sys.exit(1)

7. Validate

7. 验证

bash
python3 ~/.claude/skills/building-skills/scripts/validate_skill.py ~/.claude/skills/my-skill
Fix errors, address warnings, re-run until clean.
bash
python3 ~/.claude/skills/building-skills/scripts/validate_skill.py ~/.claude/skills/my-skill
修复错误、处理警告,重新运行直到无问题。

Restructuring an Existing Skill

重构现有技能

  1. Audit: SKILL.md line count (<500?), scripts inside skill?, credentials via env vars?, frontmatter valid?, LEARNED.md exists?, description has trigger keywords?
  2. Split: Core instructions → SKILL.md. Detailed docs → references/. Code → scripts/. Config → setup/. Output files → assets/.
  3. Fix description: Is it the trigger mechanism? Does it front-load keywords? Third person?
  4. Add self-learning: LEARNED.md + consolidation section.
  5. Validate: Run validate_skill.py.
  1. 审计:SKILL.md行数是否<500?脚本是否在技能目录内?凭证是否通过环境变量管理?前置元数据是否有效?LEARNED.md是否存在?描述是否包含触发关键词?
  2. 拆分:核心说明→SKILL.md。详细文档→references/。代码→scripts/。配置→setup/。输出文件→assets/。
  3. 优化描述:是否作为触发机制?是否前置关键词?是否为第三人称表述?
  4. 添加自学习:LEARNED.md + 整合章节。
  5. 验证:运行validate_skill.py。

Patterns

模式

Credentials

凭证管理

~/.claude/settings.json
env vars. Never hardcode. Scripts detect and print setup instructions. Document in
setup/README.md
.
使用
~/.claude/settings.json
环境变量。切勿硬编码。脚本需检测缺失并打印设置说明。在
setup/README.md
中记录相关信息。

Workflow Checklists

工作流检查清单

Multi-step tasks get numbered, copy-able checklists with explicit steps.
多步骤任务需使用编号、可复制的检查清单,包含明确步骤。

Conditional Routing

条件路由

markdown
**Creating new?** → See [Creation](#creation)
**Editing?** → See [Editing](#editing)
**Debugging?** → See [references/troubleshooting.md](references/troubleshooting.md)
markdown
**创建新内容?** → 查看[创建](#creation)
**编辑内容?** → 查看[编辑](#editing)
**调试?** → 查看[references/troubleshooting.md](references/troubleshooting.md)

Feedback Loops

反馈循环

markdown
1. Make changes → 2. Run validator → 3. If errors, fix and go to 2
markdown
1. 做出修改 → 2. 运行验证器 → 3. 若有错误,修复后回到步骤2

Output Templates

输出模板

Strict format: provide exact template in assets/. Flexible format: show examples.
严格格式:在assets/中提供精确模板。灵活格式:展示示例。

Hook Integration

钩子集成

Skills can hook into Claude Code (PreToolUse/PostToolUse) for system-level behavior like auto-indexing or domain blocking. Document in hooks/ subdirectory.
For detailed pattern examples, see references/patterns.md.
技能可挂钩Claude Code(PreToolUse/PostToolUse)以实现系统级行为,如自动索引或域名拦截。在hooks/子目录中记录相关信息。
如需详细的模式示例,请查看references/patterns.md

Anti-Patterns

反模式

Don'tDo
Trigger info only in bodyPut trigger keywords in
description
Credentials in skill files
~/.claude/settings.json
env vars
Scripts in global folderScripts inside skill directory
SKILL.md >500 linesSplit to references/
Nested references (A→B→C)One level deep from SKILL.md
No LEARNED.mdEvery skill must self-learn
Unbounded LEARNED.mdCap 50 lines, consolidate
README.md, CHANGELOG.md etcSkills are for AI, not human docs
"You can use..." in descriptionThird person: "Processes..."
Assume deps installedCheck and guide setup on failure
Large docs in references/Put in assets/ if not needed in context
切勿正确做法
仅在主体内容中放置触发信息将触发关键词放在
description
在技能文件中存储凭证使用
~/.claude/settings.json
环境变量
脚本放在全局目录脚本放在技能目录内
SKILL.md超过500行拆分至references/
嵌套引用(A→B→C)仅从SKILL.md进行一级引用
无LEARNED.md每个技能都必须具备自学习能力
LEARNED.md无限制限制在50行以内,定期整合
包含README.md、CHANGELOG.md等技能面向AI而非人类文档
描述中使用“你可以使用...”第三人称表述:“处理...”
假设依赖已安装检查依赖,失败时引导设置
在references/中存放大型文档若无需加载到上下文,放在assets/中

Self-Learning Template

自学习模板

markdown
undefined
markdown
undefined

Self-Learning

自学习

Read LEARNED.md before using this skill.
Update LEARNED.md when you discover: [list skill-specific things to record]
Consolidation (keep under 50 lines): Before adding a new entry, check file length. If over 50 lines:
  1. Merge duplicate/overlapping entries into single proven patterns
  2. Remove entries older than 3 months that haven't been reinforced
  3. Drop one-off observations that never recurred
  4. Move detailed context to
    LEARNED-archive.md
    if worth preserving
  5. Keep only entries that would change behavior - if obvious, cut it
undefined
使用此技能前,请阅读LEARNED.md
发现以下内容时更新LEARNED.md: [列出技能特定的需记录事项]
整合规则(保持在50行以内): 添加新条目前,检查文件长度。若超过50行:
  1. 将重复/重叠的条目合并为单一已验证模式
  2. 删除超过3个月且未被强化的条目
  3. 移除从未重复出现的一次性观察记录
  4. 若值得保留,将详细上下文移至
    LEARNED-archive.md
  5. 仅保留会改变行为的条目——若内容显而易见则删除
undefined

Self-Learning

自学习

Read LEARNED.md before building or reviewing any skill.
Update LEARNED.md when you discover:
  • Patterns that worked well in production skills
  • Description wording that improved or hurt triggering
  • Common mistakes when building skills
  • Validation gaps (things the validator should catch)
  • Structure decisions that helped or hurt
Consolidation (keep under 50 lines): Before adding, check length. If over 50: merge duplicates, prune stale (>3mo unreinforced), drop one-offs, archive to LEARNED-archive.md.
在构建或审核任何技能前,请阅读LEARNED.md
发现以下内容时更新LEARNED.md:
  • 在生产环境中效果良好的模式
  • 提升或降低触发效率的描述措辞
  • 构建技能时的常见错误
  • 验证工具未覆盖的漏洞
  • 对技能有帮助或有害的结构决策
整合规则(保持在50行以内): 添加新条目前检查长度。若超过50行:合并重复内容、清理过期(>3个月未强化)条目、删除一次性记录、将详细内容归档至LEARNED-archive.md。

References

参考资料

  • Patterns Reference - Workflow, output, credential, hook, and testing patterns
  • Anthropic Skill Spec - Official skill specification and examples
  • 模式参考 - 工作流、输出、凭证、钩子及测试模式
  • Anthropic技能规范 - 官方技能规范及示例