Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
fix(realtime): stabilize turn delivery and recovery
rubenluetke10-beep1b50fb4045b4
diff --git a/.github/workflows/realtime-reliability.yml b/.github/workflows/realtime-reliability.ymlnew file mode 100644index 0000000000..73aba72096--- /dev/null+++ b/.github/workflows/realtime-reliability.yml@@ -0,0 +1,134 @@+# Realtime's small, blocking cross-platform contract. It is separate from the+# monolithic CI matrix so macOS can run this focused suite on every change+# without multiplying the hour-long full-suite cost.+#+# No job here owns a microphone, speaker, desktop session, or provider secret.+# Physical microphone/acoustic-echo behavior, device hot-plug, and macOS TCC+# prompts remain explicit human release sign-offs; a headless runner must never+# turn their absence into a fake green result.++name: Realtime reliability++on:+ push:+ branches:+ - main+ - "wip/cross-platform-cloud-first-20260529"+ tags:+ - "v*"+ pull_request:+ workflow_dispatch:+ inputs:+ run_contract_soak:+ description: "Run the extended synthetic orchestration soak (not release evidence)."+ type: boolean+ default: true++concurrency:+ group: realtime-reliability-${{ github.workflow }}-${{ github.ref }}+ cancel-in-progress: true++permissions:+ contents: read++jobs:+ provider-contract:+ name: provider contract (${{ matrix.os }})+ strategy:+ fail-fast: false+ matrix:+ os:+ - ubuntu-latest+ - windows-latest+ - macos-latest+ runs-on: ${{ matrix.os }}+ timeout-minutes: 25++ steps:+ - name: Checkout+ uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2+ with:+ persist-credentials: false++ - name: Set up Python 3.11+ uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0+ with:+ python-version: "3.11"++ - name: Install portable base and focused test runner+ shell: bash+ run: |+ python -m pip install --upgrade pip+ python -m pip install -e .+ python -m pip install pytest pytest-asyncio++ - name: Blocking provider-neutral realtime contract+ run: >-+ python -m pytest+ tests/contract/test_realtime_provider_contract.py+ tests/contract/test_realtime_reliability_gate.py+ -q -p no:cacheprovider++ python-slim-no-audio:+ name: python:3.11-slim (no PortAudio)+ runs-on: ubuntu-latest+ container: python:3.11-slim+ timeout-minutes: 25++ steps:+ - name: Checkout+ uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2+ with:+ persist-credentials: false++ - name: Install base without system audio libraries+ run: |+ python -m pip install --upgrade pip+ python -m pip install -e .+ python -m pip install pytest pytest-asyncio++ - name: Prove the container really has no usable PortAudio+ run: |+ python - <<'PY'+ try:+ import sounddevice # noqa: F401+ except Exception as exc:+ print(f"NO_PORTAUDIO: {type(exc).__name__}: {exc}")+ else:+ raise SystemExit("python:3.11-slim unexpectedly loaded PortAudio")+ PY++ - name: Blocking headless realtime degradation contract+ run: >-+ python -m pytest+ tests/contract/test_realtime_provider_contract.py+ tests/contract/test_realtime_reliability_gate.py+ -q -p no:cacheprovider++ extended-contract-soak:+ name: extended contract soak (not release evidence)+ # This synthetic orchestration proof must never green-light a tag. A real+ # release still needs same-SHA target measurements and manual acoustic+ # sign-off, neither of which a headless GitHub runner can produce.+ if: github.event_name == 'workflow_dispatch' && inputs.run_contract_soak+ runs-on: ubuntu-latest+ timeout-minutes: 25++ steps:+ - name: Checkout+ uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2+ with:+ persist-credentials: false++ - name: Set up Python 3.11+ uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0+ with:+ python-version: "3.11"++ - name: Install portable base+ run: |+ python -m pip install --upgrade pip+ python -m pip install -e .++ - name: Run provider-neutral orchestration soak+ run: python scripts/realtime_reliability_gate.py --contract-soakdiff --git a/jarvis/brain/turn_planner.py b/jarvis/brain/turn_planner.pyindex e3911d4a6e..e165b67860 100644--- a/jarvis/brain/turn_planner.py+++ b/jarvis/brain/turn_planner.py@@ -154,26 +154,58 @@ _CURRENT_RE = re.compile(# its unaided public-fact recall is not a trustworthy source. It must not turn# advice, how-to requests, private data, or connected data into web searches._PUBLIC_FACT_QUESTION_RE = re.compile(- r"^\s*(?:(?:hey|hello|hi|hallo|hola|okay|ok|jarvis|please|bitte|"+ r"^[\s¿¡]*(?:(?:hey|hello|hi|hallo|hola|okay|ok|jarvis|please|bitte|"r"por favor)[\s,]+){0,3}(?:"r"who\b|where\b|when\b|which\b|"r"what\s+(?:is|are|was|were|did|does|has|have)\b|"- r"how\s+(?:many|much|old|long|large|big|tall|far)\b|"+ r"what\s+year\b|in\s+(?:what|which)\s+year\b|"+ r"how\s+(?:many|much|old|long|high|fast|large|big|tall|far)\b|"r"wer\b|wo\b|wann\b|welch\w*\b|"r"was\s+(?:ist|sind|war|waren|hat|haben|macht|machte)\b|" # i18n-allow- r"wie\s+(?:viel|viele|alt|lang|gross|weit)\b|" # i18n-allow: speech input+ r"in\s+welch\w*\s+jahr\b|"+ r"wie\s+(?:viel\w*|alt\w*|lang\w*|hoch\w*|schnell\w*|"+ r"gross\w*|weit\w*)\b|" # i18n-allow: speech inputr"quien\b|donde\b|cuando\b|cual\w*\b|cuant\w*\b|"+ r"(?:en\s+)?que\s+ano\b|"r"que\s+(?:es|son|fue|eran|hizo|hace|tiene|tienen)\b"r")" # i18n-allow: multilingual speech-input matching data)_PUBLIC_FACT_REQUEST_RE = re.compile(- r"^\s*(?:(?:hey|hello|hi|hallo|hola|okay|ok|jarvis|please|bitte|"+ r"^[\s¿¡]*(?:(?:hey|hello|hi|hallo|hola|okay|ok|jarvis|please|bitte|"r"por favor)[\s,]+){0,3}(?:"r"tell me|give me|look up|search(?: for)?|check|find|"r"sag mir|nenne mir|such\w*|pruef\w*|find\w*|"r"dime|busca|revisa|encuentra"r")\b" # i18n-allow: multilingual speech-input matching data)++# Concrete local-world evidence that can look like a public fact request.+# These shapes belong to filesystem/process/settings tools, never search_web.+# Phrases stay qualified because a bare "process" or "file" can itself be the+# subject of an evergreen definition.+_LOCAL_EVIDENCE_RE = re.compile(+ r"\b(?:"+ r"(?:on|from|inside|under)\s+(?:this|that|my|the)\s+"+ r"(?:computer|machine|device|disk|filesystem|file|folder|directory)|"+ r"(?:in|inside)\s+(?:this|that|my|the)\s+(?:file|folder|directory)|"+ r"(?:executable|file|folder|directory|path).{0,32}\b(?:on disk|locally)\b|"+ r"local\s+(?:config(?:uration)?|settings?|file|folder|directory|process|service)|"+ r"config(?:uration)?\s+file|(?:running|local)\s+(?:process|service)|"+ r"(?:process|service).{0,32}\b(?:port|pid|machine|computer)\b|"+ r"environment\s+variable|registry\s+key|system\s+setting|"+ r"(?:current|jarvis|app|system|my|the)\s+settings?|settings?\s+file|"+ r"(?:readme|pyproject|package\.json|jarvis\.toml)\b|"+ r"(?:auf|von|in)\s+(?:diesem|meinem|dem)\s+" # i18n-allow: speech input+ r"(?:computer|rechner|geraet|datei|ordner|verzeichnis)|"+ r"(?:datei|ordner|verzeichnis|pfad|prozess|dienst).{0,32}\b"+ r"(?:lokal|port|pid|rechner)\b|"+ r"umgebungsvariable|systemeinstellung|"+ r"(?:en|dentro de)\s+(?:este|esta|mi|el|la)\s+"+ r"(?:equipo|ordenador|dispositivo|archivo|carpeta|directorio)|"+ r"(?:archivo|carpeta|directorio|ruta|proceso|servicio).{0,32}\b"+ r"(?:local|puerto|pid|equipo)\b|variable\s+de\s+entorno"+ r")" # i18n-allow: multilingual speech-input matching data+)_LOCAL_STATE_RE = re.compile(r"\b(?:wiki|mcp\w*|cli\w*|tool\w*|plugin\w*|connector\w*|"r"integration\w*|setting\w*|configuration\w*|api[\s-]?key\w*|"@@ -190,9 +222,9 @@ _LOCAL_STATE_RE = re.compile(r"instalad\w*|conectad\w*|capacidad\w*)\b" # i18n-allow: speech input)_CONNECTED_DOMAIN_RE = re.compile(- r"\b(?:gmail|email|e-mail|mailbox|inbox|calendar|sap|salesforce|"+ r"\b(?:gmail|email|e-mail|mailboxes?|inboxes?|calendars?|sap|salesforce|"r"github|gitlab|drive|notion|slack|discord|telegram|whatsapp|"- r"repository|pull request|deployment|cloud billing|contact\w*|"+ r"repositor(?:y|ies)|pull requests?|deployments?|cloud billing|contact\w*|"r"postfach|posteingang|kalender|termin\w*|kontakt\w*|abrechnung\w*|"r"correo|bandeja|calendario|cita\w*|contacto\w*)\b" # i18n-allow: speech input)@@ -341,6 +373,8 @@ _DATE_TRIVIA_RE = re.compile(# i18n-allow: multilingual speech-input matching datar"\bwas (?:ist|wird|war) (?:heute|morgen|uebermorgen|gestern)" # i18n-allow: speech inputr"[^.?!]{0,24}?\b(?:tag|wochentag|datum)\b|" # i18n-allow: speech input+ r"\bwas (?:heute|morgen|uebermorgen|gestern)[^.?!]{0,24}?" # i18n-allow: speech input+ r"\b(?:tag|wochentag|datum)\b[^.?!]{0,12}?\b(?:ist|wird|war)\b|" # i18n-allowr"\b(?:welcher|welchen|was fuer ein\w*) (?:tag|wochentag)\b" # i18n-allow: speech inputr"[^.?!]{0,16}?\b(?:ist|haben wir|war)\b(?:[^.?!]{0,16}?" # i18n-allow: speech inputr"\b(?:heute|morgen|uebermorgen|gestern)\b)?|" # i18n-allow: speech input@@ -348,6 +382,7 @@ _DATE_TRIVIA_RE = re.compile(r"\bder wievielte\b(?:[^.?!]{0,16}?"r"\b(?:heute|morgen|uebermorgen|gestern)\b)?|"r"\bwhat day (?:is|was)(?: it)?(?: (?:today|tomorrow|yesterday))?\b|"+ r"\bwhat (?:day|date) (?:today|tomorrow|yesterday) (?:is|was)\b|"r"\bwhat is (?:today|tomorrow|yesterday)(?:'s)? (?:day|date|for day)\b|"r"\bwhat(?:'s| is) the (?:date|day)\b(?: (?:today|tomorrow)\b)?|"r"\bque dia es (?:hoy|manana)\b|\ba que fecha estamos\b"@@ -572,7 +607,15 @@ def is_public_fact_question(text: str) -> bool:Keeping it deterministic makes it safe on the voice hot path."""normalized = _normalize(text).strip()- if not normalized or _INSTRUCTIONAL_RE.search(normalized):+ if (+ not normalized+ or _INSTRUCTIONAL_RE.search(normalized)+ or _LOCAL_EVIDENCE_RE.search(normalized)+ or _APP_STATE_RE.search(normalized)+ or _OWNERSHIP_RE.search(normalized)+ or _CONNECTED_DOMAIN_RE.search(normalized)+ or _CONTACT_DETAIL_RE.search(normalized)+ ):return Falsereturn bool(_PUBLIC_FACT_QUESTION_RE.search(normalized)@@ -716,6 +759,8 @@ def plan_turn(reasons.add(TurnReason.PRIVATE_DATA)if _LOCAL_STATE_RE.search(normalized) and not definition:reasons.add(TurnReason.LOCAL_STATE)+ if _LOCAL_EVIDENCE_RE.search(normalized) and (lookup or action_intent):+ reasons.add(TurnReason.LOCAL_STATE)if (_CONNECTED_DOMAIN_RE.search(normalized)and not definition@@ -862,6 +907,7 @@ def plan_turn(# private lookups retain their own tools and must never leak into web# search. Set de-duplication gives the execution layer exactly one required# search capability even if the live tool catalog matched it too.+ public_fact_shape = is_public_fact_question(text)non_public_evidence = reasons & {TurnReason.LOCAL_STATE,TurnReason.MISSION,@@ -870,6 +916,8 @@ def plan_turn(TurnReason.SKILL,TurnReason.WORKSPACE,}+ if TurnReason.ACTION in reasons and not public_fact_shape:+ non_public_evidence.add(TurnReason.ACTION)required_without_public_search = {item for item in required if item != PUBLIC_FACT_GROUNDING_CAPABILITY}@@ -882,7 +930,6 @@ def plan_turn(or private):non_public_evidence.add(TurnReason.CONNECTED_DATA)- public_fact_shape = is_public_fact_question(text)fresh_public_fact = (TurnReason.CURRENT_DATA in reasonsand (public_fact_shape or lookup)diff --git a/jarvis/core/events.py b/jarvis/core/events.pyindex 9f1bfca0b6..75a0eee5da 100644--- a/jarvis/core/events.py+++ b/jarvis/core/events.py@@ -1696,6 +1696,28 @@ class RealtimeSessionPostmortem(Event):late_response_readoptions: int = 0#: Provider responses cancelled by the fail-closed output gate.unsafe_output_cancellations: int = 0+ #: Required public-fact searches started through the supervisor gateway.+ public_fact_grounding_attempts: int = 0+ #: Required public-fact searches that yielded a grounded localized answer.+ public_fact_grounding_successes: int = 0+ #: Required public-fact turns that degraded to honest uncertainty.+ public_fact_grounding_failures: int = 0+ #: Provider outputs rejected for using the wrong resolved turn language.+ output_language_mismatches: int = 0+ #: One-shot provider retries requested after a language mismatch.+ output_language_retries: int = 0+ #: Language retries that still ended in the localized safe fallback.+ output_language_failures: int = 0+ #: Stable delegate result delivery claims made during this session.+ delegate_delivery_claims: int = 0+ #: Delegate results confirmed by audible PCM or the completion channel.+ delegate_deliveries_completed: int = 0+ #: Completed delegate results recovered through AnnouncementRequested.+ delegate_delivery_recoveries: int = 0+ #: Duplicate delegate delivery attempts suppressed by the stable ledger.+ delegate_delivery_duplicates_suppressed: int = 0+ #: In-flight delegates transferred from socket to process lifetime.+ delegate_deliveries_detached: int = 0#: Opening responses cut at the cap because no user question existed yet.opening_responses_bounded: int = 0#: Self-dialogue verdicts that forced a transport replacement (BUG-124).diff --git a/jarvis/core/turn_language.py b/jarvis/core/turn_language.pyindex e9b0551df1..3e01d685b0 100644--- a/jarvis/core/turn_language.py+++ b/jarvis/core/turn_language.py@@ -77,6 +77,7 @@ _URL_RE = re.compile(r"\b(?:https?://|www\.)\S+", re.IGNORECASE)# English, or Spanish sentence containing a Chinese name remains valid._HAN_RE = re.compile(r"[\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff]")_LATIN_LETTER_RE = re.compile(r"[A-Za-z\u00c0-\u024f]")+_MIN_GROSS_HAN_CHARS = 10# Vietnamese uses Latin script, so script alone is insufficient. The validator# combines its characteristic letters/tones with a vocabulary signal and only@@ -217,7 +218,10 @@ def _prose_for_output_validation(text: str) -> str:def _detect_gross_han_output(text: str) -> bool:han_count = len(_HAN_RE.findall(text))- if han_count < 4:+ # A short Han span is commonly a person, organization, or product name,+ # including a compact label value. It is not enough evidence to suppress+ # an otherwise correctly resolved answer.+ if han_count < _MIN_GROSS_HAN_CHARS:return Falselatin_count = len(_LATIN_LETTER_RE.findall(text))script_ratio = han_count / max(1, han_count + latin_count)diff --git a/jarvis/diagnostics/realtime_forensics.py b/jarvis/diagnostics/realtime_forensics.pyindex cedc4d0684..c109f62475 100644--- a/jarvis/diagnostics/realtime_forensics.py+++ b/jarvis/diagnostics/realtime_forensics.py@@ -106,6 +106,40 @@ def evaluate_postmortem(pm: Mapping[str, Any]) -> list[RealtimeFinding]:))+ language_failures = _count(pm, "output_language_failures")+ language_mismatches = _count(pm, "output_language_mismatches")+ if language_failures or language_mismatches:+ add(+ RealtimeFinding(+ "high" if language_failures else "warn",+ "output-language-mismatch",+ f"{language_mismatches} wrong-language response(s) were "+ f"blocked; {language_failures} exhausted the one-shot retry",+ )+ )++ grounding_failures = _count(pm, "public_fact_grounding_failures")+ if grounding_failures:+ add(+ RealtimeFinding(+ "warn",+ "public-fact-grounding-unavailable",+ f"{grounding_failures} required public-fact lookup(s) "+ "degraded to an honest uncertainty response",+ )+ )++ detached_deliveries = _count(pm, "delegate_deliveries_detached")+ if detached_deliveries:+ add(+ RealtimeFinding(+ "info",+ "delegate-delivery-detached",+ f"{detached_deliveries} in-flight delegate result(s) were "+ "retained beyond realtime socket teardown",+ )+ )+quiescence = _count(pm, "quiescence_boundary_turns")if quiescence:add(diff --git a/jarvis/realtime/scrub_gate.py b/jarvis/realtime/scrub_gate.pyindex 65b3630f03..3a72cf7b2a 100644--- a/jarvis/realtime/scrub_gate.py+++ b/jarvis/realtime/scrub_gate.py@@ -110,6 +110,14 @@ class ScrubHoldGate:self._hard_leak = Falseself._transcript_seen = Falseself._transcript_tail = ""+ # Language classification needs more context than the first streamed+ # words often provide. Until the aggregate is a positive match, PCM+ # stays buffered: an indeterminate prefix must not authorize audio that+ # a later delta proves belongs to the wrong language. A still-+ # indeterminate *complete* reply is released by ``finalize`` because+ # the shared validator deliberately treats that verdict as fail-open.+ self._language_validation_active = False+ self._language_match_seen = False# A provider may split a control token across transcript deltas. The# ordinary scrubber sees each delta independently for display, so a# split token used to pass through unchanged even though the aggregate@@ -221,7 +229,13 @@ class ScrubHoldGate:"""The non-empty provider response currently owned by this gate."""return self._response_id- async def feed_transcript(self, text: str, *, response_id: str = "") -> str:+ async def feed_transcript(+ self,+ text: str,+ *,+ response_id: str = "",+ enforce_output_language: bool = False,+ ) -> str:"""Scrub a transcript boundary. Returns display-safe text.Sets the clear flag (audio may flow) on clean text; sets the hard-leak@@ -241,18 +255,23 @@ class ScrubHoldGate:self._transcript_seen = Trueaggregate = scrub_for_voice(self._transcript_tail, language=self._language)result = scrub_for_voice(text, language=self._language)- language_verdict = validate_output_language(- aggregate.cleaned,- resolved_language=self._language,- )- if language_verdict.should_block:- self._hard_leak = True- self._hard_leak_actions = ("output_language_mismatch",)- self._cleared = False- self._pending.clear()- self._pending_audio_ms = 0.0- self._pending_since = None- return self.fallback_phrase()+ language_verdict = None+ if enforce_output_language:+ self._language_validation_active = True+ language_verdict = validate_output_language(+ aggregate.cleaned,+ resolved_language=self._language,+ )+ if language_verdict.should_block:+ self._hard_leak = True+ self._hard_leak_actions = ("output_language_mismatch",)+ self._cleared = False+ self._pending.clear()+ self._pending_audio_ms = 0.0+ self._pending_since = None+ return self.fallback_phrase()+ if language_verdict.status == "match":+ self._language_match_seen = Trueaggregate_is_hard = _is_hard_scrub_result(aggregate)result_is_hard = _is_hard_scrub_result(result)if aggregate_is_hard or result_is_hard:@@ -277,6 +296,19 @@ class ScrubHoldGate:self._covered_chars += len(text)self._cleared = Falsereturn text+ if (+ language_verdict is not None+ and language_verdict.status == "indeterminate"+ and not self._language_match_seen+ ):+ # Keep the opening PCM fail-closed until enough aggregate prose+ # establishes the resolved language. Display text may continue;+ # it has already passed the ordinary regex scrub above.+ self._covered_chars += len(text)+ self._cleared = False+ if not result.actions:+ return text+ return _restore_edge_whitespace(text, result.cleaned)self._covered_chars += len(text)self._coverage_active = Trueself._cleared = True@@ -455,6 +487,11 @@ class ScrubHoldGate:self._expire_direct_speech_budget()if self.fail_closed() or self._hard_leak:return []+ # A complete short/ambiguous reply can remain indeterminate forever.+ # That verdict is intentionally non-blocking; only the response+ # boundary, after every delta has been inspected, may release it.+ if self._language_validation_active and not self._language_match_seen:+ self._cleared = Trueout = self._pendingself._pending = []self._pending_audio_ms = 0.0@@ -502,6 +539,8 @@ class ScrubHoldGate:self._hard_leak = Falseself._transcript_seen = Falseself._transcript_tail = ""+ self._language_validation_active = False+ self._language_match_seen = Falseself._control_tail = ""self._hard_leak_actions = ()self._response_id = ""diff --git a/jarvis/realtime/session.py b/jarvis/realtime/session.pyindex c0d562c2a5..d1c8da21ba 100644--- a/jarvis/realtime/session.py+++ b/jarvis/realtime/session.py@@ -11,6 +11,7 @@ from __future__ import annotationsimport arrayimport asyncioimport inspect+import jsonimport loggingimport randomimport re@@ -41,13 +42,20 @@ from jarvis.brain.provider_test import (UNREACHABLE,classify_provider_error,)-from jarvis.brain.turn_planner import TurnPath, TurnPlan, TurnReason, plan_turn+from jarvis.brain.turn_planner import (+ TurnPath,+ TurnPlan,+ TurnReason,+ is_public_fact_question,+ plan_turn,+)from jarvis.core.protocols import AudioChunk, BrainMessagefrom jarvis.core.redact import safe_previewfrom jarvis.core.turn_language import (is_substantive_turn,normalize_language_tag,resolve_output_language,+ validate_output_language,)from jarvis.realtime.audio import StreamingPcm16Resamplerfrom jarvis.realtime.protocol import RealtimeSessionConfig@@ -120,6 +128,10 @@ _TURN_STALL_POLL_S = 0.5# Withheld provider output used to leave no trace anywhere (AP-30): a turn could# be dropped in full and the log looked like a healthy call. Report it, bounded._OUTPUT_DROP_LOG_INTERVAL_S = 2.0+# Prefer the provider's own terminal boundary before requesting a language+# retry. A short timer is the bounded escape hatch for transports that never+# emit one after response cancellation.+_OUTPUT_LANGUAGE_RETRY_BOUNDARY_GRACE_S = 0.35# Answered input-item ids retained for duplicate suppression. Per transport# (cleared on rebuild) and bounded, so a long call cannot grow one entry per# utterance forever.@@ -236,26 +248,6 @@ _CREDENTIAL_TERMINAL_STATUSES = frozenset(_PROVIDER_FAILOVER_STATUSES = frozenset({MODEL_UNAVAILABLE, RATE_LIMITED, UNREACHABLE})-# Narrow proof that a native turn is an ordinary factual question. This is-# intentionally not a generic "planner said native" check: advice, deictic-# follow-ups, and ambiguous action phrases also stay native so the realtime-# model can disambiguate them with a tool call. The multilingual tokens are-# literal speech-input matching data. # i18n-allow: supported input vocabulary-_PUBLIC_KNOWLEDGE_QUESTION_RE = re.compile(- r"^\s*(?:"- r"who\b|where\b|when\b|which\b|"- r"what\s+(?:is|are|was|were|did|does|has|have)\b|"- r"how\s+(?:many|much|old|large|big|far)\b|"- r"wer\b|wo\b|wann\b|welch\w*\b|"- r"was\s+(?:ist|sind|war|waren|hat|haben|macht|machte)\b|" # i18n-allow: input- r"wie\s+(?:viel|viele|alt|gross|groß|weit)\b|" # i18n-allow: input- r"quien\b|donde\b|cuando\b|cual\w*\b|cuant\w*\b|"- r"que\s+(?:es|son|fue|eran|hizo|hace|tiene|tienen)\b"- r")",- re.IGNORECASE,-)--def _pcm16_peak(pcm: bytes) -> int:"""Peak absolute amplitude of little-endian int16 PCM (C-speed, no numpy)."""usable = len(pcm) - (len(pcm) % 2)@@ -266,10 +258,6 @@ def _pcm16_peak(pcm: bytes) -> int:return max(max(samples), -min(samples))-def _is_public_knowledge_question(text: str) -> bool:- return bool(_PUBLIC_KNOWLEDGE_QUESTION_RE.search(str(text or "").strip()))--def _dictionary_corrected(text: str) -> str:"""The user's STT dictionary, applied to a realtime input transcript.@@ -595,6 +583,31 @@ _DELEGATE_DISCOURAGED_DIRECTIVE_HANDOFF = _handoff_variant(# follow-up. The bound only decides how long a result may wait for that silence._LATE_DELEGATE_DELIVERY_TIMEOUT_S = 30.0_LATE_DELEGATE_POLL_S = 0.15+# Let tasks that are only unwinding a readback verifier observe ``_ended``+# before process-scope retention. Real action work remains untouched after+# this tiny teardown-only grace and is transferred below.+_DELEGATE_END_SETTLE_S = 0.1+# Strong references for delegated work whose realtime transport has already+# gone away. The task itself retains the session-local delivery ledger and+# publishes the final result through AnnouncementRequested; a module-level+# owner prevents garbage collection from cancelling that user-visible debt.+_DETACHED_DELEGATE_TASKS: set[asyncio.Task[None]] = set()++_OUTPUT_LANGUAGE_FAILURE: dict[str, str] = {+ "de": "Ich konnte gerade keine sichere Antwort auf Deutsch erzeugen.", # i18n-allow+ "en": "I couldn't produce a safe answer in English just now.",+ "es": "No pude generar una respuesta segura en español ahora mismo.", # i18n-allow+}+_PUBLIC_FACT_UNCERTAINTY: dict[str, str] = {+ "de": ( # i18n-allow+ "Ich konnte das gerade nicht zuverlässig mit einer öffentlichen " # i18n-allow+ "Quelle prüfen." # i18n-allow+ ),+ "en": "I couldn't verify that reliably with a public source just now.",+ "es": ( # i18n-allow+ "No pude verificarlo de forma fiable con una fuente pública ahora mismo."+ ),+}# When a delegated Brain reply ends in a question (clarify or confirmation),# the user's short elliptical answer ("the readme one", "yes the second")# matches no planner category on its own. Only answers up to this token count@@ -1025,6 +1038,15 @@ class _DelegateTurnState:result_complete: bool = Falseresult_success: bool = Falsedeterministic: bool = False+ # Resolved output language captured when this turn is dispatched. The+ # session language may change while a slow action is running; completion+ # delivery must remain in the originating turn's language.+ language: str = ""+ delivery_id: str = ""+ delivery_completed: bool = False+ delivery_channel: str = ""+ requires_public_fact_grounding: bool = False+ public_fact_grounding_timeout_s: float = 0.0delivery_started: bool = Falseprovider_boundary_seen: bool = Falseprovider_stream_ended: bool = False@@ -1052,6 +1074,10 @@ class _DelegateTurnState:# rendered no readback in time; any late provider rendering of the same# reply is then withheld so the user never hears it twice.surface_fallback_spoken: bool = False+ # ``surface_fallback_spoken`` is the race-prevention claim made before the+ # async surface send. Only this separate flag proves that the send+ # completed successfully and therefore satisfies exactly-once delivery.+ surface_fallback_confirmed: bool = False# True while the delegate task lingers in the readback-verification# watchdog AFTER delivery. In that phase a pending delegate task no# longer holds provider turn boundaries.@@ -1078,6 +1104,7 @@ class _LateDelegateResult:text: strsuccess: boollanguage: str+ delivery_id: str_TOOL_ROLE_DIRECTIVE = (@@ -1697,6 +1724,11 @@ class RealtimeVoiceSession:self._response_requested_for_turn = Falseself._response_requested_input_ids: set[str] = set()self._active_provider_response_id = ""+ # Once the adapter demonstrates response identities, every subsequent+ # audio/transcript event must carry one. Accepting an untagged stale+ # transcript after tagged PCM would recreate the cross-response pairing+ # this guard is meant to prevent.+ self._provider_response_identity_required = Falseself._completed_provider_response_ids: deque[str] = deque(maxlen=_COMPLETED_RESPONSE_ID_MAX)@@ -1708,6 +1740,28 @@ class RealtimeVoiceSession:self._response_identity_drops = 0self._late_response_readoptions = 0self._unsafe_output_cancellations = 0+ self._active_requires_public_fact_grounding = bool(+ getattr(self._provider, "requires_public_fact_grounding", False)+ )+ self._public_fact_grounding_attempts = 0+ self._public_fact_grounding_successes = 0+ self._public_fact_grounding_failures = 0+ self._output_language_mismatches = 0+ self._output_language_retries = 0+ self._output_language_failures = 0+ self._output_language_retry_attempted_for_turn = False+ self._output_language_retry_pending = False+ self._output_language_retry_requested = False+ self._output_language_retry_task: asyncio.Task[None] | None = None+ # Stable per-turn delivery ledger. A provider injection is only+ # pending until real PCM is emitted; teardown may then atomically+ # transfer that debt to the pipeline completion channel.+ self._delegate_delivery_status: dict[str, str] = {}+ self._delegate_delivery_claims = 0+ self._delegate_deliveries_completed = 0+ self._delegate_delivery_recoveries = 0+ self._delegate_delivery_duplicates_suppressed = 0+ self._delegate_deliveries_detached = 0# True once the surface TTS spoke anything in THIS turn, so the turn is# answered and the no-audio rescue must not speak over it.self._surface_spoke_this_turn = False@@ -1835,11 +1889,21 @@ class RealtimeVoiceSession:parameters = inspect.signature(brain_planner).parametersexcept (TypeError, ValueError):parameters = {}- planned = (- brain_planner(text, context=context)- if "context" in parameters- else brain_planner(text)+ accepts_kwargs = any(+ parameter.kind is inspect.Parameter.VAR_KEYWORD+ for parameter in parameters.values())+ planner_kwargs: dict[str, Any] = {}+ if "context" in parameters or accepts_kwargs:+ planner_kwargs["context"] = context+ if (+ "requires_public_fact_grounding" in parameters+ or accepts_kwargs+ ):+ planner_kwargs["requires_public_fact_grounding"] = (+ self._active_requires_public_fact_grounding+ )+ planned = brain_planner(text, **planner_kwargs)if isinstance(planned, TurnPlan):return plannedexcept Exception: # noqa: BLE001 - local planner remains available@@ -1876,6 +1940,9 @@ class RealtimeVoiceSession:context=context,skill_index=self._skill_match_index(),workspace_names=self._workspace_call_signs(),+ requires_public_fact_grounding=(+ self._active_requires_public_fact_grounding+ ),)except Exception: # noqa: BLE001 — routing must never end a live call# Planning only chooses a route, and both routes can answer. The@@ -2415,6 +2482,10 @@ class RealtimeVoiceSession:self._provider = providerself._session = session+ self._reset_provider_response_identity_state()+ self._active_requires_public_fact_grounding = bool(+ getattr(provider, "requires_public_fact_grounding", False)+ )self._active_model = model# Captured at accept so every per-turn instruction rebuild keeps# the profile the accepted provider asked for.@@ -3095,6 +3166,28 @@ class RealtimeVoiceSession:input_item_id,)continue+ late_duplicate_without_id = bool(+ event.is_final+ and transcript+ and not input_item_id+ and self._response_requested_for_turn+ and (self._output_active or self._output_transcript)+ and _normalize_for_repeat_match(transcript)+ == _normalize_for_repeat_match(self._last_user_text)+ )+ if late_duplicate_without_id:+ # ChatGPT-Live can surface the same locally grounded+ # utterance again after its answer already started, but+ # without an input item id. Treat only an exact,+ # normalized repeat as the already-owned input; a+ # different final remains a genuine correction or a+ # later multipart fragment.+ log.info(+ "realtime[%s] ignored a late duplicate final "+ "without an item id while its response was in flight",+ self.session_id,+ )+ continueif input_observed:self._input_turn_observed = Trueself._user_speech_active = False@@ -3247,11 +3340,24 @@ class RealtimeVoiceSession:screen_context_turn = (TurnReason.SCREEN_CONTEXT in turn_plan.reasons)+ grounding_turn = bool(+ turn_plan.requires_public_fact_grounding+ )deterministic_delegate_available = callable(self._brain)+ if grounding_turn:+ # Grounding is fail-closed even when synthesis is+ # unavailable: the deterministic delegate emits a+ # localized uncertainty instead of letting the+ # native model invent the public fact.+ self._delegate_required_for_turn = Trueif (self._last_user_textand deterministic_delegate_available- and (self._delegate_enabled or screen_context_turn)+ and (+ self._delegate_enabled+ or screen_context_turn+ or grounding_turn+ )):self._delegate_required_for_turn = (self._delegate_required_for_turn@@ -3431,7 +3537,9 @@ class RealtimeVoiceSession:# This branch runs on a FINAL input transcript, so the# utterance is provably over — no boundary wait needed.self._start_deterministic_delegate(- self._last_user_text, input_final=True+ self._last_user_text,+ input_final=True,+ turn_plan=turn_plan,)if (event.is_final@@ -3563,9 +3671,18 @@ class RealtimeVoiceSession:response_id=str(getattr(event, "provider_turn_id", "") or ""),+ enforce_output_language=(+ self._output_language_validation_is_active()+ ),)if self._gate.hard_leak_pending():_actions = ", ".join(self._gate.hard_leak_actions())+ if "output_language_mismatch" in (+ self._gate.hard_leak_actions()+ ):+ await self._handle_output_language_mismatch()+ self._gate.drain()+ continueawait self._cancel_unsafe_output(reason=("unsafe output transcript (shadow recovery; "@@ -3605,12 +3722,21 @@ class RealtimeVoiceSession:response_id=str(getattr(event, "provider_turn_id", "") or ""),+ enforce_output_language=(+ self._output_language_validation_is_active()+ ),)if self._gate.hard_leak_pending():# Name the tripped detectors (safe metadata, never the# flagged content) so a false-positive abort is# diagnosable from the transcript alone (BUG-056)._actions = ", ".join(self._gate.hard_leak_actions())+ if "output_language_mismatch" in (+ self._gate.hard_leak_actions()+ ):+ await self._handle_output_language_mismatch()+ self._gate.drain()+ continueawait self._cancel_unsafe_output(reason=("unsafe output transcript"@@ -3747,12 +3873,12 @@ class RealtimeVoiceSession:trusted_reply = self._scrubbed_trusted_reply(delegate_state)- if trusted_reply:- delegate_state.surface_fallback_spoken = True- self._arm_stale_readback_guard(trusted_reply)await self._cancel_unsafe_output(reason="output transcript exceeded safe audio buffer",fallback_text=trusted_reply or None,+ delegate_state=(+ delegate_state if trusted_reply else None+ ),)elif event.type == "interrupted" and getattr(event, "self_initiated", False@@ -3823,6 +3949,19 @@ class RealtimeVoiceSession:await self._ensure_turn_started()await self._handle_tool_call(event)elif event.type == "turn_complete":+ if self._output_language_retry_pending:+ if not self._output_language_retry_requested:+ await self._request_output_language_retry()+ continue+ # The retry itself ended without one acceptable text+ # fragment. Do not ask again or release any PCM.+ self._output_language_retry_pending = False+ self._output_language_failures += 1+ await self._cancel_unsafe_output(+ reason="output language retry produced no safe output",+ interrupt_provider=False,+ fallback_text=self._output_language_failure_phrase(),+ )if self._pending_tool_events:self._cancel_tool_transcript_wait()pending = self._pending_tool_events@@ -4011,11 +4150,9 @@ class RealtimeVoiceSession:# and a very late provider rendering — arriving after# this turn closes — must stay inaudible until the# user opens the next turn.- delegate_state.surface_fallback_spoken = True- self._drop_provider_output_until_user_turn = True- self._arm_stale_readback_guard(fallback_text)- await self._send_json(- self._surface_speech_message(fallback_text)+ await self._send_delegate_surface_fallback(+ delegate_state,+ fallback_text,)final_chunks = self._gate.finalize(response_id=str(@@ -4044,16 +4181,13 @@ class RealtimeVoiceSession:trusted_reply = self._scrubbed_trusted_reply(delegate_state)- if trusted_reply:- delegate_state.surface_fallback_spoken = True- self._drop_provider_output_until_user_turn = (- True- )- self._arm_stale_readback_guard(trusted_reply)await self._cancel_unsafe_output(reason="output transcript missing at turn completion",interrupt_provider=False,fallback_text=trusted_reply or None,+ delegate_state=(+ delegate_state if trusted_reply else None+ ),)for chunk in final_chunks:await self._emit_audio(chunk)@@ -4585,7 +4719,8 @@ class RealtimeVoiceSession:raw = str(getattr(delegate_state, "last_reply", "") or "").strip()if not raw:return ""- return scrub_for_voice(raw, language=self._language).cleaned.strip()+ language = str(getattr(delegate_state, "language", "") or self._language)+ return scrub_for_voice(raw, language=language).cleaned.strip()def _advance_echo_horizon(self, duration_s: float) -> None:"""Date the echo guard's activity forward to the estimated drain.@@ -4635,7 +4770,12 @@ class RealtimeVoiceSession:words = len(cleaned.split())self._advance_echo_horizon(words * 0.4 + 1.0)- def _surface_speech_message(self, text: str) -> dict[str, Any]:+ def _surface_speech_message(+ self,+ text: str,+ *,+ language: str | None = None,+ ) -> dict[str, Any]:"""Build one ``error_spoken`` payload for the surface's classic TTS.The session's active realtime voice rides along as a hint so the@@ -4654,10 +4794,11 @@ class RealtimeVoiceSession:# exported transcript honest — so without this the rescue speaks the# same sentence a second time.self._surface_spoke_this_turn = True+ output_language = str(language or self._language)message: dict[str, Any] = {"type": "error_spoken","text": text,- "language": self._language,+ "language": output_language,# Which realtime engine this line belongs to. The desktop surface# resolves its realtime-scoped TTS from ambient state that is only# set once a handshake SUCCEEDED, so a notice about a handshake@@ -4671,12 +4812,219 @@ class RealtimeVoiceSession:message["voice"] = self._active_voicereturn message+ def _output_language_failure_phrase(self, language: str | None = None) -> str:+ output_language = str(language or self._language)+ return _OUTPUT_LANGUAGE_FAILURE.get(+ output_language,+ _OUTPUT_LANGUAGE_FAILURE["en"],+ )++ async def _send_delegate_surface_fallback(+ self,+ turn_state: _DelegateTurnState,+ text: str,+ ) -> bool:+ """Claim and confirm one surface delivery for an executed action.++ The pre-await claim prevents two live fallback paths from racing. It+ is deliberately not completion evidence: if the surface send fails,+ teardown may still recover the same result through the process-scoped+ announcement channel.+ """+ if not turn_state.delivery_id:+ turn_state.delivery_id = f"{self.session_id}:{self._turn_id or uuid4()}"+ delivery_id = turn_state.delivery_id+ status = self._delegate_delivery_status.get(delivery_id, "")+ if turn_state.delivery_completed or status in {+ "surface_pending",+ "detached_pending",+ "delivered",+ }:+ self._delegate_delivery_duplicates_suppressed += 1+ return False+ language = str(turn_state.language or self._language)+ turn_state.surface_fallback_spoken = True+ turn_state.surface_fallback_confirmed = False+ self._delegate_delivery_status[delivery_id] = "surface_pending"+ self._drop_provider_output_until_user_turn = True+ self._arm_stale_readback_guard(text)+ try:+ await self._send_json(+ self._surface_speech_message(text, language=language)+ )+ except Exception: # noqa: BLE001 - leave a recoverable delivery debt+ if self._delegate_delivery_status.get(delivery_id) == "surface_pending":+ self._delegate_delivery_status.pop(delivery_id, None)+ turn_state.surface_fallback_spoken = False+ self._drop_provider_output_until_user_turn = False+ log.warning(+ "realtime[%s] delegate surface fallback delivery failed",+ self.session_id,+ exc_info=True,+ )+ if turn_state.result_complete:+ await self._deliver_detached_delegate_result(+ self._turn_id or f"detached:{delivery_id}",+ turn_state,+ )+ return False+ turn_state.surface_fallback_confirmed = True+ self._mark_delegate_delivery_complete(turn_state, channel="surface")+ return True++ def _output_language_validation_is_active(self) -> bool:+ """Whether this output has a resolved turn language to enforce.++ In auto mode, the initial English fallback is only a bootstrap value;+ before any substantive user turn it is not evidence that an opening+ provider greeting must be English. Explicit pins, established calls,+ user-owned turns, and trusted external updates all have a real target+ and are validated fail-closed.+ """+ return bool(+ self._language_is_pinned+ or self._conversation_established+ or self._input_turn_observed+ or self._external_update is not None+ )++ async def _request_output_language_retry(self) -> None:+ """Request the one provider retry with the resolved language pinned."""+ if (+ self._output_language_retry_requested+ or self._ended+ or self._session is None+ or not self._turn_id+ ):+ return+ self._output_language_retry_requested = True+ task = self._output_language_retry_task+ if task is not None and task is not asyncio.current_task() and not task.done():+ task.cancel()+ self._output_language_retry_task = None+ language_name = _LANGUAGE_NAMES.get(+ self._language,+ "the conversation language",+ )+ try:+ await self._session.update_session(+ instructions=_session_instructions(+ self._language,+ input_language=self._input_language,+ provider=self.active_provider,+ model=self._active_model,+ language_is_pinned=True,+ tool_directive=self._tool_directive(+ delegate_required=False,+ delegate_discouraged=True,+ ),+ preferences=_preferences_block(self._config),+ workspace_directive=self._workspace_directive(),+ compact=getattr(self, "_compact_instructions", False),+ ),+ language=self._language,+ )+ if self._executed_tool_names:+ send_text = getattr(self._session, "send_text", None)+ if not callable(send_text):+ raise RuntimeError(+ "provider cannot retry an already-executed tool result"+ )+ await send_text(+ _direct_tool_result_retry_prompt(language=self._language)+ )+ else:+ try:+ await self._session.request_response(required_tool=None)+ except TypeError:+ await self._session.request_response()+ log.info(+ "realtime[%s] retrying one blocked output in %s",+ self.session_id,+ language_name,+ )+ except Exception: # noqa: BLE001 - retry failure gets a canned safe answer+ self._output_language_retry_pending = False+ self._output_language_failures += 1+ await self._cancel_unsafe_output(+ reason="output language retry failed",+ interrupt_provider=False,+ fallback_text=self._output_language_failure_phrase(),+ )++ async def _request_output_language_retry_after_grace(+ self,+ turn_id: str,+ ) -> None:+ try:+ await asyncio.sleep(_OUTPUT_LANGUAGE_RETRY_BOUNDARY_GRACE_S)+ if self._turn_id == turn_id and self._output_language_retry_pending:+ await self._request_output_language_retry()+ except asyncio.CancelledError:+ raise+ finally:+ if self._output_language_retry_task is asyncio.current_task():+ self._output_language_retry_task = None++ async def _handle_output_language_mismatch(self) -> None:+ """Suppress a gross mismatch, retry once, then fail locally."""+ self._output_language_mismatches += 1+ delegate_state = self._delegate_turns.get(self._turn_id)+ if delegate_state is not None and delegate_state.last_reply:+ trusted = self._scrubbed_trusted_reply(delegate_state)+ trusted_verdict = validate_output_language(+ trusted,+ resolved_language=self._language,+ )+ if trusted and not trusted_verdict.should_block:+ await self._cancel_unsafe_output(+ reason="provider changed a trusted result's language",+ fallback_text=trusted,+ delegate_state=delegate_state,+ )+ return++ if not self._output_language_retry_attempted_for_turn:+ self._output_language_retry_attempted_for_turn = True+ self._output_language_retry_pending = True+ self._output_language_retry_requested = False+ self._output_language_retries += 1+ self._retire_active_provider_response()+ self._gate.drain()+ self._output_transcript.clear()+ self._provider_output_probe = ""+ self._output_active = False+ self._output_samples_sent = 0+ self._reset_echo_horizon()+ try:+ await self._send_json({"type": "tts_cancel"})+ except Exception: # noqa: BLE001, S110 - surface may be gone+ pass+ try:+ if self._session is not None:+ await self._session.interrupt()+ except Exception: # noqa: BLE001, S110 - boundary timer still retries+ pass+ self._output_language_retry_task = asyncio.create_task(+ self._request_output_language_retry_after_grace(self._turn_id),+ name=f"rt-language-retry-{self.session_id}",+ )+ return++ self._output_language_retry_pending = False+ self._output_language_failures += 1+ await self._cancel_unsafe_output(+ reason="provider output language mismatched after one retry",+ fallback_text=self._output_language_failure_phrase(),+ )+async def _cancel_unsafe_output(self,*,reason: str,interrupt_provider: bool = True,fallback_text: str | None = None,+ delegate_state: _DelegateTurnState | None = None,) -> None:"""Cancel one unsafe provider response and emit one honest fallback."""if self._scrub_cancelled_for_turn:@@ -4732,7 +5080,15 @@ class RealtimeVoiceSession:self._output_transcript.clear()self._output_transcript.append(spoken_fallback)try:- await self._send_json(self._surface_speech_message(spoken_fallback))+ if delegate_state is not None:+ await self._send_delegate_surface_fallback(+ delegate_state,+ spoken_fallback,+ )+ else:+ await self._send_json(+ self._surface_speech_message(spoken_fallback)+ )except Exception: # noqa: BLE001, S110 — surface may already be gonepass# Keep the transcript honest (BUG-056): the 15:13 session recorded a@@ -5086,6 +5442,20 @@ class RealtimeVoiceSession:response_id = str(getattr(event, "provider_turn_id", "") or "").strip()active_id = self._active_provider_response_idself._expire_provisional_retirements()+ if response_id:+ self._provider_response_identity_required = True+ elif (+ event.type != "turn_complete"+ and self._provider_response_identity_required+ ):+ self._response_identity_drops += 1+ log.warning(+ "realtime[%s] dropped an untagged %s event after the provider "+ "began emitting response identities",+ self.session_id,+ event.type,+ )+ return Falseif response_id and response_id in self._completed_provider_response_ids:self._response_identity_drops += 1log.warning(@@ -5114,6 +5484,12 @@ class RealtimeVoiceSession:self._active_provider_response_id = ""return True+ if self._output_language_retry_requested:+ # The retry has begun producing. Its transcript still has to pass+ # the same deterministic gate, but an older terminal boundary can+ # no longer be mistaken for the retry's completion.+ self._output_language_retry_pending = False+if not response_id:return Trueif not active_id:@@ -5167,6 +5543,20 @@ class RealtimeVoiceSession:self._drop_provider_output_until_new_response = drop_before_cancelreturn False+ def _reset_provider_response_identity_state(self) -> None:+ """Retire response identities that belonged to the previous transport.++ Response ids and the decision to require them are adapter-session+ scoped. A rebuilt transport may restart its id sequence or fall back to+ an ordered stream without ids; carrying either ledger across that+ boundary would discard the fresh transport's first answer as stale.+ Diagnostic counters remain session-wide and are deliberately retained.+ """+ self._active_provider_response_id = ""+ self._provider_response_identity_required = False+ self._completed_provider_response_ids.clear()+ self._provisional_response_retirements.clear()+def _retire_active_provider_response(self, *, provisional: bool = False) -> None:"""Remember the active response id as closed and clear its owner.@@ -5221,6 +5611,17 @@ class RealtimeVoiceSession:if response_id not in self._completed_provider_response_ids:self._completed_provider_response_ids.append(response_id)+ def _expire_provisional_retirements(self) -> None:+ """Complete provisional retirements whose re-adoption window ran out."""+ now = time.monotonic()+ for response_id, deadline in tuple(+ self._provisional_response_retirements.items()+ ):+ if now < deadline:+ continue+ del self._provisional_response_retirements[response_id]+ if response_id not in self._completed_provider_response_ids:+ self._completed_provider_response_ids.append(response_id)def _latency_detail(self, detail: str = "") -> str:fields = [@@ -5873,6 +6274,10 @@ class RealtimeVoiceSession:# it from surviving into the next unit of work and aborting a fresh# answer (AP-19 / BUG-032).self._cancel_turn_stall_watchdog()+ retry_task = self._output_language_retry_task+ self._output_language_retry_task = None+ if retry_task is not None and not retry_task.done():+ retry_task.cancel()self._turn_id = ""self._turn_trace_id = Noneself._latency_tracker = None@@ -5891,6 +6296,9 @@ class RealtimeVoiceSession:self._handoff_action_seen_for_turn = Falseself._deferred_provider_speech_start = Falseself._scrub_cancelled_for_turn = False+ self._output_language_retry_attempted_for_turn = False+ self._output_language_retry_pending = False+ self._output_language_retry_requested = Falseself._embedded_silence_ms = 0.0def _declared_tools(self) -> tuple[dict[str, Any], ...]:@@ -5983,9 +6391,19 @@ class RealtimeVoiceSession:return not (state is not None and state.bridge_delivery_started)def _delegate_surface_fallback_spoken(self) -> bool:- """True once the surface already spoke this turn's trusted reply."""+ """True while a non-provider channel owns this turn's delivery."""state = self._delegate_turns.get(self._turn_id)- return bool(state is not None and state.surface_fallback_spoken)+ if state is None:+ return False+ status = self._delegate_delivery_status.get(state.delivery_id, "")+ return bool(+ state.surface_fallback_spoken+ or status in {"surface_pending", "detached_pending"}+ or (+ state.delivery_completed+ and state.delivery_channel in {"surface", "detached"}+ )+ )def _arm_stale_readback_guard(self, reply: str) -> None:"""Remember one surface-delivered delegate reply for repeat detection.@@ -6047,7 +6465,7 @@ class RealtimeVoiceSession:if self._must_withhold_delegate_output():return "a delegated action owns this turn"if self._delegate_surface_fallback_spoken():- return "the surface already spoke this turn's reply"+ return "a non-provider channel already owns this turn's reply"return ""def _note_output_withheld(self, kind: str) -> None:@@ -6085,6 +6503,122 @@ class RealtimeVoiceSession:task.add_done_callback(_discard)+ def _retain_detached_delegate_task(+ self,+ turn_id: str,+ task: asyncio.Task[None],+ ) -> None:+ """Transfer an unfinished delegate from the socket to process scope."""+ if task.done() or task in _DETACHED_DELEGATE_TASKS:+ return+ _DETACHED_DELEGATE_TASKS.add(task)+ delivery_id = f"{self.session_id}:{turn_id}"+ if self._delegate_delivery_status.get(delivery_id) != "running_detached":+ self._delegate_delivery_status[delivery_id] = "running_detached"+ self._delegate_deliveries_detached += 1++ def _reap(done: asyncio.Task[None]) -> None:+ _DETACHED_DELEGATE_TASKS.discard(done)+ if done.cancelled():+ log.warning(+ "realtime[%s] detached delegate was cancelled",+ self.session_id,+ )+ return+ try:+ error = done.exception()+ except asyncio.CancelledError:+ return+ if error is not None:+ log.warning(+ "realtime[%s] detached delegate failed",+ self.session_id,+ exc_info=(type(error), error, error.__traceback__),+ )++ task.add_done_callback(_reap)++ def _mark_delegate_delivery_complete(+ self,+ turn_state: _DelegateTurnState,+ *,+ channel: str = "",+ ) -> None:+ delivery_id = turn_state.delivery_id+ if not delivery_id or turn_state.delivery_completed:+ return+ turn_state.delivery_completed = True+ if channel:+ turn_state.delivery_channel = channel+ self._delegate_delivery_status[delivery_id] = "delivered"+ self._delegate_deliveries_completed += 1++ async def _deliver_detached_delegate_result(+ self,+ turn_id: str,+ turn_state: _DelegateTurnState,+ ) -> bool:+ """Publish one completed result after its realtime socket is gone."""+ if turn_state.surface_fallback_confirmed:+ self._mark_delegate_delivery_complete(turn_state, channel="surface")+ return True+ if not turn_state.delivery_id:+ turn_state.delivery_id = f"{self.session_id}:{turn_id}"+ delivery_id = turn_state.delivery_id+ status = self._delegate_delivery_status.get(delivery_id, "")+ if status == "surface_pending":+ # The live surface send owns delivery until it either confirms or+ # releases the claim on failure. Its task is retained across+ # teardown and performs detached recovery in the latter case.+ return False+ if turn_state.delivery_completed or status in {"detached_pending", "delivered"}:+ self._delegate_delivery_duplicates_suppressed += 1+ return False+ text = self._scrubbed_trusted_reply(turn_state)+ if not text:+ return False+ language = str(turn_state.language or self._language)+ verdict = validate_output_language(+ text,+ resolved_language=language,+ )+ if verdict.should_block:+ self._output_language_mismatches += 1+ self._output_language_failures += 1+ text = self._output_language_failure_phrase(language)+ if self._bus is None:+ log.warning(+ "realtime[%s] completed delegate result has no delivery bus",+ self.session_id,+ )+ return False+ self._delegate_delivery_status[delivery_id] = "detached_pending"+ self._delegate_delivery_claims += 1+ self._delegate_delivery_recoveries += 1+ try:+ from jarvis.core.events import AnnouncementRequested++ await self._bus.publish(+ AnnouncementRequested(+ source_layer="realtime.delegate",+ text=text,+ priority="normal",+ language=language,+ kind="completion",+ detail=f"delivery_id={delivery_id}",+ )+ )+ except Exception: # noqa: BLE001 - retain the debt for diagnosis+ self._delegate_delivery_status.pop(delivery_id, None)+ log.warning(+ "realtime[%s] detached delegate delivery failed",+ self.session_id,+ exc_info=True,+ )+ return False+ self._mark_delegate_delivery_complete(turn_state, channel="detached")+ return True+def _turn_has_pending_delegate(self, turn_id: str) -> bool:return any(not task.done()@@ -6228,12 +6762,15 @@ class RealtimeVoiceSession:reply = str(turn_state.last_reply or "").strip()if not reply or self._ended or turn_state.delivery_started:return+ if not turn_state.delivery_id:+ turn_state.delivery_id = f"{self.session_id}:late:{uuid4()}"turn_state.delivery_started = Trueself._late_delegate_results.append(_LateDelegateResult(text=reply,success=turn_state.result_success,- language=self._language,+ language=str(turn_state.language or self._language),+ delivery_id=turn_state.delivery_id,))log.info(@@ -6398,8 +6935,8 @@ class RealtimeVoiceSession:not self._delegate_required_for_turnand not local_plan.requires_orchestratorand not provider_plan.requires_orchestrator- and _is_public_knowledge_question(self._last_user_text)- and _is_public_knowledge_question(+ and is_public_fact_question(self._last_user_text)+ and is_public_fact_question(provider_request or self._last_user_text)):@@ -6564,7 +7101,11 @@ class RealtimeVoiceSession:)def _start_deterministic_delegate(- self, user_text: str, *, input_final: bool = False+ self,+ user_text: str,+ *,+ input_final: bool = False,+ turn_plan: TurnPlan | None = None,) -> None:"""Start one orchestrator-owned Brain turn for local-evidence input.@@ -6580,9 +7121,18 @@ class RealtimeVoiceSession:turn_id,_DelegateTurnState(deterministic=True),)+ if not turn_state.delivery_id:+ turn_state.delivery_id = f"{self.session_id}:{turn_id}"+ if not turn_state.language:+ turn_state.language = self._languageturn_state.deterministic = Trueturn_state.input_final = turn_state.input_final or bool(input_final)turn_state.user_text = str(user_text or "").strip()+ if turn_plan is not None and turn_plan.requires_public_fact_grounding:+ turn_state.requires_public_fact_grounding = True+ turn_state.public_fact_grounding_timeout_s = float(+ turn_plan.public_fact_grounding_timeout_s or 2.5+ )if turn_state.dispatch_started or turn_state.result_complete:returnturn_state.dispatch_started = True@@ -6909,11 +7459,174 @@ class RealtimeVoiceSession:)return+ async def _speak_public_fact_ack(+ self,+ query: str,+ *,+ language: str,+ ) -> None:+ """Give immediate deterministic feedback before the bounded lookup."""+ try:+ from jarvis.brain.ack_generator import generate_ack++ spoken = generate_ack(+ "search_web",+ {"query": query},+ language=language,+ )+ except Exception: # noqa: BLE001 - the search itself still proceeds+ spoken = None+ if not spoken:+ return+ try:+ await self._send_json(+ self._surface_speech_message(spoken, language=language)+ )+ await self._publish_delegate_bridge_spoken(spoken)+ except Exception: # noqa: BLE001 - feedback is best-effort, grounding is not+ log.debug(+ "realtime[%s] public-fact acknowledgement failed",+ self.session_id,+ exc_info=True,+ )++ @staticmethod+ def _grounding_output_has_evidence(output: Any) -> bool:+ """Accept only a non-empty public-search result set as evidence."""+ if not isinstance(output, dict):+ return False+ results = output.get("results")+ return bool(+ str(output.get("status", "ok") or "").strip().lower() == "ok"+ and isinstance(results, list)+ and any(isinstance(item, dict) and item for item in results)+ )++ async def _ground_public_fact(+ self,+ query: str,+ *,+ timeout_s: float,+ language: str,+ ) -> tuple[str, bool]:+ """Execute exactly one bounded search, then synthesize without tools."""+ uncertainty = _PUBLIC_FACT_UNCERTAINTY.get(+ language,+ _PUBLIC_FACT_UNCERTAINTY["en"],+ )+ await self._speak_public_fact_ack(query, language=language)+ try:+ from jarvis.core import runtime_refs+ from jarvis.core.protocols import SupervisorToolRequest++ gateway = runtime_refs.get_supervisor_tool_gateway()+ descriptor_names = {+ str(item.name)+ for item in (gateway.catalog() if gateway is not None else ())+ }+ if gateway is None or "search_web" not in descriptor_names:+ self._public_fact_grounding_failures += 1+ return uncertainty, False+ self._public_fact_grounding_attempts += 1+ result = await asyncio.wait_for(+ gateway.execute(+ "search_web",+ {"query": query, "max_results": 5},+ SupervisorToolRequest(+ trace_id=self._turn_trace_id or uuid4(),+ origin="realtime_grounding",+ user_utterance=query,+ rationale=(+ "The active realtime model requires public-fact "+ "grounding before answering."+ ),+ config_snapshot={+ "output_language": language,+ "voice_confirm": True,+ },+ ),+ ),+ timeout=max(0.05, float(timeout_s or 2.5)),+ )+ except TimeoutError:+ self._public_fact_grounding_failures += 1+ return uncertainty, False+ except asyncio.CancelledError:+ raise+ except Exception: # noqa: BLE001 - honest degradation, never native guess+ log.warning(+ "realtime[%s] public-fact grounding failed safely",+ self.session_id,+ exc_info=True,+ )+ self._public_fact_grounding_failures += 1+ return uncertainty, False++ output = getattr(result, "output", None)+ if not bool(getattr(result, "success", False)) or not (+ self._grounding_output_has_evidence(output)+ ):+ self._public_fact_grounding_failures += 1+ return uncertainty, False++ run_task = getattr(self._brain, "run_task", None)+ if not callable(run_task):+ self._public_fact_grounding_failures += 1+ return uncertainty, False+ evidence = json.dumps(output, ensure_ascii=False, default=str)[:8_000]+ language_name = _LANGUAGE_NAMES.get(+ language,+ "the resolved conversation language",+ )+ prompt = (+ "Answer the user's question using only the supplied public-search "+ "evidence. Do not call tools and do not add facts absent from the "+ f"evidence. Reply concisely in {language_name}. If the evidence "+ "does not answer the question, say that honestly.\n\n"+ f"User question: {query}\n\nEvidence:\n{evidence}"+ )+ try:+ reply = str(+ await asyncio.wait_for(+ run_task(+ prompt=prompt,+ allowed_tools=(),+ model_tier="fast",+ trace_id=self._turn_trace_id,+ ),+ timeout=_DELEGATE_TIMEOUT_S,+ )+ or ""+ ).strip()+ except asyncio.CancelledError:+ raise+ except Exception: # noqa: BLE001 - evidence exists but synthesis did not+ log.warning(+ "realtime[%s] grounded public-fact synthesis failed",+ self.session_id,+ exc_info=True,+ )+ self._public_fact_grounding_failures += 1+ return uncertainty, False+ verdict = validate_output_language(+ reply,+ resolved_language=language,+ )+ if not reply or verdict.should_block:+ if verdict.should_block:+ self._output_language_mismatches += 1+ self._output_language_failures += 1+ self._public_fact_grounding_failures += 1+ return uncertainty, False+ self._public_fact_grounding_successes += 1+ return reply, True+async def _run_deterministic_delegate(self,turn_id: str,turn_state: _DelegateTurnState,) -> None:+ turn_language = str(turn_state.language or self._language)try:if bool(getattr(self._session, "creates_responses_automatically", False)@@ -6952,33 +7665,50 @@ class RealtimeVoiceSession:if not self._delegate_turn_is_active(turn_id, turn_state):returnuser_text = turn_state.user_text- reply = (- await asyncio.wait_for(- self._dispatch_brain_turn(user_text),- timeout=_DELEGATE_TIMEOUT_S,+ if turn_state.requires_public_fact_grounding:+ reply, succeeded = await self._ground_public_fact(+ user_text,+ timeout_s=turn_state.public_fact_grounding_timeout_s,+ language=turn_language,)- or ""- ).strip()- brain_chain_failed = bool(- getattr(self._brain, "_last_turn_all_failed", False)- )- if reply and not brain_chain_failed:turn_state.last_reply = reply- result: dict[str, Any] = {- "success": True,+ result = {+ "success": succeeded,"spoken_reply": reply,}- succeeded = True+ if not succeeded:+ result["error"] = "Public fact grounding was unavailable."else:- result = {- "success": False,- "error": (- "No configured Tool Model completed the delegated turn."- if brain_chain_failed- else "The delegated action returned no grounded result."- ),- }- succeeded = False+ reply = (+ await asyncio.wait_for(+ self._dispatch_brain_turn(+ user_text,+ output_language=turn_language,+ ),+ timeout=_DELEGATE_TIMEOUT_S,+ )+ or ""+ ).strip()+ brain_chain_failed = bool(+ getattr(self._brain, "_last_turn_all_failed", False)+ )+ if reply and not brain_chain_failed:+ turn_state.last_reply = reply+ result = {+ "success": True,+ "spoken_reply": reply,+ }+ succeeded = True+ else:+ result = {+ "success": False,+ "error": (+ "No configured Tool Model completed the delegated turn."+ if brain_chain_failed+ else "The delegated action returned no grounded result."+ ),+ }+ succeeded = Falseexcept TimeoutError:result = {"success": False,@@ -7004,11 +7734,11 @@ class RealtimeVoiceSession:}succeeded = False- if not succeeded:+ if not succeeded and not turn_state.requires_public_fact_grounding:from jarvis.voice.action_phrases import action_phraseturn_state.last_reply = action_phrase(- "action_failed_generic", self._language+ "action_failed_generic", turn_language)result["spoken_reply"] = turn_state.last_replyturn_state.result_complete = True@@ -7023,6 +7753,10 @@ class RealtimeVoiceSession:if self._delegate_turn_is_active(turn_id, turn_state) and succeeded:self._executed_tool_names.add(str(_DELEGATE_DECLARATION["name"]))if self._ended or self._session is None:+ await self._deliver_detached_delegate_result(+ turn_id,+ turn_state,+ )returnif self._suppress_repeated_outage_notice(turn_state):if not bool(@@ -7054,7 +7788,7 @@ class RealtimeVoiceSession:trusted_reply = action_phrase("cu_done" if succeeded else "action_failed_generic",- self._language,+ turn_language,)# From this point onward every speech and persistence fallback must use# the regex-scrubbed value (ADR-0010). The raw Brain answer must never@@ -7068,10 +7802,10 @@ class RealtimeVoiceSession:self._drop_provider_output_until_new_response = Falsetry:if turn_state.provider_stream_ended:- turn_state.surface_fallback_spoken = True- self._drop_provider_output_until_user_turn = True- self._arm_stale_readback_guard(trusted_reply)- await self._send_json(self._surface_speech_message(trusted_reply))+ await self._send_delegate_surface_fallback(+ turn_state,+ trusted_reply,+ )returnif turn_state.pending_tool_calls and not self._session_takes_tool_results():# Should be unreachable (a transport with no native tools can@@ -7112,7 +7846,7 @@ class RealtimeVoiceSession:await self._session.send_text(_delegate_result_prompt(trusted_reply,- language=self._language,+ language=turn_language,success=succeeded,))@@ -7124,8 +7858,9 @@ class RealtimeVoiceSession:self.session_id,exc_info=True,)- await self._send_json(- self._surface_speech_message(turn_state.last_reply)+ await self._send_delegate_surface_fallback(+ turn_state,+ turn_state.last_reply,)returnawait self._verify_delegate_readback(turn_id, turn_state)@@ -7182,9 +7917,6 @@ class RealtimeVoiceSession:# then a third time when the provider rendered it late).if not reply or turn_state.surface_fallback_spoken:return- turn_state.surface_fallback_spoken = True- self._drop_provider_output_until_user_turn = True- self._arm_stale_readback_guard(reply)log.warning("realtime[%s] provider rendered no readback for a delivered ""delegate result within %.1fs; speaking it through the "@@ -7192,7 +7924,7 @@ class RealtimeVoiceSession:self.session_id,self._delegate_readback_budget_s(),)- await self._send_json(self._surface_speech_message(reply))+ await self._send_delegate_surface_fallback(turn_state, reply)def _delegate_readback_budget_s(self) -> float:"""How long a delivered delegate result may wait for provider audio.@@ -7217,6 +7949,10 @@ class RealtimeVoiceSession:turn_state: _DelegateTurnState,) -> None:"""Start the single Brain dispatch owned by one realtime turn."""+ if not turn_state.delivery_id:+ turn_state.delivery_id = f"{self.session_id}:{turn_id}"+ if not turn_state.language:+ turn_state.language = self._languageif turn_state.dispatch_started or turn_state.result_complete:returnturn_state.dispatch_started = True@@ -7239,11 +7975,15 @@ class RealtimeVoiceSession:turn_id: str,turn_state: _DelegateTurnState,) -> None:+ turn_language = str(turn_state.language or self._language)succeeded = Falsetry:reply = (await asyncio.wait_for(- self._dispatch_brain_turn(turn_state.user_text),+ self._dispatch_brain_turn(+ turn_state.user_text,+ output_language=turn_language,+ ),timeout=_DELEGATE_TIMEOUT_S,)or ""@@ -7294,7 +8034,7 @@ class RealtimeVoiceSession:from jarvis.voice.action_phrases import action_phraseturn_state.last_reply = action_phrase(- "action_failed_generic", self._language+ "action_failed_generic", turn_language)result["spoken_reply"] = turn_state.last_replyturn_state.result_complete = True@@ -7307,6 +8047,10 @@ class RealtimeVoiceSession:detail=f"kind=provider_requested;success={succeeded}",)if self._ended or self._session is None:+ await self._deliver_detached_delegate_result(+ turn_id,+ turn_state,+ )returnif not self._delegate_turn_is_active(turn_id, turn_state):# The provider's function call belongs to a response that no longer@@ -7335,7 +8079,12 @@ class RealtimeVoiceSession:returnawait self._verify_delegate_readback(turn_id, turn_state)- async def _dispatch_brain_turn(self, text: str) -> str:+ async def _dispatch_brain_turn(+ self,+ text: str,+ *,+ output_language: str | None = None,+ ) -> str:# allow_voice_confirm=True is load-bearing: without it an ask-tier# tool blocks on a UI approval no voice user can give (the classic# pipeline passes the same flag). prefer_tool_model routes the@@ -7344,6 +8093,7 @@ class RealtimeVoiceSession:# the one response that was actually spoken.generate = getattr(self._brain, "generate", None)if callable(generate):+ turn_language = str(output_language or self._language)desired_kwargs: dict[str, Any] = {"allow_voice_confirm": True,"prefer_tool_model": True,@@ -7363,7 +8113,7 @@ class RealtimeVoiceSession:# 2026-07-23: an English conversation whose memory-save turns# were spoken in German). Unsupported by older managers -> the# signature filter below simply drops it.- "force_output_language": self._language,+ "force_output_language": turn_language,}try:signature = inspect.signature(generate)@@ -7465,6 +8215,9 @@ class RealtimeVoiceSession:self._tool_transcript_task = Noneasync def _emit_audio(self, chunk: Any) -> None:+ if self._ended:+ self._note_output_withheld("audio after session end")+ returnif self._must_withhold_provider_output():self._note_output_withheld("audio")return@@ -7530,6 +8283,13 @@ class RealtimeVoiceSession:# horizon by this chunk's duration (BUG-089).self._advance_echo_horizon((len(pcm) / 2) / rate)await self._send_binary(pcm)+ if audible:+ delegate_state = self._delegate_turns.get(self._turn_id)+ if delegate_state is not None and delegate_state.delivery_started:+ self._mark_delegate_delivery_complete(+ delegate_state,+ channel="provider_audio",+ )def _note_audio_flow(self, pcm: bytes, chunk: Any) -> None:"""Attribute audible mid-reply holes to their actual producer.@@ -7611,6 +8371,7 @@ class RealtimeVoiceSession:if reply_to_cut:self._drop_provider_output_until_new_response = Trueself._gate.drain()+ self._retire_active_provider_response()self._response_requested_for_turn = Falseoutput_rate = int(getattr(self._provider, "output_sample_rate", 24_000) or 24_000)audio_end_ms = (@@ -7751,6 +8512,27 @@ class RealtimeVoiceSession:response_identity_drops=self._response_identity_drops,late_response_readoptions=self._late_response_readoptions,unsafe_output_cancellations=self._unsafe_output_cancellations,+ public_fact_grounding_attempts=(+ self._public_fact_grounding_attempts+ ),+ public_fact_grounding_successes=(+ self._public_fact_grounding_successes+ ),+ public_fact_grounding_failures=(+ self._public_fact_grounding_failures+ ),+ output_language_mismatches=self._output_language_mismatches,+ output_language_retries=self._output_language_retries,+ output_language_failures=self._output_language_failures,+ delegate_delivery_claims=self._delegate_delivery_claims,+ delegate_deliveries_completed=(+ self._delegate_deliveries_completed+ ),+ delegate_delivery_recoveries=self._delegate_delivery_recoveries,+ delegate_delivery_duplicates_suppressed=(+ self._delegate_delivery_duplicates_suppressed+ ),+ delegate_deliveries_detached=self._delegate_deliveries_detached,opening_responses_bounded=diag.get("opening_responses_bounded", 0),self_dialogue_rebuilds=diag.get("self_dialogue_rebuilds", 0),handoff_action_turns=self._handoff_action_turns,@@ -7777,31 +8559,52 @@ class RealtimeVoiceSession:if self._ended:returnself._ended = True+ # Teardown claims any undelivered action result through the announcement+ # channel below. First make provider readback physically incapable of+ # racing that claim: withhold, drain buffered PCM, and signal the pump+ # before the first teardown await.+ self._drop_provider_output_until_new_response = True+ self._drop_provider_output_until_user_turn = True+ self._gate.drain()+ pump = self._pump_task+ if pump is not None and not pump.done():+ pump.cancel()self._loop_lag.stop()self._cancel_turn_stall_watchdog()self._cancel_tool_transcript_wait()if self._end_call_timer is not None and not self._end_call_timer.done():self._end_call_timer.cancel()self._end_call_timer = None+ if self._delegate_tasks:+ await asyncio.wait(+ tuple(self._delegate_tasks),+ timeout=_DELEGATE_END_SETTLE_S,+ )for turn_id, tasks in tuple(self._delegate_tasks_by_turn.items()):- if not any(not task.done() for task in tasks):- continue- # The cancel below kills the in-flight brain turn: the user hung- # up before its answer existed, and nothing will ever speak it- # (live forensic 2026-07-17 09:23: a hangup 31 s into a delegated- # answer discarded it without a trace). Name the lost request so- # the loss is diagnosable from the log.state = self._delegate_turns.get(turn_id)+ if state is not None and state.result_complete:+ # The action has already run. Claim its result before the+ # socket is closed; the delivery ledger suppresses the task's+ # own teardown branch if both paths race here.+ await self._deliver_detached_delegate_result(turn_id, state)+ unfinished = tuple(task for task in tasks if not task.done())+ if not unfinished:+ continue+ # A socket lifetime is not an action lifetime. Once dispatch has+ # started, cancelling it on hangup can leave an external side+ # effect complete while erasing its only result (and a retry can+ # then execute that effect twice). Transfer ownership to process+ # scope; the task publishes one completion announcement when it+ # finishes and never re-dispatches the action.+ for task in unfinished:+ self._retain_detached_delegate_task(turn_id, task)request = str(getattr(state, "user_text", "") or "")- log.warning(+ log.info("realtime[%s] session ended while a delegated action was "- "still running; its answer was never produced: %s",+ "still running; retaining it for exactly-once delivery: %s",self.session_id,safe_preview(request, max_chars=200) or "<unknown request>",)- for task in tuple(self._delegate_tasks):- if not task.done():- task.cancel()self._delegate_tasks.clear()self._delegate_tasks_by_turn.clear()if (@@ -7816,15 +8619,21 @@ class RealtimeVoiceSession:):self._late_delegate_flush_task.cancel()self._late_delegate_flush_task = None- for lost in self._late_delegate_results:- # The action ran; the session ended before its result could be said.- log.warning(- "realtime[%s] session ended with an unspoken action result: %s",- self.session_id,- safe_preview(lost.text, max_chars=200),+ for pending in tuple(self._late_delegate_results):+ # The provider follow-up never became audible before teardown.+ # Move the already-executed result to the same exactly-once+ # completion channel as a delegate that finishes after hangup.+ await self._deliver_detached_delegate_result(+ f"late:{pending.delivery_id}",+ _DelegateTurnState(+ last_reply=pending.text,+ result_complete=True,+ result_success=pending.success,+ language=pending.language,+ delivery_id=pending.delivery_id,+ ),)self._late_delegate_results.clear()- pump = self._pump_taskif pump is not None and not pump.done():# A single cancel() can be LOST to an asyncio race (BUG-081): when# cancel() lands while the pump's current waiter future is alreadydiff --git a/jarvis/ui/web/provider_spec.py b/jarvis/ui/web/provider_spec.pyindex 66b390480c..923e30d4d0 100644--- a/jarvis/ui/web/provider_spec.py+++ b/jarvis/ui/web/provider_spec.py@@ -105,12 +105,6 @@ class ProviderSpec:# shows a clear badge and fallback note, while runtime selection remains# capability-driven. This is presentation only and never gates behavior.experimental: bool = False- # The provider/model class cannot be trusted to answer concrete public- # facts from unaided recall. The shared turn planner uses this capability- # to require one bounded search_web evidence attempt. Consumers branch on- # this field, never on a provider id; hosted evergreen turns keep the- # default False fast path.- requires_public_fact_grounding: bool = Falsedef provider_billing(spec: ProviderSpec) -> Billing:@@ -515,7 +509,6 @@ PROVIDERS: tuple[ProviderSpec, ...] = (signup_url="https://ollama.com/download",supports_base_url=True,default_base_url="http://localhost:11434",- requires_public_fact_grounding=True,credential_help=("Runs models fully local through an Ollama server — no API key, ""no cloud account, nothing leaves this machine. Install Ollama, "@@ -541,7 +534,6 @@ PROVIDERS: tuple[ProviderSpec, ...] = ("The API key is optional; most local servers ignore it."),supports_base_url=True,- requires_public_fact_grounding=True,),# ── TTS ───────────────────────────────────────────────────────────────# Voice-Output cards render in this tuple order. OpenRouter leads (one key@@ -817,7 +809,6 @@ PROVIDERS: tuple[ProviderSpec, ...] = (dashboard_url=None,signup_url="https://platform.openai.com/docs/guides/realtime",supports_base_url=True,- requires_public_fact_grounding=True,credential_help=("Fully local voice calls, no cloud account. Easiest path: the ""install panel below checks this machine (12 GB of GPU/unified "diff --git a/scripts/realtime_reliability_gate.py b/scripts/realtime_reliability_gate.pynew file mode 100644index 0000000000..de77f24a91--- /dev/null+++ b/scripts/realtime_reliability_gate.py@@ -0,0 +1,1182 @@+"""Release gate for realtime reliability and measured latency.++Two deliberately separate checks live here:++* ``--contract-soak`` drives the production ``RealtimeVoiceSession`` through+ an in-memory provider. It proves provider-neutral lifecycle, barge-in,+ failback, and exactly-once PCM surface handoff without a microphone, network,+ account, or model.+* ``--report`` validates the schema and numerical thresholds of a report+ labelled as an instrumented local-inference target. Contract-mode output is+ schema-separated; authenticity still requires workflow-owned collection.++Physical microphone/acoustic-echo checks and macOS TCC permission prompts are+manual release sign-offs. Neither mode claims to automate them.+"""++from __future__ import annotations++import argparse+import asyncio+import hashlib+import json+import logging+import math+import re+import sys+import time+from collections.abc import Mapping, Sequence+from dataclasses import dataclass+from datetime import UTC, datetime+from pathlib import Path+from types import SimpleNamespace+from typing import Any+from uuid import UUID++SCHEMA_VERSION = 2+MIN_WARM_CONNECTS = 100+MIN_TURNS = 500+MIN_BARGE_SAMPLES = 20+MIN_FAILBACK_SAMPLES = 20+MIN_REGRESSION_SAMPLES = 50++TTFA_P50_LIMIT_MS = 800.0+TTFA_P95_LIMIT_MS = 1_200.0+BARGE_STOP_P95_LIMIT_MS = 250.0+FAILBACK_MAX_LIMIT_MS = 2_000.0+UNAFFECTED_REGRESSION_MAX_MS = 50.0++CANONICAL_TTFA_FIELD = "first_final_to_first_audio_ms"+CANONICAL_COLLECTOR = "jarvis-realtime-target-collector"+CANONICAL_COLLECTOR_VERSION = 1+CANONICAL_EVENT_SOURCE = "RealtimeSessionPostmortem.first_final_to_first_audio_ms"+CANONICAL_CLOCK = "time.perf_counter_ns"+_FULL_SHA_RE = re.compile(r"[0-9a-f]{40}")+_REPORT_PLATFORMS = frozenset({"windows", "macos", "linux"})+_REPORT_ARCHITECTURES = frozenset({"x86_64", "arm64"})++REQUIRED_SCENARIOS = frozenset(+ {+ "three_turns_de",+ "barge_in_followup",+ "delegation",+ "detached_delegate_delivery",+ "provider_replacement",+ "classic_delivery",+ }+)+++@dataclass(frozen=True, slots=True)+class GateResult:+ """One content-free release-gate verdict."""++ failures: tuple[str, ...]+ warm_connects: int = 0+ turns: int = 0+ ttfa_p50_ms: float = 0.0+ ttfa_p95_ms: float = 0.0+ barge_stop_p95_ms: float = 0.0+ failback_max_ms: float = 0.0+ unaffected_regression_max_ms: float = 0.0++ @property+ def passed(self) -> bool:+ return not self.failures+++def _percentile(values: Sequence[float], percentile: float) -> float:+ """Return a linearly interpolated percentile over finite measurements."""+ ordered = sorted(float(value) for value in values)+ if not ordered:+ return 0.0+ if len(ordered) == 1:+ return ordered[0]+ position = (len(ordered) - 1) * percentile / 100.0+ lower = int(position)+ upper = min(lower + 1, len(ordered) - 1)+ fraction = position - lower+ return ordered[lower] + (ordered[upper] - ordered[lower]) * fraction+++def _measurements(+ report: Mapping[str, Any],+ key: str,+ failures: list[str],+ *,+ minimum: int,+ allow_negative: bool = False,+) -> list[float]:+ raw = report.get(key)+ if not isinstance(raw, list):+ failures.append(f"{key} must be a JSON array")+ return []+ values: list[float] = []+ for index, value in enumerate(raw):+ if isinstance(value, bool):+ failures.append(f"{key}[{index}] is not a numeric measurement")+ continue+ try:+ number = float(value)+ except (TypeError, ValueError):+ failures.append(f"{key}[{index}] is not a numeric measurement")+ continue+ if not math.isfinite(number):+ failures.append(f"{key}[{index}] must be finite")+ continue+ if not allow_negative and number < 0.0:+ failures.append(f"{key}[{index}] must be non-negative")+ continue+ values.append(number)+ if len(values) < minimum:+ failures.append(f"{key} has {len(values)} samples; need at least {minimum}")+ return values+++def report_evidence_sha256(report: Mapping[str, Any]) -> str:+ """Detect mismatches between provenance and canonical report fields.++ The collector writes this digest after capturing raw production+ ``RealtimeSessionPostmortem`` values. This unkeyed digest is an integrity+ check, not proof that measurements came from a real target; authenticity+ requires workflow-owned same-SHA collection plus manual acoustic sign-off.+ """+ payload = {+ "schema_version": report.get("schema_version"),+ "commit_sha": report.get("commit_sha"),+ "target": report.get("target"),+ "capabilities": report.get("capabilities"),+ CANONICAL_TTFA_FIELD: report.get(CANONICAL_TTFA_FIELD),+ "barge_stop_ms": report.get("barge_stop_ms"),+ "failback_ms": report.get("failback_ms"),+ "unaffected_turn_regression_ms": report.get(+ "unaffected_turn_regression_ms"+ ),+ "turns_completed": report.get("turns_completed"),+ "orphan_deliveries": report.get("orphan_deliveries"),+ "duplicate_deliveries": report.get("duplicate_deliveries"),+ "scenario_results": report.get("scenario_results"),+ }+ try:+ canonical = json.dumps(+ payload,+ ensure_ascii=True,+ allow_nan=False,+ separators=(",", ":"),+ sort_keys=True,+ ).encode("utf-8")+ except (TypeError, ValueError):+ return ""+ return hashlib.sha256(canonical).hexdigest()+++def _utc_timestamp(value: Any, key: str, failures: list[str]) -> datetime | None:+ raw = str(value or "").strip()+ try:+ parsed = datetime.fromisoformat(raw.replace("Z", "+00:00"))+ except ValueError:+ failures.append(f"provenance.{key} must be an ISO-8601 UTC timestamp")+ return None+ if parsed.tzinfo is None or parsed.utcoffset() != UTC.utcoffset(parsed):+ failures.append(f"provenance.{key} must include the UTC offset")+ return None+ return parsed+++def _validate_provenance(report: Mapping[str, Any], failures: list[str]) -> None:+ provenance = report.get("provenance")+ if not isinstance(provenance, Mapping):+ failures.append("provenance must be a JSON object from the target collector")+ return+ expected = {+ "collector": CANONICAL_COLLECTOR,+ "collector_version": CANONICAL_COLLECTOR_VERSION,+ "event_source": CANONICAL_EVENT_SOURCE,+ "clock": CANONICAL_CLOCK,+ }+ for key, value in expected.items():+ if provenance.get(key) != value:+ failures.append(f"provenance.{key} must be {value!r}")+ try:+ UUID(str(provenance.get("measurement_id", "")))+ except (ValueError, AttributeError):+ failures.append("provenance.measurement_id must be a UUID")+ started = _utc_timestamp(provenance.get("started_at"), "started_at", failures)+ completed = _utc_timestamp(provenance.get("completed_at"), "completed_at", failures)+ if started is not None and completed is not None:+ if completed <= started:+ failures.append("provenance.completed_at must be after started_at")+ elif (completed - started).total_seconds() > 86_400:+ failures.append("provenance measurement window must not exceed 24 hours")+ evidence = str(provenance.get("evidence_sha256", "") or "").strip().lower()+ expected_evidence = report_evidence_sha256(report)+ if not expected_evidence or evidence != expected_evidence:+ failures.append("provenance.evidence_sha256 does not match the report evidence")+++def evaluate_report(+ report: Mapping[str, Any],+ *,+ expected_sha: str,+ expected_platform: str,+ expected_architecture: str,+) -> GateResult:+ """Validate one candidate target report against the numerical SLOs."""+ failures: list[str] = []+ if report.get("schema_version") != SCHEMA_VERSION:+ failures.append(+ f"schema_version must be {SCHEMA_VERSION}, got {report.get('schema_version')!r}"+ )+ if report.get("measurement_mode") != "instrumented_target":+ failures.append(+ "measurement_mode must be 'instrumented_target'; synthetic or "+ "contract-only measurements cannot release the realtime path"+ )++ capabilities = report.get("capabilities")+ if not isinstance(capabilities, Mapping) or capabilities.get("local_inference") is not True:+ failures.append("capabilities.local_inference must be true")++ expected_sha = str(expected_sha or "").strip().lower()+ commit_sha = str(report.get("commit_sha", "") or "").strip().lower()+ if _FULL_SHA_RE.fullmatch(expected_sha) is None:+ failures.append("expected_sha must be a full 40-character Git commit SHA")+ if commit_sha != expected_sha:+ failures.append(+ f"commit_sha {commit_sha!r} does not match expected release SHA {expected_sha!r}"+ )++ expected_platform = str(expected_platform or "").strip().lower()+ expected_architecture = str(expected_architecture or "").strip().lower()+ if expected_platform not in _REPORT_PLATFORMS:+ failures.append(f"unsupported expected platform {expected_platform!r}")+ if expected_architecture not in _REPORT_ARCHITECTURES:+ failures.append(f"unsupported expected architecture {expected_architecture!r}")+ target = report.get("target")+ if not isinstance(target, Mapping):+ failures.append("target must identify the measured platform and architecture")+ else:+ if target.get("platform") != expected_platform:+ failures.append(+ f"target.platform must be {expected_platform!r}, got "+ f"{target.get('platform')!r}"+ )+ if target.get("architecture") != expected_architecture:+ failures.append(+ f"target.architecture must be {expected_architecture!r}, got "+ f"{target.get('architecture')!r}"+ )++ _validate_provenance(report, failures)++ ttfa = _measurements(+ report,+ CANONICAL_TTFA_FIELD,+ failures,+ minimum=MIN_WARM_CONNECTS,+ )+ barge = _measurements(+ report,+ "barge_stop_ms",+ failures,+ minimum=MIN_BARGE_SAMPLES,+ )+ failback = _measurements(+ report,+ "failback_ms",+ failures,+ minimum=MIN_FAILBACK_SAMPLES,+ )+ regression = _measurements(+ report,+ "unaffected_turn_regression_ms",+ failures,+ minimum=MIN_REGRESSION_SAMPLES,+ allow_negative=True,+ )++ raw_turns = report.get("turns_completed", 0)+ if isinstance(raw_turns, bool) or not isinstance(raw_turns, int):+ turns = 0+ failures.append("turns_completed must be an integer")+ else:+ turns = raw_turns+ if turns < MIN_TURNS:+ failures.append(f"turns_completed is {turns}; need at least {MIN_TURNS}")++ for key in ("orphan_deliveries", "duplicate_deliveries"):+ raw_value = report.get(key, -1)+ value = raw_value if isinstance(raw_value, int) and not isinstance(raw_value, bool) else -1+ if value != 0:+ failures.append(f"{key} must be exactly 0, got {report.get(key)!r}")++ scenarios = report.get("scenario_results")+ if not isinstance(scenarios, Mapping):+ failures.append("scenario_results must map scenario names to booleans")+ else:+ missing = sorted(REQUIRED_SCENARIOS - set(scenarios))+ if missing:+ failures.append(f"scenario_results missing: {', '.join(missing)}")+ failed = sorted(name for name in REQUIRED_SCENARIOS if scenarios.get(name) is not True)+ if failed:+ failures.append(f"scenario_results failed: {', '.join(failed)}")++ ttfa_p50 = _percentile(ttfa, 50.0)+ ttfa_p95 = _percentile(ttfa, 95.0)+ barge_p95 = _percentile(barge, 95.0)+ failback_max = max(failback, default=0.0)+ regression_max = max(regression, default=0.0)++ if ttfa and ttfa_p50 > TTFA_P50_LIMIT_MS:+ failures.append(f"warm TTFA p50 {ttfa_p50:.1f}ms exceeds {TTFA_P50_LIMIT_MS:.0f}ms")+ if ttfa and ttfa_p95 > TTFA_P95_LIMIT_MS:+ failures.append(f"warm TTFA p95 {ttfa_p95:.1f}ms exceeds {TTFA_P95_LIMIT_MS:.0f}ms")+ if barge and barge_p95 > BARGE_STOP_P95_LIMIT_MS:+ failures.append(f"barge stop p95 {barge_p95:.1f}ms exceeds {BARGE_STOP_P95_LIMIT_MS:.0f}ms")+ if failback and failback_max > FAILBACK_MAX_LIMIT_MS:+ failures.append(f"failback max {failback_max:.1f}ms exceeds {FAILBACK_MAX_LIMIT_MS:.0f}ms")+ if regression and regression_max > UNAFFECTED_REGRESSION_MAX_MS:+ failures.append(+ f"unaffected-turn regression max {regression_max:.1f}ms exceeds "+ f"{UNAFFECTED_REGRESSION_MAX_MS:.0f}ms"+ )++ return GateResult(+ failures=tuple(failures),+ warm_connects=len(ttfa),+ turns=turns,+ ttfa_p50_ms=ttfa_p50,+ ttfa_p95_ms=ttfa_p95,+ barge_stop_p95_ms=barge_p95,+ failback_max_ms=failback_max,+ unaffected_regression_max_ms=regression_max,+ )+++class _Surface:+ """In-memory desktop surface used only by the contract soak."""++ def __init__(self) -> None:+ self.json: list[tuple[float, dict[str, Any]]] = []+ self.binary_count = 0+ self.binary_tick = asyncio.Event()+ self.json_tick = asyncio.Event()++ async def send_binary(self, data: bytes) -> None:+ if data:+ self.binary_count += 1+ self.binary_tick.set()++ async def send_json(self, message: dict[str, Any]) -> None:+ self.json.append((time.perf_counter(), dict(message)))+ self.json_tick.set()++ def mark(self) -> int:+ return len(self.json)++ async def wait_json(+ self,+ predicate: Any,+ *,+ since: int,+ timeout_s: float = 3.0,+ ) -> tuple[float, dict[str, Any]]:+ async def _wait() -> tuple[float, dict[str, Any]]:+ while True:+ self.json_tick.clear()+ for row in self.json[since:]:+ if predicate(row[1]):+ return row+ await self.json_tick.wait()++ return await asyncio.wait_for(_wait(), timeout=timeout_s)+++class _FiniteWire:+ session_id = "reliability-finite"+ creates_responses_automatically = False+ isolates_response_generations = False+ supports_tool_updates = True++ def __init__(self, connection_index: int, turns: int) -> None:+ self._connection_index = connection_index+ self._turns = turns++ async def receive(self): # noqa: ANN201 - protocol async generator+ from jarvis.core.protocols import AudioChunk+ from jarvis.realtime.protocol import RealtimeEvent++ for turn in range(self._turns):+ turn_id = f"c{self._connection_index}-t{turn}"+ yield RealtimeEvent(+ type="input_transcript",+ text=f"Question number {turn}",+ is_final=True,+ item_id=turn_id,+ )+ yield RealtimeEvent(+ type="output_transcript_delta",+ text=f"Answer number {turn} completed safely.",+ )+ yield RealtimeEvent(+ type="audio_delta",+ audio=AudioChunk(+ pcm=b"\x10\x01" * 240,+ sample_rate=24_000,+ timestamp_ns=0,+ ),+ )+ yield RealtimeEvent(type="turn_complete")+ await asyncio.sleep(0)++ async def send_audio(self, chunk: Any) -> None:+ del chunk++ async def update_session(self, **kwargs: Any) -> None:+ del kwargs++ async def request_response(self, **kwargs: Any) -> None:+ del kwargs++ async def send_text(self, text: str) -> None:+ del text++ async def truncate(self, audio_end_ms: int) -> None:+ del audio_end_ms++ async def interrupt(self, **kwargs: Any) -> None:+ del kwargs++ async def send_tool_result(self, *args: Any) -> None:+ del args++ async def close(self) -> None:+ return None+++class _FiniteProvider:+ supports_realtime = True+ input_sample_rate = 24_000+ output_sample_rate = 24_000++ def __init__(+ self,+ turns_per_connection: Sequence[int],+ *,+ name: str = "reliability-contract",+ ) -> None:+ self._turns = list(turns_per_connection)+ self.name = name+ self.open_count = 0++ async def can_open_duplex_session(self) -> bool:+ return True++ async def open_session(self, config: Any) -> _FiniteWire:+ del config+ if self.open_count >= len(self._turns):+ raise RuntimeError("contract provider opened more sessions than planned")+ wire = _FiniteWire(self.open_count, self._turns[self.open_count])+ self.open_count += 1+ return wire+++_QUEUE_END = object()+++class _QueueWire:+ session_id = "reliability-queue"+ supports_tool_updates = False+ rebuild_on_transport_death = True++ def __init__(+ self,+ *,+ creates_responses_automatically: bool = True,+ supports_direct_tools: bool = False,+ ) -> None:+ self.creates_responses_automatically = creates_responses_automatically+ self.isolates_response_generations = creates_responses_automatically+ self.supports_direct_tools = supports_direct_tools+ self.direct_speech_is_authoritative = not supports_direct_tools+ self._events: asyncio.Queue[Any] = asyncio.Queue()+ self.interrupts = 0+ self.closed = False++ def push(self, *events: Any) -> None:+ for event in events:+ self._events.put_nowait(event)++ async def receive(self): # noqa: ANN201 - protocol async generator+ while True:+ event = await self._events.get()+ if event is _QUEUE_END:+ return+ yield event++ async def send_audio(self, chunk: Any) -> None:+ del chunk++ async def update_session(self, **kwargs: Any) -> None:+ del kwargs++ async def request_response(self, **kwargs: Any) -> None:+ del kwargs++ 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, **kwargs: Any) -> None:+ del kwargs+ self.interrupts += 1++ async def send_tool_result(self, *args: Any) -> None:+ del args++ def diagnostics(self) -> dict[str, int]:+ return {}++ async def close(self) -> None:+ if self.closed:+ return+ self.closed = True+ self._events.put_nowait(_QUEUE_END)+++class _QueueProvider:+ supports_realtime = True+ input_sample_rate = 24_000+ output_sample_rate = 24_000++ def __init__(+ self,+ *,+ name: str = "reliability-contract",+ creates_responses_automatically: bool = True,+ supports_direct_tools: bool = False,+ ) -> None:+ self.name = name+ self.creates_responses_automatically = creates_responses_automatically+ self.supports_direct_tools = supports_direct_tools+ self.sessions: list[_QueueWire] = []++ async def can_open_duplex_session(self) -> bool:+ return True++ async def open_session(self, config: Any) -> _QueueWire:+ del config+ wire = _QueueWire(+ creates_responses_automatically=self.creates_responses_automatically,+ supports_direct_tools=self.supports_direct_tools,+ )+ self.sessions.append(wire)+ return wire+++class _UnavailableProvider:+ """One capability-present family whose handshake fails deterministically."""++ name = "unavailable-contract-family"+ supports_realtime = True+ supports_direct_tools = True+ input_sample_rate = 24_000+ output_sample_rate = 24_000++ def __init__(self) -> None:+ self.open_count = 0++ async def can_open_duplex_session(self) -> bool:+ return True++ async def open_session(self, config: Any) -> Any:+ del config+ self.open_count += 1+ raise RuntimeError("contract transport unavailable")+++def _session_config() -> SimpleNamespace:+ return SimpleNamespace(+ brain=SimpleNamespace(reply_language="en", providers={}),+ stt=SimpleNamespace(language="auto"),+ voice=SimpleNamespace(mode="realtime", realtime_tool_mode="delegate"),+ latency=SimpleNamespace(enabled=False),+ )+++async def _open_session(+ provider: Any | None,+ surface: _Surface,+ *,+ session_id: str,+ providers: Sequence[Any] | None = None,+ brain: Any | None = None,+ bus: Any | None = None,+) -> tuple[Any, list[Any]]:+ from jarvis.core.bus import EventBus+ from jarvis.core.events import RealtimeSessionPostmortem+ from jarvis.realtime.session import RealtimeVoiceSession++ bus = bus or EventBus()+ postmortems: list[Any] = []++ async def _capture(event: RealtimeSessionPostmortem) -> None:+ postmortems.append(event)++ bus.subscribe(RealtimeSessionPostmortem, _capture)+ session = RealtimeVoiceSession(+ session_id=session_id,+ send_binary=surface.send_binary,+ send_json=surface.send_json,+ provider=provider,+ providers=list(providers) if providers is not None else None,+ config=_session_config(),+ bus=bus,+ brain=brain,+ surface="desktop",+ half_duplex=True,+ browser_sample_rate=24_000,+ )+ await asyncio.wait_for(+ session.handle_control({"type": "audio_start", "sample_rate": 24_000}),+ timeout=5.0,+ )+ return session, postmortems+++async def _run_finite_connection(+ provider: _FiniteProvider,+ *,+ connection_index: int,+ expected_turns: int,+) -> tuple[Any, _Surface]:+ surface = _Surface()+ session, postmortems = await _open_session(+ provider,+ surface,+ session_id=f"reliability-finite-{connection_index}",+ )+ await asyncio.wait_for(session.wait_finished(), timeout=5.0)+ await asyncio.wait_for(session.end(reason="contract-soak"), timeout=5.0)+ if len(postmortems) != 1:+ raise AssertionError("each connection must publish exactly one postmortem")+ postmortem = postmortems[0]+ completions = sum(message.get("type") == "turn_complete" for _, message in surface.json)+ errors = [message for _, message in surface.json if message.get("type") == "provider_error"]+ if postmortem.turns_completed != expected_turns:+ raise AssertionError(+ f"connection completed {postmortem.turns_completed} turns; expected {expected_turns}"+ )+ if completions != expected_turns or surface.binary_count != expected_turns:+ raise AssertionError(+ "one logical turn must produce exactly one completion and one PCM surface handoff"+ )+ if errors or postmortem.unsafe_output_cancellations:+ raise AssertionError("a healthy contract turn was cancelled or errored")+ return postmortem, surface+++async def _barge_sample(index: int) -> float:+ from jarvis.core.protocols import AudioChunk+ from jarvis.realtime.protocol import RealtimeEvent++ provider = _QueueProvider()+ surface = _Surface()+ session, _postmortems = await _open_session(+ provider,+ surface,+ session_id=f"reliability-barge-{index}",+ )+ try:+ wire = provider.sessions[0]+ wire.push(+ RealtimeEvent(+ type="input_transcript",+ text=(+ "Please explain how the settings work and what I should do "+ "next in clear English."+ ),+ is_final=True,+ item_id=f"barge-{index}",+ ),+ RealtimeEvent(+ type="output_transcript_delta",+ text=(+ "Here is a clear explanation of how the settings work and "+ "what you should do next."+ ),+ ),+ RealtimeEvent(+ type="audio_delta",+ audio=AudioChunk(+ pcm=b"\x10\x01" * 240,+ sample_rate=24_000,+ timestamp_ns=0,+ ),+ ),+ )+ await asyncio.wait_for(surface.binary_tick.wait(), timeout=3.0)+ mark = surface.mark()+ started = time.perf_counter()+ await session.handle_control({"type": "barge_in"})+ stopped_at, _ = await surface.wait_json(+ lambda message: message.get("type") == "tts_cancel",+ since=mark,+ )+ if wire.interrupts != 1:+ raise AssertionError("one barge-in must interrupt the active provider once")+ return (stopped_at - started) * 1_000.0+ finally:+ await asyncio.wait_for(session.end(reason="contract-soak"), timeout=5.0)+++async def _failback_sample(index: int) -> float:+ from jarvis.realtime.protocol import RealtimeEvent++ provider = _QueueProvider()+ surface = _Surface()+ session, _postmortems = await _open_session(+ provider,+ surface,+ session_id=f"reliability-failback-{index}",+ )+ try:+ first = provider.sessions[0]+ mark = surface.mark()+ started = time.perf_counter()+ first.push(+ RealtimeEvent(+ type="error",+ error="transport died",+ recoverable=True,+ reconnect_advised=True,+ ),+ RealtimeEvent(type="turn_complete"),+ )+ ready_at, _ = await surface.wait_json(+ lambda message: message.get("type") == "audio_ready",+ since=mark,+ )+ if len(provider.sessions) != 2:+ raise AssertionError("failback must open exactly one replacement transport")+ return (ready_at - started) * 1_000.0+ finally:+ await asyncio.wait_for(session.end(reason="contract-soak"), timeout=5.0)+++async def _wait_until(predicate: Any, *, timeout_s: float = 5.0) -> None:+ deadline = asyncio.get_running_loop().time() + timeout_s+ while not predicate():+ if asyncio.get_running_loop().time() >= deadline:+ raise TimeoutError("contract scenario did not reach its expected state")+ await asyncio.sleep(0.01)+++async def _detached_delegate_delivery_scenario() -> dict[str, int]:+ """Prove an accepted action survives teardown and is delivered once."""+ from jarvis.core.bus import EventBus+ from jarvis.core.events import AnnouncementRequested+ from jarvis.realtime.protocol import RealtimeEvent++ class _BlockingBrain:+ def __init__(self) -> None:+ self.calls: list[str] = []+ self.started = asyncio.Event()+ self.release = asyncio.Event()++ async def __call__(self, text: str) -> str:+ return await self.generate(text)++ async def generate(self, text: str, **kwargs: Any) -> str:+ del kwargs+ self.calls.append(text)+ self.started.set()+ await self.release.wait()+ return "The requested wiki update completed successfully."++ brain = _BlockingBrain()+ bus = EventBus()+ announcements: list[Any] = []++ async def _capture(event: AnnouncementRequested) -> None:+ if event.kind == "completion":+ announcements.append(event)++ bus.subscribe(AnnouncementRequested, _capture)+ provider = _QueueProvider(+ name="delegate-contract-family",+ creates_responses_automatically=False,+ supports_direct_tools=True,+ )+ surface = _Surface()+ session, _postmortems = await _open_session(+ provider,+ surface,+ session_id="reliability-detached-delegate",+ brain=brain,+ bus=bus,+ )+ provider.sessions[0].push(+ RealtimeEvent(+ type="input_transcript",+ text="Write the current release status to my wiki page.",+ is_final=True,+ item_id="detached-delegate-turn",+ )+ )+ await asyncio.wait_for(brain.started.wait(), timeout=5.0)+ turn_id, turn_state = next(iter(session._delegate_turns.items())) # noqa: SLF001++ await asyncio.wait_for(session.end(reason="contract-detach"), timeout=5.0)+ if brain.calls != ["Write the current release status to my wiki page."]:+ raise AssertionError("the detached action must be dispatched exactly once")++ brain.release.set()+ await _wait_until(+ lambda: (+ len(announcements) == 1+ and turn_state.result_complete+ and turn_state.delivery_completed+ )+ )+ if not turn_state.result_complete or not turn_state.delivery_completed:+ raise AssertionError("the detached result must remain complete and delivered")+ if turn_state.delivery_channel != "detached" or not turn_state.result_payload:+ raise AssertionError("the retained result must use detached delivery state")+ if await session._deliver_detached_delegate_result( # noqa: SLF001+ turn_id,+ turn_state,+ ):+ raise AssertionError("a duplicate detached callback must not redeliver")+ if len(announcements) != 1:+ raise AssertionError("the detached result reached the surface more than once")+ return {+ "detached_delegate_deliveries": 1,+ "delegate_duplicates_suppressed": 1,+ }+++async def _provider_replacement_scenario() -> dict[str, int]:+ """Cross from a failed provider family to one healthy alternate."""+ primary = _UnavailableProvider()+ alternate = _FiniteProvider([1], name="replacement-contract-family")+ surface = _Surface()+ session, postmortems = await _open_session(+ None,+ surface,+ session_id="reliability-provider-replacement",+ providers=[primary, alternate],+ )+ await asyncio.wait_for(session.wait_finished(), timeout=5.0)+ await asyncio.wait_for(session.end(reason="contract-soak"), timeout=5.0)+ fallback_frames = [+ message+ for _, message in surface.json+ if message.get("type") == "provider_fallback"+ ]+ completions = sum(+ message.get("type") == "turn_complete" for _, message in surface.json+ )+ if primary.open_count != 1 or alternate.open_count != 1:+ raise AssertionError("provider replacement must try each family exactly once")+ if len(fallback_frames) != 1 or completions != 1 or surface.binary_count != 1:+ raise AssertionError("the replacement provider must deliver the turn exactly once")+ if len(postmortems) != 1 or postmortems[0].turns_completed != 1:+ raise AssertionError("provider replacement must retain one completed turn")+ return {"provider_replacements": 1}+++async def _classic_delivery_scenario() -> dict[str, int]:+ """Route one retained opening through the production Classic dispatcher."""+ import jarvis.speech.pipeline as pipeline_mod+ from jarvis.core.protocols import AudioChunk+ from jarvis.speech.pipeline import SpeechPipeline++ class _OneShotVad:+ def utterances(self, stream: Any) -> Any:+ async def _one() -> Any:+ async for chunk in stream:+ yield chunk.pcm+ return++ return _one()++ # This contract intentionally assembles a minimal pipeline without running+ # its hardware-owning constructor; ``Any`` keeps the injected test seams+ # explicit without pretending this partial object is a fully typed instance.+ pipe: Any = SpeechPipeline.__new__(SpeechPipeline)+ pipe._config = SimpleNamespace(+ voice=SimpleNamespace(mode="realtime", model_fields_set=set()),+ brain=SimpleNamespace(reply_language="en"),+ )+ pipe._ptt_mode = False+ pipe._hangup_event = asyncio.Event()+ pipe._vad = _OneShotVad()+ pipe._idle_timeout_s = 1.0+ pipe._idle_hangup_enabled = True+ pipe._session_end_reason = None+ pipe._carry_pcm = bytearray()+ pipe._carry_started_monotonic = None+ pipe._last_endpoint_reason = None+ pipe._last_announcement_spoken_monotonic = None+ pipe._last_answer_floor_monotonic = None+ pipe._active_voice_mode = "realtime"+ pipe._active_realtime_provider = ""+ pipe._active_realtime_model = ""+ pipe._voice_engine_transitioning = False+ pipe._muted = False+ pipe._input_suppressed_until_ns = 0++ captured: list[bytes] = []+ delivered: list[bytes] = []++ async def _realtime_unavailable(*, input_buffer: Any = None) -> None:+ del input_buffer+ return None++ async def _passthrough(source: Any) -> Any:+ async for chunk in source:+ yield chunk++ async def _set_state(state: Any) -> None:+ del state++ async def _publish(event: Any) -> None:+ del event++ async def _captured(pcm: bytes) -> None:+ captured.append(pcm)++ async def _classic_handle(pcm: bytes, **kwargs: Any) -> bool:+ del kwargs+ if pcm != b"retained-opening":+ raise AssertionError("Classic must receive the retained realtime opening")+ delivered.append(b"classic-reply-audio")+ return False++ pipe._active_realtime_session = _realtime_unavailable+ pipe._session_input_stream = _passthrough+ pipe._set_turn_state = _set_state+ pipe._publish_event = _publish+ pipe._publish_utterance_captured = _captured+ pipe._handle_utterance = _classic_handle++ opening = AudioChunk(+ pcm=b"retained-opening",+ sample_rate=16_000,+ timestamp_ns=1,+ )+ buffer = pipeline_mod._SessionInputBuffer(initial=(opening,)) # noqa: SLF001+ buffer.finish()+ await asyncio.wait_for(pipe._active_session(input_buffer=buffer), timeout=5.0)+ if captured != [opening.pcm] or delivered != [b"classic-reply-audio"]:+ raise AssertionError("Classic fallback must capture and deliver exactly once")+ return {"classic_deliveries": 1}+++async def run_contract_soak(+ *,+ warm_connects: int = MIN_WARM_CONNECTS,+ turns_per_connect: int = 5,+ barge_samples: int = MIN_BARGE_SAMPLES,+ failback_samples: int = MIN_FAILBACK_SAMPLES,+) -> dict[str, Any]:+ """Run the key-free provider-neutral reliability soak.++ The first connection is a warm-up and is excluded. Every subsequent+ connection carries ``turns_per_connect`` logical turns.+ """+ if warm_connects <= 0 or turns_per_connect <= 0:+ raise ValueError("warm_connects and turns_per_connect must be positive")+ # The injected reconnect failures are expected test stimuli. Suppress their+ # warning-level production diagnostics here; exceptions and gate failures+ # still propagate, and live runs retain their normal observability.+ session_log = logging.getLogger("jarvis.realtime.session")+ previous_level = session_log.level+ session_log.setLevel(logging.ERROR)+ try:+ provider = _FiniteProvider([1, *([turns_per_connect] * warm_connects)])+ await _run_finite_connection(provider, connection_index=0, expected_turns=1)++ ttfa: list[float] = []+ delivered = 0+ completions = 0+ for index in range(1, warm_connects + 1):+ postmortem, surface = await _run_finite_connection(+ provider,+ connection_index=index,+ expected_turns=turns_per_connect,+ )+ ttfa.append(float(postmortem.first_final_to_first_audio_ms))+ delivered += surface.binary_count+ completions += sum(+ message.get("type") == "turn_complete" for _, message in surface.json+ )++ turns = warm_connects * turns_per_connect+ if delivered != turns or completions != turns:+ raise AssertionError(+ f"delivery ledger mismatch: turns={turns} audio={delivered} "+ f"completions={completions}"+ )++ barge = [await _barge_sample(index) for index in range(barge_samples)]+ failback = [await _failback_sample(index) for index in range(failback_samples)]+ detached = await _detached_delegate_delivery_scenario()+ replacement = await _provider_replacement_scenario()+ classic = await _classic_delivery_scenario()+ finally:+ session_log.setLevel(previous_level)+ metrics = {+ "warm_connects": warm_connects,+ "turns": turns,+ "orphan_deliveries": max(0, turns - completions),+ "duplicate_deliveries": max(0, completions - turns),+ "ttfa_p50_ms": _percentile(ttfa, 50.0),+ "ttfa_p95_ms": _percentile(ttfa, 95.0),+ "barge_stop_p95_ms": _percentile(barge, 95.0),+ "failback_max_ms": max(failback, default=0.0),+ **detached,+ **replacement,+ **classic,+ }+ failures: list[str] = []+ if metrics["orphan_deliveries"] or metrics["duplicate_deliveries"]:+ failures.append("contract soak observed orphan or duplicate delivery")+ if metrics["ttfa_p50_ms"] > TTFA_P50_LIMIT_MS:+ failures.append("contract orchestration TTFA p50 exceeded the release SLO")+ if metrics["ttfa_p95_ms"] > TTFA_P95_LIMIT_MS:+ failures.append("contract orchestration TTFA p95 exceeded the release SLO")+ if metrics["barge_stop_p95_ms"] > BARGE_STOP_P95_LIMIT_MS:+ failures.append("contract barge stop p95 exceeded the release SLO")+ if metrics["failback_max_ms"] > FAILBACK_MAX_LIMIT_MS:+ failures.append("contract failback exceeded the release SLO")+ if metrics["detached_delegate_deliveries"] != 1:+ failures.append("contract soak did not retain one detached delegate result")+ if metrics["delegate_duplicates_suppressed"] != 1:+ failures.append("contract soak did not suppress the detached duplicate")+ if metrics["provider_replacements"] != 1:+ failures.append("contract soak did not cross to one replacement provider")+ if metrics["classic_deliveries"] != 1:+ failures.append("contract soak did not deliver one Classic fallback turn")+ if failures:+ raise AssertionError("; ".join(failures))+ return metrics+++def _print_result(result: GateResult) -> None:+ if result.passed:+ print(+ "PASS: candidate target report met every numerical SLO threshold "+ f"({result.warm_connects} warm connects, {result.turns} turns; "+ f"TTFA p50={result.ttfa_p50_ms:.1f}ms "+ f"p95={result.ttfa_p95_ms:.1f}ms; "+ f"barge p95={result.barge_stop_p95_ms:.1f}ms; "+ f"failback max={result.failback_max_ms:.1f}ms)."+ )+ print(+ "TTFA ends at Jarvis's PCM output callback, not confirmed device "+ "playback; release still requires same-SHA collection and manual "+ "acoustic sign-off."+ )+ else:+ print("FAIL: realtime release gate did not pass:")+ for failure in result.failures:+ print(f" - {failure}")+ print(+ "MANUAL SIGN-OFF STILL REQUIRED: physical microphone/acoustic echo, "+ "real speaker stop, device hot-plug, and macOS TCC permission flow."+ )+++def main(argv: Sequence[str] | None = None) -> int:+ parser = argparse.ArgumentParser(description=__doc__)+ mode = parser.add_mutually_exclusive_group(required=True)+ mode.add_argument(+ "--report",+ type=Path,+ help="instrumented target JSON report to validate",+ )+ mode.add_argument(+ "--contract-soak",+ action="store_true",+ help="run the key-free 100-connect/500-turn provider contract soak",+ )+ parser.add_argument(+ "--expected-sha",+ help="exact 40-character release commit SHA required by --report",+ )+ parser.add_argument(+ "--expected-platform",+ choices=sorted(_REPORT_PLATFORMS),+ help="canonical measured target platform required by --report",+ )+ parser.add_argument(+ "--expected-architecture",+ choices=sorted(_REPORT_ARCHITECTURES),+ help="canonical measured target architecture required by --report",+ )+ args = parser.parse_args(argv)++ if args.contract_soak:+ try:+ metrics = asyncio.run(run_contract_soak())+ except (AssertionError, TimeoutError, RuntimeError, ValueError) as exc:+ print(f"FAIL: provider-neutral contract soak: {exc}")+ return 1+ print(+ "PASS: provider-neutral contract soak "+ f"({metrics['warm_connects']} warm connects, {metrics['turns']} turns, "+ f"TTFA p95={metrics['ttfa_p95_ms']:.1f}ms, "+ f"barge p95={metrics['barge_stop_p95_ms']:.1f}ms, "+ f"failback max={metrics['failback_max_ms']:.1f}ms, "+ "detached delegate + provider replacement + Classic delivery, "+ "zero orphan/duplicate deliveries)."+ )+ print(+ "This is orchestration proof only; run --report with measured "+ "local-inference data before release."+ )+ print(+ "MANUAL SIGN-OFF STILL REQUIRED: physical microphone/acoustic echo, "+ "real speaker stop, device hot-plug, and macOS TCC permission flow."+ )+ return 0++ if not (+ args.expected_sha+ and args.expected_platform+ and args.expected_architecture+ ):+ print(+ "FAIL: --report requires --expected-sha, --expected-platform, "+ "and --expected-architecture"+ )+ return 2+ try:+ raw = json.loads(args.report.read_text(encoding="utf-8"))+ except (OSError, json.JSONDecodeError) as exc:+ print(f"FAIL: cannot read reliability report: {exc}")+ return 1+ if not isinstance(raw, Mapping):+ print("FAIL: reliability report root must be a JSON object")+ return 1+ result = evaluate_report(+ raw,+ expected_sha=args.expected_sha,+ expected_platform=args.expected_platform,+ expected_architecture=args.expected_architecture,+ )+ _print_result(result)+ return 0 if result.passed else 1+++if __name__ == "__main__":+ if hasattr(sys.stdout, "reconfigure"):+ sys.stdout.reconfigure(encoding="utf-8") # type: ignore[union-attr]+ raise SystemExit(main())diff --git a/tests/contract/test_realtime_provider_contract.py b/tests/contract/test_realtime_provider_contract.pyindex 9520c1c295..c0c0757c2a 100644--- a/tests/contract/test_realtime_provider_contract.py+++ b/tests/contract/test_realtime_provider_contract.py@@ -2,6 +2,8 @@ from __future__ import annotationsimport astimport asyncio+import subprocess+import sysfrom pathlib import Pathfrom types import SimpleNamespacefrom typing import Any@@ -231,11 +233,7 @@ async def test_unconfigured_local_provider_probe_is_false() -> None:)def test_plugin_module_imports_no_jarvis_modules(path: Path):tree = ast.parse(path.read_text(encoding="utf-8"))- imports = [- node.module or ""- for node in ast.walk(tree)- if isinstance(node, ast.ImportFrom)- ]+ imports = [node.module or "" for node in ast.walk(tree) if isinstance(node, ast.ImportFrom)]direct_imports = [alias.namefor node in ast.walk(tree)@@ -243,9 +241,7 @@ def test_plugin_module_imports_no_jarvis_modules(path: Path):for alias in node.names]assert not any(name == "jarvis" or name.startswith("jarvis.") for name in imports)- assert not any(- name == "jarvis" or name.startswith("jarvis.") for name in direct_imports- )+ assert not any(name == "jarvis" or name.startswith("jarvis.") for name in direct_imports)@pytest.mark.parametrize(@@ -257,18 +253,41 @@ def test_plugin_module_imports_no_jarvis_modules(path: Path):)def test_provider_sdk_import_is_lazy(path: Path, sdk_root: str):tree = ast.parse(path.read_text(encoding="utf-8"))- top_level = [- node- for node in tree.body- if isinstance(node, (ast.Import, ast.ImportFrom))- ]- names = [- alias.name- for node in top_level- for alias in (getattr(node, "names", []) or [])- ]+ top_level = [node for node in tree.body if isinstance(node, (ast.Import, ast.ImportFrom))]+ names = [alias.name for node in top_level for alias in (getattr(node, "names", []) or [])]modules = [getattr(node, "module", "") or "" for node in top_level]assert not any(- name == sdk_root or name.startswith(f"{sdk_root}.")- for name in [*names, *modules]+ name == sdk_root or name.startswith(f"{sdk_root}.") for name in [*names, *modules])+++def test_headless_realtime_stack_reports_unavailable_without_audio_libraries() -> None:+ """A slim/no-audio host imports cleanly and returns an honest capability.++ A fresh interpreter is required: the contract module imports provider+ classes above, while this proof must take the actual missing-dependency+ branch before any audio or WebRTC module reaches ``sys.modules``.+ """+ code = "\n".join(+ (+ "import sys",+ "sys.modules['sounddevice'] = None",+ "sys.modules['aiortc'] = None",+ "sys.modules['av'] = None",+ "from jarvis.audio.devices import list_devices",+ "from jarvis.realtime.webrtc_transport import webrtc_unavailable_reason",+ "assert list_devices(output=True) == []",+ "reason = webrtc_unavailable_reason()",+ "assert reason and 'aiortc' in reason.lower(), reason",+ "print('HEADLESS_DEGRADED')",+ )+ )+ result = subprocess.run(+ [sys.executable, "-c", code],+ capture_output=True,+ text=True,+ timeout=30,+ )++ assert result.returncode == 0, result.stderr+ assert "HEADLESS_DEGRADED" in result.stdoutdiff --git a/tests/contract/test_realtime_reliability_gate.py b/tests/contract/test_realtime_reliability_gate.pynew file mode 100644index 0000000000..210f808341--- /dev/null+++ b/tests/contract/test_realtime_reliability_gate.py@@ -0,0 +1,142 @@+"""Contract tests for the realtime release and slow-soak gates."""++from __future__ import annotations++import asyncio+import importlib.util+import sys+from pathlib import Path+from typing import Any++import pytest++_COMMIT_SHA = "abcdef0123456789abcdef0123456789abcdef01"+_PLATFORM = "linux"+_ARCHITECTURE = "x86_64"+_TTFA_FIELD = "first_final_to_first_audio_ms"+++def _load_gate():+ path = Path(__file__).resolve().parents[2] / "scripts" / "realtime_reliability_gate.py"+ spec = importlib.util.spec_from_file_location("_realtime_reliability_gate", path)+ assert spec is not None and spec.loader is not None+ module = importlib.util.module_from_spec(spec)+ sys.modules[spec.name] = module+ spec.loader.exec_module(module)+ return module+++def _report(gate: Any, **overrides: Any) -> dict[str, Any]:+ report: dict[str, Any] = {+ "schema_version": gate.SCHEMA_VERSION,+ "measurement_mode": "instrumented_target",+ "commit_sha": _COMMIT_SHA,+ "target": {"platform": _PLATFORM, "architecture": _ARCHITECTURE},+ "capabilities": {"local_inference": True},+ gate.CANONICAL_TTFA_FIELD: [600.0] * 100,+ "barge_stop_ms": [120.0] * 20,+ "failback_ms": [900.0] * 20,+ "unaffected_turn_regression_ms": [10.0] * 50,+ "turns_completed": 500,+ "orphan_deliveries": 0,+ "duplicate_deliveries": 0,+ "scenario_results": {+ "three_turns_de": True,+ "barge_in_followup": True,+ "delegation": True,+ "detached_delegate_delivery": True,+ "provider_replacement": True,+ "classic_delivery": True,+ },+ }+ report.update(overrides)+ report["provenance"] = {+ "collector": gate.CANONICAL_COLLECTOR,+ "collector_version": gate.CANONICAL_COLLECTOR_VERSION,+ "event_source": gate.CANONICAL_EVENT_SOURCE,+ "clock": gate.CANONICAL_CLOCK,+ "measurement_id": "00000000-0000-4000-8000-000000000001",+ "started_at": "2026-08-09T10:00:00Z",+ "completed_at": "2026-08-09T10:05:00Z",+ }+ report["provenance"]["evidence_sha256"] = gate.report_evidence_sha256(report)+ return report+++def _evaluate(gate: Any, **overrides: Any):+ return gate.evaluate_report(+ _report(gate, **overrides),+ expected_sha=_COMMIT_SHA,+ expected_platform=_PLATFORM,+ expected_architecture=_ARCHITECTURE,+ )+++def test_instrumented_target_report_passes_every_slo() -> None:+ gate = _load_gate()+ result = _evaluate(gate)++ assert result.passed is True+ assert result.warm_connects == 100+ assert result.turns == 500+++ ("override", "failure_fragment"),+ [+ ({"measurement_mode": "synthetic"}, "instrumented_target"),+ ({_TTFA_FIELD: [600.0] * 99}, "need at least 100"),+ ({"turns_completed": 499}, "need at least 500"),+ ({"orphan_deliveries": 1}, "orphan_deliveries"),+ ({"duplicate_deliveries": 1}, "duplicate_deliveries"),+ ({"barge_stop_ms": [251.0] * 20}, "barge stop p95"),+ ({"failback_ms": [2_001.0] * 20}, "failback max"),+ (+ {"unaffected_turn_regression_ms": [51.0] * 50},+ "unaffected-turn regression",+ ),+ (+ {+ "scenario_results": {+ "three_turns_de": True,+ "barge_in_followup": False,+ "delegation": True,+ }+ },+ "barge_in_followup",+ ),+ ],+)+def test_release_gate_fails_closed(override: dict[str, Any], failure_fragment: str) -> None:+ gate = _load_gate()+ result = _evaluate(gate, **override)++ assert result.passed is False+ assert any(failure_fragment in failure for failure in result.failures)+++def test_release_gate_checks_interpolated_ttfa_percentiles() -> None:+ gate = _load_gate()+ values = [700.0] * 94 + [1_500.0] * 6+ result = _evaluate(gate, **{gate.CANONICAL_TTFA_FIELD: values})++ assert result.passed is False+ assert result.ttfa_p50_ms <= 800.0+ assert result.ttfa_p95_ms > 1_200.0+++def test_small_provider_neutral_soak_exercises_real_session_state_machine() -> None:+ gate = _load_gate()+ metrics = asyncio.run(+ gate.run_contract_soak(+ warm_connects=2,+ turns_per_connect=2,+ barge_samples=1,+ failback_samples=1,+ )+ )++ assert metrics["warm_connects"] == 2+ assert metrics["turns"] == 4+ assert metrics["orphan_deliveries"] == 0+ assert metrics["duplicate_deliveries"] == 0diff --git a/tests/fakes/fake_realtime.py b/tests/fakes/fake_realtime.pyindex 4726bfe709..2f6efafaf3 100644--- a/tests/fakes/fake_realtime.py+++ b/tests/fakes/fake_realtime.py@@ -20,6 +20,7 @@ class FakeRealtimeWire:self._hold_after_events = hold_after_eventsself.events_drained = asyncio.Event()self.sent_audio: list[Any] = []+ self.sent_text: list[str] = []self.tool_results: list[tuple[str, str, dict[str, Any]]] = []self.session_updates: list[dict[str, Any]] = []self.response_requests = 0@@ -31,6 +32,10 @@ class FakeRealtimeWire:async def send_audio(self, chunk: Any) -> None:self.sent_audio.append(chunk)+ async def send_text(self, text: str) -> None:+ """Record an injected provider prompt required by the wire protocol."""+ self.sent_text.append(text)+async def receive(self):for event in self._events:yield eventdiff --git a/tests/integration/realtime/test_codex_multi_turn.py b/tests/integration/realtime/test_codex_multi_turn.pyindex 44a02b25ce..cd827db1fa 100644--- a/tests/integration/realtime/test_codex_multi_turn.py+++ b/tests/integration/realtime/test_codex_multi_turn.py@@ -269,6 +269,9 @@ async def _open_call() -> tuple[session.handle_control({"type": "audio_start", "sample_rate": INPUT_RATE}),TIMEOUT_S,)+ # The real desktop surface supplies this probe. This in-memory surface has+ # no device queue, so every forwarded frame is drained immediately.+ session.set_playback_probe(lambda: False)assert provider.sessions, "the provider was never opened"return session, provider, provider.sessions[0], surface@@ -502,7 +505,13 @@ async def test_a_turn_without_any_terminal_item_does_not_wedge_the_next_one(wire.push(RealtimeEvent(type="speech_started"),RealtimeEvent(type="input_transcript", text="no boundary please", is_final=True),- RealtimeEvent(type="output_transcript_delta", text="An answer with no end."),+ RealtimeEvent(+ type="output_transcript_delta",+ text=(+ "This is a complete English answer with enough ordinary "+ "words to establish its language, but no terminal boundary."+ ),+ ),RealtimeEvent(type="audio_delta", audio=_audio()),# No turn_complete, deliberately.)@@ -626,13 +635,11 @@ async def test_a_late_user_transcript_does_not_break_the_turn_in_flight() -> Nonsince = surface.mark()wire.push(RealtimeEvent(type="speech_started"),- RealtimeEvent(type="input_transcript", text="what is the weather", is_final=True),- RealtimeEvent(type="output_transcript_delta", text="It is sunny."),+ RealtimeEvent(type="input_transcript", text="how are you", is_final=True),+ RealtimeEvent(type="output_transcript_delta", text="I am doing well."),RealtimeEvent(type="audio_delta", audio=_audio()),# The far end's own copy of the SAME utterance, arriving late.- RealtimeEvent(- type="input_transcript", text="what is the weather", is_final=True- ),+ RealtimeEvent(type="input_transcript", text="how are you", is_final=True),RealtimeEvent(type="turn_complete"),)await surface.wait_json(lambda m: m.get("type") == "turn_complete", since=since)diff --git a/tests/unit/brain/test_turn_planner.py b/tests/unit/brain/test_turn_planner.pyindex f121f64c09..dda30d197b 100644--- a/tests/unit/brain/test_turn_planner.py+++ b/tests/unit/brain/test_turn_planner.py@@ -10,6 +10,7 @@ from jarvis.brain.turn_planner import (GroundingFailurePolicy,TurnPath,TurnReason,+ is_public_fact_question,plan_turn,)from jarvis.core.capabilities import Capability, CapabilityRegistry@@ -157,12 +158,21 @@ def test_strong_current_markers_still_use_orchestrator(utterance: str) -> None:@pytest.mark.parametrize("utterance",[+ "How high is Mount Everest?",+ "How fast can a cheetah run?",+ "What year was NASA founded?","How long did Muhammad Ali live?",- "Wer ist der Praesident des WBC?", # i18n-allow: German speech fixture- "Quien fundo la NASA?", # i18n-allow: Spanish speech fixture+ "Who is the current president of the WBC?",+ "Wie hoch ist der Eiffelturm?", # i18n-allow: German speech fixture+ "Wie lange lebte Muhammad Ali?", # i18n-allow: German speech fixture+ "Wer ist aktuell Praesident des WBC?", # i18n-allow: German speech fixture+ "¿En que ano se fundo la NASA?", # i18n-allow: Spanish speech fixture+ "¿Quien es el presidente actual del WBC?", # i18n-allow: Spanish speech fixture],)def test_declared_small_model_public_facts_ground_once(utterance: str) -> None:+ assert is_public_fact_question(utterance) is True+plan = plan_turn(utterance,tool_names=(PUBLIC_FACT_GROUNDING_CAPABILITY,),@@ -202,6 +212,11 @@ def test_public_search_capability_is_deduplicated() -> None:@pytest.mark.parametrize("utterance",[+ "Find the Python executable on disk.",+ "Which process is listening on port 8000 on this machine?",+ "Check the current Jarvis settings.",+ "What is inside the README.md file?",+ "Find the local config file.","What is in my Gmail inbox?","Which meetings are in my calendar today?","What is on my screen?",@@ -210,12 +225,33 @@ def test_public_search_capability_is_deduplicated() -> None:def test_private_or_connected_facts_never_leak_to_public_search(utterance: str,) -> None:+ assert is_public_fact_question(utterance) is False+plan = plan_turn(utterance, requires_public_fact_grounding=True)assert plan.requires_public_fact_grounding is Falseassert PUBLIC_FACT_GROUNDING_CAPABILITY not in plan.required_capabilities+ "utterance",+ [+ "Which pull requests are open today?",+ "Which repositories are private?",+ "Which deployments failed today?",+ "Which inboxes have unread mail?",+ ],+)+def test_plural_connected_domains_never_route_to_public_search(+ utterance: str,+) -> None:+ plan = plan_turn(utterance, requires_public_fact_grounding=True)++ assert TurnReason.CONNECTED_DATA in plan.reasons+ assert plan.requires_public_fact_grounding is False+ assert PUBLIC_FACT_GROUNDING_CAPABILITY not in plan.required_capabilities++def test_read_only_dynamic_connector_matches_live_capability(registry: CapabilityRegistry,) -> None:@@ -574,14 +610,17 @@ def test_capability_canonical_utterances_route_to_orchestrator(# ("What is tomorrow for day?") from the live transcript."Was ist morgen für ein Tag?", # i18n-allow: forensic fixture"Was ist heute für ein Datum?", # i18n-allow: forensic fixture+ "Ich will wissen, was morgen f\u00fcr ein Tag ist.", # i18n-allow: exact regression"Welcher Tag ist morgen?", # i18n-allow: German speech-input fixture"Welcher Wochentag ist heute?", # i18n-allow: German fixture"Welches Datum haben wir?", # i18n-allow: German speech-input fixture"Der Wievielte ist heute?", # i18n-allow: German speech-input fixture+ "I want to know what day tomorrow is.","What day is it today?","What day is tomorrow?","What is tomorrow for day?","What's the date?",+ "Quiero saber qu\u00e9 d\u00eda es ma\u00f1ana.", # i18n-allow: embedded Spanish"¿Qué día es hoy?",],)@@ -606,6 +645,23 @@ def test_time_words_with_real_evidence_still_delegate(utterance: str) -> None:assert plan_turn(utterance).path is TurnPath.ORCHESTRATOR+ "utterance",+ [+ "Wie ist das Wetter morgen?", # i18n-allow: German speech-input fixture+ "Was steht heute in den Nachrichten?", # i18n-allow: German fixture+ "What's in the news today?",+ ],+)+def test_calendar_trivia_suppression_does_not_hide_fresh_public_facts(+ utterance: str,+) -> None:+ plan = plan_turn(utterance)++ assert plan.requires_public_fact_grounding is True+ assert plan.required_capabilities.count(PUBLIC_FACT_GROUNDING_CAPABILITY) == 1++# --------------------------------------------------------------------------- ## A turn naming an open coding terminal ## --------------------------------------------------------------------------- #diff --git a/tests/unit/core/test_turn_language.py b/tests/unit/core/test_turn_language.pyindex f53841c8fe..f1ee15a405 100644--- a/tests/unit/core/test_turn_language.py+++ b/tests/unit/core/test_turn_language.py@@ -351,6 +351,35 @@ def test_output_language_validator_does_not_reject_a_chinese_name() -> None:assert result.detected_language != "zh"+ "text",+ [+ "Name: 中华人民共和国",+ "中华人民共和国",+ "Label: 中华人民共和国",+ "The organization 中华人民共和国 is listed with the correct English name.",+ ],+)+def test_output_language_validator_keeps_short_han_names_non_blocking(+ text: str,+) -> None:+ result = validate_output_language(text, resolved_language="en")++ assert result.detected_language != "zh"+ assert result.should_block is False+++def test_output_language_validator_still_blocks_long_han_corruption() -> None:+ result = validate_output_language(+ "这是一个完全错误的中文回答必须立即阻止不能向用户播放",+ resolved_language="en",+ )++ assert result.status == "mismatch"+ assert result.detected_language == "zh"+ assert result.should_block is True++def test_output_language_validator_does_not_reject_a_vietnamese_name() -> None:result = validate_output_language("The meeting with Nguyễn Văn Bình is today.",diff --git a/tests/unit/realtime/test_scrub_gate.py b/tests/unit/realtime/test_scrub_gate.pyindex 6b1d75ed15..3451784f7f 100644--- a/tests/unit/realtime/test_scrub_gate.py+++ b/tests/unit/realtime/test_scrub_gate.py@@ -11,6 +11,115 @@ def _chunk(n: int) -> AudioChunk:return AudioChunk(pcm=b"\x00\x01" * n, sample_rate=24000, timestamp_ns=0)+ ("language", "text"),+ [+ (+ "en",+ "This is a clear English answer with enough ordinary words to "+ "identify the language correctly.",+ ),+ (+ "de",+ "Das ist eine klare deutsche Antwort mit genügend gewöhnlichen " # i18n-allow+ "Wörtern für eine sichere Erkennung.", # i18n-allow+ ),+ (+ "es",+ "Esta es una respuesta clara en español con suficientes palabras "+ "comunes para reconocer el idioma.",+ ),+ ],+)+async def test_resolved_output_language_releases_matching_pcm(+ language: str,+ text: str,+) -> None:+ gate = ScrubHoldGate(language=language)+ buffered = _chunk(16)++ assert await gate.push_audio(buffered) == []+ assert await gate.feed_transcript(+ text,+ enforce_output_language=True,+ ) == text++ assert gate.hard_leak_pending() is False+ assert gate.release_available() == [buffered]+++ ("language", "text"),+ [+ (+ "en",+ "Xin chào, đây là câu trả lời bằng tiếng Việt với nhiều từ rõ "+ "ràng để xác định ngôn ngữ.",+ ),+ (+ "de",+ "这是一个完整的中文回答,包含足够多的文字来可靠地识别语言。",+ ),+ ],+)+async def test_gross_wrong_language_blocks_all_buffered_pcm(+ language: str,+ text: str,+) -> None:+ gate = ScrubHoldGate(language=language)+ buffered = _chunk(16)++ assert await gate.push_audio(buffered) == []+ assert await gate.feed_transcript(+ text,+ enforce_output_language=True,+ ) == gate.fallback_phrase()++ assert gate.hard_leak_pending() is True+ assert gate.hard_leak_actions() == ("output_language_mismatch",)+ assert gate.pending_audio_ms == 0.0+ assert gate.release_available() == []+++async def test_indeterminate_language_prefix_never_releases_pcm_before_mismatch():+ gate = ScrubHoldGate(language="en")+ buffered = _chunk(16)++ assert await gate.push_audio(buffered) == []+ assert await gate.feed_transcript(+ "Das ist", # i18n-allow+ enforce_output_language=True,+ ) == "Das ist" # i18n-allow+ assert gate.release_available() == []++ display = await gate.feed_transcript(+ " eine klare deutsche Antwort mit vielen normalen Woertern.", # i18n-allow+ enforce_output_language=True,+ )++ assert display == gate.fallback_phrase()+ assert gate.hard_leak_actions() == ("output_language_mismatch",)+ assert gate.release_available() == []+++async def test_complete_indeterminate_reply_releases_only_at_final_boundary():+ gate = ScrubHoldGate(language="en")+ buffered = _chunk(16)++ assert await gate.push_audio(buffered) == []+ assert await gate.feed_transcript(+ "OK",+ enforce_output_language=True,+ ) == "OK"+ assert gate.release_available() == []++ assert gate.finalize() == [buffered]++@pytest.mark.asyncioasync def test_clean_transcript_releases_buffered_audio():gate = ScrubHoldGate(language="en")diff --git a/tests/unit/realtime/test_session.py b/tests/unit/realtime/test_session.pyindex 41374622b1..b2f29698db 100644--- a/tests/unit/realtime/test_session.py+++ b/tests/unit/realtime/test_session.py@@ -6,6 +6,7 @@ from jarvis.brain.output_filter import scrub_for_voicefrom jarvis.brain.tool_gateway import BrainSupervisorToolGatewayfrom jarvis.core import runtime_refsfrom jarvis.core.events import (+ AnnouncementRequested,LatencyPhase,LatencySpan,ResponseGenerated,@@ -1033,7 +1034,10 @@ async def test_audio_after_a_leak_transcript_is_never_emitted():RealtimeEvent(type="audio_delta", audio=AudioChunk(pcm=a1, sample_rate=24000, timestamp_ns=0)),- RealtimeEvent(type="output_transcript_delta", text="A clean first sentence."),+ RealtimeEvent(+ type="output_transcript_delta",+ text="This is the normal English opening for the user.",+ ),RealtimeEvent(type="audio_delta", audio=AudioChunk(pcm=a2, sample_rate=24000, timestamp_ns=0)),@@ -1796,17 +1800,33 @@ async def test_end_call_tool_finishes_after_turn_complete():@pytest.mark.asyncio-async def test_ordinary_speech_does_not_hang_up():- provider = FakeProvider(- [- RealtimeEvent(+async def test_ordinary_speech_does_not_hang_up(monkeypatch):+ monkeypatch.setattr(+ runtime_refs,+ "get_supervisor_tool_gateway",+ lambda: None,+ )++ class _WaitForSafeGroundingFallbackSession(FakeSession):+ async def receive(self):+ yield RealtimeEvent(type="input_transcript",text="wie ist das wetter heute", # i18n-allow: ordinary speech guardis_final=True,- ),- RealtimeEvent(type="turn_complete"),- ]- )+ )+ for _ in range(100):+ if self.text_inputs:+ break+ await asyncio.sleep(0.01)+ yield RealtimeEvent(type="turn_complete")++ class _WaitForSafeGroundingFallbackProvider(FakeProvider):+ async def open_session(self, cfg):+ self.opened_with = cfg+ self.session = _WaitForSafeGroundingFallbackSession([])+ return self.session++ provider = _WaitForSafeGroundingFallbackProvider([])jsons = []sess = RealtimeVoiceSession(session_id="hangup-guard",@@ -1823,7 +1843,112 @@ async def test_ordinary_speech_does_not_hang_up():assert sess.hangup_reason == ""assert _hangup_jsons(jsons) == []- assert provider.session.response_requests == 1+ assert provider.session.response_requests == 0+ assert provider.session.text_inputs+ assert "couldn't verify that reliably" in provider.session.text_inputs[-1]+++ ("language", "user_text", "wrong_text", "correct_text"),+ [+ (+ "en",+ "What is kindness?",+ "Xin chào, đây là câu trả lời bằng tiếng Việt với nhiều từ rõ "+ "ràng để xác định ngôn ngữ.",+ "Kindness is the practice of treating other people with care "+ "and respect.",+ ),+ (+ "de",+ "Was ist Freundlichkeit?", # i18n-allow+ "这是一个完整的中文回答,包含足够多的文字来可靠地识别语言。",+ "Freundlichkeit bedeutet, andere Menschen mit Fürsorge und " # i18n-allow+ "Respekt zu behandeln.", # i18n-allow+ ),+ ],+)+async def test_wrong_output_language_retries_once_before_releasing_pcm(+ language: str,+ user_text: str,+ wrong_text: str,+ correct_text: str,+):+ wrong_pcm = b"\x02\x03" * 32+ correct_pcm = b"\x10\x20" * 32++ class _LanguageRetrySession(FakeSession):+ async def receive(self):+ yield RealtimeEvent(+ type="input_transcript",+ text=user_text,+ is_final=True,+ )+ yield RealtimeEvent(+ type="audio_delta",+ audio=AudioChunk(+ pcm=wrong_pcm,+ sample_rate=24_000,+ timestamp_ns=0,+ ),+ )+ yield RealtimeEvent(+ type="output_transcript_delta",+ text=wrong_text,+ )+ for _ in range(100):+ if self.response_requests >= 2:+ break+ await asyncio.sleep(0.01)+ yield RealtimeEvent(+ type="output_transcript_delta",+ text=correct_text,+ )+ yield RealtimeEvent(+ type="audio_delta",+ audio=AudioChunk(+ pcm=correct_pcm,+ sample_rate=24_000,+ timestamp_ns=0,+ ),+ )+ yield RealtimeEvent(type="turn_complete")++ class _LanguageRetryProvider(FakeProvider):+ async def open_session(self, cfg):+ self.opened_with = cfg+ self.session = _LanguageRetrySession([])+ return self.session++ provider = _LanguageRetryProvider([])+ jsons: list[dict] = []+ binaries: list[bytes] = []+ sess = RealtimeVoiceSession(+ session_id=f"language-retry-{language}",+ send_binary=lambda data: binaries.append(data) or asyncio.sleep(0),+ send_json=lambda message: jsons.append(message) or asyncio.sleep(0),+ provider=provider,+ config=_cfg(reply_language=language),+ bus=None,+ )++ await sess.handle_control({"type": "audio_start", "sample_rate": 16_000})+ await sess.wait_finished()+ await sess.end(reason="test")++ assert provider.session.response_requests == 2+ assert provider.session.interrupts == 1+ assert binaries == [correct_pcm]+ assert [+ item["text"]+ for item in jsons+ if item.get("type") == "transcript"+ and item.get("role") == "assistant"+ ] == [correct_text]+ assert sess._output_language_mismatches == 1 # noqa: SLF001+ assert sess._output_language_retries == 1 # noqa: SLF001+ assert sess._output_language_failures == 0 # noqa: SLF001@pytest.mark.asyncio@@ -2041,6 +2166,89 @@ async def test_delegate_mode_declares_single_action_function():assert "MCPs" in provider.opened_with.instructions+async def test_local_public_fact_uses_exactly_one_supervisor_search(+ wire_supervisor_gateway,+):+ class _SearchTool(_StubTool):+ name = "search_web"+ description = "Search public web sources."+ risk_tier = "safe"++ class _RecordingSearchExecutor:+ def __init__(self):+ self.calls = []++ async def execute(self, tool, arguments, **kwargs):+ self.calls.append((tool, arguments, kwargs))+ return ToolResult(+ success=True,+ output={+ "status": "ok",+ "results": [+ {+ "title": "Public source",+ "url": "https://example.test/source",+ "snippet": "Ada Lovelace was born in 1815.",+ }+ ],+ },+ )++ class _GroundingBrain(FakeBrain):+ def __init__(self):+ super().__init__()+ self.run_task_calls = []++ async def run_task(self, **kwargs):+ self.run_task_calls.append(kwargs)+ return "Ada Lovelace was born in 1815 according to the source."++ class _GroundedResultSession(FakeSession):+ async def receive(self):+ yield RealtimeEvent(+ type="input_transcript",+ text="When was Ada Lovelace born?",+ is_final=True,+ )+ for _ in range(100):+ if self.text_inputs:+ break+ await asyncio.sleep(0.01)+ yield RealtimeEvent(type="turn_complete")++ class _LocalFactProvider(FakeProvider):+ requires_public_fact_grounding = True++ async def open_session(self, cfg):+ self.opened_with = cfg+ self.session = _GroundedResultSession([])+ return self.session++ brain = _GroundingBrain()+ brain._tools = {"search_web": _SearchTool()}+ executor = _RecordingSearchExecutor()+ wire_supervisor_gateway(brain, executor)+ provider = _LocalFactProvider([])+ sess = _session(provider, brain=brain)++ await sess.handle_control({"type": "audio_start", "sample_rate": 16_000})+ await sess.wait_finished()+ await sess.end(reason="test")++ assert len(executor.calls) == 1+ assert executor.calls[0][1] == {+ "query": "When was Ada Lovelace born?",+ "max_results": 5,+ }+ assert len(brain.run_task_calls) == 1+ assert brain.run_task_calls[0]["allowed_tools"] == ()+ assert brain.calls == []+ assert len(provider.session.text_inputs) == 1+ assert "Ada Lovelace was born" in provider.session.text_inputs[0]+ assert "according to the source" in provider.session.text_inputs[0]++@pytest.mark.asyncioasync def test_direct_mode_uses_delegate_when_provider_cannot_declare_tools():"""A capability-limited subscription transport must keep actions usable."""@@ -2527,7 +2735,7 @@ async def test_generative_voice_provider_delegate_reply_renders_natively_on_deskawait sess.handle_control({"type": "audio_start", "sample_rate": 16_000})async def _played():- while not binaries:+ while not binaries: # noqa: ASYNC110 - callback exposes no wait handleawait asyncio.sleep(0.01)await asyncio.wait_for(_played(), timeout=5)@@ -2563,7 +2771,9 @@ async def test_generative_voice_provider_mute_still_falls_back_to_surface_tts():await sess.handle_control({"type": "audio_start", "sample_rate": 16_000})async def _spoken():- while not any(m.get("type") == "error_spoken" for m in jsons):+ while not any( # noqa: ASYNC110 - callback exposes no wait handle+ m.get("type") == "error_spoken" for m in jsons+ ):await asyncio.sleep(0.01)# Must take at least the readback wait window (2.5 s) — an immediate@@ -2610,7 +2820,7 @@ async def test_generative_voice_provider_keeps_native_readback_on_the_browser_suawait sess.handle_control({"type": "audio_start", "sample_rate": 16_000})async def _played():- while not binaries:+ while not binaries: # noqa: ASYNC110 - callback exposes no wait handleawait asyncio.sleep(0.01)await asyncio.wait_for(_played(), timeout=5)@@ -2657,7 +2867,7 @@ async def test_generative_voice_readback_race_never_speaks_twice():await sess.handle_control({"type": "audio_start", "sample_rate": 16_000})async def _one_rendering():- while not binaries and not any(+ while not binaries and not any( # noqa: ASYNC110 - two callback outcomesm.get("type") == "error_spoken" for m in jsons):await asyncio.sleep(0.01)@@ -3091,6 +3301,181 @@ async def test_action_result_that_outlived_its_turn_is_still_spoken():await sess.end(reason="test")+async def test_end_mid_delegate_delivers_exactly_once_without_rerunning_action():+ """Socket teardown must not cancel, lose, or repeat an executing action."""+ dispatch_started = asyncio.Event()+ release_action = asyncio.Event()++ class _BlockingBrain(FakeBrain):+ async def generate(self, text, **kwargs):+ dispatch_started.set()+ return await super().generate(text, **kwargs)++ class _OpenUntilEndedSession(FakeSession):+ async def receive(self):+ yield RealtimeEvent(+ type="input_transcript",+ text="Write the status to my wiki.",+ is_final=True,+ )+ await asyncio.Event().wait()++ class _OpenUntilEndedProvider(FakeProvider):+ async def open_session(self, cfg):+ self.opened_with = cfg+ self.session = _OpenUntilEndedSession([])+ return self.session++ brain = _BlockingBrain(+ replies=("The requested wiki update completed successfully.",),+ gate=release_action,+ )+ bus = FakeBus()+ provider = _OpenUntilEndedProvider([])+ sess = _session(provider, brain=brain, bus=bus)++ await sess.handle_control({"type": "audio_start", "sample_rate": 16_000})+ await asyncio.wait_for(dispatch_started.wait(), timeout=2)+ turn_id, turn_state = next(iter(sess._delegate_turns.items())) # noqa: SLF001++ await asyncio.wait_for(sess.end(reason="test"), timeout=5)+ assert brain.cancelled is False++ release_action.set()+ for _ in range(100):+ announcements = [+ event+ for event in bus.events+ if isinstance(event, AnnouncementRequested)+ and event.kind == "completion"+ ]+ if announcements:+ break+ await asyncio.sleep(0.01)++ assert len(brain.calls) == 1+ assert len(announcements) == 1+ assert announcements[0].text == (+ "The requested wiki update completed successfully."+ )++ # A late duplicate callback may observe the same completed state, but the+ # stable delivery id owns the claim and cannot publish a second result.+ assert not await sess._deliver_detached_delegate_result( # noqa: SLF001+ turn_id,+ turn_state,+ )+ assert len(+ [+ event+ for event in bus.events+ if isinstance(event, AnnouncementRequested)+ and event.kind == "completion"+ ]+ ) == 1+++async def test_failed_surface_claim_recovers_once_in_originating_language():+ from jarvis.realtime.session import _DelegateTurnState++ async def _failed_surface_send(_message):+ raise RuntimeError("surface disconnected")++ bus = FakeBus()+ binaries = []+ sess = RealtimeVoiceSession(+ session_id="surface-recovery",+ send_binary=lambda data: binaries.append(data) or asyncio.sleep(0),+ send_json=_failed_surface_send,+ provider=FakeProvider([]),+ config=_cfg(reply_language="en"),+ bus=bus,+ )+ state = _DelegateTurnState(+ last_reply="Das Ergebnis wurde erfolgreich gespeichert.", # i18n-allow+ result_complete=True,+ result_success=True,+ language="de",+ delivery_id="surface-recovery:turn-1",+ )++ assert not await sess._send_delegate_surface_fallback( # noqa: SLF001+ state,+ state.last_reply,+ )+ assert state.surface_fallback_confirmed is False+ assert state.delivery_completed is True+ assert state.delivery_channel == "detached"++ assert not await sess._deliver_detached_delegate_result( # noqa: SLF001+ "turn-1",+ state,+ )+ announcements = [+ event for event in bus.events if isinstance(event, AnnouncementRequested)+ ]+ assert len(announcements) == 1+ assert announcements[0].language == "de"+ assert announcements[0].text == state.last_reply+ sess._turn_id = "turn-1" # noqa: SLF001+ sess._delegate_turns["turn-1"] = state # noqa: SLF001+ await sess._emit_audio( # noqa: SLF001+ AudioChunk(+ pcm=b"\x10\x00" * 160,+ sample_rate=24_000,+ timestamp_ns=0,+ )+ )+ assert binaries == []+++async def test_provider_audio_is_blocked_as_soon_as_teardown_begins():+ binaries = []+ sess = _session(FakeProvider([]), binaries=binaries)+ sess._ended = True # noqa: SLF001++ await sess._emit_audio( # noqa: SLF001+ AudioChunk(+ pcm=b"\x10\x00" * 160,+ sample_rate=24_000,+ timestamp_ns=0,+ )+ )++ assert binaries == []+++async def test_tagged_provider_response_rejects_later_untagged_transcript():+ sess = _session(FakeProvider([]))+ tagged_audio = RealtimeEvent(+ type="audio_delta",+ audio=AudioChunk(+ pcm=b"\x10\x00" * 160,+ sample_rate=24_000,+ timestamp_ns=0,+ ),+ provider_turn_id="response-a",+ )++ assert await sess._accept_provider_response_event(tagged_audio) # noqa: SLF001+ assert await sess._gate.push_audio( # noqa: SLF001+ tagged_audio.audio,+ response_id="response-a",+ ) == []+ assert not await sess._accept_provider_response_event( # noqa: SLF001+ RealtimeEvent(+ type="output_transcript_delta",+ text="Stale transcript without an owner.",+ )+ )+ assert sess._gate.release_available() == [] # noqa: SLF001+ assert sess._response_identity_drops == 1 # noqa: SLF001++@pytest.mark.asyncioasync def test_turn_after_a_pending_action_may_not_claim_an_outcome():gate = asyncio.Event()@@ -3482,7 +3867,7 @@ async def test_blocked_action_promise_still_dispatches_after_boundary_timeout(await sess.handle_control({"type": "audio_start", "sample_rate": 16_000})async with asyncio.timeout(2):- while not provider.session.text_inputs:+ while not provider.session.text_inputs: # noqa: ASYNC110 - fake has no eventawait asyncio.sleep(0.01)assert brain.calls, "the recovery must dispatch the brain turn"@@ -3549,7 +3934,7 @@ class _PreemptedDelegateBridgeSession(FakeSession):async def receive(self):yield RealtimeEvent(type="input_transcript",- text="Check the current figure.",+ text="Check my current wiki status.",is_final=True,)await self._bridge_sent.wait()@@ -5368,12 +5753,13 @@ async def test_presence_check_without_pending_action_stays_native():@pytest.mark.asyncio-async def test_session_end_names_the_delegated_request_it_cancels(caplog):- """A hangup mid-action must leave a trace of the answer it discarded."""+async def test_session_end_names_the_delegated_request_it_retains(caplog):+ """A hangup mid-action must name and retain the result delivery debt."""import logging as _logging- gate = asyncio.Event() # never set: the delegated action never finishes+ gate = asyncio.Event()brain = FakeBrain(gate=gate)+ bus = FakeBus()provider = FakeProvider([RealtimeEvent(@@ -5384,11 +5770,11 @@ async def test_session_end_names_the_delegated_request_it_cancels(caplog):RealtimeEvent(type="turn_complete"),])- sess = _session(provider, brain=brain)+ sess = _session(provider, brain=brain, bus=bus)await sess.handle_control({"type": "audio_start", "sample_rate": 16_000})await sess.wait_finished()- with caplog.at_level(_logging.WARNING, logger="jarvis.realtime.session"):+ with caplog.at_level(_logging.INFO, logger="jarvis.realtime.session"):await sess.end(reason="hotkey")lost = [@@ -5398,6 +5784,17 @@ async def test_session_end_names_the_delegated_request_it_cancels(caplog):]assert len(lost) == 1assert "travel plan" in lost[0].getMessage()+ assert "retaining it for exactly-once delivery" in lost[0].getMessage()+ assert brain.cancelled is False++ gate.set()+ for _ in range(100):+ if any(isinstance(event, AnnouncementRequested) for event in bus.events):+ break+ await asyncio.sleep(0.01)+ assert len(+ [event for event in bus.events if isinstance(event, AnnouncementRequested)]+ ) == 1# ---------------------------------------------------------------------------@@ -5480,7 +5877,7 @@ class RebuildingProvider(FakeProvider):async def _wait_until(predicate):async with asyncio.timeout(2):- while not predicate():+ while not predicate(): # noqa: ASYNC110 - shared bounded test helperawait asyncio.sleep(0.01)diff --git a/tests/unit/realtime/test_session_postmortem.py b/tests/unit/realtime/test_session_postmortem.pyindex 8fe5530f45..27341e8933 100644--- a/tests/unit/realtime/test_session_postmortem.py+++ b/tests/unit/realtime/test_session_postmortem.py@@ -145,6 +145,17 @@ async def test_end_publishes_one_postmortem_with_adapter_counters() -> None:session._handoff_requests = 1 # noqa: SLF001 - postmortem inputssession._handoff_delegate_dispatches = 2 # noqa: SLF001 - postmortem inputssession._handoff_declines = 1 # noqa: SLF001 - postmortem inputs+ session._public_fact_grounding_attempts = 2 # noqa: SLF001+ session._public_fact_grounding_successes = 1 # noqa: SLF001+ session._public_fact_grounding_failures = 1 # noqa: SLF001+ session._output_language_mismatches = 2 # noqa: SLF001+ session._output_language_retries = 1 # noqa: SLF001+ session._output_language_failures = 1 # noqa: SLF001+ session._delegate_delivery_claims = 2 # noqa: SLF001+ session._delegate_deliveries_completed = 1 # noqa: SLF001+ session._delegate_delivery_recoveries = 1 # noqa: SLF001+ session._delegate_delivery_duplicates_suppressed = 1 # noqa: SLF001+ session._delegate_deliveries_detached = 1 # noqa: SLF001await asyncio.wait_for(session.end(reason="hotkey"), TIMEOUT_S)@@ -161,6 +172,17 @@ async def test_end_publishes_one_postmortem_with_adapter_counters() -> None:assert event.handoff_delegate_dispatches == 2assert event.handoff_declines == 1assert event.handoff_obligation_misses == 1+ assert event.public_fact_grounding_attempts == 2+ assert event.public_fact_grounding_successes == 1+ assert event.public_fact_grounding_failures == 1+ assert event.output_language_mismatches == 2+ assert event.output_language_retries == 1+ assert event.output_language_failures == 1+ assert event.delegate_delivery_claims == 2+ assert event.delegate_deliveries_completed == 1+ assert event.delegate_delivery_recoveries == 1+ assert event.delegate_delivery_duplicates_suppressed == 1+ assert event.delegate_deliveries_detached == 1assert event.ready_ms >= 0assert event.close_clean is Truediff --git a/tests/unit/realtime/test_session_response_identity_recovery.py b/tests/unit/realtime/test_session_response_identity_recovery.pyindex 0894104936..0c600f44f2 100644--- a/tests/unit/realtime/test_session_response_identity_recovery.py+++ b/tests/unit/realtime/test_session_response_identity_recovery.py@@ -237,6 +237,37 @@ async def test_a_superseding_response_completes_the_provisional_one() -> None:assert session._response_identity_drops == 1+async def test_transport_rebuild_resets_response_identity_scope() -> None:+ """Tagged ids from a dead wire cannot poison its replacement transport."""+ session = _session()+ provider = session._providers[0] # noqa: SLF001 - contract fixture+ provider.rebuild_on_transport_death = True+ await session._open()+ try:+ assert await session._accept_provider_response_event(+ _audio_event("reused-id")+ )+ assert await session._accept_provider_response_event(+ RealtimeEvent(type="turn_complete", provider_turn_id="reused-id")+ )+ assert session._provider_response_identity_required is True+ assert "reused-id" in session._completed_provider_response_ids++ assert await session._rebuild_transport(detail="identity scope test")++ assert session._provider_response_identity_required is False+ assert not session._completed_provider_response_ids+ assert not session._provisional_response_retirements+ assert await session._accept_provider_response_event(+ _audio_event("")+ ), "an ordered untagged replacement transport must remain compatible"+ assert await session._accept_provider_response_event(+ _audio_event("reused-id")+ ), "a fresh transport may reuse an id from the dead transport"+ finally:+ await session.end(reason="test")++async def test_the_readoption_window_expires() -> None:"""Patience is bounded by the provider's own declared render budget."""session = _session()diff --git a/tests/unit/test_provider_spec.py b/tests/unit/test_provider_spec.pyindex 02e677efe0..b98e7a4936 100644--- a/tests/unit/test_provider_spec.py+++ b/tests/unit/test_provider_spec.py@@ -140,19 +140,6 @@ def test_provider_spec_is_frozen_dataclass() -> None:raise AssertionError("ProviderSpec should be frozen")-def test_public_fact_grounding_is_declared_as_a_capability() -> None:- """Self-hosted small-model surfaces ground facts without id branches."""- for provider_id in ("ollama", "local-openai", "local-realtime"):- spec = get_spec(provider_id)- assert spec is not None- assert spec.requires_public_fact_grounding is True-- for provider_id in ("gemini", "openai", "openai-realtime", "gemini-live"):- spec = get_spec(provider_id)- assert spec is not None- assert spec.requires_public_fact_grounding is False--# ── New: per-provider credential help + billing classification ───────────────diff --git a/tests/unit/ui/test_provider_spec_codex_subscription_realtime.py b/tests/unit/ui/test_provider_spec_codex_subscription_realtime.pyindex 3ec3c8741b..9e8246e680 100644--- a/tests/unit/ui/test_provider_spec_codex_subscription_realtime.py+++ b/tests/unit/ui/test_provider_spec_codex_subscription_realtime.py@@ -776,7 +776,7 @@ def test_install_hint_pins_the_supported_release() -> None:unpin would send users to a version the trust gate rejects."""spec = get_spec("codex-subscription-realtime")assert spec is not None- assert spec.install_hint == "npm i -g @openai/[email protected]"+ assert spec.install_hint == "npm i -g @openai/[email protected]"def test_reason_code_vocabulary_is_pinned() -> None: