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(conductor): a single blip on a frequent job no longer wakes the user twice
rubenluetke10-beepb1b52db5c244
diff --git a/conductor/core/notify.py b/conductor/core/notify.pyindex 19904a8856..0f68d11fed 100644--- a/conductor/core/notify.py+++ b/conductor/core/notify.py@@ -11,22 +11,52 @@ What carries information is a **change of state**:* 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).+Two refinements, both learned from the live box (2026-08-23):++**A single blip is not a breakage.** The 5-minute GitHub healthcheck hit one+504, one 403 (GitHub's unauthenticated rate limit) and a handful of DNS+drops, and every one of them woke the user twice — "has started failing",+then six minutes later "is working again". Every monitoring product that+people keep installed (Pingdom, UptimeRobot, healthchecks.io) confirms a+failure across several consecutive checks before it alerts. So a job that+runs frequently announces "failing" only once it has failed+:data:`FAILURES_TO_ANNOUNCE_FREQUENT` times in a row. A job that runs rarely+(daily cron, manual, webhook, long interval) cannot afford to wait three+runs — three days of silence about a broken daily report is worse than one+false alarm — so it still announces on the first failure. The threshold is+derived from the schedule by :func:`failures_to_announce`.++**A recovery is only news when the breakage was.** A failure that stayed+under the threshold was never spoken, so "it works again" would answer a+question nobody heard. The host tracks which jobs it announced as failing+(the Runner does, in memory) and passes that in as ``failing_was_announced``;+the rule itself stays a pure function.++The first run of a job has no predecessor. A first failure is still news for+a rarely-running job (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 theuser'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 annotationsimport refrom dataclasses import dataclassfrom typing import Any, Literal-__all__ = ["NEWS_EVENT", "RunNews", "classify_run"]+__all__ = [+ "FAILURES_TO_ANNOUNCE_FREQUENT",+ "FREQUENT_INTERVAL_MAX_S",+ "NEWS_EVENT",+ "RunNews",+ "classify_run",+ "failures_to_announce",+]#: 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)@@ -37,6 +67,16 @@ NEWS_EVENT = "job.news"#: ``failing`` — the job just broke. ``recovered`` — the job works again.NewsKind = Literal["failing", "recovered"]+#: An interval job that runs at least this often is "frequent": its next run+#: is minutes away, so waiting for confirmation costs little and saves a+#: false alarm. 15 minutes × 3 strikes = at most 45 minutes of an outage+#: before the user hears about it — and a 5-minute job confirms in 15.+FREQUENT_INTERVAL_MAX_S = 15 * 60++#: How many consecutive failures a frequent job needs before "failing" is+#: announced. Three is the industry habit (one blip, one retry, one confirm).+FAILURES_TO_ANNOUNCE_FREQUENT = 3+_STATE_FAILED = "failed"_STATE_COMPLETED = "completed"@@ -84,6 +124,26 @@ def _condense(text: str | None) -> str:return flat[: _DETAIL_MAX_CHARS - 1].rstrip() + "…"+def failures_to_announce(schedule_type: str | None, schedule_expr: str | None) -> int:+ """How many consecutive failures make a job's breakage news.++ ``schedule_type`` / ``schedule_expr`` are the denormalized columns of the+ ``jobs`` row (``"interval"`` + seconds as a string, ``"cron"`` + the+ expression, ``"manual"``, ``"webhook"``). Only a frequent interval job+ gets the confirmation window; everything else announces on the first+ failure because its next run is too far away to wait for.+ """+ if (schedule_type or "").strip().lower() != "interval":+ return 1+ try:+ seconds = int(float(str(schedule_expr or "").strip()))+ except ValueError:+ return 1+ if seconds <= 0:+ return 1+ return FAILURES_TO_ANNOUNCE_FREQUENT if seconds <= FREQUENT_INTERVAL_MAX_S else 1++def classify_run(*,job_id: str,@@ -93,6 +153,9 @@ def classify_run(previous_state: str | None,new_state: str,error: str | None = None,+ failure_streak: int = 1,+ failures_required: int = 1,+ failing_was_announced: bool = False,) -> RunNews | None:"""Return the news in this run, or ``None`` when the run is not news.@@ -100,15 +163,29 @@ def classify_run((``None`` when the job has never finished one). ``new_state`` is thisrun's terminal state (``completed`` / ``failed`` / ``cancelled``).+ ``failure_streak`` counts consecutive failed runs INCLUDING this one when+ it failed; ``failures_required`` is the threshold from+ :func:`failures_to_announce`. "Failing" is news exactly when the streak+ reaches the threshold — not before (unconfirmed blip), not after (same+ breakage, already announced). ``failing_was_announced`` says whether the+ host actually spoke a "failing" for this breakage; only then is the+ recovery news.+A cancelled run is never news: somebody cancelled it on purpose, so theyalready know."""prev = (previous_state or "").strip().lower() or Nonenew = (new_state or "").strip().lower()+ required = max(1, int(failures_required))+ streak = max(1, int(failure_streak))- if new == _STATE_FAILED and prev != _STATE_FAILED:+ if new == _STATE_FAILED:+ if streak != required:+ return Nonekind: NewsKind = "failing"elif new == _STATE_COMPLETED and prev == _STATE_FAILED:+ if not failing_was_announced:+ return Nonekind = "recovered"else:return Nonediff --git a/conductor/core/runner.py b/conductor/core/runner.pyindex a10b2fc901..f0140c48f3 100644--- a/conductor/core/runner.py+++ b/conductor/core/runner.py@@ -21,7 +21,7 @@ import timefrom typing import TYPE_CHECKING, Any, Callablefrom ..jobs import HANDLERS-from .notify import NEWS_EVENT, classify_run+from .notify import NEWS_EVENT, classify_run, failures_to_announcefrom .schema import JobSpecif TYPE_CHECKING:@@ -44,6 +44,11 @@ class Runner:) -> None:self._store = storeself._on_event = on_event+ # Job ids whose current breakage THIS runner announced as "failing".+ # A recovery is only news when the breakage was (see ``notify.py``);+ # in-memory on purpose — a "working again" about an outage nobody in+ # this session was told about is stale chatter, not news.+ self._failing_announced: set[str] = set()def set_callback(self, on_event: EventCallback) -> None:self._on_event = on_event@@ -192,6 +197,17 @@ class Runner:"""job_id = job_row["id"]await self._store.set_last_run(job_id, time.time_ns(), new_state)+ # The run's own terminal state is already persisted (every caller+ # writes ``update_run`` first), so the streak read back includes it.+ streak = 0+ if new_state == "failed":+ try:+ streak = await self._store.failure_streak(job_id)+ except Exception as exc: # noqa: BLE001 — counting must never+ # silence a real breakage; without a count, fall back to the+ # plain state change.+ log.warning("failure_streak(%s) failed: %s", job_id, exc)+ streak = 1 if previous_state != "failed" else 2news = classify_run(job_id=job_id,job_name=job_row.get("name") or "",@@ -200,9 +216,19 @@ class Runner:previous_state=previous_state,new_state=new_state,error=error,+ failure_streak=max(1, streak),+ failures_required=failures_to_announce(+ job_row.get("schedule_type"), job_row.get("schedule_expr")+ ),+ failing_was_announced=job_id in self._failing_announced,)- if news is not None:- self._emit(NEWS_EVENT, news.as_payload())+ if new_state == "completed":+ self._failing_announced.discard(job_id)+ if news is None:+ return+ if news.kind == "failing":+ self._failing_announced.add(job_id)+ self._emit(NEWS_EVENT, news.as_payload())# ------------------------------------------------------------------diff --git a/conductor/core/store.py b/conductor/core/store.pyindex 2e9ae2bca2..e4ea593224 100644--- a/conductor/core/store.py+++ b/conductor/core/store.py@@ -294,6 +294,33 @@ class ConductorStore:await cur.close()return [dict(r) for r in rows]+ async def failure_streak(self, job_id: str, *, cap: int = 64) -> int:+ """How many of the job's most recent terminal runs failed in a row.++ Walks the run history newest-first and counts ``failed`` until the+ first ``completed`` / ``cancelled`` run. Runs still ``pending`` or+ ``running`` are skipped, never counted. Capped at ``cap`` — the+ notify rule only compares against a small threshold, so nothing+ needs the exact length of a months-long outage.+ """+ conn = self._require_conn()+ cur = await conn.execute(+ "SELECT state FROM runs WHERE job_id = ? "+ "ORDER BY started_at_ns DESC, rowid DESC LIMIT ?",+ (job_id, max(1, int(cap))),+ )+ rows = await cur.fetchall()+ await cur.close()+ streak = 0+ for row in rows:+ state = str(row["state"] or "").strip().lower()+ if state in ("pending", "running"):+ continue+ if state != "failed":+ break+ streak += 1+ return streak+async def cleanup_interrupted_runs(self) -> int:"""Startup: all running/pending → failed (app-exit detected)."""conn = self._require_conn()diff --git a/docs/BUGS.md b/docs/BUGS.mdindex 27fe43c7cd..0e94929a82 100644--- a/docs/BUGS.md+++ b/docs/BUGS.md@@ -11644,3 +11644,65 @@ Plugin: the confirm loop runs on a wall-clock deadline, reads with a 3 s boundmoment the work between sleeps can block; bound by the clock, and bound everyblocking read inside it tighter than the loop. A sequential command channelmust never run a call that can block for longer than its own client's timeout.+++## BUG-169: "The scheduled job GitHub-API Zen has started failing" keeps interrupting — one 504, one 403 or one DNS drop on the 5-minute demo healthcheck was spoken twice, as a breakage and as a recovery (MEDIUM, FIXED 2026-08-23)++**Symptom (maintainer, 2026-08-23).** Jarvis kept speaking an English sentence+about a job the maintainer had never set up — heard as "the job kit up API+started failing / is successful". `data/jarvis_desktop.log` has the exact+wording: `📢 Announcement: 'The scheduled job GitHub-API Zen has started+failing.'` at 19:38:24, `'… is working again.'` at 19:44:24, `'… has started+failing.'` again at 21:02:27 and at 09:17:12 the next morning. "GitHub-API Zen"+is the Conductor seed job `conductor/seed/url_healthcheck.yaml` — a demo HTTP+monitor that GETs `https://api.github.com/zen` every 300 s and expects a 2xx.++**Root cause.** `conductor.core.notify.classify_run` (audit AU-01) announced+every change of terminal state: `completed → failed` was "failing",+`failed → completed` was "recovered", with no confirmation window at all.+`~/.conductor/conductor.sqlite` shows what that did on a real network over seven+days: 91 runs, 29 failed — 21 × `ConnectError: [Errno 11001] getaddrinfo failed`+(the box was offline 21:02–23:32), 6 × `timeout after 10.0s`, one+`status 504`, one `status 403` (GitHub's unauthenticated rate limit, 60/h per+IP shared with every other tool on the box). The 504 and the 403 were single+blips between healthy runs, and each one produced TWO spoken announcements six+minutes apart. No monitoring product people keep installed alerts on a single+failed check; every one of them confirms across consecutive checks first. The+voice was right that it was English — a background job has no user turn to read+a language off, so `resolve_output_language` fell through to `DEFAULT_LOCALE`+("en") until the first conversation of the session — but the English was not+the defect, the alert was.++**Fix.** Two rules, both in `conductor/core/notify.py`, both pure:++1. *A single blip is not a breakage.* `failures_to_announce(schedule_type,+ schedule_expr)` returns 3 for an interval job that runs at least every+ 15 minutes (`FREQUENT_INTERVAL_MAX_S`) and 1 for everything else — a daily+ cron, a manual or webhook job cannot wait three runs, three days of silence+ about a broken daily report is worse than a false alarm. "Failing" is news+ exactly when the consecutive-failure streak EQUALS the threshold: not before+ (unconfirmed), not after (same breakage, already announced — which also+ keeps a process restart from re-announcing an old outage).+2. *A recovery is only news when the breakage was.* `Runner` keeps the set of+ job ids it announced as failing, in memory on purpose, and passes+ `failing_was_announced`; a "working again" about a blip that was never+ spoken — or about an outage a previous process announced — answers a+ question nobody heard.++`ConductorStore.failure_streak(job_id)` walks the run history newest-first and+counts `failed` until the first `completed`/`cancelled` (skipping+pending/running), so the count survives restarts and needs no schema change.+`Runner._finish` reads it after `update_run` has persisted this run's own state.++**Tests.** `tests/unit/conductor/test_run_news.py` — `a_single_blip_on_a_frequent_job_is_not_news`,+`the_third_consecutive_failure_is_the_news`, `a_recovery_nobody_heard_the_breakage_of_is_silent`,+`a_rare_job_announces_on_the_first_failure`, and the real-runner pins+`a_frequent_job_blip_never_reaches_the_user`,+`a_frequent_job_announces_once_the_failure_is_confirmed`,+`a_runner_restart_does_not_replay_a_stale_recovery`,+`a_runner_restart_does_not_reannounce_an_old_outage`.++**Lesson.** A state machine that speaks is a monitoring product, and the first+question about any alert is "how many confirmations?". "Announce on change"+sounds like the minimum-noise rule and is the maximum-noise rule on a flaky+network: every blip is two changes.diff --git a/tests/unit/conductor/test_run_news.py b/tests/unit/conductor/test_run_news.pyindex d4c3feda80..984c5c9e7f 100644--- a/tests/unit/conductor/test_run_news.py+++ b/tests/unit/conductor/test_run_news.py@@ -23,8 +23,20 @@ from typing import Anyimport pytest-from conductor import NEWS_EVENT, ConductorStore, Job, ManualSchedule, Runner, ShellJobSpec-from conductor.core.notify import classify_run+from conductor import (+ NEWS_EVENT,+ ConductorStore,+ IntervalSchedule,+ Job,+ ManualSchedule,+ Runner,+ ShellJobSpec,+)+from conductor.core.notify import (+ FAILURES_TO_ANNOUNCE_FREQUENT,+ classify_run,+ failures_to_announce,+)@pytest.fixture@@ -75,7 +87,15 @@ async def _drain_runs() -> None:# The rule itself# -----------------------------------------------------------------------def _classify(previous: str | None, new: str, error: str | None = None):+def _classify(+ previous: str | None,+ new: str,+ error: str | None = None,+ *,+ streak: int = 1,+ required: int = 1,+ announced: bool = False,+):return classify_run(job_id="job-1",job_name="GitHub-API Zen",@@ -84,6 +104,9 @@ def _classify(previous: str | None, new: str, error: str | None = None):previous_state=previous,new_state=new,error=error,+ failure_streak=streak,+ failures_required=required,+ failing_was_announced=announced,)@@ -101,7 +124,8 @@ def test_a_first_ever_run_that_fails_is_news() -> 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+ assert _classify("failed", "failed", streak=2) is None+ assert _classify("failed", "failed", streak=7, required=3) is Nonedef test_the_three_hundredth_passing_healthcheck_is_silent() -> None:@@ -115,13 +139,53 @@ def test_a_first_ever_run_that_succeeds_is_silent() -> None:def test_recovery_is_news() -> None:- news = _classify("failed", "completed")+ news = _classify("failed", "completed", announced=True)assert news is not Noneassert news.kind == "recovered"# A recovery carries no error detail — there is nothing wrong to report.assert news.detail == ""+def test_a_recovery_nobody_heard_the_breakage_of_is_silent() -> None:+ """Live box 2026-08-23: one 504 on the 5-minute healthcheck woke the user+ twice — "started failing", six minutes later "working again". If the+ blip stayed under the threshold and was never spoken, "it works again"+ answers a question nobody heard."""+ assert _classify("failed", "completed", announced=False) is None+++# ----------------------------------------------------------------------+# Confirmation window for frequent jobs+# ----------------------------------------------------------------------++def test_a_frequent_job_needs_three_strikes() -> None:+ assert failures_to_announce("interval", "300") == FAILURES_TO_ANNOUNCE_FREQUENT+ assert failures_to_announce("interval", "900") == FAILURES_TO_ANNOUNCE_FREQUENT+++def test_a_rare_job_announces_on_the_first_failure() -> None:+ """A broken daily report must not stay silent for three days."""+ assert failures_to_announce("interval", "3600") == 1+ assert failures_to_announce("cron", "0 9 * * 1-5") == 1+ assert failures_to_announce("manual", None) == 1+ assert failures_to_announce("webhook", None) == 1+ assert failures_to_announce(None, None) == 1+ assert failures_to_announce("interval", "not-a-number") == 1+++def test_a_single_blip_on_a_frequent_job_is_not_news() -> None:+ assert _classify("completed", "failed", "status 504", required=3, streak=1) is None+ assert _classify("failed", "failed", "status 504", required=3, streak=2) is None+++def test_the_third_consecutive_failure_is_the_news() -> None:+ news = _classify("failed", "failed", "getaddrinfo failed", required=3, streak=3)+ assert news is not None+ assert news.kind == "failing"+ # ...and the fourth is the same breakage, already announced.+ assert _classify("failed", "failed", "still down", required=3, streak=4) is None++def test_a_cancelled_run_is_never_news() -> None:"""Somebody cancelled it on purpose, so they already know."""assert _classify("completed", "cancelled") is None@@ -235,6 +299,113 @@ async def test_runner_stays_silent_on_a_boring_repeat_success(assert sink.news == []+async def _force_failure_streak(store: ConductorStore, job_id: str, n: int) -> None:+ """Write ``n`` failed terminal runs straight into the store — the same+ rows a real streak leaves behind, without waiting for real runs."""+ for _ in range(n):+ rid = await store.create_run(job_id, trigger="interval")+ await store.update_run(rid, state="failed", error="status 504")+ await store.set_last_run(job_id, 1, "failed")+++async def test_a_frequent_job_blip_never_reaches_the_user(+ store: ConductorStore, tmp_path: Path+) -> None:+ """The 5-minute healthcheck hits one 504 and is fine again: silence."""+ 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('ok')"), timeout_s=30.0+ )+ job = Job(name="GitHub-API Zen", spec=good, schedule=IntervalSchedule(seconds=300))+ jid = await store.upsert_job(job)++ await _run_once(runner, jid) # healthy+ await store.upsert_job(job.model_copy(update={"spec": bad}))+ await _run_once(runner, jid) # one blip+ await store.upsert_job(job.model_copy(update={"spec": good}))+ await _run_once(runner, jid) # fine again++ assert sink.news == [], "a single blip must not wake the user twice"+++async def test_a_frequent_job_announces_once_the_failure_is_confirmed(+ 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('ok')"), timeout_s=30.0+ )+ job = Job(name="GitHub-API Zen", spec=bad, schedule=IntervalSchedule(seconds=300))+ jid = await store.upsert_job(job)++ for _ in range(FAILURES_TO_ANNOUNCE_FREQUENT - 1):+ await _run_once(runner, jid)+ assert sink.news == [], "not yet confirmed"++ await _run_once(runner, jid)+ assert [n["kind"] for n in sink.news] == ["failing"]++ await _run_once(runner, jid)+ assert len(sink.news) == 1, "the same outage is announced once"++ await store.upsert_job(job.model_copy(update={"spec": good}))+ await _run_once(runner, jid)+ assert [n["kind"] for n in sink.news] == ["failing", "recovered"]+++async def test_a_runner_restart_does_not_replay_a_stale_recovery(+ store: ConductorStore, tmp_path: Path+) -> None:+ """The outage was announced by a previous process (or never at all): a+ fresh runner seeing the first success says nothing about it."""+ job = Job(+ name="GitHub-API Zen",+ spec=ShellJobSpec(+ command=_script(tmp_path, "ok.py", "print('ok')"), timeout_s=30.0+ ),+ schedule=IntervalSchedule(seconds=300),+ )+ jid = await store.upsert_job(job)+ await _force_failure_streak(store, jid, 10)++ sink = _EventSink()+ runner = Runner(store, on_event=sink) # a fresh process+ await _run_once(runner, jid)++ assert sink.news == []+++async def test_a_runner_restart_does_not_reannounce_an_old_outage(+ store: ConductorStore, tmp_path: Path+) -> None:+ """Ten failures already on disk, still failing after boot: the streak is+ way past the threshold, so this is the same breakage, not new news."""+ job = Job(+ name="GitHub-API Zen",+ spec=ShellJobSpec(+ command=_script(tmp_path, "bad.py", "import sys; sys.exit(1)"),+ timeout_s=30.0,+ ),+ schedule=IntervalSchedule(seconds=300),+ )+ jid = await store.upsert_job(job)+ await _force_failure_streak(store, jid, 10)++ sink = _EventSink()+ runner = Runner(store, on_event=sink)+ await _run_once(runner, jid)++ assert sink.news == []++async def test_runner_announces_the_recovery(store: ConductorStore, tmp_path: Path) -> None: