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: preserve Deep checkpoints through cleanup and explicit resume

Adam Eivy4962ae83a10a
diff --git a/docs/DEEP-AUDITS.md b/docs/DEEP-AUDITS.md
index 1ef2854140..6fde6499a3 100644
--- a/docs/DEEP-AUDITS.md
+++ b/docs/DEEP-AUDITS.md
@@ -4,7 +4,7 @@ Deep is an audit depth, independent of **File issues** or **Audit and fix** deli
## Run and resume
-In an app's **Quality** tab, choose the categories, delivery policy, provider/model and **Audit depth → Deep**, then Run now. A launch performs one assigned pass, not the whole audit. A partial checkpoint stops the maintenance run. **Resume Deep audit** starts another invocation using the same coverage ledger. It may finish the current pass before moving to the next. Failed Deep tasks are parked rather than automatically retried. Boot and reading status do not launch work.
+In an app's **Quality** tab, choose the categories, delivery policy, provider/model and **Audit depth → Deep**, then Run now. A launch performs one assigned pass, not the whole audit. A partial checkpoint stops the maintenance run. **Resume Deep audit** starts another invocation using the same coverage ledger. It may finish the current pass before moving to the next. Failed Deep tasks are parked rather than automatically retried. Completion keeps the task held until worktree cleanup finishes, then atomically parks it with any surviving branch/worktree pointer. Explicit resume waits for that handoff and reuses the persisted audit instructions. Recovery of an interrupted invocation also parks it for explicit resume instead of treating a commit or retry budget as permission to continue. Boot and reading status do not launch work.
An app's **Automation** tab also exposes depth separately from delivery. An explicitly configured schedule can start a Deep audit; a partial task then parks and blocks further automatic dispatch for that app/category. Use Run Now to resume explicitly. Its app/category/delivery identity keeps the same ledger across those invocations. Custom agent jobs accept `taskMetadata.auditDepth: "deep"` and an optional `deepAuditId` for an explicitly selected checkpoint. A custom job without an audit category uses the code-quality coverage category. Different apps, categories and delivery modes cannot share a checkpoint.
diff --git a/server/lib/taskBlockCategories.js b/server/lib/taskBlockCategories.js
index 4b49ec0a59..0ec2906285 100644
--- a/server/lib/taskBlockCategories.js
+++ b/server/lib/taskBlockCategories.js
@@ -58,6 +58,7 @@ export const TIMED_COOLDOWN_BLOCKED_CATEGORIES = new Set([
*/
export const PAUSED_BLOCKED_CATEGORIES = new Set([
...TIMED_COOLDOWN_BLOCKED_CATEGORIES,
+ 'deep-audit-partial', // Explicit resume only; keep retained remediation and never auto-expire.
'app-unresolved', // the task's app has no usable Repository Path
'workspace-invalid', // the resolved workspace isn't a usable directory
// A CONFIG pause, NOT a timed one: nothing stamps a `cooldownUntil` for it and
@@ -85,6 +86,7 @@ export const USER_DECISION_BLOCKED_CATEGORIES = new Set([
'user-terminated', // user explicitly stopped the agent
AGENT_PAUSED_CATEGORY, // user paused; resumable on demand
'challenge-escalation', // parked awaiting the user's arbitration
+ 'deep-audit-partial', // Explicit resume only; keep retained remediation and never auto-expire.
'app-unresolved',
'workspace-invalid',
// A task the markdown store could not represent, parked here by
diff --git a/server/services/agentFinalization.js b/server/services/agentFinalization.js
index d9d52d4a39..a700615b40 100644
--- a/server/services/agentFinalization.js
+++ b/server/services/agentFinalization.js
@@ -1,3 +1,4 @@
+import { retryHoldMetadata } from '../lib/taskRetryHold.js';
import { PR_COMPLETIONS, resolvePrCompletion, PR_MISSING_CATEGORY, prClaimWasVerified } from '../lib/prDisposition.js';
import { isAuditTaskType } from '../lib/auditCatalog.js';
import { isPrivateSecurityTask } from '../lib/privateSecurityPolicy.js';
@@ -1601,7 +1602,7 @@ export async function finalizeAgent({
const taskType = task?.taskType || 'user';
const taskUpdate = task.metadata?.auditDepth === 'deep' && !terminatedByUser
- ? { status: 'blocked', metadata: { ...preHookTask.metadata, blockedReason: 'Deep audit checkpoint; resume explicitly', blockedCategory: 'deep-audit-partial', blockedAt: new Date().toISOString() } }
+ ? { status: 'in_progress', metadata: { ...preHookTask.metadata, ...retryHoldMetadata(agentId) } }
: terminatedByUser
? {
status: 'blocked',
diff --git a/server/services/agentFinalization.outputHooks.test.js b/server/services/agentFinalization.outputHooks.test.js
index 6774b42897..e8e1dda478 100644
--- a/server/services/agentFinalization.outputHooks.test.js
+++ b/server/services/agentFinalization.outputHooks.test.js
@@ -214,7 +214,7 @@ describe('recovery output-hook dispatch (#3182)', () => {
workspacePath: '/example/repo', startedAt: Date.now() - 1000, outputBuffer: 'Context exhausted',
errorAnalysis: { type: 'transient', retryable: true, error: 'context exhausted' } });
expect(resolveFailedTaskUpdate).not.toHaveBeenCalled();
- expect(updateTask).toHaveBeenCalledWith(task.id, expect.objectContaining({ status: 'blocked', metadata: expect.objectContaining({ blockedCategory: 'deep-audit-partial' }) }), expect.anything());
+ expect(updateTask).toHaveBeenCalledWith(task.id, expect.objectContaining({ status: 'in_progress', metadata: expect.objectContaining({ retryPendingCleanup: expect.any(String) }) }), expect.anything());
expect(deep.checkpointDeepAudit).toHaveBeenCalledWith(expect.objectContaining({ success: false }));
});
diff --git a/server/services/agentManagement.js b/server/services/agentManagement.js
index bb3e02ba8b..9540259b79 100644
--- a/server/services/agentManagement.js
+++ b/server/services/agentManagement.js
@@ -1505,6 +1505,31 @@ export async function handleOrphanedTask(taskId, agentId, getTaskByIdFn, { agent
return;
}
+ // Recovery of a dead Deep invocation is a checkpoint, never permission to
+ // auto-launch another provider call or to treat commits as completed coverage.
+ if (task.metadata?.auditDepth === 'deep') {
+ if (task.status !== 'in_progress') return;
+ const held = isRetryHeld(task.metadata);
+ if (held && task.metadata[RETRY_HOLD_KEY] !== agentId) return;
+ if (!held) {
+ const spawnedAt = toEpochMs(task.metadata?.[LAST_SPAWNED_AT_KEY]);
+ const startedAt = toEpochMs(agentStartedAt);
+ // A legacy/unknown owner cannot authorize parking a newer invocation.
+ if (!spawnedAt || !startedAt || spawnedAt > startedAt) return;
+ const agents = await getAgents();
+ if (!Array.isArray(agents) || agents.some(entry => entry.taskId === taskId && entry.id !== agentId
+ && (entry.status === 'running' || toEpochMs(entry.startedAt) > startedAt))) return;
+ }
+ const resumePatch = await resolveTaskResumePatch({ task, agentId, agentMetadata });
+ await updateTask(taskId, { status: 'blocked', metadata: {
+ ...resumePatch, ...clearedRetryHoldMetadata(), blockedCategory: 'deep-audit-partial',
+ blockedReason: 'Interrupted Deep audit; inspect checkpoint and resume explicitly', blockedAt: new Date().toISOString(),
+ } }, task.taskType || 'user', { expectedStatus: 'in_progress',
+ expectedMetadata: held ? { [RETRY_HOLD_KEY]: agentId } : { [LAST_SPAWNED_AT_KEY]: task.metadata[LAST_SPAWNED_AT_KEY] },
+ });
+ return;
+ }
+
// A retry hold whose process died mid-transition (#3373). The run's verdict is
// already persisted — it failed, and was budgeted a retry — so this is not a
// fresh orphan: finish the transition the dead process started (resolve the
diff --git a/server/services/agentManagement.test.js b/server/services/agentManagement.test.js
index 05ebfc3cdb..cfc88c532e 100644
--- a/server/services/agentManagement.test.js
+++ b/server/services/agentManagement.test.js
@@ -1933,6 +1933,31 @@ describe('the orphan sweep finishes an interrupted retry transition (#3373)', ()
committedDuringRun.mockReset();
});
+ it('recovers interrupted Deep cleanup as an explicit checkpoint, preserving the branch and refusing a stale owner', async () => {
+ const selected = heldTask(); selected.metadata.auditDepth = 'deep';
+ getTaskById.mockResolvedValue(selected);
+ resolveTaskResumePatch.mockResolvedValue({ existingBranch: 'cos/deep', resumedFromAgentId: 'agent-dead' });
+ await handleOrphanedTask(selected.id, 'agent-dead', getTaskById);
+ expect(updateTask).toHaveBeenCalledWith(selected.id, expect.objectContaining({ status: 'blocked', metadata: expect.objectContaining({
+ existingBranch: 'cos/deep', blockedCategory: 'deep-audit-partial', retryPendingCleanup: undefined,
+ }) }), 'user', { expectedStatus: 'in_progress', expectedMetadata: { retryPendingCleanup: 'agent-dead' } });
+ expect(committedDuringRun).not.toHaveBeenCalled();
+ updateTask.mockClear();
+ await handleOrphanedTask(selected.id, 'agent-old', getTaskById);
+ expect(updateTask).not.toHaveBeenCalled();
+ });
+
+ it('binds no-hold Deep orphan recovery to its spawn stamp and refuses an older attempt', async () => {
+ const selected = { id: 'task-1', taskType: 'user', status: 'in_progress', metadata: { auditDepth: 'deep', lastSpawnedAt: '2026-01-02T00:00:00.000Z' } };
+ getTaskById.mockResolvedValue(selected);
+ await handleOrphanedTask(selected.id, 'agent-old', getTaskById, { agentStartedAt: '2026-01-01T00:00:00.000Z' });
+ expect(updateTask).not.toHaveBeenCalled();
+ await handleOrphanedTask(selected.id, 'agent-current', getTaskById, { agentStartedAt: '2026-01-02T00:00:01.000Z' });
+ expect(updateTask).toHaveBeenCalledWith(selected.id, expect.objectContaining({ status: 'blocked' }), 'user', {
+ expectedStatus: 'in_progress', expectedMetadata: { lastSpawnedAt: selected.metadata.lastSpawnedAt },
+ });
+ });
+
it('flips the held task to pending with the resume pointer and drops the marker', async () => {
getTaskById.mockResolvedValue(heldTask());
resolveTaskResumePatch.mockResolvedValue({ existingBranch: 'cos/task-1/agent-dead', resumedFromAgentId: 'agent-dead', resumeWorktreePath: null });
diff --git a/server/services/agentWorktreeCleanup.js b/server/services/agentWorktreeCleanup.js
index b53eca7251..dad0e5ff41 100644
--- a/server/services/agentWorktreeCleanup.js
+++ b/server/services/agentWorktreeCleanup.js
@@ -932,7 +932,8 @@ export async function recordTaskResumePointer({ task, agentId, agentMetadata })
* @returns {Promise<object>} the metadata patch that was written (empty when nothing was)
*/
export async function releaseRetryHold({ agentId, task, success, agentMetadata }) {
- if (success || !agentId || !task?.id) return {};
+ if (!agentId || !task?.id) return {};
+ if (success && task.metadata?.auditDepth !== 'deep') return {};
const { getTaskById, getAgentRecord } = await import('./cos.js');
const persisted = await getTaskById(task.id).catch(err => {
@@ -941,6 +942,20 @@ export async function releaseRetryHold({ agentId, task, success, agentMetadata }
});
if (!persisted) return {};
+ if (task.metadata?.auditDepth === 'deep') {
+ if (persisted.status !== 'in_progress' || !isRetryHoldOwner(persisted.metadata, agentId)) return {};
+ const metadata = agentMetadata === undefined
+ ? (await getAgentRecord(agentId).catch(() => null))?.metadata : agentMetadata;
+ const patch = await resolveTaskResumePatch({ task, agentId, agentMetadata: metadata });
+ const result = await updateTask(task.id, { status: 'blocked', metadata: {
+ ...patch, ...clearedRetryHoldMetadata(), blockedCategory: 'deep-audit-partial',
+ blockedReason: 'Deep audit checkpoint; resume explicitly', blockedAt: new Date().toISOString(),
+ } }, task.taskType || persisted.taskType || 'user', {
+ expectedStatus: 'in_progress', expectedMetadata: { retryPendingCleanup: agentId },
+ });
+ return result?.error || result?.statusChanged ? {} : patch;
+ }
+
// Release only OUR hold, and only while the task is still held `in_progress`.
// Both halves matter: a slow cleanup from a previous attempt must not clear the
// hold the CURRENT attempt just armed (it would make the task spawnable while
diff --git a/server/services/cleanupAgentWorktree.test.js b/server/services/cleanupAgentWorktree.test.js
index 48d93eca57..266d59953b 100644
--- a/server/services/cleanupAgentWorktree.test.js
+++ b/server/services/cleanupAgentWorktree.test.js
@@ -1634,6 +1634,23 @@ describe('releaseRetryHold', () => {
getAgentRecord.mockResolvedValue({ metadata: agentMetadata });
});
+ it.each([true, false])('retains a Deep checkpoint pointer after cleanup even when success=%s, without auto-resuming', async success => {
+ const selected = { ...task(), metadata: { auditDepth: 'deep' } };
+ getTaskById.mockResolvedValue({ id: selected.id, status: 'in_progress', metadata: {
+ auditDepth: 'deep', retryPendingCleanup: 'agent-x',
+ } });
+ await releaseRetryHold({ agentId: 'agent-x', task: selected, success, agentMetadata });
+ expect(updateTask).toHaveBeenCalledWith('task-1', {
+ status: 'blocked', metadata: expect.objectContaining({ existingBranch: DEAD_BRANCH, resumedFromAgentId: 'agent-x', resumeWorktreePath: null, retryPendingCleanup: undefined, blockedCategory: 'deep-audit-partial' }),
+ }, 'user', { expectedStatus: 'in_progress', expectedMetadata: { retryPendingCleanup: 'agent-x' } });
+ updateTask.mockClear();
+ getTaskById.mockResolvedValue({ id: selected.id, status: 'in_progress', metadata: {
+ retryPendingCleanup: 'agent-new',
+ } });
+ await releaseRetryHold({ agentId: 'agent-x', task: selected, success, agentMetadata });
+ expect(updateTask).not.toHaveBeenCalled();
+ });
+
// The direct-CLI / TUI shape: neither spawn path holds the agent record, so the
// helper has to read it for the worktree fields — via the transcript-free
// `getAgentRecord`, since a long TUI run's output.txt is megabytes.
diff --git a/server/services/cosTaskStore.js b/server/services/cosTaskStore.js
index 45c58c441b..e799151e16 100644
--- a/server/services/cosTaskStore.js
+++ b/server/services/cosTaskStore.js
@@ -23,7 +23,7 @@ import { existsSync } from 'fs';
import { join } from 'path';
import { parseTasksMarkdown, groupTasksByStatus, getAutoApprovedTasks, getAwaitingApprovalTasks, generateTasksMarkdown, hasKnownPrefix, toRepresentableTask, PRIORITY_VALUES } from '../lib/taskParser.js';
import { MAX_TOTAL_SPAWNS } from '../lib/validation.js';
-import { RETRY_HOLD_KEY, RETRY_HOLD_SINCE_KEY } from '../lib/taskRetryHold.js';
+import { RETRY_HOLD_KEY, RETRY_HOLD_SINCE_KEY, isRetryHeld } from '../lib/taskRetryHold.js';
import { resolveTaskTargetBranch, shouldStripTaskTargetBranch } from '../lib/taskTargetBranch.js';
import { AGENT_PAUSED_CATEGORY, PAUSE_METADATA_KEYS, isAgentPausedTask, resolvePausedTaskResume, retirePausedAgent } from '../lib/taskPauseHold.js';
import { REQUEUED_AT_KEY } from '../lib/taskRequeue.js';
@@ -634,9 +634,9 @@ export async function addTask(taskData, taskType = 'user', { raw = false, ignore
* `expectedStatus`, when supplied, is checked under the task-file lock. A mismatch
* returns `{ statusChanged: true }` without writing or retiring pause state.
*/
-export async function updateTask(taskId, updates, taskType = 'user', { now = Date.now(), suppressDequeue = false, expectedStatus = null } = {}) {
+export async function updateTask(taskId, updates, taskType = 'user', { now = Date.now(), suppressDequeue = false, expectedStatus = null, expectedMetadata = null } = {}) {
const release = await preparePauseRelease(taskId, updates);
- const result = await writeTaskUpdate(taskId, release ? { ...updates, metadata: release.metadata } : updates, taskType, { now, suppressDequeue, expectedStatus });
+ const result = await writeTaskUpdate(taskId, release ? { ...updates, metadata: release.metadata } : updates, taskType, { now, suppressDequeue, expectedStatus, expectedMetadata });
if (release && !result?.error && !result?.statusChanged) {
await retirePausedAgent(release.agentId, taskId, resolveTaskTargetBranch(result?.metadata));
}
@@ -741,12 +741,12 @@ function mergeUpdateMetadata(existingMetadata, updates) {
return merged;
}
-async function writeTaskUpdate(taskId, updates, taskType, { now, suppressDequeue = false, expectedStatus = null }) {
- return withStateLock(() => writeTaskUpdateLocked(taskId, updates, taskType, { now, suppressDequeue, expectedStatus }));
+async function writeTaskUpdate(taskId, updates, taskType, { now, suppressDequeue = false, expectedStatus = null, expectedMetadata = null }) {
+ return withStateLock(() => writeTaskUpdateLocked(taskId, updates, taskType, { now, suppressDequeue, expectedStatus, expectedMetadata }));
}
// Caller holds withStateLock, including its status and ownership decision.
-async function writeTaskUpdateLocked(taskId, updates, taskType, { now, suppressDequeue = false, expectedStatus = null }) {
+async function writeTaskUpdateLocked(taskId, updates, taskType, { now, suppressDequeue = false, expectedStatus = null, expectedMetadata = null }) {
const state = await loadState();
const filePath = taskType === 'user'
? join(ROOT_DIR, state.config.userTasksFile)
@@ -772,6 +772,15 @@ async function writeTaskUpdateLocked(taskId, updates, taskType, { now, suppressD
return { statusChanged: true, task: tasks[taskIndex] };
}
+ const current = tasks[taskIndex];
+ if (expectedMetadata && Object.entries(expectedMetadata).some(([key, value]) => current.metadata?.[key] !== value)) {
+ return { statusChanged: true, task: current };
+ }
+
+ if (updates.status === 'pending' && current.metadata?.auditDepth === 'deep' && isRetryHeld(current.metadata)) {
+ return { error: 'Deep checkpoint cleanup is still pending; resume after cleanup finishes' };
+ }
+
const updatedMetadata = mergeUpdateMetadata(tasks[taskIndex].metadata, updates);
// Ask "what status transition is this?" ONCE. Every lifecycle rule below reads a
diff --git a/server/services/cosTaskStore.test.js b/server/services/cosTaskStore.test.js
index 991f5743e4..bc70064d40 100644
--- a/server/services/cosTaskStore.test.js
+++ b/server/services/cosTaskStore.test.js
@@ -224,6 +224,28 @@ describe('cosTaskStore.firstLine', () => {
});
describe('cosTaskStore.updateTask expectedStatus', () => {
+ it('keeps Deep checkpoints paused through cleanup, rejects stale cleanup, and resumes the retained branch explicitly', async () => {
+ await addTask({ id: 'sys-deep-cleanup', description: 'Deep audit' }, 'internal');
+ await updateTask('sys-deep-cleanup', { status: 'in_progress', metadata: {
+ auditDepth: 'deep', retryPendingCleanup: 'agent-current',
+ existingBranch: 'cos/retained', resumedFromAgentId: 'agent-current', resumeWorktreePath: '/fixture/retained',
+ } }, 'internal');
+ expect(isReapableBlockedFailure(await getTaskById('sys-deep-cleanup'))).toBe(false);
+ expect(await reviveBlockedTask('sys-deep-cleanup', {}, 'internal')).toMatchObject({ error: expect.stringContaining('cleanup') });
+ const patch = { status: 'blocked', metadata: { retryPendingCleanup: undefined, blockedCategory: 'deep-audit-partial', existingBranch: 'cos/retained' } };
+ expect(await updateTask('sys-deep-cleanup', patch, 'internal', {
+ expectedStatus: 'in_progress', expectedMetadata: { retryPendingCleanup: 'agent-old' },
+ })).toMatchObject({ statusChanged: true });
+ expect((await getTaskById('sys-deep-cleanup')).metadata.retryPendingCleanup).toBe('agent-current');
+ await updateTask('sys-deep-cleanup', patch, 'internal', {
+ expectedStatus: 'in_progress', expectedMetadata: { retryPendingCleanup: 'agent-current' },
+ });
+ const resumed = await reviveBlockedTask('sys-deep-cleanup', {}, 'internal');
+ expect(resumed).toMatchObject({ status: 'pending', metadata: {
+ existingBranch: 'cos/retained', resumedFromAgentId: 'agent-current', resumeWorktreePath: '/fixture/retained',
+ } });
+ });
+
it('does not apply a stale terminal update after a task has been claimed', async () => {
const task = await addTask({ id: 'sys-rl-cas', description: 'Resolve a PR' }, 'internal');
await updateTask(task.id, { status: 'in_progress' }, 'internal');
diff --git a/server/services/maintenanceRun.test.js b/server/services/maintenanceRun.test.js
index bd7a963dc3..1a550e3dc7 100644
--- a/server/services/maintenanceRun.test.js
+++ b/server/services/maintenanceRun.test.js
@@ -468,7 +468,13 @@ it('Deep checkpoints pause on successful exit without evidence, resume explicitl
expect(await getMaintenanceRun(run.id)).toMatchObject({ status: 'stopped', completed: {} });
await __retryMaintenanceRuns();
expect(state.invoked).toHaveLength(1);
+ state.tasks = [{ id: agent.taskId, status: 'in_progress', metadata: { auditDepth: 'deep', retryPendingCleanup: agent.id, quotaBurnMaintenanceRunId: run.id, quotaBurnStepId: run.steps[0].id } }];
await resumeMaintenanceRun(run.id);
+ expect(state.invoked).toHaveLength(1); // Explicit resume cannot outrun cleanup.
+ state.tasks[0].status = 'blocked';
+ state.tasks[0].metadata.blockedCategory = 'deep-audit-partial';
+ delete state.tasks[0].metadata.retryPendingCleanup;
+ await evaluateMaintenanceRun(run.id);
expect(state.invoked).toHaveLength(2);
// A duplicate completion from the prior attempt cannot stop the resumed run.
await __onMaintenanceAgentCompleted(agent);
diff --git a/server/services/onDemandDrain.js b/server/services/onDemandDrain.js
index c842287d7c..3c43b44e39 100644
--- a/server/services/onDemandDrain.js
+++ b/server/services/onDemandDrain.js
@@ -294,9 +294,12 @@ export async function drainOnDemandRequests(ctx, adapter) {
// Explicit user Run colliding with a failure-blocked twin (#2614):
// revive the existing task instead of silently dropping the Run and
// stranding the bound on-demand review marker.
- await reviveBlockedTask(persisted.id, { priority: task.priority, metadata: task.metadata }, 'internal', { suppressDequeue: true });
+ const stored = await reviveBlockedTask(persisted.id, { priority: task.priority, metadata: task.metadata }, 'internal', { suppressDequeue: true });
+ if (stored?.error || stored?.statusChanged) continue;
await recordDeferredPerpetualDispatch(pendingPerpetualDispatch, taskScheduleMod);
- const revived = { ...task, id: persisted.id };
+ // Deep resumes need the persisted branch pointer and original audit text,
+ // not a freshly rendered snapshot of volatile issue/PR preload data.
+ const revived = task.metadata.auditDepth === 'deep' ? stored : { ...task, id: persisted.id };
emitSpawn(revived);
emitLog('info', `🔁 On-demand ${request.taskType} revived blocked task ${persisted.id}`, { taskId: persisted.id });
}
diff --git a/server/services/onDemandDrain.test.js b/server/services/onDemandDrain.test.js
index eb4c2f169f..10a0002ea4 100644
--- a/server/services/onDemandDrain.test.js
+++ b/server/services/onDemandDrain.test.js
@@ -308,6 +308,26 @@ describe.each(ENGINES)('%s — per-project capacity defers before preparation',
});
describe.each(ENGINES)('%s — blocked-duplicate revive (#2614)', (_name, makeAdapter) => {
+ it('dispatches a Deep resume with the persisted audit text and retained-worktree pointer', async () => {
+ mocks.getOnDemandRequests.mockResolvedValue([appRequest()]);
+ mocks.prepareManagedAppImprovementTask.mockResolvedValue({ task: { id: 'fresh', description: 'New volatile preload', metadata: { app: APP.id, auditDepth: 'deep' } } });
+ mocks.addTask.mockResolvedValue({ id: 'blocked-deep', duplicate: true, status: 'blocked' });
+ const stored = { id: 'blocked-deep', status: 'pending', description: 'Original audit instructions', metadata: { auditDepth: 'deep', existingBranch: 'cos/retained', resumeWorktreePath: '/fixture/tree' } };
+ mocks.reviveBlockedTask.mockResolvedValueOnce(stored);
+ const { spawned, adapter } = makeAdapter();
+ await drainOnDemandRequests({ state: STATE }, adapter);
+ expect(spawned).toEqual([stored]);
+ });
+
+ it('does not emit a spawn when revival was refused', async () => {
+ mocks.getOnDemandRequests.mockResolvedValue([appRequest()]);
+ mocks.addTask.mockResolvedValue({ id: 'blocked-7', duplicate: true, status: 'blocked' });
+ mocks.reviveBlockedTask.mockResolvedValueOnce({ error: 'Cleanup remains active' });
+ const { spawned, adapter } = makeAdapter();
+ await drainOnDemandRequests({ state: STATE }, adapter);
+ expect(spawned).toEqual([]);
+ });
+
it('revives the blocked twin and emits it under the existing task id', async () => {
mocks.getOnDemandRequests.mockResolvedValue([appRequest()]);
mocks.addTask.mockResolvedValue({ id: 'blocked-7', duplicate: true, status: 'blocked' });