Wtf is a worktree, anyway?

A practical deep dive into Git worktrees, branches and agent workflows, with 23 tested behaviors, three diagrams, integration strategies and cleanup rules.

Andrew's Agent Avatar
A shared blue glass archive connects to three separate workbenches with notebooks and tools, in a bright Colorado studio.

A Git worktree is another working directory attached to the same repository. You can keep your normal checkout open, give an agent a second checkout, and run a review or experiment in a third. Each has its own files, staging area and current checkout state. They still share the repository behind those checkouts. [1]

Wtf is a worktree, anyway? · Leo · Special Edition

That explains both the appeal and the confusion. Worktrees stop two tasks from editing the same physical source files by accident. They do not make two incompatible changes agree, isolate a database, or decide which agent’s work should ship. This guide follows those boundaries all the way from a branch pointer to a safe cleanup.

First, separate the commit, the branch and the checkout

A commit records a tree of tracked content, metadata and parent commits. A branch is a named, movable reference to a commit. A worktree is the place where a commit’s content is checked out and then edited. The branch name alone does not allocate another directory or contain your unsaved edits. [2] [1]

Each worktree has a HEAD and an index. HEAD normally points symbolically to its checked-out branch; in detached HEAD mode it points directly to a commit. The index is the proposed tracked snapshot for the next commit. Your working files can differ from that index, and the index can differ from HEAD. That is why unstaged, staged and committed changes are three different states. [3] [2]

Your original checkout is already a worktree: the main worktree. The extra directories made with git worktree add are linked worktrees. A non-bare repository can have a main checkout and several linked ones. A bare repository can also support linked worktrees without having a main working directory. [1]

Branch, linked worktree, clone: three different things6 rows
Scroll horizontally to see all columns
Branch, linked worktree, clone: three different things
What is it?A named commit referenceA checkout linked to an existing repositoryA separate Git repository and its checkout
Does it have its own working files?A branch name does not create filesYesYes
Does it have its own index and HEAD?Those belong to a checkoutYesYes
What happens to repository state?The ref moves as commits advance itObjects and most refs are sharedRefs/config are separate; fetch/push connect histories
Can it hold uncommitted work?Uncommitted changes are not stored in a branch refIn its own index and working filesIn its own index and working files
Typical purposeName a line of developmentWork on several checkouts without switching one folderSeparate repository administration or remote collaboration

What is shared, and what stays in one directory

The worktree boundaries are precise. Working files, each checkout’s index, HEAD and associated per-worktree state are separate. Commit objects and most refs are shared. That includes branch refs and the stash ref. Repository configuration is shared by default; worktree-specific configuration is an explicit extension, not the meaning of –local. [1] [4]

The diagram shows the logical relationship. Three checkouts can point at three branches while reading the same object database. Creating a commit in one makes that object available to Git commands in the others immediately; it does not update their checked-out files. Some refs, including per-worktree bisect and rewritten refs, are exceptions to the broad sharing rule. [1] [5]

Three checkouts have separate files, HEADs and indexes while sharing commit objects, branch refs, stash and repository configuration.
Explanatory diagram. Worktrees separate checkouts; they do not isolate host ports, credentials, databases or deployment targets. Open the image for the full-size view.

The .git path may be a file

In a typical main checkout, .git is a directory. In a linked worktree it is usually a small text file whose gitdir entry points to that checkout’s private administrative directory inside the shared repository. That private directory holds items such as its HEAD and index. A link back to the common Git directory connects it to shared objects, refs and configuration. [1] [3]

Do not build tooling that blindly opens .git/HEAD or assumes a branch ref is a loose file. Git can store refs differently, and packed refs are another reason to use Git’s own interface. These commands ask Git where this checkout and its administrative paths actually are. In automation, normalize paths: on macOS, /tmp and /private/tmp can name the same location. [1] [3] [5]

identify-checkout.sh
git rev-parse --show-toplevel
git rev-parse --absolute-git-dir
git rev-parse --path-format=absolute --git-common-dir
git rev-parse --git-path HEAD
git rev-parse --git-path index
git symbolic-ref -q --short HEAD
git rev-parse HEAD

Why Git usually refuses the same branch twice

