Skip to main content

Git Worktrees & Subagent Delegation

12 min read

What You’ll Learn

This chapter is all about subagents, specialized AI assistants you can delegate work to right from within a Claude Code session. We’ll cover what subagents are and how they differ from agent teams, the three built in subagents and when to reach for each one, how to create custom subagents with AGENT.md files and YAML frontmatter, how git worktree isolation lets you develop in parallel without file conflicts, how persistent memory helps agents learn over time, and how foreground and background execution patterns work.

By the end, you’ll be able to create purpose built agents for code review, security scanning, documentation, and other specialized tasks, and run them in parallel using git worktrees.

What Are Subagents?

Subagents are specialized AI assistants that run within a Claude Code session, each with its own context, tools, permissions, and optionally its own isolated git worktree to prevent file conflicts.

Think of subagents as specialized AI assistants that run inside your Claude Code session. Each one gets its own context, tools, permissions, and optionally its own git worktree. When you hand off a task to a subagent, it works independently and reports results back to the parent session.

The key concept here is single session delegation. You’re the parent session. You spawn a subagent, it does its work, and it reports back to you. A subagent can’t talk to other subagents; it only communicates with the parent. This is fundamentally different from agent teams, which we cover in Chapter 10. Agent teams involve multi session coordination where independent Claude Code instances collaborate on a shared task list and can communicate with each other directly.

Under the hood, subagents are spawned by the Agent tool (formerly called the Task tool). The old Task(...) syntax still works as an alias. You don’t need to invoke the Agent tool directly. Claude Code handles it when you ask it to delegate work or when you invoke a named subagent.

Built In Subagents

Claude Code ships with three built in subagents, each tuned for a different use case.

Explore runs on the Haiku model and only has access to read only tools: Read, Grep, and Glob. It can’t edit files or run commands, which makes it the cheapest and safest option for codebase exploration, information gathering, and answering questions about code structure. Reach for Explore when you want to understand something without making any changes.

Plan inherits the parent session’s model and has access to read only tools. It’s built for creating implementation plans: analyzing code, identifying what needs to change, and outlining steps, all without actually making modifications. Use Plan when you want a thorough analysis before committing to an approach.

General purpose also inherits the parent session’s model but has access to all tools, including file editing and command execution. It can do everything the parent session can. This is the one to use when you want to fully delegate a task: reading, editing, running tests, and verifying results.

Invoking subagents is as simple as using natural language. Ask Claude Code to “explore the authentication module” and it’ll use the Explore subagent. Say “plan a refactoring of the database layer” and it’ll reach for the Plan subagent. Tell it to “implement input validation for the API endpoints” and it’ll spin up a general purpose subagent.

Invoking built in subagents
Invoking built in subagents
# Claude Code selects the appropriate built in subagent based on your request
"Explore how the caching layer works in this project"
→ Uses Explore subagent (Haiku, read only, cheapest)
"Plan the migration from REST to GraphQL"
→ Uses Plan subagent (parent model, read only)
"Implement rate limiting on all public API endpoints"
→ Uses general purpose subagent (parent model, all tools)

Claude Code chooses the right subagent based on the nature of your request.

Creating Custom Subagents

You define custom subagents in AGENT.md files. Each file contains YAML frontmatter that configures the subagent’s capabilities, followed by a markdown body that serves as the subagent’s system prompt, the instructions it follows when invoked.

.claude/agents/code-reviewer.md
.claude/agents/code-reviewer.md
---
name: code-reviewer
description: Expert code review specialist
tools: Read, Grep, Glob, Bash
model: sonnet
permissionMode: acceptEdits
maxTurns: 15
isolation: worktree
---
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. Check for:
- Logic errors and edge cases
- Missing error handling
- Security vulnerabilities
- Performance concerns
- Test coverage gaps
4. Provide actionable feedback with specific file and line references
5. Rate the overall change: approve, request changes, or comment

The YAML frontmatter configures capabilities. The markdown body is the system prompt.

The markdown body after the frontmatter is the subagent’s system prompt. Write it as clear instructions covering what the agent should do, how it should approach tasks, and what standards it should follow. Keep it focused. A subagent with a specific, well-defined purpose will consistently outperform one with vague, general instructions.

Here’s a custom security reviewer subagent in action, it can only read code (no editing or execution), and it finds real issues:

A custom read only security-reviewer subagent analyzing code
View as text (accessible transcript)
$ cat .claude/agents/security-reviewer.md
---
name: security-reviewer
description: Scans code for security vulnerabilities
tools: Read, Grep, Glob
---
You are a security focused code reviewer...

