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

clean up merged worktrees along with merged branches

[._.]/ Adam Eivy265d42aa7834
diff --git a/client/src/components/apps/tabs/GitTab.jsx b/client/src/components/apps/tabs/GitTab.jsx
index ae0d398784..1354bc5bce 100644
--- a/client/src/components/apps/tabs/GitTab.jsx
+++ b/client/src/components/apps/tabs/GitTab.jsx
@@ -403,13 +403,15 @@ export default function GitTab({ appId, appName, repoPath }) {
const mergedBranchCount = remoteBranches.filter(rb => rb.merged && !rb.isDefault).length;
// Keep the action visible for every merged local branch so a worktree-held
- // branch does not make the cleanup affordance disappear. The server still
- // protects branches in use; the disclosure beside the button explains why
- // some branches may remain after cleanup.
+ // branch does not make the cleanup affordance disappear. Cleanup now tears the
+ // worktree down too, so a merged branch sitting in one is an ordinary target
+ // rather than a permanent leftover — a worktree survives only when it still
+ // holds uncommitted or unmerged work, or something (a running agent, a claim,
+ // a lock) is still using it. The server names which, per branch, in `skipped`.
const localMergedCount = branches.filter(b => b.merged).length;
const localWorktreeMergedCount = branches.filter(b => b.merged && b.worktree).length;
const localCleanupTitle = localWorktreeMergedCount > 0
- ? `Cleans merged branches when safe; ${localWorktreeMergedCount} merged branch${localWorktreeMergedCount === 1 ? '' : 'es'} checked out in a worktree will be preserved`
+ ? `Deletes merged branches locally and on the remote, removing the ${localWorktreeMergedCount} worktree${localWorktreeMergedCount === 1 ? '' : 's'} holding one — unless it still has uncommitted or unmerged work, or is in use`
: 'Deletes merged branches both locally and on the remote';
const handleCleanupMerged = async () => {
@@ -425,22 +427,35 @@ export default function GitTab({ appId, appName, repoPath }) {
const deleted = Array.isArray(result.deleted) ? result.deleted : [];
const skipped = Array.isArray(result.skipped) ? result.skipped : [];
const count = deleted.length;
+ const removedWorktrees = deleted.filter(d => d.worktree === 'removed').length;
+ // Each entry already reads "<branch> (local: <why it survived>)" — the
+ // answer to "why is this branch still here?", which a bare count isn't.
+ const preserved = `${skipped.slice(0, 2).join('; ')}${skipped.length > 2 ? ` (+${skipped.length - 2} more)` : ''}`;
if (count === 0) {
toast(
- skipped.length > 0
- ? `No branches deleted — ${skipped.length} merged branch${skipped.length === 1 ? '' : 'es'} preserved`
- : 'No merged branches to clean up',
+ skipped.length > 0 ? `No branches deleted — preserved ${preserved}` : 'No merged branches to clean up',
{ icon: skipped.length > 0 ? '⚠️' : 'ℹ️' }
);
} else {
- toast.success(`Cleaned up ${count} merged branch${count === 1 ? '' : 'es'}`);
- const deletedLocals = new Set(deleted.filter(d => d.local === 'deleted').map(d => d.name));
+ const worktreeSuffix = removedWorktrees > 0
+ ? ` and ${removedWorktrees} worktree${removedWorktrees === 1 ? '' : 's'}`
+ : '';
+ toast.success(`Cleaned up ${count} merged branch${count === 1 ? '' : 'es'}${worktreeSuffix}`);
const deletedRemotes = new Set(deleted.filter(d => d.remote === 'deleted').map(d => d.name));
- setBranches(prev => prev.filter(b => !deletedLocals.has(b.name)));
setRemoteBranches(prev => prev.filter(b => !deletedRemotes.has(b.name)));
+ // A reap also clears the `worktree` flag on whatever survived, so re-read
+ // the branches instead of filtering the stale list. Only the branch list
+ // can have changed — no need for the full loadGitInfo fan-out.
+ if (removedWorktrees > 0) {
+ const refreshed = await api.getBranches(repoPath).catch(() => null);
+ if (refreshed) setBranches(refreshed.branches || []);
+ } else {
+ const deletedLocals = new Set(deleted.filter(d => d.local === 'deleted').map(d => d.name));
+ setBranches(prev => prev.filter(b => !deletedLocals.has(b.name)));
+ }
}
if (count > 0 && skipped.length > 0) {
- toast(`${skipped.length} branch${skipped.length === 1 ? '' : 'es'} preserved`, { icon: '⚠️' });
+ toast(`Preserved ${preserved}`, { icon: '⚠️' });
}
}
};
@@ -716,7 +731,7 @@ export default function GitTab({ appId, appName, repoPath }) {
)}
{localWorktreeMergedCount > 0 && !cleanupConfirm && (
<span className="text-xs text-gray-500" role="status">
- {localWorktreeMergedCount} merged branch{localWorktreeMergedCount === 1 ? '' : 'es'} in a worktree will be preserved
+ {localWorktreeMergedCount} worktree{localWorktreeMergedCount === 1 ? '' : 's'} removed too, except any still in use or holding uncommitted work
</span>
)}
{cleanupConfirm === 'local' && (
@@ -730,7 +745,7 @@ export default function GitTab({ appId, appName, repoPath }) {
{cleaningUp
? 'Deleting...'
: localWorktreeMergedCount > 0
- ? 'Delete eligible merged (local + remote)'
+ ? 'Delete all merged (local + remote + worktrees)'
: 'Delete all merged (local + remote)'}
</button>
<button
diff --git a/client/src/components/apps/tabs/GitTab.test.jsx b/client/src/components/apps/tabs/GitTab.test.jsx
index 32a83d4078..d512980815 100644
--- a/client/src/components/apps/tabs/GitTab.test.jsx
+++ b/client/src/components/apps/tabs/GitTab.test.jsx
@@ -165,8 +165,8 @@ describe('GitTab merged-branch cleanup scoping', () => {
describe('GitTab merged branches checked out in worktrees', () => {
beforeEach(() => {
- // Both merged branches are checked out in worktrees, so the cleanup action
- // remains visible while disclosing that the server will preserve them.
+ // Both merged branches are checked out in worktrees, which cleanup now tears
+ // down as well — the disclosure names the one condition that preserves one.
api.getBranches.mockResolvedValue({
branches: [
{ name: 'main', current: true, tracking: 'origin/main', ahead: 0, behind: 0, isDefault: true, merged: false, worktree: false },
@@ -183,19 +183,32 @@ describe('GitTab merged branches checked out in worktrees', () => {
// The merged branches still render (with their badges) so the user can see them.
expect(await screen.findByText('claim/issue-1')).toBeInTheDocument();
const localCleanBtn = screen.getByRole('button', { name: 'Clean 2 merged' });
- expect(localCleanBtn).toHaveAttribute('title', 'Cleans merged branches when safe; 2 merged branches checked out in a worktree will be preserved');
- expect(screen.getByRole('status')).toHaveTextContent('2 merged branches in a worktree will be preserved');
+ expect(localCleanBtn).toHaveAttribute(
+ 'title',
+ 'Deletes merged branches locally and on the remote, removing the 2 worktrees holding one — unless it still has uncommitted or unmerged work, or is in use'
+ );
+ expect(screen.getByRole('status')).toHaveTextContent('2 worktrees removed too, except any still in use or holding uncommitted work');
});
- it('uses an eligible-only confirmation when merged branches are held in worktrees', async () => {
+ it('confirms that worktrees go with the branches', async () => {
render(<GitTab appId="x" appName="App" repoPath="/repo" />);
fireEvent.click(await screen.findByRole('button', { name: 'Clean 2 merged' }));
- expect(await screen.findByRole('button', { name: 'Delete eligible merged (local + remote)' })).toHaveAttribute(
- 'title',
- 'Cleans merged branches when safe; 2 merged branches checked out in a worktree will be preserved'
- );
+ expect(await screen.findByRole('button', { name: 'Delete all merged (local + remote + worktrees)' })).toBeInTheDocument();
+ });
+
+ it('re-reads the branches after a cleanup that removed a worktree, so stale worktree badges clear', async () => {
+ api.cleanupMergedBranches.mockResolvedValue({
+ deleted: [{ name: 'claim/issue-1', local: 'deleted', remote: null, worktree: 'removed' }],
+ skipped: []
+ });
+ render(<GitTab appId="x" appName="App" repoPath="/repo" />);
+
+ fireEvent.click(await screen.findByRole('button', { name: 'Clean 2 merged' }));
+ fireEvent.click(await screen.findByRole('button', { name: 'Delete all merged (local + remote + worktrees)' }));
+
+ await waitFor(() => expect(api.getBranches.mock.calls.length).toBeGreaterThan(1));
});
it('labels worktree-checked-out branches with a worktree badge', async () => {
diff --git a/server/routes/git.js b/server/routes/git.js
index a712ddabb5..0474dbfdb9 100644
--- a/server/routes/git.js
+++ b/server/routes/git.js
@@ -4,6 +4,7 @@ import { resolve } from 'path';
import * as git from '../services/git.js';
import * as appsService from '../services/apps.js';
import { getAgents } from '../services/cosAgentLifecycle.js';
+import { protectedAgentIds } from '../services/agentState.js';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
import { isWithinAllowedRoots, outsideAllowedRootsMessage } from '../lib/workspaceRoots.js';
import { validateRequest, submoduleStatusQuerySchema, submoduleUpdateSchema } from '../lib/validation.js';
@@ -41,14 +42,26 @@ function assertAllowedWorkspace(path) {
* Collect branch names actively used by running CoS agents.
* Includes worktree branches and workspace branches from agent metadata.
*/
-async function getActiveAgentBranches() {
- const agents = await getAgents().catch(() => []);
+/**
+ * What a branch/worktree cleanup must leave alone, from ONE read of the agent
+ * list so the two sets can't be built from different snapshots:
+ * - `excludeBranches` — the branch each running agent is working on.
+ * - `activeAgentIds` — every agent whose worktree is in use (`protectedAgentIds`).
+ *
+ * An unreadable agent list yields `activeAgentIds: null`, which the worktree
+ * reaper reads as "liveness unknown" and fails closed on — the alternative,
+ * an empty Set, would pass for "nothing is running" and take a live agent's
+ * directory out from under it.
+ * @returns {Promise<{excludeBranches: Set<string>, activeAgentIds: Set<string>|null}>}
+ */
+async function getAgentProtections() {
+ const agents = await getAgents().catch(() => null);
const branches = new Set();
- for (const agent of agents) {
+ for (const agent of agents || []) {
if (agent.status !== 'running') continue;
if (agent.metadata?.worktreeBranch) branches.add(agent.metadata.worktreeBranch);
}
- return branches;
+ return { excludeBranches: branches, activeAgentIds: agents ? protectedAgentIds(agents) : null };
}
const router = Router();
@@ -260,12 +273,15 @@ router.post('/reset-to-default', asyncHandler(async (req, res) => {
res.json(result);
}));
-// POST /api/git/cleanup-merged - Delete all merged branches (local + remote)
+// POST /api/git/cleanup-merged - Delete all merged branches (local + remote),
+// including the worktrees pinning them. The service reaps a worktree only when
+// it is clean and its branch is fully in origin/<default>; anything else comes
+// back in `skipped` with the reason.
router.post('/cleanup-merged', asyncHandler(async (req, res) => {
const { path } = req.body;
assertAllowedWorkspace(path);
- const excludeBranches = await getActiveAgentBranches();
- const result = await git.deleteMergedBranches(path, { excludeBranches });
+ const { excludeBranches, activeAgentIds } = await getAgentProtections();
+ const result = await git.deleteMergedBranches(path, { excludeBranches, activeAgentIds });
res.json(result);
}));
@@ -279,7 +295,7 @@ router.post('/delete-branch', asyncHandler(async (req, res) => {
if (!local && !remote) {
throw new ServerError('at least one of local or remote must be true', { status: 400, code: 'VALIDATION_ERROR' });
}
- const excludeBranches = await getActiveAgentBranches();
+ const { excludeBranches } = await getAgentProtections();
const result = await git.deleteBranch(path, branch, { local, remote, excludeBranches });
res.json(result);
}));
diff --git a/server/routes/git.test.js b/server/routes/git.test.js
index 37cd80c80f..e4ad6062b1 100644
--- a/server/routes/git.test.js
+++ b/server/routes/git.test.js
@@ -219,8 +219,31 @@ describe('git routes — active agent branch exclusion', () => {
// Should not 500 — getAgents failure is swallowed via .catch(() => [])
expect(res.status).toBe(200);
- const { excludeBranches } = gitService.deleteMergedBranches.mock.calls[0][1];
+ const { excludeBranches, activeAgentIds } = gitService.deleteMergedBranches.mock.calls[0][1];
expect(excludeBranches.size).toBe(0);
+ // Cleanup now tears worktrees down, so an unreadable agent list must NOT
+ // read as "nothing is running" — null makes the reaper hold every agent tree.
+ expect(activeAgentIds).toBeNull();
+ });
+
+ it('protects running AND paused agent worktrees via activeAgentIds', async () => {
+ cosAgentLifecycleService.getAgents.mockResolvedValue([
+ { id: 'agent-running', status: 'running', metadata: { worktreeBranch: 'feature/agent-work' } },
+ { id: 'agent-paused', status: 'paused' },
+ { id: 'agent-done', status: 'completed' },
+ ]);
+ gitService.deleteMergedBranches.mockResolvedValue({ deleted: [] });
+
+ const app = makeApp();
+ await request(app)
+ .post('/api/git/cleanup-merged')
+ .send({ path: WORKSPACE });
+
+ const { activeAgentIds } = gitService.deleteMergedBranches.mock.calls[0][1];
+ expect(activeAgentIds.has('agent-running')).toBe(true);
+ // A paused agent keeps its worktree as resume context.
+ expect(activeAgentIds.has('agent-paused')).toBe(true);
+ expect(activeAgentIds.has('agent-done')).toBe(false);
});
});
diff --git a/server/services/agentState.js b/server/services/agentState.js
index 75173c68d8..03f2952010 100644
--- a/server/services/agentState.js
+++ b/server/services/agentState.js
@@ -121,6 +121,32 @@ export const setUseRunner = (val) => { useRunner = val; };
// `subAgentSpawner` re-exports it for backward compatibility.
export const getActiveAgentIds = () => [...activeAgents.keys(), ...runnerAgents.keys()];
+/**
+ * Agent ids whose worktree must not be taken out from under them, from an
+ * already-read agent list:
+ *
+ * - the in-process maps, which are authoritative for THIS process;
+ * - every persisted `running` agent, which is how a run that survived a server
+ * restart (the maps are empty then) still counts;
+ * - every persisted `paused` agent — pausing deliberately preserves the tree as
+ * resume context, and a paused agent is absent from the maps.
+ *
+ * Under-counting here removes a directory another run is mid-edit in, so the one
+ * definition lives here rather than being restated by each reaper. Takes the
+ * list instead of fetching it, both to stay off `cos.js`'s import path and so a
+ * caller that already read the agents does not read them twice.
+ *
+ * @param {Array<{id?: string, status?: string}>} [agents]
+ * @returns {Set<string>}
+ */
+export const protectedAgentIds = (agents = []) => {
+ const ids = new Set(getActiveAgentIds());
+ for (const agent of agents) {
+ if (agent?.status === 'running' || agent?.status === 'paused') ids.add(agent.id);
+ }
+ return ids;
+};
+
// Does THIS process already own the agent's lifecycle?
//
// Ownership is split across the two maps by spawn mode, and which map an agent
diff --git a/server/services/agentWorkspacePrep.js b/server/services/agentWorkspacePrep.js
index 86fb62bb5b..9ab7ecd430 100644
--- a/server/services/agentWorkspacePrep.js
+++ b/server/services/agentWorkspacePrep.js
@@ -30,7 +30,7 @@ import { execGit } from '../lib/execGit.js';
import { emitLog } from './cosEvents.js';
import { updateTask, addTask } from './cos.js';
import { getAppById } from './apps.js';
-import { isTruthyMeta, isFalsyMeta, getActiveAgentIds } from './agentState.js';
+import { isTruthyMeta, isFalsyMeta, protectedAgentIds } from './agentState.js';
import { PATHS, ensureDir } from '../lib/fileUtils.js';
import * as git from './git.js';
import { detectConflicts } from './taskConflict.js';
@@ -81,25 +81,10 @@ const WORKTREE_BUSY_MAX_ATTEMPTS = 5;
// service before the shared task-target-branch contract existed.
export { resolveTaskTargetBranch as resolveTaskExistingBranch } from '../lib/taskTargetBranch.js';
-/**
- * Agent ids whose worktree must not be taken out from under them, using the same
- * definition the daily worktree reap protects on (`autonomousJobs/scriptHandlers.js`):
- *
- * - the in-process maps, which are authoritative for THIS process;
- * - every persisted `running` agent, which is how a run that survived a server
- * restart (the maps are empty then) still counts;
- * - every persisted `paused` agent — pausing deliberately preserves the tree as
- * resume context, and a paused agent is absent from the maps.
- *
- * Under-counting here would move a directory another run is mid-edit in.
- */
+/** `protectedAgentIds` over a freshly-read agent list — see agentState.js. */
async function getProtectedAgentIds() {
const { getAgents } = await import('./cos.js');
- const ids = new Set(getActiveAgentIds());
- for (const agent of await getAgents()) {
- if (agent?.status === 'running' || agent?.status === 'paused') ids.add(agent.id);
- }
- return ids;
+ return protectedAgentIds(await getAgents());
}
/**
diff --git a/server/services/git.deleteMergedBranches.test.js b/server/services/git.deleteMergedBranches.test.js
index 431c5013c6..9139d40904 100644
--- a/server/services/git.deleteMergedBranches.test.js
+++ b/server/services/git.deleteMergedBranches.test.js
@@ -6,17 +6,19 @@ vi.mock('../lib/execGit.js', () => ({
vi.mock('./worktreeManager.js', () => ({
isGitLockError: vi.fn(),
- listWorktrees: vi.fn().mockResolvedValue([])
+ listWorktrees: vi.fn().mockResolvedValue([]),
+ reapMergedWorktrees: vi.fn()
}));
import { execGit } from '../lib/execGit.js';
-import { listWorktrees } from './worktreeManager.js';
+import { listWorktrees, reapMergedWorktrees } from './worktreeManager.js';
import { deleteMergedBranches } from './git.js';
const result = (stdout = '', exitCode = 0, stderr = '') => ({ stdout, stderr, exitCode });
beforeEach(() => {
listWorktrees.mockResolvedValue([{ branch: 'refs/heads/feature/locked' }]);
+ reapMergedWorktrees.mockResolvedValue({ reaped: [], skipped: [], defaultBranch: 'main' });
execGit.mockImplementation((args) => {
if (args[0] === 'symbolic-ref') return Promise.resolve(result('origin/main\n'));
if (args[0] === 'rev-parse' && args.includes('--verify')) return Promise.resolve(result('abc123\n'));
@@ -37,12 +39,94 @@ afterEach(() => {
});
describe('deleteMergedBranches', () => {
- it('reports merged branches held by worktrees while deleting eligible locals', async () => {
+ it('reports merged branches the reaper refused, while deleting eligible locals', async () => {
+ reapMergedWorktrees.mockResolvedValue({
+ reaped: [],
+ skipped: [{ path: '/wt/locked', branch: 'feature/locked', reason: 'uncommitted' }]
+ });
+
const cleanup = await deleteMergedBranches('/repo');
expect(cleanup.deleted).toEqual([{ name: 'feature/free', local: 'deleted', remote: null }]);
- expect(cleanup.skipped).toEqual(['feature/locked (local: checked out in a worktree)']);
+ // The reaper's reason is what tells the user why the branch survived — the
+ // generic "it's in a worktree" wording is now only the unknown-reason fallback.
+ expect(cleanup.skipped).toEqual(['feature/locked (local: worktree has uncommitted changes)']);
expect(execGit).toHaveBeenCalledWith(['branch', '-d', 'feature/free'], '/repo', { ignoreExitCode: true });
expect(execGit).not.toHaveBeenCalledWith(['branch', '-d', 'feature/locked'], '/repo', { ignoreExitCode: true });
});
+
+ it('reports a worktree-held branch generically when the reaper named no reason', async () => {
+ const cleanup = await deleteMergedBranches('/repo');
+
+ expect(cleanup.skipped).toEqual(['feature/locked (local: checked out in a worktree)']);
+ });
+
+ it('counts a reaped worktree branch as deleted and folds its remote half into one row', async () => {
+ reapMergedWorktrees.mockResolvedValue({
+ reaped: [{ path: '/wt/reaped', branch: 'feature/reaped', locked: false, branchDeleted: true }],
+ skipped: []
+ });
+ execGit.mockImplementation((args) => {
+ if (args[0] === 'symbolic-ref') return Promise.resolve(result('origin/main\n'));
+ if (args[0] === 'rev-parse' && args.includes('--verify')) return Promise.resolve(result('abc123\n'));
+ if (args[0] === 'rev-parse' && args.includes('--abbrev-ref')) return Promise.resolve(result('main\n'));
+ if (args[0] === 'branch' && args.includes('--list')) return Promise.resolve(result(' main\n'));
+ if (args[0] === 'branch' && args.includes('-r') && args.includes('--merged')) {
+ return Promise.resolve(result('origin/main\norigin/feature/reaped\n'));
+ }
+ if (args[0] === 'branch' && args.includes('--merged')) return Promise.resolve(result('main\n'));
+ return Promise.resolve(result());
+ });
+
+ const cleanup = await deleteMergedBranches('/repo');
+
+ expect(cleanup.deleted).toEqual([
+ { name: 'feature/reaped', local: 'deleted', remote: 'deleted', worktree: 'removed' }
+ ]);
+ // The reap already deleted the local branch — re-running `branch -d` would
+ // only produce a spurious "not found" skip.
+ expect(execGit).not.toHaveBeenCalledWith(['branch', '-d', 'feature/reaped'], '/repo', { ignoreExitCode: true });
+ expect(execGit).toHaveBeenCalledWith(['push', 'origin', '--delete', 'feature/reaped'], '/repo', { ignoreExitCode: true });
+ });
+
+ it('hands the reaper the protected branches, agent ids and default branch, and skips its own fetch', async () => {
+ const excludeBranches = new Set(['feature/agent-work']);
+ const activeAgentIds = new Set(['agent-1']);
+
+ await deleteMergedBranches('/repo', { excludeBranches, activeAgentIds });
+
+ expect(reapMergedWorktrees).toHaveBeenCalledWith('/repo', {
+ activeAgentIds,
+ excludeBranches,
+ includeUnmanagedTrees: true,
+ // Passed so the reap skips its own lookup, which can stall on `remote set-head`.
+ defaultBranch: 'main'
+ });
+ // reapMergedWorktrees fetches --prune itself; a second round-trip is waste.
+ expect(execGit).not.toHaveBeenCalledWith(['fetch', 'origin', '--prune'], '/repo', { ignoreExitCode: true });
+ });
+
+ it('retries the branch delete when the reap removed the tree but not the branch', async () => {
+ reapMergedWorktrees.mockResolvedValue({
+ reaped: [{ path: '/wt/locked', branch: 'feature/locked', locked: false, branchDeleted: false }],
+ skipped: []
+ });
+
+ const cleanup = await deleteMergedBranches('/repo');
+
+ // The worktree hold is gone with the tree, so the branch is an ordinary
+ // target again rather than being reported as still checked out.
+ expect(execGit).toHaveBeenCalledWith(['branch', '-d', 'feature/locked'], '/repo', { ignoreExitCode: true });
+ expect(cleanup.deleted).toContainEqual({ name: 'feature/locked', local: 'deleted', remote: null });
+ expect(cleanup.skipped).toEqual([]);
+ });
+
+ it('falls back to branch-only cleanup when the reap throws', async () => {
+ reapMergedWorktrees.mockRejectedValue(new Error('worktree list failed'));
+
+ const cleanup = await deleteMergedBranches('/repo');
+
+ expect(cleanup.deleted).toEqual([{ name: 'feature/free', local: 'deleted', remote: null }]);
+ expect(execGit).toHaveBeenCalledWith(['fetch', 'origin', '--prune'], '/repo', { ignoreExitCode: true });
+ });
});
diff --git a/server/services/git.js b/server/services/git.js
index b2429cd70a..efe0af874d 100644
--- a/server/services/git.js
+++ b/server/services/git.js
@@ -2,7 +2,7 @@ import { spawn } from '../lib/childProcess.js';
import { existsSync } from 'fs';
import { join, resolve } from 'path';
import { safeJSONParse, PATHS, sleep } from '../lib/fileUtils.js';
-import { isGitLockError, listWorktrees } from './worktreeManager.js';
+import { isGitLockError, listWorktrees, reapMergedWorktrees } from './worktreeManager.js';
import { execGit } from '../lib/execGit.js';
import {
parseStatus,
@@ -1384,16 +1384,43 @@ export async function resetToDefaultBranch(dir) {
};
}
+// Prose for each `reapMergedWorktrees` skip slug, so `skipped` says WHY a merged
+// branch survived rather than only that it did. An unlisted slug falls back to
+// the plain "it's in a worktree" phrasing.
+const WORKTREE_HOLD_REASONS = {
+ uncommitted: 'worktree has uncommitted changes',
+ unmerged: 'worktree has unmerged commits',
+ 'status-failed': 'worktree status could not be read',
+ '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'
+};
+const worktreeHoldReason = (reason) => WORKTREE_HOLD_REASONS[reason] || 'checked out in a worktree';
+
/**
* Delete all merged branches (local and remote) in one operation.
* Skips the `PROTECTED_BRANCHES` set (see `../lib/gitArgs.js`), the current branch,
- * branches checked out in worktrees, and any explicitly excluded branches.
+ * and any explicitly excluded branches.
+ *
+ * A merged branch checked out in a WORKTREE is no longer reported-and-left: the
+ * worktree is reaped first (`reapMergedWorktrees`, which removes the tree and the
+ * branch together) so the "Clean N merged" affordance actually clears instead of
+ * offering the same branch on every visit. That reap refuses anything it cannot
+ * prove disposable — an uncommitted tree, a branch not fully in
+ * `origin/<default>` (which is also what rules out losing unpushed work: every
+ * commit on a reaped branch is already on the remote), a locked tree, a live
+ * agent's tree, or a human `/claim` session. Those come back in `skipped` with
+ * the reason, so the UI can say why one survived.
+ *
* @param {string} dir - Working directory
* @param {object} options
* @param {Set<string>} options.excludeBranches - Additional branches to protect (e.g., active agent branches)
- * @returns {Promise<{deleted: Array<{name: string, local: string, remote: string}>, skipped: string[], defaultBranch: string}>}
+ * @param {Set<string>} [options.activeAgentIds] - CoS agent ids whose worktrees must survive. Anything
+ * but a Set (the default) reads as "liveness unknown" and holds every `agent-*` worktree.
+ * @returns {Promise<{deleted: Array<{name: string, local: string, remote: string, worktree?: string}>, skipped: string[], defaultBranch: string}>}
*/
-export async function deleteMergedBranches(dir, { excludeBranches } = {}) {
+export async function deleteMergedBranches(dir, { excludeBranches, activeAgentIds = null } = {}) {
const [{ baseBranch }, currentBranch, worktreeBranches] = await Promise.all([
getRepoBranches(dir),
getBranch(dir),
@@ -1403,13 +1430,33 @@ export async function deleteMergedBranches(dir, { excludeBranches } = {}) {
const protectedSet = new Set(PROTECTED_BRANCHES);
if (baseBranch) protectedSet.add(baseBranch);
- // Worktree and agent branches are only protected from local deletion
+ // Worktree and agent branches are only protected from local deletion. Read
+ // BEFORE the reap and corrected below, so nothing the reap freed stays behind
+ // a hold that no longer exists.
const localOnlyProtected = new Set([...worktreeBranches]);
if (excludeBranches) {
for (const b of excludeBranches) localOnlyProtected.add(b);
}
- await execGitSafe(['fetch', 'origin', '--prune'], dir, { ignoreExitCode: true });
+ // Ahead of the merged-branch listing, so a reaped branch reads as an ordinary
+ // already-deleted local rather than as a worktree-held skip. `defaultBranch` is
+ // handed over because the reap's own lookup can fall back to a `remote set-head`
+ // probe, which is a 5s stall on this request path.
+ const reap = await reapMergedWorktrees(dir, {
+ activeAgentIds, excludeBranches, includeUnmanagedTrees: true, defaultBranch
+ }).catch(err => {
+ console.error(`❌ Worktree reap failed during merged-branch cleanup: ${err.message}`);
+ return null;
+ });
+ // Whatever the reap removed no longer has a worktree holding it, so drop the
+ // hold: a branch whose tree went but whose delete failed falls through to the
+ // ordinary `branch -d` pass below, which reports its own outcome.
+ for (const entry of reap?.reaped || []) localOnlyProtected.delete(entry.branch);
+ const reapedBranches = (reap?.reaped || []).filter(entry => entry.branch && entry.branchDeleted).map(entry => entry.branch);
+ const reapHolds = new Map((reap?.skipped || []).filter(entry => entry.branch).map(entry => [entry.branch, entry.reason]));
+
+ // The reap already fetched --prune; a second round-trip would change nothing.
+ if (!reap) await execGitSafe(['fetch', 'origin', '--prune'], dir, { ignoreExitCode: true });
const [localMergedNames, remoteMerged] = await Promise.all([
getLocalMergedBranchNames(dir, defaultBranch),
@@ -1430,7 +1477,9 @@ export async function deleteMergedBranches(dir, { excludeBranches } = {}) {
const localSet = new Set(mergedLocalNames);
const remoteSet = new Set(mergedRemoteNames);
- const deleted = [];
+ // One record per branch, so a branch whose local half the reap already deleted
+ // and whose remote half is deleted below reports as a single row.
+ const records = new Map(reapedBranches.map(name => [name, { name, local: 'deleted', remote: null, worktree: 'removed' }]));
const skipped = mergedLocalCandidates
.filter(name => localOnlyProtected.has(name) || name === currentBranch)
.map(name => {
@@ -1438,7 +1487,7 @@ export async function deleteMergedBranches(dir, { excludeBranches } = {}) {
? 'currently checked out'
: excludeBranches?.has(name)
? 'used by an active agent'
- : 'checked out in a worktree';
+ : worktreeHoldReason(reapHolds.get(name));
return `${name} (local: ${reason})`;
});
const opts = { ignoreExitCode: true };
@@ -1446,7 +1495,8 @@ export async function deleteMergedBranches(dir, { excludeBranches } = {}) {
for (const name of allMerged) {
const hasLocal = localSet.has(name);
const hasRemote = remoteSet.has(name);
- const result = { name, local: null, remote: null };
+ const result = records.get(name) || { name, local: null, remote: null };
+ records.set(name, result);
if (hasLocal) {
const r = await execGitSafe(['branch', '-d', name], dir, opts);
@@ -1459,12 +1509,10 @@ export async function deleteMergedBranches(dir, { excludeBranches } = {}) {
result.remote = r.exitCode === 0 ? 'deleted' : 'failed';
if (r.exitCode !== 0) skipped.push(`${name} (remote: ${r.stderr?.trim()})`);
}
-
- if (result.local === 'deleted' || result.remote === 'deleted') {
- deleted.push(result);
- }
}
+ const deleted = [...records.values()].filter(r => r.local === 'deleted' || r.remote === 'deleted');
+
return { deleted, skipped, defaultBranch };
}
diff --git a/server/services/worktreeManager.js b/server/services/worktreeManager.js
index c70e3bd59c..a80da8b151 100644
--- a/server/services/worktreeManager.js
+++ b/server/services/worktreeManager.js
@@ -980,6 +980,10 @@ export async function listWorktrees(sourceWorkspace) {
} else if (line === 'locked' || line.startsWith('locked ')) {
// `git worktree list --porcelain` emits a bare `locked` line, or `locked <reason>`.
current.locked = true;
+ } else if (line === 'prunable' || line.startsWith('prunable ')) {
+ // Same two spellings. Set when git considers the registration disposable —
+ // its directory is gone, or its .git pointer no longer resolves.
+ current.prunable = true;
}
}
if (current.path) worktrees.push(current);
@@ -1068,16 +1072,34 @@ export async function cleanupOrphanedWorktrees(sourceWorkspace, activeAgentIds)
* `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>} [options.activeAgentIds] - CoS agents currently running (never reaped)
+ * @param {Set<string>} [options.activeAgentIds] - CoS agents currently running (never reaped).
+ * 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}>, skipped: Array<{path,reason}>, defaultBranch: string, target: string, dryRun: boolean}>}
+ * @returns {Promise<{reaped: Array<{path,branch,locked,branchDeleted}>, skipped: Array<{path,branch,reason}>, defaultBranch: string, target: string, dryRun: boolean}>}
*/
export async function reapMergedWorktrees(sourceWorkspace, {
activeAgentIds = new Set(),
+ excludeBranches = null,
includeClaudeTrees = true,
+ includeUnmanagedTrees = false,
+ defaultBranch: knownDefaultBranch = null,
dryRun = false
} = {}) {
const { getDefaultBranch, isBranchMergedInto } = await import('./git.js');
@@ -1086,7 +1108,7 @@ export async function reapMergedWorktrees(sourceWorkspace, {
// after a `gh pr merge`. Best-effort — fall back to local refs on failure.
await execGit(['fetch', 'origin', '--prune'], sourceWorkspace, { ignoreExitCode: true }).catch(() => {});
- const defaultBranch = await getDefaultBranch(sourceWorkspace).catch(() => null) || 'main';
+ const defaultBranch = knownDefaultBranch || await getDefaultBranch(sourceWorkspace).catch(() => null) || 'main';
// Prefer the remote-tracking ref (post-merge truth); fall back to the local branch.
const remoteTarget = await execGit(['rev-parse', '--verify', `origin/${defaultBranch}^{commit}`], sourceWorkspace, { ignoreExitCode: true })
.then(r => (r.exitCode === 0 ? `origin/${defaultBranch}` : null))
@@ -1099,7 +1121,9 @@ export async function reapMergedWorktrees(sourceWorkspace, {
const protectedBranches = new Set(['main', 'master', 'dev', 'develop', 'release', defaultBranch]);
const claudeTreesRoot = join(sourceWorkspace, '.claude', 'worktrees');
- const managedRoots = [
+ // An empty allowlist is how worktreeOwnershipReason spells "no location check"
+ // (see includeUnmanagedTrees above for what that gives up).
+ const managedRoots = includeUnmanagedTrees ? [] : [
{ path: WORKTREES_DIR, requireAgentId: true },
{ path: claudeTreesRoot, requireAgentId: false },
];
@@ -1115,7 +1139,12 @@ export async function reapMergedWorktrees(sourceWorkspace, {
const branchName = wt.branch.replace(/^refs\/heads\//, '');
if (!branchName) { skipped.push({ path: wt.path, reason: 'no-branch' }); continue; }
- if (protectedBranches.has(branchName) || branchName === currentBranch) { skipped.push({ path: wt.path, reason: 'protected' }); 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)) {
+ hold('protected');
+ continue;
+ }
const isClaudeTree = isPathInsideDir(claudeTreesRoot, wt.path);
const ownershipReason = worktreeOwnershipReason({
@@ -1125,35 +1154,43 @@ export async function reapMergedWorktrees(sourceWorkspace, {
roots: managedRoots,
requireKnownLiveness: true,
});
- if (ownershipReason) {
- skipped.push({ path: wt.path, reason: ownershipReason });
- continue;
- }
- if (isClaudeTree && !includeClaudeTrees) { skipped.push({ path: wt.path, reason: 'claude-tree-excluded' }); continue; }
+ if (ownershipReason) { hold(ownershipReason); continue; }
+ if (isClaudeTree && !includeClaudeTrees) { hold('claude-tree-excluded'); continue; }
// Gate 1: working tree must be completely clean. Unlike removeWorktree(),
// the background reaper does not discard even lockfile-only edits: an
// uncommitted fresh-from-main worktree may be an active agent that has not
// made its first commit yet.
- const status = await execGit(['status', '--porcelain'], wt.path).then(r => r.stdout).catch(() => null);
- if (status === null) { skipped.push({ path: wt.path, reason: 'status-failed' }); continue; }
- if (!classifyWorktreeDirt(status).clean) { skipped.push({ path: wt.path, reason: 'uncommitted' }); continue; }
+ //
+ // A registration git already calls prunable has no working tree left to be
+ // dirty, so it reads as clean rather than status-failed — otherwise `git
+ // status` fails in the missing directory and the branch stays pinned behind a
+ // worktree that no longer exists. `existsSync` covers the same state on a git
+ // too old to report `prunable` in `worktree list --porcelain`.
+ const status = wt.prunable || !existsSync(wt.path)
+ ? ''
+ : await execGit(['status', '--porcelain'], wt.path).then(r => r.stdout).catch(() => null);
+ if (status === null) { hold('status-failed'); continue; }
+ if (!classifyWorktreeDirt(status).clean) { hold('uncommitted'); continue; }
// Gate 2: branch fully merged into the default branch (regular, squash, or rebase).
const merged = await isBranchMergedInto(sourceWorkspace, branchName, target).catch(() => false);
- if (!merged) { skipped.push({ path: wt.path, reason: 'unmerged' }); continue; }
+ if (!merged) { hold('unmerged'); continue; }
- if (dryRun) { reaped.push({ path: wt.path, branch: branchName, locked: !!wt.locked }); continue; }
+ if (dryRun) { reaped.push({ path: wt.path, branch: branchName, locked: !!wt.locked, branchDeleted: false }); continue; }
// 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, {
label: `worktree remove failed for ${wt.path}, manual cleanup`,
});
- await execGit(['branch', '-D', branchName], sourceWorkspace).catch(err => {
+ // Reported per entry: the tree is gone either way, 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}`);
+ return false;
});
- reaped.push({ path: wt.path, branch: branchName, locked: !!wt.locked });
+ reaped.push({ path: wt.path, branch: branchName, locked: !!wt.locked, branchDeleted });
}
if (reaped.length > 0) {
diff --git a/server/services/worktreeReap.test.js b/server/services/worktreeReap.test.js
index a97893da24..308e2eff3c 100644
--- a/server/services/worktreeReap.test.js
+++ b/server/services/worktreeReap.test.js
@@ -115,13 +115,31 @@ describe.skipIf(SKIP_HEAVY_INTEGRATION)('isBranchMergedInto', () => {
describe.skipIf(SKIP_HEAVY_INTEGRATION)('reapMergedWorktrees', () => {
let dir;
- beforeEach(async () => { dir = await initRepo(); });
- afterEach(async () => { await rm(dir, { recursive: true, force: true }); });
+ // One root OUTSIDE the repo for the includeUnmanagedTrees cases, torn down
+ // alongside the repo so a held tree can't leak out of the run.
+ let externalRoot;
+
+ beforeEach(async () => {
+ dir = await initRepo();
+ externalRoot = realpathSync(await mkdtemp(join(tmpdir(), 'portos-reap-ext-')));
+ });
+ afterEach(async () => {
+ await rm(dir, { recursive: true, force: true });
+ await rm(externalRoot, { recursive: true, force: true });
+ });
// The reaper only considers trees under WORKTREES_DIR (the real CoS data dir)
// or <repo>/.claude/worktrees — so the test trees live under .claude/worktrees.
const claudeRoot = (d) => join(d, '.claude', 'worktrees');
+ /** A worktree in a directory PortOS never created — the unmanaged case. */
+ async function addExternalWorktree(d, name, branch) {
+ const path = join(externalRoot, name);
+ await execGit(['worktree', 'add', '-b', branch, path, 'main'], d);
+ await commitFile(path, `${name}.txt`, `${name}\n`, `${name} work`);
+ return path;
+ }
+
async function addWorktree(d, name, branch, { commit = true, base = 'main' } = {}) {
const path = join(claudeRoot(d), name);
await mkdir(claudeRoot(d), { recursive: true });
@@ -254,6 +272,73 @@ 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 () => {
+ 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 });
+ expect(withoutOptIn.reaped.map(r => r.branch)).not.toContain('loose-br');
+ expect(skipReason(withoutOptIn, path)).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
+ // missing cwd and be skipped, pinning its branch behind a directory that no
+ // longer exists — the "clean merged" action could then never clear it.
+ it('reaps a merged branch whose worktree directory is already gone', async () => {
+ const path = await addWorktree(dir, 'vanished', 'vanished-br');
+ await execGit(['merge', '--no-ff', 'vanished-br', '--no-edit'], dir);
+ await rm(path, { recursive: true, force: true });
+
+ const result = await reapMergedWorktrees(dir, { includeClaudeTrees: true });
+
+ expect(
+ result.reaped.map(r => r.branch),
+ `nothing reaped; skipped = ${JSON.stringify(result.skipped)}`,
+ ).toContain('vanished-br');
+ const branches = (await execGit(['branch', '--format=%(refname:short)'], dir)).stdout.trim().split('\n');
+ expect(branches).not.toContain('vanished-br');
+ const listed = (await execGit(['worktree', 'list', '--porcelain'], dir)).stdout;
+ 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);