git-worktree-manager

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Git Worktree Manager

Git Worktree 管理器

Tier: POWERFUL Category: Engineering / Developer Tooling Maintainer: Claude Skills Team
等级: 高级 分类: 工程/开发者工具 维护者: Claude Skills Team

Overview

概述

Manage parallel development workflows using Git worktrees with deterministic naming, automatic port allocation, environment file synchronization, dependency installation, and cleanup automation. Optimized for multi-agent workflows where each agent or terminal session owns an isolated worktree with its own ports, environment, and running services.
使用Git worktree管理并行开发工作流,支持确定性命名、自动端口分配、环境文件同步、依赖安装和自动化清理。针对多Agent工作流做了优化,每个Agent或终端会话都拥有独立的worktree,配备专属端口、运行环境和服务。

Keywords

关键词

git worktree, parallel development, branch isolation, port allocation, multi-agent development, worktree cleanup, Docker Compose worktree, concurrent branches
git worktree, 并行开发, 分支隔离, 端口分配, 多Agent开发, worktree清理, Docker Compose worktree, 并发分支

Core Capabilities

核心功能

1. Worktree Lifecycle Management

1. Worktree生命周期管理

  • Create worktrees from new or existing branches with deterministic naming
  • Copy .env files from main repo to new worktrees
  • Install dependencies based on lockfile detection
  • List all worktrees with status (clean/dirty, ahead/behind)
  • Safe cleanup with uncommitted change detection
  • 基于新分支或已有分支创建worktree,使用确定性命名规则
  • 从主仓库复制.env文件到新worktree
  • 根据锁文件检测结果自动安装依赖
  • 列出所有worktree及状态(干净/未提交、超前/落后版本)
  • 带未提交变更检测的安全清理机制

2. Port Allocation

2. 端口分配

  • Deterministic port assignment per worktree (base + index * stride)
  • Collision detection against running processes
  • Persistent port map in
    .worktree-ports.json
  • Docker Compose override generation for per-worktree ports
  • 每个worktree的确定性端口分配(基准端口 + 索引 * 步长)
  • 针对运行中进程的端口冲突检测
  • 端口映射持久化存储在
    .worktree-ports.json
    文件中
  • 自动生成Docker Compose覆盖配置,适配各worktree的端口

3. Multi-Agent Isolation

3. 多Agent隔离

  • One branch per worktree, one agent per worktree
  • No shared state between agent workspaces
  • Conflict-free parallel execution
  • Task ID mapping for traceability
  • 每个worktree对应一个分支,每个Agent对应一个worktree
  • Agent工作区间无共享状态
  • 无冲突的并行执行
  • 任务ID映射支持可追溯性

4. Cleanup Automation

4. 自动化清理

  • Stale worktree detection by age
  • Merged branch detection for safe removal
  • Dirty state warnings before deletion
  • Bulk cleanup with safety confirmations
  • 按闲置时长识别过时worktree
  • 检测已合并分支支持安全删除
  • 删除前的未提交状态警告
  • 带安全确认的批量清理

When to Use

适用场景

  • You need 2+ concurrent branches open with running dev servers
  • You want isolated environments for feature work, hotfixes, and PR review
  • Multiple AI agents need separate workspaces that do not interfere
  • Your current branch is blocked but a hotfix is urgent
  • You want automated cleanup instead of manual
    rm -rf
    operations
  • 需要同时打开2个及以上分支并运行开发服务器
  • 需要为功能开发、热修复、PR评审提供隔离环境
  • 多个AI Agent需要互不干扰的独立工作区
  • 当前分支开发被阻塞但有紧急热修复需求
  • 希望使用自动化清理代替手动
    rm -rf
    操作

Quick Start

快速开始

Create a Worktree

创建Worktree

bash
undefined
bash
undefined

Create worktree for a new feature branch

为新功能分支创建worktree

git worktree add ../wt-auth -b feature/new-auth main
git worktree add ../wt-auth -b feature/new-auth main

Create worktree from an existing branch

基于已有分支创建worktree

git worktree add ../wt-hotfix hotfix/fix-login
git worktree add ../wt-hotfix hotfix/fix-login

Create worktree in a dedicated directory

在指定目录创建worktree

git worktree add ~/worktrees/myapp-auth -b feature/auth origin/main
undefined
git worktree add ~/worktrees/myapp-auth -b feature/auth origin/main
undefined

List All Worktrees

列出所有Worktree

bash
git worktree list
bash
git worktree list

Output:

输出:

/Users/dev/myapp abc1234 [main]

/Users/dev/myapp abc1234 [main]

/Users/dev/wt-auth def5678 [feature/new-auth]

/Users/dev/wt-auth def5678 [feature/new-auth]

/Users/dev/wt-hotfix ghi9012 [hotfix/fix-login]

/Users/dev/wt-hotfix ghi9012 [hotfix/fix-login]

undefined
undefined

Remove a Worktree

删除Worktree

bash
undefined
bash
undefined

Safe removal (fails if there are uncommitted changes)

安全删除(存在未提交变更时会失败)

git worktree remove ../wt-auth
git worktree remove ../wt-auth

Force removal (discards uncommitted changes)

强制删除(丢弃未提交变更)

git worktree remove --force ../wt-auth
git worktree remove --force ../wt-auth

Prune stale metadata

清理过时元数据

git worktree prune
undefined
git worktree prune
undefined

Port Allocation Strategy

端口分配策略

Deterministic Port Assignment

确定性端口分配

Each worktree gets a block of ports based on its index:
Worktree Index    App Port    DB Port    Redis Port    API Port
────────────────────────────────────────────────────────────────
0 (main)          3000        5432       6379          8000
1 (wt-auth)       3010        5442       6389          8010
2 (wt-hotfix)     3020        5452       6399          8020
3 (wt-feature)    3030        5462       6409          8030
Formula:
port = base_port + (worktree_index * stride)
Default stride: 10
每个worktree根据其索引获得一段端口段:
Worktree 索引    应用端口    数据库端口    Redis端口    API端口
────────────────────────────────────────────────────────────────
0 (main)          3000        5432       6379          8000
1 (wt-auth)       3010        5442       6389          8010
2 (wt-hotfix)     3020        5452       6399          8020
3 (wt-feature)    3030        5462       6409          8030
计算公式:
端口 = 基准端口 + (worktree索引 * 步长)
默认步长:10

Port Map File

端口映射文件

Store the allocation in
.worktree-ports.json
at the worktree root:
json
{
  "worktree": "wt-auth",
  "branch": "feature/new-auth",
  "index": 1,
  "ports": {
    "app": 3010,
    "database": 5442,
    "redis": 6389,
    "api": 8010
  },
  "created": "2026-03-09T10:30:00Z"
}
分配结果存储在worktree根目录的
.worktree-ports.json
中:
json
{
  "worktree": "wt-auth",
  "branch": "feature/new-auth",
  "index": 1,
  "ports": {
    "app": 3010,
    "database": 5442,
    "redis": 6389,
    "api": 8010
  },
  "created": "2026-03-09T10:30:00Z"
}

Port Collision Detection

端口冲突检测

bash
undefined
bash
undefined

Check if a port is already in use

检查端口是否被占用

check_port() { local port=$1 if lsof -i :"$port" > /dev/null 2>&1; then echo "PORT $port is BUSY" return 1 else echo "PORT $port is FREE" return 0 fi }
check_port() { local port=$1 if lsof -i :"$port" > /dev/null 2>&1; then echo "PORT $port is BUSY" return 1 else echo "PORT $port is FREE" return 0 fi }

Check all ports for a worktree

检查某个worktree的所有端口

for port in 3010 5442 6389 8010; do check_port $port done
undefined
for port in 3010 5442 6389 8010; do check_port $port done
undefined

Full Worktree Setup Script

完整Worktree设置脚本

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

setup-worktree.sh — Create a fully prepared worktree

setup-worktree.sh — 创建完整配置的worktree

