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
remove the CoS missions subsystem — no production path ever created one (#6826)
[._.]/ Adam Eivyf8ffa7dcb8d3
diff --git a/client/src/components/cos/tabs/ConfigTab.jsx b/client/src/components/cos/tabs/ConfigTab.jsxindex 4190324c29..defe035291 100644--- a/client/src/components/cos/tabs/ConfigTab.jsx+++ b/client/src/components/cos/tabs/ConfigTab.jsx@@ -61,7 +61,6 @@ const getDefaultFormData = (config, avatarStyle) => ({maxTotalProcesses: config?.maxTotalProcesses ?? 50,startOnBoot: Boolean(config?.alwaysOn || config?.autoStart),improvementEnabled: config?.improvementEnabled ?? config?.selfImprovementEnabled ?? true,- proactiveMode: config?.proactiveMode ?? true,idleReviewEnabled: config?.idleReviewEnabled ?? true,idleReviewPriority: config?.idleReviewPriority ?? 'MEDIUM',autonomousJobsEnabled: config?.autonomousJobsEnabled ?? true,@@ -82,7 +81,6 @@ const configPayload = (formData) => ({// server's `alwaysOn || autoStart` compatibility read.autoStart: false,improvementEnabled: formData.improvementEnabled,- proactiveMode: formData.proactiveMode,idleReviewEnabled: formData.idleReviewEnabled,idleReviewPriority: formData.idleReviewPriority,autonomousJobsEnabled: formData.autonomousJobsEnabled,@@ -452,7 +450,6 @@ export default function ConfigTab({ config, onUpdate, onEvaluate, avatarStyle, r</div><div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-3"><ConfigRow label="Improvement tasks" description="Allow improvement work for PortOS and managed apps." value={formData.improvementEnabled ? 'Enabled' : 'Disabled'} editing={editing} type="checkbox" inputValue={formData.improvementEnabled} onChange={(value) => setFormData((current) => ({ ...current, improvementEnabled: value }))} />- <ConfigRow label="Proactive discovery" description="Create tasks from mission goals when capacity is available." value={formData.proactiveMode ? 'Enabled' : 'Disabled'} editing={editing} type="checkbox" inputValue={formData.proactiveMode} onChange={(value) => setFormData((current) => ({ ...current, proactiveMode: value }))} /><ConfigRow label="Idle app review" description="Look for app improvements when user work is idle." value={formData.idleReviewEnabled ? 'Enabled' : 'Disabled'} editing={editing} type="checkbox" inputValue={formData.idleReviewEnabled} onChange={(value) => setFormData((current) => ({ ...current, idleReviewEnabled: value }))} /><ConfigRow label="Idle review priority" description="Priority assigned to newly generated idle-review tasks." value={PRIORITY_OPTIONS.find((option) => option.value === formData.idleReviewPriority)?.label} editing={editing} type="select" inputValue={formData.idleReviewPriority} options={PRIORITY_OPTIONS} onChange={(value) => setFormData((current) => ({ ...current, idleReviewPriority: value }))} /><ConfigRow label="Scheduled agent jobs" description="Enable the global scheduler in addition to each job's own switch." value={formData.autonomousJobsEnabled ? 'Enabled' : 'Disabled'} editing={editing} type="checkbox" inputValue={formData.autonomousJobsEnabled} onChange={(value) => setFormData((current) => ({ ...current, autonomousJobsEnabled: value }))} />diff --git a/client/src/components/cos/tabs/ConfigTab.test.jsx b/client/src/components/cos/tabs/ConfigTab.test.jsxindex 82db9c10a5..68ffa35d92 100644--- a/client/src/components/cos/tabs/ConfigTab.test.jsx+++ b/client/src/components/cos/tabs/ConfigTab.test.jsx@@ -47,7 +47,6 @@ const config = {alwaysOn: false,autoStart: false,improvementEnabled: true,- proactiveMode: true,idleReviewEnabled: true,};diff --git a/client/src/pages/ChiefOfStaff.test.jsx b/client/src/pages/ChiefOfStaff.test.jsxindex 17f2c39cf9..bb09f06e7f 100644--- a/client/src/pages/ChiefOfStaff.test.jsx+++ b/client/src/pages/ChiefOfStaff.test.jsx@@ -85,7 +85,6 @@ const config = {maxProcessMemoryMb: 2048,autoStart: false,improvementEnabled: true,- proactiveMode: true,idleReviewEnabled: true,};diff --git a/docs/features/chief-of-staff.md b/docs/features/chief-of-staff.mdindex d0ffda4680..4886291fc6 100644--- a/docs/features/chief-of-staff.md+++ b/docs/features/chief-of-staff.md@@ -83,7 +83,6 @@ The `selectModelForTask` function routes tasks to appropriate model tiers:| maxTotalProcesses | 50 | Process-count alert threshold || alwaysOn | false | Start on server boot (`autoStart` is a legacy compatibility alias). Off by default so a never-configured install does not begin autonomous LLM-backed work on its own || improvementEnabled | true | Allow improvement work for PortOS and managed apps |-| proactiveMode | true | Always find work when idle || idleReviewEnabled | true | Review managed apps while user work is idle || autonomousJobsEnabled | true | Enable the global scheduled-agent-job runner || domainAutonomy | execute per domain | Off, dry-run, or execute policy for each automatic-work domain |diff --git a/docs/features/cos-enhancement.md b/docs/features/cos-enhancement.mdindex 9329d3475c..cbbb908bf1 100644--- a/docs/features/cos-enhancement.md+++ b/docs/features/cos-enhancement.md@@ -19,7 +19,7 @@ Comprehensive upgrade from reactive task executor to proactive autonomous agent| `server/services/agentRunCache.js` | Agent output caching with TTL (not built) || `server/services/eventScheduler.js` | Cron-based event scheduling || `server/services/executionLanes.js` | Concurrent execution lane management |-| `server/services/missions.js` | Long-term goal and mission management |+| `server/services/missions.js` | Long-term goal and mission management (removed, #6826 — nothing in production ever created a mission; superseded by the Goals system) || `server/services/lmStudioManager.js` | LM Studio model discovery and health || `server/services/localThinking.js` | Local model completions || `server/services/thinkingLevels.js` | Dynamic model selection |@@ -192,7 +192,7 @@ opening line. Off by default.| `server/services/executionLanes.test.js` | Execution Lanes || `server/services/errorRecovery.test.js` | Error Recovery (not built) || `server/services/agentRunCache.test.js` | Agent Run Cache (not built) |-| `server/services/missions.test.js` | Missions Service |+| `server/services/missions.test.js` | Missions Service (removed, #6826) |## Related Featuresdiff --git a/server/lib/paths.js b/server/lib/paths.jsindex 90d4e0bb34..41c5b8d334 100644--- a/server/lib/paths.js+++ b/server/lib/paths.js@@ -61,7 +61,6 @@ export const PATHS = {// Files here are shipped via data.reference/templates/ on first install.visualTemplates: join(INSTALL_ROOT, 'data/templates'),settings: join(INSTALL_ROOT, 'data/settings'),- missions: join(INSTALL_ROOT, 'data/cos/missions'),tools: join(INSTALL_ROOT, 'data/tools'),images: join(INSTALL_ROOT, 'data/images'),// Uploaded multi-reference inputs for FLUX.2 multi-ref edits. Sibling ofdiff --git a/server/lib/testDataIsolation.js b/server/lib/testDataIsolation.jsindex 40981330ee..a9268f7ad0 100644--- a/server/lib/testDataIsolation.js+++ b/server/lib/testDataIsolation.js@@ -7,7 +7,7 @@* defense: it text-scans every test file for a path spelling that names the* install's `data/` directory. Its own header explains the hole it leaves — a* suite that imports the real `PATHS` and reads a data-rooted member- * (`PATHS.brain`, `PATHS.missions`, …) with no redirect is invisible to a text+ * (`PATHS.brain`, `PATHS.digitalTwin`, …) with no redirect is invisible to a text* scan, and ~50 of ~1300 scoped test files legitimately use that spelling, so* closing it statically would need a 50-entry allowlist that rots.*diff --git a/server/routes/cos.test.js b/server/routes/cos.test.jsindex 995b4477f3..de48aa031b 100644--- a/server/routes/cos.test.js+++ b/server/routes/cos.test.js@@ -295,6 +295,7 @@ describe('CoS Routes', () => {['autonomyLevel', 'manager'],['comprehensiveAppImprovement', true],['immediateExecution', true],+ ['proactiveMode', false],])('accepts but ignores the retired %s config field for older clients', async (field, value) => {cos.updateConfig.mockResolvedValue({ maxConcurrentAgents: 5 });const response = await request(app)diff --git a/server/routes/cosStatusRoutes.js b/server/routes/cosStatusRoutes.jsindex 86c80e63df..47ac1829dc 100644--- a/server/routes/cosStatusRoutes.js+++ b/server/routes/cosStatusRoutes.js@@ -116,6 +116,7 @@ export const cosConfigSchema = z.object({delete supportedConfig.autonomyLevel;delete supportedConfig.comprehensiveAppImprovement;delete supportedConfig.immediateExecution;+ delete supportedConfig.proactiveMode;return supportedConfig;});diff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.jsindex 68bad4e0a6..c5e36dee5d 100644--- a/server/services/agentLifecycle.js+++ b/server/services/agentLifecycle.js@@ -721,14 +721,13 @@ async function runAgentSpawn(task) {});// Surface a silent `{ error }` miss (issue #2633) — the task id wasn't present// in the file for `task.taskType`, so the claim didn't land. This is EXPECTED- // for legitimately-unpersisted autonomous emits: Priority 3 mission tasks- // (cos.js `spawnDequeuePriority3Missions`) and Priority 4 idle-review tasks- // carry `taskType: 'internal'` but are never written to COS-TASKS.md, so their- // in_progress `updateTask` returns `{ error: 'Task not found' }`. Warn-log it- // for visibility, but do NOT block the spawn on it — the pre-#2633 behavior- // spawned these anyway, and treating the error as fatal would silently kill- // every mission / idle-review autonomous spawn. Only a `null` (updateTask- // threw) is fatal.+ // for legitimately-unpersisted autonomous emits: Priority 3 idle-review tasks+ // (cos.js `spawnDequeuePriority3IdleReview`) carry `taskType: 'internal'` but+ // are never written to COS-TASKS.md, so their in_progress `updateTask` returns+ // `{ error: 'Task not found' }`. Warn-log it for visibility, but do NOT block+ // the spawn on it — the pre-#2633 behavior spawned these anyway, and treating+ // the error as fatal would silently kill every idle-review autonomous spawn.+ // Only a `null` (updateTask threw) is fatal.if (updateResult?.error) {emitLog('warn', `⚠️ in_progress claim for task ${task.id} returned an error (taskType=${task.taskType}): ${updateResult.error}`, { taskId: task.id, error: updateResult.error });}diff --git a/server/services/agentLifecycle.test.js b/server/services/agentLifecycle.test.jsindex 0045a3f765..9061380b32 100644--- a/server/services/agentLifecycle.test.js+++ b/server/services/agentLifecycle.test.js@@ -981,13 +981,13 @@ describe('runAgentSpawn source — taskType normalization + claim-miss guard (isit('only a null in_progress result is fatal — an { error } miss must NOT block the spawn', () => {// A truthy `{ error }` is EXPECTED for legitimately-unpersisted autonomous- // emits (Priority 3 mission / Priority 4 idle-review tasks carry- // taskType:'internal' but are never written to COS-TASKS.md). Blocking on it- // would silently kill every mission/idle spawn — the pre-#2633 behavior- // spawned them anyway, so the fatal guard must remain `!updateResult` only.+ // emits (Priority 3 idle-review tasks carry taskType:'internal' but are+ // never written to COS-TASKS.md). Blocking on it would silently kill every+ // idle-review spawn — the pre-#2633 behavior spawned them anyway, so the+ // fatal guard must remain `!updateResult` only.const fatalIdx = RUN_SPAWN_BODY.indexOf('if (!updateResult) {');expect(fatalIdx, 'the fatal guard must be `!updateResult` alone — the { error } shape must not be fatal').toBeGreaterThan(-1);- expect(RUN_SPAWN_BODY, 'the { error } shape must not be part of the fatal guard (it would block unpersisted mission/idle spawns)')+ expect(RUN_SPAWN_BODY, 'the { error } shape must not be part of the fatal guard (it would block unpersisted idle-review spawns)').not.toContain('if (!updateResult || updateResult.error)');});diff --git a/server/services/cos.js b/server/services/cos.jsindex bb15b69870..c3ea9dc71a 100644--- a/server/services/cos.js+++ b/server/services/cos.js@@ -28,7 +28,6 @@ import { drainOnDemandRequests } from './onDemandDrain.js';import { logCosScheduleUpdate } from './userActionScheduleLog.js';import { getPerformanceSummary, checkAndRehabilitateSkippedTasks, getLearningInsights } from './taskLearning.js';import { schedule as scheduleEvent, cancel as cancelEvent } from './eventScheduler.js';-import { generateProactiveTasks as generateMissionTasks } from './missions.js';import { recordJobExecution } from './autonomousJobs.js';import { safeJSONParse, sleep, isTopLevelEntryName } from '../lib/fileUtils.js';import { ON_DEMAND_ORIGINS } from './taskScheduleConstants.js';@@ -156,11 +155,11 @@ import {} from './cosJobScheduler.js';// Pure priority/capacity helpers for dequeueNextTask (extracted to cosDequeue.js,-// issue #2530). The per-cycle capacity tracker + mission/idle tier-eligibility-// predicates are shared with the scheduler unit tests so they exercise the real+// 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 { createDequeueCapacity, countRunningAgentsByLocalEndpoint, isMissionTierEligible, isIdleTierEligible } from './cosDequeue.js';+import { createDequeueCapacity, countRunningAgentsByLocalEndpoint, isIdleTierEligible } from './cosDequeue.js';import { buildLocalEndpointSlotContext, localEndpointCapacityError } from './cosLocalEndpointSlots.js';import {initializePersistentMindSupervisor,@@ -1016,7 +1015,7 @@ async function spawnDequeuePriority0OnDemand(ctx) {/*** Priority 1 — pending user tasks. Records `pendingUserTasks` /- * `hasPendingUserTasks` on `ctx` for the mission/idle tiers below.+ * `hasPendingUserTasks` on `ctx` for the idle tier below.*/async function spawnDequeuePriority1UserTasks(ctx) {const { state, instanceId, capacity } = ctx;@@ -1048,7 +1047,7 @@ async function spawnDequeuePriority1UserTasks(ctx) {/*** Priority 2 — auto-approved system tasks, gated by the CoS auto-run domain.* Resolves `ctx.cosAutonomyMode` and `ctx.autonomousSpawnCeiling` (used by the- * mission/idle tiers) from the daily CoS budget (#711). `off`/`dry-run` withhold+ * idle tier) from the daily CoS budget (#711). `off`/`dry-run` withhold* the unattended spawn; `dry-run` logs what execute mode would have run.*/async function spawnDequeuePriority2AutoApproved(ctx) {@@ -1081,58 +1080,11 @@ async function spawnDequeuePriority2AutoApproved(ctx) {}/**- * Priority 3 — mission-driven proactive tasks. Speculative autonomous spawns,- * only generated when the shared `isMissionTierEligible` predicate passes (auto-- * run in execute, no pending user tasks, proactive mode on, headroom left).- */-async function spawnDequeuePriority3Missions(ctx) {- const { state, capacity } = ctx;-- if (!isMissionTierEligible({- spawned: capacity.spawned,- ceiling: ctx.autonomousSpawnCeiling,- hasPendingUserTasks: ctx.hasPendingUserTasks,- proactiveMode: state.config.proactiveMode,- autonomyMode: ctx.cosAutonomyMode- })) return;-- const missionTasks = await generateMissionTasks({ maxTasks: ctx.autonomousSpawnCeiling - capacity.spawned }).catch(err => {- emitLog('debug', `Mission task generation failed: ${err.message}`);- return [];- });-- for (const missionTask of missionTasks) {- if (capacity.spawned >= ctx.autonomousSpawnCeiling) break;- const cosTask = {- id: missionTask.id,- description: missionTask.description,- priority: missionTask.priority?.toUpperCase() || 'MEDIUM',- status: 'pending',- metadata: missionTask.metadata,- taskType: 'internal',- approvalRequired: !missionTask.autoApprove- };- // Committed tier — `generateMissionTasks` has already flipped the sub-task to- // `in_progress` and saved the mission, and mission tasks are never written to- // COS-TASKS.md, so a denial drops the only copy of a sub-task that- // `generateMissionTask` will never re-pick (it selects `pending` only).- // Emitting hands it to the chokepoint, whose `holdTask` reverts the flip- // (#4858) — so the sub-task really is recovered. See canSpawnCommitted (#4834).- if (!capacity.canSpawnCommitted(cosTask, ctx.autonomousSpawnCeiling)) continue;- cosEvents.emit('task:ready', cosTask);- capacity.trackSpawn(cosTask);- emitLog('info', `Generated mission task: ${missionTask.id}`, {- missionId: missionTask.metadata?.missionId- });- }-}--/**- * Priority 4 — idle review task, only when the daemon is completely idle this+ * 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).*/-async function spawnDequeuePriority4IdleReview(ctx) {+async function spawnDequeuePriority3IdleReview(ctx) {const { state, capacity, ignoreTaskId } = ctx;if (!isIdleTierEligible({@@ -1174,12 +1126,11 @@ 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 five priority tiers in order (same order as evaluateTasks):+ * through the four priority tiers in order (same order as evaluateTasks):* 0. On-demand requests (bypasses pause)* 1. User tasks* 2. Auto-approved system tasks- * 3. Mission-driven proactive tasks (if proactiveMode)- * 4. Idle review task (if idleReviewEnabled)+ * 3. Idle review task (if idleReviewEnabled)* Returns silently when idle — no log noise.*//**@@ -1282,11 +1233,10 @@ export async function dequeueNextTask({ ignoreTaskId = null } = {}) {// Priority 1 spends against the global slot cap.await spawnDequeuePriority1UserTasks(ctx);- // Priorities 2, 3, 4 spend against the lower autonomous ceiling that+ // Priorities 2 and 3 spend against the lower autonomous ceiling that// Priority 2 resolves onto `ctx.autonomousSpawnCeiling` from the daily budget.await spawnDequeuePriority2AutoApproved(ctx);- await spawnDequeuePriority3Missions(ctx);- await spawnDequeuePriority4IdleReview(ctx);+ await spawnDequeuePriority3IdleReview(ctx);if (capacity.spawned > 0) {emitLog('info', `⚡ Dequeued ${capacity.spawned} task(s)`, { spawned: capacity.spawned, availableSlots });@@ -1463,7 +1413,7 @@ async function refillPerpetualForCompletedAgent(agent) {// 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 ordering- // race where generic dequeue claims the freed slot with idle/mission work.+ // race where generic dequeue claims the freed slot with idle-review work.}/**@@ -1476,7 +1426,7 @@ export async function init() {// When an agent completes, refill perpetual work then dequeue the next taskcosEvents.on('agent:completed', (agent) => {// Refill the perpetual backlog FIRST, THEN dequeue — in one async task so the- // generic dequeue can't fill the just-freed slot with idle/mission work ahead+ // generic dequeue can't fill the just-freed slot with idle-review work ahead// of the perpetual re-queue. Perpetual schedules (e.g. claim-issue) drain// back-to-back: regenerate the next eligible task now instead of waiting for// the ~hourly improvement check (dequeueNextTask only spawns ALREADY-queueddiff --git a/server/services/cos.test.js b/server/services/cos.test.jsindex ff3c947578..82c0cb6122 100644--- a/server/services/cos.test.js+++ b/server/services/cos.test.js@@ -3,10 +3,10 @@* 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 (mission /- * feature agent) > 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).+ * (user) > Priority 2 (auto-approved system) > Priority 3 (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).** 2. `dequeueNextTask` capacity guards — global `maxConcurrentAgents` cap* and per-project `maxConcurrentAgentsPerProject` cap. The function must@@ -15,10 +15,10 @@* permits one more spawn.** `evaluateTasks` and `dequeueNextTask` are 250+ LOC each and pull in 40+- * imported helpers (loadState, getAllTasks, addTask, getActiveApps, mission- * generation, taskSchedule, etc.). Mocking the full graph would be a brittle+ * imported helpers (loadState, getAllTasks, addTask, getActiveApps,+ * taskSchedule, etc.). Mocking the full graph would be a brittle* test of mocks rather than logic, so we exercise the *real* capacity/gate- * exports the scheduler uses — `createDequeueCapacity`, `isMissionTierEligible`,+ * exports the scheduler uses — `createDequeueCapacity`,* `isIdleTierEligible` from cosDequeue.js (issue #2530) — through a thin drain* harness. Only the tier-ordering loop glue is local; every capacity and* eligibility decision routes through the same helpers `dequeueNextTask` calls,@@ -36,7 +36,7 @@ import { fileURLToPath } from 'url';import { dirname, join } from 'path';import { firstLine, isPerpetualRefillCandidate, perpetualRefillPlan } from './cos.js';import { canQueueImprovementTasks, DEFAULT_STATE } from './cosState.js';-import { createDequeueCapacity, countRunningAgentsByLocalEndpoint, isMissionTierEligible, isIdleTierEligible } from './cosDequeue.js';+import { createDequeueCapacity, countRunningAgentsByLocalEndpoint, isIdleTierEligible } from './cosDequeue.js';import {createLocalEndpointSlotContext,cloudSwarmThreadCapacity,@@ -61,7 +61,7 @@ const COS_SRC = readFileSync(join(__dirname, 'cos.js'), 'utf-8');const GEN_SRC = readFileSync(join(__dirname, 'cosTaskGenerator.js'), 'utf-8');const PRESTEP_SRC = readFileSync(join(__dirname, 'cosTaskPreStepBlocks.js'), 'utf-8');const SCHED_SRC = readFileSync(join(__dirname, 'cosJobScheduler.js'), 'utf-8');-// The pure capacity tracker + mission/idle tier-eligibility predicates that+// The pure capacity tracker + idle tier-eligibility predicate that// dequeueNextTask (and these tests) call live in cosDequeue.js (issue #2530).const DEQ_SRC = readFileSync(join(__dirname, 'cosDequeue.js'), 'utf-8');@@ -81,40 +81,35 @@ function makeCapacityTracker(state, agentsByProject = {}) {/*** Thin drain harness modelling the priority-bucket loop in `dequeueNextTask`.- * The five buckets are drained in this exact order:+ * The four buckets are drained in this exact order:** 0. onDemand — explicit user requests (highest, bypasses pause)* 1. user — user-authored pending tasks* 2. autoSystem — auto-approved system / improvement tasks- * 3. mission — proactive mission tasks (only when eligible)- * 4. idle — generated idle-review task (only when eligible)+ * 3. idle — generated idle-review task (only when eligible)** Only the ordering/glue is local: every capacity decision routes through the- * real `capacity.canSpawn`/`trackSpawn`, and the mission/idle fences use the- * real `isMissionTierEligible` / `isIdleTierEligible` predicates the scheduler- * calls. Within a bucket, iteration order is the source array order (file order- * for parsed TASKS.md; arrival order for the on-demand queue) — the loop does- * NOT re-sort by priorityValue.+ * real `capacity.canSpawn`/`trackSpawn`, and the idle fence uses the real+ * `isIdleTierEligible` predicate the scheduler calls. Within a bucket,+ * iteration order is the source array order (file order for parsed TASKS.md;+ * arrival order for the on-demand queue) — the loop does NOT re-sort by+ * priorityValue.*- * Idle gating is stricter than mission's: `isIdleTierEligible` requires- * `spawned === 0`, so ANY earlier spawn (autoSystem or mission) suppresses idle- * on the same cycle. Tests run with auto-run in `execute` and proactive/idle- * enabled so the tier predicates reduce to the pending-user + spawned gates.+ * `isIdleTierEligible` requires `spawned === 0`, so ANY earlier spawn+ * (autoSystem) suppresses idle on the same cycle. Tests run with auto-run in+ * `execute` and idle review enabled so the tier predicate reduces to the+ * pending-user + spawned gates.*/function priorityDequeue(buckets, capacity, { paused = false } = {}) {const admitted = [];const hasPendingUserTasks = (buckets.user || []).length > 0;- // No daily budget in these fixtures, so the autonomous ceiling equals the- // global slot count.- const ceiling = capacity.availableSlots;const drain = (bucketName) => {- // Priorities 0, 3 and 4 opt OUT of the local-endpoint cap, exactly as+ // Priorities 0 and 3 opt OUT of the local-endpoint cap, exactly as// production does: a denial there DISCARDS an already-committed task (a- // cleared on-demand request, an `in_progress` mission sub-task, a bound- // app-review marker) instead of deferring it, so they emit and let the- // spawner chokepoint hold.- const committed = ['onDemand', 'mission', 'idle'].includes(bucketName);+ // cleared on-demand request, a bound app-review marker) instead of+ // deferring it, so they emit and let the spawner chokepoint hold.+ const committed = ['onDemand', 'idle'].includes(bucketName);for (const task of buckets[bucketName] || []) {if (capacity.spawned >= capacity.availableSlots) return;if (!(committed ? capacity.canSpawnCommitted(task) : capacity.canSpawn(task))) continue;@@ -131,11 +126,6 @@ function priorityDequeue(buckets, capacity, { paused = false } = {}) {drain('user');drain('autoSystem');- if (isMissionTierEligible({- spawned: capacity.spawned, ceiling, hasPendingUserTasks,- proactiveMode: true, autonomyMode: 'execute'- })) drain('mission');-if (isIdleTierEligible({spawned: capacity.spawned, hasPendingUserTasks,idleReviewEnabled: true, autonomyMode: 'execute'@@ -167,7 +157,7 @@ const task = (id, priority = 'MEDIUM', { app } = {}) => ({// ─── evaluateTasks: priority ordering ──────────────────────────────────────describe('evaluateTasks — priority ordering', () => {- it('drains buckets in order: onDemand > user > autoSystem > mission > idle', () => {+ it('drains buckets in order: onDemand > user > autoSystem > idle', () => {const state = makeState({ maxConcurrentAgents: 5 });const capacity = makeCapacityTracker(state);@@ -175,15 +165,14 @@ describe('evaluateTasks — priority ordering', () => {onDemand: [task('task-onDemand-1')],user: [task('task-user-1')],autoSystem: [task('sys-auto-1')],- // Mission/idle should be SKIPPED here because user bucket is non-empty+ // Idle should be SKIPPED here because user bucket is non-empty// (matches production line 795 `hasPendingUserTasks` gate).- mission: [task('sys-mission-1')],idle: [task('sys-idle-1')],};const spawned = priorityDequeue(buckets, capacity);- // Order is: onDemand, user, autoSystem (mission/idle blocked by user-pending gate)+ // Order is: onDemand, user, autoSystem (idle blocked by user-pending gate)expect(spawned.map(t => t.id)).toEqual(['task-onDemand-1','task-user-1',@@ -203,7 +192,6 @@ describe('evaluateTasks — priority ordering', () => {onDemand: [task('task-onDemand-1')],user: [task('task-user-1')],autoSystem: [task('sys-auto-1')],- mission: [task('sys-mission-1')],idle: [task('sys-idle-1')],};@@ -214,30 +202,8 @@ describe('evaluateTasks — priority ordering', () => {expect(spawned.map(t => t._bucket)).toEqual(['onDemand']);});- it('mission + idle fire only when there are NO pending user tasks', () => {- // Idle is fenced behind `spawned === 0` in production (cos.js:2480), so- // when autoSystem and mission are both non-empty, idle does NOT fire.- // This test pins the user-pending gate; the next test pins the idle- // `spawned === 0` gate.- const state = makeState({ maxConcurrentAgents: 5 });- const capacity = makeCapacityTracker(state);-- const buckets = {- onDemand: [],- user: [], // ← critical: no pending user tasks- autoSystem: [task('sys-auto-1')],- mission: [task('sys-mission-1')],- idle: [task('sys-idle-1')],- };-- const spawned = priorityDequeue(buckets, capacity);- // autoSystem + mission spawn; idle is SUPPRESSED because earlier buckets- // already produced spawns (mirrors cos.js:2480 `spawned === 0` guard).- expect(spawned.map(t => t._bucket)).toEqual(['autoSystem', 'mission']);- });-it('idle fires only when nothing else has spawned (spawned === 0 gate, cos.js:2480)', () => {- // When autoSystem and mission are both empty AND no user-pending, idle+ // When autoSystem is empty AND no user-pending, idle// gets to run. This is the only path through which the idle bucket// actually drains in production.const state = makeState({ maxConcurrentAgents: 5 });@@ -247,7 +213,6 @@ describe('evaluateTasks — priority ordering', () => {onDemand: [],user: [],autoSystem: [],- mission: [],idle: [task('sys-idle-1')],};@@ -255,7 +220,7 @@ describe('evaluateTasks — priority ordering', () => {expect(spawned.map(t => t._bucket)).toEqual(['idle']);});- it('idle suppressed when only autoSystem spawned (no user, no mission)', () => {+ it('idle suppressed when only autoSystem spawned (no user tasks)', () => {// Pin the asymmetry: even a SINGLE autoSystem spawn is enough to suppress// idle on the same cycle. This is the production behavior at cos.js:862// (`tasksToSpawn.length === 0`) and cos.js:2480 (`spawned === 0`).@@ -266,7 +231,6 @@ describe('evaluateTasks — priority ordering', () => {onDemand: [],user: [],autoSystem: [task('sys-auto-1')],- mission: [],idle: [task('sys-idle-1')],};@@ -291,7 +255,6 @@ describe('evaluateTasks — priority ordering', () => {task('task-critical-third', 'CRITICAL'),],autoSystem: [],- mission: [],idle: [],};@@ -313,7 +276,6 @@ describe('evaluateTasks — priority ordering', () => {onDemand: [task('task-onDemand-1')],user: [task('task-user-1'), task('task-user-2')],autoSystem: [task('sys-auto-1')],- mission: [],idle: [],};@@ -325,7 +287,7 @@ describe('evaluateTasks — priority ordering', () => {it('returns no spawns when buckets are empty (idle queue)', () => {const state = makeState({ maxConcurrentAgents: 5 });const capacity = makeCapacityTracker(state);- const buckets = { onDemand: [], user: [], autoSystem: [], mission: [], idle: [] };+ const buckets = { onDemand: [], user: [], autoSystem: [], idle: [] };expect(priorityDequeue(buckets, capacity)).toEqual([]);});});@@ -346,7 +308,6 @@ describe('dequeueNextTask — capacity guards', () => {onDemand: [task('task-onDemand-1')],user: [task('task-user-1')],autoSystem: [],- mission: [],idle: [],};const spawned = priorityDequeue(buckets, capacity);@@ -365,7 +326,7 @@ describe('dequeueNextTask — capacity guards', () => {const capacity = makeCapacityTracker(state);expect(capacity.availableSlots).toBeLessThan(0);- const buckets = { onDemand: [], user: [task('task-user-1')], autoSystem: [], mission: [], idle: [] };+ const buckets = { onDemand: [], user: [task('task-user-1')], autoSystem: [], idle: [] };expect(priorityDequeue(buckets, capacity)).toEqual([]);});@@ -389,7 +350,6 @@ describe('dequeueNextTask — capacity guards', () => {task('task-beta-1', 'MEDIUM', { app: 'beta' }),],autoSystem: [],- mission: [],idle: [],};@@ -415,7 +375,6 @@ describe('dequeueNextTask — capacity guards', () => {task('task-alpha-3', 'HIGH', { app: 'alpha' }),],autoSystem: [],- mission: [],idle: [],};@@ -443,7 +402,6 @@ describe('dequeueNextTask — capacity guards', () => {task('task-alpha-3', 'HIGH', { app: 'alpha' }),],autoSystem: [],- mission: [],idle: [],};@@ -467,7 +425,6 @@ describe('dequeueNextTask — capacity guards', () => {task('task-self-2', 'HIGH'),],autoSystem: [],- mission: [],idle: [],};@@ -534,7 +491,7 @@ function makeLocalSlotCapacity(state, { activeProvider = CLOUD_PROVIDER, limit =return { capacity, holds, slots };}-const userBuckets = (tasks) => ({ onDemand: [], user: tasks, autoSystem: [], mission: [], idle: [] });+const userBuckets = (tasks) => ({ onDemand: [], user: tasks, autoSystem: [], idle: [] });describe('dequeueNextTask — per-local-endpoint agent cap (#4834)', () => {it('serializes two queued tasks that resolve to the SAME local endpoint', () => {@@ -569,7 +526,6 @@ describe('dequeueNextTask — per-local-endpoint agent cap (#4834)', () => {onDemand: [taskOnProvider('task-run-now', 'lmstudio-tui')],user: [],autoSystem: [],- mission: [],idle: [],}, capacity);@@ -577,12 +533,10 @@ describe('dequeueNextTask — per-local-endpoint agent cap (#4834)', () => {expect(holds).toEqual([]);});- it('does NOT suppress a mission or idle task at a saturated endpoint', () => {- // Both tiers commit before canSpawn and never persist: Priority 3 has- // already flipped the mission sub-task to `in_progress` (and only `pending`- // sub-tasks are ever re-picked), Priority 4 has already bound the app-review- // marker and advanced its 30-minute cooldown. A denial strands both; the- // chokepoint's hold at least releases the marker.+ it('does NOT suppress an idle task at a saturated endpoint', () => {+ // The idle tier commits before canSpawn and never persists: it has already+ // bound the app-review marker and advanced its 30-minute cooldown. A denial+ // would strand it; the chokepoint's hold at least releases the marker.const state = makeState({maxConcurrentAgents: 5,runningAgents: [makeRunningAgentOnProvider('lmstudio-tui')],@@ -593,11 +547,10 @@ describe('dequeueNextTask — per-local-endpoint agent cap (#4834)', () => {onDemand: [],user: [],autoSystem: [],- mission: [taskOnProvider('mission-task', 'lmstudio-tui')],- idle: [],+ idle: [taskOnProvider('idle-task', 'lmstudio-tui')],}, capacity);- expect(spawned.map(t => t.id)).toEqual(['mission-task']);+ expect(spawned.map(t => t.id)).toEqual(['idle-task']);});it.each(['user', 'autoSystem'])('keeps gating the deferrable %s tier at the same endpoint', (bucket) => {@@ -611,7 +564,7 @@ describe('dequeueNextTask — per-local-endpoint agent cap (#4834)', () => {const { capacity } = makeLocalSlotCapacity(state);const spawned = priorityDequeue({- onDemand: [], user: [], autoSystem: [], mission: [], idle: [],+ onDemand: [], user: [], autoSystem: [], idle: [],[bucket]: [taskOnProvider('deferrable-task', 'lmstudio-tui')],}, capacity);@@ -1344,21 +1297,18 @@ describe('cos.js source — priority + capacity invariants', () => {// Priority 0 (onDemand) — spawnDequeuePriority0OnDemand(ctx)// Priority 1 (user) — spawnDequeuePriority1UserTasks(ctx)// Priority 2 (autoSystem) — spawnDequeuePriority2AutoApproved(ctx)- // Priority 3 (mission) — spawnDequeuePriority3Missions(ctx)- // Priority 4 (idle) — spawnDequeuePriority4IdleReview(ctx)+ // Priority 3 (idle) — spawnDequeuePriority3IdleReview(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)');- const missionIdx = fnBody.indexOf('spawnDequeuePriority3Missions(ctx)');- const idleIdx = fnBody.indexOf('spawnDequeuePriority4IdleReview(ctx)');+ const idleIdx = fnBody.indexOf('spawnDequeuePriority3IdleReview(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(missionIdx, 'spawnDequeuePriority3Missions must run after auto-approved').toBeGreaterThan(autoSysIdx);- expect(idleIdx, 'spawnDequeuePriority4IdleReview must run after missions').toBeGreaterThan(missionIdx);+ expect(idleIdx, 'spawnDequeuePriority3IdleReview must run after auto-approved').toBeGreaterThan(autoSysIdx);});it('evaluateTasks orchestrates the spawnPriority* tiers in priority order', () => {@@ -1373,7 +1323,6 @@ describe('cos.js source — priority + capacity invariants', () => {const userIdx = fnBody.indexOf('spawnPriority1UserTasks(ctx)');const autoSysIdx = fnBody.indexOf('spawnPriority2AutoApproved(ctx)');const queueIdx = fnBody.indexOf('maybeQueueImprovementTasks(ctx)');- const missionIdx = fnBody.indexOf('spawnPriority3Missions(ctx)');const featureIdx = fnBody.indexOf('spawnPriority36FeatureAgents(ctx)');const idleIdx = fnBody.indexOf('spawnPriority4IdleReview(ctx)');@@ -1381,8 +1330,7 @@ describe('cos.js source — priority + capacity invariants', () => {expect(userIdx, 'spawnPriority1UserTasks must run after on-demand').toBeGreaterThan(onDemandIdx);expect(autoSysIdx, 'spawnPriority2AutoApproved must run after user tasks').toBeGreaterThan(userIdx);expect(queueIdx, 'maybeQueueImprovementTasks must run after auto-approved').toBeGreaterThan(autoSysIdx);- expect(missionIdx, 'spawnPriority3Missions must run after improvement queueing').toBeGreaterThan(queueIdx);- expect(featureIdx, 'spawnPriority36FeatureAgents must run after missions').toBeGreaterThan(missionIdx);+ expect(featureIdx, 'spawnPriority36FeatureAgents must run after improvement queueing').toBeGreaterThan(queueIdx);expect(idleIdx, 'spawnPriority4IdleReview must run after feature agents').toBeGreaterThan(featureIdx);});@@ -1547,14 +1495,13 @@ describe('cos.js source — priority + capacity invariants', () => {});it('the DESTRUCTIVE-denial tiers opt out of the local-endpoint cap (#4834)', () => {- // Priorities 0, 3 and 4 each commit side effects before `canSpawn` and never+ // Priorities 0 and 3 each commit side effects before `canSpawn` and never// persist the task, so a denial DISCARDS it rather than deferring it: the- // on-demand request is already cleared, the mission sub-task is already- // flipped to `in_progress` (and only `pending` ones are ever re-picked), the- // app-review marker is already bound. They emit and let the chokepoint hold.+ // on-demand request is already cleared, the app-review marker is already+ // 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', 'spawnDequeuePriority3Missions', 'spawnDequeuePriority4IdleReview']) {+ for (const tier of ['spawnDequeuePriority0OnDemand', 'spawnDequeuePriority3IdleReview']) {const body = extractFnBody(COS_SRC, COS_SRC.indexOf(`async function ${tier}`));expect(body, `${tier} must admit via canSpawnCommitted`).toMatch(/canSpawnCommitted\(/);}@@ -1566,11 +1513,11 @@ 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/mission and double-load the agent pool.- // dequeueNextTask's idle tier (spawnDequeuePriority4IdleReview) now routes+ // spawn alongside autoSystem and double-load the agent pool.+ // dequeueNextTask's idle tier (spawnDequeuePriority3IdleReview) 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 spawnDequeuePriority4IdleReview'));+ const idleTier = extractFnBody(COS_SRC, COS_SRC.indexOf('async function spawnDequeuePriority3IdleReview'));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`@@ -1588,10 +1535,10 @@ describe('cos.js source — priority + capacity invariants', () => {// Per-domain autonomy: the `cos` guardrail must gate every AUTOMATIC internal// spawn path — not just the auto-approved loop. Both spawn engines// (dequeueNextTask in cos.js, evaluateTasks in cosTaskGenerator.js) must read- // the cos mode and fence their mission / idle / auto-approved blocks on it,+ // the cos mode and fence their idle / auto-approved blocks on it,// or "off"/"dry-run" leaks autonomous agents through the un-gated engine.// dequeueNextTask resolves the cos mode in spawnDequeuePriority2AutoApproved- // and fences its mission/idle tiers through the shared eligibility predicates+ // and fences its idle tier through the shared eligibility predicate// (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'));@@ -1607,9 +1554,8 @@ describe('cos.js source — priority + capacity invariants', () => {.toMatch(/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['"]/);- // Dequeue's mission/idle tiers gate through the shared predicates, and its+ // 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 mission/idle via the eligibility predicates`).toMatch(/isMissionTierEligible\(/);expect(dequeueSrc, `dequeueNextTask must gate the idle tier via the eligibility predicate`).toMatch(/isIdleTierEligible\(/);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['"]/);@@ -2407,7 +2353,7 @@ describe('cos.js source — agent:completed triggers perpetual refill', () => {it('refill is sequenced BEFORE dequeue in the handler (perpetual task queued before slots fill)', () => {// If generic dequeue ran first (or concurrently), it could claim the just-- // freed slot with idle/mission work before the perpetual task is queued,+ // freed slot with idle-review work before the perpetual task is queued,// breaking the back-to-back drain. The handler must chain refill → dequeue.const onIdx = COS_SRC.indexOf("cosEvents.on('agent:completed'");const handlerSlice = COS_SRC.slice(onIdx, onIdx + 1400);diff --git a/server/services/cosDequeue.js b/server/services/cosDequeue.jsindex c4ba64597b..fd259eb2fe 100644--- a/server/services/cosDequeue.js+++ b/server/services/cosDequeue.js@@ -2,9 +2,9 @@* CoS Dequeue — pure priority/capacity helpers (issue #2530)** The spawn-side scheduler `dequeueNextTask` (in cos.js) fills open agent slots- * by draining five priority tiers in order. This module holds the *pure*,+ * by draining four priority tiers in order. This module holds the *pure*,* side-effect-free pieces of that decision — the per-cycle capacity tracker and- * the mission/idle tier-eligibility predicates — so the scheduler and its unit+ * the idle tier-eligibility predicate — so the scheduler and its unit* tests share ONE implementation instead of the tests re-deriving a local* replica of the guards.*@@ -15,7 +15,7 @@** 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 mission → 4 idle review.+ * 3 idle review.*//**@@ -46,17 +46,14 @@* fires on a denial so the scheduler can log queued-no-slot without this module* importing the event bus.*- * `canSpawnCommitted` opts a tier out of that third cap. Three tiers use it,+ * `canSpawnCommitted` opts a tier out of that third cap. Two tiers use it,* because a denial there is DESTRUCTIVE rather than a defer — each has already* committed side effects by the time `canSpawn` runs, and none of them persists* the task, so `false` discards the only copy:** - Priority 0 has cleared the on-demand request and bound the app-review* marker — a denial silently swallows the user's explicit "Run".- * - Priority 3 has flipped the mission sub-task to `in_progress` and saved the- * mission; `generateMissionTask` only ever re-picks `pending` sub-tasks, and- * the emitted object is the only copy (holdTask reverts the flip — #4858).- * - Priority 4 has bound the app-review marker and advanced the 30-minute+ * - Priority 3 has bound the app-review marker and advanced the 30-minute* review cooldown (issue #978's failure mode).** Emitting instead is strictly better — the authoritative cap at subAgentSpawner's@@ -146,24 +143,11 @@ export function countRunningAgentsByLocalEndpoint(agents, endpointForAgent) {}/**- * Priority 3 (mission) tier eligibility. Mission tasks are speculative- * autonomous spawns: they only run when there's autonomous headroom left this- * cycle, no pending user tasks are waiting, proactive mode is on, AND the CoS- * auto-run domain is in `execute` (off/dry-run withhold autonomous spawns).- */-export function isMissionTierEligible({ spawned, ceiling, hasPendingUserTasks, proactiveMode, autonomyMode }) {- return spawned < ceiling- && !hasPendingUserTasks- && !!proactiveMode- && autonomyMode === 'execute';-}--/**- * Priority 4 (idle-review) tier eligibility. The idle task only fires when the+ * Priority 3 (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 mission's `< ceiling`: even a single- * autonomous spawn suppresses idle on the same cycle.+ * The `spawned === 0` fence is stricter than the auto-approved tier's `< ceiling`+ * admission: even a single autonomous spawn suppresses idle on the same cycle.*/export function isIdleTierEligible({ spawned, hasPendingUserTasks, idleReviewEnabled, autonomyMode }) {return spawned === 0diff --git a/server/services/cosPriority2Parity.test.js b/server/services/cosPriority2Parity.test.jsindex 1566db78c1..ec91bb096c 100644--- a/server/services/cosPriority2Parity.test.js+++ b/server/services/cosPriority2Parity.test.js@@ -111,7 +111,6 @@ function resetFixtures(mode = 'execute') {maxConcurrentAgentsPerProject: 4,appReviewCooldownMs: 0,autoApproveInvestigations: true,- proactiveMode: false,idleReviewEnabled: false,domainAutonomy: { cos: mode },},diff --git a/server/services/cosState.js b/server/services/cosState.jsindex f1fe3ee8f5..1fb66299f9 100644--- a/server/services/cosState.js+++ b/server/services/cosState.js@@ -85,7 +85,6 @@ export const DEFAULT_CONFIG = {appReviewCooldownMs: 1800000,idleReviewEnabled: true,idleReviewPriority: 'MEDIUM',- proactiveMode: true,autonomousJobsEnabled: true,// Investigation tasks normally hold only failure loops for a human. This// opt-in also admits those loop/storm investigations unattended.@@ -208,6 +207,7 @@ function mergeStoredConfig(storedConfig) {delete persistedConfig.autonomyLevel;delete persistedConfig.comprehensiveAppImprovement;delete persistedConfig.immediateExecution;+ delete persistedConfig.proactiveMode;return {...DEFAULT_CONFIG,diff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.jsindex a042fd2507..19adf63703 100644--- a/server/services/cosTaskGenerator.js+++ b/server/services/cosTaskGenerator.js@@ -5,7 +5,7 @@ import { isPrivateSecurityTask, PRIVATE_SECURITY_DELIVERY } from '../lib/private** The task-generation + evaluation engine extracted from cos.js. Owns:* - `evaluateTasks` — the periodic/startup evaluation loop that decides what- * to spawn (priority 0 on-demand → 1 user → 2 auto-system → 3 mission/feature+ * to spawn (priority 0 on-demand → 1 user → 2 auto-system → 3.6 feature agent* → 4 idle review) and emits `task:ready` for each pick.* - the self-improvement / managed-app / idle-review generators that build the* actual task objects (prompt template + metadata + confidence approval).@@ -48,11 +48,10 @@ 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 { isIdleTierEligible } from './cosDequeue.js';import { resolveAgentProviderPin } from './appTaskProviderPin.js';import { getTaskTypeConfidence } from './taskLearning.js';import { classifySafetyKind, requiresSafetyApproval } from './taskLearning/safetyKind.js';-import { generateProactiveTasks as generateMissionTasks } from './missions.js';import { isRecoveryTask } from './recoveryTasks.js';import { getCodeReviewDefaults } from './codeReview.js';import { getSkipReason } from './cosTaskClaim.js';@@ -721,7 +720,7 @@ export async function unblockExpiredCooldowns(userTaskData, cosTaskData) {* many autonomous admissions the autonomous tiers may add this cycle.** Off/dry-run withhold all AUTOMATIC internal spawns (auto-approved system- * tasks, mission, feature-agent, idle-review); user and on-demand tasks are+ * tasks, feature-agent, idle-review); user and on-demand tasks are* unaffected. Usage is tallied in completeAgent for autonomous runs only, so a* pure dry-run never accrues; user/on-demand spawns are already past this gate.*@@ -967,49 +966,6 @@ async function maybeQueueImprovementTasks(ctx) {}}-/**- * Priority 3: Mission-driven proactive tasks (if no user tasks). Autonomous —- * gated by the CoS auto-run domain (off/dry-run skip generation entirely) and- * capped by `autonomousSlotCeiling`.- */-async function spawnPriority3Missions(ctx) {- const { state, hasPendingUserTasks, cosAutonomyMode, autonomousSlotCeiling, tasksToSpawn, canSpawnTask, trackSpawn } = ctx;-- 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 [];- });-- for (const missionTask of missionTasks) {- if (tasksToSpawn.length >= autonomousSlotCeiling) break;- // Convert mission task to COS task format- const cosTask = {- id: missionTask.id,- description: missionTask.description,- priority: missionTask.priority?.toUpperCase() || 'MEDIUM',- status: 'pending',- metadata: missionTask.metadata,- taskType: 'internal',- approvalRequired: !missionTask.autoApprove- };- if (!canSpawnTask(cosTask, autonomousSlotCeiling)) continue;- tasksToSpawn.push(cosTask);- trackSpawn(cosTask);- emitLog('info', `Generated mission task: ${missionTask.id} (${missionTask.metadata?.missionName})`, {- missionId: missionTask.metadata?.missionId,- appId: missionTask.metadata?.appId- });- }- }-}-/*** Priority 3.6: Feature Agents (after autonomous jobs, yield to user tasks).* Autonomous — gated by the CoS auto-run domain and capped by@@ -1080,14 +1036,13 @@ async function spawnPriority4IdleReview(ctx) {* - Priority 0 — on-demand requests (`spawnPriority0OnDemand`)* - Priority 1 — pending user tasks (`spawnPriority1UserTasks`)* - Priority 2 — auto-approved system tasks (`spawnPriority2AutoApproved`)- * - Priority 3 — mission-driven tasks (`spawnPriority3Missions`)* - Priority 3.6 — due feature agents (`spawnPriority36FeatureAgents`)* - Priority 4 — idle review (`spawnPriority4IdleReview`)** Cross-cutting gates live here so they cover every tier uniformly: the* paused/daemon guard, the global slot cap, orphan-cooldown unblocking, and the* CoS auto-run + daily-budget gate (`resolveAutonomyBudget`). Priorities 0–1- * spend against the global `availableSlots`; the autonomous tiers (2, 3, 3.6, 4)+ * spend against the global `availableSlots`; the autonomous tiers (2, 3.6, 4)* spend against the lower `autonomousSlotCeiling` so the CoS action budget caps* them. `evaluateTasks` emits `task:ready` per pick; the spawn-side scheduler* (`dequeueNextTask`/`tryImmediateSpawn`) stays in cos.js.@@ -1236,10 +1191,9 @@ export async function evaluateTasks(options) {// unchanged. The autonomous tiers use this in place of `availableSlots`.ctx.autonomousSlotCeiling = Math.min(availableSlots, tasksToSpawn.length + autonomousActionsRemaining);- // Priorities 2, 3, 3.6, 4 spend against the lower autonomous ceiling.+ // Priorities 2, 3.6, 4 spend against the lower autonomous ceiling.await spawnPriority2AutoApproved(ctx);await maybeQueueImprovementTasks(ctx);- await spawnPriority3Missions(ctx);await spawnPriority36FeatureAgents(ctx);await spawnPriority4IdleReview(ctx);}diff --git a/server/services/missions.js b/server/services/missions.jsdeleted file mode 100644index 61a9a125d2..0000000000--- a/server/services/missions.js+++ /dev/null@@ -1,496 +0,0 @@-/**- * Missions Service- *- * Long-term goals with sub-tasks and app ownership.- * Enables proactive task generation when user queue is empty.- */--import { readdir } from 'fs/promises'-import path from 'path'-import { v4 as uuidv4 } from '../lib/uuid.js'-import { cosEvents } from './cosEvents.js'-import { atomicWrite, safeJSONParse, ensureDir, PATHS, tryReadFile, unlinkGuarded } from '../lib/fileUtils.js'--const DATA_DIR = PATHS.missions--// In-memory cache-let missionsCache = null--const isPlainObject = value =>- typeof value === 'object' && value !== null && !Array.isArray(value)--const DEFAULT_METRICS = { tasksGenerated: 0, tasksCompleted: 0, successRate: 0 }--/**- * Coerce a parsed mission record into the shape every consumer assumes.- *- * `loadMissions` is the single door into this service — `getStats`,- * `completeSubTask`, `generateMissionTask` and `archiveCompletedMissions` all- * iterate the records it hands back and dereference `subTasks` / `goals` /- * `metrics` unguarded. Normalizing here (rather than scattering `?.length ?? 0`- * across the call sites) keeps "invalid" distinguishable from "legitimately- * empty": only the loader knows a record was malformed on disk, so only the- * loader can warn about it.- *- * @param {*} record - Parsed JSON from a mission file- * @returns {Object|null} - Normalized mission, or null if unusable- */-function normalizeMission(record) {- if (!isPlainObject(record)) return null-- return {- ...record,- status: typeof record.status === 'string' ? record.status : 'unknown',- progress: Number.isFinite(record.progress) ? record.progress : 0,- goals: Array.isArray(record.goals) ? record.goals : [],- subTasks: Array.isArray(record.subTasks)- ? record.subTasks.filter(isPlainObject)- : [],- metrics: isPlainObject(record.metrics)- ? { ...DEFAULT_METRICS, ...record.metrics }- : { ...DEFAULT_METRICS }- }-}--/**- * Load all missions- * @returns {Promise<Array>} - All missions- */-async function loadMissions() {- if (missionsCache) return missionsCache-- await ensureDir(DATA_DIR)-- const files = await readdir(DATA_DIR).catch(() => [])-- // Read every mission file in parallel on cold load rather than serializing- // one disk read at a time; the result is memoized in missionsCache below.- const loaded = await Promise.all(- files- .filter(file => file.endsWith('.json'))- .map(async file => {- const content = await tryReadFile(path.join(DATA_DIR, file))- if (!content) return null- const parsed = safeJSONParse(content, null, { context: `mission:${file}` })- const mission = normalizeMission(parsed)- // A file that parsed but isn't a usable mission object is dropped, not- // silently counted — name it so a corrupt record is visible.- if (!mission) console.warn(`⚠️ Skipping malformed mission record: ${file}`)- return mission- })- )-- const missions = loaded.filter(Boolean)-- missionsCache = missions- return missions-}--/**- * Save a mission to disk- * @param {Object} mission - Mission object- */-async function saveMission(mission) {- await ensureDir(DATA_DIR)- const filePath = path.join(DATA_DIR, `${mission.id}.json`)- await atomicWrite(filePath, mission)-- // Update cache- if (missionsCache) {- const idx = missionsCache.findIndex(m => m.id === mission.id)- if (idx !== -1) {- missionsCache[idx] = mission- } else {- missionsCache.push(mission)- }- }-}--/**- * Create a new mission- * @param {Object} data - Mission data- * @returns {Promise<Object>} - Created mission- */-async function createMission(data) {- const now = new Date().toISOString()-- const mission = {- id: data.id || uuidv4(),- appId: data.appId,- name: data.name,- description: data.description || '',- goals: data.goals || [],- subTasks: data.subTasks || [],- progress: 0,- status: 'active', // active, paused, completed, archived- priority: data.priority || 'medium',- autonomyLevel: data.autonomyLevel || 'full', // full, notify, approval-required- createdAt: now,- updatedAt: now,- lastReviewedAt: null,- completedAt: null,- metrics: {- tasksGenerated: 0,- tasksCompleted: 0,- successRate: 0- }- }-- await saveMission(mission)-- console.log(`🎯 Mission created: ${mission.name} (${mission.appId})`)- cosEvents.emit('mission:created', { id: mission.id, appId: mission.appId })-- return mission-}--/**- * Get mission by ID- * @param {string} id - Mission ID- * @returns {Promise<Object|null>} - Mission or null- */-async function getMission(id) {- const missions = await loadMissions()- return missions.find(m => m.id === id) || null-}--/**- * Get missions for an app- * @param {string} appId - App identifier- * @returns {Promise<Array>} - App missions- */-async function getMissionsForApp(appId) {- const missions = await loadMissions()- return missions.filter(m => m.appId === appId && m.status === 'active')-}--/**- * Get all active missions- * @returns {Promise<Array>} - Active missions- */-async function getActiveMissions() {- const missions = await loadMissions()- return missions.filter(m => m.status === 'active')-}--/**- * Update a mission- * @param {string} id - Mission ID- * @param {Object} updates - Updates to apply- * @returns {Promise<Object|null>} - Updated mission or null- */-async function updateMission(id, updates) {- const mission = await getMission(id)- if (!mission) return null-- const updatableFields = [- 'name', 'description', 'goals', 'subTasks', 'progress',- 'status', 'priority', 'autonomyLevel', 'lastReviewedAt',- 'completedAt', 'metrics'- ]-- for (const field of updatableFields) {- if (updates[field] !== undefined) {- mission[field] = updates[field]- }- }-- mission.updatedAt = new Date().toISOString()- await saveMission(mission)-- cosEvents.emit('mission:updated', { id: mission.id, updates })- return mission-}--/**- * Add a sub-task to a mission- * @param {string} missionId - Mission ID- * @param {Object} subTask - Sub-task data- * @returns {Promise<Object|null>} - Updated mission or null- */-async function addSubTask(missionId, subTask) {- const mission = await getMission(missionId)- if (!mission) return null-- const task = {- id: uuidv4(),- description: subTask.description,- status: 'pending', // pending, in_progress, completed, failed- priority: subTask.priority || 'medium',- createdAt: new Date().toISOString(),- completedAt: null,- result: null- }-- mission.subTasks.push(task)- mission.metrics.tasksGenerated++- mission.updatedAt = new Date().toISOString()-- await saveMission(mission)- return mission-}--/**- * Complete a sub-task- * @param {string} missionId - Mission ID- * @param {string} subTaskId - Sub-task ID- * @param {Object} result - Task result- * @returns {Promise<Object|null>} - Updated mission or null- */-async function completeSubTask(missionId, subTaskId, result = {}) {- const mission = await getMission(missionId)- if (!mission) return null-- const subTask = mission.subTasks.find(t => t.id === subTaskId)- if (!subTask) return null-- subTask.status = result.success === false ? 'failed' : 'completed'- subTask.completedAt = new Date().toISOString()- subTask.result = result-- // Update metrics- if (subTask.status === 'completed') {- mission.metrics.tasksCompleted++- }- mission.metrics.successRate = mission.metrics.tasksGenerated > 0- ? (mission.metrics.tasksCompleted / mission.metrics.tasksGenerated) * 100- : 0-- // Calculate progress- const completed = mission.subTasks.filter(t => t.status === 'completed').length- const total = mission.subTasks.length- mission.progress = total > 0 ? (completed / total) * 100 : 0-- // Check if mission is complete- if (mission.progress >= 100 && mission.goals.length > 0) {- mission.status = 'completed'- mission.completedAt = new Date().toISOString()- console.log(`🎉 Mission completed: ${mission.name}`)- cosEvents.emit('mission:completed', { id: mission.id })- }-- mission.updatedAt = new Date().toISOString()- await saveMission(mission)-- return mission-}--/**- * Generate a task from a mission (for proactive execution)- * @param {string} missionId - Mission ID- * @returns {Promise<Object|null>} - Generated task or null- */-async function generateMissionTask(missionId) {- const mission = await getMission(missionId)- if (!mission || mission.status !== 'active') return null-- // Find pending sub-tasks- const pendingSubTasks = mission.subTasks.filter(t => t.status === 'pending')-- if (pendingSubTasks.length > 0) {- // Return first pending sub-task as a COS task- const subTask = pendingSubTasks[0]- subTask.status = 'in_progress'- await saveMission(mission)-- return {- id: `mission-${mission.id}-${subTask.id}`,- description: subTask.description,- metadata: {- missionId: mission.id,- missionName: mission.name,- subTaskId: subTask.id,- appId: mission.appId,- autonomyLevel: mission.autonomyLevel,- isMissionTask: true- },- priority: subTask.priority,- autoApprove: mission.autonomyLevel === 'full'- }- }-- // No pending sub-tasks - might need to generate new ones based on goals- // This would typically involve AI analysis of the mission goals- return null-}--/**- * Return a sub-task `generateMissionTask` claimed as `in_progress` to `pending`.- *- * Mission tasks are never written to `COS-TASKS.md` — the in-memory object- * `generateMissionTask` emits as `task:ready` is the only copy. The flip it- * saves first exists purely to stop the next generation cycle re-picking the- * same sub-task, so any path that declines to spawn the emitted task strands it:- * the object is gone, and `generateMissionTask` only ever selects `pending`- * sub-tasks, so nothing re-picks it. The mission silently stops advancing, one- * sub-task burned per occurrence (issue #4858).- *- * Reverting the flip is what makes the dispatch holds mean for a mission task- * what they already mean for a persisted task: still queued, re-picked when the- * condition clears. The caller is `holdTask` in `subAgentSpawner.js`, the one- * chokepoint every hold funnels through.- *- * A sub-task that is no longer `in_progress` is left alone — `completeSubTask`- * may have landed a real result between dispatch and release, and resurrecting- * that as pending work would re-run finished work.- *- * @param {string} missionId - Mission ID- * @param {string} subTaskId - Sub-task ID- * @returns {Promise<Object|null>} - Updated mission, or null when nothing was released- */-async function releaseMissionSubTask(missionId, subTaskId) {- const mission = await getMission(missionId)- if (!mission) return null-- const subTask = mission.subTasks.find(t => t.id === subTaskId)- if (!subTask || subTask.status !== 'in_progress') return null-- subTask.status = 'pending'- mission.updatedAt = new Date().toISOString()- await saveMission(mission)-- return mission-}--/**- * Generate proactive tasks from all active missions- * @param {Object} options - Generation options- * @returns {Promise<Array>} - Generated tasks- */-async function generateProactiveTasks(options = {}) {- const { maxTasks = 3 } = options- const missions = await getActiveMissions()- const tasks = []-- for (const mission of missions) {- if (tasks.length >= maxTasks) break-- // Skip recently reviewed missions- if (mission.lastReviewedAt) {- const lastReview = new Date(mission.lastReviewedAt).getTime()- const hoursSinceReview = (Date.now() - lastReview) / (1000 * 60 * 60)- if (hoursSinceReview < 1) continue // Wait at least 1 hour between reviews- }-- const task = await generateMissionTask(mission.id)- if (task) {- tasks.push(task)- }- }-- return tasks-}--/**- * Record mission review (updates lastReviewedAt)- * @param {string} missionId - Mission ID- * @returns {Promise<Object|null>} - Updated mission or null- */-async function recordMissionReview(missionId) {- return updateMission(missionId, {- lastReviewedAt: new Date().toISOString()- })-}--/**- * Get mission statistics- * @returns {Promise<Object>} - Mission statistics- */-async function getStats() {- const missions = await loadMissions()-- const byStatus = {}- let totalProgress = 0- let totalTasks = 0- let completedTasks = 0-- for (const mission of missions) {- byStatus[mission.status] = (byStatus[mission.status] || 0) + 1- totalProgress += mission.progress- totalTasks += mission.subTasks.length- completedTasks += mission.subTasks.filter(t => t.status === 'completed').length- }-- return {- totalMissions: missions.length,- byStatus,- averageProgress: missions.length > 0- ? (totalProgress / missions.length).toFixed(1) + '%'- : '0%',- totalSubTasks: totalTasks,- completedSubTasks: completedTasks,- overallCompletion: totalTasks > 0- ? ((completedTasks / totalTasks) * 100).toFixed(1) + '%'- : '0%'- }-}--/**- * Delete a mission- * @param {string} id - Mission ID- * @returns {Promise<boolean>} - True if deleted- */-async function deleteMission(id) {- const filePath = path.join(DATA_DIR, `${id}.json`)- await unlinkGuarded(filePath).catch(() => {})-- if (missionsCache) {- missionsCache = missionsCache.filter(m => m.id !== id)- }-- console.log(`🗑️ Mission deleted: ${id}`)- cosEvents.emit('mission:deleted', { id })- return true-}--/**- * Archive completed missions- * @returns {Promise<number>} - Number of missions archived- */-async function archiveCompletedMissions() {- const missions = await loadMissions()- let archived = 0-- for (const mission of missions) {- if (mission.status === 'completed' && mission.completedAt) {- const completedDate = new Date(mission.completedAt).getTime()- const daysSinceCompletion = (Date.now() - completedDate) / (1000 * 60 * 60 * 24)-- if (daysSinceCompletion > 7) {- await updateMission(mission.id, { status: 'archived' })- archived++- }- }- }-- if (archived > 0) {- console.log(`📦 Archived ${archived} completed missions`)- }-- return archived-}--/**- * Invalidate cache (call after external changes)- */-function invalidateCache() {- missionsCache = null-}--export {- createMission,- getMission,- getMissionsForApp,- getActiveMissions,- updateMission,- addSubTask,- completeSubTask,- generateMissionTask,- releaseMissionSubTask,- generateProactiveTasks,- recordMissionReview,- getStats,- deleteMission,- archiveCompletedMissions,- invalidateCache-}diff --git a/server/services/missions.test.js b/server/services/missions.test.jsdeleted file mode 100644index 664c162d00..0000000000--- a/server/services/missions.test.js+++ /dev/null@@ -1,618 +0,0 @@-import { describe, it, expect, beforeEach, afterEach, afterAll, vi } from 'vitest';-import { existsSync, mkdirSync, rmSync, writeFileSync } from 'fs';-import path from 'path';-import { mockPathsDataRoot } from '../lib/mockPathsDataRoot.js';--// Mock cosEvents before import-vi.mock('./cos.js', () => ({- cosEvents: {- emit: vi.fn()- }-}));--// This suite exercises the REAL file-backed mission store — createMission writes-// `PATHS.missions/<id>.json` and loadMissions enumerates that dir with a real-// readdir. Without a PATHS redirect that dir is the checkout's own-// `data/cos/missions`, so the suite both read the developer's live missions (one-// with no `subTasks` crashed getStats) and wrote its own fixtures into it — the-// same leak class as #3683. `mockPathsDataRoot` re-roots every data-rooted-// `PATHS` member (#3689), so `PATHS.missions` lands under `tempRoot` on its own.-const { tempRoot, makeProxy, cleanup } = mockPathsDataRoot({ prefix: 'portos-missions-' });-vi.mock('../lib/fileUtils.js', async (importOriginal) => makeProxy(await importOriginal()));--afterAll(cleanup);--// Dynamic import, not a static one: `missions.js` reads `PATHS.missions` into a-// module-level const at load time, and a static import would run that load-// BEFORE the `mockPathsDataRoot()` line above — the hoisted mock factory would-// then close over an uninitialized `makeProxy`. Top-level await defers the load-// until after it exists.-//-// So the static imports at the top of this file must never transitively reach-// `../lib/fileUtils.js`, or the factory runs during their evaluation and throws-// `Cannot access 'makeProxy' before initialization`. `vi.hoisted()` does NOT fix-// that — it hoists above the imports too, putting `mockPathsDataRoot` itself in-// TDZ (verified: `Cannot access '__vi_import_0__' before initialization`). Keep-// new static imports here dependency-free, or make them dynamic as well.-const {- createMission,- getMission,- getMissionsForApp,- getActiveMissions,- updateMission,- addSubTask,- completeSubTask,- generateMissionTask,- releaseMissionSubTask,- generateProactiveTasks,- recordMissionReview,- getStats,- deleteMission,- archiveCompletedMissions,- invalidateCache-} = await import('./missions.js');--const DATA_DIR = path.join(tempRoot, 'cos', 'missions');--describe('Missions Service', () => {- beforeEach(() => {- invalidateCache();- // The temp root is this suite's alone, so wiping the whole missions dir is- // both simpler and stricter than unlinking `test-`-prefixed files.- rmSync(DATA_DIR, { recursive: true, force: true });- });-- afterEach(() => {- invalidateCache();- });-- describe('createMission', () => {- it('should create a new mission with defaults', async () => {- const mission = await createMission({- id: 'test-mission-1',- appId: 'test-app',- name: 'Test Mission'- });-- expect(mission.id).toBe('test-mission-1');- expect(mission.appId).toBe('test-app');- expect(mission.name).toBe('Test Mission');- expect(mission.status).toBe('active');- expect(mission.progress).toBe(0);- expect(mission.autonomyLevel).toBe('full');-- await deleteMission('test-mission-1');- });-- it('should set custom fields', async () => {- const mission = await createMission({- id: 'test-mission-2',- appId: 'test-app',- name: 'Test Mission',- description: 'Test description',- goals: ['Goal 1', 'Goal 2'],- priority: 'high',- autonomyLevel: 'approval-required'- });-- expect(mission.description).toBe('Test description');- expect(mission.goals).toEqual(['Goal 1', 'Goal 2']);- expect(mission.priority).toBe('high');- expect(mission.autonomyLevel).toBe('approval-required');-- await deleteMission('test-mission-2');- });- });-- describe('getMission', () => {- it('should retrieve a mission by ID', async () => {- const created = await createMission({- id: 'test-get-mission',- appId: 'test-app',- name: 'Get Test'- });-- const retrieved = await getMission('test-get-mission');- expect(retrieved).not.toBeNull();- expect(retrieved.id).toBe('test-get-mission');-- await deleteMission('test-get-mission');- });-- it('should return null for non-existent mission', async () => {- const result = await getMission('nonexistent');- expect(result).toBeNull();- });- });-- describe('getMissionsForApp', () => {- it('should get missions for a specific app', async () => {- await createMission({- id: 'test-app-mission-1',- appId: 'specific-app',- name: 'Mission 1'- });- await createMission({- id: 'test-app-mission-2',- appId: 'specific-app',- name: 'Mission 2'- });- await createMission({- id: 'test-app-mission-3',- appId: 'other-app',- name: 'Mission 3'- });-- const missions = await getMissionsForApp('specific-app');- expect(missions.length).toBe(2);- expect(missions.every(m => m.appId === 'specific-app')).toBe(true);-- await deleteMission('test-app-mission-1');- await deleteMission('test-app-mission-2');- await deleteMission('test-app-mission-3');- });- });-- describe('updateMission', () => {- it('should update mission fields', async () => {- await createMission({- id: 'test-update-mission',- appId: 'test-app',- name: 'Update Test'- });-- const updated = await updateMission('test-update-mission', {- progress: 50,- status: 'paused'- });-- expect(updated.progress).toBe(50);- expect(updated.status).toBe('paused');-- await deleteMission('test-update-mission');- });-- it('should return null for non-existent mission', async () => {- const result = await updateMission('nonexistent', { progress: 50 });- expect(result).toBeNull();- });- });-- describe('addSubTask', () => {- it('should add a sub-task to a mission', async () => {- await createMission({- id: 'test-subtask-mission',- appId: 'test-app',- name: 'SubTask Test'- });-- const updated = await addSubTask('test-subtask-mission', {- description: 'Sub-task 1',- priority: 'high'- });-- expect(updated.subTasks.length).toBe(1);- expect(updated.subTasks[0].description).toBe('Sub-task 1');- expect(updated.subTasks[0].status).toBe('pending');- expect(updated.metrics.tasksGenerated).toBe(1);-- await deleteMission('test-subtask-mission');- });- });-- describe('completeSubTask', () => {- it('should mark sub-task as completed', async () => {- await createMission({- id: 'test-complete-mission',- appId: 'test-app',- name: 'Complete Test'- });-- const withTask = await addSubTask('test-complete-mission', {- description: 'Task to complete'- });-- const subTaskId = withTask.subTasks[0].id;- const updated = await completeSubTask('test-complete-mission', subTaskId, {- success: true,- output: 'Task completed'- });-- expect(updated.subTasks[0].status).toBe('completed');- expect(updated.metrics.tasksCompleted).toBe(1);- expect(updated.progress).toBe(100);-- await deleteMission('test-complete-mission');- });-- it('should mark sub-task as failed', async () => {- await createMission({- id: 'test-fail-mission',- appId: 'test-app',- name: 'Fail Test'- });-- const withTask = await addSubTask('test-fail-mission', {- description: 'Task to fail'- });-- const subTaskId = withTask.subTasks[0].id;- const updated = await completeSubTask('test-fail-mission', subTaskId, {- success: false,- error: 'Task failed'- });-- expect(updated.subTasks[0].status).toBe('failed');- expect(updated.metrics.tasksCompleted).toBe(0);-- await deleteMission('test-fail-mission');- });- });-- describe('generateMissionTask', () => {- it('should generate task from pending sub-task', async () => {- await createMission({- id: 'test-generate-mission',- appId: 'test-app',- name: 'Generate Test'- });-- await addSubTask('test-generate-mission', {- description: 'Pending task',- priority: 'high'- });-- const task = await generateMissionTask('test-generate-mission');-- expect(task).not.toBeNull();- expect(task.description).toBe('Pending task');- expect(task.metadata.missionId).toBe('test-generate-mission');- expect(task.metadata.isMissionTask).toBe(true);-- await deleteMission('test-generate-mission');- });-- it('should return null for mission with no pending tasks', async () => {- await createMission({- id: 'test-no-pending-mission',- appId: 'test-app',- name: 'No Pending Test'- });-- const task = await generateMissionTask('test-no-pending-mission');- expect(task).toBeNull();-- await deleteMission('test-no-pending-mission');- });- });-- // Issue #4858: `generateMissionTask` saves the `in_progress` flip before it- // returns, but the task it returns is never persisted. Any dispatch path that- // declines to spawn it must hand the sub-task back, or generation — which only- // selects `pending` — never sees it again.- describe('releaseMissionSubTask', () => {- const seedGenerated = async (id) => {- await createMission({ id, appId: 'test-app', name: 'Release Test' });- await addSubTask(id, { description: 'Held task', priority: 'high' });- const task = await generateMissionTask(id);- return task.metadata.subTaskId;- };-- it('returns an in_progress sub-task to pending', async () => {- const subTaskId = await seedGenerated('test-release-mission');-- const mission = await releaseMissionSubTask('test-release-mission', subTaskId);-- expect(mission.subTasks.find(t => t.id === subTaskId).status).toBe('pending');-- await deleteMission('test-release-mission');- });-- // The acceptance criterion the whole fix exists for: the next generation- // cycle re-picks it, so the mission keeps advancing after the hold clears.- it('makes the sub-task re-generatable, so the mission resumes', async () => {- const subTaskId = await seedGenerated('test-regenerate-mission');- // Already claimed — generation correctly refuses to hand it out twice.- expect(await generateMissionTask('test-regenerate-mission')).toBeNull();-- await releaseMissionSubTask('test-regenerate-mission', subTaskId);- const task = await generateMissionTask('test-regenerate-mission');-- expect(task).not.toBeNull();- expect(task.metadata.subTaskId).toBe(subTaskId);-- await deleteMission('test-regenerate-mission');- });-- // A release that lands after the agent finished must not resurrect the- // sub-task and re-run completed work.- it('leaves a completed sub-task alone', async () => {- const subTaskId = await seedGenerated('test-release-completed');- await completeSubTask('test-release-completed', subTaskId, { success: true });-- expect(await releaseMissionSubTask('test-release-completed', subTaskId)).toBeNull();-- const mission = await getMission('test-release-completed');- expect(mission.subTasks.find(t => t.id === subTaskId).status).toBe('completed');-- await deleteMission('test-release-completed');- });-- it('leaves a failed sub-task alone', async () => {- const subTaskId = await seedGenerated('test-release-failed');- await completeSubTask('test-release-failed', subTaskId, { success: false });-- expect(await releaseMissionSubTask('test-release-failed', subTaskId)).toBeNull();-- const mission = await getMission('test-release-failed');- expect(mission.subTasks.find(t => t.id === subTaskId).status).toBe('failed');-- await deleteMission('test-release-failed');- });-- it('returns null for an unknown mission or sub-task', async () => {- await createMission({ id: 'test-release-unknown', appId: 'test-app', name: 'Unknown Test' });-- expect(await releaseMissionSubTask('no-such-mission', 'sub-1')).toBeNull();- expect(await releaseMissionSubTask('test-release-unknown', 'no-such-sub')).toBeNull();-- await deleteMission('test-release-unknown');- });- });-- describe('generateProactiveTasks', () => {- it('should generate tasks from active missions', async () => {- await createMission({- id: 'test-proactive-1',- appId: 'test-app',- name: 'Proactive 1'- });-- await addSubTask('test-proactive-1', {- description: 'Proactive task 1'- });-- const tasks = await generateProactiveTasks({ maxTasks: 5 });- expect(tasks.length).toBeGreaterThanOrEqual(1);-- await deleteMission('test-proactive-1');- });-- it('should respect maxTasks limit', async () => {- await createMission({- id: 'test-proactive-limit',- appId: 'test-app',- name: 'Limit Test'- });-- await addSubTask('test-proactive-limit', { description: 'Task 1' });- await addSubTask('test-proactive-limit', { description: 'Task 2' });- await addSubTask('test-proactive-limit', { description: 'Task 3' });-- const tasks = await generateProactiveTasks({ maxTasks: 1 });- expect(tasks.length).toBeLessThanOrEqual(1);-- await deleteMission('test-proactive-limit');- });- });-- describe('recordMissionReview', () => {- it('should update lastReviewedAt', async () => {- await createMission({- id: 'test-review-mission',- appId: 'test-app',- name: 'Review Test'- });-- const updated = await recordMissionReview('test-review-mission');- expect(updated.lastReviewedAt).not.toBeNull();-- await deleteMission('test-review-mission');- });- });-- describe('getStats', () => {- it('should return mission statistics', async () => {- await createMission({- id: 'test-stats-mission',- appId: 'test-app',- name: 'Stats Test'- });-- const stats = await getStats();- expect(stats).toHaveProperty('totalMissions');- expect(stats).toHaveProperty('byStatus');- expect(stats).toHaveProperty('averageProgress');-- await deleteMission('test-stats-mission');- });- });-- // #3690 — `loadMissions` used to hand every parsed `.json` straight through, so- // a hand-edited / half-written / older-shape record took out the whole Missions- // overview instead of one row. Fixtures are written with `writeFileSync`- // deliberately: the point is a record PortOS itself would never produce.- describe('malformed records on disk', () => {- const writeRaw = (file, contents) => {- mkdirSync(DATA_DIR, { recursive: true });- writeFileSync(path.join(DATA_DIR, file), contents);- invalidateCache();- };-- it('does not throw on a record with no subTasks array', async () => {- writeRaw('test-no-subtasks.json', JSON.stringify({- id: 'test-no-subtasks',- appId: 'test-app',- name: 'No SubTasks',- status: 'active',- progress: 40- }));-- const stats = await getStats();- expect(stats.totalMissions).toBe(1);- expect(stats.totalSubTasks).toBe(0);- expect(stats.completedSubTasks).toBe(0);- expect(stats.overallCompletion).toBe('0%');- });-- it('never reports averageProgress as NaN for a non-numeric progress', async () => {- writeRaw('test-bad-progress.json', JSON.stringify({- id: 'test-bad-progress',- appId: 'test-app',- name: 'Bad Progress',- status: 'active',- progress: 'halfway',- subTasks: []- }));-- const stats = await getStats();- expect(stats.averageProgress).toBe('0.0%');- expect(stats.averageProgress).not.toContain('NaN');- });-- it('buckets a status-less record under a named key, not undefined', async () => {- writeRaw('test-no-status.json', JSON.stringify({- id: 'test-no-status',- appId: 'test-app',- name: 'No Status',- subTasks: []- }));-- const stats = await getStats();- expect(Object.keys(stats.byStatus)).toEqual(['unknown']);- expect(stats.byStatus.unknown).toBe(1);- });-- it.each([- ['an array', '[]'],- ['a bare string', '"just a string"'],- ['a number', '42'],- ['unparseable bytes', '{ not json at all']- ])('drops %s with one warning line naming the file, and keeps the good records', async (_label, contents) => {- const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});-- writeRaw('test-not-a-mission.json', contents);- await createMission({ id: 'test-good-mission', appId: 'test-app', name: 'Good Mission' });-- const stats = await getStats();- expect(stats.totalMissions).toBe(1);-- const dropWarnings = warn.mock.calls.filter(([msg]) =>- typeof msg === 'string' && msg.includes('test-not-a-mission.json')- );- expect(dropWarnings.length).toBe(1);- expect(dropWarnings[0][0]).toContain('⚠️');-- warn.mockRestore();- await deleteMission('test-good-mission');- });-- it('ignores non-object entries inside subTasks rather than throwing', async () => {- writeRaw('test-bad-subtask-entries.json', JSON.stringify({- id: 'test-bad-subtask-entries',- appId: 'test-app',- name: 'Bad SubTask Entries',- status: 'active',- progress: 50,- subTasks: [null, 'not-a-task', { id: 'a', status: 'completed' }, { id: 'b', status: 'pending' }]- }));-- const stats = await getStats();- expect(stats.totalSubTasks).toBe(2);- expect(stats.completedSubTasks).toBe(1);- expect(stats.overallCompletion).toBe('50.0%');- });-- it('preserves the unrelated fields of a record it normalizes', async () => {- writeRaw('test-partial-record.json', JSON.stringify({- id: 'test-partial-record',- appId: 'test-app',- name: 'Partial Record',- description: 'kept as-is'- }));-- const mission = await getMission('test-partial-record');- expect(mission.description).toBe('kept as-is');- expect(mission.subTasks).toEqual([]);- expect(mission.goals).toEqual([]);- expect(mission.metrics).toEqual({ tasksGenerated: 0, tasksCompleted: 0, successRate: 0 });- });-- // The normalized record has to survive the mutating paths too — `addSubTask`- // pushes onto `subTasks` and bumps `metrics.tasksGenerated`, both of which- // threw on a record that arrived without them.- it('lets a normalized record take a new sub-task', async () => {- writeRaw('test-normalized-mutation.json', JSON.stringify({- id: 'test-normalized-mutation',- appId: 'test-app',- name: 'Normalized Mutation',- status: 'active'- }));-- const updated = await addSubTask('test-normalized-mutation', { description: 'First task' });- expect(updated.subTasks.length).toBe(1);- expect(updated.metrics.tasksGenerated).toBe(1);- });- });-- describe('deleteMission', () => {- it('should delete a mission', async () => {- await createMission({- id: 'test-delete-mission',- appId: 'test-app',- name: 'Delete Test'- });-- const deleted = await deleteMission('test-delete-mission');- expect(deleted).toBe(true);-- const retrieved = await getMission('test-delete-mission');- expect(retrieved).toBeNull();- });- });-- describe('archiveCompletedMissions', () => {- it('should archive old completed missions', async () => {- // Create a mission and mark it completed- await createMission({- id: 'test-archive-mission',- appId: 'test-app',- name: 'Archive Test'- });-- await updateMission('test-archive-mission', {- status: 'completed',- completedAt: new Date(Date.now() - 8 * 24 * 60 * 60 * 1000).toISOString() // 8 days ago- });-- const archived = await archiveCompletedMissions();- expect(archived).toBeGreaterThanOrEqual(0);-- const mission = await getMission('test-archive-mission');- if (mission) {- expect(mission.status).toBe('archived');- await deleteMission('test-archive-mission');- }- });- });-});--// Isolation probe for #3687 — these fail the same way if the PATHS redirect at-// the top of the file is ever dropped, so the leak can't come back silently.-describe('Missions Service — the suite is isolated from the checkout\'s real data/', () => {- it('resolves PATHS.missions to a temp dir outside the repo', async () => {- const { PATHS } = await import('../lib/fileUtils.js');- expect(PATHS.missions).toBe(DATA_DIR);- });-- // Asserts WHERE the record landed, not just how many came back. A count alone- // would pass on a fresh checkout with the redirect removed — real- // `data/cos/missions` is empty there, so writing one and reading one back still- // gives 1. Only the path assertion fails in that case.- it('writes its missions under the temp root, and reads back only its own', async () => {- await createMission({ id: 'test-isolation-probe', appId: 'test-app', name: 'Isolation Probe' });- expect(existsSync(path.join(DATA_DIR, 'test-isolation-probe.json'))).toBe(true);- const stats = await getStats();- expect(stats.totalMissions).toBe(1);- });-});diff --git a/server/services/subAgentSpawner.dispatchHolds.test.js b/server/services/subAgentSpawner.dispatchHolds.test.jsindex a8923ab222..a8ee9269ff 100644--- a/server/services/subAgentSpawner.dispatchHolds.test.js+++ b/server/services/subAgentSpawner.dispatchHolds.test.js@@ -27,9 +27,8 @@* The holds live in that listener, not inside `runAgentSpawn`, because a hold* below the spawn body's entry returns past `releaseAppReviewMarker` and strands* the synthetic "in review" marker for the whole outage (issue #989). The side- * effects the dequeue tiers already committed — that marker, the scheduler's- * `spawningJobIds` reservation, and a mission sub-task's `in_progress` flip —- * are released here instead.+ * effects the dequeue tiers already committed — that marker and the scheduler's+ * `spawningJobIds` reservation — are released here instead.*/import { describe, it, expect, vi, beforeEach } from 'vitest';@@ -60,7 +59,6 @@ vi.mock('./agentManagement.js', () => ({ cleanupOrphanedAgents: vi.fn().mockResovi.mock('./agentRunTracking.js', () => ({ completeAgentRun: vi.fn() }));vi.mock('./appActivity.js', () => ({ releaseAppReviewMarker: vi.fn().mockResolvedValue(undefined) }));vi.mock('./updateChecker.js', () => ({ isUpdateInProgress: vi.fn().mockReturnValue(false) }));-vi.mock('./missions.js', () => ({ releaseMissionSubTask: vi.fn().mockResolvedValue(null) }));vi.mock('./cosState.js', () => ({ loadState: vi.fn().mockResolvedValue({ agents: {} }) }));// The real slot module is covered end-to-end in cos.test.js (resolvers, running// tally, reservations). Mocked here so this suite stays about the LISTENER's@@ -91,7 +89,6 @@ import { isRunnerReachable } from './cosRunnerClient.js';import { spawnAgentForTask } from './agentOrchestrator.js';import { releaseAppReviewMarker } from './appActivity.js';import { isUpdateInProgress } from './updateChecker.js';-import { releaseMissionSubTask } from './missions.js';import { setUseRunner } from './agentState.js';import { acquireLocalEndpointSpawnSlot } from './cosLocalEndpointSlots.js';import { forgeSpawnHoldReason } from './cosForgeSpawnGate.js';@@ -233,99 +230,6 @@ describe('subAgentSpawner — self-update hold (#4124)', () => {});});-/**- * A mission task is the one dispatch shape with NO persisted record, so "leave- * the task queued" cannot mean "do nothing" for it (issue #4858).- *- * `generateMissionTask` flips the selected sub-task to `in_progress` and saves- * the mission before returning — the flip is what stops the next generation- * cycle re-picking it. The task object it returns is the only copy; nothing- * writes it to `COS-TASKS.md`. So a hold that skipped the revert would burn one- * sub-task per occurrence: no queued record to re-dispatch, and generation only- * ever selects `pending` sub-tasks, so the mission just stops advancing.- *- * The revert lives in `holdTask` rather than in any single hold branch, for the- * same reason `job:spawn-failed` does — that is the one chokepoint every hold- * funnels through, so a fourth hold inherits it for free.- */-describe('subAgentSpawner — mission sub-task release (#4858)', () => {- const missionTask = (id) => ({- id,- metadata: { missionId: 'mission-1', subTaskId: 'sub-3', isMissionTask: true },- });-- beforeEach(async () => {- await initSpawner();- vi.clearAllMocks();- vi.useRealTimers();- setUseRunner(true);- isRunnerReachable.mockResolvedValue(true);- isUpdateInProgress.mockReturnValue(false);- releaseMissionSubTask.mockResolvedValue(null);- });-- it('returns the sub-task to pending when the runner is down', async () => {- isRunnerReachable.mockResolvedValue(false);-- await dispatch(missionTask('cos-m1'));-- expect(spawnAgentForTask).not.toHaveBeenCalled();- expect(releaseMissionSubTask).toHaveBeenCalledWith('mission-1', 'sub-3');- });-- // The whole point of releasing in holdTask: every hold gets it, not just the- // one whose branch happened to be written first.- it('returns the sub-task to pending during a self-update too', async () => {- isUpdateInProgress.mockReturnValue(true);-- await dispatch(missionTask('cos-m2'));-- expect(releaseMissionSubTask).toHaveBeenCalledWith('mission-1', 'sub-3');- });-- it('leaves the flip alone on a successful dispatch — the agent owns it now', async () => {- await dispatch(missionTask('cos-m3'));-- expect(spawnAgentForTask).toHaveBeenCalledTimes(1);- expect(releaseMissionSubTask).not.toHaveBeenCalled();- });-- it('does not touch missions for a held task that is not a mission task', async () => {- isRunnerReachable.mockResolvedValue(false);-- await dispatch({ id: 'cos-m4', metadata: { jobId: 'job-2' } });-- expect(releaseMissionSubTask).not.toHaveBeenCalled();- });-- // Both halves identify the record; a missionId alone can't address a sub-task,- // and passing undefined through would make the helper scan for `undefined`.- it('skips the release when the sub-task id is missing', async () => {- isRunnerReachable.mockResolvedValue(false);-- await dispatch({ id: 'cos-m5', metadata: { missionId: 'mission-1' } });-- expect(releaseMissionSubTask).not.toHaveBeenCalled();- });-- // holdTask runs outside the request lifecycle (a cosEvents listener), so a- // rejected release must not escape as an unhandled rejection or swallow the- // releases queued before it.- it('logs and continues when the release fails', async () => {- isRunnerReachable.mockResolvedValue(false);- releaseMissionSubTask.mockRejectedValue(new Error('disk full'));-- await expect(dispatch({- id: 'cos-m6',- metadata: { missionId: 'mission-1', subTaskId: 'sub-3', app: 'some-app' },- })).resolves.not.toThrow();-- expect(releaseAppReviewMarker).toHaveBeenCalledWith('some-app');- const warnings = emitLog.mock.calls.filter(([level]) => level === 'warn');- expect(warnings.some(([, message]) => /release mission sub-task sub-3/.test(message))).toBe(true);- });-});-describe('subAgentSpawner — local-endpoint capacity hold (#4834)', () => {// A CoS agent runs a vendor CLI that opens its own connection to the local// model server, so promptRunner's in-flight gate never sees it. The hold livesdiff --git a/server/services/subAgentSpawner.js b/server/services/subAgentSpawner.jsindex 57eef64538..a8ca86dbbb 100644--- a/server/services/subAgentSpawner.js+++ b/server/services/subAgentSpawner.js@@ -46,7 +46,6 @@ import { appendRunEvent } from './agentRunEventLog.js';import { runnerAgents, setUseRunner, useRunner } from './agentState.js';import { releaseAppReviewMarker } from './appActivity.js';import { isUpdateInProgress } from './updateChecker.js';-import { releaseMissionSubTask } from './missions.js';import { loadState } from './cosState.js';import { acquireLocalEndpointSpawnSlot } from './cosLocalEndpointSlots.js';import { forgeSpawnHoldReason } from './cosForgeSpawnGate.js';@@ -81,11 +80,6 @@ let runnerRecovery = Promise.resolve();* which also re-registers the cron schedule. Without it an autonomous job* sits wedged until the scheduler's 5-minute spawn timeout — per job, per* outage.- * - a mission sub-task's `in_progress` flip (issue #4858). `generateMissionTask`- * writes that flip before returning, and a mission task is never persisted to- * `COS-TASKS.md` — the emitted object is the only copy. Held without the- * revert, the sub-task is stranded for good: there is no record left queued,- * and generation only ever re-picks `pending` sub-tasks.** Shared by every hold condition (self-update in progress, runner down, local* inference endpoint at capacity, and any that follow) so a new one can't ship@@ -99,11 +93,6 @@ async function holdTask(task, reason) {if (task.metadata?.jobId) {cosEvents.emit('job:spawn-failed', { jobId: task.metadata.jobId });}- if (task.metadata?.missionId && task.metadata?.subTaskId) {- await releaseMissionSubTask(task.metadata.missionId, task.metadata.subTaskId).catch(err =>- emitLog('warn', `Failed to release mission sub-task ${task.metadata.subTaskId}: ${err.message}`, { taskId: task.id })- );- }}/**