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(background): say it out loud when background work dies
Harald352bdb1eb4c9
diff --git a/jarvis/plugins/tool/spawn_worker.py b/jarvis/plugins/tool/spawn_worker.pyindex 2a74f45562..0d2c9c72af 100644--- a/jarvis/plugins/tool/spawn_worker.py+++ b/jarvis/plugins/tool/spawn_worker.py@@ -43,10 +43,24 @@ from jarvis.core.events import JarvisAgentAnnouncement, JarvisAgentBackgroundComfrom jarvis.core.protocols import ExecutionContext, ToolResultfrom jarvis.missions.manager import MissionManagerfrom jarvis.missions.stream_evidence import strip_spawn_meta+from jarvis.voice.action_phrases import action_phrase, resolve_ambient_languagelog = logging.getLogger(__name__)+def _readback_lang(turn_language: str | None) -> str:+ """de/en/es for a failure readback this tool renders itself.++ The turn's resolved output language wins (stamped by the tool-use loop via+ ``resolve_output_language`` — see ``execute``). Only when the turn carries+ none does this fall back to the ambient answer (reply-language pin →+ default locale); this layer never re-derives a language from the utterance+ (CLAUDE.md §1).+ """+ lang = (turn_language or "").strip().lower()+ return lang or resolve_ambient_language()++# Resolved at execute-time, not at __init__-time. Required because the# Mission stack is bootstrapped AFTER build_default_brain() in the# DesktopApp startup sequence, but the BrainManager is built once and@@ -678,6 +692,11 @@ class SpawnWorkerTool:self._background_dispatch(mission_prompt, utterance, manager, kontrollierer,mission_language=mission_language,+ # Full de/en/es turn language (NOT the de/en-capped+ # mission_language): a failure readback the background task+ # renders itself must be in the same language the pipeline+ # will wrap it in.+ readback_language=ack_language,),# NOTE: prefix "jarvis-agent-" is a live matching key, not a# cosmetic label — jarvis/brain/manager.py@@ -720,6 +739,7 @@ class SpawnWorkerTool:kontrollierer: Any | None,*,mission_language: str = "de",+ readback_language: str | None = None,) -> None:"""Laeuft im Background. Dispatched + executes eine Mission.@@ -746,7 +766,12 @@ class SpawnWorkerTool:gets no voice feedback (BUG-016). When no Kontrollierer isavailable the dispatch still happens — the next app start'srecovery sweep will mark it as crash-recovered, which is at- least visible in the UI instead of silently lost.+ least visible in the UI instead of silently lost. That UI trace+ is NOT enough on its own: the user has already heard a spoken+ promise, so the missing runner is published as a failed+ completion (AU-11) — the same event a finished mission uses,+ so the voice layer says it out loud instead of a log line+ nobody reads.Exceptions werden geloggt und als ``success=False`` publisht — nichtspropagiert nach aussen, weil der Task fire-and-forget ist und ein@@ -766,6 +791,15 @@ class SpawnWorkerTool:"(recovery will mark it crash_recovered)",mission_id,)+ # The user was promised an answer seconds ago. Publishing the+ # SAME completion event a finished mission uses is what turns+ # that dead end into a spoken sentence; the pipeline wraps+ # ``error`` in its localized "that didn't work" line.+ await self._publish_dispatch_failure(+ utterance, action_phrase(+ "spawn_no_runner", _readback_lang(readback_language),+ ),+ )return# Run the mission. This blocks until APPROVED / FAILED;# the Voice-Listener will then publish JarvisAgentBackgroundCompleted.@@ -775,24 +809,9 @@ class SpawnWorkerTool:raise # Propagieren, damit Loop sauber aufraeumt.except BaseException as exc: # noqa: BLE001log.exception("Background Jarvis-Agent dispatch crashed")- try:- await self._bus.publish(- JarvisAgentBackgroundCompleted(- success=False,- utterance=utterance,- summary="",- error=f"{type(exc).__name__}: {exc}",- duration_s=0.0,- )- )- except Exception: # noqa: BLE001- # If even the fail-event publish crashed (dead bus,- # shutdown race), at least leave a trace — otherwise the- # whole failure disappears with no record in either the- # log or the voice path.- log.exception(- "JarvisAgentBackgroundCompleted bus-publish crashed"- )+ await self._publish_dispatch_failure(+ utterance, f"{type(exc).__name__}: {exc}",+ )finally:# Release the liveness gate on EVERY terminal state — success,# kontrollierer-None early return, failure, or shutdown cancel.@@ -800,3 +819,28 @@ class SpawnWorkerTool:# is not falsely suppressed as "already running" (#3). Floor at 0# defends against any unpaired decrement.self._active_dispatches = max(0, self._active_dispatches - 1)++ async def _publish_dispatch_failure(self, utterance: str, error: str) -> None:+ """Tell the user a promised background task will not deliver.++ The ONE exit for every dead end in ``_background_dispatch`` — the crash+ path and the no-Kontrollierer path alike — so neither can regress into a+ bare log line again (AU-11). ``error`` rides the completion event the+ Voice-Listener already publishes for a finished mission, so the readback+ goes through the established path instead of a second mechanism.+ """+ try:+ await self._bus.publish(+ JarvisAgentBackgroundCompleted(+ success=False,+ utterance=utterance,+ summary="",+ error=error,+ duration_s=0.0,+ )+ )+ except Exception: # noqa: BLE001+ # If even the fail-event publish crashed (dead bus, shutdown race),+ # at least leave a trace — otherwise the whole failure disappears+ # with no record in either the log or the voice path.+ log.exception("JarvisAgentBackgroundCompleted bus-publish crashed")diff --git a/jarvis/voice/action_phrases.py b/jarvis/voice/action_phrases.pyindex ba8f57b1e7..a968c643f6 100644--- a/jarvis/voice/action_phrases.py+++ b/jarvis/voice/action_phrases.py@@ -298,6 +298,76 @@ _PHRASES: dict[str, dict[str, str]] = {"en": "I couldn't start the background helper: {reason}","es": "No pude iniciar el ayudante en segundo plano: {reason}",},+ # The mission was accepted but NOTHING will ever pick it up: the spoken ack+ # already promised an answer, and the mission would sit PENDING until the+ # next app start's recovery sweep quietly marks it crash-recovered (AU-11).+ # Rides ``JarvisAgentBackgroundCompleted.error``, i.e. the pipeline speaks it+ # AFTER "Das hat nicht geklappt. " / "That didn't work. " — so this is the+ # second half of a sentence and must stay under the readback's 80-char cap.+ # One fact plus the one thing the user can act on, nothing else.+ "spawn_no_runner": {+ "de": "Ich kann die Aufgabe gerade nicht starten. Starte mich bitte neu.", # i18n-allow+ "en": "I can't start the task right now. Please restart me.",+ "es": "No puedo iniciar la tarea ahora. Reiníciame, por favor.",+ },+ # Scheduled-routine failures (jarvis/workflows). A broken routine used to+ # vanish into a log line, which is the maintainer's exact complaint: "you+ # tell him something and nothing happens" (AU-12 / AU-13). ``{name}`` is the+ # routine's own user-given name — never an id, never a run id.+ "workflow_trigger_failed": {+ "de": "Die Routine {name} konnte nicht starten. " # i18n-allow+ "Ich versuche es zum nächsten geplanten Zeitpunkt wieder.", # i18n-allow+ "en": "The routine {name} could not start. "+ "I'll try again at the next scheduled time.",+ "es": "La rutina {name} no pudo iniciarse. "+ "Lo intentaré en el próximo momento programado.",+ },+ # The scheduler's own poll loop threw — EVERY scheduled routine is stalled,+ # not just one, so this names no routine. It retries by itself, hence the+ # honest "I'll keep trying" instead of an action the user cannot take.+ "workflow_scheduler_stalled": {+ "de": "Deine geplanten Routinen laufen gerade nicht. " # i18n-allow+ "Ich versuche es weiter.", # i18n-allow+ "en": "Your scheduled routines aren't running right now. "+ "I'll keep trying.",+ "es": "Tus rutinas programadas no se están ejecutando ahora. "+ "Seguiré intentándolo.",+ },+ # A routine stopped mid-way. ``{step}`` is the author's own step label or the+ # plain ordinal below — NEVER ``step_display_label``'s engineering fallback+ # ("Tool: spawn_worker", "Shell: git status"), which would leak mechanics+ # into speech. ``{reason}`` passed ``extract_speakable_reason``, so it is a+ # human sentence and never an exception class name or a bare ``exit N``.+ "workflow_step_failed": {+ "de": "Die Routine {name} ist bei {step} hängen geblieben, " # i18n-allow+ "also habe ich sie angehalten.", # i18n-allow+ "en": "The routine {name} got stuck at {step}, so I stopped it.",+ "es": "La rutina {name} se atascó en {step}, así que la detuve.",+ },+ # The reason trails in its own sentence rather than after a colon: it is+ # forwarded text and may well end in a full stop of its own.+ "workflow_step_failed_reason": {+ "de": "Die Routine {name} ist bei {step} hängen geblieben, " # i18n-allow+ "also habe ich sie angehalten. Der Grund: {reason}", # i18n-allow+ "en": "The routine {name} got stuck at {step}, so I stopped it. "+ "The reason: {reason}",+ "es": "La rutina {name} se atascó en {step}, así que la detuve. "+ "El motivo: {reason}",+ },+ "workflow_step_ordinal": {+ "de": "Schritt {n}", # i18n-allow+ "en": "step {n}",+ "es": "el paso {n}",+ },+ # Fills the ``{name}`` slot when a routine row carries no name. Worded to+ # stay grammatical inside the sentences above ("Die Routine ohne Namen+ # konnte nicht starten."). Vague on purpose — the id it replaces would not+ # be vague, it would be meaningless out loud.+ "workflow_unnamed": {+ "de": "ohne Namen", # i18n-allow+ "en": "without a name",+ "es": "sin nombre",+ },# Deterministic wiki-write fast path (spec A1-A3). The saving line is a# PROGRESS ack — it must never claim the write already happened; the# saved/failed lines are the post-write truth (confirm-after-write).@@ -554,6 +624,32 @@ def resolve_phrase_language(reply_language: str | None, user_text: str) -> str:return resolve_turn_language("unknown", user_text, default=_DEFAULT)+def resolve_ambient_language() -> str:+ """Output language for a phrase with NO turn text behind it.++ Scheduled routines, cron triggers and other unattended background work have+ no user utterance to detect a language from, so the ONE resolver is fed the+ only honest inputs there are: the explicit ``brain.reply_language`` pin, and+ otherwise ``DEFAULT_LOCALE``. This layer never guesses beyond that+ (CLAUDE.md §1 — one resolver decides, no layer re-derives). Mirrors+ ``jarvis/cu/indicator/controller.py::_resolve_hint_language``, which needs+ the same answer for the same reason.+ """+ from jarvis.core.turn_language import ( # noqa: PLC0415+ DEFAULT_LOCALE,+ resolve_output_language,+ )++ pin = ""+ try:+ from jarvis.core.config import load_config # noqa: PLC0415++ pin = str(getattr(load_config().brain, "reply_language", "") or "")+ except Exception: # noqa: BLE001 — config trouble must not silence a report+ pin = ""+ return resolve_output_language(pin, "", "", default=DEFAULT_LOCALE)++def action_phrase(key: str, lang: str, **fmt: object) -> str:"""Render the localized phrase ``key`` in ``lang`` (de/en/es).@@ -869,5 +965,6 @@ __all__ = ["cu_failure_readback","cu_success_readback","extract_speakable_reason",+ "resolve_ambient_language","resolve_phrase_language",]diff --git a/jarvis/workflows/runner.py b/jarvis/workflows/runner.pyindex 7f1d17c517..6a9353381b 100644--- a/jarvis/workflows/runner.py+++ b/jarvis/workflows/runner.py@@ -35,6 +35,11 @@ from jarvis.core.events import (WorkflowStepStarted,)from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS+from jarvis.voice.action_phrases import (+ action_phrase,+ extract_speakable_reason,+ resolve_ambient_language,+)from .schema import (WorkflowDef,@@ -48,6 +53,48 @@ if TYPE_CHECKING:log = logging.getLogger(__name__)_PREVIEW_MAX = 240+#: Longest a failure reason may be when it is SPOKEN. Long enough for a real+#: sentence, short enough that a stack-shaped error does not become a monologue.+_SPOKEN_REASON_MAX = 160+#: How long a background thing that keeps failing stays quiet after it has said+#: so once. One hour: a permanently broken routine becomes an hourly reminder,+#: never a per-run metronome.+FAILURE_REANNOUNCE_S = 3600.0+++class FailureAnnouncer:+ """Suppression rule for "this ran in the background and broke" reports.++ Two failures pull in opposite directions: a routine that breaks ONCE must+ be said out loud, and a routine that breaks every 60 seconds must not be+ said out loud every 60 seconds. The rule that satisfies both:++ * the first failure of a key speaks immediately;+ * while the same key keeps failing it stays silent for ``cooldown_s``,+ then speaks again;+ * a success calls :meth:`clear`, so the next NEW failure after a recovery+ speaks at once instead of waiting the cooldown out.++ Lives here and is imported by the scheduler so the two layers cannot drift+ into two different rules — a failing cron routine passes through both.+ """++ def __init__(self, cooldown_s: float = FAILURE_REANNOUNCE_S) -> None:+ self._cooldown_s = cooldown_s+ self._last_spoken: dict[str, float] = {}++ def should_speak(self, key: str) -> bool:+ """True when this failure may be announced. Records the moment it is."""+ now = time.monotonic()+ previous = self._last_spoken.get(key)+ if previous is not None and (now - previous) < self._cooldown_s:+ return False+ self._last_spoken[key] = now+ return True++ def clear(self, key: str) -> None:+ """Forget ``key`` — it just succeeded, so its next failure is news."""+ self._last_spoken.pop(key, None)# ----------------------------------------------------------------------@@ -136,6 +183,8 @@ class WorkflowRunner:self._harness = harness_managerself._tools = tool_registryself._executor = tool_executor+ #: Keyed by workflow id — see :class:`FailureAnnouncer`.+ self._failures = FailureAnnouncer()# ------------------------------------------------------------------# Runtime dependency swap (the BrainManager is only built after the@@ -209,6 +258,13 @@ class WorkflowRunner:step_outputs: dict[str, str] = {}success = Trueerror_msg: str | None = None+ # Kept for the spoken failure report below. ``failed_reason`` is the+ # exception's own MESSAGE, never the ``ClassName: message`` form the+ # store and the events carry — an exception class name means nothing to+ # the person listening.+ failed_step_index = 0+ failed_step_label = ""+ failed_reason = ""for idx, step in enumerate(wf.steps, start=1):label = step_display_label(step)@@ -244,6 +300,13 @@ class WorkflowRunner:)success = Falseerror_msg = error_text+ failed_step_index = idx+ # The AUTHOR's own label only. ``step_display_label``'s fallback+ # is engineering shorthand ("Tool: spawn_worker", "Shell: git+ # status") — fine in a UI timeline, never in a spoken sentence;+ # the plain ordinal stands in for it.+ failed_step_label = getattr(step, "label", "") or ""+ failed_reason = str(exc).strip()log.warning("Workflow %s step %d failed: %s",wf.name, idx, error_text)break@@ -280,6 +343,64 @@ class WorkflowRunner:))+ # A broken chain used to end HERE: the ``break`` above skipped the+ # trailing speak step, so the run that had the most to report was the+ # one that said nothing (AU-13). The chain still stops — it just says+ # why first.+ if success:+ self._failures.clear(str(wf.id))+ else:+ await self._announce_failure(+ wf, failed_step_index, failed_step_label, failed_reason,+ )++ async def _announce_failure(+ self,+ wf: WorkflowDef,+ step_index: int,+ step_label: str,+ reason: str,+ ) -> None:+ """Say, in plain language, that a routine stopped and what stopped it.++ Reuses the announcement path every other background result travels+ (``AnnouncementRequested(kind="subagent")``, as in+ ``jarvis/tasks/runner.py:225``): it survives the voice hangup gate and+ is mirrored to browser tabs, so it reaches the user on a headless+ runtime too. Rate-limited per workflow — see :class:`FailureAnnouncer`.+ """+ if not self._failures.should_speak(str(wf.id)):+ log.info(+ "Workflow %s failed again within the announce cooldown — "+ "reported once already, staying quiet",+ wf.name,+ )+ return+ lang = resolve_ambient_language()+ where = step_label or action_phrase(+ "workflow_step_ordinal", lang, n=step_index,+ )+ # The gate that keeps opaque tokens out of speech — a bare "exit 1", a+ # numeric blob or internal diagnostics degrade to the reasonless line.+ speakable = extract_speakable_reason(reason)+ if speakable:+ text = action_phrase(+ "workflow_step_failed_reason", lang,+ name=wf.name, step=where, reason=speakable[:_SPOKEN_REASON_MAX],+ )+ else:+ text = action_phrase(+ "workflow_step_failed", lang, name=wf.name, step=where,+ )+ await self._bus.publish(+ AnnouncementRequested(+ text=text,+ language=lang,+ kind="subagent",+ source_layer="workflows.runner",+ )+ )+# ------------------------------------------------------------------# Step dispatch# ------------------------------------------------------------------diff --git a/jarvis/workflows/scheduler.py b/jarvis/workflows/scheduler.pyindex 0d801f3fb9..88b35d3994 100644--- a/jarvis/workflows/scheduler.py+++ b/jarvis/workflows/scheduler.py@@ -27,7 +27,10 @@ except Exception: # pragma: no cover_HAVE_CRONITER = Falsefrom jarvis.core.bus import EventBus-from jarvis.core.events import WorkflowScheduled+from jarvis.core.events import AnnouncementRequested, WorkflowScheduled+from jarvis.voice.action_phrases import action_phrase, resolve_ambient_language++from .runner import FailureAnnouncerif TYPE_CHECKING:from .runner import WorkflowRunner@@ -36,6 +39,10 @@ if TYPE_CHECKING:log = logging.getLogger(__name__)+#: :class:`FailureAnnouncer` key for the poll loop itself, as opposed to one+#: workflow. Not a workflow id, and no id can collide with it.+_LOOP_KEY = "*scheduler-loop*"+class WorkflowScheduler:"""Poll loop — computes and fires cron-based workflow runs."""@@ -51,6 +58,8 @@ class WorkflowScheduler:self._bus = busself._task: asyncio.Task | None = Noneself._stop = asyncio.Event()+ #: Keyed by workflow id, plus ``_LOOP_KEY`` for the loop itself.+ self._failures = FailureAnnouncer()# ------------------------------------------------------------------@@ -83,6 +92,13 @@ class WorkflowScheduler:except Exception as exc: # noqa: BLE001log.exception("WorkflowScheduler tick crashed: %s", exc)wait_s = 30.0+ # A crashed tick means NO scheduled routine fires — every one+ # of them silently stops happening. The loop retries by itself,+ # but the user has to learn that their routines are down from+ # something other than a log file (AU-12).+ await self._announce(_LOOP_KEY, "workflow_scheduler_stalled")+ else:+ self._failures.clear(_LOOP_KEY)try:await asyncio.wait_for(self._stop.wait(), timeout=wait_s)@@ -156,12 +172,55 @@ class WorkflowScheduler:await self._runner.trigger(wid, trigger_reason="cron")except Exception as exc: # noqa: BLE001log.warning("Cron trigger for %s failed: %s", wid, exc)+ # The routine was due and did not even start. Only the log knew+ # (AU-12); now the user does. The next fire time is already+ # stored above, so "I'll try again" is honest.+ await self._announce(+ wid, "workflow_trigger_failed",+ name=_name_for(rows, wid),+ )+ else:+ self._failures.clear(wid)if upcoming_min_ns is None:return 60.0delta_s = max(1.0, (upcoming_min_ns - time.time_ns()) / 1e9)return min(delta_s, 60.0)+ # ------------------------------------------------------------------++ async def _announce(self, key: str, phrase_key: str, **fmt: object) -> None:+ """Tell the user a scheduled routine did not happen.++ Same path as every other background result+ (``AnnouncementRequested(kind="subagent")``, as in+ ``jarvis/tasks/runner.py:225``) — it survives the voice hangup gate and+ reaches browser tabs, so a headless runtime still reports. Rate-limited+ per ``key`` by :class:`~jarvis.workflows.runner.FailureAnnouncer`: a+ routine that fails every minute is said once, not sixty times an hour.+ """+ if not self._failures.should_speak(key):+ log.info(+ "Scheduler failure %s repeated within the announce cooldown — "+ "reported once already, staying quiet", key,+ )+ return+ lang = resolve_ambient_language()+ try:+ await self._bus.publish(+ AnnouncementRequested(+ text=action_phrase(phrase_key, lang, **fmt),+ language=lang,+ kind="subagent",+ source_layer="workflows.scheduler",+ )+ )+ except Exception: # noqa: BLE001+ # A dead bus must not turn one failed routine into a claim that the+ # whole scheduler is down (this runs inside _tick, whose caller+ # announces exactly that). Leave a trace and carry on.+ log.exception("Scheduler failure announcement could not be published")+# ----------------------------------------------------------------------# Helpers@@ -185,3 +244,19 @@ def _cron_expr_for(rows: list[dict[str, Any]], wid: str) -> str:if r["id"] == wid:return r.get("cron_expression") or ""return ""+++def _name_for(rows: list[dict[str, Any]], wid: str) -> str:+ """The routine's own user-given name for a SPOKEN report.++ Never the id — an id read aloud tells the user nothing about which of their+ routines broke. A nameless row degrades to the localized generic noun rather+ than leaking the id as a substitute.+ """+ for r in rows:+ if r["id"] == wid:+ name = str(r.get("name") or "").strip()+ if name:+ return name+ break+ return action_phrase("workflow_unnamed", resolve_ambient_language())diff --git a/tests/unit/plugins/tool/test_spawn_worker_no_runner_reports.py b/tests/unit/plugins/tool/test_spawn_worker_no_runner_reports.pynew file mode 100644index 0000000000..2227c1b7ed--- /dev/null+++ b/tests/unit/plugins/tool/test_spawn_worker_no_runner_reports.py@@ -0,0 +1,107 @@+"""AU-11 — a dispatched mission with nobody to run it must still reach the user.++The tool creates the mission, finds no Kontrollierer, and used to return after+a bare ``log.warning``. By then the user had already heard the spoken+acknowledgement, so the promise stood and the answer never came: the mission+sat PENDING until the next app start quietly marked it crash-recovered.++The fix publishes the SAME completion event a finished mission publishes, with+``success=False`` and a plain-language reason, so the speech pipeline speaks it.+"""+from __future__ import annotations++import asyncio+from typing import Any+from uuid import uuid4++from jarvis.core.bus import EventBus+from jarvis.core.events import JarvisAgentBackgroundCompleted+from jarvis.core.protocols import ExecutionContext+from jarvis.plugins.tool.spawn_worker import SpawnWorkerTool+from jarvis.voice.action_phrases import action_phrase+++class _FakeMissionManager:+ """Accepts the dispatch and hands back an id — like the real one."""++ def __init__(self) -> None:+ self.prompts: list[str] = []++ async def dispatch(+ self, *, prompt: str, language: str, source_actor: str+ ) -> str:+ self.prompts.append(prompt)+ return "mission_0001"+++class _FakeAnnouncer:+ async def compose(self, **kwargs: Any) -> str:+ return "On it."+++def _ctx(output_language: str) -> ExecutionContext:+ return ExecutionContext(+ trace_id=uuid4(),+ user_utterance="",+ config={"output_language": output_language},+ memory_read=None,+ )+++async def _drain() -> None:+ """Let the fire-and-forget dispatch task finish."""+ await asyncio.sleep(0.05)+++async def test_missing_kontrollierer_publishes_a_failed_completion() -> None:+ bus = EventBus()+ seen: list[JarvisAgentBackgroundCompleted] = []+ bus.subscribe(JarvisAgentBackgroundCompleted, seen.append)++ manager = _FakeMissionManager()+ tool = SpawnWorkerTool(+ bus=bus, manager=manager, kontrollierer=None, announcer=_FakeAnnouncer()+ )++ result = await tool.execute(+ {"utterance": "Build me a small website.", "action": ""}, _ctx("en")+ )+ await _drain()++ # The dispatch itself still happens — the UI keeps its mission card.+ assert result.success is True+ assert manager.prompts, "the mission was never dispatched"++ assert len(seen) == 1, "the dead end was reported zero or twice"+ event = seen[0]+ assert event.success is False+ assert event.utterance == "Build me a small website."+ assert event.error == action_phrase("spawn_no_runner", "en")+++async def test_the_reason_is_plain_language_in_the_turn_language() -> None:+ """No ids, no exception class names — and never German on an English turn."""+ bus = EventBus()+ seen: list[JarvisAgentBackgroundCompleted] = []+ bus.subscribe(JarvisAgentBackgroundCompleted, seen.append)++ for language in ("de", "en", "es"):+ seen.clear()+ tool = SpawnWorkerTool(+ bus=bus,+ manager=_FakeMissionManager(),+ kontrollierer=None,+ announcer=_FakeAnnouncer(),+ )+ await tool.execute(+ {"utterance": "Do the thing.", "action": ""}, _ctx(language)+ )+ await _drain()++ assert len(seen) == 1+ error = seen[0].error or ""+ assert error == action_phrase("spawn_no_runner", language)+ assert "mission_" not in error+ assert "Error" not in error and "Exception" not in error+ # The pipeline caps the spoken reason at 80 characters.+ assert len(error) <= 80diff --git a/tests/unit/workflows/test_failure_is_announced.py b/tests/unit/workflows/test_failure_is_announced.pynew file mode 100644index 0000000000..7352671e1f--- /dev/null+++ b/tests/unit/workflows/test_failure_is_announced.py@@ -0,0 +1,301 @@+"""AU-12 / AU-13 — a scheduled routine that breaks must say so.++Two silent deaths lived here:++* the scheduler only ``log.warning``-ed a cron trigger that failed, and only+ ``log.exception``-ed a tick that crashed — so a broken routine, or every+ routine at once, simply stopped happening;+* the runner ``break``s out of a failed step chain, which skips a trailing+ speak step — Jarvis went quiet exactly when it had the most to report.++Both now publish the announcement event every other background result travels+on (``AnnouncementRequested(kind="subagent")``), rate-limited so a routine that+fails every minute is not said sixty times an hour.++Fakes throughout — a real store on tmp_path, a fake runner/brain, no network.+"""+from __future__ import annotations++import asyncio+import time+from pathlib import Path+from typing import Any++import pytest++from jarvis.core.bus import EventBus+from jarvis.core.events import AnnouncementRequested+from jarvis.workflows.runner import FailureAnnouncer, WorkflowRunner+from jarvis.workflows.scheduler import WorkflowScheduler+from jarvis.workflows.schema import (+ BrainPromptStep,+ ManualTrigger,+ SpeakStep,+ WorkflowDef,+)+from jarvis.workflows.store import WorkflowStore+++async def store(tmp_path: Path) -> WorkflowStore:+ s = WorkflowStore(tmp_path / "wf.sqlite")+ await s.init()+ yield s+ await s.close()+++def _announcements(bus: EventBus) -> list[AnnouncementRequested]:+ seen: list[AnnouncementRequested] = []+ bus.subscribe(AnnouncementRequested, seen.append)+ return seen+++async def _await_run_state(store: WorkflowStore, run_id: str, state: str) -> None:+ for _ in range(50):+ await asyncio.sleep(0.01)+ run = await store.get_run(run_id)+ if run and run["state"] == state:+ return+ pytest.fail(f"Run did not reach state {state!r} within 500ms")+++class _BrokenBrain:+ """Async callable that always fails — a step that dies mid-chain."""++ async def __call__(self, prompt: str) -> str:+ raise RuntimeError("the notes file could not be opened")+++class _BrokenRunner:+ """Runner stand-in whose trigger never gets off the ground."""++ def __init__(self) -> None:+ self.attempts = 0++ async def trigger(self, workflow_id: str, *, trigger_reason: str) -> str:+ self.attempts += 1+ raise RuntimeError("no worker available")+++class _OneWorkflowStore:+ """Store stand-in holding exactly one overdue cron row."""++ def __init__(self, name: str = "Morning Briefing") -> None:+ self.rows = [+ {+ "id": "wf-0001",+ "name": name,+ "enabled": 1,+ "trigger_type": "cron",+ "cron_expression": "* * * * *",+ # Already due, so the tick fires it immediately.+ "next_run_at_ns": time.time_ns() - 1,+ }+ ]++ async def list_workflows(self) -> list[dict[str, Any]]:+ return list(self.rows)++ async def set_next_run(self, workflow_id: str, next_run_at_ns: int | None) -> None:+ self.rows[0]["next_run_at_ns"] = next_run_at_ns+++# ----------------------------------------------------------------------+# AU-13 — the runner+# ----------------------------------------------------------------------++async def test_failed_step_is_announced_to_the_user(store: WorkflowStore) -> None:+ bus = EventBus()+ seen = _announcements(bus)+ runner = WorkflowRunner(store=store, bus=bus, brain=_BrokenBrain())++ wf = WorkflowDef(+ name="Morning Briefing",+ trigger=ManualTrigger(),+ steps=(+ BrainPromptStep(label="Read the notes", prompt="summarise"),+ SpeakStep(text="here is your briefing"),+ ),+ )+ wid = await store.upsert_workflow(wf)+ run_id = await runner.trigger(wid)+ await _await_run_state(store, run_id, "failed")++ # The trailing speak step never ran — that part of the control flow is+ # correct and unchanged. The failure report is what must exist.+ assert len(seen) == 1+ text = seen[0].text+ assert seen[0].kind == "subagent"+ assert "Morning Briefing" in text+ assert "Read the notes" in text+ assert "the notes file could not be opened" in text+ # Plain language only — no exception class name, no run id.+ assert "RuntimeError" not in text+ assert run_id not in text+++async def test_failure_without_a_speakable_reason_still_announces(+ store: WorkflowStore,+) -> None:+ """An opaque error degrades to the reasonless sentence, never to silence."""++ class _OpaqueBrain:+ async def __call__(self, prompt: str) -> str:+ raise RuntimeError("exit 1")++ bus = EventBus()+ seen = _announcements(bus)+ runner = WorkflowRunner(store=store, bus=bus, brain=_OpaqueBrain())++ wf = WorkflowDef(+ name="Nightly Sync",+ trigger=ManualTrigger(),+ steps=(BrainPromptStep(prompt="go"),),+ )+ wid = await store.upsert_workflow(wf)+ run_id = await runner.trigger(wid)+ await _await_run_state(store, run_id, "failed")++ assert len(seen) == 1+ assert "Nightly Sync" in seen[0].text+ assert "exit 1" not in seen[0].text+ # No author label on that step, so the plain ordinal stands in.+ assert "1" in seen[0].text+++async def test_a_routine_failing_every_run_is_announced_once(+ store: WorkflowStore,+) -> None:+ """The anti-spam rule: first failure speaks, the repeats stay quiet."""+ bus = EventBus()+ seen = _announcements(bus)+ runner = WorkflowRunner(store=store, bus=bus, brain=_BrokenBrain())++ wf = WorkflowDef(+ name="Every Minute",+ trigger=ManualTrigger(),+ steps=(BrainPromptStep(prompt="go"),),+ )+ wid = await store.upsert_workflow(wf)+ for _ in range(5):+ run_id = await runner.trigger(wid)+ await _await_run_state(store, run_id, "failed")++ assert len(seen) == 1, "a repeating failure turned into a metronome"+++async def test_a_recovery_re_arms_the_next_failure(store: WorkflowStore) -> None:+ """A successful run clears the memory, so the NEXT failure is news again."""++ class _FlakyBrain:+ def __init__(self) -> None:+ self.calls = 0++ async def __call__(self, prompt: str) -> str:+ self.calls += 1+ if self.calls == 2:+ return "fine"+ raise RuntimeError("the notes file could not be opened")++ bus = EventBus()+ seen = _announcements(bus)+ runner = WorkflowRunner(store=store, bus=bus, brain=_FlakyBrain())++ wf = WorkflowDef(+ name="Flaky",+ trigger=ManualTrigger(),+ steps=(BrainPromptStep(prompt="go"),),+ )+ wid = await store.upsert_workflow(wf)+ for expected in ("failed", "completed", "failed"):+ run_id = await runner.trigger(wid)+ await _await_run_state(store, run_id, expected)++ assert len(seen) == 2+++# ----------------------------------------------------------------------+# AU-12 — the scheduler+# ----------------------------------------------------------------------++async def test_failed_cron_trigger_is_announced_to_the_user() -> None:+ bus = EventBus()+ seen = _announcements(bus)+ broken = _BrokenRunner()+ scheduler = WorkflowScheduler(+ store=_OneWorkflowStore(), runner=broken, bus=bus, # type: ignore[arg-type]+ )++ await scheduler._tick()++ assert broken.attempts == 1+ announcements = [e for e in seen if e.source_layer == "workflows.scheduler"]+ assert len(announcements) == 1+ assert "Morning Briefing" in announcements[0].text+ assert announcements[0].kind == "subagent"+ # The routine's name, never its id.+ assert "wf-0001" not in announcements[0].text+++async def test_a_cron_trigger_failing_every_minute_is_announced_once() -> None:+ bus = EventBus()+ seen = _announcements(bus)+ store = _OneWorkflowStore()+ scheduler = WorkflowScheduler(+ store=store, runner=_BrokenRunner(), bus=bus, # type: ignore[arg-type]+ )++ for _ in range(5):+ store.rows[0]["next_run_at_ns"] = time.time_ns() - 1+ await scheduler._tick()++ announcements = [e for e in seen if e.source_layer == "workflows.scheduler"]+ assert len(announcements) == 1+++async def test_a_crashed_tick_tells_the_user_the_routines_are_down() -> None:+ """The whole poll loop died — every routine stopped, so say so once."""++ class _DeadStore:+ async def list_workflows(self) -> list[dict[str, Any]]:+ raise RuntimeError("the workflow database is unreachable")++ bus = EventBus()+ seen = _announcements(bus)+ scheduler = WorkflowScheduler(+ store=_DeadStore(), runner=_BrokenRunner(), bus=bus, # type: ignore[arg-type]+ )+ scheduler.start()+ try:+ # Two ticks would happen back to back if the loop did not sleep 30s+ # after a crash; one announcement is all the user may hear either way.+ for _ in range(30):+ await asyncio.sleep(0.01)+ if seen:+ break+ finally:+ await scheduler.stop()++ announcements = [e for e in seen if e.source_layer == "workflows.scheduler"]+ assert len(announcements) == 1+ assert announcements[0].text+ assert "RuntimeError" not in announcements[0].text+++# ----------------------------------------------------------------------+# The shared suppression rule+# ----------------------------------------------------------------------++def test_failure_announcer_speaks_again_after_the_cooldown() -> None:+ announcer = FailureAnnouncer(cooldown_s=0.0)+ assert announcer.should_speak("wf") is True+ assert announcer.should_speak("wf") is True+++def test_failure_announcer_keys_are_independent() -> None:+ announcer = FailureAnnouncer()+ assert announcer.should_speak("a") is True+ assert announcer.should_speak("b") is True+ assert announcer.should_speak("a") is False+ announcer.clear("a")+ assert announcer.should_speak("a") is True