Git worktree

From jikig-ai/soleur · View interactive version

Git worktree is an AI agent skill from the GitHub repository jikig-ai/soleur. This skill should be used when managing Git worktrees for isolated parallel development. It handles creating, listing, switching, and cleaning up worktrees with a simple interactive interface.

How to use this skill

Skill file

<!-- grok-harness-invoke:start -->

Grok Build (plugins/soleur/lib/harness.ts invokeSkill()): Read this SKILL.md in this process and run it to completion. A one-segment soleur:<name> in this document names a SKILL — on Grok Build, Read plugins/soleur/skills/<name>/SKILL.md in this process; it is not a nested tool_use. A multi-segment id such as soleur:<domain>:<name> names an AGENT: spawn it, never Read it, and on Grok Build spawn_subagent takes the id with its colons replaced by hyphens (agentIdToGrokSubagentType). Claude Code: Skill tool for a skill (soleur:<name>), Task tool with subagent_type for an agent. Forbidden is executing a subset, not the Read.

<!-- grok-harness-invoke:end -->

Git Worktree Manager

This skill provides a unified interface for managing Git worktrees across your development workflow. Whether you're reviewing PRs in isolation or working on features in parallel, this skill handles all the complexity.

What This Skill Does

CRITICAL: Always Use the Manager Script

NEVER call git worktree add directly. Always use the worktree-manager.sh script.

The script handles critical setup that raw git commands don't:

  1. Copies .env, .env.local, .env.test, etc. from main repo
  2. Ensures .worktrees is in .gitignore
  3. Creates consistent directory structure
  4. Detects bare repos (core.bare = true) and derives GIT_ROOT via --absolute-git-dir instead of --show-toplevel
  5. Sources the shared plugins/soleur/scripts/resolve-git-root.sh helper -- all scripts that need GIT_ROOT should source this helper instead of inlining their own detection logic

After creating a worktree, run npm install if the project has a package.json — worktrees do not share node_modules/ with the main working tree, and build commands (npx @11ty/eleventy, etc.) will silently hang instead of erroring.

# ✅ CORRECT - Always use the script
bash "${CLAUDE_PLUGIN_ROOT}/skills/git-worktree/scripts/worktree-manager.sh" create feature-name

# ❌ WRONG - Never do this directly
git worktree add .worktrees/feature-name -b feature-name main

When to Use This Skill

Use this skill in these scenarios:

  1. Code Review (soleur:review): If NOT already on the target branch (PR branch or requested branch), offer worktree for isolated review
  2. Feature Work (soleur:work): Always ask if user wants parallel worktree or live branch work
  3. Parallel Development: When working on multiple features simultaneously
  4. Cleanup: After completing work in a worktree

How to Use

In Claude Code Workflows

The skill is automatically called from the soleur:review and soleur:work skills:

# For review: offers worktree if not on PR branch
# For work: always asks - new branch or worktree?

Manual Usage

You can also invoke the skill directly from bash:

# Create a new worktree (copies .env files automatically)
bash "${CLAUDE_PLUGIN_ROOT}/skills/git-worktree/scripts/worktree-manager.sh" create feature-login

# List all worktrees
bash "${CLAUDE_PLUGIN_ROOT}/skills/git-worktree/scripts/worktree-manager.sh" list

# Switch to a worktree
bash "${CLAUDE_PLUGIN_ROOT}/skills/git-worktree/scripts/worktree-manager.sh" switch feature-login

# Copy .env files to an existing worktree (if they weren't copied)
bash "${CLAUDE_PLUGIN_ROOT}/skills/git-worktree/scripts/worktree-manager.sh" copy-env feature-login

# Clean up completed worktrees
bash "${CLAUDE_PLUGIN_ROOT}/skills/git-worktree/scripts/worktree-manager.sh" cleanup

Commands

`create <branch-name> [from-branch]`

Creates a new worktree with the given branch name.

Options:

Example:

bash "${CLAUDE_PLUGIN_ROOT}/skills/git-worktree/scripts/worktree-manager.sh" create feature-login

