Skip to content

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.

feat(brain): keyless local Ollama provider

Ruben Lütke814a4dbe2ea3
diff --git a/jarvis/core/config.py b/jarvis/core/config.py
index 2f537885e2..a90a06cfdd 100644
--- a/jarvis/core/config.py
+++ b/jarvis/core/config.py
@@ -2630,6 +2630,36 @@ def _coerce_env_value(v: str) -> Any:
return v
+def _dedupe_worker_tier_tables(data: dict[str, Any]) -> dict[str, Any]:
+ """Resolve the [brain.worker] vs legacy [brain.sub_jarvis] split-brain.
+
+ Both tables populate the SAME field (``BrainConfig.worker`` via
+ ``AliasChoices``); a file carrying both is a latent conflict whose winner
+ would otherwise be an artifact of alias ordering. Make it explicit code:
+ the canonical ``[brain.worker]`` wins, the legacy table is dropped from
+ the parsed dict, and ONE warning names both values so the operator can
+ see what was ignored. A file with only the legacy table stays untouched
+ (read-compat for pre-rename installs). The on-disk heal lives in
+ ``config_writer.migrate_worker_tier_table`` (called at boot).
+ """
+ brain = data.get("brain")
+ if not isinstance(brain, dict):
+ return data
+ worker = brain.get("worker")
+ legacy = brain.get("sub_jarvis")
+ if isinstance(worker, dict) and isinstance(legacy, dict):
+ logging.getLogger(__name__).warning(
+ "config: both [brain.worker] (provider=%r) and legacy "
+ "[brain.sub_jarvis] (provider=%r) are present — [brain.worker] "
+ "wins; the legacy table is ignored and will be merged away at "
+ "the next boot heal.",
+ worker.get("provider"),
+ legacy.get("provider"),
+ )
+ brain.pop("sub_jarvis", None)
+ return data
+
+
def _migrate_worker_env_vars() -> None:
"""Process-local back-compat shim for the sub_jarvis → worker rename.
@@ -2679,6 +2709,9 @@ def load_config(
if profile_file.exists():
data = _deep_merge(data, _load_yaml(profile_file))
+ # Deterministic winner for the worker-tier split-brain BEFORE env
+ # overrides land (env writes into brain.worker and wins regardless).
+ data = _dedupe_worker_tier_tables(data)
# Back-compat shim: copy old JARVIS__BRAIN__SUB_JARVIS__* to new
# JARVIS__BRAIN__WORKER__* if only the old names are set (process-local).
_migrate_worker_env_vars()
diff --git a/jarvis/core/config_writer.py b/jarvis/core/config_writer.py
index b1034d6253..ecdff5ff9e 100644
--- a/jarvis/core/config_writer.py
+++ b/jarvis/core/config_writer.py
@@ -287,6 +287,72 @@ def set_worker_model(model: str, *, path: Path = DEFAULT_CONFIG_FILE) -> None:
_sync_worker_model_drift_soll(model) # i18n-allow
+def migrate_worker_tier_table(*, path: Path = DEFAULT_CONFIG_FILE) -> bool:
+ """One-time boot heal for the [brain.sub_jarvis] / [brain.worker] split-brain.
+
+ Both tables feed the SAME config field (``BrainConfig.worker`` via
+ ``AliasChoices``), so a file carrying both is a latent conflict: the
+ canonical ``[brain.worker]`` wins at load time while the legacy table
+ silently rots (live case 2026-07-25: ``provider = "antigravity"`` vs
+ ``"openai-codex"``, with the whole ``fallback_*`` chain stranded in the
+ dead table). This migration makes the file match what the loader
+ already resolves:
+
+ * both tables present -> copy legacy-ONLY keys (e.g. the ``fallback_*``
+ chain) into ``[brain.worker]``, then drop ``[brain.sub_jarvis]``;
+ keys present in both keep the canonical worker value.
+ * only the legacy table -> its keys move to ``[brain.worker]`` verbatim.
+ * no legacy table -> no-op (a cheap string probe skips the parse).
+
+ Returns True when the file was rewritten. Best-effort by design: a
+ missing file, unparsable TOML, or a write failure (read-only flag /
+ drift-guard EPERM) degrades to a logged no-op — boot must never break
+ on this heal. Reading old files keeps working either way through the
+ ``AliasChoices`` read-compat alias, which stays.
+ """
+ try:
+ if path == DEFAULT_CONFIG_FILE:
+ from jarvis.core.config import resolve_config_path # noqa: PLC0415
+
+ path = resolve_config_path()
+ if not path.exists():
+ return False
+ with _WRITE_LOCK:
+ raw = path.read_text(encoding="utf-8")
+ had_bom = raw.startswith(_BOM)
+ if had_bom:
+ raw = raw[len(_BOM) :]
+ # Fast path: steady-state boots pay one file read, no TOML parse.
+ if "sub_jarvis" not in raw:
+ return False
+ doc: TOMLDocument = tomlkit.parse(raw)
+ brain = doc.get("brain")
+ if brain is None or "sub_jarvis" not in brain:
+ return False
+ legacy = brain["sub_jarvis"]
+ worker = brain.get("worker")
+ if worker is None:
+ worker = tomlkit.table()
+ brain["worker"] = worker
+ if isinstance(legacy, dict):
+ for key in legacy:
+ if key not in worker:
+ worker[key] = legacy[key]
+ del brain["sub_jarvis"]
+ out = tomlkit.dumps(doc)
+ if had_bom:
+ out = _BOM + out
+ _atomic_write(path, out)
+ log.info(
+ "Merged legacy [brain.sub_jarvis] into canonical [brain.worker] (%s).",
+ path,
+ )
+ return True
+ except Exception as exc: # noqa: BLE001 — boot heal must never raise
+ log.warning("Worker-tier TOML migration skipped: %s", exc)
+ return False
+
+
# Back-compat alias — callers that imported set_sub_jarvis_model still work.
set_sub_jarvis_model = set_worker_model
diff --git a/jarvis/plugins/brain/ollama.py b/jarvis/plugins/brain/ollama.py
new file mode 100644
index 0000000000..d855e3b6e8
--- /dev/null
+++ b/jarvis/plugins/brain/ollama.py
@@ -0,0 +1,159 @@
+"""Ollama — keyless local brain via Ollama's OpenAI-compatible endpoint.
+
+Runs whatever models the user has pulled into a local (or LAN) Ollama server —
+no API key, no cloud account, nothing leaves the machine. The server's ``/v1``
+endpoint speaks the OpenAI Chat-Completions format, so this brain is a thin
+binding of the shared ``_openai_base`` streamer to the server root resolved
+from ``[brain.providers.ollama].base_url`` / ``OLLAMA_HOST`` / the localhost
+default — the same shape as the NVIDIA brain.
+
+Keyless by design (§3 / AP-22): ``ollama`` is deliberately ABSENT from
+``PROVIDER_SECRET_CANDIDATES`` — that absence is what makes the key-aware
+resolver treat it as always reachable. A dead server fast-fails on the 2 s
+connect timeout so the fallback chain crosses to the next family instead of
+stalling. Tool calling rides the OpenAI-compat layer (``tool_choice`` is not
+used on the pipeline path); reliability is model-dependent — the qwen line is
+the recommended pull.
+
+Model discovery is NATIVE (``/api/tags``): with no configured model the brain
+runs the first installed one, and a model-less server produces an honest
+"pull one first" error instead of a hardcoded default that would 404.
+"""
+
+from __future__ import annotations
+
+import logging
+import os
+from collections.abc import AsyncIterator
+from typing import Any
+
+import httpx
+
+from jarvis.core import config as cfg
+from jarvis.core.protocols import BrainDelta, BrainRequest
+
+from ._openai_base import stream_complete
+
+log = logging.getLogger(__name__)
+
+DEFAULT_SERVER_ROOT = "http://localhost:11434"
+
+# A tools-capable local model line that streams tool calls reliably through
+# the OpenAI-compat layer (Gemma-family models have known streaming-tool-call
+# defects there). Used in error/help text only — never silently pulled.
+RECOMMENDED_PULL = "qwen3.5"
+
+# Local server: an unreachable endpoint must fail fast (2 s) so the fallback
+# chain moves on, while a slow CPU-bound generation may legitimately stream
+# for minutes — hence the wide read timeout.
+CLIENT_TIMEOUT = httpx.Timeout(connect=2.0, read=120.0, write=30.0, pool=30.0)
+
+
+def normalize_server_root(url: str) -> str:
+ """Normalize a user/env-supplied Ollama address to a bare server root.
+
+ Accepts ``host:port``, a full URL, a trailing slash, or a pasted ``…/v1``
+ / ``…/api`` suffix and always returns ``scheme://host[:port]`` so callers
+ append ``/v1`` (chat) or ``/api/...`` (native) themselves. ``0.0.0.0`` is
+ a server BIND address, not a client target (connecting to it fails on
+ Windows), so it maps to localhost.
+ """
+ root = (url or "").strip().rstrip("/")
+ if not root:
+ return DEFAULT_SERVER_ROOT
+ if "://" not in root:
+ root = f"http://{root}"
+ for suffix in ("/v1", "/api"):
+ if root.endswith(suffix):
+ root = root[: -len(suffix)]
+ root = root.replace("://0.0.0.0", "://localhost")
+ return root.rstrip("/")
+
+
+def default_server_root() -> str:
+ """Vendor-default server root: ``OLLAMA_HOST`` if set, else localhost.
+
+ Ollama's own CLI honors ``OLLAMA_HOST`` for both serving and connecting,
+ so a user who moved their server declares it exactly once.
+ """
+ return normalize_server_root(os.environ.get("OLLAMA_HOST") or DEFAULT_SERVER_ROOT)
+
+
+class OllamaBrain:
+ name: str = "ollama"
+ # Conservative floor — the real window is model-dependent (the qwen line
+ # reaches 128k); the manager treats this as a budget hint, not a hard cap.
+ context_window: int = 32_768
+ supports_tools: bool = True
+ supports_vision: bool = True
+
+ def __init__(self, model: str | None = None) -> None:
+ self._model = (model or "").strip()
+ self._client: Any = None
+ self._server_root: str | None = None
+ self._credential: str | None = None
+
+ def can_call_tools(self) -> bool:
+ return self.supports_tools
+
+ def _resolve_root(self) -> str:
+ if self._server_root is None:
+ ep = cfg.resolve_provider_endpoint(
+ "ollama", vendor_default_base_url=default_server_root()
+ )
+ # Root convention: the stored/resolved value is the SERVER root;
+ # ``/v1`` (chat) and ``/api/*`` (discovery) are appended here. A
+ # team-proxy target (``…/p/ollama``) follows the same convention.
+ self._server_root = normalize_server_root(ep.base_url or default_server_root())
+ self._credential = ep.credential
+ return self._server_root
+
+ def _ensure_client(self) -> Any:
+ if self._client is None:
+ root = self._resolve_root()
+ from openai import AsyncOpenAI
+
+ self._client = AsyncOpenAI(
+ # A local Ollama ignores the key entirely, but the SDK insists
+ # on a non-empty one; a team proxy swaps in its real token.
+ api_key=self._credential or "ollama",
+ base_url=f"{root}/v1",
+ timeout=CLIENT_TIMEOUT,
+ )
+ return self._client
+
+ async def _resolve_model(self) -> str:
+ """The configured model, else the first installed one (``/api/tags``)."""
+ if self._model:
+ return self._model
+ root = self._resolve_root()
+ try:
+ async with httpx.AsyncClient(timeout=CLIENT_TIMEOUT) as client:
+ resp = await client.get(f"{root}/api/tags")
+ resp.raise_for_status()
+ models = resp.json().get("models") or []
+ except Exception as exc:
+ raise RuntimeError(
+ f"Ollama not reachable at {root} — is it running? Start it "
+ "(or install from https://ollama.com/download), then retry."
+ ) from exc
+ names = [str(m.get("name") or "").strip() for m in models]
+ names = [n for n in names if n]
+ if not names:
+ raise RuntimeError(
+ f"Ollama at {root} has no models installed — run: "
+ f"ollama pull {RECOMMENDED_PULL}, then retry."
+ )
+ self._model = names[0]
+ log.info("ollama: no model configured — using first installed: %s", self._model)
+ return self._model
+
+ async def complete(self, req: BrainRequest) -> AsyncIterator[BrainDelta]:
+ client = self._ensure_client()
+ model = await self._resolve_model()
+ async for delta in stream_complete(client, model, req):
+ yield delta
+
+ def estimate_cost(self, req: BrainRequest) -> float:
+ # Local inference has no per-token bill.
+ return 0.0
diff --git a/jarvis/ui/web/launcher.py b/jarvis/ui/web/launcher.py
index 5851604b58..c426b65cc7 100644
--- a/jarvis/ui/web/launcher.py
+++ b/jarvis/ui/web/launcher.py
@@ -1105,6 +1105,17 @@ def main(argv: list[str] | None = None) -> int:
"Healed stale inherited provider env from registry: %s", healed
)
+ # One-time worker-tier heal BEFORE load_config: merge the legacy
+ # [brain.sub_jarvis] table into the canonical [brain.worker] so the two
+ # can never disagree again (config split-brain). Cheap no-op on healed
+ # files; internally best-effort and never blocks boot.
+ try:
+ from jarvis.core.config_writer import migrate_worker_tier_table
+
+ migrate_worker_tier_table()
+ except Exception: # noqa: BLE001, S110 — boot heal must never block startup
+ pass
+
cfg = load_config()
_m_mark("parse_cwd_env_loadconfig")
diff --git a/jarvis/ui/web/provider_spec.py b/jarvis/ui/web/provider_spec.py
index 82a0a270bf..20dd486d37 100644
--- a/jarvis/ui/web/provider_spec.py
+++ b/jarvis/ui/web/provider_spec.py
@@ -264,7 +264,26 @@ PROVIDERS: tuple[ProviderSpec, ...] = (
"background tasks, sluggish as your main or voice brain."
),
),
- # Ollama provider removed 2026-04-21 — pure API-provider chain.
+ # Ollama re-added 2026-07-25 as a keyless LOCAL provider (auth_mode
+ # "none" → billing "local"); the 2026-04-21 removal predates the
+ # local-first mandate.
+ ProviderSpec(
+ id="ollama",
+ label="Ollama (local)",
+ tier="brain",
+ auth_mode="none",
+ secret_keys=(),
+ dashboard_url=None,
+ install_hint="ollama pull qwen3.5",
+ signup_url="https://ollama.com/download",
+ credential_help=(
+ "Runs models fully local through an Ollama server — no API key, "
+ "no cloud account, nothing leaves this machine. Install Ollama, "
+ "pull a tools-capable model (e.g. ollama pull qwen3.5), and "
+ "Jarvis finds it at http://localhost:11434 automatically. Point "
+ "the server URL at another machine to share one Ollama box."
+ ),
+ ),
# ── TTS ───────────────────────────────────────────────────────────────
# Voice-Output cards render in this tuple order. OpenRouter leads (one key
# reaches many vetted speech models); Inworld sits last as a premium
diff --git a/pyproject.toml b/pyproject.toml
index b28bed61e7..d70ce9b303 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -409,7 +409,9 @@ gemini = "jarvis.plugins.brain.gemini:GeminiBrain"
codex = "jarvis.plugins.brain.codex:CodexBrain"
antigravity = "jarvis.plugins.brain.antigravity:AntigravityBrain"
grok = "jarvis.plugins.brain.grok:GrokBrain"
-# Ollama provider removed on 2026-04-21; the runtime uses the API provider chain.
+# Keyless LOCAL provider (2026-07-25, local-first mandate): talks to a local
+# Ollama server, deliberately absent from PROVIDER_SECRET_CANDIDATES.
+ollama = "jarvis.plugins.brain.ollama:OllamaBrain"
[project.entry-points."jarvis.harness"]
python-script = "jarvis.plugins.harness.python_script:PythonScriptHarness"
diff --git a/tests/contract/test_brain_protocol.py b/tests/contract/test_brain_protocol.py
index 279aef0137..acff352f8a 100644
--- a/tests/contract/test_brain_protocol.py
+++ b/tests/contract/test_brain_protocol.py
@@ -17,11 +17,12 @@ import pytest
from jarvis.brain.provider_registry import BrainProviderRegistry
BRAIN_PROVIDERS = [
- "claude-api",
"claude-api",
"openrouter",
"openai",
"gemini",
+ # Keyless local provider, re-added 2026-07-25 (local-first mandate).
+ "ollama",
]
@@ -33,7 +34,7 @@ def registry():
def test_all_providers_loaded(registry):
available = set(registry.available())
missing = set(BRAIN_PROVIDERS) - available
- assert not missing, f"Fehlende Brain-Provider-Plugins: {missing}"
+ assert not missing, f"Missing brain provider plugins: {missing}"
@pytest.mark.parametrize("name", BRAIN_PROVIDERS)
diff --git a/tests/unit/brain/test_tier_defaults_parity.py b/tests/unit/brain/test_tier_defaults_parity.py
new file mode 100644
index 0000000000..e16b4ba105
--- /dev/null
+++ b/tests/unit/brain/test_tier_defaults_parity.py
@@ -0,0 +1,41 @@
+"""Parity gate: every switchable brain provider has tier-default rows.
+
+``TIER_DEFAULTS_BY_PROVIDER`` feeds the wizard, the provider test, the wiki
+curator, and the CU brain-call path. A switchable provider card without rows
+is invisible-to-broken in those surfaces, so the parity is pinned here —
+including the local providers whose empty string means "plugin-side model
+discovery" (first installed model), which is a valid default, not a gap.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from jarvis.brain.manager import TIER_DEFAULTS_BY_PROVIDER
+from jarvis.ui.web.provider_spec import PROVIDERS
+
+_SWITCHABLE_BRAIN_IDS = [
+ spec.id for spec in PROVIDERS if spec.tier == "brain" and spec.brain_switchable
+]
+
+
+def test_switchable_brain_providers_exist() -> None:
+ assert _SWITCHABLE_BRAIN_IDS, "provider_spec lists no switchable brain providers"
+
+
[email protected]("provider_id", _SWITCHABLE_BRAIN_IDS)
[email protected]("tier", ["router", "deep"])
+def test_every_switchable_brain_provider_has_tier_row(tier: str, provider_id: str) -> None:
+ assert provider_id in TIER_DEFAULTS_BY_PROVIDER[tier], (
+ f"provider {provider_id!r} is switchable in provider_spec but has no "
+ f"{tier!r} row in TIER_DEFAULTS_BY_PROVIDER — add one (empty string = "
+ "plugin-side discovery for local providers)"
+ )
+
+
+def test_local_providers_use_discovery_defaults() -> None:
+ """Local providers must NOT pin a hardcoded model — no server-side catalog
+ is knowable ahead of time; the plugin discovers the first installed one."""
+ for tier in ("router", "deep"):
+ for provider_id in ("ollama",):
+ assert TIER_DEFAULTS_BY_PROVIDER[tier].get(provider_id) == ""
diff --git a/tests/unit/core/test_worker_tier_alias_parity.py b/tests/unit/core/test_worker_tier_alias_parity.py
new file mode 100644
index 0000000000..c9e70437cf
--- /dev/null
+++ b/tests/unit/core/test_worker_tier_alias_parity.py
@@ -0,0 +1,165 @@
+"""[brain.worker] vs legacy [brain.sub_jarvis] — one worker tier, one winner.
+
+Both TOML tables populate the SAME Pydantic field (``BrainConfig.worker`` via
+``AliasChoices("worker", "sub_jarvis")``), so a file carrying both is a
+split-brain: which value won depended on alias ordering, and the live install
+shipped ``provider = "antigravity"`` in one table and ``provider =
+"openai-codex"`` in the other while the fallback chain rotted in the dead
+table. The loader now resolves the conflict explicitly ([brain.worker] wins,
+one WARNING names both values) and ``config_writer.migrate_worker_tier_table``
+heals the file at boot, rescuing legacy-only keys (the ``fallback_*`` chain)
+instead of dropping them.
+"""
+
+from __future__ import annotations
+
+import logging
+import os
+import tomllib
+from pathlib import Path
+
+import pytest
+
+import jarvis.core.config_writer as config_writer_module
+from jarvis.core.config import load_config
+from jarvis.core.config_writer import migrate_worker_tier_table
+
+_REPO_ROOT = Path(__file__).resolve().parents[3]
+
+_BOTH_TABLES = """
+[brain.worker]
+provider = "openai-codex"
+model = "gemini-3.1-pro-preview"
+
+[brain.sub_jarvis]
+provider = "antigravity"
+model = "claude-opus-4-8"
+fallback_provider = "gemini"
+fallback_model = "gemini-3.1-pro-preview"
+fallback_provider_2 = "gemini"
+fallback_model_2 = "gemini-3-pro-preview"
+"""
+
+
[email protected](autouse=True)
+def _isolated_jarvis_env(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Strip every JARVIS* env override so the host's registry-persisted
+ provider choices cannot leak into these loader tests (env > TOML)."""
+ for key in list(os.environ):
+ if key.startswith("JARVIS"):
+ monkeypatch.delenv(key, raising=False)
+
+
+def _write(tmp_path: Path, body: str) -> Path:
+ path = tmp_path / "jarvis.toml"
+ path.write_text(body, encoding="utf-8")
+ return path
+
+
+# ---------------------------------------------------------------- loader
+
+
+def test_only_worker_table_is_read(tmp_path: Path) -> None:
+ cfg = load_config(_write(tmp_path, '[brain.worker]\nprovider = "openai-codex"\n'))
+ assert cfg.brain.worker is not None
+ assert cfg.brain.worker.provider == "openai-codex"
+
+
+def test_only_legacy_table_still_reads(tmp_path: Path) -> None:
+ """Read-compat mandate: pre-rename installs with ONLY [brain.sub_jarvis]
+ keep booting (AliasChoices), with no warning noise."""
+ cfg = load_config(_write(tmp_path, '[brain.sub_jarvis]\nprovider = "gemini"\n'))
+ assert cfg.brain.worker is not None
+ assert cfg.brain.worker.provider == "gemini"
+
+
+def test_both_tables_worker_wins_and_warns(
+ tmp_path: Path, caplog: pytest.LogCaptureFixture
+) -> None:
+ with caplog.at_level(logging.WARNING, logger="jarvis.core.config"):
+ cfg = load_config(_write(tmp_path, _BOTH_TABLES))
+ assert cfg.brain.worker is not None
+ assert cfg.brain.worker.provider == "openai-codex"
+ joined = " ".join(record.getMessage() for record in caplog.records)
+ assert "openai-codex" in joined
+ assert "antigravity" in joined
+
+
+def test_env_override_beats_both_tables(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.setenv("JARVIS__BRAIN__WORKER__PROVIDER", "gemini")
+ cfg = load_config(_write(tmp_path, _BOTH_TABLES))
+ assert cfg.brain.worker is not None
+ assert cfg.brain.worker.provider == "gemini"
+
+
+# ------------------------------------------------------------- migration
+
+
+def test_migration_merges_legacy_keys_and_drops_table(tmp_path: Path) -> None:
+ path = _write(tmp_path, _BOTH_TABLES)
+ assert migrate_worker_tier_table(path=path) is True
+ data = tomllib.loads(path.read_text(encoding="utf-8"))
+ assert "sub_jarvis" not in data["brain"]
+ worker = data["brain"]["worker"]
+ # Canonical values kept, legacy-only keys (the fallback chain) rescued.
+ assert worker["provider"] == "openai-codex"
+ assert worker["model"] == "gemini-3.1-pro-preview"
+ assert worker["fallback_provider"] == "gemini"
+ assert worker["fallback_model"] == "gemini-3.1-pro-preview"
+ assert worker["fallback_provider_2"] == "gemini"
+ assert worker["fallback_model_2"] == "gemini-3-pro-preview"
+
+
+def test_migration_renames_when_only_legacy_exists(tmp_path: Path) -> None:
+ path = _write(
+ tmp_path,
+ '[brain.sub_jarvis]\nprovider = "gemini"\nfallback_provider = "openai"\n',
+ )
+ assert migrate_worker_tier_table(path=path) is True
+ data = tomllib.loads(path.read_text(encoding="utf-8"))
+ assert "sub_jarvis" not in data["brain"]
+ assert data["brain"]["worker"]["provider"] == "gemini"
+ assert data["brain"]["worker"]["fallback_provider"] == "openai"
+
+
+def test_migration_is_noop_without_legacy_table(tmp_path: Path) -> None:
+ path = _write(tmp_path, '[brain.worker]\nprovider = "openai-codex"\n')
+ before = path.read_text(encoding="utf-8")
+ assert migrate_worker_tier_table(path=path) is False
+ assert path.read_text(encoding="utf-8") == before
+
+
+def test_migration_missing_file_is_noop(tmp_path: Path) -> None:
+ assert migrate_worker_tier_table(path=tmp_path / "absent.toml") is False
+
+
+def test_migration_write_failure_is_logged_noop(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
+) -> None:
+ """A drift-guarded / read-only TOML must never break boot — the heal
+ degrades to a warning and reports "not migrated"."""
+ path = _write(tmp_path, _BOTH_TABLES)
+
+ def _denied(*_args: object, **_kwargs: object) -> None:
+ raise PermissionError("locked by drift guard")
+
+ monkeypatch.setattr(config_writer_module, "_atomic_write", _denied)
+ with caplog.at_level(logging.WARNING):
+ assert migrate_worker_tier_table(path=path) is False
+ assert "migration skipped" in " ".join(r.getMessage() for r in caplog.records)
+
+
+# ------------------------------------------------------------- repo lint
+
+
+def test_checked_in_example_config_has_no_split_brain() -> None:
+ """The shipped example config must never reintroduce both tables."""
+ example = _REPO_ROOT / "jarvis.toml.example"
+ data = tomllib.loads(example.read_text(encoding="utf-8"))
+ brain = data.get("brain", {})
+ assert not ("worker" in brain and "sub_jarvis" in brain), (
+ "jarvis.toml.example carries BOTH [brain.worker] and [brain.sub_jarvis] — "
+ "keep only the canonical [brain.worker] table"
+ )
diff --git a/tests/unit/plugins/brain/test_ollama.py b/tests/unit/plugins/brain/test_ollama.py
new file mode 100644
index 0000000000..b1863358c1
--- /dev/null
+++ b/tests/unit/plugins/brain/test_ollama.py
@@ -0,0 +1,220 @@
+"""Keyless local Ollama brain: endpoint normalization, discovery, honest errors.
+
+The provider must work with ZERO credentials (§3): the SDK client gets a
+dummy key, the server root comes from config override → OLLAMA_HOST → the
+localhost default, and every failure surfaces an honest, actionable English
+message instead of a fake model id that would 404.
+"""
+
+from __future__ import annotations
+
+import json
+from typing import Any
+
+import httpx
+import pytest
+
+import jarvis.core.config as cfg
+from jarvis.core.config import BrainConfig, BrainProviderConfig, JarvisConfig
+from jarvis.plugins.brain.ollama import (
+ DEFAULT_SERVER_ROOT,
+ RECOMMENDED_PULL,
+ OllamaBrain,
+ default_server_root,
+ normalize_server_root,
+)
+
+
+class _FakeOpenAI:
+ last_kwargs: dict[str, Any] = {}
+
+ def __init__(self, **kwargs: Any) -> None:
+ _FakeOpenAI.last_kwargs = kwargs
+
+
+def _no_override(monkeypatch) -> None:
+ monkeypatch.setattr(cfg, "load_config", lambda: JarvisConfig())
+ monkeypatch.delenv("OLLAMA_HOST", raising=False)
+
+
+def _override(url: str, monkeypatch) -> None:
+ conf = JarvisConfig(brain=BrainConfig(providers={"ollama": BrainProviderConfig(base_url=url)}))
+ monkeypatch.setattr(cfg, "load_config", lambda: conf)
+ monkeypatch.delenv("OLLAMA_HOST", raising=False)
+
+
+# ── Server-root normalization ────────────────────────────────────────────
+ ("raw", "expected"),
+ [
+ ("http://localhost:11434", "http://localhost:11434"),
+ ("http://localhost:11434/", "http://localhost:11434"),
+ # A pasted OpenAI-compat suffix must not double up to /v1/v1.
+ ("http://localhost:11434/v1", "http://localhost:11434"),
+ ("http://localhost:11434/api", "http://localhost:11434"),
+ # Bare host:port (the OLLAMA_HOST shape) gains a scheme.
+ ("127.0.0.1:11434", "http://127.0.0.1:11434"),
+ ("mybox:11434", "http://mybox:11434"),
+ # 0.0.0.0 is a server BIND address — as a client target it fails on
+ # Windows, so it maps to localhost.
+ ("0.0.0.0:11434", "http://localhost:11434"),
+ ("https://gpu.lan:11434/", "https://gpu.lan:11434"),
+ ("", DEFAULT_SERVER_ROOT),
+ (" ", DEFAULT_SERVER_ROOT),
+ ],
+)
+def test_normalize_server_root(raw: str, expected: str) -> None:
+ assert normalize_server_root(raw) == expected
+
+
+def test_default_server_root_honors_ollama_host(monkeypatch) -> None:
+ monkeypatch.setenv("OLLAMA_HOST", "0.0.0.0:12345")
+ assert default_server_root() == "http://localhost:12345"
+
+
+def test_default_server_root_without_env(monkeypatch) -> None:
+ monkeypatch.delenv("OLLAMA_HOST", raising=False)
+ assert default_server_root() == DEFAULT_SERVER_ROOT
+
+
+# ── Client construction (keyless) ────────────────────────────────────────
+def test_client_defaults_to_localhost_v1_with_dummy_key(monkeypatch) -> None:
+ import openai
+
+ monkeypatch.setattr(openai, "AsyncOpenAI", _FakeOpenAI)
+ _no_override(monkeypatch)
+ OllamaBrain()._ensure_client()
+ assert _FakeOpenAI.last_kwargs["base_url"] == "http://localhost:11434/v1"
+ # Keyless: the SDK insists on a non-empty key, Ollama ignores it.
+ assert _FakeOpenAI.last_kwargs["api_key"] == "ollama"
+
+
+def test_client_uses_config_override_root(monkeypatch) -> None:
+ import openai
+
+ monkeypatch.setattr(openai, "AsyncOpenAI", _FakeOpenAI)
+ _override("http://gpu.lan:11434", monkeypatch)
+ OllamaBrain()._ensure_client()
+ assert _FakeOpenAI.last_kwargs["base_url"] == "http://gpu.lan:11434/v1"
+
+
+def test_client_normalizes_pasted_v1_override(monkeypatch) -> None:
+ import openai
+
+ monkeypatch.setattr(openai, "AsyncOpenAI", _FakeOpenAI)
+ _override("http://gpu.lan:11434/v1/", monkeypatch)
+ OllamaBrain()._ensure_client()
+ assert _FakeOpenAI.last_kwargs["base_url"] == "http://gpu.lan:11434/v1"
+
+
+def test_client_timeout_fast_connect_wide_read(monkeypatch) -> None:
+ """A dead local server must fail fast so the chain crosses families,
+ while a slow CPU-bound generation may stream for minutes."""
+ import openai
+
+ monkeypatch.setattr(openai, "AsyncOpenAI", _FakeOpenAI)
+ _no_override(monkeypatch)
+ OllamaBrain()._ensure_client()
+ timeout = _FakeOpenAI.last_kwargs["timeout"]
+ assert timeout.connect <= 2.0
+ assert timeout.read >= 120.0
+
+
+# ── Model discovery via native /api/tags ─────────────────────────────────
+class _FakeResponse:
+ def __init__(self, payload: dict[str, Any]) -> None:
+ self._payload = payload
+
+ def raise_for_status(self) -> None:
+ return None
+
+ def json(self) -> dict[str, Any]:
+ return self._payload
+
+
+class _FakeAsyncClient:
+ payload: dict[str, Any] = {}
+ fail: bool = False
+ last_url: str | None = None
+
+ def __init__(self, **kwargs: Any) -> None:
+ pass
+
+ async def __aenter__(self) -> _FakeAsyncClient:
+ return self
+
+ async def __aexit__(self, *exc: Any) -> None:
+ return None
+
+ async def get(self, url: str) -> _FakeResponse:
+ _FakeAsyncClient.last_url = url
+ if _FakeAsyncClient.fail:
+ raise httpx.ConnectError("connection refused")
+ return _FakeResponse(_FakeAsyncClient.payload)
+
+
+def fake_tags(monkeypatch):
+ monkeypatch.setattr(httpx, "AsyncClient", _FakeAsyncClient)
+ _FakeAsyncClient.fail = False
+ _FakeAsyncClient.payload = {}
+ _FakeAsyncClient.last_url = None
+ return _FakeAsyncClient
+
+
+async def test_configured_model_skips_discovery(monkeypatch, fake_tags) -> None:
+ _no_override(monkeypatch)
+ brain = OllamaBrain(model="qwen3.5:9b")
+ assert await brain._resolve_model() == "qwen3.5:9b"
+ assert fake_tags.last_url is None # no HTTP call
+
+
+async def test_discovery_uses_first_installed_model(monkeypatch, fake_tags) -> None:
+ _no_override(monkeypatch)
+ fake_tags.payload = {"models": [{"name": "qwen3.5:9b"}, {"name": "gemma4:12b"}]}
+ brain = OllamaBrain()
+ assert await brain._resolve_model() == "qwen3.5:9b"
+ assert fake_tags.last_url == "http://localhost:11434/api/tags"
+ # Cached: a second resolve must not depend on the server again.
+ fake_tags.fail = True
+ assert await brain._resolve_model() == "qwen3.5:9b"
+
+
+async def test_empty_server_gives_honest_pull_hint(monkeypatch, fake_tags) -> None:
+ _no_override(monkeypatch)
+ fake_tags.payload = {"models": []}
+ with pytest.raises(RuntimeError) as err:
+ await OllamaBrain()._resolve_model()
+ assert f"ollama pull {RECOMMENDED_PULL}" in str(err.value)
+
+
+async def test_unreachable_server_gives_honest_error(monkeypatch, fake_tags) -> None:
+ _no_override(monkeypatch)
+ fake_tags.fail = True
+ with pytest.raises(RuntimeError) as err:
+ await OllamaBrain()._resolve_model()
+ msg = str(err.value)
+ assert "not reachable" in msg
+ assert "http://localhost:11434" in msg
+
+
+# ── Protocol surface ─────────────────────────────────────────────────────
+def test_capability_flags_and_cost() -> None:
+ brain = OllamaBrain(model="x")
+ assert brain.supports_tools is True
+ assert brain.can_call_tools() is True
+ assert brain.supports_vision is True
+ # Local inference bills nothing — the cost meter must see 0.
+ req_like = type("R", (), {"messages": (), "max_tokens": 100})()
+ assert brain.estimate_cost(req_like) == 0.0
+
+
+def test_tags_payload_shape_matches_documented_api() -> None:
+ """Pin the parsed shape: /api/tags returns {"models": [{"name": ...}]}.
+
+ If Ollama ever changes this, the discovery test data here must be updated
+ together with ``_resolve_model`` — this test documents the contract.
+ """
+ payload = json.loads('{"models": [{"name": "qwen3.5:9b", "size": 1}]}')
+ names = [m.get("name") for m in payload["models"]]
+ assert names == ["qwen3.5:9b"]