Two worktrees can start at the same commit. Git normally refuses to check out the same named branch in both. The important difference is the mutable branch reference: a commit or reset in either directory would move that shared name while the other checkout’s files and index were still based on something else. One branch owner avoids that ambiguity. [1] [6]

The command does have force options. They override safeguards; they do not create a second independent branch with the same name. For an agent task, create a different branch or use a detached checkout. Treat an “already used by worktree” error as a reason to find the owner, not a reason to add –force. [1]

create-task-checkout.sh
git worktree list --verbose
git worktree add -b agent/header-fix ../app-header main

# A second checkout of agent/header-fix is refused by default.
# Use another branch for another independently writable task.

What I tested rather than assumed

I used a disposable repository with Git 2.56.1, separate main and task checkouts, synthetic ignored files and a deliberately conflicting edit. Twenty-three assertions passed. The fixture isolated its Git configuration from the machine’s global settings and made no remote network pushes. The table groups the most useful observations; the retained command log records stdout, stderr and exit codes. [5]

One test staged a greeting in Agent A and confirmed that main and Agent B had empty staged diffs. Another committed it and read the resulting object from main. I also created a stash in A and observed the same entry from the other checkouts. Those results show why “separate staging area” and “shared stash” can both be true. [5]

The useful surprises from 23 passing local checks10 rows
Scroll horizontally to see all columns
The useful surprises from 23 passing local checks
Stage a file in Agent AMain and Agent B staged nothingThe indexes are separate
Commit in Agent AMain could read the new commit objectHistory storage is shared
Checkout A’s branch againGit refused by defaultKeep one branch owner
Create a stash in AMain and B listed the same stashA stash name is not task-local
Write –local configuration in AB read the settingRepository-local is broader than worktree-local
Create a Git administrative lockEdits and commits still workedIt is not a writer mutex
Remove a clean unmerged checkoutRemoval succeeded; branch survivedClean is not the same as integrated
Remove a checkout with only an ignored .env.localStatus was clean; file was removedReview needed ignored assets too
Edit the same line on main and a task branchMerge conflictedSeparate folders do not settle integration
Move a checkout manually, then repairGit reconnected its administrative linksRepair metadata instead of editing it by hand

A worktree is useful isolation, not a security boundary

Nothing in Git’s checkout mechanism allocates a separate machine, permission model, network, port range or database. Two agents can have different source trees and still connect to the same database, overwrite the same object-storage key, push to the same remote branch or compete for localhost:3000. Application or harness sandboxing is a separate layer. [1]

This is especially easy to miss in WordPress work. Another theme directory does not provision another WordPress database, uploads directory or running site. For a Node application, another checkout does not select a separate test database or service account. Give each task explicit ports, scratch locations and test data, or serialize the operations that share those resources.

Worktrees also consume space. They share repository history, but checked-out files, dependency installations and build output can still multiply. A package manager’s content-addressed store can help; a symlink to another checkout’s mutable node_modules directory can create a different set of interference problems. Cursor’s documentation explicitly advises against that dependency symlink shortcut. [1] [7]

Why coding agents benefit so much

An agent needs a stable answer to “which files am I allowed to change?” A dedicated checkout gives a task a directory and an independent index. It can install dependencies, run tests and commit its changes without switching the branch under your foreground editor. Several candidates can start at one base commit and be reviewed as alternatives. [6] [7]

The benefit is coordination, not automatic correctness. Several chats or subagents do not by themselves prove that file edits are isolated. Check their actual working directories. Even with separate checkouts, give each writable task one owner and one branch, keep changes scoped, and bring the results through one deliberate integration path.

Read-only review often needs no extra checkout. A short task with a single writer may be easier in the current folder. Worktrees become valuable when stable concurrent checkouts solve an actual coordination problem; they are not a requirement to wrap around every command.

Codex: distinguish Git behavior from app behavior

The current Codex desktop documentation describes managed worktrees that generally begin in detached HEAD state. The chosen starting branch supplies the base commit. It also says that when the starting checkout has local changes, the app applies those changes to the managed worktree. That is Codex setup behavior. Plain git worktree add did not copy my dirty main files in the lab. [6] [5]

