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
feat: wire deterministic Tier-1 config/env fix into the fallback cascade (#2342)
Adam Eivyb1780e7e1034
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 4f949b7dba..2b65b94fdb 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -26,5 +26,6 @@- **[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.)- **[issue-2328] Auto-fix diagnostics are now persisted as structured task metadata instead of being silently dropped.** The tier/category/failure-reason diagnostics the classifier builds for every error-driven task were only ever embedded into the free-text context string and the log line — `addTask` never copied the structured object into task metadata, so it couldn't be queried or aggregated afterward. It now persists `taskData.diagnostics` as first-class `metadata.diagnostics` (round-tripping through the markdown store via the existing JSON sentinel, with a defensive non-object guard), and `createCosTaskSchema` validates it for schema parity. This is the prerequisite for the remaining #2328 telemetry slice: aggregating auto-fix outcomes by tier / failure reason / time-to-recovery and surfacing them on the dashboard.+- **[issue-2342] Auto-fix now actually *attempts* the cheapest fallback tier before escalating, instead of only annotating the tier.** The tier classifier (#2331) labeled each provider failure with a fallback tier but the runner only ever did one thing on failure — swap to a fallback provider (Tier 3) — and otherwise queued a Tier-4 investigation task. `runPromptThroughProvider` now walks the tiers in order: a `model-not-found`/`model-not-supported` failure first gets a deterministic **Tier 1 (config/env) correction** — a bounded retry of the *same* provider with a valid model it lists (no persisted config change; skips embedding-only ids) — and only if that declines/fails does it fall through to the **Tier 3** fallback-provider retry, then the **Tier 4** investigation task. Recovery at any tier is reconciled through the existing `noteFallbackStarted`/`noteFallbackHandled`/`noteFallbackFailed` lifecycle, so a Tier-1 recovery suppresses the investigation task exactly like a Tier-3 one — a fully-recovered failure leaves **zero** tasks, and only genuinely unrecovered failures escalate. The recovering tier is surfaced on the result (`fixTier`/`fixStrategy`) and in the single-line log (`🔧 Tier 1 (config/env) retry …`), and because fewer failures reach a Tier-4 task the existing #2328 telemetry automatically reflects the per-tier recovery. (Tier 2 schema/type has no safe deterministic same-provider transform at the runner layer — a malformed request/response can't be rewritten without the caller's schema — so it falls straight through to the bounded retry.)- **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`).- **A "Run now" of Layered Intelligence now tells you what actually happened.** Because the loop is handler-backed — it files one tracker issue rather than spawning a visible agent — a run that filed nothing gave no usable signal: the on-demand toast collapsed every non-filed outcome (reasoning model returned unparseable JSON, a duplicate/near-duplicate was suppressed, it parked on a blocking issue, no AI provider was configured, Jira wasn't set up, the tracker read failed) into a blanket "nothing to do right now," and on mobile that transient toast was easy to miss entirely. The handler now threads the real terminal reason through the on-demand feedback (so the toast reads e.g. "the reasoning model returned no usable JSON — try a non-reasoning model" or "paused on a blocking issue"), and every run persists its outcome (`lastRunAt` / action / reason / filed ref) so Edit App → Intelligence shows a durable **Last run** status line you can check any time. This is what made a reasoning-style local model (which often emits thinking text with no parseable JSON) look like a queued-but-not-running task with no explanation.diff --git a/server/lib/promptRunner.js b/server/lib/promptRunner.jsindex 8b6edddc52..66091cd25b 100644--- a/server/lib/promptRunner.js+++ b/server/lib/promptRunner.js@@ -201,6 +201,31 @@ function firstGenerationModel(provider) {return models.find((m) => m && isGenerationModel(m)) || models[0] || null;}+/**+ * Tier-1 (config/env) deterministic fix for a `model-not-found` /+ * `model-not-supported` failure (issue #2342): the request named a model id the+ * (reachable) provider doesn't serve, so pick a DIFFERENT valid generation+ * model that the provider DOES list and retry the SAME provider with it —+ * cheaper than benching the provider and switching to a fallback (Tier 3).+ *+ * Pure — no I/O. Returns null (⇒ Tier 1 declines, cascade falls through) when:+ * - the provider carries no enumerable `models` list (nothing to correct to), OR+ * - the only listed models are the failed one and/or embedding-only ids.+ *+ * The failed id is excluded so we never re-issue the same broken request, and+ * embedding-only ids are skipped (mirrors `firstGenerationModel`) so a+ * generation call can't get corrected onto e.g. `nomic-embed-text`.+ *+ * @param {object} provider+ * @param {string} [failedModel] — the model id that just failed model-not-found+ * @returns {string|null}+ */+export function pickConfigCorrectedModel(provider, failedModel) {+ const models = provider?.models;+ if (!Array.isArray(models)) return null;+ return models.find((m) => m && m !== failedModel && isGenerationModel(m)) || null;+}+/*** Resolve `{provider, selectedModel}` for an LLM caller. Prefers* `providerId` — any `getProviderById` failure (stale id, lookup@@ -329,7 +354,7 @@ export function assertVisionRunUsedImages(result, requestedProvider) {* must pass this — without it, the CLI/TUI spawn lands in PortOS's own* cwd and the analysis runs against the wrong files. No-op for API* providers (no spawn).- * @returns {Promise<{ text: string, runId: string, model: string|null, provider: object, usedFallback?: boolean, fallbackFrom?: { id: string, name: string }, fallbackProvider?: object }>}+ * @returns {Promise<{ text: string, runId: string, model: string|null, provider: object, usedFallback?: boolean, fixTier?: number, fixStrategy?: string, fallbackFrom?: { id: string, name: string }, fallbackProvider?: object }>}* — `model` is the resolved model that actually executed (null when* neither override nor provider.defaultModel applies). `provider` is the* provider object that actually ran, reflecting createRun's proactive swap@@ -340,7 +365,11 @@ export function assertVisionRunUsedImages(result, requestedProvider) {* `usedFallback` is true, `fallbackFrom` identifies the failed primary* and `fallbackProvider` is the full provider object that actually ran* (so callers persisting run attribution can write the correct- * providerId without re-picking the fallback themselves).+ * providerId without re-picking the fallback themselves). `fixTier` /+ * `fixStrategy` (issue #2342) record WHICH fallback tier recovered the+ * failure — `1`/`'config/env'` when a same-provider model correction+ * recovered it, `3`/`'constrained-agent-retry'` for a fallback-provider+ * retry — so callers can log/attribute the deterministic recovery path.*/export async function runPromptThroughProvider(args) {// Validate inputs up front so an accidentally-null `provider` (or one@@ -384,46 +413,131 @@ export async function runPromptThroughProvider(args) {}// The runner already wrote a failed metadata.json and the onRunFailed- // hook in server/index.js queued a deferred investigation task. If a- // fallback is configured + available, mark the failed provider- // unavailable so subsequent calls skip it, then retry once. No- // fallback ⇒ let the queued investigation task fire.+ // hook in server/index.js queued a deferred investigation task keyed on+ // (providerName, model). We now walk the deterministic fallback cascade+ // (issue #2342), attempting the CHEAPEST tier that can plausibly recover+ // the failure and escalating to the queued investigation task (Tier 4)+ // only when every deterministic tier declines or fails:+ // Tier 1 config/env — retry the SAME provider with a valid model+ // (deterministic; no persisted config change)+ // Tier 2 schema/type — no safe same-provider transform at this layer+ // (a malformed request/response can't be rewritten+ // without the caller's schema) → falls through+ // Tier 3 constrained-agent-retry — bounded retry via a fallback provider+ // Tier 4 escalate — the deferred investigation task the hook queued//// `failed` is the provider that ACTUALLY ran — usually equals// args.provider, but createRun may have proactively swapped to a// different fallback if the requested primary was already marked- // unavailable. Always dedupe against what actually ran so- // `noteFallbackHandled` cancels the right queued task.+ // unavailable. Always dedupe against what actually ran so the+ // task-suppression notifiers cancel the right queued task.const failed = firstError.effectiveProvider;const failedModel = firstError.effectiveModel || resolveEffectiveModel(failed, args.model);- // Coalesce the per-provider mark-and-pick during an N-way failure- // storm: the 2nd…Nth simultaneous failure for the same provider awaits- // the first's result instead of independently re-reading providers.json+ const category = firstError.errorAnalysis?.category;+ // The primary's queued investigation task is keyed on (providerName, model).+ // Every tier that retries suppresses this key up front so a slow retry+ // (a CLI fallback can take 20–30s) can't outrun the backstop timer+ // (autoFixer.TASK_DEFER_MS) and leave a task behind for a recovered failure.+ const primaryKey = { provider: failed.name || failed.id, model: failedModel };++ // Load the fallback-lifecycle notifiers lazily and once for the whole+ // cascade. Lazy (see loadAutoFixer) so the happy path never drags in the+ // CoS stack — and so a failure with NO recovery path (no tier applies)+ // never loads it either, since none of the note* helpers below fire.+ let autoFixerModule;+ let autoFixerLoaded = false;+ const getAutoFixer = async () => {+ if (!autoFixerLoaded) {+ autoFixerLoaded = true;+ autoFixerModule = await loadAutoFixer().catch((err) => {+ console.error(`❌ autoFixer load failed (investigation task not suppressed): ${err.message}`);+ return null;+ });+ }+ return autoFixerModule;+ };+ // Keys must match what server/index.js's onRunFailed hook published+ // (metadata.providerName + metadata.model). Best-effort throughout: a+ // notifier failure must never turn a working retry into a user-visible error.+ const noteStarted = async (key) => { const a = await getAutoFixer(); try { a?.noteFallbackStarted(key); } catch { /* best-effort */ } };+ const noteFailed = async (key) => { const a = await getAutoFixer(); try { a?.noteFallbackFailed(key); } catch { /* best-effort */ } };+ const noteHandled = async (key) => {+ const a = await getAutoFixer();+ try { a?.noteFallbackHandled(key); } catch (suppressErr) {+ console.error(`❌ noteFallbackHandled failed (investigation task not suppressed): ${suppressErr.message}`);+ }+ };++ // ── Tier 1 — config/env correction (issue #2342) ─────────────────────────+ // A model-not-found/model-not-supported failure is request-specific: the+ // provider is reachable but doesn't serve the requested model id. Before+ // escalating to a whole-provider fallback (Tier 3), attempt the cheapest+ // deterministic fix — retry the SAME provider with a valid model it lists.+ // No config is persisted; on success the user's own provider keeps serving.+ let tier1CorrectedKey = null;+ // Only a wrong-model failure is config-correctable here. Compare against+ // string literals, not `ERROR_CATEGORIES.MODEL_NOT_SUPPORTED` — that member+ // does NOT exist (it would be `undefined`, matching a category-less failure+ // and wrongly engaging Tier 1). 'model-not-supported' is autoFixer's own+ // Tier-1 category (from CoS agent analysis), matched here for parity.+ if (category === ERROR_CATEGORIES.MODEL_NOT_FOUND || category === 'model-not-supported') {+ const correctedModel = pickConfigCorrectedModel(failed, failedModel);+ if (correctedModel) {+ console.log(`🔧 Tier 1 (config/env) retry: ${args.source} on ${failed.name} with model ${correctedModel} (requested ${failedModel} → ${category})`);+ // Suppress the primary's investigation task while the corrected retry+ // runs; released in the give-up branch below if the cascade fails out.+ await noteStarted(primaryKey);+ tier1CorrectedKey = { provider: failed.name || failed.id, model: correctedModel };+ let tier1Result;+ try {+ tier1Result = await executeProviderRunOnce({+ ...args,+ provider: failed,+ model: correctedModel,+ runId: undefined, // fresh run so the failed primary's record stays intact+ });+ } catch (tier1Error) {+ // The corrected retry ALSO failed — its own onRunFailed queued a task+ // keyed on tier1CorrectedKey. Fall through to Tier 3: that task+ // survives as the escalation if nothing recovers, and is cancelled+ // below if a later tier does.+ console.log(`↪️ Tier 1 correction failed on ${failed.name} (${correctedModel}): ${tier1Error.message} — escalating to constrained-agent-retry`);+ }+ if (tier1Result) {+ await noteHandled(primaryKey);+ return {+ ...tier1Result,+ usedFallback: true,+ fixTier: 1, // FIX_TIERS.CONFIG_ENV (mirrored; kept decoupled from the lazy autoFixer import)+ fixStrategy: 'config/env',+ fallbackFrom: { id: failed.id, name: failed.name },+ fallbackProvider: failed,+ };+ }+ }+ }++ // ── Tier 3 — constrained-agent-retry via a fallback provider ─────────────+ // Coalesce the per-provider mark-and-pick during an N-way failure storm:+ // the 2nd…Nth simultaneous failure for the same provider awaits the first's+ // result instead of independently re-reading providers.json// (pickFallbackProvider) and re-writing provider-status.json- // (markUnavailable). The fallback *run* below is NOT coalesced — each- // failed call still executes its own fallback to get its own result.+ // (markUnavailable). The fallback *run* below is NOT coalesced — each failed+ // call still executes its own fallback to get its own result.const picked = await coalesceFallbackMarkAndPick(failed, firstError);if (!picked) {+ // ── Tier 4 — escalate ──: no recovery path left. Release any Tier-1+ // suppression so the primary key doesn't leak in the in-flight set (the+ // corrected retry's own task, if any, still surfaces as the escalation).+ if (tier1CorrectedKey) await noteFailed(primaryKey);throw stripFallbackContext(firstError);}const fallback = picked.provider;- console.log(`⚡ Retrying ${args.source} with fallback ${fallback.name} (primary ${failed.name} failed: ${firstError.message})`);+ console.log(`⚡ Tier 3 (constrained-agent-retry): ${args.source} with fallback ${fallback.name} (primary ${failed.name} failed: ${firstError.message})`);- // Tell the autofixer a fallback is now in flight for this failure so it- // suppresses the deferred investigation task IMMEDIATELY — before the- // backstop timer (TASK_DEFER_MS) can fire. Without this, a slow CLI- // fallback (Claude Code can take 20–30s) outruns the timer and a- // successfully-recovered failure still leaves a task in the user's plan.- // Keys must match what server/index.js's onRunFailed hook published- // (metadata.providerName + metadata.model). Best-effort throughout: a- // failure here must never turn a working fallback into a user-visible error.- const fallbackKey = { provider: failed.name || failed.id, model: failedModel };- const autoFixer = await loadAutoFixer().catch((err) => {- console.error(`❌ autoFixer load failed (investigation task not suppressed): ${err.message}`);- return null;- });- try { autoFixer?.noteFallbackStarted(fallbackKey); } catch { /* best-effort */ }+ // Re-suppress the primary key (idempotent) for the fallback run.+ await noteStarted(primaryKey);// Run the fallback as a fresh attempt. Pass the configured `fallbackModel`// when one is set (so the user's chosen fallback provider+model pair is@@ -443,22 +557,30 @@ export async function runPromptThroughProvider(args) {runId: undefined, // fresh runId so the failed primary's record stays intact});} catch (fallbackError) {- // Both failed — release the primary's suppression (the fallback's own- // failure already queued its investigation task) and rethrow.- try { autoFixer?.noteFallbackFailed(fallbackKey); } catch { /* best-effort */ }+ // ── Tier 4 — escalate ──: every deterministic tier failed. Release the+ // primary's suppression (the fallback provider's own failure already+ // queued its investigation task) and rethrow. Any Tier-1 corrected-retry+ // task is intentionally left in place — one investigation task per+ // genuinely-failed attempt is the intended escalation.+ await noteFailed(primaryKey);throw stripFallbackContext(fallbackError);}// Fallback succeeded — clear the primary's suppression so the user doesn't// see a noisy "investigate" entry in their plan for a failure that was// auto-recovered.- try { autoFixer?.noteFallbackHandled(fallbackKey); } catch (suppressErr) {- console.error(`❌ noteFallbackHandled failed (investigation task not suppressed): ${suppressErr.message}`);- }+ await noteHandled(primaryKey);+ // A Tier-1 corrected retry that failed before this recovery left its own+ // deferred task; cancel it too so a fully-recovered action creates ZERO+ // investigation tasks (issue #2342 acceptance: only UNRECOVERED failures+ // escalate to Tier 4).+ if (tier1CorrectedKey) await noteHandled(tier1CorrectedKey);return {...fallbackResult,usedFallback: true,+ fixTier: 3, // FIX_TIERS.CONSTRAINED_RETRY+ fixStrategy: 'constrained-agent-retry',fallbackFrom: { id: failed.id, name: failed.name },fallbackProvider: fallback,};diff --git a/server/lib/promptRunner.test.js b/server/lib/promptRunner.test.jsindex 4a62cb2157..e2e6195602 100644--- a/server/lib/promptRunner.test.js+++ b/server/lib/promptRunner.test.js@@ -62,7 +62,7 @@ const providers = await import('../services/providers.js');const autoFixer = await import('../services/autoFixer.js');const toolkitState = await import('./aiToolkitState.js');const { ERROR_CATEGORIES } = await import('./aiToolkit/errorDetection.js');-const { runPromptThroughProvider, resolveProviderAndModel, resolveEffectiveModel } = await import('./promptRunner.js');+const { runPromptThroughProvider, resolveProviderAndModel, resolveEffectiveModel, pickConfigCorrectedModel } = await import('./promptRunner.js');const apiProvider = (extra = {}) => ({id: 'mock-api', type: 'api', defaultModel: 'm-default', ...extra,@@ -1152,6 +1152,207 @@ describe('promptRunner — retry-with-fallback', () => {});});+// =============================================================================+// pickConfigCorrectedModel — pure Tier-1 (config/env) model corrector.+// =============================================================================++describe('pickConfigCorrectedModel', () => {+ it('returns null when the provider carries no enumerable models list', () => {+ expect(pickConfigCorrectedModel({ id: 'p', defaultModel: 'x' }, 'x')).toBeNull();+ expect(pickConfigCorrectedModel({ id: 'p', models: null }, 'x')).toBeNull();+ });++ it('picks a different valid generation model, excluding the failed id', () => {+ const p = { id: 'p', models: ['broken-model', 'good-model', 'other-model'] };+ expect(pickConfigCorrectedModel(p, 'broken-model')).toBe('good-model');+ });++ it('skips embedding-only models so a generation call is never corrected onto one', () => {+ const p = { id: 'p', models: ['broken-model', 'nomic-embed-text:latest', 'qwen3.6:35b'] };+ expect(pickConfigCorrectedModel(p, 'broken-model')).toBe('qwen3.6:35b');+ });++ it('returns null when the only alternatives are the failed id and/or embedding models', () => {+ expect(pickConfigCorrectedModel({ id: 'p', models: ['broken-model'] }, 'broken-model')).toBeNull();+ expect(pickConfigCorrectedModel({ id: 'p', models: ['broken-model', 'nomic-embed-text'] }, 'broken-model')).toBeNull();+ });+});++// =============================================================================+// Tiered fallback cascade (issue #2342) — a model-not-found failure attempts a+// deterministic Tier-1 config/env correction (retry the SAME provider with a+// valid listed model) BEFORE escalating to a Tier-3 fallback provider, and only+// an unrecovered failure escalates to a Tier-4 investigation task.+// =============================================================================++describe('promptRunner — Tier 1 config/env correction (issue #2342)', () => {+ const fallbackApi = apiProvider({ id: 'fallback-api', name: 'Fallback API', defaultModel: 'fb-model' });++ function mockToolkitWithFallback(fallback = fallbackApi) {+ const isAvailable = vi.fn().mockReturnValue(true);+ const markUnavailable = vi.fn().mockResolvedValue(undefined);+ const markUsageLimit = vi.fn().mockResolvedValue(undefined);+ const getFallbackProvider = vi.fn().mockReturnValue(fallback ? { provider: fallback, source: 'provider' } : null);+ toolkitState.getAIToolkitInstance.mockReturnValue({+ services: { providerStatus: { isAvailable, markUnavailable, markUsageLimit, getFallbackProvider } },+ });+ providers.getAllProviders.mockResolvedValue({ activeProvider: null, providers: fallback ? [fallback] : [] });+ return { isAvailable, markUnavailable, markUsageLimit, getFallbackProvider };+ }++ it('recovers a model-not-found by retrying the SAME provider with a valid listed model (never reaching Tier 3)', async () => {+ const status = mockToolkitWithFallback();+ const primary = apiProvider({ id: 'primary-api', name: 'Primary API', defaultModel: 'primary-model', models: ['primary-model', 'good-model'] });++ runner.executeApiRun.mockImplementation(async ({ model, onData, onComplete }) => {+ if (model === 'primary-model') {+ onComplete({ success: false, error: "model 'primary-model' not found", errorAnalysis: { category: ERROR_CATEGORIES.MODEL_NOT_FOUND } });+ } else {+ onData('corrected content');+ onComplete({ success: true });+ }+ });++ const out = await runPromptThroughProvider({ provider: primary, prompt: 'p', source: 'test' });++ expect(out.text).toBe('corrected content');+ expect(out.usedFallback).toBe(true);+ expect(out.fixTier).toBe(1);+ expect(out.fixStrategy).toBe('config/env');+ // Recovered on the SAME provider with the corrected model — Tier 3 untouched.+ expect(out.fallbackProvider).toMatchObject({ id: 'primary-api' });+ expect(out.model).toBe('good-model');+ expect(status.getFallbackProvider).not.toHaveBeenCalled();+ expect(status.markUnavailable).not.toHaveBeenCalled();+ // The primary's investigation task was suppressed up front and resolved.+ expect(autoFixer.noteFallbackStarted).toHaveBeenCalledWith({ provider: 'Primary API', model: 'primary-model' });+ expect(autoFixer.noteFallbackHandled).toHaveBeenCalledWith({ provider: 'Primary API', model: 'primary-model' });+ expect(autoFixer.noteFallbackFailed).not.toHaveBeenCalled();+ });++ it('declines Tier 1 when no alternative model exists and falls through to the Tier-3 fallback provider', async () => {+ const status = mockToolkitWithFallback();+ // Only the failed model is listed → pickConfigCorrectedModel returns null.+ const primary = apiProvider({ id: 'primary-api', name: 'Primary API', defaultModel: 'primary-model', models: ['primary-model'] });++ runner.executeApiRun.mockImplementation(async ({ provider: p, onData, onComplete }) => {+ if (p.id === 'primary-api') {+ onComplete({ success: false, error: 'model missing', errorAnalysis: { category: ERROR_CATEGORIES.MODEL_NOT_FOUND } });+ } else {+ onData('fallback content');+ onComplete({ success: true });+ }+ });++ const out = await runPromptThroughProvider({ provider: primary, prompt: 'p', source: 'test' });++ expect(out.text).toBe('fallback content');+ expect(out.usedFallback).toBe(true);+ expect(out.fixTier).toBe(3);+ expect(out.fixStrategy).toBe('constrained-agent-retry');+ expect(out.fallbackProvider).toMatchObject({ id: 'fallback-api' });+ // Tier 3 engaged: the fallback was looked up (MODEL_NOT_FOUND stays unbenched).+ expect(status.getFallbackProvider).toHaveBeenCalledWith('primary-api', expect.any(Object));+ expect(status.markUnavailable).not.toHaveBeenCalled();+ });++ it('escalates to Tier 3 when the Tier-1 corrected retry ALSO fails, and cancels both queued tasks on recovery', async () => {+ mockToolkitWithFallback();+ const primary = apiProvider({ id: 'primary-api', name: 'Primary API', defaultModel: 'primary-model', models: ['primary-model', 'good-model'] });++ runner.executeApiRun.mockImplementation(async ({ provider: p, model, onData, onComplete }) => {+ if (p.id === 'primary-api') {+ // Both the primary model AND the Tier-1 corrected model fail on this provider.+ onComplete({ success: false, error: `still broken (${model})`, errorAnalysis: { category: ERROR_CATEGORIES.MODEL_NOT_FOUND } });+ } else {+ onData('fallback content');+ onComplete({ success: true });+ }+ });++ const out = await runPromptThroughProvider({ provider: primary, prompt: 'p', source: 'test' });++ expect(out.text).toBe('fallback content');+ expect(out.fixTier).toBe(3);+ // Both the primary key and the Tier-1 corrected-model key are cancelled so a+ // fully-recovered action leaves ZERO investigation tasks.+ expect(autoFixer.noteFallbackHandled).toHaveBeenCalledWith({ provider: 'Primary API', model: 'primary-model' });+ expect(autoFixer.noteFallbackHandled).toHaveBeenCalledWith({ provider: 'Primary API', model: 'good-model' });+ expect(autoFixer.noteFallbackFailed).not.toHaveBeenCalled();+ });++ it('releases the Tier-1 suppression and rethrows when the corrected retry fails and no fallback exists', async () => {+ mockToolkitWithFallback(null); // no fallback available+ const primary = apiProvider({ id: 'primary-api', name: 'Primary API', defaultModel: 'primary-model', models: ['primary-model', 'good-model'] });++ runner.executeApiRun.mockImplementation(async ({ onComplete }) => {+ onComplete({ success: false, error: 'model gone', errorAnalysis: { category: ERROR_CATEGORIES.MODEL_NOT_FOUND } });+ });++ await expect(runPromptThroughProvider({ provider: primary, prompt: 'p', source: 'test' }))+ .rejects.toThrow(/model gone/);++ // The primary key was suppressed for the corrected retry, then released on+ // give-up so the in-flight set doesn't leak (the corrected retry's own+ // onRunFailed task survives as the escalation).+ expect(autoFixer.noteFallbackStarted).toHaveBeenCalledWith({ provider: 'Primary API', model: 'primary-model' });+ expect(autoFixer.noteFallbackFailed).toHaveBeenCalledWith({ provider: 'Primary API', model: 'primary-model' });+ expect(autoFixer.noteFallbackHandled).not.toHaveBeenCalled();+ });++ it('does NOT attempt a Tier-1 correction for non-model failure categories', async () => {+ const status = mockToolkitWithFallback();+ // A rate-limit (Tier 3) failure must skip the config/env correction even+ // though the provider lists an alternative model.+ const primary = apiProvider({ id: 'primary-api', name: 'Primary API', defaultModel: 'primary-model', models: ['primary-model', 'good-model'] });++ let primaryCalls = 0;+ runner.executeApiRun.mockImplementation(async ({ provider: p, onData, onComplete }) => {+ if (p.id === 'primary-api') {+ primaryCalls += 1;+ onComplete({ success: false, error: 'rate limited', errorAnalysis: { category: ERROR_CATEGORIES.RATE_LIMIT } });+ } else {+ onData('fallback content');+ onComplete({ success: true });+ }+ });++ const out = await runPromptThroughProvider({ provider: primary, prompt: 'p', source: 'test' });++ // The primary provider ran exactly once (no Tier-1 corrected retry) before+ // going straight to the Tier-3 fallback.+ expect(primaryCalls).toBe(1);+ expect(out.fixTier).toBe(3);+ expect(status.getFallbackProvider).toHaveBeenCalledWith('primary-api', expect.any(Object));+ });++ it('does NOT engage Tier 1 for a category-less failure even when the provider lists alternatives', async () => {+ // Regression: a failure with no errorAnalysis has category === undefined,+ // which must NOT match the model-not-found guard (the `undefined ===+ // ERROR_CATEGORIES.MODEL_NOT_SUPPORTED` footgun). The primary must run once,+ // then go straight to Tier 3 — never a same-provider model swap.+ const status = mockToolkitWithFallback();+ const primary = apiProvider({ id: 'primary-api', name: 'Primary API', defaultModel: 'primary-model', models: ['primary-model', 'good-model'] });++ let primaryCalls = 0;+ runner.executeApiRun.mockImplementation(async ({ provider: p, onData, onComplete }) => {+ if (p.id === 'primary-api') {+ primaryCalls += 1;+ onComplete({ success: false, error: 'exited with code 1' }); // no errorAnalysis+ } else {+ onData('fallback content');+ onComplete({ success: true });+ }+ });++ const out = await runPromptThroughProvider({ provider: primary, prompt: 'p', source: 'test' });++ expect(primaryCalls).toBe(1);+ expect(out.fixTier).toBe(3);+ expect(status.getFallbackProvider).toHaveBeenCalledWith('primary-api', expect.any(Object));+ });+});+describe('resolveEffectiveModel — embedding-model skip', () => {it('skips an embedding-first models list when defaultModel is null (the nomic-embed-text fallback bug)', () => {// Mirrors the real Ollama provider: defaultModel null, embedding model