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
resume a restart-killed agent in its own worktree instead of redoing the work
[._.]/ Adam Eivyd62a76e96a7b
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 398a8b2b98..b4b2b7ed77 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -13,6 +13,7 @@- **[issue-3180] Agents no longer run in the PortOS folder when your app's repository path is wrong** — picking an app as the workspace (in a CoS task, or Settings → Providers → Run Prompt) and asking the agent to create a file could put the file in the PortOS directory instead of your app. If the app's Repository Path was empty, mistyped, or pointed somewhere that no longer exists, PortOS quietly fell back to its own folder and said nothing, so the run looked like it had worked. Now PortOS names the directory it chose for every run and in the CoS task log; a run whose workspace doesn't exist stops with a message telling you which path to fix; and a CoS task whose app has no usable Repository Path is blocked before the agent starts, rather than turned loose in the PortOS checkout. A path saved as `~/Projects/MyApp` is also accepted. Troubleshooting steps — including why `PORTOS_WORKSPACE_ROOTS` is unrelated to this — are in `docs/TROUBLESHOOTING.md`.- **[issue-3193] OpenCode agents now run in the app you selected, not the PortOS folder** — even with a correct Repository Path, agents on an OpenCode provider wrote their files into the PortOS directory and reported the PortOS path as their working folder. OpenCode decides where it is by reading an environment variable that describes the folder PortOS itself was started in, rather than the folder it was actually handed, so the workspace you picked was quietly ignored — only on OpenCode, which is why Codex, Claude Code, and Gemini looked fine. PortOS now sets that variable to the real working directory everywhere it starts an agent, a provider run, a TUI session, or a terminal. Troubleshooting steps for telling this apart from a mistyped Repository Path are in `docs/TROUBLESHOOTING.md`.- **[issue-3180] Agent terminals on Windows get a working environment** — the environment filter for agent shell sessions was written for macOS/Linux and dropped variables Windows needs, including `Path` itself (Windows spells it mixed-case, which the filter didn't match), plus `SystemRoot`, `ComSpec`, `TEMP`, and the per-user `APPDATA` folders where the coding CLIs keep their configuration and credentials. Windows sessions now keep those while still withholding API keys and tokens.+- **An agent killed by a server restart now picks up where it left off instead of starting over.** Restarting PortOS kills every running agent mid-edit, and the task went back in the queue for a brand-new agent that built a fresh worktree from `main` — so hours of in-progress work sat on disk, untouched, while the replacement redid it from scratch. PortOS now records what the interrupted run left behind and hands the retry its actual working directory: its commits, its uncommitted edits, and its untracked files, exactly as they were. The retry is told up front that it's continuing someone else's run and to check `git status`, the commit log, and whether a PR was already opened or merged before writing any code. Work that already landed is still never resumed onto, and if the leftover folder can't be handed over for any reason the retry starts clean rather than failing to start.## Image generation- **Test Connection in Image Gen settings now tests the CLI whose tab you're on.** Pressing it from the Grok CLI or Agy CLI tab probed whichever backend was saved as the default instead — so an Agy test answered `codex — codex-cli 0.145.0`, which looked like Agy had somehow resolved to the Codex binary. The button now probes the provider for the open tab (Backend, Tokens, Expose, and Test still probe the saved default backend), and every result is shown only under the tab that asked for it — so a slow probe you left behind can't surface under the provider you switched to.diff --git a/server/services/agentCompletionCleanup.js b/server/services/agentCompletionCleanup.jsindex 81e2a8988f..272a14cca7 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, resolveResumeBranch } from './agentWorktreeCleanup.js';+import { cleanupAgentWorktree, spawnMergeRecoveryTask, recordTaskResumePointer } from './agentWorktreeCleanup.js';import { resolvePrCompletion } from '../lib/prDisposition.js';import { canTypeSlashCommands } from '../lib/slashdoInvocation.js';@@ -338,17 +338,17 @@ 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+ // A failed agent whose branch — or whole worktree — survived cleanup leaves+ // real work behind (see `preserveBranchWithCommits` in agentWorktreeCleanup.js;+ // a dirty tree aborts removal outright). Record where it lives on the TASK so+ // its retry 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.+ // record is in hand, and AFTER cleanup so it reflects what actually survived.+ // `recordTaskResumePointer` no-ops when there's nothing to resume, in which+ // case the metadata is left 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@@ -357,29 +357,11 @@ export async function runAgentCompletionCleanup({ agentId, task, agent, effectivif (!effectiveSuccess && task?.id) {const { getTaskById } = await import('./cos.js');const persisted = await getTaskById(task.id).catch(() => null);- const willRetry = (persisted?.status ?? 'pending') === 'pending';- // Reuse the `agentState` fetched at the top of this function rather than- // re-reading the record: `getAgent` on a now-completed agent re-reads and- // splits the whole output.txt transcript (hundreds of KB for a TUI run),- // and both fields here are stamped once at registerAgent and never mutated.- const { sourceWorkspace, worktreeBranch } = (willRetry && agentState?.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 ((persisted?.status ?? 'pending') === 'pending') {+ // `agentState` was fetched at the top of this function; its worktree fields+ // are stamped once at registerAgent and never mutated, so re-reading the+ // record here would only re-split the whole output.txt transcript.+ await recordTaskResumePointer({ task, agentId, agentMetadata: agentState?.metadata });}}diff --git a/server/services/agentCompletionCleanup.test.js b/server/services/agentCompletionCleanup.test.jsindex 4425fb1d84..75bd8435aa 100644--- a/server/services/agentCompletionCleanup.test.js+++ b/server/services/agentCompletionCleanup.test.js@@ -22,7 +22,11 @@ vi.mock('./cos.js', () => ({vi.mock('./jira.js', () => ({ getInstances: vi.fn(), addComment: vi.fn() }));vi.mock('./git.js', () => ({ push: vi.fn(), getRepoBranches: vi.fn(), generatePRDescription: vi.fn(), suggestPRTitle: vi.fn(), createPR: vi.fn(), checkout: vi.fn() }));vi.mock('./codeReview.js', () => ({ resolveReviewLoopOptions: vi.fn().mockResolvedValue({}) }));-vi.mock('./agentWorktreeCleanup.js', () => ({ cleanupAgentWorktree: vi.fn().mockResolvedValue([]), spawnMergeRecoveryTask: vi.fn() }));+vi.mock('./agentWorktreeCleanup.js', () => ({+ cleanupAgentWorktree: vi.fn().mockResolvedValue([]),+ spawnMergeRecoveryTask: vi.fn(),+ recordTaskResumePointer: vi.fn().mockResolvedValue(null),+}));vi.mock('./taskPromptService.js', () => ({ getStagePrompt: vi.fn().mockResolvedValue('do stage work in {appName}') }));import { handlePipelineProgression, runAgentCompletionCleanup } from './agentCompletionCleanup.js';diff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.jsindex 90425982c5..251e402d0d 100644--- a/server/services/agentLifecycle.js+++ b/server/services/agentLifecycle.js@@ -798,7 +798,12 @@ export async function handleAgentCompletion(agentId, exitCode, success, durationconst taskUpdate = await stampLiExecutionVerdict({ status: 'completed' }, task, { success });await updateTask(cosAgent.taskId, taskUpdate, task.taskType || 'user');} else {- await handleOrphanedTask(cosAgent.taskId, agentId, getTaskById);+ // Hand the dead run's metadata to the retry handler so it can resume what+ // was left behind. This path bypasses `finalizeAgent` (and its worktree+ // cleanup), so the worktree is still on disk, branch and all — without it+ // the retry builds a fresh tree off the default branch and redoes work+ // that is sitting right there.+ await handleOrphanedTask(cosAgent.taskId, agentId, getTaskById, { agentMetadata: cosAgent.metadata });// If orphan recovery settled the task into a terminal `blocked` state (retry budget// exhausted), the local completion already recorded the proposal failure — so stamp// the LI failure verdict here too (#2779, codex P2) or the originating peer woulddiff --git a/server/services/agentLifecycle.test.js b/server/services/agentLifecycle.test.jsindex 1bd9e06700..371877af4a 100644--- a/server/services/agentLifecycle.test.js+++ b/server/services/agentLifecycle.test.js@@ -272,9 +272,10 @@ describe('agentLifecycle — guard wiring', () => {it('the post-restart recovery completion path also stamps the LI verdict (#2779, codex P2)', () => {// A hand-off that finished while the server was down completes via this bypass, not// finalizeAgent — it must still stamp so the outcome federates to the originating peer.- const idx = AGENT_LIFECYCLE_SRC.indexOf('Completing untracked agent');- expect(idx, 'post-restart recovery branch must exist').toBeGreaterThan(-1);- const body = AGENT_LIFECYCLE_SRC.slice(idx, idx + 2000);+ // End-anchored on the statement that follows the branch rather than a fixed+ // char count: a fixed window silently shrinks its coverage every time the+ // branch grows, and a later addition pushed the assertions below out of it.+ const body = recoveryBranchSource();// Success path stamps a clean completion…expect(body).toMatch(/await stampLiExecutionVerdict\(\{ status: 'completed' \}, task, \{ success \}\)/);// …and the FAILURE path re-reads the task after orphan recovery and stamps the failure@@ -282,8 +283,29 @@ describe('agentLifecycle — guard wiring', () => {expect(body).toMatch(/settled\.status === 'blocked' && settled\.metadata\?\.liProposal/);expect(body).toMatch(/await stampLiExecutionVerdict\(\{\}, settled, \{ success: false \}\)/);});++ // This bypass never runs worktree cleanup, so the dead run's tree is still on+ // disk when the task is requeued. Without the dead agent's metadata,+ // handleOrphanedTask can't tell the retry what to resume, and it builds a fresh+ // worktree off the default branch and redoes work sitting right there.+ it('the post-restart recovery path hands the dead agent’s metadata to the retry handler', () => {+ const body = recoveryBranchSource();+ expect(body).toMatch(/handleOrphanedTask\([^)]*\{\s*agentMetadata: cosAgent\.metadata\s*\}\)/);+ });});+/**+ * Source of the post-restart recovery branch in handleAgentCompletion, sliced+ * between its opening log line and the first statement after it.+ */+function recoveryBranchSource() {+ const start = AGENT_LIFECYCLE_SRC.indexOf('Completing untracked agent');+ expect(start, 'post-restart recovery branch must exist').toBeGreaterThan(-1);+ const end = AGENT_LIFECYCLE_SRC.indexOf('const { task, runId, model', start);+ expect(end, 'end anchor (the statement after the branch) must exist').toBeGreaterThan(start);+ return AGENT_LIFECYCLE_SRC.slice(start, end);+}+// ─── Non-negotiable orderings inside runAgentSpawn (no behavioral seam) ──────//// These pin control-flow orderings that live inside the ~470-LOC guarded spawndiff --git a/server/services/agentManagement.js b/server/services/agentManagement.jsindex 6177a08d23..3164a4a97d 100644--- a/server/services/agentManagement.js+++ b/server/services/agentManagement.js@@ -18,7 +18,7 @@ import { activeAgents, runnerAgents, userTerminatedAgents, pausedAgents, useRunn// longer depends on the lifecycle orchestrator — which depends on THIS module// for handleOrphanedTask. Importing them from their own leaf modules is what// lets that edge be a plain static import instead of a dynamic-import dodge.-import { cleanupAgentWorktree } from './agentWorktreeCleanup.js';+import { cleanupAgentWorktree, resolveTaskResumePointer, resumePointerMetadata } from './agentWorktreeCleanup.js';import { syncRunnerAgents } from './agentRunnerSync.js';import { flushRunnerOutputBatcher } from './agentRunnerOutputBatchers.js';import { checkForTaskCommit } from './agentRunTracking.js';@@ -612,7 +612,11 @@ export async function cleanupOrphanedAgents() {cleanedCount++;if (agent.taskId) {- orphanedTaskIds.push({ taskId: agent.taskId, agentId: agent.id });+ // Carry the agent's metadata forward rather than re-reading the record+ // later: `getAgent` on a completed agent re-splits its whole output.txt+ // transcript, and the worktree fields the resume pointer needs are+ // stamped once at registerAgent and never mutated.+ orphanedTaskIds.push({ taskId: agent.taskId, agentId: agent.id, agentMetadata: agent.metadata });}}}@@ -635,9 +639,13 @@ export async function cleanupOrphanedAgents() {await settleOrphanedCreativeDirectorRun(task);}- // Handle orphaned tasks - reset for retry or create investigation task- for (const { taskId, agentId } of orphanedTaskIds) {- await handleOrphanedTask(taskId, agentId, getTask);+ // Handle orphaned tasks - reset for retry or create investigation task.+ // `agentMetadata` rides along so the retry can resume what this run left behind+ // (see handleOrphanedTask). Runs AFTER cleanupAgentWorktree above so the resume+ // pointer reflects what actually survived — a dirty tree aborts removal, leaving+ // the whole worktree in place.+ for (const { taskId, agentId, agentMetadata } of orphanedTaskIds) {+ await handleOrphanedTask(taskId, agentId, getTask, { agentMetadata });}// Trigger evaluation to spawn new agents for retried tasks@@ -655,8 +663,19 @@ export async function cleanupOrphanedAgents() {/*** Handle an orphaned task - retry or create investigation.+ *+ * Every path that retires a run whose process vanished funnels through here —+ * the boot/health-check orphan sweep, `resetOrphanedTasks`, and the post-restart+ * completion recovery — so the retry's resume pointer is resolved HERE rather than+ * at each call site. Callers that know which agent died pass its `agentMetadata`;+ * without it the retry simply starts clean, which is the pre-existing behavior.+ *+ * @param {object} [options]+ * @param {object} [options.agentMetadata] - the dead agent's registered metadata+ * (`isWorktree` / `sourceWorkspace` / `worktreeBranch` / `workspacePath`), used+ * to work out whether its branch or worktree is worth resuming.*/-export async function handleOrphanedTask(taskId, agentId, getTaskByIdFn) {+export async function handleOrphanedTask(taskId, agentId, getTaskByIdFn, { agentMetadata = null } = {}) {const task = await getTaskByIdFn(taskId).catch(() => null);if (!task) {emitLog('warn', `Could not find task ${taskId} for orphaned agent ${agentId}`, { taskId, agentId });@@ -717,13 +736,26 @@ export async function handleOrphanedTask(taskId, agentId, getTaskByIdFn) {maxRetries: MAX_ORPHAN_RETRIES});+ // Point the retry at whatever the dead run left behind — its branch, or the+ // whole worktree when the process died mid-edit and the uncommitted work is+ // still sitting in it. Folded into THIS write rather than stamped separately+ // beforehand: the flip to `pending` emits `tasks:changed`, which can spawn the+ // retry immediately, so a pointer written afterwards could land too late.+ // Fails open to "start clean": requeueing the task matters far more than+ // resuming it, and a throw here would strand it in_progress until the next sweep.+ const resume = await resolveTaskResumePointer({ task, agentId, agentMetadata }).catch(err => {+ emitLog('warn', `Resume pointer for task ${taskId} could not be resolved: ${err.message}`, { taskId, agentId });+ return null;+ });+await updateTask(taskId, {status: 'pending',metadata: {...task.metadata,orphanRetryCount: retryCount,lastOrphanedAt: new Date().toISOString(),- lastOrphanedAgentId: agentId+ lastOrphanedAgentId: agentId,+ ...resumePointerMetadata(resume, agentId, task)}}, taskType);} else if (inCooldown && retryCount < MAX_ORPHAN_RETRIES && !totalExceeded) {diff --git a/server/services/agentManagement.test.js b/server/services/agentManagement.test.jsindex 0fe7475745..308976d7dc 100644--- a/server/services/agentManagement.test.js+++ b/server/services/agentManagement.test.js@@ -45,7 +45,11 @@ vi.mock('./cos.js', () => ({updateTask: vi.fn().mockResolvedValue(true),addTask: vi.fn().mockResolvedValue({ id: 'sys-mocked' }),getTaskById: vi.fn(),- getAllTasks: vi.fn()+ getAllTasks: vi.fn(),+ // cleanupOrphanedAgents pulls these in via a dynamic import.+ getAgents: vi.fn().mockResolvedValue([]),+ completeAgent: vi.fn().mockResolvedValue(undefined),+ evaluateTasks: vi.fn().mockResolvedValue(undefined)}));vi.mock('./cosEvents.js', () => ({@@ -69,7 +73,12 @@ vi.mock('./agents.js', () => ({ unregisterSpawnedAgent: vi.fn() }));vi.mock('./executionLanes.js', () => ({ release: vi.fn() }));vi.mock('./toolStateMachine.js', () => ({ completeExecution: vi.fn(), errorExecution: vi.fn() }));vi.mock('./shell.js', () => ({ writeToSession: vi.fn(), killSession: vi.fn() }));-vi.mock('./agentWorktreeCleanup.js', () => ({ cleanupAgentWorktree: vi.fn() }));+vi.mock('./agentWorktreeCleanup.js', () => ({+ cleanupAgentWorktree: vi.fn(),+ resolveTaskResumePointer: vi.fn().mockResolvedValue(null),+ resumePointerMetadata: vi.fn().mockReturnValue({})+}));+vi.mock('./agentFinalization.js', () => ({ dispatchRecoveredTaskOutputHook: vi.fn().mockResolvedValue(undefined) }));vi.mock('./agentRunnerSync.js', () => ({ syncRunnerAgents: vi.fn().mockResolvedValue(0) }));vi.mock('./agentRunnerOutputBatchers.js', () => ({ flushRunnerOutputBatcher: vi.fn().mockResolvedValue(undefined) }));vi.mock('./worktreeManager.js', () => ({ cleanupOrphanedWorktrees: vi.fn() }));@@ -80,7 +89,9 @@ vi.mock('./creativeDirector/local.js', () => ({vi.mock('./creativeDirector/planAdvance.js', () => ({ advanceAfterPlanStepSettled: vi.fn().mockResolvedValue(undefined) }));vi.mock('./creativeDirector/completionHook.js', () => ({ advanceAfterSceneSettled: vi.fn().mockResolvedValue(undefined) }));-import { handleOrphanedTask, pauseAgent, settleOrphanedCreativeDirectorRun } from './agentManagement.js';+import { handleOrphanedTask, pauseAgent, settleOrphanedCreativeDirectorRun, cleanupOrphanedAgents } from './agentManagement.js';+import { cleanupAgentWorktree, resolveTaskResumePointer, resumePointerMetadata } from './agentWorktreeCleanup.js';+import { getAgents } from './cos.js';import { updateRun, getProject } from './creativeDirector/local.js';import { advanceAfterPlanStepSettled } from './creativeDirector/planAdvance.js';import { advanceAfterSceneSettled } from './creativeDirector/completionHook.js';@@ -769,3 +780,75 @@ describe('terminate/kill drains batched output before completion — source contexpect(flushPos).toBeLessThan(completePos);});});++// A server restart kills every agent PTY without running a completion hook, so+// the ONLY thing that retires those runs is this sweep. Before its retry carried a+// resume pointer, every restart-killed task was re-dispatched to a fresh agent+// with a fresh worktree, which redid work still sitting on disk.+describe('orphan retries resume what the dead run left behind', () => {+ const deadMetadata = { isWorktree: true, sourceWorkspace: '/repo', worktreeBranch: 'cos/task-1/agent-dead' };+ const deadAgent = { id: 'agent-dead', status: 'running', pid: null, taskId: 'task-1', metadata: deadMetadata };+ const pointer = { branchName: 'cos/task-1/agent-dead', worktreePath: '/w/agent-dead' };++ beforeEach(() => {+ vi.clearAllMocks();+ getAgents.mockResolvedValue([deadAgent]);+ getTaskById.mockResolvedValue({ id: 'task-1', taskType: 'user', status: 'in_progress', metadata: {} });+ resolveTaskResumePointer.mockResolvedValue(null);+ resumePointerMetadata.mockReturnValue({});+ activeAgents.clear();+ runnerAgents.clear();+ });++ it('hands the dead agent’s worktree metadata from the sweep to the retry handler', async () => {+ await cleanupOrphanedAgents();++ expect(resolveTaskResumePointer).toHaveBeenCalledWith({+ task: expect.objectContaining({ id: 'task-1' }),+ agentId: 'agent-dead',+ agentMetadata: deadMetadata+ });+ });++ // Ordering is the whole contract: the pointer must reflect what SURVIVED+ // cleanup, and must land in the SAME write that flips the task to pending —+ // that flip emits tasks:changed, which can spawn the retry immediately.+ it('resolves the pointer after worktree cleanup and writes it with the requeue', async () => {+ const order = [];+ cleanupAgentWorktree.mockImplementation(() => { order.push('cleanup'); });+ resolveTaskResumePointer.mockImplementation(() => { order.push('resolve'); return Promise.resolve(pointer); });+ resumePointerMetadata.mockReturnValue({ existingBranch: pointer.branchName, resumedFromAgentId: 'agent-dead', resumeWorktreePath: pointer.worktreePath });+ updateTask.mockImplementation(() => { order.push('requeue'); return Promise.resolve(true); });++ await cleanupOrphanedAgents();++ expect(order).toEqual(['cleanup', 'resolve', 'requeue']);+ expect(updateTask).toHaveBeenCalledWith('task-1', {+ status: 'pending',+ metadata: expect.objectContaining({+ existingBranch: pointer.branchName,+ resumedFromAgentId: 'agent-dead',+ resumeWorktreePath: pointer.worktreePath+ })+ }, 'user');+ });++ it('skips the resume entirely when the dead agent had no task', async () => {+ getAgents.mockResolvedValue([{ ...deadAgent, taskId: null }]);++ await cleanupOrphanedAgents();++ expect(resolveTaskResumePointer).not.toHaveBeenCalled();+ });++ // A caller that doesn't know which agent died (resetOrphanedTasks on an archived+ // agent) still requeues — it just starts clean.+ it('requeues without a pointer when no agent metadata is available', async () => {+ getTaskById.mockResolvedValue({ id: 'task-1', taskType: 'user', status: 'in_progress', metadata: {} });++ await handleOrphanedTask('task-1', 'unknown-reset', getTaskById);++ expect(resolveTaskResumePointer).toHaveBeenCalledWith(expect.objectContaining({ agentMetadata: null }));+ expect(updateTask).toHaveBeenCalledWith('task-1', expect.objectContaining({ status: 'pending' }), 'user');+ });+});diff --git a/server/services/agentPromptBuilder.js b/server/services/agentPromptBuilder.jsindex ec283fbcfd..70306809c0 100644--- a/server/services/agentPromptBuilder.js+++ b/server/services/agentPromptBuilder.js@@ -958,32 +958,43 @@ function isResumedWorktree(task, worktreeInfo) {}/**- * Resume banner for a retry attached to the branch a PREVIOUS failed agent left+ * Resume banner for a retry picking up what a PREVIOUS unfinished agent left* behind (`metadata.existingBranch` + `resumedFromAgentId`, stamped by- * agentCompletionCleanup.js when a failed run's branch survived cleanup with- * commits on it).+ * `recordTaskResumePointer` when a dead run's branch — or whole worktree —+ * survived cleanup).** 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+ * work in it and redoes what 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.*+ * An ADOPTED worktree (`worktreeInfo.adopted` — the shape a server restart leaves,+ * killed mid-edit before committing) additionally carries the dead run's+ * uncommitted edits and untracked files, so the banner points at `git status`+ * as the primary record rather than the commit log.+ ** 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;+ const carriedWork = worktreeInfo.adopted+ ? `**You are in its actual working directory** — its commits are on your branch \`${worktreeInfo.branchName}\`+AND any edits it had not committed yet are still in your working tree, exactly as it left them.`+ : `**Its commits are already on your branch** \`${worktreeInfo.branchName}\` — you are+continuing its run, not starting over.`;return `## Resuming Unfinished Work — Read This FirstA 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.+(it hung, timed out, or was terminated — a server restart kills runs mid-edit).+${carriedWork}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.+1. \`git status\` — anything it left uncommitted. Treat these as YOUR in-progress+ changes: review them, finish them, and commit them. Do not discard them wholesale.+2. \`git log --oneline ${worktreeInfo.baseBranch || 'origin/HEAD'}..HEAD\` — the commits it already made.3. Check whether it already shipped: look for an open or merged PR for this branch— \`gh pr list --head ${worktreeInfo.branchName} --state all\` on GitHub,\`glab mr list --source-branch ${worktreeInfo.branchName}\` on GitLab.diff --git a/server/services/agentWorkspacePrep.js b/server/services/agentWorkspacePrep.jsindex 1da8013f1a..2fa6d01ade 100644--- a/server/services/agentWorkspacePrep.js+++ b/server/services/agentWorkspacePrep.js@@ -33,7 +33,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 } from './worktreeManager.js';+import { createWorktree, adoptWorktree } from './worktreeManager.js';import { resolveSpawnCwd } from '../lib/spawnCwd.js';import { getAppWorkspace, getAppDataForTask, createJiraTicketForTask } from './agentPromptBuilder.js';@@ -215,9 +215,31 @@ export async function prepareAgentWorkspace({ agentId, task }) {});}- worktreeInfo = await createWorktree(agentId, workspacePath, task.id, {+ // Resume path: the run this task is retrying left a worktree behind (its+ // process died mid-edit, so `removeWorktree` refused to delete the dirty+ // tree — see recordTaskResumePointer). Adopt it, which carries the+ // uncommitted edits and untracked files no branch pointer can, instead of+ // building a fresh tree and redoing that work.+ const resumeWorktreePath = existingBranch ? task.metadata?.resumeWorktreePath : null;+ const adopted = resumeWorktreePath+ ? await adoptWorktree(agentId, workspacePath, resumeWorktreePath, existingBranch).catch(err => {+ emitLog('warn', `🌳 Could not adopt worktree ${resumeWorktreePath} for task ${task.id}: ${err.message}`, { taskId: task.id });+ return null;+ })+ : null;++ // Adoption failing while the stale tree is STILL on disk means the branch is+ // checked out there, so attaching a second worktree to it would fail with+ // "already checked out" and block the task outright. Fail open — start clean,+ // the same polarity resolveResumePointer uses — rather than not spawning.+ const branchStillClaimed = !adopted && resumeWorktreePath && existsSync(resumeWorktreePath);+ if (branchStillClaimed) {+ emitLog('warn', `🌳 Worktree ${resumeWorktreePath} could not be adopted and still holds ${existingBranch} — task ${task.id} starts from a clean branch`, { taskId: task.id });+ }++ worktreeInfo = adopted || await createWorktree(agentId, workspacePath, task.id, {baseBranch: detectedBase || undefined,- existingBranch: existingBranch || undefined,+ existingBranch: branchStillClaimed ? undefined : (existingBranch || undefined),planId: task.metadata?.planId || undefined}).catch(err => {emitLog('warn', `🌳 Worktree creation failed, using shared workspace: ${err.message}`, { taskId: task.id });@@ -226,7 +248,10 @@ export async function prepareAgentWorkspace({ agentId, task }) {if (worktreeInfo) {workspacePath = worktreeInfo.worktreePath;- emitLog('success', `🌳 Agent ${agentId} will work in worktree: ${worktreeInfo.branchName} (base: ${worktreeInfo.baseBranch})`, {+ const origin = worktreeInfo.adopted+ ? `adopted from ${task.metadata?.resumedFromAgentId || 'the interrupted run'}`+ : `base: ${worktreeInfo.baseBranch}`;+ emitLog('success', `🌳 Agent ${agentId} will work in worktree: ${worktreeInfo.branchName} (${origin})`, {agentId, worktreePath: worktreeInfo.worktreePath, branchName: worktreeInfo.branchName, baseBranch: worktreeInfo.baseBranch});} else {diff --git a/server/services/agentWorkspacePrep.test.js b/server/services/agentWorkspacePrep.test.jsindex 974d934ebd..08e4c1bb65 100644--- a/server/services/agentWorkspacePrep.test.js+++ b/server/services/agentWorkspacePrep.test.js@@ -27,7 +27,7 @@ vi.mock('./git.js', () => ({createBranch: vi.fn(),}));vi.mock('./taskConflict.js', () => ({ detectConflicts: vi.fn().mockResolvedValue({ recommendation: 'proceed' }) }));-vi.mock('./worktreeManager.js', () => ({ createWorktree: vi.fn(), mergeBaseIntoFeatureWorktree: vi.fn() }));+vi.mock('./worktreeManager.js', () => ({ 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),@@ -38,6 +38,7 @@ import { prepareAgentWorkspace } from './agentWorkspacePrep.js';import { ensureLatest } from './git.js';import { detectConflicts } from './taskConflict.js';import { getAppWorkspace } from './agentPromptBuilder.js';+import { createWorktree, adoptWorktree } from './worktreeManager.js';beforeEach(() => { vi.clearAllMocks(); });@@ -124,3 +125,87 @@ describe('prepareAgentWorkspace — workspace validation (#3180)', () => {expect(r.workspacePath).toBe(process.cwd());});});++// A run killed by a server restart never reaches its completion hook, so its+// worktree survives with UNCOMMITTED work in it. The retry must pick that tree+// up instead of building a fresh one off the default branch and redoing it.+describe('prepareAgentWorkspace — resuming an interrupted run', () => {+ const DEAD_TREE = '/mock/worktrees/agent-dead';+ const resumeTask = (extra = {}) => ({+ id: 't-resume', taskType: 'user',+ metadata: {+ useWorktree: true,+ existingBranch: 'cos/t-resume/agent-dead',+ resumedFromAgentId: 'agent-dead',+ resumeWorktreePath: DEAD_TREE,+ ...extra+ }+ });++ beforeEach(() => { ensureLatest.mockResolvedValue({ success: true, upToDate: true }); });++ it('adopts the interrupted run’s worktree instead of creating a new one', async () => {+ adoptWorktree.mockResolvedValue({+ worktreePath: '/mock/worktrees/agent-new', branchName: 'cos/t-resume/agent-dead',+ baseBranch: null, existingBranch: true, adopted: true+ });++ const r = await prepareAgentWorkspace({ agentId: 'agent-new', task: resumeTask() });++ expect(adoptWorktree).toHaveBeenCalledWith('agent-new', expect.any(String), DEAD_TREE, 'cos/t-resume/agent-dead');+ expect(createWorktree).not.toHaveBeenCalled();+ expect(r.outcome).toBe('ready');+ expect(r.worktreeInfo.adopted).toBe(true);+ expect(r.workspacePath).toBe('/mock/worktrees/agent-new');+ });++ // The tree is gone (already cleaned up) but the branch survived — attach to it,+ // which is the pre-existing resume shape.+ it('falls back to attaching the branch when the leftover tree is gone', async () => {+ adoptWorktree.mockResolvedValue(null);+ createWorktree.mockResolvedValue({+ worktreePath: '/mock/worktrees/agent-new', branchName: 'cos/t-resume/agent-dead',+ baseBranch: null, existingBranch: true+ });++ const r = await prepareAgentWorkspace({ agentId: 'agent-new', task: resumeTask() });++ expect(createWorktree).toHaveBeenCalledWith('agent-new', expect.any(String), 't-resume',+ expect.objectContaining({ existingBranch: 'cos/t-resume/agent-dead' }));+ expect(r.outcome).toBe('ready');+ });++ // Git allows a branch in only ONE worktree. If adoption failed while the stale+ // tree is still on disk holding the branch, attaching a second worktree to it+ // errors out and the task is blocked entirely — worse than starting clean.+ it('starts clean when adoption fails and the stale tree still holds the branch', async () => {+ // Any real directory stands in for the stale tree — the production check is a+ // bare `existsSync`, so `cwd` is enough and leaves nothing behind to clean up.+ const stillThere = process.cwd();+ adoptWorktree.mockResolvedValue(null);+ createWorktree.mockResolvedValue({+ worktreePath: '/mock/worktrees/agent-new', branchName: 'cos/t-resume/agent-new', baseBranch: 'main'+ });++ const r = await prepareAgentWorkspace({+ agentId: 'agent-new', task: resumeTask({ resumeWorktreePath: stillThere })+ });++ expect(createWorktree).toHaveBeenCalledWith('agent-new', expect.any(String), 't-resume',+ expect.objectContaining({ existingBranch: undefined }));+ expect(r.outcome).toBe('ready');+ });++ it('ignores a stale worktree pointer with no branch to resume', async () => {+ createWorktree.mockResolvedValue({+ worktreePath: '/mock/worktrees/agent-new', branchName: 'cos/t-resume/agent-new', baseBranch: 'main'+ });++ await prepareAgentWorkspace({+ agentId: 'agent-new', task: resumeTask({ existingBranch: undefined })+ });++ expect(adoptWorktree).not.toHaveBeenCalled();+ expect(createWorktree).toHaveBeenCalled();+ });+});diff --git a/server/services/agentWorktreeCleanup.js b/server/services/agentWorktreeCleanup.jsindex 972b2c1372..11bf7ef055 100644--- a/server/services/agentWorktreeCleanup.js+++ b/server/services/agentWorktreeCleanup.js@@ -14,11 +14,12 @@* from there).*/+import { existsSync } from 'fs';import { join } from 'path';import { emitLog } from './cosEvents.js';-import { addTask } from './cos.js';+import { addTask, updateTask } from './cos.js';import * as git from './git.js';-import { removeWorktree } from './worktreeManager.js';+import { removeWorktree, classifyWorktreeDirt } from './worktreeManager.js';import { isTruthyMeta } from './agentState.js';import { PATHS } from '../lib/fileUtils.js';import { RECOVERY_TASK_PREFIX } from './recoveryTasks.js';@@ -280,34 +281,39 @@ export async function cleanupAgentWorktree(agentId, success, { openPR = false, p}/**- * 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.+ * What, if anything, should a retry of this task pick up from the run that just+ * died? Called after cleanup has decided what to preserve, so the answer reflects+ * what's actually on disk rather than what we hoped.*- * Returns the branch name to resume, or null when there is nothing to resume —- * no branch, a branch that holds nothing the default branch doesn't already- * have, or one still checked out in a preserved worktree (unattachable). A null- * answer means the retry should start clean, which is the correct behavior for an- * agent that failed before committing anything.+ * Two shapes of leftover work, in priority order:+ *+ * 1. **Adopt the worktree** — `{ branchName, worktreePath }`. The dead agent's+ * own worktree survived cleanup (a dirty tree aborts removal) and is still on+ * its branch. This is the shape a server restart leaves behind: the run is+ * killed mid-edit, so its work is UNCOMMITTED and no branch pointer can carry+ * it. The retry moves that tree to its own directory (see `adoptWorktree`).+ * 2. **Attach the branch** — `{ branchName, worktreePath: null }`. The worktree+ * is gone but the branch survived with unmerged commits, so a fresh worktree+ * attaches to it via `createWorktree`'s `existingBranch` path.+ *+ * Returns null when there is nothing to resume — no branch, no leftover work, or+ * a branch whose commits already landed. A null answer means "start clean", the+ * correct behavior for an agent that died before producing 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.+ *+ * @param {string} sourceWorkspace - the parent git repository+ * @param {string} branchName - the dead agent's worktree branch+ * @param {string} [worktreePath] - the dead agent's worktree directory, the+ * adoption candidate. Omit to consider only the branch-attach shape.+ * @returns {Promise<{branchName: string, worktreePath: string|null}|null>}*/-export async function resolveResumeBranch(sourceWorkspace, branchName) {+export async function resolveResumePointer(sourceWorkspace, branchName, worktreePath = null) {if (!sourceWorkspace || !branchName) return null;- // Git allows a branch to be checked out in only ONE worktree, so if the dead- // agent's worktree is STILL on this branch, `git worktree add <path> <branch>`- // fails with "already checked out" and the retry can't spawn at all — worse- // than restarting clean. That combination is exactly what this change makes- // more likely: removeWorktree preserves the worktree (not just the branch)- // whenever the tree was dirty, so the branch stays claimed. Don't point a retry- // at a branch it cannot attach to.- const claimed = await git.getWorktreeBranches(sourceWorkspace).catch(() => null);- if (claimed?.has(branchName)) {- emitLog('info', `🌳 Branch ${branchName} is still checked out in a preserved worktree — a retry can't attach to it, so it will start clean`, { branchName });- return null;- }++ const survivingTree = !!(worktreePath && existsSync(worktreePath));const target = await git.getDefaultBranch(sourceWorkspace).catch(() => null) || 'main';// Same predicate `removeWorktree` used to decide whether to KEEP this branch, so// the two can't disagree and orphan it. `isBranchMergedInto` (not a rev-list@@ -317,12 +323,150 @@ export async function resolveResumeBranch(sourceWorkspace, branchName) {// clean), because a wrong resume makes an agent build on a merged branch while a// wrong clean start merely repeats work the branch still holds for a human.const merged = await git.isBranchMergedInto(sourceWorkspace, branchName, target).catch(() => true);+ // Nothing survived and nothing is unmerged — the common "run finished, branch+ // landed, tree already reaped" shape. Bail before spending any more git calls.+ if (merged && !survivingTree) return null;++ // How many commits the branch holds that the default branch doesn't. Only ever+ // consulted on one of the two mutually exclusive paths below, so it costs a+ // single call per resolution.+ const commitsAhead = async () =>+ (await git.getBranchComparison(sourceWorkspace, target, branchName).catch(() => null))?.ahead || 0;++ // 1. Adopt the surviving tree — but only if it is actually on the branch we're+ // resuming; a half-cleaned or repurposed directory must not be handed over.+ if (survivingTree && await git.getBranch(worktreePath).catch(() => null) === branchName) {+ if (!merged) {+ emitLog('info', `🌳 Worktree ${worktreePath} survived on unmerged ${branchName} — a retry can adopt it`, { branchName, worktreePath });+ return { branchName, worktreePath };+ }+ // A merged branch reads that way for two very different reasons. Commits that+ // already LANDED (ahead > 0) must never be resumed onto — that's the+ // agent-d2ae0352 incident. A branch that never committed at all (ahead === 0)+ // has nothing to duplicate, so an uncommitted tree on top of it is safe to+ // adopt — and that is exactly the restart case this function exists for:+ // killed mid-edit, zero commits, hours of uncommitted work.+ if (await commitsAhead() > 0) return null;+ // Same dirt classifier `removeWorktree` uses, so "worth preserving" and "worth+ // resuming" can't disagree: lockfile churn an agent never meant to commit is+ // not work, and a tree holding only that should start clean.+ const status = await git.getStatus(worktreePath).catch(() => null);+ if (!classifyWorktreeDirt(status?.porcelain).hasRealChanges) return null;+ emitLog('info', `🌳 Worktree ${worktreePath} survived on ${branchName} — a retry can adopt it and keep its uncommitted work`, { branchName, worktreePath });+ return { branchName, worktreePath };+ }+if (merged) return null;++ // 2. Attach a fresh worktree to the branch. Git allows a branch to be checked out+ // in only ONE worktree, so if a worktree is STILL on this branch, `git worktree+ // add <path> <branch>` fails with "already checked out" and the retry can't+ // spawn at all — worse than restarting clean. The adoption path above already+ // handled the dead agent's OWN worktree; anything else holding the branch is+ // not ours to move.+ const claimed = await git.getWorktreeBranches(sourceWorkspace).catch(() => null);+ if (claimed?.has(branchName)) {+ emitLog('info', `🌳 Branch ${branchName} is still checked out in a preserved worktree — a retry can't attach to it, so it will start clean`, { branchName });+ return null;+ }// Confirm the branch actually exists and holds commits — `isBranchMergedInto`// reports an ABSENT branch as unmerged, which would hand back a branch name no// worktree can attach to.- const comparison = await git.getBranchComparison(sourceWorkspace, target, branchName).catch(() => null);- return comparison?.ahead > 0 ? branchName : null;+ return await commitsAhead() > 0 ? { branchName, worktreePath: null } : null;+}++/**+ * What a retry of `task` can pick up from the run that just died, or null when it+ * should start clean. Resolves only — see `recordTaskResumePointer` to persist it+ * and `resumePointerMetadata` for the task patch.+ *+ * Every path that retires a dead run funnels through here so the "can this be+ * resumed?" question has one answer:+ * - `handleAgentCompletion` (agentCompletionCleanup.js) — the agent failed and+ * its completion hook ran normally.+ * - `handleOrphanedTask` (agentManagement.js) — the agent's process vanished+ * (server restart / crash), so no completion hook ever ran. That path is why+ * this is shared: a restart-killed run was requeued with no pointer at all,+ * and its replacement redid work that was already sitting on disk.+ *+ * @param {{task: object, agentId: string, agentMetadata: object}} params+ * @returns {Promise<{branchName: string, worktreePath: string|null}|null>}+ */+export async function resolveTaskResumePointer({ task, agentId, agentMetadata }) {+ if (!task?.id || !agentId) return null;+ // Persistent feature-agent worktrees are never torn down, and throwaway+ // reasoning worktrees are deliberately discarded — neither leaves work to resume.+ if (!agentMetadata?.isWorktree || agentMetadata?.isPersistentWorktree) return null;+ if (isTruthyMeta(task.metadata?.discardWorktree)) return null;++ // The agent's own recorded path is authoritative; the `<worktrees>/<agentId>`+ // convention is the fallback for a record written before it was stamped (same+ // idiom cleanupAgentWorktree uses for the PR push).+ const worktreePath = agentMetadata.workspacePath || join(PATHS.worktrees, agentId);+ const pointer = await resolveResumePointer(agentMetadata.sourceWorkspace, agentMetadata.worktreeBranch, worktreePath)+ .catch(err => {+ emitLog('warn', `Failed to resolve resume pointer for ${agentId}: ${err.message}`, { agentId });+ return null;+ });+ if (!pointer) return null;++ emitLog('info', `🔁 Task ${task.id} will resume ${pointer.worktreePath ? `in the worktree ${agentId} left behind` : `from ${pointer.branchName}`} instead of restarting`, {+ taskId: task.id, agentId, branchName: pointer.branchName, worktreePath: pointer.worktreePath+ });+ return pointer;+}++/**+ * The task-metadata patch that makes a retry resume (or stop resuming).+ *+ * `existingBranch` is the flag agentWorkspacePrep already honors to attach a+ * worktree to a pre-existing branch (the review-loop follow-up uses it), and+ * `resumeWorktreePath` is honored there too, so resuming needs no new spawn+ * plumbing. `resumedFromAgentId` records whose run is being continued — it drives+ * the prompt's resume banner and is the marker that distinguishes a resume from+ * the follow-up (see `isPrBranchWorktree` in agentPromptBuilder.js).+ *+ * With no pointer, a previously-stamped resume is CLEARED: its branch may since+ * have been merged or deleted, and leaving the pointer would attach the next+ * attempt to landed work. Keyed on `resumedFromAgentId` so it only ever clears a+ * pointer this mechanism wrote — the review-loop follow-up's own `existingBranch`+ * is its whole reason for existing and must survive being orphaned.+ *+ * @param {{branchName: string, worktreePath: string|null}|null} pointer+ * @param {string} agentId - the run being resumed from+ * @param {object} task - the task being retried (read for a prior pointer)+ * @returns {object} metadata patch to merge into an `updateTask` call+ */+export function resumePointerMetadata(pointer, agentId, task) {+ if (pointer) {+ return {+ existingBranch: pointer.branchName,+ resumedFromAgentId: agentId,+ resumeWorktreePath: pointer.worktreePath+ };+ }+ if (!task?.metadata?.resumedFromAgentId) return {};+ return { existingBranch: null, resumedFromAgentId: null, resumeWorktreePath: null };+}++/**+ * Resolve AND persist the resume pointer. For callers that aren't already writing+ * the task; `handleOrphanedTask` folds the patch into its own retry write instead,+ * so the pointer can't land after the status flip that makes the task spawnable.+ *+ * @param {{task: object, agentId: string, agentMetadata: object}} params+ * @returns {Promise<{branchName: string, worktreePath: string|null}|null>}+ */+export async function recordTaskResumePointer({ task, agentId, agentMetadata }) {+ const pointer = await resolveTaskResumePointer({ task, agentId, agentMetadata });+ if (!pointer) return null;++ await updateTask(task.id, {+ metadata: resumePointerMetadata(pointer, agentId, task)+ }, task.taskType || 'user').catch(err => {+ emitLog('warn', `Failed to record resume pointer for task ${task.id}: ${err.message}`, { taskId: task.id, agentId });+ });+ return pointer;}/**diff --git a/server/services/cleanupAgentWorktree.test.js b/server/services/cleanupAgentWorktree.test.jsindex 56aa501fb7..664df1d9ba 100644--- a/server/services/cleanupAgentWorktree.test.js+++ b/server/services/cleanupAgentWorktree.test.js@@ -153,10 +153,13 @@ vi.mock('./taskConflict.js', () => ({detectConflicts: vi.fn(() => [])}));-vi.mock('./worktreeManager.js', () => ({+vi.mock('./worktreeManager.js', async (importOriginal) => ({createWorktree: vi.fn(),removeWorktree: vi.fn().mockResolvedValue(undefined),- cleanupOrphanedWorktrees: vi.fn()+ cleanupOrphanedWorktrees: vi.fn(),+ // Real: the resume path's "is this dirt real work?" answer must be the SAME+ // classifier removeWorktree preserves a tree on, and it's a pure function.+ classifyWorktreeDirt: (await importOriginal()).classifyWorktreeDirt}));vi.mock('./jira.js', () => ({@@ -172,8 +175,11 @@ vi.mock('./git.js', () => ({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.+ // resolveResumePointer reports it as resumable. Tests override per case.getBranchComparison: vi.fn().mockResolvedValue({ ahead: 2, commits: [], stats: {} }),+ // Read off a SURVIVING worktree when deciding whether a retry can adopt it.+ getBranch: vi.fn().mockResolvedValue(''),+ getStatus: vi.fn().mockResolvedValue({ clean: true, files: [] }),// Default: no branch is claimed by a surviving worktree, so an ahead branch is// attachable. The "still checked out" test overrides this.getWorktreeBranches: vi.fn().mockResolvedValue(new Set()),@@ -203,10 +209,13 @@ vi.mock('./runner.js', () => ({// --- Import the function under test and the mocked dependencies ---+import { join } from 'path';+import { existsSync as existsSyncMock } from 'fs';import { cleanupAgentWorktree, spawnMergeRecoveryTask, spawnReviewLoopFollowUp } from './subAgentSpawner.js';-import { resolveResumeBranch } from './agentWorktreeCleanup.js';-import { getAgent, addTask } from './cos.js';+import { resolveResumePointer, recordTaskResumePointer, resumePointerMetadata } from './agentWorktreeCleanup.js';+import { getAgent, addTask, updateTask } from './cos.js';import { removeWorktree } from './worktreeManager.js';+import { PATHS } from '../lib/fileUtils.js';import * as git from './git.js';// Helper: build a mock agent state for worktree agents@@ -939,12 +948,16 @@ describe('cleanupAgentWorktree - openPR path', () => {});});-describe('resolveResumeBranch', () => {+const DEAD_BRANCH = 'cos/task-1/agent-x';+const DEAD_TREE = join(PATHS.worktrees, 'agent-x');++describe('resolveResumePointer', () => {beforeEach(() => {vi.clearAllMocks();git.getDefaultBranch.mockResolvedValue('main');git.getWorktreeBranches.mockResolvedValue(new Set());git.isBranchMergedInto.mockResolvedValue(false);+ existsSyncMock.mockReturnValue(false);});// The incident shape: PortOS merges with `--rebase` by default, so a landed@@ -954,43 +967,47 @@ describe('resolveResumeBranch', () => {git.isBranchMergedInto.mockResolvedValue(true);git.getBranchComparison.mockResolvedValue({ ahead: 6, commits: [], stats: {} });- await expect(resolveResumeBranch('/repo', 'cos/task-1/agent-x')).resolves.toBeNull();+ await expect(resolveResumePointer('/repo', DEAD_BRANCH)).resolves.toBeNull();});it('fails OPEN (no resume) when the merged check errors', async () => {git.isBranchMergedInto.mockRejectedValue(new Error('git exploded'));- await expect(resolveResumeBranch('/repo', 'cos/task-1/agent-x')).resolves.toBeNull();+ await expect(resolveResumePointer('/repo', DEAD_BRANCH)).resolves.toBeNull();});- it('returns null when the branch is still checked out in a preserved worktree', async () => {+ it('returns null when the branch is still checked out in a worktree that is not the dead agent’s', async () => {// A dirty tree makes removeWorktree preserve the WORKTREE too, so the branch// stays claimed. `git worktree add` would fail "already checked out", which is// worse for the retry than starting clean.- git.getWorktreeBranches.mockResolvedValue(new Set(['cos/task-1/agent-x']));+ git.getWorktreeBranches.mockResolvedValue(new Set([DEAD_BRANCH]));git.getBranchComparison.mockResolvedValue({ ahead: 5, commits: [], stats: {} });- await expect(resolveResumeBranch('/repo', 'cos/task-1/agent-x')).resolves.toBeNull();+ await expect(resolveResumePointer('/repo', DEAD_BRANCH, DEAD_TREE)).resolves.toBeNull();});it('still resumes when a DIFFERENT branch is checked out elsewhere', async () => {git.getWorktreeBranches.mockResolvedValue(new Set(['main', 'cos/task-9/agent-z']));git.getBranchComparison.mockResolvedValue({ ahead: 2, commits: [], stats: {} });- await expect(resolveResumeBranch('/repo', 'cos/task-1/agent-x')).resolves.toBe('cos/task-1/agent-x');+ await expect(resolveResumePointer('/repo', DEAD_BRANCH)).resolves.toEqual({+ branchName: DEAD_BRANCH, worktreePath: null+ });});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');+ await expect(resolveResumePointer('/repo', DEAD_BRANCH)).resolves.toEqual({+ branchName: DEAD_BRANCH, worktreePath: null+ });+ expect(git.getBranchComparison).toHaveBeenCalledWith('/repo', 'main', DEAD_BRANCH);});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();+ await expect(resolveResumePointer('/repo', DEAD_BRANCH)).resolves.toBeNull();});it('returns null for an absent branch (empty comparison), not a phantom resume', async () => {@@ -998,18 +1015,18 @@ describe('resolveResumeBranch', () => {// back with ahead: 0 rather than throwing.git.getBranchComparison.mockResolvedValue({ ahead: 0, commits: [], stats: {} });- await expect(resolveResumeBranch('/repo', 'cos/gone')).resolves.toBeNull();+ await expect(resolveResumePointer('/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();+ await expect(resolveResumePointer('/repo', DEAD_BRANCH)).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();+ await expect(resolveResumePointer(null, DEAD_BRANCH)).resolves.toBeNull();+ await expect(resolveResumePointer('/repo', null)).resolves.toBeNull();expect(git.getBranchComparison).not.toHaveBeenCalled();});@@ -1017,8 +1034,189 @@ describe('resolveResumeBranch', () => {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');+ await expect(resolveResumePointer('/repo', DEAD_BRANCH)).resolves.toEqual({+ branchName: DEAD_BRANCH, worktreePath: null+ });+ expect(git.getBranchComparison).toHaveBeenCalledWith('/repo', 'main', DEAD_BRANCH);+ });++ // --- Worktree adoption (the server-restart shape) ---++ // Each adoption case varies exactly one of these; the rest is the shape of "a+ // worktree survived on this branch".+ function scriptSurvivingTree({ merged = false, ahead = 0, branch = DEAD_BRANCH, porcelain = ' M a.js\n' } = {}) {+ existsSyncMock.mockReturnValue(true);+ git.isBranchMergedInto.mockResolvedValue(merged);+ git.getBranchComparison.mockResolvedValue({ ahead, commits: [], stats: {} });+ git.getBranch.mockResolvedValue(branch);+ git.getStatus.mockResolvedValue({ clean: !porcelain, files: [], porcelain });+ }++ // The restart case: the run is killed mid-edit, so it has ZERO commits (the+ // branch reads as merged) and everything it did is uncommitted. Discarding that+ // tree is exactly the "redo the work" bug — adopt it instead.+ it('adopts the dead agent’s surviving worktree when it holds uncommitted work, even with no commits', async () => {+ scriptSurvivingTree({ merged: true, ahead: 0 });++ await expect(resolveResumePointer('/repo', DEAD_BRANCH, DEAD_TREE)).resolves.toEqual({+ branchName: DEAD_BRANCH, worktreePath: DEAD_TREE+ });+ });++ it('adopts a surviving worktree whose branch holds unmerged commits even when the tree is clean', async () => {+ scriptSurvivingTree({ merged: false, ahead: 2, porcelain: '' });++ await expect(resolveResumePointer('/repo', DEAD_BRANCH, DEAD_TREE)).resolves.toEqual({+ branchName: DEAD_BRANCH, worktreePath: DEAD_TREE+ });+ });++ // The landed-work guard has to survive the adopt path too, or a run reaped just+ // after its PR merged would hand its replacement the merged tree to build on.+ it('does NOT adopt when the branch’s commits already landed', async () => {+ scriptSurvivingTree({ merged: true, ahead: 4 });++ await expect(resolveResumePointer('/repo', DEAD_BRANCH, DEAD_TREE)).resolves.toBeNull();+ });++ it('does NOT adopt a directory that has been repurposed onto another branch', async () => {+ scriptSurvivingTree({ ahead: 3, branch: 'some/other-branch' });+ git.getWorktreeBranches.mockResolvedValue(new Set());++ // Falls through to the branch-attach shape rather than handing over the tree.+ await expect(resolveResumePointer('/repo', DEAD_BRANCH, DEAD_TREE)).resolves.toEqual({+ branchName: DEAD_BRANCH, worktreePath: null+ });+ });++ it('returns null for a clean surviving worktree with nothing to contribute', async () => {+ scriptSurvivingTree({ merged: true, ahead: 0, porcelain: '' });++ await expect(resolveResumePointer('/repo', DEAD_BRANCH, DEAD_TREE)).resolves.toBeNull();+ });++ // Same classifier removeWorktree uses to decide a tree is safe to delete — the+ // two must agree, or a tree it would have discarded reads as resumable work.+ it('treats lockfile-only churn as nothing to resume', async () => {+ scriptSurvivingTree({ merged: true, ahead: 0, porcelain: ' M package-lock.json\n' });++ await expect(resolveResumePointer('/repo', DEAD_BRANCH, DEAD_TREE)).resolves.toBeNull();+ });++ // The ordinary shape — run finished, branch landed, tree already reaped — must+ // not pay for the branch comparison (two git subprocesses, one a whole-branch diff).+ it('bails before the branch comparison when nothing survived and the branch is merged', async () => {+ git.isBranchMergedInto.mockResolvedValue(true);++ await expect(resolveResumePointer('/repo', DEAD_BRANCH, DEAD_TREE)).resolves.toBeNull();+ expect(git.getBranchComparison).not.toHaveBeenCalled();+ });+});++describe('resolveTaskResumePointer / recordTaskResumePointer', () => {+ const agentMetadata = {+ isWorktree: true, sourceWorkspace: '/repo',+ worktreeBranch: DEAD_BRANCH, workspacePath: DEAD_TREE+ };++ beforeEach(() => {+ vi.clearAllMocks();+ git.getDefaultBranch.mockResolvedValue('main');+ git.getWorktreeBranches.mockResolvedValue(new Set());+ git.isBranchMergedInto.mockResolvedValue(false);+ git.getBranchComparison.mockResolvedValue({ ahead: 2, commits: [], stats: {} });+ existsSyncMock.mockReturnValue(false);+ });++ it('stamps the branch, the prior agent, and a null worktree path for a branch-only resume', async () => {+ const task = { id: 'task-1', taskType: 'user', metadata: {} };++ await recordTaskResumePointer({ task, agentId: 'agent-x', agentMetadata });++ expect(updateTask).toHaveBeenCalledWith('task-1', {+ metadata: {+ existingBranch: DEAD_BRANCH,+ resumedFromAgentId: 'agent-x',+ resumeWorktreePath: null+ }+ }, 'user');+ });++ it('stamps the worktree path when the dead agent’s tree survived', async () => {+ existsSyncMock.mockReturnValue(true);+ git.getBranch.mockResolvedValue(DEAD_BRANCH);+ git.getStatus.mockResolvedValue({ clean: false, files: [], porcelain: ' M a.js\n' });+ const task = { id: 'task-1', taskType: 'user', metadata: {} };++ await recordTaskResumePointer({ task, agentId: 'agent-x', agentMetadata });++ expect(updateTask).toHaveBeenCalledWith('task-1', {+ metadata: expect.objectContaining({ resumeWorktreePath: DEAD_TREE })+ }, 'user');+ });++ // The agent's own recorded path wins over the <worktrees>/<agentId> convention,+ // so an app-repo agent whose tree lives elsewhere is still found.+ it('looks for the tree at the path the agent recorded', async () => {+ existsSyncMock.mockReturnValue(true);+ git.getBranch.mockResolvedValue(DEAD_BRANCH);+ git.getStatus.mockResolvedValue({ clean: false, files: [], porcelain: ' M a.js\n' });++ await recordTaskResumePointer({+ task: { id: 'task-1', metadata: {} }, agentId: 'agent-x',+ agentMetadata: { ...agentMetadata, workspacePath: '/elsewhere/tree' }+ });++ expect(git.getBranch).toHaveBeenCalledWith('/elsewhere/tree');+ });++ it('records nothing when there is no leftover work', async () => {+ git.getBranchComparison.mockResolvedValue({ ahead: 0, commits: [], stats: {} });++ await recordTaskResumePointer({ task: { id: 'task-1', metadata: {} }, agentId: 'agent-x', agentMetadata });++ expect(updateTask).not.toHaveBeenCalled();+ });++ it('skips agents that never had a worktree, and persistent feature-agent worktrees', async () => {+ const task = { id: 'task-1', metadata: {} };++ await recordTaskResumePointer({ task, agentId: 'agent-x', agentMetadata: { isWorktree: false } });+ await recordTaskResumePointer({ task, agentId: 'agent-x', agentMetadata: { ...agentMetadata, isPersistentWorktree: true } });++ expect(updateTask).not.toHaveBeenCalled();+ });++ // Reasoning agents run in a worktree whose edits are deliberately thrown away —+ // resuming one would resurrect code the discard guarantee exists to drop.+ it('skips throwaway (discardWorktree) tasks', async () => {+ const task = { id: 'task-1', metadata: { discardWorktree: true } };++ await recordTaskResumePointer({ task, agentId: 'agent-x', agentMetadata });++ expect(updateTask).not.toHaveBeenCalled();+ });+});++describe('resumePointerMetadata', () => {+ it('sets the three keys a retry needs to resume', () => {+ expect(resumePointerMetadata({ branchName: 'cos/b', worktreePath: '/t' }, 'agent-x', { metadata: {} })).toEqual({+ existingBranch: 'cos/b', resumedFromAgentId: 'agent-x', resumeWorktreePath: '/t'+ });+ });++ // Attempt 1 left a resumable branch; attempt 2 landed it. Leaving the stale+ // pointer would attach attempt 3 to already-merged work.+ it('clears a pointer this mechanism wrote once there is nothing left to resume', () => {+ expect(resumePointerMetadata(null, 'agent-y', { metadata: { resumedFromAgentId: 'agent-x' } })).toEqual({+ existingBranch: null, resumedFromAgentId: null, resumeWorktreePath: null+ });+ });++ // The review-loop follow-up sets existingBranch itself and has no resumedFrom+ // marker — clearing it would strand the follow-up off its own PR branch.+ it('leaves a foreign existingBranch alone', () => {+ expect(resumePointerMetadata(null, 'agent-y', { metadata: { existingBranch: 'cos/pr-branch' } })).toEqual({});});});diff --git a/server/services/cos.js b/server/services/cos.jsindex 74e3ac522e..4d7a324e2f 100644--- a/server/services/cos.js+++ b/server/services/cos.js@@ -525,6 +525,21 @@ async function resetOrphanedTasks() {.filter(a => a.status === 'running').map(a => a.taskId);+ // The most recent agent per task. Handing it to handleOrphanedTask lets the retry+ // resume the worktree/branch that run left behind instead of restarting — the+ // residue this pass catches (an agent that died partway through its own cleanup,+ // or was archived while its task stayed in_progress) leaves exactly the same+ // preserved worktree the boot sweep's orphans do. Absent (already archived) just+ // means no pointer and a clean start, which is the pre-existing behavior.+ const lastAgentByTask = new Map();+ for (const agent of Object.values(state.agents)) {+ if (!agent.taskId) continue;+ const previous = lastAgentByTask.get(agent.taskId);+ if (!previous || new Date(agent.startedAt || 0) >= new Date(previous.startedAt || 0)) {+ lastAgentByTask.set(agent.taskId, agent);+ }+ }+// Also track tasks with recently-completed agents to avoid race condition:// Between completeAgent() and updateTask(), the agent is "completed" but the// task is still "in_progress". Without this check, resetOrphanedTasks treats@@ -600,7 +615,8 @@ async function resetOrphanedTasks() {continue;}emitLog('info', `Found orphaned in_progress task ${task.id}, routing through retry handler`, { taskId: task.id });- await handleOrphanedTask(task.id, 'unknown-reset', getTaskById);+ const deadAgent = lastAgentByTask.get(task.id);+ await handleOrphanedTask(task.id, deadAgent?.id || 'unknown-reset', getTaskById, { agentMetadata: deadAgent?.metadata });}};diff --git a/server/services/cosTaskStore.js b/server/services/cosTaskStore.jsindex bf552512b1..c32147ad94 100644--- a/server/services/cosTaskStore.js+++ b/server/services/cosTaskStore.js@@ -447,16 +447,18 @@ 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.+ // + `resumeWorktreePath` + `resumedFromAgentId` are stamped by+ // `recordTaskResumePointer` so a FAILED or ORPHANED task's retry picks up the+ // branch (and worktree) 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 (isTerminalTaskStatus(updates.status)) {delete updatedMetadata.existingBranch;delete updatedMetadata.resumedFromAgentId;+ delete updatedMetadata.resumeWorktreePath;}// Release the federation claim/lease when a task leaves `in_progress` (issuediff --git a/server/services/git.js b/server/services/git.jsindex b749a44e51..71ff2794bc 100644--- a/server/services/git.js+++ b/server/services/git.js@@ -63,7 +63,10 @@ export async function getStatus(dir) {clean: files.length === 0,files,staged: files.filter(f => f.staged).length,- unstaged: files.filter(f => !f.staged).length+ unstaged: files.filter(f => !f.staged).length,+ // Raw porcelain, so callers can hand it to `classifyWorktreeDirt`+ // (worktreeManager.js) instead of re-deriving "is this dirt real work?".+ porcelain: result.stdout};}diff --git a/server/services/worktreeManager.js b/server/services/worktreeManager.jsindex bdb8de7928..93daf37fc7 100644--- a/server/services/worktreeManager.js+++ b/server/services/worktreeManager.js@@ -66,7 +66,7 @@ export function addWorktreeWithRetry(args, repo, attempt = 1, firstError = null)err.firstAttemptError = originalError;throw err;}- console.log(`🌳 Worktree add lock contention (attempt ${attempt}/${WORKTREE_ADD_MAX_ATTEMPTS}), retrying in ${WORKTREE_ADD_RETRY_DELAY_MS}ms: ${err.message}`);+ console.log(`🌳 Worktree ${args[1] || 'add'} lock contention (attempt ${attempt}/${WORKTREE_ADD_MAX_ATTEMPTS}), retrying in ${WORKTREE_ADD_RETRY_DELAY_MS}ms: ${err.message}`);return sleep(WORKTREE_ADD_RETRY_DELAY_MS).then(() => addWorktreeWithRetry(args, repo, attempt + 1, originalError));});@@ -382,6 +382,75 @@ async function createWorktreeUnlocked(agentId, sourceWorkspace, taskId, optionsreturn { worktreePath, branchName, baseBranch, instanceId };}+/**+ * Adopt an INTERRUPTED agent's surviving worktree on behalf of the agent that is+ * retrying its task, instead of building a fresh one from the default branch.+ *+ * When an agent dies without completing (a server restart is the common case —+ * PM2 kills the PTY, so no completion hook ever runs), `removeWorktree` refuses to+ * delete a dirty tree and leaves the whole worktree in place. That tree holds the+ * dead run's uncommitted edits and untracked files, which no branch pointer can+ * carry: without adoption the retry starts from origin/main and redoes the work.+ *+ * The tree is MOVED to the retry's own `<worktrees>/<agentId>` directory rather+ * than adopted where it sits, because "directory name == the agent that owns this+ * tree" is the invariant `cleanupOrphanedWorktrees` reaps on — left at the dead+ * agent's path, the live retry's worktree would be reaped out from under it. The+ * move carries tracked edits, untracked files, and git's own bookkeeping intact.+ *+ * Returns null (never throws) whenever adoption isn't possible — the source tree+ * is gone, the target path is occupied, or git refuses the move (a locked worktree,+ * or one with initialized submodules). Callers fall back to a fresh worktree, which+ * is the pre-existing behavior.+ *+ * @param {string} agentId - the RETRYING agent (names the destination directory)+ * @param {string} sourceWorkspace - the parent git repository+ * @param {string} existingWorktreePath - absolute path of the dead agent's worktree+ * @param {string} branchName - the branch that worktree has checked out+ * @returns {Promise<{worktreePath: string, branchName: string, baseBranch: null, existingBranch: true, adopted: true, instanceId: string}|null>}+ */+export async function adoptWorktree(agentId, sourceWorkspace, existingWorktreePath, branchName) {+ return queueWorktreeCreate(sourceWorkspace, () => adoptWorktreeUnlocked(agentId, sourceWorkspace, existingWorktreePath, branchName));+}++async function adoptWorktreeUnlocked(agentId, sourceWorkspace, existingWorktreePath, branchName) {+ if (!agentId || !sourceWorkspace || !existingWorktreePath || !branchName) return null;+ if (!existsSync(existingWorktreePath)) {+ console.log(`🌳 Cannot adopt worktree for ${agentId} — ${existingWorktreePath} no longer exists`);+ return null;+ }++ const targetPath = join(WORKTREES_DIR, agentId);+ const instanceId = await ensureInstanceId();+ const adopted = {+ worktreePath: targetPath, branchName, baseBranch: null,+ existingBranch: true, adopted: true, instanceId+ };++ // Already at the destination (a retry that re-entered prep) — nothing to move.+ if (pathsEqual(existingWorktreePath, targetPath)) return adopted;++ if (existsSync(targetPath)) {+ console.log(`🌳 Cannot adopt worktree for ${agentId} — ${targetPath} is already occupied`);+ return null;+ }++ await ensureDir(WORKTREES_DIR);++ // Through the retry wrapper, not raw execGit: `worktree move` mutates the same+ // `.git/worktrees` bookkeeping whose per-repo lock motivated the retry (#2193).+ const moved = await addWorktreeWithRetry(['worktree', 'move', existingWorktreePath, targetPath], sourceWorkspace)+ .then(() => true)+ .catch(err => {+ console.log(`⚠️ Worktree adopt failed for ${agentId} (${existingWorktreePath} → ${targetPath}): ${err.message}`);+ return false;+ });+ if (!moved) return null;++ console.log(`🌳 Adopted worktree for ${agentId} at ${targetPath} (branch: ${branchName}) — resuming interrupted work`);+ return adopted;+}+/*** Remove a git worktree and its associated branch.*diff --git a/server/services/worktreeManager.test.js b/server/services/worktreeManager.test.jsindex e9a2d04bf3..38d311f91c 100644--- a/server/services/worktreeManager.test.js+++ b/server/services/worktreeManager.test.js@@ -18,6 +18,8 @@ vi.mock('fs/promises', () => ({readdir: vi.fn().mockResolvedValue([]),rm: vi.fn().mockResolvedValue(undefined),stat: vi.fn().mockResolvedValue({ isDirectory: () => true }),+ // adoptWorktree ensures the worktrees root exists before moving a tree into it.+ mkdir: vi.fn().mockResolvedValue(undefined),}));vi.mock('./instances.js', () => ({ ensureInstanceId: vi.fn().mockResolvedValue('instance-1') }));const getDefaultBranchMock = vi.fn().mockResolvedValue('main');@@ -35,7 +37,10 @@ const {addWorktreeWithRetry,isPreexistingRefError,removeWorktree,+ adoptWorktree,} = await import('./worktreeManager.js');+const { existsSync } = await import('fs');+const { PATHS } = await import('../lib/fileUtils.js');/*** Tests for the worktree manager service.@@ -665,3 +670,76 @@ describe('removeWorktree branch preservation for resume (#3167)', () => {expect(isBranchMergedIntoMock).not.toHaveBeenCalledWith('/repo', 'cos/task-1/agent-x', 'main');});});++describe('adoptWorktree — resuming an interrupted run in its own worktree', () => {+ const WORKTREES = PATHS.worktrees;+ const DEAD_TREE = join(WORKTREES, 'agent-dead');+ const NEW_TREE = join(WORKTREES, 'agent-new');++ // The dead run's tree is on disk; the retry's destination is not.+ function scriptPaths({ source = true, target = false } = {}) {+ existsSync.mockImplementation((p) => {+ if (p === DEAD_TREE) return source;+ if (p === NEW_TREE) return target;+ return true;+ });+ }++ beforeEach(() => {+ execGitMock.mockReset();+ execGitMock.mockResolvedValue({ stdout: '', stderr: '', exitCode: 0 });+ scriptPaths();+ });++ afterEach(() => { existsSync.mockReturnValue(true); });++ // Renaming to the retry's own id keeps `<worktrees>/<agentId>` == "the agent that+ // owns this tree" — the invariant cleanupOrphanedWorktrees reaps on. Adopted in+ // place, the live retry's worktree would be reaped out from under it.+ it('moves the dead run’s tree to the retrying agent’s directory', async () => {+ const result = await adoptWorktree('agent-new', '/repo', DEAD_TREE, 'cos/task-1/agent-dead');++ expect(execGitMock).toHaveBeenCalledWith(['worktree', 'move', DEAD_TREE, NEW_TREE], '/repo');+ expect(result).toMatchObject({+ worktreePath: NEW_TREE, branchName: 'cos/task-1/agent-dead',+ existingBranch: true, adopted: true+ });+ });++ it('returns null (caller starts clean) when the leftover tree is gone', async () => {+ scriptPaths({ source: false });++ await expect(adoptWorktree('agent-new', '/repo', DEAD_TREE, 'cos/task-1/agent-dead')).resolves.toBeNull();+ expect(execGitMock).not.toHaveBeenCalled();+ });++ it('refuses to clobber an occupied destination', async () => {+ scriptPaths({ target: true });++ await expect(adoptWorktree('agent-new', '/repo', DEAD_TREE, 'cos/task-1/agent-dead')).resolves.toBeNull();+ expect(execGitMock).not.toHaveBeenCalled();+ });++ // git refuses to move a locked worktree or one with initialized submodules —+ // never throw at the spawn path, just decline so the caller builds a fresh tree.+ it('returns null rather than throwing when git refuses the move', async () => {+ execGitMock.mockRejectedValue(new Error('working trees containing submodules cannot be moved'));++ await expect(adoptWorktree('agent-new', '/repo', DEAD_TREE, 'cos/task-1/agent-dead')).resolves.toBeNull();+ });++ it('is a no-op when the tree already sits at the destination', async () => {+ scriptPaths({ source: true, target: true });++ const result = await adoptWorktree('agent-new', '/repo', NEW_TREE, 'cos/task-1/agent-dead');++ expect(execGitMock).not.toHaveBeenCalled();+ expect(result).toMatchObject({ worktreePath: NEW_TREE, adopted: true });+ });++ it('returns null on incomplete input instead of guessing', async () => {+ await expect(adoptWorktree(null, '/repo', DEAD_TREE, 'b')).resolves.toBeNull();+ await expect(adoptWorktree('agent-new', '/repo', DEAD_TREE, null)).resolves.toBeNull();+ expect(execGitMock).not.toHaveBeenCalled();+ });+});