Back to skills
SkillHub ClubShip Full StackFull StackIntegration

plugin-creation

Use when creating Claude Code plugins - covers skills, commands, agents, hooks, MCP servers, and plugin configuration. Use when user says "create plugin", "make a skill", "add command", "add hooks", etc.

Packaged view

This page reorganizes the original catalog entry around fit, installability, and workflow context first. The original raw source lives below.

Stars
17
Hot score
87
Updated
March 20, 2026
Overall rating
C2.1
Composite score
2.1
Best-practice grade
F39.6

Install command

npx @skill-hub/cli install camoa-claude-skills-plugin-creation

Repository

camoa/claude-skills

Skill path: plugin-creation-tools/skills/plugin-creation

Use when creating Claude Code plugins - covers skills, commands, agents, hooks, MCP servers, and plugin configuration. Use when user says "create plugin", "make a skill", "add command", "add hooks", etc.

Open repository

Best for

Primary workflow: Ship Full Stack.

Technical facets: Full Stack, Integration.

Target audience: everyone.

License: Unknown.

Original source

Catalog source: SkillHub Club.

Repository owner: camoa.

This is still a mirrored public skill entry. Review the repository before installing into production workflows.

What it helps with

  • Install plugin-creation into Claude Code, Codex CLI, Gemini CLI, or OpenCode workflows
  • Review https://github.com/camoa/claude-skills before adding plugin-creation to shared team environments
  • Use plugin-creation for development workflows

Works across

Claude CodeCodex CLIGemini CLIOpenCode

Favorites: 0.

Sub-skills: 0.

Aggregator: No.

Original source / Raw SKILL.md

---
name: plugin-creation
description: Use when creating Claude Code plugins - covers skills, commands, agents, hooks, MCP servers, and plugin configuration. Use when user says "create plugin", "make a skill", "add command", "add hooks", etc.
---

# Plugin Creation

Create complete Claude Code plugins with any combination of components.

## When to Use

- "Create a plugin" / "Make a new plugin"
- "Add a skill" / "Create command" / "Make agent"
- "Add hooks" / "Setup MCP server"
- "Configure settings" / "Setup output directory"
- "Package for marketplace"
- NOT for: Using existing plugins (see /plugin command)

## Quick Reference

| Component | Location | Invocation | Best For |
|-----------|----------|------------|----------|
| Skills | `skills/name/SKILL.md` | Model-invoked (auto) | Complex workflows with resources |
| Commands | `commands/name.md` | User (`/command`) | Quick, frequently used prompts |
| Agents | `agents/name.md` | Auto + Manual | Task-specific expertise |
| Hooks | `hooks/hooks.json` | Event-triggered | Automation and validation |
| MCP | `.mcp.json` | Auto startup | External tool integration |

## Before Creating

1. Read `references/01-overview/component-comparison.md` to decide which components needed
2. Determine if this should be a new plugin or add to existing

## Plugin Initialization

When user says "create plugin", "initialize plugin", "new plugin":

**Option A - Use init script**:
```bash
python scripts/init_plugin.py my-plugin --path ./plugins --components skill,command,hook
```

**Option B - Manual creation**:

1. Create plugin directory structure:
   ```
   plugin-name/
   ├── .claude-plugin/
   │   └── plugin.json
   ├── commands/        # if needed
   ├── agents/          # if needed
   ├── skills/          # if needed
   │   └── skill-name/
   │       └── SKILL.md
   ├── hooks/           # if needed
   │   └── hooks.json
   └── .mcp.json        # if needed
   ```

2. Copy template from `templates/plugin.json.template`

3. Ask user which components they need

## Creating Skills

When user says "add skill", "create skill", "make skill":

1. Read `references/03-skills/writing-skillmd.md` for structure
2. Copy template from `templates/skill/SKILL.md.template`
3. Key requirements:
   - Name: lowercase, hyphens, max 64 chars
   - Description: WHAT it does + WHEN to use it, max 1024 chars, third person
   - Body: imperative instructions, under 500 lines
   - Use progressive disclosure - reference files for details

**Critical**: SKILL.md files are INSTRUCTIONS for Claude, not documentation. Write imperatives telling Claude what to do.

| Documentation (WRONG) | Instructions (CORRECT) |
|----------------------|------------------------|
| "This skill helps with PDF processing" | "Process PDF files using this workflow" |
| "The description field is important" | "Write the description starting with 'Use when...'" |

## Creating Commands

When user says "add command", "create command", "slash command":

1. Read `references/04-commands/writing-commands.md`
2. Copy template from `templates/command/command.md.template`
3. Key requirements:
   - Frontmatter: description, allowed-tools, argument-hint
   - Support `$ARGUMENTS`, `$1`, `$2` for arguments
   - Prefix lines with exclamation mark for bash execution
   - Prefix lines with at-sign for file references

## Creating Agents

When user says "add agent", "create agent", "make agent":

1. Read `references/05-agents/writing-agents.md`
2. Copy template from `templates/agent/agent.md.template`
3. Key requirements:
   - Frontmatter: name, description, tools, model, permissionMode
   - Description should include "Use proactively" for auto-delegation
   - One agent = one clear responsibility

## Creating Hooks

When user says "add hooks", "setup hooks", "event handlers":

1. Read `references/06-hooks/writing-hooks.md`
2. Read `references/06-hooks/hook-events.md` for event types
3. Copy template from `templates/hooks/hooks.json.template`
4. Key events:
   - `PreToolUse` - before tool execution
   - `PostToolUse` - after tool execution (formatting, logging)
   - `SessionStart` - setup, output directories
   - `SessionEnd` - cleanup
   - `UserPromptSubmit` - validation, context injection

## Configuring Plugin

When user says "configure plugin", "setup plugin.json":

1. Read `references/08-configuration/plugin-json.md` for full schema
2. Required fields: `name`
3. Recommended fields: `version`, `description`, `author`, `license`
4. Component paths: `commands`, `agents`, `hooks`, `mcpServers`

## Settings and Output

When user says "configure settings", "setup output", "output directory":

1. Read `references/08-configuration/settings.md` for settings hierarchy
2. Read `references/08-configuration/output-config.md` for output patterns
3. Key environment variables:
   - `${CLAUDE_PLUGIN_ROOT}` - plugin installation directory
   - `${CLAUDE_PROJECT_DIR}` - project root
   - `${CLAUDE_ENV_FILE}` - persistent env vars (SessionStart only)
4. Use SessionStart hook to create output directories

## Testing Plugin

When user says "test plugin", "validate plugin":

1. Read `references/09-testing/testing.md`
2. Run `claude --debug` to see plugin loading
3. Validate plugin.json syntax
4. Test each component:
   - Skills: Ask questions matching description
   - Commands: Run `/command-name`
   - Agents: Check `/agents` listing
   - Hooks: Trigger events manually

## Packaging for Marketplace

When user says "package plugin", "publish plugin", "marketplace":

1. Read `references/10-distribution/packaging.md`
2. Create `marketplace.json` in repository root
3. Update README with installation instructions
4. Version using semantic versioning (MAJOR.MINOR.PATCH)

## Decision Framework

Before creating a component, verify it's the right choice:

| Component | Use When |
|-----------|----------|
| Skill | Complex workflow, needs resources, auto-triggered by context |
| Command | User should trigger explicitly, quick one-off prompts |
| Agent | Specialized expertise, own context window, proactive delegation |
| Hook | Event-based automation, validation, logging |
| MCP | External API/service, custom tools, database access |

**The 5-10 Rule**: Done 5+ times? Will do 10+ more? Create a skill or command.

## References

### Overview
- `references/01-overview/what-are-plugins.md` - Plugin overview
- `references/01-overview/what-are-skills.md` - Skills overview
- `references/01-overview/what-are-commands.md` - Commands overview
- `references/01-overview/what-are-agents.md` - Agents overview
- `references/01-overview/what-are-hooks.md` - Hooks overview
- `references/01-overview/what-are-mcp.md` - MCP overview
- `references/01-overview/component-comparison.md` - When to use what

### Philosophy
- `references/02-philosophy/core-philosophy.md` - Design principles
- `references/02-philosophy/decision-frameworks.md` - Decision trees
- `references/02-philosophy/anti-patterns.md` - What to avoid

### Components
- `references/03-skills/` - Skill creation guides
- `references/04-commands/` - Command creation guides
- `references/05-agents/` - Agent creation guides
- `references/06-hooks/` - Hook creation guides
- `references/06-hooks/cross-platform-hooks.md` - Windows/macOS/Linux support
- `references/07-mcp/` - MCP overview

### Configuration
- `references/08-configuration/plugin-json.md` - Plugin manifest
- `references/08-configuration/marketplace-json.md` - Marketplace config
- `references/08-configuration/settings.md` - Settings hierarchy
- `references/08-configuration/output-config.md` - Output configuration

### Testing & Distribution
- `references/09-testing/testing.md` - Testing guide (all components)
- `references/09-testing/debugging.md` - Debugging guide
- `references/09-testing/cli-reference.md` - CLI commands reference
- `references/10-distribution/packaging.md` - Packaging guide
- `references/10-distribution/marketplace.md` - Marketplace guide
- `references/10-distribution/versioning.md` - Version strategy
- `references/10-distribution/complete-examples.md` - Full plugin examples

## Examples

Working example plugins in `examples/`:
- `examples/simple-greeter-plugin/` - Minimal plugin with one skill
- `examples/full-featured-plugin/` - Complete plugin with skill, commands, hooks

## Templates

All templates are in the `templates/` directory:
- `templates/skill/SKILL.md.template`
- `templates/command/command.md.template`
- `templates/agent/agent.md.template`
- `templates/hooks/hooks.json.template`
- `templates/hooks/run-hook.cmd.template` - Cross-platform hook wrapper
- `templates/plugin.json.template`
- `templates/marketplace.json.template`
- `templates/settings.json.template`
- `templates/mcp.json.template`

## Scripts

- `scripts/init_plugin.py` - Initialize new plugin with selected components
- `scripts/init_skill.py` - Initialize standalone skill
- `scripts/validate_skill.py` - Validate skill structure
- `scripts/package_skill.py` - Package skill for distribution


---

## Referenced Files

> The following files are referenced in this skill and included for context.

### scripts/init_plugin.py

