• AI
  • Git
  • coding agents

Using Git worktrees and sandboxes with coding agents

A beginner-friendly guide: give a coding agent its own Git worktree, limit its commands with a sandbox, then review, keep, or remove its changes safely.

Imagine you share a kitchen with a helper. You are halfway through a recipe, and you ask the helper to bake something else. If you both use the same counter, ingredients get mixed up. You would rather give the helper a second counter. You might also lock the knife drawer if the helper does not need it.

A coding agent is that helper. A coding agent is an AI tool that can read your code, edit files, and run commands such as tests. It is useful, but it raises two practical questions:

  1. How do you keep the agent’s changes apart from the work you have not finished yet?
  2. How do you limit what the agent’s commands can read, change, or connect to?

This article answers both. Git worktree gives the agent its own counter. A sandbox locks the drawers it does not need. The two work well together, but they solve different problems. A worktree is not a security boundary.

The terms you need

  • Repository (repo): a project folder tracked by Git, including its full history.
  • Commit: a saved snapshot of the project.
  • Branch: a named line of commits. You can work on a branch without touching the main one.
  • Checkout / working directory: the files you actually see and edit on disk for one branch.
  • Worktree: an extra working directory attached to the same repository. Each worktree has its own branch, its own files on disk, and its own staging area (the “index”, where git add puts changes).
  • Sandbox: a restricted environment for a running program. It can block file access, network connections, or system features that the program was not given.

Why a worktree, and why it is not enough

Without a worktree, the agent edits the same files you are editing. Your half-finished feature and its bug fix end up in one messy diff (a diff is the list of line changes between two versions). Separating them later is slow and error-prone.

You could clone the repository a second time. A worktree is lighter: it reuses the same Git history and only adds a new folder of files. Linked worktrees share most Git data with the main repository. Git worktree documentation

What a worktree does not do is restrict anything. The agent still runs as your user. It can still read your home directory, use your credentials, or reach the network. A worktree decides where the agent works, not what it is allowed to do. That second part is the sandbox’s job.

Step by step: give the agent its own worktree

The commands below were run in a throwaway repository with Git 2.54.0. Long temporary paths in the outputs are shortened to ~/work. The example project is called shop, and the agent will fix a price-rounding bug: Python’s round(2.675, 2) returns 2.67, because 2.675 cannot be stored exactly as a float.

Step 1: create the worktree

Run this in your main project folder (~/work/shop):

git worktree add -b agent/price-rounding ../agent-price-rounding HEAD

What it does:

  • -b agent/price-rounding creates a new branch with that name.
  • ../agent-price-rounding is the new folder, next to your project.
  • HEAD means “start from the commit I am on now”.

Expected output:

Preparing worktree (new branch 'agent/price-rounding')
HEAD is now at 1157db0 init

Step 2: check that both worktrees exist

Still in ~/work/shop:

git worktree list

Expected output, one line per worktree:

~/work/shop                 1157db0 [main]
~/work/agent-price-rounding 1157db0 [agent/price-rounding]

Your files stay on main. The new folder is on agent/price-rounding.

Step 3: point the agent at the new folder

Open ../agent-price-rounding in your coding agent, or start the agent from inside that folder. Do not start it in ~/work/shop. If you do, it edits your files, and the worktree gives you nothing.

Step 4: look at what the agent changed

When the agent says it is done, go into its folder:

cd ../agent-price-rounding
git status --short

In the test, the agent’s work was simulated by hand: one file was edited and a notes file was left behind:

 M price.py
?? notes.txt

M means a tracked file was modified. ?? means a new file Git does not track yet. Now read the actual changes:

git diff
diff --git a/price.py b/price.py
index eba265f..3e12677 100644
--- a/price.py
+++ b/price.py
@@ -1,2 +1,4 @@
+from decimal import Decimal, ROUND_HALF_UP
+
 def round_price(x):
-    return round(x, 2)
+    return Decimal(str(x)).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)

Lines with + were added; lines with - were removed. With Python 3.13.5, the new version returns 2.68 for 2.675. Note that git diff does not show untracked files such as notes.txt. Check those separately.

Back in ~/work/shop, git status --short printed nothing. Your own checkout was untouched.

Step 5: test, then keep the work

Run the project’s usual tests inside the agent’s worktree. Then decide. If you want to keep the change, commit it on the agent’s branch:

git add price.py
git commit -m "Fix price rounding"

