How to Keep an AI Coding Agent Inside One Feature Branch

A practical setup for containing an AI coding agent to a single feature branch, using git worktree, server-side branch protection, and a pre-commit hook that rejects the wrong branch name.

Steve Jefferson
Steve Jefferson
Developer Advocate
24 August 20261 min read

How to Keep an AI Coding Agent Inside One Feature Branch

Keeping an AI coding agent inside one feature branch is mostly a plumbing problem, not a prompting problem. You isolate its working directory with git worktree so it physically cannot touch other branches, lock down the main branch with server-side protection rules so a push to it fails even if the agent tries, and add a pre-commit or pre-push hook that checks the current branch name before anything lands. None of this requires trusting the agent to behave. It requires making the wrong action impossible, or at least loud and rejected, at the git level.

Give the agent its own worktree, not just a branch

A branch alone does not isolate anything. If the agent runs inside the same checkout you use, a stray git checkout main mid-session moves the working directory out from under it, and any background process ends up committing to whatever branch happens to be checked out at that moment. git worktree add solves this by giving the agent a completely separate directory on disk, backed by the same repository, pinned to one branch. There is no other branch to switch to inside that directory, so it can't happen by accident. This is one of the more useful patterns for using git with AI coding agents in general, and it costs nothing beyond a bit of disk space.

  1. From your main checkout, create the worktree and the branch in one step: git worktree add ../myapp-agent-feature-x -b feature-x

  2. Point the agent's working directory or repo root setting at that new folder (../myapp-agent-feature-x), not at your primary checkout.

  3. Confirm it registered correctly: git worktree list should show the new path sitting next to feature-x.

  4. When the agent's task is done, remove the worktree cleanly instead of deleting the folder by hand: git worktree remove ../myapp-agent-feature-x

  5. If a worktree folder ever does get deleted manually, clean up the stale reference with: git worktree prune

Every worktree shares the same .git history and object database, so there's no duplication of the repository, only of the checked-out files. The agent's commits on feature-x show up in git log across the whole repo immediately, they just live on that branch until someone merges it.

Make the main branch physically unreachable

Worktrees stop accidental branch switching. They don't stop an agent that decides, mid-task, to run git push origin feature-x:main or force-push over history. That's what branch protection is for. On GitHub, GitLab, or Bitbucket, set a protection rule on main, and on any release branches, that does the following:

  • Requires a pull request before merging, with no direct pushes allowed

  • Requires at least one passing status check or review before merge

  • Blocks force pushes and branch deletion on that branch

  • Restricts which users or apps can push directly, if you allow any exceptions at all

If the agent authenticates as a bot account or a scoped token, give that identity push access to feature branches only, never to main. Combine that with the permission model you'd use for a human contributor, covered in more depth in setting permissions for AI coding agents on a team, and a rogue push attempt just gets rejected by the server with a 403, not merged.

Scope the agent itself, not just the repository

Most agentic coding tools, whether that's Claude Code, Cursor, GitHub Copilot's workspace features, or a Codex-style CLI agent, let you set a working directory or repo root in their configuration, and the agent's file operations get scoped to that path. Point that setting at your worktree folder, not your main checkout. Some tools also let you restrict which shell commands the agent can run without asking, which is worth pairing with the protection rule above: even if an agent's permission settings would technically allow git push, the server-side rule on main is the backstop that actually matters. The exact config key or flag varies by tool and changes often enough that it's worth checking the tool's current documentation rather than trusting a fixed name from a blog post. Tools like Swarmz, which build apps through agent-driven workflows, run into the same question of where an agent is allowed to write, and typically expose some form of project or directory scoping to answer it. If you're still deciding which agent to standardize on, picking the right AI coding tool usually comes down to how granular its scoping options are, not just how good its code output is.

A hook that rejects a commit on the wrong branch

