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.

43.8 KB
Raw Blame
"""Output filter for the voice path — ``scrub_for_voice``.

Persona mandate phase 1: brain output → TTS path scrubs tool JSON,
stack traces, engineering jargon, self-reference, echo paraphrase, and
filler openers. Regex-only, NO LLM calls (latency-fatal, mandate § "DO NOT").

API:
    from dodaios.brain.output_filter import scrub_for_voice
    result = scrub_for_voice(text, language="en")
    result.cleaned        # scrubbed text, ready for TTS
    result.actions        # ["removed_tool_json", "rephrased_echo", ...]
    result.fallback_used  # True when the entire text was replaced by a standard phrase

Order of operations (stack trace is an early return):

    1. Stack trace → standard phrase, ``fallback_used=True`` (early return)
    2. Markdown strip (``**``, ``##``, ``` ``` ```, leading ``-``/``*``)
    3. Remove tool-call JSON (three forms: fn-call, inline, pure JSON)
    4. Remove self-reference ("Als KI", "Als Sprachmodell", "Ich bin nur")
    5. Echo paraphrase ONLY at opener position (``<= OPENER_BUDGET = 60`` chars)
    6. Remove filler openers ("Great question", "Wonderful question", ...)
    7. Remove engineering jargon (with whitelist protection via hyphen
       lookbehind/lookahead — compounds like "Browser-Provider" are preserved)
    8. Normalise whitespace

Failure mode 6 (mandate): echo paraphrase ONLY at opener position. Sometimes
the user genuinely wants an echo-style confirmation ("Du moechtest also den
Termin verschieben? Ja oder nein?") — that must not be destroyed.
"""
from __future__ import annotations

import re
from dataclasses import dataclass, field

from dodaios.i18n import catalog as i18n_catalog
from dodaios.speech.hangup import END_CALL_SIGNAL

# Mandate: user-concept words are sacred — NEVER scrubbed as jargon.
# Not referenced directly in a regex because they are not in ``JARGON_WORDS``
# anyway — the list serves as documentation and a fallback assertion
# (if someone later extends ``JARGON_WORDS``, the assert below catches it).
WHITELIST_WORDS: tuple[str, ...] = (
    "Datei", "Email", "Browser", "Terminal",
    "Notiz", "Termin", "Kalender",
)

# Mandate: engineering jargon — standalone words are scrubbed, but not
# inside hyphen-compounds ("Browser-Provider" is anchored to "Browser",
# a user-concept word, so the compound is preserved).
#
# 2026-08-18 audit OF-04: "Provider" and "MCP" are REMOVED from this list.
# Both became ordinary user-facing vocabulary — the app's own UI names brain
# providers and the MCP connector store — and the excision left a broken clause
# behind instead of a cleaner sentence ("Der Provider war nicht erreichbar." ->
# "Der war nicht erreichbar."; a bare "Provider." even fell through to the
# residue fallback and was spoken as an error). A noun cannot be deleted out of
# the middle of a sentence by regex; scrubbing it produces worse output than
# saying it. "Harness" and "Subprocess" stay — they name internals the user has
# no concept for and never appear as the subject of a user-facing sentence.
JARGON_WORDS: tuple[str, ...] = (
    "Harness", "Subprocess",
)

# Phase 1 extension 2026-04-28: engineering jargon compounds that, as a whole
# compound (with hyphen), reveal the implementation and have no user-concept
# anchor. Removed from output, including the surrounding clause when the
# compound is the subject. Probe-Drift 03/07/13 from 2026-04-28.
JARGON_COMPOUNDS: tuple[str, ...] = (
    "Sub-Agent", "Sub-Agenten",
    "Supervisor-Agent", "Supervisor-Agenten",
    "Subagent", "Subagenten",
)

# Defensive safety check: no whitelist word must appear in the jargon list.
# If that ever happens, the filter would kill one of the sacred user-concept
# words — a programming error.
assert not (set(WHITELIST_WORDS) & set(JARGON_WORDS)), (
    "Whitelist und Jargon-Liste ueberlappen — User-Konzept-Wort wuerde gescrubbt."
)

# Echo/filler patterns only in the first N characters. Mandate failure-mode 6.
OPENER_BUDGET = 60

FALLBACK_PHRASES: dict[str, str] = i18n_catalog.table("output_filter.fallback")


# ---------------------------------------------------------------------------
# Pattern definitions
# ---------------------------------------------------------------------------

# Stack trace: Python-style. Greedy up to double newline or end.
STACKTRACE_RE = re.compile(
    r"Traceback \(most recent call last\):.*?(?=\n\s*\n|\Z)",
    re.DOTALL,
)

# Raw data-structure dump guard (live bug 2026-06-22). A code path may ``str()``
# a tool-result container (dict / list of dicts) instead of humanizing it — e.g.
# the whole ``dispatch_to_harness`` result ``{'harness': 'screenshot',
# 'exit_code': 0, 'stdout': …, 'cost_usd': …, 'duration_ms': …}`` reached a
# readback verbatim. The per-pattern tool-leak rules below only catch SPECIFIC
# named shapes ({"tool":…}, XML, YAML, prose) and SPECIFIC keys, so a new result
# shape or a single-quoted Python repr slips through. This is the STRUCTURAL,
# key-independent, quote-style-independent guard that makes the whole bug class
# impossible at the common chokepoint: if the text OPENS with a container ``{``/
# ``[`` and carries a mapping signature (a quoted ``key:`` or a ``key='…'``
# repr), it is a machine dump, never a spoken sentence — fail-closed to the
# standard phrase, exactly like a stack trace. Real prose never opens with a
# brace, so this does not touch a humanized readback (which reads "Erledigt — …").
RAW_REPR_OPENER_RE = re.compile(r"^\s*[\{\[]")
REPR_SIGNATURE_RE = re.compile(
    r"['\"][^'\"]{0,120}['\"]\s*:"   # 'key': / "key":  (JSON or Python dict repr)
    r"|\b\w+\s*=\s*['\"]"            # key='…'          (Python kwargs/obj repr)
)

