---
name: worktree
description: Manage git worktrees for parallel Claude Code sessions. Create, list, navigate, and remove worktrees with automatic port allocation for local native development.
allowed-tools: Bash, Read, Write, Edit, Glob, Grep
version: 1.3.0
---

# Git Worktree Skill

Manage git worktrees for running parallel Claude Code sessions on the same repository. Each worktree gets its own isolated file state while sharing git history. All development runs natively — no Docker.

## CRITICAL: Always Use Absolute Paths

**All file operations and commands MUST use absolute paths to the target worktree.** This allows working on any worktree from any session, regardless of the current working directory.

### Rules

1. **File tools** (Read, Edit, Write, Glob, Grep): Always use the full absolute path (e.g., `$HOME/worktrees/myapp-feature-auth/app/models/user.rb`)
2. **Git commands**: Use `git -C <worktree-path>` instead of relying on cwd (e.g., `git -C $HOME/worktrees/myapp-feature-auth status`)
3. **Tests**: Pass the absolute path to your test runner (e.g., `~/.claude/scripts/native-test $HOME/worktrees/myapp-feature-auth/test/models/user_test.rb`)
4. **Bundle/Rails**: Use `bash -c 'cd <worktree-path> && bundle exec rails ...'`

### Examples

```bash
# GOOD - absolute paths work from anywhere
Read $HOME/worktrees/myapp-feature-auth/app/models/order.rb
git -C $HOME/worktrees/myapp-feature-auth diff master...HEAD

# BAD - relies on cwd, breaks cross-worktree usage
Read app/models/order.rb
git diff master...HEAD
```

## Usage

```
/worktree <command> [options]
```

**Commands:**
- `/worktree create <name>` - Create a new worktree
- `/worktree setup <path>` - Run project setup on a worktree
- `/worktree list` - List all worktrees with their ports
- `/worktree remove <name>` - Remove a worktree
- `/worktree status` - Show current worktree info and port
- `/worktree ports` - Show port allocation registry

## Core Concepts

### What is a Worktree?

A git worktree is a linked copy of your repository at a different path. All worktrees share:
- Git history and commits
- Remote connections
- Branch references

Each worktree has its own:
- Working directory (file state)
- Checked out branch
- Staged changes

### Why Use Worktrees?

1. **Parallel Claude sessions** - Work on multiple features simultaneously
2. **Single session, multiple worktrees** - Work across worktrees using absolute paths
3. **Code isolation** - Changes in one worktree don't affect others
4. **Fast context switching** - No need to stash/commit to switch tasks

---

## Port Allocation System

Each worktree runs its own dev server on a unique port.

### Port Registry

Ports are tracked in `~/.claude-worktree-ports`:

```
# Format: worktree_path|port|project_name
/Users/you/code/myapp|3000|myapp
/Users/you/worktrees/myapp-feature-a|3001|myapp
/Users/you/worktrees/myapp-feature-b|3002|myapp
```

### Port Allocation Rules

- Port 3000: Reserved for main checkout
- Ports 3001-3099: Available for worktrees
- Allocation is per-project (different projects can reuse ports)

### Checking Current Port

```bash
cat $HOME/worktrees/myapp-<name>/.worktree-port 2>/dev/null || echo "3000 (main checkout)"
```

---

## Commands Reference

### Create Worktree

**IMPORTANT: Always create worktrees in `~/worktrees/`, NEVER in `~/code/`. The `~/code/` directory is only for main checkouts.**

```bash
/worktree create feature-auth
```

**What happens:**
1. Creates worktree at `~/worktrees/<repo>-<name>/`
2. Allocates next available port
3. Creates `.worktree-port` file
4. **Runs `worktree-setup`** (copies config, installs deps)
5. Reports the assigned port

**IMPORTANT:** If you create a worktree manually (git worktree add), you MUST run `worktree-setup` afterwards.

**With specific branch:**
```bash
/worktree create feature-auth --branch user/o-1234-auth
```

**With new branch:**
```bash
/worktree create feature-auth --new-branch user/o-1234-auth
```

### List Worktrees

```bash
/worktree list
```

