AI 開発に役立つ Git Worktrees の活用
KDnuggets は、AI 開発における複雑なブランチ管理の課題を解決するため、Git Worktrees を活用した並行開発手法の有効性を紹介している。
キーポイント
複数環境の並行管理
異なるバージョンの依存関係やモデルを実験する際、従来のブランチ切り替えではなくワークツリーを使用することで、複数の Git リポジトリを同じディレクトリ構造で同時に操作できる。
開発効率の向上
ブランチ間のコンテキスト切り替えによるオーバーヘッドを排除し、AI 開発特有の試行錯誤プロセスをスムーズに行うことができるようになる。
リソース最適化
同じワークスペース内で異なる実験環境を維持できるため、ディスク容量や設定ファイルの重複管理による混乱を防ぎ、作業領域を整理できる。
重要な引用
Git Worktrees allows you to work on multiple branches simultaneously without the need for switching back and forth.
It is particularly useful for AI development where different experiments require different dependencies or model versions.
影響分析・編集コメントを表示
影響分析
この手法は、AI 開発者が頻繁に行うモデル比較や依存関係の切り替え作業において、時間的・機能的なボトルネックを解消する実用的な解決策を提供します。特に大規模な実験や複数バージョンの並行検証が必要な現場では、開発フローの安定性と生産性を高める重要なツールとして定着する可能性があります。
編集コメント
AI 開発のスピードが加速する中、ツール自体の使いこなしがイノベーション速度を左右します。Git Worktrees のような標準的なバージョン管理機能を活用したベストプラクティスの普及は、チーム全体の開発品質向上に直結する重要な一歩です。

イントロダクション
Claude Code を機能ブランチ上で実行中だとしましょう。AI エージェントは 20 分間作業を続け、コードベースを読み込み、文脈を構築し、認証システムの書き換えで着実に成果を出しています。その時、Slack にメッセージが届きます。「本番環境がダウンしている。メインブランチへのホットフィックスが必要だ。今すぐ対応してほしい」と。
従来のワークフローでは、変更内容を一時保存(stash)してブランチを切り替え、AI エージェントが蓄積した文脈や進捗をすべて失います。バグを修正し、プッシュして元のブランチに戻り、再び AI エージェントに作業の文脈を理解させるのに 10 分ほど費やすことになります。
もし同じディレクトリで 2 つのエージェントを同時に実行していた場合、状況はさらに悪化します。両方のエージェントが package.json にアクセスし、同じファイルへの編集を試みます。後から書き込まれた変更は、前のエージェントの作業を静かに上書きしてしまいます。警告もエラーも出ません。1 時間後に意味不明なテスト失敗が発生した時に初めて、作業が破損していたことに気づくのです。
Git worktrees は、こうした問題群をすべて解決します。これは新しい発明ではなく、2015 年にリリースされた Git バージョン 2.5 から実装されている機能です。しかし、2025〜2026 年の AI コーディングブームによって、これが不可欠なインフラストラクチャへと進化しました。
1 つの .git ディレクトリの中に複数の作業ディレクトリを持ち、それぞれが独立したブランチ上に存在します。互いに干渉せず、それぞれの AI エージェントには隔離されたワークスペースが用意され、ホットフィックス用にも専用のワークスペースを確保できます。衝突は起きません。
プロフェッショナル開発者の 51% が毎日 AI ツールを利用していますが、AI エージェントを使用している開発者のうち、そのツールがチームコラボレーションの向上に寄与したと答えたのはわずか 17% です。この数字の差はツールの問題ではありません。インフラストラクチャの問題です。チームは AI エージェントを導入しましたが、その下支えとなるワークフロー層が欠けていました。このガイドこそが、そのワークフロー層となります。
この記事を読み終える頃には、worktrees の仕組みや設定方法、カオスを招かずに並列で AI エージェントを実行する方法、そしてプロジェクトのライフサイクルを通じてどのように維持管理するかを理解しているはずです。
Git worktrees は実際には何なのか
標準的な Git リポジトリには作業ディレクトリが 1 つしかありません。これはファイルが存在し、コードを編集するフォルダのことです。別のブランチで作業するには、そのブランチに切り替える必要があります。そうすると、そのディレクトリ内のすべてのファイルがブランチの内容に合わせて書き換わってしまいます。未コミットの作業がある場合は、まずそれをスタッシュ(一時保存)する必要があります。AI エージェントが処理の最中なら、作業を中断させなければなりません。
Git のワークツリー機能はこの制約を打破します。ワークツリーとは、同じリポジトリからチェックアウトされた別ディレクトリのことを指します。必要な数だけ作成でき、それぞれが独立したブランチ上で動作し、ファイルシステム上では同時に共存できます。
my-project/ ← メインワークツリー (ブランチ: main)
my-project-feat-auth/ ← リンク済みワークツリー (ブランチ: feat/auth)
my-project-feat-api/ ← リンク済みワークツリー (ブランチ: feat/api)
my-project-hotfix-login/ ← リンク済みワークツリー (ブランチ: hotfix/login)
これら 4 つのディレクトリは、すべて同じ .git フォルダを共有しています。履歴やオブジェクト、コミット情報も共通です。ただし、それぞれが独立したチェックアウトされたファイル、インデックス、作業状態を持っています。my-project-feat-auth/ でファイルを編集するエージェントが、my-project-feat-api/ の内容を確認したり変更したりすることはできません。これらは物理的に分離したディレクトリであり、Git というバックエンドを共有しているだけです。