set -euo pipefail
BRANCH="${1:?Usage: setup-worktree.sh <branch-name> [base-branch]}" BASE="${2:-main}" WT_NAME="wt-$(echo "$BRANCH" | sed 's|.*/||' | tr '[:upper:]' '[:lower:]')" WT_PATH="../$WT_NAME" MAIN_REPO="$(git rev-parse --show-toplevel)"
echo "Creating worktree: $WT_PATH from $BASE..."
set -euo pipefail
BRANCH="${1:?Usage: setup-worktree.sh <branch-name> [base-branch]}" BASE="${2:-main}" WT_NAME="wt-$(echo "$BRANCH" | sed 's|.*/||' | tr '[:upper:]' '[:lower:]')" WT_PATH="../$WT_NAME" MAIN_REPO="$(git rev-parse --show-toplevel)"
echo "Creating worktree: $WT_PATH from $BASE..."

1. Create worktree

1. 创建worktree

if git rev-parse --verify "$BRANCH" > /dev/null 2>&1; then git worktree add "$WT_PATH" "$BRANCH" else git worktree add "$WT_PATH" -b "$BRANCH" "$BASE" fi
if git rev-parse --verify "$BRANCH" > /dev/null 2>&1; then git worktree add "$WT_PATH" "$BRANCH" else git worktree add "$WT_PATH" -b "$BRANCH" "$BASE" fi

2. Copy environment files

2. 复制环境文件

for envfile in .env .env.local .env.development; do if [ -f "$MAIN_REPO/$envfile" ]; then cp "$MAIN_REPO/$envfile" "$WT_PATH/$envfile" echo "Copied $envfile" fi done
for envfile in .env .env.local .env.development; do if [ -f "$MAIN_REPO/$envfile" ]; then cp "$MAIN_REPO/$envfile" "$WT_PATH/$envfile" echo "Copied $envfile" fi done

3. Allocate ports

3. 分配端口

WT_INDEX=$(git worktree list | grep -n "$WT_PATH" | cut -d: -f1) WT_INDEX=$((WT_INDEX - 1)) STRIDE=10
cat > "$WT_PATH/.worktree-ports.json" << EOF { "worktree": "$WT_NAME", "branch": "$BRANCH", "index": $WT_INDEX, "ports": { "app": $((3000 + WT_INDEX * STRIDE)), "database": $((5432 + WT_INDEX * STRIDE)), "redis": $((6379 + WT_INDEX * STRIDE)), "api": $((8000 + WT_INDEX * STRIDE)) } } EOF echo "Ports allocated (index $WT_INDEX)"
WT_INDEX=$(git worktree list | grep -n "$WT_PATH" | cut -d: -f1) WT_INDEX=$((WT_INDEX - 1)) STRIDE=10
cat > "$WT_PATH/.worktree-ports.json" << EOF { "worktree": "$WT_NAME", "branch": "$BRANCH", "index": $WT_INDEX, "ports": { "app": $((3000 + WT_INDEX * STRIDE)), "database": $((5432 + WT_INDEX * STRIDE)), "redis": $((6379 + WT_INDEX * STRIDE)), "api": $((8000 + WT_INDEX * STRIDE)) } } EOF echo "Ports allocated (index $WT_INDEX)"

4. Update .env with allocated ports

4. 用分配的端口更新.env文件

if [ -f "$WT_PATH/.env" ]; then APP_PORT=$((3000 + WT_INDEX * STRIDE)) DB_PORT=$((5432 + WT_INDEX * STRIDE)) sed -i.bak "s/APP_PORT=.*/APP_PORT=$APP_PORT/" "$WT_PATH/.env" sed -i.bak "s/:5432/:$DB_PORT/g" "$WT_PATH/.env" rm -f "$WT_PATH/.env.bak" echo "Updated .env with worktree ports" fi
if [ -f "$WT_PATH/.env" ]; then APP_PORT=$((3000 + WT_INDEX * STRIDE)) DB_PORT=$((5432 + WT_INDEX * STRIDE)) sed -i.bak "s/APP_PORT=.*/APP_PORT=$APP_PORT/" "$WT_PATH/.env" sed -i.bak "s/:5432/:$DB_PORT/g" "$WT_PATH/.env" rm -f "$WT_PATH/.env.bak" echo "Updated .env with worktree ports" fi