# Raw shell / PowerShell / .NET command guard (live bug 2026-06-28). The fast
# tier, on a garbled "navigate Discord" turn, emitted a SendKeys PowerShell
# command as its REPLY TEXT and TTS read it aloud "with special characters and everything"
# (Add-Type … [System.Windows.Forms.SendKeys]::SendWait('^(g)')). The tool-leak
# rules above only catch tool NAMES / JSON / XML — a bare command string has
# none of those, so it slipped through to TTS. Each alternative below is a
# code-ONLY signature that never appears in spoken German/English, so matching is
# fail-closed to the standard phrase (like a stacktrace) without touching prose:
#   * a [Namespace.Type]::Method static call (pure .NET/PowerShell)
#   * Add-Type / -AssemblyName / SendKeys (PowerShell-isms / Win32 API names)
#   * a $env:VAR reference
#   * an explicit shell invocation (cmd /c …, powershell -…, bash -c …)
SHELL_COMMAND_RE = re.compile(
    r"\[[\w.]+\]::\w+"
    r"|\bAdd-Type\b"
    r"|\b-AssemblyName\b"
    r"|\bSendKeys\b"
    r"|\$env:\w+"
    r"|\b(?:cmd\s+/c\b|powershell(?:\.exe)?\s+-[A-Za-z]|bash\s+-c\b)",
    re.IGNORECASE,
)

# 2026-08-18 audit OF-03: a SINGLE signature hit used to replace the WHOLE answer
# with the generic error phrase, which destroyed every shell how-to the user
# asked for ("In PowerShell liest du eine Variable mit $env:PATH aus." -> "Es
# trat ein Fehler auf."). The maintainer is a developer; "$env:", "[System.X]::Y",
# "Add-Type" and "bash -c" are normal parts of a CORRECT spoken answer. The guard
# now asks a second question before firing: is this text a COMMAND, or a SENTENCE
# that mentions one? The distinction is token shape, not token count — a command
# line is dominated by code tokens (flags, brackets, quotes, paths, ``::``),
# while an explanation is dominated by plain words.
#
# A token counts as CODE when it carries a character that spoken prose never
# has (brace/bracket/angle/pipe/backslash/dollar/equals/semicolon/quote/backtick,
# a ``::`` scope operator, a ``/`` path-or-flag separator) or when it is a
# ``-Flag`` / ``--flag``. A token counts as PROSE when it is nothing but letters
# plus optional trailing punctuation. Everything else (numbers, dotted
# identifiers, hyphenated names like "Add-Type") counts as neither, so it can
# neither rescue a command nor condemn a sentence.
_SHELL_CODE_TOKEN_RE = re.compile(r"[{}\[\]<>|\\$=;\"'`]|::|/|^-{1,2}[A-Za-z]")
_SHELL_PROSE_TOKEN_RE = re.compile(r"^[^\W\d_]{2,}[.,!?;:)\]\"']*$")
# A sentence needs a real clause worth of plain words before it earns the
# exemption, and the plain words must clearly outweigh the code tokens.
MIN_PROSE_TOKENS_FOR_SHELL_EXEMPTION = 4
PROSE_TO_CODE_RATIO_FOR_SHELL_EXEMPTION = 2

# Tool-call patterns:
#   1) tool_name({"...": "..."})       — function-call form (OpenAI)
#   2) tool_name{"...": "..."}         — Anthropic tool-use inline
#   3) {"tool": "..."} / {"op": "..."} — pure JSON
#   4) tool_name(key='val', ...)       — Python keyword args (probe-drift 12)
#   5) <tool_name>...</tool_name>      — XML tool-use (Anthropic-style leak)
#
# Patterns 4 and 5 are tool-name-specific (conservative) so harmless
# Python doc snippets ("``print(x=1)``") are not destroyed.
TOOL_NAMES: tuple[str, ...] = (
    # Current spawn tool name is ``spawn_worker``. The legacy ``spawn_openclaw``
    # and ``spawn_sub_jarvis`` names stay in the scrub list for backwards-compat
    # (old logs / replays must never leak the tool name into the voice path).
    "spawn_worker", "spawn_openclaw", "spawn_sub_jarvis",
    "dispatch_to_harness", "dispatch_to_admin",
    "run_shell", "screen_snapshot", "multi_spawn",
    "search_web", "open_app", "type_text", "click", "hotkey",
    "remember", "whoami", "execute_multi_action",
    "verify_via_curl", "verify_localhost", "start_preview_server",
)

# 2026-08-18 audit OF-06: this used to be ``\b\w+\s*\(\s*\{…\}\s*\)`` — ANY word
# followed by parentheses with braces, despite the comment above promising a
# conservative, tool-name-anchored set. It deleted ordinary sentences that named
# a function ("Rufe berechne({\"a\": 1}) auf, dann bist du fertig." -> "Rufe auf,
# dann bist du fertig."). Now anchored on TOOL_NAMES like patterns 4 and 5, so
# the promise in the comment is the actual behaviour.
TOOL_CALL_FN_RE = re.compile(
    r"\b(?:" + "|".join(TOOL_NAMES) + r")\s*\(\s*\{[^{}]*\}\s*\)",
)
TOOL_CALL_INLINE_RE = re.compile(
    r"\b\w+\{\"[^\"]+\"\s*:[^}]*\}",
)
#: A tool envelope, tolerating ONE level of nesting — ``"input": {...}`` is the
#: normal shape, and a pattern that cannot see past the inner object stops at
#: its closing brace and leaves a bare "}" standing in the spoken sentence
#: ("Ich öffne Spotify. }"). One level covers every envelope this codebase
#: emits; deeper nesting is not expressible in a regex and is out of scope for
#: a filter that must stay regex-only.
_TOOL_JSON_INNER = r"(?:[^{}]|\{[^{}]*\})"
TOOL_JSON_RE = re.compile(
    r"\{" + _TOOL_JSON_INNER + r"*?"
    r"\"(?:tool|action|op|command|name|args|parameters|utterance)\""
    r"\s*:\s*" + _TOOL_JSON_INNER + r"*\}",
    re.IGNORECASE,
)
# Tool name as a Python-style keyword call: ``spawn_openclaw(utterance='x', ...)``
TOOL_CALL_KW_RE = re.compile(
    r"\b(?:" + "|".join(TOOL_NAMES) + r")\s*\([^)]{0,2000}\)",
    re.DOTALL,
)
# XML tool tags incl. inner content: ``<spawn_openclaw>...</spawn_openclaw>``
TOOL_XML_RE = re.compile(
    r"<(?:" + "|".join(TOOL_NAMES) + r")\b[^>]*>"
    r".*?"
    r"</(?:" + "|".join(TOOL_NAMES) + r")>",
    re.DOTALL,
)

