Skip to content

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

refactor([issue-741]): extract task-generation engine from cos.js

[._.]/ Adam Eivy350a073dcfaf
diff --git a/server/services/cos.js b/server/services/cos.js
index 29b60b6604..f55b223fbb 100644
--- a/server/services/cos.js
+++ b/server/services/cos.js
@@ -18,29 +18,16 @@ import { join } from 'path';
import { v4 as uuidv4 } from '../lib/uuid.js';
import { getActiveProvider } from './providers.js';
import { isInternalTaskId } from '../lib/taskParser.js';
-// NOTE: `getAppActivityById` + `updateAppActivity` are deliberately NOT
-// listed here even though they're used elsewhere in this file. The two
-// other call sites (in `generateManagedAppImprovementTask` and
-// `generateManagedAppImprovementTaskForType`) load them via a sibling
-// dynamic `import('./appActivity.js')` for unrelated reasons. Hoisting
-// them to the static import would leave them unreferenced at the
-// top-level scope of the queue path (which now reads the snapshot via
-// `loadAppActivity` + the pure predicate) and trip "unused import"
-// warnings. The dynamic-import sites stay self-contained.
-import { isAppOnCooldown, getNextAppForReview, markAppReviewStarted, markIdleReviewStarted, clearStaleActiveAgents, loadAppActivity, isAppActivityOnCooldown } from './appActivity.js';
-import { getActiveApps, getAppTaskTypeOverrides } from './apps.js';
-import { getAdaptiveCooldownMultiplier, getSkippedTaskTypes, getPerformanceSummary, checkAndRehabilitateSkippedTasks, getLearningInsights, getTaskTypeConfidence } from './taskLearning.js';
+import { isAppOnCooldown, markAppReviewStarted, clearStaleActiveAgents } from './appActivity.js';
+import { getActiveApps } from './apps.js';
+import { getPerformanceSummary, checkAndRehabilitateSkippedTasks, getLearningInsights } from './taskLearning.js';
import { schedule as scheduleEvent, cancel as cancelEvent, getStats as getSchedulerStats, parseCronToNextRun } from './eventScheduler.js';
-import { generateProactiveTasks as generateMissionTasks, getStats as getMissionStats } from './missions.js';
+import { generateProactiveTasks as generateMissionTasks } from './missions.js';
import { generateTaskFromJob, recordJobExecution, recordJobGateSkip, isScriptJob, executeScriptJob, isShellJob, executeShellJob } from './autonomousJobs.js';
import { checkJobGate, hasGate } from './jobGates.js';
-import { ensureDir, formatDuration, safeJSONParse, PATHS } from '../lib/fileUtils.js';
-import { sanitizeTaskMetadata, PIPELINE_BEHAVIOR_FLAGS, MAX_TOTAL_SPAWNS, normalizeReviewers } from '../lib/validation.js';
+import { formatDuration, safeJSONParse } from '../lib/fileUtils.js';
import { addNotification, NOTIFICATION_TYPES } from './notifications.js';
-import { recordDecision, DECISION_TYPES } from './decisionLog.js';
-import { isRecoveryTask } from './recoveryTasks.js';
import { getUserTimezone, getLocalParts, nextLocalTime, todayInTimezone } from '../lib/timezone.js';
-import { PORTOS_UI_URL } from '../lib/ports.js';
// Shared state management (extracted to avoid circular deps)
import { loadState, saveState, withStateLock, ensureDirectories, isImprovementEnabled, AGENTS_DIR, REPORTS_DIR, SCRIPTS_DIR, ROOT_DIR, isDaemonRunning, setDaemonRunning } from './cosState.js';
@@ -80,116 +67,28 @@ const POST_STARTUP_QUEUE_DELAY_MS = 30_000;
// "recently completed" and protected from resetOrphanedTasks's reaper.
const RECENT_COMPLETION_GRACE_MS = 60_000;
-// MAX_TOTAL_SPAWNS imported from validation.js (shared with subAgentSpawner.js)
-
-/**
- * Block a task that has exceeded the max spawn limit. Returns true if blocked.
- */
-async function blockIfExceedsMaxSpawns(task, taskType) {
- const totalSpawns = Number(task.metadata?.totalSpawnCount) || 0;
- if (totalSpawns < MAX_TOTAL_SPAWNS) return false;
- emitLog('info', `🚫 Blocking task ${task.id} — exceeded max spawns (${totalSpawns}/${MAX_TOTAL_SPAWNS})`, { taskId: task.id });
- await updateTask(task.id, {
- status: 'blocked',
- metadata: { ...task.metadata, blockedReason: `Max total spawns exceeded (${totalSpawns}/${MAX_TOTAL_SPAWNS})`, blockedCategory: 'max-spawns', blockedAt: new Date().toISOString() }
- }, taskType).catch(err => {
- emitLog('warn', `Failed to block task ${task.id}: ${err.message}`, { taskId: task.id });
- });
- return true;
-}
-
-let initialStartup = false;
-
// Internal imports for functions used in this module
import { pruneOldAgentArchives, archiveStaleAgents as _archiveStaleAgents, loadAgentIndex } from './cosAgents.js';
-import { parsePlanItems, extractAllIds, findInProgressIds, pickFirstAvailable, diagnoseUnpickablePlan } from '../lib/planIds.js';
-
-// Task types where the scheduler reads PLAN.md to find an in-flight-aware pick.
-// `do-replan` is excluded — it assigns IDs rather than picking one off the list.
-const PLAN_PICK_TASK_TYPES = new Set(['feature-ideas', 'plan-task']);
-
-// Subset of PLAN_PICK_TASK_TYPES where the AGENT picks (and claims) its own slug
-// at execution time — mirroring the `/claim` slash command. For these, the
-// scheduler must NOT stamp `metadata.planId`: a dispatch-time pre-pick happens
-// before the agent creates its `claim/<slug>` branch (the real lock), so two
-// near-simultaneous dispatches would both target the same first-available item.
-// We still run the in-flight scan below purely as a DISPATCH GATE (skip the run
-// when nothing is pickable), but leave the actual pick to the agent's Phase 1
-// scan, which immediately precedes branch creation. The 2026-05-21 duplicate-PR
-// incident (see cos.test.js) is guarded by the full Phase 1–7 self-pick prompt,
-// not by the pre-pick. `feature-ideas` is intentionally NOT in this set — it
-// uses a scheduler-managed worktree whose branch name encodes `planId`.
-const PLAN_SELF_CLAIM_TASK_TYPES = new Set(['plan-task']);
-
-// Subset of PLAN_PICK_TASK_TYPES where the dispatch should be skipped entirely
-// when no PLAN.md item is dispatchable. `feature-ideas` is intentionally
-// excluded: it brainstorms new items when PLAN.md is empty/blocked, so it
-// must run regardless. `plan-task` is a strict executor and would just exit
-// cleanly — burning an LLM round for nothing.
-const PLAN_GATE_TASK_TYPES = new Set(['plan-task']);
-/**
- * For feature-ideas / plan-task, read the target repo's PLAN.md, find which
- * item IDs are already in flight via branch/PR scan, and pick the first
- * available item. Mutates `metadata` in place by setting `planId` when a
- * pick succeeds — EXCEPT for self-claiming task types (PLAN_SELF_CLAIM_TASK_TYPES),
- * where the agent picks its own slug at execution time and the scan is used
- * only as the dispatch gate (no `planId` stamp).
- *
- * Returns `{ skipReason }` so the caller can short-circuit the LLM dispatch
- * for `plan-task` when there's literally nothing to do (empty plan, all
- * items blocked on human input via NEEDS_INPUT/DRIFT, or all claimed
- * elsewhere). `feature-ideas` is never gated — its job is to brainstorm
- * from scratch when the plan is empty, so it always runs.
- *
- * @returns {Promise<{ skipReason: string | null }>}
- */
-async function applyPlanIdMetadata(taskType, repoPath, metadata) {
- if (!PLAN_PICK_TASK_TYPES.has(taskType)) return { skipReason: null };
- if (!repoPath) return { skipReason: null };
- const planMd = await readFile(join(repoPath, 'PLAN.md'), 'utf-8').catch(() => '');
- const gateDispatch = PLAN_GATE_TASK_TYPES.has(taskType);
- if (!planMd) {
- return { skipReason: gateDispatch ? 'PLAN.md missing or empty' : null };
- }
- const items = parsePlanItems(planMd);
-
- // Short-circuit on local evidence before the network round-trip to
- // `git fetch --prune` + `gh pr list`. When every unchecked item is
- // already blocked on human input, no in-flight scan can change that.
- if (gateDispatch) {
- const localOnly = diagnoseUnpickablePlan(null, new Set(), items);
- if (localOnly) return { skipReason: localOnly };
- }
-
- const knownIds = new Set(extractAllIds(planMd));
- const inFlight = await findInProgressIds(repoPath, knownIds).catch(() => new Set());
- const pick = pickFirstAvailable(items, inFlight);
- if (pick?.id) {
- // Self-claiming task types pick their own slug at execution time (like
- // `/claim`); stamping it here would pin concurrent dispatches to the same
- // item. For them this scan only serves as the gate above.
- if (!PLAN_SELF_CLAIM_TASK_TYPES.has(taskType)) {
- metadata.planId = pick.id;
- }
- return { skipReason: null };
- }
- if (!gateDispatch) return { skipReason: null };
- return { skipReason: diagnoseUnpickablePlan(null, inFlight, items) };
-}
-
-/**
- * Build the `{planConstraint}` substitution block. Empty when no planId —
- * the prompt's existing Phase 1 fallback (brainstorm or exit-clean) takes over.
- */
-function buildPlanConstraintBlock(planId) {
- if (!planId) return '';
- return `
-## Item Constraint
-
-The scheduler has reserved PLAN.md item \`[${planId}]\` for you. You MUST work on that exact item — do not pick a different one, do not brainstorm. If the line is missing from PLAN.md, has already been checked, or carries \`<!-- NEEDS_INPUT -->\`, exit cleanly without commits or PR.
-`;
-}
+// Task generation + evaluation engine (extracted to cosTaskGenerator.js).
+// `evaluateTasks` and the generators emit `task:ready`; the spawn-side
+// scheduler (dequeueNextTask / tryImmediateSpawn) below reacts to that. Most of
+// these are imported for internal use by the scheduler; checkStagePrecondition
+// and applyAppWorktreeDefault are re-exported for agentLifecycle.js and
+// subAgentSpawner, and evaluateTasks for the cos route + `import * as cos`.
+import {
+ evaluateTasks,
+ generateIdleReviewTask,
+ queueEligibleImprovementTasks,
+ generateSelfImprovementTaskForType,
+ generateManagedAppImprovementTaskForType,
+ blockIfExceedsMaxSpawns,
+ countRunningAgentsByProject,
+ isWithinProjectLimit,
+ checkStagePrecondition,
+ applyAppWorktreeDefault
+} from './cosTaskGenerator.js';
+export { evaluateTasks, checkStagePrecondition, applyAppWorktreeDefault };
/**
* Get current CoS status
@@ -407,9 +306,7 @@ export async function start() {
// Run initial evaluation to pick up existing pending tasks, then health check
// Skip improvement task generation on startup to avoid spawning agents on fresh installs
emitLog('info', 'Running initial task evaluation...');
- initialStartup = true;
- await evaluateTasks();
- initialStartup = false;
+ await evaluateTasks({ initialStartup: true });
await runHealthCheck();
cosEvents.emit('status', { running: true });
@@ -607,1502 +504,6 @@ async function resetOrphanedTasks() {
}
}
-/**
- * Count running agents grouped by project (app ID).
- * Agents without an app (self-improvement, PortOS tasks) are grouped under '_self'.
- */
-function countRunningAgentsByProject(agents) {
- const counts = {};
- for (const agent of Object.values(agents)) {
- if (agent.status !== 'running') continue;
- const project = agent.metadata?.taskApp || agent.metadata?.app || '_self';
- counts[project] = (counts[project] || 0) + 1;
- }
- return counts;
-}
-
-/**
- * Check if a task would exceed the per-project concurrency limit.
- * Returns true if the task can be spawned (within limit), false otherwise.
- */
-function isWithinProjectLimit(task, agentsByProject, perProjectLimit) {
- const project = task.metadata?.app || '_self';
- const current = agentsByProject[project] || 0;
- return current < perProjectLimit;
-}
-
-/**
- * Evaluate tasks and decide what to spawn
- *
- * Priority order:
- * 1. User tasks (not on cooldown)
- * 2. Auto-approved system tasks (not on cooldown)
- * 3. Generate idle review task if no other work
- */
-export async function evaluateTasks() {
- if (!isDaemonRunning()) return;
-
- // Check if paused - skip evaluation if so
- const paused = await isPaused();
- if (paused) {
- emitLog('debug', 'CoS is paused - skipping evaluation');
- return;
- }
-
- // Update evaluation timestamp with lock to prevent race conditions
- const state = await withStateLock(async () => {
- const s = await loadState();
- s.stats.lastEvaluation = new Date().toISOString();
- await saveState(s);
- return s;
- });
-
- // Get both user and CoS tasks
- const { user: userTaskData, cos: cosTaskData } = await getAllTasks();
-
- // Unblock tasks whose orphan-retry cooldown has expired
- const allBlocked = [
- ...(userTaskData.grouped?.blocked || []),
- ...(cosTaskData.grouped?.blocked || [])
- ];
- for (const task of allBlocked) {
- if (task.metadata?.blockedCategory === 'orphan-cooldown' && task.metadata?.cooldownUntil) {
- if (new Date(task.metadata.cooldownUntil).getTime() <= Date.now()) {
- const taskType = task.taskType || (userTaskData.grouped?.blocked?.includes(task) ? 'user' : 'internal');
- emitLog('info', `⏰ Orphan cooldown expired for task ${task.id}, unblocking`, { taskId: task.id });
- await updateTask(task.id, {
- status: 'pending',
- metadata: {
- ...task.metadata,
- blockedReason: undefined,
- blockedCategory: undefined,
- blockedAt: undefined,
- cooldownUntil: undefined
- }
- }, taskType);
- }
- }
- }
-
- // Count running agents and available slots (global + per-project)
- const runningAgentEntries = Object.values(state.agents).filter(a => a.status === 'running');
- const runningAgents = runningAgentEntries.length;
- const availableSlots = state.config.maxConcurrentAgents - runningAgents;
-
- const perProjectLimit = state.config.maxConcurrentAgentsPerProject || state.config.maxConcurrentAgents;
- const agentsByProject = countRunningAgentsByProject(state.agents);
-
- if (availableSlots <= 0) {
- emitLog('warn', `Max concurrent agents reached (${runningAgents}/${state.config.maxConcurrentAgents})`);
- await recordDecision(
- DECISION_TYPES.CAPACITY_FULL,
- `All ${state.config.maxConcurrentAgents} agent slots occupied`,
- { running: runningAgents, max: state.config.maxConcurrentAgents }
- );
- cosEvents.emit('evaluation', { message: 'Max concurrent agents reached', running: runningAgents });
- return;
- }
-
- const tasksToSpawn = [];
- // Track per-project counts including tasks we're about to spawn in this batch
- const spawnProjectCounts = { ...agentsByProject };
-
- // Helper: check if a task can spawn (within both global and per-project limits)
- const canSpawnTask = (task) => {
- if (tasksToSpawn.length >= availableSlots) return false;
- const project = task.metadata?.app || '_self';
- return (spawnProjectCounts[project] || 0) < perProjectLimit;
- };
- // Helper: track a spawned task's project
- const trackSpawn = (task) => {
- const project = task.metadata?.app || '_self';
- spawnProjectCounts[project] = (spawnProjectCounts[project] || 0) + 1;
- };
-
- // Priority 0: On-demand task requests (highest priority - user explicitly requested these)
- const taskSchedule = await import('./taskSchedule.js');
- const liveSchedule = await taskSchedule.loadSchedule();
- const onDemandRequests = Array.isArray(liveSchedule?.onDemandRequests) ? liveSchedule.onDemandRequests : [];
-
- // Track apps already marked review-started this cycle so multiple on-demand
- // requests for the same app don't each rewrite its activity record.
- const reviewStartedApps = new Set();
- if (onDemandRequests.length > 0 && tasksToSpawn.length < availableSlots) {
- for (const request of onDemandRequests) {
- if (tasksToSpawn.length >= availableSlots) break;
-
- if (!isImprovementEnabled(state)) {
- emitLog('warn', `On-demand request dropped — improvement is disabled (Config → Improve)`, { requestId: request.id, taskType: request.taskType });
- await taskSchedule.clearOnDemandRequest(request.id);
- continue;
- }
-
- // Skip if the task type was disabled or removed after queuing — parity with dequeueNextTask.
- if (!liveSchedule.tasks[request.taskType]?.enabled) {
- emitLog('info', `On-demand request skipped — task type '${request.taskType}' is disabled`, { requestId: request.id });
- await taskSchedule.clearOnDemandRequest(request.id);
- continue;
- }
-
- let task = null;
- // Determine target app (if any)
- const apps = await getActiveApps().catch(() => []);
- let targetApp = null;
-
- if (request.appId) {
- targetApp = apps.find(a => a.id === request.appId);
- if (!targetApp) {
- emitLog('warn', `On-demand request for unknown app: ${request.appId}`, { requestId: request.id });
- await taskSchedule.clearOnDemandRequest(request.id);
- continue;
- }
- }
-
- await taskSchedule.clearOnDemandRequest(request.id);
-
- if (targetApp) {
- emitLog('info', `Processing on-demand improvement: ${request.taskType} for ${targetApp.name}`, { requestId: request.id, appId: targetApp.id });
- if (!reviewStartedApps.has(targetApp.id)) {
- await markAppReviewStarted(targetApp.id, `on-demand-${Date.now()}`);
- reviewStartedApps.add(targetApp.id);
- }
- await taskSchedule.recordExecution(`task:${request.taskType}`, targetApp.id);
- task = await generateManagedAppImprovementTaskForType(request.taskType, targetApp, state, { skipPreconditions: true });
- } else {
- emitLog('info', `Processing on-demand improvement: ${request.taskType}`, { requestId: request.id });
- await taskSchedule.recordExecution(`task:${request.taskType}`);
- await withStateLock(async () => {
- const s = await loadState();
- s.stats.lastSelfImprovement = new Date().toISOString();
- s.stats.lastSelfImprovementType = request.taskType;
- await saveState(s);
- });
- task = await generateSelfImprovementTaskForType(request.taskType, state);
- }
-
- if (task && canSpawnTask(task)) {
- const persisted = await addTask(task, 'internal', { raw: true });
- if (!persisted?.duplicate) {
- tasksToSpawn.push(task);
- trackSpawn(task);
- }
- }
- }
- }
-
- // Priority 1: User tasks (always run - cooldown only applies to system tasks)
- const pendingUserTasks = userTaskData.grouped?.pending || [];
- for (const task of pendingUserTasks) {
- if (tasksToSpawn.length >= availableSlots) break;
- if (await blockIfExceedsMaxSpawns(task, 'user')) continue;
- const userTask = { ...task, taskType: 'user' };
- if (!canSpawnTask(userTask)) {
- const project = task.metadata?.app || '_self';
- emitLog('debug', `⏳ Queued user task ${task.id} - per-project limit reached for ${project}`);
- await recordDecision(
- DECISION_TYPES.CAPACITY_FULL,
- `User task ${task.id} deferred — per-project limit (${perProjectLimit}) reached for ${project}`,
- { taskId: task.id, project, limit: perProjectLimit }
- );
- continue;
- }
- tasksToSpawn.push(userTask);
- trackSpawn(userTask);
- }
-
- // Priority 2: Auto-approved system tasks (if slots available)
- if (tasksToSpawn.length < availableSlots && cosTaskData.exists) {
- const autoApproved = cosTaskData.autoApproved || [];
- for (const task of autoApproved) {
- if (tasksToSpawn.length >= availableSlots) break;
-
- if (await blockIfExceedsMaxSpawns(task, 'internal')) continue;
-
- // Check if task's app is on cooldown (pipeline continuations bypass cooldown)
- const appId = task.metadata?.app;
- const isPipelineContinuation = task.metadata?.pipeline?.currentStage > 0;
- if (appId && !isPipelineContinuation) {
- const onCooldown = await isAppOnCooldown(appId, state.config.appReviewCooldownMs);
- if (onCooldown) {
- emitLog('debug', `Skipping system task ${task.id} - app ${appId} on cooldown`);
- await recordDecision(
- DECISION_TYPES.COOLDOWN_ACTIVE,
- `System task ${task.id} skipped — app ${appId} on cooldown (${Math.round(state.config.appReviewCooldownMs / 60000)}min window)`,
- { taskId: task.id, appId, cooldownMs: state.config.appReviewCooldownMs }
- );
- continue;
- }
- }
-
- const sysTask = { ...task, taskType: 'internal' };
- if (!canSpawnTask(sysTask)) {
- const sysProject = appId || '_self';
- emitLog('debug', `⏳ Queued system task ${task.id} - per-project limit reached for ${sysProject}`);
- await recordDecision(
- DECISION_TYPES.CAPACITY_FULL,
- `System task ${task.id} deferred — per-project limit (${perProjectLimit}) reached for ${sysProject}`,
- { taskId: task.id, project: sysProject, limit: perProjectLimit }
- );
- continue;
- }
- tasksToSpawn.push(sysTask);
- trackSpawn(sysTask);
- }
- }
-
- // Check if there are pending user tasks (even if on cooldown)
- // If user tasks exist, don't run self-improvement - wait for user tasks to be ready
- const hasPendingUserTasks = pendingUserTasks.length > 0;
-
- // Background: Queue eligible self-improvement tasks as system tasks
- // Only queue if there are NO pending user tasks (user tasks always take priority)
- // Skip on initial startup to avoid auto-spawning agents on fresh installs
- if (state.config.idleReviewEnabled && !hasPendingUserTasks && !initialStartup) {
- await queueEligibleImprovementTasks(state, cosTaskData);
- }
-
- // Priority 3: Mission-driven proactive tasks (if no user tasks)
- if (tasksToSpawn.length < availableSlots && !hasPendingUserTasks && state.config.proactiveMode) {
- const missionTasks = await generateMissionTasks({ maxTasks: availableSlots - tasksToSpawn.length }).catch(err => {
- emitLog('debug', `Mission task generation failed: ${err.message}`);
- return [];
- });
-
- for (const missionTask of missionTasks) {
- if (tasksToSpawn.length >= availableSlots) 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)) 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.5: Autonomous jobs are handled by registerJobSchedules() which
- // sets up individual one-shot timers per job via executeScheduledJob().
- // Previously this section also checked getDueJobs() and spawned tasks here,
- // which caused duplicate agent spawns on startup when both paths fired
- // for the same past-due job within seconds of each other.
-
- // Priority 3.6: Feature Agents (after autonomous jobs, yield to user tasks)
- if (tasksToSpawn.length < availableSlots && !hasPendingUserTasks) {
- const { getDueFeatureAgents, generateTaskFromFeatureAgent, setCurrentAgent } = await import('./featureAgents.js');
- const dueAgents = await getDueFeatureAgents().catch(err => {
- emitLog('debug', `Feature agents check failed: ${err.message}`);
- return [];
- });
- for (const fa of dueAgents) {
- if (tasksToSpawn.length >= availableSlots) break;
- const task = generateTaskFromFeatureAgent(fa);
- if (!canSpawnTask(task)) continue;
- tasksToSpawn.push(task);
- trackSpawn(task);
- // Mark agent as having a pending task to prevent duplicate spawns
- await setCurrentAgent(fa.id, task.id).catch(() => {});
- emitLog('info', `Feature agent due: ${fa.name}`, { featureAgentId: fa.id });
- }
- }
-
- // Priority 4: Only generate direct idle task if:
- // 1. Nothing to spawn
- // 2. No pending user tasks (even on cooldown)
- // 3. No system tasks queued
- if (tasksToSpawn.length === 0 && state.config.idleReviewEnabled && !hasPendingUserTasks) {
- const freshCosTasks = await getCosTasks();
- const pendingSystemTasks = freshCosTasks.autoApproved?.length || 0;
- if (pendingSystemTasks === 0) {
- const idleTask = await generateIdleReviewTask(state);
- if (idleTask && canSpawnTask(idleTask)) {
- tasksToSpawn.push(idleTask);
- trackSpawn(idleTask);
- }
- }
- }
-
- // Emit evaluation status
- const pendingUserCount = userTaskData.grouped?.pending?.length || 0;
- const inProgressCount = userTaskData.grouped?.in_progress?.length || 0;
- const pendingSystemCount = cosTaskData.grouped?.pending?.length || 0;
-
- const evalLevel = tasksToSpawn.length > 0 ? 'info' : 'debug';
- emitLog(evalLevel, `Evaluation: ${pendingUserCount} user pending, ${inProgressCount} in_progress, ${pendingSystemCount} system, spawning ${tasksToSpawn.length}`, {
- pendingUser: pendingUserCount,
- inProgress: inProgressCount,
- pendingSystem: pendingSystemCount,
- toSpawn: tasksToSpawn.length,
- availableSlots
- });
-
- // Note: Performance summaries, learning insights, and rehabilitation checks
- // are now handled by dedicated maintenance intervals (cos-performance-summary,
- // cos-learning-insights, cos-rehabilitation-check) instead of evalCount gating.
-
- // Spawn all ready tasks (up to available slots)
- for (const task of tasksToSpawn) {
- emitLog('success', `Spawning task: ${task.id} (${task.priority || 'MEDIUM'})`, {
- taskId: task.id,
- taskType: task.taskType,
- app: task.metadata?.app
- });
- cosEvents.emit('task:ready', task);
- }
-
- // Emit awaiting approval count if any
- if (cosTaskData.exists && cosTaskData.awaitingApproval?.length > 0) {
- emitLog('info', `${cosTaskData.awaitingApproval.length} tasks awaiting approval`);
- cosEvents.emit('evaluation', {
- message: 'Tasks awaiting approval',
- awaitingApproval: cosTaskData.awaitingApproval.length
- });
- }
-
- if (tasksToSpawn.length === 0) {
- const awaitingCount = cosTaskData.awaitingApproval?.length || 0;
- const idleReason = awaitingCount > 0
- ? `${awaitingCount} task(s) awaiting approval, none auto-approved`
- : hasPendingUserTasks
- ? 'User tasks exist but all on cooldown or at capacity'
- : 'No user tasks, system tasks, or idle work available';
- emitLog('debug', `No tasks to process - idle: ${idleReason}`);
- await recordDecision(
- DECISION_TYPES.IDLE,
- idleReason,
- { pendingUser: pendingUserCount, pendingSystem: pendingSystemCount, awaitingApproval: awaitingCount, runningAgents }
- );
- cosEvents.emit('evaluation', { message: 'No pending tasks to process' });
- }
-}
-
-/**
- * Generate an idle task when no user/system tasks are pending
- * Alternates between:
- * 1. Self-improvement tasks (UI analysis, security, code quality)
- * 2. App reviews for managed apps
- *
- * @param {Object} state - Current CoS state
- * @returns {Object|null} Generated task or null if nothing to do
- */
-async function generateIdleReviewTask(state) {
- if (!isImprovementEnabled(state)) {
- emitLog('debug', 'Improvement tasks are disabled');
- return null;
- }
-
- // Get all active (non-archived) managed apps (including PortOS)
- const apps = await getActiveApps().catch(() => []);
-
- if (apps.length > 0) {
- // Find next app eligible for review (not on cooldown, oldest review first)
- const nextApp = await getNextAppForReview(apps, state.config.appReviewCooldownMs);
-
- if (nextApp) {
- // Mark that we're starting an idle review
- await markIdleReviewStarted();
- await markAppReviewStarted(nextApp.id, `idle-review-${Date.now()}`);
-
- // Update lastIdleReview timestamp
- await withStateLock(async () => {
- const s = await loadState();
- s.stats.lastIdleReview = new Date().toISOString();
- await saveState(s);
- });
-
- emitLog('info', `Generating improvement task for ${nextApp.name}`, { appId: nextApp.id });
- return await generateManagedAppImprovementTask(nextApp, state);
- }
- }
-
- emitLog('debug', 'No idle tasks available');
- return null;
-}
-
-/**
- * Queue eligible self-improvement and app improvement tasks as system tasks
- * Called during every evaluation to ensure system tasks are queued even when user tasks exist
- * Tasks are queued to COS-TASKS.md and will be picked up in Priority 2
- */
-async function queueEligibleImprovementTasks(state, cosTaskData) {
- const { getNextTaskType, recordExecution } = await import('./taskSchedule.js');
-
- if (!isImprovementEnabled(state)) return;
-
- // Get existing pending/in_progress system tasks to avoid duplicates
- // Also skip task types where a user-terminated blocked task exists (user intentionally killed it)
- const existingTasks = cosTaskData.tasks || [];
- const existingTaskTypes = new Set();
- // Apps that already have *any* pending/in_progress improvement task. We cap each
- // app at one queued improvement at a time to avoid a fan-out where multiple
- // improvement types pile up faster than the per-app cooldown can drain them.
- const appsWithPendingImprovement = new Set();
-
- for (const task of existingTasks) {
- const isActive = task.status === 'pending' || task.status === 'in_progress';
- const isUserTerminated = task.status === 'blocked' && task.metadata?.blockedCategory === 'user-terminated';
- if (isActive || isUserTerminated) {
- const analysisType = task.metadata?.analysisType ||
- task.metadata?.selfImprovementType ||
- task.description?.match(/\[(?:self-improvement|improvement)\]\s*(\w[\w-]*)/i)?.[1];
- const appId = task.metadata?.app;
- if (analysisType) {
- existingTaskTypes.add(appId ? `app:${appId}:${analysisType}` : analysisType);
- }
- }
- if (isActive && task.metadata?.app && !isRecoveryTask(task)) {
- appsWithPendingImprovement.add(task.metadata.app);
- }
- }
-
- let queued = 0;
-
- // Load the activity snapshot ONCE before the per-app loop. Both the
- // cooldown gate and the rotation `lastType` lookup are derived from
- // `data/app-activity.json`; before this hoist, each app paid two
- // separate disk reads (one via `isAppOnCooldown` + one via
- // `getAppActivityById`), so a 10-app deployment did 20 reads of the
- // same file per scheduler tick. With the snapshot pinned, the cost
- // is O(1) read per `queueEligibleImprovementTasks` invocation. Falls
- // back to an empty `apps` map on disk error so the loop's per-app
- // lookups uniformly return `undefined` (both gates treat that as
- // "no activity yet — not on cooldown, no last type").
- const activitySnapshot = await loadAppActivity().catch(() => ({ apps: {} }));
-
- // Queue eligible improvement tasks for all managed apps (including PortOS)
- const apps = await getActiveApps().catch(() => []);
- for (const app of apps) {
- // One pending improvement per app at a time — sibling types must wait
- // until the current task drains, otherwise they queue faster than they
- // can run (per-project concurrency limit + cooldown after each completion).
- if (appsWithPendingImprovement.has(app.id)) {
- emitLog('debug', `App ${app.name} already has a pending improvement task — skipping queue`);
- continue;
- }
-
- // Derive both gates from the single shared snapshot. The async
- // `isAppOnCooldown` would also work, but it loads the activity file
- // again per app — see comment on `activitySnapshot` above.
- // Optional chain on `.apps` — `loadAppActivity()` spreads
- // `DEFAULT_ACTIVITY` over the file contents, but a hand-edited
- // activity.json that explicitly sets `apps: null` (or any non-object)
- // would still surface here; both gates treat `undefined` as
- // "no activity yet."
- const appActivity = activitySnapshot.apps?.[app.id];
- if (isAppActivityOnCooldown(appActivity, state.config.appReviewCooldownMs)) continue;
-
- // Get next eligible improvement type for this app. `getNextTaskType`
- // falls back to ROTATION when nothing is time-due, and the rotation
- // pointer is derived from the `lastType` argument — without it, the
- // rotation always restarts from index 0 and starves every other
- // rotation type for the app. Mirror `generateManagedAppTask` (the
- // legacy direct-spawn caller above) which threads the per-app
- // `lastImprovementType` in.
- const lastType = appActivity?.lastImprovementType || '';
- const nextTypeResult = await getNextTaskType(app.id, lastType).catch(() => null);
- if (!nextTypeResult) continue;
- const nextType = nextTypeResult.taskType;
-
- const taskKey = `app:${app.id}:${nextType}`;
- if (existingTaskTypes.has(taskKey)) {
- emitLog('debug', `Improvement task ${nextType} for ${app.name} already queued`);
- continue;
- }
-
- // Route through the rich generator so `applyPlanIdMetadata` runs — it
- // scans open `claim/<slug>` branches + PRs and excludes in-flight slugs
- // from the pick. The old stub path skipped this and let two plan-task
- // agents claim the same slug (2026-05-21 incident). The generator
- // returns null on plan-gate / precondition skip; we silently continue.
- // Regression-pinned in cos.test.js.
- const task = await generateManagedAppImprovementTaskForType(nextType, app, state);
- if (!task) continue;
-
- // Queue-path invariants override the generator's direct-spawn defaults
- // (which use MEDIUM priority + `app-improve-*` id).
- task.priority = 'LOW';
- task.priorityValue = PRIORITY_VALUES.LOW;
- task.id = `sys-${app.id.slice(0, 8)}-${nextType}-${Date.now().toString(36)}`;
-
- // Move the generator's multi-line prompt into `metadata.context` so it
- // survives the COS-TASKS.md round-trip. The on-demand path dispatches the
- // in-memory task immediately (cosEvents.emit('task:ready', task) with the
- // unparsed object), so it never round-trips through the markdown — but
- // the queue path persists first and re-reads from disk on the next
- // `dequeueNextTask` tick. `generateTasksMarkdown` interpolates the full
- // `task.description` onto a single line (taskParser.js:268) and
- // `parseTasksMarkdown` only matches the first line of a `- [ ]` block —
- // so any newline in `description` corrupts the file (stray `## Phase`
- // lines become section headers, `- ` lines become new tasks) AND silently
- // strips the Phase 1–7 instructions on the re-read. `metadata.context` is
- // newline-escaped via `escapeNewlines`/`unescapeNewlines` (JSON-sentinel
- // encoding) so it round-trips losslessly. The agent prompt builder
- // (`cos-agent-briefing.md` + the built-in fallback in
- // `agentPromptBuilder.js`) renders both `task.description` AND
- // `task.metadata.context` into the agent's prompt, so the agent still
- // sees the full Phase 1–7 body.
- if (typeof task.description === 'string' && task.description.includes('\n')) {
- task.metadata = task.metadata || {};
- task.metadata.context = task.description;
- task.description = firstLine(task.description);
- }
-
- const newTask = await addTask(task, 'internal', { raw: true });
- if (newTask?.duplicate) continue;
-
- await recordExecution(`task:${nextType}`, app.id);
-
- emitLog('info', `Queued improvement task: ${nextType} for ${app.name}`, { taskId: newTask.id, appId: app.id });
- existingTaskTypes.add(taskKey);
- appsWithPendingImprovement.add(app.id);
- queued++;
-
- // Only queue one task per app per evaluation to avoid flooding
- }
-
- if (queued > 0) {
- emitLog('info', `Queued ${queued} improvement task(s) to system tasks`);
- }
-}
-
-// Unified improvement task types (rotates through these)
-// Organized by goal priority from GOALS.md
-const IMPROVEMENT_TYPES = [
- // Goal 1: Codebase Quality
- 'ui-bugs',
- 'mobile-responsive',
- 'security',
- 'code-quality',
- 'console-errors',
- 'performance',
- // Goal 2: Self-Improvement
- 'test-coverage',
- 'error-handling',
- 'typing',
- // Goal 3: Documentation
- 'documentation',
- // Goal 4: User Engagement
- 'feature-ideas',
- 'plan-task',
- // Goal 5: System Health
- 'accessibility',
- 'dependency-updates',
- 'release-check'
-];
-// Backward compat alias
-const SELF_IMPROVEMENT_TYPES = IMPROVEMENT_TYPES;
-
-/**
- * Generate a self-improvement task for PortOS itself
- * Uses Playwright and Opus to analyze and fix issues
- *
- * Enhanced with adaptive learning and configurable intervals:
- * - Respects per-task-type interval settings (daily, weekly, once, etc.)
- * - Skips task types with consistently poor success rates
- * - Logs learning-based recommendations
- * - Falls back to next available task type if current is skipped
- * - Checks for on-demand task requests first
- */
-async function generateSelfImprovementTask(state) {
- // Import task schedule service dynamically to avoid circular dependency
- const taskSchedule = await import('./taskSchedule.js');
-
- // First, check for any on-demand task requests (no category filter — unified)
- const onDemandRequests = await taskSchedule.getOnDemandRequests();
- const selfRequests = onDemandRequests.filter(r => !r.appId);
-
- if (selfRequests.length > 0) {
- const request = selfRequests[0];
- await taskSchedule.clearOnDemandRequest(request.id);
- emitLog('info', `Processing on-demand task request: ${request.taskType}`, { requestId: request.id });
-
- // Record execution and generate the requested task
- await taskSchedule.recordExecution(`task:${request.taskType}`);
-
- // Update state
- await withStateLock(async () => {
- const s = await loadState();
- s.stats.lastSelfImprovement = new Date().toISOString();
- s.stats.lastSelfImprovementType = request.taskType;
- await saveState(s);
- });
-
- return await generateSelfImprovementTaskForType(request.taskType, state);
- }
-
- // Use the schedule service to determine the next task type
- const lastType = state.stats.lastSelfImprovementType || '';
- const nextTypeResult = await taskSchedule.getNextTaskType(null, lastType);
-
- if (!nextTypeResult) {
- emitLog('debug', 'No improvement tasks are eligible to run based on schedule');
- await recordDecision(
- DECISION_TYPES.NOT_DUE,
- 'No improvement tasks are eligible based on schedule',
- {}
- );
- return null;
- }
-
- let nextType = nextTypeResult.taskType;
- const selectionReason = nextTypeResult.reason;
-
- // Additional check: skip if learning data suggests poor performance
- const taskTypeKey = `task:${nextType}`;
- const cooldownInfo = await getAdaptiveCooldownMultiplier(taskTypeKey).catch(() => ({ skip: false }));
-
- if (cooldownInfo.skip) {
- emitLog('warn', `Skipping ${nextType} - poor success rate (${cooldownInfo.successRate}% after ${cooldownInfo.completed} attempts)`, {
- taskType: nextType,
- successRate: cooldownInfo.successRate,
- completed: cooldownInfo.completed,
- reason: cooldownInfo.reason
- });
-
- // Record the skip decision
- await recordDecision(
- DECISION_TYPES.TASK_SKIPPED,
- `Poor success rate (${cooldownInfo.successRate}% after ${cooldownInfo.completed} attempts)`,
- { taskType: nextType, successRate: cooldownInfo.successRate, attempts: cooldownInfo.completed }
- );
-
- // Try to find another eligible task type
- const dueTasks = await taskSchedule.getDueTasks();
- const alternativeTask = dueTasks.find(t => t.taskType !== nextType);
-
- if (alternativeTask) {
- const originalType = nextType;
- nextType = alternativeTask.taskType;
- emitLog('info', `Switched to alternative task type: ${nextType}`);
-
- // Record the switch decision
- await recordDecision(
- DECISION_TYPES.TASK_SWITCHED,
- `Switched from ${originalType} to ${nextType}`,
- { fromTask: originalType, toTask: nextType, reason: 'poor-success-rate' }
- );
- } else {
- // Fall back to the skipped types logic
- const skippedTypes = await getSkippedTaskTypes().catch(() => []);
- if (skippedTypes.length > 0) {
- skippedTypes.sort((a, b) => new Date(a.lastCompleted || 0) - new Date(b.lastCompleted || 0));
- const oldestType = skippedTypes[0].taskType.replace(/^(self-improve|app-improve|task):/, '');
- nextType = oldestType;
- emitLog('info', `Retrying ${oldestType} as it hasn't been attempted recently`);
-
- // Record rehabilitation decision
- await recordDecision(
- DECISION_TYPES.REHABILITATION,
- `Retrying ${oldestType} after period of inactivity`,
- { taskType: oldestType, reason: 'oldest-skipped-type' }
- );
- } else {
- nextType = IMPROVEMENT_TYPES[0];
- }
- }
- }
-
- // Log if there's a recommendation from learning system
- if (cooldownInfo.recommendation) {
- emitLog('debug', `Learning insight for ${nextType}: ${cooldownInfo.recommendation}`, {
- taskType: nextType,
- multiplier: cooldownInfo.multiplier
- });
- }
-
- // Record execution in the schedule service
- await taskSchedule.recordExecution(`task:${nextType}`);
-
- // Update state with new timestamp and type
- await withStateLock(async () => {
- const s = await loadState();
- s.stats.lastSelfImprovement = new Date().toISOString();
- s.stats.lastSelfImprovementType = nextType;
- await saveState(s);
- });
-
- emitLog('info', `Generating improvement task: ${nextType} (${selectionReason})`);
-
- // Record task selection decision
- await recordDecision(
- DECISION_TYPES.TASK_SELECTED,
- `Selected ${nextType} for improvement`,
- {
- taskType: nextType,
- reason: selectionReason,
- multiplier: cooldownInfo.multiplier,
- successRate: cooldownInfo.successRate
- }
- );
-
- // Get task descriptions from the centralized helper function
- const taskDescriptions = getSelfImprovementTaskDescriptions();
-
- return await generateSelfImprovementTaskForType(nextType, state, taskDescriptions);
-}
-
-/**
- * Resolve auto-approval for a task based on confidence scoring.
- * Returns { autoApproved, approvalRequired } ready to spread into task objects.
- */
-async function resolveConfidenceApproval(state, taskTypeKey, logLabel) {
- const config = state?.config?.confidenceAutoApproval ?? {};
- if (config.enabled === false) return { autoApproved: true, approvalRequired: false };
-
- const confidence = await getTaskTypeConfidence(taskTypeKey, config);
- if (!confidence.autoApprove) {
- emitLog('info', `🔒 ${logLabel} requires approval (${confidence.reason})`, {}, '[Confidence]');
- }
- return { autoApproved: confidence.autoApprove, approvalRequired: !confidence.autoApprove };
-}
-
-/**
- * Helper function to generate a self-improvement task for a specific type
- * Used by both normal rotation and on-demand task requests
- */
-async function generateSelfImprovementTaskForType(taskType, state, taskDescriptions = null) {
- const taskSchedule = await import('./taskSchedule.js');
- const interval = await taskSchedule.getTaskInterval(taskType);
-
- // Get the effective prompt (custom or default)
- const description = await taskSchedule.getTaskPrompt(taskType);
-
- const metadata = {
- analysisType: taskType,
- autoGenerated: true,
- selfImprovement: true
- };
-
- // Apply sanitized task-type-specific metadata from schedule config (e.g., useWorktree, simplify)
- const sanitizedMeta = sanitizeTaskMetadata(interval.taskMetadata);
- if (sanitizedMeta) {
- Object.assign(metadata, sanitizedMeta);
- }
-
- // Use configured model/provider if specified, otherwise use default
- if (interval.providerId) {
- metadata.provider = interval.providerId;
- metadata.providerId = interval.providerId;
- }
- if (interval.model) {
- metadata.model = interval.model;
- } else {
- metadata.model = 'claude-opus-4-5-20251101';
- }
-
- const approval = await resolveConfidenceApproval(state, `self-improve:${taskType}`, `Task self-improve:${taskType}`);
-
- const task = {
- id: `self-improve-${taskType}-${Date.now().toString(36)}`,
- status: 'pending',
- priority: 'MEDIUM',
- priorityValue: PRIORITY_VALUES['MEDIUM'],
- description,
- metadata,
- taskType: 'internal',
- ...approval
- };
-
- return task;
-}
-
-/**
- * Get task descriptions for all self-improvement types
- * Extracted for reuse by on-demand task generation
- */
-function getSelfImprovementTaskDescriptions() {
- return {
- 'ui-bugs': `[Self-Improvement] UI Bug Analysis
-
-Use Playwright MCP (browser_navigate, browser_snapshot, browser_console_messages) to analyze PortOS UI:
-
-1. Navigate to ${PORTOS_UI_URL}/
-2. Check each main route: /, /apps, /cos, /cos/tasks, /cos/agents, /devtools, /devtools/history, /providers, /usage
-3. For each route:
- - Take a browser_snapshot to see the page structure
- - Check browser_console_messages for JavaScript errors
- - Look for broken UI elements, missing data, failed requests
-4. Fix any bugs found in the React components or API routes
-5. Run tests and commit changes
-
-Use model: claude-opus-4-5-20251101 for thorough analysis`,
-
- 'mobile-responsive': `[Self-Improvement] Mobile Responsiveness Analysis
-
-Use Playwright MCP to test PortOS at different viewport sizes:
-
-1. browser_resize to mobile (375x812), then navigate to ${PORTOS_UI_URL}/
-2. Take browser_snapshot and analyze for:
- - Text overflow or truncation
- - Buttons too small to tap (< 44px)
- - Horizontal scrolling issues
- - Elements overlapping
- - Navigation usability
-3. Repeat at tablet (768x1024) and desktop (1440x900)
-4. Fix Tailwind CSS responsive classes (sm:, md:, lg:) as needed
-5. Test fixes and commit changes
-
-Focus on these routes: /cos, /cos/tasks, /devtools, /providers
-
-Use model: claude-opus-4-5-20251101 for comprehensive fixes`,
-
- 'security': `[Self-Improvement] Security Audit
-
-Analyze PortOS codebase for security vulnerabilities:
-
-1. Review server/routes/*.js for:
- - Command injection in exec/spawn calls
- - Path traversal in file operations
- - Missing input validation
- - XSS in rendered content
-
-2. Review server/services/*.js for:
- - Unsafe eval() or Function()
- - Hardcoded credentials
- - SQL/NoSQL injection
-
-3. Review client/src/ for:
- - XSS vulnerabilities in React
- - Sensitive data in localStorage
- - CSRF protection
-
-4. Check server/lib/commandAllowlist.js is comprehensive
-
-Fix any vulnerabilities and commit with security advisory notes.
-
-Use model: claude-opus-4-5-20251101 for thorough security analysis`,
-
- 'code-quality': `[Self-Improvement] Code Quality Review
-
-Analyze PortOS codebase for maintainability:
-
-1. Find DRY violations - similar code in multiple places
-2. Identify functions >50 lines that should be split
-3. Look for missing error handling
-4. Find dead code and unused imports
-5. Check for console.log that should be removed
-6. Look for TODO/FIXME that need addressing
-
-Focus on:
-- server/services/*.js
-- client/src/pages/*.jsx
-- client/src/components/*.jsx
-
-Refactor issues found and commit improvements.
-
-Use model: claude-opus-4-5-20251101 for quality refactoring`,
-
- 'accessibility': `[Self-Improvement] Accessibility Audit
-
-Use Playwright MCP to audit PortOS accessibility:
-
-1. Navigate to ${PORTOS_UI_URL}/
-2. Use browser_snapshot to get accessibility tree
-3. Check each main route for:
- - Missing ARIA labels
- - Missing alt text on images
- - Insufficient color contrast
- - Keyboard navigation issues
- - Focus indicators
-
-4. Fix accessibility issues in React components
-5. Add appropriate aria-* attributes
-6. Test and commit changes
-
-Use model: claude-opus-4-5-20251101 for comprehensive a11y fixes`,
-
- 'console-errors': `[Self-Improvement] Console Error Investigation
-
-Use Playwright MCP to find and fix console errors:
-
-1. Navigate to ${PORTOS_UI_URL}/
-2. Call browser_console_messages with level: "error"
-3. Visit each route and capture errors:
- - /, /apps, /cos, /cos/tasks, /cos/agents
- - /devtools, /devtools/history, /devtools/runner
- - /providers, /usage, /prompts
-
-4. For each error:
- - Identify the source file and line
- - Understand the root cause
- - Implement a fix
-
-5. Test fixes and commit changes
-
-Use model: claude-opus-4-5-20251101 for thorough debugging`,
-
- 'performance': `[Self-Improvement] Performance Analysis
-
-Analyze PortOS for performance issues:
-
-1. Review React components for:
- - Unnecessary re-renders
- - Missing useMemo/useCallback
- - Large component files that should be split
-
-2. Review server code for:
- - N+1 query patterns
- - Missing caching opportunities
- - Inefficient file operations
-
-3. Review client bundle for:
- - Missing code splitting
- - Large dependencies that could be tree-shaken
-
-4. Check Socket.IO for:
- - Event handler memory leaks
- - Unnecessary broadcasts
-
-Optimize and commit improvements.
-
-Use model: claude-opus-4-5-20251101 for performance optimization`,
-
- 'test-coverage': `[Self-Improvement] Improve Test Coverage
-
-Analyze and improve test coverage for PortOS:
-
-1. Check existing tests in server/tests/ and client/tests/
-2. Identify untested critical paths:
- - API routes without tests
- - Services with complex logic
- - Error handling paths
-
-3. Add tests for:
- - CoS task evaluation logic
- - Agent spawning and lifecycle
- - Socket.IO event handlers
- - API endpoints
-
-4. Ensure tests:
- - Follow existing patterns
- - Use appropriate mocks
- - Test edge cases
-
-5. Run npm test to verify all tests pass
-6. Commit test additions with clear message describing what's covered
-
-Use model: claude-opus-4-5-20251101 for comprehensive test design`,
-
- 'documentation': `[Self-Improvement] Update Documentation
-
-Review and improve PortOS documentation:
-
-1. Update PLAN.md:
- - Remove completed milestones from PLAN.md outright (do NOT archive to a DONE.md — that file is retired; \`git log\` and \`.changelog/\` are the audit trail)
- - Add any new features implemented as entries in \`.changelog/NEXT.md\` (mirror the prose style of recent entries)
- - Keep PLAN.md focused on next actions and future work
-
-2. Check docs/ folder:
- - Are all features documented?
- - Is the information current?
- - Add any missing guides
-
-3. Review code comments:
- - Add JSDoc to exported functions
- - Document complex algorithms
- - Explain non-obvious code
-
-4. Update README.md if needed:
- - Installation instructions
- - Quick start guide
- - Feature overview
-
-5. Consider adding:
- - Architecture diagrams
- - API documentation
- - Troubleshooting guide
-
-Commit documentation improvements.
-
-Use model: claude-opus-4-5-20251101 for clear documentation`,
-
- 'feature-ideas': `[Self-Improvement] Implement a Feature Idea
-
-Your goal is to implement ONE feature.
-
-## Research Phase
-
-1. Read GOALS.md for context on user goals and priorities
-2. Read PLAN.md for the current roadmap and planned work (next actions, audit findings, future ideas)
-3. Skim recent \`.changelog/\` entries and \`git log\` to understand what has already shipped (avoid re-implementing existing features)
-4. Search for existing feature idea documents:
- - Check .planning/research/FEATURES.md for planned features
- - Check .planning/ directory for any feature specs or research docs
- - Check data/COS-GOALS.md for CoS-specific goals
-5. Review recent completed tasks to understand what's already been done
-6. Review recent git log to see what's been implemented recently
-
-## Selection Phase
-
-7. Choose ONE feature to implement that:
- - Aligns with GOALS.md priorities
- - Is NOT already shipped per recent \`.changelog/\` entries or \`git log\` (avoid re-implementing shipped features)
- - Is NOT already planned in PLAN.md (avoid duplicating roadmap work)
- - Is NOT already documented in existing feature idea files
- - Is a small, self-contained improvement (completable in one session)
- - Saves user time, improves developer experience, or makes CoS more helpful
-
-## Implementation Phase
-
-8. Implement the feature:
- - Write clean, tested code
- - Follow existing patterns in the codebase
- - Run tests to ensure nothing is broken
-
-9. **Review your changed code for reuse, quality, and efficiency** (DRY, dead code, naming, simpler equivalents, missed edge cases) and fix any findings. Claude Code can run \`/simplify\` for this pass; on other CLIs, do the equivalent diff review by hand.
-
-10. Commit with a clear description of the feature and rationale
-
-Use model: claude-opus-4-5-20251101 for creative feature development`,
-
- 'dependency-updates': `[Self-Improvement] Dependency Updates and Security Audit
-
-Check PortOS dependencies for updates and security vulnerabilities:
-
-1. Run npm audit in both server/ and client/ directories
-2. Check for outdated packages with npm outdated
-3. Review CRITICAL and HIGH severity vulnerabilities
-4. For each vulnerability:
- - Assess the actual risk (is the vulnerable code path used?)
- - Check if an update is available
- - Test that updates don't break functionality
-
-5. Update dependencies carefully:
- - Update patch versions first (safest)
- - Then minor versions
- - Major versions need more careful review
-
-6. After updating:
- - Run npm test in server/
- - Run npm run build in client/
- - Verify the app starts correctly
-
-7. Commit with clear changelog of what was updated and why
-
-IMPORTANT: Only update one major version bump at a time. If multiple major updates are needed, create separate commits for each.
-
-Use model: claude-opus-4-5-20251101 for thorough security analysis`
- };
-}
-
-/**
- * Generate a comprehensive self-improvement task for a managed app
- * Rotates through analysis types similar to PortOS self-improvement
- *
- * Enhanced with configurable intervals:
- * - Respects per-task-type interval settings (daily, weekly, once per app, etc.)
- * - Checks for on-demand task requests first
- * - Records execution history for interval tracking
- *
- * @param {Object} app - The managed app object
- * @param {Object} state - Current CoS state
- * @returns {Object} Generated task
- */
-/**
- * Check if a pipeline stage's precondition is met.
- * Supports { fileExists: 'path' } and { fileNotExists: 'path' }.
- * Paths are relative to repoPath.
- */
-export function checkStagePrecondition(stage, repoPath) {
- const pre = stage?.precondition;
- if (!pre || !repoPath) return { passed: true };
- if (pre.fileExists) {
- const fullPath = join(repoPath, pre.fileExists);
- if (!existsSync(fullPath)) return { passed: false, reason: `${pre.fileExists} does not exist` };
- }
- if (pre.fileNotExists) {
- const fullPath = join(repoPath, pre.fileNotExists);
- if (existsSync(fullPath)) return { passed: false, reason: `${pre.fileNotExists} already exists` };
- }
- return { passed: true };
-}
-
-/**
- * Check stage 0 precondition after pipeline initialization.
- * Returns true if the task should be skipped (precondition failed).
- */
-function shouldSkipForPrecondition(metadata, app, analysisType) {
- const stage0 = metadata.pipeline?.stages?.[0];
- if (!stage0?.precondition) return false;
- const check = checkStagePrecondition(stage0, app.repoPath);
- if (!check.passed) {
- emitLog('info', `⏭️ Skipping ${analysisType} for ${app.name}: ${check.reason}`, { appId: app.id, analysisType });
- return true;
- }
- return false;
-}
-
-/**
- * Initialize pipeline runtime state on metadata if pipeline stages are configured.
- * Mutates the metadata object in place.
- */
-function initializePipelineMetadata(metadata) {
- if (!metadata.pipeline?.stages?.length) return;
- metadata.pipeline = {
- ...metadata.pipeline,
- id: `pipeline-${Date.now().toString(36)}`,
- currentStage: 0,
- stageResults: [],
- previousStageAgentId: null,
- status: 'running'
- };
- const stage0 = metadata.pipeline.stages[0];
- if (stage0.readOnly !== undefined) {
- metadata.readOnly = stage0.readOnly;
- }
- // Propagate stage 0's provider/model so the first agent uses per-stage config
- if (stage0.model) metadata.model = stage0.model;
- if (stage0.providerId) {
- metadata.provider = stage0.providerId;
- metadata.providerId = stage0.providerId;
- }
- // Save task-level defaults and apply stage 0 overrides in one pass
- // Read-only stages default flags to false to prevent worktree/PR/simplify on review-only stages
- metadata.pipeline.taskDefaults = {};
- const stageReadOnly = stage0.readOnly ?? false;
- for (const flag of PIPELINE_BEHAVIOR_FLAGS) {
- if (metadata[flag] !== undefined) metadata.pipeline.taskDefaults[flag] = metadata[flag];
- if (flag in stage0) {
- metadata[flag] = stage0[flag];
- } else if (stageReadOnly) {
- metadata[flag] = false;
- }
- }
-}
-
-// Apply app-level worktree/PR defaults only when not already set by task-type metadata.
-// openPR is applied first since it implies useWorktree — this prevents defaultUseWorktree: false
-// from blocking defaultOpenPR: true when both are app-level defaults.
-export function applyAppWorktreeDefault(metadata, app) {
- const taskTypeDisabledWorktree = metadata.useWorktree === false || metadata.useWorktree === 'false';
-
- // Apply defaultOpenPR first (since openPR implies useWorktree)
- if (metadata.openPR === undefined) {
- if (app.defaultOpenPR === true && !taskTypeDisabledWorktree) {
- metadata.openPR = true;
- metadata.useWorktree = true; // openPR implies useWorktree
- } else if (app.defaultOpenPR === false || taskTypeDisabledWorktree) {
- metadata.openPR = false;
- }
- }
-
- // Apply defaultUseWorktree (only if not already set by task-type or openPR above)
- if (metadata.useWorktree === undefined) {
- // openPR implies useWorktree — don't let app default override explicit openPR: true
- const explicitOpenPR = metadata.openPR === true || metadata.openPR === 'true';
- if (explicitOpenPR) {
- metadata.useWorktree = true;
- } else if (app.defaultUseWorktree === true) {
- metadata.useWorktree = true;
- } else if (app.defaultUseWorktree === false) {
- metadata.useWorktree = false;
- }
- }
-
- // Final invariant: openPR implies useWorktree (normalize in both directions)
- const finalOpenPR = metadata.openPR === true || metadata.openPR === 'true';
- const finalWorktreeOff = metadata.useWorktree === false || metadata.useWorktree === 'false';
- if (finalOpenPR && finalWorktreeOff) {
- // openPR wins — force useWorktree on
- metadata.useWorktree = true;
- } else if (finalWorktreeOff) {
- metadata.openPR = false;
- }
-}
-
-async function generateManagedAppImprovementTask(app, state) {
- const { getAppActivityById, updateAppActivity } = await import('./appActivity.js');
- const taskSchedule = await import('./taskSchedule.js');
-
- // First, check for any on-demand task requests for this app
- const onDemandRequests = await taskSchedule.getOnDemandRequests();
- const appRequests = onDemandRequests.filter(r => r.appId === app.id);
-
- let nextType;
- let selectionReason;
-
- if (appRequests.length > 0) {
- const request = appRequests[0];
- await taskSchedule.clearOnDemandRequest(request.id);
- nextType = request.taskType;
- selectionReason = 'on-demand';
- emitLog('info', `Processing on-demand app task request: ${nextType} for ${app.name}`, { requestId: request.id });
- } else {
- // Get last improvement type for this app
- const appActivity = await getAppActivityById(app.id);
- const lastType = appActivity?.lastImprovementType || '';
-
- // Use the schedule service to determine the next task type
- const nextTypeResult = await taskSchedule.getNextTaskType(app.id, lastType);
-
- if (!nextTypeResult) {
- emitLog('info', `No app improvement tasks are eligible for ${app.name} based on schedule`);
- return null;
- }
-
- nextType = nextTypeResult.taskType;
- selectionReason = nextTypeResult.reason;
- }
-
- // Record execution in the schedule service
- await taskSchedule.recordExecution(`task:${nextType}`, app.id);
-
- // Update app activity with new type
- await updateAppActivity(app.id, {
- lastImprovementType: nextType
- });
-
- emitLog('info', `Generating improvement task for ${app.name}: ${nextType} (${selectionReason})`, { appId: app.id, analysisType: nextType });
-
- // Get interval settings to determine provider/model and pipeline config
- const interval = await taskSchedule.getTaskInterval(nextType);
-
- const metadata = {
- app: app.id,
- appName: app.name,
- repoPath: app.repoPath,
- analysisType: nextType,
- autoGenerated: true,
- comprehensiveImprovement: true
- };
-
- // Apply sanitized task-type-specific metadata from schedule config (e.g., useWorktree, simplify, pipeline)
- const sanitizedGlobalMeta = sanitizeTaskMetadata(interval.taskMetadata);
- if (sanitizedGlobalMeta) {
- Object.assign(metadata, sanitizedGlobalMeta);
- }
-
- // Apply sanitized per-app taskMetadata overrides (merge on top of global).
- // Strip managed-agent fields from the override first so an existing
- // app-level value for a now-managed field can't overwrite the global's
- // enforced default (the UI locks the toggle, the merge has to honor that).
- const appOverrides = await getAppTaskTypeOverrides(app.id);
- const strippedAppOverride = taskSchedule.stripManagedAgentOptionsFromOverride(
- nextType, appOverrides[nextType]?.taskMetadata
- );
- const sanitizedAppMeta = sanitizeTaskMetadata(strippedAppOverride);
- if (sanitizedAppMeta) {
- Object.assign(metadata, sanitizedAppMeta);
- }
-
- initializePipelineMetadata(metadata);
- if (shouldSkipForPrecondition(metadata, app, nextType)) return null;
-
- const planMeta = await applyPlanIdMetadata(nextType, app.repoPath, metadata);
- if (planMeta.skipReason) {
- emitLog('info', `Skipping ${nextType} for ${app.name}: ${planMeta.skipReason}`, { appId: app.id });
- return null;
- }
- const planConstraintBlock = buildPlanConstraintBlock(metadata.planId);
-
- const promptTemplate = metadata.pipeline?.stages
- ? await taskSchedule.getStagePrompt(nextType, 0)
- : await taskSchedule.getTaskPrompt(nextType);
- const reviewersCsv = normalizeReviewers(metadata).join(',');
- const description = promptTemplate
- .replace(/\{appName\}/g, app.name)
- .replace(/\{repoPath\}/g, app.repoPath)
- .replace(/\{appId\}/g, app.id)
- .replace(/\{reviewers\}/g, reviewersCsv)
- .replace(/\{planConstraint\}/g, () => planConstraintBlock);
-
- applyAppWorktreeDefault(metadata, app);
-
- if (interval.providerId) {
- metadata.provider = interval.providerId;
- metadata.providerId = interval.providerId;
- }
- if (interval.model) {
- metadata.model = interval.model;
- } else if (!metadata.provider) {
- // Only default to Claude when no per-stage provider overrides the selection
- metadata.model = 'claude-opus-4-5-20251101';
- }
-
- const approval = await resolveConfidenceApproval(state, `app-improve:${nextType}`, `Task app-improve:${nextType} for ${app.name}`);
-
- const task = {
- id: `app-improve-${app.id}-${nextType}-${Date.now().toString(36)}`,
- status: 'pending',
- priority: state.config.idleReviewPriority || 'MEDIUM',
- priorityValue: PRIORITY_VALUES[state.config.idleReviewPriority] || 2,
- description,
- metadata,
- taskType: 'internal',
- ...approval
- };
-
- return task;
-}
-
-/**
- * Generate a managed app improvement task for a specific type
- * Used by on-demand task processing and can be called directly
- *
- * @param {string} taskType - The type of improvement task (e.g., 'security-audit', 'code-quality')
- * @param {Object} app - The managed app object
- * @param {Object} state - Current CoS state
- * @returns {Object} Generated task
- */
-async function generateManagedAppImprovementTaskForType(taskType, app, state, { skipPreconditions = false } = {}) {
- const { updateAppActivity } = await import('./appActivity.js');
- const taskSchedule = await import('./taskSchedule.js');
-
- // NOTE: `updateAppActivity` + the "Generating improvement task" log are
- // intentionally deferred until AFTER every gate returns non-null (see end
- // of function). The original code stamped both eagerly, which was tolerable
- // when only the on-demand path called this — the user explicitly asked for
- // a task, so logging + rotation-pointer advance was correct even when the
- // generator decided not to produce one. Now `queueEligibleImprovementTasks`
- // routes through this every scheduler tick, so an eager update would (a)
- // advance the per-app rotation pointer on every skip (biasing
- // `getNextTaskType` away from a type with nothing actionable to do, but
- // also away from types that *could* run on a future tick) and (b) emit a
- // misleading "Generating improvement task" line for skipped types. The
- // single-call ordering at the bottom keeps both paths in sync — a returned
- // task means rotation advanced; a `return null` short-circuit means it
- // didn't.
-
- // Get interval settings to determine provider/model and pipeline config
- const interval = await taskSchedule.getTaskInterval(taskType);
-
- const metadata = {
- app: app.id,
- appName: app.name,
- repoPath: app.repoPath,
- analysisType: taskType,
- autoGenerated: true,
- comprehensiveImprovement: true
- };
-
- // Apply sanitized task-type-specific metadata from schedule config (e.g., useWorktree, simplify, pipeline)
- const sanitizedGlobalMeta = sanitizeTaskMetadata(interval.taskMetadata);
- if (sanitizedGlobalMeta) {
- Object.assign(metadata, sanitizedGlobalMeta);
- }
-
- // Apply sanitized per-app taskMetadata overrides (merge on top of global).
- // Strip managed-agent fields first — see comment in the sibling
- // generateManagedAppTask path for the full rationale.
- const appOverrides = await getAppTaskTypeOverrides(app.id);
- const strippedAppOverride = taskSchedule.stripManagedAgentOptionsFromOverride(
- taskType, appOverrides[taskType]?.taskMetadata
- );
- const sanitizedAppMeta = sanitizeTaskMetadata(strippedAppOverride);
- if (sanitizedAppMeta) {
- Object.assign(metadata, sanitizedAppMeta);
- }
-
- initializePipelineMetadata(metadata);
- if (!skipPreconditions && shouldSkipForPrecondition(metadata, app, taskType)) return null;
-
- const promptTemplate = metadata.pipeline?.stages
- ? await taskSchedule.getStagePrompt(taskType, 0)
- : await taskSchedule.getTaskPrompt(taskType);
-
- // reference-watch: dynamically inject {referenceData} — a Markdown chunk
- // describing each ref configured on the app + commits since lastReviewedSha.
- // The check itself fetches each upstream and persists status/lastError, so
- // a bad URL surfaces in the UI even if the agent dispatch is skipped below.
- let referenceDataBlock = '';
- if (taskType === 'reference-watch') {
- const refs = Array.isArray(app.referenceRepos) ? app.referenceRepos : [];
- if (refs.length === 0) {
- emitLog('info', `Skipping reference-watch for ${app.name}: no reference repos configured`, { appId: app.id });
- return null;
- }
- const referenceRepos = await import('./referenceRepos.js');
- const blocks = [];
- let anySuccessWithCommits = false;
- for (const ref of refs) {
- try {
- // eslint-disable-next-line no-await-in-loop
- const snapshot = await referenceRepos.checkReferenceRepo(app.id, ref.id);
- if (snapshot.commitCount > 0) {
- blocks.push(referenceRepos.formatReferenceForPrompt(ref, snapshot));
- anySuccessWithCommits = true;
- }
- } catch (err) {
- emitLog('warn', `Reference check failed for ${ref.name}: ${err.message}`, { appId: app.id, refId: ref.id });
- blocks.push(`## Reference: ${ref.name}\n\n_Check failed: ${err.message}_`);
- }
- }
- // Don't burn an agent dispatch when there's nothing actionable —
- // either every ref is up-to-date OR every ref errored. Errored refs
- // already surfaced their lastError in the UI via checkReferenceRepo,
- // so the user can fix configs without an agent involved.
- if (!anySuccessWithCommits) {
- emitLog('info', `Skipping reference-watch for ${app.name}: no refs produced reviewable commits`, { appId: app.id });
- return null;
- }
- referenceDataBlock = blocks.join('\n\n---\n\n');
- }
-
- const planMeta = await applyPlanIdMetadata(taskType, app.repoPath, metadata);
- if (planMeta.skipReason) {
- emitLog('info', `Skipping ${taskType} for ${app.name}: ${planMeta.skipReason}`, { appId: app.id });
- return null;
- }
- const planConstraintBlock = buildPlanConstraintBlock(metadata.planId);
- const reviewersCsv = normalizeReviewers(metadata).join(',');
-
- const description = promptTemplate
- .replace(/\{appName\}/g, app.name)
- .replace(/\{repoPath\}/g, app.repoPath)
- .replace(/\{appId\}/g, app.id)
- .replace(/\{reviewers\}/g, reviewersCsv)
- // Use a replacer function — String.replace with a replacement STRING
- // interprets `$&`, `$1`, etc. as backreferences. Commit subjects/authors
- // legitimately contain `$` (env-var docs, prices, awk snippets) and
- // would get mangled. The function form passes the value verbatim.
- .replace(/\{referenceData\}/g, () => referenceDataBlock)
- .replace(/\{planConstraint\}/g, () => planConstraintBlock);
-
- applyAppWorktreeDefault(metadata, app);
-
- // Use configured model/provider if specified, otherwise use default
- if (interval.providerId) {
- metadata.provider = interval.providerId;
- metadata.providerId = interval.providerId;
- }
- if (interval.model) {
- metadata.model = interval.model;
- } else if (!metadata.provider) {
- // Only default to Claude when no per-stage provider overrides the selection
- metadata.model = 'claude-opus-4-5-20251101';
- }
-
- const approval = await resolveConfidenceApproval(state, `app-improve:${taskType}`, `Task app-improve:${taskType} for ${app.name}`);
-
- // All gates passed — record the rotation-pointer advance + emit the
- // generation log. Deferred from the top of the function (see note there);
- // every `return null` above this point intentionally leaves both untouched.
- await updateAppActivity(app.id, { lastImprovementType: taskType });
- emitLog('info', `Generating improvement task for ${app.name}: ${taskType}`, { appId: app.id, analysisType: taskType });
-
- const task = {
- id: `app-improve-${app.id}-${taskType}-${Date.now().toString(36)}`,
- status: 'pending',
- priority: state.config.idleReviewPriority || 'MEDIUM',
- priorityValue: PRIORITY_VALUES[state.config.idleReviewPriority] || 2,
- description,
- metadata,
- taskType: 'internal',
- ...approval
- };
-
- return task;
-}
-
/**
* Save a generated script
*/
diff --git a/server/services/cos.test.js b/server/services/cos.test.js
index 8a90fcfc75..37af1fa043 100644
--- a/server/services/cos.test.js
+++ b/server/services/cos.test.js
@@ -36,6 +36,12 @@ import { firstLine } from './cos.js';
const __dirname = dirname(fileURLToPath(import.meta.url));
const COS_SRC = readFileSync(join(__dirname, 'cos.js'), 'utf-8');
+// The task-generation engine (evaluateTasks + the improvement/idle generators
+// + applyPlanIdMetadata) was extracted to cosTaskGenerator.js (issue-741). The
+// spawn-side scheduler (dequeueNextTask, tryImmediateSpawn, the tasks:changed
+// listener) stays in cos.js. Source-level guards below read each invariant from
+// whichever module now owns it.
+const GEN_SRC = readFileSync(join(__dirname, 'cosTaskGenerator.js'), 'utf-8');
// ─── Inline replicas of the cos.js priority + capacity slice ───────────────
@@ -592,9 +598,9 @@ describe('cos.js source — priority + capacity invariants', () => {
});
it('evaluateTasks short-circuits when availableSlots <= 0', () => {
- const fnStart = COS_SRC.indexOf('export async function evaluateTasks');
+ const fnStart = GEN_SRC.indexOf('export async function evaluateTasks');
expect(fnStart, 'evaluateTasks must exist').toBeGreaterThan(-1);
- const fnBody = extractFnBody(COS_SRC, fnStart);
+ const fnBody = extractFnBody(GEN_SRC, fnStart);
expect(fnBody).toMatch(/if\s*\(\s*availableSlots\s*<=\s*0\s*\)/);
});
@@ -631,7 +637,7 @@ describe('cos.js source — priority + capacity invariants', () => {
// is the safety net for older state.json files that pre-date the
// per-project cap. Both dequeueNextTask and evaluateTasks must keep it.
const dequeueFn = extractFnBody(COS_SRC, COS_SRC.indexOf('async function dequeueNextTask'));
- const evalFn = extractFnBody(COS_SRC, COS_SRC.indexOf('export async function evaluateTasks'));
+ const evalFn = extractFnBody(GEN_SRC, GEN_SRC.indexOf('export async function evaluateTasks'));
const pattern = /maxConcurrentAgentsPerProject\s*\|\|\s*state\.config\.maxConcurrentAgents/;
expect(dequeueFn).toMatch(pattern);
@@ -643,7 +649,7 @@ describe('cos.js source — priority + capacity invariants', () => {
// drops either fence, idle could spawn alongside autoSystem/mission and
// double-load the agent pool.
const dequeueFn = extractFnBody(COS_SRC, COS_SRC.indexOf('async function dequeueNextTask'));
- const evalFn = extractFnBody(COS_SRC, COS_SRC.indexOf('export async function evaluateTasks'));
+ const evalFn = extractFnBody(GEN_SRC, GEN_SRC.indexOf('export async function evaluateTasks'));
expect(dequeueFn).toMatch(/spawned\s*===\s*0\s*&&\s*state\.config\.idleReviewEnabled/);
expect(evalFn).toMatch(/tasksToSpawn\.length\s*===\s*0\s*&&\s*state\.config\.idleReviewEnabled/);
@@ -657,8 +663,12 @@ describe('cos.js source — priority + capacity invariants', () => {
// event-driven `dequeueNextTask` loop (the common "Run Now" path). Pin
// (a) the set is declared and (b) markAppReviewStarted is gated on it in
// each.
- for (const fnName of ['export async function evaluateTasks', 'async function dequeueNextTask']) {
- const fnBody = extractFnBody(COS_SRC, COS_SRC.indexOf(fnName));
+ // evaluateTasks now lives in cosTaskGenerator.js; dequeueNextTask stays in cos.js.
+ for (const { fnName, src } of [
+ { fnName: 'export async function evaluateTasks', src: GEN_SRC },
+ { fnName: 'async function dequeueNextTask', src: COS_SRC },
+ ]) {
+ const fnBody = extractFnBody(src, src.indexOf(fnName));
expect(
fnBody,
`${fnName} must declare a reviewStartedApps set to dedupe per-app marks`
@@ -679,9 +689,9 @@ describe('cos.js source — priority + capacity invariants', () => {
// `claim/<slug>` PR, and produced a duplicate. The fix routes the queue
// path through the shared generator so `applyPlanIdMetadata` runs and
// the full prompt + planId metadata land on the queued task.
- const fnStart = COS_SRC.indexOf('async function queueEligibleImprovementTasks');
+ const fnStart = GEN_SRC.indexOf('async function queueEligibleImprovementTasks');
expect(fnStart, 'queueEligibleImprovementTasks must exist').toBeGreaterThan(-1);
- const fnBody = extractFnBody(COS_SRC, fnStart);
+ const fnBody = extractFnBody(GEN_SRC, fnStart);
expect(
fnBody,
@@ -781,10 +791,10 @@ describe('cos.js source — priority + capacity invariants', () => {
// contains a `for (...) { try { ... } catch }` block and the
// brace-balanced scanner doesn't always match the right closer when
// there are template-literal braces nested inside.
- const fnStart = COS_SRC.indexOf('async function generateManagedAppImprovementTaskForType');
+ const fnStart = GEN_SRC.indexOf('async function generateManagedAppImprovementTaskForType');
expect(fnStart, 'generateManagedAppImprovementTaskForType must exist').toBeGreaterThan(-1);
- const fnEnd = COS_SRC.indexOf('\nasync function ', fnStart + 1);
- const fnBody = COS_SRC.slice(fnStart, fnEnd === -1 ? undefined : fnEnd);
+ const fnEnd = GEN_SRC.indexOf('\nasync function ', fnStart + 1);
+ const fnBody = GEN_SRC.slice(fnStart, fnEnd === -1 ? undefined : fnEnd);
// The updateAppActivity call must appear AFTER applyPlanIdMetadata —
// otherwise a `planMeta.skipReason` early-return still rotates the pointer.
@@ -815,13 +825,13 @@ describe('cos.js source — priority + capacity invariants', () => {
// in-flight scan in applyPlanIdMetadata must stay (it gates dispatch), but
// the planId stamp must be fenced behind PLAN_SELF_CLAIM_TASK_TYPES.
expect(
- COS_SRC,
+ GEN_SRC,
'plan-task must be registered as a self-claiming task type'
).toMatch(/PLAN_SELF_CLAIM_TASK_TYPES\s*=\s*new Set\(\[\s*'plan-task'\s*\]\)/);
- const fnStart = COS_SRC.indexOf('async function applyPlanIdMetadata');
+ const fnStart = GEN_SRC.indexOf('async function applyPlanIdMetadata');
expect(fnStart, 'applyPlanIdMetadata must exist').toBeGreaterThan(-1);
- const fnBody = extractFnBody(COS_SRC, fnStart);
+ const fnBody = extractFnBody(GEN_SRC, fnStart);
// The planId stamp must be guarded so self-claiming types never pre-pick.
expect(
diff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.js
new file mode 100644
index 0000000000..4f79a1a327
--- /dev/null
+++ b/server/services/cosTaskGenerator.js
@@ -0,0 +1,1639 @@
+/**
+ * CoS Task Generator Module
+ *
+ * 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
+ * → 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).
+ * - the PLAN.md in-flight pick helpers (`applyPlanIdMetadata`,
+ * `buildPlanConstraintBlock`) and the pipeline-precondition helpers
+ * (`checkStagePrecondition`, `shouldSkipForPrecondition`,
+ * `initializePipelineMetadata`, `applyAppWorktreeDefault`).
+ *
+ * Self-contained — it imports only sibling services (no import back to cos.js).
+ * `evaluateTasks` emits `task:ready` rather than spawning directly, so the
+ * spawn-side scheduler (`dequeueNextTask`/`tryImmediateSpawn`) stays in cos.js.
+ * The startup-skip flag is passed in as the `initialStartup` option rather than
+ * read from cos.js module state, and the paused check reads state directly.
+ */
+
+import { readFile } from 'fs/promises';
+import { existsSync } from 'fs';
+import { join } from 'path';
+import { sanitizeTaskMetadata, PIPELINE_BEHAVIOR_FLAGS, MAX_TOTAL_SPAWNS, normalizeReviewers } from '../lib/validation.js';
+import { parsePlanItems, extractAllIds, findInProgressIds, pickFirstAvailable, diagnoseUnpickablePlan } from '../lib/planIds.js';
+import { loadState, saveState, withStateLock, isImprovementEnabled, isDaemonRunning } from './cosState.js';
+import { cosEvents, emitLog } from './cosEvents.js';
+import { addTask, updateTask, getAllTasks, getCosTasks, firstLine, PRIORITY_VALUES } from './cosTaskStore.js';
+import { recordDecision, DECISION_TYPES } from './decisionLog.js';
+import { isAppOnCooldown, markAppReviewStarted, markIdleReviewStarted, getNextAppForReview, loadAppActivity, isAppActivityOnCooldown } from './appActivity.js';
+import { getActiveApps, getAppTaskTypeOverrides } from './apps.js';
+import { getAdaptiveCooldownMultiplier, getSkippedTaskTypes, getTaskTypeConfidence } from './taskLearning.js';
+import { generateProactiveTasks as generateMissionTasks } from './missions.js';
+import { isRecoveryTask } from './recoveryTasks.js';
+
+/**
+ * Block a task that has exceeded the max spawn limit. Returns true if blocked.
+ */
+async function blockIfExceedsMaxSpawns(task, taskType) {
+ const totalSpawns = Number(task.metadata?.totalSpawnCount) || 0;
+ if (totalSpawns < MAX_TOTAL_SPAWNS) return false;
+ emitLog('info', `🚫 Blocking task ${task.id} — exceeded max spawns (${totalSpawns}/${MAX_TOTAL_SPAWNS})`, { taskId: task.id });
+ await updateTask(task.id, {
+ status: 'blocked',
+ metadata: { ...task.metadata, blockedReason: `Max total spawns exceeded (${totalSpawns}/${MAX_TOTAL_SPAWNS})`, blockedCategory: 'max-spawns', blockedAt: new Date().toISOString() }
+ }, taskType).catch(err => {
+ emitLog('warn', `Failed to block task ${task.id}: ${err.message}`, { taskId: task.id });
+ });
+ return true;
+}
+
+// Task types where the scheduler reads PLAN.md to find an in-flight-aware pick.
+// `do-replan` is excluded — it assigns IDs rather than picking one off the list.
+const PLAN_PICK_TASK_TYPES = new Set(['feature-ideas', 'plan-task']);
+
+// Subset of PLAN_PICK_TASK_TYPES where the AGENT picks (and claims) its own slug
+// at execution time — mirroring the `/claim` slash command. For these, the
+// scheduler must NOT stamp `metadata.planId`: a dispatch-time pre-pick happens
+// before the agent creates its `claim/<slug>` branch (the real lock), so two
+// near-simultaneous dispatches would both target the same first-available item.
+// We still run the in-flight scan below purely as a DISPATCH GATE (skip the run
+// when nothing is pickable), but leave the actual pick to the agent's Phase 1
+// scan, which immediately precedes branch creation. The 2026-05-21 duplicate-PR
+// incident (see cos.test.js) is guarded by the full Phase 1–7 self-pick prompt,
+// not by the pre-pick. `feature-ideas` is intentionally NOT in this set — it
+// uses a scheduler-managed worktree whose branch name encodes `planId`.
+const PLAN_SELF_CLAIM_TASK_TYPES = new Set(['plan-task']);
+
+// Subset of PLAN_PICK_TASK_TYPES where the dispatch should be skipped entirely
+// when no PLAN.md item is dispatchable. `feature-ideas` is intentionally
+// excluded: it brainstorms new items when PLAN.md is empty/blocked, so it
+// must run regardless. `plan-task` is a strict executor and would just exit
+// cleanly — burning an LLM round for nothing.
+const PLAN_GATE_TASK_TYPES = new Set(['plan-task']);
+
+/**
+ * For feature-ideas / plan-task, read the target repo's PLAN.md, find which
+ * item IDs are already in flight via branch/PR scan, and pick the first
+ * available item. Mutates `metadata` in place by setting `planId` when a
+ * pick succeeds — EXCEPT for self-claiming task types (PLAN_SELF_CLAIM_TASK_TYPES),
+ * where the agent picks its own slug at execution time and the scan is used
+ * only as the dispatch gate (no `planId` stamp).
+ *
+ * Returns `{ skipReason }` so the caller can short-circuit the LLM dispatch
+ * for `plan-task` when there's literally nothing to do (empty plan, all
+ * items blocked on human input via NEEDS_INPUT/DRIFT, or all claimed
+ * elsewhere). `feature-ideas` is never gated — its job is to brainstorm
+ * from scratch when the plan is empty, so it always runs.
+ *
+ * @returns {Promise<{ skipReason: string | null }>}
+ */
+async function applyPlanIdMetadata(taskType, repoPath, metadata) {
+ if (!PLAN_PICK_TASK_TYPES.has(taskType)) return { skipReason: null };
+ if (!repoPath) return { skipReason: null };
+ const planMd = await readFile(join(repoPath, 'PLAN.md'), 'utf-8').catch(() => '');
+ const gateDispatch = PLAN_GATE_TASK_TYPES.has(taskType);
+ if (!planMd) {
+ return { skipReason: gateDispatch ? 'PLAN.md missing or empty' : null };
+ }
+ const items = parsePlanItems(planMd);
+
+ // Short-circuit on local evidence before the network round-trip to
+ // `git fetch --prune` + `gh pr list`. When every unchecked item is
+ // already blocked on human input, no in-flight scan can change that.
+ if (gateDispatch) {
+ const localOnly = diagnoseUnpickablePlan(null, new Set(), items);
+ if (localOnly) return { skipReason: localOnly };
+ }
+
+ const knownIds = new Set(extractAllIds(planMd));
+ const inFlight = await findInProgressIds(repoPath, knownIds).catch(() => new Set());
+ const pick = pickFirstAvailable(items, inFlight);
+ if (pick?.id) {
+ // Self-claiming task types pick their own slug at execution time (like
+ // `/claim`); stamping it here would pin concurrent dispatches to the same
+ // item. For them this scan only serves as the gate above.
+ if (!PLAN_SELF_CLAIM_TASK_TYPES.has(taskType)) {
+ metadata.planId = pick.id;
+ }
+ return { skipReason: null };
+ }
+ if (!gateDispatch) return { skipReason: null };
+ return { skipReason: diagnoseUnpickablePlan(null, inFlight, items) };
+}
+
+/**
+ * Build the `{planConstraint}` substitution block. Empty when no planId —
+ * the prompt's existing Phase 1 fallback (brainstorm or exit-clean) takes over.
+ */
+function buildPlanConstraintBlock(planId) {
+ if (!planId) return '';
+ return `
+## Item Constraint
+
+The scheduler has reserved PLAN.md item \`[${planId}]\` for you. You MUST work on that exact item — do not pick a different one, do not brainstorm. If the line is missing from PLAN.md, has already been checked, or carries \`<!-- NEEDS_INPUT -->\`, exit cleanly without commits or PR.
+`;
+}
+
+/**
+ * Count running agents grouped by project (app ID).
+ * Agents without an app (self-improvement, PortOS tasks) are grouped under '_self'.
+ */
+function countRunningAgentsByProject(agents) {
+ const counts = {};
+ for (const agent of Object.values(agents)) {
+ if (agent.status !== 'running') continue;
+ const project = agent.metadata?.taskApp || agent.metadata?.app || '_self';
+ counts[project] = (counts[project] || 0) + 1;
+ }
+ return counts;
+}
+
+/**
+ * Check if a task would exceed the per-project concurrency limit.
+ * Returns true if the task can be spawned (within limit), false otherwise.
+ */
+function isWithinProjectLimit(task, agentsByProject, perProjectLimit) {
+ const project = task.metadata?.app || '_self';
+ const current = agentsByProject[project] || 0;
+ return current < perProjectLimit;
+}
+
+/**
+ * Evaluate tasks and decide what to spawn
+ *
+ * Priority order:
+ * 1. User tasks (not on cooldown)
+ * 2. Auto-approved system tasks (not on cooldown)
+ * 3. Generate idle review task if no other work
+ */
+export async function evaluateTasks(options) {
+ // `initialStartup` is passed by cos.js's start() (true on the boot-time eval)
+ // so the self-improvement queue is skipped on fresh installs; all other
+ // callers omit it. Destructured from a plain options arg (not a destructuring
+ // param) so the signature carries no leading brace.
+ const { initialStartup = false } = options || {};
+ if (!isDaemonRunning()) return;
+
+ // Check if paused - skip evaluation if so
+ const paused = (await loadState()).paused || false;
+ if (paused) {
+ emitLog('debug', 'CoS is paused - skipping evaluation');
+ return;
+ }
+
+ // Update evaluation timestamp with lock to prevent race conditions
+ const state = await withStateLock(async () => {
+ const s = await loadState();
+ s.stats.lastEvaluation = new Date().toISOString();
+ await saveState(s);
+ return s;
+ });
+
+ // Get both user and CoS tasks
+ const { user: userTaskData, cos: cosTaskData } = await getAllTasks();
+
+ // Unblock tasks whose orphan-retry cooldown has expired
+ const allBlocked = [
+ ...(userTaskData.grouped?.blocked || []),
+ ...(cosTaskData.grouped?.blocked || [])
+ ];
+ for (const task of allBlocked) {
+ if (task.metadata?.blockedCategory === 'orphan-cooldown' && task.metadata?.cooldownUntil) {
+ if (new Date(task.metadata.cooldownUntil).getTime() <= Date.now()) {
+ const taskType = task.taskType || (userTaskData.grouped?.blocked?.includes(task) ? 'user' : 'internal');
+ emitLog('info', `⏰ Orphan cooldown expired for task ${task.id}, unblocking`, { taskId: task.id });
+ await updateTask(task.id, {
+ status: 'pending',
+ metadata: {
+ ...task.metadata,
+ blockedReason: undefined,
+ blockedCategory: undefined,
+ blockedAt: undefined,
+ cooldownUntil: undefined
+ }
+ }, taskType);
+ }
+ }
+ }
+
+ // Count running agents and available slots (global + per-project)
+ const runningAgentEntries = Object.values(state.agents).filter(a => a.status === 'running');
+ const runningAgents = runningAgentEntries.length;
+ const availableSlots = state.config.maxConcurrentAgents - runningAgents;
+
+ const perProjectLimit = state.config.maxConcurrentAgentsPerProject || state.config.maxConcurrentAgents;
+ const agentsByProject = countRunningAgentsByProject(state.agents);
+
+ if (availableSlots <= 0) {
+ emitLog('warn', `Max concurrent agents reached (${runningAgents}/${state.config.maxConcurrentAgents})`);
+ await recordDecision(
+ DECISION_TYPES.CAPACITY_FULL,
+ `All ${state.config.maxConcurrentAgents} agent slots occupied`,
+ { running: runningAgents, max: state.config.maxConcurrentAgents }
+ );
+ cosEvents.emit('evaluation', { message: 'Max concurrent agents reached', running: runningAgents });
+ return;
+ }
+
+ const tasksToSpawn = [];
+ // Track per-project counts including tasks we're about to spawn in this batch
+ const spawnProjectCounts = { ...agentsByProject };
+
+ // Helper: check if a task can spawn (within both global and per-project limits)
+ const canSpawnTask = (task) => {
+ if (tasksToSpawn.length >= availableSlots) return false;
+ const project = task.metadata?.app || '_self';
+ return (spawnProjectCounts[project] || 0) < perProjectLimit;
+ };
+ // Helper: track a spawned task's project
+ const trackSpawn = (task) => {
+ const project = task.metadata?.app || '_self';
+ spawnProjectCounts[project] = (spawnProjectCounts[project] || 0) + 1;
+ };
+
+ // Priority 0: On-demand task requests (highest priority - user explicitly requested these)
+ const taskSchedule = await import('./taskSchedule.js');
+ const liveSchedule = await taskSchedule.loadSchedule();
+ const onDemandRequests = Array.isArray(liveSchedule?.onDemandRequests) ? liveSchedule.onDemandRequests : [];
+
+ // Track apps already marked review-started this cycle so multiple on-demand
+ // requests for the same app don't each rewrite its activity record.
+ const reviewStartedApps = new Set();
+ if (onDemandRequests.length > 0 && tasksToSpawn.length < availableSlots) {
+ for (const request of onDemandRequests) {
+ if (tasksToSpawn.length >= availableSlots) break;
+
+ if (!isImprovementEnabled(state)) {
+ emitLog('warn', `On-demand request dropped — improvement is disabled (Config → Improve)`, { requestId: request.id, taskType: request.taskType });
+ await taskSchedule.clearOnDemandRequest(request.id);
+ continue;
+ }
+
+ // Skip if the task type was disabled or removed after queuing — parity with dequeueNextTask.
+ if (!liveSchedule.tasks[request.taskType]?.enabled) {
+ emitLog('info', `On-demand request skipped — task type '${request.taskType}' is disabled`, { requestId: request.id });
+ await taskSchedule.clearOnDemandRequest(request.id);
+ continue;
+ }
+
+ let task = null;
+ // Determine target app (if any)
+ const apps = await getActiveApps().catch(() => []);
+ let targetApp = null;
+
+ if (request.appId) {
+ targetApp = apps.find(a => a.id === request.appId);
+ if (!targetApp) {
+ emitLog('warn', `On-demand request for unknown app: ${request.appId}`, { requestId: request.id });
+ await taskSchedule.clearOnDemandRequest(request.id);
+ continue;
+ }
+ }
+
+ await taskSchedule.clearOnDemandRequest(request.id);
+
+ if (targetApp) {
+ emitLog('info', `Processing on-demand improvement: ${request.taskType} for ${targetApp.name}`, { requestId: request.id, appId: targetApp.id });
+ if (!reviewStartedApps.has(targetApp.id)) {
+ await markAppReviewStarted(targetApp.id, `on-demand-${Date.now()}`);
+ reviewStartedApps.add(targetApp.id);
+ }
+ await taskSchedule.recordExecution(`task:${request.taskType}`, targetApp.id);
+ task = await generateManagedAppImprovementTaskForType(request.taskType, targetApp, state, { skipPreconditions: true });
+ } else {
+ emitLog('info', `Processing on-demand improvement: ${request.taskType}`, { requestId: request.id });
+ await taskSchedule.recordExecution(`task:${request.taskType}`);
+ await withStateLock(async () => {
+ const s = await loadState();
+ s.stats.lastSelfImprovement = new Date().toISOString();
+ s.stats.lastSelfImprovementType = request.taskType;
+ await saveState(s);
+ });
+ task = await generateSelfImprovementTaskForType(request.taskType, state);
+ }
+
+ if (task && canSpawnTask(task)) {
+ const persisted = await addTask(task, 'internal', { raw: true });
+ if (!persisted?.duplicate) {
+ tasksToSpawn.push(task);
+ trackSpawn(task);
+ }
+ }
+ }
+ }
+
+ // Priority 1: User tasks (always run - cooldown only applies to system tasks)
+ const pendingUserTasks = userTaskData.grouped?.pending || [];
+ for (const task of pendingUserTasks) {
+ if (tasksToSpawn.length >= availableSlots) break;
+ if (await blockIfExceedsMaxSpawns(task, 'user')) continue;
+ const userTask = { ...task, taskType: 'user' };
+ if (!canSpawnTask(userTask)) {
+ const project = task.metadata?.app || '_self';
+ emitLog('debug', `⏳ Queued user task ${task.id} - per-project limit reached for ${project}`);
+ await recordDecision(
+ DECISION_TYPES.CAPACITY_FULL,
+ `User task ${task.id} deferred — per-project limit (${perProjectLimit}) reached for ${project}`,
+ { taskId: task.id, project, limit: perProjectLimit }
+ );
+ continue;
+ }
+ tasksToSpawn.push(userTask);
+ trackSpawn(userTask);
+ }
+
+ // Priority 2: Auto-approved system tasks (if slots available)
+ if (tasksToSpawn.length < availableSlots && cosTaskData.exists) {
+ const autoApproved = cosTaskData.autoApproved || [];
+ for (const task of autoApproved) {
+ if (tasksToSpawn.length >= availableSlots) break;
+
+ if (await blockIfExceedsMaxSpawns(task, 'internal')) continue;
+
+ // Check if task's app is on cooldown (pipeline continuations bypass cooldown)
+ const appId = task.metadata?.app;
+ const isPipelineContinuation = task.metadata?.pipeline?.currentStage > 0;
+ if (appId && !isPipelineContinuation) {
+ const onCooldown = await isAppOnCooldown(appId, state.config.appReviewCooldownMs);
+ if (onCooldown) {
+ emitLog('debug', `Skipping system task ${task.id} - app ${appId} on cooldown`);
+ await recordDecision(
+ DECISION_TYPES.COOLDOWN_ACTIVE,
+ `System task ${task.id} skipped — app ${appId} on cooldown (${Math.round(state.config.appReviewCooldownMs / 60000)}min window)`,
+ { taskId: task.id, appId, cooldownMs: state.config.appReviewCooldownMs }
+ );
+ continue;
+ }
+ }
+
+ const sysTask = { ...task, taskType: 'internal' };
+ if (!canSpawnTask(sysTask)) {
+ const sysProject = appId || '_self';
+ emitLog('debug', `⏳ Queued system task ${task.id} - per-project limit reached for ${sysProject}`);
+ await recordDecision(
+ DECISION_TYPES.CAPACITY_FULL,
+ `System task ${task.id} deferred — per-project limit (${perProjectLimit}) reached for ${sysProject}`,
+ { taskId: task.id, project: sysProject, limit: perProjectLimit }
+ );
+ continue;
+ }
+ tasksToSpawn.push(sysTask);
+ trackSpawn(sysTask);
+ }
+ }
+
+ // Check if there are pending user tasks (even if on cooldown)
+ // If user tasks exist, don't run self-improvement - wait for user tasks to be ready
+ const hasPendingUserTasks = pendingUserTasks.length > 0;
+
+ // Background: Queue eligible self-improvement tasks as system tasks
+ // Only queue if there are NO pending user tasks (user tasks always take priority)
+ // Skip on initial startup to avoid auto-spawning agents on fresh installs
+ if (state.config.idleReviewEnabled && !hasPendingUserTasks && !initialStartup) {
+ await queueEligibleImprovementTasks(state, cosTaskData);
+ }
+
+ // Priority 3: Mission-driven proactive tasks (if no user tasks)
+ if (tasksToSpawn.length < availableSlots && !hasPendingUserTasks && state.config.proactiveMode) {
+ const missionTasks = await generateMissionTasks({ maxTasks: availableSlots - tasksToSpawn.length }).catch(err => {
+ emitLog('debug', `Mission task generation failed: ${err.message}`);
+ return [];
+ });
+
+ for (const missionTask of missionTasks) {
+ if (tasksToSpawn.length >= availableSlots) 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)) 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.5: Autonomous jobs are handled by registerJobSchedules() which
+ // sets up individual one-shot timers per job via executeScheduledJob().
+ // Previously this section also checked getDueJobs() and spawned tasks here,
+ // which caused duplicate agent spawns on startup when both paths fired
+ // for the same past-due job within seconds of each other.
+
+ // Priority 3.6: Feature Agents (after autonomous jobs, yield to user tasks)
+ if (tasksToSpawn.length < availableSlots && !hasPendingUserTasks) {
+ const { getDueFeatureAgents, generateTaskFromFeatureAgent, setCurrentAgent } = await import('./featureAgents.js');
+ const dueAgents = await getDueFeatureAgents().catch(err => {
+ emitLog('debug', `Feature agents check failed: ${err.message}`);
+ return [];
+ });
+ for (const fa of dueAgents) {
+ if (tasksToSpawn.length >= availableSlots) break;
+ const task = generateTaskFromFeatureAgent(fa);
+ if (!canSpawnTask(task)) continue;
+ tasksToSpawn.push(task);
+ trackSpawn(task);
+ // Mark agent as having a pending task to prevent duplicate spawns
+ await setCurrentAgent(fa.id, task.id).catch(() => {});
+ emitLog('info', `Feature agent due: ${fa.name}`, { featureAgentId: fa.id });
+ }
+ }
+
+ // Priority 4: Only generate direct idle task if:
+ // 1. Nothing to spawn
+ // 2. No pending user tasks (even on cooldown)
+ // 3. No system tasks queued
+ if (tasksToSpawn.length === 0 && state.config.idleReviewEnabled && !hasPendingUserTasks) {
+ const freshCosTasks = await getCosTasks();
+ const pendingSystemTasks = freshCosTasks.autoApproved?.length || 0;
+ if (pendingSystemTasks === 0) {
+ const idleTask = await generateIdleReviewTask(state);
+ if (idleTask && canSpawnTask(idleTask)) {
+ tasksToSpawn.push(idleTask);
+ trackSpawn(idleTask);
+ }
+ }
+ }
+
+ // Emit evaluation status
+ const pendingUserCount = userTaskData.grouped?.pending?.length || 0;
+ const inProgressCount = userTaskData.grouped?.in_progress?.length || 0;
+ const pendingSystemCount = cosTaskData.grouped?.pending?.length || 0;
+
+ const evalLevel = tasksToSpawn.length > 0 ? 'info' : 'debug';
+ emitLog(evalLevel, `Evaluation: ${pendingUserCount} user pending, ${inProgressCount} in_progress, ${pendingSystemCount} system, spawning ${tasksToSpawn.length}`, {
+ pendingUser: pendingUserCount,
+ inProgress: inProgressCount,
+ pendingSystem: pendingSystemCount,
+ toSpawn: tasksToSpawn.length,
+ availableSlots
+ });
+
+ // Note: Performance summaries, learning insights, and rehabilitation checks
+ // are now handled by dedicated maintenance intervals (cos-performance-summary,
+ // cos-learning-insights, cos-rehabilitation-check) instead of evalCount gating.
+
+ // Spawn all ready tasks (up to available slots)
+ for (const task of tasksToSpawn) {
+ emitLog('success', `Spawning task: ${task.id} (${task.priority || 'MEDIUM'})`, {
+ taskId: task.id,
+ taskType: task.taskType,
+ app: task.metadata?.app
+ });
+ cosEvents.emit('task:ready', task);
+ }
+
+ // Emit awaiting approval count if any
+ if (cosTaskData.exists && cosTaskData.awaitingApproval?.length > 0) {
+ emitLog('info', `${cosTaskData.awaitingApproval.length} tasks awaiting approval`);
+ cosEvents.emit('evaluation', {
+ message: 'Tasks awaiting approval',
+ awaitingApproval: cosTaskData.awaitingApproval.length
+ });
+ }
+
+ if (tasksToSpawn.length === 0) {
+ const awaitingCount = cosTaskData.awaitingApproval?.length || 0;
+ const idleReason = awaitingCount > 0
+ ? `${awaitingCount} task(s) awaiting approval, none auto-approved`
+ : hasPendingUserTasks
+ ? 'User tasks exist but all on cooldown or at capacity'
+ : 'No user tasks, system tasks, or idle work available';
+ emitLog('debug', `No tasks to process - idle: ${idleReason}`);
+ await recordDecision(
+ DECISION_TYPES.IDLE,
+ idleReason,
+ { pendingUser: pendingUserCount, pendingSystem: pendingSystemCount, awaitingApproval: awaitingCount, runningAgents }
+ );
+ cosEvents.emit('evaluation', { message: 'No pending tasks to process' });
+ }
+}
+
+/**
+ * Generate an idle task when no user/system tasks are pending
+ * Alternates between:
+ * 1. Self-improvement tasks (UI analysis, security, code quality)
+ * 2. App reviews for managed apps
+ *
+ * @param {Object} state - Current CoS state
+ * @returns {Object|null} Generated task or null if nothing to do
+ */
+async function generateIdleReviewTask(state) {
+ if (!isImprovementEnabled(state)) {
+ emitLog('debug', 'Improvement tasks are disabled');
+ return null;
+ }
+
+ // Get all active (non-archived) managed apps (including PortOS)
+ const apps = await getActiveApps().catch(() => []);
+
+ if (apps.length > 0) {
+ // Find next app eligible for review (not on cooldown, oldest review first)
+ const nextApp = await getNextAppForReview(apps, state.config.appReviewCooldownMs);
+
+ if (nextApp) {
+ // Mark that we're starting an idle review
+ await markIdleReviewStarted();
+ await markAppReviewStarted(nextApp.id, `idle-review-${Date.now()}`);
+
+ // Update lastIdleReview timestamp
+ await withStateLock(async () => {
+ const s = await loadState();
+ s.stats.lastIdleReview = new Date().toISOString();
+ await saveState(s);
+ });
+
+ emitLog('info', `Generating improvement task for ${nextApp.name}`, { appId: nextApp.id });
+ return await generateManagedAppImprovementTask(nextApp, state);
+ }
+ }
+
+ emitLog('debug', 'No idle tasks available');
+ return null;
+}
+
+/**
+ * Queue eligible self-improvement and app improvement tasks as system tasks
+ * Called during every evaluation to ensure system tasks are queued even when user tasks exist
+ * Tasks are queued to COS-TASKS.md and will be picked up in Priority 2
+ */
+async function queueEligibleImprovementTasks(state, cosTaskData) {
+ const { getNextTaskType, recordExecution } = await import('./taskSchedule.js');
+
+ if (!isImprovementEnabled(state)) return;
+
+ // Get existing pending/in_progress system tasks to avoid duplicates
+ // Also skip task types where a user-terminated blocked task exists (user intentionally killed it)
+ const existingTasks = cosTaskData.tasks || [];
+ const existingTaskTypes = new Set();
+ // Apps that already have *any* pending/in_progress improvement task. We cap each
+ // app at one queued improvement at a time to avoid a fan-out where multiple
+ // improvement types pile up faster than the per-app cooldown can drain them.
+ const appsWithPendingImprovement = new Set();
+
+ for (const task of existingTasks) {
+ const isActive = task.status === 'pending' || task.status === 'in_progress';
+ const isUserTerminated = task.status === 'blocked' && task.metadata?.blockedCategory === 'user-terminated';
+ if (isActive || isUserTerminated) {
+ const analysisType = task.metadata?.analysisType ||
+ task.metadata?.selfImprovementType ||
+ task.description?.match(/\[(?:self-improvement|improvement)\]\s*(\w[\w-]*)/i)?.[1];
+ const appId = task.metadata?.app;
+ if (analysisType) {
+ existingTaskTypes.add(appId ? `app:${appId}:${analysisType}` : analysisType);
+ }
+ }
+ if (isActive && task.metadata?.app && !isRecoveryTask(task)) {
+ appsWithPendingImprovement.add(task.metadata.app);
+ }
+ }
+
+ let queued = 0;
+
+ // Load the activity snapshot ONCE before the per-app loop. Both the
+ // cooldown gate and the rotation `lastType` lookup are derived from
+ // `data/app-activity.json`; before this hoist, each app paid two
+ // separate disk reads (one via `isAppOnCooldown` + one via
+ // `getAppActivityById`), so a 10-app deployment did 20 reads of the
+ // same file per scheduler tick. With the snapshot pinned, the cost
+ // is O(1) read per `queueEligibleImprovementTasks` invocation. Falls
+ // back to an empty `apps` map on disk error so the loop's per-app
+ // lookups uniformly return `undefined` (both gates treat that as
+ // "no activity yet — not on cooldown, no last type").
+ const activitySnapshot = await loadAppActivity().catch(() => ({ apps: {} }));
+
+ // Queue eligible improvement tasks for all managed apps (including PortOS)
+ const apps = await getActiveApps().catch(() => []);
+ for (const app of apps) {
+ // One pending improvement per app at a time — sibling types must wait
+ // until the current task drains, otherwise they queue faster than they
+ // can run (per-project concurrency limit + cooldown after each completion).
+ if (appsWithPendingImprovement.has(app.id)) {
+ emitLog('debug', `App ${app.name} already has a pending improvement task — skipping queue`);
+ continue;
+ }
+
+ // Derive both gates from the single shared snapshot. The async
+ // `isAppOnCooldown` would also work, but it loads the activity file
+ // again per app — see comment on `activitySnapshot` above.
+ // Optional chain on `.apps` — `loadAppActivity()` spreads
+ // `DEFAULT_ACTIVITY` over the file contents, but a hand-edited
+ // activity.json that explicitly sets `apps: null` (or any non-object)
+ // would still surface here; both gates treat `undefined` as
+ // "no activity yet."
+ const appActivity = activitySnapshot.apps?.[app.id];
+ if (isAppActivityOnCooldown(appActivity, state.config.appReviewCooldownMs)) continue;
+
+ // Get next eligible improvement type for this app. `getNextTaskType`
+ // falls back to ROTATION when nothing is time-due, and the rotation
+ // pointer is derived from the `lastType` argument — without it, the
+ // rotation always restarts from index 0 and starves every other
+ // rotation type for the app. Mirror `generateManagedAppTask` (the
+ // legacy direct-spawn caller above) which threads the per-app
+ // `lastImprovementType` in.
+ const lastType = appActivity?.lastImprovementType || '';
+ const nextTypeResult = await getNextTaskType(app.id, lastType).catch(() => null);
+ if (!nextTypeResult) continue;
+ const nextType = nextTypeResult.taskType;
+
+ const taskKey = `app:${app.id}:${nextType}`;
+ if (existingTaskTypes.has(taskKey)) {
+ emitLog('debug', `Improvement task ${nextType} for ${app.name} already queued`);
+ continue;
+ }
+
+ // Route through the rich generator so `applyPlanIdMetadata` runs — it
+ // scans open `claim/<slug>` branches + PRs and excludes in-flight slugs
+ // from the pick. The old stub path skipped this and let two plan-task
+ // agents claim the same slug (2026-05-21 incident). The generator
+ // returns null on plan-gate / precondition skip; we silently continue.
+ // Regression-pinned in cos.test.js.
+ const task = await generateManagedAppImprovementTaskForType(nextType, app, state);
+ if (!task) continue;
+
+ // Queue-path invariants override the generator's direct-spawn defaults
+ // (which use MEDIUM priority + `app-improve-*` id).
+ task.priority = 'LOW';
+ task.priorityValue = PRIORITY_VALUES.LOW;
+ task.id = `sys-${app.id.slice(0, 8)}-${nextType}-${Date.now().toString(36)}`;
+
+ // Move the generator's multi-line prompt into `metadata.context` so it
+ // survives the COS-TASKS.md round-trip. The on-demand path dispatches the
+ // in-memory task immediately (cosEvents.emit('task:ready', task) with the
+ // unparsed object), so it never round-trips through the markdown — but
+ // the queue path persists first and re-reads from disk on the next
+ // `dequeueNextTask` tick. `generateTasksMarkdown` interpolates the full
+ // `task.description` onto a single line (taskParser.js:268) and
+ // `parseTasksMarkdown` only matches the first line of a `- [ ]` block —
+ // so any newline in `description` corrupts the file (stray `## Phase`
+ // lines become section headers, `- ` lines become new tasks) AND silently
+ // strips the Phase 1–7 instructions on the re-read. `metadata.context` is
+ // newline-escaped via `escapeNewlines`/`unescapeNewlines` (JSON-sentinel
+ // encoding) so it round-trips losslessly. The agent prompt builder
+ // (`cos-agent-briefing.md` + the built-in fallback in
+ // `agentPromptBuilder.js`) renders both `task.description` AND
+ // `task.metadata.context` into the agent's prompt, so the agent still
+ // sees the full Phase 1–7 body.
+ if (typeof task.description === 'string' && task.description.includes('\n')) {
+ task.metadata = task.metadata || {};
+ task.metadata.context = task.description;
+ task.description = firstLine(task.description);
+ }
+
+ const newTask = await addTask(task, 'internal', { raw: true });
+ if (newTask?.duplicate) continue;
+
+ await recordExecution(`task:${nextType}`, app.id);
+
+ emitLog('info', `Queued improvement task: ${nextType} for ${app.name}`, { taskId: newTask.id, appId: app.id });
+ existingTaskTypes.add(taskKey);
+ appsWithPendingImprovement.add(app.id);
+ queued++;
+
+ // Only queue one task per app per evaluation to avoid flooding
+ }
+
+ if (queued > 0) {
+ emitLog('info', `Queued ${queued} improvement task(s) to system tasks`);
+ }
+}
+
+// Unified improvement task types (rotates through these)
+// Organized by goal priority from GOALS.md
+const IMPROVEMENT_TYPES = [
+ // Goal 1: Codebase Quality
+ 'ui-bugs',
+ 'mobile-responsive',
+ 'security',
+ 'code-quality',
+ 'console-errors',
+ 'performance',
+ // Goal 2: Self-Improvement
+ 'test-coverage',
+ 'error-handling',
+ 'typing',
+ // Goal 3: Documentation
+ 'documentation',
+ // Goal 4: User Engagement
+ 'feature-ideas',
+ 'plan-task',
+ // Goal 5: System Health
+ 'accessibility',
+ 'dependency-updates',
+ 'release-check'
+];
+// Backward compat alias
+const SELF_IMPROVEMENT_TYPES = IMPROVEMENT_TYPES;
+
+/**
+ * Generate a self-improvement task for PortOS itself
+ * Uses Playwright and Opus to analyze and fix issues
+ *
+ * Enhanced with adaptive learning and configurable intervals:
+ * - Respects per-task-type interval settings (daily, weekly, once, etc.)
+ * - Skips task types with consistently poor success rates
+ * - Logs learning-based recommendations
+ * - Falls back to next available task type if current is skipped
+ * - Checks for on-demand task requests first
+ */
+async function generateSelfImprovementTask(state) {
+ // Import task schedule service dynamically to avoid circular dependency
+ const taskSchedule = await import('./taskSchedule.js');
+
+ // First, check for any on-demand task requests (no category filter — unified)
+ const onDemandRequests = await taskSchedule.getOnDemandRequests();
+ const selfRequests = onDemandRequests.filter(r => !r.appId);
+
+ if (selfRequests.length > 0) {
+ const request = selfRequests[0];
+ await taskSchedule.clearOnDemandRequest(request.id);
+ emitLog('info', `Processing on-demand task request: ${request.taskType}`, { requestId: request.id });
+
+ // Record execution and generate the requested task
+ await taskSchedule.recordExecution(`task:${request.taskType}`);
+
+ // Update state
+ await withStateLock(async () => {
+ const s = await loadState();
+ s.stats.lastSelfImprovement = new Date().toISOString();
+ s.stats.lastSelfImprovementType = request.taskType;
+ await saveState(s);
+ });
+
+ return await generateSelfImprovementTaskForType(request.taskType, state);
+ }
+
+ // Use the schedule service to determine the next task type
+ const lastType = state.stats.lastSelfImprovementType || '';
+ const nextTypeResult = await taskSchedule.getNextTaskType(null, lastType);
+
+ if (!nextTypeResult) {
+ emitLog('debug', 'No improvement tasks are eligible to run based on schedule');
+ await recordDecision(
+ DECISION_TYPES.NOT_DUE,
+ 'No improvement tasks are eligible based on schedule',
+ {}
+ );
+ return null;
+ }
+
+ let nextType = nextTypeResult.taskType;
+ const selectionReason = nextTypeResult.reason;
+
+ // Additional check: skip if learning data suggests poor performance
+ const taskTypeKey = `task:${nextType}`;
+ const cooldownInfo = await getAdaptiveCooldownMultiplier(taskTypeKey).catch(() => ({ skip: false }));
+
+ if (cooldownInfo.skip) {
+ emitLog('warn', `Skipping ${nextType} - poor success rate (${cooldownInfo.successRate}% after ${cooldownInfo.completed} attempts)`, {
+ taskType: nextType,
+ successRate: cooldownInfo.successRate,
+ completed: cooldownInfo.completed,
+ reason: cooldownInfo.reason
+ });
+
+ // Record the skip decision
+ await recordDecision(
+ DECISION_TYPES.TASK_SKIPPED,
+ `Poor success rate (${cooldownInfo.successRate}% after ${cooldownInfo.completed} attempts)`,
+ { taskType: nextType, successRate: cooldownInfo.successRate, attempts: cooldownInfo.completed }
+ );
+
+ // Try to find another eligible task type
+ const dueTasks = await taskSchedule.getDueTasks();
+ const alternativeTask = dueTasks.find(t => t.taskType !== nextType);
+
+ if (alternativeTask) {
+ const originalType = nextType;
+ nextType = alternativeTask.taskType;
+ emitLog('info', `Switched to alternative task type: ${nextType}`);
+
+ // Record the switch decision
+ await recordDecision(
+ DECISION_TYPES.TASK_SWITCHED,
+ `Switched from ${originalType} to ${nextType}`,
+ { fromTask: originalType, toTask: nextType, reason: 'poor-success-rate' }
+ );
+ } else {
+ // Fall back to the skipped types logic
+ const skippedTypes = await getSkippedTaskTypes().catch(() => []);
+ if (skippedTypes.length > 0) {
+ skippedTypes.sort((a, b) => new Date(a.lastCompleted || 0) - new Date(b.lastCompleted || 0));
+ const oldestType = skippedTypes[0].taskType.replace(/^(self-improve|app-improve|task):/, '');
+ nextType = oldestType;
+ emitLog('info', `Retrying ${oldestType} as it hasn't been attempted recently`);
+
+ // Record rehabilitation decision
+ await recordDecision(
+ DECISION_TYPES.REHABILITATION,
+ `Retrying ${oldestType} after period of inactivity`,
+ { taskType: oldestType, reason: 'oldest-skipped-type' }
+ );
+ } else {
+ nextType = IMPROVEMENT_TYPES[0];
+ }
+ }
+ }
+
+ // Log if there's a recommendation from learning system
+ if (cooldownInfo.recommendation) {
+ emitLog('debug', `Learning insight for ${nextType}: ${cooldownInfo.recommendation}`, {
+ taskType: nextType,
+ multiplier: cooldownInfo.multiplier
+ });
+ }
+
+ // Record execution in the schedule service
+ await taskSchedule.recordExecution(`task:${nextType}`);
+
+ // Update state with new timestamp and type
+ await withStateLock(async () => {
+ const s = await loadState();
+ s.stats.lastSelfImprovement = new Date().toISOString();
+ s.stats.lastSelfImprovementType = nextType;
+ await saveState(s);
+ });
+
+ emitLog('info', `Generating improvement task: ${nextType} (${selectionReason})`);
+
+ // Record task selection decision
+ await recordDecision(
+ DECISION_TYPES.TASK_SELECTED,
+ `Selected ${nextType} for improvement`,
+ {
+ taskType: nextType,
+ reason: selectionReason,
+ multiplier: cooldownInfo.multiplier,
+ successRate: cooldownInfo.successRate
+ }
+ );
+
+ // Get task descriptions from the centralized helper function
+ const taskDescriptions = getSelfImprovementTaskDescriptions();
+
+ return await generateSelfImprovementTaskForType(nextType, state, taskDescriptions);
+}
+
+/**
+ * Resolve auto-approval for a task based on confidence scoring.
+ * Returns { autoApproved, approvalRequired } ready to spread into task objects.
+ */
+async function resolveConfidenceApproval(state, taskTypeKey, logLabel) {
+ const config = state?.config?.confidenceAutoApproval ?? {};
+ if (config.enabled === false) return { autoApproved: true, approvalRequired: false };
+
+ const confidence = await getTaskTypeConfidence(taskTypeKey, config);
+ if (!confidence.autoApprove) {
+ emitLog('info', `🔒 ${logLabel} requires approval (${confidence.reason})`, {}, '[Confidence]');
+ }
+ return { autoApproved: confidence.autoApprove, approvalRequired: !confidence.autoApprove };
+}
+
+/**
+ * Helper function to generate a self-improvement task for a specific type
+ * Used by both normal rotation and on-demand task requests
+ */
+async function generateSelfImprovementTaskForType(taskType, state, taskDescriptions = null) {
+ const taskSchedule = await import('./taskSchedule.js');
+ const interval = await taskSchedule.getTaskInterval(taskType);
+
+ // Get the effective prompt (custom or default)
+ const description = await taskSchedule.getTaskPrompt(taskType);
+
+ const metadata = {
+ analysisType: taskType,
+ autoGenerated: true,
+ selfImprovement: true
+ };
+
+ // Apply sanitized task-type-specific metadata from schedule config (e.g., useWorktree, simplify)
+ const sanitizedMeta = sanitizeTaskMetadata(interval.taskMetadata);
+ if (sanitizedMeta) {
+ Object.assign(metadata, sanitizedMeta);
+ }
+
+ // Use configured model/provider if specified, otherwise use default
+ if (interval.providerId) {
+ metadata.provider = interval.providerId;
+ metadata.providerId = interval.providerId;
+ }
+ if (interval.model) {
+ metadata.model = interval.model;
+ } else {
+ metadata.model = 'claude-opus-4-5-20251101';
+ }
+
+ const approval = await resolveConfidenceApproval(state, `self-improve:${taskType}`, `Task self-improve:${taskType}`);
+
+ const task = {
+ id: `self-improve-${taskType}-${Date.now().toString(36)}`,
+ status: 'pending',
+ priority: 'MEDIUM',
+ priorityValue: PRIORITY_VALUES['MEDIUM'],
+ description,
+ metadata,
+ taskType: 'internal',
+ ...approval
+ };
+
+ return task;
+}
+
+/**
+ * Get task descriptions for all self-improvement types
+ * Extracted for reuse by on-demand task generation
+ */
+function getSelfImprovementTaskDescriptions() {
+ return {
+ 'ui-bugs': `[Self-Improvement] UI Bug Analysis
+
+Use Playwright MCP (browser_navigate, browser_snapshot, browser_console_messages) to analyze PortOS UI:
+
+1. Navigate to ${PORTOS_UI_URL}/
+2. Check each main route: /, /apps, /cos, /cos/tasks, /cos/agents, /devtools, /devtools/history, /providers, /usage
+3. For each route:
+ - Take a browser_snapshot to see the page structure
+ - Check browser_console_messages for JavaScript errors
+ - Look for broken UI elements, missing data, failed requests
+4. Fix any bugs found in the React components or API routes
+5. Run tests and commit changes
+
+Use model: claude-opus-4-5-20251101 for thorough analysis`,
+
+ 'mobile-responsive': `[Self-Improvement] Mobile Responsiveness Analysis
+
+Use Playwright MCP to test PortOS at different viewport sizes:
+
+1. browser_resize to mobile (375x812), then navigate to ${PORTOS_UI_URL}/
+2. Take browser_snapshot and analyze for:
+ - Text overflow or truncation
+ - Buttons too small to tap (< 44px)
+ - Horizontal scrolling issues
+ - Elements overlapping
+ - Navigation usability
+3. Repeat at tablet (768x1024) and desktop (1440x900)
+4. Fix Tailwind CSS responsive classes (sm:, md:, lg:) as needed
+5. Test fixes and commit changes
+
+Focus on these routes: /cos, /cos/tasks, /devtools, /providers
+
+Use model: claude-opus-4-5-20251101 for comprehensive fixes`,
+
+ 'security': `[Self-Improvement] Security Audit
+
+Analyze PortOS codebase for security vulnerabilities:
+
+1. Review server/routes/*.js for:
+ - Command injection in exec/spawn calls
+ - Path traversal in file operations
+ - Missing input validation
+ - XSS in rendered content
+
+2. Review server/services/*.js for:
+ - Unsafe eval() or Function()
+ - Hardcoded credentials
+ - SQL/NoSQL injection
+
+3. Review client/src/ for:
+ - XSS vulnerabilities in React
+ - Sensitive data in localStorage
+ - CSRF protection
+
+4. Check server/lib/commandAllowlist.js is comprehensive
+
+Fix any vulnerabilities and commit with security advisory notes.
+
+Use model: claude-opus-4-5-20251101 for thorough security analysis`,
+
+ 'code-quality': `[Self-Improvement] Code Quality Review
+
+Analyze PortOS codebase for maintainability:
+
+1. Find DRY violations - similar code in multiple places
+2. Identify functions >50 lines that should be split
+3. Look for missing error handling
+4. Find dead code and unused imports
+5. Check for console.log that should be removed
+6. Look for TODO/FIXME that need addressing
+
+Focus on:
+- server/services/*.js
+- client/src/pages/*.jsx
+- client/src/components/*.jsx
+
+Refactor issues found and commit improvements.
+
+Use model: claude-opus-4-5-20251101 for quality refactoring`,
+
+ 'accessibility': `[Self-Improvement] Accessibility Audit
+
+Use Playwright MCP to audit PortOS accessibility:
+
+1. Navigate to ${PORTOS_UI_URL}/
+2. Use browser_snapshot to get accessibility tree
+3. Check each main route for:
+ - Missing ARIA labels
+ - Missing alt text on images
+ - Insufficient color contrast
+ - Keyboard navigation issues
+ - Focus indicators
+
+4. Fix accessibility issues in React components
+5. Add appropriate aria-* attributes
+6. Test and commit changes
+
+Use model: claude-opus-4-5-20251101 for comprehensive a11y fixes`,
+
+ 'console-errors': `[Self-Improvement] Console Error Investigation
+
+Use Playwright MCP to find and fix console errors:
+
+1. Navigate to ${PORTOS_UI_URL}/
+2. Call browser_console_messages with level: "error"
+3. Visit each route and capture errors:
+ - /, /apps, /cos, /cos/tasks, /cos/agents
+ - /devtools, /devtools/history, /devtools/runner
+ - /providers, /usage, /prompts
+
+4. For each error:
+ - Identify the source file and line
+ - Understand the root cause
+ - Implement a fix
+
+5. Test fixes and commit changes
+
+Use model: claude-opus-4-5-20251101 for thorough debugging`,
+
+ 'performance': `[Self-Improvement] Performance Analysis
+
+Analyze PortOS for performance issues:
+
+1. Review React components for:
+ - Unnecessary re-renders
+ - Missing useMemo/useCallback
+ - Large component files that should be split
+
+2. Review server code for:
+ - N+1 query patterns
+ - Missing caching opportunities
+ - Inefficient file operations
+
+3. Review client bundle for:
+ - Missing code splitting
+ - Large dependencies that could be tree-shaken
+
+4. Check Socket.IO for:
+ - Event handler memory leaks
+ - Unnecessary broadcasts
+
+Optimize and commit improvements.
+
+Use model: claude-opus-4-5-20251101 for performance optimization`,
+
+ 'test-coverage': `[Self-Improvement] Improve Test Coverage
+
+Analyze and improve test coverage for PortOS:
+
+1. Check existing tests in server/tests/ and client/tests/
+2. Identify untested critical paths:
+ - API routes without tests
+ - Services with complex logic
+ - Error handling paths
+
+3. Add tests for:
+ - CoS task evaluation logic
+ - Agent spawning and lifecycle
+ - Socket.IO event handlers
+ - API endpoints
+
+4. Ensure tests:
+ - Follow existing patterns
+ - Use appropriate mocks
+ - Test edge cases
+
+5. Run npm test to verify all tests pass
+6. Commit test additions with clear message describing what's covered
+
+Use model: claude-opus-4-5-20251101 for comprehensive test design`,
+
+ 'documentation': `[Self-Improvement] Update Documentation
+
+Review and improve PortOS documentation:
+
+1. Update PLAN.md:
+ - Remove completed milestones from PLAN.md outright (do NOT archive to a DONE.md — that file is retired; \`git log\` and \`.changelog/\` are the audit trail)
+ - Add any new features implemented as entries in \`.changelog/NEXT.md\` (mirror the prose style of recent entries)
+ - Keep PLAN.md focused on next actions and future work
+
+2. Check docs/ folder:
+ - Are all features documented?
+ - Is the information current?
+ - Add any missing guides
+
+3. Review code comments:
+ - Add JSDoc to exported functions
+ - Document complex algorithms
+ - Explain non-obvious code
+
+4. Update README.md if needed:
+ - Installation instructions
+ - Quick start guide
+ - Feature overview
+
+5. Consider adding:
+ - Architecture diagrams
+ - API documentation
+ - Troubleshooting guide
+
+Commit documentation improvements.
+
+Use model: claude-opus-4-5-20251101 for clear documentation`,
+
+ 'feature-ideas': `[Self-Improvement] Implement a Feature Idea
+
+Your goal is to implement ONE feature.
+
+## Research Phase
+
+1. Read GOALS.md for context on user goals and priorities
+2. Read PLAN.md for the current roadmap and planned work (next actions, audit findings, future ideas)
+3. Skim recent \`.changelog/\` entries and \`git log\` to understand what has already shipped (avoid re-implementing existing features)
+4. Search for existing feature idea documents:
+ - Check .planning/research/FEATURES.md for planned features
+ - Check .planning/ directory for any feature specs or research docs
+ - Check data/COS-GOALS.md for CoS-specific goals
+5. Review recent completed tasks to understand what's already been done
+6. Review recent git log to see what's been implemented recently
+
+## Selection Phase
+
+7. Choose ONE feature to implement that:
+ - Aligns with GOALS.md priorities
+ - Is NOT already shipped per recent \`.changelog/\` entries or \`git log\` (avoid re-implementing shipped features)
+ - Is NOT already planned in PLAN.md (avoid duplicating roadmap work)
+ - Is NOT already documented in existing feature idea files
+ - Is a small, self-contained improvement (completable in one session)
+ - Saves user time, improves developer experience, or makes CoS more helpful
+
+## Implementation Phase
+
+8. Implement the feature:
+ - Write clean, tested code
+ - Follow existing patterns in the codebase
+ - Run tests to ensure nothing is broken
+
+9. **Review your changed code for reuse, quality, and efficiency** (DRY, dead code, naming, simpler equivalents, missed edge cases) and fix any findings. Claude Code can run \`/simplify\` for this pass; on other CLIs, do the equivalent diff review by hand.
+
+10. Commit with a clear description of the feature and rationale
+
+Use model: claude-opus-4-5-20251101 for creative feature development`,
+
+ 'dependency-updates': `[Self-Improvement] Dependency Updates and Security Audit
+
+Check PortOS dependencies for updates and security vulnerabilities:
+
+1. Run npm audit in both server/ and client/ directories
+2. Check for outdated packages with npm outdated
+3. Review CRITICAL and HIGH severity vulnerabilities
+4. For each vulnerability:
+ - Assess the actual risk (is the vulnerable code path used?)
+ - Check if an update is available
+ - Test that updates don't break functionality
+
+5. Update dependencies carefully:
+ - Update patch versions first (safest)
+ - Then minor versions
+ - Major versions need more careful review
+
+6. After updating:
+ - Run npm test in server/
+ - Run npm run build in client/
+ - Verify the app starts correctly
+
+7. Commit with clear changelog of what was updated and why
+
+IMPORTANT: Only update one major version bump at a time. If multiple major updates are needed, create separate commits for each.
+
+Use model: claude-opus-4-5-20251101 for thorough security analysis`
+ };
+}
+
+/**
+ * Generate a comprehensive self-improvement task for a managed app
+ * Rotates through analysis types similar to PortOS self-improvement
+ *
+ * Enhanced with configurable intervals:
+ * - Respects per-task-type interval settings (daily, weekly, once per app, etc.)
+ * - Checks for on-demand task requests first
+ * - Records execution history for interval tracking
+ *
+ * @param {Object} app - The managed app object
+ * @param {Object} state - Current CoS state
+ * @returns {Object} Generated task
+ */
+/**
+ * Check if a pipeline stage's precondition is met.
+ * Supports { fileExists: 'path' } and { fileNotExists: 'path' }.
+ * Paths are relative to repoPath.
+ */
+export function checkStagePrecondition(stage, repoPath) {
+ const pre = stage?.precondition;
+ if (!pre || !repoPath) return { passed: true };
+ if (pre.fileExists) {
+ const fullPath = join(repoPath, pre.fileExists);
+ if (!existsSync(fullPath)) return { passed: false, reason: `${pre.fileExists} does not exist` };
+ }
+ if (pre.fileNotExists) {
+ const fullPath = join(repoPath, pre.fileNotExists);
+ if (existsSync(fullPath)) return { passed: false, reason: `${pre.fileNotExists} already exists` };
+ }
+ return { passed: true };
+}
+
+/**
+ * Check stage 0 precondition after pipeline initialization.
+ * Returns true if the task should be skipped (precondition failed).
+ */
+function shouldSkipForPrecondition(metadata, app, analysisType) {
+ const stage0 = metadata.pipeline?.stages?.[0];
+ if (!stage0?.precondition) return false;
+ const check = checkStagePrecondition(stage0, app.repoPath);
+ if (!check.passed) {
+ emitLog('info', `⏭️ Skipping ${analysisType} for ${app.name}: ${check.reason}`, { appId: app.id, analysisType });
+ return true;
+ }
+ return false;
+}
+
+/**
+ * Initialize pipeline runtime state on metadata if pipeline stages are configured.
+ * Mutates the metadata object in place.
+ */
+function initializePipelineMetadata(metadata) {
+ if (!metadata.pipeline?.stages?.length) return;
+ metadata.pipeline = {
+ ...metadata.pipeline,
+ id: `pipeline-${Date.now().toString(36)}`,
+ currentStage: 0,
+ stageResults: [],
+ previousStageAgentId: null,
+ status: 'running'
+ };
+ const stage0 = metadata.pipeline.stages[0];
+ if (stage0.readOnly !== undefined) {
+ metadata.readOnly = stage0.readOnly;
+ }
+ // Propagate stage 0's provider/model so the first agent uses per-stage config
+ if (stage0.model) metadata.model = stage0.model;
+ if (stage0.providerId) {
+ metadata.provider = stage0.providerId;
+ metadata.providerId = stage0.providerId;
+ }
+ // Save task-level defaults and apply stage 0 overrides in one pass
+ // Read-only stages default flags to false to prevent worktree/PR/simplify on review-only stages
+ metadata.pipeline.taskDefaults = {};
+ const stageReadOnly = stage0.readOnly ?? false;
+ for (const flag of PIPELINE_BEHAVIOR_FLAGS) {
+ if (metadata[flag] !== undefined) metadata.pipeline.taskDefaults[flag] = metadata[flag];
+ if (flag in stage0) {
+ metadata[flag] = stage0[flag];
+ } else if (stageReadOnly) {
+ metadata[flag] = false;
+ }
+ }
+}
+
+// Apply app-level worktree/PR defaults only when not already set by task-type metadata.
+// openPR is applied first since it implies useWorktree — this prevents defaultUseWorktree: false
+// from blocking defaultOpenPR: true when both are app-level defaults.
+export function applyAppWorktreeDefault(metadata, app) {
+ const taskTypeDisabledWorktree = metadata.useWorktree === false || metadata.useWorktree === 'false';
+
+ // Apply defaultOpenPR first (since openPR implies useWorktree)
+ if (metadata.openPR === undefined) {
+ if (app.defaultOpenPR === true && !taskTypeDisabledWorktree) {
+ metadata.openPR = true;
+ metadata.useWorktree = true; // openPR implies useWorktree
+ } else if (app.defaultOpenPR === false || taskTypeDisabledWorktree) {
+ metadata.openPR = false;
+ }
+ }
+
+ // Apply defaultUseWorktree (only if not already set by task-type or openPR above)
+ if (metadata.useWorktree === undefined) {
+ // openPR implies useWorktree — don't let app default override explicit openPR: true
+ const explicitOpenPR = metadata.openPR === true || metadata.openPR === 'true';
+ if (explicitOpenPR) {
+ metadata.useWorktree = true;
+ } else if (app.defaultUseWorktree === true) {
+ metadata.useWorktree = true;
+ } else if (app.defaultUseWorktree === false) {
+ metadata.useWorktree = false;
+ }
+ }
+
+ // Final invariant: openPR implies useWorktree (normalize in both directions)
+ const finalOpenPR = metadata.openPR === true || metadata.openPR === 'true';
+ const finalWorktreeOff = metadata.useWorktree === false || metadata.useWorktree === 'false';
+ if (finalOpenPR && finalWorktreeOff) {
+ // openPR wins — force useWorktree on
+ metadata.useWorktree = true;
+ } else if (finalWorktreeOff) {
+ metadata.openPR = false;
+ }
+}
+
+async function generateManagedAppImprovementTask(app, state) {
+ const { getAppActivityById, updateAppActivity } = await import('./appActivity.js');
+ const taskSchedule = await import('./taskSchedule.js');
+
+ // First, check for any on-demand task requests for this app
+ const onDemandRequests = await taskSchedule.getOnDemandRequests();
+ const appRequests = onDemandRequests.filter(r => r.appId === app.id);
+
+ let nextType;
+ let selectionReason;
+
+ if (appRequests.length > 0) {
+ const request = appRequests[0];
+ await taskSchedule.clearOnDemandRequest(request.id);
+ nextType = request.taskType;
+ selectionReason = 'on-demand';
+ emitLog('info', `Processing on-demand app task request: ${nextType} for ${app.name}`, { requestId: request.id });
+ } else {
+ // Get last improvement type for this app
+ const appActivity = await getAppActivityById(app.id);
+ const lastType = appActivity?.lastImprovementType || '';
+
+ // Use the schedule service to determine the next task type
+ const nextTypeResult = await taskSchedule.getNextTaskType(app.id, lastType);
+
+ if (!nextTypeResult) {
+ emitLog('info', `No app improvement tasks are eligible for ${app.name} based on schedule`);
+ return null;
+ }
+
+ nextType = nextTypeResult.taskType;
+ selectionReason = nextTypeResult.reason;
+ }
+
+ // Record execution in the schedule service
+ await taskSchedule.recordExecution(`task:${nextType}`, app.id);
+
+ // Update app activity with new type
+ await updateAppActivity(app.id, {
+ lastImprovementType: nextType
+ });
+
+ emitLog('info', `Generating improvement task for ${app.name}: ${nextType} (${selectionReason})`, { appId: app.id, analysisType: nextType });
+
+ // Get interval settings to determine provider/model and pipeline config
+ const interval = await taskSchedule.getTaskInterval(nextType);
+
+ const metadata = {
+ app: app.id,
+ appName: app.name,
+ repoPath: app.repoPath,
+ analysisType: nextType,
+ autoGenerated: true,
+ comprehensiveImprovement: true
+ };
+
+ // Apply sanitized task-type-specific metadata from schedule config (e.g., useWorktree, simplify, pipeline)
+ const sanitizedGlobalMeta = sanitizeTaskMetadata(interval.taskMetadata);
+ if (sanitizedGlobalMeta) {
+ Object.assign(metadata, sanitizedGlobalMeta);
+ }
+
+ // Apply sanitized per-app taskMetadata overrides (merge on top of global).
+ // Strip managed-agent fields from the override first so an existing
+ // app-level value for a now-managed field can't overwrite the global's
+ // enforced default (the UI locks the toggle, the merge has to honor that).
+ const appOverrides = await getAppTaskTypeOverrides(app.id);
+ const strippedAppOverride = taskSchedule.stripManagedAgentOptionsFromOverride(
+ nextType, appOverrides[nextType]?.taskMetadata
+ );
+ const sanitizedAppMeta = sanitizeTaskMetadata(strippedAppOverride);
+ if (sanitizedAppMeta) {
+ Object.assign(metadata, sanitizedAppMeta);
+ }
+
+ initializePipelineMetadata(metadata);
+ if (shouldSkipForPrecondition(metadata, app, nextType)) return null;
+
+ const planMeta = await applyPlanIdMetadata(nextType, app.repoPath, metadata);
+ if (planMeta.skipReason) {
+ emitLog('info', `Skipping ${nextType} for ${app.name}: ${planMeta.skipReason}`, { appId: app.id });
+ return null;
+ }
+ const planConstraintBlock = buildPlanConstraintBlock(metadata.planId);
+
+ const promptTemplate = metadata.pipeline?.stages
+ ? await taskSchedule.getStagePrompt(nextType, 0)
+ : await taskSchedule.getTaskPrompt(nextType);
+ const reviewersCsv = normalizeReviewers(metadata).join(',');
+ const description = promptTemplate
+ .replace(/\{appName\}/g, app.name)
+ .replace(/\{repoPath\}/g, app.repoPath)
+ .replace(/\{appId\}/g, app.id)
+ .replace(/\{reviewers\}/g, reviewersCsv)
+ .replace(/\{planConstraint\}/g, () => planConstraintBlock);
+
+ applyAppWorktreeDefault(metadata, app);
+
+ if (interval.providerId) {
+ metadata.provider = interval.providerId;
+ metadata.providerId = interval.providerId;
+ }
+ if (interval.model) {
+ metadata.model = interval.model;
+ } else if (!metadata.provider) {
+ // Only default to Claude when no per-stage provider overrides the selection
+ metadata.model = 'claude-opus-4-5-20251101';
+ }
+
+ const approval = await resolveConfidenceApproval(state, `app-improve:${nextType}`, `Task app-improve:${nextType} for ${app.name}`);
+
+ const task = {
+ id: `app-improve-${app.id}-${nextType}-${Date.now().toString(36)}`,
+ status: 'pending',
+ priority: state.config.idleReviewPriority || 'MEDIUM',
+ priorityValue: PRIORITY_VALUES[state.config.idleReviewPriority] || 2,
+ description,
+ metadata,
+ taskType: 'internal',
+ ...approval
+ };
+
+ return task;
+}
+
+/**
+ * Generate a managed app improvement task for a specific type
+ * Used by on-demand task processing and can be called directly
+ *
+ * @param {string} taskType - The type of improvement task (e.g., 'security-audit', 'code-quality')
+ * @param {Object} app - The managed app object
+ * @param {Object} state - Current CoS state
+ * @returns {Object} Generated task
+ */
+async function generateManagedAppImprovementTaskForType(taskType, app, state, { skipPreconditions = false } = {}) {
+ const { updateAppActivity } = await import('./appActivity.js');
+ const taskSchedule = await import('./taskSchedule.js');
+
+ // NOTE: `updateAppActivity` + the "Generating improvement task" log are
+ // intentionally deferred until AFTER every gate returns non-null (see end
+ // of function). The original code stamped both eagerly, which was tolerable
+ // when only the on-demand path called this — the user explicitly asked for
+ // a task, so logging + rotation-pointer advance was correct even when the
+ // generator decided not to produce one. Now `queueEligibleImprovementTasks`
+ // routes through this every scheduler tick, so an eager update would (a)
+ // advance the per-app rotation pointer on every skip (biasing
+ // `getNextTaskType` away from a type with nothing actionable to do, but
+ // also away from types that *could* run on a future tick) and (b) emit a
+ // misleading "Generating improvement task" line for skipped types. The
+ // single-call ordering at the bottom keeps both paths in sync — a returned
+ // task means rotation advanced; a `return null` short-circuit means it
+ // didn't.
+
+ // Get interval settings to determine provider/model and pipeline config
+ const interval = await taskSchedule.getTaskInterval(taskType);
+
+ const metadata = {
+ app: app.id,
+ appName: app.name,
+ repoPath: app.repoPath,
+ analysisType: taskType,
+ autoGenerated: true,
+ comprehensiveImprovement: true
+ };
+
+ // Apply sanitized task-type-specific metadata from schedule config (e.g., useWorktree, simplify, pipeline)
+ const sanitizedGlobalMeta = sanitizeTaskMetadata(interval.taskMetadata);
+ if (sanitizedGlobalMeta) {
+ Object.assign(metadata, sanitizedGlobalMeta);
+ }
+
+ // Apply sanitized per-app taskMetadata overrides (merge on top of global).
+ // Strip managed-agent fields first — see comment in the sibling
+ // generateManagedAppTask path for the full rationale.
+ const appOverrides = await getAppTaskTypeOverrides(app.id);
+ const strippedAppOverride = taskSchedule.stripManagedAgentOptionsFromOverride(
+ taskType, appOverrides[taskType]?.taskMetadata
+ );
+ const sanitizedAppMeta = sanitizeTaskMetadata(strippedAppOverride);
+ if (sanitizedAppMeta) {
+ Object.assign(metadata, sanitizedAppMeta);
+ }
+
+ initializePipelineMetadata(metadata);
+ if (!skipPreconditions && shouldSkipForPrecondition(metadata, app, taskType)) return null;
+
+ const promptTemplate = metadata.pipeline?.stages
+ ? await taskSchedule.getStagePrompt(taskType, 0)
+ : await taskSchedule.getTaskPrompt(taskType);
+
+ // reference-watch: dynamically inject {referenceData} — a Markdown chunk
+ // describing each ref configured on the app + commits since lastReviewedSha.
+ // The check itself fetches each upstream and persists status/lastError, so
+ // a bad URL surfaces in the UI even if the agent dispatch is skipped below.
+ let referenceDataBlock = '';
+ if (taskType === 'reference-watch') {
+ const refs = Array.isArray(app.referenceRepos) ? app.referenceRepos : [];
+ if (refs.length === 0) {
+ emitLog('info', `Skipping reference-watch for ${app.name}: no reference repos configured`, { appId: app.id });
+ return null;
+ }
+ const referenceRepos = await import('./referenceRepos.js');
+ const blocks = [];
+ let anySuccessWithCommits = false;
+ for (const ref of refs) {
+ try {
+ // eslint-disable-next-line no-await-in-loop
+ const snapshot = await referenceRepos.checkReferenceRepo(app.id, ref.id);
+ if (snapshot.commitCount > 0) {
+ blocks.push(referenceRepos.formatReferenceForPrompt(ref, snapshot));
+ anySuccessWithCommits = true;
+ }
+ } catch (err) {
+ emitLog('warn', `Reference check failed for ${ref.name}: ${err.message}`, { appId: app.id, refId: ref.id });
+ blocks.push(`## Reference: ${ref.name}\n\n_Check failed: ${err.message}_`);
+ }
+ }
+ // Don't burn an agent dispatch when there's nothing actionable —
+ // either every ref is up-to-date OR every ref errored. Errored refs
+ // already surfaced their lastError in the UI via checkReferenceRepo,
+ // so the user can fix configs without an agent involved.
+ if (!anySuccessWithCommits) {
+ emitLog('info', `Skipping reference-watch for ${app.name}: no refs produced reviewable commits`, { appId: app.id });
+ return null;
+ }
+ referenceDataBlock = blocks.join('\n\n---\n\n');
+ }
+
+ const planMeta = await applyPlanIdMetadata(taskType, app.repoPath, metadata);
+ if (planMeta.skipReason) {
+ emitLog('info', `Skipping ${taskType} for ${app.name}: ${planMeta.skipReason}`, { appId: app.id });
+ return null;
+ }
+ const planConstraintBlock = buildPlanConstraintBlock(metadata.planId);
+ const reviewersCsv = normalizeReviewers(metadata).join(',');
+
+ const description = promptTemplate
+ .replace(/\{appName\}/g, app.name)
+ .replace(/\{repoPath\}/g, app.repoPath)
+ .replace(/\{appId\}/g, app.id)
+ .replace(/\{reviewers\}/g, reviewersCsv)
+ // Use a replacer function — String.replace with a replacement STRING
+ // interprets `$&`, `$1`, etc. as backreferences. Commit subjects/authors
+ // legitimately contain `$` (env-var docs, prices, awk snippets) and
+ // would get mangled. The function form passes the value verbatim.
+ .replace(/\{referenceData\}/g, () => referenceDataBlock)
+ .replace(/\{planConstraint\}/g, () => planConstraintBlock);
+
+ applyAppWorktreeDefault(metadata, app);
+
+ // Use configured model/provider if specified, otherwise use default
+ if (interval.providerId) {
+ metadata.provider = interval.providerId;
+ metadata.providerId = interval.providerId;
+ }
+ if (interval.model) {
+ metadata.model = interval.model;
+ } else if (!metadata.provider) {
+ // Only default to Claude when no per-stage provider overrides the selection
+ metadata.model = 'claude-opus-4-5-20251101';
+ }
+
+ const approval = await resolveConfidenceApproval(state, `app-improve:${taskType}`, `Task app-improve:${taskType} for ${app.name}`);
+
+ // All gates passed — record the rotation-pointer advance + emit the
+ // generation log. Deferred from the top of the function (see note there);
+ // every `return null` above this point intentionally leaves both untouched.
+ await updateAppActivity(app.id, { lastImprovementType: taskType });
+ emitLog('info', `Generating improvement task for ${app.name}: ${taskType}`, { appId: app.id, analysisType: taskType });
+
+ const task = {
+ id: `app-improve-${app.id}-${taskType}-${Date.now().toString(36)}`,
+ status: 'pending',
+ priority: state.config.idleReviewPriority || 'MEDIUM',
+ priorityValue: PRIORITY_VALUES[state.config.idleReviewPriority] || 2,
+ description,
+ metadata,
+ taskType: 'internal',
+ ...approval
+ };
+
+ return task;
+}