なぜ複数のクローンよりも優れているのか?
ワークツリーを使わない場合の素朴な代替案は、リポジトリを 2 つコピーしてそれぞれ異なるディレクトリで作業することです。これは機能しますが、いくつかの明確なコストが発生します。
ディスク上にリポジトリ全体が重複して保存され、各クローン間で Git の履歴が共有されないため、あるクローンで行ったコミットは即座に他のクローンには反映されません。また、Git レベルでの連携もできません。
一方、ワークツリーを使えば 1 回だけクローンをすれば十分です。追加でワークツリーを作成しても、コストとして増えるのはチェックアウトされたファイルのみであり、履歴の完全なコピーが新たに作成されるわけではありません。
ワークツリーの管理に必要な基本コマンドは以下の 7 つだけです。
コマンド
機能
git worktree add <path> -b <branch>
新しいブランチ上に新規ワークツリーを作成します。
git worktree add <path> <existing-branch>
既存のブランチを新しいワークツリーにチェックアウトします。
git worktree list
アクティブなすべてのワークツリー、対応するブランチ、コミットハッシュを表示します。
git worktree lock <path>
ワークツリーの削除(プリューン)を防ぎます。エージェントが実行中の場合に特に有用です。
git worktree unlock <path>
ロックを解除します。
git worktree remove <path>
ワークツリーをクリーンに削除します(ブランチ自体は保持されます)。
git worktree prune
手動で削除されたワークツリーのメタデータを整理・清掃します。
これが全機能です。この記事の残りの部分は、これら 7 つのコマンドを組み合わせたワークフローの説明に過ぎません。
# 環境構築
前提条件: Git 2.5 以上が必要です。git --version コマンドで確認してください。macOS、Linux、Windows(WSL または Git Bash を使用)など、現代のシステムであればほぼ例外なく 2.5 よりも新しいバージョンが標準搭載されています。
// ステップ 1:クリーンなリポジトリから始める
ワークツリーを最大限に活用するには、メインブランチがクリーンであることが理想です。最初のワークツリーを作成する前に、進行中の作業は必ずコミットするか、スタッシュしておきましょう。
クリーンな作業状態か確認する
git status
未コミットの作業がある場合はコミットする
git add . && git commit -m "checkpoint: work in progress"
// ステップ 2:最初のワークツリーを作成する
../myapp-feat-auth に新しいブランチ feat/auth を持つワークツリーを作成
「myapp」はプロジェクト名に、「feat/auth」はブランチ名に置き換えてください
git worktree add -b feat/auth ../myapp-feat-auth main
作成を確認する
git worktree list
以下のような出力が表示されるはずです。
/home/user/myapp abc1234 [main]
/home/user/myapp-feat-auth abc1234 [feat/auth]
両方のディレクトリが存在し、メインブランチからのファイルが同じ内容で含まれています。ここから先、myapp-feat-auth/ で行った変更はすべて feat/auth ブランチ上に残り、メインブランチとは完全に隔離されます。
// ステップ 3:新しいワークツリー内で環境を設定する
これは多くのチュートリアルで見落とされがちなステップです。ワークツリーは新しい作業ディレクトリですが、自動的に .env ファイルやインストール済みの node_modules、Python の仮想環境を持ってくるわけではありません。これらは明示的に設定する必要があります。
cd ../myapp-feat-auth
gitignore されている環境ファイルをコピーする
.env や .env.local は Git で管理されていないため、新しいワークツリーには自動的に現れません
cp ../myapp/.env .env
cp ../myapp/.env.local .env.local 2>/dev/null || true
Node.js プロジェクト:依存関係のインストール
各ワークツリーは独立した作業ディレクトリです。
親ディレクトリの node_modules は継承されません
npm install
Python プロジェクト:仮想環境の作成とアクティベーション
python -m venv .venv && source .venv/bin/activate && pip install -r requirements.txt
// ステップ 4: ワークツリーの独立性を確認する
新しいワークツリー内から実行
git branch
以下のように表示されるはずです:* feat/auth
テスト用の変更を加える
echo "// test" >> test-isolation.js
git status
このワークツリー内でのみ変更が表示されます
メインディレクトリに移動し、影響がないか確認する
cd ../myapp
git status
変更なし。先ほどの test-isolation.js の変更はここには表示されません
ls test-isolation.js 2>/dev/null || echo "存在しません -- 隔離が確認できました"
これで準備は完了です。ワークツリーはすぐに使用可能です。このディレクトリで起動したエージェントは、feat/auth ブランチに対してのみ動作します。
# 実務でのケーススタディ
AI を活用した並列開発に Git ワークツリーを活用した事例として、最も明確に文書化されているのは Microsoft Global Hackathon 2025 の取り組みです。
AI エージェントの開発に取り組むエンジニアなら、誰もが必ず直面する問題があります。それは機能の多さと開発時間の不足、そして一度に複数の作業を進めるための手段がないというジレンマです。リポジトリを複数複製するのは手間がかかりすぎますし、ブランチを切り替えると AI エージェントのコンテキストが失われてしまいます。何かを変える必要がありました。
その解決策として採用されたのが、git worktrees を活用した手法です。Tamir Dresher 氏はこれを「仮想の AI 開発チーム」と表現しました。各機能ごとに独立したワークツリーを用意し、それぞれのワークツリーに VS Code のウィンドウを割り当てます。そして、各ウィンドウで個別の AI エージェントを実行させるのです。
Dresher 氏の役割は開発者から技術リーダーへと変化しました。タスクのスコープ設定、出力レビュー、行き詰まったエージェントへの指導、完了した機能のマージなどです。
具体的なセットアップ例は以下の通りです:
myapp/ ← メインウィンドウ:調整とレビュー
myapp-feat-authentication/ ← エージェント 1: OAuth2 フローの実装
myapp-feat-api-endpoints/ ← エージェント 2: REST エンドポイントの構築
myapp-bugfix-login-crash/ ← エージェント 3: 本番環境の不具合修正
各 VS Code ウィンドウは完全に独立しています。言語サーバー、リンター、テストランナーもウィンドウごとに別々に動作します。エージェント同士が互いのファイルに干渉することはありません。
エージェント 1 が完了すると、Dresher 氏は差分を確認し承認した上で、そのブランチからプルリクエスト(PR)を作成します。これは人間エンジニアからの PR をレビューする際と同じワークフローです。
ハッカソンで Dresher 氏が記録した具体的なメリットは以下の 3 つです:
文脈の喪失はありません。各 AI エージェントは、自身の特定のタスクに関する完全なコンテキストを維持し続けました。機能切り替えの際には、ブランチやスタッシュの操作、あるいはエージェントの再起動を行う必要はなく、単に VS Code のウィンドウを切り替えるだけで済みます。そのため、構築中のものに対するエージェントの理解は常に保たれました。
異なるツールを異なる用途で使い分けることが可能です。各ウィンドウが独立しているため、Dresher 氏は高速な機能開発には Roo を、複雑な問題のデバッグには Visual Studio と GitHub Copilot をそれぞれ別のウィンドウで実行しました。タスク間でツールを組み合わせることも容易です。
ブランチ管理もクリーンに保てます。ある機能を放棄する必要がある場合、ウィンドウを閉じてワークツリーを削除するだけで 10 秒で完了します。他のエージェントへの影響はありません。

