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: hold branches queued for the pending-merge coordinator in branch reconcile (#12258)

[._.]/ Adam Eivye197cef36937
diff --git a/server/services/branchReconcile.js b/server/services/branchReconcile.js
index 5cf822c244..350ad9d3da 100644
--- a/server/services/branchReconcile.js
+++ b/server/services/branchReconcile.js
@@ -463,6 +463,26 @@ function resolveClaimOwnerReason({ branch, path, claimOwners, sourceWorkspace })
});
}
+/**
+ * A branch queued for the pr-watcher's deterministic merge coordinator (an
+ * agent handoff receipt or a merge-on-green PR) has an open PR and no live
+ * agent, yet the coordinator owns its merge: a reconcile agent waiting on CI or
+ * rebasing would race it and invalidate the handoff's head binding.
+ *
+ * `pendingMergeBranches` is a Set of queued branch names, `null` when the app
+ * record could not be read (holds every branch — fail closed), and undefined
+ * when the caller has no app to ask (nothing added).
+ *
+ * @param {Set<string>|null|undefined} pendingMergeBranches
+ * @param {string} branch
+ * @returns {string|null}
+ */
+function pendingMergeReason(pendingMergeBranches, branch) {
+ if (pendingMergeBranches === undefined) return null;
+ if (pendingMergeBranches === null) return 'pending-merge-unavailable';
+ return pendingMergeBranches.has(branch) ? 'pending-merge-queued' : null;
+}
+
/**
* Is this worktree a CoS agent workspace whose agent is no longer running?
*
@@ -885,7 +905,7 @@ async function worktreeAgeMs(worktreePath) {
* worktreeDirty, dirtyPaths, behind, ahead, collisionPaths, abandonedAgentWorktree,
* abandonedClaimWorktree, openPr }
*/
-export async function gatherBranchState(repoPath, { defaultBranch, activeAgentIds = null, claimOwners = undefined, remoteHeads: providedRemoteHeads, hasOrigin: providedHasOrigin, origin: providedOrigin, forgeExec = null, forgeAccount = null } = {}) {
+export async function gatherBranchState(repoPath, { defaultBranch, activeAgentIds = null, claimOwners = undefined, remoteHeads: providedRemoteHeads, hasOrigin: providedHasOrigin, origin: providedOrigin, forgeExec = null, forgeAccount = null, pendingMergeBranches = undefined } = {}) {
const protectedSet = new Set([...PROTECTED_BRANCHES, defaultBranch]);
// Read origin ONCE and use it for both facts below — `hasOrigin` (the gate on
// classifyBranch's ahead-based NEEDS_PR arm, so an origin-less repo's local work
@@ -999,7 +1019,7 @@ export async function gatherBranchState(repoPath, { defaultBranch, activeAgentId
// set nor the branch name can see it (#10089).
liveOwnerReason: resolveLiveOwnerReason({
branch: b.name, path: worktreePath, locked: worktreeLocked, activeAgentIds
- }) || claimOwnerReason || (worktreeStatusUnavailable ? 'worktree-status-unavailable' : null),
+ }) || claimOwnerReason || pendingMergeReason(pendingMergeBranches, b.name) || (worktreeStatusUnavailable ? 'worktree-status-unavailable' : null),
claimOwnerReason,
behind: divergence.behind,
ahead: divergence.ahead,
@@ -1559,6 +1579,8 @@ async function reapDetachedWorktrees(repoPath, defaultBranch, detached, { active
* registered claim owners — see `resolveClaimOwnerReason`; a dispatching
* caller must pass it. `readAgents` re-reads the registry right before each
* retirement, because a claim run can bind a branch after the scan.
+ * `pendingMergeBranches` (Set, or null for an unreadable app record) holds the
+ * branches queued for the pr-watcher merge coordinator — see `pendingMergeReason`.
* `forgeAccount` is the managed app record's explicit gh
* account pin, so an app whose repo belongs to another GitHub account is
* polled with a credential that can actually see it (#7540); unset, the
@@ -1574,7 +1596,7 @@ async function reapDetachedWorktrees(repoPath, defaultBranch, detached, { active
* failed mid-cycle. Either way an empty `inFlight` says nothing about the repo
* and the caller must retry rather than park on it (#3358).
*/
-export async function reconcile(repoPath = PATHS.root, { cleanup = true, reapSuperseded = cleanup, reapRemotes = false, activeAgentIds = new Set(), claimOwners = undefined, forgeAccount = null } = {}) {
+export async function reconcile(repoPath = PATHS.root, { cleanup = true, reapSuperseded = cleanup, reapRemotes = false, activeAgentIds = new Set(), claimOwners = undefined, forgeAccount = null, pendingMergeBranches = undefined } = {}) {
if (claimOwners === undefined) claimOwners = { agents: await readClaimOwnershipAgents(), readAgents: readClaimOwnershipAgents };
// Worktree cleanup is the first reconcile step, before any forge probe. It
// only removes a tree after proving both that it is completely clean and
@@ -1637,7 +1659,7 @@ export async function reconcile(repoPath = PATHS.root, { cleanup = true, reapSup
const remoteHeads = origin?.hasOrigin ? await listRemoteHeads(repoPath) : null;
const inputs = await gatherBranchState(repoPath, {
defaultBranch, activeAgentIds, claimOwners, remoteHeads, hasOrigin: Boolean(origin?.hasOrigin), origin,
- forgeExec, forgeAccount
+ forgeExec, forgeAccount, pendingMergeBranches
});
// A gh failure AFTER a passing probe (a blip mid-cycle, or an unparseable
// page) is still "we could not ask" — surface it so the caller retries next
diff --git a/server/services/branchReconcile.ownership.test.js b/server/services/branchReconcile.ownership.test.js
index ac5c57c93c..8059b008a1 100644
--- a/server/services/branchReconcile.ownership.test.js
+++ b/server/services/branchReconcile.ownership.test.js
@@ -54,7 +54,7 @@ vi.mock('./supersededLedger.js', async (importOriginal) => ({
readVerdictLedger: async () => [],
}));
-const { reconcile, cleanupMerged, reapSupersededBranches, describeIdleReconcilePark } = await import('./branchReconcile.js');
+const { reconcile, gatherBranchState, classifyBranches, cleanupMerged, reapSupersededBranches, describeIdleReconcilePark } = await import('./branchReconcile.js');
const { clearAgentDispatching, getActiveAgentIds, markAgentDispatching } = await import('./agentState.js');
const { deleteMergedBranches } = await import('./git.js');
@@ -268,6 +268,27 @@ describe.skipIf(SKIP_HEAVY_INTEGRATION)('branch-reconcile worktree ownership (re
expect(await branches()).toContain(branch);
});
+ it('holds a branch queued for the pending-merge coordinator instead of dispatching its open PR, and fails closed when the queue is unreadable', async () => {
+ const branch = 'claim/issue-1';
+ await execGit(['checkout', '-q', '-b', branch], repo);
+ await writeFile(join(repo, 'queued.txt'), 'queued work\n');
+ await execGit(['add', 'queued.txt'], repo);
+ await execGit(['commit', '-m', 'feat: queued work'], repo);
+ await execGit(['checkout', '-q', 'main'], repo);
+ const base = { defaultBranch: 'main', activeAgentIds: new Set(), claimOwners: { agents: [], readAgents: async () => [] } };
+ // No origin means no forge read, so the PR the coordinator owns is supplied
+ // on the gathered entry the way the forge listing would.
+ const stateFor = async (pendingMergeBranches) => {
+ const entry = (await gatherBranchState(repo, { ...base, pendingMergeBranches })).find(i => i.branch === branch);
+ return classifyBranches([{ ...entry, hasOrigin: true, openPr: { number: 1, mergeable: 'MERGEABLE' } }])[0];
+ };
+
+ expect(await stateFor(undefined)).toMatchObject({ state: 'IN_REVIEW' });
+ expect(await stateFor(new Set())).toMatchObject({ state: 'IN_REVIEW' });
+ expect(await stateFor(new Set([branch]))).toMatchObject({ state: 'WIP', liveOwnerReason: 'pending-merge-queued' });
+ expect(await stateFor(null)).toMatchObject({ state: 'WIP', liveOwnerReason: 'pending-merge-unavailable' });
+ });
+
it('refreshes a completion handoff before direct retirement and after a Git refusal', async () => {
const ref = 'fix/policy-held-ref';
const checkedOut = 'fix/policy-held-tree';
diff --git a/server/services/repoSync.js b/server/services/repoSync.js
index c43d0536ff..73f714ce26 100644
--- a/server/services/repoSync.js
+++ b/server/services/repoSync.js
@@ -746,6 +746,18 @@ export function describeStep(step) {
}
}
+/**
+ * Branches the app's pr-watcher queue owns (undefined without an app; null when
+ * the record is unreadable, which holds every branch in reconcile).
+ */
+async function readPendingMergeBranches(appId) {
+ if (!appId) return undefined;
+ const [{ getAppById }, { readPendingMergePrs }] = await Promise.all([import('./apps.js'), import('./prWatcher.js')]);
+ const app = await getAppById(appId).catch(() => null);
+ if (!app) return null;
+ return new Set(readPendingMergePrs(app).map((entry) => entry?.prBranch).filter(Boolean));
+}
+
/**
* Sync ONE repo: snapshot → plan → execute → hand back what still needs a human
* or an agent. Never throws; a scan that blows up is reported as a `scan-failed`
@@ -837,11 +849,13 @@ export async function syncRepo(repo, { activeAgentIds = new Set() } = {}) {
&& !state.fetchError;
if (actionOn(actions, 'cleanupMerged') && reconcileSafe) {
const { reconcile } = await import('./branchReconcile.js');
+ const pendingMergeBranches = await readPendingMergeBranches(appId);
const result = await reconcile(repoPath, {
cleanup: true,
reapRemotes: actions.reapRemotes === true,
activeAgentIds,
- forgeAccount
+ forgeAccount,
+ pendingMergeBranches
}).catch((err) => {
escalations.push({ kind: ESCALATION_KINDS.SCAN_FAILED, detail: `branch cleanup failed: ${err.message}` });
return null;
diff --git a/server/services/repoSync.test.js b/server/services/repoSync.test.js
index 7726d142da..daa72a1411 100644
--- a/server/services/repoSync.test.js
+++ b/server/services/repoSync.test.js
@@ -36,6 +36,8 @@ vi.mock('../lib/gitRemote.js', () => ({
getOriginInfo: vi.fn(async () => ({ hasOrigin: true, host: 'github.com' }))
}));
const reconcileMock = vi.fn(async () => ({ defaultBranch: 'main', cleaned: [], inFlight: [], wip: [], skipped: [], orphanRemotes: { reaped: [], reported: [] } }));
+const appsMock = vi.hoisted(() => ({ getAppById: vi.fn() }));
+vi.mock('./apps.js', () => appsMock);
vi.mock('./branchReconcile.js', () => ({ reconcile: (...args) => reconcileMock(...args) }));
const {
@@ -661,6 +663,22 @@ describe('syncRepo — the argv it issues is the non-destructive form', () => {
expect(reconcileMock.mock.calls[0][1].reapRemotes).toBe(true);
});
+ it('hands the app\'s queued pending-merge branches to branch cleanup, failing closed on an unreadable app', async () => {
+ arrange();
+ appsMock.getAppById.mockResolvedValueOnce({ id: 'app-1', pendingMergePrs: [{ prNumber: 7, prUrl: 'https://example.com/pr/7', prBranch: 'claim/issue-7', sourceTask: {} }] });
+ await syncRepo({ repoPath: process.cwd(), appId: 'app-1', name: 'Example' });
+ expect(reconcileMock.mock.calls[0][1].pendingMergeBranches).toEqual(new Set(['claim/issue-7']));
+
+ reconcileMock.mockClear();
+ appsMock.getAppById.mockRejectedValueOnce(new Error('unreadable'));
+ await syncRepo({ repoPath: process.cwd(), appId: 'app-1', name: 'Example' });
+ expect(reconcileMock.mock.calls[0][1].pendingMergeBranches).toBeNull();
+
+ reconcileMock.mockClear();
+ await syncRepo({ repoPath: process.cwd(), name: 'Example' });
+ expect(reconcileMock.mock.calls[0][1].pendingMergeBranches).toBeUndefined();
+ });
+
it('skips branch cleanup entirely when cleanupMerged is off', async () => {
arrange();
await syncRepo({ repoPath: process.cwd(), name: 'Example', actions: { cleanupMerged: false } });