From bdc95bcb268e9437ce3d64dbe5fcf94ba5cad057 Mon Sep 17 00:00:00 2001 From: Lukas May Date: Fri, 6 Mar 2026 10:54:33 +0100 Subject: [PATCH] fix: Handle existing branch in worktree creation When re-dispatching tasks, the branch from a previous run may still exist. Instead of failing with "a branch named X already exists", reset the existing branch to the base and check it out. --- apps/server/git/manager.ts | 32 ++++++++++++++++++++++---------- 1 file changed, 22 insertions(+), 10 deletions(-) diff --git a/apps/server/git/manager.ts b/apps/server/git/manager.ts index 258bc46..f7d3c1b 100644 --- a/apps/server/git/manager.ts +++ b/apps/server/git/manager.ts @@ -61,16 +61,16 @@ export class SimpleGitWorktreeManager implements WorktreeManager { const worktreePath = path.join(this.worktreesDir, id); log.info({ id, branch, baseBranch }, 'creating worktree'); - // Create worktree with new branch - // git worktree add -b - await this.git.raw([ - 'worktree', - 'add', - '-b', - branch, - worktreePath, - baseBranch, - ]); + // Create worktree — reuse existing branch or create new one + const branchExists = await this.branchExists(branch); + if (branchExists) { + // Branch exists from a previous run — reset it to baseBranch and check it out + await this.git.raw(['branch', '-f', branch, baseBranch]); + await this.git.raw(['worktree', 'add', worktreePath, branch]); + } else { + // git worktree add -b + await this.git.raw(['worktree', 'add', '-b', branch, worktreePath, baseBranch]); + } const worktree: Worktree = { id, @@ -327,6 +327,18 @@ export class SimpleGitWorktreeManager implements WorktreeManager { return worktrees; } + /** + * Check if a local branch exists in the repository. + */ + private async branchExists(branch: string): Promise { + try { + await this.git.raw(['rev-parse', '--verify', `refs/heads/${branch}`]); + return true; + } catch { + return false; + } + } + /** * Parse the output of git diff --name-status. */