Ends in
00
days
00
hrs
00
mins
00
secs
ENROLL NOW

25% OFF All Reviewers on our International Women's Month Sale Extension! Save 10% OFF All Subsciption Plans & 5% OFF Store Credits/Gift Cards

Git Worktrees: Unlocking Git’s Hidden Potential

Home » Others » Git Worktrees: Unlocking Git’s Hidden Potential

Git Worktrees: Unlocking Git’s Hidden Potential

Git has a feature most developers have never used: Git worktrees. It has been in the codebase since 2015, documented in the official manual, and available in every installation. It lets you check out multiple branches of the same repository at once, each in its own directory, without cloning the repo again. The feature is called git worktree.

Worktrees were a niche tool for years, little used by most teams. With the rise of AI coding agents, worktrees became essential. OpenAI’s Codex and Anthropic’s Claude Code now rely on worktrees to isolate parallel coding tasks, making them a vital tool for agentic coding.
 
Git worktree diagram centered around a Git repository

What a Git Worktree Is

Every git repository has a working tree. It is the directory where your files live, the place where you edit code, run tests, and see the results of git checkout. When you clone a repo, you get one working tree tied to one branch. If you want to look at a different branch, you switch to it, and your working tree changes to reflect that branch’s state.

A Git Worktree is another working tree attached to the same repository. Each worktree has its own directory, checked-out branch, and staging area. All worktrees share the .git directory, so they have the same commit history, remotes, tags, and objects. Commits or fetched changes in one worktree appear in all others.

Running git worktree add ../my-feature feature-branch creates a new directory at ../my-feature, checks out the feature-branch there, and links it back to your main repository. You now have two working directories. You can cd between them. Each one has its own files, its own HEAD, its own index.

The important constraint: a single branch can only be checked out in one worktree at a time. This prevents the ambiguity of having two working trees that could both commit to the same branch with diverging changes.

Under the hood, it is simpler than it seems. The new directory has a .git file that points to the main repository. Git adds a .git/worktrees/<name> folder holding the per-worktree state: a HEAD, an index, and a pointer back. All other data—objects, packs, refs—is shared.

Worktrees are cheap to create. Git does not copy the object database. It just checks out files and sets up a few pointer files.

What Worktrees Replace

The most common workflow before worktrees: you are halfway through a feature, a bug comes in, you run git stash, switch branches, fix the bug, switch back, run git stash pop, and hope your stashed changes apply cleanly. This works for small interruptions. It breaks down when the interruption takes hours, when you have multiple stashes and lose track of which is which, or when the stash conflicts with changes that happened while you were away.

The Limits of Stashing
Stashing also forces you to stop what you are doing. Your dev server might be running. Your test suite might be in a specific state. You lose all of that context. With worktrees, you leave your feature directory untouched and open a new terminal in a different directory. Your dev server keeps running.

Some developers keep multiple clones instead, but clones waste disk space and are disconnected from each other. A commit in one clone is invisible from the other until you push and fetch. Worktrees share everything that should be shared and separate everything that should be separate.

Switching branches also has a cost that compounds over time. In compiled languages, switching means recompiling from scratch. With worktrees, each directory maintains its own node_modules and build artifacts. Switching context is cd ../other-worktree. The build cache is warm. Nothing needs to be re-run.

A Day with Worktrees

Here is how a morning might go using worktrees on a mid-sized TypeScript project.

You start the day on a feature branch, user-profile-redesign. The dev server is running, you have unsaved changes in three files, and your test watcher is showing green.

Tutorials dojo strip

A Slack message arrives: a customer is hitting a crash on the payment page.

git worktree add ../payments-crash main
cd ../payments-crash
npm install

The npm install takes about 30 seconds. You find the bug – a null check is missing on a response field. You fix it, write a test, commit, push. Total time away from your feature work: twelve minutes. Your dev server in the other terminal never stopped. Your unsaved changes are still there.

An hour later, the PR is merged. You clean up:

git worktree remove ../payments-crash
git branch -d fix/payment-null-check

