Skip to content

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.

feat(brain): deterministic wiki-write fast path with confirm-after-write

Ruben Lütke0907984004b8
diff --git a/jarvis/brain/manager.py b/jarvis/brain/manager.py
index ecbbb47a0d..24fefb9d8c 100644
--- a/jarvis/brain/manager.py
+++ b/jarvis/brain/manager.py
@@ -5483,6 +5483,198 @@ class BrainManager:
if len(history) > self._HISTORY_MAX:
self._history = history[-self._HISTORY_MAX:]
+ def _last_exchange_text(self) -> str | None:
+ """Last user+assistant exchange as an ingest source ('write THAT').
+
+ ``_history`` entries are real :class:`BrainMessage` instances —
+ ``role`` is one of ``user``/``assistant``/``system``/``tool`` and
+ ``content`` is either a plain string or a list of multimodal blocks
+ (dropped images etc.). Only plain-string user/assistant turns are
+ usable ingest source text; anything else is skipped, never raises.
+ """
+ try:
+ items = list(self._history)[-4:]
+ except Exception: # noqa: BLE001 — history shape is provider-owned
+ return None
+ parts: list[str] = []
+ for item in items:
+ role = getattr(item, "role", None)
+ text = getattr(item, "content", None)
+ if role in ("user", "assistant") and isinstance(text, str) and text.strip():
+ parts.append(f"{role}: {text.strip()}")
+ return "\n".join(parts[-2:]) or None
+
+ async def _run_wiki_ingest_fast_path(
+ self,
+ user_text: str,
+ *,
+ trace_id: UUID | None = None,
+ ) -> str | None:
+ """Deterministic explicit wiki-write path (spec A1-A3).
+
+ Explicit "write this to the wiki" commands must not depend on the
+ router LLM picking ``wiki-ingest`` (fresh-machine forensics Bug
+ 12/18). Mirrors the Computer-Use offload: immediate localized
+ progress ack, background ingest, completion announcement AFTER the
+ write — the success phrase is generated from the tool result, so
+ it can never precede (or contradict) the file on disk.
+ """
+ from jarvis.memory.wiki.intent import match_wiki_intent
+
+ if self._tool_executor is None:
+ return None
+ match = match_wiki_intent(user_text)
+ if match is None:
+ return None
+ tool = self._tools.get("wiki-ingest")
+ if tool is None:
+ return None
+ lang = self._direct_ack_language(user_text)
+
+ content = match.content
+ if content is None:
+ content = self._last_exchange_text()
+ if not content or len(content.strip()) < 12:
+ return await render_readback(
+ getattr(self, "_readback_composer", None),
+ instruction=(
+ "The user asked to write something to the wiki but no "
+ "content could be determined; ask them to repeat it "
+ "with the content."
+ ),
+ language=lang,
+ canned=lambda: action_phrase("wiki_nothing_to_save", lang),
+ )
+
+ tid = trace_id or uuid4()
+ bg_tasks = getattr(self, "_cu_background_tasks", None)
+ if bg_tasks is None:
+ bg_tasks = set()
+ self._cu_background_tasks = bg_tasks
+ task = asyncio.create_task(
+ self._run_wiki_ingest_background(
+ tool=tool,
+ text=content,
+ user_text=user_text,
+ trace_id=tid,
+ lang=lang,
+ ),
+ name="wiki-ingest-background",
+ )
+ # Keep a strong reference so the task is not garbage-collected
+ # mid-flight, and drop it on completion (same pattern as the
+ # Computer-Use offload above — one shared retention set).
+ bg_tasks.add(task)
+ task.add_done_callback(bg_tasks.discard)
+ return await render_readback(
+ getattr(self, "_readback_composer", None),
+ instruction=(
+ "Briefly acknowledge that you are writing this to the wiki "
+ "right now. Do NOT claim it is already saved."
+ ),
+ language=lang,
+ canned=lambda: action_phrase("wiki_saving", lang),
+ in_progress=True,
+ )
+
+ async def _run_wiki_ingest_background(
+ self,
+ *,
+ tool: Any,
+ text: str,
+ user_text: str,
+ trace_id: UUID,
+ lang: str,
+ ) -> None:
+ """Run wiki-ingest off the voice turn and announce the outcome.
+
+ Never raises; ALWAYS announces (zero silent drops) — mirrors
+ :meth:`_run_computer_use_background`. Nothing here is
+ user-cancellable, so there is no cancel branch.
+ """
+ out: str
+ diag: str | None = None
+ try:
+ result = await asyncio.wait_for(
+ self._tool_executor.execute(
+ tool,
+ {"text": text, "source": "voice:wiki-command"},
+ user_utterance=user_text,
+ trace_id=trace_id,
+ ),
+ timeout=90.0,
+ )
+ if result.success:
+ pages = ", ".join(
+ line.strip(" -")
+ for line in str(result.output or "").splitlines()
+ if line.strip().startswith("- ") and line.strip().endswith(".md")
+ )
+ canned_ok = (
+ action_phrase("wiki_saved_detail", lang, detail=pages)
+ if pages else action_phrase("wiki_saved", lang)
+ )
+ out = await render_readback(
+ getattr(self, "_readback_composer", None),
+ instruction=(
+ "The user's note was just written to their wiki; "
+ "confirm naturally, keeping the page name if given."
+ ),
+ language=lang,
+ canned=lambda: canned_ok,
+ facts={"user_request": user_text, "result": canned_ok},
+ honesty_bound=True,
+ latency_budget_ms=2500,
+ )
+ else:
+ diag = str(getattr(result, "error", "") or "unknown")
+ canned_fail = action_phrase("wiki_save_failed", lang)
+ out = await render_readback(
+ getattr(self, "_readback_composer", None),
+ instruction=(
+ "Writing the user's note to the wiki failed; tell "
+ "them plainly, keep the reason simple, and mention "
+ "they can check the wiki settings."
+ ),
+ language=lang,
+ canned=lambda: canned_fail,
+ facts={"user_request": user_text, "what_happened": diag},
+ honesty_bound=False,
+ latency_budget_ms=2500,
+ )
+ except TimeoutError:
+ diag = "wiki-ingest timeout after 90s"
+ out = await render_readback(
+ getattr(self, "_readback_composer", None),
+ instruction="Writing the note to the wiki took too long and was stopped.",
+ language=lang,
+ canned=lambda: action_phrase("wiki_save_failed", lang),
+ latency_budget_ms=2000,
+ )
+ except Exception as exc: # noqa: BLE001 — background crash must not leak
+ log.error("wiki-ingest background task failed: %r", exc, exc_info=True)
+ diag = repr(exc)
+ out = await render_readback(
+ getattr(self, "_readback_composer", None),
+ instruction="Something went wrong while writing the note to the wiki.",
+ language=lang,
+ canned=lambda: action_phrase("wiki_save_failed", lang),
+ latency_budget_ms=2000,
+ )
+ self._append_cu_outcome_to_history(
+ user_request=user_text, outcome_text=out, diagnostic=diag,
+ )
+ try:
+ await self._bus.publish(AnnouncementRequested(
+ text=out,
+ priority="normal",
+ language=lang,
+ kind="completion",
+ detail=diag,
+ ))
+ except Exception: # noqa: BLE001
+ log.debug("wiki-ingest completion announce failed", exc_info=True)
+
async def _on_cu_tool_completion(self, event: Any) -> None:
"""Mirror a router-tier ``computer_use`` TOOL outcome into the history.
@@ -6448,6 +6640,25 @@ class BrainManager:
)
return local_action
+ # Wiki-write fast path (spec A1-A3): an explicit "write this to the
+ # wiki" command must not depend on the router LLM choosing the
+ # wiki-ingest tool (fresh-machine forensics Bug 12/18). Deterministic,
+ # model-independent, confirm-after-write — same shape as the
+ # local-action block above. Placed before navigation/capability gates
+ # so a skill match never shadows an explicit wiki command.
+ if self._skill_turn_match is None:
+ wiki_reply = await self._run_wiki_ingest_fast_path(
+ user_text, trace_id=turn_trace_id,
+ )
+ if wiki_reply is not None:
+ await self._record_response_side_effects(
+ user_text=user_text,
+ response_text=wiki_reply,
+ use_history=use_history,
+ trace_id=turn_trace_id,
+ )
+ return wiki_reply
+
# Navigation fast-path: a clear "go to section X" command moves the UI
# deterministically (a dumb action, AD-OE3). Placed BEFORE the capability
# gate — which would refuse "zeig die Socials" because 'social' is an
diff --git a/jarvis/voice/action_phrases.py b/jarvis/voice/action_phrases.py
index d807c3fd6a..a4d76e0a3b 100644
--- a/jarvis/voice/action_phrases.py
+++ b/jarvis/voice/action_phrases.py
@@ -240,6 +240,40 @@ _PHRASES: dict[str, dict[str, str]] = {
"en": "I couldn't start the background helper: {reason}",
"es": "No pude iniciar el ayudante en segundo plano: {reason}",
},
+ # Deterministic wiki-write fast path (spec A1-A3). The saving line is a
+ # PROGRESS ack — it must never claim the write already happened; the
+ # saved/failed lines are the post-write truth (confirm-after-write).
+ "wiki_saving": {
+ "de": "Ich schreibe das jetzt ins Wiki.", # i18n-allow
+ "en": "Writing that to the wiki now.",
+ "es": "Lo estoy escribiendo en la wiki.",
+ },
+ "wiki_saved": {
+ "de": "Im Wiki gespeichert.", # i18n-allow
+ "en": "Saved to the wiki.",
+ "es": "Guardado en la wiki.",
+ },
+ "wiki_saved_detail": {
+ "de": "Im Wiki gespeichert: {detail}.", # i18n-allow
+ "en": "Saved to the wiki: {detail}.",
+ "es": "Guardado en la wiki: {detail}.",
+ },
+ "wiki_save_failed": {
+ "de": "Das Speichern im Wiki hat nicht geklappt.", # i18n-allow
+ "en": "Saving to the wiki did not work.",
+ "es": "No se pudo guardar en la wiki.",
+ },
+ "wiki_save_failed_reason": {
+ "de": "Das Speichern im Wiki hat nicht geklappt: {reason}", # i18n-allow
+ "en": "Saving to the wiki did not work: {reason}",
+ "es": "No se pudo guardar en la wiki: {reason}",
+ },
+ "wiki_nothing_to_save": {
+ "de": "Mir ist nicht klar, was ich ins Wiki schreiben soll. Sag es mir " # i18n-allow
+ "bitte noch einmal mit Inhalt.", # i18n-allow
+ "en": "I am not sure what to write to the wiki. Please say it again with the content.",
+ "es": "No tengo claro qué escribir en la wiki; dímelo otra vez con el contenido.",
+ },
}
diff --git a/tests/unit/brain/test_wiki_fast_path.py b/tests/unit/brain/test_wiki_fast_path.py
new file mode 100644
index 0000000000..abfa0fa5c2
--- /dev/null
+++ b/tests/unit/brain/test_wiki_fast_path.py
@@ -0,0 +1,145 @@
+"""Explicit wiki commands run model-independently and confirm only after
+the write (spec A1-A3). Uses constructor-injected fakes per house style —
+build a minimal BrainManager the same way test_routing.py does (copy its
+manager fixture) and register a recording fake executor + a fake
+wiki-ingest tool."""
+from __future__ import annotations
+
+import asyncio
+from typing import Any
+
+import pytest
+
+from jarvis.brain.manager import BrainManager
+from jarvis.core.bus import EventBus
+from jarvis.core.config import JarvisConfig
+from jarvis.core.protocols import BrainMessage, ToolResult
+
+
+class FakeWikiIngestTool:
+ name = "wiki-ingest"
+ risk_tier = "monitor"
+
+ def __init__(self, result: ToolResult, delay_s: float = 0.0) -> None:
+ self.result = result
+ self.delay_s = delay_s
+ self.calls: list[dict] = []
+
+
+class RecordingExecutor:
+ def __init__(self) -> None:
+ self.order: list[str] = []
+
+ async def execute(self, tool, args, **kwargs):
+ self.order.append("execute:start")
+ if getattr(tool, "delay_s", 0):
+ await asyncio.sleep(tool.delay_s)
+ tool.calls.append(dict(args))
+ self.order.append("execute:done")
+ return tool.result
+
+
+class RecordingBus(EventBus):
+ """EventBus that also keeps a flat list of everything published.
+
+ Mirrors the ``_FakeBus``/``bus.published`` shape used by the sibling
+ Computer-Use offload tests (tests/unit/brain/test_computer_use_offload.py)
+ while staying a REAL EventBus so BrainManager's constructor/attach path
+ behaves exactly as in production.
+ """
+
+ def __init__(self) -> None:
+ super().__init__()
+ self.published: list[Any] = []
+
+ async def publish(self, event: Any) -> None: # noqa: ANN401
+ self.published.append(event)
+ await super().publish(event)
+
+
+def manager_factory():
+ """Build a minimal BrainManager wired for the wiki fast path.
+
+ Follows the ``tests/unit/brain/test_routing.py`` construction style: the
+ real ``BrainManager(config=JarvisConfig(), bus=..., tools=..., tool_executor=...)``
+ constructor, no real providers (``readback_composer`` stays unset, so
+ ``render_readback`` always returns the deterministic canned phrase — no
+ LLM call, no network).
+
+ Seeds one plausible prior user/assistant exchange into ``_history`` so an
+ ANAPHORIC "write THAT to the wiki" command (spec A1) has real content to
+ source from — mirroring production, where such a command is never
+ literally the first turn of a conversation.
+ """
+
+ def _factory(*, tools: dict[str, Any]) -> tuple[BrainManager, RecordingExecutor, RecordingBus]:
+ bus = RecordingBus()
+ executor = RecordingExecutor()
+ mgr = BrainManager(
+ config=JarvisConfig(),
+ bus=bus,
+ tools=tools,
+ tool_executor=executor, # type: ignore[arg-type]
+ )
+ mgr._history.append(
+ BrainMessage(
+ role="user",
+ content=(
+ "Ich war heute mit Joy im Park und wir haben über ihren " # i18n-allow
+ "Geburtstag im August gesprochen." # i18n-allow
+ ),
+ )
+ )
+ mgr._history.append(
+ BrainMessage(
+ role="assistant",
+ content="Klingt nach einem schönen Nachmittag im Park mit Joy.", # i18n-allow
+ )
+ )
+ return mgr, executor, bus
+
+ return _factory
+
+
+async def test_explicit_command_ingests_and_announces_after_write(manager_factory):
+ """'Schreib ins Wiki, dass X' → tool called with X; the completion
+ announcement fires only AFTER the executor returned success.""" # i18n-allow
+ tool = FakeWikiIngestTool(
+ ToolResult(
+ success=True,
+ output="Wiki ingest done:\n- applied: 1\nPages touched:\n - joy.md",
+ )
+ )
+ mgr, executor, bus = manager_factory(tools={"wiki-ingest": tool})
+ reply = await mgr._run_wiki_ingest_fast_path(
+ "Schreib ins Wiki, dass Joys Geburtstag am 14. August ist" # i18n-allow
+ )
+ assert reply is not None # immediate progress ack
+ await asyncio.sleep(0.05) # let the background task run
+ assert tool.calls, "wiki-ingest must be invoked through the executor"
+ completed = [e for e in bus.published if type(e).__name__ == "AnnouncementRequested"]
+ assert completed, "outcome must be announced (zero silent drops)"
+ assert executor.order.index("execute:done") < len(executor.order)
+
+
+async def test_failure_is_announced_honestly_never_as_success(manager_factory):
+ tool = FakeWikiIngestTool(
+ ToolResult(success=False, output="", error="wiki integration not bootstrapped")
+ )
+ mgr, executor, bus = manager_factory(tools={"wiki-ingest": tool})
+ reply = await mgr._run_wiki_ingest_fast_path("write that to the wiki")
+ assert reply is not None
+ await asyncio.sleep(0.05)
+ completed = [e for e in bus.published if type(e).__name__ == "AnnouncementRequested"]
+ assert completed
+ text = completed[-1].text.lower()
+ assert "saved to the wiki." != text # no bare success phrase
+ assert any(k in text for k in ("not work", "nicht geklappt", "no se pudo")) # i18n-allow
+
+
+async def test_non_wiki_turn_returns_none(manager_factory):
+ tool = FakeWikiIngestTool(ToolResult(success=True, output=""))
+ mgr, executor, bus = manager_factory(tools={"wiki-ingest": tool})
+ assert await mgr._run_wiki_ingest_fast_path("wie wird das wetter morgen?") is None # i18n-allow
+ assert not tool.calls