5. Install dependencies

5. 安装依赖

cd "$WT_PATH" if [ -f "pnpm-lock.yaml" ]; then pnpm install --frozen-lockfile elif [ -f "package-lock.json" ]; then npm ci elif [ -f "yarn.lock" ]; then yarn install --frozen-lockfile elif [ -f "requirements.txt" ]; then pip install -r requirements.txt elif [ -f "go.mod" ]; then go mod download fi
echo "" echo "Worktree ready: $WT_PATH" echo "Branch: $BRANCH" echo "App port: $((3000 + WT_INDEX * STRIDE))" echo "" echo "Next: cd $WT_PATH && pnpm dev"
undefined
cd "$WT_PATH" if [ -f "pnpm-lock.yaml" ]; then pnpm install --frozen-lockfile elif [ -f "package-lock.json" ]; then npm ci elif [ -f "yarn.lock" ]; then yarn install --frozen-lockfile elif [ -f "requirements.txt" ]; then pip install -r requirements.txt elif [ -f "go.mod" ]; then go mod download fi
echo "" echo "Worktree ready: $WT_PATH" echo "Branch: $BRANCH" echo "App port: $((3000 + WT_INDEX * STRIDE))" echo "" echo "Next: cd $WT_PATH && pnpm dev"
undefined

Docker Compose Per-Worktree

适配Worktree的Docker Compose配置

yaml
undefined
yaml
undefined

docker-compose.worktree.yml — override for worktree-specific ports

docker-compose.worktree.yml — worktree专属端口的覆盖配置

Usage: docker compose -f docker-compose.yml -f docker-compose.worktree.yml up

用法: docker compose -f docker-compose.yml -f docker-compose.worktree.yml up

services: postgres: ports: - "${DB_PORT:-5432}:5432" environment: POSTGRES_DB: "myapp_${WT_NAME:-main}"
redis: ports: - "${REDIS_PORT:-6379}:6379"
app: ports: - "${APP_PORT:-3000}:3000" environment: DATABASE_URL: "postgresql://dev:dev@postgres:5432/myapp_${WT_NAME:-main}"

Launch with worktree-specific ports:

```bash
DB_PORT=5442 REDIS_PORT=6389 APP_PORT=3010 WT_NAME=auth \
  docker compose -f docker-compose.yml -f docker-compose.worktree.yml up -d
services: postgres: ports: - "${DB_PORT:-5432}:5432" environment: POSTGRES_DB: "myapp_${WT_NAME:-main}"
redis: ports: - "${REDIS_PORT:-6379}:6379"
app: ports: - "${APP_PORT:-3000}:3000" environment: DATABASE_URL: "postgresql://dev:dev@postgres:5432/myapp_${WT_NAME:-main}"

使用worktree专属端口启动服务:

```bash
DB_PORT=5442 REDIS_PORT=6389 APP_PORT=3010 WT_NAME=auth \
  docker compose -f docker-compose.yml -f docker-compose.worktree.yml up -d

Cleanup Automation

自动化清理

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

cleanup-worktrees.sh — Safe worktree cleanup

cleanup-worktrees.sh — 安全清理worktree

