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(workflows): brain_prompt runs as an isolated agent turn, and the Morning Briefing reasons over tools (BUG-212)
rubenluetke10-beepf5454da4b828
diff --git a/docs/BUGS.md b/docs/BUGS.mdindex 1f0c8e4378..443ad03c92 100644--- a/docs/BUGS.md+++ b/docs/BUGS.md@@ -14867,3 +14867,60 @@ asserts `dictionary_bias=False`),**Related.** BUG-185 (the echo guard, which stays as the net for the voicelane), F14 (dictation builds its own prompt-free provider), AP-21/22 (theopt-out rides the same cross-family chain).++## BUG-212: the Morning Briefing arrived at random hours, and only ever said hello (HIGH, FIXED 2026-09-02)++**Symptom.** The scheduled Morning Briefing (cron `30 7 * * *`) was spoken+once a day but at 10:15, 20:49, 15:04, 11:18 — never at 07:30 — and every+time it was three sentences of greeting ("Good morning. It's Wednesday, a+fresh start…"), no calendar, no mail, no news. The recurring Automations+(`jarvis/tasks`) drifted the same way: a daily 07:30 task that once fired+late re-armed at "then + 24 h" and stayed late for good.++**Root cause.** Three things stacked.+1. *Catch-up without grace.* `WorkflowScheduler._tick` fired ANY row whose+ stored `next_run_at_ns` was `<= now`, however stale. The 07:30 slot is+ stored the evening before, the app is not running at 07:30, and the first+ tick after boot fires it — every run in `workflow_runs` starts at the+ exact second the `Workflow scheduler started` log line appears. The task+ scheduler (`hydrate()`) and the Conductor had the identical pattern, and+ `TaskScheduler._rearm_every` re-armed at `now + interval` instead of the+ `start_at` grid, so one late firing shifted the schedule permanently.+2. *A greeting prompt on the chat path.* The seed asked for "a short, friendly+ morning announcement (max 3 sentences)", and a `brain_prompt` step ran+ `BrainManager.__call__` → `generate()`: the LIVE voice history, the full+ tool surface, no allowlist. Nothing in the chain could look anything up.+3. *No date in the isolated turn.* `BrainManager.run_task` (the Automations+ path) dispatched without `turn_context`; in the default cache-optimized+ prompt layout that block carries the date and time, so a scheduled turn+ did not know what day it was although its prompts say the date is in+ context.++**Fix.** One misfire policy for every scheduler (`jarvis/core/misfire.py`,+`MISFIRE_GRACE_S` = 30 min): a slot later than that is **missed** — recorded+as a `missed` workflow run (dated at the slot, with the reason) or a `missed`+task step, `WorkflowScheduled(reason="missed")` on the bus, the schedule+continues from the next occurrence, the runner is never called. Within the+grace the slot still fires (a slow boot at 07:35 is still the morning).+One-shot task triggers keep firing late (ADR-0005 H9: a reminder survives a+crash). Recurring tasks re-arm on their wall-clock grid+(`next_every_due_ns`). `BrainPromptStep` grew `tools` and `model_tier`, and+the workflow runner prefers `brain.run_task(...)` — an isolated turn with an+empty history and the step's allowlist — over the callable chat path.+`run_task` now passes `turn_context`. The seed Morning Briefing is v2: a+read-only allowlist (`google_calendar`, `gmail`, `wiki-recall`,+`search_web`) and a prompt that grounds every sentence in tool output, greets+by the actual time of day and skips a disconnected area in one clause;+`ensure_seed_workflows` migrates the shipped v1 row (recognised by its+prompt, `created_by == "seed"`) and keeps the user's on/off choice. The+Workflows view renders `missed` as a neutral state with the reason (en/de/es).++**Guard.** `tests/unit/workflows/test_misfire.py`,+`tests/unit/tasks/test_scheduler_misfire.py`,+`tests/unit/conductor/test_misfire.py` (pins the Conductor's grace to the+app-wide one), `tests/unit/workflows/test_brain_prompt_isolated.py`,+`tests/unit/workflows/test_seed_scheduled.py` (v2 shape + migration).++**Related.** ADR-0005 (misfire handling was listed as "not required" — it+was), AU-02 (the one cron seed that ships on), AP-31 (the grace is a module+constant, not a config field nobody reads).diff --git a/jarvis/brain/manager.py b/jarvis/brain/manager.pyindex 504de372a9..8fed84d1b2 100644--- a/jarvis/brain/manager.py+++ b/jarvis/brain/manager.py@@ -13203,6 +13203,16 @@ class BrainManager:"""intent = "deep" if model_tier == "deep" else "fast"tools = self._select_task_tools(allowed_tools)+ # The per-turn context (date/time, awareness, wiki) rides on the user+ # message in cache-optimized mode; without it a scheduled turn did not+ # know what day it was (BUG-212 — the morning brief prompts say "the+ # date is in your context" and it was not). Legacy mode carries it in+ # the system prompt and this stays empty.+ try:+ turn_context = self._build_turn_context()+ except Exception: # noqa: BLE001 — the context block is a nicety+ log.debug("run_task: turn context skipped", exc_info=True)+ turn_context = ""attempts: list[str] = [self._active_name]failures: list[str] = []while attempts:@@ -13221,6 +13231,7 @@ class BrainManager:)agg = await dispatcher.dispatch(prompt, history=[], intent_level=intent, trace_id=trace_id,+ turn_context=turn_context,)return agg.text or ""except Exception as exc:diff --git a/jarvis/workflows/runner.py b/jarvis/workflows/runner.pyindex 6a9353381b..5a79796433 100644--- a/jarvis/workflows/runner.py+++ b/jarvis/workflows/runner.py@@ -433,7 +433,7 @@ class WorkflowRunner:"No brain available — workflow requires a BrainManager")prompt = _expand_template(step.prompt, outputs, input_data)- reply = await _maybe_await_brain(self._brain, prompt)+ reply = await _run_isolated_or_call(self._brain, step, prompt)# Cap at the user-defined max_output_charscap = getattr(step, "max_output_chars", 2000)if len(reply) > cap:@@ -607,8 +607,8 @@ class WorkflowRunner:cfg = load_config()chat_id = cfg.integrations.telegram.chat_id.strip()parse_mode = cfg.integrations.telegram.parse_mode or "Markdown"- except Exception: # noqa: BLE001- pass+ except Exception: # noqa: BLE001 — no config = the error below+ log.debug("telegram_send: config chat_id unavailable", exc_info=True)if not chat_id:raise RuntimeError("Telegram chat ID not set — either specify 'chat_id' in "@@ -679,6 +679,28 @@ def _expand_template(return _TEMPLATE_RE.sub(repl, s)+async def _run_isolated_or_call(brain: Any, step: Any, prompt: str) -> str:+ """One brain turn for a ``brain_prompt`` step.++ A ``BrainManager`` exposes ``run_task`` — an isolated agentic turn with an+ EMPTY history and the step's tool allowlist. That is the path a scheduled+ step must take: the plain callable (``BrainManager.__call__`` →+ ``generate``) runs the LIVE voice conversation's history and full tool+ surface, so a 07:30 routine would answer inside whatever the user was+ last talking about and could touch any tool (BUG-212). Brains without+ ``run_task`` (test fakes, minimal providers) keep the callable path.+ """+ run_task = getattr(brain, "run_task", None)+ if callable(run_task):+ result = await run_task(+ prompt=prompt,+ allowed_tools=tuple(getattr(step, "tools", ()) or ()),+ model_tier=getattr(step, "model_tier", "auto") or "auto",+ )+ return str(result or "")+ return await _maybe_await_brain(brain, prompt)++async def _maybe_await_brain(brain: Any, prompt: str) -> str:"""The brain can be: callable(str) -> Awaitable[str], or an object with``__call__``, or respond(thread_id, text, store)-like. We try thediff --git a/jarvis/workflows/seed.py b/jarvis/workflows/seed.pyindex d39ed9d18c..be5e6b0ac9 100644--- a/jarvis/workflows/seed.py+++ b/jarvis/workflows/seed.py@@ -5,8 +5,10 @@ user, 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 * * *, **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.+ chain. An isolated agent turn over the read-only tools that are connected+ (calendar, mail, memory, web/weather) produces a spoken day briefing. It+ needs no credentials to run at all, 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.@@ -56,30 +58,35 @@ def _morning_briefing() -> WorkflowDef:Language is NOT pinned here: the prompt asks for the configured outputlanguage and the speak step passes ``auto``, so the one resolver decides(CLAUDE.md §1). The seed used to hardcode German for everyone.++ Version 2 (BUG-212): the first seed asked for "a short, friendly morning+ announcement" and got exactly that — a greeting and a motivational+ phrase, no facts. The step now runs as an isolated agent turn with a+ read-only tool allowlist (calendar, mail, memory, web + weather) and a+ prompt that grounds every sentence in tool output. Tools that are not+ connected on an install are simply skipped, so a fresh box still gets a+ briefing — an honest one about what is and is not connected."""now_ns = time.time_ns()return WorkflowDef(id=_WF_MORNING_BRIEFING,name="Morning Briefing",description=(- "Daily 7:30 announcement: current time, day of week, and a short, "- "friendly greeting. Demonstrates a brain_prompt → speak chain."+ "Daily 07:30 spoken briefing: today's calendar, mail that matters, "+ "what you noted for today, headlines and weather — from the tools "+ "that are connected, nothing invented."),trigger=CronTrigger(expression="30 7 * * *"),steps=(BrainPromptStep(- label="Generate daily summary",- prompt=(- "You are Jarvis. It's currently morning. Compose a short, "- "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,+ label="Compile the briefing",+ prompt=_MORNING_BRIEFING_PROMPT,+ max_output_chars=1_600,+ tools=MORNING_BRIEFING_TOOLS,+ model_tier="auto",),SpeakStep(- label="Play announcement",+ label="Speak the briefing",text="{{prev.output}}",priority="normal",language="auto",@@ -92,6 +99,47 @@ def _morning_briefing() -> WorkflowDef:)+#: Read-side grants for the briefing. Every name is a live tool name or a+#: plugin prefix (``grant_matches``); a name that is not connected is skipped+#: by ``BrainManager._select_task_tools``. No tool here can send, write or+#: delete anything, so an unattended 07:30 run never waits on an approval.+MORNING_BRIEFING_TOOLS: tuple[str, ...] = (+ "google_calendar", "gmail", "wiki-recall", "search_web",+)++#: Marker of the shipped v1 prompt — how the migration recognises the old+#: seed row (and ONLY that row: a user's own edit never carries it).+_LEGACY_MORNING_BRIEFING_MARKER = "Compose a short, friendly morning announcement"++_MORNING_BRIEFING_PROMPT = """\+You are Jarvis, compiling the user's daily briefing that will be SPOKEN aloud.+The current date and time are in your context: open with the greeting that fits+the actual time of day (morning, afternoon or evening) and name the weekday.++Gather the facts with the tools you actually have in this turn. Every sentence+below must come from tool output. When a tool for an area is not available,+skip that area in one short clause (e.g. "the calendar is not connected yet")+and move on. Never invent an event, a mail, a headline or a city.++1. Calendar (a calendar tool): today's events. No events: the day is free.+ One: name it with its time. Several: the count plus the next one with its+ time. If the next event starts within the hour, say so.+2. Mail (a mail tool): unread mail. Name at most three that matter, each as+ sender and subject in one clause. Never read a mail body out.+3. Memory (wiki-recall): anything the user noted as due or planned for today.+4. World (search_web): the two or three headlines that matter most for the+ user's interests, each with its source named. If the user's city is known+ from memory, one clause of weather from search_web ("weather <city> today":+ current conditions, high and low). If no city is known, no weather.++Then write the briefing: 5 to 8 short sentences, most important first, plain+prose for speech — no bullets, no headings, no emojis, no markdown, no URLs.+Close with one sentence on what matters most today. Do not describe your+process and do not say that you searched. Write in the configured output+language.+"""++def _code_review() -> WorkflowDef:now_ns = time.time_ns()return WorkflowDef(@@ -293,8 +341,16 @@ async def ensure_seed_workflows(store: WorkflowStore) -> int:for wf in SEED_WORKFLOWS:existing = await store.get_workflow(str(wf.id))if existing is not None:- if wf.id == _WF_CODE_REVIEW and _is_legacy_code_review(existing):+ legacy = (+ (wf.id == _WF_CODE_REVIEW and _is_legacy_code_review(existing))+ or (wf.id == _WF_MORNING_BRIEFING+ and _is_legacy_morning_briefing(existing))+ )+ if legacy:await store.upsert_workflow(wf)+ # The user's on/off choice outlives a seed upgrade: an upsert+ # writes the seed's ``enabled``, so restore the row's own.+ await store.set_enabled(str(wf.id), bool(existing.get("enabled")))migrated += 1continueawait store.upsert_workflow(wf)@@ -306,6 +362,21 @@ async def ensure_seed_workflows(store: WorkflowStore) -> int:return added+def _is_legacy_morning_briefing(row: dict[str, object]) -> bool:+ """Identify only the shipped v1 greeting seed, never a user's own edit."""+ if row.get("created_by") != "seed":+ return False+ try:+ definition = WorkflowDef.model_validate_json(str(row.get("def_json") or ""))+ except Exception: # noqa: BLE001 - malformed legacy data stays user-owned+ return False+ return any(+ isinstance(step, BrainPromptStep)+ and _LEGACY_MORNING_BRIEFING_MARKER in step.prompt+ for step in definition.steps+ )++def _is_legacy_code_review(row: dict[str, object]) -> bool:"""Identify only the shipped dead seed, never an arbitrary user workflow."""if row.get("created_by") != "seed":diff --git a/tests/unit/workflows/test_brain_prompt_isolated.py b/tests/unit/workflows/test_brain_prompt_isolated.pynew file mode 100644index 0000000000..1254449dab--- /dev/null+++ b/tests/unit/workflows/test_brain_prompt_isolated.py@@ -0,0 +1,142 @@+"""BUG-212 — a ``brain_prompt`` step is an isolated agent turn.++The step used to call ``BrainManager.__call__`` → ``generate()``: the LIVE+voice conversation's history and the full tool surface. A 07:30 routine then+answered inside whatever the user last talked about and had no allowlist.+With a brain that exposes ``run_task`` the step now runs that — empty+history, the step's own tools, its model tier. Brains without ``run_task``+(fakes, minimal providers) keep the callable path.+"""+from __future__ import annotations++import asyncio+from pathlib import Path+from typing import Any++import pytest++from jarvis.core.bus import EventBus+from jarvis.workflows.runner import WorkflowRunner+from jarvis.workflows.schema import BrainPromptStep, ManualTrigger, 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()+++class _ManagerLikeBrain:+ """Both entry points, so the test can see which one the runner picked."""++ def __init__(self) -> None:+ self.task_calls: list[dict[str, Any]] = []+ self.chat_calls: list[str] = []++ async def run_task(self, *, prompt: str, allowed_tools: tuple[str, ...] = (),+ model_tier: str = "auto", trace_id: Any = None) -> str:+ self.task_calls.append({+ "prompt": prompt, "allowed_tools": allowed_tools, "model_tier": model_tier,+ })+ return "isolated reply"++ async def __call__(self, prompt: str) -> str:+ self.chat_calls.append(prompt)+ return "chat reply"+++class _CallableOnlyBrain:+ def __init__(self) -> None:+ self.calls: list[str] = []++ async def __call__(self, prompt: str) -> str:+ self.calls.append(prompt)+ return "plain reply"+++async def _run(store: WorkflowStore, runner: WorkflowRunner, wf: WorkflowDef) -> dict[str, Any]:+ wid = await store.upsert_workflow(wf)+ run_id = await runner.trigger(wid)+ for _ in range(100):+ await asyncio.sleep(0.01)+ run = await store.get_run(run_id)+ if run and run["state"] in ("completed", "failed"):+ return run+ pytest.fail("run did not finish")+++async def test_the_step_runs_as_an_isolated_task_turn_with_its_tools(+ store: WorkflowStore,+) -> None:+ brain = _ManagerLikeBrain()+ runner = WorkflowRunner(store=store, bus=EventBus(), brain=brain)+ wf = WorkflowDef(+ name="Morning Briefing",+ trigger=ManualTrigger(),+ steps=(+ BrainPromptStep(+ prompt="brief me",+ tools=("search_web", "gmail"),+ model_tier="deep",+ ),+ ),+ )++ run = await _run(store, runner, wf)++ assert run["state"] == "completed"+ assert run["steps"][0]["output"] == "isolated reply"+ assert brain.chat_calls == [], "never the live conversation path"+ assert brain.task_calls == [{+ "prompt": "brief me",+ "allowed_tools": ("search_web", "gmail"),+ "model_tier": "deep",+ }]+++async def test_a_step_without_tools_still_runs_isolated(store: WorkflowStore) -> None:+ brain = _ManagerLikeBrain()+ runner = WorkflowRunner(store=store, bus=EventBus(), brain=brain)+ wf = WorkflowDef(+ name="URL Summary",+ trigger=ManualTrigger(),+ steps=(BrainPromptStep(prompt="summarise"),),+ )++ run = await _run(store, runner, wf)++ assert run["state"] == "completed"+ assert brain.task_calls[0]["allowed_tools"] == ()+ assert brain.task_calls[0]["model_tier"] == "auto"+ assert brain.chat_calls == []+++async def test_a_brain_without_run_task_keeps_the_callable_path(+ store: WorkflowStore,+) -> None:+ brain = _CallableOnlyBrain()+ runner = WorkflowRunner(store=store, bus=EventBus(), brain=brain)+ wf = WorkflowDef(+ name="Plain",+ trigger=ManualTrigger(),+ steps=(BrainPromptStep(prompt="hello"),),+ )++ run = await _run(store, runner, wf)++ assert run["state"] == "completed"+ assert run["steps"][0]["output"] == "plain reply"+ assert brain.calls == ["hello"]+++def test_old_step_json_without_the_new_fields_still_loads() -> None:+ """Rows written before the fields existed carry neither ``tools`` nor+ ``model_tier``; ``extra="forbid"`` must not reject them."""+ step = BrainPromptStep.model_validate(+ {"kind": "brain_prompt", "prompt": "x", "max_output_chars": 500}+ )+ assert step.tools == ()+ assert step.model_tier == "auto"diff --git a/tests/unit/workflows/test_seed_scheduled.py b/tests/unit/workflows/test_seed_scheduled.pyindex e3bcccdc1c..53bc5a3864 100644--- a/tests/unit/workflows/test_seed_scheduled.py+++ b/tests/unit/workflows/test_seed_scheduled.py@@ -11,13 +11,23 @@ would just manufacture failing runs on somebody else's machine."""from __future__ import annotations+from pathlib import Path++import pytest+from jarvis.workflows.schema import (BrainPromptStep,CronTrigger,ManualTrigger,SpeakStep,+ WorkflowDef,+)+from jarvis.workflows.seed import (+ MORNING_BRIEFING_TOOLS,+ SEED_WORKFLOWS,+ ensure_seed_workflows,)-from jarvis.workflows.seed import SEED_WORKFLOWS+from jarvis.workflows.store import WorkflowStore_CREDENTIAL_FREE_STEPS = (BrainPromptStep, SpeakStep)@@ -82,3 +92,95 @@ def test_the_manual_seeds_are_untouched() -> None:wf = _seed(name)assert isinstance(wf.trigger, ManualTrigger)assert wf.enabled+++# ----------------------------------------------------------------------+# BUG-212 — version 2: a briefing, not a greeting+# ----------------------------------------------------------------------++#: Every grant is a read-side tool: nothing here can send, write or delete,+#: so an unattended run never waits on an approval nobody is there to give.+_READ_ONLY_GRANTS = frozenset({"google_calendar", "gmail", "wiki-recall", "search_web"})+++def test_the_briefing_step_is_an_isolated_turn_with_read_only_tools() -> None:+ briefing = _seed("Morning Briefing")+ brain = next(s for s in briefing.steps if isinstance(s, BrainPromptStep))+ assert brain.tools == MORNING_BRIEFING_TOOLS+ assert set(brain.tools) <= _READ_ONLY_GRANTS+ assert brain.model_tier in ("auto", "fast", "deep")+++def test_the_briefing_prompt_grounds_itself_and_greets_by_time_of_day() -> None:+ briefing = _seed("Morning Briefing")+ prompt = next(s.prompt for s in briefing.steps if isinstance(s, BrainPromptStep))+ assert "tool output" in prompt+ assert "Never invent" in prompt+ assert "time of day" in prompt+ assert "not connected" in prompt, "a disconnected area is skipped, not faked"+ assert "Compose a short, friendly morning announcement" not in prompt+++async def store(tmp_path: Path) -> WorkflowStore:+ s = WorkflowStore(tmp_path / "wf.sqlite")+ await s.init()+ yield s+ await s.close()+++def _v1_morning_briefing(*, enabled: bool) -> WorkflowDef:+ """The shipped v1 row, the shape an installed box carries in its DB."""+ v2 = _seed("Morning Briefing")+ return v2.model_copy(update={+ "enabled": enabled,+ "steps": (+ BrainPromptStep(+ label="Generate daily summary",+ prompt=(+ "You are Jarvis. It's currently morning. Compose a short, "+ "friendly morning announcement (max 3 sentences) in the "+ "configured output language."+ ),+ max_output_chars=500,+ ),+ SpeakStep(label="Play announcement", text="{{prev.output}}", language="auto"),+ ),+ })+++async def test_the_shipped_v1_row_is_migrated_and_keeps_its_switch(+ store: WorkflowStore,+) -> None:+ """An installed box has the greeting seed in its DB; it must become the+ briefing without flipping the user's on/off choice."""+ await store.upsert_workflow(_v1_morning_briefing(enabled=False))++ added = await ensure_seed_workflows(store)++ assert added == len(SEED_WORKFLOWS) - 1+ row = await store.get_workflow(str(_seed("Morning Briefing").id))+ assert row is not None+ assert row["enabled"] == 0, "the user had it off — still off"+ definition = WorkflowDef.model_validate_json(row["def_json"])+ brain = next(s for s in definition.steps if isinstance(s, BrainPromptStep))+ assert brain.tools == MORNING_BRIEFING_TOOLS+++async def test_a_users_own_edit_of_the_briefing_is_left_alone(+ store: WorkflowStore,+) -> None:+ edited = _seed("Morning Briefing").model_copy(update={+ "steps": (+ BrainPromptStep(prompt="Read me my own notes file and nothing else."),+ SpeakStep(text="{{prev.output}}", language="auto"),+ ),+ })+ await store.upsert_workflow(edited)++ await ensure_seed_workflows(store)++ row = await store.get_workflow(str(edited.id))+ assert row is not None+ definition = WorkflowDef.model_validate_json(row["def_json"])+ assert definition.steps[0].prompt == "Read me my own notes file and nothing else."