# Phase-1 extension 2 (later on 2026-04-28):
# Anthropic-internal ``<function_calls><invoke name="...">...</invoke></function_calls>``
# format. The brain occasionally leaks this verbatim into the output. The
# pattern matches the whole block, greedy up to the closing tag. Also a
# standalone ``<invoke>`` in case the ``</function_calls>`` wrapper is missing.
_FUNCTION_CALLS_TAG_RE = re.compile(r"<function_calls>|</function_calls>", re.IGNORECASE)


def _strip_function_call_blocks(text: str) -> str:
    """Remove every ``<function_calls>…</function_calls>`` block, in linear time.

    Same result as ``re.sub(r"<function_calls>.*?</function_calls>", "", text,
    flags=re.DOTALL | re.IGNORECASE)``: each block runs from the leftmost
    opener to the first closer after it. That lazy regex rescanned the rest of
    the text from every unclosed opener, which is quadratic on long LLM output
    (CodeQL py/polynomial-redos), so the tags are walked once instead. The two
    tags cannot overlap each other, so a single left-to-right token pass sees
    exactly the tags the regex would.
    """
    pieces: list[str] = []
    kept_from = 0
    block_start = -1
    for tag in _FUNCTION_CALLS_TAG_RE.finditer(text):
        closing = tag.group().startswith("</")
        if block_start < 0 and not closing:
            block_start = tag.start()
        elif block_start >= 0 and closing:
            pieces.append(text[kept_from:block_start])
            kept_from = tag.end()
            block_start = -1
    pieces.append(text[kept_from:])
    return "".join(pieces)


_UNICODE_DASH_RE = re.compile(r"[—–]")
_DOUBLE_HYPHEN_RE = re.compile(r"-{2,}")


def _collapse_unicode_dashes(text: str) -> str:
    """Replace each em/en dash and the blanks around it with ", ".

    Same result as ``re.sub(r"\\s*[—–]\\s*", ", ", text)``, in linear time:
    that pattern restarted ``\\s*`` at every position of a long blank run and
    rescanned the run each time (CodeQL py/polynomial-redos). Splitting at the
    dashes and trimming the blanks next to each cut is the same edit.
    """
    parts = _UNICODE_DASH_RE.split(text)
    if len(parts) == 1:
        return text
    last = len(parts) - 1
    return ", ".join(
        part.rstrip() if i == 0 else part.lstrip() if i == last else part.strip()
        for i, part in enumerate(parts)
    )


def _collapse_double_hyphens(text: str) -> str:
    """Replace each blank-framed ``--`` aside (and its blanks) with ", ".

    Same result as ``re.sub(r"\\s+-{2,}\\s+", ", ", text)``, in linear time
    (that pattern had the same restart problem as the dash rewrite above). A
    hyphen run counts only when blanks frame it on both sides; blanks already
    swallowed by the previous replacement cannot frame the next one.
    """
    pieces: list[str] = []
    kept_from = 0
    size = len(text)
    for run in _DOUBLE_HYPHEN_RE.finditer(text):
        start, end = run.span()
        left = start
        while left > kept_from and text[left - 1].isspace():
            left -= 1
        if left == start or end >= size or not text[end].isspace():
            continue
        right = end
        while right < size and text[right].isspace():
            right += 1
        pieces.append(text[kept_from:left])
        pieces.append(", ")
        kept_from = right
    pieces.append(text[kept_from:])
    return "".join(pieces)


ANTHROPIC_INVOKE_RE = re.compile(
    r"<invoke\b[^>]*>.*?</invoke>",
    re.DOTALL | re.IGNORECASE,
)

# Generic tool-wrapper tags such as ``<tool_call>...</tool_call>`` and
# ``<tool_response>...</tool_response>``. Conservatively limited to known
# wrapper names, so harmless XML/HTML in user content
# ("<tag>x</tag>" as example documentation) is not destroyed.
GENERIC_TOOL_WRAPPER_RE = re.compile(
    r"<(?:tool_call|tool_response|tool_use|function_results)\b[^>]*>"
    r".*?"
    r"</(?:tool_call|tool_response|tool_use|function_results)>",
    re.DOTALL | re.IGNORECASE,
)

# Base64 image drift: ``data:image/...;base64,<long-string>`` + long
# standalone base64 sequences (>=200 contiguous base64 chars).
# Re-probe-drift scenario 08 from 2026-04-28: the brain leaked an entire
# WebP image as the body string.
BASE64_DATA_URI_RE = re.compile(
    r"data:[a-zA-Z]+/[a-zA-Z0-9.+-]+;base64,[A-Za-z0-9+/=\s]+",
)

