Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: report failed worktree removal and defer PR follow-ups until the branch is released (#9909)

Adam Eivy44db795a02e4
diff --git a/server/services/agentWorktreeCleanup.js b/server/services/agentWorktreeCleanup.js
index 1c9426d21d..a617ab5cdd 100644
--- a/server/services/agentWorktreeCleanup.js
+++ b/server/services/agentWorktreeCleanup.js
@@ -214,13 +214,18 @@ async function runCleanupAgentWorktree(agentId, success, options = {}) {
return discardAgentWorktree(context);
case 'open-pr':
return openWorktreePullRequest(context);
- case 'stranded-pr-handoff':
- await mergeOrPreserveWorktree(context, disposition);
+ case 'stranded-pr-handoff': {
+ const released = await mergeOrPreserveWorktree(context, disposition);
+ if (released?.cleanupIncomplete) {
+ deferFollowUpWhileBranchHeld(context, verdict.url);
+ break;
+ }
await handoffFollowUpAfterRelease(context, verdict.url, {
prCompletion: PR_COMPLETION_VALUES.includes(context.prCompletion)
? context.prCompletion : PR_COMPLETIONS.REVIEW_THEN_MERGE,
}, 'orphaned');
break;
+ }
case 'stand-down':
case 'stand-down-uncertain':
case 'merge-or-preserve':
@@ -379,11 +384,19 @@ async function completeOpenedPullRequest(context, prResult) {
// pre-request above is the last user of that checkout.
const result = await removeWorktree(agentId, sourceWorkspace, worktreeBranch, { merge: false }).catch(err => {
emitLog('warn', `🌳 Worktree cleanup failed for ${agentId}: ${err.message}`, { agentId });
- return { warnings: [`Worktree cleanup failed: ${err.message}`] };
+ return { cleanupIncomplete: true, warnings: [`Worktree cleanup failed: ${err.message}`] };
});
warnings.push(...(result?.warnings || []));
- await completeReleasedPullRequest(context, prResult, resolvedPrCompletion, reviewerList, leaveOpen);
+ // The PR itself is already open and stays reported as such; only work that
+ // needs the branch FREE is gated on whether the release actually happened.
+ // `cleanupIncomplete` means a removal was attempted and failed. A tree merely
+ // preserved for uncommitted work (`removed:false` without it) is deliberately
+ // not gated: the follow-up adopts that surviving holder rather than racing it
+ // (agentWorkspacePrep's adoptWorktreeHoldingBranch), which is the data-safe path.
+ await completeReleasedPullRequest(context, prResult, resolvedPrCompletion, reviewerList, leaveOpen, {
+ branchHeld: !!result?.cleanupIncomplete,
+ });
return warnings;
}
@@ -413,7 +426,7 @@ async function preRequestWorktreeReview({ agentId, worktreePath, warnings }, prR
}
}
-async function completeReleasedPullRequest(context, prResult, resolvedPrCompletion, reviewerList, leaveOpen) {
+async function completeReleasedPullRequest(context, prResult, resolvedPrCompletion, reviewerList, leaveOpen, { branchHeld = false } = {}) {
const { agentId } = context;
const runsReviewLoop = resolvedPrCompletion === PR_COMPLETIONS.REVIEW_THEN_MERGE;
if (resolvedPrCompletion === PR_COMPLETIONS.LEAVE_OPEN) {
@@ -423,7 +436,9 @@ async function completeReleasedPullRequest(context, prResult, resolvedPrCompleti
} else {
const queuedDeterministicMerge = await queueWorktreeMerge(context, prResult, resolvedPrCompletion);
- if (!queuedDeterministicMerge) {
+ if (!queuedDeterministicMerge && branchHeld) {
+ deferFollowUpWhileBranchHeld(context, prResult.url);
+ } else if (!queuedDeterministicMerge) {
await handoffFollowUpAfterRelease(context, prResult.url, {
prCompletion: resolvedPrCompletion,
reviewers: runsReviewLoop ? reviewerList : [],
@@ -497,7 +512,7 @@ async function mergeOrPreserveWorktree({ agentId, sourceWorkspace, worktreeBranc
preserveBranchWithCommits: disposition.preserveBranch,
}).catch(err => {
emitLog('warn', `🌳 Worktree cleanup failed for ${agentId}: ${err.message}`, { agentId });
- return { warnings: [`Worktree cleanup failed: ${err.message}`] };
+ return { cleanupIncomplete: true, warnings: [`Worktree cleanup failed: ${err.message}`] };
});
warnings.push(...(result?.warnings || []));
@@ -508,6 +523,19 @@ async function mergeOrPreserveWorktree({ agentId, sourceWorkspace, worktreeBranc
// leaked remote branch and hands to a recovery agent. Finish the job here,
// deterministically, instead of paying a model to run one `git push --delete`.
if (result?.merged) await deleteMergedRemoteCopy(agentId, sourceWorkspace, worktreeBranch);
+ return result;
+}
+
+// A follow-up attaches its OWN worktree to the PR branch, which `git worktree
+// add` refuses while the old checkout still holds it. When cleanup could not
+// release the branch, dispatching now just blocks the task and orphans the PR it
+// exists to land — so the dispatch is withheld and the state is reported as a
+// retryable cleanup warning (the post-cleanup repo-state audit independently
+// observes the surviving worktree and files the recovery that retries removal
+// and drives the PR). The PR itself is untouched: it stays open/merged as it was.
+function deferFollowUpWhileBranchHeld({ agentId, worktreeBranch, worktreePath, warnings }, prUrl) {
+ emitLog('warn', `🌳 Deferring follow-up for ${prUrl} — worktree ${agentId} still holds ${worktreeBranch}`, { agentId, prUrl, branchName: worktreeBranch });
+ warnings.push(`PR follow-up for ${prUrl} deferred — worktree ${worktreePath || agentId} still holds branch ${worktreeBranch}; retry the worktree cleanup, then re-dispatch the follow-up`);
}
// Call only after removeWorktree settles: the follow-up attaches its own
diff --git a/server/services/autonomousJobs/scriptHandlers.js b/server/services/autonomousJobs/scriptHandlers.js
index 47857d3ce2..6dae8d59a1 100644
--- a/server/services/autonomousJobs/scriptHandlers.js
+++ b/server/services/autonomousJobs/scriptHandlers.js
@@ -168,8 +168,11 @@ async function agentDataCleanup() {
})
const mergedCount = merged?.reaped?.length || 0
- console.log(`🧹 Agent data cleanup: removed ${cleaned} dir(s) older than 7 days, ${sentinelsRemoved} stale sentinel(s), reaped ${mergedCount} merged + ${worktreesReaped} orphaned worktree(s)`)
- return { cleaned, sentinelsRemoved, mergedReaped: mergedCount, worktreesReaped }
+ // Reaps whose checkout survived removal: not counted above, surfaced here so a
+ // retryable failure is visible in the job log instead of reading as a clean day.
+ const removalFailures = merged?.skipped?.filter(s => s.reason === 'remove-failed').length || 0
+ console.log(`🧹 Agent data cleanup: removed ${cleaned} dir(s) older than 7 days, ${sentinelsRemoved} stale sentinel(s), reaped ${mergedCount} merged + ${worktreesReaped} orphaned worktree(s)${removalFailures ? `, ${removalFailures} worktree removal(s) failed (retry next run)` : ''}`)
+ return { cleaned, sentinelsRemoved, mergedReaped: mergedCount, worktreesReaped, removalFailures }
}
/**
diff --git a/server/services/branchReconcile.js b/server/services/branchReconcile.js
index 2a8b21c53c..745c3f383b 100644
--- a/server/services/branchReconcile.js
+++ b/server/services/branchReconcile.js
@@ -1170,7 +1170,12 @@ async function retireBranch(repoPath, b, { activeAgentIds = new Set(), staleClai
}
const prepared = prepare ? await prepare() : null;
if (prepared?.error) return { ok: false, reason: prepared.error };
- if (b.worktreePath) await forceRemoveWorktreeDir(repoPath, b.worktreePath, { label, log: 'all' });
+ if (b.worktreePath) {
+ const removal = await forceRemoveWorktreeDir(repoPath, b.worktreePath, { label, log: 'all' });
+ // The branch is still checked out by a surviving worktree: deleting it would
+ // fail, and reporting success would mark the branch reconciled while it is held.
+ if (!removal.removed) return { ok: false, reason: 'worktree-remove-failed' };
+ }
const result = await deleteBranch(repoPath, b.branch, { local: true }).catch((err) => ({ error: err.message }));
if (result?.error || result?.results?.local?.startsWith?.('failed')) {
return { ok: false, reason: `delete-failed: ${result.error || result.results.local}` };
diff --git a/server/services/branchReconcile.test.js b/server/services/branchReconcile.test.js
index 3de1465cb7..43b5e7e64b 100644
--- a/server/services/branchReconcile.test.js
+++ b/server/services/branchReconcile.test.js
@@ -23,7 +23,7 @@ vi.mock('./worktreeManager.js', async () => {
const { AGENT_SCRATCH_PATHS, matchesScratchRoot } = await import('../lib/agentScratchPaths.js');
return {
listWorktrees: vi.fn(async () => []),
- forceRemoveWorktreeDir: vi.fn(async () => {}),
+ forceRemoveWorktreeDir: vi.fn(async () => ({ removed: true, warning: null })),
reapMergedWorktrees: vi.fn(async () => ({ reaped: [], skipped: [] })),
// Real pure classifier semantics: empty porcelain = clean, and every non-empty
// line is a real change path (the suite never feeds it lockfile churn) EXCEPT
@@ -134,7 +134,7 @@ beforeEach(() => {
});
git.getDefaultBranch.mockResolvedValue('main');
git.deleteBranch.mockResolvedValue({ branch: 'x', results: { local: 'deleted' } });
- wt.forceRemoveWorktreeDir.mockResolvedValue(undefined);
+ wt.forceRemoveWorktreeDir.mockResolvedValue({ removed: true, warning: null });
wt.reapMergedWorktrees.mockResolvedValue({ reaped: [], skipped: [] });
execGit.mockResolvedValue({ stdout: '', exitCode: 0 });
tryReadFileMock.mockResolvedValue(null);
@@ -347,6 +347,15 @@ describe('cleanupMerged', () => {
expect(git.deleteBranch).toHaveBeenCalledWith('/repo', 'next/issue-2190', { local: true });
});
+ it('does not delete the branch or report it cleaned when the worktree survives removal', async () => {
+ git.hasBranchMergeEvidence.mockResolvedValue(true);
+ execGit.mockResolvedValue({ stdout: '', exitCode: 0 }); // clean worktree
+ wt.forceRemoveWorktreeDir.mockResolvedValue({ removed: false, warning: 'Worktree cleanup incomplete — retryable' });
+ const res = await cleanupMerged('/repo', 'main', [{ branch: 'next/issue-2190', worktreePath: '/wt/2190' }]);
+ expect(res.cleaned).toEqual([]);
+ expect(git.deleteBranch).not.toHaveBeenCalled();
+ });
+
it('skips when re-check says not merged (fail closed)', async () => {
git.hasBranchMergeEvidence.mockResolvedValue(false);
const res = await cleanupMerged('/repo', 'main', [{ branch: 'next/issue-2190', worktreePath: '/wt/2190' }]);
@@ -1376,7 +1385,7 @@ describe('reconcile — cached SUPERSEDED verdicts (#3842)', () => {
order.push('backup');
return { dir: '/backups/x', manifest: 'manifest.json', untracked: [] };
});
- wt.forceRemoveWorktreeDir.mockImplementation(async () => { order.push('remove'); });
+ wt.forceRemoveWorktreeDir.mockImplementation(async () => { order.push('remove'); return { removed: true, warning: null }; });
git.deleteBranch.mockImplementation(async () => { order.push('delete'); return { results: { local: 'deleted' } }; });
await reconcile('/repo', { activeAgentIds: new Set() });
diff --git a/server/services/cleanupAgentWorktree.test.js b/server/services/cleanupAgentWorktree.test.js
index 122336e190..7c2d10afa2 100644
--- a/server/services/cleanupAgentWorktree.test.js
+++ b/server/services/cleanupAgentWorktree.test.js
@@ -713,6 +713,79 @@ describe('cleanupAgentWorktree - PR-creation path', () => {
.toBeLessThan(removeWorktree.mock.invocationCallOrder[0]);
});
+ // #9909: the follow-up's `git worktree add` fails while the old checkout still
+ // holds the branch. When removal did not actually release it, the PR stays
+ // published but the dependent follow-up is withheld and the state is reported.
+ describe('when the old worktree could not be released (#9909)', () => {
+ const reviewLoopOpts = {
+ prCreation: 'always', requestCopilotReview: true, description: 'X',
+ originalTask: { id: 'task-orig', metadata: {}, description: 'X' },
+ };
+ // `clearAllMocks` keeps implementations, so restore what these tests override.
+ afterEach(() => {
+ removeWorktree.mockReset().mockResolvedValue(undefined);
+ findPullRequestForBranchMock.mockReset().mockResolvedValue({ status: 'unavailable' });
+ });
+ const openPr = () => {
+ git.push.mockResolvedValue(undefined);
+ git.createPR.mockResolvedValue({ success: true, url: 'https://github.com/test/repo/pull/45' });
+ git.requestCopilotReview.mockResolvedValue({ success: true });
+ addTask.mockResolvedValue({ id: 'sys-rl-held' });
+ };
+
+ it('keeps the PR published but does not dispatch the follow-up into the occupied branch', async () => {
+ openPr();
+ removeWorktree.mockResolvedValue({
+ merged: false, removed: false, cleanupIncomplete: true, uncommittedSaved: false,
+ warnings: ['Worktree cleanup incomplete for /wt/agent-1 (directory still present, git registration still registered) — retryable'],
+ });
+
+ const warnings = await cleanupAgentWorktree('agent-1', true, reviewLoopOpts);
+
+ expect(git.createPR).toHaveBeenCalledTimes(1);
+ expect(addTask).not.toHaveBeenCalled();
+ expect(forceSpawnTask).not.toHaveBeenCalled();
+ expect(warnings.some(w => /cleanup incomplete/.test(w))).toBe(true);
+ expect(warnings.some(w => w.includes('PR follow-up for https://github.com/test/repo/pull/45 deferred'))).toBe(true);
+ });
+
+ it('treats a thrown removal as an unreleased branch too', async () => {
+ openPr();
+ removeWorktree.mockRejectedValue(new Error('EBUSY'));
+
+ const warnings = await cleanupAgentWorktree('agent-1', true, reviewLoopOpts);
+
+ expect(addTask).not.toHaveBeenCalled();
+ expect(warnings.some(w => w.includes('Worktree cleanup failed: EBUSY'))).toBe(true);
+ expect(warnings.some(w => w.includes('deferred'))).toBe(true);
+ });
+
+ it('still dispatches the follow-up when the tree was merely preserved for uncommitted work', async () => {
+ openPr();
+ removeWorktree.mockResolvedValue({
+ merged: false, removed: false, uncommittedSaved: false,
+ warnings: ['Worktree preserved — uncommitted changes detected in /wt/agent-1: src/a.js'],
+ });
+
+ await cleanupAgentWorktree('agent-1', true, reviewLoopOpts);
+
+ expect(addTask).toHaveBeenCalledTimes(1);
+ });
+
+ it('withholds a failed run’s orphaned-PR follow-up the same way', async () => {
+ findPullRequestForBranchMock.mockResolvedValue({ status: 'found', url: 'https://github.com/test/repo/pull/78' });
+ removeWorktree.mockResolvedValue({
+ merged: false, removed: false, cleanupIncomplete: true, uncommittedSaved: false,
+ warnings: ['Worktree cleanup incomplete for /wt/agent-1 (directory still present, git registration removed) — retryable'],
+ });
+
+ const warnings = await cleanupAgentWorktree('agent-1', false, { prCreation: 'if-missing', description: 'Test task' });
+
+ expect(addTask).not.toHaveBeenCalled();
+ expect(warnings.some(w => w.includes('PR follow-up for https://github.com/test/repo/pull/78 deferred'))).toBe(true);
+ });
+ });
+
it('STILL spawns the review-loop follow-up when the Copilot pre-request fails (follow-up re-requests at its turn)', async () => {
git.push.mockResolvedValue(undefined);
git.createPR.mockResolvedValue({ success: true, url: 'https://github.com/test/repo/pull/43' });
diff --git a/server/services/git.js b/server/services/git.js
index 8d57d64361..868f762d2b 100644
--- a/server/services/git.js
+++ b/server/services/git.js
@@ -1645,7 +1645,8 @@ const WORKTREE_HOLD_REASONS = {
'worktree-locked': 'worktree is locked',
'worktree-active-agent': 'worktree is in use by a running agent',
'worktree-agent-liveness-unknown': 'agent liveness unknown',
- 'worktree-human-claim': 'worktree is a claimed session'
+ 'worktree-human-claim': 'worktree is a claimed session',
+ 'remove-failed': 'worktree removal failed and the checkout is still present'
};
const worktreeHoldReason = (reason) => WORKTREE_HOLD_REASONS[reason] || 'checked out in a worktree';
diff --git a/server/services/worktreeManager.forceRemove.test.js b/server/services/worktreeManager.forceRemove.test.js
index 758e998913..c715306d3e 100644
--- a/server/services/worktreeManager.forceRemove.test.js
+++ b/server/services/worktreeManager.forceRemove.test.js
@@ -1,91 +1,174 @@
-import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { describe, it, expect, vi, beforeAll, afterAll, beforeEach } from 'vitest';
+import { mkdtemp, rm as realRm, writeFile, lstat, mkdir } from 'fs/promises';
+import { existsSync, realpathSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import { materializeGitRepo, resetGitWorktreeSandbox, SKIP_HEAVY_INTEGRATION } from '../lib/gitTestRepo.js';
-// Mock the two side-effecting deps so we can assert the fallback dance without
-// touching git or the filesystem. Kept in its own test file so the pure-logic
-// suite in worktreeManager.test.js stays mock-free.
-vi.mock('../lib/execGit.js', () => ({ execGit: vi.fn() }));
+// Failure injection seams over REAL git and a REAL filesystem: both default to
+// the genuine implementation, and a test opts one call into rejecting. The
+// assertions then look at the surviving directory and registration, not at the
+// order the mocks were called in.
+const injected = vi.hoisted(() => ({ gitFails: () => false, rmFails: false }));
+vi.mock('../lib/execGit.js', async (importOriginal) => {
+ const actual = await importOriginal();
+ return {
+ ...actual,
+ execGit: vi.fn((args, ...rest) => (injected.gitFails(args)
+ ? Promise.reject(new Error(`injected git failure: ${args.slice(0, 2).join(' ')}`))
+ : actual.execGit(args, ...rest))),
+ };
+});
vi.mock('fs/promises', async (importOriginal) => {
const actual = await importOriginal();
- return { ...actual, rm: vi.fn() };
+ return {
+ ...actual,
+ rm: vi.fn((...args) => (injected.rmFails
+ ? Promise.reject(Object.assign(new Error('injected EPERM'), { code: 'EPERM' }))
+ : actual.rm(...args))),
+ };
});
import { execGit } from '../lib/execGit.js';
-import { rm } from 'fs/promises';
import { forceRemoveWorktreeDir } from './worktreeManager.js';
-describe('forceRemoveWorktreeDir', () => {
- beforeEach(() => {
- vi.clearAllMocks();
+describe.skipIf(SKIP_HEAVY_INTEGRATION)('forceRemoveWorktreeDir', () => {
+ let repo;
+ let safePath;
+ let initialHead;
+ let n = 0;
+
+ beforeAll(async () => {
+ safePath = realpathSync(await mkdtemp(join(tmpdir(), 'portos-force-remove-')));
+ await materializeGitRepo(safePath, { identity: { email: '[email protected]', name: 'Test' } });
+ repo = (await execGit(['rev-parse', '--show-toplevel'], safePath)).stdout.trim() || safePath;
+ initialHead = (await execGit(['rev-parse', 'HEAD'], repo)).stdout.trim();
+ });
+ beforeEach(async () => {
+ injected.gitFails = () => false;
+ injected.rmFails = false;
vi.spyOn(console, 'log').mockImplementation(() => {});
+ vi.spyOn(console, 'warn').mockImplementation(() => {});
+ await resetGitWorktreeSandbox(repo, initialHead, safePath);
+ });
+ afterAll(async () => {
+ injected.rmFails = false; // the cleanup below goes through the same mocked module
+ await realRm(repo, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
});
- it('happy path: a successful `worktree remove --force` skips the rm + prune fallback', async () => {
- execGit.mockResolvedValue({ stdout: '', stderr: '' });
- await forceRemoveWorktreeDir('/repo', '/repo/wt');
- expect(execGit).toHaveBeenCalledTimes(1);
- expect(execGit).toHaveBeenCalledWith(['worktree', 'remove', '/repo/wt', '--force'], '/repo');
- expect(rm).not.toHaveBeenCalled();
+ async function addWorktree() {
+ const path = join(repo, '.claude', 'worktrees', `wt-${++n}`);
+ await mkdir(join(repo, '.claude', 'worktrees'), { recursive: true });
+ await execGit(['worktree', 'add', '-b', `br-${n}`, path, 'main'], repo);
+ return (await execGit(['rev-parse', '--show-toplevel'], path)).stdout.trim() || path;
+ }
+ const registered = async (path) =>
+ (await execGit(['worktree', 'list', '--porcelain'], repo)).stdout.split(/\r?\n/)
+ .some(line => line.startsWith('worktree ') && line.slice(9).replace(/\\/g, '/') === path.replace(/\\/g, '/'));
+
+ it('removes a clean worktree and verifies both its directory and registration are gone', async () => {
+ const path = await addWorktree();
+ const outcome = await forceRemoveWorktreeDir(repo, path);
+ expect(outcome).toMatchObject({ removed: true, directory: 'absent', registration: 'absent', warning: null });
+ expect(existsSync(path)).toBe(false);
+ expect(await registered(path)).toBe(false);
});
- it('fallback: when remove rejects, rm -rf then `worktree prune` run', async () => {
- // First call (remove) rejects; second call (prune) resolves.
- execGit.mockRejectedValueOnce(new Error('locked')).mockResolvedValueOnce({ stdout: '', stderr: '' });
- rm.mockResolvedValue();
- await forceRemoveWorktreeDir('/repo', '/repo/wt');
- expect(rm).toHaveBeenCalledWith('/repo/wt', { recursive: true, force: true });
- expect(execGit).toHaveBeenCalledTimes(2);
- expect(execGit).toHaveBeenLastCalledWith(['worktree', 'prune'], '/repo');
+ it('falls back to rm + prune when git refuses, and reports the verified result', async () => {
+ const path = await addWorktree();
+ injected.gitFails = (args) => args[0] === 'worktree' && args[1] === 'remove';
+ const outcome = await forceRemoveWorktreeDir(repo, path);
+ expect(outcome.removed).toBe(true);
+ expect(existsSync(path)).toBe(false);
+ expect(await registered(path)).toBe(false);
});
- it('never throws even when the rm AND prune fallbacks also fail (best-effort cleanup)', async () => {
- execGit.mockRejectedValueOnce(new Error('remove failed')).mockRejectedValueOnce(new Error('prune failed'));
- rm.mockRejectedValue(new Error('rm failed'));
- await expect(forceRemoveWorktreeDir('/repo', '/repo/wt')).resolves.toBeUndefined();
+ it('reports an already-removed directory with a stale registration as removed once pruned', async () => {
+ const path = await addWorktree();
+ await realRm(path, { recursive: true, force: true });
+ expect(await registered(path)).toBe(true);
+ const outcome = await forceRemoveWorktreeDir(repo, path);
+ expect(outcome.removed).toBe(true);
+ expect(await registered(path)).toBe(false);
});
- it('label gates the remove-failure log; absent label stays silent', async () => {
- execGit.mockRejectedValueOnce(new Error('boom')).mockResolvedValueOnce({ stdout: '', stderr: '' });
- rm.mockResolvedValue();
+ it('treats an already-clean state (no directory, no registration) as removed', async () => {
+ const path = await addWorktree();
+ await forceRemoveWorktreeDir(repo, path);
+ expect((await forceRemoveWorktreeDir(repo, path)).removed).toBe(true);
+ });
- await forceRemoveWorktreeDir('/repo', '/repo/wt', { label: 'Remove failed for agent-1' });
- expect(console.log).toHaveBeenCalledWith(expect.stringContaining('⚠️ Remove failed for agent-1: boom'));
+ it('returns an incomplete outcome with an actionable warning when git removal AND rm both fail', async () => {
+ const path = await addWorktree();
+ await writeFile(join(path, 'keep.txt'), 'still here\n');
+ injected.gitFails = (args) => args[0] === 'worktree' && args[1] === 'remove';
+ injected.rmFails = true;
- console.log.mockClear();
- execGit.mockRejectedValueOnce(new Error('boom')).mockResolvedValueOnce({ stdout: '', stderr: '' });
- await forceRemoveWorktreeDir('/repo', '/repo/wt'); // no label
- expect(console.log).not.toHaveBeenCalled();
+ const outcome = await forceRemoveWorktreeDir(repo, path, { label: 'test cleanup' });
+
+ expect(outcome).toMatchObject({ removed: false, directory: 'present', registration: 'registered' });
+ expect(outcome.warning).toMatch(/cleanup incomplete/);
+ expect(outcome.warning).toContain(path);
+ expect(outcome.warning).toMatch(/directory still present/);
+ expect(outcome.warning).toMatch(/registration still registered/);
+ expect(outcome.warning).toMatch(/retryable/);
+ expect(outcome.warning).toContain('injected EPERM');
+ // The checkout genuinely survived — the report is not a guess.
+ expect(existsSync(join(path, 'keep.txt'))).toBe(true);
+ expect(await registered(path)).toBe(true);
+ expect(console.warn).toHaveBeenCalledWith(expect.stringContaining('cleanup incomplete'));
});
- it("log:'all' gates the rm + prune sub-failure logs", async () => {
- execGit.mockRejectedValueOnce(new Error('boom')).mockRejectedValueOnce(new Error('prune boom'));
- rm.mockRejectedValue(new Error('rm boom'));
+ it('keeps a locked registration visible: the directory is removed but the outcome is incomplete', async () => {
+ const path = await addWorktree();
+ await execGit(['worktree', 'lock', path], repo);
+ const outcome = await forceRemoveWorktreeDir(repo, path);
+ expect(outcome).toMatchObject({ removed: false, directory: 'absent', registration: 'registered' });
+ expect(existsSync(path)).toBe(false);
+ expect(await registered(path)).toBe(true);
+ });
- // default log:'remove' → only the labelled remove line, no rm/prune lines
- await forceRemoveWorktreeDir('/repo', '/repo/wt', { label: 'L' });
- expect(console.log).toHaveBeenCalledTimes(1);
- expect(console.log).toHaveBeenCalledWith(expect.stringContaining('⚠️ L: boom'));
+ it('never reads an unverifiable registration as success', async () => {
+ const path = await addWorktree();
+ // Git removal works, but the follow-up verification cannot read the registry.
+ injected.gitFails = (args) => args[0] === 'worktree' && args[1] === 'list';
+ const outcome = await forceRemoveWorktreeDir(repo, path);
+ expect(existsSync(path)).toBe(false);
+ expect(outcome).toMatchObject({ removed: false, directory: 'absent', registration: 'unknown' });
+ expect(outcome.warning).toMatch(/registration unverified/);
+ });
+
+ it('never throws, and bounds the error excerpt carried in the warning', async () => {
+ const path = await addWorktree();
+ injected.gitFails = (args) => args[0] === 'worktree';
+ injected.rmFails = true;
+ const outcome = await forceRemoveWorktreeDir(repo, path);
+ expect(outcome.removed).toBe(false);
+ expect(outcome.warning.length).toBeLessThan(600);
+ await expect(lstat(path)).resolves.toBeTruthy();
+ });
+
+ it('label gates the remove-failure log; absent label stays silent', async () => {
+ const path = await addWorktree();
+ injected.gitFails = (args) => args[0] === 'worktree' && args[1] === 'remove';
+ await forceRemoveWorktreeDir(repo, path, { label: 'Remove failed for agent-1' });
+ expect(console.log).toHaveBeenCalledWith(expect.stringContaining('⚠️ Remove failed for agent-1: injected git failure'));
console.log.mockClear();
- execGit.mockRejectedValueOnce(new Error('boom')).mockRejectedValueOnce(new Error('prune boom'));
- rm.mockRejectedValue(new Error('rm boom'));
- // log:'all' → remove line + rm-failure line + prune-failure line (3 logs)
- await forceRemoveWorktreeDir('/repo', '/repo/wt', { label: 'L', log: 'all' });
- expect(console.log).toHaveBeenCalledTimes(3);
+ const second = await addWorktree();
+ await forceRemoveWorktreeDir(repo, second); // no label
+ expect(console.log).not.toHaveBeenCalled();
});
- it("subject identifies the rm/prune sub-failures (defaults to the path, overridable to an agent id)", async () => {
- // Default subject = worktreePath.
- execGit.mockRejectedValueOnce(new Error('boom')).mockRejectedValueOnce(new Error('prune boom'));
- rm.mockRejectedValue(new Error('rm boom'));
- await forceRemoveWorktreeDir('/repo', '/repo/wt', { label: 'L', log: 'all' });
- expect(console.log).toHaveBeenCalledWith(expect.stringContaining('Manual rm failed for worktree /repo/wt'));
- expect(console.log).toHaveBeenCalledWith(expect.stringContaining('Worktree prune failed for /repo/wt'));
+ it("log:'all' gates the rm + prune sub-failure logs, and `subject` names them", async () => {
+ const path = await addWorktree();
+ injected.gitFails = (args) => args[0] === 'worktree' && (args[1] === 'remove' || args[1] === 'prune');
+ injected.rmFails = true;
+ await forceRemoveWorktreeDir(repo, path, { label: 'L' });
+ expect(console.log).toHaveBeenCalledTimes(1); // default log:'remove' → only the remove line
- // Override subject → the agent id appears instead (preserves pre-extraction wording).
console.log.mockClear();
- execGit.mockRejectedValueOnce(new Error('boom')).mockRejectedValueOnce(new Error('prune boom'));
- rm.mockRejectedValue(new Error('rm boom'));
- await forceRemoveWorktreeDir('/repo', '/repo/wt', { label: 'L', log: 'all', subject: 'agent-42' });
+ await forceRemoveWorktreeDir(repo, path, { label: 'L', log: 'all', subject: 'agent-42' });
expect(console.log).toHaveBeenCalledWith(expect.stringContaining('Manual rm failed for worktree agent-42'));
expect(console.log).toHaveBeenCalledWith(expect.stringContaining('Worktree prune failed for agent-42'));
});
diff --git a/server/services/worktreeManager.js b/server/services/worktreeManager.js
index 0bf5c6765a..9a3a65695c 100644
--- a/server/services/worktreeManager.js
+++ b/server/services/worktreeManager.js
@@ -273,14 +273,74 @@ async function cleanupOrphanBranch(repo, branchName, err) {
});
}
+/** Longest error excerpt a removal warning carries — warnings reach cards and task context. */
+const REMOVAL_ERROR_EXCERPT_CHARS = 200;
+
+/** First line of an error, bounded, for a one-line warning. */
+function errorExcerpt(err) {
+ return String(err?.message ?? err ?? '').split('\n')[0].slice(0, REMOVAL_ERROR_EXCERPT_CHARS);
+}
+
+/**
+ * Realpath of `p` even when `p` itself is gone: resolve the deepest existing
+ * ancestor and re-append the missing tail, so a removed worktree compares equal
+ * to the form git registered it under (macOS /var → /private/var).
+ */
+function canonicalPath(p) {
+ try { return realpathSync(p); } catch { /* fall through to the ancestor walk */ }
+ const parent = dirname(p);
+ return parent === p ? p : join(canonicalPath(parent), p.slice(parent.length).replace(/^[\\/]+/, ''));
+}
+
+/**
+ * Observe whether a worktree's directory and Git registration are really gone.
+ * Each probe answers `'unknown'` when it could not be read — an unverifiable
+ * state is NOT absence, so callers never report cleanup they did not establish.
+ *
+ * @returns {Promise<{directory: 'present'|'absent'|'unknown', registration: 'registered'|'absent'|'unknown'}>}
+ */
+async function probeWorktreeRemoval(repo, worktreePath) {
+ const directory = await lstat(worktreePath).then(
+ () => 'present',
+ (err) => (err?.code === 'ENOENT' || err?.code === 'ENOTDIR' ? 'absent' : 'unknown'),
+ );
+ const target = canonicalPath(worktreePath);
+ const registration = await listWorktrees(repo).then(
+ (entries) => (entries.some(wt => canonicalPath(wt.path) === target) ? 'registered' : 'absent'),
+ () => 'unknown',
+ );
+ return { directory, registration };
+}
+
+/**
+ * Fold a probe into the removal outcome every caller consumes. `removed` is true
+ * only when BOTH the directory and the registration were observed absent;
+ * `warning` is a bounded, retryable one-liner when they were not.
+ */
+function removalOutcome(worktreePath, { directory, registration }, failure = null) {
+ const removed = directory === 'absent' && registration === 'absent';
+ const state = `directory ${directory === 'absent' ? 'removed' : directory === 'present' ? 'still present' : 'unverified'}, `
+ + `git registration ${registration === 'absent' ? 'removed' : registration === 'registered' ? 'still registered' : 'unverified'}`;
+ return {
+ removed,
+ directory,
+ registration,
+ warning: removed ? null : `Worktree cleanup incomplete for ${worktreePath} (${state})${failure ? `: ${failure}` : ''} — retryable`,
+ };
+}
+
/**
* Remove a worktree directory robustly: try `git worktree remove --force`, and
* if git refuses (locked, already-gone, broken admin files), fall back to a
* plain recursive `rm` + `git worktree prune` to clear git's stale bookkeeping.
- * Every step swallows its own error — cleanup is best-effort and must never
- * throw into a completion/reap path. Inlined verbatim in four call sites
- * before extraction (removeWorktree, removePersistentWorktree,
- * reapMergedWorktrees, cleanupExternalRepoWorktrees).
+ * Never throws — cleanup is best-effort and must never throw into a
+ * completion/reap path — but it DOES report what it achieved: after every
+ * attempt it re-reads the exact directory and its Git registration, and
+ * `removed` is true only when both are observed gone. A caller that releases a
+ * branch, counts a reap or queues a follow-up must gate on `removed`; swallowing
+ * the failure is how a checkout that survived read as a completed cleanup.
+ * Shared by removeWorktree, removePersistentWorktree, reapMergedWorktrees,
+ * branch reconciliation and the worktree-add rollback.
*
* @param {string} repo - the git workspace to run worktree commands in (the
* parent repo for the worktree, NOT the worktree dir itself).
@@ -300,18 +360,27 @@ async function cleanupOrphanBranch(repo, branchName, err) {
* `worktreePath`; the agent-cleanup callers pass their agent id so the
* message wording stays byte-identical to the pre-extraction logs an operator
* may grep for (e.g. `… for worktree <agentId>`).
+ * @returns {Promise<{removed: boolean, directory: string, registration: string, warning: string|null}>}
+ * `warning` is set exactly when `removed` is false.
*/
export async function forceRemoveWorktreeDir(repo, worktreePath, { label, log = 'remove', subject = worktreePath } = {}) {
const logAll = label && log === 'all';
+ let lastFailure = null;
await execGit(['worktree', 'remove', worktreePath, '--force'], repo).catch(async (err) => {
+ lastFailure = errorExcerpt(err);
if (label) console.log(`⚠️ ${label}: ${err.message}`);
await rm(worktreePath, { recursive: true, force: true }).catch((rmErr) => {
+ lastFailure = errorExcerpt(rmErr);
if (logAll) console.log(`⚠️ Manual rm failed for worktree ${subject}: ${rmErr.message}`);
});
await execGit(['worktree', 'prune'], repo).catch((pruneErr) => {
+ lastFailure = errorExcerpt(pruneErr);
if (logAll) console.log(`⚠️ Worktree prune failed for ${subject}: ${pruneErr.message}`);
});
});
+ const outcome = removalOutcome(worktreePath, await probeWorktreeRemoval(repo, worktreePath), lastFailure);
+ if (!outcome.removed && label) console.warn(`⚠️ ${outcome.warning}`);
+ return outcome;
}
/**
@@ -330,12 +399,15 @@ export async function forceRemoveWorktreeDir(repo, worktreePath, { label, log =
*/
async function enforceUpstreamOrUndoAdd(sourceWorkspace, branchName, worktreePath, { deleteBranch }) {
return enforceSafeBranchUpstream(sourceWorkspace, branchName).catch(async (err) => {
- await forceRemoveWorktreeDir(sourceWorkspace, worktreePath, {
+ const undone = await forceRemoveWorktreeDir(sourceWorkspace, worktreePath, {
label: `Undoing worktree add for ${branchName} after an unsafe upstream`,
log: 'all',
subject: branchName,
- }).catch(() => {});
- if (deleteBranch) await cleanupOrphanBranch(sourceWorkspace, branchName, err);
+ });
+ // A branch still held by the surviving checkout cannot be deleted; leave it
+ // rather than attempt a `branch -D` that fails. The ORIGINAL error is what
+ // the caller sees either way — the rollback outcome never replaces it.
+ if (deleteBranch && undone.removed) await cleanupOrphanBranch(sourceWorkspace, branchName, err);
throw err;
});
}
@@ -932,6 +1004,14 @@ export async function removeWorktree(agentId, sourceWorkspace, branchName, optio
const warnings = [];
if (!existsSync(worktreePath)) {
+ // The directory is gone, but git may still register it (a stale entry pins the
+ // branch). Verify rather than assume; prune when the registration survives.
+ let gone = removalOutcome(worktreePath, await probeWorktreeRemoval(sourceWorkspace, worktreePath));
+ if (!gone.removed) gone = await forceRemoveWorktreeDir(sourceWorkspace, worktreePath);
+ if (!gone.removed) {
+ warnings.push(gone.warning);
+ return { merged: false, removed: false, cleanupIncomplete: true, uncommittedSaved: false, warnings };
+ }
console.log(`🌳 Worktree already removed for ${agentId}, cleaning up branch`);
await execGit(['branch', '-D', branchName], sourceWorkspace).catch(() => {});
return { merged: false, removed: true, uncommittedSaved: false, warnings };
@@ -949,9 +1029,14 @@ export async function removeWorktree(agentId, sourceWorkspace, branchName, optio
// or normalization differences don't false-positive as a broken worktree.
if (detectedToplevel && !pathsEqual(detectedToplevel, worktreePath)) {
console.log(`🌳 Worktree ${agentId} resolves to ${detectedToplevel} instead of ${worktreePath} — broken worktree, removing`);
- await rm(worktreePath, { recursive: true, force: true }).catch(rmErr => {
+ const rmFailure = await rm(worktreePath, { recursive: true, force: true }).then(() => null, rmErr => {
console.log(`⚠️ Failed to remove broken worktree ${agentId}: ${rmErr.message}`);
+ return rmErr;
});
+ if (rmFailure) {
+ warnings.push(`Worktree cleanup incomplete for ${worktreePath} (broken checkout still present): ${errorExcerpt(rmFailure)} — retryable`);
+ return { merged: false, removed: false, cleanupIncomplete: true, uncommittedSaved: false, warnings };
+ }
await execGit(['branch', '-D', branchName], sourceWorkspace).catch(() => {});
return { merged: false, removed: true, uncommittedSaved: false, warnings };
}
@@ -1039,11 +1124,20 @@ export async function removeWorktree(agentId, sourceWorkspace, branchName, optio
}
}
- await forceRemoveWorktreeDir(sourceWorkspace, worktreePath, {
+ const removal = await forceRemoveWorktreeDir(sourceWorkspace, worktreePath, {
label: `Worktree remove failed for ${agentId}, falling back to manual cleanup`,
log: 'all',
subject: agentId,
});
+ if (!removal.removed) {
+ // The checkout (or its registration) survived: the branch is still held, so
+ // deleting it would fail, and `removed: true` would tell the caller it may
+ // queue work onto a branch the old worktree still owns. Report the truth with
+ // a retryable warning; `merged` stays accurate for the publication outcome.
+ console.warn(`⚠️ Worktree for ${agentId} was not removed — branch ${branchName} kept`);
+ warnings.push(removal.warning);
+ return { merged, removed: false, cleanupIncomplete: true, uncommittedSaved: false, warnings };
+ }
// Preserve branch when (a) merge was attempted, failed, and has unmerged commits,
// OR (b) merge was refused because HEAD is on a non-default branch — the commits
@@ -1191,18 +1285,19 @@ export async function removePersistentWorktree(featureAgentId, sourceWorkspace,
if (!existsSync(worktreePath)) return { removed: false };
- await forceRemoveWorktreeDir(sourceWorkspace, worktreePath, {
+ const removal = await forceRemoveWorktreeDir(sourceWorkspace, worktreePath, {
label: `Persistent worktree remove failed for ${featureAgentId}, falling back`,
log: 'all',
subject: featureAgentId,
});
+ if (!removal.removed) return { removed: false, cleanupIncomplete: true, warnings: [removal.warning] };
await execGit(['branch', '-D', branchName], sourceWorkspace).catch(err => {
console.log(`⚠️ Branch delete failed for ${branchName}: ${err.message}`);
});
console.log(`🌳 Removed persistent worktree for feature agent ${featureAgentId}`);
- return { removed: true };
+ return { removed: true, warnings: [] };
}
/**
@@ -1400,7 +1495,7 @@ export async function cleanupOrphanedWorktrees(sourceWorkspace, activeAgentIds)
* @param {string} [options.defaultBranch] - skip the default-branch lookup, which can
* contact the remote (`remote set-head`); pass it on a latency-sensitive request path
* @param {boolean} [options.dryRun=false] - report candidates without deleting
- * @returns {Promise<{reaped: Array<{path,branch,locked,branchDeleted}>, skipped: Array<{path,branch,reason}>, defaultBranch: string, target: string, dryRun: boolean}>}
+ * @returns {Promise<{reaped: Array<{path,branch,locked,branchDeleted}>, skipped: Array<{path,branch,reason,warning?}>, defaultBranch: string, target: string, dryRun: boolean}>}
*/
export async function reapMergedWorktrees(sourceWorkspace, {
activeAgentIds = new Set(),
@@ -1481,10 +1576,16 @@ export async function reapMergedWorktrees(sourceWorkspace, {
// Remove the worktree, then force-delete the branch (-D because squash-merged
// branches aren't recognized by -d, and we've proven the work is in default).
- await forceRemoveWorktreeDir(sourceWorkspace, wt.path, {
+ const removal = await forceRemoveWorktreeDir(sourceWorkspace, wt.path, {
label: `worktree remove failed for ${wt.path}, manual cleanup`,
});
- // Reported per entry: the tree is gone either way, but a caller that
+ // A checkout that survived is not a reap: it is held (not counted) with the
+ // retryable warning, and the branch is left alone — it is still checked out.
+ if (!removal.removed) {
+ skipped.push({ path: wt.path, branch: branchName, reason: 'remove-failed', warning: removal.warning });
+ continue;
+ }
+ // Reported per entry: the tree is gone, but a caller that
// presents this as "branch deleted" would otherwise be lying on a failure.
const branchDeleted = await execGit(['branch', '-D', branchName], sourceWorkspace).then(() => true).catch(err => {
console.log(`⚠️ branch delete failed for ${branchName}: ${err.message}`);
diff --git a/server/services/worktreeManager.test.js b/server/services/worktreeManager.test.js
index bd432d2931..f773ce0e3e 100644
--- a/server/services/worktreeManager.test.js
+++ b/server/services/worktreeManager.test.js
@@ -44,6 +44,7 @@ const {
isPreexistingRefError,
isBranchCheckedOutElsewhereError,
removeWorktree,
+ removePersistentWorktree,
adoptWorktree,
findAdoptableWorktreeForBranch,
createWorktree,
@@ -688,12 +689,106 @@ describe('removeWorktree identity, dirt and branch preservation', () => {
hasBranchMergeEvidenceMock.mockResolvedValue(false);
existsSync.mockReset().mockReturnValue(true);
realpathSync.mockReset().mockImplementation(p => p);
+ // Removal is verified against the real directory afterwards; scripted removals
+ // succeed, so the worktree directory reads as gone (and `worktree list` as empty).
+ lstat.mockReset().mockRejectedValue(Object.assign(new Error('gone'), { code: 'ENOENT' }));
rm.mockClear();
scriptGit();
});
afterEach(() => {
realpathSync.mockReset().mockImplementation(p => p);
+ lstat.mockReset().mockResolvedValue({});
+ });
+
+ describe('when the checkout survives removal (#9909)', () => {
+ const present = () => lstat.mockReset().mockResolvedValue({});
+ const failRemoval = () => {
+ const scripted = execGitMock.getMockImplementation();
+ execGitMock.mockImplementation((args, ...rest) => (args[0] === 'worktree' && args[1] === 'remove'
+ ? Promise.reject(new Error('Permission denied'))
+ : scripted(args, ...rest)));
+ rm.mockRejectedValue(new Error('EPERM: operation not permitted'));
+ };
+ afterEach(() => { rm.mockReset().mockResolvedValue(undefined); });
+
+ it('reports removed:false with a retryable warning, keeps the branch, and flags cleanupIncomplete', async () => {
+ present();
+ failRemoval();
+
+ const result = await removeWorktree('agent-x', '/repo', 'cos/task-1/agent-x', { merge: false });
+
+ expect(result).toMatchObject({ merged: false, removed: false, cleanupIncomplete: true });
+ expect(result.warnings.join(' ')).toMatch(/cleanup incomplete.*directory still present.*retryable/);
+ expect(calledWith(['branch', '-D', 'cos/task-1/agent-x'])).toBe(false);
+ });
+
+ it('keeps `merged` accurate for the publication outcome while still refusing to claim removal', async () => {
+ present();
+ failRemoval();
+ const scripted = execGitMock.getMockImplementation();
+ execGitMock.mockImplementation((args, ...rest) => (args[0] === 'rev-list' ? Promise.resolve({ stdout: '2' })
+ : (args[0] === 'rev-parse' && args[1] === '--abbrev-ref' ? Promise.resolve({ stdout: 'main' }) : scripted(args, ...rest))));
+ getDefaultBranchMock.mockResolvedValue('main');
+
+ const result = await removeWorktree('agent-x', '/repo', 'cos/task-1/agent-x', { merge: true });
+
+ expect(result.removed).toBe(false);
+ expect(result.merged).toBe(true);
+ expect(calledWith(['branch', '-D', 'cos/task-1/agent-x'])).toBe(false);
+ });
+
+ it('verifies a missing directory whose registration is stale instead of assuming it is gone', async () => {
+ existsSync.mockReturnValue(false);
+ const path = join(PATHS.worktrees, 'agent-x');
+ let pruned = false;
+ execGitMock.mockImplementation((args) => {
+ if (args[0] === 'worktree' && args[1] === 'prune') pruned = true;
+ if (args[0] === 'worktree' && args[1] === 'remove') return Promise.reject(new Error('is not a working tree'));
+ if (args[0] === 'worktree' && args[1] === 'list') {
+ return Promise.resolve({ stdout: pruned ? '' : `worktree ${path}\nHEAD abc\nbranch refs/heads/cos/task-1/agent-x\nprunable\n` });
+ }
+ return Promise.resolve({ stdout: '', stderr: '', exitCode: 0 });
+ });
+
+ const result = await removeWorktree('agent-x', '/repo', 'cos/task-1/agent-x', { merge: false });
+
+ expect(result.removed).toBe(true);
+ expect(pruned).toBe(true);
+ expect(calledWith(['branch', '-D', 'cos/task-1/agent-x'])).toBe(true);
+ });
+
+ it('does not report an already-gone directory as removed while its registration survives', async () => {
+ existsSync.mockReturnValue(false);
+ const path = join(PATHS.worktrees, 'agent-x');
+ execGitMock.mockImplementation((args) => {
+ if (args[0] === 'worktree' && args[1] === 'list') return Promise.resolve({ stdout: `worktree ${path}\nHEAD abc\nbranch refs/heads/b\nlocked\n` });
+ if (args[0] === 'worktree' && args[1] === 'remove') return Promise.reject(new Error('locked'));
+ return Promise.resolve({ stdout: '', stderr: '', exitCode: 0 });
+ });
+
+ const result = await removeWorktree('agent-x', '/repo', 'cos/task-1/agent-x', { merge: false });
+
+ expect(result).toMatchObject({ removed: false, cleanupIncomplete: true });
+ expect(calledWith(['branch', '-D', 'cos/task-1/agent-x'])).toBe(false);
+ });
+
+ it('persistent removal reports the survivor and keeps the branch', async () => {
+ present();
+ failRemoval();
+
+ const result = await removePersistentWorktree('fa-1', '/repo', 'feature/x');
+
+ expect(result).toMatchObject({ removed: false, cleanupIncomplete: true });
+ expect(result.warnings.join(' ')).toMatch(/cleanup incomplete/);
+ expect(calledWith(['branch', '-D', 'feature/x'])).toBe(false);
+ });
+
+ it('persistent removal still reports a verified removal', async () => {
+ const result = await removePersistentWorktree('fa-1', '/repo', 'feature/x');
+ expect(result).toEqual({ removed: true, warnings: [] });
+ expect(calledWith(['branch', '-D', 'feature/x'])).toBe(true);
+ });
});
it('removes a broken tree resolving to the parent without trusting its dirty status', async () => {
@@ -1267,12 +1362,16 @@ describe('cleanupOrphanedWorktrees ownership and removal', () => {
beforeEach(() => {
existsSync.mockReset().mockReturnValue(true);
readdir.mockReset().mockResolvedValue([]);
+ lstat.mockReset().mockRejectedValue(Object.assign(new Error('gone'), { code: 'ENOENT' }));
rm.mockClear();
getDefaultBranchMock.mockResolvedValue('main');
execGitMock.mockReset();
});
- afterEach(() => { readdir.mockReset().mockResolvedValue([]); });
+ afterEach(() => {
+ readdir.mockReset().mockResolvedValue([]);
+ lstat.mockReset().mockResolvedValue({});
+ });
it('removes only the clean inactive agent and preserves active, human, locked and dirty trees', async () => {
const entries = [
@@ -1284,7 +1383,10 @@ describe('cleanupOrphanedWorktrees ownership and removal', () => {
{ path: tree('agent-dead'), branch: 'cos/task/agent-dead' },
{ path: tree('agent-dirty'), branch: 'cos/task/agent-dirty' },
];
- const stdout = entries.flatMap(entry => [
+ // `worktree list` reflects removals made so far, as real git does — removal is
+ // verified against the registration afterwards.
+ const removedPaths = new Set();
+ const listing = () => entries.filter(entry => !removedPaths.has(entry.path)).flatMap(entry => [
'worktree ' + entry.path, 'HEAD abc123', 'branch refs/heads/' + entry.branch,
...(entry.locked ? ['locked protected'] : []), '',
]).join('\n');
@@ -1294,7 +1396,8 @@ describe('cleanupOrphanedWorktrees ownership and removal', () => {
name: win32.basename(entry.path), isDirectory: () => true,
})));
execGitMock.mockImplementation((args, cwd) => {
- if (args[0] === 'worktree' && args[1] === 'list') return Promise.resolve({ stdout });
+ if (args[0] === 'worktree' && args[1] === 'list') return Promise.resolve({ stdout: listing() });
+ if (args[0] === 'worktree' && args[1] === 'remove') removedPaths.add(args[2]);
if (args[0] === 'rev-parse') return Promise.resolve({ stdout: args[1] === '--show-toplevel' ? cwd : 'main' });
if (args[0] === 'status') return Promise.resolve({ stdout: cwd === tree('agent-dirty') ? ' M src/work.js' : '' });
if (args[0] === 'rev-list') return Promise.resolve({ stdout: '0' });
diff --git a/server/services/worktreeReap.test.js b/server/services/worktreeReap.test.js
index 03fc56df3e..07d88c7119 100644
--- a/server/services/worktreeReap.test.js
+++ b/server/services/worktreeReap.test.js
@@ -11,7 +11,7 @@
* is excluded from `npm run test:fast` (`VITEST_FAST=1`).
*/
import { describe, it, expect, beforeAll, beforeEach, afterAll } from 'vitest';
-import { mkdtemp, rm, writeFile, mkdir } from 'fs/promises';
+import { mkdtemp, rm, writeFile, mkdir, chmod } from 'fs/promises';
import { existsSync, realpathSync } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
@@ -263,6 +263,32 @@ describe.skipIf(SKIP_HEAVY_INTEGRATION)('reapMergedWorktrees', () => {
expect(existsSync(path)).toBe(true);
});
+ // A checkout git cannot remove (here: its parent directory is read-only) is not a
+ // reap — it must not be counted, and its branch must not be deleted out from
+ // under the surviving checkout (#9909).
+ it.skipIf(process.platform === 'win32' || process.getuid?.() === 0)(
+ 'holds a merged worktree whose removal fails instead of counting it as reaped',
+ async () => {
+ const path = await addWorktree(dir, 'stuck', 'stuck-br');
+ await execGit(['merge', '--no-ff', 'stuck-br', '--no-edit'], dir);
+ await chmod(claudeRoot(dir), 0o555);
+
+ let result;
+ try {
+ result = await reapMergedWorktrees(dir, { includeClaudeTrees: true });
+ } finally {
+ await chmod(claudeRoot(dir), 0o755);
+ }
+
+ expect(result.reaped.map(r => r.branch)).not.toContain('stuck-br');
+ expect(skipReason(result, path)).toBe('remove-failed');
+ expect(result.skipped.find(entry => entry.reason === 'remove-failed').warning).toMatch(/cleanup incomplete/);
+ expect(existsSync(path)).toBe(true);
+ const branches = (await execGit(['branch', '--format=%(refname:short)'], dir)).stdout.trim().split('\n');
+ expect(branches).toContain('stuck-br');
+ },
+ );
+
it('preserves a locked merged worktree', async () => {
const path = await addWorktree(dir, 'locked', 'locked-br');
await execGit(['merge', '--no-ff', 'locked-br', '--no-edit'], dir);