Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix(cos): add pre-spawn max-spawn guard and coerce metadata counts to Number
Adam Eivy556580424eff
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex b5f132f9a0..d7db946df8 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -6,6 +6,8 @@## Fixed+- CoS task evaluation now blocks tasks that exceeded max spawn limit before reaching spawn logic+- Metadata count fields (totalSpawnCount, failureCount, orphanRetryCount) use Number() coercion to prevent string comparison bugs- jira-status-report task now runs in PortOS context (not the app's directory) and uses the correct PortOS API endpoint- jira-status-report agents no longer attempt to commit, push, or modify files (readOnly metadata flag)- readOnly tasks skip unnecessary git pull, JIRA branch creation, and worktree setupdiff --git a/server/services/cos.js b/server/services/cos.jsindex 84ff948546..84eb00fabd 100644--- a/server/services/cos.js+++ b/server/services/cos.js@@ -44,6 +44,25 @@ const REPORTS_DIR = PATHS.reports;const SCRIPTS_DIR = PATHS.scripts;const ROOT_DIR = PATHS.root;+// Must match MAX_TOTAL_SPAWNS in subAgentSpawner.js (dynamic import avoids circular dep)+const MAX_TOTAL_SPAWNS = 5;++/**+ * 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;+}+/*** Emit a log event for UI display* Exported for use by other CoS-related services@@ -1032,6 +1051,7 @@ export async function evaluateTasks() {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';@@ -1053,6 +1073,8 @@ export async function evaluateTasks() {for (const task of autoApproved) {if (tasksToSpawn.length >= availableSlots) break;+ if (await blockIfExceedsMaxSpawns(task, 'internal')) continue;+// Check if task's app is on cooldownconst appId = task.metadata?.app;if (appId) {@@ -3495,6 +3517,7 @@ async function dequeueNextTask() {for (const task of pendingUserTasks) {if (spawned >= availableSlots) break;+ if (await blockIfExceedsMaxSpawns(task, 'user')) continue;const userTask = { ...task, taskType: 'user' };if (!canSpawn(userTask)) continue;cosEvents.emit('task:ready', userTask);@@ -3507,6 +3530,7 @@ async function dequeueNextTask() {for (const task of autoApproved) {if (spawned >= availableSlots) break;+ if (await blockIfExceedsMaxSpawns(task, 'internal')) continue;const appId = task.metadata?.app;if (appId) {const onCooldown = await isAppOnCooldown(appId, state.config.appReviewCooldownMs);diff --git a/server/services/subAgentSpawner.js b/server/services/subAgentSpawner.jsindex 2382d13857..7f194628ed 100644--- a/server/services/subAgentSpawner.js+++ b/server/services/subAgentSpawner.js@@ -1050,8 +1050,8 @@ async function resolveFailedTaskUpdate(task, errorAnalysis, agentId) {}// Non-actionable errors: track retry count and block after max retries- const failureCount = (task.metadata?.failureCount || 0) + 1;- const totalSpawns = task.metadata?.totalSpawnCount || 0;+ const failureCount = (Number(task.metadata?.failureCount) || 0) + 1;+ const totalSpawns = Number(task.metadata?.totalSpawnCount) || 0;const lastErrorCategory = errorAnalysis?.category || 'unknown';if (totalSpawns >= MAX_TOTAL_SPAWNS || failureCount >= MAX_TASK_RETRIES) {@@ -1275,7 +1275,7 @@ export async function spawnAgentForTask(task) {}// Check total spawn count across all retry types to prevent runaway respawning- const totalSpawns = task.metadata?.totalSpawnCount || 0;+ const totalSpawns = Number(task.metadata?.totalSpawnCount) || 0;if (totalSpawns >= MAX_TOTAL_SPAWNS) {console.log(`🚫 Task ${task.id} hit max total spawns (${totalSpawns}/${MAX_TOTAL_SPAWNS}), blocking`);await updateTask(task.id, {@@ -1676,7 +1676,7 @@ export async function spawnAgentForTask(task) {emitLog('info', `Agent ${agentId} initializing...${worktreeInfo ? ' (worktree)' : ''}${jiraBranchName ? ` (JIRA: ${jiraTicket?.ticketId})` : ''}`, { agentId, taskId: task.id });// Mark the task as in_progress and increment total spawn count- const newSpawnCount = (task.metadata?.totalSpawnCount || 0) + 1;+ const newSpawnCount = (Number(task.metadata?.totalSpawnCount) || 0) + 1;const updateResult = await updateTask(task.id, {status: 'in_progress',metadata: {@@ -3302,7 +3302,7 @@ export async function killAllAgents() {const MAX_ORPHAN_RETRIES = 3;const MAX_TASK_RETRIES = 3;// Absolute cap on total agent spawns per task (across all retry types)-const MAX_TOTAL_SPAWNS = 5;+export const MAX_TOTAL_SPAWNS = 5;// Minimum cooldown between orphan retries (30 minutes)const ORPHAN_RETRY_COOLDOWN_MS = 30 * 60 * 1000;@@ -3451,8 +3451,8 @@ export async function handleOrphanedTask(taskId, agentId, getTaskById) {}// Get current retry count from task metadata- const retryCount = (task.metadata?.orphanRetryCount || 0) + 1;- const totalSpawns = task.metadata?.totalSpawnCount || 0;+ const retryCount = (Number(task.metadata?.orphanRetryCount) || 0) + 1;+ const totalSpawns = Number(task.metadata?.totalSpawnCount) || 0;const taskType = task.taskType || 'user';// Block if total spawn count across all retry types is exhausted