
Subagent Engineering
- 3 installs
- 19 repo stars
- Updated August 1, 2026
- xobotyi/cc-foundry
Helps with ai & agent building tasks.
About
subagent-engineering is a Claude Code skill for ai & agent building. It helps solo builders move faster with AI-assisted development.
- subagent-engineering
- AI & Agent Building
- AI-coding skill
Subagent Engineering by the numbers
- 3 all-time installs (skills.sh)
- Ranked #13,657 of 16,546 AI & Agent Building skills by installs in the Skillselion catalog
- Data as of Aug 2, 2026 (Skillselion catalog sync)
npx skills add https://github.com/xobotyi/cc-foundry --skill subagent-engineeringAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 3 |
|---|---|
| repo stars | ★ 19 |
| Last updated | August 1, 2026 |
| Repository | xobotyi/cc-foundry ↗ |
What it does
Helps with ai & agent building tasks.
Files
Subagent Engineering
Manage the full lifecycle of Claude Code subagents: creation, evaluation, iteration, and troubleshooting.
<prerequisite> Subagent prompts are system prompts. Before creating or improving a subagent, invoke prompt-engineering to load instruction design techniques.
Skill(ai-helpers:prompt-engineering)Skip only for trivial edits (typos, formatting). </prerequisite>
Route to Reference
| Situation | Reference | Contents |
|---|---|---|
| Full frontmatter field reference | [${CLAUDE_SKILL_DIR}/references/spec.md] | All fields with constraints, hooks schema, CLI-defined agents, storage locations |
| Step-by-step creation walkthrough | [${CLAUDE_SKILL_DIR}/references/creation.md] | Detailed process, common agent type templates, proactive delegation |
| Quality scoring and testing | [${CLAUDE_SKILL_DIR}/references/evaluation.md] | 5-dimension scoring rubric with weights, testing protocol (5 levels), benchmarking |
| Improving an existing subagent | [${CLAUDE_SKILL_DIR}/references/iteration.md] | Prompt refinement techniques, A/B testing, version control, redesign criteria |
| Diagnosing failures | [${CLAUDE_SKILL_DIR}/references/troubleshooting.md] | Diagnostic steps, error message catalog, debug mode |
| Architecture and examples | [${CLAUDE_SKILL_DIR}/references/patterns.md] | Full agent examples, pipeline/parallel/master-clone patterns, multi-agent coordination |
Read the relevant reference for extended depth. The rules below are sufficient for correct work without loading references.
When to Use Subagents
Use subagents when:
- Task produces verbose output you don't need in main context
- You want to enforce specific tool restrictions
- Work is self-contained and can return a summary
- You need to parallelize independent research
Use main conversation when:
- Task needs frequent back-and-forth
- Multiple phases share significant context
- Making quick, targeted changes
- Latency matters (subagents start fresh)
Use skills instead when:
- You want reusable prompts in main conversation context
- Task benefits from full conversation history
Subagent File Format
.claude/agents/my-agent.md # Project-level
~/.claude/agents/my-agent.md # User-level---
name: my-agent
description: What it does. When to use it.
tools: Read, Grep, Glob
model: sonnet
---
You are a [role]. When invoked:
1. [First step]
2. [Second step]
3. [Final output format]Scope Priority (highest to lowest)
1. --agents CLI flag (session only) 2. .claude/agents/ (project) 3. ~/.claude/agents/ (user) 4. Plugin agents (lowest)
When names collide, higher priority wins.
Required Frontmatter Fields
name
- Lowercase letters, numbers, hyphens only
- Max 64 characters, no
<or>characters - Cannot contain "anthropic" or "claude"
- Must match filename (minus
.md)
description
Claude sees ONLY name and description when deciding to delegate. The body loads AFTER delegation. This makes the description the highest-leverage field.
Formula:
[What it does in 1 sentence]. [When to use it — specific trigger context].Rules:
- Lead with what the agent does, not a slogan or tagline.
- State when to use it — specific contexts and trigger conditions.
- Include "use proactively" to encourage automatic delegation.
- Keep execution instructions out of the description — those belong
in the body.
- No keyword lists, no second person ("you can..."), no vague verbs
("helps", "assists").
- Max 1024 characters, no
<or>characters.
Good:
description: "Expert code review specialist. Proactively reviews code for
quality, security, and maintainability. Use immediately after writing
or modifying code."
description: "PostgreSQL database expert for query optimization and schema
design. Use when working with .sql files or database performance issues."Bad:
description: "Helps with code" # Too vague
description: "Review code. Steps: 1. Read 2..." # Execution details
description: "Code review. Keywords: review..." # Keyword stuffingOptional Frontmatter Fields
tools
Allowlist of tools the subagent can use. If omitted, inherits ALL tools from the main conversation (including MCP tools). Be intentional — don't leave it blank unless you want full access.
Principle: grant minimum necessary permissions.
| Agent Type | Recommended Tools |
|---|---|
| Read-only (reviewers, analysts) | Read, Grep, Glob |
| Research (with web) | Read, Grep, Glob, WebFetch, WebSearch |
| Code writers | Read, Write, Edit, Bash, Glob, Grep |
| Documentation | Read, Write, Edit, Glob, Grep, WebFetch |
Available built-in tools: Read, Write, Edit, Bash, Glob, Grep, WebFetch, WebSearch, Task (main agent only), NotebookEdit.
Use disallowedTools when you want most tools but need to exclude a few.
model
| Value | When to Use |
|---|---|
haiku | Quick searches, docs, simple analysis — fast and cheap |
sonnet | Everyday coding, debugging, refactoring |
opus | Architecture decisions, security audits, complex reasoning |
inherit | Match parent model (default if omitted) |
permissionMode
| Mode | Behavior |
|---|---|
default | Standard permission checking |
acceptEdits | Auto-accept file edits |
dontAsk | Auto-deny prompts (allowed tools still work) |
bypassPermissions | Skip all permission checks |
plan | Plan mode (read-only exploration) |
Security rules:
- Prefer
planmode for read-only agents — enforce safety at the
permission level, not just in the prompt.
bypassPermissionsskips ALL checks including file writes and command
execution. Only use for trusted, well-tested agents.
- If parent uses
bypassPermissions, child agents inherit it and
cannot override to a more restrictive mode.
skills
Skills to inject into the subagent's context at startup. Subagents don't inherit skills from parent — list them explicitly.
skills:
- api-conventions
- error-handling-patternshooks
Lifecycle hooks scoped to this subagent. Supported events: PreToolUse, PostToolUse, Stop (converted to SubagentStop).
Full hook schema and examples: see ${CLAUDE_SKILL_DIR}/references/spec.md.
Writing the System Prompt
Everything after the frontmatter becomes the subagent's system prompt. Subagents receive ONLY this prompt plus basic environment details — not the full Claude Code system prompt.
Structure Template
You are a [role] specializing in [domain].
## When Invoked
1. [First action]
2. [Second action]
3. [Continue until complete]
## Guidelines
- [Guideline 1]
- [Guideline 2]
## Constraints
- [Boundary 1 — what NOT to do]
## Output Format
[Specify exact structure with example]System Prompt Rules
- Start with role definition. "You are a [role] specializing in
[domain]."
- Use numbered steps for workflow. Explicit ordering prevents
skipped steps.
- Specify output format explicitly. Include a concrete example of
the expected output structure.
- Add constraints to prevent scope creep. "DO NOT modify files",
"ONLY report findings", "ASK for clarification if unclear."
- Include checklists for consistency. Agents follow checklists
more reliably than prose guidelines.
- Add completion criteria. "Your task is COMPLETE when: [criteria]."
Prevents both early termination and over-work.
- Keep single responsibility. If listing multiple unrelated
capabilities, split into separate agents.
- Add efficiency instructions. "Use Grep to locate relevant code
BEFORE reading entire files. Return concise summaries, not raw data."
Core Design Principles
- Description is the trigger. Claude sees ONLY
name+
description when deciding to delegate. Vague descriptions cause wrong triggers. Specific descriptions enable correct delegation.
- Single responsibility. Each subagent excels at ONE task. Don't
create Swiss Army knife agents — they're hard to trigger correctly and mediocre at everything.
- Minimal tool access. Grant only necessary permissions. Read-only
agents don't need Edit/Write. Excess tools invite scope creep.
- Clear handoffs. Design subagents to return actionable summaries,
not raw data dumps. The parent agent (or user) should be able to act on the output immediately.
- Context efficiency. Subagents should use Grep before Read,
stop when they have enough information, and return synthesized findings. Verbose returns consume parent context.
Built-in Subagents
| Agent | Model | Purpose |
|---|---|---|
| Explore | Haiku | Fast, read-only codebase exploration |
| Plan | Inherits | Research for plan mode |
| general-purpose | Inherits | Complex multi-step tasks |
| Bash | Inherits | Command execution in separate context |
| claude-code-guide | Haiku | Questions about Claude Code features |
Evaluation Criteria
When evaluating a subagent, assess these five dimensions:
- Trigger Accuracy (25%) — Does Claude delegate at the right times?
Test with: direct invocation, implicit matching, and non-matching tasks.
- Task Completion (30%) — Does the agent follow its workflow and
produce the expected output? Test happy path, edge cases, and out-of-scope requests.
- Output Quality (25%) — Is output clear, complete, actionable, and
format-compliant? Red flags: raw data dumps, missing information, inconsistent formatting.
- Context Efficiency (10%) — Does it return concise summaries? Does
it avoid unnecessary tool calls and excessive file reads?
- Tool Usage (10%) — Does it use only granted tools efficiently?
Does it handle tool errors gracefully?
Scoring: 4.5+ excellent, 3.5-4.4 good, 2.5-3.4 needs revision, <2.5 redesign. Full rubric with testing protocol: see ${CLAUDE_SKILL_DIR}/references/evaluation.md.
Common Issues and Fixes
Agent doesn't trigger
Description is too narrow or name has a typo. Broaden the description, add "use proactively", and verify the file loads with /agents.
Agent over-triggers
Description is too vague or overlaps with other agents. Narrow the scope, add explicit boundaries: "Security review for auth code only. NOT for general code review."
Wrong output format
No format specification in the prompt, or no example. Add an explicit ## Output Format section with a concrete example of the expected structure.
Incomplete task execution
Workflow isn't explicit enough. Add numbered steps with "IN ORDER", a completion checklist ("Before returning, verify:"), and explicit completion criteria.
Scope creep
Tools are too permissive or prompt doesn't set boundaries. Restrict the tools list and add a ## Constraints section with explicit prohibitions.
Poor context efficiency
No efficiency guidance. Add: "Use Grep to locate relevant code BEFORE reading entire files. Stop searching once you have sufficient information. Return a concise summary (max 500 words)."
Detailed diagnostic steps, error messages, and debug mode: see ${CLAUDE_SKILL_DIR}/references/troubleshooting.md.
Validation Checklist
Before deploying a subagent:
- [ ]
nameis lowercase with hyphens, no "anthropic" or "claude" - [ ]
descriptionexplains what AND when (under 1024 chars) - [ ]
descriptionhas no execution instructions - [ ]
toolsis minimal (only what's needed) - [ ]
modelmatches task complexity - [ ] System prompt starts with role definition
- [ ] System prompt has numbered workflow steps
- [ ] Output format is explicitly specified with example
- [ ] Constraints section prevents scope creep
- [ ] Completion criteria are defined
- [ ] Tested with representative tasks
Related Skills
prompt-engineering— Load first for instruction design techniques
(subagent prompts are system prompts)
skill-engineering— Skills and subagents complement each other;
skills run in main context, subagents run in isolation
claude-code-sdk— Consult for API/configuration details
{
"sources": {
"Claude Code Sub-agents Official Docs": "https://code.claude.com/docs/en/sub-agents.md",
"Anthropic Best Practices for Agentic Coding": "https://www.anthropic.com/engineering/claude-code-best-practices",
"Claude Code System Prompts Repository": "https://github.com/Piebald-AI/claude-code-system-prompts",
"Awesome Claude Code Subagents Collection": "https://github.com/VoltAgent/awesome-claude-code-subagents",
"PubNub Subagent Best Practices": "https://www.pubnub.com/blog/best-practices-for-claude-code-sub-agents/",
"Shipyard Subagents Guide": "https://shipyard.build/blog/claude-code-subagents-guide/",
"Tracing Claude Code LLM Traffic": "https://medium.com/@georgesung/tracing-claude-codes-llm-traffic-agentic-loop-sub-agents-tool-use-prompts-7796941806f5",
"Building Agents with Claude Agent SDK": "https://www.anthropic.com/engineering/building-agents-with-the-claude-agent-sdk",
"Claude Skills Deep Dive": "https://leehanchung.github.io/blogs/2025/10/26/claude-skills-deep-dive/",
"How to Prompt Claude Code Four Modes": "https://sderosiaux.medium.com/how-i-learned-to-prompt-ai-better-my-four-modes-177bddcfa6bd",
"Claude Code Feature Guide": "https://blog.sshh.io/p/how-i-use-every-claude-code-feature",
"Builder.io Claude Code Tips": "https://www.builder.io/blog/claude-code"
},
"lastFetched": "2026-01-31T11:03:49.771Z"
}
Creating Subagents
Step-by-step guide to creating effective subagents.
---
Table of Contents
---
Two Approaches
1. Interactive (/agents command)
Recommended for getting started:
/agents
→ Create new agent
→ Project-level or User-level
→ Generate with Claude (describe what you want)
→ Select tools
→ Select model
→ Choose color
→ SaveClaude generates the system prompt based on your description. Press e to open in editor and customize.
2. Manual (write the file)
Create a markdown file directly:
# Project-level (current repo only)
mkdir -p .claude/agents
touch .claude/agents/my-agent.md
# User-level (all projects)
mkdir -p ~/.claude/agents
touch ~/.claude/agents/my-agent.mdNote: Manually created agents load on session start. Use /agents to load immediately without restart.
Creation Process
Step 1: Define the Purpose
Answer these questions:
- What specific task does this agent handle?
- When should Claude delegate to it?
- What tools does it need?
- What output format should it produce?
Single responsibility principle: Each agent should excel at ONE task. If you're listing multiple unrelated capabilities, split into separate agents.
Step 2: Write the Description
The description is CRITICAL. Claude uses ONLY name and description to decide whether to delegate.
Template:
[What it does in 1 sentence]. [When to use it].Examples:
# Good: specific role + clear trigger
description: "Expert code review specialist. Proactively reviews code for
quality, security, and maintainability. Use immediately after writing
or modifying code."
# Good: domain-specific + use case
description: "PostgreSQL database expert for query optimization and schema
design. Use when working with .sql files or database performance issues."
# Good: action-oriented + context
description: "Debugging specialist for errors, test failures, and unexpected
behavior. Use proactively when encountering any issues."Anti-patterns:
# Bad: too vague
description: "Helps with code"
# Bad: execution details (belongs in body)
description: "Review code. Steps: 1. Read 2. Analyze 3. Report"
# Bad: keyword stuffing
description: "Code review. Keywords: review, quality, lint, security"Step 3: Select Tools
Principle: Grant minimum necessary permissions.
| Agent Type | Recommended Tools |
|---|---|
| Read-only (reviewers, analysts) | Read, Grep, Glob |
| Research (with web) | Read, Grep, Glob, WebFetch, WebSearch |
| Code writers | Read, Write, Edit, Bash, Glob, Grep |
| Documentation | Read, Write, Edit, Glob, Grep, WebFetch |
If omitted: Inherits ALL tools from main conversation (including MCP). Be intentional — don't leave it blank unless you want full access.
Step 4: Choose the Model
| Model | When to Use |
|---|---|
haiku | Quick searches, docs, simple analysis |
sonnet | Everyday coding, debugging, refactoring |
opus | Architecture decisions, security audits, complex reasoning |
inherit | Match parent (default) |
Cost consideration: Haiku is significantly cheaper. Use it for high-volume, straightforward tasks.
Step 5: Write the System Prompt
The system prompt is where prompt engineering matters most. Apply techniques from prompt-engineering skill: clear structure, numbered steps, XML tags for complex inputs, examples for format compliance.
Structure your prompt clearly:
---
name: agent-name
description: What it does. When to use it.
tools: Read, Grep, Glob
model: sonnet
---
You are a [role] specializing in [domain].
## When Invoked
1. [First action]
2. [Second action]
3. [Continue until complete]
## Guidelines
- [Guideline 1]
- [Guideline 2]
## Output Format
[Specify exact structure]
[Include examples if helpful]Best practices:
- Start with clear role definition
- Use numbered steps for workflow
- Include checklists for consistency
- Specify output format explicitly
- Add constraints to prevent scope creep
Step 6: Test and Iterate
Test with various inputs:
Use the [agent-name] subagent to [task]Observe:
- Does Claude delegate correctly?
- Does the agent follow the workflow?
- Is the output format correct?
- Are there edge cases that fail?
Iterate on the system prompt based on failures.
Common Agent Types
For full examples with complete prompts, see ${CLAUDE_SKILL_DIR}/references/patterns.md.
Common patterns:
- Code Reviewer — Read-only analysis after code changes
- Debugger — Root cause analysis with edit permissions
- Security Auditor — Vulnerability scanning (read-only, opus model)
- Domain Expert — Specialized knowledge (SQL, APIs, etc.)
- Test Runner — Execute and analyze test results
Template (compact):
---
name: [role]-[action]
description: "[What it does]. Use [when/proactively]."
tools: [minimal set]
model: [haiku|sonnet|opus|inherit]
---
You are a [role] specializing in [domain].
When invoked:
1. [First action]
2. [Analysis/work]
3. [Compile results]
Checklist:
- [ ] [Key check 1]
- [ ] [Key check 2]
Output format:
## [Section 1]
- [Finding]: [Location] - [Recommendation]Proactive Delegation
Include "use proactively" in descriptions to encourage automatic delegation:
description: "Code reviewer. Use proactively after code changes."
description: "Debugger. Use proactively when encountering errors."
description: "Test runner. Use proactively after implementation."Claude will delegate automatically when it recognizes matching contexts.
Validation Before Deployment
- [ ] Name is lowercase with hyphens
- [ ] Description explains what AND when
- [ ] Tools are minimal (only what's needed)
- [ ] Model matches task complexity
- [ ] System prompt has clear workflow
- [ ] Output format is specified
- [ ] Tested with representative tasks
Evaluating Subagents
Framework for assessing subagent quality and effectiveness.
---
Table of Contents
- Evaluation Dimensions
- Evaluation Checklist
- Testing Protocol
- Comparative Evaluation
- Quality Scoring
- Continuous Monitoring
---
Evaluation Dimensions
1. Trigger Accuracy
Does Claude delegate to this agent at the right times?
Test scenarios:
- Direct invocation: "Use the [agent] to [task]"
- Implicit match: Describe a task that should trigger delegation
- Non-match: Describe similar but different tasks (should NOT trigger)
Scoring:
| Outcome | Score | Action |
|---|---|---|
| Delegates correctly when should | Good | — |
| Delegates when shouldn't | Over-triggering | Narrow description |
| Doesn't delegate when should | Under-triggering | Broaden description |
| Never delegates | Broken | Check name/description format |
Common issues:
- Description too vague → over-triggers on unrelated tasks
- Description too specific → under-triggers on valid tasks
- Typo in name → never found
2. Task Completion
Does the agent accomplish its intended purpose?
Evaluate:
- Does it follow the specified workflow?
- Does it produce the expected output format?
- Does it handle edge cases?
- Does it stay within scope?
Test matrix:
| Input Type | Expected Behavior |
|---|---|
| Happy path | Complete successfully |
| Edge case | Handle gracefully |
| Invalid input | Fail clearly with explanation |
| Out of scope | Recognize and decline |
3. Output Quality
Is the agent's output useful and actionable?
Criteria:
- Clarity: Is the output easy to understand?
- Completeness: Does it include all necessary information?
- Actionability: Can the user/parent agent act on it?
- Format compliance: Does it match specified structure?
Red flags:
- Raw data dumps without synthesis
- Missing key information
- Inconsistent formatting
- Scope creep (doing more than asked)
4. Context Efficiency
Does the agent use context wisely?
Measure:
- How much context does it consume?
- Does it return concise summaries?
- Does it avoid unnecessary tool calls?
Good patterns:
- Returns synthesized findings, not raw search results
- Uses parallel tool calls when possible
- Stops when task is complete
Bad patterns:
- Reads entire codebase for simple lookup
- Returns verbose output to parent
- Continues working after task is done
5. Tool Usage
Does the agent use tools appropriately?
Check:
- Uses only granted tools
- Doesn't attempt dangerous operations
- Makes efficient use of tools
- Handles tool errors gracefully
Scoring:
| Behavior | Assessment |
|---|---|
| Uses minimal necessary tools | Good |
| Makes redundant tool calls | Inefficient |
| Attempts blocked tools | Over-scoped |
| Ignores available useful tools | Under-utilizing |
Evaluation Checklist
Run through this checklist for each subagent:
Description Quality
- [ ] Clearly states what the agent does
- [ ] Clearly states when to use it
- [ ] No execution instructions in description
- [ ] Under 1024 characters
Trigger Behavior
- [ ] Delegates on direct invocation
- [ ] Delegates on implicit matching tasks
- [ ] Does NOT delegate on unrelated tasks
- [ ] Delegation speed is acceptable
Task Execution
- [ ] Follows specified workflow
- [ ] Produces correct output format
- [ ] Handles happy path correctly
- [ ] Handles edge cases gracefully
- [ ] Recognizes out-of-scope requests
Output Quality
- [ ] Clear and understandable
- [ ] Contains necessary information
- [ ] Actionable by recipient
- [ ] Consistent format across runs
Resource Usage
- [ ] Reasonable context consumption
- [ ] Efficient tool usage
- [ ] Concise return to parent
Testing Protocol
Level 1: Smoke Test
Quick validation that agent works at all:
Use the [agent-name] subagent to [simple representative task]Pass criteria: Agent is invoked, produces output, returns to parent.
Level 2: Functional Test
Test core functionality:
# Happy path
Use the [agent] to [typical use case]
# Verify workflow steps are followed
# Verify output format is correctPass criteria: Workflow executed correctly, output matches spec.
Level 3: Edge Case Test
Test boundary conditions:
# Empty/minimal input
Use the [agent] with [minimal input]
# Large input
Use the [agent] on [large codebase/dataset]
# Ambiguous input
Use the [agent] for [ambiguous request]Pass criteria: Handles gracefully without crashing or hallucinating.
Level 4: Negative Test
Test what should NOT happen:
# Out of scope request
Use the [agent] for [unrelated task]
# Should reject or clarify, not attemptPass criteria: Agent recognizes scope boundary, doesn't attempt.
Level 5: Integration Test
Test in realistic workflow:
# Chain with other agents
Use [agent-1] to [task], then use [agent-2] to [follow-up]
# Parallel execution
Research [topic-a] and [topic-b] in parallel using subagentsPass criteria: Works correctly in multi-agent context.
Comparative Evaluation
When you have multiple versions or similar agents:
A/B Testing
Run same task with both versions:
# Version A
Use the code-reviewer to review the authentication module
# Version B (different prompt)
Use the code-reviewer-v2 to review the authentication moduleCompare:
- Trigger accuracy
- Output quality
- Context usage
- Completion time
Benchmarking
Create a standard test suite:
## Test Suite: Code Reviewer
### Test 1: Simple function
Input: [single function with obvious issue]
Expected: Identifies issue, suggests fix
### Test 2: Security vulnerability
Input: [code with SQL injection]
Expected: Flags as critical, explains risk
### Test 3: Clean code
Input: [well-written code]
Expected: Minimal feedback, no false positivesRun periodically to catch regressions.
Quality Scoring
Rate each dimension 1-5:
| Dimension | Score | Weight |
|---|---|---|
| Trigger Accuracy | ? | 25% |
| Task Completion | ? | 30% |
| Output Quality | ? | 25% |
| Context Efficiency | ? | 10% |
| Tool Usage | ? | 10% |
Overall = weighted average
Why these weights?
- Task Completion (30%) is highest — an agent that doesn't complete its
task fails regardless of other qualities
- Trigger Accuracy and Output Quality (25% each) — wrong triggers waste
time; poor output requires rework
- Context Efficiency and Tool Usage (10% each) — important for cost and
speed, but secondary to correctness
| Score | Rating | Action |
|---|---|---|
| 4.5+ | Excellent | Monitor only |
| 3.5-4.4 | Good | Minor improvements |
| 2.5-3.4 | Fair | Significant revision needed |
| <2.5 | Poor | Redesign from scratch |
Continuous Monitoring
Session Review
After using an agent, note:
- Did it trigger correctly?
- Was output useful?
- Any unexpected behavior?
Periodic Audit
Monthly review:
- Run test suite
- Check for regressions
- Update for new requirements
- Archive unused agents
Iterating on Subagents
Guide to improving existing subagents based on observed behavior.
---
Table of Contents
- Improvement Workflow
- Common Issues and Fixes
- Prompt Refinement Techniques
- Version Control for Agents
- A/B Testing Agents
- Incremental Improvement
- When to Redesign vs. Iterate
- Feedback Loop
---
Improvement Workflow
1. Identify Issue → What's not working?
2. Diagnose Cause → Why is it happening?
3. Plan Fix → What change will help?
4. Implement → Make the change
5. Test → Verify improvement
6. Monitor → Watch for regressionsCommon Issues and Fixes
Issue: Agent Doesn't Trigger
Symptoms:
- Claude ignores the agent even for matching tasks
- Have to explicitly say "use the X agent"
Diagnosis:
- Description too narrow?
- Name has typo?
- Agent not loaded (manual file creation)?
Fixes:
# Before: too specific
description: "Reviews Python code for PEP8 compliance"
# After: broader trigger
description: "Code review specialist for quality, style, and best practices.
Use proactively after writing or modifying code."Add "use proactively" to encourage automatic delegation:
description: "Debugger. Use proactively when encountering errors."Issue: Agent Over-Triggers
Symptoms:
- Delegates to agent for unrelated tasks
- Takes over when main conversation would be better
Diagnosis:
- Description too vague?
- Overlaps with other agents?
Fixes:
# Before: too broad
description: "Helps with code"
# After: specific scope
description: "Security vulnerability scanner for authentication and
authorization code. Use when reviewing auth modules or after
security-related changes."Add explicit boundaries:
---
name: security-reviewer
description: "Security review for auth code only. NOT for general code review."
---Issue: Wrong Output Format
Symptoms:
- Output doesn't match expected structure
- Inconsistent formatting across runs
Diagnosis:
- Format not specified clearly?
- No examples in prompt?
Fixes:
Add explicit format specification:
## Output Format
Provide your findings as:
### Critical Issues
- [Issue]: [Location] - [Fix]
### Warnings
- [Issue]: [Location] - [Fix]
### Suggestions
- [Suggestion]: [Location]Add an example:
## Example Output
### Critical Issues
- SQL Injection: auth.py:42 - Use parameterized queries
### Warnings
- Missing validation: user.py:15 - Add input sanitization
### Suggestions
- Consider adding rate limiting to login endpointIssue: Incomplete Task Execution
Symptoms:
- Stops before finishing
- Misses important steps
- Partial analysis
Diagnosis:
- Workflow not explicit enough?
- Missing checklist?
- Scope too large?
Fixes:
Add numbered steps:
When invoked, follow these steps IN ORDER:
1. Run git diff to identify changed files
2. Read each changed file completely
3. Analyze for issues using the checklist below
4. Compile findings by priority
5. Return formatted reportAdd completion checklist:
Before returning, verify:
- [ ] All changed files reviewed
- [ ] Each checklist item addressed
- [ ] Findings organized by priority
- [ ] Specific fixes providedIssue: Scope Creep
Symptoms:
- Agent does more than asked
- Modifies files when should only read
- Makes decisions it shouldn't
Diagnosis:
- Tools too permissive?
- Prompt doesn't set boundaries?
Fixes:
Restrict tools:
# Before: full access
tools: Read, Write, Edit, Bash, Glob, Grep
# After: read-only
tools: Read, Glob, GrepAdd explicit constraints:
## Constraints
- DO NOT modify any files
- DO NOT make implementation decisions
- ONLY report findings, do not fix them
- ASK for clarification if requirements are unclearIssue: Poor Context Efficiency
Symptoms:
- Reads too many files
- Returns verbose output
- Slow execution
Diagnosis:
- No efficiency guidance?
- Returns raw data instead of synthesis?
Fixes:
Add efficiency instructions:
## Efficiency Guidelines
- Use Grep to locate relevant code before reading entire files
- Stop searching once you have enough information
- Synthesize findings into actionable summary
- Do NOT return raw search resultsSpecify return format:
## Return to Parent
Return a concise summary (max 500 words) containing:
- Key findings (bullet points)
- Recommended actions
- Files examined (list only, not contents)Prompt Refinement Techniques
Adding Examples
Examples clarify expectations:
## Examples
### Input
"Review the authentication module"
### Expected Behavior
1. Locate auth-related files
2. Check for common vulnerabilities
3. Return prioritized findings
### Example Output
**Critical:** Password stored in plaintext (auth/user.py:23)
**Warning:** No rate limiting on login endpoint
**Suggestion:** Consider adding 2FA supportUsing Checklists
Checklists ensure consistency:
## Review Checklist
### Security
- [ ] No hardcoded credentials
- [ ] Input validation present
- [ ] SQL injection protected
- [ ] XSS prevented
### Quality
- [ ] Clear naming
- [ ] No code duplication
- [ ] Error handling present
- [ ] Tests existConditional Instructions
Handle different scenarios:
## Workflow
IF reviewing new code:
1. Focus on design and patterns
2. Check for test coverage
3. Verify documentation
IF reviewing bug fix:
1. Verify the fix addresses root cause
2. Check for regression risks
3. Ensure tests cover the fix
IF reviewing refactor:
1. Verify behavior unchanged
2. Check for improvements
3. Validate test coverage maintainedVersion Control for Agents
Keep track of changes:
---
name: code-reviewer
description: "..."
# version: 2.1
# changelog:
# 2.1 - Added security checklist
# 2.0 - Restructured output format
# 1.0 - Initial version
---Or maintain separate files:
.claude/agents/
├── code-reviewer.md # Current version
├── code-reviewer-v1.md # Previous version (backup)
└── code-reviewer-experimental.md # Testing new approachA/B Testing Agents
Test changes before committing:
1. Create variant with different name:
---
name: code-reviewer-v2
description: "Code reviewer (experimental v2). Use for testing new format."
---2. Run same tasks with both versions 3. Compare results 4. Keep winner, archive loser
Incremental Improvement
Don't change everything at once:
Week 1: Fix trigger accuracy
Week 2: Improve output format
Week 3: Add efficiency guidelines
Week 4: Refine checklistsTest after each change to isolate impact.
When to Redesign vs. Iterate
Iterate when:
- Core concept is sound
- Issues are specific and fixable
- Changes are incremental
Redesign when:
- Fundamental approach is wrong
- Multiple major issues
- Requirements have changed significantly
- Agent tries to do too much (split it)
Feedback Loop
Establish continuous improvement:
Use agent → Observe issues → Document → Fix → Test → RepeatKeep a log of issues and fixes:
## Agent: code-reviewer
### Issue Log
| Date | Issue | Fix | Result |
|------|-------|-----|--------|
| 2024-01-15 | Over-triggers | Narrowed description | Fixed |
| 2024-01-20 | Missing security checks | Added checklist | Fixed |
| 2024-01-25 | Verbose output | Added synthesis step | Improved |Subagent Patterns
Common patterns and real-world examples for effective subagent design.
---
Table of Contents
- Architecture Patterns
- Example Agents
- Human-in-the-Loop Patterns
- Multi-Agent Coordination
- Anti-Patterns to Avoid
---
Architecture Patterns
Single-Purpose Agents
Each agent does ONE thing well.
code-reviewer → Reviews code quality
security-auditor → Checks for vulnerabilities
test-runner → Executes and analyzes tests
debugger → Diagnoses and fixes issuesBenefits:
- Clear triggers
- Focused prompts
- Predictable behavior
Anti-pattern: Swiss Army knife agent that "helps with everything."
Pipeline Pattern
Chain agents for complex workflows (PM → Architect → Implementer).
1. pm-spec → Writes requirements, asks questions
2. architect → Validates design, produces ADR
3. implementer → Writes code, runs testsHandoff mechanism:
## Status Management
- Set status to READY_FOR_ARCH when spec complete
- Architect picks up items with READY_FOR_ARCH status
- Set status to READY_FOR_BUILD when ADR completeUse hooks to suggest next steps:
# In settings.json
hooks:
SubagentStop:
- hooks:
- type: command
command: "./scripts/suggest-next-agent.sh"Parallel Research
Spawn multiple agents to investigate independently.
Research authentication, database, and API modules in parallelMain agent delegates:
Task(Explore) → auth module
Task(Explore) → database module
Task(Explore) → API moduleEach returns a summary; main agent synthesizes.
Caution: Many parallel agents returning detailed results can consume significant context. Design agents to return concise summaries.
Master-Clone Pattern
Use general-purpose clones instead of specialized agents.
Main agent → Task(general-purpose) → Clone handles subtask
→ Task(general-purpose) → Another cloneBenefits:
- Clones inherit full context from CLAUDE.md
- Main agent decides delegation dynamically
- No need to predefine specialized agents
When to use:
- Tasks vary widely
- Can't predict specializations needed
- Want maximum flexibility
When to use specialized agents instead:
- Consistent task types
- Need strict tool restrictions
- Want optimized prompts for domain
Read-Only Explorer
Exploration agent that cannot modify files.
---
name: codebase-explorer
description: "Explores and explains codebase structure. Use for understanding
code, finding files, or answering questions about the codebase."
tools: Read, Grep, Glob, Bash
permissionMode: plan
---
=== CRITICAL: READ-ONLY MODE ===
You are STRICTLY PROHIBITED from:
- Creating new files
- Modifying existing files
- Running commands that change state
Your role is EXCLUSIVELY to search and analyze existing code.Domain Expert
Agent specialized in a technology/domain.
---
name: postgres-expert
description: "PostgreSQL specialist for query optimization, schema design,
and database performance. Use when working with .sql files or database issues."
tools: Read, Grep, Glob, Bash
model: sonnet
---
You are a PostgreSQL expert with deep knowledge of:
- Query optimization and EXPLAIN ANALYZE
- Index design and maintenance
- Schema normalization
- Performance tuning
- pg_stat views and monitoring
When asked about database issues:
1. Understand the problem context
2. Analyze relevant SQL/schemas
3. Provide specific, actionable recommendations
4. Include example queries when helpfulExample Agents
These examples demonstrate effective prompt structure. Apply prompt-engineering techniques: numbered steps, checklists, explicit output format, and XML tags for complex inputs.
Code Reviewer
---
name: code-reviewer
description: "Expert code review specialist. Proactively reviews code for
quality, security, and maintainability. Use immediately after writing
or modifying code."
tools: Read, Grep, Glob, Bash
model: inherit
---
You are a senior code reviewer ensuring high standards of code quality.
When invoked:
1. Run git diff to see recent changes
2. Focus on modified files
3. Begin review immediately
Review checklist:
- Code is clear and readable
- Functions and variables are well-named
- No duplicated code
- Proper error handling
- No exposed secrets or API keys
- Input validation implemented
- Good test coverage
- Performance considerations addressed
Provide feedback organized by priority:
- Critical issues (must fix)
- Warnings (should fix)
- Suggestions (consider improving)
Include specific examples of how to fix issues.Debugger
---
name: debugger
description: "Debugging specialist for errors, test failures, and unexpected
behavior. Use proactively when encountering any issues."
tools: Read, Edit, Bash, Grep, Glob
---
You are an expert debugger specializing in root cause analysis.
When invoked:
1. Capture error message and stack trace
2. Identify reproduction steps
3. Isolate the failure location
4. Implement minimal fix
5. Verify solution works
Debugging process:
- Analyze error messages and logs
- Check recent code changes
- Form and test hypotheses
- Add strategic debug logging
- Inspect variable states
For each issue, provide:
- Root cause explanation
- Evidence supporting the diagnosis
- Specific code fix
- Testing approach
- Prevention recommendations
Focus on fixing the underlying issue, not the symptoms.Security Auditor
---
name: security-auditor
description: "Security vulnerability scanner for code and configurations.
Use proactively after changes to auth, API, or data handling code."
tools: Read, Grep, Glob
model: opus
permissionMode: plan
---
You are a security specialist performing vulnerability assessment.
=== READ-ONLY MODE ===
Do NOT modify any files. Report findings only.
Security checklist:
- [ ] Authentication/authorization flaws
- [ ] Injection vulnerabilities (SQL, XSS, command)
- [ ] Sensitive data exposure
- [ ] Security misconfigurations
- [ ] Insecure dependencies
- [ ] Cryptographic issues
- [ ] Logging/monitoring gaps
For each vulnerability:
- Severity: Critical / High / Medium / Low
- Location: File and line number
- Description: What the vulnerability is
- Impact: What could happen if exploited
- Remediation: Specific fix with code example
Output format:
## Critical
- [Vulnerability] at [location]: [description]
Impact: [impact]
Fix: [remediation]
## High
...Test Runner
---
name: test-runner
description: "Executes tests and analyzes results. Use proactively after
writing or modifying code to verify correctness."
tools: Bash, Read, Grep, Glob
---
You are a testing specialist ensuring code quality through comprehensive testing.
When invoked:
1. Identify the test framework and commands
2. Run the relevant test suite
3. Analyze results
4. Report findings
Test execution guidelines:
- Run tests related to changed files first
- Capture full output including stack traces
- Note flaky tests vs. consistent failures
Report format:
## Test Results
- Passed: X
- Failed: Y
- Skipped: Z
## Failures
### [Test Name]
- Location: [file:line]
- Error: [message]
- Likely cause: [analysis]
- Suggested fix: [recommendation]
## Coverage Notes
[If coverage data available]Documentation Writer
---
name: doc-writer
description: "Technical documentation specialist. Use when creating or
updating README, API docs, or code documentation."
tools: Read, Write, Edit, Glob, Grep
model: sonnet
---
You are a technical writer creating clear, accurate documentation.
Documentation principles:
- Start with the "why" before the "how"
- Use concrete examples
- Keep language simple and direct
- Structure for scannability (headers, lists)
- Include code samples that actually work
When documenting code:
1. Read the code to understand functionality
2. Identify the audience (users vs. developers)
3. Draft documentation following conventions
4. Include examples and edge cases
5. Review for accuracy and completeness
Output should be:
- Accurate (matches actual behavior)
- Complete (covers important use cases)
- Clear (understandable by target audience)
- Consistent (follows project conventions)Database Query Validator
---
name: db-reader
description: "Execute read-only database queries. Use when analyzing data
or generating reports. Cannot modify data."
tools: Bash
hooks:
PreToolUse:
- matcher: "Bash"
hooks:
- type: command
command: "./scripts/validate-readonly-query.sh"
---
You are a database analyst with READ-ONLY access.
Execute SELECT queries to answer questions about the data.
When asked to analyze data:
1. Identify which tables contain relevant data
2. Write efficient SELECT queries with appropriate filters
3. Present results clearly with context
You CANNOT modify data. If asked to INSERT, UPDATE, DELETE, or modify
schema, explain that you only have read access and suggest alternatives.
Query guidelines:
- Use appropriate indexes
- Limit result sets
- Include comments for complex queries
- Format output for readabilityHook script (./scripts/validate-readonly-query.sh):
#!/bin/bash
INPUT=$(cat)
COMMAND=$(echo "$INPUT" | jq -r '.tool_input.command // empty')
if echo "$COMMAND" | grep -iE '\b(INSERT|UPDATE|DELETE|DROP|CREATE|ALTER|TRUNCATE)\b' > /dev/null; then
echo "Blocked: Write operations not allowed. Use SELECT queries only." >&2
exit 2
fi
exit 0Human-in-the-Loop Patterns
Approval Gates
Hook suggests next step; human approves:
# Hook prints suggestion
echo "Use the architect-review subagent on 'feature-x'."
# Human copies and pastes to approveStatus-Based Workflow
## Queue File: enhancements/_queue.json
{
"feature-a": "READY_FOR_ARCH",
"feature-b": "READY_FOR_BUILD",
"feature-c": "DONE"
}Agents check status before starting; update status when done.
Review Checkpoints
## Pre-Implementation Checkpoint
Before implementing, human signs off on ADR.
## Pre-PR Checkpoint
Before creating PR, human reviews implementation summary.Multi-Agent Coordination
Sequential Chain
Task 1 → Agent A → Output 1
↓
Task 2 → Agent B → Output 2
↓
Task 3 → Agent C → Final ResultParallel Fan-Out
→ Agent A → Summary A
/ \
Main Task → Agent B → Summary B → Synthesize
\ /
→ Agent C → Summary CSpecialist + Generalist
Specialist agents for known task types
↓
Generalist (Task) for everything elseAnti-Patterns to Avoid
God Agent
Agent that does everything. Hard to trigger correctly, poor at all tasks.
Vague Description
"Helps with code" — over-triggers, unclear when to use.
Execution in Description
"Steps: 1. Read 2. Analyze 3. Report" — belongs in body, not description.
Over-Scoped Tools
Granting Write/Edit to read-only reviewers.
No Output Format
Agent returns inconsistent, unparseable results.
Infinite Loop Risk
Agent that spawns agents that spawn agents. (Subagents cannot spawn subagents.)
Context Hogging
Agent that reads entire codebase for simple queries.
Subagent Specification
Complete reference for subagent frontmatter fields and constraints.
---
Table of Contents
- File Format
- Required Fields
- Optional Fields
- System Prompt (Body)
- Storage Locations
- CLI-Defined Agents
- Validation Checklist
---
File Format
Subagents are Markdown files with YAML frontmatter:
---
name: agent-name
description: What it does and when to use it
tools: Read, Grep, Glob
model: sonnet
---
System prompt content here...The frontmatter defines metadata and configuration. The body becomes the system prompt that guides the subagent's behavior.
Required Fields
name
Unique identifier for the subagent.
Constraints:
- Lowercase letters and hyphens only
- Max 64 characters
- No
<or>characters - Cannot contain "anthropic" or "claude"
# Valid
name: code-reviewer
name: db-query-validator
# Invalid
name: Code_Reviewer # uppercase, underscore
name: my<agent> # special characters
name: claude-helper # contains "claude"description
When Claude should delegate to this subagent. This is the ONLY thing Claude sees when deciding whether to use the agent.
Constraints:
- Max 1024 characters
- No
<or>characters
Must include:
- What the subagent does (1 sentence)
- When to use it (specific contexts, triggers)
Should NOT include:
- Execution instructions (belongs in body)
- Keywords lists (redundant if well-written)
- Success criteria (belongs in body)
# Bad: vague
description: Helps with code
# Bad: execution details in description
description: "Review code. Steps: 1. Read files 2. Find issues 3. Report"
# Good: clear trigger conditions
description: "Expert code review specialist. Proactively reviews code for
quality, security, and maintainability. Use immediately after writing
or modifying code."Optional Fields
tools
Allowlist of tools the subagent can use. If omitted, inherits all tools from the main conversation (including MCP tools).
# Read-only agent
tools: Read, Grep, Glob
# Full access (explicit)
tools: Read, Write, Edit, Bash, Glob, Grep
# With specific MCP tools
tools: Read, Grep, mcp__slack__search_messagesAvailable built-in tools:
Read— Read filesWrite— Create/overwrite filesEdit— Modify existing filesBash— Execute shell commandsGlob— Find files by patternGrep— Search file contentsWebFetch— Fetch web contentWebSearch— Search the webTask— Spawn subagents (main agent only)NotebookEdit— Edit Jupyter notebooks
disallowedTools
Denylist of tools to remove from inherited or specified list.
# Inherit all tools except Write and Edit
disallowedTools: Write, EditUse disallowedTools when you want most tools but need to exclude a few.
model
Which Claude model the subagent uses.
| Value | Behavior |
|---|---|
sonnet | Use Claude Sonnet |
opus | Use Claude Opus |
haiku | Use Claude Haiku (fast, cheap) |
inherit | Use same model as main conversation |
| (omitted) | Defaults to inherit |
# Fast exploration
model: haiku
# Complex reasoning
model: opus
# Match parent
model: inheritModel selection guidelines:
haiku— Quick tasks, search, documentationsonnet— Everyday coding, debugging, refactoringopus— Deep reasoning, architecture, security audits
permissionMode
How the subagent handles permission prompts.
| Mode | Behavior |
|---|---|
default | Standard permission checking |
acceptEdits | Auto-accept file edits |
dontAsk | Auto-deny prompts (allowed tools still work) |
bypassPermissions | Skip all permission checks |
plan | Plan mode (read-only exploration) |
# Read-only exploration
permissionMode: plan
# Auto-accept edits (use with caution)
permissionMode: acceptEdits⚠️ Security Warning:
bypassPermissionsskips ALL permission checks including file writes
and command execution. Only use for trusted, well-tested agents in controlled environments.
acceptEditsauto-accepts file modifications — ensure the agent's
tools and prompt are sufficiently constrained.
- If parent uses
bypassPermissions, child agents inherit it and
cannot override to a more restrictive mode.
- Prefer
planmode for read-only agents to enforce safety at the
permission level, not just in the prompt.
skills
Skills to inject into the subagent's context at startup.
skills:
- api-conventions
- error-handling-patternsThe full skill content is injected, not just made available for invocation. Subagents don't inherit skills from parent; list them explicitly.
hooks
Lifecycle hooks scoped to this subagent.
hooks:
PreToolUse:
- matcher: "Bash"
hooks:
- type: command
command: "./scripts/validate-command.sh"
PostToolUse:
- matcher: "Edit|Write"
hooks:
- type: command
command: "./scripts/run-linter.sh"Supported events in frontmatter:
PreToolUse— Before tool execution (matcher = tool name)PostToolUse— After tool execution (matcher = tool name)Stop— When subagent finishes (converted toSubagentStop)
See Claude Code hooks documentation for full schema.
System Prompt (Body)
Everything after the frontmatter becomes the subagent's system prompt. Subagents receive ONLY this prompt plus basic environment details, not the full Claude Code system prompt.
Best practices:
- Start with role definition
- Include clear workflow steps
- Specify output format
- Add checklists for consistency
- Keep focused on single responsibility
---
name: code-reviewer
description: Reviews code for quality and security
tools: Read, Grep, Glob, Bash
---
You are a senior code reviewer ensuring high standards.
When invoked:
1. Run git diff to see recent changes
2. Focus on modified files
3. Begin review immediately
Review checklist:
- Code is clear and readable
- No exposed secrets or API keys
- Proper error handling
- Good test coverage
Provide feedback organized by priority:
- Critical issues (must fix)
- Warnings (should fix)
- Suggestions (consider improving)
Include specific examples of how to fix issues.Storage Locations
| Location | Scope | Priority |
|---|---|---|
--agents CLI flag | Session only | 1 (highest) |
.claude/agents/ | Current project | 2 |
~/.claude/agents/ | All projects | 3 |
Plugin agents/ | Where plugin enabled | 4 (lowest) |
When multiple agents share the same name, higher priority wins.
CLI-Defined Agents
Pass agents as JSON when launching Claude Code:
claude --agents '{
"code-reviewer": {
"description": "Expert code reviewer. Use proactively after changes.",
"prompt": "You are a senior code reviewer...",
"tools": ["Read", "Grep", "Glob", "Bash"],
"model": "sonnet"
}
}'Use prompt for the system prompt (equivalent to markdown body). Session-only, not saved to disk.
Validation Checklist
Before deploying a subagent:
- [ ]
nameis lowercase with hyphens only - [ ]
namedoesn't contain "anthropic" or "claude" - [ ]
descriptionexplains what AND when (under 1024 chars) - [ ]
descriptionhas no execution instructions - [ ]
toolsis minimal (only what's needed) - [ ]
modelmatches task complexity - [ ] System prompt is focused on single responsibility
- [ ] Output format is clearly specified
Troubleshooting Subagents
Diagnose and fix common subagent problems.
---
Table of Contents
---
Quick Diagnosis
| Symptom | Likely Cause | Solution |
|---|---|---|
| Agent never triggers | Name typo, vague description | Check spec, broaden description |
| Agent triggers too often | Description too broad | Narrow scope, add boundaries |
| Wrong output format | No format spec in prompt | Add explicit format + example |
| Stops mid-task | Unclear workflow, no checklist | Add numbered steps, completion criteria |
| Scope creep | Too many tools, no constraints | Restrict tools, add boundaries |
| Permission errors | Wrong tools granted | Check tools field, add needed tools |
| Hook not firing | Wrong event/matcher | Check hooks configuration |
| Agent not loaded | Manual file not reloaded | Restart session or use /agents |
Detailed Troubleshooting
Agent Not Found / Never Triggers
Symptoms:
- Claude says it doesn't know about the agent
- Have to explicitly invoke by name every time
- Agent doesn't appear in
/agentslist
Diagnostic steps:
1. Check file location:
# Project-level
ls -la .claude/agents/
# User-level
ls -la ~/.claude/agents/2. Check file extension: Must be .md (not .txt, .yaml, etc.)
3. Check frontmatter syntax:
---
name: my-agent # Required
description: "..." # Required
---Common YAML errors:
- Missing
---delimiters - Incorrect indentation
- Unquoted special characters
4. Check name format:
# Valid
name: code-reviewer
name: my-agent-v2
# Invalid
name: Code_Reviewer # uppercase, underscore
name: my agent # space
name: <agent> # special chars5. Reload the agent:
- Restart Claude Code session, OR
- Run
/agentsto force reload
Agent Triggers Incorrectly
Over-triggering (false positives):
The agent activates for unrelated tasks.
Fix: Narrow the description:
# Before
description: "Helps with code"
# After
description: "Security audit for authentication modules only.
Use when reviewing auth code or after security-related changes."Under-triggering (false negatives):
The agent doesn't activate for matching tasks.
Fix: Broaden the description and add trigger phrases:
# Before
description: "Reviews Python PEP8 compliance"
# After
description: "Code review specialist for style, quality, and best practices.
Use proactively after writing or modifying code in any language."Tools Not Working
Symptoms:
- "Tool not available" errors
- Agent can't perform expected actions
- Unexpected permission prompts
Diagnostic steps:
1. Check `tools` field:
# Explicit tools list
tools: Read, Grep, Glob
# Or omit to inherit all
# (no tools field = inherit from parent)2. Check tool names are exact:
# Correct
tools: Read, Write, Edit, Bash, Glob, Grep
# Wrong
tools: read, write # lowercase
tools: ReadFile # wrong name3. Check `disallowedTools` conflict:
# Conflicting configuration
tools: Read, Write
disallowedTools: Write # Write is both allowed and disallowed4. Check permission mode:
# May block tools
permissionMode: dontAsk # auto-denies permission promptsOutput Format Problems
Symptoms:
- Inconsistent formatting
- Missing expected sections
- Wrong structure
Fix 1: Add explicit format specification:
## Output Format
Your response MUST follow this exact structure:
### Summary
[1-2 sentence overview]
### Findings
- **Critical:** [issue] at [location]
- **Warning:** [issue] at [location]
### Recommendations
1. [First action]
2. [Second action]Fix 2: Add an example:
## Example Output
### Summary
Found 2 security issues in the auth module.
### Findings
- **Critical:** SQL injection in login() at auth.py:42
- **Warning:** Missing rate limiting at auth.py:15
### Recommendations
1. Use parameterized queries for all database calls
2. Add rate limiting to prevent brute force attacksFix 3: Use prefill-like guidance:
Begin your response with "## Summary" and follow the format exactly.Task Incomplete
Symptoms:
- Agent stops before finishing
- Missing steps in workflow
- Partial analysis
Fix 1: Add numbered steps:
Execute these steps IN ORDER:
1. List all files matching the pattern
2. Read each file completely
3. Analyze using the checklist below
4. Compile findings
5. Return formatted report
Do not skip any steps.Fix 2: Add completion checklist:
Before returning your response, verify:
- [ ] All matching files examined
- [ ] Each checklist item addressed
- [ ] Findings organized by priority
- [ ] Specific recommendations provided
If any item is incomplete, continue working.Fix 3: Set explicit completion criteria:
Your task is COMPLETE when:
- All changed files have been reviewed
- Security checklist is fully addressed
- Output follows the specified format
Do not return until all criteria are met.Hooks Not Firing
Symptoms:
- Hook commands don't execute
- No stdout from hook scripts
- Expected validation not happening
Diagnostic steps:
1. Check hook configuration in frontmatter:
hooks:
PreToolUse:
- matcher: "Bash"
hooks:
- type: command
command: "./scripts/validate.sh"2. Check matcher pattern:
# Exact match
matcher: "Bash"
# Regex match
matcher: "Edit|Write"3. Check script is executable:
chmod +x ./scripts/validate.sh4. Check script path: Paths are relative to working directory.
5. Check hook event:
| Event | When |
|---|---|
PreToolUse | Before tool execution |
PostToolUse | After tool execution |
Stop | When agent finishes |
6. Test script manually:
./scripts/validate.sh
echo $? # Check exit codeContext/Memory Issues
Symptoms:
- Agent forgets earlier context
- Repeated searches for same information
- "I don't have access to..." for info it should have
Causes and fixes:
- Auto-compaction: Context may have been summarized.
- Set
CLAUDE_AUTOCOMPACT_PCT_OVERRIDElower - Use more concise prompts
- Subagent isolation: Subagents have own context, don't inherit conversation.
- Pass necessary context in the prompt/task description
- Use
skillsfield to preload required knowledge
- Fresh start: Each subagent invocation starts fresh (unless resumed).
- Use resume feature:
resume: agent-id - Or pass context explicitly
Performance Issues
Symptoms:
- Agent is very slow
- Excessive tool calls
- Reading too many files
Fix 1: Add efficiency instructions:
## Efficiency
- Use Grep to locate relevant code BEFORE reading entire files
- Stop searching once you have sufficient information
- Prefer targeted searches over broad scans
- Maximum 10 files per analysis unless explicitly neededFix 2: Restrict model:
# For simple tasks
model: haiku # Faster, cheaperFix 3: Narrow tool scope:
# Remove unnecessary tools
tools: Read, Grep # Not Bash if not neededError Messages
"Agent not found"
Agent 'xxx' not found- Check file exists in correct location
- Check name matches filename (minus .md)
- Restart session to reload
"Tool not available"
Tool 'Write' is not available to this agent- Add tool to
toolsfield - Remove from
disallowedToolsif present - Check parent permissions
"Permission denied"
Permission denied for operation- Check
permissionModesetting - Verify user has granted permission
- Consider
acceptEditsorbypassPermissionsif appropriate
"Maximum turns exceeded"
Agent reached maximum turns without completing- Task may be too complex for single agent
- Add clearer completion criteria
- Split into multiple agents
Debug Mode
Enable verbose logging:
CLAUDE_CODE_DEBUG=1 claudeOr trace LLM traffic (advanced):
- Set up proxy to inspect requests
- Check actual prompts being sent
Getting Help
If still stuck:
- Check
/agentsoutput for agent status - Review Claude Code docs: https://docs.anthropic.com/en/docs/claude-code/sub-agents
- Report issues: https://github.com/anthropics/claude-code/issues