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): improve learning system error categorization and fix byModelTier data leak
Adam Eivy8d298e1dfa45
diff --git a/.changelog/v0.16.x.md b/.changelog/v0.16.x.mdindex 01d91f5bed..89c3c34dbc 100644--- a/.changelog/v0.16.x.md+++ b/.changelog/v0.16.x.md@@ -43,3 +43,14 @@ Agent persistence, reliability, and decision transparency improvements.- **Idle decisions logged** -- when CoS has nothing to spawn after a full evaluation, it records whether that's due to tasks awaiting approval, all tasks on cooldown, or genuinely no work available- **New decision types** -- added `CAPACITY_FULL` and `IDLE` to the decision type vocabulary; started using the previously-defined but unused `COOLDOWN_ACTIVE` type- **Dashboard surfacing** -- capacity and cooldown decisions now appear in the impactful decisions summary on the dashboard, making it easy to spot bottlenecks at a glance++### Learning system error categorization improved+- **Broadened usage-limit pattern** -- session limits like "You've hit your limit · resets 6am" were falling through as "unknown" because the pattern only matched "hit your usage limit" (with "usage"); now catches "hit your limit", "plan limit", "daily limit", and "session limit" variants+- **Added startup-failure detection** -- agents that exit immediately with <50 chars of output now get categorized as `startup-failure` instead of `unknown`, distinguishing instant provider failures from real task errors+- **Added turn-limit and billing-error patterns** -- new error categories for agents hitting turn budget limits and provider billing/subscription issues+- **Wait time extraction improved** -- now parses "resets Xam/pm" format in addition to "try again in..." for usage limit cooldown times++### Fixed byModelTier data corruption in task type reset+- **Model tier metrics drifted from reality** -- `resetTaskTypeLearning()` subtracted counts from `byTaskType`, `errorPatterns`, `routingAccuracy`, and `totals`, but never touched `byModelTier`; after rehabilitation resets, the heavy tier showed 653 completed / 3 succeeded (0.46% success) due to accumulated historical data that was cleared from other structures but not from tier metrics+- **Now subtracts routing accuracy data from byModelTier** -- when a task type is reset, its per-tier succeeded/failed counts are decremented from the corresponding `byModelTier` entries, with duration estimated proportionally from the task type's average+- **Empty tiers cleaned up** -- if a tier's completed count reaches zero after subtraction, the tier entry is removed entirelydiff --git a/server/services/subAgentSpawner.js b/server/services/subAgentSpawner.jsindex b25bdcca2e..9054418507 100644--- a/server/services/subAgentSpawner.js+++ b/server/services/subAgentSpawner.js@@ -503,13 +503,14 @@ const ERROR_PATTERNS = [})},{- pattern: /(?:hit your usage limit|usage limit|quota exceeded|Upgrade to Pro)/i,+ // Catches both "hit your usage limit" and session limits like "hit your limit · resets 6am"+ pattern: /(?:hit your (?:usage )?limit|usage.?limit|quota exceeded|Upgrade to Pro|plan.?limit|daily.?limit|session.?limit)/i,category: 'usage-limit',actionable: true, // Need to switch providerextract: (match, output) => {// Try to extract the wait time from the message- // e.g., "try again in 1 day 1 hour 33 minutes"- const timeMatch = output.match(/try again in\s+(.+?)(?:\.|$)/i);+ // e.g., "try again in 1 day 1 hour 33 minutes" or "resets 6am (America/Los_Angeles)"+ const timeMatch = output.match(/(?:try again in|resets?)\s+(.+?)(?:\.|·|\n|$)/im);const waitTime = timeMatch ? timeMatch[1].trim() : null;return {message: `Usage limit exceeded${waitTime ? ` - retry in ${waitTime}` : ''}`,@@ -793,6 +794,26 @@ const ERROR_PATTERNS = [})},+ // ===== Limit & Billing Errors =====+ {+ pattern: /(?:maximum|max).*(?:turns?|iterations?|steps?)|turn.?limit|max.?turns|stopped after \d+ turns/i,+ category: 'turn-limit',+ actionable: false,+ extract: () => ({+ message: 'Agent reached turn limit',+ suggestedFix: 'Task exceeded the maximum number of agent turns. Break into smaller subtasks or increase turn limit.'+ })+ },+ {+ pattern: /(?:billing|subscription|payment).?(?:error|issue|required|expired|failed)/i,+ category: 'billing-error',+ actionable: true,+ extract: () => ({+ message: 'Billing/subscription issue',+ suggestedFix: 'Provider billing or subscription problem. Check provider account status.'+ })+ },+// ===== Safety & Content Errors ====={pattern: /content.?(?:filter|policy)|safety.?(?:filter|block)|harmful.?content/i,@@ -809,6 +830,16 @@ const ERROR_PATTERNS = [* Analyze agent failure output and categorize the error*/function analyzeAgentFailure(output, task, model) {+ // Agent produced no meaningful output — likely failed to start+ if (!output || output.trim().length < 50) {+ return {+ category: 'startup-failure',+ actionable: false,+ message: 'Agent failed to start or produced no output',+ suggestedFix: 'Agent process exited immediately. Check system resources and provider availability.'+ };+ }+for (const errorDef of ERROR_PATTERNS) {const match = output.match(errorDef.pattern);if (match) {diff --git a/server/services/taskLearning.js b/server/services/taskLearning.jsindex 99355c7098..a471decd0c 100644--- a/server/services/taskLearning.js+++ b/server/services/taskLearning.js@@ -897,8 +897,29 @@ export async function resetTaskTypeLearning(taskType) {}}- // Clean up routing accuracy data for this task type- if (data.routingAccuracy) {+ // Subtract model tier contributions using routing accuracy data (before deleting it)+ const routingData = data.routingAccuracy?.[taskType];+ if (routingData) {+ for (const [tier, counts] of Object.entries(routingData)) {+ const tierMetrics = data.byModelTier[tier];+ if (tierMetrics) {+ const tierTotal = counts.succeeded + counts.failed;+ tierMetrics.completed = Math.max(0, tierMetrics.completed - tierTotal);+ tierMetrics.succeeded = Math.max(0, tierMetrics.succeeded - counts.succeeded);+ tierMetrics.failed = Math.max(0, tierMetrics.failed - counts.failed);+ // Estimate duration contribution using task type's avg duration per agent+ if (tierTotal > 0 && metrics.avgDurationMs > 0) {+ tierMetrics.totalDurationMs = Math.max(0, tierMetrics.totalDurationMs - (metrics.avgDurationMs * tierTotal));+ }+ tierMetrics.avgDurationMs = tierMetrics.completed > 0+ ? Math.round(tierMetrics.totalDurationMs / tierMetrics.completed)+ : 0;+ // Clean up empty tiers+ if (tierMetrics.completed <= 0) {+ delete data.byModelTier[tier];+ }+ }+ }delete data.routingAccuracy[taskType];}@@ -1171,6 +1192,18 @@ function generateErrorInsight(category, percentage) {message: `${percentage}% of failures due to tool execution errors`,implication: 'Add explicit error handling instructions for tool usage'},+ 'startup-failure': {+ message: `${percentage}% of failures due to agent startup failure`,+ implication: 'Agents failing immediately - check provider availability and system resources'+ },+ 'turn-limit': {+ message: `${percentage}% of failures due to agent turn limit`,+ implication: 'Tasks are too large for the turn budget; break into smaller subtasks'+ },+ 'billing-error': {+ message: `${percentage}% of failures due to billing/subscription issues`,+ implication: 'Provider account needs attention - check subscription status'+ },'unknown': {message: `${percentage}% of failures have unknown causes`,implication: 'Review agent output logs for patterns not yet categorized'@@ -1204,6 +1237,18 @@ function generatePromptHint(category, taskType) {'spawn-error': {hint: 'Add environment prerequisites',example: 'Prerequisites: Ensure npm install has been run and dev server is started'+ },+ 'startup-failure': {+ hint: 'Add provider availability check',+ example: 'Before starting work, verify the AI provider responds to a simple test prompt'+ },+ 'turn-limit': {+ hint: 'Reduce task scope to fit within turn budget',+ example: 'Focus on ONE specific file or component per task instead of broad analysis'+ },+ 'usage-limit': {+ hint: 'Use a lighter model or reduce token consumption',+ example: 'Use targeted file reads instead of full codebase scans to reduce token usage'}};diff --git a/server/services/taskLearning.test.js b/server/services/taskLearning.test.jsindex 3d380862f9..2fdf419b76 100644--- a/server/services/taskLearning.test.js+++ b/server/services/taskLearning.test.js@@ -262,6 +262,94 @@ describe('TaskLearning - getSkippedTaskTypes', () => {expect(savedData.routingAccuracy['self-improve:ui']).toBeUndefined();expect(savedData.routingAccuracy['user-task']).toBeDefined();});++ it('should subtract from byModelTier when resetting a task type with routing data', async () => {+ let savedData;+ writeFile.mockImplementation(async (_path, content) => {+ savedData = JSON.parse(content);+ });++ const data = makeLearningData({+ byModelTier: {+ heavy: {+ completed: 50,+ succeeded: 20,+ failed: 30,+ totalDurationMs: 500000,+ avgDurationMs: 10000+ },+ medium: {+ completed: 10,+ succeeded: 2,+ failed: 8,+ totalDurationMs: 100000,+ avgDurationMs: 10000+ }+ },+ routingAccuracy: {+ 'self-improve:ui': {+ heavy: { succeeded: 5, failed: 15, lastAttempt: '2026-01-25T00:00:00.000Z' },+ medium: { succeeded: 0, failed: 5, lastAttempt: '2026-01-24T00:00:00.000Z' }+ },+ 'user-task': {+ heavy: { succeeded: 10, failed: 2, lastAttempt: '2026-01-26T00:00:00.000Z' }+ }+ }+ });+ readFile.mockResolvedValue(JSON.stringify(data));++ await resetTaskTypeLearning('self-improve:ui');++ // heavy: was 50 completed (20 succeeded, 30 failed), subtract 20 (5+15) from self-improve:ui+ expect(savedData.byModelTier.heavy.completed).toBe(30);+ expect(savedData.byModelTier.heavy.succeeded).toBe(15);+ expect(savedData.byModelTier.heavy.failed).toBe(15);+ // medium: was 10 completed, subtract 5 (0+5) from self-improve:ui+ expect(savedData.byModelTier.medium.completed).toBe(5);+ expect(savedData.byModelTier.medium.succeeded).toBe(2);+ expect(savedData.byModelTier.medium.failed).toBe(3);+ // user-task routing should be untouched+ expect(savedData.routingAccuracy['user-task']).toBeDefined();+ });++ it('should delete byModelTier entry when count reaches zero', async () => {+ let savedData;+ writeFile.mockImplementation(async (_path, content) => {+ savedData = JSON.parse(content);+ });++ const data = makeLearningData({+ byModelTier: {+ 'user-specified': {+ completed: 240,+ succeeded: 40,+ failed: 200,+ totalDurationMs: 6000000,+ avgDurationMs: 25000+ },+ medium: {+ completed: 5,+ succeeded: 0,+ failed: 5,+ totalDurationMs: 50000,+ avgDurationMs: 10000+ }+ },+ routingAccuracy: {+ 'self-improve:ui': {+ medium: { succeeded: 0, failed: 5, lastAttempt: '2026-01-24T00:00:00.000Z' }+ }+ }+ });+ readFile.mockResolvedValue(JSON.stringify(data));++ await resetTaskTypeLearning('self-improve:ui');++ // medium tier had 5 completed, all from self-improve:ui → should be deleted+ expect(savedData.byModelTier.medium).toBeUndefined();+ // user-specified should be untouched (no routing data for it)+ expect(savedData.byModelTier['user-specified']).toBeDefined();+ });});describe('TaskLearning - recordTaskCompletion routing accuracy', () => {