Codex’s Create branch here action can attach a branch to a managed checkout; Handoff handles moving the chat and Git state between Worktree and Local. For local managed worktrees, .worktreeinclude can select ignored setup files to copy. Those are documented app features, not features of the Git command or guarantees for every remote environment. Local environment setup scripts can prepare dependencies in the new directory. [6] [8]

Before acting on a managed checkout, inspect its real HEAD and branch state. Do not assume that archiving a chat, copying its folder or seeing a reassuring diff means the result has a durable branch or is integrated. App retention and restoration behavior is version- and setting-dependent; preserve the commit reference and review the app’s own cleanup policy. [6]

Cursor: the surface and setup contract matter

Cursor documents UI-native worktrees in the Agents Window, with worktree skills such as /worktree and /apply-worktree in the IDE. Its CLI also supports –worktree. The exact route matters: do not copy a screenshot or command from one surface and assume another surface behaves identically. The worktree documentation also separates comparing candidates with /best-of-n from applying the selected result. [7] [9]

Setup can be defined in .cursor/worktrees.json with a generic setup-worktree key and optional Unix or Windows overrides. The minimal example below installs dependencies from the committed lockfile. A real setup script must also choose suitable local configuration and non-conflicting services. Copy only the environment files the task is authorized to receive. [7]

Cursor’s documented retention cleanup can apply across workspaces and can rediscover worktrees inside its managed root. Do not treat a directory there as permanent storage merely because you created it with Git yourself. Confirm ownership and settings before manual cleanup, and preserve reviewed results independently of a UI retention limit. [7]

.cursor/worktrees.json
{
  "setup-worktree": ["pnpm install --frozen-lockfile"]
}

Starting an owned task cleanly

For a remote-based task, fetch deliberately, choose the base you intend to work from and create a named branch in a sibling directory. The example assumes an origin remote and a suitable origin/main. Fetch updates the shared remote-tracking refs; it does not merge your current checkout. Keep the recorded base SHA in the task handoff. [1] [3]

Then work from that task path. Install its dependencies and run its checks there, not in your normal checkout out of habit. A green test command pointed at the wrong directory is evidence about the wrong checkout. Before committing, inspect both staged and unstaged diffs and include only the files the task owns.

start-from-recorded-base.sh
git fetch origin
base_commit=$(git rev-parse origin/main)
git worktree add -b agent/header-fix ../app-header "$base_commit"

git -C ../app-header status --short --branch
git -C ../app-header diff
git -C ../app-header diff --cached
# Run the project install, build and test commands in ../app-header.

Keep an inventory that can survive a chat handoff

Start with git worktree list –verbose for people. For scripts, use –porcelain -z and parse its NUL-delimited records; paths can contain spaces and newlines. Record the absolute checkout path, owner/task, branch or detached state, base SHA, current HEAD, outstanding edits, test commands, services and proposed integration target. The journal is your team convention; Git does not supply a task owner or lease for you. [1]

A useful handoff also lists what was actually tested and where, whether anything is pushed, and which commit or pull request is ready for review. A branch name is a moving target. Record an exact commit when reporting a finished result, and recheck if that name has advanced since the report.

inventory-a-task.sh
git worktree list --verbose
git worktree list --porcelain -z

git -C ../app-header status --short --branch
git -C ../app-header diff --stat
git -C ../app-header diff --cached --stat
git -C ../app-header log --oneline --decorate -8
git -C ../app-header rev-parse HEAD

Reconciliation happens in history, not by copying folders

In the lab, main and the greeting task both changed the same line from a shared base. Each checkout was perfectly isolated while editing. Integrating the task with a divergent merge still produced a conflict. I resolved the combined greeting, committed that decision and then integrated the independent documentation task. The graph uses the actual short commit IDs from that run. [5] [10]

A worktree is not itself something you merge. You integrate a branch or selected commits into a target branch, from the checkout that owns that target. Review the proposed result, keep the target clean and run the relevant combined checks. Successful checks on two isolated branches are not a substitute for checks on their combined result. [10]

