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 auto-fixer circuit breaker to prevent runaway task loops (#2328)
Adam Eivyac52f9da41c9
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex fdcb48757b..8a946bd7df 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -8,4 +8,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.)- **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 8fc7650361..49d16455e8 100644--- a/server/services/autoFixer.js+++ b/server/services/autoFixer.js@@ -33,6 +33,41 @@ const deferredTasks = new Map(); // errorKey -> { timer }// and noteFallbackFailed (failure → the fallback's own task already covers it).const inFlightFallbacks = new Set(); // errorKey+// Circuit breaker: if the SAME resource (errorKey) trips auto-fix more than+// CIRCUIT_MAX_FAILURES times within CIRCUIT_WINDOW_MS, stop creating+// investigation/fix tasks for it. A resource failing this persistently won't be+// healed by yet another identical task — repeating only exhausts the plan queue+// and can drive an unbounded retry loop. The window is rolling: timestamps older+// than CIRCUIT_WINDOW_MS are pruned on every check, so the circuit auto-closes+// once the failure rate ages out (no manual reset needed).+const CIRCUIT_WINDOW_MS = 60 * 60 * 1000; // 1 hour+const CIRCUIT_MAX_FAILURES = 3;+const failureTimestamps = new Map(); // errorKey -> number[] (ms timestamps, newest-last)++// Record a task-worthy failure for `errorKey` and report whether the circuit is+// now OPEN — i.e. this failure is the (CIRCUIT_MAX_FAILURES + 1)th within the+// rolling window and the caller should SUPPRESS task creation. Only genuinely+// new failures (past the dedupe + in-flight-fallback guards) should reach here,+// so the count reflects distinct recovery attempts, not log spam.+function tripCircuit(errorKey) {+ const now = Date.now();++ // Sweep fully-aged keys so the map can't grow unbounded — `error.message`+ // (part of the generic errorKey) can carry dynamic text, so distinct keys+ // accumulate over the process lifetime otherwise. Mirrors isDuplicateError's+ // global cleanup of recentErrors.+ for (const [key, stamps] of failureTimestamps.entries()) {+ if (stamps.every((t) => now - t >= CIRCUIT_WINDOW_MS)) {+ failureTimestamps.delete(key);+ }+ }++ const recent = (failureTimestamps.get(errorKey) || []).filter((t) => now - t < CIRCUIT_WINDOW_MS);+ recent.push(now);+ failureTimestamps.set(errorKey, recent);+ return recent.length > CIRCUIT_MAX_FAILURES;+}+// Store pending tasks when CoS is not running (for later pickup)const pendingAutoFixTasks = [];@@ -185,6 +220,7 @@ export function _resetAutoFixerForTests() {deferredTasks.clear();inFlightFallbacks.clear();recentErrors.clear();+ failureTimestamps.clear();pendingAutoFixTasks.length = 0;}@@ -226,6 +262,14 @@ async function handleAIProviderError(error) {return;}+ // Circuit breaker: a provider/model that keeps failing this often won't be+ // fixed by scheduling yet another investigation task — suppress to avoid a+ // retry loop that floods the plan queue. Auto-closes once failures age out.+ if (tripCircuit(errorKey)) {+ console.log(`🔌 Auto-fix circuit OPEN for ${ctx.provider} (${ctx.model}) — >${CIRCUIT_MAX_FAILURES} failures within the last hour; suppressing investigation task`);+ return;+ }+// Surface the actual failure reason + category inline so pm2 logs explain// WHY a run failed without spelunking into data/runs/<id>/metadata.json. The// reason is collapsed to a single line and capped (logging convention: no@@ -305,6 +349,14 @@ function shouldAutoFix(error) {return false;}+ // Circuit breaker: the same critical error recurring past the threshold won't+ // be resolved by spawning another identical fix task — suppress to prevent a+ // runaway loop. Auto-closes once the failure rate ages out of the window.+ if (tripCircuit(errorKey)) {+ console.log(`🔌 Auto-fix circuit OPEN for ${error.code} — >${CIRCUIT_MAX_FAILURES} failures within the last hour; suppressing auto-fix task`);+ return false;+ }+return true;}diff --git a/server/services/autoFixer.test.js b/server/services/autoFixer.test.jsindex f0a0b2ea65..439e6caef8 100644--- a/server/services/autoFixer.test.js+++ b/server/services/autoFixer.test.js@@ -336,3 +336,81 @@ describe('autoFixer — generic critical-error auto-fix path', () => {expect(cos.addTask).toHaveBeenCalledTimes(1);});});++describe('autoFixer — circuit breaker (guardrail #3)', () => {+ beforeEach(() => {+ vi.useFakeTimers();+ cos.addTask.mockClear();+ cos.isRunning.mockReturnValue(true);+ _resetAutoFixerForTests();+ });++ afterEach(() => {+ vi.useRealTimers();+ _resetAutoFixerForTests();+ });++ // Distinct same-resource failures must be spaced past the 60s dedupe window,+ // otherwise isDuplicateError swallows them before the circuit ever counts.+ const DEDUPE_GAP_MS = 61000;++ it('AI-provider path: suppresses the task once the same resource fails >3 times within the hour', async () => {+ // First 3 distinct failures each raise an investigation task.+ for (let i = 0; i < 3; i++) {+ emitProviderFailure({ provider: 'Ollama', model: 'command-r', runId: `r-${i}` });+ await vi.advanceTimersByTimeAsync(5500); // let the deferred task fire+ await vi.advanceTimersByTimeAsync(DEDUPE_GAP_MS - 5500); // clear the dedupe window+ }+ expect(cos.addTask).toHaveBeenCalledTimes(3);++ // 4th failure within the same hour trips the circuit — no task scheduled.+ emitProviderFailure({ provider: 'Ollama', model: 'command-r', runId: 'r-4' });+ await vi.advanceTimersByTimeAsync(6000);+ expect(cos.addTask).toHaveBeenCalledTimes(3);+ });++ it('AI-provider path: the circuit auto-closes once failures age out of the 1h window', async () => {+ for (let i = 0; i < 4; i++) {+ emitProviderFailure({ provider: 'Ollama', model: 'command-r', runId: `r-${i}` });+ await vi.advanceTimersByTimeAsync(5500);+ await vi.advanceTimersByTimeAsync(DEDUPE_GAP_MS - 5500);+ }+ // 3 tasks (4th suppressed by the open circuit).+ expect(cos.addTask).toHaveBeenCalledTimes(3);++ // Let the whole failure burst age past the rolling 1h window.+ await vi.advanceTimersByTimeAsync(60 * 60 * 1000 + 1000);++ // A fresh failure now raises a task again — the circuit auto-closed.+ emitProviderFailure({ provider: 'Ollama', model: 'command-r', runId: 'r-late' });+ await vi.advanceTimersByTimeAsync(5500);+ expect(cos.addTask).toHaveBeenCalledTimes(4);+ });++ it('AI-provider path: the circuit is per-resource — a different provider is unaffected', async () => {+ for (let i = 0; i < 4; i++) {+ emitProviderFailure({ provider: 'Ollama', model: 'command-r', runId: `a-${i}` });+ await vi.advanceTimersByTimeAsync(5500);+ await vi.advanceTimersByTimeAsync(DEDUPE_GAP_MS - 5500);+ }+ expect(cos.addTask).toHaveBeenCalledTimes(3); // Ollama circuit open++ // A distinct provider/model still gets its investigation task.+ emitProviderFailure({ provider: 'LM Studio', model: 'qwen', runId: 'b-0' });+ await vi.advanceTimersByTimeAsync(5500);+ expect(cos.addTask).toHaveBeenCalledTimes(4);+ });++ it('generic critical-error path: suppresses the fix task once the same error fires >3 times within the hour', async () => {+ for (let i = 0; i < 3; i++) {+ emitCriticalError({ message: 'recurring boom' });+ await vi.advanceTimersByTimeAsync(0);+ await vi.advanceTimersByTimeAsync(DEDUPE_GAP_MS);+ }+ expect(cos.addTask).toHaveBeenCalledTimes(3);++ emitCriticalError({ message: 'recurring boom' });+ await vi.advanceTimersByTimeAsync(0);+ expect(cos.addTask).toHaveBeenCalledTimes(3); // circuit open — suppressed+ });+});