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(cos): harden worktree lifecycle to prevent orphans and lost work

Adam Eivy4e553b8a78f9
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 9774735365..d5ff9945bc 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -57,5 +57,10 @@
- readOnly tasks skip unnecessary git pull, JIRA branch creation, and worktree setup
- Flaky test suite stabilized by increasing vitest timeout from 5s to 10s (parallel execution pressure caused intermittent timeouts)
- Added `PORTOS_API_URL` constant to `ports.js` for dynamic API URL resolution in task prompts
+- Worktree merge failures now abort cleanly (`merge --abort`) instead of leaving the repo in MERGING state
+- Failed merges now preserve the branch for manual recovery instead of force-deleting it and orphaning commits
+- Orphaned worktree cleanup now attempts to merge committed work before removing (prevents losing PR/push failure preserved work)
+- External-repo worktrees (managed app agents) now cleaned up properly — previously invisible to `git worktree list` and accumulated on disk
+- Stash pop after rebase abort now handles conflicts consistently (checkout + drop) instead of leaving stale stashes
## Removed
diff --git a/server/services/git.js b/server/services/git.js
index 7608abaa9a..cf5c8a3a5e 100644
--- a/server/services/git.js
+++ b/server/services/git.js
@@ -583,6 +583,20 @@ export function hasChangelogDir(dir) {
* @param {string} dir - Git repository directory
* @returns {{ success: boolean, branch: string, stashed: boolean, conflict: boolean, error: string|null }}
*/
+/**
+ * Pop stash and clean up if the pop produces merge conflicts.
+ * Returns { conflict: boolean, stderr: string }
+ */
+async function popStashSafely(dir) {
+ const result = await execGit(['stash', 'pop'], dir, { ignoreExitCode: true });
+ if (result.stderr?.includes('CONFLICT')) {
+ await execGit(['checkout', '--', '.'], dir, { ignoreExitCode: true });
+ await execGit(['stash', 'drop'], dir, { ignoreExitCode: true });
+ return { conflict: true, stderr: result.stderr };
+ }
+ return { conflict: false, stderr: '' };
+}
+
export async function ensureLatest(dir) {
const gitCheck = await isRepo(dir).catch(() => false);
if (!gitCheck) return { success: true, branch: null, stashed: false, conflict: false, error: null, skipped: 'not-a-repo' };
@@ -628,13 +642,9 @@ export async function ensureLatest(dir) {
if (mergeOk) {
// Fast-forward succeeded
if (stashed) {
- const popResult = await execGit(['stash', 'pop'], dir, { ignoreExitCode: true });
- const popOk = !popResult.stderr?.includes('CONFLICT');
- if (!popOk) {
- // Stash pop conflict — abort and report
- await execGit(['checkout', '--', '.'], dir, { ignoreExitCode: true });
- await execGit(['stash', 'drop'], dir, { ignoreExitCode: true });
- return { success: false, branch: currentBranch, stashed: true, conflict: true, error: `stash pop conflict after fast-forward: ${popResult.stderr}` };
+ const { conflict, stderr } = await popStashSafely(dir);
+ if (conflict) {
+ return { success: false, branch: currentBranch, stashed: true, conflict: true, error: `stash pop conflict after fast-forward: ${stderr}` };
}
}
return { success: true, branch: currentBranch, stashed, conflict: false, error: null };
@@ -648,7 +658,7 @@ export async function ensureLatest(dir) {
// Rebase failed — abort and report conflict
await execGit(['rebase', '--abort'], dir, { ignoreExitCode: true });
if (stashed) {
- await execGit(['stash', 'pop'], dir, { ignoreExitCode: true });
+ await popStashSafely(dir);
}
return {
success: false,
@@ -661,11 +671,9 @@ export async function ensureLatest(dir) {
// Rebase succeeded
if (stashed) {
- const popResult = await execGit(['stash', 'pop'], dir, { ignoreExitCode: true });
- if (popResult.stderr?.includes('CONFLICT')) {
- await execGit(['checkout', '--', '.'], dir, { ignoreExitCode: true });
- await execGit(['stash', 'drop'], dir, { ignoreExitCode: true });
- return { success: false, branch: currentBranch, stashed: true, conflict: true, error: `stash pop conflict after rebase: ${popResult.stderr}` };
+ const { conflict, stderr } = await popStashSafely(dir);
+ if (conflict) {
+ return { success: false, branch: currentBranch, stashed: true, conflict: true, error: `stash pop conflict after rebase: ${stderr}` };
}
}
diff --git a/server/services/worktreeManager.js b/server/services/worktreeManager.js
index 176511f6d5..7be2ebce88 100644
--- a/server/services/worktreeManager.js
+++ b/server/services/worktreeManager.js
@@ -11,7 +11,7 @@
import { spawn } from 'child_process';
import { existsSync } from 'fs';
-import { rm } from 'fs/promises';
+import { readdir, readFile, rm } from 'fs/promises';
import { join } from 'path';
import { ensureDir, PATHS } from '../lib/fileUtils.js';
@@ -147,8 +147,10 @@ export async function removeWorktree(agentId, sourceWorkspace, branchName, optio
// Merge worktree branch back to the source branch
await execGit(['merge', branchName, '--no-edit'], sourceWorkspace)
.then(() => { merged = true; })
- .catch(err => {
+ .catch(async (err) => {
console.log(`⚠️ Could not auto-merge ${branchName}: ${err.message}`);
+ // Abort the failed merge to leave sourceWorkspace in a clean state
+ await execGit(['merge', '--abort'], sourceWorkspace).catch(() => {});
});
}
}
@@ -165,11 +167,17 @@ export async function removeWorktree(agentId, sourceWorkspace, branchName, optio
});
});
- // Delete the branch if we merged or if it was never used
- await execGit(['branch', '-D', branchName], sourceWorkspace)
- .catch(err => {
- console.log(`⚠️ Branch delete failed for ${branchName}: ${err.message}`);
- });
+ // Only delete the branch if merge succeeded or wasn't requested.
+ // When merge was requested but failed, preserve the branch so commits can be recovered.
+ const shouldDeleteBranch = merged || !options.merge;
+ if (shouldDeleteBranch) {
+ await execGit(['branch', '-D', branchName], sourceWorkspace)
+ .catch(err => {
+ console.log(`⚠️ Branch delete failed for ${branchName}: ${err.message}`);
+ });
+ } else {
+ console.log(`⚠️ Preserving branch ${branchName} — merge failed, commits need manual recovery`);
+ }
console.log(`🌳 Removed worktree for ${agentId}${merged ? ' (merged)' : ''}`);
@@ -303,15 +311,20 @@ export async function cleanupOrphanedWorktrees(sourceWorkspace, activeAgentIds)
const worktrees = await listWorktrees(sourceWorkspace).catch(() => []);
let cleaned = 0;
+ // Track which agent dirs we handle via git worktree list (PortOS-owned worktrees)
+ const handledAgentIds = new Set();
+
for (const wt of worktrees) {
// Only clean up worktrees under our managed directory
if (!wt.path.startsWith(WORKTREES_DIR)) continue;
- // Extract agent ID from the worktree path
const agentId = wt.path.split('/').pop();
+ handledAgentIds.add(agentId);
if (!activeAgentIds.has(agentId)) {
const branchName = wt.branch?.replace('refs/heads/', '') || '';
- await removeWorktree(agentId, sourceWorkspace, branchName, { merge: false })
+ // Attempt merge so committed work from preserved worktrees (e.g., PR/push failures) isn't lost.
+ // If merge fails, the branch is preserved for manual recovery.
+ await removeWorktree(agentId, sourceWorkspace, branchName, { merge: true })
.catch(err => {
console.log(`⚠️ Failed to clean orphaned worktree ${agentId}: ${err.message}`);
});
@@ -319,9 +332,74 @@ export async function cleanupOrphanedWorktrees(sourceWorkspace, activeAgentIds)
}
}
+ // Scan for external-repo worktrees (directories whose .git points to a different repo).
+ // These are invisible to `git worktree list` run against PortOS.
+ cleaned += await cleanupExternalRepoWorktrees(activeAgentIds, handledAgentIds);
+
if (cleaned > 0) {
console.log(`🌳 Cleaned ${cleaned} orphaned worktree(s)`);
}
return cleaned;
}
+
+/**
+ * Clean up worktree directories that belong to external repos (managed apps).
+ * These are created when agents work on apps outside PortOS but use the shared
+ * worktrees directory. They're invisible to PortOS's `git worktree list`.
+ */
+async function cleanupExternalRepoWorktrees(activeAgentIds, alreadyHandled) {
+ 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;
+
+ const worktreePath = join(WORKTREES_DIR, agentId);
+ const gitFile = join(worktreePath, '.git');
+
+ // Read .git file to find the parent repo
+ const gitContent = await readFile(gitFile, 'utf-8').catch(() => null);
+ if (!gitContent?.startsWith('gitdir:')) {
+ // Not a valid worktree — just remove the directory
+ console.log(`🌳 Removing invalid worktree directory ${agentId}`);
+ await rm(worktreePath, { recursive: true, force: true }).catch(() => {});
+ cleaned++;
+ 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(b => b.trim())
+ .catch(() => '');
+
+ await execGit(['worktree', 'remove', worktreePath, '--force'], parentRepo)
+ .catch(async () => {
+ await rm(worktreePath, { recursive: true, force: true }).catch(() => {});
+ await execGit(['worktree', 'prune'], parentRepo).catch(() => {});
+ });
+
+ if (branchName) {
+ await execGit(['branch', '-D', branchName], parentRepo).catch(() => {});
+ }
+ cleaned++;
+ }
+
+ return cleaned;
+}