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
ask origin/<default> whether a worktree branch landed, not the stale local ref
[._.]/ Adam Eivy86289641e8a6
diff --git a/server/services/worktreeManager.js b/server/services/worktreeManager.jsindex a7b71b7ffd..d973e942ca 100644--- a/server/services/worktreeManager.js+++ b/server/services/worktreeManager.js@@ -736,6 +736,30 @@ async function adoptWorktreeUnlocked(agentId, sourceWorkspace, existingWorktreePreturn adopted;}+/**+ * The ref a "has this branch landed?" question should be asked against.+ *+ * NOT the local default branch. A PR merged on the forge moves ORIGIN's default+ * branch; this clone's `main` does not move until something fetches. So a branch+ * whose PR merged minutes ago reads as unmerged against the local ref, and a+ * caller that preserves on "unmerged" keeps an already-landed branch — which is+ * how a merged review-loop task was re-queued against work that had shipped.+ *+ * Refreshing first is best-effort: a fetch that fails (offline, no remote) falls+ * back to the local branch, which is strictly what the caller had before.+ *+ * @param {string} sourceWorkspace+ * @param {string} defaultBranch+ * @returns {Promise<string>} `origin/<default>` when resolvable, else `<default>`+ */+async function resolveMergeTarget(sourceWorkspace, defaultBranch) {+ await execGit(['fetch', 'origin', '--prune'], sourceWorkspace, { ignoreExitCode: true }).catch(() => {});+ const remote = await execGit(['rev-parse', '--verify', `origin/${defaultBranch}^{commit}`], sourceWorkspace, { ignoreExitCode: true })+ .then(r => (r.exitCode === 0 ? `origin/${defaultBranch}` : null))+ .catch(() => null);+ return remote || defaultBranch;+}+/*** Remove a git worktree and its associated branch.*@@ -890,7 +914,8 @@ export async function removeWorktree(agentId, sourceWorkspace, branchName, optio// PR points at) keeps cleaning up after itself.if (!hasUnmergedCommits && options.preserveBranchWithCommits && !merged) {const { getDefaultBranch, hasBranchMergeEvidence } = await import('./git.js');- const target = await getDefaultBranch(sourceWorkspace).catch(() => null) || 'main';+ const defaultBranch = await getDefaultBranch(sourceWorkspace).catch(() => null) || 'main';+ const target = await resolveMergeTarget(sourceWorkspace, defaultBranch);// `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@@ -898,6 +923,8 @@ export async function removeWorktree(agentId, sourceWorkspace, branchName, optio// the very incident this preservation exists for ("PR merged, then reaped").// hasBranchMergeEvidence covers patch-equivalence (`git cherry`) and fails closed,// which is the polarity we want here too: unknown ⇒ keep the work.+ // Asked against `resolveMergeTarget`, not the local default branch — see there+ // for why a branch merged on the forge otherwise reads as unmerged here.const hasMergeEvidence = await hasBranchMergeEvidence(sourceWorkspace, branchName, target).catch(() => false);if (!hasMergeEvidence) {hasUnmergedCommits = true;@@ -1230,16 +1257,8 @@ export async function reapMergedWorktrees(sourceWorkspace, {} = {}) {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.- await execGit(['fetch', 'origin', '--prune'], sourceWorkspace, { ignoreExitCode: true }).catch(() => {});-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))- .catch(() => null);- const target = remoteTarget || defaultBranch;+ const target = await resolveMergeTarget(sourceWorkspace, defaultBranch);const currentBranch = await execGit(['rev-parse', '--abbrev-ref', 'HEAD'], sourceWorkspace, { ignoreExitCode: true }).then(r => r.stdout.trim())diff --git a/server/services/worktreeManager.test.js b/server/services/worktreeManager.test.jsindex 849b5db042..c3c332e9c0 100644--- a/server/services/worktreeManager.test.js+++ b/server/services/worktreeManager.test.js@@ -910,10 +910,14 @@ describe('removeWorktree branch preservation for resume (#3167)', () => {// 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 `hasBranchMergeEvidence` (see the ./git.js mock at the top of this file).- function scriptGit({ porcelain = '' } = {}) {+ function scriptGit({ porcelain = '', remoteTargetResolves = true } = {}) {execGitMock.mockReset();execGitMock.mockImplementation((args) => {const [sub] = args;+ // Whether this clone has an `origin/<default>` to prefer over the local branch.+ if (sub === 'rev-parse' && args[1] === '--verify' && String(args[2]).startsWith('origin/')) {+ return Promise.resolve({ stdout: remoteTargetResolves ? 'deadbeef' : '', stderr: '', exitCode: remoteTargetResolves ? 0 : 1 });+ }if (sub === 'rev-parse' && args[1] === '--show-toplevel') {// Empty stdout → `detectedToplevel` is falsy, so removeWorktree SKIPS its// broken-worktree check rather than taking that early-return branch (which@@ -970,6 +974,30 @@ describe('removeWorktree branch preservation for resume (#3167)', () => {expect(result.warnings.join(' ')).toMatch(/preserved/i);});+ // #7653: a PR merged on the forge moves ORIGIN's default branch — this clone's+ // `main` does not move until something fetches. Asking the local ref preserved+ // an already-landed branch and re-queued its task against shipped work.+ it('refreshes and asks origin/<default>, not the stale local branch', async () => {+ scriptGit({ remoteTargetResolves: true });++ await removeWorktree('agent-x', '/repo', 'claim/issue-7625', {+ merge: false, preserveBranchWithCommits: true,+ });++ expect(calledWith(['fetch', 'origin', '--prune'])).toBe(true);+ expect(hasBranchMergeEvidenceMock).toHaveBeenCalledWith('/repo', 'claim/issue-7625', 'origin/main');+ });++ it('falls back to the local branch when origin has no copy of the default', async () => {+ scriptGit({ remoteTargetResolves: false });++ await removeWorktree('agent-x', '/repo', 'cos/task-1/agent-x', {+ merge: false, preserveBranchWithCommits: true,+ });++ expect(hasBranchMergeEvidenceMock).toHaveBeenCalledWith('/repo', 'cos/task-1/agent-x', 'main');+ });+it('is opt-in: without the flag the no-merge path still deletes an unmerged branch', async () => {await removeWorktree('agent-x', '/repo', 'cos/task-1/agent-x', { merge: false });