Subagents Skills Slash Commands Key Principles Patterns

Claude Code: Subagents, Skills & Slash Commands - Key Principles & Patterns #

Overview #

This document outlines the key principles and patterns for effectively using Subagents, Skills, and Slash Commands in Claude Code projects. These three capabilities form a powerful layered architecture for organizing AI-assisted development workflows.


🎯 The Three-Layer Architecture #

Claude Code provides three distinct capabilities that work together:

📋 SLASH COMMANDS → 🤖 SKILLS → 👥 SUBAGENTS
(Automation)        (Workflows)   (Delegation)

Each layer serves a specific purpose and follows distinct patterns. Understanding when and how to use each is critical for effective AI-assisted development.


📋 SLASH COMMANDS - Automation Scripts #

Purpose #

Automate complex, multi-step tasks with predefined logic and exact execution steps.

Structure #

---
model: claude-sonnet-4-5-20250929
description: Brief description of what this command does
argument-hint: [arg1] [arg2]
allowed-tools: Bash, Read, Write, Edit, Glob, Grep
---

# Command Name

## Purpose
What this command accomplishes

## Variables
- VAR1: $1 (description)
- VAR2: $2 (description)

## Instructions
Detailed step-by-step instructions...

## Workflow
1. Step one with exact commands
2. Step two with validation
3. Step three with error handling

## Report
Expected output format for the user

Key Principles #

Deterministic workflows - Exact steps are predefined and executed in sequence

Variables & arguments - Accept parameters via $1, $2, $ARGUMENTS, etc.

Self-contained - Complete automation from start to finish without user intervention

Detailed instructions - Comprehensive step-by-step guide (can be 200+ lines)

Report format - Structured output to communicate results clearly

Validation & error handling - Check preconditions and handle failures gracefully

Tool restrictions - Limit available tools with allowed-tools for safety

When to Use Slash Commands #

  • Complex automation that needs exact execution
  • Multi-step processes with clear, sequential flow
  • Operations requiring precise control (file operations, git commands, deployments)
  • Tasks you’ll run repeatedly with different inputs
  • Building blocks that Skills and Subagents can call

Best Practices #

  1. Be exhaustively detailed - Don’t assume Claude knows the steps
  2. Include validation - Check preconditions before acting, verify results after
  3. Provide clear reports - Structured output with status, URLs, next steps
  4. Handle edge cases - What if files don’t exist? Ports are in use? Branch already exists?
  5. Use variables - Make commands reusable with parameters
  6. Document thoroughly - Include purpose, variables, workflow, and expected outcomes

Examples of Good Use Cases #

  • Creating isolated development environments (worktrees, Docker containers)
  • Running complex build/test/deploy pipelines
  • Multi-step data processing workflows
  • Automated code generation with templates
  • System setup and configuration tasks

🤖 SKILLS - Interactive Workflows #

Purpose #

Package domain expertise for on-demand discovery and execution. Skills are like hiring a specialist who knows multiple procedures and can decide which to use.

Structure #

---
name: skill-name
description: What this skill does and when to use it. Include trigger keywords.
allowed-tools: SlashCommand, Bash, Read, Write, Edit, Glob, Grep
---

# Skill Name

## When to use this skill
Clear description of scenarios where this skill applies

## Instructions
Step-by-step guidance for Claude on how to use this skill

## Decision Tree
Help Claude decide which operations to perform based on user intent

## Examples
Concrete examples of using this skill in various scenarios

Key Principles #

Progressive disclosure - Three levels of context:

  1. Metadata (always loaded): name and description in YAML frontmatter
  2. Instructions (loaded when triggered): Main body of SKILL.md
  3. Resources (loaded as needed): Additional files, scripts, templates

Discovery-based - Claude finds and loads the skill based on user intent and description

Composable - Skills can call slash commands internally for actual execution

Decision trees - Help Claude choose the right action from multiple options

Multi-file support - Split complex content across multiple markdown files:

  • SKILL.md - Main instructions and overview
  • OPERATIONS.md - Detailed operation guides
  • EXAMPLES.md - Usage examples
  • REFERENCE.md - Quick reference
  • TROUBLESHOOTING.md - Common issues

