Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: hold a failed task non-spawnable until its resume pointer is written (#3373)

[._.]/ Adam Eivya1d22be96af7
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index ac65b87c1c..3acef1565e 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -160,6 +160,7 @@
- **[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-3373] A failed task is no longer offered back to the scheduler before the pointer telling its retry where to resume exists.** The retry pointer from #3368 can only be worked out *after* worktree cleanup decides what survived — whether the branch is still there and still holds commits — but the failure verdict flipped the task straight back to `pending` before cleanup even started. The dequeue that fires the moment an agent completes could therefore claim the retry during that window and start it on an empty tree, and because the retry then held the task `in_progress`, the pointer write that arrived seconds later correctly declined to stamp a running task — so the preserved branch was orphaned for good. A retryable failure now leaves the task deliberately non-spawnable while cleanup runs, and one write both makes it spawnable again and records where to resume, so it is never one without the other. If PortOS dies mid-transition the held state is on disk, and the startup sweep finishes it — immediately at boot, where nothing can be mid-cleanup, and after a liveness grace on the periodic pass, so a slow merge is never mistaken for a dead process. A task that exhausted its retry budget is blocked and waiting on a human, so it is never held and never pointed, exactly as before.
- **[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.
- **[issue-3365] A pinned browser read now closes its own scratch tab, instead of every call site being expected to remember.** `navigateToUrlPinned` opens a fresh Chrome tab per call and tore it down itself on a refusal, but on success handed the caller a tab the caller was supposed to close — a convention that had already been broken twice, once leaving a tab behind for every catalog URL ingested and once for every Stacker News identity check, each fixed by hand-writing another close at the call site. The function already knows which case it is in: a caller that passes `evaluateExpression` did its DOM read on that same session and wants nothing back, while a caller that omits one wants the tab *as* the deliverable. So teardown now defaults to on exactly when an expression was supplied, the three read call sites no longer close anything, and the browser handoff and `POST /api/browser/navigate` still get their tab. `closeAfterRead: false` remains for a future caller that wants to read and keep the tab.
diff --git a/server/lib/README.md b/server/lib/README.md
index b364fa9b08..a3e9622c9f 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -217,6 +217,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `htmlToText.js` | Shared HTML → plain-text converter. `htmlToText(html, { extraEntities?, paragraphBreak?, collapseSpaces? })` — strips script/style/head/noscript blocks, converts `<br>`/block closes to newlines, strips remaining tags, decodes entities via `decodeXmlEntities`, collapses 3+ newlines, trims. Options preserve caller-specific output (Gmail: `paragraphBreak: '\n\n'` + `collapseSpaces`; SongBook import: defaults — space runs preserved for tab alignment). |
| `jsonExtract.js` | Pull JSON blocks out of LLM responses. |
| `taskParser.js` | Parse `TASKS.md` format. |
+| `taskRetryHold.js` | The failed-task RETRY HOLD state (#3373) — pure metadata helpers shared by the failure verdict, the post-cleanup release, and the orphan sweep. `retryHoldMetadata(now)` arms it (task stays `in_progress`, so no dequeue tier can claim the retry before its resume pointer is resolved); `clearedRetryHoldMetadata()` releases it in the same write that flips the task to `pending`; `isRetryHeld(metadata)` / `isStaleRetryHold(metadata, now, graceMs)` + `RETRY_HOLD_GRACE_MS` let the orphan sweep finish a transition whose process died. |
| `taxonomyTally.js` | Generic taxonomy tally + top-N-line render engine shared by the two Layered Intelligence leaf taxonomies (`services/layeredIntelligenceRejections.js`, `layeredIntelligenceExecutionFailures.js`). `createTaxonomyTally({predicate, select, field, vocabulary, sentinel, glossFn, gapWording})` is the single composed seam — it binds a taxonomy config into `{summarize, format}`, where `summarize(records)` yields the three-bucket `{entries, unknown, unclassified, diagnosed, total}` tally (commonest-first + taxonomy-order tie-break) and `format(records, limit)` renders one prompt line naming every non-zero gap. Also exports the two leaf utilities the classifiers use directly: `normalizeToken(value)` (lowercase + separator-collapse for label/category matching) and `formatTaxonomyToken(token, labels)` (gloss-map render, nullish→'', unglossed passthrough). Pure leaf — imports nothing from the LI graph. |
| `xmlEntities.js` | Shared dependency-free XML/HTML entity decoder. `decodeXmlEntities(str, extraEntities?)` — single-pass (double-decode-safe) decode of the five predefined named entities + decimal/hex numeric refs, with an optional caller-supplied extra-entity map (e.g. `{ nbsp: ' ', zwnj: '' }`). Unknown/out-of-range refs left untouched. Used by the Apple Health XML parser, Claude changelog feed, Pinterest RSS, generic feeds, and Gmail HTML-to-text. |
diff --git a/server/lib/index.js b/server/lib/index.js
index 4bbebb3ca1..964f51bc73 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -197,6 +197,7 @@ export * from './vectorMath.js';
export * from './htmlToText.js';
export * from './jsonExtract.js';
export * from './taskParser.js';
+export * from './taskRetryHold.js';
export * from './taxonomyTally.js';
export * from './xmlEntities.js';
diff --git a/server/lib/taskRetryHold.js b/server/lib/taskRetryHold.js
new file mode 100644
index 0000000000..9f04ed3e63
--- /dev/null
+++ b/server/lib/taskRetryHold.js
@@ -0,0 +1,88 @@
+/**
+ * Retry hold — the intermediate task state between a failed run's verdict and the
+ * resume pointer its retry needs (#3373).
+ *
+ * A non-actionable failure under the retry budget used to flip the task straight
+ * back to `pending` inside `finalizeAgent`, while the pointer that lets the retry
+ * adopt the branch cleanup preserved is only resolvable AFTER `cleanupAgentWorktree`
+ * has decided what survived — hundreds of milliseconds to seconds later. In that
+ * window the task is an ordinary `pending` candidate, so the dequeue that
+ * `agent:completed` schedules could claim it and start from scratch on a clean
+ * worktree, redoing work sitting on the preserved branch. Worse, the retry then
+ * holds the task `in_progress`, so the pointer write's own status gate declines and
+ * the pointer is dropped for good.
+ *
+ * The fix is a HOLD: the failure verdict leaves the task `in_progress` (no dequeue
+ * tier looks at `in_progress`, and `spawnAgentForTask` rejects it) carrying the
+ * marker below, and the post-cleanup write flips it to `pending` WITH the resume
+ * metadata in a single `updateTask`. The task is never both spawnable and pointerless.
+ *
+ * The marker is persisted task metadata, so a process killed mid-transition leaves
+ * evidence on disk: `handleOrphanedTask` recognizes a held task and completes the
+ * transition (resolve pointer → flip to `pending` → clear the marker) instead of
+ * treating it as a fresh orphan.
+ *
+ * Pure and dependency-free so the writer (agentErrorAnalysis), the releaser
+ * (agentWorktreeCleanup) and the recovery sweep (agentManagement / cos) share ONE
+ * definition of the state rather than three string literals.
+ */
+
+/**
+ * How long a hold is treated as LIVE — i.e. some in-process cleanup is presumed to
+ * still be running and about to release it. The orphan sweep only recovers a hold
+ * older than this, so it can't steal a task out from under a cleanup that is simply
+ * slow (a merge + push + PR probe). Comfortably longer than any real cleanup and
+ * shorter than nothing that matters: the sweep itself only runs every 15 minutes,
+ * so a crash costs at most one sweep interval before recovery.
+ */
+export const RETRY_HOLD_GRACE_MS = 10 * 60 * 1000;
+
+/** Metadata keys that carry the hold. Exported for tests and greppability. */
+export const RETRY_HOLD_KEY = 'retryPendingCleanup';
+export const RETRY_HOLD_SINCE_KEY = 'retryPendingSince';
+
+/**
+ * The metadata patch that ARMS the hold, merged into the failure verdict's own
+ * `updateTask` so the task never exists in a spawnable-but-pointerless state.
+ */
+export function retryHoldMetadata(now = Date.now()) {
+ return {
+ [RETRY_HOLD_KEY]: true,
+ [RETRY_HOLD_SINCE_KEY]: new Date(now).toISOString(),
+ };
+}
+
+/**
+ * The metadata patch that RELEASES the hold. `undefined` (not `null`) because
+ * `updateTask` deletes undefined keys from the merged metadata, whereas a null
+ * survives the merge and is serialized into TASKS.md as the literal string
+ * `"null"` — which would read back as a live marker.
+ */
+export function clearedRetryHoldMetadata() {
+ return {
+ [RETRY_HOLD_KEY]: undefined,
+ [RETRY_HOLD_SINCE_KEY]: undefined,
+ };
+}
+
+/**
+ * Is this task held pending its resume-pointer write? Accepts the markdown
+ * round-trip (`true` comes back as the string `'true'`), same as `isTruthyMeta`.
+ */
+export function isRetryHeld(metadata) {
+ const value = metadata?.[RETRY_HOLD_KEY];
+ return value === true || value === 'true';
+}
+
+/**
+ * A hold nobody is going to release — the process that armed it died before its
+ * cleanup finished. An unparseable or missing timestamp counts as stale: the marker
+ * is the evidence, the timestamp is only the liveness hint, and a hold we can't date
+ * must not strand the task forever.
+ */
+export function isStaleRetryHold(metadata, now = Date.now(), graceMs = RETRY_HOLD_GRACE_MS) {
+ if (!isRetryHeld(metadata)) return false;
+ const since = Date.parse(metadata?.[RETRY_HOLD_SINCE_KEY] ?? '');
+ if (!Number.isFinite(since)) return true;
+ return now - since >= graceMs;
+}
diff --git a/server/lib/taskRetryHold.test.js b/server/lib/taskRetryHold.test.js
new file mode 100644
index 0000000000..c79ba25a8c
--- /dev/null
+++ b/server/lib/taskRetryHold.test.js
@@ -0,0 +1,70 @@
+import { describe, expect, it } from 'vitest';
+import {
+ RETRY_HOLD_GRACE_MS,
+ retryHoldMetadata,
+ clearedRetryHoldMetadata,
+ isRetryHeld,
+ isStaleRetryHold,
+} from './taskRetryHold.js';
+
+const NOW = Date.parse('2026-08-02T12:00:00.000Z');
+
+describe('retryHoldMetadata / clearedRetryHoldMetadata', () => {
+ it('arms the marker with an ISO stamp', () => {
+ expect(retryHoldMetadata(NOW)).toEqual({
+ retryPendingCleanup: true,
+ retryPendingSince: '2026-08-02T12:00:00.000Z',
+ });
+ });
+
+ // `undefined` — not null: updateTask DELETES undefined keys from the merged
+ // metadata, while a null survives and TASKS.md serializes it as the string
+ // "null", which would read back as a live marker on the next boot.
+ it('clears with undefined so updateTask drops the keys entirely', () => {
+ const cleared = clearedRetryHoldMetadata();
+ expect(cleared.retryPendingCleanup).toBeUndefined();
+ expect(cleared.retryPendingSince).toBeUndefined();
+ expect(Object.keys(cleared)).toEqual(['retryPendingCleanup', 'retryPendingSince']);
+ expect(isRetryHeld({ ...retryHoldMetadata(NOW), ...cleared })).toBe(false);
+ });
+});
+
+describe('isRetryHeld', () => {
+ it('reads the boolean and its markdown round-trip string', () => {
+ expect(isRetryHeld({ retryPendingCleanup: true })).toBe(true);
+ expect(isRetryHeld({ retryPendingCleanup: 'true' })).toBe(true);
+ });
+
+ it('is false for anything else', () => {
+ expect(isRetryHeld({ retryPendingCleanup: false })).toBe(false);
+ expect(isRetryHeld({ retryPendingCleanup: 'false' })).toBe(false);
+ expect(isRetryHeld({ retryPendingCleanup: 'null' })).toBe(false);
+ expect(isRetryHeld({})).toBe(false);
+ expect(isRetryHeld(null)).toBe(false);
+ expect(isRetryHeld(undefined)).toBe(false);
+ });
+});
+
+describe('isStaleRetryHold', () => {
+ // A fresh hold means some in-process cleanup is still expected to release it;
+ // the sweep must leave it alone or it resolves the pointer mid-merge.
+ it('is not stale inside the grace window', () => {
+ expect(isStaleRetryHold(retryHoldMetadata(NOW), NOW + RETRY_HOLD_GRACE_MS - 1)).toBe(false);
+ });
+
+ it('is stale once the grace window elapses', () => {
+ expect(isStaleRetryHold(retryHoldMetadata(NOW), NOW + RETRY_HOLD_GRACE_MS)).toBe(true);
+ });
+
+ // The marker is the evidence; the stamp is only the liveness hint. A hold we
+ // cannot date must not strand the task forever.
+ it('treats a missing or unparseable stamp as stale', () => {
+ expect(isStaleRetryHold({ retryPendingCleanup: true }, NOW)).toBe(true);
+ expect(isStaleRetryHold({ retryPendingCleanup: true, retryPendingSince: 'not-a-date' }, NOW)).toBe(true);
+ });
+
+ it('is false for a task that is not held at all, however old', () => {
+ expect(isStaleRetryHold({ retryPendingSince: new Date(0).toISOString() }, NOW)).toBe(false);
+ expect(isStaleRetryHold({}, NOW)).toBe(false);
+ });
+});
diff --git a/server/services/agentCliSpawning.js b/server/services/agentCliSpawning.js
index 3b0f5b6686..e746424388 100644
--- a/server/services/agentCliSpawning.js
+++ b/server/services/agentCliSpawning.js
@@ -919,15 +919,17 @@ 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
+ // Release the retry hold: flip the failed task back to `pending` carrying a
+ // pointer at whatever the run left behind — the branch (or whole worktree)
+ // `cleanupWorktreeFn` just preserved because the run failed with commits on
+ // it. Without the pointer the retry starts clean and redoes work already
+ // sitting on disk (#3368); without the hold that release replaces, the retry
+ // could be dequeued before the pointer landed (#3373). 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}`));
+ .then(({ releaseRetryHold }) => releaseRetryHold({ agentId, task, success: cleanupSuccess }))
+ .catch(err => console.error(`❌ CLI retry-hold release 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.js
index 4724944436..9d10aeb65f 100644
--- a/server/services/agentCliSpawning.test.js
+++ b/server/services/agentCliSpawning.test.js
@@ -93,11 +93,11 @@ vi.mock('child_process', () => ({
// 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({}),
+ releaseRetryHold: vi.fn().mockResolvedValue({}),
}));
import { buildCliSpawnConfig, createStreamJsonParser, spawnDirectly } from './agentCliSpawning.js';
-import { recordResumePointerIfRetrying } from './agentWorktreeCleanup.js';
+import { releaseRetryHold } 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';
@@ -816,7 +816,7 @@ describe('stream error containment', () => {
// 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();
+ releaseRetryHold.mockClear();
const cleanupWorktreeFn = vi.fn().mockResolvedValue(undefined);
const task = { id: 'task-rp', description: 'do stuff', metadata: {} };
@@ -825,18 +825,18 @@ describe('stream error containment', () => {
fakeProcess.emit('close', 1);
await new Promise((r) => setTimeout(r, 80));
- expect(recordResumePointerIfRetrying).toHaveBeenCalledWith({
+ expect(releaseRetryHold).toHaveBeenCalledWith({
agentId: minimalArgs.agentId, task, success: false,
});
expect(cleanupWorktreeFn.mock.invocationCallOrder[0])
- .toBeLessThan(recordResumePointerIfRetrying.mock.invocationCallOrder[0]);
+ .toBeLessThan(releaseRetryHold.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();
+ releaseRetryHold.mockClear();
const task = { id: 'task-rp-ok', description: 'do stuff', metadata: {} };
spawnDirectly({ ...minimalArgs, task, cleanupWorktreeFn: vi.fn().mockResolvedValue(undefined), isTruthyMetaFn: (v) => v === true });
@@ -846,7 +846,7 @@ describe('stream error containment', () => {
fakeProcess.emit('close', 0);
await new Promise((r) => setTimeout(r, 80));
- expect(recordResumePointerIfRetrying).toHaveBeenCalledWith(expect.objectContaining({ success: true }));
+ expect(releaseRetryHold).toHaveBeenCalledWith(expect.objectContaining({ success: true }));
});
// pm2's TreeKill takes direct-CLI children down with portos-server exactly as
diff --git a/server/services/agentCompletionCleanup.js b/server/services/agentCompletionCleanup.js
index 05d2836835..2d399fe9f4 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, recordResumePointerIfRetrying } from './agentWorktreeCleanup.js';
+import { cleanupAgentWorktree, spawnMergeRecoveryTask, releaseRetryHold } from './agentWorktreeCleanup.js';
import { resolvePrCompletion } from '../lib/prDisposition.js';
import { canTypeSlashCommands } from '../lib/slashdoInvocation.js';
@@ -175,13 +175,39 @@ export async function handlePipelineProgression(task, agentId, success) {
* Called from `handleAgentCompletion` after `finalizeAgent`, inside its
* try/finally so `runnerAgents.delete(agentId)` still fires on a throw here.
*
+ * The retry hold is released in a `finally` (#3373): a failed task is left
+ * `in_progress` + held by `finalizeAgent` so nothing can dequeue its retry before
+ * the resume pointer is resolved, and ONLY this release makes it spawnable again.
+ * So it cannot hang off the `if (!jiraBranch)` worktree branch below, and it cannot
+ * be skipped by a throw from the JIRA/pipeline/Creative Director steps — either
+ * would leave the task held until the orphan sweep noticed.
+ *
* @param {{ agentId: string, task: object, agent: object, effectiveSuccess: boolean, outputBuffer: string }} params
*/
export async function runAgentCompletionCleanup({ agentId, task, agent, effectiveSuccess, outputBuffer }) {
- // Fetch agent state once for JIRA and plan-question blocks
+ // Fetch agent state once for JIRA, plan-question, and the resume pointer. Its
+ // worktree fields are stamped once at registerAgent and never mutated, so passing
+ // it to the release spares a re-read that would re-split the whole output.txt.
const { getAgent: getAgentState } = await import('./cos.js');
const agentState = await getAgentState(agentId).catch(() => null);
+ try {
+ await runCompletionCleanupSteps({ agentId, task, agent, agentState, effectiveSuccess, outputBuffer });
+ } finally {
+ await releaseRetryHold({
+ agentId,
+ task,
+ success: effectiveSuccess,
+ agentMetadata: agentState?.metadata ?? null,
+ }).catch(err => emitLog('warn', `Retry-hold release failed for ${agentId}: ${err.message}`, { agentId, taskId: task?.id }));
+ }
+}
+
+/**
+ * The cleanup steps themselves. Split from the public entry point above only so
+ * the retry-hold release can wrap them in a `finally` without re-indenting them.
+ */
+async function runCompletionCleanupSteps({ agentId, task, agent, agentState, effectiveSuccess, outputBuffer }) {
// JIRA integration: push branch, create PR, comment on ticket
const jiraTicketId = task?.metadata?.jiraTicketId;
const jiraBranch = task?.metadata?.jiraBranch;
@@ -342,21 +368,6 @@ export async function runAgentCompletionCleanup({ agentId, task, agent, effectiv
originalTask: task
});
- // 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.
- //
- // `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');
const currentAgent = await getAgentForResult(agentId).catch(() => null);
diff --git a/server/services/agentCompletionCleanup.test.js b/server/services/agentCompletionCleanup.test.js
index 163c75b324..40e6aac084 100644
--- a/server/services/agentCompletionCleanup.test.js
+++ b/server/services/agentCompletionCleanup.test.js
@@ -25,13 +25,13 @@ vi.mock('./codeReview.js', () => ({ resolveReviewLoopOptions: vi.fn().mockResolv
vi.mock('./agentWorktreeCleanup.js', () => ({
cleanupAgentWorktree: vi.fn().mockResolvedValue([]),
spawnMergeRecoveryTask: vi.fn(),
- recordResumePointerIfRetrying: vi.fn().mockResolvedValue({}),
+ releaseRetryHold: 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, getAgent } from './cos.js';
-import { cleanupAgentWorktree, recordResumePointerIfRetrying } from './agentWorktreeCleanup.js';
+import { cleanupAgentWorktree, releaseRetryHold } from './agentWorktreeCleanup.js';
const runningPipeline = (overrides = {}) => ({
id: 'p1',
@@ -195,13 +195,13 @@ describe('runAgentCompletionCleanup — resume pointer', () => {
agentId: 'a1', task, agent: { providerId: 'codex' }, effectiveSuccess: false, outputBuffer: '',
});
- expect(recordResumePointerIfRetrying).toHaveBeenCalledWith({
+ expect(releaseRetryHold).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]);
+ .toBeLessThan(releaseRetryHold.mock.invocationCallOrder[0]);
});
// A missing agent record must reach the helper as an explicit null, not
@@ -214,6 +214,33 @@ describe('runAgentCompletionCleanup — resume pointer', () => {
agentId: 'a1', task, agent: { providerId: 'codex' }, effectiveSuccess: false, outputBuffer: '',
});
- expect(recordResumePointerIfRetrying).toHaveBeenCalledWith(expect.objectContaining({ agentMetadata: null }));
+ expect(releaseRetryHold).toHaveBeenCalledWith(expect.objectContaining({ agentMetadata: null }));
+ });
+
+ // The release is what makes a held task spawnable again (#3373), so it cannot
+ // hang off the worktree-cleanup branch: a JIRA-branch task skips that block
+ // entirely, and previously skipped the pointer with it.
+ it('still releases the hold for a JIRA-branch task, which skips worktree cleanup', async () => {
+ getAgent.mockResolvedValue({ metadata: { isWorktree: true, sourceWorkspace: '/repo' } });
+ const jiraTask = { id: 't', taskType: 'user', metadata: { jiraTicketId: 'ABC-1', jiraBranch: 'feature/ABC-1' } };
+
+ await runAgentCompletionCleanup({
+ agentId: 'a1', task: jiraTask, agent: { providerId: 'codex' }, effectiveSuccess: false, outputBuffer: '',
+ });
+
+ expect(cleanupAgentWorktree).not.toHaveBeenCalled();
+ expect(releaseRetryHold).toHaveBeenCalledWith(expect.objectContaining({ agentId: 'a1', success: false }));
+ });
+
+ // ...and a throw from any earlier cleanup step must not strand the task held.
+ it('releases the hold even when a cleanup step throws', async () => {
+ getAgent.mockResolvedValue({ metadata: { isWorktree: true } });
+ cleanupAgentWorktree.mockRejectedValueOnce(new Error('git exploded'));
+
+ await expect(runAgentCompletionCleanup({
+ agentId: 'a1', task, agent: { providerId: 'codex' }, effectiveSuccess: false, outputBuffer: '',
+ })).rejects.toThrow('git exploded');
+
+ expect(releaseRetryHold).toHaveBeenCalledWith(expect.objectContaining({ agentId: 'a1' }));
});
});
diff --git a/server/services/agentErrorAnalysis.js b/server/services/agentErrorAnalysis.js
index 14240a554f..b1e7ec8526 100644
--- a/server/services/agentErrorAnalysis.js
+++ b/server/services/agentErrorAnalysis.js
@@ -11,6 +11,7 @@ import { cosEvents } from './cosEvents.js';
import { MAX_TOTAL_SPAWNS } from '../lib/validation.js';
import { redactOutput } from '../lib/commandSecurity.js';
import { stripAnsi } from '../lib/ansiStrip.js';
+import { retryHoldMetadata } from '../lib/taskRetryHold.js';
import { isTruthyMeta } from './agentState.js';
// Max retries before blocking a task
@@ -1036,23 +1037,28 @@ export async function maybeCreateInvestigationTask(agentId, task, analysis) {
}
/**
- * Pure decision logic for {@link resolveFailedTaskUpdate} — no I/O, no clock.
+ * Pure decision logic for {@link resolveFailedTaskUpdate} — no I/O, and no clock
+ * beyond the injectable `now`.
*
- * Decides whether a failed task should be blocked or retried, the metadata
- * fields to merge over `task.metadata` (timestamps excluded — they belong to
- * the async wrapper), and the analysis to hand to an investigation task.
- * Extracted so the branching can be unit-tested directly (see
- * `agentErrorAnalysis.test.js`) instead of through a drift-prone inline copy.
- * Whether an investigation task is actually created stays the sole concern of
- * {@link maybeCreateInvestigationTask}.
+ * Decides whether a failed task should be blocked or held for retry, the metadata
+ * fields to merge over `task.metadata` (the failure/blocked timestamps stay with
+ * the async wrapper; the retry hold's own stamp is part of the marker pair, so it
+ * is written here from the injected `now` rather than split across two files), and
+ * the analysis to hand to an investigation task. Extracted so the branching can be
+ * unit-tested directly (see `agentErrorAnalysis.test.js`) instead of through a
+ * drift-prone inline copy. Whether an investigation task is actually created stays
+ * the sole concern of {@link maybeCreateInvestigationTask}.
+ *
+ * `in_progress` is the RETRY status, not a typo: a retryable failure is held
+ * non-spawnable until its resume pointer is resolved (#3373, lib/taskRetryHold.js).
*
* @returns {{
- * status: 'blocked'|'pending',
+ * status: 'blocked'|'in_progress',
* investigationAnalysis: object|null,
* metadataUpdates: { failureCount?: number, lastErrorCategory?: string, [k: string]: unknown }
* }}
*/
-export function resolveFailedTaskDecision(task, errorAnalysis) {
+export function resolveFailedTaskDecision(task, errorAnalysis, now = Date.now()) {
// Actionable errors get blocked immediately. The investigation task (created
// by the wrapper unless the failure is an API-access error) gets the original
// analysis verbatim.
@@ -1093,13 +1099,24 @@ export function resolveFailedTaskDecision(task, errorAnalysis) {
}
// Retry: propagate compaction hints for retry prompt injection.
+ //
+ // The retry is NOT made spawnable here (#3373). The status stays `in_progress`
+ // and the task carries the retry-hold marker, because the resume pointer that
+ // lets this retry adopt the branch its dead run left behind can only be resolved
+ // after `cleanupAgentWorktree` decides what survived — which happens after this
+ // write lands. Flipping to `pending` now would let the dequeue that
+ // `agent:completed` schedules claim the retry with no pointer and start clean.
+ // `releaseRetryHold` (agentWorktreeCleanup.js) does the flip to `pending`
+ // together with the pointer, in one write; `handleOrphanedTask` finishes the
+ // transition if this process dies in between. See lib/taskRetryHold.js.
const compaction = errorAnalysis?.compaction || null;
return {
- status: 'pending',
+ status: 'in_progress',
investigationAnalysis: null,
metadataUpdates: {
failureCount,
lastErrorCategory,
+ ...retryHoldMetadata(now),
...(compaction && { compaction })
}
};
@@ -1146,10 +1163,12 @@ export function resolveTypeFailureSignal({ success, terminatedByUser = false, ho
* Tracks retry count and blocks the task after MAX_TASK_RETRIES,
* creating an investigation task instead of retrying endlessly.
*
- * Returns { status, metadata } to apply to the task.
+ * Returns { status, metadata } to apply to the task. A retry does NOT come back
+ * `pending`: it comes back `in_progress` + the retry-hold marker, and only becomes
+ * spawnable once `releaseRetryHold` writes the resume pointer (#3373).
*/
-export async function resolveFailedTaskUpdate(task, errorAnalysis, agentId) {
- const decision = resolveFailedTaskDecision(task, errorAnalysis);
+export async function resolveFailedTaskUpdate(task, errorAnalysis, agentId, now = Date.now()) {
+ const decision = resolveFailedTaskDecision(task, errorAnalysis, now);
const { failureCount, lastErrorCategory } = decision.metadataUpdates;
// Actionable errors get blocked immediately (investigation task created unless API access is denied)
@@ -1160,7 +1179,7 @@ export async function resolveFailedTaskUpdate(task, errorAnalysis, agentId) {
await maybeCreateInvestigationTask(agentId, task, decision.investigationAnalysis);
return {
status: decision.status,
- metadata: { ...task.metadata, ...decision.metadataUpdates, blockedAt: new Date().toISOString() }
+ metadata: { ...task.metadata, ...decision.metadataUpdates, blockedAt: new Date(now).toISOString() }
};
}
@@ -1169,18 +1188,18 @@ export async function resolveFailedTaskUpdate(task, errorAnalysis, agentId) {
taskId: task.id, failureCount, category: lastErrorCategory
});
await maybeCreateInvestigationTask(agentId, task, decision.investigationAnalysis);
- const now = new Date().toISOString();
+ const at = new Date(now).toISOString();
return {
status: 'blocked',
- metadata: { ...task.metadata, ...decision.metadataUpdates, lastFailureAt: now, blockedAt: now }
+ metadata: { ...task.metadata, ...decision.metadataUpdates, lastFailureAt: at, blockedAt: at }
};
}
- emitLog('info', `🔄 Task ${task.id} retry ${failureCount}/${MAX_TASK_RETRIES} (${lastErrorCategory})`, {
+ emitLog('info', `🔄 Task ${task.id} retry ${failureCount}/${MAX_TASK_RETRIES} held for cleanup (${lastErrorCategory})`, {
taskId: task.id, failureCount, maxRetries: MAX_TASK_RETRIES, category: lastErrorCategory
});
return {
- status: 'pending',
- metadata: { ...task.metadata, ...decision.metadataUpdates, lastFailureAt: new Date().toISOString() }
+ status: decision.status,
+ metadata: { ...task.metadata, ...decision.metadataUpdates, lastFailureAt: new Date(now).toISOString() }
};
}
diff --git a/server/services/agentErrorAnalysis.test.js b/server/services/agentErrorAnalysis.test.js
index c25af7c9ad..2741781226 100644
--- a/server/services/agentErrorAnalysis.test.js
+++ b/server/services/agentErrorAnalysis.test.js
@@ -27,6 +27,10 @@ import { API_ACCESS_ERROR_CATEGORIES } from './agentErrorAnalysis.js';
import { ENVIRONMENTAL_ERROR_CATEGORIES } from './taskLearning/metrics.js';
import { addTask, updateTask, getAllTasks } from './cos.js';
import { MAX_TOTAL_SPAWNS } from '../lib/validation.js';
+import { groupTasksByStatus, getAutoApprovedTasks, getAwaitingApprovalTasks } from '../lib/taskParser.js';
+
+// Fixed clock for the retry-hold stamp, so the assertion is exact.
+const HOLD_NOW = Date.parse('2026-08-02T12:00:00.000Z');
// Default store shape for suites that exercise the create path: no existing
// tasks, so the fingerprint dedup never fires unless a test arranges it.
@@ -262,9 +266,13 @@ describe('resolveFailedTaskDecision', () => {
});
describe('non-actionable errors with retry tracking', () => {
+ // NOT `pending` (#3373): the retry is HELD non-spawnable — `in_progress` plus
+ // the hold marker — until `releaseRetryHold` writes its resume pointer.
it('retries on the first failure (failureCount → 1) with no investigation', () => {
- const decision = resolveFailedTaskDecision(task(), { actionable: false, category: 'rate-limit', message: 'Rate limited' });
- expect(decision.status).toBe('pending');
+ const decision = resolveFailedTaskDecision(task(), { actionable: false, category: 'rate-limit', message: 'Rate limited' }, HOLD_NOW);
+ expect(decision.status).toBe('in_progress');
+ expect(decision.metadataUpdates.retryPendingCleanup).toBe(true);
+ expect(decision.metadataUpdates.retryPendingSince).toBe(new Date(HOLD_NOW).toISOString());
expect(decision.metadataUpdates.failureCount).toBe(1);
expect(decision.metadataUpdates.lastErrorCategory).toBe('rate-limit');
expect(decision.investigationAnalysis).toBeNull();
@@ -292,7 +300,7 @@ describe('resolveFailedTaskDecision', () => {
it('propagates compaction hints into the retry metadata (also missed by the inline copy)', () => {
const compaction = { needed: true, reason: 'context-limit' };
const decision = resolveFailedTaskDecision(task(), { actionable: false, category: 'context-length', message: 'too big', compaction });
- expect(decision.status).toBe('pending');
+ expect(decision.status).toBe('in_progress');
expect(decision.metadataUpdates.compaction).toEqual(compaction);
});
});
@@ -300,7 +308,7 @@ describe('resolveFailedTaskDecision', () => {
describe('missing errorAnalysis', () => {
it('treats null as a non-actionable unknown error', () => {
const decision = resolveFailedTaskDecision(task(), null);
- expect(decision.status).toBe('pending');
+ expect(decision.status).toBe('in_progress');
expect(decision.metadataUpdates.failureCount).toBe(1);
expect(decision.metadataUpdates.lastErrorCategory).toBe('unknown');
});
@@ -311,6 +319,33 @@ describe('resolveFailedTaskDecision', () => {
expect(decision.metadataUpdates.failureCount).toBe(MAX_TASK_RETRIES);
});
});
+
+ // Acceptance criterion (#3373): a dequeue that runs during the cleanup window
+ // must not claim the retry. Every dequeue tier selects candidates through these
+ // two taskParser helpers (`grouped.pending` for user tasks, `autoApproved` for
+ // system tasks), so asserting against the REAL helpers — rather than restating
+ // "status !== pending" — is what proves no tier can see the held task.
+ describe('a held retry is not a dequeue candidate', () => {
+ const applyDecision = (base, decision) => ({ ...base, status: decision.status, metadata: { ...base.metadata, ...decision.metadataUpdates } });
+
+ it('is excluded from the pending, auto-approved, and approval queues', () => {
+ const base = { id: 'task-1', description: 'do a thing', priority: 'HIGH', priorityValue: 3, autoApproved: true, approvalRequired: false, metadata: {} };
+ const held = applyDecision(base, resolveFailedTaskDecision(base, { actionable: false, category: 'rate-limit', message: 'Rate limited' }, HOLD_NOW));
+
+ expect(groupTasksByStatus([held]).pending).toEqual([]);
+ expect(groupTasksByStatus([held]).in_progress).toEqual([held]);
+ expect(getAutoApprovedTasks([held])).toEqual([]);
+ expect(getAwaitingApprovalTasks([{ ...held, approvalRequired: true, autoApproved: false }])).toEqual([]);
+ });
+
+ // ...and a blocked task gets no hold at all, so nothing has to release it.
+ it('a blocked task carries no hold marker', () => {
+ const decision = resolveFailedTaskDecision({ id: 'task-1', metadata: { failureCount: MAX_TASK_RETRIES - 1 } }, { actionable: false, category: 'network-error', message: 'Network failed' }, HOLD_NOW);
+ expect(decision.status).toBe('blocked');
+ expect(decision.metadataUpdates.retryPendingCleanup).toBeUndefined();
+ expect(decision.metadataUpdates.retryPendingSince).toBeUndefined();
+ });
+ });
});
describe('resolveTypeFailureSignal (#2616)', () => {
diff --git a/server/services/agentManagement.js b/server/services/agentManagement.js
index db87b879bb..b5345ac0d1 100644
--- a/server/services/agentManagement.js
+++ b/server/services/agentManagement.js
@@ -20,6 +20,7 @@ import { activeAgents, runnerAgents, userTerminatedAgents, pausedAgents, useRunn
// 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, resolveTaskResumePatch } from './agentWorktreeCleanup.js';
+import { isRetryHeld, clearedRetryHoldMetadata } from '../lib/taskRetryHold.js';
import { syncRunnerAgents } from './agentRunnerSync.js';
import { flushRunnerOutputBatcher } from './agentRunnerOutputBatchers.js';
import { checkForTaskCommit, completeAgentRun } from './agentRunTracking.js';
@@ -795,6 +796,29 @@ export async function handleOrphanedTask(taskId, agentId, getTaskByIdFn, { agent
return;
}
+ // A retry hold whose process died mid-transition (#3373). The run's verdict is
+ // already persisted — it failed, and was budgeted a retry — so this is not a
+ // fresh orphan: finish the transition the dead process started (resolve the
+ // pointer, flip to `pending`, drop the marker) rather than charging it orphan
+ // budget for a decision that was already made. Runs BEFORE the commit check
+ // below: a failed run that committed is exactly the case the resume pointer
+ // exists for, and completing the task on that evidence would discard the retry
+ // finalizeAgent already granted.
+ if (isRetryHeld(task.metadata)) {
+ const resumePatch = await resolveTaskResumePatch({ task, agentId, agentMetadata }).catch(err => {
+ emitLog('warn', `Resume pointer for held task ${taskId} could not be resolved: ${err.message}`, { taskId, agentId });
+ return {};
+ });
+ emitLog('info', `🔓 Completing interrupted retry transition for task ${taskId}${resumePatch.existingBranch ? ` — resuming ${resumePatch.existingBranch}` : ''}`, {
+ taskId, agentId, branchName: resumePatch.existingBranch || null
+ });
+ await updateTask(taskId, {
+ status: 'pending',
+ metadata: { ...resumePatch, ...clearedRetryHoldMetadata() }
+ }, task.taskType || 'user');
+ return;
+ }
+
// Check if the agent actually committed work before treating as orphaned
const commitFound = await checkForTaskCommit(taskId, agentMetadata?.workspacePath || ROOT_DIR);
if (commitFound) {
diff --git a/server/services/agentManagement.test.js b/server/services/agentManagement.test.js
index 10a56f3899..0c0ecf7907 100644
--- a/server/services/agentManagement.test.js
+++ b/server/services/agentManagement.test.js
@@ -905,6 +905,88 @@ describe('orphan retries resume what the dead run left behind', () => {
});
});
+// The crash-recovery half of the retry hold (#3373). finalizeAgent left the task
+// `in_progress` + held so nothing could dequeue its retry before the resume pointer
+// landed; if the process dies before `releaseRetryHold` runs, the marker on disk is
+// what stops the task being stranded non-spawnable forever.
+describe('the orphan sweep finishes an interrupted retry transition (#3373)', () => {
+ const heldTask = () => ({
+ id: 'task-1',
+ taskType: 'user',
+ status: 'in_progress',
+ metadata: { retryPendingCleanup: true, retryPendingSince: new Date().toISOString(), failureCount: 1 },
+ });
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ getAgents.mockResolvedValue([]);
+ resolveTaskResumePatch.mockResolvedValue({});
+ checkForTaskCommit.mockResolvedValue(false);
+ activeAgents.clear();
+ runnerAgents.clear();
+ });
+
+ // `clearAllMocks` keeps implementations, so hand the commit check back in the
+ // state the suites after this one expect (no queued verdict).
+ afterEach(() => {
+ checkForTaskCommit.mockReset();
+ });
+
+ it('flips the held task to pending with the resume pointer and drops the marker', async () => {
+ getTaskById.mockResolvedValue(heldTask());
+ resolveTaskResumePatch.mockResolvedValue({ existingBranch: 'cos/task-1/agent-dead', resumedFromAgentId: 'agent-dead', resumeWorktreePath: null });
+
+ await handleOrphanedTask('task-1', 'agent-dead', getTaskById, {
+ agentMetadata: { isWorktree: true, sourceWorkspace: '/repo', worktreeBranch: 'cos/task-1/agent-dead' },
+ });
+
+ expect(updateTask).toHaveBeenCalledWith('task-1', {
+ status: 'pending',
+ metadata: {
+ existingBranch: 'cos/task-1/agent-dead',
+ resumedFromAgentId: 'agent-dead',
+ resumeWorktreePath: null,
+ retryPendingCleanup: undefined,
+ retryPendingSince: undefined,
+ },
+ }, 'user');
+ });
+
+ // The verdict was already reached and already budgeted a retry — this is not a
+ // fresh orphan, so it costs no orphan-retry budget and arms no cooldown.
+ it('charges no orphan-retry budget for finishing the transition', async () => {
+ getTaskById.mockResolvedValue(heldTask());
+
+ await handleOrphanedTask('task-1', 'agent-dead', getTaskById, { agentMetadata: null });
+
+ const [, update] = updateTask.mock.calls[0];
+ expect(update.metadata.orphanRetryCount).toBeUndefined();
+ expect(update.metadata.lastOrphanedAt).toBeUndefined();
+ });
+
+ // A failed run that committed is exactly what the resume pointer is FOR —
+ // completing the task on that evidence would discard the granted retry.
+ it('does not let the commit check complete a held task', async () => {
+ getTaskById.mockResolvedValue(heldTask());
+ checkForTaskCommit.mockResolvedValue(true);
+
+ await handleOrphanedTask('task-1', 'agent-dead', getTaskById, { agentMetadata: null });
+
+ expect(checkForTaskCommit).not.toHaveBeenCalled();
+ expect(updateTask).toHaveBeenCalledWith('task-1', expect.objectContaining({ status: 'pending' }), 'user');
+ });
+
+ // A user-terminated (or budget-exhausted) task is blocked and never held, so the
+ // pre-existing guards still win over the hold branch.
+ it('still skips a user-terminated task', async () => {
+ getTaskById.mockResolvedValue({ id: 'task-1', taskType: 'user', status: 'blocked', metadata: { blockedCategory: 'user-terminated', retryPendingCleanup: true } });
+
+ await handleOrphanedTask('task-1', 'agent-dead', getTaskById, { agentMetadata: null });
+
+ expect(updateTask).not.toHaveBeenCalled();
+ });
+});
+
// A PortOS restart kills every server-owned agent. Charging those runs the same
// retry budget as a self-inflicted crash meant three routine restarts blocked the
// task outright — and the second restart in the reported reproduction landed it in
diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.js
index 7576e61aa8..957e4811b9 100644
--- a/server/services/agentTuiSpawning.js
+++ b/server/services/agentTuiSpawning.js
@@ -690,15 +690,17 @@ 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
+ // Release the retry hold: flip the failed task back to `pending` carrying a
+ // pointer at whatever the run left behind — the branch (or whole worktree)
+ // `cleanupWorktreeFn` just preserved because the run failed with commits on
+ // it. Without the pointer the retry starts clean and redoes work already
+ // sitting on disk (#3368); without the hold that release replaces, the retry
+ // could be dequeued before the pointer landed (#3373). 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 }));
+ .then(({ releaseRetryHold }) => releaseRetryHold({ agentId, task, success: cleanupSuccess }))
+ .catch(err => emitLog('warn', `TUI retry-hold release failed for ${agentId}: ${err.message}`, { agentId }));
if (agentData?.pid) unregisterSpawnedAgent(agentData.pid);
activeAgents.delete(agentId);
diff --git a/server/services/agentTuiSpawning.test.js b/server/services/agentTuiSpawning.test.js
index e10225e3aa..7c9a5af1fa 100644
--- a/server/services/agentTuiSpawning.test.js
+++ b/server/services/agentTuiSpawning.test.js
@@ -104,7 +104,7 @@ vi.mock('./git.js', () => ({
// 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({}),
+ releaseRetryHold: vi.fn().mockResolvedValue({}),
}));
vi.mock('fs', () => ({
@@ -191,7 +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 { releaseRetryHold } from './agentWorktreeCleanup.js';
import { spawnTuiSessionViaRunner } from './cosRunnerClient.js';
import * as shellService from './shell.js';
import * as agentLifecycle from './agentFinalization.js';
@@ -635,7 +635,7 @@ describe('spawnTuiAgent runtime', () => {
// 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();
+ vi.mocked(releaseRetryHold).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 } });
@@ -644,23 +644,23 @@ describe('spawnTuiAgent runtime', () => {
await capturedOnExit({ exitCode: 1, killed: false });
await spawnPromise;
- expect(recordResumePointerIfRetrying).toHaveBeenCalledWith({ agentId: 'agent-1', task, success: false });
+ expect(releaseRetryHold).toHaveBeenCalledWith({ agentId: 'agent-1', task, success: false });
expect(cleanupWorktreeFn.mock.invocationCallOrder[0])
- .toBeLessThan(vi.mocked(recordResumePointerIfRetrying).mock.invocationCallOrder[0]);
+ .toBeLessThan(vi.mocked(releaseRetryHold).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();
+ vi.mocked(releaseRetryHold).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 }));
+ expect(releaseRetryHold).toHaveBeenCalledWith(expect.objectContaining({ success: true }));
});
// ── 1. Successful idle-complete path ────────────────────────────────────────
diff --git a/server/services/agentWorktreeCleanup.js b/server/services/agentWorktreeCleanup.js
index a01c1f6243..5468cd4869 100644
--- a/server/services/agentWorktreeCleanup.js
+++ b/server/services/agentWorktreeCleanup.js
@@ -22,6 +22,7 @@ import * as git from './git.js';
import { removeWorktree, classifyWorktreeDirt } from './worktreeManager.js';
import { isTruthyMeta } from './agentState.js';
import { PATHS } from '../lib/fileUtils.js';
+import { isRetryHeld, clearedRetryHoldMetadata } from '../lib/taskRetryHold.js';
import { RECOVERY_TASK_PREFIX } from './recoveryTasks.js';
import { detectForgeCli } from '../lib/gitForge.js';
import { PR_COMPLETIONS, PR_COMPLETION_VALUES, leavesPrForHuman } from '../lib/prDisposition.js';
@@ -491,7 +492,12 @@ export function resumePointerMetadata(pointer, agentId, task) {
};
}
if (!task?.metadata?.resumedFromAgentId) return {};
- return { existingBranch: null, resumedFromAgentId: null, resumeWorktreePath: null };
+ // `undefined`, not `null`: `updateTask` DELETES undefined keys from the merged
+ // metadata, while a null survives the merge and TASKS.md serializes it as the
+ // literal string `"null"` — which reads back as a truthy `existingBranch` and
+ // sends the next attempt looking for a branch named "null". The keys are still
+ // present on the returned patch, so callers can tell a clear from a no-op.
+ return { existingBranch: undefined, resumedFromAgentId: undefined, resumeWorktreePath: undefined };
}
/**
@@ -516,7 +522,8 @@ export async function recordTaskResumePointer({ task, agentId, agentMetadata })
}
/**
- * The post-cleanup resume-pointer write, shared by every spawn mode (#3368).
+ * The post-cleanup write that RELEASES a failed task's retry hold, shared by every
+ * spawn mode (#3368, #3373).
*
* A failed agent whose branch — or whole worktree — survived cleanup leaves real
* work behind (see `preserveBranchWithCommits` above; a dirty tree aborts removal
@@ -533,13 +540,21 @@ export async function recordTaskResumePointer({ task, agentId, agentMetadata })
* 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, and
- * that a later `reviveBlockedTask` would resurrect as a live pointer to a branch
- * nobody vetted. So the pointer needs a task record we actually READ saying
- * `pending`; a failed read or a task deleted mid-run is not evidence of a retry.
+ * been persisted by `finalizeAgent` at this point, and a retryable failure leaves
+ * the task HELD — `in_progress` plus the retry-hold marker (#3373,
+ * lib/taskRetryHold.js) — precisely so nothing can dequeue it during the cleanup
+ * this call follows. Releasing the hold and writing the pointer is therefore ONE
+ * `updateTask`: the task becomes spawnable and pointed in the same write, never
+ * spawnable-then-pointed. A `blocked` task that exhausted its budget carries no
+ * hold and gets no pointer — dead metadata `updateTask` would strip again on the
+ * next terminal write, and that a later `reviveBlockedTask` would resurrect as a
+ * live pointer to a branch nobody vetted.
+ *
+ * The no-hold fallback (a task we read as plain `pending`) still writes the pointer
+ * alone: that is the pre-#3373 shape, and it is also what a task the orphan sweep
+ * already recovered mid-cleanup looks like. Anything else we read — `blocked`,
+ * `in_progress` without the marker (the retry already spawned), a failed read, a
+ * task deleted mid-run — is not evidence of a retry, so we write nothing.
*
* `agentMetadata` is optional: pass it when the caller already holds the agent
* record (the runner path does), omit it and this reads the record itself —
@@ -549,9 +564,9 @@ export async function recordTaskResumePointer({ task, agentId, agentMetadata })
* `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)
+ * @returns {Promise<object>} the metadata patch that was written (empty when nothing was)
*/
-export async function recordResumePointerIfRetrying({ agentId, task, success, agentMetadata }) {
+export async function releaseRetryHold({ agentId, task, success, agentMetadata }) {
if (success || !agentId || !task?.id) return {};
const { getTaskById, getAgentRecord } = await import('./cos.js');
@@ -559,14 +574,44 @@ export async function recordResumePointerIfRetrying({ agentId, task, success, ag
emitLog('warn', `Skipping resume pointer for task ${task.id} — status unreadable: ${err.message}`, { taskId: task.id, agentId });
return null;
});
+ if (!persisted) return {};
+
+ const held = isRetryHeld(persisted.metadata);
// A record with no `status` at all is a legacy shape that predates the field;
- // those are pending. A record we couldn't read, or that is gone, is neither.
- if (!persisted || (persisted.status ?? 'pending') !== 'pending') return {};
+ // those are pending.
+ if (!held && (persisted.status ?? 'pending') !== 'pending') return {};
const metadata = agentMetadata === undefined
? (await getAgentRecord(agentId).catch(() => null))?.metadata
: agentMetadata;
- return await recordTaskResumePointer({ task, agentId, agentMetadata: metadata });
+
+ if (!held) return await recordTaskResumePointer({ task, agentId, agentMetadata: metadata });
+
+ // Fails open to "start clean" for the same reason `handleOrphanedTask` does:
+ // requeueing the task matters far more than resuming it, and a throw here would
+ // leave it held until the orphan sweep.
+ const patch = await resolveTaskResumePatch({ task, agentId, agentMetadata: metadata }).catch(err => {
+ emitLog('warn', `Resume pointer for task ${task.id} could not be resolved: ${err.message}`, { taskId: task.id, agentId });
+ return {};
+ });
+ const taskType = task.taskType || persisted.taskType || 'user';
+ const result = await updateTask(task.id, {
+ status: 'pending',
+ metadata: { ...patch, ...clearedRetryHoldMetadata() }
+ }, taskType).catch(err => {
+ emitLog('warn', `Failed to release retry hold on task ${task.id}: ${err.message}`, { taskId: task.id, agentId });
+ return { error: err.message };
+ });
+ if (result?.error) {
+ // The hold is still on disk, so the orphan sweep finishes the transition —
+ // the task is delayed, never stranded.
+ emitLog('warn', `⏳ Task ${task.id} still held after a failed release — the orphan sweep will requeue it`, { taskId: task.id, agentId });
+ return {};
+ }
+ emitLog('info', patch.existingBranch
+ ? `🔁 Task ${task.id} requeued pointing at ${patch.existingBranch}`
+ : `🔓 Task ${task.id} requeued for retry`, { taskId: task.id, agentId, branchName: patch.existingBranch || null });
+ return patch;
}
/**
diff --git a/server/services/cleanupAgentWorktree.test.js b/server/services/cleanupAgentWorktree.test.js
index 02f1943440..d0205f8f6d 100644
--- a/server/services/cleanupAgentWorktree.test.js
+++ b/server/services/cleanupAgentWorktree.test.js
@@ -213,7 +213,7 @@ 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, recordResumePointerIfRetrying, resumePointerMetadata } from './agentWorktreeCleanup.js';
+import { resolveResumePointer, resolveTaskResumePatch, recordTaskResumePointer, releaseRetryHold, resumePointerMetadata } from './agentWorktreeCleanup.js';
import { getAgent, getAgentRecord, getTaskById, addTask, updateTask } from './cos.js';
import { removeWorktree } from './worktreeManager.js';
import { PATHS } from '../lib/fileUtils.js';
@@ -1188,7 +1188,7 @@ describe('resolveTaskResumePatch / recordTaskResumePointer', () => {
await recordTaskResumePointer({ task, agentId: 'agent-x', agentMetadata });
expect(updateTask).toHaveBeenCalledWith('task-1', {
- metadata: { existingBranch: null, resumedFromAgentId: null, resumeWorktreePath: null }
+ metadata: { existingBranch: undefined, resumedFromAgentId: undefined, resumeWorktreePath: undefined }
}, 'user');
});
@@ -1223,10 +1223,12 @@ 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', () => {
+// The shared post-cleanup gate every spawn mode calls (#3368, #3373). 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. It now also RELEASES
+// the retry hold the failure verdict armed, so the task becomes spawnable and
+// pointed in one write.
+describe('releaseRetryHold', () => {
const agentMetadata = {
isWorktree: true, sourceWorkspace: '/repo',
worktreeBranch: DEAD_BRANCH, workspacePath: DEAD_TREE
@@ -1248,7 +1250,7 @@ describe('recordResumePointerIfRetrying', () => {
// helper has to read it for the worktree fields — via the transcript-free
// `getAgentRecord`, since a long TUI run's output.txt is megabytes.
it('records the pointer for a failed run whose task is still pending', async () => {
- await recordResumePointerIfRetrying({ agentId: 'agent-x', task: task(), success: false });
+ await releaseRetryHold({ agentId: 'agent-x', task: task(), success: false });
expect(getAgentRecord).toHaveBeenCalledWith('agent-x');
expect(getAgent).not.toHaveBeenCalled();
@@ -1262,13 +1264,13 @@ describe('recordResumePointerIfRetrying', () => {
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 });
+ await releaseRetryHold({ 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 });
+ await releaseRetryHold({ agentId: 'agent-x', task: task(), success: true });
expect(getTaskById).not.toHaveBeenCalled();
expect(updateTask).not.toHaveBeenCalled();
@@ -1280,7 +1282,7 @@ describe('recordResumePointerIfRetrying', () => {
it('records nothing when the task status is unreadable', async () => {
getTaskById.mockRejectedValue(new Error('read failed'));
- await recordResumePointerIfRetrying({ agentId: 'agent-x', task: task(), success: false });
+ await releaseRetryHold({ agentId: 'agent-x', task: task(), success: false });
expect(updateTask).not.toHaveBeenCalled();
});
@@ -1288,7 +1290,7 @@ describe('recordResumePointerIfRetrying', () => {
it('records nothing when the task was deleted mid-run', async () => {
getTaskById.mockResolvedValue(null);
- await recordResumePointerIfRetrying({ agentId: 'agent-x', task: task(), success: false });
+ await releaseRetryHold({ agentId: 'agent-x', task: task(), success: false });
expect(updateTask).not.toHaveBeenCalled();
});
@@ -1297,26 +1299,102 @@ describe('recordResumePointerIfRetrying', () => {
it('treats a status-less legacy task record as pending', async () => {
getTaskById.mockResolvedValue({ id: 'task-1' });
- await recordResumePointerIfRetrying({ agentId: 'agent-x', task: task(), success: false });
+ await releaseRetryHold({ agentId: 'agent-x', task: task(), success: false });
expect(updateTask).toHaveBeenCalled();
});
// The runner path already holds the agent record; passing it spares a re-read.
it('uses caller-supplied agent metadata instead of re-reading the record', async () => {
- await recordResumePointerIfRetrying({ agentId: 'agent-x', task: task(), success: false, agentMetadata });
+ await releaseRetryHold({ agentId: 'agent-x', task: task(), success: false, agentMetadata });
expect(getAgentRecord).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 });
+ await releaseRetryHold({ agentId: '', task: task(), success: false });
+ await releaseRetryHold({ agentId: 'agent-x', task: { metadata: {} }, success: false });
expect(getTaskById).not.toHaveBeenCalled();
expect(updateTask).not.toHaveBeenCalled();
});
+
+ // The #3373 shape. The failure verdict left the task `in_progress` + held; the
+ // flip to `pending` and the pointer MUST be the same write, or a dequeue between
+ // them claims the retry with no pointer and restarts from scratch.
+ describe('a held task (#3373)', () => {
+ const heldTask = { id: 'task-1', status: 'in_progress', metadata: { retryPendingCleanup: true, retryPendingSince: new Date().toISOString() } };
+
+ it('flips to pending WITH the pointer and the cleared marker in one updateTask', async () => {
+ getTaskById.mockResolvedValue(heldTask);
+
+ await releaseRetryHold({ agentId: 'agent-x', task: task(), success: false, agentMetadata });
+
+ expect(updateTask).toHaveBeenCalledTimes(1);
+ expect(updateTask).toHaveBeenCalledWith('task-1', {
+ status: 'pending',
+ metadata: {
+ existingBranch: DEAD_BRANCH,
+ resumedFromAgentId: 'agent-x',
+ resumeWorktreePath: null,
+ retryPendingCleanup: undefined,
+ retryPendingSince: undefined,
+ }
+ }, 'user');
+ });
+
+ // Nothing survived cleanup — the task still has to become spawnable, it just
+ // starts clean. Releasing the hold is NOT conditional on having a pointer.
+ it('still releases the hold when there is nothing left to resume', async () => {
+ getTaskById.mockResolvedValue(heldTask);
+ git.getBranchComparison.mockResolvedValue({ ahead: 0, commits: [], stats: {} });
+
+ await releaseRetryHold({ agentId: 'agent-x', task: task(), success: false, agentMetadata });
+
+ expect(updateTask).toHaveBeenCalledWith('task-1', {
+ status: 'pending',
+ metadata: { retryPendingCleanup: undefined, retryPendingSince: undefined }
+ }, 'user');
+ });
+
+ // The markdown round-trip stores metadata booleans as strings.
+ it('recognizes the hold marker after a markdown round-trip', async () => {
+ getTaskById.mockResolvedValue({ ...heldTask, metadata: { retryPendingCleanup: 'true' } });
+
+ await releaseRetryHold({ agentId: 'agent-x', task: task(), success: false, agentMetadata });
+
+ expect(updateTask).toHaveBeenCalledWith('task-1', expect.objectContaining({ status: 'pending' }), 'user');
+ });
+
+ // The orphan sweep got there first and already requeued + cleared the hold, or
+ // the retry has since spawned. Either way this run no longer owns the task.
+ it('writes nothing when the hold is gone and the task is in_progress again', async () => {
+ getTaskById.mockResolvedValue({ id: 'task-1', status: 'in_progress', metadata: {} });
+
+ await releaseRetryHold({ agentId: 'agent-x', task: task(), success: false, agentMetadata });
+
+ expect(updateTask).not.toHaveBeenCalled();
+ });
+
+ // A blocked task is never held, so it can never be flipped spawnable here.
+ it('never flips a blocked task, even one carrying a stale marker', async () => {
+ getTaskById.mockResolvedValue({ id: 'task-1', status: 'blocked', metadata: {} });
+
+ await releaseRetryHold({ agentId: 'agent-x', task: task(), success: false, agentMetadata });
+
+ expect(updateTask).not.toHaveBeenCalled();
+ });
+
+ // The hold stays on disk, so the orphan sweep can finish the transition.
+ it('leaves the task held when the release write fails', async () => {
+ getTaskById.mockResolvedValue(heldTask);
+ updateTask.mockResolvedValueOnce({ error: 'Task file not found' });
+
+ await expect(releaseRetryHold({ agentId: 'agent-x', task: task(), success: false, agentMetadata }))
+ .resolves.toEqual({});
+ });
+ });
});
describe('resumePointerMetadata', () => {
@@ -1330,7 +1408,7 @@ describe('resumePointerMetadata', () => {
// 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
+ existingBranch: undefined, resumedFromAgentId: undefined, resumeWorktreePath: undefined
});
});
diff --git a/server/services/cos.js b/server/services/cos.js
index ba889cfabd..95c20c56b2 100644
--- a/server/services/cos.js
+++ b/server/services/cos.js
@@ -18,6 +18,7 @@ import { join } from 'path';
import { v4 as uuidv4 } from '../lib/uuid.js';
import { getActiveProvider } from './providers.js';
import { isInternalTaskId } from '../lib/taskParser.js';
+import { isRetryHeld, isStaleRetryHold } from '../lib/taskRetryHold.js';
import { isAppOnCooldown, markAppReviewCooldown, bindAppReviewAgent, clearStaleActiveAgents } from './appActivity.js';
import { getActiveApps } from './apps.js';
import { getPerformanceSummary, checkAndRehabilitateSkippedTasks, getLearningInsights } from './taskLearning.js';
@@ -236,7 +237,7 @@ export async function start() {
]);
// Then reset any orphaned in_progress tasks (no running agent)
- await resetOrphanedTasks();
+ await resetOrphanedTasks({ bootRecovery: true });
// Clear stale activeAgentId pointers in app-activity.json. Without this, an
// idle-review agent that died across a restart (or a long-stale Feb-era state
@@ -510,8 +511,13 @@ export async function forceSpawnTask(taskId) {
/**
* Reset orphaned in_progress tasks back to pending
* (tasks marked in_progress but no running agent)
+ *
+ * `bootRecovery` says this is the startup pass, where no in-process worktree
+ * cleanup can possibly be running — so a retry hold (#3373) is recovered
+ * immediately instead of waiting out its liveness grace, which on the periodic
+ * pass is what stops the sweep stealing a task mid-cleanup.
*/
-async function resetOrphanedTasks() {
+async function resetOrphanedTasks({ bootRecovery = false } = {}) {
const state = await loadState();
const { user: userTaskData, cos: cosTaskData } = await getAllTasks();
@@ -597,6 +603,17 @@ async function resetOrphanedTasks() {
emitLog('debug', `Skipping task ${task.id} — agent recently completed, awaiting task status update`, { taskId: task.id });
continue;
}
+ // A failed task held non-spawnable while its worktree cleanup resolves the
+ // resume pointer (#3373). While the hold is fresh some in-process cleanup is
+ // still expected to release it, so leave it alone — requeueing here would
+ // resolve the pointer against a branch mid-merge. Once the hold is stale (or
+ // this is the boot pass, where nothing can be mid-cleanup) the process that
+ // armed it is gone, and handleOrphanedTask finishes the transition instead
+ // of treating the task as a fresh orphan.
+ if (isRetryHeld(task.metadata) && !bootRecovery && !isStaleRetryHold(task.metadata)) {
+ emitLog('debug', `Skipping task ${task.id} — retry held while its worktree cleanup finishes`, { taskId: task.id });
+ continue;
+ }
// If the agent completed successfully but task wasn't updated (silent updateTask failure),
// complete the task now instead of treating it as orphaned
const successAgentId = successfullyCompletedTaskIds.get(task.id);
@@ -1268,6 +1285,9 @@ export async function init() {
// - 'approved': a newly approved internal task can now spawn — re-run dequeue.
// - 'unblocked': a blocked task flipped back to pending (revive/retry, #2614)
// is newly spawnable exactly like an approval — re-run dequeue.
+ // - 'requeued': an in_progress task flipped back to pending — a failed run's
+ // retry released from its cleanup hold (#3373) or an orphan sweep requeue.
+ // Newly spawnable, and long after the completion dequeue ran — re-run dequeue.
cosEvents.on('tasks:changed', (data) => {
if (!isDaemonRunning() || !data?.action) return;
if (data.action === 'added') {
@@ -1278,7 +1298,7 @@ export async function init() {
// first; tryImmediateSpawn then handles the just-added task.
setImmediate(() => dequeueNextTask());
if (data.type === 'user' && data.task) setImmediate(() => tryImmediateSpawn(data.task));
- } else if (data.action === 'approved' || data.action === 'unblocked') {
+ } else if (data.action === 'approved' || data.action === 'unblocked' || data.action === 'requeued') {
setImmediate(() => dequeueNextTask());
}
});
diff --git a/server/services/cos.test.js b/server/services/cos.test.js
index ee0e3c8224..f5fe7b9c13 100644
--- a/server/services/cos.test.js
+++ b/server/services/cos.test.js
@@ -1097,6 +1097,40 @@ describe('cos.js source — priority + capacity invariants', () => {
// tryImmediateSpawn is user-task-only, matching the pre-extraction guard.
expect(handler).toMatch(/data\.type\s*===\s*'user'/);
});
+
+ // The retry-hold release (#3373) and the orphan sweep both requeue via an
+ // in_progress → pending flip, which cosTaskStore reports as 'requeued'. Without
+ // a wake here the released retry idles until an unrelated event or timer.
+ it('tasks:changed listener re-runs the dequeue on a requeued task', () => {
+ const onIdx = COS_SRC.indexOf("cosEvents.on('tasks:changed'");
+ const handler = COS_SRC.slice(onIdx, COS_SRC.indexOf('});', onIdx) + 3);
+ expect(handler).toMatch(/data\.action\s*===\s*'requeued'/);
+ });
+});
+
+// A failed run's retry is held non-spawnable (`in_progress` + marker) while its
+// worktree cleanup resolves the resume pointer (#3373). The boot/health-check
+// sweep walks in_progress tasks, so it must leave a LIVE hold alone — requeueing
+// there would resolve the pointer against a branch mid-merge — and must hand a
+// STALE one (the process that armed it died) to handleOrphanedTask, which
+// finishes the transition.
+describe('resetOrphanedTasks — retry holds (#3373)', () => {
+ const sweepFn = extractFnBody(COS_SRC, COS_SRC.indexOf('async function resetOrphanedTasks'));
+
+ it('skips a held task until its hold goes stale', () => {
+ expect(sweepFn, 'the sweep must consult the retry hold')
+ .toMatch(/isRetryHeld\(task\.metadata\)\s*&&\s*!bootRecovery\s*&&\s*!isStaleRetryHold\(task\.metadata\)/);
+ const guardIdx = sweepFn.indexOf('isRetryHeld(task.metadata)');
+ const handlerIdx = sweepFn.indexOf('handleOrphanedTask(');
+ expect(guardIdx, 'the hold guard must run before the orphan handler').toBeLessThan(handlerIdx);
+ });
+
+ // Nothing can be mid-cleanup on the startup pass, so a hold left by the process
+ // that died is recovered immediately rather than idling out its grace window.
+ it('recovers a held task immediately on the boot pass', () => {
+ expect(COS_SRC).toMatch(/resetOrphanedTasks\(\{\s*bootRecovery:\s*true\s*\}\)/);
+ expect(sweepFn).toMatch(/bootRecovery\s*=\s*false/);
+ });
});
describe('forceSpawnTask — pre-validate provider before task:ready', () => {
diff --git a/server/services/cosAgentLifecycle.js b/server/services/cosAgentLifecycle.js
index b01df0d482..de023b95c5 100644
--- a/server/services/cosAgentLifecycle.js
+++ b/server/services/cosAgentLifecycle.js
@@ -317,7 +317,7 @@ export async function getAgents() {
* worktree/provider metadata, the status) don't pay to read and line-split a
* completed agent's entire output.txt — which for a long TUI run is megabytes,
* and whose read failing would otherwise take the whole lookup down with it.
- * `recordResumePointerIfRetrying` is the motivating caller (#3368).
+ * `releaseRetryHold` is the motivating caller (#3368).
*/
export async function getAgentRecord(agentId) {
const state = await loadState();
diff --git a/server/services/cosTaskStore.js b/server/services/cosTaskStore.js
index 26b76aeb49..0cde2e7339 100644
--- a/server/services/cosTaskStore.js
+++ b/server/services/cosTaskStore.js
@@ -518,7 +518,15 @@ export async function updateTask(taskId, updates, taskType = 'user', { now = Dat
// like an approval. Emit a distinct action so cos.init's listener re-runs the
// dequeue (#2614) — the generic 'updated' action doesn't wake the scheduler,
// which left revived tasks stranded until an unrelated event or timer fired.
- const action = previousStatus === 'blocked' && updatedTask.status === 'pending' ? 'unblocked' : 'updated';
+ //
+ // An in_progress → pending flip is a requeue and needs the same wake (#3373):
+ // a failed run's retry is released from its hold by exactly this transition,
+ // and by then the `agent:completed` dequeue has long since run — without a
+ // signal the retry would idle until the next timer. Same for the orphan sweep's
+ // requeue, which previously depended on its caller remembering to evaluate.
+ const action = updatedTask.status === 'pending' && previousStatus === 'blocked'
+ ? 'unblocked'
+ : (updatedTask.status === 'pending' && previousStatus === 'in_progress' ? 'requeued' : 'updated');
cosEvents.emit('tasks:changed', { type: taskType, action, task: updatedTask });
return updatedTask;
});
diff --git a/server/services/cosTaskStore.test.js b/server/services/cosTaskStore.test.js
index 38270af128..68ef16b944 100644
--- a/server/services/cosTaskStore.test.js
+++ b/server/services/cosTaskStore.test.js
@@ -364,6 +364,29 @@ describe('cosTaskStore.addTask', () => {
expect(mock.events.find(e => e.name === 'tasks:changed').payload.action).toBe('updated');
});
+ it('emits tasks:changed action "requeued" on an in_progress → pending flip (#3373)', async () => {
+ // The retry-hold release and the orphan sweep both requeue this way, long
+ // after the completion dequeue ran — without a wake signal the retry would
+ // idle until an unrelated event or timer fired.
+ const task = await addTask({ description: 'requeue me', app: 'portos', id: 'sys-requeue' }, 'internal');
+ await updateTask(task.id, { status: 'in_progress' }, 'internal');
+ mock.events.length = 0;
+ await updateTask(task.id, { status: 'pending', metadata: { retryPendingCleanup: undefined } }, 'internal');
+ expect(mock.events.find(e => e.name === 'tasks:changed').payload.action).toBe('requeued');
+ });
+
+ // The hold clear has to actually leave the disk: a `null` would serialize as
+ // the string "null" and read back as a live marker on the next boot.
+ it('drops undefined metadata keys entirely rather than persisting them (#3373)', async () => {
+ const task = await addTask({ description: 'clear my marker', app: 'portos', id: 'sys-marker' }, 'internal');
+ await updateTask(task.id, { status: 'in_progress', metadata: { retryPendingCleanup: true } }, 'internal');
+ await updateTask(task.id, { status: 'pending', metadata: { retryPendingCleanup: undefined } }, 'internal');
+ const { tasks } = await getCosTasks();
+ const stored = tasks.find(t => t.id === task.id);
+ expect(stored.status).toBe('pending');
+ expect('retryPendingCleanup' in stored.metadata).toBe(false);
+ });
+
it('reviveBlockedTask flips to pending with a FRESH retry budget (#2614)', async () => {
// A revived task must behave like a fresh one: without clearing the
// spawn/orphan budgets it would immediately re-block on the exhausted