SuperAPI AI Directory

writing-skills

Writing & research

View repository

Updated 10-14 12:19

About this skill

Writing Skills

Overview

Writing skills is applying test-driven development to process documentation.

Personal skills live in the skills directory of the runtime environment you use(on Claude Code it is ~/.claude/skills/) — for paths in other runtime environments see codex-tools.md or gemini-tools.md. Codex, Copilot CLI, and Gemini CLI also all recognize ~/.agents/skills/, as a cross-runtime environment alias.

You write test cases (stress scenarios with subagents), watch them fail (baseline behavior), write the skill (documentation), watch the tests pass (the agent follows the rules), then refactor (plug the loopholes).

Core principle: If you have not observed the agent failing without the skill, you do not know whether this skill teaches the right thing.

Required background: Before using this skill, you must understand test-driven-development. That skill defines the basic red-green-refactor loop. This skill adapts TDD to documentation writing.

Official guidance: For Anthropic's official skill authoring best practices, see anthropic-best-practices.md. That document provides additional patterns and guidance that complement this skill's TDD-oriented 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: reusable techniques, patterns, tools, reference guides

A skill is not: a narrative about how you solved a problem one time

TDD mapped to skills

TDD concept Skill creation
Test case Stress scenario with subagents
Production code Skill documentation (SKILL.md)
Test fails (red) The agent violates the rules without the skill (baseline)
Test passes (green) The agent follows the rules with the skill
Refactor Plug the loopholes while maintaining compliance
Write the test first Run the baseline scenario before writing the skill
Observe failure Record the exact rationalizations the agent uses
Minimal code Write the skill to target those specific violations
Observe passing Verify that the agent now follows the rules
Refactor loop Discover new rationalizations → plug → 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 repeatedly reference it across different projects
  • The pattern has broad applicability (not project-specific)
  • Others will also benefit

Do not create:

  • One-off solutions
  • Standard practices that are well documented elsewhere
  • Project-specific conventions (put those in CLAUDE.md)
  • Mechanical constraints (automate with regex/validation if possible—leave documentation for scenarios that require judgment)

Skill types

Technique

Methods with concrete steps (condition-based-waiting, root-cause-tracing)

Pattern

Ways of thinking about problems (flatten-with-flags, test-invariants)

Reference

API docs, syntax guides, tool documentation (office docs)

Directory structure

skills/
  skill-name/
    SKILL.md              # 主参考文档(必需)
    supporting-file.*     # 仅在需要时

Flat namespace - all skills in one searchable namespace

Cases for separate files:

  1. Large amounts of reference content(100+ lines) - API docs, comprehensive syntax explanations
  2. Reusable tools - scripts, utilities, templates

Keep inline:

  • Principles and concepts
  • Code patterns (< 50 lines)
  • Everything else

SKILL.md structure

Frontmatter(YAML):

  • Two required fields:name and description(for the full set of supported fields, see agentskills.io/specification)
  • 1024 characters maximum in 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 concrete symptoms, scenarios, and contexts
    • Never summarize the skill's process or workflow(see the SDO section for why)
    • Try to keep it within 500 characters
---
name: Skill-Name-With-Hyphens
description: Use when [具体的触发条件和症状]
---

# 技能名称

## 概述
这是什么?用 1-2 句话说明核心原则。

## 何时使用
[如果决策不明显,使用小型内联流程图]

症状和用例的要点列表
不适用的场景

## 核心模式(技术/模式类)
前后代码对比

## 快速参考
用于快速浏览常见操作的表格或要点

## 实现
简单模式内联代码
大量参考或可复用工具链接到文件

## 常见错误
常见问题 + 修复方法

## 实际效果(可选)
具体结果

Skill Discovery Optimization (SDO)

Discovery is critical: future Claudes need to find your skill

1. Rich description field

Purpose: Claude reads the description to decide which skills to load for the current task. Make it able to 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 describe only trigger conditions. Do not summarize the skill's process or workflow in the description.

Why this matters: Tests show that when a description summarizes the skill's workflow, Claude may follow the description instead of reading the full skill content. A description that says "perform code review between tasks" caused Claude to do only one review, even though the skill's flowchart clearly showed two reviews (first spec compliance, then code quality).

