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: recover desktop startup from structured env drift
Ruben Lütkea90a38ea91b4
diff --git a/jarvis/core/config.py b/jarvis/core/config.pyindex 6faccd31b1..1b733dd6b4 100644--- a/jarvis/core/config.py+++ b/jarvis/core/config.py@@ -22,8 +22,9 @@ from collections.abc import Iterator, Mappingfrom contextlib import contextmanagerfrom contextvars import ContextVarfrom dataclasses import dataclass+from functools import lru_cachefrom pathlib import Path-from typing import TYPE_CHECKING, Any, Literal+from typing import TYPE_CHECKING, Any, Literal, get_args, get_originimport yamlfrom pydantic import AliasChoices, BaseModel, ConfigDict, Field, field_validator@@ -3640,25 +3641,110 @@ def refresh_persisted_env_from_user_registry(return changed+def _base_model_type(annotation: Any) -> type[BaseModel] | None:+ """Return the BaseModel carried by an annotation, including unions."""+ if isinstance(annotation, type) and issubclass(annotation, BaseModel):+ return annotation+ for candidate in get_args(annotation):+ model_type = _base_model_type(candidate)+ if model_type is not None:+ return model_type+ return None+++def _container_type(annotation: Any) -> type[dict] | type[list] | None:+ """Return the mapping/list shape carried by a field annotation."""+ origin = get_origin(annotation)+ candidate = origin or annotation+ if isinstance(candidate, type) and issubclass(candidate, Mapping):+ return dict+ if candidate is list:+ return list+ for nested in get_args(annotation):+ container_type = _container_type(nested)+ if container_type is not None:+ return container_type+ return None+++@lru_cache(maxsize=256)+def _expected_env_container(path: tuple[str, ...]) -> type[dict] | type[list] | None:+ """Resolve a structured ENV target from the Pydantic config schema."""+ model_type: type[BaseModel] = JarvisConfig+ for index, segment in enumerate(path):+ field = model_type.model_fields.get(segment)+ if field is None:+ return None+ if index == len(path) - 1:+ return _container_type(field.annotation)+ nested_model = _base_model_type(field.annotation)+ if nested_model is None:+ return None+ model_type = nested_model+ return None++def _apply_env_overrides(data: dict[str, Any], prefix: str = "JARVIS__") -> dict[str, Any]:"""Override config with env variables in the format JARVIS__SECTION__KEY=value.Example: JARVIS__BRAIN__PRIMARY=openrouter → config["brain"]["primary"]"""- for env_key, env_val in os.environ.items():+ for env_key, env_val in tuple(os.environ.items()):if not env_key.startswith(prefix):continuepath = env_key[len(prefix):].lower().split("__")cursor = data+ blocked = Falsefor segment in path[:-1]:- cursor = cursor.setdefault(segment, {})- cursor[path[-1]] = _coerce_env_value(env_val)+ existing_segment = cursor.get(segment)+ if existing_segment is None:+ existing_segment = {}+ cursor[segment] = existing_segment+ if not isinstance(existing_segment, dict):+ blocked = True+ break+ cursor = existing_segment+ if blocked:+ os.environ.pop(env_key, None)+ logging.getLogger(__name__).warning(+ "Ignoring config override %s because its path crosses a scalar",+ env_key,+ )+ continue+ value = _coerce_env_value(env_val)+ existing_value = cursor.get(path[-1])+ expected_container = _expected_env_container(tuple(path))+ mapping_conflict = (+ expected_container is dict or isinstance(existing_value, dict)+ ) and not isinstance(value, dict)+ list_conflict = (+ expected_container is list or isinstance(existing_value, list)+ ) and not isinstance(value, list)+ if mapping_conflict or list_conflict:+ # An older drift-guard serialized structured JSON as a PowerShell+ # string such as "@{provider=model}". Replacing a TOML mapping/list+ # with that scalar bricks Pydantic validation and desktop startup.+ os.environ.pop(env_key, None)+ logging.getLogger(__name__).warning(+ "Ignoring scalar config override %s for a structured value",+ env_key,+ )+ continue+ cursor[path[-1]] = valuereturn datadef _coerce_env_value(v: str) -> Any:- """Coerce a string env value to bool/int/float/str."""+ """Coerce an environment string to JSON containers or a scalar."""lv = v.strip().lower()+ if lv.startswith(("{", "[")):+ try:+ parsed = json.loads(v)+ except (TypeError, ValueError):+ pass+ else:+ if isinstance(parsed, (dict, list)):+ return parsedif lv in ("true", "yes", "1"):return Trueif lv in ("false", "no", "0"):diff --git a/scripts/jarvis-config-drift-guard.ps1 b/scripts/jarvis-config-drift-guard.ps1index 4678c558e4..bda1416cda 100644--- a/scripts/jarvis-config-drift-guard.ps1+++ b/scripts/jarvis-config-drift-guard.ps1@@ -1,42 +1,39 @@<#.SYNOPSIS- Config-Drift-Guard: prueft jarvis.toml + ENV-Overrides gegen die Soll-Liste- in scripts/config-soll.json und repariert automatisch jeden Drift.+ Compares jarvis.toml and environment overrides with the desired-state file+ in scripts/config-soll.json and repairs drift automatically..DESCRIPTION- Hintergrund:- Am 2026-05-13 hat BUG-010 (Gemini-Flash-TTS leerer Audio-Buffer) sich in- 80 Minuten dreimal wiederholt, weil eine parallele zweite OpenClaw-- Session jarvis.toml-Werte zurueckgerollt hat. ENV-Overrides + read-only-- TOML waren noetig, sind aber nicht vollstaendig drift-resistent (Read-- only kann entlockt werden, ENV kann geloescht werden). Dieses Skript- ist die dritte Verteidigungs-Schicht: selbstheilender Watchdog.-- Ablauf pro Lauf:- 1. Liest scripts/config-soll.json (User-editierbar -- dort steht der- "approved State").- 2. Liest jarvis.toml als Text.- 3. Vergleicht alle Soll-Keys mit den Ist-Werten via Section-aware Regex.- 4. Bei Mismatch: entfernt Read-only, schreibt den Soll-Wert per Replace,- setzt Read-only wieder.- 5. Prueft die JARVIS__* ENV-Overrides im User-Scope. Setzt fehlende.- 6. Schreibt strukturiertes Log nach logs/config-drift-guard.log.-- Notification:- Wenn -ToastOnDrift gesetzt ist und Drift erkannt wurde, BurntToast wird- versucht (silent fallback bei Fehler).+ BUG-010 recurred three times in 80 minutes because a parallel session+ reverted jarvis.toml values. Environment overrides and a read-only TOML+ file reduced the risk but were not sufficient on their own. This script is+ the third defense layer: a self-healing watchdog.++ Each run:+ 1. Reads scripts/config-soll.json, the user-editable approved state.+ 2. Reads jarvis.toml as text.+ 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.+ 6. Removes obsolete structured overrides that cannot be represented by+ the scalar environment codec.+ 7. Writes a structured log to logs/config-drift-guard.log..PARAMETER RepoRoot- Pfad zum Repo-Root. Default: C:\Users\Administrator\Desktop\Personal Jarvis+ Repository root. Defaults to the parent of this script's directory.-.PARAMETER SollFile- Pfad zur Soll-JSON. Default: $RepoRoot\scripts\config-soll.json+.PARAMETER DesiredFile+ Desired-state JSON path. Defaults to scripts/config-soll.json below RepoRoot.++.PARAMETER EnvironmentTarget+ Environment scope used for reads and writes. User is the production+ default. Process exists for isolated behavioral tests..PARAMETER DryRun- Nur loggen was getan wuerde, kein Fix.+ Reports intended repairs without changing TOML or environment state..PARAMETER ToastOnDrift- Bei erkanntem Drift Toast-Notification senden (BurntToast falls vorhanden).+ Attempts a BurntToast notification after a repair..EXAMPLEpowershell -NoProfile -ExecutionPolicy Bypass -File scripts/jarvis-config-drift-guard.ps1@@ -47,286 +44,312 @@[CmdletBinding()]param(- [string]$RepoRoot = "C:\Users\Administrator\Desktop\Personal Jarvis",- [string]$SollFile = "",+ [string]$RepoRoot = "",+ [string]$DesiredFile = "",+ [ValidateSet("User", "Process")]+ [string]$EnvironmentTarget = "User",[switch]$DryRun,[switch]$ToastOnDrift)$ErrorActionPreference = "Stop"-# ---------- Pfade ----------------------------------------------------------+# ---------- Paths -----------------------------------------------------------if (-not $SollFile) { $SollFile = Join-Path $RepoRoot "scripts\config-soll.json" }+if (-not $RepoRoot) {+ $RepoRoot = [System.IO.Path]::GetFullPath((Join-Path $PSScriptRoot ".."))+}+if (-not $DesiredFile) {+ $DesiredFile = Join-Path $RepoRoot "scripts\config-soll.json"+}$tomlFile = Join-Path $RepoRoot "jarvis.toml"-$logDir = Join-Path $RepoRoot "logs"-$logFile = Join-Path $logDir "config-drift-guard.log"+$logDir = Join-Path $RepoRoot "logs"+$logFile = Join-Path $logDir "config-drift-guard.log"-if (-not (Test-Path $logDir)) { New-Item -ItemType Directory -Path $logDir -Force | Out-Null }-if (-not (Test-Path $tomlFile)) { Write-Host "FATAL: jarvis.toml nicht gefunden bei $tomlFile"; exit 2 }-if (-not (Test-Path $SollFile)) { Write-Host "FATAL: Soll-Datei nicht gefunden bei $SollFile"; exit 3 }+if (-not (Test-Path $logDir)) {+ New-Item -ItemType Directory -Path $logDir -Force | Out-Null+}+if (-not (Test-Path $tomlFile)) {+ Write-Host "FATAL: jarvis.toml was not found at $tomlFile"+ exit 2+}+if (-not (Test-Path $DesiredFile)) {+ Write-Host "FATAL: desired-state file was not found at $DesiredFile"+ exit 3+}function Write-Log {param([string]$Level, [string]$Message)- $ts = Get-Date -Format "yyyy-MM-dd HH:mm:ss"- $line = "$ts | $Level | $Message"+ $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"+ $line = "$timestamp | $Level | $Message"Add-Content -Path $logFile -Value $line -Encoding utf8if ($Level -ne "DEBUG") { Write-Host $line }}-# ---------- Soll lesen -----------------------------------------------------+# ---------- Desired state --------------------------------------------------try {- $soll = Get-Content -Path $SollFile -Raw -Encoding utf8 | ConvertFrom-Json+ $desired = Get-Content -Path $DesiredFile -Raw -Encoding utf8 | ConvertFrom-Json} catch {- Write-Log "FATAL" "Soll-Datei nicht parsebar: $_"+ Write-Log "FATAL" "Desired-state file could not be parsed: $_"exit 4}-# ---------- TOML-Soll-vs-Ist-Vergleich -------------------------------------+# A JARVIS__SECTION__KEY override can represent one scalar only. PowerShell+# stringifies nested JSON objects as "@{key=value}"; Python then receives a+# string where the config schema expects a mapping and the desktop app cannot+# boot. Structured values stay in their TOML sub-table and never enter the+# scalar environment layer.+function Test-IsScalarConfigValue {+ param($Value)+ return (+ ($Value -is [string]) -or+ ($Value -is [bool]) -or+ ($Value -is [byte]) -or+ ($Value -is [int16]) -or+ ($Value -is [int32]) -or+ ($Value -is [int64]) -or+ ($Value -is [single]) -or+ ($Value -is [double]) -or+ ($Value -is [decimal])+ )+}-# Wir nutzen Section-aware Regex: pro Section iterieren wir die Keys.-# Die Soll-Struktur hat zwei "echte" Sections (tts, brain) plus underscore--# prefixed Metadata-Keys (_comment, _updated, _reason) die ignoriert werden.+# ---------- TOML desired-versus-actual comparison --------------------------$drifts = @() # @{section, key, ist, soll}+# Metadata keys use an underscore prefix and are intentionally ignored.+$drifts = @()-foreach ($section in $soll.PSObject.Properties) {+foreach ($section in $desired.PSObject.Properties) {if ($section.Name.StartsWith("_")) { continue }- $sectionName = $section.Name- $sectionData = $section.Value- foreach ($keyProp in $sectionData.PSObject.Properties) {- $key = $keyProp.Name- # NOTE: use a distinct loop-local name ($sollValue), NOT $soll.- # PowerShell foreach has no block scoping, so assigning to $soll here- # would clobber the parsed-JSON object loaded at the top of the script.- # The ENV-override loop below re-iterates $soll.PSObject.Properties --- # if $soll were overwritten with the last scalar key value, that loop- # would iterate a bare string's members instead of the config sections- # and the ENV check would silently become a no-op (it always logged- # "ENV-Overrides clean" regardless of the real ENV). Discovered + fixed- # 2026-05-28 while hardening the brain.primary three-layer sync.- $sollValue = $keyProp.Value- # ist-Wert aus TOML extrahieren -- robuste Regex pro Section+ $sectionName = $section.Name+ $sectionData = $section.Value+ foreach ($keyProperty in $sectionData.PSObject.Properties) {+ $key = $keyProperty.Name+ # PowerShell foreach blocks share scope. Keep this value distinct from+ # $desired so the later environment loop still sees the parsed object.+ $desiredValue = $keyProperty.Value+ if (-not (Test-IsScalarConfigValue $desiredValue)) {+ continue+ }+$tomlText = Get-Content -Path $tomlFile -Raw -Encoding utf8- # Section-Block: alles von "[<section>]" bis zur naechsten "[..."-Zeile$sectionPattern = "(?ms)^\[$sectionName\][^\[]*"$sectionMatch = [regex]::Match($tomlText, $sectionPattern)if (-not $sectionMatch.Success) {- Write-Log "WARN" "Section [$sectionName] nicht in TOML gefunden -- uebersprungen"+ Write-Log "WARN" "Section [$sectionName] was not found in TOML; skipped"continue}$sectionBody = $sectionMatch.Value- # 2026-05-17 fix: capture BOTH quoted strings AND unquoted scalars- # (booleans, integers, floats). The original pattern only matched- # `key = "value"`, so any `enabled = false` / `timeout_ms = 4000`- # entry in config-soll.json was silently skipped with a WARN —- # the drift was never enforced. Now group 1 = quoted, group 2 =- # unquoted token (until whitespace / comment-marker / EOL).++ # Group 1 captures quoted strings; group 2 captures unquoted scalars.$keyPattern = "(?m)^\s*$key\s*=\s*(?:`"([^`"]*)`"|([^\s#`r`n]+))"$keyMatch = [regex]::Match($sectionBody, $keyPattern)if (-not $keyMatch.Success) {- Write-Log "WARN" "Key '$key' in [$sectionName] nicht in TOML gefunden -- uebersprungen (Soll '$sollValue')"+ Write-Log "WARN" "Key '$key' in [$sectionName] was not found; desired '$desiredValue' was skipped"continue}if ($keyMatch.Groups[1].Success) {- $ist = $keyMatch.Groups[1].Value+ $actual = $keyMatch.Groups[1].Value} else {- $ist = $keyMatch.Groups[2].Value+ $actual = $keyMatch.Groups[2].Value}- # Normalize both sides to lower-case strings so the JSON bool- # `$false` ("False") matches the TOML bool `false`, and ints- # like 4000 compare as their string form.- $istNorm = ([string]$ist).Trim().ToLower()- $sollNorm = ([string]$sollValue).Trim().ToLower()- if ($istNorm -ne $sollNorm) {- $drifts += [PSCustomObject]@{ Section=$sectionName; Key=$key; Ist=$ist; Soll=$sollValue }++ # Normalize booleans and numerics through their lowercase string form.+ $actualNormalized = ([string]$actual).Trim().ToLower()+ $desiredNormalized = ([string]$desiredValue).Trim().ToLower()+ if ($actualNormalized -ne $desiredNormalized) {+ $drifts += [PSCustomObject]@{+ Section = $sectionName+ Key = $key+ Actual = $actual+ Desired = $desiredValue+ }}}}-# ---------- ENV-Overrides pruefen -----------------------------------------+# ---------- Environment comparison -----------------------------------------# Die ENV-Overrides haben Format JARVIS__<SECTION>__<KEY> (uppercase).-# 2026-05-18 H11 fix: ENV values are always strings, but $keyProp.Value-# carries the original JSON type (bool/int/float/string). Compare via-# the same lowercase-trim normalization the TOML branch uses -- otherwise-# bool $false stringifies to "False" and never matches the user-scope-# "false" they set manually, looping a no-op FIX every 5 min.function Format-EnvLiteral {- param($v)- if ($v -is [bool]) { return $(if ($v) { "true" } else { "false" }) }- return [string]$v+ param($Value)+ if ($Value -is [bool]) {+ return $(if ($Value) { "true" } else { "false" })+ }+ return [string]$Value}-$envMissing = @()-foreach ($section in $soll.PSObject.Properties) {++$missingEnv = @()+$obsoleteStructuredEnv = @()+foreach ($section in $desired.PSObject.Properties) {if ($section.Name.StartsWith("_")) { continue }- foreach ($keyProp in $section.Value.PSObject.Properties) {- $envName = "JARVIS__" + $section.Name.ToUpper() + "__" + $keyProp.Name.ToUpper()- $envValue = [Environment]::GetEnvironmentVariable($envName, "User")- $sollLit = Format-EnvLiteral $keyProp.Value- if (-not $envValue -or $envValue.Trim().ToLower() -ne $sollLit.Trim().ToLower()) {- $envMissing += [PSCustomObject]@{ EnvName=$envName; Soll=$sollLit; Ist=$envValue }+ foreach ($keyProperty in $section.Value.PSObject.Properties) {+ $envName = "JARVIS__" + $section.Name.ToUpper() + "__" + $keyProperty.Name.ToUpper()+ $envValue = [Environment]::GetEnvironmentVariable($envName, $EnvironmentTarget)+ if (-not (Test-IsScalarConfigValue $keyProperty.Value)) {+ if ($null -ne $envValue) {+ $obsoleteStructuredEnv += $envName+ }+ continue+ }+ $desiredLiteral = Format-EnvLiteral $keyProperty.Value+ if (+ $null -eq $envValue -or+ $envValue.Trim().ToLower() -ne $desiredLiteral.Trim().ToLower()+ ) {+ $missingEnv += [PSCustomObject]@{+ EnvName = $envName+ Desired = $desiredLiteral+ Actual = $envValue+ }}}}-# ---------- Fixes anwenden ------------------------------------------------+# ---------- Apply repairs --------------------------------------------------$fixesApplied = 0if ($drifts.Count -gt 0) {- Write-Log "DRIFT" "TOML-Drift erkannt: $($drifts.Count) Key(s) abweichend"- foreach ($d in $drifts) {- Write-Log "DRIFT" " [$($d.Section)] $($d.Key): ist='$($d.Ist)' soll='$($d.Soll)'"+ Write-Log "DRIFT" "Detected $($drifts.Count) divergent TOML key(s)"+ foreach ($drift in $drifts) {+ Write-Log "DRIFT" " [$($drift.Section)] $($drift.Key): actual='$($drift.Actual)' desired='$($drift.Desired)'"}if (-not $DryRun) {- # Read-only Flag temporaer entfernen$tomlItem = Get-Item -Path $tomlFile$wasReadOnly = $tomlItem.IsReadOnlyif ($wasReadOnly) {Set-ItemProperty -Path $tomlFile -Name IsReadOnly -Value $false}- # Fixes anwenden -- Section-aware, PowerShell -replace mit Multiline-Flag+$tomlText = Get-Content -Path $tomlFile -Raw -Encoding utf8- foreach ($d in $drifts) {- $sectionPattern = "(?ms)^\[$($d.Section)\][^\[]*"+ foreach ($drift in $drifts) {+ $sectionPattern = "(?ms)^\[$($drift.Section)\][^\[]*"$sectionMatch = [regex]::Match($tomlText, $sectionPattern)if (-not $sectionMatch.Success) { continue }$sectionBody = $sectionMatch.Value- # 2026-05-18 H11 fix: the FIX regex used to match only quoted- # strings (`key = "value"`). Combined with the 2026-05-17- # detection-side fix that started catching unquoted scalars- # (`enabled = false`, `timeout_ms = 4000`), this meant the- # drift was DETECTED but never REPAIRED -- the WARN branch- # below fired on every loop. Now we dispatch on the JSON- # type of $d.Soll: bool/int/float emit unquoted, strings- # stay quoted (TOML semantics).- $sollType = $null- if ($d.Soll -is [bool]) { $sollType = "bool" }- elseif ($d.Soll -is [int]) { $sollType = "int" }- elseif ($d.Soll -is [long]) { $sollType = "int" }- elseif ($d.Soll -is [double]) { $sollType = "float" }- elseif ($d.Soll -is [decimal]) { $sollType = "float" }- else { $sollType = "string" }-- # Use ${1} (not $1) so PowerShell's -replace parser does NOT- # accidentally fuse the backref with leading digits in the- # replacement value -- e.g. '$1' + '4000' would become- # '$14000' (= regex group #14 = empty), silently corrupting- # the file as "...=$14000...". See 2026-05-18 H11 debug run.- if ($sollType -eq "string") {- # key = "value"- $keyPattern = '(?m)^(\s*' + [regex]::Escape($d.Key) + '\s*=\s*)"[^"]*"'- $replacement = '${1}"' + $d.Soll + '"'++ if ($drift.Desired -is [bool]) { $desiredType = "bool" }+ elseif ($drift.Desired -is [int16]) { $desiredType = "int" }+ elseif ($drift.Desired -is [int32]) { $desiredType = "int" }+ elseif ($drift.Desired -is [int64]) { $desiredType = "int" }+ elseif ($drift.Desired -is [single]) { $desiredType = "float" }+ elseif ($drift.Desired -is [double]) { $desiredType = "float" }+ elseif ($drift.Desired -is [decimal]) { $desiredType = "float" }+ else { $desiredType = "string" }++ # ${1} prevents a leading digit in the value from being parsed as+ # part of the regex group number, for example $1 + 4000 -> $14000.+ if ($desiredType -eq "string") {+ $keyPattern = '(?m)^(\s*' + [regex]::Escape($drift.Key) + '\s*=\s*)"[^"]*"'+ $replacement = '${1}"' + $drift.Desired + '"'} else {- # key = literal (bool/int/float). TOML wants lowercase- # booleans, so normalize PowerShell's $true / $false.- $literal = if ($sollType -eq "bool") {- if ($d.Soll) { "true" } else { "false" }+ $literal = if ($desiredType -eq "bool") {+ if ($drift.Desired) { "true" } else { "false" }} else {- [string]$d.Soll+ [string]$drift.Desired}- # Match the existing assignment regardless of whether it- # is currently quoted or unquoted -- we always rewrite to- # the literal form for non-string types.- $keyPattern = '(?m)^(\s*' + [regex]::Escape($d.Key) + '\s*=\s*)(?:"[^"]*"|[^\s#\r\n]+)'+ $keyPattern = '(?m)^(\s*' + [regex]::Escape($drift.Key) + '\s*=\s*)(?:"[^"]*"|[^\s#\r\n]+)'$replacement = '${1}' + $literal}$newSectionBody = $sectionBody -replace $keyPattern, $replacementif ($newSectionBody -eq $sectionBody) {- Write-Log "WARN" " [$($d.Section)] $($d.Key) -- Pattern matched nicht ($sollType), Fix uebersprungen"+ Write-Log "WARN" " [$($drift.Section)] $($drift.Key) did not match the repair pattern ($desiredType); skipped"continue}$tomlText = $tomlText.Replace($sectionBody, $newSectionBody)- Write-Log "FIX" " [$($d.Section)] $($d.Key) := '$($d.Soll)' ($sollType)"+ Write-Log "FIX" " [$($drift.Section)] $($drift.Key) := '$($drift.Desired)' ($desiredType)"$fixesApplied++}- # PS 5.1 `-Encoding utf8` writes a BOM, which Python's `tomllib`- # rejects with "Invalid statement at line 1, column 1". Write raw- # UTF-8 without BOM via .NET so Jarvis can still parse the file.++ # Windows PowerShell 5.1 adds a BOM for -Encoding utf8. Write explicit+ # BOM-free UTF-8 so Python tomllib can parse the file.$utf8NoBom = New-Object System.Text.UTF8Encoding($false)[System.IO.File]::WriteAllText($tomlFile, $tomlText, $utf8NoBom)- # Read-only wieder setzenSet-ItemProperty -Path $tomlFile -Name IsReadOnly -Value $true} else {- Write-Log "INFO" "DryRun -- keine Aenderung an jarvis.toml"+ Write-Log "INFO" "DryRun -- jarvis.toml was not changed"}} else {- Write-Log "DEBUG" "TOML clean -- keine Drift"+ Write-Log "DEBUG" "TOML is in sync"}-if ($envMissing.Count -gt 0) {- Write-Log "DRIFT" "ENV-Override fehlt/abweichend: $($envMissing.Count) Variable(n)"- foreach ($e in $envMissing) {- Write-Log "DRIFT" " $($e.EnvName): ist='$($e.Ist)' soll='$($e.Soll)'"+if ($missingEnv.Count -gt 0) {+ Write-Log "DRIFT" "Detected $($missingEnv.Count) missing or divergent environment override(s)"+ foreach ($entry in $missingEnv) {+ Write-Log "DRIFT" " $($entry.EnvName): actual='$($entry.Actual)' desired='$($entry.Desired)'"}if (-not $DryRun) {- foreach ($e in $envMissing) {- [Environment]::SetEnvironmentVariable($e.EnvName, $e.Soll, "User")- Write-Log "FIX" " $($e.EnvName) := '$($e.Soll)' (User-Scope)"+ foreach ($entry in $missingEnv) {+ [Environment]::SetEnvironmentVariable(+ $entry.EnvName,+ $entry.Desired,+ $EnvironmentTarget+ )+ Write-Log "FIX" " $($entry.EnvName) := '$($entry.Desired)' ($EnvironmentTarget scope)"$fixesApplied++}} else {- Write-Log "INFO" "DryRun -- keine ENV-Aenderung"+ Write-Log "INFO" "DryRun -- environment overrides were not changed"}} else {- Write-Log "DEBUG" "ENV-Overrides clean -- alle gesetzt"+ Write-Log "DEBUG" "Scalar environment overrides are in sync"+}++if ($obsoleteStructuredEnv.Count -gt 0) {+ Write-Log "DRIFT" "Removing $($obsoleteStructuredEnv.Count) unsupported structured environment override(s)"+ if (-not $DryRun) {+ foreach ($envName in $obsoleteStructuredEnv) {+ [Environment]::SetEnvironmentVariable($envName, $null, $EnvironmentTarget)+ Write-Log "FIX" " removed $envName from $EnvironmentTarget-scope environment"+ $fixesApplied+++ }+ } else {+ Write-Log "INFO" "DryRun -- structured environment overrides were not removed"+ }}-# ---------- TOML read-only sicherstellen ------------------------------------# We re-assert the read-only flag every run as a defence-in-depth measure-# (a rogue session could have cleared it). But the *meaning* of that re-lock-# depends on whether this run actually saw drift:-#-# * Drift was detected this run -> the unlocked TOML was an active attack-# surface; re-locking is part of the FIX. Log it loud, count it.-# * No drift this run (TOML/ENV fully synced) -> the TOML is simply writable-# because the desktop app's provider switch (UI) just rewrote it via the-# atomic config_writer (tempfile + os.replace drops the read-only bit).-# Re-locking here is routine maintenance, NOT a correction. It must be a-# true no-op from the operator's point of view: DEBUG-level only, and it-# MUST NOT increment $fixesApplied (otherwise a synced UI switch would-# fire a Toast and an INFO "Fix(es) angewendet" line on the very next run,-# i.e. log spam / churn the task forbids). The provider value is left-# untouched either way -- this branch only ever flips a file *attribute*.-$driftThisRun = ($drifts.Count -gt 0) -or ($envMissing.Count -gt 0)+# ---------- Preserve TOML read-only state ---------------------------------++# Re-assert the read-only flag as defense in depth. A routine re-lock after a+# synchronized UI write stays at DEBUG and does not count as a repair.+$driftThisRun = (+ ($drifts.Count -gt 0) -or+ ($missingEnv.Count -gt 0) -or+ ($obsoleteStructuredEnv.Count -gt 0)+)if (-not $DryRun) {$tomlItem = Get-Item -Path $tomlFileif (-not $tomlItem.IsReadOnly) {Set-ItemProperty -Path $tomlFile -Name IsReadOnly -Value $trueif ($driftThisRun) {- Write-Log "FIX" "jarvis.toml read-only-Flag re-aktiviert"+ Write-Log "FIX" "Re-enabled the jarvis.toml read-only flag"$fixesApplied++} else {- # Synced state: routine re-lock after a UI provider switch. Quiet.- Write-Log "DEBUG" "jarvis.toml read-only-Flag re-aktiviert (routine, kein Drift)"+ Write-Log "DEBUG" "Re-enabled the jarvis.toml read-only flag after a synchronized write"}}}-# ---------- Toast bei Drift -----------------------------------------------+# ---------- Optional toast -------------------------------------------------if ($ToastOnDrift -and $fixesApplied -gt 0) {try {Import-Module BurntToast -ErrorAction StopNew-BurntToastNotification `- -Text "Personal Jarvis -- Config-Drift gefixt", "$fixesApplied Aenderung(en) repariert" `+ -Text "Personal Jarvis -- config drift repaired", "$fixesApplied repair(s) applied" `-AppLogo (Join-Path $RepoRoot "jarvis\assets\icon.ico" -ErrorAction SilentlyContinue) `-ErrorAction Stop} catch {- Write-Log "WARN" "BurntToast-Notification fehlgeschlagen (silent): $_"+ Write-Log "WARN" "BurntToast notification failed: $_"}}-# ---------- Final -----------------------------------------------------------if ($fixesApplied -gt 0) {- Write-Log "INFO" "Drift-Guard-Lauf abgeschlossen -- $fixesApplied Fix(es) angewendet"+ Write-Log "INFO" "Drift-guard run completed -- $fixesApplied repair(s) applied"} else {- Write-Log "DEBUG" "Drift-Guard-Lauf abgeschlossen -- alles ok"+ Write-Log "DEBUG" "Drift-guard run completed -- state is clean"}exit 0diff --git a/scripts/test-drift-guard-scalars.ps1 b/scripts/test-drift-guard-scalars.ps1index 2967be83fe..0c7d623ec2 100644--- a/scripts/test-drift-guard-scalars.ps1+++ b/scripts/test-drift-guard-scalars.ps1@@ -3,7 +3,7 @@Self-test for jarvis-config-drift-guard.ps1 scalar handling (Bug H11)..DESCRIPTION- Pester-free mini-test that builds a sandbox TOML + soll-JSON in a+ Pester-free mini-test that builds a sandbox TOML + desired-state JSON in atemp dir, runs the drift-guard, and asserts the post-state.Covers the H11 fix (2026-05-18): unquoted scalar bool/int/float mustbe both detected AND repaired.@@ -17,6 +17,7 @@ param()$ErrorActionPreference = "Stop"$failures = @()+$powerShellExecutable = (Get-Process -Id $PID).Path$guardScript = Join-Path $PSScriptRoot "jarvis-config-drift-guard.ps1"if (-not (Test-Path $guardScript)) {@@ -26,12 +27,12 @@ if (-not (Test-Path $guardScript)) {# --------- Sandbox helper -----------------------------------------------function New-Sandbox {- param([string]$TomlContent, [string]$SollJson)+ param([string]$TomlContent, [string]$DesiredJson)$sb = New-Item -ItemType Directory -Path (Join-Path $env:TEMP "drift-guard-test-$([guid]::NewGuid().Guid.Substring(0,8))") -Force$tomlPath = Join-Path $sb "jarvis.toml"- $sollPath = Join-Path $sb "config-soll.json"+ $desiredPath = Join-Path $sb "config-soll.json"[System.IO.File]::WriteAllText($tomlPath, $TomlContent, (New-Object System.Text.UTF8Encoding($false)))- [System.IO.File]::WriteAllText($sollPath, $SollJson, (New-Object System.Text.UTF8Encoding($false)))+ [System.IO.File]::WriteAllText($desiredPath, $DesiredJson, (New-Object System.Text.UTF8Encoding($false)))New-Item -ItemType Directory -Path (Join-Path $sb "logs") -Force | Out-NullNew-Item -ItemType Directory -Path (Join-Path $sb "scripts") -Force | Out-Nullreturn $sb.FullName@@ -39,8 +40,10 @@ function New-Sandbox {function Invoke-Guard {param([string]$Sandbox)- & powershell -NoProfile -ExecutionPolicy Bypass -File $guardScript `- -RepoRoot $Sandbox -SollFile (Join-Path $Sandbox "config-soll.json") *>&1 | Out-Null+ & $powerShellExecutable -NoProfile -ExecutionPolicy Bypass -File $guardScript `+ -RepoRoot $Sandbox `+ -DesiredFile (Join-Path $Sandbox "config-soll.json") `+ -EnvironmentTarget Process *>&1 | Out-Null}function Assert-TomlContains {@@ -59,7 +62,7 @@ function Assert-TomlContains {Write-Host "TEST 1: bool drift (enabled true -> false)" -ForegroundColor Cyan$sb1 = New-Sandbox `-TomlContent "[memory.legacy_curator]`nenabled = true`n" `- -SollJson '{"memory.legacy_curator": {"enabled": false}}'+ -DesiredJson '{"memory.legacy_curator": {"enabled": false}}'# Drift-guard will set the TOML read-only at end -- clear that first.$tomlItem = Get-Item (Join-Path $sb1 "jarvis.toml")if ($tomlItem.IsReadOnly) { Set-ItemProperty (Join-Path $sb1 "jarvis.toml") -Name IsReadOnly -Value $false }@@ -80,7 +83,7 @@ Remove-Item -Recurse -Force $sb1Write-Host "TEST 2: int drift (timeout_ms 1000 -> 4000)" -ForegroundColor Cyan$sb2 = New-Sandbox `-TomlContent "[ack_brain]`ntimeout_ms = 1000`nprovider = `"gemini`"`n" `- -SollJson '{"ack_brain": {"timeout_ms": 4000, "provider": "gemini"}}'+ -DesiredJson '{"ack_brain": {"timeout_ms": 4000, "provider": "gemini"}}'$tomlItem = Get-Item (Join-Path $sb2 "jarvis.toml")if ($tomlItem.IsReadOnly) { Set-ItemProperty (Join-Path $sb2 "jarvis.toml") -Name IsReadOnly -Value $false }Invoke-Guard -Sandbox $sb2@@ -95,7 +98,7 @@ Remove-Item -Recurse -Force $sb2Write-Host "TEST 3: string drift (provider grok -> gemini)" -ForegroundColor Cyan$sb3 = New-Sandbox `-TomlContent "[tts]`nprovider = `"grok-voice`"`n" `- -SollJson '{"tts": {"provider": "gemini-flash-tts"}}'+ -DesiredJson '{"tts": {"provider": "gemini-flash-tts"}}'$tomlItem = Get-Item (Join-Path $sb3 "jarvis.toml")if ($tomlItem.IsReadOnly) { Set-ItemProperty (Join-Path $sb3 "jarvis.toml") -Name IsReadOnly -Value $false }Invoke-Guard -Sandbox $sb3diff --git a/tests/unit/core/test_config_toml_cache.py b/tests/unit/core/test_config_toml_cache.pyindex 4481787661..67a92f3a21 100644--- a/tests/unit/core/test_config_toml_cache.py+++ b/tests/unit/core/test_config_toml_cache.py@@ -182,3 +182,60 @@ def test_load_config_reflects_an_edit(tmp_path, monkeypatch):os.utime(target, ns=(0, 10_000_000_000))assert load_config(target).brain.primary == "openrouter"+++def test_legacy_structured_stt_env_cannot_brick_config_load(tmp_path, monkeypatch):+ """A stale PowerShell object string must not replace the models table."""+ from jarvis.core.config import load_config++ monkeypatch.setenv(+ "JARVIS__STT__MODELS",+ "@{openrouter-stt=openai/gpt-4o-transcribe}",+ )+ target = tmp_path / "jarvis.toml"+ _write(+ target,+ '[stt.models]\nopenrouter-stt = "openai/gpt-4o-transcribe"\n',+ )++ cfg = load_config(target)++ assert cfg.stt.models == {"openrouter-stt": "openai/gpt-4o-transcribe"}+ assert "JARVIS__STT__MODELS" not in os.environ+++def test_schema_blocks_legacy_mapping_env_when_toml_table_is_absent(+ tmp_path, monkeypatch+):+ """Minimal configs still get their structured shape from Pydantic."""+ from jarvis.core.config import load_config++ monkeypatch.setenv("JARVIS__STT__MODELS", "@{provider=model}")+ target = tmp_path / "jarvis.toml"+ _write(target, '[brain]\nprimary = "gemini"\n')++ cfg = load_config(target)++ assert cfg.stt.models == {}+ assert "JARVIS__STT__MODELS" not in os.environ+++def test_scalar_env_cannot_replace_an_arbitrary_mapping(monkeypatch):+ """The safeguard follows the data shape instead of naming one STT key."""+ monkeypatch.setenv("JARVIS__EXAMPLE__MAPPING", "@{nested=value}")+ data = {"example": {"mapping": {"nested": "value"}}}++ result = config_module._apply_env_overrides(data)++ assert result["example"]["mapping"] == {"nested": "value"}+ assert "JARVIS__EXAMPLE__MAPPING" not in os.environ+++def test_json_env_can_replace_an_arbitrary_mapping(monkeypatch):+ """Valid JSON remains a supported structured environment override."""+ monkeypatch.setenv("JARVIS__EXAMPLE__MAPPING", '{"nested":"updated"}')+ data = {"example": {"mapping": {"nested": "value"}}}++ result = config_module._apply_env_overrides(data)++ assert result["example"]["mapping"] == {"nested": "updated"}diff --git a/tests/unit/scripts/test_drift_guard_brain_primary_contract.py b/tests/unit/scripts/test_drift_guard_brain_primary_contract.pyindex 1552e78e9a..fcafd325b9 100644--- a/tests/unit/scripts/test_drift_guard_brain_primary_contract.py+++ b/tests/unit/scripts/test_drift_guard_brain_primary_contract.py@@ -1,10 +1,10 @@-"""Contract test: ``scripts/config-soll.json`` ``brain.primary`` <-> ENV mapping. # i18n-allow: filename/jargon identifier, not translatable prose+"""Contract tests for the desired-state ``brain.primary`` ENV mapping.The Brain-provider switch in the desktop app's API/Settings section persistsacross all three drift-defence layers (BUG-010):* ``jarvis.toml`` -> ``[brain].primary``-* ``scripts/config-soll.json`` -> ``brain.primary`` (the drift-guard's soll) # i18n-allow: filename/jargon identifier, not translatable prose+* Desired-state JSON -> ``brain.primary``* User-scope ENV override -> ``JARVIS__BRAIN__PRIMARY``For the UI switch to make the drift-guard a no-op (instead of reverting the@@ -21,21 +21,27 @@ This test mirrors that rule in Python and pins the contract so a rename oneither side (the JSON section/key, or the guard's derivation rule) fails CIloudly instead of silently breaking provider persistence.-No PowerShell or Windows dependency: it only parses the JSON and reproduces a-string-formatting rule, so it runs on the cloud-first Linux CI path too.+Most tests are platform-independent. The structured-override regression runs+PowerShell in a process-scoped sandbox when available and skips otherwise."""from __future__ import annotationsimport json+import os+import shutil+import subprocessfrom pathlib import Pathimport pytest+from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS-# scripts/config-soll.json lives at <repo>/scripts/config-soll.json. # i18n-allow: filename identifier, not translatable prose+# Desired state: scripts/config-soll.json. # i18n-allow: filename# This test file is at <repo>/tests/unit/scripts/, so parents[3] is the repo root.-CONFIG_SOLL_PATH = ( # i18n-allow: filename/jargon identifier, not translatable prose- Path(__file__).resolve().parents[3] / "scripts" / "config-soll.json" # i18n-allow: filename identifier, not translatable prose+DESIRED_STATE_PATH = (+ Path(__file__).resolve().parents[3]+ / "scripts"+ / "config-soll.json" # i18n-allow: filename)@@ -49,11 +55,11 @@ def _derive_env_name(section: str, key: str) -> str:@pytest.fixture(scope="module")-def soll() -> dict: # i18n-allow: fixture name mirrors the config-soll.json jargon term, not translatable prose- assert CONFIG_SOLL_PATH.is_file(), ( # i18n-allow: filename/jargon identifier, not translatable prose- f"expected the drift-guard soll file at {CONFIG_SOLL_PATH}" # i18n-allow: filename/jargon identifier, not translatable prose+def desired_state() -> dict:+ assert DESIRED_STATE_PATH.is_file(), (+ f"expected the drift-guard desired-state file at {DESIRED_STATE_PATH}")- return json.loads(CONFIG_SOLL_PATH.read_text(encoding="utf-8")) # i18n-allow: filename/jargon identifier, not translatable prose+ return json.loads(DESIRED_STATE_PATH.read_text(encoding="utf-8"))# ---------------------------------------------------------------------------@@ -61,25 +67,27 @@ def soll() -> dict: # i18n-allow: fixture name mirrors the config-soll.json jar# ----------------------------------------------------------------------------def test_config_soll_is_valid_json(soll: dict) -> None: # i18n-allow: identifier name mirrors the config-soll.json jargon term, not translatable prose+def test_desired_state_is_valid_json(desired_state: dict) -> None:"""If the JSON is malformed the whole drift-guard fails to parse (exit 4)."""- assert isinstance(soll, dict) # i18n-allow: identifier name mirrors the config-soll.json jargon term, not translatable prose+ assert isinstance(desired_state, dict)-def test_brain_section_exists(soll: dict) -> None: # i18n-allow: identifier name mirrors the config-soll.json jargon term, not translatable prose- assert "brain" in soll, "config-soll.json must keep a top-level 'brain' section" # i18n-allow: filename/jargon identifier, not translatable prose- assert isinstance(soll["brain"], dict) # i18n-allow: identifier name mirrors the config-soll.json jargon term, not translatable prose+def test_brain_section_exists(desired_state: dict) -> None:+ assert "brain" in desired_state, (+ "desired-state JSON must keep a top-level 'brain' section"+ )+ assert isinstance(desired_state["brain"], dict)-def test_brain_primary_is_non_empty_string(soll: dict) -> None: # i18n-allow: identifier name mirrors the config-soll.json jargon term, not translatable prose+def test_brain_primary_is_non_empty_string(desired_state: dict) -> None:"""brain.primary must exist and be a non-empty string.The drift-guard pins this value and the UI provider switch overwrites it.A missing/empty value would make the guard skip the key (WARN) and the UI- switch would have no soll to keep in sync -> silent revert risk. # i18n-allow: filename/jargon identifier, not translatable prose+ switch would have no desired state to keep in sync -> silent revert risk."""- primary = soll["brain"].get("primary") # i18n-allow: identifier name mirrors the config-soll.json jargon term, not translatable prose- assert primary is not None, "brain.primary must be present in config-soll.json" # i18n-allow: filename/jargon identifier, not translatable prose+ primary = desired_state["brain"].get("primary")+ assert primary is not None, "brain.primary must exist in the desired state"assert isinstance(primary, str), "brain.primary must be a string"assert primary.strip() != "", "brain.primary must not be empty/whitespace"@@ -89,31 +97,99 @@ def test_brain_primary_is_non_empty_string(soll: dict) -> None: # i18n-allow: i# ----------------------------------------------------------------------------def test_brain_primary_env_name_is_canonical(soll: dict) -> None: # i18n-allow: identifier name mirrors the config-soll.json jargon term, not translatable prose+def test_brain_primary_env_name_is_canonical(desired_state: dict) -> None:"""The guard-derived ENV name for brain.primary is JARVIS__BRAIN__PRIMARY.This is the exact variable the desktop app's provider switch sets and the- maintainer sets by hand. If the section/key in config-soll.json is ever # i18n-allow: filename identifier, not translatable prose- renamed, the derived name diverges from what the UI writes and the guard+ maintainer sets by hand. If the desired-state section or key is renamed,+ the derived name diverges from what the UI writes and the guardwould re-add a 'missing' ENV var every run -> the whole fix breaks."""- assert "primary" in soll["brain"] # i18n-allow: identifier name mirrors the config-soll.json jargon term, not translatable prose+ assert "primary" in desired_state["brain"]env_name = _derive_env_name("brain", "primary")assert env_name == "JARVIS__BRAIN__PRIMARY"-def test_env_derivation_rule_matches_guard_for_all_keys(soll: dict) -> None: # i18n-allow: identifier name mirrors the config-soll.json jargon term, not translatable prose- """Every (section, key) in the soll maps to a JARVIS__-prefixed ENV name. # i18n-allow: filename/jargon identifier, not translatable prose+def test_env_derivation_rule_matches_guard_for_all_keys(desired_state: dict) -> None:+ """Every scalar desired-state entry maps to a JARVIS__-prefixed ENV name.Pins the general derivation rule (double-underscore separator, upper-case,JARVIS__ prefix) the guard relies on -- not just brain.primary -- so anyfuture key inherits the same contract."""- for section, payload in soll.items(): # i18n-allow: identifier name mirrors the config-soll.json jargon term, not translatable prose+ for section, payload in desired_state.items():if section.startswith("_") or not isinstance(payload, dict):continue- for key in payload:+ for key, value in payload.items():+ if isinstance(value, (dict, list)) or value is None:+ continueenv_name = _derive_env_name(section, key)assert env_name.startswith("JARVIS__"), env_nameassert "__" in env_name[len("JARVIS__"):], env_nameassert env_name == env_name.upper(), env_name+++def test_structured_stt_models_never_becomes_one_env_override(+ desired_state: dict,+ tmp_path: Path,+) -> None:+ """A sandboxed guard run removes the malformed process override."""+ assert isinstance(desired_state["stt"]["models"], dict)+ powershell = shutil.which("powershell") or shutil.which("pwsh")+ if powershell is None:+ pytest.skip("PowerShell is unavailable")++ guard = (+ Path(__file__).resolve().parents[3]+ / "scripts"+ / "jarvis-config-drift-guard.ps1"+ )+ sandbox = tmp_path / "repo"+ sandbox.mkdir()+ desired_file = sandbox / "desired.json"+ desired_file.write_text(+ json.dumps({"stt": {"models": desired_state["stt"]["models"]}}),+ encoding="utf-8",+ )+ toml_file = sandbox / "jarvis.toml"+ toml_file.write_text(+ '[stt.models]\nopenrouter-stt = "openai/gpt-4o-transcribe"\n',+ encoding="utf-8",+ )+ env = os.environ.copy()+ env["JARVIS__STT__MODELS"] = "@{openrouter-stt=openai/gpt-4o-transcribe}"++ result = subprocess.run(+ [+ powershell,+ "-NoProfile",+ "-ExecutionPolicy",+ "Bypass",+ "-File",+ str(guard),+ "-RepoRoot",+ str(sandbox),+ "-DesiredFile",+ str(desired_file),+ "-EnvironmentTarget",+ "Process",+ ],+ cwd=sandbox,+ env=env,+ capture_output=True,+ text=True,+ encoding="utf-8",+ errors="replace",+ timeout=30,+ check=False,+ creationflags=NO_WINDOW_CREATIONFLAGS,+ )++ assert result.returncode == 0, result.stdout + result.stderr+ log = (sandbox / "logs" / "config-drift-guard.log").read_text(+ encoding="utf-8-sig"+ )+ assert "removed JARVIS__STT__MODELS from Process-scope environment" in log+ assert toml_file.read_text(encoding="utf-8") == (+ '[stt.models]\nopenrouter-stt = "openai/gpt-4o-transcribe"\n'+ )