git-worktree-workflow

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Git Worktree Workflow Skill

Git Worktree工作流技能

Version: 1.1.0 Created: 2025-12-30 Last Updated: 2026-01-02 Category: Development
版本:1.1.0 创建时间:2025-12-30 最后更新:2026-01-02 分类:开发

Overview

概述

Git worktrees allow you to have multiple working directories from a single repository, enabling parallel development workflows with Claude Code. This is essential for running multiple Claude instances on different tasks simultaneously.
Git Worktree允许你从单个仓库拥有多个工作目录,从而实现与Claude Code结合的并行开发工作流。这对于同时在不同任务上运行多个Claude实例至关重要。

Quick Start

快速开始

bash
undefined
bash
undefined

1. Create worktree for new feature branch

1. 为新功能分支创建工作树

git worktree add -b feature-api ../project-api main
git worktree add -b feature-api ../project-api main

2. Run Claude in worktree

2. 在工作树中运行Claude

cd ../project-api && claude "Implement the feature"
cd ../project-api && claude "Implement the feature"

3. After completion, merge and cleanup

3. 完成后合并并清理

cd ../project git merge feature-api git worktree remove ../project-api git branch -d feature-api
undefined
cd ../project git merge feature-api git worktree remove ../project-api git branch -d feature-api
undefined

When to Use

适用场景

  • Running multiple Claude agents on different features
  • Testing changes while continuing development
  • Code review with live comparison
  • Parallel bug fixes across branches
  • Subagent verification workflows
  • A/B implementation comparisons
  • CI/CD parallel job execution
  • 在不同功能上运行多个Claude Agent
  • 测试变更的同时继续开发
  • 结合实时对比进行代码评审
  • 跨分支并行修复Bug
  • 子Agent验证工作流
  • A/B方案实现对比
  • CI/CD并行任务执行

Concepts

核心概念

What is a Worktree?

什么是Worktree?

Main repo: /project (on main branch)
Worktree 1: /project-feature-a (on feature-a branch)
Worktree 2: /project-feature-b (on feature-b branch)
Worktree 3: /project-hotfix (on hotfix branch)
All share the same
.git
directory but have independent working directories.
主仓库:/project(位于main分支)
工作树1:/project-feature-a(位于feature-a分支)
工作树2:/project-feature-b(位于feature-b分支)
工作树3:/project-hotfix(位于hotfix分支)
所有工作树共享同一个
.git
目录,但拥有独立的工作目录。

Basic Commands

基础命令

Create a Worktree

创建工作树

bash
undefined
bash
undefined

Create worktree for existing branch

为已有分支创建工作树

git worktree add ../project-feature feature-branch
git worktree add ../project-feature feature-branch

Create worktree with new branch

创建带新分支的工作树

git worktree add -b new-feature ../project-new-feature main
git worktree add -b new-feature ../project-new-feature main

Create worktree for detached HEAD (testing)

创建分离HEAD的工作树(用于测试)

git worktree add --detach ../project-test HEAD
undefined
git worktree add --detach ../project-test HEAD
undefined

List Worktrees

列出工作树

bash
git worktree list
bash
git worktree list

Output:

输出:

/project abc1234 [main]

/project abc1234 [main]

/project-feature def5678 [feature-a]

/project-feature def5678 [feature-a]

/project-hotfix ghi9012 [hotfix-123]

/project-hotfix ghi9012 [hotfix-123]

undefined
undefined

Remove Worktree

删除工作树

bash
undefined
bash
undefined

Remove after merging

合并后删除工作树

git worktree remove ../project-feature
git worktree remove ../project-feature

Force remove (discards changes)

强制删除(丢弃变更)

git worktree remove --force ../project-abandoned
git worktree remove --force ../project-abandoned

Prune stale worktrees

清理过期工作树

git worktree prune
undefined
git worktree prune
undefined

Parallel Claude Workflows

并行Claude工作流

Pattern 1: Feature + Review

模式1:开发+评审

