Saturday, July 18, 2026

Git Worktrees for AI Improvement


 

Introduction

 
You might be 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 most important, and so they want it now.

Within the previous workflow, you stash your modifications, swap branches, lose all the things 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. In case you have been working two brokers concurrently on the identical listing, the state of affairs is worse — each brokers touching package deal.json, each producing edits to the identical information, and the second writes silently, overwriting the primary. No warning. No error. Simply corrupted work you uncover an hour later when exams fail in a method that is not sensible.

Git worktrees eradicate this whole class of issues. They don’t seem to be 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 each day, however solely 17% of builders utilizing AI brokers say these instruments have improved crew collaboration. The hole between these two numbers just isn’t a tooling downside. It’s an infrastructure downside. Groups adopted AI brokers with out the workflow layer beneath. This information is that workflow layer.

By the tip, you’ll know what worktrees are, how one can set them up, how one can run parallel AI brokers inside them with out chaos, and how one can preserve them over the lifetime of a mission.

 

What Git Worktrees Really Are

 

A regular Git repository has one working listing — the folder the place your information stay and the place you edit code. To work on a unique department, you turn to it, which modifications all of the information in that listing to match the department. When you’ve got 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 possibly can have as many as you want, every by itself department, all coexisting concurrently in your filesystem.

my-project/                    ← most important worktree  (department: most 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 information, its personal index, and its personal working state. An agent modifying information in my-project-feat-auth/ can not see or contact something in my-project-feat-api/. They’re bodily separate directories that occur to share a git backend.

 
A diagram showing one .git folder at the center with four directory boxes branching out from it
 

Why does this beat a number of clones? The naive various to worktrees is cloning the repository twice and dealing in numerous clone directories. This works, nevertheless it has actual prices: you duplicate your complete repository on disk, git historical past just isn’t shared between clones, commits in a single clone usually are 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 information, not one other copy of the total historical past.

The seven instructions that cowl all the things it’s good to handle worktrees:

 

Command What It Does
git worktree add -b Create a brand new worktree on a brand new department
git worktree add Try an present department into a brand new worktree
git worktree record 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. The whole lot else on this article is a workflow constructed on high of those seven instructions.

 

Setting Up

 
Stipulations: Git 2.5 or greater. Run git --version to examine. 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 finest when your most important department is clear. Commit or stash any in-progress work earlier than creating your first worktree.

# Confirm you've gotten a clear working tree
git standing

# If there may be 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
# Exchange "myapp" together with your mission identify and "feat/auth" together with your department identify
git worktree add -b feat/auth ../myapp-feat-auth most important

# Confirm it was created
git worktree record

 

It’s best to see output like this:

/residence/person/myapp            abc1234 [main]
/residence/person/myapp-feat-auth  abc1234 [feat/auth]

 

Each directories exist. Each comprise the identical information from the most important department. From this level, any modifications you make in myapp-feat-auth/ keep on feat/auth and are utterly remoted from most important.

 

// Step 3: Setting Up the Atmosphere within the New Worktree

That is the step most tutorials skip. A worktree is a brand new working listing. It doesn’t routinely have your .env file, your put in node_modules, or your Python digital surroundings. It’s essential set these up explicitly.

cd ../myapp-feat-auth

# Copy surroundings information which can be gitignored
# .env, .env.native, and comparable information usually are not tracked in git --
# they won't seem within the new worktree routinely
cp ../myapp/.env .env
cp ../myapp/.env.native .env.native 2>/dev/null || true

# Node.js mission: set up dependencies
# Every worktree is an impartial working listing --
# node_modules from the mother or father doesn't carry over
npm set up

# Python mission: create and activate a digital surroundings
# 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

# Change to the principle 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 it’s good to get began. The worktree is stay. 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 solution 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 received its personal worktree. Every worktree received its personal VS Code window. Every window ran its personal AI agent. Dresher’s position shifted from developer to tech lead: scoping duties, reviewing output, guiding brokers that received caught, and merging completed work.

The setup seemed like this:

myapp/                       ← most important window: coordination and evaluations
myapp-feat-authentication/   ← Agent 1: implementing OAuth2 circulate
myapp-feat-api-endpoints/    ← Agent 2: constructing REST endpoints
myapp-bugfix-login-crash/    ← Agent 3: fixing manufacturing bug

 

Every VS Code window was utterly impartial. Language servers, linters, and check runners run per window. The brokers by no means touched one another’s information. When Agent 1 completed, Dresher reviewed the diff, authorized 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:

  1. No context loss. Every AI agent maintained full context of its particular job. 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.
  2. Totally different instruments for various jobs. As a result of every window was impartial, Dresher ran Roo in a single window for fast characteristic improvement and GitHub Copilot with Visible Studio in one other for debugging advanced points. Mixing instruments throughout duties was trivial.
  3. 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.

 
A flowchart showing the hackathon setup
 

The sample that emerged from this hackathon is now a documented finest apply throughout the AI coding group.

 

Operating Parallel AI Brokers With Worktrees

 

The mechanics of the total parallel workflow have 4 levels: 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 — surroundings information, dependency set up, and a clear start line.

Stipulations: Git 2.5+, Bash (macOS/Linux/WSL)

run: Save as create-worktree.sh in your mission root, run chmod +x create-worktree.sh, then ./create-worktree.sh feat/auth-redesign most important.

#!/usr/bin/env bash
# create-worktree.sh
# Creates an remoted worktree for one AI agent job
# Utilization: ./create-worktree.sh  [base-branch]
# Instance: ./create-worktree.sh feat/auth-redesign most 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")"

# Exchange slashes in department identify 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 testing an present department if -b fails
git worktree add -b "$BRANCH" "$WORKTREE_PATH" "$BASE" 2>/dev/null || 
  git worktree add "$WORKTREE_PATH" "$BRANCH"

# Copy non-tracked surroundings information into the worktree
# These are gitignored, so they don't carry over routinely
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
completed

# 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 surroundings
if [ -f "$WORKTREE_PATH/requirements.txt" ] || [ -f "$WORKTREE_PATH/pyproject.toml" ]; then
  echo "Python mission 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 surroundings information throughout (the commonest 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 only most essential 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 beneficial properties in purposeful 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 mission root and commit it. Each agent reads it on session begin. Totally 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 identify.

# AGENTS.md
# Challenge context for AI coding brokers
# Commit this to your repository root.
# Each agent that opens this mission reads it first.

## Challenge Overview
Node.js/TypeScript REST API with a React frontend.
Stack: Node 20, Categorical 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 exams (Vitest)
npm run check:watch   # watch mode
npm run lint         # ESLint and Prettier examine
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/providers/      by no means in route handlers
- Database entry:   src/repositories/  by no means name Prisma straight from providers
- Shared sorts:      src/sorts/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 providers, catch in route handlers
- Department naming: feat/, repair/, refactor/

## Prohibited Zones -- Do NOT modify until explicitly informed to
- src/auth/              (safety crew possession, separate overview course of)
- prisma/migrations/     (solely modify through npm run db:migrate)
- .env information             (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 mustn’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

# Quick kind
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 known as worktree-feat-auth-redesign, then begins the session inside it. The .worktreeinclude file (gitignore syntax) controls which gitignored information are routinely 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 your complete setup saves time and ensures consistency.

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="most 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 most important git worktree add -b "$BRANCH" "$WT_PATH" "$MAIN_BRANCH" 2>/dev/null || git worktree add "$WT_PATH" "$BRANCH" # Copy surroundings information for f in .env .env.native; do [ -f "$REPO_ROOT/$f" ] && cp "$REPO_ROOT/$f" "$WT_PATH/$f" completed echo "Created: $WT_PATH (department: $BRANCH)" completed echo "" echo "All worktrees:" git worktree record 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 surroundings information copied. Operating ./parallel-setup.sh feat/auth feat/api feat/dashboard provides you three remoted working directories in underneath 5 seconds. Open every in its personal terminal tab, fill in AGENTS.md, and begin the brokers.

 

Holding Worktrees From Drifting

 
The largest long-term failure mode just isn’t conflicts at creation time — it’s drift. A worktree that runs for 3 days with out syncing to most important accumulates divergence that makes merging a mission in itself.

Practitioners utilizing Claude Code with worktrees in manufacturing are clear on this: after finishing a checkpoint, pull and merge updates from the principle department — this prevents the worktree from drifting too far, which might end in huge, hard-to-resolve conflicts. The advice is to sync on the finish of each vital agent session, not simply earlier than the PR.

The fitting technique is rebase, not merge. Rebasing writes your department’s commits on high of the newest most important, which retains the historical past linear and makes the PR diff clear.

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 most important
# Run at checkpoints to forestall department drift
# Utilization (from contained in the worktree): ./sync-worktree.sh [main-branch-name]
# Instance: ./sync-worktree.sh most 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 may be 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 most important
# --autostash handles minor working tree variations routinely
git rebase "origin/$MAIN_BRANCH" --autostash

echo ""
echo "Carried out. '$CURRENT_BRANCH' is updated with origin/$MAIN_BRANCH."
echo ""
echo "When able to push:"
echo "  git push --force-with-lease"
echo ""
echo "Notice: --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 examine earlier than the rebase is a crucial security measure. A rebase on a grimy 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 complete merge lifecycle from agent completion to merged PR:

# Contained in the worktree, after the agent finishes its job

# 1. Commit the agent's work
git add .
git commit -m "feat: implement OAuth2 + PKCE auth circulate"

# 2. Sync with most important earlier than opening a PR
./sync-worktree.sh

# 3. Run exams 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 through GitHub CLI or the online interface
gh pr create 
  --title "feat: OAuth2 + PKCE authentication" 
  --body "Implements OAuth2 per docs/auth-spec.md. All exams move."

# 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 most important
git worktree add -b feat/funds ../myapp-payments most important

# Try an present department into a brand new worktree
git worktree add ../myapp-feat-auth feat/auth

# Indifferent HEAD -- helpful for reproducing a bug at a selected commit
git worktree add --detach ../myapp-debug abc1234

# Monitor a distant department straight
git worktree add ../myapp-hotfix origin/hotfix/login-crash

 

// Inspecting and Managing

# Present all worktrees with path, commit hash, and department identify
git worktree record

# Machine-readable output to be used in scripts
git worktree record --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

# Pressure take away even with uncommitted modifications
# Solely use this if you find yourself sure the work may 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 really 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 unique department, or take away the prevailing worktree first
deadly: already exists Goal listing exists Delete it or select a unique path
error: '...' is a most important worktree Tried to take away the principle checkout Solely linked worktrees may be eliminated
error: worktree has modified information Uncommitted modifications current Commit the work, or use --force to discard
Worktree seems in git worktree record after rm -rf Metadata not cleaned up Run git worktree prune

 

Conclusion

 
Git worktrees usually are 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 just isn’t 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 group has converged on for one purpose: it’s the easiest factor that reliably solves the issue it was constructed to resolve.

The setup price is low. The 4 scripts on this article cowl the total lifecycle — create, sync, and clear up — in about 120 traces of bash. The conceptual mannequin is straightforward: one job, one department, one worktree, one agent. The payoff is that you may 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 mission. 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 could try this cleanly, in parallel, with out getting in its personal method.
 
 

Shittu Olumide is a software program engineer and technical author keen about leveraging cutting-edge applied sciences to craft compelling narratives, with a eager eye for element and a knack for simplifying advanced ideas. You too can discover Shittu on Twitter.



Related Articles

Latest Articles