**Output:**
```
Git Worktrees for myapp:

| Path | Branch | Port | Status |
|------|--------|------|--------|
| ~/code/myapp | master | 3000 | main |
| ~/worktrees/myapp-feature-a | user/o-1234-auth | 3001 | active |
| ~/worktrees/myapp-feature-b | user/o-1235-api | 3002 | active |
```

### Remove Worktree

```bash
/worktree remove feature-auth
```

**What happens:**
1. Removes the worktree directory
2. Frees the port allocation
3. Cleans up git worktree reference

### Show Status

```bash
/worktree status
```

**Output:**
```
Current Worktree: ~/worktrees/myapp-feature-a
Branch: user/o-1234-auth
Port: 3001
Web URL: http://localhost:3001
```

---

## Post-Create Setup

**ALWAYS run setup after creating a worktree.** Use the setup script:

```bash
~/.claude/scripts/worktree-setup $HOME/worktrees/myapp-<name>
```

The setup script should be customized for your project. A typical Rails setup:

1. **Copies config files** from main checkout (credentials, environment configs, etc.)
2. **Runs `bundle install`** — Installs Ruby dependencies
3. **Runs `yarn install`** — Installs JavaScript dependencies
4. **Writes `.env.native`** — Port-aware environment variables
5. **Prints server start command** with correct port

### Starting the Server

After setup, start with:

```bash
cd $HOME/worktrees/myapp-<name>
set -a && source .env.native && set +a && bundle exec rails server -p $PORT
```

### Important: Work Within the Worktree

**Never copy files from a worktree back to the main checkout.** Each worktree is an isolated workspace. Always run tests and commands using absolute paths.

---

## Implementation Details

### Worktree Location

**MANDATORY: All worktrees MUST be created in `~/worktrees/`.** Never create worktrees in `~/code/` or any other directory. The `~/code/` directory is reserved exclusively for the main checkout of each repository.

Path format: `~/worktrees/<repo-name>-<worktree-name>/`

Example:
- Repo: `myapp`
- Worktree name: `feature-auth`
- Path: `~/worktrees/myapp-feature-auth/`

**WRONG:** `~/code/myapp-feature-auth/` — never put worktrees in `~/code/`

### Port File

Each worktree has a `.worktree-port` file containing just the port number:

```bash
cat $HOME/worktrees/myapp-<name>/.worktree-port
# Output: 3001
```

This file is:
- Created by the worktree skill
- Read by your test runner and server start command
- Used to configure web server port and test DB isolation

### Registry File

`~/.claude-worktree-ports` tracks all allocations:

```bash
cat ~/.claude-worktree-ports

# Format: path|port|project
/Users/you/code/myapp|3000|myapp
/Users/you/worktrees/myapp-feature-a|3001|myapp
```

---

## Best Practices

### 1. One Task Per Worktree

Each worktree should represent one logical unit of work:
- A single feature
- A bug fix
- An exploration or spike

### 2. Clean Up After Merging

When a branch is merged, remove its worktree:

```bash
/worktree remove feature-auth
```

### 3. Isolated Test Databases

Each worktree automatically gets its own test database to avoid lock contention:
- Main checkout (port 3000) → `myapp_test`
- Worktree 1 (port 3001) → `myapp_test_1`
- Worktree 2 (port 3002) → `myapp_test_2`

This is handled by your test runner reading `.worktree-port` and setting `TEST_ENV_NUMBER`, which `database.yml` uses to suffix the test DB name. The development database is still shared across all worktrees.

The test database is auto-created on first test run — no extra setup needed.

---

## Troubleshooting

### "Worktree already exists"

```bash
# List existing worktrees
git worktree list

# Remove stale worktree reference
git worktree remove <path> --force
```

### "Port already in use"

```bash
# Find what's using the port
lsof -i :3001

# Kill the process
kill -9 <PID>

# Or reallocate port
/worktree remove feature-a
/worktree create feature-a
```

### "Branch already checked out"

Git doesn't allow the same branch in multiple worktrees:

```bash
# Check which worktree has the branch
git worktree list

# Either remove that worktree or use a different branch
```
