---
name: writing-skills
description: Use when creating new skills, editing existing skills, or verifying skills work before deployment
---

# Writing Skills

Audience: AI coding agents first. Optimize for model activation.

Writing skills = TDD for process documentation. RED → GREEN → REFACTOR.

Skills live in `~/.claude/skills/` (Claude Code) or `~/.agents/skills/` (Codex).

**REQUIRED BACKGROUND:** Understand tdd before using this skill. Same RED-GREEN-REFACTOR cycle applies.

## What is a Skill?

**Skill = reference guide** for proven techniques, patterns, tools.
**NEVER:** narrative about how you solved something once.

## TDD Mapping

| TDD Concept | Skill Creation |
|-------------|----------------|
| Test case | Pressure scenario with subagent |
| Production code | Skill document (SKILL.md) |
| RED | Agent violates rule without skill (baseline) |
| GREEN | Agent complies with skill present |
| Refactor | Close loopholes while maintaining compliance |
| Write test first | Run baseline scenario BEFORE writing skill |
| Watch it fail | Document exact rationalizations agent uses |
| Minimal code | Write skill addressing those specific violations |
| Watch it pass | Verify agent now complies |
| Refactor cycle | Find new rationalizations → plug → re-verify |

## When to Create

**Create when:**
- Technique wasn't intuitively obvious
- Reusable across projects
- Pattern applies broadly
- Others benefit

**Don't create for:**
- One-off solutions
- Standard practices documented elsewhere
- Project-specific conventions → CLAUDE.md
- Mechanically enforceable constraints → automate instead

## Skill Types

- **Technique** — concrete method with steps (condition-based-waiting)
- **Pattern** — way of thinking about problems (flatten-with-flags)
- **Reference** — API docs, syntax guides

## File Organization

### Self-Contained Skill
```
defense-in-depth/
  SKILL.md    # Everything inline
```
When: All content fits, no heavy reference needed

### Skill with Reusable Tool
```
condition-based-waiting/
  SKILL.md    # Overview + patterns
  example.ts  # Working helpers to adapt
```
When: Tool is reusable code, not just narrative

### Skill with Heavy Reference
```
pptx/
  SKILL.md       # Overview + workflows
  pptxgenjs.md   # 600 lines API reference
  ooxml.md       # 500 lines XML structure
  scripts/       # Executable tools
```
When: Reference material too large for inline

## SKILL.md Structure

**Frontmatter:**
- `name`: letters, numbers, hyphens only. No parentheses/special chars.
- `description`: max 1024 chars total. Third-person. Starts with "Use when..."
  - **CRITICAL: description = triggering conditions ONLY. NEVER summarize workflow.**
  - Workflow-in-description creates shortcut Claude takes instead of reading skill body.

```yaml
# ❌ BAD: Summarizes workflow — Claude follows description, skips skill body
description: Use when executing plans — dispatches subagent per task with code review between tasks

# ✅ GOOD: Triggering conditions only
description: Use when executing implementation plans with independent tasks in the current session
```

```markdown
---
name: Skill-Name-With-Hyphens
description: Use when [specific triggering conditions and symptoms]
---

# Skill Name

## Overview
Core principle in 1-2 sentences.

## When to Use
[Small inline flowchart IF decision non-obvious]
Symptoms and use cases. When NOT to use.

## Core Pattern
Before/after code comparison.

## Quick Reference
Table or bullets for scanning.

## Implementation
Inline code for simple patterns. Link to file for heavy reference.

## Common Mistakes
What goes wrong + fixes.
```

## Claude Search Optimization (CSO)

### Description Field

**description = When to Use, NOT What the Skill Does**

Workflow-in-description → Claude follows description instead of reading skill body.

```yaml
# ❌ BAD: too abstract
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 tech-specific
description: Use when tests use setTimeout/sleep and are flaky

# ✅ GOOD: problem-focused, no workflow
description: Use when tests have race conditions, timing dependencies, or pass/fail inconsistently

# ✅ GOOD: tech-specific with explicit trigger
description: Use when using React Router and handling authentication redirects
```

### Keyword Coverage

Use words 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

### Naming

Active voice, verb-first:
- ✅ `creating-skills` not `skill-creation`
- ✅ `condition-based-waiting` not `async-test-helpers`
- Gerunds (-ing) work well for processes

### Token Efficiency

**Target word counts:**
- getting-started workflows: <150 words
- Frequently-loaded: <200 words total
- Other skills: <500 words

Techniques: move flag details to `--help`, use cross-references, compress examples, eliminate redundancy.

### Cross-Referencing Skills

```markdown
# ✅ GOOD
**REQUIRED SUB-SKILL:** Use tdd
**REQUIRED BACKGROUND:** You MUST understand debug

# ❌ BAD
See skills/tdd                    # unclear if required
@skills/tdd/SKILL.md              # force-loads, burns context
```

## Flowchart Usage