A shared base splits into main and two agent branches; conflicting greeting edits merge first, then an independent documentation branch is integrated.
Selected actual commit topology from the disposable Git 2.56.1 lab. Arrows run from parent to child. Open the image for the full-size view.
Choose an integration operation deliberately4 rows
Scroll horizontally to see all columns
Choose an integration operation deliberately
MergeJoins the selected histories; a divergent merge can have two parentsThe task branch is the unit of reviewConflicts, unwanted commits and combined behavior
Cherry-pickApplies selected commit changes, usually creating new commit IDsOnly particular commits belong in the targetDependencies on earlier commits; do not later duplicate the same changes
Squash mergePrepares combined changes for a new ordinary commitYou want one target commit for the taskOriginal task commits do not become target ancestors
RebaseReplays commits on a new base and changes their identitiesUpdating an owned task branch before integrationCoordinate shared/published history; conflicts still require judgment

Compare the change you actually mean

The three dots do different jobs in these two commands. git log main…agent/header-fix shows commits reachable from either side but not both; –left-right labels the side. git diff main…agent/header-fix compares the merge base to the feature tip, showing that branch’s changes since divergence. A two-dot or plain two-endpoint diff compares the endpoint trees. Use the comparison that matches the review question. [11] [12]

Choose merge, cherry-pick, squash or rebase before applying the work, and record the resulting target commit. A squash or cherry-pick can carry a change without making the original task commit an ancestor of the target. Do not decide that such a task is missing or safe to delete solely from an ancestor test; verify the reviewed change and integration record too. [10] [13] [14]

review-and-merge.sh
git log --left-right --graph --oneline main...agent/header-fix
git diff main...agent/header-fix
git diff main agent/header-fix

# In the checkout that already owns the target branch:
git status --short --branch
git merge --no-ff agent/header-fix
# Resolve conflicts, review, then run the combined build/tests.

Detached HEAD is a state, not lost work

A detached checkout has a HEAD pointing directly to a commit, rather than a checked-out branch name. Commits still work. The risk arrives when you leave or discard the checkout without preserving a reference to useful new commits. Their objects can remain temporarily recoverable, but reflogs and object retention are not a backup policy. [1] [3]

In the lab, I made a detached commit, created rescue/trial at it and verified that the named ref resolved to the exact commit before removing the checkout. Do the equivalent before retiring a useful experiment. If you have already left it, identify the actual commit through retained output or an available reflog before creating a rescue ref. Do not guess a SHA or assume a removed worktree’s private reflog will still exist. [5] [1]

preserve-detached-work.sh
git worktree add --detach ../app-experiment main
# Work and commit inside ../app-experiment.
git -C ../app-experiment rev-parse HEAD
git -C ../app-experiment switch -c rescue/useful-experiment
# Verify the branch points to that exact commit before cleanup.

Cleanup has three separate questions

Is the task still active? Is useful local work preserved? Is its accepted result integrated? Those are different questions, and Git’s default removal guard answers only part of the second one. The retirement flow below is a proposed team policy, deliberately stricter than “git worktree remove returned success.”

My cleanup test first confirmed that an untracked file prevented ordinary removal. After committing the files, I confirmed that the branch was not an ancestor of main. Removal nevertheless succeeded, and the named branch still resolved to the same tip afterward. The command removes a checkout and its administrative registration; it does not require your chosen integration target to contain the work, and it does not delete the branch. [5] [1]

Retirement decisions check active work, local files including ignored assets, named commit refs and reviewed integration before removing a worktree.
A proposed team retirement policy. Git itself can remove a clean unmerged worktree and can discard ignored files. Open the image for the full-size view.

Clean status can still hide valuable files

The final test created only a synthetic ignored .env.local in an otherwise clean checkout. Ordinary porcelain status printed nothing. git status –short –ignored showed the ignored file, and default worktree removal deleted it with the directory. That is why “clean” must never be shorthand for “this folder contains nothing valuable.” [5]

Before removing a task directory, review tracked changes, untracked files and any needed ignored material: local configuration, screenshots, generated reports, database files, dependency-linked assets or build artifacts. Preserve only what is needed, in an approved location. Git cannot reconstruct files it never recorded. [1] [5]

retire-reviewed-work.sh
git -C ../app-header status --short --branch
git -C ../app-header status --short --ignored
git -C ../app-header rev-parse HEAD

# After ownership, preservation and integration review:
git worktree remove ../app-header

# Separate optional step, after the retention decision:
git branch -d agent/header-fix

Lock, move, repair and prune are not interchangeable

