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

address review (codex): scope the retry hold to its arming run and refuse to spawn a held task (#3373)

[._.]/ Adam Eivye565104ae49e
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 3acef1565e..832abb5ecb 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -160,7 +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-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. The hold names the run that armed it, so a slow cleanup from an earlier attempt can't release a later attempt's hold or reopen a task that has since been blocked, and the spawn path refuses a held task outright — a dispatch queued before the failure can no longer slip past on the lease this instance still holds. 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 a3e9622c9f..6093bc4914 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -217,7 +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. |
+| `taskRetryHold.js` | The failed-task RETRY HOLD state (#3373) — pure metadata helpers shared by the failure verdict, the post-cleanup release, the spawn guard, and the orphan sweep. `retryHoldMetadata(agentId, now)` arms it (task stays `in_progress`, so no dequeue tier can claim the retry before its resume pointer is resolved); `clearedRetryHoldMetadata()` releases it in the same write that flips the task to `pending`; `isRetryHeld(metadata)` / `isRetryHoldOwner(metadata, agentId)` gate the spawn and the owner-scoped release; `isStaleRetryHold(metadata, now, graceMs)` + `RETRY_HOLD_GRACE_MS` let the orphan sweep finish a transition whose process died. |
| `taxonomyTally.js` | Generic taxonomy tally + top-N-line render engine shared by the two Layered Intelligence leaf taxonomies (`services/layeredIntelligenceRejections.js`, `layeredIntelligenceExecutionFailures.js`). `createTaxonomyTally({predicate, select, field, vocabulary, sentinel, glossFn, gapWording})` is the single composed seam — it binds a taxonomy config into `{summarize, format}`, where `summarize(records)` yields the three-bucket `{entries, unknown, unclassified, diagnosed, total}` tally (commonest-first + taxonomy-order tie-break) and `format(records, limit)` renders one prompt line naming every non-zero gap. Also exports the two leaf utilities the classifiers use directly: `normalizeToken(value)` (lowercase + separator-collapse for label/category matching) and `formatTaxonomyToken(token, labels)` (gloss-map render, nullish→'', unglossed passthrough). Pure leaf — imports nothing from the LI graph. |
| `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/taskRetryHold.js b/server/lib/taskRetryHold.js
index 9f04ed3e63..7a56f699ac 100644
--- a/server/lib/taskRetryHold.js
+++ b/server/lib/taskRetryHold.js
@@ -44,10 +44,16 @@ 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.
+ *
+ * The marker VALUE is the id of the run that armed it, not a bare `true`, so the
+ * release is owner-scoped: a slow cleanup from attempt A that lands after attempt
+ * B has already failed and armed its own hold must not clear B's hold, overwrite
+ * B's pointer, or make the task spawnable while B's cleanup is still running.
+ * A hold with no id (`true`) is a legacy/unattributed shape any releaser may clear.
*/
-export function retryHoldMetadata(now = Date.now()) {
+export function retryHoldMetadata(agentId, now = Date.now()) {
return {
- [RETRY_HOLD_KEY]: true,
+ [RETRY_HOLD_KEY]: agentId || true,
[RETRY_HOLD_SINCE_KEY]: new Date(now).toISOString(),
};
}
@@ -66,12 +72,26 @@ export function clearedRetryHoldMetadata() {
}
/**
- * Is this task held pending its resume-pointer write? Accepts the markdown
- * round-trip (`true` comes back as the string `'true'`), same as `isTruthyMeta`.
+ * Is this task held pending its resume-pointer write? The marker is an agent id,
+ * or `true` for the legacy/unattributed shape — and the markdown round-trip turns
+ * both booleans into strings, so `'false'`/`'null'` must read as NOT held.
*/
export function isRetryHeld(metadata) {
const value = metadata?.[RETRY_HOLD_KEY];
- return value === true || value === 'true';
+ if (value === true || value === 'true') return true;
+ return typeof value === 'string' && value !== '' && value !== 'false' && value !== 'null' && value !== 'undefined';
+}
+
+/**
+ * May `agentId` release this hold? Only the run that armed it — or anyone, when
+ * the marker carries no id (legacy shape). The orphan sweep deliberately does NOT
+ * consult this: whoever armed the hold is gone by the time it looks.
+ */
+export function isRetryHoldOwner(metadata, agentId) {
+ if (!isRetryHeld(metadata)) return false;
+ const value = metadata[RETRY_HOLD_KEY];
+ if (value === true || value === 'true') return true;
+ return !!agentId && value === agentId;
}
/**
diff --git a/server/lib/taskRetryHold.test.js b/server/lib/taskRetryHold.test.js
index c79ba25a8c..2b852da46d 100644
--- a/server/lib/taskRetryHold.test.js
+++ b/server/lib/taskRetryHold.test.js
@@ -4,19 +4,25 @@ import {
retryHoldMetadata,
clearedRetryHoldMetadata,
isRetryHeld,
+ isRetryHoldOwner,
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,
+ // The marker VALUE is the arming run's id, so the release is owner-scoped.
+ it('arms the marker with the owning agent id and an ISO stamp', () => {
+ expect(retryHoldMetadata('agent-x', NOW)).toEqual({
+ retryPendingCleanup: 'agent-x',
retryPendingSince: '2026-08-02T12:00:00.000Z',
});
});
+ it('falls back to an unattributed hold when no agent id is known', () => {
+ expect(retryHoldMetadata(null, NOW).retryPendingCleanup).toBe(true);
+ });
+
// `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.
@@ -25,35 +31,61 @@ describe('retryHoldMetadata / clearedRetryHoldMetadata', () => {
expect(cleared.retryPendingCleanup).toBeUndefined();
expect(cleared.retryPendingSince).toBeUndefined();
expect(Object.keys(cleared)).toEqual(['retryPendingCleanup', 'retryPendingSince']);
- expect(isRetryHeld({ ...retryHoldMetadata(NOW), ...cleared })).toBe(false);
+ expect(isRetryHeld({ ...retryHoldMetadata('agent-x', NOW), ...cleared })).toBe(false);
});
});
describe('isRetryHeld', () => {
- it('reads the boolean and its markdown round-trip string', () => {
+ it('reads an agent id, the legacy boolean, and its markdown round-trip string', () => {
+ expect(isRetryHeld({ retryPendingCleanup: 'agent-x' })).toBe(true);
expect(isRetryHeld({ retryPendingCleanup: true })).toBe(true);
expect(isRetryHeld({ retryPendingCleanup: 'true' })).toBe(true);
});
+ // The markdown round-trip stringifies every value, so the falsy forms have to be
+ // recognized as strings or a cleared marker would read as a live hold.
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({ retryPendingCleanup: 'undefined' })).toBe(false);
+ expect(isRetryHeld({ retryPendingCleanup: '' })).toBe(false);
expect(isRetryHeld({})).toBe(false);
expect(isRetryHeld(null)).toBe(false);
expect(isRetryHeld(undefined)).toBe(false);
});
});
+// Only the run that armed the hold may release it: a slow cleanup from a previous
+// attempt landing after the NEXT attempt failed and armed its own hold would
+// otherwise make the task spawnable while that attempt's cleanup is still running.
+describe('isRetryHoldOwner', () => {
+ it('is true only for the arming agent', () => {
+ expect(isRetryHoldOwner({ retryPendingCleanup: 'agent-x' }, 'agent-x')).toBe(true);
+ expect(isRetryHoldOwner({ retryPendingCleanup: 'agent-x' }, 'agent-y')).toBe(false);
+ expect(isRetryHoldOwner({ retryPendingCleanup: 'agent-x' }, null)).toBe(false);
+ });
+
+ it('lets anyone release an unattributed (legacy) hold', () => {
+ expect(isRetryHoldOwner({ retryPendingCleanup: true }, 'agent-y')).toBe(true);
+ expect(isRetryHoldOwner({ retryPendingCleanup: 'true' }, 'agent-y')).toBe(true);
+ });
+
+ it('is false when there is no hold at all', () => {
+ expect(isRetryHoldOwner({}, 'agent-x')).toBe(false);
+ expect(isRetryHoldOwner(null, 'agent-x')).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);
+ expect(isStaleRetryHold(retryHoldMetadata('agent-x', 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);
+ expect(isStaleRetryHold(retryHoldMetadata('agent-x', NOW), NOW + RETRY_HOLD_GRACE_MS)).toBe(true);
});
// The marker is the evidence; the stamp is only the liveness hint. A hold we
diff --git a/server/services/agentErrorAnalysis.js b/server/services/agentErrorAnalysis.js
index b1e7ec8526..1e1cca59de 100644
--- a/server/services/agentErrorAnalysis.js
+++ b/server/services/agentErrorAnalysis.js
@@ -1051,6 +1051,7 @@ export async function maybeCreateInvestigationTask(agentId, task, analysis) {
*
* `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).
+ * `agentId` is stamped INTO that hold so only the run that armed it can release it.
*
* @returns {{
* status: 'blocked'|'in_progress',
@@ -1058,7 +1059,7 @@ export async function maybeCreateInvestigationTask(agentId, task, analysis) {
* metadataUpdates: { failureCount?: number, lastErrorCategory?: string, [k: string]: unknown }
* }}
*/
-export function resolveFailedTaskDecision(task, errorAnalysis, now = Date.now()) {
+export function resolveFailedTaskDecision(task, errorAnalysis, { agentId = null, 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.
@@ -1116,7 +1117,7 @@ export function resolveFailedTaskDecision(task, errorAnalysis, now = Date.now())
metadataUpdates: {
failureCount,
lastErrorCategory,
- ...retryHoldMetadata(now),
+ ...retryHoldMetadata(agentId, now),
...(compaction && { compaction })
}
};
@@ -1168,7 +1169,7 @@ export function resolveTypeFailureSignal({ success, terminatedByUser = false, ho
* spawnable once `releaseRetryHold` writes the resume pointer (#3373).
*/
export async function resolveFailedTaskUpdate(task, errorAnalysis, agentId, now = Date.now()) {
- const decision = resolveFailedTaskDecision(task, errorAnalysis, now);
+ const decision = resolveFailedTaskDecision(task, errorAnalysis, { agentId, now });
const { failureCount, lastErrorCategory } = decision.metadataUpdates;
// Actionable errors get blocked immediately (investigation task created unless API access is denied)
diff --git a/server/services/agentErrorAnalysis.test.js b/server/services/agentErrorAnalysis.test.js
index 2741781226..d9e10900cb 100644
--- a/server/services/agentErrorAnalysis.test.js
+++ b/server/services/agentErrorAnalysis.test.js
@@ -269,9 +269,9 @@ describe('resolveFailedTaskDecision', () => {
// 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' }, HOLD_NOW);
+ const decision = resolveFailedTaskDecision(task(), { actionable: false, category: 'rate-limit', message: 'Rate limited' }, { agentId: 'agent-x', now: HOLD_NOW });
expect(decision.status).toBe('in_progress');
- expect(decision.metadataUpdates.retryPendingCleanup).toBe(true);
+ expect(decision.metadataUpdates.retryPendingCleanup).toBe('agent-x');
expect(decision.metadataUpdates.retryPendingSince).toBe(new Date(HOLD_NOW).toISOString());
expect(decision.metadataUpdates.failureCount).toBe(1);
expect(decision.metadataUpdates.lastErrorCategory).toBe('rate-limit');
@@ -330,7 +330,7 @@ describe('resolveFailedTaskDecision', () => {
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));
+ const held = applyDecision(base, resolveFailedTaskDecision(base, { actionable: false, category: 'rate-limit', message: 'Rate limited' }, { agentId: 'agent-x', now: HOLD_NOW }));
expect(groupTasksByStatus([held]).pending).toEqual([]);
expect(groupTasksByStatus([held]).in_progress).toEqual([held]);
@@ -340,7 +340,7 @@ describe('resolveFailedTaskDecision', () => {
// ...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);
+ const decision = resolveFailedTaskDecision({ id: 'task-1', metadata: { failureCount: MAX_TASK_RETRIES - 1 } }, { actionable: false, category: 'network-error', message: 'Network failed' }, { agentId: 'agent-x', now: HOLD_NOW });
expect(decision.status).toBe('blocked');
expect(decision.metadataUpdates.retryPendingCleanup).toBeUndefined();
expect(decision.metadataUpdates.retryPendingSince).toBeUndefined();
diff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.js
index daec0f8fd3..f443679ffe 100644
--- a/server/services/agentLifecycle.js
+++ b/server/services/agentLifecycle.js
@@ -31,6 +31,7 @@ import { getConfig, updateTask, getTaskById, getAgent as getAgentRecord } from '
import { spawnAgentViaRunner, getRunnerHealth } from './cosRunnerClient.js';
import { MAX_TOTAL_SPAWNS, normalizeReviewers } from '../lib/validation.js';
import { isInternalTaskId } from '../lib/taskParser.js';
+import { isRetryHeld } from '../lib/taskRetryHold.js';
import { ensureDir, PATHS, sleep, tryReadFile } from '../lib/fileUtils.js';
import { createToolExecution, startExecution, completeExecution, errorExecution } from './toolStateMachine.js';
import { determineLane, acquire, release } from './executionLanes.js';
@@ -229,6 +230,19 @@ async function runAgentSpawn(task) {
// within one install the `spawningTasks` guard already prevents duplicates.)
const freshTask = await getTaskById(task.id).catch(() => null);
if (freshTask) {
+ // A retry held for its resume pointer (#3373) is not spawnable, however this
+ // dispatch reached us. The dequeue tiers can't see it (they select `pending`),
+ // but a `task:ready` emitted before the hold was armed — or a stale generator
+ // snapshot — arrives with a task object from before the failure, and the claim
+ // check below passes because the hold keeps OUR OWN lease. Spawning here is
+ // exactly the race the hold exists to close: the retry would start clean while
+ // the pointer naming its predecessor's branch is still being resolved. The
+ // release re-emits `tasks:changed`, which re-runs the dequeue.
+ if (isRetryHeld(freshTask.metadata)) {
+ console.log(`⏳ Task ${task.id} is held for its retry pointer — not spawning until cleanup releases it`);
+ await cleanupOnError('retry held pending cleanup');
+ return null;
+ }
// The task is persisted — honor a peer's claim that synced in since dispatch,
// then take the lease up front.
if (!isClaimableBy(freshTask.metadata, instanceId)) {
diff --git a/server/services/agentLifecycle.test.js b/server/services/agentLifecycle.test.js
index b40fac0f45..04584f080b 100644
--- a/server/services/agentLifecycle.test.js
+++ b/server/services/agentLifecycle.test.js
@@ -458,6 +458,19 @@ describe('runAgentSpawn source — instance provenance + claim ordering (#1563)'
expect(recheckIdx, 'must re-check claimability against the fresh metadata').toBeGreaterThan(rereadIdx);
});
+ // The hold keeps this instance's OWN lease (updateTask only releases it when a
+ // status other than in_progress is written), so the claim re-check above passes
+ // for a held task. A `task:ready` emitted before the failure — or a stale
+ // generator snapshot — would otherwise spawn the retry while the pointer naming
+ // its predecessor's branch is still being resolved (#3373).
+ it('refuses to spawn a task whose retry is held for its resume pointer', () => {
+ const rereadIdx = RUN_SPAWN_BODY.indexOf('await getTaskById(task.id)');
+ const holdIdx = RUN_SPAWN_BODY.indexOf('isRetryHeld(freshTask.metadata)');
+ const registerIdx = RUN_SPAWN_BODY.indexOf('registerAgent(agentId, task.id, {');
+ expect(holdIdx, 'must check the retry hold on the fresh metadata').toBeGreaterThan(rereadIdx);
+ expect(holdIdx, 'the hold guard must run BEFORE registering the agent').toBeLessThan(registerIdx);
+ });
+
it('releases the claim on a failed-setup early exit (cleanupOnError)', () => {
const fnStart = AGENT_LIFECYCLE_SRC.indexOf('const cleanupOnError = async');
const fnBody = AGENT_LIFECYCLE_SRC.slice(fnStart, fnStart + 1200);
diff --git a/server/services/agentManagement.test.js b/server/services/agentManagement.test.js
index 0c0ecf7907..79035e77fd 100644
--- a/server/services/agentManagement.test.js
+++ b/server/services/agentManagement.test.js
@@ -914,7 +914,7 @@ describe('the orphan sweep finishes an interrupted retry transition (#3373)', ()
id: 'task-1',
taskType: 'user',
status: 'in_progress',
- metadata: { retryPendingCleanup: true, retryPendingSince: new Date().toISOString(), failureCount: 1 },
+ metadata: { retryPendingCleanup: 'agent-dead', retryPendingSince: new Date().toISOString(), failureCount: 1 },
});
beforeEach(() => {
@@ -976,10 +976,20 @@ describe('the orphan sweep finishes an interrupted retry transition (#3373)', ()
expect(updateTask).toHaveBeenCalledWith('task-1', expect.objectContaining({ status: 'pending' }), 'user');
});
+ // The sweep is NOT owner-scoped by design — whoever armed the hold is gone by
+ // the time it looks, so a hold from any agent is recoverable.
+ it('finishes a transition armed by an agent it was not told about', async () => {
+ getTaskById.mockResolvedValue({ ...heldTask(), metadata: { retryPendingCleanup: 'agent-someone-else' } });
+
+ await handleOrphanedTask('task-1', 'unknown-reset', getTaskById, { agentMetadata: null });
+
+ 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 } });
+ getTaskById.mockResolvedValue({ id: 'task-1', taskType: 'user', status: 'blocked', metadata: { blockedCategory: 'user-terminated', retryPendingCleanup: 'agent-dead' } });
await handleOrphanedTask('task-1', 'agent-dead', getTaskById, { agentMetadata: null });
diff --git a/server/services/agentWorktreeCleanup.js b/server/services/agentWorktreeCleanup.js
index 5468cd4869..9d783d1976 100644
--- a/server/services/agentWorktreeCleanup.js
+++ b/server/services/agentWorktreeCleanup.js
@@ -22,7 +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 { isRetryHoldOwner, 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';
@@ -553,8 +553,9 @@ export async function recordTaskResumePointer({ task, agentId, agentMetadata })
* 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.
+ * `in_progress` under someone else's hold or none at all (the retry already
+ * spawned), a failed read, a task deleted mid-run — is not evidence of a retry we
+ * own, 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 —
@@ -576,7 +577,13 @@ export async function releaseRetryHold({ agentId, task, success, agentMetadata }
});
if (!persisted) return {};
- const held = isRetryHeld(persisted.metadata);
+ // Release only OUR hold, and only while the task is still held `in_progress`.
+ // Both halves matter: a slow cleanup from a previous attempt must not clear the
+ // hold the CURRENT attempt just armed (it would make the task spawnable while
+ // that attempt's cleanup is still running — the very race this exists to close),
+ // and a task that reached `blocked`/`completed` carrying a stale marker must
+ // never be flipped back to `pending` by a late cleanup.
+ const held = isRetryHoldOwner(persisted.metadata, agentId) && persisted.status === 'in_progress';
// A record with no `status` at all is a legacy shape that predates the field;
// those are pending.
if (!held && (persisted.status ?? 'pending') !== 'pending') return {};
diff --git a/server/services/cleanupAgentWorktree.test.js b/server/services/cleanupAgentWorktree.test.js
index d0205f8f6d..3443276da1 100644
--- a/server/services/cleanupAgentWorktree.test.js
+++ b/server/services/cleanupAgentWorktree.test.js
@@ -1324,7 +1324,7 @@ describe('releaseRetryHold', () => {
// 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() } };
+ const heldTask = { id: 'task-1', status: 'in_progress', metadata: { retryPendingCleanup: 'agent-x', retryPendingSince: new Date().toISOString() } };
it('flips to pending WITH the pointer and the cleared marker in one updateTask', async () => {
getTaskById.mockResolvedValue(heldTask);
@@ -1358,8 +1358,9 @@ describe('releaseRetryHold', () => {
}, 'user');
});
- // The markdown round-trip stores metadata booleans as strings.
- it('recognizes the hold marker after a markdown round-trip', async () => {
+ // A hold armed before the marker carried an id (legacy shape) is releasable by
+ // whoever finds it, and the markdown round-trip stores booleans as strings.
+ it('recognizes an unattributed hold after a markdown round-trip', async () => {
getTaskById.mockResolvedValue({ ...heldTask, metadata: { retryPendingCleanup: 'true' } });
await releaseRetryHold({ agentId: 'agent-x', task: task(), success: false, agentMetadata });
@@ -1367,6 +1368,17 @@ describe('releaseRetryHold', () => {
expect(updateTask).toHaveBeenCalledWith('task-1', expect.objectContaining({ status: 'pending' }), 'user');
});
+ // The whole point of stamping the owner: attempt A's slow cleanup lands after
+ // attempt B failed and armed ITS hold. Releasing here would make the task
+ // spawnable while B's cleanup is still resolving B's pointer.
+ it('does not release a hold armed by a later attempt', async () => {
+ getTaskById.mockResolvedValue({ ...heldTask, metadata: { retryPendingCleanup: 'agent-later' } });
+
+ await releaseRetryHold({ agentId: 'agent-x', task: task(), success: false, agentMetadata });
+
+ expect(updateTask).not.toHaveBeenCalled();
+ });
+
// 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 () => {
@@ -1377,10 +1389,13 @@ describe('releaseRetryHold', () => {
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: {} });
+ // A late release must never REOPEN a task that has since gone terminal —
+ // user-terminated, budget-exhausted, or completed by a recovery path.
+ it('never flips a blocked or completed task, even one carrying a stale marker', async () => {
+ getTaskById.mockResolvedValue({ id: 'task-1', status: 'blocked', metadata: { retryPendingCleanup: 'agent-x' } });
+ await releaseRetryHold({ agentId: 'agent-x', task: task(), success: false, agentMetadata });
+ getTaskById.mockResolvedValue({ id: 'task-1', status: 'completed', metadata: { retryPendingCleanup: 'agent-x' } });
await releaseRetryHold({ agentId: 'agent-x', task: task(), success: false, agentMetadata });
expect(updateTask).not.toHaveBeenCalled();
diff --git a/server/services/cos.js b/server/services/cos.js
index 95c20c56b2..ae239861e0 100644
--- a/server/services/cos.js
+++ b/server/services/cos.js
@@ -597,23 +597,30 @@ async function resetOrphanedTasks({ bootRecovery = false } = {}) {
}
continue;
}
- // Skip tasks whose agent just completed — updateTask will set them to
- // completed shortly; treating them as orphaned causes spurious retries
- if (recentlyCompletedTaskIds.has(task.id)) {
- 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)) {
+ // resolve the pointer against a branch mid-merge. Once the hold is stale, or
+ // this is the boot pass (nothing can be mid-cleanup in a process that just
+ // started), the process that armed it is gone and `handleOrphanedTask`
+ // finishes the transition instead of treating the task as a fresh orphan.
+ //
+ // Evaluated BEFORE the recently-completed grace below, which it deliberately
+ // bypasses: the hold is armed AFTER `completeAgent`, so a crash-restart
+ // inside that 60s window would otherwise skip the very task the boot pass
+ // exists to recover and strand it until the 15-minute periodic sweep.
+ const held = isRetryHeld(task.metadata);
+ const recoverHold = held && (bootRecovery || isStaleRetryHold(task.metadata));
+ if (held && !recoverHold) {
emitLog('debug', `Skipping task ${task.id} — retry held while its worktree cleanup finishes`, { taskId: task.id });
continue;
}
+ // Skip tasks whose agent just completed — updateTask will set them to
+ // completed shortly; treating them as orphaned causes spurious retries
+ if (!recoverHold && recentlyCompletedTaskIds.has(task.id)) {
+ emitLog('debug', `Skipping task ${task.id} — agent recently completed, awaiting task status update`, { 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);
diff --git a/server/services/cos.test.js b/server/services/cos.test.js
index f5fe7b9c13..cb342e7808 100644
--- a/server/services/cos.test.js
+++ b/server/services/cos.test.js
@@ -1119,9 +1119,11 @@ describe('resetOrphanedTasks — retry holds (#3373)', () => {
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)');
+ .toMatch(/const recoverHold = held && \(bootRecovery \|\| isStaleRetryHold\(task\.metadata\)\)/);
+ expect(sweepFn, 'a live hold must skip the task').toMatch(/if \(held && !recoverHold\)/);
+ const guardIdx = sweepFn.indexOf('const held = isRetryHeld(task.metadata)');
const handlerIdx = sweepFn.indexOf('handleOrphanedTask(');
+ expect(guardIdx, 'the hold guard must run before the orphan handler').toBeGreaterThan(-1);
expect(guardIdx, 'the hold guard must run before the orphan handler').toBeLessThan(handlerIdx);
});
@@ -1131,6 +1133,16 @@ describe('resetOrphanedTasks — retry holds (#3373)', () => {
expect(COS_SRC).toMatch(/resetOrphanedTasks\(\{\s*bootRecovery:\s*true\s*\}\)/);
expect(sweepFn).toMatch(/bootRecovery\s*=\s*false/);
});
+
+ // The hold is armed AFTER completeAgent, so a crash-restart inside the 60s
+ // recently-completed grace would otherwise skip exactly the task the boot pass
+ // exists to recover, stranding it until the 15-minute periodic sweep.
+ it('lets a recoverable hold bypass the recently-completed grace', () => {
+ const holdIdx = sweepFn.indexOf('const recoverHold =');
+ const graceIdx = sweepFn.indexOf('recentlyCompletedTaskIds.has(task.id)');
+ expect(holdIdx, 'the hold must be evaluated before the recently-completed grace').toBeLessThan(graceIdx);
+ expect(sweepFn).toMatch(/if \(!recoverHold && recentlyCompletedTaskIds\.has\(task\.id\)\)/);
+ });
});
describe('forceSpawnTask — pre-validate provider before task:ready', () => {
diff --git a/server/services/cosTaskStore.js b/server/services/cosTaskStore.js
index 0cde2e7339..7d25acc3c3 100644
--- a/server/services/cosTaskStore.js
+++ b/server/services/cosTaskStore.js
@@ -18,6 +18,7 @@ import { join } from 'path';
import { parseTasksMarkdown, groupTasksByStatus, getAutoApprovedTasks, getAwaitingApprovalTasks, generateTasksMarkdown, hasKnownPrefix } from '../lib/taskParser.js';
import { REVIEW_STOP_MODES, normalizeReviewers, normalizeReviewUsernames, normalizeOptionalReviewers, normalizeReviewerMaxRounds, normalizeReviewerModels } from '../lib/validation.js';
import { PR_COMPLETIONS, PR_COMPLETION_VALUES } from '../lib/prDisposition.js';
+import { RETRY_HOLD_KEY, RETRY_HOLD_SINCE_KEY } from '../lib/taskRetryHold.js';
import { loadState, withStateLock, ROOT_DIR } from './cosState.js';
import { cosEvents } from './cosEvents.js';
import { CLAIM_METADATA_KEYS } from './cosTaskClaim.js';
@@ -467,6 +468,17 @@ export async function updateTask(taskId, updates, taskType = 'user', { now = Dat
delete updatedMetadata.resumeWorktreePath;
}
+ // A retry hold (#3373) only means anything while the task is `in_progress`
+ // waiting on a cleanup to resolve its resume pointer. Any other status the task
+ // reaches — terminal, or a requeue that some other path performed — retires it,
+ // so drop the marker rather than leave a stale one for a late cleanup (or the
+ // orphan sweep) to act on. The release's own write passes these as undefined,
+ // which lands in the same place.
+ if (updates.status && updates.status !== 'in_progress') {
+ delete updatedMetadata[RETRY_HOLD_KEY];
+ delete updatedMetadata[RETRY_HOLD_SINCE_KEY];
+ }
+
// Release the federation claim/lease when a task leaves `in_progress` (issue
// #1563). A claim only protects in-flight work; once the task completes, fails
// back to pending, or is blocked, it must become freely claimable by either
diff --git a/server/services/cosTaskStore.test.js b/server/services/cosTaskStore.test.js
index 68ef16b944..9603475b97 100644
--- a/server/services/cosTaskStore.test.js
+++ b/server/services/cosTaskStore.test.js
@@ -387,6 +387,17 @@ describe('cosTaskStore.addTask', () => {
expect('retryPendingCleanup' in stored.metadata).toBe(false);
});
+ // A hold only means anything on an in_progress task waiting for its cleanup. Any
+ // other status retires it, so a late cleanup (or the orphan sweep) can never act
+ // on a marker left behind on a task that has since gone blocked or completed.
+ it('strips a retry hold when the task leaves in_progress (#3373)', async () => {
+ const task = await addTask({ description: 'hold retired', app: 'portos', id: 'sys-hold' }, 'internal');
+ await updateTask(task.id, { status: 'in_progress', metadata: { retryPendingCleanup: 'agent-x', retryPendingSince: new Date().toISOString() } }, 'internal');
+ const blocked = await updateTask(task.id, { status: 'blocked', metadata: { blockedCategory: 'user-terminated' } }, 'internal');
+ expect(blocked.metadata.retryPendingCleanup).toBeUndefined();
+ expect(blocked.metadata.retryPendingSince).toBeUndefined();
+ });
+
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