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

release a paused task's pause hold when anything un-blocks it, so resume stops spawning a second agent

[._.]/ Adam Eivye0ebc0bf49a6
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 0c24fe8984..e64d9ca9b0 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -10,6 +10,8 @@
## Stability
+- **Resuming a paused CoS agent stopped spawning a second agent when something else had already restarted its task.** Resuming was taught to requeue the paused agent's *own* task in place, but it could only recognize that task while it still carried the pause — and plenty of things take a paused task back without knowing an agent is waiting on it: a duplicate dispatch reviving it, the autopilot re-sending the same work, an orphan cooldown lapsing, or you unblocking it from the task list. None of them cleared the pause, so the task ran again while still advertising itself as paused, the paused agent sat in the list with nothing left to resume, and clicking Resume on it read its own pause as spent and queued a *fresh* duplicate task on a second agent — against a clean worktree, redoing work that was already in flight. The pause is now released by the task itself the moment it leaves the blocked state, whichever path un-blocked it; a paused record whose task has moved on is retired automatically instead of lingering; and Resume now reports what it actually did — it requeues a task that is still blocked (including one that fell into a later failure block, resetting its retry budget the way an explicit dispatch should), creates *nothing* when the task is already queued or running, and leaves a later agent's pause alone rather than duplicating around it. When it does fall back to a fresh task — the task was deleted or already completed — that task now inherits the original's app, provider, model, effort, and context, so the replacement runs against the right repo with the right settings instead of a bare description.
+
- **A story about money no longer gets your AI provider benched for a billing problem it doesn't have.** When a command-line AI run exceeded its time limit, PortOS killed it and then guessed at the cause by reading everything the run had printed. Codex echoes your entire prompt back as it works, so a single ordinary phrase inside a story — one character sending work on "without demanding credit" — was enough to match the billing/credit wording and file a plain five-minute timeout as *quota exceeded*: a perfectly healthy provider sidelined, a fallback sent to redo the work, and an investigation task queued about an account problem that never existed. A run stopped by its own time limit is now reported as a timeout on that basis alone, with no guessing from the text, and says so on the run record — the same rule the TUI runner already followed. Runs that fail for other reasons are still read for the provider's own error banner, which is usually the only clue there is.
- **[issue-3703] A worktree agent is no longer failed for commits it didn't write.** The primary-checkout guard used to fail any worktree agent whose run window overlapped commits landing on the shared primary checkout — but a concurrent coding-on-main agent, your own terminal, or `update.sh`'s pull can move it too, so read-only reasoners and correctly-behaved agents were being blamed and escalated to you. The guard now attributes the stranded commits by patch-id (`git cherry`, so a cherry-picked or rebased copy still counts) to the agent's own branch: only commits actually traceable to that agent fail the run. Everything else is warn-logged — the unreviewed commits on the primary are still surfaced — but a run that didn't cause them stays a success.
diff --git a/client/src/components/cos/tabs/AgentsTab.jsx b/client/src/components/cos/tabs/AgentsTab.jsx
index eb0cd06a33..c0666b9da9 100644
--- a/client/src/components/cos/tabs/AgentsTab.jsx
+++ b/client/src/components/cos/tabs/AgentsTab.jsx
@@ -8,6 +8,17 @@ import ResumeAgentModal from './ResumeAgentModal';
import BrailleSpinner from '../../BrailleSpinner';
import InlineConfirmRow from '../../ui/InlineConfirmRow';
+// What each `resumeAgent` outcome actually did (server modes, agentManagement.js).
+// `already-active` and `superseded` deliberately queue NOTHING — the task is already
+// in flight, or a later pause owns it — so an unmapped mode must NOT fall through to
+// "created a resume task". The server's `created` flag decides that (see below); this
+// map only supplies the specific wording.
+const RESUME_MESSAGES = {
+ requeued: 'Resumed — the paused task is queued on its preserved worktree',
+ 'already-active': 'Its task is already queued or running — nothing new was created',
+ superseded: 'A later agent now holds this task paused — that pause was left intact',
+};
+
const needsAgentFeedback = (agent) => {
const isSystemAgent = agent.taskId?.startsWith('sys-') || agent.id?.startsWith('sys-');
return !isSystemAgent && !agent.feedback?.rating;
@@ -140,9 +151,11 @@ export default function AgentsTab({ agents, onRefresh, liveOutputs, providers, a
// Errors propagate to the modal, which owns the failure toast and re-enables
// its submit button — swallowing them here closed the dialog on failure and
// left the user believing the resume was queued.
- toast.success(result.mode === 'requeued'
- ? 'Resumed — the paused task is queued on its preserved worktree'
- : `Created ${type === 'internal' ? 'system ' : ''}resume task`);
+ // A resume that created nothing (`created: false`) never claims it did, even for
+ // a mode this build has no wording for — the completed-agent branch above has no
+ // `created` field at all and did queue a task, so it keeps the default.
+ toast.success(RESUME_MESSAGES[result.mode]
+ || (result.created === false ? 'Resumed — nothing new was queued' : `Created ${type === 'internal' ? 'system ' : ''}resume task`));
setResumingAgent(null);
onRefresh();
};
diff --git a/client/src/components/cos/tabs/AgentsTab.test.jsx b/client/src/components/cos/tabs/AgentsTab.test.jsx
index 8f1d03ecf2..40ace9a129 100644
--- a/client/src/components/cos/tabs/AgentsTab.test.jsx
+++ b/client/src/components/cos/tabs/AgentsTab.test.jsx
@@ -62,6 +62,7 @@ vi.mock('./ResumeAgentModal', () => ({
vi.mock('../../ui/InlineConfirmRow', () => ({ default: () => null }));
import * as api from '../../../services/api';
+import toast from '../../ui/Toast';
import AgentsTab from './AgentsTab';
const completedAgent = (id, description, extra = {}) => ({
@@ -119,6 +120,41 @@ describe('AgentsTab resume routing', () => {
expect(api.addCosTask).not.toHaveBeenCalled();
});
+ // `already-active` and `superseded` create NOTHING server-side — the task is
+ // already in flight, or a later pause owns it. Reporting "created a resume task"
+ // there is the message that had users hunting for an agent that never spawned.
+ it.each([
+ ['already-active', /already queued or running/i],
+ ['superseded', /later agent/i],
+ ])('reports the %s outcome without claiming a task was created', async (mode, pattern) => {
+ const user = userEvent.setup();
+ api.resumeCosAgent.mockResolvedValue({ success: true, taskId: 'task-abc', mode });
+ renderTab([pausedAgent]);
+ await act(async () => {});
+
+ await user.click(screen.getByRole('button', { name: 'Resume agent-paused' }));
+ await user.click(screen.getByRole('button', { name: 'Submit resume' }));
+
+ await waitFor(() => expect(toast.success).toHaveBeenCalledWith(expect.stringMatching(pattern)));
+ expect(toast.success).not.toHaveBeenCalledWith(expect.stringMatching(/resume task/i));
+ });
+
+ // The default has to be safe by construction, not by keeping a copy of the server's
+ // mode enum in sync — a future non-creating mode this build has no wording for must
+ // not regress to announcing a task that was never queued.
+ it('never claims a task was created for an unrecognized non-creating mode', async () => {
+ const user = userEvent.setup();
+ api.resumeCosAgent.mockResolvedValue({ success: true, taskId: 'task-abc', mode: 'some-future-mode', created: false });
+ renderTab([pausedAgent]);
+ await act(async () => {});
+
+ await user.click(screen.getByRole('button', { name: 'Resume agent-paused' }));
+ await user.click(screen.getByRole('button', { name: 'Submit resume' }));
+
+ await waitFor(() => expect(toast.success).toHaveBeenCalled());
+ expect(toast.success).not.toHaveBeenCalledWith(expect.stringMatching(/created/i));
+ });
+
it('still queues a fresh task for a COMPLETED agent, which has no task to requeue', async () => {
const user = userEvent.setup();
api.addCosTask.mockResolvedValue({ id: 'task-new' });
diff --git a/server/lib/README.md b/server/lib/README.md
index a00f0a7ce8..b025985106 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -238,6 +238,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. `findBalancedBlocks` walks top-level blocks and stops at the first unbalanced one; `findAllBalancedBlocks` is the stack-based variant that scans past stray braces and returns nested blocks in closing order (reverse it for outermost-newest-first). |
| `taskParser.js` | Parse `TASKS.md` format. |
+| `taskPauseHold.js` | The user-PAUSE hold — pure metadata helpers shared by the writer (`pauseAgent`), the reader (`resumeAgent`), and the clearer (`updateTask`). `AGENT_PAUSED_CATEGORY` is the `blockedCategory` a pause stamps; `PAUSE_METADATA_KEYS` names every key it writes; `pauseMetadata({agentId, pausedAt, workspacePath, runId})` arms it and `clearedPauseMetadata()` releases it (undefined-valued, so `updateTask` deletes rather than serializing `"null"`); `isAgentPausedTask(task)` / `isResumablePausedTask(task, agentId)` answer whether a pause is still live and whether it is THIS agent's. `updateTask` clears the whole set whenever the task leaves `blocked`, so a revive by any path (dedupe, cooldown expiry, manual unblock) can't leave a task running under a stale pause. |
| `taskRequeue.js` | The REQUEUE stamp (#3376) — pure metadata helpers for the one BACKWARD lifecycle step (`in_progress → pending`, performed by the orphan sweep and the retry-hold release). `REQUEUED_AT_KEY` / `LAST_SPAWNED_AT_KEY` name the two stamps; `isPostSpawnRequeue(pendingTask, inProgressTask)` answers whether the requeue happened strictly AFTER that spawn, which is how the federated merge tells a real requeue apart from an ordinary edit landing on a peer's stale `pending` copy. Returns false when either stamp is missing, so callers fall back to the lifecycle rank. |
| `taskRetryHold.js` | The failed-task RETRY HOLD state (#3373) — pure metadata helpers shared by the failure verdict, the post-cleanup release, the spawn guard, and the orphan sweep. `retryHoldMetadata(agentId, now)` arms it (task stays `in_progress`, so no dequeue tier can claim the retry before its resume pointer is resolved); `clearedRetryHoldMetadata()` releases it in the same write that flips the task to `pending`; `isRetryHeld(metadata)` / `isRetryHoldOwner(metadata, agentId)` gate the spawn and the owner-scoped release; `isStaleRetryHold(metadata, now, graceMs)` + `RETRY_HOLD_GRACE_MS` let the orphan sweep finish a transition whose process died. |
| `taxonomyTally.js` | Generic taxonomy tally + top-N-line render engine shared by the two Layered Intelligence leaf taxonomies (`services/layeredIntelligenceRejections.js`, `layeredIntelligenceExecutionFailures.js`). `createTaxonomyTally({predicate, select, field, vocabulary, sentinel, glossFn, gapWording})` is the single composed seam — it binds a taxonomy config into `{summarize, format}`, where `summarize(records)` yields the three-bucket `{entries, unknown, unclassified, diagnosed, total}` tally (commonest-first + taxonomy-order tie-break) and `format(records, limit)` renders one prompt line naming every non-zero gap. Also exports the two leaf utilities the classifiers use directly: `normalizeToken(value)` (lowercase + separator-collapse for label/category matching) and `formatTaxonomyToken(token, labels)` (gloss-map render, nullish→'', unglossed passthrough). Pure leaf — imports nothing from the LI graph. |
diff --git a/server/lib/index.js b/server/lib/index.js
index 614d05f761..e96b13b2d1 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -222,6 +222,7 @@ export * from './vectorMath.js';
export * from './htmlToText.js';
export * from './jsonExtract.js';
export * from './taskParser.js';
+export * from './taskPauseHold.js';
export * from './taskRequeue.js';
export * from './taskRetryHold.js';
export * from './taxonomyTally.js';
diff --git a/server/lib/taskPauseHold.js b/server/lib/taskPauseHold.js
new file mode 100644
index 0000000000..5c3d781bb8
--- /dev/null
+++ b/server/lib/taskPauseHold.js
@@ -0,0 +1,79 @@
+/**
+ * User-pause hold — the bookkeeping a `pauseAgent` stamps onto the paused agent's
+ * task, and the single definition of when that pause is still live.
+ *
+ * A pause parks a task in `blocked` under the `agent-paused` category plus a small
+ * set of pointer keys naming the run that parked it. Three parties read that state
+ * and they must not drift into three different literals:
+ *
+ * - the WRITER (`pauseAgent` → `markPausedTask`, agentManagement.js),
+ * - the READER (`resumeAgent`, which requeues only the task ITS pause parked),
+ * - and the CLEARER — `updateTask` (cosTaskStore.js), which drops the whole set
+ * the moment the task leaves `blocked` by ANY path.
+ *
+ * That last one is why this is a hold and not a pair of ad-hoc literals. `resumeAgent`
+ * is not the only way a paused task runs again: a dedupe revive, an autopilot
+ * re-dispatch, an orphan-cooldown expiry, or a human unblocking it from the task list
+ * all flip it back to `pending`. Before the clear moved into `updateTask`, every one
+ * of those left `pausedAt`/`pausedAgentId` behind on a task that was running again —
+ * so the UI kept showing a live pause, and the paused agent record sat next to it with
+ * nothing left to resume.
+ *
+ * Pure and dependency-free so the writer, the reader, and the clearer share ONE
+ * definition. Mirrors `taskRetryHold.js`, the same shape for the retry hold.
+ */
+
+/**
+ * The `blockedCategory` a user pause stamps. Proves a blocked task is parked by a
+ * pause rather than finished with — the failure reaper exempts it, and `resumeAgent`
+ * requires it before requeueing in place.
+ */
+export const AGENT_PAUSED_CATEGORY = 'agent-paused';
+
+/**
+ * Every metadata key the pause writes. Listed once so the arm and the clear can't
+ * drift — a key added to `pauseMetadata` that the clear doesn't know about outlives
+ * the pause it belongs to.
+ */
+export const PAUSE_METADATA_KEYS = ['pausedAt', 'pausedAgentId', 'resumeWorkspacePath', 'resumeRunId'];
+
+/**
+ * The metadata patch that ARMS the hold, merged into the pause's own `updateTask`
+ * alongside the blocked status. `resumeWorkspacePath`/`resumeRunId` are omitted when
+ * the run had neither, rather than written as null — an absent key is absence, and a
+ * null would serialize into TASKS.md as the literal string `"null"`.
+ */
+export function pauseMetadata({ agentId, pausedAt, workspacePath, runId }) {
+ return {
+ pausedAt,
+ pausedAgentId: agentId,
+ ...(workspacePath ? { resumeWorkspacePath: workspacePath } : {}),
+ ...(runId ? { resumeRunId: runId } : {}),
+ };
+}
+
+/**
+ * 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 TASKS.md serializes it as the literal string `"null"` —
+ * which reads back as a live pause.
+ */
+export function clearedPauseMetadata() {
+ return Object.fromEntries(PAUSE_METADATA_KEYS.map(key => [key, undefined]));
+}
+
+/** Is this task parked by a user pause right now? */
+export function isAgentPausedTask(task) {
+ return task?.status === 'blocked' && task?.metadata?.blockedCategory === AGENT_PAUSED_CATEGORY;
+}
+
+/**
+ * Is this task the one `agentId`'s pause parked, still waiting to be resumed?
+ *
+ * Anything else — the user re-ran it, it was revived and completed, a DIFFERENT
+ * agent has since paused it — means this pause is spent, and requeueing the task on
+ * its behalf would stomp whatever happened after.
+ */
+export function isResumablePausedTask(task, agentId) {
+ return isAgentPausedTask(task) && !!agentId && task.metadata?.pausedAgentId === agentId;
+}
diff --git a/server/lib/taskPauseHold.test.js b/server/lib/taskPauseHold.test.js
new file mode 100644
index 0000000000..9ba61a749c
--- /dev/null
+++ b/server/lib/taskPauseHold.test.js
@@ -0,0 +1,76 @@
+import { describe, it, expect } from 'vitest';
+import {
+ AGENT_PAUSED_CATEGORY,
+ PAUSE_METADATA_KEYS,
+ pauseMetadata,
+ clearedPauseMetadata,
+ isAgentPausedTask,
+ isResumablePausedTask,
+} from './taskPauseHold.js';
+
+const pausedTask = (metadata = {}) => ({
+ id: 'task-1',
+ status: 'blocked',
+ metadata: { blockedCategory: AGENT_PAUSED_CATEGORY, pausedAgentId: 'agent-1', ...metadata },
+});
+
+describe('pauseMetadata', () => {
+ it('writes every key the clear knows about, so the two can never drift', () => {
+ const armed = pauseMetadata({
+ agentId: 'agent-1',
+ pausedAt: '2026-08-10T00:00:00.000Z',
+ workspacePath: '/w/agent-1',
+ runId: 'run-1',
+ });
+ expect(Object.keys(armed).sort()).toEqual([...PAUSE_METADATA_KEYS].sort());
+ expect(armed.pausedAgentId).toBe('agent-1');
+ });
+
+ // A null would survive updateTask's merge and serialize into TASKS.md as the
+ // literal string "null", which reads back as a resume pointer to nowhere.
+ it('omits the pointer keys a run without a worktree has nothing to put in', () => {
+ const armed = pauseMetadata({ agentId: 'agent-1', pausedAt: '2026-08-10T00:00:00.000Z' });
+ expect(armed).not.toHaveProperty('resumeWorkspacePath');
+ expect(armed).not.toHaveProperty('resumeRunId');
+ });
+});
+
+describe('clearedPauseMetadata', () => {
+ it('releases every key as undefined — updateTask DELETES those, but keeps a null', () => {
+ const cleared = clearedPauseMetadata();
+ expect(Object.keys(cleared).sort()).toEqual([...PAUSE_METADATA_KEYS].sort());
+ for (const key of PAUSE_METADATA_KEYS) {
+ expect(cleared).toHaveProperty(key);
+ expect(cleared[key]).toBeUndefined();
+ }
+ });
+});
+
+describe('isAgentPausedTask / isResumablePausedTask', () => {
+ it('recognizes a live pause and its owner', () => {
+ expect(isAgentPausedTask(pausedTask())).toBe(true);
+ expect(isResumablePausedTask(pausedTask(), 'agent-1')).toBe(true);
+ });
+
+ it('rejects a pause a LATER agent now owns — requeueing would stomp that pause', () => {
+ expect(isAgentPausedTask(pausedTask({ pausedAgentId: 'agent-2' }))).toBe(true);
+ expect(isResumablePausedTask(pausedTask({ pausedAgentId: 'agent-2' }), 'agent-1')).toBe(false);
+ });
+
+ it('rejects a task that is no longer blocked, whatever its stale metadata says', () => {
+ expect(isAgentPausedTask({ ...pausedTask(), status: 'in_progress' })).toBe(false);
+ expect(isResumablePausedTask({ ...pausedTask(), status: 'pending' }, 'agent-1')).toBe(false);
+ });
+
+ it('rejects a task blocked for some other reason, and a missing task', () => {
+ expect(isAgentPausedTask(pausedTask({ blockedCategory: 'max-retries' }))).toBe(false);
+ expect(isAgentPausedTask(null)).toBe(false);
+ expect(isResumablePausedTask(null, 'agent-1')).toBe(false);
+ });
+
+ // Guards against the `undefined === undefined` hole: an agent id we don't have
+ // must never match a task that never recorded one.
+ it('never matches on a missing agent id', () => {
+ expect(isResumablePausedTask(pausedTask({ pausedAgentId: undefined }), undefined)).toBe(false);
+ });
+});
diff --git a/server/services/agentManagement.js b/server/services/agentManagement.js
index 17f72c13fb..16adcc65ad 100644
--- a/server/services/agentManagement.js
+++ b/server/services/agentManagement.js
@@ -16,7 +16,7 @@ import { emitLog } from './cosEvents.js';
// live", which is the thing this sequencing keeps removing.
import { completeAgent, updateAgent, getAgents, getAgentRecord } from './cosAgentLifecycle.js';
import { updateTask, addTask, getTaskById, reviveBlockedTask, evaluateTasks } from './cos.js';
-import { AGENT_PAUSED_CATEGORY } from './cosTaskStore.js';
+import { AGENT_PAUSED_CATEGORY, pauseMetadata, clearedPauseMetadata, isAgentPausedTask, isResumablePausedTask } from '../lib/taskPauseHold.js';
import { terminateAgentViaRunner, killAgentViaRunner, pauseAgentViaRunner, getAgentStatsFromRunner, getActiveAgentsFromRunner } from './cosRunnerClient.js';
import { MAX_TOTAL_SPAWNS } from '../lib/validation.js';
import { isInternalTaskId } from '../lib/taskParser.js';
@@ -97,25 +97,6 @@ async function terminateRunnerAgent(agentId, runnerFn, errorMessage, blockedReas
return result;
}
-// The pause bookkeeping a user pause stamps onto its task, and the patch that
-// clears it again on resume. Paired (the `taskRetryHold.js` idiom) so the two key
-// lists can't drift — a new key added to one is uncleared by the other otherwise.
-// The clear uses `undefined`, not `null`: `updateTask` DELETES undefined keys from
-// the merged metadata, while a null survives and TASKS.md serializes it as the
-// literal string `"null"`, which reads back as a live pause.
-const pauseMetadata = (agentInfo, agentId, pausedAt) => ({
- pausedAt,
- pausedAgentId: agentId,
- ...(agentInfo?.workspacePath ? { resumeWorkspacePath: agentInfo.workspacePath } : {}),
- ...(agentInfo?.runId ? { resumeRunId: agentInfo.runId } : {})
-});
-const clearedPauseMetadata = () => ({
- pausedAt: undefined,
- pausedAgentId: undefined,
- resumeWorkspacePath: undefined,
- resumeRunId: undefined
-});
-
async function markPausedTask(agentInfo, agentId, pausedAt, reason) {
const task = agentInfo?.task || (agentInfo?.taskId ? await getTaskById(agentInfo.taskId).catch(() => null) : null);
if (!task) return;
@@ -126,7 +107,7 @@ async function markPausedTask(agentInfo, agentId, pausedAt, reason) {
blockedReason: reason ? `Paused by user: ${reason}` : 'Paused by user',
blockedCategory: AGENT_PAUSED_CATEGORY,
blockedAt: pausedAt,
- ...pauseMetadata(agentInfo, agentId, pausedAt)
+ ...pauseMetadata({ agentId, pausedAt, workspacePath: agentInfo?.workspacePath, runId: agentInfo?.runId })
}
}, task.taskType || 'user');
}
@@ -223,16 +204,30 @@ export async function pauseAgent(agentId, reason = null) {
}
/**
- * Is this task the one `agentId`'s pause blocked, still waiting to be resumed?
+ * What resuming `agentId` should actually DO, given the current state of the task
+ * its pause parked. Four outcomes, and only one of them creates anything:
*
- * Anything else — the user re-ran it, it was revived and completed, a different
- * agent has since paused it — means the pause is spent and requeueing this task
- * would stomp whatever happened after. The resume falls back to a fresh task.
+ * - `requeued` — the task is still BLOCKED and is ours to restart. That covers the
+ * pause itself and any later block the task fell into (a failed retry, a cooldown,
+ * a config block): the user asking to resume is an explicit dispatch, and
+ * `reviveBlockedTask` resets the spawn/orphan budgets so it can actually run.
+ * - `superseded` — a DIFFERENT agent has since paused it. That pause is live and
+ * belongs to someone else; ours is spent, so we retire our record and touch nothing.
+ * - `already-active` — the task is `pending` or `in_progress`: some other path
+ * (a dedupe revive, an autopilot re-dispatch, a cooldown expiry, a human unblocking
+ * it) already put it back in flight. Queueing anything here is what spawned the
+ * SECOND agent users kept seeing — the work is already running, so we only retire
+ * the stale paused record.
+ * - `new-task` — the task is gone or `completed`. Nothing to restart, so the fresh
+ * task the dialog described is the honest answer.
*/
-function isResumablePausedTask(task, agentId) {
- return task?.status === 'blocked'
- && task.metadata?.blockedCategory === AGENT_PAUSED_CATEGORY
- && task.metadata?.pausedAgentId === agentId;
+function classifyResume(task, agentId) {
+ if (!task) return 'new-task';
+ if (task.status === 'pending' || task.status === 'in_progress') return 'already-active';
+ if (task.status === 'blocked') {
+ return isAgentPausedTask(task) && !isResumablePausedTask(task, agentId) ? 'superseded' : 'requeued';
+ }
+ return 'new-task';
}
/**
@@ -257,10 +252,10 @@ function isResumablePausedTask(task, agentId) {
* run. A falsy value means "unchanged" — the dialog seeds its selects from the
* paused run, so blank is absence, not an intentional clear.
*
- * When the task is no longer resumable (deleted, completed, re-run, or paused by
- * a later agent) this falls back to adding the fresh task the caller described,
- * rather than erroring: the paused RUN is over either way, and the agent record
- * is retired on both paths so nothing is left stranded in `paused`.
+ * `classifyResume` decides which of the four outcomes applies; only `new-task`
+ * creates anything. The agent record is retired on ALL of them, so a resume never
+ * leaves a stale `paused` row next to a task that has moved on — that stale row is
+ * what made the next resume click read its own pause as spent and queue a duplicate.
*
* The retirement carries `resumed: true`, which is what keeps a pause from reading
* as a failure downstream: `completeAgent` skips the `stats.errors` bump and the
@@ -270,7 +265,7 @@ function isResumablePausedTask(task, agentId) {
*
* @param {string} agentId
* @param {{context?: string, description?: string, provider?: string, model?: string, effort?: string, app?: string, screenshots?: string[]}} overrides
- * @returns {Promise<{success: true, agentId: string, taskId: string, mode: 'requeued'|'new-task', branchName: string|null}>}
+ * @returns {Promise<{success: true, agentId: string, taskId: string|null, mode: 'requeued'|'already-active'|'superseded'|'new-task', created: boolean, branchName: string|null}>}
*/
export async function resumeAgent(agentId, overrides = {}) {
const agent = await getAgentRecord(agentId);
@@ -287,9 +282,20 @@ export async function resumeAgent(agentId, overrides = {}) {
const task = taskId ? await getTaskById(taskId).catch(() => null) : null;
const taskType = task?.taskType || agent.metadata?.taskType || 'user';
- const resumed = isResumablePausedTask(task, agentId)
- ? await requeuePausedTask({ task, taskType, agentId, agentMetadata: agent.metadata, overrides })
- : await replacePausedTask({ agentId, task, taskType, overrides });
+ const mode = classifyResume(task, agentId);
+ let resumed;
+ switch (mode) {
+ case 'requeued':
+ resumed = await requeuePausedTask({ task, taskType, agentId, agentMetadata: agent.metadata, overrides });
+ break;
+ case 'new-task':
+ resumed = await replacePausedTask({ agentId, task, taskType, overrides });
+ break;
+ default:
+ // `already-active` / `superseded` — the task needs nothing done to it.
+ resumed = { taskId: task.id, mode, branchName: null };
+ }
+ const summary = resumeSummary(agentId, resumed);
// Retire the paused record LAST: `completeAgent` emits `agent:completed`, whose
// handler dequeues — so the task must already be `pending` and pointed at the
@@ -300,15 +306,32 @@ export async function resumeAgent(agentId, overrides = {}) {
success: false,
resumed: true,
resumedTaskId: resumed.taskId,
- error: `Resumed by user as ${resumed.taskId}`
+ error: summary
});
- emitLog('info', resumed.mode === 'requeued'
- ? `▶️ Resumed agent ${agentId} — task ${resumed.taskId} requeued${resumed.branchName ? ` on ${resumed.branchName}` : ' from a clean workspace'}`
- : `▶️ Resumed agent ${agentId} — its task was no longer resumable, queued ${resumed.taskId} instead`,
- { agentId, taskId: resumed.taskId, branchName: resumed.branchName });
+ emitLog('info', `▶️ ${summary}`, {
+ agentId, taskId: resumed.taskId, branchName: resumed.branchName, mode: resumed.mode
+ });
+
+ // `created` says whether anything was queued, so a caller doesn't have to keep its
+ // own copy of the mode enum to know — a client that guesses would go on announcing
+ // "created a resume task" for a future non-creating mode, which is the exact false
+ // claim this change exists to delete.
+ return { success: true, agentId, created: mode === 'new-task', ...resumed };
+}
- return { success: true, agentId, ...resumed };
+/** One line naming what the resume actually did — used for the log and the record. */
+function resumeSummary(agentId, { taskId, mode, branchName }) {
+ switch (mode) {
+ case 'requeued':
+ return `Resumed agent ${agentId} — task ${taskId} requeued${branchName ? ` on ${branchName}` : ' from a clean workspace'}`;
+ case 'already-active':
+ return `Resumed agent ${agentId} — task ${taskId} is already queued or running, nothing to restart`;
+ case 'superseded':
+ return `Resumed agent ${agentId} — task ${taskId} is paused by a later agent, leaving that pause intact`;
+ default:
+ return `Resumed agent ${agentId} — its task was no longer resumable, queued ${taskId} instead`;
+ }
}
/**
@@ -334,11 +357,10 @@ async function requeuePausedTask({ task, taskType, agentId, agentMetadata, overr
const metadata = {
...pointer,
...resumeOverrideMetadata(overrides, task.metadata?.context),
- // The pause bookkeeping `markPausedTask` stamped, cleared now that the pause
- // is lifted. `undefined`, not `null`: `updateTask` DELETES undefined keys from
- // the merged metadata, while a null survives and TASKS.md serializes it as the
- // literal string `"null"` — which reads back as a live pause.
- pausedAt: undefined, pausedAgentId: undefined, resumeWorkspacePath: undefined, resumeRunId: undefined
+ // The pause `markPausedTask` stamped, released in the same patch that consumes
+ // it (the pointer above is computed FROM it). `updateTask` drops these on the
+ // blocked transition anyway — this keeps the write self-contained.
+ ...clearedPauseMetadata()
};
// `pending` is non-terminal, so the pointer written here survives the write
@@ -353,22 +375,27 @@ async function requeuePausedTask({ task, taskType, agentId, agentMetadata, overr
}
/**
- * The fallback: the paused run's task is gone or has moved on, so queue the fresh
- * task the caller described instead. Same outcome the pre-fix client always took,
- * kept only for the case where it is actually correct.
+ * The fallback: the paused run's task is gone or completed, so queue the fresh task
+ * the caller described instead. Same outcome the pre-fix client always took, kept
+ * only for the case where it is actually correct.
+ *
+ * Everything the original task carried that SHAPES the run — its app, its
+ * provider/model/effort, its context — is INHERITED as the base, with the dialog's
+ * edits layered on top through the same `resumeOverrideMetadata` the requeue path
+ * uses, so both resumes merge by one rule. A bare description is not a runnable
+ * substitute for a task that was scoped to a managed app or pinned to a provider:
+ * dropping those is how the replacement ended up running against the wrong repo, or
+ * against a default model the user had deliberately moved off.
*/
async function replacePausedTask({ agentId, task, taskType, overrides }) {
const description = overrides.description
|| task?.description
|| `Resume ${agentId}`;
+ const { context, provider, model, effort, app } = task?.metadata || {};
const created = await addTask({
description,
- context: overrides.context || undefined,
- provider: overrides.provider || undefined,
- model: overrides.model || undefined,
- effort: overrides.effort || undefined,
- app: overrides.app || undefined,
- screenshots: overrides.screenshots?.length ? overrides.screenshots : undefined
+ context, provider, model, effort, app,
+ ...resumeOverrideMetadata(overrides, context)
}, taskType);
if (created?.error) {
throw new ServerError(`Failed to queue resume task: ${created.error}`, {
@@ -756,6 +783,59 @@ export async function settleOrphanedCreativeDirectorRun(task) {
return true;
}
+/**
+ * How long after a pause the sweep leaves a paused record alone regardless of what
+ * its task says. `markAgentPaused` writes the agent record BEFORE the task's pause
+ * hold, so for a moment a genuinely-paused agent has a task that doesn't know it —
+ * and if that second write fails outright, the sweep is the recovery, just not
+ * within the same minute.
+ */
+const PAUSE_SETTLE_GRACE_MS = 60 * 1000;
+
+/**
+ * Retire `paused` agent records whose task has moved on without them.
+ *
+ * A pause is a two-part state: the agent record says `paused`, and its task holds
+ * the matching pause (see lib/taskPauseHold.js). Plenty of paths legitimately take
+ * the task half back — a dedupe revive, an autopilot re-dispatch, a cooldown expiry,
+ * a human unblocking it, another agent pausing it later. None of them know about the
+ * agent record, so it used to sit in `paused` forever: visible in the paused list,
+ * and — because a stale pause reads as spent — turning the next resume click into a
+ * duplicate task on a second agent.
+ *
+ * Only the record is retired. The worktree stays on disk: whoever picked the task up
+ * may be running on that very branch, and the scheduled `agent-data-cleanup` job is
+ * what reaps worktrees with no live agent.
+ */
+async function retireStrandedPausedAgents(agents) {
+ const now = Date.now();
+ for (const agent of agents) {
+ if (agent.status !== 'paused') continue;
+ // No task to compare against — nothing proves the pause is spent, so leave it.
+ const taskId = agent.taskId || agent.metadata?.taskId || null;
+ if (!taskId) continue;
+ const pausedAt = Date.parse(agent.pausedAt ?? agent.metadata?.pausedAt ?? '');
+ if (Number.isFinite(pausedAt) && now - pausedAt < PAUSE_SETTLE_GRACE_MS) continue;
+
+ const task = await getTaskById(taskId).catch(() => null);
+ if (isResumablePausedTask(task, agent.id)) continue;
+
+ const reason = !task
+ ? `its task ${taskId} no longer exists`
+ : `task ${taskId} is ${task.status} and no longer holds this pause`;
+ pausedAgents.delete(agent.id);
+ // `resumed: true` for the same reason `resumeAgent` uses it: this run produced no
+ // verdict of its own, so charging it an error would invent a failure the task
+ // never had — whoever ran the task records the real outcome.
+ await completeAgent(agent.id, {
+ success: false,
+ resumed: true,
+ error: `Pause retired — ${reason}`
+ });
+ emitLog('info', `⏹️ Retired stranded paused agent ${agent.id} — ${reason}`, { agentId: agent.id, taskId });
+ }
+}
+
export async function cleanupOrphanedAgents() {
// Was `await import('./cos.js')` destructuring all four of these (#3450). The
// deferral bought nothing — this module already imports `./cos.js` statically
@@ -919,6 +999,11 @@ export async function cleanupOrphanedAgents() {
// 15-minute sweep, forever.
if (shutdownMarker) await clearHostShutdownMarker();
+ // Paused records whose task moved on without them. Not orphans (nothing died) and
+ // not counted as such — but this is the sweep that already holds the agent list,
+ // and leaving them stranded is what turns a later resume click into a duplicate.
+ await retireStrandedPausedAgents(agents);
+
// Trigger evaluation to spawn new agents for retried tasks
if (cleanedCount > 0) {
emitLog('info', `Cleaned up ${cleanedCount} orphaned agents, triggering evaluation`, { cleanedCount });
diff --git a/server/services/agentManagement.test.js b/server/services/agentManagement.test.js
index 227edcceb1..8e03b064f5 100644
--- a/server/services/agentManagement.test.js
+++ b/server/services/agentManagement.test.js
@@ -786,13 +786,56 @@ describe('resumeAgent — requeues the paused agent\'s own task', () => {
expect(markAgentComplete).toHaveBeenCalled();
});
- it('falls back to a fresh task when a LATER agent owns the pause', async () => {
+ it('inherits the replaced task\'s app and run settings — a bare description is not runnable', async () => {
+ getTaskById.mockResolvedValue({
+ ...PAUSED_TASK,
+ status: 'completed',
+ metadata: { ...PAUSED_TASK.metadata, app: 'bookloom', provider: 'codex-tui', model: 'gpt-5.6-terra', effort: 'medium' },
+ });
+ await resumeAgent('agent-paused-1', { description: '[Resume] Do the thing', context: 'extra guidance' });
+ expect(addTask).toHaveBeenCalledWith(expect.objectContaining({
+ app: 'bookloom',
+ provider: 'codex-tui',
+ model: 'gpt-5.6-terra',
+ effort: 'medium',
+ context: 'original context\n\nextra guidance',
+ }), 'user');
+ });
+
+ it('leaves a LATER agent\'s pause intact and creates nothing', async () => {
getTaskById.mockResolvedValue({
...PAUSED_TASK,
metadata: { ...PAUSED_TASK.metadata, pausedAgentId: 'agent-someone-else' },
});
- await expect(resumeAgent('agent-paused-1')).resolves.toMatchObject({ mode: 'new-task' });
+ await expect(resumeAgent('agent-paused-1')).resolves.toMatchObject({ mode: 'superseded', taskId: 'task-abc' });
+ expect(reviveBlockedTask).not.toHaveBeenCalled();
+ expect(addTask).not.toHaveBeenCalled();
+ // The stale record still retires — leaving it paused is what makes the NEXT
+ // resume click read its own pause as spent and queue a duplicate.
+ expect(markAgentComplete).toHaveBeenCalledWith('agent-paused-1', expect.objectContaining({ resumed: true }));
+ });
+
+ // The regression this whole mode exists for: something else (a dedupe revive, an
+ // autopilot re-dispatch, a cooldown expiry, a human unblocking it) already put the
+ // task back in flight. Queueing anything here is the "second agent" users saw.
+ it.each(['pending', 'in_progress'])('creates nothing when the task is already %s', async (status) => {
+ getTaskById.mockResolvedValue({ ...PAUSED_TASK, status, metadata: { context: 'original context' } });
+ await expect(resumeAgent('agent-paused-1')).resolves.toMatchObject({ mode: 'already-active', taskId: 'task-abc' });
+ expect(addTask).not.toHaveBeenCalled();
expect(reviveBlockedTask).not.toHaveBeenCalled();
+ expect(markAgentComplete).toHaveBeenCalledWith('agent-paused-1', expect.objectContaining({ resumed: true }));
+ });
+
+ // A user asking to resume is an explicit dispatch, and reviveBlockedTask resets the
+ // spawn/orphan budgets — so a task that fell into a LATER failure block restarts in
+ // place rather than being duplicated onto a fresh task.
+ it('requeues a task re-blocked for a non-pause reason instead of duplicating it', async () => {
+ getTaskById.mockResolvedValue({
+ ...PAUSED_TASK,
+ metadata: { ...PAUSED_TASK.metadata, blockedCategory: 'pr-missing' },
+ });
+ await expect(resumeAgent('agent-paused-1')).resolves.toMatchObject({ mode: 'requeued', taskId: 'task-abc' });
+ expect(addTask).not.toHaveBeenCalled();
});
it('falls back to a fresh task when the task was deleted outright', async () => {
@@ -1420,3 +1463,65 @@ describe('host-restart interruptions are not charged orphan-retry budget (#3202)
expect(markAgentComplete).toHaveBeenCalledWith('agent-dead', expect.objectContaining({ interruptedByRestart: false }));
});
});
+
+// ─── Stranded paused records ──────────────────────────────────────────────────
+//
+// A pause is TWO halves: the agent record says `paused`, and its task holds the
+// matching pause. Plenty of paths take the task half back without knowing about the
+// agent — a dedupe revive, an autopilot re-dispatch, a cooldown expiry, a human
+// unblocking it. Each left the record in `paused` forever, and because a stale pause
+// reads as spent, the next resume click queued a duplicate task on a second agent.
+describe('the sweep retires paused records whose task moved on', () => {
+ const OLD_PAUSE = new Date('2026-08-10T00:00:00.000Z').toISOString();
+ const pausedAgent = {
+ id: 'agent-paused-9', status: 'paused', taskId: 'task-9', pausedAt: OLD_PAUSE, metadata: {},
+ };
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ getAgents.mockResolvedValue([pausedAgent]);
+ readHostShutdownMarker.mockResolvedValue(null);
+ activeAgents.clear();
+ runnerAgents.clear();
+ pausedAgents.clear();
+ });
+
+ const livePause = {
+ id: 'task-9', taskType: 'user', status: 'blocked',
+ metadata: { blockedCategory: 'agent-paused', pausedAgentId: 'agent-paused-9' },
+ };
+
+ it('leaves a live pause alone — a user may resume it days later', async () => {
+ getTaskById.mockResolvedValue(livePause);
+ await cleanupOrphanedAgents();
+ expect(markAgentComplete).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ ['the task is running again', { ...livePause, status: 'in_progress', metadata: {} }],
+ ['a later agent owns the pause', { ...livePause, metadata: { blockedCategory: 'agent-paused', pausedAgentId: 'agent-other' } }],
+ ['the task was deleted', null],
+ ])('retires the record when %s', async (_label, task) => {
+ getTaskById.mockResolvedValue(task);
+ await cleanupOrphanedAgents();
+ // `resumed: true` for the same reason resumeAgent uses it — this run has no
+ // verdict of its own, so charging it an error invents a failure.
+ expect(markAgentComplete).toHaveBeenCalledWith('agent-paused-9', expect.objectContaining({
+ success: false, resumed: true, error: expect.stringContaining('Pause retired'),
+ }));
+ });
+
+ it('leaves a just-paused record alone — markAgentPaused writes the agent before the task', async () => {
+ getAgents.mockResolvedValue([{ ...pausedAgent, pausedAt: new Date().toISOString() }]);
+ getTaskById.mockResolvedValue({ id: 'task-9', taskType: 'user', status: 'in_progress', metadata: {} });
+ await cleanupOrphanedAgents();
+ expect(markAgentComplete).not.toHaveBeenCalled();
+ });
+
+ it('leaves a paused record with no task alone — nothing proves the pause is spent', async () => {
+ getAgents.mockResolvedValue([{ ...pausedAgent, taskId: null }]);
+ await cleanupOrphanedAgents();
+ expect(getTaskById).not.toHaveBeenCalled();
+ expect(markAgentComplete).not.toHaveBeenCalled();
+ });
+});
diff --git a/server/services/cosTaskStore.js b/server/services/cosTaskStore.js
index ad750172bf..6f2c270a47 100644
--- a/server/services/cosTaskStore.js
+++ b/server/services/cosTaskStore.js
@@ -20,6 +20,7 @@ import { REVIEW_STOP_MODES, normalizeReviewers, normalizeReviewUsernames, normal
import { isPlainObject } from '../lib/objects.js';
import { PR_COMPLETIONS, PR_COMPLETION_VALUES } from '../lib/prDisposition.js';
import { RETRY_HOLD_KEY, RETRY_HOLD_SINCE_KEY } from '../lib/taskRetryHold.js';
+import { AGENT_PAUSED_CATEGORY, PAUSE_METADATA_KEYS } from '../lib/taskPauseHold.js';
import { REQUEUED_AT_KEY } from '../lib/taskRequeue.js';
import { loadState, withStateLock, ROOT_DIR } from './cosState.js';
import { cosEvents } from './cosEvents.js';
@@ -44,11 +45,6 @@ export const PRIORITY_VALUES = {
const CLAIM_KEY_SET = new Set(CLAIM_METADATA_KEYS);
-// The `blockedCategory` a user pause stamps. Written by `markAgentPaused` and read
-// back by `resumeAgent` (both agentManagement.js) to prove a blocked task is still
-// the one THAT pause parked — named here so the write side, the read side, and the
-// reaper's exemption list below can't drift into three different literals.
-export const AGENT_PAUSED_CATEGORY = 'agent-paused';
// Blocked categories that mean "paused until something outside the task
// changes", not "this task is finished with". A pause keeps the resume pointer
@@ -550,9 +546,18 @@ export async function updateTask(taskId, updates, taskType = 'user', { now = Dat
if (updates[f] !== undefined) updatedMetadata[f] = updates[f] ?? undefined;
}
- // Clear blocked/failure metadata when transitioning out of blocked status
+ // Clear blocked/failure metadata when transitioning out of blocked status.
+ //
+ // The PAUSE keys go with them (`PAUSE_METADATA_KEYS`, lib/taskPauseHold.js).
+ // `resumeAgent` is not the only way a paused task runs again — a dedupe revive, an
+ // autopilot re-dispatch, an orphan-cooldown expiry, or a human unblocking it from
+ // the task list all flip it back to `pending` through here. Clearing only in
+ // `resumeAgent` left every one of those paths running a task that still advertised
+ // a live pause: the UI kept showing it parked, and `resumeAgent` on the still-paused
+ // agent record then read its own pause as spent and spawned a SECOND agent on a
+ // fresh task. The clear belongs at the transition, not at one caller.
if (updates.status && updates.status !== 'blocked' && tasks[taskIndex].status === 'blocked') {
- for (const key of ['blocker', 'blockedReason', 'blockedCategory', 'blockedAt', 'failureCount', 'lastErrorCategory', 'lastFailureAt']) {
+ for (const key of ['blocker', 'blockedReason', 'blockedCategory', 'blockedAt', 'failureCount', 'lastErrorCategory', 'lastFailureAt', ...PAUSE_METADATA_KEYS]) {
delete updatedMetadata[key];
}
}
diff --git a/server/services/cosTaskStore.test.js b/server/services/cosTaskStore.test.js
index c271ece5ac..5b948e874c 100644
--- a/server/services/cosTaskStore.test.js
+++ b/server/services/cosTaskStore.test.js
@@ -116,6 +116,7 @@ import {
DEFAULT_FAILURE_TASK_MAX_AGE_MS,
__resetTaskCache
} from './cosTaskStore.js';
+import { AGENT_PAUSED_CATEGORY, PAUSE_METADATA_KEYS } from '../lib/taskPauseHold.js';
import { MAX_TOTAL_SPAWNS } from '../lib/cosValidation.js';
const USER_FILE = '/root/TASKS.md';
@@ -682,6 +683,29 @@ describe('cosTaskStore.updateTask', () => {
expect(reopened.metadata.blockedCategory).toBeUndefined();
});
+ // The pause hold goes with it, whatever un-blocked the task. `resumeAgent` is only
+ // ONE of the paths back to pending — a dedupe revive, an autopilot re-dispatch, a
+ // cooldown expiry and a human unblocking it all land here — and every one of them
+ // used to leave a running task advertising a live pause, which made the paused
+ // agent's own resume read as spent and queue a duplicate.
+ it.each(['pending', 'in_progress'])('clears the pause hold when an unrelated path flips it to %s', async (status) => {
+ await addTask({ description: 'paused', id: 'task-pz' }, 'user');
+ await updateTask('task-pz', {
+ status: 'blocked',
+ metadata: {
+ blockedCategory: AGENT_PAUSED_CATEGORY,
+ pausedAt: '2026-08-10T00:00:00.000Z',
+ pausedAgentId: 'agent-1',
+ resumeWorkspacePath: '/w/agent-1',
+ resumeRunId: 'run-1',
+ },
+ }, 'user');
+ const revived = await updateTask('task-pz', { status }, 'user');
+ for (const key of PAUSE_METADATA_KEYS) {
+ expect(revived.metadata[key]).toBeUndefined();
+ }
+ });
+
// The pointer is spent once a task is done or parked for a human: a PERPETUAL
// task id gets re-queued for unrelated work later, and a stale existingBranch
// would attach that fresh run to a long-merged branch.