```python
#!/usr/bin/env python3
"""
Plugin Initializer - Creates a new plugin from template

Usage:
    init_plugin.py <plugin-name> --path <path> [--components <components>]

Components:
    skill, command, agent, hook, mcp (comma-separated)

Examples:
    init_plugin.py my-tools --path ./plugins
    init_plugin.py enterprise-tools --path ./plugins --components command,agent,hook
    init_plugin.py doc-processor --path ./plugins --components skill
"""

import sys
import re
import json
from pathlib import Path


PLUGIN_JSON_TEMPLATE = """{
  "name": "%s",
  "version": "1.0.0",
  "description": "Brief description of plugin purpose",
  "author": {
    "name": "Your Name"
  },
  "license": "MIT"
}
"""

SKILL_TEMPLATE = """---
name: %s
description: Use when [triggers] - [what it does]. Keywords: [terms]
---

# %s

## When to Use
- [Trigger phrase 1]
- [Trigger phrase 2]
- NOT for: [exclusions]

## Workflow

1. Step one
2. Step two
3. Step three

## See Also
- `references/` - detailed documentation
"""

COMMAND_TEMPLATE = """---
description: Brief description of what this command does
allowed-tools: Read, Edit, Bash
argument-hint: [arg1] [arg2]
---

# %s

Execute this command to [purpose].

## Steps

1. First, [action]
2. Then, [action]
3. Finally, [action]

## Arguments

- `$1`: First argument (e.g., environment)
- `$2`: Second argument (e.g., version)
- `$ARGUMENTS`: All arguments
"""

AGENT_TEMPLATE = """---
name: %s
description: [Expertise]. Use proactively when [trigger conditions].
tools: Read, Grep, Glob
model: sonnet
---

# %s

## Role

[Detailed description of the agent's expertise and responsibilities]

## Capabilities

- [Capability 1]
- [Capability 2]
- [Capability 3]

## When to Use

Use this agent when:
- [Scenario 1]
- [Scenario 2]
"""

HOOKS_TEMPLATE = """{
  "description": "Plugin hooks for automation",
  "hooks": {
    "SessionStart": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "${CLAUDE_PLUGIN_ROOT}/scripts/setup-output.sh",
            "timeout": 30
          }
        ]
      }
    ],
    "PostToolUse": [
      {
        "matcher": "Write|Edit",
        "hooks": [
          {
            "type": "command",
            "command": "${CLAUDE_PLUGIN_ROOT}/scripts/example-hook.sh",
            "timeout": 30
          }
        ]
      }
    ],
    "SessionEnd": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "${CLAUDE_PLUGIN_ROOT}/scripts/cleanup.sh",
            "timeout": 30
          }
        ]
      }
    ]
  }
}
"""

SETUP_OUTPUT_SCRIPT = """#!/bin/bash
# SessionStart hook - Create output directories and set env vars
set -e

OUTPUT_DIR="${CLAUDE_PROJECT_DIR}/claude-outputs"

# Create directories
mkdir -p "${OUTPUT_DIR}/logs"
mkdir -p "${OUTPUT_DIR}/artifacts"
mkdir -p "${OUTPUT_DIR}/temp"

# Persist environment variables for session
if [ -n "${CLAUDE_ENV_FILE}" ]; then
  cat >> "${CLAUDE_ENV_FILE}" <<EOF
export PLUGIN_OUTPUT_DIR="${OUTPUT_DIR}"
export PLUGIN_LOG_FILE="${OUTPUT_DIR}/logs/session.log"
EOF
fi

echo "[$(date)] Output initialized at ${OUTPUT_DIR}" >> "${OUTPUT_DIR}/logs/setup.log"
exit 0
"""

CLEANUP_SCRIPT = """#!/bin/bash
# SessionEnd hook - Clean up temporary files
OUTPUT_DIR="${PLUGIN_OUTPUT_DIR:-${CLAUDE_PROJECT_DIR}/claude-outputs}"

# Remove temp files
rm -rf "${OUTPUT_DIR}/temp/"* 2>/dev/null || true

# Archive session log if exists
SESSION_LOG="${OUTPUT_DIR}/logs/session.log"
if [ -f "$SESSION_LOG" ] && [ -s "$SESSION_LOG" ]; then
  ARCHIVE_NAME="session-$(date +%Y%m%d-%H%M%S).log"
  mv "$SESSION_LOG" "${OUTPUT_DIR}/logs/${ARCHIVE_NAME}"
fi

exit 0
"""

HOOK_SCRIPT_TEMPLATE = """#!/bin/bash
# PostToolUse hook - Triggered after Write or Edit operations

# Access tool information via stdin (JSON)
# input=$(cat)

# Example: Log the operation
OUTPUT_DIR="${PLUGIN_OUTPUT_DIR:-./claude-outputs}"
echo "[$(date)] PostToolUse hook executed" >> "${OUTPUT_DIR}/logs/operations.log"

exit 0
"""

MCP_TEMPLATE = """{
  "server-name": {
    "command": "${CLAUDE_PLUGIN_ROOT}/servers/server-binary",
    "args": ["--config", "${CLAUDE_PLUGIN_ROOT}/config.json"],
    "env": {
      "LOG_LEVEL": "info"
    }
  }
}
"""

README_TEMPLATE = """# %s

Brief description of what this plugin does.

## Installation

```bash
/plugin marketplace add path/to/marketplace
/plugin install %s@marketplace-name
```

## Components

%s

## Usage

[How to use this plugin]

## Configuration

[Any configuration options]

## Output

If hooks are enabled, outputs are written to `claude-outputs/`:

```
claude-outputs/
├── logs/        # Session and operation logs
├── artifacts/   # Generated files
└── temp/        # Temporary files (cleaned on session end)
```

Add to `.gitignore`:
```
claude-outputs/
.claude/settings.local.json
```
"""


def title_case(name):
    """Convert hyphenated name to Title Case."""
    return ' '.join(word.capitalize() for word in name.split('-'))


def validate_name(name):
    """Validate plugin/component name follows conventions."""
    if not name:
        return False, "Name cannot be empty"
    if not re.match(r'^[a-z0-9-]+$', name):
        return False, "Name must be hyphen-case (lowercase letters, digits, hyphens only)"
    if name.startswith('-') or name.endswith('-') or '--' in name:
        return False, "Name cannot start/end with hyphen or have consecutive hyphens"
    if len(name) > 64:
        return False, f"Name too long ({len(name)} chars). Maximum is 64."
    return True, "Valid"


def init_plugin(plugin_name, path, components=None):
    """
    Initialize a new plugin directory with selected components.

    Args:
        plugin_name: Name of the plugin (hyphen-case)
        path: Directory where plugin folder should be created
        components: List of components to include (skill, command, agent, hook, mcp)

    Returns:
        Path to created plugin directory, or None if error
    """
    # Validate name
    valid, msg = validate_name(plugin_name)
    if not valid:
        print(f"Error: Invalid name: {msg}")
        return None

    if components is None:
        components = ['skill']  # Default to skill only

    plugin_dir = Path(path).resolve() / plugin_name

    if plugin_dir.exists():
        print(f"Error: Directory already exists: {plugin_dir}")
        return None

    try:
        plugin_dir.mkdir(parents=True, exist_ok=False)
        print(f"Created: {plugin_dir}")
    except Exception as e:
        print(f"Error creating directory: {e}")
        return None

    # Create .claude-plugin/plugin.json (required)
    try:
        claude_plugin_dir = plugin_dir / '.claude-plugin'
        claude_plugin_dir.mkdir()
        (claude_plugin_dir / 'plugin.json').write_text(
            PLUGIN_JSON_TEMPLATE % plugin_name
        )
        print("Created .claude-plugin/plugin.json")
    except Exception as e:
        print(f"Error creating plugin.json: {e}")
        return None

    plugin_title = title_case(plugin_name)
    component_list = []

    # Create components based on selection
    if 'skill' in components:
        try:
            skill_dir = plugin_dir / 'skills' / plugin_name
            skill_dir.mkdir(parents=True)
            (skill_dir / 'SKILL.md').write_text(
                SKILL_TEMPLATE % (plugin_name, plugin_title)
            )
            (skill_dir / 'references').mkdir()
            print(f"Created skills/{plugin_name}/SKILL.md")
            component_list.append(f"- **Skill**: `{plugin_name}`")
        except Exception as e:
            print(f"Error creating skill: {e}")

    if 'command' in components:
        try:
            cmd_dir = plugin_dir / 'commands'
            cmd_dir.mkdir()
            cmd_name = plugin_name.split('-')[0]  # Use first word
            (cmd_dir / f'{cmd_name}.md').write_text(
                COMMAND_TEMPLATE % plugin_title
            )
            print(f"Created commands/{cmd_name}.md")
            component_list.append(f"- **Command**: `/{cmd_name}`")
        except Exception as e:
            print(f"Error creating command: {e}")

    if 'agent' in components:
        try:
            agent_dir = plugin_dir / 'agents'
            agent_dir.mkdir()
            agent_name = plugin_name.replace('-', '-') + '-agent'
            (agent_dir / f'{agent_name}.md').write_text(
                AGENT_TEMPLATE % (agent_name, plugin_title + ' Agent')
            )
            print(f"Created agents/{agent_name}.md")
            component_list.append(f"- **Agent**: `{agent_name}`")
        except Exception as e:
            print(f"Error creating agent: {e}")

    if 'hook' in components:
        try:
            hooks_dir = plugin_dir / 'hooks'
            hooks_dir.mkdir()
            (hooks_dir / 'hooks.json').write_text(HOOKS_TEMPLATE)
            print("Created hooks/hooks.json")

            scripts_dir = plugin_dir / 'scripts'
            scripts_dir.mkdir(exist_ok=True)

            # SessionStart - output setup
            setup_script = scripts_dir / 'setup-output.sh'
            setup_script.write_text(SETUP_OUTPUT_SCRIPT)
            setup_script.chmod(0o755)
            print("Created scripts/setup-output.sh")

            # PostToolUse - example hook
            hook_script = scripts_dir / 'example-hook.sh'
            hook_script.write_text(HOOK_SCRIPT_TEMPLATE)
            hook_script.chmod(0o755)
            print("Created scripts/example-hook.sh")

            # SessionEnd - cleanup
            cleanup_script = scripts_dir / 'cleanup.sh'
            cleanup_script.write_text(CLEANUP_SCRIPT)
            cleanup_script.chmod(0o755)
            print("Created scripts/cleanup.sh")

            component_list.append("- **Hooks**: SessionStart, PostToolUse, SessionEnd")
            component_list.append("- **Output**: `claude-outputs/` directory (logs, artifacts, temp)")
        except Exception as e:
            print(f"Error creating hooks: {e}")

    if 'mcp' in components:
        try:
            (plugin_dir / '.mcp.json').write_text(MCP_TEMPLATE)
            print("Created .mcp.json")
            component_list.append("- **MCP Server**: server-name")
        except Exception as e:
            print(f"Error creating MCP config: {e}")

    # Create README
    try:
        components_text = '\n'.join(component_list) if component_list else '- None'
        (plugin_dir / 'README.md').write_text(
            README_TEMPLATE % (plugin_title, plugin_name, components_text)
        )
        print("Created README.md")
    except Exception as e:
        print(f"Error creating README: {e}")

    print(f"\nPlugin '{plugin_name}' initialized at {plugin_dir}")
    print("\nNext steps:")
    print("1. Edit plugin.json - update description and metadata")
    print("2. Complete component files with your content")
    print("3. Test locally: /plugin marketplace add ./path && /plugin install")
    print("4. Package for distribution")

    return plugin_dir


def main():
    if len(sys.argv) < 4 or sys.argv[2] != '--path':
        print("Usage: init_plugin.py <plugin-name> --path <path> [--components <list>]")
        print("\nComponents (comma-separated):")
        print("  skill   - Model-invoked capability")
        print("  command - User-invoked slash command")
        print("  agent   - Specialized assistant")
        print("  hook    - Event-triggered automation")
        print("  mcp     - MCP server configuration")
        print("\nExamples:")
        print("  init_plugin.py my-tools --path ./plugins")
        print("  init_plugin.py my-tools --path ./plugins --components command,hook")
        print("  init_plugin.py my-tools --path ./plugins --components skill,agent")
        sys.exit(1)

    plugin_name = sys.argv[1]
    path = sys.argv[3]

    # Parse optional components
    components = ['skill']  # Default
    for i, arg in enumerate(sys.argv):
        if arg == '--components' and i + 1 < len(sys.argv):
            components = [c.strip() for c in sys.argv[i + 1].split(',')]

    print(f"Initializing plugin: {plugin_name}")
    print(f"Location: {path}")
    print(f"Components: {', '.join(components)}\n")

    result = init_plugin(plugin_name, path, components)
    sys.exit(0 if result else 1)


if __name__ == "__main__":
    main()

```

### references/01-overview/component-comparison.md

```markdown
# Component Comparison - When to Use What

## Quick Reference Table

| Component | Location | Invocation | Best For |
|-----------|----------|------------|----------|
| Skills | `skills/name/SKILL.md` | Model-invoked (auto) | Complex workflows with resources |
| Commands | `commands/name.md` | User (`/command`) | Quick, frequently used prompts |
| Agents | `agents/name.md` | Auto + Manual | Task-specific expertise |
| Hooks | `hooks/hooks.json` | Event-triggered | Automation and validation |
| MCP | `.mcp.json` | Auto startup | External tool integration |

## Decision Tree

### Start Here: What triggers this capability?

```
1. Should the USER explicitly trigger it?
   └── YES → COMMAND

2. Should Claude trigger it automatically based on context?
   └── YES → SKILL or AGENT
       ├── Needs own context window? → AGENT
       └── Shares conversation context? → SKILL

