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: retire merged branches before recovery tasks

[._.]/ Adam Eivy592555f76853
diff --git a/server/services/agentRepoStateVerification.js b/server/services/agentRepoStateVerification.js
index a70915c53d..467309d2b0 100644
--- a/server/services/agentRepoStateVerification.js
+++ b/server/services/agentRepoStateVerification.js
@@ -36,7 +36,7 @@ import { emitLog } from './cosEvents.js';
import { addTask } from './cos.js';
import * as git from './git.js';
import { listWorktrees } from './worktreeManager.js';
-import { listRemoteHeads, driveToMerge } from './branchReconcile.js';
+import { listRemoteHeads, driveToMerge, cleanupMerged } from './branchReconcile.js';
import { readAllTasksFlat } from './investigationTaskProducer.js';
import { execGit } from '../lib/execGit.js';
import { PATHS } from '../lib/fileUtils.js';
@@ -312,6 +312,26 @@ export async function verifyAgentRepoState({ agentId, task, agentState, success,
return { verified: true, skipReason: null, issues: [], observed, recoveryTaskId: null };
}
+ // A merged branch with no remote ref is safe for the deterministic reaper to
+ // retire. Do this before creating another agent task: the common failure is
+ // simply that the completing agent exited before its worktree teardown ran.
+ // `cleanupMerged` repeats merge evidence and the clean-worktree/protection
+ // gates at action time, so an unsafe or racing state falls through to the
+ // existing evidence-backed recovery task.
+ const cleanupOnly = observed.branchMerged === true
+ && observed.remoteBranchPresent === false
+ && !issues.some(issue => issue.code === REPO_STATE_ISSUES.PR_UNMERGED);
+ if (cleanupOnly) {
+ const retired = await cleanupMerged(sourceWorkspace, observed.defaultBranch, [{
+ branch: branchName,
+ upstreamGone: true,
+ }]).catch(() => ({ cleaned: [] }));
+ if (retired.cleaned.includes(branchName)) {
+ emitLog('info', `🔎 Deterministic cleanup retired merged branch ${branchName} for ${agentId}`, { agentId, branchName });
+ return { verified: true, skipReason: null, issues: [], observed, recoveryTaskId: null };
+ }
+ }
+
emitLog('warn', `🔎 Repo state diverged after ${agentId}: ${issues.map(i => i.code).join(', ')}`, { agentId, branchName, taskId: task?.id });
const recoveryTaskId = await fileRepoStateRecoveryTask({
diff --git a/server/services/agentRepoStateVerification.test.js b/server/services/agentRepoStateVerification.test.js
index f7119d9fdf..33d2329274 100644
--- a/server/services/agentRepoStateVerification.test.js
+++ b/server/services/agentRepoStateVerification.test.js
@@ -25,6 +25,7 @@ vi.mock('./prWatcher.js', () => ({ readPendingMergePrs: vi.fn().mockReturnValue(
vi.mock('./worktreeManager.js', () => ({ listWorktrees: vi.fn().mockResolvedValue([]) }));
vi.mock('./branchReconcile.js', () => ({
listRemoteHeads: vi.fn().mockResolvedValue(new Map()),
+ cleanupMerged: vi.fn().mockResolvedValue({ cleaned: [] }),
driveToMerge: (pr) => `merge ${pr} from the repo root once CI is green`,
}));
vi.mock('./git.js', () => ({
@@ -53,7 +54,7 @@ import { verifyAgentRepoState, REPO_STATE_REMEDIATIONS } from './agentRepoStateV
import { addTask, getAllTasks } from './cos.js';
import { ensureTaskThread } from './brainTaskThreads.js';
import { listWorktrees } from './worktreeManager.js';
-import { listRemoteHeads } from './branchReconcile.js';
+import { listRemoteHeads, cleanupMerged } from './branchReconcile.js';
import { hasBranchMergeEvidence, resolveForgeForRepo } from './git.js';
import { findPullRequestForBranch } from './github.js';
import { findMergeRequestForBranch } from './gitlab.js';
@@ -102,6 +103,7 @@ beforeEach(() => {
vi.clearAllMocks();
listWorktrees.mockResolvedValue([]);
listRemoteHeads.mockResolvedValue(new Map());
+ cleanupMerged.mockResolvedValue({ cleaned: [] });
existsSync.mockReturnValue(false);
hasBranchMergeEvidence.mockResolvedValue(true);
queuedTasks([]);
@@ -136,6 +138,19 @@ describe('verifyAgentRepoState — clean runs', () => {
});
describe('verifyAgentRepoState — divergent runs', () => {
+ it('retires a clean merged branch deterministically instead of queuing an agent', async () => {
+ existsSync.mockReturnValue(true);
+ localBranch(true);
+ findPullRequestForBranch.mockResolvedValue({ status: 'found', url: 'https://example.com/pr/1', detail: 'MERGED' });
+ cleanupMerged.mockResolvedValue({ cleaned: [BRANCH], skipped: [] });
+
+ const result = await run();
+
+ expect(result).toMatchObject({ verified: true, recoveryTaskId: null });
+ expect(cleanupMerged).toHaveBeenCalledWith('/repo', 'main', [{ branch: BRANCH, upstreamGone: true }]);
+ expect(addTask).not.toHaveBeenCalled();
+ });
+
it('files ONE recovery task for a leftover worktree and branch after a merged PR', async () => {
// The reported failure shape: the agent merged its own PR (branch gone on the
// forge) but its local branch and worktree survived cleanup silently.