Skip to content
Back to skills

Git Worktree Manager

BSecurity

Run parallel Git worktrees without collisions: a port block per worktree, health checks (stale, missing, detached, merged, .env and lockfile drift, port clashes) and safe cleanup of merged ones. Use when several branches or agents need dev servers at once, or when a repo with many worktrees needs an audit.

  • 1,271 stars
  • 0 votes
  • 0 copies
  • 2 views
  • Added May 27, 2026
data-aipythongobashdockergitapidatabaseci/cddocumentation

Works with

  • terminal
  • api

Security analysis

B85/100
  • highPerforms destructive filesystem operations

Pro scans all 4 files and shows the line behind each finding

Scanned December 4, 2026

npx -y skills add borghei/Claude-Skills --skill git-worktree-manager --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Git Worktree Manager?

Add the live security badge to your README. It updates with every re-scan.

Security grade badge for Git Worktree Manager
[![Security: B — Skills Directory](https://www.skillsdirectory.com/api/skills/borghei-git-worktree-manager/badge)](https://www.skillsdirectory.com/skills/borghei-git-worktree-manager)

More formats (shields.io, HTML) on the badges page. Keep it an A: scan every change in CI with Pro.

Download with Pro
SKILL.md
---
name: git-worktree-manager
description: >
  Run parallel Git worktrees without collisions: a port block per worktree, health checks
  (stale, missing, detached, merged, .env and lockfile drift, port clashes) and safe cleanup of
  merged ones. Use when several branches or agents need dev servers at once, or when a repo with
  many worktrees needs an audit.
license: MIT + Commons Clause
metadata:
  version: 1.1.0
  author: borghei
  category: engineering
  domain: developer-tooling
  tier: POWERFUL
  updated: 2026-11-08
  frameworks: git-worktree
  tags:
    - git
    - worktrees
    - parallel-development
    - branching
    - developer-tooling
---
# Git Worktree Manager

Plain `git worktree add/remove` is the easy part. The agent uses this skill for what git does not do: give every worktree its own port block so dev servers and Docker services do not collide, carry `.env` files across, spot worktrees that are stale, dirty or tracking deleted branches, and remove merged ones without losing uncommitted work. Each finding comes with the command or edit that fixes it. It suits multi-agent setups where each agent or terminal owns one worktree.

## Core Capabilities

- **Worktree lifecycle** — create worktrees from new or existing branches with deterministic naming (`wt-<last path segment of the branch>`, next to the main checkout), list with clean/dirty + ahead/behind status, and remove with uncommitted-change detection. Copying `.env` files and installing dependencies is done by the `setup-worktree.sh` script in the references.
- **Port allocation** — deterministic per-worktree assignment (`base + index * stride`), collision detection against running processes, persistent map in `.worktree-ports.json`, and Docker Compose override generation.
- **Multi-agent isolation** — one branch per worktree, one agent per worktree, no shared state, conflict-free parallel execution, task-ID mapping for traceability.
- **Cleanup automation** — stale detection by age, merged-branch detection for safe removal, dirty-state warnings, and bulk cleanup with safety confirmations.

## 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.

## Clarify First

Before managing worktrees, settle the inputs below. When one is missing or vague and would change the result, ask about it; when it wouldn't, use a sensible default and say which one you used.

- **Operation:** create, list, remove, or clean up worktrees (selects the `worktree_manager.py` action vs `port_allocator.py` vs `worktree_validator.py`).
- **Branch & base:** which branch(es) the worktree(s) track and from what base (drives worktree naming and isolation).
- **Port/service needs:** whether dev servers or Docker need allocated ports (drives the deterministic port block and the Docker Compose override generated).

Ask about the two or three inputs that matter most for this request, not the whole list. If the user wants a result straight away, produce it and state your assumptions at the top.

## Workflow

1. **Create** the worktree with `worktree_manager.py create <branch> --base main`; it names the directory deterministically. Copy `.env` files and install dependencies with the setup script in [references/setup-and-ports.md](references/setup-and-ports.md).
2. **Assign ports** with `port_allocator.py assign <worktree-name>`: a block at `base + index * stride`, refused when a process already listens on it, recorded in `.worktree-ports-registry.json` (repo root) and `.worktree-ports.json` (worktree). Use the Docker Compose override in [references/setup-and-ports.md](references/setup-and-ports.md) to apply it.
3. **Work**: one branch and one agent per worktree, no shared mutable state.
4. **Check health** with `worktree_validator.py` (stale trees, missing directories, deleted branches, `.env` parity, port conflicts, lockfile drift).
5. **Clean up** with `worktree_manager.py cleanup --dry-run` first, then without `--dry-run`; dirty worktrees are reported, not deleted. Run `port_allocator.py sync` afterwards to free released blocks.
6. **Verify** that `worktree_validator.py` reports no issues and `git worktree list` matches the port registry.

## Quick Start

Every tool reads the repository given by `--repo` (default: the current directory) and supports
`--format text|json` (`--json` is an alias). To try the tools on a generated repository with known
problems:

```bash
python3 scripts/make_sample_repo.py --out-dir demo --scenario flawed
python3 scripts/worktree_validator.py --repo demo/repo
python3 scripts/worktree_manager.py list --repo demo/repo
python3 scripts/port_allocator.py status --repo demo/repo
python3 scripts/worktree_manager.py cleanup --stale-days 30 --dry-run --repo demo/repo
```

Real output of the validator on that repository (excerpt, paths shortened):

```text
Repository: demo/repo
Read 7 worktree(s) (6 linked); checks: stale, missing, branch, env, ports, lockfile

[ERROR] missing: Worktree directory does not exist. Run 'git worktree prune'.
    path:   demo/wt-gone
    branch: feat/gone
    fix:    git worktree prune

[ERROR] ports: Port 3010 (app) conflicts with demo/wt-auth.
    path:   demo/wt-billing
    fix:    python3 scripts/port_allocator.py release wt-billing && python3 scripts/port_allocator.py assign wt-billing

[WARNING] env: .env is missing 2 key(s) present in main: API_KEY, PORT
    path:   demo/wt-billing
    fix:    add API_KEY, PORT to demo/wt-billing/.env
...
2 error(s), 3 warning(s), 1 info note(s).
FIX 5 issues
```

The same command on `--scenario sound` prints `PASS` and exits 0.

## Tools Overview

| Tool | Subcommands and flags |
|------|-----------------------|
| `worktree_manager.py` | `list [--target BRANCH] [--stale-days N]`, `create <branch> [--base]`, `remove <path> [--force]`, `cleanup [--stale-days N] [--target BRANCH] [--dry-run]` |
| `port_allocator.py` | `status`, `assign <name> [--index N] [--branch B] [--base-port NAME=PORT] [--stride N]`, `release <name>`, `check --port 3010,5442`, `sync [--dry-run]` |
| `worktree_validator.py` | `--checks stale,missing,branch,env,ports,lockfile`, `--stale-days N` |
| `make_sample_repo.py` | `--out-dir DIR --scenario sound\|flawed`: builds a throwaway repository to try the tools on |

All except `make_sample_repo.py` also take `--repo PATH` and `--format text|json`.

## Exit Codes

| Code | Meaning |
|------|---------|
| 0 | Clean, or the operation succeeded (`PASS`) |
| 1 | Findings the user must act on (`FIX n issues`): missing, merged or stale worktrees, errors or warnings from the validator, orphaned or duplicate port allocations, busy or taken ports, a dirty tree that blocks removal, a git operation that failed |
| 2 | Unusable input (`BLOCKED: ...` on stderr): `--repo` is not a git repository, unknown check name, bad port or index, unreadable registry, no subcommand |

## Notes on how it judges

- **Merged** means the target branch (origin/HEAD, else `main`, else `master`; override with `--target`) contains every commit of the branch and has moved past it. A fresh branch still on the target tip is not merged.
- **Stale** is a heuristic: the worktree directory's modification time is older than `--stale-days` (default 14). Editing a file inside a subdirectory does not refresh it, so treat it as a prompt to look, not proof.
- **Lockfile drift** compares modification times, not contents (heuristic). **Env parity** compares variable names only; values are never printed.
- Default base ports (app 3000, database 5432, redis 6379, api 8000, stride 10) are conventions used only when no registry exists; set your own on the first `assign` with `--base-port app=4000 --stride 20`.
- `cleanup` never removes the main checkout or a dirty worktree, and never deletes branches.

## Anti-Patterns

**Mistake:** Deleting worktree directories with `rm -rf`.
**Why it happens:** It looks like any other folder.
**Instead:** Use `worktree_manager.py remove` (or `git worktree remove`); a raw delete leaves stale metadata and loses uncommitted work without warning.

**Mistake:** Two worktrees on the same dev-server ports.
**Why it happens:** Every checkout reads the same default `.env`.
**Instead:** Assign a port block per worktree and generate the Compose override from it.

**Mistake:** Two agents sharing one worktree.
**Why it happens:** It saves a checkout.
**Instead:** One agent per worktree and branch; shared working trees produce interleaved, unreviewable changes.

## Files

- `scripts/worktree_manager.py`, `scripts/port_allocator.py`, `scripts/worktree_validator.py` — the tools above; they read the repository you point them at.
- `scripts/make_sample_repo.py` — generates a sound or flawed sample repository on demand (nothing is written unless you pass `--out-dir`).
- `assets/contract.json` — the checked runs (sound, flawed, malformed, JSON) behind the exit codes; `assets/malformed_repo.txt` is the not-a-repository input.

## Reference Documentation

Load the reference that matches the task — keep this file lean and pull detail on demand:

- **[references/setup-and-ports.md](references/setup-and-ports.md)** — quick-start `git worktree` commands, the deterministic port-allocation strategy and `.worktree-ports.json` format, collision-detection snippet, the full `setup-worktree.sh` script, and the Docker Compose per-worktree override. Read when creating a worktree or wiring up ports/services.
- **[references/cleanup-and-workflows.md](references/cleanup-and-workflows.md)** — the `cleanup-worktrees.sh` safe-cleanup script, the multi-agent assignment pattern and rules, the scenario→action decision matrix, and the post-creation validation checklist. Read when automating cleanup or coordinating agents.
- **[references/operations-playbook.md](references/operations-playbook.md)** — common pitfalls, best practices, the troubleshooting table, and the success-criteria bar. Read before shipping a workflow or when diagnosing problems.

## 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`)

Related skills: `engineering/env-secrets-manager` (the `.env` files copied into worktrees), `engineering/monorepo-navigator` (package boundaries inside a worktree).

Files in this skill

  • SKILL.md16.5 KB
  • scripts/port_allocator.py15 KB
  • scripts/worktree_manager.py13.5 KB
  • scripts/worktree_validator.py16.2 KB

Attribution

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

View all in data-ai →

Comments

Loading comments…

Newsletter

Get the weekly list of safe new skills, and the ones we pulled.