Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

fix(voice): one language resolver, as the contract says

Harald6e19ae5323e5
diff --git a/jarvis/brain/ack_brain/generator.py b/jarvis/brain/ack_brain/generator.py
index 340c9639d9..43f7c36080 100644
--- a/jarvis/brain/ack_brain/generator.py
+++ b/jarvis/brain/ack_brain/generator.py
@@ -11,7 +11,8 @@ Failure-mode coverage (spec §6):
- F3 Empty / whitespace
- F4 Over-long output (truncate at first [.!?])
- F5 Blacklist-stripped to < 3 alnum chars
-- F6 Language mismatch (top-100 word heuristic)
+- F6 Language mismatch (validated against the turn's resolved
+ output language via ``jarvis.core.turn_language``)
- F8 Circuit breaker open
- F10 Self-answer (post-filter for answer-shaped output) — spec
update 2026-05-13
@@ -32,6 +33,10 @@ from jarvis.brain.ack_brain.circuit_breaker import CircuitBreaker
from jarvis.brain.ack_brain.persona_prompt import get_persona_prompt
from jarvis.brain.action_honesty import has_deferred_action_claim
from jarvis.brain.output_filter import scrub_for_voice
+from jarvis.core.turn_language import (
+ detect_text_language,
+ validate_output_language,
+)
if TYPE_CHECKING:
from jarvis.brain.ack_brain.config import AckBrainConfig
@@ -59,56 +64,21 @@ def _augment_with_preferences(
return f"{base_prompt}\n\n{extra}" if extra else base_prompt
-# ----------------------------------------------------------------------
-# Cheap top-100-word language heuristic
-# ----------------------------------------------------------------------
-# Tokens that appear in the v2.1 persona-prompt examples + common
-# function words. Kept small (~70 each) — frozenset overlap is O(n)
-# in token count, dominated by re.findall.
-
-_TOP_DE: frozenset[str] = frozenset({
- "der", "die", "das", "und", "ich", "ist", "nicht", "ein", "eine", "zu", # i18n-allow: German output-language-detection vocabulary, matched against generated ack text
- "den", "mit", "sich", "auf", "für", "von", "im", "dem", "ja", "kurz", # i18n-allow: same German language-detection vocabulary
- "mache", "danke", "hallo", "klar", "okay", "gut", "lass", "mich", "kann", # i18n-allow: same German language-detection vocabulary
- "gleich", "schaue", "suche", "prüfe", "starte", "wechsle", "öffne", # i18n-allow: same German language-detection vocabulary
- "hole", "schaut", "ändere", "recherchiere", "guten", "tag", "abend", # i18n-allow: same German language-detection vocabulary
- "morgen", "schön", "bitte", "leider", "noch", "schon", "aber", # i18n-allow: same German language-detection vocabulary
- "oder", "auch", "nur", "weil", "wenn", "dann", "doch", "wie", "was", # i18n-allow: same German language-detection vocabulary
- "wer", "wo", "wann", "warum", "diese", "dieser", "dieses", "habe",
- "hast", "hat", "haben", "wird", "werden", "wollen", "kannst", "konnte", # i18n-allow: same German language-detection vocabulary
- "sollst", "soll", "muss", "müssen", "Chef", # i18n-allow: same German language-detection vocabulary
-})
-
-_TOP_EN: frozenset[str] = frozenset({
- "the", "and", "you", "that", "for", "with", "this", "let", "me", "on",
- "check", "sure", "got", "ok", "fine", "good", "morning", "afternoon",
- "evening", "yes", "no", "search", "fetch", "look", "up", "launch",
- "change", "switch", "open", "thanks", "hi", "hello", "hey", "please",
- "still", "now", "but", "or", "also", "only", "because", "if", "then",
- "how", "what", "who", "where", "when", "why", "have", "has", "had",
- "will", "would", "could", "should", "must", "can", "be", "is", "are",
- "was", "were", "am", "do", "does", "did", "going", "want", "need",
- "it", "to", "of", "in", "a", "an",
-})
-
_TOKEN_RE = re.compile(r"\b[\w']+\b", re.UNICODE)
-
-def _detect_language(text: str) -> str:
- """Cheap heuristic: pick the language whose top-100 set has more overlap.
-
- Returns "de", "en", or "unknown" (both counts zero — e.g. pure
- proper-noun output). The generator treats "unknown" as a non-mismatch
- so single-word names like ``"Spotify."`` don't get false-rejected.
- """
- tokens = {t.lower() for t in _TOKEN_RE.findall(text)}
- if not tokens:
- return "unknown"
- de = len(tokens & _TOP_DE)
- en = len(tokens & _TOP_EN)
- if de == 0 and en == 0:
- return "unknown"
- return "de" if de >= en else "en"
+# Back-compat re-export. This module used to own a private de/en-only
+# top-100-word heuristic (``_TOP_DE`` / ``_TOP_EN``), which is exactly the
+# per-layer language re-derivation CLAUDE.md §1 forbids: it scored the German
+# ack "Moment, in Ordnung." as English (the bare token "in" was in the English
+# set) and dropped it, and it classified every Spanish ack containing "no" as
+# English and dropped that too — the user simply heard nothing. The tables are
+# gone; ``jarvis.core.turn_language`` is the single authority, and it covers
+# de/en/es equally.
+#
+# Kept under the old name because ``jarvis.voice.contextual_readback`` still
+# imports it from here (see that module's ``_validate``); that caller should
+# move to ``validate_output_language`` — see the note on ``_postprocess``.
+_detect_language = detect_text_language
# ----------------------------------------------------------------------
@@ -300,7 +270,7 @@ class AckGenerator:
f) any other Exception → None
g) empty / whitespace → None
h) word count > 25 → truncate at first [.!?]
- i) language mismatch heuristic → None
+ i) output-language mismatch → None
j) scrub_for_voice → < 3 alnum chars → None
k) F10 self-answer post-filter → None
l) ack_emitted_total++, latency histogram, return scrubbed
@@ -354,9 +324,14 @@ class AckGenerator:
text = _truncate_at_first_sentence(text)
_emit_counter("ack_truncated_total")
- # (i) cheap language sanity check
- detected = _detect_language(text)
- if detected != "unknown" and detected != language:
+ # (i) output-language sanity check. ``language`` is ALREADY this turn's
+ # resolved output language (``resolve_output_language``, resolved once
+ # by the pipeline) — this layer must never re-derive it (CLAUDE.md §1).
+ # ``validate_output_language`` blocks only on a high-confidence
+ # mismatch; short, ambiguous, or name-only acks come back
+ # ``indeterminate`` and PASS. Dropping user-facing output on a language
+ # guess is the bug: silence is worse than a slightly odd ack.
+ if validate_output_language(text, resolved_language=language).should_block:
_emit_counter("ack_lang_mismatch_total", provider=provider_label)
await self._breaker.record_success() # provider was healthy
return None
@@ -423,8 +398,10 @@ class AckGenerator:
return None
if _word_count(text) > 25:
text = _truncate_at_first_sentence(text)
- detected = _detect_language(text)
- if detected != "unknown" and detected != language:
+ # Same single-resolver rule as ``run()`` step (i): validate against the
+ # already-resolved ``language``, never a local detector, and let
+ # anything indeterminate through rather than dropping the sentence.
+ if validate_output_language(text, resolved_language=language).should_block:
return None
scrub_result = scrub_for_voice(text, language=language, ack_mode=True)
if scrub_result.fallback_used:
diff --git a/jarvis/brain/ack_brain/spawn_announcement.py b/jarvis/brain/ack_brain/spawn_announcement.py
index 8a99691141..5313c3fdc1 100644
--- a/jarvis/brain/ack_brain/spawn_announcement.py
+++ b/jarvis/brain/ack_brain/spawn_announcement.py
@@ -58,12 +58,15 @@ from typing import TYPE_CHECKING
from jarvis.brain.ack_brain.generator import (
_TOKEN_RE,
_augment_with_preferences,
- _detect_language,
_emit_counter,
)
from jarvis.brain.assistant_name import agent_brand_from_name
from jarvis.brain.output_filter import scrub_for_voice
-from jarvis.core.turn_language import DEFAULT_LOCALE
+from jarvis.core.turn_language import (
+ DEFAULT_LOCALE,
+ detect_text_language,
+ validate_output_language,
+)
if TYPE_CHECKING:
from jarvis.brain.ack_brain.circuit_breaker import CircuitBreaker
@@ -376,7 +379,7 @@ def _resolve_language(explicit: str | None, utterance: str) -> str:
return "es"
if low.startswith("de"):
return "de"
- detected = _detect_language(utterance or "")
+ detected = detect_text_language(utterance or "")
return detected if detected in ("de", "en", "es") else DEFAULT_LOCALE
@@ -531,8 +534,12 @@ class SpawnAnnouncementComposer:
return None
if _COMPLETION_CLAIM_RE.search(trimmed):
return None
- detected = _detect_language(trimmed)
- if detected != "unknown" and detected != lang:
+ # ``lang`` is already this turn's resolved output language — validate
+ # against it through the single resolver, never a local detector
+ # (CLAUDE.md §1). Only a high-confidence mismatch rejects; an
+ # indeterminate verdict keeps the announcement, since staying silent on
+ # a language guess is worse than an odd-sounding one.
+ if validate_output_language(trimmed, resolved_language=lang).should_block:
return None
try:
result = scrub_for_voice(trimmed, language=lang, ack_mode=True)
diff --git a/jarvis/brain/evidence_gate.py b/jarvis/brain/evidence_gate.py
index a8fa247a48..f664d15d16 100644
--- a/jarvis/brain/evidence_gate.py
+++ b/jarvis/brain/evidence_gate.py
@@ -22,6 +22,11 @@ from dataclasses import dataclass
from typing import Any, Literal
from jarvis.core.capabilities import _normalize
+from jarvis.core.turn_language import (
+ DEFAULT_LOCALE,
+ detect_text_language,
+ normalize_language_tag,
+)
log = logging.getLogger(__name__)
@@ -195,20 +200,50 @@ _REFUSAL_EN: dict[str, str] = {
}
_REFUSAL_EN_FALLBACK = "I have no data access for that right now."
+# Spoken Spanish voice replies (TTS-safe, deterministic). All locales are
+# equal (CLAUDE.md §1): a Spanish-speaking user gets the refusal in Spanish,
+# not the English table because no Spanish one existed.
+_REFUSAL_ES: dict[str, str] = {
+ "calendar": "Ahora mismo no tengo acceso a tu calendario.", # i18n-allow
+ "email": "Ahora mismo no tengo acceso a tu correo.", # i18n-allow
+ "tasks": "Ahora mismo no tengo acceso a tus tareas.", # i18n-allow
+ "repos": "Ahora mismo no tengo acceso a tus repositorios.", # i18n-allow
+ "deployments": "Ahora mismo no tengo acceso a tus despliegues.", # i18n-allow
+ "cloud": "Ahora mismo no tengo acceso a tu facturación en la nube.", # i18n-allow
+ "activity": "Ahora mismo no puedo acceder a tu historial de actividad.", # i18n-allow
+}
+_REFUSAL_ES_FALLBACK = "Ahora mismo no tengo acceso a esos datos." # i18n-allow
+
+#: One table per supported locale, so adding a language is a table, not a
+#: branch. Keys must stay in step with ``jarvis.core.turn_language``'s pins.
+_REFUSALS: dict[str, tuple[dict[str, str], str]] = {
+ "de": (_REFUSAL_DE, _REFUSAL_DE_FALLBACK),
+ "en": (_REFUSAL_EN, _REFUSAL_EN_FALLBACK),
+ "es": (_REFUSAL_ES, _REFUSAL_ES_FALLBACK),
+}
-def _detect_lang(text: str) -> str:
- """Cheap DE/EN heuristic for the refusal language (mirrors the existing
- heuristic in ``BrainManager._check_unsupported_intent``)."""
- if re.search(r"[äöüÄÖÜß]", text): # i18n-allow: umlaut character class, language-detection matching data
- return "de"
- if re.search(
- r"\b(was|wie|welche|welcher|steht|stehen|heute|morgen|hab|habe|"
- r"meine|meinem|bitte|gibt)\b",
- text,
- re.I,
- ):
- return "de"
- return "en"
+
+def _refusal_language(resolved: object, text: str) -> str:
+ """Which language the deterministic refusal is spoken in.
+
+ The turn's ALREADY-resolved output language wins outright — this module
+ must never re-derive it (CLAUDE.md §1: one resolver,
+ ``resolve_output_language``, decides for all layers). It used to sniff the
+ utterance with a private de/en-only heuristic, so an explicit
+ ``brain.reply_language`` pin was ignored: a Spanish-pinned user asking in
+ English heard an English refusal, and there was no Spanish table to reach
+ at all.
+
+ The text fallback exists only for callers not yet passing ``language``. It
+ is the canonical detector rather than a local one, and an undecidable text
+ lands on the shared ``DEFAULT_LOCALE`` instead of a hardcoded per-layer
+ default.
+ """
+ code = normalize_language_tag(resolved)
+ if code in _REFUSALS:
+ return code
+ detected = detect_text_language(text)
+ return detected if detected in _REFUSALS else DEFAULT_LOCALE
def check_evidence_domain(
@@ -220,6 +255,7 @@ def check_evidence_domain(
domain_tool_map: Mapping[str, str],
refusal_hint_fn: Callable[[str, str], str] | None = None,
live_tool_names: Sequence[str] = (),
+ language: object = "",
) -> EvidenceVerdict:
"""Classify one utterance against the evidence-required domains.
@@ -228,6 +264,13 @@ def check_evidence_domain(
matching tool on the live surface beats an empty registry (see
:func:`live_surface_covers`). Defaulting to ``()`` keeps every existing
caller on the registry-only behaviour.
+
+ ``language`` is THIS turn's resolved output language (de/en/es), produced
+ by ``jarvis.core.turn_language.resolve_output_language`` and passed down by
+ the caller. The honest refusal is user-facing speech, so it must be spoken
+ in the same language as every other layer of the turn. Callers that omit it
+ fall back to detecting the utterance (see :func:`_refusal_language`), which
+ silently ignores an explicit ``brain.reply_language`` pin — pass it.
"""
if not enabled:
return _PASS
@@ -296,12 +339,9 @@ def check_evidence_domain(
)
return _PASS
- lang = _detect_lang(t)
- base = (
- _REFUSAL_DE.get(matched_domain, _REFUSAL_DE_FALLBACK)
- if lang == "de"
- else _REFUSAL_EN.get(matched_domain, _REFUSAL_EN_FALLBACK)
- )
+ lang = _refusal_language(language, t)
+ table, table_fallback = _REFUSALS[lang]
+ base = table.get(matched_domain, table_fallback)
hint = ""
if refusal_hint_fn is not None:
try:
diff --git a/jarvis/plugins/tts/cartesia_tts.py b/jarvis/plugins/tts/cartesia_tts.py
index 5cfffeee41..bda3078251 100644
--- a/jarvis/plugins/tts/cartesia_tts.py
+++ b/jarvis/plugins/tts/cartesia_tts.py
@@ -47,15 +47,23 @@ DEFAULT_VOICE_ID = DEFAULT_VOICE_ID_EN
_SENTENCE_END = re.compile(r"(?<=[.!?…])\s+(?=[A-ZÄÖÜ])") # i18n-allow (DE letters are part of the sentence-boundary match set)
-# Text-detection heuristic: when the caller does not pass a language_code,
-# we look at the transcript to pick the right voice. Cheap, no LLM call,
-# no library dependency. False positives fall back to the generic voice.
+# DEPRECATED — no longer used by this plugin. This sniff picked the VOICE from
+# bare function words, so English prose containing "die"/"das"/"der"/"ist" was
+# spoken by the German voice: "the die is cast" came out with German phonetics,
+# i.e. the right words rendered unintelligible. Language is resolved ONCE per
+# turn by the pipeline (``resolve_output_language``) and arrives as
+# ``language_code``; a plugin must not re-derive it, and cannot call the
+# resolver anyway (no ``jarvis.*`` import inside plugins, CLAUDE.md §5).
+#
+# Kept only because ``jarvis.plugins.tts.inworld_tts`` still imports it and
+# carries the identical defect; delete both together once that plugin takes its
+# language from the caller too.
_DE_HINTS = re.compile(r"[äöüÄÖÜß]|\b(ich|nicht|und|der|die|das|ist|mit|für|werde|machen|gerne|bitte)\b", re.IGNORECASE) # i18n-allow (DE word list a language-detection classifier must match)
_ES_HINTS = re.compile(r"[ñáéíóúÑÁÉÍÓÚ¿¡]|\b(que|para|con|por|esto|esta|hola|gracias|señor|cómo)\b", re.IGNORECASE)
def _detect_lang_from_text(text: str) -> str | None:
- """Return 'de', 'es' or None (unknown — caller falls back to default)."""
+ """Return 'de', 'es' or None. DEPRECATED — see the note above."""
if _DE_HINTS.search(text):
return "de"
if _ES_HINTS.search(text):
@@ -122,17 +130,25 @@ class CartesiaTTS:
def _resolve_voice(
self, text: str, voice_override: str | None, language_code: str | None
) -> str:
- """Pick the voice UUID that best matches the language of this segment.
+ """Pick the voice UUID for this segment from the CALLER's language.
Priority:
1. Explicit ``voice`` override from the caller (Pipeline can pass
a per-utterance voice).
- 2. ``language_code`` from the caller (matches the Pipeline's
- ``voice_auto_switch`` per-utterance detection or the user's
- reply-language pin).
- 3. Text-detection heuristic on the transcript (cheap, regex-based,
- handles the case where the caller passes 'auto' or nothing).
- 4. The generic ``voice_id`` fallback.
+ 2. ``language_code`` from the caller — REQUIRED in practice. It is
+ the turn's single resolved output language (the pipeline resolves
+ it once via ``resolve_output_language`` and pins every layer to
+ it), so this plugin has nothing left to decide.
+ 3. The configured ``[tts.cartesia].language``, else the doctrine
+ default locale — never a hardcoded English voice on German text
+ (British-accent symptom, forensic 2026-06-23).
+
+ There is deliberately no text sniff. Guessing the voice from the words
+ picked the German voice for any English sentence containing "die",
+ "das", "der" or "ist" — "the die is cast" was spoken with German
+ phonetics, which is unintelligible rather than merely wrong. A caller
+ that omits the code gets the configured default and a warning, so the
+ gap is visible instead of silently mis-voiced.
"""
if voice_override:
return voice_override
@@ -141,13 +157,13 @@ class CartesiaTTS:
short = hint.split("-", 1)[0]
if short in self._voice_by_lang:
return self._voice_by_lang[short]
- # Caller did not pin a language — sniff the text.
- detected = _detect_lang_from_text(text)
- if detected and detected in self._voice_by_lang:
- return self._voice_by_lang[detected]
- # No language could be resolved — follow the configured default_locale,
- # never a hardcoded English voice on German text (British-accent
- # symptom). default_locale is "en" only when configured/auto.
+ elif text.strip():
+ logging.getLogger("jarvis.tts.cartesia").warning(
+ "No language_code passed for %r — falling back to the "
+ "configured default voice (%s). The caller must pass this "
+ "turn's resolved output language.",
+ text[:60], self._default_locale,
+ )
return self._voice_by_lang.get(self._default_locale, self._voice_id)
def _resolve_api_key(self) -> str:
diff --git a/tests/unit/brain/test_ack_brain/test_output_language_gate.py b/tests/unit/brain/test_ack_brain/test_output_language_gate.py
new file mode 100644
index 0000000000..ef44c884f5
--- /dev/null
+++ b/tests/unit/brain/test_ack_brain/test_output_language_gate.py
@@ -0,0 +1,80 @@
+"""The ack's language gate must not drop user-facing speech on a guess.
+
+The generator used to run its own de/en-only top-100-word heuristic and drop
+any ack whose guessed language differed from the turn's. Two consequences,
+both of which left the user hearing NOTHING on a slow turn — the exact silence
+the ack exists to bridge:
+
+* "Moment, in Ordnung." scored en=1 / de=0, because the bare token "in" sat in
+ the English set, so a perfectly good German ack was suppressed.
+* Any Spanish ack containing "no" was read as English and suppressed too. The
+ heuristic could not return "es" at all, so Spanish was structurally unable
+ to pass.
+
+The gate now validates against the turn's ALREADY-resolved output language
+through ``jarvis.core.turn_language`` (CLAUDE.md §1: one resolver for every
+layer), which fails open on anything indeterminate and covers de/en/es equally.
+A genuine, high-confidence mismatch must still be blocked.
+"""
+from __future__ import annotations
+
+import pytest
+
+from tests.unit.brain.test_ack_brain.conftest import (
+ FakeAckProvider,
+ build_ack_generator_with_fake,
+)
+
+
+# Every phrase below is runtime voice output in the language it is testing.
+# i18n-allow: de/en/es ack phrases under test
+ ("ack_text", "language", "case"),
+ [
+ # The two live regressions.
+ ("Moment, in Ordnung.", "de", "German ack with the token 'in'"),
+ ("Un momento, no tardo nada.", "es", "Spanish ack with the token 'no'"),
+ # All three locales are equal — an ordinary ack passes in each.
+ ("Na klar, kein Problem und auch nicht schlimm.", "de", "German ack"),
+ ("Alright, no problem at all for you.", "en", "English ack"),
+ ("Hola, qué tal, y gracias por la pregunta.", "es", "Spanish ack"),
+ # Names and near-empty output carry no language evidence at all.
+ ("Spotify, Notepad, Chrome.", "es", "bare proper nouns"),
+ ("Okay.", "de", "bare interjection"),
+ ],
+)
+async def test_ack_survives_when_the_language_is_not_clearly_wrong(
+ ack_text: str, language: str, case: str
+) -> None:
+ gen = build_ack_generator_with_fake(FakeAckProvider(response=ack_text))
+
+ assert await gen.run("egal", language=language) is not None, (
+ f"ack dropped for {case}: {ack_text!r}"
+ )
+
+
+async def test_ack_is_still_dropped_on_a_high_confidence_mismatch() -> None:
+ """The guard is relaxed, not removed: real cross-language output blocks."""
+ # A plainly German ack on an English turn — the one case worth suppressing.
+ german_ack = "Ich schaue gleich einmal nach dem Wetter." # i18n-allow
+ gen = build_ack_generator_with_fake(FakeAckProvider(response=german_ack))
+
+ assert await gen.run("what is the weather", language="en") is None
+
+
+async def test_streaming_path_uses_the_same_relaxed_gate() -> None:
+ """``_postprocess`` (the run_stream path) must not re-introduce the drop."""
+
+ class _StreamingFake:
+ async def run(self, u: str, lang: str, *, persona_prompt: str) -> str | None:
+ return "Moment, in Ordnung." # i18n-allow: German ack under test
+
+ async def run_stream(self, u: str, lang: str, *, persona_prompt: str):
+ yield "Moment, " # i18n-allow: German ack under test
+ yield "in Ordnung." # i18n-allow: German ack under test
+
+ gen = build_ack_generator_with_fake(_StreamingFake()) # type: ignore[arg-type]
+
+ out = [s async for s in gen.run_stream("egal", language="de")]
+
+ assert out, "the streaming ack was dropped on a language guess"
diff --git a/tests/unit/brain/test_evidence_gate_refusal_language.py b/tests/unit/brain/test_evidence_gate_refusal_language.py
new file mode 100644
index 0000000000..161f9fc9ab
--- /dev/null
+++ b/tests/unit/brain/test_evidence_gate_refusal_language.py
@@ -0,0 +1,103 @@
+"""The honest refusal is spoken in the turn's resolved language, in all locales.
+
+The gate used to sniff the utterance with a private de/en-only heuristic to
+choose the refusal language. Two consequences:
+
+* the user's explicit ``brain.reply_language`` pin was ignored — a
+ Spanish-pinned or English-pinned user heard whatever language the utterance
+ happened to look like;
+* there was no Spanish table at all, so a Spanish turn could only ever fall
+ back to English.
+
+The refusal is user-facing speech, so it must follow the ONE resolver like
+every other layer (CLAUDE.md §1). ``check_evidence_domain`` now takes the
+already-resolved ``language``; the utterance is only consulted when a caller
+omits it.
+"""
+from jarvis.brain.evidence_gate import (
+ _REFUSAL_DE,
+ _REFUSAL_EN,
+ _REFUSAL_ES,
+ check_evidence_domain,
+)
+from jarvis.core.capabilities import CapabilityRegistry
+
+DOMAINS = {
+ "calendar": ["kalender", "termin", "termine", "calendar", "meeting", "meetings"],
+ "email": ["mail", "mails", "inbox", "postfach"],
+}
+
+# Same meaning in each language, so only the resolved language can move the
+# refusal — the utterance's own language is deliberately varied against it.
+DE_UTTERANCE = "Welche Termine habe ich heute?" # i18n-allow: German utterance under test
+EN_UTTERANCE = "What meetings do I have today?"
+
+
+def _refuse(text, *, language=""):
+ return check_evidence_domain(
+ text,
+ enabled=True,
+ domains=DOMAINS,
+ capability_registry=CapabilityRegistry(),
+ domain_tool_map={},
+ language=language,
+ )
+
+
+def test_every_locale_has_a_complete_refusal_table():
+ """All locales are equal: no table may lag another (CLAUDE.md §1)."""
+ assert set(_REFUSAL_ES) == set(_REFUSAL_DE) == set(_REFUSAL_EN)
+ assert all(text.strip() for text in _REFUSAL_ES.values())
+
+
+def test_resolved_language_wins_over_the_utterance_language():
+ for utterance in (DE_UTTERANCE, EN_UTTERANCE):
+ for language in ("de", "en", "es"):
+ v = _refuse(utterance, language=language)
+ assert v.kind == "honest_refusal"
+ assert v.refusal_text == {
+ "de": _REFUSAL_DE, "en": _REFUSAL_EN, "es": _REFUSAL_ES,
+ }[language]["calendar"], (
+ f"utterance={utterance!r} language={language!r} "
+ f"got {v.refusal_text!r}"
+ )
+
+
+def test_spanish_turn_is_refused_in_spanish():
+ """The live defect: a Spanish-pinned user used to hear English."""
+ v = _refuse(EN_UTTERANCE, language="es")
+
+ assert v.refusal_text == _REFUSAL_ES["calendar"]
+ assert v.refusal_text != _REFUSAL_EN["calendar"]
+
+
+def test_bcp47_and_whisper_style_tags_are_accepted():
+ """The resolver's own tag shapes (``es-ES``, ``spanish``) must not miss."""
+ for tag in ("es", "es-ES", "spanish", "Español"):
+ assert _refuse(EN_UTTERANCE, language=tag).refusal_text == (
+ _REFUSAL_ES["calendar"]
+ )
+
+
+def test_unknown_or_missing_language_falls_back_to_the_utterance():
+ """Callers not yet passing the language keep working (no silent break)."""
+ assert _refuse(DE_UTTERANCE).refusal_text == _REFUSAL_DE["calendar"]
+ assert _refuse(EN_UTTERANCE).refusal_text == _REFUSAL_EN["calendar"]
+ # A tag outside de/en/es is not a pin — the utterance decides.
+ assert _refuse(DE_UTTERANCE, language="fr").refusal_text == (
+ _REFUSAL_DE["calendar"]
+ )
+
+
+def test_domain_fallback_phrase_also_follows_the_resolved_language():
+ """An unmapped domain uses that language's fallback, never English's."""
+ v = check_evidence_domain(
+ "What is in my inbox?",
+ enabled=True,
+ domains={"email": ["inbox"]},
+ capability_registry=CapabilityRegistry(),
+ domain_tool_map={},
+ language="es",
+ )
+ assert v.kind == "honest_refusal"
+ assert v.refusal_text == _REFUSAL_ES["email"]
diff --git a/tests/unit/plugins/tts/test_cartesia_tts.py b/tests/unit/plugins/tts/test_cartesia_tts.py
index 9324a2a562..32061cff35 100644
--- a/tests/unit/plugins/tts/test_cartesia_tts.py
+++ b/tests/unit/plugins/tts/test_cartesia_tts.py
@@ -230,16 +230,16 @@ async def test_language_code_de_picks_de_voice(patched_secret) -> None:
assert captured["voice"]["id"] == "DE-VOICE-UUID"
-async def test_text_heuristic_picks_de_when_caller_says_auto(patched_secret) -> None:
- """When the caller passes nothing or 'auto', the text-detect heuristic
- routes German-looking text to the DE voice."""
- tts = CartesiaTTS(
+def _lang_voice_tts() -> CartesiaTTS:
+ return CartesiaTTS(
voice_id="GENERIC",
voice_id_de="DE-VOICE-UUID",
voice_id_en="EN-VOICE-UUID",
voice_id_es="ES-VOICE-UUID",
)
+
+
+def _capturing_client(tts: CartesiaTTS) -> dict[str, Any]:
captured: dict[str, Any] = {}
async def fake_post(url: str, json: dict[str, Any]) -> _Resp:
@@ -249,33 +249,79 @@ async def test_text_heuristic_picks_de_when_caller_says_auto(patched_secret) ->
mock_client = AsyncMock()
mock_client.post = fake_post # type: ignore[assignment]
tts._client = mock_client
+ return captured
- [_ async for _ in tts.synthesize("Ich bin Jarvis und freue mich für Sie.")] # i18n-allow: German text synthesized to prove the German voice/locale is picked
- assert captured["voice"]["id"] == "DE-VOICE-UUID"
+ ("language_code", "expected"),
+ [
+ ("de-DE", "DE-VOICE-UUID"),
+ ("en-US", "EN-VOICE-UUID"),
+ ("es-ES", "ES-VOICE-UUID"),
+ ],
+)
+async def test_caller_language_alone_picks_the_voice(
+ patched_secret, language_code: str, expected: str
+) -> None:
+ """The turn's resolved output language decides the voice — for every locale.
+
+ The pipeline resolves the language ONCE per turn
+ (``resolve_output_language``) and passes it as ``language_code``. This
+ plugin must simply obey it; it has nothing to re-derive.
+ """
+ tts = _lang_voice_tts()
+ captured = _capturing_client(tts)
+
+ # Same words in every case, so only ``language_code`` can move the voice.
+ [_ async for _ in tts.synthesize("Jarvis.", language_code=language_code)]
+
+ assert captured["voice"]["id"] == expected
+
+
+async def test_english_text_with_german_lookalike_words_keeps_the_en_voice(
+ patched_secret,
+) -> None:
+ """Regression: the voice must never be sniffed out of the words.
+
+ The old heuristic matched the bare tokens "die"/"das"/"der"/"ist", so the
+ English idiom "the die is cast" was routed to the GERMAN voice and spoken
+ with German phonetics — the right words, rendered unintelligible.
+ """
+ tts = _lang_voice_tts()
+ captured = _capturing_client(tts)
+
+ [_ async for _ in tts.synthesize(
+ "The die is cast, and so the das ist question is moot.",
+ language_code="en-US",
+ )]
+
+ assert captured["voice"]["id"] == "EN-VOICE-UUID"
@pytest.mark.asyncio
-async def test_text_heuristic_picks_es_for_spanish_text(patched_secret) -> None:
+async def test_no_language_code_falls_back_to_the_configured_locale(
+ patched_secret,
+) -> None:
+ """A caller that omits the language gets the configured default, not a sniff.
+
+ ``language="de"`` configures the default locale, so German-looking text and
+ English-looking text must BOTH land on the DE voice — proof that nothing is
+ being read out of the transcript any more.
+ """
tts = CartesiaTTS(
voice_id="GENERIC",
voice_id_de="DE-VOICE-UUID",
voice_id_en="EN-VOICE-UUID",
voice_id_es="ES-VOICE-UUID",
+ language="de",
)
- captured: dict[str, Any] = {}
-
- async def fake_post(url: str, json: dict[str, Any]) -> _Resp:
- captured.update(json)
- return _Resp(200, content=b"\x00\x01" * 100)
-
- mock_client = AsyncMock()
- mock_client.post = fake_post # type: ignore[assignment]
- tts._client = mock_client
+ captured = _capturing_client(tts)
[_ async for _ in tts.synthesize("Hola, ¿cómo está? Gracias por su atención.")]
- assert captured["voice"]["id"] == "ES-VOICE-UUID"
+ assert captured["voice"]["id"] == "DE-VOICE-UUID"
@pytest.mark.asyncio