[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7AJ1CGXH74ZSZPQ1DP8RQA2":3,"skill-same:01M7AJ1CGXH74ZSZPQ1DP8RQA2":51},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":28,"commitSha":29,"skillDirectory":30,"forksCount":31,"repositoryHtmlUrl":32,"repositoryHomepageUrl":6,"ownerHtmlUrl":33,"ownerBlogUrl":34,"ownerDescription":35,"updatedAt":36,"install":37,"resources":50},"01M7AJ1CGXH74ZSZPQ1DP8RQA2","speckit-spex-worktrees-manage",null,"Manage git worktrees for isolated feature development - create after specify, list active worktrees, finish and cleanup","jimmidyson\u002Fkcp-cluster-api","jimmidyson","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F464659?v=4","01M7AHMAJZVCKJFJ493ENNT2AF","Jimmi Dyson","01M7AHMAKKXY03Y7QK73HWEQQN",1,"Apache-2.0","https:\u002F\u002Fgithub.com\u002Fjimmidyson\u002Fkcp-cluster-api\u002Fblob\u002Fmain\u002F.specify\u002Fextensions\u002Fspex-worktrees\u002F.specify-dev\u002Fagent-commands\u002Fclaude\u002Fspeckit-spex-worktrees-manage\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: speckit-spex-worktrees-manage\ndescription: Manage git worktrees for isolated feature development - create after specify, list active worktrees, finish and cleanup\ncompatibility: Requires spec-kit project structure with .specify\u002F directory\nmetadata:\n  author: github-spec-kit\n  source: spex-worktrees:commands\u002Fspeckit.spex-worktrees.manage.md\n---\n\n# Git Worktree Management for spex\n\n## Overview\n\nThis command manages git worktrees to isolate feature development. It supports four actions:\n\n- **create**: Called by the `after_specify` hook after `speckit-specify` completes. Creates a worktree, restores `main`, and prints switch instructions.\n- **ensure**: Called by the `before_implement` hook. Verifies worktree isolation exists. If already in a worktree, proceeds silently. If not, creates one (same as `create`).\n- **list**: Shows all active feature worktrees with path, branch, and feature name.\n- **finish**: Merges the current worktree's branch into the default branch and removes the worktree. Use when implementation is complete.\n- **cleanup**: Detects worktrees whose branches are merged and offers removal.\n\n## Action Routing\n\nDetermine the action from the argument:\n\n- If invoked with argument `create` (from the `after_specify` hook): the action is **create**. Execute immediately, no confirmation needed.\n- If invoked with argument `ensure` (from the `before_implement` hook): the action is **ensure**. See Action: Ensure below.\n- If invoked with argument `finish`: the action is **finish**.\n- If invoked with argument `cleanup`: the action is **cleanup**.\n- Otherwise (no args, `list`, or invoked directly): the action is **list**.\n\n## Prerequisites\n\nThe project must be a git repository.\n\n```bash\ngit rev-parse --git-dir >\u002Fdev\u002Fnull 2>&1 || { echo \"ERROR: Not a git repository\"; exit 1; }\n```\n\n## Action: Create\n\nThis action runs after `speckit-specify` has created a feature branch and spec files.\n\n### Step 1: Read Configuration\n\nRead `base_path` from the worktrees extension config (or default to `.claude\u002Fworktrees`):\n\n```bash\nWORKTREE_CONFIG=\".specify\u002Fextensions\u002Fspex-worktrees\u002Fworktree-config.yml\"\nBASE_PATH=$(yq -r '.worktrees.base_path \u002F\u002F \".claude\u002Fworktrees\"' \"$WORKTREE_CONFIG\" 2>\u002Fdev\u002Fnull || echo \".claude\u002Fworktrees\")\n```\n\nDefault: `.claude\u002Fworktrees` (inside the project directory, keeps CWD stable for the coding agent).\n\n### Step 2: Get Current Branch\n\n```bash\nBRANCH_NAME=$(git rev-parse --abbrev-ref HEAD)\n```\n\nVerify it matches the `NNN-feature-name` pattern. If not, warn that worktree creation only applies to feature branches and skip.\n\n### Step 3: Detect If Already in a Worktree\n\nA git worktree has a `.git` file (not directory) pointing to the main repo. Detect this:\n\n```bash\nREPO_ROOT=$(git rev-parse --show-toplevel)\nGIT_DIR=$(git rev-parse --git-dir)\n\n# If git-dir is not \u003Crepo>\u002F.git, we're inside a worktree\nif [ \"$GIT_DIR\" != \"$REPO_ROOT\u002F.git\" ] && [ \"$GIT_DIR\" != \".git\" ]; then\n  echo \"WARNING: Already inside a git worktree. Skipping worktree creation.\"\n  echo \"Worktree nesting is not supported.\"\n  # Stop here. Do not proceed to subsequent steps.\nfi\n```\n\nIf inside a worktree, skip the entire create action. Do not proceed to any subsequent Create steps.\n\n### Step 4: Compute Target Path and Validate\n\nDetermine if the worktree should be inside or outside the project, then build the path:\n\n```bash\nREPO_ROOT=$(git rev-parse --show-toplevel)\n\n# Detect inside-project worktrees (.claude\u002Fworktrees and .worktrees are allowed)\nINSIDE_PROJECT=false\ncase \"$BASE_PATH\" in\n  .claude\u002Fworktrees*|.worktrees*) INSIDE_PROJECT=true ;;\nesac\n```\n\n**If inside project** (`INSIDE_PROJECT` is `true`):\n\n```bash\nmkdir -p \"$REPO_ROOT\u002F$BASE_PATH\"\nWORKTREE_PATH=\"$REPO_ROOT\u002F$BASE_PATH\u002F$BRANCH_NAME\"\n```\n\n**If outside project** (`INSIDE_PROJECT` is `false`):\n\n```bash\nREPO_NAME=$(basename \"$REPO_ROOT\")\n\n# Handle both absolute and relative base paths\nif [[ \"$BASE_PATH\" = \u002F* ]]; then\n  RESOLVED_BASE=$(cd \"$BASE_PATH\" && pwd)\nelse\n  RESOLVED_BASE=$(cd \"$REPO_ROOT\u002F$BASE_PATH\" && pwd)\nfi\n```\n\nIf the `cd` fails (directory does not exist), report a clear error and stop:\n\n```bash\nif [ -z \"$RESOLVED_BASE\" ]; then\n  echo \"ERROR: base_path '$BASE_PATH' does not resolve to a valid directory.\"\n  echo \"Check worktrees.base_path in .specify\u002Fextensions\u002Fspex-worktrees\u002Fworktree-config.yml\"\n  # Stop here. Do not proceed to subsequent steps.\nfi\n```\n\nBuild the worktree path using `@` as separator between repo name and branch:\n\n```bash\nWORKTREE_PATH=\"${RESOLVED_BASE}\u002F${REPO_NAME}@${BRANCH_NAME}\"\n```\n\n**For both paths**, verify the worktree is not inside the main repository in a disallowed location:\n\n```bash\ncase \"$WORKTREE_PATH\" in\n  \"$REPO_ROOT\"\u002F.claude\u002Fworktrees\u002F*|\"$REPO_ROOT\"\u002F.worktrees\u002F*)\n    ;; # Allowed: inside .claude\u002Fworktrees\u002F or .worktrees\u002F\n  \"$REPO_ROOT\"\u002F*)\n    echo \"ERROR: Worktree path is inside the main repository: $WORKTREE_PATH\"\n    echo \"Set base_path to '.claude\u002Fworktrees', '.worktrees', or a directory outside the repo\"\n    # Stop here. Do not proceed to subsequent steps.\n    ;;\nesac\n```\n\nCheck if the target path already exists:\n\n```bash\nif [ -d \"$WORKTREE_PATH\" ] || [ -f \"$WORKTREE_PATH\" ]; then\n  echo \"ERROR: Target path already exists: $WORKTREE_PATH\"\n  echo \"Remove it manually or choose a different base_path in .specify\u002Fextensions\u002Fspex-worktrees\u002Fworktree-config.yml\"\n  # Stop here. Do not proceed to subsequent steps.\nfi\n```\n\n### Step 5: Commit All Tracked Changes to Feature Branch\n\nBefore switching away from the feature branch, commit all modified tracked files. This includes spec files, `.specify\u002F` configuration changes, and any other modified tracked files. Stage changes in two passes to avoid capturing unintended untracked files:\n\n```bash\n# Stage modifications to already-tracked files\ngit add -u\n\n# Stage new spec and brainstorm artifacts (these are untracked but expected)\n# Read the actual spec directory from feature.json (may differ from branch name\n# when feature numbering is sequential but branch uses issue numbers)\nSPEC_DIR=\"\"\nif [ -f \".specify\u002Ffeature.json\" ]; then\n  SPEC_DIR=$(jq -r '.feature_directory \u002F\u002F empty' \".specify\u002Ffeature.json\" 2>\u002Fdev\u002Fnull)\nfi\nSPEC_DIR=\"${SPEC_DIR:-specs\u002F$BRANCH_NAME}\"\n[ -d \"$SPEC_DIR\" ] && git add \"$SPEC_DIR\"\n[ -d \"brainstorm\" ] && git add brainstorm\u002F\n[ -d \".specify\" ] && git add .specify\u002F\n\nif ! git diff --cached --quiet; then\n  git commit -m \"feat: Add spec for $BRANCH_NAME\n\nAssisted-By: 🤖 Claude Code\"\nfi\n```\n\nUsing `git add -u` (tracked modifications only) plus explicit paths for new spec artifacts limits the commit scope to intended files. The `git diff --cached --quiet` guard skips the commit when there are no staged changes, avoiding empty commits.\n\n### Step 5b: Capture Feature Directory and Flow State Before Branch Switch\n\nThe next step switches to the default branch, which changes tracked files on disk. Since `.specify\u002Ffeature.json` is tracked, its contents will revert to whatever the default branch has. And `.specify\u002F.spex-state` is gitignored, so it won't survive the branch switch. Capture both now, while still on the feature branch:\n\n```bash\nFEATURE_DIR=\"\"\nif [ -f \".specify\u002Ffeature.json\" ]; then\n  FEATURE_DIR=$(jq -r '.feature_directory \u002F\u002F empty' \".specify\u002Ffeature.json\")\nfi\n# Fallback to branch-derived path if feature.json is missing or empty\nFEATURE_DIR=${FEATURE_DIR:-\"specs\u002F$BRANCH_NAME\"}\n\n# Capture flow state content (gitignored, will be lost on branch switch)\nSPEX_STATE_CONTENT=\"\"\nif [ -f \".specify\u002F.spex-state\" ]; then\n  SPEX_STATE_CONTENT=$(cat \".specify\u002F.spex-state\")\nfi\n```\n\nThese values are used in Step 8b to set the correct feature context in the worktree.\n\n### Step 6: Restore Default Branch (before worktree creation)\n\nGit does not allow two worktrees to have the same branch checked out. Since `speckit-specify` just created and checked out the feature branch, we must switch back to the default branch before creating a worktree for that branch.\n\nDetect the default branch dynamically with a fallback chain:\n\n```bash\nDEFAULT_BRANCH=$(git symbolic-ref refs\u002Fremotes\u002Forigin\u002FHEAD 2>\u002Fdev\u002Fnull | sed 's@^refs\u002Fremotes\u002Forigin\u002F@@')\nif [ -z \"$DEFAULT_BRANCH\" ]; then\n  # origin\u002FHEAD not set (common with git init + remote add). Try common names.\n  for candidate in main master; do\n    if git rev-parse --verify \"$candidate\" >\u002Fdev\u002Fnull 2>&1; then\n      DEFAULT_BRANCH=\"$candidate\"\n      break\n    fi\n  done\nfi\nDEFAULT_BRANCH=${DEFAULT_BRANCH:-main}\n```\n\n```bash\nif ! git checkout \"$DEFAULT_BRANCH\" 2>&1; then\n  echo \"WARNING: Could not switch back to $DEFAULT_BRANCH.\"\n  echo \"You likely have uncommitted changes. Commit or stash them first.\"\n  echo \"The repository remains on branch $BRANCH_NAME.\"\n  echo \"Worktree creation skipped (cannot create worktree while branch is checked out here).\"\n  # Stop here. Do not proceed to subsequent steps.\nfi\n```\n\n### Step 7: Create the Worktree\n\nNow that the current worktree is on the default branch, create a new worktree for the feature branch. If this fails (disk full, permission denied, etc.), report the error clearly:\n\n```bash\nif ! git worktree add \"$WORKTREE_PATH\" \"$BRANCH_NAME\" 2>&1; then\n  echo \"ERROR: Failed to create worktree at $WORKTREE_PATH\"\n  echo \"The repository is on $DEFAULT_BRANCH. The feature branch $BRANCH_NAME still exists.\"\n  echo \"Resolve the issue and retry, or switch to the branch manually: git checkout $BRANCH_NAME\"\n  # Stop here. Do not proceed to subsequent steps.\nfi\n```\n\n### Step 8: Copy Configuration to Worktree\n\nGitignored config directories (`.claude\u002F` and `.specify\u002F`) won't exist in the new worktree. Copy them so spec-kit extensions, skills, and settings work immediately without re-running init:\n\n```bash\n# Copy .specify\u002F (extensions registry, hooks, state, config)\nif [ -d \".specify\" ]; then\n  rsync -a --exclude='.git' \".specify\u002F\" \"$WORKTREE_PATH\u002F.specify\u002F\"\nfi\n# Copy .claude\u002F (skills, settings, commands)\n# Exclude worktrees\u002F to avoid copying nested worktrees when base_path is .claude\u002Fworktrees\nif [ -d \".claude\" ]; then\n  rsync -a --exclude='worktrees\u002F' \".claude\u002F\" \"$WORKTREE_PATH\u002F.claude\u002F\"\nfi\n```\n\nIf the spec directory exists in the main repo but not in the worktree (e.g., when specs are gitignored or were not committed), copy it:\n\n```bash\n# Copy spec directory if it exists locally but not in the worktree\n# (happens when specs are gitignored\u002Fexcluded, or when git add missed them)\nif [ -n \"$FEATURE_DIR\" ] && [ -d \"$FEATURE_DIR\" ] && [ ! -d \"$WORKTREE_PATH\u002F$FEATURE_DIR\" ]; then\n  mkdir -p \"$WORKTREE_PATH\u002F$(dirname \"$FEATURE_DIR\")\"\n  rsync -a \"$FEATURE_DIR\u002F\" \"$WORKTREE_PATH\u002F$FEATURE_DIR\u002F\"\nfi\n```\n\nThis ensures the worktree has the same extensions, hooks, permissions, skills, and spec files as the main repo. No `\u002Fspex:init` needed in the worktree.\n\n### Step 8b: Update feature.json and flow state for the Worktree Branch\n\nThe copied `.specify\u002Ffeature.json` may point to whatever feature was active on the default branch (since feature.json is tracked and reverts on branch switch). Write the correct value captured in Step 5b:\n\n```bash\nFEATURE_JSON=\"$WORKTREE_PATH\u002F.specify\u002Ffeature.json\"\njq -n --arg dir \"$FEATURE_DIR\" '{\"feature_directory\": $dir}' > \"$FEATURE_JSON\"\n```\n\nThis writes the `FEATURE_DIR` value captured in Step 5b, which reflects the actual spec directory created by speckit-specify (not a branch-name derivation that may differ).\n\nThe `.specify\u002F.spex-state` file is gitignored but persists on disk across branch switches. It may still be present in the main repo after `git checkout $DEFAULT_BRANCH`. Restore it to the worktree from the content captured in Step 5b, then remove it from the main repo to prevent the statusline from showing stale state:\n\n```bash\nSTATE_FILE=\"$WORKTREE_PATH\u002F.specify\u002F.spex-state\"\nif [ -n \"$SPEX_STATE_CONTENT\" ]; then\n  echo \"$SPEX_STATE_CONTENT\" | jq --arg branch \"$BRANCH_NAME\" --arg dir \"$FEATURE_DIR\" \\\n    '.feature_branch = $branch | .spec_dir = $dir' > \"$STATE_FILE\"\nfi\n\n# Remove stale state from main repo — the pipeline continues in the worktree\nrm -f \".specify\u002F.spex-state\"\n```\n\nThis restores the flow state (including any quality gate results from the specify phase) in the worktree and ensures the main repo's statusline does not display stale pipeline progress.\n\n### Step 9: Print Output\n\nPrint a machine-readable line followed by human-readable instructions:\n\n```bash\necho \"WORKTREE_CREATED path=$WORKTREE_PATH\"\n```\n\nThen check whether this is running inside a ship pipeline:\n\n```bash\nif [ -n \"$SPEX_STATE_CONTENT\" ] && echo \"$SPEX_STATE_CONTENT\" | jq -e '.status == \"running\"' >\u002Fdev\u002Fnull 2>&1; then\n  # Pipeline mode: suppress the completion box to avoid stalling the pipeline.\n  # Ship will handle the CWD switch and continue to the next stage.\n  echo \"Worktree created at $WORKTREE_PATH (pipeline mode, continuing)\"\nelse\n  # Interactive mode: print full instructions for the user.\nfi\n```\n\n**Interactive mode output** (when NOT in pipeline mode):\n\nFor inside-project worktrees, show the relative path (e.g., `.claude\u002Fworktrees\u002F032-feature`). For external worktrees, show the absolute path.\n\n```\n┌─────────────────────────────────────────────────────────────┐\n│ Worktree created at \u003Cdisplay-path>                          │\n│                                                             │\n│ To continue with planning\u002Fimplementation:                   │\n│   cd \u003Cworktree-path> && claude                              │\n│                                                             │\n│ Config (.claude\u002F and .specify\u002F) has been copied.            │\n│ All extensions and skills are ready to use.                 │\n│                                                             │\n│ The spec file contains all context from this session.       │\n└─────────────────────────────────────────────────────────────┘\n```\n\nWhere `\u003Cdisplay-path>` is `.claude\u002Fworktrees\u002F\u003Cbranch>` for inside-project worktrees, or the full absolute path for external worktrees.\n\nUse the actual `WORKTREE_PATH` value (computed in Step 4) in the output.\n\n## Action: Ensure\n\nCalled by the `before_implement` hook to verify worktree isolation before implementation starts. This closes the gap in multi-session workflows where `specify` and `implement` run in different conversations.\n\n### Step 1: Check if Already in a Worktree\n\n```bash\nREPO_ROOT=$(git rev-parse --show-toplevel)\nGIT_DIR=$(git rev-parse --git-dir)\n\nif [ \"$GIT_DIR\" != \"$REPO_ROOT\u002F.git\" ] && [ \"$GIT_DIR\" != \".git\" ]; then\n  # Already in a worktree — isolation exists, nothing to do\n  exit 0\nfi\n```\n\nIf already in a worktree, stop here (success). Implementation can proceed.\n\n### Step 2: Check if on a Feature Branch\n\n```bash\nBRANCH_NAME=$(git rev-parse --abbrev-ref HEAD)\n```\n\nIf the branch does NOT match the `NNN-feature-name` pattern, skip silently. This is not a feature branch, so worktree isolation does not apply.\n\n### Step 3: Check if a Worktree Already Exists for This Branch\n\n```bash\nWORKTREE_CONFIG=\".specify\u002Fextensions\u002Fspex-worktrees\u002Fworktree-config.yml\"\nBASE_PATH=$(yq -r '.worktrees.base_path \u002F\u002F \".claude\u002Fworktrees\"' \"$WORKTREE_CONFIG\" 2>\u002Fdev\u002Fnull || echo \".claude\u002Fworktrees\")\nWORKTREE_PATH=\"$REPO_ROOT\u002F$BASE_PATH\u002F$BRANCH_NAME\"\n\nif git worktree list --porcelain | grep -q \"worktree.*$BRANCH_NAME\"; then\n  echo \"WARNING: A worktree for branch $BRANCH_NAME already exists but you are not in it.\"\n  echo \"Switch to the worktree before implementing:\"\n  echo \"  cd $WORKTREE_PATH && claude\"\n  # Stop here. Do not create a duplicate worktree.\nfi\n```\n\n### Step 4: Offer to Create a Worktree\n\nPresent a single-select question to the user:\n- header: \"Worktree\"\n- question: \"Implementation is about to start without worktree isolation. Create a worktree now?\"\n- options:\n  - \"Create worktree (Recommended)\": \"Isolate implementation in a git worktree\"\n  - \"Continue without worktree\": \"Implement directly on the current branch (no isolation)\"\n\nIf the user selects \"Create worktree\", execute the full **Action: Create** flow (Steps 1-9 above).\n\nIf the user selects \"Continue without worktree\", proceed without isolation.\n\n## Action: List\n\nShow all active feature worktrees for the project.\n\n### Step 1: Get Worktree List\n\n```bash\ngit worktree list --porcelain\n```\n\nParse the output. Each worktree entry has:\n- `worktree \u003Cpath>`\n- `HEAD \u003Ccommit>`\n- `branch refs\u002Fheads\u002F\u003Cbranch-name>`\n\n### Step 2: Filter Feature Branches\n\nOnly show worktrees whose branch matches the `NNN-*` feature branch pattern (three-digit prefix followed by a hyphen).\n\nSkip the main worktree (the original repo).\n\n### Step 3: Format Output\n\nDisplay a table with worktree directory names (`@` separator):\n\n```\nActive Feature Worktrees:\n\n  Path                              Branch              Feature\n  ─────────────────────────────────────────────────────────────\n  .claude\u002Fworktrees\u002F004-user-auth   004-user-auth       user-auth\n  .claude\u002Fworktrees\u002F007-worktrees   007-worktrees-trait  worktrees-trait\n```\n\nFor inside-project worktrees, show the relative path (`.claude\u002Fworktrees\u002F\u003Cbranch>`). For external worktrees, show the last path component (`repo@branch`).\n\nIf no feature worktrees exist:\n\n```\nNo active feature worktrees found.\n\nCreate one by running \u002Fspeckit-specify with the worktrees extension enabled.\n```\n\n## Action: Finish\n\nMerges the current worktree's feature branch into the default branch and removes the worktree. This is the recommended way to complete work in a spex worktree.\n\n{harness:worktree-isolation}\nSpex worktrees are managed via `git worktree add` and `git worktree remove` commands directly.\nDo NOT use harness-specific worktree tools, as spex worktrees are created independently.\nAlways use git commands for worktree operations.\n{\u002Fharness:worktree-isolation}\n\n### Step 1: Verify We're in a Worktree\n\n```bash\nREPO_ROOT=$(git rev-parse --show-toplevel)\nGIT_DIR=$(git rev-parse --git-dir)\n\n# A worktree has a .git file (not directory) pointing to the main repo\nif [ \"$GIT_DIR\" = \"$REPO_ROOT\u002F.git\" ] || [ \"$GIT_DIR\" = \".git\" ]; then\n  echo \"ERROR: Not inside a git worktree. Use 'finish' from within a spex worktree.\"\n  # Stop here.\nfi\n```\n\n### Step 2: Get Branch and Main Worktree Info\n\n```bash\nBRANCH_NAME=$(git rev-parse --abbrev-ref HEAD)\nWORKTREE_PATH=$(git rev-parse --show-toplevel)\n\n# Find the main worktree (first entry in worktree list)\nMAIN_WORKTREE=$(git worktree list --porcelain | head -1 | sed 's\u002F^worktree \u002F\u002F')\n\n# Detect default branch\nDEFAULT_BRANCH=$(git symbolic-ref refs\u002Fremotes\u002Forigin\u002FHEAD 2>\u002Fdev\u002Fnull | sed 's@^refs\u002Fremotes\u002Forigin\u002F@@')\nif [ -z \"$DEFAULT_BRANCH\" ]; then\n  for candidate in main master; do\n    if git rev-parse --verify \"$candidate\" >\u002Fdev\u002Fnull 2>&1; then\n      DEFAULT_BRANCH=\"$candidate\"\n      break\n    fi\n  done\nfi\nDEFAULT_BRANCH=${DEFAULT_BRANCH:-main}\n```\n\n### Step 3: Ensure All Changes Are Committed\n\n```bash\nif ! git diff --quiet || ! git diff --cached --quiet; then\n  echo \"ERROR: Uncommitted changes in worktree. Commit or stash before finishing.\"\n  # Stop here.\nfi\n```\n\n### Step 4: Ask User How to Proceed\n\n{harness:interactive-choice} (single-select, header: \"Finish\"):\n- \"Merge and remove (Recommended)\": \"Fast-forward merge branch into default, remove worktree and branch\"\n- \"Remove only\": \"Remove worktree and branch without merging (changes stay in git reflog)\"\n- \"Cancel\": \"Keep worktree as-is\"\n\nIf \"Cancel\": stop.\n\n### Step 5: Switch CWD to Main Worktree\n\n**CRITICAL:** Switch the working directory to the main worktree BEFORE doing anything destructive. If cwd is inside the worktree being removed, all subsequent Bash commands will fail with \"path does not exist\".\n\n```bash\ncd \"$MAIN_WORKTREE\"\n```\n\n### Step 6: Merge (if selected)\n\nIf the user chose \"Merge and remove\":\n\n```bash\ncd \"$MAIN_WORKTREE\"\ngit checkout \"$DEFAULT_BRANCH\"\ngit merge --ff-only \"$BRANCH_NAME\" 2>&1\n```\n\nIf fast-forward merge fails (branches diverged), ask the user:\n\n{harness:interactive-choice} (single-select, header: \"Merge\"):\n- \"Create merge commit\": \"Merge with a merge commit (branches have diverged)\"\n- \"Abort\": \"Keep worktree, resolve manually\"\n\nIf \"Create merge commit\":\n```bash\ngit merge \"$BRANCH_NAME\" -m \"Merge branch '$BRANCH_NAME'\n\nAssisted-By: 🤖 Claude Code\" 2>&1\n```\n\nIf \"Abort\": stop. The cwd is already at the main worktree, so the user can navigate back.\n\n### Step 7: Remove Worktree and Branch\n\n```bash\n# Remove worktree (cwd is already at main worktree from Step 5)\ngit worktree remove \"$WORKTREE_PATH\" 2>&1\n\n# Delete the feature branch (it's merged or user chose remove-only)\ngit branch -d \"$BRANCH_NAME\" 2>&1 || git branch -D \"$BRANCH_NAME\" 2>&1\n```\n\n### Step 8: Clear Flow State\n\n```bash\nSTATE_FILE=\".specify\u002F.spex-state\"\nif [ -f \"$STATE_FILE\" ]; then\n  rm -f \"$STATE_FILE\"\nfi\n```\n\n### Step 9: Report\n\n```\n┌─────────────────────────────────────────────────────────┐\n│ Feature branch \u003Cbranch> finished.                       │\n│                                                         │\n│ - Merged to \u003Cdefault-branch> (if selected)              │\n│ - Worktree removed: \u003Cworktree-path>                     │\n│ - Branch deleted: \u003Cbranch>                              │\n│ - Flow state cleared                                    │\n│                                                         │\n│ You are now in the main repo on \u003Cdefault-branch>.       │\n└─────────────────────────────────────────────────────────┘\n```\n\nIf the user wants to push: `git push origin $DEFAULT_BRANCH`\n\n## Action: Cleanup\n\nDetect worktrees whose branches are merged and offer removal.\n\n### Step 1: Get Merged Branches\n\n```bash\n# Detect default branch with fallback chain\nDEFAULT_BRANCH=$(git symbolic-ref refs\u002Fremotes\u002Forigin\u002FHEAD 2>\u002Fdev\u002Fnull | sed 's@^refs\u002Fremotes\u002Forigin\u002F@@')\nif [ -z \"$DEFAULT_BRANCH\" ]; then\n  for candidate in main master; do\n    if git rev-parse --verify \"$candidate\" >\u002Fdev\u002Fnull 2>&1; then\n      DEFAULT_BRANCH=\"$candidate\"\n      break\n    fi\n  done\nfi\nDEFAULT_BRANCH=${DEFAULT_BRANCH:-main}\n\n# Get all feature branches merged into the default branch\nMERGED_BRANCHES=$(git branch --merged \"$DEFAULT_BRANCH\" | sed 's\u002F^[+* ]*\u002F\u002F' | grep -E '^[0-9]{3}-')\n```\n\n### Step 2: Cross-Reference with Worktrees\n\nFor each worktree with a feature branch, check if its branch appears in the merged list.\n\n### Step 3: Handle Merged Worktrees\n\nFor each merged worktree, present it to the user and ask for confirmation:\n\n```\nWorktree cc-spex@004-user-auth (branch 004-user-auth) is merged into main.\nRemove this worktree? (yes\u002Fno)\n```\n\nIf the user confirms, first switch to the main repo root (to avoid cwd pointing at the deleted directory), then remove the worktree:\n\n```bash\n# Switch cwd to the main worktree BEFORE removing the feature worktree.\n# If cwd is inside the worktree being removed, all subsequent commands will\n# fail with \"Path does not exist\" because the Bash tool persists cwd.\nMAIN_WORKTREE=$(git worktree list --porcelain | head -1 | sed 's\u002F^worktree \u002F\u002F')\ncd \"$MAIN_WORKTREE\"\ngit worktree remove \u003Cpath>\ngit branch -d \u003Cbranch-name>\n```\n\n### Step 4: Handle Unmerged Worktrees\n\nFor worktrees with unmerged branches, warn the user:\n\n```\nWorktree cc-spex@007-worktrees-trait (branch 007-worktrees-trait) has NOT been merged.\nSkipping. Use --force to remove unmerged worktrees (data may be lost).\n```\n\nOnly remove unmerged worktrees if the user explicitly confirms after seeing the warning.\n\n---\n\n## Worktree Context for Downstream Commands\n\nWhen running in a worktree created by this extension, downstream spec-kit commands should be aware of the worktree context:\n\n### Planning Context\n\nYou are likely running in a worktree created by the `worktrees` extension. The spec file in this worktree contains all decisions from the brainstorm\u002Fspecify session. No separate handoff file is needed.\n\n### Implementation Context\n\nYou are likely running in a worktree created by the `worktrees` extension. The spec and plan files in this worktree contain all context needed for implementation. No separate handoff file is needed.","# Git Worktree Management for spex\n\n## Overview\n\nThis command manages git worktrees to isolate feature development. It supports four actions:\n\n- **create**: Called by the `after_specify` hook after `speckit-specify` completes. Creates a worktree, restores `main`, and prints switch instructions.\n- **ensure**: Called by the `before_implement` hook. Verifies worktree isolation exists. If already in a worktree, proceeds silently. If not, creates one (same as `create`).\n- **list**: Shows all active feature worktrees with path, branch, and feature name.\n- **finish**: Merges the current worktree's branch into the default branch and removes the worktree. Use when implementation is complete.\n- **cleanup**: Detects worktrees whose branches are merged and offers removal.\n\n## Action Routing\n\nDetermine the action from the argument:\n\n- If invoked with argument `create` (from the `after_specify` hook): the action is **create**. Execute immediately, no confirmation needed.\n- If invoked with argument `ensure` (from the `before_implement` hook): the action is **ensure**. See Action: Ensure below.\n- If invoked with argument `finish`: the action is **finish**.\n- If invoked with argument `cleanup`: the action is **cleanup**.\n- Otherwise (no args, `list`, or invoked directly): the action is **list**.\n\n## Prerequisites\n\nThe project must be a git repository.\n\n```bash\ngit rev-parse --git-dir >\u002Fdev\u002Fnull 2>&1 || { echo \"ERROR: Not a git repository\"; exit 1; }\n```\n\n## Action: Create\n\nThis action runs after `speckit-specify` has created a feature branch and spec files.\n\n### Step 1: Read Configuration\n\nRead `base_path` from the worktrees extension config (or default to `.claude\u002Fworktrees`):\n\n```bash\nWORKTREE_CONFIG=\".specify\u002Fextensions\u002Fspex-worktrees\u002Fworktree-config.yml\"\nBASE_PATH=$(yq -r '.worktrees.base_path \u002F\u002F \".claude\u002Fworktrees\"' \"$WORKTREE_CONFIG\" 2>\u002Fdev\u002Fnull || echo \".claude\u002Fworktrees\")\n```\n\nDefault: `.claude\u002Fworktrees` (inside the project directory, keeps CWD stable for the coding agent).\n\n### Step 2: Get Current Branch\n\n```bash\nBRANCH_NAME=$(git rev-parse --abbrev-ref HEAD)\n```\n\nVerify it matches the `NNN-feature-name` pattern. If not, warn that worktree creation only applies to feature branches and skip.\n\n### Step 3: Detect If Already in a Worktree\n\nA git worktree has a `.git` file (not directory) pointing to the main repo. Detect this:\n\n```bash\nREPO_ROOT=$(git rev-parse --show-toplevel)\nGIT_DIR=$(git rev-parse --git-dir)\n\n# If git-dir is not \u003Crepo>\u002F.git, we're inside a worktree\nif [ \"$GIT_DIR\" != \"$REPO_ROOT\u002F.git\" ] && [ \"$GIT_DIR\" != \".git\" ]; then\n  echo \"WARNING: Already inside a git worktree. Skipping worktree creation.\"\n  echo \"Worktree nesting is not supported.\"\n  # Stop here. Do not proceed to subsequent steps.\nfi\n```\n\nIf inside a worktree, skip the entire create action. Do not proceed to any subsequent Create steps.\n\n### Step 4: Compute Target Path and Validate\n\nDetermine if the worktree should be inside or outside the project, then build the path:\n\n```bash\nREPO_ROOT=$(git rev-parse --show-toplevel)\n\n# Detect inside-project worktrees (.claude\u002Fworktrees and .worktrees are allowed)\nINSIDE_PROJECT=false\ncase \"$BASE_PATH\" in\n  .claude\u002Fworktrees*|.worktrees*) INSIDE_PROJECT=true ;;\nesac\n```\n\n**If inside project** (`INSIDE_PROJECT` is `true`):\n\n```bash\nmkdir -p \"$REPO_ROOT\u002F$BASE_PATH\"\nWORKTREE_PATH=\"$REPO_ROOT\u002F$BASE_PATH\u002F$BRANCH_NAME\"\n```\n\n**If outside project** (`INSIDE_PROJECT` is `false`):\n\n```bash\nREPO_NAME=$(basename \"$REPO_ROOT\")\n\n# Handle both absolute and relative base paths\nif [[ \"$BASE_PATH\" = \u002F* ]]; then\n  RESOLVED_BASE=$(cd \"$BASE_PATH\" && pwd)\nelse\n  RESOLVED_BASE=$(cd \"$REPO_ROOT\u002F$BASE_PATH\" && pwd)\nfi\n```\n\nIf the `cd` fails (directory does not exist), report a clear error and stop:\n\n```bash\nif [ -z \"$RESOLVED_BASE\" ]; then\n  echo \"ERROR: base_path '$BASE_PATH' does not resolve to a valid directory.\"\n  echo \"Check worktrees.base_path in .specify\u002Fextensions\u002Fspex-worktrees\u002Fworktree-config.yml\"\n  # Stop here. Do not proceed to subsequent steps.\nfi\n```\n\nBuild the worktree path using `@` as separator between repo name and branch:\n\n```bash\nWORKTREE_PATH=\"${RESOLVED_BASE}\u002F${REPO_NAME}@${BRANCH_NAME}\"\n```\n\n**For both paths**, verify the worktree is not inside the main repository in a disallowed location:\n\n```bash\ncase \"$WORKTREE_PATH\" in\n  \"$REPO_ROOT\"\u002F.claude\u002Fworktrees\u002F*|\"$REPO_ROOT\"\u002F.worktrees\u002F*)\n    ;; # Allowed: inside .claude\u002Fworktrees\u002F or .worktrees\u002F\n  \"$REPO_ROOT\"\u002F*)\n    echo \"ERROR: Worktree path is inside the main repository: $WORKTREE_PATH\"\n    echo \"Set base_path to '.claude\u002Fworktrees', '.worktrees', or a directory outside the repo\"\n    # Stop here. Do not proceed to subsequent steps.\n    ;;\nesac\n```\n\nCheck if the target path already exists:\n\n```bash\nif [ -d \"$WORKTREE_PATH\" ] || [ -f \"$WORKTREE_PATH\" ]; then\n  echo \"ERROR: Target path already exists: $WORKTREE_PATH\"\n  echo \"Remove it manually or choose a different base_path in .specify\u002Fextensions\u002Fspex-worktrees\u002Fworktree-config.yml\"\n  # Stop here. Do not proceed to subsequent steps.\nfi\n```\n\n### Step 5: Commit All Tracked Changes to Feature Branch\n\nBefore switching away from the feature branch, commit all modified tracked files. This includes spec files, `.specify\u002F` configuration changes, and any other modified tracked files. Stage changes in two passes to avoid capturing unintended untracked files:\n\n```bash\n# Stage modifications to already-tracked files\ngit add -u\n\n# Stage new spec and brainstorm artifacts (these are untracked but expected)\n# Read the actual spec directory from feature.json (may differ from branch name\n# when feature numbering is sequential but branch uses issue numbers)\nSPEC_DIR=\"\"\nif [ -f \".specify\u002Ffeature.json\" ]; then\n  SPEC_DIR=$(jq -r '.feature_directory \u002F\u002F empty' \".specify\u002Ffeature.json\" 2>\u002Fdev\u002Fnull)\nfi\nSPEC_DIR=\"${SPEC_DIR:-specs\u002F$BRANCH_NAME}\"\n[ -d \"$SPEC_DIR\" ] && git add \"$SPEC_DIR\"\n[ -d \"brainstorm\" ] && git add brainstorm\u002F\n[ -d \".specify\" ] && git add .specify\u002F\n\nif ! git diff --cached --quiet; then\n  git commit -m \"feat: Add spec for $BRANCH_NAME\n\nAssisted-By: 🤖 Claude Code\"\nfi\n```\n\nUsing `git add -u` (tracked modifications only) plus explicit paths for new spec artifacts limits the commit scope to intended files. The `git diff --cached --quiet` guard skips the commit when there are no staged changes, avoiding empty commits.\n\n### Step 5b: Capture Feature Directory and Flow State Before Branch Switch\n\nThe next step switches to the default branch, which changes tracked files on disk. Since `.specify\u002Ffeature.json` is tracked, its contents will revert to whatever the default branch has. And `.specify\u002F.spex-state` is gitignored, so it won't survive the branch switch. Capture both now, while still on the feature branch:\n\n```bash\nFEATURE_DIR=\"\"\nif [ -f \".specify\u002Ffeature.json\" ]; then\n  FEATURE_DIR=$(jq -r '.feature_directory \u002F\u002F empty' \".specify\u002Ffeature.json\")\nfi\n# Fallback to branch-derived path if feature.json is missing or empty\nFEATURE_DIR=${FEATURE_DIR:-\"specs\u002F$BRANCH_NAME\"}\n\n# Capture flow state content (gitignored, will be lost on branch switch)\nSPEX_STATE_CONTENT=\"\"\nif [ -f \".specify\u002F.spex-state\" ]; then\n  SPEX_STATE_CONTENT=$(cat \".specify\u002F.spex-state\")\nfi\n```\n\nThese values are used in Step 8b to set the correct feature context in the worktree.\n\n### Step 6: Restore Default Branch (before worktree creation)\n\nGit does not allow two worktrees to have the same branch checked out. Since `speckit-specify` just created and checked out the feature branch, we must switch back to the default branch before creating a worktree for that branch.\n\nDetect the default branch dynamically with a fallback chain:\n\n```bash\nDEFAULT_BRANCH=$(git symbolic-ref refs\u002Fremotes\u002Forigin\u002FHEAD 2>\u002Fdev\u002Fnull | sed 's@^refs\u002Fremotes\u002Forigin\u002F@@')\nif [ -z \"$DEFAULT_BRANCH\" ]; then\n  # origin\u002FHEAD not set (common with git init + remote add). Try common names.\n  for candidate in main master; do\n    if git rev-parse --verify \"$candidate\" >\u002Fdev\u002Fnull 2>&1; then\n      DEFAULT_BRANCH=\"$candidate\"\n      break\n    fi\n  done\nfi\nDEFAULT_BRANCH=${DEFAULT_BRANCH:-main}\n```\n\n```bash\nif ! git checkout \"$DEFAULT_BRANCH\" 2>&1; then\n  echo \"WARNING: Could not switch back to $DEFAULT_BRANCH.\"\n  echo \"You likely have uncommitted changes. Commit or stash them first.\"\n  echo \"The repository remains on branch $BRANCH_NAME.\"\n  echo \"Worktree creation skipped (cannot create worktree while branch is checked out here).\"\n  # Stop here. Do not proceed to subsequent steps.\nfi\n```\n\n### Step 7: Create the Worktree\n\nNow that the current worktree is on the default branch, create a new worktree for the feature branch. If this fails (disk full, permission denied, etc.), report the error clearly:\n\n```bash\nif ! git worktree add \"$WORKTREE_PATH\" \"$BRANCH_NAME\" 2>&1; then\n  echo \"ERROR: Failed to create worktree at $WORKTREE_PATH\"\n  echo \"The repository is on $DEFAULT_BRANCH. The feature branch $BRANCH_NAME still exists.\"\n  echo \"Resolve the issue and retry, or switch to the branch manually: git checkout $BRANCH_NAME\"\n  # Stop here. Do not proceed to subsequent steps.\nfi\n```\n\n### Step 8: Copy Configuration to Worktree\n\nGitignored config directories (`.claude\u002F` and `.specify\u002F`) won't exist in the new worktree. Copy them so spec-kit extensions, skills, and settings work immediately without re-running init:\n\n```bash\n# Copy .specify\u002F (extensions registry, hooks, state, config)\nif [ -d \".specify\" ]; then\n  rsync -a --exclude='.git' \".specify\u002F\" \"$WORKTREE_PATH\u002F.specify\u002F\"\nfi\n# Copy .claude\u002F (skills, settings, commands)\n# Exclude worktrees\u002F to avoid copying nested worktrees when base_path is .claude\u002Fworktrees\nif [ -d \".claude\" ]; then\n  rsync -a --exclude='worktrees\u002F' \".claude\u002F\" \"$WORKTREE_PATH\u002F.claude\u002F\"\nfi\n```\n\nIf the spec directory exists in the main repo but not in the worktree (e.g., when specs are gitignored or were not committed), copy it:\n\n```bash\n# Copy spec directory if it exists locally but not in the worktree\n# (happens when specs are gitignored\u002Fexcluded, or when git add missed them)\nif [ -n \"$FEATURE_DIR\" ] && [ -d \"$FEATURE_DIR\" ] && [ ! -d \"$WORKTREE_PATH\u002F$FEATURE_DIR\" ]; then\n  mkdir -p \"$WORKTREE_PATH\u002F$(dirname \"$FEATURE_DIR\")\"\n  rsync -a \"$FEATURE_DIR\u002F\" \"$WORKTREE_PATH\u002F$FEATURE_DIR\u002F\"\nfi\n```\n\nThis ensures the worktree has the same extensions, hooks, permissions, skills, and spec files as the main repo. No `\u002Fspex:init` needed in the worktree.\n\n### Step 8b: Update feature.json and flow state for the Worktree Branch\n\nThe copied `.specify\u002Ffeature.json` may point to whatever feature was active on the default branch (since feature.json is tracked and reverts on branch switch). Write the correct value captured in Step 5b:\n\n```bash\nFEATURE_JSON=\"$WORKTREE_PATH\u002F.specify\u002Ffeature.json\"\njq -n --arg dir \"$FEATURE_DIR\" '{\"feature_directory\": $dir}' > \"$FEATURE_JSON\"\n```\n\nThis writes the `FEATURE_DIR` value captured in Step 5b, which reflects the actual spec directory created by speckit-specify (not a branch-name derivation that may differ).\n\nThe `.specify\u002F.spex-state` file is gitignored but persists on disk across branch switches. It may still be present in the main repo after `git checkout $DEFAULT_BRANCH`. Restore it to the worktree from the content captured in Step 5b, then remove it from the main repo to prevent the statusline from showing stale state:\n\n```bash\nSTATE_FILE=\"$WORKTREE_PATH\u002F.specify\u002F.spex-state\"\nif [ -n \"$SPEX_STATE_CONTENT\" ]; then\n  echo \"$SPEX_STATE_CONTENT\" | jq --arg branch \"$BRANCH_NAME\" --arg dir \"$FEATURE_DIR\" \\\n    '.feature_branch = $branch | .spec_dir = $dir' > \"$STATE_FILE\"\nfi\n\n# Remove stale state from main repo — the pipeline continues in the worktree\nrm -f \".specify\u002F.spex-state\"\n```\n\nThis restores the flow state (including any quality gate results from the specify phase) in the worktree and ensures the main repo's statusline does not display stale pipeline progress.\n\n### Step 9: Print Output\n\nPrint a machine-readable line followed by human-readable instructions:\n\n```bash\necho \"WORKTREE_CREATED path=$WORKTREE_PATH\"\n```\n\nThen check whether this is running inside a ship pipeline:\n\n```bash\nif [ -n \"$SPEX_STATE_CONTENT\" ] && echo \"$SPEX_STATE_CONTENT\" | jq -e '.status == \"running\"' >\u002Fdev\u002Fnull 2>&1; then\n  # Pipeline mode: suppress the completion box to avoid stalling the pipeline.\n  # Ship will handle the CWD switch and continue to the next stage.\n  echo \"Worktree created at $WORKTREE_PATH (pipeline mode, continuing)\"\nelse\n  # Interactive mode: print full instructions for the user.\nfi\n```\n\n**Interactive mode output** (when NOT in pipeline mode):\n\nFor inside-project worktrees, show the relative path (e.g., `.claude\u002Fworktrees\u002F032-feature`). For external worktrees, show the absolute path.\n\n```\n┌─────────────────────────────────────────────────────────────┐\n│ Worktree created at \u003Cdisplay-path>                          │\n│                                                             │\n│ To continue with planning\u002Fimplementation:                   │\n│   cd \u003Cworktree-path> && claude                              │\n│                                                             │\n│ Config (.claude\u002F and .specify\u002F) has been copied.            │\n│ All extensions and skills are ready to use.                 │\n│                                                             │\n│ The spec file contains all context from this session.       │\n└─────────────────────────────────────────────────────────────┘\n```\n\nWhere `\u003Cdisplay-path>` is `.claude\u002Fworktrees\u002F\u003Cbranch>` for inside-project worktrees, or the full absolute path for external worktrees.\n\nUse the actual `WORKTREE_PATH` value (computed in Step 4) in the output.\n\n## Action: Ensure\n\nCalled by the `before_implement` hook to verify worktree isolation before implementation starts. This closes the gap in multi-session workflows where `specify` and `implement` run in different conversations.\n\n### Step 1: Check if Already in a Worktree\n\n```bash\nREPO_ROOT=$(git rev-parse --show-toplevel)\nGIT_DIR=$(git rev-parse --git-dir)\n\nif [ \"$GIT_DIR\" != \"$REPO_ROOT\u002F.git\" ] && [ \"$GIT_DIR\" != \".git\" ]; then\n  # Already in a worktree — isolation exists, nothing to do\n  exit 0\nfi\n```\n\nIf already in a worktree, stop here (success). Implementation can proceed.\n\n### Step 2: Check if on a Feature Branch\n\n```bash\nBRANCH_NAME=$(git rev-parse --abbrev-ref HEAD)\n```\n\nIf the branch does NOT match the `NNN-feature-name` pattern, skip silently. This is not a feature branch, so worktree isolation does not apply.\n\n### Step 3: Check if a Worktree Already Exists for This Branch\n\n```bash\nWORKTREE_CONFIG=\".specify\u002Fextensions\u002Fspex-worktrees\u002Fworktree-config.yml\"\nBASE_PATH=$(yq -r '.worktrees.base_path \u002F\u002F \".claude\u002Fworktrees\"' \"$WORKTREE_CONFIG\" 2>\u002Fdev\u002Fnull || echo \".claude\u002Fworktrees\")\nWORKTREE_PATH=\"$REPO_ROOT\u002F$BASE_PATH\u002F$BRANCH_NAME\"\n\nif git worktree list --porcelain | grep -q \"worktree.*$BRANCH_NAME\"; then\n  echo \"WARNING: A worktree for branch $BRANCH_NAME already exists but you are not in it.\"\n  echo \"Switch to the worktree before implementing:\"\n  echo \"  cd $WORKTREE_PATH && claude\"\n  # Stop here. Do not create a duplicate worktree.\nfi\n```\n\n### Step 4: Offer to Create a Worktree\n\nPresent a single-select question to the user:\n- header: \"Worktree\"\n- question: \"Implementation is about to start without worktree isolation. Create a worktree now?\"\n- options:\n  - \"Create worktree (Recommended)\": \"Isolate implementation in a git worktree\"\n  - \"Continue without worktree\": \"Implement directly on the current branch (no isolation)\"\n\nIf the user selects \"Create worktree\", execute the full **Action: Create** flow (Steps 1-9 above).\n\nIf the user selects \"Continue without worktree\", proceed without isolation.\n\n## Action: List\n\nShow all active feature worktrees for the project.\n\n### Step 1: Get Worktree List\n\n```bash\ngit worktree list --porcelain\n```\n\nParse the output. Each worktree entry has:\n- `worktree \u003Cpath>`\n- `HEAD \u003Ccommit>`\n- `branch refs\u002Fheads\u002F\u003Cbranch-name>`\n\n### Step 2: Filter Feature Branches\n\nOnly show worktrees whose branch matches the `NNN-*` feature branch pattern (three-digit prefix followed by a hyphen).\n\nSkip the main worktree (the original repo).\n\n### Step 3: Format Output\n\nDisplay a table with worktree directory names (`@` separator):\n\n```\nActive Feature Worktrees:\n\n  Path                              Branch              Feature\n  ─────────────────────────────────────────────────────────────\n  .claude\u002Fworktrees\u002F004-user-auth   004-user-auth       user-auth\n  .claude\u002Fworktrees\u002F007-worktrees   007-worktrees-trait  worktrees-trait\n```\n\nFor inside-project worktrees, show the relative path (`.claude\u002Fworktrees\u002F\u003Cbranch>`). For external worktrees, show the last path component (`repo@branch`).\n\nIf no feature worktrees exist:\n\n```\nNo active feature worktrees found.\n\nCreate one by running \u002Fspeckit-specify with the worktrees extension enabled.\n```\n\n## Action: Finish\n\nMerges the current worktree's feature branch into the default branch and removes the worktree. This is the recommended way to complete work in a spex worktree.\n\n{harness:worktree-isolation}\nSpex worktrees are managed via `git worktree add` and `git worktree remove` commands directly.\nDo NOT use harness-specific worktree tools, as spex worktrees are created independently.\nAlways use git commands for worktree operations.\n{\u002Fharness:worktree-isolation}\n\n### Step 1: Verify We're in a Worktree\n\n```bash\nREPO_ROOT=$(git rev-parse --show-toplevel)\nGIT_DIR=$(git rev-parse --git-dir)\n\n# A worktree has a .git file (not directory) pointing to the main repo\nif [ \"$GIT_DIR\" = \"$REPO_ROOT\u002F.git\" ] || [ \"$GIT_DIR\" = \".git\" ]; then\n  echo \"ERROR: Not inside a git worktree. Use 'finish' from within a spex worktree.\"\n  # Stop here.\nfi\n```\n\n### Step 2: Get Branch and Main Worktree Info\n\n```bash\nBRANCH_NAME=$(git rev-parse --abbrev-ref HEAD)\nWORKTREE_PATH=$(git rev-parse --show-toplevel)\n\n# Find the main worktree (first entry in worktree list)\nMAIN_WORKTREE=$(git worktree list --porcelain | head -1 | sed 's\u002F^worktree \u002F\u002F')\n\n# Detect default branch\nDEFAULT_BRANCH=$(git symbolic-ref refs\u002Fremotes\u002Forigin\u002FHEAD 2>\u002Fdev\u002Fnull | sed 's@^refs\u002Fremotes\u002Forigin\u002F@@')\nif [ -z \"$DEFAULT_BRANCH\" ]; then\n  for candidate in main master; do\n    if git rev-parse --verify \"$candidate\" >\u002Fdev\u002Fnull 2>&1; then\n      DEFAULT_BRANCH=\"$candidate\"\n      break\n    fi\n  done\nfi\nDEFAULT_BRANCH=${DEFAULT_BRANCH:-main}\n```\n\n### Step 3: Ensure All Changes Are Committed\n\n```bash\nif ! git diff --quiet || ! git diff --cached --quiet; then\n  echo \"ERROR: Uncommitted changes in worktree. Commit or stash before finishing.\"\n  # Stop here.\nfi\n```\n\n### Step 4: Ask User How to Proceed\n\n{harness:interactive-choice} (single-select, header: \"Finish\"):\n- \"Merge and remove (Recommended)\": \"Fast-forward merge branch into default, remove worktree and branch\"\n- \"Remove only\": \"Remove worktree and branch without merging (changes stay in git reflog)\"\n- \"Cancel\": \"Keep worktree as-is\"\n\nIf \"Cancel\": stop.\n\n### Step 5: Switch CWD to Main Worktree\n\n**CRITICAL:** Switch the working directory to the main worktree BEFORE doing anything destructive. If cwd is inside the worktree being removed, all subsequent Bash commands will fail with \"path does not exist\".\n\n```bash\ncd \"$MAIN_WORKTREE\"\n```\n\n### Step 6: Merge (if selected)\n\nIf the user chose \"Merge and remove\":\n\n```bash\ncd \"$MAIN_WORKTREE\"\ngit checkout \"$DEFAULT_BRANCH\"\ngit merge --ff-only \"$BRANCH_NAME\" 2>&1\n```\n\nIf fast-forward merge fails (branches diverged), ask the user:\n\n{harness:interactive-choice} (single-select, header: \"Merge\"):\n- \"Create merge commit\": \"Merge with a merge commit (branches have diverged)\"\n- \"Abort\": \"Keep worktree, resolve manually\"\n\nIf \"Create merge commit\":\n```bash\ngit merge \"$BRANCH_NAME\" -m \"Merge branch '$BRANCH_NAME'\n\nAssisted-By: 🤖 Claude Code\" 2>&1\n```\n\nIf \"Abort\": stop. The cwd is already at the main worktree, so the user can navigate back.\n\n### Step 7: Remove Worktree and Branch\n\n```bash\n# Remove worktree (cwd is already at main worktree from Step 5)\ngit worktree remove \"$WORKTREE_PATH\" 2>&1\n\n# Delete the feature branch (it's merged or user chose remove-only)\ngit branch -d \"$BRANCH_NAME\" 2>&1 || git branch -D \"$BRANCH_NAME\" 2>&1\n```\n\n### Step 8: Clear Flow State\n\n```bash\nSTATE_FILE=\".specify\u002F.spex-state\"\nif [ -f \"$STATE_FILE\" ]; then\n  rm -f \"$STATE_FILE\"\nfi\n```\n\n### Step 9: Report\n\n```\n┌─────────────────────────────────────────────────────────┐\n│ Feature branch \u003Cbranch> finished.                       │\n│                                                         │\n│ - Merged to \u003Cdefault-branch> (if selected)              │\n│ - Worktree removed: \u003Cworktree-path>                     │\n│ - Branch deleted: \u003Cbranch>                              │\n│ - Flow state cleared                                    │\n│                                                         │\n│ You are now in the main repo on \u003Cdefault-branch>.       │\n└─────────────────────────────────────────────────────────┘\n```\n\nIf the user wants to push: `git push origin $DEFAULT_BRANCH`\n\n## Action: Cleanup\n\nDetect worktrees whose branches are merged and offer removal.\n\n### Step 1: Get Merged Branches\n\n```bash\n# Detect default branch with fallback chain\nDEFAULT_BRANCH=$(git symbolic-ref refs\u002Fremotes\u002Forigin\u002FHEAD 2>\u002Fdev\u002Fnull | sed 's@^refs\u002Fremotes\u002Forigin\u002F@@')\nif [ -z \"$DEFAULT_BRANCH\" ]; then\n  for candidate in main master; do\n    if git rev-parse --verify \"$candidate\" >\u002Fdev\u002Fnull 2>&1; then\n      DEFAULT_BRANCH=\"$candidate\"\n      break\n    fi\n  done\nfi\nDEFAULT_BRANCH=${DEFAULT_BRANCH:-main}\n\n# Get all feature branches merged into the default branch\nMERGED_BRANCHES=$(git branch --merged \"$DEFAULT_BRANCH\" | sed 's\u002F^[+* ]*\u002F\u002F' | grep -E '^[0-9]{3}-')\n```\n\n### Step 2: Cross-Reference with Worktrees\n\nFor each worktree with a feature branch, check if its branch appears in the merged list.\n\n### Step 3: Handle Merged Worktrees\n\nFor each merged worktree, present it to the user and ask for confirmation:\n\n```\nWorktree cc-spex@004-user-auth (branch 004-user-auth) is merged into main.\nRemove this worktree? (yes\u002Fno)\n```\n\nIf the user confirms, first switch to the main repo root (to avoid cwd pointing at the deleted directory), then remove the worktree:\n\n```bash\n# Switch cwd to the main worktree BEFORE removing the feature worktree.\n# If cwd is inside the worktree being removed, all subsequent commands will\n# fail with \"Path does not exist\" because the Bash tool persists cwd.\nMAIN_WORKTREE=$(git worktree list --porcelain | head -1 | sed 's\u002F^worktree \u002F\u002F')\ncd \"$MAIN_WORKTREE\"\ngit worktree remove \u003Cpath>\ngit branch -d \u003Cbranch-name>\n```\n\n### Step 4: Handle Unmerged Worktrees\n\nFor worktrees with unmerged branches, warn the user:\n\n```\nWorktree cc-spex@007-worktrees-trait (branch 007-worktrees-trait) has NOT been merged.\nSkipping. Use --force to remove unmerged worktrees (data may be lost).\n```\n\nOnly remove unmerged worktrees if the user explicitly confirms after seeing the warning.\n\n---\n\n## Worktree Context for Downstream Commands\n\nWhen running in a worktree created by this extension, downstream spec-kit commands should be aware of the worktree context:\n\n### Planning Context\n\nYou are likely running in a worktree created by the `worktrees` extension. The spec file in this worktree contains all decisions from the brainstorm\u002Fspecify session. No separate handoff file is needed.\n\n### Implementation Context\n\nYou are likely running in a worktree created by the `worktrees` extension. The spec and plan files in this worktree contain all context needed for implementation. No separate handoff file is needed.",{"name":5,"metadata":24,"description":7,"compatibility":27},{"author":25,"source":26},"github-spec-kit","spex-worktrees:commands\u002Fspeckit.spex-worktrees.manage.md","Requires spec-kit project structure with .specify\u002F directory","main","bf2af6077064ba2889ff548f6745f7a89096b9e7",".specify\u002Fextensions\u002Fspex-worktrees\u002F.specify-dev\u002Fagent-commands\u002Fclaude\u002Fspeckit-spex-worktrees-manage",0,"https:\u002F\u002Fgithub.com\u002Fjimmidyson\u002Fkcp-cluster-api","https:\u002F\u002Fgithub.com\u002Fjimmidyson","https:\u002F\u002Feng.d2iq.com\u002F","Principal Engineer at Nutanix ","2026-11-14 13:13:21",{"source":8,"skillName":5,"commands":38,"prompt":48,"zipAvailable":49},[39,42,45],{"tool":40,"command":41},"npx","npx skills add jimmidyson\u002Fkcp-cluster-api --skill speckit-spex-worktrees-manage",{"tool":43,"command":44},"bunx","bunx skills add jimmidyson\u002Fkcp-cluster-api --skill speckit-spex-worktrees-manage",{"tool":46,"command":47},"pnpm","pnpm dlx skills add jimmidyson\u002Fkcp-cluster-api --skill speckit-spex-worktrees-manage","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fjimmidyson\u002Fkcp-cluster-api\u002Fblob\u002Fmain\u002F.specify\u002Fextensions\u002Fspex-worktrees\u002F.specify-dev\u002Fagent-commands\u002Fclaude\u002Fspeckit-spex-worktrees-manage\u002FSKILL.md",true,[],[52,59,66,73,80,87],{"skillNo":53,"name":54,"nameZh":6,"description":55,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":56,"categories":57,"keywords":58,"publishedAt":19},"01M7AJ18QSWTJ2SAGX0CWJGTRF","speckit-spex-teams-research","Parallel codebase research for planning via parallel agent teams","https:\u002F\u002Fgithub.com\u002Fjimmidyson\u002Fkcp-cluster-api\u002Fblob\u002Fmain\u002F.specify\u002Fextensions\u002Fspex-teams\u002F.specify-dev\u002Fagent-commands\u002Fclaude\u002Fspeckit-spex-teams-research\u002FSKILL.md",[],[],{"skillNo":60,"name":61,"nameZh":6,"description":62,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":63,"categories":64,"keywords":65,"publishedAt":19},"01M7AJ14V817SCP3YPDSR9E968","speckit-spex-teams-orchestrate","Unified team orchestration: parallel task implementation with spec guardian review pattern via parallel agent teams","https:\u002F\u002Fgithub.com\u002Fjimmidyson\u002Fkcp-cluster-api\u002Fblob\u002Fmain\u002F.specify\u002Fextensions\u002Fspex-teams\u002F.specify-dev\u002Fagent-commands\u002Fclaude\u002Fspeckit-spex-teams-orchestrate\u002FSKILL.md",[],[],{"skillNo":67,"name":68,"nameZh":6,"description":69,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":70,"categories":71,"keywords":72,"publishedAt":19},"01M7AJ12G1WGNDSGBVX73ADMTR","speckit-spex-teams-implement","Parallel implementation via agent teams for independent tasks","https:\u002F\u002Fgithub.com\u002Fjimmidyson\u002Fkcp-cluster-api\u002Fblob\u002Fmain\u002F.specify\u002Fextensions\u002Fspex-teams\u002F.specify-dev\u002Fagent-commands\u002Fclaude\u002Fspeckit-spex-teams-implement\u002FSKILL.md",[],[],{"skillNo":74,"name":75,"nameZh":6,"description":76,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":77,"categories":78,"keywords":79,"publishedAt":19},"01M7AJ0ZAAP2EDC2DV873YDND9","speckit-spex-gates-verify","Final verification gate: tests, code hygiene, spec compliance, and drift check","https:\u002F\u002Fgithub.com\u002Fjimmidyson\u002Fkcp-cluster-api\u002Fblob\u002Fmain\u002F.specify\u002Fextensions\u002Fspex-gates\u002F.specify-dev\u002Fagent-commands\u002Fclaude\u002Fspeckit-spex-gates-verify\u002FSKILL.md",[],[],{"skillNo":81,"name":82,"nameZh":6,"description":83,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":84,"categories":85,"keywords":86,"publishedAt":19},"01M7AJ0W0J07D6X6M77FAYJYPE","speckit-spex-gates-stamp","Final gate before completion - invokes verification for tests, code hygiene, spec compliance, and drift check","https:\u002F\u002Fgithub.com\u002Fjimmidyson\u002Fkcp-cluster-api\u002Fblob\u002Fmain\u002F.specify\u002Fextensions\u002Fspex-gates\u002F.specify-dev\u002Fagent-commands\u002Fclaude\u002Fspeckit-spex-gates-stamp\u002FSKILL.md",[],[],{"skillNo":88,"name":89,"nameZh":6,"description":90,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":91,"categories":92,"keywords":93,"publishedAt":19},"01M7AJ0G09FAQQ2Z4QGRKV5EVK","speckit-spex-gates-review-spec","Review specifications for soundness, completeness, and implementability","https:\u002F\u002Fgithub.com\u002Fjimmidyson\u002Fkcp-cluster-api\u002Fblob\u002Fmain\u002F.specify\u002Fextensions\u002Fspex-gates\u002F.specify-dev\u002Fagent-commands\u002Fclaude\u002Fspeckit-spex-gates-review-spec\u002FSKILL.md",[],[]]