Meta-plugin for creating, validating, and publishing Claude Code plugins

version
1.0.0

Install

/plugin install plugin-creator@agent-toolkit

Run it inside Claude Code after adding the marketplace with /plugin marketplace add TomazWang/agent-toolkit.

Contents

Discovered from source

Skills 7

Agent Development Skill

Guide to creating effective autonomous agents for Claude Code plugins.

When to Use

Activate when:

  • Creating new agents
  • User asks about agent structure
  • Designing specialized automation
  • Questions about agent capabilities

What Are Agents?

Agents are autonomous specialized workers that:

  • Perform focused tasks independently
  • Have specific domain expertise
  • Work in background with limited tools
  • Return results when complete

When to use agents:

  • Focused analysis needed (code review, validation)
  • Background processing (report generation)
  • Specialized expertise (performance analysis, security audit)
  • User wants autonomous work

When NOT to use agents:

  • User needs interactive control → Use Commands
  • Just providing guidance → Use Skills
  • Event-driven automation → Use Hooks

Agent Structure

File Location

plugin-name/
└── agents/
    ├── analyzer.md
    ├── validator.md
    └── reviewer.md

Basic Agent Format

---
name: agent-name
description: Clear description of agent's specialized purpose
color: blue|green|orange|cyan|purple
tools: [Read, Grep, Glob]
---

# Agent Name

Detailed description of agent's role and expertise.

## Your Role

[Clear role definition for the agent]

## Process

[Step-by-step workflow the agent follows]

## Analysis

[What the agent analyzes and how]

## Output Format

[Expected output structure]

## Examples

