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

refactor: remove obsolete worktree cleanup controls (#12574)

[._.]/ Adam Eivy3f3873743f16
diff --git a/server/lib/repoStateExpectations.js b/server/lib/repoStateExpectations.js
index a181c6d306..2233cd0876 100644
--- a/server/lib/repoStateExpectations.js
+++ b/server/lib/repoStateExpectations.js
@@ -70,7 +70,7 @@ export const REPO_STATE_SKIPS = Object.freeze({
* The two skips worth spelling out:
*
* - **A failed run is never audited.** Its branch and worktree are PRESERVED on
- * purpose (`preserveBranchWithCommits`, `resolveResumePointer`) so the task's
+ * purpose by merge-evidence retention and `resolveResumePointer` so the task's
* retry resumes rather than restarts. Auditing it would report the resume
* pointer as a leak.
* - **A pending owner defers the audit.** A review-loop follow-up or a pr-watcher
diff --git a/server/services/agentWorktreeCleanup.js b/server/services/agentWorktreeCleanup.js
index 0b5989b07a..5ed19165cb 100644
--- a/server/services/agentWorktreeCleanup.js
+++ b/server/services/agentWorktreeCleanup.js
@@ -159,12 +159,12 @@ async function auditMergeGate(agentId, originalTask) {
// still governed by success/skipMerge even for stand-down: the existing local
// cleanup contract is independent of who opened the PR.
const WORKTREE_DISPOSITIONS = Object.freeze({
- 'not-a-worktree': Object.freeze({ merge: false, preserveBranch: false }),
- discard: Object.freeze({ merge: false, preserveBranch: false }),
- 'open-pr': Object.freeze({ merge: false, preserveBranch: false }),
- 'stand-down': Object.freeze({ preserveBranch: false }),
- 'stand-down-uncertain': Object.freeze({ preserveBranch: true }),
- 'stranded-pr-handoff': Object.freeze({ preserveBranch: true }),
+ 'not-a-worktree': Object.freeze({ merge: false }),
+ discard: Object.freeze({ merge: false }),
+ 'open-pr': Object.freeze({ merge: false }),
+ 'stand-down': Object.freeze({}),
+ 'stand-down-uncertain': Object.freeze({}),
+ 'stranded-pr-handoff': Object.freeze({}),
'merge-or-preserve': Object.freeze({}),
});
@@ -185,7 +185,6 @@ export function resolveWorktreeDisposition({ isWorktree, success, prCreation, di
return {
disposition: name,
merge: success && !skipMerge,
- preserveBranch: !success,
...WORKTREE_DISPOSITIONS[name],
};
}
@@ -587,14 +586,11 @@ async function mergeOrPreserveWorktree({ agentId, sourceWorkspace, worktreeBranc
agentId, branchName: worktreeBranch, merge: shouldMerge
});
+ // Cleanup retains branches without merge evidence, including failed runs and
+ // successful runs whose PR could not be confirmed. Their retry can resume
+ // from the preserved work through resolveResumeBranch below.
const result = await removeWorktree(agentId, sourceWorkspace, worktreeBranch, {
merge: shouldMerge,
- // A FAILED agent's branch is the only record of what it got done. Keep it when
- // it holds commits so the task's retry can attach to it and resume rather than
- // redo the work (see resolveResumeBranch below + removeWorktree's flag docs).
- // Same reasoning for a SUCCESSFUL run whose PR we could not confirm: we chose
- // not to push it, so the local branch is the only copy.
- preserveBranchWithCommits: disposition.preserveBranch,
}).catch(err => {
emitLog('warn', `🌳 Worktree cleanup failed for ${agentId}: ${err.message}`, { agentId });
return { cleanupIncomplete: true, warnings: [`Worktree cleanup failed: ${err.message}`] };
@@ -931,7 +927,7 @@ export async function recordTaskResumePointer({ task, agentId, agentMetadata })
* spawn mode (#3368, #3373).
*
* A failed agent whose branch — or whole worktree — survived cleanup leaves real
- * work behind (see `preserveBranchWithCommits` above; a dirty tree aborts removal
+ * work behind (cleanup requires merge evidence; a dirty tree aborts removal
* outright). Recording where it lives on the TASK is what makes its retry RESUME
* rather than restart from scratch — the behavior the agent-d2ae0352 incident
* exposed, where a run reaped 30s after its PR merged was re-dispatched to a fresh
diff --git a/server/services/cleanupAgentWorktree.test.js b/server/services/cleanupAgentWorktree.test.js
index 2b817cef3f..e8d1184cca 100644
--- a/server/services/cleanupAgentWorktree.test.js
+++ b/server/services/cleanupAgentWorktree.test.js
@@ -422,7 +422,7 @@ describe('cleanupAgentWorktree - PR-creation path', () => {
expect(git.push).not.toHaveBeenCalled();
expect(git.createPR).not.toHaveBeenCalled();
- expect(removeWorktree).toHaveBeenCalledWith('agent-1', '/mock/workspace', 'cos/task-abc123', { merge: true, preserveBranchWithCommits: false });
+ expect(removeWorktree).toHaveBeenCalledWith('agent-1', '/mock/workspace', 'cos/task-abc123', { merge: true });
});
it('should use auto-merge path when prCreation is not provided (defaults to never)', async () => {
@@ -430,7 +430,7 @@ describe('cleanupAgentWorktree - PR-creation path', () => {
expect(git.push).not.toHaveBeenCalled();
expect(git.createPR).not.toHaveBeenCalled();
- expect(removeWorktree).toHaveBeenCalledWith('agent-1', '/mock/workspace', 'cos/task-abc123', { merge: true, preserveBranchWithCommits: false });
+ expect(removeWorktree).toHaveBeenCalledWith('agent-1', '/mock/workspace', 'cos/task-abc123', { merge: true });
});
it('should skip PR flow when prCreation is always but success is false', async () => {
@@ -439,9 +439,7 @@ describe('cleanupAgentWorktree - PR-creation path', () => {
expect(git.push).not.toHaveBeenCalled();
expect(git.createPR).not.toHaveBeenCalled();
// Falls through to auto-merge path with merge: false (failure cleanup). A
- // FAILED agent additionally asks removeWorktree to KEEP the branch when it
- // holds commits, so the task's retry can resume from it (#3167).
- expect(removeWorktree).toHaveBeenCalledWith('agent-1', '/mock/workspace', 'cos/task-abc123', { merge: false, preserveBranchWithCommits: true });
+ expect(removeWorktree).toHaveBeenCalledWith('agent-1', '/mock/workspace', 'cos/task-abc123', { merge: false });
});
it('should use baseBranch as PR base (not devBranch, since worktrees are created from baseBranch)', async () => {
@@ -618,22 +616,18 @@ describe('cleanupAgentWorktree - PR-creation path', () => {
const warnings = await cleanupAgentWorktree('agent-1', true, netOpts);
expect(git.createPR).not.toHaveBeenCalled();
- // …but standing down must NOT also throw the work away. `removeWorktree`
- // deletes an unmerged branch outright on a `success` run, so without this
- // a transient `gh pr list` failure takes the agent's only copy of the
- // commits with it — we chose not to push, so the branch IS the copy.
expect(removeWorktree).toHaveBeenCalledWith('agent-1', '/mock/workspace', 'cos/task-abc123',
- expect.objectContaining({ preserveBranchWithCommits: true }));
+ { merge: true });
expect(warnings.some(w => w.includes('Could not confirm a pull request'))).toBe(true);
});
- it('lets the branch be tidied up when the agent DID open its PR', async () => {
+ it('continues cleanup without warnings when the agent opened its PR', async () => {
verifyPrClaimMock.mockResolvedValue({ ok: true, branch: 'cos/task-abc123' });
const warnings = await cleanupAgentWorktree('agent-1', true, netOpts);
expect(removeWorktree).toHaveBeenCalledWith('agent-1', '/mock/workspace', 'cos/task-abc123',
- expect.objectContaining({ preserveBranchWithCommits: false }));
+ { merge: true });
expect(warnings).toEqual([]);
});
@@ -650,7 +644,7 @@ describe('cleanupAgentWorktree - PR-creation path', () => {
expect(git.createPR).not.toHaveBeenCalled();
expect(removeWorktree).toHaveBeenCalledWith('agent-1', '/mock/workspace', 'cos/task-abc123',
- expect.objectContaining({ preserveBranchWithCommits: true }));
+ { merge: true });
expect(warnings.some(w => w.includes('Could not confirm a pull request'))).toBe(true);
});
@@ -662,7 +656,7 @@ describe('cleanupAgentWorktree - PR-creation path', () => {
expect(git.createPR).not.toHaveBeenCalled();
expect(removeWorktree).toHaveBeenCalledWith('agent-1', '/mock/workspace', 'cos/task-abc123',
- expect.objectContaining({ preserveBranchWithCommits: true }));
+ { merge: true });
});
it('stands down when the branch holds no commits — there was nothing to open a PR for', async () => {
@@ -1283,7 +1277,7 @@ describe('cleanupAgentWorktree - PR-creation path', () => {
expect(getPullRequestStateMock).toHaveBeenCalledWith('42', expect.objectContaining({ cwd: '/mock/workspace' }));
expect(findPullRequestForBranchMock).not.toHaveBeenCalled();
if (state === 'MERGED') {
- expect(removeWorktree).toHaveBeenCalledWith('agent-1', '/mock/workspace', 'fork/contributor/main', { merge: false, preserveBranchWithCommits: false });
+ expect(removeWorktree).toHaveBeenCalledWith('agent-1', '/mock/workspace', 'fork/contributor/main', { merge: false });
} else expect(removeWorktree).not.toHaveBeenCalled();
expect(git.deleteBranch).not.toHaveBeenCalled();
});
@@ -1295,7 +1289,7 @@ describe('cleanupAgentWorktree - PR-creation path', () => {
await cleanupAgentWorktree('agent-1', true, { prCreation: 'never', skipMerge: true });
expect(removeWorktree).toHaveBeenCalledWith(
- 'agent-1', '/mock/workspace', 'cos/task-abc123', { merge: false, preserveBranchWithCommits: false }
+ 'agent-1', '/mock/workspace', 'cos/task-abc123', { merge: false }
);
});
@@ -1303,29 +1297,11 @@ describe('cleanupAgentWorktree - PR-creation path', () => {
await cleanupAgentWorktree('agent-1', true, { prCreation: 'never', skipMerge: false });
expect(removeWorktree).toHaveBeenCalledWith(
- 'agent-1', '/mock/workspace', 'cos/task-abc123', { merge: true, preserveBranchWithCommits: false }
+ 'agent-1', '/mock/workspace', 'cos/task-abc123', { merge: true }
);
});
- // --- branch preservation for resume (#3167) ---
-
- it('asks removeWorktree to preserve a FAILED agent\'s branch so its retry can resume', async () => {
- await cleanupAgentWorktree('agent-1', false);
-
- expect(removeWorktree).toHaveBeenCalledWith(
- 'agent-1', '/mock/workspace', 'cos/task-abc123',
- expect.objectContaining({ preserveBranchWithCommits: true })
- );
- });
- it('does NOT preserve the branch on success — the merge/PR path owns cleanup', async () => {
- await cleanupAgentWorktree('agent-1', true);
-
- expect(removeWorktree).toHaveBeenCalledWith(
- 'agent-1', '/mock/workspace', 'cos/task-abc123',
- expect.objectContaining({ preserveBranchWithCommits: false })
- );
- });
});
const DEAD_BRANCH = 'cos/task-1/agent-x';
@@ -2563,26 +2539,26 @@ describe('cleanupAgentWorktree - remote copy of a locally merged branch', () =>
// In particular, no branch identity is uncertainty even when ok is true.
describe('resolveWorktreeDisposition', () => {
it.each([
- [true, 'always', null, {}, 'open-pr', false, false],
- [false, 'always', null, {}, 'merge-or-preserve', false, true],
- [true, 'never', null, {}, 'merge-or-preserve', true, false],
- [false, 'never', null, {}, 'merge-or-preserve', false, true],
- [true, 'if-missing', { category: 'pr-missing' }, {}, 'open-pr', false, false],
- [true, 'if-missing', { ok: true, branch: 'example' }, {}, 'stand-down', true, false],
- [true, 'if-missing', { ok: true, branch: 'example', branchProvenEmpty: true }, {}, 'stand-down', true, false],
- [true, 'if-missing', { ok: true, branch: null }, {}, 'stand-down-uncertain', true, true],
- [true, 'if-missing', { category: 'forge-unreachable' }, {}, 'stand-down-uncertain', true, true],
- [true, 'if-missing', null, {}, 'stand-down-uncertain', true, true],
- [false, 'if-missing', { status: 'found', url: 'https://github.com/test/repo/pull/1' }, {}, 'stranded-pr-handoff', false, true],
- [false, 'if-missing', { status: 'found' }, {}, 'merge-or-preserve', false, true],
- [false, 'if-missing', { status: 'unavailable' }, {}, 'merge-or-preserve', false, true],
- [false, 'if-missing', { status: 'none' }, {}, 'merge-or-preserve', false, true],
- [true, 'always', null, { discardWorktree: true }, 'discard', false, false],
- [false, 'if-missing', { status: 'found', url: 'https://github.com/test/repo/pull/1' }, { discardWorktree: true }, 'discard', false, false],
- [true, 'always', null, { isWorktree: false, discardWorktree: true }, 'not-a-worktree', false, false],
- [true, 'never', null, { skipMerge: true }, 'merge-or-preserve', false, false],
- ])('success=%s creation=%s verdict=%j overrides=%j → %s', (success, prCreation, prClaimVerdict, overrides, disposition, merge, preserveBranch) => {
+ [true, 'always', null, {}, 'open-pr', false],
+ [false, 'always', null, {}, 'merge-or-preserve', false],
+ [true, 'never', null, {}, 'merge-or-preserve', true],
+ [false, 'never', null, {}, 'merge-or-preserve', false],
+ [true, 'if-missing', { category: 'pr-missing' }, {}, 'open-pr', false],
+ [true, 'if-missing', { ok: true, branch: 'example' }, {}, 'stand-down', true],
+ [true, 'if-missing', { ok: true, branch: 'example', branchProvenEmpty: true }, {}, 'stand-down', true],
+ [true, 'if-missing', { ok: true, branch: null }, {}, 'stand-down-uncertain', true],
+ [true, 'if-missing', { category: 'forge-unreachable' }, {}, 'stand-down-uncertain', true],
+ [true, 'if-missing', null, {}, 'stand-down-uncertain', true],
+ [false, 'if-missing', { status: 'found', url: 'https://github.com/test/repo/pull/1' }, {}, 'stranded-pr-handoff', false],
+ [false, 'if-missing', { status: 'found' }, {}, 'merge-or-preserve', false],
+ [false, 'if-missing', { status: 'unavailable' }, {}, 'merge-or-preserve', false],
+ [false, 'if-missing', { status: 'none' }, {}, 'merge-or-preserve', false],
+ [true, 'always', null, { discardWorktree: true }, 'discard', false],
+ [false, 'if-missing', { status: 'found', url: 'https://github.com/test/repo/pull/1' }, { discardWorktree: true }, 'discard', false],
+ [true, 'always', null, { isWorktree: false, discardWorktree: true }, 'not-a-worktree', false],
+ [true, 'never', null, { skipMerge: true }, 'merge-or-preserve', false],
+ ])('success=%s creation=%s verdict=%j overrides=%j → %s', (success, prCreation, prClaimVerdict, overrides, disposition, merge) => {
expect(resolveWorktreeDisposition({ success, prCreation, prClaimVerdict, ...overrides }))
- .toEqual({ disposition, merge, preserveBranch });
+ .toEqual({ disposition, merge });
});
});
diff --git a/server/services/git.js b/server/services/git.js
index b1f5977e00..6fc635068e 100644
--- a/server/services/git.js
+++ b/server/services/git.js
@@ -3,7 +3,7 @@ import { mkdtemp } from 'fs/promises';
import { tmpdir } from 'os';
import { delimiter, join, resolve } from 'path';
import { safeJSONParse, PATHS, sleep, rmGuarded } from '../lib/fileUtils.js';
-import { isGitLockError, listWorktrees, reapMergedWorktrees } from './worktreeManager.js';
+import { isGitLockError, listWorktrees } from './worktreeManager.js';
import { execGit, execGitSafe } from '../lib/execGit.js';
import { clearStaleGitLock } from '../lib/gitStaleLock.js';
import { resolveForgeForRepo } from './forgeAuth.js';
diff --git a/server/services/worktreeManager.js b/server/services/worktreeManager.js
index c2d2f7c9a4..4bf90fb6a9 100644
--- a/server/services/worktreeManager.js
+++ b/server/services/worktreeManager.js
@@ -1353,8 +1353,6 @@ async function cleanupWorktreeBranch(sourceWorkspace, branchName, {
* @param {string} branchName - The worktree branch to clean up
* @param {object} options
* @param {boolean} [options.merge] - attempt to merge the branch back first
- * @param {boolean} [options.preserveBranchWithCommits] - legacy caller hint;
- * unmerged branches and checkouts are now always retained until merge proof.
* @param {boolean} [options.discardDirt] - remove even when the tree is dirty.
* The dirty-abort exists to protect work that might still be wanted; the
* throwaway-worktree posture has already declared this tree's contents
@@ -1436,7 +1434,7 @@ async function removeWorktreeNow(agentId, sourceWorkspace, branchName, options,
if (finalOwner) return { merged: false, removed: true, uncommittedSaved: false,
warnings: [...warnings, `Branch ${branchName} preserved — ${finalOwner}`] };
await cleanupWorktreeBranch(sourceWorkspace, branchName, {
- preserveBranchWithCommits: options.preserveBranchWithCommits || options.merge, warnings, expectedHead: preservation?.head,
+ warnings, expectedHead: preservation?.head,
});
return { merged: false, removed: true, uncommittedSaved: false, warnings };
}
@@ -1926,47 +1924,30 @@ export async function cleanupOrphanedWorktrees(sourceWorkspace, getActiveIds, {
* `requireAgentId: true`, so a `claim-*` basename is refused as
* `worktree-missing-agent-id` before the claim test is even reached.)
*
- * `includeUnmanagedTrees` drops the managed-root allowlist, so a worktree living
- * anywhere is eligible. It drops the two rules that allowlist carried — the
- * location check, and `WORKTREES_DIR`'s `requireAgentId` — and nothing else: the
- * lock, live-agent, unknown-liveness and human-claim holds all still apply, as do
- * both gates above (so a tree it reaches is still merged + clean before anything
- * is removed). It exists for the user-initiated "clean merged branches" action,
- * where the point IS to clear whatever worktree pins a merged branch; the
- * scheduled sweeps leave it off so an unattended pass never reaches outside the
- * directories PortOS created.
- *
* @param {string} sourceWorkspace - repo root
* @param {object} [options]
* @param {Set<string>|(() => Set<string>)} [options.activeAgentIds] - CoS agents currently running
* (never reaped), or a getter re-read per tree and again before removal. Anything but a
* Set reads as "liveness unknown" and holds every `agent-*` tree.
- * @param {Set<string>} [options.excludeBranches] - branch names never reaped, whatever their tree
* @param {boolean} [options.includeClaudeTrees=true] - also reap `.claude/worktrees/`
- * @param {boolean} [options.includeUnmanagedTrees=false] - consider worktrees outside the managed roots
- * @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,warning?}>, defaultBranch: string, target: string, dryRun: boolean}>}
+ * @param {{agents?: object[]|null, readAgents?: () => Promise<object[]|null>}} [options.claimOwners] -
+ * trusted agent registry reader or snapshot; omitted reads state.json
+ * @returns {Promise<{reaped: Array<{path,branch,locked,branchDeleted}>, skipped: Array<{path,branch,reason,warning?}>, defaultBranch: string, target: string}>}
*/
export async function reapMergedWorktrees(sourceWorkspace, {
activeAgentIds = new Set(),
claimOwners,
- excludeBranches = null,
- includeClaudeTrees = true,
- includeUnmanagedTrees = false,
- defaultBranch: knownDefaultBranch = null,
- dryRun = false
+ includeClaudeTrees = true
} = {}) {
const { getDefaultBranch, hasBranchMergeEvidence } = await import('./git.js');
const { withClaimOwnershipLock, readClaimOwnershipAgents } = await import('./cosClaimOwnershipState.js');
const { readBranchCompletionHold } = await import('./branchCompletionPolicy.js');
- // Every entry point (scheduled, reconcile, operator cleanup) needs a trusted
+ // Every entry point (scheduled or reconcile) needs a trusted
// registry. loadState/getAgents may default a corrupt file to empty state.
const readOwners = claimOwnerReader(claimOwners, readClaimOwnershipAgents);
const readActiveIds = activeIdsReader(activeAgentIds);
- const defaultBranch = knownDefaultBranch || await getDefaultBranch(sourceWorkspace).catch(() => null) || 'main';
+ const defaultBranch = await getDefaultBranch(sourceWorkspace).catch(() => null) || 'main';
const target = await resolveMergeTarget(sourceWorkspace, defaultBranch);
const currentBranch = await execGit(['rev-parse', '--abbrev-ref', 'HEAD'], sourceWorkspace, { ignoreExitCode: true })
@@ -1975,9 +1956,7 @@ export async function reapMergedWorktrees(sourceWorkspace, {
const protectedBranches = new Set(['main', 'master', 'dev', 'develop', 'release', defaultBranch]);
const claudeTreesRoot = join(sourceWorkspace, '.claude', 'worktrees');
- // An empty allowlist is how worktreeOwnershipReason spells "no location check"
- // (see includeUnmanagedTrees above for what that gives up).
- const managedRoots = includeUnmanagedTrees ? [] : [
+ const managedRoots = [
{ path: WORKTREES_DIR, requireAgentId: true },
{ path: claudeTreesRoot, requireAgentId: false },
];
@@ -1995,7 +1974,7 @@ export async function reapMergedWorktrees(sourceWorkspace, {
if (!branchName) { skipped.push({ path: wt.path, reason: 'no-branch' }); continue; }
// Named so a caller can say WHICH branch a hold kept, not just which path.
const hold = (reason) => skipped.push({ path: wt.path, branch: branchName, reason });
- if (protectedBranches.has(branchName) || branchName === currentBranch || excludeBranches?.has(branchName)) {
+ if (protectedBranches.has(branchName) || branchName === currentBranch) {
hold('protected');
continue;
}
@@ -2044,12 +2023,6 @@ export async function reapMergedWorktrees(sourceWorkspace, {
if (!classifyWorktreeDirt(freshStatus).clean) return 'worktree-dirty';
return await hasBranchMergeEvidence(sourceWorkspace, branchName, target).catch(() => false) ? null : 'unmerged';
};
- if (dryRun) {
- const reason = await verifyRemoval(wt);
- if (reason) hold(reason);
- else reaped.push({ path: wt.path, branch: branchName, locked: !!wt.locked, branchDeleted: false });
- return;
- }
const initialHold = await verifyRemoval(wt);
if (initialHold) { hold(initialHold); return; }
const { preserveMergedCheckout } = await import('./heldCheckoutRecovery.js');
@@ -2072,10 +2045,10 @@ export async function reapMergedWorktrees(sourceWorkspace, {
}
if (reaped.length > 0) {
- console.log(`🌳 ${dryRun ? 'Would reap' : 'Reaped'} ${reaped.length} merged worktree(s): ${reaped.map(r => r.branch).join(', ')}`);
+ console.log(`🌳 Reaped ${reaped.length} merged worktree(s): ${reaped.map(r => r.branch).join(', ')}`);
}
- return { reaped, skipped, defaultBranch, target, dryRun };
+ return { reaped, skipped, defaultBranch, target };
}
/**
diff --git a/server/services/worktreeReap.test.js b/server/services/worktreeReap.test.js
index fbce24e7fa..62386100c4 100644
--- a/server/services/worktreeReap.test.js
+++ b/server/services/worktreeReap.test.js
@@ -388,7 +388,7 @@ describe.skipIf(SKIP_HEAVY_INTEGRATION)('read-only inspection of initialized lin
describe.skipIf(SKIP_HEAVY_INTEGRATION)('reapMergedWorktrees', () => {
let dir;
let safePath;
- // One root OUTSIDE the repo for the includeUnmanagedTrees cases, torn down
+ // One root OUTSIDE the repo for the managed-root refusal case, torn down
// alongside the repo so a held tree can't leak out of the run.
let externalRoot;
let initialHead;
@@ -565,19 +565,6 @@ describe.skipIf(SKIP_HEAVY_INTEGRATION)('reapMergedWorktrees', () => {
expect(result.reaped.find(r => r.branch === 'main')).toBeUndefined();
});
- it('does not delete in dryRun mode', async () => {
- const path = await addWorktree(dir, 'dry', 'dry-br');
- await execGit(['merge', '--no-ff', 'dry-br', '--no-edit'], dir);
-
- const result = await reapMergedWorktrees(dir, { includeClaudeTrees: true, dryRun: true });
-
- expect(result.dryRun).toBe(true);
- expect(result.reaped.map(r => r.branch)).toContain('dry-br');
- expect(existsSync(path)).toBe(true);
- const branches = (await execGit(['branch', '--format=%(refname:short)'], dir)).stdout.trim().split('\n');
- expect(branches).toContain('dry-br');
- });
-
// This reaper knows only "merged + clean", which is equally true of a claim a
// human paused ten minutes ago. Reclaiming one turns on idle time AND on
// whether the branch was provably shipped — both computed by branchReconcile,
@@ -601,45 +588,22 @@ describe.skipIf(SKIP_HEAVY_INTEGRATION)('reapMergedWorktrees', () => {
expect(existsSync(agentPath)).toBe(false);
});
- // The user-initiated "clean merged branches" action reaps whatever worktree
- // pins a merged branch, wherever it lives — otherwise the button re-offers the
- // same branch forever. Widening WHERE we look must not widen WHAT we accept,
- // which is why the claim tree below is still held.
- it('reaps an unmanaged-location worktree only when includeUnmanagedTrees is set', async () => {
+ it('preserves a merged worktree outside the managed roots', async () => {
const path = await addExternalWorktree(dir, 'loose', 'loose-br');
await execGit(['merge', '--no-ff', 'loose-br', '--no-edit'], dir);
- const withoutOptIn = await reapMergedWorktrees(dir, { includeClaudeTrees: true });
+ const result = await reapMergedWorktrees(dir, { includeClaudeTrees: true });
// A bare `expected undefined` says the path matched no skip entry but not
// why; this reproduces only on Windows, so the CI log is the sole place to
- // read it. Same style as the sibling assertion below.
+ // read it.
const context = () => [
`wanted path = ${JSON.stringify(path)}`,
- `skipped = ${JSON.stringify(withoutOptIn.skipped)}`,
- `reaped = ${JSON.stringify(withoutOptIn.reaped)}`,
+ `skipped = ${JSON.stringify(result.skipped)}`,
+ `reaped = ${JSON.stringify(result.reaped)}`,
].join('\n');
- expect(withoutOptIn.reaped.map(r => r.branch), context()).not.toContain('loose-br');
- expect(skipReason(withoutOptIn, path), context()).toBe('worktree-unmanaged-location');
+ expect(result.reaped.map(r => r.branch), context()).not.toContain('loose-br');
+ expect(skipReason(result, path), context()).toBe('worktree-unmanaged-location');
expect(existsSync(path)).toBe(true);
-
- const withOptIn = await reapMergedWorktrees(dir, { includeUnmanagedTrees: true });
- expect(
- withOptIn.reaped.map(r => r.branch),
- `nothing reaped; skipped = ${JSON.stringify(withOptIn.skipped)}`,
- ).toContain('loose-br');
- expect(existsSync(path)).toBe(false);
- });
-
- // Dropping the location check must not drop the claim hold with it.
- it('still refuses a human /claim tree under includeUnmanagedTrees', async () => {
- const claimPath = await addExternalWorktree(dir, 'claim-issue-7', 'claim/issue-7');
- await execGit(['merge', '--no-ff', 'claim/issue-7', '--no-edit'], dir);
-
- const result = await reapMergedWorktrees(dir, { includeUnmanagedTrees: true });
-
- expect(result.reaped.map(r => r.branch)).toEqual([]);
- expect(skipReason(result, claimPath)).toBe('worktree-human-claim');
- expect(existsSync(claimPath)).toBe(true);
});
// A registration git already considers prunable used to fail `git status` in a
@@ -662,20 +626,6 @@ describe.skipIf(SKIP_HEAVY_INTEGRATION)('reapMergedWorktrees', () => {
expect(listed).not.toContain('vanished');
});
- it('holds a merged + clean tree whose branch is in excludeBranches', async () => {
- const path = await addWorktree(dir, 'spoken-for', 'spoken-for-br');
- await execGit(['merge', '--no-ff', 'spoken-for-br', '--no-edit'], dir);
-
- const result = await reapMergedWorktrees(dir, {
- includeClaudeTrees: true,
- excludeBranches: new Set(['spoken-for-br'])
- });
-
- expect(result.reaped.map(r => r.branch)).not.toContain('spoken-for-br');
- expect(skipReason(result, path)).toBe('protected');
- expect(existsSync(path)).toBe(true);
- });
-
it('excludes .claude trees when includeClaudeTrees is false', async () => {
const path = await addWorktree(dir, 'excluded', 'excluded-br');
await execGit(['merge', '--no-ff', 'excluded-br', '--no-edit'], dir);