3. Should it run automatically on events?
   └── YES → HOOK

4. Does it need external tools/APIs?
   └── YES → MCP SERVER
```

### Detailed Decision Questions

**Use a SKILL when:**
- Complex workflow with multiple steps
- Needs supporting files (scripts, references, templates)
- Claude should decide when to use it
- Benefits from progressive disclosure of resources
- Shares context with main conversation

**Use a COMMAND when:**
- User should control when it runs
- Simple, quick operation
- Frequently used prompt
- No supporting resources needed
- Explicit trigger is important

**Use an AGENT when:**
- Task requires specialized expertise
- Benefits from fresh context window
- Needs different tool permissions than main
- Should be delegated to automatically
- Complex multi-step operations

**Use a HOOK when:**
- Should run on specific events
- Automation without user intervention
- Validation before/after operations
- Logging and audit trails
- Session setup/cleanup

**Use MCP SERVER when:**
- External API integration needed
- Database access required
- Custom tools beyond Claude's built-ins
- Third-party service integration

## Comparison by Characteristic

### Context Management

| Component | Context |
|-----------|---------|
| Skill | Shares main conversation context |
| Command | Adds to main conversation |
| Agent | Own separate context window |
| Hook | Runs independently, no conversation |
| MCP | Tool calls, results in context |

### Complexity

| Low | Medium | High |
|-----|--------|------|
| Commands | Skills, Hooks | Agents, MCP |

### Discovery

| Component | How User Finds It |
|-----------|-------------------|
| Command | `/help`, autocomplete |
| Skill | Automatic (model decides) |
| Agent | `/agents`, automatic delegation |
| Hook | Invisible (event-based) |
| MCP | Shows as available tools |

## Common Combinations

### Code Quality Plugin
```
├── skills/code-audit/       # Complex audit workflow
├── commands/quick-lint.md   # Quick user-triggered lint
├── hooks/hooks.json         # Auto-format on save
└── agents/security-review.md # Security expertise
```

### Deployment Plugin
```
├── commands/deploy.md       # User-triggered deploy
├── commands/status.md       # Check status
├── hooks/hooks.json         # Pre-deploy validation
└── .mcp.json               # Cloud provider API
```

### Documentation Plugin
```
├── skills/doc-writer/       # Complex doc generation
├── agents/doc-reviewer.md   # Review expertise
└── commands/readme.md       # Quick README update
```

## The 5-10 Rule

**Create a skill or command when:**
- Done 5+ times
- Will do 10+ more times

**Don't create when:**
- One-off task
- Simple enough to type directly
- Project-specific (use CLAUDE.md instead)

## Anti-Patterns

| Anti-Pattern | Problem | Solution |
|--------------|---------|----------|
| Everything as commands | User fatigue | Use skills for auto-trigger |
| Multi-purpose agents | Confused delegation | One agent = one task |
| Global hook matchers | Performance impact | Specific matchers |
| MCP for simple things | Over-engineering | Use commands/skills |

## See Also

- Individual component guides in respective directories
- `../02-philosophy/decision-frameworks.md` - detailed decision trees

```

### references/03-skills/writing-skillmd.md

```markdown
# Writing Effective SKILL.md

Detailed guidance on voice, style, structure, and word count for SKILL.md files.

## The Critical Distinction

**SKILL.md files are INSTRUCTIONS for Claude, not documentation about the skill.**

This is the most common mistake. When Claude reads a SKILL.md, it needs to know what to DO, not what the skill IS.

| Documentation (WRONG) | Instructions (CORRECT) |
|----------------------|------------------------|
| "This skill processes PDFs" | "Process PDFs using this workflow" |
| "Skills extend Claude's capabilities" | "When triggered, follow these steps" |
| "The form filling feature supports..." | "To fill forms, run scripts/fill_form.py" |
| "What Are Skills?" | "## Workflow" |
| "Guide for creating skills" | "Follow this workflow to create a skill" |

**Test your SKILL.md**: Read each sentence and ask "Does this tell Claude what to DO?" If it explains what something IS, rewrite it.

## Voice and Style

| Do | Don't |
|----|-------|
| "To create a document, use..." | "You should create a document by..." |
| "Extract text with pdfplumber" | "If you need to extract text, you can..." |
| Third person descriptions | First/second person instructions |
| Imperative/infinitive form | Narrative storytelling |

### Examples

**Good (imperative, third person):**
```markdown
## Creating Documents
To create a new document, initialize a Document object and add paragraphs.
Run scripts/create_doc.py for templated creation.
```

**Bad (second person, narrative):**
```markdown
## Creating Documents
When you want to create a document, you should first think about what you need.
If you're making a report, you might want to start with a template...
```

## Recommended Structure

```markdown
---
name: skill-name
description: Use when [triggers] - [what it does]
---

# Skill Name

## Overview
[1-2 sentence purpose statement]

## When to Use
- [Specific trigger 1]
- [Specific trigger 2]
- NOT for: [anti-patterns]

## Core Pattern
[Essential technique or workflow]

## Quick Reference
| Operation | Command/Code |
|-----------|--------------|
| ... | ... |

## Implementation
[Step-by-step with examples]

## Common Mistakes
| Mistake | Fix |
|---------|-----|
| ... | ... |

## See Also
- references/detailed-guide.md
- scripts/helper.py
```

## Word Count Targets

| Skill Type | Target | When |
|------------|--------|------|
| Getting-started | <150 words | Loads every conversation |
| Frequently-loaded | <200 words | Used often |
| Standard skills | <500 words | Normal usage |
| Complex reference | <5000 words | Use progressive disclosure |

### Why These Limits?

- **<150 words**: Skills that load in every conversation (like `using-superpowers`) must be minimal
- **<200 words**: Frequently triggered skills should minimize context impact
- **<500 words**: Standard skills balance completeness with efficiency
- **<5000 words**: Complex skills MUST use progressive disclosure (references/)

## Line Count Target

**Keep SKILL.md under 500 lines.** If approaching this limit:
1. Move detailed content to `references/`
2. Link from SKILL.md: "See references/topic.md for..."
3. Keep only essential workflow in SKILL.md

## Frontmatter Requirements

```yaml
---
name: processing-pdfs
description: Extracts text and tables from PDF files, fills forms. Use when working with PDF files or when the user mentions PDFs, forms, or document extraction.
---
```

| Field | Required | Constraints |
|-------|----------|-------------|
| `name` | Yes | Lowercase, numbers, hyphens only. Max 64 chars. No "anthropic" or "claude". |
| `description` | Yes | Max 1024 chars. Must include WHAT and WHEN. Third person only. |
| `allowed-tools` | No | Restricts available tools when skill active |
| `license` | No | License for the skill |
| `metadata` | No | Custom key-value pairs |

**Do not add other fields.** Only these are recognized.

### Naming Convention

**Prefer gerund form** (verb + -ing) for skill names:

| Good (Gerund) | Acceptable | Avoid |
|---------------|------------|-------|
| `processing-pdfs` | `pdf-processing` | `pdf-helper` |
| `analyzing-code` | `code-analyzer` | `utils` |
| `managing-git` | `git-manager` | `tools` |

Reserved words not allowed: `anthropic`, `claude`

## Section Guidelines

### Overview
- 1-2 sentences maximum
- State the purpose clearly
- No background or history

### When to Use
- Bullet list of specific triggers
- Include "NOT for:" anti-patterns
- Match the description field

### Core Pattern
- The essential technique or workflow
- Scannable format (bullets, tables)
- One excellent example if needed

### Quick Reference
- Table format preferred
- Most common operations only
- Commands, not explanations

### Implementation
- Step-by-step when needed
- Reference files, don't reproduce
- Brief examples (5-15 lines max)

### Common Mistakes
- Table format: Mistake | Fix
- Real issues, not hypothetical
- Brief, actionable fixes

### See Also
- Link to references/ files
- Link to scripts/
- No external links unless critical

## Progressive Disclosure Patterns

### Pattern 1: Hub with References
```markdown
## PDF Processing

Quick start: `python scripts/process.py input.pdf`

For advanced features:
- **Form filling**: See references/forms.md
- **Merging**: See references/merge.md
- **OCR**: See references/ocr.md
```

### Pattern 2: Conditional Loading
```markdown
## Document Editing

For simple edits, modify content directly.

**For tracked changes**: See references/tracked-changes.md
**For complex formatting**: See references/formatting.md
```

### Pattern 3: Domain Organization
```
skill/
├── SKILL.md (overview + navigation)
└── references/
    ├── finance.md    # Load for finance questions
    ├── sales.md      # Load for sales questions
    └── support.md    # Load for support questions
```

## Reference File Guidelines

### Table of Contents for Long Files

For reference files longer than 100 lines, add a table of contents:

```markdown
# API Reference

## Contents
- Authentication and setup
- Core methods (create, read, update, delete)
- Advanced features (batch operations, webhooks)
- Error handling patterns
- Code examples

## Authentication and setup
...
```

### One Level Deep Only

**Avoid nested references.** All reference files should link directly from SKILL.md.

```
Bad (nested):
  SKILL.md → advanced.md → details.md → actual-info.md

Good (flat):
  SKILL.md → advanced.md
  SKILL.md → details.md
  SKILL.md → actual-info.md
```

### Avoid Time-Sensitive Information

Don't include dates or temporal references that will become outdated:

```markdown
# Bad
If you're doing this before August 2025, use the old API.

# Good
## Current method
Use the v2 API endpoint.

## Legacy patterns (deprecated)
<details>
<summary>v1 API (no longer supported)</summary>
...
</details>
```

## Testing Skills

### Test with Multiple Models

Skills behave differently across models. Test with:

| Model | Check For |
|-------|-----------|
| Claude Haiku | Does the skill provide enough guidance? |
| Claude Sonnet | Is the skill clear and efficient? |
| Claude Opus | Does the skill avoid over-explaining? |

### Create Evaluations

Build at least 3 test scenarios before finalizing:

```json
{
  "skills": ["pdf-processing"],
  "query": "Extract text from this PDF and save to output.txt",
  "files": ["test-files/document.pdf"],
  "expected_behavior": [
    "Reads the PDF using appropriate library",
    "Extracts text from all pages",
    "Saves to output.txt"
  ]
}
```

## Checklist Before Completion

### Core Quality
- [ ] Under 500 lines
- [ ] Imperative/third person voice
- [ ] Clear structure with headers
- [ ] One excellent example per pattern
- [ ] References linked, not duplicated
- [ ] No unnecessary content
- [ ] No time-sensitive information
- [ ] Consistent terminology throughout

### Frontmatter
- [ ] Name uses gerund form (preferred)
- [ ] Name is lowercase, hyphens only
- [ ] Description is third person
- [ ] Description includes WHAT and WHEN
- [ ] Description under 1024 chars

### References
- [ ] All references one level deep
- [ ] Files >100 lines have table of contents
- [ ] Progressive disclosure used appropriately

### Testing
- [ ] Tested with Haiku, Sonnet, Opus
- [ ] At least 3 evaluation scenarios
- [ ] Real usage scenarios tested

```

### references/04-commands/writing-commands.md

```markdown
# Writing Commands

Commands are markdown files that define slash commands for Claude Code. They provide user-invoked prompts that integrate with the command system.

## File Location

Place command files in:
```
plugin-name/
└── commands/
    ├── review.md
    ├── deploy.md
    └── frontend/        # Creates namespace: /frontend:component
        └── component.md
```

## Basic Structure

```markdown
---
description: Brief description of what the command does
allowed-tools: Bash(git:*), Read, Edit
argument-hint: [argument1] [argument2]
model: claude-3-5-haiku-20241022
---

# Command Name

Detailed instructions for Claude on how to execute this command.
Include specific guidance on parameters, expected outcomes, and special considerations.

