AI Agents SDE Task Viewer
      • Context
      • Plan
      • Prd
  1. Home
  2. AgentSDE
  3. agent-core
  4. gh-266
  5. plan
  6. plan.md
plan.md(2.2 KB)· Apr 3, 2026· 2 min read
  • Summary
  • Files
  • Steps
  • Verification
  • Risks

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#

FileActionDescription
src/worktree/worktree.service.tsmodifyAdd branch guard logic before stale-branch cleanup block (before line 100)
src/worktree/worktree.service.spec.tsmodifyAdd unit tests for the new guard: auto-switch, checkout failure, and detached HEAD scenarios

Steps#

  1. In createWorktree(), after git fetch origin (line 75) and before stale worktree cleanup (line 78), add a guard that runs git rev-parse --abbrev-ref HEAD in repoPath to get the current branch.
  2. If the current branch equals branchName (feat/issue-{N}), run git checkout master in repoPath with a log message explaining the auto-recovery.
  3. If git checkout master fails, throw a descriptive Error with a message including the branch name and the underlying git error — do not swallow.
  4. If git rev-parse --abbrev-ref HEAD returns HEAD (detached state), skip the guard — proceed normally.
  5. Add unit test: main repo on target branch → git checkout master is called → worktree creation succeeds.
  6. Add unit test: main repo on target branch → git checkout master fails → typed error is thrown with descriptive message.
  7. Add unit test: git branch -D failure 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 test passes with new and existing tests
  • npm run lint passes with zero warnings
  • Manual review confirms the guard is placed before both the stale-branch cleanup and worktree add calls

Risks#

  • If repoPath has uncommitted changes, git checkout master will fail — this is by design per the issue scope (surface the error, do not stash).
ContextPrd