Sub topic 14
Limits of worktrees and when to use containers or clones
This chapter assumes you can run git worktree add, merge branches, and start a command-line agent in a background shell. It covers where worktrees stop protecting you and which isolation method to choose instead.
What a worktree isolates
A linked worktree gives each agent its own working directory, its own index, and its own HEAD. Two agents can edit src/app.py at the same time without overwriting each other, because each one edits a different copy of the file on disk.
Everything else is shared. All worktrees of one repository use the same object database, the same refs, the same config, the same hooks, and the same stash. The operating system also sees one user, one network, and one set of installed tools.
That split determines the limits. Anything stored in the working directory is isolated. Anything stored in .git, on the machine, or in a remote service is shared.
Limits of the worktree model
Shared Git state
Because refs are shared, a branch created or deleted in one worktree is immediately visible in all of them. This causes several problems.
- Branch rules. A branch can be checked out in only one worktree. An agent that runs
git switch mainin its worktree fails ifmainis checked out elsewhere. Some agents retry with--forceor try to work around the error, so tell them to stay on their assigned branch. - Destructive ref operations. An agent that runs
git branch -D agent/searchorgit push --forceaffects every other worktree and the remote. A worktree does not limit what Git commands can touch. - Stash.
git stashis stored in a single ref shared by all worktrees. One agent can pop another agent's stash by accident. - Config and hooks. Settings in
.git/configand scripts in.git/hooksapply to every worktree. A hook that runs a slow test suite on each commit will run once per agent, concurrently. - Garbage collection. Running
git gcwhile another worktree is mid-operation is usually safe, but it adds disk load. Do not run aggressive pruning while agents are working.
A quick way to see this shared state is to inspect a linked worktree's .git entry.
cat ../myrepo-auth/.git
git rev-parse --git-common-dir
git rev-parse --git-dirIn a linked worktree, .git is a file that points to a per-worktree directory under the main repository's .git/worktrees/. --git-common-dir shows the shared part, and --git-dir shows the private part (the index and HEAD).
Machine resources
Worktrees do not separate processes. Three agents each running a test suite, a build, and a language server compete for the same CPU cores, memory, and disk bandwidth. On a laptop, running more than three or four agents often slows each one down enough that total throughput stops improving.
Disk use is smaller than a full clone, since objects are shared, but each worktree still holds a full copy of the checked-out files plus anything generated there. A node_modules directory or a build cache of several gigabytes is duplicated per worktree.
Ports, databases and services
Each worktree can run its own dev server, but two servers cannot bind the same port. The same applies to any local database, message queue, or Docker Compose stack that uses fixed names and ports. If every worktree points at localhost:5432 and the same database name, agents run migrations against each other's data.
The usual fixes are per-worktree environment variables: a different PORT, a different database name such as app_auth and app_search, and a different cache directory. These work for simple setups. They get fragile when the project hardcodes ports in several config files.
Global caches and credentials
Tools like npm, pip, Cargo, and Gradle keep caches in your home directory. Concurrent installs usually coordinate through lock files, but not always, and a corrupted cache affects every worktree. Credentials are also shared: every agent runs as you, with your SSH keys, cloud profile, and tokens.
That last point is a security limit. A worktree is not a sandbox. An agent in ../myrepo-auth can still read ~/.ssh, edit files in ../myrepo-search, or run rm -rf on the main checkout, because the file system permissions are the same.
Task-level limits
Worktrees prevent file-level overwrites, but they do not prevent logical conflicts. Two agents can change the same function in different worktrees. Both edits are valid, and the merge then fails or, worse, succeeds with code that is broken. Careful task splitting reduces this, but cannot remove it. Review and integration remain your job, as covered in earlier chapters.
Alternatives
Containers
A container runs the agent inside an isolated file system, process space, and network namespace. You mount one worktree into each container, so you keep the Git benefits and add isolation.
docker run --rm -d \
--name agent-auth \
-v "$PWD/../myrepo-auth:/workspace" \
-w /workspace \
--memory 4g --cpus 2 \
my-agent-image \
your-agent-command "Work on the auth task described in TASKS.md"This gives you several things worktrees cannot:
- A limit on CPU and memory per agent.
- Separate network namespaces, so each container can use port 3000 internally and you map different host ports.
- No access to your home directory, SSH keys, or other worktrees unless you mount them.
- A reproducible toolchain, since every agent runs the same image.
There is a catch. A linked worktree's .git file points to the main repository's .git/worktrees/ directory by absolute path. If you mount only the worktree, Git inside the container cannot find that directory and fails with "not a git repository". You have two options: mount the main repository's .git directory at the same absolute path, or use a clone (below). Mounting .git read-write lets the agent modify shared refs again, which weakens the isolation you wanted.
Containers also add cost: image builds, slower file I/O on some platforms (notably macOS bind mounts), and extra setup for each project.
Separate clones
git clone (or git clone --local) creates a repository with its own .git directory. The agent cannot affect refs, stash, config, or hooks in any other copy.
git clone --local ../myrepo ../myrepo-clone-auth
cd ../myrepo-clone-auth
git switch -c agent/authClones remove the shared Git state and the same-branch restriction. Two clones can both have main checked out. The agent works against its clone, and you fetch its branch back when done.
git fetch ../myrepo-clone-auth agent/auth:agent/authThe cost is disk space, since local clones may hardlink objects but a remote clone copies them. Branches also do not appear in your main repository until you fetch them.
Virtual machines and remote machines
For untrusted agents, large test suites, or heavy databases, use a virtual machine or a remote development host. Each agent gets its own kernel, disk, and network. This is the strongest isolation and the highest cost in setup time and money.
Choosing a method
| Concern | Worktree | Worktree plus container | Clone | VM or remote host |
|---|---|---|---|---|
| Overwritten files | Isolated | Isolated | Isolated | Isolated |
| Shared refs and stash | Shared | Shared if `.git` is mounted | Isolated | Isolated |
| Ports and services | Manual fixes | Isolated | Manual fixes | Isolated |
| CPU and memory limits | None | Yes | None | Yes |
| Access to your credentials | Full | Controlled | Full | Controlled |
| Setup cost | Low | Medium | Low | High |
| Disk cost | Moderate | Moderate | Higher | Highest |
Use these criteria to decide:
- Trusted agent, independent tasks, no services: use worktrees. This is the cheapest option and covers most cases.
- Tasks that need their own ports or database: use worktrees with per-worktree environment variables first. Move to containers if the project resists that.
- Agent that runs arbitrary commands or you do not fully trust: use containers or a VM, regardless of Git setup.
- Agents that need to run Git commands freely, such as rebasing or switching branches: use clones, so they cannot disturb shared refs.
- Resource-heavy workloads: use containers with limits, or remote machines.
You can combine methods. A common setup is one clone per agent, each run inside a container. This removes shared Git state and limits the blast radius, at the cost of more disk and setup.
Common errors
- "fatal: 'main' is already checked out at ..." The branch is in use in another worktree. Create a new branch with
-bor use--detach. - "not a git repository" inside a container. The
.gitfile points to a path that does not exist in the container. Mount the common.gitdirectory at the same path, or use a clone. - Port already in use. Two worktrees started the same dev server. Set a unique
PORTfor each. - Migrations affect the wrong data. Worktrees share one local database. Give each its own database name.
- A branch vanished. An agent deleted it from a different worktree. Recover it with
git reflog, and restrict what the agent is told to do with branches.
Exercise
You run three agents in three worktrees. One agent needs to run git rebase onto a fast-moving main, and another runs a database migration against a local PostgreSQL instance. Which isolation changes would you make, and why?
Show answer
Give the rebasing agent a separate clone, since rebasing and switching branches act on refs that all worktrees share, and main can only be checked out in one worktree. For the migration agent, give its worktree a unique database name (or run it in a container with its own database) so the migration does not change data the other agents use. The third agent can stay in a plain worktree if it has no shared services and you trust it.
Exercise
Why does mounting only a linked worktree directory into a container usually break Git inside the container, and what is a trade-off of the main fix?
Show answer
The worktree's .git is a file containing an absolute path to a directory under the main repository's .git/worktrees/. That path does not exist in the container, so Git cannot find the repository. Mounting the main .git directory at the same path fixes it, but then the agent can modify shared refs, stash, and config, which weakens isolation. A clone avoids this.