Clear triggers - Description must include BOTH what it does AND when to use it

When to Use Skills #

  • Domain-specific expertise (video processing, API testing, database management)
  • When user needs guidance on multiple related operations
  • Workflows that require decision-making based on context
  • Capabilities you want Claude to discover automatically
  • Orchestrating multiple slash commands
  • Providing context and best practices for a domain

Progressive Disclosure in Practice #

Level 1: Always loaded (lightweight)

---
name: worktree-manager
description: Manages git worktrees. Use when user wants to create, remove, or list worktrees.
---

Level 2: Loaded when triggered

# Worktree Manager

## Decision Tree

- User wants to CREATE → use /create_worktree
- User wants to LIST → use /list_worktrees
- User wants to REMOVE → use /remove_worktree

Level 3: Loaded as needed

For detailed creation steps, see [operations.md](operations.md)
For troubleshooting, see [troubleshooting.md](troubleshooting.md)

Best Practices #

  1. Write excellent descriptions - This determines if/when Claude loads your skill

    • ✅ “Transcribes audio/video files to text using Whisper. Use when user asks to transcribe, convert speech to text, or needs transcripts.”
    • ❌ “Helps with audio”
  2. Keep main instructions focused - Under 5k tokens ideal, split complex content

  3. Use decision trees - Help Claude choose between operations

  4. Reference, don’t duplicate - Call slash commands instead of reimplementing logic

  5. Split by topic - Multiple focused files better than one massive file

  6. Include examples - Show 2-4 concrete usage scenarios

  7. Test discoverability - Ask questions matching your description, verify Claude loads it

  8. One skill = one capability - Don’t combine unrelated tasks

Skill Organization Patterns #

Pattern 1: Simple skill (single file)

.claude/skills/code-review/
└── SKILL.md

Pattern 2: Multi-file skill

.claude/skills/worktree-manager/
├── SKILL.md           # Overview & decision tree
├── OPERATIONS.md      # Detailed operations
├── EXAMPLES.md        # Usage examples
└── TROUBLESHOOTING.md # Common issues

Pattern 3: Skill with scripts

.claude/skills/video-processor/
├── SKILL.md
├── scripts/
│   ├── extract_audio.py
│   └── transcribe.py
└── templates/
    └── output_template.md

Examples of Good Use Cases #

  • Managing complex subsystems (git worktrees, Docker environments, databases)
  • Domain-specific workflows (video processing, data analysis, API testing)
  • Multi-operation capabilities (create/list/remove, analyze/visualize/report)
  • Technical documentation (style guides, architecture patterns)
  • Code quality workflows (review, refactor, test generation)

👥 SUBAGENTS - Specialized Delegation #

Purpose #

Delegate specific tasks to isolated agent instances with focused responsibilities and separate context/memory from the main agent.

Structure #

---
name: specialist-subagent
description: Use when the user explicitly asks for a SUBAGENT to do X. Only trigger on explicit delegation requests.
tools: SlashCommand, Bash, Read, Write, Edit, Glob, Grep
model: sonnet
color: green
---

# Purpose
You are a specialist for X. Your sole responsibility is...

## Instructions
- DO use the appropriate slash command
- DO NOT attempt manual implementation
- The slash command is fully automated

## Workflow
1. Parse the user's request
2. Invoke the slash command
3. Wait for completion
4. Report results

## Examples
Concrete examples of requests and how to handle them

Key Principles #

Explicit trigger - Only used when user explicitly requests delegation

  • “Use a subagent to create a worktree”
  • “Delegate this to a subagent”
  • “Spawn a subagent to handle this”

Single responsibility - Focused on one specific task or domain

Isolated context - Separate conversation/memory from main agent

Delegates to slash commands - Subagent → Slash Command pattern is best practice (don’t reimplement)

  • ⚠️ Important: Only use this pattern when isolation adds real value
  • Subagent should provide benefit beyond just calling the slash command
  • If no added value, consider using a skill instead

Clear boundaries - Description states exactly when to trigger (and when NOT to)

Visual distinction - Color coding for observability and debugging

