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

don't resume a rebase-merged branch, and name the wedged-provider reap

[._.]/ Adam Eivy1d31abb3e5e8
diff --git a/server/services/agentErrorAnalysis.js b/server/services/agentErrorAnalysis.js
index 2d7070d80c..5c2c0bee3f 100644
--- a/server/services/agentErrorAnalysis.js
+++ b/server/services/agentErrorAnalysis.js
@@ -603,6 +603,16 @@ export const COMPLETION_REASON_ANALYSES = {
message: 'Agent exceeded its maximum runtime',
suggestedFix: 'Task took longer than the configured max runtime. Break it into smaller subtasks or raise the runtime budget.'
},
+ // Distinct from the bare ceiling above: this agent was explicitly ASKED to wrap
+ // up and write its sentinel (see MAX_RUNTIME_WRAP_UP_GRACE_MS) and never did, so
+ // "raise the runtime budget" is the wrong advice — a session that can't answer a
+ // direct prompt in five minutes is wedged, not merely slow.
+ 'max-runtime-no-wrap-up': {
+ category: 'timeout',
+ actionable: false,
+ message: 'Agent did not wrap up when asked at its max runtime',
+ suggestedFix: 'The agent was asked to write its completion sentinel and did not respond within the grace window — its provider/CLI is likely wedged rather than merely slow. Check the raw transcript for a stalled request, and check for open or merged-but-uncleaned PRs it left behind.'
+ },
'command-not-found': {
category: 'spawn-error',
actionable: true,
diff --git a/server/services/agentPromptBuilder.js b/server/services/agentPromptBuilder.js
index 8c7c3a042d..29bbce757e 100644
--- a/server/services/agentPromptBuilder.js
+++ b/server/services/agentPromptBuilder.js
@@ -933,12 +933,26 @@ export function buildCompletionGuidelineBullet({
const DISCARD_WORKTREE_NOTE = 'Do NOT commit, push, or open a PR — this worktree is discarded on exit. Make any scratch edits that help you reason; only the completion sentinel is kept.';
/**
- * Is this worktree a RESUME of a previous failed agent's branch, as opposed to
- * the review-loop follow-up's PR branch? Both arrive as `existingBranch: true`,
- * but they need opposite guidance: the follow-up must push review fixes to a
- * branch a PR already points at, while a resume follows the task's ordinary
- * push/PR flow (there may be no PR yet at all). Keyed on `resumedFromAgentId`,
- * which only the resume path stamps.
+ * Is this worktree attached to a branch a PR already points at — i.e. the
+ * review-loop follow-up, whose guidance is "push review fixes here, the PR
+ * points at this branch"?
+ *
+ * Identified POSITIVELY, off the follow-up's own `reviewLoopFollowUp` marker,
+ * rather than as "any `existingBranch` worktree". `existingBranch` means only
+ * "attach to this branch" and now has two producers: the follow-up, and a retry
+ * resuming a dead agent's branch (`resumedFromAgentId`), which follows the task's
+ * ordinary push/PR flow and may have no PR at all. Keying on the marker means a
+ * THIRD producer defaults to the ordinary flow instead of silently inheriting
+ * review-fix instructions for a PR that doesn't exist.
+ */
+function isPrBranchWorktree(task, worktreeInfo) {
+ return worktreeInfo?.existingBranch === true && !!task?.metadata?.reviewLoopFollowUp;
+}
+
+/**
+ * Is this worktree a RESUME of a previous failed agent's branch? Keyed on
+ * `resumedFromAgentId`, which only the resume path stamps (see
+ * agentCompletionCleanup.js).
*/
function isResumedWorktree(task, worktreeInfo) {
return worktreeInfo?.existingBranch === true && !!task?.metadata?.resumedFromAgentId;
@@ -972,7 +986,8 @@ Before you write any code, establish what is already done:
1. \`git log --oneline ${worktreeInfo.baseBranch || 'origin/HEAD'}..HEAD\` — the commits it already made.
2. \`git status\` — anything it left uncommitted.
3. Check whether it already shipped: look for an open or merged PR for this branch
- (\`gh pr list --head ${worktreeInfo.branchName} --state all\`).
+ — \`gh pr list --head ${worktreeInfo.branchName} --state all\` on GitHub,
+ \`glab mr list --source-branch ${worktreeInfo.branchName}\` on GitLab.
Then do only what remains. If a PR is already **merged**, the work is done — go
straight to your completion step and report that. If a PR is already **open**,
@@ -1173,10 +1188,7 @@ export async function buildAgentPrompt(task, config, workspaceDir, worktreeInfo
// `pending` BEFORE this flag existed (persisted across an upgrade) are still
// recognized without a metadata migration.
const noCodeOutput = isTruthyMetaFn(task.metadata?.noCodeOutput) || !!task.metadata?.creativeDirector;
- // PR-branch guidance ("push review fixes, the PR points here") applies only to
- // the review-loop follow-up — NOT to a resume, which reuses the same
- // `existingBranch` mechanism but follows the task's ordinary push/PR flow.
- const isWorktreeOnExistingBranch = worktreeInfo?.existingBranch === true && !isResumedWorktree(task, worktreeInfo);
+ const isWorktreeOnExistingBranch = isPrBranchWorktree(task, worktreeInfo);
const worktreeSection = worktreeInfo ? `
## Git Worktree Context
You are working in an **isolated git worktree** to avoid conflicts with other agents working concurrently.
@@ -1550,9 +1562,7 @@ function buildLightContextSections(task, workspaceDir, worktreeInfo, isTruthyMet
// tasks (queued before this flag existed) are recognized without a migration.
const noCodeOutput = isTruthyMetaFn(task.metadata?.noCodeOutput) || !!task.metadata?.creativeDirector;
const isReviewLoopFollowUp = isTruthyMetaFn(task.metadata?.reviewLoopFollowUp);
- // See the matching derivation in the full prompt path: a RESUME reuses
- // `existingBranch` but must not inherit the follow-up's PR-branch guidance.
- const isWorktreeOnExistingBranch = worktreeInfo?.existingBranch === true && !isResumedWorktree(task, worktreeInfo);
+ const isWorktreeOnExistingBranch = isPrBranchWorktree(task, worktreeInfo);
// Ordered reviewer list + flags for the Review Loop (task metadata wins; else
// the install's configured Code Review Defaults threaded from buildAgentPrompt;
// else `[copilot]`). Flows as `/do:pr --review-with a,b,c [--review-stop-on-*]
diff --git a/server/services/agentPromptBuilder.test.js b/server/services/agentPromptBuilder.test.js
index 24f6dde74e..f9da8e2cf3 100644
--- a/server/services/agentPromptBuilder.test.js
+++ b/server/services/agentPromptBuilder.test.js
@@ -1226,8 +1226,12 @@ describe('buildLightContextPrompt', () => {
// sees commits that are actually pushed. This branch is selected even
// for a Claude Code CLI provider with `openPR: true`, because the PR
// already exists; opening another one would be wrong.
+ // `reviewLoopFollowUp` is what identifies this case — the PR-branch guidance
+ // keys on that marker, not on bare `existingBranch`, so the OTHER producer of
+ // `existingBranch` (a resume) can't inherit review-fix instructions for a PR
+ // that may not exist.
const prompt = buildLightContextPrompt(
- makeTask({ metadata: { openPR: true, simplify: true } }),
+ makeTask({ metadata: { openPR: true, simplify: true, reviewLoopFollowUp: true } }),
'/r',
{ branchName: 'feat-x', worktreePath: '/tmp/wt', existingBranch: true },
isTruthyMeta,
@@ -1241,6 +1245,34 @@ describe('buildLightContextPrompt', () => {
expect(prompt).not.toMatch(/the \*\*Completion\*\* section below drives the push and PR/);
});
+ it('a RESUMED worktree gets the resume briefing, not the PR-branch review-fix wording', () => {
+ // A retry attached to a dead agent's branch rides the same `existingBranch`
+ // mechanism but follows the task's ordinary push/PR flow — there may be no PR
+ // at all. It must be told what is already done instead of being told to push
+ // review fixes to a PR that doesn't exist.
+ const prompt = buildLightContextPrompt(
+ makeTask({ metadata: { openPR: true, simplify: true, resumedFromAgentId: 'agent-dead' } }),
+ '/r',
+ { branchName: 'cos/task-1/agent-dead', worktreePath: '/tmp/wt', existingBranch: true },
+ isTruthyMeta,
+ { isTui: false, providerId: 'claude-code' });
+ expect(prompt).toMatch(/## Resuming Unfinished Work/);
+ expect(prompt).toMatch(/agent-dead/);
+ expect(prompt).not.toMatch(/\*\(pre-existing PR branch\)\*/);
+ expect(prompt).not.toMatch(/review-fix commits/);
+ });
+
+ it('omits the resume briefing for an ordinary fresh worktree', () => {
+ const prompt = buildLightContextPrompt(
+ makeTask({ metadata: { openPR: true, simplify: true } }),
+ '/r',
+ { branchName: 'cos/task-1/agent-new', worktreePath: '/tmp/wt', baseBranch: 'main' },
+ isTruthyMeta,
+ { isTui: false, providerId: 'claude-code' });
+ expect(prompt).toMatch(/## Git Worktree/);
+ expect(prompt).not.toMatch(/## Resuming Unfinished Work/);
+ });
+
it('worktreeCommitGuidance: hasSlashdo + !willOpenPR emits the push-only Completion wording', () => {
// Claude Code CLI with a worktree but no PR (e.g. a managed-app task
// whose flow is "push the branch, no PR"). The agent owns its own
diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.js
index 68368525a4..576a73d422 100644
--- a/server/services/agentTuiSpawning.js
+++ b/server/services/agentTuiSpawning.js
@@ -733,13 +733,13 @@ export async function spawnTuiAgent({
// needs-manual-finish error (same recovery guidance as the merge-queue /
// review-loop idle-timeout paths — a stuck orchestrator may have left
// PRs/worktrees behind).
- const finishMaxRuntimeFailure = (detail) => {
+ const finishMaxRuntimeFailure = (detail, reason = 'max-runtime-timeout') => {
captureWorktreeDiff(cwd, agentDir).catch(() => {});
finish({
success: false,
exitCode: 124,
error: `TUI agent exceeded its max runtime of ${Math.round(tuiConfig.maxRuntimeMs / 60000)}min — ${detail} check for open or merged-but-uncleaned PRs and finish them manually.`,
- reason: 'max-runtime-timeout',
+ reason,
}).catch(err => {
emitLog('error', `Failed to finalize TUI agent ${agentId} at max-runtime: ${err.message}`, { agentId });
});
@@ -797,7 +797,10 @@ export async function spawnTuiAgent({
if (Date.now() - graceStartedAt < MAX_RUNTIME_WRAP_UP_GRACE_MS) return;
clearInterval(wrapUpTimer);
wrapUpTimer = null;
- finishMaxRuntimeFailure(`it did not wrap up within ${graceMin}min of being asked, so the provider/CLI likely hung (a stalled request keeps the working counter repainting so the idle reaper never fires);`);
+ finishMaxRuntimeFailure(
+ `it did not wrap up within ${graceMin}min of being asked, so the provider/CLI likely hung (a stalled request keeps the working counter repainting so the idle reaper never fires);`,
+ 'max-runtime-no-wrap-up',
+ );
} catch (err) {
// setInterval callback: an uncaught throw here would crash the process.
console.error(`❌ wrapUpTimer interval callback failed: ${err.message}`);
diff --git a/server/services/agentTuiSpawning.test.js b/server/services/agentTuiSpawning.test.js
index 853273e515..26b10ed5e1 100644
--- a/server/services/agentTuiSpawning.test.js
+++ b/server/services/agentTuiSpawning.test.js
@@ -882,11 +882,13 @@ describe('spawnTuiAgent runtime', () => {
vi.useRealTimers();
await completeDone;
+ // Reaped under the DISTINCT reason: it was asked to wrap up and didn't, which
+ // means a wedged provider — not "raise the runtime budget".
expect(agentLifecycle.finalizeAgent).toHaveBeenCalledWith(
expect.objectContaining({
agentId: 'agent-1',
success: false,
- completionReason: 'max-runtime-timeout',
+ completionReason: 'max-runtime-no-wrap-up',
})
);
});
@@ -961,6 +963,7 @@ describe('spawnTuiAgent runtime', () => {
vi.useRealTimers();
await completeDone;
+ // Never prodded, so this keeps the plain-ceiling reason (not no-wrap-up).
expect(agentLifecycle.finalizeAgent).toHaveBeenCalledWith(
expect.objectContaining({ success: false, completionReason: 'max-runtime-timeout' })
);
diff --git a/server/services/agentWorktreeCleanup.js b/server/services/agentWorktreeCleanup.js
index 0a712e46c2..972b2c1372 100644
--- a/server/services/agentWorktreeCleanup.js
+++ b/server/services/agentWorktreeCleanup.js
@@ -285,9 +285,10 @@ export async function cleanupAgentWorktree(agentId, success, { openPR = false, p
* the branch) so the answer reflects what's actually on disk, not what we hoped.
*
* Returns the branch name to resume, or null when there is nothing to resume —
- * no branch, or a branch that holds nothing the default branch doesn't already
- * have. A null answer means the retry should start clean, which is the correct
- * behavior for an agent that failed before committing anything.
+ * no branch, a branch that holds nothing the default branch doesn't already
+ * have, or one still checked out in a preserved worktree (unattachable). A null
+ * answer means the retry should start clean, which is the correct behavior for an
+ * agent that failed before committing anything.
*
* Deliberately checks the LOCAL branch: `removeWorktree` preserves it in place,
* and `createWorktree`'s `existingBranch` path prefers a local copy before
@@ -295,12 +296,31 @@ export async function cleanupAgentWorktree(agentId, success, { openPR = false, p
*/
export async function resolveResumeBranch(sourceWorkspace, branchName) {
if (!sourceWorkspace || !branchName) return null;
+ // Git allows a branch to be checked out in only ONE worktree, so if the dead
+ // agent's worktree is STILL on this branch, `git worktree add <path> <branch>`
+ // fails with "already checked out" and the retry can't spawn at all — worse
+ // than restarting clean. That combination is exactly what this change makes
+ // more likely: removeWorktree preserves the worktree (not just the branch)
+ // whenever the tree was dirty, so the branch stays claimed. Don't point a retry
+ // at a branch it cannot attach to.
+ const claimed = await git.getWorktreeBranches(sourceWorkspace).catch(() => null);
+ if (claimed?.has(branchName)) {
+ emitLog('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;
+ }
const target = await git.getDefaultBranch(sourceWorkspace).catch(() => null) || 'main';
- // `getBranchComparison` answers "does it exist" and "does it hold anything" in
- // one call: an absent branch makes the rev-range invalid, so the log comes back
- // empty and `ahead` is 0. A git error surfaces as null — don't claim a resume we
- // can't substantiate; the retry starting clean is the safe default, and the
- // branch (if any) is still on disk for a human.
+ // 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
+ // 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);
+ if (merged) 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
+ // worktree can attach to.
const comparison = await git.getBranchComparison(sourceWorkspace, target, branchName).catch(() => null);
return comparison?.ahead > 0 ? branchName : null;
}
diff --git a/server/services/cleanupAgentWorktree.test.js b/server/services/cleanupAgentWorktree.test.js
index 1f34d58e83..56aa501fb7 100644
--- a/server/services/cleanupAgentWorktree.test.js
+++ b/server/services/cleanupAgentWorktree.test.js
@@ -174,6 +174,12 @@ vi.mock('./git.js', () => ({
// Default: the branch is 2 commits ahead of the default branch, so
// resolveResumeBranch reports it as resumable. Tests override per case.
getBranchComparison: vi.fn().mockResolvedValue({ ahead: 2, commits: [], stats: {} }),
+ // Default: no branch is claimed by a surviving worktree, so an ahead branch is
+ // attachable. The "still checked out" test overrides this.
+ 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),
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) => {
@@ -937,6 +943,41 @@ describe('resolveResumeBranch', () => {
beforeEach(() => {
vi.clearAllMocks();
git.getDefaultBranch.mockResolvedValue('main');
+ git.getWorktreeBranches.mockResolvedValue(new Set());
+ git.isBranchMergedInto.mockResolvedValue(false);
+ });
+
+ // The incident shape: PortOS merges with `--rebase` by default, so a landed
+ // 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.getBranchComparison.mockResolvedValue({ ahead: 6, commits: [], stats: {} });
+
+ await expect(resolveResumeBranch('/repo', 'cos/task-1/agent-x')).resolves.toBeNull();
+ });
+
+ it('fails OPEN (no resume) when the merged check errors', async () => {
+ git.isBranchMergedInto.mockRejectedValue(new Error('git exploded'));
+
+ await expect(resolveResumeBranch('/repo', 'cos/task-1/agent-x')).resolves.toBeNull();
+ });
+
+ it('returns null when the branch is still checked out in a preserved worktree', async () => {
+ // A dirty tree makes removeWorktree preserve the WORKTREE too, so the branch
+ // stays claimed. `git worktree add` would fail "already checked out", which is
+ // worse for the retry than starting clean.
+ git.getWorktreeBranches.mockResolvedValue(new Set(['cos/task-1/agent-x']));
+ git.getBranchComparison.mockResolvedValue({ ahead: 5, commits: [], stats: {} });
+
+ await expect(resolveResumeBranch('/repo', 'cos/task-1/agent-x')).resolves.toBeNull();
+ });
+
+ it('still resumes when a DIFFERENT branch is checked out elsewhere', async () => {
+ git.getWorktreeBranches.mockResolvedValue(new Set(['main', 'cos/task-9/agent-z']));
+ git.getBranchComparison.mockResolvedValue({ ahead: 2, commits: [], stats: {} });
+
+ await expect(resolveResumeBranch('/repo', 'cos/task-1/agent-x')).resolves.toBe('cos/task-1/agent-x');
});
it('returns the branch when it holds commits the default branch does not', async () => {
diff --git a/server/services/cosTaskStore.js b/server/services/cosTaskStore.js
index e4fc0e8314..6e235e3fce 100644
--- a/server/services/cosTaskStore.js
+++ b/server/services/cosTaskStore.js
@@ -451,7 +451,7 @@ export async function updateTask(taskId, updates, taskType = 'user', { now = Dat
// unrelated future work, and a stale `existingBranch` would silently attach
// that fresh run to a long-merged branch. Only cleared on terminal statuses —
// a `pending` retry is exactly who needs the pointer intact.
- if (updates.status === 'completed' || updates.status === 'blocked') {
+ if (isTerminalTaskStatus(updates.status)) {
delete updatedMetadata.existingBranch;
delete updatedMetadata.resumedFromAgentId;
}
diff --git a/server/services/worktreeManager.js b/server/services/worktreeManager.js
index 783482c168..bdb8de7928 100644
--- a/server/services/worktreeManager.js
+++ b/server/services/worktreeManager.js
@@ -507,20 +507,22 @@ 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 } = await import('./git.js');
+ const { getDefaultBranch, isBranchMergedInto } = await import('./git.js');
const target = await getDefaultBranch(sourceWorkspace).catch(() => null) || 'main';
- // `??` on the count: a failed rev-list (unknown ref, detached target) must not
- // read as "0 commits" and green-light the delete. Fail closed — preserve.
- const aheadOfDefault = await execGit(['rev-list', '--count', `${target}..${branchName}`], sourceWorkspace)
- .then(r => parseInt(r.stdout.trim(), 10))
- .catch(() => null);
- if (aheadOfDefault === null || aheadOfDefault > 0) {
+ // `isBranchMergedInto` — 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,
+ // which is the polarity we want here too: unknown ⇒ keep the work.
+ const alreadyMerged = await isBranchMergedInto(sourceWorkspace, branchName, target).catch(() => false);
+ if (!alreadyMerged) {
hasUnmergedCommits = true;
- const count = aheadOfDefault === null ? 'an unknown number of' : aheadOfDefault;
- console.log(`🌳 Preserving branch ${branchName} — holds ${count} commit(s) not in ${target}, kept so a retry can resume from it`);
+ 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`);
} else {
- console.log(`🌳 Branch ${branchName} holds nothing not already in ${target} — safe to delete`);
+ console.log(`🌳 Branch ${branchName} is already merged into ${target} — safe to delete`);
}
}
if (hasUnmergedCommits) {
diff --git a/server/services/worktreeManager.test.js b/server/services/worktreeManager.test.js
index 09a0642069..e9a2d04bf3 100644
--- a/server/services/worktreeManager.test.js
+++ b/server/services/worktreeManager.test.js
@@ -21,9 +21,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);
vi.mock('./git.js', () => ({
getDefaultBranch: (...args) => getDefaultBranchMock(...args),
- isBranchMergedInto: vi.fn().mockResolvedValue(false),
+ isBranchMergedInto: (...args) => isBranchMergedIntoMock(...args),
}));
const {
@@ -593,10 +594,10 @@ describe('isPreexistingRefError (orphan-cleanup guard, #2193)', () => {
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 (the rev-list
- // count) instead of ordering every call. `revListCount` of null makes rev-list
- // FAIL, which is the fail-closed case.
- function scriptGit({ porcelain = '', revListCount = 0 } = {}) {
+ // 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).
+ function scriptGit({ porcelain = '' } = {}) {
execGitMock.mockReset();
execGitMock.mockImplementation((args) => {
const [sub] = args;
@@ -607,11 +608,6 @@ describe('removeWorktree branch preservation for resume (#3167)', () => {
return Promise.resolve({ stdout: '', stderr: '', exitCode: 0 });
}
if (sub === 'status') return Promise.resolve({ stdout: porcelain, stderr: '', exitCode: 0 });
- if (sub === 'rev-list') {
- return revListCount === null
- ? Promise.reject(new Error('unknown revision'))
- : Promise.resolve({ stdout: String(revListCount), stderr: '', exitCode: 0 });
- }
return Promise.resolve({ stdout: '', stderr: '', exitCode: 0 });
});
}
@@ -621,11 +617,14 @@ describe('removeWorktree branch preservation for resume (#3167)', () => {
beforeEach(() => {
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);
+ scriptGit();
});
- it('KEEPS the branch when it holds commits the default branch does not', async () => {
- scriptGit({ revListCount: 4 });
-
+ it('KEEPS the branch when it is not yet merged into the default branch', async () => {
const result = await removeWorktree('agent-x', '/repo', 'cos/task-1/agent-x', {
merge: false, preserveBranchWithCommits: true,
});
@@ -634,8 +633,11 @@ describe('removeWorktree branch preservation for resume (#3167)', () => {
expect(result.warnings.join(' ')).toMatch(/preserved/i);
});
- it('DELETES the branch when it holds nothing the default branch lacks', async () => {
- scriptGit({ revListCount: 0 });
+ // Patch-equivalence matters here: PortOS merges with `--rebase`, so a landed
+ // branch has new SHAs. `isBranchMergedInto` 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);
await removeWorktree('agent-x', '/repo', 'cos/task-1/agent-x', {
merge: false, preserveBranchWithCommits: true,
@@ -644,8 +646,8 @@ describe('removeWorktree branch preservation for resume (#3167)', () => {
expect(calledWith(['branch', '-D', 'cos/task-1/agent-x'])).toBe(true);
});
- it('fails CLOSED — keeps the branch when the commit count cannot be determined', async () => {
- scriptGit({ revListCount: null });
+ it('fails CLOSED — keeps the branch when the merged check cannot be determined', async () => {
+ isBranchMergedIntoMock.mockRejectedValue(new Error('unknown revision'));
const result = await removeWorktree('agent-x', '/repo', 'cos/task-1/agent-x', {
merge: false, preserveBranchWithCommits: true,
@@ -655,13 +657,11 @@ describe('removeWorktree branch preservation for resume (#3167)', () => {
expect(result.warnings.join(' ')).toMatch(/preserved/i);
});
- it('is opt-in: without the flag the no-merge path still deletes a branch with commits', async () => {
- scriptGit({ revListCount: 7 });
-
+ 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 });
expect(calledWith(['branch', '-D', 'cos/task-1/agent-x'])).toBe(true);
- // The resume gate never even ran — no rev-list against the default branch.
- expect(calledWith(['rev-list', '--count', 'main..cos/task-1/agent-x'])).toBe(false);
+ // The resume gate never consulted the merged check for THIS branch.
+ expect(isBranchMergedIntoMock).not.toHaveBeenCalledWith('/repo', 'cos/task-1/agent-x', 'main');
});
});