Later, a colleague asks you to review their PR for a database migration. Instead of checking out their branch in your main directory (which would trigger a full rebuild), you create another worktree, run the tests, read the migration files, leave comments, and remove the worktree. Your feature branch was never noticed.

Each interruption gets its own directory. Each directory has its own state. When the interruption is complete, the directory disappears.

The Agentic Coding Connection

For years, worktrees were a workflow optimization. Useful, but not transformative. Then AI coding agents changed the equation.

An AI coding agent reads your codebase, makes edits, runs commands, and iterates on results. The key property that makes worktrees essential is that these agents can run in parallel. One agent writes a new feature, while another fixes a bug, while a third refactors a test suite.

The Shared State Problem
Consider what happens when two agents share a single working directory. Agent A is midway through refactoring an authentication module. It has deleted an old helper function and updated three call sites. Agent B, working on an unrelated payment feature, runs git add to stage its changes. Agent B’s staging captures Agent A’s half-finished refactor. If Agent B commits, the commit contains a mix of payment code and a broken auth module.

AI agent handling multiple worktrees of a directory

The problems compound. Agent A runs tests and sees failures from Agent B’s changes. Agent B’s build fails because Agent A deleted a function. Both agents start “fixing” errors that the other caused. This is the standard shared-mutable-state problem, applied to the filesystem.

Separate clones provide isolation, but at a high cost: cloning a large repository takes time and disk space. More importantly, each clone is disconnected—Agent A’s commits are invisible to Agent B until pushed and fetched. Worktrees solve this. Each agent has a directory and a staging area, but all share the same object database. Commits become immediately visible to everyone.

Docker containers provide stronger isolation, but break the connection to the local repository. The practical answer is not either-or. Codex uses containers for security and worktrees for git isolation within those containers. Claude Code uses worktrees directly for local isolation.

How Claude Code and Codex Use Worktrees

Claude Code’s --worktree flag starts a session in an isolated git worktree:
claude --worktree feature-auth
claude --worktree bugfix-123

This creates a worktree at <repo>/.claude/worktrees/feature-auth/, branching from the default remote branch. Claude operates entirely within this worktree. Your checkout is untouched. When you exit, Claude cleans up automatically if the agent made no changes, or asks whether to keep the worktree if changes exist.

Claude Code also supports worktree isolation at the subagent level. A subagent configured with isolation: worktree gets its own temporary worktree. Multiple subagents can run in parallel, each in its own worktree, each working on an independent task.

Different Architectural Approaches
Codex takes a different architectural approach. Where Claude Code runs locally, Codex runs tasks in cloud sandbox environments. Each task gets a sandbox preloaded with a copy of your repository. Codex worktrees operate in detached HEAD state rather than as named branches, which sidesteps the one-branch-per-worktree constraint entirely. Multiple tasks can start from the same branch state without conflicts.

Codex also includes a “Handoff” feature for moving threads between your local checkout and a worktree, solving the problem of wanting an agent to continue work on a branch you’re currently checking out.

Both tools use worktrees for one reason: they are the lightest, fastest way to isolate work without sacrificing the ability to see the latest code or share results instantly. Claude Code provides this at the filesystem level, Codex inside a remote sandbox. In both cases, developers and agents move faster and with less friction.

Patterns Worth Knowing

When running parallel agents, assign one agent per worktree with a clear, bounded task. “Fix the login validation bug” is better than “improve the authentication system.” Bounded tasks produce bounded diffs that are easier to review and merge.
Git branches and git worktrees diagram
One pattern that surprised me with how well it works: when facing a design decision with two possible approaches, assign each approach to a separate agent in a separate worktree. Both agents implement the feature their way. You compare the resulting diffs, evaluate tradeoffs with real code, and keep the approach you prefer. It costs twice as much as the computer. It costs almost no developer time. For decisions that would be expensive to reverse, the tradeoff is worth it.

Limitations

The biggest practical limitation: worktrees do not copy untracked or ignored files. A new worktree in a Node.js project has no node_modules. A new worktree in a Python project has no virtual environment. You need to run your setup process in each new worktree. Automate this with a setup script, or with Claude Code’s WorktreeCreate hook that runs setup commands when a worktree is created.

