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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: serialize deferred drain wakeups
[._.]/ Adam Eivyf6d593a0add8
diff --git a/server/services/cos.js b/server/services/cos.jsindex 6b59a43852..a01fc35b9e 100644--- a/server/services/cos.js+++ b/server/services/cos.js@@ -1023,7 +1023,7 @@ async function spawnDequeuePriority0OnDemand(ctx) {// and `agent:completed` fires before the completing task's updateTask// settles it to `completed` — so without excluding it the re-issued claim is// rejected as a duplicate of the run that just finished and the drain stalls.- const persisted = await addTask(task, 'internal', { raw: true, ignoreTaskId });+ const persisted = await addTask(task, 'internal', { raw: true, ignoreTaskId, suppressDequeue: true });if (!persisted?.duplicate) {await recordDeferredPerpetualDispatch(task, taskScheduleMod);cosEvents.emit('task:ready', task);@@ -1033,7 +1033,7 @@ async function spawnDequeuePriority0OnDemand(ctx) {// retry path is reviving the existing task, not minting a duplicate —// and without this branch the Run is a silent no-op that strands the// bound on-demand review marker.- await reviveBlockedTask(persisted.id, { priority: task.priority, metadata: task.metadata }, 'internal');+ await reviveBlockedTask(persisted.id, { priority: task.priority, metadata: task.metadata }, 'internal', { suppressDequeue: true });await recordDeferredPerpetualDispatch(task, taskScheduleMod);const revived = { ...task, id: persisted.id };cosEvents.emit('task:ready', revived);@@ -1538,7 +1538,7 @@ async function refillPerpetualForCompletedAgent(agent) {// regenerates an identical first-line per app) is rejected as a duplicate of// the completing task and the drain stalls until the next scheduler tick.const cosTaskData = await getCosTasks();- await queueEligibleImprovementTasks(state, cosTaskData, { ignoreTaskId: agent?.taskId });+ await queueEligibleImprovementTasks(state, cosTaskData, { ignoreTaskId: agent?.taskId, wakeAfterRecord: false });// NOTE: the caller (the agent:completed handler) runs dequeueNextTask AFTER// this resolves, so the freshly-queued perpetual task is on the queue before// slots are filled. Do not dequeue here — that would re-introduce the orderingdiff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.jsindex cd6048be70..3b4d548df4 100644--- a/server/services/cosTaskGenerator.js+++ b/server/services/cosTaskGenerator.js@@ -971,7 +971,7 @@ async function spawnPriority0OnDemand(ctx) {// engines must stamp it — either may drain a given request. Stamped before// addTask so the blocked-revive branch inherits it via `task.metadata`.task.metadata = { ...(task.metadata || {}), onDemand: true };- const persisted = await addTask(task, 'internal', { raw: true });+ const persisted = await addTask(task, 'internal', { raw: true, suppressDequeue: true });if (!persisted?.duplicate) {await recordDeferredPerpetualDispatch(task, taskSchedule);tasksToSpawn.push(task);@@ -981,7 +981,7 @@ async function spawnPriority0OnDemand(ctx) {// revive the existing task instead of silently dropping the Run and// stranding the bound on-demand review marker. Mirrors the sibling// dequeueNextTask on-demand engine in cos.js.- await reviveBlockedTask(persisted.id, { priority: task.priority, metadata: task.metadata }, 'internal');+ await reviveBlockedTask(persisted.id, { priority: task.priority, metadata: task.metadata }, 'internal', { suppressDequeue: true });await recordDeferredPerpetualDispatch(task, taskSchedule);const revived = { ...task, id: persisted.id };tasksToSpawn.push(revived);@@ -1570,7 +1570,7 @@ export function buildImprovementDedupSets(existingTasks, { ignoreTaskId = null }* Called during every evaluation to ensure system tasks are queued even when user tasks exist* Tasks are queued to COS-TASKS.md and will be picked up in Priority 2*/-export async function queueEligibleImprovementTasks(state, cosTaskData, { ignoreTaskId = null } = {}) {+export async function queueEligibleImprovementTasks(state, cosTaskData, { ignoreTaskId = null, wakeAfterRecord = true } = {}) {const taskSchedule = await import('./taskSchedule.js');const { getNextTaskType, recordExecution } = taskSchedule;@@ -1709,9 +1709,10 @@ export async function queueEligibleImprovementTasks(state, cosTaskData, { ignoretask.description = firstLine(task.description);}- const newTask = await addTask(task, 'internal', { raw: true, ignoreTaskId });+ const newTask = await addTask(task, 'internal', { raw: true, ignoreTaskId, suppressDequeue: true });if (newTask?.duplicate) continue;await recordDeferredPerpetualDispatch(task, taskSchedule);+ if (wakeAfterRecord) cosEvents.emit('cos:dequeue-requested');await recordExecution(`task:${nextType}`, app.id);diff --git a/server/services/cosTaskGenerator.test.js b/server/services/cosTaskGenerator.test.jsindex 9b8a854d85..235e0cf6f6 100644--- a/server/services/cosTaskGenerator.test.js+++ b/server/services/cosTaskGenerator.test.js@@ -1453,7 +1453,7 @@ describe('ignoreTaskId reaches the in-flight-counting gates (#3179)', () => {it('queueEligibleImprovementTasks passes its ignoreTaskId down to the generator', () => {// It already forwards the same id to addTask and buildImprovementDedupSets;// the generator was the one path that dropped it.- expect(GEN_SRC).toContain('generateManagedAppImprovementTaskForType(nextType, app, state, { ignoreTaskId })');+ expect(GEN_SRC).toMatch(/generateManagedAppImprovementTaskForType\(nextType, app, state, \{[\s\S]*ignoreTaskId[\s\S]*deferPerpetualDispatch: true[\s\S]*\}\)/);});it('the perpetual gate hands ignoreTaskId to the work detector', () => {@@ -1488,7 +1488,7 @@ describe('ignoreTaskId reaches BOTH completion-continuation generators (#3179)',expect(GEN_SRC).toMatch(/export async function generateIdleReviewTask\(state, \{ ignoreTaskId = null \} = \{\}\)/);expect(GEN_SRC).toContain('generateManagedAppImprovementTask(nextApp, state, { ignoreTaskId })');expect(GEN_SRC).toMatch(/async function generateManagedAppImprovementTask\(app, state, \{ ignoreTaskId = null \} = \{\}\)/);- expect(GEN_SRC).toContain('generateManagedAppImprovementTaskForType(nextType, app, state, { ignoreTaskId })');+ expect(GEN_SRC).toMatch(/generateManagedAppImprovementTaskForType\(nextType, app, state, \{[\s\S]*ignoreTaskId[\s\S]*deferPerpetualDispatch: true[\s\S]*\}\)/);});it('cos.js passes the completing task id into the dequeue that follows the refill', () => {@@ -1646,7 +1646,7 @@ describe('the drain cap has exactly one implementation, at the choke point', ()const genStart = GEN_SRC.indexOf('export async function generateManagedAppImprovementTaskForType');const body = GEN_SRC.slice(genStart, GEN_SRC.indexOf('return task;', genStart));- const spendIdx = body.search(/if \(perpetualGate\.spendDispatch\) \{\s*await taskSchedule\.recordPerpetualDispatch\(taskType, app\.id, perpetualGate\.signature \?\? null\)/);+ const spendIdx = body.search(/if \(perpetualGate\.spendDispatch\) \{[\s\S]*recordPerpetualDispatch\(taskType, app\.id, perpetualGate\.signature \?\? null\)/);expect(spendIdx, 'the choke point must spend the deferred dispatch').toBeGreaterThan(-1);// Every `return null` gate must precede it — planId is the last one.expect(body.indexOf('planMeta.skipReason')).toBeLessThan(spendIdx);diff --git a/server/services/cosTaskStore.js b/server/services/cosTaskStore.jsindex dcbda6e9ad..e4995b87f5 100644--- a/server/services/cosTaskStore.js+++ b/server/services/cosTaskStore.js@@ -630,7 +630,7 @@ export async function addTask(taskData, taskType = 'user', { raw = false, ignore* 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() } = {}) {+export async function updateTask(taskId, updates, taskType = 'user', { now = Date.now(), suppressDequeue = false } = {}) {const release = await preparePauseRelease(taskId, updates);const result = await writeTaskUpdate(taskId, release ? { ...updates, metadata: release.metadata } : updates, taskType, { now });if (release && !result?.error) {@@ -840,7 +840,9 @@ async function writeTaskUpdate(taskId, updates, taskType, { now }) {// description is enough — so a consumer that reacts to "reached completed"// (the investigation auto-retry; the voice completion line) needs the edge, not// `status === 'completed'`, which is true on every later write too.- cosEvents.emit('tasks:changed', { type: taskType, action, task: updatedTask, previousStatus });+ const change = { type: taskType, action, task: updatedTask, previousStatus };+ if (suppressDequeue) change.suppressDequeue = true;+ cosEvents.emit('tasks:changed', change);return updatedTask;});}@@ -861,7 +863,7 @@ async function writeTaskUpdate(taskId, updates, taskType, { now }) {* updateTask emits `tasks:changed` action 'unblocked', which re-runs the* dequeue, so callers don't need a separate wake signal.*/-export async function reviveBlockedTask(taskId, { priority, metadata } = {}, taskType = 'internal') {+export async function reviveBlockedTask(taskId, { priority, metadata } = {}, taskType = 'internal', { suppressDequeue = false } = {}) {return updateTask(taskId, {status: 'pending',...(priority ? { priority } : {}),@@ -877,7 +879,7 @@ export async function reviveBlockedTask(taskId, { priority, metadata } = {}, tas// every wait and would defeat the cap.worktreeBusyAttempts: undefined}- }, taskType);+ }, taskType, { suppressDequeue });}/**