Git Worktree Manager
Run parallel feature work safely with Git worktrees. Each worktree behaves like an independent local app: own branch, own ports, own env, with safe cleanup. One branch per worktree, one agent per worktree.
When to create a worktree (decision matrix)
- Need isolated deps + server ports → new worktree
- Quick local diff review only → stay on current tree
- Hotfix while feature branch is dirty → dedicated hotfix worktree
- Ephemeral bug-repro branch → temp worktree, clean up same day
Create a fully-prepared worktree
- Pick branch name + worktree name (deterministic:
wt-<topic>orwt-<taskid>-<topic>). - Create worktree from new/existing branch (create branch if missing) OUTSIDE the main repo dir.
- Auto-allocate non-conflicting ports; persist to
.worktree-ports.jsonin the worktree. - Copy
.env*from main repo into the worktree. - Optionally install deps (detect lockfile).
- Start app on the allocated ports.
Port allocation strategy
Default: base + (index * stride) with collision checks. App 3000, Postgres 5432, Redis 6379, stride 10. Persist the map to a file — never keep it only in memory/terminal notes. Per-worktree Docker Compose: use override files mapped from the allocated port map.
Parallel session convention
- Main repo: integration branch (main/develop) on default port
- Worktree A: feature branch + offset ports
- Worktree B: hotfix branch + next offset
Cleanup with safety checks
- Scan all worktrees + stale age.
- Inspect dirty trees and branch merge status.
- Remove only merged + clean worktrees. Never force-remove a dirty worktree unless changes are intentionally discarded.
Validation checklist (before claiming done)
git worktree listshows expected path + branch..worktree-ports.jsonexists with unique ports..envfiles copied (if present in source).- Dependency install exits 0 (if enabled).
- App boots on the allocated app port; DB/cache target isolated ports.
- Cleanup scan reports no unintended stale dirty trees.
Common pitfalls
- Creating worktrees inside the main repo dir.
- Reusing
localhost:3000across all branches. - Sharing one DB URL across isolated branches.
- Removing a worktree with uncommitted changes.
- Forgetting to prune metadata after branch deletion.
- Assuming merged status without checking against the target branch.
Failure recovery
git worktree addfails on existing path → inspect, do not overwrite.- Dep install fails → keep worktree, mark status, recover manually.
- Env copy fails → continue with warning + explicit missing-file list.
- Port collides with external service → rerun with adjusted base ports.