set -euo pipefail
STALE_DAYS="${1:-14}" DRY_RUN="${2:-true}"
echo "Scanning worktrees (stale threshold: ${STALE_DAYS} days)..." echo ""
git worktree list --porcelain | while read -r line; do case "$line" in worktree\ *) WT_PATH="${line#worktree }" ;; branch\ *) BRANCH="${line#branch refs/heads/}" # Skip main worktree if [ "$WT_PATH" = "$(git rev-parse --show-toplevel)" ]; then continue fi
  # Check if branch is merged
  MERGED=""
  if git branch --merged main | grep -q "$BRANCH" 2>/dev/null; then
    MERGED=" [MERGED]"
  fi

  # Check for uncommitted changes
  DIRTY=""
  if [ -d "$WT_PATH" ]; then
    cd "$WT_PATH"
    if [ -n "$(git status --porcelain)" ]; then
      DIRTY=" [DIRTY - has uncommitted changes]"
    fi
    cd - > /dev/null
  fi

  # Check age
  if [ -d "$WT_PATH" ]; then
    AGE_DAYS=$(( ($(date +%s) - $(stat -f %m "$WT_PATH" 2>/dev/null || stat -c %Y "$WT_PATH" 2>/dev/null)) / 86400 ))
    STALE=""
    if [ "$AGE_DAYS" -gt "$STALE_DAYS" ]; then
      STALE=" [STALE: ${AGE_DAYS} days old]"
    fi
  fi

  echo "$WT_PATH ($BRANCH)$MERGED$DIRTY$STALE"

  if [ -n "$MERGED" ] && [ -z "$DIRTY" ] && [ "$DRY_RUN" = "false" ]; then
    echo "  -> Removing merged clean worktree..."
    git worktree remove "$WT_PATH"
  fi
  ;;
esac done
echo "" git worktree prune echo "Done. Run with 'false' as second arg to actually remove."
undefined
set -euo pipefail
STALE_DAYS="${1:-14}" DRY_RUN="${2:-true}"
echo "Scanning worktrees (stale threshold: ${STALE_DAYS} days)..." echo ""
git worktree list --porcelain | while read -r line; do case "$line" in worktree\ *) WT_PATH="${line#worktree }" ;; branch\ *) BRANCH="${line#branch refs/heads/}" # 跳过主仓库worktree if [ "$WT_PATH" = "$(git rev-parse --show-toplevel)" ]; then continue fi
  # 检查分支是否已合并
  MERGED=""
  if git branch --merged main | grep -q "$BRANCH" 2>/dev/null; then
    MERGED=" [MERGED]"
  fi

  # 检查未提交变更
  DIRTY=""
  if [ -d "$WT_PATH" ]; then
    cd "$WT_PATH"
    if [ -n "$(git status --porcelain)" ]; then
      DIRTY=" [DIRTY - has uncommitted changes]"
    fi
    cd - > /dev/null
  fi

  # 检查闲置时长
  if [ -d "$WT_PATH" ]; then
    AGE_DAYS=$(( ($(date +%s) - $(stat -f %m "$WT_PATH" 2>/dev/null || stat -c %Y "$WT_PATH" 2>/dev/null)) / 86400 ))
    STALE=""
    if [ "$AGE_DAYS" -gt "$STALE_DAYS" ]; then
      STALE=" [STALE: ${AGE_DAYS} days old]"
    fi
  fi

  echo "$WT_PATH ($BRANCH)$MERGED$DIRTY$STALE"

  if [ -n "$MERGED" ] && [ -z "$DIRTY" ] && [ "$DRY_RUN" = "false" ]; then
    echo "  -> Removing merged clean worktree..."
    git worktree remove "$WT_PATH"
  fi
  ;;
esac done
echo "" git worktree prune echo "Done. Run with 'false' as second arg to actually remove."
undefined

Multi-Agent Workflow Pattern

多Agent工作流模式

When running multiple AI agents (Claude Code, Cursor, Copilot) on the same repo:
Agent Assignment:
───────────────────────────────────────────────────
Agent 1 (Claude Code)  → wt-feature-auth   (port 3010)
Agent 2 (Cursor)       → wt-feature-billing (port 3020)
Agent 3 (Copilot)      → wt-bugfix-login   (port 3030)
Main repo              → integration (main) (port 3000)
───────────────────────────────────────────────────

Rules:
- Each agent works ONLY in its assigned worktree
- No agent modifies another agent's worktree
- Integration happens via PRs to main, not direct merges
- Port conflicts are impossible due to deterministic allocation
当在同一个仓库运行多个AI Agent(Claude Code、Cursor、Copilot)时:
Agent 分配:
───────────────────────────────────────────────────
Agent 1 (Claude Code)  → wt-feature-auth   (port 3010)
Agent 2 (Cursor)       → wt-feature-billing (port 3020)
Agent 3 (Copilot)      → wt-bugfix-login   (port 3030)
主仓库                  → integration (main) (port 3000)
───────────────────────────────────────────────────

