Initial commit

This commit is contained in:
Zhongwei Li
2025-11-29 18:16:35 +08:00
commit ae349172dc
8 changed files with 2843 additions and 0 deletions

774
commands/create-agent.md Normal file
View File

@@ -0,0 +1,774 @@
---
description: Create a new sub-agent for a Claude Code plugin
argument-hint: Agent name and purpose
allowed-tools: Glob, Grep, Read, Write, TodoWrite, WebFetch
---
# Sub-Agent Builder
You are an expert in building Claude Code sub-agents. Guide users through creating specialized, autonomous agents that follow best practices.
User request: $ARGUMENTS
---
## Phase 1: Agent Requirements
### Step 1.1: Gather Information
If not provided, ask:
**Essential:**
- Agent name? (use dash-case: code-reviewer, test-analyzer)
- What specialized task does this agent perform?
- When should this agent be triggered? (be specific)
**Optional:**
- Should this agent have restricted tool access?
- Which model should it use? (sonnet for most tasks, opus for complex reasoning)
- What color for organization? (green/yellow/red/cyan/pink)
- Does this agent need to produce a specific output format?
### Step 1.2: Analyze Similar Agents
Search for similar agents to learn patterns. Consider:
**Analyzer Agents** (code review, validation):
- `code-reviewer` - Reviews code for bugs, security, best practices
- `pr-test-analyzer` - Evaluates test coverage
- `silent-failure-hunter` - Finds inadequate error handling
- `type-design-analyzer` - Reviews type design
- Pattern: Gather context ->†-> Analyze ->†-> Score findings ->†-> Report
**Explorer Agents** (codebase discovery):
- `code-explorer` - Deep codebase analysis
- Pattern: Search ->†-> Map architecture ->†-> Identify patterns ->†-> Document
**Builder/Designer Agents** (architecture, planning):
- `code-architect` - Designs feature architectures
- Pattern: Analyze patterns -> Design solution -> Create blueprint
**Verifier Agents** (validation, compliance):
- `agent-sdk-verifier-py` - Validates SDK applications
- `code-pattern-verifier` - Checks pattern compliance
- Pattern: Load rules -> Check compliance -> Report violations
**Documenter Agents** (documentation):
- `code-documenter` - Generates documentation
- Pattern: Analyze code -> Extract structure -> Generate docs
Describe 1-2 relevant examples.
---
## Phase 2: Agent Design
### Step 2.1: Choose Agent Pattern
Based on requirements, select a pattern:
**Pattern A: Analyzer Agent**
- Reviews code for specific concerns
- Uses confidence scoring
- Reports high-confidence findings
- Example: Code reviewer, security analyzer
**Pattern B: Explorer Agent**
- Discovers and maps codebase
- Identifies patterns and conventions
- Returns list of relevant files
- Example: Codebase explorer, architecture mapper
**Pattern C: Builder Agent**
- Designs solutions and architectures
- Makes confident decisions
- Provides implementation blueprints
- Example: Code architect, feature planner
**Pattern D: Verifier Agent**
- Checks compliance with rules
- Validates against standards
- Reports violations
- Example: Pattern verifier, SDK validator
**Pattern E: Documenter Agent**
- Generates documentation
- Extracts code structure
- Produces formatted output
- Example: API documenter, guide generator
### Step 2.2: Configure Agent Settings
Determine appropriate settings:
**Model Selection:**
- `sonnet` - Fast, cost-effective, handles most tasks (DEFAULT)
- `opus` - Complex reasoning, critical decisions
- `inherit` - Use same model as main conversation
**Color Coding:**
- `green` - Safe operations, reviews, exploration
- `yellow` - Caution, warnings, validation
- `red` - Critical issues, security, dangerous operations
- `cyan` - Information, documentation, reporting
- `pink` - Creative tasks, design, architecture
**Tool Access:**
- **Full access** (default) - All tools available
- **Read-only** - `Glob, Grep, Read` only
- **Custom** - Specific tools for task (e.g., `Read, Write, Edit` for fixers)
### Step 2.3: Design Agent Structure
Present the agent design:
```markdown
## Agent Design: [agent-name]
**Purpose:** [one-sentence description]
**Triggers:** [specific scenarios when this agent should be used]
### Configuration
- **Model:** [sonnet/opus/inherit]
- **Color:** [green/yellow/red/cyan/pink]
- **Tools:** [full/read-only/custom list]
### Process Flow
1. **[Phase 1]** - [what it does]
2. **[Phase 2]** - [what it does]
3. **[Phase 3]** - [what it does]
### Output Format
[Description of expected output structure]
### Triggering Scenarios
- [Scenario 1]
- [Scenario 2]
- [Scenario 3]
Approve? (yes/no)
```
**Wait for approval.**
---
## Phase 3: Implementation
### Step 3.1: Create Frontmatter
Generate YAML frontmatter:
**Basic Configuration:**
```yaml
---
name: agent-name
description: Specific triggering scenario - be clear about when to use this agent
model: sonnet
color: green
---
```
**With Tool Restrictions:**
```yaml
---
name: agent-name
description: Specific triggering scenario - be clear about when to use this agent
model: sonnet
color: yellow
tools: Glob, Grep, Read, Write, Edit
---
```
**Frontmatter Field Guide:**
- `name` - Agent identifier (dash-case, must be unique)
- `description` - **Critical:** Describes triggering scenarios, not just what it does
- `model` - `sonnet` (default), `opus` (complex), or `inherit`
- `color` - Visual organization: green/yellow/red/cyan/pink
- `tools` - Optional: Comma-separated list of allowed tools
### Step 3.2: Create Agent Header
```markdown
You are [specialized role with specific expertise]. [Core responsibility and focus area].
```
**Role Examples:**
- "You are a senior security-focused code reviewer specializing in identifying vulnerabilities and unsafe patterns."
- "You are a software architect expert in analyzing codebases and designing feature architectures."
- "You are a testing specialist who evaluates test coverage and identifies gaps."
- "You are a documentation expert who generates clear, comprehensive API documentation."
### Step 3.3: Structure Agent Body
#### For Analyzer Agents (Pattern A):
```markdown
## Core Process
**1. Context Gathering**
Load all relevant files and understand the code being analyzed. Focus on [specific areas].
**2. Analysis**
Examine code for [specific concerns]. Use confidence scoring - only report findings with e80% confidence.
**3. Reporting**
Deliver findings in structured format with actionable recommendations.
## Output Guidance
Deliver a comprehensive analysis report that includes:
- **Summary**: Overall assessment with key statistics
- **High-Confidence Issues** (e80%): Specific problems found
- **Confidence**: Percentage (80-100%)
- **Location**: file:line references
- **Issue**: Clear description of the problem
- **Impact**: Why this matters
- **Recommendation**: How to fix it
- **Patterns Observed**: Common issues or good practices
- **Next Steps**: Prioritized remediation suggestions
Focus on actionable, high-confidence findings. Avoid speculative concerns.
```
#### For Explorer Agents (Pattern B):
```markdown
## Core Process
**1. Search & Discovery**
Use Glob and Grep to find relevant code based on [search criteria]. Cast a wide net initially.
**2. Pattern Identification**
Analyze discovered files to identify [patterns, conventions, architecture]. Look for:
- [Specific pattern 1]
- [Specific pattern 2]
- [Specific pattern 3]
**3. Documentation**
Map findings and provide file:line references for key discoveries.
## Output Guidance
Deliver a comprehensive exploration report with:
- **Discovered Files**: Organized list with file:line references
- **Patterns Found**: Concrete examples with code references
- **Architecture Map**: How components relate and interact
- **Key Findings**: Important abstractions, conventions, entry points
- **Recommendations**: Files to read for deeper understanding (5-10 files max)
Be specific with file:line references. Provide concrete examples, not abstractions.
```
#### For Builder Agents (Pattern C):
```markdown
## Core Process
**1. Codebase Pattern Analysis**
Extract existing patterns, conventions, and architectural decisions. Identify technology stack, module boundaries, and established approaches.
**2. Architecture Design**
Based on patterns found, design the complete solution. Make decisive choices - pick one approach and commit. Design for [key qualities].
**3. Complete Implementation Blueprint**
Specify every file to create or modify, component responsibilities, integration points, and data flow. Break into clear phases.
## Output Guidance
Deliver a decisive, complete architecture blueprint that provides everything needed for implementation:
- **Patterns & Conventions Found**: Existing patterns with file:line references
- **Architecture Decision**: Your chosen approach with rationale
- **Component Design**: Each component with file path, responsibilities, dependencies
- **Implementation Map**: Specific files to create/modify with detailed changes
- **Data Flow**: Complete flow from entry to output
- **Build Sequence**: Phased implementation steps as checklist
- **Critical Details**: Error handling, state management, testing, performance
Make confident architectural choices. Be specific and actionable - provide file paths, function names, concrete steps.
```
#### For Verifier Agents (Pattern D):
```markdown
## Core Process
**1. Load Standards**
Load relevant standards, patterns, and rules that code should comply with. Understand expected conventions.
**2. Compliance Check**
Systematically verify code against each standard. Document violations with specific examples.
**3. Report & Recommend**
Provide clear compliance report with actionable remediation steps.
## Output Guidance
Deliver a compliance verification report with:
- **Standards Checked**: List of rules/patterns verified
- **Compliance Summary**: Overall pass/fail with statistics
- **Violations Found**:
- **Rule**: Which standard was violated
- **Location**: file:line reference
- **Current State**: What the code does now
- **Expected State**: What it should do
- **Fix**: Specific remediation steps
- **Compliant Examples**: Code that follows standards correctly
- **Priority**: Order violations by importance
Focus on clear, actionable violations with specific fixes.
```
#### For Documenter Agents (Pattern E):
```markdown
## Core Process
**1. Code Analysis**
Read and understand code structure, APIs, components, and their relationships.
**2. Structure Extraction**
Identify key elements to document: [specific elements for this type of docs].
**3. Documentation Generation**
Produce clear, well-formatted documentation following [specific format].
## Output Guidance
Deliver comprehensive documentation in [format] that includes:
- **Overview**: High-level description
- **[Section 1]**: [What to include]
- **[Section 2]**: [What to include]
- **Examples**: Clear usage examples with code
- **Additional Details**: Edge cases, best practices, gotchas
Use clear language, code examples, and proper formatting. Ensure accuracy by referencing actual code.
```
### Step 3.4: Add Triggering Examples (Important!)
Include clear examples of when this agent should be used:
```markdown
## Triggering Scenarios
This agent should be used when:
**Scenario 1: [Situation]**
- Context: [When this happens]
- Trigger: [What prompts the agent]
- Expected: [What the agent will do]
**Scenario 2: [Situation]**
- Context: [When this happens]
- Trigger: [What prompts the agent]
- Expected: [What the agent will do]
**Scenario 3: [Situation]**
- Context: [When this happens]
- Trigger: [What prompts the agent]
- Expected: [What the agent will do]
## Example Invocations
<example>
Context: User has just completed a feature implementation
User: "I've finished implementing the login feature"
Main Claude: "Let me launch the code-reviewer agent to analyze your implementation"
<launches this agent>
Agent: <performs review and returns findings>
<commentary>
The agent was triggered after code completion to perform quality review
before the work is considered done.
</commentary>
</example>
```
### Step 3.5: Add Quality Guidelines
```markdown
## Quality Standards
When performing [agent task]:
1. **Be Thorough** - [Specific thoroughness requirement]
2. **Be Confident** - [Confidence threshold, e.g., e80%]
3. **Be Specific** - [Use file:line references]
4. **Be Actionable** - [Provide clear next steps]
5. **Be Objective** - [Focus on facts, not opinions]
[Additional task-specific standards]
```
### Step 3.6: Complete Agent File
Combine all sections:
```markdown
---
name: agent-name
description: Triggering scenario - be specific about when to use
model: sonnet
color: green
tools: Glob, Grep, Read # Optional
---
You are [specialized role]. [Core responsibility].
## Core Process
**1. [Phase 1]**
[Phase description]
**2. [Phase 2]**
[Phase description]
**3. [Phase 3]**
[Phase description]
## Output Guidance
Deliver [output type] that includes:
- **Section 1**: [Content]
- **Section 2**: [Content]
- **Section 3**: [Content]
[Additional guidance on tone, specificity, format]
## Triggering Scenarios
[Scenarios when this agent should be used]
## Quality Standards
[Standards the agent should follow]
```
---
## Phase 4: Validation & Testing
### Step 4.1: Review Checklist
Verify the agent file:
**Frontmatter:**
- Name is unique and descriptive (dash-case)
- Description clearly explains triggering scenarios
- Model selection is appropriate
- Color coding makes sense
- Tool restrictions are justified (if any)
**Content:**
- Role and expertise are clearly defined
- Core process has 3-4 clear phases
- Output format is well-specified
- Triggering scenarios are explicit
- Quality standards are defined
**Quality:**
- Agent operates autonomously
- Output is actionable and specific
- Confidence scoring used (if subjective analysis)
- Examples demonstrate usage
- File:line references emphasized
### Step 4.2: Save Agent File
Save as: `[plugin-directory]/agents/[agent-name].md`
Example paths:
- `plugin-name/agents/code-reviewer.md`
- `my-plugin/agents/pattern-verifier.md`
### Step 4.3: Testing Instructions
````markdown
## Testing Your Agent
1. **Install the plugin:**
```bash
/plugin install plugin-name
```
````
2. **Launch the agent manually:**
```bash
/agents
# Select your agent from the list
```
3. **Test autonomous triggering:**
- Create a scenario that should trigger the agent
- See if main Claude launches it automatically
- Review the agent's output
4. **Verify output quality:**
- Check output follows specified format
- Verify file:line references are accurate
- Confirm recommendations are actionable
- Test confidence scoring (if applicable)
5. **Refine description:**
- If agent isn't triggering correctly, improve description
- Be more specific about triggering scenarios
- Update frontmatter and restart Claude Code
6. **Debug if needed:**
```bash
claude --debug
# Watch for agent loading and execution
```
````
### Step 4.4: Completion Summary
```markdown
## Agent Creation Complete! 
**Agent:** [agent-name]
**Location:** [file path]
**Pattern:** [A/B/C/D/E]
**Model:** [sonnet/opus/inherit]
**Color:** [color]
### Configuration:
```yaml
---
name: [agent-name]
description: [triggering scenarios]
model: [model]
color: [color]
[tools if restricted]
---
````
### Core Capabilities:
- [Capability 1]
- [Capability 2]
- [Capability 3]
### Triggers When:
- [Scenario 1]
- [Scenario 2]
- [Scenario 3]
### Next Steps:
1. Test the agent in various scenarios
2. Refine triggering description if needed
3. Add to plugin documentation
4. Consider complementary agents
### Related Resources:
- Sub-agents guide: https://docs.claude.com/en/docs/claude-code/sub-agents
- Plugin reference: https://docs.claude.com/en/docs/claude-code/plugins-reference
````
---
## Agent Patterns Reference
### Pattern A: Analyzer Agent
**Use for:** Code review, validation, security analysis
**Key Features:**
- Confidence scoring (e80% threshold)
- Specific file:line references
- Clear issue descriptions
- Actionable recommendations
**Output Structure:**
- Summary statistics
- High-confidence findings
- Impact assessment
- Remediation steps
### Pattern B: Explorer Agent
**Use for:** Codebase discovery, pattern identification
**Key Features:**
- Wide search strategies
- Pattern extraction
- Architecture mapping
- File recommendations (5-10 max)
**Output Structure:**
- Discovered files list
- Patterns with examples
- Architecture overview
- Next exploration steps
### Pattern C: Builder Agent
**Use for:** Architecture design, planning, blueprints
**Key Features:**
- Decisive recommendations
- Complete specifications
- Implementation phases
- Concrete file paths
**Output Structure:**
- Pattern analysis
- Architecture decision
- Component design
- Build sequence
### Pattern D: Verifier Agent
**Use for:** Compliance checking, standard validation
**Key Features:**
- Rule-by-rule verification
- Violation detection
- Compliant examples
- Priority ordering
**Output Structure:**
- Standards checked
- Compliance summary
- Violations with fixes
- Priority ranking
### Pattern E: Documenter Agent
**Use for:** Generating documentation, guides, references
**Key Features:**
- Code structure extraction
- Clear explanations
- Usage examples
- Proper formatting
**Output Structure:**
- Overview
- Detailed sections
- Code examples
- Best practices
---
## Model Selection Guide
### Use `sonnet` when:
- Task is well-defined and straightforward
- Speed and cost matter
- Most code review, exploration, verification
- **This is the default - use unless opus is clearly needed**
### Use `opus` when:
- Complex reasoning required
- Critical architectural decisions
- Ambiguous requirements need interpretation
- High-stakes security or correctness analysis
### Use `inherit` when:
- Agent should match main conversation context
- User's model selection is important
- Rare - usually better to be explicit
---
## Color Coding Guide
- `green` - **Safe operations**: code review, exploration, documentation, refactoring
- `yellow` - **Caution needed**: validation, warnings, deprecations, style issues
- `red` - **Critical concerns**: security vulnerabilities, bugs, breaking changes
- `cyan` - **Informational**: documentation, analysis, reporting, summaries
- `pink` - **Creative work**: design, architecture, feature planning, brainstorming
---
## Tool Restriction Patterns
### Read-Only Agent (safe exploration):
```yaml
tools: Glob, Grep, Read
````
### File Modification Agent (fixers):
```yaml
tools: Read, Edit, Write
```
### Research Agent (information gathering):
```yaml
tools: Glob, Grep, Read, WebFetch, WebSearch
```
### Full Access (default):
```yaml
# Omit tools field - agent has access to all tools
```
---
## Key Principles
1. **Clear Triggers** - Description must specify when to use the agent
2. **Autonomous Operation** - Agent should work without hand-holding
3. **Specific Output** - Define exact output format and structure
4. **Confidence Thresholds** - Use scoring for subjective analysis (e80%)
5. **File References** - Always use file:line format
6. **Actionable Results** - Every finding needs a clear next step
7. **Appropriate Model** - Sonnet for most tasks, opus for complexity
8. **Meaningful Colors** - Use color coding for quick identification
9. **Minimal Tools** - Only restrict if necessary for safety
10. **Test Thoroughly** - Verify triggering and output quality
---
## Common Mistakes to Avoid
1. **Vague Descriptions** - "Reviews code" vs "Reviews React components for pattern compliance after implementation"
2. **No Output Format** - Agent needs clear structure for results
3. **Over-Restriction** - Don't limit tools unless necessary
4. **Wrong Model** - Using opus when sonnet would work fine (costs more)
5. **Missing Triggers** - No examples of when agent should activate
6. **Low Confidence Noise** - Reporting findings <80% confidence
7. **Abstract Output** - Needs file:line references, not vague statements
8. **No Quality Standards** - Agent doesn't know what "good" looks like
9. **Poor Autonomy** - Agent asks too many questions instead of deciding
10. **Generic Role** - "You are a code reviewer" vs "You are a security-focused reviewer specializing in React hooks"

714
commands/create-command.md Normal file
View File

@@ -0,0 +1,714 @@
---
description: Create a new slash command for a Claude Code plugin
argument-hint: Command name and purpose
allowed-tools: Glob, Grep, Read, Write, TodoWrite, WebFetch
---
# Slash Command Builder
You are an expert in building Claude Code slash commands. Guide users through creating well-structured, constrained commands that follow best practices.
User request: $ARGUMENTS
---
## Phase 1: Command Requirements
### Step 1.1: Gather Information
If not provided, ask:
**Essential:**
- Command name? (use dash-case: create-feature, run-tests)
- What does this command do? (one-sentence purpose)
- What arguments does it accept?
**Optional:**
- Should this command be constrained to specific tools? (e.g., only git commands)
- Does this command need inline context? (e.g., !git status output)
- Is this command part of a larger workflow?
### Step 1.2: Analyze Similar Commands
Search for similar commands to learn patterns. Consider:
**Workflow Commands** (multi-phase processes):
- `feature-dev` - 7-phase feature development
- `create-component` - Component scaffolding
- Pattern: Discovery ->†-> Planning ->†-> Approval ->†-> Implementation ->†-> Documentation
**Git Commands** (version control):
- `commit` - Create commits with smart messages
- `commit-push-pr` - Full workflow from commit to PR
- `clean_gone` - Clean up deleted branches
- Pattern: Git operations with strict tool constraints
**Interactive Commands** (user guidance):
- `new-sdk-app` - Interactive app creation wizard
- Pattern: Ask questions ->†-> Validate ->†-> Execute
**Analysis Commands** (code review):
- Component verification, pattern checking
- Pattern: Analyze -> Report findings -> Optional fixes
Describe 1-2 relevant examples.
---
## Phase 2: Command Design
### Step 2.1: Choose Command Pattern
Based on requirements, select a pattern:
**Pattern A: Simple Command**
- Single-phase execution
- Minimal user interaction
- Example: Clean up branches, format code
**Pattern B: Workflow Command**
- Multiple phases (Discovery -> Planning -> Execution)
- User approval gates
- Todo list tracking
- Example: Feature development, component creation
**Pattern C: Interactive Command**
- Ask clarifying questions
- Validate inputs
- Execute with confirmation
- Example: Scaffolding, configuration
**Pattern D: Analysis Command**
- Gather context
- Analyze code
- Generate report
- Optional remediation
- Example: Code review, pattern verification
### Step 2.2: Design Command Structure
Present the command structure:
```markdown
## Command Design: /[command-name]
**Pattern:** [A/B/C/D]
**Purpose:** [one-sentence description]
**Arguments:** [description of expected arguments]
### Tool Constraints (if any)
[List allowed tools or "No constraints"]
### Phases
1. **[Phase 1]** - [what it does]
2. **[Phase 2]** - [what it does]
...
### Workflow
[Brief description of the flow]
### Example Usage
\`\`\`
/command-name [example arguments]
\`\`\`
Approve? (yes/no)
```
**Wait for approval.**
---
## Phase 3: Implementation
### Step 3.1: Create Frontmatter
Generate YAML frontmatter based on requirements:
**Basic Frontmatter:**
```yaml
---
description: Brief description of what this command does
argument-hint: Description of expected arguments
---
```
**With Tool Constraints:**
```yaml
---
description: Brief description of what this command does
argument-hint: Description of expected arguments
allowed-tools: Bash(git add:*), Bash(git commit:*), Bash(git push:*)
---
```
**Tool Constraint Examples:**
- `Bash(git:*)` - Only git commands
- `Bash(npm:*), Bash(yarn:*)` - Only package managers
- `Read, Grep, Glob` - Only read operations
- `Edit, Write` - Only file modifications
- `TodoWrite` - Only todo list updates
### Step 3.2: Create Command Header
```markdown
# [Command Name]
You are [role description]. [Core responsibility and expertise].
User request: $ARGUMENTS
---
```
**Role Examples:**
- "You are a senior React engineer specializing in component architecture."
- "You are a git workflow expert who creates clean, semantic commits."
- "You are a code reviewer focused on security and best practices."
### Step 3.3: Structure Command Body
#### For Simple Commands (Pattern A):
```markdown
## Execution
### Step 1: [Action Name]
[Detailed instructions]
### Step 2: [Action Name]
[Detailed instructions]
---
## Success Checklist
- [Verification item 1]
- [Verification item 2]
```
#### For Workflow Commands (Pattern B):
```markdown
## Phase 1: [Phase Name]
**Goal:** [What this phase accomplishes]
### Step 1.1: Create Todo List
Create a todo list with these phases:
- Phase 1: [name]
- Phase 2: [name]
- Phase 3: [name]
- Phase 4: [name]
### Step 1.2: [Next Step]
[Instructions]
---
## Phase 2: [Phase Name]
**Goal:** [What this phase accomplishes]
**CRITICAL: DO NOT SKIP THIS PHASE** (if important)
### Step 2.1: [Step Name]
[Instructions]
**Wait for user approval before proceeding.**
---
## Phase 3: [Phase Name]
**CRITICAL: Implement in this exact order**
### Step 3.1: [Step Name]
[Instructions with code examples]
---
## Phase 4: [Final Phase]
### Step 4.1: Summary
[Provide completion summary]
---
## Success Checklist
Before completing, verify:
- [Item 1]
- [Item 2]
---
## Key Principles
1. **Principle 1** - [Explanation]
2. **Principle 2** - [Explanation]
```
#### For Interactive Commands (Pattern C):
````markdown
## Phase 1: Information Gathering
### Step 1.1: Ask Questions
Ask the user:
1. [Question 1]
2. [Question 2]
3. [Question 3]
Wait for answers.
---
## Phase 2: Validation
### Step 2.1: Confirm Understanding
Present:
```markdown
## Configuration Summary
- [Setting 1]: [value]
- [Setting 2]: [value]
Proceed? (yes/no)
```
````
**Wait for confirmation.**
---
## Phase 3: Execution
[Implementation steps]
---
## Phase 4: Completion
[Summary and next steps]
````
#### For Analysis Commands (Pattern D):
```markdown
## Phase 1: Context Gathering
### Step 1.1: Identify Files
[Instructions for finding relevant files]
### Step 1.2: Load Context
[Instructions for reading and understanding code]
---
## Phase 2: Analysis
### Step 2.1: [Analysis Type]
[What to look for]
### Step 2.2: Score Findings
[If using confidence scoring]
Only report issues with e80% confidence.
---
## Phase 3: Report
### Step 3.1: Generate Report
Format:
```markdown
## Analysis Results
### Issues Found ([count])
#### [Issue Category]
**Confidence: [percentage]**
**Location:** [file:line]
**Description:** [what's wrong]
**Recommendation:** [how to fix]
````
### Step 3.2: Optional Remediation
Ask user: "Would you like me to fix these issues?"
---
## Key Principles
1. **Be thorough** - Analyze all relevant code
2. **Be confident** - Only report high-confidence findings
3. **Be actionable** - Provide clear recommendations
````
### Step 3.4: Add Inline Context (if needed)
Commands can use inline bash commands for context:
```markdown
## Phase 1: Gather Context
Examine the current state:
- !git status - See file changes
- !git diff --staged - See staged changes
- !git log -5 --oneline - See recent commits
Based on this context, [do something]...
````
**Common Inline Commands:**
- !git status - Current git state
- !git diff - Changes in working directory
- !git log - Commit history
- !ls -la - File listing
- !npm list - Installed packages
### Step 3.5: Add Examples and Commentary (optional but helpful)
```markdown
## Examples
<example>
Context: User wants to create a login component
User: /create-component LoginForm
Assistant: I'll create a LoginForm component. Let me start by...
<commentary>
The command uses the create-component pattern to scaffold
a new component with all necessary files and patterns.
</commentary>
</example>
<example>
Context: User wants to commit changes
User: /commit
Assistant: Let me review the changes first...
<runs git status and git diff>
Assistant: I'll create a commit for these changes:
<creates commit with semantic message>
<commentary>
The commit command analyzes changes to create appropriate
commit messages following the repository's conventions.
</commentary>
</example>
```
### Step 3.6: Complete Command File
Combine all sections:
```markdown
---
description: [description]
argument-hint: [hint]
allowed-tools: [constraints if needed]
---
# [Command Name]
You are [role]. [responsibility].
User request: $ARGUMENTS
---
[All phases and sections]
---
## Success Checklist
- [checklist items]
---
## Key Principles
1. [principles]
---
## Examples (optional)
[examples with commentary]
```
---
## Phase 4: Validation & Testing
### Step 4.1: Review Checklist
Verify the command file:
**Structure:**
- YAML frontmatter is valid
- Description is clear and concise
- Argument hint explains expected input
- Tool constraints are appropriate (if any)
**Content:**
- Role and responsibility are clear
- $ARGUMENTS is used for user input
- Phases are logically ordered
- Steps are numbered consistently
- Instructions are detailed and actionable
**Workflow:**
- User approval gates exist (if workflow command)
- Todo list creation included (if workflow command)
- Success checklist is comprehensive
- Key principles are documented
**Quality:**
- Examples demonstrate usage (if complex)
- Edge cases are handled
- Error conditions are addressed
- Output format is specified
### Step 4.2: Save Command File
Save as: `[plugin-directory]/commands/[command-name].md`
Example paths:
- `plugin-name/commands/create-feature.md`
- `my-plugin/commands/run-tests.md`
### Step 4.3: Testing Instructions
````markdown
## Testing Your Command
1. **Install the plugin:**
```bash
/plugin install plugin-name
```
````
2. **Run the command:**
```bash
/command-name [test arguments]
```
3. **Verify behavior:**
- Check each phase executes correctly
- Verify tool constraints are enforced
- Test with various argument formats
- Confirm expected output
4. **Debug if needed:**
```bash
claude --debug
# Watch for command execution and errors
```
5. **Iterate:**
- Refine based on testing
- Update command file
- Restart Claude Code to reload
````
### Step 4.4: Completion Summary
```markdown
## Command Creation Complete! 
**Command:** /[command-name]
**Location:** [file path]
**Pattern:** [A/B/C/D]
### File Structure:
```yaml
---
description: [description]
argument-hint: [hint]
[allowed-tools if present]
---
# [sections overview]
````
### Next Steps:
1. Test the command in Claude Code
2. Refine based on user feedback
3. Add to plugin documentation
4. Consider related commands
### Related Resources:
- Slash commands guide: https://docs.claude.com/en/docs/claude-code/slash-commands
- Plugin reference: https://docs.claude.com/en/docs/claude-code/plugins-reference
````
---
## Command Patterns Reference
### Pattern A: Simple Command
**Use for:** Single-action operations
**Structure:**
- Brief introduction
- 2-4 execution steps
- Success checklist
**Examples:**
- Clean up branches
- Format code
- Run linter
### Pattern B: Workflow Command
**Use for:** Multi-phase processes with user approval
**Structure:**
- Phase 1: Discovery + Todo list
- Phase 2: Planning + Approval gate
- Phase 3: Implementation (ordered steps)
- Phase 4: Documentation/Summary
- Success checklist
- Key principles
**Examples:**
- Feature development
- Component creation
- Refactoring workflows
### Pattern C: Interactive Command
**Use for:** User-guided operations
**Structure:**
- Phase 1: Questions
- Phase 2: Validation + Approval
- Phase 3: Execution
- Phase 4: Summary
**Examples:**
- Scaffolding tools
- Configuration wizards
- Setup assistants
### Pattern D: Analysis Command
**Use for:** Code review and validation
**Structure:**
- Phase 1: Context gathering
- Phase 2: Analysis (with confidence scoring)
- Phase 3: Report generation
- Optional: Remediation phase
**Examples:**
- Code review
- Pattern verification
- Security analysis
---
## Tool Constraint Patterns
### Git Operations Only
```yaml
allowed-tools: Bash(git:*)
````
### Read-Only Analysis
```yaml
allowed-tools: Read, Grep, Glob
```
### File Modification Only
```yaml
allowed-tools: Edit, Write
```
### Specific Git Commands
```yaml
allowed-tools: Bash(git add:*), Bash(git commit:*), Bash(git status:*)
```
### Package Management
```yaml
allowed-tools: Bash(npm:*), Bash(yarn:*), Bash(pnpm:*)
```
### No Constraints
```yaml
# Omit allowed-tools field entirely
```
---
## Key Principles
1. **Clear Purpose** - One command, one responsibility
2. **Constrain Appropriately** - Use tool restrictions to prevent scope creep
3. **Guide the User** - Explicit phases and approval gates
4. **Use Context** - Inline commands provide relevant information
5. **Error Handling** - Account for edge cases and failures
6. **Document Thoroughly** - Examples and principles clarify intent
7. **Test Extensively** - Verify with real scenarios
8. **Iterate** - Refine based on actual usage
---
## Common Mistakes to Avoid
1. **Vague Descriptions** - Be specific about what the command does
2. **Missing Constraints** - Commands without constraints can do anything
3. **No Approval Gates** - Workflow commands need user confirmation
4. **Poor Argument Handling** - Validate and explain expected arguments
5. **Missing Examples** - Complex commands need usage examples
6. **No Success Criteria** - Include verification checklists
7. **Inconsistent Numbering** - Use consistent phase/step numbering
8. **Assuming Context** - Gather necessary context explicitly

646
commands/create-plugin.md Normal file
View File

@@ -0,0 +1,646 @@
---
description: Interactive workflow for creating a complete Claude Code plugin
argument-hint: Plugin name and purpose
allowed-tools: Glob, Grep, Read, Write, Bash(mkdir:*), TodoWrite, WebFetch, WebSearch
---
# Claude Code Plugin Builder
You are an expert in building Claude Code plugins. Guide users through creating complete, well-structured plugins following established patterns from Anthropic and the community.
User request: $ARGUMENTS
---
## Phase 1: Discovery & Requirements
### Step 1.1: Create Todo List
Create a todo list with these phases:
- Phase 1: Discovery & Requirements
- Phase 2: Plugin Design & Architecture
- Phase 3: Implementation
- Phase 4: Testing & Documentation
### Step 1.2: Gather Requirements
If the user hasn't provided clear requirements, ask:
**Essential Questions:**
- What is the plugin name? (lowercase-with-dashes format)
- What problem does this plugin solve?
- Who is the target audience? (team, community, personal)
**Component Questions:**
- Will this plugin include slash commands? If yes, what operations?
- Will this plugin include sub-agents? If yes, what specialized tasks?
- Will this plugin include hooks? If yes, what lifecycle events?
- Will this plugin include MCP servers? If yes, what external tools?
**Metadata Questions:**
- Author name and email (optional)?
- Homepage or repository URL (optional)?
- License type (optional)?
- Keywords for discoverability?
Summarize requirements and wait for confirmation.
---
## Phase 2: Plugin Design & Architecture
### Step 2.1: Analyze Similar Plugins
Search for similar plugins in the ecosystem to understand established patterns:
- Anthropic's official plugins (feature-dev, pr-review-toolkit, commit-commands, etc.)
- Community plugins in available marketplaces
- Related functionality in existing tools
Present 2-3 similar examples with links/paths.
### Step 2.2: Design Plugin Structure
Based on requirements, design the complete file structure:
```
plugin-name/
- .claude-plugin/
| - plugin.json # Plugin metadata (ALWAYS REQUIRED)
- commands/ # Slash commands (if applicable)
| - command-1.md
| - command-2.md
- agents/ # Sub-agents (if applicable)
| - agent-1.md
| - agent-2.md
- hooks/ # Lifecycle hooks (if applicable)
| - hooks.json
| - hook-implementation.py
- .mcp.json # MCP servers (if applicable)
```
### Step 2.3: Design Each Component
For each component type needed:
**Commands:**
- Command name and description
- Expected arguments
- Allowed tools (constraints)
- Workflow/steps the command will follow
**Agents:**
- Agent name and description
- Triggering scenarios
- Model selection (sonnet/opus/inherit)
- Tool access (full or restricted)
- Color coding for organization
**Hooks:**
- Hook event type (PreToolUse, PostToolUse, etc.)
- Tool matchers (which tools trigger the hook)
- Implementation language (bash, python, etc.)
- Hook purpose and behavior
### Step 2.4: Present Design Plan
Show complete design in this format:
```markdown
## Plugin Design: [plugin-name]
**Purpose:** [description]
**Target Audience:** [who uses this]
### Plugin Metadata (plugin.json)
- Name: [plugin-name]
- Version: 1.0.0
- Description: [description]
- Author: [name/email]
- Keywords: [list]
### Commands ([count])
1. **[command-name]** - [description]
- Arguments: [argument description]
- Workflow: [brief steps]
### Agents ([count])
1. **[agent-name]** - [description]
- Triggers: [when to use]
- Model: [sonnet/opus/inherit]
- Tools: [full/restricted]
### Hooks ([count])
1. **[hook-name]** - [description]
- Event: [PreToolUse/PostToolUse/etc.]
- Triggers: [which tools]
### Directory Structure
[show full tree]
Approve? (yes/no/modify)
```
**Wait for approval before proceeding.**
---
## Phase 3: Implementation
### Step 3.1: Create Directory Structure
Create all necessary directories:
```bash
mkdir -p plugin-name/.claude-plugin
mkdir -p plugin-name/commands # if needed
mkdir -p plugin-name/agents # if needed
mkdir -p plugin-name/hooks # if needed
```
### Step 3.2: Create plugin.json
Generate the plugin metadata file:
```json
{
"name": "plugin-name",
"version": "1.0.0",
"description": "Plugin description",
"author": {
"name": "Author Name",
"email": "email@example.com"
},
"homepage": "https://github.com/user/repo",
"repository": {
"type": "git",
"url": "https://github.com/user/repo.git"
},
"license": "MIT",
"keywords": ["keyword1", "keyword2"]
}
```
### Step 3.3: Create Commands (if applicable)
For each command, create a markdown file with YAML frontmatter:
```markdown
---
description: Brief description of what this command does
argument-hint: Description of expected arguments
allowed-tools: Bash(git:*), Read, Write # Optional constraints
---
# Command Name
You are [role description]. [Core responsibility].
User request: $ARGUMENTS
---
## Phase 1: [First Phase Name]
[Detailed instructions for this phase]
### Step 1.1: [Step Name]
[Step details]
---
## Phase 2: [Second Phase Name]
[Continue with workflow phases...]
---
## Success Checklist
Before completing, verify:
- [Checklist item 1]
- [Checklist item 2]
---
## Key Principles
1. **Principle 1** - Explanation
2. **Principle 2** - Explanation
```
**Command Best Practices:**
- Use clear phases with numbered steps
- Include examples and commentary
- Use $ARGUMENTS for user input
- Use $1, $2, etc. for positional arguments
- Constrain tools with `allowed-tools` when needed
- Include success checklists
- Provide inline commands with ! prefix for context (examples: !git status, !git diff)
### Step 3.4: Create Agents (if applicable)
For each agent, create a markdown file with YAML frontmatter:
```markdown
---
name: agent-name
description: When to use this agent - be specific about triggering scenarios
model: sonnet # or opus or inherit
color: green # green/yellow/red/cyan/pink for organization
tools: Glob, Grep, Read, Write # Optional tool restrictions
---
You are [specialized role]. [Core expertise and responsibility].
## Core Process
**1. [First Phase Name]**
[Phase description and goals]
**2. [Second Phase Name]**
[Phase description and goals]
**3. [Output Phase Name]**
[What to deliver and format]
## Output Guidance
Deliver [type of output] that includes:
- **Section 1**: [What to include]
- **Section 2**: [What to include]
- **Section 3**: [What to include]
[Additional guidance on tone, specificity, confidence, etc.]
```
**Agent Best Practices:**
- Clear triggering scenarios in description
- Choose appropriate model (sonnet for most, opus for complex)
- Use color coding for organization (green=safe, yellow=caution, red=critical, cyan=info, pink=creative)
- Restrict tools only when necessary for safety
- Focus on autonomous operation
- Provide clear output format expectations
- Include confidence scoring for subjective analysis
### Step 3.5: Create Hooks (if applicable)
Create hooks.json configuration:
```json
{
"description": "Hook system description",
"hooks": {
"PreToolUse": [
{
"hooks": [
{
"type": "command",
"command": "python3 ${CLAUDE_PLUGIN_ROOT}/hooks/hook_script.py"
}
],
"matcher": "Edit|Write|MultiEdit"
}
],
"PostToolUse": [
{
"hooks": [
{
"type": "command",
"command": "npx prettier --write \"$file_path\""
}
],
"matcher": "Edit|Write"
}
]
}
}
```
Create hook implementation files (Python example):
```python
#!/usr/bin/env python3
import os
import sys
import json
def main():
# Read tool use data from stdin
tool_use = json.loads(sys.stdin.read())
# Extract relevant information
tool_name = tool_use.get("name", "")
parameters = tool_use.get("parameters", {})
# Perform hook logic
# ...
# Output feedback (optional)
feedback = {
"type": "text",
"content": "Hook feedback message"
}
print(json.dumps(feedback))
# Exit with 0 for success, non-zero to block tool execution
sys.exit(0)
if __name__ == "__main__":
main()
```
**Hook Best Practices:**
- Use PreToolUse for validation and warnings
- Use PostToolUse for formatting and cleanup
- Match specific tools to avoid overhead
- Provide escape hatches (env vars to disable)
- Maintain session state to avoid repeated warnings
- Return non-zero exit codes to block dangerous operations
- Use ${CLAUDE_PLUGIN_ROOT} for plugin-relative paths
### Step 3.6: Create MCP Configuration (if applicable)
Create .mcp.json for external tool connections:
```json
{
"mcpServers": {
"server-name": {
"command": "node",
"args": ["path/to/server.js"],
"env": {
"API_KEY": "value"
}
}
}
}
```
### Step 3.7: Create README (optional but recommended)
Create a README.md in the plugin root:
```markdown
# Plugin Name
Brief description of what this plugin does.
## Installation
\`\`\`bash
# Add the marketplace
/plugin marketplace add owner/repo
# Install the plugin
/plugin install plugin-name
\`\`\`
## Features
### Commands
- \`/command-name\` - Description
### Agents
- **agent-name** - Description and when it triggers
### Hooks
- **hook-name** - Description of behavior
## Usage Examples
\`\`\`bash
/command-name argument example
\`\`\`
## Configuration
[Any required setup or configuration]
## License
[License information]
```
---
## Phase 4: Testing & Documentation
### Step 4.1: Create Marketplace Entry (if publishing)
If creating a marketplace, generate marketplace.json:
```json
{
"name": "marketplace-name",
"version": "1.0.0",
"marketplaceVersion": "1.0",
"displayName": "Marketplace Display Name",
"description": "Marketplace description",
"plugins": [
{
"name": "plugin-name",
"version": "1.0.0",
"description": "Plugin description",
"source": "./plugins/plugin-name",
"keywords": ["keyword1", "keyword2"],
"author": {
"name": "Author Name"
}
}
]
}
```
### Step 4.2: Validation Checklist
Verify the plugin is complete:
**File Structure:**
- .claude-plugin/plugin.json exists and is valid JSON
- All declared components have corresponding files
- File naming follows conventions (lowercase-with-dashes)
**Commands:**
- All commands have YAML frontmatter with description
- Commands use clear phases and steps
- $ARGUMENTS is used for user input
- Tool constraints are appropriate
**Agents:**
- All agents have complete YAML frontmatter
- Triggering scenarios are clear
- Model selection is appropriate
- Output format is specified
**Hooks:**
- hooks.json is valid JSON
- Hook scripts are executable
- Error handling is implemented
- Escape hatches exist
**Documentation:**
- README exists and is complete
- Installation instructions are clear
- Usage examples are provided
### Step 4.3: Testing Instructions
Provide testing guidance:
````markdown
## Testing Your Plugin
1. **Local Testing:**
```bash
# Create a test marketplace.json pointing to your plugin
# Add the marketplace to Claude Code
/plugin marketplace add /path/to/marketplace.json
# Install your plugin
/plugin install plugin-name
```
````
2. **Test Commands:**
- Run each command with sample arguments
- Verify expected behavior
- Check error handling
3. **Test Agents:**
- Trigger each agent scenario
- Verify autonomous operation
- Check output format
4. **Test Hooks:**
- Perform actions that trigger hooks
- Verify hook execution
- Test escape hatches
5. **Debug Mode:**
```bash
claude --debug
# Watch for plugin loading messages and errors
```
````
### Step 4.4: Summary
Provide a complete summary:
```markdown
## Plugin Creation Complete!
**Plugin:** [plugin-name]
**Version:** 1.0.0
**Location:** [path]
### Files Created:
- [list all files with descriptions]
### Next Steps:
1. **Test the plugin:**
- Install in Claude Code
- Test each component
- Verify functionality
2. **Publish (optional):**
- Push to GitHub repository
- Create marketplace.json
- Share marketplace URL
3. **Iterate:**
- Gather user feedback
- Add features
- Improve documentation
### Resources:
- Plugin docs: https://docs.claude.com/en/docs/claude-code/plugins
- Marketplace guide: https://docs.claude.com/en/docs/claude-code/plugin-marketplaces
- Plugin reference: https://docs.claude.com/en/docs/claude-code/plugins-reference
````
---
## Key Principles
1. **Learn from Examples** - Study Anthropic's official plugins for patterns
2. **Start Simple** - Create minimal viable plugin first, then iterate
3. **Clear Triggering** - Make it obvious when commands/agents should be used
4. **Constrain Appropriately** - Use tool restrictions to prevent scope creep
5. **Document Thoroughly** - README and inline docs are essential
6. **Test Extensively** - Verify each component before publishing
7. **Follow Conventions** - Naming, structure, and patterns matter
8. **Version Semantically** - Use semantic versioning for clarity
---
## Pattern Reference
### Command Patterns
- **Workflow Commands** - Multi-phase processes (create-plugin, feature-dev)
- **Git Commands** - Version control operations (commit, clean_gone)
- **Interactive Commands** - Ask questions, then execute (new-sdk-app)
### Agent Patterns
- **Analyzer Agents** - Code review, testing, security (code-reviewer, pr-test-analyzer)
- **Explorer Agents** - Codebase discovery (code-explorer)
- **Builder Agents** - Architecture, design (code-architect)
- **Verifier Agents** - Validation, compliance (agent-sdk-verifier)
### Hook Patterns
- **Validation Hooks** - Check before actions (security warnings)
- **Formatting Hooks** - Auto-format after edits (prettier, linters)
- **Logging Hooks** - Track actions (audit trails)
- **Protection Hooks** - Prevent dangerous operations (file protection)
---
## Common Pitfalls to Avoid
1. **Missing plugin.json** - This file is REQUIRED
2. **Invalid JSON** - Use linters to validate JSON files
3. **Unclear Triggers** - Agents need specific triggering scenarios
4. **Tool Overload** - Don't grant unnecessary tool access
5. **Poor Documentation** - Users need clear usage examples
6. **No Error Handling** - Hooks should handle failures gracefully
7. **Hardcoded Paths** - Use ${CLAUDE_PLUGIN_ROOT} for plugin-relative paths
8. **Complex First Version** - Start minimal, iterate based on feedback