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
chore(i18n): translate/mark German introduced by concurrent commits during merge (0 backlog)
Ruben Lütke9420d916baf0
diff --git a/docs/local-wakeword/WAKE-RELIABILITY-DEEPDIVE.md b/docs/local-wakeword/WAKE-RELIABILITY-DEEPDIVE.mdindex b66590033a..914b472cc2 100644--- a/docs/local-wakeword/WAKE-RELIABILITY-DEEPDIVE.md+++ b/docs/local-wakeword/WAKE-RELIABILITY-DEEPDIVE.md@@ -20,8 +20,8 @@ on a Pixel — on Windows, Linux and macOS. Reported symptom: a clear, loudexactly "say it 2-3 times".- **The wake runs a weak `base` model on the CPU** while the RTX 5070 Ti sitsidle (the post-wake utterance STT is cloud/Groq, so the GPU is free). Under app- CPU/GIL contention `base` both mis-transcribes ("Mach weiter" -> "Nach- weiter"/"Wetter. Its fun.") and occasionally hangs past the 8 s timeout.+ CPU/GIL contention `base` both mis-transcribes ("Mach weiter" -> "Nach <!-- i18n-allow -->+ weiter"/"Wetter. Its fun.") and occasionally hangs past the 8 s timeout. <!-- i18n-allow -->The deeper truth: **wake detection via full speech-to-text is the wrongarchitecture.** "Hey Google"/Alexa/Siri never transcribe to wake — they run adiff --git a/jarvis/plugins/wake/openwakeword_provider.py b/jarvis/plugins/wake/openwakeword_provider.pyindex 74bc015ed9..1958b035d3 100644--- a/jarvis/plugins/wake/openwakeword_provider.py+++ b/jarvis/plugins/wake/openwakeword_provider.py@@ -1,14 +1,14 @@-"""openWakeWord-Plugin — detektiert "Hey Jarvis" / "Jarvis" im Audio-Stream.+"""openWakeWord plugin — detects "Hey Jarvis" / "Jarvis" in the audio stream.-openWakeWord ist ein freies, Open-Source Wake-Word-System (MIT), nutzt-ONNX-Runtime und hat "hey_jarvis" als vortrainiertes Model eingebaut —-Null API-Key nötig.+openWakeWord is a free, open-source wake-word system (MIT), uses the+ONNX runtime, and ships "hey_jarvis" as a built-in pretrained model —+zero API key needed.-Input-Format: 16 kHz mono int16 PCM, Frame-Größe muss 1280 Samples (80 ms)-sein. Wir pufern Mic-Chunks rein und splitten auf Frame-Grenze.+Input format: 16 kHz mono int16 PCM, frame size must be 1280 samples (80 ms).+We buffer mic chunks and split on the frame boundary.-Output: Continuous Score [0, 1] pro Keyword — wir filtern auf-`activation_threshold` und debouncen (kein Re-Trigger innerhalb Cooldown).+Output: continuous score [0, 1] per keyword — we filter on+`activation_threshold` and debounce (no re-trigger within the cooldown)."""from __future__ import annotations@@ -26,7 +26,7 @@ log = logging.getLogger("jarvis.wake")OWW_SAMPLE_RATE = 16_000-OWW_FRAME_SAMPLES = 1280 # openWakeWord erwartet genau diese Frame-Länge+OWW_FRAME_SAMPLES = 1280 # openWakeWord expects exactly this frame length# After the pipeline's STT prefix-verifier REJECTS a candidate, the detector# stays deaf only this long (not the full cooldown). Short enough that a real@@ -133,11 +133,11 @@ class WakeGainNormalizer:class OpenWakeWordProvider:- """Wake-Word-Detector — strukturell `WakeWordProvider`-kompatibel.+ """Wake-word detector — structurally compatible with `WakeWordProvider`.- Standardmäßig lauscht er auf "hey_jarvis" — das vortrainierte Modell- reagiert aus meinem Test heraus sowohl auf "Hey Jarvis" als auch auf- "Jarvis" allein, wenn der Threshold niedrig genug ist (0.5 tauglich).+ By default it listens for "hey_jarvis" — in my testing the pretrained+ model reacts to both "Hey Jarvis" and "Jarvis" alone, as long as the+ threshold is low enough (0.5 works)."""name = "openwakeword"@@ -156,9 +156,10 @@ class OpenWakeWordProvider:activation_threshold: float = PRODUCTION_WAKE_THRESHOLD,cooldown_s: float = 2.0,inference_framework: str = "onnx",- # Diagnose-Log: alles >= diesem Wert loggen. 0.05 ist bewusst niedrig,- # damit beim Testen Scores überhaupt sichtbar sind (sonst silent wenn- # User zu leise spricht oder Model deutsche Aussprache nicht gut trifft).+ # Diagnostic log: log everything >= this value. 0.05 is deliberately low+ # so scores are visible at all during testing (otherwise silent when+ # the user speaks too quietly, or the model doesn't handle German+ # pronunciation well).score_log_threshold: float = 0.05,# Explicit ONNX wake-model path. When set (custom-wake-word feature: a# pretrained alexa/mycroft/rhasspy from the openWakeWord package, or a@@ -307,10 +308,10 @@ class OpenWakeWordProvider:def _ensure_model(self) -> None:if self._model is None:from openwakeword.model import Model- # wakeword_models=[...] akzeptiert entweder Built-in-Namen oder- # Pfade zu .onnx / .tflite Dateien. Wir bevorzugen die gebündelten- # lokalen ONNX-Pfade (siehe _model_kwargs) — kein Runtime-Download,- # offline-fähig beim ersten Start.+ # wakeword_models=[...] accepts either built-in names or paths to+ # .onnx / .tflite files. We prefer the bundled local ONNX paths+ # (see _model_kwargs) — no runtime download, offline-capable on+ # first boot.self._model = Model(**self._model_kwargs())def _warmup_model(self) -> None:@@ -333,7 +334,7 @@ class OpenWakeWordProvider:log.debug("OWW warm-up inference skipped: %s", exc)async def start(self) -> None:- """Pre-load AND warm the model — spart Kaltstart-Latenz beim ersten Frame."""+ """Pre-load AND warm the model — saves cold-start latency on the first frame."""await asyncio.to_thread(self._ensure_model)await asyncio.to_thread(self._warmup_model)@@ -369,10 +370,10 @@ class OpenWakeWordProvider:async def detect(self, chunks: AsyncIterator[AudioChunk]) -> AsyncIterator[str]:- """Konsumiert Audio-Chunks, yielded Keyword-Namen bei Detection.+ """Consumes audio chunks, yields keyword names on detection.- Das ist die Convenience-API — intern nutzen wir `stream()` für- rohe Confidence-Werte (Protocol-Anforderung).+ This is the convenience API — internally we use `stream()` for+ raw confidence values (protocol requirement)."""self._ensure_model()assert self._model is not None@@ -390,11 +391,11 @@ class OpenWakeWordProvider:self._reset_session_stats()async for chunk in chunks:- # Int16-View auf die Bytes — openWakeWord erwartet int16 arrays+ # Int16 view over the bytes — openWakeWord expects int16 arraysint16 = np.frombuffer(chunk.pcm, dtype=np.int16)buf = np.concatenate([self._residual, int16])- # In 1280-Sample-Frames splitten, Rest aufheben+ # Split into 1280-sample frames, keep the remaindern_full = len(buf) // OWW_FRAME_SAMPLESif n_full == 0:self._residual = buf@@ -407,7 +408,7 @@ class OpenWakeWordProvider:# so a normal-volume "Hey Jarvis" reaches the score band the# threshold expects (no shouting). Amplify-only + noise-floor gated.norm_frame = self._gain.process(frame) if self._gain is not None else frame- # predict() gibt dict zurück: {"hey_jarvis": score_float, ...}+ # predict() returns a dict: {"hey_jarvis": score_float, ...}scores = await asyncio.to_thread(self._model.predict, norm_frame)self._frames_seen += 1frame_max = max(scores.values()) if scores else 0.0@@ -415,8 +416,8 @@ class OpenWakeWordProvider:if frame_max > self._max_score:self._max_score = frame_maxfor keyword, score in scores.items():- # Live-Debugging: alles über `score_log_threshold` loggen,- # damit der User beim Testen sieht wie nah er am Hit dran ist.+ # Live debugging: log everything above `score_log_threshold`,+ # so during testing the user can see how close they are to a hit.if score >= self._score_log_threshold:log.info("wake score %s = %.3f (threshold %.2f)",keyword, score, self._threshold)@@ -448,9 +449,9 @@ class OpenWakeWordProvider:self._maybe_log_stats_heartbeat()async def stream(self) -> AsyncIterator[float]:- """Protocol-Pflicht: Confidence-Stream. Nicht die primäre API hier."""- # Placeholder — wir nutzen `detect()` intern. Für Protocol-Konformität- # müsste der Consumer sein eigenes Audio einspeisen.+ """Protocol requirement: confidence stream. Not the primary API here."""+ # Placeholder — we use `detect()` internally. For protocol conformance+ # the consumer would need to feed in its own audio.if False:yield 0.0returndiff --git a/jarvis/speech/rolling_whisper_wake.py b/jarvis/speech/rolling_whisper_wake.pyindex e65f7b5431..2ce1044d74 100644--- a/jarvis/speech/rolling_whisper_wake.py+++ b/jarvis/speech/rolling_whisper_wake.py@@ -1,24 +1,23 @@-"""Rolling-Window Whisper Wake-Detection — robuster Wake ohne VAD-Abhängigkeit.--Im Gegensatz zu `whisper_wake.py` (wartet auf VAD-Endpoint, scheitert bei-leisen Mics): hier wird ein Ring-Buffer von 2.5 Sekunden Audio gehalten-und alle 500 ms durch Whisper transkribiert. Wenn "jarvis" im Transkript-auftaucht — Trigger.--Vorteile:-- Kein VAD-Dependency → funktioniert auch bei niedrigem Mic-Pegel-- Triggert sofort (500 ms Polling-Intervall), nicht erst nach Sprachende-- Nutzt Whisper (nativ deutsch-fähig) → keine Englisch-Trainings-Bias--Nachteile:-- Höhere GPU-Last (Whisper läuft permanent statt nur bei Utterance-Ende)-- Auf RTX 5070 Ti mit distil-large-v3: ~80-150 ms pro 2.5-Sek-Transkription- = ~20 % GPU-Nutzung bei 500 ms Poll-Intervall--Parameter:-- `window_s`: Buffer-Länge (Default 2.5 s — lang genug für "Hey Jarvis")-- `poll_interval_s`: wie oft wir transkribieren (Default 0.5 s)-- `cooldown_s`: nach Trigger nicht sofort wieder (Default 2 s)+"""Rolling-window Whisper wake detection — robust wake without a VAD dependency.++Unlike `whisper_wake.py` (which waits for a VAD endpoint and fails on quiet+mics): here a 2.5-second ring buffer of audio is held and transcribed by+Whisper every 500 ms. If "jarvis" shows up in the transcript — trigger.++Advantages:+- No VAD dependency → also works at a low mic level+- Triggers immediately (500 ms polling interval), not only after speech ends+- Uses Whisper (natively German-capable) → no English-training bias++Disadvantages:+- Higher GPU load (Whisper runs continuously instead of only at utterance end)+- On an RTX 5070 Ti with distil-large-v3: ~80-150 ms per 2.5-second transcription+ = ~20 % GPU usage at a 500 ms poll interval++Parameters:+- `window_s`: buffer length (default 2.5 s — long enough for "Hey Jarvis")+- `poll_interval_s`: how often we transcribe (default 0.5 s)+- `cooldown_s`: don't trigger again immediately after a trigger (default 2 s)"""from __future__ import annotations@@ -50,7 +49,7 @@ from jarvis.speech.wake_constants import JARVIS_WAKE_PATTERN as DEFAULT_PATTERNlog = logging.getLogger("jarvis.wake.rolling")-# Watchdog-Verzeichnis für Debug-WAVs+# Watchdog directory for debug WAVsDEBUG_DIR = Path(os.environ.get("JARVIS_DEBUG_DIR", "./data/wake_debug"))# Production default is OFF. The watchdog WAV dump writes ONE WAV file per@@ -82,7 +81,7 @@ _WEDGE_RECOVER_AFTER_FAILS = 2def _save_wav(pcm_bytes: bytes, sample_rate: int, path: Path) -> None:- """Schreibt int16-PCM als gültiges WAV-File."""+ """Writes int16 PCM as a valid WAV file."""path.parent.mkdir(parents=True, exist_ok=True)with wave.open(str(path), "wb") as wf:wf.setnchannels(1)@@ -132,22 +131,22 @@ class RollingWhisperWake:# Either a compiled regex or a WakeMatcher — both expose# ``.search(text)`` returning an object with ``.group(0)``.pattern: Any = DEFAULT_PATTERN,- window_s: float = 1.8, # kürzer = weniger Stille-Anteil = höhere avg-RMS+ window_s: float = 1.8, # shorter = less silence share = higher avg RMS# 2026-06-30 ("~0.5 s delay"): 0.3 -> 0.2 so a spoken custom wake reaches# the bar within one snappier poll. The gates skip silence cheaply, so the# extra polls only transcribe when a window actually passes the audio# gates — negligible extra cost, a visibly faster reaction.poll_interval_s: float = 0.2,- cooldown_s: float = 5.0, # längerer Cooldown → weniger Over-Triggering+ cooldown_s: float = 5.0, # longer cooldown → less over-triggeringsample_rate: int = 16_000,- # 2026-04-22 (3. Iteration): RMS/Peak-Gates zurueck auf niedrig. Die- # Headset-Aussteuerung des Users ist sehr leise (typisch rms 0.01-0.02- # bei normalem Sprechen). Hoehere Gates blockten echtes "Hey Jarvis".- # Schutz gegen Halluzinationen liefert jetzt das Pattern alleine:- # Whisper halluziniert "JARVIS.", "Vielen Dank.", "Thank you" — das- # matched unser Pattern (nur "hey/hi/hallo + jarv-Stamm") nicht.- # Whisper wird dabei etwas oefter aufgerufen (mehr GPU-Last), aber das- # Trigger-Verhalten ist korrekt — genau was der User will.+ # 2026-04-22 (3rd iteration): RMS/peak gates back down to low. The+ # user's headset input level is very quiet (typically rms 0.01-0.02+ # at normal speaking volume). Higher gates blocked genuine "Hey Jarvis".+ # Protection against hallucinations now comes from the pattern alone:+ # Whisper hallucinates "JARVIS.", "Vielen Dank.", "Thank you" — none of # i18n-allow+ # these match our pattern (only "hey/hi/hallo" + the jarv- stem).+ # Whisper does get called a bit more often as a result (more GPU load),+ # but the trigger behavior is correct — exactly what the user wants.min_rms: float = 0.003,# 2026-06-29 (mission "wake only triggers when shouting"): the raw peak# gate runs BEFORE transcription on a quiet mic, so a normal-volume@@ -162,10 +161,10 @@ class RollingWhisperWake:min_peak: float = 0.008,save_debug_wavs: bool = False, # Watchdog-Modus — OFF in prod (env opt-in)heartbeat_interval_s: float = 3.0,- # Peak-Normalization statt fester Gain: misst Audio-Peak, wendet- # dynamisch den Gain an, der nötig ist um auf -3 dBFS zu kommen.- # Ersetzt fehlenden Windows/Hardware-Mic-Boost OHNE Clipping.- # Bei Stille/leisem Rauschen wird der Gain gecappt (max_gain_db).+ # Peak normalization instead of a fixed gain: measures the audio peak,+ # dynamically applies whatever gain is needed to reach -3 dBFS.+ # Substitutes for a missing Windows/hardware mic boost WITHOUT clipping.+ # During silence/quiet noise the gain is capped (max_gain_db).target_peak_dbfs: float = -3.0,max_gain_db: float = 40.0,language: str = "de",@@ -217,14 +216,14 @@ class RollingWhisperWake:self._target_peak = float(10.0 ** (target_peak_dbfs / 20.0)) # -3 dBFS ≈ 0.707self._max_gain_factor = float(10.0 ** (max_gain_db / 20.0)) # 40 dB = 100xself._min_peak = min_peak- # Wake-Transkription auf eine feste Sprache pinnen — auto-detect auf- # 1.8s-Chunks kippt oft fälschlich auf EN (User spricht DE, Whisper- # halluziniert "Thank you"). None = auto (nicht empfohlen).+ # Pin wake transcription to a fixed language — auto-detect on 1.8s+ # chunks often falsely flips to EN (user speaks DE, Whisper+ # hallucinates "Thank you"). None = auto (not recommended).self._language: str | None = languageself._min_wake_confidence = min_wake_confidenceself._max_no_speech_prob = max_no_speech_probself._transcribe_timeout_s = float(transcribe_timeout_s)- # Statistik für Heartbeat+ # Statistics for the heartbeatself._chunks_seen = 0self._total_bytes = 0self._max_rms = 0.0@@ -272,7 +271,7 @@ class RollingWhisperWake:async def detect(self, chunks: AsyncIterator[AudioChunk]) -> AsyncIterator[str]:- """Konsumiert Audio-Chunks, yielded matched-Keyword bei Hit.+ """Consumes audio chunks, yields the matched keyword on a hit.The chunk consumer and the (slow, blocking) Whisper transcription run asTWO concurrent tasks. The consumer keeps the rolling ring-buffer pinned@@ -283,7 +282,7 @@ class RollingWhisperWake:``await transcribe_pcm`` *inside* the consume loop, so while a CPU "base"transcription ran for ~0.5-1 s no new chunks were pulled. They backed upin the upstream fanout queue (observed ``wsp_q=100``) and every following- transcription ran on ~3 s-stale audio — the "riesige Verzoegerung". With+ transcription ran on ~3 s-stale audio — the "huge lag". Withthe consumer decoupled, the buffer is always live and the transcriptionsees the newest window, never a backlog."""@@ -301,14 +300,14 @@ class RollingWhisperWake:buffer.append(samples)buf_len[0] += len(samples)- # Heartbeat-Statistik updaten (live RMS pro Chunk)+ # Update heartbeat statistics (live RMS per chunk)self._chunks_seen += 1self._total_bytes += len(chunk.pcm)chunk_rms = float(np.sqrt(np.mean(samples * samples) + 1e-12))if chunk_rms > self._max_rms:self._max_rms = chunk_rms- # Heartbeat regelmäßig ausgeben — auch wenn Whisper nichts matched+ # Emit the heartbeat regularly — even when Whisper matched nothingnow_hb = time.time()if now_hb - self._last_heartbeat_t >= self._heartbeat_interval_s:dbfs = 20.0 * np.log10(max(self._max_rms, 1e-12))@@ -338,7 +337,7 @@ class RollingWhisperWake:self._max_rms = 0.0self._last_heartbeat_t = now_hb- # Ältere Samples rauswerfen wenn Buffer zu lang+ # Discard older samples when the buffer gets too longwhile buf_len[0] > self._window_samples:oldest = buffer[0]overflow = buf_len[0] - self._window_samples@@ -384,11 +383,11 @@ class RollingWhisperWake:await asyncio.sleep(self._poll_interval_s)now = time.time()- # Cooldown nach letztem Trigger+ # Cooldown after the last triggerif now - last_trigger_t < self._cooldown_s:self._stat_suppressed_cooldown += 1continue- # Noch nicht genug Audio im Buffer+ # Not enough audio in the buffer yetif buf_len[0] < self._sample_rate: # mind. 1 Sekcontinue@@ -404,16 +403,16 @@ class RollingWhisperWake:# evaluation attempt (the denominator for the gate counters).self._stat_windows_polled += 1- # Lautstärke-Check (RMS) — kein Whisper-Call bei Stille+ # Volume check (RMS) — no Whisper call during silencerms = float(np.sqrt(np.mean(audio_np * audio_np) + 1e-12))if rms < self._min_rms:self._stat_gated_rms += 1continue- # Peak-Gate: bei reinem Rauschen gar nicht erst Whisper bemühen+ # Peak gate: don't bother Whisper at all on pure noisepeak = float(np.max(np.abs(audio_np)))if peak < self._min_peak:- # Kein Whisper-Call — zu leise für Sprache. Log the measured+ # No Whisper call — too quiet for speech. Log the measured# peak so "wake stopped working" on a quiet mic is visible as# "your audio peaks below the gate", not silent nothing.self._stat_gated_peak += 1@@ -423,10 +422,10 @@ class RollingWhisperWake:)continue- # Whisper-Call mit Peak-Normalization (dynamischer Gain)+ # Whisper call with peak normalization (dynamic gain)try:if peak > 1e-6:- # Gain berechnen um Ziel-Peak zu erreichen, aber cappen+ # Compute the gain needed to reach the target peak, but cap itgain = min(self._target_peak / peak, self._max_gain_factor)else:gain = 1.0@@ -460,15 +459,15 @@ class RollingWhisperWake:consecutive_fail = 0 # a success clears the wedge streakexcept TimeoutError:log.warning(- "Rolling-Whisper Transkription nach %.1fs abgebrochen "- "(hung STT, %d in Folge) — re-poll, Wake bleibt lebendig",+ "Rolling-Whisper transcription aborted after %.1fs "+ "(hung STT, %d in a row) — re-polling, wake stays alive",self._transcribe_timeout_s,_note_transcribe_fail(),)continueexcept Exception as exc: # noqa: BLE001log.warning(- "Rolling-Whisper Transkription fehlgeschlagen (%d in Folge): %s",+ "Rolling-Whisper transcription failed (%d in a row): %s",_note_transcribe_fail(), exc,)continue@@ -476,7 +475,7 @@ class RollingWhisperWake:text = transcript.text.strip()self._last_transcript = text- # Watchdog: WAV speichern damit User/ich die Aufnahme nachprüfen können+ # Watchdog: save the WAV so the user/I can review the recordingif self._save_debug_wavs:try:pcm_bytes_for_wav = (@@ -487,11 +486,11 @@ class RollingWhisperWake:wav_path = DEBUG_DIR / f"wake_{ts}_rms{rms:.3f}_{safe_text}.wav"_save_wav(pcm_bytes_for_wav, self._sample_rate, wav_path)except Exception as exc: # noqa: BLE001- log.warning("WAV-Save fehlgeschlagen: %s", exc)+ log.warning("WAV save failed: %s", exc)if not text:self._stat_empty += 1- log.info("rolling-whisper: rms=%.4f text=<leer>", rms)+ log.info("rolling-whisper: rms=%.4f text=<empty>", rms)continueif not _reliable_wake_transcript(diff --git a/jarvis/voice/number_speller.py b/jarvis/voice/number_speller.pyindex 2160c138af..5ef321830f 100644--- a/jarvis/voice/number_speller.py+++ b/jarvis/voice/number_speller.py@@ -14,7 +14,7 @@ passes through unchanged instead of crashing the voice path.Locale-aware separators: German/Spanish use a comma decimal and dot thousands("3,8" = three-point-eight, "1.000" = one thousand); English is the reverse.-Times ("20:30") are spoken as "zwanzig Uhr dreißig" before the general pass so+Times ("20:30") are spoken as "zwanzig Uhr dreißig" before the general pass so # i18n-allowthe colon parts are not spelled as two bare integers."""from __future__ import annotationsdiff --git a/scripts/voice_style_eval.py b/scripts/voice_style_eval.pyindex b5294188e9..74ac8efe92 100644--- a/scripts/voice_style_eval.py+++ b/scripts/voice_style_eval.py@@ -78,12 +78,12 @@ class Scenario:SCENARIOS: tuple[Scenario, ...] = (Scenario("01", "greeting", "Guten Morgen, wie geht es dir?", "de"),Scenario("02", "smalltalk", "Ich bin heute echt ein bisschen gestresst.", "de"),- Scenario("03", "opinion-80s", "Was hältst du eigentlich von Musik aus den Achtzigern?", "de"),- Scenario("04", "explain", "Erklär mir mal, warum der Himmel blau ist.", "de"),- Scenario("05", "advice", "Hast du einen Tipp, wie ich morgens besser in die Gänge komme?", "de"),- Scenario("06", "knowledge", "Erzähl mir was Interessantes über den Mond.", "de"),- Scenario("07", "compare", "Was ist der Unterschied zwischen Nebel und Wolken?", "de"),- Scenario("08", "chitchat", "Puh, war ein langer Tag. Womit kennst du dich eigentlich gut aus?", "de"),+ Scenario("03", "opinion-80s", "Was hältst du eigentlich von Musik aus den Achtzigern?", "de"), # i18n-allow+ Scenario("04", "explain", "Erklär mir mal, warum der Himmel blau ist.", "de"), # i18n-allow+ Scenario("05", "advice", "Hast du einen Tipp, wie ich morgens besser in die Gänge komme?", "de"), # i18n-allow+ Scenario("06", "knowledge", "Erzähl mir was Interessantes über den Mond.", "de"), # i18n-allow+ Scenario("07", "compare", "Was ist der Unterschied zwischen Nebel und Wolken?", "de"), # i18n-allow+ Scenario("08", "chitchat", "Puh, war ein langer Tag. Womit kennst du dich eigentlich gut aus?", "de"), # i18n-allowScenario("09", "greeting", "Good morning, how are you doing today?", "en"),Scenario("10", "explain", "Explain to me why the sky is blue.", "en"),Scenario("11", "knowledge", "Tell me something interesting about the moon.", "en"),diff --git a/tests/unit/brain/test_output_filter.py b/tests/unit/brain/test_output_filter.pyindex 037dbedef8..43c7883afd 100644--- a/tests/unit/brain/test_output_filter.py+++ b/tests/unit/brain/test_output_filter.py@@ -1,17 +1,17 @@-"""Tests fuer ``jarvis.brain.output_filter.scrub_for_voice``.--Persona-Mandat Phase 1: Output-Filter am Brain->TTS-Pfad scrubbt Tool-JSON,-Stacktraces, Engineering-Jargon, Self-Reference, Echo-Paraphrase und-Filler-Opener — bevor der Text an die TTS-Synthese geht.--Mandat-Anforderungen an die Tests:-- 5 Positiv-Cases (sauberer Text bleibt unveraendert)-- 5 Schwarzliste-Treffer (jedes Pattern mind. 1x)-- 3 Mixed-Cases (Stacktrace + Markdown + sauberer Text)-- 2 Whitelist-Schutz-Cases (User-Konzept-Worte wie "Datei" duerfen NIE- als Engineering-Jargon scrubbt werden)-- Failure-Mode-6-Test: Echo-Paraphrase NUR Opener-Position (erste 60- Zeichen) — mid-sentence Echo darf NICHT abgeschnitten werden.+"""Tests for ``jarvis.brain.output_filter.scrub_for_voice``.++Persona mandate Phase 1: the output filter on the Brain->TTS path scrubs+tool JSON, stacktraces, engineering jargon, self-reference, echo paraphrase,+and filler openers — before the text goes to TTS synthesis.++Mandate requirements for the tests:+- 5 positive cases (clean text stays unchanged)+- 5 blacklist hits (each pattern at least once)+- 3 mixed cases (stacktrace + markdown + clean text)+- 2 whitelist-protection cases (user-concept words like "Datei" must NEVER+ be scrubbed as engineering jargon)+- Failure-mode-6 test: echo paraphrase ONLY at opener position (first 60+ characters) — a mid-sentence echo must NOT be cut off."""from __future__ import annotations@@ -21,24 +21,24 @@ from jarvis.brain.output_filter import ScrubResult, scrub_for_voice# ----------------------------------------------------------------------------# 5 Positiv-Cases — sauberer Text muss UNVERAENDERT durchgehen.+# 5 positive cases — clean text must pass through UNCHANGED.# ---------------------------------------------------------------------------POSITIVE_CASES = [- pytest.param("Halb drei.", id="terse-fact"),+ pytest.param("Halb drei.", id="terse-fact"), # i18n-allowpytest.param(- "Die Datei deklariert vier Brain-Provider und enthält den Voice-Stack-Block.",+ "Die Datei deklariert vier Brain-Provider und enthält den Voice-Stack-Block.", # i18n-allowid="file-summary",),- pytest.param("Soll ich den Termin verschieben?", id="shall-i-question"),- pytest.param("Es ist warm draussen.", id="weather-fact"),+ pytest.param("Soll ich den Termin verschieben?", id="shall-i-question"), # i18n-allow+ pytest.param("Es ist warm draussen.", id="weather-fact"), # i18n-allowpytest.param("Goodbye, Ruben.", id="hangup-contract"),]@pytest.mark.parametrize("text", POSITIVE_CASES)def test_clean_text_passes_through_unchanged(text: str) -> None:- """Sauberer Text wird nicht modifiziert, kein fallback_used."""+ """Clean text is not modified, no fallback_used."""result = scrub_for_voice(text)assert isinstance(result, ScrubResult)assert result.cleaned == text@@ -47,25 +47,25 @@ def test_clean_text_passes_through_unchanged(text: str) -> None:# ----------------------------------------------------------------------------# 5 Schwarzliste-Treffer — jedes Pattern mind. einmal.+# 5 blacklist hits — each pattern at least once.# ---------------------------------------------------------------------------def test_tool_json_is_removed() -> None:- """Tool-Call-JSON in der Mitte des Texts wird komplett rausgeschnitten."""- text = 'Sub-Jarvis startet: spawn_worker({"utterance": "test"}) — bitte warten.'+ """Tool-call JSON in the middle of the text is cut out entirely."""+ text = 'Sub-Jarvis startet: spawn_worker({"utterance": "test"}) — bitte warten.' # i18n-allowresult = scrub_for_voice(text)assert '{"utterance"' not in result.cleanedassert "spawn_worker(" not in result.cleanedassert "removed_tool_json" in result.actions or "removed_tool_call" in result.actions- # Resttext sollte erhalten sein- assert "bitte warten" in result.cleaned.lower()+ # The remaining text should be preserved+ assert "bitte warten" in result.cleaned.lower() # i18n-allowdef test_tool_call_python_keyword_args_is_removed() -> None:- """Python-style keyword-args (``tool(key='val', ...)``) — Probe-Drift 03."""+ """Python-style keyword-args (``tool(key='val', ...)``) — probe drift 03."""text = (- "spawn_worker(utterance='Wie kann ich das beschleunigen?', "+ "spawn_worker(utterance='Wie kann ich das beschleunigen?', " # i18n-allow"context_hints=['x', 'y'], action='analyze', target='')")result = scrub_for_voice(text)@@ -75,29 +75,29 @@ def test_tool_call_python_keyword_args_is_removed() -> None:def test_tool_xml_tags_are_removed() -> None:- """XML-Tool-Tags inkl. Inner-Content — Probe-Drift 12."""+ """XML tool tags including inner content — probe drift 12."""text = (- "Ich delegiere das. <spawn_worker> <utterance>Lies die Datei</utterance>"- " <action>x</action> </spawn_worker> Fertig."+ "Ich delegiere das. <spawn_worker> <utterance>Lies die Datei</utterance>" # i18n-allow+ " <action>x</action> </spawn_worker> Fertig." # i18n-allow)result = scrub_for_voice(text)assert "<spawn_worker" not in result.cleanedassert "<utterance>" not in result.cleanedassert "removed_tool_json" in result.actions- # Resttext bleibt- assert "Fertig" in result.cleaned+ # The remaining text stays+ assert "Fertig" in result.cleaned # i18n-allowdef test_tool_kw_pattern_does_not_break_harmless_python() -> None:- """Harmlose Python-Beispiele (``print(x=1)``) duerfen NICHT zerschossen werden.+ """Harmless Python examples (``print(x=1)``) must NOT be destroyed.- TOOL_CALL_KW_RE ist tool-name-spezifisch — nur bekannte Tool-Namen- matchen, nicht jeder ``\\w+(...)``-Aufruf.+ TOOL_CALL_KW_RE is tool-name-specific — only known tool names+ match, not every ``\\w+(...)`` call."""text = "Use print(x=1) to debug."result = scrub_for_voice(text)- # 'print' ist nicht in TOOL_NAMES — der Aufruf bleibt erhalten (die Ziffer- # wird nur fuer die Sprachausgabe ausgeschrieben: "print(x=eins)").+ # 'print' is not in TOOL_NAMES — the call is preserved (the digit is only+ # spelled out for speech output: "print(x=eins)").assert "print(x=" in result.cleanedassert "debug" in result.cleaned@@ -105,7 +105,7 @@ def test_tool_kw_pattern_does_not_break_harmless_python() -> None:def test_stacktrace_is_replaced_with_fallback_phrase() -> None:"""Stacktrace -> 'Es trat ein Fehler auf.' + fallback_used=True."""text = (- "Hier der Fehler:\n"+ "Hier der Fehler:\n" # i18n-allow'Traceback (most recent call last):\n'' File "/x/y.py", line 42, in run\n'" raise ValueError('boom')\n"@@ -115,34 +115,34 @@ def test_stacktrace_is_replaced_with_fallback_phrase() -> None:assert "Traceback" not in result.cleanedassert 'File "' not in result.cleanedassert "ValueError" not in result.cleaned- assert "Es trat ein Fehler auf" in result.cleaned+ assert "Es trat ein Fehler auf" in result.cleaned # i18n-allowassert result.fallback_used is Trueassert "replaced_stacktrace" in result.actionsdef test_markdown_is_stripped() -> None:- """Markdown-Reste (``**``, ``##``, code-fences, list-bullets) werden entfernt."""- text = "## Bericht\n\n**Wichtig:** Die Datei ist da.\n\n- Punkt eins\n- Punkt zwei"+ """Leftover markdown (``**``, ``##``, code fences, list bullets) is removed."""+ text = "## Bericht\n\n**Wichtig:** Die Datei ist da.\n\n- Punkt eins\n- Punkt zwei" # i18n-allowresult = scrub_for_voice(text)assert "**" not in result.cleanedassert "##" not in result.cleaned- assert "- Punkt" not in result.cleaned- # Inhalt bleibt — nur das Markup ist weg- assert "Wichtig" in result.cleaned- assert "Datei" in result.cleaned+ assert "- Punkt" not in result.cleaned # i18n-allow+ # Content remains — only the markup is gone+ assert "Wichtig" in result.cleaned # i18n-allow+ assert "Datei" in result.cleaned # i18n-allowassert "stripped_markdown" in result.actionsdef test_self_reference_is_removed() -> None:- """``Als KI`` / ``Ich bin nur ein Sprachmodell`` werden gescrubbt."""- text = "Als KI kann ich das natuerlich pruefen. Halb drei."+ """``Als KI`` / ``Ich bin nur ein Sprachmodell`` are scrubbed."""+ text = "Als KI kann ich das natuerlich pruefen. Halb drei." # i18n-allowresult = scrub_for_voice(text)low = result.cleaned.lower()- assert "als ki" not in low- assert "als sprachmodell" not in low- assert "ich bin nur" not in low- # Kerninhalt bleibt- assert "halb drei" in low+ assert "als ki" not in low # i18n-allow+ assert "als sprachmodell" not in low # i18n-allow+ assert "ich bin nur" not in low # i18n-allow+ # Core content remains+ assert "halb drei" in low # i18n-allowassert "removed_self_reference" in result.actions@@ -151,11 +151,11 @@ def test_self_reference_is_removed() -> None:[# The maintainer never wants Jarvis to SAY it is noting / reviewing the# last transcription — it happens silently in the background.- ("Verstanden. Ich notiere mir das. Das Wetter ist sonnig.", "de",+ ("Verstanden. Ich notiere mir das. Das Wetter ist sonnig.", "de", # i18n-allow"notiere", "sonnig"),- ("Ich schaue mir die letzte Transkription an. Die Hauptstadt ist Rom.",+ ("Ich schaue mir die letzte Transkription an. Die Hauptstadt ist Rom.", # i18n-allow"de", "transkription", "rom"),- ("Ich merke mir das. Hier ist die Antwort.", "de", "merke mir", "antwort"),+ ("Ich merke mir das. Hier ist die Antwort.", "de", "merke mir", "antwort"), # i18n-allow("Got it. I am noting that down. The capital is Rome.", "en","noting", "rome"),("Sure. Let me look at the last transcription. It is 25 degrees.", "en",@@ -179,9 +179,9 @@ def test_background_action_narration_is_removed([# Must NOT be stripped: content lead-ins + legit save/check confirmations.("Looking at the data, the answer is 42.", "en"),- ("Ich schaue gleich nach dem Wetter und melde mich.", "de"),+ ("Ich schaue gleich nach dem Wetter und melde mich.", "de"), # i18n-allow("I'm saving the file now.", "en"),- ("Die Datei ist gespeichert.", "de"),+ ("Die Datei ist gespeichert.", "de"), # i18n-allow("I will check the weather for you.", "en"),],)@@ -194,47 +194,47 @@ def test_background_action_narration_no_false_positive(def test_echo_paraphrase_in_opener_is_cut() -> None:- """Echo-Paraphrase am Satzanfang wird abgeschnitten — Antwort ist die Substanz."""- text = "Du möchtest also wissen, wie spät es ist. Halb drei."+ """Echo paraphrase at the start of the sentence is cut off — the answer is the substance."""+ text = "Du möchtest also wissen, wie spät es ist. Halb drei." # i18n-allowresult = scrub_for_voice(text)low = result.cleaned.lower()- assert "du möchtest also" not in low- assert "halb drei" in low+ assert "du möchtest also" not in low # i18n-allow+ assert "halb drei" in low # i18n-allowassert "rephrased_echo" in result.actionsdef test_filler_opener_is_removed() -> None:- """``Großartige Frage`` / ``Tolle Frage`` als Opener werden entfernt."""- text = "Großartige Frage! Es ist halb drei."+ """``Großartige Frage`` / ``Tolle Frage`` as an opener are removed."""+ text = "Großartige Frage! Es ist halb drei." # i18n-allowresult = scrub_for_voice(text)low = result.cleaned.lower()- assert "großartige frage" not in low+ assert "großartige frage" not in low # i18n-allowassert "grossartige frage" not in low- assert "halb drei" in low+ assert "halb drei" in low # i18n-allowassert "removed_filler_opener" in result.actionsdef test_engineering_jargon_is_removed() -> None:- """``MCP``/``Subprocess``/``Provider`` als Standalone-Worte werden gescrubbt."""- text = "Der Subprocess wurde via MCP-Provider gestartet."+ """``MCP``/``Subprocess``/``Provider`` as standalone words are scrubbed."""+ text = "Der Subprocess wurde via MCP-Provider gestartet." # i18n-allowresult = scrub_for_voice(text)low = result.cleaned.lower()- # Substanz-Worte verschwinden ODER werden umschrieben — wichtig ist:- # keines der drei Jargon-Worte als Standalone-Wort verbleibt.- assert "mcp" not in low.split() # nicht als Wort+ # The substance words either disappear or get rephrased — what matters is+ # that none of the three jargon words remains as a standalone word.+ assert "mcp" not in low.split() # not as a wordassert "subprocess" not in lowassert "removed_engineering_jargon" in result.actions# ----------------------------------------------------------------------------# 3 Mixed-Cases — mehrere Patterns gleichzeitig.+# 3 mixed cases — several patterns at once.# ---------------------------------------------------------------------------def test_mixed_stacktrace_with_markdown() -> None:- """Stacktrace + Markdown -> Stacktrace gewinnt (fallback_used=True)."""+ """Stacktrace + markdown -> stacktrace wins (fallback_used=True)."""text = (- "## Fehler\n\n"+ "## Fehler\n\n" # i18n-allow"**Detail:** Traceback (most recent call last):\n"' File "/x/y.py", line 1, in <module>\n'" raise RuntimeError('x')"@@ -247,76 +247,76 @@ def test_mixed_stacktrace_with_markdown() -> None:def test_mixed_tool_json_with_clean_text() -> None:- """Tool-JSON mid-sentence + sauberer Text -> Tool-JSON raus, Text bleibt."""- text = 'Bitte: dispatch_to_admin({"op": "shutdown"}) ist nicht erlaubt.'+ """Tool JSON mid-sentence + clean text -> tool JSON gone, text stays."""+ text = 'Bitte: dispatch_to_admin({"op": "shutdown"}) ist nicht erlaubt.' # i18n-allowresult = scrub_for_voice(text)assert "dispatch_to_admin" not in result.cleanedassert "{\"op\"" not in result.cleaned- assert "ist nicht erlaubt" in result.cleaned.lower()+ assert "ist nicht erlaubt" in result.cleaned.lower() # i18n-allowdef test_mixed_filler_with_clean_rest() -> None:- """Filler-Opener + saubere Antwort -> Filler raus, Rest bleibt unveraendert.+ """Filler opener + clean answer -> filler gone, rest stays unchanged.- Bewusst keine Jargon-Worte (Provider/Subprocess/MCP/Harness) im Resttext,- damit der Test nur die Filler-Entfernung isoliert prueft. Compounds wie- "Brain-Modelle" sind durch das Bindestrich-Lookbehind in JARGON_RE- ohnehin geschuetzt.+ Deliberately no jargon words (Provider/Subprocess/MCP/Harness) in the+ remaining text, so the test isolates only the filler removal. Compounds+ like "Brain-Modelle" are already protected by the hyphen lookbehind in+ JARGON_RE."""- text = "Tolle Frage! Die Datei jarvis.toml hat vier Brain-Modelle."+ text = "Tolle Frage! Die Datei jarvis.toml hat vier Brain-Modelle." # i18n-allowresult = scrub_for_voice(text)- assert "Tolle Frage" not in result.cleaned- # User-Konzept-Worte (Datei) duerfen NICHT verschwinden- assert "Datei" in result.cleaned+ assert "Tolle Frage" not in result.cleaned # i18n-allow+ # User-concept words (Datei) must NOT disappear+ assert "Datei" in result.cleaned # i18n-allowassert "jarvis.toml" in result.cleaned- assert "vier Brain-Modelle" in result.cleaned+ assert "vier Brain-Modelle" in result.cleaned # i18n-allow# ----------------------------------------------------------------------------# 2 Whitelist-Schutz-Cases — User-Konzept-Worte sind heilig.+# 2 whitelist-protection cases — user-concept words are sacred.# ---------------------------------------------------------------------------def test_whitelist_datei_is_protected() -> None:- """``Datei`` wird NIE gescrubbt, auch nicht als Jargon-Lookalike."""- text = "Die Datei wurde gespeichert."+ """``Datei`` is NEVER scrubbed, not even as a jargon lookalike."""+ text = "Die Datei wurde gespeichert." # i18n-allowresult = scrub_for_voice(text)assert result.cleaned == textassert result.actions == []def test_whitelist_user_concepts_protected() -> None:- """``Browser``/``Email``/``Terminal``/``Notiz``/``Termin``/``Kalender`` bleiben."""- text = "Browser geöffnet, Email versendet, Termin im Kalender eingetragen, Notiz im Terminal gespeichert."+ """``Browser``/``Email``/``Terminal``/``Notiz``/``Termin``/``Kalender`` stay."""+ text = "Browser geöffnet, Email versendet, Termin im Kalender eingetragen, Notiz im Terminal gespeichert." # i18n-allowresult = scrub_for_voice(text)for concept in ("Browser", "Email", "Termin", "Kalender", "Notiz", "Terminal"):- assert concept in result.cleaned, f"Whitelist-Wort {concept!r} wurde gescrubbt"+ assert concept in result.cleaned, f"Whitelist word {concept!r} was scrubbed"# ----------------------------------------------------------------------------# Failure-Mode-6-Test: Echo-Paraphrase NUR Opener-Position.+# Failure-mode-6 test: echo paraphrase ONLY at opener position.# ---------------------------------------------------------------------------def test_echo_paraphrase_mid_sentence_is_kept() -> None:- """Mid-sentence Echo-Pattern (nach 60 Zeichen) DARF NICHT gescrubbt werden.+ """A mid-sentence echo pattern (after 60 characters) must NOT be scrubbed.- Mandat-Failure-Mode 6: Manchmal will der User wirklich eine Bestaetigung- im Echo-Stil ('Du moechtest also den Termin verschieben? Ja oder nein?').- Filter NUR auf Opener-Position (erste 60 Zeichen) anwenden.+ Mandate failure-mode 6: sometimes the user genuinely wants a confirmation+ in echo style ('Du moechtest also den Termin verschieben? Ja oder nein?'). # i18n-allow+ Apply the filter ONLY at opener position (first 60 characters)."""- # Echo-Pattern in der Mitte (nach >60 Zeichen sauberen Texts)+ # Echo pattern in the middle (after >60 characters of clean text)text = (- "Ich habe den Termin am Freitag im Kalender und einen Konflikt erkannt. "- "Du möchtest also den Termin verschieben? Ja oder nein?"+ "Ich habe den Termin am Freitag im Kalender und einen Konflikt erkannt. " # i18n-allow+ "Du möchtest also den Termin verschieben? Ja oder nein?" # i18n-allow)- # Sicherheitscheck: Echo-Pattern liegt nach Position 60- echo_pos = text.lower().find("du möchtest also")- assert echo_pos > 60, f"Test-Setup-Bug: Echo-Pattern bei Position {echo_pos}"+ # Sanity check: the echo pattern sits after position 60+ echo_pos = text.lower().find("du möchtest also") # i18n-allow+ assert echo_pos > 60, f"Test setup bug: echo pattern at position {echo_pos}"result = scrub_for_voice(text)- # Mid-sentence Echo bleibt erhalten- assert "möchtest also" in result.cleaned.lower()+ # Mid-sentence echo is preserved+ assert "möchtest also" in result.cleaned.lower() # i18n-allowassert "rephrased_echo" not in result.actions@@ -335,10 +335,10 @@ def test_em_dash_becomes_comma() -> None:def test_en_dash_becomes_comma() -> None:- text = "Alles bereit – wir können sofort loslegen."+ text = "Alles bereit – wir können sofort loslegen." # i18n-allowresult = scrub_for_voice(text)assert "–" not in result.cleaned- assert "Alles bereit, wir können" in result.cleaned+ assert "Alles bereit, wir können" in result.cleaned # i18n-allowdef test_hyphen_compound_survives_em_dash_filter() -> None:@@ -360,30 +360,30 @@ def test_ascii_double_hyphen_dash_aside_becomes_comma() -> None:same hard TTS pause as an em dash — collapse it to a comma too. TheUnicode-only scrub missed it, and several canned phrases / LLM outputs use' -- ' (live forensic 2026-06-30)."""- result = scrub_for_voice("Mach ich -- ich sage Bescheid, sobald es fertig ist.")+ result = scrub_for_voice("Mach ich -- ich sage Bescheid, sobald es fertig ist.") # i18n-allowassert "--" not in result.cleaned- assert "Mach ich, ich sage Bescheid" in result.cleaned+ assert "Mach ich, ich sage Bescheid" in result.cleaned # i18n-allowdef test_ascii_hyphen_compound_and_range_survive_double_hyphen_filter() -> None:"""No false positive: a compound ('T-Shirt') or numeric range ('20-30') hasno surrounding spaces and must survive the double-hyphen scrub. The rangeendpoints are spelled out for speech, but the joining hyphen is preserved."""- result = scrub_for_voice("Dein T-Shirt kostet 20-30 Euro.")+ result = scrub_for_voice("Dein T-Shirt kostet 20-30 Euro.") # i18n-allowassert "T-Shirt" in result.cleaned- assert "zwanzig-dreißig" in result.cleaned+ assert "zwanzig-dreißig" in result.cleaned # i18n-allowdef test_fallback_used_true_only_for_stacktrace() -> None:- """``fallback_used`` nur ``True`` wenn der gesamte Text durch Standard-- Phrase ersetzt wurde (Stacktrace), nicht bei Teil-Scrub."""- # Ein Filler-Opener entfernt nur einen Teil — kein Fallback- result = scrub_for_voice("Großartige Frage! Halb drei.")+ """``fallback_used`` is only ``True`` when the whole text was replaced by+ the standard phrase (stacktrace), not for a partial scrub."""+ # A filler opener only removes part of the text — no fallback+ result = scrub_for_voice("Großartige Frage! Halb drei.") # i18n-allowassert result.fallback_used is Falsedef test_empty_input_returns_empty() -> None:- """Leerer Input -> leeres Output, keine Exception."""+ """Empty input -> empty output, no exception."""result = scrub_for_voice("")assert result.cleaned == ""assert result.actions == []@@ -391,91 +391,91 @@ def test_empty_input_returns_empty() -> None:# ----------------------------------------------------------------------------# Phase-1-Erweiterungen aus Research-Report 2026-04-28 Sektion 1.3.+# Phase 1 extensions from research report 2026-04-28 section 1.3.#-# Vier neue Drift-Klassen, die die ursprueeglich Mandat-Phase-1-Schwarzliste-# nicht abdeckte aber genau in den Filter-Scope passen:+# Four new drift classes that the original Phase-1-mandate blacklist did not+# cover but that fit squarely into the filter's scope:#-# 1. A1 "Sir"-Anrede (Szenarien 03/07 der Probe vom 2026-04-28).-# 2. "Sub-Agent"/"Supervisor-Agent" als Engineering-Reveal.-# 3. Tool-Args-Body-Leak in YAML-/key:value-Form.-# 4. Post-Scrub-Muell (z.B. einzelnes `}`) -> fallback_used=True.+# 1. A1 "Sir" salutation (scenarios 03/07 of the 2026-04-28 rehearsal).+# 2. "Sub-Agent"/"Supervisor-Agent" as an engineering reveal.+# 3. Tool-args body leak in YAML-/key:value form.+# 4. Post-scrub residue (e.g. a lone `}`) -> fallback_used=True.# ----------------------------------------------------------------------------def test_sir_anrede_is_removed() -> None:- """A1: 'Sir' als Anrede wird gescrubbt — Mandat A1 (Ruben statt Sir)."""- text = "Sir, ich starte die Analyse."+def test_sir_anrede_is_removed() -> None: # i18n-allow+ """A1: 'Sir' as a salutation is scrubbed — mandate A1 (Ruben instead of Sir)."""+ text = "Sir, ich starte die Analyse." # i18n-allowresult = scrub_for_voice(text)low = result.cleaned.lower()- assert "sir" not in low.split(",")[0].split() # nicht als Wort im Opener+ assert "sir" not in low.split(",")[0].split() # not as a word in the openerassert "sir" not in low- assert "ich starte die analyse" in low- assert "removed_anrede_drift" in result.actions+ assert "ich starte die analyse" in low # i18n-allow+ assert "removed_anrede_drift" in result.actions # i18n-allow-def test_sir_anrede_mid_sentence_is_removed() -> None:- """A1: 'Sir' auch mitten im Satz (nach Komma) wird entfernt."""- text = "Erledigt, Sir. Die Datei ist gespeichert."+def test_sir_anrede_mid_sentence_is_removed() -> None: # i18n-allow+ """A1: 'Sir' is also removed in the middle of a sentence (after a comma)."""+ text = "Erledigt, Sir. Die Datei ist gespeichert." # i18n-allowresult = scrub_for_voice(text)assert "Sir" not in result.cleaned- assert "Datei" in result.cleaned- assert "removed_anrede_drift" in result.actions+ assert "Datei" in result.cleaned # i18n-allow+ assert "removed_anrede_drift" in result.actions # i18n-allowdef test_legitimate_sir_in_quote_is_kept() -> None:- """Innerhalb von Anfuehrungszeichen bleibt 'Sir' erhalten (Zitat-Schutz).+ """Inside quotation marks, 'Sir' is preserved (quote protection).- Wenn der User Jarvis bittet, einen Songtext oder ein Zitat vorzulesen, in- dem 'Sir' vorkommt, soll der Filter das nicht zerschiessen. Heuristik:- 'Sir' direkt in Quotes wird nicht gescrubbt.+ If the user asks Jarvis to read out a song lyric or quote that contains+ 'Sir', the filter must not destroy it. Heuristic: 'Sir' directly inside+ quotes is not scrubbed."""- text = 'Im Lied steht: "Yes, Sir, I can boogie." — kennst du das?'+ text = 'Im Lied steht: "Yes, Sir, I can boogie." — kennst du das?' # i18n-allowresult = scrub_for_voice(text)- assert "Sir" in result.cleaned, "Sir in Quote wurde faelschlich gescrubbt"+ assert "Sir" in result.cleaned, "Sir inside the quote was scrubbed by mistake"def test_sub_agent_jargon_is_removed() -> None:- """'Sub-Agent' als Engineering-Reveal wird entfernt — Probe-Drift 03/07."""- text = "Ich starte einen Sub-Agent, der die Datei analysiert."+ """'Sub-Agent' as an engineering reveal is removed — probe drift 03/07."""+ text = "Ich starte einen Sub-Agent, der die Datei analysiert." # i18n-allowresult = scrub_for_voice(text)assert "Sub-Agent" not in result.cleanedassert "sub-agent" not in result.cleaned.lower()- # Kerninhalt bleibt- assert "analysiert" in result.cleaned.lower()+ # Core content remains+ assert "analysiert" in result.cleaned.lower() # i18n-allowassert "removed_engineering_jargon" in result.actionsdef test_supervisor_agent_jargon_is_removed() -> None:- """'Supervisor-Agent' als Engineering-Reveal wird entfernt — Probe-Drift 13."""- text = "Dein persoenlicher Supervisor-Agent erledigt das."+ """'Supervisor-Agent' as an engineering reveal is removed — probe drift 13."""+ text = "Dein persoenlicher Supervisor-Agent erledigt das." # i18n-allowresult = scrub_for_voice(text)assert "Supervisor-Agent" not in result.cleanedassert "supervisor-agent" not in result.cleaned.lower()- assert "erledigt" in result.cleaned.lower()+ assert "erledigt" in result.cleaned.lower() # i18n-allowassert "removed_engineering_jargon" in result.actionsdef test_tool_args_yaml_block_is_removed() -> None:- """Tool-Args-Body-Leak als YAML/key:value-Block — Probe-Drift 03 Body.+ """Tool-args body leak as a YAML/key:value block — probe drift 03 body.- Die Probe vom 2026-04-28 hat in Szenario 03 den vollstaendigen- Sub-Jarvis-Tool-Aufruf-Body durchgeleakt:+ The 2026-04-28 rehearsal leaked the full Sub-Jarvis tool-call body in+ scenario 03:utterance: "Wie kann ich das beschleunigen?"context_hints:- Unklar ...- Benoetigt Kontext ...action: "die Beschleunigung ..."target: ""- Diese YAML-aehnliche Form ist von TOOL_JSON_RE nicht gefangen.+ This YAML-like form is not caught by TOOL_JSON_RE."""text = (- "Ich starte die Analyse.\n"- '"Wie kann ich das beschleunigen?"\n'+ "Ich starte die Analyse.\n" # i18n-allow+ '"Wie kann ich das beschleunigen?"\n' # i18n-allow"context_hints:\n"- "Unklar, was beschleunigt werden soll.\n"- "Benoetigt Kontext zur aktuellen Aufgabe oder zum System.\n"- 'action: "die Beschleunigung einer unklaren Aufgabe analysiert"\n'+ "Unklar, was beschleunigt werden soll.\n" # i18n-allow+ "Benoetigt Kontext zur aktuellen Aufgabe oder zum System.\n" # i18n-allow+ 'action: "die Beschleunigung einer unklaren Aufgabe analysiert"\n' # i18n-allow'target: ""')result = scrub_for_voice(text)@@ -483,57 +483,57 @@ def test_tool_args_yaml_block_is_removed() -> None:assert "action:" not in result.cleanedassert "target:" not in result.cleanedassert "removed_tool_json" in result.actions- # Der Resttext ('Ich starte die Analyse.') bleibt erhalten+ # The remaining text ('Ich starte die Analyse.') is preserved # i18n-allowassert "Analyse" in result.cleaneddef test_post_scrub_residue_triggers_fallback() -> None:- """Wenn nach allen Scrubs nur Muell uebrig bleibt -> fallback_used=True.+ """When only residue is left after all scrubs -> fallback_used=True.- Probe-Drift 12: Tool-Filter zerschoss alles bis auf '}', das geht- unkommentiert an TTS und der User hoert quasi nichts. Wenn der- gefilterte Text weniger als 3 alphanumerische Chars enthaelt,- soll der Filter auf die Standard-Fehler-Phrase zurueckfallen.+ Probe drift 12: the tool filter destroyed everything down to a lone '}',+ which went to TTS uncommented and the user heard essentially nothing. If+ the filtered text contains fewer than 3 alphanumeric chars, the filter+ must fall back to the standard error phrase."""- # Nur ein '}' uebrig — mehr nicht+ # Only a '}' remains — nothing elsetext = '<spawn_worker>{"utterance": "test"}</spawn_worker>}'result = scrub_for_voice(text)- # Entweder fallback_used=True ODER cleaned ist leer (beides akzeptabel)+ # Either fallback_used=True OR cleaned is empty (both acceptable)assert (result.fallback_used and result.cleaned), (- f"Post-Scrub-Muell {result.cleaned!r} wurde nicht durch Fallback ersetzt"+ f"Post-scrub residue {result.cleaned!r} was not replaced by the fallback")- assert "Es trat ein Fehler auf" in result.cleaned or result.cleaned.strip() == ""+ assert "Es trat ein Fehler auf" in result.cleaned or result.cleaned.strip() == "" # i18n-allowdef test_post_scrub_meaningful_text_no_fallback() -> None:- """Defense gegen den Fallback-Trigger: substanzieller Resttext loest KEIN- fallback_used aus."""- text = "Erledigt. Die Datei ist da."+ """Defense against the fallback trigger: substantial remaining text does+ NOT trigger fallback_used."""+ text = "Erledigt. Die Datei ist da." # i18n-allowresult = scrub_for_voice(text)assert result.fallback_used is False- assert "Datei" in result.cleaned+ assert "Datei" in result.cleaned # i18n-allow# ----------------------------------------------------------------------------# Phase-1-Erweiterung 2 (2026-04-28 spaeter):-# Anthropic-Internal-Tag-Drifts aus der Re-Probe — Brain leakt:+# Phase 1 extension 2 (2026-04-28, later):+# Anthropic-internal tag drifts from the re-rehearsal — the brain leaks:# 1. ``<function_calls>...<invoke name="...">...</invoke></function_calls>``-# 2. Generische ``<tool_call>...</tool_call>`` / ``<tool_response>...</tool_response>``-# 3. Base64-Image-Strings als Body-Leak+# 2. Generic ``<tool_call>...</tool_call>`` / ``<tool_response>...</tool_response>``+# 3. Base64 image strings as a body leak# ---------------------------------------------------------------------------def test_anthropic_function_calls_block_is_removed() -> None:- """Anthropic-internes ``<function_calls><invoke name='...'>``-Format —- Re-Probe-Drift Szenario 12 vom 2026-04-28."""+ """Anthropic-internal ``<function_calls><invoke name='...'>`` format —+ re-rehearsal drift scenario 12 from 2026-04-28."""text = (- 'Hier: <function_calls>\n'+ 'Hier: <function_calls>\n' # i18n-allow'<invoke name="spawn_worker">\n'- '<parameter name="utterance">Lies die Datei</parameter>\n'+ '<parameter name="utterance">Lies die Datei</parameter>\n' # i18n-allow'<parameter name="action">x</parameter>\n''</invoke>\n''</function_calls>\n'- 'Fertig.'+ 'Fertig.' # i18n-allow)result = scrub_for_voice(text)assert "<function_calls>" not in result.cleaned@@ -541,21 +541,21 @@ def test_anthropic_function_calls_block_is_removed() -> None:assert "<parameter" not in result.cleanedassert "spawn_worker" not in result.cleanedassert "removed_tool_json" in result.actions- assert "Hier:" in result.cleaned- assert "Fertig" in result.cleaned+ assert "Hier:" in result.cleaned # i18n-allow+ assert "Fertig" in result.cleaned # i18n-allowdef test_generic_tool_call_tags_are_removed() -> None:- """``<tool_call>{}</tool_call>`` mit irgendwelchem Content — Re-Probe+ """``<tool_call>{}</tool_call>`` with arbitrary content — re-rehearsal01/06/11."""text = (- 'Lass mich schauen. <tool_call>\n'+ 'Lass mich schauen. <tool_call>\n' # i18n-allow'}\n''</tool_call>\n''<tool_response>\n''{"status": "ok"}\n''</tool_response>\n'- '09:17 Uhr.'+ '09:17 Uhr.' # i18n-allow)result = scrub_for_voice(text)assert "<tool_call>" not in result.cleaned@@ -563,110 +563,112 @@ def test_generic_tool_call_tags_are_removed() -> None:assert "<tool_response>" not in result.cleanedassert "</tool_response>" not in result.cleanedassert "removed_tool_json" in result.actions- # Kerninhalt bleibt (die Uhrzeit wird fuer die Sprachausgabe ausgeschrieben)- assert "neun Uhr siebzehn" in result.cleaned+ # Core content remains (the clock time is spelled out for speech output)+ assert "neun Uhr siebzehn" in result.cleaned # i18n-allowdef test_base64_image_block_is_removed() -> None:- """Base64-Image-String (sehr lange ASCII-Sequenz) — Re-Probe 08."""- # Realistischer Trigger: data-URI mit langer Base64-Sequenz+ """Base64 image string (very long ASCII sequence) — re-rehearsal 08."""+ # Realistic trigger: data URI with a long base64 sequencetext = (- 'Hier das Bild: data:image/webp;base64,'+ 'Hier das Bild: data:image/webp;base64,' # i18n-allow+ 'A' * 800- + '. Fertig.'+ + '. Fertig.' # i18n-allow)result = scrub_for_voice(text)- # Base64-Block ist weg- assert ("A" * 200) not in result.cleaned, "Lange Base64-Sequenz nicht entfernt"+ # The base64 block is gone+ assert ("A" * 200) not in result.cleaned, "Long base64 sequence not removed"assert "data:image" not in result.cleanedassert "removed_tool_json" in result.actions- assert "Fertig" in result.cleaned+ assert "Fertig" in result.cleaned # i18n-allowdef test_short_clean_alphanumeric_is_kept() -> None:- """Defense gegen Base64-False-Positive: kurze alphanumerische Strings- (z.B. Datei-Namen, Hashes, Tokens in normaler Kommunikation) bleiben."""- text = "Die Datei abc123def456 wurde gespeichert."+ """Defense against base64 false positives: short alphanumeric strings+ (e.g. file names, hashes, tokens in ordinary communication) stay."""+ text = "Die Datei abc123def456 wurde gespeichert." # i18n-allowresult = scrub_for_voice(text)assert "abc123def456" in result.cleanedassert result.actions == []# ----------------------------------------------------------------------------# Phase-2-Anti-Pattern-Filter — die in voice_e2e_probe.py:ANTI_PATTERNS-# gelisteten Strings sollen vom Filter VOR der Probe-Heuristik gescrubbt-# werden, nicht nur als Probe-Detection-Pattern dienen. Sonst zaehlt jeder-# Brain-Output mit Anti-Pattern als DRIFT, obwohl der User es nie hoert.+# Phase 2 anti-pattern filter — the strings listed in+# voice_e2e_probe.py:ANTI_PATTERNS are meant to be scrubbed by the filter+# BEFORE the rehearsal heuristic runs, not merely serve as a rehearsal+# detection pattern. Otherwise every brain output containing an anti-pattern+# counts as DRIFT even though the user never hears it.# ---------------------------------------------------------------------------@pytest.mark.parametrize("opener,rest", [- ("Lass mich kurz", "schauen. Ja, gespeichert."),- ("Lass mich kurz", "checken. Halb drei."),+ ("Lass mich kurz", "schauen. Ja, gespeichert."), # i18n-allow+ ("Lass mich kurz", "checken. Halb drei."), # i18n-allow("Let me think,", "the answer is 42."),- ("Let me think.", "It's halb drei."),+ ("Let me think.", "It's halb drei."), # i18n-allow])-def test_filler_selbstreferenz_opener_is_removed(opener: str, rest: str) -> None:- """Phase-2-Anti-Pattern: 'Lass mich kurz' / 'Let me think' als Opener.+def test_filler_selbstreferenz_opener_is_removed(opener: str, rest: str) -> None: # i18n-allow+ """Phase 2 anti-pattern: 'Lass mich kurz' / 'Let me think' as an opener.- Diese Phrasen sind in voice_e2e_probe.py:ANTI_PATTERNS unter- 'Filler-Selbstreferenz' gelistet. Der Filter muss sie wegschneiden,- sonst loest die Probe-Heuristik einen DRIFT-Treffer aus, obwohl der- User die Phrase ohnehin nicht hoeren soll.+ These phrases are listed in voice_e2e_probe.py:ANTI_PATTERNS under+ 'Filler-Selbstreferenz' (filler self-reference). The filter must cut # i18n-allow+ them out, otherwise the rehearsal heuristic fires a DRIFT hit even though+ the user isn't meant to hear the phrase anyway."""text = f"{opener} {rest}"result = scrub_for_voice(text)low = result.cleaned.lower()- assert "lass mich kurz" not in low+ assert "lass mich kurz" not in low # i18n-allowassert "let me think" not in low- # Kerninhalt (rest minus Opener-Komma) bleibt erhalten+ # The core content (rest minus the opener comma) is preservedrest_substantive = rest.split(".", 1)[-1].strip().lower()if rest_substantive:assert rest_substantive in lowassert "removed_filler_opener" in result.actions-def test_filler_selbstreferenz_mid_sentence_is_kept() -> None:- """Failure-Mode-6-analog: mid-sentence 'lass mich kurz' bleibt erhalten.+def test_filler_selbstreferenz_mid_sentence_is_kept() -> None: # i18n-allow+ """Failure-mode-6 analog: a mid-sentence 'lass mich kurz' is preserved.- Wenn der User wirklich darum bittet ('Schau dir das an, lass mich kurz- mal nachdenken, dann sage ich es dir'), darf der Filter das nicht- zerschiessen. Wie bei Echo-Paraphrase nur am Opener (<= 60 Zeichen).+ If the user genuinely asks for it ('Schau dir das an, lass mich kurz mal+ nachdenken, dann sage ich es dir'), the filter must not destroy it. Same+ as echo paraphrase: only at the opener (<= 60 characters)."""- # Mind. 61 Zeichen vor 'lass mich kurz' damit Failure-Mode-6 greift.+ # At least 61 characters before 'lass mich kurz' so failure-mode-6 applies.text = (- "Ich gehe das systematisch durch, "- "und im naechsten Schritt soll ich lass mich kurz nachdenken, "- "und dann antworte ich."+ "Ich gehe das systematisch durch, " # i18n-allow+ "und im naechsten Schritt soll ich lass mich kurz nachdenken, " # i18n-allow+ "und dann antworte ich." # i18n-allow)- pos = text.lower().find("lass mich kurz")- assert pos > 60, f"Test-Setup-Bug: pos={pos}"+ pos = text.lower().find("lass mich kurz") # i18n-allow+ assert pos > 60, f"Test setup bug: pos={pos}"result = scrub_for_voice(text)- assert "lass mich kurz" in result.cleaned.lower()+ assert "lass mich kurz" in result.cleaned.lower() # i18n-allowassert "removed_filler_opener" not in result.actions# ----------------------------------------------------------------------------# Audit F-AUDIT-4 (2026-04-29): prosaisch geschriebene Tool-Args.-# Brain leakte in Probe-Run vom 2026-04-29 Szenario 07 wortlich:+# Audit F-AUDIT-4 (2026-04-29): tool args written as prose.+# The brain leaked verbatim in the 2026-04-29 rehearsal run scenario 07:# "spawn_worker with utterance is Analysiere... context_hints is [...]# action is ... target is ..."-# Der Filter musste um dieses natuerlichsprachige Format erweitert werden.+# The filter had to be extended to cover this natural-language format.# ---------------------------------------------------------------------------def test_tool_call_prose_with_keys_is_removed() -> None:- """spawn_worker with utterance is X context_hints is Y → gescrubbt.+ """spawn_worker with utterance is X context_hints is Y -> scrubbed.- Realistischer Probe-Output 2026-04-29 Szenario 07. Filter muss den- ganzen Tool-Call-Block bis Satzende rausschneiden. Resttext bleibt.+ Realistic rehearsal output from 2026-04-29 scenario 07. The filter must+ cut the whole tool-call block up to the end of the sentence. The+ remaining text stays."""text = (- "Okay. spawn_worker with utterance is Analysiere das gesamte "- "Projektverzeichnis context_hints is Vollstaendige Projektstruktur "- "erfassen action is das Projekt analysiert target is Arbeitsordner. "- "Fertig."+ "Okay. spawn_worker with utterance is Analysiere das gesamte " # i18n-allow+ "Projektverzeichnis context_hints is Vollstaendige Projektstruktur " # i18n-allow+ "erfassen action is das Projekt analysiert target is Arbeitsordner. " # i18n-allow+ "Fertig." # i18n-allow)result = scrub_for_voice(text)assert "spawn_worker" not in result.cleaned@@ -674,32 +676,32 @@ def test_tool_call_prose_with_keys_is_removed() -> None:assert "context_hints" not in result.cleanedassert "action is" not in result.cleanedassert "removed_tool_json" in result.actions- # Resttext bleibt+ # The remaining text staysassert "Okay" in result.cleaned- assert "Fertig" in result.cleaned+ assert "Fertig" in result.cleaned # i18n-allowdef test_tool_args_prose_without_tool_name_is_removed() -> None:- """'utterance is X' allein (ohne Tool-Name-Prefix) wird auch gescrubbt."""- text = "Ich versuche es. utterance is lies die Datei. Fertig."+ """'utterance is X' alone (without a tool-name prefix) is also scrubbed."""+ text = "Ich versuche es. utterance is lies die Datei. Fertig." # i18n-allowresult = scrub_for_voice(text)assert "utterance is" not in result.cleanedassert "removed_tool_json" in result.actions- assert "Ich versuche es" in result.cleaned- assert "Fertig" in result.cleaned+ assert "Ich versuche es" in result.cleaned # i18n-allow+ assert "Fertig" in result.cleaned # i18n-allowdef test_legitimate_is_sentence_is_kept() -> None:- """Defense gegen False-Positive: legitime 'X is Y'-Saetze bleiben.+ """Defense against false positives: legitimate 'X is Y' sentences stay.- Wenn der User sagt 'Die Hauptstadt ist Paris', oder Brain antwortet- 'Es ist halb drei' — KEIN Match auf TOOL_ARGS_PROSE_RE, weil 'Die- Hauptstadt' und 'Es' keine Tool-Arg-Schluessel sind.+ If the user says 'Die Hauptstadt ist Paris', or the brain answers 'Es ist+ halb drei' — NO match on TOOL_ARGS_PROSE_RE, because 'Die Hauptstadt' and+ 'Es' are not tool-arg keys."""- text = "Es ist halb drei. Die Datei ist gespeichert."+ text = "Es ist halb drei. Die Datei ist gespeichert." # i18n-allowresult = scrub_for_voice(text)- assert "ist halb drei" in result.cleaned- assert "Datei ist gespeichert" in result.cleaned+ assert "ist halb drei" in result.cleaned # i18n-allow+ assert "Datei ist gespeichert" in result.cleaned # i18n-allowassert "removed_tool_json" not in result.actions@@ -715,8 +717,8 @@ def test_legitimate_is_sentence_is_kept() -> None:def test_openclaw_brand_name_is_scrubbed() -> None:"""OpenClaw must NOT survive voice output anymore (2026-05-24 reversal)."""text = (- "Mach ich, ich lasse dafür einen OpenClaw-Subagent "- "ein Hello-World-Programm schreiben."+ "Mach ich, ich lasse dafür einen OpenClaw-Subagent " # i18n-allow+ "ein Hello-World-Programm schreiben." # i18n-allow)result = scrub_for_voice(text)assert "OpenClaw" not in result.cleaned@@ -725,8 +727,8 @@ def test_openclaw_brand_name_is_scrubbed() -> None:def test_bare_subagent_still_scrubbed_without_brand_prefix() -> None:- """Bare 'Subagent' / 'Sub-Agent' ohne Brand-Praefix bleibt gescrubbt."""- text = "Ich aktiviere einen Subagent für die Aufgabe."+ """A bare 'Subagent' / 'Sub-Agent' without a brand prefix stays scrubbed."""+ text = "Ich aktiviere einen Subagent für die Aufgabe." # i18n-allowresult = scrub_for_voice(text)assert "Subagent" not in result.cleanedassert "removed_engineering_jargon" in result.actions@@ -734,15 +736,15 @@ def test_bare_subagent_still_scrubbed_without_brand_prefix() -> None:def test_openclaw_compound_prefix_stripped_but_noun_kept() -> None:"""'OpenClaw-Mission' -> 'Mission' (brand prefix removed, noun stays)."""- text = "Die OpenClaw-Mission ist fertig."+ text = "Die OpenClaw-Mission ist fertig." # i18n-allowresult = scrub_for_voice(text)assert "OpenClaw" not in result.cleanedassert "Mission" in result.cleaneddef test_openclaw_subagenten_plural_also_scrubbed() -> None:- """Plural 'OpenClaw-Subagenten' muss ebenfalls gescrubbt werden."""- text = "Mehrere OpenClaw-Subagenten arbeiten parallel."+ """The plural 'OpenClaw-Subagenten' must also be scrubbed."""+ text = "Mehrere OpenClaw-Subagenten arbeiten parallel." # i18n-allowresult = scrub_for_voice(text)assert "OpenClaw" not in result.cleanedassert "Subagenten" not in result.cleaned@@ -751,9 +753,9 @@ def test_openclaw_subagenten_plural_also_scrubbed() -> None:def test_scrub_strips_end_call_sentinel() -> None:from jarvis.speech.hangup import END_CALL_SIGNAL- result = scrub_for_voice(f"Bis später, Ruben. {END_CALL_SIGNAL}", language="de")+ result = scrub_for_voice(f"Bis später, Ruben. {END_CALL_SIGNAL}", language="de") # i18n-allowassert END_CALL_SIGNAL not in result.cleaned- assert result.cleaned.strip() == "Bis später, Ruben."+ assert result.cleaned.strip() == "Bis später, Ruben." # i18n-allowassert "stripped_end_signal" in result.actions@@ -768,11 +770,11 @@ def test_scrub_strips_end_call_sentinel() -> None:def test_http_url_is_stripped_from_voice() -> None:"""A spoken answer must never read out an http(s) URL."""- text = "Die Prüfung dauert 190 Minuten. Mehr unter https://www.km.bayern.de/schueler.html"+ text = "Die Prüfung dauert 190 Minuten. Mehr unter https://www.km.bayern.de/schueler.html" # i18n-allowresult = scrub_for_voice(text)assert "http" not in result.cleaned.lower()assert "km.bayern.de" not in result.cleaned.lower()- assert "einhundertneunzig minuten" in result.cleaned.lower()+ assert "einhundertneunzig minuten" in result.cleaned.lower() # i18n-allowassert "removed_source_artifacts" in result.actions@@ -800,7 +802,7 @@ def test_bare_www_domain_is_stripped_from_voice() -> None:def test_clean_answer_without_sources_is_untouched() -> None:"""Defense against false positives: a normal spoken answer with no URL /domain / SERP footer must pass through unchanged (no source-artifact pass)."""- text = "Morgen schreiben alle Realschüler in Bayern ihre Mathe-Abschlussprüfung."+ text = "Morgen schreiben alle Realschüler in Bayern ihre Mathe-Abschlussprüfung." # i18n-allowresult = scrub_for_voice(text)assert result.cleaned == textassert "removed_source_artifacts" not in result.actions@@ -900,16 +902,16 @@ def test_fallback_phrase_localized_to_spanish() -> None:def test_scrub_keeps_humanized_readback_with_quotes() -> None:"""No false positive: a clean readback that merely quotes a UI label (andcontains an apostrophe + colon-free) must pass through untouched."""- text = "Erledigt — die Einstellungen sind auf 'Bluetooth und Geräte' offen."+ text = "Erledigt — die Einstellungen sind auf 'Bluetooth und Geräte' offen." # i18n-allowresult = scrub_for_voice(text, language="de")assert result.fallback_used is False- assert "Bluetooth und Geräte" in result.cleaned+ assert "Bluetooth und Geräte" in result.cleaned # i18n-allowdef test_scrub_keeps_sentence_with_inline_brace_not_a_dump() -> None:"""A sentence that happens to mention a brace mid-text is NOT a dump (itdoes not OPEN with a container) — must pass."""- text = "Ich habe die Funktion test() geprüft, alles in Ordnung."+ text = "Ich habe die Funktion test() geprüft, alles in Ordnung." # i18n-allowresult = scrub_for_voice(text, language="de")assert result.fallback_used is Falseassert "test()" in result.cleaned or "test" in result.cleaned@@ -918,8 +920,9 @@ def test_scrub_keeps_sentence_with_inline_brace_not_a_dump() -> None:# ---------------------------------------------------------------------------# Raw shell / PowerShell command guard (live bug 2026-06-28): the fast tier# emitted a SendKeys PowerShell command as its reply and TTS read it aloud-# "mit Sonderzeichen und allem". A raw command is code, never a spoken-# sentence -> fail-closed to the standard phrase, like a stacktrace.+# "mit Sonderzeichen und allem" (with special characters and everything). # i18n-allow+# A raw command is code, never a spoken sentence -> fail-closed to the+# standard phrase, like a stacktrace.# ---------------------------------------------------------------------------SHELL_COMMAND_CASES = [@@ -948,10 +951,10 @@ def test_raw_shell_command_is_never_spoken(text: str) -> None:@pytest.mark.parametrize("clean",[- "Schau bitte im Browser-Verlauf nach.",+ "Schau bitte im Browser-Verlauf nach.", # i18n-allow"Das kostet 5-10 Euro.",- "Die E-Mail ist raus.",- "Ich habe die Datei gespeichert.",+ "Die E-Mail ist raus.", # i18n-allow+ "Ich habe die Datei gespeichert.", # i18n-allow"Ruf Anna an und sag ihr Bescheid.",],)diff --git a/tests/unit/plugins/tool/test_gmail_rest.py b/tests/unit/plugins/tool/test_gmail_rest.pyindex 1050b8477e..e42b16a1b0 100644--- a/tests/unit/plugins/tool/test_gmail_rest.py+++ b/tests/unit/plugins/tool/test_gmail_rest.py@@ -199,13 +199,13 @@ def test_risk_tier_for_args_unknown_action_is_conservative():@pytest.mark.asyncioasync def test_get_message_returns_slim_projection_not_raw_mime():- body_text = "Hallo Ruben, hier ist der Kern der Nachricht. " * 5+ body_text = "Hallo Ruben, hier ist der Kern der Nachricht. " * 5 # i18n-allowraw_body_b64 = base64.urlsafe_b64encode(body_text.encode("utf-8")).decode("ascii")fat = {"id": "m1","threadId": "t1","labelIds": ["UNREAD", "INBOX"],- "snippet": "Hallo Ruben, hier ist der Kern",+ "snippet": "Hallo Ruben, hier ist der Kern", # i18n-allow"payload": {"mimeType": "multipart/alternative","headers": [@@ -236,8 +236,8 @@ async def test_get_message_returns_slim_projection_not_raw_mime():assert out["from"] == "Chef <[email protected]>"assert out["subject"] == "Quartalszahlen"assert out["date"].startswith("Wed, 01 Jul 2026")- assert out["snippet"] == "Hallo Ruben, hier ist der Kern"- assert "Kern der Nachricht" in out["body"]+ assert out["snippet"] == "Hallo Ruben, hier ist der Kern" # i18n-allow+ assert "Kern der Nachricht" in out["body"] # i18n-allowimport json as _jsondiff --git a/tests/unit/speech/test_rolling_whisper_wake_quiet_mic.py b/tests/unit/speech/test_rolling_whisper_wake_quiet_mic.pyindex 6f65bb56db..6a125a9ada 100644--- a/tests/unit/speech/test_rolling_whisper_wake_quiet_mic.py+++ b/tests/unit/speech/test_rolling_whisper_wake_quiet_mic.py@@ -101,7 +101,7 @@ async def test_very_quiet_wake_below_legacy_peak_gate_reaches_whisper() -> None:("Leo", "leo"), # 3-char name — short-token relaxed ratio("Ruben", "ruben"), # name("Herz", "herz"), # German common noun- ("Björn", "björn"), # umlaut name — diacritics folded for match+ ("Björn", "björn"), # umlaut name — diacritics folded for match # i18n-allow("Athena", "athena"), # longer name("Computer", "computer"), # English noun("Hey Zeus", "hey zeus"), # two-word phrase, prefix strippeddiff --git a/tests/unit/speech/test_wake_phrase_phonetic.py b/tests/unit/speech/test_wake_phrase_phonetic.pyindex 0ddcf37cd8..4fc31c25aa 100644--- a/tests/unit/speech/test_wake_phrase_phonetic.py+++ b/tests/unit/speech/test_wake_phrase_phonetic.py@@ -26,7 +26,7 @@ def test_sound_equivalent_spellings_of_the_wake_word_match(heard: str) -> None:@pytest.mark.parametrize("heard",- ["Marco", "Hallo", "Computer", "das war die Welt", "Schule fertig"],+ ["Marco", "Hallo", "Computer", "das war die Welt", "Schule fertig"], # i18n-allow)def test_clearly_different_words_still_do_not_match(heard: str) -> None:m = compile_wake_matcher("Nico")diff --git a/tests/unit/voice/test_number_speller.py b/tests/unit/voice/test_number_speller.pyindex 35b9549203..fb8a8f2567 100644--- a/tests/unit/voice/test_number_speller.py+++ b/tests/unit/voice/test_number_speller.py@@ -15,7 +15,7 @@ requires_num2words = pytest.mark.skipif(@requires_num2wordsdef test_no_bare_digit_survives_german():- out = spell_out_numbers("Der Mond entfernt sich 3,8 Zentimeter pro Jahr.", "de")+ out = spell_out_numbers("Der Mond entfernt sich 3,8 Zentimeter pro Jahr.", "de") # i18n-allowassert not any(c.isdigit() for c in out)assert "drei Komma acht" in out@@ -47,14 +47,14 @@ def test_decimal_english_uses_point():def test_time_german():out = spell_out_numbers("Wir treffen uns um 20:30.", "de")assert not any(c.isdigit() for c in out)- assert "zwanzig Uhr dreißig" in out+ assert "zwanzig Uhr dreißig" in out # i18n-allow@requires_num2wordsdef test_full_hour_german():out = spell_out_numbers("Es ist 15:00.", "de")assert not any(c.isdigit() for c in out)- assert "fünfzehn Uhr" in out+ assert "fünfzehn Uhr" in out # i18n-allow@requires_num2words