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. */