When the description was changed to only "Use when executing an implementation plan containing independent tasks in the current session" (with no workflow summary), Claude correctly read the flowchart and followed the two-phase review process.

Pitfall: A description that summarizes the workflow creates shortcuts that Claude will take. The skill body becomes documentation that Claude skips.

# 错误:总结了工作流 - Claude 可能会跟随描述而非阅读技能
description: Use when executing plans - dispatches subagent per task with code review between tasks

# 错误:流程细节太多
description: Use for TDD - write test first, watch it fail, write minimal code, refactor

# 正确:只有触发条件,无工作流摘要
description: Use when executing implementation plans with independent tasks in the current session

# 正确:仅触发条件
description: Use when implementing any feature or bugfix, before writing implementation code

Content:

  • Use concrete trigger conditions, symptoms, and scenarios to indicate that this skill applies
  • Describe the problem (race conditions, inconsistent behavior) rather than language-specific symptoms (setTimeout, sleep)
  • Keep trigger conditions technology-agnostic unless the skill itself is technology-specific
  • If the skill is technology-specific, state that explicitly in the trigger conditions
  • Write in third person (injected into the system prompt)
  • Never summarize the skill's process or workflow
# 错误:太抽象、模糊,未包含何时使用
description: For async testing

# 错误:第一人称
description: I can help you with async tests when they're flaky

# 错误:提到了技术但技能并非该技术特定的
description: Use when tests use setTimeout/sleep and are flaky

# 正确:以"Use when"开头,描述问题,无工作流
description: Use when tests have race conditions, timing dependencies, or pass/fail inconsistently

# 正确:技术特定的技能带有明确的触发条件
description: Use when using React Router and handling authentication redirects

2. Keyword coverage

Use words that Claude will 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, verb-first:

  • ✅ creating-skills instead of skill-creation
  • ✅ condition-based-waiting instead of async-test-helpers

4. Token efficiency (critical)

Problem: getting-started and frequently referenced skills are loaded into every conversation. Every token matters.

Target word counts:

  • getting-started workflow: <150 words each
  • Frequently loaded skills: <200 words total
  • Other skills: <500 words (still be concise)

Techniques:

Move details into tool help:

# 错误:在 SKILL.md 中列出所有参数
search-conversations supports --text, --both, --after DATE, --before DATE, --limit N

# 正确:引用 --help
search-conversations 支持多种模式和过滤器。运行 --help 查看详情。

Use cross-references:

# 错误:重复工作流细节
搜索时,用模板分派子智能体……
[20 行重复的说明]

# 正确:引用其他技能
始终使用子智能体(节省 50-100 倍上下文)。必需:使用 [other-skill-name] 工作流。

Condense examples:

# 错误:冗长的示例(42 词)
你的搭档:"我们之前是怎么处理 React Router 中的认证错误的?"
你:我来搜索过去对话中的 React Router 认证模式。
[用搜索查询分派子智能体:"React Router authentication error handling 401"]

# 正确:精简的示例(20 词)
搭档:"我们之前是怎么处理 React Router 中的认证错误的?"
你:正在搜索……
[分派子智能体 → 整合]

Eliminate redundancy:

  • Don't repeat content already in cross-referenced skills
  • Don't explain things that are obvious from the command
  • Don't provide multiple examples for the same pattern

Validation:

wc -w skills/path/SKILL.md
# getting-started 工作流:目标 <150 每个
# 其他频繁加载的:目标总计 <200

Name it after what you do or the core insight:

  • ✅ condition-based-waiting > async-test-helpers
  • ✅ using-skills instead of skill-usage
  • ✅ flatten-with-flags > data-structure-refactoring
  • ✅ root-cause-tracing > debugging-techniques

Gerunds (-ing) suit describing processes:

  • creating-skills、testing-skills、debugging-with-logs
  • Active, describing the operation you are performing

5. Cross-reference other skills

When writing documentation that references other skills:

Use only the skill name, with clear required markers:

  • ✅ Good:**必需子技能:** 使用 test-driven-development
  • ✅ Good:**必需背景:** 你必须理解 systematic-debugging
  • ❌ Bad:参见 skills/testing/test-driven-development(unclear whether required)
  • ❌ Bad:@skills/testing/test-driven-development/SKILL.md(forced loading, wastes context)