## Usage
Instructions on how to use this command with examples.
```

## Frontmatter Fields

| Field | Type | Required | Default | Description |
|-------|------|----------|---------|-------------|
| description | string | **Yes** | - | Brief description (shown in `/help`) |
| allowed-tools | string | No | All | Comma-separated tool list |
| argument-hint | string | No | None | Hint for autocomplete |
| model | string | No | Inherit | Model to use |
| disable-model-invocation | bool | No | false | Prevent auto-invocation |

### disable-model-invocation Explained

When `true`, prevents Claude from invoking this command via the `SlashCommand` tool. The command remains available for direct user invocation (`/command-name`) but Claude cannot trigger it programmatically.

**Use when:**
- Command has side effects (deployments, deletions)
- Command requires explicit human decision
- Command is expensive or rate-limited

```yaml
---
description: Deploy to production (requires manual confirmation)
disable-model-invocation: true
---
```

## Description Best Practices

The description appears in `/help` and autocomplete. Write it well:

**Good**:
```yaml
description: Review current PR for code quality issues and suggest improvements
```

**Bad**:
```yaml
description: PR review
```

Include:
- What the command does
- When to use it
- Key context

## Allowed Tools

Restrict tool access when needed:

```yaml
# Read-only command
allowed-tools: Read, Grep, Glob

# Git operations only
allowed-tools: Bash(git:*)

# Full access
allowed-tools: Read, Edit, Bash, Write
```

If omitted, command inherits all available tools.

## Body Content

The body contains instructions for Claude. Write in imperative voice:

```markdown
# PR Review

Review the current pull request for:
1. Code quality issues
2. Potential bugs
3. Performance concerns
4. Security vulnerabilities

Use `git diff` to see changes. Check each file systematically.
Provide actionable feedback with specific line references.
```

## Example Commands

### Simple Review Command

```markdown
---
description: Quick code review of recent changes
allowed-tools: Bash(git:*), Read, Grep
---

# Quick Review

1. Run `git diff HEAD~1` to see recent changes
2. Identify any obvious issues
3. Provide brief summary of findings
```

### Deployment Command

```markdown
---
description: Deploy to staging environment after running tests
allowed-tools: Bash
argument-hint: [environment]
---

# Deploy

Deploy to the specified environment ($1, defaults to "staging").

1. Run test suite: `npm test`
2. If tests pass, run: `npm run deploy:$1`
3. Verify deployment with health check
4. Report success or failure
```

### Documentation Command

```markdown
---
description: Generate or update README documentation
allowed-tools: Read, Write, Glob
---

# Update README

1. Read existing README.md if present
2. Scan project structure
3. Update or create documentation covering:
   - Project overview
   - Installation
   - Usage
   - Configuration
```

## Naming Conventions

- Use lowercase with hyphens: `review-pr.md`, `deploy-staging.md`
- Be action-oriented: `optimize`, `analyze`, `generate`
- Avoid generic names: `help`, `run`, `do`

## Testing Commands

1. Install the plugin
2. Run `/command-name` with test arguments
3. Verify behavior matches expectations
4. Check `/help` shows correct description

## See Also

- `command-patterns.md` - advanced patterns (bash, files, namespacing)
- `command-arguments.md` - argument handling
- `../01-overview/what-are-commands.md` - when to use commands

```

### references/05-agents/writing-agents.md

```markdown
# Writing Agents

Agents are specialized AI assistants with their own context window and custom system prompts. They can be automatically delegated to or manually invoked.

## File Location

Place agent files in:
```
plugin-name/
└── agents/
    ├── code-reviewer.md
    ├── security-checker.md
    └── performance-analyst.md
```

## Basic Structure

```markdown
---
name: agent-name
description: Brief, action-oriented description of when to use this agent
capabilities: ["capability1", "capability2", "capability3"]
tools: Read, Grep, Glob, Bash
model: sonnet
permissionMode: default
skills: skill1, skill2
---

# Agent Name

## Role
Detailed description of the agent's role, expertise, and responsibilities.

## Capabilities
- Specific task the agent excels at
- Another specialized capability
- When to use this agent vs others

## Context and Examples
Provide realistic examples of when this agent should be used and what problems it solves.

## Decision Criteria
How this agent decides what to focus on. Any constraints or special considerations.
```

## Frontmatter Fields

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| name | string | **Yes** | Unique identifier (lowercase, hyphens) |
| description | string | **Yes** | When to invoke; used for auto-delegation |
| capabilities | array | No | List of specific tasks handled |
| tools | string | No | Comma-separated allowed tools |
| model | string | No | Model alias (sonnet, opus, haiku, inherit) |
| permissionMode | string | No | Permission handling mode |
| skills | string | No | Skills to auto-load |

## The Description Field

The description is **critical** for auto-delegation. Claude uses it to decide when to delegate tasks.

**Good descriptions**:
```yaml
# Encourages auto-delegation
description: Security specialist. Use proactively when reviewing code for vulnerabilities.

# Specific trigger conditions
description: Performance analyzer. Use when optimizing slow code or reducing memory usage.
```

**Bad descriptions**:
```yaml
# Too vague
description: Helps with code

# No trigger information
description: Reviews things
```

## Permission Modes

| Mode | Behavior |
|------|----------|
| default | Normal permission handling |
| acceptEdits | Auto-accept edit suggestions |
| bypassPermissions | Skip permission prompts |
| plan | Read-only mode |
| ignore | Ignore permission system |

## Body Content

The body becomes the agent's system prompt. Structure it clearly:

### Role Section

```markdown
## Role
Expert security analyst specializing in vulnerability detection, OWASP compliance,
and secure coding practices. Focus on identifying injection, XSS, and authentication issues.
```

### Capabilities Section

```markdown
## Capabilities
- Identify SQL injection, XSS, and command injection vulnerabilities
- Review authentication and authorization patterns
- Check for insecure dependencies
- Validate input sanitization
- Audit access control implementations
```

### Decision Criteria

```markdown
## Decision Criteria
Focus on:
1. Security-critical code paths (auth, input handling, database)
2. Changes to existing security controls
3. New external integrations

Prioritize by risk:
- Critical: Auth bypass, injection, data exposure
- High: Weak crypto, session issues
- Medium: Missing input validation
- Low: Informational findings
```

## Example Agents

### Code Reviewer Agent

```markdown
---
name: code-reviewer
description: Reviews code changes for quality, bugs, and best practices. Use proactively after code modifications.
capabilities: ["code quality", "bug detection", "best practices"]
tools: Read, Grep, Glob
model: sonnet
---

# Code Reviewer

## Role
Senior code reviewer focused on maintainability, correctness, and adherence to project conventions.

## Capabilities
- Identify logic errors and edge cases
- Check for code style consistency
- Spot performance anti-patterns
- Verify error handling completeness

## Review Process
1. Understand the change context
2. Check for correctness
3. Evaluate maintainability
4. Verify test coverage
5. Provide actionable feedback
```

### Documentation Writer Agent

```markdown
---
name: doc-writer
description: Creates and updates technical documentation. Use when generating README, API docs, or guides.
capabilities: ["technical writing", "API documentation", "user guides"]
tools: Read, Write, Glob
model: sonnet
---

# Documentation Writer

## Role
Technical writer creating clear, comprehensive documentation for developers.

## Capabilities
- Generate README files
- Create API reference documentation
- Write setup and installation guides
- Document configuration options

## Style Guidelines
- Use clear, concise language
- Include code examples
- Structure with headers and lists
- Target the intended audience
```

## Testing Agent Delegation

After creating an agent:

1. Run `/agents` to verify it appears in the list
2. Ask questions matching the description
3. Verify auto-delegation triggers appropriately
4. Adjust description if not triggering

## See Also

- `agent-patterns.md` - best practices and patterns
- `agent-tools.md` - tool configuration
- `../01-overview/what-are-agents.md` - when to use agents

```

### references/06-hooks/writing-hooks.md

```markdown
# Writing Hooks

Hooks are event handlers that execute automatically when specific events occur in Claude Code. They enable automation, validation, and logging without user intervention.

## File Location

Place hooks configuration in:
```
plugin-name/
└── hooks/
    └── hooks.json
```

Or inline in `plugin.json`:
```json
{
  "name": "my-plugin",
  "hooks": {
    "PostToolUse": [...]
  }
}
```

## Basic Structure

```json
{
  "description": "Description of what these hooks do",
  "hooks": {
    "EventName": [
      {
        "matcher": "ToolPattern",
        "hooks": [
          {
            "type": "command",
            "command": "${CLAUDE_PLUGIN_ROOT}/scripts/action.sh",
            "timeout": 30
          }
        ]
      }
    ]
  }
}
```

## Hook Configuration Fields

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| matcher | string | No | Pattern to match (regex, exact, or `*`) |
| hooks | array | **Yes** | Array of hook actions |
| type | string | **Yes** | Hook type (command, validation, notification, prompt) |
| command | string | Depends | Shell command to execute |
| timeout | number | No | Timeout in seconds (default varies) |
| prompt | string | Depends | LLM prompt (for prompt type) |

## Hook Types

### Command Hook

Execute a bash script:

```json
{
  "type": "command",
  "command": "${CLAUDE_PLUGIN_ROOT}/scripts/format.sh",
  "timeout": 30
}
```

### Validation Hook

Validate input/output:

```json
{
  "type": "validation",
  "command": "${CLAUDE_PLUGIN_ROOT}/scripts/lint-check.py"
}
```

### Notification Hook

Send alerts:

```json
{
  "type": "notification",
  "command": "${CLAUDE_PLUGIN_ROOT}/scripts/notify.sh"
}
```

### Prompt Hook

LLM-based decision:

```json
{
  "type": "prompt",
  "prompt": "Evaluate if the task is complete based on: $ARGUMENTS",
  "timeout": 30
}
```

## Matcher Patterns

| Pattern | Behavior | Example |
|---------|----------|---------|
| Exact | Matches exactly | `Write` |
| Regex | Pattern match | `Write\|Edit` |
| Wildcard | All events | `*` |
| Omit | Global (no filter) | Don't include field |

Examples:
```json
// Match Write tool only
"matcher": "Write"

// Match Write OR Edit
"matcher": "Write|Edit"

// Match all tools
"matcher": "*"

// Match Bash commands starting with git
"matcher": "Bash(git:*)"
```

## Environment Variables

Available in hook scripts:

| Variable | Description |
|----------|-------------|
| `${CLAUDE_PLUGIN_ROOT}` | Plugin installation directory |
| `${CLAUDE_PROJECT_DIR}` | Project root directory |
| `${CLAUDE_ENV_FILE}` | Env file path (SessionStart only) |

## Example: Complete hooks.json

```json
{
  "description": "Code quality and logging hooks",
  "hooks": {
    "SessionStart": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "${CLAUDE_PLUGIN_ROOT}/scripts/setup.sh",
            "timeout": 30
          }
        ]
      }
    ],
    "PostToolUse": [
      {
        "matcher": "Write|Edit",
        "hooks": [
          {
            "type": "command",
            "command": "${CLAUDE_PLUGIN_ROOT}/scripts/format.sh",
            "timeout": 30
          }
        ]
      }
    ],
    "SessionEnd": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "${CLAUDE_PLUGIN_ROOT}/scripts/cleanup.sh",
            "timeout": 10
          }
        ]
      }
    ]
  }
}
```

## Hook Scripts

### Basic Script Structure

```bash
#!/bin/bash
# ${CLAUDE_PLUGIN_ROOT}/scripts/format.sh

# Exit on error
set -e

# Read input from stdin if available
if [ -t 0 ]; then
  INPUT=""
else
  INPUT=$(cat)
fi

# Your logic here
echo "Hook executed successfully"

exit 0
```

### Script with Input Processing

```python
#!/usr/bin/env python3
import json
import sys

# Read hook input
input_data = json.load(sys.stdin)

# Process
event = input_data.get("hook_event_name")
tool = input_data.get("tool_name")

# Your logic here
print(f"Processed {event} for {tool}")

