📦 deps(thirdparty): update snapshots

This commit is contained in:
ci[bot]
2026-05-29 08:33:53 +00:00
parent fdb52f1e96
commit 06e0d13d57
1615 changed files with 232858 additions and 0 deletions
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,395 @@
---
name: claude-agents
description: This skill should be used when creating agents, writing agent frontmatter, configuring subagents, or when "create agent", "agent.md", "subagent", or "Task tool" are mentioned.
metadata:
version: "1.0.0"
related-skills:
- skills-dev
- claude-plugins
- claude-hooks
---
# Claude Agent Development
Create and validate specialized subagents that extend Claude Code with focused expertise.
## Agents vs Skills
**Critical distinction**:
| Aspect | Agents (This Skill) | Skills |
| -------------- | ------------------------------------------- | -------------------------------------- |
| **Purpose** | Specialized subagents with focused expertise | Capability packages with instructions |
| **Invocation** | Task tool (`subagent_type` parameter) | Automatic (model-triggered by context) |
| **Location** | `agents/` directory | `skills/` directory |
| **Structure** | Single `.md` file with frontmatter | Directory with `SKILL.md` + resources |
See [agent-vs-skill.md](references/agent-vs-skill.md) for details.
## Quick Start
### Using Templates
Copy a template from `templates/`:
| Template | Use When |
| ----------------- | -------------------------------------------- |
| `basic.md` | Simple agents with focused expertise |
| `advanced.md` | Full-featured agents with all config options |
### Scaffolding
```bash
./scripts/scaffold-agent.sh security-reviewer -t reviewer
```
## Workflow Overview
1. **Discovery** - Define purpose, scope, and triggers
2. **Design** - Choose archetype and configuration
3. **Implementation** - Write frontmatter and instructions
4. **Validation** - Verify against quality standards
---
## Stage 1: Discovery
Before writing code, clarify:
- **Purpose**: What specialized expertise does this agent provide?
- **Triggers**: What keywords/phrases should invoke it?
- **Scope**: What does it do? What does it NOT do?
- **Location**: Personal (`~/.claude/agents/`), project (`agents/`), or plugin?
**Key questions**:
- Is this a specialized role or a general capability? (Role = agent, Capability = skill)
- What user phrases should trigger this agent?
- What tools does it need access to?
---
## Stage 2: Design
### Agent Archetypes
| Type | Purpose | Typical Tools |
|------|---------|---------------|
| **Analyzer** | Examine without modifying | `Glob, Grep, Read, Skill, Task, TaskCreate, TaskUpdate, TaskList, TaskGet` |
| **Implementer** | Build and modify code | Full access (inherit) |
| **Reviewer** | Provide feedback | `Glob, Grep, Read, Skill, Task, TaskCreate, TaskUpdate, TaskList, TaskGet` |
| **Tester** | Create and manage tests | `Glob, Grep, Read, Write, Edit, Bash, ...` |
| **Researcher** | Find and synthesize info | `..., WebSearch, WebFetch` |
| **Deployer** | Handle infrastructure | `..., Bash(kubectl *), Bash(docker *)` |
See [agent-types.md](references/agent-types.md) for details.
### Frontmatter Schema
```yaml
---
name: agent-name # Required: kebab-case, matches filename
description: | # Required: when to use + triggers + examples
Use this agent when [conditions]. Triggers on [keywords].
<example>
Context: [Situation]
user: "[User message]"
assistant: "I'll use the agent-name agent to [action]."
</example>
model: inherit # Optional: inherit|haiku|sonnet|opus
tools: Glob, Grep, Read # Optional: restrict tools (default: inherit all)
skills: tdd, debugging # Optional: skills to auto-load (NOT inherited)
permissionMode: default # Optional: default|acceptEdits|bypassPermissions
---
```
See [frontmatter.md](references/frontmatter.md) for complete schema.
### Model Selection
| Model | When to Use |
|-------|-------------|
| `inherit` | Recommended default - adapts to parent context |
| `haiku` | Fast exploration, simple tasks, low-latency |
| `sonnet` | Balanced cost/capability (default if omitted) |
| `opus` | Nuanced judgment, security/architecture review, irreversible decisions |
### Tool Configuration
**Philosophy**: Don't over-restrict. Only limit tools when there's a specific safety reason.
**Baseline** (always include when restricting):
```yaml
tools: Glob, Grep, Read, Skill, Task, TaskCreate, TaskUpdate, TaskList, TaskGet
```
See [tools.md](references/tools.md) for patterns.
---
## Stage 3: Implementation
### Agent File Structure
```markdown
---
name: security-reviewer
description: |
Use this agent for security vulnerability detection.
Triggers on security audits, OWASP, injection, XSS.
<example>
Context: User wants security review.
user: "Review auth code for vulnerabilities"
assistant: "I'll use the security-reviewer agent."
</example>
model: inherit
---
# Security Reviewer
You are a security expert specializing in [expertise].
## Expertise
- Domain expertise 1
- Domain expertise 2
## Process
### Step 1: [Stage Name]
- Action item
- Action item
### Step 2: [Stage Name]
- Action item
## Output Format
For each finding:
- **Severity**: critical|high|medium|low
- **Location**: file:line
- **Issue**: Description
- **Remediation**: How to fix
## Constraints
**Always:**
- Required behavior
**Never:**
- Prohibited action
```
### Description Guidelines
Descriptions are the most critical field for agent discovery:
1. **Start with trigger conditions**: "Use this agent when..."
2. **Include 3-5 trigger keywords**: specific terms users would say
3. **Add 2-3 examples**: showing user request -> assistant delegation
4. **Be specific**: avoid vague descriptions like "helps with code"
### Best Practices
**Single Responsibility**
```yaml
# Good: Focused
description: SQL injection vulnerability detector
# Bad: Too broad
description: Security expert handling all issues
```
**Document Boundaries**
```markdown
## What I Don't Do
- I analyze, not implement fixes
- I review, not build from scratch
```
**Consistent Output Format**
Define structured output so results are predictable and parseable.
---
## Stage 4: Validation
After creating an agent, validate against these checklists.
### YAML Frontmatter Checks
- [ ] Opens with `---` on line 1
- [ ] Closes with `---` before content
- [ ] `name` present and matches filename (without `.md`)
- [ ] `description` present and non-empty
- [ ] Uses spaces (not tabs) for indentation
- [ ] `tools` uses comma-separated valid tool names
- [ ] `model` is valid: `sonnet`, `opus`, `haiku`, or `inherit`
### Naming Conventions
- [ ] Kebab-case (lowercase-with-hyphens)
- [ ] Follows `[role]-[specialty]` or `[specialty]` pattern
- [ ] Specific, not generic
- [ ] Concise (1-3 words, max 4)
**Good**: `code-reviewer`, `test-runner`, `security-auditor`
**Bad**: `helper`, `my-agent`, `the-best-agent`
### Description Quality
- [ ] **WHAT**: Explains what the agent does
- [ ] **WHEN**: States when to invoke it
- [ ] **TRIGGERS**: Includes 3-5 trigger keywords
- [ ] **EXAMPLES**: Has 2-3 example conversations
- [ ] Specific about agent's purpose (not vague)
- [ ] Clear about scope
**Anti-patterns**:
- "Helps with code" - too vague
- No trigger conditions
- Missing keywords
### System Prompt Quality
- [ ] Clear role definition
- [ ] Step-by-step process
- [ ] Key practices or guidelines
- [ ] Output format specification
- [ ] Specific and actionable instructions
- [ ] Constraints (what NOT to do)
- [ ] Single responsibility focus
**Anti-patterns**:
- "You are helpful" - too vague
- No process defined
- Missing constraints
- Scope creep
### Tool Configuration
- [ ] Field name is `tools:` (not `allowed-tools:`)
- [ ] Comma-separated list
- [ ] Tool names correctly spelled and case-sensitive
- [ ] Includes baseline tools if restricting: `Glob, Grep, Read, Skill, Task, TaskCreate, TaskUpdate, TaskList, TaskGet`
- [ ] Tools appropriate for agent's purpose
**Common patterns**:
```yaml
# Read-only
tools: Glob, Grep, Read, Skill, Task, TaskCreate, TaskUpdate, TaskList, TaskGet
# Read-only + git
tools: Glob, Grep, Read, Skill, Task, TaskCreate, TaskUpdate, TaskList, TaskGet, Bash(git show:*), Bash(git diff:*)
# Research
tools: Glob, Grep, Read, Skill, Task, TaskCreate, TaskUpdate, TaskList, TaskGet, WebSearch, WebFetch
# Full access
# (omit field to inherit all)
```
### Validation Report Format
```markdown
# Agent Validation Report: [Agent Name]
## Summary
- **Status**: PASS | FAIL | WARNINGS
- **Location**: [path]
- **Issues**: [count critical] / [count warnings]
## Critical Issues (must fix)
1. [Issue with specific fix]
## Warnings (should fix)
1. [Issue with specific fix]
## Strengths
- [What's done well]
```
---
## Agent Scopes
| Scope | Location | Priority | Visibility |
|-------|----------|----------|------------|
| Project | `agents/` | Highest | Team via git |
| Personal | `~/.claude/agents/` | Medium | You only |
| Plugin | `<plugin>/agents/` | Lowest | Plugin users |
Project agents override personal agents with the same name.
---
## Testing Agents
### Manual Testing
1. Create agent file in `agents/`
2. In Claude Code: "Use the [agent-name] agent to [task]"
3. Claude invokes via Task tool
4. Review results
### Verify Discovery
Agents are loaded from:
- `~/.claude/agents/` (personal)
- `./agents/` (project)
- Plugins (installed)
Debug with: `claude --debug`
---
## Troubleshooting
### Agent Not Being Invoked
- Check file location: `agents/agent-name.md`
- Validate YAML frontmatter syntax
- Make description more specific with trigger keywords
- Add example conversations
### Wrong Agent Invoked
- Make description more distinct
- Add specific trigger keywords
- Include negative examples (what NOT to use it for)
### Agent Has Wrong Tools
Prefer `model: inherit` to use parent's tool access. Only specify `tools:` when agent needs different access.
---
## References
| Reference | Content |
|-----------|---------|
| [agent-vs-skill.md](references/agent-vs-skill.md) | Agents vs Skills distinction |
| [frontmatter.md](references/frontmatter.md) | YAML schema and fields |
| [tools.md](references/tools.md) | Tool configuration patterns |
| [task-tool.md](references/task-tool.md) | Task tool integration |
| [discovery.md](references/discovery.md) | How agents are found and loaded |
| [agent-types.md](references/agent-types.md) | Archetypes: analysis, implementation, etc. |
| [patterns.md](references/patterns.md) | Best practices and multi-agent patterns |
| [tasks.md](references/tasks.md) | Task tool patterns for agents |
| [advanced-features.md](references/advanced-features.md) | Resumable agents, CLI config |
See [EXAMPLES.md](EXAMPLES.md) for complete real-world agent examples.
See `templates/` for starter templates.
---
## Related Skills
- **skills-development**: Create Skills (different from agents)
- **claude-plugin-development**: Bundle agents into plugins
@@ -0,0 +1,155 @@
# Advanced Agent Features
Advanced capabilities for agent configuration and usage.
## Resumable Agents
Agents can be resumed to continue previous conversations across multiple invocations.
### How It Works
1. Each agent execution returns a unique `agentId`
2. Agent conversation stored in separate transcript: `agent-{agentId}.jsonl`
3. Resume via `resume` parameter with the `agentId`
4. Agent continues with full context from previous conversation
### Example Workflow
```
> Use the code-analyzer agent to start reviewing the authentication module
[Agent completes initial analysis and returns agentId: "abc123"]
> Resume agent abc123 and now analyze the authorization logic as well
[Agent continues with full context from previous conversation]
```
### Programmatic Usage
```json
{
"description": "Continue analysis",
"prompt": "Now examine the error handling patterns",
"subagent_type": "code-analyzer",
"resume": "abc123"
}
```
### Use Cases
- **Long-running research**: Break complex analysis into multiple sessions
- **Iterative refinement**: Continue improving without losing context
- **Multi-step workflows**: Sequential tasks that build on previous context
## CLI Agent Configuration
Define agents dynamically via CLI for testing or automation.
### `--agents` Flag
```bash
claude --agents '{
"code-reviewer": {
"description": "Expert code reviewer. Use proactively after code changes.",
"prompt": "You are a senior code reviewer. Focus on code quality, security, and best practices.",
"tools": ["Read", "Grep", "Glob", "Bash"],
"model": "sonnet"
}
}'
```
### Priority
CLI-defined agents have lower priority than project-level but higher than user-level:
1. Project (`.claude/agents/`) — Highest
2. CLI (`--agents`) — Medium
3. User (`~/.claude/agents/`) — Lower
4. Plugin — Lowest
### Use Cases
- Quick testing of agent configurations before committing
- Session-specific agents that don't need to persist
- Automation scripts with custom agents
- Sharing agent definitions in documentation
## Built-in Agents
Claude Code includes built-in agents you should understand before creating custom agents.
### General-purpose Agent
- **Model**: Sonnet
- **Tools**: All tools
- **Mode**: Read and write, execute commands
- **Purpose**: Complex research, multi-step operations, code modifications
**When used:**
- Tasks requiring both exploration AND modification
- Complex reasoning across multiple files
- When multiple strategies may be needed
### Plan Agent
- **Model**: Sonnet
- **Tools**: Read, Glob, Grep, Bash (exploration only)
- **Purpose**: Research during plan mode
**When used:**
- Automatically in plan mode when Claude needs to research codebase
- Only used in plan mode (prevents infinite nesting)
### Explore Agent
- **Model**: Haiku (fast, low-latency)
- **Mode**: Strictly read-only
- **Tools**: Glob, Grep, Read, Bash (read-only commands only)
- **Purpose**: Fast file discovery and code exploration
**Thoroughness levels:**
- `quick` — Basic searches
- `medium` — Moderate exploration
- `very thorough` — Comprehensive analysis
### When to Create Custom vs Use Built-in
**Use built-in agents when:**
- Task is general code exploration (Explore)
- Task is general implementation (General-purpose)
- You're in plan mode (Plan)
**Create custom agents when:**
- You need specialized domain expertise
- You want consistent output formats
- You need specific tool restrictions
- You want proactive invocation based on keywords
## Proactive Invocation
To encourage automatic agent use, include trigger phrases in descriptions:
```yaml
description: |
Use this agent PROACTIVELY after any code changes for security review.
MUST BE USED when authentication or authorization code is modified.
```
**Effective phrases:**
- "Use PROACTIVELY"
- "MUST BE USED when..."
- "Automatically invoke for..."
## Agent Chaining
Explicit user-facing syntax for chaining agents:
```
> First use the code-analyzer agent to find performance issues,
then use the optimizer agent to fix them
```
Claude will:
1. Invoke code-analyzer agent
2. Collect results
3. Invoke optimizer agent with context from first agent
4. Return combined results
@@ -0,0 +1,126 @@
# Agent Types
Common agent archetypes and their characteristics.
## Analysis Agents
**Purpose:** Examine and report without modifying.
**Characteristics:**
- Read-only operations
- Detailed reporting
- Recommendations, no implementation
- Metrics and measurements
**Example tasks:** "Analyze performance", "Find memory leaks", "Review bundle size"
```yaml
tools: Glob, Grep, Read, Skill, Task, TaskCreate, TaskUpdate, TaskList, TaskGet
```
## Implementation Agents
**Purpose:** Build and modify code.
**Characteristics:**
- Creates/modifies code
- Follows templates and patterns
- Implements specifications
**Example tasks:** "Create component", "Implement feature", "Build API endpoint"
```yaml
# Usually inherit full access (no tools field)
```
## Review Agents
**Purpose:** Provide feedback and suggestions.
**Characteristics:**
- Evaluates existing code
- Specific, actionable feedback
- Rates/scores quality
- Suggests improvements
**Example tasks:** "Review this PR", "Check code quality", "Evaluate architecture"
```yaml
tools: Glob, Grep, Read, Skill, Task, TaskCreate, TaskUpdate, TaskList, TaskGet
```
## Testing Agents
**Purpose:** Create and manage tests.
**Characteristics:**
- Generates test code
- Runs test suites
- Analyzes coverage
- Identifies gaps
**Example tasks:** "Create tests for X", "Improve coverage", "Add edge case tests"
```yaml
tools: Glob, Grep, Read, Write, Edit, Bash, Skill, Task, TaskCreate, TaskUpdate, TaskList, TaskGet
```
## Migration Agents
**Purpose:** Transform code from one form to another.
**Characteristics:**
- Systematic transformation
- Preserves functionality
- Gradual approach
- Validation at each step
**Example tasks:** "Migrate to TypeScript", "Update to new API", "Refactor to pattern"
```yaml
tools: Glob, Grep, Read, Write, Edit, Skill, Task, TaskCreate, TaskUpdate, TaskList, TaskGet
```
## Research Agents
**Purpose:** Find information and synthesize knowledge.
**Characteristics:**
- Information gathering
- Source verification
- Synthesis and summary
- Citation and linking
**Example tasks:** "Research how to X", "Find examples of Y", "Best practice for Z"
```yaml
tools: Glob, Grep, Read, Skill, Task, TaskCreate, TaskUpdate, TaskList, TaskGet, WebSearch, WebFetch
```
## Deployment Agents
**Purpose:** Handle deployment and infrastructure.
**Characteristics:**
- Infrastructure operations
- Deployment procedures
- Safety checks
- Monitoring integration
**Example tasks:** "Deploy to staging", "Rollback deployment", "Check cluster health"
```yaml
tools: Glob, Grep, Read, Skill, Task, TaskCreate, TaskUpdate, TaskList, TaskGet, Bash(kubectl *), Bash(docker *)
```
## Choosing an Archetype
```
Need to examine without changing? → Analysis
Need to build or modify code? → Implementation
Need to evaluate and give feedback? → Review
Need to create or run tests? → Testing
Need to transform existing code? → Migration
Need to gather external information? → Research
Need to manage infrastructure? → Deployment
```
@@ -0,0 +1,57 @@
# Agent vs Skill
Critical distinction—agents and skills serve different purposes.
## Comparison
| Aspect | Agents | Skills |
|--------|--------|--------|
| **Location** | `agents/*.md` | `skills/*/SKILL.md` |
| **Structure** | Single markdown file | Directory with resources |
| **Invocation** | Explicit via Task tool | Automatic via context |
| **Parameter** | `subagent_type` in Task | N/A |
| **Scope** | Narrow, specialized | Broad capability |
| **Trigger** | "Use X agent to..." | Automatic on keywords |
| **Context** | Separate conversation | Main conversation |
## When to Use Agents
- Specialized expertise for specific task types
- Task requires separate context/conversation thread
- Compartmentalized work (security review, testing)
- Narrow specialization that shouldn't pollute main context
- Clear handoff between roles (review → implement → test)
## When to Use Skills
- Capabilities available throughout conversation
- Expertise applies to many task types
- Claude autonomously decides when to use it
- Capability is a tool/technique, not a role
- Resources (scripts, templates) need bundling
## Combined Usage
Use both together for layered capability:
```
# Skill: code-review (capability)
skills/code-review/SKILL.md
- Provides review techniques
- Available in all conversations
- Claude uses when reviewing
# Agent: security-reviewer (specialized role)
agents/security-reviewer.md
- Uses review techniques from skill
- Focused exclusively on security
- Invoked for security-specific reviews
```
## Quick Decision
```
Need specialized expertise for one task type? → Agent
Need capability across many task types? → Skill
Need both focused role AND broad technique? → Both
```
@@ -0,0 +1,94 @@
# Agent Discovery & Loading
How Claude finds and loads agents.
## Loading Order
1. **Scan directories:**
- Plugin agents: `<plugin>/agents/*.md`
- Project agents: `<project>/agents/*.md`
- Personal agents: `~/.claude/agents/*.md`
2. **Parse frontmatter:**
- Validate YAML syntax
- Extract description, tools
- Build agent registry
3. **Priority resolution:**
- Personal > Project > Plugin
- Same name: higher priority wins
## Discovery Process
**How Claude matches agents to requests:**
1. **Parse user intent** — identify task type, extract keywords
2. **Match descriptions** — compare request with agent descriptions
3. **Rank by relevance** — score matches, consider tool requirements
4. **Select best match** — invoke via Task tool
## Naming for Discovery
Good descriptions contain keywords users naturally say:
```yaml
# ✅ Good: Keywords + examples
description: |
React testing specialist using Jest and React Testing Library.
Triggers on component testing, Jest test creation, or RTL usage.
<example>
Context: User wants to test a React component
user: "Write tests for the UserProfile component"
assistant: "I'll use the react-tester agent to create tests."
</example>
# Keywords: react, testing, jest, react testing library
# Triggers: "test react component", "jest tests", "RTL"
# ❌ Bad: Vague, no examples
description: Testing helper
```
## Trigger Keywords
Include terms users naturally say:
- **Action verbs:** review, check, audit, analyze, test, build, fix
- **Domain terms:** security, performance, auth, API, database
- **Technologies:** GraphQL, JWT, PostgreSQL, React, TypeScript
## Debug Discovery
```bash
# Enable debug mode
claude --debug
# Look for:
# "Loading agent: security-reviewer"
# "Agent match score: X"
# "Invoking agent: security-reviewer"
```
## Reload Agents
```bash
# Changes detected automatically
# Force reload:
/clear
# Or restart Claude Code
```
## Common Issues
**Agent not being invoked:**
- Check file location: `agents/agent-name.md`
- Validate YAML frontmatter syntax
- Make description more specific with trigger keywords
- Add example conversations
**Wrong agent invoked:**
- Make description more distinct
- Add specific trigger keywords
- Include negative examples (what NOT to use it for)
@@ -0,0 +1,207 @@
# Agent Frontmatter
YAML frontmatter schema for agent files.
## Required Fields
### `name`
Agent identifier. Should match filename without `.md`.
```yaml
name: security-reviewer
```
### `description`
When to use + trigger keywords + examples. Most critical field for discovery.
**Format:**
```yaml
description: |
Use this agent when [trigger conditions]. Triggers on [keywords].
<example>
Context: [Situation]
user: "[User message]"
assistant: "[Claude's delegation response]"
</example>
```
**Checklist:**
- Starts with "Use this agent when..."
- Includes 3-5 trigger keywords
- Has 3-4 examples covering: typical use, edge case, verb triggers
- Specific, not vague
**Example:**
```yaml
description: |
Use this agent for security vulnerability detection in code.
Triggers on security audits, OWASP, injection, XSS, auth review.
<example>
Context: User wants security review.
user: "Review this auth code for vulnerabilities"
assistant: "I'll use the security-reviewer agent to analyze for security issues."
</example>
<example>
Context: User mentions specific vulnerability type.
user: "Check for SQL injection in the user service"
assistant: "I'll delegate to the security-reviewer agent for SQL injection analysis."
</example>
```
## Optional Fields
### `model`
Model selection. Default: `sonnet` (NOT inherited automatically).
```yaml
model: inherit # Use parent's model (recommended)
model: haiku # Fast/cheap - simple tasks, quick exploration
model: sonnet # Balanced - standard tasks (default if omitted)
model: opus # Complex reasoning, high-stakes decisions
```
**Guidance:**
- `inherit` — Recommended default. Adapts to parent's model context
- `haiku` — Fast exploration, simple pattern matching, low-latency
- `sonnet` — Good default. Balanced cost/capability
- `opus` — Deeper reasoning, higher quality output, complex analysis
**When to use `opus`:** Nuanced judgment, multi-step reasoning, security/architecture review, complex refactoring, irreversible decisions, when quality matters more than speed.
**When `sonnet` is fine:** Straightforward implementation, standard review, test generation, docs.
### `skills`
Skills to auto-load. **Critical:** Subagents do NOT inherit skills from parent.
```yaml
skills: tdd, debugging, type-safety
```
If your agent needs specific skills, you must explicitly list them here.
### `permissionMode`
Control permission handling for automation scenarios.
```yaml
permissionMode: default # Standard permission handling
permissionMode: acceptEdits # Auto-accept edit operations
permissionMode: bypassPermissions # Skip permission prompts entirely
permissionMode: plan # Planning mode permissions
```
Use `acceptEdits` or `bypassPermissions` for CI/CD or batch processing agents.
### `tools`
Restrict tool access. Default: inherits full access from parent.
```yaml
# Read-only analysis
tools: Glob, Grep, Read, Skill, Task, TaskCreate, TaskUpdate, TaskList, TaskGet
# With git history
tools: Glob, Grep, Read, Skill, Task, TaskCreate, TaskUpdate, TaskList, TaskGet, Bash(git show:*), Bash(git diff:*)
# Research agent
tools: Glob, Grep, Read, Skill, Task, TaskCreate, TaskUpdate, TaskList, TaskGet, WebSearch, WebFetch
```
See [tools.md](tools.md) for detailed patterns.
### `color`
Status line color for this agent.
```yaml
color: orange
```
## File Naming
- Kebab-case: `security-reviewer.md`, `api-tester.md`
- No spaces or special characters
- Extension must be `.md`
- Filename = agent identifier
```
agents/security-reviewer.md → subagent_type: "security-reviewer"
agents/db-migrator.md → subagent_type: "db-migrator"
```
## File Locations
| Scope | Path | Priority |
|-------|------|----------|
| Project | `.claude/agents/` | Highest |
| Personal | `~/.claude/agents/` | Medium |
| Plugin | `<plugin>/agents/` | Lowest |
Project-level agents take precedence over personal agents. This allows team-specific agents to override personal defaults.
## Minimal Example
```markdown
---
name: code-formatter
description: |
Use this agent for code formatting tasks.
<example>
Context: User wants code formatted.
user: "Format the utils module"
assistant: "I'll use the code-formatter agent."
</example>
model: inherit
---
# Code Formatter
Format code according to project style guide.
```
## Standard Example
```markdown
---
name: auth-security-reviewer
description: |
Use this agent when reviewing authentication implementations.
Triggers on auth flow review, token security, session management.
<example>
Context: User wants auth code reviewed.
user: "Review the login flow for security issues"
assistant: "I'll use the auth-security-reviewer agent."
</example>
<example>
Context: User mentions specific auth concern.
user: "Check our JWT token handling"
assistant: "I'll delegate to the auth-security-reviewer agent."
</example>
model: inherit
---
# Authentication Security Reviewer
## Expertise
- OAuth 2.0 and OIDC
- JWT tokens
- Session management
## Process
1. Analyze authentication flow
2. Check token handling
3. Verify session security
4. Report findings with severity
```
@@ -0,0 +1,191 @@
# Agent Patterns & Best Practices
Design patterns and quality guidelines.
## Best Practices
### Single Responsibility
```yaml
# ✅ Focused
description: SQL injection vulnerability detector
# ❌ Too broad
description: Security expert for all issues
```
**Why:** Easier to invoke correctly and maintain.
### Clear Boundaries
```markdown
## Scope
**I handle:**
- ✅ Security vulnerability detection
- ✅ Secure coding recommendations
**I don't handle:**
- ❌ Implementation of fixes
- ❌ Performance optimization
```
**Why:** Prevents confusion, improves invocation accuracy.
### Consistent Output
```markdown
## Output Format
**For each finding:**
- Severity: critical|high|medium|low
- Location: file:line
- Description: What's vulnerable
- Remediation: How to fix
```
**Why:** Predictable, parseable results.
### Safety First
```markdown
## Safety Protocol
Before modifying production:
1. ✅ Backup verified
2. ✅ Tested in staging
3. ✅ Rollback plan ready
4. ⚠️ Get explicit approval
```
**Why:** Prevents accidents and data loss.
### Document Examples
```markdown
## Example Tasks
**Good:**
- "Review auth.service.ts for security issues"
- "Check JWT implementation"
**Not ideal:**
- "Review everything" (too broad)
- "Fix bugs" (not my role)
```
**Why:** Helps users work effectively with agent.
## Multi-Agent Patterns
### Sequential Processing
```
User: "Prepare this code for production"
1. Security Agent → Issues found
2. Fixer Agent → Code updated
3. Test Agent → Tests created
4. Quality Agent → Approved
```
**When:** Steps depend on previous results.
### Parallel Review
```
User: "Comprehensive code review"
┌─ Security Agent → Security report
├─ Performance Agent → Performance report
├─ Quality Agent → Quality report
└─ Test Agent → Coverage report
Aggregate → User
```
**When:** Independent reviews, faster results.
### Specialist Consultation
```
Main Claude implementing feature
Question about security pattern
Task(security-expert, "Best pattern for X?")
Answer received
Continue implementation
```
**When:** Need expert input mid-task.
### Iterative Refinement
```
1. Implementation Agent → Creates initial
2. Review Agent → Finds issues
3. Implementation Agent → Fixes
4. Review Agent → Verifies
5. Repeat until approved
```
**When:** High-quality requirements.
## Anti-Patterns
### Over-Restriction
```yaml
# ❌ Unnecessary restriction
tools: Read # Can't even search!
# ✅ Appropriate baseline
tools: Glob, Grep, Read, Skill, Task, TaskCreate, TaskUpdate, TaskList, TaskGet
```
### Vague Description
```yaml
# ❌ Hard to invoke
description: Helps with code stuff
# ✅ Clear triggers
description: |
SQL injection detector for user input handling.
Triggers on query security, input validation, parameterization.
```
### Missing Examples
```yaml
# ❌ No examples
description: Security reviewer
# ✅ With examples
description: |
Security reviewer for authentication code.
<example>
user: "Check the login flow"
assistant: "I'll use security-reviewer agent."
</example>
```
### Scope Creep
```markdown
# ❌ Does too much
- Reviews code
- Fixes issues
- Writes tests
- Deploys changes
- Monitors production
# ✅ Focused
- Reviews code for security issues
- Reports findings with severity
- Suggests remediation
```
@@ -0,0 +1,109 @@
# Performance Considerations
Optimizing agent efficiency and resource usage.
## Cost Factors
- Agent loading time
- Context switching overhead
- Tool invocations
- Model inference
## Optimization Strategies
### Right-Size Models
```yaml
# ❌ Heavyweight for simple task
model: opus
# Task: Format code
# ✅ Appropriate
model: haiku # or inherit
```
### Focused Descriptions
```yaml
# ❌ Too many triggers (slow matching)
description: Does everything related to code...
# ✅ Focused (fast matching)
description: |
SQL injection detector. Triggers on
SQL security, injection detection, query validation.
```
### Minimal Context
```json
// ❌ Too much context
{
"task": "Review code",
"context": ["@entire-codebase", "All git history"]
}
// ✅ Focused context
{
"task": "Review authentication code",
"context": ["@src/auth/auth.service.ts", "Focus on JWT validation"]
}
```
### Sequential Over Parallel
```
// ❌ Parallel (multiple agent contexts)
- Security agent reviewing
- Performance agent reviewing
- Quality agent reviewing
// ✅ Sequential (one at a time)
1. Security agent → results
2. Performance agent → results
3. Quality agent → results
```
**Why:** Lower memory overhead, clearer results.
## Caching
Agents benefit from prompt caching:
- Description and instructions cached
- Repeated invocations faster
- Tool restrictions cached
**Maximize caching:**
- Keep agent instructions stable
- Don't dynamically generate agent content
- Reuse agents frequently
## Tool Philosophy
```yaml
# Default: inherit (don't over-specify)
model: inherit
# If restricting, use baseline + needed extras
tools: Glob, Grep, Read, Skill, Task, TaskCreate, TaskUpdate, TaskList, TaskGet, WebSearch
# Full bash when needed (simpler than Bash(*))
tools: Glob, Grep, Read, Skill, Task, TaskCreate, TaskUpdate, TaskList, TaskGet, Bash
```
## Context Size Guidelines
| Agent Type | Typical Context | Max Recommended |
|------------|-----------------|-----------------|
| Quick review | 1-3 files | 5 files |
| Standard review | 3-10 files | 20 files |
| Deep analysis | Full module | 50 files |
| Research | Varies | Focused queries |
## Latency vs Quality Tradeoffs
| Priority | Model | Context | Use Case |
|----------|-------|---------|----------|
| Speed | haiku | Minimal | Quick checks |
| Balance | sonnet/inherit | Moderate | Standard work |
| Quality | opus | Full | Critical analysis |
@@ -0,0 +1,353 @@
# Task Tool Integration
How agents are invoked and orchestrated via the Task tool.
## Basic Invocation
From main conversation, Claude uses Task tool:
```json
{
"description": "Security review of auth code",
"prompt": "Review authentication code for security vulnerabilities",
"subagent_type": "security-reviewer"
}
```
## Parameters
| Parameter | Required | Purpose |
|-----------|----------|---------|
| `description` | Yes | Short summary (3-5 words) of what agent will do |
| `prompt` | Yes | Detailed instructions for the agent |
| `subagent_type` | Yes | Agent identifier (see naming below) |
| `resume` | No | Agent ID to resume a previous conversation |
| `model` | No | Override model for this invocation |
| `run_in_background` | No | Run agent asynchronously |
## Agent Naming
The `subagent_type` format depends on agent source:
| Source | Format | Example |
|--------|--------|---------|
| Built-in | `name` | `Explore`, `Plan`, `general-purpose` |
| Same plugin | `name` | `security-reviewer` (file: `agents/security-reviewer.md`) |
| Other plugin | `plugin:name` | `outfitter:reviewer`, `outfitter:quartermaster` |
**Note**: Examples in this file use short names assuming agents are in the same plugin. When invoking plugin agents from outside, use the `plugin:name` format.
## Invocation Examples
**Basic:**
```json
{
"description": "Review auth code",
"prompt": "Review this authentication code for security issues",
"subagent_type": "security-reviewer"
}
```
**Detailed prompt:**
```json
{
"description": "Generate auth tests",
"prompt": "Generate unit tests for the authentication service in src/auth/. Target 90% coverage. Focus on edge cases and error handling. Use existing patterns from tests/.",
"subagent_type": "testing-specialist"
}
```
**With previous context:**
```json
{
"description": "Fix security issues",
"prompt": "Fix the security issues found in the previous review: SQL injection in user query, XSS vulnerability in profile page",
"subagent_type": "security-fixer"
}
```
## Resumable Agents
Agents can be resumed to continue previous conversations:
```json
{
"description": "Continue analysis",
"prompt": "Now examine the error handling patterns",
"subagent_type": "code-analyzer",
"resume": "abc123"
}
```
**How it works:**
- Each agent execution returns a unique `agentId`
- Agent conversation stored in separate transcript
- Use `resume` parameter with the `agentId` to continue
- Agent resumes with full context from previous conversation
**Use cases:**
- Long-running research broken into multiple sessions
- Iterative refinement without losing context
- Multi-step workflows with sequential context
## Background Execution
Run agents asynchronously while continuing other work. Essential for parallel workflows.
### When to Use Background Execution
| Scenario | Background? | Rationale |
|----------|-------------|-----------|
| Independent parallel reviews | Yes | No dependencies, faster completion |
| Sequential pipeline | No | Each step needs previous result |
| Long-running analysis while user waits | Yes | Can work on other tasks meanwhile |
| Quick consultation mid-task | No | Need immediate answer to continue |
### Launching Background Agents
Set `run_in_background: true` in the Task tool call:
```json
{
"description": "Security review (background)",
"prompt": "Review authentication code for vulnerabilities",
"subagent_type": "security-reviewer",
"run_in_background": true
}
```
The Task tool returns immediately with a `task_id` instead of waiting for completion.
### Retrieving Results with TaskOutput
Use the `TaskOutput` tool to get results from background agents:
```json
{
"task_id": "abc123",
"block": true,
"timeout": 30000
}
```
**Parameters:**
| Parameter | Default | Purpose |
|-----------|---------|---------|
| `task_id` | Required | ID returned when launching background agent |
| `block` | `true` | Wait for completion (`true`) or check status (`false`) |
| `timeout` | `30000` | Max wait time in milliseconds (up to 600000) |
**Blocking mode** (`block: true`): Waits until agent completes or timeout.
**Non-blocking mode** (`block: false`): Returns current status immediately, useful for polling.
### Parallel Execution Pattern
Launch multiple agents in a single message, then collect results:
```
┌─────────────────────────────────────────────────────────────────┐
│ Step 1: Launch all agents in parallel (single message) │
├─────────────────────────────────────────────────────────────────┤
│ Task(security-reviewer, run_in_background: true) → task_id_1 │
│ Task(performance-analyzer, run_in_background: true) → task_id_2│
│ Task(quality-reviewer, run_in_background: true) → task_id_3 │
└─────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────┐
│ Step 2: Collect results (can work on other tasks meanwhile) │
├─────────────────────────────────────────────────────────────────┤
│ TaskOutput(task_id_1, block: true) → security findings │
│ TaskOutput(task_id_2, block: true) → performance findings │
│ TaskOutput(task_id_3, block: true) → quality findings │
└─────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────┐
│ Step 3: Aggregate and synthesize results │
└─────────────────────────────────────────────────────────────────┘
```
### Example: Comprehensive Code Review
```json
// Launch three reviewers in parallel (single message with multiple tool calls)
[
{
"description": "Security review",
"prompt": "Review src/auth/ for security vulnerabilities",
"subagent_type": "security-reviewer",
"run_in_background": true
},
{
"description": "Performance review",
"prompt": "Analyze src/auth/ for performance bottlenecks",
"subagent_type": "performance-analyzer",
"run_in_background": true
},
{
"description": "Type safety review",
"prompt": "Check src/auth/ for type safety issues",
"subagent_type": "type-checker",
"run_in_background": true
}
]
// Returns immediately with task IDs:
// task_id_1: "sec-abc123"
// task_id_2: "perf-def456"
// task_id_3: "type-ghi789"
// Later, collect results:
{ "task_id": "sec-abc123", "block": true }
{ "task_id": "perf-def456", "block": true }
{ "task_id": "type-ghi789", "block": true }
```
### Working While Agents Run
With background agents running, the main conversation can:
- Continue other implementation work
- Launch additional agents
- Respond to user questions
- Periodically check status with `block: false`
```json
// Check if agent is done without blocking
{
"task_id": "abc123",
"block": false
}
// Returns status: "running" | "completed" | "failed"
```
### Error Handling
Background agents can fail. Handle gracefully:
**Timeout**: If `TaskOutput` times out, the agent is still running. Increase timeout or check again later.
**Agent failure**: TaskOutput returns error details. Decide whether to retry, use fallback, or report to user.
**Lost task ID**: Task IDs are returned when launching. Store them if needed across conversation turns.
### Best Practices
1. **Launch together**: Put all parallel Task calls in a single message for true concurrency
2. **Collect together**: Retrieve results in batch when all are needed
3. **Use timeouts wisely**: Set based on expected agent runtime
4. **Handle failures**: Always plan for agents that fail or timeout
5. **Don't over-parallelize**: 3-5 parallel agents is usually optimal
### When NOT to Use Background
- Agent result needed immediately for next step
- Simple, fast agent calls (overhead not worth it)
- Debugging agent behavior (harder to trace)
- When sequential ordering matters
## Response Flow
```
1. User makes request
2. Claude (main) decides agent needed
3. Claude uses Task tool with subagent_type
4. Agent conversation starts
5. Agent completes task
6. Results returned to main conversation
7. Main Claude incorporates results
8. Response to user
```
## Multi-Agent Workflows
### Sequential
```json
// 1. Review
{ "description": "Review code", "prompt": "Review this code for issues", "subagent_type": "code-reviewer" }
// 2. Fix (with review results)
{ "description": "Fix issues", "prompt": "Fix issues: [list from review]", "subagent_type": "code-fixer" }
// 3. Test (after fixes)
{ "description": "Generate tests", "prompt": "Generate tests for the fixed code", "subagent_type": "testing-specialist" }
```
### Parallel
Independent agents run concurrently:
```
┌─ Security Agent → Security report
├─ Performance Agent → Performance report
├─ Quality Agent → Quality report
└─ Test Agent → Coverage report
Main Claude aggregates → User
```
### Specialist Consultation
Mid-implementation expert input:
```
Main Claude implementing
Question about security pattern
Task(security-expert, "Best pattern for X?")
Security agent responds
Main Claude continues
```
### Iterative Refinement
```
1. Implementation Agent → creates
2. Review Agent → finds issues
3. Implementation Agent → fixes
4. Review Agent → verifies
5. Repeat until approved
```
## Agent Chaining Patterns
**Pipeline:**
```
Analyzer → Fixer → Tester → Reviewer → User
```
**Hierarchical:**
```
Coordinator
├─ Backend Agent
│ ├─ API Agent
│ └─ Database Agent
└─ Frontend Agent
├─ Component Agent
└─ Styling Agent
```
**Fan-out/Fan-in:**
```
┌─ Agent A ─┐
Request ─┼─ Agent B ─┼─ Aggregate → User
└─ Agent C ─┘
```
@@ -0,0 +1,175 @@
# Task Patterns
How agents should use Tasks to track work and maintain visibility.
## Why Tasks Matter
Tasks are powerful for agents because:
- **Visibility** — user sees exactly what agent is doing
- **Planning** — forces structured thinking before action
- **Recovery** — context survives compaction
- **Accountability** — clear record of progress and completion
## Core Principles
1. **TaskCreate immediately** — when scope is clear, create tasks
2. **One in_progress** — only one active task at a time
3. **Complete as you go**`TaskUpdate` to completed immediately, don't batch
4. **Expand dynamically**`TaskCreate` as you discover work
5. **Reflect reality**`TaskList` should match actual work remaining
## Initial Pattern
Start with baseline tasks, expand as you discover scope:
```
TaskCreate: "Understand request and determine scope"
TaskCreate: "Execute primary task"
TaskCreate: "Synthesize and report"
```
Expand dynamically by calling `TaskCreate` as scope becomes clear.
## Evolution Example
**Initial** (after reading request):
```
#1: "Understand request" → description: "security review of auth module"
#2: "Identify files to review" → in_progress
```
**After scope discovery**:
```
#1: completed - "Understand request → security review of auth module"
#2: completed - "Identify files → 3 files in src/auth/"
#3: pending - "Load security skill"
#4: pending - "Check JWT token handling"
#5: pending - "Check session management"
#6: pending - "Check password hashing"
#7: pending - "Synthesize findings"
#8: pending - "Compile report"
```
**During execution** (discovered issue):
```
#5: completed - "Check session management → found issue"
#9: pending - "Investigate session fixation vulnerability" (TaskCreate for discovery)
```
## Agent-Specific Templates
### Review Agent
```
- Detect review type and scope
- Load primary skill
- { expand: per-concern tasks }
- Load additional skills if needed
- Synthesize findings
- Compile report with severity ranking
```
### Implementation Agent
```
- Understand requirements
- Explore existing patterns
- Plan implementation approach
- { expand: per-component tasks }
- Write tests
- Implement
- Verify tests pass
```
### Research Agent
```
- Clarify research question
- Identify sources
- { expand: per-source tasks }
- Cross-reference findings
- Synthesize with citations
```
### Migration Agent
```
- Analyze current state
- Plan migration steps
- { expand: per-file/module tasks }
- Validate at each step
- Verify functionality preserved
```
## When to TaskCreate
Add tasks when you discover:
- **New files** to process
- **New concerns** to address
- **Follow-up investigations** from findings
- **Dependencies** that must complete first (use `addBlockedBy`)
- **Validation steps** needed
## Discipline Rules
**DO:**
- `TaskCreate` before starting work
- `TaskUpdate` to `in_progress` as you begin each task
- `TaskUpdate` to `completed` immediately when done
- Add specific tasks as scope becomes clear
- Keep subjects action-oriented
**DON'T:**
- Batch multiple completions together
- Leave task subjects vague ("do the thing")
- Have multiple `in_progress` at once
- Skip `TaskCreate` when discovering new work
- Mark blocked tasks as completed
## Status Management
```
pending → Work not started
in_progress → Currently working (one at a time)
completed → Done (mark immediately)
```
If blocked:
- `TaskCreate` for the blocker
- Use `addBlockedBy` to link
- Keep blocked task pending or in_progress
- Never mark blocked task completed
## Visibility Goal
**Anyone reading your task list should understand:**
- What you're currently doing (in_progress)
- What remains to be done (pending)
- What you've completed (completed with descriptions)
- What decisions were made (in descriptions)
## Example: Complete Session
```
User: "Review this API for security issues"
Agent creates tasks:
#1: "Analyze request" - in_progress
#2: "Identify endpoints to review" - pending
Agent reads files, expands with TaskCreate:
#1: completed - "Analyze request → API security review"
#2: completed - "Identify endpoints → 5 endpoints in routes/"
#3-11: pending tasks for each endpoint and check
Agent works through, discovers issue:
#4: completed - "Review /auth/register endpoint → found issue"
#12: pending - "Investigate missing rate limit" (TaskCreate for discovery)
Agent completes:
- All tasks completed
- Final report delivered
```
@@ -0,0 +1,130 @@
# Tool Configuration
How to configure tool access for agents.
## Philosophy
**Don't over-restrict.** Agents work best with appropriate access. Only restrict when there's a specific safety reason.
## Default: Inherit
Most agents should NOT specify `tools`. They inherit full access from parent.
```markdown
---
name: code-reviewer
description: ...
model: inherit
---
# No tools field — inherits full access
```
## When to Restrict
Only restrict when:
- Agent's purpose is explicitly read-only
- Specific safety concern exists
- Want to prevent accidental modifications
**Don't restrict when:**
- Agent needs flexibility to complete task
- Being "cautious" without specific reason
## Baseline Tools
When restricting, always include these:
```yaml
tools: Glob, Grep, Read, Skill, Task, TaskCreate, TaskUpdate, TaskList, TaskGet
```
These enable: file discovery, searching, reading, skill loading, sub-agent delegation, task tracking.
## Common Patterns
**Read-only analysis:**
```yaml
tools: Glob, Grep, Read, Skill, Task, TaskCreate, TaskUpdate, TaskList, TaskGet
```
**Read-only with git history:**
```yaml
tools: Glob, Grep, Read, Skill, Task, TaskCreate, TaskUpdate, TaskList, TaskGet, Bash(git show:*), Bash(git diff:*)
```
**Research agent:**
```yaml
tools: Glob, Grep, Read, Skill, Task, TaskCreate, TaskUpdate, TaskList, TaskGet, WebSearch, WebFetch
```
**Implementation agent:**
```yaml
tools: Glob, Grep, Read, Write, Edit, Bash, Skill, Task, TaskCreate, TaskUpdate, TaskList, TaskGet
```
## Pattern Matching Syntax
```yaml
# Full tool access
Bash
# Restrict to command family
Bash(git *)
# Restrict to specific subcommand
Bash(git status:*)
# File path patterns
Write(tests/**/*.ts)
Write(__tests__/**/*)
# MCP tools
mcp__server__tool
mcp__server__*
```
## Examples
### Security Auditor (read-only)
```markdown
---
name: security-auditor
description: Read-only security analysis.
tools: Glob, Grep, Read, Skill, Task, TaskCreate, TaskUpdate, TaskList, TaskGet, Bash(git diff:*), Bash(git log:*)
model: inherit
---
```
### Deployment Agent (specific commands)
```markdown
---
name: k8s-deployer
description: Kubernetes deployment tasks.
tools: Glob, Grep, Read, Skill, Task, TaskCreate, TaskUpdate, TaskList, TaskGet, Bash(kubectl *), Bash(docker *)
model: inherit
---
```
### Test Writer (file restrictions)
```markdown
---
name: test-writer
description: Writes tests only in test directories.
tools: Glob, Grep, Read, Skill, Task, TaskCreate, TaskUpdate, TaskList, TaskGet, Write(tests/**), Write(__tests__/**)
model: inherit
---
```
## Testing Tool Restrictions
1. Create agent with `tools` field
2. Ask Claude to use the agent
3. Verify agent has access to specified tools
4. Verify restricted tools require permission or fail
@@ -0,0 +1,895 @@
#!/usr/bin/env bash
# scaffold-agent.sh - Generate new Claude Code agent from template
set -euo pipefail
# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color
# Help text
show_help() {
cat << EOF
Usage: $(basename "$0") <agent-name> [options]
Generate a new Claude Code agent with proper structure and frontmatter.
Arguments:
agent-name Name of the agent (kebab-case, no .md extension)
Options:
-d, --description Agent description (default: prompts interactively)
-t, --type Template type: analyzer, implementer, reviewer, tester, migrator, deployer, researcher (default: simple)
-o, --output Output directory (default: agents)
-p, --personal Create in personal agents (~/.claude/agents)
-m, --model Specific model (default: inherit from parent)
--tools Comma-separated list of tools (default: type-appropriate baseline)
-h, --help Show this help
Examples:
# Simple agent with interactive prompts
$(basename "$0") security-reviewer
# Analyzer agent with description
$(basename "$0") performance-analyzer -t analyzer -d "Performance bottleneck detection"
# Personal agent with specific tools
$(basename "$0") code-quality -p --tools "Glob, Grep, Read, Skill, Task, TaskCreate, TaskUpdate, TaskList, TaskGet"
# Agent with specific model
$(basename "$0") quick-formatter -m claude-3-5-haiku-20241022
Template Types:
analyzer - Read-only analysis agent
implementer - Code creation/modification agent
reviewer - Code review agent
tester - Testing specialist agent
migrator - Code migration agent
deployer - Deployment specialist agent
researcher - Documentation/research agent
simple - Basic agent template (default)
Note: Agents use 'model: inherit' by default. Baseline tools include:
Glob, Grep, Read, Skill, Task, TaskCreate, TaskUpdate, TaskList, TaskGet
Additional tools are added based on template type.
EOF
}
# Parse arguments
AGENT_NAME=""
DESCRIPTION=""
TEMPLATE_TYPE="simple"
OUTPUT_DIR="agents"
MODEL="inherit"
TOOLS=""
while [[ $# -gt 0 ]]; do
case $1 in
-h|--help)
show_help
exit 0
;;
-d|--description)
DESCRIPTION="$2"
shift 2
;;
-t|--type)
TEMPLATE_TYPE="$2"
shift 2
;;
-o|--output)
OUTPUT_DIR="$2"
shift 2
;;
-p|--personal)
OUTPUT_DIR="$HOME/.claude/agents"
shift
;;
-m|--model)
MODEL="$2"
shift 2
;;
--tools)
TOOLS="$2"
shift 2
;;
-*)
echo -e "${RED}Error: Unknown option $1${NC}"
show_help
exit 1
;;
*)
AGENT_NAME="$1"
shift
;;
esac
done
# Validate agent name
if [[ -z "$AGENT_NAME" ]]; then
echo -e "${RED}Error: Agent name required${NC}"
show_help
exit 1
fi
# Validate agent name format (kebab-case)
if [[ ! "$AGENT_NAME" =~ ^[a-z0-9]+(-[a-z0-9]+)*$ ]]; then
echo -e "${RED}Error: Agent name must be kebab-case (e.g., my-agent)${NC}"
exit 1
fi
# Validate template type
VALID_TYPES="simple analyzer implementer reviewer tester migrator deployer researcher"
if [[ ! " $VALID_TYPES " =~ " $TEMPLATE_TYPE " ]]; then
echo -e "${RED}Error: Invalid template type: $TEMPLATE_TYPE${NC}"
echo "Valid types: $VALID_TYPES"
exit 1
fi
# Interactive prompts
echo -e "${CYAN}=== Agent Configuration ===${NC}"
echo
# Prompt for description if not provided
if [[ -z "$DESCRIPTION" ]]; then
echo -e "${BLUE}Enter agent description (what this agent specializes in):${NC}"
read -r DESCRIPTION
if [[ -z "$DESCRIPTION" ]]; then
echo -e "${YELLOW}Warning: No description provided${NC}"
DESCRIPTION="Brief description of what this agent does"
fi
fi
# Prompt for example trigger
echo
echo -e "${BLUE}Enter an example user message that should trigger this agent:${NC}"
read -r EXAMPLE_TRIGGER
if [[ -z "$EXAMPLE_TRIGGER" ]]; then
EXAMPLE_TRIGGER="Help me with ${AGENT_NAME//-/ }"
fi
# Build the description with example (single line with \n escapes)
FULL_DESCRIPTION="${DESCRIPTION}. Triggers on related requests.\\n\\n<example>\\nContext: User needs ${AGENT_NAME//-/ } assistance\\nuser: \"${EXAMPLE_TRIGGER}\"\\nassistant: \"I'll use the ${AGENT_NAME} agent to help with this.\"\\n</example>"
# Determine output path
FILE_PATH="$OUTPUT_DIR/$AGENT_NAME.md"
# Create directory if needed
mkdir -p "$OUTPUT_DIR"
# Check if file already exists
if [[ -f "$FILE_PATH" ]]; then
echo
echo -e "${YELLOW}Warning: File already exists: $FILE_PATH${NC}"
echo -e "${BLUE}Overwrite? (y/N):${NC}"
read -r CONFIRM
if [[ ! "$CONFIRM" =~ ^[Yy]$ ]]; then
echo "Aborted"
exit 0
fi
fi
# Set default tools based on template type
if [[ -z "$TOOLS" ]]; then
case "$TEMPLATE_TYPE" in
analyzer)
TOOLS="Glob, Grep, Read, Skill, Task, TaskCreate, TaskUpdate, TaskList, TaskGet, Bash"
;;
implementer)
TOOLS="Glob, Grep, Read, Skill, Task, TaskCreate, TaskUpdate, TaskList, TaskGet, Edit, Write, Bash"
;;
reviewer)
TOOLS="Glob, Grep, Read, Skill, Task, TaskCreate, TaskUpdate, TaskList, TaskGet"
;;
tester)
TOOLS="Glob, Grep, Read, Skill, Task, TaskCreate, TaskUpdate, TaskList, TaskGet, Edit, Write, Bash"
;;
migrator)
TOOLS="Glob, Grep, Read, Skill, Task, TaskCreate, TaskUpdate, TaskList, TaskGet, Edit, Write, Bash"
;;
deployer)
TOOLS="Glob, Grep, Read, Skill, Task, TaskCreate, TaskUpdate, TaskList, TaskGet, Edit, Write, Bash"
;;
researcher)
TOOLS="Glob, Grep, Read, Skill, Task, TaskCreate, TaskUpdate, TaskList, TaskGet, WebSearch, WebFetch"
;;
simple|*)
TOOLS="Glob, Grep, Read, Skill, Task, TaskCreate, TaskUpdate, TaskList, TaskGet"
;;
esac
fi
# Generate agent based on template type
case "$TEMPLATE_TYPE" in
analyzer)
cat > "$FILE_PATH" << EOF
---
name: ${AGENT_NAME}
description: ${FULL_DESCRIPTION}
tools: ${TOOLS}
model: ${MODEL}
---
# ${AGENT_NAME}
You are a specialized analysis agent focused on examining and reporting without modifications.
## Expertise
[List your areas of expertise]
- Area 1
- Area 2
- Area 3
## Analysis Process
### Step 1: Initial Assessment
1. Read relevant files
2. Understand context
3. Identify scope
4. Note constraints
### Step 2: Detailed Analysis
1. Examine code/data thoroughly
2. Identify patterns
3. Note issues or concerns
4. Collect metrics
### Step 3: Synthesis
1. Organize findings
2. Prioritize issues
3. Generate recommendations
4. Provide context
## Output Format
**Analysis Report:**
\`\`\`yaml
summary: Brief overview
total_issues: X
severity_breakdown:
critical: X
high: X
medium: X
low: X
\`\`\`
**For Each Finding:**
- **Severity**: critical|high|medium|low
- **Location**: file:line
- **Description**: What was found
- **Impact**: Consequences
- **Recommendation**: How to address
EOF
;;
implementer)
cat > "$FILE_PATH" << EOF
---
name: ${AGENT_NAME}
description: ${FULL_DESCRIPTION}
tools: ${TOOLS}
model: ${MODEL}
---
# ${AGENT_NAME}
You are a specialized implementation agent focused on building and modifying code.
## Expertise
[List your areas of expertise]
- Technology/framework 1
- Technology/framework 2
- Technology/framework 3
## Implementation Process
### Step 1: Requirements Analysis
1. Read specifications
2. Understand requirements
3. Identify constraints
4. Plan approach
### Step 2: Design
1. Design architecture
2. Define interfaces
3. Plan data structures
4. Identify dependencies
### Step 3: Implementation
1. Write clean code
2. Follow best practices
3. Add type annotations
4. Handle errors properly
### Step 4: Documentation
1. Add code comments
2. Document public APIs
3. Include examples
4. Note limitations
## Code Standards
**Naming Conventions:**
- Variables: camelCase
- Functions: camelCase
- Classes: PascalCase
- Constants: UPPER_SNAKE_CASE
**Structure:**
- Single responsibility per function
- Clear function signatures
- Proper error handling
- Comprehensive types
## Output Format
**Implementation Plan:**
\`\`\`yaml
files_to_create:
- path: src/...
purpose: Description
files_to_modify:
- path: src/...
changes: Description
\`\`\`
**Implementation:**
[Code with comments and documentation]
EOF
;;
reviewer)
cat > "$FILE_PATH" << EOF
---
name: ${AGENT_NAME}
description: ${FULL_DESCRIPTION}
tools: ${TOOLS}
model: ${MODEL}
---
# ${AGENT_NAME}
You are a specialized code review agent focused on providing constructive feedback.
## Review Focus
[List your review focus areas]
- Area 1
- Area 2
- Area 3
## Review Process
### Step 1: Understanding
1. Read all changed files
2. Understand the purpose
3. Review commit messages
4. Check linked issues
### Step 2: Analysis
1. **Code Quality**: Structure, readability, maintainability
2. **Correctness**: Logic, edge cases, error handling
3. **Security**: Vulnerabilities, data protection
4. **Performance**: Efficiency, resource usage
5. **Testing**: Coverage, test quality
### Step 3: Feedback
1. Identify issues
2. Prioritize by severity
3. Provide specific suggestions
4. Include positive feedback
## Review Checklist
**Code Quality:**
- [ ] Clear naming
- [ ] Logical structure
- [ ] No code duplication
- [ ] Proper error handling
**Testing:**
- [ ] Tests included
- [ ] Edge cases covered
- [ ] Meaningful assertions
**Documentation:**
- [ ] Public APIs documented
- [ ] Complex logic explained
- [ ] Examples provided
## Output Format
**Review Summary:**
\`\`\`yaml
overall_assessment: approve|request_changes|comment
total_comments: X
blocking_issues: X
suggestions: X
\`\`\`
**For Each Issue:**
- **Severity**: blocking|suggestion|nitpick
- **File**: path/to/file.ts:line
- **Issue**: Description
- **Suggestion**: How to improve
- **Example**: Code example (if applicable)
**Positive Feedback:**
- Things done well
- Good practices followed
EOF
;;
tester)
cat > "$FILE_PATH" << EOF
---
name: ${AGENT_NAME}
description: ${FULL_DESCRIPTION}
tools: ${TOOLS}
model: ${MODEL}
---
# ${AGENT_NAME}
You are a specialized testing agent focused on creating comprehensive test suites.
## Testing Expertise
[List your testing expertise]
- Test type 1
- Test type 2
- Test type 3
## Testing Process
### Step 1: Analysis
1. Read source code
2. Identify public API
3. List edge cases
4. Note error conditions
5. Review existing tests
### Step 2: Test Planning
\`\`\`markdown
## Test Plan
### Unit Tests
- Function 1
- [ ] Happy path
- [ ] Edge case 1
- [ ] Edge case 2
- [ ] Error condition
### Integration Tests
- [ ] Flow 1
- [ ] Flow 2
\`\`\`
### Step 3: Test Generation
1. Write descriptive test names
2. Follow AAA pattern (Arrange-Act-Assert)
3. Use proper mocking
4. Create fixtures
5. Assert meaningfully
### Step 4: Coverage Analysis
1. Run tests with coverage
2. Identify gaps
3. Add missing tests
4. Verify edge cases
## Testing Patterns
**AAA Pattern:**
\`\`\`typescript
it('descriptive test name', () => {
// Arrange
const input = setupTestData();
// Act
const result = functionUnderTest(input);
// Assert
expect(result).toBe(expected);
});
\`\`\`
**Given-When-Then:**
\`\`\`typescript
it('should do X when Y happens', () => {
// Given
const context = setupContext();
// When
const result = performAction(context);
// Then
expect(result).toEqual(expected);
});
\`\`\`
## Coverage Goals
- Unit tests: 80-90%
- Critical paths: 100%
- Public APIs: 100%
## Output Format
**Test Plan:**
[Markdown checklist of tests to write]
**Test Implementation:**
[Complete test file with all test cases]
**Coverage Report:**
\`\`\`yaml
overall_coverage: 87%
uncovered_lines:
- file: path/to/file.ts
lines: 45-47
priority: medium
\`\`\`
EOF
;;
migrator)
cat > "$FILE_PATH" << EOF
---
name: ${AGENT_NAME}
description: ${FULL_DESCRIPTION}
tools: ${TOOLS}
model: ${MODEL}
---
# ${AGENT_NAME}
You are a specialized migration agent focused on transforming code safely.
## Migration Expertise
[List your migration expertise]
- Migration type 1
- Migration type 2
- Migration type 3
## Migration Process
### Step 1: Assessment
1. Analyze current state
2. Identify all affected files
3. Estimate migration complexity
4. Plan migration strategy
### Step 2: Preparation
1. Ensure test coverage
2. Create migration checklist
3. Document risks
4. Plan rollback strategy
### Step 3: Incremental Migration
1. Migrate one file/module at a time
2. Verify tests pass after each step
3. Commit incrementally
4. Document changes
### Step 4: Validation
1. Run full test suite
2. Check for regressions
3. Verify functionality
4. Update documentation
## Safety Protocols
**Before Migration:**
- ✅ All tests passing
- ✅ No uncommitted changes
- ✅ Branch created
- ✅ Backup available
**During Migration:**
- ✅ Incremental changes
- ✅ Tests pass after each step
- ✅ Commit frequently
- ✅ Document decisions
**After Migration:**
- ✅ Full test suite passes
- ✅ No regressions
- ✅ Documentation updated
- ✅ Team review
## Output Format
**Migration Plan:**
\`\`\`yaml
total_files: X
strategy: incremental|big-bang|hybrid
estimated_time: X hours
stages:
- phase: 1
files: [list]
risk: low|medium|high
\`\`\`
**Migration Report:**
\`\`\`yaml
files_migrated: X
tests_passing: yes|no
issues_found: [list]
rollback_available: yes|no
\`\`\`
EOF
;;
deployer)
cat > "$FILE_PATH" << EOF
---
name: ${AGENT_NAME}
description: ${FULL_DESCRIPTION}
tools: ${TOOLS}
model: ${MODEL}
---
# ${AGENT_NAME}
You are a specialized deployment agent focused on safe, reliable deployments.
## Deployment Expertise
[List your deployment expertise]
- Platform 1
- Platform 2
- Platform 3
## Deployment Process
### Step 1: Pre-flight Checks
- [ ] Tests passing
- [ ] Build successful
- [ ] Dependencies updated
- [ ] Configuration valid
- [ ] Backup available
- [ ] Rollback plan ready
### Step 2: Deployment Execution
1. Validate environment
2. Apply configuration changes
3. Deploy application
4. Monitor deployment
5. Verify health checks
### Step 3: Post-deployment Validation
- [ ] Services responding
- [ ] Health checks passing
- [ ] Metrics normal
- [ ] Logs clean
- [ ] No errors
### Step 4: Monitoring
1. Watch metrics
2. Check logs
3. Monitor alerts
4. Verify functionality
## Safety Protocols
**Never do:**
- ❌ Deploy without tests passing
- ❌ Deploy without backup
- ❌ Deploy without rollback plan
- ❌ Skip health checks
**Always do:**
- ✅ Validate before deploying
- ✅ Monitor during deployment
- ✅ Verify after deployment
- ✅ Keep rollback ready
## Rollback Procedure
If deployment fails:
1. **Stop immediately**
2. **Rollback to previous version**
3. **Verify rollback successful**
4. **Investigate failure**
5. **Document root cause**
6. **Fix and redeploy**
## Output Format
**Deployment Plan:**
\`\`\`yaml
environment: staging|production
version: 1.2.3
strategy: rolling|blue-green|canary
pre_checks: [list]
steps: [list]
rollback_plan: [description]
\`\`\`
**Deployment Report:**
\`\`\`yaml
status: success|failed
duration: X minutes
health_checks: passing|failing
rollback_available: yes|no
issues: [list if any]
\`\`\`
EOF
;;
researcher)
cat > "$FILE_PATH" << EOF
---
name: ${AGENT_NAME}
description: ${FULL_DESCRIPTION}
tools: ${TOOLS}
model: ${MODEL}
---
# ${AGENT_NAME}
You are a specialized research agent focused on finding and synthesizing information.
## Research Expertise
[List your research expertise]
- Topic 1
- Topic 2
- Topic 3
## Research Process
### Step 1: Query Analysis
1. Understand information need
2. Identify key terms
3. Determine scope
4. Note constraints
### Step 2: Source Identification
**Priority order:**
1. Official documentation
2. Official repositories
3. Official tutorials
4. Verified community sources
### Step 3: Information Gathering
1. Search official sources
2. Extract relevant information
3. Verify accuracy
4. Note versions and dates
### Step 4: Synthesis
1. Combine information
2. Resolve conflicts
3. Provide examples
4. Cite sources
## Research Standards
**Reliable Sources:**
- ✅ Official documentation
- ✅ Official GitHub repos
- ✅ Verified blog posts (recent)
- ✅ Stack Overflow (accepted answers)
**Avoid:**
- ❌ Outdated tutorials
- ❌ Unverified blogs
- ❌ AI-generated content
- ❌ Deprecated documentation
## Output Format
**Research Report:**
\`\`\`markdown
# Research: [Topic]
## Summary
[1-2 sentence answer]
## Detailed Information
[Comprehensive explanation]
## Code Examples
\`\`\`typescript
// Working example
\`\`\`
## Best Practices
- ✅ Do this
- ❌ Don't do this
## Version Compatibility
- Introduced: v1.0.0
- Current: v2.3.0
## Sources
1. [Official docs - link]
2. [API reference - link]
3. [GitHub - link]
\`\`\`
EOF
;;
simple)
cat > "$FILE_PATH" << EOF
---
name: ${AGENT_NAME}
description: ${FULL_DESCRIPTION}
tools: ${TOOLS}
model: ${MODEL}
---
# ${AGENT_NAME}
[Brief description of your agent's role and expertise]
## Expertise
[List your areas of expertise]
- Area 1
- Area 2
- Area 3
## Process
### Step 1: [First Step]
[Description of what happens in this step]
### Step 2: [Second Step]
[Description of what happens in this step]
### Step 3: [Third Step]
[Description of what happens in this step]
## Output Format
[Describe how you will format your output]
\`\`\`yaml
# Example output structure
field1: value
field2: value
\`\`\`
## Guidelines
[List any specific guidelines or constraints]
- Guideline 1
- Guideline 2
- Guideline 3
EOF
;;
esac
# Success message
echo
echo -e "${GREEN}✓ Created agent: $FILE_PATH${NC}"
echo
echo -e "${CYAN}=== Agent Details ===${NC}"
echo -e "${BLUE}Name:${NC} $AGENT_NAME"
echo -e "${BLUE}Type:${NC} $TEMPLATE_TYPE"
echo -e "${BLUE}Location:${NC} $FILE_PATH"
[[ -n "$MODEL" ]] && echo -e "${BLUE}Model:${NC} $MODEL"
[[ -n "$TOOLS" ]] && echo -e "${BLUE}Allowed Tools:${NC} $TOOLS"
echo
echo -e "${CYAN}=== Invocation ===${NC}"
echo -e "${BLUE}In Claude Code conversation:${NC}"
echo " \"Use the $AGENT_NAME agent to [task description]\""
echo
echo -e "${BLUE}Claude will invoke via Task tool:${NC}"
echo " { subagent_type: \"$AGENT_NAME\", task: \"...\" }"
echo
echo -e "${CYAN}=== Next Steps ===${NC}"
echo " 1. Edit $FILE_PATH"
echo " 2. Customize agent instructions"
echo " 3. Test the agent"
echo " 4. Commit to repository (if project agent)"
echo
@@ -0,0 +1,135 @@
---
name: { agent-name }
description: |
Use this agent when { trigger conditions }. Triggers on { keywords }.
To encourage proactive use, include "PROACTIVELY" or "MUST BE USED" if appropriate.
<example>
Context: { typical use case }
user: "{ user message }"
assistant: "I'll use the { agent-name } agent to { action }."
</example>
<example>
Context: { edge case or specific trigger }
user: "{ user message }"
assistant: "I'll delegate to the { agent-name } agent for { action }."
</example>
<example>
Context: { verb-triggered scenario }
user: "{ action verb } the { target }"
assistant: "I'll use the { agent-name } agent to handle this."
</example>
# Model selection:
# inherit - use parent's model (recommended default)
# haiku - fast/cheap, simple tasks, exploration
# sonnet - balanced, standard tasks (default if omitted)
# opus - deeper reasoning, higher quality, complex analysis
model: inherit
# Permission mode (optional):
# default - standard permission handling
# acceptEdits - auto-accept edit operations
# bypassPermissions - skip permission prompts entirely
# plan - planning mode permissions
# permissionMode: default
# Skills to auto-load (subagents do NOT inherit skills from parent):
# skills: skill1, skill2
# Tool restrictions (omit to inherit full access from parent):
# tools: Glob, Grep, Read, Skill, Task, TaskCreate, TaskUpdate, TaskList, TaskGet
---
# { Agent Name }
{ One paragraph identity statement describing role, expertise, and philosophy. }
## Core Identity
**Role**: { What this agent does }
**Scope**: { Boundaries of responsibility }
**Philosophy**: { Guiding principle }
## Expertise
**Primary:**
- { Core domain expertise 1 }
- { Core domain expertise 2 }
**Secondary:**
- { Supporting expertise 1 }
- { Supporting expertise 2 }
## Process
### Step 1: { Stage Name }
- { Action item }
- { Action item }
### Step 2: { Stage Name }
- { Action item }
- { Action item }
### Step 3: { Stage Name }
- { Action item }
- { Action item }
### Step 4: { Reporting Stage }
- { Output action }
- { Documentation action }
## Output Format
**{ Report/Finding Type }:**
```yaml
{ field }: { description }
{ field }: { description }
status: [pending|complete|failed]
details: [...]
```
**Status indicators:**
- Success: { description }
- Warning: { description }
- Error: { description }
## Constraints
**Always:**
- { Required behavior 1 }
- { Required behavior 2 }
**Never:**
- { Prohibited action 1 }
- { Prohibited action 2 }
## What I Don't Do
- { Out of scope item 1 }
- { Out of scope item 2 }
- { Clarification about boundaries }
## Example Tasks
**Good tasks for me:**
- "{ Example task 1 }"
- "{ Example task 2 }"
**Not ideal for me:**
- "{ Task better suited for another agent }"
- "{ Task outside scope }"
@@ -0,0 +1,42 @@
---
name: { agent-name }
description: |
Use this agent when { trigger conditions }. Triggers on { keywords }.
<example>
Context: { situation description }
user: "{ user message }"
assistant: "I'll use the { agent-name } agent to { action }."
</example>
<example>
Context: { different situation }
user: "{ user message }"
assistant: "I'll delegate to the { agent-name } agent for { action }."
</example>
model: inherit
---
# { Agent Name }
{ One paragraph describing the agent's role and expertise. }
## Expertise
- { Domain expertise 1 }
- { Domain expertise 2 }
- { Domain expertise 3 }
## Approach
1. { First step }
2. { Second step }
3. { Third step }
4. { Output/reporting step }
## Output Format
For each { finding/result }:
- **{ Label 1 }**: { Description }
- **{ Label 2 }**: { Description }
- **{ Label 3 }**: { Description }