Git Worktree Manager
Tier: POWERFUL
Category: Engineering
Domain: Parallel Development & Branch Isolation
Overview
Use this skill to run parallel feature work safely with Git worktrees. It standardizes branch isolation, port allocation, environment sync, and cleanup so each worktree behaves like an independent local app without stepping on another branch.
This skill is optimized for multi-agent workflows where each agent or terminal session owns one worktree.
Core Capabilities
- - Create worktrees from new or existing branches with deterministic naming
- Auto-allocate non-conflicting ports per worktree and persist assignments
- Copy local environment files (
.env*) from main repo to new worktree - Optionally install dependencies based on lockfile detection
- Detect stale worktrees and uncommitted changes before cleanup
- Identify merged branches and safely remove outdated worktrees
When to Use
- - You need 2+ concurrent branches open locally
- You want isolated dev servers for feature, hotfix, and PR validation
- You are working with multiple agents that must not share a branch
- Your current branch is blocked but you need to ship a quick fix now
- You want repeatable cleanup instead of ad-hoc
rm -rf operations
Key Workflows
1. Create a Fully-Prepared Worktree
- 1. Pick a branch name and worktree name.
- Run the manager script (creates branch if missing).
- Review generated port map.
- Start app using allocated ports.
CODEBLOCK0
If you use JSON automation input:
CODEBLOCK1
2. Run Parallel Sessions
Recommended convention:
- - Main repo: integration branch (
main/develop) on default port - Worktree A: feature branch + offset ports
- Worktree B: hotfix branch + next offset
Each worktree contains .worktree-ports.json with assigned ports.
3. Cleanup with Safety Checks
- 1. Scan all worktrees and stale age.
- Inspect dirty trees and branch merge status.
- Remove only merged + clean worktrees, or force explicitly.
CODEBLOCK2
4. Docker Compose Pattern
Use per-worktree override files mapped from allocated ports. The script outputs a deterministic port map; apply it to docker-compose.worktree.yml.
See docker-compose-patterns.md for concrete templates.
5. Port Allocation Strategy
Default strategy is base + (index * stride) with collision checks:
- - App: INLINECODE7
- Postgres: INLINECODE8
- Redis: INLINECODE9
- Stride: INLINECODE10
See port-allocation-strategy.md for the full strategy and edge cases.
Script Interfaces
- Create/list worktrees
- Allocate/persist ports
- Copy
.env* files
- Optional dependency installation
- Stale detection by age
- Dirty-state detection
- Merged-branch detection
- Optional safe removal
Both tools support stdin JSON and --input file mode for automation pipelines.
Common Pitfalls
- 1. Creating worktrees inside the main repo directory
- Reusing
localhost:3000 across all branches - Sharing one database URL across isolated feature branches
- Removing a worktree with uncommitted changes
- Forgetting to prune old metadata after branch deletion
- Assuming merged status without checking against the target branch
Best Practices
- 1. One branch per worktree, one agent per worktree.
- Keep worktrees short-lived; remove after merge.
- Use a deterministic naming pattern (
wt-<topic>). - Persist port mappings in file, not memory or terminal notes.
- Run cleanup scan weekly in active repos.
- Use
--format json for machine flows and --format text for human review. - Never force-remove dirty worktrees unless changes are intentionally discarded.
Validation Checklist
Before claiming setup complete:
- 1.
git worktree list shows expected path + branch. - INLINECODE20 exists and contains unique ports.
- INLINECODE21 files copied successfully (if present in source repo).
- Dependency install command exits with code
0 (if enabled). - Cleanup scan reports no unintended stale dirty trees.
References
Decision Matrix
Use this quick selector before creating a new worktree:
- - Need isolated dependencies and server ports -> create a new worktree
- Need only a quick local diff review -> stay on current tree
- Need hotfix while feature branch is dirty -> create dedicated hotfix worktree
- Need ephemeral reproduction branch for bug triage -> create temporary worktree and cleanup same day
Operational Checklist
Before Creation
- 1. Confirm main repo has clean baseline or intentional WIP commits.
- Confirm target branch naming convention.
- Confirm required base branch exists (
main/develop). - Confirm no reserved local ports are already occupied by non-repo services.
After Creation
- 1. Verify
git status branch matches expected branch. - Verify
.worktree-ports.json exists. - Verify app boots on allocated app port.
- Verify DB and cache endpoints target isolated ports.
Before Removal
- 1. Verify branch has upstream and is merged when intended.
- Verify no uncommitted files remain.
- Verify no running containers/processes depend on this worktree path.
CI and Team Integration
- - Use worktree path naming that maps to task ID (
wt-1234-auth). - Include the worktree path in terminal title to avoid wrong-window commits.
- In automated setups, persist creation metadata in CI artifacts/logs.
- Trigger cleanup report in scheduled jobs and post summary to team channel.
Failure Recovery
- - If
git worktree add fails due to existing path: inspect path, do not overwrite. - If dependency install fails: keep worktree created, mark status and continue manual recovery.
- If env copy fails: continue with warning and explicit missing file list.
- If port allocation collides with external service: rerun with adjusted base ports.
Git Worktree 管理器
层级: 强大
类别: 工程
领域: 并行开发与分支隔离
概述
使用此技能可安全地通过 Git worktree 并行开展功能开发工作。它标准化了分支隔离、端口分配、环境同步和清理流程,使每个 worktree 的行为如同独立的本地应用,而不会干扰其他分支。
此技能针对多代理工作流进行了优化,其中每个代理或终端会话拥有一个 worktree。
核心能力
- - 从新分支或现有分支创建 worktree,并采用确定性命名
- 为每个 worktree 自动分配无冲突端口,并持久化分配结果
- 将本地环境文件(.env*)从主仓库复制到新的 worktree
- 可选地根据锁文件检测结果安装依赖
- 在清理前检测过时的 worktree 和未提交的更改
- 识别已合并的分支并安全移除过时的 worktree
使用时机
- - 你需要在本地同时打开 2 个或更多并发分支
- 你需要为功能开发、热修复和 PR 验证提供独立的开发服务器
- 你正在与多个代理协作,且这些代理不能共享同一个分支
- 当前分支被阻塞,但你需要立即发布一个快速修复
- 你希望进行可重复的清理,而不是临时执行 rm -rf 操作
关键工作流
1. 创建一个完全准备好的 Worktree
- 1. 选择一个分支名称和 worktree 名称。
- 运行管理器脚本(如果分支不存在则创建)。
- 查看生成的端口映射。
- 使用分配的端口启动应用。
bash
python scripts/worktree_manager.py \
--repo . \
--branch feature/new-auth \
--name wt-auth \
--base-branch main \
--install-deps \
--format text
如果你使用 JSON 自动化输入:
bash
cat config.json | python scripts/worktree_manager.py --format json
或
python scripts/worktree_manager.py --input config.json --format json
2. 运行并行会话
推荐约定:
- - 主仓库:集成分支(main/develop)使用默认端口
- Worktree A:功能分支 + 偏移端口
- Worktree B:热修复分支 + 下一个偏移端口
每个 worktree 包含 .worktree-ports.json 文件,其中记录了分配的端口。
3. 带安全检查的清理
- 1. 扫描所有 worktree 及其过期时间。
- 检查脏树状态和分支合并状态。
- 仅移除已合并且干净的 worktree,或显式强制移除。
bash
python scripts/worktree_cleanup.py --repo . --stale-days 14 --format text
python scripts/worktree_cleanup.py --repo . --remove-merged --format text
4. Docker Compose 模式
使用基于分配端口映射的每个 worktree 覆盖文件。脚本输出确定性的端口映射;将其应用到 docker-compose.worktree.yml。
具体模板请参见 docker-compose-patterns.md。
5. 端口分配策略
默认策略为 base + (index * stride),并带有冲突检查:
- - 应用:3000
- PostgreSQL:5432
- Redis:6379
- 步长:10
完整策略及边界情况请参见 port-allocation-strategy.md。
脚本接口
- - python scripts/worktree_manager.py --help
- 创建/列出 worktree
- 分配/持久化端口
- 复制 .env* 文件
- 可选地安装依赖
- - python scripts/worktree_cleanup.py --help
- 按时间检测过期
- 脏状态检测
- 已合并分支检测
- 可选的安全移除
两个工具均支持标准输入 JSON 和 --input 文件模式,适用于自动化流水线。
常见陷阱
- 1. 在主仓库目录内创建 worktree
- 在所有分支上重复使用 localhost:3000
- 在隔离的功能分支之间共享一个数据库 URL
- 移除包含未提交更改的 worktree
- 删除分支后忘记清理旧的元数据
- 未对照目标分支检查就假定合并状态
最佳实践
- 1. 每个 worktree 对应一个分支,每个 worktree 对应一个代理。
- 保持 worktree 短期存在;合并后移除。
- 使用确定性命名模式(wt-<主题>)。
- 将端口映射持久化到文件中,而非内存或终端笔记。
- 在活跃仓库中每周运行清理扫描。
- 机器流程使用 --format json,人工审查使用 --format text。
- 除非有意丢弃更改,否则切勿强制移除脏 worktree。
验证清单
在声明设置完成之前:
- 1. git worktree list 显示预期的路径和分支。
- .worktree-ports.json 存在且包含唯一的端口。
- .env 文件已成功复制(如果源仓库中存在)。
- 依赖安装命令以退出码 0 结束(如果启用)。
- 清理扫描未报告意外的过期脏树。
参考
决策矩阵
在创建新的 worktree 之前,使用此快速选择器:
- - 需要隔离的依赖和服务器端口 -> 创建新的 worktree
- 仅需快速本地差异审查 -> 停留在当前 tree
- 功能分支脏乱时需要热修复 -> 创建专用的热修复 worktree
- 需要临时复现分支进行 Bug 分类 -> 创建临时 worktree 并在当天清理
操作清单
创建前
- 1. 确认主仓库具有干净的基线或有意的 WIP 提交。
- 确认目标分支命名约定。
- 确认所需的基础分支存在(main/develop)。
- 确认没有保留的本地端口已被非仓库服务占用。
创建后
- 1. 验证 git status 分支与预期分支匹配。
- 验证 .worktree-ports.json 存在。
- 验证应用在分配的应用程序端口上启动。
- 验证数据库和缓存端点指向隔离的端口。
移除前
- 1. 验证分支已推送到上游,并在预期时已合并。
- 验证没有未提交的文件残留。
- 验证没有正在运行的容器/进程依赖此 worktree 路径。
CI 与团队集成
- - 使用映射到任务 ID 的 worktree 路径命名(wt-1234-auth)。
- 在终端标题中包含 worktree 路径,以避免在错误的窗口中提交。
- 在自动化设置中,将创建元数据持久化到 CI 工件/日志中。
- 在计划任务中触发清理报告,并将摘要发布到团队频道。
故障恢复
- - 如果 git worktree add 因路径已存在而失败:检查路径,不要覆盖。
- 如果依赖安装失败:保留已创建的 worktree,标记状态并继续手动恢复。
- 如果环境文件复制失败:继续执行并发出警告,列出缺失的文件。
- 如果端口分配与外部服务冲突:调整基础端口后重新运行。