Why not use @ links: @ syntax immediately forces the file to load, consuming 200k+ of context before you need it.

Flowchart usage

digraph when_flowchart {
    "需要展示信息?" [shape=diamond];
    "我可能在决策中犯错?" [shape=diamond];
    "使用 markdown" [shape=box];
    "小型内联流程图" [shape=box];

    "需要展示信息?" -> "我可能在决策中犯错?" [label="是"];
    "我可能在决策中犯错?" -> "小型内联流程图" [label="是"];
    "我可能在决策中犯错?" -> "使用 markdown" [label="否"];
}

Use flowcharts only for:

  • Non-obvious decision points
  • Process loops where you might stop too early
  • "When to use A vs B" decisions

Never use flowcharts for:

  • Reference material → tables, lists
  • Code examples → Markdown code blocks
  • Linear instructions → numbered lists
  • Labels without semantic meaning (step1, helper2)

See @graphviz-conventions.dot for graphviz style rules.

Visualize for your partner: Use the render-graphs.js in this directory to render the skill's flowcharts as SVG:

node ./render-graphs.js ../some-skill           # 每个图表分别渲染
node ./render-graphs.js ../some-skill --combine # 所有图表合并为一个 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
  • Directly adaptable (not a generic template)

Do not:

  • Implement in 5 or more languages
  • Create fill-in-the-blank templates
  • Write artificially constructed examples

You are good at language porting—one excellent example is enough.

File organization

Self-contained skill

defense-in-depth/
  SKILL.md    # 所有内容内联

Applicable scenarios: everything fits without needing extensive references

Skill with reusable tools

condition-based-waiting/
  SKILL.md    # 概述 + 模式
  example.ts  # 可适配的工作代码

Applicable scenarios: the tool is reusable code, not just narration

Skill with extensive references

pptx/
  SKILL.md       # 概述 + 工作流
  pptxgenjs.md   # 600 行 API 参考
  ooxml.md       # 500 行 XML 结构
  scripts/       # 可执行工具

Applicable scenarios: reference material is too extensive to inline

When calling a script bundled with the skill in the main text, invoke it through an interpreter (bash scripts/tool.sh、node scripts/tool.js), never with a bare path: some runtime plugin packagers strip the executable bit, and writing scripts/tool.sh bare there will fail with Permission denied .

Iron rule (same as TDD)

没有失败的测试就不写技能

This applies to new skills and edits to existing skills.

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

No exceptions:

  • Does not apply to "simple additions"
  • Does not apply to "just adding a section"
  • Does not apply to "documentation updates"
  • Do not keep untested changes as a "reference"
  • Do not "tweak" while running tests
  • Deleting means deleting

Required background: The test-driven-development skill explains why this matters. The same principles apply to documentation.

Test all skill types

Different types of skills require different testing methods:

Discipline-enforcing skills (rules/requirements)

For example: TDD, verification before completion, design before coding

Testing method:

  • Academic questions: do they understand the rules?
  • Stress scenarios: do they comply under pressure?
  • Combinations of multiple pressures: time + sunk cost + exhaustion
  • Identify rationalization excuses and add explicit rebuttals

Success criteria: The agent follows the rules under maximum pressure

Technical skills (how-to guides)

For example: condition-based-waiting、root-cause-tracing、defensive-programming

Testing method:

  • Application scenarios: can they apply the technique correctly?
  • Variant scenarios: can they handle edge cases?
  • Missing information test: are there any omissions in the instructions?

Success criteria: The agent successfully applies the technique to new scenarios

Pattern-type skills (mental models)

For example: reducing-complexity, information-hiding concepts

Testing method:

  • 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 correctly identifies when/how to apply the pattern

Reference-type skills (documentation/API)

For example: API documentation, command references, library guides

Testing method:

  • Retrieval scenario: can they find the right information?
  • Application scenario: can they correctly use what they found?
  • Coverage testing: are the common use cases all covered?

Success criteria: The agent finds and correctly applies the reference information

Common rationalizations for skipping tests

