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

Plan: Make createWorktree() Idempotent#

Summary#

Replace the destructive nuke-and-recreate logic in WorktreeService.createWorktree() with an idempotent flow that detects existing worktrees/branches and reuses them, fixing the permanent stuck-loop caused when a branch is already checked out elsewhere (#246).

Files#

FileActionDescription
src/worktree/worktree.service.tsmodifyReplace lines 77–128 with idempotent worktree/branch detection and reuse logic
src/worktree/worktree.service.spec.tsmodifyAdd 4 new test cases covering all idempotent paths; update existing tests for new flow

Steps#

  1. Add isValidWorktree(path) private helper in worktree.service.ts — runs git worktree list --porcelain and checks if the given path appears as a registered worktree.
  2. Replace lines 77–95 (stale worktree cleanup) with: if worktree directory exists AND isValidWorktree() returns true, log reuse and skip to fetch+reset. If directory exists but is NOT a valid worktree, remove the directory and fall through.
  3. Remove lines 100–118 (aggressive git branch -D block) entirely — this is the root cause of the silent failure.
  4. Replace lines 120–128 (unconditional git worktree add -b) with three-path logic: (a) if worktree was reused in step 2, run git fetch origin + git reset --hard origin/master inside the worktree; (b) if no worktree but branch exists locally (git branch --list <branch> is non-empty), run git worktree add <path> <branch> (no -b); (c) if neither exists, run git worktree add -b <branch> <path> origin/master (current fresh-start behavior).
  5. Add unit test: worktree directory exists and is valid → reused without removal, fetch+reset executed.
  6. Add unit test: worktree directory exists but is invalid → directory removed, falls through to branch-check logic.
  7. Add unit test: branch exists locally but no worktree directory → git worktree add <path> <branch> called (no -b).
  8. Add unit test: neither branch nor worktree exist → git worktree add -b <branch> <path> origin/master called (existing behavior preserved).
  9. Update existing tests that assert the old git branch -D or forced removal behavior to match the new idempotent flow.

Verification#

  • npm run test passes with all new and updated worktree tests green.
  • npm run lint passes with zero warnings.
  • No changes outside src/worktree/ directory.

Risks#

  • git reset --hard origin/master in reuse path discards uncommitted worktree changes — acceptable since agent worktrees are ephemeral and always start from origin/master. The issue explicitly requests this behavior.
ContextPrd