
# Introduction
You’re working Claude Code on a characteristic department. The agent has been working for twenty minutes, it has learn your codebase, constructed up context, and began making actual progress on the authentication rewrite. Then a Slack message seems: manufacturing is down, somebody wants a hotfix on important, and so they want it now.
Within the outdated workflow, you stash your modifications, swap branches, lose every thing your AI agent constructed up, repair the bug, push, swap again, and spend ten minutes getting the agent re-oriented to what it was doing. When you have been working two brokers concurrently on the identical listing, the scenario is worse — each brokers touching bundle.json, each producing edits to the identical recordsdata, and the second writes silently, overwriting the primary. No warning. No error. Simply corrupted work you uncover an hour later when checks fail in a method that is mindless.
Git worktrees remove this whole class of issues. They aren’t a brand new invention — the characteristic has been in Git since model 2.5, launched in 2015 — however the AI coding wave of 2025–2026 made them important infrastructure. One .git listing, a number of working directories, every by itself department, every invisible to the others. Every AI agent will get its personal remoted workspace. The hotfix will get its personal workspace. Nothing collides.
51% {of professional} builders now use AI instruments every day, however solely 17% of builders utilizing AI brokers say these instruments have improved crew collaboration. The hole between these two numbers shouldn’t be a tooling drawback. It’s an infrastructure drawback. Groups adopted AI brokers with out the workflow layer beneath. This information is that workflow layer.
By the top, you’ll know what worktrees are, tips on how to set them up, tips on how to run parallel AI brokers inside them with out chaos, and tips on how to preserve them over the lifetime of a undertaking.
# What Git Worktrees Truly Are
A typical Git repository has one working listing — the folder the place your recordsdata dwell and the place you edit code. To work on a distinct department, you turn to it, which modifications all of the recordsdata in that listing to match the department. If in case you have uncommitted work, you stash it first. In case your AI agent is mid-task, you interrupt it.
Git worktrees break this constraint. A worktree is a separate listing checked out from the identical repository. You’ll be able to have as many as you want, every by itself department, all coexisting concurrently in your filesystem.
my-project/ ← important worktree (department: important)
my-project-feat-auth/ ← linked worktree (department: feat/auth)
my-project-feat-api/ ← linked worktree (department: feat/api)
my-project-hotfix-login/ ← linked worktree (department: hotfix/login)
All 4 directories share the identical .git folder. They share historical past, objects, and commits. However every has its personal checked-out recordsdata, its personal index, and its personal working state. An agent modifying recordsdata in my-project-feat-auth/ can’t see or contact something in my-project-feat-api/. They’re bodily separate directories that occur to share a git backend.

