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 a TUI agent to wrap up before the max-runtime ceiling kills it
[._.]/ Adam Eivyc4bc2fd90e3d
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 42df380844..adb86a4f74 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -7,6 +7,9 @@## Local LLM installs- **A large Hugging Face model that failed with "context deadline exceeded" at 100% now finishes installing.** Ollama downloads the multi-gigabyte weights first and fetches the model's tiny metadata blob last; when Hugging Face's CDN takes a minute to serve that few-hundred-byte file, Ollama's internal request deadline expires and it abandons the install without writing the manifest — so tens of gigabytes of verified weights sit on disk and the model looks like it was never installed, and every retry loses the same race. PortOS now recognizes that specific failure and completes the install itself: it re-fetches the manifest and any missing *small* metadata blobs with a generous timeout, verifies every blob's SHA-256 against the manifest, clears leftover partial files, and only then writes the manifest. A missing multi-gigabyte layer, an unknown blob size, or a checksum mismatch is refused instead of papered over, so a genuinely incomplete download still reports as failed. The progress banner now says "finishing install from downloaded files…" instead of sitting at 100%.+## Chief of Staff agents++- **An agent that hits its runtime limit is now asked to wrap up before it's killed, and a retry continues its work instead of starting over.** The 3-hour ceiling is a wall clock, so it lands wherever it lands — including on an agent that had already opened and merged its pull request and was seconds from reporting done. That happened: a run was terminated 30 seconds after its PR merged, its branch was deleted, and a replacement agent began the finished work again from scratch. Now the ceiling first sends the agent a "wrap up and report now" message in its own session and waits five minutes for it to land its summary, so a run that was genuinely finishing is recorded as the success it was. If it truly is hung, it's still terminated — just five minutes later, and its branch is kept whenever it holds commits so the retry attaches to that branch and picks up where the dead run stopped. The retry is told which agent it's continuing and to check the log and PR state before writing any code, so already-shipped work isn't redone.## Usage cost reportingdiff --git a/server/lib/tuiHandshake.js b/server/lib/tuiHandshake.jsindex d1cdc48aa9..10ee15f5c0 100644--- a/server/lib/tuiHandshake.js+++ b/server/lib/tuiHandshake.js@@ -512,6 +512,50 @@ export const DEFAULT_TUI_IDLE_TIMEOUT_MS = 180000;// agent. Provider-configurable via `tuiMaxRuntimeMs`.export const DEFAULT_TUI_MAX_RUNTIME_MS = 3 * 60 * 60 * 1000;+// Grace window opened when the max-runtime ceiling fires, BEFORE the agent is+// reaped. The ceiling above is a wall-clock deadline, so it lands wherever it+// lands — including on an agent that is seconds from writing `.agent-done`.+// Measured (2026-07-27, agent-d2ae0352): its PR merged at 01:32:29 and the+// max-runtime timer killed it at 01:32:59 — 30 SECONDS later. The run was+// complete; it just hadn't written the sentinel yet. The kill deleted the+// worktree, and CoS re-dispatched the task to a fresh agent that started the+// (already-shipped) work over from scratch.+//+// So instead of reaping on the deadline, we PROD the agent — paste a "wrap up+// and write your sentinel now" message into its live TUI (the same+// bracketed-paste channel `sendBtwToAgent` uses) — and keep polling for the+// sentinel for this long before failing. An agent that was genuinely finishing+// gets to land its summary and finalize as a SUCCESS; a truly hung one is+// unaffected and still reaped, just this much later. 5 minutes covers a+// Claude Code turn that has to finish a tool call, run its completion workflow,+// and write the file, without meaningfully loosening the ceiling.+export const MAX_RUNTIME_WRAP_UP_GRACE_MS = 5 * 60 * 1000;++/**+ * The wrap-up prod pasted into a TUI agent's session when its max-runtime+ * ceiling fires. Deliberately imperative and short: the agent is mid-turn on a+ * provider that may itself be slow, so the message has to be actionable in one+ * read. It names the sentinel path convention rather than an absolute path —+ * the agent already knows its own workspace from its system prompt.+ *+ * `graceMs` is interpolated so the deadline the agent is told matches the one+ * actually enforced (a drift here would tell the agent it has more time than it+ * has, and it would be reaped mid-wrap-up).+ */+export function buildWrapUpProdMessage(graceMs = MAX_RUNTIME_WRAP_UP_GRACE_MS) {+ const minutes = Math.max(1, Math.round(graceMs / 60000));+ return [+ `STOP — you have hit your maximum runtime and will be terminated in ${minutes} minute(s).`,+ '',+ 'If your work is already shipped (PR opened/merged, or changes committed and pushed),',+ 'write your `.agent-done` sentinel in your workspace root RIGHT NOW with a short summary',+ 'so this run is recorded as a success. Do not start anything new.',+ '',+ 'If the work is NOT shipped, commit whatever is worth keeping to your branch, push it,',+ 'and then write `.agent-done` describing exactly what is done and what is left.',+ ].join('\n');+}+// Extended idle threshold applied ONLY while a `/do:next --swarm` orchestrator// is in its Phase C serialized merge queue (issue #2074). Merging PRs one at a// time makes each subsequent PR rebase onto the new `main` and re-run requireddiff --git a/server/services/agentCompletionCleanup.js b/server/services/agentCompletionCleanup.jsindex 6607a418ac..5203d22407 100644--- a/server/services/agentCompletionCleanup.js+++ b/server/services/agentCompletionCleanup.js@@ -27,7 +27,7 @@ import * as jiraService from './jira.js';import * as git from './git.js';import { isTruthyMeta } from './agentState.js';import { resolveReviewLoopOptions } from './codeReview.js';-import { cleanupAgentWorktree, spawnMergeRecoveryTask } from './agentWorktreeCleanup.js';+import { cleanupAgentWorktree, spawnMergeRecoveryTask, resolveResumeBranch } from './agentWorktreeCleanup.js';import { resolvePrCompletion } from '../lib/prDisposition.js';import { canTypeSlashCommands } from '../lib/slashdoInvocation.js';@@ -338,6 +338,48 @@ export async function runAgentCompletionCleanup({ agentId, task, agent, effectivoriginalTask: task});+ // A failed agent whose branch survived cleanup with commits on it (see+ // `preserveBranchWithCommits` in agentWorktreeCleanup.js) leaves real work+ // behind. Record that branch on the TASK so its retry attaches a worktree to+ // it and RESUMES rather than restarting from scratch — the behavior the+ // agent-d2ae0352 incident exposed, where a run reaped 30s after its PR merged+ // was re-dispatched to a fresh agent that began the shipped work over.+ //+ // Written here (not in cleanupAgentWorktree) because this is where the task+ // record is in hand, and AFTER cleanup so it reflects the branch that actually+ // survived. `resolveResumeBranch` returns null when there's nothing to resume,+ // in which case we leave the metadata untouched and the retry starts clean.+ // Only for a task that is actually going to RETRY. `finalizeAgent` has already+ // written the failure verdict by now, so the persisted status distinguishes a+ // `pending` retry (wants the pointer) from a `blocked` task that exhausted its+ // budget and is waiting on a human (a pointer there would be dead metadata+ // that `updateTask` has to strip again on the next terminal write).+ if (!effectiveSuccess && task?.id) {+ const { getTaskById, getAgent: getAgentForBranch } = await import('./cos.js');+ const persisted = await getTaskById(task.id).catch(() => null);+ const willRetry = (persisted?.status ?? 'pending') === 'pending';+ const cleanedAgent = willRetry ? await getAgentForBranch(agentId).catch(() => null) : null;+ const { sourceWorkspace, worktreeBranch } = cleanedAgent?.metadata || {};+ const resumeBranch = await resolveResumeBranch(sourceWorkspace, worktreeBranch).catch(err => {+ emitLog('warn', `Failed to resolve resume branch for ${agentId}: ${err.message}`, { agentId });+ return null;+ });+ if (resumeBranch) {+ // `existingBranch` is the flag agentWorkspacePrep already honors to attach+ // a worktree to a pre-existing branch (the review-loop follow-up path uses+ // it), so a retry needs no new plumbing to resume. `resumedFromAgentId`+ // records which run's work is being continued, for the prompt + postmortems.+ await updateTask(task.id, {+ metadata: { existingBranch: resumeBranch, resumedFromAgentId: agentId }+ }, task.taskType || 'user').catch(err => {+ emitLog('warn', `Failed to record resume branch for task ${task.id}: ${err.message}`, { taskId: task.id, agentId });+ });+ emitLog('info', `🔁 Task ${task.id} will resume from ${resumeBranch} (work left by ${agentId}) instead of restarting`, {+ taskId: task.id, agentId, branchName: resumeBranch+ });+ }+ }+if (cleanupWarnings?.length > 0) {const { getAgent: getAgentForResult } = await import('./cos.js');const currentAgent = await getAgentForResult(agentId).catch(() => null);diff --git a/server/services/agentPromptBuilder.js b/server/services/agentPromptBuilder.jsindex b5f4a35b3f..8c7c3a042d 100644--- a/server/services/agentPromptBuilder.js+++ b/server/services/agentPromptBuilder.js@@ -932,6 +932,55 @@ export function buildCompletionGuidelineBullet({// `discardWorktree` in agentWorktreeCleanup.js).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.+ */+function isResumedWorktree(task, worktreeInfo) {+ return worktreeInfo?.existingBranch === true && !!task?.metadata?.resumedFromAgentId;+}++/**+ * Resume banner for a retry attached to the branch a PREVIOUS failed agent left+ * behind (`metadata.existingBranch` + `resumedFromAgentId`, stamped by+ * agentCompletionCleanup.js when a failed run's branch survived cleanup with+ * commits on it).+ *+ * Without this the retry sees an ordinary worktree that just happens to have+ * commits on it and redoes work that is already done — the failure mode the+ * agent-d2ae0352 incident exposed (reaped 30s after its PR merged; the+ * replacement agent started the shipped work over). Telling it to read the log+ * FIRST is the whole point: the prior run may have gone as far as opening or even+ * merging a PR, in which case there is nothing left to build.+ *+ * Returns '' when this isn't a resume, so callers can interpolate unconditionally.+ */+export function buildResumeSection(task, worktreeInfo) {+ if (!isResumedWorktree(task, worktreeInfo)) return '';+ const priorAgentId = task.metadata.resumedFromAgentId;+ return `+## Resuming Unfinished Work — Read This First+A previous agent (\`${priorAgentId}\`) worked this same task and did NOT finish cleanly+(it hung, timed out, or was terminated). **Its commits are already on your branch**+\`${worktreeInfo.branchName}\` — you are continuing its run, not starting over.++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\`).++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**,+finish/land that PR rather than opening a second one. Do NOT redo completed work,+and do NOT revert its commits unless they are actually wrong.+`;+}+/*** Completion block for a **programmatic-output** (throwaway-worktree) task: the* agent reasons in a worktree that is discarded on exit, so it must NOT commit,@@ -1124,7 +1173,10 @@ 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;- const isWorktreeOnExistingBranch = worktreeInfo?.existingBranch === true;+ // 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 worktreeSection = worktreeInfo ? `## Git Worktree ContextYou are working in an **isolated git worktree** to avoid conflicts with other agents working concurrently.@@ -1139,7 +1191,7 @@ ${worktreeInfo.baseBranch ? `- **Based on**: \`${worktreeInfo.baseBranch}\` (lat: isWorktreeOnExistingBranch? 'Commit and **push** any review-fix commits to this branch — the PR points at it, so pushed commits are how Copilot sees your fixes. Use `git pull --rebase` before pushing if needed.': `Commit your changes to this branch.${willOpenPR ? ' When your task completes, the system will push this branch and open a pull request against the default branch — do NOT push or open a PR yourself.' : ' Your commits will be automatically merged back to the main development branch when your task completes.'}`} Do NOT manually switch branches or modify the worktree configuration.-` : '';+${buildResumeSection(task, worktreeInfo)}` : '';// Build pipeline context section if this is a pipeline stageconst pipelineCtx = task.metadata?.pipeline;@@ -1498,7 +1550,9 @@ 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);- const isWorktreeOnExistingBranch = worktreeInfo?.existingBranch === true;+ // 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);// 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-*]@@ -1575,7 +1629,10 @@ function buildLightContextSections(task, workspaceDir, worktreeInfo, isTruthyMetworktreeInfo.baseBranch ? `- **Based on**: \`${worktreeInfo.baseBranch}\`` : null,'',worktreeCommitGuidance({ isTui, hasSlashdo, isWorktreeOnExistingBranch, willOpenPR, discardWorktree }),- 'Do NOT manually switch branches or modify the worktree configuration.'+ 'Do NOT manually switch branches or modify the worktree configuration.',+ // Resuming a previous failed agent's branch: establish what's already done+ // before writing code (see buildResumeSection). '' when not a resume.+ buildResumeSection(task, worktreeInfo) || null].filter(Boolean).join('\n'));}diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.jsindex 65ca45fa5c..68368525a4 100644--- a/server/services/agentTuiSpawning.js+++ b/server/services/agentTuiSpawning.js@@ -29,6 +29,8 @@ import {DEFAULT_TUI_PROMPT_DELAY_MS,DEFAULT_TUI_IDLE_TIMEOUT_MS,DEFAULT_TUI_MAX_RUNTIME_MS,+ MAX_RUNTIME_WRAP_UP_GRACE_MS,+ buildWrapUpProdMessage,MERGE_QUEUE_IDLE_TIMEOUT_MS,REVIEW_LOOP_IDLE_TIMEOUT_MS,READY_POLL_INTERVAL_MS,@@ -343,6 +345,10 @@ export async function spawnTuiAgent({// ticking), this bounds the total run so a hung provider/CLI can't run// unbounded. See DEFAULT_TUI_MAX_RUNTIME_MS for the incident.let maxRuntimeTimer = null;+ // Poll driving the wrap-up grace window that the max-runtime ceiling opens+ // instead of reaping immediately (see MAX_RUNTIME_WRAP_UP_GRACE_MS). Cleared+ // in finish() alongside every other timer.+ let wrapUpTimer = null;const streamingStrip = createStreamingAnsiStripper();@@ -361,9 +367,15 @@ export async function spawnTuiAgent({// finalize chokepoint); idempotent via `sentinelIngested` so it reads at most// once. Capped at 4 KB so an agent that pasted the whole diff into the// sentinel can't blow up the record.+ // Has the agent written its completion sentinel? One predicate for every path+ // that asks (the 2s watcher, the max-runtime salvage, the wrap-up grace poll,+ // and ingestDoneSentinel) so "the run finished" can't mean subtly different+ // things in four places.+ const sentinelPresent = () => !!doneSentinelPath && existsSync(doneSentinelPath);+const ingestDoneSentinel = async () => {if (sentinelIngested) return;- if (!doneSentinelPath || !existsSync(doneSentinelPath)) return;+ if (!sentinelPresent()) return;sentinelIngested = true;const contents = await readFile(doneSentinelPath, 'utf8').catch(err => {console.error(`❌ ingestDoneSentinel readFile failed: ${err.message}`);@@ -393,6 +405,7 @@ export async function spawnTuiAgent({if (pasteVerifyTimer) { clearInterval(pasteVerifyTimer); pasteVerifyTimer = null; }if (submitEnterTimer) { clearInterval(submitEnterTimer); submitEnterTimer = null; }if (maxRuntimeTimer) { clearTimeout(maxRuntimeTimer); maxRuntimeTimer = null; }+ if (wrapUpTimer) { clearInterval(wrapUpTimer); wrapUpTimer = null; }// Release the post-paste accumulator even when finalize fires mid-paste-// window. The pasteEnterTimer's own cleanup path nulls this too, but if// finalize comes from elsewhere (shell-exit, command-not-found, user@@ -714,6 +727,84 @@ export async function spawnTuiAgent({// codex is still booting its MCP servers).let firstPasteStartedAt = null;+ // Reap the run as a max-runtime failure. Shared by the wrap-up grace window's+ // expiry and its own "session already died" branch so both produce the same+ // record: uncommitted work captured for post-mortem, then a+ // 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) => {+ 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',+ }).catch(err => {+ emitLog('error', `Failed to finalize TUI agent ${agentId} at max-runtime: ${err.message}`, { agentId });+ });+ };++ // Max-runtime wrap-up grace: prod the agent to land its sentinel, then watch+ // for it before reaping (see MAX_RUNTIME_WRAP_UP_GRACE_MS). The prod goes in+ // over the same bracketed-paste + delayed-Enter channel `sendBtwToAgent` uses,+ // so from the agent's side it is indistinguishable from the user typing it.+ //+ // Success here finalizes through the ordinary sentinel path — we do NOT call+ // finish() ourselves on the happy path, because the 2s doneSentinelTimer is+ // still running and owns that transition; racing it would just be a second+ // caller into the same `finalized` guard. This poll exists to bound the WAIT+ // and to reap when the prod doesn't work.+ const startWrapUpGrace = () => {+ if (finalized || wrapUpTimer) return;+ // A dead session can't be prodded — nothing will ever write the sentinel, so+ // skip the grace window entirely rather than idling out the full 5min.+ if (!sessionId || !shellService.getSession(sessionId)) {+ finishMaxRuntimeFailure('the TUI session was already gone, so it could not be asked to wrap up;');+ return;+ }+ const graceMin = Math.round(MAX_RUNTIME_WRAP_UP_GRACE_MS / 60000);+ appendLine(`⏳ Max runtime reached — asking the agent to wrap up and write its sentinel (${graceMin}min grace)`);+ emitLog('warn', `TUI agent ${agentId} hit max runtime — prodding it to wrap up with ${graceMin}min of grace before reaping`, { agentId, phase: 'wrap-up' });+ updateAgent(agentId, { metadata: { phase: 'wrap-up' } }).catch(err => {+ emitLog('warn', `Failed to mark TUI agent ${agentId} as wrapping up: ${err.message}`, { agentId });+ });++ shellService.writeToSession(sessionId, `\x1b[200~${buildWrapUpProdMessage(MAX_RUNTIME_WRAP_UP_GRACE_MS)}\x1b[201~`);+ // Submit with the same repeated-Enter helper the initial prompt uses — a+ // single `\r` can be swallowed while the TUI reflows the paste, and a prod+ // that never submits is a prod that never happened. Clear any prior+ // submit-Enter interval first: hours after submission the prompt's own is+ // long finished, but overwriting a live handle would leak it past finish().+ if (submitEnterTimer) clearInterval(submitEnterTimer);+ submitEnterTimer = scheduleSubmitEnters(+ () => shellService.writeToSession(sessionId, '\r'),+ () => finalized,+ );++ const graceStartedAt = Date.now();+ wrapUpTimer = setInterval(() => {+ try {+ if (finalized) { clearInterval(wrapUpTimer); wrapUpTimer = null; return; }+ // The sentinel landed — the prod worked. Let the doneSentinelTimer+ // finalize it as `agent-signaled-done`; just stop the grace clock.+ if (sentinelPresent()) {+ clearInterval(wrapUpTimer);+ wrapUpTimer = null;+ appendLine(`✅ Agent wrapped up within the max-runtime grace window`);+ return;+ }+ 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);`);+ } catch (err) {+ // setInterval callback: an uncaught throw here would crash the process.+ console.error(`❌ wrapUpTimer interval callback failed: ${err.message}`);+ }+ }, DONE_POLL_INTERVAL_MS);+ };+const sendPrompt = async (reason) => {if (finalized || promptSentAt) return;promptSentAt = Date.now();@@ -778,26 +869,18 @@ export async function spawnTuiAgent({// success — mirrors the one-shot runner's response-file salvage. The// 2s doneSentinelTimer normally catches this first; this covers the// boundary where it lands right at the deadline.- const salvaged = doneSentinelPath && existsSync(doneSentinelPath);- if (salvaged) {+ if (sentinelPresent()) {finish({ success: true, exitCode: 0, reason: 'max-runtime-sentinel' }).catch(err => {emitLog('error', `Failed to finalize TUI agent ${agentId} at max-runtime salvage: ${err.message}`, { agentId });});return;}- // Capture any uncommitted work for post-mortem before cleanup, then- // fail with a needs-manual-finish message — a stuck orchestrator may- // have left PRs/worktrees behind (same recovery guidance as the- // merge-queue/review-loop idle-timeout paths).- captureWorktreeDiff(cwd, agentDir).catch(() => {});- finish({- success: false,- exitCode: 124,- error: `TUI agent exceeded its max runtime of ${Math.round(tuiConfig.maxRuntimeMs / 60000)}min — the provider/CLI likely hung (a stalled request keeps the working counter repainting so the idle reaper never fires); check for open or merged-but-uncleaned PRs and finish them manually.`,- reason: 'max-runtime-timeout',- }).catch(err => {- emitLog('error', `Failed to finalize TUI agent ${agentId} at max-runtime: ${err.message}`, { agentId });- });+ // No sentinel yet — but a wall-clock deadline lands wherever it lands,+ // including on an agent seconds from writing one (see+ // MAX_RUNTIME_WRAP_UP_GRACE_MS for the measured 30s miss). PROD it to+ // wrap up and keep watching for the sentinel through the grace window+ // before reaping. Only then does this become a real failure.+ startWrapUpGrace();}, tuiConfig.maxRuntimeMs);}};diff --git a/server/services/agentTuiSpawning.test.js b/server/services/agentTuiSpawning.test.jsindex b4cc63a4a9..853273e515 100644--- a/server/services/agentTuiSpawning.test.js+++ b/server/services/agentTuiSpawning.test.js@@ -172,6 +172,7 @@ import * as agentErrorAnalysis from './agentErrorAnalysis.js';import * as cosAgents from './cosAgents.js';import * as gitService from './git.js';import { activeAgents, userTerminatedAgents } from './agentState.js';+import { MAX_RUNTIME_WRAP_UP_GRACE_MS } from '../lib/tuiHandshake.js';describe('agent TUI spawning', () => {it('builds a codex TUI command without a model flag for the configured-default sentinel', () => {@@ -867,6 +868,17 @@ describe('spawnTuiAgent runtime', () => {await vi.advanceTimersByTimeAsync(31000);await flushMicrotasks();+ // The ceiling PRODS rather than reaping (#3167): it pastes a wrap-up message+ // and opens a grace window, so the agent is NOT finalized yet.+ expect(agentLifecycle.finalizeAgent).not.toHaveBeenCalled();+ expect(shellService.writeToSession).toHaveBeenCalledWith(+ SESSION_ID, expect.stringContaining('you have hit your maximum runtime')+ );++ // No sentinel ever appears → the grace window expires → NOW it reaps.+ await vi.advanceTimersByTimeAsync(MAX_RUNTIME_WRAP_UP_GRACE_MS + 2000);+ await flushMicrotasks();+vi.useRealTimers();await completeDone;@@ -879,6 +891,81 @@ describe('spawnTuiAgent runtime', () => {);});+ // The whole point of the grace window: an agent that was SECONDS from writing+ // its sentinel when the ceiling landed must finalize as a SUCCESS, not be+ // reaped. This is the agent-d2ae0352 shape (PR merged 01:32:29, killed+ // 01:32:59) that made a fresh agent redo already-shipped work.+ it('max-runtime: an agent that wraps up during the grace window finalizes as success', async () => {+ let resolveComplete;+ const completeDone = new Promise((r) => { resolveComplete = r; });+ vi.mocked(agentLifecycle.finalizeAgent).mockImplementation(async () => { resolveComplete(); });++ runSpawn({ tuiConfig: { ...defaultTuiConfig, idleTimeoutMs: 600000, maxRuntimeMs: 30000 } });+ await flushMicrotasks();++ await capturedOnData(Buffer.from('Codex booting...\n'));+ await flushMicrotasks();+ await vi.advanceTimersByTimeAsync(2000);+ await flushMicrotasks();+ await capturedOnData(Buffer.from('do the thing\n'));+ await flushMicrotasks();+ await vi.advanceTimersByTimeAsync(3600);+ await flushMicrotasks();++ // Ceiling fires → prod + grace window, no finalize.+ await vi.advanceTimersByTimeAsync(31000);+ await flushMicrotasks();+ expect(agentLifecycle.finalizeAgent).not.toHaveBeenCalled();++ // The prod works: the agent writes .agent-done well inside the grace window.+ vi.mocked(existsSync).mockReturnValue(true);+ await vi.advanceTimersByTimeAsync(4000);+ await flushMicrotasks();++ vi.useRealTimers();+ await completeDone;++ // Finalized as a SUCCESS via the ordinary sentinel path — never reaped.+ expect(agentLifecycle.finalizeAgent).toHaveBeenCalledWith(+ expect.objectContaining({ agentId: 'agent-1', success: true })+ );+ expect(agentLifecycle.finalizeAgent).not.toHaveBeenCalledWith(+ expect.objectContaining({ completionReason: 'max-runtime-timeout' })+ );+ });++ // A dead session can't be prodded, so the grace window is pointless — reap+ // immediately rather than idling the full window for a message nobody reads.+ it('max-runtime: reaps immediately (no grace) when the TUI session is already gone', async () => {+ let resolveComplete;+ const completeDone = new Promise((r) => { resolveComplete = r; });+ vi.mocked(agentLifecycle.finalizeAgent).mockImplementation(async () => { resolveComplete(); });++ runSpawn({ tuiConfig: { ...defaultTuiConfig, idleTimeoutMs: 600000, maxRuntimeMs: 30000 } });+ await flushMicrotasks();++ await capturedOnData(Buffer.from('Codex booting...\n'));+ await flushMicrotasks();+ await vi.advanceTimersByTimeAsync(2000);+ await flushMicrotasks();+ await capturedOnData(Buffer.from('do the thing\n'));+ await flushMicrotasks();+ await vi.advanceTimersByTimeAsync(3600);+ await flushMicrotasks();++ // Session died before the ceiling landed.+ vi.mocked(shellService.getSession).mockReturnValue(null);+ await vi.advanceTimersByTimeAsync(31000);+ await flushMicrotasks();++ vi.useRealTimers();+ await completeDone;++ expect(agentLifecycle.finalizeAgent).toHaveBeenCalledWith(+ expect.objectContaining({ success: false, completionReason: 'max-runtime-timeout' })+ );+ });+// ── 1d. A written .agent-done sentinel is never overridden by a FAILURE reap ─// If the agent wrote .agent-done, the run truly finished — the max-runtime// ceiling firing would be a false failure. The 2s sentinel poll normallydiff --git a/server/services/agentWorktreeCleanup.js b/server/services/agentWorktreeCleanup.jsindex 8e3f44708a..0a712e46c2 100644--- a/server/services/agentWorktreeCleanup.js+++ b/server/services/agentWorktreeCleanup.js@@ -265,7 +265,13 @@ export async function cleanupAgentWorktree(agentId, success, { openPR = false, pagentId, branchName: worktreeBranch, merge: shouldMerge});- const result = await removeWorktree(agentId, sourceWorkspace, worktreeBranch, { merge: shouldMerge }).catch(err => {+ const result = await removeWorktree(agentId, sourceWorkspace, worktreeBranch, {+ merge: shouldMerge,+ // A FAILED agent's branch is the only record of what it got done. Keep it when+ // it holds commits so the task's retry can attach to it and resume rather than+ // redo the work (see resolveResumeBranch below + removeWorktree's flag docs).+ preserveBranchWithCommits: !success,+ }).catch(err => {emitLog('warn', `🌳 Worktree cleanup failed for ${agentId}: ${err.message}`, { agentId });return { warnings: [`Worktree cleanup failed: ${err.message}`] };});@@ -273,6 +279,32 @@ export async function cleanupAgentWorktree(agentId, success, { openPR = false, preturn warnings;}+/**+ * Does a failed agent's branch still exist with commits a retry should resume+ * from? Called at completion time (after cleanup has decided whether to preserve+ * 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.+ *+ * Deliberately checks the LOCAL branch: `removeWorktree` preserves it in place,+ * and `createWorktree`'s `existingBranch` path prefers a local copy before+ * falling back to `origin/<branch>`, so a local-only branch resumes fine.+ */+export async function resolveResumeBranch(sourceWorkspace, branchName) {+ if (!sourceWorkspace || !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.+ const comparison = await git.getBranchComparison(sourceWorkspace, target, branchName).catch(() => null);+ return comparison?.ahead > 0 ? branchName : null;+}+/*** Spawn an internal follow-up task that drives the ordered multi-reviewer* review-and-fix loop on the just-created PR until the configured reviewer chaindiff --git a/server/services/cleanupAgentWorktree.test.js b/server/services/cleanupAgentWorktree.test.jsindex 178cf18b4a..1f34d58e83 100644--- a/server/services/cleanupAgentWorktree.test.js+++ b/server/services/cleanupAgentWorktree.test.js@@ -171,6 +171,9 @@ vi.mock('./git.js', () => ({generatePRDescription: vi.fn(),suggestPRTitle: vi.fn(),deleteBranch: vi.fn().mockResolvedValue(undefined),+ // 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: {} }),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) => {@@ -195,6 +198,7 @@ vi.mock('./runner.js', () => ({// --- Import the function under test and the mocked dependencies ---import { cleanupAgentWorktree, spawnMergeRecoveryTask, spawnReviewLoopFollowUp } from './subAgentSpawner.js';+import { resolveResumeBranch } from './agentWorktreeCleanup.js';import { getAgent, addTask } from './cos.js';import { removeWorktree } from './worktreeManager.js';import * as git from './git.js';@@ -300,7 +304,7 @@ describe('cleanupAgentWorktree - openPR path', () => {expect(git.push).not.toHaveBeenCalled();expect(git.createPR).not.toHaveBeenCalled();- expect(removeWorktree).toHaveBeenCalledWith('agent-1', '/mock/workspace', 'cos/task-abc123', { merge: true });+ expect(removeWorktree).toHaveBeenCalledWith('agent-1', '/mock/workspace', 'cos/task-abc123', { merge: true, preserveBranchWithCommits: false });});it('should use auto-merge path when openPR is not provided (defaults to false)', async () => {@@ -308,7 +312,7 @@ describe('cleanupAgentWorktree - openPR path', () => {expect(git.push).not.toHaveBeenCalled();expect(git.createPR).not.toHaveBeenCalled();- expect(removeWorktree).toHaveBeenCalledWith('agent-1', '/mock/workspace', 'cos/task-abc123', { merge: true });+ expect(removeWorktree).toHaveBeenCalledWith('agent-1', '/mock/workspace', 'cos/task-abc123', { merge: true, preserveBranchWithCommits: false });});it('should skip PR flow when openPR is true but success is false', async () => {@@ -316,8 +320,10 @@ describe('cleanupAgentWorktree - openPR path', () => {expect(git.push).not.toHaveBeenCalled();expect(git.createPR).not.toHaveBeenCalled();- // Falls through to auto-merge path with merge: false (failure cleanup)- expect(removeWorktree).toHaveBeenCalledWith('agent-1', '/mock/workspace', 'cos/task-abc123', { merge: false });+ // Falls through to auto-merge path with merge: false (failure cleanup). A+ // FAILED agent additionally asks removeWorktree to KEEP the branch when it+ // holds commits, so the task's retry can resume from it (#3167).+ expect(removeWorktree).toHaveBeenCalledWith('agent-1', '/mock/workspace', 'cos/task-abc123', { merge: false, preserveBranchWithCommits: true });});it('should use baseBranch as PR base (not devBranch, since worktrees are created from baseBranch)', async () => {@@ -894,7 +900,7 @@ describe('cleanupAgentWorktree - openPR path', () => {await cleanupAgentWorktree('agent-1', true, { openPR: false, skipMerge: true });expect(removeWorktree).toHaveBeenCalledWith(- 'agent-1', '/mock/workspace', 'cos/task-abc123', { merge: false }+ 'agent-1', '/mock/workspace', 'cos/task-abc123', { merge: false, preserveBranchWithCommits: false });});@@ -902,11 +908,79 @@ describe('cleanupAgentWorktree - openPR path', () => {await cleanupAgentWorktree('agent-1', true, { openPR: false, skipMerge: false });expect(removeWorktree).toHaveBeenCalledWith(- 'agent-1', '/mock/workspace', 'cos/task-abc123', { merge: true }+ 'agent-1', '/mock/workspace', 'cos/task-abc123', { merge: true, preserveBranchWithCommits: false }+ );+ });++ // --- branch preservation for resume (#3167) ---++ it('asks removeWorktree to preserve a FAILED agent\'s branch so its retry can resume', async () => {+ await cleanupAgentWorktree('agent-1', false);++ expect(removeWorktree).toHaveBeenCalledWith(+ 'agent-1', '/mock/workspace', 'cos/task-abc123',+ expect.objectContaining({ preserveBranchWithCommits: true })+ );+ });++ it('does NOT preserve the branch on success — the merge/PR path owns cleanup', async () => {+ await cleanupAgentWorktree('agent-1', true);++ expect(removeWorktree).toHaveBeenCalledWith(+ 'agent-1', '/mock/workspace', 'cos/task-abc123',+ expect.objectContaining({ preserveBranchWithCommits: false }));});});+describe('resolveResumeBranch', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ git.getDefaultBranch.mockResolvedValue('main');+ });++ it('returns the branch when it holds commits the default branch does not', async () => {+ git.getBranchComparison.mockResolvedValue({ ahead: 3, commits: [], stats: {} });++ await expect(resolveResumeBranch('/repo', 'cos/task-1/agent-x')).resolves.toBe('cos/task-1/agent-x');+ expect(git.getBranchComparison).toHaveBeenCalledWith('/repo', 'main', 'cos/task-1/agent-x');+ });++ it('returns null when the branch holds nothing to resume', async () => {+ git.getBranchComparison.mockResolvedValue({ ahead: 0, commits: [], stats: {} });++ await expect(resolveResumeBranch('/repo', 'cos/task-1/agent-x')).resolves.toBeNull();+ });++ it('returns null for an absent branch (empty comparison), not a phantom resume', async () => {+ // An absent branch makes the rev-range invalid, so getBranchComparison comes+ // back with ahead: 0 rather than throwing.+ git.getBranchComparison.mockResolvedValue({ ahead: 0, commits: [], stats: {} });++ await expect(resolveResumeBranch('/repo', 'cos/gone')).resolves.toBeNull();+ });++ it('returns null when git errors — never claims a resume it cannot substantiate', async () => {+ git.getBranchComparison.mockRejectedValue(new Error('not a git repository'));++ await expect(resolveResumeBranch('/repo', 'cos/task-1/agent-x')).resolves.toBeNull();+ });++ it('returns null without touching git when the workspace or branch is missing', async () => {+ await expect(resolveResumeBranch(null, 'cos/task-1/agent-x')).resolves.toBeNull();+ await expect(resolveResumeBranch('/repo', null)).resolves.toBeNull();+ expect(git.getBranchComparison).not.toHaveBeenCalled();+ });++ it('falls back to main when the default branch cannot be detected', async () => {+ git.getDefaultBranch.mockRejectedValue(new Error('no remote'));+ git.getBranchComparison.mockResolvedValue({ ahead: 1, commits: [], stats: {} });++ await expect(resolveResumeBranch('/repo', 'cos/task-1/agent-x')).resolves.toBe('cos/task-1/agent-x');+ expect(git.getBranchComparison).toHaveBeenCalledWith('/repo', 'main', 'cos/task-1/agent-x');+ });+});+describe('spawnReviewLoopFollowUp', () => {beforeEach(() => {vi.clearAllMocks();diff --git a/server/services/cosTaskStore.js b/server/services/cosTaskStore.jsindex cbaad9717f..e4fc0e8314 100644--- a/server/services/cosTaskStore.js+++ b/server/services/cosTaskStore.js@@ -443,6 +443,19 @@ export async function updateTask(taskId, updates, taskType = 'user', { now = Dat}}+ // Drop the resume pointer once the task reaches a terminal state. `existingBranch`+ // + `resumedFromAgentId` are stamped by agentCompletionCleanup.js so a FAILED+ // task's retry attaches to the branch its dead agent left behind and resumes+ // instead of restarting. Once the task is done (or blocked for a human), that+ // pointer is spent: a PERPETUAL task type re-queues the same task id for+ // 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') {+ delete updatedMetadata.existingBranch;+ delete updatedMetadata.resumedFromAgentId;+ }+// Release the federation claim/lease when a task leaves `in_progress` (issue// #1563). A claim only protects in-flight work; once the task completes, fails// back to pending, or is blocked, it must become freely claimable by eitherdiff --git a/server/services/worktreeManager.js b/server/services/worktreeManager.jsindex 13918303d1..783482c168 100644--- a/server/services/worktreeManager.js+++ b/server/services/worktreeManager.js@@ -391,7 +391,12 @@ async function createWorktreeUnlocked(agentId, sourceWorkspace, taskId, options* @param {string} agentId - The agent identifier* @param {string} sourceWorkspace - The original git repository path* @param {string} branchName - The worktree branch to clean up- * @param {object} options - { merge: boolean } whether to attempt merge back+ * @param {object} options+ * @param {boolean} [options.merge] - attempt to merge the branch back first+ * @param {boolean} [options.preserveBranchWithCommits] - keep the branch (rather+ * than deleting it) whenever it still holds commits the default branch doesn't,+ * so a retry can resume the work instead of restarting. Used by the FAILED-agent+ * cleanup path; the PR path leaves it off so its local branch is still tidied up.*/export async function removeWorktree(agentId, sourceWorkspace, branchName, options = {}) {const worktreePath = join(WORKTREES_DIR, agentId);@@ -491,9 +496,35 @@ export async function removeWorktree(agentId, sourceWorkspace, branchName, optio// Preserve branch when (a) merge was attempted, failed, and has unmerged commits,// OR (b) merge was refused because HEAD is on a non-default branch — the commits// are still there and the user / a follow-up task may want to integrate manually.- const hasUnmergedCommits = options.merge && !merged && (commitsAhead > 0 || mergeRefused);+ let hasUnmergedCommits = options.merge && !merged && (commitsAhead > 0 || mergeRefused);+ // ...OR (c) the caller asked us to keep any branch that still holds commits+ // (`preserveBranchWithCommits`). The no-merge path — which is what a FAILED+ // agent's cleanup takes — otherwise deletes the branch unconditionally, taking+ // the agent's committed work with it. That is what forces a retry to restart+ // from scratch instead of resuming: measured on agent-d2ae0352 (2026-07-27),+ // reaped 30s after its PR merged, whose branch was deleted and whose task was+ // re-dispatched to a fresh agent. Opt-in rather than automatic so the PR flow+ // (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 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) {+ 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`);+ 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`);+ }+ }if (hasUnmergedCommits) {- console.log(`⚠️ Preserving branch ${branchName} — merge failed, commits need manual recovery`);+ console.log(`⚠️ Preserving worktree branch ${branchName} for manual/automated recovery`);} else {await execGit(['branch', '-D', branchName], sourceWorkspace).catch(err => {diff --git a/server/services/worktreeManager.test.js b/server/services/worktreeManager.test.jsindex 8e330f3544..09a0642069 100644--- a/server/services/worktreeManager.test.js+++ b/server/services/worktreeManager.test.js@@ -7,6 +7,25 @@ import { join } from 'path';const execGitMock = vi.fn();vi.mock('../lib/execGit.js', () => ({ execGit: (...args) => execGitMock(...args) }));+// removeWorktree's branch-preservation path needs the fs + git boundaries stubbed:+// it checks the worktree dir exists, reads `git status`, and (for the resume gate)+// asks git.js for the default branch. Pure helpers don't touch these.+vi.mock('fs', () => ({+ existsSync: vi.fn().mockReturnValue(true),+ realpathSync: vi.fn((p) => p),+}));+vi.mock('fs/promises', () => ({+ readdir: vi.fn().mockResolvedValue([]),+ rm: vi.fn().mockResolvedValue(undefined),+ stat: vi.fn().mockResolvedValue({ isDirectory: () => true }),+}));+vi.mock('./instances.js', () => ({ ensureInstanceId: vi.fn().mockResolvedValue('instance-1') }));+const getDefaultBranchMock = vi.fn().mockResolvedValue('main');+vi.mock('./git.js', () => ({+ getDefaultBranch: (...args) => getDefaultBranchMock(...args),+ isBranchMergedInto: vi.fn().mockResolvedValue(false),+}));+const {shouldRefuseDefaultBranchMerge,isHumanClaimWorktree,@@ -14,6 +33,7 @@ const {isGitLockError,addWorktreeWithRetry,isPreexistingRefError,+ removeWorktree,} = await import('./worktreeManager.js');/**@@ -570,3 +590,78 @@ describe('isPreexistingRefError (orphan-cleanup guard, #2193)', () => {expect(isPreexistingRefError(undefined)).toBe(false);});});++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 } = {}) {+ execGitMock.mockReset();+ execGitMock.mockImplementation((args) => {+ const [sub] = args;+ 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+ // deletes the branch itself and would mask what these tests assert).+ 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 });+ });+ }++ const calledWith = (subcommandArgs) =>+ execGitMock.mock.calls.some(([args]) => JSON.stringify(args) === JSON.stringify(subcommandArgs));++ beforeEach(() => {+ getDefaultBranchMock.mockResolvedValue('main');+ });++ it('KEEPS the branch when it holds commits the default branch does not', async () => {+ scriptGit({ revListCount: 4 });++ const result = await removeWorktree('agent-x', '/repo', 'cos/task-1/agent-x', {+ merge: false, preserveBranchWithCommits: true,+ });++ expect(calledWith(['branch', '-D', 'cos/task-1/agent-x'])).toBe(false);+ expect(result.warnings.join(' ')).toMatch(/preserved/i);+ });++ it('DELETES the branch when it holds nothing the default branch lacks', async () => {+ scriptGit({ revListCount: 0 });++ await removeWorktree('agent-x', '/repo', 'cos/task-1/agent-x', {+ merge: false, preserveBranchWithCommits: true,+ });++ 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 });++ const result = await removeWorktree('agent-x', '/repo', 'cos/task-1/agent-x', {+ merge: false, preserveBranchWithCommits: true,+ });++ expect(calledWith(['branch', '-D', 'cos/task-1/agent-x'])).toBe(false);+ 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 });++ 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);+ });+});