# Audit F-AUDIT-4 (2026-04-29): the brain leaks tool calls as a prose
# enumeration ("spawn_openclaw with utterance is X context_hints is Y
# action is Z target is W"). A probe from 2026-04-29 scenario 07 showed
# this in the voice output. This is neither JSON, YAML, nor XML — the
# filter had to be extended for this natural-language format.
#
# Pattern: tool name + " with " + one or more "<key> is <value>"
# phrases, separated by spaces or ".". Greedy up to a double newline
# or sentence boundary (max 600 chars as a safety cap).
TOOL_CALL_PROSE_RE = re.compile(
    r"\b(?:" + "|".join(TOOL_NAMES) + r")\s+with\s+"
    r"[\w\-]+\s+is\s+.*?"
    r"(?=\n\s*\n|\Z|(?<=\.)(?=\s+[A-ZÄÖÜ]))",  # i18n-allow: umlaut character class, sentence-boundary matching data
    re.DOTALL | re.IGNORECASE,
)
# Fallback: individual "<key> is <value>" phrases with tool-arg keys,
# even without a tool-name prefix (the brain may have omitted the tool name).
#
# 2026-08-18 audit OF-05: the key list is SPLIT by ambiguity. "utterance",
# "context_hints", "tool_hint" and "step_id" are tool vocabulary that never
# occurs in a spoken sentence, so one occurrence still identifies a leak. But
# "action" and "target" are ordinary English words, and a single one of them
# swallowed up to 400 characters of a correct answer ("Status: action is delayed
# until tomorrow because the server is down." -> "Status:."). They now only
# count inside a CHAIN — an "<key> is <value>" phrase directly followed by
# another one — which is the shape the F-AUDIT-4 leak actually had and which an
# ordinary sentence does not have.
TOOL_ARGS_PROSE_KEYS: tuple[str, ...] = (
    "utterance", "context_hints", "context hints",
    "tool_hint", "tool hint", "step_id", "step id",
)
TOOL_ARGS_PROSE_AMBIGUOUS_KEYS: tuple[str, ...] = (
    "action", "target",
)
_UNAMBIGUOUS_ARG_KEYS = "|".join(re.escape(k) for k in TOOL_ARGS_PROSE_KEYS)
_AMBIGUOUS_ARG_KEYS = "|".join(re.escape(k) for k in TOOL_ARGS_PROSE_AMBIGUOUS_KEYS)
_ANY_ARG_KEY = _UNAMBIGUOUS_ARG_KEYS + "|" + _AMBIGUOUS_ARG_KEYS
TOOL_ARGS_PROSE_RE = re.compile(
    r"\b(?:"
    # tool-only vocabulary — a single "<key> is <value>" is already a leak
    r"(?:" + _UNAMBIGUOUS_ARG_KEYS + r")\s+is\s+[^.\n]{1,400}"
    r"|"
    # ordinary words — only as the head of a chain of >= 2 arg phrases
    r"(?:" + _AMBIGUOUS_ARG_KEYS + r")\s+is\s+[^.\n]{1,400}?"
    r"\b(?:" + _ANY_ARG_KEY + r")\s+is\s+[^.\n]{1,400}"
    r")",
    re.IGNORECASE,
)
LONG_BASE64_RE = re.compile(
    r"[A-Za-z0-9+/=]{200,}",
)

# Web-search / SERP source artefacts (live forensic 2026-06-28, voice Turn 4).
# The brain occasionally reads a raw search hit verbatim — a title, a snippet,
# a URL, a bare domain, or the "Weitere Ergebnisse von <domain>" / "more results
# from <domain>" SERP footer — instead of synthesizing an answer (the whole
# DuckDuckGo result list incl. "26.06.2017 · …Weitere Ergebnisse von
# www.gutefrage.net" was spoken). The search_web tool result now instructs the
# brain to synthesize (primary fix); these patterns are the fail-closed defense
# so a source URL / domain / footer can never reach TTS. Real spoken prose has
# no http(s):// or bare www. token, so this does not touch a clean answer.
URL_RE = re.compile(r"https?://\S+", re.IGNORECASE)
# The SERP "more results from <source>" footer (de/en/es/pt). Cut it before the
# bare-www pass so "Weitere Ergebnisse von www.x.de" goes as one unit.
MORE_RESULTS_RE = re.compile(
    r"\b(?:weitere|mehr)\s+ergebnisse\s+(?:von|auf|bei)\s+\S+"  # de  # i18n-allow
    r"|more\s+results\s+(?:from|on|for)\s+\S+"                  # en
    r"|m[aá]s\s+resultados\s+(?:de|en|para)\s+\S+"              # es
    r"|mais\s+resultados\s+(?:de|do|da|em|no|na|para)\s+\S+",    # pt
    re.IGNORECASE,
)
# A bare www-prefixed domain reference ("www.gutefrage.net"). Anchored on the
# "www." token so a normal sentence is never touched (no false positive on a
# plain word that happens to contain a dot).
BARE_WWW_RE = re.compile(r"\bwww\.\S+", re.IGNORECASE)

# 2026-08-18 audit OF-07: the URL/domain passes used to DELETE the token, which
# left the preposition in front of it dangling ("Die Doku steht auf https://…
# und erklaert alles." -> "Die Doku steht auf und erklaert alles."). A spoken
# sentence needs an object where the link stood, so the link is REPLACED by a
# spoken placeholder instead of cut out. The source itself still never reaches
# TTS — the 2026-06-28 forensic was about the scheme, path and domain being read
# out character by character, and none of that survives. Runtime-output-language
# doctrine: all supported locales, no German default for a Spanish-pinned user.
SOURCE_LINK_PLACEHOLDER: dict[str, str] = {
    "de": "der Website",  # i18n-allow: spoken German placeholder (runtime voice output)
    "en": "the website",
    "es": "el sitio web",
    "pt": "o site",
}

# Markdown
MARKDOWN_BOLD_RE = re.compile(r"\*\*")
MARKDOWN_HEADER_RE = re.compile(r"^\s*#{1,6}\s+", re.MULTILINE)
CODE_FENCE_RE = re.compile(r"```[^`]*```", re.DOTALL)
INLINE_CODE_RE = re.compile(r"`([^`]+)`")
LIST_BULLET_RE = re.compile(r"^\s*[-*]\s+", re.MULTILINE)

# Self-Reference (DE+EN). Schneidet die ganze Klausel inkl. Satzpunkt weg.
SELF_REF_RE = re.compile(
    r"\b("
    r"Als KI|Als Sprachmodell|Ich bin nur|Ich bin lediglich|"
    r"As an AI|I'?m just a language model|I am a language model"
    r")\b[^.!?]*[.!?]?\s*",
    re.IGNORECASE,
)