Excuse Reality
"The skill is obviously clear" Clear to you ≠ clear to other agents. Test it.
"This is just reference material" Reference material may have omissions or unclear parts. Test retrieval.
"Testing is overkill" Untested skills always have problems. 15 minutes of testing saves hours.
"Test it if there's a problem" A problem = the agent can't use the skill. Test before deployment.
"Testing is too tedious" Testing is far less tedious than debugging a bad skill in production.
"I'm confident it's good" Overconfidence guarantees problems. Test it anyway.
"Academic review is enough" Reading ≠ using. Test the application scenarios.
"No time to test" Deploying an untested skill wastes more time than fixing it later.

All of the above means: test before deployment. No exceptions.

Match the form to the failure type

Before writing the guidance content, first give the baseline failureCategorize. A form that makes one category of failure airtight will, when used on another category,measurably backfire。

Baseline failure Correct form Wrong form
Skipping/violating rules under pressure (knowingly) Prohibition + rationalization excuse table + red lines (see "Make the skill withstand rationalization" below) Soft suggestions ("prefer...", "consider...")
Complied, but the outputshapeis wrong (bloated prompt, buried conclusion, restating the spec) Positive recipe or contract: state directly what the outputis — what parts it consists of and in what order Prohibition list ("don't restate", "never narrate")
In what theywould have produced anywaythey omitted a required element Structural means: put a REQUIRED field or placeholder slot in the template they need to fill in Write prose reminders near the template
Behaviorshould depend on some condition Conditional sentences attached to observable predicates ("if the brief exists, cite it") Unconditional rules + a pile of exception clauses

Why prohibitions backfire on "shaping" problems: When there are competing incentives (such as "make the prompt self-contained"), the agent willbargain with "don't do X". In same-question wording comparison tests for dispatch prompt guidance, the prohibition group produced noticeably more unwanted contentMore thanformulation groups (two groups of distributions completely separated), even worse than the "no guidance at all" control group — please do micro-tests on your own scenarios, don't take it for granted, butnever treat prohibitions as the default choice. Formulations leave no room for bargaining: the output either matches the stated shape or it doesn't.

Rules that apply no matter which form you choose:

  • Don't add "as appropriate" clauses. "Don't do X unless it's important" reopens negotiation — in the same batch of wording tests, appendingone"as appropriate" clause to a winning formulation degraded it from stable to erratic. Genuine exceptions should be expressed asits ownconditional clause, attached to an observable predicate.
  • Exemption clauses do not scope-limit. "This length limit doesn't apply to code blocks" will still suppress code blocks. If part of the output must be exempt, thenrestructure so the rule can't reach it, rather than writing an exemption.

Make skills withstand rationalization

Skills that enforce discipline (like TDD) need to resist rationalization. Agents are smart and will find loopholes under pressure.

Psychology note: Understanding why persuasion techniques work helps you apply them systematically. See persuasion-principles.md for the research basis (Cialdini, 2021; Meincke et al., 2025), covering authority, commitment, scarcity, social proof, and belonging principles.

Explicitly plug every loophole

Don't just state the rule—prohibit the specific workarounds:

No exceptions:

  • Don't keep it as a "reference"
  • Don't "adjust" it while writing tests
  • Don't look at it
  • Deleting means deleting
</Good>

### 应对"精神 vs 字面"的辩论

在前面加入基础原则:

```markdown
**违反规则的字面意思就是违反规则的精神。**

This cuts off the entire class of "I was following the spirit" rationalization excuses.

Build a rationalization excuse table

Capture rationalization excuses from baseline tests (see the testing section below). Every excuse agents use goes into the table:

| 借口 | 现实 |
|------|------|
| "太简单不值得测试" | 简单的代码也会出错。测试只需 30 秒。 |
| "我后面再测试" | 测试立即通过什么也证明不了。 |
| "后写测试效果一样" | 后写测试 = "这做了什么?" 先写测试 = "这应该做什么?" |

Create a red-line list

Make it easy for agents to self-check whether they are rationalizing:

## 红线 - 停下来重新开始

- 先写代码再写测试
- "我已经手动测试过了"
- "后写测试效果一样"
- "重要的是精神不是仪式"
- "这个情况不同,因为……"

**以上所有都意味着:删除代码。用 TDD 重新开始。**

Update the SDO to include violation symptoms

Add to the description: symptoms of 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)

Run the stress scenario without the skill. Record behavior verbatim:

  • What choices did they make?
  • What rationalization excuses did they use (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 targeting those specific rationalization excuses. Don't add extra content for hypothetical situations.

Run the same scenario with the skill. The agent should now comply.

Refactor: plug the loopholes

Did the agent find new rationalization excuses? Add explicit rebuttals. Re-test until airtight.

Do wording micro-tests first, then run the full scenario

The complete stress scenario is the final checkpoint, but it is slow and expensive on every iteration. First usemicro-teststo validate the wording itself:

  1. One fresh-context sample per call — a bare API call, or a single-shot subagent when there is no API access. Put in the system promptthe real context in which this guidance will actually exist(the complete skill or prompt template, not the guidance pulled out on its own); put in the user message a task that willtrigger that failure.
  2. Always include a "no guidance" control group. If the control group does not exhibit that failure at all, then there is nothing to fix — stop, do not write this guidance.
  3. At least 5 repetitions per variant. A single sample will lie.
  4. Every flagged hit must be read manually. Programmatic scoring is fine, but template echoes and cited counterexamples willmasquerade as hits; looking only at automatic counts will both overestimate failures and overestimate successes.
  5. Variance itself is a metric. When the guidance truly takes effect, multiple repetitions converge to the same shape. 5 repetitions producing 5 different interpretations means this wordinghas no binding force — tighten the form first, don't rush to add words.

Micro-tests validatewording; for discipline-enforcement skills, theycannot replacestress scenarios.

Testing methodology: See @testing-skills-with-subagents.md for the complete testing methodology:

  • How to write stress scenarios
  • Stress types (time, sunk cost, authority, exhaustion)
  • Systematically plugging loopholes
  • 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 flowcharts

step1 [label="import fs"];
step2 [label="read file"];

Why it's bad: Cannot copy-paste, hard to read

Generic labels

helper1、helper2、step3、pattern4 Why it's bad: Labels should have semantic meaning

Stop: before moving to the next skill

After writing any skill, you must stop and complete the deployment process.

Do not:

  • Batch-create multiple skills without testing them one by one
  • Move to the next one before the current skill is validated
  • Skip testing because "batching is more efficient"

The deployment checklist below is mandatory for every skill.

Deploying an untested skill = deploying untested code. This is a violation of quality standards.

Skill creation checklist (TDD adapted)

Important: Use TodoWrite to create a todo for each checklist item below.

Red phase - write a failing test:

  • Create a stress scenario (discipline-type skills require 3 or more combined stresses)
  • Run the scenario without the skill - verbatim record baseline behavior
  • Identify patterns in rationalization excuses

Green phase - Write the minimal skill:

  • Name uses only letters, numbers, hyphens (no parentheses/special characters)
  • YAML frontmatter contains the required name and description fields (max 1024 characters; see spec)
  • Description starts with "Use when..." and contains specific trigger conditions/symptoms
  • Description uses third person
  • Full text contains search keywords (errors, symptoms, tools)
  • Clear overview with core principles
  • Addresses the specific baseline failures identified in the red phase
  • Code inline or linked to a separate file
  • One excellent example (not multilingual)
  • Run the scenario with the skill - verify the agent now complies

Refactor phase - Close the loopholes:

  • Identify new rationalization excuses from testing
  • Add explicit rebuttals (discipline-type skills)
  • Build a rationalization excuse table from all test iterations
  • Create a red-line list
  • Retest until airtight

Quality check:

  • Use a small flowchart only when the decision is not obvious
  • Quick reference table
  • Common mistakes section
  • No narrative stories
  • Supporting files only for tools or extensive references

Deploy:

  • Commit the skill to git and push to your fork (if configured)
  • Consider contributing back via a PR (if broadly useful)

Discovery workflow

How a future Claude finds your skill:

  1. Encounters a problem("tests are flaky")
  2. Finds the skill(description match)
  3. Skims the overview(is this relevant?)
  4. Reads the patterns(quick reference table)
  5. Loads the examples(only when implementing)

Optimize for this flow - put searchable terms up front and everywhere.