[Concrete examples of agent's work]

YAML Frontmatter

Required Fields

---
name: agent-name         # Must match filename
description: Brief desc  # What agent does
color: blue             # Visual identifier
tools: [Read, Grep]     # Available tools
---

Agent Colors

Purpose: Visual identification in UI

Available colors:

  • blue - General purpose, analysis
  • green - Testing, validation, success-focused
  • orange - Performance, optimization, warnings
  • cyan - Style, formatting, documentation
  • purple - Architecture, design, planning

Examples:

color: blue      # code-analyzer
color: green     # test-validator
color: orange    # performance-reviewer
color: cyan      # style-checker
color: purple    # architecture-reviewer

Tool Selection

Read-only agents (analysis, reporting):

tools: [Read, Grep, Glob]

Analysis with execution:

tools: [Read, Grep, Glob, Bash]

Implementation agents (rare, usually use commands instead):

tools: [Read, Grep, Glob, Bash, Edit, Write]

Available tools:

  • Read - Read files
  • Grep - Search content
  • Glob - Find files by pattern
  • Bash - Execute commands
  • Edit - Modify existing files
  • Write - Create new files
  • Task - Spawn subagents (advanced)

Agent Patterns

Analysis Agent

Purpose: Examine code and generate reports

---
name: code-analyzer
description: Analyzes code quality and identifies issues
color: blue
tools: [Read, Grep, Glob]
---

# Code Analyzer Agent

Specialized agent for code quality analysis.

## Your Role

Analyze code for:
1. Code quality issues
2. Potential bugs
3. Anti-patterns
4. Improvement opportunities

## Process

1. **Find relevant files**:
   - Use Glob to find source files
   - Filter by language/framework

2. **Analyze each file**:
   - Read file contents
   - Check for common issues
   - Identify patterns

3. **Generate report**:
   - Categorize issues by severity
   - Provide specific locations
   - Suggest fixes

## Analysis

### Code Quality Checks

**Look for**:
- Overly complex functions (>50 lines)
- Deep nesting (>3 levels)
- Duplicate code
- Missing error handling
- Poor naming

### Example Analysis

For each issue found:
```markdown
### Issue: Complex Function
Location: src/utils.ts:45
Severity: Medium

Function `processData` is 120 lines.
Recommendation: Break into smaller functions

Output Format

# Code Analysis Report

## Summary
- Files analyzed: 25
- Issues found: 12
- Critical: 2
- Warnings: 10

## Critical Issues

### Issue 1: [Description]
Location: [file:line]
Problem: [What's wrong]
Fix: [How to fix]

## Warnings

[Similar format]

## Recommendations

1. [High-level suggestion]
2. [Another suggestion]

### Validation Agent

**Purpose**: Verify correctness and completeness

```yaml
---
name: spec-validator
description: Validates API specifications for completeness
color: green
tools: [Read, Grep, Glob, Bash]
---

# Spec Validator Agent

Validates OpenAPI/AsyncAPI specifications.

## Your Role

Ensure API specs are:
1. Syntactically valid
2. Complete and consistent
3. Following best practices
4. Ready for implementation

## Process

1. **Find spec files**:
   - Glob for `*.openapi.{yml,yaml,json}`
   - Glob for `*.asyncapi.{yml,yaml,json}`

2. **Validate syntax**:
   - Use validator tool (Bash)
   - Check YAML/JSON parsing
   - Verify spec version

3. **Check completeness**:
   - All endpoints documented
   - Request/response schemas defined
   - Authentication specified
   - Error responses included

4. **Verify consistency**:
   - Schema references valid
   - No duplicate operations
   - Consistent naming

## Validation Checks

### Syntax
- [ ] Valid YAML/JSON
- [ ] Correct OpenAPI/AsyncAPI version
- [ ] No parsing errors

### Completeness
- [ ] All paths have descriptions
- [ ] All parameters documented
- [ ] All responses defined
- [ ] Schemas have examples

### Best Practices
- [ ] Consistent naming
- [ ] Proper use of references
- [ ] Security schemes defined
- [ ] Version specified

## Output Format

```markdown
# Spec Validation Report

## File: api.openapi.yml

### Status: ⚠️ WARNINGS

### Syntax ✓
- Valid YAML
- OpenAPI 3.0.0
- No parsing errors

### Completeness Issues

#### Missing Response Schemas
- GET /users - 404 response not defined
- POST /users - 400 response missing

#### Missing Descriptions
- Parameter `limit` in GET /users
- Schema `UserResponse`

### Best Practice Violations

#### Inconsistent Naming
- `/users` vs `/user-orders` (use consistent pluralization)

## Recommendations

1. Add error response definitions (400, 404, 500)
2. Document all parameters and schemas
3. Use consistent naming convention
4. Add examples for complex schemas

## Next Steps

Fix the issues above, then run:
/spec:validate --strict

### Review Agent

**Purpose**: Provide expert feedback

```yaml
---
name: security-reviewer
description: Reviews code for security vulnerabilities
color: orange
tools: [Read, Grep, Glob]
---

# Security Reviewer Agent

Specialized security audit agent.

## Your Role

Identify security vulnerabilities:
1. Injection attacks (SQL, XSS, Command)
2. Authentication/authorization issues
3. Insecure dependencies
4. Data exposure
5. Cryptographic weaknesses

## Process

1. **Scan for vulnerability patterns**:
   - Grep for dangerous functions
   - Check input validation
   - Review authentication logic

2. **Analyze each finding**:
   - Determine severity
   - Assess exploitability
   - Suggest remediation

3. **Generate security report**:
   - Prioritize by risk
   - Provide specific fixes
   - Include references

## Detection Patterns

### SQL Injection

Search for:

  • String concatenation in SQL queries
  • Unparameterized queries
  • Direct user input in SQL

### XSS

Search for:

  • Unescaped user input in HTML
  • innerHTML with dynamic content
  • Unsafe DOM manipulation

### Command Injection

Search for:

  • Shell commands with user input
  • Unvalidated file paths
  • Process execution with dynamic args

## Output Format

```markdown
# Security Review Report

## Summary
- Critical: 2
- High: 5
- Medium: 8
- Low: 3

## Critical Vulnerabilities

### SQL Injection in User Query
**Location**: src/database.ts:45
**Severity**: CRITICAL
**CWE**: CWE-89

**Vulnerable Code**:
```typescript
const query = `SELECT * FROM users WHERE id = ${userId}`;
db.execute(query);

Exploitation: Attacker can inject SQL: 1 OR 1=1--

Fix:

const query = `SELECT * FROM users WHERE id = ?`;
db.execute(query, [userId]);

References:

[Continue for other issues]

Recommendations

  1. Implement parameterized queries everywhere
  2. Add input validation middleware
  3. Enable SQL injection protection in ORM
  4. Security code review before deployment

Meta Agent

Purpose: Coordinate other agents or complex workflows

---
name: meta-validator
description: Orchestrates multi-faceted validation
color: purple
tools: [Read, Grep, Glob, Bash, Task]
---

# Meta Validator Agent

Coordinates comprehensive validation.

## Your Role

Run multiple validation checks:
1. Technical validation (syntax, compilation)
2. Conceptual validation (design review)
3. Integration validation (component interaction)

## Process

1. **Technical Validation**:
   - Generate minimal PoC code
   - Attempt to compile/run
   - Check for basic errors

2. **Conceptual Validation**:
   - Analyze design decisions
   - Check scalability
   - Review architecture

3. **Integration Validation**:
   - Verify component compatibility
   - Check dependency conflicts
   - Test integration points

4. **Generate comprehensive report**:
   - Combine all findings
   - Prioritize issues
   - Recommend next steps

## Coordination

**Can launch subagents**:

Launch syntax-checker agent for file X Launch security-reviewer for auth module Launch performance-analyzer for query optimization


Wait for all agents to complete, then synthesize results.

## Output Format

```markdown
# Meta Validation Report

## Technical Validation ✓
- PoC compiles successfully
- No syntax errors
- Basic functionality works

## Conceptual Validation ⚠️

### Scalability Concern
Current design loads all users into memory.
With 1M+ users, this will cause OOM errors.

**Recommendation**: Implement pagination

### Architecture Question
Using REST for real-time updates.
Consider WebSockets for better performance.

## Integration Validation ✓
- All dependencies compatible
- No version conflicts
- Integration tests pass

## Overall Assessment

**Status**: READY WITH MODIFICATIONS

**Required changes**:
1. Add pagination (CRITICAL)
2. Consider WebSocket migration (OPTIONAL)

**Once fixed**: Ready to implement

## Agent Best Practices

### Clear Role Definition

**Good**:
```markdown
## Your Role

Analyze test coverage:
1. Identify untested code
2. Measure coverage percentage
3. Suggest missing test cases
4. Prioritize by criticality

Bad:

## Your Role

You're a testing agent. Help with tests.

Specific Process

Good:

## Process

1. Find test files:
   - Glob: `**/*.test.{js,ts}`
   - Glob: `**/*.spec.{js,ts}`

2. Find source files:
   - Glob: `src/**/*.{js,ts}`

3. For each source file:
   - Check if corresponding test exists
   - Read test and source
   - Identify untested functions

4. Calculate coverage:
   - Total functions: X
   - Tested functions: Y
   - Coverage: Y/X * 100%

5. Generate report

Bad:

## Process

1. Check test coverage
2. Make a report

Structured Output

Good:

## Output Format

```markdown
# Test Coverage Report

## Summary
- Coverage: 68%
- Files: 25 total, 18 tested
- Functions: 120 total, 82 tested

## Untested Files
- src/utils/helper.ts (0% coverage)
- src/api/legacy.ts (15% coverage)

## Missing Tests by Priority

### Critical
- `processPayment()` - handles money
- `authenticateUser()` - security critical

### High
- `validateInput()` - data integrity
- `sendEmail()` - user-facing feature

## Recommendations
1. Add tests for critical functions
2. Increase coverage to 80% target

**Bad**:
```markdown
## Output Format

Return a report with the findings.

Advanced Techniques

Conditional Analysis

## Process

1. **Detect project type**:
   - If `package.json` → Node.js
   - If `requirements.txt` → Python
   - If `pom.xml` → Java

2. **Use language-specific checks**:

**For Node.js**:
- Check for `npm audit` vulnerabilities
- Validate package.json scripts
- Check for outdated dependencies

**For Python**:
- Check for `safety` vulnerabilities
- Validate requirements.txt
- Check for deprecated packages

**For Java**:
- Check for known CVEs in dependencies
- Validate pom.xml
- Check for outdated libraries

Progressive Analysis

## Process

1. **Quick scan** (surface issues):
   - Run in <30 seconds
   - Find obvious problems
   - Return preliminary results

2. **If issues found**:
   **Deep analysis** (thorough investigation):
   - Detailed examination
   - Root cause analysis
   - Comprehensive recommendations

3. **If no issues in quick scan**:
   Return clean report, skip deep analysis

Multi-Stage Reporting

## Process

1. **Initial findings**:
   Report issues as found (streaming)

2. **Analysis phase**:
   Investigate each issue

3. **Final report**:
   Comprehensive summary with prioritization

Tool Usage Patterns

Read + Grep + Glob Combo

1. **Find files**: Glob `src/**/*.ts`
2. **Search patterns**: Grep `"TODO|FIXME|HACK"`
3. **Read context**: Read files with matches
4. **Analyze**: Review surrounding code

Bash for Validation

1. **Run linter**:
   ```bash
   npm run lint 2>&1
  1. Parse output: Extract error messages and locations

  2. Categorize: Group by error type

  3. Report: Include in analysis


## Testing Agents

### Test Scenarios

```markdown
Test security-reviewer agent:

1. **Clean code**:
   Input: Secure, parameterized queries
   Expected: Clean report, no issues

2. **SQL injection**:
   Input: String concatenation in SQL
   Expected: Critical vulnerability reported

3. **Mixed issues**:
   Input: Some secure, some vulnerable
   Expected: Identifies only vulnerable code

4. **False positives**:
   Input: Safe dynamic queries (ORM-generated)
   Expected: Doesn't flag as vulnerable

Common Pitfalls

Too Broad Scope

Problem:

---
name: code-helper
description: Helps with code
tools: [Read, Grep, Glob, Bash, Edit, Write]
---

Fix:

---
name: performance-analyzer
description: Identifies performance bottlenecks and optimization opportunities
color: orange
tools: [Read, Grep, Glob, Bash]
---

Vague Instructions

Problem:

## Your Role
Review code and provide feedback.

Fix:

## Your Role

Perform style consistency review:
1. Check naming conventions (camelCase vs snake_case)
2. Verify formatting consistency (indentation, spacing)
3. Review documentation completeness (JSDoc for public APIs)
4. Identify commented-out code
5. Check for TODO cleanup needs

No Output Structure

Problem:

## Output
Provide a report of findings.

Fix:

## Output Format

```markdown
# Style Review Report

## Naming Issues
- Inconsistent casing: `getUserData()` vs `get_user_name()`
- Vague names: `data` in api.ts:45 (suggest: `userData`)

## Formatting Issues
- Inconsistent indentation: mix of 2 and 4 spaces
- Long lines: utils.ts:120 (145 chars, exceeds 120 limit)

## Documentation Gaps
- Missing JSDoc: `processPayment()`, `calculateTax()`
- Found 12 TODOs: create issues for tracking

## Recommendations
1. Configure Prettier/ESLint
2. Add pre-commit hooks
3. Document public APIs

## References

- Official agents documentation: https://code.claude.com/docs/en/agents
- Plugin reference: https://code.claude.com/docs/en/plugins-reference
- Official plugin examples: https://github.com/anthropics/claude-code/tree/main/plugins

Commands vs Skills

Guide to choosing between commands/ (flat files) and skills/ (folders) for creating slash commands.

When to Use

Activate when:

  • User asks "commands or skills?"
  • Discussing command structure
  • Migrating from commands to skills
  • Questions about slash command creation

Commands and Skills are Equivalent

Both create slash commands that users invoke with /plugin:name:

AspectCommandsSkills
Locationcommands/name.mdskills/name/SKILL.md
Invocation/plugin:name/plugin:name
FeaturesBasic frontmatter, argumentsAdvanced frontmatter, supporting files
Use caseSimple, single-file commandsComplex workflows, need supporting files
StatusWorks, backward compatiblePreferred for new development

When to Use Each

Use Skills (skills/name/SKILL.md):

  • Preferred for all new development
  • Need supporting files (templates, examples, scripts)
  • Want user-invocable: false for background skills
  • Want disable-model-invocation: true for manual-only skills
  • Complex workflows needing organization

Use Commands (commands/name.md):

  • Maintaining existing commands
  • Prefer flat file structure
  • Very simple single-purpose commands
  • Backward compatibility needed

Command Structure

File Location

plugin-name/
└── commands/
    ├── command1.md
    ├── command2.md
    └── subcommand/
        └── action.md      # For /plugin:subcommand:action

Command Naming

Plugin auto-prefixes command names:

File: commands/start.md Plugin: workflow Invoked as: /workflow:start

CRITICAL: Don't duplicate prefix!

  • ✓ File: start.md → /workflow:start
  • ✗ File: workflow:start.md → /workflow:workflow:start

Basic Command Format

---
name: command-name
description: Brief description of what command does
usage: |
  /plugin:command <required-arg> [optional-arg] --flag value
examples:
  - /plugin:command example1
  - /plugin:command example2 --verbose
---

# Command Name

Detailed description of command purpose and behavior.

## Arguments

### Required
- `arg1` - Description of required argument

### Optional
- `arg2` - Description of optional argument (default: value)

### Flags
- `--flag` - Description of flag

## Process

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

## Examples

### Example 1: Basic Usage
```bash
/plugin:command basic-example

What happens:

  • [Explain the outcome]

Example 2: Advanced Usage

/plugin:command complex-example --flag value

What happens:

  • [Explain the outcome]

Integration

  • Works with: [Related plugins/commands]
  • Requires: [Dependencies if any]

## YAML Frontmatter

### Required Fields

```yaml
---
name: command-name        # Must match filename
description: Brief desc   # Shows in help text
---

Full Frontmatter

---
name: command-name
description: One-line description for command listing
usage: |
  /plugin:command <required> [optional] --flag value
  /plugin:command --help
examples:
  - /plugin:command example1
  - /plugin:command example2 --verbose
  - /plugin:command --interactive
aliases:
  - shortname
  - alternate-name
---

Argument Patterns

Positional Arguments

---
usage: |
  /plugin:create <plugin-name> [directory]
---

# Create Command

## Arguments
- `plugin-name` (required) - Name of plugin to create
- `directory` (optional) - Target directory (default: ./plugins)

## Examples
```bash
/plugin:create my-plugin
/plugin:create my-plugin ./custom-dir

### Flags and Options

```yaml
---
usage: |
  /plugin:validate [path] --strict --format <json|text>
---

# Validate Command

## Flags
- `--strict` - Enable strict validation mode
- `--format <format>` - Output format: json or text (default: text)

## Examples
```bash
/plugin:validate                    # Current directory, text format
/plugin:validate --strict           # Strict mode
/plugin:validate --format json      # JSON output
/plugin:validate ./my-plugin --strict --format json

### Subcommands

```yaml
---
usage: |
  /plugin:add skill <name>
  /plugin:add command <name>
  /plugin:add agent <name>
  /plugin:add hook <event>
---

# Add Command

Adds a component to existing plugin.

## Subcommands

### skill
Add a new skill to the plugin.
```bash
/plugin:add skill my-skill

command

Add a new command to the plugin.

/plugin:add command my-command

agent

Add a new agent to the plugin.

/plugin:add agent my-agent

hook

Add an event hook to the plugin.

/plugin:add hook PreToolUse

## Command Patterns

### Simple Action Command

**Purpose**: Single, straightforward action

```yaml
---
name: build
description: Build the project
usage: /plugin:build [--watch]
examples:
  - /plugin:build
  - /plugin:build --watch
---

# Build Command

Compiles the project.

## Process

1. Clean output directory
2. Compile source files
3. Copy assets
4. Generate build report

## Flags

- `--watch` - Watch mode for development

Interactive Workflow Command

Purpose: Multi-step guided process

---
name: init
description: Initialize new project interactively
usage: /plugin:init [project-name]
examples:
  - /plugin:init
  - /plugin:init my-project
---

# Init Command

Interactive project initialization.

## Process

1. **Prompt for project details**:
   - Project name (if not provided)
   - Description
   - License type
   - Dependencies

2. **Create structure**:
   - Generate directory layout
   - Create configuration files
   - Install dependencies

3. **Verify**:
   - Run validation
   - Show summary

Multi-Action Command

Purpose: Multiple related actions in one command

---
name: task
description: Manage tasks
usage: |
  /plugin:task create <title>
  /plugin:task list [--status pending|done]
  /plugin:task complete <id>
  /plugin:task delete <id>
examples:
  - /plugin:task create "Implement feature"
  - /plugin:task list
  - /plugin:task list --status pending
  - /plugin:task complete 1
---

# Task Command

Complete task management.

## Subcommands

### create
Create a new task.

### list
List all tasks, optionally filtered by status.

### complete
Mark a task as completed.

### delete
Delete a task.

Delegating Command

Purpose: Routes to skills or agents

---
name: start
description: Start workflow with auto-detection
usage: |
  /plugin:start <description>
  /plugin:start <description> --mode <auto|spec|plan|simple>
examples:
  - /plugin:start "Implement user authentication"
  - /plugin:start "Fix login bug" --mode simple
---

# Start Command

Initiates workflow with complexity detection.

## Process

1. **Analyze request**:
   - Parse description
   - Detect complexity
   - Identify project context

2. **Route to appropriate workflow**:
   - Complex → Spec + Validation
   - Medium → Spec + TDD
   - Simple → Simple Planning

3. **Hand off to skill/agent**:
   - Invoke appropriate skill
   - Or launch specialized agent

Using AskUserQuestion

Commands can ask interactive questions:

## Process

1. **Gather plugin details**:
   Use AskUserQuestion to ask:
   - Plugin name
   - Description
   - Components to include (commands, skills, agents, hooks)
   - Author name

2. **Create structure**:
   Based on user responses, generate plugin files

3. **Confirm**:
   Show what was created

Example in command:

Ask user to choose components:
- [ ] Commands - User-invoked actions
- [ ] Skills - Guidance and workflows
- [ ] Agents - Autonomous workers
- [ ] Hooks - Event handlers

Then create the selected components.

Integration Patterns

With Skills

## Process

1. Invoke related skill:
   - Skill provides the methodology
   - Command triggers the workflow

**Example**:
```bash
/tdd:start "User authentication"

→ Invokes test-driven-development skill → Guides through RED-GREEN-REFACTOR


### With Agents

```markdown
## Process

1. Launch specialized agent:

Launch meta-validator agent to check spec


2. Wait for agent completion

3. Present results

With Hooks

## Process

1. Command performs action
2. Hook validates/logs automatically

**Example**:
- User runs: `/plugin:deploy`
- PreToolUse hook checks environment
- PostToolUse hook logs deployment

With Other Commands

## Process

1. Run prerequisite commands:
   ```bash
   /workflow:spec "Create API spec"
   /workflow:plan "Implement spec"
   /workflow:start
  1. Chain commands for workflows

## Best Practices

### Clear Documentation

**Good**:
```yaml
---
name: validate
description: Validate plugin structure and metadata
usage: |
  /plugin:validate [path]
  /plugin:validate [path] --strict
examples:
  - /plugin:validate
  - /plugin:validate ./my-plugin
  - /plugin:validate ./my-plugin --strict
---

# Validate Command

Checks plugin for structural and metadata issues.

## What It Checks
- plugin.json exists and is valid JSON
- All referenced components exist
- YAML frontmatter is valid
- Skills are folders with SKILL.md
- README.md exists

## Output
Generates validation report with errors and warnings.

Argument Validation

## Process

1. **Validate arguments**:
   - Check required args provided
   - Validate arg formats
   - Check file paths exist

2. **If validation fails**:

❌ Invalid argument:

Usage: /plugin:command [optional]

Examples:

  • /plugin:command valid-example

3. **If validation passes**:
Continue with command logic

Error Handling

## Process

1. Attempt operation

2. **If error occurs**:

❌ Operation Failed

Error: [Clear error message]

Common solutions:

  • Check that [requirement]
  • Verify [dependency]

Need help? /plugin:command --help


3. **If successful**:

✓ Operation completed

Results:

  • [What was done]

Next steps:

  • [Suggested actions]

Progress Indication

For long-running commands:

## Process

1. Show what's happening:

Creating plugin structure... ✓ Created plugin.json ✓ Created commands/ ✓ Created skills/ ⏳ Installing dependencies...


2. Update as progress occurs

3. Show completion:

✓ Plugin created successfully

Location: ./plugins/my-plugin

Next: /plugin:add skill my-skill

Advanced Techniques

Dynamic Arguments

## Process

1. **Detect context**:
   - If in git repo → offer git-related options
   - If package.json → offer npm-related options
   - If requirements.txt → offer pip-related options

2. **Adapt arguments**:
   - Show relevant flags for detected context
   - Hide irrelevant options

Conditional Execution

## Process

1. **Check prerequisites**:
   - Required files exist?
   - Required tools installed?
   - Valid configuration?

2. **If prerequisites missing**:

⚠️ Prerequisites Missing

Required:

  • [Tool/file needed]

Install: [How to install]


3. **If prerequisites met**:
Proceed with command

Command Composition

## Process

1. **Run subcommands in sequence**:
   ```bash
   # Equivalent to running:
   /plugin:create my-plugin
   /plugin:add skill my-skill
   /plugin:add command start
   /plugin:validate
  1. Stop on first error:
    • If any subcommand fails, stop
    • Show which step failed
    • Suggest how to recover

## Testing Commands

### Manual Testing Checklist

- [ ] Command invokes correctly
- [ ] Required arguments validated
- [ ] Optional arguments work
- [ ] Flags work as documented
- [ ] Error messages are clear
- [ ] Success messages are informative
- [ ] Help text is accurate
- [ ] Examples work as shown

### Test Scenarios

```markdown
Test /plugin:create:

1. **Valid input**:
   /plugin:create my-plugin
   Expected: Plugin created successfully

2. **Missing argument**:
   /plugin:create
   Expected: Error about missing plugin-name

3. **Invalid characters**:
   /plugin:create my@plugin
   Expected: Error about invalid name format

4. **Existing plugin**:
   /plugin:create my-plugin (when exists)
   Expected: Error or prompt to overwrite

5. **Help flag**:
   /plugin:create --help
   Expected: Show usage and examples

Common Pitfalls

Vague Usage Documentation

Problem:

---
usage: /plugin:command [options]
---

Fix:

---
usage: |
  /plugin:command <file> [--format json|yaml]
  /plugin:command --help
examples:
  - /plugin:command config.json
  - /plugin:command data.yaml --format yaml
---

Missing Examples

Problem:

---
name: deploy
description: Deploy application
---

Fix:

---
name: deploy
description: Deploy application to production
usage: |
  /plugin:deploy [environment] [--dry-run]
examples:
  - /plugin:deploy staging
  - /plugin:deploy production
  - /plugin:deploy production --dry-run
---

Poor Error Messages

Problem:

Error: Invalid input

Fix:

❌ Invalid plugin name: "my@plugin"

Plugin names must:
- Use lowercase letters
- Use hyphens for spaces
- No special characters

Examples:
- my-plugin ✓
- user-manager ✓
- my@plugin ✗

Try: /plugin:create my-plugin

Migrating from Commands to Skills

Convert existing commands to skills for additional features:

1. Create skill folder:

# Old: commands/deploy.md
# New: skills/deploy/SKILL.md
mkdir skills/deploy

2. Move and rename:

mv commands/deploy.md skills/deploy/SKILL.md

3. Update frontmatter (if needed):

---
name: deploy
description: Deploy application to production
disable-model-invocation: true  # New feature - manual only
---

4. Add supporting files (if helpful):

skills/deploy/
├── SKILL.md                # Main instructions
├── templates/              # Deployment templates
│   └── prod-config.yaml
└── scripts/                # Helper scripts
    └── verify.sh

Both work: Your old commands/deploy.md keeps working. Migrate when you need advanced features.

Key Differences

Commands Features

---
name: review
description: Review code quality
usage: |
  /plugin:review <file>
examples:
  - /plugin:review src/app.js
---

Review instructions...

Skills Additional Features

---
name: review
description: Review code quality
argument-hint: <file> [--strict]
user-invocable: true                    # Can hide from menu
disable-model-invocation: false         # Can prevent auto-invoke
allowed-tools: Read, Grep, Glob         # Restrict tool access
context: fork                           # Can run in subagent
---

Review instructions...

See [examples.md](examples.md) for patterns.  # Supporting files

Official Documentation

Create Plugin Skill

Interactive wizard for creating new Claude Code plugins with proper structure and validation.

When to Use

  • User invokes /plugin-creator:create-plugin
  • User asks "create a plugin"
  • User mentions "new plugin" or "scaffold plugin"
  • User wants to start plugin development

Official Documentation

Reference these official resources:

Process

1. Initialize Plugin

/plugin-creator:create-plugin my-awesome-plugin

The wizard will:

  1. Invoke custom-plugin-architect agent
  2. Ask clarifying questions:
    • What's the plugin purpose?
    • What type? (workflow, analysis, utility, meta)
    • What components needed? (skills, agents, hooks)
  3. Suggest optimal architecture
  4. Create base structure

2. Create Structure

Creates complete plugin directory:

my-awesome-plugin/
├── .claude-plugin/
│   └── plugin.json          # Plugin manifest
├── skills/                   # User-invocable workflows
│   └── (empty, ready for skills)
├── agents/                   # Specialized sub-agents
│   └── (empty, ready for agents)
├── hooks/                    # Event handlers
│   └── (empty, ready for hooks)
└── README.md                 # User documentation

3. Generate plugin.json

Creates valid manifest with:

{
  "name": "my-awesome-plugin",
  "version": "1.0.0",
  "description": "Brief description of plugin",
  "author": {
    "name": "Your Name"
  },
  "keywords": ["category", "tags"],
  "repository": {
    "type": "git",
    "url": "https://github.com/user/repo"
  },
  "license": "MIT"
}

Note: Commands, skills, agents, hooks are auto-discovered from directories. Don't list them manually in plugin.json.

4. Next Steps

After scaffolding, the wizard guides you to:

  1. Add Skills → Use /skill-creator:create for focused skill creation
  2. Add Agents → The custom-agent-development skill auto-activates to guide
  3. Add Hooks → The custom-hook-development skill auto-activates to guide
  4. Validate → Run /plugin-creator:validate-plugin-structure to check structure
  5. Test → Symlink and test: ln -s $(pwd) ~/.claude/plugins/my-awesome-plugin

Examples

Example 1: Workflow Plugin

/plugin-creator:create-plugin task-workflow

# Wizard asks:
# - Purpose? "Structured task management with dependencies"
# - Type? workflow
# - Components? skills, agents
#
# Creates:
# - Base structure
# - README template
# - plugin.json with workflow tags

Next steps:

# Add orchestrator skill
/skill-creator:create orchestrator

# Add task-organizer agent
# (custom-agent-development skill guides you)

Example 2: Analysis Plugin

/plugin-creator:create-plugin code-analyzer

# Wizard asks:
# - Purpose? "Multi-agent code quality analysis"
# - Type? analysis
# - Components? skills, agents
#
# Creates:
# - Base structure
# - README for analysis plugin
# - plugin.json with quality tags

Next steps:

# Add main analysis skill
/skill-creator:create analyze

# Add specialized agents manually
# (custom-agent-development skill guides you)

Example 3: Utility Plugin

/plugin-creator:create-plugin dev-utils

# Wizard asks:
# - Purpose? "Developer utilities and helpers"
# - Type? utility
# - Components? skills
#
# Creates:
# - Minimal structure
# - Skills directory ready

Component Types Guide

Skills

Purpose: User-invocable workflows or auto-activating helpers

When to use:

  • Main entry points for users
  • Orchestration logic
  • Workflow guidance
  • Auto-activating helpers

Create with: /skill-creator:create skill-name

Structure:

skills/
└── skill-name/
    └── SKILL.md

Agents

Purpose: Specialized autonomous workers for parallel execution

When to use:

  • Specialized analysis (security, performance, etc.)
  • Parallel execution tasks
  • Focused expertise areas

Create with: Manual creation (auto-activating skill guides you)

Structure:

agents/
└── custom-agent-name.md

Important: Prefix with custom- to avoid collisions with built-in agents.

Hooks

Purpose: Event-driven automation and validation

When to use:

  • Validate before tool execution
  • Process after tool completion
  • Session initialization
  • Custom notifications

Create with: Manual creation (auto-activating skill guides you)

Structure:

hooks/
└── PreToolUse.sh  # Must be executable

Validation

After creating your plugin, validate it:

cd my-awesome-plugin
/plugin-creator:validate-plugin-structure

Checks:

  • ✓ plugin.json format (against schema)
  • ✓ Directory structure
  • ✓ Skills are folders with SKILL.md
  • ✓ Agents have custom- prefix
  • ✓ README completeness

Best Practices

Plugin Design

  • Single Responsibility: One clear purpose per plugin
  • Modularity: Independent, composable components
  • Documentation: Clear README with examples
  • Attribution: Credit sources and inspirations

Naming Conventions

  • Plugin name: kebab-case (e.g., task-management)
  • Skill names: kebab-case (e.g., workflow-router)
  • Agent names: custom- prefix + kebab-case (e.g., custom-validator)
  • Hook names: Official event names (e.g., PreToolUse.sh)

Structure Guidelines

  • Skills: Always folders with SKILL.md (not flat .md files)
  • Agents: Flat .md files with frontmatter
  • Hooks: Executable .sh files (chmod +x)
  • Auto-discovery: Don't manually list components in plugin.json

user-invocable Flags

  • Default (omit flag): Skill is user-invocable
  • Set to false: Skill only auto-activates, never invoked directly

Integration with Other Plugins

skill-creator

For focused skill creation:

/skill-creator:create my-skill

workflow

For structured plugin development:

/workflow:start "Create code-review plugin"
# Stages: Spec → Dev → Exec

validation

Always validate before distributing:

/plugin-creator:validate-plugin-structure

Common Issues

Plugin not loading?

  • Check plugin.json is valid JSON
  • Ensure symlinked to ~/.claude/plugins/
  • Validate with /plugin-creator:validate-plugin-structure

Skills not activating?

  • Verify "When to Use" section is clear
  • Check skills are folders (not flat .md)
  • Ensure SKILL.md is uppercase

Agents not available?

  • Confirm custom- prefix
  • Check valid tools list
  • Verify frontmatter syntax

Resources

Hook Development Skill

Guide to creating event-driven hooks for Claude Code plugins.

When to Use

Activate when:

  • Creating event hooks
  • User asks about automation
  • Implementing validation logic
  • Questions about hook events

What Are Hooks?

Hooks are executable scripts that respond to events:

  • PreToolUse - Before any tool execution
  • PostToolUse - After tool execution
  • SessionStart - Session initialization
  • SessionEnd - Session cleanup
  • Stop - Before session ends
  • SubagentStop - When agent completes
  • UserPromptSubmit - After user input
  • PreCompact - Before context compression
  • Notification - System notifications

When to use hooks:

  • Automatic validation before actions
  • Event-driven automation
  • Logging and auditing
  • Safety checks and enforcement

When NOT to use hooks:

  • User-invoked actions → Use Commands
  • Guidance and workflows → Use Skills
  • Focused analysis → Use Agents

Hook Structure

File Location

plugin-name/
└── hooks/
    ├── PreToolUse.sh
    ├── PostToolUse.sh
    ├── SessionStart.sh
    └── Stop.sh

Basic Hook Format

#!/bin/bash
# hooks/PreToolUse.sh

# Hook receives event data via environment variables
# Exit codes:
#   0 - Allow action to proceed
#   1 - Block action
# Output to stderr - shown to user

# Example: Block dangerous operations
if [[ "$TOOL_NAME" == "Bash" ]] && [[ "$COMMAND" == *"rm -rf"* ]]; then
  echo "⛔ Dangerous command blocked: rm -rf" >&2
  exit 1
fi

# Allow all other actions
exit 0

Making Hooks Executable

CRITICAL: Hooks must be executable:

chmod +x hooks/PreToolUse.sh
chmod +x hooks/PostToolUse.sh

Available Hooks

PreToolUse

Triggers: Before any tool execution

Use cases:

  • Validate tool arguments
  • Block dangerous operations
  • Enforce workflow rules
  • Check prerequisites

Environment variables:

  • TOOL_NAME - Tool being invoked (Bash, Read, Edit, etc.)
  • TOOL_ARGS - Tool arguments (JSON)
  • Additional tool-specific vars

Example - Block destructive commands:

#!/bin/bash
# hooks/PreToolUse.sh

if [[ "$TOOL_NAME" == "Bash" ]]; then
  COMMAND=$(echo "$TOOL_ARGS" | jq -r '.command')

  # Block force push to main
  if [[ "$COMMAND" == *"git push"*"--force"* ]] && [[ "$COMMAND" == *"main"* ]]; then
    echo "⛔ Force push to main blocked" >&2
    echo "This is dangerous. Use a feature branch." >&2
    exit 1
  fi
fi

exit 0

PostToolUse

Triggers: After tool execution

Use cases:

  • Log operations
  • Trigger follow-up actions
  • Update external systems
  • Collect metrics

Environment variables:

  • TOOL_NAME - Tool that was executed
  • TOOL_RESULT - Tool output
  • EXIT_CODE - Tool exit code

Example - Log all bash commands:

#!/bin/bash
# hooks/PostToolUse.sh

if [[ "$TOOL_NAME" == "Bash" ]]; then
  COMMAND=$(echo "$TOOL_ARGS" | jq -r '.command')
  TIMESTAMP=$(date -u +"%Y-%m-%dT%H:%M:%SZ")

  echo "$TIMESTAMP | $COMMAND | Exit: $EXIT_CODE" >> ~/.claude/command.log
fi

exit 0

SessionStart

Triggers: When Claude Code session begins

Use cases:

  • Initialize environment
  • Load configuration
  • Check dependencies
  • Set up workspace

Example - Verify environment:

#!/bin/bash
# hooks/SessionStart.sh

# Check required tools
MISSING=()

command -v git >/dev/null 2>&1 || MISSING+=("git")
command -v node >/dev/null 2>&1 || MISSING+=("node")
command -v jq >/dev/null 2>&1 || MISSING+=("jq")

if [ ${#MISSING[@]} -gt 0 ]; then
  echo "⚠️  Missing tools: ${MISSING[*]}" >&2
  echo "Some plugin features may not work." >&2
fi

# Load project config
if [ -f ".claude/config.json" ]; then
  echo "✓ Loaded project configuration" >&2
fi

exit 0

SessionEnd

Triggers: When session ends normally

Use cases:

  • Cleanup temporary files
  • Save session state
  • Push uncommitted work
  • Generate reports

Example - Cleanup:

#!/bin/bash
# hooks/SessionEnd.sh

# Clean up temp files
rm -rf /tmp/claude-session-*

# Save session summary
SUMMARY_FILE="$HOME/.claude/sessions/$(date +%Y%m%d-%H%M%S).log"
echo "Session ended at $(date)" > "$SUMMARY_FILE"

exit 0

Stop

Triggers: Before session stops (user can cancel)

Use cases:

  • Warn about uncommitted changes
  • Prompt for cleanup
  • Check for running processes
  • Save work in progress

Example - Check uncommitted changes:

#!/bin/bash
# hooks/Stop.sh

# Check for uncommitted changes
if git rev-parse --git-dir > /dev/null 2>&1; then
  if ! git diff-index --quiet HEAD --; then
    echo "⚠️  You have uncommitted changes" >&2
    echo "Consider committing or stashing before exiting." >&2

    # Don't block, just warn
    exit 0
  fi
fi

exit 0

SubagentStop

Triggers: When a spawned agent completes

Use cases:

  • Process agent results
  • Trigger next step in workflow
  • Log agent completion
  • Update task status

Environment variables:

  • AGENT_NAME - Agent that completed
  • AGENT_RESULT - Agent output
  • AGENT_STATUS - Success/failure

Example - Log agent completion:

#!/bin/bash
# hooks/SubagentStop.sh

TIMESTAMP=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
echo "$TIMESTAMP | Agent: $AGENT_NAME | Status: $AGENT_STATUS" >> ~/.claude/agents.log

exit 0

UserPromptSubmit

Triggers: After user submits a prompt

Use cases:

  • Track user requests
  • Analyze patterns
  • Trigger automations
  • Log interactions

Environment variables:

  • USER_PROMPT - The user's input

Example - Track prompts:

#!/bin/bash
# hooks/UserPromptSubmit.sh

TIMESTAMP=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
echo "$TIMESTAMP | $USER_PROMPT" >> ~/.claude/prompts.log

exit 0

PreCompact

Triggers: Before context window compression

Use cases:

  • Save context snapshot
  • Export important data
  • Preserve state
  • Generate checkpoint

Example - Save context snapshot:

#!/bin/bash
# hooks/PreCompact.sh

SNAPSHOT_DIR="$HOME/.claude/snapshots"
mkdir -p "$SNAPSHOT_DIR"

TIMESTAMP=$(date +%Y%m%d-%H%M%S)
SNAPSHOT_FILE="$SNAPSHOT_DIR/context-$TIMESTAMP.json"

# Save context metadata
cat > "$SNAPSHOT_FILE" <<EOF
{
  "timestamp": "$(date -u +"%Y-%m-%dT%H:%M:%SZ")",
  "working_directory": "$(pwd)",
  "git_branch": "$(git branch --show-current 2>/dev/null || echo 'none')",
  "git_commit": "$(git rev-parse HEAD 2>/dev/null || echo 'none')"
}
EOF

exit 0

Notification

Triggers: System notifications

Use cases:

  • Send alerts
  • Update external systems
  • Trigger integrations
  • Custom notifications

Example - Send notification:

#!/bin/bash
# hooks/Notification.sh

# Forward to system notification
osascript -e "display notification \"$NOTIFICATION_MESSAGE\" with title \"Claude Code\""

exit 0

Hook Patterns

Validation Hook

Purpose: Enforce rules and prevent mistakes

#!/bin/bash
# hooks/PreToolUse.sh

# Enforce TDD: Block code changes without tests
if [[ "$TOOL_NAME" == "Edit" ]] || [[ "$TOOL_NAME" == "Write" ]]; then
  FILE_PATH=$(echo "$TOOL_ARGS" | jq -r '.file_path')

  # If editing source code
  if [[ "$FILE_PATH" == *"/src/"* ]] && [[ "$FILE_PATH" != *".test."* ]]; then
    # Check if corresponding test exists
    TEST_FILE="${FILE_PATH/.ts/.test.ts}"

    if [ ! -f "$TEST_FILE" ]; then
      echo "⛔ TDD Violation" >&2
      echo "No test file found for: $FILE_PATH" >&2
      echo "Create test first: $TEST_FILE" >&2
      exit 1
    fi
  fi
fi

exit 0

Logging Hook

Purpose: Audit trail of operations

#!/bin/bash
# hooks/PostToolUse.sh

LOG_FILE="$HOME/.claude/audit.log"
TIMESTAMP=$(date -u +"%Y-%m-%dT%H:%M:%SZ")

# Log all tool usage
echo "$TIMESTAMP | $TOOL_NAME | $TOOL_ARGS" >> "$LOG_FILE"

# Rotate log if too large
if [ -f "$LOG_FILE" ] && [ $(wc -l < "$LOG_FILE") -gt 10000 ]; then
  mv "$LOG_FILE" "$LOG_FILE.old"
fi

exit 0

Environment Setup Hook

Purpose: Prepare workspace

#!/bin/bash
# hooks/SessionStart.sh

# Load environment variables
if [ -f ".env" ]; then
  export $(cat .env | xargs)
fi

# Start required services
if command -v docker-compose >/dev/null 2>&1; then
  if [ -f "docker-compose.yml" ]; then
    echo "🐳 Starting Docker services..." >&2
    docker-compose up -d
  fi
fi

# Initialize git hooks
if [ -d ".git" ] && [ ! -f ".git/hooks/pre-commit" ]; then
  echo "⚙️  Setting up git hooks..." >&2
  # Install git hooks
fi

exit 0

Workflow Enforcement Hook

Purpose: Ensure process compliance

#!/bin/bash
# hooks/PreToolUse.sh

# Check if in workflow mode
WORKFLOW_STATE="$HOME/.claude/workflow-state.json"

if [ -f "$WORKFLOW_STATE" ]; then
  CURRENT_PHASE=$(jq -r '.phase' "$WORKFLOW_STATE")

  # If in SPEC phase, block implementation
  if [[ "$CURRENT_PHASE" == "spec" ]]; then
    if [[ "$TOOL_NAME" == "Edit" ]] || [[ "$TOOL_NAME" == "Write" ]]; then
      FILE_PATH=$(echo "$TOOL_ARGS" | jq -r '.file_path')

      # Block implementation code during spec phase
      if [[ "$FILE_PATH" == *"/src/"* ]] && [[ "$FILE_PATH" != *".spec."* ]]; then
        echo "⛔ Workflow Violation" >&2
        echo "Currently in SPEC phase" >&2
        echo "Complete specification before implementation" >&2
        exit 1
      fi
    fi
  fi
fi

exit 0

Advanced Techniques

Conditional Hooks

#!/bin/bash
# hooks/PreToolUse.sh

# Only enforce in CI environment
if [ -z "$CI" ]; then
  # Not in CI, allow everything
  exit 0
fi

# In CI, enforce strict rules
if [[ "$TOOL_NAME" == "Bash" ]]; then
  COMMAND=$(echo "$TOOL_ARGS" | jq -r '.command')

  # Block interactive commands in CI
  if [[ "$COMMAND" == *"vim"* ]] || [[ "$COMMAND" == *"nano"* ]]; then
    echo "⛔ Interactive editors not allowed in CI" >&2
    exit 1
  fi
fi

exit 0

State Management

#!/bin/bash
# hooks/PreToolUse.sh

STATE_FILE="$HOME/.claude/plugin-state.json"

# Initialize state if not exists
if [ ! -f "$STATE_FILE" ]; then
  echo '{"commits": 0, "tests_run": 0}' > "$STATE_FILE"
fi

# Update state based on tool usage
if [[ "$TOOL_NAME" == "Bash" ]]; then
  COMMAND=$(echo "$TOOL_ARGS" | jq -r '.command')

  if [[ "$COMMAND" == *"git commit"* ]]; then
    # Increment commit counter
    COMMITS=$(jq -r '.commits' "$STATE_FILE")
    COMMITS=$((COMMITS + 1))
    jq ".commits = $COMMITS" "$STATE_FILE" > "$STATE_FILE.tmp"
    mv "$STATE_FILE.tmp" "$STATE_FILE"
  fi
fi

exit 0

Integration with External Tools

#!/bin/bash
# hooks/PostToolUse.sh

# Send to external monitoring system
if [ -n "$MONITORING_WEBHOOK" ]; then
  curl -X POST "$MONITORING_WEBHOOK" \
    -H "Content-Type: application/json" \
    -d "{
      \"tool\": \"$TOOL_NAME\",
      \"timestamp\": \"$(date -u +"%Y-%m-%dT%H:%M:%SZ")\",
      \"status\": \"$EXIT_CODE\"
    }" \
    >/dev/null 2>&1
fi

exit 0

Testing Hooks

Manual Testing

# Test PreToolUse hook
TOOL_NAME="Bash" TOOL_ARGS='{"command":"echo test"}' ./hooks/PreToolUse.sh
echo "Exit code: $?"

# Test with blocked command
TOOL_NAME="Bash" TOOL_ARGS='{"command":"rm -rf /"}' ./hooks/PreToolUse.sh
echo "Exit code: $?"

Test Checklist

  • Hook is executable (chmod +x)
  • Exit code 0 allows action
  • Exit code 1 blocks action
  • Error messages go to stderr
  • Handles missing environment vars gracefully
  • No infinite loops or hangs
  • Fast execution (< 100ms if possible)
  • Idempotent (can run multiple times safely)

Best Practices

Fast Execution

Good:

#!/bin/bash
# Quick check, minimal processing

if [[ "$TOOL_NAME" == "Bash" ]]; then
  # Simple string match
  if [[ "$COMMAND" == *"rm -rf"* ]]; then
    echo "⛔ Blocked" >&2
    exit 1
  fi
fi

exit 0

Bad:

#!/bin/bash
# Slow: Complex processing

# Don't do heavy computation in hooks
RESULT=$(find / -name "*.js" | xargs grep "pattern" | wc -l)
# This will block every tool call!

Error Handling

#!/bin/bash
# hooks/PreToolUse.sh

set -euo pipefail  # Exit on error

# Check required commands exist
if ! command -v jq >/dev/null 2>&1; then
  # Graceful degradation
  exit 0
fi

# Your hook logic
# ...

exit 0

Clear Messages

Good:

echo "⛔ Force push to main blocked" >&2
echo "" >&2
echo "Force push is dangerous and can destroy history." >&2
echo "" >&2
echo "To update main:" >&2
echo "  1. Create feature branch" >&2
echo "  2. Open pull request" >&2
echo "  3. Merge after review" >&2

Bad:

echo "Error: operation not allowed" >&2

Configuration

#!/bin/bash
# hooks/PreToolUse.sh

# Allow configuration
CONFIG_FILE=".claude/hook-config.json"

if [ -f "$CONFIG_FILE" ]; then
  STRICT_MODE=$(jq -r '.strict_mode' "$CONFIG_FILE")
else
  STRICT_MODE="false"
fi

# Use configuration
if [[ "$STRICT_MODE" == "true" ]]; then
  # Enforce strict rules
else
  # Relaxed mode
fi

Common Pitfalls

Blocking Everything

Problem:

# This blocks ALL tool usage!
exit 1

Fix:

# Only block specific dangerous operations
if [[ dangerous_condition ]]; then
  exit 1
fi

# Allow everything else
exit 0

Slow Hooks

Problem:

# This makes every tool call slow
sleep 5

Fix:

# Keep hooks fast
# Run heavy operations in background if needed
(heavy_operation &)
exit 0

Not Executable

Problem:

# Hook file created but not executable
# Won't run at all

Fix:

chmod +x hooks/PreToolUse.sh

Infinite Recursion

Problem:

# Hook triggers itself
if [[ "$TOOL_NAME" == "Bash" ]]; then
  # This triggers PreToolUse again!
  bash -c "echo test"
fi

Fix:

# Don't call tools from hooks
# Only validate and return

Debugging Hooks

Add Logging

#!/bin/bash
# hooks/PreToolUse.sh

DEBUG_LOG="$HOME/.claude/hook-debug.log"

if [ "$HOOK_DEBUG" = "true" ]; then
  echo "$(date) | PreToolUse | $TOOL_NAME | $TOOL_ARGS" >> "$DEBUG_LOG"
fi

# Your hook logic

Test in Isolation

# Set environment variables manually
export TOOL_NAME="Bash"
export TOOL_ARGS='{"command":"rm -rf test"}'

# Run hook
./hooks/PreToolUse.sh

# Check exit code
echo "Exit code: $?"

References

Plugin Development Skill

Comprehensive guide to creating Claude Code plugins following official specifications.

When to Use

Activate when:

  • User wants to create a new plugin
  • Discussing plugin architecture
  • Questions about plugin structure
  • Planning plugin features

Official Resources

Always reference:

Plugin Architecture

Directory Structure

my-plugin/
├── .claude-plugin/
│   └── plugin.json          # Plugin manifest (REQUIRED)
├── commands/                 # Slash commands
│   ├── start.md
│   └── validate.md
├── skills/                   # Guidance and workflows
│   ├── my-skill/
│   │   └── SKILL.md         # Skills are FOLDERS with SKILL.md
│   └── another-skill/
│       └── SKILL.md
├── agents/                   # Autonomous agents
│   ├── analyzer.md
│   └── validator.md
├── hooks/                    # Event handlers
│   ├── PreToolUse.sh
│   └── SessionStart.sh
└── README.md                 # Documentation (REQUIRED)

plugin.json Format

Minimal format (recommended - uses auto-discovery):

{
  "name": "my-plugin",
  "version": "1.0.0",
  "description": "What this plugin does",
  "author": {
    "name": "Your Name"
  }
}

With optional fields:

{
  "name": "plugin-name",
  "version": "1.0.0",
  "description": "Clear description of plugin purpose",
  "author": {
    "name": "Your Name"
  },
  "keywords": ["workflow", "development", "tools"],
  "repository": {
    "type": "git",
    "url": "https://github.com/user/repo"
  },
  "license": "MIT",
  "dependencies": ["other-plugin"]
}

Important: Commands, skills, agents, and hooks are auto-discovered from their directories. Do NOT list them manually in plugin.json.

Component Types

Skills vs Commands

Both create slash commands, but skills are preferred for new development:

FeatureCommands (commands/name.md)Skills (skills/name/SKILL.md)
StructureFlat .md fileFolder with SKILL.md
Invocation/plugin:command-name/plugin:skill-name
SupportingSingle file onlyMultiple files in folder
FeaturesBasic frontmatteruser-invocable, disable-model-invocation
StatusWorks, backward compatiblePreferred, more features
Auto-discoverFrom commands/ directoryFrom skills/ directory

Recommendation: Use skills for new plugins. Commands still work if you prefer flat files.

Skills (Preferred)

Purpose: Provide guidance, enforce workflows, share knowledge

When to use:

  • Teaching concepts
  • Enforcing methodologies (TDD, API-first)
  • Multi-step workflows
  • Best practices

Structure:

skills/
└── skill-name/              # MUST be a folder
    └── SKILL.md             # MUST be named SKILL.md

SKILL.md format:

---
name: skill-name
description: What this skill teaches or enforces
---

# Skill Name

## When to Use
Activate when: [triggering conditions]

## Process
[Step-by-step workflow]

## Examples
[Concrete examples]

Best practices:

  • Use progressive disclosure (simple → detailed)
  • Include concrete examples
  • Clear triggering conditions
  • Actionable guidance, not just theory

Agents

Purpose: Autonomous specialized workers

When to use:

  • Focused analysis tasks
  • Background processing
  • Specialized expertise domains
  • Repetitive workflows

Structure:

---
name: agent-name
description: Agent's specialized purpose
color: blue|green|orange|cyan|purple
tools: [Read, Grep, Glob, Bash, Edit, Write]
---

# Agent Name

## Your Role
[Clear role definition]

## Process
[How agent works]

## Output Format
[Expected output structure]

Tool selection:

  • Read-only agents: [Read, Grep, Glob]
  • Analysis agents: [Read, Grep, Glob, Bash]
  • Implementation agents: [Read, Grep, Glob, Bash, Edit, Write]

Hooks

Purpose: React to events automatically

When to use:

  • Validation before actions
  • Automatic logging
  • Workflow enforcement
  • Integration points

Available hooks:

  • PreToolUse - Before any tool execution
  • PostToolUse - After tool execution
  • SessionStart - Session initialization
  • SessionEnd - Session cleanup
  • Stop - Before session ends
  • SubagentStop - Agent completion
  • UserPromptSubmit - After user input
  • PreCompact - Before context compression
  • Notification - System notifications

Structure:

#!/bin/bash
# hooks/PreToolUse.sh

# Exit 0: allow action
# Exit 1: block action
# Echo to stderr: show message to user

Design Principles

Single Responsibility

Each plugin should have ONE clear purpose:

  • ✓ task-management - Task tracking only
  • ✓ tdd-workflow - TDD enforcement only
  • ✗ super-tool - Does everything

Component Selection

Commands/Skills (user-invocable workflows):

  • User explicitly invokes with /plugin:name
  • Interactive prompts and questions
  • Multi-step guided processes
  • Workflow orchestration
  • Choose skills over commands for new development (more features)

Agents (autonomous specialized workers):

  • Background processing
  • Specialized domain expertise (security, performance)
  • Parallel execution tasks
  • Focused analysis

Hooks (event-driven automation):

  • Automatic validation before actions
  • Logging and auditing
  • Cross-cutting concerns
  • Safety checks and guardrails

Composition Over Monoliths

Good: Small focused plugins

workflow/          → Workflow routing
tdd-workflow/      → TDD enforcement
sdd-workflow/      → Spec-first enforcement
task-management/   → Task tracking

Bad: One giant plugin

super-workflow/    → Does everything (harder to maintain, test, reuse)

Development Workflow

1. Design Phase

Clarify purpose:

  • What problem does this solve?
  • Who is the target user?
  • What's the core workflow?

Choose components:

  • Commands for user actions
  • Skills for guidance
  • Agents for automation
  • Hooks for events

2. Implementation Phase

Start with plugin.json:

{
  "name": "my-plugin",
  "version": "0.1.0",
  "description": "Clear purpose",
  "commands": [],
  "skills": [],
  "agents": []
}

Build incrementally:

  1. Create basic structure
  2. Implement one component fully
  3. Test it works
  4. Add next component
  5. Repeat

3. Documentation Phase

README.md must include:

  • What the plugin does
  • When to use it
  • Installation instructions
  • Usage examples
  • Component descriptions

4. Validation Phase

Check:

  • plugin.json valid and complete
  • All referenced components exist
  • Skills are folders with SKILL.md
  • Commands have frontmatter
  • Agents have valid tools/colors
  • README has examples
  • Source attribution if applicable

Common Patterns

Workflow Plugin Pattern

Coordinates multi-step processes:

  • Skill: Workflow routing logic
  • Commands: Start, status, complete
  • Agent: Specialized validation

Example: workflow plugin

Methodology Enforcement Pattern

Ensures best practices:

  • Skill: Methodology guide (TDD, API-first)
  • Commands: Initialize workflow
  • Hooks: Block violations

Example: tdd-workflow plugin

Tool Integration Pattern

Wraps external tools:

  • Commands: Tool operations
  • Agent: Tool-specific tasks
  • Hooks: Environment setup

Example: Database management plugin

Meta Plugin Pattern

Helps create other plugins:

  • Commands: Scaffolding operations
  • Skills: Development guides
  • Agent: Structure validation

Example: plugin-creator plugin

Dependencies

When to use dependencies

{
  "dependencies": ["task-management"]
}

Use when:

  • Your plugin extends another
  • You integrate with specific tools
  • You require specific functionality

Avoid when:

  • Optional integration
  • Can work standalone
  • Just following similar patterns

Optional Integration Pattern

Instead of hard dependency:

// Check if task-management exists
if (hasPlugin('task-management')) {
  // Use it
} else {
  // Graceful degradation
}

Testing

Manual Testing Checklist

  • Commands execute without errors
  • Skills load and display correctly
  • Agents complete tasks successfully
  • Hooks trigger at right events
  • Documentation is clear
  • Examples work as shown

Validation Testing

/plugin validate path/to/plugin

Distribution

Marketplace Preparation

  1. Validate plugin structure
  2. Complete README
  3. Add source attribution
  4. Specify version
  5. Add tags for discovery

Installation Methods

  • Marketplace install
  • Manual copy to ~/.claude/plugins/
  • Symlink for development

Examples

Minimal Plugin

hello-world/
├── .claude-plugin/
│   └── plugin.json
├── commands/
│   └── greet.md
└── README.md

Complete Plugin

workflow/
├── .claude-plugin/
│   └── plugin.json
├── commands/
│   ├── start.md
│   ├── spec.md
│   ├── plan.md
│   └── status.md
├── skills/
│   ├── workflow-router/
│   │   └── SKILL.md
│   ├── block-a-spec-validation/
│   │   └── SKILL.md
│   └── meta-testing/
│       └── SKILL.md
├── agents/
│   └── meta-validator.md
└── README.md

Troubleshooting

"Skill not found"

  • Skills must be FOLDERS with SKILL.md
  • Not flat .md files in skills/

"Command prefix duplicated"

  • Commands auto-get plugin prefix
  • Name: start.md, not plugin:start.md

"Agent not loading"

  • Check YAML frontmatter valid
  • Verify tools list correct
  • Color must be valid value

References

Skill Development Skill

Guide to creating powerful, reusable skills for Claude Code.

When to Use

Activate when:

  • Creating new skills
  • Improving existing skills
  • Skill not triggering properly
  • Unclear skill structure

What Are Skills?

Skills are reusable knowledge modules that:

  • Teach concepts and methodologies
  • Enforce workflows and best practices
  • Provide context-sensitive guidance
  • Act as "muscle memory" for Claude

Not just documentation - Skills are active guidance that Claude follows.

Skill Structure

Directory Layout

CRITICAL: Skills are FOLDERS, not flat files:

skills/
└── my-skill/              # Folder named after skill
    └── SKILL.md           # Must be named SKILL.md

Common mistake:

skills/
└── my-skill.md            # ❌ WRONG - flat file won't work

SKILL.md Format

---
name: skill-name
description: Clear, concise description of what skill does
---

# Skill Title

## When to Use

Activate when:
- [Specific triggering condition 1]
- [Specific triggering condition 2]
- User mentions "[keyword]"
- [Context-specific scenario]

## [Main Content Sections]

[Progressive disclosure structure]

## Examples

[Concrete, actionable examples]

Designing Effective Skills

1. Clear Triggering Conditions

Purpose: Tell Claude WHEN to use this skill

Good triggering conditions:

## When to Use

Activate when:
- User wants to implement API endpoint
- User mentions "REST", "GraphQL", or "API"
- OpenAPI/AsyncAPI files detected in project
- Before implementing any API code

Bad triggering conditions:

## When to Use

Use this skill for API development.  # ❌ Too vague

Patterns:

  • User intent: "User wants to..."
  • Keywords: "User mentions 'X', 'Y', or 'Z'"
  • File detection: "package.json detected"
  • Workflow stage: "Before writing tests"
  • Context: "When debugging performance issues"

2. Progressive Disclosure

Start simple, add detail progressively:

# Quick Start (TL;DR)
[30 second overview]

# The Process
[High-level steps]

# Step 1: [First Step]
[Detailed guidance]

# Step 2: [Second Step]
[Detailed guidance]

# Advanced Topics
[Deep dives, edge cases]

# Reference
[Links, tables, technical details]

Why: User reads what they need, when they need it.

3. Concrete Examples

Show, don't just tell:

## Example: Creating REST API Spec

**BAD** (vague):
```yaml
paths:
  /users:
    get:
      # Define your endpoint here

GOOD (concrete):

paths:
  /users:
    get:
      summary: List all users
      parameters:
        - name: limit
          in: query
          schema:
            type: integer
            default: 20
      responses:
        '200':
          description: Success
          content:
            application/json:
              schema:
                type: array
                items:
                  $ref: '#/components/schemas/User'

### 4. Actionable Guidance

**Tell Claude what to DO, not just what to know**:

**Good** (actionable):
```markdown
## Process

1. Search for all test files:
   - Use Glob: `**/*.test.{js,ts}`
   - Read each test file

2. Analyze test coverage:
   - Count tested functions vs total functions
   - Identify untested code paths

3. Generate report:
   - List missing tests
   - Prioritize by criticality
   - Suggest test cases

Bad (informational):

## Process

Test coverage is important. You should check that your code
has adequate test coverage and identify gaps.

5. Enforcement vs Guidance

Enforcement Skills (Rigid):

## TDD Workflow

**MUST follow this order**:

1. RED: Write failing test FIRST
2. GREEN: Write minimum code to pass
3. REFACTOR: Improve code

**If user tries to write code before tests:**

⛔ TDD Violation

You must write the test FIRST.

Run: /tdd:start "feature description"

Guidance Skills (Flexible):

## Brainstorming Workflow

**Suggested approach**:

1. Understand the problem
2. Generate ideas
3. Evaluate options
4. Refine solution

**Adapt this process** to your needs.

Skill Types

Workflow Skills

Purpose: Multi-step processes

Example: spec-driven-development

## Process

### 1. Spec First
- Define API contract in OpenAPI/AsyncAPI
- Document all endpoints
- Specify schemas

### 2. Validate Spec
- Run spec linter
- Check completeness

### 3. Generate from Spec
- Server stubs
- Client SDK
- Tests

### 4. Implement
- Fill in business logic
- Keep implementation matching spec

Methodology Skills

Purpose: Enforce best practices

Example: test-driven-development

## RED-GREEN-REFACTOR Cycle

### RED Phase
**Write failing test FIRST**
- No implementation yet
- Test should fail

### GREEN Phase
**Minimum code to pass**
- No premature optimization
- Just make it work

### REFACTOR Phase
**Improve while tests pass**
- Clean up code
- Tests stay green

Routing Skills

Purpose: Decision-making and delegation

Example: workflow-router

## Complexity Detection

### Simple (Block C)
- <8 steps
- Single file changes
- Bug fixes
→ Route to: Simple Planning

### Medium (Block B)
- 8-15 steps
- Existing spec
- Feature implementation
→ Route to: Spec + TDD

### Complex (Block A)
- >15 steps
- New architecture
- Security critical
→ Route to: Spec + Meta-Validation

Domain Knowledge Skills

Purpose: Specialized expertise

Example: frontend-design-system

## Component Patterns

### Atomic Design
- Atoms: Button, Input, Label
- Molecules: FormField, SearchBar
- Organisms: Header, ProductCard
- Templates: PageLayout
- Pages: HomePage, ProductPage

### Implementation
[Detailed guidance for each level]

Advanced Techniques

Multi-Mode Skills

Support different user contexts:

## Modes

### Mode 1: Quick Start
For users who want to get started fast.
[Minimal steps]

### Mode 2: Comprehensive
For users who want full control.
[Detailed workflow]

### Mode 3: Expert
For advanced users.
[Advanced options]

**Auto-detect mode** based on user request:
- "quickly add X" → Quick Start
- "properly implement X" → Comprehensive
- "optimize X" → Expert

Conditional Workflows

Adapt based on context:

## Process

### 1. Detect Project Type

**If package.json exists:**
→ Node.js project
→ Use npm/yarn commands
→ Check for test framework

**If requirements.txt exists:**
→ Python project
→ Use pip commands
→ Check for pytest/unittest

**If pom.xml exists:**
→ Java project
→ Use maven commands
→ Check for JUnit

### 2. Adapt Workflow
[Language-specific guidance]

Integration Patterns

Work with other plugins:

## Integration

### With task-management
**If task-management plugin available:**

/task:create "Implement feature X"

Track progress with task statuses.

**If not available:**
Use inline checklist:
- [ ] Step 1
- [ ] Step 2

### With workflow plugin
**If in workflow session:**
Follow workflow blocks (A/B/C).

**If standalone:**
Use independent process.

Testing Skills

Manual Testing

  1. Create test scenario:

    User says: "I want to implement a REST API for users"
    Expected: Skill should trigger and guide spec-first development
    
  2. Test triggering:

    • Does skill activate when it should?
    • Does it stay dormant when it shouldn't?
  3. Test guidance:

    • Is the process clear?
    • Can Claude follow it successfully?
    • Does it handle edge cases?
  4. Test examples:

    • Are examples concrete enough?
    • Do they work as shown?

Refinement Cycle

  1. Write initial skill
  2. Test with real scenarios
  3. Identify confusion points
  4. Add examples/clarification
  5. Retest
  6. Repeat

Common Pitfalls

Too Vague

Problem:

## When to Use
Use this for API development.

Fix:

## When to Use

Activate when:
- User says "create API" or "add endpoint"
- User mentions "REST", "GraphQL", "OpenAPI"
- Before implementing any API code
- OpenAPI files detected in project

Too Much Information Upfront

Problem:

# API Development

[3000 words of theory and edge cases]

## Getting Started
[Finally, the process]

Fix:

# API Development

## Quick Start
1. Define spec
2. Validate spec
3. Implement

[Detailed sections below]

## 1. Define Spec
[Details]

Missing Examples

Problem:

## Process
1. Create the specification
2. Validate it
3. Generate code

Fix:

## Process

### 1. Create Specification

**Example - User API**:
```yaml
openapi: 3.0.0
info:
  title: User API
paths:
  /users:
    get:
      summary: List users
      responses:
        '200':
          description: Success

[Continue with concrete examples]


### Informational Not Actionable

**Problem**:
```markdown
Testing is important for code quality. Good tests catch bugs early.

Fix:

## Writing Tests

1. **Identify what to test**:
   - Use Glob to find source files: `src/**/*.{js,ts}`
   - List all public functions

2. **For each function**:
   - Write test for happy path
   - Write test for error cases
   - Write test for edge cases

3. **Run tests**:
   ```bash
   npm test

## Skill Templates

### Basic Skill Template

```markdown
---
name: skill-name
description: Clear description in one sentence
---

# Skill Name

Expanded description of what this skill does and why it's useful.

## When to Use

Activate when:
- [Specific condition 1]
- [Specific condition 2]
- User mentions "[keyword]"

## Quick Start

[30-second overview]

## Process

### Step 1: [First Step]
[What to do]

**Example**:
[Concrete example]

### Step 2: [Second Step]
[What to do]

**Example**:
[Concrete example]

## Advanced

[Deep dive topics]

## Troubleshooting

**Problem**: [Common issue]
**Solution**: [How to fix]

## References

- [Relevant links]

Workflow Enforcement Template

---
name: workflow-name
description: Enforces [methodology] workflow
---

# [Methodology] Workflow

## When to Use

Activate when:
- User wants to implement [feature type]
- Before writing [code type]
- [Methodology] detected in project

## Required Process

**MUST follow this order**:

### Phase 1: [First Phase]
**Requirements**:
- [Requirement 1]
- [Requirement 2]

**Example**:
[Show what this looks like]

**If user skips this**:

⛔ [Methodology] Violation [Explanation why this is required] [How to fix]


### Phase 2: [Second Phase]
[Continue pattern]

## Enforcement

**Block these actions**:
- Writing implementation before [phase 1]
- Skipping [required step]

**Allow these actions**:
- [Safe actions during workflow]

References

Plugin Validation Skill

Validates complete plugin structure using schema-based validation.

When to Use

  • User invokes /plugin-creator:validate-plugin-structure
  • User asks "validate my plugin"
  • After creating or modifying plugin
  • Before publishing plugin

Validation Process

1. Locate Plugin

# If in plugin directory
/plugin-creator:validate-plugin-structure

# Or specify path
/plugin-creator:validate-plugin-structure /path/to/my-plugin

2. Load Validation Schemas

Read schemas from skills/validation/schema/:

  • plugin-frontmatter.md - plugin.json validation
  • skill-frontmatter.md - SKILL.md frontmatter validation
  • agent-frontmatter.md - Agent frontmatter validation
  • directory-structure.md - Directory layout validation
  • hook-structure.md - Hook file validation

3. Run Validation Checks

Invoke custom-plugin-validator agent with schemas:

Validator checks against schemas:
1. Plugin structure (directory-structure.md)
2. plugin.json format (plugin-frontmatter.md)
3. All skills (skill-frontmatter.md)
4. All agents (agent-frontmatter.md)
5. All hooks (hook-structure.md)

4. Report Results

Validating: my-awesome-plugin/

Plugin Structure
================
✓ .claude-plugin/ exists
✓ plugin.json exists
✓ README.md exists

plugin.json
===========
✓ Valid JSON
✓ Required fields: name, version, description, author
✓ keywords: array of strings
⚠ Repository URL missing (recommended)

Skills (3 found)
================
✓ skills/create/ - Valid
✓ skills/analyze/ - Valid
⚠ skills/format/ - Missing examples section

Agents (2 found)
================
✓ agents/custom-analyzer.md - Valid
✗ agents/validator.md - Missing 'custom-' prefix

Hooks (1 found)
===============
✓ hooks/PreToolUse.sh - Valid, executable

Summary
=======
✓ 15 passed
⚠ 2 warnings
✗ 1 error

Fix errors before publishing!

Schema Files

All schemas are in skills/validation/schema/:

plugin-frontmatter.md

Defines valid plugin.json structure

skill-frontmatter.md

Defines valid SKILL.md frontmatter

agent-frontmatter.md

Defines valid agent frontmatter

directory-structure.md

Defines expected plugin layout

hook-structure.md

Defines hook file requirements

Validation Levels

✓ PASS - Ready to publish ⚠ WARNING - Works but has recommendations ✗ ERROR - Critical issues, fix before use

Integration

Works with:

  • custom-plugin-validator agent (uses schemas)
  • Workflow plugin (validation in Stage C)
  • CI/CD pipelines (automated validation)

Agents 2

Plugin Architect Agent

Specialized agent for designing Claude Code plugin architecture.

Your Role

Design optimal plugin structure by:

  1. Understanding plugin requirements
  2. Choosing appropriate components
  3. Planning component interactions
  4. Ensuring best practices
  5. Documenting architecture decisions

Process

1. Analyze Requirements

Gather information:

  • What problem does this plugin solve?
  • Who are the target users?
  • What are the main use cases?
  • Are there similar existing plugins?

Use Glob and Grep:

# Check for existing similar plugins
Glob: "plugins/**/plugin.json"
Read: Each plugin.json to understand existing solutions

# Check for related functionality
Grep: Pattern matching for similar features

2. Component Selection

Decision matrix:

NeedComponentRationale
User invokes actionCommandInteractive, explicit control
Teach methodologySkillWorkflow guidance, best practices
Autonomous analysisAgentBackground work, specialized expertise
Event automationHookTrigger-based, validation

Questions to ask:

Commands needed?

  • Does user need to explicitly trigger actions?
  • Is interactive input required?
  • Are there discrete operations? → Yes: Add commands

Skills needed?

  • Is there a methodology to teach?
  • Are there multi-step workflows?
  • Should process be enforced? → Yes: Add skills

Agents needed?

  • Is specialized analysis needed?
  • Can work happen autonomously?
  • Is there domain expertise required? → Yes: Add agents

Hooks needed?

  • Should actions be validated automatically?
  • Is event-driven automation needed?
  • Are safety checks required? → Yes: Add hooks

3. Design Architecture

For simple plugins (<3 components):

plugin-name/
├── .claude-plugin/
│   └── plugin.json
├── commands/
│   └── main-command.md
├── skills/
│   └── main-skill/
│       └── SKILL.md
└── README.md

For medium plugins (3-6 components):

plugin-name/
├── .claude-plugin/
│   └── plugin.json
├── commands/
│   ├── start.md
│   ├── status.md
│   └── complete.md
├── skills/
│   ├── workflow/
│   │   └── SKILL.md
│   └── integration/
│       └── SKILL.md
├── agents/
│   └── analyzer.md
└── README.md

For complex plugins (6+ components):

plugin-name/
├── .claude-plugin/
│   └── plugin.json
├── commands/
│   ├── start.md
│   ├── spec.md
│   ├── plan.md
│   └── status.md
├── skills/
│   ├── router/
│   │   └── SKILL.md
│   ├── block-a/
│   │   └── SKILL.md
│   ├── block-b/
│   │   └── SKILL.md
│   └── integration/
│       └── SKILL.md
├── agents/
│   ├── validator.md
│   └── analyzer.md
├── hooks/
│   ├── PreToolUse.sh
│   └── SessionStart.sh
└── README.md

4. Component Interactions

Design flow:

Example: TDD Workflow Plugin

User: /tdd:start "feature"
  ↓
Command: tdd/commands/start.md
  ↓
Invokes Skill: test-driven-development
  ↓
Skill enforces: RED → GREEN → REFACTOR
  ↓
Hook validates: PreToolUse.sh
  ├─ Block implementation before test
  └─ Allow test creation

Example: Code Review Plugin

User: /review:start
  ↓
Command: review/commands/start.md
  ↓
Launches Agents:
  ├─ security-reviewer.md
  ├─ performance-reviewer.md
  └─ style-reviewer.md
  ↓
Agents analyze code
  ↓
Command aggregates results
  ↓
Generate comprehensive report

5. Dependency Analysis

Check if plugin should depend on others:

# Search for existing plugins that could be integrated
Glob: "plugins/**/plugin.json"

# Analyze for common patterns
Read: Related plugin.json files

Dependency decision:

  • ✓ Hard dependency: Plugin cannot work without it
  • ✓ Optional integration: Enhances but not required
  • ✗ Avoid: Can work standalone

Examples:

Hard dependency (rare):

{
  "name": "task-advanced",
  "dependencies": ["task-management"]
}

Optional integration (preferred):

## Integration

### With task-management
If task-management plugin available, integrate task tracking.
If not available, use inline progress tracking.

6. Naming Conventions

Plugin names:

  • Lowercase
  • Hyphens for spaces
  • Descriptive but concise
  • Examples: workflow, tdd-workflow, code-review

Command names:

  • Lowercase
  • Simple verbs or actions
  • No plugin prefix (auto-added)
  • Examples: start, validate, create

Skill names:

  • Lowercase
  • Hyphens for spaces
  • Descriptive of workflow
  • Examples: workflow-router, test-driven-development

Agent names:

  • Lowercase
  • Role-based naming
  • Indicates specialization
  • Examples: security-reviewer, meta-validator

Architecture Patterns

Pattern 1: Single-Purpose Plugin

Characteristics:

  • One clear focused goal
  • Minimal components
  • Easy to understand

Example: Task Management

task-management/
├── plugin.json
├── commands/
│   └── task.md        # All task operations
├── skills/
│   └── task-tracking/
│       └── SKILL.md   # Workflow guidance
└── README.md

Pattern 2: Methodology Enforcement

Characteristics:

  • Enforces best practices
  • Uses skills + hooks
  • Validates actions

Example: TDD Workflow

tdd-workflow/
├── plugin.json
├── commands/
│   └── start.md
├── skills/
│   └── test-driven-development/
│       └── SKILL.md
├── hooks/
│   └── PreToolUse.sh  # Block code before tests
└── README.md

Pattern 3: Analysis and Review

Characteristics:

  • Multiple specialized agents
  • Aggregated reporting
  • Autonomous analysis

Example: Code Review

code-review/
├── plugin.json
├── commands/
│   └── review.md
├── agents/
│   ├── security-reviewer.md
│   ├── performance-reviewer.md
│   └── style-reviewer.md
└── README.md

Pattern 4: Workflow Orchestration

Characteristics:

  • Complexity routing
  • Multiple workflows
  • Integration hub

Example: Workflow Plugin

workflow/
├── plugin.json
├── commands/
│   ├── start.md
│   ├── spec.md
│   ├── plan.md
│   └── status.md
├── skills/
│   ├── workflow-router/
│   ├── block-a-spec-validation/
│   ├── block-b-spec-to-tdd/
│   └── block-c-simple-planning/
├── agents/
│   └── meta-validator.md
└── README.md

Pattern 5: Meta Plugin

Characteristics:

  • Creates/manages other plugins
  • Self-referential
  • Comprehensive guides

Example: Plugin Creator

plugin-creator/
├── plugin.json
├── commands/
│   └── plugin.md
├── skills/
│   ├── plugin-development/
│   ├── skill-development/
│   ├── command-development/
│   ├── agent-development/
│   └── hook-development/
├── agents/
│   ├── plugin-architect.md     # This agent!
│   └── plugin-validator.md
└── README.md

Design Decisions

Monolithic vs Modular

Monolithic (one big plugin):

  • ✓ Pros: Single install, integrated
  • ✗ Cons: Hard to maintain, all-or-nothing

Modular (multiple focused plugins):

  • ✓ Pros: Focused, composable, maintainable
  • ✗ Cons: Multiple installs, coordination

Recommendation: Prefer modular unless tight integration required

Example - Modular approach:

workflow/          → Main orchestration
tdd-workflow/      → TDD methodology
sdd-workflow/      → Spec-first methodology
task-management/   → Task tracking (standalone)

Skill vs Command

Use Skill when:

  • Teaching a process
  • Enforcing methodology
  • Context-sensitive guidance
  • Want automatic triggering

Use Command when:

  • User explicit invocation
  • Interactive prompts
  • One-time operations
  • Configuration changes

Can use both:

Command: /tdd:start
  ↓
Invokes Skill: test-driven-development
  ↓
Skill provides ongoing guidance

Agent vs Command

Use Agent when:

  • Analysis can be autonomous
  • Specialized domain knowledge
  • Can work in background
  • Complex multi-step analysis

Use Command when:

  • User needs control
  • Interactive decisions
  • Quick operations
  • Simple workflows

Output Format

# Plugin Architecture Design

## Plugin: <name>

### Purpose
[Clear one-sentence purpose]

### Target Users
[Who will use this plugin]

### Use Cases
1. [Primary use case]
2. [Secondary use case]
3. [Tertiary use case]

## Architecture

### Components

#### Commands
- `start` - [Purpose]
- `status` - [Purpose]

**Rationale**: [Why these commands]

#### Skills
- `workflow-router/` - [Purpose]
- `main-workflow/` - [Purpose]

**Rationale**: [Why these skills]

#### Agents
- `analyzer` - [Purpose]

**Rationale**: [Why this agent]

#### Hooks
- `PreToolUse.sh` - [Purpose]

**Rationale**: [Why this hook]

### Component Interactions

User invokes /plugin:start ↓ Command routes to workflow-router skill ↓ Skill launches analyzer agent ↓ Agent analyzes and returns results ↓ Command presents results to user


## File Structure

plugin-name/ ├── .claude-plugin/ │ └── plugin.json ├── commands/ │ └── start.md ├── skills/ │ └── workflow-router/ │ └── SKILL.md ├── agents/ │ └── analyzer.md └── README.md


## Dependencies

- None (standalone)
- OR: Optional integration with [plugin-name]
- OR: Requires [plugin-name]

**Rationale**: [Why dependencies chosen]

## Design Trade-offs

### Decision 1: [Choice made]
**Options considered**:
- Option A: [Pros/Cons]
- Option B: [Pros/Cons]

**Chosen**: Option A

**Rationale**: [Why this choice]

### Decision 2: [Choice made]
[Same format]

## Implementation Phases

### Phase 1: Core Functionality
- [ ] Create plugin.json
- [ ] Implement primary command
- [ ] Create main skill
- [ ] Basic README

### Phase 2: Advanced Features
- [ ] Add specialized agents
- [ ] Implement validation hooks
- [ ] Add integration points

### Phase 3: Polish
- [ ] Comprehensive documentation
- [ ] Examples and templates
- [ ] Validation and testing

## Success Criteria

- [ ] Solves stated problem
- [ ] Easy to use
- [ ] Well documented
- [ ] Follows best practices
- [ ] Integrates with ecosystem

## Next Steps

1. Review architecture with user
2. Implement Phase 1
3. Test basic functionality
4. Iterate based on feedback

Best Practices Applied

Single Responsibility

Each component has ONE clear purpose.

Progressive Disclosure

Start simple, add complexity as needed.

Clear Naming

Names immediately convey purpose.

Documentation First

Architecture documented before implementation.

Composition Over Inheritance

Small focused plugins that work together.

Example Architectures

Example 1: Simple Tool Plugin

Requirements: Integrate with external API

Architecture:

api-integration/
├── plugin.json
├── commands/
│   └── api.md          # /api:call, /api:config
└── README.md

Rationale: Simple wrapper, just commands needed

Example 2: Workflow Enforcer

Requirements: Enforce API-first development

Architecture:

sdd-workflow/
├── plugin.json
├── commands/
│   └── create.md       # /sdd:create
├── skills/
│   └── spec-driven-development/
│       └── SKILL.md    # Methodology
└── README.md

Rationale: Skill for methodology, command to initiate

Example 3: Comprehensive Review

Requirements: Multi-faceted code review

Architecture:

code-review/
├── plugin.json
├── commands/
│   └── review.md
├── agents/
│   ├── security-reviewer.md
│   ├── performance-reviewer.md
│   ├── style-reviewer.md
│   └── test-coverage-reviewer.md
└── README.md

Rationale: Multiple specialized agents for parallel analysis

References

Plugin Validator Agent

Specialized agent for validating Claude Code plugins.

Your Role

Validate plugins for:

  1. Structural correctness
  2. Metadata completeness
  3. Component existence
  4. Best practices compliance
  5. Documentation quality

Process

1. Find Plugin

# If path provided, use it
# Otherwise, search current directory

Glob: ".claude-plugin/plugin.json"

2. Validate Structure

Check directory structure:

Required:
- .claude-plugin/plugin.json ✓
- README.md ✓

Referenced in plugin.json:
- commands/ (if commands listed)
- skills/ (if skills listed)
- agents/ (if agents listed)
- hooks/ (if hooks listed)

3. Validate plugin.json

Check JSON syntax:

Bash: jq . .claude-plugin/plugin.json
# Should parse without errors

Check required fields:

{
  "name": "required",
  "version": "required",
  "description": "required"
}

Check optional fields:

{
  "author": "recommended",
  "commands": "array or omit",
  "skills": "array or omit",
  "agents": "array or omit",
  "hooks": "array or omit",
  "dependencies": "array or omit",
  "tags": "array or omit"
}

Validate field formats:

  • name: lowercase, hyphens, no spaces
  • version: semver format (1.0.0)
  • commands: array of strings (no prefixes)
  • skills: array of strings
  • agents: array of strings
  • hooks: array of filenames
  • tags: array of category strings

4. Validate Commands

For each command in plugin.json:

# Check file exists
File should exist: commands/<command-name>.md

# Read file
Read: commands/<command-name>.md

# Validate YAML frontmatter
Required fields:
- name: <command-name>
- description: <text>

Optional fields:
- usage: <usage text>
- examples: <array>
- aliases: <array>

# Check for common issues
- Name matches filename ✓
- No plugin prefix in name ✓
- Description exists ✓
- Usage documentation present (recommended)
- Examples provided (recommended)

Common command issues:

  • ❌ name: plugin:start → Should be name: start
  • ❌ File: commands/start → Should be commands/start.md
  • ❌ No description
  • ⚠️ No usage examples

5. Validate Skills

Critical: Skills are FOLDERS with SKILL.md

# For each skill in plugin.json
For skill in skills:
  # Check folder exists
  Check: skills/<skill-name>/ is a directory

  # Check SKILL.md exists
  Check: skills/<skill-name>/SKILL.md exists

  # Read SKILL.md
  Read: skills/<skill-name>/SKILL.md

  # Validate frontmatter
  Required:
  - name: <skill-name>
  - description: <text>

Common skill issues:

  • ❌ skills/my-skill.md → Should be skills/my-skill/SKILL.md
  • ❌ skills/my-skill/my-skill.md → Must be named SKILL.md
  • ❌ No frontmatter
  • ⚠️ No "When to Use" section
  • ⚠️ No examples

Skill content quality:

  • "When to Use" section present
  • Clear triggering conditions
  • Actionable process steps
  • Concrete examples
  • Not just informational

6. Validate Agents

For each agent in plugin.json:

# Check file exists
File: agents/<agent-name>.md

# Read file
Read: agents/<agent-name>.md

# Validate frontmatter
Required:
- name: <agent-name>
- description: <text>
- color: blue|green|orange|cyan|purple
- tools: [array of valid tools]

Valid tools:
- Read, Grep, Glob, Bash, Edit, Write, Task

Common agent issues:

  • ❌ Invalid color value
  • ❌ Invalid tool name
  • ❌ Too many tools (agents should be focused)
  • ⚠️ No "Your Role" section
  • ⚠️ No "Output Format" example

Agent content quality:

  • Clear role definition
  • Specific process steps
  • Output format specified
  • Appropriate tool selection
  • Examples of analysis

7. Validate Hooks

For each hook in plugin.json:

# Check file exists
File: hooks/<hook-name>.sh

# Check executable
Bash: test -x hooks/<hook-name>.sh
# Must be executable

# Validate hook name
Valid names:
- PreToolUse.sh
- PostToolUse.sh
- SessionStart.sh
- SessionEnd.sh
- Stop.sh
- SubagentStop.sh
- UserPromptSubmit.sh
- PreCompact.sh
- Notification.sh

Common hook issues:

  • ❌ Not executable (chmod +x needed)
  • ❌ Invalid hook name
  • ❌ Missing shebang (#!/bin/bash)
  • ⚠️ No comments explaining purpose
  • ⚠️ Slow execution (>100ms)

8. Validate README

Check README.md exists:

File: README.md

Check completeness:

Required sections:
- [ ] Plugin title/name
- [ ] Description/Overview
- [ ] Installation or Usage

Recommended sections:
- [ ] Features list
- [ ] Commands documentation
- [ ] Examples
- [ ] Source attribution (if applicable)
- [ ] License (if public)

Content quality:

  • Clear purpose statement
  • Usage examples
  • Not just auto-generated template
  • Explains when to use plugin

9. Cross-Reference Validation

Verify all references:

# All commands in plugin.json have files
For command in plugin.json.commands:
  Check: commands/<command>.md exists

# All skills in plugin.json have folders
For skill in plugin.json.skills:
  Check: skills/<skill>/SKILL.md exists

# All agents in plugin.json have files
For agent in plugin.json.agents:
  Check: agents/<agent>.md exists

# All hooks in plugin.json have files
For hook in plugin.json.hooks:
  Check: hooks/<hook> exists and executable

# No orphaned files (files not in plugin.json)
Find all files in commands/, skills/, agents/, hooks/
Check each is referenced in plugin.json

10. Best Practices Check

Naming conventions:

  • Plugin name is lowercase with hyphens
  • Command names have no plugin prefix
  • Skill names are descriptive
  • Agent names indicate role

Component selection:

  • Commands for user actions
  • Skills for workflows
  • Agents for autonomous work
  • Appropriate tool selection

Documentation:

  • README has examples
  • Commands have usage docs
  • Skills have triggering conditions
  • Agents have output formats

Dependencies:

  • Minimal dependencies
  • Dependencies documented
  • Optional integrations noted

Validation Report Format

# Plugin Validation Report

**Plugin**: <name> v<version>
**Path**: <path-to-plugin>
**Date**: <validation-date>

---

## Overall Status: ✓ PASS | ⚠️ WARNINGS | ❌ FAIL

---

## Structure Validation

### Required Files
- ✓ .claude-plugin/plugin.json
- ✓ README.md

### Component Directories
- ✓ commands/ (3 commands)
- ✓ skills/ (2 skills)
- ✓ agents/ (1 agent)
- ⊗ hooks/ (not used)

---

## plugin.json Validation

### Syntax ✓
- Valid JSON
- Proper formatting

### Required Fields ✓
- ✓ name: "my-plugin"
- ✓ version: "1.0.0"
- ✓ description: "Plugin purpose"

### Optional Fields
- ✓ author: "Author Name"
- ✓ tags: ["workflow", "development"]
- ⊗ dependencies: (none)

### Issues
None

---

## Commands Validation (3 commands)

### ✓ start.md
- ✓ File exists
- ✓ Valid frontmatter
- ✓ name: "start" (correct, no prefix)
- ✓ Description present
- ✓ Usage examples
- ✓ Well documented

### ⚠️ validate.md
- ✓ File exists
- ✓ Valid frontmatter
- ✓ name: "validate"
- ⚠️ No usage examples (recommended)

### ❌ plugin:configure.md
- ❌ Incorrect filename (has plugin prefix)
- Should be: commands/configure.md
- Should have: name: "configure"

---

## Skills Validation (2 skills)

### ✓ workflow-router/
- ✓ Folder exists
- ✓ SKILL.md exists
- ✓ Valid frontmatter
- ✓ name: "workflow-router"
- ✓ Description present
- ✓ "When to Use" section
- ✓ Examples included

### ❌ my-skill.md
- ❌ WRONG: Flat file instead of folder
- Should be: skills/my-skill/SKILL.md
- Current: skills/my-skill.md

---

## Agents Validation (1 agent)

### ✓ validator.md
- ✓ File exists
- ✓ Valid frontmatter
- ✓ name: "validator"
- ✓ color: "green"
- ✓ tools: [Read, Grep, Glob, Bash]
- ✓ "Your Role" section
- ✓ "Output Format" specified

---

## Hooks Validation

No hooks used (optional)

---

## README Validation

### Structure ✓
- ✓ Title/name present
- ✓ Description
- ✓ Usage instructions
- ✓ Examples
- ⚠️ No source attribution

### Content Quality ✓
- ✓ Clear purpose
- ✓ Good examples
- ✓ Not just template

---

## Cross-Reference Check

### Referenced Files ⚠️
- ✓ All commands in plugin.json exist (except plugin:configure issue)
- ❌ Skill "my-skill" has wrong structure
- ✓ All agents exist

### Orphaned Files
- ⚠️ Found: docs/design.md (not referenced, okay for docs)

---

## Best Practices

### Naming ⚠️
- ✓ Plugin name follows convention
- ❌ Command has plugin prefix (plugin:configure)
- ✓ Skill names descriptive
- ✓ Agent name indicates role

### Component Design ✓
- ✓ Appropriate command usage
- ✓ Skills provide workflow guidance
- ✓ Agent has focused purpose
- ✓ Tools appropriate for agents

### Documentation ⚠️
- ✓ README comprehensive
- ⚠️ One command missing examples
- ✓ Skills well documented
- ✓ Agent well documented

---

## Issues Summary

### Critical (MUST FIX)
1. ❌ Skill "my-skill" must be folder with SKILL.md
   - Current: skills/my-skill.md
   - Fix: Create skills/my-skill/ and move to skills/my-skill/SKILL.md

2. ❌ Command file has plugin prefix
   - Current: commands/plugin:configure.md
   - Fix: Rename to commands/configure.md
   - Fix: Change frontmatter name to "configure"

### Warnings (SHOULD FIX)
1. ⚠️ Command "validate" missing usage examples
   - Add examples section

2. ⚠️ README missing source attribution
   - Add if based on other work

### Info (OPTIONAL)
- Orphaned file docs/design.md (okay)
- No hooks used (optional feature)

---

## Recommendations

### Priority 1 (Critical)
Fix skill structure and command naming before publication.

### Priority 2 (Quality)
1. Add usage examples to all commands
2. Add source attribution if applicable

### Priority 3 (Enhancement)
Consider adding:
- Pre-commit hook for validation
- More comprehensive examples
- Integration guide for other plugins

---

## Next Steps

1. Fix critical issues:
   ```bash
   # Fix skill structure
   mkdir -p skills/my-skill
   mv skills/my-skill.md skills/my-skill/SKILL.md

   # Fix command naming
   mv commands/plugin:configure.md commands/configure.md
   # Edit file to change name: "configure"
  1. Re-validate:

    /plugin validate
    
  2. When all critical issues fixed:

    ✓ Ready for publication
    

Validation Metrics

  • Structure: 95% ✓
  • Metadata: 90% ✓
  • Components: 80% ⚠️
  • Documentation: 85% ✓
  • Best Practices: 85% ⚠️

Overall Score: 87% ⚠️ (PASS with warnings)

Status: FIX CRITICAL ISSUES before publishing


## Validation Levels

### Strict Mode

Enforces all best practices:
- All commands must have examples
- All skills must have triggering conditions
- All agents must have output formats
- README must be comprehensive
- No warnings allowed

### Standard Mode (Default)

Allows warnings:
- Critical structural issues: FAIL
- Missing required fields: FAIL
- Best practice violations: WARN
- Missing recommended sections: WARN

### Lenient Mode

Only fails on critical errors:
- Invalid JSON: FAIL
- Missing required files: FAIL
- Invalid references: FAIL
- Everything else: INFO

## Common Issues Reference

### Issue: Skill is flat file
**Problem**: `skills/my-skill.md`
**Fix**:
```bash
mkdir -p skills/my-skill
mv skills/my-skill.md skills/my-skill/SKILL.md

Issue: Command has plugin prefix

Problem: name: plugin:start Fix: Change to name: start

Issue: Hook not executable

Problem: Hook exists but won't run Fix:

chmod +x hooks/PreToolUse.sh

Issue: Invalid agent color

Problem: color: red Fix: Use valid color (blue, green, orange, cyan, purple)

Issue: Invalid tool in agent

Problem: tools: [InvalidTool] Fix: Use valid tools (Read, Grep, Glob, Bash, Edit, Write, Task)

Issue: Missing frontmatter

Problem: No YAML frontmatter in component Fix: Add frontmatter:

---
name: component-name
description: Component purpose
---

Automated Checks

Can run automated validation:

# Validate structure
find . -name "plugin.json"
jq . .claude-plugin/plugin.json

# Check for flat skills (common error)
find skills/ -maxdepth 1 -name "*.md" -type f

# Check hooks executable
find hooks/ -type f ! -executable

# Check command names don't have plugin prefix
grep -r "^name:.*:.*" commands/

Output

Return comprehensive validation report with:

  • Overall status (PASS/WARNINGS/FAIL)
  • Detailed findings per component type
  • Specific issues with locations
  • Fix instructions for each issue
  • Recommendations for improvement
  • Next steps

References

Sponsors

Details

Marketplace
TomazWang/agent-toolkit
Source
plugins/plugin-creator
Author
Agent Toolkit
Category
Meta
Keywords
meta, development, tools, plugin-development

More from TomazWang/agent-toolkit

All 6