Skip to main content
InfraGap.com Logo
Home
Getting Started
Core Concept What is a CDE? How It Works Benefits CDE Assessment Getting Started Guide Inner Loop vs Outer Loop Environment Drift Local vs Cloud CDEs for Startups
AI & Automation
AI Coding Assistants Agentic AI AI-Native IDEs Agentic Engineering AI Agent Orchestration AI Governance AI-Assisted Architecture Shift-Left AI LLMOps Autonomous Development AI/ML Workloads CDEs for Data Science GPU Computing
Agent Infrastructure
Agent Experience (AX) Agent Egress Control Computer Use Agents Agent Evals Agent Runbooks Agent Client Protocol AGENTS.md MCP Servers Git Worktrees Kubernetes Agent Sandbox Agent Fleets Agent Identity Prompt Injection Defense Agent Observability Context Engineering AI Code Review Bottleneck Headless Agents in CI Spec-Driven Development Agent Readiness Code Provenance
Implementation
Architecture Patterns DevContainers Advanced DevContainers Language Quickstarts IDE Integration CI/CD Integration Platform Engineering Developer Portals Container Registry Multi-CDE Strategies Remote Dev Protocols Nix Environments Hermetic Builds OpenTofu for CDEs Kubernetes Development
Operations
Performance Optimization High Availability & DR Disaster Recovery Monitoring Capacity Planning Multi-Cluster Development Troubleshooting Runbooks Ephemeral Environments Sandbox Environments Workspace Snapshots Database Branching
Security
Security Deep Dive Zero Trust Architecture Secrets Management Vulnerability Management Network Security IAM Guide Supply Chain Security Air-Gapped Environments AI Agent Security MicroVM Isolation Compliance Guide EU AI Act Cyber Resilience Act Data Residency Governance
Planning
Pilot Program Design Stakeholder Communication Risk Management Migration Guide Cost Analysis FinOps GreenOps Vendor Evaluation Training Resources Developer Onboarding Team Structure Platform Maturity Model Open Source CDEs AI Productivity Paradox Build vs Buy DevEx Metrics Productivity Engineering Industry Guides CDEs for Healthcare CDEs for Financial Services CDEs for Government Edge Development WebAssembly in CDEs
Resources
Tools Comparison State of CDEs 2026 Isolation Decision Tool Template Library
Learning Paths
All Paths Platform Engineer Security and Compliance Engineering Manager
Vendor Reviews
GitHub Codespaces Coder Ona Google Workstations Microsoft Dev Box Okteto Eclipse Che DevPod Daytona E2B
Head to Head
Coder vs Codespaces Coder vs Ona Ona vs Codespaces Coder vs Okteto Self-Hosted vs Managed E2B vs Daytona CDE Market Guide CDE vs Alternatives Case Studies Lessons Learned Glossary FAQ Sources & Citations

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 prune

Two 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

TierBoundaryStartupMarginal costBlast radius if compromised
Git worktreeDirectory onlySecondsOne checkout of diskThe whole developer machine
Container / devcontainerNamespaces, cgroupsSecondsContainer image plus limitsShared host kernel
Kubernetes Sandbox CRDNamespaced pod, policy, RuntimeClassSeconds, near-instant from a warm poolPod plus cluster overheadNode kernel, narrowed by gVisor or Kata
MicroVMHypervisor, dedicated guest kernelHundreds of millisecondsGuest kernel plus VMM overheadOne 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 2

Ramp: 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 Agent

This 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

1

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.

2

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.

3

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.

4

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.