Model selection - Choose appropriate model (sonnet for complex, haiku for simple)

When to Use Subagents #

  • User explicitly requests delegation or parallel work
  • Long-running background tasks that shouldn’t block main conversation
  • Parallel execution of multiple independent operations
  • When you want completely isolated context/memory
  • Tasks that benefit from specialized focus
  • Comparative analysis (run multiple subagents with different approaches)

When NOT to Use Subagents #

  • User didn’t explicitly request delegation
  • Simple tasks that can be handled by main agent
  • When you want to maintain conversation context
  • Sequential dependent operations
  • When a skill would suffice

Best Practices #

  1. Require explicit triggers - Don’t auto-spawn subagents, user must request them

  2. Keep them simple - Subagents should call slash commands, not implement complex logic

  3. Single responsibility - One subagent = one focused task

  4. Clear descriptions - State explicitly when to trigger AND when not to trigger

  5. Choose model wisely - Sonnet for complex reasoning, Haiku for simple execution

  6. Report back clearly - Main agent needs to know what the subagent accomplished

  7. Handle failures gracefully - Report errors back to main agent for user communication

Subagent Patterns #

Pattern 1: Execution specialist

---
description: Use when user explicitly asks for SUBAGENT to create worktree
---

Purpose: Execute the /create_worktree command
Don't: Implement creation logic manually

Pattern 2: Research specialist

---
description: Use when user explicitly asks for SUBAGENT to research documentation
---

Purpose: Fetch and analyze docs, return summary
Don't: Make changes to codebase

Pattern 3: Parallel workers

Multiple subagents running simultaneously:

- Subagent A: Analyze approach X
- Subagent B: Analyze approach Y
- Main agent: Compare and synthesize results

Examples of Good Use Cases #

  • Parallel experimentation (multiple approaches simultaneously)
  • Background documentation fetching while main agent continues
  • Isolated codebase analysis (explore without polluting main context)
  • Long-running operations (benchmarks, tests, builds)
  • Comparative analysis (different models, different strategies)

⚠️ Important: When Subagent → Slash Command Makes Sense #

The “Subagent calls Slash Command” pattern is good practice, BUT only when the subagent layer provides real value:

✅ Good - Subagent adds value:

# Parallel execution benefit
User: "Use 3 subagents to create worktrees for feature-a, feature-b, and feature-c in parallel"
→ Each subagent calls /create_worktree independently
→ Isolation enables true parallel execution

# Context isolation benefit
User: "Use a subagent to research the codebase while I continue working"
→ Subagent explores without polluting main conversation
→ Returns summary when done

# Complex orchestration benefit
User: "Use a subagent to fetch docs, analyze them, and create a summary"
→ Subagent calls /fetch_docs slash command
→ Then analyzes results and synthesizes
→ More than just a wrapper

❌ Questionable - Subagent adds no value:

# Simple wrapper with no benefit
User: "Create a worktree for feature-x"
→ Don't: Spawn subagent just to call /create_worktree
→ Do: Use skill to call /create_worktree directly
→ Why: No benefit from isolation, just overhead

# Better alternative: Let skill handle it
User: "Create a worktree for feature-x"
→ Skill discovers intent
→ Skill calls /create_worktree
→ Faster, simpler, same result

Key Decision Points:

  1. Did user explicitly request a subagent?

    • YES → Consider using subagent
    • NO → Use skill instead
  2. Does isolation provide concrete benefit?

    • Parallel execution needed? → YES, use subagent
    • Long-running without blocking? → YES, use subagent
    • Complex multi-step orchestration? → YES, use subagent
    • Just passing through to slash command? → NO, use skill
  3. Is the subagent doing more than calling the command?

    • Fetching additional context? → YES, valuable
    • Analyzing or transforming results? → YES, valuable
    • Just invoking with arguments? → NO, use skill

Rule of Thumb: If you can achieve the same result with a skill calling a slash command, skip the subagent layer unless explicitly requested by the user.


🔄 The Layered Call Pattern #

Understanding how these three layers interact is crucial for effective design.

Standard Flow (via Skill) #

