# Worktree setup — directory selection and creation

Phase 1 of the PR workflow: pick a worktree directory, verify it's gitignored, create the worktree, install deps, verify the baseline. Load this when starting a new feature/bugfix/refactor that needs an isolated worktree.

## Directory selection process

Follow this priority order:

### 1. Check existing directories

```bash
# Check in priority order
ls -d .worktrees 2>/dev/null     # Preferred (hidden)
ls -d worktrees 2>/dev/null      # Alternative
```

**If found:** Use that directory. If both exist, `.worktrees` wins.

### 2. Check CLAUDE.md

```bash
grep -i "worktree.*director" CLAUDE.md 2>/dev/null
```

**If preference specified:** Use it without asking.

### 3. Ask user

If no directory exists and no CLAUDE.md preference:

```
No worktree directory found. Where should I create worktrees?

1. .worktrees/ (project-local, hidden)
2. worktrees/ (project-local, visible)
3. Custom path

Which would you prefer?
```

## Safety verification

**MUST verify directory is ignored before creating worktree:**

```bash
# Check if directory is ignored (respects local, global, and system gitignore)
git check-ignore -q .worktrees 2>/dev/null || git check-ignore -q worktrees 2>/dev/null
```

**If NOT ignored:**

Fix immediately:
1. Add appropriate line to `.gitignore`
2. Commit the change
3. Proceed with worktree creation

**Why critical:** Prevents accidentally committing worktree contents to the repository.

## Creation steps

### 1. Detect project and branch name

```bash
project=$(basename "$(git rev-parse --show-toplevel)")
# Branch name from feature manifest or task
branch_name="feat/feature-name"  # or fix/, refactor/ per git-workflow rules
```

**Branch naming convention:**
- Features: `feat/short-description`
- Bug fixes: `fix/short-description`
- Refactors: `refactor/short-description`
- Hotfixes: `hotfix/short-description`

### 2. Create worktree

```bash
# Determine full path
path=".worktrees/$branch_name"

# Create worktree with new branch
git worktree add "$path" -b "$branch_name"
cd "$path"
```

### 3. Run project setup

Auto-detect and run appropriate setup:

```bash
# Node.js
if [ -f package.json ]; then npm install; fi

# Python
if [ -f requirements.txt ]; then pip install -r requirements.txt; fi
if [ -f pyproject.toml ]; then pip install -e ".[dev]" || poetry install; fi

# Rust
if [ -f Cargo.toml ]; then cargo build; fi

# Go
if [ -f go.mod ]; then go mod download; fi
```

### 4. Verify clean baseline

Run tests to ensure the worktree starts clean:

```bash
# Use project-appropriate command
npm test / pytest / cargo test / go test ./...
```

**If tests fail:** Report failures, ask whether to proceed or investigate.

**If tests pass:** Report ready.

### 5. Report

```
Worktree ready at <full-path>
Branch: <branch-name>
Tests passing (<N> tests, 0 failures)
Ready to implement <feature-name>
```
