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: record a task resume pointer for failed direct-CLI and TUI runs (#3368)
[._.]/ Adam Eivy90b24c970b11
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 2c0c175b69..c40724a012 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -159,6 +159,7 @@- **[issue-3335] Deleting a prompt stage now checks the source, not a hand-written list of ten.** `DELETE /api/prompts/:stage` force-guarded exactly the ten curated CoS/Brain/Memory stages, so removing `pipeline-series-concept-judge` (or roughly a hundred others PortOS resolves by literal key) succeeded with no warning and left the feature naming it throwing `Stage <key> not found` on its next run. Adding them all to the curated table was the wrong fix — the same table drives the Prompt Manager's `SYSTEM` badge and its "System only" filter, and badging ~100 of 127 rows makes both meaningless. Deletion protection is now a second, generated set: a checked-in manifest indexes every stage key a `server/` source names, including the ones reached only through an interpolated prefix like `pipeline-panel-${personaId}`, and a drift test fails until a new call site is regenerated into it. The badge and the filter still show the same ten stages; the delete dialog now names the files that reference the one you're about to remove.- **[issue-3288] Video render submission is no longer a 717-line route handler — and a failed lookup mid-request stops orphaning your upload.** `POST /api/video-gen` did request validation, backend-pin resolution, model checks, durable staging for four upload kinds with rollback bookkeeping, IC-LoRA/keyframe/a2v validation, render-history lookups, LoRA normalization and chunk resolution inline, with twenty-plus throw sites sharing mutable cleanup state — so every new video-gen parameter meant editing the monolith and risking an unrelated validation branch. That whole region now lives in `services/videoGen/prepareParams.js`, mirroring what `imageGen` already did, and the route is a thin parse → prepare → enqueue → respond shell. Validation order and the exact cleanup-on-throw unwind are preserved verbatim, pinned by the existing route suite plus a new service suite. The extraction also closed a real leak (#3326): every *explicit* throw released the staged uploads, but a plain rejected `await` — a music-video project or track lookup, a render-history read, or the enqueue itself — bubbled straight past them, orphaning up to 100MB per request under `data/uploads` with no job to ever clean it up. One rollback guard now covers every rejection point at once and stays correct as new awaits are added, rethrowing the original error untouched.- **[issue-3353] Client tests that type into a field and then submit no longer race the keystrokes.** A Stacker News save test failed on CI for a pull request whose entire diff was a dependency config file, and passed on the rerun. The cause is a shape that suite had in six places: `user.type` enters `20` as two separate events, and nothing between the last keystroke and the Save click asserted that the controlled input had actually reached `20` — so under load the click could send a payload built from the intermediate `2`, or from the post-clear empty string that `Number('')` turns into `0`. Waiting on the assertion cannot recover from that, because the call has already happened with the wrong argument and re-waiting never produces a second one. A shared `src/test/settledInput.js` helper now pins the settled input value between the keystrokes and whatever depends on them, and every instance of the shape now uses it — all six in the Stacker News suite plus ten more found by auditing the rest of the client tests, across the CoS agent card and reviewer picker, the sprite reference workflow, the media jobs queue, the duplicate-universe merge tab, and Media Collections. Two of those submitted with Enter typed as part of the same keystroke run, where a partially-typed `bad token!` would have been a *valid* username and quietly emitted; the Enter is now a separate press after the draft is pinned. One more asserted only the navigation that followed its submit, so a half-typed collection name could not have failed it — it now asserts the request it sent. The failure mode it replaces is an honest one — an input that never settles now fails saying so, rather than silently asserting against a half-typed value.+- **[issue-3368] A failed agent's committed work is now picked up by its retry no matter which way the agent was launched.** When a run fails with commits on its branch, cleanup deliberately preserves that branch so the retry can continue from it — but turning a preserved branch into an actual resume takes a pointer written onto the task, and only one of the three ways PortOS launches an agent was writing it. A failed direct-CLI or TUI run therefore left a branch full of finished work that nothing would ever point at: the retry started from an empty tree and redid all of it, while the previous attempt's branch sat there untouched. The PR verification added in #3358 made this easy to hit — a run that committed, pushed, and only failed to open its pull request is now retried, and under those two launch modes the retry redid the whole task instead of just opening the PR — but any failed run with commits had the same gap. All three launch paths now share one gate, which still declines to stamp a pointer on a task that has exhausted its retry budget and is waiting on a human.- **[issue-3358] An unreachable `gh` no longer looks like a quiet repo — and an agent can no longer report success having filed no PR.** Around thirty call sites ran `gh` and turned *any* failure into an empty result, so a firewalled or unauthenticated CLI was indistinguishable from a repo with nothing going on: the PR watcher saw no PRs, the branch reconciler classified every pushed branch as "needs a PR" (and would have had an agent open duplicates on top of the ones already open), the issue reconciler saw nothing to reconcile, and none of it logged a distinguishable error. Those reads now answer with three states instead of two — the forge said nothing, the forge said nothing *exists*, or we could not ask — and every forge-dependent scheduled job (`pr-watcher`, `branch-reconcile`, `issue-reconcile`, layered intelligence, self-diagnostics) probes `gh` first and skips the cycle with one clear line rather than executing against a forge it cannot read. Separately, a run whose task shape promised a pull request is now verified against the forge before it is recorded complete: an agent that commits, pushes over SSH (unaffected by an outbound block) and then fails to create the PR is recorded as needing attention with the branch named, not as "Completed successfully" — and "we could not confirm the PR" is kept distinct from "there is no PR", so a network outage is treated as environmental instead of denting the task type's measured success rate.- **[issue-3359] The prompt-integrity snapshot now pins prompt bytes instead of the machine that generated it.** `taskPromptDefaults.test.js` hashes every current and preserved-historical prompt body against a checked-in snapshot, because editing a preserved body silently strands every other install on a prompt it can no longer recognize as an upgradable default. Prompt bodies embed this install's API origin, so hashing normalized it away first — but only the *runtime* origin, while the historical bodies written before that interpolation existed hardcode `http://localhost:5555`. The snapshot therefore only reproduced on a machine whose own origin happened to equal that literal: set a custom host, or merely run the suite in a shell with `PORT` set (as every CoS agent does), and five untouched bodies hashed differently and the suite failed reporting drift that had not happened. Regenerating the snapshot there would have been the damaging fix — it blesses whatever edited a preserved body, which is the one thing this test exists to catch. Hashing now collapses the frozen legacy origin too, which reproduces the committed snapshot byte for byte on every install, and the shared hasher is what both the test and a new `scripts/regen-prompt-integrity-snapshot.js` use, so the regeneration path can no longer normalize differently from the assertion. The guard is also in the CI planner's always-run list now: it covers a cross-install contract nothing else covers, so no impact scope may scope it out.diff --git a/server/services/agentCliSpawning.js b/server/services/agentCliSpawning.jsindex 72e4211dfc..3b0f5b6686 100644--- a/server/services/agentCliSpawning.js+++ b/server/services/agentCliSpawning.js@@ -919,6 +919,16 @@ export async function spawnDirectly({originalTask: task}).catch(err => console.error(`❌ CLI worktree cleanup failed for ${agentId}: ${err.message}`));+ // Point this task's retry at whatever the run left behind — the branch (or+ // whole worktree) `cleanupWorktreeFn` just preserved because the run failed+ // with commits on it. Without this the retry starts clean and redoes work+ // that is already sitting on disk (#3368). Imported lazily for the same+ // reason `cleanupWorktreeFn` is injected: pulling the cleanup graph in at+ // module top level races this file's own init in the agentLifecycle cycle.+ await import('./agentWorktreeCleanup.js')+ .then(({ recordResumePointerIfRetrying }) => recordResumePointerIfRetrying({ agentId, task, success: cleanupSuccess }))+ .catch(err => console.error(`❌ CLI resume-pointer record failed for ${agentId}: ${err.message}`));+unregisterSpawnedAgent(agentData?.pid || claudeProcess.pid);activeAgents.delete(agentId);}diff --git a/server/services/agentCliSpawning.test.js b/server/services/agentCliSpawning.test.jsindex 9e10d44b9a..4724944436 100644--- a/server/services/agentCliSpawning.test.js+++ b/server/services/agentCliSpawning.test.js@@ -89,7 +89,15 @@ vi.mock('child_process', () => ({execFile: vi.fn(),}));+// Lazily imported by the close handler's cleanup block to record a failed run's+// resume pointer (#3368). Mocked so the test doesn't pull the real cleanup graph+// (cos.js, git.js, worktreeManager) in behind it.+vi.mock('./agentWorktreeCleanup.js', () => ({+ recordResumePointerIfRetrying: vi.fn().mockResolvedValue({}),+}));+import { buildCliSpawnConfig, createStreamJsonParser, spawnDirectly } from './agentCliSpawning.js';+import { recordResumePointerIfRetrying } from './agentWorktreeCleanup.js';// Real module — the flag is a plain process-local boolean, so driving it// directly exercises the same code path production does.import { markHostShuttingDown, resetHostShutdownFlagForTests } from '../lib/hostShutdown.js';@@ -804,6 +812,43 @@ describe('stream error containment', () => {expect(opts.reviewer).toBeUndefined();});+ // A failed direct-CLI run's branch is preserved by cleanup when it holds commits;+ // without this call nothing ever points the retry at it and the work is redone+ // from scratch (#3368). Runs after cleanup so it reflects what actually survived.+ it('records a resume pointer after cleanup when the run failed', async () => {+ recordResumePointerIfRetrying.mockClear();+ const cleanupWorktreeFn = vi.fn().mockResolvedValue(undefined);+ const task = { id: 'task-rp', description: 'do stuff', metadata: {} };++ spawnDirectly({ ...minimalArgs, task, cleanupWorktreeFn, isTruthyMetaFn: (v) => v === true });+ await new Promise((r) => setTimeout(r, 10));+ fakeProcess.emit('close', 1);+ await new Promise((r) => setTimeout(r, 80));++ expect(recordResumePointerIfRetrying).toHaveBeenCalledWith({+ agentId: minimalArgs.agentId, task, success: false,+ });+ expect(cleanupWorktreeFn.mock.invocationCallOrder[0])+ .toBeLessThan(recordResumePointerIfRetrying.mock.invocationCallOrder[0]);+ });++ // The helper no-ops on success (unit-tested in cleanupAgentWorktree.test.js) —+ // what this pins is that the close handler hands it the real verdict, not a+ // hardcoded false that would stamp pointers on every completed run.+ it('passes the success verdict through on a clean run', async () => {+ recordResumePointerIfRetrying.mockClear();+ const task = { id: 'task-rp-ok', description: 'do stuff', metadata: {} };++ spawnDirectly({ ...minimalArgs, task, cleanupWorktreeFn: vi.fn().mockResolvedValue(undefined), isTruthyMetaFn: (v) => v === true });+ await new Promise((r) => setTimeout(r, 10));+ fakeProcess.stdout.emit('data', Buffer.from('{"type":"result","result":"ok"}\n'));+ await new Promise((r) => setTimeout(r, 50));+ fakeProcess.emit('close', 0);+ await new Promise((r) => setTimeout(r, 80));++ expect(recordResumePointerIfRetrying).toHaveBeenCalledWith(expect.objectContaining({ success: true }));+ });+// pm2's TreeKill takes direct-CLI children down with portos-server exactly as// it does TUI PTYs (#3202). Finalizing here would charge the task's failure// budget — and possibly file an investigation task — for a fault the agentdiff --git a/server/services/agentCompletionCleanup.js b/server/services/agentCompletionCleanup.jsindex a01f72ea62..05d2836835 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, recordTaskResumePointer } from './agentWorktreeCleanup.js';+import { cleanupAgentWorktree, spawnMergeRecoveryTask, recordResumePointerIfRetrying } from './agentWorktreeCleanup.js';import { resolvePrCompletion } from '../lib/prDisposition.js';import { canTypeSlashCommands } from '../lib/slashdoInvocation.js';@@ -342,32 +342,20 @@ export async function runAgentCompletionCleanup({ agentId, task, agent, effectivoriginalTask: task});- // 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.+ // Point the task's retry at whatever this run left behind (branch and/or+ // worktree) instead of letting it restart from scratch. Shared with the+ // direct-CLI and TUI spawn paths — see `recordResumePointerIfRetrying` for why+ // it runs after cleanup and only for a still-`pending` task.//- // Written here (not in cleanupAgentWorktree) because this is where the task- // 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- // budget and is waiting on a human (a pointer there would be dead metadata- // that `updateTask` has to strip again on the next terminal write).- if (!effectiveSuccess && task?.id) {- const { getTaskById } = await import('./cos.js');- const persisted = await getTaskById(task.id).catch(() => null);- 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 });- }- }+ // `agentState` was fetched at the top of this function; its worktree fields are+ // stamped once at registerAgent and never mutated, so passing it spares the+ // helper a re-read that would re-split the whole output.txt transcript.+ await recordResumePointerIfRetrying({+ agentId,+ task,+ success: effectiveSuccess,+ agentMetadata: agentState?.metadata ?? null,+ });if (cleanupWarnings?.length > 0) {const { getAgent: getAgentForResult } = await import('./cos.js');diff --git a/server/services/agentCompletionCleanup.test.js b/server/services/agentCompletionCleanup.test.jsindex 75bd8435aa..163c75b324 100644--- a/server/services/agentCompletionCleanup.test.js+++ b/server/services/agentCompletionCleanup.test.js@@ -25,13 +25,13 @@ vi.mock('./codeReview.js', () => ({ resolveReviewLoopOptions: vi.fn().mockResolvvi.mock('./agentWorktreeCleanup.js', () => ({cleanupAgentWorktree: vi.fn().mockResolvedValue([]),spawnMergeRecoveryTask: vi.fn(),- recordTaskResumePointer: vi.fn().mockResolvedValue(null),+ recordResumePointerIfRetrying: vi.fn().mockResolvedValue({}),}));vi.mock('./taskPromptService.js', () => ({ getStagePrompt: vi.fn().mockResolvedValue('do stage work in {appName}') }));import { handlePipelineProgression, runAgentCompletionCleanup } from './agentCompletionCleanup.js';-import { updateTask, addTask, reviveBlockedTask } from './cos.js';-import { cleanupAgentWorktree } from './agentWorktreeCleanup.js';+import { updateTask, addTask, reviveBlockedTask, getAgent } from './cos.js';+import { cleanupAgentWorktree, recordResumePointerIfRetrying } from './agentWorktreeCleanup.js';const runningPipeline = (overrides = {}) => ({id: 'p1',@@ -182,3 +182,38 @@ describe('runAgentCompletionCleanup — agentOwnsPR mirrors the prompt gate', ()expect((await cleanupCallFor({ providerId: 'codex-tui' })).openPR).toBe(true);});});++// Runner mode shares the resume-pointer gate with the direct-CLI and TUI spawn+// paths (#3368) — it must call the helper, not keep its own inline copy.+describe('runAgentCompletionCleanup — resume pointer', () => {+ const task = { id: 't', taskType: 'user', metadata: {} };++ it('hands the verdict and the already-loaded agent metadata to the shared helper', async () => {+ getAgent.mockResolvedValue({ metadata: { isWorktree: true, sourceWorkspace: '/repo' } });++ await runAgentCompletionCleanup({+ agentId: 'a1', task, agent: { providerId: 'codex' }, effectiveSuccess: false, outputBuffer: '',+ });++ expect(recordResumePointerIfRetrying).toHaveBeenCalledWith({+ agentId: 'a1', task, success: false,+ agentMetadata: { isWorktree: true, sourceWorkspace: '/repo' },+ });+ // After cleanup, so the pointer reflects what actually survived.+ expect(cleanupAgentWorktree.mock.invocationCallOrder[0])+ .toBeLessThan(recordResumePointerIfRetrying.mock.invocationCallOrder[0]);+ });++ // A missing agent record must reach the helper as an explicit null, not+ // `undefined` — `undefined` is the helper's "go read it yourself" sentinel, and+ // re-reading here would re-split the whole output.txt transcript for nothing.+ it('passes null when the agent record could not be read', async () => {+ getAgent.mockResolvedValue(null);++ await runAgentCompletionCleanup({+ agentId: 'a1', task, agent: { providerId: 'codex' }, effectiveSuccess: false, outputBuffer: '',+ });++ expect(recordResumePointerIfRetrying).toHaveBeenCalledWith(expect.objectContaining({ agentMetadata: null }));+ });+});diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.jsindex e5a413f841..7576e61aa8 100644--- a/server/services/agentTuiSpawning.js+++ b/server/services/agentTuiSpawning.js@@ -690,6 +690,16 @@ export async function spawnTuiAgent({originalTask: task}).catch(err => emitLog('warn', `TUI worktree cleanup failed for ${agentId}: ${err.message}`, { agentId }));+ // Point this task's retry at whatever the run left behind — the branch (or+ // whole worktree) `cleanupWorktreeFn` just preserved because the run failed+ // with commits on it. Without this the retry starts clean and redoes work+ // that is already sitting on disk (#3368). Imported lazily for the same+ // reason `cleanupWorktreeFn` is injected: pulling the cleanup graph in at+ // module top level races this file's own init in the agentLifecycle cycle.+ await import('./agentWorktreeCleanup.js')+ .then(({ recordResumePointerIfRetrying }) => recordResumePointerIfRetrying({ agentId, task, success: cleanupSuccess }))+ .catch(err => emitLog('warn', `TUI resume-pointer record failed for ${agentId}: ${err.message}`, { agentId }));+if (agentData?.pid) unregisterSpawnedAgent(agentData.pid);activeAgents.delete(agentId);if (sessionId && shellService.getSession(sessionId)) shellService.killSession(sessionId);diff --git a/server/services/agentTuiSpawning.test.js b/server/services/agentTuiSpawning.test.jsindex 4c62cad6fa..e10225e3aa 100644--- a/server/services/agentTuiSpawning.test.js+++ b/server/services/agentTuiSpawning.test.js@@ -100,6 +100,13 @@ vi.mock('./git.js', () => ({resolveForgeTokenEnv: vi.fn().mockResolvedValue({}),}));+// Lazily imported by finish()'s cleanup block to record a failed run's resume+// pointer (#3368). Mocked so the test doesn't pull the real cleanup graph+// (cos.js, worktreeManager, recoveryTasks) in behind it.+vi.mock('./agentWorktreeCleanup.js', () => ({+ recordResumePointerIfRetrying: vi.fn().mockResolvedValue({}),+}));+vi.mock('fs', () => ({// Default: no .agent-done sentinel on disk. The completion-sentinel test// overrides this to true. Re-set in beforeEach so it can't leak between tests.@@ -184,6 +191,7 @@ import { existsSync } from 'fs';import { readFile } from 'fs/promises';import { execFile } from 'child_process';import { buildTuiSpawnConfig, spawnTuiAgent } from './agentTuiSpawning.js';+import { recordResumePointerIfRetrying } from './agentWorktreeCleanup.js';import { spawnTuiSessionViaRunner } from './cosRunnerClient.js';import * as shellService from './shell.js';import * as agentLifecycle from './agentFinalization.js';@@ -623,6 +631,38 @@ describe('spawnTuiAgent runtime', () => {}));});+ // A failed TUI run's branch is preserved by cleanup when it holds commits; without+ // this call nothing ever points the retry at it and the work is redone from+ // scratch (#3368). Runs after cleanup so it reflects what actually survived.+ it('records a resume pointer after cleanup when the run failed', async () => {+ vi.mocked(recordResumePointerIfRetrying).mockClear();+ const cleanupWorktreeFn = vi.fn().mockResolvedValue(undefined);+ const task = { id: 'task-1', description: 'do the thing', metadata: {} };+ const spawnPromise = runSpawn({ task, helpers: { cleanupWorktreeFn, isTruthyMetaFn: (v) => !!v } });+ await flushMicrotasks();++ await capturedOnExit({ exitCode: 1, killed: false });+ await spawnPromise;++ expect(recordResumePointerIfRetrying).toHaveBeenCalledWith({ agentId: 'agent-1', task, success: false });+ expect(cleanupWorktreeFn.mock.invocationCallOrder[0])+ .toBeLessThan(vi.mocked(recordResumePointerIfRetrying).mock.invocationCallOrder[0]);+ });++ // The helper no-ops on success (unit-tested in cleanupAgentWorktree.test.js) —+ // what this pins is that finish() hands it the real verdict, not a hardcoded+ // false that would stamp pointers on every completed run.+ it('passes the success verdict through on a clean run', async () => {+ vi.mocked(recordResumePointerIfRetrying).mockClear();+ const spawnPromise = runSpawn({ helpers: { cleanupWorktreeFn: vi.fn().mockResolvedValue(undefined), isTruthyMetaFn: (v) => !!v } });+ await flushMicrotasks();++ await capturedOnExit({ exitCode: 0, killed: false });+ await spawnPromise;++ expect(recordResumePointerIfRetrying).toHaveBeenCalledWith(expect.objectContaining({ success: true }));+ });+// ── 1. Successful idle-complete path ────────────────────────────────────────it('idle-complete: calls finalizeAgent(success:true) with completionReason=idle-complete when idle fires after enough output and runtime', async () => {// Wire finalizeAgent to resolve a promise we can await, so we can detectdiff --git a/server/services/agentWorktreeCleanup.js b/server/services/agentWorktreeCleanup.jsindex 9a86f545d8..bb3a1c7a85 100644--- a/server/services/agentWorktreeCleanup.js+++ b/server/services/agentWorktreeCleanup.js@@ -515,6 +515,51 @@ export async function recordTaskResumePointer({ task, agentId, agentMetadata })return metadata;}+/**+ * The post-cleanup resume-pointer write, shared by every spawn mode (#3368).+ *+ * A failed agent whose branch — or whole worktree — survived cleanup leaves real+ * work behind (see `preserveBranchWithCommits` above; a dirty tree aborts removal+ * outright). Recording where it lives on the TASK is what makes its retry RESUME+ * rather than restart 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.+ *+ * Call this AFTER `cleanupAgentWorktree` so it reflects what actually survived, and+ * from all three spawn sites — `spawnDirectly` (agentCliSpawning.js), the TUI+ * `finish()` (agentTuiSpawning.js), and `handleAgentCompletion`+ * (agentCompletionCleanup.js, runner mode). Only the runner path used to do it, so a+ * failed direct-CLI/TUI run left a branch full of commits nothing would ever point a+ * retry at.+ *+ * Only for a task that is actually going to RETRY. The failure verdict has already+ * been persisted by `finalizeAgent` at this point, so the task's *persisted* status+ * distinguishes a `pending` retry (wants the pointer) from a `blocked` task that+ * exhausted its budget and is waiting on a human — a pointer there would be dead+ * metadata that `updateTask` has to strip again on the next terminal write.+ *+ * `agentMetadata` is optional: pass it when the caller already holds the agent+ * record (the runner path does, and re-reading it there would re-split the whole+ * output.txt transcript), omit it and this reads the record itself. `undefined`+ * means "not supplied" — a caller that genuinely has no metadata still gets the+ * no-op it deserves, since `resolveTaskResumePatch` bails on a non-worktree run.+ *+ * @param {{agentId: string, task: object, success: boolean, agentMetadata?: object}} params+ * @returns {Promise<object>} the patch that was written (empty when nothing was)+ */+export async function recordResumePointerIfRetrying({ agentId, task, success, agentMetadata }) {+ if (success || !agentId || !task?.id) return {};++ const { getTaskById, getAgent } = await import('./cos.js');+ const persisted = await getTaskById(task.id).catch(() => null);+ if ((persisted?.status ?? 'pending') !== 'pending') return {};++ const metadata = agentMetadata === undefined+ ? (await getAgent(agentId).catch(() => null))?.metadata+ : agentMetadata;+ return await recordTaskResumePointer({ task, agentId, agentMetadata: metadata });+}+/*** Spawn an internal follow-up task that drives the ordered multi-reviewer* review-and-fix loop on the just-created PR until the configured reviewer chaindiff --git a/server/services/cleanupAgentWorktree.test.js b/server/services/cleanupAgentWorktree.test.jsindex 6e4bd70f9a..69759ca116 100644--- a/server/services/cleanupAgentWorktree.test.js+++ b/server/services/cleanupAgentWorktree.test.js@@ -212,8 +212,8 @@ vi.mock('./runner.js', () => ({import { join } from 'path';import { existsSync as existsSyncMock } from 'fs';import { cleanupAgentWorktree, spawnMergeRecoveryTask, spawnReviewLoopFollowUp } from './subAgentSpawner.js';-import { resolveResumePointer, resolveTaskResumePatch, recordTaskResumePointer, resumePointerMetadata } from './agentWorktreeCleanup.js';-import { getAgent, addTask, updateTask } from './cos.js';+import { resolveResumePointer, resolveTaskResumePatch, recordTaskResumePointer, recordResumePointerIfRetrying, resumePointerMetadata } from './agentWorktreeCleanup.js';+import { getAgent, getTaskById, addTask, updateTask } from './cos.js';import { removeWorktree } from './worktreeManager.js';import { PATHS } from '../lib/fileUtils.js';import * as git from './git.js';@@ -1222,6 +1222,83 @@ describe('resolveTaskResumePatch / recordTaskResumePointer', () => {});});+// The shared post-cleanup gate every spawn mode calls (#3368). Direct-CLI and TUI+// runs used to skip this entirely, so a failed run's preserved branch was never+// pointed at and its retry redid the work from scratch.+describe('recordResumePointerIfRetrying', () => {+ const agentMetadata = {+ isWorktree: true, sourceWorkspace: '/repo',+ worktreeBranch: DEAD_BRANCH, workspacePath: DEAD_TREE+ };+ const task = () => ({ id: 'task-1', taskType: 'user', metadata: {} });++ 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);+ getTaskById.mockResolvedValue({ id: 'task-1', status: 'pending' });+ getAgent.mockResolvedValue({ metadata: agentMetadata });+ });++ // The direct-CLI / TUI shape: neither spawn path holds the agent record, so the+ // helper has to read it for the worktree fields.+ it('records the pointer for a failed run whose task is still pending', async () => {+ await recordResumePointerIfRetrying({ agentId: 'agent-x', task: task(), success: false });++ expect(getAgent).toHaveBeenCalledWith('agent-x');+ expect(updateTask).toHaveBeenCalledWith('task-1', {+ metadata: { existingBranch: DEAD_BRANCH, resumedFromAgentId: 'agent-x', resumeWorktreePath: null }+ }, 'user');+ });++ // A task that exhausted its retry budget is waiting on a human — a pointer there+ // is dead metadata `updateTask` has to strip again on the next terminal write.+ it('records nothing when the task is already blocked', async () => {+ getTaskById.mockResolvedValue({ id: 'task-1', status: 'blocked' });++ await recordResumePointerIfRetrying({ agentId: 'agent-x', task: task(), success: false });++ expect(updateTask).not.toHaveBeenCalled();+ });++ it('records nothing on a successful run', async () => {+ await recordResumePointerIfRetrying({ agentId: 'agent-x', task: task(), success: true });++ expect(getTaskById).not.toHaveBeenCalled();+ expect(updateTask).not.toHaveBeenCalled();+ });++ // A task whose record vanished (deleted mid-run) still defaults to pending so the+ // pointer isn't silently dropped.+ it('treats an unreadable task record as pending', async () => {+ getTaskById.mockRejectedValue(new Error('gone'));++ await recordResumePointerIfRetrying({ agentId: 'agent-x', task: task(), success: false });++ expect(updateTask).toHaveBeenCalled();+ });++ // The runner path already holds the agent record; passing it spares a re-read+ // that would re-split the whole output.txt transcript.+ it('uses caller-supplied agent metadata instead of re-reading the record', async () => {+ await recordResumePointerIfRetrying({ agentId: 'agent-x', task: task(), success: false, agentMetadata });++ expect(getAgent).not.toHaveBeenCalled();+ expect(updateTask).toHaveBeenCalled();+ });++ it('is a no-op without an agent id or a task id', async () => {+ await recordResumePointerIfRetrying({ agentId: '', task: task(), success: false });+ await recordResumePointerIfRetrying({ agentId: 'agent-x', task: { metadata: {} }, success: false });++ expect(getTaskById).not.toHaveBeenCalled();+ 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({