Effective Git Worktree Management for Parallel Development: A Complete CLI Workflow

Git worktrees let you check out multiple branches simultaneously in separate directories, and the Git Worktree Manager skill automates this with port allocation, environment sync, and cleanup tools to prevent conflicts.

The engineering/git-worktree-manager skill in the alirezarezvani/claude-skills repository provides a self‑contained workflow for managing parallel development environments. This solution eliminates the friction of switching branches by automating port assignment, dependency installation, and safe cleanup of stale worktrees.

What is Git Worktree Management?

Git worktrees allow developers to maintain multiple working trees attached to the same repository. Unlike cloning the repository multiple times, worktrees share the same .git object database while keeping branch checkouts isolated in separate directories. The Git Worktree Manager extends this native Git capability with deterministic port allocation and lifecycle management scripts.

Creating Isolated Development Environments with worktree_manager.py

The primary automation tool is engineering/git-worktree-manager/scripts/worktree_manager.py. This CLI handles the complete setup of a new worktree from branch creation to dependency installation.

Automatic Port Allocation Strategy

The find_next_ports() function (lines 86‑107 in worktree_manager.py) prevents port collisions when running multiple services side‑by‑side. It scans existing worktrees for .worktree-ports.json files and calculates the next available port trio using a deterministic algorithm: base + (index × stride). By default, the script uses base ports 3000 (app), 5432 (DB), and 6379 (Redis) with a stride of 10.

Branch Handling and Worktree Creation

The ensure_worktree() function (lines 36‑52) checks whether the requested directory exists before executing git worktree add. If the branch does not exist, it automatically creates one using -b from the specified base branch, ensuring you never accidentally work on the wrong branch.

Environment Synchronization

Configuration drift is prevented by sync_env_files() (lines 10‑18), which copies all .env* files from the main repository into the new worktree. This guarantees identical database credentials, API keys, and service configuration across all parallel environments.

Dependency Installation

The install_dependencies_if_requested() function (lines 25‑33) detects your package manager by examining lockfiles (pnpm-lock.yaml, yarn.lock, package-lock.json, bun.lockb, or requirements.txt). It then executes the appropriate install command (npm install, pip install, etc.) automatically.


# Create a fully-prepared worktree (adds branch if missing)

python engineering/git-worktree-manager/scripts/worktree_manager.py \
  --repo . \
  --branch feature/login-improvement \
  --name wt-login \
  --base-branch main \
  --install-deps \
  --format text

# Automate creation via JSON (useful in CI pipelines)

cat <<EOF > config.json
{
  "repo": ".",
  "branch": "feature/api-v2",
  "name": "wt-api-v2",
  "base_branch": "main",
  "install_deps": true,
  "app_base": 3000,
  "db_base": 5432,
  "redis_base": 6379,
  "stride": 10
}
EOF

cat config.json | python engineering/git-worktree-manager/scripts/worktree_manager.py --format json

Maintaining Clean Workspaces with worktree_cleanup.py

Long‑running projects accumulate stale worktrees. The engineering/git-worktree-manager/scripts/worktree_cleanup.py script provides intelligent pruning based on commit age and merge status.

Detecting Stale Worktrees

The parse_worktrees() function (lines 57‑71) parses the porcelain output of git worktree list to build a metadata inventory. get_last_commit_age_days() (lines 79‑84) calculates the age of the latest commit in each worktree and flags entries older than the configurable --stale-days threshold (default: 14 days).

Safe Removal of Merged Branches

Before removal, the script validates two critical conditions:

  • is_dirty() (lines 86‑99): Checks for uncommitted changes
  • is_merged() (lines 86‑99): Verifies the branch is merged into the base branch

When invoked with --remove-merged, the cleanup script (lines 73‑81) executes git worktree remove only on worktrees that are stale, merged, and clean. Use --force to override the dirty‑state check if necessary.


# List worktrees and detect stale ones (default 14 days)

python engineering/git-worktree-manager/scripts/worktree_cleanup.py \
  --repo . \
  --stale-days 14 \
  --format text

# Safely remove merged & stale worktrees

python engineering/git-worktree-manager/scripts/worktree_cleanup.py \
  --repo . \
  --remove-merged \
  --format text

Configuration and Reference Architecture

Port Allocation Strategy Reference

The deterministic port system is documented in engineering/git-worktree-manager/references/port-allocation-strategy.md. This reference explains how the stride‑based algorithm ensures that worktree #0 uses ports 3000/5432/6379, worktree #1 uses 3010/5442/6389, and so on, preventing collisions in multi‑service architectures.

Docker Compose Integration Patterns

The references/docker-compose-patterns.md file provides templates for injecting allocated ports into per‑worktree Docker Compose override files. This allows each worktree to run its own isolated database and cache instances without manual configuration editing.

Installation and Usage Examples

Install the skill by cloning the alirezarezvani/claude-skills repository and referencing the installation instructions in the root README.md for Claude Code, OpenAI Codex, or OpenClaw.

Example JSON output from a successful worktree creation:

{
  "repo": "/path/to/project",
  "worktree_path": "/path/to/project/wt-login",
  "branch": "feature/login-improvement",
  "created": true,
  "ports": {"app": 3000, "db": 5432, "redis": 6379},
  "copied_env_files": [".env"],
  "dependency_install": "installed via npm install"
}

Summary

  • Port isolation: The find_next_ports() function uses a deterministic base‑plus‑stride algorithm to assign unique ports to each worktree
  • Automated setup: worktree_manager.py handles branch creation, environment file sync, and dependency installation in a single command
  • Safe cleanup: worktree_cleanup.py removes only merged, stale worktrees after verifying clean working states
  • Zero configuration: Default ports (3000, 5432, 6379) and stride values work out‑of‑the‑box for most web stacks
  • Docker integration: Reference documentation provides patterns for wiring ports into Docker Compose overrides

Frequently Asked Questions

What is Git worktree management?

Git worktree management is the practice of maintaining multiple working directories attached to a single repository. Unlike running git checkout to switch branches, worktrees let you keep several branches checked out simultaneously in separate folders, enabling parallel development without stashing changes or rebuilding dependencies repeatedly.

How does the port allocation prevent conflicts?

The port allocation strategy defined in worktree_manager.py uses a deterministic formula (base + (index × 10)) to assign application, database, and Redis ports. By scanning existing .worktree-ports.json files in sibling directories, the script finds the next available index and calculates ports that will not collide with running services from other worktrees.

Can I use this with Docker Compose?

Yes. The references/docker-compose-patterns.md document provides templates for creating per‑worktree override files. These overrides inject the ports allocated by worktree_manager.py into your container definitions, ensuring each worktree connects to its own isolated database and cache instances.

How do I safely remove old worktrees?

Run worktree_cleanup.py with the --remove-merged flag. The script checks three conditions before deletion: the worktree must be merged into the base branch, the last commit must be older than the --stale-days threshold (default 14 days), and the working directory must be clean (unless --force is used). This prevents accidental deletion of active feature branches or uncommitted work.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →