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: clean reconciled branches when the coordinator completes

Adam Eivy12cf746ab7d0
diff --git a/server/services/README.md b/server/services/README.md
index 32307663bd..388711dd25 100644
--- a/server/services/README.md
+++ b/server/services/README.md
@@ -6,6 +6,7 @@ image-generation paths below are useful entry points when tracing render jobs.
| Module | Responsibility |
| --- | --- |
+| `branchReconcileCompletion.js` | Runs ownership-checked merged and superseded cleanup on coordinator completion, independent of perpetual scheduling. |
| `branchCompletionPolicy.js` | Retains explicit registered PR completion policy through agent archives. `readBranchCompletionHold` gates reconciliation by exact repository/branch/PR identity; human handoffs and configured review stay held, explicit releases require a fresh matching forge head, and verified merged retirement is a separate action. |
| `databaseCutoverHandshake.js` | Narrow fenced-boot path for the ordinary server: at `verifying`/`verified` prove this process's own pool reaches the recorded target, publish a per-pid proof, and wait for admission release before the app graph loads. |
| `databaseMaintenanceCutover.js` | Internal cutover worker body (transfer → forward-only `.env` mode commit → server restart with target proof → release → CoS restart) and `recoverDatabaseCutover(id)` same-operation recovery for the CLI/API. |
diff --git a/server/services/branchReconcile.js b/server/services/branchReconcile.js
index 350ad9d3da..73e71577b7 100644
--- a/server/services/branchReconcile.js
+++ b/server/services/branchReconcile.js
@@ -1840,7 +1840,7 @@ const supersessionGate = ({ collisionPaths = [], behind } = {}) => {
'For each, read the default branch\'s current version and compare it to what this branch does there. You are looking for one thing: has the default branch already solved this branch\'s problem, by any means? A differently-named function, a policy object where this branch has a boolean, a scheduled tick where this branch has a watcher — all count. It does not need to look like this branch\'s approach to have replaced it.',
'If it HAS been solved there, this branch is SUPERSEDED: stop, do not commit, rebase, resolve, or merge anything, and report it as superseded naming the file(s) and what on the default branch replaced it. Merging it would undo work already shipped. Say so plainly rather than resolving the conflict — a conflict you can resolve is exactly how a regression gets in looking deliberate.',
recordVerdictInstruction(ledgerPath()),
- 'Recording the verdict is the handoff to this scheduled task\'s deterministic cleanup pass. It backs up the branch commits, tracked diff, and untracked files, then removes the worktree and branch on the immediately-following drain pass. Do not describe the surviving branch as work a human must clean up, and do not write the verdict anywhere except the absolute ledger path above — a ledger inside the abandoned worktree is invisible to the running PortOS instance and leaves the branch stranded.',
+ 'Recording the verdict is the handoff to this scheduled task\'s deterministic cleanup pass. It backs up the branch commits, tracked diff, and untracked files, then removes the worktree and branch in the completion cleanup pass (without waiting for another scheduled run). Do not describe the surviving branch as work a human must clean up, and do not write the verdict anywhere except the absolute ledger path above — a ledger inside the abandoned worktree is invisible to the running PortOS instance and leaves the branch stranded.',
'Only once you have confirmed the work is still needed, continue.'
].join(' ');
};
diff --git a/server/services/branchReconcile.test.js b/server/services/branchReconcile.test.js
index b00a42fcad..ff9adba481 100644
--- a/server/services/branchReconcile.test.js
+++ b/server/services/branchReconcile.test.js
@@ -2005,7 +2005,7 @@ describe('desiredEndState', () => {
expect(instruction).toContain('SUPERSEDED');
expect(instruction).toContain('still needed');
expect(instruction).toMatch(/[\\/]repo[\\/]data[\\/]cos[\\/]branch-reconcile-verdicts\.json/);
- expect(instruction).toContain('immediately-following drain pass');
+ expect(instruction).toContain('without waiting for another scheduled run');
expect(instruction).toContain('ledger inside the abandoned worktree is invisible');
// Ordering: the gate precedes any instruction to commit/rebase/resolve.
const gateAt = instruction.indexOf('still needed');
diff --git a/server/services/branchReconcileCompletion.js b/server/services/branchReconcileCompletion.js
new file mode 100644
index 0000000000..0dcf1da6ef
--- /dev/null
+++ b/server/services/branchReconcileCompletion.js
@@ -0,0 +1,39 @@
+import { getAppById } from './apps.js';
+import { getTaskById } from './cosTaskStore.js';
+import { getActiveAgentIds } from './agentState.js';
+import { readClaimOwnershipAgents } from './cosClaimOwnership.js';
+import { reconcile, buildActiveOwnerIds, describeIdleReconcilePark } from './branchReconcile.js';
+import { emitLog } from './cosEvents.js';
+
+/** Finish deterministic cleanup without requiring another provider dispatch. */
+export async function settleBranchReconcileRun(agent) {
+ const type = agent?.metadata?.taskAnalysisType || agent?.metadata?.analysisType || agent?.metadata?.selfImprovementType;
+ if (type !== 'branch-reconcile') return null;
+ const task = await getTaskById(agent.taskId);
+ // The task holds the resolved per-app toggles. Missing records cannot grant cleanup.
+ if (!task?.metadata || task.metadata.cleanupMerged === false) return null;
+ const app = await getAppById(agent.metadata.taskApp);
+ if (!app?.repoPath) throw new Error('Branch reconciliation completion target unavailable');
+ const agents = await readClaimOwnershipAgents();
+ if (!Array.isArray(agents)) throw new Error('Branch reconciliation ownership state unavailable');
+ // Branches queued for the pr-watcher merge coordinator count as owned (#12258).
+ const { readPendingMergePrs } = await import('./prWatcher.js');
+ const pendingMergeBranches = new Set(readPendingMergePrs(app).map((entry) => entry?.prBranch).filter(Boolean));
+ const result = await reconcile(app.repoPath, {
+ cleanup: true,
+ pendingMergeBranches,
+ activeAgentIds: buildActiveOwnerIds(getActiveAgentIds(), agents),
+ claimOwners: { agents, readAgents: readClaimOwnershipAgents },
+ forgeAccount: app.forgeAccount || null
+ });
+ const holds = describeIdleReconcilePark(result.skipped || [], [], {
+ wip: result.wip, detachedWorktrees: result.detachedWorktrees,
+ superseded: result.superseded, claimMarkersHeld: result.claimMarkersHeld
+ });
+ const uncertain = result.forgeUnavailable || result.prStateUnavailable;
+ const remaining = (result.inFlight?.length || 0) + (holds.counts?.heldBranches || 0) + (holds.counts?.heldDetached || 0);
+ emitLog(uncertain || remaining ? 'warn' : 'info',
+ `Branch reconciliation completion: cleaned ${result.cleaned.length}, superseded ${result.reapedSuperseded?.length || 0}, remaining ${remaining}${uncertain ? '; scan incomplete' : ''}`,
+ { appId: app.id, analysisType: type, counts: holds.counts, skipCauses: holds.skipCauses });
+ return result;
+}
diff --git a/server/services/branchReconcileCompletion.test.js b/server/services/branchReconcileCompletion.test.js
new file mode 100644
index 0000000000..88b1667905
--- /dev/null
+++ b/server/services/branchReconcileCompletion.test.js
@@ -0,0 +1,55 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+vi.mock('./apps.js', () => ({ getAppById: vi.fn() }));
+vi.mock('./cosTaskStore.js', () => ({ getTaskById: vi.fn() }));
+vi.mock('./agentState.js', () => ({ getActiveAgentIds: vi.fn(() => new Set(['active'])) }));
+vi.mock('./cosClaimOwnership.js', () => ({ readClaimOwnershipAgents: vi.fn() }));
+vi.mock('./branchReconcile.js', () => ({
+ reconcile: vi.fn(), buildActiveOwnerIds: vi.fn(() => new Set(['active'])),
+ describeIdleReconcilePark: vi.fn(() => ({ counts: null, skipCauses: null }))
+}));
+vi.mock('./cosEvents.js', () => ({ emitLog: vi.fn() }));
+vi.mock('./prWatcher.js', () => ({ readPendingMergePrs: vi.fn(() => [{ prBranch: 'claim/queued' }]) }));
+import { getAppById } from './apps.js';
+import { getTaskById } from './cosTaskStore.js';
+import { readClaimOwnershipAgents } from './cosClaimOwnership.js';
+import { reconcile } from './branchReconcile.js';
+import { settleBranchReconcileRun } from './branchReconcileCompletion.js';
+
+const agent = { taskId: 'task-example', metadata: { taskAnalysisType: 'branch-reconcile', taskApp: 'example' } };
+describe('branch reconciliation completion', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ getTaskById.mockResolvedValue({ metadata: { perpetual: false } });
+ getAppById.mockResolvedValue({ id: 'example', repoPath: '/example/repo', forgeAccount: 'example-account' });
+ readClaimOwnershipAgents.mockResolvedValue([]);
+ reconcile.mockResolvedValue({ cleaned: ['merged'], reapedSuperseded: ['superseded'], inFlight: [], skipped: [] });
+ });
+ it('settles a non-perpetual run immediately using fresh ownership and its target account', async () => {
+ expect(await settleBranchReconcileRun(agent)).toMatchObject({ cleaned: ['merged'], reapedSuperseded: ['superseded'] });
+ expect(reconcile).toHaveBeenCalledWith('/example/repo', {
+ cleanup: true, pendingMergeBranches: new Set(['claim/queued']), activeAgentIds: new Set(['active']),
+ claimOwners: { agents: [], readAgents: readClaimOwnershipAgents }, forgeAccount: 'example-account'
+ });
+ });
+ it('cleans verified work even when the coordinator failed after making progress', async () => {
+ await settleBranchReconcileRun({ ...agent, result: { success: false } });
+ expect(reconcile).toHaveBeenCalledOnce();
+ });
+ it('preserves a disabled cleanup action and missing task policy', async () => {
+ getTaskById.mockResolvedValueOnce({ metadata: { cleanupMerged: false } }).mockResolvedValueOnce(null);
+ await settleBranchReconcileRun(agent);
+ await settleBranchReconcileRun(agent);
+ expect(reconcile).not.toHaveBeenCalled();
+ });
+ it('fails closed on unreadable ownership or a missing target', async () => {
+ readClaimOwnershipAgents.mockRejectedValueOnce(new Error('unreadable'));
+ await expect(settleBranchReconcileRun(agent)).rejects.toThrow('unreadable');
+ getAppById.mockResolvedValueOnce(null);
+ await expect(settleBranchReconcileRun(agent)).rejects.toThrow('target unavailable');
+ expect(reconcile).not.toHaveBeenCalled();
+ });
+ it('ignores other completed task types', async () => {
+ await settleBranchReconcileRun({ metadata: { taskAnalysisType: 'claim-issue' } });
+ expect(getTaskById).not.toHaveBeenCalled();
+ });
+});
diff --git a/server/services/cos.js b/server/services/cos.js
index 0c640bb393..86d5de5465 100644
--- a/server/services/cos.js
+++ b/server/services/cos.js
@@ -1521,17 +1521,18 @@ export async function init() {
// When an agent completes, refill perpetual work then dequeue the next task
cosEvents.on('agent:completed', (agent) => {
- // Refill the perpetual backlog FIRST, THEN dequeue — in one async task so the
- // generic dequeue can't fill the just-freed slot with idle-review work ahead
- // of the perpetual re-queue. Perpetual schedules (e.g. claim-issue) drain
- // back-to-back: regenerate the next eligible task now instead of waiting for
- // the ~hourly improvement check (dequeueNextTask only spawns ALREADY-queued
- // work, so on its own a perpetual backlog stalls between ticks). The refill
- // early-returns fast for non-perpetual or failed completions, so for those
- // this stays a thin wrapper around the dequeue. Both steps are .catch-guarded
- // because this runs outside the request lifecycle.
+ // Settle deterministic cleanup even for one-shot/failed runs. Then refill
+ // before dequeue so unrelated idle work cannot take the newly freed slot.
+ // Each phase owns its rejection because this is an event boundary.
setImmediate(() => {
- refillPerpetualForCompletedAgent(agent)
+ Promise.resolve()
+ .then(async () => {
+ if (agentScheduledType(agent) !== 'branch-reconcile') return;
+ const { settleBranchReconcileRun } = await import('./branchReconcileCompletion.js');
+ await settleBranchReconcileRun(agent);
+ })
+ .catch(err => console.error(`❌ Branch reconciliation completion failed: ${err.message}`))
+ .then(() => refillPerpetualForCompletedAgent(agent))
.catch(err => console.error(`❌ Perpetual refill after ${agent?.id} failed: ${err.message}`))
// Same window as the refill above: this runs before the completing
// task's `updateTask` settles it, so the idle tier's generator must
diff --git a/server/services/cos.test.js b/server/services/cos.test.js
index 2816d77622..0bbcc100c7 100644
--- a/server/services/cos.test.js
+++ b/server/services/cos.test.js
@@ -2423,6 +2423,9 @@ describe('cos.js source — agent:completed triggers perpetual refill', () => {
it("the agent:completed listener invokes the perpetual refill path", () => {
const onIdx = COS_SRC.indexOf("cosEvents.on('agent:completed'");
expect(onIdx, 'agent:completed listener must exist').toBeGreaterThan(-1);
+ const completionIdx = COS_SRC.indexOf('await settleBranchReconcileRun(agent)', onIdx);
+ expect(completionIdx).toBeGreaterThan(onIdx);
+ expect(completionIdx).toBeLessThan(COS_SRC.indexOf('refillPerpetualForCompletedAgent(agent)', onIdx));
const handlerSlice = COS_SRC.slice(onIdx, onIdx + 1200);
expect(
handlerSlice.includes('refillPerpetualForCompletedAgent'),