$ claude

> Use the security-reviewer agent to review src/routes/auth.ts

Claude spawns the subagent. It can only Read, Glob, Grep (no Edit, no Bash).

Findings:
- No input validation on registration endpoint
- Password stored in plain text (no hashing)
- JWT_SECRET from env could be undefined
A custom read only security-reviewer subagent analyzing code

AGENT.md Frontmatter Reference

The YAML frontmatter in an AGENT.md file supports the following fields. They’re all optional; a minimal AGENT.md can contain just a system prompt with no frontmatter at all.

name: The display name of the subagent. This is what shows up in the /agents menu and when the agent is invoked. If you leave it out, the filename is used instead.

description: A short description of the subagent’s purpose. It appears in the /agents menu to help you pick the right agent. Claude Code also uses it to decide when to auto-select this agent.

tools: The tools this subagent is allowed to use, specified as a comma separated list or YAML array. For example: Read, Grep, Glob for read only access, or Read, Grep, Glob, Write, Edit, Bash for full access.

disallowedTools: Tools explicitly blocked for this subagent, even if they’d otherwise be available. Handy for removing specific dangerous tools while keeping the rest.

model: Overrides the model used by this subagent. Options include sonnet, haiku, opus, or a specific model identifier. If omitted, the subagent inherits the parent session’s model.

permissionMode: Controls how the subagent handles permission prompts. Choose from five modes: default, acceptEdits, dontAsk, bypassPermissions, or plan. See the Permission Modes section below for details.

maxTurns: The maximum number of agentic loop iterations the subagent can perform. This prevents runaway agents; if a subagent has been looping for 50 turns, it’s probably stuck. A reasonable default is 10-25 depending on task complexity.

skills: Skills available to this subagent, specified as a YAML array. The subagent can invoke these skills during its execution.

mcpServers: MCP servers available to this subagent, specified as a YAML array. This restricts which external tool integrations the subagent can access.

hooks: Subagent scoped hooks using the same format as settings.json hooks. These hooks only fire for this specific subagent, not for the parent session or other subagents.

memory: Persistent memory scope for this subagent. Choose from user (global across all projects), project (per-repository), or local (per-directory). See the Persistent Memory section below.

background: Whether this subagent runs in the background by default. Set to true for agents that perform long running tasks you don’t need to watch. Defaults to false (foreground).

isolation: Set to worktree to give this subagent its own git worktree. The subagent works on an isolated copy of the codebase, preventing file conflicts with the parent session. See the Subagent Worktree Isolation section below.

Here’s a more advanced example that pulls several frontmatter fields together.

.claude/agents/security-reviewer.md
.claude/agents/security-reviewer.md
---
name: security-reviewer
description: Scans code for security vulnerabilities and compliance issues
tools: Read, Grep, Glob, Bash
disallowedTools: Write, Edit
model: opus
permissionMode: plan
maxTurns: 20
memory: project
isolation: worktree
hooks:
Stop:
- hooks:
- type: command
command: "echo 'Security review complete' >> .claude/security-log.txt"
---
You are a security focused code reviewer. Your job is to identify vulnerabilities,
insecure patterns, and compliance issues in the codebase.
Focus areas:
- SQL injection and input validation
- Authentication and authorization flaws
- Secrets and credentials in source code
- Dependency vulnerabilities (check package.json, requirements.txt)
- OWASP Top 10 issues
- Data exposure risks
Output a structured report with severity levels: critical, high, medium, low.
Include specific file paths, line numbers, and remediation recommendations.

Read only tools with plan permission mode ensures this agent cannot modify code.

Where Subagents Live

Subagent definitions can live in one of four locations, searched in this order.

Subagent storage locations
Subagent storage locations
~/.claude/agents/ # User scope (personal, all projects)
daily-standup.md
code-reviewer.md
my-project/
.claude/agents/ # Project scope (shared via git)
api-tester.md
migration-helper.md
security-reviewer.md
# CLI flag (session only, not persisted)
claude --agent "You are a documentation expert..."
# Plugin scope (installed from marketplaces)
# Managed by Claude Code's plugin system

Project agents in .claude/agents/ are the most common. Commit them to Git for team sharing.

CLI flag (session only) creates a one off subagent for the current session only. Great for quick experiments. The agent definition is passed directly on the command line and isn’t saved anywhere.

Project agents live in .claude/agents/ at your project root. They get committed to Git and shared with your team. This is the recommended spot for agents specific to your codebase.