# Background-action narration (DE+EN+ES). The maintainer finds it annoying when
# Jarvis ANNOUNCES internal bookkeeping it does silently in the background —
# "I'm noting that", "let me look at the last transcription", "ich notiere mir
# das", "ich schaue mir die letzte Transkription an", "tomo nota". The action  # i18n-allow: quoted German/Spanish input examples matching BACKGROUND_ACTION_RE below
# still happens; it is just never spoken. Cuts the whole narration clause incl.
# its sentence punctuation (same shape as SELF_REF_RE). Applies in BOTH normal
# and ack mode. The "look at the previous transcript/answer" alternatives are
# gated on a leading intent verb ("let me / I'll / ich schaue") so a content
# lead-in like "Looking at the data, the answer is X" is NOT stripped.
BACKGROUND_ACTION_RE = re.compile(
    r"\b("
    # --- noting / saving down (DE) ---
    r"ich notiere(?:\s+mir)?|"
    r"ich merke\s+mir|"
    r"ich halte\s+(?:das|es|alles)\s+fest|"
    # --- reviewing the previous transcript / answer (DE) ---
    r"ich (?:schaue|sehe|gucke)(?:\s+mir)?\b[^.!?]*?\b"
    r"(?:transkription|transkript|aufzeichnung|aufnahme|"
    r"(?:letzte|vorherige|bisherige)[ns]?\s+antwort)|"
    # --- noting (EN) — kept narrow ("noting/jotting", not "saving/recording",
    #     so a legit "I'm saving the file" confirmation is NOT stripped) ---
    r"(?:I'?m|I am)\s+(?:noting|jotting)\b(?:[^.!?]*?\bdown)?|"
    r"(?:I'?ll|I will)\s+(?:note|jot)\b|"
    r"(?:let me|I'?ll)\s+make\s+a\s+note|"
    # --- reviewing the previous transcript / answer (EN) ---
    r"(?:let me|I'?ll|I'?m going to|I will)\s+"
    r"(?:look at|check|review|pull up|go through)\b[^.!?]*?\b"
    r"(?:transcript(?:ion)?|recording|(?:last|previous|earlier|prior)\s+"
    r"(?:answer|response|conversation))|"
    # --- noting / reviewing (ES) — "anoto/apunto", not "guardo" (= save) ---
    r"tomo nota|"
    r"(?:lo|eso|esto)\s+(?:anoto|apunto)|"
    r"(?:voy a|d[eé]jame)\s+(?:revisar|mirar|ver|consultar)\b[^.!?]*?\b"
    r"(?:transcripci[oó]n|grabaci[oó]n|(?:[uú]ltima|anterior)\s+respuesta)"
    r")\b[^.!?]*[.!?]?\s*",
    re.IGNORECASE,
)

# Echo paraphrase — only at the opener (via position slicing in the
# function, not in the regex itself).
ECHO_PATTERNS: tuple[re.Pattern[str], ...] = tuple(
    re.compile(p, re.IGNORECASE) for p in [
        r"^\s*Du möchtest also\b[^.!?]*[.!?]\s*",  # i18n-allow: German echo-paraphrase matching data, checked against generated brain text
        r"^\s*Ich verstehe(?:,|\s+)?\s*dass\b[^.!?]*[.!?]\s*",
        r"^\s*If I understand correctly\b[^.!?]*[.!?]\s*",
        r"^\s*You'?d like me to\b[^.!?]*[.!?]\s*",
        r"^\s*Verstanden(?:,|\s+)?\s*du\b[^.!?]*[.!?]\s*",
    ]
)

# Filler opener — Phase-2 anti-pattern list from voice_e2e_probe.py,
# extended with filler self-reference ('Lass mich kurz', 'Let me think').
# The pattern matches ONLY at the opener; mid-sentence occurrences are
# preserved (failure-mode-6 analog).
FILLER_OPENER_RE = re.compile(
    r"^\s*("
    # Classic Phase-0
    r"Großartige Frage|Grossartige Frage|Tolle Frage|Geniale Frage|"  # i18n-allow: German filler-opener matching data, checked against generated brain text
    r"Great question|Excellent question|Good question|"
    # Phase-2 filler self-reference (ANTI_PATTERNS list in voice_e2e_probe.py)
    r"Lass mich kurz[^.!?]*?(?=[.!?,]|$)|"
    r"Let me think"
    r")[!.?,]*\s*",
    re.IGNORECASE,
)

# Engineering jargon — standalone words, not a hyphen compound.
# IMPORTANT: ``(?<!\w-)`` must come BEFORE the alternation, not after —
# a lookbehind at the regex end checks the 2 chars before match-END, not
# match-START. In an earlier draft this destroyed "Brain-Provider".
# See test ``test_clean_text_passes_through_unchanged[file-summary]``.
JARGON_RE = re.compile(
    r"(?<!\w-)"     # no "Browser-" / "Brain-" prefix in front
    r"\b(?:" + "|".join(JARGON_WORDS) + r")\b"
    r"(?!-\w)",     # no "-Server" / "-Provider" suffix allowed to follow
    re.IGNORECASE,
)

# Engineering jargon compounds (with hyphen) — stripped entirely, because
# they have no user-concept anchor ("Sub-Agent" has no whitelist anchor
# like "Browser" or "Datei"). The pattern matches the compound plus a
# following article/adverb phrase when the sentence starts with the
# compound, otherwise just the compound itself.
#
# 2026-05-24: the 2026-05-13 "OpenClaw is a brand name, let it through"
# exception is REVERSED. The internal worker was renamed to Jarvis-Agent — the
# retired "OpenClaw" subprocess no longer exists (the worker now runs Opus 4.7
# directly), so Jarvis must never say "OpenClaw" or "OpenClaw-Subagent" — that
# would claim a component that no longer exists. The negative lookbehind is
# removed, and LEGACY_BRAND_RE below strips the retired brand token itself.
JARGON_COMPOUND_RE = re.compile(
    r"\b(?:" + "|".join(re.escape(c) for c in JARGON_COMPOUNDS) + r")\b",
    re.IGNORECASE,
)

# 2026-08-24: the compound is REPLACED by the user-facing brand, not deleted.
# Live voice session 10:24: "…a complete overview using a Sub-Agent for your
# morning briefing…" was spoken as "…using a for your morning briefing…", and
# "Ich starte dafür einen Subagenten." became "Ich starte dafür einen."  # i18n-allow
# so Jarvis could not even announce what he was starting. This is exactly
# the failure the OF-04 audit recorded four lines above for "Provider" and
# "MCP": a noun cannot be deleted out of the middle of a sentence by regex,
# and a bare remnant falls through to the residue guard and is spoken as an
# error. The mandate itself is untouched — the user must not hear the
# internal compound — but "Agent" IS the user-facing name (the product surface
# is "<wake-name> Agent" and the app has an Agents board), so substituting it
# satisfies the mandate and leaves a sentence behind. Declension is preserved
# so the German accusative stays right ("einen Subagenten" -> "einen Agenten").
_JARGON_COMPOUND_BRAND = "Agent"


def _compound_to_brand(match: re.Match[str]) -> str:
    """Swap an internal agent compound for the user-facing brand word."""
    return (
        f"{_JARGON_COMPOUND_BRAND}en"
        if match.group(0).lower().endswith("en")
        else _JARGON_COMPOUND_BRAND
    )


# English needs "an" before the vowel the substitution introduces ("a Sub-Agent"
# -> "a Agent"). German articles are unaffected because they do not elide.
_A_BEFORE_AGENT_RE = re.compile(rf"\ba(?=\s+{_JARGON_COMPOUND_BRAND}\b)")