规则:
- 每个Agent仅在分配的worktree中工作
- 禁止Agent修改其他Agent的worktree
- 集成通过向main分支提交PR完成,不直接合并
- 确定性端口分配完全避免端口冲突

Decision Matrix

决策矩阵

ScenarioAction
Need isolated dev server for a featureCreate a new worktree
Quick diff review of a branch
git diff
in current tree (no worktree needed)
Hotfix while feature branch is dirtyCreate dedicated hotfix worktree
Bug triage with reproduction branchTemporary worktree, cleanup same day
PR review with running codeWorktree at PR branch, run tests
Multiple agents on same repoOne worktree per agent
场景操作
需要为功能提供隔离的开发服务器创建新worktree
快速对比分支差异在当前仓库执行
git diff
(无需创建worktree)
功能分支有未提交变更时需要处理热修复创建专属热修复worktree
使用复现分支排查Bug创建临时worktree,当日清理
需要运行代码的PR评审基于PR分支创建worktree,运行测试
多个Agent在同一个仓库工作每个Agent分配一个独立worktree

Validation Checklist

校验清单

After creating a worktree, verify:
  1. git worktree list
    shows the expected path and branch
  2. .worktree-ports.json
    exists with unique port assignments
  3. .env
    files are present and contain worktree-specific ports
  4. pnpm install
    (or equivalent) completed without errors
  5. Dev server starts on the allocated port
  6. Database connects on the allocated DB port
  7. No port conflicts with other worktrees or services
创建worktree后,请验证以下内容:
  1. git worktree list
    显示预期的路径和分支
  2. .worktree-ports.json
    存在且包含唯一的端口分配
  3. .env
    文件存在且包含worktree专属端口
  4. pnpm install
    (或对应包管理器命令)执行无报错
  5. 开发服务器在分配的端口正常启动
  6. 数据库在分配的端口正常连接
  7. 与其他worktree或服务无端口冲突

Common Pitfalls

常见陷阱

  • Creating worktrees inside the main repo directory — always use
    ../wt-name
    to keep them alongside
  • Reusing localhost:3000 across all branches — causes port conflicts; use deterministic allocation
  • Sharing one DATABASE_URL across worktrees — each needs its own database or schema
  • Removing a worktree with uncommitted changes — always check dirty state before removal
  • Forgetting to prune after branch deletion — run
    git worktree prune
    to clean metadata
  • Not updating .env ports after worktree creation — the setup script should handle this automatically
  • 在主仓库目录内创建worktree — 始终使用
    ../wt-name
    路径将worktree放在主仓库同级目录
  • 所有分支都复用localhost:3000 — 会导致端口冲突,使用确定性分配方案
  • 多个worktree共享同一个DATABASE_URL — 每个worktree需要独立的数据库或schema
  • 删除有未提交变更的worktree — 删除前始终检查dirty状态
  • 分支删除后忘记清理元数据 — 运行
    git worktree prune
    清理冗余元数据
  • 创建worktree后忘记更新.env端口 — 设置脚本会自动处理该步骤

Best Practices

最佳实践

  1. One branch per worktree, one agent per worktree — never share
  2. Keep worktrees short-lived — remove after the branch is merged
  3. Deterministic naming — use
    wt-<topic>
    pattern for easy identification
  4. Persist port mappings — store in
    .worktree-ports.json
    , not in memory
  5. Run cleanup weekly — scan for stale and merged-branch worktrees
  6. Include worktree path in terminal title — prevents wrong-window commits
  7. Never force-remove dirty worktrees — unless changes are intentionally discarded
  1. 每个worktree对应一个分支,每个Agent对应一个worktree — 禁止共享
  2. 保持worktree短生命周期 — 分支合并后立即删除
  3. 确定性命名规则 — 使用
    wt-<主题>
    前缀便于识别
  4. 持久化端口映射 — 存储在
    .worktree-ports.json
    中,不要仅保存在内存
  5. 每周运行清理任务 — 扫描过时和已合并分支的worktree
  6. 在终端标题中包含worktree路径 — 避免在错误的窗口提交代码
  7. 不要强制删除有未提交变更的worktree — 除非确认要丢弃变更