USER REQUEST
    ↓
SKILL (discovers based on intent, decides what to do)
    ↓
SLASH COMMAND (executes automation)
    ↓
TOOLS (Bash, Read, Write, etc.)

Delegated Flow (via Subagent) #

USER REQUEST (explicit delegation)
    ↓
SUBAGENT (spawns with isolated context)
    ↓
SLASH COMMAND (executes automation)
    ↓
TOOLS (Bash, Read, Write, etc.)

Direct Flow (advanced users) #

USER REQUEST (/create_worktree feature-auth)
    ↓
SLASH COMMAND (executes automation)
    ↓
TOOLS (Bash, Read, Write, etc.)

Why This Layering Matters #

Separation of Concerns

  • Slash commands handle EXECUTION
  • Skills handle DECISION-MAKING
  • Subagents handle ISOLATION

Reusability

  • One slash command, many callers (skills, subagents, direct users)
  • No duplication of complex logic
  • Single source of truth

Maintainability

  • Update slash command → all callers benefit
  • Skills can evolve decision logic without changing execution
  • Subagents remain simple wrappers

Composition

  • Build complex capabilities from simple building blocks
  • Mix and match as needed
  • Easy to test each layer independently

📚 Critical Design Patterns #

1. Single Responsibility Principle #

Each layer does ONE thing well:

  • Slash Command: Execute predefined workflow ✓
  • Skill: Decide which operation to perform ✓
  • Subagent: Isolate execution context ✓

2. Progressive Disclosure #

Only load what’s needed, when it’s needed:

Always loaded:     YAML metadata (name, description) - ~100 bytes
Load on trigger:   Main instructions (SKILL.md body) - ~2-5k tokens
Load as needed:    Supporting files (*.md, scripts) - ~10k+ tokens

This keeps context windows efficient and focused.

3. Explicit Over Implicit #

Bad (implicit)

description: Helps with git worktrees

Good (explicit)

description: Manages git worktrees including create, list, and remove operations. Use when user wants to manage parallel development environments.

4. Composition Over Duplication #

Bad (duplication)

# In skill

1. Run git worktree add
2. Create .env files
3. Install dependencies
   ...

# In subagent

1. Run git worktree add
2. Create .env files
3. Install dependencies
   ...

Good (composition)

# In skill

Use /create_worktree command

# In subagent

Use /create_worktree command

# In slash command (single source of truth)

1. Run git worktree add
2. Create .env files
3. Install dependencies
   ...

5. Clear Trigger Conditions #

Be explicit about when each capability should activate:

Slash Command

description: Create a git worktree with isolated configuration
argument-hint: [branch-name] [port-offset]

Skill

description: Manages worktrees. Use when user wants to create, remove, list, or manage worktrees.

Subagent

description: Use when user explicitly asks for SUBAGENT to create worktree. If user does not mention "subagent", do NOT trigger.

6. Fail Fast with Validation #

All three layers should validate early:

## Workflow

### 1. Validate Arguments

- Check required parameters present
- Validate format/constraints
- Error immediately if invalid

### 2. Check Preconditions

- Verify dependencies installed
- Check permissions
- Confirm resources available
- Error if preconditions not met

### 3. Execute Operation

- Now that validation passed, execute safely

### 4. Verify Results

- Confirm operation succeeded
- Check expected outcomes
- Report any issues

7. Structured Reporting #

Consistent output format helps users understand results:

## Report Format

✅ Operation Completed Successfully

📁 Details:

- Key information
- Relevant paths
- Status indicators

🌐 Access:

- URLs or entry points
- How to use the result

📝 Next Steps:

- What user should do next
- Related commands
- Documentation links

⚡ Decision Matrix: When to Use What #

Scenario Use This Why
“Create a worktree for feature-x” Skill Auto-discovers based on intent
“Use a subagent to create worktree” Subagent Explicit delegation request
/create_worktree feature-x Slash Command Direct invocation
Need to orchestrate multiple operations Skill Decision tree + multiple commands
Need isolated context/memory Subagent Separate conversation
Repeated automation (same steps) Slash Command Efficient execution
Domain expertise (teach Claude) Skill Package knowledge
Parallel independent tasks Multiple Subagents Concurrent execution
Complex automation (50+ steps) Slash Command Deterministic flow
User learning curve matters Skill Discoverable by description

