Skip to content

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

address review (claude): handle blocked duplicates at raw addTask producers and scope the per-app cap to improvement tasks

[._.]/ Adam Eivy84012c413ff4
diff --git a/server/services/agentCompletionCleanup.js b/server/services/agentCompletionCleanup.js
index dab76fcd49..a7cd15f81b 100644
--- a/server/services/agentCompletionCleanup.js
+++ b/server/services/agentCompletionCleanup.js
@@ -140,7 +140,28 @@ export async function handlePipelineProgression(task, agentId, success) {
}
}
- await addTask(nextTask, 'internal', { raw: true });
+ const persisted = await addTask(nextTask, 'internal', { raw: true });
+ if (persisted?.duplicate) {
+ // A stage prompt interpolates only app fields, so two runs of the same
+ // pipeline produce identical first lines — and addTask's dedup also matches
+ // blocked tasks (#2614). A stale blocked stage task from an earlier run
+ // would otherwise silently swallow this advance (nothing reaps blocked
+ // tasks), wedging every future run of the pipeline. Revive it with the
+ // fresh stage payload — the retry path is unblocking the existing task,
+ // not minting a duplicate. updateTask clears the blocked metadata on the
+ // status transition and merges in the new pipeline state.
+ if (persisted.status === 'blocked') {
+ await updateTask(persisted.id, {
+ status: 'pending',
+ priority: nextTask.priority,
+ metadata: nextTask.metadata
+ }, 'internal');
+ emitLog('info', `🔗 Pipeline ${pipeline.id} advancing to stage ${nextStageIndex} by reviving blocked task ${persisted.id}: ${nextStage.name}`, { pipelineId: pipeline.id, agentId });
+ return;
+ }
+ emitLog('warn', `⚠️ Pipeline ${pipeline.id} stage ${nextStageIndex} already queued as ${persisted.id} (${persisted.status}) — skipping duplicate advance`, { pipelineId: pipeline.id, agentId });
+ return;
+ }
emitLog('info', `🔗 Pipeline ${pipeline.id} advancing to stage ${nextStageIndex}: ${nextStage.name}`, { pipelineId: pipeline.id, agentId });
}
diff --git a/server/services/agentCompletionCleanup.test.js b/server/services/agentCompletionCleanup.test.js
index e058d054ba..9906fae4da 100644
--- a/server/services/agentCompletionCleanup.test.js
+++ b/server/services/agentCompletionCleanup.test.js
@@ -99,4 +99,28 @@ describe('handlePipelineProgression', () => {
const [nextTask] = addTask.mock.calls[0];
expect(nextTask.metadata.effort).toBe('high');
});
+
+ it('revives a blocked duplicate stage task instead of silently dropping the advance (#2614)', async () => {
+ // Stage prompts interpolate only app fields, so two runs of the same
+ // pipeline collide on the dedup scan — which now also matches blocked
+ // tasks. A stale blocked stage task from an earlier run must be revived
+ // with the fresh pipeline state, not swallow the advance.
+ addTask.mockResolvedValue({ id: 'sys-stale-stage', status: 'blocked', duplicate: true });
+ const task = { id: 't', taskType: 'user', metadata: { pipeline: runningPipeline() } };
+ await handlePipelineProgression(task, 'agent-1', true);
+ expect(updateTask).toHaveBeenCalledTimes(1);
+ const [taskId, updates, group] = updateTask.mock.calls[0];
+ expect(taskId).toBe('sys-stale-stage');
+ expect(updates.status).toBe('pending');
+ expect(updates.metadata.pipeline.currentStage).toBe(1);
+ expect(updates.metadata.pipeline.previousStageAgentId).toBe('agent-1');
+ expect(group).toBe('internal');
+ });
+
+ it('skips the advance without reviving when the duplicate stage task is still active (#2614)', async () => {
+ addTask.mockResolvedValue({ id: 'sys-live-stage', status: 'pending', duplicate: true });
+ const task = { id: 't', taskType: 'user', metadata: { pipeline: runningPipeline() } };
+ await handlePipelineProgression(task, 'agent-1', true);
+ expect(updateTask).not.toHaveBeenCalled();
+ });
});
diff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.js
index 6553728821..59cb9f9ccc 100644
--- a/server/services/cosTaskGenerator.js
+++ b/server/services/cosTaskGenerator.js
@@ -1170,15 +1170,19 @@ export async function generateIdleReviewTask(state) {
* failures (max-retries, max-spawns, provider-config, unknown, …) was
* invisible to dedup and the generator minted an identical duplicate every
* cadence tick — nothing reaps blocked tasks, so the pile grew unbounded.
- * Failure-blocked tasks (blocked with any category except `user-terminated`)
- * also count toward the per-app cap — the retry path is unblocking the
- * existing task, not creating a new one. `user-terminated` keeps its original
- * scope (per-type slot only) so an intentional kill of one type doesn't
- * freeze the whole app's improvement rotation.
+ * Failure-blocked *improvement* tasks (blocked with any category except
+ * `user-terminated`, AND an analysis type is derivable) also count toward the
+ * per-app cap — the retry path is unblocking the existing task, not creating
+ * a new one. A blocked NON-improvement task (an investigation, a review
+ * follow-up) never holds the app cap: blocked tasks are not reaped, so it
+ * would freeze the app's improvement rotation forever. `user-terminated`
+ * keeps its original scope (per-type slot only) so an intentional kill of
+ * one type doesn't freeze the whole app's rotation either.
*
- * `blockedTaskTypes` / `appsWithBlockedImprovement` mirror which entries came
- * from blocked tasks so the caller can log a visible skip reason instead of
- * silently suppressing generation.
+ * `blockedTaskTypes` / `appsWithBlockedImprovement` are Maps (key → blocking
+ * task id) mirroring which entries came from blocked tasks so the caller can
+ * log a visible, actionable skip reason instead of silently suppressing
+ * generation.
*
* `ignoreTaskId` excludes one task from every set — used by the perpetual
* drain-on-completion refill, where the just-completed task is still
@@ -1193,28 +1197,30 @@ export function buildImprovementDedupSets(existingTasks, { ignoreTaskId = null }
// where multiple improvement types pile up faster than the per-app cooldown
// can drain them.
const appsWithPendingImprovement = new Set();
- const blockedTaskTypes = new Set();
- const appsWithBlockedImprovement = new Set();
+ const blockedTaskTypes = new Map();
+ const appsWithBlockedImprovement = new Map();
for (const task of existingTasks) {
if (task.id === ignoreTaskId) continue;
const isActive = task.status === 'pending' || task.status === 'in_progress';
const isBlocked = task.status === 'blocked';
const isFailureBlocked = isBlocked && task.metadata?.blockedCategory !== 'user-terminated';
- if (isActive || isBlocked) {
- const analysisType = task.metadata?.analysisType ||
- task.metadata?.selfImprovementType ||
- task.description?.match(/\[(?:self-improvement|improvement)\]\s*(\w[\w-]*)/i)?.[1];
- const appId = task.metadata?.app;
- if (analysisType) {
- const taskKey = appId ? `app:${appId}:${analysisType}` : analysisType;
- existingTaskTypes.add(taskKey);
- if (isBlocked) blockedTaskTypes.add(taskKey);
- }
+ const analysisType = task.metadata?.analysisType ||
+ task.metadata?.selfImprovementType ||
+ task.description?.match(/\[(?:self-improvement|improvement)\]\s*(\w[\w-]*)/i)?.[1];
+ const appId = task.metadata?.app;
+ if ((isActive || isBlocked) && analysisType) {
+ const taskKey = appId ? `app:${appId}:${analysisType}` : analysisType;
+ existingTaskTypes.add(taskKey);
+ if (isBlocked && !blockedTaskTypes.has(taskKey)) blockedTaskTypes.set(taskKey, task.id);
}
- if ((isActive || isFailureBlocked) && task.metadata?.app && !isRecoveryTask(task)) {
- appsWithPendingImprovement.add(task.metadata.app);
- if (isFailureBlocked) appsWithBlockedImprovement.add(task.metadata.app);
+ // Active tasks of ANY kind with an app hold the per-app cap (pre-existing
+ // behavior — active tasks drain, so the hold is temporary). Blocked tasks
+ // hold it only when failure-blocked AND actually an improvement task —
+ // see the docstring above.
+ if ((isActive || (isFailureBlocked && analysisType)) && appId && !isRecoveryTask(task)) {
+ appsWithPendingImprovement.add(appId);
+ if (isFailureBlocked && !appsWithBlockedImprovement.has(appId)) appsWithBlockedImprovement.set(appId, task.id);
}
}
@@ -1261,7 +1267,7 @@ export async function queueEligibleImprovementTasks(state, cosTaskData, { ignore
// can run (per-project concurrency limit + cooldown after each completion).
if (appsWithPendingImprovement.has(app.id)) {
if (appsWithBlockedImprovement.has(app.id)) {
- emitLog('info', `⛔ Skipping improvement queue for ${app.name}: a failure-blocked improvement task occupies the app slot — resolve or delete it to resume`, { appId: app.id });
+ emitLog('info', `⛔ Skipping improvement queue for ${app.name}: failure-blocked improvement task ${appsWithBlockedImprovement.get(app.id)} occupies the app slot — resolve or delete it to resume`, { appId: app.id });
} else {
emitLog('debug', `App ${app.name} already has a pending improvement task — skipping queue`);
}
@@ -1310,7 +1316,7 @@ export async function queueEligibleImprovementTasks(state, cosTaskData, { ignore
const taskKey = `app:${app.id}:${nextType}`;
if (existingTaskTypes.has(taskKey)) {
if (blockedTaskTypes.has(taskKey)) {
- emitLog('info', `⛔ Skipping ${nextType} for ${app.name}: a blocked task of this type already exists — resolve or delete it to resume`, { appId: app.id });
+ emitLog('info', `⛔ Skipping ${nextType} for ${app.name}: blocked task ${blockedTaskTypes.get(taskKey)} of this type already exists — resolve or delete it to resume`, { appId: app.id });
} else {
emitLog('debug', `Improvement task ${nextType} for ${app.name} already queued`);
}
diff --git a/server/services/cosTaskGenerator.test.js b/server/services/cosTaskGenerator.test.js
index 70a0141d50..28a7666c18 100644
--- a/server/services/cosTaskGenerator.test.js
+++ b/server/services/cosTaskGenerator.test.js
@@ -586,8 +586,34 @@ describe('buildImprovementDedupSets (#2614 — failure-blocked tasks occupy thei
]);
expect(sets.existingTaskTypes.has('app:app-1:layered-intelligence')).toBe(true);
expect(sets.appsWithPendingImprovement.has('app-1')).toBe(true);
- expect(sets.blockedTaskTypes.has('app:app-1:layered-intelligence')).toBe(true);
- expect(sets.appsWithBlockedImprovement.has('app-1')).toBe(true);
+ // The blocked maps carry the occupying task id so skip logs are actionable.
+ expect(sets.blockedTaskTypes.get('app:app-1:layered-intelligence')).toBe('sys-t1');
+ expect(sets.appsWithBlockedImprovement.get('app-1')).toBe('sys-t1');
+ });
+
+ it('a failure-blocked NON-improvement task never holds the per-app cap', () => {
+ // Blocked tasks are not reaped, so a blocked investigation / review
+ // follow-up (app-tagged but no derivable analysis type) holding the cap
+ // would freeze the app's improvement rotation forever.
+ const sets = buildImprovementDedupSets([{
+ id: 'sys-inv-1',
+ status: 'blocked',
+ description: 'Investigate AI provider failure',
+ metadata: { app: 'app-1', blockedCategory: 'max-retries' }
+ }]);
+ expect(sets.appsWithPendingImprovement.size).toBe(0);
+ expect(sets.appsWithBlockedImprovement.size).toBe(0);
+ expect(sets.existingTaskTypes.size).toBe(0);
+ });
+
+ it('an ACTIVE non-improvement app task still holds the per-app cap (pre-existing behavior)', () => {
+ const sets = buildImprovementDedupSets([{
+ id: 'sys-inv-2',
+ status: 'in_progress',
+ description: 'Investigate AI provider failure',
+ metadata: { app: 'app-1' }
+ }]);
+ expect(sets.appsWithPendingImprovement.has('app-1')).toBe(true);
});
it('a blocked task with NO blockedCategory counts as failure-blocked', () => {
diff --git a/server/services/creativeDirector/agentBridge.js b/server/services/creativeDirector/agentBridge.js
index c5843d7b21..9418d27f1e 100644
--- a/server/services/creativeDirector/agentBridge.js
+++ b/server/services/creativeDirector/agentBridge.js
@@ -15,7 +15,7 @@
*/
import { randomUUID } from 'crypto';
-import { addTask, cosEvents } from '../cos.js';
+import { addTask, updateTask, cosEvents } from '../cos.js';
import { buildTreatmentPrompt, buildEvaluatePrompt, buildPlanPrompt } from '../../lib/creativeDirectorPrompts.js';
import { getToolSpecs } from '../creative/toolRegistry.js';
import { getSettings } from '../settings.js';
@@ -93,19 +93,45 @@ function buildDescription(project, kind, scene) {
}
async function persistAndEmit({ id, runId, record }, project, kind, sceneId) {
- // Record the run as `running` up-front so the Runs tab shows in-flight
- // state immediately. completionHook updates the same runId on finish.
+ // Persist FIRST and resolve the effective task before recording the run or
+ // emitting `task:ready`. CD descriptions are deterministic per project+kind,
+ // so addTask's dedup (which also matches blocked tasks, #2614) can return an
+ // existing task instead of persisting this record — emitting `task:ready`
+ // for a never-persisted record spawns a ghost agent whose task doesn't
+ // exist (every state transition then fails with "Task not found").
+ const persisted = await addTask(record, 'internal', { raw: true });
+ let effective = record;
+ if (persisted?.duplicate) {
+ if (persisted.status === 'blocked') {
+ // A CD enqueue is an explicit user re-trigger — revive the blocked
+ // duplicate with the fresh payload (updateTask clears the blocked
+ // metadata on the status transition) instead of wedging forever.
+ await updateTask(persisted.id, {
+ status: 'pending',
+ priority: record.priority,
+ metadata: record.metadata
+ }, 'internal');
+ effective = { ...record, id: persisted.id };
+ console.log(`📤 CD ${kind} task revived blocked duplicate ${persisted.id} on ${project.id}`);
+ } else {
+ // An identical CD task is already pending/in_progress — it will run and
+ // report through its own runId; don't spawn a second agent for it.
+ console.log(`⚠️ CD ${kind} task already queued as ${persisted.id} (${persisted.status}) — skipping duplicate enqueue`);
+ return persisted;
+ }
+ }
+ // Record the run as `running` so the Runs tab shows in-flight state.
+ // completionHook updates the same runId on finish.
await recordRun(project.id, {
runId,
- taskId: id,
+ taskId: effective.id,
kind,
sceneId: sceneId || null,
status: 'running',
}).catch((err) => console.log(`⚠️ CD recordRun(running) failed: ${err.message}`));
- await addTask(record, 'internal', { raw: true });
- cosEvents.emit('task:ready', record);
- console.log(`📤 CD task enqueued: ${id} (${kind}${sceneId ? ` for ${sceneId}` : ''} on ${project.id})`);
- return record;
+ cosEvents.emit('task:ready', effective);
+ console.log(`📤 CD task enqueued: ${effective.id} (${kind}${sceneId ? ` for ${sceneId}` : ''} on ${project.id})`);
+ return effective;
}
export async function enqueueTreatmentTask(project) {
diff --git a/server/services/creativeDirector/agentBridge.test.js b/server/services/creativeDirector/agentBridge.test.js
index b9218ac5ba..911585a2a2 100644
--- a/server/services/creativeDirector/agentBridge.test.js
+++ b/server/services/creativeDirector/agentBridge.test.js
@@ -2,6 +2,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';
const mocks = vi.hoisted(() => ({
addTask: vi.fn(),
+ updateTask: vi.fn(),
emit: vi.fn(),
buildTreatmentPrompt: vi.fn(),
buildEvaluatePrompt: vi.fn(),
@@ -13,6 +14,7 @@ const mocks = vi.hoisted(() => ({
vi.mock('../cos.js', () => ({
addTask: mocks.addTask,
+ updateTask: mocks.updateTask,
cosEvents: { emit: mocks.emit },
}));
vi.mock('../../lib/creativeDirectorPrompts.js', () => ({
@@ -97,3 +99,39 @@ describe('Creative Director agent bridge model assignments', () => {
});
});
});
+
+describe('persistAndEmit duplicate handling (#2614 — addTask dedup also matches blocked tasks)', () => {
+ it('revives a blocked duplicate instead of emitting task:ready for an unpersisted record', async () => {
+ // CD descriptions are deterministic per project+kind, so a re-trigger after
+ // a failure collides with the blocked twin. The enqueue must revive that
+ // task (status flip clears blocked metadata server-side) and emit
+ // task:ready with the EXISTING id — never with the never-persisted one.
+ mocks.addTask.mockResolvedValue({ id: 'sys-cd-old', status: 'blocked', duplicate: true, metadata: { blockedCategory: 'max-retries' } });
+
+ const result = await enqueueTreatmentTask(project);
+
+ expect(mocks.updateTask).toHaveBeenCalledTimes(1);
+ const [taskId, updates, group] = mocks.updateTask.mock.calls[0];
+ expect(taskId).toBe('sys-cd-old');
+ expect(updates.status).toBe('pending');
+ expect(updates.metadata.creativeDirector.projectId).toBe('cd-1');
+ expect(group).toBe('internal');
+ // task:ready and the run record both reference the revived (existing) id.
+ expect(result.id).toBe('sys-cd-old');
+ const emitted = mocks.emit.mock.calls.find(([name]) => name === 'task:ready');
+ expect(emitted[1].id).toBe('sys-cd-old');
+ expect(mocks.recordRun.mock.calls[0][1].taskId).toBe('sys-cd-old');
+ });
+
+ it('does not spawn a second agent or record a run for a pending duplicate', async () => {
+ const existing = { id: 'sys-cd-live', status: 'pending', duplicate: true };
+ mocks.addTask.mockResolvedValue(existing);
+
+ const result = await enqueueTreatmentTask(project);
+
+ expect(mocks.updateTask).not.toHaveBeenCalled();
+ expect(mocks.emit).not.toHaveBeenCalled();
+ expect(mocks.recordRun).not.toHaveBeenCalled();
+ expect(result).toBe(existing);
+ });
+});