```dot
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 for:** non-obvious decision points, process loops where you might stop early, "A vs B" decisions.

**NEVER for:** reference material (→ tables), code examples (→ code blocks), linear instructions (→ numbered lists), labels without semantic meaning.

## Code Examples

One excellent example beats many mediocre ones.

**Good example:** complete and runnable, from real scenario, shows pattern clearly, ready to adapt.
**Language:** testing → TypeScript/JS; system debugging → Shell/Python; data processing → Python.
**Don't:** implement in 5+ languages, create fill-in-the-blank templates, write contrived examples.

## The Iron Law

```
NO SKILL WITHOUT A FAILING TEST FIRST
```

Applies to NEW skills AND edits to existing skills.

Write skill before testing? Delete it. Start over.
Edit skill without testing? Same violation.

**No exceptions:**
- Not for "simple additions"
- Not for "just adding a section"
- Not for "documentation updates"
- Don't keep untested changes as "reference"
- Don't "adapt" while running tests
- Delete means delete

## Testing All Skill Types

### Discipline-Enforcing Skills

**Test with:** pressure scenarios combining time + sunk cost + exhaustion.
**Success criteria:** agent follows rule under maximum pressure.

### Technique Skills

**Test with:** application scenarios, variation scenarios, missing-information tests.
**Success criteria:** agent successfully applies technique to new scenario.

### Pattern Skills

**Test with:** recognition scenarios, application scenarios, counter-examples.
**Success criteria:** agent identifies when/how to apply pattern.

### Reference Skills

**Test with:** retrieval scenarios, application scenarios, gap testing.
**Success criteria:** agent finds and correctly applies reference information.

## Common Rationalizations for Skipping Testing

| Excuse | Reality |
|--------|---------|
| "Skill is obviously clear" | Clear to you ≠ clear to other agents. Test it. |
| "It's just a reference" | References can have gaps. Test retrieval. |
| "Testing is overkill" | Untested skills have issues. Always. 15 min testing saves hours. |
| "I'll test if problems emerge" | Problems = agents can't use skill. Test BEFORE deploying. |
| "Too tedious to test" | Testing < debugging bad skill in production. |
| "I'm confident it's good" | Overconfidence guarantees issues. Test anyway. |
| "Academic review is enough" | Reading ≠ using. Test application scenarios. |
| "No time to test" | Deploying untested skill wastes more time fixing it later. |

**All of these mean: Test before deploying. No exceptions.**

## Bulletproofing Against Rationalization

Close loopholes explicitly:

```markdown
# ❌ BAD: Leaves loophole
Write code before test? Delete it.

# ✅ GOOD: Closes all escapes
Write code before test? Delete it. Start over.
**No exceptions:**
- Don't keep it as "reference"
- Don't "adapt" it while writing tests
- Don't look at it
- Delete means delete
```

Add foundational principle early:
```markdown
**Violating the letter of the rules is violating the spirit of the rules.**
```

Build rationalization table from baseline testing. Add red flags list. Update CSO for violation symptoms.

## RED-GREEN-REFACTOR for Skills

### RED: Write Failing Test (Baseline)

Run pressure scenario WITHOUT skill. Document:
- What choices did they make?
- What rationalizations (verbatim)?
- Which pressures triggered violations?

MUST see what agents do before writing skill.

### GREEN: Write Minimal Skill

Address those specific rationalizations. Don't add content for hypothetical cases.
Run same scenarios WITH skill. Agent should comply.

### REFACTOR: Close Loopholes

Agent found new rationalization → add explicit counter → re-test until bulletproof.

## Anti-Patterns

❌ **Narrative example** — "In session 2025-10-03, we found..." → too specific, not reusable

❌ **Multi-language dilution** — example-js.js, example-py.py → mediocre quality, maintenance burden

❌ **Code in flowcharts** — can't copy-paste, hard to read

❌ **Generic labels** — helper1, step3 → labels must have semantic meaning

## STOP: Before Moving to Next Skill

After ANY skill, MUST complete deployment before next:
- NEVER create multiple skills in batch without testing each
- NEVER move to next skill before current verified
- Deploying untested skills = deploying untested code. Violation of quality standards.

## Skill Creation Checklist (TDD Adapted)

**IMPORTANT: Use TodoWrite for EACH checklist item below.**

**RED Phase — Write Failing Test:**
- [ ] Create pressure scenarios (3+ combined pressures for discipline skills)
- [ ] Run scenarios WITHOUT skill — document baseline behavior verbatim
- [ ] Identify patterns in rationalizations/failures

**GREEN Phase — Write Minimal Skill:**
- [ ] Name uses only letters, numbers, hyphens
- [ ] YAML frontmatter with `name` and `description` (max 1024 chars)
- [ ] Description starts with "Use when..." — triggering conditions only, NO workflow summary
- [ ] Description in third person
- [ ] Keywords throughout for search (errors, symptoms, tools)
- [ ] Clear overview with core principle
- [ ] Address specific baseline failures from RED
- [ ] Code inline OR link to separate file
- [ ] One excellent example (not multi-language)
- [ ] Run scenarios WITH skill — verify agents comply

**REFACTOR Phase — Close Loopholes:**
- [ ] Identify NEW rationalizations from testing
- [ ] Add explicit counters (if discipline skill)
- [ ] Build rationalization table from all test iterations
- [ ] Create red flags list
- [ ] Re-test until bulletproof

**Quality Checks:**
- [ ] Small flowchart only if decision non-obvious
- [ ] Quick reference table
- [ ] Common mistakes section
- [ ] No narrative storytelling
- [ ] Supporting files only for tools or heavy reference

**Deployment:**
- [ ] Commit to git and push (if configured)
- [ ] Consider PR if broadly useful

## Supporting Files

Load as needed — do NOT `@`-include (force-loads = context waste):

- `anthropic-best-practices.md` — Anthropic's official skill authoring guidance; read when writing description fields or structuring a new skill
- `testing-skills-with-subagents.md` — **complete testing methodology**; load when setting up pressure scenarios or baseline runs
- `graphviz-conventions.dot` — dotgraph style conventions; load when adding a flowchart
- `render-graphs.js` — render dotgraphs to PNG: `node render-graphs.js <file.dot>`
- `persuasion-principles.md` — behavioral levers for bulletproofing discipline skills; load when writing rationalization tables or red flags

## Discovery Workflow

1. Encounters problem ("tests are flaky")
2. Finds SKILL (description matches)
3. Scans overview (is this relevant?)
4. Reads patterns (quick reference table)
5. Loads example (only when implementing)

Optimize for this flow — put searchable terms early and often.
