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(ultrawiki): serve the readable Explore surface over REST

Ruben Lütkec42dd62d84f5
diff --git a/jarvis/ui/web/server.py b/jarvis/ui/web/server.py
index 5112a5819e..65730f7080 100644
--- a/jarvis/ui/web/server.py
+++ b/jarvis/ui/web/server.py
@@ -342,6 +342,7 @@ class WebServer:
from .telephony_routes import router as telephony_router
from .tool_model_routes import router as tool_model_router
from .tools_routes import router as tools_router
+ from .ultrawiki_explore_routes import router as ultrawiki_explore_router
from .ultrawiki_routes import router as ultrawiki_router
from .update_routes import router as update_router
from .wiki_routes import router as wiki_router
@@ -469,6 +470,9 @@ class WebServer:
# while it is None the routes answer 503 (search answers 409 whenever
# the mode switch is off).
app.include_router(ultrawiki_router)
+ # The readable Explore surface over the same store — separate module,
+ # same prefix and tag (see ultrawiki_explore_routes for why).
+ app.include_router(ultrawiki_explore_router)
# ConnectionManager singleton for the global event stream. Attached
# to MissionBus.subscribe_all() in start().
app.state.missions_ws_manager = _MissionsConnMgr()
diff --git a/jarvis/ui/web/ultrawiki_explore_routes.py b/jarvis/ui/web/ultrawiki_explore_routes.py
new file mode 100644
index 0000000000..787ea2e43c
--- /dev/null
+++ b/jarvis/ui/web/ultrawiki_explore_routes.py
@@ -0,0 +1,220 @@
+"""UltraWiki Explore REST surface — the readable view over the store.
+
+UltraWiki could answer questions long before it could SHOW anything. The
+store is a log (one row per raw unit, titles repeating by the hundred), so
+these routes serve the condensed model from
+:mod:`jarvis.ultrawiki.projection` instead: entity pages, moment pages, and
+the graph over them. Pure reads, no writes, off the voice hot path.
+
+Own module rather than more lines in ``ultrawiki_routes.py``: that file had
+already grown past 1800 lines and is edited concurrently by other sessions in
+this shared tree. Same prefix and same ``ultrawiki`` tag, so the CLI-first
+contract still resolves every handler to ``jarvis api ultrawiki <op>``.
+
+The mode gate and the store accessor are reused from the main module — one
+definition of "is UltraWiki answering right now", never a second opinion.
+"""
+
+from __future__ import annotations
+
+import logging
+from typing import Any
+
+from fastapi import APIRouter, HTTPException, Query, Request
+
+from jarvis.ui.web.ultrawiki_routes import _require_active, _store_of
+
+log = logging.getLogger(__name__)
+
+router = APIRouter(prefix="/api/ultrawiki", tags=["ultrawiki"])
+
+
+async def _explore_context(request: Request) -> tuple[Any, Any, dict[str, int]]:
+ """(store, projection, corpus counts) for any Explore read.
+
+ The corpus counts travel with EVERY Explore answer, not just the empty
+ ones: they are what turns "nothing here" from a dead end into a diagnosis.
+ """
+ from jarvis.ultrawiki.projection import get_projection
+
+ service = _require_active(request)
+ store = await _store_of(service)
+ sources = await store.list_sources()
+ counts = await store.counts()
+ distilled, _max_id, _newest = await store.distilled_fingerprint()
+ projection = await get_projection(store)
+ return (
+ store,
+ projection,
+ {
+ "sources": len(sources),
+ "items": int(getattr(counts, "total", 0)),
+ "distilled": int(distilled),
+ },
+ )
+
+
+def _explore_reason(corpus: dict[str, int], entity_count: int) -> str:
+ """Name the cause of an empty Explore view, in the order it fails."""
+ from jarvis.ultrawiki.types import ExploreReason
+
+ if corpus["sources"] == 0:
+ return ExploreReason.NO_SOURCES.value
+ if corpus["items"] == 0:
+ return ExploreReason.NOTHING_IMPORTED.value
+ if corpus["distilled"] == 0:
+ return ExploreReason.NOTHING_DISTILLED.value
+ if entity_count == 0:
+ return ExploreReason.NO_ENTITIES.value
+ return ExploreReason.OK.value
+
+
+def _entity_payload(entity: Any, projection: Any) -> dict[str, Any]:
+ """One entity as the UI needs it — neighbours carry their display label,
+ because a raw case-folded key is not something to show a human."""
+ return {
+ "key": entity.key,
+ "label": entity.label,
+ "mentions": entity.mentions,
+ "first_seen": entity.first_seen,
+ "last_seen": entity.last_seen,
+ "neighbors": [
+ {
+ "key": key,
+ "label": (
+ projection.entity_by_key[key].label if key in projection.entity_by_key else key
+ ),
+ "shared": shared,
+ }
+ for key, shared in entity.neighbors
+ ],
+ }
+
+
+def _moment_payload(moment: Any) -> dict[str, Any]:
+ return {
+ "document_id": moment.document_id,
+ "item_id": moment.item_id,
+ "title": moment.title,
+ "summary": moment.summary,
+ "resolution": moment.resolution,
+ "entity_keys": list(moment.entity_keys),
+ "timestamp_utc": moment.timestamp_utc,
+ "month": moment.month,
+ "source_id": moment.source_id,
+ "source_label": moment.source_label,
+ "permalink": moment.permalink,
+ }
+
+
+ "/explore/entities",
+ summary="Browse the people, places and things the knowledge base knows",
+)
+async def list_explore_entities(
+ request: Request,
+ q: str = Query(default="", description="Substring filter over entity labels"),
+ limit: int = Query(default=200, ge=1, le=2000),
+ offset: int = Query(default=0, ge=0),
+) -> dict[str, Any]:
+ """Entity pages, most-mentioned first, with the reason when there are none."""
+ _store, projection, corpus = await _explore_context(request)
+ needle = q.strip().casefold()
+ matched = [
+ entity
+ for entity in projection.entities
+ if not needle or needle in entity.key or needle in entity.label.casefold()
+ ]
+ page = matched[offset : offset + limit]
+ return {
+ "ok": True,
+ "entities": [_entity_payload(entity, projection) for entity in page],
+ "total": len(matched),
+ "corpus": corpus,
+ "reason": _explore_reason(corpus, len(projection.entities)),
+ }
+
+
+ "/explore/entities/{key:path}",
+ summary="One entity page with the moments it appears in",
+)
+async def get_explore_entity(
+ key: str,
+ request: Request,
+ limit: int = Query(default=100, ge=1, le=1000),
+) -> dict[str, Any]:
+ """Everything the knowledge base has on one entity, newest evidence first."""
+ _store, projection, corpus = await _explore_context(request)
+ entity = projection.entity_by_key.get(key.casefold())
+ if entity is None:
+ raise HTTPException(status_code=404, detail=f"no entity named {key!r}")
+ moments = projection.moments_by_entity.get(entity.key, ())
+ return {
+ "ok": True,
+ "entity": _entity_payload(entity, projection),
+ "moments": [_moment_payload(m) for m in moments[:limit]],
+ "total": len(moments),
+ "corpus": corpus,
+ }
+
+
+ "/explore/moments",
+ summary="Browse the distilled moments, newest first",
+)
+async def list_explore_moments(
+ request: Request,
+ entity: str = Query(default="", description="Restrict to one entity key"),
+ month: str = Query(default="", description="Restrict to one YYYY-MM bucket"),
+ limit: int = Query(default=100, ge=1, le=1000),
+ offset: int = Query(default=0, ge=0),
+) -> dict[str, Any]:
+ """Each moment is titled by the question it answers and links to its evidence."""
+ _store, projection, corpus = await _explore_context(request)
+ if entity:
+ moments = list(projection.moments_by_entity.get(entity.casefold(), ()))
+ else:
+ moments = list(projection.moments)
+ if month:
+ moments = [m for m in moments if m.month == month]
+ page = moments[offset : offset + limit]
+ return {
+ "ok": True,
+ "moments": [_moment_payload(m) for m in page],
+ "total": len(moments),
+ "corpus": corpus,
+ "reason": _explore_reason(corpus, len(projection.entities)),
+ }
+
+
+ "/explore/graph",
+ summary="The entity graph — who and what appears together",
+)
+async def get_explore_graph(
+ request: Request,
+ min_mentions: int = Query(
+ default=2,
+ ge=1,
+ le=100,
+ description="Hide entities mentioned fewer times than this",
+ ),
+) -> dict[str, Any]:
+ """Nodes + weighted edges above a mention floor.
+
+ The floor defaults to 2 because the long tail dominates a real corpus
+ (measured: 977 entities collapse to 313 at two mentions); drawing every
+ one-off at once is a hairball rather than a map.
+ """
+ _store, projection, corpus = await _explore_context(request)
+ nodes, edges = projection.graph(min_mentions=min_mentions)
+ return {
+ "ok": True,
+ "nodes": nodes,
+ "edges": edges,
+ "min_mentions": min_mentions,
+ "total_entities": len(projection.entities),
+ "corpus": corpus,
+ "reason": _explore_reason(corpus, len(projection.entities)),
+ }
\ No newline at end of file
diff --git a/jarvis/ultrawiki/types.py b/jarvis/ultrawiki/types.py
index 6c0bb54abc..fe9d868417 100644
--- a/jarvis/ultrawiki/types.py
+++ b/jarvis/ultrawiki/types.py
@@ -22,6 +22,7 @@ __all__ = [
"ItemState",
"DocType",
"ConsentState",
+ "ExploreReason",
"IncrementalMode",
"AuthKind",
"RawItem",
@@ -78,6 +79,28 @@ class ConsentState(StrEnum):
REVOKED = "revoked"
+class ExploreReason(StrEnum):
+ """Why the Explore view has nothing to show — or that it has.
+
+ "The knowledge base looks empty" has FOUR different causes and the user
+ cannot tell them apart by looking: no source configured, a source that
+ never imported, imported items nothing has distilled yet, or distilled
+ items that named no entity. A previous forensic found exactly one of them
+ (consent granted but never fetched) undiagnosed for days behind a blank
+ screen, so the server names the cause instead of leaving the surface to
+ guess from counts.
+
+ Five-layer discipline (AP-4 / BUG-008): this is the CANONICAL list. The
+ TypeScript union in ``lib/ultrawikiApi.ts`` is parity-tested against it.
+ """
+
+ OK = "ok"
+ NO_SOURCES = "no_sources"
+ NOTHING_IMPORTED = "nothing_imported"
+ NOTHING_DISTILLED = "nothing_distilled"
+ NO_ENTITIES = "no_entities"
+
+
class IncrementalMode(StrEnum):
"""How a connector keeps a source fresh after backfill."""
diff --git a/tests/unit/web/test_ultrawiki_explore_routes.py b/tests/unit/web/test_ultrawiki_explore_routes.py
new file mode 100644
index 0000000000..d5755e2395
--- /dev/null
+++ b/tests/unit/web/test_ultrawiki_explore_routes.py
@@ -0,0 +1,302 @@
+"""Full-app tests for the /api/ultrawiki/explore REST surface.
+
+The Explore routes are what makes the store readable — entity pages, moment
+pages, and the graph over them. They are pure reads over the projection, so
+these tests seed the store directly (a documented service seam) instead of
+driving the ingestion pipeline.
+
+Emptiness is the interesting case here, not the happy path: a knowledge base
+that looks empty has THREE different causes the user cannot tell apart, and
+a previous forensic found one of them undiagnosed for days. Every one of them
+gets its own asserted reason code.
+"""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+from fastapi.testclient import TestClient
+
+from jarvis.core.bus import EventBus
+from jarvis.core.config import JarvisConfig
+from jarvis.ui.web.server import WebServer
+from jarvis.ultrawiki import service as uw_service_mod
+from jarvis.ultrawiki.service import UltraWikiService
+from jarvis.ultrawiki.types import DocType, ExploreReason, ItemState, RawItem
+
+
+def env(tmp_path: Path, monkeypatch):
+ toml_path = tmp_path / "jarvis.toml"
+ toml_path.write_text("", encoding="utf-8")
+ monkeypatch.setenv("JARVIS_CONFIG", str(toml_path))
+
+ cfg = JarvisConfig()
+ cfg.ui.dev_mode = True
+ cfg.memory.data_dir = str(tmp_path / "data")
+ cfg.ultrawiki.enabled = True
+
+ server = WebServer(cfg, bus=EventBus())
+ service = UltraWikiService(cfg, embedding_backend_factory=lambda: None)
+ server.app.state.ultrawiki = service
+ uw_service_mod.clear_jobs()
+ with TestClient(server.app) as client:
+ yield SimpleNamespace(client=client, service=service, cfg=cfg, tmp=tmp_path)
+ client.portal.call(service.shutdown)
+ uw_service_mod.clear_jobs()
+
+
+def seed(env, rows: list[dict], *, source_label: str = "Docs") -> None:
+ """Put distilled documents straight into the store.
+
+ Each row: external_id, question, entities, timestamp, optional summary.
+ """
+
+ async def _run() -> None:
+ await env.service.ensure_started()
+ store = env.service._store # noqa: SLF001 — documented test seam
+ assert store is not None
+ await store.upsert_source("src1", connector="local-folder", label=source_label)
+ for row in rows:
+ await store.upsert_items(
+ "src1",
+ [
+ RawItem(
+ external_id=row["external_id"],
+ body=row.get("summary", "") or row["question"],
+ permalink=f"app://{row['external_id']}",
+ timestamp_utc=row.get("timestamp", "2026-03-01T10:00:00Z"),
+ title="Conversation on 2026-03-01",
+ )
+ ],
+ )
+ item = await store.get_item_by_external_id("src1", row["external_id"])
+ assert item is not None
+ if row.get("distilled", True):
+ await store.add_document(
+ item["id"],
+ DocType.SUMMARY,
+ row.get("summary", "") or row["question"],
+ distill_json=json.dumps(
+ {
+ "question": row["question"],
+ "summary": row.get("summary", ""),
+ "resolution": row.get("resolution", ""),
+ "entities": row.get("entities", []),
+ "refs": [],
+ }
+ ),
+ distill_version=1,
+ )
+ await store.mark_stage_done(item["id"], ItemState.DISTILLED)
+
+ env.client.portal.call(_run)
+
+
+def seed_source_only(env) -> None:
+ async def _run() -> None:
+ await env.service.ensure_started()
+ store = env.service._store # noqa: SLF001 — documented test seam
+ await store.upsert_source("src1", connector="local-folder", label="Docs")
+
+ env.client.portal.call(_run)
+
+
+TRIP = [
+ {
+ "external_id": "a",
+ "question": "How do I get to Bora Bora?",
+ "summary": "Routes via Tahiti.",
+ "entities": ["Bora Bora", "Tahiti"],
+ "timestamp": "2026-03-01T10:00:00Z",
+ },
+ {
+ "external_id": "b",
+ "question": "Which airline flies to Tahiti?",
+ "entities": ["Bora Bora", "Tahiti"],
+ "timestamp": "2026-04-01T10:00:00Z",
+ },
+ {
+ "external_id": "c",
+ "question": "What is the weather in Berlin?",
+ "entities": ["Berlin"],
+ "timestamp": "2026-05-01T10:00:00Z",
+ },
+]
+
+
+# ---------------------------------------------------------------------------
+# Entities
+# ---------------------------------------------------------------------------
+
+
+def test_entities_list_is_ranked_by_mentions(env):
+ seed(env, TRIP)
+
+ response = env.client.get("/api/ultrawiki/explore/entities")
+
+ assert response.status_code == 200, response.text
+ body = response.json()
+ assert body["ok"] is True
+ assert [e["label"] for e in body["entities"]][:2] == ["Bora Bora", "Tahiti"]
+ assert body["total"] == 3
+ assert body["reason"] == ExploreReason.OK
+
+
+def test_entities_can_be_filtered_by_query(env):
+ seed(env, TRIP)
+
+ response = env.client.get("/api/ultrawiki/explore/entities", params={"q": "bor"})
+
+ assert [e["label"] for e in response.json()["entities"]] == ["Bora Bora"]
+
+
+def test_entity_detail_carries_its_moments(env):
+ seed(env, TRIP)
+
+ response = env.client.get("/api/ultrawiki/explore/entities/tahiti")
+
+ assert response.status_code == 200, response.text
+ body = response.json()
+ assert body["entity"]["label"] == "Tahiti"
+ assert body["entity"]["mentions"] == 2
+ assert [m["title"] for m in body["moments"]] == [
+ "Which airline flies to Tahiti?",
+ "How do I get to Bora Bora?",
+ ]
+ assert [n["label"] for n in body["entity"]["neighbors"]] == ["Bora Bora"]
+
+
+def test_unknown_entity_is_a_404_not_an_empty_page(env):
+ seed(env, TRIP)
+
+ response = env.client.get("/api/ultrawiki/explore/entities/atlantis")
+
+ assert response.status_code == 404
+
+
+# ---------------------------------------------------------------------------
+# Moments
+# ---------------------------------------------------------------------------
+
+
+def test_moments_are_newest_first_with_their_evidence_link(env):
+ seed(env, TRIP)
+
+ body = env.client.get("/api/ultrawiki/explore/moments").json()
+
+ assert [m["title"] for m in body["moments"]][0] == "What is the weather in Berlin?"
+ assert body["moments"][0]["permalink"] == "app://c"
+ assert body["total"] == 3
+
+
+def test_moments_can_be_scoped_to_one_entity(env):
+ seed(env, TRIP)
+
+ body = env.client.get("/api/ultrawiki/explore/moments", params={"entity": "berlin"}).json()
+
+ assert [m["title"] for m in body["moments"]] == ["What is the weather in Berlin?"]
+
+
+def test_moments_can_be_scoped_to_one_month(env):
+ seed(env, TRIP)
+
+ body = env.client.get("/api/ultrawiki/explore/moments", params={"month": "2026-04"}).json()
+
+ assert [m["title"] for m in body["moments"]] == ["Which airline flies to Tahiti?"]
+
+
+def test_moments_paginate(env):
+ seed(env, TRIP)
+
+ body = env.client.get("/api/ultrawiki/explore/moments", params={"limit": 1, "offset": 1}).json()
+
+ assert [m["title"] for m in body["moments"]] == ["Which airline flies to Tahiti?"]
+ assert body["total"] == 3
+
+
+# ---------------------------------------------------------------------------
+# Graph
+# ---------------------------------------------------------------------------
+
+
+def test_graph_defaults_to_the_two_mention_floor(env):
+ seed(env, TRIP)
+
+ body = env.client.get("/api/ultrawiki/explore/graph").json()
+
+ assert {n["key"] for n in body["nodes"]} == {"bora bora", "tahiti"}
+ assert body["edges"] == [{"source": "bora bora", "target": "tahiti", "weight": 2}]
+ assert body["min_mentions"] == 2
+
+
+def test_graph_floor_of_one_shows_the_whole_corpus(env):
+ seed(env, TRIP)
+
+ body = env.client.get("/api/ultrawiki/explore/graph", params={"min_mentions": 1}).json()
+
+ assert len(body["nodes"]) == 3
+
+
+# ---------------------------------------------------------------------------
+# The three honest empty states
+# ---------------------------------------------------------------------------
+
+
+def test_no_sources_says_so_rather_than_showing_an_empty_canvas(env):
+ body = env.client.get("/api/ultrawiki/explore/entities").json()
+
+ assert body["entities"] == []
+ assert body["reason"] == ExploreReason.NO_SOURCES
+ assert body["corpus"] == {"sources": 0, "items": 0, "distilled": 0}
+
+
+def test_a_source_with_nothing_imported_is_its_own_reason(env):
+ seed_source_only(env)
+
+ body = env.client.get("/api/ultrawiki/explore/entities").json()
+
+ assert body["reason"] == ExploreReason.NOTHING_IMPORTED
+ assert body["corpus"]["sources"] == 1
+
+
+def test_imported_but_undistilled_items_are_their_own_reason(env):
+ seed(
+ env,
+ [{"external_id": "a", "question": "Q", "distilled": False}],
+ )
+
+ body = env.client.get("/api/ultrawiki/explore/entities").json()
+
+ assert body["reason"] == ExploreReason.NOTHING_DISTILLED
+ assert body["corpus"] == {"sources": 1, "items": 1, "distilled": 0}
+
+
+def test_distilled_items_that_named_nobody_are_their_own_reason(env):
+ seed(env, [{"external_id": "a", "question": "Q", "entities": []}])
+
+ body = env.client.get("/api/ultrawiki/explore/entities").json()
+
+ assert body["reason"] == ExploreReason.NO_ENTITIES
+ assert body["corpus"]["distilled"] == 1
+ # The moments still exist — only the entity layer is empty.
+ assert env.client.get("/api/ultrawiki/explore/moments").json()["total"] == 1
+
+
+# ---------------------------------------------------------------------------
+# Mode discipline
+# ---------------------------------------------------------------------------
+
+
+def test_explore_answers_409_while_ultra_mode_is_off(env):
+ env.cfg.ultrawiki.enabled = False
+
+ for path in (
+ "/api/ultrawiki/explore/entities",
+ "/api/ultrawiki/explore/moments",
+ "/api/ultrawiki/explore/graph",
+ ):
+ assert env.client.get(path).status_code == 409, path