🎨 File Organization #

Directory Structure #

your-project/
├── .claude/
│   ├── commands/              # Slash commands
│   │   ├── create_thing.md
│   │   ├── deploy_app.md
│   │   └── run_tests.md
│   │
│   ├── skills/                # Skills
│   │   ├── thing-manager/
│   │   │   ├── SKILL.md
│   │   │   ├── OPERATIONS.md
│   │   │   └── EXAMPLES.md
│   │   │
│   │   └── deployment-specialist/
│   │       └── SKILL.md
│   │
│   ├── agents/                # Subagents
│   │   ├── thing_creator_subagent.md
│   │   └── doc_fetcher_subagent.md
│   │
│   └── settings.json          # Hook configuration

Naming Conventions #

Slash Commands (action-based)

  • create_worktree.md
  • deploy_to_production.md
  • run_integration_tests.md
  • Use underscores, action verbs

Skills (capability-based)

  • worktree-manager/
  • deployment-specialist/
  • video-processor/
  • Use hyphens, noun phrases

Subagents (role-based)

  • worktree_creator_subagent.md
  • docs_fetcher_subagent.md
  • code_reviewer_subagent.md
  • Use underscores, end with _subagent

🚀 Implementation Workflow #

Starting a New Capability #

Step 1: Start with a Slash Command

  • Define the core automation
  • Make it deterministic and well-tested
  • This is your foundation

Step 2: Add a Skill (if needed)

  • If users need discovery/guidance
  • If multiple related operations
  • If decision-making required

Step 3: Add Subagent (if needed)

  • Only if delegation makes sense
  • Only if isolation benefits users
  • Only if explicitly requested

Example: Building Worktree Management #

Phase 1: Slash Commands

Created:
- /create_worktree [branch] [port-offset]
- /list_worktrees
- /remove_worktree [branch]

Each is fully automated and tested.

Phase 2: Add Skill

Created: worktree-manager-skill/

Provides:
- Decision tree (create vs list vs remove)
- Best practices
- Calls the slash commands

Users can now say "manage my worktrees" and get help.

Phase 3: Add Subagent (optional)

Created: create_worktree_subagent.md

Provides:
- Isolated execution for parallel worktree creation
- Only triggers on explicit request
- Calls /create_worktree command

Advanced users can now say "use a subagent" for delegation.

💡 Mental Models #

The Restaurant Analogy #

Think of your Claude Code setup like a restaurant:

  • Slash Commands = Recipes

    • Exact step-by-step instructions
    • Anyone following the recipe gets same result
    • Stored in the cookbook (.claude/commands/)
  • Skills = Chefs

    • Know many recipes
    • Decide which recipe to use based on order
    • Can adapt and make decisions
    • Stored in the training manual (.claude/skills/)
  • Subagents = Guest Chefs

    • Brought in for special dishes
    • Work in separate kitchen station
    • Focus on one dish at a time
    • Return to main kitchen when done
    • Stored in the contractor directory (.claude/agents/)

The Company Analogy #

  • Slash Commands = Standard Operating Procedures (SOPs)

    • Document exactly how to do something
    • Step-by-step, no ambiguity
    • Anyone can follow them
  • Skills = Department Managers

    • Know multiple SOPs
    • Decide which SOP to use
    • Provide context and guidance
    • Handle multiple related operations
  • Subagents = Contractors

    • Brought in for specific jobs
    • Work independently with clear scope
    • Don’t need full company context
    • Report results when done

🎓 Learning Path #

Beginner #

  1. Start with Slash Commands

    • Create 1-2 simple automation commands
    • Learn the structure and patterns
    • Get comfortable with variables and workflows
  2. Observe Claude’s behavior

    • Watch how Claude executes commands
    • Notice where guidance would help
    • Identify repeated decision-making