# 2026-05-24: strip the retired "OpenClaw" brand from voice output. Removes the
# "OpenClaw-" compound prefix ("OpenClaw-Mission" -> "Mission"; "OpenClaw-
# Subagent" -> "Subagent", which JARGON_COMPOUND_RE then drops) and any
# standalone "OpenClaw"/"OpenClore" (common STT mis-spelling of the brand).
#
# 2026-10-06: OpenClaw is also a society agent runtime now (docs/agent-runtimes.md).
# The runtime is real, so its name survives where it means the runtime: before
# "agent" ("your OpenClaw agent") and after "on/as/with/to" or their German
# forms ("moved to OpenClaw"). The retired worker compounds stay scrubbed.
LEGACY_BRAND_RE = re.compile(
    r"(?<!\bon\s)(?<!\bto\s)(?<!\bas\s)(?<!\bwith\s)"
    r"(?<!\bauf\s)(?<!\bals\s)(?<!\bmit\s)(?<!\bzu\s)"  # i18n-allow: German prepositions
    r"\bOpenCl(?:aw|ore)-?(?![-\s]?agent(?:en|s)?\b)",
    re.IGNORECASE,
)

# A1 drift (Mandate A1): remove the "Sir" honorific from the output.
# The pattern matches ``Sir`` as an honorific in three forms:
#   1) Opener with comma:   "Sir, ich starte..." -> "ich starte..."
#   2) Tail after comma:    "Erledigt, Sir."    -> "Erledigt."
#   3) Standalone word:     "Sir." (rare, but possible after honorific drift)
# Inside quotes (``"Yes, Sir, ..."``) it is NOT scrubbed — quote
# protection for song lyrics, quotations, films. Heuristic: if ``Sir``
# sits between two quotation marks, no match.
SIR_OPENER_RE = re.compile(r"^\s*Sir\s*,\s*", re.IGNORECASE)
SIR_TAIL_RE = re.compile(r",\s*Sir\b", re.IGNORECASE)
QUOTE_PROTECT_RE = re.compile(r'"[^"]*\bSir\b[^"]*"', re.IGNORECASE)

# Tool-args YAML block — probe-drift 03 from 2026-04-28. Detects YAML-like
# blocks with tool-arg keys such as ``context_hints:``, ``action:``,
# ``target:``, ``utterance:``. Greedy up to the next double newline or
# end — cuts out the whole YAML block.
TOOL_ARGS_YAML_KEYS: tuple[str, ...] = (
    "context_hints", "action", "target", "utterance",
    "tool_hint", "step_id", "args", "parameters",
)
TOOL_ARGS_YAML_RE = re.compile(
    r"(?:^|\n)"
    r"(?:" + "|".join(TOOL_ARGS_YAML_KEYS) + r")\s*:\s*"
    r"(?:.*?)"
    r"(?=\n\s*\n|\n[A-ZÄÖÜ][a-zäöüß]|\Z)",  # i18n-allow: umlaut character class, sentence-boundary matching data
    re.DOTALL | re.IGNORECASE,
)

# Post-scrub-residue threshold: after all filters run, the output must
# contain at least this many alphanumeric characters, otherwise it is
# recognized as a filter artifact and replaced by the standard phrase.
# Probe-drift 12 from 2026-04-28: output was a single ``}``.
MIN_MEANINGFUL_CHARS = 3


# ---------------------------------------------------------------------------
# API
# ---------------------------------------------------------------------------


@dataclass
class ScrubResult:
    """Result of ``scrub_for_voice``.

    Attributes:
        cleaned: The scrubbed text, ready for TTS.
        actions: List of operations performed, for telemetry/debug.
            Examples: ``"replaced_stacktrace"``, ``"removed_tool_json"``,
            ``"stripped_markdown"``, ``"removed_self_reference"``,
            ``"rephrased_echo"``, ``"removed_filler_opener"``,
            ``"removed_engineering_jargon"``.
        fallback_used: ``True`` when the entire text was replaced by a
            standard phrase (currently only on a stacktrace hit).
    """

    cleaned: str
    actions: list[str] = field(default_factory=list)
    fallback_used: bool = False


def _has_meaningful_content(text: str) -> bool:
    """``True`` when ``text`` still carries something worth speaking.

    Same threshold the post-scrub residue guard uses. Prose-shaping passes call
    it BEFORE committing their substitution, so a filter can never be the reason
    the whole answer disappears (2026-08-18 audit OF-02).
    """
    return sum(1 for c in text if c.isalnum()) >= MIN_MEANINGFUL_CHARS


def _is_prose_mentioning_code(text: str) -> bool:
    """``True`` when ``text`` is a SENTENCE that mentions a command, not a command.

    Token-shape heuristic behind the shell guard's prose exemption — see the
    comment at ``_SHELL_CODE_TOKEN_RE``. Regex-only, no LLM (mandate § "DO NOT").
    """
    prose = 0
    code = 0
    for token in text.split():
        if _SHELL_CODE_TOKEN_RE.search(token):
            code += 1
        elif _SHELL_PROSE_TOKEN_RE.match(token):
            prose += 1
    return (
        prose >= MIN_PROSE_TOKENS_FOR_SHELL_EXEMPTION
        and prose > PROSE_TO_CODE_RATIO_FOR_SHELL_EXEMPTION * code
    )