sys.exit(0)
```

## Timeout Configuration

| Use Case | Recommended Timeout |
|----------|---------------------|
| Quick validation | 10-15 seconds |
| Formatting | 30 seconds |
| Long-running tasks | 60+ seconds |
| Network operations | 30-60 seconds |

## Best Practices

1. **Use specific matchers** - Avoid `*` for performance
2. **Set appropriate timeouts** - Don't block too long
3. **Handle errors gracefully** - Return meaningful messages
4. **Log for debugging** - Include logging in scripts
5. **Test in isolation** - Run scripts manually first

## See Also

- `hook-events.md` - all available events
- `hook-patterns.md` - common patterns and examples

```

### references/06-hooks/hook-events.md

```markdown
# Hook Events

Complete reference for all available hook events in Claude Code.

## Event Reference Table

| Event | Trigger | Matcher | Use Case |
|-------|---------|---------|----------|
| PreToolUse | Before tool execution | Yes | Validation, blocking |
| PostToolUse | After tool execution | Yes | Formatting, logging |
| SessionStart | Session begins | Yes | Setup, initialization |
| SessionEnd | Session ends | Yes | Cleanup |
| UserPromptSubmit | User submits prompt | No | Validation, injection |
| PermissionRequest | Permission dialog shown | Yes | Auto-approve/deny |
| Notification | Alert sent | Yes | Alert handling |
| Stop | Claude finishes responding | No | Continuation logic |
| SubagentStop | Subagent finishes | No | Task completion check |
| PreCompact | Before conversation compact | Yes | Pre-compact actions |

## Event Details

### PreToolUse

**Trigger**: Before Claude executes any tool

**Matcher**: Tool name (e.g., `Bash`, `Write`, `Edit`)

**Use Cases**:
- Block dangerous operations
- Validate before execution
- Log intended actions

**Example**:
```json
{
  "PreToolUse": [
    {
      "matcher": "Bash",
      "hooks": [
        {
          "type": "validation",
          "command": "${CLAUDE_PLUGIN_ROOT}/scripts/validate-bash.sh"
        }
      ]
    }
  ]
}
```

**Return Values**:
- Exit 0: Allow execution
- Exit non-zero: Block execution

### PostToolUse

**Trigger**: After Claude executes a tool

**Matcher**: Tool name

**Use Cases**:
- Format code after writes
- Log operations
- Validate output

**Example**:
```json
{
  "PostToolUse": [
    {
      "matcher": "Write|Edit",
      "hooks": [
        {
          "type": "command",
          "command": "${CLAUDE_PLUGIN_ROOT}/scripts/format.sh",
          "timeout": 30
        }
      ]
    }
  ]
}
```

### SessionStart

**Trigger**: When a Claude Code session begins

**Matcher**: Optional (typically omitted)

**Use Cases**:
- Setup output directories
- Load environment variables
- Initialize logging

**Special**: Access to `${CLAUDE_ENV_FILE}` for persisting variables

**Example**:
```json
{
  "SessionStart": [
    {
      "hooks": [
        {
          "type": "command",
          "command": "${CLAUDE_PLUGIN_ROOT}/scripts/setup.sh"
        }
      ]
    }
  ]
}
```

### SessionEnd

**Trigger**: When session ends

**Matcher**: Optional

**Use Cases**:
- Cleanup temporary files
- Save session state
- Final logging

**Example**:
```json
{
  "SessionEnd": [
    {
      "hooks": [
        {
          "type": "command",
          "command": "${CLAUDE_PLUGIN_ROOT}/scripts/cleanup.sh"
        }
      ]
    }
  ]
}
```

### UserPromptSubmit

**Trigger**: When user submits a prompt

**Matcher**: Not supported (fires for all prompts)

**Use Cases**:
- Validate user input
- Inject context
- Block certain prompts

**Example**:
```json
{
  "UserPromptSubmit": [
    {
      "hooks": [
        {
          "type": "validation",
          "command": "${CLAUDE_PLUGIN_ROOT}/scripts/validate-prompt.sh"
        }
      ]
    }
  ]
}
```

### PermissionRequest

**Trigger**: When permission dialog shown

**Matcher**: Tool name

**Use Cases**:
- Auto-approve trusted operations
- Auto-deny risky operations

**Example**:
```json
{
  "PermissionRequest": [
    {
      "matcher": "Read(./docs/**)",
      "hooks": [
        {
          "type": "command",
          "command": "echo 'approve'"
        }
      ]
    }
  ]
}
```

**Return Values**:
- `approve`: Auto-approve
- `deny`: Auto-deny
- Other/empty: Show prompt

### Notification

**Trigger**: When Claude sends notifications

**Matcher**: Notification type

**Use Cases**:
- External alert routing
- Notification logging

**Example**:
```json
{
  "Notification": [
    {
      "matcher": "*",
      "hooks": [
        {
          "type": "command",
          "command": "${CLAUDE_PLUGIN_ROOT}/scripts/log-notification.sh"
        }
      ]
    }
  ]
}
```

### Stop

**Trigger**: When Claude finishes responding

**Matcher**: Not supported

**Use Cases**:
- Intelligent continuation decisions
- Task completion checks

**Example**:
```json
{
  "Stop": [
    {
      "hooks": [
        {
          "type": "prompt",
          "prompt": "Check if all tasks are complete. Return 'continue' if more work needed."
        }
      ]
    }
  ]
}
```

### SubagentStop

**Trigger**: When a subagent finishes

**Matcher**: Not supported

**Use Cases**:
- Verify subagent task completion
- Chain subagent operations

**Example**:
```json
{
  "SubagentStop": [
    {
      "hooks": [
        {
          "type": "prompt",
          "prompt": "Evaluate if the subagent completed its assigned task."
        }
      ]
    }
  ]
}
```

### PreCompact

**Trigger**: Before conversation is compacted

**Matcher**: Optional

**Use Cases**:
- Notify user
- Save important context
- Pre-compaction logging

**Example**:
```json
{
  "PreCompact": [
    {
      "hooks": [
        {
          "type": "notification",
          "command": "${CLAUDE_PLUGIN_ROOT}/scripts/compact-notify.sh"
        }
      ]
    }
  ]
}
```

## Multiple Hooks per Event

You can have multiple hook configurations per event:

```json
{
  "PostToolUse": [
    {
      "matcher": "Write",
      "hooks": [{ "type": "command", "command": "..." }]
    },
    {
      "matcher": "Edit",
      "hooks": [{ "type": "command", "command": "..." }]
    }
  ]
}
```

## See Also

- `writing-hooks.md` - hook configuration basics
- `hook-patterns.md` - common implementation patterns

```

### references/08-configuration/plugin-json.md

```markdown
# Plugin Manifest (plugin.json)

The plugin manifest defines your plugin's metadata and component locations.

## Location

**Required**: `.claude-plugin/plugin.json`

```
plugin-name/
└── .claude-plugin/
    └── plugin.json
```

## Complete Schema

```json
{
  "name": "enterprise-tools",
  "version": "3.0.0",
  "description": "Enterprise automation, security, and deployment tools",
  "author": {
    "name": "DevOps Team",
    "email": "[email protected]",
    "url": "https://github.com/company"
  },
  "homepage": "https://docs.company.com/plugins/enterprise-tools",
  "repository": "https://github.com/company/enterprise-plugin",
  "license": "MIT",
  "keywords": ["enterprise", "deployment", "security", "automation"],
  "commands": [
    "./commands/deploy.md",
    "./custom/commands/special.md"
  ],
  "agents": [
    "./agents/security-reviewer.md",
    "./agents/compliance-checker.md"
  ],
  "hooks": "./hooks/hooks.json",
  "mcpServers": "./.mcp.json"
}
```

## Required Fields

| Field | Type | Description |
|-------|------|-------------|
| name | string | Unique identifier (kebab-case, no spaces) |

The `name` field is the **only required field**.

## Metadata Fields

| Field | Type | Description |
|-------|------|-------------|
| version | string | Semantic version (e.g., "2.1.0") |
| description | string | Brief explanation of plugin purpose |
| author | object/string | Author information |
| homepage | string | Documentation URL |
| repository | string | Source code URL |
| license | string | SPDX identifier (MIT, Apache-2.0, etc.) |
| keywords | array | Discovery tags |

### Author Object

```json
{
  "author": {
    "name": "Your Name",
    "email": "[email protected]",
    "url": "https://github.com/username"
  }
}
```

Or simple string:
```json
{
  "author": "Your Name <[email protected]>"
}
```

## Component Path Fields

| Field | Type | Description |
|-------|------|-------------|
| commands | string/array | Custom command file paths |
| agents | string/array | Custom agent file paths |
| hooks | string/object | Hook config path or inline config |
| mcpServers | string/object | MCP config path or inline config |

### Path Patterns

**Single path**:
```json
{
  "commands": "./custom-commands/deploy.md"
}
```

**Multiple paths (array)**:
```json
{
  "commands": [
    "./commands/deploy.md",
    "./commands/status.md",
    "./other/special.md"
  ]
}
```

**Inline configuration**:
```json
{
  "hooks": {
    "PostToolUse": [...]
  }
}
```

## Important Path Rules

1. **Custom paths SUPPLEMENT default directories**
   - If `commands/` exists, it's loaded automatically
   - Custom paths add to (don't replace) defaults

2. **All paths relative to plugin root**
   - Must start with `./`
   - Example: `./commands/deploy.md`

3. **Use forward slashes**
   - Works across all platforms
   - Example: `./path/to/file.md`

## Environment Variables

Available in paths:

| Variable | Description |
|----------|-------------|
| `${CLAUDE_PLUGIN_ROOT}` | Plugin installation directory |

Example:
```json
{
  "mcpServers": {
    "my-server": {
      "command": "${CLAUDE_PLUGIN_ROOT}/servers/my-server"
    }
  }
}
```

## Minimal Example

```json
{
  "name": "my-plugin"
}
```

This minimal plugin will still load:
- Commands from `commands/` directory
- Agents from `agents/` directory
- Skills from `skills/` directory

## Recommended Example

```json
{
  "name": "code-quality",
  "version": "1.0.0",
  "description": "Code quality tools for linting and formatting",
  "author": {
    "name": "Your Name"
  },
  "license": "MIT",
  "keywords": ["code-quality", "linting", "formatting"]
}
```

## Full Example

```json
{
  "name": "full-featured-plugin",
  "version": "2.0.0",
  "description": "Complete plugin with all component types",
  "author": {
    "name": "Plugin Author",
    "email": "[email protected]"
  },
  "repository": "https://github.com/author/plugin",
  "license": "MIT",
  "keywords": ["complete", "example"],
  "commands": "./commands",
  "agents": [
    "./agents/reviewer.md",
    "./agents/analyzer.md"
  ],
  "hooks": "./hooks/hooks.json",
  "mcpServers": "./.mcp.json"
}
```

## Validation

Ensure your plugin.json is valid JSON:

```bash
# Check syntax
cat .claude-plugin/plugin.json | jq .

# Or use Node
node -e "require('./.claude-plugin/plugin.json')"
```

## See Also

- `marketplace-json.md` - marketplace configuration
- `settings.md` - settings hierarchy
- `../10-distribution/packaging.md` - packaging guide

```

### references/08-configuration/settings.md

```markdown
# Settings Configuration

Claude Code settings control plugin behavior, permissions, and environment. Settings follow a hierarchy where more specific settings override general ones.

## Important: Plugins Cannot Define Custom Settings

**Plugins cannot add their own settings fields to settings.json.** The available settings fields are fixed by Claude Code. To configure plugin-specific options, use the `env` block pattern described below.

## Settings Hierarchy (Precedence Order)

```
1. Enterprise Managed Policies (Highest Priority)
   ├── /Library/Application Support/ClaudeCode/managed-settings.json (macOS)
   ├── /etc/claude-code/managed-settings.json (Linux/WSL)
   └── C:\Program Files\ClaudeCode\managed-settings.json (Windows)

2. Command Line Arguments
   └── --settings flag overrides for current session

3. Local Project Settings (Not Committed)
   └── .claude/settings.local.json

4. Shared Project Settings (Version Controlled)
   └── .claude/settings.json

5. User Settings (Lowest Priority)
   └── ~/.claude/settings.json
