Git Worktrees for Parallel AI Coding Agent Workflows
Give every agent its own working directory without cloning the repository again. The cheapest isolation tier available, and when to escalate past it.
What a Worktree Actually Is
One object store, many checked-out branches, each in its own directory on disk
A Git repository normally has exactly one working directory. You check out a branch, the files on disk change to match it, and that is the only state you can see at once. This is fine for a single human working on a single task. It falls apart the moment several AI coding agents are asked to work on different branches of the same repository at the same time, because every agent is fighting over the same set of files.
git worktree removes that constraint. It attaches additional working directories to one existing repository. Each worktree has its own checked-out branch and its own files on disk, but they all share a single .git object store. There is no second copy of the history, no second fetch of every object, and no second set of remotes to keep in sync. As the Nx engineering blog puts it in its writeup on worktrees for AI agents, "All worktrees share the same Git history. Changes committed in any worktree are immediately available to all others."
The practical payoff is proportional to repository size. On a small service repository, cloning again costs a few seconds and worktrees save little. On a large monorepo where a fresh clone means pulling gigabytes of history, the difference between git clone and git worktree add is the difference between minutes and seconds per agent. When you are standing up five or ten agent working directories, that difference compounds.
The Commands You Actually Need
# Create a worktree on a new branch, in a sibling directory
git worktree add ../repo-agent-1 -b agent/refactor-auth
# Create a worktree on an existing branch
git worktree add ../repo-agent-2 feature/billing-retry
# Create a worktree from a specific base, without checking out a branch
git worktree add --detach ../repo-agent-3 origin/main
# See what exists right now
git worktree list
# Tear one down (refuses if the directory is dirty)
git worktree remove ../repo-agent-1
# Force removal, then clean up stale administrative records
git worktree remove --force ../repo-agent-1
git worktree pruneTwo rules save most of the pain. A branch can only be checked out in one worktree at a time, so an orchestrator that assigns branches to agents must treat branch names as an exclusive resource. And git worktree prune is what reconciles the administrative records under .git/worktrees after a directory has been deleted out from under Git, which is exactly what happens when an agent process is killed mid-task.
No Second History
Objects, packfiles, and refs live once. Adding a worktree costs roughly the size of one checkout, not the size of the repository plus its history. On a monorepo this is the entire argument.
Commits Are Instantly Shared
An agent that commits in one worktree makes that commit immediately visible to every other worktree. Rebasing one agent's branch onto another's work needs no fetch and no network round trip.
No More Stash Ceremony
You stop stashing your own work to let an agent switch branches. Nx names this directly: without worktrees "you have to temporarily commit changes or stash whatever you've been currently working on."
The Isolation Gap
The most common and most expensive misunderstanding about worktrees
A Worktree Is Not a Sandbox
Worktrees give you no process isolation, no filesystem isolation, no network isolation, and no resource limits. Every agent runs as the same user, on the same kernel, with the same environment variables, the same credential helpers, and the same reachable network. An agent in one worktree can read another worktree's files, read your SSH keys and cloud credentials, exhaust the machine's memory or disk, and make any outbound request the host can make. Worktrees solve branch collision. They do not solve security.
This matters more for agents than it did for humans. A human developer exercises judgment about what they run. An agent executes code it generated from model output, installs packages from public registries, and follows instructions that may have arrived through a README, an issue comment, or a dependency's postinstall script. Prompt injection turns "the agent has my credentials" from a theoretical concern into a live one. The isolation properties you need are covered on sandbox environments and microVM isolation; worktrees sit below both.
The right way to think about it is a ladder. Each rung costs more and isolates more, and you should be able to say out loud which rung a given workload belongs on and why.
The Isolation Escalation Ladder
| Tier | Boundary | Startup | Marginal cost | Blast radius if compromised |
|---|---|---|---|---|
| Git worktree | Directory only | Seconds | One checkout of disk | The whole developer machine |
| Container / devcontainer | Namespaces, cgroups | Seconds | Container image plus limits | Shared host kernel |
| Kubernetes Sandbox CRD | Namespaced pod, policy, RuntimeClass | Seconds, near-instant from a warm pool | Pod plus cluster overhead | Node kernel, narrowed by gVisor or Kata |
| MicroVM | Hypervisor, dedicated guest kernel | Hundreds of milliseconds | Guest kernel plus VMM overhead | One virtual machine |
Startup and cost figures are directional and depend heavily on image size, storage backend, and whether a warm pool is in front of the tier. Treat the ordering as the durable claim, not the numbers.
Operational Realities
The things that surprise teams in the first week of running agents on worktrees
Dependencies Are Not Shared
Git shares the object store. It does not share anything Git does not track. node_modules, Python virtual environments, Rust target/, Go build caches, and compiled artifacts all start empty in a new worktree. Nx names the same friction, noting you "potentially re-install node_modules (or whatever package manager you're using)," and Upsun is blunt about it: "Each worktree needs npm install or npm ci." The fast install is often longer than the worktree creation it followed.
Gitignored Config Does Not Follow
Anything correctly excluded from version control is, by definition, absent from a fresh worktree. Upsun singles out ".env (which is gitignored, as it should be)" as needing manual per-worktree setup. An agent that starts in a worktree with no local configuration will either fail immediately or, worse, silently fall back to a default that points somewhere real.
Ports and Local Services Collide
Worktrees share the host's network namespace, so they share its ports. Upsun's description is exact: "Every dev server defaults to the same ports: 3000, 5432, 8080. Launch two React apps from different worktrees and one fails." The same post notes worktrees "share the same local database, Docker daemon, and cache directories," so "two agents modifying database state at the same time creates race conditions." Port offsetting schemes work but are one more thing to maintain.
Disk Use Is Not Free
The history is shared, but every checkout plus its installed dependencies is not. Upsun reports users seeing "automatic worktree creation used 9.82 GB" in twenty minutes against a 2GB codebase, and "15 forgotten worktrees consuming gigabytes." Automatic creation without automatic teardown fills a laptop disk quickly.
Conflicts Move, They Do Not Vanish
Isolating the working directories means agents stop stepping on each other while they work. It also means nobody notices divergence until merge time. Upsun's framing is worth keeping in mind: "The worktrees are separate, so you can create merge conflicts between them without knowing." Parallelism at the checkout layer becomes serialization at the review and merge layer.
Tooling Support Is Still Uneven
Editor and agent-CLI support for worktrees has been catching up rather than leading. Upsun notes that "VS Code added worktree support in July 2025" and that "Claude Code's /ide command fails to recognize worktrees, reporting 'No available IDEs detected'." Check the specific versions your team runs before assuming a workflow is smooth.
A Bootstrap Script Is Mandatory, Not Optional
Because dependencies, gitignored config, and ports do not come along for free, every serious worktree workflow ends up with a wrapper. Keep it in the repository so agents and humans use the same one.
#!/usr/bin/env bash
# scripts/agent-worktree.sh NAME BASE_BRANCH
set -euo pipefail
NAME="$1"
BASE="${2:-main}"
ROOT="$(git rev-parse --show-toplevel)"
DIR="${ROOT}/../wt-${NAME}"
git worktree add "$DIR" -b "agent/${NAME}" "$BASE"
# Gitignored config never follows a worktree - copy it explicitly
cp "${ROOT}/.env.local" "${DIR}/.env.local" 2>/dev/null || true
# Dependencies are per-worktree, not per-repository
( cd "$DIR" && npm ci --prefer-offline )
# Give each worktree its own port block so dev servers do not collide.
# Derive the port from the worktree NAME, not from a count of existing worktrees:
# a count is reused as soon as anything is removed, so a torn-down worktree hands
# its port to the next one created while the old dev server may still hold it.
PORT=$(( 3000 + ( $(printf '%s' "$NAME" | cksum | cut -d' ' -f1) % 600 ) * 10 ))
echo "PORT=${PORT}" >> "${DIR}/.env.local"
echo "worktree ready: ${DIR}"Pair it with a teardown path that runs git worktree remove followed by git worktree prune, and run the teardown on a schedule rather than trusting anyone to remember. A tooling category has grown up around exactly this problem, including Worktrunk and agent-worktree. Evaluate them the way you would any other developer tool, but understand they automate the ceremony rather than change the isolation properties.
What Teams at Scale Actually Did
Two published accounts of organizations that moved past local worktrees
Stripe: Worktrees Help, But Are Hard to Combine
Writing about its "minions" agent system, Stripe describes the limits of local approaches directly: "Containerization or git worktrees can help, but they're hard to combine and it's fundamentally difficult to build local agents that have all the power of a developer's shell but are appropriately constrained." Stripe's stated requirement is that "unattended agent coding at scale requires a cloud developer environment that's parallelizable, predictable, and isolated," and the approach it landed on is pre-provisioned cloud devboxes: "we proactively provision and warm up a pool of devboxes so they are ready when a developer wants them."
Stripe Engineering, Minions Part 2Ramp: Remote Sandboxes Removed the Rationing
Ramp built a background agent called Inspect and reports that "~30% of all pull requests merged to our frontend and backend repos are written by Inspect." Each session "runs in a sandboxed VM on Modal with everything an engineer would have locally," and Ramp frames the benefit in terms of what it replaced: because sessions are "fast to start and effectively free to run, you can use them without rationing local checkouts or worktrees." The observation worth taking away is that worktrees were the scarce local resource being rationed.
Ramp Engineering, Why We Built Our Background AgentThis Is Not an Argument Against Worktrees
Both accounts come from organizations running agents at a volume most teams will never reach. For one engineer running two or three agents against a repository they already trust, a worktree per agent is the correct amount of machinery and anything heavier is waste. The signal in these accounts is directional: the failure mode of worktrees is not that they stop working, it is that they stop being enough once concurrency rises and the code being executed stops being trusted.
When to Escalate Past a Worktree
Concrete triggers, not vibes
The Agent Runs Code You Have Not Read
The moment an agent installs dependencies, executes generated scripts, or acts on text it fetched from outside the repository, the relevant boundary is a kernel or a hypervisor, not a directory. Move to a container at minimum. If the workload is multi-tenant or regulated, keep going up the ladder to microVM isolation.
Concurrency Outgrows One Machine
A laptop can host a handful of worktrees before disk, memory, and port collisions dominate. Once you want tens of concurrent sessions, the constraint is scheduling and capacity, not checkout management. That is the point where a Kubernetes Sandbox primitive earns its complexity, and where the cost questions on agent fleets start to matter more than the checkout mechanics.
Reproducibility Starts Mattering
A worktree inherits whatever toolchain the host happens to have. When an agent's result depends on the machine that ran it, you have lost the ability to reason about failures. A declared environment, such as a devcontainer or an ephemeral environment defined in code, restores it.
You Need Resource Limits and an Off Switch
Worktrees have no cgroups, no timeouts, and no egress policy. A runaway agent is bounded only by the machine. If you need a hard CPU cap, a memory ceiling, a wall-clock kill, or an allowlist of reachable hosts, those controls live at the container or VM layer and cannot be retrofitted onto a directory.
Related
Where to go once a directory is no longer a sufficient boundary
Kubernetes Agent Sandbox
The Sandbox CRD and its companions, one rung up the ladder.
Agent Fleets
What it costs to run many agents at once, at any isolation tier.
Sandbox Environments
Isolated execution environments for agents and preview workloads.
MicroVM Isolation
The top rung: dedicated guest kernels via Firecracker and Kata.
Ephemeral Environments
Short-lived environments created and destroyed per branch or task.
AI Agent Orchestration
Assigning, sequencing, and supervising work across many agents.
Agentic Engineering
Practices for building software with agents in the loop.
Sources
Primary research and vendor documentation cited across the site.
