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: add tiered fallback classifier + structured auto-fix diagnostics (#2328)
Adam Eivydb9cbc0a7ea1
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 8a946bd7df..756dcf29d3 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -9,4 +9,5 @@## Fixed- **[issue-2328] Auto-fixer now has a circuit breaker so a persistently-failing resource can't flood the task queue.** The auto-fixer only deduped identical errors within a 60-second window, so a provider/model (or critical error) that failed every ~minute would queue a fresh investigation/fix task indefinitely — a runaway loop that exhausts the plan queue and never gets healed by yet another identical task. It now trips a per-resource circuit after more than 3 task-worthy failures within a rolling 1-hour window, suppressing further task creation (logged as `🔌 Auto-fix circuit OPEN …`) until the failure rate ages out and the circuit auto-closes. (Partial delivery of #2328's guardrails; the tiered fallback chain, structured failure-reason telemetry, and dashboard metrics remain.)+- **[issue-2328] Auto-fixer now classifies every failure into a fallback tier and records structured per-attempt diagnostics.** A deterministic classifier maps each error category (config/env, schema/type, transient, or unknown) to one of four fallback tiers — 1 config/env, 2 schema/type, 3 constrained-agent-retry, 4 escalate — with unrecognized categories always escalating so nothing is silently swallowed. Each auto-fix attempt now builds a structured `{ triggerEvent, target, errorType, category, tier, fixStrategy, failureReason }` diagnostics object that rides on the investigation/fix task record (and its agent-facing context) and is surfaced inline in the existing single-line log (`… tier=1 (config/env) …`), so failures can be broken out by tier / category / reason. (Further #2328 slices remain: dashboard telemetry surfacing, time-to-recovery metric, full 4-tier execution wiring.)- **Layered Intelligence loop now supports every provider type.** The per-app AI-provider picker previously listed only `cli` providers, while the reasoning call went through the api-only `callProviderAISimple` — so a selected CLI provider failed at runtime with "requires an API-based provider," and API/TUI providers (Ollama, LM Studio, Claude/Codex/OpenCode TUI, etc.) never appeared at all. The reasoning call now routes through the unified `runPromptThroughProvider`, which dispatches on `provider.type`, and the picker lists all enabled `cli`/`api`/`tui` providers. CLI/TUI spawns run in the app's repo (`cwd`).diff --git a/server/services/autoFixer.js b/server/services/autoFixer.jsindex 123d6538b8..2e9d5413e5 100644--- a/server/services/autoFixer.js+++ b/server/services/autoFixer.js@@ -79,6 +79,126 @@ const oneLine = (s, max = 300) => {return t.length > max ? `${t.slice(0, max - 1)}…` : t;};+// ── Tiered fallback cascade (issue #2328) ─────────────────────────────────+// A failure is routed to the CHEAPEST tier that can plausibly recover it,+// escalating only when no deterministic fix applies:+// 1 config/env — wrong provider/model/key/path/env; fixable by config+// 2 schema/type — malformed request/response; type/format/parse/build+// 3 constrained-agent-retry — transient/recoverable; a bounded retry may clear it+// 4 escalate — unknown or human-judgement-required; hand to investigation+export const FIX_TIERS = {+ CONFIG_ENV: 1,+ SCHEMA_TYPE: 2,+ CONSTRAINED_RETRY: 3,+ ESCALATE: 4,+};++const FIX_TIER_META = {+ [FIX_TIERS.CONFIG_ENV]: { strategy: 'config/env', label: 'config/env correction' },+ [FIX_TIERS.SCHEMA_TYPE]: { strategy: 'schema/type', label: 'schema/type correction' },+ [FIX_TIERS.CONSTRAINED_RETRY]: { strategy: 'constrained-agent-retry', label: 'constrained agent retry' },+ [FIX_TIERS.ESCALATE]: { strategy: 'escalate', label: 'escalate for investigation' },+};++// Deterministic error-category → tier map. Categories come from BOTH+// errorDetection.js (AI-provider failures) and agentErrorAnalysis.js (CoS agent+// failures); the two vocabularies overlap and are unioned here. Anything+// unmapped falls through to Tier 4 (escalate) — an unrecognized failure has no+// deterministic fix, so an investigation task carries it to a human/agent.+const CATEGORY_TO_TIER = {+ // Tier 1 — config/env (wrong key/model/path/permissions/env)+ 'auth-error': FIX_TIERS.CONFIG_ENV,+ forbidden: FIX_TIERS.CONFIG_ENV,+ 'model-not-found': FIX_TIERS.CONFIG_ENV,+ 'model-not-supported': FIX_TIERS.CONFIG_ENV,+ 'quota-exceeded': FIX_TIERS.CONFIG_ENV,+ 'billing-error': FIX_TIERS.CONFIG_ENV,+ 'usage-limit': FIX_TIERS.CONFIG_ENV,+ 'spawn-error': FIX_TIERS.CONFIG_ENV,+ 'permission-denied': FIX_TIERS.CONFIG_ENV,+ 'file-not-found': FIX_TIERS.CONFIG_ENV,+ // Tier 2 — schema/type (malformed request/response, parse/build/format)+ 'parse-error': FIX_TIERS.SCHEMA_TYPE,+ 'bad-request': FIX_TIERS.SCHEMA_TYPE,+ 'context-length': FIX_TIERS.SCHEMA_TYPE,+ 'output-length': FIX_TIERS.SCHEMA_TYPE,+ 'build-error': FIX_TIERS.SCHEMA_TYPE,+ 'lint-error': FIX_TIERS.SCHEMA_TYPE,+ // Tier 3 — constrained-agent-retry (transient/recoverable)+ 'rate-limit': FIX_TIERS.CONSTRAINED_RETRY,+ 'network-error': FIX_TIERS.CONSTRAINED_RETRY,+ timeout: FIX_TIERS.CONSTRAINED_RETRY,+ 'server-error': FIX_TIERS.CONSTRAINED_RETRY,+ 'tool-error': FIX_TIERS.CONSTRAINED_RETRY,+ 'mcp-error': FIX_TIERS.CONSTRAINED_RETRY,+ 'test-failure': FIX_TIERS.CONSTRAINED_RETRY,+ 'npm-error': FIX_TIERS.CONSTRAINED_RETRY,+ 'memory-error': FIX_TIERS.CONSTRAINED_RETRY,+ 'turn-limit': FIX_TIERS.CONSTRAINED_RETRY,+ 'process-killed': FIX_TIERS.CONSTRAINED_RETRY,+ 'browser-error': FIX_TIERS.CONSTRAINED_RETRY,+ 'locator-error': FIX_TIERS.CONSTRAINED_RETRY,+ 'claude-error': FIX_TIERS.CONSTRAINED_RETRY,+ 'startup-failure': FIX_TIERS.CONSTRAINED_RETRY,+ // Tier 4 — escalate (explicit entries; also the fall-through default)+ 'content-refusal': FIX_TIERS.ESCALATE,+ 'content-filtered': FIX_TIERS.ESCALATE,+ 'task-rejected': FIX_TIERS.ESCALATE,+ 'git-conflict': FIX_TIERS.ESCALATE,+ 'git-error': FIX_TIERS.ESCALATE,+ 'no-changes': FIX_TIERS.ESCALATE,+ unknown: FIX_TIERS.ESCALATE,+};++/**+ * Deterministically map an error category to a fallback tier (issue #2328).+ * Pure — no I/O. Unknown/absent categories escalate (Tier 4), so a failure the+ * cascade doesn't recognize is never silently swallowed.+ * @param {string} [category]+ * @returns {{ tier: number, strategy: string, label: string }}+ */+export function classifyFixTier(category) {+ const tier = CATEGORY_TO_TIER[category] ?? FIX_TIERS.ESCALATE;+ return { tier, ...FIX_TIER_META[tier] };+}++/**+ * Build a structured, per-attempt auto-fix diagnostics record (issue #2328).+ * Beyond the single-line log, this object rides on the task/return shape so+ * downstream telemetry can break failures out by tier / category / reason /+ * time-to-recovery. Pure — no I/O.+ * @returns {{ triggerEvent: string, target: string, errorType: string,+ * category: string, tier: number, fixStrategy: string, failureReason: string }}+ */+export function buildFixDiagnostics({ triggerEvent, target, category, failureReason } = {}) {+ const cat = category || 'unknown';+ const { tier, strategy } = classifyFixTier(cat);+ return {+ triggerEvent: triggerEvent || 'unknown',+ target: target || 'unknown',+ errorType: cat,+ category: cat,+ tier,+ fixStrategy: strategy,+ failureReason: oneLine(failureReason) || 'no error text captured',+ };+}++/**+ * Derive the diagnostics record for an AI-provider failure `error`. Kept as a+ * single helper so the deferred log line and the investigation task record are+ * always built from the same fields (no drift).+ */+function providerFixDiagnostics(error) {+ const ctx = error.context || {};+ return buildFixDiagnostics({+ triggerEvent: error.code,+ target: `${ctx.provider || 'Unknown'} (${ctx.model || 'N/A'})`,+ category: ctx.errorAnalysis?.category,+ failureReason: ctx.errorDetails || ctx.errorAnalysis?.message,+ });+}+function aiProviderErrorKey(providerName, model) {// NUL separator: provider names ("Claude Code CLI") and model ids// ("gpt-4o-mini") both commonly contain `-`, so a `-`-joined key would@@ -268,7 +388,11 @@ async function handleAIProviderError(error) {// multi-line blobs) — the full text stays in the run record's `error` field.const reason = oneLine(ctx.errorDetails || ctx.errorAnalysis?.message) || 'no error text captured';const category = ctx.errorAnalysis?.category || 'unknown';- console.log(`🤖 AI provider error detected: ${ctx.provider} (${ctx.model}) [${category}] exit=${ctx.exitCode ?? '?'} - run ${ctx.runId}: ${reason} (deferring ${TASK_DEFER_MS}ms for possible fallback retry)`);+ // Structured per-attempt diagnostics (issue #2328): classify the failure into+ // a fallback tier and surface it inline so pm2 logs (and the task record+ // below) break failures out by tier/strategy without spelunking metadata.+ const diagnostics = providerFixDiagnostics(error);+ console.log(`🤖 AI provider error detected: ${ctx.provider} (${ctx.model}) [${category}] tier=${diagnostics.tier} (${diagnostics.fixStrategy}) exit=${ctx.exitCode ?? '?'} - run ${ctx.runId}: ${reason} (deferring ${TASK_DEFER_MS}ms for possible fallback retry)`);const timer = setTimeout(() => {deferredTasks.delete(errorKey);@@ -296,13 +420,17 @@ async function handleAIProviderError(error) {async function createAIProviderInvestigationTask(error) {const ctx = error.context || {};+ // Structured diagnostics ride on the task record so downstream telemetry can+ // break auto-fix outcomes out by tier / category / failure reason (#2328).+ const diagnostics = providerFixDiagnostics(error);// Build specialized context for AI provider errors- const context = buildAIProviderErrorContext(error);+ const context = buildAIProviderErrorContext(error, diagnostics);const taskData = {description: `Investigate AI provider failure: ${ctx.provider} (${ctx.model})`,priority: 'MEDIUM',context,+ diagnostics,app: 'portos', // Associate with PortOS appapprovalRequired: true // Require user approval before investigating};@@ -310,12 +438,12 @@ async function createAIProviderInvestigationTask(error) {// If CoS is running, create the task immediatelyif (isRunning()) {const task = await addTask(taskData, 'internal');- console.log(`✅ AI provider investigation task created: ${task.id}`);+ console.log(`✅ AI provider investigation task created: ${task.id} [tier ${diagnostics.tier}: ${diagnostics.fixStrategy}]`);return task;}// Otherwise, store for later pickup- console.log(`📋 CoS not running - queuing AI provider investigation task`);+ console.log(`📋 CoS not running - queuing AI provider investigation task [tier ${diagnostics.tier}: ${diagnostics.fixStrategy}]`);pendingAutoFixTasks.push({...taskData,createdAt: Date.now(),@@ -364,7 +492,7 @@ function shouldAutoFix(error) {/*** Build detailed context for AI provider execution errors*/-function buildAIProviderErrorContext(error) {+function buildAIProviderErrorContext(error, diagnostics) {const ctx = error.context || {};const lines = ['# AI Provider Execution Failure',@@ -380,6 +508,16 @@ function buildAIProviderErrorContext(error) {''];+ // Fallback-tier diagnostics (issue #2328) — tells the investigating agent+ // which class of fix to try first before escalating to open-ended debugging.+ if (diagnostics) {+ lines.push('## Fallback Tier');+ lines.push(`- **Tier:** ${diagnostics.tier} (${diagnostics.fixStrategy})`);+ lines.push(`- **Error Type:** ${diagnostics.errorType}`);+ lines.push(`- **Failure Reason:** ${diagnostics.failureReason}`);+ lines.push('');+ }+// Add error category if availableif (ctx.errorCategory) {lines.push(`## Error Category: ${ctx.errorCategory}`);@@ -433,7 +571,16 @@ function buildAIProviderErrorContext(error) {* Create a CoS task to fix the error*/async function createAutoFixTask(error) {- console.log(`🤖 Creating auto-fix task for error: ${error.code}`);+ // Structured diagnostics (issue #2328): a bare crash usually has no recognized+ // category, so it classifies to Tier 4 (escalate) — which is exactly right for+ // an unsupervised fix task that still requires human approval below.+ const diagnostics = buildFixDiagnostics({+ triggerEvent: error.code,+ target: error.code,+ category: error.context?.errorAnalysis?.category,+ failureReason: error.message,+ });+ console.log(`🤖 Creating auto-fix task for error: ${error.code} [tier ${diagnostics.tier}: ${diagnostics.fixStrategy}]`);// Build context for the agentconst context = buildErrorContext(error);@@ -445,6 +592,7 @@ async function createAutoFixTask(error) {description: `Fix critical error: ${error.message}`,priority: 'HIGH',context,+ diagnostics,approvalRequired: true};diff --git a/server/services/autoFixer.test.js b/server/services/autoFixer.test.jsindex 13e54b6725..7cc9b0c900 100644--- a/server/services/autoFixer.test.js+++ b/server/services/autoFixer.test.js@@ -16,6 +16,9 @@ const {getPendingAutoFixTasks,clearPendingAutoFixTasks,_resetAutoFixerForTests,+ classifyFixTier,+ buildFixDiagnostics,+ FIX_TIERS,} = await import('./autoFixer.js');const { errorEvents } = await import('../lib/errorHandler.js');@@ -436,3 +439,164 @@ describe('autoFixer — circuit breaker (guardrail #3)', () => {expect(cos.addTask).toHaveBeenCalledTimes(3); // circuit open — suppressed});});++describe('autoFixer — tiered fallback classifier (guardrail #1, issue #2328)', () => {+ it('maps config/env-fixable categories to Tier 1', () => {+ for (const cat of ['auth-error', 'forbidden', 'model-not-found', 'model-not-supported',+ 'quota-exceeded', 'billing-error', 'usage-limit', 'spawn-error', 'permission-denied', 'file-not-found']) {+ expect(classifyFixTier(cat).tier, cat).toBe(FIX_TIERS.CONFIG_ENV);+ }+ });++ it('maps schema/type/format categories to Tier 2', () => {+ for (const cat of ['parse-error', 'bad-request', 'context-length', 'output-length', 'build-error', 'lint-error']) {+ expect(classifyFixTier(cat).tier, cat).toBe(FIX_TIERS.SCHEMA_TYPE);+ }+ });++ it('maps transient/recoverable categories to Tier 3 (constrained-agent-retry)', () => {+ for (const cat of ['rate-limit', 'network-error', 'timeout', 'server-error', 'tool-error',+ 'mcp-error', 'test-failure', 'npm-error', 'memory-error', 'turn-limit']) {+ expect(classifyFixTier(cat).tier, cat).toBe(FIX_TIERS.CONSTRAINED_RETRY);+ }+ });++ it('maps human-judgement categories to Tier 4 (escalate)', () => {+ for (const cat of ['content-refusal', 'content-filtered', 'task-rejected', 'git-conflict', 'unknown']) {+ expect(classifyFixTier(cat).tier, cat).toBe(FIX_TIERS.ESCALATE);+ }+ });++ it('escalates unknown/absent categories to Tier 4 (no silent swallow)', () => {+ expect(classifyFixTier('some-brand-new-category').tier).toBe(FIX_TIERS.ESCALATE);+ expect(classifyFixTier(undefined).tier).toBe(FIX_TIERS.ESCALATE);+ expect(classifyFixTier('').tier).toBe(FIX_TIERS.ESCALATE);+ });++ it('returns a stable {tier, strategy, label} shape', () => {+ const t1 = classifyFixTier('auth-error');+ expect(t1).toMatchObject({ tier: 1, strategy: 'config/env' });+ expect(typeof t1.label).toBe('string');+ expect(classifyFixTier('rate-limit').strategy).toBe('constrained-agent-retry');+ expect(classifyFixTier('unknown').strategy).toBe('escalate');+ });+});++describe('autoFixer — structured per-attempt diagnostics (issue #2328)', () => {+ it('builds a full diagnostics record from trigger/target/category/reason', () => {+ const d = buildFixDiagnostics({+ triggerEvent: 'AI_PROVIDER_EXECUTION_FAILED',+ target: 'Claude Code CLI (claude-opus-4-8)',+ category: 'model-not-found',+ failureReason: 'API Error (claude-opus-4-8): 400 The provided model identifier is invalid.',+ });+ expect(d).toMatchObject({+ triggerEvent: 'AI_PROVIDER_EXECUTION_FAILED',+ target: 'Claude Code CLI (claude-opus-4-8)',+ errorType: 'model-not-found',+ category: 'model-not-found',+ tier: FIX_TIERS.CONFIG_ENV,+ fixStrategy: 'config/env',+ });+ expect(d.failureReason).toContain('model identifier is invalid');+ });++ it('collapses a multi-line failure reason to one line and fills sensible defaults', () => {+ const d = buildFixDiagnostics({ failureReason: 'line one\n\n line two \nline three' });+ expect(d.failureReason).toBe('line one line two line three');+ expect(d.triggerEvent).toBe('unknown');+ expect(d.target).toBe('unknown');+ expect(d.category).toBe('unknown');+ expect(d.tier).toBe(FIX_TIERS.ESCALATE);+ });++ it("reports 'no error text captured' when no reason is supplied", () => {+ expect(buildFixDiagnostics({ category: 'auth-error' }).failureReason).toBe('no error text captured');+ });+});++describe('autoFixer — diagnostics ride on the created task record (issue #2328)', () => {+ beforeEach(() => {+ vi.useFakeTimers();+ cos.addTask.mockClear();+ cos.isRunning.mockReturnValue(true);+ _resetAutoFixerForTests();+ });++ afterEach(() => {+ vi.useRealTimers();+ _resetAutoFixerForTests();+ });++ it('attaches tier-classified diagnostics to the AI-provider investigation task', async () => {+ errorEvents.emit('error', {+ code: 'AI_PROVIDER_EXECUTION_FAILED',+ message: 'AI provider Claude Code CLI execution failed: …',+ severity: 'error',+ canAutoFix: true,+ timestamp: Date.now(),+ context: {+ runId: 'run-diag', provider: 'Claude Code CLI', providerId: 'claude-code',+ model: 'claude-opus-4-8', exitCode: 1,+ errorDetails: 'API Error (claude-opus-4-8): 400 The provided model identifier is invalid.',+ errorAnalysis: { category: 'model-not-found', message: 'model identifier is invalid' },+ },+ });+ await vi.advanceTimersByTimeAsync(5500);++ expect(cos.addTask).toHaveBeenCalledTimes(1);+ const taskArg = cos.addTask.mock.calls[0][0];+ expect(taskArg.diagnostics).toMatchObject({+ triggerEvent: 'AI_PROVIDER_EXECUTION_FAILED',+ target: 'Claude Code CLI (claude-opus-4-8)',+ category: 'model-not-found',+ tier: FIX_TIERS.CONFIG_ENV,+ fixStrategy: 'config/env',+ });+ expect(taskArg.diagnostics.failureReason).toContain('model identifier is invalid');+ // Diagnostics are also embedded in the agent-facing context markdown.+ expect(taskArg.context).toContain('## Fallback Tier');+ expect(taskArg.context).toContain('Tier:** 1 (config/env)');+ });++ it('emits the tier inline on the "AI provider error detected" log line', async () => {+ const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});+ try {+ emitProviderFailure({ provider: 'Ollama', model: 'command-r' });+ await vi.advanceTimersByTimeAsync(0);+ const line = logSpy.mock.calls.map((c) => c[0]).find((m) => typeof m === 'string' && m.includes('AI provider error detected'));+ expect(line).toBeTruthy();+ expect(line).toMatch(/tier=\d/);+ } finally {+ logSpy.mockRestore();+ }+ });++ it('attaches diagnostics to the pending record when CoS is not running', async () => {+ clearPendingAutoFixTasks();+ cos.isRunning.mockReturnValue(false);+ emitProviderFailure({ provider: 'LM Studio', model: 'qwen', runId: 'p-1' });+ await vi.advanceTimersByTimeAsync(5500);++ const pending = getPendingAutoFixTasks();+ expect(pending).toHaveLength(1);+ expect(pending[0].diagnostics).toMatchObject({+ triggerEvent: 'AI_PROVIDER_EXECUTION_FAILED',+ target: 'LM Studio (qwen)',+ tier: FIX_TIERS.ESCALATE, // no errorAnalysis category → unknown → escalate+ });+ clearPendingAutoFixTasks();+ });++ it('attaches diagnostics to the generic critical-error fix task', async () => {+ emitCriticalError({ code: 'UNCAUGHT_EXCEPTION', message: 'Cannot read properties of undefined' });+ await vi.advanceTimersByTimeAsync(0);++ expect(cos.addTask).toHaveBeenCalledTimes(1);+ expect(cos.addTask.mock.calls[0][0].diagnostics).toMatchObject({+ triggerEvent: 'UNCAUGHT_EXCEPTION',+ target: 'UNCAUGHT_EXCEPTION',+ tier: FIX_TIERS.ESCALATE,+ });+ });+});