Run development and review in parallel:
bash
undefined
并行执行开发与评审:
bash
undefined

Terminal 1: Development Claude

终端1:开发用Claude

cd /project-feature claude "Implement the new authentication module"
cd /project-feature claude "Implement the new authentication module"

Terminal 2: Review Claude

终端2:评审用Claude

cd /project claude "Review the authentication changes in feature-auth branch"
undefined
cd /project claude "Review the authentication changes in feature-auth branch"
undefined

Pattern 2: Multi-Feature Development

模式2:多功能并行开发

Work on multiple features simultaneously:
bash
undefined
同时开发多个功能:
bash
undefined

Setup worktrees

搭建工作树

git worktree add -b feature-api ../project-api main git worktree add -b feature-ui ../project-ui main git worktree add -b feature-tests ../project-tests main
git worktree add -b feature-api ../project-api main git worktree add -b feature-ui ../project-ui main git worktree add -b feature-tests ../project-tests main

Run Claude in each (separate terminals)

在每个工作树中运行Claude(分开的终端)

cd ../project-api && claude "Build REST API endpoints" cd ../project-ui && claude "Create React components" cd ../project-tests && claude "Write integration tests"
undefined
cd ../project-api && claude "Build REST API endpoints" cd ../project-ui && claude "Create React components" cd ../project-tests && claude "Write integration tests"
undefined

Pattern 3: Subagent Verification

模式3:子Agent验证

Main Claude spawns verification in separate worktree:
bash
undefined
主Claude在独立工作树中启动验证任务:
bash
undefined

Main Claude working in /project

主Claude在/project目录工作

Creates verification worktree:

创建验证工作树:

git worktree add --detach ../project-verify HEAD
git worktree add --detach ../project-verify HEAD

Spawns subagent to verify:

启动子Agent进行验证:

cd ../project-verify && claude -p "Verify the implementation works correctly"
undefined
cd ../project-verify && claude -p "Verify the implementation works correctly"
undefined

Pattern 4: A/B Implementation

模式4:A/B方案实现对比

Compare two approaches:
bash
undefined
对比两种实现方式:
bash
undefined

Create two worktrees from same point

从同一节点创建两个工作树

git worktree add -b approach-a ../project-a main git worktree add -b approach-b ../project-b main
git worktree add -b approach-a ../project-a main git worktree add -b approach-b ../project-b main

Different Claude instances try different solutions

不同Claude实例尝试不同解决方案

cd ../project-a && claude "Implement caching using Redis" cd ../project-b && claude "Implement caching using Memcached"
cd ../project-a && claude "Implement caching using Redis" cd ../project-b && claude "Implement caching using Memcached"

Compare results

对比结果

diff -r ../project-a/src ../project-b/src
undefined
diff -r ../project-a/src ../project-b/src
undefined

Best Practices

最佳实践

Do

建议执行

  1. Use descriptive naming convention:
    <project>-<purpose>
  2. Create worktrees in sibling directories (not inside project)
  3. Commit or stash changes before removing worktrees
  4. Prune stale worktrees regularly
  5. Document active worktrees in team communication
  6. Clean up merged worktrees promptly
  1. 使用描述性命名规则:
    <项目名>-<用途>
  2. 在同级目录创建工作树(不要在项目内部)
  3. 删除工作树前提交或暂存变更
  4. 定期清理过期工作树
  5. 在团队沟通中记录活跃的工作树
  6. 合并后及时清理工作树

Don't

请勿执行

  1. Create worktrees inside the main project directory
  2. Leave uncommitted changes in worktrees before removal
  3. Forget to merge/push changes from worktrees
  4. Create excessive worktrees (manage actively)
  5. Use worktrees for long-lived branches (use separate clones)
  6. Skip the cleanup step after merging
  1. 在主项目目录内部创建工作树
  2. 删除工作树前保留未提交的变更
  3. 忘记合并/推送工作树中的变更
  4. 创建过多工作树(需主动管理)
  5. 为长期分支使用工作树(建议使用独立克隆)
  6. 合并后跳过清理步骤

