Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
fix(wiki): key-aware provider fallback so background capture survives a dead provider
Ruben Lütke37c9374c66d4
diff --git a/jarvis/memory/wiki/curator_llm.py b/jarvis/memory/wiki/curator_llm.pyindex 1845be93cf..5ec323c68f 100644--- a/jarvis/memory/wiki/curator_llm.py+++ b/jarvis/memory/wiki/curator_llm.py@@ -380,10 +380,6 @@ class WikiCuratorLLM:)return []- brain = await self._ensure_brain()- if brain is None:- return []-vault_summary = await asyncio.to_thread(compute_vault_summary, vault, log_path=self._log_path,)@@ -402,25 +398,29 @@ class WikiCuratorLLM:)start_ns = time.time_ns()- try:- agg = await asyncio.wait_for(- aggregate(brain.complete(request)),- timeout=self._cfg.timeout_s,- )- except TimeoutError:- duration_ms = (time.time_ns() - start_ns) // 1_000_000- logger.warning(- "WikiCuratorLLM timeout after %dms (config timeout_s=%.1f, provider=%s)",- duration_ms, self._cfg.timeout_s, self._resolved_provider,- )- return []- except Exception as exc: # noqa: BLE001- duration_ms = (time.time_ns() - start_ns) // 1_000_000- logger.warning(- "WikiCuratorLLM brain-call failed after %dms (provider=%s): %s",- duration_ms, self._resolved_provider, exc,- )+ from jarvis.memory.wiki.provider_chain import (+ build_wiki_provider_chain,+ complete_with_fallback,+ )++ # Key-aware fallback (AP-22/23): cross to a reachable family instead of+ # dying on one dead / throttled provider (live 2026-06-30 silent brick).+ chain = build_wiki_provider_chain(+ primary=(self._cfg.provider.strip() or self._config.brain.primary),+ model_override=self._cfg.model,+ available=set(self._registry.available()),+ )+ result = await complete_with_fallback(+ registry=self._registry,+ chain=chain,+ request=request,+ timeout_s=self._cfg.timeout_s,+ label="WikiCuratorLLM",+ aggregate=aggregate,+ )+ if result is None:return []+ agg, self._resolved_provider = resultif is_length_truncated(agg.finish_reason, agg.text):duration_ms = (time.time_ns() - start_ns) // 1_000_000diff --git a/jarvis/memory/wiki/extractor.py b/jarvis/memory/wiki/extractor.pyindex 3be2755ad2..97a8dae4d6 100644--- a/jarvis/memory/wiki/extractor.py+++ b/jarvis/memory/wiki/extractor.py@@ -199,10 +199,6 @@ class ConversationFactExtractor:# ------------------------------------------------------------------async def _extract(self, user_text: str, assistant_text: str) -> list[CandidateFact]:- brain = self._ensure_brain()- if brain is None:- return []-context = assistant_text[:_MAX_ASSISTANT_CONTEXT_CHARS]# Real-time anchor so relative phrases ("last month", "this spring")# resolve to the correct year downstream.@@ -221,23 +217,30 @@ class ConversationFactExtractor:)start_ns = time.time_ns()- try:- agg = await asyncio.wait_for(- aggregate(brain.complete(request)),- timeout=float(self._cfg.timeout_s),- )- except TimeoutError:- log.warning(- "ConversationFactExtractor: timeout after %.1fs (provider=%s)",- self._cfg.timeout_s, self._resolved_provider,- )- return []- except Exception as exc: # noqa: BLE001- log.warning(- "ConversationFactExtractor: brain call failed (provider=%s): %s",- self._resolved_provider, exc,- )+ from jarvis.memory.wiki.provider_chain import (+ build_wiki_provider_chain,+ complete_with_fallback,+ )++ # Key-aware fallback (AP-22/23): try the configured provider, then cross+ # to whatever family is reachable, instead of silently dropping the turn+ # when one provider is throttled / keyless (live 2026-06-30).+ chain = build_wiki_provider_chain(+ primary=(self._curator_cfg.provider.strip() or self._root_cfg.brain.primary),+ model_override=self._curator_cfg.model,+ available=set(self._registry.available()),+ )+ result = await complete_with_fallback(+ registry=self._registry,+ chain=chain,+ request=request,+ timeout_s=float(self._cfg.timeout_s),+ label="ConversationFactExtractor",+ aggregate=aggregate,+ )+ if result is None:return []+ agg, self._resolved_provider = resultif is_length_truncated(agg.finish_reason, agg.text):log.warning(diff --git a/jarvis/memory/wiki/provider_chain.py b/jarvis/memory/wiki/provider_chain.pyindex a337ff2e94..4c7ed94a40 100644--- a/jarvis/memory/wiki/provider_chain.py+++ b/jarvis/memory/wiki/provider_chain.py@@ -19,6 +19,7 @@ credit. This module gives the wiki the SAME resilience, plus an HONEST signalwhen the whole chain is exhausted (AP-22 single-provider brick / AP-23maintainer-config coupling)."""+from __future__ import annotationsimport asyncio@@ -88,7 +89,9 @@ async def complete_with_fallback(try:brain = instantiate_curator_brain(registry, provider, model)except Exception as exc: # noqa: BLE001 — a bad provider must not abort the chain- log.warning("%s: could not instantiate %s (%s) — trying next provider", label, provider, exc)+ log.warning(+ "%s: could not instantiate %s (%s) — trying next provider", label, provider, exc+ )continueif brain is None:continue@@ -96,7 +99,12 @@ async def complete_with_fallback(agg = await asyncio.wait_for(aggregate(brain.complete(request)), timeout=timeout_s)return agg, providerexcept TimeoutError:- log.warning("%s: provider %s timed out after %.1fs — trying next provider", label, provider, timeout_s)+ log.warning(+ "%s: provider %s timed out after %.1fs — trying next provider",+ label,+ provider,+ timeout_s,+ )continueexcept Exception as exc: # noqa: BLE001 — try the next family, never dead-end on onelog.warning("%s: provider %s failed (%s) — trying next provider", label, provider, exc)@@ -111,7 +119,7 @@ async def complete_with_fallback(try:telemetry.inc("wiki_all_providers_failed")except Exception: # noqa: BLE001 — telemetry must never break the pipeline- pass+ log.debug("%s: telemetry inc failed", label, exc_info=True)return Nonediff --git a/tests/integration/memory/test_three_triggers.py b/tests/integration/memory/test_three_triggers.pyindex bda5e3e9bd..dda8292d60 100644--- a/tests/integration/memory/test_three_triggers.py+++ b/tests/integration/memory/test_three_triggers.py@@ -116,6 +116,9 @@ class _SpyRegistry:self._brain = brainself.instantiate_calls: list[tuple[str, dict[str, Any]]] = []+ def available(self) -> set[str]:+ return {"gemini", "claude-api", "openrouter", "openai"}+def instantiate(self, name: str, **kwargs: Any) -> Any:self.instantiate_calls.append((name, dict(kwargs)))return self._braindiff --git a/tests/integration/memory/wiki/test_two_stage_e2e.py b/tests/integration/memory/wiki/test_two_stage_e2e.pyindex d0d416a55b..57e878b4d5 100644--- a/tests/integration/memory/wiki/test_two_stage_e2e.py+++ b/tests/integration/memory/wiki/test_two_stage_e2e.py@@ -98,6 +98,9 @@ class FakeRegistry:def __init__(self, brain: Any) -> None:self._brain = brain+ def available(self) -> set[str]:+ return {"gemini"}+def instantiate(self, name: str, **kwargs: Any) -> Any:return self._braindiff --git a/tests/unit/memory/wiki/test_conversation_observer.py b/tests/unit/memory/wiki/test_conversation_observer.pyindex 54bda30d43..86ba17ee03 100644--- a/tests/unit/memory/wiki/test_conversation_observer.py+++ b/tests/unit/memory/wiki/test_conversation_observer.py@@ -72,6 +72,11 @@ class FakeRegistry:def __init__(self, brain: Any) -> None:self._brain = brain+ def available(self) -> set[str]:+ # The configured primary is reachable, so the key-aware fallback chain+ # is a single hop to it.+ return {"gemini"}+def instantiate(self, name: str, **kwargs: Any) -> Any:return self._braindiff --git a/tests/unit/memory/wiki/test_curator_llm.py b/tests/unit/memory/wiki/test_curator_llm.pyindex 3798124577..306c5d39fb 100644--- a/tests/unit/memory/wiki/test_curator_llm.py+++ b/tests/unit/memory/wiki/test_curator_llm.py@@ -77,11 +77,28 @@ class FakeBrain:class FakeRegistry:"""Stand-in for ``BrainProviderRegistry`` that yields a pre-built brain."""- def __init__(self, brain: Any, *, fail_on: str | None = None) -> None:+ def __init__(+ self,+ brain: Any,+ *,+ fail_on: str | None = None,+ available: set[str] | None = None,+ ) -> None:self._brain = brainself._fail_on = fail_on+ # Default to the families the wiki fallback chain may cross to, so a+ # configured primary leads and succeeds first. A test pins a narrower+ # set to exercise the all-providers-down (chain-exhausted) path.+ self._available = (+ set(available)+ if available is not None+ else {"gemini", "claude-api", "openrouter", "openai"}+ )self.instantiate_calls: list[tuple[str, dict[str, Any]]] = []+ def available(self) -> set[str]:+ return set(self._available)+def instantiate(self, name: str, **kwargs: Any) -> Any:self.instantiate_calls.append((name, dict(kwargs)))if self._fail_on is not None and name == self._fail_on:@@ -448,7 +465,8 @@ async def test_propose_updates_timeout_returns_empty("source", "label", repo=FakeRepo(), vault=FakeVault(),)assert result == []- assert any("timeout" in rec.message.lower() for rec in caplog.records)+ # Every provider timed out → the chain is exhausted and gives up honestly.+ assert any("timed out" in rec.message.lower() for rec in caplog.records)@pytest.mark.asyncio@@ -471,7 +489,11 @@ async def test_propose_updates_brain_exception_returns_empty("source", "label", repo=FakeRepo(), vault=FakeVault(),)assert result == []- assert any("brain-call failed" in rec.message.lower() for rec in caplog.records)+ # The chain tries every family, then gives up HONESTLY (not a silent empty).+ assert any(+ "failed" in rec.message.lower() and "provider" in rec.message.lower()+ for rec in caplog.records+ )@pytest.mark.asyncio@@ -501,11 +523,15 @@ async def test_propose_updates_missing_schema_returns_empty(async def test_propose_updates_unavailable_provider_returns_empty(tmp_path: Path, caplog: pytest.LogCaptureFixture,) -> None:- """A registry that doesn't know the provider name yields ``[]``."""+ """An unavailable provider with NOTHING to fall back to yields ``[]``."""cfg = _make_config(primary="nonsense-provider")brain = FakeBrain(_ok_response())- registry = FakeRegistry(brain, fail_on="nonsense-provider")+ # Only the (failing) primary is reachable — the chain has nothing to cross+ # to, so it is exhausted and the curator gives up honestly.+ registry = FakeRegistry(+ brain, fail_on="nonsense-provider", available={"nonsense-provider"},+ )llm = WikiCuratorLLM(config=cfg,@@ -517,12 +543,19 @@ async def test_propose_updates_unavailable_provider_returns_empty("source", "label", repo=FakeRepo(), vault=FakeVault(),)assert result == []- assert any("cannot instantiate" in rec.message.lower() for rec in caplog.records)+ assert any("instantiate" in rec.message.lower() for rec in caplog.records)@pytest.mark.asyncio-async def test_propose_updates_caches_brain_across_calls(tmp_path: Path) -> None:- """The provider is instantiated at most once per ``WikiCuratorLLM``."""+async def test_propose_updates_reresolves_provider_per_call(tmp_path: Path) -> None:+ """The key-aware fallback chain re-resolves the provider on every call.++ The old single-brain cache (one instantiate per instance) was replaced by a+ per-call chain so a provider switch — or a previously-dead provider that+ recovered — is picked up immediately. A SUCCESSFUL call still stops at the+ first working provider (no needless fallback instantiation), so two+ successful calls instantiate exactly twice — never the whole chain.+ """cfg = _make_config()brain = FakeBrain(_ok_response())@@ -535,7 +568,8 @@ async def test_propose_updates_caches_brain_across_calls(tmp_path: Path) -> None)await llm.propose_updates("first source", "l1", repo=FakeRepo(), vault=FakeVault())await llm.propose_updates("second source", "l2", repo=FakeRepo(), vault=FakeVault())- assert len(registry.instantiate_calls) == 1+ assert len(registry.instantiate_calls) == 2+ assert [name for name, _ in registry.instantiate_calls] == ["gemini", "gemini"]@pytest.mark.asynciodiff --git a/tests/unit/memory/wiki/test_extractor.py b/tests/unit/memory/wiki/test_extractor.pyindex 1c23869027..59a3e6d5ac 100644--- a/tests/unit/memory/wiki/test_extractor.py+++ b/tests/unit/memory/wiki/test_extractor.py@@ -61,6 +61,12 @@ class FakeRegistry:self._brain = brainself.instantiate_calls: list[tuple[str, dict[str, Any]]] = []+ def available(self) -> set[str]:+ # Only the configured primary is reachable, so the key-aware fallback+ # chain is a single hop — the existing assertions on the first (only)+ # instantiated provider still hold.+ return {"gemini"}+def instantiate(self, name: str, **kwargs: Any) -> Any:self.instantiate_calls.append((name, dict(kwargs)))return self._braindiff --git a/tests/unit/memory/wiki/test_provider_chain.py b/tests/unit/memory/wiki/test_provider_chain.pyindex fe05b70057..40e7766d87 100644--- a/tests/unit/memory/wiki/test_provider_chain.py+++ b/tests/unit/memory/wiki/test_provider_chain.py@@ -7,6 +7,7 @@ journaled/wrote nothing — while the main brain limped on via its chain. Thesetests pin the new resilience: cross to a working FAMILY, give up honestly onlywhen ALL fail."""+from __future__ import annotationsfrom typing import Any@@ -25,15 +26,15 @@ _ALL = {"openrouter", "gemini", "claude-api", "openai"}def test_chain_leads_with_primary_then_crosses_families():chain = build_wiki_provider_chain(primary="openrouter", model_override="", available=_ALL)providers = [p for p, _ in chain]- assert providers[0] == "openrouter" # configured/primary first- assert "claude-api" in providers # then a different family+ assert providers[0] == "openrouter" # configured/primary first+ assert "claude-api" in providers # then a different familyassert "gemini" in providers- assert providers.count("openrouter") == 1 # primary not duplicated+ assert providers.count("openrouter") == 1 # primary not duplicateddef test_chain_keeps_only_available_providers():chain = build_wiki_provider_chain(primary="gemini", model_override="", available={"gemini"})- assert [p for p, _ in chain] == ["gemini"] # nothing to cross to+ assert [p for p, _ in chain] == ["gemini"] # nothing to cross todef test_model_override_applies_only_to_primary():@@ -41,7 +42,7 @@ def test_model_override_applies_only_to_primary():primary="gemini", model_override="gemini-custom-x", available={"gemini", "claude-api"})by = dict(chain)- assert by["gemini"] == "gemini-custom-x" # explicit model honored for primary+ assert by["gemini"] == "gemini-custom-x" # explicit model honored for primaryassert by["claude-api"] != "gemini-custom-x" # fallback gets its OWN cheap model@@ -83,36 +84,54 @@ async def _aggregate(stream: Any) -> Any:async def test_falls_over_to_first_working_provider():reg = _FakeRegistry(fail_providers={"openrouter", "gemini"})- chain = build_wiki_provider_chain(primary="openrouter", model_override="", available=reg.available())+ chain = build_wiki_provider_chain(+ primary="openrouter", model_override="", available=reg.available()+ )result = await complete_with_fallback(- registry=reg, chain=chain, request=object(), timeout_s=5.0,- label="test", aggregate=_aggregate,+ registry=reg,+ chain=chain,+ request=object(),+ timeout_s=5.0,+ label="test",+ aggregate=_aggregate,)assert result is not Noneagg, provider = result- assert provider == "claude-api" # crossed past the two dead ones+ assert provider == "claude-api" # crossed past the two dead onesassert reg.tried == ["openrouter", "claude-api"]assert agg.text == "chunk"async def test_returns_none_only_when_every_provider_fails():reg = _FakeRegistry(fail_providers=set(_ALL))- chain = build_wiki_provider_chain(primary="openrouter", model_override="", available=reg.available())+ chain = build_wiki_provider_chain(+ primary="openrouter", model_override="", available=reg.available()+ )result = await complete_with_fallback(- registry=reg, chain=chain, request=object(), timeout_s=5.0,- label="test", aggregate=_aggregate,+ registry=reg,+ chain=chain,+ request=object(),+ timeout_s=5.0,+ label="test",+ aggregate=_aggregate,)- assert result is None # honest give-up, not a crash- assert set(reg.tried) == _ALL # it really tried all families+ assert result is None # honest give-up, not a crash+ assert set(reg.tried) == _ALL # it really tried all familiesasync def test_first_provider_success_does_not_try_others():reg = _FakeRegistry(fail_providers=set())- chain = build_wiki_provider_chain(primary="gemini", model_override="", available=reg.available())+ chain = build_wiki_provider_chain(+ primary="gemini", model_override="", available=reg.available()+ )result = await complete_with_fallback(- registry=reg, chain=chain, request=object(), timeout_s=5.0,- label="test", aggregate=_aggregate,+ registry=reg,+ chain=chain,+ request=object(),+ timeout_s=5.0,+ label="test",+ aggregate=_aggregate,)assert result is not Noneassert result[1] == "gemini"- assert reg.tried == ["gemini"] # no needless fallback calls+ assert reg.tried == ["gemini"] # no needless fallback calls