fix(#270): make createWorktree() idempotent — reuse existing worktree/branch#
Problem#
createWorktree() unconditionally deleted the existing worktree directory and force-deleted the branch before recreating both. When the branch was already checked out in another worktree, git branch -D failed silently and left the task stuck in a permanent retry loop.
Task / Link#
GitHub Issue #270 — AgentSDE/agent-core
Changes#
- Added
isValidWorktree(path, repoPath)private helper — checksgit worktree list --porcelainto detect registered worktrees - Replaced destructive cleanup block with three-path idempotent logic:
- Valid worktree exists → reuse it (
git fetch origin+git reset --hard origin/master) - Directory exists but invalid → remove directory, fall through to branch check
- Branch exists locally, no worktree →
git worktree add <path> <branch>(no-b) - Neither exists → fresh
git worktree add -b <branch> <path> origin/master
- Valid worktree exists → reuse it (
- Removed
git branch -Dblock entirely (root cause of stuck loop) - Added 4 unit tests covering all idempotent paths
Notes#
git reset --hard origin/master in the reuse path discards any uncommitted changes in the worktree — acceptable since agent worktrees are always ephemeral and start from origin/master.
Testing#
- 15 unit tests pass (
npm run test) npm run lintpasses with zero errors in changed files