What happens:

  1. Checks if worktree already exists
  2. Fetches refs/remotes/origin/<from-branch> (the local <from-branch> ref is NOT touched — this lets create succeed even when a sibling worktree has <from-branch> checked out; see #3741)
  3. Creates the new worktree from origin/<from-branch> with --no-track (preserves the pre-fix upstream-unset state so downstream git push -u origin <branch> flows are unchanged)
  4. Copies all .env files from main repo (.env, .env.local, .env.test, etc.)
  5. Shows path for cd-ing to the worktree

Opt-in: also update local <from-branch>

Pass --update-local-main (as a global flag, before create) to additionally fast-forward the local <from-branch> ref. Default behavior leaves the local ref untouched.

bash "${CLAUDE_PLUGIN_ROOT}/skills/git-worktree/scripts/worktree-manager.sh" --update-local-main create feature-login

Dependency install (bounded, skippable):

After copying .env files, create/feature install dependencies at the root and for each apps/*/ package (bun/npm/yarn by lockfile). Two guards keep this from hanging a pipeline on a restricted host:

All skips and failures warn-and-continue: worktree creation exits 0 and the worktree stays on disk.

`list` or `ls`

Lists all available worktrees with their branches and current status.

Example:

bash "${CLAUDE_PLUGIN_ROOT}/skills/git-worktree/scripts/worktree-manager.sh" list

Output shows:

`switch <name>` or `go <name>`

Switches to an existing worktree and cd's into it.

Example:

bash "${CLAUDE_PLUGIN_ROOT}/skills/git-worktree/scripts/worktree-manager.sh" switch feature-login

Optional:

`cleanup` or `clean`

Interactively cleans up inactive worktrees with confirmation.

Example:

bash "${CLAUDE_PLUGIN_ROOT}/skills/git-worktree/scripts/worktree-manager.sh" cleanup

What happens:

  1. Lists all inactive worktrees
  2. Asks for confirmation
  3. Removes selected worktrees
  4. Cleans up empty directories

`cleanup-merged` and `space-report`

cleanup-merged runs at every session start: it removes worktrees whose branch merged, sweeps dead-owner scratch under /tmp and /var/tmp (ADR-250), and prints what it freed. space-report prints the same SOLEUR_CLEANUP_SPACE state line without running any cleanup (read-only).

| Variable | Default | Effect |

|---|---|---|

| SOLEUR_QUARANTINE_DRAIN=1 | off (only the exact value 1 enables it) | Also delete scratch-quarantine entries past their TTL, inside the sweep's lock. Opt-in: a terminal delete on your machine. |

| SOLEUR_SWEEP_QUAR_SCRATCH_TTL_MIN / SOLEUR_SWEEP_QUAR_WT_TTL_MIN | 10080 (7 d) / 43200 (30 d) | Per-class TTL, minutes. |

| SOLEUR_SWEEP_QUAR_TTL_FLOOR_MIN | 1440 | Floor under both TTLs, so an exported 0 cannot empty a fresh quarantine. |

| SOLEUR_SWEEP_DRAIN_TIMEBOX_S / SOLEUR_SWEEP_DRAIN_MAX_ENTRIES | 5 / 200 | Checked between entries, per base. One very large entry can overrun them. A non-numeric value falls back to the default; a max of 0 means 200. |

| SOLEUR_DOCKER_PRUNE=1 / apply | off | After a run that removed a worktree, prune Docker build cache and dangling images older than 24 h (1 is a dry run, an upper bound). Never -a, volumes or containers. Any other value (including 0) prints skipped reason=invalid-value. SOLEUR_DOCKER_TIMEOUT_S (60) bounds each call, so apply can take about 140 s. |

Markers (stdout): SOLEUR_TMP_SWEEP (adds drained, drained_bytes, map_s), SOLEUR_DOCKER_PRUNE and SOLEUR_CLEANUP_SPACE logical_bytes=… df_delta_bytes=… fstype=… docker_prune=… snapshots=…. A SOLEUR_DOCKER_PRUNE skipped reason= names every no-op: invalid-value, no-worktree-removed (the common one), docker-missing, no-timeout, remote-daemon (a tcp:// or ssh:// DOCKER_HOST is never pruned), daemon-unreachable, timeout, df-failed rc=N (dry run), prune-failed rc=N. Docker's own Total: text is embedded verbatim and is opaque. logical_bytes counts drained bytes only; - means no baseline was taken (space-report). df_delta_bytes is the signed change in free space on /var/tmp and can be smaller, or negative, because other processes write too and, on btrfs with snapper, snapshots keep deleted blocks pinned (snapshots=snapper; Soleur never deletes snapshots). snapshots=none is reported for any non-btrfs filesystem and for btrfs without a snapper config named root, so it also covers a differently named config or Timeshift.

The markers stay on your machine when you run the plugin yourself. On the Soleur web platform the same lines are mirrored to server logs like every other SOLEUR_* marker. The sweep needs flock, so on stock macOS the sweep and drain skip with flock-missing; the Docker step needs timeout or gtimeout and otherwise prints skipped reason=no-timeout, and without findmnt the report prints fstype=unknown snapshots=unknown. Set SOLEUR_DOCKER_PRUNE in your shell profile or the session environment.

`sync-bare-files` or `sync`

Syncs stale on-disk files from git HEAD in a bare repo. Only needed when the repo uses core.bare=true — on-disk files at the bare root become stale after merges since git never updates them. Auto-called after cleanup-merged cleans branches in bare repo context.

Example:

bash "${CLAUDE_PLUGIN_ROOT}/skills/git-worktree/scripts/worktree-manager.sh" sync-bare-files

What it syncs: EVERY tracked file at HEAD — there is no allowlist.

The implementation builds a throwaway index from HEAD and runs

git checkout-index -a -f against the bare root, so every path git tracks is

materialized. That pass is additive — it never removes anything — so a

separate prune step afterwards deletes on-disk leftovers for paths that were

tracked once and are absent from HEAD. The two together are what make the bare

root equal HEAD exactly. It then re-applies execute bits for the scripts and

hooks the plugin loader and SessionStart hooks exec.

The prune is locale-independent (every sed/sort/comm stage runs under LC_ALL=C; a comm

in the user's locale once deleted tracked files, including .claude-plugin/marketplace.json) and

runs against the bare root's HEAD, pinned once, even when sync is started from a worktree on

another branch. Each candidate is checked against that commit right before removal, and a path under

a symlinked directory, a ./../.git path, a quoted spelling, and (when the root is the git dir)

a top-level name git owns are skipped (best effort for that legacy *.git layout).

A candidate that HEAD still tracks aborts the whole prune with ERROR: tracked path in prune set

(nothing is removed; the first one found is named). A prune larger than SOLEUR_SYNC_PRUNE_MAX (default

5000, counted on paths about to be removed; a leading zero is read as decimal, an invalid value falls

back to 5000 with a WARN, 0 skips every prune) is skipped with a WARN. There are three skip

paths (tracked hit, ceiling, could not compute the candidate set), all exit 0 so cleanup-merged

completes, and the last line then reads Synced on-disk files from git HEAD (prune skipped ...).

Nothing was deleted in that case; do not re-run, and report the ERROR path if one was printed.

A deleted file whose name holds a tab, newline, quote or backslash is never pruned (git quotes it).

Corrected 2026-08-10 (#7409). This section previously enumerated a

seven-entry list (AGENTS.md, plugins/soleur/hooks/*, .claude/hooks/*.sh,

resolve-git-root.sh, …) and told readers that "any file Claude Code executes

at runtime from the bare repo root must be added to the sync list". Both

halves were wrong: the enumeration described a whitelist the code has not

had, and the instruction sent readers to register files in a list that does

not exist. Worth stating precisely rather than deleting, because the

difference is load-bearing — when #7409 moved the session-state lock/lease

library to plugins/soleur/scripts/lib/, a genuine whitelist would have left

the bare root's repointed .claude/hooks/* sources pointing at a file the

mirror never copied, and they degrade silently (|| true). The full

mirror is what makes that a non-event.

Still important: run sync-bare-files after any merge that moves or adds a

file executed from the bare root. The mirror is complete, but it is not

automatic — on-disk files at a core.bare=true root are never updated by git

itself, so a stale copy survives until this runs.

If sync-bare-files fails with checkout-index from HEAD failed or `the bare root's HEAD does not

resolve (<ref>), check the bare root's HEAD: a PR merge that deleted the branch HEAD` named leaves

it dangling, and git -C <bare-root> symbolic-ref HEAD refs/heads/main repairs it (name the root with

-C: run bare from a worktree it would re-point that worktree). The Claude Code and Devin SessionStart loader does this

automatically (.claude/hooks/README.md, "Bare-root HEAD self-heal"); other harnesses do not.

Workflow Examples

Code Review with Worktree

# Claude Code recognizes you're not on the PR branch
# Offers: "Use worktree for isolated review? (y/n)"

# You respond: yes
# Script runs (copies .env files automatically):
bash "${CLAUDE_PLUGIN_ROOT}/skills/git-worktree/scripts/worktree-manager.sh" create pr-123-feature-name

# You're now in isolated worktree for review with all env vars
cd .worktrees/pr-123-feature-name

# After review, return to main:
cd ../..
bash "${CLAUDE_PLUGIN_ROOT}/skills/git-worktree/scripts/worktree-manager.sh" cleanup

Parallel Feature Development

# For first feature (copies .env files):
bash "${CLAUDE_PLUGIN_ROOT}/skills/git-worktree/scripts/worktree-manager.sh" create feature-login

# Later, start second feature (also copies .env files):
bash "${CLAUDE_PLUGIN_ROOT}/skills/git-worktree/scripts/worktree-manager.sh" create feature-notifications

# List what you have:
bash "${CLAUDE_PLUGIN_ROOT}/skills/git-worktree/scripts/worktree-manager.sh" list

# Switch between them as needed:
bash "${CLAUDE_PLUGIN_ROOT}/skills/git-worktree/scripts/worktree-manager.sh" switch feature-login

# Return to main and cleanup when done:
cd .
bash "${CLAUDE_PLUGIN_ROOT}/skills/git-worktree/scripts/worktree-manager.sh" cleanup

Key Design Principles

KISS (Keep It Simple, Stupid)

Opinionated Defaults

Safety First

Integration with Workflows

`soleur:review`

Instead of always creating a worktree:

1. Check current branch
2. If ALREADY on target branch (PR branch or requested branch) → stay there, no worktree needed
3. If DIFFERENT branch than the review target → offer worktree:
   "Use worktree for isolated review? (y/n)"
   - yes → call git-worktree skill
   - no → proceed with PR diff on current branch

`soleur:work`

Always offer choice:

1. Ask: "How do you want to work?
   1. New branch on current worktree (live work)
   2. Worktree (parallel work)"

2. If choice 1 → create new branch normally
3. If choice 2 → call git-worktree skill to create from main

Troubleshooting

"Worktree already exists"

If you see this, the script will ask if you want to switch to it instead.

"Cannot remove worktree: it is the current worktree"

Switch out of the worktree first (to main repo), then cleanup:

Navigate to the repository root directory, then run:

bash "${CLAUDE_PLUGIN_ROOT}/skills/git-worktree/scripts/worktree-manager.sh" cleanup

Lost in a worktree?

See where you are:

bash "${CLAUDE_PLUGIN_ROOT}/skills/git-worktree/scripts/worktree-manager.sh" list

.env files missing in worktree?

If a worktree was created without .env files (e.g., via raw git worktree add), copy them:

bash "${CLAUDE_PLUGIN_ROOT}/skills/git-worktree/scripts/worktree-manager.sh" copy-env feature-name

Navigate back to the repository root directory.

node_modules missing in worktree?

A worktree created without an install step (raw git worktree add, a

harness-created agent worktree, or a create whose dep install warned and

continued) carries no node_modules. Since #8580 the pre-commit lint hook

resolves its pinned binary from a sibling checkout's node_modules

automatically — accepted only when the sibling's package manifests report

CLI+engine versions equal to this checkout's pins (verified by file reads, so

an unchecked binary never runs) — so docs commits work without any install.

Everything else (vitest, tsx-driven suites, npm run scripts) still needs

the real install inside the worktree — run both from the worktree root:

npm ci --ignore-scripts
npm ci --ignore-scripts --prefix apps/web-platform   # needed by the webplat arm of scripts/test-all.sh

Sharp Edges

paths, and they override a subprocess's cwd and git -C.** A plain clone exports no

GIT_DIR at all, and only a RELATIVE GIT_INDEX_FILE (.git/index) which resolves

against the subprocess's own cwd and is harmless — so this reproduces only here; anyone

diagnosing it in a fresh clone will measure nothing and wrongly conclude the report is stale.

Consequence: a test fixture's git init initialises nothing and its commits land on the

worktree's live branch, moving the tip. Test-side convention and the rc=97 tripwire that now

refuses such a run: plugins/soleur/AGENTS.md §Test Fixture Conventions (#7833).

This is now largely a fallback — worktree-manager.sh performs both halves itself (#7394, ADR-173). ensure_bare_config removes the extension on every create / create-for-feature / cleanup-merged, create seeds core.bare = false into each new worktree's config.worktree, and a detection-time self-heal repairs the CURRENT worktree the moment git reports it as bare — so an already-wedged worktree recovers on first use rather than waiting for a session-start gate. The root cause of #7332 was that ensure_bare_config was dead code on the operator's bare-repo-in-.git layout: its guard branched on the gitdir's SHAPE (.git is a directory) which is true of that layout too. Reach for the manual repair only if SOLEUR_GIT_BARE_SELFHEAL … branch=failed or a worktree wedge: could not … line shows the automated path could not write. Do not gate on SOLEUR_GIT_BARE_POISON — it is emitted on the SUCCESS path too (branch=clean fires on every healthy run), so treating its presence as a failure signal sends you into config surgery on a healthy repo. Correction to the text above: the per-worktree files are typically absent, not 0 bytes — measured on git 2.53.0, git worktree add writes no config.worktree at all, so test for non-existence rather than for an empty file.

```bash

# Run this from INSIDE the new worktree. The lease key is the worktree

# DIRECTORY name, not the branch. Since #8400 cleanup-merged probes TWO keys per

# candidate — is_lease_active "$(_safe_worktree_name "$branch")" first, then

# is_lease_active "$(basename "$worktree_path")" — and holding EITHER is a hold.

# The directory basename is still the key to use here, because it is the one that

# survives switch's legacy-nested fallback (which leases under foo for a branch

# ci/foo, where the safe name is ci-foo). For a worktree created flat by the

# script the two keys are the same slug. The branch-keyed probe is the one that runs

# for a merged branch whose worktree is ALREADY GONE — the cohort that used to

# short-circuit every guard in the loop. The acquire side keys on

# the same slug (every / becomes -). Passing a branch name with a slash

# writes nothing at all — the validator rejects / — and says so only in a

# per-PID log file the agent never reads, so the worktree runs unleased and

# reapable with no visible signal. basename "$PWD" is also exactly what the

# matching release_lease calls in one-shot and work use.

SS_LIB="${CLAUDE_PLUGIN_ROOT}/scripts/lib/session-state.sh"

WT_KEY="$(basename "$PWD")"

if [[ -r "$SS_LIB" ]]; then

source "$SS_LIB" && acquire_lease "$WT_KEY" "<skill>" <minutes>

# rc=0 is NOT proof the lease exists: acquire_lease returns 0 and writes

# nothing when the layer is disabled. Assert the FILE, and reuse the marker

# the script already emits — it is mirrored and paged, so a new name here

# would be observable to nobody.

if [[ ! -f "$(git rev-parse --git-common-dir)/soleur-session-state/leases/$WT_KEY.lease" ]]; then

echo "SOLEUR_WORKTREE_LEASE_ACQUIRE_FAILED key=$WT_KEY site=manual reason=file-absent"

fi

else

# NEVER silent (#7409). Unlike release_lease and with_lock — advisory

# operations that degrade open quietly — this call IS the acquisition of

# the protection itself. There is nothing else to do when the library is

# absent, but degrading open without saying so manufactures exactly the

# exposure the lease exists to prevent: an unleased worktree that a

# sibling cleanup-merged is now free to reap.

echo "SOLEUR_SESSION_STATE_UNAVAILABLE path=$SS_LIB reason=worktree-UNLEASED-and-reapable"

fi

```

Note the default grant is 240 minutes: a long review-and-fix pass outlives it, so re-acquire rather than assuming the initial grant still covers you. Recovery when it is reaped: the commit objects survive unreferenced, so git branch <name> <sha> pins them before gc can prune, then re-push. Tell for the whole class — a test run whose failures read fatal: Unable to read current working directory or getcwd: cannot access parent directories is reporting its own environment being deleted, not defects. Why: 2026-08-10 (#7278) — reaped twice in one session, once on lease expiry and once with no lease at all; 2 of 3 full-suite "failures" were the deletion landing mid-run.

SOLEUR_ORPHAN_UNREMOVABLE count=<n> cleaned=<n> errno=<LABEL> names=<basename,basename> reason=rm-partial hint="…"

count= is how many could not be removed, cleaned= how many actually were (carried here so the success counter is readable at the default verbose=false, where the success summary is suppressed), and names= is sanitized basenames only. A human-readable failure summary naming each full path goes to stderr and prints even at verbose=false. A separate SOLEUR_ORPHAN_REGISTRY_UNAVAILABLE fires when git worktree list fails — the reaper then refuses to reap anything rather than treat an empty registry as "everything is an orphan". To clear it, stop the local Supabase stack (supabase stop) so the bind-mount is released, then re-run cleanup-merged. Do not reach for a containerized rm -rf as a privileged workaround. guardrails:block-rm-rf-worktrees still matches most docker-wrapped forms (the .worktrees/ path survives in the command line), but it is defeated by a remapped mount — docker run -v <abs>/.worktrees/foo:/target alpine rm -rf /target never names .worktrees/ after the rm -rf, so it is allowed. Measured; matcher gap tracked in #7113 (which also covers rm -rf -- <path>, where the -- separator defeats the same matcher). A safely-designed privileged fallback is tracked in #7112; the producer-side fix that would stop the residue being created at all is #7114.

```bash

ROOT="$(cd "$(git rev-parse --path-format=absolute --git-common-dir)/.." && pwd)"

# 1. Find nested entries. A flat worktree has no second / after .worktrees/.

git worktree list --porcelain | grep -E '^worktree .*/\.worktrees/[^/]+/'

# 2. The destination MUST NOT already exist. git worktree move into an

# existing directory moves the worktree INSIDE it, producing a NEW

# 3-level nesting — and git worktree list then prints a plausible path,

# so the migration silently reproduces the defect it is undoing.

test -e "$ROOT/.worktrees/ci-rule-metrics" && echo "ABORT: destination exists"

# 3. Absolute paths: relative ones resolve against your cwd, and running

# this from inside a worktree (the normal position) fails with a

# misleading "No such file or directory".

git worktree move "$ROOT/.worktrees/ci/rule-metrics" "$ROOT/.worktrees/ci-rule-metrics"

rmdir "$ROOT/.worktrees/ci" # only succeeds if now empty

git worktree list # confirm the new path is registered

```

Use git worktree move, never mv — the latter leaves the worktree's gitdir file pointing at the old path and the worktree reads as broken. (In this bare repo that admin file is <bare-root>/worktrees/<name>/gitdir, not .git/worktrees/<name>/gitdir.) git worktree move also refuses a locked worktree; unlock it first rather than reaching for -f -f. After the move the lease key changes with the basename, so re-run switch to re-acquire.

Technical Details

Directory Structure

.worktrees/
├── feature-login/          # Worktree 1
│   ├── .git
│   ├── app/
│   └── ...
├── feature-notifications/  # Worktree 2
│   ├── .git
│   ├── app/
│   └── ...
└── ...

.gitignore (updated to include .worktrees)

How It Works

Performance

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.