Makuhari Development Corporation
9 min read, 1679 words, last updated: 2026/2/5
TwitterLinkedInFacebookEmail

Introduction

Modern AI-assisted development often involves running multiple agents simultaneously — one refactoring the backend, another designing a new API, a third fixing a bug. The traditional git branching model, designed for sequential human workflows, breaks down the moment two agents try to occupy the same working directory at the same time.

This tutorial explains how git worktree solves that problem by giving each agent its own physical workspace while sharing a single .git history. You will also learn when plain branches are perfectly sufficient, how git subtree fits into the picture (and why it is unrelated to agent parallelism), and how to safely merge work from multiple agents back into a main branch.

By the end, you will have a reusable mental model and a set of concrete commands you can drop into your own projects.


Prerequisites

  • Git 2.5 or later (worktree support)
  • A working repository you can experiment on
  • Basic familiarity with branching (git checkout -b, git merge)
  • Optional: Claude Code or any other AI coding agent

Step-by-step Guide

Step 1 — Understand Why Branches Alone Are Not Enough for Parallel Agents

A git branch is a logical concept: it moves the HEAD pointer to a different commit, but there is still only one working directory on disk.

git checkout branch-a
# Agent A starts working…
 
git checkout branch-b
# Agent B starts working… but Agent A's world just disappeared.

For human developers this is fine — they pause, switch context, come back later. AI agents cannot do this. An agent treats the filesystem as a stable environment. Switching branches underneath a running agent is equivalent to resetting its world mid-task, corrupting its context.

Additionally, long-running side effects — npm install, a running dev server, a build cache — are tied to the working directory. Every branch switch destroys them.

When branches are sufficient:

Situation Verdict
Frontend and backend changes that do not overlap Branch is fine
Single agent working with you Branch is fine
No persistent build state or dev server Branch is fine
Multiple agents truly running at the same time Need worktree
Agent must not be interrupted mid-task Need worktree

The decision rule is simple: "Does this require real-time parallelism?" If yes, use worktree. If no, a branch is the simpler and correct choice.


Step 2 — Create a Worktree for Each Agent

A git worktree creates a new physical directory linked to the same .git database, but checked out to its own branch. Multiple worktrees can coexist simultaneously.

# From inside your main repository directory
git worktree add ../project-agent-a agent/feature-auth
git worktree add ../project-agent-b agent/refactor-storage
git worktree add ../project-agent-c agent/fix-pagination

Result on disk:

project-main/       ← your regular directory (main branch)
project-agent-a/    ← agent A's workspace (agent/feature-auth)
project-agent-b/    ← agent B's workspace (agent/refactor-storage)
project-agent-c/    ← agent C's workspace (agent/fix-pagination)

All three share one .git. Each has its own files, its own uncommitted changes, its own node_modules, its own build cache.

Branch naming convention — use semantic prefixes:

agent/arch-api-spec
agent/impl-auth-module
agent/refactor-database-layer
agent/fix-search-edge-case

This makes the git log readable at a glance after parallel work completes.


Step 3 — Assign Clear Responsibilities to Each Agent

The key to conflict-free merging is not clever tooling — it is clear ownership boundaries before work starts.

Agent Role Branch Prefix Allowed to Modify
Spec / Architecture agent/arch-* Interfaces, README, design docs
Implementation agent/impl-* Source files, tests
Refactoring agent/refactor-* Internal structure only, no API changes
Bug Fix agent/fix-* Minimal diff, targeted change

When agents stay within their lane, merges become nearly mechanical.


Step 4 — Run Agents and Commit Their Work

Each agent works exclusively in its own worktree directory. Commit discipline matters here — annotated commit messages help you understand who did what when reviewing.

# Inside project-agent-a/
git add src/auth/
git commit -m "agent(impl): add JWT refresh token support"
 
# Inside project-agent-b/
git add src/storage/
git commit -m "agent(refactor): extract storage adapter interface"
 
# Inside project-agent-c/
git add src/search/
git commit -m "agent(fix): handle empty query string in search handler"

After commits, you can inspect the full picture from the main repository:

cd project-main
git log --oneline --graph --all

Step 5 — Merge Agent Branches Safely

Never merge everything at once. Merge sequentially, in order of dependency.

Recommended merge order:

spec/architecture → implementation → refactoring → bug fixes
cd project-main
 
# Verify graph before merging
git log --oneline --graph --all
 
# Merge one at a time
git merge agent/arch-api-spec
git merge agent/impl-auth-module
git merge agent/refactor-database-layer
git merge agent/fix-search-edge-case

If a conflict arises:

  • Resolve it on main, not inside the agent branch.
  • The spec/architecture branch wins disputes about interfaces — implementation adapts to spec, not the other way around.
# After a conflicting merge
git status
# Edit conflicting files manually
git add .
git commit

Step 6 — Optional: Pre-check Conflicts with Rebase

Before merging an agent branch into main, you can do a dry-run rebase to surface conflicts early:

cd project-agent-b
git rebase main
  • Clean rebase: merge will be trivial.
  • Rebase conflict: the agent's scope overlapped with something it shouldn't have. Investigate why before proceeding.