Worktrees and branch protection cover most of the risk. A local hook covers the gap in between: an agent committing locally to a branch it shouldn't, before anything even reaches the remote. Pre-commit hooks live in .git/hooks and run before a commit is created; pre-push hooks run before a push leaves the machine. Both can read the current branch name and refuse to proceed if it doesn't match a pattern you define.

Here's a minimal pre-commit hook. Save it as .git/hooks/pre-commit and make it executable with chmod +x .git/hooks/pre-commit:

  • #!/bin/sh

  • protected="^(main|master|release/.*)$"

  • branch=$(git symbolic-ref --short HEAD)

  • if echo "$branch" | grep -Eq "$protected"; then

  • echo "Commits to $branch are blocked here. Create a feature branch."

  • exit 1

  • fi

  • exit 0

For a pre-push version, swap the hook name to pre-push and check the branch being pushed rather than HEAD, since pre-push receives ref information on stdin rather than reading it from the current checkout. The point isn't cleverness, it's that the check runs automatically every time, so it doesn't depend on the agent remembering a rule you wrote in a prompt or in a CLAUDE.md file somewhere.

One caveat: hooks in .git/hooks aren't committed with the repo by default, so a fresh clone or a new worktree won't have them until you copy them over or point at a shared hooks directory. If you want every worktree and every teammate's clone to enforce this automatically, run git config core.hooksPath .githooks and commit the scripts into that versioned folder.

Running two agents on two branches without collisions

Once one agent is safely contained to one worktree, running a second one is the same move repeated: another git worktree add, another branch, another directory. Each agent works in its own files with its own index and its own HEAD, so they can commit at the same time without touching each other's staging area. What they still share is the object database and, eventually, the merge. Two agents refactoring overlapping code on separate branches will still produce a real merge conflict when one of those branches lands on main. Worktrees don't prevent that, they just make sure the conflict shows up as a normal git merge instead of as a corrupted working directory. Plan for it the way you'd plan for handling merge conflicts with AI coding agents, and keep the two branches' scopes as narrow and non-overlapping as you reasonably can before starting both agents. Once a branch is ready, the usual path is a pull request, review, merge to main, and then deploying an app built with AI from that main branch, not from whichever worktree happens to still be open.

Frequently asked questions

Can an AI coding agent commit directly to main by accident?

Only if nothing stops it. Without a worktree, branch protection, or a hook, an agent running in your main checkout can end up committing to whatever branch happens to be checked out, including main, especially in a session where the agent also runs git checkout or git switch on its own. Isolating it in its own worktree and locking main server-side removes the accident, not just the bad intent.

Does git worktree slow anything down or use much disk space?

Not meaningfully. Each worktree is its own working directory and index, but all worktrees share the same object store, so you're not duplicating the repository's full history for every branch. Disk usage grows by roughly the size of one checkout per worktree, not one full clone.

What if the agent needs to touch files outside the repo?

Scope its working directory to the worktree for repo writes, and if it genuinely needs to read or write outside the repo, most tools let you allowlist specific additional paths rather than opening the whole filesystem. Keep that allowlist as small as the task actually requires.

Do I still need code review if the agent can't reach main?

Yes. Branch isolation stops the agent from bypassing your process, it doesn't replace review. A pull request that requires at least one approval before merge, combined with the isolation described above, is what actually keeps bad changes out of main, not just misdirected ones.

Can two agents share the same worktree?

Don't. One worktree checks out one branch, and giving two agents the same directory reintroduces the exact race condition worktrees exist to avoid, with one agent's uncommitted changes sitting in the way of the other's commit. Give each agent its own worktree even when they're collaborating on related work.

How did this land?

About the author

Steve Jefferson
Steve Jefferson

Developer Advocate

Steve builds something with Swarmz every week and writes up what worked, what broke, and what he'd do differently. Tutorials and hands-on guides are his lane.

Share

Get the next post in your inbox

One email a month. Product updates, engineering posts, and the best of Built with Swarmz.

I agree to receive emails about AI building tips and Swarmz product news. Unsubscribe any time.