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: keep queued runs when idle review hits project capacity (#9359)
[._.]/ Adam Eivybdc83f80903b
diff --git a/server/services/cos.js b/server/services/cos.jsindex 397e943621..71d9f01b4a 100644--- a/server/services/cos.js+++ b/server/services/cos.js@@ -133,9 +133,7 @@ import { resolveAgentProviderAndModel } from './agentProviderResolution.js';// suite, and evaluateTasks for the cos route + `import * as cos`.import {evaluateTasks,- generateIdleReviewTask,queueEligibleImprovementTasks,- recordDeferredPerpetualDispatch,admitAutoApprovedSystemTasks,admitPendingUserTasks,resolveAutonomyBudget,@@ -160,12 +158,10 @@ import {clearSpawningJob} from './cosJobScheduler.js';-// Pure priority/capacity helpers for dequeueNextTask (extracted to cosDequeue.js,-// issue #2530). The per-cycle capacity tracker + idle tier-eligibility-// predicate are shared with the scheduler unit tests so they exercise the real-// guards instead of a local replica. The async tiers stay here as-// `spawnDequeuePriorityN(ctx)` helpers.-import { closeStolenIdleReviewCard, createDequeueCapacity, countRunningAgentsByLocalEndpoint, isIdleTierEligible } from './cosDequeue.js';+// 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 { buildLocalEndpointSlotContext, localEndpointCapacityError } from './cosLocalEndpointSlots.js';import {initializePersistentMindSupervisor,@@ -1132,37 +1128,23 @@ async function spawnDequeuePriority2AutoApproved(ctx) {/*** Priority 3 — idle review task, only when the daemon is completely idle this- * cycle (shared `isIdleTierEligible` predicate: nothing spawned, no pending user- * tasks, idle review on, auto-run in execute).+ * cycle. The shared owner checks eligibility and capacity before preparation,+ * then performs the committed handoff.*/async function spawnDequeuePriority3IdleReview(ctx) {- const { state, capacity, ignoreTaskId } = ctx;-- if (!isIdleTierEligible({- spawned: capacity.spawned,+ const { capacity } = ctx;+ return admitIdleReviewTask({+ state: ctx.state,+ alreadySpawned: capacity.spawned,hasPendingUserTasks: ctx.hasPendingUserTasks,- idleReviewEnabled: state.config.idleReviewEnabled,- autonomyMode: ctx.cosAutonomyMode- })) return;-- const freshCosTasks = await getCosTasks();- const pendingSystemTasks = freshCosTasks.autoApproved?.length || 0;- if (pendingSystemTasks === 0) {- const { task: idleTask, pendingPerpetualDispatch, preflightCardId } = await generateIdleReviewTask(state, { ignoreTaskId });- // Committed tier — `generateIdleReviewTask` has already bound the app-review- // marker and advanced the 30-minute cooldown, and only `holdTask` releases- // that marker, which requires the emit. A denial would leave the app reading- // "in review" indefinitely (#978's mode). See canSpawnCommitted (#4834).- const admitted = idleTask && capacity.canSpawnCommitted(idleTask, ctx.autonomousSpawnCeiling);- if (admitted) {- await recordDeferredPerpetualDispatch(pendingPerpetualDispatch, await import('./taskSchedule.js'));- cosEvents.emit('task:ready', idleTask);- capacity.trackSpawn(idleTask);- }- // This tier may have STOLEN a human's on-demand request. Closing its card is- // the tier's job because only here is the admission decision final.- await closeStolenIdleReviewCard(preflightCardId, admitted ? idleTask : null);- }+ cosAutonomyMode: ctx.cosAutonomyMode,+ autonomousSlotCeiling: ctx.autonomousSpawnCeiling,+ ignoreTaskId: ctx.ignoreTaskId,+ }, {+ canSpawn: (task, ceiling) => capacity.canSpawnCommitted(task, ceiling),+ emitSpawn: (task) => cosEvents.emit('task:ready', task),+ trackSpawn: (task) => capacity.trackSpawn(task),+ });}// Every dequeue below is scheduled from a timer/setImmediate outside the requestdiff --git a/server/services/cos.test.js b/server/services/cos.test.jsindex fa493d0ce6..ae71c3855d 100644--- a/server/services/cos.test.js+++ b/server/services/cos.test.js@@ -1585,11 +1585,12 @@ describe('cos.js source — priority + capacity invariants', () => {// — scope to the whole cosTaskGenerator module (the engine).const evalIdleTier = extractFnBody(GEN_SRC, GEN_SRC.indexOf('async function spawnPriority4IdleReview'));- expect(idleTier, 'idle tier must call the shared isIdleTierEligible predicate').toMatch(/isIdleTierEligible\(/);- expect(idleTier, 'idle tier must pass state.config.idleReviewEnabled into the predicate').toMatch(/idleReviewEnabled:\s*state\.config\.idleReviewEnabled/);+ expect(idleTier, 'dequeue idle tier must call the shared workflow').toMatch(/admitIdleReviewTask\(/);+ expect(evalIdleTier, 'evaluate idle tier must call the shared workflow').toMatch(/admitIdleReviewTask\(/);expect(idlePred, 'isIdleTierEligible must fence on spawned === 0 && idleReviewEnabled').toMatch(/spawned\s*===\s*0\s*&&\s*!!idleReviewEnabled/);- expect(evalIdleTier, 'evaluate idle tier must call the shared predicate').toMatch(/isIdleTierEligible\(/);- expect(evalIdleTier).toMatch(/spawned:\s*tasksToSpawn\.length/);+ const idleWorkflow = extractFnBody(DEQ_SRC, DEQ_SRC.indexOf('export async function admitIdleReviewTask'));+ expect(idleWorkflow).toMatch(/isIdleTierEligible\(/);+ expect(idleWorkflow).toMatch(/idleReviewEnabled:\s*state\.config\.idleReviewEnabled/);});it('CoS auto-run domain gate (#711) fences autonomous spawns in BOTH engines', () => {@@ -1617,7 +1618,7 @@ describe('cos.js source — priority + capacity invariants', () => {expect(evalFn, `evaluateTasks must fence autonomous spawns on cosAutonomyMode === 'execute'`).toMatch(/cosAutonomyMode\s*===\s*['"]execute['"]/);// Dequeue's idle tier gates through the shared predicate, and its// auto-approved tier delegates to the same pass as evaluateTasks.- expect(dequeueSrc, `dequeueNextTask must gate the idle tier via the eligibility predicate`).toMatch(/isIdleTierEligible\(/);+ expect(dequeueSrc, `dequeueNextTask must delegate idle admission to the shared workflow`).toMatch(/admitIdleReviewTask\(/);expect(dequeueP2, 'dequeue auto-approved tier must call the shared pass').toMatch(/admitAutoApprovedSystemTasks\(/);expect(GEN_SRC, 'the shared pass must withhold spawns unless mode is execute').toMatch(/cosAutonomyMode\s*!==\s*['"]execute['"]/);expect(DEQ_SRC, `cosDequeue predicates must enforce autonomyMode === 'execute'`).toMatch(/autonomyMode\s*===\s*['"]execute['"]/);diff --git a/server/services/cosDequeue.js b/server/services/cosDequeue.jsindex 2bdc88f6e7..81c7adf310 100644--- a/server/services/cosDequeue.js+++ b/server/services/cosDequeue.js@@ -8,10 +8,10 @@* tests share ONE implementation instead of the tests re-deriving a local* replica of the guards.*- * The async tiers themselves (which load schedules, generate tasks, emit- * `task:ready`, advance cooldowns) stay in cos.js as `spawnDequeuePriorityN(ctx)`- * helpers — they're integration-level and pinned by source-order regression- * tests — but every capacity/gate decision they make routes through here.+ * Idle review has one shared admission/handoff workflow here: check the+ * autonomous ceiling and project eligibility BEFORE preparation can consume a+ * 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 →@@ -61,7 +61,7 @@ import { hasActiveTaskOwner } from './agentState.js';* Emitting instead is strictly better — the authoritative cap at subAgentSpawner's* `task:ready` chokepoint HOLDS the task (still `pending`, marker released, job* reservation freed), which is exactly the outcome these tiers cannot produce.- * The global/per-project caps carry the same hazard here; that is pre-existing.+ * Idle review prechecks global/project capacity before preparation below.*/export function createDequeueCapacity(state, {agentsByProject = {},@@ -84,7 +84,9 @@ export function createDequeueCapacity(state, {let spawned = 0;const admit = (task, ceiling, gateLocalEndpoint) => {- if (hasActiveTaskOwner(task.id, state.agents)) return false;+ // App eligibility probes have no task id yet; only real tasks can have+ // an owner (a running legacy agent may also have no taskId).+ if (task.id && hasActiveTaskOwner(task.id, state.agents)) return false;if (spawned >= ceiling) return false;const project = task.metadata?.app || '_self';if ((spawnProjectCounts[project] || 0) >= perProjectLimit) return false;@@ -179,6 +181,45 @@ export async function closeStolenIdleReviewCard(cardId, admittedTask) {return finishPreflightDispatch(cardId, admittedTask?.id ?? null);}+/**+ * Shared idle-review lifecycle for the periodic and dequeue engines. Capacity+ * comes from each engine's existing tracker; the same committed admission+ * predicate filters apps before generation and admits the resulting task.+ * Local-endpoint denial remains the spawn chokepoint's durable hold/release.+ */+export async function admitIdleReviewTask({+ state,+ alreadySpawned,+ hasPendingUserTasks,+ cosAutonomyMode,+ autonomousSlotCeiling,+ ignoreTaskId = null,+}, { canSpawn, emitSpawn, trackSpawn }) {+ if (!isIdleTierEligible({+ spawned: alreadySpawned,+ hasPendingUserTasks,+ idleReviewEnabled: state.config.idleReviewEnabled,+ autonomyMode: cosAutonomyMode,+ }) || alreadySpawned >= autonomousSlotCeiling) return;++ // Deferred: the generator imports this owner, and ordinary capacity users+ // need neither the task store nor the prompt-generation dependency graph.+ const { getCosTasks } = await import('./cosTaskStore.js');+ if ((await getCosTasks()).autoApproved?.length) return;+ const { generateIdleReviewTask, recordDeferredPerpetualDispatch } = await import('./cosTaskGenerator.js');+ const { task, pendingPerpetualDispatch, preflightCardId } = await generateIdleReviewTask(state, {+ ignoreTaskId,+ isAppEligible: (app) => canSpawn({ metadata: { app: app.id } }, autonomousSlotCeiling),+ });+ const admitted = task && canSpawn(task, autonomousSlotCeiling);+ if (admitted) {+ await recordDeferredPerpetualDispatch(pendingPerpetualDispatch, await import('./taskSchedule.js'));+ emitSpawn(task);+ trackSpawn(task);+ }+ await closeStolenIdleReviewCard(preflightCardId, admitted ? task : null);+}+/*** Priority 1 (user) tier: is this pending user row runnable unattended?*diff --git a/server/services/cosIdleReviewParity.test.js b/server/services/cosIdleReviewParity.test.jsnew file mode 100644index 0000000000..fa084a9e55--- /dev/null+++ b/server/services/cosIdleReviewParity.test.js@@ -0,0 +1,274 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++const mocks = vi.hoisted(() => ({+ state: null,+ interval: null, localEndpoint: null, requestsAfterPriority0: false, requestReads: 0,+ cosTaskData: null,+ emit: vi.fn(),+ emitLog: vi.fn(),+ recordDecision: vi.fn(async () => {}),+ apps: [], requests: [], activity: {}, cards: {}, persisted: [], executions: [], perpetualDispatches: [],+ noWork: false, budget: { exceeded: null, budget: {}, usage: {} }, preflightInputs: [], hookInputs: [], userTasks: [],+}));++vi.mock('./cosEvents.js', () => ({+ cosEvents: { emit: (...args) => mocks.emit(...args), on: vi.fn(), off: vi.fn() },+ emitLog: (...args) => mocks.emitLog(...args),+}));+vi.mock('./cosState.js', async (importActual) => ({+ ...(await importActual()),+ isDaemonRunning: () => true,+ loadState: async () => mocks.state,+ saveState: async () => {},+ withStateLock: async (fn) => fn(),+}));+vi.mock('./cosTaskStore.js', async (importActual) => ({+ ...(await importActual()),+ getAllTasks: async () => ({+ user: { exists: true, grouped: { pending: mocks.userTasks, in_progress: [], blocked: [] } },+ cos: mocks.cosTaskData,+ }),+ getUserTasks: async () => ({ exists: true, grouped: { pending: mocks.userTasks } }),+ getCosTasks: async () => mocks.cosTaskData,+ addTask: async (task) => { mocks.persisted.push(task); return task; },+}));+vi.mock('./domainUsage.js', async (importActual) => ({+ ...(await importActual()),+ getDomainBudgetStatus: async () => mocks.budget,+}));+vi.mock('./instanceIdentity.js', async (importActual) => ({+ ...(await importActual()),+ ensureInstanceId: async () => 'instance-a',+}));+vi.mock('./decisionLog.js', async (importActual) => ({+ ...(await importActual()),+ recordDecision: (...args) => mocks.recordDecision(...args),+}));+vi.mock('./apps.js', async (importActual) => ({+ ...(await importActual()),+ getActiveApps: async () => mocks.apps,+ getAppTaskTypeOverrides: async () => ({}),+}));+vi.mock('./appActivity.js', async (importActual) => ({+ ...(await importActual()),+ loadAppActivity: async () => ({ apps: mocks.activity }),+ isAppOnCooldown: async (appId) => !!mocks.activity[appId]?.cooldown,+ getNextAppForReview: async (apps) => apps.find((app) => !mocks.activity[app.id]?.cooldown && !mocks.activity[app.id]?.activeAgentId) || null,+ markIdleReviewStarted: async () => {},+ markAppReviewCooldown: async (appId) => { mocks.activity[appId] = { ...mocks.activity[appId], cooldown: true }; },+ bindAppReviewAgent: async (appId, id) => { mocks.activity[appId] = { ...mocks.activity[appId], activeAgentId: id }; },+ updateAppActivity: async () => {},+}));+vi.mock('./taskSchedule.js', async (importActual) => ({+ ...(await importActual()),+ loadSchedule: async () => ({ tasks: { 'code-quality': { enabled: true } } }),+ getOnDemandRequests: async () => {+ mocks.requestReads++;+ return mocks.requestsAfterPriority0 && mocks.requestReads === 1 ? [] : [...mocks.requests];+ },+ clearOnDemandRequest: async (id) => { mocks.requests = mocks.requests.filter((r) => r.id !== id); },+ applyOnDemandRunResets: async () => true,+ recordExecution: async (type, appId) => { mocks.executions.push({ type, appId }); },+ recordPerpetualDispatch: async (...args) => { mocks.perpetualDispatches.push(args); },+ getTaskInterval: async () => mocks.interval,+ recordPerpetualStall: async () => {},+ getPerpetualDrainState: async () => ({ signature: null, dispatchCount: 0 }),+ getNextTaskType: async () => ({ taskType: 'code-quality', reason: 'scheduled' }),+}));+vi.mock('./preflightTaskCard.js', async (importActual) => ({+ ...(await importActual()),+ startPreflightCard: async ({ requestId }) => { mocks.cards[`preflight-${requestId}`] ??= { outcome: 'waiting' }; },+ reportPreflightStep: async () => {},+ preflightReporter: (cardId) => ({ cardId }),+ finishPreflightDispatch: async (cardId, taskId) => {+ if (cardId && mocks.cards[cardId]?.outcome === 'waiting') {+ mocks.cards[cardId] = { outcome: taskId ? 'handed-off' : 'nothing-to-do', taskId: taskId ?? null };+ }+ },+}));+vi.mock('./prReviewerPipeline.js', async (importActual) => ({+ ...(await importActual()),+ runPrReviewerSecurityPreflight: async (_type, _app, _metadata, target, _schedule, options) => {+ mocks.preflightInputs.push({ target, progress: options.progress });+ return { skipped: mocks.noWork };+ },+}));+vi.mock('./taskPromptService.js', () => ({ getTaskPrompt: async () => 'Review Example App', getStagePrompt: async () => 'Review Example App' }));+vi.mock('./taskTypeHooks.js', async (importActual) => ({+ ...(await importActual()),+ getTaskInputHook: async () => async (args) => { mocks.hookInputs.push(args); return { prompt: 'Review Example App' }; },+}));+vi.mock('./taskLearning.js', async (importActual) => ({+ ...(await importActual()),+ getTaskTypeConfidence: async () => ({ autoApprove: true }),+}));+vi.mock('./cosTaskPreStepBlocks.js', async (importActual) => ({+ ...(await importActual()),+ applyPerpetualDrainCap: async () => ({ skip: false }),+ buildImprovementTaskDescription: async ({ promptTemplate }) => promptTemplate,+}));+vi.mock('./perpetualWork.js', () => ({+ detectActionableWork: async () => ({ actionable: true, signature: ['example-work'], count: 1 }),+}));+vi.mock('./taskDataInputs.js', () => ({ resolveTaskDataInputs: async () => [], appendTaskDataInputs: (description) => description }));+vi.mock('./prWatcher.js', async (importActual) => ({+ ...(await importActual()),+ sweepPendingMergePrs: async () => ({ merged: 0, escalated: 0, timedOut: 0 }),+}));+vi.mock('./cosLocalEndpointSlots.js', async (importActual) => ({+ ...(await importActual()),+ buildLocalEndpointSlotContext: async () => ({+ endpointForAgent: () => mocks.localEndpoint,+ resolveLocalEndpoint: () => mocks.localEndpoint,+ limit: 1,+ }),+}));+vi.mock('./featureAgents.js', async (importActual) => ({+ ...(await importActual()),+ getDueFeatureAgents: async () => [],+}));++const { evaluateTasks } = await import('./cosTaskGenerator.js');+const { dequeueNextTask } = await import('./cos.js');++const engines = [+ ['evaluateTasks', () => evaluateTasks({ initialStartup: true })],+ ['dequeueNextTask', () => dequeueNextTask({ ignoreTaskId: 'completed-task' })],+];+const readyTasks = () => mocks.emit.mock.calls.filter(([event]) => event === 'task:ready').map(([, task]) => task);+const app = (id = 'example-app') => ({ id, name: 'Example App' });+const request = () => ({ id: 'demand-1', appId: 'example-app', taskType: 'code-quality', targetPullRequest: { number: 42, repo: 'example/repo' } });++beforeEach(() => {+ vi.clearAllMocks();+ mocks.state = {+ paused: false, agents: {}, stats: {},+ config: { maxConcurrentAgents: 2, maxConcurrentAgentsPerProject: 1, appReviewCooldownMs: 0,+ idleReviewEnabled: true, improvementEnabled: true, domainAutonomy: { cos: 'execute' } },+ };+ mocks.cosTaskData = { exists: true, autoApproved: [], awaitingApproval: [], grouped: { pending: [], blocked: [] } };+ mocks.apps = [app()];+ mocks.requests = [];+ mocks.interval = { taskMetadata: { runInapplicableAudit: true } };+ mocks.localEndpoint = null;+ mocks.requestsAfterPriority0 = false;+ mocks.requestReads = 0;+ mocks.userTasks = [];+ mocks.activity = {};+ mocks.cards = {};+ mocks.persisted = [];+ mocks.executions = [];+ mocks.perpetualDispatches = [];+ mocks.noWork = false;+ mocks.budget = { exceeded: null, budget: {}, usage: {} };+ mocks.preflightInputs = [];+ mocks.hookInputs = [];+});++describe.each(engines)('%s idle admission public boundary', (name, run) => {+ it('retains a full project Run and later dispatches it once with the original scope and card', async () => {+ const originalRequest = request();+ mocks.requests = [originalRequest];+ mocks.state.agents = { ordinary: { status: 'running', metadata: { app: 'example-app' } } };+ await run();+ expect(mocks.requests).toEqual([originalRequest]);+ expect(readyTasks()).toEqual([]);+ expect(mocks.activity).toEqual({});+ expect(mocks.executions).toEqual([]);+ expect(mocks.cards['preflight-demand-1']).toEqual({ outcome: 'waiting' });++ mocks.state.agents = {};+ await run();+ const [task] = readyTasks();+ expect(readyTasks()).toHaveLength(1);+ expect(task.metadata).toMatchObject({ app: 'example-app', analysisType: 'code-quality', onDemand: true });+ expect(mocks.preflightInputs).toEqual([{ target: originalRequest.targetPullRequest, progress: { cardId: 'preflight-demand-1' } }]);+ expect(mocks.requests).toEqual([]);+ expect(mocks.cards['preflight-demand-1']).toEqual({ outcome: 'handed-off', taskId: task.id });+ await run();+ expect(readyTasks()).toHaveLength(1);+ });++ it('selects another eligible app without consuming the full project request', async () => {+ mocks.requests = [request()];+ mocks.apps.push(app('second-app'));+ mocks.state.agents = { ordinary: { status: 'running', metadata: { app: 'example-app' } } };+ await run();+ expect(readyTasks()).toHaveLength(1);+ expect(readyTasks()[0].metadata.app).toBe('second-app');+ expect(mocks.requests).toEqual([request()]);+ expect(mocks.activity['example-app']).toBeUndefined();+ expect(mocks.executions).toEqual([{ type: 'task:code-quality', appId: 'second-app' }]);+ expect(mocks.cards['preflight-demand-1'].outcome).toBe('waiting');+ });++ it('dispatches an eligible idle task once and carries completion ignoreTaskId into preparation', async () => {+ await run();+ expect(readyTasks()).toHaveLength(1);+ expect(mocks.activity['example-app']).toMatchObject({ cooldown: true, activeAgentId: expect.stringMatching(/^idle-review-/) });+ expect(mocks.hookInputs[0].ignoreTaskId).toBe(name === 'dequeueNextTask' ? 'completed-task' : null);+ await run();+ expect(readyTasks()).toHaveLength(1);+ });++ it('keeps the no-work cooldown without binding an active review marker', async () => {+ mocks.noWork = true;+ await run();+ expect(readyTasks()).toEqual([]);+ expect(mocks.activity['example-app']).toEqual({ cooldown: true });+ await run();+ expect(mocks.executions).toHaveLength(1);+ });++ it.each(['paused', 'off', 'dry-run', 'budget', 'global-full', 'pending-user', 'pending-system'])('leaves idle preparation untouched for %s', async (gate) => {+ if (gate === 'paused') mocks.state.paused = true;+ if (gate === 'off' || gate === 'dry-run') mocks.state.config.domainAutonomy.cos = gate;+ if (gate === 'budget') mocks.budget = { exceeded: 'actions', budget: { maxActionsPerDay: 1 }, usage: { actions: 1 } };+ if (gate === 'global-full') mocks.state.agents = { a: { status: 'running' }, b: { status: 'running' } };+ if (gate === 'pending-user') mocks.userTasks = [{ id: 'user-waiting', autoApproved: false, approvalRequired: true }];+ if (gate === 'pending-system') {+ mocks.cosTaskData.autoApproved = [{ id: 'held-system', metadata: { app: 'example-app' } }];+ mocks.state.agents = { ordinary: { status: 'running', metadata: { app: 'example-app' } } };+ }+ await run();+ expect(readyTasks()).toEqual([]);+ expect(mocks.activity).toEqual({});+ expect(mocks.executions).toEqual([]);+ });++ it.each([false, true])('closes the correct stolen card after late request preparation (no-work: %s)', async (noWork) => {+ mocks.requests = [request()];+ mocks.requestsAfterPriority0 = true;+ mocks.cards['preflight-demand-1'] = { outcome: 'waiting' };+ mocks.noWork = noWork;+ mocks.interval.perpetual = true;+ await run();+ expect(mocks.requests).toEqual([]);+ expect(mocks.preflightInputs).toEqual([{ target: request().targetPullRequest, progress: { cardId: 'preflight-demand-1' } }]);+ expect(mocks.cards['preflight-demand-1']).toEqual({+ outcome: noWork ? 'nothing-to-do' : 'handed-off', taskId: readyTasks()[0]?.id ?? null,+ });+ expect(mocks.perpetualDispatches).toHaveLength(noWork ? 0 : 1);+ if (!noWork) expect(mocks.perpetualDispatches[0]).toEqual(['code-quality', 'example-app', JSON.stringify({ taskType: 'code-quality', candidates: ['example-work'] })]);+ if (noWork) expect(mocks.activity['example-app'].activeAgentId).toBeUndefined();+ });++ it('hands committed idle work to the downstream hold when the local endpoint is full', async () => {+ mocks.localEndpoint = 'http://example.invalid/inference';+ mocks.state.agents = { ordinary: { taskId: 'running-task', status: 'running', metadata: { app: 'other-app' } } };+ await run();+ // The spawn chokepoint owns the durable hold/release; discarding here+ // would strand the synthetic marker and lose the prepared task.+ expect(readyTasks()).toHaveLength(1);+ expect(readyTasks()[0].metadata.app).toBe('example-app');+ });++ it('still dispatches explicit on-demand work while paused', async () => {+ mocks.state.paused = true;+ mocks.requests = [request()];+ await run();+ expect(readyTasks()).toHaveLength(1);+ expect(mocks.requests).toEqual([]);+ expect(mocks.cards['preflight-demand-1'].outcome).toBe('handed-off');+ });+});diff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.jsindex bbdbb7a7ed..d34b0a8126 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 { closeStolenIdleReviewCard, isIdleTierEligible, isUserTaskRunnableUnattended } from './cosDequeue.js';+import { admitIdleReviewTask, isUserTaskRunnableUnattended } from './cosDequeue.js';import { resolveAgentProviderPin } from './appTaskProviderPin.js';import { getTaskTypeConfidence } from './taskLearning.js';import { classifySafetyKind, requiresSafetyApproval } from './taskLearning/safetyKind.js';@@ -1074,29 +1074,17 @@ async function spawnPriority36FeatureAgents(ctx) {* Autonomous — gated by the CoS auto-run domain.*/async function spawnPriority4IdleReview(ctx) {- const { state, hasPendingUserTasks, cosAutonomyMode, autonomousSlotCeiling, tasksToSpawn, canSpawnTask, trackSpawn } = ctx;-- if (isIdleTierEligible({- spawned: tasksToSpawn.length,- hasPendingUserTasks,- idleReviewEnabled: state.config.idleReviewEnabled,- autonomyMode: cosAutonomyMode- })) {- const freshCosTasks = await getCosTasks();- const pendingSystemTasks = freshCosTasks.autoApproved?.length || 0;- if (pendingSystemTasks === 0) {- const { task: idleTask, pendingPerpetualDispatch, preflightCardId } = await generateIdleReviewTask(state);- const admitted = idleTask && canSpawnTask(idleTask, autonomousSlotCeiling);- if (admitted) {- await recordDeferredPerpetualDispatch(pendingPerpetualDispatch, await import('./taskSchedule.js'));- tasksToSpawn.push(idleTask);- trackSpawn(idleTask);- }- // This tier may have STOLEN a human's on-demand request. Closing its card is- // the tier's job because only here is the admission decision final.- await closeStolenIdleReviewCard(preflightCardId, admitted ? idleTask : null);- }- }+ return admitIdleReviewTask({+ state: ctx.state,+ alreadySpawned: ctx.tasksToSpawn.length,+ hasPendingUserTasks: ctx.hasPendingUserTasks,+ cosAutonomyMode: ctx.cosAutonomyMode,+ autonomousSlotCeiling: ctx.autonomousSlotCeiling,+ }, {+ canSpawn: ctx.canSpawnTask,+ emitSpawn: (task) => ctx.tasksToSpawn.push(task),+ trackSpawn: ctx.trackSpawn,+ });}/**@@ -1335,16 +1323,17 @@ export async function evaluateTasks(options) {* 2. App reviews for managed apps** @param {Object} state - Current CoS state- * @returns {Object|null} Generated task or null if nothing to do+ * @param {Object} options - Completion exclusion and optional app eligibility+ * @returns {Object} Task plus deferred dispatch/card handoff, or a null task*/-export async function generateIdleReviewTask(state, { ignoreTaskId = null } = {}) {+export async function generateIdleReviewTask(state, { ignoreTaskId = null, isAppEligible = () => true } = {}) {if (!isImprovementEnabled(state)) {emitLog('debug', 'Improvement tasks are disabled');return { task: null, pendingPerpetualDispatch: null, preflightCardId: null };}- // Get all active (non-archived) managed apps (including PortOS)- const apps = await getActiveApps().catch(() => []);+ // Exclude full projects before selection commits cooldown/request state.+ const apps = (await getActiveApps().catch(() => [])).filter(isAppEligible);if (apps.length > 0) {// Find next app eligible for review (not on cooldown, oldest review first)diff --git a/server/services/cosTaskGenerator.test.js b/server/services/cosTaskGenerator.test.jsindex 4cceae4a94..4462331a99 100644--- a/server/services/cosTaskGenerator.test.js+++ b/server/services/cosTaskGenerator.test.js@@ -1725,7 +1725,7 @@ describe('ignoreTaskId reaches the in-flight-counting gates (#3179)', () => {*/describe('ignoreTaskId reaches BOTH completion-continuation generators (#3179)', () => {it('the idle-review chain threads ignoreTaskId end to end', () => {- expect(GEN_SRC).toMatch(/export async function generateIdleReviewTask\(state, \{ ignoreTaskId = null \} = \{\}\)/);+ expect(GEN_SRC).toMatch(/export async function generateIdleReviewTask\(state, \{ ignoreTaskId = null, isAppEligible = \(\) => true \} = \{\}\)/);expect(GEN_SRC).toContain('generateManagedAppImprovementTask(nextApp, state, { ignoreTaskId })');expect(GEN_SRC).toMatch(/async function generateManagedAppImprovementTask\(app, state, \{ ignoreTaskId = null \} = \{\}\)/);expect(GEN_SRC).toMatch(/prepareManagedAppImprovementTask\(nextType, app, state, \{[\s\S]*ignoreTaskId[\s\S]*\}\)/);@@ -1734,7 +1734,7 @@ describe('ignoreTaskId reaches BOTH completion-continuation generators (#3179)',it('cos.js passes the completing task id into the dequeue that follows the refill', () => {expect(COS_SRC).toContain('dequeueNextTask({ ignoreTaskId: agent?.taskId })');expect(COS_SRC).toMatch(/async function dequeueNextTask\(\{ ignoreTaskId = null \} = \{\}\)/);- expect(COS_SRC).toContain('generateIdleReviewTask(state, { ignoreTaskId })');+ expect(COS_SRC).toContain('ignoreTaskId: ctx.ignoreTaskId');});});