Naming Convention

命名规则

bash
undefined
bash
undefined

Pattern: <project>-<purpose>

格式:<项目名>-<用途>

../project-feature-auth # Feature work ../project-hotfix-123 # Bug fix ../project-review # Code review ../project-test # Testing ../project-experiment # Experiments
undefined
../project-feature-auth # 功能开发 ../project-hotfix-123 # Bug修复 ../project-review # 代码评审 ../project-test # 测试 ../project-experiment # 实验
undefined

Workspace Organization

工作区组织

/workspace/
├── project/                 # Main development
├── project-feature-a/       # Active features
├── project-feature-b/
├── project-review/          # Review worktree
└── project-archive/         # Completed features (before cleanup)
/workspace/
├── project/                 # 主开发目录
├── project-feature-a/       # 活跃功能开发
├── project-feature-b/
├── project-review/          # 评审工作树
└── project-archive/         # 已完成功能(清理前)

Cleanup Script

清理脚本

bash
#!/bin/bash
bash
#!/bin/bash

cleanup-worktrees.sh

cleanup-worktrees.sh

Remove merged branches

删除已合并的分支

git branch --merged main | grep -v main | while read branch; do worktree=$(git worktree list | grep "$branch" | awk '{print $1}') if [ -n "$worktree" ]; then echo "Removing worktree: $worktree" git worktree remove "$worktree" fi done
git branch --merged main | grep -v main | while read branch; do worktree=$(git worktree list | grep "$branch" | awk '{print $1}') if [ -n "$worktree" ]; then echo "Removing worktree: $worktree" git worktree remove "$worktree" fi done

Prune stale references

清理过期引用

git worktree prune
undefined
git worktree prune
undefined

Integration with Claude Code

与Claude Code的集成

CLAUDE.md Configuration

CLAUDE.md配置

Add to project CLAUDE.md:
markdown
undefined
在项目的CLAUDE.md中添加以下内容:
markdown
undefined

Worktree Workflow

Worktree工作流

When running parallel tasks:
  1. Create worktree:
    git worktree add -b <branch> ../<project>-<purpose> main
  2. Work in isolated directory
  3. Commit changes normally
  4. Return to main and merge
  5. Remove worktree:
    git worktree remove ../<worktree>
undefined
执行并行任务时:
  1. 创建工作树:
    git worktree add -b <branch> ../<project>-<purpose> main
  2. 在独立目录中工作
  3. 正常提交变更
  4. 返回主目录并合并
  5. 删除工作树:
    git worktree remove ../<worktree>
undefined

Headless Mode in Worktrees

工作树中的无头模式

bash
undefined
bash
undefined

Automate worktree operations

自动化工作树操作

WORKTREE="../project-auto-$(date +%s)" git worktree add -b auto-task "$WORKTREE" main
cd "$WORKTREE" claude -p "Complete the task in task.md" --output result.md
WORKTREE="../project-auto-$(date +%s)" git worktree add -b auto-task "$WORKTREE" main
cd "$WORKTREE" claude -p "Complete the task in task.md" --output result.md

Collect results

收集结果

cp result.md ../results/ git worktree remove "$WORKTREE"
undefined
cp result.md ../results/ git worktree remove "$WORKTREE"
undefined

Error Handling

错误处理

ErrorCauseSolution
Branch already checked outBranch exists in another worktreeRemove existing worktree or use different branch
Cannot remove worktreeUncommitted changes presentCommit, stash, or force remove
Permission errorsDirectory not writable
chmod -R u+w <worktree>
then remove
Stale worktree referencesWorktree directory deleted manuallyRun
git worktree prune
Lock file existsPrevious operation interruptedRemove
.git/worktrees/<name>/locked
file
Path already existsDirectory exists at target pathChoose different path or remove existing directory
错误原因解决方案
分支已被检出分支已存在于另一个工作树中删除现有工作树或使用其他分支
无法删除工作树存在未提交的变更提交、暂存或强制删除
权限错误目录不可写执行
chmod -R u+w <worktree>
后再删除
过期工作树引用手动删除了工作树目录执行
git worktree prune
存在锁定文件之前的操作被中断删除
.git/worktrees/<name>/locked
文件
路径已存在目标路径下已有目录选择其他路径或删除现有目录