Do not force the rebase if it explodes. That is a signal to review the agent's work scope, not to resolve conflicts blindly.


Step 7 — Clean Up After Merging

Once all agent branches are merged and verified:

# Remove the worktree directories
git worktree remove ../project-agent-a
git worktree remove ../project-agent-b
git worktree remove ../project-agent-c
 
# Delete the merged branches
git branch -d agent/arch-api-spec
git branch -d agent/impl-auth-module
git branch -d agent/refactor-database-layer
git branch -d agent/fix-search-edge-case

This keeps the repository clean and prevents stale worktrees from accumulating.


Code Examples

Minimal Shell Script to Spawn an Agent Worktree

#!/usr/bin/env bash
# spawn-agent-worktree.sh
# Usage: ./spawn-agent-worktree.sh impl-auth
 
ROLE="${1:-agent-task}"
BRANCH="agent/${ROLE}"
WORKDIR="../project-${ROLE}"
 
git worktree add "$WORKDIR" -b "$BRANCH"
echo "Worktree created: $WORKDIR (branch: $BRANCH)"
echo "Run your agent inside: $WORKDIR"

Merge All Agent Branches in Order

#!/usr/bin/env bash
# merge-agents.sh
# Merges agent branches in dependency order with early exit on conflict
 
set -e
 
BRANCHES=(
  "agent/arch-api-spec"
  "agent/impl-auth-module"
  "agent/refactor-database-layer"
  "agent/fix-search-edge-case"
)
 
for branch in "${BRANCHES[@]}"; do
  echo "Merging $branch..."
  git merge "$branch" --no-edit
  echo "Done: $branch"
done
 
echo "All agent branches merged successfully."

Check All Worktrees

git worktree list

Output:

/path/to/project-main       abc1234 [main]
/path/to/project-agent-a    def5678 [agent/impl-auth-module]
/path/to/project-agent-b    ghi9012 [agent/refactor-database-layer]

A Note on git subtree (and Why It Is Unrelated)

A common source of confusion: git subtree sounds similar to git worktree but solves a completely different problem.

Mechanism Shared .git History Separate Working Directory Use Case
branch Yes No Sequential development
worktree Yes Yes Parallel development
subtree No (copied) Subdirectory Embedding external code

git subtree is for embedding the contents of another repository into a subdirectory of your project. The two commit histories are independent — changes you make inside the subtree directory only exist in your repo unless you explicitly push them back with git subtree push.

# Adding an external library as a subtree
git subtree add --prefix=vendor/some-lib https://github.com/example/some-lib.git main --squash
 
# Pushing local changes back upstream
git subtree push --prefix=vendor/some-lib https://github.com/example/some-lib.git main

This is useful for vendoring stable libraries or shared internal tools. It is not a mechanism for parallel agent work, and using it that way results in reconciling divergent histories — a much harder problem than a simple merge conflict.

Three-line summary:

  • branch: switch perspective
  • worktree: switch physical workspace
  • subtree: transplant code, disconnect lineage

Practical Tips

Tip 1 — Keep agent scope small. The smaller each agent's domain, the fewer conflicts you will see at merge time. If an agent needs to touch shared configuration files (.env, database schema, shared types), isolate that work into its own dedicated agent branch.

Tip 2 — Shared state files are hidden landmines. Files like package-lock.json, schema.prisma, or a shared types.ts are frequently modified by multiple agents without either realizing it. Identify these before you assign work and assign ownership of each to exactly one agent.

Tip 3 — Do not resolve conflicts inside agent branches. This pollutes the agent's history and makes review harder. Always resolve on main.

Tip 4 — Worktrees are cheap. Creating a worktree takes under a second and uses almost no extra disk space (it hard-links most of the .git internals). Use them liberally.

Tip 5 — When in doubt, use a branch. If you are not sure whether you need a worktree, you probably do not. Start with branches, and reach for worktrees when you feel the friction of needing two live workspaces simultaneously.


Summary

The core insight from this tutorial:

Branches solve version divergence. Worktrees solve time parallelism. AI agents require time parallelism.

Here is the full workflow at a glance:

  1. Create a dedicated worktree for each agent with a semantic branch name.
  2. Define clear scope boundaries before work begins — agents that stay in their lane produce conflict-free merges.
  3. Commit with annotated prefixes (agent(impl):, agent(fix):) for legible history.
  4. Merge sequentially: spec → impl → refactor → fix.
  5. Resolve any conflicts on main, with the spec/architecture branch taking precedence on interface disputes.
  6. Run git worktree remove and git branch -d after successful merges to keep the repository clean.

For day-to-day work that does not require simultaneous agent activity — separate frontend and backend changes, small independent tasks — plain branches remain the right tool. Worktrees are the upgrade path when you need real physical isolation for genuinely concurrent workflows.

Makuhari Development Corporation
法人番号: 6040001134259
ご利用にあたって
個人情報保護方針
個人情報取扱に関する同意事項
お問い合わせ
Copyright© Makuhari Development Corporation. All Rights Reserved.