User agents live in ~/.claude/agents/ and are available to you across all projects. Perfect for personal productivity agents you use everywhere.

Plugin agents are installed from plugin marketplaces and managed by Claude Code’s plugin system.

Git Worktrees for Parallel Development

The --worktree flag starts Claude Code in an isolated git worktree. A worktree is essentially a separate working copy of your repository that shares the same Git history but has its own file tree. Changes in the worktree won’t affect your main working directory until you merge them.

Starting a worktree session
Starting a worktree session
# Start Claude Code in a named worktree
claude --worktree feature-auth
# Start with an auto-generated worktree name
claude --worktree

Worktrees are created at .claude/worktrees/<name>.

When you run claude --worktree feature-auth, Claude Code creates a git worktree at .claude/worktrees/feature-auth. This gives you a full copy of your repository where Claude Code can read, edit, and create files without touching anything in your main working directory.

This is really powerful for parallel development. You can have Claude Code working on a feature branch in a worktree while you keep coding in your main directory. There are no file conflicts because each environment has its own file tree.

Here’s a worktree session in action, Claude works in an isolated copy while the original project stays untouched:

An isolated worktree session for parallel development
View as text (accessible transcript)
$ claude --worktree feature-logging

Claude starts in an isolated copy at .claude/worktrees/feature-logging/

> Add request logging middleware that logs method, path, and status code

Claude creates src/middleware/requestLogger.ts and wires it into the app.

> /quit

$ ls src/middleware/
auth.ts  index.ts

The original project does NOT have the logging file. Isolation works.
An isolated worktree session for parallel development

By default, worktrees are cleaned up automatically when the session ends. Once the Claude Code session using the worktree finishes, the worktree directory is removed. You can configure this behavior if you’d rather have worktrees persist.

Worktree directory structure
Worktree directory structure
# Your main working directory stays untouched
~/my-project/ # You work here
~/my-project/.claude/worktrees/
feature-auth/ # Claude Code works here (isolated)
fix-database/ # Another worktree (isolated)

Each worktree is a separate copy of the codebase sharing Git history.

Subagent Worktree Isolation

When you set isolation: "worktree" in an AGENT.md frontmatter, the subagent automatically gets its own git worktree every time it’s invoked. This is the recommended approach for any subagent that makes file changes, since the parent session and the subagent can edit files simultaneously without stepping on each other.

.claude/agents/feature-implementer.md
.claude/agents/feature-implementer.md
---
name: feature-implementer
description: Implements features in an isolated worktree
tools: Read, Grep, Glob, Write, Edit, Bash
permissionMode: acceptEdits
isolation: worktree
maxTurns: 25
---
Implement the requested feature in your isolated worktree.
After implementation:
1. Run the test suite to verify
2. Commit your changes with a descriptive message
3. Report what you built and any issues found

isolation: worktree gives this agent its own file tree automatically.

Without worktree isolation, a subagent editing files could easily conflict with changes you (or the parent session) are making at the same time. With isolation, each subagent works on its own copy. Once it finishes, you can review the changes and merge them into your working directory through normal Git operations.

This becomes especially valuable when you’re running multiple subagents in the background. Each background subagent gets its own worktree, so they can all work in parallel without colliding.

Persistent Memory

Subagents can maintain persistent memory across sessions using the memory field in their AGENT.md frontmatter. This lets agents learn your preferences, remember project conventions, and build context over time.

There are three scopes to choose from:

user: Global memory shared across all projects. Stored at the user level. Great for agents that need to remember your personal preferences regardless of which project you’re working on.

project: Per-repository memory. Stored with the project. Use this for agents that need to remember project-specific conventions, architecture decisions, or patterns.

local: Per-directory memory. Stored at the current directory level. Best for agents that operate on specific subsystems or modules within a project.

Memory is stored in MEMORY.md files with a curated 200 line limit. As the agent accumulates observations and preferences, it summarizes and condenses its memory to stay within this limit. Older, less relevant memories get replaced by newer, more useful ones.

.claude/agents/style-guide-enforcer.md
.claude/agents/style-guide-enforcer.md
---
name: style-guide-enforcer
description: Reviews code for project style consistency
tools: Read, Grep, Glob
memory: project
---
Review code for style consistency. Over time, learn the project's conventions
and enforce them. Remember patterns you've seen in previous reviews.

Project-scoped memory lets this agent learn your codebase's style over time.

Foreground vs Background Execution