Troubleshooting

问题排查

ProblemCauseSolution
fatal: '<path>' is already checked out
Branch is already active in another worktreeUse
git worktree list
to find where the branch is checked out, then switch to a different branch or remove the existing worktree first
Port conflict despite deterministic allocationA non-worktree process is occupying the assigned portRun
lsof -i :<port>
to identify the process, terminate it or adjust the stride/base in the port allocation formula
.env
file missing after worktree creation
Setup script was not run or
.env
does not exist in the main repo
Copy
.env
manually from the main repo root, or re-run
setup-worktree.sh
which handles env file copying
git worktree prune
reports nothing but stale paths remain
Worktree directory was deleted manually without
git worktree remove
Run
git worktree prune
to clean orphaned metadata, then verify with
git worktree list
Dependencies fail to install in new worktreeLockfile references a private registry or cache not available in the worktree pathEnsure
.npmrc
,
.yarnrc.yml
, or pip config files are copied alongside
.env
during setup
Docker Compose services start on wrong portsThe
docker-compose.worktree.yml
override was not included in the compose command
Always pass both files:
docker compose -f docker-compose.yml -f docker-compose.worktree.yml up
Worktree shows as dirty immediately after creationUntracked files from
.env
copy or generated
.worktree-ports.json
Add
.worktree-ports.json
and copied env files to
.gitignore
in the project
问题原因解决方案
fatal: '<path>' is already checked out
分支已在另一个worktree中激活使用
git worktree list
找到分支所在的worktree,切换到其他分支或先删除已有worktree
尽管使用确定性分配仍出现端口冲突非worktree进程占用了分配的端口运行
lsof -i :<端口号>
识别占用进程,终止进程或调整端口分配公式的步长/基准端口
创建worktree后
.env
文件缺失
未运行设置脚本或主仓库不存在
.env
文件
从主仓库根目录手动复制
.env
,或重新运行
setup-worktree.sh
,脚本会自动处理环境文件复制
git worktree prune
无输出但仍存在过时路径
未使用
git worktree remove
直接手动删除了worktree目录
运行
git worktree prune
清理孤立元数据,之后用
git worktree list
验证
新worktree中依赖安装失败锁文件引用了worktree路径下无法访问的私有镜像源或缓存确保设置过程中
.npmrc
.yarnrc.yml
或pip配置文件和
.env
一起被复制
Docker Compose服务启动端口错误compose命令未包含
docker-compose.worktree.yml
覆盖配置
始终传入两个配置文件:
docker compose -f docker-compose.yml -f docker-compose.worktree.yml up
创建后worktree立即显示为dirty复制的
.env
文件或生成的
.worktree-ports.json
是未跟踪文件
.worktree-ports.json
和复制的环境文件添加到项目的
.gitignore

Success Criteria

成功指标

  • Zero port conflicts across all active worktrees measured by
    lsof
    checks returning no collisions after setup
  • Worktree creation under 60 seconds including dependency installation for projects with warm package caches
  • 100% env parity between main repo and worktrees verified by diffing
    .env
    keys (values may differ for ports)
  • Stale worktree count stays at zero when cleanup automation runs on a weekly schedule with a 14-day threshold
  • No cross-worktree interference validated by running concurrent dev servers in 3+ worktrees simultaneously without failures
  • Branch-to-worktree traceability maintained via
    .worktree-ports.json
    present in every active worktree with correct metadata
  • Cleanup safety rate of 100% meaning no worktree with uncommitted changes is ever removed without explicit
    --force
    confirmation
  • 零端口冲突:所有活跃worktree设置完成后,
    lsof
    检查无端口冲突
  • worktree创建耗时<60秒:包缓存预热的项目,创建包含依赖安装的完整worktree耗时低于60秒
  • 100%环境一致性:主仓库和worktree的
    .env
    键完全一致(端口等值可不同)
  • 过时worktree数为0:按14天阈值每周运行自动化清理后,无过时worktree
  • 无跨worktree干扰:同时在3个及以上worktree运行开发服务,无任何故障
  • 分支到worktree可追溯:所有活跃worktree都包含
    .worktree-ports.json
    ,元数据准确
  • 清理安全率100%:无未提交变更的worktree在未显式使用
    --force
    确认的情况下被删除