Why does this beat a number of clones? The naive various to worktrees is cloning the repository twice and dealing in several clone directories. This works, however it has actual prices: you duplicate the complete repository on disk, git historical past shouldn’t be shared between clones, commits in a single clone are usually not instantly seen in one other, and there’s no coordination between them on the git layer. With worktrees, you clone as soon as. Each extra worktree provides solely the price of the checked-out recordsdata, not one other copy of the complete historical past.
The seven instructions that cowl every thing that you must handle worktrees:
| Command | What It Does |
|---|---|
git worktree add |
Create a brand new worktree on a brand new department |
git worktree add |
Try an current department into a brand new worktree |
git worktree listing |
Present all energetic worktrees with their branches and commit hashes |
git worktree lock |
Forestall a worktree from being pruned (helpful whereas an agent is working) |
git worktree unlock |
Launch the lock |
git worktree take away |
Delete a worktree cleanly (department is preserved) |
git worktree prune |
Clear up metadata for worktrees that have been manually deleted |
That’s the full floor space. Every part else on this article is a workflow constructed on prime of those seven instructions.
# Setting Up
Stipulations: Git 2.5 or greater. Run git --version to test. Any fashionable system (macOS, Linux, Home windows with WSL or Git Bash) ships with a model above 2.5.
// Step 1: Beginning From a Clear Repository
Worktrees work greatest when your important department is clear. Commit or stash any in-progress work earlier than creating your first worktree.
# Confirm you've a clear working tree
git standing
# If there's uncommitted work, commit it
git add . && git commit -m "checkpoint: work in progress"
// Step 2: Creating Your First Worktree
# Create a brand new worktree at ../myapp-feat-auth on a brand new department feat/auth
# Change "myapp" together with your undertaking title and "feat/auth" together with your department title
git worktree add -b feat/auth ../myapp-feat-auth important
# Confirm it was created
git worktree listing
It’s best to see output like this:
/house/person/myapp abc1234 [main]
/house/person/myapp-feat-auth abc1234 [feat/auth]
Each directories exist. Each comprise the identical recordsdata from the important department. From this level, any modifications you make in myapp-feat-auth/ keep on feat/auth and are utterly remoted from important.
// Step 3: Setting Up the Surroundings within the New Worktree
That is the step most tutorials skip. A worktree is a brand new working listing. It doesn’t mechanically have your .env file, your put in node_modules, or your Python digital setting. You want to set these up explicitly.
cd ../myapp-feat-auth
# Copy setting recordsdata which are gitignored
# .env, .env.native, and related recordsdata are usually not tracked in git --
# they won't seem within the new worktree mechanically
cp ../myapp/.env .env
cp ../myapp/.env.native .env.native 2>/dev/null || true
# Node.js undertaking: set up dependencies
# Every worktree is an unbiased working listing --
# node_modules from the mother or father doesn't carry over
npm set up
# Python undertaking: create and activate a digital setting
# python -m venv .venv && supply .venv/bin/activate && pip set up -r necessities.txt
// Step 4: Verifying the Worktree Is Remoted
# From inside the brand new worktree
git department
# Ought to present: * feat/auth
# Make a check change
echo "// check" >> test-isolation.js
git standing
# Solely reveals the change on this worktree
# Swap to the primary listing and confirm it's unaffected
cd ../myapp
git standing
# Clear -- the test-isolation.js change is invisible right here
ls test-isolation.js 2>/dev/null || echo "Not right here -- isolation confirmed"
That’s all that you must get began. The worktree is dwell. Any agent you open in that listing operates solely on feat/auth.
# A Actual-World Case Examine
The clearest documented instance of git worktrees used for AI-driven parallel improvement comes from the Microsoft World Hackathon 2025.
Tamir Dresher, an engineering lead, confronted an issue that everybody constructing with AI brokers finally hits: too many options, too little time, and no method to work on multiple factor directly with out fixed context-switching. Creating a number of clones of the repository was cumbersome. Switching branches destroyed the AI agent’s context. One thing needed to change.
The answer was to make use of git worktrees to create what Dresher described as a digital AI improvement crew. Every characteristic acquired its personal worktree. Every worktree acquired its personal VS Code window. Every window ran its personal AI agent. Dresher’s function shifted from developer to tech lead: scoping duties, reviewing output, guiding brokers that acquired caught, and merging completed work.
The setup appeared like this:
myapp/ ← important window: coordination and opinions
myapp-feat-authentication/ ← Agent 1: implementing OAuth2 movement
myapp-feat-api-endpoints/ ← Agent 2: constructing REST endpoints
myapp-bugfix-login-crash/ ← Agent 3: fixing manufacturing bug
Every VS Code window was utterly unbiased. Language servers, linters, and check runners run per window. The brokers by no means touched one another’s recordsdata. When Agent 1 completed, Dresher reviewed the diff, permitted it, and opened a pull request (PR) from that department — the identical workflow as reviewing a PR from a human engineer.
Three concrete benefits Dresher documented from the hackathon:
- No context loss. Every AI agent maintained full context of its particular process. Switching between options meant switching VS Code home windows, not branches, not stashes, not agent restarts. The agent’s understanding of what it was constructing stayed intact.
- Completely different instruments for various jobs. As a result of every window was unbiased, Dresher ran Roo in a single window for speedy characteristic improvement and GitHub Copilot with Visible Studio in one other for debugging complicated points. Mixing instruments throughout duties was trivial.
- Clear department administration. If a characteristic wanted to be deserted, closing the window and deleting the worktree took ten seconds. The opposite brokers have been unaffected.

