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(wiki): run the evidence-safe realtime backfill as a periodic background task

Ruben Lütke2f57b60b47d8
diff --git a/jarvis/ui/web/server.py b/jarvis/ui/web/server.py
index 563538e1bc..cfd50933c2 100644
--- a/jarvis/ui/web/server.py
+++ b/jarvis/ui/web/server.py
@@ -121,6 +121,8 @@ class WebServer:
self._task_cancel_token: Any | None = None
# Phase B5 wiki write-wiring handle — shutdown() called in stop().
self._wiki_integration_handle: Any | None = None
+ # Periodic evidence-safe realtime wiki backfill — cancelled in stop().
+ self._wiki_backfill_task: asyncio.Task[None] | None = None
# Phase B3 wiki live-reload watchdog handle — shutdown() called in stop().
self._wiki_watcher: Any | None = None
self._channel_chat_bridge: Any | None = None
@@ -2497,6 +2499,15 @@ class WebServer:
)
self._wiki_integration_handle = handle
logger.info("wiki_integration: bootstrap_wiki_integration succeeded")
+ # Safety net for realtime turns whose live capture was missed (empty
+ # provider input transcript, crash, provider outage): sweep persisted
+ # sessions periodically. Idempotent via durable review keys, so a
+ # session already reviewed live is skipped, never re-journaled. The
+ # manual POST /api/wiki/backfill stays the explicit control.
+ if self._wiki_backfill_task is None:
+ self._wiki_backfill_task = asyncio.create_task(
+ self._wiki_auto_backfill_loop(), name="wiki-auto-backfill"
+ )
try:
from jarvis.memory.wiki.health import health as _wiki_health
@@ -2504,6 +2515,64 @@ class WebServer:
except Exception: # noqa: BLE001 — health recording must never break boot
logger.debug("wiki health.record_bootstrap(True) failed", exc_info=True)
+ async def _wiki_auto_backfill_loop(
+ self,
+ *,
+ initial_delay_s: float = 300.0,
+ interval_s: float = 6 * 3600.0,
+ ) -> None:
+ """Periodically sweep persisted realtime sessions into the wiki.
+
+ The live per-turn capture silently loses a turn whenever the realtime
+ provider delivers no input transcript, and the session-end sweep dies
+ with whichever layer misses its teardown. ``backfill_realtime_sessions``
+ re-reads the persisted voice turns and runs the same evidence-bound
+ pipeline, idempotent across retries via durable review keys — so this
+ loop only ever pays for sessions live capture actually missed. First
+ run is delayed well past boot readiness (AP-26); every pass is bounded
+ (2 days, 20 sessions).
+ """
+ from jarvis.memory.wiki.backfill import backfill_realtime_sessions
+ from jarvis.memory.wiki.integration import get_running_capture_runtime
+
+ await asyncio.sleep(initial_delay_s)
+ while True:
+ try:
+ runtime = get_running_capture_runtime()
+ store = getattr(self.app.state, "session_store", None)
+ if runtime is None or store is None or runtime.scheduler is None:
+ logger.debug(
+ "wiki auto-backfill: capture runtime or session store "
+ "not ready — skipping this pass"
+ )
+ else:
+ result = await backfill_realtime_sessions(
+ store=store,
+ extractor=runtime.extractor,
+ days=2,
+ max_sessions=20,
+ dry_run=False,
+ )
+ if result.sessions_reviewed or result.candidates_journaled:
+ logger.info(
+ "wiki auto-backfill: reviewed {} session(s), "
+ "journaled {} candidate(s)",
+ result.sessions_reviewed,
+ result.candidates_journaled,
+ )
+ else:
+ logger.debug(
+ "wiki auto-backfill: nothing eligible "
+ "(scanned={}, already_reviewed={})",
+ result.sessions_scanned,
+ result.sessions_already_reviewed,
+ )
+ except asyncio.CancelledError:
+ raise
+ except Exception: # noqa: BLE001 — the safety net must never crash the app
+ logger.opt(exception=True).warning("wiki auto-backfill pass failed")
+ await asyncio.sleep(interval_s)
+
def _init_wiki_boot_index(self, *, background: bool = False) -> None:
"""Rebuild the derived FTS view against the active vault.
@@ -2901,6 +2970,12 @@ class WebServer:
except Exception as exc: # noqa: BLE001
logger.opt(exception=exc).debug("Board-Aggregator close(): {}", exc)
+ # Stop the periodic realtime backfill before the wiki runtime goes away.
+ backfill_task = getattr(self, "_wiki_backfill_task", None)
+ if backfill_task is not None:
+ backfill_task.cancel()
+ self._wiki_backfill_task = None
+
# Phase B5 wiki write-wiring: unsubscribe + drain in-flight rollup task.
wiki_handle = getattr(self, "_wiki_integration_handle", None)
if wiki_handle is not None:
diff --git a/tests/unit/ui/test_wiki_auto_backfill_loop.py b/tests/unit/ui/test_wiki_auto_backfill_loop.py
new file mode 100644
index 0000000000..d03ed4fc5c
--- /dev/null
+++ b/tests/unit/ui/test_wiki_auto_backfill_loop.py
@@ -0,0 +1,110 @@
+"""The periodic realtime wiki backfill loop (server background task).
+
+Live 2026-07-18: realtime turns whose provider delivered no input transcript
+were silently lost to live capture, and the manual ``POST /api/wiki/backfill``
+was the only recovery. The server now runs the evidence-safe backfill as a
+bounded periodic background task. These tests bind the loop method to a
+minimal fake server so no real WebServer (sockets, config, voice) is built.
+"""
+from __future__ import annotations
+
+import asyncio
+from types import SimpleNamespace
+from typing import Any
+
+import pytest
+
+from jarvis.memory.wiki.backfill import BackfillResult
+
+
+def _fake_server(store: Any) -> SimpleNamespace:
+ return SimpleNamespace(app=SimpleNamespace(state=SimpleNamespace(session_store=store)))
+
+
+def _result(**overrides: Any) -> BackfillResult:
+ defaults: dict[str, Any] = {
+ "dry_run": False,
+ "days": 2,
+ "sessions_scanned": 1,
+ "sessions_eligible": 1,
+ "sessions_already_reviewed": 0,
+ "sessions_in_progress": 0,
+ "sessions_reviewed": 1,
+ "sessions_failed": 0,
+ "turns_considered": 3,
+ "candidates_journaled": 2,
+ }
+ defaults.update(overrides)
+ return BackfillResult(**defaults)
+
+
+async def _run_until(task: asyncio.Task, condition, *, timeout_s: float = 2.0) -> None:
+ deadline = asyncio.get_event_loop().time() + timeout_s
+ while not condition() and asyncio.get_event_loop().time() < deadline: # noqa: ASYNC110
+ await asyncio.sleep(0.01)
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+
+
+async def test_loop_runs_bounded_live_backfill(monkeypatch: pytest.MonkeyPatch) -> None:
+ from jarvis.memory.wiki import backfill as backfill_module
+ from jarvis.memory.wiki import integration as integration_module
+ from jarvis.ui.web.server import WebServer
+
+ extractor = object()
+ runtime = SimpleNamespace(extractor=extractor, scheduler=object())
+ monkeypatch.setattr(
+ integration_module, "get_running_capture_runtime", lambda: runtime
+ )
+ calls: list[dict[str, Any]] = []
+
+ async def _fake_backfill(**kwargs: Any) -> BackfillResult:
+ calls.append(kwargs)
+ return _result()
+
+ monkeypatch.setattr(backfill_module, "backfill_realtime_sessions", _fake_backfill)
+
+ store = object()
+ loop = WebServer._wiki_auto_backfill_loop.__get__(_fake_server(store))
+ task = asyncio.get_event_loop().create_task(
+ loop(initial_delay_s=0.0, interval_s=3600.0)
+ )
+ await _run_until(task, lambda: len(calls) >= 1)
+
+ assert len(calls) == 1 # one pass, then the long interval sleep
+ call = calls[0]
+ assert call["store"] is store
+ assert call["extractor"] is extractor
+ assert call["dry_run"] is False # a safety net that actually writes
+ assert call["days"] == 2 and call["max_sessions"] == 20 # bounded pass
+
+
+async def test_loop_skips_pass_when_runtime_not_ready(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ from jarvis.memory.wiki import backfill as backfill_module
+ from jarvis.memory.wiki import integration as integration_module
+ from jarvis.ui.web.server import WebServer
+
+ probes: list[bool] = []
+
+ def _no_runtime() -> None:
+ probes.append(True)
+ return None
+
+ monkeypatch.setattr(integration_module, "get_running_capture_runtime", _no_runtime)
+
+ async def _must_not_run(**_kwargs: Any) -> BackfillResult:
+ raise AssertionError("backfill must not run without a capture runtime")
+
+ monkeypatch.setattr(backfill_module, "backfill_realtime_sessions", _must_not_run)
+
+ loop = WebServer._wiki_auto_backfill_loop.__get__(_fake_server(object()))
+ task = asyncio.get_event_loop().create_task(
+ loop(initial_delay_s=0.0, interval_s=3600.0)
+ )
+ await _run_until(task, lambda: len(probes) >= 1)
+ assert probes # the pass ran, probed the runtime, and skipped gracefully