AI Engineering Curriculum
Phase 1: Claude Code Mastery·5 min read

Module 1.4

Subagents

What Subagents Are

A subagent is a specialized Claude instance that runs in its own isolated context window, with its own system prompt, tool restrictions, model choice, and permissions. When Claude encounters a task that matches a subagent's description, it delegates to that subagent, which works independently and returns a summary.

Why they matter:

  • Context preservation - verbose output stays in the subagent's context, not yours
  • Tool enforcement - a read-only subagent literally cannot write files
  • Cost control - route simple tasks to Haiku, complex ones to Opus
  • Parallelism - multiple subagents can run simultaneously on independent tasks

Built-in Subagents

AgentModelToolsWhen Claude uses it
ExploreHaikuRead-onlySearching/understanding codebases without making changes
PlanInheritsRead-onlyResearch during plan mode before presenting a plan
General-purposeInheritsAllComplex multi-step tasks needing both exploration and action
BashInheritsBashRunning terminal commands in a separate context
Claude Code GuideHaikuWhen you ask questions about Claude Code features

Where Subagents Live

LocationScopePriority
--agents CLI flagCurrent session only1 (highest)
.claude/agents/This project2
~/.claude/agents/All your projects3
Plugin agents/ dirWhere plugin is enabled4 (lowest)

When names conflict, higher priority wins. Project subagents (.claude/agents/) should be committed to version control.


Anatomy of a Subagent File

markdown
--- 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: sonnet --- 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 Provide feedback organized by: Critical → Warnings → Suggestions.
  • YAML frontmatter - configuration
  • Markdown body - becomes the subagent's entire system prompt (not the full Claude Code system prompt - just this)

All Frontmatter Fields

FieldRequiredDescription
nameYesUnique identifier, lowercase with hyphens
descriptionYesWhen Claude should delegate. Write this carefully.
toolsNoAllowlist of tools. Inherits all if omitted.
disallowedToolsNoDenylist - remove specific tools from inherited set
modelNosonnet, opus, haiku, or inherit. Defaults to inherit.
permissionModeNoHow it handles permission prompts
maxTurnsNoMax agentic turns before it stops
skillsNoSkills to inject into context at startup
mcpServersNoMCP servers available to this subagent
hooksNoLifecycle hooks scoped to this subagent
memoryNoPersistent memory: user, project, or local

Tool Scoping

YAML
# Allowlist - only these tools tools: Read, Grep, Glob, Bash # Denylist - everything except these disallowedTools: Write, Edit # Restrict which subagents it can spawn (orchestrators only) tools: Task(worker, researcher), Read, Bash

Permission Modes

ModeBehavior
defaultStandard permission checking with prompts
acceptEditsAuto-accepts file edits
dontAskAuto-denies permission prompts
bypassPermissionsSkips all permission checks ⚠️
planRead-only plan mode
delegateFor agent team leads

Persistent Memory

YAML
--- name: code-reviewer memory: user --- Update your memory with patterns, recurring issues, and architectural insights you discover across reviews.
ScopeLocationUse when
user~/.claude/agent-memory/<name>/Learnings apply across all projects
project.claude/agent-memory/<name>/Project-specific, committable
local.claude/agent-memory-local/<name>/Project-specific, gitignored

When enabled: subagent gets Read/Write/Edit for its memory directory, and first 200 lines of MEMORY.md are injected into its system prompt each session.


Preloading Skills

YAML
--- name: api-developer skills: - api-conventions - error-handling-patterns ---

Full skill content is injected at startup - not just made available. Subagents don't inherit parent skills automatically.


Hooks in Subagents

YAML
--- name: safe-coder hooks: PreToolUse: - matcher: "Bash" hooks: - type: command command: "./scripts/validate-command.sh" PostToolUse: - matcher: "Edit|Write" hooks: - type: command command: "./scripts/run-linter.sh" ---

Stop hooks in frontmatter are automatically converted to SubagentStop at runtime.


Foreground vs Background

Foreground (default) - blocks main conversation, permission prompts pass through to you.

Background - runs concurrently. Claude pre-approves permissions upfront. Press Ctrl+B or say "run this in the background."


Resuming Subagents

Continue that code review and now analyze the authorization logic

Claude resumes the subagent with its full previous history. Transcripts stored at:

~/.claude/projects/{project}/{sessionId}/subagents/agent-{agentId}.jsonl

Real Examples

Code reviewer (read-only)

markdown
--- name: code-reviewer description: Proactively reviews code for quality and security. Use after writing or modifying code. tools: Read, Grep, Glob, Bash model: sonnet --- You are a senior code reviewer. When invoked: 1. Run `git diff` to see recent changes 2. Review for: readability, error handling, security, test coverage 3. Output: Critical issues → Warnings → Suggestions

Debugger (can edit)

markdown
--- name: debugger description: Debugging specialist for errors and test failures. Use when encountering any issues. tools: Read, Edit, Bash, Grep, Glob --- You are an expert debugger. Capture the error, identify root cause, implement a minimal fix, then verify it works.

DB reader (hook-gated)

markdown
--- name: db-reader description: Execute read-only database queries for analysis. tools: Bash hooks: PreToolUse: - matcher: "Bash" hooks: - type: command command: "./scripts/validate-readonly-query.sh" --- You have read-only database access. Execute SELECT queries only.

CLI-defined agent (session-only)

Bash
claude --agents '{ "quick-reviewer": { "description": "Fast code reviewer", "prompt": "Review code for quality and security.", "tools": ["Read", "Grep"], "model": "haiku" } }'

Power User Patterns

  • Isolate high-volume ops - test runs, log processing produce enormous output; keep it out of main context
  • Parallel research - "Research auth, database, and API modules in parallel" - all run simultaneously
  • Chain subagents - "Use code-reviewer to find issues, then debugger to fix them"
  • Disable a subagent - add to settings: { "permissions": { "deny": ["Task(Explore)"] } }

Important: Subagents cannot spawn other subagents. Chain them from the main conversation instead.


Source