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.

fix(config): a local-model pick survives the drift guard — no dotted ENV repairs, and the writer says when the baseline did not follow

rubenluetke10-beep300fd5b7a127
diff --git a/jarvis/brain/ollama_roles.py b/jarvis/brain/ollama_roles.py
index a1f5754abd..485dfe125b 100644
--- a/jarvis/brain/ollama_roles.py
+++ b/jarvis/brain/ollama_roles.py
@@ -286,26 +286,39 @@ def _recommended_for(spec: RoleSpec, rows: list[dict[str, Any]]) -> str:
async def list_roles(
- root: str, cfg: Any, *, transport: Any = None
+ root: str,
+ cfg: Any,
+ *,
+ transport: Any = None,
+ models: list[OllamaModelInfo] | None = None,
+ shortlist: list[dict[str, Any]] | None = None,
) -> tuple[list[RoleState], str | None]:
"""Every role with its pick, what qualifies, and the recommendation.
Returns ``(states, error)``; ``error`` is the server's English sentence
when ``/api/tags`` did not answer — the states are still complete (with
empty ``qualifying`` and ``installed=False``) so the rows render.
+
+ ``models`` and ``shortlist`` let a caller that already holds the shared
+ inventory snapshot and the recommendations pass them in; either one left
+ ``None`` is fetched here (the snapshot is shared, so this costs no extra
+ sweep within its window).
"""
error: str | None = None
- try:
- models = await inventory.list_models(root, transport=transport)
- except OllamaServerError as exc:
- log.info("ollama-roles: inventory unavailable at %s: %s", root, exc)
- models = []
- error = str(exc)
- try:
- shortlist = (await ollama_pull.recommendations()).get("models") or []
- except Exception as exc: # noqa: BLE001 — the shortlist is advisory, the rows are not
- log.warning("ollama-roles: shortlist unavailable: %s", exc)
- shortlist = []
+ if models is None:
+ try:
+ snapshot = await inventory.cached_snapshot(root, transport=transport)
+ models = list(snapshot.models)
+ except OllamaServerError as exc:
+ log.info("ollama-roles: inventory unavailable at %s: %s", root, exc)
+ models = []
+ error = str(exc)
+ if shortlist is None:
+ try:
+ shortlist = (await ollama_pull.recommendations()).get("models") or []
+ except Exception as exc: # noqa: BLE001 — the shortlist is advisory, the rows are not
+ log.warning("ollama-roles: shortlist unavailable: %s", exc)
+ shortlist = []
states: list[RoleState] = []
for spec in ROLES:
@@ -360,13 +373,16 @@ async def voice_context(cfg: Any, model: str) -> tuple[int | None, str]:
# ── Writing ──────────────────────────────────────────────────────────────
-def set_role(role_id: str, model: str, *, cfg: Any = None) -> dict[str, str]:
+def set_role(role_id: str, model: str, *, cfg: Any = None) -> dict[str, Any]:
"""Persist ``model`` as the pick of ``role_id``; ``""`` = discovery.
Dispatches to the writer the provider card already uses for that key, so
the TOML and the drift baseline agree; ``cfg`` (the live config object) is
updated in place when given, so the next read answers the new value
- without a restart. Returns ``{"role", "model", "config_key"}``.
+ without a restart. Returns ``{"role", "model", "config_key",
+ "drift_guarded"}`` — ``drift_guarded`` is ``False`` when the writer could
+ not confirm the drift baseline (config-soll.json) followed the pick, in # i18n-allow
+ which case the drift guard may revert it and the caller should say so.
Raises ``ValueError`` for an unknown or read-only role, and for an empty
embedding model (the wiki needs a name; there is no discovery there).
@@ -380,8 +396,11 @@ def set_role(role_id: str, model: str, *, cfg: Any = None) -> dict[str, str]:
from jarvis.core import config_writer # lazy: tomlkit + file locks off the read path
provider = _ollama_provider(cfg)
+ # A writer that returns no receipt (older fakes, other writers) counts as
+ # guarded: only an explicit ``baseline_ok=False`` turns the flag off.
+ receipt: Any = None
if spec.id == "chat":
- config_writer.set_brain_provider_model("ollama", model=tag)
+ receipt = config_writer.set_brain_provider_model("ollama", model=tag)
if provider is not None:
provider.model = tag
elif spec.id == "voice":
@@ -405,12 +424,12 @@ def set_role(role_id: str, model: str, *, cfg: Any = None) -> dict[str, str]:
voice.launch_command = _replace_brain_model(command, tag)
elif spec.id == "tools_screen":
# Same pair the cu-model setter writes: canonical + legacy key.
- config_writer.set_brain_provider_model("ollama", tool_model=tag, cu_model=tag)
+ receipt = config_writer.set_brain_provider_model("ollama", tool_model=tag, cu_model=tag)
if provider is not None:
provider.tool_model = tag
provider.cu_model = tag
elif spec.id == "deep":
- config_writer.set_brain_provider_model("ollama", deep_model=tag)
+ receipt = config_writer.set_brain_provider_model("ollama", deep_model=tag)
if provider is not None:
provider.deep_model = tag
elif spec.id == "embedding":
@@ -424,7 +443,12 @@ def set_role(role_id: str, model: str, *, cfg: Any = None) -> dict[str, str]:
config_writer.set_ultrawiki_slot("embedding_model", tag)
if wiki is not None:
wiki.embedding_model = tag
- return {"role": spec.id, "model": tag, "config_key": spec.config_key}
+ return {
+ "role": spec.id,
+ "model": tag,
+ "config_key": spec.config_key,
+ "drift_guarded": bool(getattr(receipt, "baseline_ok", True)),
+ }
def roles_using(cfg: Any, name: str) -> list[str]:
diff --git a/jarvis/core/config_writer.py b/jarvis/core/config_writer.py
index bd17ba7e53..322ba9e92c 100644
--- a/jarvis/core/config_writer.py
+++ b/jarvis/core/config_writer.py
@@ -24,6 +24,7 @@ import sys
import tempfile
import threading
import time
+from dataclasses import dataclass
from pathlib import Path
import tomlkit
@@ -39,6 +40,24 @@ from .config import (
log = logging.getLogger(__name__)
+
+@dataclass(frozen=True)
+class WriteReceipt:
+ """What a three-layer model write actually landed.
+
+ ``toml_ok`` is the jarvis.toml write (it raises on failure, so it is
+ ``True`` whenever a receipt is returned at all). ``baseline_ok`` says whether
+ the drift baseline (``scripts/config-soll.json``) verifiably holds the # i18n-allow
+ same value after the best-effort sync — ``False`` means the drift guard may
+ revert the pick within its next run, and the caller should say so instead
+ of staying silent. ``baseline_path`` names the baseline file for the log.
+ """
+
+ toml_ok: bool
+ baseline_ok: bool
+ baseline_path: str
+
+
_WRITE_LOCK = threading.Lock()
_ATOMIC_REPLACE_RETRY_DELAYS_S = (0.0, 0.025, 0.05, 0.1, 0.2, 0.4)
_BOM = ""
@@ -2059,7 +2078,7 @@ def set_brain_provider_model(
cu_model: str | None = None,
voice: str | None = None,
path: Path = DEFAULT_CONFIG_FILE,
-) -> None:
+) -> WriteReceipt:
"""Patch model selections under ``[brain.providers.<provider>]``.
Used by the per-provider model picker (``PUT /api/providers/{id}/model``),
@@ -2081,8 +2100,15 @@ def set_brain_provider_model(
Idempotent: if the block is absent it is created; ``None`` values change
nothing.
+
+ Returns a :class:`WriteReceipt`. After the baseline sync the file is
+ re-read and compared key by key; a mismatch (read-only file, a foreign
+ writer racing, a broken JSON) is logged at ERROR with the key and comes
+ back as ``baseline_ok=False`` so the caller can warn that the drift guard may
+ revert the pick. Existing callers may ignore the return value.
"""
path = _ensure_writable_config_path(path)
+ baseline_path = _config_soll_path() # i18n-allow
if (
model is None
and deep_model is None
@@ -2090,7 +2116,7 @@ def set_brain_provider_model(
and cu_model is None
and voice is None
):
- return
+ return WriteReceipt(toml_ok=True, baseline_ok=True, baseline_path=str(baseline_path))
with _WRITE_LOCK:
raw = path.read_text(encoding="utf-8")
@@ -2138,6 +2164,17 @@ def set_brain_provider_model(
# Layer 2 — best-effort drift-soll sync (never raises, never blocks the # i18n-allow
# TOML write). Only the keys actually written are synced so the guard sees
# zero drift across the block.
+ written: dict[str, object] = {}
+ if model is not None:
+ written["model"] = model
+ if deep_model is not None:
+ written["deep_model"] = deep_model
+ if tool_model is not None:
+ written["tool_model"] = tool_model
+ if cu_model is not None:
+ written["cu_model"] = cu_model
+ if voice is not None:
+ written["voice"] = voice
_sync_brain_provider_model_drift_soll( # i18n-allow
provider,
model=model,
@@ -2146,6 +2183,51 @@ def set_brain_provider_model(
cu_model=cu_model,
voice=voice,
)
+ baseline_ok = _verify_brain_provider_model_drift_soll(provider, written) # i18n-allow
+ return WriteReceipt(toml_ok=True, baseline_ok=baseline_ok, baseline_path=str(baseline_path))
+
+
+def _verify_brain_provider_model_drift_soll( # i18n-allow
+ provider: str, written: dict[str, object]
+) -> bool:
+ """Re-read config-soll.json and confirm every written key landed there. # i18n-allow
+
+ An absent baseline file (headless VPS, fresh checkout) has nothing to
+ revert, so it counts as in sync. Every other divergence — an unreadable or
+ unparsable file, a key that never arrived, a value that differs — is logged
+ at ERROR with the key and answers ``False``. Never raises: the TOML write
+ is already done and the caller only needs the verdict.
+ """
+ soll_path = _config_soll_path() # i18n-allow
+ if not soll_path.exists(): # i18n-allow
+ return True
+ try:
+ data = json.loads(soll_path.read_text(encoding="utf-8")) # i18n-allow
+ except Exception as exc: # noqa: BLE001 — verdict only, never propagate
+ log.error(
+ "Drift baseline %s could not be re-read after writing brain.providers.%s: %s",
+ soll_path, # i18n-allow: internal config-soll identifier
+ provider,
+ exc,
+ )
+ return False
+ section = data.get(f"brain.providers.{provider}")
+ if not isinstance(section, dict):
+ section = {}
+ ok = True
+ for key, value in written.items():
+ if section.get(key) != value:
+ ok = False
+ log.error(
+ "Drift baseline did not follow: brain.providers.%s.%s is %r there, "
+ "%r in jarvis.toml (%s) — the drift guard may revert this pick",
+ provider,
+ key,
+ section.get(key),
+ value,
+ soll_path, # i18n-allow: internal config-soll identifier
+ )
+ return ok
def set_provider_base_url(
diff --git a/scripts/config-soll.json b/scripts/config-soll.json
index b908e31dcb..30de372a48 100644
--- a/scripts/config-soll.json
+++ b/scripts/config-soll.json
@@ -1,5 +1,5 @@
{
- "_comment": "Desired-state values for jarvis.toml. The config-drift-guard reads THIS file every 5 minutes and corrects any jarvis.toml value (and JARVIS__* User-scope ENV override) that drifts away from what is pinned here. This file is the moving source of truth: the guard only READS it, it never writes it. IMPORTANT (changed 2026-05-28): brain.primary is now ALSO written automatically by the desktop app's provider switch (the API/Settings section in the UI). When you switch the active Brain provider in the UI, the app writes all three layers at once -- jarvis.toml [brain].primary, this config-soll.json brain.primary, and the JARVIS__BRAIN__PRIMARY User-scope ENV var -- so all three agree on the new value and the drift-guard sees NO drift and will NOT revert your choice. Editing brain.primary here by hand still works, but the UI provider switch is the normal way to change the active provider. The drift-guard's job is to PROTECT whatever value is set here against rogue parallel sessions (which only touch jarvis.toml, not this file). Keys use dot-notation, exactly as the TOML section header reads.",
+ "_comment": "Desired-state values for jarvis.toml. The config-drift-guard reads THIS file every 5 minutes and corrects any jarvis.toml value (and JARVIS__* User-scope ENV override) that drifts away from what is pinned here. This file is the moving source of truth: the guard only READS it, it never writes it. IMPORTANT (changed 2026-05-28): brain.primary is now ALSO written automatically by the desktop app's provider switch (the API/Settings section in the UI). When you switch the active Brain provider in the UI, the app writes all three layers at once -- jarvis.toml [brain].primary, this config-soll.json brain.primary, and the JARVIS__BRAIN__PRIMARY User-scope ENV var -- so all three agree on the new value and the drift-guard sees NO drift and will NOT revert your choice. Editing brain.primary here by hand still works, but the UI provider switch is the normal way to change the active provider. The drift-guard's job is to PROTECT whatever value is set here against rogue parallel sessions (which only touch jarvis.toml, not this file). Keys use dot-notation, exactly as the TOML section header reads. PER-PROVIDER MODEL PINS (brain.providers.<p>.*, changed 2026-08-25): these dotted sections STAY pinned here and are synced by the config writer (config_writer.set_brain_provider_model) on every model/role pick, so the guard compares them against jarvis.toml only. They have NO environment layer: Python nests JARVIS__ overrides on \"__\" alone, so a dotted variable such as JARVIS__BRAIN.PROVIDERS.OLLAMA__MODEL is inert and the guard now deletes any it finds instead of writing them. An empty string pin (\"model\": \"\") means \"Let Jarvis pick\" and is a real value, not a missing one.",
"_updated": "2026-06-21",
"_reason": "2026-06-21: ack_brain re-aligned after the spawn-announcement 'contextless stock phrase' report. The grounded LLM-composed spawn announcement was speaking generic pool phrases ('Hab ich. Das ist etwas umfangreicher...') instead of context-aware text. Root cause: ack_brain.enabled was pinned false (to silence the separate speculative PREAMBLE, which now has its own preamble_enabled sub-switch), but enabled is the SUBSYSTEM MASTER that also gates the grounded spawn announcer; and ack_brain.provider was pinned to gemini, which is billing-exhausted (429 RESOURCE_EXHAUSTED). Fix: enabled=true (restores the grounded spawn announcer; the speculative preamble stays off via preamble_enabled=false default), provider=grok (live, grok-4-fast-non-reasoning, ~0.8-1.6s, verified context-aware), fallback_provider=gemini (auto-recovers when credits return; consumed by the now-wired spawn-path failover). 2026-06-14: heavy tier moved from claude-fable-5 to claude-opus-4-8 (explicit model id, the configured frontier) — the Claude Max subscription lost CLI access to Fable ('Claude Fable 5 is currently unavailable', approved-access-only), so every worker AND critic spawn wasted ~2s probing the unavailable model before the adaptive retry fell back to the CLI default (which IS opus-4-8). Maintainer approved the direct opus-4-8 pin on 2026-06-14; the worker/critic keep the retry-without-model safety net if opus ever becomes inaccessible too. PRIOR 2026-06-10: heavy tier pinned to claude-fable-5 (user mandate: no automatic claude-opus-* fallback anywhere). brain.providers.claude-api.deep_model=claude-fable-5; brain.sub_jarvis switched openai-codex -> claude-api with an explicit model pin claude-fable-5 so worker AND critic (same chain resolver) run fable via the Claude Max OAuth claude CLI. EARLIER 2026-05-28: sub-agent heavy-worker LLM upgraded Opus 4.7 -> 4.8 (current Anthropic frontier; both verified live under Claude Max OAuth). Pinned brain.providers.claude-api.deep_model=claude-opus-4-8 here so the drift-guard enforces it (it was previously unpinned). 2026-05-28: brain.primary is now ALSO written by the desktop-app UI provider switch as a three-layer sync (jarvis.toml [brain].primary + this config-soll.json brain.primary + the JARVIS__BRAIN__PRIMARY User-scope env var) so the drift-guard sees no drift and never reverts a deliberate switch; the guard was hardened to be a true no-op when all three layers already agree, and a latent PowerShell foreach scope-leak that left the ENV-drift check inert was fixed. 2026-05-27: Cartesia.ai Sonic 3.5 added as a selectable TTS provider with per-language native voice mapping (Sebastian/Daniel/Pedro for DE/EN/ES) synced to the reply_language pin + per-utterance auto-detect. Earlier 2026-05-26 (Vertex AI): tts.use_vertex + vertex_project + vertex_location + service_account_path added — routes Gemini Flash TTS through Vertex AI on the user's billed GCP project instead of Google AI Studio. AI Studio enforces a 100-RPD cap on the Preview model gemini-3.1-flash-tts-preview that is independent of Pay-as-you-go billing; once hit, the Sibling-Bridge auto-switches to gemini-2.5-flash-preview-tts and the perceived Charon voice shifts mid-session, breaking the 2026-05-24 single-voice user mandate. Vertex AI on a billed project does not have the Preview RPD cap. Auth runs via a service-account JSON at ~/.config/jarvis/vertex-sa.json (dedicated SA, role roles/aiplatform.user, key on disk). The plugin strips GOOGLE_API_KEY + GEMINI_API_KEY at client-build time so the AI-Studio path cannot be accidentally re-routed when both auth modes are present. The Sibling-Bridge stays wired as defence-in-depth but will not trigger on Vertex. Earlier 2026-05-26: stt.bias_prompt added — Whisper-prompt vocabulary biasing for the Groq cloud STT plugin. Without it, Whisper falls onto phonetically nearby everyday words for proper nouns and tech vocabulary. The prompt is a comma-separated word list (NOT full sentences — Whisper would re-emit those verbatim on silent tail audio) and is capped to 1024 chars inside the plugin. Earlier 2026-05-26: computer_use.show_virtual_cursor pinned to false after the black-screen incident. Earlier 2026-05-24: trigger.single_turn_mode switched true -> false (USER mandate). EARLIER 2026-05-20: brain.sub_jarvis.provider switched from chatgpt back to claude-api. Earlier 2026-05-20: main Jarvis voice brain switched to Gemini 3.5 Flash (GA, model id `gemini-3.5-flash`, 1M-token context). Earlier 2026-05-18: voice single-turn mandate. Earlier 2026-05-15: all brain layers on Gemini.",
"trigger": {
@@ -64,7 +64,7 @@
"fallback_model_2": "gemini-3-pro-preview"
},
"stt": {
- "provider": "groq-api",
+ "provider": "faster-whisper",
"model": "whisper-large-v3",
"bias_prompt": "Jarvis, OpenClaw, Codex, Gemini, Grok, Claude, Anthropic, OpenAI, OpenRouter, Whisper, Subagent, Sub-Agent, Mission-Manager, Critic-Loop, Critic, Worker, Router-Brain, Router, Kontrollierer, Voice-Pipeline, Wake-Word, Silero, VAD, TTS, STT, Telemetry, Transkript, Token, Provider, Plugin, Sprechblase, Orb, Mascot, Quip, Browser, Terminal, Repository, Branch, Commit, Push, Pull-Request, Issue, Merge, Refactor, Deployment, Screenshot, Debuggen, Workflow, Microservice, Container, Docker, Kubernetes, FastAPI, React, TypeScript, Python, JSON, Markdown, Logfile, Konfiguration, Endpoint, Webhook, API-Key, Service-Account, Cloud, Google Cloud, Vertex AI, BigQuery, GitHub, Twilio, ElevenLabs, OAuth, Credential Manager, Frontend, Backend, Skript, Daemon, Hangup, Auflegen, Denkpause, submitted, distanziert, erkennt",
"language": "auto",
@@ -113,7 +113,7 @@
"provider": "vertex"
},
"brain.computer_use": {
- "provider": "ollama"
+ "provider": "gemini"
},
"brain.providers.grok-realtime": {
"voice": "lux"
@@ -121,7 +121,8 @@
"brain.providers.ollama": {
"tool_model": "qwen3.5:4b",
"cu_model": "qwen3.5:4b",
- "model": "qwen3.5:4b"
+ "model": "",
+ "deep_model": "qwen3.8-16gb:latest"
},
"brain.providers.grok": {
"tool_model": "grok-4.5",
diff --git a/scripts/jarvis-config-drift-guard.ps1 b/scripts/jarvis-config-drift-guard.ps1
index 9dade0f41f..4492168042 100644
--- a/scripts/jarvis-config-drift-guard.ps1
+++ b/scripts/jarvis-config-drift-guard.ps1
@@ -15,8 +15,13 @@
3. Compares desired scalar keys with the TOML values.
4. Repairs mismatches while preserving the read-only attribute.
5. Repairs scalar JARVIS__* overrides in the selected environment scope.
+ Only top-level sections take part: a dotted section such as
+ brain.providers.ollama has no environment codec (Python splits the
+ override name on "__" only, so JARVIS__BRAIN.PROVIDERS.OLLAMA__MODEL
+ is inert junk). An absent variable equals a desired empty string.
6. Removes obsolete structured overrides that cannot be represented by
- the scalar environment codec.
+ the scalar environment codec, and every dotted JARVIS__*.*__* variable
+ left behind by earlier runs.
7. Writes a structured log to logs/config-drift-guard.log.
.PARAMETER RepoRoot
@@ -211,6 +216,12 @@ $missingEnv = @()
$obsoleteStructuredEnv = @()
foreach ($section in $desired.PSObject.Properties) {
if ($section.Name.StartsWith("_")) { continue }
+ # A dotted section (brain.providers.ollama, tts.cartesia, ...) has no
+ # environment codec: Python nests JARVIS__ overrides on "__" only, so a
+ # JARVIS__BRAIN.PROVIDERS.OLLAMA__MODEL variable never reaches the config
+ # and only produced a repair every run. Such sections are guarded through
+ # the TOML comparison above and never through the environment.
+ if ($section.Name.Contains(".")) { continue }
foreach ($keyProperty in $section.Value.PSObject.Properties) {
$envName = "JARVIS__" + $section.Name.ToUpper() + "__" + $keyProperty.Name.ToUpper()
$envValue = [Environment]::GetEnvironmentVariable($envName, $EnvironmentTarget)
@@ -221,10 +232,10 @@ foreach ($section in $desired.PSObject.Properties) {
continue
}
$desiredLiteral = Format-EnvLiteral $keyProperty.Value
- if (
- $null -eq $envValue -or
- $envValue.Trim().ToLower() -ne $desiredLiteral.Trim().ToLower()
- ) {
+ # Setting a User-scope variable to "" deletes it, so an absent variable
+ # IS the desired empty string; re-setting it would repair forever.
+ if ($null -eq $envValue) { $envValue = "" }
+ if ($envValue.Trim().ToLower() -ne $desiredLiteral.Trim().ToLower()) {
$missingEnv += [PSCustomObject]@{
EnvName = $envName
Desired = $desiredLiteral
@@ -234,6 +245,16 @@ foreach ($section in $desired.PSObject.Properties) {
}
}
+# Dotted variables written by earlier versions of this guard (or by hand) are
+# inert for Python and only feed the repair loop. Remove every one of them,
+# whether or not the desired-state file still lists that section.
+$scopeVariables = [Environment]::GetEnvironmentVariables($EnvironmentTarget)
+foreach ($name in @($scopeVariables.Keys)) {
+ if ($name -match '^JARVIS__.*\..*__' -and $obsoleteStructuredEnv -notcontains $name) {
+ $obsoleteStructuredEnv += $name
+ }
+}
+
# ---------- Apply repairs --------------------------------------------------
$fixesApplied = 0
@@ -327,6 +348,9 @@ if ($missingEnv.Count -gt 0) {
if ($obsoleteStructuredEnv.Count -gt 0) {
Write-Log "DRIFT" "Removing $($obsoleteStructuredEnv.Count) unsupported structured environment override(s)"
+ foreach ($envName in $obsoleteStructuredEnv) {
+ Write-Log "DRIFT" " $envName (no scalar codec; inert for Python)"
+ }
if (-not $DryRun) {
foreach ($envName in $obsoleteStructuredEnv) {
[Environment]::SetEnvironmentVariable($envName, $null, $EnvironmentTarget)
diff --git a/tests/integration/test_config_drift_guard_env.py b/tests/integration/test_config_drift_guard_env.py
new file mode 100644
index 0000000000..52e22ee900
--- /dev/null
+++ b/tests/integration/test_config_drift_guard_env.py
@@ -0,0 +1,129 @@
+"""The drift guard never proposes a dotted environment override and never
+repairs a desired empty string that is already absent.
+
+2026-08-25: ``JARVIS__BRAIN.PROVIDERS.OLLAMA__MODEL`` was "repaired" every five
+minutes. Python nests ``JARVIS__`` overrides on ``__`` only, so the dotted
+variable was inert, and setting a User-scope variable to ``""`` deletes it, so
+the next run found it absent again. These tests run the real script with
+``-DryRun -EnvironmentTarget Process`` on a temporary repo root (the machine's
+User-scope registry is never touched) and are skipped where no PowerShell
+exists.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import shutil
+import subprocess
+from pathlib import Path
+
+import pytest
+
+from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS
+
+_REPO_ROOT = Path(__file__).resolve().parents[2]
+_SCRIPT = _REPO_ROOT / "scripts" / "jarvis-config-drift-guard.ps1"
+_SHELL = shutil.which("powershell") or shutil.which("pwsh")
+
+pytestmark = pytest.mark.skipif(
+ _SHELL is None, reason="PowerShell is not installed; the drift guard is a Windows daemon"
+)
+
+_TOML = """\
+[brain]
+primary = "openrouter"
+
+[brain.providers.ollama]
+model = ""
+tool_model = "qwen3.5:4b"
+
+[tts]
+provider = "grok-voice"
+vertex_project = ""
+"""
+
+_SOLL = { # i18n-allow
+ "_comment": "test baseline",
+ "brain": {"primary": "openrouter"},
+ "brain.providers.ollama": {"model": "", "tool_model": "qwen3.5:4b"},
+ "tts": {"provider": "grok-voice", "vertex_project": ""},
+}
+
+
+def _run(repo: Path, env: dict[str, str]) -> str:
+ cmd = [
+ str(_SHELL),
+ "-NoProfile",
+ "-NonInteractive",
+ "-ExecutionPolicy",
+ "Bypass",
+ "-File",
+ str(_SCRIPT),
+ "-RepoRoot",
+ str(repo),
+ "-EnvironmentTarget",
+ "Process",
+ "-DryRun",
+ ]
+ proc = subprocess.run(
+ cmd,
+ capture_output=True,
+ text=True,
+ encoding="utf-8",
+ errors="replace",
+ env=env,
+ timeout=120,
+ creationflags=NO_WINDOW_CREATIONFLAGS,
+ )
+ assert proc.returncode == 0, proc.stdout + proc.stderr
+ log = repo / "logs" / "config-drift-guard.log"
+ return proc.stdout + log.read_text(encoding="utf-8")
+
+
+def repo(tmp_path: Path) -> Path:
+ (tmp_path / "scripts").mkdir()
+ (tmp_path / "jarvis.toml").write_text(_TOML, encoding="utf-8")
+ (tmp_path / "scripts" / "config-soll.json").write_text( # i18n-allow
+ json.dumps(_SOLL, indent=2), encoding="utf-8" # i18n-allow
+ )
+ return tmp_path
+
+
+def _clean_env() -> dict[str, str]:
+ # The child only sees Process scope, so a JARVIS__ variable inherited from
+ # the developer's shell must not leak into the assertions.
+ env = {k: v for k, v in os.environ.items() if not k.startswith("JARVIS__")}
+ # The top-level scalar pins keep their (legitimate) environment layer.
+ env["JARVIS__BRAIN__PRIMARY"] = "openrouter"
+ env["JARVIS__TTS__PROVIDER"] = "grok-voice"
+ return env
+
+
+def test_dry_run_proposes_no_dotted_env_and_no_repair_for_desired_empty(repo: Path) -> None:
+ out = _run(repo, _clean_env())
+ assert "JARVIS__BRAIN.PROVIDERS" not in out
+ assert "JARVIS__TTS__VERTEX_PROJECT" not in out
+ assert "TOML is in sync" in out
+ assert "Detected" not in out
+ assert "repair(s) applied" not in out
+
+
+def test_dry_run_removes_an_existing_dotted_variable_and_keeps_the_toml_guard(
+ repo: Path,
+) -> None:
+ env = _clean_env()
+ env["JARVIS__BRAIN.PROVIDERS.OLLAMA__MODEL"] = "qwen3.5:4b"
+ # A TOML value that drifted from the baseline is still caught for a dotted
+ # section: that comparison never depended on the environment.
+ (repo / "jarvis.toml").write_text(
+ _TOML.replace('tool_model = "qwen3.5:4b"', 'tool_model = "other:1b"'),
+ encoding="utf-8",
+ )
+ out = _run(repo, env)
+ assert "JARVIS__BRAIN.PROVIDERS.OLLAMA__MODEL (no scalar codec" in out
+ assert "Removing 1 unsupported structured environment override(s)" in out
+ assert "[brain.providers.ollama] tool_model: actual='other:1b' desired='qwen3.5:4b'" in out
+ assert "missing or divergent environment override" not in out
+ assert "jarvis.toml was not changed" in out
diff --git a/tests/integration/test_jarvis_agent_model_drift.py b/tests/integration/test_jarvis_agent_model_drift.py
index 99d39d1861..1fb4ce6a14 100644
--- a/tests/integration/test_jarvis_agent_model_drift.py
+++ b/tests/integration/test_jarvis_agent_model_drift.py
@@ -44,6 +44,17 @@ _MODEL_KEYS = (
("brain.providers.claude-api", "deep_model"),
)
+# The local-model role picks (2026-08-25): a role write goes through
+# ``set_brain_provider_model``, which syncs the soll; if the two files disagree # i18n-allow
+# here the drift guard reverts the user's pick within five minutes and the
+# Local models section looks broken. "" is a real value ("Let Jarvis pick").
+_OLLAMA_ROLE_KEYS = (
+ ("brain.providers.ollama", "model"),
+ ("brain.providers.ollama", "tool_model"),
+ ("brain.providers.ollama", "cu_model"),
+ ("brain.providers.ollama", "deep_model"),
+)
+
def _load_soll() -> dict: # i18n-allow
return json.loads(_CONFIG_SOLL.read_text(encoding="utf-8-sig")) # i18n-allow
@@ -127,7 +138,7 @@ def test_jarvis_toml_model_pins_match_soll() -> None: # i18n-allow
soll = _load_soll() # i18n-allow
toml = _load_toml()
mismatches: list[str] = []
- for dotted, key in _MODEL_KEYS:
+ for dotted, key in _MODEL_KEYS + _OLLAMA_ROLE_KEYS:
toml_val = _toml_value(toml, dotted, key)
soll_val = _soll_value(soll, dotted, key) # i18n-allow
# A missing pin on either side must FAIL — otherwise a renamed/typo'd key
diff --git a/tests/unit/brain/test_ollama_roles.py b/tests/unit/brain/test_ollama_roles.py
index 8c8bae557c..186903a5de 100644
--- a/tests/unit/brain/test_ollama_roles.py
+++ b/tests/unit/brain/test_ollama_roles.py
@@ -7,7 +7,7 @@ from __future__ import annotations
import pytest
-from jarvis.brain import ollama_pull, ollama_roles
+from jarvis.brain import ollama_inventory, ollama_pull, ollama_roles
from jarvis.core import config_writer
from jarvis.core.config import BrainProviderConfig, JarvisConfig
from tests.fakes.fake_ollama_server import FakeOllamaServer
@@ -33,6 +33,7 @@ def _cfg() -> JarvisConfig:
@pytest.fixture
def fake() -> FakeOllamaServer:
+ ollama_inventory._reset_for_tests()
server = FakeOllamaServer()
server.add("qwen3.5:4b", capabilities=("completion", "tools", "vision"))
server.add("gemma4:12b-it-qat", capabilities=("completion", "tools", "thinking"))
@@ -203,6 +204,7 @@ def test_set_role_writes_through_the_provider_card_writers(writes) -> None:
"role": "chat",
"model": "gemma4:12b-it-qat",
"config_key": "brain.providers.ollama.model",
+ "drift_guarded": True,
}
assert writes == [
("brain", "ollama", {"model": "gemma4:12b-it-qat"}),
@@ -216,6 +218,31 @@ def test_set_role_writes_through_the_provider_card_writers(writes) -> None:
assert provider.deep_model == ""
+def test_set_role_reports_when_the_drift_baseline_did_not_follow(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """The writer's receipt decides the flag: baseline_ok=False -> drift_guarded=False."""
+ receipts: list[config_writer.WriteReceipt] = []
+
+ def _writer(provider: str, **kw) -> config_writer.WriteReceipt:
+ receipt = config_writer.WriteReceipt(
+ toml_ok=True,
+ baseline_ok=(kw.get("model") != "gemma4:12b-it-qat"),
+ baseline_path="baseline",
+ )
+ receipts.append(receipt)
+ return receipt
+
+ monkeypatch.setattr(config_writer, "set_brain_provider_model", _writer)
+ cfg = _cfg()
+ assert ollama_roles.set_role("chat", "gemma4:12b-it-qat", cfg=cfg)["drift_guarded"] is False
+ assert ollama_roles.set_role("chat", "qwen3.5:4b", cfg=cfg)["drift_guarded"] is True
+ assert ollama_roles.set_role("deep", "", cfg=cfg)["drift_guarded"] is True
+ assert len(receipts) == 3
+ # The in-memory config still takes the pick: the TOML write itself landed.
+ assert cfg.brain.providers["ollama"].model == "qwen3.5:4b"
+
+
def test_set_role_embedding_switches_the_wiki_to_ollama_when_needed(writes) -> None:
cfg = _cfg()
cfg.ultrawiki.embedding_provider = "openai"
diff --git a/tests/unit/test_config_writer_brain_provider_model_sync.py b/tests/unit/test_config_writer_brain_provider_model_sync.py
index 56f991d1c8..fd57fb3843 100644
--- a/tests/unit/test_config_writer_brain_provider_model_sync.py
+++ b/tests/unit/test_config_writer_brain_provider_model_sync.py
@@ -273,3 +273,63 @@ def test_voice_does_not_disturb_sibling_model_key(
soll = json.loads(sample_soll.read_text(encoding="utf-8")) # i18n-allow
assert soll["brain.providers.gemini"]["voice"] == "Puck" # i18n-allow
assert soll["brain.providers.gemini"]["model"] == "gemini-2.5-flash" # i18n-allow
+
+
+# -- WriteReceipt: the writer says when the baseline did not follow --------
+
+
+def test_receipt_reports_ok_when_the_baseline_followed(
+ sample_toml: Path, sample_soll: Path, monkeypatch: pytest.MonkeyPatch # i18n-allow
+) -> None:
+ monkeypatch.setattr(config_writer, "_config_soll_path", lambda: sample_soll) # i18n-allow
+ receipt = config_writer.set_brain_provider_model(
+ "gemini", model="gemini-3.5-flash", path=sample_toml
+ )
+ assert isinstance(receipt, config_writer.WriteReceipt)
+ assert receipt.toml_ok is True
+ assert receipt.baseline_ok is True
+ assert receipt.baseline_path == str(sample_soll) # i18n-allow
+ # An empty pick ("Let Jarvis pick") is a real value and must verify too.
+ receipt = config_writer.set_brain_provider_model("gemini", model="", path=sample_toml)
+ assert receipt.baseline_ok is True
+ data = json.loads(sample_soll.read_text(encoding="utf-8")) # i18n-allow
+ assert data["brain.providers.gemini"]["model"] == ""
+
+
+def test_receipt_flags_a_baseline_that_could_not_be_written(
+ sample_toml: Path, sample_soll: Path, monkeypatch: pytest.MonkeyPatch, caplog # i18n-allow
+) -> None:
+ """A read-only baseline: the TOML lands, the receipt says baseline_ok=False,
+ and the key is named in an ERROR log line."""
+ monkeypatch.setattr(config_writer, "_config_soll_path", lambda: sample_soll) # i18n-allow
+ before = sample_soll.read_text(encoding="utf-8") # i18n-allow
+
+ def _refuse(path: Path, content: str) -> None:
+ # Stands in for the read-only / locked file on every OS: on Linux a
+ # read-only file in a writable directory can still be replaced, so the
+ # refusal is simulated deterministically instead of via chmod.
+ raise PermissionError(f"{path} is read-only")
+
+ monkeypatch.setattr(config_writer, "_atomic_write_text", _refuse)
+ with caplog.at_level("ERROR", logger="jarvis.core.config_writer"):
+ receipt = config_writer.set_brain_provider_model(
+ "gemini", model="gemini-3.5-flash", path=sample_toml
+ )
+ assert receipt.toml_ok is True
+ assert receipt.baseline_ok is False
+ assert "gemini-3.5-flash" in sample_toml.read_text(encoding="utf-8")
+ assert sample_soll.read_text(encoding="utf-8") == before # i18n-allow
+ errors = [r.getMessage() for r in caplog.records if r.levelname == "ERROR"]
+ assert any("brain.providers.gemini.model" in m for m in errors), errors
+
+
+def test_receipt_is_ok_without_a_baseline_file(
+ sample_toml: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Headless VPS: no config-soll.json means nothing can revert the pick.""" # i18n-allow
+ missing = tmp_path / "nope" / "config-soll.json" # i18n-allow
+ monkeypatch.setattr(config_writer, "_config_soll_path", lambda: missing) # i18n-allow
+ receipt = config_writer.set_brain_provider_model(
+ "gemini", deep_model="gemini-3.1-pro", path=sample_toml
+ )
+ assert receipt.baseline_ok is True and receipt.toml_ok is True