Advanced: CI/CD Integration

进阶:CI/CD集成

GitHub Actions Parallel Jobs

GitHub Actions并行任务

yaml
jobs:
  parallel-claude:
    strategy:
      matrix:
        task: [lint, test, security]
    steps:
      - uses: actions/checkout@v4

      - name: Create worktree
        run: |
          git worktree add -b ${{ matrix.task }} ../work-${{ matrix.task }}

      - name: Run Claude task
        run: |
          cd ../work-${{ matrix.task }}
          claude -p "Run ${{ matrix.task }} analysis"
yaml
jobs:
  parallel-claude:
    strategy:
      matrix:
        task: [lint, test, security]
    steps:
      - uses: actions/checkout@v4

      - name: Create worktree
        run: |
          git worktree add -b ${{ matrix.task }} ../work-${{ matrix.task }}

      - name: Run Claude task
        run: |
          cd ../work-${{ matrix.task }}
          claude -p "Run ${{ matrix.task }} analysis"

Execution Checklist

执行检查清单

StepCommandVerification
Create worktree
git worktree add -b <branch> <path> main
git worktree list
shows new entry
Navigate to worktree
cd <path>
pwd
shows worktree path
Run Claude task
claude "<task>"
Task completes successfully
Commit changes
git add . && git commit -m "message"
git log
shows commit
Return to main
cd <main-project>
pwd
shows main path
Merge changes
git merge <branch>
git log
shows merge
Remove worktree
git worktree remove <path>
git worktree list
excludes entry
Delete branch
git branch -d <branch>
git branch
excludes branch
Prune stale
git worktree prune
No stale references remain
步骤命令验证方式
创建工作树
git worktree add -b <branch> <path> main
git worktree list
显示新条目
进入工作树
cd <path>
pwd
显示工作树路径
运行Claude任务
claude "<task>"
任务成功完成
提交变更
git add . && git commit -m "message"
git log
显示提交记录
返回主目录
cd <main-project>
pwd
显示主项目路径
合并变更
git merge <branch>
git log
显示合并记录
删除工作树
git worktree remove <path>
git worktree list
中无该条目
删除分支
git branch -d <branch>
git branch
中无该分支
清理过期引用
git worktree prune
无过期引用残留

Metrics

指标

MetricTargetDescription
Worktree Creation Time<5sTime to create new worktree
Parallel Efficiency>80%CPU utilization across worktrees
Cleanup Rate100%Worktrees removed after merge
Branch Isolation100%No cross-worktree conflicts
Merge Success Rate>95%Clean merges without conflicts
指标目标说明
工作树创建时间<5秒创建新工作树的耗时
并行效率>80%工作树的CPU利用率
清理率100%合并后工作树均被删除
分支隔离度100%工作树间无交叉冲突
合并成功率>95%无冲突的干净合并

Related Skills

相关技能

  • repo-sync - Manage multiple repositories
  • sparc-workflow - Systematic development process
  • agent-orchestration - Multi-agent coordination

  • repo-sync - 管理多个仓库
  • sparc-workflow - 系统化开发流程
  • agent-orchestration - 多Agent协调

Version History

版本历史

  • 1.1.0 (2026-01-02): Added Quick Start, Error Handling table, Metrics, Execution Checklist, Best Practices Do/Don't, updated frontmatter with version/category/related_skills
  • 1.0.0 (2025-12-30): Initial release based on Claude Code best practices
  • 1.1.0 (2026-01-02):新增快速开始、错误处理表格、指标、执行检查清单、最佳实践的建议/禁忌,更新头信息包含版本/分类/相关技能
  • 1.0.0 (2025-12-30):基于Claude Code最佳实践的初始版本