Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
fix(brain): stop sending real questions to the cheap model
Harald6f03dd9bbfe2
diff --git a/jarvis/brain/intent_router.py b/jarvis/brain/intent_router.pyindex 3c612fb2bf..f348a5ec22 100644--- a/jarvis/brain/intent_router.py+++ b/jarvis/brain/intent_router.py@@ -6,21 +6,32 @@ Orthogonal to the tier router from Phase 5 (`jarvis/brain/router.py`):chosen tier (fast / deep / code). Used by `BrainManager` once the tier selectionis fixed and a brain is being constructed from the fallback chain.-Goal: no extra LLM-call latency for routing. Heuristic-based:--- **FAST** (Haiku): simple actions, tool calls, smalltalk responses- Keywords: öffne, spawn, starte, klicke, tippe, sag, merk, zeig, such, etc. # i18n-allow- Heuristic: short (<80 chars), imperative, one clear verb + object--- **DEEP** (Opus): reasoning, analysis, planning, explaining, comparing, coding- Keywords: recherchiere, analysiere, plane, erkläre, vergleich, schreib, baue, # i18n-allow- debug, refactor, überlege, zusammenfass, etc. # i18n-allow- Heuristic: long, many subclauses, multiple aspects, question word + depth--- **CODE** (Jarvis-Agent Heavy-Worker): explicit coding tasks- Keywords: code, implementier, fix bug, review pr, git commit, test--On ambiguity → DEEP (the user must not think Jarvis is dumb).+Goal: no extra LLM-call latency for routing. Heuristic-based — but the heuristic+decides only when it can be RIGHT, and the capable model has the last word.++**The capable model is the default.** A keyword may promote a turn to CODE or+confirm DEEP, but no keyword may demote a substantive request to the cheap fast+tier. That is exactly what used to happen: a ~40-pattern substring list ran over+the whole utterance, so "Ok, kannst du mir bei meiner Steuererklärung helfen?" # i18n-allow+matched ``\\bok\\b``, silently took Haiku, and the user got a worse answer than+the product can produce — recorded in a debug log and nowhere else.++Two things, and only two, still reach FAST:++- **A closed-set one-shot** — a greeting, a thank-you, an acknowledgement, or a+ clock/date question. Matched against the WHOLE utterance, so a greeting that+ merely OPENS a real question no longer counts.+- **A short imperative command** — an action verb at the START, at most+ ``_MAX_ONE_SHOT_TOKENS`` words in total, no subclause, no question. "öffne # i18n-allow+ notepad", "klick auf submit". Anything longer carries reasoning the fast tier+ cannot do, so it goes to the capable model.++Everything else — including every unrecognised utterance — is DEEP. A wrong+DEEP costs latency and tokens; a wrong FAST costs the answer.++- **DEEP** (Opus): reasoning, analysis, planning, explaining, comparing, and+ the default for anything not proven trivial.+- **CODE** (Jarvis-Agent Heavy-Worker): explicit coding tasks."""from __future__ import annotations@@ -30,38 +41,108 @@ from typing import LiteralIntentLevel = Literal["fast", "deep", "code"]--# Simple actions / tool triggers (Haiku is sufficient).-_FAST_PATTERNS = [- # German — imperatives- r"\böffne\b", r"\bstart(e|et)?\b", r"\bstarte\b", r"\bspawn(e)?\b", # i18n-allow- r"\bklick(e|t)?\b", r"\btipp(e|t)?\b", r"\btype\b",- r"\bsag\b", r"\bsage\b", r"\bsprich\b",- r"\bzeig(e|t)?\b", r"\bliste\b", r"\bdisplay\b",- r"\bmach auf\b", r"\bmach zu\b", r"\bminimier\b", r"\bmaximier\b",- r"\bmerk dir\b", r"\bspeicher\b",- r"\bkopiere\b", r"\bfüg(e)? ein\b", # i18n-allow- r"\bsuch\b", r"\bfinde\b",- r"\bwie spät\b", r"\bdatum\b", # i18n-allow- r"\bwelcher tag\b",- # Englisch- r"\bopen\b", r"\bclose\b", r"\blaunch\b", r"\brun\b",- r"\bclick\b", r"\btype\b", r"\bshow\b", r"\blist\b",- r"\bremember\b", r"\bsave\b", r"\bcopy\b",- r"\bwhat time\b", r"\bwhat date\b",- # Hangup / Smalltalk- r"\bhallo\b", r"\bhi\b", r"\bguten morgen\b",- r"\bdanke\b", r"\bthank you\b", r"\bokay\b", r"\bok\b",+#: A one-shot imperative is short. Beyond this many words an utterance carries+#: qualifiers, context or a second thought — work for the capable model.+_MAX_ONE_SHOT_TOKENS = 6++_TOKEN_RE = re.compile(r"[\w'’-]+", re.UNICODE)++# Utterances that are complete in themselves and need no reasoning whatsoever.+# Matched against the WHOLE text (anchored), never as a substring: "danke" is a+# one-shot, "Danke, und wie geht das jetzt weiter?" is a real question.+_ONE_SHOT_PATTERNS = [+ # Greetings — DE / EN / ES+ r"hallo|hi|hey|moin|servus|na\b", # i18n-allow: DE greeting+ r"gu?ten\s+(?:morgen|tag|abend)", # i18n-allow: DE greeting+ r"hello|hey\s+there|good\s+(?:morning|afternoon|evening)",+ r"hola|buenos\s+d[íi]as|buenas\s+(?:tardes|noches)",+ # Thanks+ r"danke(?:\s+(?:sch[öo]n|dir|sehr|vielmals))?|vielen\s+dank", # i18n-allow: DE thanks+ r"thanks(?:\s+a\s+lot)?|thank\s+you|cheers",+ r"gracias(?:\s+mil)?|muchas\s+gracias",+ # Acknowledgements+ r"ok(?:ay)?|alles\s+klar|passt|verstanden|geht\s+klar", # i18n-allow: DE acknowledgement+ r"alright|all\s+right|got\s+it|understood|sounds\s+good|sure",+ r"vale|entendido|de\s+acuerdo",+ # Farewells+ r"tsch[üu]ss|ciao|bis\s+(?:sp[äa]ter|dann|morgen)|gute\s+nacht", # i18n-allow: DE farewell+ r"bye|goodbye|see\s+you|good\s+night",+ r"adi[óo]s|hasta\s+luego|buenas\s+noches",+ # Clock / date — a single lookup with one right answer.+ r"wie\s+sp[äa]e?t\s+(?:ist\s+es|haben\s+wir)", # i18n-allow: DE clock question+ r"wie\s?viel\s+uhr\s+(?:ist\s+es|haben\s+wir)", # i18n-allow: DE clock question+ r"welchen?\s+(?:tag|datum)\s+(?:ist|haben\s+wir)\s*(?:heute|wir)?", # i18n-allow+ r"welches\s+datum\s+(?:ist\s+heute|haben\s+wir)", # i18n-allow: DE date question+ r"what(?:'s|\s+is)\s+the\s+(?:time|date)|what\s+time\s+is\s+it",+ r"what\s+day\s+is\s+(?:it|today)",+ r"qu[ée]\s+hora\s+es|qu[ée]\s+d[íi]a\s+es(?:\s+hoy)?",]--# Complex reasoning tasks (Opus).+_ONE_SHOT_RE = re.compile(+ r"^(?:" + "|".join(_ONE_SHOT_PATTERNS) + r")[\s.!?,…]*$",+ re.IGNORECASE,+)++# A leading acknowledgement before the real request ("Ok, öffne Notepad"). # i18n-allow+# Stripped before the opener test so the ack does not hide the verb — and it+# cannot make a substantive turn fast, because the remainder still has to pass+# the opener AND the word cap.+_LEAD_IN_RE = re.compile(+ r"^(?:ok(?:ay)?|alles\s+klar|hey|hi|hallo|so|also|bitte|please|" # i18n-allow: DE lead-in+ r"und|and|y)\b[\s,.:;!–-]+",+ re.IGNORECASE,+)++# Imperative action verbs, anchored at the START of the utterance. A verb in the+# MIDDLE of a sentence is part of a description, not a command — that is how+# "such mal eine Lösung für mein Speicherleck" used to reach Haiku. # i18n-allow+_FAST_OPENER_PATTERNS = [+ # German imperatives+ r"[öo]e?ffne|mach|schlie[ßs]|beende|starte?|spawne?|f[üu]hr\s+aus", # i18n-allow: DE imperative+ r"klicke?|tippe?|dr[üu]cke?|scrolle?|wechsle?|springe?", # i18n-allow: DE imperative+ r"sage?|sprich|lies|zeige?|liste|nenne?", # i18n-allow: DE imperative+ r"minimiere?|maximiere?|schlie[ßs]e", # i18n-allow: DE imperative+ r"merk\s+dir|merke?|speichere?|kopiere?|f[üu]ge?\s+ein", # i18n-allow: DE imperative+ r"suche?|finde|[öo]e?ffne", # i18n-allow: DE imperative+ r"spiele?|stopp|pausiere?|stelle?\s+lauter|stelle?\s+leiser", # i18n-allow: DE imperative+ # English imperatives+ r"open|close|quit|launch|run|start|spawn|execute",+ r"click|type|press|scroll|switch|jump",+ r"say|read|show|list|display|name",+ r"minimi[sz]e|maximi[sz]e",+ r"remember|save|copy|paste",+ r"search|find|look\s+up",+ r"play|stop|pause|mute|unmute",+ # Spanish imperatives+ r"abre|cierra|inicia|lanza|ejecuta",+ r"haz\s+clic|escribe|pulsa|cambia",+ r"di|muestra|lista|lee",+ r"recuerda|guarda|copia|pega",+ r"busca|encuentra|reproduce|para|pausa",+]+_FAST_OPENER_RE = re.compile(+ r"^(?:" + "|".join(_FAST_OPENER_PATTERNS) + r")\b",+ re.IGNORECASE,+)++# A subclause turns a command into a request with reasoning in it. Any of these+# vetoes the fast route regardless of how short the utterance is.+_SUBCLAUSE_RE = re.compile(+ r"\b(?:weil|damit|obwohl|falls|sobald|w[äa]hrend|sodass|dass|ob|" # i18n-allow+ r"aber|oder|wenn|warum|wieso|weshalb|" # i18n-allow+ r"because|although|whether|unless|while|so\s+that|but|or|if|why|how\s+come|"+ r"porque|aunque|mientras|pero|si|por\s+qu[ée])\b",+ re.IGNORECASE,+)++# Complex reasoning tasks (Opus). These CONFIRM deep — they no longer have to+# fight a fast keyword for it, since deep is the default._DEEP_PATTERNS = [# German — `\w*` instead of `\b` at the end to catch conjugationsr"\brecherchier\w*", r"\banalysier\w*", r"\bplane\w*\b", r"\bplanung\b",- r"\berklär\w*", r"\bvergleich\w*", r"\bunterschied\w*", # i18n-allow+ r"\berkl[äa]r\w*", r"\bvergleich\w*", r"\bunterschied\w*", # i18n-allowr"\bschreib\w*", r"\bformulier\w*", r"\bverfass\w*",r"\bbau(e|t)?\b.*\bmir\b", r"\bentwickel\w*", r"\bentwerf\w*",- r"\büberleg\w*", r"\bdenk gründlich\b", r"\bnachdenk\w*", # i18n-allow+ r"\b[üu]berleg\w*", r"\bdenk gr[üu]ndlich\b", r"\bnachdenk\w*", # i18n-allowr"\bzusammenfass\w*", r"\bfass\w*.*zusammen",r"\bwarum\b", r"\bwieso\b", r"\bweshalb\b",r"\boptimier\w*", r"\bverbesser\w*",@@ -77,7 +158,7 @@ _DEEP_PATTERNS = [# Coding tasks are routed to the Jarvis-Agent heavy worker._CODE_PATTERNS = [- r"\bcode\b.*(für|for|write|schreib)", # i18n-allow+ r"\bcode\b.*(f[üu]r|for|write|schreib)", # i18n-allowr"\bimplementier\b", r"\bimplement\b",r"\bfix bug\b", r"\bfehler finden\b", r"\bdebug\b",r"\brefactor\b", r"\brefaktor\b",@@ -87,7 +168,6 @@ _CODE_PATTERNS = [r"\bpull request\b", r"\bpr\b.*?beschreib",]-_FAST_RE = re.compile("|".join(_FAST_PATTERNS), re.IGNORECASE)_DEEP_RE = re.compile("|".join(_DEEP_PATTERNS), re.IGNORECASE)_CODE_RE = re.compile("|".join(_CODE_PATTERNS), re.IGNORECASE)@@ -99,35 +179,54 @@ class RoutingDecision:matched: str = ""+def _is_short_imperative(text: str) -> bool:+ """True for a command that is provably a one-shot: verb first, and short.++ The word cap is the load-bearing part. "öffne notepad" is a one-shot; # i18n-allow+ "such mir raus, warum der Build seit gestern rot ist" opens with the same # i18n-allow+ kind of verb and is not.+ """+ stripped = _LEAD_IN_RE.sub("", text).strip()+ if not stripped or "?" in stripped:+ return False+ if not _FAST_OPENER_RE.match(stripped):+ return False+ if _SUBCLAUSE_RE.search(stripped):+ return False+ return len(_TOKEN_RE.findall(stripped)) <= _MAX_ONE_SHOT_TOKENS++def classify(user_text: str) -> RoutingDecision:- """Classifies user text as fast/deep/code. No LLM call."""+ """Classifies user text as fast/deep/code. No LLM call.++ Order matters: coding wins, then deep keywords, then the two proven-trivial+ fast routes, and DEEP takes everything left over.+ """t = user_text.strip()if not t:- return RoutingDecision(level="fast", reason="leer")+ return RoutingDecision(level="fast", reason="empty")# 1. Coding pattern takes precedence (will use the harness later)m = _CODE_RE.search(t)if m:return RoutingDecision(level="code", reason="code-keyword", matched=m.group(0))- # 2. Deep pattern beats fast pattern (user wants depth when detectable)+ # 2. An explicit reasoning verb confirms deep.m = _DEEP_RE.search(t)if m:return RoutingDecision(level="deep", reason="deep-keyword", matched=m.group(0))- # 3. Fast-Pattern- m = _FAST_RE.search(t)+ # 3. A closed-set one-shot: the WHOLE utterance is a greeting, a thank-you,+ # an acknowledgement, or a clock/date question.+ m = _ONE_SHOT_RE.match(t)if m:- return RoutingDecision(level="fast", reason="fast-keyword", matched=m.group(0))-- # 4. Length heuristic as tiebreaker- # Short statements → a simple answer is probably sufficient- if len(t) < 30:- return RoutingDecision(level="fast", reason="short-default")+ return RoutingDecision(level="fast", reason="one-shot", matched=m.group(0))- # Long / complex queries → Opus to ensure quality- if len(t) > 120 or t.count(",") >= 2 or t.count("?") >= 1:- return RoutingDecision(level="deep", reason="long-or-question")+ # 4. A short imperative command with no subclause and no question.+ if _is_short_imperative(t):+ return RoutingDecision(level="fast", reason="short-imperative")- # Default: mid-range fast — when in doubt use Haiku (speed > depth)- return RoutingDecision(level="fast", reason="default")+ # 5. Everything else gets the capable model. An utterance we cannot prove+ # trivial is not trivial — a wrong deep costs latency, a wrong fast costs+ # the answer.+ return RoutingDecision(level="deep", reason="capable-default")diff --git a/jarvis/brain/manager.py b/jarvis/brain/manager.pyindex 2072c3272c..52a1eb08c2 100644--- a/jarvis/brain/manager.py+++ b/jarvis/brain/manager.py@@ -23,8 +23,10 @@ Architecture:"""from __future__ import annotations+import astimport asyncioimport base64+import jsonimport loggingimport reimport time@@ -1479,13 +1481,14 @@ def _extract_leaked_spawn_call(text: str) -> dict[str, Any] | None:return None-def _looks_like_tool_use_leak(text: str) -> bool:- """True if ``text`` looks like a provider leaked a tool_use block as TEXT.+def _may_be_tool_use_leak(text: str) -> bool:+ """Cheap shape test: could ``text`` still turn out to be a leaked tool_use?- A natural voice reply never starts with ``[`` or ``{`` — structured JSON at- the very start (optionally inside a ```json fence) means the provider emitted- a function call as *content* instead of invoking it. Cheap enough to run on- the growing streamed buffer so the raw JSON is never handed to TTS.+ Structured JSON at the very start (optionally inside a ```json fence) is the+ only cue available while a stream is still growing. It is a SUSPICION, never+ a verdict — a perfectly good answer may open with a markdown link+ (``[Doku](…)``) or a JSON example. Use it only to WITHHOLD a chunk until the+ buffer is complete; :func:`_looks_like_tool_use_leak` then decides for real."""if not text:return False@@ -1498,6 +1501,55 @@ def _looks_like_tool_use_leak(text: str) -> bool:return s.startswith("[") or s.startswith("{")+def _is_whole_structured_document(text: str) -> bool:+ """True when ``text`` is ONE structured document and nothing else.++ ``[Doku](https://…) beschreibt das genau.`` opens with ``[`` but carries+ prose after the bracket — that is speech. ``{"exit_code": 0, …}`` and its+ Python-repr twin ``{'exit_code': 0, …}`` are blobs with no prose at all and+ must never reach TTS. Parsing decides; the first character does not.+ """+ s = text.strip()+ if s.startswith("```") and s.endswith("```") and len(s) > 6:+ s = s[3:-3].strip()+ if s[:4].lower() == "json":+ s = s[4:].strip()+ if not (s.startswith("[") or s.startswith("{")):+ return False+ try:+ json.loads(s)+ return True+ except (json.JSONDecodeError, ValueError):+ pass+ # A Python repr is not JSON but is just as unspeakable. Literals only —+ # ``literal_eval`` never executes anything. Bounded so a long prose answer+ # that merely opens with a bracket cannot cost real parse time.+ if len(s) > 20_000:+ return False+ try:+ ast.literal_eval(s)+ except (ValueError, SyntaxError, MemoryError, RecursionError):+ return False+ return True+++def _looks_like_tool_use_leak(text: str) -> bool:+ """True if ``text`` IS a provider's tool_use block emitted as TEXT.++ The authoritative verdict, for a COMPLETE buffer. The old test — "the text+ starts with ``[`` or ``{``" — was a suspicion promoted to a verdict: an+ answer opening with a markdown link or a JSON example was classed as a leak+ and, on the streaming path, silently dropped in full. So the shape test only+ gates the real check now: either the strict recovery parser finds an actual+ tool call, or the whole text is a structured document with no prose in it.+ """+ if not _may_be_tool_use_leak(text):+ return False+ if extract_leaked_tool_calls(text):+ return True+ return _is_whole_structured_document(text)++_CLI_TOOL_PREFIX = "cli_"# Lines a CLI prints when it wants interactive confirmation — never spoken._CLI_PROMPT_NOISE_RE = re.compile(@@ -1576,6 +1628,111 @@ def _evidence_answer_is_unverified(return bool((response_text or "").strip())+# A concrete particular — something the answer could only have if it had the+# data in front of it: a clock time, a calendar date, any figure, a named+# weekday or month, an address or link, a list of items, or a bare statement+# that there are none. Explanations and general knowledge carry none of these.+# Deliberately broad on the "specific" side: over-detecting costs one honest+# fallback, under-detecting speaks a confabulation.+_CONCRETE_DATUM_RE = re.compile(+ r"\d" # any figure at all+ r"|\bhttps?://|\bwww\.|@[\w.-]+\.\w{2,}" # a link or an address+ r"|^\s*[-*•]\s+.+$" # a bullet item+ r"|\b(?:"+ # Named days and months. DE / EN / ES — the answer surface is localized.+ r"montag|dienstag|mittwoch|donnerstag|freitag|samstag|sonnabend|" # i18n-allow+ r"sonntag|" # i18n-allow+ r"januar|februar|m[äa]rz|dezember|oktober|" # i18n-allow: DE months that differ from EN+ r"monday|tuesday|wednesday|thursday|friday|saturday|sunday|"+ r"january|february|march|april|may|june|july|august|september|october|"+ r"november|december|"+ r"lunes|martes|mi[ée]rcoles|jueves|viernes|s[áa]bado|domingo|"+ r"enero|febrero|marzo|abril|mayo|junio|julio|agosto|septiembre|"+ r"octubre|noviembre|diciembre"+ r")\b"+ # "you have none" is as much a claim about the data as naming an item. The+ # subject is required — a bare "kein"/"no" belongs to ordinary prose+ # ("not by a spark plug") and must not count.+ r"|\b(?:du\s+hast|es\s+(?:gibt|sind|ist))(?:\s+\w+){0,3}\s+" # i18n-allow: DE existence claim+ r"(?:keine?|nichts)\b" # i18n-allow: DE existence claim+ r"|\b(?:you\s+have|there\s+(?:is|are))(?:\s+\w+){0,3}\s+"+ r"(?:no|none|nothing)\b"+ r"|\b(?:tienes|hay)(?:\s+\w+){0,3}\s+(?:ning[úu]n\w*|nada)\b",+ re.IGNORECASE | re.MULTILINE,+)++# The answer attributes the fact to what was already said in this conversation.+# Repeating something the user themselves stated is not a fabrication, and no+# tool could have grounded it — the honest fallback would be the wrong answer.+_CONVERSATION_ATTRIBUTION_RE = re.compile(+ r"\b(?:"+ r"du\s+hattest\s+\w*\s?gesagt|du\s+sagtest|hattest\s+du\s+gesagt|" # i18n-allow+ r"wie\s+(?:du\s+)?(?:gesagt|erw[äa]hnt|besprochen)|" # i18n-allow: DE history reference+ r"vorhin\s+(?:gesagt|erw[äa]hnt)|laut\s+deiner\s+angabe|" # i18n-allow: DE history reference+ r"you\s+(?:said|told\s+me|mentioned)|as\s+you\s+(?:said|mentioned)|"+ r"earlier\s+you\s+(?:said|mentioned)|from\s+what\s+you\s+told\s+me|"+ r"(?:me\s+)?dijiste|seg[úu]n\s+me\s+dijiste|como\s+mencionaste"+ r")\b",+ re.IGNORECASE,+)+++# A claim about the mandated tool ITSELF — that it ran, refused, failed, or+# returned something. The 2026-06-17 confabulation was exactly this shape ("the+# gcloud tool blocked execution because it classified the request as an+# explanatory question"): no figure, no date, and entirely invented. Nothing the+# user said can excuse it, so it is never exempted by attribution.+_TOOL_NOUN_RE = re.compile(+ r"\b(?:tool|werkzeug|befehl|kommando|cli|api|abfrage|query|command|" # i18n-allow: DE tool noun+ r"skript|script|herramienta|comando|consulta)\w*",+ re.IGNORECASE,+)+_EXECUTION_VERB_RE = re.compile(+ r"\b(?:blockier\w*|verweiger\w*|abgelehnt|fehlgeschlagen|" # i18n-allow: DE execution verb+ r"zur[üu]ckgegeben|ausgef[üu]hrt|gelaufen|geliefert|aufgerufen|" # i18n-allow+ r"gestartet|" # i18n-allow+ r"block\w*|refus\w*|denied|deny|return\w*|fail\w*|ran|run|executed|"+ r"invoked|called|"+ r"bloque\w*|rechaz\w*|devolv\w*|fall\w*|ejecut\w*|llam\w*)\b",+ re.IGNORECASE,+)+++def _answer_claims_tool_behaviour(response_text: str) -> bool:+ """True when the answer says what the mandated tool did — it did nothing."""+ text = response_text or ""+ return bool(_TOOL_NOUN_RE.search(text) and _EXECUTION_VERB_RE.search(text))+++def _answer_claims_unverified_data(response_text: str) -> bool:+ """True when the answer reports a PARTICULAR the mandated tool never supplied.++ The evidence backstop used to replace *every* answer of a turn whose+ mandated tool did not run. That deleted correct answers: the model explains+ how something works, or repeats what the user said two turns ago, and the+ user hears "Ich konnte das gerade nicht abrufen" instead — the guard+ fabricating a failure to prevent a fabrication.++ So the backstop now needs an actual claim, of one of two kinds: a statement+ about what the mandated tool did (:func:`_answer_claims_tool_behaviour`), or+ a concrete particular (:data:`_CONCRETE_DATUM_RE`) that is not attributed to+ the conversation itself. An answer made of explanation alone claims nothing+ and stays.++ Pure regex, no LLM (AP-11). This judges DATA claims only — a false *action*+ claim ("I checked your calendar") carries no particular and is caught by+ :func:`replace_unbacked_action_claim` right after this guard.+ """+ text = (response_text or "").strip()+ if not text:+ return False+ if _answer_claims_tool_behaviour(text):+ return True+ if not _CONCRETE_DATUM_RE.search(text):+ return False+ return not _CONVERSATION_ATTRIBUTION_RE.search(text)++_EVIDENCE_UNFULFILLED_PHRASES: dict[str, str] = {"de": ("Ich konnte das gerade nicht abrufen — der Zugriff über das passende " # i18n-allow: German TTS@@ -1750,6 +1907,11 @@ def _unfulfilled_replacement(user to repeat a missing/broken field (e.g. the '@'-less email) is thedesired behavior, not a fake claim — only a flat confirmation with noquestion is corrected.++ A READ mandate leaves an answer that CLAIMS NOTHING intact: an explanation,+ or a fact the user themselves supplied earlier, is not a confabulation and+ must not be traded for "I couldn't retrieve that" (see+ :func:`_answer_claims_unverified_data`)."""if not _evidence_answer_is_unverified(required_tool, executed, response_text, suppressed=suppressed@@ -1759,6 +1921,8 @@ def _unfulfilled_replacement(if "?" in (response_text or ""):return None # honest clarifying question — keep itreturn _action_unfulfilled_answer(required_tool, lang=lang)+ if not _answer_claims_unverified_data(response_text):+ return None # nothing was claimed — nothing to correctreturn _evidence_unfulfilled_answer(lang=lang, domain=domain)@@ -11408,6 +11572,19 @@ class BrainManager:)return agg.text+ # ONE output-language resolution for every honesty phrase this turn+ # (CLAUDE.md §1: one resolver decides the turn for ALL layers). The two+ # guards below used to resolve separately with DIFFERENT defaults+ # ("de" here, DEFAULT_LOCALE there), so an undetectable turn could speak+ # a German evidence fallback followed by an English honesty phrase in the+ # same breath. All locales are equal — the shared DEFAULT_LOCALE decides.+ honesty_lang = resolve_output_language(+ self._reply_language,+ "unknown",+ user_text,+ default=DEFAULT_LOCALE,+ )+# Evidence-gate enforcement (live repro 2026-06-17, session 296abc82):# the gate MANDATED a tool this turn, but neither the normal tool loop# nor the leaked-tool recovery above actually ran it — so the model's@@ -11423,9 +11600,7 @@ class BrainManager:response_text=response_text,suppressed=self._last_turn_suppressed,is_write=self._evidence_required_is_write,- lang=resolve_output_language(- self._reply_language, "unknown", user_text, default="de"- ),+ lang=honesty_lang,domain=self._evidence_required_domain,)if _replacement is not None:@@ -11442,12 +11617,7 @@ class BrainManager:honest_response = replace_unbacked_action_claim(response_text,executed_tools=execution_evidence,- language=resolve_output_language(- self._reply_language,- "unknown",- user_text,- default=DEFAULT_LOCALE,- ),+ language=honesty_lang,)if honest_response != response_text:log.warning(@@ -11754,6 +11924,8 @@ class BrainManager:task = asyncio.create_task(_producer(), name="brain-stream-producer")accumulated = ""+ holding = False+ held = ""leaked = Falseyielded = Falseevidence_buffered = False@@ -11769,17 +11941,39 @@ class BrainManager:# scrub to silence and the action would be lost). generate()# recovers + executes the leaked tool and returns a speakable# result, which we yield once the stream ends.- if not leaked and _looks_like_tool_use_leak(accumulated):- leaked = True- if leaked:- continue- if getattr(self, "_evidence_required_tool", ""):+ #+ # A growing buffer cannot tell a leak from an answer that merely+ # OPENS with a bracket — "[Doku](…)", a JSON example. So the+ # shape test only HOLDS the chunks; the verdict is taken once,+ # after the sentinel, on the finished buffer. Held prose is+ # released there instead of being dropped for the rest of the+ # turn, which is what used to swallow such answers whole.+ if not holding and _may_be_tool_use_leak(accumulated):+ holding = True+ evidence_now = bool(getattr(self, "_evidence_required_tool", ""))+ if evidence_now:evidence_buffered = True+ if holding:+ held += chunk+ continue+ if evidence_now:continueif action_buffered:continueyield chunkyielded = True+ if holding:+ leaked = _looks_like_tool_use_leak(accumulated)+ if (+ not leaked+ and not evidence_buffered+ and not action_buffered+ and held.strip()+ ):+ # Never a tool call — ordinary speech that happened to open+ # with "[" or "{". The user gets the whole answer.+ yield held+ yielded = True# Surface generate()'s authoritative final text whenever NOTHING was# streamed to TTS — either because a leaked tool_use JSON was# withheld, OR because the brain produced a STRUCTURED / suppressdiff --git a/tests/unit/brain/test_evidence_enforcement.py b/tests/unit/brain/test_evidence_enforcement.pyindex 9e8fe6dabd..1df1b6a953 100644--- a/tests/unit/brain/test_evidence_enforcement.py+++ b/tests/unit/brain/test_evidence_enforcement.py@@ -8,8 +8,10 @@ mandated-tool turn whose tool never ran must never speak the model's(unverified) answer."""from jarvis.brain.manager import (+ _answer_claims_unverified_data,_evidence_answer_is_unverified,_evidence_unfulfilled_answer,+ _unfulfilled_replacement,)@@ -63,3 +65,91 @@ def test_unfulfilled_answer_unknown_language_falls_back_to_default():# An unrecognised code must degrade safely, never crash the spoken turn.fallback = _evidence_unfulfilled_answer(lang="fr")assert isinstance(fallback, str) and fallback.strip()+++# ---------------------------------------------------------------------------+# The backstop must not delete a correct answer (audit GT-18).+#+# `_evidence_answer_is_unverified` is true for EVERY answer of a mandated-tool+# turn whose tool did not run — including an explanation and a fact the user+# supplied two turns ago. Replacing those made the guard fabricate a failure to+# prevent a fabrication: the model answered correctly, the user heard+# "Ich konnte das gerade nicht abrufen". Only a concrete data claim is # i18n-allow+# replaced now.+# ---------------------------------------------------------------------------+++def _read_replacement(answer: str) -> str | None:+ return _unfulfilled_replacement(+ required_tool="list_calendar_events",+ executed=set(),+ response_text=answer,+ suppressed=False,+ is_write=False,+ lang="en",+ domain="calendar",+ )+++def test_general_knowledge_answer_is_kept():+ answer = (+ "A diesel engine ignites its fuel by compression heat, not by a spark "+ "plug."+ )+ assert _answer_claims_unverified_data(answer) is False+ assert _read_replacement(answer) is None+++def test_answer_attributed_to_the_conversation_is_kept():+ # The user themselves said it — no tool could have grounded it, and the+ # honest fallback would be the wrong answer.+ answer = "You said earlier that the meeting is on Monday."+ assert _answer_claims_unverified_data(answer) is False+ assert _read_replacement(answer) is None+++def test_clarifying_question_is_kept():+ answer = "Which period do you mean exactly?"+ assert _read_replacement(answer) is None+++def test_concrete_data_claim_is_still_replaced():+ for answer in (+ "You have an appointment tomorrow at 9:15 with Ms Meier.",+ "You have no appointments tomorrow.",+ "Your next appointment is on Thursday.",+ "- Standup\n- Review",+ "You have 3 unread messages from [email protected].",+ ):+ assert _answer_claims_unverified_data(answer) is True, answer+ assert _read_replacement(answer) is not None, answer+++def test_write_mandate_is_unchanged_by_the_data_claim_test():+ # A write is a say-do gap, not a data claim: a flat confirmation is still+ # corrected and a clarifying question is still kept.+ flat = _unfulfilled_replacement(+ required_tool="contact-upsert", executed=set(),+ response_text="Okay, all done.", suppressed=False, is_write=True,+ lang="en",+ )+ question = _unfulfilled_replacement(+ required_tool="contact-upsert", executed=set(),+ response_text="What is the email address?", suppressed=False,+ is_write=True, lang="en",+ )+ assert flat is not None+ assert question is None+++def test_confabulated_tool_behaviour_is_still_replaced():+ # The original live repro (2026-06-17, session 296abc82): the model invented+ # what the tool did. No figure, no date — and entirely made up.+ for answer in (+ "the gcloud tool blocked execution because it classified the request "+ "as an explanatory question",+ "Der Befehl ist fehlgeschlagen, deshalb habe ich nichts.", # i18n-allow+ "The CLI returned an empty result.",+ ):+ assert _answer_claims_unverified_data(answer) is True, answer+ assert _read_replacement(answer) is not None, answerdiff --git a/tests/unit/brain/test_honesty_language_parity.py b/tests/unit/brain/test_honesty_language_parity.pynew file mode 100644index 0000000000..43d226a96c--- /dev/null+++ b/tests/unit/brain/test_honesty_language_parity.py@@ -0,0 +1,49 @@+"""One output language per turn for every honesty phrase (audit OF-17).++The evidence-gate fallback and the action-honesty replacement sit two lines+apart in ``BrainManager.generate`` and used to resolve the turn's language+separately with DIFFERENT defaults — ``"de"`` here, ``DEFAULT_LOCALE`` there.+On a turn whose language cannot be detected (a bare product name, "42", a+grunt) the user could get a German refusal followed by an English honesty+phrase in the same breath.++CLAUDE.md §1: ONE resolver decides the turn for ALL layers, and every locale is+equal — no layer may pin its own default.+"""+from __future__ import annotations++import re+from pathlib import Path++from jarvis.core.turn_language import DEFAULT_LOCALE++_MANAGER = Path(__file__).resolve().parents[3] / "jarvis" / "brain" / "manager.py"+_RESOLVE_CALL_RE = re.compile(+ r"resolve_output_language\((?:[^()]|\([^()]*\))*\)", re.DOTALL+)+++def test_default_locale_is_not_german() -> None:+ # The whole point of the shared constant: nobody's mother tongue is the+ # silent winner of an undetectable turn.+ assert DEFAULT_LOCALE == "en"+++def test_no_output_language_call_pins_its_own_default() -> None:+ source = _MANAGER.read_text(encoding="utf-8")+ offenders = [+ call for call in _RESOLVE_CALL_RE.findall(source)+ if "default=" in call and "default=DEFAULT_LOCALE" not in call+ ]+ assert not offenders, (+ "resolve_output_language must use the shared DEFAULT_LOCALE: "+ f"{offenders}"+ )+++def test_the_two_honesty_guards_share_one_resolution() -> None:+ """The evidence fallback and the action-honesty guard read one variable."""+ source = _MANAGER.read_text(encoding="utf-8")+ assert "honesty_lang = resolve_output_language(" in source+ assert source.count("lang=honesty_lang") == 1+ assert source.count("language=honesty_lang") == 1diff --git a/tests/unit/brain/test_manager_streaming.py b/tests/unit/brain/test_manager_streaming.pyindex 87d46defed..5dc987cf78 100644--- a/tests/unit/brain/test_manager_streaming.py+++ b/tests/unit/brain/test_manager_streaming.py@@ -68,3 +68,100 @@ async def test_generate_stream_buffers_contextual_action_turn_until_final() -> Nassert await _collect_stream(manager, "What does it say?") == ["I did not start that action."]+++# ---------------------------------------------------------------------------+# Tool-use leak guard (audit OF-10).+#+# The guard used to fire when the ACCUMULATED buffer merely STARTED with "[" or+# "{", and the flag was sticky for the rest of the turn — every later chunk was+# dropped in silence. An answer opening with a markdown link or a JSON example+# lost the ENTIRE streamed reply. The shape test may now only HOLD the chunks;+# the verdict is taken once, on the finished buffer, with the real parser.+# ---------------------------------------------------------------------------+++async def test_stream_releases_answer_that_only_opens_like_json() -> None:+ manager = _bare_manager()++ async def fake_generate(user_text: str, **kwargs: Any) -> str:+ consumer = kwargs["text_consumer"]+ consumer("[Doku](https://example.com)")+ consumer(" covers it. ")+ consumer("The rest follows.")+ return "[Doku](https://example.com) covers it. The rest follows."++ manager.generate = fake_generate # type: ignore[method-assign]++ chunks = await _collect_stream(manager)+ assert "".join(chunks) == (+ "[Doku](https://example.com) covers it. The rest follows."+ )+++async def test_stream_releases_answer_opening_with_a_json_example() -> None:+ manager = _bare_manager()++ async def fake_generate(user_text: str, **kwargs: Any) -> str:+ consumer = kwargs["text_consumer"]+ consumer('{"name": "x"}')+ consumer(" is a valid configuration entry.")+ return '{"name": "x"} is a valid configuration entry.'++ manager.generate = fake_generate # type: ignore[method-assign]++ assert "".join(await _collect_stream(manager)) == (+ '{"name": "x"} is a valid configuration entry.'+ )+++async def test_stream_still_withholds_a_real_leaked_tool_use() -> None:+ manager = _bare_manager()++ async def fake_generate(user_text: str, **kwargs: Any) -> str:+ consumer = kwargs["text_consumer"]+ consumer('[{"type":"tool_use",')+ consumer('"name":"open_app",')+ consumer('"input":{"app":"notepad"}}]')+ return "Notepad is open."++ manager.generate = fake_generate # type: ignore[method-assign]++ # The raw envelope never reaches TTS; generate()'s spoken result does.+ assert await _collect_stream(manager) == ["Notepad is open."]+++async def test_stream_withholds_a_bare_structured_blob() -> None:+ """A whole-document blob is not speech even when it is not a tool call."""+ manager = _bare_manager()++ async def fake_generate(user_text: str, **kwargs: Any) -> str:+ consumer = kwargs["text_consumer"]+ consumer('{"query": "x", ')+ consumer('"results": []}')+ return "I found nothing for that."++ manager.generate = fake_generate # type: ignore[method-assign]++ assert await _collect_stream(manager) == ["I found nothing for that."]+++async def test_stream_held_prose_still_yields_to_the_evidence_gate() -> None:+ """Holding must not smuggle an unverified answer past the evidence gate."""+ manager = _bare_manager()++ async def fake_generate(user_text: str, **kwargs: Any) -> str:+ manager._evidence_required_tool = "cli_gcloud"+ consumer = kwargs["text_consumer"]+ consumer("[see the invoice](https://example.com)")+ consumer(" — 42 euros.")+ return "honest fallback"++ manager.generate = fake_generate # type: ignore[method-assign]++ assert await _collect_stream(manager) == ["honest fallback"]diff --git a/tests/unit/test_intent_router.py b/tests/unit/test_intent_router.pyindex 39c9880252..68e9d979bd 100644--- a/tests/unit/test_intent_router.py+++ b/tests/unit/test_intent_router.py@@ -70,3 +70,81 @@ def test_empty_defaults_to_fast():def test_long_unknown_falls_to_deep():long_text = ("Ich frage mich schon länger, wie man das " * 5) + "machen könnte?" # i18n-allowassert classify(long_text).level == "deep"+++# ---------------------------------------------------------------------------+# No silent downgrade (audit PR-07).+#+# A ~40-pattern keyword list ran over the whole utterance, so any hit anywhere+# routed the turn to the cheap fast model — "Ok, kannst du mir helfen …" matched # i18n-allow+# \bok\b and got Haiku. The user was never told; only a debug log recorded it.+# A keyword may no longer demote a substantive request: FAST needs either a+# closed-set one-shot or a short verb-first command.+# ---------------------------------------------------------------------------++[email protected]("text", [+ # A one-shot word that merely OPENS a real request.+ "Ok, kannst du mir helfen, meine Steuererklärung zu sortieren?", # i18n-allow+ "Okay, was hältst du von dieser Investitionsstrategie?", # i18n-allow+ "Hi, ich brauche Rat zu meinem Arbeitsvertrag", # i18n-allow+ "Danke, und wie geht das jetzt technisch weiter?", # i18n-allow+ # An action verb inside a request that needs reasoning.+ "such mal eine Lösung für mein Speicherleck im Renderer", # i18n-allow+ "zeig mir, welche Konsequenzen es hätte, wenn ich das Team halbiere", # i18n-allow+ "list the tradeoffs between a monolith and microservices for my team",+ "save me from this mess: the deploy keeps failing and I do not know why",+ "run me through the whole onboarding process step by step",+ "open question: should we migrate the database or not",+ "close reading of this contract clause, please",+ # A noun that happens to be a keyword.+ "Ich will das Datum meiner Hochzeit auf einen Tag legen, an dem alle können", # i18n-allow+ # Plain substantive turns with no keyword at all.+ "Sollte ich kündigen?", # i18n-allow+ "Erzähl mir was über Quantencomputer", # i18n-allow+ "Wie funktioniert eigentlich ein Dieselmotor", # i18n-allow+ "Was kostet mich das ungefähr im Monat?", # i18n-allow+])+def test_substantive_requests_keep_the_capable_model(text):+ d = classify(text)+ assert d.level != "fast", f"{text!r} was downgraded => {d}"++[email protected]("text", [+ "hallo",+ "danke schön", # i18n-allow+ "alles klar", # i18n-allow+ "thanks a lot",+ "gracias",+ "bis später", # i18n-allow+ "wie spät ist es?", # i18n-allow+ "what time is it",+])+def test_closed_set_one_shots_stay_fast(text):+ d = classify(text)+ assert d.level == "fast", f"{text!r} => {d}"+ assert d.reason == "one-shot"++[email protected]("text", [+ "öffne notepad", # i18n-allow+ "starte Chrome",+ "klick auf submit",+ "ok, öffne notepad", # i18n-allow — a lead-in does not hide the command+ "open notepad",+ "show me the time",+])+def test_short_verb_first_commands_stay_fast(text):+ d = classify(text)+ assert d.level == "fast", f"{text!r} => {d}"+++def test_unknown_utterance_defaults_to_the_capable_model():+ # The old router defaulted an unrecognised turn to Haiku ("speed > depth").+ assert classify("Mein Nachbar hat wieder was Merkwürdiges gebaut").level == "deep" # i18n-allow+ assert classify("Sag mal, was meinst du dazu, ehrlich gesagt").level == "deep" # i18n-allow+++def test_a_command_with_a_subclause_is_not_a_one_shot():+ assert classify("öffne den Editor, wenn die Datei existiert").level == "deep" # i18n-allow+ assert classify("open the file if the build is green").level == "deep"