worktree-lifecycle
Use when starting isolated feature work or before executing implementation plans. Manages full worktree lifecycle from creation through cleanup with safety checks and error recovery.
What this skill does
# Worktree Lifecycle
**Purpose:** Manage git worktrees for isolated feature work with safety checks, multi-stack setup, and clean lifecycle management.
## When to Use
This skill applies whenever you:
- Start a new feature that requires isolated workspace
- Execute risky or experimental changes
- Need to keep current work untouched while testing alternatives
- Coordinate parallel agent work (each agent in separate worktree)
- Follow an implementation plan requiring clean environment
- Preserve long-running feature work across sessions
**Trigger keywords:** experiment, prototype, risky, breaking, parallel, isolate, worktree, workspace
## Red Flags (Anti-Patterns)
- [ ] Creating worktree without checking if branch already exists
- [ ] Creating worktree without checking if directory path is available
- [ ] Forgetting to add worktree directory to .gitignore
- [ ] Manually deleting worktree with `rm -rf` (use `git worktree remove`)
- [ ] Removing worktree with uncommitted changes without user confirmation
- [ ] Using same branch in multiple worktrees simultaneously
- [ ] Working in worktree after returning to main directory (stale CWD)
- [ ] Not storing original CWD before entering worktree
- [ ] Skipping dependency installation in new worktree
- [ ] Not running baseline tests before starting work
## 6-Phase Lifecycle
### Phase 1: Pre-flight Checks
**Purpose:** Verify all prerequisites before creating anything.
**Required checks** (all must pass):
```bash
# 1. Verify git repository
git rev-parse --git-dir &>/dev/null
if [ $? -ne 0 ]; then
ERROR: "Not a git repository"
RECOVERY: Abort with clear error message
fi
# 2. Detect detached HEAD state
if ! git symbolic-ref HEAD &>/dev/null; then
WARNING: "Currently in detached HEAD state"
RECOVERY: Ask user if they want to create branch from current commit
fi
# 3. Check if branch already in a worktree
if git worktree list | grep -q "$BRANCH"; then
ERROR: "Branch $BRANCH already checked out in a worktree"
RECOVERY: Ask user - reuse existing, rename branch, or cancel
fi
# 4. Check if branch exists (but not in worktree)
if git branch --list "$BRANCH" | grep -q .; then
WARNING: "Branch $BRANCH already exists"
RECOVERY: Ask user - use existing branch or create new with different name
fi
# 5. Check if target path is available
# IMPORTANT: Create directory first before checking (git check-ignore needs path to exist)
mkdir -p "$WORKTREE_DIR"
if [ -d "$WORKTREE_PATH" ]; then
ERROR: "Directory $WORKTREE_PATH already exists"
RECOVERY: Ask user - choose different path or remove existing
fi
```
**Error Recovery Table:**
| Error | Detection | Recovery |
|-------|-----------|----------|
| Not a git repo | `git rev-parse --git-dir` fails | Abort with clear error |
| Detached HEAD | `git symbolic-ref HEAD` fails | Ask: create branch from commit? |
| Branch in worktree | `git worktree list \| grep $BRANCH` succeeds | Ask: reuse, rename, or cancel |
| Branch exists | `git branch --list $BRANCH` returns result | Ask: use existing or rename |
| Path exists | Directory already present | Ask: choose different path or remove |
| Parent not writable | Cannot create parent directory | Abort with permission error |
### Phase 2: Directory Selection
**Priority order** (cascading, first match wins):
1. **Check for existing `.worktrees/` directory** → use it (no prompt)
2. **Check for existing `worktrees/` directory** → use it (no prompt)
3. **Check CLAUDE.md for worktree preference** → follow it (no prompt)
4. **Ask user** (only if no default found)
**For orchestrator integration**: Pass `WORKTREE_DIR=".worktrees"` to skip this phase entirely.
**Example detection**:
```bash
if [ -d ".worktrees" ]; then
WORKTREE_DIR=".worktrees"
elif [ -d "worktrees" ]; then
WORKTREE_DIR="worktrees"
elif grep -q "worktree.*directory" CLAUDE.md 2>/dev/null; then
WORKTREE_DIR=$(grep "worktree.*directory" CLAUDE.md | extract_path)
else
# Ask user via AskUserQuestion
# Options: .worktrees/, worktrees/, custom
fi
```
### Phase 3: Creation
**Steps** (must be executed in order):
```bash
# 1. Verify .gitignore safety
# IMPORTANT: Directory must exist before git check-ignore
mkdir -p "$WORKTREE_DIR"
if ! git check-ignore -q "$WORKTREE_DIR" 2>/dev/null; then
echo "$WORKTREE_DIR/" >> .gitignore
git add .gitignore
git commit -m "chore: add $WORKTREE_DIR to .gitignore"
fi
# 2. Store original CWD (critical for Phase 6 cleanup)
ORIGINAL_CWD=$(pwd)
# 3. Create worktree
git worktree add "$WORKTREE_PATH" -b "$BRANCH"
# 4. Verify creation succeeded
if [ ! -d "$WORKTREE_PATH" ]; then
ERROR: "Worktree creation failed"
RECOVERY: Clean up any partial state, report error
exit 1
fi
# 5. Change to worktree directory
cd "$WORKTREE_PATH"
# 6. Initialize submodules (if any)
if [ -f .gitmodules ]; then
git submodule update --init --recursive
fi
# 7. Write statusline worktree marker (persists across compaction)
if [ -n "$SESSION_ID" ]; then
cat > "$HOME/.claude/.statusline-worktree-${SESSION_ID}" <<MARKER_EOF
{
"worktree_path": "$WORKTREE_PATH",
"branch": "$BRANCH",
"worktree_name": "$(basename "$WORKTREE_PATH")"
}
MARKER_EOF
fi
```
**Error handling**: If `git worktree add` fails, clean up any partial state and report the error to user.
### Phase 4: Setup
**Multi-stack detection**:
```bash
# Detect all present stacks
STACKS=()
[ -f package.json ] && STACKS+=("nodejs")
[ -f Cargo.toml ] && STACKS+=("rust")
[ -f go.mod ] && STACKS+=("golang")
[ -f pyproject.toml ] || [ -f requirements.txt ] && STACKS+=("python")
[ -f Gemfile ] && STACKS+=("ruby")
# Run setup for each detected stack
for stack in "${STACKS[@]}"; do
echo "Setting up $stack..."
case "$stack" in
nodejs)
if [ -f bun.lockb ]; then
bun install
elif [ -f pnpm-lock.yaml ]; then
pnpm install
elif [ -f yarn.lock ]; then
yarn install
else
npm install
fi
;;
rust)
cargo build
;;
golang)
go mod download
;;
python)
if [ -f pyproject.toml ]; then
pip install -e .
else
pip install -r requirements.txt
fi
;;
ruby)
bundle install
;;
esac
done
```
**Baseline test verification**:
```bash
# Run tests and capture output (allow pre-existing failures)
for stack in "${STACKS[@]}"; do
case "$stack" in
nodejs)
if [ -f bun.lockb ]; then
bun test 2>&1 | tee test-output.log
else
npm test 2>&1 | tee test-output.log
fi
;;
rust)
cargo test 2>&1 | tee test-output.log
;;
golang)
go test ./... 2>&1 | tee test-output.log
;;
python)
pytest 2>&1 | tee test-output.log
;;
esac
# Parse test results (do NOT block on pre-existing failures)
PASSING=$(grep -o '[0-9]* passing' test-output.log | cut -d' ' -f1)
FAILING=$(grep -o '[0-9]* failing' test-output.log | cut -d' ' -f1)
echo "Baseline tests: $PASSING passing, $FAILING failing"
if [ "${FAILING:-0}" -gt 0 ]; then
echo "WARNING: Pre-existing test failures detected. Proceed with caution."
fi
done
```
### Phase 5: Handoff
**Structured output for orchestrator**:
```
Worktree ready:
Path: .worktrees/feature-auth-system
Branch: feature/auth-system
Stacks: nodejs
Dependencies: installed
Tests: 47 passing, 0 failing
Status: READY
Original CWD: /path/to/project
Worktree CWD: /path/to/project/.worktrees/feature-auth-system
```
**Write metadata to session** (for cleanup phase):
```bash
cat > "${SESSION_PATH}/worktree-metadata.json" <<EOF
{
"worktreePath": "$WORKTREE_PATH",
"absolutePath": "$(realpath $WORKTREE_PATH)",
"branchName": "$BRANCH",
"originalCwd": "$ORIGINAL_CWD",
"createdAt": "$(date -u +%Y-%m-%dT%H:%M:%SZ)",
"stacks": $(printf '%s\n' "${STACKS[@]}" | jq -R . | jq -s .),
"baselineTests": {
"passing": ${PASSING:-0},
"failing": ${FAILING:-0}
},
"status": "active"
}
EOF
```
**Orchestrator context passing** (for Related in General
modeling-omnistudio-epc-catalog
IncludedSalesforce Industries CME EPC product-modeling skill for Product2-based catalog creation. Use when creating EPC products, configuring product attributes, building offer bundles with Product Child Items, or reviewing EPC DataPack JSON metadata for product catalog changes. TRIGGER when: user creates or updates Product2 EPC records, AttributeAssignment payloads, AttributeMetadata/AttributeDefaultValues, Offer bundles, or ProductChildItem relationships. DO NOT TRIGGER when: designing OmniScripts/FlexCards/Integration Procedures (use building-omnistudio-omniscript, building-omnistudio-flexcard, or building-omnistudio-integration-procedure), implementing Apex business logic (use generating-apex), or troubleshooting deployment pipelines (use deploying-metadata).
relationship-science-coach
IncludedUse this skill for direct, practical adult relationship coaching: couples conflict, repair, trust, marriage, dating, flirting, attachment patterns, emotional connection, sex, desire differences, eroticism, kink negotiation, affection, love languages, breakups, and long-term passion. Draw on Gottman, EFT and Hold Me Tight, attachment science, modern sex research, Perel, Nagoski, Kerner, Schnarch, Love and Stosny, and flexible love-language tools. Be concrete and low-hedge. Redirect only for imminent danger, abuse, coercive control, minors, non-consent, self-harm, stalking, or medical/legal/psychiatric decisions.
building-sf-integrations
IncludedSalesforce integration architecture and runtime plumbing with 120-point scoring. Use this skill to set up Named Credentials, External Credentials, External Services, REST/SOAP callout patterns, Platform Events, and Change Data Capture. TRIGGER when: user sets up Named Credentials, External Services, REST/SOAP callouts, Platform Events, CDC, or touches .namedCredential-meta.xml files. DO NOT TRIGGER when: Connected App/OAuth config (use configuring-connected-apps), Apex-only logic (use generating-apex), or data import/export (use handling-sf-data).
venue-templates
IncludedAccess comprehensive LaTeX templates, formatting requirements, and submission guidelines for major scientific publication venues (Nature, Science, PLOS, IEEE, ACM), academic conferences (NeurIPS, ICML, CVPR, CHI), research posters, and grant proposals (NSF, NIH, DOE, DARPA). This skill should be used when preparing manuscripts for journal submission, conference papers, research posters, or grant proposals and need venue-specific formatting requirements and templates.
let-fate-decide
IncludedDraws the 12 Houses of the Zodiac Tarot spread to inject entropy into planning when prompts are vague, ambiguous, or casually delegated. Interprets the spread to guide next steps. Use when the user says 'let fate decide', 'YOLO', 'whatever', 'idk', or other nonchalant phrases, makes Yu-Gi-Oh references, or when you are about to arbitrarily pick between multiple reasonable approaches. Prefer over ask-questions-if-underspecified when the user's tone is casual or playful rather than precision-seeking.
net-ops
IncludedCross-platform network troubleshooting (Windows, macOS, Linux) via local or remote shell. Use for: DNS broken, can't resolve hostnames, nslookup/dig works but apps fail, NRPT, WFP, scutil, /etc/resolver, systemd-resolved, /etc/resolv.conf, NetworkManager, VPN DNS leak residue (ProtonVPN/Mullvad/WireGuard/AnyConnect), AV/firewall blocking DNS or DoH, Tailscale DNS interaction, intermittent connectivity, remote diagnostics over SSH.