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(wake): strict span-local confirm + mid-sentence recall, no dead time
rubenluetke10-beep32827fb5c39d
diff --git a/docs/BUGS.md b/docs/BUGS.mdindex 3109f2ffc4..fdb668625d 100644--- a/docs/BUGS.md+++ b/docs/BUGS.md@@ -9121,3 +9121,71 @@ opened, the panes were briefed, every receipt looked healthy — only therouting the user spoke was gone. When users hand out work they do it inexactly two ways, by NAME and by ENUMERATION; an executor that models onlythe collective address will mash both.++## BUG-133: the wake word fires on random words and goes deaf mid-sentence — the shape path's competition rubber-stamps the full ring while the isolation gate demands staged silence (HIGH, FIXED 2026-08-12)++**Symptoms (2026-08-12, vosk_kws, phrase "Hey George").** Both accuracy+directions broken at once. False fires: three activations this session, and+in two the free ear heard something with NO resemblance to the phrase — a+bare `'pedro'` (16:43:34) and `'age watch'` (16:09:32); a single random word+activated a two-word wake phrase. Missed activations: the phrase spoken in+the middle or at the end of a sentence never fired, and after normal speech+the user had to stay silent for seconds before the detector would accept the+real wake word again.++**Root — four causes stacked.** (1) The acoustic competition, the shape+path's only content gate, re-scored the WHOLE 3 s ring: forced alignment+over that much audio places the phrase anywhere and absorbs the rest into+"[unk]"s, so it kept the phrase at conf 1.0 for nearly any short speech+burst — 'pedro' won a competition it should have lost. (2) The shape path+demanded no prefix-part evidence, so one bare word could satisfy a+multi-part phrase. (3) The 2026-08-10 leading-isolation gate hard-rejected+any candidate with >0.25 s of voiced speech in the 0.6 s before it — the+mid-/end-of-sentence deafness and the "wait in silence" dead time, by+design. (4) The verify re-score pooled every phrase word anywhere in the+ring decode ('hey hey george hey [unk]' → min-conf over four entries, span+seconds wide), so an embedded wake failed the re-score even where it was+heard; rejected candidates then armed a 2 s verify backoff whose latch+kept the FIRST candidate and dropped everything after it.++**Fix.** `jarvis/plugins/wake/vosk_kws_provider.py`: the competition now+judges the SPAN-TRIMMED audio (±0.3 s pad) and offers the free ear's own+hypothesis as an explicit grammar alternative next to "<prefix> [unk]" and+"[unk]" — the decoder keeps the phrase only when the span's audio genuinely+supports it; unprefixed phrases compete too. The isolation gate is removed+(maintainer mandate: mid-sentence wakes must fire); shape durations are+clipped to the unpadded span so neighbouring sentence words no longer+overflow the call-sized budget. The re-score scores only an ADJACENT+in-order token run (scattered 'hey … george' never counts — a multi-part+wake is one unit) and retries over the trailing 1.8 s cut when the full+ring absorbed the phrase. A stage-1 hit during reject-backoff refreshes the+latch instead of dying in it.++**Evidence.** `scripts/vosk_wake_bench.py` (new): synthesized de+en voices+through the REAL detector and models, HEAD vs fixed on the SAME corpus+(stream-time clock, so backoff deadlines behave as in the live pipeline).+False fires 10/48 → 0/48 for "Hey George", and 0/144 across three phrases.+Positives 14/16 → 15/16 with end-of-sentence 3/4 → 4/4 — and the baseline's+embedded-wake numbers flatter it: the TTS renders comma pauses long enough+to satisfy the isolation gate, which real flowing dictation does not (the+live "wait in silence" reports). Generalization: "Hey Jarvis" 15/16,+"Hey Alex" (a hard first-name phrase) 14/16, all at zero false fires.+Borderline candidates may flicker ±1 between runs (Kaldi prewarm conf+jitter ≤0.09 at the 0.9 anchor); the negative classes are stable at zero.++**Guards:** `tests/unit/plugins/wake/test_vosk_wake_word_agnostic.py` —+'pedro' and the 2026-08-10 mid-dictation transcripts stay silent (by+content, not position), the mid-sentence spelled wake fires, the competition+provably receives span-trimmed audio plus the hypothesis, scattered phrase+parts never re-score, and the trailing-cut retry runs only after the full+ring failed.++**Lesson.** Position was standing in for content: the isolation gate+suppressed mid-speech fires because the competition could not discriminate+mid-speech audio — but the competition was weak only because it judged+audio the candidate never claimed. Trim the question to the claimed span+and give the decoder its own best alternative, and the position heuristic+(with its dead time) becomes unnecessary. A verify stage that pools+evidence across the whole window ('any phrase word anywhere') will both+under-accept the genuine embedded case and over-accept the scattered one;+score exactly the run that claims to be the phrase.diff --git a/jarvis/plugins/wake/vosk_kws_provider.py b/jarvis/plugins/wake/vosk_kws_provider.pyindex da6d5d0c52..f7abd22366 100644--- a/jarvis/plugins/wake/vosk_kws_provider.py+++ b/jarvis/plugins/wake/vosk_kws_provider.py@@ -263,32 +263,14 @@ SHAPE_WAKE = "wake" # looks like a call — competition confirms as bSHAPE_UNDECIDED = "undecided" # tokenisation/confidence contradicts — competition decidesSHAPE_SPEECH = "speech" # too much sound, or no name-sized body: never a wake-# --- leading isolation: a wake call STANDS ALONE (live forensic 2026-08-10) ---# Three fires in 94 s while the user dictated German to a coding agent-# (19:57:53 'herr tracks' undecided, 19:58:34 'hey george' SPELLED by the en-# model out of German flow, 19:59:27 'aufbürdet' undecided; i18n-allow:-# recognition content quoted from the live log). Two leaked through-# the acoustic competition — which measurably does not discriminate mid-stream-# audio (the forced grammar happily keeps the phrase at conf 1.0 inside flowing-# speech) — and one through the spelling path itself, so no per-path tightening-# can close the class.-#-# What every genuine call has and every one of these fires lacks is word--# agnostic and durational (AP-27-safe): a wake call stands alone, with silence-# immediately BEFORE it, while a forced hit on conversation has the previous-# word ending at the phrase's doorstep. Mid-speech no-fire is the ACCEPTED-# product trade-off (the maintainer explicitly chose it over mid-speech-# recall), so lead-in speech is a HARD rejection for BOTH confirm paths.-# Only the LEADING side is gated — trailing speech is the legitimate-# wake+command breath (2026-07-25) and stays untouched.-#-# Bounds: voiced overlap of strictly-preceding free-decode words with the-# ``_ISOLATION_LEAD_S`` window before the span may not exceed-# ``_ISOLATION_MAX_LEAD_VOICED_S`` (a syllable of slack for breath sounds and-# decoder timing jitter). Combined with the span's own 0.3 s guard this asks-# for ~0.65 s of quiet before the phrase — a natural pause, not a staged one.-_ISOLATION_LEAD_S = 0.6-_ISOLATION_MAX_LEAD_VOICED_S = 0.25+# (The former "leading isolation" gate — a hard rejection of any candidate+# with voiced speech in the 0.6 s before the span, added 2026-08-10 — was+# REMOVED 2026-08-12 by explicit maintainer mandate: the wake word must fire+# when spoken in the middle or at the end of a longer sentence, with no dead+# time after prior speech. The mid-stream precision it bought is now owed by+# the SPAN-TRIMMED, hypothesis-aware acoustic competition below, which was+# bench-measured to kill the same mid-dictation false-fire classes WITHOUT+# demanding silence before the phrase — see scripts/vosk_wake_bench.py.)# --- acoustic competition for the SHAPE path (live forensic 2026-07-17) -----# The shape gate accepts anything that LOOKS like a wake call — which a call of@@ -321,6 +303,16 @@ _COMPETITION_KIND = "competition"# spoken phrase plus lead-in at the moment the partial trigger fires._RING_SECONDS = 3.0+# Trailing-cut length for the SECOND grammar re-score attempt (embedded+# wakes). A candidate fires DURING the phrase and waits ~0.6 s of confirm+# tail, so at verify time the phrase occupies roughly the last 0.6-1.6 s of+# the ring; 1.8 s covers it plus alignment slack while excluding most of the+# preceding sentence — which is exactly what made the full-ring re-score+# deaf to a mid-/end-of-sentence wake (bench 2026-08-12: pos_mid/pos_end+# 0 % -> see scripts/vosk_wake_bench.py). Runs ONLY when the full-ring+# re-score failed, so an isolated call never pays it.+_RESCORE_TAIL_S = 1.8+# Refractory period after a fired wake._COOLDOWN_S = 5.0@@ -456,6 +448,7 @@ def candidate_shape_verdict(max_voiced_s_per_token: float = _SHAPE_MAX_VOICED_S_PER_TOKEN,max_other_word_conf: float = _SHAPE_MAX_OTHER_WORD_CONF,min_core_body_s: float = _SHAPE_MIN_CORE_BODY_S,+ span: tuple[float, float] | None = None,) -> str:"""Does the free ear's output AT the candidate span look like a wake call?@@ -495,14 +488,31 @@ def candidate_shape_verdict(Empty input is ``SHAPE_SPEECH``: the grammar claimed the phrase where thefree ear heard no speech at all.++ ``span`` (start_s, end_s — the UNPADDED phrase span from the grammar+ re-score) clips each word's duration contribution to the audio the phrase+ actually claims. Without it, a wake embedded in a sentence always fails+ the duration bounds: the ±0.3 s slack that selects ``local_words`` pulls+ the neighbouring sentence words in, and their full durations overflow a+ budget meant to measure the CALL (bench 2026-08-12: a genuine embedded+ 'Hey George' arrived as 'fetish hate you watch much' — 1.62 s voiced —+ and was hard-rejected). Clipping is pure timing arithmetic (AP-27-safe)+ and keeps the original rejection intact: a grammar hit STRETCHED across+ flowing speech has its span full of speech, clipped or not."""if not local_words:return SHAPE_SPEECH++ def _voiced(w: dict) -> float:+ start = float(w.get("start", 0.0))+ end = float(w.get("end", 0.0))+ if span is not None:+ start = max(start, span[0])+ end = min(end, span[1])+ return max(0.0, end - start)+n_tokens = max(1, len(normalize_phrase_for_match(phrase)))- voiced_s = sum(- max(0.0, float(w.get("end", 0.0)) - float(w.get("start", 0.0)))- for w in local_words- )+ voiced_s = sum(_voiced(w) for w in local_words)if voiced_s > max_voiced_s_per_token * n_tokens:return SHAPE_SPEECH# A confidently recognised wake prefix is expected evidence, not proof the@@ -525,10 +535,7 @@ def candidate_shape_verdict(# A phrase that IS nothing but prefixes ("Hey", "Hallo") has no core to# demand, so it must not be gated on a core duration.if not phrase_is_all_prefix:- core_body_s = sum(- max(0.0, float(w.get("end", 0.0)) - float(w.get("start", 0.0)))- for w in core_words- )+ core_body_s = sum(_voiced(w) for w in core_words)if core_body_s < min_core_body_s:return SHAPE_SPEECHcontested = len(local_words) > n_tokens + _SHAPE_TOKEN_SLACK@@ -545,6 +552,7 @@ def candidate_shape_ok(max_voiced_s_per_token: float = _SHAPE_MAX_VOICED_S_PER_TOKEN,max_other_word_conf: float = _SHAPE_MAX_OTHER_WORD_CONF,min_core_body_s: float = _SHAPE_MIN_CORE_BODY_S,+ span: tuple[float, float] | None = None,) -> bool:"""True only for an UNCONTESTED wake shape (see ``candidate_shape_verdict``).@@ -559,6 +567,7 @@ def candidate_shape_ok(max_voiced_s_per_token=max_voiced_s_per_token,max_other_word_conf=max_other_word_conf,min_core_body_s=min_core_body_s,+ span=span,) == SHAPE_WAKE@@ -602,8 +611,6 @@ class VoskKwsProvider:cooldown_s: float = _COOLDOWN_S,rejected_candidate_backoff_s: float = _REJECTED_CANDIDATE_BACKOFF_S,confirm_tail_s: float = _CONFIRM_TAIL_S,- isolation_lead_s: float = _ISOLATION_LEAD_S,- isolation_max_lead_voiced_s: float = _ISOLATION_MAX_LEAD_VOICED_S,# Production poll-loop parity: peak-normalize the confirm window to# -3 dBFS (gain capped at 40 dB) exactly like the other wake paths.target_peak: float = 0.7079,@@ -646,8 +653,6 @@ class VoskKwsProvider:0.0, float(rejected_candidate_backoff_s))self._confirm_tail_bytes = int(float(confirm_tail_s) * sample_rate) * 2- self._isolation_lead_s = float(isolation_lead_s)- self._isolation_max_lead_voiced_s = float(isolation_max_lead_voiced_s)self._target_peak = float(target_peak)self._max_gain = float(max_gain)self._models: dict[str, Any] = {}@@ -709,7 +714,6 @@ class VoskKwsProvider:self._stat_early_shown = 0self._stat_early_retracted = 0self._stat_suppressed_shape_competition = 0- self._stat_suppressed_lead_speech = 0# Rate limiter for the verify-suppression log. Every rejection used to# be DEBUG-only, so a dropped GENUINE wake left no production trace at# all: the log could not tell "never heard" from "heard, verified,@@ -808,9 +812,10 @@ class VoskKwsProvider:not await the full stock (see ``start``)."""limit = self._stock_target if target is None else target- kinds = ("grammar", "free") if self._competition_grammar is None else (- "grammar", "free", _COMPETITION_KIND,- )+ # The competition kind is stocked for EVERY phrase now: since+ # 2026-08-12 an unprefixed phrase competes too (against the free+ # ear's hypothesis and "[unk]") instead of standing unconditionally.+ kinds = ("grammar", "free", _COMPETITION_KIND)for path in self._model_paths:for kind in kinds:key = (path, kind)@@ -946,7 +951,6 @@ class VoskKwsProvider:"suppressed_shape_competition": (self._stat_suppressed_shape_competition),- "suppressed_lead_speech": self._stat_suppressed_lead_speech,}# -- early candidate (visual-only) ----------------------------------------@@ -1137,10 +1141,14 @@ class VoskKwsProvider:OVERLAPPING the span (±0.3 s) — the permissive sound match thenjudges what was said AT the candidate's position instead offishing the best pair out of three seconds of conversation.- 4. **Leading isolation**: a wake call STANDS ALONE — voiced free-decode- words immediately BEFORE the span reject the candidate outright,- ahead of both confirm paths (see the ``_ISOLATION_*`` note; live- forensic 2026-08-10, three mid-dictation fires in 94 s).+ 4. **Span-trimmed acoustic competition** (shape/undecided acceptances+ only): the candidate's OWN audio, cut to the phrase span, must be+ better explained by the configured phrase than by "<prefix> [unk]",+ plain "[unk]", or the free ear's own hypothesis — see+ ``_shape_competition_ok``. (This replaced the 2026-08-10 "leading+ isolation" silence-before-the-phrase gate on 2026-08-12: the+ maintainer mandated mid-sentence wakes, so precision now comes+ from judging the span's content, not its position.)On infrastructure errors the ``fail_open`` polarity decides: theauthoritative confirm accepts (a broken confirm must never eat a real@@ -1199,23 +1207,83 @@ class VoskKwsProvider:gres = grammar_future.result()fres = free_future.result()- gwords = [- w for w in gres.get("result", [])- if w.get("word") in self._grammar_words- ]- if self._phrase.lower() not in gres.get("text", "") or not gwords:+ def _rescored(res: dict, offset_s: float) -> tuple[list[dict], float] | None:+ """The best CONSECUTIVE phrase-token run in a grammar decode.++ The old check collected every occurrence of any phrase word in+ the whole decode ('hey hey george hey [unk]' -> four entries):+ the min-conf then included stray low-conf tokens far from the+ actual call and the span stretched across seconds — an+ embedded wake could never pass (bench 2026-08-12). Matching+ the phrase as an ADJACENT in-order token run scores exactly+ the words that ARE the call; the best-conf run wins. This is+ also the stricter reading: "hey ... george" with other words+ between the parts no longer counts as the phrase (a multi-part+ wake is one unit).++ ``offset_s`` shifts word times back into FULL-window seconds+ when the decode ran over a trailing cut of the window.+ """+ tokens = self._grammar_words+ result = [w for w in res.get("result", []) if isinstance(w, dict)]+ best: tuple[list[dict], float] | None = None+ for i in range(len(result) - len(tokens) + 1):+ run = result[i : i + len(tokens)]+ if [w.get("word") for w in run] != tokens:+ continue+ run_conf = min(float(w.get("conf", 0.0)) for w in run)+ if run_conf < self._min_final_conf:+ continue+ if best is None or run_conf > best[1]:+ best = (run, run_conf)+ if best is None:+ return None+ words, min_conf = best+ if offset_s:+ words = [+ {+ **w,+ "start": float(w.get("start", 0.0)) + offset_s,+ "end": float(w.get("end", 0.0)) + offset_s,+ }+ for w in words+ ]+ return words, min_conf++ scored = _rescored(gres, 0.0)+ if scored is None:+ # Embedded-wake retry (bench-measured 2026-08-12): over the+ # full 3 s ring the grammar decode of a wake spoken MID- or+ # END-of-sentence routinely absorbs the name into the+ # surrounding "[unk]"s ('hey [unk] [unk]') and the re-score+ # goes deaf — pos_mid/pos_end recall was 0. A second pass over+ # the trailing cut re-hears it. The 2026-07-10 objection to a+ # shorter-cut retry ("helped room speech more than genuine+ # calls") predates the span-trimmed hypothesis competition:+ # the extra candidates a permissive cut admits are now killed+ # downstream (same bench: 0/48 negative fires WITH this+ # retry), while the recall it buys is what makes a wake work+ # inside a flowing sentence at all.+ tail_samples = int(_RESCORE_TAIL_S * self._sample_rate)+ if len(window) > tail_samples:+ offset_s = (len(window) - tail_samples) / self._sample_rate+ pcm_tail = pcm[2 * (len(window) - tail_samples):]++ def _tail_pass() -> dict:+ g = self._take_verify_rec(model_path, "grammar")+ g.AcceptWaveform(pcm_tail)+ return _parse_recognizer_json(+ g.FinalResult(), where="verify.grammar_tail"+ )++ scored = _rescored(_tail_pass(), offset_s)+ if scored is None:self._log_suppression(- "re-score did not re-hear %r (heard %r)",+ "re-score did not re-hear %r reliably (heard %r)",self._phrase, gres.get("text", "")[:60],)return False- conf = min(w.get("conf", 0.0) for w in gwords)- if conf < self._min_final_conf:- self._log_suppression(- "re-score conf %.2f < %.2f for %r",- conf, self._min_final_conf, self._phrase,- )- return False+ gwords, conf = scoredstart_s = min(w.get("start", 0.0) for w in gwords)end_s = max(w.get("end", 0.0) for w in gwords)span_a = start_s - 0.3@@ -1243,32 +1311,13 @@ class VoskKwsProvider:]free_local = " ".join(w.get("word", "") for w in local_words)- # 4) leading isolation — a wake call STANDS ALONE (see the- # _ISOLATION_* note). Voiced duration of strictly-preceding free- # words inside the lead window; a HARD rejection for both confirm- # paths, ahead of spelling and shape alike, because the spelled- # path leaked too (live 2026-08-10: the en model spelled- # 'hey george' out of flowing German dictation). Reads only word- # TIMINGS, never text (AP-27).- lead_a = span_a - self._isolation_lead_s- lead_voiced = 0.0- for w in fres.get("result", []):- if float(w.get("end", 0.0)) >= span_a:- continue # candidate-adjacent or later: not lead-in- lead_voiced += max(- 0.0,- min(float(w.get("end", 0.0)), span_a)- - max(float(w.get("start", 0.0)), lead_a),- )- if lead_voiced > self._isolation_max_lead_voiced_s:- self._stat_suppressed_lead_speech += 1- self._log_suppression(- "lead-in speech %.2fs in the %.1fs before the span — "- "a wake call stands alone, this was mid-speech",- lead_voiced,- self._isolation_lead_s,- )- return False+ # 4) span-trimmed audio for the acoustic competition: the bytes of+ # the candidate span itself (±0.3 s pad), so the competition below+ # judges ONLY the audio the phrase claims to be — surrounding+ # sentence audio must not hand the forced alignment room to fake.+ # (The former hard "leading isolation" gate stood here until+ # 2026-08-12 — see the module-level note on its removal.)+ pcm_span = pcm[2 * a : 2 * b] if b > a else pcm# OPEN (2026-07-25, measured): a wake spoken in ONE breath with the# command is materially less likely to fire than an isolated call.# A command word starting inside the trailing 0.3 s slack is counted@@ -1323,9 +1372,17 @@ class VoskKwsProvider:# questions stay hard rejections — they measure how much sound was# made, never what it was.ok = sound_confirm(free_local, self._phrase, ratio=self._confirm_ratio)- shape = "" if ok else candidate_shape_verdict(local_words, self._phrase)+ shape = (+ ""+ if ok+ else candidate_shape_verdict(+ local_words, self._phrase, span=(start_s, end_s)+ )+ )if not ok and shape in (SHAPE_WAKE, SHAPE_UNDECIDED):- ok = self._shape_competition_ok(pcm, model_path)+ ok = self._shape_competition_ok(+ pcm_span, model_path, free_hypothesis=free_local+ )if not ok:self._stat_suppressed_shape_competition += 1if ok:@@ -1363,19 +1420,35 @@ class VoskKwsProvider:)return ok- def _shape_competition_ok(self, pcm: bytes, model_path: str | None) -> bool:+ def _shape_competition_ok(+ self, pcm: bytes, model_path: str | None, free_hypothesis: str = ""+ ) -> bool:"""Must the shape-only acceptance stand? Purely acoustic, fail-OPEN.- Re-scores the window with a grammar that offers the configured phrase- AND an explicit "<prefix> [unk]" competitor: the decoder itself decides- whether the name slot is better explained by the configured wake word- or by any other word. The window already passed the normal re-score,- the energy gate, and the shape gate — this only breaks the tie the- forced no-alternative grammar could not express (replay-calibrated- 2026-07-17: kills every shape-path foreign-name fire at a 1-2 %- genuine-recall cost; see the _COMPETITION_KIND note).+ Re-scores the candidate with a grammar that offers, next to the+ configured phrase, an explicit "<prefix> [unk]" competitor, a plain+ "[unk]", and — decisively — the free ear's OWN hypothesis for the+ span: the decoder itself chooses whether the audio is better explained+ by the configured wake word or by what the unconstrained pass actually+ heard there. The candidate already passed the normal re-score, the+ energy gate, and the shape gate — this breaks the tie the forced+ no-alternative grammar could not express.++ Two changes bench-measured on 2026-08-12 (scripts/vosk_wake_bench.py;+ live false fires 'pedro' / 'age watch' / 'hey nova' for "Hey George"):++ * ``pcm`` is the SPAN-TRIMMED audio, not the whole 3 s ring. Over the+ full ring the forced alignment could place the phrase anywhere and+ absorb the rest into [unk]s — it kept the phrase at conf 1.0 for+ nearly every short speech burst, so the competition confirmed+ random words. On the span alone the phrase must explain exactly the+ audio it claims.+ * ``free_hypothesis`` (the free decode's words at the span, in-vocab+ for the SAME model by construction) joins the alternatives. A+ decoder offered its own best guess next to the phrase only keeps+ the phrase when the audio genuinely supports it — 'peter' audio+ picks 'peter', a garbled genuine call still picks the phrase.- An unprefixed phrase has no competitor to offer — it always stands.Infrastructure errors accept (a broken extra check must never make thedetector deaf; the spelling path never consults this at all).@@ -1383,13 +1456,26 @@ class VoskKwsProvider:rather than only confirming a clean one. The fail-open polarity is keptdeliberately: it matches the authoritative confirm this runs inside, anda candidate only gets here after the grammar re-score (conf >= 0.9), the- energy gate and BOTH hard shape bounds — so a broken competitor- recognizer degrades to those four gates, not to no gate at all.+ energy gate and the hard shape bounds — so a broken competitor+ recognizer degrades to those gates, not to no gate at all."""- if self._competition_grammar is None:- return True+ alternatives = [self._phrase.lower()]+ raw_tokens = [t for t in self._phrase.lower().split() if t]+ if self._competition_grammar is not None and raw_tokens:+ alternatives.append(f"{raw_tokens[0]} [unk]")+ hypothesis = " ".join(free_hypothesis.lower().split())+ if hypothesis and hypothesis != self._phrase.lower():+ alternatives.append(hypothesis)+ alternatives.append("[unk]")try:rec = self._take_verify_rec(model_path, _COMPETITION_KIND)+ # The prewarmed stock recognizer carries the STATIC competitor+ # grammar; swap in the per-candidate alternatives when the vosk+ # build supports it (0.3.32+). Without SetGrammar the static+ # grammar still runs — a weaker but valid competition.+ set_grammar = getattr(rec, "SetGrammar", None)+ if callable(set_grammar):+ set_grammar(json.dumps(alternatives))rec.AcceptWaveform(pcm)res = json.loads(rec.FinalResult())if self._phrase.lower() not in res.get("text", ""):@@ -1503,14 +1589,24 @@ class VoskKwsProvider:recs = self._fresh_recs()if pending is not None:pending_tail += len(pcm)+ # Keep every model's stream fed during the tail/backoff wait so+ # their decode state stays aligned with the ring.+ found = await _in_pool(self._grammar_hit_all, recs, pcm)if backpressure_active:- # The retry is already latched. Advancing the ring is- # enough; do not spend stage-one or verifier work yet.+ if found is not None:+ # A NEWER hit refreshes the latch. The old behaviour+ # kept the first latched candidate and went deaf for+ # anything after it, so room speech rejected moments+ # earlier could hold the slot while the user's real+ # wake landed in it unheard ("say it twice"). Still+ # exactly ONE verify runs, at the same deadline — the+ # BUG-045 load bound is untouched.+ is_final_new, _conf_new, _path_new = found+ pending = found+ pending_tail = (+ self._confirm_tail_bytes if is_final_new else 0+ )continue- # Keep every model's stream fed during the tail wait so their- # decode state stays aligned with the ring. The verdict is- # irrelevant here — the latched candidate already won the slot.- await _in_pool(self._grammar_hit_all, recs, pcm)# A POSITIVE early check is already authoritative for this# candidate (later audio belongs to the session and cannot# revoke it — see _run_early_check). Waiting out the rest ofdiff --git a/scripts/vosk_wake_bench.py b/scripts/vosk_wake_bench.pynew file mode 100644index 0000000000..5ee121462a--- /dev/null+++ b/scripts/vosk_wake_bench.py@@ -0,0 +1,331 @@+"""Vosk wake-word benchmark — replay a synthesized corpus through the REAL path.++Companion to ``wake_bench.py`` (which benches the stt_match path): this one+measures the ``vosk_kws`` engine end-to-end — streaming grammar stage 1 plus+the full verify stack — against synthesized speech, with the real Vosk models+installed under ``data/wake_models/vosk/``. It exists so precision/recall+changes to the verify gates are MEASURED, never hunch-calibrated (the standing+rule on every ``_SHAPE_*`` / competition bound in the provider).++Corpus: synthesized once via ``edge-tts`` (network required on first run) into+``data/wake_bench_corpus/<phrase-slug>/`` and cached; ffmpeg converts to+16 kHz mono s16 WAV. Classes per phrase:++- ``pos_isolated`` — the phrase alone -> must fire+- ``pos_command`` — phrase + command in one breath -> must fire+- ``pos_mid`` — phrase EMBEDDED mid-sentence -> must fire+- ``pos_end`` — phrase at the END of a longer sentence -> must fire+- ``neg_random`` — unrelated words/sentences -> must stay silent+- ``neg_bare_core`` — the core word without its prefix -> must stay silent+- ``neg_bare_prefix``— the prefix without the core -> must stay silent+- ``neg_other_name``— "<prefix> <different name>" -> must stay silent+- ``neg_flow`` — flowing dictation without the phrase -> must stay silent++Examples:+ python scripts/vosk_wake_bench.py --phrase "Hey George"+ python scripts/vosk_wake_bench.py --phrase "Hey Jarvis" --json out.json+"""+from __future__ import annotations++import argparse+import asyncio+import contextlib+import json+import logging+import shutil+import subprocess+import sys+import unicodedata+from collections.abc import AsyncIterator+from dataclasses import dataclass, field+from pathlib import Path++REPO_ROOT = Path(__file__).resolve().parents[1]+sys.path.insert(0, str(REPO_ROOT))++from jarvis.core.protocols import AudioChunk # noqa: E402+from jarvis.plugins.wake.vosk_kws_provider import VoskKwsProvider # noqa: E402+from jarvis.speech.wake_constants import ( # noqa: E402+ phrase_core,+ resolve_vosk_model_paths,+)++SAMPLE_RATE = 16_000+CHUNK_MS = 100+CORPUS_ROOT = REPO_ROOT / "data" / "wake_bench_corpus"++# A small de+en voice mix: the live install pairs a German speaker with+# English wake phrases, so both accents matter for every class.+VOICES = (+ ("de", "de-DE-KatjaNeural"),+ ("de", "de-DE-ConradNeural"),+ ("en", "en-US-JennyNeural"),+ ("en", "en-GB-RyanNeural"),+)++# Sentence templates keyed by language; "{p}" is the phrase, "{c}" the core.+TEMPLATES: dict[str, dict[str, list[str]]] = {+ "pos_isolated": {+ "de": ["{p}!"],+ "en": ["{p}!"],+ },+ "pos_command": {+ "de": ["{p}, wie ist das Wetter heute?"], # i18n-allow+ "en": ["{p}, what's the weather today?"],+ },+ "pos_mid": {+ "de": ["Ich denke wir sind hier fertig, {p}, mach bitte weiter."], # i18n-allow+ "en": ["I think we are done here, {p}, please continue."],+ },+ "pos_end": {+ "de": ["Okay, das reicht jetzt, {p}."], # i18n-allow+ "en": ["Okay, that's enough for now, {p}."],+ },+ "neg_random": {+ "de": ["Pedro.", "Banane und Katalog.", "Wunderbar, vielen Dank."], # i18n-allow+ "en": ["Pedro.", "Banana and catalogue.", "Wonderful, thank you."],+ },+ "neg_bare_core": {+ "de": ["{c}.", "Ich habe gestern mit {c} gesprochen."], # i18n-allow+ "en": ["{c}.", "I talked to {c} yesterday."],+ },+ "neg_bare_prefix": {+ "de": ["Hey!", "Hey, hallo zusammen."], # i18n-allow+ "en": ["Hey!", "Hey, hello everyone."],+ },+ "neg_other_name": {+ "de": ["Hey Nova!", "Hey Peter!", "Hallo Florian!"], # i18n-allow+ "en": ["Hey Nova!", "Hey Peter!", "Hello Florian!"],+ },+ "neg_flow": {+ "de": [+ "Bitte speichere die Datei und öffne dann den Browser.", # i18n-allow+ "Der Termin morgen wird auf halb drei verschoben, sag allen Bescheid.", # i18n-allow+ ],+ "en": [+ "Please save the file and then open the browser with the new tab.",+ "The meeting tomorrow moves to half past two, please tell everyone.",+ ],+ },+}+++def _slug(text: str) -> str:+ folded = unicodedata.normalize("NFKD", text.lower())+ return "".join(c if c.isalnum() else "_" for c in folded).strip("_")+++@dataclass+class FileResult:+ path: Path+ cls: str+ fired: int = 0+ log_lines: list[str] = field(default_factory=list)+++def _to_wav(mp3: Path, out_wav: Path) -> None:+ """ffmpeg mp3 -> 16 kHz mono s16 WAV; removes the mp3 afterwards."""+ ffmpeg = shutil.which("ffmpeg")+ if ffmpeg is None:+ raise SystemExit("ffmpeg is required to build the corpus (not found on PATH)")+ subprocess.run(+ [ffmpeg, "-y", "-loglevel", "error", "-i", str(mp3),+ "-ar", str(SAMPLE_RATE), "-ac", "1", "-c:a", "pcm_s16le", str(out_wav)],+ check=True,+ )+ mp3.unlink(missing_ok=True)+++async def _synthesize(text: str, voice: str, out_wav: Path) -> None:+ """edge-tts -> mp3 -> ffmpeg -> 16 kHz mono s16 WAV (cached)."""+ if await asyncio.to_thread(out_wav.exists):+ return+ import edge_tts++ await asyncio.to_thread(out_wav.parent.mkdir, parents=True, exist_ok=True)+ mp3 = out_wav.with_suffix(".mp3")+ await edge_tts.Communicate(text, voice=voice).save(str(mp3))+ await asyncio.to_thread(_to_wav, mp3, out_wav)+++def _load_wav(path: Path) -> bytes:+ import wave++ with wave.open(str(path), "rb") as wf:+ assert wf.getframerate() == SAMPLE_RATE, path+ assert wf.getnchannels() == 1, path+ return wf.readframes(wf.getnframes())+++async def _chunks(pcm: bytes, clock: list[float]) -> AsyncIterator[AudioChunk]:+ """Chunk the padded stream and advance the STREAM clock per chunk.++ ``clock[0]`` drives the provider's ``_monotonic`` seam: the bench decodes+ faster than real time, so backoff/cooldown deadlines must follow stream+ time or a latched retry would never come due inside a file (the live+ pipeline gets real-time chunks, where the two clocks agree). The tail+ padding is generous on purpose: it carries the post-phrase seconds during+ which a latched candidate's backoff deadline expires.+ """+ chunk_bytes = SAMPLE_RATE * CHUNK_MS // 1000 * 2+ lead = b"\x00" * int(0.4 * SAMPLE_RATE) * 2+ tail = b"\x00" * int(4.0 * SAMPLE_RATE) * 2+ stream = lead + pcm + tail+ for i in range(0, len(stream), chunk_bytes):+ clock[0] = i / (SAMPLE_RATE * 2)+ yield AudioChunk(+ pcm=stream[i : i + chunk_bytes],+ sample_rate=SAMPLE_RATE,+ timestamp_ns=i * 1_000_000_000 // (SAMPLE_RATE * 2),+ )+++class _Capture(logging.Handler):+ def __init__(self) -> None:+ super().__init__(level=logging.DEBUG)+ self.lines: list[str] = []++ def emit(self, record: logging.LogRecord) -> None:+ with contextlib.suppress(Exception):+ self.lines.append(record.getMessage())+++async def _run_file(+ phrase: str, model_paths: list[str], shared_models: dict, wav: Path, cls: str+) -> FileResult:+ provider = VoskKwsProvider(+ phrase,+ model_path=model_paths[0],+ model_paths=model_paths,+ )+ provider._models = shared_models # share the loaded models across files+ provider._load_attempted = True+ clock = [0.0]+ provider._monotonic = lambda: clock[0] # stream time, see _chunks+ result = FileResult(path=wav, cls=cls)+ capture = _Capture()+ vlog = logging.getLogger("jarvis.wake.vosk")+ vlog.addHandler(capture)+ old_level = vlog.level+ vlog.setLevel(logging.DEBUG)+ try:+ async for _keyword in provider.detect(_chunks(_load_wav(wav), clock)):+ result.fired += 1+ finally:+ vlog.removeHandler(capture)+ vlog.setLevel(old_level)+ result.log_lines = [+ ln for ln in capture.lines+ if "verify OK" in ln or "SUPPRESSED" in ln or "WAKE fired" in ln+ ]+ return result+++async def _build_corpus(phrase: str) -> dict[str, list[Path]]:+ core = " ".join(phrase_core(phrase)).title()+ root = CORPUS_ROOT / _slug(phrase)+ out: dict[str, list[Path]] = {}+ jobs: list[tuple[str, str, Path]] = []+ for cls, by_lang in TEMPLATES.items():+ out[cls] = []+ for lang, voice in VOICES:+ for i, template in enumerate(by_lang[lang]):+ text = template.format(p=phrase, c=core)+ wav = root / cls / f"{voice}_{i}.wav"+ out[cls].append(wav)+ jobs.append((text, voice, wav))+ sem = asyncio.Semaphore(4)++ async def _one(text: str, voice: str, wav: Path) -> None:+ async with sem:+ await _synthesize(text, voice, wav)++ await asyncio.gather(*(_one(*j) for j in jobs))+ return out+++async def main() -> int:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--phrase", default="Hey George")+ parser.add_argument("--language", default="en", help="primary wake language")+ parser.add_argument("--json", default="", help="write raw results to this file")+ parser.add_argument("--verbose", action="store_true")+ args = parser.parse_args()++ model_paths = resolve_vosk_model_paths(args.language)+ if not model_paths:+ raise SystemExit("no Vosk models under data/wake_models/vosk/ — install one first")+ print(f"phrase={args.phrase!r} models={[Path(p).name for p in model_paths]}")++ corpus = await _build_corpus(args.phrase)++ # Load each model ONCE and share it across per-file providers (documented+ # Vosk multi-client pattern: one Model, many recognizers).+ loader = VoskKwsProvider(+ args.phrase, model_path=model_paths[0], model_paths=model_paths+ )+ for path in model_paths:+ await asyncio.to_thread(loader._ensure_model, path)+ shared_models = loader._models++ results: list[FileResult] = []+ for cls, files in corpus.items():+ for wav in files:+ res = await _run_file(+ args.phrase, model_paths, shared_models, wav, cls+ )+ results.append(res)+ if args.verbose:+ mark = "FIRE" if res.fired else " "+ print(f" [{mark}] {cls:15s} {wav.name}")+ for ln in res.log_lines:+ print(f" | {ln[:150]}")++ print()+ print(f"{'class':16s} {'files':>5s} {'fired':>5s} verdict")+ failures = 0+ by_class: dict[str, dict[str, int]] = {}+ for cls in TEMPLATES:+ rows = [r for r in results if r.cls == cls]+ fired = sum(1 for r in rows if r.fired)+ want_fire = cls.startswith("pos_")+ ok = fired == len(rows) if want_fire else fired == 0+ if not ok:+ failures += 1+ verdict = "ok" if ok else ("MISSED WAKES" if want_fire else "FALSE FIRES")+ by_class[cls] = {"files": len(rows), "fired": fired}+ print(f"{cls:16s} {len(rows):5d} {fired:5d} {verdict}")+ if not ok and not args.verbose:+ bad = [r for r in rows if bool(r.fired) != want_fire]+ for r in bad[:6]:+ print(f" -> {r.path.name}")+ for ln in r.log_lines[-2:]:+ print(f" | {ln[:150]}")++ if args.json:+ payload = json.dumps(+ {+ "phrase": args.phrase,+ "classes": by_class,+ "files": [+ {+ "path": str(r.path),+ "class": r.cls,+ "fired": r.fired,+ "log": r.log_lines,+ }+ for r in results+ ],+ },+ indent=2,+ )+ def _write_json() -> None:+ Path(args.json).write_text(payload, encoding="utf-8")++ await asyncio.to_thread(_write_json)+ print(f"raw results -> {args.json}")+ return 1 if failures else 0+++if __name__ == "__main__":+ raise SystemExit(asyncio.run(main()))diff --git a/tests/unit/plugins/wake/test_vosk_wake_word_agnostic.py b/tests/unit/plugins/wake/test_vosk_wake_word_agnostic.pyindex 525374d301..f42856c525 100644--- a/tests/unit/plugins/wake/test_vosk_wake_word_agnostic.py+++ b/tests/unit/plugins/wake/test_vosk_wake_word_agnostic.py@@ -246,7 +246,13 @@ def test_verify_fires_on_a_wake_the_free_ear_could_not_spell(monkeypatch) -> Nondef test_verify_still_rejects_room_speech_forced_onto_the_phrase(monkeypatch) -> None:- """The precision contract the free-ear check was added for stays intact."""+ """The precision contract the free-ear check was added for stays intact.++ Since the span-duration clipping (2026-08-12) this fixture sits at the+ duration bound and is decided by the span-trimmed competition; on+ unrelated flowing speech the decoder keeps the alternative ("[unk]"+ scripted — the measured outcome, 0/48 negative fires on the bench).+ """p = VoskKwsProvider("Hey Ruben", model_path="fake", keyword="ruben")grammar = {@@ -266,8 +272,9 @@ def test_verify_still_rejects_room_speech_forced_onto_the_phrase(monkeypatch) ->_w("gibt", 1.40, 1.70, conf=1.0),],}+ competition = {"text": "[unk]", "result": []}- monkeypatch.setattr(p, "_take_verify_rec", _stub_take(grammar, free))+ monkeypatch.setattr(p, "_take_verify_rec", _stub_take(grammar, free, competition))assert p._verify_window(_loud_window(), fail_open=True) is False@@ -361,11 +368,32 @@ def test_a_broken_competition_pass_fails_open(monkeypatch) -> None:assert p._verify_window(_loud_window(), fail_open=True) is True-def test_an_unprefixed_phrase_has_no_competition_to_lose() -> None:- """"Computer" offers no prefix anchor — the check always stands."""+def test_an_unprefixed_phrase_competes_against_the_free_hypothesis(+ monkeypatch,+) -> None:+ """"Computer" has no prefix anchor, but since 2026-08-12 it still competes+ — against the free ear's own hypothesis and "[unk]". A shape acceptance+ whose audio the decoder rather explains as the hypothesis is rejected;+ one the decoder keeps as the phrase stands. (Before this, an unprefixed+ phrase's competition ALWAYS stood, which left the live 'pedro' class —+ a random word firing through the shape path — open for those phrases.)+ """p = VoskKwsProvider("Computer", model_path="fake", keyword="computer")- assert p._competition_grammar is None- assert p._shape_competition_ok(b"", None) is True+ assert p._competition_grammar is None # still no static prefix competitor++ grammar = {+ "text": "computer",+ "result": [{"word": "computer", "start": 0.40, "end": 0.95, "conf": 1.0}],+ }+ free = {"text": "kompott", "result": [_w("kompott", 0.40, 0.95, conf=0.6)]}++ lost = {"text": "kompott", "result": []}+ monkeypatch.setattr(p, "_take_verify_rec", _stub_take(grammar, free, lost))+ assert p._verify_window(_loud_window(), fail_open=True) is False++ p2 = VoskKwsProvider("Computer", model_path="fake", keyword="computer")+ monkeypatch.setattr(p2, "_take_verify_rec", _stub_take(grammar, free))+ assert p2._verify_window(_loud_window(), fail_open=True) is Truedef test_the_competition_grammar_derives_from_the_configured_phrase() -> None:@@ -434,8 +462,13 @@ def test_room_speech_across_the_phrase_span_is_still_rejected(monkeypatch) -> No"""The narrower shape window must not become a way in for room speech.Here the surrounding words OVERLAP the phrase span rather than following- it, which is what a forced grammar hit on conversation actually looks like- — so they are still counted and the candidate is still rejected.+ it, which is what a forced grammar hit on conversation actually looks+ like. Since the span-duration clipping (2026-08-12) such a candidate is+ UNDECIDED rather than hard-rejected, and the span-trimmed competition+ decides: on unrelated flowing speech the decoder keeps the alternative+ ("[unk]" scripted here — the measured outcome for unrelated audio, 0/20+ kept in the 2026-08-04 calibration and 0/48 negative fires in the+ 2026-08-12 bench)."""p = VoskKwsProvider("Hey Ruben", model_path="fake", keyword="ruben")@@ -456,9 +489,11 @@ def test_room_speech_across_the_phrase_span_is_still_rejected(monkeypatch) -> No_w("gibt", 1.40, 1.70, conf=1.0),],}+ competition = {"text": "[unk]", "result": []}- monkeypatch.setattr(p, "_take_verify_rec", _stub_take(grammar, free))+ monkeypatch.setattr(p, "_take_verify_rec", _stub_take(grammar, free, competition))assert p._verify_window(_loud_window(), fail_open=True) is False+ assert p.stats()["suppressed_shape_competition"] == 1def test_a_bare_interjection_plus_a_command_is_still_not_a_wake() -> None:@@ -586,17 +621,19 @@ def test_a_contested_shape_that_loses_the_competition_does_not_fire(assert p.stats()["suppressed_shape_competition"] == 1-# --- a wake call STANDS ALONE (live forensic 2026-08-10) ---------------------+# --- a wake spoken MID-SENTENCE must fire (maintainer mandate 2026-08-12) ----#-# Three fires in 94 s while the user dictated German to a coding agent: the-# grammar forced flowing speech onto 'Hey George' and the verify let it-# through — twice via the acoustic competition, with unrelated German words-# ('herr tracks', 'aufbürdet' — i18n-allow: live-log recognition content)-# at the span, both conf 1.0), once via the SPELLING path itself (the en-# model heard a literal 'hey george' inside German flow). What every genuine-# call has and all three fires lack: silence immediately BEFORE the phrase.-# Mid-speech no-fire is the accepted product trade-off, so lead-in speech is-# a hard rejection for BOTH confirm paths — word-agnostic (timings only).+# REVERSAL of the 2026-08-10 "a wake call stands alone" rule. The hard lead-in+# silence gate made the wake word dead in the middle and at the end of a+# longer sentence, and after normal speech the user had to wait seconds of+# quiet before the detector would listen again — both explicitly rejected by+# the maintainer on 2026-08-12 ("no dead time; the phrase fires embedded in a+# flowing sentence"). Precision against the 2026-08-10 mid-dictation fires is+# now owed by CONTENT, not position: the acoustic competition judges the+# SPAN-TRIMMED audio against the free ear's own hypothesis. Bench evidence+# (scripts/vosk_wake_bench.py, real de+en models, synthesized de+en voices):+# 0/144 negative fires across three phrases while every mid-/end-of-sentence+# positive for "Hey George" fires._GEORGE_LEAD_IN = [@@ -616,39 +653,100 @@ _GEORGE_GRAMMAR = {}-def test_a_mid_speech_shape_fire_is_rejected_by_lead_in_speech(monkeypatch) -> None:- """LIVE (2026-08-10 19:59:27): free ear 'aufbürdet' (i18n-allow:- recognition content quoted from the live log), shape UNDECIDED, the- competition kept the phrase at conf 1.0 mid-stream — and it fired."""+def test_a_mid_sentence_spelled_wake_fires(monkeypatch) -> None:+ """The free ear SPELLED the phrase inside flowing speech — that IS the+ wake word, spoken mid-sentence, and under the 2026-08-12 mandate it+ activates. (This exact fixture was the isolation gate's canonical+ suppression case before the reversal.)"""+ p = VoskKwsProvider("Hey George", model_path="fake", keyword="george")+ free = {+ "text": "und dann machen wir hey george", # i18n-allow: recognition content under test+ "result": [+ *_GEORGE_LEAD_IN,+ _w("hey", 1.50, 1.72, conf=1.0),+ _w("george", 1.72, 2.15, conf=1.0),+ ],+ }++ monkeypatch.setattr(p, "_take_verify_rec", _stub_take(_GEORGE_GRAMMAR, free))+ assert p._verify_window(_loud_window(3.0), fail_open=True) is True+++def test_mid_sentence_room_speech_loses_the_competition(monkeypatch) -> None:+ """The 2026-08-10 false-fire class ('aufbürdet' at the span, i18n-allow:+ recognition content quoted from the live log) stays dead — by content,+ not position: the shape is contested and the span-trimmed competition+ hears the alternative, so the candidate falls."""p = VoskKwsProvider("Hey George", model_path="fake", keyword="george")free = {"text": "und dann machen wir aufbürdet", # i18n-allow: recognition content under test"result": [*_GEORGE_LEAD_IN, _w("aufbürdet", 1.45, 2.20, conf=1.0)], # i18n-allow}+ competition = {"text": "[unk]", "result": []}- monkeypatch.setattr(p, "_take_verify_rec", _stub_take(_GEORGE_GRAMMAR, free))+ monkeypatch.setattr(+ p, "_take_verify_rec", _stub_take(_GEORGE_GRAMMAR, free, competition)+ )+ assert p._verify_window(_loud_window(3.0), fail_open=True) is False+ assert p.stats()["suppressed_shape_competition"] == 1+++def test_a_bare_random_word_loses_the_competition(monkeypatch) -> None:+ """LIVE (2026-08-12): the free ear heard a bare 'pedro' — one word, no+ prefix at all — and 'Hey George' fired through the shape/undecided path+ because the full-ring competition rubber-stamped it. With the span-trimmed+ hypothesis-aware competition the decoder keeps 'pedro', and no part of a+ multi-part wake phrase on its own (nor any random word) can activate."""+ p = VoskKwsProvider("Hey George", model_path="fake", keyword="george")+ free = {"text": "pedro", "result": [_w("pedro", 1.60, 2.10, conf=1.0)]}+ competition = {"text": "pedro", "result": []}++ monkeypatch.setattr(+ p, "_take_verify_rec", _stub_take(_GEORGE_GRAMMAR, free, competition)+ )assert p._verify_window(_loud_window(3.0), fail_open=True) is False- assert p.stats()["suppressed_lead_speech"] == 1+ assert p.stats()["suppressed_shape_competition"] == 1-def test_a_mid_speech_spelled_phrase_is_rejected_by_lead_in_speech(+def test_the_competition_judges_span_trimmed_audio_with_the_hypothesis(monkeypatch,) -> None:- """LIVE (2026-08-10 19:58:34): the en free ear SPELLED 'hey george' out of- flowing German — the accept-only spelling path cannot be the way around- the isolation rule, or mentioning the wake word mid-sentence fires."""+ """The two mechanics the 2026-08-12 precision rests on, pinned:++ * the competition decodes ONLY the candidate span's audio (±0.3 s pad),+ never the whole ring — over the full ring the forced alignment could+ place the phrase anywhere and confirmed nearly everything;+ * the free ear's hypothesis joins the grammar alternatives, so the+ decoder chooses between the phrase and what was actually heard.+ """p = VoskKwsProvider("Hey George", model_path="fake", keyword="george")- free = {- "text": "und dann machen wir hey george", # i18n-allow: recognition content under test- "result": [- *_GEORGE_LEAD_IN,- _w("hey", 1.50, 1.72, conf=1.0),- _w("george", 1.72, 2.15, conf=1.0),- ],- }+ free = {"text": "pedro", "result": [_w("pedro", 1.60, 2.10, conf=1.0)]}+ seen: dict = {}- monkeypatch.setattr(p, "_take_verify_rec", _stub_take(_GEORGE_GRAMMAR, free))+ class _RecordingRec(_StubRec):+ def SetGrammar(self, grammar: str) -> None: # noqa: N802 - vosk API+ seen["alternatives"] = json.loads(grammar)++ def AcceptWaveform(self, pcm: bytes) -> bool: # noqa: N802 - vosk API+ seen["pcm_bytes"] = len(pcm)+ return True++ def _take(model_path, kind): # noqa: ANN001+ if kind == "competition":+ return _RecordingRec({"text": "pedro", "result": []})+ return _StubRec(_GEORGE_GRAMMAR if kind == "grammar" else free)++ monkeypatch.setattr(p, "_take_verify_rec", _take)assert p._verify_window(_loud_window(3.0), fail_open=True) is False+ # span [1.50, 2.15] padded ±0.3 -> [1.20, 2.45] = 1.25 s of 3.0 s audio+ # (± a couple of samples of float rounding, never the whole ring).+ assert abs(seen["pcm_bytes"] - int(1.25 * 16_000) * 2) <= 4+ assert seen["alternatives"] == [+ "hey george",+ "hey [unk]",+ "pedro",+ "[unk]",+ ]def test_an_isolated_call_still_fires_with_nothing_before_it(monkeypatch) -> None:@@ -661,7 +759,6 @@ def test_an_isolated_call_still_fires_with_nothing_before_it(monkeypatch) -> Nonmonkeypatch.setattr(p, "_take_verify_rec", _stub_take(_GEORGE_GRAMMAR, free))assert p._verify_window(_loud_window(3.0), fail_open=True) is True- assert p.stats()["suppressed_lead_speech"] == 0def test_a_call_after_a_natural_pause_still_fires(monkeypatch) -> None:@@ -681,9 +778,24 @@ def test_a_call_after_a_natural_pause_still_fires(monkeypatch) -> None:assert p._verify_window(_loud_window(3.0), fail_open=True) is True+def test_a_garbled_wake_after_flowing_speech_still_fires(monkeypatch) -> None:+ """The dead-time complaint, pinned from the other side: speech ending at+ the phrase's doorstep must not eat a wake whose shape and competition are+ clean. Under the removed isolation gate this exact fixture ('wir' ends+ 0.02 s before the span pad) was a guaranteed rejection."""+ p = VoskKwsProvider("Hey George", model_path="fake", keyword="george")+ free = {+ "text": "und dann machen wir gorsch", # i18n-allow: recognition content under test+ "result": [*_GEORGE_LEAD_IN, _w("gorsch", 1.50, 2.15, conf=0.6)],+ }++ monkeypatch.setattr(p, "_take_verify_rec", _stub_take(_GEORGE_GRAMMAR, free))+ assert p._verify_window(_loud_window(3.0), fail_open=True) is True++def test_trailing_command_speech_is_never_lead_in(monkeypatch) -> None:- """Only the LEADING side is gated: the wake+command breath (2026-07-25)- has all its extra words AFTER the phrase and keeps firing."""+ """The wake+command breath (2026-07-25) has all its extra words AFTER the+ phrase and keeps firing."""p = VoskKwsProvider("Hey George", model_path="fake", keyword="george")free = {"text": "gorsch wie ist das wetter", # i18n-allow: recognition content under test@@ -699,12 +811,12 @@ def test_trailing_command_speech_is_never_lead_in(monkeypatch) -> None:assert p._verify_window(_loud_window(3.0), fail_open=True) is True-def test_the_sibling_rescue_cannot_bypass_the_isolation_gate(monkeypatch) -> None:+def test_the_sibling_rescue_faces_the_same_competition(monkeypatch) -> None:"""The sibling rescue verifies through the SAME window check (the- fail-closed ``_early_check``): a sibling model whose free ear also heard- flowing speech right up to the span must not resurrect a mid-speech- candidate the primary model already rejected. Secondary rescue paths are- exactly where earlier gates in this file leaked, so this is pinned."""+ fail-closed ``_early_check``): a sibling whose span audio loses the+ competition must not resurrect a candidate the primary model already+ rejected. Secondary rescue paths are exactly where earlier gates in this+ file leaked, so this is pinned."""p = VoskKwsProvider("Hey George",model_path="primary",@@ -715,15 +827,110 @@ def test_the_sibling_rescue_cannot_bypass_the_isolation_gate(monkeypatch) -> Non"text": "und dann machen wir aufbürdet", # i18n-allow"result": [*_GEORGE_LEAD_IN, _w("aufbürdet", 1.45, 2.20, conf=1.0)], # i18n-allow}+ competition = {"text": "[unk]", "result": []}def _take(model_path, kind): # noqa: ANN001assert model_path == "sibling", "the rescue must verify on the sibling"+ if kind == "competition":+ return _StubRec(competition)return _StubRec(free if kind == "free" else _GEORGE_GRAMMAR)monkeypatch.setattr(p, "_take_verify_rec", _take)assert p._early_check(_loud_window(3.0), "sibling") is False+# --- embedded-wake re-score mechanics (2026-08-12) ---------------------------+++def test_the_rescore_scores_the_adjacent_run_not_scattered_phrase_words(+ monkeypatch,+) -> None:+ """A ring decode like 'hey hey george hey [unk]' contains the phrase ONCE,+ plus stray forced 'hey's elsewhere in the window. The old check pooled+ EVERY phrase word in the decode: the min-conf swallowed a distant weak+ 'hey' and the span stretched seconds wide, so an embedded wake could+ never pass. Only an adjacent in-order token run counts now — which is+ also the stricter reading: scattered parts ('hey ... george') are not+ the phrase, a multi-part wake is one unit."""+ p = VoskKwsProvider("Hey George", model_path="fake", keyword="george")+ grammar = {+ "text": "hey hey george hey [unk]",+ "result": [+ _w("hey", 0.20, 0.40, conf=0.30), # stray forced hit, weak+ _w("hey", 1.50, 1.72, conf=1.0), # the call+ _w("george", 1.72, 2.15, conf=1.0),+ _w("hey", 2.50, 2.60, conf=0.40), # stray forced hit, weak+ ],+ }+ free = {+ "text": "hey george",+ "result": [_w("hey", 1.50, 1.72, conf=1.0), _w("george", 1.72, 2.15, conf=0.8)],+ }++ monkeypatch.setattr(p, "_take_verify_rec", _stub_take(grammar, free))+ assert p._verify_window(_loud_window(3.0), fail_open=True) is True+++def test_scattered_phrase_parts_are_not_the_phrase(monkeypatch) -> None:+ """'hey ... george' with other audio between the parts must NOT re-score:+ the parts of a multi-part wake count only spoken together, in order."""+ p = VoskKwsProvider("Hey George", model_path="fake", keyword="george")+ scattered = {+ "text": "hey [unk] george",+ "result": [+ _w("hey", 0.20, 0.40, conf=1.0),+ _w("[unk]", 0.60, 1.50, conf=1.0),+ _w("george", 1.72, 2.15, conf=1.0),+ ],+ }+ free = {+ "text": "hey george",+ "result": [_w("hey", 0.20, 0.40, conf=1.0), _w("george", 1.72, 2.15, conf=0.8)],+ }++ monkeypatch.setattr(p, "_take_verify_rec", _stub_take(scattered, free))+ assert p._verify_window(_loud_window(3.0), fail_open=True) is False+++def test_an_embedded_wake_is_rescored_over_the_trailing_cut(monkeypatch) -> None:+ """Over the full ring the grammar absorbs an embedded phrase into the+ surrounding "[unk]"s and the re-score goes deaf (bench 2026-08-12:+ pos_mid/pos_end recall was 0 before this). The trailing 1.8 s cut+ re-hears it; its word times are shifted back into full-window seconds so+ every downstream span check (energy, free-word localisation, trimmed+ competition) still lines up."""+ p = VoskKwsProvider("Hey George", model_path="fake", keyword="george")+ ring_gres = {"text": "hey [unk] [unk]", "result": [_w("hey", 0.3, 0.5, conf=1.0)]}+ # Times below are CUT-relative; the cut starts at 3.0 - 1.8 = 1.2 s.+ tail_gres = {+ "text": "hey george",+ "result": [_w("hey", 0.35, 0.55, conf=1.0), _w("george", 0.55, 1.00, conf=1.0)],+ }+ # The free decode runs over the FULL window — times are window-relative;+ # the spelled phrase sits at 1.55-2.20 s, exactly where the shifted tail+ # span must land for the localisation to find it.+ free = {+ "text": "machen wir hey george", # i18n-allow: recognition content under test+ "result": [+ _w("machen", 0.90, 1.25, conf=1.0), # i18n-allow+ _w("wir", 1.25, 1.40, conf=1.0),+ _w("hey", 1.55, 1.75, conf=1.0),+ _w("george", 1.75, 2.20, conf=0.8),+ ],+ }+ grammar_calls = {"n": 0}++ def _take(model_path, kind): # noqa: ANN001+ if kind == "grammar":+ grammar_calls["n"] += 1+ return _StubRec(ring_gres if grammar_calls["n"] == 1 else tail_gres)+ return _StubRec(free)++ monkeypatch.setattr(p, "_take_verify_rec", _take)+ assert p._verify_window(_loud_window(3.0), fail_open=True) is True+ assert grammar_calls["n"] == 2 # the cut ran only after the ring failed++# --- diagnosability: a suppressed wake must leave a trace (2026-07-25) --------