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
fix: stop a merge follow-up from blocking on the worktree that spawned it
[._.]/ Adam Eivy120252d27ad8
diff --git a/.changelog/next/fixed-agent-8249579a.md b/.changelog/next/fixed-agent-8249579a.mdnew file mode 100644index 0000000000..f307dfe0e1--- /dev/null+++ b/.changelog/next/fixed-agent-8249579a.md@@ -0,0 +1 @@+- A merge follow-up no longer blocks when the PR branch is still checked out in the agent worktree that spawned it — cleanup releases the branch before queueing the follow-up, and a branch-busy failure pauses on a short cooldown instead of stranding the pull requestdiff --git a/server/lib/README.md b/server/lib/README.mdindex 7f0dd98b28..3da4ecb4c2 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -251,7 +251,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `jsonExtract.js` | Pull JSON blocks out of LLM responses. `findBalancedBlocks` walks top-level blocks and stops at the first unbalanced one; `findAllBalancedBlocks` is the stack-based variant that scans past stray braces and returns nested blocks in closing order (reverse it for outermost-newest-first). || `taskParser.js` | Parse `TASKS.md` format. || `taskPauseHold.js` | The user-PAUSE hold — pure metadata helpers shared by the writer (`pauseAgent`), the reader (`resumeAgent`), and the clearer (`updateTask`). `AGENT_PAUSED_CATEGORY` is the `blockedCategory` a pause stamps; `PAUSE_METADATA_KEYS` names every key it writes; `pauseMetadata({agentId, pausedAt, workspacePath, runId})` arms it and `clearedPauseMetadata()` releases it (undefined-valued, so `updateTask` deletes rather than serializing `"null"`); `isAgentPausedTask(task)` / `isResumablePausedTask(task, agentId)` answer whether a pause is still live and whether it is THIS agent's. `updateTask` clears the whole set whenever the task leaves `blocked`, so a revive by any path (dedupe, cooldown expiry, manual unblock) can't leave a task running under a stale pause. Also carries the cycle-safe RELEASE adapter (#3730) `agentManagement.js` registers at load — `resolvePausedTaskResume(task)` hands `updateTask` the paused run's resume pointer before the write (so any un-block resumes on the preserved worktree, not just the Resume dialog) and `retirePausedAgent(agentId, taskId, branchName)` retires the paused record after it. |-| `taskBlockCategories.js` | The `blockedCategory` vocabulary — which blocks are the system's to clear and which are a person's, read by the pause logic, the failure reaper, and the investigation auto-retry so they can't drift into three literal sets. `PAUSED_BLOCKED_CATEGORIES` (paused until something outside the task changes — keeps the resume pointer), `USER_DECISION_BLOCKED_CATEGORIES` (user intent / open decision — the reaper's exemption), `NON_AUTO_RETRY_BLOCK_CATEGORIES` (their union — a completed investigation must never revive these). Pure. |+| `taskBlockCategories.js` | The `blockedCategory` vocabulary — which blocks are the system's to clear and which are a person's, read by the pause logic, the failure reaper, and the investigation auto-retry so they can't drift into three literal sets. `PAUSED_BLOCKED_CATEGORIES` (paused until something outside the task changes — keeps the resume pointer), `USER_DECISION_BLOCKED_CATEGORIES` (user intent / open decision — the reaper's exemption), `NON_AUTO_RETRY_BLOCK_CATEGORIES` (their union — a completed investigation must never revive these), `TIMED_COOLDOWN_BLOCKED_CATEGORIES` (a timer clears these — the cooldown sweeper revives them, so block reporters stay quiet). Pure. || `taskRequeue.js` | The REQUEUE stamp (#3376) — pure metadata helpers for the one BACKWARD lifecycle step (`in_progress → pending`, performed by the orphan sweep and the retry-hold release). `REQUEUED_AT_KEY` / `LAST_SPAWNED_AT_KEY` name the two stamps; `isPostSpawnRequeue(pendingTask, inProgressTask)` answers whether the requeue happened strictly AFTER that spawn, which is how the federated merge tells a real requeue apart from an ordinary edit landing on a peer's stale `pending` copy. Returns false when either stamp is missing, so callers fall back to the lifecycle rank. || `taskRetryHold.js` | The failed-task RETRY HOLD state (#3373) — pure metadata helpers shared by the failure verdict, the post-cleanup release, the spawn guard, and the orphan sweep. `retryHoldMetadata(agentId, now)` arms it (task stays `in_progress`, so no dequeue tier can claim the retry before its resume pointer is resolved); `clearedRetryHoldMetadata()` releases it in the same write that flips the task to `pending`; `isRetryHeld(metadata)` / `isRetryHoldOwner(metadata, agentId)` gate the spawn and the owner-scoped release; `isStaleRetryHold(metadata, now, graceMs)` + `RETRY_HOLD_GRACE_MS` let the orphan sweep finish a transition whose process died. || `taxonomyTally.js` | Generic taxonomy tally + top-N-line render engine shared by the two Layered Intelligence leaf taxonomies (`services/layeredIntelligenceRejections.js`, `layeredIntelligenceExecutionFailures.js`). `createTaxonomyTally({predicate, select, field, vocabulary, sentinel, glossFn, gapWording})` is the single composed seam — it binds a taxonomy config into `{summarize, format}`, where `summarize(records)` yields the three-bucket `{entries, unknown, unclassified, diagnosed, total}` tally (commonest-first + taxonomy-order tie-break) and `format(records, limit)` renders one prompt line naming every non-zero gap. Also exports the two leaf utilities the classifiers use directly: `normalizeToken(value)` (lowercase + separator-collapse for label/category matching) and `formatTaxonomyToken(token, labels)` (gloss-map render, nullish→'', unglossed passthrough). Pure leaf — imports nothing from the LI graph. |diff --git a/server/lib/taskBlockCategories.js b/server/lib/taskBlockCategories.jsindex 5ed651d6a8..64c90e8b5d 100644--- a/server/lib/taskBlockCategories.js+++ b/server/lib/taskBlockCategories.js@@ -17,14 +17,34 @@import { AGENT_PAUSED_CATEGORY } from './taskPauseHold.js';+/**+ * Pauses a TIMER clears, not a person: the task carries a `cooldownUntil` and the+ * cooldown sweeper (`unblockExpiredCooldowns`, cosTaskGenerator.js) flips it back+ * to `pending` once that stamp passes.+ *+ * Membership is what makes a block self-reviving, so anything that reports a+ * block to a human — the orphaned-PR notifier is the one that matters, since a+ * merge follow-up's block means its PR is stranded — must check here first and+ * stay quiet: the system is already going to clear this one.+ */+export const TIMED_COOLDOWN_BLOCKED_CATEGORIES = new Set([+ 'orphan-cooldown', // the orphan sweep's retry backoff+ 'worktree-busy' // the branch is checked out in another worktree+]);+/*** "Paused until something outside the task changes", not "finished with". A* pause keeps the resume pointer (see `updateTask`) and is never auto-expired by* the failure reaper — the task is expected to run again once the cooldown* lapses or the user fixes the config.+ *+ * Every TIMED cooldown is a pause by construction, so it is spread in rather+ * than re-listed: a new timed category added to one set but not the other would+ * either lose its resume pointer or never revive — exactly the three-literal-sets+ * drift this module exists to prevent.*/export const PAUSED_BLOCKED_CATEGORIES = new Set([- 'orphan-cooldown', // timed cooldown; unblockExpiredOrphanCooldowns revives it+ ...TIMED_COOLDOWN_BLOCKED_CATEGORIES,'app-unresolved', // the task's app has no usable Repository Path'workspace-invalid' // the resolved workspace isn't a usable directory]);@@ -36,9 +56,9 @@ export const PAUSED_BLOCKED_CATEGORIES = new Set([** The workspace blocks are an open user decision, not a stale failure: the task* is waiting for the app's Repository Path to be fixed, and auto-completing it- * at 14 days would silently retire work nobody decided to drop. (The third pause- * category, `orphan-cooldown`, stays reapable — it revives itself in ~30- * minutes, so one still sitting there after 14 days IS stale.)+ * at 14 days would silently retire work nobody decided to drop. (The TIMED pause+ * categories stay reapable — they revive themselves in minutes, so one still+ * sitting there after 14 days IS stale.)*/export const USER_DECISION_BLOCKED_CATEGORIES = new Set(['user-terminated', // user explicitly stopped the agentdiff --git a/server/services/agentWorkspacePrep.js b/server/services/agentWorkspacePrep.jsindex 07a4ffbcde..385868323e 100644--- a/server/services/agentWorkspacePrep.js+++ b/server/services/agentWorkspacePrep.js@@ -18,6 +18,7 @@* { outcome: 'ready', workspacePath, resolvedAppName, worktreeInfo, jiraTicket, jiraBranchName, explicitWorktree }* { outcome: 'deferred', reason, deferReason, branch } // git conflict — task re-queued* { outcome: 'blocked', reason } // explicit worktree requested but creation failed+ * // (`worktree-busy` blocks are a TIMED pause and revive themselves)** An unexpected throw bubbles to the caller's widened try/catch the same way* the inline code did.@@ -33,7 +34,7 @@ import { isTruthyMeta, isFalsyMeta } from './agentState.js';import { PATHS } from '../lib/fileUtils.js';import * as git from './git.js';import { detectConflicts } from './taskConflict.js';-import { createWorktree, adoptWorktree } from './worktreeManager.js';+import { createWorktree, adoptWorktree, isBranchCheckedOutElsewhereError } from './worktreeManager.js';import { resolveSpawnCwd } from '../lib/spawnCwd.js';import { enforceSafeBranchUpstream } from '../lib/branchUpstreamGuard.js';import { getAppWorkspace, getAppDataForTask, createJiraTicketForTask } from './agentPromptBuilder.js';@@ -51,7 +52,7 @@ const ROOT_DIR = PATHS.root;* it revivable once the config is fixed. Best-effort — the caller's block* outcome must stand even if the write fails.*/-async function blockTask(task, reason, blockedCategory) {+async function blockTask(task, reason, blockedCategory, extraMetadata = {}) {await updateTask(task.id, {status: 'blocked',metadata: {@@ -59,10 +60,21 @@ async function blockTask(task, reason, blockedCategory) {blockedReason: reason,blockedCategory,blockedAt: new Date().toISOString(),+ ...extraMetadata,},}, task.taskType || 'user').catch(() => {});}+// How long a task waits for another worktree to release the branch it needs, and+// how many times it may wait. The producer of that contention is a cleanup+// tearing down the previous agent's worktree, which finishes in seconds — but a+// worktree `removeWorktree` REFUSED to delete (uncommitted changes) holds the+// branch until a human clears it, so the wait has to be bounded. Past the cap the+// task takes the ordinary `worktree-failed` block and the orphaned-PR notifier+// raises its card.+const WORKTREE_BUSY_COOLDOWN_MS = 2 * 60 * 1000;+const WORKTREE_BUSY_MAX_ATTEMPTS = 5;+/*** Prepare the workspace (and any worktree/JIRA branch) for an agent task.*@@ -288,11 +300,19 @@ export async function prepareAgentWorkspace({ agentId, task }) {emitLog('warn', `🌳 Worktree ${resumeWorktreePath} could not be adopted and still holds ${existingBranch} — task ${task.id} starts from a clean branch`, { taskId: task.id });}+ // Both read only by the block/pause decision below: the failure REASON+ // decides whether the task is unrunnable or merely early, and `attempt` is+ // which branch-busy wait this would be (TASKS.md round-trips metadata as+ // strings, hence the coercion; never reset on revive, so the cap is the+ // task's whole patience budget rather than a per-attempt one).+ let worktreeError = null;+ const attempt = (Number(task.metadata?.worktreeBusyAttempts) || 0) + 1;worktreeInfo = adopted || await createWorktree(agentId, workspacePath, task.id, {baseBranch: detectedBase || undefined,existingBranch: branchStillClaimed ? undefined : (existingBranch || undefined),planId: task.metadata?.planId || undefined}).catch(err => {+ worktreeError = err;emitLog('warn', `🌳 Worktree creation failed, using shared workspace: ${err.message}`, { taskId: task.id });return null;});@@ -312,6 +332,21 @@ export async function prepareAgentWorkspace({ agentId, task }) {// degrade to that instead. The resume is lost (the leftover work stays on// disk for the next attempt), but the task still runs.emitLog('warn', `🌳 Worktree creation failed for task ${task.id}; resuming is not possible, continuing in the shared workspace`, { taskId: task.id });+ } else if (isBranchCheckedOutElsewhereError(worktreeError?.message) && attempt <= WORKTREE_BUSY_MAX_ATTEMPTS) {+ // The branch is checked out in ANOTHER worktree. Routinely that other+ // worktree is the previous agent's, still being torn down by the very+ // cleanup that spawned this task, so waiting it out lands the pull+ // request a permanent block would have stranded. `worktree-busy` is a+ // TIMED PAUSE (lib/taskBlockCategories.js): the cooldown sweeper revives+ // it, and the pause keeps `existingBranch` so the revived attempt still+ // attaches to the PR branch instead of cutting a fresh one off main.+ const reason = `Branch ${existingBranch || 'for this task'} is still checked out in another worktree; retrying after a short cooldown`;+ emitLog('info', `🌳 ${reason} (attempt ${attempt}/${WORKTREE_BUSY_MAX_ATTEMPTS})`, { taskId: task.id, branch: existingBranch || null });+ await blockTask(task, `${reason}. ${worktreeError?.message || ''}`.trim(), 'worktree-busy', {+ cooldownUntil: new Date(Date.now() + WORKTREE_BUSY_COOLDOWN_MS).toISOString(),+ worktreeBusyAttempts: attempt,+ });+ return { outcome: 'blocked', reason };} else {// Isolation was EXPLICITLY requested (useWorktree/openPR) but the// worktree couldn't be created. Falling back to the shared workspace@@ -323,7 +358,7 @@ export async function prepareAgentWorkspace({ agentId, task }) {// since there the worktree was only a recommendation, not a request.)const reason = `Worktree creation failed for task ${task.id}; refusing to run in the shared workspace because isolation was explicitly requested`;emitLog('warn', `🌳 ${reason}`, { taskId: task.id });- await blockTask(task, 'Worktree creation failed — isolation was explicitly requested', 'worktree-failed');+ await blockTask(task, `Worktree creation failed — isolation was explicitly requested${worktreeError?.message ? `: ${worktreeError.message}` : ''}`, 'worktree-failed');return { outcome: 'blocked', reason };}} else if (!jiraBranchName && !isFalsyMeta(task.metadata?.useWorktree)) {diff --git a/server/services/agentWorkspacePrep.test.js b/server/services/agentWorkspacePrep.test.jsindex 9a3fc5a555..d7b8e9405c 100644--- a/server/services/agentWorkspacePrep.test.js+++ b/server/services/agentWorkspacePrep.test.js@@ -27,7 +27,16 @@ vi.mock('./git.js', () => ({createBranch: vi.fn(),}));vi.mock('./taskConflict.js', () => ({ detectConflicts: vi.fn().mockResolvedValue({ recommendation: 'proceed' }) }));-vi.mock('./worktreeManager.js', () => ({ createWorktree: vi.fn(), adoptWorktree: vi.fn(), mergeBaseIntoFeatureWorktree: vi.fn() }));+// `isBranchCheckedOutElsewhereError` is imported from the REAL module: it is a+// pure predicate over git's own wording, and re-stating that regex in the mock+// would make every branch-busy assertion below agree with a copy of the code+// instead of with the code.+vi.mock('./worktreeManager.js', async (importOriginal) => ({+ ...(await importOriginal()),+ createWorktree: vi.fn(),+ adoptWorktree: vi.fn(),+ mergeBaseIntoFeatureWorktree: vi.fn(),+}));vi.mock('./agentPromptBuilder.js', () => ({getAppWorkspace: vi.fn().mockResolvedValue('/repos/app-x'),getAppDataForTask: vi.fn().mockResolvedValue(null),@@ -280,3 +289,72 @@ describe('prepareAgentWorkspace — resuming an interrupted run', () => {expect(createWorktree).toHaveBeenCalled();});});++// A merge follow-up preps its worktree within a second or two of the cleanup that+// spawned it, so it can find the PR branch still checked out in the previous+// agent's tree. Blocking there orphans the pull request the follow-up exists to+// land, so the branch-busy failure is a TIMED pause instead.+describe('prepareAgentWorkspace — the branch is checked out in another worktree', () => {+ const BUSY = new Error("fatal: 'cos/task-x/agent-y' is already used by worktree at '/mock/worktrees/agent-y'");+ const followUpTask = (extra = {}) => ({+ id: 'sys-rl-1', taskType: 'internal',+ metadata: {+ useWorktree: true,+ existingBranch: 'cos/task-x/agent-y',+ reviewLoopFollowUp: true,+ reviewLoopPRUrl: 'https://github.com/o/r/pull/1',+ ...extra+ }+ });++ beforeEach(() => {+ ensureLatest.mockResolvedValue({ success: true, upToDate: true });+ adoptWorktree.mockResolvedValue(null);+ createWorktree.mockRejectedValue(BUSY);+ });++ it('pauses with a cooldown instead of blocking, and keeps the branch pointer', async () => {+ const r = await prepareAgentWorkspace({ agentId: 'agent-new', task: followUpTask() });++ expect(r.outcome).toBe('blocked');+ const [, patch] = updateTask.mock.calls.at(-1);+ expect(patch.status).toBe('blocked');+ expect(patch.metadata.blockedCategory).toBe('worktree-busy');+ // `worktree-busy` is a PAUSE category, so updateTask keeps `existingBranch` —+ // the revived attempt must still attach to the PR branch, not cut a new one.+ expect(patch.metadata.existingBranch).toBe('cos/task-x/agent-y');+ // The cooldown stamp is what the sweeper in cosTaskGenerator revives on.+ expect(new Date(patch.metadata.cooldownUntil).getTime()).toBeGreaterThan(Date.now());+ expect(patch.metadata.worktreeBusyAttempts).toBe(1);+ });++ it('counts up from the attempts already recorded on the task', async () => {+ // Metadata round-trips through TASKS.md as strings.+ await prepareAgentWorkspace({ agentId: 'agent-new', task: followUpTask({ worktreeBusyAttempts: '3' }) });++ const [, patch] = updateTask.mock.calls.at(-1);+ expect(patch.metadata.worktreeBusyAttempts).toBe(4);+ expect(patch.metadata.blockedCategory).toBe('worktree-busy');+ });++ it('gives up on a branch nothing is going to release, so a human sees the real block', async () => {+ // A worktree removeWorktree REFUSED to delete (uncommitted changes) holds the+ // branch until someone clears it — waiting forever would just hide the PR.+ await prepareAgentWorkspace({ agentId: 'agent-new', task: followUpTask({ worktreeBusyAttempts: 5 }) });++ const [, patch] = updateTask.mock.calls.at(-1);+ expect(patch.metadata.blockedCategory).toBe('worktree-failed');+ // The git error rides along — "worktree creation failed" alone said nothing+ // about which branch was held, or by what.+ expect(patch.metadata.blockedReason).toContain('already used by worktree');+ });++ it('does NOT pause for a permanent worktree failure', async () => {+ createWorktree.mockRejectedValue(new Error("fatal: '/mock/worktrees/agent-new' already exists"));++ await prepareAgentWorkspace({ agentId: 'agent-new', task: followUpTask() });++ const [, patch] = updateTask.mock.calls.at(-1);+ expect(patch.metadata.blockedCategory).toBe('worktree-failed');+ });+});diff --git a/server/services/agentWorktreeCleanup.js b/server/services/agentWorktreeCleanup.jsindex 8f7453f97e..02ea380f12 100644--- a/server/services/agentWorktreeCleanup.js+++ b/server/services/agentWorktreeCleanup.js@@ -269,6 +269,22 @@ async function runCleanupAgentWorktree(agentId, success, { prCreation = PR_CREAT// run, but the follow-up must not merge. An explicit leave-open policy is// different — opening the PR is the entire requested outcome.const leaveOpen = leavesPrForHuman(originalTask);++ // Release the PR branch BEFORE anything is queued against it. A follow-up+ // spawned below attaches its OWN worktree to `worktreeBranch`, and the CoS+ // evaluation tick preps that task within a second or two — comfortably+ // inside the window this cleanup needs for its own teardown. Removing+ // afterwards lost that race (~0.7s in the reported incident): the+ // follow-up's `git worktree add` failed with "is already used by worktree+ // at …", the task was blocked, and the pull request it existed to land was+ // orphaned. Nothing below this point reads the worktree — the Copilot+ // pre-request above is the last user of that checkout.+ const result = await removeWorktree(agentId, sourceWorkspace, worktreeBranch, { merge: false }).catch(err => {+ emitLog('warn', `🌳 Worktree cleanup failed for ${agentId}: ${err.message}`, { agentId });+ return { warnings: [`Worktree cleanup failed: ${err.message}`] };+ });+ warnings.push(...(result?.warnings || []));+if (resolvedPrCompletion === PR_COMPLETIONS.LEAVE_OPEN) {emitLog('info', `🤝 Leaving ${prResult.url} open by task completion policy`, { agentId, prUrl: prResult.url });} else if (leaveOpen && !runsReviewLoop) {@@ -337,11 +353,6 @@ async function runCleanupAgentWorktree(agentId, success, { prCreation = PR_CREAT}}- const result = await removeWorktree(agentId, sourceWorkspace, worktreeBranch, { merge: false }).catch(err => {- emitLog('warn', `🌳 Worktree cleanup failed for ${agentId}: ${err.message}`, { agentId });- return { warnings: [`Worktree cleanup failed: ${err.message}`] };- });- warnings.push(...(result?.warnings || []));return warnings;}@@ -361,6 +372,12 @@ async function runCleanupAgentWorktree(agentId, success, { prCreation = PR_CREAT// budget and goes `blocked` would strand it — and the orphaned-PR notifier// keys on a follow-up task's `reviewLoopPRUrl`, which an inline run never// creates. So hand it to the same follow-up machinery the old flow used.+ //+ // The lookup happens here (it needs the checkout), but the SPAWN waits until+ // after `removeWorktree` below — same reason as the PR path above: the+ // follow-up attaches its own worktree to this branch and would otherwise race+ // this cleanup's teardown for it.+ let strandedPrUrl = null;if (prCreation === PR_CREATION.IF_MISSING && !success) {const worktreePath = agentState.metadata.workspacePath || join(PATHS.worktrees, agentId);const { findPullRequestForBranch } = await import('./github.js');@@ -368,22 +385,9 @@ async function runCleanupAgentWorktree(agentId, success, { prCreation = PR_CREATconst found = await findPullRequestForBranch(worktreeBranch, { cwd: worktreePath, env: env || null }).catch(() => ({ status: 'unavailable' }));if (found.status === 'found' && found.url) {+ strandedPrUrl = found.url;emitLog('warn', `🌳 ${agentId} failed after opening ${found.url} — handing the PR to a follow-up so it isn't stranded`, { agentId, prUrl: found.url, branchName: worktreeBranch });warnings.push(`Agent ${agentId} failed after opening ${found.url}; a follow-up was queued to land it.`);- await spawnReviewLoopFollowUp({- originalAgentId: agentId,- originalTask,- prUrl: found.url,- prBranch: worktreeBranch,- sourceWorkspace,- prCompletion: PR_COMPLETION_VALUES.includes(prCompletion) ? prCompletion : PR_COMPLETIONS.REVIEW_THEN_MERGE,- reviewers, usernames, optionalReviewers, reviewerMaxRounds,- reviewStopMode, reviewerApplies, reviewerModels, reviewerEfforts,- leaveOpen: leavesPrForHuman(originalTask),- }).catch(err => {- emitLog('warn', `🌳 Failed to spawn a follow-up for orphaned ${found.url}: ${err.message}`, { agentId });- warnings.push(`Could not queue a follow-up for ${found.url}: ${err.message}`);- });}}@@ -409,6 +413,24 @@ async function runCleanupAgentWorktree(agentId, success, { prCreation = PR_CREATreturn { warnings: [`Worktree cleanup failed: ${err.message}`] };});warnings.push(...(result?.warnings || []));++ // The branch is released now, so the follow-up can check it out.+ if (strandedPrUrl) {+ await spawnReviewLoopFollowUp({+ originalAgentId: agentId,+ originalTask,+ prUrl: strandedPrUrl,+ prBranch: worktreeBranch,+ sourceWorkspace,+ prCompletion: PR_COMPLETION_VALUES.includes(prCompletion) ? prCompletion : PR_COMPLETIONS.REVIEW_THEN_MERGE,+ reviewers, usernames, optionalReviewers, reviewerMaxRounds,+ reviewStopMode, reviewerApplies, reviewerModels, reviewerEfforts,+ leaveOpen: leavesPrForHuman(originalTask),+ }).catch(err => {+ emitLog('warn', `🌳 Failed to spawn a follow-up for orphaned ${strandedPrUrl}: ${err.message}`, { agentId });+ warnings.push(`Could not queue a follow-up for ${strandedPrUrl}: ${err.message}`);+ });+ }return warnings;}diff --git a/server/services/cleanupAgentWorktree.test.js b/server/services/cleanupAgentWorktree.test.jsindex 75d26e5acd..6c72a97644 100644--- a/server/services/cleanupAgentWorktree.test.js+++ b/server/services/cleanupAgentWorktree.test.js@@ -198,6 +198,13 @@ vi.mock('./prWatcher.js', () => ({queuePendingMerge: (...args) => queuePendingMergeMock(...args)}));+// The `if-missing` net's OTHER half: a FAILED run may still have opened its PR+// before it died, and cleanup hands that orphan to the same follow-up machinery.+const findPullRequestForBranchMock = vi.fn().mockResolvedValue({ status: 'unavailable' });+vi.mock('./github.js', () => ({+ findPullRequestForBranch: (...args) => findPullRequestForBranchMock(...args)+}));+// The `if-missing` safety net asks finalize's own PR-claim check whether// the agent actually opened the PR it was told to open (#3733).const verifyPrClaimMock = vi.fn();@@ -577,6 +584,23 @@ describe('cleanupAgentWorktree - PR-creation path', () => {expect(git.createPR).not.toHaveBeenCalled();});+ // The failed-run half of the net hands its orphaned PR to the same follow-up,+ // so it needs the same ordering guarantee as the success path: the follow-up+ // checks the branch out, and the teardown below has to release it first.+ it('releases the branch before handing a failed run’s orphaned PR to a follow-up', async () => {+ findPullRequestForBranchMock.mockResolvedValue({ status: 'found', url: 'https://github.com/test/repo/pull/77' });+ addTask.mockResolvedValue({ id: 'sys-rl-orphan' });++ const warnings = await cleanupAgentWorktree('agent-1', false, netOpts);++ expect(addTask).toHaveBeenCalledTimes(1);+ expect(addTask.mock.calls[0][0].metadata.reviewLoopPRUrl).toBe('https://github.com/test/repo/pull/77');+ expect(removeWorktree).toHaveBeenCalledTimes(1);+ expect(removeWorktree.mock.invocationCallOrder[0])+ .toBeLessThan(addTask.mock.invocationCallOrder[0]);+ expect(warnings.some(w => w.includes('a follow-up was queued to land it'))).toBe(true);+ });+it('still creates the PR outright when the net is off (a lean session hands off)', async () => {git.push.mockResolvedValue(undefined);git.createPR.mockResolvedValue({ success: true, url: 'https://github.com/test/repo/pull/43' });@@ -650,6 +674,31 @@ describe('cleanupAgentWorktree - PR-creation path', () => {expect(followUp.autoApproved).toBe(true);});+ // Git allows a branch in exactly one worktree. The follow-up attaches its own+ // worktree to the PR branch and the CoS tick preps it a second or two after+ // this call queues it — so tearing THIS worktree down afterwards lost the race:+ // `git worktree add` failed with "is already used by worktree at …", the+ // follow-up was blocked, and the PR it existed to land was orphaned.+ it('removes the worktree BEFORE queueing the follow-up that must check out its branch', async () => {+ git.push.mockResolvedValue(undefined);+ git.createPR.mockResolvedValue({ success: true, url: 'https://github.com/test/repo/pull/44' });+ git.requestCopilotReview.mockResolvedValue({ success: true });+ addTask.mockResolvedValue({ id: 'sys-rl-order' });++ await cleanupAgentWorktree('agent-1', true, {+ prCreation: 'always', requestCopilotReview: true, description: 'X',+ originalTask: { id: 'task-orig', metadata: {}, description: 'X' }+ });++ expect(removeWorktree).toHaveBeenCalledTimes(1);+ expect(addTask).toHaveBeenCalledTimes(1);+ expect(removeWorktree.mock.invocationCallOrder[0])+ .toBeLessThan(addTask.mock.invocationCallOrder[0]);+ // ...but not so early that the Copilot pre-request loses the checkout it runs in.+ expect(git.requestCopilotReview.mock.invocationCallOrder[0])+ .toBeLessThan(removeWorktree.mock.invocationCallOrder[0]);+ });+it('STILL spawns the review-loop follow-up when the Copilot pre-request fails (follow-up re-requests at its turn)', async () => {git.push.mockResolvedValue(undefined);git.createPR.mockResolvedValue({ success: true, url: 'https://github.com/test/repo/pull/43' });diff --git a/server/services/cosTaskGenerator.orphanCooldown.test.js b/server/services/cosTaskGenerator.cooldown.test.jssimilarity index 68%rename from server/services/cosTaskGenerator.orphanCooldown.test.jsrename to server/services/cosTaskGenerator.cooldown.test.jsindex 06eac7c7a2..e73adb8bcb 100644--- a/server/services/cosTaskGenerator.orphanCooldown.test.js+++ b/server/services/cosTaskGenerator.cooldown.test.js@@ -1,8 +1,9 @@/**- * `unblockExpiredOrphanCooldowns` — expired orphan-cooldown revival (#3500).+ * `unblockExpiredCooldowns` — expired timed-cooldown revival (#3500).*- * The pass walks BOTH task stores' blocked groups and flips any- * `orphan-cooldown` task whose `cooldownUntil` has passed back to `pending`.+ * The pass walks BOTH task stores' blocked groups and flips any task in+ * `TIMED_COOLDOWN_BLOCKED_CATEGORIES` whose `cooldownUntil` has passed back to+ * `pending`.* Each revived task has to be written back to the store it came from, and the* pre-fix version re-derived that origin per task with* `userTaskData.grouped.blocked.includes(task)` — an O(N) scan inside the O(N)@@ -21,7 +22,7 @@ vi.mock('./cosTaskStore.js', async (importActual) => ({updateTask: (...args) => updateTaskMock(...args),}));-import { unblockExpiredOrphanCooldowns } from './cosTaskGenerator.js';+import { unblockExpiredCooldowns } from './cosTaskGenerator.js';const EXPIRED = new Date(Date.now() - 60_000).toISOString();const PENDING = new Date(Date.now() + 60 * 60_000).toISOString();@@ -54,9 +55,9 @@ beforeEach(() => {updateTaskMock.mockClear();});-describe('unblockExpiredOrphanCooldowns', () => {+describe('unblockExpiredCooldowns', () => {it('routes each revived task back to the store it was read from', async () => {- await unblockExpiredOrphanCooldowns(+ await unblockExpiredCooldowns(store([cooldownTask('u1', EXPIRED)]),store([cooldownTask('c1', EXPIRED)]));@@ -77,7 +78,7 @@ describe('unblockExpiredOrphanCooldowns', () => {Array.from({ length: 25 }, (_, i) => cooldownTask(`c${i}`, EXPIRED)));- await unblockExpiredOrphanCooldowns(store(userBlocked), store(cosBlocked));+ await unblockExpiredCooldowns(store(userBlocked), store(cosBlocked));expect(updateTaskMock).toHaveBeenCalledTimes(50);expect(userBlocked.scans).toBe(0);@@ -86,7 +87,7 @@ describe('unblockExpiredOrphanCooldowns', () => {it('honors an explicit taskType over the queue default', async () => {// A user-typed task parked in the CoS store still writes back as 'user'.- await unblockExpiredOrphanCooldowns(+ await unblockExpiredCooldowns(store([]),store([cooldownTask('c1', EXPIRED, { taskType: 'user' })]));@@ -95,7 +96,7 @@ describe('unblockExpiredOrphanCooldowns', () => {});it('clears the block fields and flips status to pending', async () => {- await unblockExpiredOrphanCooldowns(store([cooldownTask('u1', EXPIRED)]), store([]));+ await unblockExpiredCooldowns(store([cooldownTask('u1', EXPIRED)]), store([]));const [, update] = updateTaskMock.mock.calls[0];expect(update.status).toBe('pending');@@ -106,7 +107,7 @@ describe('unblockExpiredOrphanCooldowns', () => {});it('leaves unexpired cooldowns, other block categories, and missing groups alone', async () => {- await unblockExpiredOrphanCooldowns(+ await unblockExpiredCooldowns(store([cooldownTask('u1', PENDING),{ id: 'u2', metadata: { blockedCategory: 'max-spawns', cooldownUntil: EXPIRED } },@@ -119,11 +120,41 @@ describe('unblockExpiredOrphanCooldowns', () => {expect(updateTaskMock).not.toHaveBeenCalled();});+ // The pass sweeps the whole TIMED_COOLDOWN_BLOCKED_CATEGORIES vocabulary, not a+ // literal `orphan-cooldown` — a category added to that set with no sweeper of+ // its own would otherwise sit blocked forever. `worktree-busy` is the second+ // member: a merge follow-up waiting for another worktree to release its branch.+ it('revives every timed-cooldown category, not just orphan-cooldown', async () => {+ await unblockExpiredCooldowns(+ store([]),+ store([{+ id: 'sys-rl-1',+ status: 'blocked',+ metadata: {+ blockedCategory: 'worktree-busy',+ cooldownUntil: EXPIRED,+ existingBranch: 'cos/task-1/agent-1',+ worktreeBusyAttempts: 1,+ },+ }])+ );++ expect(updateTaskMock).toHaveBeenCalledTimes(1);+ const [id, update] = updateTaskMock.mock.calls[0];+ expect(id).toBe('sys-rl-1');+ expect(update.status).toBe('pending');+ expect(update.metadata.blockedCategory).toBeUndefined();+ // The branch the follow-up exists to land survives the revival...+ expect(update.metadata.existingBranch).toBe('cos/task-1/agent-1');+ // ...and so does the attempt count, or the wait would never give up.+ expect(update.metadata.worktreeBusyAttempts).toBe(1);+ });+it('leaves a task with an unparseable cooldownUntil blocked rather than reviving it', async () => {// NaN loses both `<=` and `>`, so writing the expiry test as the negation of// "still cooling" would silently unblock every malformed timestamp on the// next tick instead of leaving it parked for a human to look at.- await unblockExpiredOrphanCooldowns(store([cooldownTask('u1', 'not-a-date')]), store([]));+ await unblockExpiredCooldowns(store([cooldownTask('u1', 'not-a-date')]), store([]));expect(updateTaskMock).not.toHaveBeenCalled();});diff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.jsindex e0ea730e94..27dee4ef36 100644--- a/server/services/cosTaskGenerator.js+++ b/server/services/cosTaskGenerator.js@@ -43,6 +43,7 @@ import { isHeldByOther, getClaimOwner } from './cosTaskClaim.js';import { ensureInstanceId } from './instances.js';import { PR_COMPLETION_VALUES } from '../lib/prDisposition.js';import { resolveTrackerFilingBlock } from '../lib/workTracker.js';+import { TIMED_COOLDOWN_BLOCKED_CATEGORIES } from '../lib/taskBlockCategories.js';/*** Block a task that has exceeded the max spawn limit. Returns true if blocked.@@ -723,21 +724,27 @@ export function isWithinProjectLimit(task, agentsByProject, perProjectLimit) {}/**- * Unblock every expired `orphan-cooldown` task in ONE queue's blocked group.+ * Unblock every expired timed-cooldown task in ONE queue's blocked group.* `defaultTaskType` names the store the array came from, so a task that carries* no explicit `taskType` is routed back to the queue it was read from — no* membership scan needed.+ *+ * Gated on the shared `TIMED_COOLDOWN_BLOCKED_CATEGORIES` vocabulary rather than+ * a literal `orphan-cooldown`: any block whose only precondition is "wait a+ * while" (the newer `worktree-busy` is the second) revives through this same+ * pass, and a category added to that set without a sweeper of its own would+ * otherwise sit blocked forever.*/async function unblockExpiredCooldownsInQueue(blocked, defaultTaskType) {for (const task of blocked || []) {- if (task.metadata?.blockedCategory !== 'orphan-cooldown' || !task.metadata?.cooldownUntil) continue;+ if (!TIMED_COOLDOWN_BLOCKED_CATEGORIES.has(task.metadata?.blockedCategory) || !task.metadata?.cooldownUntil) continue;// An unparseable `cooldownUntil` yields NaN, and NaN loses BOTH comparisons —// so the expiry test has to be written as "is expired", not as the negation of// "is still cooling". Guard it explicitly: a garbage timestamp leaves the task// blocked (the pre-#3500 behavior) rather than reviving it on the next tick.const cooldownUntil = new Date(task.metadata.cooldownUntil).getTime();if (!(cooldownUntil <= Date.now())) continue;- emitLog('info', `⏰ Orphan cooldown expired for task ${task.id}, unblocking`, { taskId: task.id });+ emitLog('info', `⏰ Cooldown expired for task ${task.id} (${task.metadata.blockedCategory}), unblocking`, { taskId: task.id });await updateTask(task.id, {status: 'pending',metadata: {@@ -752,17 +759,17 @@ async function unblockExpiredCooldownsInQueue(blocked, defaultTaskType) {}/**- * Unblock tasks whose orphan-retry cooldown has expired. Walks the blocked- * groups of both task stores and flips any `orphan-cooldown` task back to- * pending once its `cooldownUntil` has passed. Extracted from `evaluateTasks`- * so the cooldown-unblock pass is independently testable.+ * Unblock tasks whose timed cooldown has expired. Walks the blocked groups of+ * both task stores and flips any task in `TIMED_COOLDOWN_BLOCKED_CATEGORIES`+ * back to pending once its `cooldownUntil` has passed. Extracted from+ * `evaluateTasks` so the cooldown-unblock pass is independently testable.** Each store is walked separately rather than concatenated: the old single-pass* version re-derived the queue of origin with `userBlocked.includes(task)` per* task, an O(N) scan inside an O(N) loop (#3500). Passing the origin down makes* classification O(1) and the whole pass linear.*/-export async function unblockExpiredOrphanCooldowns(userTaskData, cosTaskData) {+export async function unblockExpiredCooldowns(userTaskData, cosTaskData) {await unblockExpiredCooldownsInQueue(userTaskData.grouped?.blocked, 'user');await unblockExpiredCooldownsInQueue(cosTaskData.grouped?.blocked, 'internal');}@@ -1225,7 +1232,7 @@ export async function evaluateTasks(options) {const { user: userTaskData, cos: cosTaskData } = await getAllTasks();// Unblock tasks whose orphan-retry cooldown has expired- await unblockExpiredOrphanCooldowns(userTaskData, cosTaskData);+ await unblockExpiredCooldowns(userTaskData, cosTaskData);// Count running agents and available slots (global + per-project)const runningAgentEntries = Object.values(state.agents).filter(a => a.status === 'running');diff --git a/server/services/cosTaskStore.js b/server/services/cosTaskStore.jsindex faddcfae99..02bcb1f2ee 100644--- a/server/services/cosTaskStore.js+++ b/server/services/cosTaskStore.js@@ -633,14 +633,24 @@ async function writeTaskUpdate(taskId, updates, taskType, { now }) {// PAUSE-shaped blocks are the exception (`PAUSED_BLOCKED_CATEGORIES`): the task// is waiting on something outside itself and is expected to run again, so its// pointer is not spent. `orphan-cooldown` is a TIMED pause —- // `unblockExpiredOrphanCooldowns` (cosTaskGenerator.js) flips it back to+ // `unblockExpiredCooldowns` (cosTaskGenerator.js) flips it back to// `pending` once `cooldownUntil` passes. The workspace blocks are a CONFIG pause:// the app's Repository Path is missing/unreachable, and the user fixes it and// revives the task. Stripping the pointer in either case means the revived task// starts clean and abandons the worktree its dead agent left behind — which is// exactly the recovery this mechanism exists for.if (isTerminalTaskStatus(updates.status) && !PAUSED_BLOCKED_CATEGORIES.has(updatedMetadata.blockedCategory)) {- delete updatedMetadata.existingBranch;+ // ...but only the RESUME mechanism's `existingBranch`, which is keyed by the+ // `resumedFromAgentId` it is always written with — the same discriminator+ // `resumePointerMetadata` (agentWorktreeCleanup.js) uses to avoid clearing a+ // pointer it didn't write. A review-loop / merge follow-up sets+ // `existingBranch` as its own CONFIGURATION: it exists to land the PR on that+ // branch. Stripping that copy meant re-running a blocked merge follow-up got+ // a worktree cut fresh off the default branch — the merge still targets the+ // right PR by url, but any fix-and-push lands on a branch the PR has never+ // heard of. Keyed on the mechanism rather than on the task kind so the next+ // producer of a self-configured `existingBranch` doesn't re-hit this.+ if (updatedMetadata.resumedFromAgentId) delete updatedMetadata.existingBranch;delete updatedMetadata.resumedFromAgentId;delete updatedMetadata.resumeWorktreePath;}@@ -769,7 +779,13 @@ export async function reviveBlockedTask(taskId, { priority, metadata } = {}, tas...(metadata || {}),totalSpawnCount: undefined,orphanRetryCount: undefined,- lastOrphanedAt: undefined+ lastOrphanedAt: undefined,+ // Same reasoning: the branch-busy patience budget is spent by the time a+ // follow-up hard-blocks, so a revived one would hard-block again on the+ // first busy race instead of waiting the other worktree out. NOT cleared on+ // the cooldown revive (updateTask's blocked→pending path) — that runs on+ // every wait and would defeat the cap.+ worktreeBusyAttempts: undefined}}, taskType);}diff --git a/server/services/cosTaskStore.test.js b/server/services/cosTaskStore.test.jsindex 972f533d2a..0a58cecd5f 100644--- a/server/services/cosTaskStore.test.js+++ b/server/services/cosTaskStore.test.js@@ -549,13 +549,19 @@ describe('cosTaskStore.addTask', () => {const task = await addTask({ description: 'budget reset', app: 'portos', id: 'sys-budget' }, 'internal');await updateTask(task.id, {status: 'blocked',- metadata: { blockedCategory: 'max-spawns', totalSpawnCount: 99, orphanRetryCount: 3, lastOrphanedAt: '2026-01-01T00:00:00.000Z' }+ metadata: {+ blockedCategory: 'max-spawns', totalSpawnCount: 99, orphanRetryCount: 3,+ lastOrphanedAt: '2026-01-01T00:00:00.000Z', worktreeBusyAttempts: 5+ }}, 'internal');const revived = await reviveBlockedTask(task.id, { metadata: { totalSpawnCount: 99, fresh: 'yes' } }, 'internal');expect(revived.status).toBe('pending');expect(revived.metadata.totalSpawnCount).toBeUndefined();expect(revived.metadata.orphanRetryCount).toBeUndefined();expect(revived.metadata.lastOrphanedAt).toBeUndefined();+ // The branch-busy patience budget is spent by the time a follow-up gives up;+ // leaving it would make the revived task hard-block on the first busy race.+ expect(revived.metadata.worktreeBusyAttempts).toBeUndefined();expect(revived.metadata.blockedCategory).toBeUndefined();expect(revived.metadata.fresh).toBe('yes');});@@ -873,6 +879,54 @@ describe('cosTaskStore.updateTask', () => {expect(blocked.metadata.resumeWorktreePath).toBe('/w/agent-x');});+ // An `existingBranch` with no `resumedFromAgentId` beside it was never written+ // by the resume mechanism — it is the task's OWN configuration. A merge+ // follow-up is the producer: it exists to land the PR on that branch. Stripping+ // that copy meant re-running a blocked follow-up cut a worktree fresh off the+ // default branch, so any fix-and-push landed on a branch the PR never heard of.+ it('keeps a self-configured branch pointer through a terminal block', async () => {+ await addTask({ description: 'merge PR 1', id: 'sys-rl-keep' }, 'internal');+ await updateTask('sys-rl-keep', {+ metadata: { existingBranch: 'cos/task-1/agent-1', reviewLoopFollowUp: true, reviewLoopPRUrl: 'https://github.com/o/r/pull/1' }+ }, 'internal');+ const blocked = await updateTask('sys-rl-keep', {+ status: 'blocked',+ metadata: { blockedCategory: 'worktree-failed' }+ }, 'internal');+ expect(blocked.metadata.existingBranch).toBe('cos/task-1/agent-1');+ });++ // ...but once the resume mechanism has stamped its marker, the whole pointer is+ // the resume's and goes with it — the tree the dead run left behind is gone by+ // the time anyone re-runs the task.+ it('drops the branch pointer once resumedFromAgentId marks it as the resume’s', async () => {+ await addTask({ description: 'merge PR 2', id: 'sys-rl-halfkeep' }, 'internal');+ await updateTask('sys-rl-halfkeep', {+ metadata: {+ existingBranch: 'cos/task-2/agent-2', reviewLoopFollowUp: true,+ resumedFromAgentId: 'agent-2', resumeWorktreePath: '/w/agent-2'+ }+ }, 'internal');+ const done = await updateTask('sys-rl-halfkeep', { status: 'completed' }, 'internal');+ expect(done.metadata.existingBranch).toBeUndefined();+ expect(done.metadata.resumedFromAgentId).toBeUndefined();+ expect(done.metadata.resumeWorktreePath).toBeUndefined();+ });++ // `worktree-busy` joins the pause categories: the cooldown sweeper revives it,+ // and the revived attempt must still attach to the PR branch.+ it('keeps the pointer through a worktree-busy cooldown block', async () => {+ await addTask({ description: 'merge PR 3', id: 'sys-rl-busy' }, 'internal');+ await updateTask('sys-rl-busy', {+ metadata: { existingBranch: 'cos/task-3/agent-3', resumedFromAgentId: 'agent-3', reviewLoopFollowUp: true }+ }, 'internal');+ const cooled = await updateTask('sys-rl-busy', {+ status: 'blocked',+ metadata: { blockedCategory: 'worktree-busy', cooldownUntil: '2026-01-01T00:02:00.000Z' }+ }, 'internal');+ expect(cooled.metadata.existingBranch).toBe('cos/task-3/agent-3');+ });+it('releases the federation claim/lease when a task leaves in_progress (#1563)', async () => {await addTask({ description: 'claimed', id: 'task-claimed' }, 'user');// Spawn-time claim: status in_progress carries the claim metadata.diff --git a/server/services/orphanedPrNotifier.js b/server/services/orphanedPrNotifier.jsindex 263876c30b..4d23d1e71b 100644--- a/server/services/orphanedPrNotifier.js+++ b/server/services/orphanedPrNotifier.js@@ -24,6 +24,7 @@*/import { addNotification, exists as notificationExists, NOTIFICATION_TYPES, PRIORITY_LEVELS } from './notifications.js';+import { TIMED_COOLDOWN_BLOCKED_CATEGORIES } from '../lib/taskBlockCategories.js';/*** Raise a notification when a task that was going to merge a PR gets blocked.@@ -41,6 +42,13 @@ export async function notifyIfPrLeftOrphaned({ task, previousStatus } = {}) {if (task?.status !== 'blocked' || previousStatus === 'blocked') return false;const prUrl = task.metadata?.reviewLoopPRUrl;if (!prUrl) return false;+ // A TIMED pause is not an orphaning: the cooldown sweeper flips the task back+ // to `pending` on its own, so the PR still has something coming for it. Staying+ // quiet matters twice over — the card would be wrong, and the one-per-PR guard+ // below would then swallow the card for a REAL block that followed (the+ // `worktree-busy` wait gives up after a bounded number of attempts and re-blocks+ // as `worktree-failed`, which is the block a human actually needs to see).+ if (TIMED_COOLDOWN_BLOCKED_CATEGORIES.has(task.metadata?.blockedCategory)) return false;// One notification per PR, not per block. Fixing the cause and re-running is// the intended recovery, and a re-run that blocks again would otherwise stack// another HIGH card for a PR the user is already looking at.diff --git a/server/services/orphanedPrNotifier.test.js b/server/services/orphanedPrNotifier.test.jsindex b93a957913..6e4d69733a 100644--- a/server/services/orphanedPrNotifier.test.js+++ b/server/services/orphanedPrNotifier.test.js@@ -68,6 +68,22 @@ describe('notifyIfPrLeftOrphaned', () => {expect(addNotification.mock.calls[0][0].description).toContain('worktree-failed');});+ // ...but a TIMED pause is not an orphaning: the cooldown sweeper revives it.+ // The one-per-PR guard makes this load-bearing — a card raised for the pause+ // would swallow the card for the real block the task lands on if it gives up.+ it('stays quiet for a self-reviving cooldown block', async () => {+ const task = followUp({+ blockedCategory: 'worktree-busy',+ blockedReason: 'Branch cos/task-1/agent-1 is still checked out in another worktree',+ cooldownUntil: new Date(Date.now() + 60_000).toISOString(),+ });+ expect(await notifyIfPrLeftOrphaned({ task, previousStatus: 'pending' })).toBe(false);+ expect(addNotification).not.toHaveBeenCalled();+ // The cooldown check must come before the dedupe probe, or the pause would+ // still consume the one card this PR gets.+ expect(exists).not.toHaveBeenCalled();+ });+it('ignores an ordinary blocked task that is not landing a PR', async () => {const task = { id: 't-plain', status: 'blocked', metadata: { blockedCategory: 'app-unresolved' } };expect(await notifyIfPrLeftOrphaned({ task, previousStatus: 'pending' })).toBe(false);diff --git a/server/services/voice/proactiveTriggers.js b/server/services/voice/proactiveTriggers.jsindex 0363fefb6d..e57785f780 100644--- a/server/services/voice/proactiveTriggers.js+++ b/server/services/voice/proactiveTriggers.js@@ -31,6 +31,7 @@ import { cosEvents } from '../cosEvents.js';import { notificationEvents } from '../notifications.js';import { speakProactive as defaultSpeak } from './proactiveSpeech.js';import { getVoiceConfig } from './config.js';+import { TIMED_COOLDOWN_BLOCKED_CATEGORIES } from '../../lib/taskBlockCategories.js';// Per-source minimum interval between spoken lines (ms). Tuned for an opt-in// assistant: critical errors are rare so a wide spacing is fine; tasks and@@ -262,6 +263,11 @@ export const wireProactiveTriggers = ({ io, speak = defaultSpeak, limits = RATE_if (status !== 'completed' && status !== 'blocked') return;if (!isMetaTrue(task.metadata?.voiceDispatch)) return;if (status === 'blocked' && task.metadata?.blockedCategory === 'user-terminated') return;+ // A TIMED cooldown is not a terminal outcome — the sweeper flips it back to+ // `pending` in minutes. Announcing it would be wrong AND would burn the+ // once-per-`${id}:blocked` reservation below, swallowing the announcement+ // for a real block the task lands on later.+ if (status === 'blocked' && TIMED_COOLDOWN_BLOCKED_CATEGORIES.has(task.metadata?.blockedCategory)) return;// Reserve this terminal outcome synchronously (before queueing onto the// async tail) so a same-tick / in-flight duplicate dedups to one line. The// reservation is rolled back inside the tail if no line went out (configdiff --git a/server/services/worktreeManager.js b/server/services/worktreeManager.jsindex 00dded14dd..7732b5bcf5 100644--- a/server/services/worktreeManager.js+++ b/server/services/worktreeManager.js@@ -83,6 +83,26 @@ export function isGitLockError(message) {return /index\.lock|cannot lock|could not lock|unable to create '[^']*\.lock'|unable to (?:write|lock)|already locked|another git process/i.test(message || '');}+/**+ * True when `git worktree add` refused because the branch is ALREADY checked out+ * in some other worktree — `fatal: '<branch>' is already used by worktree at+ * '<path>'` on current git, `is already checked out at '<path>'` on older ones.+ *+ * This is a TRANSIENT condition, not a misconfiguration: the only routine+ * producer is a cleanup still tearing down the previous agent's worktree while+ * the follow-up spawned to land its PR is already prepping (the two ran ~0.7s+ * apart in the incident that motivated this). Callers use it to pause and retry+ * rather than blocking the task, which stranded the pull request the follow-up+ * existed to merge.+ *+ * Deliberately NOT folded into `isGitLockError`: that predicate drives the+ * in-process add retry, whose budget is sized in milliseconds for bookkeeping+ * locks. Waiting out another worktree's teardown belongs at the task level.+ */+export function isBranchCheckedOutElsewhereError(message) {+ return /already (?:used by worktree|checked out) at/i.test(message || '');+}+/*** Run `git worktree add …` with retry on lock contention. Promise-chained* (no try/catch) so it stays idiomatic with the rest of the module: on a lockdiff --git a/server/services/worktreeManager.test.js b/server/services/worktreeManager.test.jsindex ef1d6109f3..0f8e566e3c 100644--- a/server/services/worktreeManager.test.js+++ b/server/services/worktreeManager.test.js@@ -36,6 +36,7 @@ const {isGitLockError,addWorktreeWithRetry,isPreexistingRefError,+ isBranchCheckedOutElsewhereError,removeWorktree,adoptWorktree,createWorktree,@@ -687,6 +688,34 @@ describe('isPreexistingRefError (orphan-cleanup guard, #2193)', () => {});});+describe('isBranchCheckedOutElsewhereError (branch-busy pause gate)', () => {+ it('matches git\'s wording for a branch held by another worktree, old and new', () => {+ // Current git.+ expect(isBranchCheckedOutElsewhereError(+ "fatal: 'cos/task-x/agent-y' is already used by worktree at '/repo/data/cos/worktrees/agent-y'"+ )).toBe(true);+ // Pre-2.30 wording.+ expect(isBranchCheckedOutElsewhereError(+ "fatal: 'cos/task-x/agent-y' is already checked out at '/repo/data/cos/worktrees/agent-y'"+ )).toBe(true);+ });++ it('does NOT match the other "already exists" failures — those are permanent', () => {+ // An occupied worktree DIRECTORY is not a branch another tree is holding;+ // pausing on it would wait out a cooldown that can never clear it.+ expect(isBranchCheckedOutElsewhereError("fatal: '/repo/data/cos/worktrees/agent-x' already exists")).toBe(false);+ expect(isBranchCheckedOutElsewhereError("fatal: a branch named 'cos/task/agent' already exists")).toBe(false);+ expect(isBranchCheckedOutElsewhereError('error: cannot lock ref')).toBe(false);+ expect(isBranchCheckedOutElsewhereError('fatal: invalid reference: origin/nope')).toBe(false);+ expect(isBranchCheckedOutElsewhereError('')).toBe(false);+ expect(isBranchCheckedOutElsewhereError(undefined)).toBe(false);+ });++ it('stays out of the in-process add retry — that budget is sized for lock contention', () => {+ expect(isGitLockError("fatal: 'b' is already used by worktree at '/repo/wt'")).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 instead of