```

Higher priority settings override lower ones.

## Settings File Locations

### User Settings

Global settings for all projects:

| OS | Location |
|----|----------|
| macOS | `~/.claude/settings.json` |
| Linux | `~/.claude/settings.json` |
| Windows | `%USERPROFILE%\.claude\settings.json` |

### Project Settings

Project-specific settings:

```
project/
└── .claude/
    ├── settings.json        # Shared (commit to git)
    └── settings.local.json  # Local (gitignore)
```

## Plugin Settings Fields

### enabledPlugins

Control which plugins are enabled:

```json
{
  "enabledPlugins": {
    "formatter@company-tools": true,
    "deployer@company-tools": true,
    "analyzer@security-plugins": false
  }
}
```

Format: `"plugin-name@marketplace-name": true/false`

### extraKnownMarketplaces

Define additional marketplaces for the team:

```json
{
  "extraKnownMarketplaces": {
    "company-tools": {
      "source": {
        "source": "github",
        "repo": "company/claude-plugins"
      }
    },
    "project-specific": {
      "source": {
        "source": "git",
        "url": "https://git.company.com/project-plugins.git"
      }
    }
  }
}
```

Team members are prompted to install when trusting the folder.

### env

Custom environment variables - **this is how plugins provide configurable options**:

```json
{
  "env": {
    "PLUGIN_OUTPUT_DIR": "${HOME}/claude-outputs",
    "PLUGIN_LOG_LEVEL": "debug",
    "PLUGIN_CONFIG_PATH": "${HOME}/.config/plugins"
  }
}
```

Variables support expansion like `${HOME}`.

## Plugin-Specific Configuration Pattern

Since plugins cannot define custom settings fields, use environment variables with a naming convention:

### Naming Convention

Use `PLUGINNAME_SETTING` format:

```json
{
  "env": {
    "MYFORMATTER_STYLE": "prettier",
    "MYFORMATTER_LINE_WIDTH": "100",
    "MYFORMATTER_TABS": "false",
    "MYDEPLOYER_ENV": "staging",
    "MYDEPLOYER_DRY_RUN": "true"
  }
}
```

### Using in Scripts

```bash
#!/bin/bash
# Use environment variable with fallback default
STYLE="${MYFORMATTER_STYLE:-prettier}"
LINE_WIDTH="${MYFORMATTER_LINE_WIDTH:-80}"

# Boolean handling
if [ "${MYFORMATTER_TABS}" = "true" ]; then
  echo "Using tabs"
fi
```

### Using in Python

```python
import os

style = os.environ.get("MYFORMATTER_STYLE", "prettier")
line_width = int(os.environ.get("MYFORMATTER_LINE_WIDTH", "80"))
use_tabs = os.environ.get("MYFORMATTER_TABS", "false").lower() == "true"
```

### Alternative: Plugin Config File

For complex configuration, your plugin can ship with or read a config file:

```json
// ${CLAUDE_PLUGIN_ROOT}/config.json
{
  "defaults": {
    "style": "prettier",
    "lineWidth": 80
  },
  "rules": {
    "noConsoleLog": true
  }
}
```

Read in scripts:
```bash
CONFIG_FILE="${CLAUDE_PLUGIN_ROOT}/config.json"
STYLE=$(jq -r '.defaults.style' "$CONFIG_FILE")
```

### Documenting Configuration

Always document available configuration in your plugin README:

```markdown
## Configuration

Set these environment variables in `.claude/settings.json`:

| Variable | Default | Description |
|----------|---------|-------------|
| `MYPLUGIN_OUTPUT_DIR` | `./output` | Where to save generated files |
| `MYPLUGIN_LOG_LEVEL` | `info` | Logging verbosity (debug, info, warn, error) |
| `MYPLUGIN_FEATURE_X` | `false` | Enable experimental feature X |
```

### permissions

Control tool permissions:

```json
{
  "permissions": {
    "allow": [
      "Bash(npm run:*)",
      "Edit(./output/**)",
      "Edit(./logs/**)"
    ],
    "deny": [
      "Read(.env)",
      "Read(.env.*)",
      "Read(./secrets/**)"
    ],
    "ask": [
      "Bash(rm:*)"
    ]
  }
}
```

| Permission | Behavior |
|------------|----------|
| allow | Run without prompting |
| deny | Block completely |
| ask | Prompt for confirmation |

## Complete Example

```json
{
  "enabledPlugins": {
    "code-quality@camoa-skills": true,
    "security-tools@org-plugins": true
  },
  "extraKnownMarketplaces": {
    "org-plugins": {
      "source": {
        "source": "github",
        "repo": "myorg/claude-plugins"
      }
    }
  },
  "env": {
    "PLUGIN_OUTPUT_DIR": "${HOME}/claude-outputs",
    "PLUGIN_LOG_LEVEL": "info"
  },
  "permissions": {
    "allow": [
      "Read(./docs/**)",
      "Edit(./output/**)"
    ],
    "deny": [
      "Read(.env*)",
      "Read(./secrets/**)"
    ]
  }
}
```

## Recommended .gitignore

```gitignore
# Claude Code local settings
.claude/settings.local.json
.claude/outputs/
```

## Project vs User Settings

### Use Project Settings For:

- Team-shared configurations
- Project-specific plugins
- Repository marketplace references
- Shared permissions

### Use User Settings For:

- Personal preferences
- Global plugin enablement
- Personal environment variables
- Development overrides

### Use Local Settings For:

- Machine-specific paths
- Temporary overrides
- Secrets and credentials
- Development-only configs

## See Also

- `plugin-json.md` - plugin manifest
- `output-config.md` - output configuration
- `marketplace-json.md` - marketplace setup

```

### references/08-configuration/output-config.md

```markdown
# Output Configuration

Plugins often need to write logs, artifacts, and reports. This guide covers best practices for output management.

## Standard Environment Variables

| Variable | Purpose | Availability |
|----------|---------|--------------|
| `CLAUDE_PLUGIN_ROOT` | Plugin installation directory | Always |
| `CLAUDE_PROJECT_DIR` | Project root directory | Always |
| `CLAUDE_ENV_FILE` | Persistent env vars file | SessionStart only |
| `CLAUDE_CONFIG_DIR` | Config directory (~/.claude) | Always |

## Recommended Output Structure

```
project-root/
├── .claude/
│   ├── settings.json
│   └── settings.local.json
├── claude-outputs/            # Generated outputs
│   ├── logs/
│   │   ├── session.log
│   │   ├── operations.log
│   │   └── errors.log
│   ├── artifacts/
│   │   ├── reports/
│   │   ├── builds/
│   │   └── exports/
│   └── temp/
└── .gitignore
```

## SessionStart Output Setup

Use SessionStart hooks to create output directories:

### hooks.json

```json
{
  "SessionStart": [
    {
      "hooks": [
        {
          "type": "command",
          "command": "${CLAUDE_PLUGIN_ROOT}/scripts/setup-output.sh",
          "timeout": 30
        }
      ]
    }
  ]
}
```

### scripts/setup-output.sh

```bash
#!/bin/bash
set -e

# Define output directory
OUTPUT_DIR="${CLAUDE_PROJECT_DIR}/claude-outputs"

# Create directories
mkdir -p "${OUTPUT_DIR}/logs"
mkdir -p "${OUTPUT_DIR}/artifacts"
mkdir -p "${OUTPUT_DIR}/temp"

# Set permissions
chmod 755 "${OUTPUT_DIR}"

# Persist environment variables for session
if [ -n "${CLAUDE_ENV_FILE}" ]; then
  cat >> "${CLAUDE_ENV_FILE}" <<EOF
export PLUGIN_OUTPUT_DIR="${OUTPUT_DIR}"
export PLUGIN_LOG_FILE="${OUTPUT_DIR}/logs/session.log"
export PLUGIN_ARTIFACTS_DIR="${OUTPUT_DIR}/artifacts"
EOF
fi

# Log initialization
echo "[$(date)] Output directories initialized" >> "${OUTPUT_DIR}/logs/setup.log"

exit 0
```

## Custom Environment Variables

Define in settings:

```json
{
  "env": {
    "CLAUDE_PLUGIN_OUTPUT_DIR": "${HOME}/claude-outputs",
    "CLAUDE_PLUGIN_LOG_LEVEL": "info",
    "CLAUDE_PLUGIN_RETENTION_DAYS": "30"
  }
}
```

Use in scripts:

```bash
OUTPUT_DIR="${CLAUDE_PLUGIN_OUTPUT_DIR:-${HOME}/claude-outputs}"
```

## .gitignore Patterns

Add to project `.gitignore`:

```gitignore
# Claude Code outputs
claude-outputs/
.claude/settings.local.json

# Alternative output directories
/output/
/logs/
/artifacts/
/.reports/
```

## Permission Settings for Output

Allow writing to output directories:

```json
{
  "permissions": {
    "allow": [
      "Write(./claude-outputs/**)",
      "Edit(./claude-outputs/**)",
      "Write(./output/**)",
      "Write(./logs/**)"
    ]
  }
}
```

## Structured Logging

### Log to JSON Lines

```python
#!/usr/bin/env python3
import json
import os
from datetime import datetime

log_file = os.path.join(
    os.environ.get("PLUGIN_OUTPUT_DIR", "."),
    "logs",
    "operations.jsonl"
)

def log_operation(event, tool, status="success", details=None):
    entry = {
        "timestamp": datetime.utcnow().isoformat(),
        "event": event,
        "tool": tool,
        "status": status,
        "details": details
    }

    os.makedirs(os.path.dirname(log_file), exist_ok=True)

    with open(log_file, "a") as f:
        f.write(json.dumps(entry) + "\n")
```

### Log Rotation Script

```bash
#!/bin/bash
# scripts/rotate-logs.sh

OUTPUT_DIR="${PLUGIN_OUTPUT_DIR:-./claude-outputs}"
LOG_DIR="${OUTPUT_DIR}/logs"
RETENTION_DAYS="${PLUGIN_RETENTION_DAYS:-7}"

# Archive old logs
find "${LOG_DIR}" -name "*.log" -mtime +${RETENTION_DAYS} -exec gzip {} \;

# Delete very old archives
find "${LOG_DIR}" -name "*.gz" -mtime +30 -delete

echo "[$(date)] Log rotation complete" >> "${LOG_DIR}/rotation.log"
```

## Project-Relative vs User Outputs

### Project-Relative (Recommended)

```bash
OUTPUT_DIR="${CLAUDE_PROJECT_DIR}/claude-outputs"
```

Benefits:
- Outputs stay with project
- Easy to clean up
- Context preserved

### User-Level

```bash
OUTPUT_DIR="${HOME}/claude-outputs"
```

Benefits:
- Persists across projects
- Centralized logs
- Global history

## Cleanup Patterns

### SessionEnd Cleanup

```json
{
  "SessionEnd": [
    {
      "hooks": [
        {
          "type": "command",
          "command": "${CLAUDE_PLUGIN_ROOT}/scripts/cleanup.sh"
        }
      ]
    }
  ]
}
```

### scripts/cleanup.sh

```bash
#!/bin/bash

OUTPUT_DIR="${PLUGIN_OUTPUT_DIR:-./claude-outputs}"

# Remove temp files
rm -rf "${OUTPUT_DIR}/temp/*" 2>/dev/null || true

# Archive session log
SESSION_LOG="${OUTPUT_DIR}/logs/session.log"
if [ -f "$SESSION_LOG" ]; then
  ARCHIVE_NAME="session-$(date +%Y%m%d-%H%M%S).log"
  mv "$SESSION_LOG" "${OUTPUT_DIR}/logs/${ARCHIVE_NAME}"
fi

exit 0
```

## Best Practices

1. **Use standard directories**: `claude-outputs/logs`, `claude-outputs/artifacts`
2. **Always gitignore outputs**: Add patterns to `.gitignore`
3. **Use CLAUDE_ENV_FILE**: Persist paths for session duration
4. **Implement log rotation**: Prevent unbounded growth
5. **Set appropriate permissions**: Allow writing to output paths
6. **Clean up on session end**: Remove temporary files

## See Also

- `settings.md` - settings hierarchy
- `../06-hooks/hook-patterns.md` - session hooks
- `../06-hooks/hook-events.md` - event reference

```