今回のハッカソンで見られたこのパターンは、現在 AI コーディングコミュニティ全体で文書化されたベストプラクティスとして定着しています。
# ワークツリーを用いた並列 AI エージェントの実行
並列ワークフローをフル稼働させる仕組みには、4 つの段階があります。まずワークツリーのセットアップを行い、各エージェントにコンテキストを与え、実行を開始し、定期的にチェックポイントを残すという流れです。
// ステージ 1: ワークツリー作成のスクリプト化
毎回手動でワークツリーを作成するのはやめましょう。スクリプトを使えば、環境ファイルの準備、依存関係のインストール、クリーンなスタート地点の確保など、すべてのワークツリーに同じセットアップを確実に適用できます。
前提条件:Git 2.5 以上、Bash(macOS/Linux/WSL)
必ず JSON 形式で返してください。translation フィールドのみ。他のフィールドは一切追加しないこと — 余計なフィールドを書こうとして本文がトークン上限で打ち切られる事故を防ぐため:
{"translation": "リライト全文"}
実行方法:
プロジェクトのルートディレクトリに create-worktree.sh という名前で保存し、chmod +x create-worktree.sh で実行権限を付与した上で、./create-worktree.sh feat/auth-redesign main とコマンドを実行してください。
#!/usr/bin/env bash
create-worktree.sh
AI エージェントのタスクごとに隔離されたワークツリーを作成します
使い方:./create-worktree.sh [ブランチ名] [ベースブランチ]
例:./create-worktree.sh feat/auth-redesign main
set -euo pipefail
BRANCH="${1:?Usage: $0 [ブランチ名] [ベースブランチ]}"
BASE="${2:-main}"
REPO_ROOT="$(git rev-parse --show-toplevel)"
REPO_NAME="$(basename "$REPO_ROOT")"
ブランチ名のスラッシュをディレクトリ名用にダッシュに置換します
例:feat/auth-redesign → feat-auth-redesign
WORKTREE_PATH="${REPO_ROOT}/../${REPO_NAME}-${BRANCH//\/-}"
echo "ブランチ $BRANCH のワークツリーを作成中..."
echo "ベースブランチ:$BASE"
echo "ワークツリーパス:$WORKTREE_PATH"
新しいブランチが現在のリモート状態から始まるよう、最新情報を取得します
git fetch origin 2>/dev/null || echo "(リモートなし -- スキップ)"
ベースブランチから新しいブランチを作成してワークツリーを追加します
-b オプションで失敗した場合、既存のブランチをチェックアウトするようフォールバックします
git worktree add -b "$BRANCH" "$WORKTREE_PATH" "$BASE" 2>/dev/null || \
git worktree add "$WORKTREE_PATH" "$BRANCH"
Git で追跡されていない環境設定ファイルをワークツリーへコピーします
これらは .gitignore に含まれているため、自動的に引き継がれません
for f in .env .env.local .env.development .env.test; do
if [ -f "$REPO_ROOT/$f" ]; then
cp "$REPO_ROOT/$f" "$WORKTREE_PATH/$f"
echo "$f をコピーしました"
fi
done
Node.js: 新しい作業ディレクトリで依存関係をインストール
if [ -f "$WORKTREE_PATH/package.json" ]; then
echo "Installing Node dependencies..."
(cd "$WORKTREE_PATH" && npm install --silent 2>/dev/null || \
echo "(npm install skipped -- run it manually in the worktree)")
fi
Python: 開発者に環境構築を促すメッセージを表示
if [ -f "$WORKTREE_PATH/requirements.txt" ] || [ -f "$WORKTREE_PATH/pyproject.toml" ]; then
echo "Python project detected."
echo "Run in the new worktree:"
echo " python -m venv .venv && source .venv/bin/activate && pip install -r requirements.txt"
fi
echo ""
echo "Worktree ready. Open it in your IDE and start your agent:"
echo " cd $WORKTREE_PATH"
このスクリプトが行うのは、作業用ブランチ(worktree)の作成と、Git で無視されている環境設定ファイルの転送です。これらはセットアップで最も頻繁に失敗する箇所ですが、本スクリプトがカバーします。また、${BRANCH//\//-} という置換処理により、feat/auth といったブランチ名を feat-auth のようにファイルシステムで扱いやすい形式に変換しています。23 行目のフォールバック処理は、リモート側ですでに同名のブランチが存在する場合に対応するためのものです。
// ステージ 2: AGENTS.md コンテキストファイルの設定
エージェントの出力品質を向上させるために、最も重要かつ効果的な施策は、各エージェントに明確な「文書化されたコンテキストファイル」を与えることです。ICSE 2026 で査読付き発表された研究では、アーキテクチャドキュメントをエージェントのコンテキストに組み込むことで、機能的正規性、アーキテクチャへの適合性、コードのモジュール性が明確に向上することが実証されています。
このコンテキストを信頼性高く、大規模かつ全セッションで提供するための手段が「AGENTS.md」ファイルです。プロジェクトルートにこのファイルを配置し、リポジトリにコミットしてください。各エージェントはセッション開始時に必ずこのファイルを読み込みます。ツールによって読み込むファイル名は異なります(OpenAI Codex なら AGENTS.md、Claude Code なら CLAUDE.md、汎用ツールなら AGENTS.md など)が、重要なのはファイル名ではなく中身です。
AGENTS.md
Project context for AI coding agents
Commit this to your repository root.
Every agent that opens this project reads it first.
Project Overview
Node.js/TypeScript REST API with a React frontend.
Stack: Node 20, Express 5, Prisma ORM, PostgreSQL, React 18, Vite.
Build and Test Commands
npm run dev # start dev server on port 3000
npm run build # production build to dist/
npm run test # run all tests (Vitest)
npm run test:watch # watch mode
npm run lint # ESLint and Prettier check
npm run db:migrate # run pending Prisma migrations
npm run db:seed # seed development data
アーキテクチャ
- API ルート:
src/routes/にリソースごとに 1 ファイルずつ配置 - ビジネスロジック:
src/services/に記述。ルートハンドラ内には書かないこと - データベースアクセス:
src/repositories/を利用。サービス層から直接 Prisma を呼び出さないこと - 共通型定義:
src/types/index.ts
コーディング規約
- 公開するすべての関数には JSDoc コメントを必須とする
- コミット済みのコードに
console.logは使用しない。代わりにsrc/utils/logger.tsを利用すること - エラーハンドリングは、サービス層で型付きエラーをスローし、ルートハンドラ側でキャッチする
- ブランチ名の命名規則:
feat/,fix/,refactor/
変更禁止ゾーン(明示的な指示がない限り絶対に変更不可)
src/auth/(セキュリティチームの管轄。レビュープロセスも別途存在)prisma/migrations/(npm run db:migrateを経由してのみ修正可能).envファイル(コミット禁止、設定ファイル以外で参照禁止)
現在のワークツリータスク
タスク:[エージェント開始前に記入]
ブランチ:[記入]
受入基準:[記入]
この下部のセクションこそが、本ファイルを各ワークツリーごとに機能させる鍵です。新しいワークツリーを作成する際は、必ず AGENTS.md を開き、エージェントを開始する前に上記 3 つの項目を埋めてください。これにより、エージェントの作業範囲を正確に限定し、手を出すべきでない領域へ誤って踏み込むのを防ぎます。
Claude Code の場合、ネイティブの -w フラグを使うと、ワークツリーの作成とセッション開始を単一コマンドで完結できます:
ワークツリーを作成し、その中で Claude Code セッションを開始する
claude --worktree feat/auth-redesign
短縮形
claude -w feat/auth-redesign
tmux パンを活用した分割画面での可視性
claude -w feat/auth-redesign --tmux
claude --worktree は、worktree-feat-auth-redesign というブランチ上に .claude/worktrees/feat-auth-redesign/ ディレクトリを作成し、その中でセッションを開始します。新しいワークツリー作成時に Git によって無視されているファイルを自動的にコピーするかどうかは、.worktreeinclude ファイル(gitignore の構文を使用)で制御できます。
.worktreeinclude -- リポジトリのルートに配置
新規作成時にすべてのワークツリーにコピーされるファイル
.env
.env.local
.env.development
// ステージ 3: 複数のエージェントを同時に実行する
3 つや 4 つのエージェントを同時に動かす必要がある場合、セットアップ全体をスクリプト化することで時間を節約し、一貫性を保つことができます。
実行方法: parallel-setup.sh という名前で保存し、chmod +x parallel-setup.sh で実行権限を与えた後、./parallel-setup.sh feat/auth feat/api feat/dashboard と実行します。
#!/usr/bin/env bash
# parallel-setup.sh
# 1 つのコマンドで N 個の並列 AI エージェント用に N 個のワークツリーを作成
# 使い方: ./parallel-setup.sh ...
# 例: ./parallel-setup.sh feat/auth feat/api feat/dashboard
set -euo pipefail
if [ $# -eq 0 ]; then
echo "Usage: $0 ... "
echo "Example: $0 feat/auth feat/api feat/dashboard"
exit 1
fi
REPO_ROOT="$(git rev-parse --show-toplevel)"
REPO_NAME="$(basename "$REPO_ROOT")"
MAIN_BRANCH="main"
echo "Setting up ${#@} parallel worktrees..."
git fetch origin 2>/dev/null || echo "(no remote -- skipping fetch)"for BRANCH in "$@"; do
SAFE="${BRANCH//\/-}"
WT_PATH="${REPO_ROOT}/../${REPO_NAME}-${SAFE}"
if [ -d "$WT_PATH" ]; then
echo "Already exists: $WT_PATH (skipping)"
continue
fi
# Create worktree on a new branch from main
git worktree add -b "$BRANCH" "$WT_PATH" "$MAIN_BRANCH" 2>/dev/null || \
git worktree add "$WT_PATH" "$BRANCH"
# Copy environment files
for f in .env .env.local; do
[ -f "$REPO_ROOT/$f" ] && cp "$REPO_ROOT/$f" "$WT_PATH/$f"
done
echo "Created: $WT_PATH (branch: $BRANCH)"
done
echo ""
echo "All worktrees:"
git worktree list
echo ""
echo "Open each path in a separate terminal or IDE window and start your agent."
echo "Remember to fill in the Task section of AGENTS.md in each worktree."
このスクリプトの利点は、1 つのコマンドで環境ファイルがコピーされたワークツリーをすべて作成できる点です。./parallel-setup.sh feat/auth feat/api feat/dashboard を実行するだけで、5 秒もかからずに 3 つの独立した作業ディレクトリが用意されます。それぞれのディレクトリを別のターミナルタブや IDE ウィンドウで開き、AGENTS.md にタスク内容を記入してエージェントを起動すれば完了です。
ワークツリーが主ブランチから乖離しないようにする
長期的なプロジェクトで最も大きな失敗要因は、作成時の競合ではなく「乖離(ドリフト)」です。3 日間メインブランチとの同期を行わずにワークツリーを実行し続けると、その間に蓄積された差分が大きくなりすぎてしまい、結果としてマージ作業自体が巨大なプロジェクト化してしまいます。
Claude Code をワークツリー環境で本番運用している実践者たちは、この点を明確に理解しています。チェックポイントの完了後には、必ずメインブランチから更新をプルしてマージしてください。これを怠るとワークツリーがメインブランチから大きく乖離し、解決困難な大規模なコンフリクトが発生するリスクがあります。
推奨されるのは、PR を作成する前だけでなく、重要なエージェントセッションの終了時に毎回同期を行うことです。
最適な戦略は「マージ」ではなく「リベース」です。リベースを行えば、ブランチのコミットを最新のメインブランチの上に重ねる形になり、履歴が線形に保たれ、PR の差分も明確でクリーンになります。
実行方法:sync-worktree.sh という名前で保存し、chmod +x sync-worktree.sh で実行権限を与えた後、任意のワークツリーディレクトリ内で ./sync-worktree.sh を実行してください。
#!/usr/bin/env bash
sync-worktree.sh
Rebases the current worktree branch onto the latest main
Run at checkpoints to prevent branch drift
Usage (from inside the worktree): ./sync-worktree.sh [main-branch-name]
Example: ./sync-worktree.sh main
set -euo pipefail
MAIN_BRANCH="${1:-main}"
CURRENT_BRANCH="$(git rev-parse --abbrev-ref HEAD)"
if [ "$CURRENT_BRANCH" = "$MAIN_BRANCH" ]; then
echo "Already on $MAIN_BRANCH -- nothing to sync."
exit 0
fi
echo "Syncing '$CURRENT_BRANCH' onto '$MAIN_BRANCH'..."
Reject if there is uncommitted work -- rebase requires a clean state
if ! git diff --quiet || ! git diff --cached --quiet; then
echo "ERROR: Uncommitted changes detected."
echo "Commit your progress first:"
echo " git add . && git commit -m 'checkpoint: agent progress'"
exit 1
fi
リモート側の最新状態を取得する
git fetch origin
このブランチを最新の main 上にリベースする
--autostash オプションは、作業ツリー内の細かい差分を自動的に処理します
git rebase "origin/$MAIN_BRANCH" --autostash
echo ""
echo "完了しました。'$CURRENT_BRANCH' は origin/$MAIN_BRANCH と同期されています。"
echo ""
echo "プッシュする準備ができたら:"
echo " git push --force-with-lease"
echo ""
echo "注意:--force-with-lease は --force よりも安全です。"
echo "これは、あなたが最後に取得した後に他の誰かがこのブランチにプッシュした場合、上書きを拒否します。"
何をしているのか?
リベース前に未コミットの変更があるかチェックするのは、重要な安全対策です。作業ツリーが汚れた状態でリベースすると、状態が混乱してしまいます。--autostash オプションは細かい差分の処理を担当し、プッシュ時の --force-with-lease は、まだ確認していないリモート上の作業を上書きしないため、--force よりも安全です。
エージェント完了から PR がマージされるまでの完全なライフサイクル:
作業ツリー内で、エージェントがタスクを完了した後
1. エージェントの成果物をコミットする
git add .
git commit -m "feat: implement OAuth2 + PKCE auth flow"
2. PR を作成する前に main と同期する
./sync-worktree.sh
3. 同期中に何かが壊れていないか確認するためテストを実行する
npm run test
4. ブランチをプッシュする
git push --force-with-lease origin feat/auth-redesign
5. GitHub CLI または Web インターフェースを使って PR を作成する
gh pr create \
--title "feat: OAuth2 + PKCE authentication" \
--body "Implements OAuth2 per docs/auth-spec.md. All tests pass."
6. PR がマージされたらクリーンアップする
cd ../myapp
./cleanup-worktree.sh feat/auth-redesign
Git Worktrees の完全コマンドリファレンス
Git Worktree を使ったすべてのコマンドを実例付きで紹介しています。最初のワークフローを構築する際は、このセクションを開いたままにしておくと便利です。
// ワークツリーの作成
main ブランチから新しいブランチ上のワークツリーを作成
git worktree add -b feat/payments ../myapp-payments main既存のブランチを新しいワークツリーとしてチェックアウト
git worktree add ../myapp-feat-auth feat/authDETACHED HEAD 状態にする(特定のコミットでバグを再現する際に有用)
git worktree add --detach ../myapp-debug abc1234リモートブランチを直接トラッキング
git worktree add ../myapp-hotfix origin/hotfix/login-crash// 確認と管理
すべてのワークツリー(パス、コミットハッシュ、ブランチ名)を表示
git worktree listスクリプトで利用可能な機械可読形式での出力
git worktree list --porcelain特定のワークツリーをロックする(prune コマンドによる削除を防ぐため)。エージェント実行中は、誤ってクリーンアップされないように保護するために使用します。
git worktree lock ../myapp-feat-auth --reason "agent-running"ロックの解除
git worktree unlock ../myapp-feat-authワークツリーディレクトリの移動(開いているエディタは必ず閉じてから実行)
git worktree move ../myapp-feat-auth ../worktrees/auth-redesign// クリーンアップ
ワークツリーをクリーンに削除(ブランチ自体は Git 上に残ります)
git worktree remove ../myapp-feat-auth未コミットの変更があっても強制的に削除
※作業内容を破棄して問題ないと確信できる場合のみ使用してください。
git worktree remove --force ../myapp-feat-authrm -rf で手動削除されたワークツリーのメタデータを整理
git worktree prune実際に削除する前に、何が消えるか確認する
git worktree prune --dry-run
.git ディレクトリを移動した後の参照情報を修復する
git worktree repair
よくあるエラーと対処法
エラーメッセージ | 原因 | 対処法
---|---|---
fatal: 'feat/auth' is already checked out | 別のワークツリーでそのブランチが使用中 | 別のブランチを使うか、既存のワークツリーを先に削除する
fatal: <path> already exists | 対象ディレクトリが存在している | そのディレクトリを削除するか、パスを変更する
error: '...' is a main worktree | メインチェックアウト(メインブランチ)の削除を試みた | 削除できるのはリンクされたワークツリーのみ
error: worktree has modified files | 未コミットの変更がある | 作業をコミットするか、--force オプションで破棄する
git worktree list に rm -rf 後も表示される | メタデータが清掃されていない | git worktree prune を実行する
まとめ
Git のワークツリーは、難解な Git の秘術などではありません。AI コーディングエージェントが同じコードベース上で並列実行され始めた瞬間から、不可欠なインフラストラクチャの基礎要素として機能しています。
この記事で紹介するワークフローは、単なる理論ではありません。これはマイクロソフトのグローバル・ハッカソンでタミール・ドレシャー氏のチームが実際に実行した手法です。また、現在 GitHub や Medium で実践者が Claude Code、Cursor、Codex を活用して報告している内容でもあります。
なぜ「アジェンティック・コーディング」コミュニティがこのパターンに収束したのか。それは、この手法が解決すべき課題に対して、最もシンプルかつ確実に機能するからにほかなりません。
セットアップの負担は低く抑えられます。本記事で紹介する 4 つのスクリプトで、ブランチ作成、同期、クリーンアップというライフサイクル全体を約 120 行の Bash スクリプトでカバーできます。概念モデルもシンプルです。「1 つのタスクに、1 つのブランチ、1 つのワークツリー、1 つのエージェント」。この構成により、複数のエージェントを並列実行できるようになります。その結果、午後を費やして、どちらのエージェントも意図的に作成したわけではない競合を解きほぐす必要がなくなります。
すでに AI コーディングツールを活用しているなら、次のプロジェクトでワークツリーの設定を始めましょう。create-worktree.sh スクリプトを使えば、わずか 10 秒で準備が整います。チームのワークフローを AI エージェント中心に再構築する場合は、AGENTS.md と並列設定スクリプトを活用することで、場当たり的なセッションから、拡張性のある反復可能なプロセスへと移行できます。
コードを書くのはモデルです。あなたの役割は、そのモデルが混乱せず、並列でクリーンに動作できる環境を整えることです。
Shittu Olumide は、最先端の技術を活用して魅力的な物語を紡ぎ出すことに情熱を注ぐソフトウェアエンジニアであり、テクニカルライターです。細部へのこだわりと複雑な概念をわかりやすく解説する能力に長けており、Twitter でも活動しています。
原文を表示

**
# Introduction
You are running Claude Code** on a feature branch. The agent has been working for twenty minutes, it has read your codebase, built up context, and started making real progress on the authentication rewrite. Then a Slack message appears: production is down, someone needs a hotfix on main, and they need it now.
In the old workflow, you stash your changes, switch branches, lose everything your AI agent built up, fix the bug, push, switch back, and spend ten minutes getting the agent re-oriented to what it was doing. If you were running two agents simultaneously on the same directory, the situation is worse — both agents touching package.json, both generating edits to the same files, and the second writes silently, overwriting the first. No warning. No error. Just corrupted work you discover an hour later when tests fail in a way that makes no sense.
Git worktrees eliminate this entire class of problems. They are not a new invention — the feature has been in Git since version 2.5, released in 2015 — but the AI coding wave of 2025–2026 made them essential infrastructure. One .git directory, multiple working directories, each on its own branch, each invisible to the others. Each AI agent gets its own isolated workspace. The hotfix gets its own workspace. Nothing collides.
51% of professional developers now use AI tools daily, but only 17% of developers using AI agents say those tools have improved team collaboration. The gap between those two numbers is not a tooling problem. It is an infrastructure problem. Teams adopted AI agents without the workflow layer underneath. This guide is that workflow layer.
By the end, you will know what worktrees are, how to set them up, how to run parallel AI agents inside them without chaos, and how to maintain them over the life of a project.
# What Git Worktrees Actually Are
A standard Git repository has one working directory — the folder where your files live and where you edit code. To work on a different branch, you switch to it, which changes all the files in that directory to match the branch. If you have uncommitted work, you stash it first. If your AI agent is mid-task, you interrupt it.
Git worktrees break this constraint. A worktree is a separate directory checked out from the same repository. You can have as many as you need, each on its own branch, all coexisting simultaneously on your filesystem.
my-project/ ← main worktree (branch: main)
my-project-feat-auth/ ← linked worktree (branch: feat/auth)
my-project-feat-api/ ← linked worktree (branch: feat/api)
my-project-hotfix-login/ ← linked worktree (branch: hotfix/login)All four directories share the same .git folder. They share history, objects, and commits. But each has its own checked-out files, its own index, and its own working state. An agent editing files in my-project-feat-auth/ cannot see or touch anything in my-project-feat-api/. They are physically separate directories that happen to share a git backend.
**

Why does this beat multiple clones?** The naive alternative to worktrees is cloning the repository twice and working in different clone directories. This works, but it has real costs: you duplicate the entire repository on disk, git history is not shared between clones, commits in one clone are not immediately visible in another, and there is no coordination between them at the git layer. With worktrees, you clone once. Every additional worktree adds only the cost of the checked-out files, not another copy of the full history.
The seven commands that cover everything you need to manage worktrees:
Command
What It Does
git worktree add <path> -b <branch>
Create a new worktree on a new branch
git worktree add <path> <existing-branch>
Check out an existing branch into a new worktree
git worktree list
Show all active worktrees with their branches and commit hashes
git worktree lock <path>
Prevent a worktree from being pruned (useful while an agent is running)
git worktree unlock <path>
Release the lock
git worktree remove <path>
Delete a worktree cleanly (branch is preserved)
git worktree prune
Clean up metadata for worktrees that were manually deleted
That is the full surface area. Everything else in this article is a workflow built on top of these seven commands.
# Setting Up
**
Prerequisites: Git 2.5 or higher. Run git --version to check. Any modern system (macOS, Linux, Windows with WSL or Git Bash) ships with a version above 2.5.
// Step 1: Starting From a Clean Repository
Worktrees work best when your main branch is clean. Commit or stash any in-progress work before creating your first worktree.
# Verify you have a clean working tree
git status
# If there is uncommitted work, commit it
git add . && git commit -m "checkpoint: work in progress"// Step 2: Creating Your First Worktree
# Create a new worktree at ../myapp-feat-auth on a new branch feat/auth
# Replace "myapp" with your project name and "feat/auth" with your branch name
git worktree add -b feat/auth ../myapp-feat-auth main
# Verify it was created
git worktree listYou should see output like this:
/home/user/myapp abc1234 [main]
/home/user/myapp-feat-auth abc1234 [feat/auth]Both directories exist. Both contain the same files from the main branch. From this point, any changes you make in myapp-feat-auth/ stay on feat/auth and are completely isolated from main.
// Step 3: Setting Up the Environment in the New Worktree
This is the step most tutorials skip. A worktree is a new working directory. It does not automatically have your .env file, your installed node_modules, or your Python virtual environment. You need to set those up explicitly.
cd ../myapp-feat-auth
# Copy environment files that are gitignored
# .env, .env.local, and similar files are not tracked in git --
# they will not appear in the new worktree automatically
cp ../myapp/.env .env
cp ../myapp/.env.local .env.local 2>/dev/null || true
# Node.js project: install dependencies
# Each worktree is an independent working directory --
# node_modules from the parent does not carry over
npm install
# Python project: create and activate a virtual environment
# python -m venv .venv && source .venv/bin/activate && pip install -r requirements.txt// Step 4: Verifying the Worktree Is Isolated
# From inside the new worktree
git branch
# Should show: * feat/auth
# Make a test change
echo "// test" >> test-isolation.js
git status
# Only shows the change in this worktree
# Switch to the main directory and verify it is unaffected
cd ../myapp
git status
# Clean -- the test-isolation.js change is invisible here
ls test-isolation.js 2>/dev/null || echo "Not here -- isolation confirmed"That is all you need to get started. The worktree is live. Any agent you open in that directory operates only on feat/auth**.
# A Real-World Case Study
The clearest documented example of git worktrees used for AI-driven parallel development comes from the Microsoft Global Hackathon 2025.
Tamir Dresher, an engineering lead, faced a problem that everyone building with AI agents eventually hits: too many features, too little time, and no way to work on more than one thing at once without constant context-switching. Creating multiple clones of the repository was cumbersome. Switching branches destroyed the AI agent's context. Something had to change.
The solution was to use git worktrees to create what Dresher described as a virtual AI development team. Each feature got its own worktree. Each worktree got its own VS Code window. Each window ran its own AI agent. Dresher's role shifted from developer to tech lead: scoping tasks, reviewing output, guiding agents that got stuck, and merging finished work.
The setup looked like this:
myapp/ ← main window: coordination and reviews
myapp-feat-authentication/ ← Agent 1: implementing OAuth2 flow
myapp-feat-api-endpoints/ ← Agent 2: building REST endpoints
myapp-bugfix-login-crash/ ← Agent 3: fixing production bugEach VS Code window was completely independent. Language servers, linters, and test runners run per window. The agents never touched each other's files. When Agent 1 finished, Dresher reviewed the diff, approved it, and opened a pull request (PR) from that branch — the same workflow as reviewing a PR from a human engineer.
Three concrete advantages Dresher documented from the hackathon:
- No context loss. Each AI agent maintained full context of its specific task. Switching between features meant switching VS Code windows, not branches, not stashes, not agent restarts. The agent's understanding of what it was building stayed intact.
- Different tools for different jobs. Because each window was independent, Dresher ran Roo in one window for rapid feature development and GitHub Copilot with Visual Studio in another for debugging complex issues. Mixing tools across tasks was trivial.
- Clean branch management. If a feature needed to be abandoned, closing the window and deleting the worktree took ten seconds. The other agents were unaffected.
**

The pattern that emerged from this hackathon is now a documented best practice across the AI coding community.
# Running Parallel AI Agents With Worktrees
The mechanics of the full parallel workflow have four stages: set up the worktrees, give each agent its context, run the agents, and checkpoint regularly.
// Stage 1: Scripting the Worktree Creation
Do not create worktrees manually each time. A script ensures every worktree gets the same setup — environment files, dependency installation, and a clean starting point.
Prerequisites: Git 2.5+, Bash (macOS/Linux/WSL)
How to run: Save as create-worktree.sh in your project root, run chmod +x create-worktree.sh, then ./create-worktree.sh feat/auth-redesign main.
#!/usr/bin/env bash
# create-worktree.sh
# Creates an isolated worktree for one AI agent task
# Usage: ./create-worktree.sh [base-branch]
# Example: ./create-worktree.sh feat/auth-redesign main
set -euo pipefail
BRANCH="${1:?Usage: $0 [base-branch]}"
BASE="${2:-main}"
REPO_ROOT="$(git rev-parse --show-toplevel)"
REPO_NAME="$(basename "$REPO_ROOT")"
# Replace slashes in branch name with dashes for directory naming
# feat/auth-redesign becomes feat-auth-redesign in the path
WORKTREE_PATH="${REPO_ROOT}/../${REPO_NAME}-${BRANCH//\//-}"
echo "Creating worktree for branch: $BRANCH"
echo "Base branch: $BASE"
echo "Worktree path: $WORKTREE_PATH"
# Fetch latest so the new branch starts from the current remote state
git fetch origin 2>/dev/null || echo "(no remote -- skipping fetch)"
# Create the worktree on a new branch from the base branch
# Falls back to checking out an existing branch if -b fails
git worktree add -b "$BRANCH" "$WORKTREE_PATH" "$BASE" 2>/dev/null || \
git worktree add "$WORKTREE_PATH" "$BRANCH"
# Copy non-tracked environment files into the worktree
# These are gitignored, so they do not carry over automatically
for f in .env .env.local .env.development .env.test; do
if [ -f "$REPO_ROOT/$f" ]; then
cp "$REPO_ROOT/$f" "$WORKTREE_PATH/$f"
echo "Copied $f"
fi
done
# Node.js: install dependencies in the new working directory
if [ -f "$WORKTREE_PATH/package.json" ]; then
echo "Installing Node dependencies..."
(cd "$WORKTREE_PATH" && npm install --silent 2>/dev/null || \
echo "(npm install skipped -- run it manually in the worktree)")
fi
# Python: remind the developer to set up their environment
if [ -f "$WORKTREE_PATH/requirements.txt" ] || [ -f "$WORKTREE_PATH/pyproject.toml" ]; then
echo "Python project detected."
echo "Run in the new worktree:"
echo " python -m venv .venv && source .venv/bin/activate && pip install -r requirements.txt"
fi
echo ""
echo "Worktree ready. Open it in your IDE and start your agent:"
echo " cd $WORKTREE_PATH"What this does: The script creates the worktree, copies gitignored environment files across (the most common setup failure), and runs dependency installation in the new directory. The ${BRANCH//\//-} substitution safely converts branch names like feat/auth into filesystem-friendly directory names like feat-auth. The fallback on line 23 handles the case where the branch already exists remotely.
// Stage 2: Setting Up the AGENTS.md Context File
The single most important thing you can do to improve agent output is give each agent a clear, written context file. Peer-reviewed research at ICSE 2026 confirmed that incorporating architectural documentation into agent context produces measurable gains in functional correctness, architectural conformance, and code modularity. The AGENTS.md file is how you deliver that context reliably, at scale, across every session.
Create this file in your project root and commit it. Every agent reads it on session start. Different tools read different filenames — AGENTS.md (OpenAI Codex), CLAUDE.md (Claude Code), AGENTS.md (generic) — but the content matters more than the name.
# AGENTS.md
# Project context for AI coding agents
# Commit this to your repository root.
# Every agent that opens this project reads it first.
## Project Overview
Node.js/TypeScript REST API with a React frontend.
Stack: Node 20, Express 5, Prisma ORM, PostgreSQL, React 18, Vite.
## Build and Test Commands
npm run dev # start dev server on port 3000
npm run build # production build to dist/
npm run test # run all tests (Vitest)
npm run test:watch # watch mode
npm run lint # ESLint and Prettier check
npm run db:migrate # run pending Prisma migrations
npm run db:seed # seed development data
## Architecture
- API routes: src/routes/ one file per resource
- Business logic: src/services/ never in route handlers
- Database access: src/repositories/ never call Prisma directly from services
- Shared types: src/types/index.ts
## Conventions
- All exported functions require JSDoc comments
- No console.log in committed code -- use src/utils/logger.ts
- Error handling: throw typed errors from services, catch in route handlers
- Branch naming: feat/, fix/, refactor/
## Prohibited Zones -- Do NOT modify unless explicitly told to
- src/auth/ (security team ownership, separate review process)
- prisma/migrations/ (only modify via npm run db:migrate)
- .env files (never commit, never read outside config/)
## Current Worktree Task
Task: [FILL IN before starting the agent]
Branch: [FILL IN]
Acceptance criteria: [FILL IN]The bottom section is what makes this file work per-worktree. Every time you create a new worktree, open AGENTS.md and fill in those three lines before starting the agent. This scopes the agent's work precisely and prevents it from wandering into areas it should not touch.
For Claude Code specifically, the native -w flag handles worktree creation and session start in one command:
# Create a worktree and start a Claude Code session inside it
claude --worktree feat/auth-redesign
# Short form
claude -w feat/auth-redesign
# With tmux panes for split-screen visibility
claude -w feat/auth-redesign --tmuxclaude --worktree creates .claude/worktrees/feat-auth-redesign/ on a branch called worktree-feat-auth-redesign, then starts the session inside it. The .worktreeinclude file (gitignore syntax) controls which gitignored files are automatically copied into new worktrees:
# .worktreeinclude -- place in your repo root
# Files to copy into every new worktree on creation
.env
.env.local
.env.development// Stage 3: Running Multiple Agents at Once
When you need three or four agents running simultaneously, scripting the entire setup saves time and ensures consistency.
How to run: Save as parallel-setup.sh, run chmod +x parallel-setup.sh, then ./parallel-setup.sh feat/auth feat/api feat/dashboard.
#!/usr/bin/env bash
# parallel-setup.sh
# Creates N worktrees for N parallel AI agents in one command
# Usage: ./parallel-setup.sh ...
# Example: ./parallel-setup.sh feat/auth feat/api feat/dashboard
set -euo pipefail
if [ $# -eq 0 ]; then
echo "Usage: $0 ... "
echo "Example: $0 feat/auth feat/api feat/dashboard"
exit 1
fi
REPO_ROOT="$(git rev-parse --show-toplevel)"
REPO_NAME="$(basename "$REPO_ROOT")"
MAIN_BRANCH="main"
echo "Setting up ${#@} parallel worktrees..."
git fetch origin 2>/dev/null || echo "(no remote -- skipping fetch)"
for BRANCH in "$@"; do
SAFE="${BRANCH//\//-}"
WT_PATH="${REPO_ROOT}/../${REPO_NAME}-${SAFE}"
if [ -d "$WT_PATH" ]; then
echo "Already exists: $WT_PATH (skipping)"
continue
fi
# Create worktree on a new branch from main
git worktree add -b "$BRANCH" "$WT_PATH" "$MAIN_BRANCH" 2>/dev/null || \
git worktree add "$WT_PATH" "$BRANCH"
# Copy environment files
for f in .env .env.local; do
[ -f "$REPO_ROOT/$f" ] && cp "$REPO_ROOT/$f" "$WT_PATH/$f"
done
echo "Created: $WT_PATH (branch: $BRANCH)"
done
echo ""
echo "All worktrees:"
git worktree list
echo ""
echo "Open each path in a separate terminal or IDE window and start your agent."
echo "Remember to fill in the Task section of AGENTS.md in each worktree."What this does: One command produces all the worktrees with environment files copied. Running ./parallel-setup.sh feat/auth feat/api feat/dashboard gives you three isolated working directories in under five seconds. Open each in its own terminal tab, fill in AGENTS.md, and start the agents.
# Keeping Worktrees From Drifting
The biggest long-term failure mode is not conflicts at creation time — it is drift. A worktree that runs for three days without syncing to main** accumulates divergence that makes merging a project in itself.
Practitioners using Claude Code with worktrees in production are clear on this: after completing a checkpoint, pull and merge updates from the main branch — this prevents the worktree from drifting too far, which would result in massive, hard-to-resolve conflicts. The recommendation is to sync at the end of every significant agent session, not just before the PR.
The right strategy is rebase, not merge. Rebasing writes your branch's commits on top of the latest main, which keeps the history linear and makes the PR diff clean.
How to run: Save as sync-worktree.sh, run chmod +x sync-worktree.sh, then run ./sync-worktree.sh from inside any worktree directory.
#!/usr/bin/env bash
# sync-worktree.sh
# Rebases the current worktree branch onto the latest main
# Run at checkpoints to prevent branch drift
# Usage (from inside the worktree): ./sync-worktree.sh [main-branch-name]
# Example: ./sync-worktree.sh main
set -euo pipefail
MAIN_BRANCH="${1:-main}"
CURRENT_BRANCH="$(git rev-parse --abbrev-ref HEAD)"
if [ "$CURRENT_BRANCH" = "$MAIN_BRANCH" ]; then
echo "Already on $MAIN_BRANCH -- nothing to sync."
exit 0
fi
echo "Syncing '$CURRENT_BRANCH' onto '$MAIN_BRANCH'..."
# Reject if there is uncommitted work -- rebase requires a clean state
if ! git diff --quiet || ! git diff --cached --quiet; then
echo "ERROR: Uncommitted changes detected."
echo "Commit your progress first:"
echo " git add . && git commit -m 'checkpoint: agent progress'"
exit 1
fi
# Fetch the latest remote state
git fetch origin
# Rebase this branch onto the latest main
# --autostash handles minor working tree differences automatically
git rebase "origin/$MAIN_BRANCH" --autostash
echo ""
echo "Done. '$CURRENT_BRANCH' is up to date with origin/$MAIN_BRANCH."
echo ""
echo "When ready to push:"
echo " git push --force-with-lease"
echo ""
echo "Note: --force-with-lease is safer than --force."
echo "It refuses to push if someone else pushed to this branch since your last fetch."What this does: The uncommitted-changes check before the rebase is an important safety measure. A rebase on a dirty tree produces a confusing state. --autostash handles minor differences. --force-with-lease on push is safer than --force because it refuses to overwrite remote work you have not seen yet.
The full merge lifecycle from agent completion to merged PR:
# Inside the worktree, after the agent finishes its task
# 1. Commit the agent's work
git add .
git commit -m "feat: implement OAuth2 + PKCE auth flow"
# 2. Sync with main before opening a PR
./sync-worktree.sh
# 3. Run tests to verify nothing broke in the sync
npm run test
# 4. Push the branch
git push --force-with-lease origin feat/auth-redesign
# 5. Open a PR via GitHub CLI or the web interface
gh pr create \
--title "feat: OAuth2 + PKCE authentication" \
--body "Implements OAuth2 per docs/auth-spec.md. All tests pass."
# 6. After the PR merges, clean up
cd ../myapp
./cleanup-worktree.sh feat/auth-redesign# The Complete Command Reference
**
Every git worktree command with real examples. Keep this section open while building your first workflow.
// Creating Worktrees
# Create a worktree on a new branch from main
git worktree add -b feat/payments ../myapp-payments main
# Check out an existing branch into a new worktree
git worktree add ../myapp-feat-auth feat/auth
# Detached HEAD -- useful for reproducing a bug at a specific commit
git worktree add --detach ../myapp-debug abc1234
# Track a remote branch directly
git worktree add ../myapp-hotfix origin/hotfix/login-crash// Inspecting and Managing
# Show all worktrees with path, commit hash, and branch name
git worktree list
# Machine-readable output for use in scripts
git worktree list --porcelain
# Lock a worktree so prune does not remove it
# Use while an agent is running to protect against accidental cleanup
git worktree lock ../myapp-feat-auth --reason "agent-running"
# Release the lock
git worktree unlock ../myapp-feat-auth
# Move a worktree directory (close any open editors first)
git worktree move ../myapp-feat-auth ../worktrees/auth-redesign// Cleanup
# Remove a worktree cleanly -- the branch is preserved in git
git worktree remove ../myapp-feat-auth
# Force remove even with uncommitted changes
# Only use this when you are certain the work can be discarded
git worktree remove --force ../myapp-feat-auth
# Clean up metadata for worktrees manually deleted with rm -rf
git worktree prune
# Preview what would be pruned without actually pruning
git worktree prune --dry-run
# Fix worktree references after moving the .git directory
git worktree repair# Common Errors and Fixes
Error Message**
Cause
Fix
fatal: 'feat/auth' is already checked out
Branch in use by another worktree
Use a different branch, or remove the existing worktree first
fatal: <path> already exists
Target directory exists
Delete it or choose a different path
error: '...' is a main worktree
Tried to remove the main checkout
Only linked worktrees can be removed
error: worktree has modified files
Uncommitted changes present
Commit the work, or use --force to discard
Worktree appears in git worktree list after rm -rf
Metadata not cleaned up
Run git worktree prune
# Conclusion
**
Git worktrees are not advanced Git arcana. They are a core infrastructure primitive that became essential the moment AI coding agents started running in parallel on the same codebases.
The workflow in this article is not theoretical. It is what Tamir Dresher's team ran at the Microsoft Global Hackathon. It is what practitioners with Claude Code, Cursor, and Codex** are documenting across GitHub and Medium right now. It is the pattern the agentic coding community has converged on for one reason: it is the simplest thing that reliably solves the problem it was built to solve.
The setup cost is low. The four scripts in this article cover the full lifecycle — create, sync, and clean up — in about 120 lines of bash. The conceptual model is simple: one task, one branch, one worktree, one agent. The payoff is that you can run multiple agents in parallel without spending your afternoon untangling conflicts that neither agent created intentionally.
If you are already using AI coding tools and not using worktrees, set them up on your next project. The create-worktree.sh script is a ten-second start. If you are building a team workflow around AI agents, AGENTS.md and the parallel setup script move you from ad-hoc sessions to a repeatable process that scales.
The model writes the code. Your job is to create the conditions where it can do that cleanly, in parallel, without getting in its own way.
Shittu Olumide is a software engineer and technical writer passionate about leveraging cutting-edge technologies to craft compelling narratives, with a keen eye for detail and a knack for simplifying complex concepts. You can also find Shittu on Twitter.
関連記事
今日のまとめ
AI日報で今日の重要ニュースをまとめ読み