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: resolve the resume pointer at the pause release so any un-block resumes in place, not just the Resume dialog (#3730)

[._.]/ Adam Eivya2135753802b
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index cd56118c38..5a18dbacf3 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -245,3 +245,5 @@
- **[issue-3726] The character-foundation repair stage no longer builds a prompt too large to answer.** A real autonomous run assembled a 72,404-char prompt for `pipeline-character-foundation` and burned the CLI runner's full 5-minute wall clock without emitting a single byte, failing the whole run. The stage already had a budget — `REPAIR_OUTLINE_MAX_CHARS`, added after a 35KB prompt hung both a primary and a fallback TUI provider — but it bound only one of the prompt's three large sections, and not the largest: 35KB of raw series seed and 15KB of candidate cast rode along unbudgeted, while the outline itself overran its own soft cap by 49% because `renderArc`'s volume spine and character-arc tail were unconditional and could exceed `maxChars` outright. Each section now carries a 12,000-char budget and degrades in priority order rather than being sliced mid-sentence: the series seed sheds its style-guide exemplars (craft material a character repair cannot use) before flattening authored arcs to their want/need spine; the cast payload compacts the full-ensemble roster to a name/role/want/need line and drops members before it touches the batch actually under repair; and `renderArc` drops whole episode lines, then per-volume synopses (keeping `V# title: logline`), and finally clamps — so `maxChars` is a hard bound for any volume/episode/arc shape, pinned by a property test. Every tier names what it left out so the model can tell a short plan from a budgeted one, and the JSON sections stay parseable at every tier. The stage also now requests an explicit 10-minute timeout, matching what TUI providers already default to: the runner's 300s default is what actually killed the run.
- **[issue-3733] The reviewer row's Effort cell now narrows to the tiers its pinned model actually offers.** `agy` validates the model/effort PAIR — `gemini-3.1-pro` has no `medium` tier — and the provider pickers already honored that, but `ReviewerPicker`'s Effort column read a static `low|medium|high` ladder with no knowledge of the model pinned beside it. So a user could pick `gemini-3.1-pro` + `medium` and PortOS would store, display, and emit an invocation agy rejects. `useReviewerModelOptions` (which already fetches `/api/providers` for the Model column) now exposes a `modelEffortLevels(reviewer, model)` accessor built on the same `antigravityModelEffortLevels` helper, and the Effort cell narrows through it — falling back to the full ladder whenever the catalog is empty, the model is unset, or the caller passes no options, so no surface loses its control. A model the catalog lists with no tiers at all drops the cell, unless an effort is already stored: a stale pin stays visible (`medium (unsupported)`) and clearable rather than silently reading as unset.
+
+- **[issue-3730] Un-blocking a paused CoS task from the Tasks tab now resumes it on the worktree its paused run left behind, instead of starting clean.** Releasing a pause takes two things, and only one of them had moved out of the Resume dialog: the bookkeeping is now dropped by the task itself whichever path un-blocks it, but the *pointer* at the branch and worktree the paused run left on disk was still resolved inside Resume. So clicking the blocked-status icon on a paused task — or any of the five dispatch paths that revive a blocked twin (on-demand Run, pipeline advance, a Creative Director re-trigger, a manual job trigger, voice dispatch) — put the task back in the queue with nothing pointing at that work, and the next agent started from a clean checkout and redid it. The pointer is now resolved by the same transition that clears the pause, so every door resumes in place; it is resolved *before* the task becomes queueable, so no spawn can grab the task in the moment between un-blocking it and pointing it. The paused agent card is also retired the instant its task starts running again rather than waiting for the next background sweep to notice, and a pointer that can't be resolved (the branch merged, the worktree is gone) still un-blocks the task and simply starts clean, as every other resume path does.
diff --git a/server/lib/README.md b/server/lib/README.md
index b025985106..907ebed1ec 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -238,7 +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. |
+| `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. Also carries the cycle-safe RELEASE adapter (#3730) `agentManagement.js` registers at load — `resolvePausedTaskResume(task)` hands `updateTask` the paused run's resume pointer before the write (so any un-block resumes on the preserved worktree, not just the Resume dialog) and `retirePausedAgent(agentId, taskId, branchName)` retires the paused record after it. |
| `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/taskPauseHold.js b/server/lib/taskPauseHold.js
index 5c3d781bb8..c7ba59f0f5 100644
--- a/server/lib/taskPauseHold.js
+++ b/server/lib/taskPauseHold.js
@@ -77,3 +77,55 @@ export function isAgentPausedTask(task) {
export function isResumablePausedTask(task, agentId) {
return isAgentPausedTask(task) && !!agentId && task.metadata?.pausedAgentId === agentId;
}
+
+// === Pause-release adapter (registration-based) ============================
+//
+// Releasing the hold is not only a metadata clear (#3730). The run that paused
+// left a branch and often a worktree behind, and the resumed run has to be POINTED
+// at them or it starts clean and redoes the work — the exact symptom the resume fix
+// removed for the Resume dialog and nowhere else. Resolving that pointer needs the
+// paused agent's RECORD, which lives in the agent graph; `cosTaskStore.js` cannot
+// import it (static cycle, see `services/agentImportCycles.test.js`). So the
+// agent-addressed half is injected: `agentManagement.js` registers it at module
+// load, the way `services/sharing/recordEvents.js` registers its subscription
+// adapter. Until registration every call is a silent no-op — which is what the task
+// store's own unit suites want: no agent graph pulled in, nothing to mock.
+
+let pauseReleaseAdapter = null;
+
+/** `agentManagement.js` registers the real implementation at module load. */
+export function registerPauseReleaseAdapter(adapter) {
+ pauseReleaseAdapter = adapter;
+}
+
+/** Whether the agent-side half is wired. */
+export function hasPauseReleaseAdapter() {
+ return pauseReleaseAdapter !== null;
+}
+
+/** Test-only: detach the adapter so later suites see the unregistered state. */
+export function __resetPauseReleaseAdapter() {
+ pauseReleaseAdapter = null;
+}
+
+/**
+ * What did the paused run leave behind? The resume-pointer patch
+ * (`existingBranch` / `resumeWorktreePath` / `resumedFromAgentId`) for the agent
+ * `task.metadata.pausedAgentId` names, or `{}` when there is nothing to adopt.
+ * Awaited BEFORE the task's own write, so the task is never `pending` — and
+ * therefore spawnable — without its pointer.
+ */
+export async function resolvePausedTaskResume(task) {
+ return (await pauseReleaseAdapter?.resolvePausedTaskResume?.(task)) || {};
+}
+
+/**
+ * Retire the paused record now that its task is running again — immediately, rather
+ * than leaving it to the next `retireStrandedPausedAgents` sweep, so the paused card
+ * disappears when the user un-blocks the task instead of up to a sweep interval
+ * later. Called AFTER the task write: retirement emits `agent:completed`, whose
+ * handler dequeues, so the task must already be `pending` and pointed first.
+ */
+export async function retirePausedAgent(agentId, taskId, branchName) {
+ return pauseReleaseAdapter?.retirePausedAgent?.(agentId, taskId, branchName);
+}
diff --git a/server/services/agentManagement.js b/server/services/agentManagement.js
index 16adcc65ad..deb15d5099 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, pauseMetadata, clearedPauseMetadata, isAgentPausedTask, isResumablePausedTask } from '../lib/taskPauseHold.js';
+import { AGENT_PAUSED_CATEGORY, pauseMetadata, isAgentPausedTask, isResumablePausedTask, registerPauseReleaseAdapter } 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,6 +97,47 @@ async function terminateRunnerAgent(agentId, runnerFn, errorMessage, blockedReas
return result;
}
+// The agent-addressed half of the pause release (#3730). `updateTask` drops the
+// pause bookkeeping whenever a task leaves `blocked`, but the resumed run also has
+// to be POINTED at the branch/worktree the paused run left behind — and resolving
+// that needs the paused agent's record. `cosTaskStore.js` cannot import this module
+// (static cycle, see `agentImportCycles.test.js`), so it reaches these two steps
+// through the registration below, the way `sharing/recordEvents.js` registers its
+// subscription adapter. That is what makes the Tasks-tab status toggle and
+// `reviveBlockedTask` resume in place instead of spawning clean, not just the
+// Resume dialog.
+registerPauseReleaseAdapter({
+ /**
+ * Same `resolveTaskResumePatch` every other dead-run path uses, addressed by the
+ * agent the task's own pause bookkeeping names.
+ */
+ resolvePausedTaskResume: async (task) => {
+ const agentId = task?.metadata?.pausedAgentId;
+ if (!agentId) return {};
+ const agent = await getAgentRecord(agentId).catch(() => null);
+ return resolveTaskResumePatch({ task, agentId, agentMetadata: agent?.metadata || null });
+ },
+
+ /**
+ * Retire the paused record the moment its task is running again, rather than
+ * leaving the card stranded until the next `retireStrandedPausedAgents` sweep.
+ * Guarded on the record still being `paused`, and it writes the SAME verdict
+ * `resumeAgent` would — so whichever of the two fires first, the record reads
+ * identically and the other is a no-op through `completeAgent`'s idempotence.
+ */
+ retirePausedAgent: async (agentId, taskId, branchName) => {
+ const agent = await getAgentRecord(agentId).catch(() => null);
+ if (agent?.status !== 'paused') return;
+ pausedAgents.delete(agentId);
+ await completeAgent(agentId, {
+ success: false,
+ resumed: true,
+ resumedTaskId: taskId,
+ error: resumeSummary(agentId, { taskId, mode: 'requeued', branchName })
+ });
+ }
+});
+
async function markPausedTask(agentInfo, agentId, pausedAt, reason) {
const task = agentInfo?.task || (agentInfo?.taskId ? await getTaskById(agentInfo.taskId).catch(() => null) : null);
if (!task) return;
@@ -286,7 +327,7 @@ export async function resumeAgent(agentId, overrides = {}) {
let resumed;
switch (mode) {
case 'requeued':
- resumed = await requeuePausedTask({ task, taskType, agentId, agentMetadata: agent.metadata, overrides });
+ resumed = await requeuePausedTask({ task, taskType, overrides });
break;
case 'new-task':
resumed = await replacePausedTask({ agentId, task, taskType, overrides });
@@ -340,38 +381,32 @@ function resumeSummary(agentId, { taskId, mode, branchName }) {
* spawnable before it is pointed, or the dequeue `completeAgent` triggers could
* grab it mid-transition and start clean.
*
+ * Since #3730 this is a thin agent-addressed wrapper contributing ONLY the dialog's
+ * overrides: the pointer, the pause release, and the record's retirement belong to
+ * `cosTaskStore.updateTask`, which performs them for every caller of the flip.
+ *
* 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 `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
+async function requeuePausedTask({ task, taskType, overrides }) {
+ // Only the dialog's edits. The resume pointer and the pause release belong to
+ // `updateTask` (#3730) so every OTHER door into this flip gets them too — resolving
+ // them here as well would run the same git probe twice per Resume click and put a
+ // second copy of the rule where it can drift.
+ //
+ // `pending` is non-terminal, so the pointer that write lands survives it
// (updateTask only strips a resume pointer on a terminal status).
- const result = await reviveBlockedTask(task.id, { metadata }, taskType);
+ const result = await reviveBlockedTask(task.id, {
+ metadata: resumeOverrideMetadata(overrides, task.metadata?.context)
+ }, 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 };
+ return { taskId: task.id, mode: 'requeued', branchName: result?.metadata?.existingBranch || null };
}
/**
diff --git a/server/services/agentManagement.test.js b/server/services/agentManagement.test.js
index 8e03b064f5..ac64b36f69 100644
--- a/server/services/agentManagement.test.js
+++ b/server/services/agentManagement.test.js
@@ -117,6 +117,7 @@ import { readHostShutdownMarker, clearHostShutdownMarker } from '../lib/hostShut
import { completeAgentRun } from './agentRunTracking.js';
import { committedDuringRun } from '../lib/gitCommitProbe.js';
import { activeAgents, runnerAgents, pausedAgents } from './agentState.js';
+import { hasPauseReleaseAdapter, resolvePausedTaskResume, retirePausedAgent } from '../lib/taskPauseHold.js';
describe('settleOrphanedCreativeDirectorRun — reap a dead CD agent run (#2705)', () => {
beforeEach(() => vi.clearAllMocks());
@@ -688,31 +689,27 @@ describe('resumeAgent — requeues the paused agent\'s own task', () => {
});
});
- it('flips the SAME task back to pending carrying the resume pointer — no new task', async () => {
+ it('flips the SAME task back to pending — 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');
+ // ONLY the dialog's overrides (none here). Since #3730 the resume pointer and
+ // the pause release are `updateTask`'s, so the Tasks-tab toggle and every other
+ // door into this flip get them too — see the adapter suite below and
+ // cosTaskStore.test.js for the transition itself.
+ expect(reviveBlockedTask).toHaveBeenCalledWith('task-abc', { metadata: {} }, '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('reports the branch the shared transition resumed on', async () => {
+ reviveBlockedTask.mockResolvedValueOnce({ metadata: { existingBranch: 'cos/task-abc/agent-paused-1' } });
+ await expect(resumeAgent('agent-paused-1')).resolves.toMatchObject({
+ mode: 'requeued', branchName: 'cos/task-abc/agent-paused-1',
+ });
});
it('retires the paused agent record so it stops showing as paused', async () => {
@@ -750,16 +747,8 @@ describe('resumeAgent — requeues the paused agent\'s own task', () => {
});
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();
+ reviveBlockedTask.mockResolvedValueOnce({ metadata: {} });
+ await expect(resumeAgent('agent-paused-1')).resolves.toMatchObject({ mode: 'requeued', branchName: null });
});
it('throws 404 for an unknown agent and 409 for one that is not paused', async () => {
@@ -844,6 +833,69 @@ describe('resumeAgent — requeues the paused agent\'s own task', () => {
});
});
+// ─── Pause-release adapter (#3730) ────────────────────────────────────────────
+//
+// The agent-addressed half `cosTaskStore.updateTask` calls through, registered at
+// this module's load. Exercised via the lib accessors — the same address the task
+// store uses — so a registration that silently stops happening fails here. It is
+// what makes an unblock from ANY door resume on the preserved worktree, not just
+// the Resume dialog.
+
+describe('pause-release adapter registration', () => {
+ const PAUSED_AGENT = {
+ id: 'agent-paused-9',
+ status: 'paused',
+ taskId: 'task-xyz',
+ metadata: { isWorktree: true, worktreeBranch: 'cos/task-xyz/agent-paused-9', workspacePath: '/tmp/worktrees/agent-paused-9' },
+ };
+ const PAUSED_TASK = {
+ id: 'task-xyz',
+ status: 'blocked',
+ metadata: { blockedCategory: 'agent-paused', pausedAgentId: 'agent-paused-9' },
+ };
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ pausedAgents.clear();
+ getAgentRecord.mockResolvedValue(PAUSED_AGENT);
+ });
+
+ it('is wired at module load', () => {
+ expect(hasPauseReleaseAdapter()).toBe(true);
+ });
+
+ it('resolves the pointer from the agent the task names', async () => {
+ resolveTaskResumePatch.mockResolvedValue({ existingBranch: 'cos/task-xyz/agent-paused-9' });
+ await expect(resolvePausedTaskResume(PAUSED_TASK)).resolves.toMatchObject({ existingBranch: 'cos/task-xyz/agent-paused-9' });
+ expect(resolveTaskResumePatch).toHaveBeenCalledWith({
+ task: PAUSED_TASK, agentId: 'agent-paused-9', agentMetadata: PAUSED_AGENT.metadata,
+ });
+ });
+
+ it('resolves empty when the task names no paused agent', async () => {
+ await expect(resolvePausedTaskResume({ id: 't', metadata: {} })).resolves.toEqual({});
+ expect(resolveTaskResumePatch).not.toHaveBeenCalled();
+ });
+
+ it('retires the paused record immediately, with the verdict resumeAgent would write', async () => {
+ pausedAgents.set('agent-paused-9', { pausedAt: 'now' });
+ await retirePausedAgent('agent-paused-9', 'task-xyz', 'cos/task-xyz/agent-paused-9');
+ expect(pausedAgents.has('agent-paused-9')).toBe(false);
+ expect(markAgentComplete).toHaveBeenCalledWith('agent-paused-9', {
+ success: false,
+ resumed: true,
+ resumedTaskId: 'task-xyz',
+ error: 'Resumed agent agent-paused-9 — task task-xyz requeued on cos/task-xyz/agent-paused-9',
+ });
+ });
+
+ it('is a no-op when the record is no longer paused — the second retire must not re-complete it', async () => {
+ getAgentRecord.mockResolvedValue({ ...PAUSED_AGENT, status: 'completed' });
+ await retirePausedAgent('agent-paused-9', 'task-xyz', null);
+ expect(markAgentComplete).not.toHaveBeenCalled();
+ });
+});
+
// ─── Close-handler skip-finalization contract ─────────────────────────────────
//
// When a pausedAgents-flagged agent's process exits, the close handlers in
diff --git a/server/services/cosTaskStore.js b/server/services/cosTaskStore.js
index 6f2c270a47..5c59cd658f 100644
--- a/server/services/cosTaskStore.js
+++ b/server/services/cosTaskStore.js
@@ -20,7 +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 { AGENT_PAUSED_CATEGORY, PAUSE_METADATA_KEYS, isAgentPausedTask, resolvePausedTaskResume, retirePausedAgent } 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';
@@ -510,9 +510,64 @@ export async function addTask(taskData, taskType = 'user', { raw = false, ignore
}
/**
- * Update an existing task
+ * Update an existing task.
+ *
+ * Wraps the persisted write with the rest of the pause release (#3730). Dropping
+ * `PAUSE_METADATA_KEYS` on the blocked transition (below) stops a revived task from
+ * advertising a pause it no longer has, but a pause is not only bookkeeping: the run
+ * that paused left a branch — usually a whole worktree — behind, and the resumed run
+ * has to be POINTED at it or it starts clean and redoes that work. Resolving that
+ * pointer lived in `resumeAgent`, so the Resume dialog resumed properly while every
+ * other door into `blocked(agent-paused) → pending` (the Tasks-tab status toggle's
+ * bare `{ status: 'pending' }`, and `reviveBlockedTask` on behalf of on-demand Run /
+ * pipeline advance / Creative Director / manual job trigger / voice dispatch) still
+ * spawned a second agent on a clean workspace. Owning it at the transition fixes
+ * them all, and future callers by construction.
+ *
+ * The resolve runs BEFORE the lock and the retire AFTER it. Both reach the agent
+ * layer through the registered adapter, and `retirePausedAgent` writes agent state
+ * via `completeAgent` — which takes the same non-reentrant `withStateLock`, so
+ * running either inside would deadlock. Resolving first is also what keeps the task
+ * from ever being `pending` (spawnable) without its pointer.
*/
export async function updateTask(taskId, updates, taskType = 'user', { now = Date.now() } = {}) {
+ const release = await preparePauseRelease(taskId, updates);
+ const result = await writeTaskUpdate(taskId, release ? { ...updates, metadata: release.metadata } : updates, taskType, { now });
+ if (release && !result?.error) {
+ await retirePausedAgent(release.agentId, taskId, result?.metadata?.existingBranch || null);
+ }
+ return result;
+}
+
+/**
+ * Is this update releasing a user pause, and if so what does the resumed run need?
+ *
+ * `null` for every other update — including a paused task moving to any status but
+ * `pending` (terminating a paused task is not a resume; nothing to point at, and the
+ * record's retirement belongs to whatever terminated it), and a pending flip on a
+ * task nobody paused. `pausedAgentId` is required: without it there is no record to
+ * resolve a pointer from or retire, so the flip is an ordinary unblock.
+ */
+async function preparePauseRelease(taskId, updates) {
+ if (updates?.status !== 'pending') return null;
+ const task = await getTaskById(taskId).catch(() => null);
+ if (!isAgentPausedTask(task)) return null;
+ const agentId = task.metadata?.pausedAgentId;
+ if (!agentId) return null;
+
+ // Fails open to "start clean" the way every other resume-pointer caller does:
+ // un-blocking the task matters more than resuming it in place, and the worktree
+ // stays on disk for a human either way.
+ const pointer = await resolvePausedTaskResume(task).catch(err => {
+ console.error(`❌ Resume pointer for task ${taskId} could not be resolved: ${err.message}`);
+ return {};
+ });
+ // The caller's own metadata still wins — the Resume dialog's provider/model/context
+ // overrides, and a caller that resolved a pointer itself.
+ return { agentId, metadata: { ...pointer, ...(updates.metadata || {}) } };
+}
+
+async function writeTaskUpdate(taskId, updates, taskType, { now }) {
return withStateLock(async () => {
const state = await loadState();
const filePath = taskType === 'user'
diff --git a/server/services/cosTaskStore.test.js b/server/services/cosTaskStore.test.js
index 5b948e874c..fa8df143e0 100644
--- a/server/services/cosTaskStore.test.js
+++ b/server/services/cosTaskStore.test.js
@@ -9,7 +9,7 @@
* was extracted) that pin the first-line dedup + per-app dedup scope.
*/
-import { describe, it, expect, beforeEach, vi } from 'vitest';
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { readFileSync as realReadFileSync } from 'node:fs';
import { fileURLToPath } from 'url';
import { dirname, join } from 'path';
@@ -116,7 +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 { AGENT_PAUSED_CATEGORY, PAUSE_METADATA_KEYS, registerPauseReleaseAdapter, __resetPauseReleaseAdapter } from '../lib/taskPauseHold.js';
import { MAX_TOTAL_SPAWNS } from '../lib/cosValidation.js';
const USER_FILE = '/root/TASKS.md';
@@ -706,6 +706,125 @@ describe('cosTaskStore.updateTask', () => {
}
});
+ // ─── Resuming in place, from ANY door (#3730) ──────────────────────────────
+ //
+ // Clearing the hold above stops a revived task from advertising a pause it no
+ // longer has, but a pause is not only bookkeeping: the run that paused left a
+ // branch (usually a whole worktree) behind, and the resumed run has to be POINTED
+ // at it or it starts clean and redoes the work. That resolve lived in
+ // `resumeAgent`, so the Resume dialog resumed properly while the Tasks-tab status
+ // toggle and `reviveBlockedTask` — the shared address for on-demand Run, pipeline
+ // advance, Creative Director, manual job trigger and voice dispatch — still spawned
+ // a second agent on a clean workspace. These drive each entry point.
+ describe('releasing a user pause resumes in place', () => {
+ let calls;
+ const POINTER = { existingBranch: 'cos/task-p/agent-paused-1', resumeWorktreePath: '/tmp/wt', resumedFromAgentId: 'agent-paused-1' };
+
+ const plantPausedTask = async (id) => {
+ await addTask({ description: `paused ${id}`, id }, 'user');
+ await updateTask(id, {
+ status: 'blocked',
+ metadata: {
+ blockedCategory: AGENT_PAUSED_CATEGORY,
+ blockedReason: 'Paused by user',
+ pausedAt: '2026-08-10T00:00:00.000Z',
+ pausedAgentId: 'agent-paused-1',
+ resumeWorkspacePath: '/tmp/wt',
+ resumeRunId: 'run-1',
+ },
+ }, 'user');
+ return id;
+ };
+
+ const expectResumedInPlace = (task) => {
+ expect(task.status).toBe('pending');
+ expect(task.metadata).toMatchObject(POINTER);
+ for (const key of [...PAUSE_METADATA_KEYS, 'blockedCategory']) {
+ expect(task.metadata[key]).toBeUndefined();
+ }
+ expect(calls.retired).toEqual([['agent-paused-1', task.id, POINTER.existingBranch]]);
+ };
+
+ beforeEach(() => {
+ calls = { resolved: [], retired: [], statusAtRetire: [] };
+ registerPauseReleaseAdapter({
+ resolvePausedTaskResume: async (task) => { calls.resolved.push(task.id); return POINTER; },
+ retirePausedAgent: async (agentId, taskId, branchName) => {
+ calls.retired.push([agentId, taskId, branchName]);
+ calls.statusAtRetire.push((await getTaskById(taskId))?.status);
+ },
+ });
+ });
+ afterEach(() => __resetPauseReleaseAdapter());
+
+ it('resumes on the preserved worktree from a bare status flip (the Tasks-tab toggle)', async () => {
+ const id = await plantPausedTask('task-pause-toggle');
+ expectResumedInPlace(await updateTask(id, { status: 'pending' }, 'user'));
+ });
+
+ it('resumes on the preserved worktree from reviveBlockedTask (the five dispatch paths)', async () => {
+ const id = await plantPausedTask('task-pause-revive');
+ expectResumedInPlace(await reviveBlockedTask(id, { metadata: { context: 'from the dispatcher' } }, 'user'));
+ });
+
+ it("keeps the caller's own metadata alongside the pointer", async () => {
+ const id = await plantPausedTask('task-pause-overrides');
+ const revived = await reviveBlockedTask(id, { metadata: { provider: 'claude', context: 'extra' } }, 'user');
+ expect(revived.metadata).toMatchObject({ provider: 'claude', context: 'extra', existingBranch: POINTER.existingBranch });
+ });
+
+ // The task must never be `pending` (spawnable) without its pointer, and the
+ // retirement — whose `agent:completed` triggers a dequeue — must not run until
+ // the pointed task is on disk.
+ it('resolves the pointer BEFORE the write and retires the record AFTER it', async () => {
+ const id = await plantPausedTask('task-pause-order');
+ await updateTask(id, { status: 'pending' }, 'user');
+ expect(calls.resolved).toEqual([id]);
+ expect(calls.statusAtRetire).toEqual(['pending']);
+ });
+
+ it('still un-blocks (clean) when the pointer cannot be resolved', async () => {
+ registerPauseReleaseAdapter({
+ resolvePausedTaskResume: async () => { throw new Error('git exploded'); },
+ retirePausedAgent: async (agentId, taskId, branchName) => calls.retired.push([agentId, taskId, branchName]),
+ });
+ const id = await plantPausedTask('task-pause-boom');
+ const revived = await updateTask(id, { status: 'pending' }, 'user');
+ expect(revived.status).toBe('pending');
+ expect(revived.metadata.existingBranch).toBeUndefined();
+ expect(revived.metadata.pausedAgentId).toBeUndefined();
+ expect(calls.retired).toEqual([['agent-paused-1', id, null]]);
+ });
+
+ it('leaves a differently-blocked task alone', async () => {
+ await addTask({ description: 'not paused', id: 'task-not-paused' }, 'user');
+ await updateTask('task-not-paused', { status: 'blocked', metadata: { blockedCategory: 'max-spawns' } }, 'user');
+ await reviveBlockedTask('task-not-paused', {}, 'user');
+ expect(calls.resolved).toEqual([]);
+ expect(calls.retired).toEqual([]);
+ });
+
+ // Terminating a paused task is not a resume — nothing to point at, nothing to
+ // continue, and the record's retirement belongs to whatever terminated it.
+ it('leaves a paused task moving to a terminal status alone', async () => {
+ const id = await plantPausedTask('task-pause-terminal');
+ await updateTask(id, { status: 'completed' }, 'user');
+ expect(calls.resolved).toEqual([]);
+ expect(calls.retired).toEqual([]);
+ });
+
+ // The bookkeeping names the agent to resolve against and retire. Without it the
+ // flip is an ordinary unblock, not a resume.
+ it('treats a paused task with no pausedAgentId as an ordinary unblock', async () => {
+ await addTask({ description: 'orphan pause', id: 'task-pause-noagent' }, 'user');
+ await updateTask('task-pause-noagent', { status: 'blocked', metadata: { blockedCategory: AGENT_PAUSED_CATEGORY } }, 'user');
+ const revived = await updateTask('task-pause-noagent', { status: 'pending' }, 'user');
+ expect(revived.status).toBe('pending');
+ expect(calls.resolved).toEqual([]);
+ expect(calls.retired).toEqual([]);
+ });
+ });
+
// 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.