git-worktrees

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Git Worktrees

Git Worktrees

Description

说明

Git Worktrees enables parallel development by maintaining multiple checked-out branches simultaneously in separate directories. Instead of stashing changes and switching branches, the agent creates isolated worktrees for each task, providing clean test baselines and eliminating context-switching overhead. Each worktree is a fully independent workspace tied to its own branch.
This skill is essential for subagent-driven development, where multiple agents work on different tasks concurrently. Without worktrees, agents would clobber each other's uncommitted changes. With worktrees, each agent operates in its own directory with its own branch, and the orchestrator merges completed work back into the main line.
Worktrees also provide clean baselines for testing. When you need to verify that tests pass on a clean checkout—without build artifacts, local config, or uncommitted changes—a fresh worktree gives you exactly that. The worktree lifecycle is managed explicitly: create when a task starts, verify when it completes, and prune when it merges.
Git Worktrees 通过在独立目录中同时维护多个已检出的分支,实现并行开发。无需暂存更改并切换分支,智能体可为每个任务创建独立的工作树,提供干净的测试基线并消除上下文切换的开销。每个工作树都是一个完全独立的工作区,绑定到其专属分支。
该技能对于子智能体驱动的开发至关重要,在这类开发场景中,多个智能体同时处理不同任务。如果没有工作树,智能体之间会互相覆盖未提交的更改。借助工作树,每个智能体可在自己的目录和分支中操作,编排器会将完成的工作合并回主线分支。
工作树还能为测试提供干净的基线。当你需要验证测试在干净检出环境下是否通过——不受构建产物、本地配置或未提交更改影响时,全新的工作树正好能满足需求。工作树的生命周期是显式管理的:任务开始时创建,完成时验证,合并后清理。

Use When

适用场景

  • Multiple tasks must be developed in parallel without interference
  • Subagents need isolated filesystems for concurrent work
  • You need a clean checkout to run tests without local artifacts
  • Hotfix work must happen while a feature branch is in progress
  • Best-of-N implementations need separate workspaces
  • You want to compare behavior across branches side by side
  • 多个任务需并行开发且互不干扰
  • 子智能体需要独立文件系统以同时工作
  • 你需要干净的检出环境来运行测试,不受本地产物影响
  • 开发特性分支时需同时处理紧急修复
  • 多方案对比实现需要独立工作区
  • 你想要并排对比不同分支的行为

How It Works

工作原理

mermaid
graph TD
    A[Main Repo] --> B["git worktree add ../task-1 -b feature/task-1"]
    A --> C["git worktree add ../task-2 -b feature/task-2"]
    A --> D["git worktree add ../hotfix -b hotfix/urgent"]
    B --> E[Agent 1 works in ../task-1]
    C --> F[Agent 2 works in ../task-2]
    D --> G[Agent 3 works in ../hotfix]
    E --> H[PR + Merge]
    F --> H
    G --> H
    H --> I["git worktree remove ../task-1"]
    H --> J["git worktree remove ../task-2"]
    H --> K["git worktree remove ../hotfix"]
Each worktree is a real directory on disk with its own checked-out branch. Changes in one worktree do not affect others. The
.git
metadata is shared, so branch operations (push, fetch, log) work normally from any worktree.
mermaid
graph TD
    A[Main Repo] --> B["git worktree add ../task-1 -b feature/task-1"]
    A --> C["git worktree add ../task-2 -b feature/task-2"]
    A --> D["git worktree add ../hotfix -b hotfix/urgent"]
    B --> E[Agent 1 works in ../task-1]
    C --> F[Agent 2 works in ../task-2]
    D --> G[Agent 3 works in ../hotfix]
    E --> H[PR + Merge]
    F --> H
    G --> H
    H --> I["git worktree remove ../task-1"]
    H --> J["git worktree remove ../task-2"]
    H --> K["git worktree remove ../hotfix"]
每个工作树都是磁盘上的真实目录,拥有自己的已检出分支。一个工作树中的更改不会影响其他工作树。
.git
元数据是共享的,因此分支操作(推送、拉取、查看日志)可从任意工作树正常执行。

Implementation

实现示例

bash
undefined
bash
undefined

Create a worktree for a new feature

Create a worktree for a new feature

git worktree add ../feature-auth -b feature/user-auth cd ../feature-auth npm install # Dependencies may differ per branch
git worktree add ../feature-auth -b feature/user-auth cd ../feature-auth npm install # Dependencies may differ per branch

List active worktrees

List active worktrees

git worktree list
git worktree list

/home/user/project abc1234 [main]

/home/user/project abc1234 [main]

/home/user/feature-auth def5678 [feature/user-auth]