### references/09-testing/testing.md

```markdown
# Testing Plugins

How to validate plugins and their components work correctly before deployment.

## Workflow Checklist Pattern

For complex multi-step testing, provide a checklist Claude can track:

```markdown
Copy this checklist and track progress:

Testing Progress:
- [ ] Step 1: Validate plugin structure
- [ ] Step 2: Test skill triggering
- [ ] Step 3: Test command execution
- [ ] Step 4: Verify agent delegation
- [ ] Step 5: Confirm hook firing
```

This pattern is recommended for any multi-step workflow in your skills.

## Test with Multiple Models

Skills behave differently across models:

| Model | What to Check |
|-------|---------------|
| **Claude Haiku** | Does the skill provide enough guidance? |
| **Claude Sonnet** | Is the skill clear and efficient? |
| **Claude Opus** | Does the skill avoid over-explaining? |

## Testing Overview

| Component | Test Method | Success Indicator |
|-----------|-------------|-------------------|
| **Skills** | Ask matching questions | Auto-triggers, workflow runs |
| **Commands** | Run `/command-name` | Appears in `/help`, executes correctly |
| **Agents** | Check `/agents`, trigger scenarios | Listed, auto-delegates when expected |
| **Hooks** | Trigger events, check `--debug` | Executes on events, output correct |
| **MCP** | Check `/mcp`, use tools | Server listed, tools work |

## Plugin-Level Testing

### Quick Validation

```bash
# Validate plugin structure
claude plugin validate .

# Check with debug output
claude --debug "plugins"

# Run plugin doctor
claude doctor
```

### Installation Test

```bash
# 1. Add local marketplace
/plugin marketplace add ./path/to/dev-marketplace

# 2. Install plugin
/plugin install my-plugin@dev-marketplace

# 3. Verify loading (no errors)
claude --debug "plugins"
```

---

## Testing Commands

### Checklist

- [ ] Appears in `/help` output
- [ ] Description is clear and complete
- [ ] Arguments work (`$1`, `$2`, `$ARGUMENTS`)
- [ ] Tool restrictions enforced (`allowed-tools`)
- [ ] Bash execution works (`!command`)
- [ ] File references work (`@file.md`)

### Test Process

```bash
# 1. Check command appears
/help

# 2. Run with no arguments
/my-command

# 3. Run with arguments
/my-command arg1 arg2

# 4. Test tool restrictions (should fail if restricted)
# (run command that would use disallowed tool)
```

---

## Testing Agents

### Checklist

- [ ] Appears in `/agents` output
- [ ] Description triggers auto-delegation
- [ ] Tool permissions correct
- [ ] Handles expected scenarios
- [ ] Returns useful results

### Test Process

```bash
# 1. Check agent appears
/agents

# 2. Test auto-delegation
# Ask question matching agent description
# Example: "Review this code for security issues"

# 3. Test manual invocation
# Use Task tool with agent name

# 4. Verify tool restrictions
# Check agent doesn't use tools outside its list
```

### Common Issues

**Agent not triggering:**
- Description too vague
- Missing "proactively" or action triggers
- Competing with similar agent

**Fix:** Make description more specific with examples.

---

## Testing Hooks

### Checklist

- [ ] Scripts are executable (`chmod +x`)
- [ ] Correct event type used
- [ ] Matcher patterns correct
- [ ] Timeouts appropriate
- [ ] Errors handled gracefully

### Test Process

```bash
# 1. Make scripts executable
chmod +x scripts/*.sh

# 2. Test scripts directly
./scripts/my-hook.sh

# 3. Run Claude with debug
claude --debug "hooks"

# 4. Trigger the event
# PostToolUse: Edit a file
# SessionStart: Start new session
# UserPromptSubmit: Enter a prompt
```

### Debug Hooks

```bash
# See all hook activity
claude --debug "hooks"

# View hook configurations
/hooks
```

### Common Issues

**Hook not firing:**
- Script not executable
- Wrong event type
- Matcher doesn't match tool name

**Hook fails:**
- Script has errors (test manually first)
- Timeout too short
- Missing environment variables

---

## Testing MCP Servers

### Checklist

- [ ] Server binary/command exists
- [ ] Config paths use `${CLAUDE_PLUGIN_ROOT}`
- [ ] Environment variables set
- [ ] Server starts without errors
- [ ] Tools appear in listing

### Test Process

```bash
# 1. Check server appears
/mcp

# 2. Test server manually
${CLAUDE_PLUGIN_ROOT}/servers/my-server --help

# 3. Debug connection
claude --debug "mcp"

# 4. Use tools
# Ask Claude to use the MCP-provided tools
```

### Common Issues

**Server not starting:**
- Binary not found (check path)
- Missing `${CLAUDE_PLUGIN_ROOT}` variable
- Config file errors

**Tools not working:**
- Server crashes (run manually to debug)
- Environment variables missing
- Authentication required

---

## TDD for Skills

### RED Phase
1. Run pressure scenario WITHOUT skill
2. Document exact behavior verbatim
3. Identify failure patterns and rationalizations

### GREEN Phase
4. Write minimal skill addressing failures
5. Test again - verify improvement

### REFACTOR Phase
6. Identify new rationalizations
7. Add explicit counters
8. Re-test until bulletproof

## Testing by Skill Type

### Discipline-Enforcing Skills
- Test with academic understanding questions
- Test under pressure (time, sunk cost, authority)
- Test with combined pressures
- **Success**: Agent follows rule under maximum pressure

### Technique Skills
- Test application scenarios
- Test edge cases and variations
- Test with missing information
- **Success**: Agent applies technique correctly

### Reference Skills
- Test information retrieval
- Test application of information
- Test for coverage gaps
- **Success**: Agent finds and uses information correctly

## Validation Checklist

### Frontmatter
- [ ] Only `name` and `description` fields (plus optional: license, allowed-tools, metadata)
- [ ] Name: lowercase letters, numbers, hyphens only
- [ ] Name: max 64 characters
- [ ] Name: matches directory name
- [ ] Description: starts with "Use when..."
- [ ] Description: includes specific triggers
- [ ] Description: written in third person
- [ ] Description: under 1024 characters

### Content
- [ ] SKILL.md body under 500 lines
- [ ] No duplicate information
- [ ] All referenced files exist
- [ ] Scripts tested and working
- [ ] Examples are complete and runnable

### Discovery
- [ ] Description triggers correctly for intended tasks
- [ ] Doesn't trigger for unrelated tasks
- [ ] Keywords match likely searches

## Quick Validation Commands

```bash
# Check frontmatter format
head -20 SKILL.md

# Count lines (target: <500)
wc -l SKILL.md

# Find broken references
grep -o 'references/[^)]*' SKILL.md | while read f; do
  [ -f "$f" ] || echo "Missing: $f"
done

# Find broken script references
grep -o 'scripts/[^)]*' SKILL.md | while read f; do
  [ -f "$f" ] || echo "Missing: $f"
done

# Test scripts run
python scripts/*.py --help 2>/dev/null || echo "Check script syntax"

# Run validator
python scripts/validate_skill.py .
```

## Size Guidelines

| Component | Target | Maximum |
|-----------|--------|---------|
| Description | 200-500 chars | 1024 chars |
| SKILL.md body | <500 lines | 5000 words |
| Individual reference | <1000 lines | 10k words |
| Total skill files | <50 files | No limit |

## Success Criteria

A skill is ready when:

1. **Triggers correctly** - Loads for intended tasks, not unrelated ones
2. **Workflow works** - Claude follows the process correctly
3. **Output matches** - Results meet expectations
4. **No rationalization** - Claude doesn't skip or shortcut the skill
5. **Scripts execute** - All bundled scripts run without errors
6. **References exist** - All referenced files are present

## Example Test Scenarios

Per Anthropic guidelines, create 3+ evaluation scenarios before deployment.

### Scenario 1: New Skill Creation
**Input:** "I want to create a skill for generating API documentation"
**Expected:**
- Skill triggers and loads
- Six-step workflow is followed
- Scripts are used for init/validate/package
- Progressive disclosure applied (SKILL.md hub, details in references/)

### Scenario 2: Skill Not Discovered
**Input:** "My skill isn't showing up when I ask Claude to use it"
**Expected:**
- Skill triggers on discovery issues
- Description field guidance provided
- Checklist for triggers/keywords reviewed

### Scenario 3: Choosing Creation Approach
**Input:** "Should I scrape docs or write a skill manually?"
**Expected:**
- Decision framework referenced
- Tool comparison provided
- Recommendation based on source material

## Cross-Model Testing

Anthropic recommends testing skills across models:

| Model | Focus |
|-------|-------|
| Haiku | Speed, basic compliance |
| Sonnet | Balance, typical usage |
| Opus | Complex reasoning, edge cases |

Run each scenario on all three models before deployment.

```

### references/10-distribution/packaging.md

```markdown
# Packaging Plugins

Prepare your plugin for distribution through marketplaces.

## Pre-Packaging Checklist

### Required Files

- [ ] `.claude-plugin/plugin.json` - Valid manifest
- [ ] At least one component (command, agent, skill, hook, or MCP)

### Recommended Files

- [ ] `README.md` - Installation and usage instructions
- [ ] `CHANGELOG.md` - Version history
- [ ] `LICENSE` - License file

### Quality Checks

- [ ] All JSON files parse correctly
- [ ] All markdown frontmatter is valid YAML
- [ ] Scripts are executable (`chmod +x`)
- [ ] No hardcoded paths (use `${CLAUDE_PLUGIN_ROOT}`)
- [ ] No secrets in committed files

## Directory Structure

```
plugin-name/
├── .claude-plugin/
│   └── plugin.json          # Required
├── commands/                 # Optional
│   └── *.md
├── agents/                   # Optional
│   └── *.md
├── skills/                   # Optional
│   └── skill-name/
│       └── SKILL.md
├── hooks/                    # Optional
│   └── hooks.json
├── scripts/                  # Optional
│   └── *.sh
├── .mcp.json                # Optional
├── README.md                # Recommended
├── CHANGELOG.md             # Recommended
└── LICENSE                  # Recommended
```

## Validation Script

Create a validation script:

```bash
#!/bin/bash
# validate-plugin.sh

set -e

echo "Validating plugin..."

# Check plugin.json exists
if [ ! -f ".claude-plugin/plugin.json" ]; then
  echo "ERROR: .claude-plugin/plugin.json not found"
  exit 1
fi

# Validate JSON
cat .claude-plugin/plugin.json | jq . > /dev/null
echo "✓ plugin.json is valid JSON"

# Check commands
if [ -d "commands" ]; then
  for cmd in commands/*.md; do
    if [ -f "$cmd" ]; then
      # Check for frontmatter
      if ! head -1 "$cmd" | grep -q "^---"; then
        echo "WARNING: $cmd missing frontmatter"
      fi
    fi
  done
  echo "✓ Commands checked"
fi

# Check agents
if [ -d "agents" ]; then
  for agent in agents/*.md; do
    if [ -f "$agent" ]; then
      if ! head -1 "$agent" | grep -q "^---"; then
        echo "WARNING: $agent missing frontmatter"
      fi
    fi
  done
  echo "✓ Agents checked"
fi

# Check skills
if [ -d "skills" ]; then
  for skill_dir in skills/*/; do
    if [ ! -f "${skill_dir}SKILL.md" ]; then
      echo "WARNING: ${skill_dir} missing SKILL.md"
    fi
  done
  echo "✓ Skills checked"
fi

# Check hooks
if [ -f "hooks/hooks.json" ]; then
  cat hooks/hooks.json | jq . > /dev/null
  echo "✓ hooks.json is valid JSON"
fi

