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
refactor: share Priority-2 CoS admission pass (#6767)
[._.]/ Adam Eivy35de7796af44
diff --git a/server/services/cos.js b/server/services/cos.jsindex 167ee51760..be256232e1 100644--- a/server/services/cos.js+++ b/server/services/cos.js@@ -20,7 +20,6 @@ import { existsSync } from 'fs';import { join } from 'path';import { getActiveProvider } from './providers.js';import { isInternalTaskId } from '../lib/taskParser.js';-import { isAutoApprovableInvestigation } from '../lib/investigationTasks.js';import { isRetryHeld, isStaleRetryHold } from '../lib/taskRetryHold.js';import { isAppOnCooldown, clearStaleActiveAgents } from './appActivity.js';// The single Priority-0 on-demand loop body, shared with the evaluateTasks@@ -38,14 +37,12 @@ import { addNotification, NOTIFICATION_TYPES } from './notifications.js';import { todayInTimezone } from '../lib/timezone.js';import { getUserTimezone } from './userTimezone.js';import { normalizeDomainAutonomy, getDomainMode } from '../lib/domainAutonomy.js';-import { normalizeDomainBudgets, remainingActionBudget } from '../lib/domainBudgets.js';+import { normalizeDomainBudgets } from '../lib/domainBudgets.js';import { mergePersistentMindCapabilities } from '../lib/persistentMindCapabilities.js';import { mergePersistentMindProfile, normalizePersistentMindProfile } from '../lib/persistentMindProfile.js';import { mergePersistentMindPrompt } from '../lib/persistentMindPrompt.js';import { mergePersistentMindPlaybook } from '../lib/persistentMindPlaybook.js';import { mergePersistentMindThinkingPresets } from '../lib/persistentMindThinkingPresets.js';-import { getDomainBudgetStatus } from './domainUsage.js';-import { pendingCosActionReservations } from './cosAdmissionReservations.js';// Dependency-free leaf holding the shared agent maps + the runner-mode flag,// read by `isRunnerHolding` below.import { useRunner } from './agentState.js';@@ -136,8 +133,8 @@ import {queueEligibleImprovementTasks,recordDeferredPerpetualDispatch,blockIfExceedsMaxSpawns,- selectDryRunAutoApproved,- isCooldownExemptTask,+ admitAutoApprovedSystemTasks,+ resolveAutonomyBudget,countRunningAgentsByProject,isWithinProjectLimit,checkStagePrecondition,@@ -1058,106 +1055,29 @@ async function spawnDequeuePriority2AutoApproved(ctx) {const { state, instanceId, capacity } = ctx;const cosTaskData = await getCosTasks();- const autoApproved = [- ...(cosTaskData.autoApproved || []),- ...(state.config.autoApproveInvestigations- ? (cosTaskData.grouped?.pending || []).filter((task) => isAutoApprovableInvestigation(task, state.config))- : [])- ];- let cosAutonomyMode = getDomainMode(state.config, 'cos');-- // Daily CoS budget (#711) — same enforcement as the periodic evaluator- // (cosTaskGenerator.evaluateTasks). This is the event-driven primary spawn- // path, so the budget MUST be applied here too. Minutes is a binary off-gate- // (a run's duration is unknown at spawn); actions cap THIS cycle's autonomous- // admissions to the remaining daily allowance (completed + in-flight runs),- // surfaced as `autonomousSpawnCeiling` below. On-demand (Priority 0) and user- // (Priority 1) tasks are already spawned above and never count against it.- const cosBudget = await getDomainBudgetStatus('cos');- let autonomousActionsRemaining = Infinity;- if (cosAutonomyMode !== 'off') {- if (cosBudget.exceeded === 'minutes') {- emitLog('info', `CoS auto-run paused — daily minutes budget reached`, { domainBudget: 'cos', exceeded: 'minutes' });- cosAutonomyMode = 'off';- } else if (cosBudget.budget?.maxActionsPerDay != null) {- const runningAutonomous = Object.values(state.agents).filter(- (a) => a.status === 'running' && a.metadata?.taskType && a.metadata.taskType !== 'user'- ).length;- autonomousActionsRemaining = remainingActionBudget(- cosBudget.budget,- cosBudget.usage,- runningAutonomous + pendingCosActionReservations()- );- if (autonomousActionsRemaining === 0) {- emitLog('info', `CoS auto-run paused — daily actions budget reached`, { domainBudget: 'cos', exceeded: 'actions' });- cosAutonomyMode = 'off';- }- }- }+ const runningAgentEntries = Object.values(state.agents).filter((agent) => agent.status === 'running');+ const { cosAutonomyMode, autonomousActionsRemaining } = await resolveAutonomyBudget(state, runningAgentEntries);const autonomousSpawnCeiling = Math.min(capacity.availableSlots, capacity.spawned + autonomousActionsRemaining);ctx.cosAutonomyMode = cosAutonomyMode;ctx.autonomousSpawnCeiling = autonomousSpawnCeiling;- // Engine-specific gate shared by execute and dry-run: improvement tasks whose- // task type was disabled after queuing are skipped.- const isDisabledAnalysisType = (task) => {- const analysisType = task.metadata?.analysisType || task.metadata?.selfImprovementType;- return Boolean(analysisType) && !ctx.taskSchedule.tasks[analysisType]?.enabled;- };-- if (cosAutonomyMode !== 'execute') {- // off/dry-run withhold the unattended spawn; dry-run logs only the tasks- // execute mode would ACTUALLY spawn — applying the same max-spawns /- // disabled-type / cooldown / per-project gates against virtual capacity —- // rather than every auto-approved task regardless of eligibility.- if (cosAutonomyMode === 'dry-run') {- const wouldSpawn = await selectDryRunAutoApproved(autoApproved, {- availableSlots: autonomousSpawnCeiling,- alreadySpawned: capacity.spawned,- perProjectLimit: capacity.perProjectLimit,- spawnProjectCounts: capacity.spawnProjectCounts,- isOnCooldown: (appId) => isAppOnCooldown(appId, state.config.appReviewCooldownMs),- cooldownExempt: isCooldownExemptTask,- extraSkip: isDisabledAnalysisType,- notRunnableHere: (task) => getSkipReason(task.metadata, instanceId) !== null- });- for (const task of wouldSpawn) {- emitLog('info', `[dry-run] CoS auto-run would spawn system task: ${task.id}`, { taskId: task.id, domainAutonomy: 'cos' });- }- }- } else {- for (const task of autoApproved) {- if (capacity.spawned >= autonomousSpawnCeiling) break;- // Pinned to another instance (#4520), or a federated peer holds a live- // lease on it (#1650) — skip it during candidate selection so it doesn't- // consume an autonomous slot the spawn guard would just reject.- const skipReason = getSkipReason(task.metadata, instanceId);- if (skipReason) {- emitLog('debug', `Skipping system task ${task.id} — ${skipReason}`, { taskId: task.id });- continue;- }- if (await blockIfExceedsMaxSpawns(task, 'internal')) continue;- // Skip improvement tasks whose type was disabled after queuing- if (isDisabledAnalysisType(task)) {- const analysisType = task.metadata?.analysisType || task.metadata?.selfImprovementType;- emitLog('info', `System task skipped — task type '${analysisType}' is disabled`, { taskId: task.id });- continue;- }- // Pipeline continuations AND perpetual drains bypass the per-app cooldown- // (see isCooldownExemptTask) — otherwise a perpetual task the refill just- // queued is skipped here until the 30-min window expires, stalling the- // manually-triggered back-to-back drain one item in.- const appId = task.metadata?.app;- if (appId && !isCooldownExemptTask(task)) {- const onCooldown = await isAppOnCooldown(appId, state.config.appReviewCooldownMs);- if (onCooldown) continue;- }- const sysTask = { ...task, taskType: 'internal' };- if (!capacity.canSpawn(sysTask, autonomousSpawnCeiling)) continue;- cosEvents.emit('task:ready', sysTask);- capacity.trackSpawn(sysTask);- }- }+ return admitAutoApprovedSystemTasks({+ state,+ cosTaskData,+ taskSchedule: ctx.taskSchedule,+ cosAutonomyMode,+ autonomousSlotCeiling: autonomousSpawnCeiling,+ alreadySpawned: capacity.spawned,+ perProjectLimit: capacity.perProjectLimit,+ spawnProjectCounts: capacity.spawnProjectCounts,+ instanceId,+ }, {+ canSpawn: (task, ceiling) => capacity.canSpawn(task, ceiling),+ trackSpawn: (task) => capacity.trackSpawn(task),+ emitSpawn: (task) => {+ cosEvents.emit('task:ready', task);+ },+ });}/**@@ -1270,7 +1190,7 @@ const scheduleDequeue = (options = {}) => setImmediate(() => {* charge the finished run twice. Only the completion continuation passes it; every* other caller runs outside that window and correctly leaves it null.*/-async function dequeueNextTask({ ignoreTaskId = null } = {}) {+export async function dequeueNextTask({ ignoreTaskId = null } = {}) {if (!isDaemonRunning()) return;// In runner mode the cos-runner app owns every agent process, so a cycle rundiff --git a/server/services/cos.test.js b/server/services/cos.test.jsindex bf6e79979b..0297fbfc16 100644--- a/server/services/cos.test.js+++ b/server/services/cos.test.js@@ -1575,12 +1575,13 @@ describe('cos.js source — priority + capacity invariants', () => {// The generator engine's tiers are decomposed into named spawnPriority*// helpers (issue #1082), so its gate lives in `spawnPriority4IdleReview`// — scope to the whole cosTaskGenerator module (the engine).- const evalFn = GEN_SRC;+ 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(idlePred, 'isIdleTierEligible must fence on spawned === 0 && idleReviewEnabled').toMatch(/spawned\s*===\s*0\s*&&\s*!!idleReviewEnabled/);- expect(evalFn).toMatch(/tasksToSpawn\.length\s*===\s*0\s*&&\s*state\.config\.idleReviewEnabled/);+ expect(evalIdleTier, 'evaluate idle tier must call the shared predicate').toMatch(/isIdleTierEligible\(/);+ expect(evalIdleTier).toMatch(/spawned:\s*tasksToSpawn\.length/);});it('CoS auto-run domain gate (#711) fences autonomous spawns in BOTH engines', () => {@@ -1593,22 +1594,24 @@ describe('cos.js source — priority + capacity invariants', () => {// and fences its mission/idle tiers through the shared eligibility predicates// (issue #2530) — both still live in the cos.js module, so scope to it.const dequeueSrc = COS_SRC;+ const dequeueP2 = extractFnBody(COS_SRC, COS_SRC.indexOf('async function spawnDequeuePriority2AutoApproved'));// evaluateTasks resolves the mode in `resolveAutonomyBudget` and fences each// autonomous tier inside its spawnPriority* helper (issue #1082) — both still// live in the cosTaskGenerator module, so scope to the whole engine source.const evalFn = GEN_SRC;- for (const [name, fnBody] of [['dequeueNextTask (cos.js)', dequeueSrc], ['evaluateTasks (cosTaskGenerator)', evalFn]]) {- expect(fnBody, `${name} must resolve the cos autonomy mode`).toMatch(/getDomainMode\(\s*state\.config\s*,\s*['"]cos['"]\s*\)/);- }+ expect(dequeueP2, 'dequeue Priority 2 must call the shared budget resolver').toMatch(/resolveAutonomyBudget\(/);+ expect(evalFn, 'evaluateTasks must call the shared budget resolver').toMatch(/resolveAutonomyBudget\(/);+ expect(GEN_SRC, 'the one budget resolver must read the CoS autonomy mode')+ .toMatch(/export async function resolveAutonomyBudget[\s\S]*getDomainMode\(state\.config, 'cos'\)/);// evaluateTasks fences autonomous spawns inline on `cosAutonomyMode === 'execute'`.expect(evalFn, `evaluateTasks must fence autonomous spawns on cosAutonomyMode === 'execute'`).toMatch(/cosAutonomyMode\s*===\s*['"]execute['"]/);- // dequeueNextTask's autonomous tiers gate through the shared predicates, which- // enforce `autonomyMode === 'execute'` in cosDequeue.js; the auto-approved tier- // withholds spawns unless the mode is execute (`cosAutonomyMode !== 'execute'`).+ // Dequeue's mission/idle tiers gate through the shared predicates, and its+ // auto-approved tier delegates to the same pass as evaluateTasks.expect(dequeueSrc, `dequeueNextTask must gate mission/idle via the eligibility predicates`).toMatch(/isMissionTierEligible\(/);expect(dequeueSrc, `dequeueNextTask must gate the idle tier via the eligibility predicate`).toMatch(/isIdleTierEligible\(/);- expect(dequeueSrc, `dequeueNextTask auto-approved tier must withhold spawns unless mode is execute`).toMatch(/cosAutonomyMode\s*!==\s*['"]execute['"]/);+ 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/cosPriority2Parity.test.js b/server/services/cosPriority2Parity.test.jsnew file mode 100644index 0000000000..b40fb67ace--- /dev/null+++ b/server/services/cosPriority2Parity.test.js@@ -0,0 +1,168 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++const mocks = vi.hoisted(() => ({+ state: null,+ cosTaskData: null,+ emit: vi.fn(),+ emitLog: vi.fn(),+ recordDecision: vi.fn(async () => {}),+}));++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: [], in_progress: [], blocked: [] } },+ cos: mocks.cosTaskData,+ }),+ getUserTasks: async () => ({ exists: true, grouped: { pending: [] } }),+ getCosTasks: async () => mocks.cosTaskData,+}));+vi.mock('./onDemandDrain.js', () => ({+ drainOnDemandRequests: async () => ({ schedule: {+ tasks: {+ enabled: { enabled: true },+ disabled: { enabled: false },+ },+ } }),+}));+vi.mock('./domainUsage.js', async (importActual) => ({+ ...(await importActual()),+ getDomainBudgetStatus: async () => ({ exceeded: null, budget: {}, usage: {} }),+}));+vi.mock('./instances.js', async (importActual) => ({+ ...(await importActual()),+ ensureInstanceId: async () => 'instance-a',+}));+vi.mock('./decisionLog.js', async (importActual) => ({+ ...(await importActual()),+ recordDecision: (...args) => mocks.recordDecision(...args),+}));+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: () => null,+ resolveLocalEndpoint: () => null,+ limit: Infinity,+ }),+}));+vi.mock('./featureAgents.js', async (importActual) => ({+ ...(await importActual()),+ getDueFeatureAgents: async () => [],+}));++const { evaluateTasks } = await import('./cosTaskGenerator.js');+const { dequeueNextTask } = await import('./cos.js');++const ordinaryTask = (id, analysisType) => ({+ id,+ status: 'pending',+ approvalRequired: false,+ metadata: { analysisType },+});++const investigationTask = () => ({+ id: 'investigation',+ description: '[Auto] Investigate agent failure: provider setup',+ status: 'pending',+ approvalRequired: true,+ metadata: { isInvestigation: true },+});++const engines = [+ ['evaluateTasks', () => evaluateTasks()],+ ['dequeueNextTask', () => dequeueNextTask()],+];++const readyIds = () => mocks.emit.mock.calls+ .filter(([event]) => event === 'task:ready')+ .map(([, task]) => task.id);++const dryRunIds = () => mocks.emitLog.mock.calls+ .filter(([, message]) => message.startsWith('[dry-run] CoS auto-run would spawn system task:'))+ .map(([, message]) => message.split(': ').at(-1));++function resetFixtures(mode = 'execute') {+ mocks.state = {+ paused: false,+ agents: {},+ stats: {},+ config: {+ maxConcurrentAgents: 4,+ maxConcurrentAgentsPerProject: 4,+ appReviewCooldownMs: 0,+ autoApproveInvestigations: true,+ proactiveMode: false,+ idleReviewEnabled: false,+ domainAutonomy: { cos: mode },+ },+ };+ mocks.cosTaskData = {+ exists: true,+ autoApproved: [],+ awaitingApproval: [],+ grouped: { pending: [], blocked: [] },+ };+}++beforeEach(() => {+ vi.clearAllMocks();+ resetFixtures();+});++describe.each(engines)('%s Priority-2 public boundary', (_name, run) => {+ it('skips an auto-approved task whose scheduled analysis type is disabled', async () => {+ mocks.cosTaskData.autoApproved = [+ ordinaryTask('disabled-task', 'disabled'),+ ordinaryTask('enabled-task', 'enabled'),+ ];++ await run();++ expect(readyIds()).toEqual(['enabled-task']);+ });++ it('admits a pending investigation when auto-approval is enabled', async () => {+ mocks.cosTaskData.grouped.pending = [investigationTask()];++ await run();++ expect(readyIds()).toEqual(['investigation']);+ });++ it('dry-run logs the same ids execute mode would emit', async () => {+ mocks.cosTaskData.autoApproved = [+ ordinaryTask('disabled-task', 'disabled'),+ ordinaryTask('enabled-task', 'enabled'),+ ];+ mocks.cosTaskData.grouped.pending = [investigationTask()];+ await run();+ const executeIds = readyIds();++ vi.clearAllMocks();+ resetFixtures('dry-run');+ mocks.cosTaskData.autoApproved = [+ ordinaryTask('disabled-task', 'disabled'),+ ordinaryTask('enabled-task', 'enabled'),+ ];+ mocks.cosTaskData.grouped.pending = [investigationTask()];+ await run();++ expect(readyIds()).toEqual([]);+ expect(dryRunIds()).toEqual(executeIds);+ });+});diff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.jsindex 438520fb95..f071b6ee4b 100644--- a/server/services/cosTaskGenerator.js+++ b/server/services/cosTaskGenerator.js@@ -32,6 +32,7 @@ import { sanitizeTaskMetadata, PIPELINE_STAGE_BEHAVIOR_FLAGS, MAX_TOTAL_SPAWNS,import { PATHS } from '../lib/fileUtils.js';import { isPlainObject } from '../lib/objects.js';import { hasQuotaBurnProvenance } from '../lib/quotaBurnOrigin.js';+import { isAutoApprovableInvestigation } from '../lib/investigationTasks.js';import { parsePlanItems, extractAllIds, findInProgressIds, pickFirstAvailable, diagnoseUnpickablePlan } from '../lib/planIds.js';import { loadState, saveState, withStateLock, isImprovementEnabled, isDaemonRunning } from './cosState.js';import { getDomainMode } from '../lib/domainAutonomy.js';@@ -47,6 +48,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 { isMissionTierEligible, isIdleTierEligible } from './cosDequeue.js';import { resolveAgentProviderPin } from './appTaskProviderPin.js';import { getTaskTypeConfidence } from './taskLearning.js';import { classifySafetyKind, requiresSafetyApproval } from './taskLearning/safetyKind.js';@@ -725,7 +727,7 @@ export async function unblockExpiredCooldowns(userTaskData, cosTaskData) {** @returns {Promise<{ cosAutonomyMode: string, autonomousActionsRemaining: number }>}*/-async function resolveAutonomyBudget(state, runningAgentEntries) {+export async function resolveAutonomyBudget(state, runningAgentEntries) {let cosAutonomyMode = getDomainMode(state.config, 'cos');// Daily CoS budget (#711). Two dimensions, handled differently so a single@@ -761,6 +763,111 @@ async function resolveAutonomyBudget(state, runningAgentEntries) {return { cosAutonomyMode, autonomousActionsRemaining };}+const analysisTypeForTask = (task) => task.metadata?.analysisType || task.metadata?.selfImprovementType;++function isDisabledAnalysisType(task, taskSchedule) {+ const analysisType = analysisTypeForTask(task);+ return Boolean(analysisType) && !taskSchedule.tasks[analysisType]?.enabled;+}++/**+ * Run the one Priority-2 admission pass shared by the periodic evaluator and+ * event-driven dequeue engine. The pass owns candidate expansion and every+ * dry-run/execute gate; adapters only decide how an admitted task is emitted+ * and how their per-cycle capacity bookkeeping is updated.+ */+export async function admitAutoApprovedSystemTasks(ctx, adapter) {+ const {+ state,+ cosTaskData,+ taskSchedule,+ cosAutonomyMode,+ autonomousSlotCeiling,+ alreadySpawned,+ perProjectLimit,+ spawnProjectCounts,+ instanceId,+ } = ctx;+ const { canSpawn, trackSpawn, emitSpawn, onDefer = async () => {} } = adapter;++ if (!cosTaskData.exists) return [];++ const autoApproved = [+ ...(cosTaskData.autoApproved || []),+ ...(state.config.autoApproveInvestigations+ ? (cosTaskData.grouped?.pending || []).filter((task) => isAutoApprovableInvestigation(task, state.config))+ : [])+ ];+ const disabledAnalysisType = (task) => isDisabledAnalysisType(task, taskSchedule);++ if (cosAutonomyMode !== 'execute') {+ if (cosAutonomyMode !== 'dry-run') return [];+ const wouldSpawn = await selectDryRunAutoApproved(autoApproved, {+ availableSlots: autonomousSlotCeiling,+ alreadySpawned,+ perProjectLimit,+ spawnProjectCounts,+ isOnCooldown: (appId) => isAppOnCooldown(appId, state.config.appReviewCooldownMs),+ cooldownExempt: isCooldownExemptTask,+ extraSkip: disabledAnalysisType,+ notRunnableHere: (task) => getSkipReason(task.metadata, instanceId) !== null+ });+ for (const task of wouldSpawn) {+ emitLog('info', `[dry-run] CoS auto-run would spawn system task: ${task.id}`, { taskId: task.id, domainAutonomy: 'cos' });+ }+ return wouldSpawn;+ }++ const admitted = [];+ let spawned = alreadySpawned;+ for (const task of autoApproved) {+ if (spawned >= autonomousSlotCeiling) break;+ const skipReason = getSkipReason(task.metadata, instanceId);+ if (skipReason) {+ emitLog('debug', `Skipping system task ${task.id} — ${skipReason}`, { taskId: task.id });+ continue;+ }+ if (await blockIfExceedsMaxSpawns(task, 'internal')) continue;+ if (disabledAnalysisType(task)) {+ emitLog('info', `System task skipped — task type '${analysisTypeForTask(task)}' is disabled`, { taskId: task.id });+ continue;+ }+ const appId = task.metadata?.app;+ if (appId && !isCooldownExemptTask(task) && (await isAppOnCooldown(appId, state.config.appReviewCooldownMs))) {+ await onDefer({ type: 'cooldown', task, appId });+ continue;+ }+ const sysTask = { ...task, taskType: 'internal' };+ if (!canSpawn(sysTask, autonomousSlotCeiling)) {+ await onDefer({ type: 'capacity', task, project: appId || '_self' });+ continue;+ }+ emitSpawn(sysTask);+ trackSpawn(sysTask);+ admitted.push(sysTask);+ spawned++;+ }+ return admitted;+}++async function recordAutoApprovedDeferral({ type, task, appId, project }, state, perProjectLimit) {+ if (type === 'cooldown') {+ emitLog('debug', `Skipping system task ${task.id} - app ${appId} on cooldown`);+ await recordDecision(+ DECISION_TYPES.COOLDOWN_ACTIVE,+ `System task ${task.id} skipped — app ${appId} on cooldown (${Math.round(state.config.appReviewCooldownMs / 60000)}min window)`,+ { taskId: task.id, appId, cooldownMs: state.config.appReviewCooldownMs }+ );+ return;+ }+ emitLog('debug', `⏳ Queued system task ${task.id} - per-project limit reached for ${project}`);+ await recordDecision(+ DECISION_TYPES.CAPACITY_FULL,+ `System task ${task.id} deferred — per-project limit (${perProjectLimit}) reached for ${project}`,+ { taskId: task.id, project, limit: perProjectLimit }+ );+}+/*** Priority 0: On-demand task requests (highest priority — user explicitly* requested these). Reads the live schedule's `onDemandRequests`, clears each@@ -771,7 +878,7 @@ async function resolveAutonomyBudget(state, runningAgentEntries) {async function spawnPriority0OnDemand(ctx) {const { state, availableSlots, tasksToSpawn, canSpawnTask, trackSpawn } = ctx;- await drainOnDemandRequests({ state }, {+ const { schedule } = await drainOnDemandRequests({ state }, {capacityExhausted: () => tasksToSpawn.length >= availableSlots,canSpawn: (task) => canSpawnTask(task),emitSpawn: (task) => {@@ -779,6 +886,7 @@ async function spawnPriority0OnDemand(ctx) {trackSpawn(task);},});+ ctx.taskSchedule = schedule;}/**@@ -825,73 +933,22 @@ async function spawnPriority1UserTasks(ctx) {*/async function spawnPriority2AutoApproved(ctx) {const { state, cosTaskData, cosAutonomyMode, autonomousSlotCeiling, perProjectLimit, spawnProjectCounts, tasksToSpawn, canSpawnTask, trackSpawn, instanceId } = ctx;-- if (tasksToSpawn.length < autonomousSlotCeiling && cosTaskData.exists && cosAutonomyMode !== 'execute') {- if (cosAutonomyMode === 'dry-run') {- // Log only the tasks execute mode would ACTUALLY spawn — applying the same- // instance-pin / peer-lease / max-spawns / cooldown / per-project gates- // against virtual capacity — rather than every auto-approved task- // regardless of eligibility.- const wouldSpawn = await selectDryRunAutoApproved(cosTaskData.autoApproved || [], {- availableSlots: autonomousSlotCeiling,- alreadySpawned: tasksToSpawn.length,- perProjectLimit,- spawnProjectCounts,- isOnCooldown: (appId) => isAppOnCooldown(appId, state.config.appReviewCooldownMs),- cooldownExempt: isCooldownExemptTask,- notRunnableHere: (task) => getSkipReason(task.metadata, instanceId) !== null- });- for (const task of wouldSpawn) {- emitLog('info', `[dry-run] CoS auto-run would spawn system task: ${task.id}`, { taskId: task.id, domainAutonomy: 'cos' });- }- }- } else if (tasksToSpawn.length < autonomousSlotCeiling && cosTaskData.exists) {- const autoApproved = cosTaskData.autoApproved || [];- for (const task of autoApproved) {- if (tasksToSpawn.length >= autonomousSlotCeiling) break;-- // Pinned to another instance (#4520), or a federated peer holds a live- // lease on it (#1650) — skip it during candidate selection so it doesn't- // consume an autonomous slot the spawn guard would just reject.- const skipReason = getSkipReason(task.metadata, instanceId);- if (skipReason) {- emitLog('debug', `Skipping system task ${task.id} — ${skipReason}`, { taskId: task.id });- continue;- }-- if (await blockIfExceedsMaxSpawns(task, 'internal')) continue;-- // Check if task's app is on cooldown (pipeline continuations AND perpetual- // drains bypass cooldown — see isCooldownExemptTask).- const appId = task.metadata?.app;- if (appId && !isCooldownExemptTask(task)) {- const onCooldown = await isAppOnCooldown(appId, state.config.appReviewCooldownMs);- if (onCooldown) {- emitLog('debug', `Skipping system task ${task.id} - app ${appId} on cooldown`);- await recordDecision(- DECISION_TYPES.COOLDOWN_ACTIVE,- `System task ${task.id} skipped — app ${appId} on cooldown (${Math.round(state.config.appReviewCooldownMs / 60000)}min window)`,- { taskId: task.id, appId, cooldownMs: state.config.appReviewCooldownMs }- );- continue;- }- }-- const sysTask = { ...task, taskType: 'internal' };- if (!canSpawnTask(sysTask, autonomousSlotCeiling)) {- const sysProject = appId || '_self';- emitLog('debug', `⏳ Queued system task ${task.id} - per-project limit reached for ${sysProject}`);- await recordDecision(- DECISION_TYPES.CAPACITY_FULL,- `System task ${task.id} deferred — per-project limit (${perProjectLimit}) reached for ${sysProject}`,- { taskId: task.id, project: sysProject, limit: perProjectLimit }- );- continue;- }- tasksToSpawn.push(sysTask);- trackSpawn(sysTask);- }- }+ return admitAutoApprovedSystemTasks({+ state,+ cosTaskData,+ taskSchedule: ctx.taskSchedule,+ cosAutonomyMode,+ autonomousSlotCeiling,+ alreadySpawned: tasksToSpawn.length,+ perProjectLimit,+ spawnProjectCounts,+ instanceId,+ }, {+ canSpawn: canSpawnTask,+ trackSpawn,+ emitSpawn: (task) => tasksToSpawn.push(task),+ onDefer: (decision) => recordAutoApprovedDeferral(decision, state, perProjectLimit),+ });}/**@@ -915,7 +972,13 @@ async function maybeQueueImprovementTasks(ctx) {async function spawnPriority3Missions(ctx) {const { state, hasPendingUserTasks, cosAutonomyMode, autonomousSlotCeiling, tasksToSpawn, canSpawnTask, trackSpawn } = ctx;- if (tasksToSpawn.length < autonomousSlotCeiling && !hasPendingUserTasks && state.config.proactiveMode && cosAutonomyMode === 'execute') {+ if (isMissionTierEligible({+ spawned: tasksToSpawn.length,+ ceiling: autonomousSlotCeiling,+ hasPendingUserTasks,+ proactiveMode: state.config.proactiveMode,+ autonomyMode: cosAutonomyMode+ })) {const missionTasks = await generateMissionTasks({ maxTasks: autonomousSlotCeiling - tasksToSpawn.length }).catch(err => {emitLog('debug', `Mission task generation failed: ${err.message}`);return [];@@ -987,7 +1050,12 @@ async function spawnPriority36FeatureAgents(ctx) {async function spawnPriority4IdleReview(ctx) {const { state, hasPendingUserTasks, cosAutonomyMode, autonomousSlotCeiling, tasksToSpawn, canSpawnTask, trackSpawn } = ctx;- if (tasksToSpawn.length === 0 && state.config.idleReviewEnabled && !hasPendingUserTasks && cosAutonomyMode === 'execute') {+ 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) {@@ -1143,6 +1211,7 @@ export async function evaluateTasks(options) {hasPendingUserTasks,canSpawnTask,trackSpawn,+ taskSchedule: null,autonomousSlotCeiling: availableSlots};diff --git a/server/services/cosTaskGenerator.test.js b/server/services/cosTaskGenerator.test.jsindex bd2b8a0ef5..0333fef056 100644--- a/server/services/cosTaskGenerator.test.js+++ b/server/services/cosTaskGenerator.test.js@@ -212,43 +212,42 @@ describe('claim reviewer resolution', () => {});// The unit tests above exercise selectDryRunAutoApproved with synthetic hooks;-// these source-level guards pin that each ENGINE wires the hook set matching-// its own execute path — so a future edit can't silently swap or drop a hook.-// Both engines now share the `isCooldownExemptTask` predicate (pipeline-// continuations AND perpetual drains bypass the cooldown), so a dry-run plan-// matches its execute path; the only remaining asymmetry is `extraSkip`-// (dequeue's disabled-analysis-type gate), which evaluateTasks does not have.-describe('dry-run hook wiring matches each engine execute path', () => {- // Isolate each engine's selectDryRunAutoApproved call site.- const callSite = (src) => {+// these source-level guards pin that both engines route through the ONE shared+// Priority-2 pass, whose dry-run hook set matches its own execute gates.+describe('dry-run hook wiring matches the shared execute path', () => {+ const callSite = () => {// Anchor on the CALL (`await selectDryRunAutoApproved(`), not the function// definition (`export async function selectDryRunAutoApproved(`).- const start = src.indexOf('await selectDryRunAutoApproved(');+ const start = GEN_SRC.indexOf('await selectDryRunAutoApproved(');expect(start, 'selectDryRunAutoApproved must be called').toBeGreaterThan(-1);- return src.slice(start, src.indexOf('});', start) + 3);+ return GEN_SRC.slice(start, GEN_SRC.indexOf('});', start) + 3);};- it('dequeueNextTask (cos.js) passes the shared cooldownExempt AND extraSkip (disabled-analysis-type)', () => {- const site = callSite(COS_SRC);- expect(site).toContain('extraSkip: isDisabledAnalysisType');+ it('the shared pass applies cooldown exemption and disabled-analysis-type gates', () => {+ const site = callSite();+ expect(site).toContain('extraSkip: disabledAnalysisType');// dequeue must exempt perpetual/pipeline tasks from cooldown in its dry-run// plan too, mirroring its execute gate — otherwise the plan over-reports a// perpetual drain as "would skip (cooldown)" that execute actually spawns.expect(site).toContain('cooldownExempt: isCooldownExemptTask');});- it('evaluateTasks (cosTaskGenerator.js) passes the shared cooldownExempt but NOT extraSkip', () => {- const site = callSite(GEN_SRC);- expect(site).toContain('cooldownExempt: isCooldownExemptTask');- expect(site).not.toContain('extraSkip');+ it('both engines delegate Priority 2 to admitAutoApprovedSystemTasks', () => {+ expect(COS_SRC.slice(COS_SRC.indexOf('async function spawnDequeuePriority2AutoApproved'), COS_SRC.indexOf('/**\n * Priority 3', COS_SRC.indexOf('async function spawnDequeuePriority2AutoApproved'))))+ .toContain('admitAutoApprovedSystemTasks(');+ expect(GEN_SRC.slice(GEN_SRC.indexOf('async function spawnPriority2AutoApproved'), GEN_SRC.indexOf('/**\n * Background:', GEN_SRC.indexOf('async function spawnPriority2AutoApproved'))))+ .toContain('admitAutoApprovedSystemTasks(');});- it('both engines gate their EXECUTE cooldown check on isCooldownExemptTask', () => {+ it('the shared EXECUTE loop gates cooldown on isCooldownExemptTask', () => {// The spawn gate (not just the dry-run planner) must consult the shared// predicate, or a perpetual task the refill queued is skipped at spawn time// until the 30-min window expires — the manually-triggered-drain stall.- expect(COS_SRC).toMatch(/if\s*\(appId\s*&&\s*!isCooldownExemptTask\(task\)\)/);- expect(GEN_SRC).toMatch(/if\s*\(appId\s*&&\s*!isCooldownExemptTask\(task\)\)/);+ const sharedPass = GEN_SRC.slice(+ GEN_SRC.indexOf('export async function admitAutoApprovedSystemTasks'),+ GEN_SRC.indexOf('async function recordAutoApprovedDeferral')+ );+ expect(sharedPass).toMatch(/appId\s*&&\s*!isCooldownExemptTask\(task\)/);});});@@ -409,19 +408,16 @@ describe('not-runnable-here skip during candidate selection (#1650, #4520)', ()expect(GEN_SRC).toContain('const instanceId = await ensureInstanceId();');});- it('both engines skip not-runnable-here tasks in their EXECUTE candidate loops', () => {- // Each engine must have the skip in BOTH the user-task and the auto-approved- // tiers — at least two execute-path skip sites per engine.+ it('both engines keep user-task skips and share the auto-approved execute skip', () => {const cosSkips = COS_SRC.match(/getSkipReason\(task\.metadata,\s*instanceId\);\n\s*if \(skipReason\)/g) || [];const genSkips = GEN_SRC.match(/getSkipReason\(task\.metadata,\s*instanceId\);\n\s*if \(skipReason\)/g) || [];- expect(cosSkips.length).toBeGreaterThanOrEqual(2);+ expect(cosSkips.length).toBeGreaterThanOrEqual(1);expect(genSkips.length).toBeGreaterThanOrEqual(2);});- it('both engines pass notRunnableHere into their dry-run plan so it matches execute', () => {+ it('the shared pass supplies notRunnableHere so both dry-run adapters match execute', () => {// Covers BOTH reasons this instance passes over a task at spawn time: a// peer's live lease (#1650) and a pin to another instance (#4520).- expect(COS_SRC).toContain('notRunnableHere: (task) => getSkipReason(task.metadata, instanceId) !== null');expect(GEN_SRC).toContain('notRunnableHere: (task) => getSkipReason(task.metadata, instanceId) !== null');});});