Git Worktrees & Subagent Delegation
15 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 with dedicated storage and topic files, how foreground and background execution patterns work, how initialPrompt auto-submits a first turn for session agents, and how sparse-checkout keeps monorepo worktrees lean.
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. You can also type @agent-name in your prompt to invoke a specific subagent by name, whether it’s a built in agent or one you’ve defined in an AGENT.md file.
# 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)
# Or invoke a specific agent by name"@security-reviewer check the auth module for vulnerabilities"→ Invokes the named security-reviewer subagent directlyClaude Code chooses the right subagent based on your request, or you can target one by name with @agent-name.
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.
---name: code-reviewerdescription: Expert code review specialisttools: Read, Grep, Glob, Bashmodel: sonnetpermissionMode: acceptEditsmaxTurns: 15isolation: worktree---
You are a senior code reviewer ensuring high standards of code quality.
When invoked:1. Run git diff to see recent changes2. Focus on modified files3. Check for: - Logic errors and edge cases - Missing error handling - Security vulnerabilities - Performance concerns - Test coverage gaps4. Provide actionable feedback with specific file and line references5. Rate the overall change: approve, request changes, or commentThe 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:
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 undefinedAGENT.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 six modes: default, acceptEdits, plan, auto, dontAsk, or bypassPermissions. 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.
initialPrompt: A prompt that auto-submits as the first turn when the agent runs as the main session agent (via the --agent flag or agent setting). Commands and skills referenced in the prompt are processed. If the user provides a prompt at launch, the initialPrompt is prepended to it.
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 an example that uses initialPrompt to auto-start a review workflow when the agent is launched as the main session agent:
---name: code-reviewerdescription: Reviews staged changes for security and quality issuestools: Read, Grep, Glob, BashinitialPrompt: "Review all staged changes for security issues and code quality. Use /compact if context gets large."memory: project---
You are a senior code reviewer. Focus on:- Security vulnerabilities (injection, auth bypass, data exposure)- Logic errors and unhandled edge cases- Performance concerns- Missing error handling
Output a structured report with severity levels and specific file references.initialPrompt auto-submits when this agent runs as the main session agent via --agent code-reviewer.
Here’s a more advanced example that pulls several frontmatter fields together.
---name: security-reviewerdescription: Scans code for security vulnerabilities and compliance issuestools: Read, Grep, Glob, BashdisallowedTools: Write, Editmodel: opuspermissionMode: planmaxTurns: 20memory: projectisolation: worktreehooks: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.
~/.claude/agents/ # User scope (personal, all projects)daily-standup.mdcode-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 systemProject 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.
You can also define multiple subagents inline at launch using the --agents flag with a JSON array. These agents exist only for the current session and aren’t saved to disk.
claude --agents '[{"name": "reviewer", "description": "Reviews code for issues"}, {"name": "tester", "description": "Writes and runs tests"}]'Session-only agents defined as JSON. Useful for automation scripts and quick experiments.
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. For details on creating and distributing plugins that include agents, see Plugins.
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.
# Start Claude Code in a named worktreeclaude --worktree feature-auth
# Start with an auto-generated worktree nameclaude --worktreeWorktrees 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:
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.By default, worktrees are cleaned up automatically when the session ends. The ExitWorktree tool handles this cleanup, removing the worktree branch once the session finishes and there are no uncommitted changes. You can configure this behavior if you’d rather have worktrees persist.
Sparse Checkout for Monorepos
In large monorepos, checking out the entire repository for each worktree can be wasteful. The worktree.sparsePaths setting enables sparse-checkout, so worktrees only contain the directories each subagent actually needs.
{ "worktree": { "sparsePaths": ["packages/frontend", "packages/shared"] }}Worktrees only check out the specified directories instead of the full repo.
This is particularly useful when you have subagents that work on specific parts of a monorepo. A frontend subagent only needs packages/frontend and shared libraries, not the entire backend, infrastructure, and documentation trees. Sparse checkout reduces disk usage and speeds up worktree creation.
# 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.
---name: feature-implementerdescription: Implements features in an isolated worktreetools: Read, Grep, Glob, Write, Edit, BashpermissionMode: acceptEditsisolation: worktreemaxTurns: 25---
Implement the requested feature in your isolated worktree.After implementation:1. Run the test suite to verify2. Commit your changes with a descriptive message3. Report what you built and any issues foundisolation: 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 ~/.claude/agent-memory/<name>/ where <name> is the agent’s name. Great for agents that need to remember your personal preferences regardless of which project you’re working on.
project: Per-repository memory. Stored at .claude/agent-memory/<name>/ in the project root. 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.
Each agent’s memory directory contains a MEMORY.md entrypoint file that the agent reads on startup. As the agent accumulates observations and preferences, it can also create topic files for specific subjects like coding standards, project architecture, or common patterns. This keeps memory organized and relevant.
# User-scoped memory (global, all projects)~/.claude/agent-memory/code-reviewer/ MEMORY.md # Main entrypoint, read on startup coding-standards.md # Topic file: learned style preferences common-patterns.md # Topic file: recurring code patterns
# Project-scoped memory (per-repository)my-project/.claude/agent-memory/security-reviewer/ MEMORY.md # Project-specific memory vulnerability-history.md # Topic file: past findingsMEMORY.md is the entrypoint. Topic files organize knowledge by subject.
At session start, the first 200 lines or 25KB of memory content is loaded into the agent’s context. As memory grows beyond this limit, the agent summarizes and condenses older observations to stay within the budget. More recent and more frequently referenced memories take priority over older, less relevant ones.
---name: style-guide-enforcerdescription: Reviews code for project style consistencytools: Read, Grep, Globmemory: project---
Review code for style consistency. Over time, learn the project's conventionsand 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.
When a subagent runs in the background, permissions are handled differently. Any tools that were pre-approved upfront (through the agent’s permissionMode or explicit tool list) run normally. But if the agent encounters a tool call that would normally require human approval, it’s automatically denied since there’s no human watching to approve it. Design your background agents with appropriate permission modes so they can complete their work autonomously.
---name: test-runnerdescription: Runs full test suite in backgroundtools: Bash, Readbackground: trueisolation: worktree---
Run the complete test suite and report results. Include:- Total tests run, passed, failed, skipped- Failure details with stack traces- Test execution timebackground: 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.
If you need to disable background execution entirely, for instance on a shared machine or in a resource constrained environment, set the CLAUDE_CODE_DISABLE_BACKGROUND_TASKS environment variable:
export CLAUDE_CODE_DISABLE_BACKGROUND_TASKS=1When set, all subagents run in the foreground regardless of their background setting.
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. The menu is organized into two tabs:
Running shows all currently active subagents with their status, whether they’re executing in the foreground or background. From here you can monitor progress, send a foreground agent to the background, or review results from completed background agents.
Library shows all available agents from every source: built in agents, project agents from .claude/agents/, user agents from ~/.claude/agents/, and agents provided by installed plugins. From the Library tab you can:
- Browse all available agents with their descriptions
- Create new agents with guided prompts, or use Generate with Claude for AI-assisted agent creation
- Edit existing agent configurations
- Customize agent colors for visual identification
- Delete agents you no longer need
/agentsThe Running tab shows active agents. The Library tab shows all available agents across all scopes.
Permission Modes
Each subagent operates under one of six 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.
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.
auto: A classifier-based mode where safe actions proceed automatically and destructive or suspicious actions are blocked. This provides intelligent permission management without manual approvals. See the Security chapter for full details on auto mode behavior.
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.
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 progression as trust buildsplan → Read only analysis (safest)default → Same prompts as parent sessionacceptEdits → Auto-accept file changes, prompt for commandsauto → Classifier-based safe/block decisionsdontAsk → Auto-accept everythingbypassPermissions → Skip all checks (most permissive)Move from left to right as you build confidence in an agent's behavior.
Building Agents Programmatically
For production workflows and CI/CD pipelines, you can create and manage agents programmatically using the Agent SDK. The SDK exposes AgentDefinition objects for defining agents in Python or TypeScript, with the same capabilities as AGENT.md files but controlled through code. This is particularly useful when agent configurations need to be dynamic or generated at runtime.
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: worktreeto 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
defaultand only escalate as you verify the agent behaves correctly. An agent withbypassPermissionsthat goes wrong can cause real damage fast. -
Name agents descriptively. Something like
security-reviewerorapi-testermakes it obvious what the agent does. Steer clear of generic names likehelperorassistant. -
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: truewithisolation: worktreeto have several agents working concurrently on different tasks. Review and merge their results when they’re done. -
Use sparsePaths in monorepos. If your subagents only need a subset of the repository, configure
worktree.sparsePathsto keep worktrees lean and creation fast.
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.