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(brain): key-aware ack flash-provider fallback instead of hardcoded gemini
Ruben Lütke55b678ed63d3
diff --git a/jarvis/brain/factory.py b/jarvis/brain/factory.pyindex 642130725d..a60bb5057c 100644--- a/jarvis/brain/factory.py+++ b/jarvis/brain/factory.py@@ -1637,9 +1637,11 @@ def _build_flash_provider(jcfg: Any, ack_cfg: Any) -> Any:"follow_brain" meta-value: resolve to whatever ``brain.primary``currently points at, so the user does not have to keep two providersettings in sync. If the main brain is on a provider the Flash-Brain- has no adapter for (openrouter, claude_api), fall back to "gemini" —- the historical default. Mutates ``ack_cfg.provider`` to the resolved- name so telemetry labels show the concrete provider.+ has no adapter for (openrouter, claude_api), fall back to the first+ REGISTRY family with a usable credential (AP-22 — a hardcoded literal+ fallback would brick this tier for every downloader whose only key is+ e.g. OpenAI). Mutates ``ack_cfg.provider`` to the resolved name so+ telemetry labels show the concrete provider."""from jarvis.brain.ack_brain.providers import REGISTRY@@ -1654,12 +1656,21 @@ def _build_flash_provider(jcfg: Any, ack_cfg: Any) -> Any:)provider_name = primaryelse:+ fallback = _pick_keyed_flash_fallback(ack_cfg)+ if fallback is None:+ log.warning(+ "Flash-Brain: brain.primary=%r has no Flash adapter "+ "(REGISTRY=%s) and no REGISTRY provider has a usable "+ "credential; disabling Flash-Brain.",+ primary, sorted(REGISTRY.keys()),+ )+ return Nonelog.warning("Flash-Brain: brain.primary=%r has no Flash adapter "- "(REGISTRY=%s); falling back to gemini.",- primary, sorted(REGISTRY.keys()),+ "(REGISTRY=%s); falling back to keyed provider %r.",+ primary, sorted(REGISTRY.keys()), fallback,)- provider_name = "gemini"+ provider_name = fallbackack_cfg.provider = provider_nameprovider_cls = REGISTRY.get(provider_name)if provider_cls is None:@@ -1673,6 +1684,29 @@ def _build_flash_provider(jcfg: Any, ack_cfg: Any) -> Any:return provider_cls(provider_cfg)+def _pick_keyed_flash_fallback(ack_cfg: Any) -> str | None:+ """First REGISTRY provider family with a usable credential, or ``None``.++ AP-21/AP-22: never hardcode a literal provider name as the fallback — a+ downloader whose only key is e.g. OpenAI must resolve to "openai", not a+ keyless "gemini". Iterates ``REGISTRY`` in its declared order (gemini,+ openai, ollama, ...) as the tie-break so an all-keyed setup keeps the+ historical default. A provider config with no ``api_key_secret`` field+ (local Ollama) needs no credential and is always considered usable.+ """+ from jarvis.brain.ack_brain.providers import REGISTRY+ from jarvis.core.config import get_secret++ for name in REGISTRY:+ provider_cfg = getattr(ack_cfg.providers, name, None)+ if provider_cfg is None:+ continue+ secret_name = getattr(provider_cfg, "api_key_secret", None)+ if secret_name is None or get_secret(secret_name):+ return name+ return None++def _build_ack_fallback(ack_cfg: Any, preferences_provider: Any = None) -> Any:"""Build the secondary failover AckGenerator, or ``None``.diff --git a/tests/unit/brain/test_ack_brain/test_flash_provider_fallback.py b/tests/unit/brain/test_ack_brain/test_flash_provider_fallback.pynew file mode 100644index 0000000000..0027e5f283--- /dev/null+++ b/tests/unit/brain/test_ack_brain/test_flash_provider_fallback.py@@ -0,0 +1,91 @@+"""Tests for the Flash-Brain's key-aware ``follow_brain`` fallback (AP-22).++When ``brain.primary`` points at a provider the Flash-Brain has no adapter+for (openrouter, claude_api), ``_build_flash_provider`` used to fall back to+a hardcoded literal ``"gemini"`` — bricking the tier for any downloader whose+only configured key is for a different provider. The fallback must instead+pick the first REGISTRY family with a usable credential.+"""+from __future__ import annotations++from types import SimpleNamespace++import pytest++from jarvis.brain.factory import _build_flash_provider+from tests.unit.brain.test_ack_brain.conftest import make_ack_config+++def _jcfg(*, brain_primary: str) -> SimpleNamespace:+ return SimpleNamespace(brain=SimpleNamespace(primary=brain_primary))+++def test_falls_back_to_openai_when_only_openai_key_present(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """brain.primary="claude-api" has no Flash adapter; only an OpenAI key is+ configured — the fallback must resolve to "openai", never "gemini"."""++ def _fake_get_secret(key: str, env_fallback: str | None = None) -> str | None:+ return "sk-test" if key == "openai_api_key" else None++ monkeypatch.setattr("jarvis.core.config.get_secret", _fake_get_secret)++ ack_cfg = make_ack_config(provider="follow_brain")+ provider = _build_flash_provider(_jcfg(brain_primary="claude-api"), ack_cfg)++ assert ack_cfg.provider == "openai"+ assert type(provider).__name__ == "OpenAIMiniAck"+++def test_falls_back_to_gemini_when_only_gemini_key_present(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ def _fake_get_secret(key: str, env_fallback: str | None = None) -> str | None:+ return "gk-test" if key == "gemini_api_key" else None++ monkeypatch.setattr("jarvis.core.config.get_secret", _fake_get_secret)++ ack_cfg = make_ack_config(provider="follow_brain")+ provider = _build_flash_provider(_jcfg(brain_primary="claude-api"), ack_cfg)++ assert ack_cfg.provider == "gemini"+ assert type(provider).__name__ == "GeminiFlashAck"+++def test_falls_back_to_ollama_when_no_key_present_at_all(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """Ollama needs no credential (local endpoint) — it is the last-resort+ keyless fallback when no cloud provider has a usable key."""+ monkeypatch.setattr(+ "jarvis.core.config.get_secret", lambda key, env_fallback=None: None+ )++ ack_cfg = make_ack_config(provider="follow_brain")+ provider = _build_flash_provider(_jcfg(brain_primary="claude-api"), ack_cfg)++ assert ack_cfg.provider == "ollama"+ assert type(provider).__name__ == "OllamaFlashAck"+++def test_does_not_change_ack_behavior_when_primary_has_a_flash_adapter(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """When brain.primary IS a REGISTRY family, the fallback path is never+ consulted — no credential lookup happens at all."""+ called = False++ def _fail_get_secret(key: str, env_fallback: str | None = None) -> str | None:+ nonlocal called+ called = True+ return None++ monkeypatch.setattr("jarvis.core.config.get_secret", _fail_get_secret)++ ack_cfg = make_ack_config(provider="follow_brain")+ provider = _build_flash_provider(_jcfg(brain_primary="openai"), ack_cfg)++ assert ack_cfg.provider == "openai"+ assert type(provider).__name__ == "OpenAIMiniAck"+ assert called is Falsediff --git a/tests/unit/skills/test_runner_risk_gate.py b/tests/unit/skills/test_runner_risk_gate.pynew file mode 100644index 0000000000..da38ba9c22--- /dev/null+++ b/tests/unit/skills/test_runner_risk_gate.py@@ -0,0 +1,177 @@+"""Tests for SkillRunner's internal risk gate (AP-3).++A skill's ``TOOL:`` line must never bypass the same risk-tier discipline+every other tool invocation goes through. Before this fix, ``_check_risk``+was a no-op whenever no ``safety_enforcer`` was injected — which was ALWAYS+true, since none of the three production construction sites ever passed one+(``jarvis/ui/desktop_app.py``, ``jarvis/brain/factory.py``,+``jarvis/skills/cli.py``). These tests pin the fail-closed internal gate:+``block`` refuses, ``ask`` refuses (skills/cron triggers have no interactive+human to approve), ``safe``/``monitor`` still execute.+"""+from __future__ import annotations++from pathlib import Path+from typing import Any++import pytest++from jarvis.core.config import SafetyConfig+from jarvis.core.protocols import ExecutionContext, ToolResult+from jarvis.safety.risk_tier import RiskTierEvaluator+from jarvis.skills.runner import SkillRunner+from jarvis.skills.schema import (+ Skill,+ SkillFrontmatter,+ SkillLifecycleState,+ SkillRiskPolicy,+)+++class _StubRegistry:+ """SkillRunner only reads ``skill.name``/``skill.body`` — registry is unused."""+++class _FakeTool:+ """A tool whose OWN static ``risk_tier`` is "safe" — the gate must still+ refuse a block/ask-declared skill call, proving the SKILL's frontmatter+ ``risk_policy`` governs the decision, not the tool's own declaration."""++ name = "fake_tool"+ schema: dict[str, Any] = {}+ description = "test tool"+ risk_tier = "safe"++ def __init__(self) -> None:+ self.calls: list[dict[str, Any]] = []++ async def execute(self, args: dict[str, Any], ctx: ExecutionContext) -> ToolResult:+ self.calls.append(args)+ return ToolResult(success=True, output="ran")+++def _make_skill(tmp_path: Path, *, default_tier: str) -> Skill:+ fm = SkillFrontmatter(+ schema_version="1",+ name="gate_skill",+ description="tests the risk gate",+ risk_policy=SkillRiskPolicy(default_tier=default_tier), # type: ignore[arg-type]+ )+ body = 'Do the thing.\nTOOL: fake_tool {"x": 1}\n'+ return Skill(+ path=tmp_path / "gate_skill" / "SKILL.md",+ frontmatter=fm,+ body=body,+ state=SkillLifecycleState.ACTIVE,+ body_hash="cafe",+ error=None,+ )+++def _runner_with_default_safety(tool: Any) -> SkillRunner:+ """A SkillRunner whose internal risk gate is pinned to plain+ ``SafetyConfig()`` defaults — independent of whatever ``jarvis.toml``+ happens to be on the machine running the test."""+ runner = SkillRunner(+ registry=_StubRegistry(), tool_registry={"fake_tool": tool}, bus=None+ )+ runner._risk_evaluator_cache = RiskTierEvaluator(SafetyConfig())+ return runner+++async def test_block_tier_tool_is_refused(tmp_path: Path) -> None:+ tool = _FakeTool()+ runner = _runner_with_default_safety(tool)+ skill = _make_skill(tmp_path, default_tier="block")++ result = await runner.run(skill, args={})++ assert result.success is False+ assert tool.calls == [] # never executed+ assert "risk_tier denied" in (result.error or "")+++async def test_ask_tier_tool_is_refused_with_clear_message(tmp_path: Path) -> None:+ tool = _FakeTool()+ runner = _runner_with_default_safety(tool)+ skill = _make_skill(tmp_path, default_tier="ask")++ result = await runner.run(skill, args={})++ assert result.success is False+ assert tool.calls == []+ assert result.steps[0]["success"] is False+ assert "ask" in result.steps[0]["error"].lower()+ assert "approver" in result.steps[0]["error"].lower()+++async def test_safe_tier_tool_still_executes(tmp_path: Path) -> None:+ tool = _FakeTool()+ runner = _runner_with_default_safety(tool)+ skill = _make_skill(tmp_path, default_tier="safe")++ result = await runner.run(skill, args={})++ assert result.success is True+ assert len(tool.calls) == 1+++async def test_monitor_tier_tool_still_executes(tmp_path: Path) -> None:+ tool = _FakeTool()+ runner = _runner_with_default_safety(tool)+ skill = _make_skill(tmp_path, default_tier="monitor")++ result = await runner.run(skill, args={})++ assert result.success is True+ assert len(tool.calls) == 1+++async def test_approved_by_is_honest_risk_gate_label(tmp_path: Path) -> None:+ """The ``ExecutionContext`` passed to the tool must not fabricate an+ approval that never happened — it must name the internal risk gate."""+ seen_ctx: list[ExecutionContext] = []++ class _RecordingTool(_FakeTool):+ async def execute(self, args: dict[str, Any], ctx: ExecutionContext) -> ToolResult:+ seen_ctx.append(ctx)+ return await super().execute(args, ctx)++ tool = _RecordingTool()+ runner = _runner_with_default_safety(tool)+ skill = _make_skill(tmp_path, default_tier="safe")++ await runner.run(skill, args={})++ assert seen_ctx+ assert seen_ctx[0].approved_by == "skill-runner:risk-gate"+++async def test_injected_safety_enforcer_still_takes_priority(tmp_path: Path) -> None:+ """Back-compat: an explicitly injected ``safety_enforcer`` overrides the+ internal gate entirely — its ``.check()`` decides."""++ class _DenyEnforcer:+ def check(self, *, tool_name: str, tier: str) -> tuple[bool, str]:+ return False, "enforcer-says-no"++ tool = _FakeTool()+ runner = SkillRunner(+ registry=_StubRegistry(),+ tool_registry={"fake_tool": tool},+ bus=None,+ safety_enforcer=_DenyEnforcer(),+ )+ skill = _make_skill(tmp_path, default_tier="safe") # would pass the internal gate++ result = await runner.run(skill, args={})++ assert result.success is False+ assert tool.calls == []+ assert "enforcer-says-no" in (result.steps[0].get("error") or "")