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(realtime): give every session a postmortem, and the forensics to read it
rubenluetke10-beepf9d1c3e30bc2
diff --git a/jarvis/codex_app_server.py b/jarvis/codex_app_server.pyindex b325df0577..42d038b415 100644--- a/jarvis/codex_app_server.py+++ b/jarvis/codex_app_server.py@@ -2152,6 +2152,20 @@ class CodexAppServerClient:# give-up path would turn executor saturation into a permanent# claim leak, because the worker would still claim later with# nobody left to release.+ # RT-SPAWN sub-spans: the cold bundle is the biggest single chunk+ # of a session open, and without per-step numbers "the handshake+ # is slow" is unattributable. Local stamps only; one summary INFO+ # on success.+ spans: dict[str, int] = {}+ bundle_started = time.monotonic()+ last_stamp = bundle_started++ def _stamp(name: str) -> None:+ nonlocal last_stamp+ now = time.monotonic()+ spans[name] = int((now - last_stamp) * 1000.0)+ last_stamp = now+decision_lock = threading.Lock()abandoned = threading.Event()published_epoch: list[int] = []@@ -2200,6 +2214,8 @@ class CodexAppServerClient:_release_subscription_transport(self, epoch)raise+ _stamp("reserve")+async def _release_after_failure() -> None:epoch = self._profile_transport_epochself._profile_transport_epoch = None@@ -2215,6 +2231,7 @@ class CodexAppServerClient:except BaseException:await _release_after_failure()raise+ _stamp("capability_probe")if not capability.available:await _release_after_failure()raise CodexSubscriptionUnavailable(capability.reason)@@ -2238,12 +2255,17 @@ class CodexAppServerClient:self._workspace,)await self._ensure_sink_started()+ _stamp("home_workspace_sink")await asyncio.to_thread(_verify_spawn_binary, capability.binary_path)+ _stamp("binary_verify")await self._spawn(capability.binary_path)+ _stamp("spawn")await self._initialize_live_process()+ _stamp("initialize")await self._verify_live_chatgpt_account()+ _stamp("account_verify")self._audit_config_requirements(await self._read_config_requirements())@@ -2255,7 +2277,13 @@ class CodexAppServerClient:require_marker=True,trusted_binary_path=self._trusted_binary_path,)+ _stamp("config_audit")self._ready = True+ log.info(+ "RT-SPAWN span=ensure_started ms=%d detail=%s",+ int((time.monotonic() - bundle_started) * 1000.0),+ ",".join(f"{name}={ms}" for name, ms in spans.items()),+ )# The audit that just passed is byte-for-byte the one# ``thread_start`` performs. Record which process it covers so# the very next thread start rides it instead of repeatingdiff --git a/jarvis/core/events.py b/jarvis/core/events.pyindex 5372fb972a..25e283307f 100644--- a/jarvis/core/events.py+++ b/jarvis/core/events.py@@ -1558,6 +1558,68 @@ class VoiceSessionEnded(Event):duration_s: float = 0.0+@dataclass(frozen=True, slots=True)+class RealtimeSessionPostmortem(Event):+ """Health counters of one finished realtime session, for forensics.++ Published by ``RealtimeVoiceSession.end()`` on every teardown and picked+ up by the wildcard flight recorder — the one place a live call's transport+ health survives the call. Counters only, never transcript text: telemetry+ must stay content-free. This event never crosses to the UI, so the+ five-layer enum-parity rule does not apply to its fields.++ All counters are zero in a healthy call except ``turns_completed`` (and,+ until the real v3 terminal item is confirmed live,+ ``quiescence_boundary_turns`` — every ChatGPT-Live turn currently ends on+ the local silence backstop).+ """++ session_id: str = ""+ provider: str = ""+ surface: str = ""+ hangup_reason: str = ""+ duration_ms: int = 0+ #: audio_start → provider handshake complete (RealtimeSessionReady).+ ready_ms: int = 0+ #: audio_start → first provider audio frame emitted to the surface.+ first_audio_ms: int = 0+ turns_completed: int = 0+ #: In-place transport rebuilds this session survived (BUG-071 machinery).+ rebuilds: int = 0+ #: Full open() retries over a STUN server after host candidates failed.+ stun_retries: int = 0+ #: Server user captions dropped for lacking local microphone energy.+ ungrounded_captions_dropped: int = 0+ #: Automatic provider responses refused by the grounding gate.+ ungrounded_responses_refused: int = 0+ #: Responses authorized by a trusted injection (announcement/readback).+ trusted_permit_responses: int = 0+ #: Turns closed by the local quiescence backstop (no protocol boundary).+ quiescence_boundary_turns: int = 0+ #: Turns closed by a confirmed terminal response item.+ terminal_item_turns: int = 0+ #: Back-to-back responses that spliced into one playback stream (<1.5 s).+ response_splices: int = 0+ #: Self-dialogue verdicts that forced a transport replacement (BUG-124).+ self_dialogue_rebuilds: int = 0+ #: Half-duplex mutes released by the emergency timer, not a turn boundary.+ mute_emergency_releases: int = 0+ #: Microphone sender wall-clock resyncs (mic audio lost to a stall).+ sender_pacing_resyncs: int = 0+ #: Stale outgoing microphone frames shed by the elastic backlog cap.+ sender_shed_frames: int = 0+ #: Silent frames skipped while the sender drained its backlog.+ sender_catchup_dropped_frames: int = 0+ #: Provider audio frames dropped on a full receive queue.+ recv_dropped_frames: int = 0+ #: Worst event-loop scheduling stall observed during the session.+ max_loop_stall_ms: int = 0+ #: Output-language changes after the first resolution.+ language_flips: int = 0+ #: False when teardown abandoned a provider socket or the stream failed.+ close_clean: bool = True++@dataclass(frozen=True, slots=True)class ToolCallStarted(Event):parent_trace_id: UUID | None = Nonediff --git a/jarvis/diagnostics/realtime_forensics.py b/jarvis/diagnostics/realtime_forensics.pynew file mode 100644index 0000000000..ff52d95159--- /dev/null+++ b/jarvis/diagnostics/realtime_forensics.py@@ -0,0 +1,236 @@+"""Verdict functions over realtime session postmortem counters.++Shared by the two consumers so their verdicts can never drift apart:+``scripts/diag_voice_sessions.py`` (flight-recorder audits after live rounds)+and the codex live-call probe. Pure functions over plain dicts - no bus, no+I/O, no heavy imports; nothing on the boot path imports this module+(AP-26/AP-9).++The input is the payload of one ``RealtimeSessionPostmortem`` event+(``jarvis/core/events.py``): session-lifetime counters, all zero in a healthy+call except ``turns_completed`` - and, until the real ChatGPT-Live terminal+item is confirmed, ``quiescence_boundary_turns``.+"""++from __future__ import annotations++from collections.abc import Iterable, Mapping+from dataclasses import dataclass+from typing import Any++#: Spawn budgets. The forensics report treats an overrun as a WARN; the live+#: probe starts at WARN too and flips to FAIL once the latency phase lands+#: (that flip lives in the probe, deliberately not here).+SPAWN_READY_BUDGET_MS = 4_000+SPAWN_FIRST_AUDIO_BUDGET_MS = 6_000++#: Mirrors the adapter's refusal-storm verdict (``_REFUSALS_BEFORE_REBUILD``):+#: at this many refused automatic responses the far end was talking to itself.+_REFUSAL_STORM = 5+++@dataclass(frozen=True, slots=True)+class RealtimeFinding:+ severity: str # "high" | "warn" | "info"+ kind: str+ detail: str+++def _count(pm: Mapping[str, Any], key: str) -> int:+ try:+ return int(pm.get(key, 0) or 0)+ except (TypeError, ValueError):+ return 0+++def evaluate_postmortem(pm: Mapping[str, Any]) -> list[RealtimeFinding]:+ """Map one postmortem payload onto the known realtime failure classes."""+ findings: list[RealtimeFinding] = []+ add = findings.append+ turns = _count(pm, "turns_completed")++ splices = _count(pm, "response_splices")+ if splices:+ add(+ RealtimeFinding(+ "high",+ "splice-seam",+ f"{splices} back-to-back response(s) spliced into one "+ "playback stream - audible garble",+ )+ )++ quiescence = _count(pm, "quiescence_boundary_turns")+ if quiescence:+ add(+ RealtimeFinding(+ "warn" if quiescence >= 2 else "info",+ "turn-without-boundary",+ f"{quiescence} of {turns} turn(s) ended on the local silence "+ "backstop, not a protocol boundary",+ )+ )++ captions = _count(pm, "ungrounded_captions_dropped")+ if captions >= 2:+ add(+ RealtimeFinding(+ "high",+ "ungrounded-caption-storm",+ f"{captions} server user captions with no microphone energy - "+ "the far end invented user turns",+ )+ )+ elif captions:+ add(+ RealtimeFinding(+ "warn",+ "ungrounded-caption",+ "1 server user caption with no microphone energy",+ )+ )++ refused = _count(pm, "ungrounded_responses_refused")+ if refused >= _REFUSAL_STORM:+ add(+ RealtimeFinding(+ "high",+ "refusal-storm",+ f"{refused} automatic responses refused with no grounded "+ "speech between them",+ )+ )+ elif refused >= 3:+ add(+ RealtimeFinding(+ "warn",+ "refusal-run",+ f"{refused} automatic responses refused",+ )+ )++ if _count(pm, "self_dialogue_rebuilds"):+ add(+ RealtimeFinding(+ "high",+ "self-dialogue",+ "the self-dialogue detector forced a transport replacement",+ )+ )++ mutes = _count(pm, "mute_emergency_releases")+ if mutes:+ add(+ RealtimeFinding(+ "warn",+ "mute-emergency-release",+ f"{mutes} half-duplex mute(s) released only by the emergency "+ "timer - a turn ended without any boundary",+ )+ )++ stall = _count(pm, "max_loop_stall_ms")+ if stall > 1_000:+ add(+ RealtimeFinding(+ "high",+ "event-loop-stall",+ f"event loop stalled {stall} ms mid-call - a blocking call "+ "ran on the loop",+ )+ )++ resyncs = _count(pm, "sender_pacing_resyncs")+ shed = _count(pm, "sender_shed_frames")+ if resyncs or shed:+ add(+ RealtimeFinding(+ "high",+ "sender-behind-wall-clock",+ f"microphone sender resynced {resyncs}x and shed {shed} stale "+ "frame(s) - user speech was lost",+ )+ )++ dropped = _count(pm, "recv_dropped_frames")+ if dropped:+ add(+ RealtimeFinding(+ "warn",+ "recv-overflow",+ f"{dropped} provider audio frame(s) dropped on a full "+ "receive queue",+ )+ )++ rebuilds = _count(pm, "rebuilds")+ stun = _count(pm, "stun_retries")+ if rebuilds >= 2 or stun >= 1:+ add(+ RealtimeFinding(+ "high",+ "rebuild-loop",+ f"{rebuilds} transport rebuild(s) and {stun} STUN retry(ies) "+ "in one session",+ )+ )+ elif rebuilds:+ add(RealtimeFinding("warn", "transport-rebuild", "1 transport rebuild"))++ flips = _count(pm, "language_flips")+ if flips >= 2:+ add(+ RealtimeFinding(+ "warn",+ "language-mismatch",+ f"the call's output language flipped {flips}x",+ )+ )++ ready_ms = _count(pm, "ready_ms")+ first_audio_ms = _count(pm, "first_audio_ms")+ over_ready = ready_ms > SPAWN_READY_BUDGET_MS+ over_first = bool(first_audio_ms) and first_audio_ms > SPAWN_FIRST_AUDIO_BUDGET_MS+ if over_ready or over_first:+ add(+ RealtimeFinding(+ "warn",+ "spawn-over-budget",+ f"ready {ready_ms} ms (budget {SPAWN_READY_BUDGET_MS}), "+ f"first audio {first_audio_ms} ms "+ f"(budget {SPAWN_FIRST_AUDIO_BUDGET_MS})",+ )+ )++ if not pm.get("close_clean", True):+ add(+ RealtimeFinding(+ "warn",+ "unclean-close",+ "teardown abandoned the provider socket or the stream failed",+ )+ )++ return findings+++def extract_postmortems(+ rows: Iterable[Mapping[str, Any]],+) -> list[dict[str, Any]]:+ """Pull postmortem payloads out of flight-recorder or probe JSONL rows.++ Accepts both shapes: the flight recorder's+ ``{"event": "RealtimeSessionPostmortem", "payload": {...}}`` and the live+ probe's ``{"src": "postmortem", "data": {...}}``.+ """+ payloads: list[dict[str, Any]] = []+ for row in rows:+ if row.get("event") == "RealtimeSessionPostmortem":+ payload = row.get("payload")+ if isinstance(payload, Mapping):+ payloads.append(dict(payload))+ elif row.get("src") == "postmortem":+ data = row.get("data")+ if isinstance(data, Mapping):+ payloads.append(dict(data))+ return payloadsdiff --git a/jarvis/plugins/realtime/codex_subscription.py b/jarvis/plugins/realtime/codex_subscription.pyindex fb027e93af..bb475c7e8e 100644--- a/jarvis/plugins/realtime/codex_subscription.py+++ b/jarvis/plugins/realtime/codex_subscription.py@@ -17,6 +17,8 @@ import importlibimport inspectimport jsonimport logging+import time+from collections import Counterfrom collections.abc import AsyncIteratorfrom contextlib import suppressfrom dataclasses import dataclass@@ -583,11 +585,34 @@ class _CodexSubscriptionRealtimeSession:# fail-open behaviour as a host that never had one — otherwise the gate# refuses and interrupts every remaining answer of the call.self._local_grounding_ok = True+ # Session-lifetime counters for the end-of-session postmortem event.+ # Bumped at the same sites that already log the condition; the session+ # layer reads them once at teardown via ``diagnostics()``. Counters,+ # never text — transcripts have no business in telemetry.+ self._diag: Counter[str] = Counter()def _local_grounding_active(self) -> bool:"""Whether locally grounded input is available AND still trustworthy."""return self._input_transcriber is not None and self._local_grounding_ok+ def diagnostics(self) -> dict[str, int]:+ """Postmortem counters, merged with the media endpoint's own.++ Read once by ``RealtimeVoiceSession.end()``; every key is a plain int+ so the frozen bus event can carry it. Best-effort by contract — a+ broken endpoint must never break teardown.+ """+ merged: dict[str, int] = {k: int(v) for k, v in self._diag.items()}+ endpoint_diag = getattr(self._audio_endpoint, "diagnostics", None)+ if callable(endpoint_diag):+ try:+ merged.update(+ {k: int(v) for k, v in endpoint_diag().items()}+ )+ except Exception: # noqa: BLE001 — diagnostics never break teardown+ log.debug("audio endpoint diagnostics unavailable", exc_info=True)+ return merged+async def _append_trusted(self, write: Any, *, arms_response: bool) -> Any:"""Run one provider write through the single trusted-write path.@@ -928,6 +953,7 @@ class _CodexSubscriptionRealtimeSession:# its one plausible client-side mechanism; this line# timestamps the seam so the next incident is attributable# to the seam or to the server's own audio.+ self._diag["response_splices"] += 1log.info("Codex subscription realtime opened a new response ""%d ms after the previous response's audio "@@ -947,6 +973,7 @@ class _CodexSubscriptionRealtimeSession:response_allowed = Trueelif _trusted_permit_available():self._trusted_output_permits -= 1+ self._diag["trusted_permit_responses"] += 1response_allowed = Trueelif _entitled_turn_continues():active_response_generation = entitled_generation@@ -969,6 +996,7 @@ class _CodexSubscriptionRealtimeSession:refusal_run_started_at = nowrefusal_storm_noted = Falserefusal_run += 1+ self._diag["ungrounded_responses_refused"] += 1if post_interrupt:# Expected fallout of OUR own cut: the far end streams the# remainder of the retired answer for a while. Dropping it@@ -1010,6 +1038,7 @@ class _CodexSubscriptionRealtimeSession:and not self_dialogue_detected):self_dialogue_detected = True+ self._diag["self_dialogue_rebuilds"] += 1log.warning("Codex subscription refused %d automatic responses ""within %.0f s with no locally grounded speech in "@@ -1558,6 +1587,7 @@ class _CodexSubscriptionRealtimeSession:if recovered is not None:yield recoveredcompletion_emitted = True+ self._diag["quiescence_boundary_turns"] += 1yield _ProviderEvent(type="turn_complete")_reset_assistant_capture()_finish_response()@@ -1800,6 +1830,7 @@ class _CodexSubscriptionRealtimeSession:)yield _ProviderEvent(type="turn_complete")return+ self._diag["ungrounded_captions_dropped"] += 1log.info("Ignoring a server user transcript with no ""microphone energy and no fresh local utterance "@@ -1994,6 +2025,7 @@ class _CodexSubscriptionRealtimeSession:if recovered is not None:yield recoveredcompletion_emitted = True+ self._diag["terminal_item_turns"] += 1log.info("Codex subscription realtime turn ended on item %r (protocol %s)",item_type,@@ -2496,9 +2528,15 @@ class CodexSubscriptionRealtimeProvider:last_error: BaseException | None = Nonefor index, ice_factory in enumerate(attempts):try:- return await self._open_session_once(+ session = await self._open_session_once(cfg, None if ice_factory is None else ice_factory())+ if index > 0:+ # Postmortem marker: this call paid the full re-open (a+ # second thread_start bundle included) to reach STUN.+ session._diag["stun_retries"] = index+ log.info("RT-SPAWN stun_retry=%d", index)+ return sessionexcept transport_module.WebRtcMediaPathUnavailable as exc:last_error = excif index + 1 < len(attempts):@@ -2558,6 +2596,19 @@ class CodexSubscriptionRealtimeProvider:# Jarvis owns the media path in-process. The UI could only ever broker# a signalling-shaped offer (no microphone), which ChatGPT-Live cannot# use: on v3 the audio IS the WebRTC track.+ # RT-SPAWN spans: every step of this open is sequential today, so the+ # per-step numbers are what makes the latency budget (and any future+ # overlap) measurable instead of anecdotal.+ last_stamp = time.monotonic()++ def _stamp(name: str) -> None:+ nonlocal last_stamp+ now = time.monotonic()+ log.info(+ "RT-SPAWN span=%s ms=%d", name, int((now - last_stamp) * 1000.0)+ )+ last_stamp = now+audio_endpoint: Any = Noneif self._audio_endpoint_factory is not None:audio_endpoint = self._audio_endpoint_factory(ice_servers)@@ -2565,6 +2616,7 @@ class CodexSubscriptionRealtimeProvider:transport_module = importlib.import_module("jarvis.realtime.webrtc_transport")audio_endpoint = transport_module.RealtimeWebRtcAudioEndpoint(ice_servers)offer_sdp = await audio_endpoint.create_offer()+ _stamp("offer_create")client = self._clientif client is None:@@ -2585,6 +2637,7 @@ class CodexSubscriptionRealtimeProvider:thread_id = _thread_id_from_result(thread_result)if not thread_id:raise RuntimeError("Codex app-server did not return a thread id")+ _stamp("thread_start")subscription = client.subscribe(thread_id)configured_model = str(getattr(cfg, "model", "") or "").strip()@@ -2622,10 +2675,12 @@ class CodexSubscriptionRealtimeProvider:answer_sdp = str(getattr(start, "answer_sdp", "") or "").strip()if not answer_sdp:raise RuntimeError("Codex app-server did not return a WebRTC answer SDP")+ _stamp("realtime_start_sdp")await audio_endpoint.apply_answer(answer_sdp)# Fail here rather than mid-call: without a live media path the# session would look connected and stay mute in both directions.await audio_endpoint.wait_connected()+ _stamp("media_connect")session = _CodexSubscriptionRealtimeSession(client=client,subscription=subscription,@@ -2643,10 +2698,13 @@ class CodexSubscriptionRealtimeProvider:warm = getattr(session._input_transcriber, "warm", None)if callable(warm):await warm()+ _stamp("transcriber_warm")# Identity FIRST: the model must know who it is and what this# project is before the user's first word arrives.await session._deliver_context(getattr(cfg, "instructions", ""))+ _stamp("context_deliver")await session._deliver_history(getattr(cfg, "history", ()))+ _stamp("history_deliver")# Then the language — but ONLY when the user explicitly pinned one# (brain.reply_language). At open nobody has spoken yet, so the# resolved value is just DEFAULT_LOCALE; hard-pinning it naileddiff --git a/jarvis/realtime/session.py b/jarvis/realtime/session.pyindex 4928c7b43e..c6fefc35a1 100644--- a/jarvis/realtime/session.py+++ b/jarvis/realtime/session.py@@ -15,7 +15,7 @@ import loggingimport randomimport reimport time-from collections import deque+from collections import Counter, dequefrom dataclasses import dataclass, fieldfrom datetime import datetimefrom typing import Any@@ -287,6 +287,9 @@ class _LoopLagProbe:self._samples: deque[tuple[float, float]] = deque()self._task: asyncio.Task[None] | None = Noneself._last_warn_at = float("-inf")+ # Session-lifetime worst case, for the end-of-session postmortem —+ # the windowed samples above forget a stall after _WINDOW_S.+ self.max_lag_ever_ms = 0.0def start(self) -> None:if self._task is None or self._task.done():@@ -311,6 +314,8 @@ class _LoopLagProbe:def _note_sample(self, now: float, lag_ms: float) -> None:"""Record one lag sample; warn on a stall-grade gap (rate-limited)."""self._samples.append((now, lag_ms))+ if lag_ms > self.max_lag_ever_ms:+ self.max_lag_ever_ms = lag_mscutoff = now - self._WINDOW_Swhile self._samples and self._samples[0][0] < cutoff:self._samples.popleft()@@ -1242,6 +1247,20 @@ class RealtimeVoiceSession:# Frames discarded because a transport rebuild is pending. Reported so a# stuck marker cannot silently swallow the microphone (AP-30).self._rebuild_drop_reported = 0.0+ # ---- Postmortem bookkeeping (RealtimeSessionPostmortem) ----------+ # Stamps and counters read exactly once at end(); they never gate+ # behavior. The adapter accumulator exists because a transport rebuild+ # replaces the provider session OBJECT and its counters die with it —+ # rebuild-heavy calls are precisely the ones the postmortem is for.+ self._created_monotonic = time.monotonic()+ self._audio_start_monotonic = 0.0+ self._ready_monotonic = 0.0+ self._first_audio_emit_monotonic = 0.0+ self._rebuild_count = 0+ self._mute_emergency_releases = 0+ self._language_flips = 0+ self._close_timed_out = False+ self._adapter_diag_accum: Counter[str] = Counter()brain_config = getattr(self._config, "brain", None)reply_language = str(@@ -1751,6 +1770,8 @@ class RealtimeVoiceSession:async def handle_control(self, msg: dict[str, Any]) -> None:kind = str(msg.get("type", ""))if kind == "audio_start":+ if not self._audio_start_monotonic:+ self._audio_start_monotonic = time.monotonic()rate = int(msg.get("sample_rate", self.browser_sample_rate) or self.browser_sample_rate)if rate != self.browser_sample_rate:self.browser_sample_rate = rate@@ -1801,6 +1822,17 @@ class RealtimeVoiceSession:if answer_sdp:ready["webrtc_answer_sdp"] = answer_sdpawait self._send_json(ready)+ if not self._ready_monotonic:+ self._ready_monotonic = time.monotonic()+ log.info(+ "RT-SPAWN span=total_ready ms=%d session=%s provider=%s",+ int(+ (self._ready_monotonic - self._audio_start_monotonic)+ * 1000.0+ ),+ self.session_id,+ self.active_provider,+ )await self._announce_language()if self._surface == "browser" and not self._browser_session_started:await self._publish_browser_session_started()@@ -2146,6 +2178,7 @@ class RealtimeVoiceSession:silent_since = self._last_output_audio_at or self._half_duplex_muted_sincesilent_s = now - silent_sinceif silent_s >= _HALF_DUPLEX_MUTE_ALERT_S:+ self._mute_emergency_releases += 1log.warning("realtime[%s] releasing a half-duplex mute held %.1fs with no ""provider audio for %.1fs - the turn ended without a boundary, "@@ -2665,6 +2698,7 @@ class RealtimeVoiceSession:if transcript:new_language = self._resolve_lang(text=transcript)if new_language != self._language:+ self._language_flips += 1self._language = new_languageself._gate = ScrubHoldGate(new_language)if self._tool_bridge is not None:@@ -3847,6 +3881,9 @@ class RealtimeVoiceSession:f"{_TRANSPORT_REBUILD_WINDOW_S:.0f} s); giving up: {detail}")return False+ # Postmortem counter: monotone for the session, unlike the windowed+ # stamp list above, which forgets rebuilds after the rate window.+ self._rebuild_count += 1self._transport_rebuild_times.append(now)# Second-or-later rebuild inside the window: the previous rebuilt# transport died again almost immediately. The dominant cause is a@@ -3868,6 +3905,7 @@ class RealtimeVoiceSession:if self._transport_rebuild_pending is old_session:self._transport_rebuild_pending = Noneif old_session is not None:+ self._harvest_adapter_diagnostics(old_session)try:await old_session.close()except Exception: # noqa: BLE001, S110 — the transport is already dead@@ -6638,6 +6676,15 @@ class RealtimeVoiceSession:pcm = bytes(getattr(chunk, "pcm", b"") or b"")if not pcm:return+ if not self._first_audio_emit_monotonic:+ self._first_audio_emit_monotonic = time.monotonic()+ start = self._audio_start_monotonic or self._created_monotonic+ log.info(+ "RT-SPAWN span=first_audio ms=%d session=%s provider=%s",+ int((self._first_audio_emit_monotonic - start) * 1000.0),+ self.session_id,+ self.active_provider,+ )if self._output_samples_sent == 0 and self._bus is not None:from jarvis.core.events import AudioOutFirst@@ -6775,6 +6822,75 @@ class RealtimeVoiceSession:except Exception: # noqa: BLE001, S110pass+ def _harvest_adapter_diagnostics(self, session: Any) -> None:+ """Accumulate a provider session's postmortem counters.++ Called on every transport swap and once more at teardown: a rebuild+ replaces the provider session OBJECT, so without the harvest a+ rebuild-heavy call — exactly the kind the postmortem exists for —+ would report only its last transport's numbers.+ """+ diag = getattr(session, "diagnostics", None)+ if not callable(diag):+ return+ try:+ for key, value in diag().items():+ self._adapter_diag_accum[str(key)] += int(value)+ except Exception: # noqa: BLE001 — diagnostics never break teardown+ log.debug(+ "realtime[%s] adapter diagnostics harvest failed",+ self.session_id,+ exc_info=True,+ )++ def _build_postmortem(self, reason: str) -> Any:+ """Assemble the RealtimeSessionPostmortem event from all counters."""+ from jarvis.core.events import RealtimeSessionPostmortem++ now = time.monotonic()+ start = self._audio_start_monotonic or self._created_monotonic+ diag = self._adapter_diag_accum++ def _since_start_ms(stamp: float) -> int:+ if stamp <= 0.0 or stamp < start:+ return 0+ return int((stamp - start) * 1000.0)++ return RealtimeSessionPostmortem(+ source_layer=f"realtime.{self.active_provider}",+ session_id=self.session_id,+ provider=self.active_provider,+ surface=self._surface,+ hangup_reason=reason,+ duration_ms=int((now - start) * 1000.0),+ ready_ms=_since_start_ms(self._ready_monotonic),+ first_audio_ms=_since_start_ms(self._first_audio_emit_monotonic),+ turns_completed=self._turn_index,+ rebuilds=self._rebuild_count,+ stun_retries=diag.get("stun_retries", 0),+ ungrounded_captions_dropped=diag.get(+ "ungrounded_captions_dropped", 0+ ),+ ungrounded_responses_refused=diag.get(+ "ungrounded_responses_refused", 0+ ),+ trusted_permit_responses=diag.get("trusted_permit_responses", 0),+ quiescence_boundary_turns=diag.get("quiescence_boundary_turns", 0),+ terminal_item_turns=diag.get("terminal_item_turns", 0),+ response_splices=diag.get("response_splices", 0),+ self_dialogue_rebuilds=diag.get("self_dialogue_rebuilds", 0),+ mute_emergency_releases=self._mute_emergency_releases,+ sender_pacing_resyncs=diag.get("sender_pacing_resyncs", 0),+ sender_shed_frames=diag.get("sender_shed_frames", 0),+ sender_catchup_dropped_frames=diag.get(+ "sender_catchup_dropped_frames", 0+ ),+ recv_dropped_frames=diag.get("recv_dropped_frames", 0),+ max_loop_stall_ms=int(self._loop_lag.max_lag_ever_ms),+ language_flips=self._language_flips,+ close_clean=not (self._close_timed_out or self._failed.is_set()),+ )+async def end(self, *, reason: str = "") -> None:if self._ended:return@@ -6884,6 +7000,7 @@ class RealtimeVoiceSession:self._session.close(), timeout=_PROVIDER_CLOSE_BOUND_S)except TimeoutError:+ self._close_timed_out = Truelog.warning("realtime[%s] provider close timed out during end(); ""abandoning the socket so hangup can complete",@@ -6896,6 +7013,19 @@ class RealtimeVoiceSession:await self._tool_bridge.close()except Exception: # noqa: BLE001, S110 — teardown is best-effortpass+ # Transport-health postmortem, unconditionally — including handovers+ # and browser sessions: it describes THIS realtime transport's life,+ # not the logical call, so no session-boundary subscriber reacts to+ # it. The flight recorder is its consumer.+ if self._session is not None:+ self._harvest_adapter_diagnostics(self._session)+ if self._bus is not None:+ try:+ await self._bus.publish(+ self._build_postmortem(reason or HANGUP_CLIENT_STOP)+ )+ except Exception: # noqa: BLE001, S110 — telemetry never blocks teardown+ pass# Every surface publishes the logical session end. The browser# surface has no other publisher (it bypasses the speech pipeline),# so it keeps its started-gate; the desktop surface ALSO gets onediff --git a/jarvis/realtime/webrtc_transport.py b/jarvis/realtime/webrtc_transport.pyindex ea4fd8d1dd..0a25c14440 100644--- a/jarvis/realtime/webrtc_transport.py+++ b/jarvis/realtime/webrtc_transport.py@@ -434,6 +434,7 @@ class RealtimeWebRtcAudioEndpoint:self._reader_task: asyncio.Task[None] | None = Noneself._mic_resampler = _MicResampler()self._outgoing_drops = 0+ self._recv_dropped = 0self._first_audio_timeout_s = max(0.1, float(first_audio_timeout_s))self._closed = False# The output stream is terminated exactly once, and that fact outlives@@ -536,6 +537,7 @@ class RealtimeWebRtcAudioEndpoint:with_suppress_get(self._recv_queue)self._recv_queue.put_nowait(pcm)dropped += 1+ self._recv_dropped += 1if dropped == 1 or dropped % _DROP_LOG_EVERY == 0:log.warning("Realtime WebRTC receive queue is full; dropped "@@ -571,6 +573,23 @@ class RealtimeWebRtcAudioEndpoint:# silence for the life of the process.await self.close()+ def diagnostics(self) -> dict[str, int]:+ """Transport counters for the end-of-session postmortem event.++ All zero in a healthy call. This method is the one public seam for+ them — reading the sender's private fields here keeps every other+ consumer (session postmortem, probe, forensics) off the internals.+ """+ sender = getattr(self._sender, "_impl", None)+ return {+ "sender_pacing_resyncs": int(getattr(sender, "_pacing_resyncs", 0)),+ "sender_catchup_dropped_frames": int(+ getattr(sender, "_catchup_dropped", 0)+ ),+ "sender_shed_frames": int(self._outgoing_drops),+ "recv_dropped_frames": int(self._recv_dropped),+ }+def _end_stream(self) -> None:"""Terminate the output stream exactly once, without fail.diff --git a/scripts/diag_voice_sessions.py b/scripts/diag_voice_sessions.pyindex 74a25a95f3..d28b0e4d41 100644--- a/scripts/diag_voice_sessions.py+++ b/scripts/diag_voice_sessions.py@@ -14,13 +14,23 @@ confirmed in the 2026-07-13 realtime forensics (BUG-047..BUG-050):returned no text at all (outside the legitimate suppress paths).- ``silent-turn`` — a user turn completed without any assistant text.+Plus every realtime transport-health class from the ``RealtimeSessionPostmortem``+event (splice seams, ungrounded caption/refusal storms, event-loop stalls,+sender-behind-wall-clock, rebuild loops, mute emergency releases, language+flips, spawn budget) — the verdict logic is shared with the codex live-call+probe via ``jarvis.diagnostics.realtime_forensics`` so the two can never+disagree.+Usage::python scripts/diag_voice_sessions.py # today's sessionspython scripts/diag_voice_sessions.py --date 2026-07-13python scripts/diag_voice_sessions.py --last 3 # newest N sessions only+ python scripts/diag_voice_sessions.py --harness data/diagnostics/codex_live/<ts>/round.jsonl-Read-only developer diagnostic: no app, network, or config access.+Read-only developer diagnostic: no app, network, or config access. The+``--harness`` mode exits 1 when any HIGH finding survives, so probe rounds+can gate on it."""from __future__ import annotations@@ -37,6 +47,10 @@ REPO_ROOT = Path(__file__).resolve().parents[1]sys.path.insert(0, str(REPO_ROOT))from jarvis.brain.action_honesty import has_deferred_action_claim # noqa: E402+from jarvis.diagnostics.realtime_forensics import ( # noqa: E402+ evaluate_postmortem,+ extract_postmortems,+)_MAX_PREVIEW_CHARS = 90_RETRY_LOOP_THRESHOLD = 3@@ -210,12 +224,26 @@ def _check_silent_turns(session: Session) -> None:)+def _check_realtime_postmortem(session: Session) -> None:+ """Fold the shared transport-health verdicts into this session's findings."""+ for payload in extract_postmortems(session.events):+ for verdict in evaluate_postmortem(payload):+ session.findings.append(+ Finding(+ severity=verdict.severity,+ kind=verdict.kind,+ detail=verdict.detail,+ )+ )++_CHECKS = (_check_promise_without_action,_check_voice_identity,_check_tool_retry_loops,_check_exhausted_brain_turns,_check_silent_turns,+ _check_realtime_postmortem,)@@ -257,6 +285,36 @@ def _format_report(sessions: list[Session]) -> str:return "\n".join(lines)+def audit_harness_capture(rows: list[dict[str, Any]]) -> tuple[str, int]:+ """Verdict table for a probe round capture; exit 1 on any HIGH finding.++ A probe round is one session (occasionally more after a rebuild), so the+ report is per postmortem rather than per reconstructed session timeline.+ """+ postmortems = extract_postmortems(rows)+ if not postmortems:+ return "no RealtimeSessionPostmortem in the capture", 2+ lines: list[str] = []+ worst_is_high = False+ for payload in postmortems:+ findings = evaluate_postmortem(payload)+ verdict = "PASS"+ if any(f.severity == "high" for f in findings):+ verdict, worst_is_high = "FAIL", True+ elif findings:+ verdict = "WARN"+ lines.append(+ f"postmortem {str(payload.get('session_id', '?'))[:12]} "+ f"provider={payload.get('provider', '?')} "+ f"turns={payload.get('turns_completed', 0)} "+ f"ready={payload.get('ready_ms', 0)}ms "+ f"first_audio={payload.get('first_audio_ms', 0)}ms -> {verdict}"+ )+ for finding in findings:+ lines.append(f" [{finding.severity:4}] {finding.kind}: {finding.detail}")+ return "\n".join(lines), (1 if worst_is_high else 0)++def main(argv: list[str] | None = None) -> int:parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])parser.add_argument(@@ -270,8 +328,25 @@ def main(argv: list[str] | None = None) -> int:default=0,help="audit only the newest N sessions (default: all)",)+ parser.add_argument(+ "--harness",+ type=Path,+ default=None,+ help=(+ "audit a codex live-probe round capture (round.jsonl) instead of "+ "the flight recorder; exits 1 on any HIGH finding"+ ),+ )args = parser.parse_args(argv)+ if args.harness is not None:+ if not args.harness.exists():+ print(f"no harness capture at {args.harness}")+ return 2+ report, code = audit_harness_capture(_load_events(args.harness))+ print(report)+ return code+recorder_path = REPO_ROOT / "data" / "flight_recorder" / f"{args.date}.jsonl"if not recorder_path.exists():print(f"no flight recorder file for {args.date}: {recorder_path}")diff --git a/tests/unit/diagnostics/test_realtime_forensics.py b/tests/unit/diagnostics/test_realtime_forensics.pynew file mode 100644index 0000000000..23823fd2d3--- /dev/null+++ b/tests/unit/diagnostics/test_realtime_forensics.py@@ -0,0 +1,107 @@+"""Shared realtime postmortem verdicts (probe + diag script consume these).++The whole point of the module is that the live-call probe and the+flight-recorder audit judge a session identically — so these tests pin the+verdict boundaries, not the wording.+"""++from __future__ import annotations++from jarvis.diagnostics.realtime_forensics import (+ SPAWN_FIRST_AUDIO_BUDGET_MS,+ SPAWN_READY_BUDGET_MS,+ evaluate_postmortem,+ extract_postmortems,+)+++def _healthy() -> dict[str, object]:+ return {+ "session_id": "healthy",+ "provider": "codex-subscription-realtime",+ "turns_completed": 4,+ "ready_ms": 2400,+ "first_audio_ms": 4100,+ "close_clean": True,+ }+++def _kinds(pm: dict[str, object]) -> set[str]:+ return {finding.kind for finding in evaluate_postmortem(pm)}+++def test_a_healthy_session_yields_no_findings() -> None:+ assert evaluate_postmortem(_healthy()) == []+++def test_every_failure_class_maps_to_its_finding() -> None:+ sick = _healthy() | {+ "response_splices": 2,+ "quiescence_boundary_turns": 4,+ "ungrounded_captions_dropped": 3,+ "ungrounded_responses_refused": 7,+ "self_dialogue_rebuilds": 1,+ "mute_emergency_releases": 2,+ "max_loop_stall_ms": 15_000,+ "sender_pacing_resyncs": 1,+ "sender_shed_frames": 40,+ "recv_dropped_frames": 5,+ "rebuilds": 2,+ "stun_retries": 1,+ "language_flips": 2,+ "ready_ms": SPAWN_READY_BUDGET_MS + 1,+ "first_audio_ms": SPAWN_FIRST_AUDIO_BUDGET_MS + 1,+ "close_clean": False,+ }+ assert _kinds(sick) == {+ "splice-seam",+ "turn-without-boundary",+ "ungrounded-caption-storm",+ "refusal-storm",+ "self-dialogue",+ "mute-emergency-release",+ "event-loop-stall",+ "sender-behind-wall-clock",+ "recv-overflow",+ "rebuild-loop",+ "language-mismatch",+ "spawn-over-budget",+ "unclean-close",+ }+++def test_severity_boundaries_hold() -> None:+ # One ungrounded caption is a warn; two are the storm.+ one = evaluate_postmortem(_healthy() | {"ungrounded_captions_dropped": 1})+ assert [(f.severity, f.kind) for f in one] == [("warn", "ungrounded-caption")]+ # Refusals: quiet below 3, warn at 3-4, high at the adapter's storm verdict.+ assert _kinds(_healthy() | {"ungrounded_responses_refused": 2}) == set()+ assert _kinds(_healthy() | {"ungrounded_responses_refused": 3}) == {"refusal-run"}+ assert _kinds(_healthy() | {"ungrounded_responses_refused": 5}) == {+ "refusal-storm"+ }+ # A single rebuild is a warn; two (or any STUN retry) are the loop class.+ assert _kinds(_healthy() | {"rebuilds": 1}) == {"transport-rebuild"}+ assert _kinds(_healthy() | {"stun_retries": 1}) == {"rebuild-loop"}+ # A sub-second scheduling wobble is not a stall.+ assert _kinds(_healthy() | {"max_loop_stall_ms": 900}) == set()+ # first_audio_ms == 0 means "no audio ever" — reported by other counters,+ # never as a spawn overrun.+ assert _kinds(_healthy() | {"first_audio_ms": 0}) == set()+ # One language flip is normal conversation behaviour (de -> en on purpose).+ assert _kinds(_healthy() | {"language_flips": 1}) == set()+++def test_extract_postmortems_reads_both_capture_shapes() -> None:+ recorder_row = {+ "event": "RealtimeSessionPostmortem",+ "payload": {"session_id": "a", "turns_completed": 1},+ }+ probe_row = {"src": "postmortem", "data": {"session_id": "b"}}+ noise = [+ {"event": "VoiceTurnCompleted", "payload": {}},+ {"src": "notif", "data": {"method": "thread/realtime/x"}},+ {"src": "postmortem", "data": "not-a-mapping"},+ ]+ payloads = extract_postmortems([recorder_row, probe_row, *noise])+ assert [p.get("session_id") for p in payloads] == ["a", "b"]diff --git a/tests/unit/realtime/test_session_postmortem.py b/tests/unit/realtime/test_session_postmortem.pynew file mode 100644index 0000000000..ad3d4d38e7--- /dev/null+++ b/tests/unit/realtime/test_session_postmortem.py@@ -0,0 +1,189 @@+"""RealtimeSessionPostmortem: end() publishes one content-free counter event.++The postmortem is the only place a live call's transport health survives the+call (the wildcard flight recorder persists it). Pinned here: exactly one+event per session with the adapter's counters, accumulation across a+transport swap — the provider session OBJECT is replaced on a rebuild and its+counters would otherwise die with it — and honest ``close_clean`` reporting+when teardown has to abandon a hanging provider socket.+"""++from __future__ import annotations++import asyncio+from types import SimpleNamespace+from typing import Any++from jarvis.core.bus import EventBus+from jarvis.core.events import RealtimeSessionPostmortem+from jarvis.realtime.session import RealtimeVoiceSession++TIMEOUT_S = 5.0+RATE = 24_000+++class _Wire:+ """Codex-shaped provider session carrying postmortem diagnostics."""++ session_id = "postmortem-wire"+ creates_responses_automatically = True+ isolates_response_generations = True+ supports_direct_tools = False+ supports_tool_updates = False+ direct_speech_is_authoritative = True+ rebuild_on_transport_death = True++ def __init__(self, diag: dict[str, int] | None = None) -> None:+ self._events: asyncio.Queue[Any] = asyncio.Queue()+ self._diag = dict(diag or {})+ self.closed = False+ self.close_hangs = False++ def diagnostics(self) -> dict[str, int]:+ return dict(self._diag)++ async def send_audio(self, chunk: Any) -> None:+ del chunk++ async def receive(self): # noqa: ANN201 - async generator, protocol shape+ while True:+ event = await self._events.get()+ if event is None:+ return+ yield event++ async def update_session(self, **kwargs: Any) -> None:+ del kwargs++ async def request_response(self, *, required_tool: str | None = None) -> None:+ del required_tool++ async def send_text(self, text: str) -> None:+ del text++ async def send_speech(self, text: str) -> None:+ del text++ async def truncate(self, audio_end_ms: int) -> None:+ del audio_end_ms++ async def interrupt(self) -> None:+ return None++ async def close(self) -> None:+ if self.close_hangs:+ await asyncio.sleep(30.0)+ self.closed = True+ self._events.put_nowait(None)+++class _Provider:+ name = "codex-subscription"+ supports_realtime = True+ input_sample_rate = RATE+ output_sample_rate = RATE++ def __init__(self, wire: _Wire) -> None:+ self._wire = wire++ async def can_open_duplex_session(self) -> bool:+ return True++ async def open_session(self, config: Any) -> _Wire:+ del config+ return self._wire+++def _config() -> SimpleNamespace:+ return SimpleNamespace(+ brain=SimpleNamespace(+ reply_language="en",+ providers={"codex-subscription": SimpleNamespace(model="", voice="cove")},+ ),+ stt=SimpleNamespace(language="auto"),+ voice=SimpleNamespace(mode="realtime", realtime_tool_mode="delegate"),+ )+++async def _open(wire: _Wire) -> tuple[RealtimeVoiceSession, list[RealtimeSessionPostmortem]]:+ bus = EventBus()+ seen: list[RealtimeSessionPostmortem] = []++ async def _collect(event: RealtimeSessionPostmortem) -> None:+ seen.append(event)++ bus.subscribe(RealtimeSessionPostmortem, _collect)+ session = RealtimeVoiceSession(+ session_id="postmortem-session",+ send_binary=lambda data: asyncio.sleep(0),+ send_json=lambda message: asyncio.sleep(0),+ providers=[_Provider(wire)],+ config=_config(),+ bus=bus,+ surface="desktop",+ half_duplex=True,+ browser_sample_rate=RATE,+ )+ await asyncio.wait_for(+ session.handle_control({"type": "audio_start", "sample_rate": RATE}),+ TIMEOUT_S,+ )+ return session, seen+++async def test_end_publishes_one_postmortem_with_adapter_counters() -> None:+ wire = _Wire(+ {+ "ungrounded_responses_refused": 3,+ "ungrounded_captions_dropped": 2,+ "quiescence_boundary_turns": 2,+ "sender_pacing_resyncs": 1,+ }+ )+ session, seen = await _open(wire)++ await asyncio.wait_for(session.end(reason="hotkey"), TIMEOUT_S)++ assert len(seen) == 1, "exactly one postmortem per session"+ event = seen[0]+ assert event.provider == "codex-subscription"+ assert event.hangup_reason == "hotkey"+ assert event.ungrounded_responses_refused == 3+ assert event.ungrounded_captions_dropped == 2+ assert event.quiescence_boundary_turns == 2+ assert event.sender_pacing_resyncs == 1+ assert event.ready_ms >= 0+ assert event.close_clean is True++ # A second end() must not publish a second postmortem.+ await asyncio.wait_for(session.end(reason="hotkey"), TIMEOUT_S)+ assert len(seen) == 1+++async def test_postmortem_accumulates_across_a_transport_swap() -> None:+ """A rebuild replaces the provider session object; its counters must not+ vanish with it — the harvest folds them into the accumulator the final+ postmortem reads."""+ dead_wire = _Wire({"response_splices": 2, "ungrounded_responses_refused": 4})+ live_wire = _Wire({"response_splices": 1})+ session, seen = await _open(live_wire)++ session._harvest_adapter_diagnostics(dead_wire) # noqa: SLF001 — the rebuild path's harvest+ await asyncio.wait_for(session.end(reason="error"), TIMEOUT_S)++ assert len(seen) == 1+ assert seen[0].response_splices == 3+ assert seen[0].ungrounded_responses_refused == 4+++async def test_a_hanging_provider_close_reports_unclean() -> None:+ wire = _Wire()+ wire.close_hangs = True+ session, seen = await _open(wire)++ await asyncio.wait_for(session.end(reason="hotkey"), TIMEOUT_S)++ assert len(seen) == 1+ assert seen[0].close_clean is False, (+ "an abandoned provider socket is not a clean close"+ )diff --git a/tests/unit/realtime/test_webrtc_transport.py b/tests/unit/realtime/test_webrtc_transport.pyindex 84b5b30d85..fcede9a09e 100644--- a/tests/unit/realtime/test_webrtc_transport.py+++ b/tests/unit/realtime/test_webrtc_transport.py@@ -93,6 +93,8 @@ class _Endpoint(webrtc_transport.RealtimeWebRtcAudioEndpoint):self._closed = Falseself._ended = Falseself._outgoing_drops = 0+ self._recv_dropped = 0+ self._sender = Noneself._remote_track_seen = asyncio.Event()self._connection_changed = asyncio.Event()@@ -347,6 +349,27 @@ async def test_close_is_idempotent_and_closes_the_peer_once() -> None:assert endpoint._pc.closed == 1+def test_diagnostics_reports_all_transport_counters() -> None:+ """``diagnostics()`` is the one public seam for the postmortem counters.++ All zero on a healthy endpoint; the sender-less test double stands for an+ endpoint whose sender never came up — still all zero, never an error.+ """+ endpoint = _Endpoint()+ assert endpoint.diagnostics() == {+ "sender_pacing_resyncs": 0,+ "sender_catchup_dropped_frames": 0,+ "sender_shed_frames": 0,+ "recv_dropped_frames": 0,+ }++ endpoint._outgoing_drops = 7+ endpoint._recv_dropped = 3+ diag = endpoint.diagnostics()+ assert diag["sender_shed_frames"] == 7+ assert diag["recv_dropped_frames"] == 3++# --------------------------------------------------------------------------# WR-4 — a connected peer is not the same as a usable media path# --------------------------------------------------------------------------