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

fix(cos): add retry limit for non-actionable task failures

Adam Eivye03125d7c5fc
diff --git a/.changelog/v0.10.x.md b/.changelog/v0.10.x.md
index 1f0c281112..43d5c47e73 100644
--- a/.changelog/v0.10.x.md
+++ b/.changelog/v0.10.x.md
@@ -483,6 +483,12 @@ This release introduces a structured changelog documentation system for creating
- **Batch orphaned agent events**: When the CoS runner cleans up orphaned agents on startup, it now emits a single `agents:orphaned` batch event instead of hundreds of individual `agent:completed` events
- **Cleaner logs**: Startup logs no longer flood with "📡 Emitted agent:completed" for each orphaned agent - now shows a single summary line like "📡 Emitted agents:orphaned (374 agents)"
+### CoS Non-Actionable Error Retry Loop
+- **Retry limit for non-actionable failures**: Tasks that fail with transient errors (rate-limit, server-error, network-error, unknown) now track a `failureCount` in metadata and are blocked after 3 consecutive failures instead of retrying endlessly every evaluation cycle
+- **Investigation task on max retries**: When a task exceeds the retry limit, an investigation task is created with the accumulated error context, just like actionable errors
+- **Consistent failure handling**: Both runner mode and direct spawn mode use the same `resolveFailedTaskUpdate()` function, ensuring identical retry/block behavior regardless of spawn mode
+- **DRY refactor**: Consolidated duplicate task-status-update and investigation-task-creation logic from both completion paths into a single shared function
+
## 📦 Installation
```bash
diff --git a/server/services/subAgentSpawner.js b/server/services/subAgentSpawner.js
index 82bb95bd95..e22d203b64 100644
--- a/server/services/subAgentSpawner.js
+++ b/server/services/subAgentSpawner.js
@@ -537,6 +537,78 @@ Review the error, fix the configuration or code issue, and retry the original ta
return investigationTask;
}
+/**
+ * Handle task status update after agent failure.
+ * Tracks retry count and blocks the task after MAX_TASK_RETRIES,
+ * creating an investigation task instead of retrying endlessly.
+ *
+ * Returns { status, metadata } to apply to the task.
+ */
+async function resolveFailedTaskUpdate(task, errorAnalysis, agentId) {
+ // Actionable errors get blocked immediately with investigation
+ if (errorAnalysis?.actionable) {
+ emitLog('warn', `🚫 Task ${task.id} blocked: ${errorAnalysis.message} (${errorAnalysis.category})`, {
+ taskId: task.id, category: errorAnalysis.category
+ });
+ await createInvestigationTask(agentId, task, errorAnalysis).catch(err => {
+ emitLog('warn', `Failed to create investigation task: ${err.message}`, { agentId });
+ });
+ return {
+ status: 'blocked',
+ metadata: {
+ ...task.metadata,
+ blockedReason: errorAnalysis.message,
+ blockedCategory: errorAnalysis.category,
+ blockedAt: new Date().toISOString()
+ }
+ };
+ }
+
+ // Non-actionable errors: track retry count and block after max retries
+ const failureCount = (task.metadata?.failureCount || 0) + 1;
+ const lastErrorCategory = errorAnalysis?.category || 'unknown';
+
+ if (failureCount >= MAX_TASK_RETRIES) {
+ emitLog('warn', `🚫 Task ${task.id} blocked after ${failureCount} failures (${lastErrorCategory})`, {
+ taskId: task.id, failureCount, category: lastErrorCategory
+ });
+ const blockedAnalysis = {
+ ...(errorAnalysis || {}),
+ message: `Task failed ${failureCount} times: ${errorAnalysis?.message || 'unknown error'}`,
+ suggestedFix: `Task has failed ${failureCount} consecutive times with ${lastErrorCategory} errors. ${errorAnalysis?.suggestedFix || 'Investigate agent output logs.'}`,
+ category: lastErrorCategory
+ };
+ await createInvestigationTask(agentId, task, blockedAnalysis).catch(err => {
+ emitLog('warn', `Failed to create investigation task: ${err.message}`, { agentId });
+ });
+ return {
+ status: 'blocked',
+ metadata: {
+ ...task.metadata,
+ failureCount,
+ lastFailureAt: new Date().toISOString(),
+ lastErrorCategory,
+ blockedReason: `Max retries exceeded (${failureCount}/${MAX_TASK_RETRIES}): ${lastErrorCategory}`,
+ blockedCategory: lastErrorCategory,
+ blockedAt: new Date().toISOString()
+ }
+ };
+ }
+
+ emitLog('info', `🔄 Task ${task.id} retry ${failureCount}/${MAX_TASK_RETRIES} (${lastErrorCategory})`, {
+ taskId: task.id, failureCount, maxRetries: MAX_TASK_RETRIES, category: lastErrorCategory
+ });
+ return {
+ status: 'pending',
+ metadata: {
+ ...task.metadata,
+ failureCount,
+ lastFailureAt: new Date().toISOString(),
+ lastErrorCategory
+ }
+ };
+}
+
// Track if using runner mode
let useRunner = false;
@@ -1037,51 +1109,32 @@ async function handleAgentCompletion(agentId, exitCode, success, duration) {
await completeAgentRun(runId, outputBuffer, exitCode, duration, errorAnalysis);
}
- // Update task status - block actionable errors instead of retrying endlessly
- const newStatus = success ? 'completed'
- : (errorAnalysis?.actionable ? 'blocked' : 'pending');
- const statusUpdate = { status: newStatus };
- if (newStatus === 'blocked' && errorAnalysis) {
- statusUpdate.metadata = {
- ...task.metadata,
- blockedReason: errorAnalysis.message,
- blockedCategory: errorAnalysis.category,
- blockedAt: new Date().toISOString()
- };
- emitLog('warn', `🚫 Task ${task.id} blocked: ${errorAnalysis.message} (${errorAnalysis.category})`, {
- taskId: task.id, category: errorAnalysis.category
- });
- }
- await updateTask(task.id, statusUpdate, task.taskType || 'user');
+ // Update task status with retry tracking
+ if (success) {
+ await updateTask(task.id, { status: 'completed' }, task.taskType || 'user');
+ } else {
+ const failedUpdate = await resolveFailedTaskUpdate(task, errorAnalysis, agentId);
+ await updateTask(task.id, failedUpdate, task.taskType || 'user');
- // On failure, handle provider status updates and create investigation task if actionable
- if (!success && errorAnalysis) {
- // Mark provider unavailable if usage limit hit
- if (errorAnalysis.category === 'usage-limit' && errorAnalysis.requiresFallback) {
- const providerId = agent.providerId || (await getActiveProvider())?.id;
- if (providerId) {
- await markProviderUsageLimit(providerId, errorAnalysis).catch(err => {
- emitLog('warn', `Failed to mark provider unavailable: ${err.message}`, { providerId });
- });
+ // Handle provider status updates on failure
+ if (errorAnalysis) {
+ if (errorAnalysis.category === 'usage-limit' && errorAnalysis.requiresFallback) {
+ const providerId = agent.providerId || (await getActiveProvider())?.id;
+ if (providerId) {
+ await markProviderUsageLimit(providerId, errorAnalysis).catch(err => {
+ emitLog('warn', `Failed to mark provider unavailable: ${err.message}`, { providerId });
+ });
+ }
}
- }
-
- // Mark provider rate limited (temporary)
- if (errorAnalysis.category === 'rate-limit') {
- const providerId = agent.providerId || (await getActiveProvider())?.id;
- if (providerId) {
- await markProviderRateLimited(providerId).catch(err => {
- emitLog('warn', `Failed to mark provider rate limited: ${err.message}`, { providerId });
- });
+ if (errorAnalysis.category === 'rate-limit') {
+ const providerId = agent.providerId || (await getActiveProvider())?.id;
+ if (providerId) {
+ await markProviderRateLimited(providerId).catch(err => {
+ emitLog('warn', `Failed to mark provider rate limited: ${err.message}`, { providerId });
+ });
+ }
}
}
-
- // Create investigation task if actionable
- if (errorAnalysis.actionable) {
- await createInvestigationTask(agentId, task, errorAnalysis).catch(err => {
- emitLog('warn', `Failed to create investigation task: ${err.message}`, { agentId });
- });
- }
}
// Process memory extraction and app cooldown
@@ -1251,51 +1304,32 @@ async function spawnDirectly(agentId, task, prompt, workspacePath, model, provid
await completeAgentRun(agentData?.runId || runId, outputBuffer, code, duration, errorAnalysis);
- // Block actionable errors instead of retrying endlessly
- const newStatus = success ? 'completed'
- : (errorAnalysis?.actionable ? 'blocked' : 'pending');
- const statusUpdate = { status: newStatus };
- if (newStatus === 'blocked' && errorAnalysis) {
- statusUpdate.metadata = {
- ...task.metadata,
- blockedReason: errorAnalysis.message,
- blockedCategory: errorAnalysis.category,
- blockedAt: new Date().toISOString()
- };
- emitLog('warn', `🚫 Task ${task.id} blocked: ${errorAnalysis.message} (${errorAnalysis.category})`, {
- taskId: task.id, category: errorAnalysis.category
- });
- }
- await updateTask(task.id, statusUpdate, task.taskType || 'user');
-
- // On failure, handle provider status updates and create investigation task if actionable
- if (!success && errorAnalysis) {
- // Mark provider unavailable if usage limit hit
- if (errorAnalysis.category === 'usage-limit' && errorAnalysis.requiresFallback) {
- const providerId = agentData?.providerId || provider.id;
- if (providerId) {
- await markProviderUsageLimit(providerId, errorAnalysis).catch(err => {
- emitLog('warn', `Failed to mark provider unavailable: ${err.message}`, { providerId });
- });
+ // Update task status with retry tracking
+ if (success) {
+ await updateTask(task.id, { status: 'completed' }, task.taskType || 'user');
+ } else {
+ const failedUpdate = await resolveFailedTaskUpdate(task, errorAnalysis, agentId);
+ await updateTask(task.id, failedUpdate, task.taskType || 'user');
+
+ // Handle provider status updates on failure
+ if (errorAnalysis) {
+ if (errorAnalysis.category === 'usage-limit' && errorAnalysis.requiresFallback) {
+ const providerId = agentData?.providerId || provider.id;
+ if (providerId) {
+ await markProviderUsageLimit(providerId, errorAnalysis).catch(err => {
+ emitLog('warn', `Failed to mark provider unavailable: ${err.message}`, { providerId });
+ });
+ }
}
- }
-
- // Mark provider rate limited (temporary)
- if (errorAnalysis.category === 'rate-limit') {
- const providerId = agentData?.providerId || provider.id;
- if (providerId) {
- await markProviderRateLimited(providerId).catch(err => {
- emitLog('warn', `Failed to mark provider rate limited: ${err.message}`, { providerId });
- });
+ if (errorAnalysis.category === 'rate-limit') {
+ const providerId = agentData?.providerId || provider.id;
+ if (providerId) {
+ await markProviderRateLimited(providerId).catch(err => {
+ emitLog('warn', `Failed to mark provider rate limited: ${err.message}`, { providerId });
+ });
+ }
}
}
-
- // Create investigation task if actionable
- if (errorAnalysis.actionable) {
- await createInvestigationTask(agentId, task, errorAnalysis).catch(err => {
- emitLog('warn', `Failed to create investigation task: ${err.message}`, { agentId });
- });
- }
}
// Process memory extraction and app cooldown
@@ -1736,6 +1770,7 @@ export async function killAllAgents() {
// Max retries before creating investigation task
const MAX_ORPHAN_RETRIES = 3;
+const MAX_TASK_RETRIES = 3;
/**
* Check if a process is running by PID
diff --git a/server/services/subAgentSpawner.test.js b/server/services/subAgentSpawner.test.js
index c4271db0c5..f50ab4ae0f 100644
--- a/server/services/subAgentSpawner.test.js
+++ b/server/services/subAgentSpawner.test.js
@@ -472,3 +472,186 @@ describe('Spawn Arguments Building', () => {
expect(args).not.toContain('--model');
});
});
+
+// Test failure retry logic
+describe('Task Failure Retry Logic', () => {
+ const MAX_TASK_RETRIES = 3;
+
+ /**
+ * Inline copy of resolveFailedTaskUpdate decision logic (sans async I/O).
+ * Returns { status, metadata, shouldCreateInvestigation }
+ */
+ function resolveFailedTaskStatus(task, errorAnalysis) {
+ // Actionable errors get blocked immediately
+ if (errorAnalysis?.actionable) {
+ return {
+ status: 'blocked',
+ metadata: {
+ ...task.metadata,
+ blockedReason: errorAnalysis.message,
+ blockedCategory: errorAnalysis.category,
+ blockedAt: 'test-timestamp'
+ },
+ shouldCreateInvestigation: true
+ };
+ }
+
+ // Non-actionable: track failure count
+ const failureCount = (task.metadata?.failureCount || 0) + 1;
+ const lastErrorCategory = errorAnalysis?.category || 'unknown';
+
+ if (failureCount >= MAX_TASK_RETRIES) {
+ return {
+ status: 'blocked',
+ metadata: {
+ ...task.metadata,
+ failureCount,
+ lastFailureAt: 'test-timestamp',
+ lastErrorCategory,
+ blockedReason: `Max retries exceeded (${failureCount}/${MAX_TASK_RETRIES}): ${lastErrorCategory}`,
+ blockedCategory: lastErrorCategory,
+ blockedAt: 'test-timestamp'
+ },
+ shouldCreateInvestigation: true
+ };
+ }
+
+ return {
+ status: 'pending',
+ metadata: {
+ ...task.metadata,
+ failureCount,
+ lastFailureAt: 'test-timestamp',
+ lastErrorCategory
+ },
+ shouldCreateInvestigation: false
+ };
+ }
+
+ describe('Actionable errors', () => {
+ it('should block immediately on actionable error (first failure)', () => {
+ const task = { id: 'task-1', description: 'test', metadata: {} };
+ const errorAnalysis = { actionable: true, category: 'auth-error', message: 'Auth failed' };
+
+ const result = resolveFailedTaskStatus(task, errorAnalysis);
+
+ expect(result.status).toBe('blocked');
+ expect(result.metadata.blockedCategory).toBe('auth-error');
+ expect(result.shouldCreateInvestigation).toBe(true);
+ });
+
+ it('should block immediately regardless of failure count', () => {
+ const task = { id: 'task-1', description: 'test', metadata: { failureCount: 0 } };
+ const errorAnalysis = { actionable: true, category: 'model-not-found', message: 'Model not found' };
+
+ const result = resolveFailedTaskStatus(task, errorAnalysis);
+
+ expect(result.status).toBe('blocked');
+ expect(result.shouldCreateInvestigation).toBe(true);
+ });
+ });
+
+ describe('Non-actionable errors with retry tracking', () => {
+ it('should retry on first failure (failureCount goes to 1)', () => {
+ const task = { id: 'task-1', description: 'test', metadata: {} };
+ const errorAnalysis = { actionable: false, category: 'rate-limit', message: 'Rate limited' };
+
+ const result = resolveFailedTaskStatus(task, errorAnalysis);
+
+ expect(result.status).toBe('pending');
+ expect(result.metadata.failureCount).toBe(1);
+ expect(result.metadata.lastErrorCategory).toBe('rate-limit');
+ expect(result.shouldCreateInvestigation).toBe(false);
+ });
+
+ it('should retry on second failure (failureCount goes to 2)', () => {
+ const task = { id: 'task-1', description: 'test', metadata: { failureCount: 1 } };
+ const errorAnalysis = { actionable: false, category: 'server-error', message: 'Server error' };
+
+ const result = resolveFailedTaskStatus(task, errorAnalysis);
+
+ expect(result.status).toBe('pending');
+ expect(result.metadata.failureCount).toBe(2);
+ expect(result.metadata.lastErrorCategory).toBe('server-error');
+ expect(result.shouldCreateInvestigation).toBe(false);
+ });
+
+ it('should block after MAX_TASK_RETRIES failures', () => {
+ const task = { id: 'task-1', description: 'test', metadata: { failureCount: 2 } };
+ const errorAnalysis = { actionable: false, category: 'network-error', message: 'Network failed' };
+
+ const result = resolveFailedTaskStatus(task, errorAnalysis);
+
+ expect(result.status).toBe('blocked');
+ expect(result.metadata.failureCount).toBe(3);
+ expect(result.metadata.blockedReason).toContain('Max retries exceeded');
+ expect(result.metadata.blockedCategory).toBe('network-error');
+ expect(result.shouldCreateInvestigation).toBe(true);
+ });
+
+ it('should block when already past max retries', () => {
+ const task = { id: 'task-1', description: 'test', metadata: { failureCount: 5 } };
+ const errorAnalysis = { actionable: false, category: 'unknown', message: 'Unknown error' };
+
+ const result = resolveFailedTaskStatus(task, errorAnalysis);
+
+ expect(result.status).toBe('blocked');
+ expect(result.metadata.failureCount).toBe(6);
+ expect(result.shouldCreateInvestigation).toBe(true);
+ });
+ });
+
+ describe('Unknown errors (no errorAnalysis)', () => {
+ it('should treat null errorAnalysis as non-actionable unknown', () => {
+ const task = { id: 'task-1', description: 'test', metadata: {} };
+
+ const result = resolveFailedTaskStatus(task, null);
+
+ expect(result.status).toBe('pending');
+ expect(result.metadata.failureCount).toBe(1);
+ expect(result.metadata.lastErrorCategory).toBe('unknown');
+ });
+
+ it('should still block after max retries with null errorAnalysis', () => {
+ const task = { id: 'task-1', description: 'test', metadata: { failureCount: 2 } };
+
+ const result = resolveFailedTaskStatus(task, null);
+
+ expect(result.status).toBe('blocked');
+ expect(result.metadata.failureCount).toBe(3);
+ expect(result.shouldCreateInvestigation).toBe(true);
+ });
+ });
+
+ describe('Metadata preservation', () => {
+ it('should preserve existing metadata fields on retry', () => {
+ const task = {
+ id: 'task-1',
+ description: 'test',
+ metadata: { app: 'my-app', context: 'some context', failureCount: 1 }
+ };
+ const errorAnalysis = { actionable: false, category: 'rate-limit', message: 'Rate limited' };
+
+ const result = resolveFailedTaskStatus(task, errorAnalysis);
+
+ expect(result.metadata.app).toBe('my-app');
+ expect(result.metadata.context).toBe('some context');
+ expect(result.metadata.failureCount).toBe(2);
+ });
+
+ it('should preserve existing metadata fields when blocked', () => {
+ const task = {
+ id: 'task-1',
+ description: 'test',
+ metadata: { app: 'my-app', failureCount: 2 }
+ };
+ const errorAnalysis = { actionable: false, category: 'server-error', message: 'Server error' };
+
+ const result = resolveFailedTaskStatus(task, errorAnalysis);
+
+ expect(result.metadata.app).toBe('my-app');
+ expect(result.metadata.failureCount).toBe(3);
+ expect(result.status).toBe('blocked');
+ });
+ });
+});