Intermediate #

  1. Add Skills

    • Package your slash commands into discoverable skills
    • Write clear descriptions with trigger keywords
    • Create decision trees for multiple operations
    • Test discoverability
  2. Refine and split

    • Split large skills into multiple files
    • Use progressive disclosure
    • Add examples and troubleshooting

Advanced #

  1. Introduce Subagents

    • Identify tasks that benefit from isolation
    • Create focused subagents
    • Test parallel execution
    • Build orchestration patterns
  2. Optimize the system

    • Minimize context usage
    • Maximize reusability
    • Build composable capabilities
    • Create team standards

📊 Success Metrics #

How do you know your architecture is working well?

Good Signs ✅ #

  • New team members discover capabilities naturally
  • Claude rarely needs clarification on which operation to use
  • Slash commands are reused by multiple skills/subagents
  • Context windows stay manageable
  • Validation catches errors before execution
  • Reports provide clear next steps
  • Parallel execution works smoothly

Warning Signs ⚠️ #

  • Skills aren’t being discovered (bad descriptions)
  • Claude duplicates logic instead of calling commands
  • Context windows constantly hit limits
  • Users confused about which capability to use
  • Slash commands failing due to missing validation
  • Subagents being used when skills would suffice
  • Lots of duplication across files

🔧 Troubleshooting Common Issues #

Issue: Skill Not Being Discovered #

Symptoms: User asks question but skill doesn’t load

Solutions:

  1. Improve description to include trigger keywords
  2. Add “Use when…” clause explicitly
  3. Test with exact user phrasing
  4. Make description more specific

Issue: Context Window Bloat #

Symptoms: Hitting token limits, slow responses

Solutions:

  1. Split large skills into multiple files
  2. Use progressive disclosure (load on demand)
  3. Keep slash command instructions focused
  4. Remove unnecessary examples

Issue: Slash Command Failures #

Symptoms: Commands fail mid-execution

Solutions:

  1. Add validation steps at the beginning
  2. Check preconditions before acting
  3. Improve error handling
  4. Add rollback procedures

Issue: Subagents Not Triggering #

Symptoms: Subagent doesn’t spawn when expected

Solutions:

  1. Make description more explicit about triggers
  2. Add negative examples (“Do NOT trigger when…”)
  3. Require specific keywords (“explicitly asks for SUBAGENT”)
  4. Test with exact delegation phrasing

Issue: Duplication Across Layers #

Symptoms: Same logic in multiple places

Solutions:

  1. Move logic to slash command (single source of truth)
  2. Have skills/subagents call the slash command
  3. Remove redundant implementations
  4. Add composition patterns

🎯 Key Takeaways #

  1. Slash Commands are your foundation - deterministic, reusable automation
  2. Skills provide discovery and decision-making - package expertise
  3. Subagents enable isolation and delegation - focused specialists
  4. Compose, don’t duplicate - build complex from simple
  5. Progressive disclosure - only load what’s needed
  6. Explicit triggers - clear about when to use what
  7. Validate early - catch errors before they cascade
  8. Report clearly - structured output for users
  9. Start simple - slash commands first, add layers as needed
  10. Test discoverability - verify Claude finds and uses your capabilities

📚 Additional Resources #

For deeper understanding of Claude Code capabilities:

  • Claude Code Documentation: Official guides for hooks, skills, subagents, and MCP servers
  • Progressive Disclosure: Techniques for managing context window efficiency
  • Agent Orchestration: Patterns for coordinating multiple agents
  • Prompt Engineering: Best practices for clear, effective instructions

Community & Support #

  • GitHub Issues: Report bugs and request features
  • Documentation Site: Latest updates and guides
  • Example Projects: Real-world implementations and patterns

🙏 Final Thoughts #

The layered architecture of Slash Commands, Skills, and Subagents enables you to build sophisticated AI-assisted development workflows that are:

  • Discoverable - Claude finds the right capability
  • Maintainable - Update in one place, benefit everywhere
  • Scalable - Add new capabilities without complexity explosion
  • Efficient - Only load what you need
  • Reliable - Validation and error handling throughout

Start simple, iterate based on usage, and build up your capability library over time. The key is composition: build complex behaviors from simple, well-tested building blocks.

Happy building! 🚀