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
feat(diagnostics): a headless live-call probe for the codex realtime path
rubenluetke10-beep60115e140c87
diff --git a/jarvis/diagnostics/realtime_probe.py b/jarvis/diagnostics/realtime_probe.pynew file mode 100644index 0000000000..814ffe5a52--- /dev/null+++ b/jarvis/diagnostics/realtime_probe.py@@ -0,0 +1,892 @@+"""Headless live-call probe for the codex-subscription realtime provider.++Drives ONE real ChatGPT-Live call end to end - real adapter, real app-server,+real aiortc media path, real local recognizer - with committed speech+fixtures instead of a microphone, against the production+``RealtimeVoiceSession`` in its desktop half-duplex shape. No sound card is+needed; aiortc encodes and decodes in-process.++This module is a developer diagnostic (invoked by+``scripts/codex_live_probe.py`` and by the env-gated integration test). It is+imported by nothing on the boot path (AP-26/AP-9), and every jarvis import+below is lazy so importing the module costs nothing.++Every run consumes the maintainer's ChatGPT subscription realtime usage; the+CLI caps calls per invocation. The desktop app must be STOPPED - the+fail-closed profile lock otherwise refuses the probe (exit 3), by design.++Capture format (``round.jsonl``): one JSON object per row -+``{"ts": epoch_s, "mono": monotonic_s, "src": ..., "kind": ..., "data": {...}}``+with ``src`` in {probe, surface, log, postmortem, notif}. The ``postmortem``+row is what ``scripts/diag_voice_sessions.py --harness`` and+``jarvis.diagnostics.realtime_forensics`` judge.+"""++from __future__ import annotations++import asyncio+import contextlib+import dataclasses+import json+import logging+import time+import wave+from collections import deque+from pathlib import Path+from typing import Any++log = logging.getLogger(__name__)++INPUT_RATE = 24_000+CHUNK_MS = 20+CHUNK_BYTES = INPUT_RATE * 2 * CHUNK_MS // 1000+LEAD_SILENCE_MS = 300+TRAIL_SILENCE_MS = 700+DEFAULT_REPLY_TIMEOUT_S = 15.0+#: Cold subscription handshakes legitimately take tens of seconds; the+#: provider declares 45 s and the probe adds slack rather than guessing.+HANDSHAKE_SLACK_S = 15.0+SCENARIO_WALL_CAP_S = 120.0+END_BOUND_S = 10.0+#: Greeting allowance: at most one assistant turn with no grounded user+#: utterance, and only within this window after audio_ready.+GREETING_WINDOW_S = 10.0+#: A mid-reply arrival gap larger than this (beyond the audio the previous+#: chunk carried) counts as a client-side hole. Above the 1.2 s quiescence+#: backstop on purpose: longer pauses legitimately become turn boundaries.+CONTINUITY_GAP_S = 1.5++_REPO_ROOT = Path(__file__).resolve().parents[2]+FIXTURE_DIR = _REPO_ROOT / "tests" / "fixtures" / "audio" / "realtime"+SCENARIO_DIR = _REPO_ROOT / "tests" / "integration" / "realtime" / "scenarios"+++class ProbeEnvironmentError(RuntimeError):+ """The environment cannot run a live probe; ``exit_code`` says why.++ 2 = missing prerequisite (login, fixtures, aiortc, network) ·+ 3 = the desktop app holds the voice-profile lock (close it first).+ """++ def __init__(self, message: str, *, exit_code: int = 2) -> None:+ super().__init__(message)+ self.exit_code = exit_code+++# ---------------------------------------------------------------------------+# Fixtures+# ---------------------------------------------------------------------------+++def load_manifest() -> list[dict[str, Any]]:+ manifest_path = FIXTURE_DIR / "manifest.json"+ if not manifest_path.exists():+ raise ProbeEnvironmentError(+ "speech fixtures are missing - run "+ "scripts/gen_realtime_speech_fixtures.py once"+ )+ return json.loads(manifest_path.read_text(encoding="utf-8"))+++def load_fixture_pcm(fixture_id: str) -> bytes:+ entry = next((e for e in load_manifest() if e.get("id") == fixture_id), None)+ if entry is None:+ raise ProbeEnvironmentError(f"unknown fixture id {fixture_id!r}")+ path = FIXTURE_DIR / str(entry["path"])+ with wave.open(str(path), "rb") as handle:+ if handle.getframerate() != INPUT_RATE or handle.getnchannels() != 1:+ raise ProbeEnvironmentError(+ f"fixture {fixture_id!r} is not {INPUT_RATE} Hz mono"+ )+ return handle.readframes(handle.getnframes())+++def load_scenario(name: str) -> dict[str, Any]:+ path = SCENARIO_DIR / f"{name}.json"+ if not path.exists():+ raise ProbeEnvironmentError(+ f"unknown scenario {name!r} (no {path.name} in {SCENARIO_DIR})"+ )+ return json.loads(path.read_text(encoding="utf-8"))+++# ---------------------------------------------------------------------------+# Capture+# ---------------------------------------------------------------------------+++class Capture:+ """Ordered probe timeline; one JSONL row per note."""++ def __init__(self) -> None:+ self.rows: list[dict[str, Any]] = []++ def note(self, src: str, kind: str, data: Any = None) -> None:+ self.rows.append(+ {+ "ts": time.time(),+ "mono": time.monotonic(),+ "src": src,+ "kind": kind,+ "data": data if data is not None else {},+ }+ )++ def write(self, path: Path) -> None:+ path.parent.mkdir(parents=True, exist_ok=True)+ with path.open("w", encoding="utf-8") as handle:+ for row in self.rows:+ handle.write(json.dumps(row, ensure_ascii=False, default=str))+ handle.write("\n")+++class _LogTap(logging.Handler):+ """Mirror jarvis log records into the capture (bounded message length)."""++ def __init__(self, capture: Capture) -> None:+ super().__init__(level=logging.INFO)+ self._capture = capture++ def emit(self, record: logging.LogRecord) -> None: # pragma: no cover - trivial+ try:+ message = record.getMessage()+ except Exception: # noqa: BLE001 - a broken record must not kill the probe+ message = "<unformattable log record>"+ self._capture.note(+ "log",+ record.levelname,+ {"logger": record.name, "message": message[:400]},+ )+++# ---------------------------------------------------------------------------+# Surface + microphone+# ---------------------------------------------------------------------------+++class ProbeSurface:+ """Desktop-surface stand-in recording everything with timestamps."""++ def __init__(self, capture: Capture) -> None:+ self._capture = capture+ self.json: list[dict[str, Any]] = []+ self.binary_bytes = 0+ self._tick = asyncio.Event()++ async def send_json(self, message: dict[str, Any]) -> None:+ payload = dict(message)+ self.json.append(payload)+ self._capture.note("surface", "json", payload)+ self._tick.set()++ async def send_binary(self, data: bytes) -> None:+ self.binary_bytes += len(data)+ self._capture.note("surface", "binary", {"bytes": len(data)})+ self._tick.set()++ def mark(self) -> int:+ return len(self.json)++ async def wait_json(+ self, predicate: Any, *, since: int = 0, timeout_s: float+ ) -> dict[str, Any] | None:+ async def _loop() -> dict[str, Any]:+ while True:+ self._tick.clear()+ for message in self.json[since:]:+ if predicate(message):+ return message+ await self._tick.wait()++ try:+ return await asyncio.wait_for(_loop(), timeout_s)+ except TimeoutError:+ return None+++class MicFeeder:+ """Continuous 24 kHz microphone stream: room tone, with spliced speech.++ Models the real desktop pipeline, which streams microphone frames for the+ whole call: silence between utterances is quiet ROOM TONE (the committed+ ~-55 dBFS fixture), never digital zero, so the energy gates under test see+ exactly what a real microphone would give them. Paced against an absolute+ deadline - a sleep-per-chunk loop would drift (the webrtc sender lesson).+ """++ def __init__(self, session: Any, capture: Capture) -> None:+ self._session = session+ self._capture = capture+ self._noise = load_fixture_pcm("room_noise")+ self._noise_at = 0+ self._segments: deque[bytes] = deque()+ self._task: asyncio.Task[None] | None = None+ self._stopped = asyncio.Event()+ self.resyncs = 0++ def speak(self, pcm: bytes) -> None:+ lead = b"\x00\x00" * (INPUT_RATE * LEAD_SILENCE_MS // 1000)+ trail = b"\x00\x00" * (INPUT_RATE * TRAIL_SILENCE_MS // 1000)+ self._segments.append(lead + pcm + trail)++ @property+ def speaking(self) -> bool:+ return bool(self._segments)++ def start(self) -> None:+ self._task = asyncio.create_task(self._run(), name="probe-mic-feeder")++ async def stop(self) -> None:+ self._stopped.set()+ if self._task is not None:+ self._task.cancel()+ with contextlib.suppress(asyncio.CancelledError):+ await self._task++ def _next_chunk(self) -> bytes:+ if self._segments:+ segment = self._segments[0]+ chunk, rest = segment[:CHUNK_BYTES], segment[CHUNK_BYTES:]+ if rest:+ self._segments[0] = rest+ else:+ self._segments.popleft()+ if len(chunk) < CHUNK_BYTES:+ chunk += b"\x00\x00" * ((CHUNK_BYTES - len(chunk)) // 2)+ return chunk+ start = self._noise_at+ end = start + CHUNK_BYTES+ if end <= len(self._noise):+ chunk = self._noise[start:end]+ self._noise_at = end if end < len(self._noise) else 0+ return chunk+ chunk = self._noise[start:] + self._noise[: end - len(self._noise)]+ self._noise_at = end - len(self._noise)+ return chunk++ async def _run(self) -> None:+ interval = CHUNK_MS / 1000.0+ next_at = time.monotonic()+ while not self._stopped.is_set():+ chunk = self._next_chunk()+ try:+ await self._session.handle_audio_frame(chunk)+ except Exception: # noqa: BLE001 - a dying session ends the feed+ log.debug("probe mic feed rejected a frame", exc_info=True)+ next_at += interval+ now = time.monotonic()+ if next_at < now - 0.5:+ # The probe process itself hiccuped; restart the clock rather+ # than bursting stale audio (mirrors the sender's own rule).+ self.resyncs += 1+ self._capture.note(+ "probe", "mic_resync", {"behind_s": round(now - next_at, 3)}+ )+ next_at = now+ await asyncio.sleep(max(0.0, next_at - now))+++# ---------------------------------------------------------------------------+# Environment checks+# ---------------------------------------------------------------------------+++def _require_webrtc() -> None:+ from jarvis.realtime.webrtc_transport import webrtc_unavailable_reason++ reason = webrtc_unavailable_reason()+ if reason:+ raise ProbeEnvironmentError(f"WebRTC transport unavailable: {reason}")+++def _provider_class() -> Any:+ from jarvis.plugins.realtime.codex_subscription import (+ CodexSubscriptionRealtimeProvider,+ )++ return CodexSubscriptionRealtimeProvider+++def _require_login() -> None:+ if not _provider_class().external_login_ready():+ raise ProbeEnvironmentError(+ "no ready Codex subscription voice profile - connect the ChatGPT "+ "subscription (Codex) card in the app first"+ )+++def _is_profile_lock_error(message: str) -> bool:+ return "another jarvis process" in message.lower()+++# ---------------------------------------------------------------------------+# Scenario runner+# ---------------------------------------------------------------------------+++async def run_scenario(+ scenario: dict[str, Any],+ *,+ out_dir: Path,+ budgets: dict[str, Any] | None = None,+ with_delegate: bool = False,+) -> dict[str, Any]:+ """Run one scenario as one live call; return the summary dict."""+ _require_webrtc()+ _require_login()+ manifest = load_manifest()++ from jarvis.core.bus import EventBus+ from jarvis.core.config import load_config+ from jarvis.core.events import RealtimeSessionPostmortem+ from jarvis.realtime.session import RealtimeVoiceSession++ cfg = load_config()+ provider = _provider_class().from_runtime_config(cfg)++ capture = Capture()+ capture.note("probe", "scenario", {"name": scenario.get("name", "?")})+ surface = ProbeSurface(capture)+ bus = EventBus()+ postmortems: list[dict[str, Any]] = []++ async def _on_postmortem(event: RealtimeSessionPostmortem) -> None:+ payload = dataclasses.asdict(event)+ payload.pop("trace_id", None)+ postmortems.append(payload)+ capture.note("postmortem", "session", payload)++ bus.subscribe(RealtimeSessionPostmortem, _on_postmortem)++ brain = None+ if with_delegate:+ brain = _build_delegate_brain(cfg)++ session = RealtimeVoiceSession(+ session_id=f"probe-{int(time.time())}",+ send_binary=surface.send_binary,+ send_json=surface.send_json,+ providers=[provider],+ config=cfg,+ bus=bus,+ surface="desktop",+ half_duplex=True,+ browser_sample_rate=INPUT_RATE,+ brain=brain,+ allow_classic_fallback=False,+ )++ tap = _LogTap(capture)+ jarvis_logger = logging.getLogger("jarvis")+ jarvis_logger.addHandler(tap)+ feeder: MicFeeder | None = None+ end_duration_s = 0.0+ try:+ handshake_budget = float(+ getattr(provider, "handshake_budget_s", 45.0) or 45.0+ )+ started = surface.mark()+ capture.note("probe", "audio_start", {})+ open_task = asyncio.create_task(+ session.handle_control(+ {"type": "audio_start", "sample_rate": INPUT_RATE}+ )+ )+ ready = await surface.wait_json(+ lambda m: m.get("type") in {"audio_ready", "provider_error", "hangup"},+ since=started,+ timeout_s=handshake_budget + HANDSHAKE_SLACK_S,+ )+ await asyncio.wait_for(open_task, timeout=HANDSHAKE_SLACK_S)+ if ready is None or ready.get("type") != "audio_ready":+ detail = str((ready or {}).get("error", "no audio_ready arrived"))+ if _is_profile_lock_error(detail):+ raise ProbeEnvironmentError(+ "the desktop app is running and holds the subscription "+ "voice profile - close the Jarvis app first",+ exit_code=3,+ )+ raise ProbeEnvironmentError(f"session did not open: {detail}")+ capture.note("probe", "ready", ready)++ feeder = MicFeeder(session, capture)+ feeder.start()++ deadline = time.monotonic() + SCENARIO_WALL_CAP_S+ for step in scenario.get("steps", ()): # noqa: PLR1702 - a flat script+ if time.monotonic() > deadline:+ capture.note("probe", "wall_cap", {"cap_s": SCENARIO_WALL_CAP_S})+ break+ if "speak" in step:+ fixture_id = str(step["speak"])+ capture.note("probe", "speak", _fixture_meta(manifest, fixture_id))+ feeder.speak(load_fixture_pcm(fixture_id))+ elif "wait_reply" in step:+ timeout_s = float(+ (step["wait_reply"] or {}).get("timeout_s", DEFAULT_REPLY_TIMEOUT_S)+ )+ mark = surface.mark()+ reply = await surface.wait_json(+ lambda m: m.get("type") == "turn_complete",+ since=mark,+ timeout_s=timeout_s,+ )+ capture.note(+ "probe",+ "wait_reply",+ {"timed_out": reply is None, "timeout_s": timeout_s},+ )+ elif "silence_s" in step:+ capture.note("probe", "silence", {"seconds": step["silence_s"]})+ await asyncio.sleep(float(step["silence_s"]))+ elif "barge_in" in step:+ spec = step["barge_in"] or {}+ after_ms = float(spec.get("after_reply_ms", 700))+ mark = surface.mark()+ # Wait for a reply to actually be playing before cutting it.+ await surface.wait_json(+ lambda m: m.get("type") == "transcript"+ and m.get("role") == "assistant",+ since=mark,+ timeout_s=DEFAULT_REPLY_TIMEOUT_S,+ )+ await asyncio.sleep(after_ms / 1000.0)+ capture.note("probe", "barge_in", {"after_reply_ms": after_ms})+ await session.handle_control({"type": "barge_in"})+ then_speak = spec.get("then_speak")+ if then_speak:+ capture.note(+ "probe", "speak", _fixture_meta(manifest, str(then_speak))+ )+ feeder.speak(load_fixture_pcm(str(then_speak)))+ elif "end" in step:+ break+ else: # An unknown step is a scenario bug, not a soft skip.+ raise ProbeEnvironmentError(f"unknown scenario step: {step!r}")+ finally:+ if feeder is not None:+ await feeder.stop()+ end_started = time.monotonic()+ with contextlib.suppress(Exception):+ await asyncio.wait_for(session.end(reason="hotkey"), END_BOUND_S + 5.0)+ end_duration_s = time.monotonic() - end_started+ capture.note("probe", "end", {"duration_s": round(end_duration_s, 3)})+ jarvis_logger.removeHandler(tap)++ postmortem = postmortems[-1] if postmortems else {}+ verdicts = evaluate_scenario(+ capture.rows,+ postmortem,+ scenario,+ manifest,+ budgets=budgets or {},+ end_duration_s=end_duration_s,+ )+ summary = {+ "scenario": scenario.get("name", "?"),+ "asserts": verdicts,+ "postmortem": postmortem,+ "passed": all(v["status"] != "fail" for v in verdicts.values()),+ }+ await asyncio.to_thread(_persist, out_dir, capture, summary)+ return summary+++def _persist(out_dir: Path, capture: Capture, summary: dict[str, Any]) -> None:+ """Synchronous capture/summary write, thread-hopped by the async runners."""+ out_dir.mkdir(parents=True, exist_ok=True)+ capture.write(out_dir / "round.jsonl")+ (out_dir / "summary.json").write_text(+ json.dumps(summary, indent=2, ensure_ascii=False, default=str) + "\n",+ encoding="utf-8",+ )+++def _fixture_meta(manifest: list[dict[str, Any]], fixture_id: str) -> dict[str, Any]:+ entry = next((e for e in manifest if e.get("id") == fixture_id), {})+ return {+ "id": fixture_id,+ "text": entry.get("text", ""),+ "language": entry.get("language", ""),+ }+++def _build_delegate_brain(cfg: Any) -> Any:+ try:+ from jarvis.brain.factory import build_brain_manager # type: ignore[attr-defined]++ return build_brain_manager(cfg)+ except Exception as exc: # noqa: BLE001 - opt-in extra, honest refusal+ raise ProbeEnvironmentError(+ f"--with-delegate needs a configured brain: {exc}"+ ) from exc+++# ---------------------------------------------------------------------------+# Assertions+# ---------------------------------------------------------------------------+++def _normalize(text: str) -> str:+ cleaned = "".join(+ c.lower() if c.isalnum() or c.isspace() else " " for c in text+ )+ return " ".join(cleaned.split())+++def evaluate_scenario(+ rows: list[dict[str, Any]],+ postmortem: dict[str, Any],+ scenario: dict[str, Any],+ manifest: list[dict[str, Any]],+ *,+ budgets: dict[str, Any],+ end_duration_s: float,+) -> dict[str, dict[str, str]]:+ """Judge one capture against the scenario's assert list.++ Pure over the capture rows + postmortem, so it is unit-testable without a+ live call. Statuses: pass | warn | fail.+ """+ wanted = list(scenario.get("asserts", ()))+ verdicts: dict[str, dict[str, str]] = {}++ surface = [r for r in rows if r["src"] == "surface"]+ ready_rows = [r for r in rows if r["src"] == "probe" and r["kind"] == "ready"]+ ready_mono = ready_rows[0]["mono"] if ready_rows else 0.0++ # Reconstruct exchanges: a turn_complete "earns" a turn when a non-empty+ # final user transcript arrived since the previous boundary.+ exchanges = 0+ ungrounded_turns: list[float] = []+ user_final_pending = False+ assistant_text_rows: list[tuple[float, str]] = []+ for row in surface:+ data = row["data"]+ if row["kind"] != "json":+ continue+ if data.get("type") == "transcript":+ text = str(data.get("text", "")).strip()+ if data.get("role") == "user" and data.get("is_final") and text:+ user_final_pending = True+ elif data.get("role") == "assistant" and text:+ assistant_text_rows.append((row["mono"], text))+ elif data.get("type") == "turn_complete":+ if user_final_pending:+ exchanges += 1+ user_final_pending = False+ else:+ # A boundary with no grounded user final: greeting or self-talk.+ ungrounded_turns.append(row["mono"])++ def _verdict(name: str, status: str, detail: str) -> None:+ verdicts[name] = {"status": status, "detail": detail}++ for name in wanted:+ if name.startswith("turns>="):+ need = int(name.split(">=", 1)[1])+ _verdict(+ name,+ "pass" if exchanges >= need else "fail",+ f"{exchanges} grounded exchange(s), need {need}",+ )+ elif name == "no_ungrounded":+ allowed = [+ mono+ for mono in ungrounded_turns+ if ready_mono and mono - ready_mono <= GREETING_WINDOW_S+ ][:1]+ extra = [m for m in ungrounded_turns if m not in allowed]+ _verdict(+ name,+ "pass" if not extra else "fail",+ f"{len(ungrounded_turns)} ungrounded boundary(ies), "+ f"{len(allowed)} allowed as the greeting",+ )+ elif name == "no_selftalk":+ late_assistant = [+ mono+ for mono, _ in assistant_text_rows+ if ready_mono and mono - ready_mono > GREETING_WINDOW_S+ ]+ _verdict(+ name,+ "pass" if not late_assistant else "fail",+ f"{len(late_assistant)} assistant transcript(s) past the "+ f"{GREETING_WINDOW_S:.0f}s greeting window on a silent mic",+ )+ elif name == "no_roleplay":+ spoken_ids = [+ r["data"].get("id")+ for r in rows+ if r["src"] == "probe" and r["kind"] == "speak"+ ]+ questions = [+ _normalize(str(e.get("text", "")))+ for e in manifest+ if e.get("id") in spoken_ids and e.get("text")+ ]+ assistant_all = _normalize(" ".join(t for _, t in assistant_text_rows))+ echoed = [q for q in questions if len(q) >= 15 and q in assistant_all]+ _verdict(+ name,+ "pass" if not echoed else "fail",+ "assistant transcript never contains a full probe question"+ if not echoed+ else f"assistant echoed the user's question verbatim: {echoed[0][:60]!r}",+ )+ elif name == "audio_continuity":+ holes = _continuity_holes(rows)+ drops = int(postmortem.get("recv_dropped_frames", 0) or 0)+ ok = not holes and drops == 0+ _verdict(+ name,+ "pass" if ok else "fail",+ f"{len(holes)} client-side hole(s) > {CONTINUITY_GAP_S}s, "+ f"{drops} recv drop(s)",+ )+ elif name == "no_rebuilds":+ rebuilds = int(postmortem.get("rebuilds", 0) or 0)+ stun = int(postmortem.get("stun_retries", 0) or 0)+ _verdict(+ name,+ "pass" if rebuilds == 0 and stun == 0 else "fail",+ f"rebuilds={rebuilds} stun_retries={stun}",+ )+ elif name == "mic_wall_clock":+ resyncs = int(postmortem.get("sender_pacing_resyncs", 0) or 0)+ shed = int(postmortem.get("sender_shed_frames", 0) or 0)+ _verdict(+ name,+ "pass" if resyncs == 0 and shed == 0 else "fail",+ f"sender resyncs={resyncs} shed_frames={shed}",+ )+ elif name == "clean_close":+ clean = bool(postmortem.get("close_clean", False))+ bounded = end_duration_s <= END_BOUND_S+ _verdict(+ name,+ "pass" if clean and bounded else "fail",+ f"close_clean={clean} end_duration={end_duration_s:.1f}s",+ )+ elif name == "spawn_budget":+ ready_ms = int(postmortem.get("ready_ms", 0) or 0)+ first_ms = int(postmortem.get("first_audio_ms", 0) or 0)+ ready_cap = float(budgets.get("ready_s", 4.0)) * 1000+ first_cap = float(budgets.get("first_audio_s", 6.0)) * 1000+ over = ready_ms > ready_cap or (first_ms and first_ms > first_cap)+ enforce = bool(budgets.get("enforce", False))+ status = "pass" if not over else ("fail" if enforce else "warn")+ _verdict(+ name,+ status,+ f"ready={ready_ms}ms (cap {ready_cap:.0f}), "+ f"first_audio={first_ms}ms (cap {first_cap:.0f})",+ )+ else:+ _verdict(name, "fail", "unknown assert - fix the scenario")++ return verdicts+++def _continuity_holes(rows: list[dict[str, Any]]) -> list[float]:+ """Arrival gaps between audio chunks of one open turn, beyond the audio+ the previous chunk itself carried and beyond CONTINUITY_GAP_S."""+ holes: list[float] = []+ prev_mono: float | None = None+ prev_audio_s = 0.0+ for row in rows:+ if row["src"] != "surface":+ continue+ data = row["data"]+ if row["kind"] == "binary":+ mono = row["mono"]+ if prev_mono is not None:+ gap = mono - prev_mono - prev_audio_s+ if gap > CONTINUITY_GAP_S:+ holes.append(round(gap, 3))+ prev_mono = mono+ prev_audio_s = int(data.get("bytes", 0)) / 2 / INPUT_RATE+ elif row["kind"] == "json" and data.get("type") == "turn_complete":+ prev_mono = None # a boundary legitimately pauses the stream+ return holes+++# ---------------------------------------------------------------------------+# Dump mode (contract discovery)+# ---------------------------------------------------------------------------+++async def run_dump(*, out_dir: Path, listen_s: float = 25.0) -> dict[str, Any]:+ """One adapter-bypass call that records EVERY app-server notification.++ Purpose: convert the guessed ``_TERMINAL_RESPONSE_ITEMS`` spelling into+ live evidence, and answer whether ``realtime_stop`` -> ``realtime_start``+ works on the SAME thread (the STUN-retry salvage question). Writes the+ full notification stream to the (gitignored) capture; the returned+ summary carries only type names, never transcript payloads.+ """+ _require_webrtc()+ _require_login()++ from jarvis.codex_app_server import get_shared_codex_app_server+ from jarvis.plugins.realtime.codex_subscription import (+ _TERMINAL_RESPONSE_ITEMS,+ _THREAD_BASE_INSTRUCTIONS,+ _THREAD_DEVELOPER_INSTRUCTIONS,+ _cleanup_remote_thread,+ _thread_id_from_result,+ )+ from jarvis.realtime.webrtc_transport import RealtimeWebRtcAudioEndpoint++ capture = Capture()+ capture.note("probe", "dump_start", {"listen_s": listen_s})+ client = get_shared_codex_app_server()+ endpoint = RealtimeWebRtcAudioEndpoint(None)+ thread_id = ""+ methods: dict[str, int] = {}+ item_types: dict[str, int] = {}+ audio_bytes = 0+ second_start: dict[str, Any] = {"attempted": False}+ try:+ offer_sdp = await endpoint.create_offer()+ try:+ thread_result = await client.thread_start(+ base_instructions=_THREAD_BASE_INSTRUCTIONS,+ developer_instructions=_THREAD_DEVELOPER_INSTRUCTIONS,+ ephemeral=True,+ )+ except Exception as exc: # noqa: BLE001 - map the lock to exit 3+ if _is_profile_lock_error(str(exc)):+ raise ProbeEnvironmentError(+ "the desktop app is running and holds the subscription "+ "voice profile - close the Jarvis app first",+ exit_code=3,+ ) from exc+ raise+ thread_id = _thread_id_from_result(thread_result)+ if not thread_id:+ raise ProbeEnvironmentError(+ "Codex app-server did not return a thread id"+ )+ subscription = client.subscribe(thread_id)+ start = await client.realtime_start(+ thread_id,+ output_modality="audio",+ offer_sdp=offer_sdp,+ prompt="",+ model=None,+ voice="cove",+ version="v3",+ include_startup_context=False,+ client_managed_handoffs=True,+ )+ answer_sdp = str(getattr(start, "answer_sdp", "") or "")+ capture.note("probe", "realtime_start", {"version": "v3"})+ await endpoint.apply_answer(answer_sdp)+ await endpoint.wait_connected()++ async def _pump_notifications() -> None:+ while True:+ notification = await subscription.get(timeout_s=listen_s)+ method = str(getattr(notification, "method", "") or "")+ params = getattr(notification, "params", None) or {}+ methods[method] = methods.get(method, 0) + 1+ item = params.get("item") if isinstance(params, dict) else None+ if isinstance(item, dict) and item.get("type"):+ item_type = str(item["type"])+ item_types[item_type] = item_types.get(item_type, 0) + 1+ capture.note(+ "notif", method or "?", params if isinstance(params, dict) else {}+ )++ async def _pump_audio_out() -> None:+ nonlocal audio_bytes+ while True:+ pcm = await endpoint.next_output_pcm()+ if pcm is None:+ return+ audio_bytes += len(pcm)++ async def _feed_mic() -> None:+ pcm = load_fixture_pcm("en_giraffe")+ lead = b"\x00\x00" * (INPUT_RATE * LEAD_SILENCE_MS // 1000)+ trail = b"\x00\x00" * (INPUT_RATE * TRAIL_SILENCE_MS // 1000)+ stream = lead + pcm + trail+ interval = CHUNK_MS / 1000.0+ next_at = time.monotonic()+ for offset in range(0, len(stream), CHUNK_BYTES):+ endpoint.send_pcm(stream[offset : offset + CHUNK_BYTES], INPUT_RATE)+ next_at += interval+ await asyncio.sleep(max(0.0, next_at - time.monotonic()))++ pumps = [+ asyncio.create_task(_pump_notifications(), name="dump-notifs"),+ asyncio.create_task(_pump_audio_out(), name="dump-audio"),+ ]+ try:+ await _feed_mic()+ await asyncio.sleep(listen_s)+ finally:+ for pump in pumps:+ pump.cancel()+ for pump in pumps:+ with contextlib.suppress(+ asyncio.CancelledError, Exception+ ):+ await pump++ # Same-thread restart probe: does v3 accept a second realtime_start?+ second_start["attempted"] = True+ try:+ await client.realtime_stop(thread_id)+ fresh_endpoint = RealtimeWebRtcAudioEndpoint(None)+ try:+ fresh_offer = await fresh_endpoint.create_offer()+ restart = await client.realtime_start(+ thread_id,+ output_modality="audio",+ offer_sdp=fresh_offer,+ prompt="",+ model=None,+ voice="cove",+ version="v3",+ include_startup_context=False,+ client_managed_handoffs=True,+ )+ second_start["ok"] = bool(+ str(getattr(restart, "answer_sdp", "") or "").strip()+ )+ finally:+ await fresh_endpoint.close()+ except Exception as exc: # noqa: BLE001 - the refusal IS the answer+ second_start["ok"] = False+ second_start["error"] = f"{type(exc).__name__}: {exc}"[:300]+ capture.note("probe", "same_thread_restart", second_start)+ finally:+ with contextlib.suppress(Exception):+ await endpoint.close()+ if thread_id:+ with contextlib.suppress(Exception):+ await _cleanup_remote_thread(client, thread_id)++ observed_terminals = sorted(+ t for t in item_types if t in _TERMINAL_RESPONSE_ITEMS+ )+ candidate_terminals = sorted(+ t+ for t in item_types+ if "done" in t or "complete" in t or "finished" in t or "stop" in t+ )+ summary = {+ "methods": dict(sorted(methods.items())),+ "item_types": dict(sorted(item_types.items())),+ "audio_bytes": audio_bytes,+ "terminal_in_frozenset": observed_terminals,+ "terminal_candidates": candidate_terminals,+ "same_thread_restart": second_start,+ }+ await asyncio.to_thread(_persist, out_dir, capture, summary)+ return summary++diff --git a/scripts/ci/german-allowlist.txt b/scripts/ci/german-allowlist.txtindex e80eb570a4..8280905ed3 100644--- a/scripts/ci/german-allowlist.txt+++ b/scripts/ci/german-allowlist.txt@@ -56,6 +56,13 @@ jarvis/plugins/tool/navigate.pyjarvis/plugins/tool/inspect_pointer.pyjarvis/plugins/tool/contact_lookup.py+# --- Codex live-probe speech fixtures: the German nonce sentences the+# headless realtime harness SPEAKS at ChatGPT-Live (speech-input data for+# a bilingual voice product, category 3; committed as WAV + manifest so+# the probe needs no TTS key) ---+scripts/gen_realtime_speech_fixtures.py+tests/fixtures/audio/realtime/manifest.json+# --- Tests for the above: German fixture utterances are required to exercise# the bilingual recognizers (same rationale as the gate's own tests) ---tests/unit/pointer/*diff --git a/scripts/codex_live_probe.py b/scripts/codex_live_probe.pynew file mode 100644index 0000000000..d1c00525dc--- /dev/null+++ b/scripts/codex_live_probe.py@@ -0,0 +1,160 @@+"""Drive real headless ChatGPT-Live calls against the codex-subscription path.++The reproduction tool this provider never had: every earlier fix round was+verified by reading ``data/jarvis_desktop.log`` after a live call died. This+CLI runs scripted calls (committed speech fixtures, real adapter, real+app-server, real WebRTC) and prints a PASS/WARN/FAIL verdict per scenario.++Every call consumes the ChatGPT subscription's realtime usage - the run is+capped (``--max-calls``, default 5; more needs ``--yes-really``). The desktop+app must be STOPPED first: the fail-closed voice-profile lock otherwise+refuses the probe (exit 3).++Usage::++ python scripts/codex_live_probe.py --dump # contract discovery+ python scripts/codex_live_probe.py --scenario three_turns_de+ python scripts/codex_live_probe.py --scenario three_turns_de \+ --scenario barge_in_followup --scenario silence_no_selftalk+ python scripts/diag_voice_sessions.py --harness <out>/round.jsonl++Exit codes: 0 pass · 1 assert failed · 2 environment missing · 3 the app+holds the profile lock.+"""+from __future__ import annotations++import argparse+import asyncio+import json+import sys+import time+from pathlib import Path++if hasattr(sys.stdout, "reconfigure"):+ sys.stdout.reconfigure(encoding="utf-8") # type: ignore[union-attr]++# The worktree the script lives in is the code that runs, regardless of where+# the editable install points (BUG-006 class) - same pattern as+# scripts/diag_voice_sessions.py.+REPO_ROOT = Path(__file__).resolve().parents[1]+sys.path.insert(0, str(REPO_ROOT))++from jarvis.diagnostics.realtime_probe import ( # noqa: E402+ ProbeEnvironmentError,+ load_scenario,+ run_dump,+ run_scenario,+)++DEFAULT_MAX_CALLS = 5+++def _print_summary(summary: dict) -> None:+ verdict = "PASS" if summary.get("passed") else "FAIL"+ print(f"\nscenario {summary.get('scenario')}: {verdict}")+ for name, entry in (summary.get("asserts") or {}).items():+ print(f" [{entry['status']:4}] {name}: {entry['detail']}")+ postmortem = summary.get("postmortem") or {}+ if postmortem:+ print(+ f" postmortem: turns={postmortem.get('turns_completed', 0)} "+ f"ready={postmortem.get('ready_ms', 0)}ms "+ f"first_audio={postmortem.get('first_audio_ms', 0)}ms "+ f"rebuilds={postmortem.get('rebuilds', 0)}"+ )+++async def _run(args: argparse.Namespace) -> int:+ calls_planned = (1 if args.dump else 0) + len(args.scenario)+ if calls_planned == 0:+ print("nothing to do: pass --dump and/or --scenario <name>")+ return 2+ if calls_planned > args.max_calls and not args.yes_really:+ print(+ f"{calls_planned} live calls exceed the cap of {args.max_calls}; "+ "re-run with --yes-really if you mean it"+ )+ return 2+ print(+ f"NOTE: {calls_planned} live call(s) will bill the ChatGPT "+ "subscription's realtime usage."+ )++ stamp = time.strftime("%Y%m%d-%H%M%S")+ base = args.out or (REPO_ROOT / "data" / "diagnostics" / "codex_live" / stamp)+ base = Path(base)+ exit_code = 0++ if args.dump:+ print("\n-- dump round (contract discovery) --")+ summary = await run_dump(out_dir=base / "dump")+ print(json.dumps(summary, indent=2, ensure_ascii=False, default=str))+ terminal = summary.get("terminal_in_frozenset") or []+ candidates = summary.get("terminal_candidates") or []+ if terminal:+ print(f"terminal response item observed: {terminal} - IN _TERMINAL_RESPONSE_ITEMS")+ elif candidates:+ print(+ f"terminal response item observed: {candidates} - "+ "NOT IN _TERMINAL_RESPONSE_ITEMS (update the frozenset)"+ )+ else:+ print(+ "no terminal-shaped item observed - the quiescence backstop "+ "remains the only boundary"+ )++ budgets = {+ "ready_s": args.budget_ready_s,+ "first_audio_s": args.budget_first_audio_s,+ "enforce": args.enforce_budgets,+ }+ for name in args.scenario:+ print(f"\n-- scenario {name} --")+ scenario = load_scenario(name)+ summary = await run_scenario(+ scenario,+ out_dir=base / name,+ budgets=budgets,+ with_delegate=args.with_delegate,+ )+ _print_summary(summary)+ if not summary.get("passed"):+ exit_code = 1++ print(f"\ncaptures under {base}")+ return exit_code+++def main() -> int:+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])+ parser.add_argument("--scenario", action="append", default=[])+ parser.add_argument("--dump", action="store_true")+ parser.add_argument("--out", type=Path, default=None)+ parser.add_argument("--max-calls", type=int, default=DEFAULT_MAX_CALLS)+ parser.add_argument("--yes-really", action="store_true")+ parser.add_argument("--budget-ready-s", type=float, default=4.0)+ parser.add_argument("--budget-first-audio-s", type=float, default=6.0)+ parser.add_argument(+ "--enforce-budgets",+ action="store_true",+ help="spawn budget overruns FAIL instead of WARN (the B6 flip)",+ )+ parser.add_argument(+ "--with-delegate",+ action="store_true",+ help="wire the configured brain so the delegation scenario can run",+ )+ args = parser.parse_args()+ try:+ return asyncio.run(_run(args))+ except ProbeEnvironmentError as exc:+ print(f"probe environment: {exc}")+ return exc.exit_code+ except KeyboardInterrupt:+ print("interrupted")+ return 130+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/scripts/gen_realtime_speech_fixtures.py b/scripts/gen_realtime_speech_fixtures.pynew file mode 100644index 0000000000..079ff5d762--- /dev/null+++ b/scripts/gen_realtime_speech_fixtures.py@@ -0,0 +1,232 @@+"""Generate the committed speech fixtures for the codex live-call probe.++Run ONCE (or when a sentence changes) by a developer with a working TTS+provider; the WAVs are committed so RUNNING the probe needs no TTS key at+all. Uses the normal capability-resolved TTS chain (``build_tts_from_config``,+AP-22) exactly like ``scripts/measure_voice_stages.py``.++The sentences are NONCE questions: each carries an invented word or object+that cannot occur in ordinary conversation, so the probe's role-play check+can match the literal question inside an assistant transcript without false+positives. Room tone is generated deterministically at ~-55 dBFS - genuinely+quiet, but never digital zero, which would cheat the energy gates the probe+exists to exercise.++Usage::++ python scripts/gen_realtime_speech_fixtures.py # write fixtures+ python scripts/gen_realtime_speech_fixtures.py --dry-run # list only+"""+from __future__ import annotations++import argparse+import asyncio+import json+import random+import sys+import wave+from pathlib import Path++if hasattr(sys.stdout, "reconfigure"):+ sys.stdout.reconfigure(encoding="utf-8") # type: ignore[union-attr]++REPO = Path(__file__).resolve().parents[1]+if str(REPO) not in sys.path:+ sys.path.insert(0, str(REPO))++from jarvis.core.config import load_config # noqa: E402++TARGET_RATE = 24_000 # the codex adapter's _INPUT_RATE+FIXTURE_DIR = REPO / "tests" / "fixtures" / "audio" / "realtime"+MAX_FILE_BYTES = 500_000+NOISE_SECONDS = 8.0+NOISE_PEAK = 58 # ~-55 dBFS on int16 full scale+NOISE_SEED = 20260806++#: id, language, BCP-47 for TTS, the sentence, and its load-bearing nonce.+#: German sentences are speech-input vocabulary for the probe (§1 category 3;+#: this file and the manifest are entries in scripts/ci/german-allowlist.txt).+SENTENCES: tuple[dict[str, str], ...] = (+ {+ "id": "en_giraffe",+ "language": "en",+ "bcp47": "en-US",+ "text": "What color is the violet giraffe from my example? Answer in one short sentence.",+ "nonce": "violet giraffe",+ },+ {+ "id": "en_tandelbrook",+ "language": "en",+ "bcp47": "en-US",+ "text": "Please repeat my invented word tandelbrook exactly once.",+ "nonce": "tandelbrook",+ },+ {+ "id": "en_bicycle",+ "language": "en",+ "bcp47": "en-US",+ "text": "How many wheels does my imaginary quintuple bicycle have?",+ "nonce": "quintuple bicycle",+ },+ {+ "id": "en_glimmerpond",+ "language": "en",+ "bcp47": "en-US",+ "text": "Name one word that rhymes with my invented word glimmerpond.",+ "nonce": "glimmerpond",+ },+ {+ "id": "en_zebrastorm",+ "language": "en",+ "bcp47": "en-US",+ "text": "In one sentence, what would a zebrastorm picnic be?",+ "nonce": "zebrastorm",+ },+ {+ "id": "de_giraffe",+ "language": "de",+ "bcp47": "de-DE",+ "text": (+ "Welche Farbe hat die violette Giraffe aus meinem Beispiel? "+ "Antworte in einem kurzen Satz."+ ),+ "nonce": "violette Giraffe",+ },+ {+ "id": "de_tandelbrook",+ "language": "de",+ "bcp47": "de-DE",+ "text": "Bitte wiederhole mein erfundenes Wort Tandelbrook genau einmal.",+ "nonce": "Tandelbrook",+ },+ {+ "id": "de_fahrrad",+ "language": "de",+ "bcp47": "de-DE",+ "text": "Wie viele Räder hat mein erfundenes Fünffach-Fahrrad?",+ "nonce": "Fünffach-Fahrrad",+ },+)+++def _write_wav(path: Path, pcm: bytes) -> None:+ with wave.open(str(path), "wb") as handle:+ handle.setnchannels(1)+ handle.setsampwidth(2)+ handle.setframerate(TARGET_RATE)+ handle.writeframes(pcm)+++def _room_noise() -> bytes:+ # Deterministic room tone, not cryptography - reproducible fixtures beat+ # secure randomness here.+ rng = random.Random(NOISE_SEED) # noqa: S311+ samples = int(NOISE_SECONDS * TARGET_RATE)+ return b"".join(+ rng.randint(-NOISE_PEAK, NOISE_PEAK).to_bytes(2, "little", signed=True)+ for _ in range(samples)+ )+++async def _synthesize(tts, text: str, bcp47: str) -> tuple[bytes, int]:+ """Return (pcm, source_rate) for one sentence via the real TTS chain."""+ pieces: list[bytes] = []+ rate = TARGET_RATE+ try:+ stream = tts.synthesize(text, language_code=bcp47)+ except TypeError:+ stream = tts.synthesize(text)+ async for chunk in stream:+ pieces.append(bytes(chunk.pcm))+ rate = int(getattr(chunk, "sample_rate", TARGET_RATE) or TARGET_RATE)+ return b"".join(pieces), rate+++def _resample(pcm: bytes, source_rate: int) -> bytes:+ if source_rate == TARGET_RATE:+ return pcm+ from jarvis.realtime.audio import StreamingPcm16Resampler++ # One whole utterance in one call; the resampler's un-flushed tail is a+ # single trailing sample and does not matter for a fixture.+ return StreamingPcm16Resampler(source_rate, TARGET_RATE).process(pcm)+++async def main(dry_run: bool) -> int:+ if dry_run:+ for entry in SENTENCES:+ print(f"{entry['id']:16} [{entry['language']}] {entry['text']}")+ print("room_noise [--] deterministic ~-55 dBFS room tone")+ return 0++ cfg = load_config(REPO / "jarvis.toml")+ from jarvis.plugins.tts import build_tts_from_config++ tts = build_tts_from_config(cfg.tts)+ print(f"TTS chain: {type(tts).__name__}")+ FIXTURE_DIR.mkdir(parents=True, exist_ok=True)++ manifest: list[dict[str, object]] = []+ for entry in SENTENCES:+ pcm, rate = await _synthesize(tts, entry["text"], entry["bcp47"])+ if not pcm:+ print(f"ERROR: TTS produced no audio for {entry['id']}")+ return 1+ pcm = _resample(pcm, rate)+ duration_ms = int(len(pcm) / 2 / TARGET_RATE * 1000)+ path = FIXTURE_DIR / f"{entry['id']}.wav"+ _write_wav(path, pcm)+ size = path.stat().st_size+ if size > MAX_FILE_BYTES:+ print(+ f"ERROR: {path.name} is {size} bytes (cap {MAX_FILE_BYTES}) - "+ "shorten the sentence"+ )+ return 1+ manifest.append(+ {+ "id": entry["id"],+ "path": path.name,+ "language": entry["language"],+ "text": entry["text"],+ "nonce": entry["nonce"],+ "duration_ms": duration_ms,+ "sample_rate": TARGET_RATE,+ }+ )+ print(f" {path.name}: {duration_ms} ms, {size / 1024:.0f} KB")++ noise = _room_noise()+ noise_path = FIXTURE_DIR / "room_noise.wav"+ _write_wav(noise_path, noise)+ manifest.append(+ {+ "id": "room_noise",+ "path": noise_path.name,+ "language": "",+ "text": "",+ "nonce": "",+ "duration_ms": int(NOISE_SECONDS * 1000),+ "sample_rate": TARGET_RATE,+ }+ )+ print(f" {noise_path.name}: {int(NOISE_SECONDS * 1000)} ms (deterministic)")++ manifest_path = FIXTURE_DIR / "manifest.json"+ manifest_path.write_text(+ json.dumps(manifest, indent=2, ensure_ascii=False) + "\n",+ encoding="utf-8",+ )+ print(f"wrote {manifest_path}")+ return 0+++if __name__ == "__main__":+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])+ parser.add_argument("--dry-run", action="store_true")+ args = parser.parse_args()+ try:+ from _grpc_exit import hard_exit # noqa: PLC0415 - sibling helper+ except ImportError: # pragma: no cover - helper is repo-local+ raise SystemExit(asyncio.run(main(args.dry_run))) from None+ hard_exit(asyncio.run(main(args.dry_run)))diff --git a/tests/fixtures/audio/realtime/de_fahrrad.wav b/tests/fixtures/audio/realtime/de_fahrrad.wavnew file mode 100644index 0000000000..d0006f10baBinary files /dev/null and b/tests/fixtures/audio/realtime/de_fahrrad.wav differdiff --git a/tests/fixtures/audio/realtime/de_giraffe.wav b/tests/fixtures/audio/realtime/de_giraffe.wavnew file mode 100644index 0000000000..d82dba1f8eBinary files /dev/null and b/tests/fixtures/audio/realtime/de_giraffe.wav differdiff --git a/tests/fixtures/audio/realtime/de_tandelbrook.wav b/tests/fixtures/audio/realtime/de_tandelbrook.wavnew file mode 100644index 0000000000..2087e61cb6Binary files /dev/null and b/tests/fixtures/audio/realtime/de_tandelbrook.wav differdiff --git a/tests/fixtures/audio/realtime/en_bicycle.wav b/tests/fixtures/audio/realtime/en_bicycle.wavnew file mode 100644index 0000000000..df9abc043aBinary files /dev/null and b/tests/fixtures/audio/realtime/en_bicycle.wav differdiff --git a/tests/fixtures/audio/realtime/en_giraffe.wav b/tests/fixtures/audio/realtime/en_giraffe.wavnew file mode 100644index 0000000000..437482356cBinary files /dev/null and b/tests/fixtures/audio/realtime/en_giraffe.wav differdiff --git a/tests/fixtures/audio/realtime/en_glimmerpond.wav b/tests/fixtures/audio/realtime/en_glimmerpond.wavnew file mode 100644index 0000000000..9d53de79bdBinary files /dev/null and b/tests/fixtures/audio/realtime/en_glimmerpond.wav differdiff --git a/tests/fixtures/audio/realtime/en_tandelbrook.wav b/tests/fixtures/audio/realtime/en_tandelbrook.wavnew file mode 100644index 0000000000..2b0f634a37Binary files /dev/null and b/tests/fixtures/audio/realtime/en_tandelbrook.wav differdiff --git a/tests/fixtures/audio/realtime/en_zebrastorm.wav b/tests/fixtures/audio/realtime/en_zebrastorm.wavnew file mode 100644index 0000000000..b518d5abb5Binary files /dev/null and b/tests/fixtures/audio/realtime/en_zebrastorm.wav differdiff --git a/tests/fixtures/audio/realtime/manifest.json b/tests/fixtures/audio/realtime/manifest.jsonnew file mode 100644index 0000000000..16e0c04493--- /dev/null+++ b/tests/fixtures/audio/realtime/manifest.json@@ -0,0 +1,83 @@+[+ {+ "id": "en_giraffe",+ "path": "en_giraffe.wav",+ "language": "en",+ "text": "What color is the violet giraffe from my example? Answer in one short sentence.",+ "nonce": "violet giraffe",+ "duration_ms": 5534,+ "sample_rate": 24000+ },+ {+ "id": "en_tandelbrook",+ "path": "en_tandelbrook.wav",+ "language": "en",+ "text": "Please repeat my invented word tandelbrook exactly once.",+ "nonce": "tandelbrook",+ "duration_ms": 4172,+ "sample_rate": 24000+ },+ {+ "id": "en_bicycle",+ "path": "en_bicycle.wav",+ "language": "en",+ "text": "How many wheels does my imaginary quintuple bicycle have?",+ "nonce": "quintuple bicycle",+ "duration_ms": 3924,+ "sample_rate": 24000+ },+ {+ "id": "en_glimmerpond",+ "path": "en_glimmerpond.wav",+ "language": "en",+ "text": "Name one word that rhymes with my invented word glimmerpond.",+ "nonce": "glimmerpond",+ "duration_ms": 4140,+ "sample_rate": 24000+ },+ {+ "id": "en_zebrastorm",+ "path": "en_zebrastorm.wav",+ "language": "en",+ "text": "In one sentence, what would a zebrastorm picnic be?",+ "nonce": "zebrastorm",+ "duration_ms": 3848,+ "sample_rate": 24000+ },+ {+ "id": "de_giraffe",+ "path": "de_giraffe.wav",+ "language": "de",+ "text": "Welche Farbe hat die violette Giraffe aus meinem Beispiel? Antworte in einem kurzen Satz.",+ "nonce": "violette Giraffe",+ "duration_ms": 5260,+ "sample_rate": 24000+ },+ {+ "id": "de_tandelbrook",+ "path": "de_tandelbrook.wav",+ "language": "de",+ "text": "Bitte wiederhole mein erfundenes Wort Tandelbrook genau einmal.",+ "nonce": "Tandelbrook",+ "duration_ms": 4170,+ "sample_rate": 24000+ },+ {+ "id": "de_fahrrad",+ "path": "de_fahrrad.wav",+ "language": "de",+ "text": "Wie viele Räder hat mein erfundenes Fünffach-Fahrrad?",+ "nonce": "Fünffach-Fahrrad",+ "duration_ms": 3225,+ "sample_rate": 24000+ },+ {+ "id": "room_noise",+ "path": "room_noise.wav",+ "language": "",+ "text": "",+ "nonce": "",+ "duration_ms": 8000,+ "sample_rate": 24000+ }+]diff --git a/tests/fixtures/audio/realtime/room_noise.wav b/tests/fixtures/audio/realtime/room_noise.wavnew file mode 100644index 0000000000..38cd72dcf5Binary files /dev/null and b/tests/fixtures/audio/realtime/room_noise.wav differdiff --git a/tests/integration/realtime/scenarios/barge_in_followup.json b/tests/integration/realtime/scenarios/barge_in_followup.jsonnew file mode 100644index 0000000000..aa8c98a0f2--- /dev/null+++ b/tests/integration/realtime/scenarios/barge_in_followup.json@@ -0,0 +1,20 @@+{+ "name": "barge_in_followup",+ "description": "Reviewer checklist item 1: interrupt a running answer, ask a follow-up, and the follow-up must be answered (the speech-edge/entitlement regression class).",+ "steps": [+ {"speak": "en_zebrastorm"},+ {"barge_in": {"after_reply_ms": 700, "then_speak": "en_giraffe"}},+ {"wait_reply": {"timeout_s": 20}},+ {"speak": "en_glimmerpond"},+ {"wait_reply": {"timeout_s": 20}},+ {"end": {}}+ ],+ "asserts": [+ "turns>=2",+ "no_ungrounded",+ "no_roleplay",+ "no_rebuilds",+ "mic_wall_clock",+ "clean_close"+ ]+}diff --git a/tests/integration/realtime/scenarios/delegation.json b/tests/integration/realtime/scenarios/delegation.jsonnew file mode 100644index 0000000000..0eb2047f8b--- /dev/null+++ b/tests/integration/realtime/scenarios/delegation.json@@ -0,0 +1,18 @@+{+ "name": "delegation",+ "description": "Opt-in (needs --with-delegate): one action-shaped request must dispatch a delegation and speak its result without killing the call. Reviewer checklist item 2.",+ "steps": [+ {"speak": "en_giraffe"},+ {"wait_reply": {"timeout_s": 20}},+ {"speak": "en_tandelbrook"},+ {"wait_reply": {"timeout_s": 30}},+ {"end": {}}+ ],+ "asserts": [+ "turns>=2",+ "no_ungrounded",+ "no_roleplay",+ "no_rebuilds",+ "clean_close"+ ]+}diff --git a/tests/integration/realtime/scenarios/silence_no_selftalk.json b/tests/integration/realtime/scenarios/silence_no_selftalk.jsonnew file mode 100644index 0000000000..63256c7c88--- /dev/null+++ b/tests/integration/realtime/scenarios/silence_no_selftalk.json@@ -0,0 +1,14 @@+{+ "name": "silence_no_selftalk",+ "description": "Ten seconds of room tone and nothing else: beyond at most one bounded greeting, the assistant must stay silent (the 17:03 two-person demo dialogue class).",+ "steps": [+ {"silence_s": 10},+ {"end": {}}+ ],+ "asserts": [+ "no_selftalk",+ "no_rebuilds",+ "mic_wall_clock",+ "clean_close"+ ]+}diff --git a/tests/integration/realtime/scenarios/split_reply_pause.json b/tests/integration/realtime/scenarios/split_reply_pause.jsonnew file mode 100644index 0000000000..bf1b4c5da5--- /dev/null+++ b/tests/integration/realtime/scenarios/split_reply_pause.json@@ -0,0 +1,19 @@+{+ "name": "split_reply_pause",+ "description": "A prompt that invites a longer, pause-bearing answer: generation pauses beyond the 1.2s backstop must not produce audible seams or splices (Fix E's live guard).",+ "steps": [+ {"speak": "en_zebrastorm"},+ {"wait_reply": {"timeout_s": 25}},+ {"speak": "de_fahrrad"},+ {"wait_reply": {"timeout_s": 25}},+ {"end": {}}+ ],+ "asserts": [+ "turns>=2",+ "no_ungrounded",+ "no_roleplay",+ "audio_continuity",+ "no_rebuilds",+ "clean_close"+ ]+}diff --git a/tests/integration/realtime/scenarios/three_turns_de.json b/tests/integration/realtime/scenarios/three_turns_de.jsonnew file mode 100644index 0000000000..135ddfbec6--- /dev/null+++ b/tests/integration/realtime/scenarios/three_turns_de.json@@ -0,0 +1,23 @@+{+ "name": "three_turns_de",+ "description": "The headline multi-turn guard: two German turns, then one English turn, each answered. Pins the 50% one-turn death rate at zero.",+ "steps": [+ {"speak": "de_giraffe"},+ {"wait_reply": {"timeout_s": 20}},+ {"speak": "de_tandelbrook"},+ {"wait_reply": {"timeout_s": 20}},+ {"speak": "en_bicycle"},+ {"wait_reply": {"timeout_s": 20}},+ {"end": {}}+ ],+ "asserts": [+ "turns>=3",+ "no_ungrounded",+ "no_roleplay",+ "audio_continuity",+ "no_rebuilds",+ "mic_wall_clock",+ "spawn_budget",+ "clean_close"+ ]+}diff --git a/tests/integration/realtime/test_codex_live_call.py b/tests/integration/realtime/test_codex_live_call.pynew file mode 100644index 0000000000..4ec65f2540--- /dev/null+++ b/tests/integration/realtime/test_codex_live_call.py@@ -0,0 +1,46 @@+"""Env-gated REAL ChatGPT-Live call through the production codex path.++Never runs in CI and never by accident: it needs the explicit+``JARVIS_CODEX_LIVE=1`` opt-in (each run bills the maintainer's ChatGPT+subscription realtime usage), a logged-in Codex voice profile, aiortc, and+the desktop app STOPPED (the profile lock refuses the probe otherwise —+that refusal is itself fail-closed behavior, reported as a skip here).+"""++from __future__ import annotations++import os+from pathlib import Path++import pytest++pytestmark = [pytest.mark.integration, pytest.mark.slow, pytest.mark.e2e]++if os.environ.get("JARVIS_CODEX_LIVE") != "1": # noqa: SIM108 - collection-time gate+ pytest.skip(+ "live codex probe needs the explicit JARVIS_CODEX_LIVE=1 opt-in "+ "(it bills the ChatGPT subscription)",+ allow_module_level=True,+ )++from jarvis.diagnostics.realtime_probe import ( # noqa: E402+ ProbeEnvironmentError,+ load_scenario,+ run_scenario,+)+++async def test_three_turns_de_live(tmp_path: Path) -> None:+ try:+ summary = await run_scenario(+ load_scenario("three_turns_de"),+ out_dir=tmp_path / "three_turns_de",+ )+ except ProbeEnvironmentError as exc:+ pytest.skip(str(exc))+ failed = {+ name: entry+ for name, entry in summary["asserts"].items()+ if entry["status"] == "fail"+ }+ assert not failed, f"live scenario failed: {failed}"diff --git a/tests/unit/diagnostics/test_realtime_probe_eval.py b/tests/unit/diagnostics/test_realtime_probe_eval.pynew file mode 100644index 0000000000..dc79de363b--- /dev/null+++ b/tests/unit/diagnostics/test_realtime_probe_eval.py@@ -0,0 +1,192 @@+"""The probe's scenario judge, exercised without any live call.++``evaluate_scenario`` is pure over the capture rows + postmortem, so every+assert's pass/fail boundary is pinned here — the live integration test then+only has to trust one judgment path, not two.+"""++from __future__ import annotations++from typing import Any++from jarvis.diagnostics.realtime_probe import (+ CONTINUITY_GAP_S,+ evaluate_scenario,+)++MANIFEST = [+ {+ "id": "en_giraffe",+ "text": "What color is the violet giraffe from my example? Answer in one short sentence.",+ "nonce": "violet giraffe",+ "language": "en",+ },+]+++def _row(mono: float, src: str, kind: str, data: dict[str, Any]) -> dict[str, Any]:+ return {"ts": mono, "mono": mono, "src": src, "kind": kind, "data": data}+++def _transcript(mono: float, role: str, text: str, *, final: bool = True) -> dict[str, Any]:+ return _row(+ mono,+ "surface",+ "json",+ {"type": "transcript", "role": role, "text": text, "is_final": final},+ )+++def _happy_rows() -> list[dict[str, Any]]:+ rows = [+ _row(0.0, "probe", "scenario", {"name": "t"}),+ _row(1.0, "probe", "ready", {"type": "audio_ready"}),+ _row(2.0, "probe", "speak", {"id": "en_giraffe"}),+ _transcript(4.0, "user", "what color is the violet giraffe"),+ ]+ # A contiguous reply: chunks 100 ms apart, each carrying 100 ms of audio.+ mono = 5.0+ for _ in range(10):+ rows.append(_row(mono, "surface", "binary", {"bytes": 4800}))+ mono += 0.1+ rows.append(_transcript(mono, "assistant", "It is violet."))+ rows.append(_row(mono + 0.2, "surface", "json", {"type": "turn_complete"}))+ return rows+++def _pm(**overrides: Any) -> dict[str, Any]:+ base: dict[str, Any] = {+ "turns_completed": 1,+ "rebuilds": 0,+ "stun_retries": 0,+ "recv_dropped_frames": 0,+ "sender_pacing_resyncs": 0,+ "sender_shed_frames": 0,+ "ready_ms": 2500,+ "first_audio_ms": 4200,+ "close_clean": True,+ }+ base.update(overrides)+ return base+++def _judge(+ rows: list[dict[str, Any]],+ pm: dict[str, Any],+ asserts: list[str],+ *,+ budgets: dict[str, Any] | None = None,+ end_duration_s: float = 1.0,+) -> dict[str, dict[str, str]]:+ return evaluate_scenario(+ rows,+ pm,+ {"name": "t", "asserts": asserts},+ MANIFEST,+ budgets=budgets or {},+ end_duration_s=end_duration_s,+ )+++def test_happy_path_passes_everything() -> None:+ verdicts = _judge(+ _happy_rows(),+ _pm(),+ [+ "turns>=1",+ "no_ungrounded",+ "no_roleplay",+ "audio_continuity",+ "no_rebuilds",+ "mic_wall_clock",+ "spawn_budget",+ "clean_close",+ ],+ )+ assert all(v["status"] == "pass" for v in verdicts.values()), verdicts+++def test_missing_turn_fails_the_count() -> None:+ rows = _happy_rows()+ verdicts = _judge(rows, _pm(), ["turns>=2"])+ assert verdicts["turns>=2"]["status"] == "fail"+++def test_ungrounded_boundary_is_allowed_once_as_greeting_then_fails() -> None:+ rows = _happy_rows()+ # A greeting boundary 3 s after ready (inside the window) - allowed.+ rows.insert(3, _row(3.0, "surface", "json", {"type": "turn_complete"}))+ assert _judge(rows, _pm(), ["no_ungrounded"])["no_ungrounded"]["status"] == "pass"+ # A second ungrounded boundary long after the window - self-talk.+ rows.append(_row(30.0, "surface", "json", {"type": "turn_complete"}))+ assert _judge(rows, _pm(), ["no_ungrounded"])["no_ungrounded"]["status"] == "fail"+++def test_roleplay_detects_the_full_question_but_not_the_topic() -> None:+ rows = _happy_rows()+ # Answering with the nonce topic is legitimate.+ assert _judge(rows, _pm(), ["no_roleplay"])["no_roleplay"]["status"] == "pass"+ # Speaking the user's full question verbatim is the both-sides signature.+ rows.append(+ _transcript(+ 9.0,+ "assistant",+ "Hi! What color is the violet giraffe from my example? "+ "Answer in one short sentence. Well, violet!",+ )+ )+ assert _judge(rows, _pm(), ["no_roleplay"])["no_roleplay"]["status"] == "fail"+++def test_selftalk_on_a_silent_microphone_fails() -> None:+ rows = [+ _row(1.0, "probe", "ready", {"type": "audio_ready"}),+ _transcript(20.0, "assistant", "Hey. Hi, what's up?", final=False),+ ]+ assert _judge(rows, _pm(), ["no_selftalk"])["no_selftalk"]["status"] == "fail"+ early = [+ _row(1.0, "probe", "ready", {"type": "audio_ready"}),+ _transcript(4.0, "assistant", "Hey!", final=False),+ ]+ assert _judge(early, _pm(), ["no_selftalk"])["no_selftalk"]["status"] == "pass"+++def test_audio_hole_beyond_the_gap_budget_fails_continuity() -> None:+ rows = _happy_rows()+ verdict = _judge(rows, _pm(), ["audio_continuity"])["audio_continuity"]+ assert verdict["status"] == "pass"+ # Inject a hole: the next chunk arrives seconds late inside the same turn.+ late = _happy_rows()+ hole_at = late[-3]["mono"] + CONTINUITY_GAP_S + 1.0+ late.insert(-2, _row(hole_at, "surface", "binary", {"bytes": 4800}))+ assert _judge(late, _pm(), ["audio_continuity"])["audio_continuity"]["status"] == "fail"+++def test_postmortem_counters_gate_their_asserts() -> None:+ rows = _happy_rows()+ assert _judge(rows, _pm(rebuilds=1), ["no_rebuilds"])["no_rebuilds"]["status"] == "fail"+ assert (+ _judge(rows, _pm(sender_shed_frames=3), ["mic_wall_clock"])["mic_wall_clock"]["status"]+ == "fail"+ )+ assert (+ _judge(rows, _pm(close_clean=False), ["clean_close"])["clean_close"]["status"]+ == "fail"+ )+ assert (+ _judge(rows, _pm(), ["clean_close"], end_duration_s=30.0)["clean_close"]["status"]+ == "fail"+ )+++def test_spawn_budget_warns_until_enforced() -> None:+ rows = _happy_rows()+ slow = _pm(ready_ms=9000)+ assert _judge(rows, slow, ["spawn_budget"])["spawn_budget"]["status"] == "warn"+ enforced = _judge(rows, slow, ["spawn_budget"], budgets={"enforce": True})+ assert enforced["spawn_budget"]["status"] == "fail"+++def test_unknown_assert_is_a_scenario_bug() -> None:+ verdicts = _judge(_happy_rows(), _pm(), ["definitely_not_a_check"])+ assert verdicts["definitely_not_a_check"]["status"] == "fail"diff --git a/tests/unit/realtime/test_probe_fixture_budget.py b/tests/unit/realtime/test_probe_fixture_budget.pynew file mode 100644index 0000000000..3f56e3f8be--- /dev/null+++ b/tests/unit/realtime/test_probe_fixture_budget.py@@ -0,0 +1,71 @@+"""Committed speech fixtures for the codex live probe: shape and size pins.++The WAVs are committed so running the probe needs no TTS key; these pins keep+the directory from quietly growing into a repo-weight problem and keep every+file in the exact shape the adapter consumes (24 kHz mono s16).+"""++from __future__ import annotations++import json+import wave+from pathlib import Path++FIXTURE_DIR = (+ Path(__file__).resolve().parents[3] / "tests" / "fixtures" / "audio" / "realtime"+)+MAX_FILE_BYTES = 500_000+MAX_DIR_BYTES = 4_000_000+EXPECTED_RATE = 24_000+++def _manifest() -> list[dict]:+ return json.loads((FIXTURE_DIR / "manifest.json").read_text(encoding="utf-8"))+++def test_manifest_and_wavs_agree() -> None:+ entries = _manifest()+ ids = [e["id"] for e in entries]+ assert len(ids) == len(set(ids)), "duplicate fixture ids"+ assert "room_noise" in ids, "the probe's room tone is part of the contract"+ for entry in entries:+ path = FIXTURE_DIR / entry["path"]+ assert path.exists(), f"missing fixture file {entry['path']}"+ with wave.open(str(path), "rb") as handle:+ assert handle.getframerate() == EXPECTED_RATE, entry["id"]+ assert handle.getnchannels() == 1, entry["id"]+ assert handle.getsampwidth() == 2, entry["id"]+ duration_ms = int(+ handle.getnframes() / handle.getframerate() * 1000+ )+ assert abs(duration_ms - int(entry["duration_ms"])) <= 5, entry["id"]+++def test_fixture_sizes_stay_bounded() -> None:+ total = 0+ for path in FIXTURE_DIR.glob("*.wav"):+ size = path.stat().st_size+ total += size+ assert size <= MAX_FILE_BYTES, f"{path.name} is {size} bytes"+ assert total <= MAX_DIR_BYTES, f"fixture dir grew to {total} bytes"+++def test_speech_fixtures_carry_their_nonce() -> None:+ """The role-play check matches the literal question; every speech fixture+ must therefore name the nonce that makes it unmistakable."""+ for entry in _manifest():+ if entry["id"] == "room_noise":+ continue+ assert entry["nonce"], entry["id"]+ assert entry["nonce"].lower().split()[0] in entry["text"].lower(), entry["id"]+++def test_room_noise_is_quiet_but_never_digital_zero() -> None:+ with wave.open(str(FIXTURE_DIR / "room_noise.wav"), "rb") as handle:+ frames = handle.readframes(handle.getnframes())+ samples = [+ int.from_bytes(frames[i : i + 2], "little", signed=True)+ for i in range(0, min(len(frames), 96_000), 2)+ ]+ peak = max(abs(s) for s in samples)+ assert 0 < peak <= 120, f"room tone peak {peak} is not ~-55 dBFS"