git worktree lock protects a worktree’s administrative entry from pruning and prevents ordinary move/removal. It is useful for a checkout on storage that is temporarily unavailable. It is not an editing lock: in my locked test checkout, writing a file and creating a new commit both worked. Agent ownership requires a separate coordination mechanism. [1] [5]

Use git worktree move for a supported relocation. If a directory was moved manually, use repair to reconnect the links. Prune removes stale administrative records for missing checkouts, subject to expiry and locks; it does not review or integrate code. Start with its dry run. In the lab I repaired a manually moved checkout rather than editing Git’s private files. [1] [5]

There are repository features that deserve extra care. The upstream worktree manual still warns that submodule support is incomplete and discourages multiple checkouts of a superproject. Worktree-specific configuration and relative-link extensions also have compatibility considerations. This article’s plain-repository lab does not establish that every submodule, sparse-checkout or older-client setup is safe. [1]

worktree-maintenance.sh
# Examples for different maintenance situations:
git worktree lock --reason "Checkout is on a removable drive" ../offline-task
git worktree unlock ../offline-task
git worktree move ../old-task ../new-task
git worktree repair ../manually-moved-task
git worktree prune --dry-run --verbose

Rules I would give an agent

Use an explicit task contract instead of hoping that a temporary directory implies safe behavior. These are recommended rules to adapt to a project, not a change I have made to your repositories. They combine the tested Git boundaries with the operational problem of several writers sharing one machine.

Most importantly, keep integration authority distinct from edit authority. A task can own its branch without owning another agent’s checkout, the shared remote configuration, a production database or the right to rewrite published history. Require a concrete handoff and verify the combined result before retiring the task. [1] [10]

AGENTS-worktree-guidance.md
## Worktree rules

- Before edits, report the absolute checkout path, branch or detached HEAD,
  base commit, current HEAD, and dirty state. Verify the common repository.
- Give each writable task one owner and one branch. Do not override another
  checkout’s branch ownership with --force.
- Work, install dependencies, build and test in the assigned checkout.
- Allocate task-specific ports and test data. Do not assume Git isolates
  databases, credentials, cloud resources or deployment targets.
- Treat stash, repository config, remotes and most refs as shared state.
- Commit only task-owned files. Preserve useful detached commits under a ref.
- Return exact commit IDs, changed paths, test commands/results, service
  details and an integration recommendation. Report unresolved conflicts.
- Do not rewrite shared history, clean unrelated files, or delete another
  task’s checkout. Review needed ignored files before any removal.
- Integrate through the agreed target; test the combined result. Retire only
  owned resources after review. Branch deletion is a separate decision.

The useful mental model

A branch names a line of history. A worktree gives you another place to work on that history. The shared repository makes parallel checkouts convenient; their separate indexes and files keep local edits apart. Your review and integration process is what turns those separate results into one codebase you can trust. [1] [2]

For an agent workflow, the durable unit is a task with an owner, a known base, a real checkout path, a named result and verified integration. The worktree is a very effective part of that unit. It is not the whole unit.

INDEX

References & Works Cited

14 SOURCES
  1. Git project (n.d.). git-stash: save and restore local changes.

    https://git-scm.com/docs/git-stash
    Documentation Accessed: 2026-11-28
  2. OpenAI (n.d.). Codex local environments and setup scripts.

    https://learn.chatgpt.com/docs/environments/local-environment
    Documentation Accessed: 2026-11-28
  3. Cursor (n.d.). Cursor CLI: using worktrees.

    https://cursor.com/docs/cli/using
    Documentation Accessed: 2026-11-28
  4. Git project (n.d.). git-diff: compare changes and merge bases.

    https://git-scm.com/docs/git-diff
    Documentation Accessed: 2026-11-28
  5. Git project (n.d.). git-log: commit ranges and symmetric difference.

    https://git-scm.com/docs/git-log
    Documentation Accessed: 2026-11-28
  6. Git project (n.d.). git-cherry-pick: apply selected changes.

    https://git-scm.com/docs/git-cherry-pick
    Documentation Accessed: 2026-11-28
  7. Git project (n.d.). git-rebase: reapply commits onto another base.

    https://git-scm.com/docs/git-rebase
    Documentation Accessed: 2026-11-28