
Writing Skills
- 676 installs
- 44k repo stars
- Updated July 27, 2026
- sickn33/antigravity-awesome-skills
writing-skills is an agent skill that teaches developers to author concise, discoverable Claude Agent Skills with practical structure and real-usage testing guidance.
About
writing-skills is an agent skill from sickn33/antigravity-awesome-skills that documents skill authoring best practices for Claude agent Skills. The guide emphasizes concision because Skills share the context window with system prompts and conversation history, and it covers practical authoring decisions so Claude can discover and invoke Skills reliably during real tasks. Developers reach for writing-skills when creating new SKILL.md files, refining skill descriptions and triggers, or testing whether an agent loads custom skills successfully before publishing to a team catalog.
- Concise-is-key principle that minimizes context-window usage
- Default assumption that Claude is already very smart
- Practical authoring decisions for discoverability and real usage
- Metadata-first loading strategy that only reads SKILL.md when relevant
- Token-cost challenge framework for every piece of added context
Writing Skills by the numbers
- 676 all-time installs (skills.sh)
- +1 installs in the week ending Jul 27, 2026 (Skillselion tracking)
- Ranked #85 of 826 Skill Development skills by installs in the Skillselion catalog
- Security screen: LOW risk (skills.sh audit)
- Data as of Jul 28, 2026 (Skillselion catalog sync)
npx skills add https://github.com/sickn33/antigravity-awesome-skills --skill writing-skillsAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 676 |
|---|---|
| repo stars | ★ 44k |
| Security audit | 3 / 3 scanners passed |
| Last updated | July 27, 2026 |
| Repository | sickn33/antigravity-awesome-skills ↗ |
How do you write effective Claude Agent Skills?
Create concise, discoverable, and effective Skills that Claude loads and uses reliably.
Who is it for?
Developers creating or maintaining custom Claude/Cursor agent Skills who need discoverable, context-efficient SKILL.md authoring guidance.
Skip if: Teams building application features or production APIs without authoring reusable agent instruction bundles.
When should I use this skill?
User asks to create a new skill, improve SKILL.md discoverability, or follow agent skill authoring best practices for Claude.
What you get
Structured SKILL.md file, tested skill triggers, and concise agent instructions optimized for discovery.
- SKILL.md skill definition
- Tested skill trigger phrases
Files
Writing Skills (Excellence)
Dispatcher for skill creation excellence. Use the decision tree below to find the right template and standards.
⚡ Quick Decision Tree
What do you need to do?
1. Create a NEW skill:
- Is it simple (single file, <200 lines)? → Tier 1 Architecture
- Is it complex (multi-concept, 200-1000 lines)? → Tier 2 Architecture
- Is it a massive platform (10+ products, AWS, Convex)? → Tier 3 Architecture
2. Improve an EXISTING skill:
- Fix "it's too long" -> Modularize (Tier 3)
- Fix "AI ignores rules" -> Anti-Rationalization
- Fix "users can't find it" -> CSO (Search Optimization)
3. Verify Compliance:
- Check metadata/naming -> Standards
- Add tests -> Testing Guide
📚 Component Index
| Component | Purpose |
|---|---|
| [CSO](references/cso/README.md) | "SEO for LLMs". How to write descriptions that trigger. |
| [Standards](references/standards/README.md) | File naming, YAML frontmatter, directory structure. |
| [Anti-Rationalization](references/anti-rationalization/README.md) | How to write rules that agents won't ignore. |
| [Testing](references/testing/README.md) | How to ensure your skill actually works. |
🛠️ Templates
- Technique Skill (How-to)
- Reference Skill (Docs)
- Discipline Skill (Rules)
- Pattern Skill (Design Patterns)
When to Use
- Creating a NEW skill from scratch
- Improving an EXISTING skill that agents ignore
- Debugging why a skill isn't being triggered
- Standardizing skills across a team
How It Works
1. Identify goal → Use decision tree above 2. Select template → From references/templates/ 3. Apply CSO → Optimize description for discovery 4. Add anti-rationalization → For discipline skills 5. Test → RED-GREEN-REFACTOR cycle
Quick Example
---
name: my-technique
description: Use when [specific symptom occurs].
metadata:
category: technique
triggers: error-text, symptom, tool-name
---
# My Technique
## When to Use
- [Symptom A]
- [Error message]Common Mistakes
| Mistake | Fix |
|---|---|
| Description summarizes workflow | Use "Use when..." triggers only |
No metadata.triggers | Add 3+ keywords |
| Generic name ("helper") | Use gerund (creating-skills) |
| Long monolithic SKILL.md | Split into references/ |
See gotchas.md for more.
✅ Pre-Deploy Checklist
Before deploying any skill:
- [ ]
namefield matches directory name exactly - [ ]
SKILL.mdfilename is ALL CAPS - [ ] Description starts with "Use when..."
- [ ]
metadata.triggershas 3+ keywords - [ ] Total lines < 500 (use
references/for more) - [ ] No
@force-loading in cross-references - [ ] Tested with real scenarios
🔗 Related Skills
- opencode-expert: For OpenCode environment configuration
- Use
/write-skillcommand for guided skill creation
Examples
Create a Tier 1 skill:
mkdir -p ~/.config/opencode/skills/my-technique
touch ~/.config/opencode/skills/my-technique/SKILL.mdCreate a Tier 2 skill:
mkdir -p ~/.config/opencode/skills/my-skill/references/core
touch ~/.config/opencode/skills/my-skill/{SKILL.md,gotchas.md}
touch ~/.config/opencode/skills/my-skill/references/core/README.mdLimitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.
Skill authoring best practices
Learn how to write effective Skills that Claude can discover and use successfully.
Good Skills are concise, well-structured, and tested with real usage. This guide provides practical authoring decisions to help you write Skills that Claude can discover and use effectively.
For conceptual background on how Skills work, see the Skills overview.
Core principles
Concise is key
The context window is a public good. Your Skill shares the context window with everything else Claude needs to know, including:
- The system prompt
- Conversation history
- Other Skills' metadata
- Your actual request
Not every token in your Skill has an immediate cost. At startup, only the metadata (name and description) from all Skills is pre-loaded. Claude reads SKILL.md only when the Skill becomes relevant, and reads additional files only as needed. However, being concise in SKILL.md still matters: once Claude loads it, every token competes with conversation history and other context.
Default assumption: Claude is already very smart
Only add context Claude doesn't already have. Challenge each piece of information:
- "Does Claude really need this explanation?"
- "Can I assume Claude knows this?"
- "Does this paragraph justify its token cost?"
Good example: Concise (approximately 50 tokens):
````markdown theme={null}
Extract PDF text
Use pdfplumber for text extraction:
import pdfplumber
with pdfplumber.open("file.pdf") as pdf:
text = pdf.pages[0].extract_text()````
Bad example: Too verbose (approximately 150 tokens):
```markdown theme={null}
Extract PDF text
PDF (Portable Document Format) files are a common file format that contains text, images, and other content. To extract text from a PDF, you'll need to use a library. There are many libraries available for PDF processing, but we recommend pdfplumber because it's easy to use and handles most cases well. First, you'll need to install it using pip. Then you can use the code below...
The concise version assumes Claude knows what PDFs are and how libraries work.
### Set appropriate degrees of freedom
Match the level of specificity to the task's fragility and variability.
**High freedom** (text-based instructions):
Use when:
* Multiple approaches are valid
* Decisions depend on context
* Heuristics guide the approach
Example:
Code review process
1. Analyze the code structure and organization 2. Check for potential bugs or edge cases 3. Suggest improvements for readability and maintainability 4. Verify adherence to project conventions
**Medium freedom** (pseudocode or scripts with parameters):
Use when:
* A preferred pattern exists
* Some variation is acceptable
* Configuration affects behavior
Example:
Generate report
Use this template and customize as needed:
def generate_report(data, format="markdown", include_charts=True):
# Process data
# Generate output in specified format
# Optionally include visualizations````
Low freedom (specific scripts, few or no parameters):
Use when:
- Operations are fragile and error-prone
- Consistency is critical
- A specific sequence must be followed
Example:
````markdown theme={null}
Database migration
Run exactly this script:
python scripts/migrate.py --verify --backupDo not modify the command or add additional flags. ````
Analogy: Think of Claude as a robot exploring a path:
- Narrow bridge with cliffs on both sides: There's only one safe way forward. Provide specific guardrails and exact instructions (low freedom). Example: database migrations that must run in exact sequence.
- Open field with no hazards: Many paths lead to success. Give general direction and trust Claude to find the best route (high freedom). Example: code reviews where context determines the best approach.
Test with all models you plan to use
Skills act as additions to models, so effectiveness depends on the underlying model. Test your Skill with all the models you plan to use it with.
Testing considerations by model:
- Claude Haiku (fast, economical): Does the Skill provide enough guidance?
- Claude Sonnet (balanced): Is the Skill clear and efficient?
- Claude Opus (powerful reasoning): Does the Skill avoid over-explaining?
What works perfectly for Opus might need more detail for Haiku. If you plan to use your Skill across multiple models, aim for instructions that work well with all of them.
Skill structure
<Note> YAML Frontmatter: The SKILL.md frontmatter supports two fields:
name- Human-readable name of the Skill (64 characters maximum)description- One-line description of what the Skill does and when to use it (1024 characters maximum)
For complete Skill structure details, see the Skills overview. </Note>
Naming conventions
Use consistent naming patterns to make Skills easier to reference and discuss. We recommend using gerund form (verb + -ing) for Skill names, as this clearly describes the activity or capability the Skill provides.
Good naming examples (gerund form):
- "Processing PDFs"
- "Analyzing spreadsheets"
- "Managing databases"
- "Testing code"
- "Writing documentation"
Acceptable alternatives:
- Noun phrases: "PDF Processing", "Spreadsheet Analysis"
- Action-oriented: "Process PDFs", "Analyze Spreadsheets"
Avoid:
- Vague names: "Helper", "Utils", "Tools"
- Overly generic: "Documents", "Data", "Files"
- Inconsistent patterns within your skill collection
Consistent naming makes it easier to:
- Reference Skills in documentation and conversations
- Understand what a Skill does at a glance
- Organize and search through multiple Skills
- Maintain a professional, cohesive skill library
Writing effective descriptions
The description field enables Skill discovery and should include both what the Skill does and when to use it.
<Warning> Always write in third person. The description is injected into the system prompt, and inconsistent point-of-view can cause discovery problems.
- Good: "Processes Excel files and generates reports"
- Avoid: "I can help you process Excel files"
- Avoid: "You can use this to process Excel files"
</Warning>
Be specific and include key terms. Include both what the Skill does and specific triggers/contexts for when to use it.
Each Skill has exactly one description field. The description is critical for skill selection: Claude uses it to choose the right Skill from potentially 100+ available Skills. Your description must provide enough detail for Claude to know when to select this Skill, while the rest of SKILL.md provides the implementation details.
Effective examples:
PDF Processing skill:
```yaml theme={null} description: Extract text and tables from PDF files, fill forms, merge documents. Use when working with PDF files or when the user mentions PDFs, forms, or document extraction.
**Excel Analysis skill:**
description: Analyze Excel spreadsheets, create pivot tables, generate charts. Use when analyzing Excel files, spreadsheets, tabular data, or .xlsx files.
**Git Commit Helper skill:**
description: Generate descriptive commit messages by analyzing git diffs. Use when the user asks for help writing commit messages or reviewing staged changes.
Avoid vague descriptions like these:
description: Helps with documents
description: Processes data
description: Does stuff with files
### Progressive disclosure patterns
SKILL.md serves as an overview that points Claude to detailed materials as needed, like a table of contents in an onboarding guide. For an explanation of how progressive disclosure works, see [How Skills work](/en/docs/agents-and-tools/agent-skills/overview#how-skills-work) in the overview.
**Practical guidance:**
* Keep SKILL.md body under 500 lines for optimal performance
* Split content into separate files when approaching this limit
* Use the patterns below to organize instructions, code, and resources effectively
#### Visual overview: From simple to complex
A basic Skill starts with just a SKILL.md file containing metadata and instructions:
<img src="https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-simple-file.png?fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=87782ff239b297d9a9e8e1b72ed72db9" alt="Simple SKILL.md file showing YAML frontmatter and markdown body" data-og-width="2048" width="2048" data-og-height="1153" height="1153" data-path="images/agent-skills-simple-file.png" data-optimize="true" data-opv="3" srcset="https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-simple-file.png?w=280&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=c61cc33b6f5855809907f7fda94cd80e 280w, https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-simple-file.png?w=560&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=90d2c0c1c76b36e8d485f49e0810dbfd 560w, https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-simple-file.png?w=840&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=ad17d231ac7b0bea7e5b4d58fb4aeabb 840w, https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-simple-file.png?w=1100&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=f5d0a7a3c668435bb0aee9a3a8f8c329 1100w, https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-simple-file.png?w=1650&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=0e927c1af9de5799cfe557d12249f6e6 1650w, https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-simple-file.png?w=2500&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=46bbb1a51dd4c8202a470ac8c80a893d 2500w" />
As your Skill grows, you can bundle additional content that Claude loads only when needed:
<img src="https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-bundling-content.png?fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=a5e0aa41e3d53985a7e3e43668a33ea3" alt="Bundling additional reference files like reference.md and forms.md." data-og-width="2048" width="2048" data-og-height="1327" height="1327" data-path="images/agent-skills-bundling-content.png" data-optimize="true" data-opv="3" srcset="https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-bundling-content.png?w=280&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=f8a0e73783e99b4a643d79eac86b70a2 280w, https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-bundling-content.png?w=560&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=dc510a2a9d3f14359416b706f067904a 560w, https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-bundling-content.png?w=840&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=82cd6286c966303f7dd914c28170e385 840w, https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-bundling-content.png?w=1100&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=56f3be36c77e4fe4b523df209a6824c6 1100w, https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-bundling-content.png?w=1650&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=d22b5161b2075656417d56f41a74f3dd 1650w, https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-bundling-content.png?w=2500&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=3dd4bdd6850ffcc96c6c45fcb0acd6eb 2500w" />
The complete Skill directory structure might look like this:
pdf/ ├── SKILL.md # Main instructions (loaded when triggered) ├── FORMS.md # Form-filling guide (loaded as needed) ├── reference.md # API reference (loaded as needed) ├── examples.md # Usage examples (loaded as needed) └── scripts/ ├── analyze_form.py # Utility script (executed, not loaded) ├── fill_form.py # Form filling script └── validate.py # Validation script
#### Pattern 1: High-level guide with references
--- name: PDF Processing description: Extracts text and tables from PDF files, fills forms, and merges documents. Use when working with PDF files or when the user mentions PDFs, forms, or document extraction. ---
PDF Processing
Quick start
Extract text with pdfplumber:
import pdfplumber
with pdfplumber.open("file.pdf") as pdf:
text = pdf.pages[0].extract_text()Advanced features
Form filling: See FORMS.md for complete guide API reference: See REFERENCE.md for all methods Examples: See EXAMPLES.md for common patterns ````
Claude loads FORMS.md, REFERENCE.md, or EXAMPLES.md only when needed.
Pattern 2: Domain-specific organization
For Skills with multiple domains, organize content by domain to avoid loading irrelevant context. When a user asks about sales metrics, Claude only needs to read sales-related schemas, not finance or marketing data. This keeps token usage low and context focused.
bigquery-skill/
├── SKILL.md (overview and navigation)
└── reference/
├── finance.md (revenue, billing metrics)
├── sales.md (opportunities, pipeline)
├── product.md (API usage, features)
└── marketing.md (campaigns, attribution)````markdown SKILL.md theme={null}
BigQuery Data Analysis
Available datasets
Finance: Revenue, ARR, billing → See reference/finance.md Sales: Opportunities, pipeline, accounts → See reference/sales.md Product: API usage, features, adoption → See reference/product.md Marketing: Campaigns, attribution, email → See reference/marketing.md
Quick search
Find specific metrics using grep:
grep -i "revenue" reference/finance.md
grep -i "pipeline" reference/sales.md
grep -i "api usage" reference/product.md````
Pattern 3: Conditional details
Show basic content, link to advanced content:
```markdown theme={null}
DOCX Processing
Creating documents
Use docx-js for new documents. See DOCX-JS.md.
Editing documents
For simple edits, modify the XML directly.
For tracked changes: See REDLINING.md For OOXML details: See OOXML.md
Claude reads REDLINING.md or OOXML.md only when the user needs those features.
### Avoid deeply nested references
Claude may partially read files when they're referenced from other referenced files. When encountering nested references, Claude might use commands like `head -100` to preview content rather than reading entire files, resulting in incomplete information.
**Keep references one level deep from SKILL.md**. All reference files should link directly from SKILL.md to ensure Claude reads complete files when needed.
**Bad example: Too deep**:
SKILL.md
See advanced.md...
advanced.md
See details.md...
details.md
Here's the actual information...
**Good example: One level deep**:
SKILL.md
Basic usage: [instructions in SKILL.md] Advanced features: See advanced.md API reference: See reference.md Examples: See examples.md
### Structure longer reference files with table of contents
For reference files longer than 100 lines, include a table of contents at the top. This ensures Claude can see the full scope of available information even when previewing with partial reads.
**Example**:
API Reference
Contents
- Authentication and setup
- Core methods (create, read, update, delete)
- Advanced features (batch operations, webhooks)
- Error handling patterns
- Code examples
Authentication and setup
...
Core methods
...
Claude can then read the complete file or jump to specific sections as needed.
For details on how this filesystem-based architecture enables progressive disclosure, see the [Runtime environment](#runtime-environment) section in the Advanced section below.
## Workflows and feedback loops
### Use workflows for complex tasks
Break complex operations into clear, sequential steps. For particularly complex workflows, provide a checklist that Claude can copy into its response and check off as it progresses.
**Example 1: Research synthesis workflow** (for Skills without code):
Research synthesis workflow
Copy this checklist and track your progress:
Research Progress:
- [ ] Step 1: Read all source documents
- [ ] Step 2: Identify key themes
- [ ] Step 3: Cross-reference claims
- [ ] Step 4: Create structured summary
- [ ] Step 5: Verify citationsStep 1: Read all source documents
Review each document in the sources/ directory. Note the main arguments and supporting evidence.
Step 2: Identify key themes
Look for patterns across sources. What themes appear repeatedly? Where do sources agree or disagree?
Step 3: Cross-reference claims
For each major claim, verify it appears in the source material. Note which source supports each point.
Step 4: Create structured summary
Organize findings by theme. Include:
- Main claim
- Supporting evidence from sources
- Conflicting viewpoints (if any)
Step 5: Verify citations
Check that every claim references the correct source document. If citations are incomplete, return to Step 3. ````
This example shows how workflows apply to analysis tasks that don't require code. The checklist pattern works for any complex, multi-step process.
Example 2: PDF form filling workflow (for Skills with code):
````markdown theme={null}
PDF form filling workflow
Copy this checklist and check off items as you complete them:
Task Progress:
- [ ] Step 1: Analyze the form (run analyze_form.py)
- [ ] Step 2: Create field mapping (edit fields.json)
- [ ] Step 3: Validate mapping (run validate_fields.py)
- [ ] Step 4: Fill the form (run fill_form.py)
- [ ] Step 5: Verify output (run verify_output.py)Step 1: Analyze the form
Run: python scripts/analyze_form.py input.pdf
This extracts form fields and their locations, saving to fields.json.
Step 2: Create field mapping
Edit fields.json to add values for each field.
Step 3: Validate mapping
Run: python scripts/validate_fields.py fields.json
Fix any validation errors before continuing.
Step 4: Fill the form
Run: python scripts/fill_form.py input.pdf fields.json output.pdf
Step 5: Verify output
Run: python scripts/verify_output.py output.pdf
If verification fails, return to Step 2. ````
Clear steps prevent Claude from skipping critical validation. The checklist helps both Claude and you track progress through multi-step workflows.
Implement feedback loops
Common pattern: Run validator → fix errors → repeat
This pattern greatly improves output quality.
Example 1: Style guide compliance (for Skills without code):
```markdown theme={null}
Content review process
1. Draft your content following the guidelines in STYLE_GUIDE.md 2. Review against the checklist:
- Check terminology consistency
- Verify examples follow the standard format
- Confirm all required sections are present
3. If issues found:
- Note each issue with specific section reference
- Revise the content
- Review the checklist again
4. Only proceed when all requirements are met 5. Finalize and save the document
This shows the validation loop pattern using reference documents instead of scripts. The "validator" is STYLE\_GUIDE.md, and Claude performs the check by reading and comparing.
**Example 2: Document editing process** (for Skills with code):
Document editing process
1. Make your edits to word/document.xml 2. Validate immediately: python ooxml/scripts/validate.py unpacked_dir/ 3. If validation fails:
- Review the error message carefully
- Fix the issues in the XML
- Run validation again
4. Only proceed when validation passes 5. Rebuild: python ooxml/scripts/pack.py unpacked_dir/ output.docx 6. Test the output document
The validation loop catches errors early.
## Content guidelines
### Avoid time-sensitive information
Don't include information that will become outdated:
**Bad example: Time-sensitive** (will become wrong):
If you're doing this before August 2025, use the old API. After August 2025, use the new API.
**Good example** (use "old patterns" section):
Current method
Use the v2 API endpoint: api.example.com/v2/messages
Old patterns
<details> <summary>Legacy v1 API (deprecated 2025-08)</summary>
The v1 API used: api.example.com/v1/messages
This endpoint is no longer supported. </details>
The old patterns section provides historical context without cluttering the main content.
### Use consistent terminology
Choose one term and use it throughout the Skill:
**Good - Consistent**:
* Always "API endpoint"
* Always "field"
* Always "extract"
**Bad - Inconsistent**:
* Mix "API endpoint", "URL", "API route", "path"
* Mix "field", "box", "element", "control"
* Mix "extract", "pull", "get", "retrieve"
Consistency helps Claude understand and follow instructions.
## Common patterns
### Template pattern
Provide templates for output format. Match the level of strictness to your needs.
**For strict requirements** (like API responses or data formats):
Report structure
ALWAYS use this exact template structure:
# [Analysis Title]
## Executive summary
[One-paragraph overview of key findings]
## Key findings
- Finding 1 with supporting data
- Finding 2 with supporting data
- Finding 3 with supporting data
## Recommendations
1. Specific actionable recommendation
2. Specific actionable recommendation````
For flexible guidance (when adaptation is useful):
````markdown theme={null}
Report structure
Here is a sensible default format, but use your best judgment based on the analysis:
# [Analysis Title]
## Executive summary
[Overview]
## Key findings
[Adapt sections based on what you discover]
## Recommendations
[Tailor to the specific context]Adjust sections as needed for the specific analysis type. ````
Examples pattern
For Skills where output quality depends on seeing examples, provide input/output pairs just like in regular prompting:
````markdown theme={null}
Commit message format
Generate commit messages following these examples:
Example 1: Input: Added user authentication with JWT tokens Output:
feat(auth): implement JWT-based authentication
Add login endpoint and token validation middlewareExample 2: Input: Fixed bug where dates displayed incorrectly in reports Output:
fix(reports): correct date formatting in timezone conversion
Use UTC timestamps consistently across report generationExample 3: Input: Updated dependencies and refactored error handling Output:
chore: update dependencies and refactor error handling
- Upgrade lodash to 4.17.21
- Standardize error response format across endpointsFollow this style: type(scope): brief description, then detailed explanation. ````
Examples help Claude understand the desired style and level of detail more clearly than descriptions alone.
Conditional workflow pattern
Guide Claude through decision points:
```markdown theme={null}
Document modification workflow
1. Determine the modification type:
Creating new content? → Follow "Creation workflow" below Editing existing content? → Follow "Editing workflow" below
2. Creation workflow:
- Use docx-js library
- Build document from scratch
- Export to .docx format
3. Editing workflow:
- Unpack existing document
- Modify XML directly
- Validate after each change
- Repack when complete
<Tip>
If workflows become large or complicated with many steps, consider pushing them into separate files and tell Claude to read the appropriate file based on the task at hand.
</Tip>
## Evaluation and iteration
### Build evaluations first
**Create evaluations BEFORE writing extensive documentation.** This ensures your Skill solves real problems rather than documenting imagined ones.
**Evaluation-driven development:**
1. **Identify gaps**: Run Claude on representative tasks without a Skill. Document specific failures or missing context
2. **Create evaluations**: Build three scenarios that test these gaps
3. **Establish baseline**: Measure Claude's performance without the Skill
4. **Write minimal instructions**: Create just enough content to address the gaps and pass evaluations
5. **Iterate**: Execute evaluations, compare against baseline, and refine
This approach ensures you're solving actual problems rather than anticipating requirements that may never materialize.
**Evaluation structure**:
{ "skills": ["pdf-processing"], "query": "Extract all text from this PDF file and save it to output.txt", "files": ["test-files/document.pdf"], "expected_behavior": [ "Successfully reads the PDF file using an appropriate PDF processing library or command-line tool", "Extracts text content from all pages in the document without missing any pages", "Saves the extracted text to a file named output.txt in a clear, readable format" ] }
<Note>
This example demonstrates a data-driven evaluation with a simple testing rubric. We do not currently provide a built-in way to run these evaluations. Users can create their own evaluation system. Evaluations are your source of truth for measuring Skill effectiveness.
</Note>
### Develop Skills iteratively with Claude
The most effective Skill development process involves Claude itself. Work with one instance of Claude ("Claude A") to create a Skill that will be used by other instances ("Claude B"). Claude A helps you design and refine instructions, while Claude B tests them in real tasks. This works because Claude models understand both how to write effective agent instructions and what information agents need.
**Creating a new Skill:**
1. **Complete a task without a Skill**: Work through a problem with Claude A using normal prompting. As you work, you'll naturally provide context, explain preferences, and share procedural knowledge. Notice what information you repeatedly provide.
2. **Identify the reusable pattern**: After completing the task, identify what context you provided that would be useful for similar future tasks.
**Example**: If you worked through a BigQuery analysis, you might have provided table names, field definitions, filtering rules (like "always exclude test accounts"), and common query patterns.
3. **Ask Claude A to create a Skill**: "Create a Skill that captures this BigQuery analysis pattern we just used. Include the table schemas, naming conventions, and the rule about filtering test accounts."
<Tip>
Claude models understand the Skill format and structure natively. You don't need special system prompts or a "writing skills" skill to get Claude to help create Skills. Simply ask Claude to create a Skill and it will generate properly structured SKILL.md content with appropriate frontmatter and body content.
</Tip>
4. **Review for conciseness**: Check that Claude A hasn't added unnecessary explanations. Ask: "Remove the explanation about what win rate means - Claude already knows that."
5. **Improve information architecture**: Ask Claude A to organize the content more effectively. For example: "Organize this so the table schema is in a separate reference file. We might add more tables later."
6. **Test on similar tasks**: Use the Skill with Claude B (a fresh instance with the Skill loaded) on related use cases. Observe whether Claude B finds the right information, applies rules correctly, and handles the task successfully.
7. **Iterate based on observation**: If Claude B struggles or misses something, return to Claude A with specifics: "When Claude used this Skill, it forgot to filter by date for Q4. Should we add a section about date filtering patterns?"
**Iterating on existing Skills:**
The same hierarchical pattern continues when improving Skills. You alternate between:
* **Working with Claude A** (the expert who helps refine the Skill)
* **Testing with Claude B** (the agent using the Skill to perform real work)
* **Observing Claude B's behavior** and bringing insights back to Claude A
1. **Use the Skill in real workflows**: Give Claude B (with the Skill loaded) actual tasks, not test scenarios
2. **Observe Claude B's behavior**: Note where it struggles, succeeds, or makes unexpected choices
**Example observation**: "When I asked Claude B for a regional sales report, it wrote the query but forgot to filter out test accounts, even though the Skill mentions this rule."
3. **Return to Claude A for improvements**: Share the current SKILL.md and describe what you observed. Ask: "I noticed Claude B forgot to filter test accounts when I asked for a regional report. The Skill mentions filtering, but maybe it's not prominent enough?"
4. **Review Claude A's suggestions**: Claude A might suggest reorganizing to make rules more prominent, using stronger language like "MUST filter" instead of "always filter", or restructuring the workflow section.
5. **Apply and test changes**: Update the Skill with Claude A's refinements, then test again with Claude B on similar requests
6. **Repeat based on usage**: Continue this observe-refine-test cycle as you encounter new scenarios. Each iteration improves the Skill based on real agent behavior, not assumptions.
**Gathering team feedback:**
1. Share Skills with teammates and observe their usage
2. Ask: Does the Skill activate when expected? Are instructions clear? What's missing?
3. Incorporate feedback to address blind spots in your own usage patterns
**Why this approach works**: Claude A understands agent needs, you provide domain expertise, Claude B reveals gaps through real usage, and iterative refinement improves Skills based on observed behavior rather than assumptions.
### Observe how Claude navigates Skills
As you iterate on Skills, pay attention to how Claude actually uses them in practice. Watch for:
* **Unexpected exploration paths**: Does Claude read files in an order you didn't anticipate? This might indicate your structure isn't as intuitive as you thought
* **Missed connections**: Does Claude fail to follow references to important files? Your links might need to be more explicit or prominent
* **Overreliance on certain sections**: If Claude repeatedly reads the same file, consider whether that content should be in the main SKILL.md instead
* **Ignored content**: If Claude never accesses a bundled file, it might be unnecessary or poorly signaled in the main instructions
Iterate based on these observations rather than assumptions. The 'name' and 'description' in your Skill's metadata are particularly critical. Claude uses these when deciding whether to trigger the Skill in response to the current task. Make sure they clearly describe what the Skill does and when it should be used.
## Anti-patterns to avoid
### Avoid Windows-style paths
Always use forward slashes in file paths, even on Windows:
* ✓ **Good**: `scripts/helper.py`, `reference/guide.md`
* ✗ **Avoid**: `scripts\helper.py`, `reference\guide.md`
Unix-style paths work across all platforms, while Windows-style paths cause errors on Unix systems.
### Avoid offering too many options
Don't present multiple approaches unless necessary:
Bad example: Too many choices (confusing): "You can use pypdf, or pdfplumber, or PyMuPDF, or pdf2image, or..."
Good example: Provide a default (with escape hatch): "Use pdfplumber for text extraction:
import pdfplumberFor scanned PDFs requiring OCR, use pdf2image with pytesseract instead." ````
Advanced: Skills with executable code
The sections below focus on Skills that include executable scripts. If your Skill uses only markdown instructions, skip to Checklist for effective Skills.
Solve, don't punt
When writing scripts for Skills, handle error conditions rather than punting to Claude.
Good example: Handle errors explicitly:
```python theme={null} def process_file(path): """Process a file, creating it if it doesn't exist.""" try: with open(path) as f: return f.read() except FileNotFoundError:
Create file with default content instead of failing
print(f"File {path} not found, creating default") with open(path, 'w') as f: f.write('') return '' except PermissionError:
Provide alternative instead of failing
print(f"Cannot access {path}, using default") return ''
**Bad example: Punt to Claude**:
def process_file(path):
Just fail and let Claude figure it out
return open(path).read()
Configuration parameters should also be justified and documented to avoid "voodoo constants" (Ousterhout's law). If you don't know the right value, how will Claude determine it?
**Good example: Self-documenting**:
HTTP requests typically complete within 30 seconds
Longer timeout accounts for slow connections
REQUEST_TIMEOUT = 30
Three retries balances reliability vs speed
Most intermittent failures resolve by the second retry
MAX_RETRIES = 3
**Bad example: Magic numbers**:
TIMEOUT = 47 # Why 47? RETRIES = 5 # Why 5?
### Provide utility scripts
Even if Claude could write a script, pre-made scripts offer advantages:
**Benefits of utility scripts**:
* More reliable than generated code
* Save tokens (no need to include code in context)
* Save time (no code generation required)
* Ensure consistency across uses
<img src="https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-executable-scripts.png?fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=4bbc45f2c2e0bee9f2f0d5da669bad00" alt="Bundling executable scripts alongside instruction files" data-og-width="2048" width="2048" data-og-height="1154" height="1154" data-path="images/agent-skills-executable-scripts.png" data-optimize="true" data-opv="3" srcset="https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-executable-scripts.png?w=280&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=9a04e6535a8467bfeea492e517de389f 280w, https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-executable-scripts.png?w=560&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=e49333ad90141af17c0d7651cca7216b 560w, https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-executable-scripts.png?w=840&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=954265a5df52223d6572b6214168c428 840w, https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-executable-scripts.png?w=1100&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=2ff7a2d8f2a83ee8af132b29f10150fd 1100w, https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-executable-scripts.png?w=1650&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=48ab96245e04077f4d15e9170e081cfb 1650w, https://mintcdn.com/anthropic-claude-docs/4Bny2bjzuGBK7o00/images/agent-skills-executable-scripts.png?w=2500&fit=max&auto=format&n=4Bny2bjzuGBK7o00&q=85&s=0301a6c8b3ee879497cc5b5483177c90 2500w" />
The diagram above shows how executable scripts work alongside instruction files. The instruction file (forms.md) references the script, and Claude can execute it without loading its contents into context.
**Important distinction**: Make clear in your instructions whether Claude should:
* **Execute the script** (most common): "Run `analyze_form.py` to extract fields"
* **Read it as reference** (for complex logic): "See `analyze_form.py` for the field extraction algorithm"
For most utility scripts, execution is preferred because it's more reliable and efficient. See the [Runtime environment](#runtime-environment) section below for details on how script execution works.
**Example**:
Utility scripts
analyze_form.py: Extract all form fields from PDF
python scripts/analyze_form.py input.pdf > fields.jsonOutput format:
{
"field_name": {"type": "text", "x": 100, "y": 200},
"signature": {"type": "sig", "x": 150, "y": 500}
}validate_boxes.py: Check for overlapping bounding boxes
python scripts/validate_boxes.py fields.json
# Returns: "OK" or lists conflictsfill_form.py: Apply field values to PDF
python scripts/fill_form.py input.pdf fields.json output.pdf````
Use visual analysis
When inputs can be rendered as images, have Claude analyze them:
````markdown theme={null}
Form layout analysis
1. Convert PDF to images:
python scripts/pdf_to_images.py form.pdf2. Analyze each page image to identify form fields 3. Claude can see field locations and types visually ````
<Note> In this example, you'd need to write the pdf_to_images.py script. </Note>
Claude's vision capabilities help understand layouts and structures.
Create verifiable intermediate outputs
When Claude performs complex, open-ended tasks, it can make mistakes. The "plan-validate-execute" pattern catches errors early by having Claude first create a plan in a structured format, then validate that plan with a script before executing it.
Example: Imagine asking Claude to update 50 form fields in a PDF based on a spreadsheet. Without validation, Claude might reference non-existent fields, create conflicting values, miss required fields, or apply updates incorrectly.
Solution: Use the workflow pattern shown above (PDF form filling), but add an intermediate changes.json file that gets validated before applying changes. The workflow becomes: analyze → create plan file → validate plan → execute → verify.
Why this pattern works:
- Catches errors early: Validation finds problems before changes are applied
- Machine-verifiable: Scripts provide objective verification
- Reversible planning: Claude can iterate on the plan without touching originals
- Clear debugging: Error messages point to specific problems
When to use: Batch operations, destructive changes, complex validation rules, high-stakes operations.
Implementation tip: Make validation scripts verbose with specific error messages like "Field 'signature\_date' not found. Available fields: customer\_name, order\_total, signature\_date\_signed" to help Claude fix issues.
Package dependencies
Skills run in the code execution environment with platform-specific limitations:
- claude.ai: Can install packages from npm and PyPI and pull from GitHub repositories
- Anthropic API: Has no network access and no runtime package installation
List required packages in your SKILL.md and verify they're available in the code execution tool documentation.
Runtime environment
Skills run in a code execution environment with filesystem access, bash commands, and code execution capabilities. For the conceptual explanation of this architecture, see The Skills architecture in the overview.
How this affects your authoring:
How Claude accesses Skills:
1. Metadata pre-loaded: At startup, the name and description from all Skills' YAML frontmatter are loaded into the system prompt 2. Files read on-demand: Claude uses bash Read tools to access SKILL.md and other files from the filesystem when needed 3. Scripts executed efficiently: Utility scripts can be executed via bash without loading their full contents into context. Only the script's output consumes tokens 4. No context penalty for large files: Reference files, data, or documentation don't consume context tokens until actually read
- File paths matter: Claude navigates your skill directory like a filesystem. Use forward slashes (
reference/guide.md), not backslashes - Name files descriptively: Use names that indicate content:
form_validation_rules.md, notdoc2.md - Organize for discovery: Structure directories by domain or feature
- Good:
reference/finance.md,reference/sales.md - Bad:
docs/file1.md,docs/file2.md - Bundle comprehensive resources: Include complete API docs, extensive examples, large datasets; no context penalty until accessed
- Prefer scripts for deterministic operations: Write
validate_form.pyrather than asking Claude to generate validation code - Make execution intent clear:
- "Run
analyze_form.pyto extract fields" (execute) - "See
analyze_form.pyfor the extraction algorithm" (read as reference) - Test file access patterns: Verify Claude can navigate your directory structure by testing with real requests
Example:
bigquery-skill/
├── SKILL.md (overview, points to reference files)
└── reference/
├── finance.md (revenue metrics)
├── sales.md (pipeline data)
└── product.md (usage analytics)When the user asks about revenue, Claude reads SKILL.md, sees the reference to reference/finance.md, and invokes bash to read just that file. The sales.md and product.md files remain on the filesystem, consuming zero context tokens until needed. This filesystem-based model is what enables progressive disclosure. Claude can navigate and selectively load exactly what each task requires.
For complete details on the technical architecture, see How Skills work in the Skills overview.
MCP tool references
If your Skill uses MCP (Model Context Protocol) tools, always use fully qualified tool names to avoid "tool not found" errors.
Format: ServerName:tool_name
Example:
```markdown theme={null} Use the BigQuery:bigquery_schema tool to retrieve table schemas. Use the GitHub:create_issue tool to create issues.
Where:
* `BigQuery` and `GitHub` are MCP server names
* `bigquery_schema` and `create_issue` are the tool names within those servers
Without the server prefix, Claude may fail to locate the tool, especially when multiple MCP servers are available.
### Avoid assuming tools are installed
Don't assume packages are available:
Bad example: Assumes installation: "Use the pdf library to process the file."
Good example: Explicit about dependencies: "Install required package: pip install pypdf
Then use it:
from pypdf import PdfReader
reader = PdfReader("file.pdf")````
Technical notes
YAML frontmatter requirements
The SKILL.md frontmatter includes only name (64 characters max) and description (1024 characters max) fields. See the Skills overview for complete structure details.
Token budgets
Keep SKILL.md body under 500 lines for optimal performance. If your content exceeds this, split it into separate files using the progressive disclosure patterns described earlier. For architectural details, see the Skills overview.
Checklist for effective Skills
Before sharing a Skill, verify:
Core quality
- [ ] Description is specific and includes key terms
- [ ] Description includes both what the Skill does and when to use it
- [ ] SKILL.md body is under 500 lines
- [ ] Additional details are in separate files (if needed)
- [ ] No time-sensitive information (or in "old patterns" section)
- [ ] Consistent terminology throughout
- [ ] Examples are concrete, not abstract
- [ ] File references are one level deep
- [ ] Progressive disclosure used appropriately
- [ ] Workflows have clear steps
Code and scripts
- [ ] Scripts solve problems rather than punt to Claude
- [ ] Error handling is explicit and helpful
- [ ] No "voodoo constants" (all values justified)
- [ ] Required packages listed in instructions and verified as available
- [ ] Scripts have clear documentation
- [ ] No Windows-style paths (all forward slashes)
- [ ] Validation/verification steps for critical operations
- [ ] Feedback loops included for quality-critical tasks
Testing
- [ ] At least three evaluations created
- [ ] Tested with Haiku, Sonnet, and Opus
- [ ] Tested with real usage scenarios
- [ ] Team feedback incorporated (if applicable)
Next steps
<CardGroup cols={2}> <Card title="Get started with Agent Skills" icon="rocket" href="/en/docs/agents-and-tools/agent-skills/quickstart"> Create your first Skill </Card>
<Card title="Use Skills in Claude Code" icon="terminal" href="/en/docs/claude-code/skills"> Create and manage Skills in Claude Code </Card>
<Card title="Use Skills with the API" icon="code" href="/en/api/skills-guide"> Upload and use Skills programmatically </Card> </CardGroup>
Skill Templates & Examples
Complete, copy-paste templates for each skill type.
---
Template: Technique Skill
For how-to guides that teach a specific method.
---
name: technique-name
description: >-
Use when [specific symptom].
metadata:
category: technique
triggers: error-text, symptom, tool-name
---
# Technique Name
## Overview
[1-2 sentence core principle]
## When to Use
- [Symptom A]
- [Symptom B]
- [Error message text]
**NOT for:**
- [When to avoid]
## The Problem
// Bad example function badCode() { // problematic pattern }
## The Solution
// Good example function goodCode() { // improved pattern }
## Step-by-Step
1. [First step]
2. [Second step]
3. [Final step]
## Quick Reference
| Scenario | Approach |
|----------|----------|
| Case A | Solution A |
| Case B | Solution B |
## Common Mistakes
**Mistake 1:** [Description]
- Wrong: `bad code`
- Right: `good code`---
Template: Reference Skill
For documentation, APIs, and lookup tables.
---
name: reference-name
description: >-
Use when working with [domain].
metadata:
category: reference
triggers: tool, api, specific-terms
---
# Reference Name
## Quick Reference
| Command | Purpose |
|---------|---------|
| `cmd1` | Does X |
| `cmd2` | Does Y |
## Common Patterns
**Pattern A:**example command
**Pattern B:**another example
## Detailed Docs
For more options, run `--help` or see:
- patterns.md
- [examples.md](examples.md)---
Template: Discipline Skill
For rules that agents must follow. Requires anti-rationalization techniques.
---
name: discipline-name
description: >-
Use when [BEFORE violation].
metadata:
category: discipline
triggers: new feature, code change, implementation
---
# Rule Name
## Iron Law
**[SINGLE SENTENCE ABSOLUTE RULE]**
Violating the letter IS violating the spirit.
## The Rule
1. ALWAYS [step 1]
2. NEVER [step 2]
3. [Step 3]
## Violations
[Action before rule]? **Delete it. Start over.**
**No exceptions:**
- Don't keep it as "reference"
- Don't "adapt" it
- Delete means delete
## Common Rationalizations
| Excuse | Reality |
|--------|---------|
| "Too simple" | Simple code breaks. Rule takes 30 seconds. |
| "I'll do it after" | After = never. Do it now. |
| "Spirit not ritual" | The ritual IS the spirit. |
## Red Flags - STOP
- [Flag 1]
- [Flag 2]
- "This is different because..."
**All mean:** Delete. Start over.
## Valid Exceptions
- [Exception 1]
- [Exception 2]
**Everything else:** Follow the rule.---
Template: Pattern Skill
For mental models and design patterns.
---
name: pattern-name
description: >-
Use when [recognizable symptom].
metadata:
category: pattern
triggers: complexity, hard-to-follow, nested
---
# Pattern Name
## The Pattern
[1-2 sentence core idea]
## Recognition Signs
- [Sign that pattern applies]
- [Another sign]
- [Code smell]
## Before
// Complex/problematic function before() { // nested, confusing }
## After
// Clean/improved function after() { // flat, clear }
## When NOT to Use
- [Over-engineering case]
- [Simple case that doesn't need it]
## Impact
**Before:** [Problem metric]
**After:** [Improved metric]---
Real Example: Condition-Based Waiting
---
name: condition-based-waiting
description: >-
Use when tests have race conditions or timing dependencies.
metadata:
category: technique
triggers: flaky tests, timeout, race condition, sleep, setTimeout
---# Condition-Based Waiting
## Overview
Replace `sleep(ms)` with `waitFor(() => condition)`.
## When to Use
- Tests pass sometimes, fail other times
- Tests use `sleep()` or `setTimeout()`
- "Works on my machine"
## The Fix
// ❌ Bad await sleep(2000); expect(element).toBeVisible();
// ✅ Good await waitFor(() => element.isVisible(), { timeout: 5000 }); expect(element).toBeVisible();
## Impact
- Flaky tests: 15/100 → 0/100
- Speed: 40% faster (no over-waiting)Skill Writing Gotchas
Tribal knowledge to avoid common mistakes.
YAML Frontmatter
Invalid Syntax
# ❌ BAD: Mixed list and map
metadata:
references:
triggers: a, b, c
- item1
- item2
# ✅ GOOD: Consistent structure
metadata:
triggers: a, b, c
references:
- item1
- item2Multiline Description
# ❌ BAD: Line breaks create parsing errors
description: Use when creating skills.
Also for updating.
# ✅ GOOD: Use YAML multiline syntax
description: >-
Use when creating or updating skills.
Triggers: new skill, update skillNaming
Directory Must Match name Field
# ❌ BAD
directory: my-skill/
name: mySkill # Mismatch!
# ✅ GOOD
directory: my-skill/
name: my-skill # Exact matchSKILL.md Must Be ALL CAPS
# ❌ BAD
skill.md
Skill.md
# ✅ GOOD
SKILL.mdDiscovery
Description = Triggers, NOT Workflow
# ❌ BAD: Agent reads this and skips the full skill
description: Analyzes code, finds bugs, suggests fixes
# ✅ GOOD: Agent reads full skill to understand workflow
description: Use when debugging errors or reviewing code qualityPre-Violation Triggers for Discipline Skills
# ❌ BAD: Triggers AFTER violation
description: Use when you forgot to write tests
# ✅ GOOD: Triggers BEFORE violation
description: Use when implementing any feature, before writing codeToken Efficiency
Skill Loaded Every Conversation = Token Drain
- Frequently-loaded skills: <200 words
- All others: <500 words
- Move details to
references/files
Don't Duplicate CLI Help
# ❌ BAD: 50 lines documenting all flags
# ✅ GOOD: One line
Run `mytool --help` for all options.Anti-Rationalization (Discipline Skills Only)
Agents Are Smart at Finding Loopholes
# ❌ BAD: Trust agents will "get the spirit"
Write test before code.
# ✅ GOOD: Close every loophole explicitly
Write test before code.
**No exceptions:**
- Don't keep code as "reference"
- Don't "adapt" existing code
- Delete means deleteBuild Rationalization Table
Every excuse from baseline testing goes in the table:
| Excuse | Reality |
|---|---|
| "Too simple to test" | Simple code breaks. Test takes 30 seconds. |
| "I'll test after" | Tests-after prove nothing immediately. |
Cross-References
Keep References One Level Deep
# ❌ BAD: Nested chain (A → B → C)
See [patterns.md] → which links to [advanced.md] → which links to [deep.md]
# ✅ GOOD: Flat (A → B, A → C)
See [patterns.md] and [advanced.md]Never Force-Load with @
# ❌ BAD: Burns context immediately
@skills/my-skill/SKILL.md
# ✅ GOOD: Agent loads when needed
See [my-skill] for details.OpenCode Integration
Correct Skill Directory
# ❌ BAD: Old singular path
~/.config/opencode/skill/my-skill/
# ✅ GOOD: Plural path
~/.config/opencode/skills/my-skill/Skill Cross-Reference Syntax
# ❌ BAD: File path (fragile)
See /home/user/.config/opencode/skills/my-skill/SKILL.md
# ✅ GOOD: Skill protocol
See my-skillTier Selection
Don't Overthink Tier Choice
# ❌ BAD: Starting with Tier 3 "just in case"
# Result: Wasted effort, empty reference files
# ✅ GOOD: Start with Tier 1, upgrade when needed
# Can always add references/ laterSignals You Need to Upgrade
| Signal | Action |
|---|---|
| SKILL.md > 200 lines | → Tier 2 |
| 3+ related sub-topics | → Tier 2 |
| 10+ products/services | → Tier 3 |
| "I need X" vs "I want Y" | → Tier 3 decision trees |
digraph STYLE_GUIDE {
// The style guide for our process DSL, written in the DSL itself
// Node type examples with their shapes
subgraph cluster_node_types {
label="NODE TYPES AND SHAPES";
// Questions are diamonds
"Is this a question?" [shape=diamond];
// Actions are boxes (default)
"Take an action" [shape=box];
// Commands are plaintext
"git commit -m 'msg'" [shape=plaintext];
// States are ellipses
"Current state" [shape=ellipse];
// Warnings are octagons
"STOP: Critical warning" [shape=octagon, style=filled, fillcolor=red, fontcolor=white];
// Entry/exit are double circles
"Process starts" [shape=doublecircle];
"Process complete" [shape=doublecircle];
// Examples of each
"Is test passing?" [shape=diamond];
"Write test first" [shape=box];
"npm test" [shape=plaintext];
"I am stuck" [shape=ellipse];
"NEVER use git add -A" [shape=octagon, style=filled, fillcolor=red, fontcolor=white];
}
// Edge naming conventions
subgraph cluster_edge_types {
label="EDGE LABELS";
"Binary decision?" [shape=diamond];
"Yes path" [shape=box];
"No path" [shape=box];
"Binary decision?" -> "Yes path" [label="yes"];
"Binary decision?" -> "No path" [label="no"];
"Multiple choice?" [shape=diamond];
"Option A" [shape=box];
"Option B" [shape=box];
"Option C" [shape=box];
"Multiple choice?" -> "Option A" [label="condition A"];
"Multiple choice?" -> "Option B" [label="condition B"];
"Multiple choice?" -> "Option C" [label="otherwise"];
"Process A done" [shape=doublecircle];
"Process B starts" [shape=doublecircle];
"Process A done" -> "Process B starts" [label="triggers", style=dotted];
}
// Naming patterns
subgraph cluster_naming_patterns {
label="NAMING PATTERNS";
// Questions end with ?
"Should I do X?";
"Can this be Y?";
"Is Z true?";
"Have I done W?";
// Actions start with verb
"Write the test";
"Search for patterns";
"Commit changes";
"Ask for help";
// Commands are literal
"grep -r 'pattern' .";
"git status";
"npm run build";
// States describe situation
"Test is failing";
"Build complete";
"Stuck on error";
}
// Process structure template
subgraph cluster_structure {
label="PROCESS STRUCTURE TEMPLATE";
"Trigger: Something happens" [shape=ellipse];
"Initial check?" [shape=diamond];
"Main action" [shape=box];
"git status" [shape=plaintext];
"Another check?" [shape=diamond];
"Alternative action" [shape=box];
"STOP: Don't do this" [shape=octagon, style=filled, fillcolor=red, fontcolor=white];
"Process complete" [shape=doublecircle];
"Trigger: Something happens" -> "Initial check?";
"Initial check?" -> "Main action" [label="yes"];
"Initial check?" -> "Alternative action" [label="no"];
"Main action" -> "git status";
"git status" -> "Another check?";
"Another check?" -> "Process complete" [label="ok"];
"Another check?" -> "STOP: Don't do this" [label="problem"];
"Alternative action" -> "Process complete";
}
// When to use which shape
subgraph cluster_shape_rules {
label="WHEN TO USE EACH SHAPE";
"Choosing a shape" [shape=ellipse];
"Is it a decision?" [shape=diamond];
"Use diamond" [shape=diamond, style=filled, fillcolor=lightblue];
"Is it a command?" [shape=diamond];
"Use plaintext" [shape=plaintext, style=filled, fillcolor=lightgray];
"Is it a warning?" [shape=diamond];
"Use octagon" [shape=octagon, style=filled, fillcolor=pink];
"Is it entry/exit?" [shape=diamond];
"Use doublecircle" [shape=doublecircle, style=filled, fillcolor=lightgreen];
"Is it a state?" [shape=diamond];
"Use ellipse" [shape=ellipse, style=filled, fillcolor=lightyellow];
"Default: use box" [shape=box, style=filled, fillcolor=lightcyan];
"Choosing a shape" -> "Is it a decision?";
"Is it a decision?" -> "Use diamond" [label="yes"];
"Is it a decision?" -> "Is it a command?" [label="no"];
"Is it a command?" -> "Use plaintext" [label="yes"];
"Is it a command?" -> "Is it a warning?" [label="no"];
"Is it a warning?" -> "Use octagon" [label="yes"];
"Is it a warning?" -> "Is it entry/exit?" [label="no"];
"Is it entry/exit?" -> "Use doublecircle" [label="yes"];
"Is it entry/exit?" -> "Is it a state?" [label="no"];
"Is it a state?" -> "Use ellipse" [label="yes"];
"Is it a state?" -> "Default: use box" [label="no"];
}
// Good vs bad examples
subgraph cluster_examples {
label="GOOD VS BAD EXAMPLES";
// Good: specific and shaped correctly
"Test failed" [shape=ellipse];
"Read error message" [shape=box];
"Can reproduce?" [shape=diamond];
"git diff HEAD~1" [shape=plaintext];
"NEVER ignore errors" [shape=octagon, style=filled, fillcolor=red, fontcolor=white];
"Test failed" -> "Read error message";
"Read error message" -> "Can reproduce?";
"Can reproduce?" -> "git diff HEAD~1" [label="yes"];
// Bad: vague and wrong shapes
bad_1 [label="Something wrong", shape=box]; // Should be ellipse (state)
bad_2 [label="Fix it", shape=box]; // Too vague
bad_3 [label="Check", shape=box]; // Should be diamond
bad_4 [label="Run command", shape=box]; // Should be plaintext with actual command
bad_1 -> bad_2;
bad_2 -> bad_3;
bad_3 -> bad_4;
}
}Persuasion Principles for Skill Design
Overview
LLMs respond to the same persuasion principles as humans. Understanding this psychology helps you design more effective skills - not to manipulate, but to ensure critical practices are followed even under pressure.
Research foundation: Meincke et al. (2025) tested 7 persuasion principles with N=28,000 AI conversations. Persuasion techniques more than doubled compliance rates (33% → 72%, p < .001).
The Seven Principles
1. Authority
What it is: Deference to expertise, credentials, or official sources.
How it works in skills:
- Imperative language: "YOU MUST", "Never", "Always"
- Non-negotiable framing: "No exceptions"
- Eliminates decision fatigue and rationalization
When to use:
- Discipline-enforcing skills (TDD, verification requirements)
- Safety-critical practices
- Established best practices
Example:
✅ Write code before test? Delete it. Start over. No exceptions.
❌ Consider writing tests first when feasible.2. Commitment
What it is: Consistency with prior actions, statements, or public declarations.
How it works in skills:
- Require announcements: "Announce skill usage"
- Force explicit choices: "Choose A, B, or C"
- Use tracking: TodoWrite for checklists
When to use:
- Ensuring skills are actually followed
- Multi-step processes
- Accountability mechanisms
Example:
✅ When you find a skill, you MUST announce: "I'm using [Skill Name]"
❌ Consider letting your partner know which skill you're using.3. Scarcity
What it is: Urgency from time limits or limited availability.
How it works in skills:
- Time-bound requirements: "Before proceeding"
- Sequential dependencies: "Immediately after X"
- Prevents procrastination
When to use:
- Immediate verification requirements
- Time-sensitive workflows
- Preventing "I'll do it later"
Example:
✅ After completing a task, IMMEDIATELY request code review before proceeding.
❌ You can review code when convenient.4. Social Proof
What it is: Conformity to what others do or what's considered normal.
How it works in skills:
- Universal patterns: "Every time", "Always"
- Failure modes: "X without Y = failure"
- Establishes norms
When to use:
- Documenting universal practices
- Warning about common failures
- Reinforcing standards
Example:
✅ Checklists without TodoWrite tracking = steps get skipped. Every time.
❌ Some people find TodoWrite helpful for checklists.5. Unity
What it is: Shared identity, "we-ness", in-group belonging.
How it works in skills:
- Collaborative language: "our codebase", "we're colleagues"
- Shared goals: "we both want quality"
When to use:
- Collaborative workflows
- Establishing team culture
- Non-hierarchical practices
Example:
✅ We're colleagues working together. I need your honest technical judgment.
❌ You should probably tell me if I'm wrong.6. Reciprocity
What it is: Obligation to return benefits received.
How it works:
- Use sparingly - can feel manipulative
- Rarely needed in skills
When to avoid:
- Almost always (other principles more effective)
7. Liking
What it is: Preference for cooperating with those we like.
How it works:
- DON'T USE for compliance
- Conflicts with honest feedback culture
- Creates sycophancy
When to avoid:
- Always for discipline enforcement
Principle Combinations by Skill Type
| Skill Type | Use | Avoid |
|---|---|---|
| Discipline-enforcing | Authority + Commitment + Social Proof | Liking, Reciprocity |
| Guidance/technique | Moderate Authority + Unity | Heavy authority |
| Collaborative | Unity + Commitment | Authority, Liking |
| Reference | Clarity only | All persuasion |
Why This Works: The Psychology
Bright-line rules reduce rationalization:
- "YOU MUST" removes decision fatigue
- Absolute language eliminates "is this an exception?" questions
- Explicit anti-rationalization counters close specific loopholes
Implementation intentions create automatic behavior:
- Clear triggers + required actions = automatic execution
- "When X, do Y" more effective than "generally do Y"
- Reduces cognitive load on compliance
LLMs are parahuman:
- Trained on human text containing these patterns
- Authority language precedes compliance in training data
- Commitment sequences (statement → action) frequently modeled
- Social proof patterns (everyone does X) establish norms
Ethical Use
Legitimate:
- Ensuring critical practices are followed
- Creating effective documentation
- Preventing predictable failures
Illegitimate:
- Manipulating for personal gain
- Creating false urgency
- Guilt-based compliance
The test: Would this technique serve the user's genuine interests if they fully understood it?
Research Citations
Cialdini, R. B. (2021). Influence: The Psychology of Persuasion (New and Expanded). Harper Business.
- Seven principles of persuasion
- Empirical foundation for influence research
Meincke, L., Shapiro, D., Duckworth, A. L., Mollick, E., Mollick, L., & Cialdini, R. (2025). Call Me A Jerk: Persuading AI to Comply with Objectionable Requests. University of Pennsylvania.
- Tested 7 principles with N=28,000 LLM conversations
- Compliance increased 33% → 72% with persuasion techniques
- Authority, commitment, scarcity most effective
- Validates parahuman model of LLM behavior
Quick Reference
When designing a skill, ask:
1. What type is it? (Discipline vs. guidance vs. reference) 2. What behavior am I trying to change? 3. Which principle(s) apply? (Usually authority + commitment for discipline) 4. Am I combining too many? (Don't use all seven) 5. Is this ethical? (Serves user's genuine interests?)
Anti-Rationalization Guide
Techniques for bulletproofing skills against agent rationalization.
The Problem
Discipline-enforcing skills (like TDD) face a unique challenge: smart agents under pressure will find loopholes.
Example: Skill says "Write test first". Agent under deadline thinks:
- "This is too simple to test"
- "I'll test after, same result"
- "It's the spirit that matters, not ritual"
Psychology Foundation
Understanding WHY persuasion works helps apply it systematically.
Research basis: Cialdini (2021), Meincke et al. (2025)
Core principles:
- Authority: "The TDD community agrees..."
- Commitment: "You already said you follow TDD..."
- Scarcity: "Missing tests now = bugs later"
- Social Proof: "All tested code passing CI proves value"
- Unity: "We're engineers who value quality"
Technique 1: Close Every Loophole Explicitly
Don't just state the rule - forbid specific workarounds.
Bad Example
Write code before test? Delete it.Good Example
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 deleteWhy it works: Agents try specific workarounds. Counter each explicitly.
Technique 2: Address "Spirit vs Letter" Arguments
Add foundational principle early:
**Violating the letter of the rules is violating the spirit of the rules.**Why it works: Cuts off entire class of "I'm following the spirit" rationalizations.
Technique 3: Build Rationalization Table
Capture excuses from baseline testing. Every rationalization goes in 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?" |
| "It's about spirit not ritual" | The letter IS the spirit. TDD's value comes from the specific sequence. |Why it works: Agents read table, recognize their own thinking, see the counter-argument.
Technique 4: Create Red Flags List
Make it easy for agents 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..."
**All of these mean**: Delete code. Start over with TDD.Why it works: Simple checklist, clear action (delete & restart).
Technique 5: Update Description for Violation Symptoms
Add to description: symptoms of when you're ABOUT to violate:
# ❌ BAD: Only describes what skill does
description: TDD methodology for writing code
# ✅ GOOD: Includes pre-violation symptoms
description: Use when implementing any feature or bugfix, before writing implementation code
metadata:
triggers: new feature, bug fix, code changeWhy it works: Triggers skill BEFORE violation, not after.
Technique 6: Use Strong Language
Weak language invites rationalization:
# Weak
You should write tests first.
Generally, test before code.
It's better to test first.
# Strong
ALWAYS write test first.
NEVER write code before test.
Test-first is MANDATORY.Why it works: No ambiguity, no wiggle room.
Technique 7: Invoke Commitment & Consistency
Reference agent's own standards:
You claimed to follow TDD.
TDD means test-first.
Code-first is NOT TDD.
**Either**:
- Follow TDD (test-first), or
- Admit you're not doing TDD
Don't redefine TDD to fit what you already did.Why it works: Agents resist cognitive dissonance (Festinger, 1957).
Technique 8: Provide Escape Hatch for Legitimate Cases
If there ARE valid exceptions, state them explicitly:
## When NOT to Use TDD
- Spike solutions (throwaway exploratory code)
- One-time scripts deleting in 1 hour
- Generated boilerplate (verified via other means)
**Everything else**: Use TDD. No exceptions.Why it works: Removes "but this is different" argument for non-exception cases.
Complete Bulletproofing Checklist
For discipline-enforcing skills:
Loophole Closing:
- [ ] Forbidden each specific workaround explicitly?
- [ ] Added "spirit vs letter" principle?
- [ ] Built rationalization table from baseline tests?
- [ ] Created red flags list?
Strength:
- [ ] Used strong language (ALWAYS/NEVER)?
- [ ] Invoked commitment & consistency?
- [ ] Provided explicit escape hatch?
Discovery:
- [ ] Description includes pre-violation symptoms?
- [ ] Keywords target moment BEFORE violation?
Testing:
- [ ] Tested with combined pressures?
- [ ] Agent complied under maximum pressure?
- [ ] No new rationalizations found?
Real-World Example: TDD Skill
Baseline Rationalizations Found
1. "Too simple to test" 2. "I'll test after" 3. "Spirit not ritual" 4. "Already manually tested" 5. "This is different because..."
Counters Applied
Rationalization table:
| Excuse | Reality |
| -------------------- | -------------------------------------------------------------- |
| "Too simple to test" | Simple code breaks. Test takes 30 seconds. |
| "I'll test after" | Tests passing immediately prove nothing. |
| "Spirit not ritual" | The letter IS the spirit. TDD's value comes from the sequence. |
| "Manually tested" | Manual tests don't run automatically. They rot. |Red flags:
## Red Flags - STOP
- Code before test
- "I already tested manually"
- "Spirit not ritual"
- "This is different..."
All mean: Delete code. Start over.Result: Agent compliance under combined time + sunk cost pressure.
Common Mistakes
| Mistake | Fix |
|---|---|
| Trust agents will "get the spirit" | Close explicit loopholes. Agents are smart at rationalization. |
| Use weak language ("should", "better") | Use ALWAYS/NEVER for discipline rules. |
| Skip rationalization table | Every excuse needs explicit counter. |
| No red flags list | Make self-checking easy. |
| Generic description | Add pre-violation symptoms to trigger skill earlier. |
Meta-Strategy
For each new rationalization:
1. Document it verbatim (from failed test) 2. Add to rationalization table 3. Update red flags list 4. Re-test
Iterate until: Agent can't find ANY rationalization that works.
That's bulletproof.
CSO Guide - Claude Search Optimization
Advanced techniques for making skills discoverable by agents.
The Discovery Problem
You have 100+ skills. Agent receives a task. How does it find the RIGHT skill?
Answer: The description field.
Critical Rule: Description = Triggers, NOT Workflow
The Trap
When description summarizes workflow, agents take a shortcut.
Real example that failed:
# Agent did ONE review instead of TWO
description: Code review between tasks
# Skill body had flowchart showing TWO reviews:
# 1. Spec compliance
# 2. Code qualityWhy it failed: Agent read description, thought "code review between tasks means one review", never read the flowchart.
Fix:
# Agent now reads full skill and follows flowchart
description: Use when executing implementation plans with independent tasksThe Pattern
# ❌ BAD: Workflow summary
description: Analyzes git diff, generates commit message in conventional format
# ✅ GOOD: Trigger conditions only
description: Use when generating commit messages or reviewing staged changesToken Efficiency Critical for Skills
Problem: Frequently-loaded skills consume tokens in EVERY conversation.
Target word counts:
- Frequently-loaded skills: <200 words total
- Other skills: <500 words
Techniques
1. Move details to 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. Run --help for details.2. Use cross-references:
# ❌ BAD: Repeat workflow
When searching, dispatch agent with template...
[20 lines of repeated instructions]
# ✅ GOOD: Reference other skill
Use subagents for searches. See [delegating-to-subagents] for workflow.3. Compress examples:
# ❌ BAD: Verbose (42 words)
Partner: "How did we handle auth errors in React Router?"
You: I'll search past conversations for patterns.
[Dispatch subagent with query: "React Router authentication error handling 401"]
# ✅ GOOD: Minimal (20 words)
Partner: "Auth errors in React Router?"
You: Searching...
[Dispatch subagent → synthesis]Keyword Strategy
Error Messages
Include EXACT error text users will see:
- "Hook timed out after 5000ms"
- "ENOTEMPTY: directory not empty"
- "jest --watch is not responding"
Symptoms
Use words users naturally say:
- "flaky", "hangs", "zombie process"
- "slow", "timeout", "race condition"
- "cleanup failed", "pollution"
Tools & Commands
Actual names, not descriptions:
- "pytest", not "Python testing"
- "git rebase", not "rebasing"
- ".docx files", not "Word documents"
Synonyms
Cover multiple ways to describe same thing:
- timeout/hang/freeze
- cleanup/teardown/after Each
- mock/stub/fake
Naming Conventions
Gerunds (-ing) for Processes
✅ creating-skills, debugging-with-logs, testing-async-code
Verb-first for Actions
✅ flatten-with-flags, reduce-complexity, trace-root-cause
❌ Avoid
skill-creation(passive, less searchable)async-test-helpers(too generic)debugging-techniques(vague)
Description Template
description: "Use when [SPECIFIC TRIGGER]."
metadata:
triggers: [error1], [symptom2], [tool3]Examples:
# Technique skill
description: "Use when tests have race conditions, timing dependencies, or pass/fail inconsistently."
metadata:
triggers: flaky tests, timeout, race condition
# Pattern skill
description: "Use when complex data structures make code hard to follow."
metadata:
triggers: nested loops, multiple flags, confusing state
# Reference skill
description: "Use when working with React Router and authentication."
metadata:
triggers: 401 redirect, login flow, protected routes
# Discipline skill
description: "Use when implementing any feature or bugfix, before writing implementation code."
metadata:
triggers: new feature, bug fix, code changeThird Person Rule
Description is injected into system prompt. Inconsistent POV breaks discovery.
# ❌ BAD: First person
description: "I can help you with async tests"
# ❌ BAD: Second person
description: "You can use this for race conditions"
# ✅ GOOD: Third person
description: "Handles async tests with race conditions"Cross-Referencing Other Skills
When documenting a skill that references other skills:
Use skill name only, with explicit requirement markers:
# ✅ GOOD: Clear requirement
**REQUIRED BACKGROUND**: You MUST understand test-driven-development before using this skill.
**REQUIRED SUB-SKILL**: Use defensive-programming for error handling.
# ❌ BAD: Unclear if required
See test-driven-development skill for context.
# ❌ NEVER: Force-loads (burns context)
@skills/testing/test-driven-development/SKILL.mdWhy no @ links: @ syntax force-loads files immediately, consuming tokens before needed.
Verification Checklist
Before deploying:
- [ ] Description starts with "Use when..."?
- [ ] Description is <500 characters?
- [ ] Description lists ONLY triggers, not workflow?
- [ ] Includes 3+ keywords (errors/symptoms/tools)?
- [ ] Third person throughout?
- [ ] Name uses gerund or verb-first format?
- [ ] Name has only letters, numbers, hyphens?
- [ ] No @ syntax for cross-references?
- [ ] Word count <200 (frequent) or <500 (other)?
Real-World Examples
Before/After: TDD Skill
❌ Before (workflow in description):
description: Write test first, watch it fail, write minimal code, refactorResult: Agents followed description, skipped reading full skill.
✅ After (triggers only):
description: Use when implementing any feature or bugfix, before writing implementation codeResult: Agents read full skill, followed complete TDD cycle.
Before/After: BigQuery Skill
❌ Before (too vague):
description: Helps with database queriesResult: Never loaded (too generic, agents couldn't identify relevance).
✅ After (specific triggers):
description: Use when analyzing BigQuery data. Triggers: revenue metrics, pipeline data, API usage, campaign attribution.Result: Loads for relevant queries, includes domain keywords.
SKILL.md Metadata Standard
Official frontmatter fields recognized by OpenCode.
Required Fields
---
name: skill-name
description: >-
Use when [trigger condition].
metadata:
triggers: keyword1, keyword2, error-message
---| Field | Rules |
|---|---|
name | 1-64 chars, lowercase, hyphens only, must match directory name |
description | 1-1024 chars, should describe when to use |
Optional Fields
---
name: skill-name
description: Purpose and triggers.
metadata:
license: MIT
compatibility: opencode
author: "your-name"
version: "1.0.0"
category: "reference"
tags: "tag1, tag2"
---| Field | Purpose |
|---|---|
license | License identifier (e.g., MIT, Apache-2.0) |
compatibility | Tool compatibility marker |
metadata | String-to-string map for custom key-values |
Name Validation
^[a-z0-9]+(-[a-z0-9]+)*$Valid: my-skill, git-release, tdd Invalid: My-Skill, my_skill, -my-skill, my--skill
Common Metadata Keys
Use these conventions for consistency across skills:
| Key | Example | Purpose |
|---|---|---|
author | "your-name" | Skill creator |
version | "1.0.0" | Semantic version |
category | "reference" | Type: reference, technique, discipline, pattern |
tags | "react, hooks" | Searchable keywords |
[!IMPORTANT]
Any field not listed here is ignored by OpenCode's skill loader.
Skill Development Guide
Comprehensive reference for creating effective agent skills.
Directory Structure
~/.config/opencode/skills/
{skill-name}/ # kebab-case, matches `name` field
SKILL.md # Required: main skill definition
references/ # Optional: supporting documentation
README.md # Sub-topic entry point
*.md # Additional filesProject-local alternative:
.agent/skills/{skill-name}/SKILL.mdNaming Rules
| Element | Rule | Example |
|---|---|---|
| Directory | kebab-case, 1-64 chars | react-best-practices |
SKILL.md | ALL CAPS, exact filename | SKILL.md (not skill.md) |
name field | Must match directory name | name: react-best-practices |
SKILL.md Structure
---
name: {skill-name}
description: >-
Use when [trigger condition].
metadata:
category: technique
triggers: keyword1, keyword2, error-text
---
# Skill Title
Brief description of what this skill does.
## When to Use
- Symptom or situation A
- Symptom or situation B
## How It Works
Step-by-step instructions or reference content.
## Examples
Concrete usage examples.
## Common Mistakes
What to avoid and why.Description Best Practices
The description field is critical for skill discovery:
# ❌ BAD: Workflow summary (agent skips reading full skill)
description: Analyzes code, finds bugs, suggests fixes
# ✅ GOOD: Trigger conditions only
description: Use when debugging errors or reviewing code quality.
metadata:
triggers: bug, error, code reviewRules:
- Start with "Use when..."
- Put triggers under
metadata.triggers - Keep under 500 characters
- Use third person (not "I" or "You")
Context Efficiency
Skills load into context on-demand. Optimize for token usage:
| Guideline | Reason |
|---|---|
| Keep SKILL.md < 500 lines | Reduces context consumption |
| Put details in supporting files | Agent reads only what's needed |
| Use tables for reference data | More compact than prose |
Link to --help for CLI tools | Avoids duplicating docs |
Supporting Files
For complex skills, use additional files:
my-skill/
SKILL.md # Overview + navigation
patterns.md # Detailed patterns
examples.md # Code examples
troubleshooting.md # Common issuesSupporting file frontmatter is required (for any .md besides SKILL.md):
---
description: >-
Short summary used for search and retrieval.
metadata:
tags: [pattern, troubleshooting, api]
source: internal
---This frontmatter helps the LLM locate the right file when referenced from SKILL.md.
Reference from SKILL.md:
## Detailed Reference
- Patterns - Common usage patterns
- Examples - Code samplesSkill Types
| Type | Purpose | Example |
|---|---|---|
| Reference | Documentation, APIs | bigquery-analysis |
| Technique | How-to guides | condition-based-waiting |
| Pattern | Mental models | flatten-with-flags |
| Discipline | Rules to enforce | test-driven-development |
Verification Checklist
Before deploying:
- [ ]
namematches directory name? - [ ]
SKILL.mdis ALL CAPS? - [ ] Description starts with "Use when..."?
- [ ] Triggers listed under metadata?
- [ ] Under 500 lines?
- [ ] Tested with real scenarios?
Rule Name
Iron Law
[SINGLE SENTENCE ABSOLUTE RULE]
Violating the letter IS violating the spirit.
The Rule
1. ALWAYS [step 1] 2. NEVER [step 2] 3. [Step 3]
Violations
[Action before rule]? Delete it. Start over.
No exceptions:
- Don't keep it as "reference"
- Don't "adapt" it
- Delete means delete
Common Rationalizations
| Excuse | Reality |
|---|---|
| "Too simple" | Simple code breaks. Rule takes 30 seconds. |
| "I'll do it after" | After = never. Do it now. |
| "Spirit not ritual" | The ritual IS the spirit. |
Red Flags - STOP
- [Flag 1]
- [Flag 2]
- "This is different because..."
All mean: Delete. Start over.
Valid Exceptions
- [Exception 1]
- [Exception 2]
Everything else: Follow the rule.
Pattern Name
The Pattern
[1-2 sentence core idea]
Recognition Signs
- [Sign that pattern applies]
- [Another sign]
- [Code smell]
Before
// Complex/problematic
function before() {
// nested, confusing
}After
// Clean/improved
function after() {
// flat, clear
}When NOT to Use
- [Over-engineering case]
- [Simple case that doesn't need it]
Impact
Before: [Problem metric] After: [Improved metric]
Reference Name
Quick Reference
| Command | Purpose |
|---|---|
cmd1 | Does X |
cmd2 | Does Y |
Common Patterns
Pattern A:
example commandPattern B:
another exampleDetailed Docs
For more options, run --help or see:
- patterns.md
- examples.md
Technique Name
Overview
[1-2 sentence core principle]
When to Use
- [Symptom A]
- [Symptom B]
- [Error message text]
NOT for:
- [When to avoid]
The Problem
// Bad example
function badCode() {
// problematic pattern
}The Solution
// Good example
function goodCode() {
// improved pattern
}Step-by-Step
1. [First step] 2. [Second step] 3. [Final step]
Quick Reference
| Scenario | Approach |
|---|---|
| Case A | Solution A |
| Case B | Solution B |
Common Mistakes
Mistake 1: [Description]
- Wrong:
bad code - Right:
good code
Platform Name Skill
Template for complex Tier 3 skills.
Structure
skill/
├── SKILL.md # Dispatcher
├── commands/
│ └── skill.md # Orchestrator
└── references/
└── topic/
├── README.md # Overview
├── api.md # API Reference
├── config.md # Configuration
├── patterns.md # Recipes
└── gotchas.md # Critical ErrorsTesting Guide - TDD for Skills
Complete methodology for testing skills using RED-GREEN-REFACTOR cycle.
Testing All Skill Types
Different skill types need different test approaches.
Discipline-Enforcing Skills (rules/requirements)
Examples: TDD, verification-before-completion, designing-before-coding
Test with:
- Academic questions: Do they understand the rules?
- Pressure scenarios: Do they comply under stress?
- Multiple pressures combined: time + sunk cost + exhaustion
- Identify rationalizations and add explicit counters
Success criteria: Agent follows rule under maximum pressure
Technique Skills (how-to guides)
Examples: condition-based-waiting, root-cause-tracing, defensive-programming
Test with:
- Application scenarios: Can they apply the technique correctly?
- Variation scenarios: Do they handle edge cases?
- Missing information tests: Do instructions have gaps?
Success criteria: Agent successfully applies technique to new scenario
Pattern Skills (mental models)
Examples: reducing-complexity, information-hiding concepts
Test with:
- Recognition scenarios: Do they recognize when pattern applies?
- Application scenarios: Can they use the mental model?
- Counter-examples: Do they know when NOT to apply?
Success criteria: Agent correctly identifies when/how to apply pattern
Reference Skills (documentation/APIs)
Examples: API documentation, command references, library guides
Test with:
- Retrieval scenarios: Can they find the right information?
- Application scenarios: Can they use what they found correctly?
- Gap testing: Are common use cases covered?
Success criteria: Agent finds and correctly applies reference information
Pressure Types for Testing
Time Pressure
"You have 5 minutes to complete this task"
Sunk Cost Pressure
"You already spent 2 hours on this, just finish it quickly"
Authority Pressure
"The senior developer said to skip tests for this quick bug fix"
Exhaustion Pressure
"This is the 10th task today, let's wrap it up"
RED Phase: Baseline Testing
Goal: Watch the agent fail WITHOUT the skill.
Steps:
1. Design pressure scenario (combine 2-3 pressures) 2. Give agent the task WITHOUT the skill loaded 3. Document EXACT behavior:
- What rationalization did they use?
- Which pressure triggered the violation?
- How did they justify the shortcut?
Critical: Copy exact quotes. You'll need them for GREEN phase.
Example Baseline:
Scenario: Implement feature under time pressure
Pressure: "You have 10 minutes"
Agent response: "Since we're short on time, I'll implement the feature first
and add tests after. Testing later achieves the same goal."GREEN Phase: Minimal Implementation
Goal: Write skill that addresses SPECIFIC baseline failures.
Steps:
1. Review baseline rationalizations 2. Write skill sections that counter THOSE EXACT arguments 3. Re-run scenario WITH skill 4. Agent should now comply
Bad (too general):
## Testing
Always write tests.Good (addresses specific rationalization):
## Common Rationalizations
| Excuse | Reality |
| ----------------------------------- | ----------------------------------------------------------------------- |
| "Testing after achieves same goals" | Tests-after = "what does this do?" Tests-first = "what should this do?" |
| "Too simple to test" | Simple code breaks. Test takes 30 seconds. |REFACTOR Phase: Loophole Closing
Goal: Find and plug new rationalizations.
Steps:
1. Agent found new workaround? Document it. 2. Add explicit counter to skill 3. Re-test same scenario 4. Repeat until bulletproof
Pattern:
## 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..."
**All of these mean**: Delete code. Start over with TDD.Complete Test Checklist
Before deploying a skill:
Baseline (RED):
- [ ] Designed 3+ pressure scenarios
- [ ] Ran scenarios WITHOUT skill
- [ ] Documented verbatim agent responses
- [ ] Identified pattern in rationalizations
Implementation (GREEN):
- [ ] Skill addresses SPECIFIC baseline failures
- [ ] Re-ran scenarios WITH skill
- [ ] Agent complied in all scenarios
- [ ] No hand-waving or generic advice
Bulletproofing (REFACTOR):
- [ ] Tested with combined pressures
- [ ] Found and documented new rationalizations
- [ ] Added explicit counters
- [ ] Re-tested until no more loopholes
- [ ] Created "Red Flags" section
Common Testing Mistakes
| Mistake | Fix |
|---|---|
| "I'll test if problems emerge" | Problems = agents can't use skill. Test BEFORE deploying. |
| "Skill is obviously clear" | Clear to you ≠ clear to agents. Test it. |
| "Testing is overkill" | Untested skills have issues. Always. |
| "Academic review is enough" | Reading ≠ using. Test application scenarios. |
Meta-Testing
Test the test: If agent passes too easily, your test is weak.
Good test indicators:
- Agent fails WITHOUT skill (proves skill is needed)
- Agent p asses WITH skill (proves skill works)
- Multiple pressures needed to trigger failure (proves realistic)
Bad test indicators:
- Agent passes even without skill (test is irrelevant)
- Agent fails even with skill (skill is unclear)
- Single obvious scenario (test is too simple)
Tier 1: Simple Skills
Single-file skills for focused, specific purposes.
When to Use
- Single concept: One technique, one pattern, one reference
- Under 200 lines: Can fit comfortably in one file
- No complex decision logic: User knows exactly what they need
- Frequently loaded: Needs minimal token footprint
Structure
my-skill/
└── SKILL.md # Everything in one fileExample
---
name: flatten-with-flags
description: Use when simplifying deeply nested conditionals.
metadata:
category: pattern
triggers: nested if, complex conditionals, early return
---
# Flatten with Flags
## When to Use
- Code has 3+ levels of nesting
- Conditions are hard to follow
## The Pattern
Replace nested conditions with early returns and flag variables.
## Beforefunction process(data) { if (data) { if (data.valid) { if (data.ready) { return doWork(data); } } } return null; }
## Afterfunction process(data) { if (!data) return null; if (!data.valid) return null; if (!data.ready) return null; return doWork(data); }
Checklist
- [ ] Fits in <200 lines
- [ ] Single focused purpose
- [ ] No need for
references/directory - [ ] Description uses "Use when..." pattern
Tier 2: Expanded Skills
Multi-file skills for complex topics with multiple sub-concepts.
When to Use
- Multiple related concepts: Needs separation of concerns
- 200-1000 lines total: Too big for one file
- Needs reference files: Patterns, examples, troubleshooting
- Cross-linking: Users need to navigate between sub-topics
Structure
my-skill/
├── SKILL.md # Overview + navigation
└── references/
├── core/
│ ├── README.md # Main concept
│ └── api.md # API reference
├── patterns/
│ └── README.md # Usage patterns
└── troubleshooting/
└── README.md # Common issuesExample
The writing-skills skill itself is Tier 2:
writing-skills/
├── SKILL.md # Decision tree + navigation
├── gotchas.md # Tribal knowledge
└── references/
├── anti-rationalization/
├── cso/
├── standards/
├── templates/
└── testing/Progressive Disclosure
1. Metadata (~100 tokens): Name + description loaded at startup 2. SKILL.md (<500 lines): Decision tree + index 3. References (as needed): Loaded only when user navigates
Key Differences from Tier 1
| Aspect | Tier 1 | Tier 2 |
|---|---|---|
| Files | 1 | 5-20 |
| Total lines | <200 | 200-1000 |
| Decision logic | None | Simple tree |
| Token cost | Minimal | Medium (progressive) |
Checklist
- [ ] SKILL.md has clear navigation links
- [ ] Each
references/subdir has README.md - [ ] No circular references between files
- [ ] Decision tree points to specific files
Tier 3: Platform Skills
Enterprise-grade skills for entire platforms (AWS, Cloudflare, Convex, etc).
When to Use
- Entire platform: 10+ products/services
- 1000+ lines total: Would overwhelm context if monolithic
- Complex decision logic: Users start with "I need X" not "I want product Y"
- Undocumented gotchas: Tribal knowledge is critical
The Cloudflare Pattern
Based on cloudflare-skill by Dillon Mulroy.
Structure
my-platform/
├── SKILL.md # Decision trees only
└── references/
└── <product>/
├── README.md # Overview, when to use
├── api.md # Runtime API reference
├── configuration.md # Config options
├── patterns.md # Usage patterns
└── gotchas.md # Pitfalls, limitsThe 5-File Pattern
Each product directory has exactly 5 files:
| File | Purpose | When to Load |
|---|---|---|
README.md | Overview, when to use | Always first |
api.md | Runtime APIs, methods | Implementing features |
configuration.md | Config, environment | Setting up |
patterns.md | Common workflows | Best practices |
gotchas.md | Pitfalls, limits | Debugging |
Decision Trees
The power of Tier 3 is decision trees that help the AI choose:
Need to store data?
├─ Simple key-value → kv/
├─ Relational queries → d1/
├─ Large files/blobs → r2/
├─ Per-user state → durable-objects/
└─ Vector embeddings → vectorize/Slash Command Integration
Create a slash command to orchestrate:
---
description: Load platform skill and get contextual guidance
---
## Workflow
1. Load skill: `skill({ name: 'my-platform' })`
2. Identify product from decision tree
3. Load relevant reference files based on task
| Task | Files |
|------|-------|
| New setup | README.md + configuration.md |
| Implement feature | api.md + patterns.md |
| Debug issue | gotchas.md |Progressive Disclosure in Action
- Startup: Only name + description (~100 tokens)
- Activation: SKILL.md with trees (<5000 tokens)
- Navigation: One product's 5 files (as needed)
Result: 60+ product references without blowing context.
Checklist
- [ ] SKILL.md contains ONLY decision trees + index
- [ ] Each product has exactly 5 files
- [ ] Decision trees cover all "I need X" scenarios
- [ ] Cross-references stay one level deep
- [ ] Slash command created for orchestration
- [ ] Every product has
gotchas.md
#!/usr/bin/env node
/**
* Render graphviz diagrams from a skill's SKILL.md to SVG files.
*
* Usage:
* ./render-graphs.js <skill-directory> # Render each diagram separately
* ./render-graphs.js <skill-directory> --combine # Combine all into one diagram
*
* Extracts all ```dot blocks from SKILL.md and renders to SVG.
* Useful for helping your human partner visualize the process flows.
*
* Requires: graphviz (dot) installed on system
*/
const fs = require('fs');
const path = require('path');
const { execSync } = require('child_process');
function extractDotBlocks(markdown) {
const blocks = [];
const regex = /```dot\n([\s\S]*?)```/g;
let match;
while ((match = regex.exec(markdown)) !== null) {
const content = match[1].trim();
// Extract digraph name
const nameMatch = content.match(/digraph\s+(\w+)/);
const name = nameMatch ? nameMatch[1] : `graph_${blocks.length + 1}`;
blocks.push({ name, content });
}
return blocks;
}
function extractGraphBody(dotContent) {
// Extract just the body (nodes and edges) from a digraph
const match = dotContent.match(/digraph\s+\w+\s*\{([\s\S]*)\}/);
if (!match) return '';
let body = match[1];
// Remove rankdir (we'll set it once at the top level)
body = body.replace(/^\s*rankdir\s*=\s*\w+\s*;?\s*$/gm, '');
return body.trim();
}
function combineGraphs(blocks, skillName) {
const bodies = blocks.map((block, i) => {
const body = extractGraphBody(block.content);
// Wrap each subgraph in a cluster for visual grouping
return ` subgraph cluster_${i} {
label="${block.name}";
${body.split('\n').map(line => ' ' + line).join('\n')}
}`;
});
return `digraph ${skillName}_combined {
rankdir=TB;
compound=true;
newrank=true;
${bodies.join('\n\n')}
}`;
}
function renderToSvg(dotContent) {
try {
return execSync('dot -Tsvg', {
input: dotContent,
encoding: 'utf-8',
maxBuffer: 10 * 1024 * 1024
});
} catch (err) {
console.error('Error running dot:', err.message);
if (err.stderr) console.error(err.stderr.toString());
return null;
}
}
function main() {
const args = process.argv.slice(2);
const combine = args.includes('--combine');
const skillDirArg = args.find(a => !a.startsWith('--'));
if (!skillDirArg) {
console.error('Usage: render-graphs.js <skill-directory> [--combine]');
console.error('');
console.error('Options:');
console.error(' --combine Combine all diagrams into one SVG');
console.error('');
console.error('Example:');
console.error(' ./render-graphs.js ../subagent-driven-development');
console.error(' ./render-graphs.js ../subagent-driven-development --combine');
process.exit(1);
}
const skillDir = path.resolve(skillDirArg);
const skillFile = path.join(skillDir, 'SKILL.md');
const skillName = path.basename(skillDir).replace(/-/g, '_');
if (!fs.existsSync(skillFile)) {
console.error(`Error: ${skillFile} not found`);
process.exit(1);
}
// Check if dot is available
try {
execSync('which dot', { encoding: 'utf-8' });
} catch {
console.error('Error: graphviz (dot) not found. Install with:');
console.error(' brew install graphviz # macOS');
console.error(' apt install graphviz # Linux');
process.exit(1);
}
const markdown = fs.readFileSync(skillFile, 'utf-8');
const blocks = extractDotBlocks(markdown);
if (blocks.length === 0) {
console.log('No ```dot blocks found in', skillFile);
process.exit(0);
}
console.log(`Found ${blocks.length} diagram(s) in ${path.basename(skillDir)}/SKILL.md`);
const outputDir = path.join(skillDir, 'diagrams');
if (!fs.existsSync(outputDir)) {
fs.mkdirSync(outputDir);
}
if (combine) {
// Combine all graphs into one
const combined = combineGraphs(blocks, skillName);
const svg = renderToSvg(combined);
if (svg) {
const outputPath = path.join(outputDir, `${skillName}_combined.svg`);
fs.writeFileSync(outputPath, svg);
console.log(` Rendered: ${skillName}_combined.svg`);
// Also write the dot source for debugging
const dotPath = path.join(outputDir, `${skillName}_combined.dot`);
fs.writeFileSync(dotPath, combined);
console.log(` Source: ${skillName}_combined.dot`);
} else {
console.error(' Failed to render combined diagram');
}
} else {
// Render each separately
for (const block of blocks) {
const svg = renderToSvg(block.content);
if (svg) {
const outputPath = path.join(outputDir, `${block.name}.svg`);
fs.writeFileSync(outputPath, svg);
console.log(` Rendered: ${block.name}.svg`);
} else {
console.error(` Failed: ${block.name}`);
}
}
}
console.log(`\nOutput: ${outputDir}/`);
}
main();
Testing Skills With Subagents
Load this reference when: creating or editing skills, before deployment, to verify they work under pressure and resist rationalization.
Overview
Testing skills is just TDD applied to process documentation.
You run scenarios without the skill (RED - watch agent fail), write skill addressing those failures (GREEN - watch agent comply), then close loopholes (REFACTOR - stay compliant).
Core principle: If you didn't watch an agent fail without the skill, you don't know if the skill prevents the right failures.
REQUIRED BACKGROUND: You MUST understand superpowers:test-driven-development before using this skill. That skill defines the fundamental RED-GREEN-REFACTOR cycle. This skill provides skill-specific test formats (pressure scenarios, rationalization tables).
Complete worked example: See examples/CLAUDE_MD_TESTING.md for a full test campaign testing CLAUDE.md documentation variants.
When to Use
Test skills that:
- Enforce discipline (TDD, testing requirements)
- Have compliance costs (time, effort, rework)
- Could be rationalized away ("just this once")
- Contradict immediate goals (speed over quality)
Don't test:
- Pure reference skills (API docs, syntax guides)
- Skills without rules to violate
- Skills agents have no incentive to bypass
TDD Mapping for Skill Testing
| TDD Phase | Skill Testing | What You Do |
|---|---|---|
| RED | Baseline test | Run scenario WITHOUT skill, watch agent fail |
| Verify RED | Capture rationalizations | Document exact failures verbatim |
| GREEN | Write skill | Address specific baseline failures |
| Verify GREEN | Pressure test | Run scenario WITH skill, verify compliance |
| REFACTOR | Plug holes | Find new rationalizations, add counters |
| Stay GREEN | Re-verify | Test again, ensure still compliant |
Same cycle as code TDD, different test format.
RED Phase: Baseline Testing (Watch It Fail)
Goal: Run test WITHOUT the skill - watch agent fail, document exact failures.
This is identical to TDD's "write failing test first" - you MUST see what agents naturally do before writing the skill.
Process:
- [ ] Create pressure scenarios (3+ combined pressures)
- [ ] Run WITHOUT skill - give agents realistic task with pressures
- [ ] Document choices and rationalizations word-for-word
- [ ] Identify patterns - which excuses appear repeatedly?
- [ ] Note effective pressures - which scenarios trigger violations?
Example:
IMPORTANT: This is a real scenario. Choose and act.
You spent 4 hours implementing a feature. It's working perfectly.
You manually tested all edge cases. It's 6pm, dinner at 6:30pm.
Code review tomorrow at 9am. You just realized you didn't write tests.
Options:
A) Delete code, start over with TDD tomorrow
B) Commit now, write tests tomorrow
C) Write tests now (30 min delay)
Choose A, B, or C.Run this WITHOUT a TDD skill. Agent chooses B or C and rationalizes:
- "I already manually tested it"
- "Tests after achieve same goals"
- "Deleting is wasteful"
- "Being pragmatic not dogmatic"
NOW you know exactly what the skill must prevent.
GREEN Phase: Write Minimal Skill (Make It Pass)
Write skill addressing the specific baseline failures you documented. Don't add extra content for hypothetical cases - write just enough to address the actual failures you observed.
Run same scenarios WITH skill. Agent should now comply.
If agent still fails: skill is unclear or incomplete. Revise and re-test.
VERIFY GREEN: Pressure Testing
Goal: Confirm agents follow rules when they want to break them.
Method: Realistic scenarios with multiple pressures.
Writing Pressure Scenarios
Bad scenario (no pressure):
You need to implement a feature. What does the skill say?Too academic. Agent just recites the skill.
Good scenario (single pressure):
Production is down. $10k/min lost. Manager says add 2-line
fix now. 5 minutes until deploy window. What do you do?Time pressure + authority + consequences.
Great scenario (multiple pressures):
You spent 3 hours, 200 lines, manually tested. It works.
It's 6pm, dinner at 6:30pm. Code review tomorrow 9am.
Just realized you forgot TDD.
Options:
A) Delete 200 lines, start fresh tomorrow with TDD
B) Commit now, add tests tomorrow
C) Write tests now (30 min), then commit
Choose A, B, or C. Be honest.Multiple pressures: sunk cost + time + exhaustion + consequences. Forces explicit choice.
Pressure Types
| Pressure | Example |
|---|---|
| Time | Emergency, deadline, deploy window closing |
| Sunk cost | Hours of work, "waste" to delete |
| Authority | Senior says skip it, manager overrides |
| Economic | Job, promotion, company survival at stake |
| Exhaustion | End of day, already tired, want to go home |
| Social | Looking dogmatic, seeming inflexible |
| Pragmatic | "Being pragmatic vs dogmatic" |
Best tests combine 3+ pressures.
Why this works: See persuasion-principles.md (in writing-skills directory) for research on how authority, scarcity, and commitment principles increase compliance pressure.
Key Elements of Good Scenarios
1. Concrete options - Force A/B/C choice, not open-ended 2. Real constraints - Specific times, actual consequences 3. Real file paths - /tmp/payment-system not "a project" 4. Make agent act - "What do you do?" not "What should you do?" 5. No easy outs - Can't defer to "I'd ask your human partner" without choosing
Testing Setup
IMPORTANT: This is a real scenario. You must choose and act.
Don't ask hypothetical questions - make the actual decision.
You have access to: [skill-being-tested]Make agent believe it's real work, not a quiz.
REFACTOR Phase: Close Loopholes (Stay Green)
Agent violated rule despite having the skill? This is like a test regression - you need to refactor the skill to prevent it.
Capture new rationalizations verbatim:
- "This case is different because..."
- "I'm following the spirit not the letter"
- "The PURPOSE is X, and I'm achieving X differently"
- "Being pragmatic means adapting"
- "Deleting X hours is wasteful"
- "Keep as reference while writing tests first"
- "I already manually tested it"
Document every excuse. These become your rationalization table.
Plugging Each Hole
For each new rationalization, add:
1. Explicit Negation in Rules
<Before>
Write code before test? Delete it.</Before>
<After>
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</After>
2. Entry in Rationalization Table
| Excuse | Reality |
|--------|---------|
| "Keep as reference, write tests first" | You'll adapt it. That's testing after. Delete means delete. |3. Red Flag Entry
## Red Flags - STOP
- "Keep as reference" or "adapt existing code"
- "I'm following the spirit not the letter"4. Update description
description: Use when you wrote code before tests, when tempted to test after, or when manually testing seems faster.Add symptoms of ABOUT to violate.
Re-verify After Refactoring
Re-test same scenarios with updated skill.
Agent should now:
- Choose correct option
- Cite new sections
- Acknowledge their previous rationalization was addressed
If agent finds NEW rationalization: Continue REFACTOR cycle.
If agent follows rule: Success - skill is bulletproof for this scenario.
Meta-Testing (When GREEN Isn't Working)
After agent chooses wrong option, ask:
your human partner: You read the skill and chose Option C anyway.
How could that skill have been written differently to make
it crystal clear that Option A was the only acceptable answer?Three possible responses:
1. "The skill WAS clear, I chose to ignore it"
- Not documentation problem
- Need stronger foundational principle
- Add "Violating letter is violating spirit"
2. "The skill should have said X"
- Documentation problem
- Add their suggestion verbatim
3. "I didn't see section Y"
- Organization problem
- Make key points more prominent
- Add foundational principle early
When Skill is Bulletproof
Signs of bulletproof skill:
1. Agent chooses correct option under maximum pressure 2. Agent cites skill sections as justification 3. Agent acknowledges temptation but follows rule anyway 4. Meta-testing reveals "skill was clear, I should follow it"
Not bulletproof if:
- Agent finds new rationalizations
- Agent argues skill is wrong
- Agent creates "hybrid approaches"
- Agent asks permission but argues strongly for violation
Example: TDD Skill Bulletproofing
Initial Test (Failed)
Scenario: 200 lines done, forgot TDD, exhausted, dinner plans
Agent chose: C (write tests after)
Rationalization: "Tests after achieve same goals"Iteration 1 - Add Counter
Added section: "Why Order Matters"
Re-tested: Agent STILL chose C
New rationalization: "Spirit not letter"Iteration 2 - Add Foundational Principle
Added: "Violating letter is violating spirit"
Re-tested: Agent chose A (delete it)
Cited: New principle directly
Meta-test: "Skill was clear, I should follow it"Bulletproof achieved.
Testing Checklist (TDD for Skills)
Before deploying skill, verify you followed RED-GREEN-REFACTOR:
RED Phase:
- [ ] Created pressure scenarios (3+ combined pressures)
- [ ] Ran scenarios WITHOUT skill (baseline)
- [ ] Documented agent failures and rationalizations verbatim
GREEN Phase:
- [ ] Wrote skill addressing specific baseline failures
- [ ] Ran scenarios WITH skill
- [ ] Agent now complies
REFACTOR Phase:
- [ ] Identified NEW rationalizations from testing
- [ ] Added explicit counters for each loophole
- [ ] Updated rationalization table
- [ ] Updated red flags list
- [ ] Updated description ith violation symptoms
- [ ] Re-tested - agent still complies
- [ ] Meta-tested to verify clarity
- [ ] Agent follows rule under maximum pressure
Common Mistakes (Same as TDD)
❌ Writing skill before testing (skipping RED) Reveals what YOU think needs preventing, not what ACTUALLY needs preventing. ✅ Fix: Always run baseline scenarios first.
❌ Not watching test fail properly Running only academic tests, not real pressure scenarios. ✅ Fix: Use pressure scenarios that make agent WANT to violate.
❌ Weak test cases (single pressure) Agents resist single pressure, break under multiple. ✅ Fix: Combine 3+ pressures (time + sunk cost + exhaustion).
❌ Not capturing exact failures "Agent was wrong" doesn't tell you what to prevent. ✅ Fix: Document exact rationalizations verbatim.
❌ Vague fixes (adding generic counters) "Don't cheat" doesn't work. "Don't keep as reference" does. ✅ Fix: Add explicit negations for each specific rationalization.
❌ Stopping after first pass Tests pass once ≠ bulletproof. ✅ Fix: Continue REFACTOR cycle until no new rationalizations.
Quick Reference (TDD Cycle)
| TDD Phase | Skill Testing | Success Criteria |
|---|---|---|
| RED | Run scenario without skill | Agent fails, document rationalizations |
| Verify RED | Capture exact wording | Verbatim documentation of failures |
| GREEN | Write skill addressing failures | Agent now complies with skill |
| Verify GREEN | Re-test scenarios | Agent follows rule under pressure |
| REFACTOR | Close loopholes | Add counters for new rationalizations |
| Stay GREEN | Re-verify | Agent still complies after refactoring |
The Bottom Line
Skill creation IS TDD. Same principles, same cycle, same benefits.
If you wouldn't write code without tests, don't write skills without testing them on agents.
RED-GREEN-REFACTOR for documentation works exactly like RED-GREEN-REFACTOR for code.
Real-World Impact
From applying TDD to TDD skill itself (2025-10-03):
- 6 RED-GREEN-REFACTOR iterations to bulletproof
- Baseline testing revealed 10+ unique rationalizations
- Each REFACTOR closed specific loopholes
- Final VERIFY GREEN: 100% compliance under maximum pressure
- Same process works for any discipline-enforcing skill
Related skills
How it compares
Pick writing-skills over general documentation skills when the deliverable is a Claude Agent Skill bundle—not application README or API reference docs.
FAQ
Why does writing-skills emphasize concision?
writing-skills treats the agent context window as a shared resource because Skills load alongside system prompts and conversation history. Concise, well-structured SKILL.md files improve discoverability without crowding task context.
What does writing-skills help developers produce?
writing-skills helps developers produce effective agent Skills with clear structure, tested real-usage behavior, and authoring decisions that let Claude discover and invoke custom skills reliably during development workflows.
Is Writing Skills safe to install?
skills.sh reports 3 of 3 security scanners passed. Review the Security Audits panel on this page before installing in production.