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(artifacts): a page about the user's own mail or calendar is built from facts Jarvis reads, never from what the worker imagines
rubenluetke10-beep10dfe0225e06
diff --git a/jarvis/artifacts/brief.py b/jarvis/artifacts/brief.pyindex e126d0a500..8bf682f506 100644--- a/jarvis/artifacts/brief.py+++ b/jarvis/artifacts/brief.py@@ -62,10 +62,38 @@ _NON_SLUG_RE: Final = re.compile(r"[^a-z0-9]+")_QUALITY_LEAD: Final = ("Deliver a complete, polished, production-quality artifact that fully ""satisfies the request below. A skeleton, stub, placeholder or "- '"content follows" shell is a FAILURE — never ship one. If a detail is '- "unspecified, pick a rich, sensible default and build the finished page."+ '"content follows" shell is a FAILURE — never ship one. If a detail of the '+ "DESIGN is unspecified — layout, order, colour, the wording of a label — "+ "pick a rich, sensible default and build the finished page. A FACT is "+ "never defaulted: see 'Facts, never inventions' below.")+# The rule the forensic of 2026-08-27 was missing (mission 01a0426e-8d79: a+# "morning briefing from my calendar and mail" built by a worker with no+# data access came back full of invented senders, subjects and meetings —+# the old quality lead's "pick a rich default" read as permission). A+# worker sees no account of the user's; what it may state about that user+# is exactly what the brief carries, and an honest empty section beats a+# plausible fiction every time.+FACTS_RULE: Final = """\+## Facts, never inventions+The page is a factual document about THIS user. Every name, sender, subject, \+appointment, contact, amount, date, quote and number on it comes from the request \+or from the "Source data" section — nothing else.+- Never invent personal data: no made-up emails, senders, meetings, colleagues, \+companies, deadlines, balances or figures — not as an "example", not to fill a \+column, not to make the page look complete.+- Where the request asks for the user's own data (inbox, calendar, contacts, \+files, spending, messages …) and the Source data section carries nothing for it \+— missing, "nothing there", or "UNAVAILABLE" — the page says exactly that in \+that section, in one plain sentence (e.g. "Gmail is not connected — no inbox \+data was available to this build"), and leaves the section otherwise empty. A \+page that is honest and half-empty is CORRECT; a page full of plausible fiction \+is a FAILURE.+- Sample data is allowed only when the request itself asks for a sample, demo, \+mock-up or template — and then every sample element is visibly labelled as \+sample data on the page itself."""+_LANGUAGE_NAMES: Final[dict[str, str]] = {"de": "German","en": "English",@@ -120,6 +148,7 @@ def build_artifact_brief(previous_html: str | None = None,previous_filename: str | None = None,brand_marks: Sequence[BrandMark] = (),+ source_data: str | None = None,) -> ArtifactBrief:"""Compose the worker instruction for one artifact.@@ -127,6 +156,12 @@ def build_artifact_brief(request: what the user wants on the page — the content, the data,the style wishes — in the user's own words or the brain's faithfulsummary of them. Never empty; the caller validates.+ source_data: the rendered ``## Source data`` section+ (:func:`jarvis.artifacts.source_data.render_source_data`) — the+ facts Jarvis read from the user's accounts for a page about their+ own mail or calendar, or the honest "unavailable" notes when it+ could not. Empty/None when the request names no such data. The+ caller fetches; this function stays free of I/O.title: the artifact's title; names the file and the ``<title>``.language: the turn's output language code (de / en / es). The page'svisible text is written in it.@@ -176,10 +211,14 @@ def build_artifact_brief("label, caption and note. Code identifiers and comments stay English.","- Responsive from 360 px to 1600 px; the page never scrolls sideways.","- Real content, never filler: the numbers, facts and data the request "- "names go into the page; a missing fact becomes a clearly labelled "- "assumption — never lorem ipsum, never 'TODO'.",+ "names go into the page; a missing GENERAL fact (a rate, a definition) "+ "becomes a clearly labelled assumption — never lorem ipsum, never "+ "'TODO'. A missing fact about the USER is never assumed: see "+ "'Facts, never inventions'.",]),+ FACTS_RULE,+ *([source_data.strip()] if source_data and source_data.strip() else []),READ_THE_REQUEST,DESIGN_SYSTEM,"\n".join(@@ -227,6 +266,7 @@ def build_artifact_brief(__all__ = [+ "FACTS_RULE","MAX_PREVIOUS_HTML_CHARS","ArtifactBrief","artifact_filename",diff --git a/jarvis/artifacts/source_data.py b/jarvis/artifacts/source_data.pynew file mode 100644index 0000000000..7554bded6d--- /dev/null+++ b/jarvis/artifacts/source_data.py@@ -0,0 +1,400 @@+"""The facts an artifact about the user's OWN data is built from — fetched by+the harness, never left to the worker to imagine.++The worker that writes an artifact runs in an empty worktree on an external+CLI. It has no Gmail, no calendar, no contacts: when the brief asks for "a+morning briefing from my calendar and my important mail" and carries no+data, the strongest model on the box does what every model does with a+confident brief and no facts — it writes a page full of plausible people,+subjects and appointments (forensic 2026-08-27, mission 01a0426e-8d79: a+"Dr. Markus Weber", a "NovaTech SLA", a "Sarah Keller" — none of them real).++So the facts are gathered HERE, on the app side, before the brief is+composed, the way the brain manager pre-fetches the activity timeline rather+than trusting a fast model to call the tool: deterministic, harness-side, and+through the ``ToolExecutor`` (never a direct ``Tool.execute`` — AP-3), so the+risk-tier and audit path are honoured. A read that the plugin cannot serve —+not connected, expired token, timeout — becomes an *unavailable* section the+brief carries verbatim, so the page says "Gmail is not connected" instead of+inventing an inbox.++Two halves:++* :func:`plan_source_data` — pure, regex-only (AP-11): which sources the+ request names. The vocabulary is input-matching (DE/EN/ES), which the+ language policy allows on the input surface.+* :func:`fetch_source_data` — the reads, bounded in count, time and size, and+ :func:`render_source_data`, the brief section the worker reads.+"""++from __future__ import annotations++import asyncio+import json+import logging+import re+from collections.abc import Mapping, Sequence+from dataclasses import dataclass, field+from datetime import datetime, timedelta+from typing import Any, Final+from uuid import UUID++log = logging.getLogger(__name__)+++@dataclass(frozen=True)+class SourceNeed:+ """One kind of the user's own data an artifact request names."""++ key: str+ """Stable id: ``inbox`` / ``calendar``."""+ tool: str+ """The router tool that serves it (``gmail`` / ``google_calendar``)."""+ label: str+ """How the brief names it."""+++INBOX: Final = SourceNeed("inbox", "gmail", "Gmail inbox")+CALENDAR: Final = SourceNeed("calendar", "google_calendar", "Google Calendar")++#: Every source the planner knows, in the order the brief lists them.+SOURCES: Final[tuple[SourceNeed, ...]] = (CALENDAR, INBOX)++# Input-matching vocabulary (DE/EN/ES) — nouns for the user's mail and+# calendar. Deliberately nouns only: "mail me the page" is not a request for+# inbox data, and an over-trigger would hand the user's mail to a build about+# something else.+_INBOX_RE: Final = re.compile(+ r"\b(?:gmail|e-?mails?|mails?|inbox|posteingang|postfach|" # i18n-allow: input vocab+ r"correos?(?:\s+electr[oó]nicos?)?|bandeja\s+de\s+entrada)\b", # i18n-allow: input vocab+ re.IGNORECASE,+)+_CALENDAR_RE: Final = re.compile(+ r"\b(?:kalender|calendar|calendario|termine?n?|meetings?|agenda|" # i18n-allow: input vocab+ r"citas?|reuni[oó]n(?:es)?|besprechung(?:en)?)\b", # i18n-allow: input vocab+ re.IGNORECASE,+)+# A request that asks for a SAMPLE is the one case where made-up items are+# wanted — and then the brief tells the worker to label them as such.+_SAMPLE_RE: Final = re.compile(+ r"\b(?:sample|demo|mock-?ups?|dummy|fake|fictional|placeholders?|templates?|"+ r"beispiel\w*|platzhalter|vorlage|" # i18n-allow: input vocab+ r"ejemplos?|ficticio\w*|plantilla)\b", # i18n-allow: input vocab+ re.IGNORECASE,+)++_NEED_PATTERNS: Final[tuple[tuple[SourceNeed, re.Pattern[str]], ...]] = (+ (CALENDAR, _CALENDAR_RE),+ (INBOX, _INBOX_RE),+)+++def plan_source_data(text: str) -> tuple[SourceNeed, ...]:+ """The sources a request names, in :data:`SOURCES` order; empty when none."""+ haystack = text or ""+ return tuple(need for need, pattern in _NEED_PATTERNS if pattern.search(haystack))+++def wants_sample_data(text: str) -> bool:+ """True when the request explicitly asks for sample / demo / template content."""+ return bool(_SAMPLE_RE.search(text or ""))+++# --- Fetching --------------------------------------------------------------------++#: Mail newer than this many days is what a briefing is about.+INBOX_WINDOW_DAYS: Final = 2+#: Messages read in full (list → get per id); the brief stays a brief.+INBOX_MAX_MESSAGES: Final = 12+#: Body text kept per message, after the plugin's own cap.+INBOX_BODY_CHARS: Final = 400+#: Calendar window: today and tomorrow, from local midnight.+CALENDAR_WINDOW_DAYS: Final = 2+CALENDAR_MAX_EVENTS: Final = 30+#: A plugin that does not answer within this stays "unavailable" — the build+#: must not hang on a dead token refresh.+PER_SOURCE_TIMEOUT_S: Final = 45.0+++@dataclass(frozen=True)+class SourceSection:+ """What one source yielded — or why it yielded nothing."""++ need: SourceNeed+ status: str+ """``ok`` (items follow), ``empty`` (read fine, nothing there), ``unavailable``."""+ items: tuple[dict[str, Any], ...] = ()+ note: str = ""+ """The window that was read, or why the read failed — shown on the page."""+++@dataclass(frozen=True)+class SourceData:+ sections: tuple[SourceSection, ...] = field(default_factory=tuple)+ fetched_at: datetime | None = None++ @property+ def needs(self) -> tuple[SourceNeed, ...]:+ return tuple(s.need for s in self.sections)+++def unavailable_source_data(+ needs: Sequence[SourceNeed], *, reason: str = "this build had no access to the user's accounts"+) -> SourceData:+ """Every named source marked unavailable — the honest brief when nothing+ could be fetched (no executor wired, no tools built)."""+ return SourceData(+ sections=tuple(SourceSection(need, "unavailable", note=reason) for need in needs),+ )+++async def fetch_source_data(+ needs: Sequence[SourceNeed],+ *,+ tools: Mapping[str, Any],+ executor: Any,+ trace_id: UUID,+ utterance: str,+ now: datetime,+) -> SourceData:+ """Read every named source through *executor* (a ``ToolExecutor``).++ Never raises: a missing tool, a failed read, a timeout or a crash becomes+ an ``unavailable`` section with the reason. Sources are read one after the+ other — two OAuth-backed plugins refreshing tokens at once is how a token+ store gets clobbered.+ """+ sections: list[SourceSection] = []+ for need in needs:+ tool = tools.get(need.tool)+ if tool is None:+ sections.append(+ SourceSection(+ need, "unavailable", note=f"the {need.label} plugin is not connected"+ )+ )+ continue+ try:+ section = await asyncio.wait_for(+ _fetch_one(need, tool, executor, trace_id=trace_id, utterance=utterance, now=now),+ timeout=PER_SOURCE_TIMEOUT_S,+ )+ except TimeoutError:+ log.warning(+ "artifact source data: %s did not answer in %.0fs",+ need.tool,+ PER_SOURCE_TIMEOUT_S,+ )+ section = SourceSection(+ need,+ "unavailable",+ note=f"the {need.label} plugin did not answer within {PER_SOURCE_TIMEOUT_S:.0f} s",+ )+ except asyncio.CancelledError:+ raise+ except Exception as exc: # noqa: BLE001 — one dead source must not sink the build+ log.warning(+ "artifact source data: %s read crashed: %s", need.tool, exc, exc_info=True+ )+ section = SourceSection(+ need,+ "unavailable",+ note=f"reading {need.label} failed: {type(exc).__name__}: {exc}",+ )+ sections.append(section)+ return SourceData(sections=tuple(sections), fetched_at=now)+++async def _run(+ executor: Any, tool: Any, args: dict[str, Any], *, trace_id: UUID, utterance: str+) -> Any:+ return await executor.execute(+ tool,+ args,+ user_utterance=utterance,+ trace_id=trace_id,+ rationale="facts for an artifact about the user's own data",+ )+++def _failed(result: Any) -> str | None:+ """The error text of a failed ToolResult, or None when it succeeded."""+ if result is None:+ return "no result"+ if bool(getattr(result, "success", False)):+ return None+ return str(getattr(result, "error", "") or "the read failed")+++async def _fetch_one(+ need: SourceNeed,+ tool: Any,+ executor: Any,+ *,+ trace_id: UUID,+ utterance: str,+ now: datetime,+) -> SourceSection:+ if need.key == "inbox":+ return await _fetch_inbox(need, tool, executor, trace_id=trace_id, utterance=utterance)+ if need.key == "calendar":+ return await _fetch_calendar(+ need, tool, executor, trace_id=trace_id, utterance=utterance, now=now+ )+ return SourceSection(need, "unavailable", note=f"no reader for {need.key}")+++async def _fetch_inbox(+ need: SourceNeed, tool: Any, executor: Any, *, trace_id: UUID, utterance: str+) -> SourceSection:+ window = f"the last {INBOX_WINDOW_DAYS} days"+ listing = await _run(+ executor,+ tool,+ {+ "action": "list_messages",+ "query": f"newer_than:{INBOX_WINDOW_DAYS}d",+ "max_results": INBOX_MAX_MESSAGES,+ },+ trace_id=trace_id,+ utterance=utterance,+ )+ error = _failed(listing)+ if error is not None:+ return SourceSection(need, "unavailable", note=f"reading {need.label} failed: {error}")+ out = getattr(listing, "output", None)+ messages = out.get("messages") if isinstance(out, dict) else None+ ids = [+ str(m["id"])+ for m in (messages or [])+ if isinstance(m, dict) and m.get("id")+ ][:INBOX_MAX_MESSAGES]+ if not ids:+ return SourceSection(need, "empty", note=f"no mail arrived in {window}")+ items: list[dict[str, Any]] = []+ failures = 0+ for message_id in ids:+ got = await _run(+ executor,+ tool,+ {"action": "get_message", "message_id": message_id},+ trace_id=trace_id,+ utterance=utterance,+ )+ if _failed(got) is not None or not isinstance(getattr(got, "output", None), dict):+ failures += 1+ continue+ items.append(_slim_message(got.output))+ if not items:+ return SourceSection(+ need, "unavailable", note=f"{failures} of {len(ids)} messages could not be read"+ )+ note = f"{len(items)} messages from {window}"+ if failures:+ note += f" ({failures} more could not be read)"+ return SourceSection(need, "ok", items=tuple(items), note=note)+++def _slim_message(raw: Mapping[str, Any]) -> dict[str, Any]:+ body = str(raw.get("body") or "")+ if len(body) > INBOX_BODY_CHARS:+ body = body[:INBOX_BODY_CHARS].rstrip() + "…"+ labels = raw.get("labelIds") or []+ return {+ "from": str(raw.get("from") or ""),+ "to": str(raw.get("to") or ""),+ "subject": str(raw.get("subject") or ""),+ "date": str(raw.get("date") or ""),+ "unread": "UNREAD" in labels if isinstance(labels, (list, tuple)) else False,+ "snippet": str(raw.get("snippet") or ""),+ "body": body,+ }+++async def _fetch_calendar(+ need: SourceNeed,+ tool: Any,+ executor: Any,+ *,+ trace_id: UUID,+ utterance: str,+ now: datetime,+) -> SourceSection:+ start = now.replace(hour=0, minute=0, second=0, microsecond=0)+ end = start + timedelta(days=CALENDAR_WINDOW_DAYS)+ window = f"{start.date().isoformat()} to {(end - timedelta(days=1)).date().isoformat()}"+ result = await _run(+ executor,+ tool,+ {+ "action": "list_events",+ "time_min": start.isoformat(),+ "time_max": end.isoformat(),+ "max_results": CALENDAR_MAX_EVENTS,+ },+ trace_id=trace_id,+ utterance=utterance,+ )+ error = _failed(result)+ if error is not None:+ return SourceSection(need, "unavailable", note=f"reading {need.label} failed: {error}")+ out = getattr(result, "output", None)+ events = out.get("events") if isinstance(out, dict) else None+ items = tuple(e for e in (events or []) if isinstance(e, dict))[:CALENDAR_MAX_EVENTS]+ if not items:+ return SourceSection(need, "empty", note=f"no events between {window}")+ return SourceSection(need, "ok", items=items, note=f"{len(items)} events between {window}")+++# --- The brief section ------------------------------------------------------------++_STATUS_WORD: Final[dict[str, str]] = {+ "ok": "available",+ "empty": "nothing there",+ "unavailable": "UNAVAILABLE",+}+++def render_source_data(data: SourceData) -> str:+ """The ``## Source data`` section of the brief — the only facts the page+ may show about the user's own data. Empty string when nothing was named."""+ if not data.sections:+ return ""+ when = (+ f"at {data.fetched_at.isoformat(timespec='minutes')}"+ if data.fetched_at is not None+ else "for this build"+ )+ lines: list[str] = [+ "## Source data — the only facts about the user's own data",+ f"Jarvis read the user's connected accounts {when}. The page shows THESE "+ "items and nothing else for the sections they cover. A section marked "+ "'nothing there' or 'UNAVAILABLE' stays empty on the page and shows its "+ "note in one plain sentence — never a made-up item in its place.",+ ]+ for section in data.sections:+ lines.append("")+ status = _STATUS_WORD.get(section.status, section.status)+ lines.append(f"### {section.need.label} — {status}")+ if section.note:+ lines.append(section.note)+ if section.status == "ok" and section.items:+ lines.append("```json")+ lines.append(json.dumps(list(section.items), ensure_ascii=False, indent=1))+ lines.append("```")+ return "\n".join(lines)+++__all__ = [+ "CALENDAR",+ "INBOX",+ "SOURCES",+ "SourceData",+ "SourceNeed",+ "SourceSection",+ "fetch_source_data",+ "plan_source_data",+ "render_source_data",+ "unavailable_source_data",+ "wants_sample_data",+]diff --git a/jarvis/brain/factory.py b/jarvis/brain/factory.pyindex a6a7906e1e..95ea39bd68 100644--- a/jarvis/brain/factory.py+++ b/jarvis/brain/factory.py@@ -515,11 +515,20 @@ def _load_tools_for_tier(# spawn-worker (AD-OC1: the stack bootstraps after the brain).# Publishes NavigateSidebar("visualization") on dispatch so the# Artifacts section shows the build as it happens.+ #+ # The executor and the router's tool set (read lazily — the+ # dict is still being filled here) let the tool read the user's+ # mail / calendar plugins itself before it composes the brief,+ # so a page about the user's own data is built from facts the+ # harness fetched, not from what a worker with no account+ # access imagines (forensic 2026-08-27, mission 01a0426e-8d79).inst = cls(bus=bus,manager=mission_manager,manager_resolver=_resolve_mission_manager,kontrollierer_resolver=_resolve_kontrollierer,+ executor=executor,+ tools_resolver=lambda: tools,)elif ep.name == "whoami":inst = cls(profile=user_profile, people=people)diff --git a/jarvis/plugins/tool/create_artifact.py b/jarvis/plugins/tool/create_artifact.pyindex a94daf517f..52102e0ef0 100644--- a/jarvis/plugins/tool/create_artifact.py+++ b/jarvis/plugins/tool/create_artifact.py@@ -27,12 +27,22 @@ from __future__ import annotationsimport asyncioimport logging-from collections.abc import Callable+from collections.abc import Callable, Mapping+from datetime import datetimefrom typing import Any, Final+from uuid import UUIDfrom jarvis.artifacts.brand_marks import find_brand_marks-from jarvis.artifacts.brief import build_artifact_brief+from jarvis.artifacts.brief import ArtifactBrief, build_artifact_brieffrom jarvis.artifacts.locate import locate_artifact+from jarvis.artifacts.source_data import (+ SourceNeed,+ fetch_source_data,+ plan_source_data,+ render_source_data,+ unavailable_source_data,+ wants_sample_data,+)from jarvis.core.bus import EventBusfrom jarvis.core.events import (JarvisAgentAnnouncement,@@ -53,6 +63,9 @@ ARTIFACTS_SECTION: Final = "visualization"#: pattern ``spawn_worker`` uses).ManagerResolver = Callable[[], Any | None]KontrolliererResolver = Callable[[], Any | None]+#: The router's built tool set by name — read at fetch time, so the dict the+#: factory is still filling when this tool is constructed is seen complete.+ToolsResolver = Callable[[], Mapping[str, Any]]#: The brief carries the user's request verbatim; this caps a runaway model#: summary, not a real request. Anything longer is still a request — clipped.@@ -156,7 +169,18 @@ class CreateArtifactTool:manager_resolver: ManagerResolver | None = None,kontrollierer: Any | None = None,kontrollierer_resolver: KontrolliererResolver | None = None,+ executor: Any | None = None,+ tools_resolver: ToolsResolver | None = None,) -> None:+ """+ ``executor`` (the ``ToolExecutor``) and ``tools_resolver`` (the router's+ built tool set, read lazily because the set is still being filled when+ this tool is constructed) are what lets a page about the user's own+ mail or calendar be built from FACTS: the tool reads those plugins+ itself before the brief is composed (:mod:`jarvis.artifacts.source_data`).+ Without them the brief still names every such source as unavailable,+ so the worker says so on the page instead of inventing an inbox.+ """if manager is None and manager_resolver is None:raise ValueError("CreateArtifactTool requires 'manager' or 'manager_resolver'")self._bus = bus@@ -164,6 +188,8 @@ class CreateArtifactTool:self._manager_resolver = manager_resolverself._kontrollierer = kontrolliererself._kontrollierer_resolver = kontrollierer_resolver+ self._executor = executor+ self._tools_resolver = tools_resolver# -- resolvers ----------------------------------------------------------@@ -227,16 +253,34 @@ class CreateArtifactTool:# The original marks for the brands the request names ride along in the# brief (the worker's workspace holds no repo); a request that names# none adds one rule: text, never a lettered tile in a logo's place.- brief = build_artifact_brief(- request,- title=previous.title if previous else title,- language=language,- previous_html=previous.html if previous else None,- previous_filename=previous.file.name if previous else None,- brand_marks=find_brand_marks(f"{title} {request}"),- )+ brand_marks = find_brand_marks(f"{title} {request}")++ def build(source_data: str | None) -> ArtifactBrief:+ return build_artifact_brief(+ request,+ title=previous.title if previous else title,+ language=language,+ previous_html=previous.html if previous else None,+ previous_filename=previous.file.name if previous else None,+ brand_marks=brand_marks,+ source_data=source_data,+ )++ # The brief without facts names the file and the title now; the one+ # the worker reads is composed in the background, after the facts.+ brief = build(None)kontrollierer = self._resolve_kontrollierer()utterance = _utterance(ctx) or request+ # A page about the user's own mail or calendar is built from what+ # Jarvis reads there — fetched in the background, past the voice+ # budget, before the mission is composed. A request for a sample /+ # mock-up wants made-up items and gets none fetched (the brief tells+ # the worker to label them).+ needs = (+ ()+ if wants_sample_data(f"{utterance}\n{request}")+ else plan_source_data(f"{utterance}\n{request}")+ )# The mission dispatch contract is de/en; an "es" turn keeps the German# mission readback (the same cap spawn_worker applies).mission_language = language if language in ("de", "en") else "de"@@ -260,10 +304,12 @@ class CreateArtifactTool:# ``_cancel_all_background_tasks`` cancels by it.asyncio.create_task(self._background_dispatch(- brief.prompt,+ build,+ needs,utterance,manager,kontrollierer,+ trace_id=ctx.trace_id,mission_language=mission_language,readback_language=language,),@@ -303,24 +349,65 @@ class CreateArtifactTool:),)+ async def _source_data(+ self, needs: tuple[SourceNeed, ...], *, trace_id: UUID, utterance: str+ ) -> str | None:+ """The brief's ``## Source data`` section for *needs* — the facts read+ through the executor, or every source marked unavailable when the tool+ was built without one. None when the request names no such data."""+ if not needs:+ return None+ tools: Mapping[str, Any] = {}+ if self._tools_resolver is not None:+ try:+ tools = self._tools_resolver() or {}+ except Exception as exc: # noqa: BLE001 — a broken resolver reads as "no tools"+ log.warning("create_artifact: tools resolver failed: %s", exc)+ tools = {}+ if self._executor is None or not tools:+ log.warning(+ "create_artifact: no executor/tools wired — %s stay unavailable in the brief",+ ", ".join(n.key for n in needs),+ )+ data = unavailable_source_data(needs)+ else:+ data = await fetch_source_data(+ needs,+ tools=tools,+ executor=self._executor,+ trace_id=trace_id,+ utterance=utterance,+ now=datetime.now().astimezone(),+ )+ log.info(+ "create_artifact: source data %s",+ ", ".join(f"{s.need.key}={s.status}({len(s.items)})" for s in data.sections),+ )+ return render_source_data(data)+async def _background_dispatch(self,- prompt: str,+ build: Callable[[str | None], ArtifactBrief],+ needs: tuple[SourceNeed, ...],utterance: str,manager: Any,kontrollierer: Any | None,*,+ trace_id: UUID,mission_language: str,readback_language: str,) -> None:- """Persist the mission and run it — the two-step contract spawn_worker- documents (dispatch → PENDING, run_mission → APPROVED/FAILED).+ """Read the facts, compose the brief, persist the mission and run it —+ the two-step contract spawn_worker documents (dispatch → PENDING,+ run_mission → APPROVED/FAILED).Every dead end becomes a spoken failure through the same completionevent a finished mission uses, never a log line alone (AU-11): theuser already heard a promise."""try:+ source_data = await self._source_data(needs, trace_id=trace_id, utterance=utterance)+ prompt = build(source_data).promptmission_id = await manager.dispatch(prompt=prompt,language=mission_language,diff --git a/tests/unit/artifacts/test_brief.py b/tests/unit/artifacts/test_brief.pyindex 43ea992fcb..16202d0abe 100644--- a/tests/unit/artifacts/test_brief.py+++ b/tests/unit/artifacts/test_brief.py@@ -118,3 +118,43 @@ def test_brief_is_deterministic() -> None:a = build_artifact_brief("Same.", title="Same", language="es")b = build_artifact_brief("Same.", title="Same", language="es")assert a == b+++def test_facts_rule_forbids_invented_personal_data_and_defaults_only_design() -> None:+ """The forensic of 2026-08-27: a briefing built with no data came back+ full of invented senders and meetings. The lead now defaults DESIGN only,+ and the facts rule names the honest empty section as the correct page."""+ prompt = build_artifact_brief("A morning briefing.", title="Briefing", language="en").prompt+ lead = prompt.split("\n\n", 1)[0]+ assert "production-quality" in lead # the rail still strips it by this phrase+ assert "detail of the DESIGN is unspecified" in lead+ assert "A FACT is never defaulted" in lead+ assert "## Facts, never inventions" in prompt+ assert "Never invent personal data" in prompt+ assert "no inbox data was available to this build" in prompt+ assert "honest and half-empty is CORRECT" in prompt+ assert "labelled as sample data" in prompt+ # The rule sits with the build rules, before the design guide.+ assert prompt.index("## Facts, never inventions") < prompt.index("## Read the request first")+++def test_source_data_rides_between_the_facts_rule_and_the_design_guide() -> None:+ section = (+ "## Source data — the only facts about the user's own data\n"+ "### Gmail inbox — available"+ )+ with_data = build_artifact_brief(+ "My mail as a page.", title="Mail", language="en", source_data=section+ ).prompt+ assert section in with_data+ assert (+ with_data.index("## Facts, never inventions")+ < with_data.index(section)+ < with_data.index("## Read the request first")+ )+ # Empty / whitespace source data adds nothing — the brief stays byte-identical.+ plain = build_artifact_brief("My mail as a page.", title="Mail", language="en").prompt+ assert build_artifact_brief(+ "My mail as a page.", title="Mail", language="en", source_data=" \n"+ ).prompt == plain+ assert "## Source data" not in plaindiff --git a/tests/unit/artifacts/test_source_data.py b/tests/unit/artifacts/test_source_data.pynew file mode 100644index 0000000000..059efce017--- /dev/null+++ b/tests/unit/artifacts/test_source_data.py@@ -0,0 +1,248 @@+"""The facts an artifact about the user's own data is built from.++Pinned: which requests name the inbox / the calendar (and which do not), that+the reads go through the executor with bounded arguments, that every failure+mode — plugin missing, read failed, nothing there, timeout — becomes an+honest section rather than an exception, and that the rendered brief section+tells the worker what it may and may not show. Fakes, not mocks.+"""++from __future__ import annotations++import asyncio+from datetime import datetime, timedelta, timezone+from typing import Any+from uuid import uuid4++import pytest++from jarvis.artifacts import source_data as sd+from jarvis.core.protocols import ToolResult++# -- planning -------------------------------------------------------------------+++ ("text", "keys"),+ [+ (+ "Ein Morning Briefing aus dem Google Kalender " # i18n-allow+ "und wichtigen E-Mails aus Gmail", # i18n-allow+ ("calendar", "inbox"),+ ),+ ("what's in my inbox today, as a page", ("inbox",)),+ ("meine Termine der Woche als Timeline", ("calendar",)), # i18n-allow+ ("un resumen de mis correos y reuniones", ("calendar", "inbox")), # i18n-allow+ ("Umsatz pro Monat 2026 als Balken", ()), # i18n-allow+ ("a landing page for my SaaS", ()),+ ],+)+def test_plan_names_the_sources_the_request_names(text: str, keys: tuple[str, ...]) -> None:+ assert tuple(n.key for n in sd.plan_source_data(text)) == keys+++def test_a_sample_request_is_recognised() -> None:+ assert sd.wants_sample_data("build a demo dashboard with sample data") is True+ assert sd.wants_sample_data("eine Vorlage für ein Briefing") # i18n-allow+ assert sd.wants_sample_data("my real inbox, please") is False+++# -- fetching -------------------------------------------------------------------+++class _FakeExecutor:+ """Records every call and answers from a per-tool script."""++ def __init__(self, script: dict[str, Any]) -> None:+ self.script = script+ self.calls: list[tuple[str, dict[str, Any]]] = []++ async def execute(self, tool: Any, args: dict[str, Any], **_: Any) -> ToolResult:+ self.calls.append((tool.name, dict(args)))+ answer = self.script.get(tool.name)+ if callable(answer):+ return await answer(args)+ return answer+++class _Tool:+ def __init__(self, name: str) -> None:+ self.name = name+++NOW = datetime(2026, 8, 27, 9, 30, tzinfo=timezone(timedelta(hours=2)))+++async def _gmail(args: dict[str, Any]) -> ToolResult:+ if args["action"] == "list_messages":+ return ToolResult(success=True, output={"messages": [{"id": "m1"}, {"id": "m2"}]})+ if args["message_id"] == "m2":+ return ToolResult(success=False, output=None, error="404")+ return ToolResult(+ success=True,+ output={+ "from": "Real Sender <[email protected]>",+ "subject": "Invoice 4711",+ "date": "Thu, 27 Aug 2026 08:42:00 +0200",+ "labelIds": ["INBOX", "UNREAD"],+ "snippet": "Please find attached",+ "body": "x" * 1000,+ },+ )+++def _run(coro: Any) -> Any:+ return asyncio.run(coro)+++def test_inbox_is_read_through_the_executor_and_slimmed() -> None:+ executor = _FakeExecutor({"gmail": _gmail})+ data = _run(+ sd.fetch_source_data(+ (sd.INBOX,),+ tools={"gmail": _Tool("gmail")},+ executor=executor,+ trace_id=uuid4(),+ utterance="my mail",+ now=NOW,+ )+ )+ (section,) = data.sections+ assert section.status == "ok"+ assert section.note == "1 messages from the last 2 days (1 more could not be read)"+ (item,) = section.items+ assert item["from"] == "Real Sender <[email protected]>"+ assert item["subject"] == "Invoice 4711"+ assert item["unread"] is True+ assert len(item["body"]) == sd.INBOX_BODY_CHARS + 1 and item["body"].endswith("…")+ # list, then one get per id — through the executor, never Tool.execute.+ assert [c[1]["action"] for c in executor.calls] == [+ "list_messages",+ "get_message",+ "get_message",+ ]+ assert executor.calls[0][1]["query"] == "newer_than:2d"+ assert executor.calls[0][1]["max_results"] == sd.INBOX_MAX_MESSAGES+++def test_calendar_window_is_today_and_tomorrow_from_local_midnight() -> None:+ events = [{"summary": "Standup", "start": "2026-08-27T09:00:00+02:00"}]+ executor = _FakeExecutor(+ {"google_calendar": ToolResult(success=True, output={"events": events})}+ )+ data = _run(+ sd.fetch_source_data(+ (sd.CALENDAR,),+ tools={"google_calendar": _Tool("google_calendar")},+ executor=executor,+ trace_id=uuid4(),+ utterance="my day",+ now=NOW,+ )+ )+ (section,) = data.sections+ assert section.status == "ok" and section.items == (events[0],)+ args = executor.calls[0][1]+ assert args["action"] == "list_events"+ assert args["time_min"] == "2026-08-27T00:00:00+02:00"+ assert args["time_max"] == "2026-08-29T00:00:00+02:00"+++def test_every_dead_end_is_an_honest_section_never_an_exception() -> None:+ async def boom(_: dict[str, Any]) -> ToolResult:+ raise RuntimeError("token store on fire")++ executor = _FakeExecutor(+ {+ "gmail": ToolResult(success=False, output=None, error="Gmail plugin not connected"),+ "google_calendar": boom,+ }+ )+ data = _run(+ sd.fetch_source_data(+ (sd.CALENDAR, sd.INBOX),+ tools={"gmail": _Tool("gmail"), "google_calendar": _Tool("google_calendar")},+ executor=executor,+ trace_id=uuid4(),+ utterance="briefing",+ now=NOW,+ )+ )+ calendar, inbox = data.sections+ assert calendar.status == "unavailable" and "RuntimeError" in calendar.note+ assert inbox.status == "unavailable" and "not connected" in inbox.note+++def test_a_missing_tool_and_an_empty_read_are_named_as_such() -> None:+ executor = _FakeExecutor(+ {"google_calendar": ToolResult(success=True, output={"events": []})}+ )+ data = _run(+ sd.fetch_source_data(+ (sd.CALENDAR, sd.INBOX),+ tools={"google_calendar": _Tool("google_calendar")},+ executor=executor,+ trace_id=uuid4(),+ utterance="briefing",+ now=NOW,+ )+ )+ calendar, inbox = data.sections+ assert calendar.status == "empty"+ assert "no events between 2026-08-27 to 2026-08-28" in calendar.note+ assert inbox.status == "unavailable" and "not connected" in inbox.note+ # Only the connected plugin was asked.+ assert [c[0] for c in executor.calls] == ["google_calendar"]+++def test_a_hanging_plugin_is_bounded(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(sd, "PER_SOURCE_TIMEOUT_S", 0.01)++ async def never(_: dict[str, Any]) -> ToolResult:+ await asyncio.sleep(5)+ return ToolResult(success=True, output={})++ data = _run(+ sd.fetch_source_data(+ (sd.INBOX,),+ tools={"gmail": _Tool("gmail")},+ executor=_FakeExecutor({"gmail": never}),+ trace_id=uuid4(),+ utterance="mail",+ now=NOW,+ )+ )+ (section,) = data.sections+ assert section.status == "unavailable" and "did not answer" in section.note+++# -- rendering ------------------------------------------------------------------+++def test_render_tells_the_worker_what_it_may_show() -> None:+ data = sd.SourceData(+ sections=(+ sd.SourceSection(+ sd.CALENDAR, "ok", items=({"summary": "Standup"},), note="1 events"+ ),+ sd.SourceSection(+ sd.INBOX, "unavailable", note="the Gmail inbox plugin is not connected"+ ),+ ),+ fetched_at=NOW,+ )+ text = sd.render_source_data(data)+ assert text.startswith("## Source data — the only facts about the user's own data")+ assert "2026-08-27T09:30+02:00" in text+ assert "### Google Calendar — available" in text+ assert '"summary": "Standup"' in text+ assert "### Gmail inbox — UNAVAILABLE" in text+ assert "the Gmail inbox plugin is not connected" in text+ assert "never a made-up item in its place" in text+ assert sd.render_source_data(sd.SourceData()) == ""+++def test_unavailable_source_data_marks_every_need() -> None:+ data = sd.unavailable_source_data((sd.CALENDAR, sd.INBOX))+ assert [s.status for s in data.sections] == ["unavailable", "unavailable"]+ assert "no access" in data.sections[0].notediff --git a/tests/unit/plugins/tool/test_create_artifact.py b/tests/unit/plugins/tool/test_create_artifact.pyindex 8e733fe5f1..5c7bf7a64d 100644--- a/tests/unit/plugins/tool/test_create_artifact.py+++ b/tests/unit/plugins/tool/test_create_artifact.py@@ -104,6 +104,145 @@ async def test_dispatches_the_brief_and_runs_the_mission() -> None:assert nav.section == "visualization"+class _Tool:+ def __init__(self, name: str) -> None:+ self.name = name+++class _FakeExecutor:+ """Answers reads from a script and records that every call came through+ it — the tool never touches ``Tool.execute`` itself (AP-3)."""++ def __init__(self) -> None:+ self.calls: list[tuple[str, dict[str, Any]]] = []++ async def execute(self, tool: Any, args: dict[str, Any], **_: Any) -> Any:+ from jarvis.core.protocols import ToolResult++ self.calls.append((tool.name, dict(args)))+ if tool.name == "google_calendar":+ event = {"summary": "Zahnarzt", "start": "2026-08-27T11:30:00+02:00"} # i18n-allow+ return ToolResult(success=True, output={"events": [event]})+ if args.get("action") == "list_messages":+ return ToolResult(success=True, output={"messages": [{"id": "m1"}]})+ return ToolResult(+ success=True,+ output={+ "from": "Real Person <[email protected]>",+ "subject": "Rechnung 4711", # i18n-allow+ "date": "Thu, 27 Aug 2026 08:42:00 +0200",+ "labelIds": ["INBOX"],+ "snippet": "Anbei", # i18n-allow+ "body": "Die Rechnung.", # i18n-allow+ },+ )+++async def _settle_fetch() -> None:+ """The background task now reads two plugins before it dispatches."""+ for _ in range(40):+ await asyncio.sleep(0)+++async def test_a_page_about_the_users_mail_and_calendar_is_built_from_fetched_facts() -> None:+ """Forensic 2026-08-27: the briefing was invented because the worker had+ no data. Now the tool reads the plugins through the executor first and+ the brief carries the items — and the rule that nothing else may appear."""+ bus, manager, kontrollierer = _FakeBus(), _FakeManager(), _FakeKontrollierer()+ executor = _FakeExecutor()+ tools = {"gmail": _Tool("gmail"), "google_calendar": _Tool("google_calendar")}+ tool = CreateArtifactTool(+ bus,+ manager=manager,+ kontrollierer=kontrollierer,+ executor=executor,+ tools_resolver=lambda: tools,+ )+ result = await tool.execute(+ {+ "title": "Morning Briefing",+ "request": (+ "Die heutigen Termine aus dem Kalender " # i18n-allow+ "und wichtige Mails aus Gmail." # i18n-allow+ ),+ },+ _ctx(utterance="mach mir ein morning briefing als artefakt"), # i18n-allow+ )+ await _settle_fetch()++ assert result.success is True+ # Nothing was read on the voice path: the ack returned before the fetch.+ assert len(manager.dispatched) == 1+ prompt = manager.dispatched[0]["prompt"]+ assert "## Facts, never inventions" in prompt+ assert "## Source data — the only facts about the user's own data" in prompt+ assert "### Google Calendar — available" in prompt+ assert '"summary": "Zahnarzt"' in prompt # i18n-allow+ assert "### Gmail inbox — available" in prompt+ assert '"subject": "Rechnung 4711"' in prompt # i18n-allow+ assert [c[1]["action"] for c in executor.calls] == [+ "list_events",+ "list_messages",+ "get_message",+ ]+ assert kontrollierer.ran == ["mission-1"]+++async def test_without_data_access_the_brief_names_every_source_unavailable() -> None:+ manager = _FakeManager()+ tool = CreateArtifactTool(_FakeBus(), manager=manager, kontrollierer=_FakeKontrollierer())+ await tool.execute(+ {"title": "Inbox", "request": "Show my inbox as a page."}, _ctx(language="en")+ )+ await _settle_fetch()+ prompt = manager.dispatched[0]["prompt"]+ assert "### Gmail inbox — UNAVAILABLE" in prompt+ assert "no access to the user's accounts" in prompt+ assert "### Google Calendar" not in prompt+++async def test_a_request_without_personal_data_fetches_nothing() -> None:+ manager = _FakeManager()+ executor = _FakeExecutor()+ tool = CreateArtifactTool(+ _FakeBus(),+ manager=manager,+ kontrollierer=_FakeKontrollierer(),+ executor=executor,+ tools_resolver=lambda: {"gmail": _Tool("gmail")},+ )+ await tool.execute(+ {"title": "Plans", "request": "Compare the three plans by price."}, _ctx(language="en")+ )+ await _settle_fetch()+ assert executor.calls == []+ assert "## Source data" not in manager.dispatched[0]["prompt"]+ assert "## Facts, never inventions" in manager.dispatched[0]["prompt"]+++async def test_a_sample_request_fetches_nothing_either() -> None:+ manager = _FakeManager()+ executor = _FakeExecutor()+ tool = CreateArtifactTool(+ _FakeBus(),+ manager=manager,+ kontrollierer=_FakeKontrollierer(),+ executor=executor,+ tools_resolver=lambda: {"gmail": _Tool("gmail")},+ )+ await tool.execute(+ {"title": "Demo", "request": "A demo inbox dashboard with sample mails."},+ _ctx(language="en"),+ )+ await _settle_fetch()+ assert executor.calls == []+ assert "## Source data" not in manager.dispatched[0]["prompt"]++@pytest.mark.asyncioasync def test_a_brain_supplied_ack_is_spoken_verbatim() -> None:tool = CreateArtifactTool(