Plan: Guard against main repo on target branch before worktree creation#
Summary#
Add a pre-flight check in WorktreeService.createWorktree() that detects when the main repo is checked out on the target feature branch and auto-switches to master before stale-branch cleanup. This prevents the git branch -D silent failure that causes git worktree add -b to fatal with "branch already exists", which was the root cause of #246 being stuck for 12+ hours.
Files#
| File | Action | Description |
|---|---|---|
src/worktree/worktree.service.ts | modify | Add branch guard logic before stale-branch cleanup block (before line 100) |
src/worktree/worktree.service.spec.ts | modify | Add unit tests for the new guard: auto-switch, checkout failure, and detached HEAD scenarios |
Steps#
- In
createWorktree(), aftergit fetch origin(line 75) and before stale worktree cleanup (line 78), add a guard that runsgit rev-parse --abbrev-ref HEADinrepoPathto get the current branch. - If the current branch equals
branchName(feat/issue-{N}), rungit checkout masterinrepoPathwith a log message explaining the auto-recovery. - If
git checkout masterfails, throw a descriptiveErrorwith a message including the branch name and the underlying git error — do not swallow. - If
git rev-parse --abbrev-ref HEADreturnsHEAD(detached state), skip the guard — proceed normally. - Add unit test: main repo on target branch →
git checkout masteris called → worktree creation succeeds. - Add unit test: main repo on target branch →
git checkout masterfails → typed error is thrown with descriptive message. - Add unit test:
git branch -Dfailure when branch is checked out is now unreachable due to guard, but verify the existing catch block still handles unexpected deletion failures gracefully.
Verification#
npm run testpasses with new and existing testsnpm run lintpasses with zero warnings- Manual review confirms the guard is placed before both the stale-branch cleanup and worktree add calls
Risks#
- If
repoPathhas uncommitted changes,git checkout masterwill fail — this is by design per the issue scope (surface the error, do not stash).