Then merge the branch or open a pull request in the normal way. A worktree only separates the files. It does not check the code and does not merge anything for you.

Limit the agent’s commands with a sandbox

Now for the second question. A sandbox limits the process that runs the agent’s commands. Depending on the tool, it can restrict which files may be read or written, which network hosts may be reached, and which system features may be used. The exact boundary depends on the sandbox technology and its configuration, so read your tool’s documentation before relying on it.

A good habit is to write down what the task really needs. For the rounding fix:

  • Read: source code, the dependency lockfile (the file that pins exact package versions), and test data.
  • Write: only the agent’s worktree and a temporary directory.
  • Network: none during the fix. If tests need packages, install them from the lockfile before the task, or allow only the package registry during installation.
  • Services: if a test needs a database, use a dedicated test instance with credentials that have a limited scope and lifetime.

When a command is blocked, do not just add the permission. First look at what was blocked and why. If a package is missing, installing it while you prepare the environment is often safer than giving the whole session broad network access.

A sandbox works at the process level. If you also want to refuse specific agent actions before they run, such as writes to a protected path, see hooks for coding-agent workflow controls.

GitHub’s local and cloud sandboxes for Copilot, announced in public preview in June 2026, are one example of command restrictions built into a coding-agent tool. Local sandboxing is turned on with /sandbox enable inside a Copilot session. The actual access still depends on the policies for each environment. GitHub Changelog

If the agent runs in a container

A container is a common kind of sandbox: an isolated environment with its own file system. Worktrees need some care here.

A linked worktree does not contain a full .git folder. It has a small .git file that points back to the main repository. In the test it contained one line:

gitdir: ~/work/shop/.git/worktrees/agent-price-rounding

If you copy or mount only the worktree folder into a container, that path may not exist inside it. Git commands such as git diff then cannot find the repository.

Two common fixes:

  1. Mount the worktree together with the Git metadata it needs, and make sure the paths resolve inside the container.
  2. Create a separate clone inside the container. A clone is an independent repository with its own metadata. Bring the branch you need into it using your project’s normal workflow.

Either way, run git status and git diff inside the container before handing the task to the agent.

Paths matter in both directions. The main repository records where each linked worktree lives, and the worktree’s .git file records where the main repository lives. If a worktree directory is moved or mounted at a different path without git worktree move, git worktree list may mark it as prunable, and a later git worktree prune (or automatic cleanup) can delete its administrative files. Run git worktree repair inside the moved worktree, or git worktree repair <new-path> from the main repository, to reconnect them. Git worktree documentation

In the test, a worktree moved with plain mv showed up as prunable. Running git worktree repair with its new path printed repair: gitdir incorrect: … and fixed the link, and git worktree list showed the new location.

Remove the worktree when you are done

After the branch is merged or discarded, return to the main repository and remove the worktree. Run this in ~/work/shop:

git worktree remove ../agent-price-rounding

Git only removes a clean worktree. If the agent left modified or untracked files, the command stops:

fatal: '../agent-price-rounding' contains modified or untracked files, use --force to delete it

Treat that message as a prompt to check git status again, not as an obstacle. git worktree remove --force deletes the directory together with its uncommitted changes and untracked files, and they cannot be recovered from Git because they were never committed. Commit or copy anything you want to keep first.

In the test, after committing the change, the same command succeeded with no output. Removing the worktree does not delete the agent/price-rounding branch or its commits; git branch still listed it.

Delete the branch only after you have merged it or decided to discard its changes.

Common mistakes

  • Starting the agent in the wrong folder. If it runs in your main checkout, its edits mix with yours. Check the agent’s working directory before you give it the task.
  • Treating the worktree as protection. It separates files, not permissions. Without a sandbox, the agent can still read anything your user can.
  • Reading only git diff. It hides untracked files. Use git status --short too.
  • Reaching for --force on removal. It throws away uncommitted work. Look first.
  • Moving the worktree folder by hand. Use git worktree move, or run git worktree repair afterwards, before anything prunes it.
  • Granting broad access after one blocked command. Find out what was missing and grant only that, ideally while preparing the environment.

Conclusion

Give a coding agent its own worktree so its changes stay apart from yours and are easy to review. Then use a sandbox to grant only the access the task needs, because a worktree does not limit anything by itself. Before merging, read git status and git diff, run the tests, and remove the worktree without --force unless you are sure nothing in it is worth keeping.

Written by Duy Pham Independent developer. I build the apps on this site and write about how they work.

More about me