Scope & Limitations

适用范围与限制

This skill covers:
  • Git worktree lifecycle: creation, listing, status inspection, and removal
  • Deterministic port allocation and collision avoidance for parallel dev servers
  • Environment file synchronization and Docker Compose override patterns
  • Multi-agent workspace isolation strategies and cleanup automation
This skill does NOT cover:
  • Git branching strategies or merge conflict resolution (see
    pr-review-expert
    and
    release-manager
    )
  • Secret rotation, vault integration, or credential management (see
    env-secrets-manager
    )
  • CI/CD pipeline configuration or automated test orchestration (see
    ci-cd-pipeline-builder
    )
  • Monorepo package management, workspace linking, or cross-package dependency resolution (see
    monorepo-navigator
    )
本技能覆盖:
  • Git worktree全生命周期:创建、列表、状态检查、删除
  • 并行开发服务器的确定性端口分配和冲突规避
  • 环境文件同步和Docker Compose覆盖配置模式
  • 多Agent工作区隔离策略和自动化清理
本技能不覆盖:
  • Git分支策略或合并冲突解决(参见
    pr-review-expert
    release-manager
  • 密钥轮换、Vault集成或凭证管理(参见
    env-secrets-manager
  • CI/CD流水线配置或自动化测试编排(参见
    ci-cd-pipeline-builder
  • Monorepo包管理、工作区链接或跨包依赖解析(参见
    monorepo-navigator

Integration Points

集成点

SkillIntegrationData Flow
env-secrets-manager
Worktree setup copies
.env
files that contain secrets managed by this skill
.env
files flow from main repo to each worktree; secret references remain consistent across all copies
ci-cd-pipeline-builder
CI pipelines can spin up worktrees for parallel test matrix executionPipeline config triggers
setup-worktree.sh
per matrix job; port allocation prevents service collisions
release-manager
Release branches get dedicated worktrees for stabilization while feature work continuesRelease worktree is created from the release branch; merged status drives cleanup automation
monorepo-navigator
In monorepo setups, worktrees must respect package boundaries and shared dependenciesWorktree creation inherits the monorepo root lockfile; package-level dev servers use allocated port blocks
pr-review-expert
PR reviews can be performed in isolated worktrees with running code for manual validationReviewer creates a worktree at the PR branch, runs the dev server on allocated ports, and removes after review
tech-debt-tracker
Stale worktrees and abandoned branches surface as tech debt indicatorsCleanup script output feeds into debt tracking; worktree age and merge status inform priority scores
技能集成方式数据流
env-secrets-manager
Worktree设置脚本复制的
.env
文件包含该技能管理的密钥
.env
文件从主仓库流向每个worktree,所有副本的密钥引用保持一致
ci-cd-pipeline-builder
CI流水线可创建worktree执行并行测试矩阵流水线配置为每个矩阵任务触发
setup-worktree.sh
,端口分配避免服务冲突
release-manager
发布分支获得专属worktree用于稳定性验证,同时可继续功能开发从发布分支创建发布worktree,合并状态驱动自动化清理
monorepo-navigator
Monorepo场景下,worktree需遵守包边界和共享依赖规则Worktree创建继承Monorepo根目录锁文件,包级开发服务使用分配的端口段
pr-review-expert
PR评审可在隔离worktree中运行代码进行人工验证评审者基于PR分支创建worktree,在分配端口运行开发服务器,评审完成后删除
tech-debt-tracker
过时worktree和废弃分支作为技术债务指标清理脚本输出输入到债务跟踪系统,worktree年龄和合并状态用于计算优先级分数