# Check MCP
if [ -f ".mcp.json" ]; then
  cat .mcp.json | jq . > /dev/null
  echo "✓ .mcp.json is valid JSON"
fi

# Check scripts are executable
if [ -d "scripts" ]; then
  for script in scripts/*.sh scripts/*.py; do
    if [ -f "$script" ] && [ ! -x "$script" ]; then
      echo "WARNING: $script is not executable"
    fi
  done
  echo "✓ Scripts checked"
fi

echo ""
echo "Plugin validation complete!"
```

## Plugin.json Requirements

Minimum viable:

```json
{
  "name": "my-plugin"
}
```

Recommended for distribution:

```json
{
  "name": "my-plugin",
  "version": "1.0.0",
  "description": "Brief description of plugin purpose",
  "author": {
    "name": "Your Name"
  },
  "license": "MIT",
  "keywords": ["keyword1", "keyword2"],
  "repository": "https://github.com/username/plugin"
}
```

## README Template

```markdown
# Plugin Name

Brief description of what this plugin does.

## Installation

1. Add marketplace (if not already added):
   ```
   /plugin marketplace add username/marketplace-repo
   ```

2. Install plugin:
   ```
   /plugin install plugin-name@marketplace
   ```

## Features

- Feature 1: Description
- Feature 2: Description

## Commands

- `/command-name` - What it does

## Agents

- `agent-name` - What expertise it provides

## Skills

- `skill-name` - What capability it adds

## Configuration

Any configuration options...

## License

MIT License
```

## Testing Before Distribution

1. **Fresh install test**:
   - Remove local plugin
   - Install from marketplace
   - Verify all components work

2. **Test each component**:
   - Run each command
   - Trigger each agent
   - Query for each skill
   - Trigger hook events

3. **Error handling**:
   - Test with invalid inputs
   - Verify graceful failures

## See Also

- `marketplace.md` - marketplace distribution
- `versioning.md` - version management
- `debugging.md` - troubleshooting

```

### references/01-overview/what-are-plugins.md

```markdown
# What Are Claude Code Plugins?

Marketplace plugins are extensible packages that add custom functionality to Claude Code. They can be discovered, installed, and managed through plugin marketplaces—catalogs distributed via Git repositories, GitHub, or local paths.

## Why Use Plugins?

- **Team Standardization**: Share tools and workflows across projects
- **Easy Distribution**: Distribute through marketplaces
- **Encapsulation**: Package multiple components together
- **Reusability**: Use same plugin across different projects
- **Discoverability**: Browse and install from centralized catalogs
- **Version Management**: Track and update plugin versions

## What Plugins Can Contain

Plugins can contain up to 5 core component types:

| Component | Location | Format | Invocation | Best For |
|-----------|----------|--------|-----------|----------|
| Commands | `commands/` | Markdown | User (`/command`) | Quick, frequently used prompts |
| Agents | `agents/` | Markdown | Auto + Manual | Task-specific expertise |
| Skills | `skills/` | Directory + SKILL.md | Model-invoked | Complex workflows with files |
| Hooks | `hooks/hooks.json` | JSON | Event-triggered | Automation and validation |
| MCP Servers | `.mcp.json` | JSON | Auto startup | External tool integration |

## Plugin Structure

```
plugin-name/
├── .claude-plugin/
│   └── plugin.json          # REQUIRED - plugin manifest
├── commands/                 # Slash commands (optional)
├── agents/                   # Custom agents (optional)
├── skills/                   # Agent skills (optional)
│   └── skill-name/
│       └── SKILL.md
├── hooks/                    # Event hooks (optional)
│   └── hooks.json
├── .mcp.json                 # MCP servers (optional)
├── scripts/                  # Utility scripts
├── README.md
└── CHANGELOG.md
```

## Required vs Optional

**Required**:
- `.claude-plugin/plugin.json` - the plugin manifest

**Optional (at least one recommended)**:
- Commands, Agents, Skills, Hooks, or MCP servers

## Plugin vs Other Extension Methods

| Extension | Use Case |
|-----------|----------|
| **Plugin** | Distribute multiple components, team sharing |
| **Project CLAUDE.md** | Project-specific context |
| **User ~/.claude/CLAUDE.md** | Personal preferences |
| **Standalone MCP** | External tool without plugin wrapper |

## Key Points

- Plugins are the **primary distribution mechanism** for sharing custom tools
- Support **semantic versioning** for tracking updates
- Can be hosted on GitHub, GitLab, or any git hosting
- **Enterprise policy management** available for organizations
- Full **CLI control** for automation

## See Also

- `component-comparison.md` - deciding which components to use
- `../08-configuration/plugin-json.md` - plugin manifest schema
- `../10-distribution/marketplace.md` - distributing plugins

```

### references/01-overview/what-are-skills.md

```markdown
# What Are Skills?

Foundational understanding of Claude Code skills.

## Official Definition

> "Skills extend Claude's capabilities by packaging your expertise into composable resources, transforming general-purpose agents into specialized agents that fit your needs." — Anthropic

## What Skills Provide

1. **Specialized workflows** - Multi-step procedures for specific domains
2. **Tool integrations** - Instructions for working with specific file formats or APIs
3. **Domain expertise** - Company-specific knowledge, schemas, business logic
4. **Bundled resources** - Scripts, references, and assets for complex and repetitive tasks

## Key Characteristics

| Aspect | Description |
|--------|-------------|
| **Model-Invoked** | Claude automatically decides when to use based on description |
| **Progressive Disclosure** | Only loads what's needed, when needed |
| **Procedural Knowledge** | Workflows and expertise, not just reference data |
| **Composable** | Multiple focused skills work better than one large skill |

## Skills vs Other Claude Features

| Feature | Invocation | Use Case |
|---------|------------|----------|
| **Skills** | Automatic (model-invoked) | Specialized capabilities, workflows |
| **Slash Commands** | Manual (`/command`) | Quick shortcuts, explicit actions |
| **MCP Servers** | Tool calls | External service integrations |
| **Projects** | Always loaded | Project context, instructions |
| **Agents** | Task tool | Complex multi-step autonomous work |
| **CLAUDE.md** | Always loaded | Project-specific instructions |

## When to Use Skills vs Alternatives

| Use Case | Best Choice | Why |
|----------|-------------|-----|
| Specialized workflow Claude should auto-detect | **Skill** | Model-invoked, progressive disclosure |
| User must explicitly trigger | **Slash Command** | Manual invocation required |
| External API/service integration | **MCP Server** | Tool calls, real-time data |
| Project-specific context always needed | **CLAUDE.md** | Always in context |
| Complex autonomous multi-step work | **Agent** | Dedicated subprocess |

## Skill Types

### Technique Skills
Teach a method or approach.
- Focus: How-to guidance, examples
- Example: TDD workflow, debugging methodology

### Discipline Skills
Enforce process or prevent mistakes.
- Focus: Rules, rationalization counters
- Example: Verification before completion, code review requirements

### Reference Skills
Provide lookup information.
- Focus: Searchable documentation
- Example: API reference, schema documentation

### Toolkit Skills
Provide utilities and tools.
- Focus: Scripts, integrations
- Example: PDF processing, document creation

## The 5-10 Rule

```
Have you done this task 5+ times?
├─ NO → Don't create skill yet
└─ YES → Will you do it 10+ more times?
    ├─ NO → Consider slash command instead
    └─ YES → Create a skill
```

```

### references/01-overview/what-are-commands.md

```markdown
# What Are Commands (Slash Commands)?

Commands are custom slash commands that integrate with Claude Code's command system. They are **user-invoked** via `/command-name` and appear in the `/help` listing.

## Key Characteristics

- User-invoked via `/command-name`
- Support arguments and bash execution
- Can reference files with `@` prefix
- Appear in `/help` listing
- Discoverable in slash command menu
- Single markdown file per command

## When to Use Commands

**Good Use Cases**:
- Quick, frequently used prompts
- One-off automation
- Explicit workflows the user should trigger
- Simple templates and reminders
- Tasks that need user control over when they run

**Examples**:
- `/review-pr` - Review current PR
- `/deploy` - Deploy to staging
- `/fix-issue 123` - Fix specific issue
- `/summarize @file.md` - Summarize a file

## Commands vs Other Components

| Aspect | Commands | Skills | Agents |
|--------|----------|--------|--------|
| Invocation | User (`/command`) | Model-invoked | Auto + Manual |
| Files | Single .md | Directory + SKILL.md | Single .md |
| Discovery | `/help` | Automatic | `/agents` |
| Best For | Quick prompts | Complex workflows | Task expertise |

## File Location

```
plugin-name/
└── commands/
    ├── review.md
    ├── deploy.md
    └── frontend/        # Namespace: /frontend:component
        └── component.md
```

## Basic Format

```markdown
---
description: What this command does and when to use it
allowed-tools: Read, Edit, Bash
argument-hint: [file] [options]
---

# Command Title

Instructions for Claude when this command is invoked.

Use $1 for first argument, $2 for second, $ARGUMENTS for all.
```

## Key Features

1. **Arguments**: `$1`, `$2`, `$ARGUMENTS`
2. **Bash execution**: `!git status` runs bash inline
3. **File references**: `@src/file.js` includes file content
4. **Namespacing**: Subdirectories create namespaced commands

## The 5-10 Rule

Use commands when:
- Task is done 5+ times
- Will be done 10+ more times
- User should control when it runs

## See Also

- `../04-commands/writing-commands.md` - how to write commands
- `../04-commands/command-patterns.md` - advanced patterns
- `../04-commands/command-arguments.md` - argument handling

```

### references/01-overview/what-are-agents.md

```markdown
# What Are Agents (Subagents)?

Agents are specialized AI assistants with their own context window, custom system prompt, and configurable tool permissions. They can be automatically delegated to based on context or manually invoked.

## Key Characteristics

- **Own separate context window** (prevents main conversation pollution)
- Custom system prompts for specialized expertise
- Configurable tool permissions
- Automatic delegation based on context
- Can be manually invoked
- Appear in `/agents` interface

## When to Use Agents

**Good Use Cases**:
- Task-specific expertise areas (code review, security analysis)
- Different tool permission levels
- Team workflows requiring specialized knowledge
- Complex, multi-step operations
- Tasks that benefit from a fresh context

**Examples**:
- Security reviewer that checks for vulnerabilities
- Performance analyst for optimization
- Documentation writer
- Test generator

## Agents vs Other Components

| Aspect | Agents | Commands | Skills |
|--------|--------|----------|--------|
| Invocation | Auto + Manual | User (`/command`) | Model-invoked |
| Context | Own window | Included in command | Shared with main |
| Files | Single .md | Single .md | Directory + SKILL.md |
| Best For | Task expertise | Quick prompts | Complex workflows |

## Built-in Agent Types

Claude Code includes built-in agents:

| Agent | Purpose |
|-------|---------|
| general-purpose | Complex multi-step tasks with read+write access |
| Plan | Read-only codebase exploration in plan mode |
| Explore | Fast, lightweight, read-only with Haiku |

## File Location

```
plugin-name/
└── agents/
    ├── code-reviewer.md
    ├── security-checker.md
    └── performance-analyst.md
```

## Basic Format

```markdown
---
name: security-reviewer
description: Reviews code for security vulnerabilities. Use proactively after code changes.
capabilities: ["vulnerability detection", "OWASP compliance", "dependency audit"]
tools: Read, Grep, Glob
model: sonnet
permissionMode: default
---

# Security Reviewer

## Role
Expert security analyst specializing in vulnerability detection and code hardening.

## Capabilities
- Identify injection vulnerabilities (SQL, XSS, command)
- Check for insecure dependencies
- Verify authentication patterns

## When to Use
- After code changes
- Before merges to main
- During security audits
```

## Auto-Delegation

Include "Use proactively" in the description for automatic delegation:

```
description: Security specialist. Use proactively when reviewing code for vulnerabilities.
```

## See Also

- `../05-agents/writing-agents.md` - how to write agents
- `../05-agents/agent-patterns.md` - best practices
- `../05-agents/agent-tools.md` - tool configuration

```