Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(proactivity): let the background work reach the user
Haraldf8b2a40333f6
diff --git a/conductor/__init__.py b/conductor/__init__.pyindex 969b34556a..6732e65cb9 100644--- a/conductor/__init__.py+++ b/conductor/__init__.py@@ -27,6 +27,7 @@ from __future__ import annotations__version__ = "0.1.0"+from .core.notify import NEWS_EVENT, RunNews, classify_runfrom .core.runner import Runnerfrom .core.scheduler import Schedulerfrom .core.schema import (@@ -56,13 +57,16 @@ __all__ = ["Job","JobSpec","ManualSchedule",+ "NEWS_EVENT","Run",+ "RunNews","RunStep","Runner","Schedule","Scheduler","ShellJobSpec","WebhookSchedule",+ "classify_run","ensure_seed_jobs","SEED_YAML_DIR",]diff --git a/conductor/core/notify.py b/conductor/core/notify.pynew file mode 100644index 0000000000..19904a8856--- /dev/null+++ b/conductor/core/notify.py@@ -0,0 +1,124 @@+"""Decide which finished run a human actually wants to hear about.++A scheduler that reports every run is noise. The URL healthcheck in+``conductor/seed/url_healthcheck.yaml`` runs every 300 seconds — announcing+its 300th consecutive success carries exactly zero information, and after two+days of that the user has learned to ignore Conductor entirely.++What carries information is a **change of state**:++* a job that was fine and has just started failing — that is news;+* a job that was failing and has just recovered — that is news;+* anything else (a repeat pass, a repeat failure) — silence.++The first run of a job has no predecessor. A first failure is still news (the+job never worked); a first success is not (nobody needs "your new job worked",+least of all right after boot, when every seed job runs for the first time).++This module deliberately produces **structured facts, never a sentence**.+Conductor is a standalone tool with no Jarvis import and no notion of the+user's language; the embedding host renders the wording and picks the locale.+See ``Runner._emit`` for how the facts leave the package.+"""+from __future__ import annotations++import re+from dataclasses import dataclass+from typing import Any, Literal++__all__ = ["NEWS_EVENT", "RunNews", "classify_run"]++#: The ``on_event`` name a piece of news is emitted under. Distinct from the+#: ``run.*`` lifecycle events so a dashboard subscriber (which wants every run)+#: and a notification subscriber (which wants only the news) never fight over+#: the same stream.+NEWS_EVENT = "job.news"++#: ``failing`` — the job just broke. ``recovered`` — the job works again.+NewsKind = Literal["failing", "recovered"]++_STATE_FAILED = "failed"+_STATE_COMPLETED = "completed"++#: Technical error text is a diagnostic, not a sentence for the user. It rides+#: along trimmed so a host can show it in a log/transcript track, and it is+#: capped so a stack trace can never become the payload.+_DETAIL_MAX_CHARS = 160+_WHITESPACE_RE = re.compile(r"\s+")+++@dataclass(frozen=True, slots=True)+class RunNews:+ """One announcement-worthy fact about a job, in structured form."""++ job_id: str+ job_name: str+ kind: NewsKind+ state: str+ run_id: str+ trigger: str+ #: Trimmed technical reason (empty when there is none). Never a sentence+ #: meant to be read aloud.+ detail: str = ""++ def as_payload(self) -> dict[str, Any]:+ """Flat dict for the ``on_event`` callback — JSON-safe throughout."""+ return {+ "job_id": self.job_id,+ "job_name": self.job_name,+ "kind": self.kind,+ "state": self.state,+ "run_id": self.run_id,+ "trigger": self.trigger,+ "detail": self.detail,+ }+++def _condense(text: str | None) -> str:+ """Collapse a multi-line error into one short, single-line diagnostic."""+ if not text:+ return ""+ flat = _WHITESPACE_RE.sub(" ", str(text)).strip()+ if len(flat) <= _DETAIL_MAX_CHARS:+ return flat+ return flat[: _DETAIL_MAX_CHARS - 1].rstrip() + "…"+++def classify_run(+ *,+ job_id: str,+ job_name: str,+ run_id: str,+ trigger: str,+ previous_state: str | None,+ new_state: str,+ error: str | None = None,+) -> RunNews | None:+ """Return the news in this run, or ``None`` when the run is not news.++ ``previous_state`` is the job's last terminal state before this run+ (``None`` when the job has never finished one). ``new_state`` is this+ run's terminal state (``completed`` / ``failed`` / ``cancelled``).++ A cancelled run is never news: somebody cancelled it on purpose, so they+ already know.+ """+ prev = (previous_state or "").strip().lower() or None+ new = (new_state or "").strip().lower()++ if new == _STATE_FAILED and prev != _STATE_FAILED:+ kind: NewsKind = "failing"+ elif new == _STATE_COMPLETED and prev == _STATE_FAILED:+ kind = "recovered"+ else:+ return None++ return RunNews(+ job_id=job_id,+ job_name=job_name,+ kind=kind,+ state=new,+ run_id=run_id,+ trigger=trigger,+ detail=_condense(error) if kind == "failing" else "",+ )diff --git a/conductor/core/runner.py b/conductor/core/runner.pyindex 5057dbdb6d..a10b2fc901 100644--- a/conductor/core/runner.py+++ b/conductor/core/runner.py@@ -5,6 +5,12 @@ One runner = many concurrent runs. Each run is started as its ownare informed via the ``on_event`` callback — so Jarvis (or any otherembed situation) can render live updates in the frontend withoutdepending on the Conductor package.++The same callback carries the one event a *person* cares about: ``job.news``+(:data:`conductor.core.notify.NEWS_EVENT`), emitted only when a job changes+state — it just started failing, or it just recovered. See ``notify.py`` for+why every-run chatter is deliberately not emitted, and why the payload is+structured facts rather than a finished sentence."""from __future__ import annotations@@ -15,6 +21,7 @@ import timefrom typing import TYPE_CHECKING, Any, Callablefrom ..jobs import HANDLERS+from .notify import NEWS_EVENT, classify_runfrom .schema import JobSpecif TYPE_CHECKING:@@ -74,6 +81,11 @@ class Runner:) -> None:job_id = job_row["id"]spec_json = job_row["spec_json"]+ # The job's terminal state BEFORE this run — the only thing that makes+ # this run's outcome newsworthy or not (see ``notify.classify_run``).+ # Read from the row fetched at trigger time; the scheduler never+ # overlaps two runs of the same job, so it is the live value.+ previous_state = job_row.get("last_run_state")# Reconstruct JobSpec from JSON — we know the type from 'type'try:@@ -89,6 +101,13 @@ class Runner:self._emit("run.failed", {"run_id": run_id, "job_id": job_id, "error": str(exc),})+ # A job whose spec no longer loads DID run and DID fail. Recording+ # that keeps the state machine honest — and makes the second+ # broken run silent instead of announcing the same breakage twice.+ await self._finish(+ job_row, run_id, trigger, previous_state,+ "failed", f"spec-deserialize: {exc}",+ )returnhandler = HANDLERS.get(spec.type)@@ -101,6 +120,10 @@ class Runner:"run_id": run_id, "job_id": job_id,"error": f"unknown type {spec.type}",})+ await self._finish(+ job_row, run_id, trigger, previous_state,+ "failed", f"no handler for type={spec.type}",+ )returnawait self._store.update_run(run_id, state="running")@@ -119,11 +142,14 @@ class Runner:error=f"{type(exc).__name__}: {exc}",metrics={"duration_ms": duration_ms},)- await self._store.set_last_run(job_id, time.time_ns(), "failed")self._emit("run.failed", {"run_id": run_id, "job_id": job_id, "error": str(exc),"duration_ms": duration_ms,})+ await self._finish(+ job_row, run_id, trigger, previous_state,+ "failed", f"{type(exc).__name__}: {exc}",+ )log.exception("Job %s run %s crashed", job_row["name"], run_id)return@@ -136,7 +162,6 @@ class Runner:error=result.error,metrics=result.metrics,)- await self._store.set_last_run(job_id, time.time_ns(), final_state)self._emit("run.finished", {"run_id": run_id, "job_id": job_id,"state": final_state,@@ -145,6 +170,39 @@ class Runner:"duration_ms": result.metrics.get("duration_ms", 0),"output_preview": (result.output or "")[:240],})+ await self._finish(+ job_row, run_id, trigger, previous_state, final_state, result.error,+ )++ # ------------------------------------------------------------------++ async def _finish(+ self,+ job_row: dict[str, Any],+ run_id: str,+ trigger: str,+ previous_state: str | None,+ new_state: str,+ error: str | None,+ ) -> None:+ """Record the job's terminal state and emit the news, if any.++ Order matters: the store is written first, so the state a subscriber+ reads back always matches the state it was told about.+ """+ job_id = job_row["id"]+ await self._store.set_last_run(job_id, time.time_ns(), new_state)+ news = classify_run(+ job_id=job_id,+ job_name=job_row.get("name") or "",+ run_id=run_id,+ trigger=trigger,+ previous_state=previous_state,+ new_state=new_state,+ error=error,+ )+ if news is not None:+ self._emit(NEWS_EVENT, news.as_payload())# ------------------------------------------------------------------diff --git a/jarvis/ui/desktop_app.py b/jarvis/ui/desktop_app.pyindex cc533d7881..4da709694f 100644--- a/jarvis/ui/desktop_app.py+++ b/jarvis/ui/desktop_app.py@@ -1158,6 +1158,130 @@ def acquire_single_instance_lock(time.sleep(0.3)+# ---------------------------------------------------------------------------+# Conductor -> voice bridge+# ---------------------------------------------------------------------------+# Conductor is a standalone OSS package that must never import ``jarvis``, so+# it cannot reach the EventBus itself. It hands out structured facts through+# the ``on_event`` callback its Runner has always had; THIS side turns them+# into a sentence and publishes it — the same seam every other embedded+# component uses to get the bus.+#+# Division of labour: Conductor decides WHETHER a finished run is news+# (``conductor.core.notify`` — state changes only, never every-run chatter);+# Jarvis decides WHAT IS SAID and in WHICH LANGUAGE, so no locale is ever+# baked into the standalone package.++#: One plain sentence per news kind and locale. No job ids, no exit codes, no+#: stack traces — the user hears the outcome; the technical reason rides along+#: in ``AnnouncementRequested.detail``, which the transcript shows and the+#: voice never speaks. Runtime voice output is the closed product surface, so+#: these strings stay localized (CLAUDE.md §1).+_CONDUCTOR_NEWS_PHRASES: dict[str, dict[str, str]] = {+ "failing": {+ "de": "Der geplante Job {name} schlägt gerade fehl.", # i18n-allow+ "en": "The scheduled job {name} has started failing.",+ "es": "El trabajo programado {name} está fallando.",+ },+ "recovered": {+ "de": "Der geplante Job {name} läuft wieder.", # i18n-allow+ "en": "The scheduled job {name} is working again.",+ "es": "El trabajo programado {name} vuelve a funcionar.",+ },+}+++def _conductor_news_sentence(kind: str, job_name: str, language: str) -> str:+ """Render one piece of Conductor news as a plain, speakable sentence.++ Returns ``""`` for an unknown kind or a nameless job — an announcement+ that cannot say WHICH job it means is worse than no announcement.+ """+ phrases = _CONDUCTOR_NEWS_PHRASES.get(kind)+ if phrases is None:+ return ""+ name = " ".join(str(job_name or "").split())+ if not name:+ return ""+ return phrases.get(language, phrases["en"]).format(name=name)+++def _make_conductor_announcer(+ bus: Any,+ brain_ref: Callable[[], Any],+ reply_language_ref: Callable[[], str],+) -> Callable[[str, dict[str, Any]], Any]:+ """Build the Conductor ``on_event`` callback that speaks its news.++ Everything except ``job.news`` is ignored here: the ``run.*`` lifecycle+ stream belongs to the dashboard, not to the voice. The callback is a+ coroutine function, so ``Runner._emit`` schedules it as its own task and+ the Conductor run loop never waits on the bus, the brain, or TTS.+ """++ async def _on_conductor_event(event: str, payload: dict[str, Any]) -> None:+ from conductor import NEWS_EVENT++ if event != NEWS_EVENT or bus is None:+ return+ from jarvis.core.events import AnnouncementRequested+ from jarvis.core.turn_language import (+ DEFAULT_LOCALE,+ resolve_output_language,+ )++ brain: Any = None+ with suppress(Exception):+ brain = brain_ref()+ pin = ""+ with suppress(Exception):+ pin = reply_language_ref() or ""+ # A background job has no user turn to read a language off, so the+ # pin wins, then the language the conversation is already running in,+ # then the default locale — resolved through the ONE resolver like+ # every other output layer (CLAUDE.md §1). The empty text is what+ # makes the conversation stickiness apply.+ language = resolve_output_language(+ pin,+ "",+ "",+ default=DEFAULT_LOCALE,+ conversation_language=getattr(brain, "conversation_language", ""),+ )+ text = _conductor_news_sentence(+ str(payload.get("kind") or ""),+ str(payload.get("job_name") or ""),+ language,+ )+ if not text:+ return+ try:+ result = bus.publish(+ AnnouncementRequested(+ source_layer="desktop_app.conductor",+ text=text,+ language=language,+ priority="normal",+ # A readback kind: a job that breaks at 03:00 must still+ # reach the user with no session open, so it has to+ # survive the hangup gate — the same choice+ # ``jarvis/tasks/runner.py`` makes for When-Then results.+ kind="subagent",+ detail=str(payload.get("detail") or "").strip() or None,+ )+ )+ if inspect.isawaitable(result):+ await result+ except Exception as exc: # noqa: BLE001 — news is never worth a crash+ from loguru import logger as _clog++ _clog.opt(exception=exc).warning(+ "Conductor announcement could not be published"+ )++ return _on_conductor_event++# ---------------------------------------------------------------------------# DesktopApp# ---------------------------------------------------------------------------@@ -2201,7 +2325,18 @@ class DesktopApp:from conductor import Scheduler as _CSchedconductor_store = _CStore() # ~/.conductor/conductor.sqlite- conductor_runner = _CRunner(conductor_store)+ # The bus reaches Conductor through its ``on_event`` seam, not the+ # other way round (Conductor never imports ``jarvis``). Without+ # this, every scheduled job ran into its own SQLite and the user+ # never learned that anything had happened at all (audit AU-01).+ conductor_runner = _CRunner(+ conductor_store,+ on_event=_make_conductor_announcer(+ server.bus,+ lambda: getattr(server.app.state, "brain", None),+ lambda: getattr(self.cfg.brain, "reply_language", ""),+ ),+ )conductor_scheduler = _CSched(conductor_store, conductor_runner)server.app.state.conductor_store = conductor_storeserver.app.state.conductor_runner = conductor_runnerdiff --git a/jarvis/workflows/seed.py b/jarvis/workflows/seed.pyindex ae4b787232..d39ed9d18c 100644--- a/jarvis/workflows/seed.py+++ b/jarvis/workflows/seed.py@@ -4,8 +4,9 @@ Philosophy: **small, immediately functional, demoable.** We want theuser, after the first launch, to open the WorkflowsView and see 3meaningful examples, be able to click "Run", and get a result right away.-- *Morning Briefing* (cron 30 7 * * *) — brain_prompt → speak chain. Produces- a mini standup announcement. No external service needed.+- *Morning Briefing* (cron 30 7 * * *, **enabled**) — brain_prompt → speak+ chain. Produces a mini standup announcement. No external service needed,+ which is exactly why it is the only cron seed that ships switched on.- *Code Review* (manual) — git diff capture followed by a brain review.- *URL Summary* (manual, input field ``url``) — brain_prompt with thetemplate variable {{input.url}}. Demos input binding.@@ -34,17 +35,31 @@ log = logging.getLogger(__name__)# Fixed UUIDs, so repeated seeding is idempotent — we recognize# existing seed entries by their ID and let user modifications# survive (no force overwrite).-_WF_MORGEN_BRIEFING = UUID("4a0f9e01-5c11-4c57-9c1d-10aabb000001")+_WF_MORNING_BRIEFING = UUID("4a0f9e01-5c11-4c57-9c1d-10aabb000001")_WF_CODE_REVIEW = UUID("4a0f9e01-5c11-4c57-9c1d-10aabb000002")_WF_URL_SUMMARY = UUID("4a0f9e01-5c11-4c57-9c1d-10aabb000003")_WF_EMAIL_DIGEST = UUID("4a0f9e01-5c11-4c57-9c1d-10aabb000004")_WF_GIT_STANDUP = UUID("4a0f9e01-5c11-4c57-9c1d-10aabb000005")-def _morgen_briefing() -> WorkflowDef:+def _morning_briefing() -> WorkflowDef:+ """The one scheduled workflow that ships ON.++ Every other cron seed here needs something a fresh install does not have+ (a configured Telegram bot, an authenticated ``gws`` CLI), so shipping+ them enabled would only produce failing runs. This one needs nothing but+ a brain and a voice — both of which the app already requires — so it is+ the honest default for "Jarvis does things without being asked"+ (audit AU-02: with every cron seed disabled, the scheduler polled an+ empty list forever and a fresh install did nothing on a schedule).++ Language is NOT pinned here: the prompt asks for the configured output+ language and the speak step passes ``auto``, so the one resolver decides+ (CLAUDE.md §1). The seed used to hardcode German for everyone.+ """now_ns = time.time_ns()return WorkflowDef(- id=_WF_MORGEN_BRIEFING,+ id=_WF_MORNING_BRIEFING,name="Morning Briefing",description=("Daily 7:30 announcement: current time, day of week, and a short, "@@ -56,9 +71,10 @@ def _morgen_briefing() -> WorkflowDef:label="Generate daily summary",prompt=("You are Jarvis. It's currently morning. Compose a short, "- "friendly morning announcement (max 3 sentences, in German). Include "- "the day of the week and a short motivating remark. NO "- "emojis, NO stating the time — the user can already see that."+ "friendly morning announcement (max 3 sentences) in the "+ "configured output language. Include the day of the week "+ "and a short motivating remark. NO emojis, NO stating the "+ "time — the user can already see that."),max_output_chars=500,),@@ -66,10 +82,10 @@ def _morgen_briefing() -> WorkflowDef:label="Play announcement",text="{{prev.output}}",priority="normal",- language="de",+ language="auto",),),- enabled=False, # cron default off — user must enable deliberately+ enabled=True,created_at_ns=now_ns,created_by="seed",tags=("demo", "brain", "speak"),@@ -257,7 +273,7 @@ def _git_standup_telegram() -> WorkflowDef:SEED_WORKFLOWS: tuple[WorkflowDef, ...] = (- _morgen_briefing(),+ _morning_briefing(),_code_review(),_url_summary(),_email_digest_telegram(),diff --git a/tests/unit/conductor/test_run_news.py b/tests/unit/conductor/test_run_news.pynew file mode 100644index 0000000000..d4c3feda80--- /dev/null+++ b/tests/unit/conductor/test_run_news.py@@ -0,0 +1,313 @@+"""Conductor tells the user about state CHANGES, never about every run.++Audit AU-01: the Conductor scheduler runs from the moment the app boots, three+seed jobs are enabled out of the box, and every result went into its own SQLite+and nowhere else. From outside, Jarvis looked like it had no proactivity at all.++The fix has two halves, and this file pins the Conductor half:++* ``conductor.core.notify.classify_run`` decides what is worth saying — a job+ that just started failing, or one that just recovered. The 300th consecutive+ pass of the 5-minute healthcheck is not news and stays silent.+* ``Runner`` emits that verdict through its existing ``on_event`` seam, so the+ package still never imports ``jarvis``.++Real store, real shell subprocess, real runner — no mocks.+"""+from __future__ import annotations++import asyncio+import sys+from pathlib import Path+from typing import Any++import pytest++from conductor import NEWS_EVENT, ConductorStore, Job, ManualSchedule, Runner, ShellJobSpec+from conductor.core.notify import classify_run+++async def store(tmp_path: Path) -> ConductorStore:+ s = ConductorStore(tmp_path / "conductor.sqlite")+ await s.init()+ yield s+ await s.close()+++class _EventSink:+ """Records every ``on_event`` call, exactly as a real observer sees it."""++ def __init__(self) -> None:+ self.events: list[tuple[str, dict[str, Any]]] = []++ def __call__(self, event: str, payload: dict[str, Any]) -> None:+ self.events.append((event, dict(payload)))++ @property+ def news(self) -> list[dict[str, Any]]:+ return [p for name, p in self.events if name == NEWS_EVENT]+++def _script(tmp_path: Path, name: str, body: str) -> str:+ path = tmp_path / name+ path.write_text(body, encoding="utf-8")+ return f'"{sys.executable}" "{path}"'+++async def _drain_runs() -> None:+ """Wait until every in-flight Conductor run task has finished."""+ for _ in range(50):+ pending = [+ t+ for t in asyncio.all_tasks()+ if t.get_name().startswith("conductor-run-") and not t.done()+ ]+ if not pending:+ return+ await asyncio.wait_for(+ asyncio.gather(*pending, return_exceptions=True), timeout=30.0+ )+ raise AssertionError("Conductor runs never settled")+++# ----------------------------------------------------------------------+# The rule itself+# ----------------------------------------------------------------------++def _classify(previous: str | None, new: str, error: str | None = None):+ return classify_run(+ job_id="job-1",+ job_name="GitHub-API Zen",+ run_id="run-1",+ trigger="interval",+ previous_state=previous,+ new_state=new,+ error=error,+ )+++def test_a_job_that_starts_failing_is_news() -> None:+ news = _classify("completed", "failed", error="status 500 does not match '2xx'")+ assert news is not None+ assert news.kind == "failing"+ assert news.job_name == "GitHub-API Zen"+++def test_a_first_ever_run_that_fails_is_news() -> None:+ """No predecessor and it broke — the user has never had a working job."""+ assert _classify(None, "failed") is not None+++def test_a_job_that_keeps_failing_says_nothing_more() -> None:+ """One alert per breakage. The second failing run is the same breakage."""+ assert _classify("failed", "failed") is None+++def test_the_three_hundredth_passing_healthcheck_is_silent() -> None:+ assert _classify("completed", "completed") is None+++def test_a_first_ever_run_that_succeeds_is_silent() -> None:+ """Every seed job runs for the first time right after boot. Announcing+ those would make the very first minute of the app pure noise."""+ assert _classify(None, "completed") is None+++def test_recovery_is_news() -> None:+ news = _classify("failed", "completed")+ assert news is not None+ assert news.kind == "recovered"+ # A recovery carries no error detail — there is nothing wrong to report.+ assert news.detail == ""+++def test_a_cancelled_run_is_never_news() -> None:+ """Somebody cancelled it on purpose, so they already know."""+ assert _classify("completed", "cancelled") is None+ assert _classify("failed", "cancelled") is None+++def test_the_technical_reason_is_condensed_to_one_short_line() -> None:+ stack = "Traceback (most recent call last):\n" + " frame\n" * 200+ news = _classify("completed", "failed", error=stack)+ assert news is not None+ assert "\n" not in news.detail+ assert len(news.detail) <= 160+++def test_payload_is_json_safe_and_names_the_job() -> None:+ news = _classify("completed", "failed", error="boom")+ assert news is not None+ payload = news.as_payload()+ assert payload["kind"] == "failing"+ assert payload["job_name"] == "GitHub-API Zen"+ assert all(isinstance(v, str) for v in payload.values())+++# ----------------------------------------------------------------------+# The Runner emits it+# ----------------------------------------------------------------------++async def _run_once(runner: Runner, job_id: str) -> None:+ await runner.trigger(job_id, trigger="interval")+ await _drain_runs()+++async def test_runner_announces_a_job_that_starts_failing(+ store: ConductorStore, tmp_path: Path+) -> None:+ sink = _EventSink()+ runner = Runner(store, on_event=sink)+ job = Job(+ name="GitHub-API Zen",+ spec=ShellJobSpec(+ command=_script(tmp_path, "ok.py", "print('fine')"), timeout_s=30.0+ ),+ schedule=ManualSchedule(),+ )+ jid = await store.upsert_job(job)++ # A first, healthy run: the dashboard hears about it, the user does not.+ await _run_once(runner, jid)+ assert sink.news == []+ assert any(name == "run.finished" for name, _ in sink.events)++ # Now the job breaks.+ broken = job.model_copy(+ update={+ "spec": ShellJobSpec(+ command=_script(tmp_path, "bad.py", "import sys; sys.exit(3)"),+ timeout_s=30.0,+ )+ }+ )+ await store.upsert_job(broken)+ await _run_once(runner, jid)++ assert len(sink.news) == 1+ assert sink.news[0]["kind"] == "failing"+ assert sink.news[0]["job_name"] == "GitHub-API Zen"+ assert sink.news[0]["job_id"] == jid+++async def test_runner_stays_silent_when_the_same_job_fails_again(+ store: ConductorStore, tmp_path: Path+) -> None:+ sink = _EventSink()+ runner = Runner(store, on_event=sink)+ jid = await store.upsert_job(+ Job(+ name="Broken",+ spec=ShellJobSpec(+ command=_script(tmp_path, "bad.py", "import sys; sys.exit(1)"),+ timeout_s=30.0,+ ),+ schedule=ManualSchedule(),+ )+ )++ await _run_once(runner, jid)+ await _run_once(runner, jid)+ await _run_once(runner, jid)++ assert len(sink.news) == 1, "one breakage, one announcement"+++async def test_runner_stays_silent_on_a_boring_repeat_success(+ store: ConductorStore, tmp_path: Path+) -> None:+ sink = _EventSink()+ runner = Runner(store, on_event=sink)+ jid = await store.upsert_job(+ Job(+ name="Healthy",+ spec=ShellJobSpec(+ command=_script(tmp_path, "ok.py", "print('ok')"), timeout_s=30.0+ ),+ schedule=ManualSchedule(),+ )+ )++ for _ in range(3):+ await _run_once(runner, jid)++ assert sink.news == []+++async def test_runner_announces_the_recovery(+ store: ConductorStore, tmp_path: Path+) -> None:+ sink = _EventSink()+ runner = Runner(store, on_event=sink)+ bad = ShellJobSpec(+ command=_script(tmp_path, "bad.py", "import sys; sys.exit(1)"), timeout_s=30.0+ )+ good = ShellJobSpec(+ command=_script(tmp_path, "ok.py", "print('back')"), timeout_s=30.0+ )+ job = Job(name="Flaky", spec=bad, schedule=ManualSchedule())+ jid = await store.upsert_job(job)++ await _run_once(runner, jid)+ await store.upsert_job(job.model_copy(update={"spec": good}))+ await _run_once(runner, jid)++ kinds = [n["kind"] for n in sink.news]+ assert kinds == ["failing", "recovered"]+++async def test_a_job_with_an_unknown_type_announces_once_not_every_run(+ store: ConductorStore,+) -> None:+ """A job whose spec no longer loads still 'ran' and still failed.++ Recording that terminal state is what keeps the second broken run quiet.+ """+ sink = _EventSink()+ runner = Runner(store, on_event=sink)+ jid = await store.upsert_job(+ Job(+ name="Rotten",+ spec=ShellJobSpec(command="echo hi"),+ schedule=ManualSchedule(),+ )+ )+ conn = store._require_conn()+ await conn.execute(+ "UPDATE jobs SET spec_json = ? WHERE id = ?",+ ('{"type": "not_a_real_type"}', jid),+ )++ await _run_once(runner, jid)+ await _run_once(runner, jid)++ assert len(sink.news) == 1+ assert sink.news[0]["kind"] == "failing"+++async def test_a_crashing_callback_never_kills_the_run(+ store: ConductorStore, tmp_path: Path+) -> None:+ """The Conductor loop must not depend on its observer behaving."""++ def _explode(event: str, payload: dict[str, Any]) -> None:+ raise RuntimeError("observer is broken")++ runner = Runner(store, on_event=_explode)+ jid = await store.upsert_job(+ Job(+ name="Resilient",+ spec=ShellJobSpec(+ command=_script(tmp_path, "ok.py", "print('still ran')"),+ timeout_s=30.0,+ ),+ schedule=ManualSchedule(),+ )+ )+ run_id = await runner.trigger(jid, trigger="manual")+ await _drain_runs()++ run = await store.get_run(run_id)+ assert run is not None+ assert run["state"] == "completed"diff --git a/tests/unit/ui/test_conductor_announcement_bridge.py b/tests/unit/ui/test_conductor_announcement_bridge.pynew file mode 100644index 0000000000..5e718ff0e7--- /dev/null+++ b/tests/unit/ui/test_conductor_announcement_bridge.py@@ -0,0 +1,195 @@+"""Conductor news must arrive as spoken words, in the user's language.++Audit AU-01, the Jarvis half: Conductor decides WHETHER a finished run is news+(``conductor.core.notify``, pinned in ``tests/unit/conductor/test_notify.py``);+this bridge decides WHAT IS SAID and in WHICH LANGUAGE, and publishes it as an+``AnnouncementRequested`` — the same event the skill/task/workflow layers use.++Two contracts live here:++* the wording is plain user language and never a job id, exit code, or stack+ trace (the technical reason rides in ``detail``, which is never spoken);+* the language comes from the ONE resolver (``resolve_output_language``), so a+ German conversation is never told about a broken job in English.++Real ``EventBus``, real event class — no mocks.+"""+from __future__ import annotations++from types import SimpleNamespace+from typing import Any++import pytest++from conductor import NEWS_EVENT+from jarvis.core.bus import EventBus+from jarvis.core.events import AnnouncementRequested+from jarvis.ui.desktop_app import _make_conductor_announcer+++class _Heard:+ """Everything the voice layer would have said."""++ def __init__(self, bus: EventBus) -> None:+ self.events: list[AnnouncementRequested] = []+ bus.subscribe(AnnouncementRequested, self._on)++ async def _on(self, event: AnnouncementRequested) -> None:+ self.events.append(event)++ @property+ def last(self) -> AnnouncementRequested:+ assert self.events, "expected an announcement, heard nothing"+ return self.events[-1]+++def _bridge(+ bus: EventBus,+ *,+ pin: str = "auto",+ conversation_language: str = "",+) -> Any:+ brain = SimpleNamespace(conversation_language=conversation_language)+ return _make_conductor_announcer(bus, lambda: brain, lambda: pin)+++def _failing(job_name: str = "GitHub-API Zen", detail: str = "") -> dict[str, Any]:+ return {+ "job_id": "7b4d7e01-5c11-4c57-9c1d-10cc00000001",+ "job_name": job_name,+ "kind": "failing",+ "state": "failed",+ "run_id": "run-1",+ "trigger": "interval",+ "detail": detail,+ }+++async def test_a_job_that_starts_failing_is_spoken_in_plain_words() -> None:+ bus = EventBus()+ heard = _Heard(bus)+ await _bridge(bus)(NEWS_EVENT, _failing(detail="status 500 does not match '2xx'"))++ said = heard.last.text+ assert said == "The scheduled job GitHub-API Zen has started failing."+ # No job id, no exit code, no stack trace in what the user hears.+ assert "7b4d7e01" not in said+ assert "500" not in said+ # The technical reason survives — on the transcript track, never spoken.+ assert heard.last.detail == "status 500 does not match '2xx'"+++async def test_recovery_is_spoken_too() -> None:+ bus = EventBus()+ heard = _Heard(bus)+ payload = _failing() | {"kind": "recovered", "state": "completed", "detail": ""}+ await _bridge(bus)(NEWS_EVENT, payload)++ assert heard.last.text == "The scheduled job GitHub-API Zen is working again."+ assert heard.last.detail is None+++async def test_a_german_pin_is_answered_in_german() -> None:+ bus = EventBus()+ heard = _Heard(bus)+ await _bridge(bus, pin="de")(NEWS_EVENT, _failing())++ assert heard.last.language == "de"+ # i18n-allow: the German voice output IS the fixture under test.+ assert heard.last.text == "Der geplante Job GitHub-API Zen schlägt gerade fehl."+++async def test_an_ongoing_spanish_conversation_keeps_its_language() -> None:+ """No pin, no user turn to read a language off — the conversation decides."""+ bus = EventBus()+ heard = _Heard(bus)+ await _bridge(bus, conversation_language="es")(NEWS_EVENT, _failing())++ assert heard.last.language == "es"+ assert heard.last.text == "El trabajo programado GitHub-API Zen está fallando."+++async def test_a_pin_beats_the_conversation_language() -> None:+ bus = EventBus()+ heard = _Heard(bus)+ await _bridge(bus, pin="en", conversation_language="de")(NEWS_EVENT, _failing())++ assert heard.last.language == "en"+++async def test_the_announcement_survives_a_hangup() -> None:+ """A job that breaks at 03:00 has to reach a user with no session open, so+ it must carry a readback kind (the pipeline's ``_READBACK_KINDS``)."""+ from jarvis.speech.pipeline import _READBACK_KINDS++ bus = EventBus()+ heard = _Heard(bus)+ await _bridge(bus)(NEWS_EVENT, _failing())++ assert heard.last.kind in _READBACK_KINDS+ # Normal priority: news, not an emergency that talks over the user.+ assert heard.last.priority == "normal"+++async def test_run_lifecycle_events_stay_out_of_the_voice() -> None:+ """``run.started`` / ``run.finished`` belong to the dashboard. If those were+ spoken, the 5-minute healthcheck alone would talk 288 times a day."""+ bus = EventBus()+ heard = _Heard(bus)+ bridge = _bridge(bus)+ for name in ("run.started", "run.finished", "run.failed"):+ await bridge(name, _failing())++ assert heard.events == []+++async def test_an_unknown_kind_says_nothing_rather_than_something_wrong() -> None:+ bus = EventBus()+ heard = _Heard(bus)+ await _bridge(bus)(NEWS_EVENT, _failing() | {"kind": "sideways"})++ assert heard.events == []+++async def test_a_nameless_job_says_nothing() -> None:+ """An announcement that cannot name the job is worse than silence."""+ bus = EventBus()+ heard = _Heard(bus)+ await _bridge(bus)(NEWS_EVENT, _failing(job_name=" "))++ assert heard.events == []+++async def test_a_broken_bus_never_reaches_the_conductor_loop() -> None:+ class _BrokenBus:+ def publish(self, event: Any) -> None:+ raise RuntimeError("bus is down")++ bridge = _make_conductor_announcer(+ _BrokenBus(), lambda: None, lambda: "auto"+ )+ # Must not raise — a job result is never worth taking the scheduler down.+ await bridge(NEWS_EVENT, _failing())+++async def test_an_unreadable_brain_still_gets_the_news_out() -> None:+ def _explode() -> Any:+ raise RuntimeError("brain not built yet")++ bus = EventBus()+ heard = _Heard(bus)+ bridge = _make_conductor_announcer(bus, _explode, lambda: "auto")+ await bridge(NEWS_EVENT, _failing())++ assert heard.last.language == "en"++[email protected]("language", ["de", "en", "es"])+def test_every_supported_locale_has_both_sentences(language: str) -> None:+ from jarvis.ui.desktop_app import _conductor_news_sentence++ for kind in ("failing", "recovered"):+ text = _conductor_news_sentence(kind, "Nightly Backup", language)+ assert text.endswith(".")+ assert "Nightly Backup" in text+ assert "{" not in textdiff --git a/tests/unit/workflows/test_seed_scheduled.py b/tests/unit/workflows/test_seed_scheduled.pynew file mode 100644index 0000000000..e3bcccdc1c--- /dev/null+++ b/tests/unit/workflows/test_seed_scheduled.py@@ -0,0 +1,84 @@+"""A fresh install must actually do something on a schedule.++Audit AU-02: all three cron seeds shipped ``enabled=False`` and the only+enabled ones were ManualTrigger, so the WorkflowScheduler polled an empty list+every 60 seconds forever. Jarvis had a scheduler and nothing to schedule.++Exactly one cron seed is now on — the Morning Briefing, because it is the only+one that needs nothing a fresh install does not have. The other two need a+configured Telegram bot (and an authenticated ``gws`` CLI), so enabling them+would just manufacture failing runs on somebody else's machine.+"""+from __future__ import annotations++from jarvis.workflows.schema import (+ BrainPromptStep,+ CronTrigger,+ ManualTrigger,+ SpeakStep,+)+from jarvis.workflows.seed import SEED_WORKFLOWS++_CREDENTIAL_FREE_STEPS = (BrainPromptStep, SpeakStep)+++def _seed(name: str):+ return next(wf for wf in SEED_WORKFLOWS if wf.name == name)+++def test_a_fresh_install_has_something_on_the_clock() -> None:+ scheduled = [+ wf+ for wf in SEED_WORKFLOWS+ if isinstance(wf.trigger, CronTrigger) and wf.enabled+ ]+ assert scheduled, "no enabled cron seed — the scheduler polls an empty list"+++def test_the_morning_briefing_is_the_one_that_ships_on() -> None:+ briefing = _seed("Morning Briefing")+ assert briefing.enabled+ assert isinstance(briefing.trigger, CronTrigger)++ others = [+ wf.name+ for wf in SEED_WORKFLOWS+ if isinstance(wf.trigger, CronTrigger) and wf.enabled+ ]+ assert others == ["Morning Briefing"]+++def test_the_morning_briefing_needs_no_credentials() -> None:+ """Only brain + speak. Nothing that reaches an external account, a shell,+ or a tool — so nothing that can stall on an approval nobody is there to+ give during an unattended 07:30 run."""+ briefing = _seed("Morning Briefing")+ assert briefing.steps+ for step in briefing.steps:+ assert isinstance(step, _CREDENTIAL_FREE_STEPS), (+ f"{step.kind} step needs something a fresh install may not have"+ )+++def test_the_morning_briefing_pins_no_language() -> None:+ """The one resolver decides the output language, not the seed+ (CLAUDE.md §1). This seed used to hardcode German for every downloader."""+ briefing = _seed("Morning Briefing")+ speak = next(s for s in briefing.steps if isinstance(s, SpeakStep))+ assert speak.language == "auto"+ prompts = " ".join(+ s.prompt for s in briefing.steps if isinstance(s, BrainPromptStep)+ )+ assert "in German" not in prompts+++def test_the_telegram_seeds_stay_off_until_telegram_is_configured() -> None:+ for name in ("Email Digest via Telegram", "Git Standup via Telegram"):+ assert not _seed(name).enabled, f"{name} needs credentials to work"+++def test_the_manual_seeds_are_untouched() -> None:+ for name in ("Code Review", "URL Summary"):+ wf = _seed(name)+ assert isinstance(wf.trigger, ManualTrigger)+ assert wf.enabled