The sample that emerged from this hackathon is now a documented greatest apply throughout the AI coding neighborhood.
# Operating Parallel AI Brokers With Worktrees
The mechanics of the complete parallel workflow have 4 phases: arrange the worktrees, give every agent its context, run the brokers, and checkpoint repeatedly.
// Stage 1: Scripting the Worktree Creation
Don’t create worktrees manually every time. A script ensures each worktree will get the identical setup — setting recordsdata, dependency set up, and a clear start line.
Stipulations: Git 2.5+, Bash (macOS/Linux/WSL)
The way to run: Save as create-worktree.sh in your undertaking root, run chmod +x create-worktree.sh, then ./create-worktree.sh feat/auth-redesign important.
#!/usr/bin/env bash
# create-worktree.sh
# Creates an remoted worktree for one AI agent process
# Utilization: ./create-worktree.sh [base-branch]
# Instance: ./create-worktree.sh feat/auth-redesign important
set -euo pipefail
BRANCH="${1:?Utilization: $0 [base-branch]}"
BASE="${2:-main}"
REPO_ROOT="$(git rev-parse --show-toplevel)"
REPO_NAME="$(basename "$REPO_ROOT")"
# Change slashes in department title with dashes for listing naming
# feat/auth-redesign turns into feat-auth-redesign within the path
WORKTREE_PATH="${REPO_ROOT}/../${REPO_NAME}-${BRANCH////-}"
echo "Creating worktree for department: $BRANCH"
echo "Base department: $BASE"
echo "Worktree path: $WORKTREE_PATH"
# Fetch newest so the brand new department begins from the present distant state
git fetch origin 2>/dev/null || echo "(no distant -- skipping fetch)"
# Create the worktree on a brand new department from the bottom department
# Falls again to trying out an current department if -b fails
git worktree add -b "$BRANCH" "$WORKTREE_PATH" "$BASE" 2>/dev/null ||
git worktree add "$WORKTREE_PATH" "$BRANCH"
# Copy non-tracked setting recordsdata into the worktree
# These are gitignored, so they don't carry over mechanically
for f in .env .env.native .env.improvement .env.check; do
if [ -f "$REPO_ROOT/$f" ]; then
cp "$REPO_ROOT/$f" "$WORKTREE_PATH/$f"
echo "Copied $f"
fi
carried out
# Node.js: set up dependencies within the new working listing
if [ -f "$WORKTREE_PATH/package.json" ]; then
echo "Putting in Node dependencies..."
(cd "$WORKTREE_PATH" && npm set up --silent 2>/dev/null ||
echo "(npm set up skipped -- run it manually within the worktree)")
fi
# Python: remind the developer to arrange their setting
if [ -f "$WORKTREE_PATH/requirements.txt" ] || [ -f "$WORKTREE_PATH/pyproject.toml" ]; then
echo "Python undertaking detected."
echo "Run within the new worktree:"
echo " python -m venv .venv && supply .venv/bin/activate && pip set up -r necessities.txt"
fi
echo ""
echo "Worktree prepared. Open it in your IDE and begin your agent:"
echo " cd $WORKTREE_PATH"
What this does: The script creates the worktree, copies gitignored setting recordsdata throughout (the most typical setup failure), and runs dependency set up within the new listing. The ${BRANCH////-} substitution safely converts department names like feat/auth into filesystem-friendly listing names like feat-auth. The fallback on line 23 handles the case the place the department already exists remotely.
// Stage 2: Setting Up the AGENTS.md Context File
The one most vital factor you are able to do to enhance agent output is give every agent a transparent, written context file. Peer-reviewed analysis at ICSE 2026 confirmed that incorporating architectural documentation into agent context produces measurable good points in useful correctness, architectural conformance, and code modularity. The AGENTS.md file is the way you ship that context reliably, at scale, throughout each session.
Create this file in your undertaking root and commit it. Each agent reads it on session begin. Completely different instruments learn completely different filenames — AGENTS.md (OpenAI Codex), CLAUDE.md (Claude Code), AGENTS.md (generic) — however the content material issues greater than the title.
# AGENTS.md
# Undertaking context for AI coding brokers
# Commit this to your repository root.
# Each agent that opens this undertaking reads it first.
## Undertaking Overview
Node.js/TypeScript REST API with a React frontend.
Stack: Node 20, Specific 5, Prisma ORM, PostgreSQL, React 18, Vite.
## Construct and Take a look at Instructions
npm run dev # begin dev server on port 3000
npm run construct # manufacturing construct to dist/
npm run check # run all checks (Vitest)
npm run check:watch # watch mode
npm run lint # ESLint and Prettier test
npm run db:migrate # run pending Prisma migrations
npm run db:seed # seed improvement information
## Structure
- API routes: src/routes/ one file per useful resource
- Enterprise logic: src/companies/ by no means in route handlers
- Database entry: src/repositories/ by no means name Prisma immediately from companies
- Shared varieties: src/varieties/index.ts
## Conventions
- All exported capabilities require JSDoc feedback
- No console.log in dedicated code -- use src/utils/logger.ts
- Error dealing with: throw typed errors from companies, catch in route handlers
- Department naming: feat/, repair/, refactor/
## Prohibited Zones -- Do NOT modify except explicitly advised to
- src/auth/ (safety crew possession, separate assessment course of)
- prisma/migrations/ (solely modify by way of npm run db:migrate)
- .env recordsdata (by no means commit, by no means learn outdoors config/)
## Present Worktree Process
Process: [FILL IN before starting the agent]
Department: [FILL IN]
Acceptance standards: [FILL IN]
The underside part is what makes this file work per-worktree. Each time you create a brand new worktree, open AGENTS.md and fill in these three traces earlier than beginning the agent. This scopes the agent’s work exactly and prevents it from wandering into areas it shouldn’t contact.
For Claude Code particularly, the native -w flag handles worktree creation and session begin in a single command:
# Create a worktree and begin a Claude Code session inside it
claude --worktree feat/auth-redesign
# Brief type
claude -w feat/auth-redesign
# With tmux panes for split-screen visibility
claude -w feat/auth-redesign --tmux
claude --worktree creates .claude/worktrees/feat-auth-redesign/ on a department referred to as worktree-feat-auth-redesign, then begins the session inside it. The .worktreeinclude file (gitignore syntax) controls which gitignored recordsdata are mechanically copied into new worktrees:
# .worktreeinclude -- place in your repo root
# Information to repeat into each new worktree on creation
.env
.env.native
.env.improvement
// Stage 3: Operating A number of Brokers at As soon as
While you want three or 4 brokers working concurrently, scripting the complete setup saves time and ensures consistency.
The way to run: Save as parallel-setup.sh, run chmod +x parallel-setup.sh, then ./parallel-setup.sh feat/auth feat/api feat/dashboard.
#!/usr/bin/env bash
# parallel-setup.sh
# Creates N worktrees for N parallel AI brokers in a single command
# Utilization: ./parallel-setup.sh ...
# Instance: ./parallel-setup.sh feat/auth feat/api feat/dashboard
set -euo pipefail
if [ $# -eq 0 ]; then
echo "Utilization: $0
... "
echo "Instance: $0 feat/auth feat/api feat/dashboard"
exit 1
fi
REPO_ROOT="$(git rev-parse --show-toplevel)"
REPO_NAME="$(basename "$REPO_ROOT")"
MAIN_BRANCH="important"
echo "Establishing ${#@} parallel worktrees..."
git fetch origin 2>/dev/null || echo "(no distant -- skipping fetch)"
for BRANCH in "$@"; do
SAFE="${BRANCH////-}"
WT_PATH="${REPO_ROOT}/../${REPO_NAME}-${SAFE}"
if [ -d "$WT_PATH" ]; then
echo "Already exists: $WT_PATH (skipping)"
proceed
fi
# Create worktree on a brand new department from important
git worktree add -b "$BRANCH" "$WT_PATH" "$MAIN_BRANCH" 2>/dev/null ||
git worktree add "$WT_PATH" "$BRANCH"
# Copy setting recordsdata
for f in .env .env.native; do
[ -f "$REPO_ROOT/$f" ] && cp "$REPO_ROOT/$f" "$WT_PATH/$f"
carried out
echo "Created: $WT_PATH (department: $BRANCH)"
carried out
echo ""
echo "All worktrees:"
git worktree listing
echo ""
echo "Open every path in a separate terminal or IDE window and begin your agent."
echo "Bear in mind to fill within the Process part of AGENTS.md in every worktree."
What this does: One command produces all of the worktrees with setting recordsdata copied. Operating ./parallel-setup.sh feat/auth feat/api feat/dashboard offers you three remoted working directories in underneath 5 seconds. Open every in its personal terminal tab, fill in AGENTS.md, and begin the brokers.
# Protecting Worktrees From Drifting
The most important long-term failure mode shouldn’t be conflicts at creation time — it’s drift. A worktree that runs for 3 days with out syncing to important accumulates divergence that makes merging a undertaking in itself.
Practitioners utilizing Claude Code with worktrees in manufacturing are clear on this: after finishing a checkpoint, pull and merge updates from the primary department — this prevents the worktree from drifting too far, which might lead to large, hard-to-resolve conflicts. The advice is to sync on the finish of each vital agent session, not simply earlier than the PR.
The appropriate technique is rebase, not merge. Rebasing writes your department’s commits on prime of the newest important, which retains the historical past linear and makes the PR diff clear.
The way to run: Save as sync-worktree.sh, run chmod +x sync-worktree.sh, then run ./sync-worktree.sh from inside any worktree listing.
#!/usr/bin/env bash
# sync-worktree.sh
# Rebases the present worktree department onto the newest important
# Run at checkpoints to stop department drift
# Utilization (from contained in the worktree): ./sync-worktree.sh [main-branch-name]
# Instance: ./sync-worktree.sh important
set -euo pipefail
MAIN_BRANCH="${1:-main}"
CURRENT_BRANCH="$(git rev-parse --abbrev-ref HEAD)"
if [ "$CURRENT_BRANCH" = "$MAIN_BRANCH" ]; then
echo "Already on $MAIN_BRANCH -- nothing to sync."
exit 0
fi
echo "Syncing '$CURRENT_BRANCH' onto '$MAIN_BRANCH'..."
# Reject if there's uncommitted work -- rebase requires a clear state
if ! git diff --quiet || ! git diff --cached --quiet; then
echo "ERROR: Uncommitted modifications detected."
echo "Commit your progress first:"
echo " git add . && git commit -m 'checkpoint: agent progress'"
exit 1
fi
# Fetch the newest distant state
git fetch origin
# Rebase this department onto the newest important
# --autostash handles minor working tree variations mechanically
git rebase "origin/$MAIN_BRANCH" --autostash
echo ""
echo "Executed. '$CURRENT_BRANCH' is updated with origin/$MAIN_BRANCH."
echo ""
echo "When able to push:"
echo " git push --force-with-lease"
echo ""
echo "Word: --force-with-lease is safer than --force."
echo "It refuses to push if another person pushed to this department since your final fetch."
What this does: The uncommitted-changes test earlier than the rebase is a crucial security measure. A rebase on a unclean tree produces a complicated state. --autostash handles minor variations. --force-with-lease on push is safer than --force as a result of it refuses to overwrite distant work you haven’t seen but.
The total merge lifecycle from agent completion to merged PR:
# Contained in the worktree, after the agent finishes its process
# 1. Commit the agent's work
git add .
git commit -m "feat: implement OAuth2 + PKCE auth movement"
# 2. Sync with important earlier than opening a PR
./sync-worktree.sh
# 3. Run checks to confirm nothing broke within the sync
npm run check
# 4. Push the department
git push --force-with-lease origin feat/auth-redesign
# 5. Open a PR by way of GitHub CLI or the online interface
gh pr create
--title "feat: OAuth2 + PKCE authentication"
--body "Implements OAuth2 per docs/auth-spec.md. All checks go."
# 6. After the PR merges, clear up
cd ../myapp
./cleanup-worktree.sh feat/auth-redesign
# The Full Command Reference
Each git worktree command with actual examples. Hold this part open whereas constructing your first workflow.
// Creating Worktrees
# Create a worktree on a brand new department from important
git worktree add -b feat/funds ../myapp-payments important
# Try an current department into a brand new worktree
git worktree add ../myapp-feat-auth feat/auth
# Indifferent HEAD -- helpful for reproducing a bug at a particular commit
git worktree add --detach ../myapp-debug abc1234
# Observe a distant department immediately
git worktree add ../myapp-hotfix origin/hotfix/login-crash
// Inspecting and Managing
# Present all worktrees with path, commit hash, and department title
git worktree listing
# Machine-readable output to be used in scripts
git worktree listing --porcelain
# Lock a worktree so prune doesn't take away it
# Use whereas an agent is working to guard in opposition to unintentional cleanup
git worktree lock ../myapp-feat-auth --reason "agent-running"
# Launch the lock
git worktree unlock ../myapp-feat-auth
# Transfer a worktree listing (shut any open editors first)
git worktree transfer ../myapp-feat-auth ../worktrees/auth-redesign
// Cleanup
# Take away a worktree cleanly -- the department is preserved in git
git worktree take away ../myapp-feat-auth
# Drive take away even with uncommitted modifications
# Solely use this if you find yourself sure the work could be discarded
git worktree take away --force ../myapp-feat-auth
# Clear up metadata for worktrees manually deleted with rm -rf
git worktree prune
# Preview what could be pruned with out truly pruning
git worktree prune --dry-run
# Repair worktree references after shifting the .git listing
git worktree restore
# Frequent Errors and Fixes
| Error Message | Trigger | Repair |
|---|---|---|
deadly: 'feat/auth' is already checked out |
Department in use by one other worktree | Use a distinct department, or take away the prevailing worktree first |
deadly: |
Goal listing exists | Delete it or select a distinct path |
error: '...' is a important worktree |
Tried to take away the primary checkout | Solely linked worktrees could be eliminated |
error: worktree has modified recordsdata |
Uncommitted modifications current | Commit the work, or use --force to discard |
Worktree seems in git worktree listing after rm -rf |
Metadata not cleaned up | Run git worktree prune |
# Conclusion
Git worktrees are usually not superior Git arcana. They’re a core infrastructure primitive that grew to become important the second AI coding brokers began working in parallel on the identical codebases.
The workflow on this article shouldn’t be theoretical. It’s what Tamir Dresher’s crew ran on the Microsoft World Hackathon. It’s what practitioners with Claude Code, Cursor, and Codex are documenting throughout GitHub and Medium proper now. It’s the sample the agentic coding neighborhood has converged on for one purpose: it’s the easiest factor that reliably solves the issue it was constructed to unravel.
The setup value is low. The 4 scripts on this article cowl the complete lifecycle — create, sync, and clear up — in about 120 traces of bash. The conceptual mannequin is easy: one process, one department, one worktree, one agent. The payoff is you can run a number of brokers in parallel with out spending your afternoon untangling conflicts that neither agent created deliberately.
In case you are already utilizing AI coding instruments and never utilizing worktrees, set them up in your subsequent undertaking. The create-worktree.sh script is a ten-second begin. In case you are constructing a crew workflow round AI brokers, AGENTS.md and the parallel setup script transfer you from ad-hoc periods to a repeatable course of that scales.
The mannequin writes the code. Your job is to create the circumstances the place it may possibly try this cleanly, in parallel, with out getting in its personal method.
Shittu Olumide is a software program engineer and technical author enthusiastic about leveraging cutting-edge applied sciences to craft compelling narratives, with a eager eye for element and a knack for simplifying complicated ideas. You can too discover Shittu on Twitter.
