
Skill Architect
- 137 installs
- 178 repo stars
- Updated July 14, 2026
- erichowens/some_claude_skills
Design robust Claude Code skills with clear triggers, progressive disclosure, bundled resources, and evaluation criteria so agents behave predictably across diverse user tasks.
About
Architects production-grade agent skills end to end: naming, activation conditions, SKILL.md structure, supporting assets, and maintainability patterns so Claude Code capabilities stay composable, testable, and safe as agent automation grows across projects.
- Trigger and scope definition
- Progressive disclosure layout
- Bundled script and reference design
- Skill composition patterns
- Quality gates for agent behavior
Skill Architect by the numbers
- 137 all-time installs (skills.sh)
- Ranked #3,568 of 16,546 AI & Agent Building skills by installs in the Skillselion catalog
- Data as of Aug 4, 2026 (Skillselion catalog sync)
npx skills add https://github.com/erichowens/some_claude_skills --skill skill-architectAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 137 |
|---|---|
| repo stars | ★ 178 |
| Last updated | July 14, 2026 |
| Repository | erichowens/some_claude_skills ↗ |
What it does
Design robust Claude Code skills with clear triggers, progressive disclosure, bundled resources, and evaluation criteria so agents behave predictably across diverse user tasks.
Files
Skill Architect: The Authoritative Meta-Skill
The unified authority for creating expert-level Agent Skills. Encodes the knowledge that separates a skill that merely exists from one that activates precisely, teaches efficiently, and makes users productive immediately.
Philosophy
Great skills are progressive disclosure machines. They encode real domain expertise (shibboleths), not surface instructions. They follow a three-layer architecture: lightweight metadata for discovery, lean SKILL.md for core process, and reference files for deep dives loaded only on demand.
---
When to Use This Skill
✅ Use for:
- Creating new skills from scratch or from existing expertise
- Auditing/reviewing skills for quality, activation, and progressive disclosure
- Improving activation rates and reducing false positives
- Encoding domain expertise (shibboleths, anti-patterns, temporal knowledge)
- Designing skills that subagents consume effectively
- Building self-contained tools (scripts, MCPs, subagents)
- Debugging why skills don't activate or activate incorrectly
❌ NOT for:
- General Claude Code features (slash commands, MCP server implementation)
- Non-skill coding advice or code review
- Debugging runtime errors (use domain-specific skills)
- Template generation without real domain expertise to encode
---
Quick Wins (Immediate Improvements)
For existing skills, apply in priority order:
1. Tighten description → Follow [What] [When] [Keywords]. NOT for [Exclusions] formula 2. Check line count → SKILL.md must be <500 lines; move depth to /references 3. Add NOT clause → Prevent false activation with explicit exclusions 4. Add 1-2 anti-patterns → Use shibboleth template (Novice/Expert/Timeline) 5. Remove dead files → Delete unreferenced scripts/references (no phantoms) 6. Test activation → Write 5 queries that should trigger and 5 that shouldn't
---
Progressive Disclosure Architecture
Skills use three-layer loading. The runtime scans metadata at startup, loads SKILL.md on activation, and pulls reference files only when the agent decides it needs them.
| Layer | Content | Size | Loading |
|---|---|---|---|
| 1. Metadata | name + description in frontmatter | ~100 tokens | Always in context (catalog scan) |
| 2. SKILL.md | Core process, decision trees, brief anti-patterns | <5k tokens | On skill activation |
| 3. References | Deep dives, examples, templates, specs | Unlimited | On-demand, per-file, only when relevant |
Critical rules:
- Keep SKILL.md under 500 lines. Move depth to
/references. - Reference files are NOT auto-loaded. Only SKILL.md enters context on activation.
- In SKILL.md, list each reference file with a 1-line description of when to consult it. This teaches the agent what's available without loading it.
- Never instruct "read all reference files before starting." Instead: "Read only the files relevant to the current step."
- If a reference file is large, the agent should skim headings first, then drill into the relevant section.
---
Frontmatter Rules
Required Fields
| Key | Purpose | Example |
|---|---|---|
name | Lowercase-hyphenated identifier | react-server-components |
description | Activation trigger: [What] [When] [Keywords]. NOT for [Exclusions] | See Description Formula |
Optional Fields
| Key | Purpose | Example |
|---|---|---|
allowed-tools | Comma-separated tool names (least privilege) | Read,Write,Grep |
argument-hint | Hint shown in autocomplete for expected arguments | "[path] [format]" |
license | License identifier | MIT |
disable-model-invocation | If true, only user-triggered via /skill-name | true |
user-invocable | Controls whether skill appears in UI menus | true |
context | Execution context; fork runs skill in isolated subagent | fork |
agent | Which subagent type when context: fork | code-reviewer |
model | Override model when skill is active | sonnet |
hooks | Hooks scoped to this skill's lifecycle | See hooks reference |
metadata | Arbitrary key-value map for tooling/dashboards | author: your-org |
Custom Keys (Safe to Use)
Custom keys like category, tags, version are ignored by Claude Code but safe to include for your own tooling (gallery websites, documentation generators, dashboards). They don't conflict with runtime parsing.
Invalid Keys (Confusingly Similar to Valid Ones)
# ❌ These look like valid keys but aren't — use the correct alternatives
tools: Read,Write # Use 'allowed-tools' instead
integrates_with: [...] # Use SKILL.md body text instead
triggers: [...] # Use 'description' keywords instead
outputs: [...] # Use SKILL.md Output Format section instead
coordinates_with: [...] # Use SKILL.md body text instead
python_dependencies: [...] # Use SKILL.md body text instead---
Description Formula
Pattern: [What it does] [When to use] [Trigger keywords]. NOT for [Exclusions].
The description is the most important line for activation. Claude's runtime scans descriptions to decide which skill to load. A weak description means zero activations or constant false positives.
| Problem | Bad | Good |
|---|---|---|
| Too vague | "Helps with images" | "CLIP semantic search for image-text matching and zero-shot classification. NOT for counting, spatial reasoning, or generation." |
| No exclusions | "Reviews code changes" | "Reviews TypeScript/React diffs and PRs for correctness. NOT for writing new features." |
| Mini-manual | "Researches, then outlines, then drafts..." | "Structured research producing 1-3 page synthesis reports. NOT for quick factual questions." |
| Catch-all | "Helps with product management" | "Writes and refines product requirement documents (PRDs). NOT for strategy decks." |
| Name mismatch | name: db-migration / desc: "writes marketing emails" | name: db-migration / desc: "Plans database schema migrations with rollback strategies." |
Full guide with more examples: See references/description-guide.md
---
SKILL.md Template
---
name: your-skill-name
description: [What] [When] [Keywords]. NOT for [Exclusions].
allowed-tools: Read,Write
---
# Skill Name
[One sentence purpose]
## When to Use
✅ Use for: [A, B, C with specific trigger keywords]
❌ NOT for: [D, E, F — explicit boundaries]
## Core Process
[Mermaid diagrams — 23 types available. See visual-artifacts.md for full catalog]
## Anti-Patterns
### [Pattern Name]
**Novice**: [Wrong assumption]
**Expert**: [Why it's wrong + correct approach]
**Timeline**: [When this changed, if temporal]
## References
- `references/guide.md` — Consult when [specific situation]
- `references/examples.md` — Consult for [worked examples of X]---
The 6-Step Skill Creation Process
flowchart LR
S1[1. Gather Examples] --> S2[2. Plan Contents]
S2 --> S3[3. Initialize]
S3 --> S4[4. Write Skill]
S4 --> S5[5. Validate]
S5 --> S6{Errors?}
S6 -->|Yes| S4
S6 -->|No| S7[6. Ship & Iterate]Step 1: Gather Concrete Examples
Collect 3-5 real queries that should trigger this skill, and 3-5 that should NOT.
Step 2: Plan Reusable Contents
For each example, identify what scripts, references, or assets would prevent re-work. Also identify shibboleths: domain algorithms, temporal knowledge, framework evolution, common pitfalls.
Step 3: Initialize
scripts/init_skill.py <skill-name> --path <output-directory>For existing skills, skip to Step 4.
Step 4: Write the Skill
Order of implementation: 1. Scripts first (scripts/) — Working code, not templates 2. References next (references/) — Domain knowledge, schemas, guides 3. SKILL.md last — Core process, anti-patterns, reference index
Write in imperative form: "To accomplish X, do Y" not "You should do X."
Answer these questions in SKILL.md: 1. Purpose: What is this skill for? (1-2 sentences) 2. Activation: What triggers it? What shouldn't? 3. Process: Use Mermaid diagrams (23 types) — flowcharts for decisions, sequence for protocols, state for lifecycles, etc. 4. Anti-patterns: What do novices get wrong? 5. Visual artifacts: Render workflows, architectures, timelines as Mermaid diagrams (see references/visual-artifacts.md) 6. References: What files exist and when to consult them?
Step 5: Validate
python scripts/validate_skill.py <path>
python scripts/check_self_contained.py <path>Fix ERRORS → WARNINGS → SUGGESTIONS.
Step 6: Iterate
After real-world use: notice struggles, improve SKILL.md and resources, update CHANGELOG.md.
---
Designing Skills for Subagent Consumption
When skills will be loaded by subagents (not just direct user invocation), apply these patterns:
Three Skill-Loading Layers
1. Preloaded (2-5 core skills): Injected into the subagent's system context. These are its standard operating procedures — always present. 2. Dynamically selected: Subagent receives a catalog (name + 1-line description) and picks 1-3 matching skills before starting. The orchestrator can also pre-filter. 3. Execution-time: Subagent reads each skill's "When to use" section, follows numbered steps in order, respects output contracts, and runs QA checks.
How Subagents Should Use Skills
Teach the subagent to treat each skill like a mini-protocol:
- Check the "When to use / When not to use" section for applicability
- Follow numbered steps in order (adapt only if task constraints force it)
- Respect the skill's output contract (templates, JSON shapes, required sections)
- Apply QA/validation steps last
- Reference skill steps by number: "Completed step 3 of refactor-plan-skill"
Subagent Prompt Structure
The subagent's prompt should have four sections: 1. Identity: "You are the [role]. You handle [narrow domain]. If outside scope, say so." 2. Skill usage rules: "Your skills define your methods. Decide which apply, follow their workflows." 3. Task loop: Restate → Select skills → Clarify → Plan → Execute step-by-step → Validate → Return (artifacts + skills used + remaining risks). 4. Constraints: Quality bar, safety rules, tie-breaking priorities.
Full templates and orchestration patterns: See references/subagent-design.md
---
Visual Artifacts: Mermaid Diagrams & Code
Skills that include Mermaid diagrams serve two audiences at once. For humans, diagrams render as visual flowcharts, state machines, and timelines — instantly parseable. For agents, Mermaid is a text-based graph DSL — A -->|Yes| B is an explicit, unambiguous edge that's actually easier to reason about than equivalent prose. The agent reads the text; the human sees the picture. Both win.
Rule: If a skill describes a process, decision tree, architecture, state machine, timeline, or data relationship, include a Mermaid diagram. Use raw `mermaid blocks directly in SKILL.md — not wrapped in outer markdown fences.
All 23 Mermaid Diagram Types
Mermaid supports 23 diagram types. Use the most specific one for your content — a state diagram for lifecycles is better than a flowchart with "go back" arrows.
| Skill Content | Diagram Type | Syntax |
|---|---|---|
| Decision trees / troubleshooting | Flowchart | flowchart TD |
| API/agent communication protocols | Sequence | sequenceDiagram |
| Lifecycle / status transitions | State | stateDiagram-v2 |
| Data models / schemas | ER | erDiagram |
| Type hierarchies / interfaces | Class | classDiagram |
| Temporal knowledge / evolution | Timeline | timeline |
| Domain taxonomy / concept maps | Mindmap | mindmap |
| Priority matrices (2-axis) | Quadrant | quadrantChart |
| Component layout / blocks | Block | block-beta |
| Infrastructure / cloud topology | Architecture | architecture-beta |
| Multi-level system views (C4) | C4 | C4Context / C4Container / C4Component |
| Project phases / rollout plans | Gantt | gantt |
| Git branching / release strategy | Git Graph | gitGraph |
| User experience flows | Journey | journey |
| Quantity flows / budgets | Sankey | sankey-beta |
| Metrics / benchmarks | XY Chart | xychart-beta |
| Proportional breakdowns | Pie | pie |
| Hierarchical size comparison | Treemap | treemap |
| Multi-axis capability comparison | Radar | radar |
| Task/status tracking | Kanban | kanban |
| Requirements traceability | Requirement | requirementDiagram |
| Network protocols / binary formats | Packet | packet-beta |
| Sequence diagrams (code syntax) | ZenUML | zenuml (plugin) |
YAML Frontmatter in Mermaid (Optional)
Mermaid supports an optional --- frontmatter block for rendering customization (themes, colors, spacing). It is not required. Agents ignore it. Renderers apply sensible defaults without it. Only add it when you need specific visual styling for published documentation.
# Optional — only for render customization
---
title: My Diagram
config:
theme: neutral
flowchart:
curve: basis
---Themes: default, dark, forest, neutral, base. Full config reference: https://mermaid.ai/open-source/config/configuration.html
Full diagram catalog with examples of all 16+ types: See references/visual-artifacts.md
---
Encoding Shibboleths
Expert knowledge that separates novices from experts. Things LLMs get wrong due to outdated training data or cargo-culted patterns.
Shibboleth Template
### Anti-Pattern: [Name]
**Novice**: "[Wrong assumption]"
**Expert**: [Why it's wrong, with evidence]
**Timeline**: [Date]: [Old way] → [Date]: [New way]
**LLM mistake**: [Why LLMs suggest the old pattern]
**Detection**: [How to spot this in code/config]What to Encode
- Framework evolution (React Classes → Hooks → Server Components)
- Model limitations (CLIP can't count; embedding models are task-specific)
- Tool architecture (Script → MCP graduation path)
- API versioning (ada-002 → text-embedding-3-large)
- Temporal traps (advice that was correct in 2023 but harmful in 2025)
Full catalog with case studies: See references/antipatterns.md
---
Self-Contained Tools and the Extension Taxonomy
Skills are one of seven Claude extension types: Skills (domain knowledge), Plugins (packaged bundles for distribution), MCP Servers (external APIs + auth), Scripts (local operations), Slash Commands (user-triggered skills), Hooks (lifecycle automation at 17+ event points), and Agent SDK (programmatic Claude Code access). Most skills should include scripts. MCPs are only for auth/state boundaries. Plugins are for sharing skills across teams/community.
| Need | Extension Type | Key Requirement |
|---|---|---|
| Domain expertise / process | Skill (SKILL.md) | Decision trees, anti-patterns, output contracts |
| Packaging & distribution | Plugin (plugin.json) | Bundles skills + hooks + MCP + agents |
| External API + auth | MCP Server | Working server + setup README |
| Repeatable local operation | Script | Actually runs (not a template), minimal deps |
| Multi-step orchestration | Subagent | 4-section prompt, skills, workflow |
| User-triggered action | Slash Command | Skill with user-invocable: true |
| Lifecycle automation | Hook | 17+ events: PreToolUse, PostToolUse, Stop, etc. |
| Programmatic access | Agent SDK | npm/pip package, CI/CD pipelines |
Evolution path: Skill → Skill + Scripts → Skill + MCP Server → Skill + Subagent → Plugin (for distribution). Only promote when complexity justifies it.
Full taxonomy with examples and common mistakes: See references/claude-extension-taxonomy.md Detailed tool patterns: See references/self-contained-tools.md Plugin creation and distribution: See references/plugin-architecture.md
---
Tool Permissions
Principle: Least privilege — only grant what's needed.
| Access Level | allowed-tools |
|---|---|
| Read-only | Read,Grep,Glob |
| File modifier | Read,Write,Edit |
| Build integration | Read,Write,Bash(npm:*,git:*) |
| ⚠️ Never for untrusted | Unrestricted Bash |
---
Anti-Pattern Summary
| # | Anti-Pattern | Fix |
|---|---|---|
| 1 | Documentation Dump | Decision trees in SKILL.md, depth in /references |
| 2 | Missing NOT clause | Always include "NOT for X, Y, Z" in description |
| 3 | Phantom Tools | Only reference files that exist and work |
| 4 | Template Soup | Ship working code or nothing |
| 5 | Overly Permissive Tools | Least privilege: specific tool list, scoped Bash |
| 6 | Stale Temporal Knowledge | Date all advice, update quarterly |
| 7 | Catch-All Skill | Split by expertise type, not domain |
| 8 | Vague Description | Use [What] [When] [Keywords]. NOT for [Exclusions] |
| 9 | Eager Loading | Never "read all files first"; lazy-load references |
| 10 | Prose-Only Processes | Use Mermaid diagrams (23 types) — flowcharts, sequences, states, ER, timelines, etc. |
Full case studies: See references/antipatterns.md
---
Validation Checklist
□ SKILL.md exists and is <500 lines
□ Frontmatter has name + description (minimum required)
□ Description follows [What][When][Keywords] NOT [Exclusions] formula
□ Description uses keywords users would actually type
□ Name and description are aligned (not contradictory)
□ At least 1 anti-pattern with shibboleth template
□ All referenced files actually exist (no phantoms)
□ Scripts work (not templates), have clear CLI, handle errors
□ Reference files each have a 1-line purpose in SKILL.md
□ Processes/decisions/lifecycles use Mermaid diagrams (23 types), not prose
□ CHANGELOG.md tracks version history
□ If subagent-consumed: output contracts are definedRun automated checks: python scripts/validate_skill.py <path> and python scripts/validate_mermaid.py <path>
---
Common Rejection Causes
Things that make Claude Code reject or mishandle skills at load time:
| Cause | Symptom | Fix |
|---|---|---|
Missing name or description | Skill won't load | Add both to frontmatter |
tools: instead of allowed-tools: | Tools silently ignored | Use allowed-tools: (hyphenated) |
YAML list in allowed-tools | Parse error | Use comma-separated: Read,Write,Edit |
Brackets in allowed-tools | Parse error | No [ ] — just Read,Write,Edit |
Invalid keys (triggers, outputs) | Silently ignored or error | Move to SKILL.md body text |
| Name with spaces/uppercase | May fail matching | Lowercase-hyphenated: my-skill-name |
| Name doesn't match directory | Activation mismatch | Keep name = directory name |
context: not fork | Ignored | Only valid value is fork |
disable-model-invocation: not boolean | Ignored | Use true or false |
| Phantom file references | Agent wastes tool calls | Delete references or create files |
Full validation: python scripts/validate_skill.py <path> catches all of these.
---
Success Metrics
| Metric | Target | How to Measure |
|---|---|---|
| Correct activation | >90% | Test queries that should trigger |
| False positive rate | <5% | Test queries that shouldn't trigger |
| Token usage | <5k | SKILL.md size + typical reference loads |
| Time to productive | <5 min | User starts working immediately |
| Anti-pattern prevention | >80% | Users avoid documented mistakes |
---
Reference Files
Consult these for deep dives — they are NOT loaded by default:
| File | Consult When |
|---|---|
references/knowledge-engineering.md | KE methods for extracting expert knowledge into skills; protocol analysis, repertory grids, aha! moments |
references/description-guide.md | Writing or rewriting a skill description |
references/antipatterns.md | Looking for shibboleths, case studies, or temporal patterns |
references/self-contained-tools.md | Adding scripts, MCP servers, or subagents to a skill |
references/subagent-design.md | Designing skills for subagent consumption or orchestration |
references/claude-extension-taxonomy.md | Skills vs Plugins vs MCPs vs Hooks vs Agent SDK — the 7-type taxonomy |
references/plugin-architecture.md | Creating, packaging, and distributing plugins via marketplaces |
references/visual-artifacts.md | Adding Mermaid diagrams: all 23 types, YAML config, best practices |
references/mcp-template.md | Building an MCP server for a skill |
references/subagent-template.md | Defining subagent prompts and multi-agent pipelines |
scripts/validate_mermaid.py | Validates Mermaid syntax in any file — checks diagram types, balanced blocks, structural correctness |
Changelog: skill-architect
v2.1.1 (2026-02-05)
Clarifications
Agent parseability — Clarified that Mermaid works for both agents AND humans. Agents read Mermaid as a text-based graph DSL with explicit edge semantics (A -->|Yes| B); they don't need rendered pictures. Added "Can Agents Actually Interpret Mermaid?" section to references/visual-artifacts.md explaining why formal graph notation is actually more precise for agents than equivalent prose.
YAML frontmatter is optional — Demoted YAML frontmatter from "here's how to configure" to "this is purely for rendering customization; agents ignore it; skip it unless publishing polished docs." Updated both SKILL.md and references/visual-artifacts.md.
Raw vs. quoted Mermaid — Added guidance: use raw `mermaid blocks in SKILL.md (operative content the agent interprets). Only use outer ``markdown fences in docs about Mermaid (illustrative examples). Added SKILL.md's own 6-step process as a raw Mermaid flowchart — eating our own cooking.
---
v2.1.0 (2026-02-05)
Visual Artifacts
New section in SKILL.md: "Visual Artifacts: Mermaid Diagrams & Code" — encourages skills to render decision trees, workflows, architectures, timelines, and data models as Mermaid diagrams. Includes quick-reference table mapping content types to diagram types.
New reference: references/visual-artifacts.md — comprehensive guide to all 16+ Mermaid diagram types with:
- "Can Agents Interpret Mermaid?" section (yes — it's a text DSL with explicit graph structure)
- Raw vs. quoted Mermaid guidance
- Full YAML frontmatter configuration (optional — for rendering only)
- Concrete examples for every diagram type: flowchart, sequence, state, ER, gantt, mindmap, timeline, pie, quadrant, gitgraph, class, user journey, sankey, XY chart, block, architecture, kanban
- Node shapes, edge styles, and features for each diagram type
- Decision matrix: which diagram type for which skill content
- Best practices for Mermaid in progressive-disclosure skills
Anti-pattern #10: "Prose-Only Processes" — if a skill describes a decision tree or workflow in paragraph form when it could be a Mermaid diagram, that's an improvement opportunity.
Updated validation checklist: Now includes "Decision trees/workflows use Mermaid diagrams, not prose."
Updated Step 4: Skill creation now explicitly calls out visual artifacts and Mermaid as part of the writing process.
---
v2.0.0 (2026-02-05)
Major Improvements
SKILL.md rewrite — Reduced from 637 lines to 350 lines (was violating its own <500 line rule). Restructured for clarity and actionability.
Description Formula — Expanded with concrete bad→good examples covering 7 common failure modes: too vague, overlapping, mini-manual, missing exclusions, wrong keywords, name mismatch, catch-all. Full guide moved to references/description-guide.md.
Frontmatter Documentation — Added newly documented optional fields: argument-hint, disable-model-invocation, user-invocable, context (fork), and metadata. Previous version was incomplete about what's valid.
Subagent-Aware Skill Design — New section covering how to design skills that subagents consume effectively: three loading layers (preloaded, dynamic, execution-time), subagent prompt structure (identity, skill rules, task loop, constraints), and orchestrator patterns (single-specialist, chain, parallel).
Progressive Disclosure — Enhanced with specific lazy-loading rules: reference files are NOT auto-loaded, teach agents to load on-demand per-step, never instruct "read all files first."
Anti-Pattern #9 — Added "Eager Loading" to the anti-pattern catalog.
New Reference Files
references/description-guide.md— Comprehensive guide to writing skill descriptions with bad→good examples, keyword strategy, length guidelines, and testing checklistreferences/subagent-design.md— Full guide to designing skills for subagent consumption, including three loading layers, subagent prompt structure, orchestrator patterns, input/output contracts, and lazy-loading best practices
Updated Reference Files
references/subagent-template.md— Added four-section prompt structure (Identity, Skill Usage Rules, Task-Handling Loop, Constraints), YAML config with skill references, and skill-aware example patterns
Removed (Deduplicated)
- Case studies removed from SKILL.md (were already duplicated in
references/antipatterns.md) - Verbose code examples moved to reference files where they belong
- Redundant script example removed (already in
references/self-contained-tools.md)
Philosophy Update
From "progressive disclosure machines" to "progressive disclosure machines with lazy-loaded references" — emphasizing that reference files are only loaded when the agent decides they're relevant to the current step, not eagerly.
---
v1.0.0 (2026-01-14)
Created
- Unified meta-skill combining skill-coach and skill-creator
- Merged systematic workflow from skill-creator
- Merged domain expertise encoding from skill-coach
- Consolidated best practices from both skills
Features
- 6-step skill creation process
- Shibboleth encoding (expert knowledge patterns)
- Anti-pattern catalog with case studies
- Self-contained tool implementation (scripts, MCP, subagents)
- Progressive disclosure design principles
- Activation debugging workflows
- Comprehensive validation checklists
References Added
antipatterns.md- Shibboleths and anti-pattern catalogself-contained-tools.md- Scripts, MCP, and subagent patternsmcp-template.md- Minimal MCP server startersubagent-template.md- Agent definition format
Philosophy
"Great skills are progressive disclosure machines that encode real domain expertise, not just surface instructions."
Replaces
- skill-coach (v2.x) - Expertise encoding focus
- skill-creator (v1.x) - Systematic workflow focus
Migration
Users of skill-coach or skill-creator should switch to skill-architect for the unified experience.
Skill Architect
The authoritative meta-skill for creating, auditing, and improving Agent Skills.
What It Does
Skill Architect is a meta-skill that teaches Claude how to build other skills well. It combines:
- Systematic workflow (6-step creation process)
- Domain expertise encoding (shibboleths, anti-patterns, temporal knowledge)
- Progressive disclosure architecture (three-layer loading with lazy references)
- Subagent-aware design (skills that work well when consumed by subagents)
Quick Start
Creating a new skill: 1. Gather 3-5 concrete example queries (what should/shouldn't trigger) 2. Plan reusable contents (scripts, references, assets) 3. Initialize: scripts/init_skill.py <skill-name> 4. Write scripts first, references next, SKILL.md last 5. Validate: scripts/validate_skill.py <path> 6. Iterate based on real-world use
Improving an existing skill: 1. Tighten description: [What] [When] [Keywords]. NOT for [Exclusions] 2. Check line count (<500 lines in SKILL.md) 3. Add anti-patterns with shibboleth template 4. Remove phantom references (files that don't exist) 5. Test activation with 5 should-trigger + 5 shouldn't-trigger queries
Key Concepts
Progressive Disclosure (Three Layers)
| Layer | Content | When Loaded |
|---|---|---|
| 1. Metadata | name + description | Always (catalog scan) |
| 2. SKILL.md | Core process, decision trees | On skill activation |
| 3. References | Deep dives, examples, specs | On-demand, per-file, lazy |
Reference files are NOT auto-loaded. The agent reads them only when relevant to the current step.
Description Formula
[What it does] [When to use] [Trigger keywords]. NOT for [Exclusions].
The description is the single most important line for activation. See references/description-guide.md for 7 bad→good examples.
Frontmatter Fields
Required: name, description
Optional: allowed-tools, argument-hint, license, disable-model-invocation, user-invocable, context, metadata
Visual Artifacts
Skills should render processes, decision trees, architectures, and temporal knowledge as Mermaid diagrams instead of prose. Mermaid is text-based, version-controllable, and renders natively in GitHub, Docusaurus, and Claude's output.
16+ diagram types are available: flowchart, sequence, state, ER, timeline, mindmap, quadrant, gantt, gitgraph, class, user journey, sankey, XY chart, block, architecture, kanban, pie.
See references/visual-artifacts.md for the full catalog with examples and YAML configuration.
Subagent-Aware Design
Skills consumed by subagents should have:
- Explicit "When to Use / NOT" sections
- Numbered steps (not prose)
- Output contracts (JSON schema or markdown template)
- QA/validation checklists
See references/subagent-design.md for full patterns.
Shibboleths
Expert knowledge that separates novices from experts:
- Framework evolution (React: Classes → Hooks → Server Components)
- Model limitations (CLIP can't count objects)
- Tool architecture (Script → MCP graduation path)
- Temporal traps (advice correct in 2023, harmful in 2025)
Structure
skill-architect/
├── SKILL.md # Core instructions (<500 lines)
├── CHANGELOG.md # Version history
├── README.md # This file
└── references/
├── description-guide.md # How to write effective descriptions
├── visual-artifacts.md # Mermaid diagram catalog & configuration
├── antipatterns.md # Shibboleths and case studies
├── self-contained-tools.md # Scripts, MCP, subagent patterns
├── subagent-design.md # Designing skills for subagent consumption
├── mcp-template.md # Minimal MCP server starter
└── subagent-template.md # Agent definition formatAnti-Patterns (Summary)
| # | Anti-Pattern | Fix |
|---|---|---|
| 1 | Documentation Dump | Decision trees in SKILL.md, depth in references |
| 2 | Missing NOT clause | Always include exclusions in description |
| 3 | Phantom Tools | Only reference files that exist and work |
| 4 | Template Soup | Ship working code or nothing |
| 5 | Overly Permissive Tools | Least privilege, scoped Bash |
| 6 | Stale Temporal Knowledge | Date all advice, update quarterly |
| 7 | Catch-All Skill | Split by expertise type |
| 8 | Vague Description | Use the description formula |
| 9 | Eager Loading | Lazy-load references, never "read all first" |
| 10 | Prose-Only Processes | Use Mermaid for decision trees, workflows, architectures |
Success Metrics
| Metric | Target |
|---|---|
| Correct activation | >90% |
| False positive rate | <5% |
| Token usage | <5k |
| Time to productive | <5 min |
Version History
- v2.1.0 (2026-02-05) — Visual artifacts: Mermaid diagram guide, 16+ diagram types, YAML config, anti-pattern #10
- v2.0.0 (2026-02-05) — Major rewrite: description guide, subagent design, frontmatter fields, lazy loading, trimmed to 350 lines
- v1.0.0 (2026-01-14) — Initial unified meta-skill combining skill-coach + skill-creator
Replaces
This skill unifies and replaces:
- skill-coach — Expertise encoding
- skill-creator — Systematic workflow
Skill Anti-Patterns: The Shibboleths
This document catalogs domain-specific knowledge that separates novices from experts - the things LLMs get wrong because their training data includes outdated patterns, oversimplified tutorials, or cargo-culted code.
Table of Contents
1. ML/AI Model Selection 2. Framework Evolution 3. Tool Architecture 4. Skill Design
---
ML/AI Model Selection
Anti-Pattern: CLIP for Everything
Novice thinking: "CLIP is pre-trained on 400M image-text pairs and does zero-shot classification. Use it for all image-text tasks!"
Reality: CLIP has fundamental geometric limitations. Research from 2023-2025 proves it cannot simultaneously handle:
1. Basic descriptions 2. Attribute binding ("red car AND blue truck" vs "blue car AND red truck") 3. Spatial relationships ("cat left of dog" vs "dog left of cat") 4. Negation ("not a cat")
What CLIP fails at:
- ❌ Counting objects in images
- ❌ Fine-grained classification (celebrity ID, car models, flower species)
- ❌ Compositional reasoning
- ❌ Spatial understanding
- ❌ Handwritten text (MNIST-style)
When to use alternatives:
| Task | Use Instead | Why |
|---|---|---|
| Counting objects | DETR, Faster R-CNN | Object detection models built for counting |
| Fine-grained classification | EfficientNet + task head | Transfer learning on specific domain |
| Compositional reasoning | DCSMs, PC-CLIP | Preserve patch/token topology |
| Spatial relationships | GQA models, SWIG | Built for spatial understanding |
| Attribute binding | PC-CLIP (pairwise) | Trained on comparative data |
Timeline:
- 2021: Original CLIP released
- 2022-2023: Limitations discovered in research
- 2024: DCSMs (Dense Cosine Similarity Maps) paper
- 2024: PC-CLIP (Pairwise Comparison CLIP)
- 2025: SpLiCE (Sparse Linear Concept Embeddings)
LLM mistake: LLMs trained on 2021-2023 data will suggest CLIP for everything because limitations weren't widely known yet.
---
Anti-Pattern: Single Embedding Model
Novice thinking: "Pick one embedding model and use it everywhere"
Expert knowledge: Different tasks need different models:
Text embeddings:
- Semantic search:
text-embedding-3-large,voyage-2 - Code search:
voyage-code-2,text-embedding-ada-002 - Multi-lingual:
multilingual-e5-large - Long documents:
jina-embeddings-v2(8k tokens)
Image embeddings:
- General: CLIP ViT-L/14
- Fine-grained: DINOv2
- Medical: BiomedCLIP
- Faces: ArcFace, CosFace
Multi-modal:
- Image-text: CLIP, BLIP-2
- Video: X-CLIP, VideoCLIP
- 3D: ULIP, PointCLIP
Why this matters: Embedding quality directly impacts retrieval accuracy. Using the wrong model can drop accuracy by 20-40%.
---
Anti-Pattern: Ignoring Model Versioning
Problem: "We're using text-embedding-ada-002" (doesn't specify when)
Why wrong: Models evolve:
text-embedding-ada-002(Dec 2022) vstext-embedding-3-small(Jan 2024)- CLIP ViT-B/32 vs ViT-L/14 vs ViT-g-14
- Different training data, different capabilities
Best practice: Pin versions, document when you adopted them:
# embeddings.py
MODEL = "text-embedding-3-large" # Adopted: 2024-03-15
MODEL_DIMENSIONS = 3072
TRAINING_CUTOFF = "2023-09" # Approximate---
Framework Evolution
Anti-Pattern: Pages Router in App Router Projects
Context: Next.js 13 (Oct 2022) introduced App Router, fundamentally changing architecture.
Outdated pattern (Pages Router):
// pages/api/users.js
export default function handler(req, res) {
res.json({ users: [] })
}
// pages/users.js
export async function getServerSideProps() {
return { props: { users: [] } }
}Current pattern (App Router):
// app/api/users/route.js
export async function GET() {
return Response.json({ users: [] })
}
// app/users/page.js
async function UsersPage() {
const users = await fetchUsers() // Server Component
return <UserList users={users} />
}Why it matters: Pages Router patterns don't work in App Router and vice versa.
LLM mistake: Training data from 2020-2023 overwhelmingly shows Pages Router. LLMs will default to old patterns unless specifically prompted.
Timeline:
- 2016-2022: Pages Router only
- Oct 2022: App Router introduced (beta)
- May 2023: App Router stable
- 2024+: App Router is default
---
Anti-Pattern: Redux for Everything
Novice thinking: "Global state needs Redux"
Timeline:
- 2015-2020: Redux dominated
- 2019: Context API improved in React 16.3
- 2020: Zustand, Jotai emerged
- 2023: React Server Components changed the game
Current wisdom:
- Local UI state:
useState,useReducer - Derived state:
useMemo, selectors - Global state (simple): Context API
- Global state (complex): Zustand, Jotai
- Server state: React Query, SWR
- URL state: Next.js searchParams
- Redux: Only if you need time-travel debugging or complex middleware
Why Redux fell out of favor:
- Boilerplate heavy
- Server Components make much state "server-native"
- Simpler alternatives emerged
LLM mistake: LLMs will suggest Redux by default because 80% of training data predates alternatives.
---
Anti-Pattern: Class Components
Timeline:
- 2013-2018: Class components only
- Feb 2019: Hooks introduced (React 16.8)
- 2020+: Functional components are standard
Outdated:
class UserProfile extends React.Component {
state = { user: null }
componentDidMount() {
fetchUser().then(user => this.setState({ user }))
}
render() {
return <div>{this.state.user?.name}</div>
}
}Current:
function UserProfile() {
const [user, setUser] = useState(null)
useEffect(() => {
fetchUser().then(setUser)
}, [])
return <div>{user?.name}</div>
}When class components are still valid:
- Error boundaries (no hook equivalent yet)
- Legacy codebases
LLM mistake: Will generate class components for complex state management
---
Tool Architecture
Anti-Pattern: MCP for Everything
Novice thinking: "MCP is the new standard, make everything an MCP!"
Expert reality: MCPs have overhead. Use them strategically.
Use MCP when:
- ✅ External API with authentication
- ✅ Stateful connections (WebSocket, database)
- ✅ Real-time data streams
- ✅ Security boundaries (credentials, OAuth)
Use Scripts when:
- ✅ Local file operations
- ✅ Batch transformations
- ✅ Stateless computations
- ✅ CLI wrappers
Example - Wrong:
# mcp_server_for_json_parsing.py - OVERKILL!
@mcp.tool()
def parse_json(file_path: str):
with open(file_path) as f:
return json.load(f)Example - Right:
# scripts/parse_json.py - Simple script!
import json
import sys
with open(sys.argv[1]) as f:
data = json.load(f)
print(json.dumps(data, indent=2))Philosophy: "MCP's job isn't to abstract reality for the agent; its job is to manage the auth, networking, and security boundaries and then get out of the way."
---
Anti-Pattern: Premature Abstraction
Problem: Building a complex MCP before understanding the use case
Better approach: Start with scripts, graduate to MCP when you need: 1. Auth/security boundaries 2. Multiple tools in same domain 3. State management 4. Error handling standardization
Evolution path:
Script → Multiple Scripts → Helper Library → MCP ServerOnly promote to MCP when complexity justifies it.
---
Skill Design
Anti-Pattern: Skill as Documentation Dump
Bad:
---
name: react-guide
description: Everything about React
---
# React Guide
React is a JavaScript library for building user interfaces...
[50 pages of tutorial content]Why wrong: Not progressive disclosure, not actionable, not targeted.
Good:
---
name: react-server-components
description: Use React Server Components correctly. Use when working with Next.js App Router, async components, or server-side data fetching.
---
# React Server Components
## Quick Decision Tree
Is your component:
- Fetching data? → Server Component
- Using hooks/events? → Client Component
- Both? → Server Component wrapper + Client Component child
## Common Anti-Pattern: Everything is 'use client'
❌ **Wrong**:'use client' async function Page() { // This doesn't work! const data = await fetch(...) return <div>{data}</div> }
✅ **Right**:// Server Component (default) async function Page() { const data = await fetchData() return <ClientComponent data={data} /> }
// client-component.jsx 'use client' function ClientComponent({ data }) { const [count, setCount] = useState(0) return <div onClick={() => setCount(count + 1)}>{data}</div> }
## When This Pattern Changed
- Pre-Next.js 13: All components are client-side
- Next.js 13+: Server Components by default
- LLM confusion: Will add 'use client' everywhere because older patterns
See /references/server-components-deep-dive.md for more.---
Anti-Pattern: Missing "When NOT to Use"
Problem: Skills activate on false positives
Example - Without negatives:
description: Processes images using computer vision techniquesActivates for: image resizing, image generation, image editing, OCR, face detection, etc.
Example - With negatives:
description: Semantic image search using CLIP embeddings. Use for finding similar images, zero-shot classification. NOT for image generation, editing, or OCR. NOT for counting objects or fine-grained classification.Pattern: Always include "NOT for X, Y, Z" to prevent false activation.
---
Anti-Pattern: No Validation Script
Problem: Skill gives instructions but no way to check correctness
Better: Include validation
# scripts/validate.py
def validate_setup():
"""Check if environment is configured correctly."""
checks = {
"Node version": check_node_version(),
"Dependencies": check_dependencies(),
"API keys": check_api_keys(),
}
for name, passed in checks.items():
print(f"{'✅' if passed else '❌'} {name}")
return all(checks.values())---
Anti-Pattern: Overly Permissive Tools
Bad:
allowed-tools: BashWhy: Can execute ANY bash command
Better:
allowed-tools: Bash(git:*,npm:run,npm:install),Read,WritePrinciple: Least privilege - only grant what's needed
---
Temporal Knowledge Patterns
When documenting anti-patterns, always include:
1. Timeline: When was this practice common? 2. Why deprecated: What replaced it and why? 3. LLM confusion: Why will LLMs suggest the old pattern? 4. Migration path: How to update from old to new?
Template:
### Anti-Pattern: [Pattern Name]
**Used**: [Date range]
**Replaced by**: [New approach]
**Why deprecated**: [Reason]
**Old way**:
[code example]
**New way**:
[code example]
**LLM mistake**: [Why LLM suggests old pattern]
**How to detect**: [Validation rule]---
---
Real-World Failure Case Studies
Case Study 1: The Photo Expert Explosion
Skill: photo-expert (v1.0) Problem: Single skill for ALL photo operations
Symptoms:
- Activated on "photo" anywhere in query
- 800+ lines of instructions
- Slow loading, high token usage
- Wrong advice given (composition advice when user wanted color theory)
Root Cause: Everything Skill anti-pattern
Resolution: Split into 5 focused skills:
clip-aware-embeddings- semantic searchphoto-composition-critic- aesthetic analysiscolor-theory-palette-harmony-expert- color sciencecollage-layout-expert- arrangement algorithmsevent-detection-temporal-intelligence-expert- clustering
Lesson: One domain ≠ one skill. Split by expertise type.
---
Case Study 2: The Phantom MCP
Skill: github-workflow-helper (v1.1) Problem: Referenced MCP server that didn't exist
SKILL.md said:
Use the included MCP server for GitHub API access.
Run: `npx github-helper-mcp`Reality: No mcp-server/ directory existed
Symptoms:
- Claude confidently told users to run non-existent commands
- Users filed bug reports
- Trust in skill ecosystem damaged
Root Cause: Reference Illusion anti-pattern
Resolution: 1. Added check_self_contained.py to detect phantom tools 2. Either create the MCP or remove the reference 3. Added validation to CI
Lesson: Don't promise tools you don't deliver.
---
Case Study 3: The Time Bomb
Skill: react-hooks-expert (v2.0) Problem: Temporal knowledge became stale
Original content (2023):
Use useEffect with empty deps for componentDidMount behaviorBy 2024: This caused issues with React 18 Strict Mode double-mounting
Symptoms:
- Users followed advice → got bugs
- Skill became actively harmful
- No CHANGELOG to track when content was written
Root Cause: Missing temporal knowledge markers
Resolution:
## Temporal Context
- **Pre-React 18**: useEffect with [] = componentDidMount
- **React 18+**: useEffect with [] runs TWICE in dev (Strict Mode)
- **Current best practice**: Use refs for "run once" patternsLesson: Date your knowledge. Update quarterly.
---
Case Study 4: The Activation Black Hole
Skill: api-design-expert (v1.0) Problem: Never activated when needed
Description:
description: Expert guidance for API designSymptoms:
- User: "How should I structure my REST endpoints?"
- Skill: silence
- User confused why skill existed but never helped
Root Cause: Missing Exclusions + no keywords
Resolution:
description: REST/GraphQL API design patterns. Activate on "API design",
"endpoint structure", "REST architecture", "GraphQL schema".
NOT for API implementation, SDK generation, or documentation.Lesson: Generic descriptions = zero activations
---
Contributing
When you discover a new anti-pattern:
1. Document what looks right but is wrong 2. Explain the fundamental reason it's wrong 3. Show the correct approach 4. Include temporal context (when did this change?) 5. Note why LLMs make this mistake 6. Add detection/validation if possible
Remember: The goal is to encode the knowledge that separates "it compiles" from "it's correct" - the shibboleths that reveal expertise.
Claude Extension Taxonomy: Skills, Plugins, MCPs, Hooks, Agent SDK
The Claude ecosystem has seven extension types. Each serves a different purpose. Choosing the wrong one is a common mistake. This reference defines each type and when to use it.
Last updated: March 2026
---
The Full Taxonomy
flowchart TD
A{What are you extending?} -->|Agent knowledge/process| B[Skill]
A -->|Packaging for distribution| P[Plugin]
A -->|External API/auth/state| C[MCP Server]
A -->|Repeatable local operation| D[Script]
A -->|User-triggered action| E[Slash Command]
A -->|Lifecycle automation| F[Hook]
A -->|Programmatic access / CI/CD| G[Agent SDK]---
Skills (SKILL.md in .claude/skills/)
What they are: Markdown documents that encode domain expertise, decision trees, anti-patterns, and process instructions. Loaded into the agent's context as standard operating procedures.
How they work: The runtime scans name + description at startup. When a skill matches a query, its full SKILL.md is loaded into context. Reference files are loaded on demand.
When to use:
- Encoding domain expertise (shibboleths, anti-patterns, temporal knowledge)
- Providing decision trees and process workflows
- Defining output contracts for downstream consumers
- Teaching the agent HOW to think about a domain
When NOT to use:
- Calling external APIs (use MCP)
- Running code (use scripts)
- Providing a user-triggered action (use slash command)
Key property: Skills are passive knowledge — they shape the agent's reasoning but don't execute code. They're the cheapest, most portable extension type.
Frontmatter fields (as of March 2026):
| Field | Required | Purpose |
|---|---|---|
name | No (defaults to dir name) | Display name |
description | Recommended | Activation trigger + keywords |
allowed-tools | No | Tool whitelist (least privilege) |
argument-hint | No | Autocomplete hint |
disable-model-invocation | No | true = user-only via / |
user-invocable | No | false = hidden from / menu |
context | No | fork = run in isolated subagent |
agent | No | Which subagent type when context: fork |
model | No | Override model when skill is active |
hooks | No | Hooks scoped to skill lifecycle |
license | No | License identifier |
metadata | No | Arbitrary key-value map |
---
Plugins (.claude-plugin/plugin.json)
What they are: Self-contained directories that bundle skills, agents, hooks, MCP servers, and slash commands into a distributable package. Plugins are the packaging and distribution mechanism for Claude Code extensions.
How they work: Plugins live in a directory with .claude-plugin/plugin.json manifest. Components are auto-discovered in standard locations (skills/, agents/, commands/, hooks/). When installed, plugin components get namespaced: plugin-name:skill-name.
When to use:
- Sharing skills with teammates or the community
- Bundling related skills + hooks + MCP servers together
- Distributing via marketplaces (git repos with
marketplace.json) - Versioning and publishing extension sets
When NOT to use:
- Personal-only skills (just use
.claude/skills/directly) - Single scripts that don't need packaging
- One-off customizations
The colon syntax: /plugin-name:skill-name is namespacing, preventing collisions when multiple plugins define components with the same name.
Plugin directory structure:
my-plugin/
├── .claude-plugin/
│ └── plugin.json # Manifest (only this goes in .claude-plugin/)
├── skills/ # Skill directories (SKILL.md in each)
├── agents/ # Agent definitions (markdown)
├── commands/ # Slash commands (markdown)
├── hooks/
│ └── hooks.json # Hook configuration
├── .mcp.json # MCP server configs
├── settings.json # Default settings
└── README.mdDistribution methods:
- Local:
claude --plugin-dir ./my-plugin - Marketplace:
claude plugin install name@marketplace - Official directory:
github.com/anthropics/claude-plugins-official
Key property: Plugins are for distribution, not for new functionality. All plugin components (skills, hooks, MCP servers, agents) work identically whether standalone or inside a plugin.
Full guide: See references/plugin-architecture.md
---
MCP Servers (Model Context Protocol)
What they are: Standalone servers that expose tools, resources, and prompts to Claude via a standardized JSON-RPC 2.0 protocol. They run as separate processes.
How they work: Claude discovers available tools from the MCP server at startup. When the agent decides to use a tool, it sends a JSON-RPC request to the server, which executes the operation and returns results.
Three transport types:
| Transport | Use Case | Command |
|---|---|---|
| HTTP (recommended) | Remote cloud services | claude mcp add --transport http name url |
| SSE (deprecated) | Server-Sent Events | claude mcp add --transport sse name url |
| stdio | Local processes | claude mcp add --transport stdio name -- cmd args |
Configuration scopes:
- Local (default):
~/.claude.jsonunder project path - Project:
.mcp.jsonat project root (committed to VCS) - User:
~/.claude.jsonglobally - Plugin:
.mcp.jsonat plugin root (bundled)
When to use:
- External API access requiring authentication (OAuth, API keys)
- Stateful connections (WebSockets, database connections, sessions)
- Operations needing security boundaries (credentials shouldn't be in prompts)
- Real-time data streams or event subscriptions
- Rate-limited services that need connection pooling
When NOT to use:
- Simple local file operations (just use scripts or built-in tools)
- Stateless computations (scripts are lighter weight)
- One-off operations that don't need auth or state
- Encoding domain knowledge (use skills)
Tool Search: When many MCP servers are configured and tool descriptions exceed 10% of context window, Claude Code automatically enables Tool Search — deferring MCP tool loading until needed.
Skills + MCP: Skills can reference MCP tools in allowed-tools using mcp__<server>__<tool> naming. Skills cannot formally declare MCP dependencies in frontmatter, but can document requirements.
Key property: MCPs are for operations that need auth, state, or security boundaries. Not a general abstraction layer. If you don't need those things, a script is simpler.
Status (March 2026): MCP is the universal tool integration standard. Spec at modelcontextprotocol.io/specification/2025-11-25. Donated to Linux Foundation's AAIF in Dec 2025.
---
Scripts (scripts/ in skill folders)
What they are: Working code files (Python, Bash, Node.js) bundled with skills that perform repeatable operations.
How they work: The agent runs them via Bash tool calls. They take CLI arguments, do their work, and return results via stdout.
When to use:
- Repeatable local operations (validation, analysis, transformation)
- Domain-specific algorithms that must be implemented correctly
- Pre-flight checks that prevent common errors
- Batch processing of local files
- Any stateless computation
When NOT to use:
- Operations requiring auth or API keys (use MCP)
- Stateful operations across multiple calls (use MCP)
- Long-running background processes (use MCP or Temporal)
Requirements: Must actually work (not templates), minimal dependencies (prefer stdlib), clear CLI interface, graceful error handling, installation docs.
Key property: Scripts are the workhorse of self-contained skills. They make skills immediately useful without any infrastructure setup.
---
Slash Commands (/command-name)
What they are: User-triggered actions invoked by typing / in the Claude Code interface.
How they work: When a user types /skill-name, Claude loads that skill's SKILL.md and executes it. In plugins, the format is /plugin-name:command-name.
Relation to skills: A slash command IS a skill. user-invocable: true makes it appear in the / menu. disable-model-invocation: true makes it ONLY available via /.
Plugin commands: Plugins can also define commands in a commands/ directory as standalone markdown files (separate from skills in skills/).
---
Hooks (Claude Code Lifecycle Events)
What they are: Deterministic scripts, HTTP calls, or LLM checks that execute at specific lifecycle points in Claude Code. Much more powerful than git hooks alone.
How they work: Configured in settings.json (user, project, or plugin scope). When the specified event fires, the hook runs. Hooks can block, modify, or provide context for agent actions.
17+ Event Types (as of March 2026):
| Event | When | Can Block? |
|---|---|---|
SessionStart | Session begins/resumes | No |
UserPromptSubmit | User submits prompt | No |
PreToolUse | Before tool execution | Yes (allow/deny/ask) |
PermissionRequest | Permission dialog appears | Yes |
PostToolUse | After tool succeeds | No (provides context) |
PostToolUseFailure | After tool fails | No |
Notification | Claude sends notification | No |
SubagentStart | Subagent spawned | No |
SubagentStop | Subagent finishes | No |
Stop | Claude finishes responding | Yes (can continue) |
TeammateIdle | Agent team member going idle | No |
TaskCompleted | Task marked complete | No |
ConfigChange | Configuration file changes | Yes |
WorktreeCreate | Worktree being created | Replaces default |
WorktreeRemove | Worktree being removed | No |
PreCompact | Before context compaction | No |
SessionEnd | Session terminates | No |
Four Hook Types:
| Type | What It Does |
|---|---|
command | Runs shell command. stdin=JSON event, stdout=response, stderr=feedback |
http | POSTs event data to HTTP endpoint |
prompt | Single-turn LLM check (Haiku by default). Returns {ok, reason} |
agent | Multi-turn verification with tool access. Same response format |
PreToolUse Input Modification (v2.0.10+): PreToolUse hooks can modify tool inputs before execution via updatedToolInput in JSON output.
When to use:
- Blocking dangerous operations (PreToolUse: deny
rm -rf, force push) - Auto-formatting after file writes (PostToolUse)
- Security monitoring (PreToolUse: check for credential leaks)
- Quality gates (Stop: verify tests pass before finishing)
- Session initialization (SessionStart: inject context)
NOT just git hooks: The old taxonomy was wrong. Claude Code hooks are a rich lifecycle system, not limited to git events. Git hooks (.git/hooks/) are a separate system that still works for git-specific automation.
---
Agent SDK (Programmatic Claude Code Access)
What it is: npm/pip packages that provide the same tools, agent loop, and context management that power Claude Code, accessible programmatically.
Packages:
- TypeScript:
@anthropic-ai/claude-agent-sdk - Python:
claude-agent-sdk
How it works: Import the SDK, call query() with a prompt and options, receive a stream of messages. The agent runs with the same capabilities as Claude Code (Read, Write, Edit, Bash, Glob, Grep, WebSearch, etc.).
When to use:
- CI/CD pipelines (automated code review, test generation)
- Custom applications built on Claude Code's runtime
- Batch processing (analyze many files programmatically)
- Building agents that leverage Claude Code's tool ecosystem
- Production automation workflows
When NOT to use:
- Interactive development (use CLI)
- Simple one-off tasks (use CLI)
- Tasks that don't need code execution tools (use Messages API directly)
Skills + Agent SDK: The SDK loads filesystem-based configuration including skills when setting_sources=["project"] is set. This means SDK-powered agents can use your skill library.
# Python example
from claude_agent_sdk import query, ClaudeAgentOptions
async for message in query(
prompt="Find and fix the bug in auth.py",
options=ClaudeAgentOptions(
allowed_tools=["Read", "Edit", "Bash"],
setting_sources=["project"], # Load skills, CLAUDE.md, etc.
),
):
print(message)Relation to MCPs: The Agent SDK can connect to MCP servers programmatically, giving SDK-powered agents access to the same external tools as interactive Claude Code.
Relation to SDK Tools (Messages API): The Agent SDK wraps the Messages API's tool_use capability but adds the full Claude Code runtime (filesystem access, shell execution, context management). SDK tools via the Messages API are the lower-level primitive; the Agent SDK is the high-level abstraction.
---
Decision Matrix
| Need | Extension Type | Why |
|---|---|---|
| Encode domain expertise | Skill | Passive knowledge, cheapest, most portable |
| Package for sharing | Plugin | Bundles skills + hooks + MCP + agents |
| External API + auth | MCP Server | Manages auth, state, security boundaries |
| Local repeatable operation | Script | Works immediately, no infra needed |
| User-triggered explicit action | Slash Command (skill) | Discoverable in UI, invoked with / |
| Lifecycle automation | Hook | 17+ events: PreToolUse, Stop, SessionStart, etc. |
| CI/CD / programmatic access | Agent SDK | npm/pip, same tools as CLI |
| Custom app integration | SDK Tool (Messages API) | Lower-level tool_use for your codebase |
The Graduation Path
Domain knowledge → Skill (SKILL.md)
↓ needs code?
Script (scripts/)
↓ needs auth/state?
MCP Server (mcp-server/)
↓ needs orchestration?
Subagent (agents/)
↓ needs distribution?
Plugin (plugin.json)
↓ needs CI/CD automation?
Agent SDKEach level adds infrastructure. Only promote when the simpler level genuinely can't do the job.
---
Common Mistakes
MCP for Everything
Wrong: Building an MCP server for local JSON parsing. Right: Write a 10-line Python script. MCPs are for auth/state boundaries.
Skills Without Scripts
Wrong: A skill that describes a validation process but doesn't include a validation script. Right: Include scripts/validate.py that actually runs. Skills + scripts = immediately productive.
Slash Command for Auto-Trigger Skills
Wrong: Making every skill a slash command. Right: Most skills should auto-trigger on matching queries. Only make it a slash command if the user needs to invoke it explicitly.
Script That Should Be an MCP
Wrong: A script that stores API keys in environment variables and makes authenticated API calls. Right: Package it as an MCP server with proper credential management.
Plugin for Personal Use
Wrong: Creating a full plugin for skills only you use. Right: Keep personal skills in .claude/skills/. Plugins are for distribution.
Confusing Hooks with Git Hooks
Wrong: Thinking Claude Code hooks are just .git/hooks/ wrappers. Right: Claude Code hooks fire at 17+ lifecycle events (PreToolUse, PostToolUse, Stop, etc.) with 4 execution types (command, http, prompt, agent). Git hooks are a separate system.
Agent SDK for Simple Tasks
Wrong: Using the Agent SDK to run a one-off fix. Right: Use the CLI interactively. The SDK is for automation and programmatic access.
Skill Description Writing Guide
The description field in SKILL.md frontmatter is the single most important line for activation. Claude's runtime scans descriptions at startup to build a catalog. When a user's query arrives, the runtime matches against these descriptions to decide which skills to load. A weak description means zero activations or constant false positives.
---
The Formula
`[What it does] [When to use it] [Trigger keywords]. NOT for [Exclusions].`
Every description should answer: 1. What: What does this skill do? (specific verb + domain noun) 2. When: In what situations should it activate? 3. Keywords: What words in a user's query should trigger it? 4. NOT for: What should explicitly NOT trigger it?
---
Bad → Good Examples
1. Too Vague / Generic
Bad:
"This skill helps with writing and improving content."
Problems: No task type, no audience, no trigger conditions, overlaps with every writing-related skill.
Good:
"Drafts and revises long-form technical blog posts for software engineers, including structure, headings, and examples. Use when creating or improving an in-depth engineering blog post. NOT for short replies, casual notes, or marketing copy."
Why it works: Specific audience (software engineers), specific format (long-form blog posts), clear exclusions.
---
2. Overlapping with Other Skills
Bad:
"This skill writes documents and summaries for business use."
Problems: Collides with marketing, ops, product, and general summarization skills. Which one should activate?
Good:
"Creates and updates quarterly business review (QBR) slide decks for executives, using a standard section layout (executive summary, KPIs, highlights, risks, next steps). Use when preparing or revising a QBR or leadership performance review. NOT for internal status docs, detailed PRDs, or marketing materials."
Why it works: Specific deliverable (QBR decks), specific audience (executives), clear format, explicit exclusions.
---
3. Description is a Mini-Manual
Bad:
"This skill helps you research and summarize complex topics. First it collects requirements, then it searches, then it writes an outline, then it drafts a report, then it revises based on feedback, and it always uses clear language and bullet points with citations and examples and..."
Problems: Too long, procedures belong in the SKILL.md body, risks truncation in the catalog scan. The runtime only reads the description for matching — process details don't help activation.
Good:
"Performs structured research and writes 1-3 page synthesis reports on technical or business topics for non-expert readers. Use when requesting a researched overview or briefing document. NOT for quick factual questions, casual brainstorming, or academic papers."
Why it works: Concise, specifies output format (1-3 pages), names the audience, excludes adjacent tasks.
---
4. Missing "When Not to Use"
Bad:
"This skill reviews code changes and suggests improvements."
Problems: Will activate for every coding request — writing new features, debugging, refactoring, reviewing PRs. Way too broad.
Good:
"Reviews existing code changes (diffs, pull requests) in TypeScript and React projects, providing structured feedback on correctness, readability, performance, and tests. Use when sharing diffs or PRs for review. NOT for implementing new features from scratch, debugging runtime errors, or general coding advice."
Why it works: Specific input (diffs/PRs), specific tech stack (TypeScript/React), clear boundary (review vs. implementation).
---
5. Not Using User Language / Domain Keywords
Bad:
"This skill manages agile processes for teams and helps with planning and coordination."
Problems: "Agile processes" is a category, not a trigger. No mention of the specific artifacts users actually ask about.
Good:
"Plans and updates agile sprints in tools like Jira or Linear, including writing user stories, prioritizing the backlog, and drafting sprint goals. Use when planning a sprint, grooming a backlog, or turning product ideas into user stories. NOT for low-level coding tasks, architecture decisions, or retrospective facilitation."
Why it works: Names the tools (Jira, Linear), names the artifacts (user stories, backlog, sprint goals), uses verbs users would actually type.
---
6. Misaligned Name and Description
Bad:
name: database-migration-skill
description: This skill writes marketing emails to customers.Problems: Name says infrastructure, description says marketing. The runtime and human readers will both be confused.
Good:
name: database-migration-skill
description: Plans and reviews database schema and data migrations, focusing on safety, rollout strategy, and rollback plans. Use when designing or validating a database migration. NOT for general application feature design or marketing content.---
7. Overly Broad "Catch-All" Skills
Bad:
"This skill helps the user with anything related to product management, including discovery, strategy, roadmapping, writing, and stakeholder communication."
Problems: Becomes a generic PM agent that competes with every other skill, easy to misfire, impossible to test activation precisely.
Good (narrowed to one deliverable):
"Structures and writes product requirement documents (PRDs) for new or existing features, including problem statement, goals, user stories, and acceptance criteria. Use when drafting or refining a PRD. NOT for high-level strategy decks, user interview notes, or OKR planning."
Why it works: One specific deliverable (PRDs), clear trigger ("draft a PRD"), explicit boundaries.
---
Activation Keyword Strategy
Use Domain-Specific Terms
Include the exact words users type:
- ✅ "CLIP", "embeddings", "similarity search"
- ❌ "computer vision techniques" (too abstract)
Include Verb + Noun Combinations
Users ask for actions on objects:
- ✅ "create skill", "improve skill", "debug activation"
- ❌ "skill-related activities"
Add Common Synonyms
Users phrase things differently:
- ✅ "review code", "code review", "PR review", "diff review"
- ❌ Just "review" (too generic)
Test with Anti-Queries
For every keyword that should trigger, think of a query with that word that should NOT trigger:
- "CLIP" → triggers: "Use CLIP for image search"
- "CLIP" → should NOT trigger: "Clip the audio at 30 seconds" (different meaning)
If anti-queries would false-positive, add them to the NOT clause.
---
Description Length Guidelines
- Minimum: 15 words (enough for What + When + NOT)
- Ideal: 25-50 words
- Maximum: ~100 words (longer descriptions get truncated in catalog scans)
- Process details: Never in description. Put in SKILL.md body.
- Examples: Never in description. Put in SKILL.md body.
---
Common Description Patterns by Skill Type
Domain Expertise Skills
[Domain] expertise for [specific area]. Use when [trigger situations].
Activate on [keywords]. NOT for [adjacent domains].Tool/Script Skills
[Action verb] [objects] using [method/tool]. Use when [trigger situations].
NOT for [related but different tasks].Process/Workflow Skills
[Multi-step process name] for [deliverable]. Use when [trigger situations].
NOT for [simpler/different processes].Audit/Review Skills
Audits/reviews [what] for [quality criteria]. Use when [trigger situations].
NOT for [creating/implementing the thing being reviewed].---
Testing a Description
After writing a description, validate with this checklist:
□ Contains at least one specific verb (creates, reviews, plans, debugs)
□ Names a specific deliverable or domain (PRDs, TypeScript diffs, CLIP embeddings)
□ Includes keywords users would actually type in a query
□ Has a NOT clause with 2-5 explicit exclusions
□ Name and description are aligned (no contradictions)
□ Under 100 words (ideally 25-50)
□ No process/workflow details (those go in SKILL.md body)
□ Doesn't overlap with other skills in the same repo---
Rewriting Exercise
When improving an existing description, use this process:
1. List 5 queries that should trigger this skill 2. List 5 queries that should NOT trigger (but are in a similar domain) 3. Extract keywords from the "should trigger" list 4. Extract exclusions from the "should NOT trigger" list 5. Write: [What from step 1 patterns] [When from step 1 patterns] [Keywords from step 3]. NOT for [Exclusions from step 4]. 6. Test: Re-read each of the 10 queries. Would the description correctly match/reject each one?
Knowledge Engineering for Skill Creation
How to apply knowledge engineering (KE) methods to extract expert knowledge and build skills. Covers structured knowledge acquisition, mental model elicitation, tacit-to-explicit conversion, and novel AI-native approaches.
---
Why Knowledge Engineering Matters for Skills
A skill is a codified expert mental model. The challenge: experts don't think in SKILL.md templates. They think in intuitions, pattern-matching, contextual heuristics, and embodied know-how accumulated over years. Knowledge engineering is the discipline of extracting this tacit knowledge and converting it to explicit, transferable form.
Traditional KE built expert systems with formal rules. We build skills with natural language. The extraction challenge is the same.
---
Structured Knowledge Acquisition Methods
Protocol Analysis (Think-Aloud)
What: Ask the expert to solve a real problem while narrating their thought process.
How to apply: 1. Give the expert a representative task in their domain 2. Record them solving it while explaining each decision 3. Listen for: decision points, rejection of alternatives, pattern-matching, "obvious" shortcuts that aren't obvious to novices 4. Extract: decision trees, anti-patterns, temporal knowledge, shibboleths
What you're extracting: The expert's procedural knowledge — the steps they follow and why. This maps directly to a skill's "Core Process" section.
The gold: The moments where the expert says "well, obviously you wouldn't..." or "the trick here is..." or "most people get this wrong because...". These are shibboleths. They go in the anti-patterns section.
Real-world example (University of Southampton): A geologist analyzing a hand specimen narrated: "it's obviously a fairly coarse-grained rock... and you've got some nice big orthoclase crystals... quartz, which is this fairly clear mineral." From this, production rules were extracted: IF grain size is large THEN rock is plutonic. The verbalization exposed classification logic that the expert used automatically but had never articulated.
Practical note: Train the expert to think aloud first using a simple warm-up task (like long multiplication). Uninhibited verbalization is a learned skill. Keep sessions short — they are mentally exhausting, especially for automatized knowledge the expert has never had to explain.
Repertory Grid Technique
What: Elicit the expert's personal construct system — the dimensions along which they evaluate things in their domain.
How to apply: 1. Present the expert with 3 examples of [domain objects] (e.g., 3 code PRs, 3 building designs, 3 patient cases) 2. Ask: "In what way are two of these alike but different from the third?" 3. The expert produces a construct (a bipolar dimension, e.g., "well-structured vs. tangled" or "safe vs. risky") 4. Repeat with different triads until constructs stabilize 5. Rate all examples on all constructs
What you're extracting: The expert's evaluative framework — the axes along which they judge quality. These map to the skill's evaluation criteria and to the skill-grader's axes for this domain.
Real-world example (Boeing, 1983-1989): Boeing's Expertise Transfer System (ETS) and its successor Aquinas used repertory grids to build 100+ expert system prototypes. In a typical 30-minute session, an associate sat with a domain expert (e.g., a DBMS advisor). The expert listed solutions (database systems), ETS presented triads and elicited discriminating traits, and within an hour a working prototype with production rules was generated. Experts found the process engaging rather than threatening — the analysis tools surfaced implications in their own knowledge they hadn't consciously recognized.
Practical note: Grids become unwieldy beyond ~15-20 elements. Boeing found a 38×35 grid "hard for the expert to use and manage." The solution: hierarchical decomposition — break a large domain into sub-grids at different abstraction levels.
Card Sorting
What: Give the expert a pile of domain concepts and ask them to organize them into groups.
How to apply: 1. Write each domain concept/task/tool on a card 2. Ask the expert to sort into groups that "make sense to them" 3. Ask them to name each group 4. Ask why certain items are together and others aren't 5. Repeat with different experts; compare group structures
What you're extracting: The expert's ontology — how they categorize their domain. This maps to domain meta-skills (decomposition patterns) and skill catalog organization.
Critical Incident Technique
What: Ask experts to describe times things went very wrong (or very right) and what they did.
How to apply: 1. "Tell me about a time when [domain task] went badly. What happened? What would you do differently?" 2. "Tell me about a time when you caught a problem that someone else missed. How did you spot it?" 3. Extract: failure modes, recovery strategies, early warning signs
What you're extracting: The expert's failure knowledge — what goes wrong and how to prevent it. These map directly to anti-patterns and shibboleths. This is often the most valuable knowledge because it's the hardest to acquire any other way.
Real-world example (Healthcare, Ireland 2020): Researchers used CIT to study interdisciplinary team interventions. Seventeen informants described critical incidents, producing seven Context-Mechanism-Outcome Configurations. Two findings emerged ONLY through CIT: prior personal relationships as a contextual enabler and inter-professional tensions as a barrier — neither identified in the literature review.
Real-world example (Flanagan's WWII pilot studies): The original CIT application asked trainees and observers to recount incidents of success and failure. Common threads in aptitude, proficiency, and temperament were extracted and used to formulate selection tests for pilots. Incidents "need not be spectacular" — significance, not drama, defines criticality.
Concept Mapping
What: The expert draws a visual map of how concepts in their domain relate to each other.
How to apply: 1. Give the expert a whiteboard or tool 2. Ask: "Map out the key concepts in [domain] and how they connect" 3. Listen for: hierarchies, causal relationships, conditional dependencies, temporal sequences
What you're extracting: The expert's conceptual structure — how ideas relate. This maps to the Mermaid diagrams in skills and to domain meta-skill phase patterns.
---
Extracting How Professionals Think
The Architecture of Expert Cognition
Research on expertise (Dreyfus, Ericsson, Klein) identifies how expert thinking differs from novice thinking:
| Dimension | Novice | Expert |
|---|---|---|
| Problem representation | Surface features ("it's a React bug") | Deep structure ("it's a stale closure over mutable state") |
| Pattern matching | Slow, rule-by-rule | Instant recognition of familiar patterns |
| Anomaly detection | Can't tell when something is "off" | Immediately senses when a situation is atypical |
| Forward reasoning | Works from symptoms to causes | Works from hypotheses to evidence |
| Chunking | Sees individual elements | Sees meaningful clusters (the chess master's "chunks") |
| Metacognition | Doesn't know what they don't know | Knows precisely what they're uncertain about |
Skills should encode ALL of these dimensions:
- Deep structure → decision trees based on underlying causes, not surface symptoms
- Pattern matching → "If you see X, that's almost always Y" shibboleths
- Anomaly detection → "If this looks unusual, check for Z"
- Forward reasoning → hypothesis-first diagnostic processes
- Chunking → domain-specific vocabulary and abbreviations
- Metacognition → "You should be uncertain about this if..." qualifiers
The Aha! Moment Problem
The most valuable knowledge is often the hardest to extract: the moment when a practitioner's mental model clicked. The music student who suddenly hears harmonic structure instead of individual notes. The programmer who suddenly sees the dependency graph instead of individual files. The mathematician who suddenly recognizes a problem as homologous to one they've solved before.
These moments represent conceptual phase transitions — qualitative reorganizations of the mental model that can't be reached by accumulating individual facts. They're Kuhnian revolutions at the individual level.
How to extract them: 1. Ask: "When did [domain] stop feeling confusing and start making sense? What changed?" 2. Ask: "What do you see now that you couldn't see as a beginner?" 3. Ask: "If you could give your younger self one insight that would have saved years, what would it be?" 4. The answers to these questions are the highest-leverage content for skills. A single paragraph capturing an expert's aha! moment can be worth more than pages of procedural steps.
Structured Ignorance Management
Experts are distinguished not by what they know but by how they manage what they don't know:
- Known unknowns: "I don't know X, but I know how to find out"
- Unknown unknowns: "I don't even know what questions to ask"
- Knowable but not worth knowing: "I could learn X but the ROI isn't there"
- Axiomatic certainties: "I know X is true and can reason from it"
This maps to skill architecture:
- Known unknowns → "Consult
references/X.mdwhen you need this information" - Unknown unknowns → "If the situation doesn't match any known pattern, escalate to research/human"
- Not worth knowing → "NOT for X" in the description (explicit scope boundaries)
- Axiomatic certainties → Decision trees built on stable truths
---
AI-Native Knowledge Acquisition
Technique: Corpus Distillation
Deploy an army of Haiku summarization agents at professional handbooks, biographies, and career guides. Each agent extracts:
1. Process patterns: "When this expert encounters [situation], they do [steps]" 2. Decision heuristics: "The expert chooses between A and B based on [criteria]" 3. Failure stories: "This went wrong because [reason]; the fix was [approach]" 4. Aha! moments: "The turning point was realizing [insight]" 5. Metaphors and mental models: "They think of [domain] as [metaphor]"
The summarization army processes at ~$0.001/page. A 300-page handbook costs ~$0.30 to distill. The output is a structured knowledge map that feeds skill crystallization.
See the very-long-text-summarization skill for the technical implementation.
Technique: Interview Simulation
Use a Sonnet agent with the domain meta-skill to "interview" the source material:
Given this handbook chapter on [topic], answer as if you are the author:
1. What's the most common mistake newcomers make?
2. What changed in your field in the last 5 years?
3. What do you check first when things go wrong?
4. What's the one thing you wish everyone in your field understood?This extracts the same knowledge that a real interview would, at machine speed.
Technique: Cross-Source Triangulation
Extract knowledge from multiple sources about the same domain. Where they agree, that's reliable. Where they disagree, that's interesting — it may indicate:
- A paradigm shift in progress (Kuhnian revolution)
- Domain-specific school-of-thought divisions
- Temporal drift (older source vs. newer source)
---
From Knowledge to Skill
The Pipeline
flowchart TD
S[Source Material] --> E[Extract]
E --> P1[Process patterns]
E --> P2[Decision heuristics]
E --> P3[Failure stories]
E --> P4[Aha moments]
E --> P5[Metaphors]
P1 --> SK[SKILL.md Core Process]
P2 --> SK
P3 --> AP[Anti-Patterns section]
P4 --> AP
P5 --> SK
SK --> V[Validate with skill-grader]
AP --> V
V --> D[Deploy to catalog]
D --> R[Rank from execution data]---
Source Material: Books That Expose Expert Thinking
For the corpus distillation pipeline (very-long-text-summarization), these books expose HOW experts think, not just what they know. Organized by the type of knowledge they yield.
Cross-Domain (How Expertise Itself Works)
| Book | Author | What It Yields |
|---|---|---|
| Sources of Power | Gary Klein | Recognition-Primed Decision model: experts pattern-match, simulate one option, act. Firefighters, nurses, pilots, military. |
| The Reflective Practitioner | Donald Schön | "Reflection-in-action" across 5 professions (engineering, architecture, management, therapy, planning). Professionals know more than they can say. |
| Thinking in Systems | Donella Meadows | Feedback loops, stocks and flows, leverage points. The meta-mental-model for any complex system. |
| Seeing Like a State | James C. Scott | Mētis (practical, local, embodied knowledge) vs. legibility (top-down simplification). Why abstract models destroy the knowledge that makes systems work. |
| Range | David Epstein | Generalists outperform specialists in complex domains. Analogical transfer across fields. |
Software Engineering
| Book | What It Yields for Skills |
|---|---|
| A Philosophy of Software Design (Ousterhout) | Deep vs. shallow modules, information hiding, complexity as the root enemy. Empirically tested heuristics. |
| The Pragmatic Programmer (Hunt & Thomas) | DRY, tracer bullets, broken window theory, programming by coincidence. A practitioner's operating system. |
| The Mythical Man-Month (Brooks) | Conceptual integrity, Brooks' Law, surgical team model. Human topology of projects. |
Architecture & Design
| Book | What It Yields for Skills |
|---|---|
| A Pattern Language (Alexander) | 253 problem-solution patterns composable into designs. Origin of pattern thinking. |
| How Buildings Learn (Brand) | Shearing layers: 6 layers changing at different rates. Design for adaptability. |
Mathematics
| Book | What It Yields for Skills |
|---|---|
| How to Solve It (Pólya) | 67 heuristics: analogy, generalization, working backward, auxiliary problems. The foundation of structured problem-solving. |
| Proofs and Refutations (Lakatos) | Math proceeds by conjecture → proof → counterexample → revision, not clean deduction. Messy iteration as the actual method. |
Medicine
| Book | What It Yields for Skills |
|---|---|
| How Doctors Think (Groopman) | Specific cognitive errors: anchoring, availability, commission bias. Thinking process made visible. |
| The Checklist Manifesto (Gawande) | When to rely on expert judgment vs. systematic process. The boundary that defines skill structure. |
Finance
| Book | What It Yields for Skills |
|---|---|
| Poor Charlie's Almanack (Munger) | Latticework of mental models from every discipline. Inversion, fat pitches, Lollapalooza Effect. |
| Thinking in Bets (Annie Duke) | Separate decision quality from outcome quality. Think in probabilities, not certainties. |
The Distillation Pipeline
Feed these books through very-long-text-summarization in skill-draft mode: 1. Haiku army extracts process patterns, decision heuristics, failure stories, aha! moments, metaphors 2. Sonnet synthesizes into a structured knowledge map 3. Opus crystallizes into a SKILL.md 4. skill-grader validates quality (must score B+ or above)
Cost: ~$0.19 per 300-page book. The entire cross-domain reading list (~12 books, ~3,600 pages) costs ~$2.30 to distill.
---
Quality Gate
Before deploying a KE-derived skill: 1. Grade it with skill-grader — must score B+ or above overall 2. Test with 5 should-trigger and 5 shouldn't-trigger queries 3. Run through one complete DAG execution as a dry run 4. If the skill was derived from source material, include citations ("Based on [Handbook], Chapter 7")
Minimal MCP Server Template
Production-ready starter template for MCP servers.
File Structure
mcp-server/
├── src/
│ └── index.ts # Server implementation
├── package.json # Dependencies and scripts
├── tsconfig.json # TypeScript configuration
└── README.md # Installation instructionssrc/index.ts
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
// Server metadata
const server = new Server(
{
name: "my-skill-mcp",
version: "1.0.0"
},
{
capabilities: {
tools: {}
}
}
);
// Define available tools
server.setRequestHandler("tools/list", async () => ({
tools: [
{
name: "example_tool",
description: "Example tool that demonstrates the pattern",
inputSchema: {
type: "object",
properties: {
input: {
type: "string",
description: "Input parameter description"
}
},
required: ["input"]
}
}
]
}));
// Handle tool calls
server.setRequestHandler("tools/call", async (request) => {
const { name, arguments: args } = request.params;
if (name === "example_tool") {
try {
// Your tool implementation here
const result = await processInput(args.input);
return {
content: [
{
type: "text",
text: JSON.stringify(result, null, 2)
}
]
};
} catch (error) {
throw new Error(`Failed to process: ${error.message}`);
}
}
throw new Error(`Unknown tool: ${name}`);
});
// Helper function (example)
async function processInput(input: string): Promise<any> {
// Implement your logic here
return {
processed: input,
timestamp: new Date().toISOString()
};
}
// Start server
const transport = new StdioServerTransport();
await server.connect(transport);package.json
{
"name": "my-skill-mcp",
"version": "1.0.0",
"description": "MCP server for [domain] operations",
"type": "module",
"bin": {
"my-skill-mcp": "dist/index.js"
},
"scripts": {
"build": "tsc",
"start": "node dist/index.js",
"watch": "tsc --watch"
},
"dependencies": {
"@modelcontextprotocol/sdk": "^1.0.0"
},
"devDependencies": {
"@types/node": "^20.0.0",
"typescript": "^5.0.0"
}
}tsconfig.json
{
"compilerOptions": {
"target": "ES2022",
"module": "Node16",
"moduleResolution": "Node16",
"outDir": "dist",
"rootDir": "src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"]
}README.md
# My Skill MCP Server
MCP server for [domain] operations.
## Features
- [Feature 1]
- [Feature 2]
- [Feature 3]
## Installation
\`\`\`bash
cd mcp-server
npm install
npm run build
\`\`\`
## Configuration
Add to your Claude Code MCP settings (`~/.config/claude/config.json`):
\`\`\`json
{
"mcpServers": {
"my-skill": {
"command": "node",
"args": ["/absolute/path/to/mcp-server/dist/index.js"],
"env": {
"API_KEY": "your-api-key-here"
}
}
}
}
\`\`\`
## Tools
### example_tool
Description of what this tool does.
**Parameters**:
- `input` (string, required): Description of input parameter
**Example**:
\`\`\`json
{
"input": "test value"
}
\`\`\`
## Development
\`\`\`bash
npm run watch # Auto-rebuild on changes
\`\`\`
## Testing
Test the server manually:
\`\`\`bash
echo '{"jsonrpc":"2.0","method":"tools/list","id":1}' | npm start
\`\`\`Best Practices
1. Error Handling: Always wrap tool implementations in try-catch 2. Validation: Validate inputs before processing 3. Logging: Use structured logging for debugging 4. Secrets: Use environment variables for API keys 5. Types: Use TypeScript for type safety 6. Documentation: Keep README up to date with tool changes
Common Patterns
Authentication
const API_KEY = process.env.API_KEY;
if (!API_KEY) {
throw new Error("API_KEY environment variable required");
}Rate Limiting
import pLimit from 'p-limit';
const limit = pLimit(5); // Max 5 concurrent requests
async function processWithLimit(items: string[]) {
return Promise.all(
items.map(item => limit(() => processItem(item)))
);
}Caching
const cache = new Map<string, any>();
async function getCached(key: string, fetcher: () => Promise<any>) {
if (cache.has(key)) {
return cache.get(key);
}
const value = await fetcher();
cache.set(key, value);
return value;
}Troubleshooting
Server won't start:
- Check that
npm run buildcompleted successfully - Verify absolute path in config.json
- Check environment variables are set
Tool not found:
- Ensure tool name in
tools/listmatchestools/callhandler - Check for typos in tool names
Authentication errors:
- Verify API_KEY environment variable is set correctly
- Check API key has necessary permissions
Plugin Architecture: Creating, Packaging, and Distributing
Complete guide to Claude Code plugins — the distribution mechanism for skills, hooks, MCP servers, and agents.
Last updated: March 2026
---
What is a Plugin?
A plugin is a self-contained directory that extends Claude Code with custom functionality. It can include any combination of:
- Skills (domain knowledge)
- Agents (subagent definitions)
- Commands (slash commands)
- Hooks (lifecycle automation)
- MCP Servers (external tool integration)
- Settings (default configuration)
The key distinction: skills are for expertise, plugins are for distribution.
---
Plugin vs Standalone
| Approach | Skill Names | Best For |
|---|---|---|
Standalone (.claude/skills/) | /hello | Personal workflows, project-specific |
Plugin (.claude-plugin/plugin.json) | /plugin-name:hello | Team sharing, community distribution |
When a skill lives inside a plugin, it gets namespaced with the plugin name. The colon syntax (plugin-name:skill-name) prevents naming collisions.
---
Plugin Directory Structure
my-plugin/
├── .claude-plugin/
│ └── plugin.json # Plugin manifest — ONLY this goes here
├── skills/ # Skill directories
│ └── my-skill/
│ ├── SKILL.md
│ └── references/
├── agents/ # Agent definitions (markdown)
│ └── reviewer.md
├── commands/ # Slash commands (markdown)
│ └── review-pr.md
├── hooks/
│ └── hooks.json # Hook configuration
├── scripts/ # Hook and utility scripts
│ └── format.sh
├── settings.json # Default settings when plugin enabled
├── .mcp.json # MCP server configurations
├── .lsp.json # LSP server configurations (optional)
└── README.mdCritical rule: Only plugin.json goes inside .claude-plugin/. All other directories must be at the plugin root.
---
Plugin Manifest (plugin.json)
Minimal
{
"name": "my-plugin"
}The manifest is technically optional — if omitted, Claude Code auto-discovers components and derives the name from the directory.
Full Schema
{
"name": "my-plugin",
"version": "1.2.0",
"description": "Brief description of what this plugin does",
"author": {
"name": "Your Name",
"email": "you@example.com",
"url": "https://github.com/you"
},
"homepage": "https://docs.example.com/my-plugin",
"repository": "https://github.com/you/my-plugin",
"license": "MIT",
"keywords": ["keyword1", "keyword2"],
"commands": ["./custom/commands/special.md"],
"agents": "./custom/agents/",
"skills": "./custom/skills/",
"hooks": "./config/hooks.json",
"mcpServers": "./mcp-config.json",
"outputStyles": "./styles/",
"lspServers": "./.lsp.json"
}Only name is required when the file exists.
---
Plugin Components
Skills in Plugins
Same as standalone skills. Place each in skills/<name>/SKILL.md. They follow all the same rules (frontmatter, progressive disclosure, references).
Agents in Plugins
Agent definitions are markdown files in agents/:
---
name: code-reviewer
description: Reviews code for quality issues
---
You are a code reviewer. Focus on...Commands in Plugins
Slash commands are markdown files in commands/:
---
name: review-pr
description: Review the current PR
argument-hint: "[PR number]"
---
Review the current pull request...Hooks in Plugins
Configure in hooks/hooks.json:
{
"hooks": {
"PostToolUse": [{
"matcher": "Write|Edit",
"hooks": [{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/scripts/format.sh"
}]
}],
"PreToolUse": [{
"matcher": "Bash",
"hooks": [{
"type": "prompt",
"prompt": "Check if this bash command is safe to run"
}]
}]
}
}The ${CLAUDE_PLUGIN_ROOT} variable resolves to the absolute path of the plugin directory.
MCP Servers in Plugins
Configure in .mcp.json at plugin root:
{
"my-server": {
"command": "${CLAUDE_PLUGIN_ROOT}/servers/server",
"args": ["--config", "${CLAUDE_PLUGIN_ROOT}/config.json"],
"env": {
"API_KEY": "${API_KEY}"
}
}
}Plugin MCP servers start automatically when the plugin is enabled.
---
Testing Locally
# Run Claude Code with your plugin loaded
claude --plugin-dir ./my-plugin
# Load multiple plugins
claude --plugin-dir ./plugin-one --plugin-dir ./plugin-two---
Distribution Methods
1. Plugin Marketplace (Primary)
A marketplace is a git repository with .claude-plugin/marketplace.json:
{
"name": "company-tools",
"owner": { "name": "DevTools Team" },
"plugins": [
{
"name": "code-formatter",
"source": "./plugins/formatter",
"description": "Automatic code formatting",
"version": "2.1.0"
},
{
"name": "security-scanner",
"source": "github:org/security-plugin",
"description": "Security scanning tools",
"version": "1.0.0"
}
]
}Plugin sources can be: relative paths, GitHub repos, Git URLs, npm packages, or pip packages.
Users install from marketplaces:
# Add marketplace
/plugin marketplace add owner/repo
/plugin marketplace add https://gitlab.com/company/plugins.git
/plugin marketplace add ./local-marketplace
# Install plugin from marketplace
/plugin install code-formatter@company-tools
claude plugin install code-formatter@company-tools --scope project2. Official Plugin Directory
Anthropic maintains the official directory at github.com/anthropics/claude-plugins-official (8.7k+ stars).
Submit your plugin:
- Via
claude.ai/settings/plugins/submit - Or
platform.claude.com/plugins/submit
3. Direct Installation
For team-wide adoption without a marketplace:
// .claude/settings.json (project-level)
{
"extraKnownMarketplaces": {
"our-tools": {
"source": { "source": "github", "repo": "our-org/claude-plugins" }
}
},
"enabledPlugins": {
"code-formatter@our-tools": true
}
}4. Community Registries
claude-plugins.dev— Community CLI for one-command installsclaudepluginhub.com— Community directorygithub.com/hesreallyhim/awesome-claude-code— Curated list
---
Official Example Plugins
From github.com/anthropics/claude-code/tree/main/plugins:
| Plugin | Components | Description |
|---|---|---|
| code-review | Command + 5 Agents | Parallel PR review with confidence scoring |
| feature-dev | Command + 3 Agents | 7-phase feature development workflow |
| pr-review-toolkit | Command + 6 Agents | Specialized PR review (comments, tests, types) |
| plugin-dev | Command + 3 Agents + 7 Skills | 8-phase plugin creation toolkit |
| hookify | Commands + Agent + Skill | Custom hook creation tool |
| commit-commands | Commands | Git workflow: /commit, /commit-push-pr |
| security-guidance | Hook (PreToolUse) | Security pattern monitoring |
| ralph-wiggum | Commands + Hook (Stop) | Autonomous iteration loops |
---
Anti-Patterns
Plugin for Personal Use
Wrong: Creating a full plugin for skills only you use. Right: Keep personal skills in .claude/skills/. Plugins add packaging overhead that only pays off when sharing.
Everything in .claude-plugin/
Wrong: Putting skills, hooks, scripts inside the .claude-plugin/ directory. Right: Only plugin.json goes in .claude-plugin/. Everything else at plugin root.
No README
Wrong: Publishing a plugin without installation instructions. Right: Include a README with setup steps, MCP server requirements, and example usage.
Unpinned Dependencies
Wrong: MCP server with "@modelcontextprotocol/sdk": "*". Right: Pin major versions. MCP spec is still evolving; breaking changes happen.
---
Checklist: Is My Plugin Ready?
□ plugin.json has name, version, description
□ README.md has installation and usage instructions
□ All skills follow skill-architect standards
□ All referenced files exist (no phantoms)
□ Hooks use ${CLAUDE_PLUGIN_ROOT} for paths
□ MCP servers have setup docs and env var requirements
□ Tested locally with claude --plugin-dir
□ No hardcoded absolute paths
□ License specifiedSelf-Contained Tools
Implementation patterns for scripts, MCP servers, and subagents that make skills immediately useful.
Philosophy
The best skill is one where the user can start working immediately.
| Approach | Result |
|---|---|
| "Here's how to build a CLIP embedder" | User spends 2 hours implementing |
| "Here's a working CLIP embedder, run it" | User is productive in 2 minutes |
Skills should encode expertise AND provide working tools to apply that expertise.
---
Scripts
When to Include Scripts
- Skill describes repeatable operations (analysis, validation, transformation)
- Domain has specific algorithms that should be implemented correctly
- Pre-flight checks would prevent common errors
Script Requirements
1. Actually work - Not templates, not pseudocode 2. Minimal dependencies - Prefer stdlib, document any pip/npm installs 3. Clear interface - CLI args or stdin/stdout 4. Error handling - Graceful failures with helpful messages 5. README - How to install and run
Example: Domain Analysis Script
#!/usr/bin/env python3
"""
Photo Composition Analyzer
Analyzes images for composition quality using rule of thirds,
visual weight distribution, and color harmony.
Usage: python analyze_composition.py <image_path>
Dependencies: pip install pillow numpy
"""
import sys
from pathlib import Path
def analyze_composition(image_path: str) -> dict:
"""Analyze composition and return scores."""
# Import here to give helpful error if missing
try:
from PIL import Image
import numpy as np
except ImportError:
print("Install dependencies: pip install pillow numpy")
sys.exit(1)
img = Image.open(image_path)
# ... actual implementation ...
return {
"rule_of_thirds": 0.85,
"visual_balance": 0.72,
"color_harmony": 0.91,
"overall": 0.83
}
if __name__ == "__main__":
if len(sys.argv) != 2:
print(f"Usage: {sys.argv[0]} <image_path>")
sys.exit(1)
result = analyze_composition(sys.argv[1])
for metric, score in result.items():
print(f"{metric}: {score:.2f}")Example: Validation Script
#!/bin/bash
# validate_skill.sh - Pre-flight checks for skill quality
# Usage: ./validate_skill.sh /path/to/skill
SKILL_DIR="$1"
if [ -z "$SKILL_DIR" ]; then
echo "Usage: $0 <skill_directory>"
exit 1
fi
errors=0
# Check SKILL.md exists
if [ ! -f "$SKILL_DIR/SKILL.md" ]; then
echo "❌ Missing SKILL.md"
((errors++))
else
echo "✅ SKILL.md exists"
fi
# Check line count
lines=$(wc -l < "$SKILL_DIR/SKILL.md")
if [ "$lines" -gt 500 ]; then
echo "⚠️ SKILL.md is $lines lines (target: <500)"
else
echo "✅ SKILL.md is $lines lines"
fi
# Check for NOT clause in description
if grep -q "NOT for" "$SKILL_DIR/SKILL.md"; then
echo "✅ Description has NOT clause"
else
echo "❌ Missing NOT clause in description"
((errors++))
fi
exit $errors---
MCP Servers
When to Build an MCP
- Skill needs external API access (GitHub, Figma, databases, etc.)
- OAuth or API key authentication required
- Stateful connections (websockets, streaming)
- Rate limiting or caching needed
MCP Server Structure
mcp-server/
├── src/
│ └── index.ts # Server implementation
├── package.json # Dependencies and scripts
├── tsconfig.json # TypeScript config
└── README.md # Installation instructionsExample: Minimal MCP Server
// src/index.ts
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
const server = new Server(
{ name: "my-skill-mcp", version: "1.0.0" },
{ capabilities: { tools: {} } }
);
// Define tools
server.setRequestHandler("tools/list", async () => ({
tools: [
{
name: "analyze_repo",
description: "Analyze a GitHub repository structure",
inputSchema: {
type: "object",
properties: {
repo: { type: "string", description: "owner/repo format" }
},
required: ["repo"]
}
}
]
}));
server.setRequestHandler("tools/call", async (request) => {
const { name, arguments: args } = request.params;
if (name === "analyze_repo") {
// Actual implementation
const result = await analyzeRepo(args.repo);
return { content: [{ type: "text", text: JSON.stringify(result) }] };
}
throw new Error(`Unknown tool: ${name}`);
});
// Start server
const transport = new StdioServerTransport();
await server.connect(transport);package.json
{
"name": "my-skill-mcp",
"version": "1.0.0",
"type": "module",
"bin": { "my-skill-mcp": "dist/index.js" },
"scripts": {
"build": "tsc",
"start": "node dist/index.js"
},
"dependencies": {
"@modelcontextprotocol/sdk": "^1.0.0"
},
"devDependencies": {
"typescript": "^5.0.0"
}
}README Template
# My Skill MCP Server
MCP server for [domain] operations.
## Installation
\`\`\`bash
cd mcp-server
npm install
npm run build
\`\`\`
## Configuration
Add to your Claude Code MCP settings:
\`\`\`json
{
"mcpServers": {
"my-skill": {
"command": "node",
"args": ["/path/to/mcp-server/dist/index.js"],
"env": {
"API_KEY": "your-api-key"
}
}
}
}
\`\`\`
## Tools
- `analyze_repo` - Analyze a GitHub repository structure
- `fetch_issues` - Get open issues with labels---
Subagents
When to Define Subagents
- Skill involves multi-step workflows
- Different phases need different tool access
- Orchestration logic is complex enough to warrant isolation
Subagent Definition Format
# agents/research-workflow.md
## Agent: Research Coordinator
### Purpose
Orchestrate multi-source research with synthesis.
### System Prompt
You are a research coordinator. Your job is to:
1. Break down research questions into searchable queries
2. Dispatch searches to appropriate sources
3. Synthesize findings into coherent answers
### Tools Required
- WebSearch
- WebFetch
- Read
- Write
### Workflow
1. Receive research question
2. Generate 3-5 search queries
3. Execute searches in parallel
4. Read and extract relevant content
5. Synthesize into final answer
### Success Criteria
- All claims have citations
- Multiple sources corroborate findings
- Contradictions are explicitly notedMulti-Agent Orchestration Pattern
# agents/orchestrator.md
## Pipeline: Code Review
### Agents
1. **security-scanner** - Check for vulnerabilities
2. **style-checker** - Verify code style
3. **architecture-reviewer** - Assess design patterns
### Orchestration
\`\`\`
parallel:
- security-scanner → security_report
- style-checker → style_report
then:
- architecture-reviewer(security_report, style_report) → final_review
\`\`\`
### Handoff Protocol
Each agent produces structured output:
- `status`: pass | warn | fail
- `findings`: list of issues
- `recommendations`: suggested fixes---
Anti-Patterns
Phantom Tools
What it looks like: SKILL.md references scripts/analyze.py but file doesn't exist
Why it's wrong: Users try to run non-existent code, lose trust in skill
Fix: Only reference tools that actually exist and work
Template Soup
What it looks like: Scripts are templates with # TODO: implement comments
Why it's wrong: User still has to do the implementation work
Fix: Ship working code or don't ship at all
Dependency Hell
What it looks like: Script requires 15 pip packages, specific Python version, system libraries
Why it's wrong: Most users won't complete setup
Fix: Minimize dependencies, prefer stdlib, document clearly
MCP Without Purpose
What it looks like: MCP server for operations that could be a simple script
Why it's wrong: Over-engineering; MCP has setup overhead
Fix: Use MCP only when you need: auth, state, external APIs, or caching
---
Checklist: Is My Skill Self-Contained?
□ Can a user start using this skill immediately?
□ Are all referenced scripts/tools actually present and working?
□ Do scripts have clear installation instructions?
□ Do scripts handle errors gracefully?
□ If MCP needed, is server implementation complete?
□ If subagents needed, are prompts and workflows defined?
□ Is there a validation script to check environment?
□ Does README explain how to set everything up?---
Examples of Self-Contained Skills
| Skill | Tools Included |
|---|---|
| clip-aware-embeddings | scripts/validate_clip_usage.py |
| site-reliability-engineer | scripts/validate-brackets.js, scripts/validate-liquid.js |
| skill-coach | scripts/validate_skill.py |
Goal: Every skill with repeatable operations should have working tools.
Designing Skills for Subagent Consumption
This guide covers how to design skills that subagents can load and use effectively. A Claude subagent that "loads up" skills well is: (1) a very focused role, (2) with a curated skill set pre-injected, and (3) a clear internal workflow for applying those skills to the user's task.
---
High-Level Architecture
Think of one subagent as "a specialist with a toolkit":
| Component | Purpose | Example |
|---|---|---|
| Role/system prompt | Defines domain and responsibilities | "You are a refactoring engineer for TypeScript monorepos" |
| Attached skills | Small, explicit set encoding methods/checklists/templates | refactor-plan-skill, code-review-skill |
| Tool and memory policy | What tools it may use, whether it keeps long-term memory | Code tools + tests, project memory |
| Communication protocol | How it receives tasks and reports back | Summary + artifacts + open questions |
The orchestrator hands the subagent a concrete sub-goal plus relevant context. The subagent's job is to solve it using its skills as standard operating procedures rather than improvising a new process each time.
---
Three Skill-Loading Layers
Layer 1: Preloaded (Always in Context)
For core behaviors, inject the full content of 2-5 key skills directly into the subagent's system context. These are always "present" — the subagent doesn't need to discover them mid-run.
When to preload:
- The skill defines the subagent's primary workflow
- The skill is needed for >80% of tasks the subagent handles
- The skill is small enough (<5k tokens) to keep in context
Layer 2: Dynamically Selected (Catalog-Based)
If you have many skills, don't load all of them. Instead, give the subagent:
- A short catalog (name + 1-line description for each skill)
- Instructions: "Before starting, scan the skill catalog and choose 1-3 skills whose purpose matches this task. If none match, fall back to generic reasoning."
The orchestrator can also pre-filter and only pass a relevant subset of skills along with the task.
Layer 3: Execution-Time (Protocol-Based)
The subagent treats each selected skill like a mini-protocol: 1. Read the skill's "When to use / When not to use" section → confirm applicability 2. Follow its numbered steps in order (adapt only if task constraints force it) 3. Respect its output contract (templates, JSON shapes, required headings) 4. Apply its QA/validation section last (run checklist over own output)
Make this explicit in the prompt: "When using a skill, reference its steps by number and confirm you've completed each one before returning your result."
---
Subagent Prompt Structure
Inside the subagent's prompt, maintain this stable four-section structure:
1. Identity and Purpose
You are the **[role]** for this system. You handle [narrow domain of tasks].
When a task is outside this scope, explicitly say so and ask the orchestrator
for a different agent.Keep the role narrow. "Refactoring engineer for TypeScript monorepos" is better than "code helper."
2. Skill Usage Meta-Rules
You have access to the following skills, which define your methods:
- Skill A: for doing X
- Skill B: for doing Y
- Skill C: for doing Z
When tackling a task, you must:
- Decide which skill(s) apply
- Follow their step-by-step workflow
- Use their output formats and checklistsThis tells the subagent that skills are standard operating procedures, not optional hints.
3. Task-Handling Loop
For each task you receive:
1) Restate the task in your own words
2) Select one or more skills that fit. If none fit well, say so.
3) If needed, ask 2-5 clarifying questions
4) Produce an internal plan (short, not user-visible unless asked)
5) Execute the skill workflow step by step
6) Run any validation / QA steps from the skill
7) Return:
(a) final answer/artifacts
(b) what skills you used
(c) assumptions and remaining risks4. Constraints and Priorities
Quality bar: [e.g., "never knowingly leave tests failing"]
Safety rules: [e.g., "never execute destructive operations without confirmation"]
Tie-breaking: [e.g., "if speed vs robustness conflict, pick robustness"]---
Orchestrator + Subagent Interaction Patterns
Single-Specialist Pattern
Orchestrator identifies that the request maps to one domain and routes entirely to that subagent:
User: "Refactor this module"
→ Orchestrator routes to Refactorer subagent
→ Refactorer uses refactor-plan-skill + code-review-skill
→ Returns refactored code + review summaryChain Pattern
Sequential handoff between specialized subagents:
Design API → Implement → Test
1. API-Designer subagent (design skills) → API spec
2. Implementer subagent (coding skills) → working code
3. QA subagent (testing skills) → test results + coverageEach receives the prior subagent's artifacts and uses its own skills to transform them.
Parallel Pattern
Independent subagents work concurrently:
parallel:
- Auth subagent → auth implementation
- Billing subagent → billing implementation
- UI subagent → frontend components
then:
- Orchestrator merges outputs, resolves conflicts---
Designing Skills That Subagents Consume Well
1. Explicit "When to Use" / "When Not to Use"
Subagents need clear applicability signals. A skill without these forces the subagent to guess:
## When to Use
✅ Existing code needs restructuring for maintainability
✅ Module has grown beyond 500 lines
✅ Tests exist and pass (safe to refactor)
## When NOT to Use
❌ Greenfield development (nothing to refactor)
❌ No test coverage (too risky without safety net)
❌ Performance optimization (different skill)2. Numbered Steps (Not Prose)
Subagents follow steps better than paragraphs. Steps are referenceable: "Completed step 3 of refactor-plan-skill."
## Process
1. Read the target module and identify code smells
2. Categorize smells by type (duplication, coupling, complexity)
3. Propose a refactor plan with before/after signatures
4. Execute changes in atomic commits
5. Run test suite after each commit
6. Self-review the diff using code-review-skill3. Output Contracts
Define what the skill produces so downstream agents or the orchestrator can consume it:
## Output Format
Return a JSON object:
{
"status": "pass" | "warn" | "fail",
"changes": ["list of files changed"],
"tests_passing": true | false,
"risks": ["list of remaining risks"],
"summary": "1-2 sentence description of what changed"
}4. QA/Validation Section
Every skill should end with a self-check:
## Validation
Before returning results, verify:
□ All tests still pass
□ No TODO comments left behind
□ Changes match the original plan
□ No unrelated files were modified5. Minimal Context Assumptions
Don't assume the subagent knows your project structure. Include paths, conventions, and setup steps in the skill itself or its references.
---
Concrete Example: Refactorer Subagent
Config
name: refactorer
description: "Use for non-trivial refactors or large cleanups in TypeScript."
tools: [Read, Write, Edit, Bash(npm:test, git:*)]
skills:
- refactor-plan-skill
- code-review-skill
- safe-refactor-skill
memory: projectPrompt Body
You are the **Refactorer** subagent for this repo. You:
- Design safe refactors
- Implement them in small, atomic steps
- Keep tests passing at every step
You have the following skills and must rely on them as your standard process:
- `refactor-plan-skill`: analyze current code and design a stepwise refactor plan
- `code-review-skill`: review diffs for correctness, style, and risk
- `safe-refactor-skill`: apply changes incrementally, validate after each change
For every task:
1) Restate the requested refactor
2) If unclear, ask 2-3 clarifying questions
3) Use `refactor-plan-skill` to propose a stepwise plan
4) Execute the plan, running tests after each logical chunk
5) Use `code-review-skill` to self-review your changes
6) Summarize: what changed, what skills you used, remaining risks---
Context Loading Best Practices
Keep References Separate
- Put only high-level process and triggers in SKILL.md
- Move bulky content (API specs, FAQs, examples, style guides) to
references/files - Reference by path and purpose: "see
references/api-guide.mdfor full endpoints"
Teach Lazy Loading
In the subagent's system prompt, make reference loading explicit:
When you need detailed information, read the specific reference file.
Never read large reference files "just in case." Only open them when
directly relevant to the current step of your plan.
If a file looks huge, skim the headings first and jump to the relevant section.Scope Narrowly
Progressive loading works best when each subagent:
- Has a narrow responsibility (not "do all marketing" but "draft landing pages")
- Points to its own small set of reference files
- Only loads focused subsets, keeping context lean
Use Summarized Intermediates
Have the subagent produce short internal summaries from large references ("key API constraints," "brand voice bullets") and work from those. Only re-open the original reference if something seems missing.
Avoid Eager Meta-Prompts
Never: "Read all reference files before you start." Instead: "Read only the minimal set of files required to answer the current question accurately."
---
Input/Output Contracts for Multi-Agent Pipelines
Define what each subagent expects and produces so agents can be composed:
Input Contract
## Expected Input
- `files`: List of file paths to analyze
- `focus`: One of "security" | "performance" | "readability"
- `prior_findings`: (optional) Output from a previous agentOutput Contract
## Output Format
{
"status": "pass" | "warn" | "fail",
"findings": [
{
"severity": "high" | "medium" | "low",
"file": "path/to/file.ts",
"line": 42,
"message": "Description of finding",
"recommendation": "How to fix"
}
],
"summary": {
"total_issues": 5,
"high": 1,
"medium": 2,
"low": 2
}
}Handoff Protocol
Each agent in a pipeline should produce structured output that the next agent can consume without transformation. Standardize on:
statusfield for pass/fail signalingfindingsarray for detailed resultssummaryobject for quick assessmentmetadataobject for timing, agent name, skills used
---
Anti-Patterns in Subagent Skill Design
1. Skill Without Output Contract
Problem: Subagent produces free-form text that downstream agents can't parse. Fix: Define explicit output format (JSON schema, markdown template with required sections).
2. Skill That Assumes Context
Problem: Skill says "check the config file" without specifying which one or where. Fix: Include paths, conventions, and any setup requirements.
3. Overly Broad Skill for Subagent
Problem: Subagent has a 50-skill catalog and spends half its context selecting. Fix: Orchestrator pre-filters to 2-5 relevant skills before dispatching.
4. No Applicability Check
Problem: Subagent blindly follows a skill even when it doesn't fit. Fix: Every skill needs "When to Use / When NOT to Use" so the subagent can check before committing.
5. Eager Reference Loading
Problem: Subagent loads all reference files "just in case" and blows context. Fix: Teach lazy loading in the subagent prompt; reference files loaded per-step, not upfront.