/home/user/feature-auth def5678 [feature/user-auth]

Run tests in a clean worktree

Run tests in a clean worktree

git worktree add ../clean-test --detach HEAD cd ../clean-test npm ci && npm test cd ../project git worktree remove ../clean-test
git worktree add ../clean-test --detach HEAD cd ../clean-test npm ci && npm test cd ../project git worktree remove ../clean-test

Prune stale worktrees (after branch deletion)

Prune stale worktrees (after branch deletion)

git worktree prune

```python
class WorktreeManager:
    def __init__(self, repo_root):
        self.repo_root = repo_root
        self.worktree_base = Path(repo_root).parent

    def create(self, task_name, base_branch="main"):
        branch = f"feature/{task_name}"
        path = self.worktree_base / task_name
        subprocess.run(
            ["git", "worktree", "add", str(path), "-b", branch, base_branch],
            cwd=self.repo_root, check=True
        )
        return WorktreeContext(path, branch)

    def remove(self, task_name):
        path = self.worktree_base / task_name
        subprocess.run(
            ["git", "worktree", "remove", str(path)],
            cwd=self.repo_root, check=True
        )

    def list_active(self):
        result = subprocess.run(
            ["git", "worktree", "list", "--porcelain"],
            cwd=self.repo_root, capture_output=True, text=True
        )
        return self.parse_worktree_list(result.stdout)
git worktree prune

```python
class WorktreeManager:
    def __init__(self, repo_root):
        self.repo_root = repo_root
        self.worktree_base = Path(repo_root).parent

    def create(self, task_name, base_branch="main"):
        branch = f"feature/{task_name}"
        path = self.worktree_base / task_name
        subprocess.run(
            ["git", "worktree", "add", str(path), "-b", branch, base_branch],
            cwd=self.repo_root, check=True
        )
        return WorktreeContext(path, branch)

    def remove(self, task_name):
        path = self.worktree_base / task_name
        subprocess.run(
            ["git", "worktree", "remove", str(path)],
            cwd=self.repo_root, check=True
        )

    def list_active(self):
        result = subprocess.run(
            ["git", "worktree", "list", "--porcelain"],
            cwd=self.repo_root, capture_output=True, text=True
        )
        return self.parse_worktree_list(result.stdout)

Best Practices

最佳实践

  • Always create worktrees from the main repository, not from another worktree
  • Run
    npm ci
    or equivalent in each new worktree—
    node_modules
    are not shared
  • Remove worktrees promptly after merging to avoid disk bloat
  • Use
    git worktree prune
    periodically to clean up stale references
  • Name worktree directories descriptively to match their branch purpose
  • Never checkout the same branch in two worktrees simultaneously
  • 始终从主仓库创建工作树,而非从其他工作树创建
  • 在每个新工作树中运行
    npm ci
    或等效命令——
    node_modules
    不会共享
  • 合并后及时删除工作树,避免磁盘空间浪费
  • 定期使用
    git worktree prune
    清理过期引用
  • 为工作树目录命名时要清晰描述其分支用途
  • 切勿同时在两个工作树中检出同一个分支

Platform Compatibility

平台兼容性

PlatformSupportNotes
CursorFullbest-of-n-runner uses worktrees natively
VS CodeFullMulti-root workspace support
WindsurfFullShell-based worktree management
Claude CodeFullDirect git access
ClineFullTerminal git commands
aiderFullWorks from any worktree directory
PlatformSupportNotes
CursorFullbest-of-n-runner 原生支持工作树
VS CodeFull支持多根工作区
WindsurfFull基于Shell的工作树管理
Claude CodeFull直接访问Git
ClineFull终端Git命令
aiderFull可在任意工作树目录中使用

Related Skills

相关技能

  • Subagent-Driven Development - Parallel task dispatch that relies on worktrees for filesystem isolation between agents
  • Executing Plans - Plan execution with rollback that uses worktrees for clean verification baselines
  • Code Review - Pre-merge quality gate applied to each worktree branch before merging
  • 子智能体驱动开发 - 并行任务分发依赖工作树实现智能体间的文件系统隔离
  • 计划执行 - 带回滚的计划执行使用工作树作为干净的验证基线
  • 代码评审 - 合并前对每个工作树分支应用质量检查门

Keywords

关键词

git-worktrees
parallel-development
isolated-workspace
clean-baseline
concurrent-branches
subagent-isolation
best-of-n
branch-management

© 2026 googleadsagent.ai™ | Agent Skills™ | MIT License
git-worktrees
parallel-development
isolated-workspace
clean-baseline
concurrent-branches
subagent-isolation
best-of-n
branch-management

© 2026 googleadsagent.ai™ | Agent Skills™ | MIT License