One Branch, One Worktree
A branch can only be checked out in one worktree at a time. Codex works around this by using detached HEAD. If you need the same branch in two places, git worktree add --detach is the escape hatch.

Worktrees do not help with the hardest part of parallel development: merging. Two agents working on different files will merge cleanly. Two agents working on the same files will produce conflicts. Worktrees defer conflicts to merge time, which is better than collisions during development, but they do not eliminate them. A useful heuristic: if two tasks touch the same files, run them sequentially. If they touch different files, worktrees let them run safely in parallel.

The Bigger Shift

The adoption of worktrees by both Claude Code and Codex validates a particular model of agent-human collaboration. The agent works on a branch in a worktree. The human reviews the branch and decides whether to merge. This is the same pull request workflow teams already use for human-to-human collaboration, reviewed through the same tools.

The bottleneck moves from writing code to reviewing code. A single developer can run multiple agents on multiple tasks simultaneously. Worktrees make this possible at the git level, but the bigger change is organizational: the developer becomes a reviewer and coordinator rather than the sole author. Codebases that are modular, have clear boundaries, and have good test coverage are easier to parallelize. The same properties that make code maintainable for humans also make it amenable to parallel-agent work.

Git worktrees has been in git for a decade. What changed is that AI agents turned a useful workflow optimization into a practical requirement. If you write code with AI agents, or plan to, worktrees are worth learning. They are the mechanism that enables parallel agentic coding.

References

  • git-worktree documentation – the official reference. Covers every subcommand, flag, and internal detail, including shared vs. per-worktree state.
  • How I use git worktrees by Bill Mill – a practical workflow post. His wrapper script for reducing git worktree add friction and his copy-on-write trick for node_modules are both worth stealing.
  • Claude Code: common workflows – the –worktree flag, worktree cleanup behavior, WorktreeCreate hooks, and how sessions persist across worktrees.
  • Codex app: worktrees – how Codex manages worktrees in detached HEAD state, the Handoff feature, and automatic cleanup with snapshot restoration.
Free AWS Courses

🌸 25% OFF All Reviewers on our International Women’s Month Sale! Save 10% OFF All Subscriptions Plans & 5% OFF Store Credits/Gift Cards!

Tutorials Dojo portal

Learn AWS with our PlayCloud Hands-On Labs

$2.99 AWS and Azure Exam Study Guide eBooks

tutorials dojo study guide eBook

New AWS Generative AI Developer Professional Course AIP-C01

AIP-C01 Exam Guide AIP-C01 examtopics AWS Certified Generative AI Developer Professional Exam Domains AIP-C01

Learn GCP By Doing! Try Our GCP PlayCloud

Learn Azure with our Azure PlayCloud

FREE AI and AWS Digital Courses

FREE AWS, Azure, GCP Practice Test Samplers

SAA-C03 Exam Guide SAA-C03 examtopics AWS Certified Solutions Architect Associate

Subscribe to our YouTube Channel

Tutorials Dojo YouTube Channel

Follow Us On Linkedin

Written by: Duncan Bandojo

Duncan F. Bandojo is a undergraduate of Computer Science at Polytechnic University of the Philippines, with an interest in backeend development and geospatial data analysis, and is currently diving into frontend development. He is passionate about building applications that leverage visual data (geospatial) to provide visual insights that genuinely helps people.

AWS, Azure, and GCP Certifications are consistently among the top-paying IT certifications in the world, considering that most companies have now shifted to the cloud. Earn over $150,000 per year with an AWS, Azure, or GCP certification!

Follow us on LinkedIn, YouTube, Facebook, or join our Slack study group. More importantly, answer as many practice exams as you can to help increase your chances of passing your certification exams on your first try!

View Our AWS, Azure, and GCP Exam Reviewers Check out our FREE courses

Our Community

~98%
passing rate
Around 95-98% of our students pass the AWS Certification exams after training with our courses.
200k+
students
Over 200k enrollees choose Tutorials Dojo in preparing for their AWS Certification exams.
~4.8
ratings
Our courses are highly rated by our enrollees from all over the world.

What our students say about us?