By default, subagents run in foreground mode, which means the parent session waits for the subagent to finish before moving on. You’ll see the subagent’s output in real time.

Background mode lets the subagent run concurrently while the parent session continues with other work. Background subagents report their results when they’re done. This is ideal for long running tasks that don’t need your immediate attention.

You can set background: true in an AGENT.md frontmatter to make an agent always run in the background. Or, if a foreground subagent is taking longer than expected, just press Ctrl+B to send it to the background mid execution.

.claude/agents/test-runner.md
.claude/agents/test-runner.md
---
name: test-runner
description: Runs full test suite in background
tools: Bash, Read
background: true
isolation: worktree
---
Run the complete test suite and report results. Include:
- Total tests run, passed, failed, skipped
- Failure details with stack traces
- Test execution time

background: true means this agent always runs concurrently.

When a background subagent completes, Claude Code notifies you with a summary of the results. From there, you can review the output and decide how to proceed.

A common pattern is running multiple background subagents in parallel, say one running tests, one performing a security review, and one checking documentation coverage, while you keep working on implementation in the foreground.

Managing Subagents with /agents

The /agents command opens an interactive menu for managing your subagents. From here you can:

  • Browse all available agents (built in, project, user, and plugin)
  • Create new agents with guided prompts
  • Edit existing agent configurations
  • Delete agents you no longer need

If you’ve used the /hooks command for managing lifecycle hooks (covered in the Hooks chapter), this will feel familiar.

Opening the agent management menu
Opening the agent management menu
/agents

Lists all agents across all scopes with their descriptions.

Permission Modes

Each subagent operates under one of five permission modes that control how it handles prompts for file edits and command execution.

default: The subagent follows the same permission rules as the parent session. It’ll prompt you for approval before writing files or running commands, just like Claude Code normally does. This is the safest mode and the best starting point for new agents.

acceptEdits: The subagent automatically accepts file edits (creating, modifying, and deleting files) without prompting, but still asks before running shell commands. A good middle ground for agents you trust with code changes but want to keep an eye on when it comes to command execution.

dontAsk: The subagent automatically accepts all operations, including file edits and shell commands, without prompting. Use this for trusted agents performing well-scoped, predictable tasks.

bypassPermissions: The subagent skips all permission checks entirely. This is the most permissive mode and should only be used for agents you fully trust in controlled environments.

plan: The subagent operates in read only mode. It can’t write files or execute commands, only read, search, and analyze. This is the permission mode used by the built in Plan subagent, and it’s ideal for review and analysis agents that should never modify code.

Start with default for new agents. As you build trust in an agent’s behavior, graduate to acceptEdits. Reserve dontAsk and bypassPermissions for mature, well tested agents performing predictable operations.

Permission mode spectrum
Permission mode spectrum
# Permission mode progression as trust builds
plan → Read only analysis (safest)
default → Same prompts as parent session
acceptEdits → Auto-accept file changes, prompt for commands
dontAsk → Auto-accept everything
bypassPermissions → Skip all checks (most permissive)

Move from left to right as you build confidence in an agent's behavior.

Best Practices

  • Use Explore for information gathering. It’s the cheapest subagent (Haiku model) and can’t modify your code. When you just need to understand something, Explore is the right call.

  • Use worktree isolation for agents that edit files. Any subagent that writes or edits code should use isolation: worktree to prevent conflicts with your working directory and with other subagents.

  • Set maxTurns to prevent runaway agents. Without a turn limit, a stuck subagent can loop indefinitely, burning through tokens. Set a reasonable limit based on expected task complexity: 10-15 for focused tasks, 20-30 for complex ones.

  • Match permission modes to trust level. Start with default and only escalate as you verify the agent behaves correctly. An agent with bypassPermissions that goes wrong can cause real damage fast.

  • Name agents descriptively. Something like security-reviewer or api-tester makes it obvious what the agent does. Steer clear of generic names like helper or assistant.

  • Keep system prompts focused. An agent with a single, well-defined purpose will consistently outperform one with a broad mandate. Create multiple specialized agents rather than one general-purpose agent that tries to do everything.

  • Run multiple background agents for parallel work. Combine background: true with isolation: worktree to have several agents working concurrently on different tasks. Review and merge their results when they’re done.

Further Reading

  • Subagents, the official documentation on creating, configuring, and managing subagents
  • Common Workflows, covering practical patterns including git worktree usage and parallel development

Up next, learn how to coordinate multiple Claude Code instances working together in Agent Teams & Advanced Orchestration.