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
chore: auto-save WIP via Claude stop-hook safety net (2026-07-02 08:48)
Ruben Lütke7801b4f07652
diff --git a/docs/diagnostics/BOOT-TTU-NOTES.md b/docs/diagnostics/BOOT-TTU-NOTES.mdnew file mode 100644index 0000000000..c16707cc01--- /dev/null+++ b/docs/diagnostics/BOOT-TTU-NOTES.md@@ -0,0 +1,69 @@+# Boot TTU (Time-to-Usable) — working notes++Loop task 2026-07-02: cut boot TTU by >= 20x, measured, on Windows/macOS/Linux,+with a regression guard. TTU = process start until the user can REALLY interact+(wake word armed AND firing, speech -> STT -> brain -> answer, typed turn works,+TTS ready) — all end-to-end over the same EventBus. "Window visible" does not count.++## Baseline measurement #1 — Windows, live log, boot of 2026-07-02 08:20 (commit 157b9f57)++Wake engine: stt_match (phrase "Hey Fable", rolling local Whisper base/cpu).++| t (mm:ss from first log line 08:20:18) | milestone |+|---|---|+| 00:00 | first bootstrap log lines (registries created, scans deferred) |+| 00:06 | speech pipeline built ("Pipeline bereit", voice build timings: tts=25ms wake_join=459ms) |+| 00:06 | wake loop started (whisper wake) — but local whisper NOT loaded yet |+| 00:58 | "Heavy backend: wake-model gate timed out (12 s) — starting the backend anyway" |+| 00:58 | persistent overlay (JarvisBar) revealed — ~1 min after start |+| 01:03 | rolling-whisper wedged during warm-up -> self-heal rebuild |+| 02:00 | "Wake-model pre-warm done in 114718 ms" (!!) |+| 03:23 | first real wake match ("Hey Fable" recognised) |++=> TTU(wake path) ~ 200+ s this boot. Even overlay-visible took ~60 s.++## Regression context (why "5x slower since today")++Until 2026-07-02 the wake engine was custom_onnx (small ONNX model, hear-ready in+~3 s). The stale-model fix (157b9f57, correct) resolved the changed phrase+"Hey Fable" to engine=stt_match — which puts the local faster-whisper base/cpu+load + pre-warm on the boot path: 114.7 s pre-warm + a wedge/self-heal cycle.+So the regression is NOT the fix itself but the stt_match boot cost that the+custom_onnx engine had hidden.++## Suspected critical-path blockers (to verify with code + measurements)++1. Wake-Whisper (faster-whisper base/cpu) load + pre-warm: 114.7 s logged.+ Why so long? Model load alone should be ~2-5 s; suspects: CPU contention+ with the parallel boot (uvicorn, wiki, registries), ctranslate2 thread pool+ vs the rest (AP-25), warm-up inference serialised behind the GIL, or an+ in-flight lock collision (the 08:21:21 wedge suggests the poll loop already+ ran while pre-warm was still using the model — AP-24 territory).+2. "Heavy backend: wake-model gate" — backend start WAITS up to 12 s on the+ wake model; overlay reveal is tied to boot completion (timeout-fallback).+3. Unknown import/spawn cost before the first log line (process start ->+ 08:20:18) — must instrument.++## Findings log (append per loop iteration)++- **F1 (verified in code, iteration 1):** the wake POLL loop starts at+ "Wake-Loop gestartet" (t+6s) while `_warmup_deferred_loaders` is still+ pre-warming the SAME stt model object (`pipeline.py::_warmup_deferred_loaders`,+ "PRIORITY: pre-warm the WAKE model FIRST"). The poll's own transcribe attempts+ collide with the warm-up ("a transcription is already in flight on this+ model", 08:21:21), the 8 s transcribe cap + 2-fail self-heal then REBUILDS the+ model mid-warm-up — throwing away the half-loaded state. AP-24 territory, on+ the boot path.+- **F2 (verified in code, iteration 1):** `_heavy_backend_bg` waits on+ `_wake_model_loaded` (12 s cap); the signal task `_signal_wake_model_loaded`+ polls `base_stt._model is not None` for max 20 s (desktop_app.py:2444). In the+ 08:20 boot the gate TIMED OUT -> the heavy backend storm (server.start init+ chain + brain build + MCP) started mid-model-load, adding CPU contention on+ top of F1. Combined effect: 114.7 s pre-warm for a model measured at ~3-4 s+ isolated (per existing comments), TTU ~200 s.+- **F3:** overlay (JarvisBar) reveal waited for the boot-complete signal and+ fired via "timeout-fallback" at ~60 s.++## Fixes applied (append per loop iteration, with measured effect)++- (pending)diff --git a/jarvis/plugins/stt/fwhisper.py b/jarvis/plugins/stt/fwhisper.pyindex eaeb9ae469..e7a4757ac8 100644--- a/jarvis/plugins/stt/fwhisper.py+++ b/jarvis/plugins/stt/fwhisper.py@@ -231,6 +231,20 @@ class FasterWhisperProvider:# 2026-06-29) or return garbage. This lock makes the model call mutually# exclusive per instance so the two callers serialize instead of racing.self._infer_lock = threading.Lock()+ # True once ``warm_up`` completed (model constructed + one priming+ # inference). Boot-time consumers (the rolling-whisper wake poll loop,+ # the heavy-backend gate) wait on this instead of poking the model+ # while it is still loading: a transcribe DURING the load used to time+ # out at 8 s, the next poll hit TranscribeBusy, two fails triggered+ # recover() which threw the half-loaded model away and reloaded from+ # scratch — a load cascade that turned a ~4 s model load into 114.7 s+ # on the boot path (TTU forensic 2026-07-02).+ self._warm = False++ @property+ def is_warm(self) -> bool:+ """True when the model is constructed AND primed (safe to poll)."""+ return self._warmdef _ensure_model(self) -> None:if self._model is not None:@@ -278,6 +292,7 @@ class FasterWhisperProvider:)self._model = Noneself._infer_lock = threading.Lock()+ self._warm = Falsedef warm_up(self) -> None:"""Prime the engine with one throwaway inference so the FIRST live@@ -312,6 +327,10 @@ class FasterWhisperProvider:self._transcribe_sync(warm_audio, 16_000)except Exception as exc: # noqa: BLE001 — priming is best-effortlog.debug("Whisper warm-up inference skipped: %s", exc)+ # Signal readiness even when the priming inference failed: the model+ # object exists, so pollers can safely transcribe (lazy paths cover the+ # rest). Leaving _warm False here would park the wake poll loop forever.+ self._warm = Trueasync def transcribe(self, audio: AsyncIterator[AudioChunk]) -> Transcript:"""Collects all chunks, transcribes them in one go.diff --git a/jarvis/speech/rolling_whisper_wake.py b/jarvis/speech/rolling_whisper_wake.pyindex 2ce1044d74..48bbde44b4 100644--- a/jarvis/speech/rolling_whisper_wake.py+++ b/jarvis/speech/rolling_whisper_wake.py@@ -201,9 +201,18 @@ class RollingWhisperWake:# the OWW prefix-verifier's _WAKE_VERIFY_TIMEOUT_S. Set high enough to# tolerate a slow/loaded CPU box (€5-VPS doctrine); <= 0 disables the cap.transcribe_timeout_s: float = 8.0,+ # Boot serialisation (TTU forensic 2026-07-02): how long to wait for the+ # provider's one-off warm-up (owned by the pipeline's deferred loader)+ # before this loop warms the model itself as a fallback owner. Polling+ # transcribe WHILE the model loads used to cascade: 8 s timeout ->+ # TranscribeBusy -> self-heal recover() threw the half-loaded model away+ # -> reload from scratch under the boot CPU storm (114.7 s for a ~4 s+ # load). The poll phase therefore starts only on a warm model.+ warm_wait_fallback_s: float = 20.0,) -> None:self._stt = sttself._pattern = pattern+ self._warm_wait_fallback_s = float(warm_wait_fallback_s)self._window_samples = int(window_s * sample_rate)self._poll_interval_s = poll_interval_sself._cooldown_s = cooldown_s@@ -358,6 +367,45 @@ class RollingWhisperWake:# can never leave the wake permanently dead.consecutive_fail = 0+ # --- Boot serialisation: poll only a WARM model -------------------+ # The pipeline's deferred loader owns the one-off model warm-up. Poking+ # ``transcribe_pcm`` while that load is in flight used to cascade+ # (timeout -> TranscribeBusy -> recover() threw the half-loaded model+ # away -> reload under the boot storm; 114.7 s instead of ~4 s, TTU+ # forensic 2026-07-02). Wait for ``is_warm``; if nobody warms the model+ # within the fallback window (unusual wiring), own the warm-up HERE —+ # exactly one loader either way. Providers without the flag (fakes,+ # cloud STT) report warm immediately. The audio consumer keeps filling+ # the rolling buffer during the wait, so no wake audio is lost.+ warm_wait_t0 = time.time()+ warm_wait_logged = False+ while not stopped.is_set() and not getattr(self._stt, "is_warm", True):+ if time.time() - warm_wait_t0 > self._warm_wait_fallback_s:+ log.info(+ "rolling-whisper: wake model still cold after %.0f s — "+ "warming it from the poll loop (fallback owner).",+ self._warm_wait_fallback_s,+ )+ warm = getattr(self._stt, "warm_up", None)+ if callable(warm):+ try:+ await asyncio.to_thread(warm)+ except Exception as exc: # noqa: BLE001 — lazy load still works+ log.warning("rolling-whisper: fallback warm-up failed: %s", exc)+ break+ if not warm_wait_logged:+ log.info(+ "rolling-whisper: waiting for the wake model warm-up before "+ "polling (buffer keeps filling)."+ )+ warm_wait_logged = True+ await asyncio.sleep(0.25)+ if warm_wait_logged:+ log.info(+ "rolling-whisper: wake model warm — polling starts (waited %.1f s).",+ time.time() - warm_wait_t0,+ )+def _note_transcribe_fail() -> int:nonlocal consecutive_failconsecutive_fail += 1diff --git a/jarvis/ui/desktop_app.py b/jarvis/ui/desktop_app.pyindex e1f58ce48d..11e03879eb 100644--- a/jarvis/ui/desktop_app.py+++ b/jarvis/ui/desktop_app.py@@ -2435,10 +2435,16 @@ class DesktopApp:def _wake_model_is_loaded() -> bool:ww = getattr(pipeline, "_whisper_wake", None)base_stt = getattr(ww, "_stt", None) if ww is not None else stt- return (- base_stt is not None- and getattr(base_stt, "_model", None) is not None- )+ if base_stt is None:+ return False+ # Prefer the provider's warm signal (model constructed AND+ # primed) so the heavy-backend CPU storm starts only after the+ # priming inference, not in the middle of it. Fall back to the+ # raw model handle for providers without the flag.+ warm = getattr(base_stt, "is_warm", None)+ if warm is not None:+ return bool(warm)+ return getattr(base_stt, "_model", None) is not Nonefrom jarvis.core import runtime_refs as _rr_readyif stt is None:diff --git a/scripts/wake_bench.py b/scripts/wake_bench.pynew file mode 100644index 0000000000..c6ee365886--- /dev/null+++ b/scripts/wake_bench.py@@ -0,0 +1,466 @@+"""Wake-word benchmark harness — measures the stt_match wake path offline.++Reproducible evidence for the 2026-07-02 wake reliability/latency work: no+live microphone, no network, deterministic fixture selection. It exercises the+SAME production code the app runs (``build_wake_whisper`` construction,+``RollingWhisperWake`` gates/gain/matcher) against real captured audio from+``data/wake_debug/`` (1.8 s / 16 kHz mono int16 windows, filenames embed the+transcript heard at capture time).++Fixture classes (word-boundary token match on the filename transcript):+- ``pos_full`` — windows containing prefix + core ("Hey Nico ...") -> must fire+- ``neg_bare`` — core word WITHOUT prefix ("Das war wahrscheinlich+ Nico") — the RC5(a) false-activation class -> must stay silent+- ``neg_ambient``— speech without the core word (rms >= 0.01) -> must stay silent+- ``neg_quiet`` — low-level noise/breath (0.003 <= rms < 0.01) -> must stay silent+- ``neg_silence``— synthesized near-silence windows -> must stay silent++Modes:+- ``window`` (default): per-window micro-benchmark. Replicates the poll loop's+ gates + peak-normalization gain, transcribes each window directly, applies+ the production reliability gates + matcher. Reports recall / false accepts /+ transcribe-time stats / cold-start cost. Fast — used for the config matrix.+- ``stream``: end-to-end wall-clock benchmark. Builds composite audio+ (lead-in + positive + tail), streams it through ``RollingWhisperWake.+ detect()`` in real time and measures speech-end -> trigger latency.+- ``stress``: ``stream`` while CPU-burner threads emulate the boot storm;+ counts wedge recoveries (RC1 reproduction).++Examples:+ python scripts/wake_bench.py --mode window+ python scripts/wake_bench.py --mode window --model tiny --bias off+ python scripts/wake_bench.py --mode stream --limit 8+ python scripts/wake_bench.py --mode stress --burners 8 --limit 6+"""+from __future__ import annotations++import argparse+import asyncio+import json+import random+import re+import statistics+import sys+import threading+import time+import wave+from dataclasses import dataclass, field+from pathlib import Path+from types import SimpleNamespace+from typing import Any++import numpy as np++REPO_ROOT = Path(__file__).resolve().parents[1]+sys.path.insert(0, str(REPO_ROOT))++from jarvis.core.protocols import AudioChunk # noqa: E402+from jarvis.speech.rolling_whisper_wake import ( # noqa: E402+ RollingWhisperWake,+ _reliable_wake_transcript,+)+from jarvis.speech.wake_phrase import compile_wake_matcher # noqa: E402++SAMPLE_RATE = 16_000+WAKE_DEBUG_DIR = REPO_ROOT / "data" / "wake_debug"++# Production gate / gain constants (mirror RollingWhisperWake defaults).+MIN_RMS = 0.003+MIN_PEAK = 0.008+TARGET_PEAK = 10.0 ** (-3.0 / 20.0) # -3 dBFS+MAX_GAIN = 10.0 ** (40.0 / 20.0) # 40 dB+MIN_WAKE_CONFIDENCE = 0.22+MAX_NO_SPEECH_PROB = 0.6++_PREFIX_TOKENS = {"hey", "hi", "hallo", "he"}+++# ---------------------------------------------------------------------------+# Fixtures+# ---------------------------------------------------------------------------++def _tokens(name: str) -> list[str]:+ stem = re.sub(r"^wake_\d+_rms[0-9.]+_", "", Path(name).stem)+ return [t.lower() for t in stem.split("_") if t]+++def _rms_from_name(name: str) -> float:+ m = re.search(r"rms([0-9.]+)", name)+ return float(m.group(1)) if m else -1.0+++def _has_core(tokens: list[str], core_res: list[re.Pattern[str]]) -> bool:+ return any(rx.fullmatch(t) for t in tokens for rx in core_res)+++@dataclass+class FixtureSet:+ pos_full: list[Path] = field(default_factory=list)+ neg_bare: list[Path] = field(default_factory=list)+ neg_ambient: list[Path] = field(default_factory=list)+ neg_quiet: list[Path] = field(default_factory=list)+++def discover_fixtures(+ core_variants: list[str], *, neg_cap: int, seed: int = 42+) -> FixtureSet:+ """Classify data/wake_debug WAVs by their filename transcript."""+ core_res = [re.compile(v, re.I) for v in core_variants]+ fx = FixtureSet()+ ambient_pool: list[Path] = []+ quiet_pool: list[Path] = []+ for entry in sorted(WAKE_DEBUG_DIR.iterdir()):+ if entry.suffix != ".wav":+ continue+ toks = _tokens(entry.name)+ if _has_core(toks, core_res):+ if any(t in _PREFIX_TOKENS for t in toks):+ fx.pos_full.append(entry)+ else:+ fx.neg_bare.append(entry)+ continue+ r = _rms_from_name(entry.name)+ if r >= 0.01:+ ambient_pool.append(entry)+ elif 0.003 <= r < 0.01:+ quiet_pool.append(entry)+ rng = random.Random(seed)+ fx.neg_ambient = sorted(rng.sample(ambient_pool, min(neg_cap, len(ambient_pool))))+ fx.neg_quiet = sorted(rng.sample(quiet_pool, min(neg_cap // 2, len(quiet_pool))))+ fx.neg_bare = fx.neg_bare[: neg_cap]+ return fx+++def load_wav(path: Path) -> np.ndarray:+ """Return float32 samples in [-1, 1] at 16 kHz mono."""+ with wave.open(str(path), "rb") as wf:+ assert wf.getframerate() == SAMPLE_RATE, path+ raw = wf.readframes(wf.getnframes())+ return np.frombuffer(raw, dtype=np.int16).astype(np.float32) / 32768.0+++def scale_to_peak_dbfs(audio: np.ndarray, dbfs: float) -> np.ndarray:+ peak = float(np.max(np.abs(audio)))+ if peak <= 1e-9:+ return audio+ return audio * (10.0 ** (dbfs / 20.0) / peak)+++def synth_silence_windows(n: int, seed: int = 42) -> list[np.ndarray]:+ """Near-silence with a hint of hiss — must be gated or stay unmatched."""+ rng = np.random.default_rng(seed)+ return [+ rng.normal(0.0, 0.002, int(1.8 * SAMPLE_RATE)).astype(np.float32)+ for _ in range(n)+ ]+++def speech_end_s(audio: np.ndarray, threshold: float = 0.02) -> float:+ """Offset (s) of the last sample above ``threshold`` — end of speech."""+ idx = np.nonzero(np.abs(audio) > threshold)[0]+ return float(idx[-1] / SAMPLE_RATE) if len(idx) else len(audio) / SAMPLE_RATE+++# ---------------------------------------------------------------------------+# Wake model construction (production path or explicit matrix cell)+# ---------------------------------------------------------------------------++def build_model(args: argparse.Namespace, phrase: str) -> Any:+ """Build the wake Whisper exactly like production (or a matrix variant)."""+ bias_phrase = None if args.bias == "off" else phrase+ if args.production:+ from jarvis.plugins.stt import build_wake_whisper++ cfg = SimpleNamespace(+ wake_model=args.model, wake_device="cpu",+ wake_compute_type="int8", wake_high_accuracy=False,+ )+ return build_wake_whisper(+ cfg, language=None, wake_phrase=bias_phrase,+ cuda_available=False, fast_first=True,+ )+ from jarvis.plugins.stt.fwhisper import FasterWhisperProvider++ return FasterWhisperProvider(+ model=args.model, device="cpu", compute_type="int8",+ language=None, initial_prompt=bias_phrase,+ beam_size=1, cpu_threads=args.threads,+ )+++# ---------------------------------------------------------------------------+# Window mode (per-window recall / false accepts / speed)+# ---------------------------------------------------------------------------++def apply_poll_loop_gain(audio: np.ndarray) -> bytes:+ """Replicate the poll loop's peak normalization + int16 conversion."""+ peak = float(np.max(np.abs(audio)))+ gain = min(TARGET_PEAK / peak, MAX_GAIN) if peak > 1e-6 else 1.0+ return (np.clip(audio * gain, -1.0, 1.0) * 32767.0).astype(np.int16).tobytes()+++@dataclass+class WindowResult:+ name: str+ cls: str+ gated: bool = False+ transcribe_ms: float = 0.0+ text: str = ""+ confidence: float = 0.0+ reliable: bool = False+ matched: bool = False+++async def run_window_case(+ stt: Any, matcher: Any, audio: np.ndarray, name: str, cls: str,+ language: str | None,+) -> WindowResult:+ res = WindowResult(name=name, cls=cls)+ rms = float(np.sqrt(np.mean(audio * audio) + 1e-12))+ peak = float(np.max(np.abs(audio)))+ if rms < MIN_RMS or peak < MIN_PEAK:+ res.gated = True+ return res+ pcm = apply_poll_loop_gain(audio)+ t0 = time.perf_counter()+ transcript = await stt.transcribe_pcm(pcm, language=language)+ res.transcribe_ms = (time.perf_counter() - t0) * 1000.0+ res.text = (transcript.text or "").strip()+ res.confidence = float(getattr(transcript, "confidence", 0.0) or 0.0)+ res.reliable = bool(res.text) and _reliable_wake_transcript(+ transcript,+ min_confidence=MIN_WAKE_CONFIDENCE,+ max_no_speech_prob=MAX_NO_SPEECH_PROB,+ )+ res.matched = res.reliable and matcher.search(res.text) is not None+ return res+++async def run_window_mode(args: argparse.Namespace) -> dict:+ matcher = compile_wake_matcher(args.phrase, fuzzy_ratio=0.8)+ core_variants = [v.strip() for v in args.core_variants.split(",")]+ fx = discover_fixtures(core_variants, neg_cap=args.neg_cap)+ stt = build_model(args, args.phrase)+ lang = None if args.language in ("", "auto", "none") else args.language++ print(+ f"fixtures: pos_full={len(fx.pos_full)} neg_bare={len(fx.neg_bare)} "+ f"neg_ambient={len(fx.neg_ambient)} neg_quiet={len(fx.neg_quiet)}"+ )++ cases: list[tuple[str, str, np.ndarray]] = []+ limit = args.limit or len(fx.pos_full)+ volumes = [float(v) for v in args.volumes.split(",") if v.strip()]+ for p in fx.pos_full[:limit]:+ audio = load_wav(p)+ cases.append((p.name, "pos_orig", audio))+ for db in volumes:+ cases.append((f"{p.name}@{db:g}dB", f"pos@{db:g}dB",+ scale_to_peak_dbfs(audio, db)))+ for p in fx.neg_bare:+ cases.append((p.name, "neg_bare", load_wav(p)))+ for p in fx.neg_ambient:+ cases.append((p.name, "neg_ambient", load_wav(p)))+ for p in fx.neg_quiet:+ cases.append((p.name, "neg_quiet", load_wav(p)))+ for i, audio in enumerate(synth_silence_windows(10)):+ cases.append((f"silence_{i}", "neg_silence", audio))++ results: list[WindowResult] = []+ cold_ms: float | None = None+ for name, cls, audio in cases:+ r = await run_window_case(stt, matcher, audio, name, cls, lang)+ if cold_ms is None and not r.gated:+ cold_ms = r.transcribe_ms+ results.append(r)+ if args.verbose and (r.matched or cls.startswith("pos")):+ print(f" [{cls:>12}] matched={r.matched!s:>5} "+ f"{r.transcribe_ms:7.0f}ms conf={r.confidence:.2f} "+ f"text={r.text[:60]!r} ({name[:50]})")++ summary: dict[str, Any] = {"mode": "window", "config": _config_str(args),+ "cold_first_transcribe_ms": cold_ms}+ by_cls: dict[str, list[WindowResult]] = {}+ for r in results:+ by_cls.setdefault(r.cls, []).append(r)+ times = [r.transcribe_ms for r in results if not r.gated]+ summary["transcribe_ms"] = {+ "n": len(times),+ "mean": round(statistics.mean(times), 1) if times else None,+ "median": round(statistics.median(times), 1) if times else None,+ "p95": round(np.percentile(times, 95), 1) if times else None,+ }+ print(f"\n== {summary['config']} ==")+ print(f"cold first transcribe: {cold_ms:.0f} ms" if cold_ms else "all gated?!")+ print(f"warm transcribe: median={summary['transcribe_ms']['median']} ms "+ f"mean={summary['transcribe_ms']['mean']} ms "+ f"p95={summary['transcribe_ms']['p95']} ms (n={len(times)})")+ for cls in sorted(by_cls):+ rs = by_cls[cls]+ matched = sum(r.matched for r in rs)+ gated = sum(r.gated for r in rs)+ rate = matched / len(rs) if rs else 0.0+ kind = "recall" if cls.startswith("pos") else "FALSE-ACCEPT"+ print(f" {cls:>12}: {kind}={rate:6.1%} ({matched}/{len(rs)}) gated={gated}")+ summary[cls] = {"n": len(rs), "matched": matched, "gated": gated,+ "rate": round(rate, 4)}+ return summary+++# ---------------------------------------------------------------------------+# Stream mode (end-to-end latency through RollingWhisperWake)+# ---------------------------------------------------------------------------++async def _stream_chunks(audio: np.ndarray, chunk_ms: int = 100):+ """Yield AudioChunks at real-time pace."""+ step = int(SAMPLE_RATE * chunk_ms / 1000)+ for i in range(0, len(audio), step):+ seg = audio[i : i + step]+ pcm = (np.clip(seg, -1.0, 1.0) * 32767.0).astype(np.int16).tobytes()+ yield AudioChunk(pcm=pcm, sample_rate=SAMPLE_RATE,+ timestamp_ns=time.time_ns())+ await asyncio.sleep(chunk_ms / 1000.0)+++async def run_stream_mode(args: argparse.Namespace) -> dict:+ matcher = compile_wake_matcher(args.phrase, fuzzy_ratio=0.8)+ core_variants = [v.strip() for v in args.core_variants.split(",")]+ fx = discover_fixtures(core_variants, neg_cap=args.neg_cap)+ stt = build_model(args, args.phrase)+ lang = args.language if args.language not in ("", "auto", "none") else None++ # Count recover() calls (wedge events) via a counting shim.+ recover_calls = {"n": 0}+ orig_recover = getattr(stt, "recover", None)+ if callable(orig_recover):+ def counting_recover() -> None:+ recover_calls["n"] += 1+ orig_recover()+ stt.recover = counting_recover # type: ignore[attr-defined]++ quiet_pool = [load_wav(p) for p in fx.neg_quiet[:6]] or synth_silence_windows(4)++ burners: list[threading.Thread] = []+ stop_burn = threading.Event()+ if args.burners:+ def _burn() -> None:+ a = np.random.default_rng(1).normal(size=(220, 220))+ while not stop_burn.is_set():+ a = a @ a.T+ a /= max(1e-9, float(np.max(np.abs(a))))+ burners = [threading.Thread(target=_burn, daemon=True)+ for _ in range(args.burners)]+ for b in burners:+ b.start()+ print(f"stress: {args.burners} CPU-burner threads running")++ latencies: list[float] = []+ misses = 0+ limit = args.limit or len(fx.pos_full)+ try:+ for p in fx.pos_full[:limit]:+ pos = load_wav(p)+ lead = np.concatenate([random.Random(7).choice(quiet_pool)+ for _ in range(2)])+ tail = np.concatenate([random.Random(9).choice(quiet_pool)+ for _ in range(4)])+ composite = np.concatenate([lead, pos, tail]).astype(np.float32)+ word_end_s = len(lead) / SAMPLE_RATE + speech_end_s(pos)++ wake = RollingWhisperWake(stt, pattern=matcher, language=lang)+ t_start = time.perf_counter()+ fired_at: float | None = None++ async def _detect(w=wake, comp=composite):+ async for _kw in w.detect(_stream_chunks(comp)):+ return time.perf_counter()+ return None++ try:+ fired_at = await asyncio.wait_for(+ _detect(), timeout=len(composite) / SAMPLE_RATE + 10.0+ )+ except TimeoutError:+ fired_at = None+ if fired_at is None:+ misses += 1+ print(f" MISS {p.name[:60]}")+ else:+ lat = fired_at - t_start - word_end_s+ latencies.append(lat)+ print(f" fired {lat*1000:6.0f} ms after word end ({p.name[:55]})")+ finally:+ stop_burn.set()++ summary = {+ "mode": "stress" if args.burners else "stream",+ "config": _config_str(args),+ "n": len(latencies) + misses,+ "misses": misses,+ "recover_calls": recover_calls["n"],+ "latency_ms": {+ "median": round(statistics.median(latencies) * 1000)+ if latencies else None,+ "p95": round(float(np.percentile(latencies, 95)) * 1000)+ if latencies else None,+ "max": round(max(latencies) * 1000) if latencies else None,+ },+ }+ print(f"\n== {summary['config']} ({summary['mode']}) ==")+ print(f"hits={len(latencies)}/{summary['n']} misses={misses} "+ f"wedge-recovers={recover_calls['n']}")+ if latencies:+ print(f"word-end -> trigger latency: median={summary['latency_ms']['median']} ms "+ f"p95={summary['latency_ms']['p95']} ms max={summary['latency_ms']['max']} ms")+ return summary+++# ---------------------------------------------------------------------------++def _config_str(args: argparse.Namespace) -> str:+ return (f"model={args.model} threads={args.threads} lang={args.language} "+ f"bias={args.bias} production={args.production}")+++def main() -> None:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--mode", choices=("window", "stream", "stress"),+ default="window")+ parser.add_argument("--phrase", default="Hey Nico",+ help="wake phrase matching the fixture set")+ parser.add_argument("--core-variants", default=r"ni[ckh]?[ck]o|nikko|nicko|niko",+ help="comma-separated regexes for the core word in filenames")+ parser.add_argument("--model", default="base")+ parser.add_argument("--threads", type=int, default=1)+ parser.add_argument("--language", default="de",+ help='"de", "en", or "auto"/"none" for auto-detect')+ parser.add_argument("--bias", choices=("on", "off"), default="on")+ parser.add_argument("--production", action="store_true",+ help="build via build_wake_whisper (ignores --threads)")+ parser.add_argument("--volumes", default="-20,-30,-40",+ help="peak dBFS levels for scaled positive variants")+ parser.add_argument("--neg-cap", type=int, default=60)+ parser.add_argument("--limit", type=int, default=0,+ help="cap positive fixtures (0 = all)")+ parser.add_argument("--burners", type=int, default=0,+ help="CPU burner threads (stress mode)")+ parser.add_argument("--json", dest="json_out", default="")+ parser.add_argument("--verbose", action="store_true")+ args = parser.parse_args()+ if args.mode == "stress" and args.burners == 0:+ args.burners = 8++ if args.mode == "window":+ summary = asyncio.run(run_window_mode(args))+ else:+ summary = asyncio.run(run_stream_mode(args))++ if args.json_out:+ Path(args.json_out).write_text(+ json.dumps(summary, indent=2), encoding="utf-8"+ )+ print(f"json written: {args.json_out}")+++if __name__ == "__main__":+ main()diff --git a/tests/unit/speech/test_rolling_whisper_wake_boot_warm.py b/tests/unit/speech/test_rolling_whisper_wake_boot_warm.pynew file mode 100644index 0000000000..db0d0a3af0--- /dev/null+++ b/tests/unit/speech/test_rolling_whisper_wake_boot_warm.py@@ -0,0 +1,165 @@+"""The wake poll loop must not poke the STT model while it is still loading.++TTU forensic 2026-07-02 (data/jarvis_desktop.log, boot 08:20): the poll loop's+first ``transcribe_pcm`` triggered the LAZY model load, hit the 8 s per-call+timeout while the load was still running, the next poll hit TranscribeBusy,+two failures tripped the self-heal ``recover()`` which threw the half-loaded+model away — a reload cascade under the boot CPU storm that turned a ~4 s+model load into 114.7 s and TTU ~200 s. The fix: the poll (and the fail+counter) starts only once the provider reports ``is_warm``; if nobody warms+the model within the fallback window, the poll loop owns the warm-up itself —+exactly one loader either way.+"""+from __future__ import annotations++import asyncio+import re++import numpy as np++from jarvis.core.protocols import AudioChunk+from jarvis.speech.rolling_whisper_wake import RollingWhisperWake+++def _loud_chunk(marker: int, n: int = 1600) -> AudioChunk:+ val = 12000 + (marker % 80) * 100+ arr = np.full(n, val, dtype=np.int16)+ return AudioChunk(pcm=arr.tobytes(), sample_rate=16000, timestamp_ns=0)+++class _WarmableSTT:+ """Fake provider with the warm-signal surface of FasterWhisperProvider."""++ def __init__(self, *, warm: bool = False) -> None:+ self.is_warm = warm+ self.transcribe_calls = 0+ self.warm_up_calls = 0+ self.recover_calls = 0++ async def transcribe_pcm(self, pcm, sample_rate=16000, language=None): # noqa: ANN001+ self.transcribe_calls += 1++ class _T:+ text = ""+ confidence = 1.0+ segments = ()++ return _T()++ def warm_up(self) -> None:+ self.warm_up_calls += 1+ self.is_warm = True++ def recover(self) -> None:+ self.recover_calls += 1+++def _wake(stt, *, fallback_s: float = 30.0) -> RollingWhisperWake:+ return RollingWhisperWake(+ stt,+ pattern=re.compile(r"nico", re.IGNORECASE),+ poll_interval_s=0.01,+ cooldown_s=0.0,+ save_debug_wavs=False,+ min_rms=0.0,+ min_peak=0.0,+ transcribe_timeout_s=1.0,+ warm_wait_fallback_s=fallback_s,+ )+++async def _drive_with_audio(wake: RollingWhisperWake):+ """Start detect() with a steady loud-audio feed; return (stop, tasks)."""+ src: asyncio.Queue = asyncio.Queue()+ stop = asyncio.Event()++ async def _iter():+ while True:+ chunk = await src.get()+ if chunk is None:+ return+ yield chunk++ async def _feed() -> None:+ i = 0+ while not stop.is_set():+ await src.put(_loud_chunk(i))+ i += 1+ await asyncio.sleep(0.002)++ async def _drain() -> None:+ async for _kw in wake.detect(_iter()):+ pass++ feeder = asyncio.create_task(_feed())+ driver = asyncio.create_task(_drain())++ async def _shutdown() -> None:+ stop.set()+ await src.put(None)+ driver.cancel()+ feeder.cancel()+ for t in (driver, feeder):+ try:+ await t+ except (asyncio.CancelledError, Exception): # noqa: BLE001, S110+ pass++ return _shutdown+++async def test_poll_does_not_touch_a_cold_model_then_starts_when_warm() -> None:+ stt = _WarmableSTT(warm=False)+ wake = _wake(stt)+ shutdown = await _drive_with_audio(wake)+ try:+ # Cold phase: plenty of loud audio, but the model is not warm — the+ # poll loop must make ZERO transcribe attempts (no timeout/busy fails,+ # no self-heal recover() that would throw a loading model away).+ await asyncio.sleep(0.4)+ assert stt.transcribe_calls == 0, "poll loop poked a cold model"+ assert stt.recover_calls == 0++ # Someone (the deferred loader) finishes the warm-up -> polling starts.+ stt.is_warm = True+ for _ in range(200):+ if stt.transcribe_calls > 0:+ break+ await asyncio.sleep(0.01)+ assert stt.transcribe_calls > 0, "poll never started on a warm model"+ finally:+ await shutdown()+++async def test_poll_owns_the_warmup_after_the_fallback_window() -> None:+ """If nobody warms the model (unusual wiring), the poll loop must warm it+ itself after the fallback window instead of waiting forever."""+ stt = _WarmableSTT(warm=False)+ wake = _wake(stt, fallback_s=0.1)+ shutdown = await _drive_with_audio(wake)+ try:+ for _ in range(300):+ if stt.transcribe_calls > 0:+ break+ await asyncio.sleep(0.01)+ assert stt.warm_up_calls >= 1, "fallback warm-up never ran"+ assert stt.transcribe_calls > 0, "poll never started after fallback warm-up"+ finally:+ await shutdown()+++async def test_provider_without_warm_flag_polls_immediately() -> None:+ """Fakes / cloud STT providers without ``is_warm`` must behave as before —+ no warm-wait phase, polling starts right away."""+ stt = _WarmableSTT(warm=False)+ del stt.is_warm # instance attr removed -> getattr falls back to default+ wake = _wake(stt)+ shutdown = await _drive_with_audio(wake)+ try:+ for _ in range(200):+ if stt.transcribe_calls > 0:+ break+ await asyncio.sleep(0.01)+ assert stt.transcribe_calls > 0+ finally:+ await shutdown()diff --git a/tests/unit/speech/test_zz_diag_bootwarm_scratch.py b/tests/unit/speech/test_zz_diag_bootwarm_scratch.pynew file mode 100644index 0000000000..b23f95d5a1--- /dev/null+++ b/tests/unit/speech/test_zz_diag_bootwarm_scratch.py@@ -0,0 +1,103 @@+"""Temporary diagnostic for the boot-warm test failure — deleted after use."""+from __future__ import annotations++import asyncio+import re++import numpy as np++from jarvis.core.protocols import AudioChunk+from jarvis.speech.rolling_whisper_wake import RollingWhisperWake+++class _STT:+ def __init__(self) -> None:+ self.is_warm = False+ self.calls = 0++ async def transcribe_pcm(self, pcm, sample_rate=16000, language=None): # noqa: ANN001+ self.calls += 1++ class _T:+ text = ""+ confidence = 1.0+ segments = ()++ return _T()++ def warm_up(self) -> None:+ self.is_warm = True+++async def test_diag_bootwarm(capsys) -> None:+ stt = _STT()+ wake = RollingWhisperWake(+ stt,+ pattern=re.compile("nico"),+ poll_interval_s=0.01,+ cooldown_s=0.0,+ min_rms=0.0,+ min_peak=0.0,+ transcribe_timeout_s=1.0,+ warm_wait_fallback_s=30.0,+ )+ src: asyncio.Queue = asyncio.Queue()+ stop = asyncio.Event()++ async def _iter():+ while True:+ c = await src.get()+ if c is None:+ return+ yield c++ async def _feed() -> None:+ i = 0+ while not stop.is_set():+ arr = np.full(1600, 12000 + (i % 80) * 100, dtype=np.int16)+ await src.put(AudioChunk(pcm=arr.tobytes(), sample_rate=16000, timestamp_ns=0))+ i += 1+ await asyncio.sleep(0.002)++ async def _drain() -> None:+ async for _kw in wake.detect(_iter()):+ pass++ import time as _time++ f = asyncio.create_task(_feed())+ d = asyncio.create_task(_drain())+ _t0 = _time.perf_counter()+ await asyncio.sleep(0.4)+ _slept = _time.perf_counter() - _t0+ with capsys.disabled():+ print(f"\nDIAG sleep(0.4) took {_slept:.3f}s real")+ print(f"DIAG cold: calls={stt.calls} feeder_done={f.done()} driver_done={d.done()}")+ if f.done():+ print("feeder exc:", repr(f.exception()))+ if d.done():+ print("driver exc:", repr(d.exception()))+ stt.is_warm = True+ for _ in range(200):+ if stt.calls > 0:+ break+ await asyncio.sleep(0.01)+ with capsys.disabled():+ print(f"DIAG warm: calls={stt.calls} feeder_done={f.done()} driver_done={d.done()}")+ if f.done() and f.exception() is not None:+ print("feeder exc:", repr(f.exception()))+ if d.done() and d.exception() is not None:+ print("driver exc:", repr(d.exception()))+ print("stats:", wake.stats())+ import sys+ print("--- driver stack ---")+ d.print_stack(file=sys.stdout)+ stop.set()+ await src.put(None)+ d.cancel()+ f.cancel()+ for t in (d, f):+ try:+ await t+ except (asyncio.CancelledError, Exception): # noqa: BLE001, S110+ passdiff --git a/tests/unit/stt/test_fwhisper_warm_flag.py b/tests/unit/stt/test_fwhisper_warm_flag.pynew file mode 100644index 0000000000..cd7fa0db77--- /dev/null+++ b/tests/unit/stt/test_fwhisper_warm_flag.py@@ -0,0 +1,56 @@+"""FasterWhisperProvider.is_warm — the boot-time ready signal.++The rolling-whisper wake poll loop and the heavy-backend gate wait on this+flag instead of poking the model while it loads (the 114.7 s load-cascade TTU+forensic, 2026-07-02). Contract: False until ``warm_up`` completes, True even+when the priming inference fails (the model object exists, lazy paths cover+the rest), back to False after ``recover()`` drops a wedged model.+"""+from __future__ import annotations++import pytest++from jarvis.plugins.stt.fwhisper import FasterWhisperProvider+++def provider(monkeypatch) -> FasterWhisperProvider:+ p = FasterWhisperProvider()++ def _fake_ensure() -> None:+ p._model = object()++ monkeypatch.setattr(p, "_ensure_model", _fake_ensure)+ monkeypatch.setattr(+ p, "_transcribe_sync", lambda *a, **k: None, raising=True+ )+ return p+++def test_cold_provider_is_not_warm(provider: FasterWhisperProvider) -> None:+ assert provider.is_warm is False+++def test_warm_up_sets_the_flag(provider: FasterWhisperProvider) -> None:+ provider.warm_up()+ assert provider.is_warm is True+++def test_warm_up_sets_the_flag_even_if_priming_fails(+ provider: FasterWhisperProvider, monkeypatch+) -> None:+ def _boom(*a, **k): # noqa: ANN001, ANN002, ANN003+ raise RuntimeError("priming failed")++ monkeypatch.setattr(provider, "_transcribe_sync", _boom)+ provider.warm_up()+ # The model object exists, so pollers may transcribe (lazy paths cover the+ # rest) — leaving the flag False would park the wake poll loop forever.+ assert provider.is_warm is True+++def test_recover_resets_the_flag(provider: FasterWhisperProvider) -> None:+ provider.warm_up()+ provider.recover()+ assert provider.is_warm is False+ assert provider._model is None