def scrub_for_voice(
    text: str, *, language: str = "en", ack_mode: bool = False
) -> ScrubResult:
    """Cleans up brain output for TTS synthesis.

    Args:
        text: The text to scrub (brain response, Jarvis-Agent summary,
            skill output, announcement text, ...).
        language: ``"de"`` or ``"en"`` — determines the fallback phrase
            on a stacktrace hit.
        ack_mode: ``True`` marks the call as a pre-thinking ack
            (flash brain). In ack_mode the ``FILLER_OPENER_RE`` pass is
            skipped, because flash-brain acks are explicitly allowed by
            the persona spec to use such openers ("Let me take a quick
            look.", "Let me check on that."). All other filters (blacklist,
            stacktrace, markdown, self-reference) stay active.

    Returns:
        ``ScrubResult`` with cleaned/actions/fallback_used.
    """
    if not text or not text.strip():
        return ScrubResult(cleaned="", actions=[], fallback_used=False)

    actions: list[str] = []

    # 1. Stacktrace: early return with the standard phrase. Mandate: "cut
    #    out entirely, replaced by the German fallback phrase".
    if STACKTRACE_RE.search(text):
        fallback = i18n_catalog.pick(FALLBACK_PHRASES, language)
        return ScrubResult(
            cleaned=fallback,
            actions=["replaced_stacktrace"],
            fallback_used=True,
        )

    # 1b. Raw data-structure dump: Early-Return mit Standard-Phrase. A text that
    #     OPENS with a container ({ / [) AND carries a mapping signature is a
    #     machine repr (a str()'d tool-result dict / JSON array), never a spoken
    #     sentence. Fail-closed at the common chokepoint so NO path — present or
    #     future — can ever speak/show a raw {'…': …} dump again (live bug
    #     2026-06-22: the whole dispatch_to_harness result reached a CU readback).
    if RAW_REPR_OPENER_RE.match(text) and REPR_SIGNATURE_RE.search(text):
        fallback = i18n_catalog.pick(FALLBACK_PHRASES, language)
        return ScrubResult(
            cleaned=fallback,
            actions=["replaced_raw_repr"],
            fallback_used=True,
        )

    # 1c. Raw shell / PowerShell / .NET command: Early-Return mit Standard-Phrase.
    #     A code-only signature (a [Type]::Method call, Add-Type/-AssemblyName/
    #     SendKeys, $env:, an explicit shell invocation) is never a spoken
    #     sentence, so the whole text is replaced rather than partially stripped
    #     (a half-spoken command is worse than the generic phrase). Live bug
    #     2026-06-28: TTS read a SendKeys PowerShell command aloud verbatim.
    #     Exemption (audit OF-03, 2026-08-18): a text whose tokens are dominated
    #     by plain words is an ANSWER that mentions a command, not a command —
    #     the developer asked how to read $env:PATH and must get the answer.
    if SHELL_COMMAND_RE.search(text) and not _is_prose_mentioning_code(text):
        fallback = i18n_catalog.pick(FALLBACK_PHRASES, language)
        return ScrubResult(
            cleaned=fallback,
            actions=["replaced_shell_command"],
            fallback_used=True,
        )

    out = text

    # 0. Hang-up control sentinel: the brain appends END_CALL_SIGNAL to signal
    #    session end. The signal is read upstream on the RAW response; here we
    #    guarantee it can never reach TTS (defense-in-depth). If the text was
    #    nothing but the token, return empty so the caller stays silent.
    if END_CALL_SIGNAL in out:
        out = out.replace(END_CALL_SIGNAL, "")
        actions.append("stripped_end_signal")
        if not out.strip():
            return ScrubResult(cleaned="", actions=actions, fallback_used=False)

    # 2. Markdown — code fences first (otherwise INLINE_CODE would grab the
    #    fence content). Inline code keeps the content, only backticks go.
    new = CODE_FENCE_RE.sub(" ", out)
    new = INLINE_CODE_RE.sub(r"\1", new)
    new = MARKDOWN_BOLD_RE.sub("", new)
    new = MARKDOWN_HEADER_RE.sub("", new)
    new = LIST_BULLET_RE.sub("", new)
    if new != out:
        actions.append("stripped_markdown")
        out = new

    # 3. Tool-Call-JSON / -KW / -XML / YAML-Args / Anthropic-Tags / Base64 —
    #    cut out every tool-use / internal leak.
    #    Order: the largest wrapper blocks first (function_calls,
    #    generic_tool_wrappers, base64_data_uri), then the remaining smaller
    #    patterns. Otherwise inner token patterns could match parts of the
    #    wrapper content and leave whitespace behind.
    new = _strip_function_call_blocks(out)
    new = ANTHROPIC_INVOKE_RE.sub("", new)
    new = GENERIC_TOOL_WRAPPER_RE.sub("", new)
    new = BASE64_DATA_URI_RE.sub("", new)
    new = LONG_BASE64_RE.sub("", new)
    new = TOOL_XML_RE.sub("", new)
    new = TOOL_CALL_FN_RE.sub("", new)
    new = TOOL_CALL_INLINE_RE.sub("", new)
    new = TOOL_JSON_RE.sub("", new)
    new = TOOL_CALL_KW_RE.sub("", new)
    new = TOOL_ARGS_YAML_RE.sub("", new)  # Phase-1 extension 2026-04-28
    # Audit F-AUDIT-4 (2026-04-29): tool args written as prose
    # ("X with utterance is Y context_hints is Z action is ...") — after
    # the YAML pattern, because the prose pattern is stricter (greedy up
    # to sentence end) and otherwise the YAML block would already be gone.
    new = TOOL_CALL_PROSE_RE.sub("", new)
    new = TOOL_ARGS_PROSE_RE.sub("", new)
    if new != out:
        actions.append("removed_tool_json")
        out = new

    # 3b. Web-search source artefacts — URLs, bare www-domains, and the
    #     "Weitere Ergebnisse von <domain>" / "more results from <domain>" SERP
    #     footer. The brain may read a raw search hit aloud instead of answering
    #     (live forensic 2026-06-28, Turn 4). The footer is cut FIRST, whole, so
    #     "von www.x.de" / "from https://x.de" goes as one unit — it is a SERP
    #     artefact, not a link the sentence refers to. A link the sentence DOES
    #     refer to is replaced by a spoken placeholder rather than deleted, so
    #     the preposition in front of it keeps its object (audit OF-07). Neither
    #     the scheme, the path nor the domain ever reaches TTS. Fail-closed
    #     defense; the real fix is the search_web answer_instruction that tells
    #     the brain to synthesize.
    placeholder = i18n_catalog.pick(SOURCE_LINK_PLACEHOLDER, language)
    new = MORE_RESULTS_RE.sub("", out)
    new = URL_RE.sub(placeholder, new)
    new = BARE_WWW_RE.sub(placeholder, new)
    if new != out:
        actions.append("removed_source_artifacts")
        out = new

    # 4. Self-Reference (ganze Klausel inkl. Satzpunkt entfernen)
    new = SELF_REF_RE.sub("", out)
    if new != out:
        actions.append("removed_self_reference")
        out = new

    # 4b. Background-action narration — the user never wants to HEAR that Jarvis
    # is noting/saving something or reviewing the last transcription/answer; it
    # happens silently in the background (maintainer mandate 2026-06-28). Cut the
    # whole narration clause (DE/EN/ES). Runs in both normal + ack mode.
    #
    # 2026-08-18 audit OF-02: the strip only commits when OTHER content survives
    # in the same text. "Ich merke mir das." IS the whole answer — a confirmation
    # the user asked for — and stripping it emptied the text, which then hit the
    # residue guard and came back as "Es trat ein Fehler auf.". The mandate is
    # "don't ANNOUNCE bookkeeping alongside the answer", not "never confirm".
    new = BACKGROUND_ACTION_RE.sub("", out)
    if new != out and _has_meaningful_content(new):
        actions.append("removed_background_action_narration")
        out = new

    # 5. Echo-Paraphrase NUR Opener (<=OPENER_BUDGET Zeichen).
    #    Mid-sentence Echo bleibt erhalten (Failure-Mode 6).
    head = out[:OPENER_BUDGET]
    tail = out[OPENER_BUDGET:]
    for pat in ECHO_PATTERNS:
        if pat.match(head):
            head = pat.sub("", head, count=1)
            actions.append("rephrased_echo")
            break
    out = head + tail

    # 6. Filler-Opener — skipped in ack_mode because Flash-Brain acks
    # are *meant* to look like contextual openers per persona spec
    # ("Lass mich kurz nachschauen.", "Let me check on that.").
    if not ack_mode:
        new = FILLER_OPENER_RE.sub("", out)
        if new != out:
            actions.append("removed_filler_opener")
            out = new

    # 7. Engineering-Jargon (Whitelist-Schutz via Bindestrich-Lookbehind)
    #    + Engineering-Compounds (Sub-Agent / Supervisor-Agent — Phase-1-
    #    Erweiterung 2026-04-28).
    new = LEGACY_BRAND_RE.sub("", out)
    new = JARGON_RE.sub("", new)
    new = JARGON_COMPOUND_RE.sub(_compound_to_brand, new)
    new = _A_BEFORE_AGENT_RE.sub("an", new)
    if new != out:
        actions.append("removed_engineering_jargon")
        out = new

    # 7b. A1 drift: remove the "Sir" honorific, with quote protection for quotations.
    #     (Mandate A1 + Phase-1 extension 2026-04-28.)
    quote_spans: list[tuple[int, int]] = [
        m.span() for m in QUOTE_PROTECT_RE.finditer(out)
    ]

    def _outside_quotes(match: re.Match[str]) -> bool:
        ms, me = match.span()
        return not any(qs <= ms and me <= qe for qs, qe in quote_spans)

    sir_changed = False
    # Opener: "Sir, ..." -> "..."
    m = SIR_OPENER_RE.match(out)
    if m and _outside_quotes(m):
        out = out[m.end():]
        sir_changed = True
    # Tail/Mid: ", Sir" -> ""
    def _sub_sir_tail(m: re.Match[str]) -> str:
        return "" if _outside_quotes(m) else m.group(0)
    new = SIR_TAIL_RE.sub(_sub_sir_tail, out)
    if new != out:
        sir_changed = True
        out = new
    if sir_changed:
        actions.append("removed_anrede_drift")  # i18n-allow: internal telemetry action-name identifier, not prose

    # 7c. Em dash / en dash -> comma (2026-06-29 "choppy voice" forensic). A
    #     parenthetical dash renders as a hard pause and a trailing half-sentence
    #     once a speech engine reads it. The persona forbids them, but any
    #     provider can still emit one, so collapse the Unicode dashes into a
    #     comma. Hyphen compounds ("Browser-Provider", "Sub-Agent") use a plain
    #     ASCII '-' with no surrounding whitespace and are NOT in the class below,
    #     so they survive untouched.
    new = _collapse_unicode_dashes(out)
    # ASCII double hyphen used as a dash-aside (" -- ") reads as the same hard
    # TTS pause; collapse it too (2026-06-30: the Unicode-only scrub missed it,
    # and several canned phrases / LLM outputs use " -- "). Require surrounding
    # whitespace so hyphen compounds ("T-Shirt") and numeric ranges ("20-30") —
    # which have no spaces — survive untouched.
    new = _collapse_double_hyphens(new)
    if new != out:
        actions.append("removed_em_dash")
        out = new

    # 7d. Numbers -> words. TTS reads a bare digit inconsistently across engines
    #     and locales, and the persona mandates spelling every number out as
    #     words. A flash-tier model still emits digits despite that rule, so this
    #     is the deterministic backstop (num2words, rule-based — NO LLM, AP-11
    #     safe). Locale-aware; a transparent no-op when num2words is missing.
    from dodaios.voice.number_speller import spell_out_numbers

    new = spell_out_numbers(out, language=language)
    if new != out:
        actions.append("spelled_out_numbers")
        out = new

    # 8. Normalise whitespace. After the first line every blank run is a
    #    single character, so the ``\s+`` patterns below cannot backtrack.
    out = re.sub(r"\s{2,}", " ", out).strip()
    out = re.sub(r"\s+([,.!?;:])", r"\1", out)
    # A dash->comma swap can leave a doubled or dangling comma; tidy it.
    out = re.sub(r",\s*(?=[,.!?;:])", "", out)
    out = re.sub(r",\s*$", "", out).strip()

    # 9. Post-scrub-residue fallback: if fewer than MIN_MEANINGFUL_CHARS
    #    alphanumeric characters remain after all filtering AND the filter
    #    actually did something (actions not empty), this is a filter
    #    artifact -> standard phrase. Probe-drift 12 from 2026-04-28.
    if actions:
        meaningful = sum(1 for c in out if c.isalnum())
        if meaningful < MIN_MEANINGFUL_CHARS:
            fallback = i18n_catalog.pick(FALLBACK_PHRASES, language)
            return ScrubResult(
                cleaned=fallback,
                actions=actions + ["replaced_with_fallback_residue"],
                fallback_used=True,
            )

    return ScrubResult(cleaned=out, actions=actions, fallback_used=False)


__all__ = [
    "ScrubResult",
    "scrub_for_voice",
    "WHITELIST_WORDS",
    "JARGON_WORDS",
    "OPENER_BUDGET",
    "FALLBACK_PHRASES",
    "SOURCE_LINK_PLACEHOLDER",
]