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: dispatch due feature agents from the event-driven CoS dequeue and align tier numbering (#9646)
Adam Eivy80b2b5850b11
diff --git a/server/services/cos.js b/server/services/cos.jsindex c3b8a91871..3be38f76ea 100644--- a/server/services/cos.js+++ b/server/services/cos.js@@ -161,7 +161,7 @@ import {// Shared capacity and idle-review admission owner. The engines retain their// priority ordering and dispatch adapters; cosDequeue owns idle preparation's// capacity precheck and its committed handoff.-import { admitIdleReviewTask, createDequeueCapacity, countRunningAgentsByLocalEndpoint } from './cosDequeue.js';+import { admitFeatureAgentTasks, admitIdleReviewTask, createDequeueCapacity, countRunningAgentsByLocalEndpoint } from './cosDequeue.js';import { buildLocalEndpointSlotContext, localEndpointCapacityError } from './cosLocalEndpointSlots.js';import {initializePersistentMindSupervisor,@@ -1129,11 +1129,30 @@ async function spawnDequeuePriority2AutoApproved(ctx, { taskSchedule }) {}/**- * Priority 3 — idle review task, only when the daemon is completely idle this+ * Priority 3.6 — due feature agents. Same shared admission pass as+ * evaluateTasks, so an agent that comes due is dispatched by the next+ * completion/queue event instead of waiting for a batch evaluation.+ */+async function spawnDequeuePriority36FeatureAgents(ctx, { hasPendingUserTasks, cosAutonomyMode, autonomousSpawnCeiling }) {+ const { capacity } = ctx;+ return admitFeatureAgentTasks({+ spawnedCount: () => capacity.spawned,+ hasPendingUserTasks,+ cosAutonomyMode,+ autonomousSlotCeiling: autonomousSpawnCeiling,+ }, {+ canSpawn: (task, ceiling) => capacity.canSpawn(task, ceiling),+ emitSpawn: (task) => cosEvents.emit('task:ready', task),+ trackSpawn: (task) => capacity.trackSpawn(task),+ });+}++/**+ * Priority 4 — idle review task, only when the daemon is completely idle this* cycle. The shared owner checks eligibility and capacity before preparation,* then performs the committed handoff.*/-async function spawnDequeuePriority3IdleReview(ctx, { hasPendingUserTasks, cosAutonomyMode, autonomousSpawnCeiling }) {+async function spawnDequeuePriority4IdleReview(ctx, { hasPendingUserTasks, cosAutonomyMode, autonomousSpawnCeiling }) {const { capacity } = ctx;return admitIdleReviewTask({state: ctx.state,@@ -1165,11 +1184,14 @@ const scheduleDequeue = (options = {}) => setImmediate(() => {** Triggered by: agent:completed, tasks:user:added, tasks:cos:added, status:resumed* Thin orchestrator: computes per-cycle capacity, then threads a shared `ctx`- * through the four priority tiers in order (same order as evaluateTasks):+ * through the priority tiers in order (same tiers/numbering as evaluateTasks;+ * evaluateTasks' queue-regeneration step is+ * batch-only and has no event-driven counterpart):* 0. On-demand requests (bypasses pause)* 1. User tasks* 2. Auto-approved system tasks- * 3. Idle review task (if idleReviewEnabled)+ * 3.6. Due feature agents+ * 4. Idle review task (if idleReviewEnabled)* Returns silently when idle — no log noise.*//**@@ -1268,10 +1290,11 @@ export async function dequeueNextTask({ ignoreTaskId = null } = {}) {// Priority 1 spends against the global slot cap.const { hasPendingUserTasks } = await spawnDequeuePriority1UserTasks(ctx);- // Priorities 2 and 3 spend against the lower autonomous ceiling that+ // Priorities 2, 3.6 and 4 spend against the lower autonomous ceiling that// Priority 2 resolves `autonomousSpawnCeiling` from the daily budget.const { cosAutonomyMode, autonomousSpawnCeiling } = await spawnDequeuePriority2AutoApproved(ctx, { taskSchedule });- await spawnDequeuePriority3IdleReview(ctx, { hasPendingUserTasks, cosAutonomyMode, autonomousSpawnCeiling });+ await spawnDequeuePriority36FeatureAgents(ctx, { hasPendingUserTasks, cosAutonomyMode, autonomousSpawnCeiling });+ await spawnDequeuePriority4IdleReview(ctx, { hasPendingUserTasks, cosAutonomyMode, autonomousSpawnCeiling });if (capacity.spawned > 0) {const ids = capacity.spawnedTaskIds.join(', ');diff --git a/server/services/cos.test.js b/server/services/cos.test.jsindex 1dc8b30d91..da122121c4 100644--- a/server/services/cos.test.js+++ b/server/services/cos.test.js@@ -3,7 +3,8 @@* agent spawn but have no full-function test sibling:** 1. `evaluateTasks` priority ordering — Priority 0 (on-demand) > Priority 1- * (user) > Priority 2 (auto-approved system) > Priority 3 (idle review).+ * (user) > Priority 2 (auto-approved system) > Priority 3.6 (feature agents) >+ * Priority 4 (idle review).* Within a priority bucket tasks are taken in the order they appear in* TASKS.md (the parser sorts nothing for the pending slice — file order is* the tie-breaker).@@ -1360,18 +1361,21 @@ describe('cos.js source — priority + capacity invariants', () => {// Priority 0 (onDemand) — spawnDequeuePriority0OnDemand(ctx)// Priority 1 (user) — spawnDequeuePriority1UserTasks(ctx)// Priority 2 (autoSystem) — spawnDequeuePriority2AutoApproved(ctx, { taskSchedule })- // Priority 3 (idle) — spawnDequeuePriority3IdleReview(ctx, { ... })+ // Priority 3.6 (features) — spawnDequeuePriority36FeatureAgents(ctx, { ... })+ // Priority 4 (idle) — spawnDequeuePriority4IdleReview(ctx, { ... })const fnBody = extractFnBody(COS_SRC, COS_SRC.indexOf('async function dequeueNextTask'));const onDemandIdx = fnBody.indexOf('spawnDequeuePriority0OnDemand(ctx)');const userIdx = fnBody.indexOf('spawnDequeuePriority1UserTasks(ctx)');const autoSysIdx = fnBody.indexOf('spawnDequeuePriority2AutoApproved(ctx, { taskSchedule })');- const idleIdx = fnBody.indexOf('spawnDequeuePriority3IdleReview(ctx, {');+ const featureIdx = fnBody.indexOf('spawnDequeuePriority36FeatureAgents(ctx, {');+ const idleIdx = fnBody.indexOf('spawnDequeuePriority4IdleReview(ctx, {');expect(onDemandIdx, 'spawnDequeuePriority0OnDemand must be invoked').toBeGreaterThan(-1);expect(userIdx, 'spawnDequeuePriority1UserTasks must run after on-demand').toBeGreaterThan(onDemandIdx);expect(autoSysIdx, 'spawnDequeuePriority2AutoApproved must run after user tasks').toBeGreaterThan(userIdx);- expect(idleIdx, 'spawnDequeuePriority3IdleReview must run after auto-approved').toBeGreaterThan(autoSysIdx);+ expect(featureIdx, 'spawnDequeuePriority36FeatureAgents must run after auto-approved').toBeGreaterThan(autoSysIdx);+ expect(idleIdx, 'spawnDequeuePriority4IdleReview must run after feature agents').toBeGreaterThan(featureIdx);});it('evaluateTasks orchestrates the spawnPriority* tiers in priority order', () => {@@ -1562,7 +1566,7 @@ describe('cos.js source — priority + capacity invariants', () => {// bound. They emit and let the chokepoint hold.// Priorities 1 and 2 read from persisted queues, so skipping there is a// genuine defer — they keep the cap.- for (const tier of ['spawnDequeuePriority0OnDemand', 'spawnDequeuePriority3IdleReview']) {+ for (const tier of ['spawnDequeuePriority0OnDemand', 'spawnDequeuePriority4IdleReview']) {const body = extractFnBody(COS_SRC, COS_SRC.indexOf(`async function ${tier}`));expect(body, `${tier} must admit via canSpawnCommitted`).toMatch(/canSpawnCommitted\(/);}@@ -1575,10 +1579,10 @@ describe('cos.js source — priority + capacity invariants', () => {it('idle generator is fenced by spawned===0 / tasksToSpawn.length===0', () => {// Pin the strict-idle gate. If a refactor drops either fence, idle could// spawn alongside autoSystem and double-load the agent pool.- // dequeueNextTask's idle tier (spawnDequeuePriority3IdleReview) now routes+ // dequeueNextTask's idle tier (spawnDequeuePriority4IdleReview) now routes// through the shared `isIdleTierEligible` predicate in cosDequeue.js// (issue #2530), whose body carries the `spawned === 0` fence.- const idleTier = extractFnBody(COS_SRC, COS_SRC.indexOf('async function spawnDequeuePriority3IdleReview'));+ const idleTier = extractFnBody(COS_SRC, COS_SRC.indexOf('async function spawnDequeuePriority4IdleReview'));const idlePred = extractFnBody(DEQ_SRC, DEQ_SRC.indexOf('export function isIdleTierEligible'));// The generator engine's tiers are decomposed into named spawnPriority*// helpers (issue #1082), so its gate lives in `spawnPriority4IdleReview`diff --git a/server/services/cosDequeue.js b/server/services/cosDequeue.jsindex 81c7adf310..f183602315 100644--- a/server/services/cosDequeue.js+++ b/server/services/cosDequeue.js@@ -13,12 +13,16 @@* human request or commit cooldown/marker state. The two engines retain only* their trigger ordering and dispatch adapters.*- * Priority-tier order (pinned by the source-order regression test in- * cos.test.js): 0 on-demand (bypasses pause) → 1 user → 2 auto-approved →- * 3 idle review.+ * Priority-tier order, shared by BOTH engines (`dequeueNextTask` in cos.js and+ * `evaluateTasks` in cosTaskGenerator.js; pinned by the source-order regression+ * tests in cos.test.js): 0 on-demand (bypasses pause) → 1 user → 2 auto-approved+ * → 3.6 feature agents → 4 idle review. The evaluator additionally runs `maybeQueueImprovementTasks` between 2 and+ * 3.6, which only WRITES queue rows (batch regeneration) and never spawns, so the+ * event-driven dequeue deliberately has no counterpart.*/import { hasActiveTaskOwner } from './agentState.js';+import { emitLog } from './cosEvents.js';/*** Per-cycle spawn-capacity tracker. Owns the running `spawned` count and the@@ -151,7 +155,45 @@ export function countRunningAgentsByLocalEndpoint(agents, endpointForAgent) {}/**- * Priority 3 (idle-review) tier eligibility. The idle task only fires when the+ * Priority 3.6 (feature agents) tier. Shared by both spawn engines: due feature+ * agents are autonomous work, so they yield to pending user tasks, need CoS+ * auto-run in `execute`, and spend only the autonomous ceiling. Each admitted+ * agent is marked as holding a pending task so a second cycle cannot re-spawn it.+ *+ * Priority 3.5 (autonomous jobs) has no inline tier: those are handled by+ * registerJobSchedules(), which sets up one-shot timers per job via+ * executeScheduledJob(). Spawning them here as well caused duplicate agent spawns+ * on startup when both paths fired for the same past-due job.+ *+ * `spawnedCount()` reads the engine's live spawn total (it grows as agents are+ * admitted); `canSpawn`/`emitSpawn`/`trackSpawn` are the engine's own hooks.+ */+export async function admitFeatureAgentTasks({+ spawnedCount,+ hasPendingUserTasks,+ cosAutonomyMode,+ autonomousSlotCeiling,+}, { canSpawn, emitSpawn, trackSpawn }) {+ if (spawnedCount() >= autonomousSlotCeiling || hasPendingUserTasks || cosAutonomyMode !== 'execute') return;++ const { getDueFeatureAgents, generateTaskFromFeatureAgent, setCurrentAgent } = await import('./featureAgents.js');+ const dueAgents = await getDueFeatureAgents().catch(err => {+ emitLog('debug', `Feature agents check failed: ${err.message}`);+ return [];+ });+ for (const fa of dueAgents) {+ if (spawnedCount() >= autonomousSlotCeiling) break;+ const task = generateTaskFromFeatureAgent(fa);+ if (!canSpawn(task, autonomousSlotCeiling)) continue;+ emitSpawn(task);+ trackSpawn(task);+ await setCurrentAgent(fa.id, task.id).catch(() => {});+ emitLog('info', `Feature agent due: ${fa.name}`, { featureAgentId: fa.id });+ }+}++/**+ * Priority 4 (idle-review) tier eligibility. The idle task only fires when the* daemon is COMPLETELY idle this cycle — nothing else spawned (`spawned === 0`),* no pending user tasks, idle review enabled, and CoS auto-run in `execute`.* The `spawned === 0` fence is stricter than the auto-approved tier's `< ceiling`diff --git a/server/services/cosIdleReviewParity.test.js b/server/services/cosIdleReviewParity.test.jsindex 1fddf8c642..c6d7dbe98f 100644--- a/server/services/cosIdleReviewParity.test.js+++ b/server/services/cosIdleReviewParity.test.js@@ -1,6 +1,7 @@import { beforeEach, describe, expect, it, vi } from 'vitest';const mocks = vi.hoisted(() => ({+ dueFeatureAgents: [], featureAgentPending: [],state: null,interval: null, localEndpoint: null, requestsAfterPriority0: false, requestReads: 0,cosTaskData: null,@@ -129,7 +130,8 @@ vi.mock('./cosLocalEndpointSlots.js', async (importActual) => ({}));vi.mock('./featureAgents.js', async (importActual) => ({...(await importActual()),- getDueFeatureAgents: async () => [],+ getDueFeatureAgents: async () => [...mocks.dueFeatureAgents],+ setCurrentAgent: async (...args) => { mocks.featureAgentPending.push(args); },}));const { evaluateTasks } = await import('./cosTaskGenerator.js');diff --git a/server/services/cosPriority2Parity.test.js b/server/services/cosPriority2Parity.test.jsindex c27bb814a0..3620739881 100644--- a/server/services/cosPriority2Parity.test.js+++ b/server/services/cosPriority2Parity.test.js@@ -1,6 +1,7 @@import { beforeEach, describe, expect, it, vi } from 'vitest';const mocks = vi.hoisted(() => ({+ dueFeatureAgents: [], featureAgentPending: [], userPending: [],state: null,cosTaskData: null,emit: vi.fn(),@@ -23,10 +24,10 @@ vi.mock('./cosState.js', async (importActual) => ({vi.mock('./cosTaskStore.js', async (importActual) => ({...(await importActual()),getAllTasks: async () => ({- user: { exists: true, grouped: { pending: [], in_progress: [], blocked: [] } },+ user: { exists: true, grouped: { pending: mocks.userPending, in_progress: [], blocked: [] } },cos: mocks.cosTaskData,}),- getUserTasks: async () => ({ exists: true, grouped: { pending: [] } }),+ getUserTasks: async () => ({ exists: true, grouped: { pending: mocks.userPending } }),getCosTasks: async () => mocks.cosTaskData,}));vi.mock('./onDemandDrain.js', () => ({@@ -67,7 +68,8 @@ vi.mock('./cosLocalEndpointSlots.js', async (importActual) => ({}));vi.mock('./featureAgents.js', async (importActual) => ({...(await importActual()),- getDueFeatureAgents: async () => [],+ getDueFeatureAgents: async () => [...mocks.dueFeatureAgents],+ setCurrentAgent: async (...args) => { mocks.featureAgentPending.push(args); },}));const { evaluateTasks } = await import('./cosTaskGenerator.js');@@ -122,6 +124,9 @@ function resetFixtures(mode = 'execute') {grouped: { pending: [], blocked: [] },};mocks.cooldownAppId = null;+ mocks.dueFeatureAgents = [];+ mocks.featureAgentPending = [];+ mocks.userPending = [];}beforeEach(() => {@@ -172,6 +177,49 @@ describe.each(engines)('%s Priority-2 public boundary', (_name, run) => {});});+const dueAgent = (id) => ({ id, name: `Agent ${id}`, description: 'example', appId: `app-${id}` });+const featureAgentIds = () => readyIds().filter(id => id.startsWith('fa-run-'));++describe.each(engines)('%s Priority-3.6 feature-agent tier', (_name, run) => {+ it('spawns a due feature agent and marks it pending so the next cycle skips it', async () => {+ mocks.dueFeatureAgents = [dueAgent('a')];++ await run();++ expect(featureAgentIds()).toHaveLength(1);+ expect(mocks.featureAgentPending).toEqual([['a', featureAgentIds()[0]]]);+ });++ it('runs after the auto-approved tier and stops at the free slots', async () => {+ mocks.state.config.maxConcurrentAgents = 2;+ mocks.state.config.maxConcurrentAgentsPerProject = 2;+ mocks.cosTaskData.autoApproved = [ordinaryTask('enabled-task', 'enabled')];+ mocks.dueFeatureAgents = [dueAgent('a'), dueAgent('b')];++ await run();++ const ids = readyIds();+ expect(ids[0]).toBe('enabled-task');+ expect(ids).toHaveLength(2);+ expect(featureAgentIds()).toHaveLength(1);+ expect(mocks.featureAgentPending).toHaveLength(1);+ });++ it.each(['pending-user', 'dry-run', 'off'])('does not spawn a due agent for %s', async (gate) => {+ mocks.dueFeatureAgents = [dueAgent('a')];+ if (gate === 'pending-user') {+ mocks.userPending = [{ id: 'user-waiting', status: 'pending', approvalRequired: true }];+ } else {+ mocks.state.config.domainAutonomy.cos = gate;+ }++ await run();++ expect(featureAgentIds()).toEqual([]);+ expect(mocks.featureAgentPending).toEqual([]);+ });+});+it('keeps cooldown decision logging in the evaluate adapter only', async () => {const blockedTask = { ...ordinaryTask('cooldown-task', 'enabled'), metadata: { analysisType: 'enabled', app: 'app-a' } };mocks.cooldownAppId = 'app-a';diff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.jsindex 094fb795ea..e665dd7daa 100644--- a/server/services/cosTaskGenerator.js+++ b/server/services/cosTaskGenerator.js@@ -52,7 +52,7 @@ import { getActiveApps, getAppTaskTypeOverrides } from './apps.js';// The single Priority-0 on-demand loop body, shared with the dequeueNextTask// engine in cos.js so the two can no longer drift (#6618).import { drainOnDemandRequests } from './onDemandDrain.js';-import { admitIdleReviewTask, isUserTaskRunnableUnattended } from './cosDequeue.js';+import { admitFeatureAgentTasks, admitIdleReviewTask, isUserTaskRunnableUnattended } from './cosDequeue.js';import { resolveAgentProviderPin } from './appTaskProviderPin.js';import { getTaskTypeConfidence } from './taskLearning.js';import { classifySafetyKind, requiresSafetyApproval } from './taskLearning/safetyKind.js';@@ -1087,33 +1087,15 @@ async function maybeQueueImprovementTasks(ctx) {/*** Priority 3.6: Feature Agents (after autonomous jobs, yield to user tasks).* Autonomous — gated by the CoS auto-run domain and capped by- * `autonomousSlotCeiling`.- *- * Priority 3.5 (autonomous jobs) has no inline tier: those are handled by- * registerJobSchedules(), which sets up individual one-shot timers per job via- * executeScheduledJob(). It used to also check getDueJobs() and spawn here,- * which caused duplicate agent spawns on startup when both paths fired for the- * same past-due job within seconds of each other.+ * `autonomousSlotCeiling`. The admission pass is shared with dequeueNextTask.*/async function spawnPriority36FeatureAgents(ctx, { autonomousSlotCeiling }) {- const { hasPendingUserTasks, cosAutonomyMode, tasksToSpawn, spawnAdapter } = ctx;-- if (tasksToSpawn.length < autonomousSlotCeiling && !hasPendingUserTasks && cosAutonomyMode === 'execute') {- const { getDueFeatureAgents, generateTaskFromFeatureAgent, setCurrentAgent } = await import('./featureAgents.js');- const dueAgents = await getDueFeatureAgents().catch(err => {- emitLog('debug', `Feature agents check failed: ${err.message}`);- return [];- });- for (const fa of dueAgents) {- if (tasksToSpawn.length >= autonomousSlotCeiling) break;- const task = generateTaskFromFeatureAgent(fa);- if (!spawnAdapter.canSpawn(task, autonomousSlotCeiling)) continue;- spawnAdapter.emitSpawn(task);- // Mark agent as having a pending task to prevent duplicate spawns- await setCurrentAgent(fa.id, task.id).catch(() => {});- emitLog('info', `Feature agent due: ${fa.name}`, { featureAgentId: fa.id });- }- }+ return admitFeatureAgentTasks({+ spawnedCount: () => ctx.tasksToSpawn.length,+ hasPendingUserTasks: ctx.hasPendingUserTasks,+ cosAutonomyMode: ctx.cosAutonomyMode,+ autonomousSlotCeiling,+ }, ctx.spawnAdapter);}/**