Skip to content

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

fix: resume a paused CoS agent in place instead of spawning a second one

[._.]/ Adam Eivyfc0296d507f7
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 751c2410e6..e5a48314af 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -66,6 +66,8 @@
- **A CoS agent failure now gets investigated without waiting on you.** Every `[Auto] Investigate agent failure` task was filed approval-required, so the whole point of the feature — CoS diagnosing its own failures — stalled behind a manual APPROVE click on work that is ordinary, expected traffic. Those tasks now run unattended by default, and a human is asked only when the failure is a *loop*, where spending another agent would just repeat what already didn't work: either the same cause was already investigated within the last 24 hours and has come back, or the hour is already one slot from the circuit breaker that suppresses investigations entirely, meaning failures are cascading rather than isolated. A held task says which of the two it was, in its body and on the APPROVE button, so "why is this one waiting on me?" is answerable without opening it. The existing guards are untouched: one open investigation per cause, no investigations of investigations, no investigation at all when the provider itself is unreachable, and a hard cap of three per hour. The unattended spawn still obeys the CoS autonomy mode and daily budget, so `off` and `dry-run` installs are unaffected.
+- **Resuming a paused CoS agent now actually resumes it.** "Resume" on a paused agent used to queue a *brand-new* `[Resume] …` task: a second agent spawned on a clean worktree off the default branch — redoing (or losing) whatever the paused run had already written — while the original task sat blocked as "paused" forever and the paused agent stayed listed as paused with nothing left to resume it. Every run setting the original task carried (worktree, PR posture, reviewers) was dropped along with it. Resume now requeues the paused agent's *own* task, pointed at the branch and worktree its run left behind, and retires the paused record — so the continuation picks up the uncommitted work already on disk and the agent's prompt says it is continuing rather than starting. Extra instructions from the dialog are appended to the task's own context instead of replacing it, and a blank provider/model/effort keeps what the paused run used. If the paused task has since been deleted, completed, or re-run by something else, the resume falls back to queueing a fresh task rather than stomping that outcome. A resumed run no longer counts as an error in the CoS stats or teaches the learning system a phantom failure — the continuation records the real verdict — and it revives through the shared unblock path, so a task paused near the spawn ceiling doesn't resume straight into "max spawns". Unblocking a paused task from the Tasks tab still starts clean; that second entry point is tracked in [issue-3730].
+
- **Complete LLM answers no longer fail on recoverable JSON serialization mistakes.** Long foundation calls could begin as normal JSON, then emit the complete remaining objects as escaped `\\n` / `\\"` text, leave quotation marks inside prose unescaped, or omit a prose field's closing quote immediately before its structural `}` line. The shared parser now decodes an escaped tail only from the JSON parser's exact failure position, repairs quotes only at structurally unambiguous boundaries, and accepts repairs only when the entire reconstructed response parses—preserving expensive completed work without making partial or arbitrary text look valid.
- **The foundation judge no longer mistakes visual prompt families for binding story canon.** Universe Builder categories are additive image-prompt design systems, but the foundation judge rendered their labels beside the narrative bible and named canon, then penalized duplicate-looking creatures, vehicles, and artifacts even though its world-repair editor can only revise narrative world rules. That produced a structurally unwinnable loop: the critic demanded canon-tier metadata or inventory pruning from a repair path that could not—and must not—delete the user's visual assets. Foundation scoring now reads the universe logline, premise, style, influences, and named canon only; visual prompt families remain intact and available for rendering, but edits to them no longer invalidate or distort a narrative verdict.
diff --git a/client/src/components/cos/tabs/AgentCard.jsx b/client/src/components/cos/tabs/AgentCard.jsx
index b0ce7ad838..bdc36c34db 100644
--- a/client/src/components/cos/tabs/AgentCard.jsx
+++ b/client/src/components/cos/tabs/AgentCard.jsx
@@ -493,7 +493,9 @@ export default function AgentCard({ agent, onPause, onKill, onDelete, onResume,
<button
onClick={() => onResume(agent)}
className="flex items-center gap-1 text-xs px-2 py-1 rounded bg-port-accent/20 text-port-accent hover:bg-port-accent/30 transition-colors"
- aria-label="Create new task from this agent's context"
+ aria-label={paused
+ ? "Resume this agent's task on its preserved worktree"
+ : "Create new task from this agent's context"}
>
<RotateCcw size={12} aria-hidden="true" />
<span className="hidden sm:inline">Resume</span>
diff --git a/client/src/components/cos/tabs/AgentsTab.jsx b/client/src/components/cos/tabs/AgentsTab.jsx
index 202f559eae..eb0cd06a33 100644
--- a/client/src/components/cos/tabs/AgentsTab.jsx
+++ b/client/src/components/cos/tabs/AgentsTab.jsx
@@ -120,22 +120,29 @@ export default function AgentsTab({ agents, onRefresh, liveOutputs, providers, a
onRefresh();
}, [onRefresh]);
+ // A PAUSED agent resumes IN PLACE (see `resumeAgent` in agentManagement.js):
+ // the server requeues that agent's own task on the worktree its run left behind.
+ // A COMPLETED agent's task is long settled, so it still gets a fresh one.
const handleResumeSubmit = async ({ description, context, model, provider, effort, app, type = 'user', screenshots }) => {
- const result = await api.addCosTask({
+ const payload = {
description,
context,
model: model || undefined,
provider: provider || undefined,
effort: effort || undefined,
app: app || undefined,
- type,
screenshots
- }, { silent: true }).catch(err => {
- toast.error(err.message);
- return null;
- });
- if (!result) return;
- toast.success(`Created ${type === 'internal' ? 'system ' : ''}resume task`);
+ };
+ const result = await (resumingAgent?.status === 'paused'
+ ? api.resumeCosAgent(resumingAgent.id, payload, { silent: true })
+ : api.addCosTask({ ...payload, type }, { silent: true })
+ );
+ // 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`);
setResumingAgent(null);
onRefresh();
};
diff --git a/client/src/components/cos/tabs/AgentsTab.test.jsx b/client/src/components/cos/tabs/AgentsTab.test.jsx
index d562b63dcf..8f1d03ecf2 100644
--- a/client/src/components/cos/tabs/AgentsTab.test.jsx
+++ b/client/src/components/cos/tabs/AgentsTab.test.jsx
@@ -9,6 +9,8 @@ vi.mock('../../../services/api', () => ({
getCosAgentDates: vi.fn(),
getCosAgentsByDate: vi.fn(),
clearCompletedCosAgents: vi.fn(),
+ resumeCosAgent: vi.fn(),
+ addCosTask: vi.fn(),
}));
vi.mock('../../ui/Toast', () => ({
@@ -16,9 +18,12 @@ vi.mock('../../ui/Toast', () => ({
}));
vi.mock('./AgentCard', () => ({
- default: ({ agent, onFeedbackChange }) => (
+ default: ({ agent, onFeedbackChange, onResume }) => (
<div data-testid={`agent-${agent.id}`}>
<span>{agent.metadata?.taskDescription}</span>
+ {onResume && (
+ <button type="button" onClick={() => onResume(agent)}>Resume {agent.id}</button>
+ )}
{!agent.feedback?.rating && (
<button
type="button"
@@ -34,7 +39,26 @@ vi.mock('./AgentCard', () => ({
),
}));
-vi.mock('./ResumeAgentModal', () => ({ default: () => null }));
+// Stands in for the real dialog's submit: the payload shape it hands back is
+// what AgentsTab has to route to the right endpoint.
+vi.mock('./ResumeAgentModal', () => ({
+ default: ({ agent, onSubmit }) => (
+ <button
+ type="button"
+ onClick={() => onSubmit({
+ description: `[Resume] ${agent.metadata?.taskDescription}`,
+ context: 'previous context',
+ provider: 'claude',
+ model: 'claude-opus-5',
+ effort: 'high',
+ app: '',
+ type: 'user',
+ }).catch(() => {})}
+ >
+ Submit resume
+ </button>
+ ),
+}));
vi.mock('../../ui/InlineConfirmRow', () => ({ default: () => null }));
import * as api from '../../../services/api';
@@ -69,6 +93,49 @@ beforeEach(() => {
api.getCosAgentsByDate.mockResolvedValue([]);
});
+describe('AgentsTab resume routing', () => {
+ const pausedAgent = {
+ id: 'agent-paused',
+ taskId: 'task-abc',
+ status: 'paused',
+ startedAt: '2026-07-13T09:00:00.000Z',
+ metadata: { taskDescription: 'Half-finished work' },
+ };
+
+ it('resumes a PAUSED agent in place instead of queueing a second task', async () => {
+ const user = userEvent.setup();
+ api.resumeCosAgent.mockResolvedValue({ success: true, taskId: 'task-abc', mode: 'requeued' });
+ 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(api.resumeCosAgent).toHaveBeenCalledWith(
+ 'agent-paused',
+ expect.objectContaining({ provider: 'claude', model: 'claude-opus-5', effort: 'high' }),
+ { silent: true },
+ ));
+ expect(api.addCosTask).not.toHaveBeenCalled();
+ });
+
+ 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' });
+ renderTab([completedAgent('done', 'Finished work')]);
+ await act(async () => {});
+
+ await user.click(screen.getByRole('button', { name: 'Resume done' }));
+ await user.click(screen.getByRole('button', { name: 'Submit resume' }));
+
+ await waitFor(() => expect(api.addCosTask).toHaveBeenCalledWith(
+ expect.objectContaining({ description: '[Resume] Finished work' }),
+ { silent: true },
+ ));
+ expect(api.resumeCosAgent).not.toHaveBeenCalled();
+ });
+});
+
describe('AgentsTab feedback review queue', () => {
it('filters loaded completed agents to unrated non-system runs', async () => {
const user = userEvent.setup();
diff --git a/client/src/components/cos/tabs/ResumeAgentModal.jsx b/client/src/components/cos/tabs/ResumeAgentModal.jsx
index 8eaf89aa0e..37a7674aa4 100644
--- a/client/src/components/cos/tabs/ResumeAgentModal.jsx
+++ b/client/src/components/cos/tabs/ResumeAgentModal.jsx
@@ -9,6 +9,10 @@ import EffortSelect from '../EffortSelect';
import { effectiveModelFor, effortAwareModelOptions, effortSurvivingModel, seedModelEffort } from '../../../utils/providers';
export default function ResumeAgentModal({ agent, taskType = 'user', providers, apps, onSubmit, onClose }) {
+ // A paused agent resumes IN PLACE: its own task is requeued on the worktree its
+ // run left behind. Everything else (a completed/failed run, whose task is long
+ // settled) can only be continued by queueing a new task.
+ const isPaused = agent.status === 'paused';
const taskDescription = agent.metadata?.taskDescription || agent.taskId || 'Resume previous task';
const outputSummary = agent.output?.length > 0
? agent.output.slice(-20).map(o => o.line).join('\n')
@@ -16,7 +20,7 @@ export default function ResumeAgentModal({ agent, taskType = 'user', providers,
const resultInfo = agent.result
? (agent.result.success ? 'Previous run: Completed successfully' : `Previous run: Failed - ${agent.result.error || 'Unknown error'}`)
: '';
- const pauseInfo = agent.status === 'paused'
+ const pauseInfo = isPaused
? `Previous run: Paused${agent.metadata?.pauseReason ? ` - ${agent.metadata.pauseReason}` : ''}`
: '';
const resumeWorkspace = agent.metadata?.resumeWorkspacePath || agent.metadata?.workspacePath;
@@ -134,8 +138,15 @@ export default function ResumeAgentModal({ agent, taskType = 'user', providers,
{/* Previous Task Info */}
<div className="mb-4 p-3 bg-port-bg border border-port-border rounded-lg">
- <div className="text-sm text-gray-400 mb-1">Original Task</div>
+ <div className="text-sm text-gray-400 mb-1">
+ {isPaused ? 'Paused Task (will be resumed in place)' : 'Original Task'}
+ </div>
<div className="text-white">{taskDescription}</div>
+ {isPaused && (
+ <div className="text-sm text-gray-400 mt-2">
+ This requeues the same task on the worktree the paused run left behind — no second agent, and nothing to clean up afterward.
+ </div>
+ )}
{agent.result && (
<div className={`text-sm mt-2 flex items-center gap-2 ${agent.result.success ? 'text-port-success' : 'text-port-error'}`}>
{agent.result.success ? (
@@ -283,7 +294,7 @@ export default function ResumeAgentModal({ agent, taskType = 'user', providers,
className="flex items-center gap-2 px-4 py-2 bg-port-accent/20 hover:bg-port-accent/30 text-port-accent rounded-lg text-sm transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
>
{isSubmitting ? <Loader2 size={14} className="animate-spin" /> : <RotateCcw size={14} />}
- {isSubmitting ? 'Queuing...' : 'Queue Resume Task'}
+ {isSubmitting ? 'Queuing...' : (isPaused ? 'Resume Agent' : 'Queue Resume Task')}
</button>
</div>
</form>
diff --git a/client/src/services/apiAgents.js b/client/src/services/apiAgents.js
index 841195e803..9984411812 100644
--- a/client/src/services/apiAgents.js
+++ b/client/src/services/apiAgents.js
@@ -112,6 +112,15 @@ export const pauseCosAgent = (id, reason, options = {}) => request(`/cos/agents/
body: JSON.stringify({ reason }),
...options
});
+// Resume a PAUSED agent: the server requeues that agent's own task on the branch
+// and worktree its run left behind. `overrides` are the resume dialog's edits
+// (extra context, provider/model/effort/app) — omit a field to keep the paused
+// run's value.
+export const resumeCosAgent = (id, overrides = {}, options = {}) => request(`/cos/agents/${id}/resume`, {
+ method: 'POST',
+ body: JSON.stringify(overrides),
+ ...options
+});
export const killCosAgent = (id, options = {}) => request(`/cos/agents/${id}/kill`, { method: 'POST', ...options });
export const getCosAgentStats = (id, options) => request(`/cos/agents/${id}/stats`, options);
export const getCosAgentPrompt = (id) => request(`/cos/agents/${id}/prompt`);
diff --git a/server/lib/cosValidation.js b/server/lib/cosValidation.js
index a2de7daca7..8c678cc3ac 100644
--- a/server/lib/cosValidation.js
+++ b/server/lib/cosValidation.js
@@ -1353,6 +1353,17 @@ export const slashdoTaskSchema = createCosTaskSchema
issueAuthorFilter: z.enum(ISSUE_AUTHOR_FILTERS).optional(),
});
+// POST /api/cos/agents/:id/resume — the resume dialog's edits for a paused
+// agent's next run. PICKED from createCosTaskSchema for the same reason
+// slashdoTaskSchema is: one vocabulary and one set of preprocessors for the
+// provider/model/effort knobs, whichever form supplied them. Every field is
+// optional — the resume requeues the paused agent's OWN task, so an untouched
+// dialog is a valid "resume exactly as it was". `description` only matters on
+// the fallback path where the paused task is gone and a fresh one is queued.
+export const resumeCosAgentSchema = createCosTaskSchema
+ .pick({ description: true, context: true, model: true, provider: true, effort: true, app: true, screenshots: true })
+ .partial();
+
/**
* Sanitize taskMetadata to an allow-list of agent-option keys. Boolean flags
* (`useWorktree`/`openPR`/`simplify`/`reviewLoop`/`readOnly`/`reviewerApplies`)
diff --git a/server/routes/cos.test.js b/server/routes/cos.test.js
index a26f93d23b..807c939732 100644
--- a/server/routes/cos.test.js
+++ b/server/routes/cos.test.js
@@ -53,6 +53,7 @@ vi.mock('../services/cos.js', () => ({
vi.mock('../services/agentOrchestrator.js', () => ({
requestAgentTermination: vi.fn(),
pauseAgent: vi.fn(),
+ resumeAgent: vi.fn(),
killAgent: vi.fn(),
getAgentProcessStats: vi.fn()
}));
@@ -616,6 +617,51 @@ describe('CoS Routes', () => {
});
});
+ describe('POST /api/cos/agents/:id/resume', () => {
+ it('forwards the dialog overrides to resumeAgent', async () => {
+ agentOrchestrator.resumeAgent.mockResolvedValue({ success: true, agentId: 'agent-001', taskId: 'task-abc', mode: 'requeued' });
+
+ const response = await request(app)
+ .post('/api/cos/agents/agent-001/resume')
+ .send({ context: 'try the other approach', provider: 'claude', effort: 'high' });
+
+ expect(response.status).toBe(200);
+ expect(response.body.mode).toBe('requeued');
+ expect(agentOrchestrator.resumeAgent).toHaveBeenCalledWith(
+ 'agent-001',
+ expect.objectContaining({ context: 'try the other approach', provider: 'claude', effort: 'high' }),
+ );
+ });
+
+ it('accepts an empty body — an untouched dialog resumes exactly as paused', async () => {
+ agentOrchestrator.resumeAgent.mockResolvedValue({ success: true, agentId: 'agent-001', taskId: 'task-abc', mode: 'requeued' });
+
+ const response = await request(app).post('/api/cos/agents/agent-001/resume');
+
+ expect(response.status).toBe(200);
+ expect(agentOrchestrator.resumeAgent).toHaveBeenCalledWith('agent-001', {});
+ });
+
+ it('returns 409 when the agent is not paused', async () => {
+ agentOrchestrator.resumeAgent.mockRejectedValue(
+ new ServerError('Agent agent-001 is running, not paused', { status: 409, code: 'AGENT_NOT_PAUSED' }),
+ );
+
+ const response = await request(app).post('/api/cos/agents/agent-001/resume');
+
+ expect(response.status).toBe(409);
+ });
+
+ it('rejects a malformed effort rather than passing it to the resumed run', async () => {
+ const response = await request(app)
+ .post('/api/cos/agents/agent-001/resume')
+ .send({ effort: 'turbo' });
+
+ expect(response.status).toBe(400);
+ expect(agentOrchestrator.resumeAgent).not.toHaveBeenCalled();
+ });
+ });
+
describe('POST /api/cos/agents/:id/kill', () => {
it('should force kill agent', async () => {
agentOrchestrator.killAgent.mockResolvedValue({ success: true, agentId: 'agent-001', signal: 'SIGKILL' });
diff --git a/server/routes/cosAgentRoutes.js b/server/routes/cosAgentRoutes.js
index b713700342..83d2f1bb6c 100644
--- a/server/routes/cosAgentRoutes.js
+++ b/server/routes/cosAgentRoutes.js
@@ -8,7 +8,7 @@ import * as cos from '../services/cos.js';
// Lifecycle transitions go through the facade (#3450), not the `cos.js` barrel.
import * as agentOrchestrator from '../services/agentOrchestrator.js';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
-import { validateRequest } from '../lib/validation.js';
+import { validateRequest, resumeCosAgentSchema } from '../lib/validation.js';
const router = Router();
@@ -94,6 +94,16 @@ router.post('/agents/:id/pause', asyncHandler(async (req, res) => {
res.json(result);
}));
+// POST /api/cos/agents/:id/resume - Requeue a paused agent's own task on the
+// branch/worktree its run left behind, and retire the paused record.
+// resumeAgent throws a ServerError — 404 when the agent is missing, 409 when it
+// isn't paused, 500 when the requeue write fails.
+router.post('/agents/:id/resume', asyncHandler(async (req, res) => {
+ const overrides = validateRequest(resumeCosAgentSchema, req.body ?? {});
+ const result = await agentOrchestrator.resumeAgent(req.params.id, overrides);
+ res.json(result);
+}));
+
// POST /api/cos/agents/:id/kill - Force kill agent (immediate SIGKILL)
// killAgent throws a ServerError — 404 when the agent is missing, 500 when the
// runner termination fails — so no result-shape string-matching here.
diff --git a/server/services/agentManagement.js b/server/services/agentManagement.js
index 9fcc6e5fc5..17f72c13fb 100644
--- a/server/services/agentManagement.js
+++ b/server/services/agentManagement.js
@@ -14,8 +14,9 @@ import { emitLog } from './cosEvents.js';
// to open. Inside the closure the single address for a transition is the module
// that declares it; a barrel would be a third answer to "where does completeAgent
// live", which is the thing this sequencing keeps removing.
-import { completeAgent, updateAgent, getAgents } from './cosAgentLifecycle.js';
-import { updateTask, addTask, getTaskById, evaluateTasks } from './cos.js';
+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 { terminateAgentViaRunner, killAgentViaRunner, pauseAgentViaRunner, getAgentStatsFromRunner, getActiveAgentsFromRunner } from './cosRunnerClient.js';
import { MAX_TOTAL_SPAWNS } from '../lib/validation.js';
import { isInternalTaskId } from '../lib/taskParser.js';
@@ -96,22 +97,37 @@ 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;
- const metadata = {
- ...task.metadata,
- blockedReason: reason ? `Paused by user: ${reason}` : 'Paused by user',
- blockedCategory: 'agent-paused',
- blockedAt: pausedAt,
- pausedAt,
- pausedAgentId: agentId
- };
- if (agentInfo?.workspacePath) metadata.resumeWorkspacePath = agentInfo.workspacePath;
- if (agentInfo?.runId) metadata.resumeRunId = agentInfo.runId;
await updateTask(task.id, {
status: 'blocked',
- metadata
+ metadata: {
+ ...task.metadata,
+ blockedReason: reason ? `Paused by user: ${reason}` : 'Paused by user',
+ blockedCategory: AGENT_PAUSED_CATEGORY,
+ blockedAt: pausedAt,
+ ...pauseMetadata(agentInfo, agentId, pausedAt)
+ }
}, task.taskType || 'user');
}
@@ -206,6 +222,183 @@ export async function pauseAgent(agentId, reason = null) {
return { success: true, agentId, pausedAt, mode: agent.tuiSessionId ? 'tui' : 'direct' };
}
+/**
+ * Is this task the one `agentId`'s pause blocked, 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 the pause is spent and requeueing this task
+ * would stomp whatever happened after. The resume falls back to a fresh task.
+ */
+function isResumablePausedTask(task, agentId) {
+ return task?.status === 'blocked'
+ && task.metadata?.blockedCategory === AGENT_PAUSED_CATEGORY
+ && task.metadata?.pausedAgentId === agentId;
+}
+
+/**
+ * Resume a PAUSED agent: requeue the agent's OWN task, pointed at the branch and
+ * worktree its paused run left behind, and retire the paused agent record.
+ *
+ * Before this, "resume" was a client-side illusion — the UI queued a brand-new
+ * `[Resume] <description>` task carrying the old run's context as prose. That
+ * produced three wrong outcomes at once: a second agent spawned on a clean
+ * worktree off the default branch (so the paused run's work was redone, or lost),
+ * the original task stayed `blocked` as `agent-paused` forever, and the paused
+ * agent record sat in `paused` with nothing left to resume it.
+ *
+ * The requeue reuses the retry machinery: `resolveTaskResumePatch` decides what
+ * the paused run actually left behind (adopt its surviving worktree, attach to
+ * its branch, or nothing) and `agentWorkspacePrep` already honors the resulting
+ * `existingBranch`/`resumeWorktreePath` pointer — so resuming needs no new spawn
+ * plumbing, and `resumedFromAgentId` gets the prompt's resume banner for free.
+ *
+ * `overrides` carries the resume dialog's edits: extra `context` (appended to the
+ * task's, never replacing it), and provider/model/effort/app changes for the new
+ * 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`.
+ *
+ * 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
+ * learning listener (taskLearning/lifecycle.js) skips the record entirely. Both
+ * matter because the run is a CONTINUATION — the resumed run records the real
+ * verdict, so counting this one charges a phantom failure and double-counts the task.
+ *
+ * @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}>}
+ */
+export async function resumeAgent(agentId, overrides = {}) {
+ const agent = await getAgentRecord(agentId);
+ if (!agent) {
+ throw new ServerError('Agent not found', { status: 404, code: 'NOT_FOUND' });
+ }
+ if (agent.status !== 'paused') {
+ throw new ServerError(`Agent ${agentId} is ${agent.status}, not paused`, {
+ status: 409, code: 'AGENT_NOT_PAUSED'
+ });
+ }
+
+ const taskId = agent.taskId || agent.metadata?.taskId || null;
+ 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 });
+
+ // Retire the paused record LAST: `completeAgent` emits `agent:completed`, whose
+ // handler dequeues — so the task must already be `pending` and pointed at the
+ // resume branch before the spawn it triggers can pick it up. Paused records are
+ // explicitly completable (see the idempotence guard in `completeAgent`).
+ pausedAgents.delete(agentId);
+ await completeAgent(agentId, {
+ success: false,
+ resumed: true,
+ resumedTaskId: resumed.taskId,
+ error: `Resumed by user as ${resumed.taskId}`
+ });
+
+ 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 });
+
+ return { success: true, agentId, ...resumed };
+}
+
+/**
+ * The in-place resume: flip the paused task back to `pending` carrying the resume
+ * pointer and the dialog's overrides, in ONE write — the task must never be
+ * spawnable before it is pointed, or the dequeue `completeAgent` triggers could
+ * grab it mid-transition and start clean.
+ *
+ * Through `reviveBlockedTask`, the shared address for "an explicit dispatch path
+ * un-blocks a blocked task": on top of updateTask's blocked-transition clear it
+ * resets the spawn/orphan retry budgets, so a task paused near the MAX_TOTAL_SPAWNS
+ * ceiling doesn't resume straight into `max-spawns`.
+ */
+async function requeuePausedTask({ task, taskType, agentId, agentMetadata, overrides }) {
+ // Fails open to "start clean" the way every other resume-pointer caller does:
+ // requeueing the task matters more than resuming it, and the worktree stays on
+ // disk for a human either way.
+ const pointer = await resolveTaskResumePatch({ task, agentId, agentMetadata }).catch(err => {
+ emitLog('warn', `Resume pointer for task ${task.id} could not be resolved: ${err.message}`, { taskId: task.id, agentId });
+ return {};
+ });
+
+ 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
+ };
+
+ // `pending` is non-terminal, so the pointer written here survives the write
+ // (updateTask only strips a resume pointer on a terminal status).
+ const result = await reviveBlockedTask(task.id, { metadata }, taskType);
+ if (result?.error) {
+ throw new ServerError(`Failed to requeue task ${task.id}: ${result.error}`, {
+ status: 500, code: 'AGENT_RESUME_FAILED'
+ });
+ }
+ return { taskId: task.id, mode: 'requeued', branchName: pointer.existingBranch || null };
+}
+
+/**
+ * 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.
+ */
+async function replacePausedTask({ agentId, task, taskType, overrides }) {
+ const description = overrides.description
+ || task?.description
+ || `Resume ${agentId}`;
+ 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
+ }, taskType);
+ if (created?.error) {
+ throw new ServerError(`Failed to queue resume task: ${created.error}`, {
+ status: 500, code: 'AGENT_RESUME_FAILED'
+ });
+ }
+ return { taskId: created.id, mode: 'new-task', branchName: null };
+}
+
+/**
+ * The dialog's edits as a task-metadata patch. Every field is "unchanged unless
+ * supplied" — the dialog seeds its selects from the paused run, so a blank value
+ * is absence rather than an intentional clear (CLAUDE.md's absent-vs-empty rule).
+ * `context` APPENDS to `existingContext`: the task's own context is what the
+ * original run was given, and dropping it would resume with less information than
+ * the run that paused.
+ */
+function resumeOverrideMetadata({ context, provider, model, effort, app, screenshots }, existingContext) {
+ const patch = {};
+ if (context) {
+ patch.context = [existingContext, context].filter(Boolean).join('\n\n');
+ }
+ if (provider) patch.provider = provider;
+ if (model) patch.model = model;
+ if (effort) patch.effort = effort;
+ if (app) patch.app = app;
+ if (screenshots?.length) patch.screenshots = screenshots;
+ return patch;
+}
+
/**
* Terminate an agent (graceful SIGTERM with SIGKILL fallback).
*/
diff --git a/server/services/agentManagement.test.js b/server/services/agentManagement.test.js
index d1c1e4e991..227edcceb1 100644
--- a/server/services/agentManagement.test.js
+++ b/server/services/agentManagement.test.js
@@ -46,6 +46,7 @@ vi.mock('./cos.js', () => ({
addTask: vi.fn().mockResolvedValue({ id: 'sys-mocked' }),
getTaskById: vi.fn(),
getAllTasks: vi.fn(),
+ reviveBlockedTask: vi.fn().mockResolvedValue(true),
evaluateTasks: vi.fn().mockResolvedValue(undefined)
}));
@@ -69,6 +70,7 @@ vi.mock('./cosAgentLifecycle.js', () => ({
completeAgent: vi.fn().mockResolvedValue(undefined),
updateAgent: vi.fn().mockResolvedValue(undefined),
getAgents: vi.fn().mockResolvedValue([]),
+ getAgentRecord: vi.fn().mockResolvedValue(null),
}));
vi.mock('./cosRunnerClient.js', () => ({
terminateAgentViaRunner: vi.fn(),
@@ -102,13 +104,13 @@ vi.mock('./creativeDirector/local.js', () => ({
vi.mock('./creativeDirector/planAdvance.js', () => ({ advanceAfterPlanStepSettled: vi.fn().mockResolvedValue(undefined) }));
vi.mock('./creativeDirector/completionHook.js', () => ({ advanceAfterSceneSettled: vi.fn().mockResolvedValue(undefined) }));
-import { handleOrphanedTask, pauseAgent, settleOrphanedCreativeDirectorRun, cleanupOrphanedAgents } from './agentManagement.js';
+import { handleOrphanedTask, pauseAgent, resumeAgent, settleOrphanedCreativeDirectorRun, cleanupOrphanedAgents } from './agentManagement.js';
import { cleanupAgentWorktree, resolveTaskResumePatch } from './agentWorktreeCleanup.js';
-import { getAgents, updateAgent, completeAgent as markAgentComplete } from './cosAgentLifecycle.js';
+import { getAgents, updateAgent, getAgentRecord, completeAgent as markAgentComplete } from './cosAgentLifecycle.js';
import { updateRun, getProject } from './creativeDirector/local.js';
import { advanceAfterPlanStepSettled } from './creativeDirector/planAdvance.js';
import { advanceAfterSceneSettled } from './creativeDirector/completionHook.js';
-import { updateTask, addTask, getTaskById } from './cos.js';
+import { updateTask, addTask, getTaskById, reviveBlockedTask } from './cos.js';
import { pauseAgentViaRunner } from './cosRunnerClient.js';
import * as shellService from './shell.js';
import { readHostShutdownMarker, clearHostShutdownMarker } from '../lib/hostShutdown.js';
@@ -639,6 +641,166 @@ describe('pauseAgent — agent not found', () => {
});
});
+// ─── resumeAgent ──────────────────────────────────────────────────────────────
+//
+// Resuming used to be a client-side illusion: the UI queued a brand-new
+// `[Resume] <description>` task, so a SECOND agent spawned on a clean worktree,
+// the paused agent's own task stayed `blocked` as `agent-paused` forever, and
+// the paused record was never retired. These lock the real transition.
+
+describe('resumeAgent — requeues the paused agent\'s own task', () => {
+ const PAUSED_AGENT = {
+ id: 'agent-paused-1',
+ status: 'paused',
+ taskId: 'task-abc',
+ metadata: {
+ isWorktree: true,
+ worktreeBranch: 'cos/task-abc/agent-paused-1',
+ workspacePath: '/tmp/worktrees/agent-paused-1',
+ sourceWorkspace: '/tmp/repo',
+ taskType: 'user',
+ },
+ };
+ const PAUSED_TASK = {
+ id: 'task-abc',
+ taskType: 'user',
+ description: 'Do the thing',
+ status: 'blocked',
+ metadata: {
+ blockedCategory: 'agent-paused',
+ pausedAgentId: 'agent-paused-1',
+ pausedAt: '2026-08-10T00:00:00.000Z',
+ resumeWorkspacePath: '/tmp/worktrees/agent-paused-1',
+ resumeRunId: 'run-1',
+ context: 'original context',
+ },
+ };
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ pausedAgents.clear();
+ getAgentRecord.mockResolvedValue(PAUSED_AGENT);
+ getTaskById.mockResolvedValue(PAUSED_TASK);
+ resolveTaskResumePatch.mockResolvedValue({
+ existingBranch: 'cos/task-abc/agent-paused-1',
+ resumedFromAgentId: 'agent-paused-1',
+ resumeWorktreePath: '/tmp/worktrees/agent-paused-1',
+ });
+ });
+
+ it('flips the SAME task back to pending carrying the resume pointer — no new task', async () => {
+ const result = await resumeAgent('agent-paused-1');
+
+ expect(result).toMatchObject({ success: true, taskId: 'task-abc', mode: 'requeued' });
+ expect(addTask).not.toHaveBeenCalled();
+ expect(reviveBlockedTask).toHaveBeenCalledWith('task-abc', {
+ metadata: expect.objectContaining({
+ existingBranch: 'cos/task-abc/agent-paused-1',
+ resumedFromAgentId: 'agent-paused-1',
+ resumeWorktreePath: '/tmp/worktrees/agent-paused-1',
+ }),
+ }, 'user');
+ // Through reviveBlockedTask, NOT a raw updateTask: it also resets the
+ // spawn/orphan budgets, so a task paused near MAX_TOTAL_SPAWNS doesn't resume
+ // straight into `max-spawns`.
+ expect(updateTask).not.toHaveBeenCalled();
+ });
+
+ it('clears the spent pause bookkeeping with undefined (which updateTask deletes), not null', async () => {
+ await resumeAgent('agent-paused-1');
+ const { metadata } = reviveBlockedTask.mock.calls[0][1];
+ for (const key of ['pausedAt', 'pausedAgentId', 'resumeWorkspacePath', 'resumeRunId']) {
+ expect(metadata).toHaveProperty(key);
+ expect(metadata[key]).toBeUndefined();
+ }
+ });
+
+ it('retires the paused agent record so it stops showing as paused', async () => {
+ await resumeAgent('agent-paused-1');
+ expect(markAgentComplete).toHaveBeenCalledWith('agent-paused-1', expect.objectContaining({
+ success: false,
+ resumed: true,
+ resumedTaskId: 'task-abc',
+ }));
+ });
+
+ it('requeues BEFORE retiring the record — the dequeue completeAgent triggers must see a pointed task', async () => {
+ const order = [];
+ reviveBlockedTask.mockImplementationOnce(async () => { order.push('reviveBlockedTask'); return true; });
+ markAgentComplete.mockImplementationOnce(async () => { order.push('completeAgent'); });
+ await resumeAgent('agent-paused-1');
+ expect(order).toEqual(['reviveBlockedTask', 'completeAgent']);
+ });
+
+ it('appends dialog context to the task\'s own and applies provider/model/effort overrides', async () => {
+ await resumeAgent('agent-paused-1', {
+ context: 'extra guidance', provider: 'claude', model: 'claude-opus-5', effort: 'high',
+ });
+ const { metadata } = reviveBlockedTask.mock.calls[0][1];
+ expect(metadata.context).toBe('original context\n\nextra guidance');
+ expect(metadata).toMatchObject({ provider: 'claude', model: 'claude-opus-5', effort: 'high' });
+ });
+
+ it('leaves unspecified run settings alone — a blank dialog field is absence, not a clear', async () => {
+ await resumeAgent('agent-paused-1', { provider: '', model: undefined, context: '' });
+ const { metadata } = reviveBlockedTask.mock.calls[0][1];
+ expect(metadata).not.toHaveProperty('provider');
+ expect(metadata).not.toHaveProperty('model');
+ expect(metadata).not.toHaveProperty('context');
+ });
+
+ it('still requeues (clean) when the paused run left nothing resumable behind', async () => {
+ resolveTaskResumePatch.mockResolvedValue({});
+ const result = await resumeAgent('agent-paused-1');
+ expect(result).toMatchObject({ mode: 'requeued', branchName: null });
+ expect(reviveBlockedTask.mock.calls[0][1].metadata).not.toHaveProperty('existingBranch');
+ });
+
+ it('requeues clean rather than failing when the pointer cannot be resolved', async () => {
+ resolveTaskResumePatch.mockRejectedValue(new Error('git exploded'));
+ await expect(resumeAgent('agent-paused-1')).resolves.toMatchObject({ mode: 'requeued' });
+ expect(reviveBlockedTask).toHaveBeenCalled();
+ });
+
+ it('throws 404 for an unknown agent and 409 for one that is not paused', async () => {
+ getAgentRecord.mockResolvedValueOnce(null);
+ await expect(resumeAgent('nope')).rejects.toMatchObject({ status: 404, code: 'NOT_FOUND' });
+
+ getAgentRecord.mockResolvedValueOnce({ ...PAUSED_AGENT, status: 'running' });
+ await expect(resumeAgent('agent-paused-1')).rejects.toMatchObject({ status: 409, code: 'AGENT_NOT_PAUSED' });
+ expect(reviveBlockedTask).not.toHaveBeenCalled();
+ });
+
+ it('falls back to a fresh task when the pause is spent — and still retires the record', async () => {
+ // The task was revived and completed while the agent sat paused; requeueing
+ // it would stomp that outcome.
+ getTaskById.mockResolvedValue({ ...PAUSED_TASK, status: 'completed' });
+ const result = await resumeAgent('agent-paused-1', { description: '[Resume] Do the thing' });
+
+ expect(result).toMatchObject({ mode: 'new-task', taskId: 'sys-mocked' });
+ expect(reviveBlockedTask).not.toHaveBeenCalled();
+ expect(addTask).toHaveBeenCalledWith(
+ expect.objectContaining({ description: '[Resume] Do the thing' }),
+ 'user',
+ );
+ expect(markAgentComplete).toHaveBeenCalled();
+ });
+
+ it('falls back to a fresh task when a LATER agent owns the pause', async () => {
+ getTaskById.mockResolvedValue({
+ ...PAUSED_TASK,
+ metadata: { ...PAUSED_TASK.metadata, pausedAgentId: 'agent-someone-else' },
+ });
+ await expect(resumeAgent('agent-paused-1')).resolves.toMatchObject({ mode: 'new-task' });
+ expect(reviveBlockedTask).not.toHaveBeenCalled();
+ });
+
+ it('falls back to a fresh task when the task was deleted outright', async () => {
+ getTaskById.mockResolvedValue(null);
+ await expect(resumeAgent('agent-paused-1')).resolves.toMatchObject({ mode: 'new-task' });
+ });
+});
+
// ─── Close-handler skip-finalization contract ─────────────────────────────────
//
// When a pausedAgents-flagged agent's process exits, the close handlers in
diff --git a/server/services/agentOrchestrator.js b/server/services/agentOrchestrator.js
index b922105b72..b308901953 100644
--- a/server/services/agentOrchestrator.js
+++ b/server/services/agentOrchestrator.js
@@ -132,6 +132,7 @@
// Process/runner layer — owns the live agent maps and the OS-level signals.
export {
pauseAgent, // running → paused (process stopped, worktree preserved)
+ resumeAgent, // paused → completed, task requeued on the preserved branch
killAgent, // running → completed (immediate SIGKILL)
terminateAgent, // running → completed (SIGTERM, SIGKILL fallback)
getAgentProcessStats, // read, not a transition — but it needs the process layer
diff --git a/server/services/agentOrchestrator.test.js b/server/services/agentOrchestrator.test.js
index 41f5fa9314..f9f23ad935 100644
--- a/server/services/agentOrchestrator.test.js
+++ b/server/services/agentOrchestrator.test.js
@@ -14,6 +14,7 @@ import { describe, it, expect, vi } from 'vitest';
vi.mock('./agentManagement.js', () => ({
pauseAgent: () => {},
+ resumeAgent: () => {},
killAgent: () => {},
terminateAgent: () => {},
getAgentProcessStats: () => {}
@@ -36,6 +37,7 @@ import * as agentLifecycle from './agentLifecycle.js';
// [facade export, source module, name in that module]
const WIRING = [
['pauseAgent', agentManagement, 'pauseAgent'],
+ ['resumeAgent', agentManagement, 'resumeAgent'],
['killAgent', agentManagement, 'killAgent'],
['terminateAgent', agentManagement, 'terminateAgent'],
['getAgentProcessStats', agentManagement, 'getAgentProcessStats'],
diff --git a/server/services/cosAgentLifecycle.js b/server/services/cosAgentLifecycle.js
index 8f152ca26c..1fd3537863 100644
--- a/server/services/cosAgentLifecycle.js
+++ b/server/services/cosAgentLifecycle.js
@@ -185,7 +185,11 @@ export async function completeAgent(agentId, result = {}) {
if (result.success) {
state.stats.tasksCompleted++;
- } else {
+ } else if (!result.resumed) {
+ // `resumed` records are retired by `resumeAgent`, not failed: the user paused
+ // the run and its task is already requeued, so the continuation will land in
+ // one of these two counters itself. Counting it here reports an error the user
+ // caused deliberately and never saw.
state.stats.errors = (state.stats.errors || 0) + 1;
}
diff --git a/server/services/cosAgentLifecycle.test.js b/server/services/cosAgentLifecycle.test.js
index 70060391d1..21c35a68e0 100644
--- a/server/services/cosAgentLifecycle.test.js
+++ b/server/services/cosAgentLifecycle.test.js
@@ -234,6 +234,27 @@ describe('completeAgent budget-ledger ordering (#1683)', () => {
consoleSpy.mockRestore();
});
+ it('does not charge stats.errors for a record retired by a resume', async () => {
+ // `resumeAgent` retires a PAUSED record here so it stops showing as paused. The
+ // run wasn't a failure — the user paused it and its task is already requeued, so
+ // the continuation lands in one of these counters itself. Counting it reports an
+ // error the user caused deliberately and never saw.
+ mockCosState.state.agents['agent-resumed'] = {
+ id: 'agent-resumed', status: 'paused', metadata: { taskType: 'user' }
+ };
+ mockCosState.state.agents['agent-failed'] = {
+ id: 'agent-failed', status: 'running', metadata: { taskType: 'user' }
+ };
+
+ await completeAgent('agent-resumed', { success: false, resumed: true, resumedTaskId: 'task-abc' });
+ expect(mockCosState.state.stats.errors).toBe(0);
+ expect(mockCosState.state.agents['agent-resumed'].status).toBe('completed');
+
+ // An ordinary failure still counts.
+ await completeAgent('agent-failed', { success: false, exitCode: 1 });
+ expect(mockCosState.state.stats.errors).toBe(1);
+ });
+
it('skips usage accounting for user tasks but still emits agent:completed', async () => {
const agentId = 'agent-user';
mockCosState.state.agents[agentId] = {
diff --git a/server/services/cosTaskStore.js b/server/services/cosTaskStore.js
index 69d80385e1..ad750172bf 100644
--- a/server/services/cosTaskStore.js
+++ b/server/services/cosTaskStore.js
@@ -44,6 +44,12 @@ 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
// (see updateTask) and is never auto-expired by the failure reaper (see
@@ -823,8 +829,8 @@ export const DEFAULT_REAP_LIMIT = 50;
// stale failure artifact — the reaper leaves these alone. Everything else with a
// `blockedCategory` is a failure-path block and therefore reapable.
const NON_REAPABLE_BLOCKED_CATEGORIES = new Set([
- 'user-terminated', // user explicitly stopped the agent
- 'agent-paused', // user paused; resumable on demand
+ 'user-terminated', // user explicitly stopped the agent
+ AGENT_PAUSED_CATEGORY, // user paused; resumable on demand
'challenge-escalation', // parked awaiting the user's arbitration
// The workspace blocks are an OPEN user decision, not a stale failure: the task
// is waiting for the app's Repository Path to be fixed, and auto-completing it
diff --git a/server/services/taskLearning/lifecycle.js b/server/services/taskLearning/lifecycle.js
index b290d76286..ba7f80bc6a 100644
--- a/server/services/taskLearning/lifecycle.js
+++ b/server/services/taskLearning/lifecycle.js
@@ -35,6 +35,12 @@ function withoutStaleCoordinatorVerdict(agent, task) {
*/
export function initTaskLearning() {
cosEvents.on('agent:completed', async (agent) => {
+ // A record retired by `resumeAgent` is a CONTINUATION, not an outcome: the run
+ // was paused by the user and its task is already back in the queue, where the
+ // resumed run will record the real verdict. Learning from it would charge the
+ // task type and model tier a phantom failure per pause, and double-count the
+ // task once the continuation finishes.
+ if (agent?.result?.resumed) return;
// Get task info from agent
const task = {
id: agent.taskId,
diff --git a/server/services/taskLearning/lifecycle.test.js b/server/services/taskLearning/lifecycle.test.js
index 07680de786..fd0ab508f8 100644
--- a/server/services/taskLearning/lifecycle.test.js
+++ b/server/services/taskLearning/lifecycle.test.js
@@ -18,8 +18,9 @@ vi.mock('./store.js', () => ({
}));
vi.mock('../cos.js', () => ({ getAgents: vi.fn(async () => agentsStore.list) }));
-import { backfillFromHistory } from './lifecycle.js';
+import { backfillFromHistory, initTaskLearning } from './lifecycle.js';
import { recordTaskCompletion } from './metrics.js';
+import { cosEvents } from './store.js';
const completed = (taskId, analysisType, validationPassed) => ({
status: 'completed',
@@ -104,3 +105,36 @@ describe('backfillFromHistory — stale coordinator verdict (#2696)', () => {
expect(recordTaskCompletion.mock.calls[0][0].result.validationPassed).toBeNull();
});
});
+
+describe('agent:completed listener — a resumed record is a continuation, not an outcome', () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ // `resumeAgent` (agentManagement.js) retires a PAUSED record via completeAgent so it
+ // stops showing as paused. That fires `agent:completed` with `success: false` — but the
+ // run wasn't a failure, it was interrupted by the user and its task is already back in
+ // the queue. Learning from it charges the task type and model tier a phantom failure
+ // per pause, and double-counts the task once the continuation finishes.
+ const emitCompleted = async (agent) => {
+ initTaskLearning();
+ const handler = cosEvents.on.mock.calls.find(([event]) => event === 'agent:completed')[1];
+ await handler(agent);
+ };
+
+ it('skips a record retired by a resume', async () => {
+ await emitCompleted({
+ status: 'completed', taskId: 't1',
+ result: { success: false, resumed: true, resumedTaskId: 't1' },
+ metadata: { taskType: 'user', taskDescription: 'Half-finished work' },
+ });
+ expect(recordTaskCompletion).not.toHaveBeenCalled();
+ });
+
+ it('still records an ordinary failed run', async () => {
+ await emitCompleted({
+ status: 'completed', taskId: 't1',
+ result: { success: false, error: 'tests failed' },
+ metadata: { taskType: 'user', taskDescription: 'Half-finished work' },
+ });
+ expect(recordTaskCompletion).toHaveBeenCalledTimes(1);
+ });
+});