
Agent Patterns
- 72 installs
- 14 repo stars
- Updated March 2, 2026
- oakoss/agent-skills
Helps with ai & agent building tasks during AI-assisted development.
About
agent-patterns is a Claude Code skill for ai & agent building. It helps solo builders move faster with AI-assisted coding.
- agent-patterns
- AI & Agent Building
- AI-coding skill
Agent Patterns by the numbers
- 72 all-time installs (skills.sh)
- +2 installs in the week ending Aug 4, 2026 (Skillselion tracking)
- Ranked #5,635 of 16,546 AI & Agent Building skills by installs in the Skillselion catalog
- Data as of Aug 4, 2026 (Skillselion catalog sync)
npx skills add https://github.com/oakoss/agent-skills --skill agent-patternsAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 72 |
|---|---|
| repo stars | ★ 14 |
| Last updated | March 2, 2026 |
| Repository | oakoss/agent-skills ↗ |
What it does
Helps with ai & agent building tasks during AI-assisted development.
Files
Agent Patterns
Multi-agent design, delegation, and orchestration in Claude Code and AI-assisted development. Default to fungible agents for large-scale software dev; use specialized agents only for peer review or discourse-based workflows.
Subagents in Claude Code are specialized AI assistants that run in isolated context windows with custom system prompts, specific tool access, and independent permissions. They preserve main conversation context by keeping exploration, test runs, and verbose operations out of the primary thread.
Key constraint: subagents cannot spawn other subagents. Multi-step orchestration requires chaining subagents from the main conversation.
Quick Reference
| Pattern | Description | When to Use |
|---|---|---|
| Fungible swarm | Identical agents pick tasks from a shared board | Large-scale software dev, resilient systems |
| Sequential pipeline | Each agent builds on previous output | Multi-step workflows with clear dependencies |
| Hierarchical | Manager decomposes, workers execute in parallel | Complex tasks with independent subtasks |
| Peer collaboration | Agents iterate until consensus | Code review, quality-critical outputs |
| Orchestrator delegation | Main conversation chains subagents | Multi-phase workflows, parallel specialists |
| Two-stage review | Spec compliance check, then code quality check | High-stakes code, complex requirements |
| Question-first delegation | Agent asks clarifying questions before proceeding | Ambiguous tasks, expensive-to-redo work |
| Review loop enforcement | Fix-review cycle with max iteration escalation | Any review workflow needing convergence |
| Built-in Subagent | Model | Tools | Purpose |
|---|---|---|---|
| Explore | Haiku | Read-only | File discovery, code search, codebase exploration |
| Plan | Inherits | Read-only | Codebase research during plan mode |
| General-purpose | Inherits | All tools | Complex research, multi-step operations |
| Bash | Inherits | Terminal | Running terminal commands in separate context |
| Claude Code Guide | Haiku | Read-only | Answering questions about Claude Code features |
| Configuration | Value |
|---|---|
| Custom agent location | .claude/agents/*.md (project), ~/.claude/agents/*.md (user) |
| CLI agents | --agents '{...}' (session only, JSON format) |
| Plugin agents | Plugin agents/ directory (lowest priority) |
| Required fields | name, description |
| Optional fields | tools, disallowedTools, model, permissionMode, skills, hooks, color |
| Model values | sonnet, opus, haiku, inherit (default) |
| Permission modes | default, acceptEdits, dontAsk, bypassPermissions, plan |
| Nesting limit | Subagents cannot spawn other subagents (one level only) |
| Foreground vs background | Foreground blocks main conversation; background runs concurrently |
| Batch size | 5-8 items per agent (standard tasks) |
| Parallel agents | 2-4 simultaneously |
When to Use Subagents vs Main Conversation
| Use Subagents When | Use Main Conversation When |
|---|---|
| Task produces verbose output (test suites, logs, API responses) | Task needs frequent back-and-forth or iterative refinement |
| Enforcing specific tool restrictions or permissions | Multiple phases share significant context |
| Work is self-contained and can return a summary | Making a quick, targeted change |
| Parallel independent research paths | Latency matters (subagents start fresh and gather context) |
Tool Access Patterns
| Agent Role | Recommended Tools | Rationale |
|---|---|---|
| Read-only reviewer | Read, Grep, Glob | Cannot modify code; safe for audits |
| File creator | Read, Write, Edit, Glob, Grep | NO Bash; avoids heredoc approval spam |
| Script runner | Read, Write, Edit, Glob, Grep, Bash | Full access for build/deploy tasks |
| Research agent | Read, Grep, Glob, WebFetch, WebSearch | External data access for documentation lookup |
Subagents inherit all tools by default (including MCP tools). Use tools as an allowlist or disallowedTools as a denylist to restrict access. MCP tools are not available in background subagents.
Common Mistakes
| Mistake | Correct Pattern |
|---|---|
| Expecting subagents to spawn sub-subagents | Subagents cannot nest; chain subagents from the main conversation instead |
| Giving Bash tool to agents that only create files | Use Write and Edit tools only; Bash causes approval spam from heredoc usage |
Omitting disallowedTools for sensitive operations | Use disallowedTools to explicitly deny dangerous tools even when inheriting |
| Spawning too many agents (5+) for a small task | Start with 2-3 agents; coordination overhead outweighs benefit at higher counts |
| Burying critical instructions past line 300 of agent prompt | Put critical rules immediately after frontmatter; models deprioritize late instructions |
| Using specialized agents for large-scale software dev | Use fungible agents with a shared task board; specialized agents create single points of failure |
| Not including "FIX issues found" in delegation prompts | Without explicit action directive, agents only report problems without making changes |
| Setting model to Haiku for content generation | Default to Sonnet; Haiku only for script execution, fast lookups, or pass/fail checks |
| Not writing clear descriptions for custom agents | Claude uses the description field to decide when to auto-delegate; vague descriptions prevent delegation |
| Using MCP tools in background subagents | MCP tools are not available in background subagents; run in foreground instead |
| Not preloading skills into subagents | Subagents do not inherit skills from the parent; list them explicitly in the skills field |
Delegation
- Explore codebase before designing agent prompts: Claude auto-delegates to the built-in Explore subagent (Haiku, read-only) for file discovery and code search; supports quick, medium, and very thorough modes
- Plan multi-agent architecture for complex projects: Use plan mode; Claude delegates research to the Plan subagent before presenting a plan
- Execute batch operations across many files: Chain General-purpose subagents from the main conversation with identical prompts and non-overlapping item lists
- Isolate high-volume operations: Delegate test runs, log processing, or doc fetching to subagents to keep verbose output out of your main context
- Run parallel research: Spawn multiple subagents simultaneously for independent investigations; Claude synthesizes findings when all complete
- Resume interrupted work: Ask Claude to continue a previous subagent; resumed agents retain full conversation history including tool calls and reasoning
For project-level workflow sequencing, phase-gate validation, goal decomposition, and capability scoring, use the orchestration skill.References
- Agent types and design patterns
- Delegation patterns and batch workflows
- Sub-agent configuration and prompt engineering
- Communication and orchestration patterns
- Troubleshooting and anti-patterns
Agent Types and Design Patterns
Pattern 1: Fungible Agent Swarm
All agents are identical and interchangeable. Each picks the highest-priority available task. No role assignment needed.
When to use: Software development at scale, task-based workflows, systems that need resilience to agent failure.
How it works:
1. Front-load planning into structured tasks (beads/issues with dependency graphs) 2. Spawn N identical agents with the same initial prompt 3. Each agent reads the task board and picks the next unblocked task 4. If an agent dies, another picks up its in-progress task
Properties:
| Property | Fungible Agents | Specialized Agents |
|---|---|---|
| Failure handling | Simple (any agent works) | Complex (need matching) |
| Scaling | Just add more | Requires role balancing |
| Single point of failure | No | Yes (each role) |
| Coordination overhead | Low (via task board) | High (role dependencies) |
| Human involvement | Front-loaded in planning | Ongoing |
Initial prompt template (same for all agents):
Read ALL of AGENTS.md and README.md carefully. Understand the codebase architecture.
Register with agent communication system. Check for messages and respond promptly.
Use the task board to find your next highest-priority unblocked task.
Mark tasks in-progress before starting. Inform other agents via messages.
When idle, check the task board for the next available task. Use ultrathink.When an agent fails: Start a new session with the same prompt. It reads the task board, sees what is in-progress or stuck, and either resumes or picks a new task. No special logic needed.
Pattern 2: Sequential Pipeline
Each agent builds on the previous agent's output.
User Query -> Researcher -> Analyst -> Writer -> Editor -> OutputWhen to use: Multi-step workflows with clear dependencies.
Pros: Clear dependencies, easy to debug. Cons: No parallelization, bottleneck at any stage.
Pattern 3: Hierarchical (Manager-Worker)
A manager decomposes work, workers execute in parallel, an aggregator combines results.
Manager Agent
/ | \
Worker 1 Worker 2 Worker 3
\ | /
Aggregator AgentWhen to use: Complex tasks with independent subtasks that benefit from parallelization.
Pattern 4: Peer Collaboration (Round Table)
Multiple agents iterate until consensus. Useful when review improves quality.
Coder <-> Reviewer <-> Tester -> ConsensusWhen to use: Code generation with review, quality-critical outputs. Cons: May not converge, expensive (multiple LLM calls per iteration).
Pattern 5: Agent Swarm (Exploration)
Multiple agents independently explore the solution space. A selector picks the best result.
When to use: Creative brainstorming, exploring multiple approaches.
Built-in Subagents
Claude Code includes built-in subagents that Claude automatically uses when appropriate:
| Subagent | Model | Tools | Purpose |
|---|---|---|---|
| Explore | Haiku | Read-only | File discovery, code search, codebase exploration |
| Plan | Inherits | Read-only | Codebase research during plan mode |
| General-purpose | Inherits | All tools | Complex research, multi-step operations, code modifications |
| Bash | Inherits | Terminal | Running terminal commands in separate context |
| Claude Code Guide | Haiku | Read-only | Answering questions about Claude Code features |
Explore supports thoroughness levels: quick (targeted lookups), medium (balanced), very thorough (comprehensive).
Nesting Constraint
Subagents cannot spawn other subagents. If a workflow requires multi-step delegation, chain subagents from the main conversation. Each subagent completes its task and returns results to Claude, which then passes relevant context to the next subagent.
Choosing the Right Pattern
| Scenario | Recommended Pattern |
|---|---|
| Large codebase, many tasks | Fungible swarm |
| Multi-step data processing | Sequential pipeline |
| Independent subtasks needing parallelism | Hierarchical (chained from main conversation) |
| Code review, quality-critical output | Peer collaboration |
| Creative exploration, multiple approaches | Agent swarm |
| Multi-phase release workflow | Orchestrator delegation (chained subagents) |
Delegation Patterns and Batch Workflows
The Sweet Spot
Tasks that are repetitive but require judgment:
- Audit 70 skills checking versions against docs
- Update 50 files deciding what needs changing
- Research 10 frameworks evaluating trade-offs
Not a good fit: simple find-replace (no judgment), single complex tasks (not repetitive), tasks with cross-item dependencies (agents work independently).
Core Prompt Template
For each [item]:
1. Read [source file/data]
2. Verify with [external check]
3. Check [authoritative source]
4. Evaluate/score
5. FIX issues found
Items: [explicit list]
Working directory: [absolute path]"FIX issues found" is critical -- without it agents only report, with it they act.
Batch Sizing
| Batch Size | Use When |
|---|---|
| 3-5 items | Complex tasks (deep research, multi-step fixes) |
| 5-8 items | Standard tasks (audits, updates, validations) |
| 8-12 items | Simple tasks (version checks, format fixes) |
Launch 2-4 agents in parallel, each with their own batch.
Workflow
1. PLAN: Identify items, divide into batches
2. LAUNCH: Parallel Task calls with identical templates, different item lists
3. WAIT: Agents work in parallel (read -> verify -> check -> edit -> report)
4. REVIEW: Check agent reports, git status, spot-check diffs
5. COMMIT: Batch changes with meaningful changelog (one commit per category)Context Hygiene
The primary value of sub-agents is keeping the main context clean.
Without agents: A deploy workflow runs ~10 tool calls, consuming 500+ lines in main context. Over a session, this compounds.
With agents: The same workflow returns a 30-line summary. All verbose tool outputs and intermediate reasoning are discarded after the agent returns.
When this matters most:
- Repeatable workflows (deploy, migrate, audit, review)
- Verbose tool outputs (build logs, test results, API responses)
- Multi-step operations where only the final result matters
- Long sessions where context pressure builds up
Communication and Orchestration Patterns
Communication Methods
Shared Memory
All agents read/write to a shared state object. Simple but prone to race conditions.
Message Passing
Agents send structured messages to each other. Clear communication flow, traceable, but more complex.
Event-Driven
Agents subscribe to events and publish when done. Loose coupling, scalable, but harder to trace execution.
Task Board (Recommended for Fungible Swarms)
Agents read from a shared task board (beads, issues, or similar). Each agent claims work independently. No central assignment needed.
Orchestration via Chaining
Subagents cannot spawn other subagents. Orchestration works by chaining subagents from the main conversation:
Main conversation -> Subagent A (completes, returns results)
Main conversation -> Subagent B (uses A's results)
Main conversation -> Subagent C (uses B's results)
Main conversation synthesizes all resultsFor parallel work, ask Claude to spawn multiple subagents simultaneously:
Use separate subagents to research authentication, database, and API modules in parallelEach subagent explores its area independently, then Claude synthesizes the findings. This works best when the research paths do not depend on each other.
Custom Agent as Orchestrator Template
A custom agent can coordinate multi-step workflows by describing the steps in its system prompt. Claude chains subagent calls from the main conversation when instructed:
---
name: release-orchestrator
description: Coordinates release preparation by delegating to specialized agents.
tools: Read, Grep, Glob, Bash
---
You are a release orchestrator. When invoked:
1. Review uncommitted changes using git diff
2. Run the full test suite
3. Check documentation currency
4. Synthesize: Blockers / Warnings / Ready YES|NOQuestion-First Delegation Protocol
Before an agent starts work, it asks clarifying questions. The controller answers all questions before giving the "proceed" signal. This prevents wasted work from misunderstood tasks.
Protocol Steps
1. Controller sends task description to agent
2. Agent reads the task, identifies ambiguities
3. Agent returns a list of clarifying questions (does NOT start work)
4. Controller answers all questions
5. Controller sends explicit "proceed" signal
6. Agent begins implementation with full understandingWhen to Use Question-First
| Use Question-First | Skip It (Direct Delegation) |
|---|---|
| Task has ambiguous requirements | Task is mechanical and fully specified |
| Multiple valid interpretations exist | Agent has done identical work before |
| Wrong interpretation wastes significant work | Cost of redo is low (small edits) |
| Cross-cutting concerns need clarification | Batch operations with a proven template |
Agent Prompt for Question-First
---
name: cautious-implementer
description: Asks clarifying questions before starting work. Use for ambiguous tasks.
tools: Read, Write, Edit, Glob, Grep
---
Before starting ANY implementation:
1. Read the task description and all referenced files
2. List every assumption you are making
3. Ask clarifying questions for anything ambiguous
4. WAIT for answers before writing any code
Only begin implementation after receiving explicit confirmation.
Do NOT guess at requirements — ask instead.Context Bundling for Subagents
Provide full task text plus surrounding context rather than just a task title. Subagents start with empty context and cannot see the main conversation, so they need everything up front.
What to Include
| Context Element | Example | Why |
|---|---|---|
| Full task description | "Add rate limiting to the /api/users endpoint" | The actual work to do |
| Where it fits in the plan | "This is step 3 of 5 in the API hardening initiative" | Helps agent make consistent design decisions |
| Related decisions | "We chose token bucket over sliding window in step 1" | Prevents agent from re-debating settled items |
| Relevant file paths | "Rate limiter config is at src/middleware/rate-limit.ts" | Saves exploration time |
| Constraints | "Must not break existing /api/users tests in users.test.ts" | Prevents regressions |
| Expected output format | "Return a summary: files changed, tests added, edge cases" | Structures the response |
Minimal vs Bundled Delegation
BAD (minimal context):
"Add rate limiting to the users endpoint"
GOOD (bundled context):
"Add rate limiting to the /api/users endpoint.
Context: This is part of the API hardening initiative. In step 1, we chose
token bucket algorithm (see src/middleware/rate-limit.ts for the base
implementation). Step 2 added rate limiting to /api/auth.
Requirements:
- 100 requests per minute per API key
- Return 429 with Retry-After header when exceeded
- Add tests in src/middleware/__tests__/rate-limit-users.test.ts
Constraints:
- Do not modify existing tests in users.test.ts
- Follow the same pattern used in the /api/auth rate limiter
Return: summary of files changed, tests added, and any edge cases found."Two-Stage Review Workflow
After an implementer agent completes work, run two sequential review passes: spec compliance first, then code quality. This catches both requirement misses and code issues without overloading a single reviewer.
Workflow Steps
1. Implementer agent completes the task
2. Spec compliance reviewer checks:
- Does the output match all requirements?
- Are edge cases from the spec handled?
- Are acceptance criteria satisfied?
3. If spec review fails: implementer fixes, return to step 2
4. Code quality reviewer checks:
- Is the code clean and idiomatic?
- Are there performance or security issues?
- Does it follow project conventions?
5. If quality review fails: implementer fixes, return to step 4
6. Both reviewers approve: work is completeWhen to Use Two-Stage vs Single-Pass
| Two-Stage Review | Single-Pass Review |
|---|---|
| Complex requirements with many criteria | Simple, well-defined changes |
| High-stakes code (auth, payments, data) | Internal tooling, scripts |
| Spec and quality concerns are distinct | One reviewer can cover both adequately |
| Multiple agents available for review | Limited agent budget |
Reviewer Agent Configurations
---
name: spec-reviewer
description: Checks implementation against requirements. Use after code changes.
tools: Read, Grep, Glob
model: sonnet
---
You are a spec compliance reviewer. Given an implementation and its requirements:
1. Read the requirements document or task description
2. Read all changed files
3. Check each requirement against the implementation
4. Report: PASS (all requirements met) or FAIL (list unmet requirements)
Do NOT comment on code style or quality. Focus only on whether the
implementation satisfies the stated requirements.---
name: quality-reviewer
description: Reviews code quality after spec compliance is confirmed. Use after spec review passes.
tools: Read, Grep, Glob
model: sonnet
---
You are a code quality reviewer. The implementation already passes spec review.
1. Read all changed files
2. Check for: naming, structure, duplication, error handling, performance, security
3. Report: PASS (code is clean) or FAIL (list specific issues to fix)
Do NOT re-check requirements. Focus only on code quality and conventions.Review Loop Enforcement
When a reviewer finds issues, the implementer fixes them, then the reviewer checks again. This loop repeats until the reviewer approves.
Loop Structure
Iteration 1: Implementer builds → Reviewer finds 5 issues
Iteration 2: Implementer fixes → Reviewer finds 2 remaining issues
Iteration 3: Implementer fixes → Reviewer approves (PASS)Max Iterations and Escalation
| Iteration | Action |
|---|---|
| 1-3 | Normal review loop: fix issues, re-review |
| 4 | Escalate: controller reviews the remaining issues directly |
| 5+ | Abort the loop, merge what is passing, file issues for the rest |
Loops that do not converge after 3-4 iterations usually indicate one of:
- Ambiguous requirements: reviewer and implementer interpret specs differently. Fix the spec, not the code.
- Scope creep: reviewer keeps finding new issues beyond the original scope. Constrain the review checklist.
- Model disagreement: two models produce different opinions on style. Pick one opinion and move on.
Orchestrating the Loop from Main Conversation
1. Spawn implementer subagent with task
2. Spawn reviewer subagent with implementer's output
3. If reviewer returns FAIL:
a. Pass failure list back to implementer subagent
b. Implementer fixes, returns updated output
c. Spawn reviewer again with updated output
d. Repeat (max 3-4 iterations)
4. If reviewer returns PASS: done
5. If max iterations reached: escalate or file remaining issuesParallel vs Sequential Dispatch
When to run agents in parallel versus chaining them sequentially.
Decision Criteria
| Criterion | Parallel | Sequential |
|---|---|---|
| Task dependency | Tasks are independent | Task B needs Task A's output |
| File overlap | Agents touch different files | Agents may edit the same files |
| Information flow | No data passes between agents | Output of one feeds into the next |
| Time sensitivity | All tasks needed ASAP | Order matters more than speed |
| Failure impact | One failure does not block others | Failure in step N blocks steps N+1... |
Parallel Dispatch Patterns
Good candidates for parallel execution:
- Independent research: "Research auth libraries" + "Research database options" + "Research deployment platforms"
- Batch operations: 4 agents each processing a non-overlapping subset of files
- Multi-module updates: agent per module when modules do not share interfaces
- Test + lint + typecheck: independent validation passes on the same codebase
Main conversation spawns:
Agent 1 -> Research authentication (independent)
Agent 2 -> Research database (independent)
Agent 3 -> Research deployment (independent)
All complete -> Main conversation synthesizes findingsSequential Dispatch Patterns
Must be sequential when:
- Review chains: implement -> spec review -> quality review
- Dependent transforms: parse data -> validate -> transform -> write
- Iterative refinement: draft -> review -> revise -> final review
- Context-dependent steps: explore codebase -> design solution -> implement
Main conversation -> Agent A: explore codebase (returns architecture summary)
Main conversation -> Agent B: design solution (receives A's summary)
Main conversation -> Agent C: implement design (receives B's design)
Main conversation -> Agent D: review implementation (receives C's changes)Hybrid Dispatch
Combine parallel and sequential for complex workflows:
Phase 1 (parallel):
Agent 1 -> Research frontend options
Agent 2 -> Research backend options
Phase 2 (sequential, uses Phase 1 results):
Agent 3 -> Design architecture using research findings
Phase 3 (parallel):
Agent 4 -> Implement frontend
Agent 5 -> Implement backend
Phase 4 (sequential):
Agent 6 -> Integration reviewForeground vs Background Execution
| Mode | Behavior | Permission Handling |
|---|---|---|
| Foreground | Blocks main conversation until complete | Prompts passed through to user |
| Background | Runs concurrently while user continues | Pre-approved upfront; auto-denies unapproved |
Background subagents cannot use MCP tools. If a background subagent fails due to missing permissions, resume it in the foreground to retry with interactive prompts.
To background a running task: press Ctrl+B. To request background execution: ask Claude to "run this in the background".
Resuming Subagents
Each subagent invocation creates a new instance with fresh context. To continue an existing subagent's work:
Continue that code review and now analyze the authorization logicResumed subagents retain their full conversation history, including all previous tool calls, results, and reasoning. Subagent transcripts persist independently of the main conversation and survive main conversation compaction.
Communication Pattern Selection
| Pattern | Best For | Tradeoffs |
|---|---|---|
| Shared memory | Simple state coordination | Race conditions, no trace |
| Message passing | Structured agent-to-agent flow | Complex setup, traceable |
| Event-driven | Loose coupling, scalability | Hard to trace execution |
| Task board | Fungible swarms | Requires task management system |
Recovery Patterns
| Scenario | Recovery |
|---|---|
| Agent dies | Bead remains in-progress; any agent picks it up |
| Wrong change | git checkout -- [file]; re-run with better instructions |
| Conflict | Check which change is correct; manually resolve |
| Stale task | Agent marks complete, board not updated; use atomic claiming |
| Background agent fails | Resume in foreground to retry with interactive permissions |
| Review loop diverges | Escalate after 3-4 iterations; fix spec or constrain scope |
Sub-Agent Configuration and Prompt Engineering
File Format
Markdown files with YAML frontmatter. The body becomes the system prompt. Subagents receive only this system prompt plus basic environment details (working directory), not the full Claude Code system prompt.
---
name: code-reviewer
description: Expert code reviewer. Use proactively after code changes.
tools: Read, Grep, Glob, Bash
model: sonnet
color: Blue
permissionMode: default
skills:
- api-conventions
hooks:
PostToolUse:
- matcher: 'Edit|Write'
hooks:
- type: command
command: './scripts/run-linter.sh'
---
Your sub-agent's system prompt goes here.Supported Frontmatter Fields
| Field | Required | Description |
|---|---|---|
name | Yes | Unique identifier using lowercase letters and hyphens |
description | Yes | When Claude should delegate to this subagent |
tools | No | Allowlist of tools the subagent can use; inherits all tools if omitted |
disallowedTools | No | Denylist of tools to remove from inherited or specified list |
model | No | sonnet, opus, haiku, or inherit (default: inherit) |
permissionMode | No | default, acceptEdits, dontAsk, bypassPermissions, or plan |
skills | No | Skills to inject into subagent context at startup (full content, not just available) |
hooks | No | Lifecycle hooks scoped to this subagent |
color | No | Background color for UI identification (Red, Blue, Green, Yellow, Purple, Orange, Pink, Cyan) |
Agent Locations and Priority
| Priority | Location | Scope |
|---|---|---|
| 1 (highest) | --agents CLI flag | Current session only |
| 2 | .claude/agents/*.md | Current project |
| 3 | ~/.claude/agents/*.md | All your projects |
| 4 (lowest) | Plugin agents/ directory | Where plugin is enabled |
When multiple subagents share the same name, the higher-priority location wins.
CLI-Defined Subagents
Pass JSON when launching Claude Code for session-scoped agents:
claude --agents '{
"code-reviewer": {
"description": "Expert code reviewer. Use proactively after code changes.",
"prompt": "You are a senior code reviewer...",
"tools": ["Read", "Grep", "Glob", "Bash"],
"model": "sonnet"
}
}'Use prompt for the system prompt (equivalent to the markdown body in file-based agents).
Tool Access Patterns
| Agent Type | Recommended Tools | Notes |
|---|---|---|
| Read-only | Read, Grep, Glob | Reviewers, auditors |
| File creators | Read, Write, Edit, Glob, Grep | NO Bash (causes approval spam) |
| Script runners | Read, Write, Edit, Glob, Grep, Bash | Full access |
| Research | Read, Grep, Glob, WebFetch, WebSearch | External data access |
Subagents inherit all tools by default, including MCP tools. Use disallowedTools to explicitly deny tools:
---
name: safe-researcher
description: Research agent with restricted capabilities
tools: Read, Grep, Glob, Bash
disallowedTools: Write, Edit
---Permission Modes
| Mode | Behavior |
|---|---|
default | Standard permission checking with prompts |
acceptEdits | Auto-accept file edits |
dontAsk | Auto-deny permission prompts (explicitly allowed tools still work) |
bypassPermissions | Skip all permission checks (use with caution) |
plan | Plan mode (read-only exploration) |
If the parent uses bypassPermissions, this takes precedence and cannot be overridden.
Model Selection
| Task Type | Model | Reason |
|---|---|---|
| Content generation | Sonnet | Quality matters |
| Code writing | Sonnet | Bugs are expensive |
| Creative work | Opus | Maximum quality |
| Fast lookups | Haiku | Speed over depth |
| Format checks | Haiku | Pass/fail only |
Default is inherit (uses the main conversation's model).
Preloading Skills
Inject skill content directly into a subagent's context at startup:
---
name: api-developer
description: Implement API endpoints following team conventions
skills:
- api-conventions
- error-handling-patterns
---
Implement API endpoints. Follow the conventions and patterns from the preloaded skills.Subagents do not inherit skills from the parent conversation. Each skill must be listed explicitly. The full skill content is injected, not just made available for invocation.
Prompt Engineering for Agents
Put Critical Instructions First
Instructions past approximately line 300 in the system prompt get deprioritized by models. Structure prompts with the most important rules immediately after frontmatter.
Avoiding Bash Approval Spam
When subagents have Bash, they default to heredocs for file creation, triggering approval prompts.
Solutions (in order of preference):
1. Remove Bash from tools list if the agent only creates files 2. Put "USE WRITE TOOL FOR ALL FILES" as the first instruction 3. Remove contradictory examples that show bash-based file creation
Write Clear Descriptions
Claude uses the description field to decide when to auto-delegate. Include phrases like "use proactively" for eager delegation:
description: Expert code reviewer. Use proactively after code changes.Hooks for Validation
Use PreToolUse hooks to validate operations before they execute:
hooks:
PreToolUse:
- matcher: 'Bash'
hooks:
- type: command
command: './scripts/validate-command.sh'
PostToolUse:
- matcher: 'Edit|Write'
hooks:
- type: command
command: './scripts/run-linter.sh'Hook scripts receive JSON via stdin with tool input in tool_input. Exit code 2 blocks the operation and feeds the error message back to Claude via stderr. Supported events: PreToolUse, PostToolUse, Stop (converted to SubagentStop at runtime).
Disabling Specific Subagents
Add to the deny array in settings to prevent Claude from using specific agents:
{
"permissions": {
"deny": ["Task(Explore)", "Task(my-custom-agent)"]
}
}Troubleshooting and Anti-Patterns
Anti-Patterns
| Anti-Pattern | Why It Fails | Fix |
|---|---|---|
| Too many agents | Coordination overhead > benefit | Start with 2-3, add only if needed |
| Delegating without a clear objective | "Fix this" gives no direction | Provide a manifest: objective, constraints, tools |
| Passing entire codebase to a sub-agent | Context overflow | Use context distillation -- pass only relevant symbols and facts |
| Ignoring sub-agent logs | Silent failures are hard to debug | Always review agent reports |
| Specialized agents for software dev at scale | Brittle, single points of failure | Use fungible agents with a shared task board |
| Giving Bash to file-creation agents | Approval spam, wrong patterns | Remove Bash, use Write/Edit tools |
| Burying critical instructions deep in prompt | Instructions past line 300 get ignored | Put critical rules FIRST after frontmatter |
| Expecting nested sub-agent spawning | Subagents cannot spawn other subagents | Chain subagents from the main conversation |
| Agents committing directly | No review, messy git history | Agents edit files, humans review and commit |
| Haiku for content generation | Quality drops significantly | Default to Sonnet, Haiku only for fast lookups or script execution |
| Vague agent descriptions | Claude cannot auto-delegate effectively | Write specific descriptions with "use proactively" or "use when..." phrases |
| Running many subagents that return detailed results | Context consumed in main conversation | Request concise summaries; isolate verbose output |
Troubleshooting Guide
Agent Does Not Appear in /agents
Created the agent file mid-session. Use the /agents command to reload, or restart Claude Code. Agents are loaded at startup or via the /agents interface.
Agent Uses Bash Heredocs Instead of Write Tool
Bash is in the tools list and the model defaults to shell commands. Remove Bash from tools or put "USE WRITE TOOL FOR ALL FILES" as the first instruction.
Agent Loses Track Mid-Task (Context Rot)
Context window filled with verbose outputs. Split into smaller batches (3-5 items instead of 10+). Use subagents for context isolation -- verbose tool outputs stay in the subagent's context while only the summary returns.
Subagent Returns Incomplete Results
The task was too broad for a single subagent context window. Break the work into smaller, focused subagent calls chained from the main conversation. Each subagent should have a bounded, specific task.
Fungible Agent Picks Up Stale Task
Another agent already completed it but the board was not updated. Ensure agents mark tasks in-progress before starting and closed when done. Use atomic task claiming if the system supports it.
Agents Make Conflicting File Edits
Multiple agents edited the same file. Assign non-overlapping item lists per agent. Review with git diff before committing and resolve manually.
Agent Fails and Task Is Stuck
The in-progress task has no active agent. Start a new agent with the same initial prompt. It reads the task board, sees the stuck task, and resumes or restarts it.
Background Subagent Fails Due to Missing Permissions
Background subagents auto-deny anything not pre-approved. Resume the subagent in the foreground to retry with interactive permission prompts.
Handoff Drift (Original Objective Lost)
Multi-step delegation without re-stating the goal. Include a "Manifest of Objective" in every sub-agent prompt: objective, constraints, expected output format.
MCP Tools Not Available in Background Subagent
MCP tools are not supported in background subagents. Run the subagent in the foreground instead, or restructure the workflow to avoid MCP tool usage in background tasks.