Overview
Writing skills is applying test-driven development to process documentation.
Personal skills live in an agent-specific directory (Claude Code uses ~/.claude/skills, Codex uses ~/.agents/skills/)
You write test cases (stress scenarios with subagents), watch them fail (baseline behavior), write the skill (documentation), watch the tests pass (the agent complies), then refactor (close the loopholes).
Core principle: If you haven't watched the agent fail without the skill, you don't know whether the skill teaches the right thing.
REQUIRED BACKGROUND: Before using this skill, you must understand superpowers:test-driven-development. That skill defines the foundational RED-GREEN-REFACTOR cycle. This skill adapts TDD to documentation.
Official guidance: Anthropic's official skill-writing best practices are in anthropic-best-practices.md. This document provides additional patterns and guidance to supplement this skill's TDD-centered approach.
What Is a Skill?
A skillis a reference guide to a proven technique, pattern, or tool. Skills help future Claude instances find and apply effective methods.
A skill is: A reusable technique, pattern, tool, reference guide
A skill is not: A narrative about how you solved a problem one time
TDD Mapping for Skills
| TDD Concept | Skill Creation |
|---|---|
| Test case | Stress scenario with subagent |
| Production code | Skill documentation (SKILL.md) |
| Test fails (RED) | Agent violates the rule without the skill (baseline) |
| Test passes (GREEN) | Agent complies with the skill present |
| Refactor | Close loopholes while maintaining compliance |
| Write the test first | Run the baseline scenario before writing the skill |
| Watch it fail | Record the exact rationalizations the agent uses |
| Minimal code | Write a skill that addresses only these specific violations |
| Watch it pass | Verify the agent now complies |
| Refactor loop | Find new rationalizations → close them → re-verify |
The entire skill creation process follows RED-GREEN-REFACTOR.
When to Create a Skill
Create when:
- The technique is not intuitively obvious to you
- You will reference it again across multiple projects
- The pattern applies broadly (not project-specific)
- Others will benefit too
Do not create for:
- One-off solutions
- Standard practices already well documented elsewhere
- Project-specific conventions (put them in CLAUDE.md)
- Mechanical constraints (if it can be enforced with regex/validation, automate it; leave documentation for situations that require judgment)
Skill Types
Technique
Concrete methods with executable steps (condition-based-waiting, root-cause-tracing)
Pattern
Ways of thinking about problems (flatten-with-flags, test-invariants)
Reference
API documentation, syntax guides, tool documentation (office documents)
Directory structure
skills/
skill-name/
SKILL.md # Main reference (required)
supporting-file.* # Only if needed
Flat namespace - All skills located in one searchable namespace
The following are kept as separate files:
- Large reference materials(100+ lines) - API documentation, complete syntax
- Reusable tools - Scripts, utilities, templates
The following are kept in the body:
- Principles and concepts
- Code patterns (< 50 lines)
- Everything else
SKILL.md structure
Frontmatter(YAML):
- Two required fields:
nameanddescription(for all supported fields see agentskills.io/specification) - Maximum of 1024 characters total
name: use only letters, numbers, and hyphens (no parentheses, special characters)description: third person, describe only when to use it (not what it does)- Start with "Use when...", focus on trigger conditions
- Include specific symptoms, situations, and contexts
- Never summarize the skill's process or workflow(for the reason, see the CSO section)
- Keep it under 500 characters if possible
---
name: Skill-Name-With-Hyphens
description: Use when [specific triggering conditions and symptoms]
---
# Skill Name
## 概述
What is this? Core principle in 1-2 sentences.
## When to Use
[Small inline flowchart IF decision non-obvious]
Bullet list with SYMPTOMS and use cases
When NOT to use
## Core Pattern (for techniques/patterns)
Before/after code comparison
## Quick Reference
Table or bullets for scanning common operations
## Implementation
Inline code for simple patterns
Link to file for heavy reference or reusable tools
## Common Mistakes
What goes wrong + fixes
## Real-World Impact (optional)
Concrete results
Claude Search Optimization (CSO)
Critical for discovery: Future Claudes need to find your skill
1. Rich Description field
Purpose: Claude reads the description to decide which skills to load for a given task. Let it answer: "Should I read this skill right now?"
Format: Start with "Use when...", focus on trigger conditions
Key: Description = when to use, not what the skill does
The description should only describe trigger conditions. Do not summarize the skill's process or workflow in the description.
Why this matters: Testing found that when the description summarizes the skill workflow, Claude may follow the description instead of reading the full skill content. A description saying "code review between tasks" caused Claude to perform only one review, even though the skill flowchart clearly showed that two reviews were required (first check spec compliance, then check code quality).
After the description was changed to only say "Use when executing implementation plans with independent tasks" (with no workflow summary), Claude correctly read the flowchart and followed the two-phase review process.
Pitfall: A description that summarizes the workflow creates a shortcut that Claude will take. The skill body becomes documentation that Claude skips.
# ❌ BAD: Summarizes workflow - Claude may follow this instead of reading skill
description: Use when executing plans - dispatches subagent per task with code review between tasks
# ❌ BAD: Too much process detail
description: Use for TDD - write test first, watch it fail, write minimal code, refactor
# ✅ GOOD: Just triggering conditions, no workflow summary
description: Use when executing implementation plans with independent tasks in the current session
# ✅ GOOD: Triggering conditions only
description: Use when implementing any feature or bugfix, before writing implementation code
Content:
- Use specific triggers, symptoms, and situations to indicate that this skill applies
- DescriptionProblem(race conditions, inconsistent behavior), notLanguage-specific symptoms(setTimeout、sleep)
- Unless the skill itself is technology-specific, keep trigger conditions technology-agnostic
- If the skill is technology-specific, state that explicitly in the trigger conditions
- Use third person (will be injected into the system prompt)
- Never summarize the skill's process or workflow
# ❌ BAD: Too abstract, vague, doesn't include when to use
description: For async testing
# ❌ BAD: First person
description: I can help you with async tests when they're flaky
# ❌ BAD: Mentions technology but skill isn't specific to it
description: Use when tests use setTimeout/sleep and are flaky
# ✅ GOOD: Starts with "Use when", describes problem, no workflow
description: Use when tests have race conditions, timing dependencies, or pass/fail inconsistently
# ✅ GOOD: Technology-specific skill with explicit trigger
description: Use when using React Router and handling authentication redirects
2. Keyword coverage
Use words that Claude would search for:
- Error messages: "Hook timed out", "ENOTEMPTY", "race condition"
- Symptoms: "flaky", "hanging", "zombie", "pollution"
- Synonyms: "timeout/hang/freeze", "cleanup/teardown/afterEach"
- Tools: actual commands, library names, file types
3. Descriptive naming
Use active voice, verbs first:
- ✅
creating-skillsinstead ofskill-creation - ✅
condition-based-waitinginstead ofasync-test-helpers
4. Token efficiency (critical)
Problem: getting-started and frequently referenced skills get loaded into every conversation. Every token matters.
Target word counts:
- getting-started workflows: <150 words each
- Frequently loaded skills: <200 words total
- Other skills: <500 words (still needs to be concise)
Techniques:
Move details into tool help:
# ❌ BAD: Document all flags in SKILL.md
search-conversations supports --text, --both, --after DATE, --before DATE, --limit N
# ✅ GOOD: Reference --help
search-conversations supports multiple modes and filters. Run --help for details.
Use cross-references:
# ❌ BAD: Repeat workflow details
When searching, dispatch subagent with template...
[20 lines of repeated instructions]
# ✅ GOOD: Reference other skill
Always use subagents (50-100x context savings). REQUIRED: Use [other-skill-name] for workflow.
Compress examples:
# ❌ BAD: Verbose example (42 words)
your human partner: "How did we handle authentication errors in React Router before?"
You: I'll search past conversations for React Router authentication patterns.
[Dispatch subagent with search query: "React Router authentication error handling 401"]
# ✅ GOOD: Minimal example (20 words)
Partner: "How did we handle auth errors in React Router?"
You: Searching...
[Dispatch subagent → synthesis]
Eliminate redundancy:
- Don't repeat content from cross-referenced skills
- Don't explain what is self-evident about the command itself
- Don't include multiple examples for the same pattern
Validation:
wc -w skills/path/SKILL.md
# getting-started workflows: aim for <150 each
# Other frequently-loaded: aim for <200 total
Name it by what you do or the core insight:
- ✅
condition-based-waiting>async-test-helpers - ✅
using-skillsinstead ofskill-usage - ✅
flatten-with-flags>data-structure-refactoring - ✅
root-cause-tracing>debugging-techniques
Gerunds (-ing) work well for processes:
creating-skills,testing-skills,debugging-with-logs- Active, describes the action you are taking
4. Cross-reference other skills
When writing documentation that references other skills:
Use only the skill name, with a clear requirement marker:
- ✅ Good:
**REQUIRED SUB-SKILL:** Use superpowers:test-driven-development - ✅ Good:
**REQUIRED BACKGROUND:** You MUST understand superpowers:systematic-debugging - ❌ Bad:
See skills/testing/test-driven-development(unclear whether required) - ❌ Bad:
@skills/testing/test-driven-development/SKILL.md(forced load, consumes context)
Why not @ links: @ syntax immediately forces the file to load, consuming 200k+ context before you actually need it.
Flowchart usage
digraph when_flowchart {
"Need to show information?" [shape=diamond];
"Decision where I might go wrong?" [shape=diamond];
"Use markdown" [shape=box];
"Small inline flowchart" [shape=box];
"Need to show information?" -> "Decision where I might go wrong?" [label="yes"];
"Decision where I might go wrong?" -> "Small inline flowchart" [label="yes"];
"Decision where I might go wrong?" -> "Use markdown" [label="no"];
}
Use flowcharts only in the following cases:
- Non-obvious decision points
- Process loops where you might stop too early
- "When to use A vs B" decisions
Never use flowcharts for the following:
- Reference material → tables, lists
- Code examples → Markdown code blocks
- Linear instructions → numbered lists
- Labels with no semantic meaning (step1, helper2)
See @graphviz-conventions.dot for graphviz style rules.
Visualize for your human partner: Use render-graphs.js in this directory to render skill flowcharts as SVG:
./render-graphs.js ../some-skill # Each diagram separately
./render-graphs.js ../some-skill --combine # All diagrams in one SVG
Code examples
One excellent example beats many mediocre ones
Choose the most relevant language:
- Testing techniques → TypeScript/JavaScript
- System debugging → Shell/Python
- Data processing → Python
Good examples:
- Complete and runnable
- Well commented, explaining why
- From real scenarios
- Clearly demonstrate the pattern
- Can be directly adapted (not a generic template)
Don't:
- Implement in 5+ languages
- Create fill-in-the-blank templates
- Write contrived examples
You are good at porting; one excellent example is enough.
File organization
Self-contained skill
defense-in-depth/
SKILL.md # Everything inline
When to use: everything fits and no large reference materials are needed
Skill with reusable tools
condition-based-waiting/
SKILL.md # Overview + patterns
example.ts # Working helpers to adapt
When to use: the tools are reusable code, not just narrative
Skill with large reference materials
pptx/
SKILL.md # Overview + workflows
pptxgenjs.md # 600 lines API reference
ooxml.md # 500 lines XML structure
scripts/ # Executable tools
When to use: the reference materials are too large to inline
Iron rule (same as TDD)
NO SKILL WITHOUT A FAILING TEST FIRST
This applies both to new skills and to edits of existing skills.
Write a skill before testing it? Delete it and start over. Edit a skill without testing it? Same violation.
No exceptions:
- "Simple addition" is no exception
- "Just adding a small section" is no exception
- "Documentation update" is no exception
- Don't keep untested changes as a "reference"
- Don't "adapt" it while running tests
- Deleting means deleting
REQUIRED BACKGROUND: The superpowers:test-driven-development skill explains why this matters. The same principle applies to documentation.
Test all skill types
Different skill types require different testing methods:
Discipline-enforcing skills (rules/requirements)
Examples: TDD、verification-before-completion、designing-before-coding
How to test:
- Academic questions: Do they understand the rules?
- Pressure scenarios: Do they comply under pressure?
- Combinations of multiple pressures: time + sunk cost + fatigue
- Identify rationalizations and add explicit countermeasures
Success criteria: The agent follows the rules under maximum pressure
Technique-type skills (how-to guides)
Examples: condition-based-waiting、root-cause-tracing、defensive-programming
How to test:
- Application scenarios: Can they apply the technique correctly?
- Variation scenarios: Can they handle edge cases?
- Missing information test: Are there gaps in the explanation?
Success criteria: The agent can successfully apply the technique to new scenarios
Pattern-type skills (mental models)
Examples: reducing-complexity, information-hiding concepts
How to test:
- Recognition scenarios: Can they recognize when the pattern applies?
- Application scenarios: Can they use the mental model?
- Counterexamples: Do they know when not to apply it?
Success criteria: The agent can correctly recognize when and how to apply the pattern
Reference-type skills (documentation/APIs)
Examples: API documentation, command references, library guides
How to test:
- Retrieval scenarios: Can they find the correct information?
- Application scenarios: Can they correctly use the information they find?
- Gap test: Are common use cases covered?
Success criteria: The agent can find and correctly apply the reference information
Common rationalizations for skipping tests
| Excuse | Reality |
|---|---|
| "The skill is obviously clear" | Clear to you ≠ clear to other agents. Test it. |
| "It's just reference material" | Reference material may have gaps or unclear sections. Test retrieval. |
| "Too much testing" | An untested skill definitely has problems. 15 minutes of testing can save hours. |
| "I'll test if problems come up" | Problems = agents can't use the skill. Test before deployment. |
| "Testing is too tedious" | Testing is less tedious than debugging a broken skill in production. |
| "I'm sure it's good" | Overconfidence inevitably brings problems. Test anyway. |
| "Academic review is enough" | Reading ≠ using. Test application scenarios. |
| "No time to test" | Deploying an untested skill wastes even more time on later fixes. |
All of this means: test before deployment. No exceptions.
Make skills resistant to rationalization excuses
Skills that enforce discipline (such as TDD) need to resist rationalization excuses. Agents are smart and will find loopholes under pressure.
Psychology note: Understanding why persuasion techniques work helps apply them systematically. For the research basis on the principles of authority, commitment, scarcity, social proof, and consistency (Cialdini, 2021; Meincke et al., 2025), see persuasion-principles.md.
Explicitly close every loophole
Don't just state the rule; also prohibit specific workarounds:
No exceptions:
- Don't keep it as "reference"
- Don't "adapt" it while writing tests
- Don't look at it
- Delete means delete
</Good>
### 处理“精神 vs 字面”论点
尽早加入基础原则:
```markdown
**Violating the letter of the rules is violating the spirit of the rules.**
This cuts off the entire class of "I'm following the spirit" rationalization excuses.
Build a rationalization excuse table
Capture rationalization excuses from baseline testing (see the testing section below). Put every excuse the agent raises into the table:
| Excuse | Reality |
|--------|---------|
| "Too simple to test" | Simple code breaks. Test takes 30 seconds. |
| "I'll test after" | Tests passing immediately prove nothing. |
| "Tests after achieve same goals" | Tests-after = "what does this do?" Tests-first = "what should this do?" |
Create a red flag list
Make it easy for the agent to self-check when rationalizing:
## Red Flags - STOP and Start Over
- Code before test
- "I already manually tested it"
- "Tests after achieve the same purpose"
- "It's about spirit not ritual"
- "This is different because..."
**所有这些都意味着:删除代码。用 TDD 重新开始。**
Update CSO for violation symptoms
Add to description: symptoms for when you are about to violate the rule:
description: use when implementing any feature or bugfix, before writing implementation code
RED-GREEN-REFACTOR for skills
Follow the TDD cycle:
RED: Write a failing test (baseline)
Without the skill, run stress scenarios with a subagent. Record the exact behavior:
- What choices did they make?
- What rationalization excuses did they use (record verbatim)?
- Which pressures triggered violations?
This is "watch the test fail" - before writing the skill, you must see what the agent naturally does.
GREEN: Write the minimal skill
Write a skill that handles these specific rationalization excuses. Don't add extra content for hypothetical situations.
Run the same scenarios with the skill. The agent should now comply.
REFACTOR: Close loopholes
Did the agent find new rationalization excuses? Add explicit countermeasures. Retest until solid.
Testing method: For the complete testing method, see @testing-skills-with-subagents.md:
- How to write stress scenarios
- Stress types (time, sunk cost, authority, exhaustion)
- Systematically closing holes
- Meta-testing techniques
Anti-patterns
❌ Narrative examples
"In the session on 2025-10-03, we found that an empty projectDir caused..." Why it's bad: Too specific, not reusable
❌ Multilingual dilution
example-js.js, example-py.py, example-go.go Why it's bad: Mediocre quality, heavy maintenance burden
❌ Code in a flowchart
step1 [label="import fs"];
step2 [label="read file"];
Why it's bad: Cannot copy and paste, hard to read
❌ Vague labels
helper1, helper2, step3, pattern4 Why it's bad: Labels should have semantic meaning
STOP: Before moving on to the next skill
After writing any skill, you must stop and complete the deployment process.
Do not:
- Create multiple skills in batch without testing them one by one
- Move on to the next skill before the current skill is verified
- Skip testing because "batching is more efficient"
The deployment checklist below is mandatory for every skill.
Deploying an untested skill = deploying untested code. This violates quality standards.
Skill Creation Checklist (TDD Adaptation)
Important: Use TodoWrite to create a todo for each checklist item below.
RED phase - Write failing tests:
- Create pressure scenarios (discipline-type skills need 3+ combined pressures)
- Run the scenarios without the skill - record baseline behavior verbatim
- Identify patterns in rationalizations/excuses/failures
GREEN phase - Write the minimal skill:
- Name uses only letters, numbers, hyphens (no parentheses/special characters)
- YAML frontmatter includes the required
nameanddescriptionfields (max 1024 characters; see spec) - Description starts with "Use when..." and includes specific triggers/symptoms
- Description is written in the third person
- Includes keywords for search throughout (errors, symptoms, tools)
- Has a clear overview and core principles
- Addresses the specific baseline failures identified in RED
- Code is inline or linked to a separate file
- One excellent example (not multilingual)
- Run the scenarios with the skill - verify the agent now complies
REFACTOR phase - Close the loopholes:
- Identify new rationalizations that appeared in testing
- Add explicit counters (if it's a discipline-type skill)
- Build a rationalization table from all test iterations
- Create a red flags list
- Retest until solid
Quality check:
- Use a small flowchart only when the decision is not obvious
- Quick reference table
- Common mistakes section
- No narrative stories
- Support files only for tools or large reference materials
Deploy:
- Commit the skill to git and push to your fork (if configured)
- Consider contributing back via PR (if broadly useful)
Discovery Workflow
How future Claudes find your skill:
- Encounters a problem("tests are flaky")
- Finds the SKILL(description matches)
- Scans the overview(is this relevant?)
- Reads the pattern(Quick Reference Table)
- Loading Examples(only when implementing)
Optimize for this process - Put searchable terms in early and often.
Bottom Line
Creating a skill is TDD for process documentation.
The same iron law: no skill without a failing test first. The same cycle: RED (baseline) → GREEN (write the skill) → REFACTOR (close the loopholes). The same benefits: higher quality, fewer surprises, more solid results.
If you follow TDD for code, follow it for skills too. It's the same discipline applied to documentation.