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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
refactor: clarify branch merge evidence while preserving cleanup behavior (#6716)
[._.]/ Adam Eivy0dc663e9fdfc
diff --git a/server/services/agentRepoStateVerification.js b/server/services/agentRepoStateVerification.jsindex f16ece14c8..4d7fb073b4 100644--- a/server/services/agentRepoStateVerification.js+++ b/server/services/agentRepoStateVerification.js@@ -102,8 +102,7 @@ async function branchHasPendingOwner(branchName, app) {}/**- * Is `branch` already on `target`? Tri-state, unlike `isBranchMergedInto`, which- * answers `false` both for "not merged" and for "could not tell".+ * Probe merge evidence, returning null when the preliminary ref checks fail.** @returns {Promise<boolean|null>} null when either ref could not be resolved*/@@ -113,7 +112,7 @@ async function probeBranchMerged(repoPath, branch, target) {.catch(() => false);const [hasBranch, hasTarget] = await Promise.all([resolvable(branch), resolvable(target)]);if (!hasBranch || !hasTarget) return null;- return git.isBranchMergedInto(repoPath, branch, target).catch(() => null);+ return git.hasBranchMergeEvidence(repoPath, branch, target).catch(() => null);}/**@@ -189,13 +188,8 @@ async function probeRepoState({ sourceWorkspace, branchName, worktreePath, branc]);// Only meaningful while the branch still exists locally.- //- // `isBranchMergedInto` fails CLOSED — it returns `false`, not a throw, when it- // cannot resolve either ref (git.js). That polarity is right for its original- // caller, which preserves a branch on doubt; here it inverts into a FINDING, so- // an unreadable repo would file a recovery task claiming unmerged work. Resolve- // both refs first: if either cannot be read, the answer is `null` (unknown), and- // only a `false` backed by two resolvable refs is reported.+ // Diagnostics require readable refs before reporting absent merge evidence;+ // otherwise an unreadable repo would produce a false recovery finding.const branchMerged = localBranchPresent === true && defaultBranch? await probeBranchMerged(sourceWorkspace, branchName, defaultBranch): null;diff --git a/server/services/agentRepoStateVerification.test.js b/server/services/agentRepoStateVerification.test.jsindex 4b1a406bf9..ca9f383613 100644--- a/server/services/agentRepoStateVerification.test.js+++ b/server/services/agentRepoStateVerification.test.js@@ -29,7 +29,7 @@ vi.mock('./branchReconcile.js', () => ({}));vi.mock('./git.js', () => ({getDefaultBranch: vi.fn().mockResolvedValue('main'),- isBranchMergedInto: vi.fn().mockResolvedValue(true),+ hasBranchMergeEvidence: vi.fn().mockResolvedValue(true),resolveForgeForRepo: vi.fn().mockResolvedValue({ cli: 'gh', env: null }),}));vi.mock('./github.js', () => ({@@ -52,7 +52,7 @@ import { verifyAgentRepoState, REPO_STATE_REMEDIATIONS } from './agentRepoStateVimport { addTask, getAllTasks } from './cos.js';import { listWorktrees } from './worktreeManager.js';import { listRemoteHeads } from './branchReconcile.js';-import { isBranchMergedInto, resolveForgeForRepo } from './git.js';+import { hasBranchMergeEvidence, resolveForgeForRepo } from './git.js';import { findPullRequestForBranch } from './github.js';import { findMergeRequestForBranch } from './gitlab.js';import { getAppById } from './apps.js';@@ -101,7 +101,7 @@ beforeEach(() => {listWorktrees.mockResolvedValue([]);listRemoteHeads.mockResolvedValue(new Map());existsSync.mockReturnValue(false);- isBranchMergedInto.mockResolvedValue(true);+ hasBranchMergeEvidence.mockResolvedValue(true);queuedTasks([]);getAppById.mockResolvedValue({ id: 'demo-app', name: 'Demo App' });readPendingMergePrs.mockReturnValue([]);@@ -173,7 +173,7 @@ describe('verifyAgentRepoState — divergent runs', () => {it('reports an unmerged PR the agent left open', async () => {localBranch(true);- isBranchMergedInto.mockResolvedValue(false);+ hasBranchMergeEvidence.mockResolvedValue(false);listRemoteHeads.mockResolvedValue(new Map([[BRANCH, 'abc123']]));findPullRequestForBranch.mockResolvedValue({ status: 'found', url: 'https://example.com/pr/9', detail: 'OPEN' });@@ -366,7 +366,7 @@ describe('verifyAgentRepoState — never fires', () => {});it('does not claim unmerged work when the merge check could not be answered', async () => {- // `isBranchMergedInto` fails CLOSED (`false`, not a throw) when it cannot read+ // `hasBranchMergeEvidence` fails CLOSED (`false`, not a throw) when it cannot read// a ref — right for its original caller, inverted into a false finding here.// An unresolvable ref must read as unknown, not as "carries unmerged commits".execGit.mockImplementation((args) => {@@ -374,11 +374,11 @@ describe('verifyAgentRepoState — never fires', () => {// rev-parse --verify fails => the ref could not be resolvedreturn Promise.resolve({ exitCode: 128, stdout: '', stderr: 'bad revision' });});- isBranchMergedInto.mockResolvedValue(false);+ hasBranchMergeEvidence.mockResolvedValue(false);const result = await run({ prExpected: false });- expect(isBranchMergedInto).not.toHaveBeenCalled();+ expect(hasBranchMergeEvidence).not.toHaveBeenCalled();expect(result.observed.branchMerged).toBeNull();expect(result.issues.map(i => i.code)).not.toContain(REPO_STATE_ISSUES.BRANCH_UNMERGED);expect(result.observed.unreadable).toContain('branch-merged');diff --git a/server/services/agentWorktreeCleanup.js b/server/services/agentWorktreeCleanup.jsindex e751f923a5..912c4b52be 100644--- a/server/services/agentWorktreeCleanup.js+++ b/server/services/agentWorktreeCleanup.js@@ -504,7 +504,7 @@ async function runCleanupAgentWorktree(agentId, success, { prCreation = PR_CREAT* so `refs/remotes/origin/<branch>` answers "did this agent push?" with one* local rev-parse and no network. Absent ⇒ nothing to do. (A push from some* other clone is invisible here; the repo-state audit still reports it.)- * - Merged-ness is `git.isBranchMergedInto` — the definition the branch-+ * - Merge evidence uses `git.hasBranchMergeEvidence` — the predicate the branch-* reconcile reaper and `removeWorktree` already use — so a copy the agent* amended or rebased after pushing (patch-equivalent, not an ancestor) still* counts as landed, and an unresolvable object fails closed.@@ -521,9 +521,9 @@ async function deleteMergedRemoteCopy(agentId, sourceWorkspace, branchName) {.catch(() => null);const pushedSha = tracked?.exitCode === 0 ? tracked.stdout.trim() : '';if (!pushedSha) return;- const landed = await git.isBranchMergedInto(sourceWorkspace, pushedSha, 'HEAD').catch(() => false);- if (!landed) {- emitLog('warn', `🌳 origin/${branchName} (${pushedSha.slice(0, 7)}) is not merged into the checkout that received the branch — left in place for the repo-state audit`, { agentId, branchName });+ const hasMergeEvidence = await git.hasBranchMergeEvidence(sourceWorkspace, pushedSha, 'HEAD').catch(() => false);+ if (!hasMergeEvidence) {+ emitLog('warn', `🌳 origin/${branchName} (${pushedSha.slice(0, 7)}) has no established merge evidence in the checkout that received the branch — left in place for the repo-state audit`, { agentId, branchName });return;}const pushed = await execGit(['push', `--force-with-lease=${remoteRef}:${pushedSha}`, 'origin', `:${remoteRef}`], sourceWorkspace, { ignoreExitCode: true })@@ -572,16 +572,16 @@ export async function resolveResumePointer(sourceWorkspace, branchName, worktreeconst survivingTree = !!(worktreePath && existsSync(worktreePath));const target = await git.getDefaultBranch(sourceWorkspace).catch(() => null) || 'main';// Same predicate `removeWorktree` used to decide whether to KEEP this branch, so- // the two can't disagree and orphan it. `isBranchMergedInto` (not a rev-list+ // the two can't disagree and orphan it. `hasBranchMergeEvidence` (not a rev-list// count) because a rebase/squash-merged branch has new SHAs and would otherwise// read as resumable — pointing a retry at already-landed work. Note the polarity- // flips here: preservation fails closed (keep), but resuming fails OPEN (start- // clean), because a wrong resume makes an agent build on a merged branch while a- // wrong clean start merely repeats work the branch still holds for a human.- const merged = await git.isBranchMergedInto(sourceWorkspace, branchName, target).catch(() => true);+ // flips only for a rejected call: resume starts clean on rejection, while the+ // predicate's internal probe failures still return false. The existence checks+ // below keep that negative evidence result from reviving an absent branch.+ const hasMergeEvidence = await git.hasBranchMergeEvidence(sourceWorkspace, branchName, target).catch(() => true);// Nothing survived and nothing is unmerged — the common "run finished, branch// landed, tree already reaped" shape. Bail before spending any more git calls.- if (merged && !survivingTree) return null;+ if (hasMergeEvidence && !survivingTree) return null;// How many commits the branch holds that the default branch doesn't. Only ever// consulted on one of the two mutually exclusive paths below, so it costs a@@ -592,8 +592,8 @@ export async function resolveResumePointer(sourceWorkspace, branchName, worktree// 1. Adopt the surviving tree — but only if it is actually on the branch we're// resuming; a half-cleaned or repurposed directory must not be handed over.if (survivingTree && await git.getBranch(worktreePath).catch(() => null) === branchName) {- if (!merged) {- emitLog('info', `🌳 Worktree ${worktreePath} survived on unmerged ${branchName} — a retry can adopt it`, { branchName, worktreePath });+ if (!hasMergeEvidence) {+ emitLog('info', `🌳 Worktree ${worktreePath} survived on ${branchName} without established merge evidence — a retry can adopt it`, { branchName, worktreePath });return { branchName, worktreePath };}// A merged branch reads that way for two very different reasons. Commits that@@ -612,7 +612,7 @@ export async function resolveResumePointer(sourceWorkspace, branchName, worktreereturn { branchName, worktreePath };}- if (merged) return null;+ if (hasMergeEvidence) return null;// 2. Attach a fresh worktree to the branch. Git allows a branch to be checked out// in only ONE worktree, so if a worktree is STILL on this branch, `git worktree@@ -625,8 +625,8 @@ export async function resolveResumePointer(sourceWorkspace, branchName, worktreeemitLog('info', `🌳 Branch ${branchName} is still checked out in a preserved worktree — a retry can't attach to it, so it will start clean`, { branchName });return null;}- // Confirm the branch actually exists and holds commits — `isBranchMergedInto`- // reports an ABSENT branch as unmerged, which would hand back a branch name no+ // Confirm the branch actually exists and holds commits — `hasBranchMergeEvidence`+ // returns false for an absent branch, which would hand back a branch name no// worktree can attach to.return await commitsAhead() > 0 ? { branchName, worktreePath: null } : null;}diff --git a/server/services/agentWorktreeCleanup.repoStateAudit.test.js b/server/services/agentWorktreeCleanup.repoStateAudit.test.jsindex 95e8491466..a4b6ecccdc 100644--- a/server/services/agentWorktreeCleanup.repoStateAudit.test.js+++ b/server/services/agentWorktreeCleanup.repoStateAudit.test.js@@ -29,7 +29,7 @@ vi.mock('./git.js', () => ({generatePRDescription: vi.fn(),suggestPRTitle: vi.fn(),requestCopilotReview: vi.fn(),- isBranchMergedInto: vi.fn().mockResolvedValue(true),+ hasBranchMergeEvidence: vi.fn().mockResolvedValue(true),}));vi.mock('./worktreeManager.js', () => ({removeWorktree: vi.fn().mockResolvedValue({ removed: true, warnings: [] }),diff --git a/server/services/branchReconcile.js b/server/services/branchReconcile.jsindex 87760444c1..a2ed0381a6 100644--- a/server/services/branchReconcile.js+++ b/server/services/branchReconcile.js@@ -23,7 +23,7 @@*/import { stat } from 'node:fs/promises';-import { getBranches, getDefaultBranch, isBranchMergedInto, deleteBranch } from './git.js';+import { getBranches, getDefaultBranch, hasBranchMergeEvidence, deleteBranch } from './git.js';import { execGit } from '../lib/execGit.js';import { listWorktrees, forceRemoveWorktreeDir, classifyWorktreeDirt, reapMergedWorktrees } from './worktreeManager.js';import { isAgentWorktreeId, worktreeOwnershipReason, worktreeHoldExpiresAt } from '../lib/worktreeOwnership.js';@@ -648,8 +648,8 @@ export async function reapOrphanedRemotes(repoPath, defaultBranch, { reap = falsconst reaped = [];const reported = [];for (const { branch, sha } of orphans) {- const merged = await isBranchMergedInto(repoPath, sha, defaultBranch).catch(() => false);- if (!merged) {+ const hasMergeEvidence = await hasBranchMergeEvidence(repoPath, sha, defaultBranch).catch(() => false);+ if (!hasMergeEvidence) {reported.push({ branch, reason: 'unmerged-remote-only' });continue;}@@ -767,9 +767,9 @@ export async function gatherBranchState(repoPath, { defaultBranch, activeAgentIdconst worktreeDirty = dirtyPaths.length > 0;const divergence = await gatherDivergence(repoPath, b.name, defaultBranch, dirtyPaths);// getBranches' `merged` is ancestor-based (misses squash/rebase); confirm- // the harder cases via isBranchMergedInto (covers squash + rebase). Short+ // the harder cases via hasBranchMergeEvidence (covers squash + rebase). Short// -circuit when the cheap check already proved it merged.- const isMerged = b.merged || await isBranchMergedInto(repoPath, b.name, defaultBranch);+ const hasMergeEvidence = b.merged || await hasBranchMergeEvidence(repoPath, b.name, defaultBranch);// Tip SHA is the primary cache key for a recorded SUPERSEDED verdict (see// supersededLedger.js) — a branch that moved must be re-analyzed. `null` on// failure so an unreadable tip can never match a recorded one.@@ -792,7 +792,7 @@ export async function gatherBranchState(repoPath, { defaultBranch, activeAgentId// remote (`null`) yields false — "we could not ask" must not read as// "the remote branch is gone". See the SHIPPED_CLAIM note on cleanupMerged.upstreamGone: Boolean(remoteHeads) && upstreamName !== null && !remoteHeads.has(upstreamName),- isMerged,+ isMerged: hasMergeEvidence,hasWorktree: Boolean(worktreePath),worktreePath,worktreeLocked,@@ -855,7 +855,7 @@ export function describeIdleReconcilePark(skipped = [], heldLive = []) {/*** Deterministically clean up fully-merged branches: remove the lingering* worktree, then delete the local branch. Safety gates (ALL must hold):- * 1. `isBranchMergedInto(default)` re-verified true (fail closed).+ * 1. `hasBranchMergeEvidence(default)` re-verified true (fail closed).* 2. the branch's worktree (if any) has no real uncommitted changes.* A failed gate skips the branch (with a reason) — never a force-delete of* unmerged or dirty work.@@ -867,7 +867,7 @@ export function describeIdleReconcilePark(skipped = [], heldLive = []) {* "merged branches held back" — the exact stall this reconcile exists to clear.** A shipped claim is one where all three hold, established here in order:- * 1. `stillMerged` — re-verified against the default branch just above.+ * 1. Merge evidence — re-verified against the default branch just above.* 2. `upstreamGone` — the branch was pushed and its remote ref is no longer on* origin, i.e. its PR merged with `--delete-branch`.* 3. clean worktree — the dirty gate below, which this never overrides.@@ -895,13 +895,13 @@ export async function cleanupMerged(repoPath, defaultBranch, merged, { activeAgeconst skipped = [];for (const b of merged) {// Re-verify at action time — state may have shifted since the gather.- const stillMerged = await isBranchMergedInto(repoPath, b.branch, defaultBranch);- if (!stillMerged) {+ const hasMergeEvidence = await hasBranchMergeEvidence(repoPath, b.branch, defaultBranch);+ if (!hasMergeEvidence) {skipped.push({ branch: b.branch, reason: 'not-merged-on-recheck' });continue;}// A SHIPPED claim (see SHIPPED_CLAIM above) waits out the short window instead- // of the week-long one — `stillMerged` is proven above, and retireBranch's+ // of the week-long one — merge evidence was established above, and retireBranch's// dirty gate is still ahead of the removal.const retired = await retireBranch(repoPath, b, {activeAgentIds,diff --git a/server/services/branchReconcile.test.js b/server/services/branchReconcile.test.jsindex cde64dbdb3..ee0613830d 100644--- a/server/services/branchReconcile.test.js+++ b/server/services/branchReconcile.test.js@@ -13,7 +13,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';vi.mock('./git.js', () => ({getBranches: vi.fn(),getDefaultBranch: vi.fn(async () => 'main'),- isBranchMergedInto: vi.fn(),+ hasBranchMergeEvidence: vi.fn(),deleteBranch: vi.fn(async () => ({ branch: 'x', results: { local: 'deleted' } }))}));vi.mock('../lib/execGit.js', () => ({@@ -258,7 +258,7 @@ describe('classifyBranches', () => {describe('cleanupMerged', () => {it('removes worktree + deletes branch when merged and clean', async () => {- git.isBranchMergedInto.mockResolvedValue(true);+ git.hasBranchMergeEvidence.mockResolvedValue(true);execGit.mockResolvedValue({ stdout: '', exitCode: 0 }); // clean worktreeconst res = await cleanupMerged('/repo', 'main', [{ branch: 'next/issue-2190', worktreePath: '/wt/2190' }]);expect(res.cleaned).toEqual(['next/issue-2190']);@@ -267,7 +267,7 @@ describe('cleanupMerged', () => {});it('skips when re-check says not merged (fail closed)', async () => {- git.isBranchMergedInto.mockResolvedValue(false);+ git.hasBranchMergeEvidence.mockResolvedValue(false);const res = await cleanupMerged('/repo', 'main', [{ branch: 'next/issue-2190', worktreePath: '/wt/2190' }]);expect(res.cleaned).toEqual([]);expect(res.skipped).toEqual([{ branch: 'next/issue-2190', reason: 'not-merged-on-recheck' }]);@@ -275,7 +275,7 @@ describe('cleanupMerged', () => {});it('skips when the worktree has real uncommitted changes', async () => {- git.isBranchMergedInto.mockResolvedValue(true);+ git.hasBranchMergeEvidence.mockResolvedValue(true);execGit.mockResolvedValue({ stdout: ' M server/index.js', exitCode: 0 }); // dirtyconst res = await cleanupMerged('/repo', 'main', [{ branch: 'next/issue-2196', worktreePath: '/wt/2196' }]);expect(res.cleaned).toEqual([]);@@ -285,14 +285,14 @@ describe('cleanupMerged', () => {});it('deletes a merged branch with no worktree', async () => {- git.isBranchMergedInto.mockResolvedValue(true);+ git.hasBranchMergeEvidence.mockResolvedValue(true);const res = await cleanupMerged('/repo', 'main', [{ branch: 'orphan', worktreePath: null }]);expect(res.cleaned).toEqual(['orphan']);expect(wt.forceRemoveWorktreeDir).not.toHaveBeenCalled();});it('never tears down a locked / human-claim / active-agent worktree', async () => {- git.isBranchMergedInto.mockResolvedValue(true);+ git.hasBranchMergeEvidence.mockResolvedValue(true);const activeAgentIds = new Set(['agent-abc12345']);const res = await cleanupMerged('/repo', 'main', [{ branch: 'locked-b', worktreePath: '/wt/locked', worktreeLocked: true },@@ -310,7 +310,7 @@ describe('cleanupMerged', () => {});it('reaps an ABANDONED claim worktree (merged + clean + stale age)', async () => {- git.isBranchMergedInto.mockResolvedValue(true);+ git.hasBranchMergeEvidence.mockResolvedValue(true);execGit.mockResolvedValue({ stdout: '', exitCode: 0 }); // cleanconst res = await cleanupMerged('/repo', 'main', [// 10 days old — comfortably past the 7-day STALE_CLAIM_IDLE_MS default@@ -322,7 +322,7 @@ describe('cleanupMerged', () => {});it('still protects a RECENT claim worktree even when merged + clean, and says when the hold lifts', async () => {- git.isBranchMergedInto.mockResolvedValue(true);+ git.hasBranchMergeEvidence.mockResolvedValue(true);execGit.mockResolvedValue({ stdout: '', exitCode: 0 }); // cleanconst before = Date.now();const res = await cleanupMerged('/repo', 'main', [@@ -345,7 +345,7 @@ describe('cleanupMerged', () => {const shipped = (over) => ({worktreePath: '/repo/data/cos/worktrees/claim-x', worktreeAgeMs: 2 * HOUR, upstreamGone: true, ...over});- git.isBranchMergedInto.mockResolvedValue(true);+ git.hasBranchMergeEvidence.mockResolvedValue(true);execGit.mockResolvedValue({ stdout: '', exitCode: 0 }); // cleanconst reaped = await cleanupMerged('/repo', 'main', [{ branch: 'claim/issue-0', ...shipped() }]);@@ -378,7 +378,7 @@ describe('cleanupMerged', () => {});it('omits retryAt for holds that do NOT lift on a clock', async () => {- git.isBranchMergedInto.mockResolvedValue(true);+ git.hasBranchMergeEvidence.mockResolvedValue(true);const res = await cleanupMerged('/repo', 'main', [{ branch: 'locked-b', worktreePath: '/wt/locked', worktreeLocked: true, worktreeAgeMs: 60 * 1000 },{ branch: 'active-b', worktreePath: '/repo/data/cos/worktrees/agent-abc12345', worktreeAgeMs: 60 * 1000 }@@ -447,7 +447,7 @@ describe('gatherBranchState', () => {execGh.mockResolvedValue(JSON.stringify([{ number: 2206, headRefName: 'next/issue-2199', mergeable: 'MERGEABLE', isDraft: false, url: 'u' }]));- git.isBranchMergedInto.mockResolvedValue(false);+ git.hasBranchMergeEvidence.mockResolvedValue(false);const inputs = await gatherBranchState('/repo', { defaultBranch: 'main' });const names = inputs.map((i) => i.branch);@@ -470,7 +470,7 @@ describe('gatherBranchState', () => {{ name: 'next/issue-77', isDefault: false, current: false, tracking: 'origin/next/issue-77', merged: false }]);wt.listWorktrees.mockResolvedValue([]);- git.isBranchMergedInto.mockResolvedValue(false);+ git.hasBranchMergeEvidence.mockResolvedValue(false);execGh.mockResolvedValueOnce(JSON.stringify([{ number: 77, headRefName: 'next/issue-77', mergeable: 'MERGEABLE', isDraft: false, url: 'u' }]));@@ -490,7 +490,7 @@ describe('gatherBranchState', () => {{ name: 'next/issue-88', isDefault: false, current: false, tracking: 'origin/next/issue-88', merged: false }]);wt.listWorktrees.mockResolvedValue([]);- git.isBranchMergedInto.mockResolvedValue(false);+ git.hasBranchMergeEvidence.mockResolvedValue(false);execGh.mockClear();const inputs = await gatherBranchState('/repo', { defaultBranch: 'main' });@@ -512,7 +512,7 @@ describe('gatherBranchState', () => {{ name: 'local/only', isDefault: false, current: false, tracking: null, merged: false }]);wt.listWorktrees.mockResolvedValue([]);- git.isBranchMergedInto.mockResolvedValue(false);+ git.hasBranchMergeEvidence.mockResolvedValue(false);execGit.mockImplementation(async (args) => (args[0] === 'ls-remote'? { stdout: '', stderr: "fatal: 'origin' does not appear to be a git repository", exitCode: 128 }: { stdout: '', exitCode: 0 }));@@ -734,7 +734,7 @@ describe('unreachable forge (#3358)', () => {]);wt.listWorktrees.mockResolvedValue([]);execGh.mockRejectedValue(new Error('connect: bad file descriptor'));- git.isBranchMergedInto.mockResolvedValue(false);+ git.hasBranchMergeEvidence.mockResolvedValue(false);const inputs = await gatherBranchState('/repo', { defaultBranch: 'main' });expect(inputs[0].prStateUnavailable).toBe(true);@@ -747,7 +747,7 @@ describe('unreachable forge (#3358)', () => {]);wt.listWorktrees.mockResolvedValue([]);execGh.mockResolvedValue('[]');- git.isBranchMergedInto.mockResolvedValue(false);+ git.hasBranchMergeEvidence.mockResolvedValue(false);const inputs = await gatherBranchState('/repo', { defaultBranch: 'main' });expect(inputs[0].prStateUnavailable).toBe(false);@@ -760,7 +760,7 @@ describe('unreachable forge (#3358)', () => {]);wt.listWorktrees.mockResolvedValue([]);execGh.mockRejectedValue(new Error('connect: bad file descriptor'));- git.isBranchMergedInto.mockResolvedValue(false);+ git.hasBranchMergeEvidence.mockResolvedValue(false);const res = await reconcile('/repo');// The probe passed, so the cycle ran — but the in-flight set is empty for a@@ -780,7 +780,7 @@ describe('unreachable forge (#3358)', () => {{ name: 'claim/issue-1', isDefault: false, current: false, tracking: 'origin/claim/issue-1', merged: false }]);wt.listWorktrees.mockResolvedValue([]);- git.isBranchMergedInto.mockResolvedValue(false);+ git.hasBranchMergeEvidence.mockResolvedValue(false);execGh.mockResolvedValue('[]');await reconcile('/repo');@@ -794,7 +794,7 @@ describe('unreachable forge (#3358)', () => {{ name: 'claim/issue-1', isDefault: false, current: false, tracking: 'origin/claim/issue-1', merged: false }]);wt.listWorktrees.mockResolvedValue([]);- git.isBranchMergedInto.mockResolvedValue(false);+ git.hasBranchMergeEvidence.mockResolvedValue(false);execGit.mockImplementation(async (args) => args[0] === 'ls-remote'? { stdout: 'sha\trefs/heads/claim/issue-1\n', exitCode: 0 }: { stdout: '', exitCode: 0 });@@ -817,7 +817,7 @@ describe('unreachable forge (#3358)', () => {]);wt.listWorktrees.mockResolvedValue([]);execGh.mockResolvedValue('[]');- git.isBranchMergedInto.mockResolvedValue(false);+ git.hasBranchMergeEvidence.mockResolvedValue(false);expect((await reconcile('/repo')).prStateUnavailable).toBe(false);});@@ -836,7 +836,7 @@ describe('unreachable forge (#3358)', () => {{ name: 'feature/x', isDefault: false, current: false, tracking: 'origin/feature/x', merged: true }]);wt.listWorktrees.mockResolvedValue([]);- git.isBranchMergedInto.mockResolvedValue(true);+ git.hasBranchMergeEvidence.mockResolvedValue(true);const res = await reconcile('/repo');expect(ensureForgeReachableMock).not.toHaveBeenCalled();@@ -884,7 +884,7 @@ describe('reconcile', () => {]);wt.listWorktrees.mockResolvedValue([]);execGh.mockResolvedValue('[]');- git.isBranchMergedInto.mockResolvedValue(false);+ git.hasBranchMergeEvidence.mockResolvedValue(false);const res = await reconcile('/repo');expect(res.inFlight.map((i) => i.branch)).toEqual(['claim/issue-42', 'feature/new-thing', 'scratch-thing']);@@ -910,7 +910,7 @@ describe('reconcile', () => {: { stdout: '', exitCode: 0 });// Idle for hours — past SHIPPED_CLAIM_IDLE_MS, so no live session is implied.worktreeMtimeMs = Date.now() - 4 * 60 * 60 * 1000;- git.isBranchMergedInto.mockResolvedValue(true);+ git.hasBranchMergeEvidence.mockResolvedValue(true);const res = await reconcile('/repo');expect(res.cleaned).toEqual(['claim/issue-4348']);@@ -938,7 +938,7 @@ describe('reconcile', () => {// Idle long enough that the SHORT window would have released it — so the only// thing holding it back is the unreadable remote, which is what this pins.worktreeMtimeMs = Date.now() - 4 * 60 * 60 * 1000;- git.isBranchMergedInto.mockResolvedValue(true);+ git.hasBranchMergeEvidence.mockResolvedValue(true);const res = await reconcile('/repo');expect(res.cleaned).toEqual([]);@@ -959,7 +959,7 @@ describe('reconcile', () => {// Branch-aware: only 2190 is merged (gather short-circuits it via merged:true;// this also satisfies the cleanup re-check). 2199 must stay un-merged so it// classifies IN_REVIEW rather than being swept into cleanup.- git.isBranchMergedInto.mockImplementation(async (_dir, branch) => branch === 'next/issue-2190');+ git.hasBranchMergeEvidence.mockImplementation(async (_dir, branch) => branch === 'next/issue-2190');const res = await reconcile('/repo');expect(res.cleaned).toEqual(['next/issue-2190']);@@ -979,7 +979,7 @@ describe('reconcile', () => {wt.listWorktrees.mockResolvedValue([{ path: '/repo/data/cos/worktrees/agent-live1234', branch: 'refs/heads/cos/task-y/agent-live1234' }]);- git.isBranchMergedInto.mockResolvedValue(false);+ git.hasBranchMergeEvidence.mockResolvedValue(false);execGh.mockResolvedValue(JSON.stringify([{ number: 4001, headRefName: 'cos/task-y/agent-live1234', mergeable: 'MERGEABLE', isDraft: false, url: 'u' }]));@@ -1004,7 +1004,7 @@ describe('reconcile', () => {{ name: 'cos/task-z/agent-live5678', isDefault: false, current: false, tracking: 'origin/cos/task-z/agent-live5678', merged: false }]);wt.listWorktrees.mockResolvedValue([]); // worktree already cleaned up- git.isBranchMergedInto.mockResolvedValue(false);+ git.hasBranchMergeEvidence.mockResolvedValue(false);execGh.mockResolvedValue(JSON.stringify([{ number: 4002, headRefName: 'cos/task-z/agent-live5678', mergeable: 'MERGEABLE', isDraft: false, url: 'u' }]));@@ -1022,7 +1022,7 @@ describe('reconcile', () => {wt.listWorktrees.mockResolvedValue([{ path: '/repo/data/cos/worktrees/claim-issue-42', branch: 'refs/heads/claim/issue-42' }]);- git.isBranchMergedInto.mockResolvedValue(false);+ git.hasBranchMergeEvidence.mockResolvedValue(false);execGh.mockResolvedValue(JSON.stringify([{ number: 4200, headRefName: 'claim/issue-42', mergeable: 'MERGEABLE', isDraft: false, url: 'u' }]));@@ -1047,7 +1047,7 @@ describe('reconcile', () => {wt.listWorktrees.mockResolvedValue([{ path: '/repo/data/cos/worktrees/agent-deadbeef', branch: 'refs/heads/cos/task-x/agent-deadbeef' }]);- git.isBranchMergedInto.mockResolvedValue(true);+ git.hasBranchMergeEvidence.mockResolvedValue(true);// Uncommitted work in the worktree.execGit.mockResolvedValue({ stdout: ' M server/services/thing.js\n?? server/services/newThing.js\n', exitCode: 0 });@@ -1065,7 +1065,7 @@ describe('reconcile', () => {wt.listWorktrees.mockResolvedValue([{ path: '/repo/data/cos/worktrees/agent-deadbeef', branch: 'refs/heads/cos/task-x/agent-deadbeef' }]);- git.isBranchMergedInto.mockResolvedValue(true);+ git.hasBranchMergeEvidence.mockResolvedValue(true);execGit.mockResolvedValue({ stdout: ' M server/services/thing.js\n', exitCode: 0 });const res = await reconcile('/repo', { activeAgentIds: new Set(['agent-deadbeef']) });@@ -1091,7 +1091,7 @@ describe('reconcile — cached SUPERSEDED verdicts (#3842)', () => {{ name: BRANCH, isDefault: false, current: false, tracking: 'origin/main', merged: false }]);wt.listWorktrees.mockResolvedValue([{ path: WORKTREE, branch: `refs/heads/${BRANCH}` }]);- git.isBranchMergedInto.mockResolvedValue(false);+ git.hasBranchMergeEvidence.mockResolvedValue(false);execGit.mockImplementation(async (args) => {const [cmd] = args;if (cmd === 'rev-parse') return { stdout: `${tip}\n`, exitCode: 0 };@@ -1177,7 +1177,7 @@ describe('reconcile — cached SUPERSEDED verdicts (#3842)', () => {{ name: CLAIM, isDefault: false, current: false, tracking: null, merged: false }]);wt.listWorktrees.mockResolvedValue([{ path: CLAIM_TREE, branch: `refs/heads/${CLAIM}` }]);- git.isBranchMergedInto.mockResolvedValue(false);+ git.hasBranchMergeEvidence.mockResolvedValue(false);execGit.mockImplementation(async (args) => {const [cmd] = args;if (cmd === 'rev-parse') return { stdout: 'aaaaaaa\n', exitCode: 0 };@@ -1332,7 +1332,7 @@ describe('reconcile — a worktree holding only PortOS runtime scratch', () => {{ name: BRANCH, isDefault: false, current: false, tracking: null, merged: true }]);wt.listWorktrees.mockResolvedValue([{ path: WORKTREE, branch: `refs/heads/${BRANCH}` }]);- git.isBranchMergedInto.mockResolvedValue(true);+ git.hasBranchMergeEvidence.mockResolvedValue(true);execGit.mockImplementation(async (args) => {if (args[0] === 'rev-list') return { stdout: '114\t0\n', exitCode: 0 };if (args[0] === 'status') return { stdout: porcelain, exitCode: 0 };@@ -1840,7 +1840,7 @@ describe('orphaned remote branches', () => {// shared forge and cannot be undone from here.mockRemote(lsRemote([['stale/merged', 'sha-merged']]));git.getBranches.mockResolvedValue([]);- git.isBranchMergedInto.mockResolvedValue(true);+ git.hasBranchMergeEvidence.mockResolvedValue(true);const res = await reapOrphanedRemotes('/repo', 'main');expect(res.reaped).toEqual([]);@@ -1851,7 +1851,7 @@ describe('orphaned remote branches', () => {it('deletes a merged orphan on the remote when reaping is enabled', async () => {mockRemote(lsRemote([['stale/merged', 'sha-merged']]));git.getBranches.mockResolvedValue([]);- git.isBranchMergedInto.mockResolvedValue(true);+ git.hasBranchMergeEvidence.mockResolvedValue(true);git.deleteBranch.mockResolvedValue({ branch: 'stale/merged', results: { remote: 'deleted' } });const res = await reapOrphanedRemotes('/repo', 'main', { reap: true });@@ -1884,16 +1884,16 @@ describe('orphaned remote branches', () => {// since moved past; the live SHA is the only safe thing to judge.mockRemote(lsRemote([['stale/merged', 'sha-from-ls-remote']]));git.getBranches.mockResolvedValue([]);- git.isBranchMergedInto.mockResolvedValue(true);+ git.hasBranchMergeEvidence.mockResolvedValue(true);await reapOrphanedRemotes('/repo', 'main', { reap: true });- expect(git.isBranchMergedInto).toHaveBeenCalledWith('/repo', 'sha-from-ls-remote', 'main');+ expect(git.hasBranchMergeEvidence).toHaveBeenCalledWith('/repo', 'sha-from-ls-remote', 'main');});it('never deletes an unmerged remote-only branch — it may be a peer\'s live work', async () => {mockRemote(lsRemote([['peer/in-progress', 'sha-unmerged']]));git.getBranches.mockResolvedValue([]);- git.isBranchMergedInto.mockResolvedValue(false);+ git.hasBranchMergeEvidence.mockResolvedValue(false);const res = await reapOrphanedRemotes('/repo', 'main', { reap: true });expect(res.reaped).toEqual([]);@@ -1906,7 +1906,7 @@ describe('orphaned remote branches', () => {// "leave it alone", never as "not merged, so safe to assume".mockRemote(lsRemote([['never/fetched', 'sha-missing']]));git.getBranches.mockResolvedValue([]);- git.isBranchMergedInto.mockRejectedValue(new Error('bad object'));+ git.hasBranchMergeEvidence.mockRejectedValue(new Error('bad object'));const res = await reapOrphanedRemotes('/repo', 'main', { reap: true });expect(res.reaped).toEqual([]);@@ -1937,7 +1937,7 @@ describe('orphaned remote branches', () => {it('surfaces a failed remote delete rather than claiming it was reaped', async () => {mockRemote(lsRemote([['stale/merged', 'sha-merged']]));git.getBranches.mockResolvedValue([]);- git.isBranchMergedInto.mockResolvedValue(true);+ git.hasBranchMergeEvidence.mockResolvedValue(true);git.deleteBranch.mockResolvedValue({ results: { remote: 'failed: protected branch' } });const res = await reapOrphanedRemotes('/repo', 'main', { reap: true });@@ -1957,7 +1957,7 @@ describe('orphaned remote branches', () => {]);wt.listWorktrees.mockResolvedValue([]);execGh.mockResolvedValue('[]');- git.isBranchMergedInto.mockResolvedValue(true);+ git.hasBranchMergeEvidence.mockResolvedValue(true);mockRemote(lsRemote([['left/behind', 'sha-merged'], ['main', 'sha-main']]));const res = await reconcile('/repo');diff --git a/server/services/cleanupAgentWorktree.test.js b/server/services/cleanupAgentWorktree.test.jsindex b8ded5665b..cdf27468f4 100644--- a/server/services/cleanupAgentWorktree.test.js+++ b/server/services/cleanupAgentWorktree.test.js@@ -189,7 +189,7 @@ vi.mock('./git.js', () => ({getWorktreeBranches: vi.fn().mockResolvedValue(new Set()),// Default: NOT already merged, so an ahead branch is resumable. The// rebase/squash-merged case overrides this.- isBranchMergedInto: vi.fn().mockResolvedValue(false),+ hasBranchMergeEvidence: vi.fn().mockResolvedValue(false),requestCopilotReview: vi.fn().mockResolvedValue({ success: true }),resolveForgeForRepo: vi.fn().mockResolvedValue({ cli: 'gh', env: process.env, host: 'github.com', owner: null, account: null }),parsePullRequestUrl: vi.fn((url) => {@@ -1174,7 +1174,7 @@ describe('resolveResumePointer', () => {vi.clearAllMocks();git.getDefaultBranch.mockResolvedValue('main');git.getWorktreeBranches.mockResolvedValue(new Set());- git.isBranchMergedInto.mockResolvedValue(false);+ git.hasBranchMergeEvidence.mockResolvedValue(false);existsSyncMock.mockReturnValue(false);});@@ -1182,14 +1182,14 @@ describe('resolveResumePointer', () => {// branch has NEW SHAs and still reads as "ahead" of the default branch. Pointing// a retry at it would have it build on already-merged work.it('returns null for a rebase/squash-merged branch even though it reads as ahead', async () => {- git.isBranchMergedInto.mockResolvedValue(true);+ git.hasBranchMergeEvidence.mockResolvedValue(true);git.getBranchComparison.mockResolvedValue({ ahead: 6, commits: [], stats: {} });await expect(resolveResumePointer('/repo', DEAD_BRANCH)).resolves.toBeNull();});it('fails OPEN (no resume) when the merged check errors', async () => {- git.isBranchMergedInto.mockRejectedValue(new Error('git exploded'));+ git.hasBranchMergeEvidence.mockRejectedValue(new Error('git exploded'));await expect(resolveResumePointer('/repo', DEAD_BRANCH)).resolves.toBeNull();});@@ -1264,7 +1264,7 @@ describe('resolveResumePointer', () => {// worktree survived on this branch".function scriptSurvivingTree({ merged = false, ahead = 0, branch = DEAD_BRANCH, porcelain = ' M a.js\n' } = {}) {existsSyncMock.mockReturnValue(true);- git.isBranchMergedInto.mockResolvedValue(merged);+ git.hasBranchMergeEvidence.mockResolvedValue(merged);git.getBranchComparison.mockResolvedValue({ ahead, commits: [], stats: {} });git.getBranch.mockResolvedValue(branch);git.getStatusPorcelain.mockResolvedValue(porcelain);@@ -1324,7 +1324,7 @@ describe('resolveResumePointer', () => {// The ordinary shape — run finished, branch landed, tree already reaped — must// not pay for the branch comparison (two git subprocesses, one a whole-branch diff).it('bails before the branch comparison when nothing survived and the branch is merged', async () => {- git.isBranchMergedInto.mockResolvedValue(true);+ git.hasBranchMergeEvidence.mockResolvedValue(true);await expect(resolveResumePointer('/repo', DEAD_BRANCH, DEAD_TREE)).resolves.toBeNull();expect(git.getBranchComparison).not.toHaveBeenCalled();@@ -1341,7 +1341,7 @@ describe('resolveTaskResumePatch / recordTaskResumePointer', () => {vi.clearAllMocks();git.getDefaultBranch.mockResolvedValue('main');git.getWorktreeBranches.mockResolvedValue(new Set());- git.isBranchMergedInto.mockResolvedValue(false);+ git.hasBranchMergeEvidence.mockResolvedValue(false);git.getBranchComparison.mockResolvedValue({ ahead: 2, commits: [], stats: {} });existsSyncMock.mockReturnValue(false);});@@ -1456,7 +1456,7 @@ describe('releaseRetryHold', () => {vi.clearAllMocks();git.getDefaultBranch.mockResolvedValue('main');git.getWorktreeBranches.mockResolvedValue(new Set());- git.isBranchMergedInto.mockResolvedValue(false);+ git.hasBranchMergeEvidence.mockResolvedValue(false);git.getBranchComparison.mockResolvedValue({ ahead: 2, commits: [], stats: {} });existsSyncMock.mockReturnValue(false);getTaskById.mockResolvedValue({ id: 'task-1', status: 'pending' });@@ -2132,7 +2132,7 @@ describe('cleanupAgentWorktree - remote copy of a locally merged branch', () =>// `clearAllMocks` drains calls, not once-queues — reset both mocks so a test// that stops early can never hand its leftover answers to the next one.execGitMock.mockReset().mockResolvedValue({ exitCode: 128, stdout: '', stderr: '' });- git.isBranchMergedInto.mockReset().mockResolvedValue(false);+ git.hasBranchMergeEvidence.mockReset().mockResolvedValue(false);getAgent.mockResolvedValue(mockWorktreeAgent());});afterEach(() => removeWorktree.mockResolvedValue(undefined));@@ -2142,10 +2142,10 @@ describe('cleanupAgentWorktree - remote copy of a locally merged branch', () =>execGitMock.mockResolvedValueOnce(tracking(SHA)).mockResolvedValueOnce({ exitCode: 0, stdout: '', stderr: '' });- git.isBranchMergedInto.mockResolvedValueOnce(true);+ git.hasBranchMergeEvidence.mockResolvedValueOnce(true);const warnings = await cleanupAgentWorktree('agent-1', true, {});expect(execGitMock).toHaveBeenNthCalledWith(1, ['rev-parse', '--verify', '--quiet', `refs/remotes/origin/${BRANCH}`], '/mock/workspace', { ignoreExitCode: true });- expect(git.isBranchMergedInto).toHaveBeenCalledWith('/mock/workspace', SHA, 'HEAD');+ expect(git.hasBranchMergeEvidence).toHaveBeenCalledWith('/mock/workspace', SHA, 'HEAD');expect(execGitMock).toHaveBeenNthCalledWith(2, ['push', `--force-with-lease=${REF}:${SHA}`, 'origin', `:${REF}`], '/mock/workspace', { ignoreExitCode: true });// A clean finish, not a cleanup issue — no warning, so no recovery task.expect(warnings).toEqual([]);@@ -2156,13 +2156,13 @@ describe('cleanupAgentWorktree - remote copy of a locally merged branch', () =>execGitMock.mockResolvedValueOnce(tracking(null));await cleanupAgentWorktree('agent-1', true, {});expect(execGitMock).toHaveBeenCalledTimes(1);- expect(git.isBranchMergedInto).not.toHaveBeenCalled();+ expect(git.hasBranchMergeEvidence).not.toHaveBeenCalled();});it('leaves the copy alone when the pushed tip is not merged into the checkout', async () => {mergedLocally();execGitMock.mockResolvedValueOnce(tracking(SHA));- git.isBranchMergedInto.mockResolvedValueOnce(false);+ git.hasBranchMergeEvidence.mockResolvedValueOnce(false);const warnings = await cleanupAgentWorktree('agent-1', true, {});expect(execGitMock).toHaveBeenCalledTimes(1);expect(warnings).toEqual([]);@@ -2179,7 +2179,7 @@ describe('cleanupAgentWorktree - remote copy of a locally merged branch', () =>execGitMock.mockResolvedValueOnce(tracking(SHA)).mockResolvedValueOnce({ exitCode: 1, stdout: '', stderr: ` ! [rejected] ${BRANCH} (stale info)` });- git.isBranchMergedInto.mockResolvedValueOnce(true);+ git.hasBranchMergeEvidence.mockResolvedValueOnce(true);const warnings = await cleanupAgentWorktree('agent-1', true, {});// The delete was attempted and refused — the silence is deliberate, not a skip.expect(execGitMock).toHaveBeenCalledTimes(2);@@ -2194,7 +2194,7 @@ describe('cleanupAgentWorktree - remote copy of a locally merged branch', () =>execGitMock.mockResolvedValueOnce(tracking(SHA)).mockRejectedValueOnce(new Error('spawn git ENOENT'));- git.isBranchMergedInto.mockResolvedValueOnce(true);+ git.hasBranchMergeEvidence.mockResolvedValueOnce(true);await expect(cleanupAgentWorktree('agent-1', true, {})).resolves.toEqual([]);});});diff --git a/server/services/git.js b/server/services/git.jsindex 71cc57aa5c..39be7da0d0 100644--- a/server/services/git.js+++ b/server/services/git.js@@ -1179,8 +1179,8 @@ export async function mergeBranch(dir, branchName) {}/**- * Determine whether a branch's work is fully present in `target` (e.g. main),- * covering BOTH a normal/fast-forward/no-ff merge AND a squash (or rebase) merge.+ * True means the merge probes found evidence; false means they did not establish+ * it, including missing inputs, self-comparison, unresolved refs, and probe failures.** - Normal / ff / no-ff merge: the branch tip becomes reachable from target, so* `git merge-base --is-ancestor` settles it immediately.@@ -1203,7 +1203,7 @@ export async function mergeBranch(dir, branchName) {* @param {string} target - Branch it should be merged into (e.g. 'main')* @returns {Promise<boolean>}*/-export async function isBranchMergedInto(dir, branch, target) {+export async function hasBranchMergeEvidence(dir, branch, target) {if (!branch || !target || branch === target) return false;const resolve = (ref) => execGit(['rev-parse', '--verify', `${ref}^{commit}`], dir, { ignoreExitCode: true })@@ -1243,9 +1243,9 @@ export async function isBranchMergedInto(dir, branch, target) {.catch(() => null);if (!branchTree) return false;- // Synthesize a single commit with the branch's full tree atop the merge base.+ // Write a synthetic commit object with the branch's full tree atop the merge base.// commit-tree uses the repo's configured identity; if that's unset it fails and- // we fall through to "not merged" (safe — the worktree is just preserved).+ // no merge evidence is established (the worktree is preserved).const synthesized = await execGit(['commit-tree', branchTree, '-p', mergeBase, '-m', 'merged-check-probe'], dir, { ignoreExitCode: true }).then(r => (r.exitCode === 0 ? r.stdout.trim() : null)).catch(() => null);@@ -1259,6 +1259,9 @@ export async function isBranchMergedInto(dir, branch, target) {return combinedCherry.split('\n').every(line => line.startsWith('-'));}+// Backward-compatible name for callers using the original evidence predicate.+export const isBranchMergedInto = hasBranchMergeEvidence;+/*** Checkout a remote branch that doesn't exist locally.* Creates a local tracking branch from the remote ref.diff --git a/server/services/git.test.js b/server/services/git.test.jsindex 9b7ad6c88a..869543fdc1 100644--- a/server/services/git.test.js+++ b/server/services/git.test.js@@ -286,9 +286,10 @@ describe('extractAgentSummary', () => {describe('git.js exports the helpers the agent resume path calls', () => {it('exposes every function agentWorktreeCleanup.resolveResumePointer uses', async () => {const git = await vi.importActual('./git.js');+ expect(git.isBranchMergedInto).toBe(git.hasBranchMergeEvidence);for (const name of ['getBranch', 'getStatusPorcelain', 'getBranchComparison',- 'isBranchMergedInto', 'getWorktreeBranches', 'getDefaultBranch'+ 'hasBranchMergeEvidence', 'getWorktreeBranches', 'getDefaultBranch']) {expect(typeof git[name], `git.${name} must be exported`).toBe('function');}diff --git a/server/services/repoSync.js b/server/services/repoSync.jsindex e986a7f0a9..da9a6c9077 100644--- a/server/services/repoSync.js+++ b/server/services/repoSync.js@@ -47,7 +47,7 @@ import { existsSync } from 'node:fs';import { isAbsolute, join, resolve } from 'node:path';import {execGitSafe, fetchOrigin, findActiveAgentInWorkspace, getBranch, getBranches,- getDefaultBranch, getStatusPorcelain, isBranchMergedInto, isRepo+ getDefaultBranch, getStatusPorcelain, hasBranchMergeEvidence, isRepo} from './git.js';import { getOriginInfo } from '../lib/gitRemote.js';import { mapWithConcurrency } from '../lib/mapWithConcurrency.js';@@ -414,11 +414,11 @@ async function collectRepoState(repoPath) {// CURRENT branch is always reported unmerged. Ask directly, against origin's// copy of the default branch when we have one (the local copy may not have// been fast-forwarded yet, which would read a landed branch as unmerged).- // `isBranchMergedInto` also covers squash- and rebase-merges, and returns+ // `hasBranchMergeEvidence` also covers squash- and rebase-merges, and returns// true for a branch carrying no unique commits at all (a bare pointer// someone branched and never committed on).currentBranch && currentBranch !== defaultBranch- ? isBranchMergedInto(repoPath, currentBranch, remoteDefault || defaultBranch).catch(() => false)+ ? hasBranchMergeEvidence(repoPath, currentBranch, remoteDefault || defaultBranch).catch(() => false): Promise.resolve(false)]);diff --git a/server/services/repoSync.test.js b/server/services/repoSync.test.jsindex 2d78fc7d29..46005fe866 100644--- a/server/services/repoSync.test.js+++ b/server/services/repoSync.test.js@@ -28,7 +28,7 @@ const gitMocks = {getBranches: vi.fn(async () => []),getDefaultBranch: vi.fn(async () => 'main'),getStatusPorcelain: vi.fn(async () => ''),- isBranchMergedInto: vi.fn(async () => false),+ hasBranchMergeEvidence: vi.fn(async () => false),isRepo: vi.fn(async () => true)};vi.mock('./git.js', () => gitMocks);@@ -524,7 +524,7 @@ describe('syncRepo — the argv it issues is the non-destructive form', () => {});it('updates a non-checked-out default branch with a refspec fetch git itself refuses to non-FF', async () => {- gitMocks.isBranchMergedInto.mockResolvedValue(false);+ gitMocks.hasBranchMergeEvidence.mockResolvedValue(false);arrange({current: 'feature/x',branches: [{ name: 'feature/x', current: true, tracking: 'origin/feature/x', ahead: 0, behind: 0, isDefault: false, merged: false }],@@ -539,7 +539,7 @@ describe('syncRepo — the argv it issues is the non-destructive form', () => {// will be on main by then. If the checkout is refused, a `merge --ff-only// origin/main` issued anyway would land main's commits ON the feature// branch — a real change to the wrong branch. The executor re-reads HEAD.- gitMocks.isBranchMergedInto.mockResolvedValue(true);+ gitMocks.hasBranchMergeEvidence.mockResolvedValue(true);arrange({current: 'feature/x',divergence: '2\t0',diff --git a/server/services/worktreeManager.js b/server/services/worktreeManager.jsindex ddea294caf..f49897f587 100644--- a/server/services/worktreeManager.js+++ b/server/services/worktreeManager.js@@ -876,20 +876,20 @@ export async function removeWorktree(agentId, sourceWorkspace, branchName, optio// (which deletes the LOCAL branch after pushing — the remote branch is what the// PR points at) keeps cleaning up after itself.if (!hasUnmergedCommits && options.preserveBranchWithCommits && !merged) {- const { getDefaultBranch, isBranchMergedInto } = await import('./git.js');+ const { getDefaultBranch, hasBranchMergeEvidence } = await import('./git.js');const target = await getDefaultBranch(sourceWorkspace).catch(() => null) || 'main';- // `isBranchMergedInto` — NOT a bare `rev-list --count target..branch`. A branch+ // `hasBranchMergeEvidence` — NOT a bare `rev-list --count target..branch`. A branch// whose PR was REBASE- or SQUASH-merged has new SHAs, so rev-list still reports// it ahead and we would preserve an already-landed branch and point a retry at// it. PortOS merges with `--rebase` by default, so that is the COMMON shape of// the very incident this preservation exists for ("PR merged, then reaped").- // isBranchMergedInto covers patch-equivalence (`git cherry`) and fails closed,+ // hasBranchMergeEvidence covers patch-equivalence (`git cherry`) and fails closed,// which is the polarity we want here too: unknown ⇒ keep the work.- const alreadyMerged = await isBranchMergedInto(sourceWorkspace, branchName, target).catch(() => false);- if (!alreadyMerged) {+ const hasMergeEvidence = await hasBranchMergeEvidence(sourceWorkspace, branchName, target).catch(() => false);+ if (!hasMergeEvidence) {hasUnmergedCommits = true;- console.log(`🌳 Preserving branch ${branchName} — not yet merged into ${target}, kept so a retry can resume from it`);- warnings.push(`Branch ${branchName} preserved — it holds unmerged commits a retry can resume from`);+ console.log(`🌳 Preserving branch ${branchName} — merge evidence into ${target} was not established, kept so a retry can resume from it`);+ warnings.push(`Branch ${branchName} preserved — merge evidence was not established; kept for a retry`);} else {console.log(`🌳 Branch ${branchName} is already merged into ${target} — safe to delete`);}@@ -1161,7 +1161,7 @@ export async function cleanupOrphanedWorktrees(sourceWorkspace, activeAgentIds)* changes, and honors worktree locks. A worktree is reaped only when BOTH hold:* 1. the working tree is completely clean, and* 2. every commit on the branch is already in the default branch — detected via- * `isBranchMergedInto`, which covers normal AND squash/rebase merges.+ * `hasBranchMergeEvidence`, which covers normal AND squash/rebase merges.** Because of gate (2) this works regardless of merge strategy, but a true merge* commit (see the `--merge`-preferring agent prompts) makes detection bulletproof.@@ -1215,7 +1215,7 @@ export async function reapMergedWorktrees(sourceWorkspace, {defaultBranch: knownDefaultBranch = null,dryRun = false} = {}) {- const { getDefaultBranch, isBranchMergedInto } = await import('./git.js');+ const { getDefaultBranch, hasBranchMergeEvidence } = await import('./git.js');// Refresh remote refs so "merged into origin/main" reflects the canonical state// after a `gh pr merge`. Best-effort — fall back to local refs on failure.@@ -1287,8 +1287,8 @@ export async function reapMergedWorktrees(sourceWorkspace, {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) { hold('unmerged'); continue; }+ const hasMergeEvidence = await hasBranchMergeEvidence(sourceWorkspace, branchName, target).catch(() => false);+ if (!hasMergeEvidence) { hold('unmerged'); continue; }if (dryRun) { reaped.push({ path: wt.path, branch: branchName, locked: !!wt.locked, branchDeleted: false }); continue; }diff --git a/server/services/worktreeManager.test.js b/server/services/worktreeManager.test.jsindex e3c7a02a76..16974a831d 100644--- a/server/services/worktreeManager.test.js+++ b/server/services/worktreeManager.test.js@@ -23,10 +23,10 @@ vi.mock('fs/promises', () => ({}));vi.mock('./instances.js', () => ({ ensureInstanceId: vi.fn().mockResolvedValue('instance-1') }));const getDefaultBranchMock = vi.fn().mockResolvedValue('main');-const isBranchMergedIntoMock = vi.fn().mockResolvedValue(false);+const hasBranchMergeEvidenceMock = vi.fn().mockResolvedValue(false);vi.mock('./git.js', () => ({getDefaultBranch: (...args) => getDefaultBranchMock(...args),- isBranchMergedInto: (...args) => isBranchMergedIntoMock(...args),+ hasBranchMergeEvidence: (...args) => hasBranchMergeEvidenceMock(...args),}));const {@@ -877,7 +877,7 @@ describe('removeWorktree branch preservation for resume (#3167)', () => {// Routes each git invocation this path makes to a scripted answer, keyed on the// subcommand, so a test only has to state what it cares about instead of// ordering every call. The preserve/delete decision itself comes from the- // mocked `isBranchMergedInto` (see the ./git.js mock at the top of this file).+ // mocked `hasBranchMergeEvidence` (see the ./git.js mock at the top of this file).function scriptGit({ porcelain = '' } = {}) {execGitMock.mockReset();execGitMock.mockImplementation((args) => {@@ -900,8 +900,8 @@ describe('removeWorktree branch preservation for resume (#3167)', () => {getDefaultBranchMock.mockResolvedValue('main');// mockReset (not just mockResolvedValue): the opt-in test asserts the merged// check was NOT consulted, so recorded calls must not leak in from a prior test.- isBranchMergedIntoMock.mockReset();- isBranchMergedIntoMock.mockResolvedValue(false);+ hasBranchMergeEvidenceMock.mockReset();+ hasBranchMergeEvidenceMock.mockResolvedValue(false);scriptGit();});@@ -915,10 +915,10 @@ describe('removeWorktree branch preservation for resume (#3167)', () => {});// Patch-equivalence matters here: PortOS merges with `--rebase`, so a landed- // branch has new SHAs. `isBranchMergedInto` is what sees through that — a bare+ // branch has new SHAs. `hasBranchMergeEvidence` is what sees through that — a bare// `rev-list --count` would report it ahead and preserve a merged branch forever.it('DELETES the branch once it is merged (including rebase/squash-merged)', async () => {- isBranchMergedIntoMock.mockResolvedValue(true);+ hasBranchMergeEvidenceMock.mockResolvedValue(true);await removeWorktree('agent-x', '/repo', 'cos/task-1/agent-x', {merge: false, preserveBranchWithCommits: true,@@ -928,7 +928,7 @@ describe('removeWorktree branch preservation for resume (#3167)', () => {});it('fails CLOSED — keeps the branch when the merged check cannot be determined', async () => {- isBranchMergedIntoMock.mockRejectedValue(new Error('unknown revision'));+ hasBranchMergeEvidenceMock.mockRejectedValue(new Error('unknown revision'));const result = await removeWorktree('agent-x', '/repo', 'cos/task-1/agent-x', {merge: false, preserveBranchWithCommits: true,@@ -943,7 +943,7 @@ describe('removeWorktree branch preservation for resume (#3167)', () => {expect(calledWith(['branch', '-D', 'cos/task-1/agent-x'])).toBe(true);// The resume gate never consulted the merged check for THIS branch.- expect(isBranchMergedIntoMock).not.toHaveBeenCalledWith('/repo', 'cos/task-1/agent-x', 'main');+ expect(hasBranchMergeEvidenceMock).not.toHaveBeenCalledWith('/repo', 'cos/task-1/agent-x', 'main');});// The bare "uncommitted changes detected" message left the user unable to telldiff --git a/server/services/worktreeReap.test.js b/server/services/worktreeReap.test.jsindex 72190faaca..947cc2e25c 100644--- a/server/services/worktreeReap.test.js+++ b/server/services/worktreeReap.test.js@@ -2,7 +2,7 @@* Integration tests for merge-verified worktree reaping.** These exercise REAL git (in a throwaway temp repo) rather than mirroring the- * logic inline, because the squash-merge detection in isBranchMergedInto relies+ * logic inline, because the squash-merge detection in hasBranchMergeEvidence relies* on git's own `commit-tree` + `cherry` patch-id behavior — a hand-mirrored copy* wouldn't catch git-version quirks, and that detection is the safety gate the* reaper trusts before deleting anything.@@ -22,7 +22,7 @@ import {resetGitWorktreeSandbox,SKIP_HEAVY_INTEGRATION,} from '../lib/gitTestRepo.js';-import { isBranchMergedInto } from './git.js';+import { hasBranchMergeEvidence } from './git.js';import { reapMergedWorktrees } from './worktreeManager.js';/**@@ -66,7 +66,7 @@ async function initRepo() {return { dir, safePath };}-describe.skipIf(SKIP_HEAVY_INTEGRATION)('isBranchMergedInto', () => {+describe.skipIf(SKIP_HEAVY_INTEGRATION)('hasBranchMergeEvidence', () => {let dir;let safePath;let initialHead;@@ -87,7 +87,7 @@ describe.skipIf(SKIP_HEAVY_INTEGRATION)('isBranchMergedInto', () => {await execGit(['checkout', 'main'], dir);await execGit(['merge', '--no-ff', 'feat', '--no-edit'], dir);- expect(await isBranchMergedInto(dir, 'feat', 'main')).toBe(true);+ expect(await hasBranchMergeEvidence(dir, 'feat', 'main')).toBe(true);});it('detects a squash merge (branch tip is NOT an ancestor)', async () => {@@ -102,7 +102,7 @@ describe.skipIf(SKIP_HEAVY_INTEGRATION)('isBranchMergedInto', () => {const ancestor = await execGit(['merge-base', '--is-ancestor', 'squashed', 'main'], dir, { ignoreExitCode: true });expect(ancestor.exitCode).not.toBe(0);- expect(await isBranchMergedInto(dir, 'squashed', 'main')).toBe(true);+ expect(await hasBranchMergeEvidence(dir, 'squashed', 'main')).toBe(true);});it('detects a multi-commit rebase merge after the target branch advanced', async () => {@@ -121,7 +121,7 @@ describe.skipIf(SKIP_HEAVY_INTEGRATION)('isBranchMergedInto', () => {const ancestor = await execGit(['merge-base', '--is-ancestor', 'rebased', 'main'], dir, { ignoreExitCode: true });expect(ancestor.exitCode).not.toBe(0);- expect(await isBranchMergedInto(dir, 'rebased', 'main')).toBe(true);+ expect(await hasBranchMergeEvidence(dir, 'rebased', 'main')).toBe(true);});it('returns false for an unmerged branch with unique work', async () => {@@ -129,13 +129,13 @@ describe.skipIf(SKIP_HEAVY_INTEGRATION)('isBranchMergedInto', () => {await commitFile(dir, 'pending.txt', 'wip\n', 'wip');await execGit(['checkout', 'main'], dir);- expect(await isBranchMergedInto(dir, 'pending', 'main')).toBe(false);+ expect(await hasBranchMergeEvidence(dir, 'pending', 'main')).toBe(false);});it('returns false for missing refs and self-comparison', async () => {- expect(await isBranchMergedInto(dir, 'nope', 'main')).toBe(false);- expect(await isBranchMergedInto(dir, 'main', 'nope')).toBe(false);- expect(await isBranchMergedInto(dir, 'main', 'main')).toBe(false);+ expect(await hasBranchMergeEvidence(dir, 'nope', 'main')).toBe(false);+ expect(await hasBranchMergeEvidence(dir, 'main', 'nope')).toBe(false);+ expect(await hasBranchMergeEvidence(dir, 'main', 'main')).toBe(false);});});