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.
This commit is contained in:
Lukas May
2026-03-06 10:54:33 +01:00
parent 1e2819eeff
commit bdc95bcb26

View File

@@ -61,16 +61,16 @@ export class SimpleGitWorktreeManager implements WorktreeManager {
const worktreePath = path.join(this.worktreesDir, id); const worktreePath = path.join(this.worktreesDir, id);
log.info({ id, branch, baseBranch }, 'creating worktree'); log.info({ id, branch, baseBranch }, 'creating worktree');
// Create worktree with new branch // Create worktree — reuse existing branch or create new one
// git worktree add -b <branch> <path> <base-branch> const branchExists = await this.branchExists(branch);
await this.git.raw([ if (branchExists) {
'worktree', // Branch exists from a previous run — reset it to baseBranch and check it out
'add', await this.git.raw(['branch', '-f', branch, baseBranch]);
'-b', await this.git.raw(['worktree', 'add', worktreePath, branch]);
branch, } else {
worktreePath, // git worktree add -b <branch> <path> <base-branch>
baseBranch, await this.git.raw(['worktree', 'add', '-b', branch, worktreePath, baseBranch]);
]); }
const worktree: Worktree = { const worktree: Worktree = {
id, id,
@@ -327,6 +327,18 @@ export class SimpleGitWorktreeManager implements WorktreeManager {
return worktrees; return worktrees;
} }
/**
* Check if a local branch exists in the repository.
*/
private async branchExists(branch: string): Promise<boolean> {
try {
await this.git.raw(['rev-parse', '--verify', `refs/heads/${branch}`]);
return true;
} catch {
return false;
}
}
/** /**
* Parse the output of git diff --name-status. * Parse the output of git diff --name-status.
*/ */