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: preserve external worktree recovery during orphan cleanup (#9907)

Adam Eivy2eab09845b33
diff --git a/server/services/git.js b/server/services/git.js
index de7b968038..8d57d64361 100644
--- a/server/services/git.js
+++ b/server/services/git.js
@@ -1382,7 +1382,7 @@ export async function hasBranchMergeEvidence(dir, branch, target) {
// Rebase/cherry-pick path: does target contain every branch commit as an
// individual patch-equivalent commit?
const individualCherry = await execGit(['cherry', targetSha, branchSha], dir, { ignoreExitCode: true })
- .then(r => r.stdout.trim())
+ .then(r => r.exitCode === 0 ? r.stdout.trim() : null)
.catch(() => null);
if (individualCherry === null) return false;
if (individualCherry !== '' && individualCherry.split('\n').every(line => line.startsWith('-'))) {
@@ -1411,7 +1411,7 @@ export async function hasBranchMergeEvidence(dir, branch, target) {
if (!synthesized) return false;
const combinedCherry = await execGit(['cherry', targetSha, synthesized], dir, { ignoreExitCode: true })
- .then(r => r.stdout.trim())
+ .then(r => r.exitCode === 0 ? r.stdout.trim() : null)
.catch(() => null);
if (combinedCherry === null) return false;
if (combinedCherry === '') return true; // empty patch (tree already matches) ⇒ merged
diff --git a/server/services/worktreeExternalCleanup.test.js b/server/services/worktreeExternalCleanup.test.js
new file mode 100644
index 0000000000..f21486fad2
--- /dev/null
+++ b/server/services/worktreeExternalCleanup.test.js
@@ -0,0 +1,143 @@
+/** Real separate-repository fixtures for the public scheduled cleanup consumer. */
+import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
+import { existsSync, realpathSync } from 'fs';
+import { mkdir, readFile, rm, writeFile } from 'fs/promises';
+import { join, relative } from 'path';
+import { cleanupTempDataRoots, lazyTempDataRoot, makePathsProxy } from '../lib/mockPathsDataRoot.js';
+import { materializeGitRepo, resetGitWorktreeSandbox, SKIP_HEAVY_INTEGRATION } from '../lib/gitTestRepo.js';
+import { PATHS } from '../lib/fileUtils.js';
+import { execGit } from '../lib/execGit.js';
+import { cleanupOrphanedWorktrees } from './worktreeManager.js';
+
+vi.mock('../lib/fileUtils.js', async (importOriginal) => makePathsProxy(await importOriginal(), {
+ dataRoot: () => lazyTempDataRoot('portos-external-cleanup-'),
+}));
+const fault = vi.hoisted(() => ({ command: null, cwd: null, successfulMatches: 0, calls: [] }));
+vi.mock('../lib/execGit.js', async (importOriginal) => {
+ const actual = await importOriginal();
+ return { ...actual, execGit: async (args, cwd, options) => {
+ fault.calls.push({ args, cwd });
+ if (args[0] === fault.command && (!fault.cwd || cwd === fault.cwd)) {
+ if (fault.successfulMatches > 0) {
+ fault.successfulMatches--;
+ return actual.execGit(args, cwd, options);
+ }
+ if (options?.ignoreExitCode) return { stdout: '', stderr: 'fixture read failure', exitCode: 1 };
+ throw new Error('fixture read failure');
+ }
+ return actual.execGit(args, cwd, options);
+ } };
+});
+
+const root = () => realpathSync(lazyTempDataRoot('portos-external-cleanup-'));
+let primary;
+let external;
+let initialHead;
+async function addTree(name, { committed = false, detached = false } = {}) {
+ const path = join(PATHS.worktrees, name);
+ await execGit(['worktree', 'add', ...(detached ? ['--detach'] : ['-b', name]), path, 'main'], external);
+ if (committed) {
+ await writeFile(join(path, 'recovery.txt'), `recover ${name}\n`);
+ await execGit(['add', '.'], path);
+ await execGit(['commit', '-m', 'fixture recovery work'], path);
+ }
+ return path;
+}
+async function branchExists(branch) {
+ return (await execGit(['show-ref', '--verify', `refs/heads/${branch}`], external, { ignoreExitCode: true })).exitCode === 0;
+}
+
+describe.skipIf(SKIP_HEAVY_INTEGRATION)('external orphan cleanup recovery policy', () => {
+ beforeAll(async () => {
+ primary = join(root(), 'primary');
+ external = join(root(), 'managed-app');
+ await materializeGitRepo(primary);
+ await materializeGitRepo(external);
+ await mkdir(PATHS.worktrees, { recursive: true });
+ initialHead = (await execGit(['rev-parse', 'HEAD'], external)).stdout.trim();
+ });
+ beforeEach(async () => {
+ fault.command = null;
+ fault.cwd = null;
+ fault.successfulMatches = 0;
+ await resetGitWorktreeSandbox(external, initialHead);
+ await rm(PATHS.worktrees, { recursive: true, force: true });
+ await mkdir(PATHS.worktrees, { recursive: true });
+ fault.calls = [];
+ });
+ afterAll(cleanupTempDataRoots);
+
+ it('retains dirty, unmerged, locked, detached, active, human and non-agent work while reclaiming merged clean work', async () => {
+ const dirty = await addTree('agent-dirty');
+ await writeFile(join(dirty, 'private-recovery.txt'), 'dirty recovery\n');
+ const unmerged = await addTree('agent-unmerged', { committed: true });
+ const locked = await addTree('agent-locked');
+ await writeFile(join(locked, 'private-recovery.txt'), 'locked recovery\n');
+ await execGit(['worktree', 'lock', locked], external);
+ const detached = await addTree('agent-detached', { detached: true });
+ const active = await addTree('agent-active');
+ const human = await addTree('claim-issue-42');
+ const nonAgent = await addTree('other-work');
+ const merged = await addTree('agent-merged', { committed: true });
+ await execGit(['merge', '--no-ff', 'agent-merged', '--no-edit'], external);
+
+ expect(await cleanupOrphanedWorktrees(primary, new Set(['agent-active']))).toBe(1);
+ for (const path of [dirty, unmerged, locked, detached, active, human, nonAgent]) expect(existsSync(path)).toBe(true);
+ expect(await readFile(join(dirty, 'private-recovery.txt'), 'utf8')).toBe('dirty recovery\n');
+ expect(await readFile(join(locked, 'private-recovery.txt'), 'utf8')).toBe('locked recovery\n');
+ expect(await branchExists('agent-unmerged')).toBe(true);
+ expect(existsSync(merged)).toBe(false);
+ expect(await branchExists('agent-merged')).toBe(false);
+ });
+
+ it('resolves a relative .git pointer through Git rather than assuming an absolute parent path', async () => {
+ const path = await addTree('agent-relative');
+ const pointer = (await readFile(join(path, '.git'), 'utf8')).replace(/^gitdir: /, '').trim();
+ await writeFile(join(path, '.git'), `gitdir: ${relative(realpathSync(path), pointer)}\n`);
+ expect(await cleanupOrphanedWorktrees(primary, new Set())).toBe(1);
+ expect(existsSync(path)).toBe(false);
+ });
+
+ it('retains recovery files when the parent repository disappears or the git pointer is unreadable', async () => {
+ const missing = await addTree('agent-missing-parent');
+ const unreadable = await addTree('agent-unreadable');
+ await writeFile(join(unreadable, '.git'), 'unreadable registration\n');
+ await rm(external, { recursive: true, force: true });
+ expect(await cleanupOrphanedWorktrees(primary, new Set())).toBe(0);
+ expect(existsSync(missing)).toBe(true);
+ expect(existsSync(unreadable)).toBe(true);
+ });
+
+ it.each(['status', 'rev-parse', 'worktree'])('preserves recovery when the %s read fails', async command => {
+ const path = await addTree('agent-read-failure');
+ fault.command = command;
+ fault.cwd = path;
+ expect(await cleanupOrphanedWorktrees(primary, new Set())).toBe(0);
+ expect(existsSync(path)).toBe(true);
+ expect(await branchExists('agent-read-failure')).toBe(true);
+ });
+
+ it.each([0, 1])('does not treat failed cherry probe %s with empty stdout as merge evidence', async successfulMatches => {
+ const path = await addTree('agent-cherry-failure', { committed: true });
+ fault.command = 'cherry';
+ fault.successfulMatches = successfulMatches;
+ expect(await cleanupOrphanedWorktrees(primary, new Set())).toBe(0);
+ expect(existsSync(path)).toBe(true);
+ expect(await branchExists('agent-cherry-failure')).toBe(true);
+ });
+
+ it('never bypasses a Git removal refusal with recursive deletion or branch removal', async () => {
+ const path = await addTree('agent-remove-refused');
+ fault.command = 'worktree';
+ fault.cwd = external;
+ expect(await cleanupOrphanedWorktrees(primary, new Set())).toBe(0);
+ expect(existsSync(path)).toBe(true);
+ expect(fault.calls.some(({ args }) => args[0] === 'branch' && args[1] === '-D')).toBe(false);
+ });
+
+ it('holds all external agent work when liveness cannot be established', async () => {
+ const path = await addTree('agent-unknown-liveness');
+ expect(await cleanupOrphanedWorktrees(primary, null)).toBe(0);
+ expect(existsSync(path)).toBe(true);
+ });
+});
diff --git a/server/services/worktreeManager.js b/server/services/worktreeManager.js
index b02bbc60de..36e3c7b191 100644
--- a/server/services/worktreeManager.js
+++ b/server/services/worktreeManager.js
@@ -1506,57 +1506,58 @@ export async function reapMergedWorktrees(sourceWorkspace, {
* worktrees directory. They're invisible to PortOS's `git worktree list`.
*/
async function cleanupExternalRepoWorktrees(activeAgentIds, alreadyHandled) {
+ const { getDefaultBranch, hasBranchMergeEvidence } = await import('./git.js');
const entries = await readdir(WORKTREES_DIR, { withFileTypes: true }).catch(() => []);
let cleaned = 0;
for (const entry of entries) {
- if (!entry.isDirectory()) continue;
- const agentId = entry.name;
- if (alreadyHandled.has(agentId) || activeAgentIds.has(agentId)) continue;
- // Human-driven `/claim` worktrees are not CoS agents — never reap them.
- if (isHumanClaimWorktree(agentId)) continue;
-
- const worktreePath = join(WORKTREES_DIR, agentId);
- const gitFile = join(worktreePath, '.git');
-
- // Read .git file to find the parent repo
- // In a worktree, .git is a file containing "gitdir: ..."; in a normal repo it's a directory
- const gitStat = await stat(gitFile).catch(() => null);
- if (gitStat?.isDirectory()) {
- // This is a normal git repo, not a worktree — skip to avoid accidental data loss
- continue;
- }
- const gitContent = gitStat ? await tryReadFile(gitFile) : null;
- if (!gitContent?.startsWith('gitdir:')) {
- // No .git file or unreadable — skip rather than removing potentially valuable data
- console.log(`🌳 Skipping worktree directory ${agentId} — cannot determine parent repo`);
- continue;
- }
-
- // Extract the parent repo from the gitdir path (e.g., /path/to/repo/.git/worktrees/agent-xxx)
- const gitdir = gitContent.replace('gitdir:', '').trim();
- const parentRepoGitDir = gitdir.replace(/\/worktrees\/[^/]+$/, '');
- const parentRepo = parentRepoGitDir.replace(/\/\.git$/, '');
-
- if (!existsSync(parentRepo)) {
- // Parent repo no longer exists — just remove directory
- console.log(`🌳 Removing orphaned external worktree ${agentId} (parent repo gone: ${parentRepo})`);
- await rm(worktreePath, { recursive: true, force: true }).catch(() => {});
- cleaned++;
- continue;
- }
-
- // Clean via the parent repo's git
- console.log(`🌳 Cleaning external worktree ${agentId} from ${parentRepo}`);
- const branchName = await execGit(['rev-parse', '--abbrev-ref', 'HEAD'], worktreePath)
- .then(r => r.stdout.trim())
- .catch(() => '');
-
- await forceRemoveWorktreeDir(parentRepo, worktreePath);
+ if (!entry.isDirectory() || alreadyHandled.has(entry.name)) continue;
+ const worktreePath = join(WORKTREES_DIR, entry.name);
+ const ownership = {
+ path: worktreePath,
+ activeAgentIds,
+ roots: [{ path: WORKTREES_DIR, requireAgentId: true }],
+ requireKnownLiveness: true,
+ };
+ if (worktreeOwnershipReason(ownership)) continue;
+
+ // Ask Git for its common directory and actual registration, rather than
+ // inferring a parent from the spelling of a .git file. Relative pointers,
+ // separate git directories and Windows separators are all valid.
+ const commonDir = await execGit(['rev-parse', '--git-common-dir'], worktreePath)
+ .then(r => r.stdout.trim() ? resolve(worktreePath, r.stdout.trim()) : null).catch(() => null);
+ if (!commonDir) continue;
+ const registrations = await listWorktrees(worktreePath).catch(() => []);
+ const wt = registrations.find(candidate => pathsEqual(candidate.path, worktreePath));
+ const primary = registrations[0];
+ if (!wt || wt.bare || wt.detached || wt.prunable || !wt.branch) continue;
+ if (!primary || primary.bare || pathsEqual(primary.path, worktreePath)) continue;
+ if (worktreeOwnershipReason({ ...ownership, locked: wt.locked })) continue;
+
+ const parentRepo = primary.path;
+ const parentCommonDir = await execGit(['rev-parse', '--git-common-dir'], parentRepo)
+ .then(r => r.stdout.trim() ? resolve(parentRepo, r.stdout.trim()) : null).catch(() => null);
+ if (!parentCommonDir || !pathsEqual(commonDir, parentCommonDir)) continue;
- if (branchName) {
- await execGit(['branch', '-D', branchName], parentRepo).catch(() => {});
- }
+ const branchName = wt.branch.replace(/^refs\/heads\//, '');
+ const defaultBranch = await getDefaultBranch(parentRepo, { strict: true }).catch(() => null);
+ if (!defaultBranch || ['main', 'master', 'dev', 'develop', 'release', defaultBranch].includes(branchName)) continue;
+ const status = await execGit(['status', '--porcelain'], worktreePath).then(r => r.stdout).catch(() => null);
+ if (status === null || !classifyWorktreeDirt(status).clean) continue;
+ const target = await resolveMergeTarget(parentRepo, defaultBranch);
+ const merged = await hasBranchMergeEvidence(parentRepo, branchName, target).catch(() => false);
+ if (!merged) continue;
+
+ // Non-force removal is a final Git guard against newly dirty or locked
+ // trees. A refusal must never fall through to recursive filesystem removal.
+ const removed = await execGit(['worktree', 'remove', worktreePath], parentRepo).then(() => true).catch(err => {
+ console.warn(`⚠️ Preserved external worktree ${entry.name}: ${err.message}`);
+ return false;
+ });
+ if (!removed) continue;
+ await execGit(['branch', '-D', branchName], parentRepo).catch(err => {
+ console.warn(`⚠️ External branch cleanup failed for ${branchName}: ${err.message}`);
+ });
cleaned++;
}