Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
chore: auto-save WIP via Claude stop-hook safety net (2026-07-06 20:13)
Ruben Lütke4bc56ae53a52
diff --git a/jarvis/brain/ack_brain/config.py b/jarvis/brain/ack_brain/config.pyindex 8a126ac617..74d4326bdb 100644--- a/jarvis/brain/ack_brain/config.py+++ b/jarvis/brain/ack_brain/config.py@@ -116,13 +116,29 @@ class AckBrainConfig(BaseModel):# grounded acks (manager-wide, across utterances). Within the gap the# emitter stays silent: Jarvis just said it is working; saying it again# seconds later is noise. 0 restores the legacy per-turn-only guard.- grounded_ack_min_gap_s: int = Field(default=20, ge=0, le=600)+ # v2 (contextual interim voice): 20 -> 30 s — interim lines are meant to+ # be RARE, only bridging genuinely long waits.+ grounded_ack_min_gap_s: int = Field(default=30, ge=0, le=600)# Usefulness gate for the grounded ack at the speech layer: when the# announcement arrives while a voice turn is in PROCESSING, the pipeline# waits this long (AD-OE5 commit-grace helper) and only speaks the ack if# the brain is STILL busy — a turn that answers quickly stays ack-free.- # 0 restores speak-immediately.- grounded_ack_commit_grace_ms: int = Field(default=900, ge=0, le=5000)+ # 0 restores speak-immediately. v2: 900 -> 2500 ms; with tool selection+ # ~3-5 s into a deep turn the line speaks ~6-8 s in, so any turn that+ # answers sooner stays completely silent (necessity = the actual wait).+ grounded_ack_commit_grace_ms: int = Field(default=2500, ge=0, le=5000)+ # Contextual Interim Voice (2026-07-06 v2 spec): compose the grounded+ # interim line per-turn via the ReadbackComposer flash path (user request+ # + concrete action), with the deterministic phrase pool as the instant+ # fallback. False = pools only (v1 behavior); automatically inert on a+ # keyless install (the composer reports has_llm=False).+ contextual_interim: bool = Field(default=True)+ # Anti-loop backstop at the speech layer: hard cap on SPOKEN+ # preamble/progress lines per rolling 60 s window, any source. The+ # historical "kept saying it forever" bug class dies at this chokepoint+ # regardless of which emitter misbehaves. Completion/interrupt readbacks+ # are exempt (owed answers). 0 disables the cap.+ preamble_rate_limit_per_min: int = Field(default=3, ge=0, le=60)# Duplicate-text safety net at the speech layer: a preamble/progress-class# announcement whose (scrubbed) text is identical to the previously spoken# preamble/progress line within this window is dropped — no source maydiff --git a/jarvis/brain/ack_generator.py b/jarvis/brain/ack_generator.pyindex 71a21b8b58..54782ed418 100644--- a/jarvis/brain/ack_generator.py+++ b/jarvis/brain/ack_generator.py@@ -49,6 +49,7 @@ from typing import Any__all__ = ["ACK_SKIP_TOOLS","AckPhrasePicker",+ "describe_tool_action","final_summary_marker","generate_ack","is_voice_control_utterance",@@ -747,6 +748,81 @@ def generate_ack(return chooser.pick(_GENERIC_ACK[lang])+def describe_tool_action(+ tool_name: str, tool_args: Mapping[str, Any] | None = None+) -> str:+ """Compact ENGLISH description of what the tool call is about to do.++ Prompt input for the contextual interim composer (`ReadbackComposer`),+ NOT product surface — the composer answers in the resolved turn language.+ Extracts the most informative arg (query / app / skill / CLI service)+ without ever echoing raw shell commands. Total: never raises; unknown+ tools get a neutral "working on the request".+ """+ norm = _normalize_tool_name(tool_name)+ args: Mapping[str, Any] = tool_args or {}++ def _arg(*names: str, max_len: int = 60) -> str:+ for name in names:+ try:+ value = str(args.get(name) or "").strip()+ except Exception: # noqa: BLE001 — garbage args must not break the ack+ value = ""+ if value:+ return _trim_to_words(value, max_len)+ return ""++ try:+ if norm.startswith("cli_") and norm != "cli_tools":+ suffix = norm[len("cli_"):].strip("_")+ service = _CLI_SERVICE_NAMES.get(+ suffix, suffix.replace("_", " ").title()+ )+ return f"querying {service}" if service else "running a quick lookup"+ if norm == "search_web":+ query = _arg("query", "q")+ return (+ f"running a web search for {query!r}" if query+ else "running a web search"+ )+ if norm in ("run_shell", "cli_tools"):+ return "running a quick check on the computer"+ if norm in ("dispatch_to_harness", "dispatch_with_review",+ "spawn_sub_jarvis", "spawn_worker"):+ return "handing the task to a background helper"+ if norm == "multi_spawn":+ tasks = args.get("tasks") or args.get("jobs") or []+ n = len(tasks) if isinstance(tasks, (list, tuple)) else 0+ return (+ f"starting {n} tasks in parallel" if n >= 2+ else "starting background tasks"+ )+ if norm == "open_app":+ app = _arg("app", "app_name", "name", max_len=30)+ return f"opening {app}" if app else "opening an application"+ if norm == "run_skill":+ skill = _arg("skill", "skill_name", "name", max_len=40)+ return f"running the {skill} routine" if skill else "running a routine"+ if norm == "gmail":+ action = str(args.get("action") or "list_messages").strip()+ if action == "send_message":+ return "preparing an email"+ return "fetching the user's email"+ if norm == "google_calendar":+ return "checking the user's calendar"+ if norm == "remember":+ return "saving a note to memory"+ if norm in ("verify_via_curl", "verify_localhost"):+ return "verifying the result"+ if norm == "start_preview_server":+ return "starting the preview server"+ if norm == "set_config_value":+ return "updating a setting"+ except Exception: # noqa: BLE001 — a description bug must not mute the ack+ pass+ return "working on the request"++def final_summary_marker(language: str = "de") -> str:"""Return the short completion phrase ('Erledigt.' / 'Done.')."""return _FINAL_MARKERS[_normalize_language(language)]diff --git a/jarvis/brain/manager.py b/jarvis/brain/manager.pyindex c7bc92cca7..ecbbb47a0d 100644--- a/jarvis/brain/manager.py+++ b/jarvis/brain/manager.py@@ -701,7 +701,11 @@ _INHERITABLE_ACTION_TOOL_NAMES: frozenset[str] = _SPAWN_TOOL_NAMES | {"computer_# reads never regress. The background wiki (VoiceFactBridge) is untouched — it is# not a model-callable tool (AP-9)._DETERMINISTIC_WRITE_TOOL_NAMES: frozenset[str] = frozenset({- "contact-upsert", "update-profile", "wiki-ingest", "google_calendar",+ # Keys are the tools' .name attributes (what the turn dict is keyed by) —+ # NOT the hyphenated entry-point names. "update-profile" (the ep name)+ # sat here since introduction, so the signalless gate never actually+ # stripped update_profile (found in the 2026-07-06 pipeline audit).+ "contact-upsert", "update_profile", "wiki-ingest", "google_calendar","call-contact",})@@ -1699,6 +1703,28 @@ def _provider_down_phrase(lang: str, idx: int) -> str:return variants[idx % len(variants)]+# AD-OE6: a model round that dies AFTER tools already ran must end in an honest+# spoken notice, never silence. Forensic 2026-07-05 (session 3e27dd8e): the+# provider sent finish_reason="error" on a ~224k-token round following 10++# executed tools; the empty-response guard is (correctly) skipped when tool+# calls exist, so the turn counted as success with empty text — the user heard+# NOTHING. Voice-safe: no provider names, no jargon (ADR-0010).+_MID_ANSWER_ERROR_PHRASES: dict[str, str] = {+ "de": (+ "Ich habe die Zwischenschritte ausgeführt, aber beim Formulieren der " # i18n-allow+ "Antwort gab es einen Fehler. Frag mich bitte gleich noch einmal." # i18n-allow+ ),+ "en": (+ "I ran the steps, but something went wrong while composing the answer. "+ "Please ask me again in a moment."+ ),+ "es": (+ "Ejecuté los pasos, pero algo falló al redactar la respuesta. "+ "Vuelve a preguntarme en un momento."+ ),+}++class BrainManager:"""Top-level orchestrator with intent router and smart fallback."""@@ -2326,32 +2352,46 @@ class BrainManager:Returns an async callback the tool-use loop awaits ONCE, the moment therouter brain has actually SELECTED a tool call — so the otherwise-silent- tool-execution + readback window speaks a short, deterministic, LLM-free- line ("Okay, ich schaue in deine Mails."). This bridges the wait on slow- plugin turns (e.g. a cold email/calendar fetch) where the persona forbids- any spoken preamble before the tool and round-2 has not started yet.+ tool-execution + readback window speaks a short interim line. This+ bridges the wait on slow turns (e.g. a cold email/calendar fetch, a+ multi-tool research) where the persona forbids any spoken preamble+ before the tool and round-2 has not started yet.++ Contextual Interim Voice (2026-07-06 v2 spec): when the manager's+ ``ReadbackComposer`` has a live flash provider, the spoken text is+ COMPOSED for this exact turn (user request + concrete action) instead+ of drawn from a phrase pool — the pool line remains only as the+ instant deterministic fallback (keyless install, breaker open,+ timeout, rejected output). Composition + publish run fire-and-forget+ so the tool-use loop is never delayed; ``[ack_brain].contextual_interim+ = false`` is the kill switch back to pools-only.Returns ``None`` when there is no bus, the feature is off(``[ack_brain].grounded_tool_ack = false``), or the utterance is aVoice-Control command (the action itself is the confirmation).GROUNDED, not speculative: unlike the retired Flash-Brain preamble it- fires only after a real tool decision, never on suspicion. The words are- rendered by ``generate_ack`` (skip-list-aware, so passive reads / low-- latency UI events stay silent) and the language is re-resolved and- re-scrubbed authoritatively at the speech layer, so the reply-language- pin and conversation stickiness still win there. Publishing with- ``source_layer="brain.router.ack"`` means the existing pipeline guard- keeps "one ack per turn" when a machine re-enables the Flash-Brain- preamble (``jarvis/speech/pipeline.py`` drops this source while the- Flash-Brain is active); with the preamble off (the default) it is heard.+ fires only after a real tool decision, never on suspicion. The fallback+ words are rendered by ``generate_ack`` (skip-list-aware, so passive+ reads / low-latency UI events stay silent) and the language is+ re-resolved and re-scrubbed authoritatively at the speech layer, so the+ reply-language pin and conversation stickiness still win there.+ Publishing with ``source_layer="brain.router.ack"`` keeps every+ pipeline gate on this source: the necessity commit-grace (speak only if+ the brain is STILL busy), duplicate-wording dedup, the rate-limit+ backstop, and the legacy one-ack-per-turn drop while the Flash-Brain+ preamble is active."""if self._bus is None:return Noneack_cfg = getattr(self._config, "ack_brain", None) if self._config else Noneif not getattr(ack_cfg, "grounded_tool_ack", True):return None- from .ack_generator import generate_ack, is_voice_control_utterance+ from .ack_generator import (+ describe_tool_action,+ generate_ack,+ is_voice_control_utterance,+ )if is_voice_control_utterance(user_text):return None@@ -2387,20 +2427,75 @@ class BrainManager:"(min gap %.0fs)", time.monotonic() - last, min_gap_s,)return- text = generate_ack(tool_name, tool_args, language=language)- if text is None: # skip-list tool (passive read / UI micro-event)+ canned_text = generate_ack(tool_name, tool_args, language=language)+ if canned_text is None: # skip-list tool (passive read / UI micro-event)returnfired = Trueself._last_grounded_ack_monotonic = time.monotonic()- await bus.publish(- AnnouncementRequested(- text=text,- priority="normal",- language=language,- kind="preamble",- source_layer="brain.router.ack",++ async def _publish(text: str) -> None:+ await bus.publish(+ AnnouncementRequested(+ text=text,+ priority="normal",+ language=language,+ kind="preamble",+ source_layer="brain.router.ack",+ ))- )++ composer = getattr(self, "_readback_composer", None)+ contextual = bool(getattr(ack_cfg, "contextual_interim", True))+ if not (contextual and bool(getattr(composer, "has_llm", False))):+ # Deterministic path (keyless install / kill switch): publish+ # inline — sub-millisecond, the historical contract.+ await _publish(canned_text)+ return++ action = describe_tool_action(tool_name, tool_args)++ async def _compose_and_publish() -> None:+ # Runs detached: composition must never delay tool execution+ # (the loop already moved on) and must never raise. The+ # pipeline's commit-grace re-checks necessity AFTER this+ # composition lands, so the flash latency costs nothing.+ text = canned_text+ try:+ from jarvis.voice.contextual_readback import ( # noqa: PLC0415+ render_readback,+ )+ text = await render_readback(+ composer,+ instruction=(+ f"You have JUST started {action} to answer the "+ "user's request and it is taking a moment. In one "+ "short sentence, tell the user what you are doing "+ "RIGHT NOW, tied to their actual topic — an "+ "in-progress bridge line, never a result."+ ),+ language=language,+ canned=lambda: canned_text,+ facts={+ "user_request": user_text[:200],+ "current_action": action,+ },+ in_progress=True,+ latency_budget_ms=1200,+ )+ except Exception as exc: # noqa: BLE001 — fall back to the pool line+ log.debug("Contextual interim compose failed: %s", exc)+ try:+ await _publish(text)+ except Exception as exc: # noqa: BLE001 — a publish fault must die here+ log.warning("Interim ack publish failed: %s", exc)++ tasks = getattr(self, "_interim_ack_tasks", None)+ if tasks is None:+ tasks = set()+ self._interim_ack_tasks = tasks+ task = asyncio.create_task(_compose_and_publish())+ tasks.add(task)+ task.add_done_callback(tasks.discard)return emit@@ -6937,6 +7032,29 @@ class BrainManager:continueresponse_text = agg.text+ # Honest mid-answer error notice (AD-OE6): the model round+ # AFTER tool execution died mid-stream (the provider sent+ # finish_reason="error") and produced no text. The empty-+ # response guard above is correctly skipped when tool calls+ # exist, so without this branch the turn counts as a success+ # with empty text and the user hears NOTHING (forensic+ # 2026-07-05, session 3e27dd8e, 223k-token round). Do NOT+ # fall through to the next provider — the executed tools+ # would re-run their side effects; speak honestly instead.+ if (+ response_empty+ and tool_calls_executed+ and str(agg.finish_reason or "") == "error"+ ):+ response_text = _MID_ANSWER_ERROR_PHRASES.get(+ self._resolve_turn_lang(), _MID_ANSWER_ERROR_PHRASES["de"]+ )+ log.warning(+ "Brain %s(%s): stream ended finish_reason=error AFTER "+ "%d tool call(s) — speaking the honest mid-answer "+ "error notice instead of an empty (silent) turn.",+ prov_name, model, len(agg.tool_calls),+ )# Record whether THIS (winning) turn was a fire-and-forget# ``suppress_response`` spawn, so the voice pipeline can stay# silent for it but speak a clarifying question for a differentdiff --git a/jarvis/brain/tool_use_loop.py b/jarvis/brain/tool_use_loop.pyindex 368d3f2b5e..7e12a89eeb 100644--- a/jarvis/brain/tool_use_loop.py+++ b/jarvis/brain/tool_use_loop.py@@ -402,6 +402,24 @@ class ToolUseLoop:)return tool, alias+ async def _publish_guard_denied(+ self, tool_name: str, reason: str, tid: UUID,+ ) -> None:+ """Make a guard-blocked / unknown-name tool call visible on the bus.++ The guard branches in ``run`` never reach ``ToolExecutor.execute``, so+ no ActionProposed/ActionExecuted fires — the session timeline showed NO+ trace of why a turn refused (2026-07-06 audit). Defensive: test fakes+ and older executors may not have the publisher; skip silently then.+ """+ publisher = getattr(self._executor, "publish_guard_denied", None)+ if publisher is None:+ return+ try:+ await publisher(tool_name, reason, trace_id=tid)+ except Exception: # noqa: BLE001 — observability must never break the loop+ log.debug("guard-denied publish failed", exc_info=True)+def _tool_schemas(self) -> list[dict[str, Any]]:"""Schemas in Anthropic-compatible format (providers normalise)."""return [@@ -594,6 +612,11 @@ class ToolUseLoop:"tool_use_loop: side-effect tool '%s' blocked for a how-to question",tool_name,)+ await self._publish_guard_denied(+ tool_name,+ "guard: how-to question — side-effect tool not executed",+ tid,+ )tool_result_payload = {"success": False,"output": None,@@ -613,6 +636,11 @@ class ToolUseLoop:"tool_use_loop: side-effect tool '%s' blocked for self-identification",tool_name,)+ await self._publish_guard_denied(+ tool_name,+ "guard: self-identification turn — side-effect tool not executed",+ tid,+ )tool_result_payload = {"success": False,"output": None,@@ -638,6 +666,12 @@ class ToolUseLoop:"tool_use_loop: tool '%s' not in the router tool set — ""anti-silence fallback instead of an empty response", tool_name,)+ await self._publish_guard_denied(+ tool_name,+ "unknown tool name — not in this turn's tool set "+ "(model-invented or gated off this turn)",+ tid,+ )tool_result_payload = {"error": f"Tool '{tool_name}' not available"}suppress_output = _anti_silence_phrase(user_utterance, reply_language@@ -646,6 +680,11 @@ class ToolUseLoop:log.info("tool_use_loop: spawn_worker blocked for a meta/debug utterance")+ await self._publish_guard_denied(+ tool_name,+ "guard: meta/debug utterance — spawn_worker not executed",+ tid,+ )# Asking the LLM to "answer directly and concretely" via a# tool_result error message turned out to be unreliable —# Gemini Flash regularly ignores the instruction, the@@ -682,6 +721,11 @@ class ToolUseLoop:"tool_use_loop: STT-hallucination guard blocked %s — %s",tool_name, stt_reason,)+ await self._publish_guard_denied(+ tool_name,+ f"guard: STT-hallucination suspect args — {stt_reason}",+ tid,+ )tool_result_payload = {"success": False,"output": None,@@ -707,6 +751,11 @@ class ToolUseLoop:"(intent_level=%s) — LLM redirected to search_web",tool_name, intent_level,)+ await self._publish_guard_denied(+ tool_name,+ "guard: research intent — action tool redirected to search_web",+ tid,+ )tool_result_payload = {"success": False,"output": None,diff --git a/jarvis/safety/tool_executor.py b/jarvis/safety/tool_executor.pyindex 45fe0eb1d8..7a067e2525 100644--- a/jarvis/safety/tool_executor.py+++ b/jarvis/safety/tool_executor.py@@ -118,6 +118,33 @@ class ToolExecutor:config=self._plausibility_config,)+ async def publish_guard_denied(+ self,+ tool_name: str,+ reason: str,+ *,+ trace_id: UUID | None = None,+ ) -> None:+ """Surface a tool call refused BEFORE reaching :meth:`execute`.++ The tool-use loop's deterministic guards (how-to question, research+ intent, STT hallucination, unknown tool name, …) block a call without+ ever entering the executor — so no ActionProposed/ActionExecuted event+ fires and the session timeline shows NO trace of why a turn refused+ (2026-07-06 audit: the unknown-tool 'run-shell' incident left zero+ events). Publishing the same ``ActionDenied`` the blacklist path uses+ makes the refusal visible; the recorder already subscribes to it.+ Best-effort: observability must never break tool execution.+ """+ try:+ await self._bus.publish(ActionDenied(+ trace_id=trace_id or uuid4(),+ tool_name=tool_name,+ reason=reason,+ ))+ except Exception: # noqa: BLE001+ log.debug("publish_guard_denied failed", exc_info=True)+async def execute(self,tool: Tool,diff --git a/jarvis/speech/pipeline.py b/jarvis/speech/pipeline.pyindex ded881669d..6604f775f5 100644--- a/jarvis/speech/pipeline.py+++ b/jarvis/speech/pipeline.py@@ -1457,6 +1457,12 @@ class SpeechPipeline:# verbatim in quick succession (forensic 2026-07-05: the identical# grounded ack spoke three times in one session).self._last_preamble_spoken: tuple[str, float] | None = None+ # v2 anti-loop backstop: monotonic timestamps of SPOKEN preamble/+ # progress lines. ``_on_announcement`` drops anything beyond+ # ``preamble_rate_limit_per_min`` in a rolling 60 s window so the+ # historical "kept repeating forever" bug class dies at this shared+ # chokepoint no matter which emitter misbehaves.+ self._preamble_spoken_times: deque[float] = deque(maxlen=32)# AD-OE5/OE6: completion-class announcements that arrive while the user# holds the floor are parked here and flushed at the next turn-boundary# (when the turn-state returns to LISTENING/IDLE) instead of barging@@ -2893,7 +2899,32 @@ class SpeechPipeline:event.text[:80],)return- self._last_preamble_spoken = (spoken_text, time.monotonic())+ # v2 anti-loop backstop: hard cap on spoken preamble/progress+ # lines per rolling 60 s window, ANY source. Kills the historical+ # "kept saying it forever" bug class at the last shared+ # chokepoint. Completion/interrupt readbacks never enter this+ # branch (owed answers are exempt).+ rate_limit = int(+ getattr(dedup_cfg, "preamble_rate_limit_per_min", 3) or 0+ )+ spoken_times = getattr(self, "_preamble_spoken_times", None)+ if spoken_times is None:+ spoken_times = deque(maxlen=32)+ self._preamble_spoken_times = spoken_times+ now_monotonic = time.monotonic()+ if rate_limit > 0:+ recent_count = sum(+ 1 for t in spoken_times if now_monotonic - t < 60.0+ )+ if recent_count >= rate_limit:+ log.warning(+ "Preamble dropped — rate-limit backstop (%d spoken in "+ "the last 60s, cap %d): %r",+ recent_count, rate_limit, event.text[:80],+ )+ return+ self._last_preamble_spoken = (spoken_text, now_monotonic)+ spoken_times.append(now_monotonic)# We are now committed to actually speaking this announcement (past every# suppression / defer / empty guard). Record it as voice activity so the# idle-timeout branch in ``_active_session`` re-arms a fresh window: andiff --git a/scripts/config-soll.json b/scripts/config-soll.jsonindex fbfe099022..2c935b08a7 100644--- a/scripts/config-soll.json+++ b/scripts/config-soll.json@@ -8,8 +8,8 @@"tts": {"provider": "openrouter-tts","fallback": "grok-voice",- "voice_de": "ara",- "voice_en": "ara",+ "voice_de": "Kore",+ "voice_en": "Kore","language_code": "auto","chunk_by_sentence": false,"seed": 7,@@ -18,7 +18,7 @@"vertex_project": "","vertex_location": "us-central1","service_account_path": "~/.config/jarvis/vertex-sa.json",- "model": "x-ai/grok-voice-tts-1.0",+ "model": "sonic-2","volume": 1.0},"tts.cartesia": {diff --git a/tests/unit/brain/test_ack_generator.py b/tests/unit/brain/test_ack_generator.pyindex f5f06499bc..56e7fa9371 100644--- a/tests/unit/brain/test_ack_generator.py+++ b/tests/unit/brain/test_ack_generator.py@@ -28,6 +28,7 @@ from jarvis.brain.ack_generator import (_SEARCH_TOPIC_ACK,_SHELL_ACK,AckPhrasePicker,+ describe_tool_action,final_summary_marker,generate_ack,is_voice_control_utterance,@@ -406,6 +407,44 @@ class TestGermanDiacritics:assert bad not in low, f"ASCII umlaut substitute in {phrase!r}"+class TestDescribeToolAction:+ """English action descriptions consumed as PROMPT INPUT by the contextual+ interim composer (v2 spec) — never spoken verbatim."""++ def test_search_names_the_query(self) -> None:+ desc = describe_tool_action("search_web", {"query": "PrimeRandat github"})+ assert "web search" in desc+ assert "PrimeRandat" in desc++ def test_cli_names_the_service(self) -> None:+ assert "GitHub" in describe_tool_action("cli_gh", {"command": "gh repo view"})+ assert "Google Cloud" in describe_tool_action("cli_gcloud", {})++ def test_cli_never_echoes_the_raw_command(self) -> None:+ desc = describe_tool_action("cli_gh", {"command": "gh api graphql --paginate"})+ assert "graphql" not in desc++ def test_shell_stays_generic(self) -> None:+ desc = describe_tool_action("run_shell", {"command": "rm -rf /tmp/x"})+ assert "rm -rf" not in desc+ assert desc++ def test_spawn_family_describes_the_handover(self) -> None:+ for tool in ("spawn_worker", "spawn_sub_jarvis", "dispatch_to_harness"):+ assert "background helper" in describe_tool_action(tool, {})++ def test_gmail_send_vs_read(self) -> None:+ assert "email" in describe_tool_action("gmail", {"action": "send_message"})+ assert "fetching" in describe_tool_action("gmail", {"action": "list_messages"})++ def test_open_app_names_the_app(self) -> None:+ assert "Notepad" in describe_tool_action("open_app", {"app": "Notepad"})++ def test_unknown_tool_is_neutral_and_total(self) -> None:+ assert describe_tool_action("mystery_tool", {"x": object()})+ assert describe_tool_action("", None)++class TestFinalSummaryMarker:def test_german_default(self) -> None:assert final_summary_marker("de") == "Erledigt." # i18n-allow: German completion marker under testdiff --git a/tests/unit/brain/test_stream_error_after_tools.py b/tests/unit/brain/test_stream_error_after_tools.pynew file mode 100644index 0000000000..5414b9c0bd--- /dev/null+++ b/tests/unit/brain/test_stream_error_after_tools.py@@ -0,0 +1,96 @@+"""Regression: a model round that dies AFTER tools ran must speak, not stay silent.++Live incident 2026-07-05 (session 3e27dd8e, 19:49:12): the turn executed 10++tools, then the final model round returned ``finish_reason="error"`` (OpenRouter+mid-stream error on a ~224k-token prompt) with empty text. The empty-response+guard is (correctly) skipped when tool calls exist, so the turn counted as a+success with empty text — the user heard NOTHING (AD-OE6 violation).++Contract under test:+1. The manager returns an honest localized notice instead of empty text.+2. It does NOT fall through to the next provider — the executed tools would+ re-run their side effects on the retry.+"""+from __future__ import annotations++import pytest++from jarvis.brain.manager import BrainManager+from jarvis.core.bus import EventBus+from jarvis.core.config import BrainProviderConfig, JarvisConfig, SafetyConfig+from jarvis.core.protocols import BrainDelta, ExecutionContext, ToolResult+from jarvis.safety import ApprovalWorkflow, RiskTierEvaluator, ToolExecutor+from tests.fixtures.brain.fake_brain import FakeBrain, tool_call_delta+++class _RecallTool:+ """Benign read tool (wiki-recall shape): safe tier, no side-effect names."""++ name = "wiki-recall"+ description = "Fake wiki recall"+ risk_tier = "safe"+ schema: dict = {+ "type": "object",+ "properties": {"query": {"type": "string"}},+ "required": ["query"],+ }++ def __init__(self) -> None:+ self.calls: list[dict] = []++ async def execute(self, args, ctx: ExecutionContext) -> ToolResult:+ self.calls.append(args)+ return ToolResult(success=True, output="wiki says: jarvis is a project")+++async def test_stream_error_after_tools_speaks_honest_notice() -> None:+ bus = EventBus()+ config = JarvisConfig()+ config.brain.primary = "claude-subscription"+ config.brain.providers["claude-subscription"] = BrainProviderConfig(+ model="haiku-model",+ deep_model="opus-model",+ )++ tool = _RecallTool()+ executor = ToolExecutor(bus, RiskTierEvaluator(SafetyConfig()), ApprovalWorkflow(bus))+ manager = BrainManager(+ config=config, bus=bus,+ tools={"wiki-recall": tool},+ tool_executor=executor,+ )+ manager._registry._loaded = True++ # Turn 1: the model calls the tool. Turn 2 (after the tool result): the+ # provider stream dies — finish_reason="error", no content (the live+ # OpenRouter mid-stream error shape).+ primary = FakeBrain(script=[+ [tool_call_delta("wiki-recall", {"query": "jarvis"}, call_id="c1")],+ [BrainDelta(finish_reason="error")],+ ])+ fallback = FakeBrain(text_response="I must not be called")++ manager._brain_cache[("claude-subscription", "haiku-model")] = primary+ manager._brain_cache[("claude-subscription", "opus-model")] = fallback+ manager._build_fallback_chain = lambda level: [+ ("claude-subscription", "haiku-model"),+ ("claude-subscription", "opus-model"),+ ]++ result = await manager.generate("was steht im wiki zu jarvis", use_history=False)++ assert isinstance(result, str) and result.strip(), (+ "a stream error after executed tools must produce a SPOKEN notice, "+ "never an empty (silent) turn"+ )+ # It must be the honest mid-answer notice, not the all-failed apology.+ assert "unerreichbar" not in result.lower() # i18n-allow (matches production error text)+ assert "fehlgeschlagen" not in result.lower() # i18n-allow (matches production error text)+ # The tool ran exactly once — no provider fall-through re-running it.+ assert len(tool.calls) == 1, (+ f"tool ran {len(tool.calls)}x — a fallback retry would re-run side effects"+ )+ assert len(fallback.calls) == 0, (+ "the chain must NOT fall through after tools already executed"+ )diff --git a/tests/unit/brain/test_tool_ack_emitter.py b/tests/unit/brain/test_tool_ack_emitter.pyindex 29c1c71af9..4baefe0381 100644--- a/tests/unit/brain/test_tool_ack_emitter.py+++ b/tests/unit/brain/test_tool_ack_emitter.py@@ -14,6 +14,7 @@ in tests/integration/test_ack_flow.py).from __future__ import annotations+import asyncioimport timeimport typesfrom types import SimpleNamespace@@ -124,7 +125,7 @@ async def test_fires_at_most_once_across_retries() -> None:the tool loop must not double-announce."""bus = _RecordingBus()stub = _make_stub(bus=bus)- emit = stub._build_tool_ack_emitter("Was steht in meinen Mails")+ emit = stub._build_tool_ack_emitter("Schau mal in meine Mails")assert emit is not Noneawait emit("gmail", {"action": "list_messages"})@@ -212,3 +213,146 @@ async def test_skip_tool_does_not_arm_the_gap() -> None:emit_turn_2 = stub._build_tool_ack_emitter("Was steht in meinen Mails")await emit_turn_2("gmail", {"action": "list_messages"})assert len(_preambles(bus)) == 1+++# ---------------------------------------------------------------------------+# Contextual Interim Voice (v2 spec) — LLM-composed line via ReadbackComposer+# ---------------------------------------------------------------------------++class _FakeComposer:+ """Duck-typed ReadbackComposer: records the compose() call, returns a+ scripted line (or the canned fallback when scripted to fail)."""++ def __init__(self, response: str | None) -> None:+ self._response = response+ self.calls: list[dict[str, Any]] = []+ self.has_llm = True++ async def compose(+ self,+ *,+ instruction: str,+ language: str,+ canned: Any,+ facts: dict[str, Any] | None = None,+ in_progress: bool = False,+ honesty_bound: bool = False,+ latency_budget_ms: int | None = None,+ ) -> str:+ self.calls.append({+ "instruction": instruction,+ "language": language,+ "facts": facts or {},+ "in_progress": in_progress,+ })+ if self._response is None:+ return (canned() or "").strip() # composer contract: fall back, never raise+ return self._response+++async def _drain_interim_tasks(stub: Any) -> None:+ tasks = getattr(stub, "_interim_ack_tasks", None) or ()+ if tasks:+ await asyncio.gather(*list(tasks))+++async def test_contextual_line_is_composed_from_the_turn() -> None:+ """With a live composer the spoken text is the per-turn composition, and+ the composer receives the user's request + the concrete action as facts."""+ bus = _RecordingBus()+ stub = _make_stub(bus=bus)+ composer = _FakeComposer("Ich grabe gerade durch die GitHub-Profile.") # i18n-allow: German TTS fixture+ stub._readback_composer = composer++ emit = stub._build_tool_ack_emitter("Wo liegt das PrimeRandat-Repo?")+ await emit("cli_gh", {"command": "gh repo view PrimeRandat"})+ # Fire-and-forget: the publish happens on the detached task, not inline.+ await _drain_interim_tasks(stub)++ preambles = _preambles(bus)+ assert len(preambles) == 1+ assert preambles[0].text == "Ich grabe gerade durch die GitHub-Profile." # i18n-allow: German TTS fixture+ call = composer.calls[0]+ assert call["in_progress"] is True+ assert "PrimeRandat" in call["facts"]["user_request"]+ assert "GitHub" in call["facts"]["current_action"]+++async def test_emit_does_not_block_on_composition() -> None:+ """The tool-use loop awaits emit(); the flash call must run detached so+ tool execution is never delayed by composition latency."""+ bus = _RecordingBus()+ stub = _make_stub(bus=bus)++ release = asyncio.Event()++ class _SlowComposer(_FakeComposer):+ async def compose(self, **kwargs: Any) -> str:+ await release.wait()+ return "Ich schaue gerade in dein Postfach." # i18n-allow: German TTS fixture++ stub._readback_composer = _SlowComposer(None)++ emit = stub._build_tool_ack_emitter("Schau mal in meine Mails")+ await emit("gmail", {"action": "list_messages"}) # returns without waiting++ assert _preambles(bus) == [], "emit() blocked on the flash composition"+ release.set()+ await _drain_interim_tasks(stub)+ assert len(_preambles(bus)) == 1+++async def test_composer_failure_falls_back_to_the_pool_line() -> None:+ """A rejected/failed composition degrades to the deterministic pool line+ (keyless-install contract) — never silence, never an exception."""+ bus = _RecordingBus()+ stub = _make_stub(bus=bus)+ stub._readback_composer = _FakeComposer(None) # scripted: fall back to canned++ emit = stub._build_tool_ack_emitter("Schau mal in meine Mails")+ await emit("gmail", {"action": "list_messages"})+ await _drain_interim_tasks(stub)++ preambles = _preambles(bus)+ assert len(preambles) == 1+ assert preambles[0].text in _GMAIL_READ_ACK["de"]+++async def test_contextual_kill_switch_uses_pool_inline() -> None:+ """[ack_brain].contextual_interim = false: pools only, published inline."""+ bus = _RecordingBus()+ stub = _make_stub(bus=bus)+ stub._config.ack_brain.contextual_interim = False+ composer = _FakeComposer("Nie zu hoeren.") # i18n-allow: German TTS fixture+ stub._readback_composer = composer++ emit = stub._build_tool_ack_emitter("Schau mal in meine Mails")+ await emit("gmail", {"action": "list_messages"})++ preambles = _preambles(bus)+ assert len(preambles) == 1 # inline — no task drain needed+ assert preambles[0].text in _GMAIL_READ_ACK["de"]+ assert composer.calls == []+++async def test_fallback_only_composer_uses_pool_inline() -> None:+ """A keyless install wires a fallback-only composer (has_llm=False) — the+ deterministic path stays synchronous, no detached task."""+ bus = _RecordingBus()+ stub = _make_stub(bus=bus)+ composer = _FakeComposer("Nie zu hoeren.") # i18n-allow: German TTS fixture+ composer.has_llm = False+ stub._readback_composer = composer++ emit = stub._build_tool_ack_emitter("Schau mal in meine Mails")+ await emit("gmail", {"action": "list_messages"})++ preambles = _preambles(bus)+ assert len(preambles) == 1+ assert preambles[0].text in _GMAIL_READ_ACK["de"]+ assert composer.calls == []diff --git a/tests/unit/brain/test_tool_use_loop.py b/tests/unit/brain/test_tool_use_loop.pyindex fde317c030..6821bfb9ff 100644--- a/tests/unit/brain/test_tool_use_loop.py+++ b/tests/unit/brain/test_tool_use_loop.py@@ -229,6 +229,56 @@ async def test_underscore_alias_resolves_to_hyphenated_tool() -> None:assert "wiki-recall" in result.executed_tool_names+class _ExecWithDeniedLog(_ExecOK):+ """Executor fake that records guard-denied publications (Task-3 contract)."""++ def __init__(self) -> None:+ super().__init__()+ self.denied: list[tuple[str, str]] = []++ async def publish_guard_denied(self, tool_name, reason, *, trace_id=None):+ self.denied.append((tool_name, reason))+++async def test_unknown_tool_publishes_guard_denied_event() -> None:+ """A model-invented tool name must leave a visible trace (2026-07-06+ audit: the 'run-shell' incident produced ZERO events — the timeline+ could not show why the turn refused)."""+ brain = _AliasCallingBrain("totally_made_up_tool")+ executor = _ExecWithDeniedLog()+ loop = ToolUseLoop(+ brain,+ {"run_shell": _RunShellTool()},+ executor, # type: ignore[arg-type]+ )++ await loop.run([], user_utterance="zeig mir den letzten Commit")++ assert executor.calls == []+ assert executor.denied, "unknown tool must publish a guard-denied event"+ assert executor.denied[0][0] == "totally_made_up_tool"+ assert "unknown tool name" in executor.denied[0][1]+++async def test_howto_guard_publishes_guard_denied_event() -> None:+ brain = _Brain()+ executor = _ExecWithDeniedLog()+ loop = ToolUseLoop(+ brain,+ {"dispatch_to_harness": _Tool()},+ executor, # type: ignore[arg-type]+ )++ await loop.run(+ [],+ user_utterance="Wie kann ich bei Windows reinzoomen?", # i18n-allow: simulated German user utterance under test+ )++ assert executor.denied and "how-to" in executor.denied[0][1]++@pytest.mark.asyncioasync def test_ambiguous_alias_is_not_guessed() -> None:"""If two registered tools collide on the normalized form, an inexact namediff --git a/tests/unit/speech/test_interim_ack_gates.py b/tests/unit/speech/test_interim_ack_gates.pyindex 4136d8deb3..86dd0d1e38 100644--- a/tests/unit/speech/test_interim_ack_gates.py+++ b/tests/unit/speech/test_interim_ack_gates.py@@ -77,6 +77,7 @@ def _make_pipeline(*,commit_grace_ms: int = 900,dedup_window_s: int = 180,+ rate_limit_per_min: int = 3,) -> SpeechPipeline:pipeline = SpeechPipeline(tts=tts, bus=bus, enable_whisper_wake=False)pipeline._player = player # type: ignore[assignment]@@ -85,6 +86,7 @@ def _make_pipeline(suppress_preamble_after_interrupt_ms=5000,grounded_ack_commit_grace_ms=commit_grace_ms,preamble_dedup_window_s=dedup_window_s,+ preamble_rate_limit_per_min=rate_limit_per_min,))return pipeline@@ -168,6 +170,62 @@ async def test_completion_readbacks_are_never_deduped() -> None:assert player.plays == 2, "an owed completion readback was deduped"+# ---------------------------------------------------------------------------+# Anti-loop rate-limit backstop (v2)+# ---------------------------------------------------------------------------++async def test_rate_limit_caps_preambles_per_minute() -> None:+ """The historical 'kept saying it forever' loop dies here: beyond the+ per-minute cap, further preamble-class lines are dropped — even with+ DISTINCT wording (dedup alone would not catch a looping emitter that+ varies its text)."""+ bus = EventBus()+ tts = FakeTTS()+ player = FakePlayer()+ _make_pipeline(tts, bus, player, rate_limit_per_min=3)++ for i in range(5):+ await bus.publish(_preamble(f"Zwischenmeldung Nummer {i}.")) # i18n-allow: German TTS fixture++ assert player.plays == 3, "the rate-limit backstop did not cap the loop"+++async def test_rate_limit_zero_disables_the_backstop() -> None:+ bus = EventBus()+ tts = FakeTTS()+ player = FakePlayer()+ _make_pipeline(tts, bus, player, rate_limit_per_min=0)++ for i in range(5):+ await bus.publish(_preamble(f"Zwischenmeldung Nummer {i}.")) # i18n-allow: German TTS fixture++ assert player.plays == 5+++async def test_rate_limit_never_touches_completions() -> None:+ """Completion readbacks are owed answers — a burst of finished missions+ must all be spoken regardless of the preamble cap."""+ bus = EventBus()+ tts = FakeTTS()+ player = FakePlayer()+ _make_pipeline(tts, bus, player, rate_limit_per_min=1)++ for i in range(3):+ await bus.publish(+ AnnouncementRequested(+ text=f"Auftrag {i} ist fertig geworden.", # i18n-allow: German TTS fixture+ language="de",+ priority="normal",+ kind="completion",+ )+ )++ assert player.plays == 3++# ---------------------------------------------------------------------------# Grounded-ack usefulness gate (commit grace)# ---------------------------------------------------------------------------