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: retain exact receipts for scheduled and Git cleanup (#13405)

[._.]/ Adam Eivye6051d1b4619
diff --git a/server/services/autonomousJobs.test.js b/server/services/autonomousJobs.test.js
index 368089d3e0..ba0ce542e4 100644
--- a/server/services/autonomousJobs.test.js
+++ b/server/services/autonomousJobs.test.js
@@ -42,6 +42,8 @@ vi.mock('fs', () => ({
existsSync: vi.fn().mockReturnValue(false)
}))
+vi.mock('./retirementAppScope.js', () => ({ resolveRetirementApp: vi.fn(async () => ({ app: { id: 'app-1', repoPath: '/mock/root' } })) }))
+
vi.mock('./worktreeManager.js', () => ({
reapMergedWorktrees: vi.fn().mockResolvedValue({ reaped: [] }),
cleanupOrphanedWorktrees: vi.fn().mockResolvedValue(0)
@@ -1252,6 +1254,13 @@ describe('autonomousJobs', () => {
expect(opts.activeAgentIds().has('live-agent-99')).toBe(true)
})
+ it('does not fall through to orphan cleanup after a failed merged sweep', async () => {
+ reapMergedWorktrees.mockRejectedValueOnce(new Error('synthetic sweep failure'))
+ await expect(agentDataCleanup()).resolves.toMatchObject({ mergedReaped: 0, worktreesReaped: 0,
+ worktreeHolds: [{ reason: 'merged-worktree-reap-failed' }] })
+ expect(cleanupOrphanedWorktrees).not.toHaveBeenCalled()
+ })
+
it('skips every reap when the stored statuses cannot be read (a paused agent could look orphaned)', async () => {
listStoredAgentStatuses.mockRejectedValueOnce(new Error('database unavailable'))
diff --git a/server/services/autonomousJobs/scriptHandlers.js b/server/services/autonomousJobs/scriptHandlers.js
index 9e4ce2ac9f..404b3aa576 100644
--- a/server/services/autonomousJobs/scriptHandlers.js
+++ b/server/services/autonomousJobs/scriptHandlers.js
@@ -184,30 +184,41 @@ async function agentDataCleanup() {
}
}
+ const { resolveRetirementApp } = await import('../retirementAppScope.js')
+ const scope = await resolveRetirementApp(PATHS.root)
+ if (!scope.app) {
+ console.log(`🚫 Agent data cleanup: retaining worktrees (${scope.reason})`)
+ return { cleaned, sentinelsRemoved, mergedReaped: 0, worktreesReaped: 0, removalFailures: 0, worktreeHold: scope.reason }
+ }
+
// First pass — SAFE reap: remove any worktree (CoS or `.claude/worktrees/`) whose
// branch is fully merged into the default branch AND whose working tree is clean.
// This is the bulk of the cleanup and cannot lose work (merged+clean ⇒ nothing
// pending). It guards active agents and human `claim-*` worktrees.
- const merged = await reapMergedWorktrees(PATHS.root, { activeAgentIds: getLiveProtectedIds }).catch((err) => {
+ const merged = await reapMergedWorktrees(scope.app.repoPath, { activeAgentIds: getLiveProtectedIds, appId: scope.app.id }).catch((err) => {
console.warn(`⚠️ Merged-worktree reap failed: ${err.message}`)
- return { reaped: [] }
+ return null
})
// Second pass — orphan integration: for inactive CoS worktrees that were NOT
// merged (e.g. an agent died after committing but before its PR landed), attempt
// to merge their commits back so the work isn't stranded. The helper guards
// `claim-*` worktrees, so this can't touch a human's in-flight claim.
- const worktreesReaped = await cleanupOrphanedWorktrees(PATHS.root, getLiveProtectedIds).catch((err) => {
+ // A failed preservation/receipt must not fall through to the older orphan
+ // remover. Only unmerged candidates belong to that second pass.
+ const retainedPaths = new Set((merged?.skipped || []).filter(row => row.reason !== 'unmerged').map(row => row.path))
+ const worktreesReaped = merged ? await cleanupOrphanedWorktrees(PATHS.root, getLiveProtectedIds, { retainedPaths }).catch((err) => {
console.warn(`⚠️ Orphaned worktree cleanup failed: ${err.message}`)
return 0
- })
+ }) : 0
const mergedCount = merged?.reaped?.length || 0
// 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
+ const worktreeHolds = merged?.skipped || [{ reason: 'merged-worktree-reap-failed' }]
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 }
+ return { cleaned, sentinelsRemoved, mergedReaped: mergedCount, worktreesReaped, removalFailures, worktreeHolds }
}
/**
diff --git a/server/services/branchReconcile.ownership.test.js b/server/services/branchReconcile.ownership.test.js
index e2f2788a77..12cb53d6eb 100644
--- a/server/services/branchReconcile.ownership.test.js
+++ b/server/services/branchReconcile.ownership.test.js
@@ -26,7 +26,7 @@ vi.mock('../lib/paths.js', async importOriginal => makePathsProxy(await importOr
}));
afterAll(cleanupTempDataRoots);
-const injected = vi.hoisted(() => ({ statusPath: null, statusThrows: false, beforeRemove: null, owners: [], policies: [], forge: {}, gitSpawns: [] }));
+const injected = vi.hoisted(() => ({ statusPath: null, statusThrows: false, beforeRemove: null, owners: [], policies: [], app: null, schedule: { tasks: {}, executions: {} }, forge: {}, gitSpawns: [] }));
vi.mock('../lib/execGit.js', async (importOriginal) => {
const actual = await importOriginal();
return { ...actual, execGit: async (args, cwd, options) => {
@@ -45,6 +45,11 @@ vi.mock('../lib/execGit.js', async (importOriginal) => {
return actual.execGit(args, cwd, options);
} };
});
+vi.mock('./apps.js', () => ({ getAllApps: async () => [injected.app], getAppById: async id => injected.app?.id === id ? injected.app : null }));
+vi.mock('./taskScheduleStore.js', async importOriginal => ({
+ ...await importOriginal(), loadSchedule: async () => injected.schedule,
+ updateSchedule: async mutate => (await mutate(injected.schedule)).result,
+}));
vi.mock('./cosState.js', () => ({
readAgentsStateForSafetyCheck: async () => ({ trusted: injected.owners !== null,
agents: injected.owners && Object.fromEntries(injected.owners.map(agent => [agent.id, agent])) }),
@@ -89,12 +94,13 @@ describe.skipIf(SKIP_HEAVY_INTEGRATION)('branch-reconcile worktree ownership (re
let external;
beforeEach(async () => {
- Object.assign(injected, { statusPath: null, statusThrows: false, beforeRemove: null, owners: [], policies: [], forge: {}, gitSpawns: [] });
+ Object.assign(injected, { statusPath: null, statusThrows: false, beforeRemove: null, owners: [], policies: [], app: null, schedule: { tasks: {}, executions: {} }, forge: {}, gitSpawns: [] });
scratch = realpathSync(await mkdtemp(join(tmpdir(), 'portos-reconcile-own-')));
const safeRepo = join(scratch, 'repo');
await mkdir(safeRepo);
await materializeGitRepo(safeRepo, { identity: { email: '[email protected]', name: 'Test' } });
repo = (await execGit(['rev-parse', '--show-toplevel'], safeRepo)).stdout.trim() || safeRepo;
+ injected.app = { id: 'app-1', repoPath: repo };
external = join(scratch, 'elsewhere');
await mkdir(external);
});
diff --git a/server/services/git.deleteMergedBranches.test.js b/server/services/git.deleteMergedBranches.test.js
index bd0f2ed163..0114b7d148 100644
--- a/server/services/git.deleteMergedBranches.test.js
+++ b/server/services/git.deleteMergedBranches.test.js
@@ -6,6 +6,7 @@ vi.mock('../lib/execGit.js', () => {
return { execGit, execGitSafe: (...args) => execGit(...args).catch(error => ({ exitCode: 1, stdout: '', stderr: error.message })) };
});
vi.mock('./worktreeManager.js', () => ({ isGitLockError: vi.fn(), listWorktrees: vi.fn(async () => []) }));
+vi.mock('./retirementAppScope.js', () => ({ resolveRetirementApp: vi.fn(async () => ({ app: { id: 'app-1', repoPath: '/repo', forgeAccount: 'example-account' } })) }));
vi.mock('./branchReconcile.js', () => ({ cleanupMerged: vi.fn() }));
vi.mock('./cosClaimOwnershipState.js', () => ({ withClaimOwnershipLock: work => work(), readClaimOwnershipAgents: vi.fn(async () => []) }));
vi.mock('./branchCompletionPolicy.js', () => ({ readBranchCompletionHold: vi.fn(async () => null) }));
@@ -45,7 +46,7 @@ describe('delete merged branches', () => {
it('shares local retirement and leases the merged remote head', async () => {
const result = await deleteMergedBranches('/repo');
expect(result.deleted).toEqual([{ name: 'feature/done', local: 'deleted', remote: 'deleted' }]);
- expect(cleanupMerged).toHaveBeenCalledWith('/repo', HEAD, [{ branch: 'feature/done' }], { activeAgentIds: null });
+ expect(cleanupMerged).toHaveBeenCalledWith('/repo', HEAD, [{ branch: 'feature/done' }], { activeAgentIds: null, appId: 'app-1', forgeAccount: 'example-account' });
expect(execGit).toHaveBeenCalledWith(['push', `--force-with-lease=refs/heads/feature/done:${HEAD}`, '--', REMOTE, ':refs/heads/feature/done'], '/repo', { ignoreExitCode: true });
expect(readBranchCompletionHold).toHaveBeenCalledWith({ repoPath: '/repo', branch: 'feature/done', tip: HEAD, retirement: true });
});
diff --git a/server/services/git.js b/server/services/git.js
index 8f642c7780..0a27560fe2 100644
--- a/server/services/git.js
+++ b/server/services/git.js
@@ -2130,6 +2130,9 @@ export async function deleteMergedBranches(dir, { excludeBranches, activeAgentId
const records = new Map();
const context = await prepareRemoteRetirement(dir, defaultBranch);
if (context.reason) return { deleted: [], skipped: [`cleanup (${context.reason})`], defaultBranch };
+ const { resolveRetirementApp } = await import('./retirementAppScope.js');
+ const scope = await resolveRetirementApp(dir);
+ if (!scope.app) return { deleted: [], skipped: [`cleanup (${scope.reason})`], defaultBranch };
const { targetSha } = context;
const branches = await execGitSafe(['branch', '--format=%(refname:short)'], dir, { ignoreExitCode: true });
if (branches.exitCode !== 0) return { deleted: [], skipped: ['cleanup (local branches unavailable)'], defaultBranch };
@@ -2145,7 +2148,9 @@ export async function deleteMergedBranches(dir, { excludeBranches, activeAgentId
const record = { name, local: null, remote: null };
records.set(name, record);
if (local.has(name)) {
- const retired = await cleanupMerged(dir, targetSha, [{ branch: name }], { activeAgentIds });
+ const retired = await cleanupMerged(scope.app.repoPath, targetSha, [{ branch: name }], {
+ activeAgentIds, appId: scope.app.id, forgeAccount: scope.app.forgeAccount ?? null,
+ });
if (retired.cleaned.includes(name)) record.local = 'deleted';
else {
for (const hold of retired.skipped) skipped.push(`${name} (local: ${worktreeHoldReason(hold.reason)}${hold.detail ? `: ${hold.detail}` : ''})`);
diff --git a/server/services/retirementAppScope.js b/server/services/retirementAppScope.js
new file mode 100644
index 0000000000..f9e6e81197
--- /dev/null
+++ b/server/services/retirementAppScope.js
@@ -0,0 +1,20 @@
+import { stat } from 'fs/promises';
+
+/** A repository path grants no app identity; retirement needs one exact registry match. */
+export async function resolveRetirementApp(repoPath) {
+ const { getAllApps } = await import('./apps.js');
+ const apps = await getAllApps().catch(() => null);
+ if (!Array.isArray(apps)) return { reason: 'retirement-app-registry-unavailable' };
+ const root = await stat(repoPath, { bigint: true }).catch(() => null);
+ if (!root?.isDirectory() || root.ino === 0n) return { reason: 'retirement-repository-unavailable' };
+ const matches = [];
+ for (const app of apps) {
+ if (typeof app?.repoPath !== 'string' || !app.repoPath) continue;
+ const info = await stat(app.repoPath, { bigint: true }).catch(() => null);
+ // Compare physical directories, including symlink and Windows short-name aliases.
+ if (info?.isDirectory() && info.dev === root.dev && info.ino === root.ino) matches.push(app);
+ }
+ if (matches.length > 1) return { reason: 'retirement-app-ambiguous' };
+ if (!matches[0]?.id) return { reason: 'retirement-app-unavailable' };
+ return { app: matches[0] };
+}
diff --git a/server/services/retirementAppScope.test.js b/server/services/retirementAppScope.test.js
new file mode 100644
index 0000000000..6ee24182d9
--- /dev/null
+++ b/server/services/retirementAppScope.test.js
@@ -0,0 +1,139 @@
+/** Exact retirement receipts at the Git UI and daily cleanup boundaries (#13405). */
+import { describe, it, expect, beforeEach, afterEach, afterAll, vi } from 'vitest';
+import { mkdtemp, mkdir, rm, readFile } from 'fs/promises';
+import { existsSync, realpathSync } from 'fs';
+import { tmpdir } from 'os';
+import { basename, dirname, join } from 'path';
+import { execGit } from '../lib/execGit.js';
+import { readRetirementCheckoutIdentity } from '../lib/retirementCheckoutObservation.js';
+import { materializeGitRepo, SKIP_HEAVY_INTEGRATION } from '../lib/gitTestRepo.js';
+import { cleanupTempDataRoots, lazyTempDataRoot, makePathsProxy } from '../lib/mockPathsDataRoot.js';
+import { PATHS } from '../lib/paths.js';
+
+const injected = vi.hoisted(() => ({ app: null, apps: null, schedule: null, scheduleWrites: 0, failScheduleWrite: null }));
+vi.mock('../lib/paths.js', async importOriginal => makePathsProxy(await importOriginal(), {
+ dataRoot: () => realpathSync.native(lazyTempDataRoot('portos-cleanup-receipts-')),
+ extraOverrides: () => ({ root: injected.app?.repoPath || lazyTempDataRoot('portos-cleanup-receipts-') }),
+}));
+afterAll(cleanupTempDataRoots);
+vi.mock('./apps.js', () => ({
+ getAllApps: async () => { if (injected.apps instanceof Error) throw injected.apps; return injected.apps ?? (injected.app ? [injected.app] : []); },
+ getAppById: async id => injected.app?.id === id ? injected.app : null,
+}));
+vi.mock('./cosState.js', () => ({ readAgentsStateForSafetyCheck: async () => ({ trusted: true, agents: {} }) }));
+vi.mock('./cosAgentRepository.js', () => ({ listStoredAgentStatuses: async () => [] }));
+vi.mock('./autobiography.js', () => ({ checkAndPrompt: vi.fn() }));
+vi.mock('./goalCheckIn.js', () => ({ runGoalCheckIn: vi.fn() }));
+vi.mock('./branchCompletionPolicy.js', () => ({ readBranchCompletionHold: async () => null }));
+vi.mock('./taskScheduleStore.js', async importOriginal => ({
+ ...await importOriginal(), loadSchedule: async () => injected.schedule,
+ updateSchedule: async mutate => {
+ if (++injected.scheduleWrites === injected.failScheduleWrite) throw new Error('synthetic receipt persistence failure');
+ return (await mutate(injected.schedule)).result;
+ },
+}));
+const { recordBranchReconcileOutcome, getBranchReconcileOutcome } = await import('./taskSchedule.js');
+
+describe.skipIf(SKIP_HEAVY_INTEGRATION)('outside reconciliation retirement receipts (real git)', () => {
+ let scratch;
+ let repo;
+ beforeEach(async () => {
+ Object.assign(injected, { app: null, apps: null, schedule: { tasks: {}, executions: {} }, scheduleWrites: 0, failScheduleWrite: null });
+ scratch = realpathSync.native(await mkdtemp(join(tmpdir(), 'portos-cleanup-repo-')));
+ await mkdir(join(scratch, 'repo'));
+ await materializeGitRepo(join(scratch, 'repo'), { identity: { email: '[email protected]', name: 'Test' } });
+ repo = (await execGit(['rev-parse', '--show-toplevel'], join(scratch, 'repo'))).stdout.trim();
+ injected.app = { id: 'app-1', repoPath: repo };
+ });
+ afterEach(async () => {
+ await rm(scratch, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
+ });
+ const registered = async path => (await execGit(['worktree', 'list', '--porcelain'], repo)).stdout
+ .split(/\r?\n/).includes(`worktree ${path.replaceAll('\\', '/')}`);
+
+ it.each(['Git UI', 'daily cleanup'])('persists exact %s retirement before the next inventory scan', async entryPoint => {
+ const { release, unrelated, run } = await outsideCleanupFixture(entryPoint);
+ const result = await run();
+ if (entryPoint === 'Git UI') expect(result).toMatchObject({ deleted: [{ name: release.branch, local: 'deleted' }], skipped: [] });
+ else expect(result).toMatchObject({ mergedReaped: 1, worktreesReaped: 0 });
+ expect(existsSync(release.path)).toBe(false);
+ expect((await execGit(['rev-parse', '--verify', '--quiet', `refs/heads/${release.branch}`], repo, { ignoreExitCode: true })).exitCode).toBe(1);
+ const first = await getBranchReconcileOutcome('app-1');
+ expect(first.retired).toEqual([expect.objectContaining({ branch: release.branch, path: release.path, head: release.head,
+ checkoutIdentity: release.checkoutIdentity, branchDeleted: true, archiveDir: expect.any(String) })]);
+ const manifest = JSON.parse(await readFile(join(first.retired[0].archiveDir, 'manifest.json'), 'utf8'));
+ expect(manifest).toMatchObject({ repoPath: repo, branch: release.branch });
+ const next = await recordBranchReconcileOutcome('app-1', { status: 'complete', remaining: [] });
+ expect(next.retired).toEqual(first.retired);
+ expect(next.retirementObligations).toEqual([expect.objectContaining({ branch: unrelated.branch })]);
+ });
+
+ async function outsideCleanupFixture(entryPoint) {
+ const branch = 'feature/outside-cleanup';
+ const path = join(PATHS.worktrees, `agent-${basename(scratch)}`);
+ await mkdir(dirname(path), { recursive: true });
+ await execGit(['worktree', 'add', '-b', branch, path, 'main'], repo);
+ const holder = (await (await import('./worktreeManager.js')).listWorktrees(repo)).find(tree => tree.branch === `refs/heads/${branch}`);
+ const release = { branch, path: holder.path, head: holder.head, locked: false, lockReason: null,
+ checkoutIdentity: await readRetirementCheckoutIdentity(path) };
+ const unrelated = { branch: 'feature/unexplained', head: holder.head, reason: 'branch-held' };
+ await recordBranchReconcileOutcome('app-1', { status: 'incomplete', remaining: [{ ...release, reason: 'checkout-retained' }, unrelated] });
+ if (entryPoint === 'Git UI') {
+ const remote = join(scratch, 'origin.git');
+ await execGit(['init', '--bare', remote], scratch);
+ await execGit(['symbolic-ref', 'HEAD', 'refs/heads/main'], remote);
+ await execGit(['remote', 'add', 'origin', remote], repo);
+ await execGit(['push', 'origin', 'main'], repo);
+ }
+ const run = () => entryPoint === 'Git UI'
+ ? import('./git.js').then(m => m.deleteMergedBranches(repo, { activeAgentIds: new Set() }))
+ : import('./autonomousJobs/scriptHandlers.js').then(m => m.agentDataCleanup());
+ return { release, unrelated, run };
+ }
+
+ it.each(['Git UI', 'daily cleanup'])('retains originals when %s cannot persist preservation, including the orphan fallback', async entryPoint => {
+ const { release, run } = await outsideCleanupFixture(entryPoint);
+ injected.failScheduleWrite = injected.scheduleWrites + 3;
+ const result = await run();
+ expect(entryPoint === 'Git UI' ? result.deleted : result.mergedReaped).toEqual(entryPoint === 'Git UI' ? [] : 0);
+ if (entryPoint === 'daily cleanup') expect(result.worktreesReaped).toBe(0);
+ expect(existsSync(release.path)).toBe(true);
+ expect(await registered(release.path)).toBe(true);
+ expect((await execGit(['rev-parse', release.branch], repo)).stdout.trim()).toBe(release.head);
+ const outcome = await getBranchReconcileOutcome('app-1');
+ expect(outcome.retired || []).toEqual([]);
+ expect(outcome.retirementObligations, JSON.stringify(result)).toContainEqual(expect.objectContaining({ path: release.path, head: release.head }));
+ });
+
+ it.each(['Git UI', 'daily cleanup'])('keeps failed %s completion and a recreated checkout separate from its old archive', async entryPoint => {
+ const { release, unrelated, run } = await outsideCleanupFixture(entryPoint);
+ injected.failScheduleWrite = injected.scheduleWrites + 4;
+ await run();
+ expect(existsSync(release.path)).toBe(false);
+ const failed = await getBranchReconcileOutcome('app-1');
+ expect(failed.retired || []).toEqual([]);
+ const obligation = failed.retirementObligations.find(row => row.path === release.path);
+ expect(obligation.preservationReceipt.archiveDir).toBeTruthy();
+ await execGit(['worktree', 'add', '-b', release.branch, release.path, release.head], repo);
+ const recreated = { ...release, checkoutIdentity: await readRetirementCheckoutIdentity(release.path), reason: 'checkout-retained' };
+ expect(recreated.checkoutIdentity).not.toBe(release.checkoutIdentity);
+ await recordBranchReconcileOutcome('app-1', { status: 'incomplete', remaining: [recreated, unrelated] });
+ const next = await recordBranchReconcileOutcome('app-1', { status: 'complete', remaining: [] });
+ expect(next.retired || []).toEqual([]);
+ expect(next.retirementObligations).toContainEqual(expect.objectContaining({ path: recreated.path, head: recreated.head }));
+ expect(next.retirementObligations).toContainEqual(expect.objectContaining({ branch: unrelated.branch }));
+ expect(existsSync(release.path)).toBe(true);
+ });
+
+ it.each(['missing', 'ambiguous', 'unreadable'])('retains both cleanup entry points with %s app scope', async mode => {
+ const { release, run } = await outsideCleanupFixture('Git UI');
+ injected.apps = mode === 'missing' ? [] : mode === 'ambiguous' ? [injected.app, { ...injected.app, id: 'app-2' }] : new Error('synthetic registry unavailable');
+ const reason = mode === 'missing' ? 'retirement-app-unavailable' : mode === 'ambiguous' ? 'retirement-app-ambiguous' : 'retirement-app-registry-unavailable';
+ expect(await run()).toMatchObject({ deleted: [], skipped: [`cleanup (${reason})`] });
+ expect(await (await import('./autonomousJobs/scriptHandlers.js')).agentDataCleanup()).toMatchObject({ mergedReaped: 0, worktreesReaped: 0, worktreeHold: reason });
+ expect(existsSync(release.path)).toBe(true);
+ expect((await execGit(['rev-parse', release.branch], repo)).stdout.trim()).toBe(release.head);
+ expect((await getBranchReconcileOutcome('app-1')).retired || []).toEqual([]);
+ });
+
+});
diff --git a/server/services/worktreeManager.js b/server/services/worktreeManager.js
index 50fb8cfda8..0afeecc2ac 100644
--- a/server/services/worktreeManager.js
+++ b/server/services/worktreeManager.js
@@ -2060,8 +2060,9 @@ function activeIdsReader(activeIds) {
* @param {object} [options]
* @param {{agents?: object[]|null, readAgents?: () => Promise<object[]|null>}} [options.claimOwners] -
* agent registry override (tests); omitted reads state.json
+ * @param {Set<string>} [options.retainedPaths] - registered paths held by an earlier cleanup pass
*/
-export async function cleanupOrphanedWorktrees(sourceWorkspace, getActiveIds, { claimOwners } = {}) {
+export async function cleanupOrphanedWorktrees(sourceWorkspace, getActiveIds, { claimOwners, retainedPaths = new Set() } = {}) {
if (!existsSync(WORKTREES_DIR)) return 0;
const readActiveIds = activeIdsReader(getActiveIds);
@@ -2086,6 +2087,7 @@ export async function cleanupOrphanedWorktrees(sourceWorkspace, getActiveIds, {
if (initialReason === 'worktree-unmanaged-location') continue;
const agentId = worktreeAgentId(wt.path);
handledAgentIds.add(agentId);
+ if (retainedPaths.has(wt.path)) continue;
if (initialReason) continue;
// A detached HEAD has no branch to merge or measure; force-removing it would drop commits only its reflog holds.
if (wt.detached || !wt.branch) continue;