Using Git Worktrees for Subagent Isolation: Run Multiple Claude Code Agents on Separate Branches Simultaneously
Claude Code supports git worktrees for subagent isolation, allowing multiple AI agents to work concurrently on separate branch copies without interfering with your main working directory or each other.
The shanraisshan/claude-code-best-practice repository documents advanced patterns for orchestrating Claude Code subagents. By leveraging git worktrees for subagent isolation, you can run parallel agents that each operate on independent branch copies, ensuring complete sandboxing while maintaining zero impact on your primary checkout.
What Is Git Worktree Isolation?
Git worktree isolation is a sandboxing mechanism where Claude Code creates a temporary Git worktree for each subagent. When the isolation front-matter field is set to "worktree", the runtime automatically generates a new worktree branched from HEAD, switches the agent's working directory to that path, and handles cleanup when the agent terminates. This approach, documented in best-practice/claude-subagents.md at line 33, enables true branch-level parallelism for AI-assisted development workflows.
Benefits of Using Worktrees for Agent Isolation
Implementing git worktrees for subagent isolation provides four critical advantages for multi-agent workflows:
-
Branch-level parallelism: Each agent works on its own branch copy, allowing two agents to edit the same repository simultaneously without creating merge conflicts between their in-progress changes.
-
Zero-impact on main checkout: The original working directory remains pristine throughout the session; the worktree lives in a hidden temporary directory completely separate from your primary workspace.
-
Automatic cleanup: If the agent leaves the worktree unchanged, Claude Code removes it automatically when the agent finishes, keeping the filesystem tidy without manual intervention.
-
Hook integration: The
WorktreeCreateandWorktreeRemovehook events fire whenever a worktree is created or torn down, enabling custom side-effects like logging, notifications, or external system integration.
How Worktree Isolation Works Under the Hood
The isolation mechanism follows a precise seven-step lifecycle defined in the repository's hook documentation and subagent best practices:
-
Agent definition: The agent's front-matter contains
isolation: "worktree"to trigger the isolation subsystem. -
Agent launch: Claude Code invokes the worktree isolation subsystem upon agent startup.
-
Worktree creation: The system executes
git worktree addto create a new worktree branched fromHEAD, and the agent's current working directory switches to that temporary path. -
Hook emission: The
WorktreeCreatehook fires immediately after creation, as documented in.claude/hooks/HOOKS-README.mdat line 25. -
Agent execution: The agent runs its tools, reads files, makes edits, and commits changes wholly contained within the isolated worktree environment.
-
Termination check: When the agent stops, Claude Code checks for uncommitted changes. If none exist, the worktree is removed automatically; otherwise, it persists for user inspection.
-
Final hook emission: The
WorktreeRemovehook runs during teardown, enabling cleanup notifications or custom logic as referenced inHOOKS-README.mdat line 26.
This flow allows you to spin up multiple agents concurrently—via --agents JSON configurations or separate /task commands—with each receiving its own isolated branch copy.
Configuring Worktree Isolation in Practice
Enabling Isolation in Agent Front-matter
To activate worktree isolation for a specific agent, add the isolation field to the YAML front-matter in your agent definition file located at .claude/agents/[agent-name].md:
---
name: refactor-agent
description: Refactors code on a separate branch
model: haiku
tools: Read, Write, Edit, Bash
isolation: "worktree" # ← enable git worktree isolation
maxTurns: 30
---
When Claude Code loads this agent, it automatically creates the temporary worktree before executing the agent's instructions.
Launching Multiple Isolated Agents Simultaneously
You can launch parallel agents with individual worktree isolation using the --agents CLI flag with a JSON array. Both agents run in separate temporary branches, allowing them to make conflicting edits without interference:
# Start Claude Code with multiple isolated agents
claude --agents '[{
"name":"refactor-agent",
"isolation":"worktree"
},{
"name":"doc-gen-agent",
"isolation":"worktree"
}]' --debug "agent,worktree"
Each object in the array can specify its own isolation strategy, though setting "worktree" for multiple agents enables the parallel workflow described in the subagents best-practice documentation.
Global Worktree Mode with CLI Flags
For scenarios requiring entire session isolation, the CLI supports a global --worktree flag documented in best-practice/claude-cli-startup-flags.md at line 24. This starts the entire Claude session inside a temporary worktree:
# The whole Claude session runs inside a temporary worktree
claude --worktree --agent refactor-agent
In this mode, every sub-agent inherits the same isolated worktree rather than creating separate ones, which is useful when you want the entire workflow sandboxed from your main repository state.
Hook Integration for Worktree Lifecycle Events
You can observe and react to worktree creation and removal by implementing hook scripts in .claude/hooks/scripts/. The following Python excerpt demonstrates handling the WorktreeCreate and WorktreeRemove events:
# .claude/hooks/scripts/hooks.py (excerpt)
if args.event == "WorktreeCreate":
print(f"🔧 Worktree created at {args.path}")
elif args.event == "WorktreeRemove":
print(f"🧹 Worktree removed from {args.path}")
Configure these hooks in your hooks-config.json to enable automatic notifications, metrics collection, or integration with external orchestration systems whenever agents spin up or tear down their isolated environments.
Summary
- Git worktrees for subagent isolation enable parallel agent execution by giving each agent its own branch copy via temporary worktrees.
- Configure isolation by setting
isolation: "worktree"in agent front-matter files stored in.claude/agents/. - Use the global
--worktreeflag (documented inclaude-cli-startup-flags.md) to sandbox entire sessions rather than individual agents. - Leverage
WorktreeCreateandWorktreeRemovehooks (defined in.claude/hooks/HOOKS-README.md) to build observability into your multi-agent workflows. - Automatic cleanup removes temporary worktrees when agents exit without uncommitted changes, ensuring filesystem hygiene.
Frequently Asked Questions
How do I enable worktree isolation for a single Claude Code agent?
Add isolation: "worktree" to the YAML front-matter of your agent definition file in the .claude/agents/ directory. When Claude Code launches that agent, it automatically creates a temporary Git worktree branched from HEAD and switches the agent's working context to that isolated environment.
Can I run multiple agents with worktree isolation simultaneously?
Yes. Pass a JSON array to the --agents CLI flag with multiple agent objects, each specifying "isolation":"worktree". Each agent receives its own independent worktree, allowing concurrent modifications to the same files without merge conflicts or cross-agent interference.
What happens to the temporary worktree when an agent finishes?
Claude Code checks for uncommitted changes upon agent termination. If the worktree contains no modifications, the system automatically removes it to keep your filesystem clean. If changes exist, the worktree persists for manual inspection and cleanup, and the WorktreeRemove hook still fires to notify your monitoring systems.
What is the difference between agent-level and global worktree isolation?
Agent-level isolation (configured via front-matter) creates separate temporary worktrees for each individual subagent, enabling true parallel processing. Global isolation (activated with the --worktree CLI flag documented in best-practice/claude-cli-startup-flags.md) places the entire Claude session into a single worktree, meaning all subagents share that same isolated environment rather than receiving individual branch copies.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →