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
refactor(speech): extract the BUG-084 self-echo text guard into a shared SelfEchoGuard module
Ruben Lütke2611dc8e8e5c
diff --git a/jarvis/speech/echo_guard.py b/jarvis/speech/echo_guard.pynew file mode 100644index 0000000000..4e71d54d45--- /dev/null+++ b/jarvis/speech/echo_guard.py@@ -0,0 +1,130 @@+"""Self-echo TEXT guard shared by every voice surface (BUG-084, BUG-089).++Last line of defense behind the acoustic gates (barge-in energy floor,+post-TTS suppression window): when a "user" utterance that arrives during or+right after the assistant's own playback consists — fuzzily, STT garbles+echo — of nothing but words the assistant itself just spoke, it is the+speaker echo that slipped every acoustic gate, never a turn to answer.+Without this, ONE missed false barge loops forever: reply → echo transcribed+→ brain answers itself → new reply → new echo (the Mac test machine's+multi-turn self-conversation, 2026-07-18). Conservative by design:+near-total containment in the assistant's own recent words is required, so a+genuine user answer that ADDS anything is always kept (fail-open).++The logic originated as pipeline-private methods (BUG-084); it lives here so+the classic pipeline and the realtime session (BUG-089) share ONE+implementation instead of drifting copies. Deliberately dependency-light+(``re``/``difflib``/``deque``/``time`` only) so the optional realtime stack+imports it without touching the pipeline module.+"""++from __future__ import annotations++import difflib+import re+import time+from collections import deque++__all__ = ["SelfEchoGuard"]+++class SelfEchoGuard:+ """Remembers recently voiced assistant text and judges suspected echoes."""++ WINDOW_S = 6.0+ REF_TTL_S = 30.0+ MIN_TOKENS = 3+ MIN_OVERLAP = 0.8+ # 0.8, not lower: at 0.75 near-misses like "gut"→"guten" (ratio exactly+ # 0.75) count as contained and a genuine short user answer built from the+ # assistant's own words plus one inflected token would be eaten. Real STT+ # echo garble sits above 0.8:+ # "misch"→"mich" 0.89, "hörn"→"hören" 0.89. # i18n-allow: garble anchors+ FUZZY_CUTOFF = 0.8++ def __init__(self) -> None:+ # (slot, tokens, registered_ns); slot=None entries are append-only.+ self._refs: deque[tuple[str | None, list[str], int]] = deque(maxlen=8)+ self.activity_ns: int = 0++ @staticmethod+ def tokens(text: str) -> list[str]:+ return re.findall(r"\w+", text.lower())++ def register(self, text: str, *, slot: str | None = None) -> None:+ """Remember text the assistant is about to voice as an echo reference.++ ``slot`` makes a reference replaceable: re-registering the same slot+ removes the previous snapshot and appends the new one, so a cumulative+ per-turn transcript occupies ONE deque entry instead of evicting every+ other reference with its own growing prefixes.+ """+ tokens = self.tokens(text)+ if not tokens:+ return+ if slot is not None:+ for index, (ref_slot, _tokens, _ns) in enumerate(self._refs):+ if ref_slot == slot:+ del self._refs[index]+ break+ self._refs.append((slot, tokens, time.time_ns()))+ self.touch()++ def touch(self, activity_ns: int | None = None, *, force: bool = False) -> None:+ """Stamp "assistant audio is active around ``activity_ns``".++ Accepts a FUTURE stamp: the realtime session dates activity forward to+ the estimated physical playback drain, because provider audio arrives+ faster than realtime and the surface never reports the drain back. By+ default the stamp only ever advances, so a plain touch cannot pull an+ armed horizon back; ``force=True`` overwrites (barge-in/cancel resets+ the horizon to "now", tests set a synthetic past).+ """+ stamp = int(time.time_ns() if activity_ns is None else activity_ns)+ if force:+ self.activity_ns = stamp+ else:+ self.activity_ns = max(self.activity_ns, stamp)++ def is_echo(self, text: str) -> bool:+ """True when ``text`` is (fuzzily) contained in recent assistant speech.++ Only consulted while playback activity is recent (``WINDOW_S``);+ outside that window a user may echo the assistant verbatim all they+ want. Tokens match fuzzily (``difflib``-ratio ≥ ``FUZZY_CUTOFF``)+ because STT garbles echo (see the ratio anchors at ``FUZZY_CUTOFF``+ above). Utterances shorter than ``MIN_TOKENS`` are never judged —+ short commands ("stopp") must always reach their handlers. References+ are checked per spoken phrase plus the concatenation of the two newest+ phrases, so an echo spanning a sentence boundary still matches without+ building a big vocabulary union that common words could false-match.+ """+ if self.activity_ns <= 0:+ return False+ now_ns = time.time_ns()+ if now_ns - self.activity_ns > int(self.WINDOW_S * 1e9):+ return False+ utterance = self.tokens(text)+ if len(utterance) < self.MIN_TOKENS:+ return False+ ttl_ns = int(self.REF_TTL_S * 1e9)+ fresh = [tokens for _slot, tokens, ref_ns in self._refs if now_ns - ref_ns <= ttl_ns]+ if not fresh:+ return False+ candidates = list(fresh)+ if len(fresh) >= 2:+ candidates.append(fresh[-2] + fresh[-1])+ allowed_novel = len(utterance) // 6+ for reference in candidates:+ matched = sum(+ 1+ for token in utterance+ if token in reference+ or difflib.get_close_matches(token, reference, n=1, cutoff=self.FUZZY_CUTOFF)+ )+ if (+ matched / len(utterance) >= self.MIN_OVERLAP+ and (len(utterance) - matched) <= allowed_novel+ ):+ return True+ return Falsediff --git a/jarvis/speech/pipeline.py b/jarvis/speech/pipeline.pyindex d7a068c1da..e8c4ced1aa 100644--- a/jarvis/speech/pipeline.py+++ b/jarvis/speech/pipeline.py@@ -12,7 +12,6 @@ hotkeys remain active alongside wake detection.from __future__ import annotationsimport asyncio-import difflibimport enumimport hashlibimport logging@@ -113,6 +112,7 @@ from jarvis.speech.completion import ()from jarvis.speech.continuation_buffer import ContinuationBufferfrom jarvis.speech.continuation_window import ContinuationWindow+from jarvis.speech.echo_guard import SelfEchoGuardfrom jarvis.speech.hangup import (HANGUP_RE,contains_end_signal,@@ -6953,99 +6953,46 @@ class SpeechPipeline:log.info("TTS echo lock armed: %.1fs (%s).", seconds, reason)# --- Self-echo TEXT guard (BUG-084) --------------------------------- #- # Last line of defense behind the acoustic gates (barge-in energy floor,- # post-TTS suppression window): when a "user" utterance that arrives- # during / right after our own playback consists — fuzzily, STT garbles- # echo — of nothing but words Jarvis itself just spoke, it is the speaker- # echo that slipped every acoustic gate, never a turn to answer. Without- # this, ONE missed false barge loops forever: reply → echo transcribed →- # brain answers itself → new reply → new echo (the Mac test machine's- # multi-turn self-conversation, 2026-07-18). Conservative by design:- # near-total containment in the assistant's own recent words is required,- # so a genuine user answer that ADDS anything is always kept (fail-open).-- _ECHO_TEXT_GUARD_WINDOW_S = 6.0- _ECHO_TEXT_REF_TTL_S = 30.0- _ECHO_TEXT_MIN_TOKENS = 3- _ECHO_TEXT_MIN_OVERLAP = 0.8- # 0.8, not lower: at 0.75 near-misses like "gut"→"guten" (ratio exactly- # 0.75) count as contained and a genuine short user answer built from the- # assistant's own words plus one inflected token would be eaten. Real STT- # echo garble sits above 0.8:- # "misch"→"mich" 0.89, "hörn"→"hören" 0.89. # i18n-allow: German STT-garble ratio anchors under test- _ECHO_TEXT_FUZZY_CUTOFF = 0.8-- @staticmethod- def _echo_guard_tokens(text: str) -> list[str]:- return re.findall(r"\w+", text.lower())+ # The logic lives in jarvis.speech.echo_guard.SelfEchoGuard so the+ # realtime session shares ONE implementation (BUG-089) instead of a+ # drifting copy; these thin delegates keep the pipeline's historical+ # call sites and test surface unchanged.++ def _echo_text_guard(self) -> SelfEchoGuard:+ guard = getattr(self, "_self_echo_guard", None)+ if guard is None:+ guard = SelfEchoGuard()+ self._self_echo_guard = guard+ return guarddef _register_assistant_speech(self, text: str) -> None:"""Remember what Jarvis is about to voice as an echo-guard reference."""- tokens = self._echo_guard_tokens(text)- if not tokens:- return- refs = getattr(self, "_assistant_echo_refs", None)- if refs is None:- refs = deque(maxlen=8)- self._assistant_echo_refs = refs- refs.append((tokens, time.time_ns()))- self._touch_assistant_speech_activity()+ self._echo_text_guard().register(text)def _touch_assistant_speech_activity(self) -> None:"""Stamp 'assistant audio was active around now' for the echo guard."""- self._assistant_speech_activity_ns = time.time_ns()+ self._echo_text_guard().touch()def _looks_like_self_echo(self, text: str) -> bool:"""True when ``text`` is (fuzzily) contained in Jarvis' recent speech.- Only consulted while playback activity is recent- (``_ECHO_TEXT_GUARD_WINDOW_S``); outside that window a user may echo- Jarvis verbatim all they want. Tokens match fuzzily- (``difflib``-ratio ≥ ``_ECHO_TEXT_FUZZY_CUTOFF``) because STT garbles- echo (see the ratio anchors at ``_ECHO_TEXT_FUZZY_CUTOFF`` above).- Utterances shorter than ``_ECHO_TEXT_MIN_TOKENS`` are never judged —- short commands ("stopp") must always reach their handlers. References- are checked per spoken phrase plus the concatenation of the two- newest phrases, so an echo spanning a sentence boundary still matches- without building a big vocabulary union that common words could- false-match.+ See ``SelfEchoGuard.is_echo`` for the containment contract (activity+ window, fuzzy cutoff anchors, fail-open novelty allowance)."""- activity_ns = getattr(self, "_assistant_speech_activity_ns", 0)- if activity_ns <= 0:- return False- now_ns = time.time_ns()- if now_ns - activity_ns > int(self._ECHO_TEXT_GUARD_WINDOW_S * 1e9):- return False- utterance = self._echo_guard_tokens(text)- if len(utterance) < self._ECHO_TEXT_MIN_TOKENS:- return False- refs = list(getattr(self, "_assistant_echo_refs", ()) or ())- ttl_ns = int(self._ECHO_TEXT_REF_TTL_S * 1e9)- fresh = [tokens for tokens, ref_ns in refs if now_ns - ref_ns <= ttl_ns]- if not fresh:- return False- candidates = list(fresh)- if len(fresh) >= 2:- candidates.append(fresh[-2] + fresh[-1])- allowed_novel = len(utterance) // 6- for reference in candidates:- matched = sum(- 1- for token in utterance- if token in reference- or difflib.get_close_matches(- token, reference, n=1, cutoff=self._ECHO_TEXT_FUZZY_CUTOFF- )- )- if (- matched / len(utterance) >= self._ECHO_TEXT_MIN_OVERLAP- and (len(utterance) - matched) <= allowed_novel- ):- return True- return False+ return self._echo_text_guard().is_echo(text)++ @property+ def _assistant_speech_activity_ns(self) -> int:+ """Guard activity stamp, proxied for historical direct pokes."""++ return self._echo_text_guard().activity_ns++ @_assistant_speech_activity_ns.setter+ def _assistant_speech_activity_ns(self, value: int) -> None:+ self._echo_text_guard().touch(int(value), force=True)def _voice_confirm_pending(self) -> bool:"""True while the brain is awaiting a spoken yes/no for a deferreddiff --git a/tests/unit/speech/test_echo_guard.py b/tests/unit/speech/test_echo_guard.pynew file mode 100644index 0000000000..14d1553f9a--- /dev/null+++ b/tests/unit/speech/test_echo_guard.py@@ -0,0 +1,82 @@+"""Direct pins for the shared ``SelfEchoGuard`` (BUG-084 extraction, BUG-089).++The pipeline facade stays pinned by ``test_self_echo_guard.py``; these tests+cover the guard's own contract plus the two additions the realtime session+relies on: slot-replacement registration (one deque entry per cumulative turn+transcript) and the future-dated activity stamp (playback horizon). German+fixture strings quote the runtime voice product surface (the actual Mac+transcript).+"""++from __future__ import annotations++import time++from jarvis.speech.echo_guard import SelfEchoGuard+++def test_garbled_echo_fragment_is_flagged() -> None:+ guard = SelfEchoGuard()+ guard.register("Das freut mich zu hören.") # i18n-allow: voice fixture+ assert guard.is_echo("Misch zu hören") is True # i18n-allow: garbled echo+++def test_user_answer_with_novel_word_is_kept() -> None:+ guard = SelfEchoGuard()+ guard.register(+ "Guten Morgen, bei mir läuft alles bestens. Was geht bei dir?" # i18n-allow+ )+ assert guard.is_echo("bei mir läuft alles gut") is False # i18n-allow+++def test_slot_reregistration_replaces_instead_of_appending() -> None:+ guard = SelfEchoGuard()+ guard.register("Ich bin bereit", slot="turn:1") # i18n-allow: voice fixture+ guard.register(+ "Ich bin bereit für den Tag heute", # i18n-allow: voice fixture+ slot="turn:1",+ )+ assert len(guard._refs) == 1+ assert guard.is_echo("bereit für den Tag heute") is True # i18n-allow+++def test_growing_slot_snapshots_do_not_evict_other_references() -> None:+ # A cumulative turn transcript re-registers on every scrub-gate release;+ # its growing prefixes must occupy ONE entry, never flushing the canned+ # phrase reference out of the 8-slot deque.+ guard = SelfEchoGuard()+ guard.register(+ "Entschuldige, ich komme gerade nicht an mein Sprachmodell." # i18n-allow+ )+ for step in range(20):+ guard.register(+ "Alles klar " + "sehr " * step + "gerne", # i18n-allow: voice fixture+ slot="turn:1",+ )+ assert guard.is_echo("komme gerade nicht an mein Sprachmodell") is True # i18n-allow+++def test_future_dated_touch_keeps_guard_armed() -> None:+ # The realtime session stamps activity forward to the estimated playback+ # drain; the window check treats a future stamp as "active now".+ guard = SelfEchoGuard()+ guard.register("Das freut mich zu hören wirklich sehr") # i18n-allow+ guard.touch(time.time_ns() + int(30e9))+ assert guard.is_echo("freut mich zu hören wirklich") is True # i18n-allow+++def test_plain_touch_cannot_pull_back_an_armed_horizon() -> None:+ guard = SelfEchoGuard()+ future = time.time_ns() + int(30e9)+ guard.touch(future)+ guard.touch()+ assert guard.activity_ns == future+++def test_forced_touch_resets_the_horizon() -> None:+ # Barge-in/cancel pulls the horizon back to "now"; tests set a synthetic+ # past to lapse the window.+ guard = SelfEchoGuard()+ guard.register("Das freut mich zu hören.") # i18n-allow: voice fixture+ guard.touch(time.time_ns() - int(60e9), force=True)+ assert guard.is_echo("freut mich zu hören") is False # i18n-allow