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): store, staged pipeline, hybrid search, REST surface

Ruben Lütke55accbfc9480
diff --git a/jarvis/core/config_writer.py b/jarvis/core/config_writer.py
index 4a2b7abac6..b1034d6253 100644
--- a/jarvis/core/config_writer.py
+++ b/jarvis/core/config_writer.py
@@ -649,6 +649,53 @@ def set_wiki_vault_root(vault_root: str, *, path: Path = DEFAULT_CONFIG_FILE) ->
_patch_table(path, "wiki_integration", "vault_root", vault_root)
+#: Closed list of ``[ultrawiki]`` slot keys the settings surface may write.
+#: ``enabled`` has its own dedicated setter (the mode switch is a deliberate,
+#: separate act); credentials NEVER go here — the Postgres connection string
+#: lives in the secret chain under ``ultrawiki_db_url`` (AP-12).
+ULTRAWIKI_SLOT_KEYS = (
+ "db_backend",
+ "embedding_provider",
+ "embedding_model",
+ "distill_provider",
+ "distill_model",
+ "rerank_provider",
+ "ollama_endpoint",
+)
+
+
+def set_ultrawiki_enabled(enabled: bool, *, path: Path = DEFAULT_CONFIG_FILE) -> None:
+ """Persist the UltraWiki mode switch to ``[ultrawiki] enabled``.
+
+ The either-or Wiki mode switch (design D-5): True = UltraWiki captures and
+ answers, False = the normal wiki does. Switching is non-destructive in both
+ directions (D-9) — this writes one flag and never deletes data. TOML-only
+ by design: ``ultrawiki`` is NOT tracked in the drift-guard's reference
+ snapshot, so a plain atomic write is never reverted (same rationale as
+ :func:`set_wiki_vault_root`). The UltraWiki routes apply the change live;
+ this persists the boot default.
+ """
+ _patch_table(path, "ultrawiki", "enabled", bool(enabled))
+
+
+def set_ultrawiki_slot(key: str, value: str, *, path: Path = DEFAULT_CONFIG_FILE) -> None:
+ """Persist one flat ``[ultrawiki]`` capability-slot key.
+
+ ``key`` must come from the closed :data:`ULTRAWIKI_SLOT_KEYS` list — the
+ storage-backend selector plus the provider/model slots. Values are plain
+ strings; empty string is the documented "unconfigured" sentinel. Secrets
+ are refused by construction: the Postgres connection string rides the
+ secret chain under ``ultrawiki_db_url`` (AP-12), never the TOML. TOML-only,
+ same drift-guard rationale as :func:`set_ultrawiki_enabled`.
+ """
+ if key not in ULTRAWIKI_SLOT_KEYS:
+ raise ValueError(
+ f"unknown [ultrawiki] slot key {key!r} "
+ f"(allowed: {', '.join(ULTRAWIKI_SLOT_KEYS)})"
+ )
+ _patch_table(path, "ultrawiki", key, str(value))
+
+
def set_overlay_style(style: str, *, path: Path = DEFAULT_CONFIG_FILE) -> None:
"""Persist the on-screen overlay style to ``[ui] orb_style`` in jarvis.toml.
diff --git a/jarvis/ui/web/server.py b/jarvis/ui/web/server.py
index d47294add1..5de19dad0d 100644
--- a/jarvis/ui/web/server.py
+++ b/jarvis/ui/web/server.py
@@ -331,6 +331,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_routes import router as ultrawiki_router
from .update_routes import router as update_router
from .wiki_routes import router as wiki_router
from .wiki_ws import router as wiki_ws_router
@@ -452,6 +453,11 @@ class WebServer:
# Forwards WikiPageChanged events from the shared EventBus to
# subscribed UI clients. WikiWatcher is started in start().
app.include_router(wiki_ws_router)
+ # UltraWiki (semantic memory mode) — status/activation/sources/sync/
+ # search. The service handle is wired in start() via _init_ultrawiki();
+ # while it is None the routes answer 503 (search answers 409 whenever
+ # the mode switch is off).
+ app.include_router(ultrawiki_router)
# ConnectionManager singleton for the global event stream. Attached
# to MissionBus.subscribe_all() in start().
app.state.missions_ws_manager = _MissionsConnMgr()
@@ -460,6 +466,9 @@ class WebServer:
# so the REST routes return 503 instead of crashing.
app.state.mission_manager = None
app.state.kontrollierer = None
+ # UltraWikiService is constructed in start() (_init_ultrawiki); None
+ # keeps /api/ultrawiki honest (503 / degraded status) until then.
+ app.state.ultrawiki = None
app.state.mission_tool_approvals = self._mission_tool_approvals
# Board aggregator (personal-mastery dashboard) — the aggregator is
@@ -2055,6 +2064,18 @@ class WebServer:
)
_boot_mark("wiki_watcher")
+ # UltraWiki (semantic memory mode): construct the service handle ALWAYS
+ # (cheap ctor — in-app activation from a disabled state must work);
+ # the store + staged pipeline only start while [ultrawiki].enabled is
+ # true, and both live off the boot critical path (AP-26).
+ try:
+ await self._init_ultrawiki()
+ except Exception as exc: # noqa: BLE001
+ logger.opt(exception=exc).warning(
+ "UltraWiki init failed — /api/ultrawiki answers 503"
+ )
+ _boot_mark("ultrawiki")
+
# Voice-session recorder + store for the transcription view.
# Sub-setup: runs sync (SQLite-WAL, no async loop needed), but is
# run in start() so the EventBus is guaranteed to be alive.
@@ -2612,6 +2633,26 @@ class WebServer:
logger.opt(exception=True).warning("wiki auto-backfill pass failed")
await asyncio.sleep(interval_s)
+ async def _init_ultrawiki(self) -> None:
+ """UltraWiki (semantic memory mode): wire the service handle.
+
+ The constructor is deliberately cheap (no I/O, no heavy import), so it
+ ALWAYS runs — the REST surface must be able to activate the mode from
+ a disabled state in-app. The store and the staged pipeline start only
+ while ``cfg.ultrawiki.enabled`` is true; a later in-app enable reaches
+ ``ensure_started()`` again through the routes (AP-26: nothing here
+ touches the boot-critical or voice path).
+ """
+ from jarvis.ultrawiki.service import UltraWikiService
+
+ service = UltraWikiService(self.cfg, bus=self.bus)
+ self.app.state.ultrawiki = service
+ if bool(getattr(getattr(self.cfg, "ultrawiki", None), "enabled", False)):
+ await service.ensure_started()
+ logger.info("ultrawiki: service started (mode enabled)")
+ else:
+ logger.info("ultrawiki: service constructed (mode disabled — dormant)")
+
def _init_wiki_boot_index(self, *, background: bool = False) -> None:
"""Rebuild the derived FTS view against the active vault.
@@ -3015,6 +3056,18 @@ class WebServer:
backfill_task.cancel()
self._wiki_backfill_task = None
+ # UltraWiki: the service owns the ordering internally — cancel the
+ # pipeline + every sync task (cancel, then wait_for(2 s) each), THEN
+ # close its store. Runs before the store-dependent closes below so no
+ # loop ever ticks against a closed connection.
+ ultrawiki_service = getattr(self.app.state, "ultrawiki", None)
+ if ultrawiki_service is not None:
+ try:
+ await ultrawiki_service.shutdown()
+ except Exception as exc: # noqa: BLE001 — shutdown best-effort
+ logger.opt(exception=exc).debug("UltraWiki shutdown failed: {}", exc)
+ self.app.state.ultrawiki = 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/jarvis/ui/web/ultrawiki_routes.py b/jarvis/ui/web/ultrawiki_routes.py
new file mode 100644
index 0000000000..9155971986
--- /dev/null
+++ b/jarvis/ui/web/ultrawiki_routes.py
@@ -0,0 +1,850 @@
+"""UltraWiki REST surface — status, activation, providers, sources, sync jobs,
+areas, and hybrid search (CLI-first contract).
+
+Every handler function name doubles as the ``jarvis api ultrawiki <op>`` CLI
+command name, so handlers are named like commands. The routes are a thin shell
+over :class:`jarvis.ultrawiki.service.UltraWikiService` held on
+``app.state.ultrawiki`` (wired in ``WebServer.start()``; ``None`` while the app
+is still starting or when init failed — routes then answer 503 honestly).
+
+Mode discipline: ``GET /status`` ALWAYS answers, even while the mode is off —
+it is the honesty surface. Search answers 409 (not 503) while the mode switch
+is off, because the app itself is healthy; the normal wiki is the one
+answering. Heavy modules (store, embeddings, search) are imported lazily
+inside the handlers (AP-26) — importing this module stays boot-cheap.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import dataclasses
+import logging
+import re
+import time
+from typing import Any
+
+from fastapi import APIRouter, HTTPException, Query, Request
+from pydantic import BaseModel, Field
+
+log = logging.getLogger(__name__)
+
+router = APIRouter(prefix="/api/ultrawiki", tags=["ultrawiki"])
+
+_MODE_OFF_DETAIL = "UltraWiki mode is off — the normal wiki answers today."
+
+#: The flat ``[ultrawiki]`` slot keys the settings surface may change.
+_SLOT_KEYS = (
+ "db_backend",
+ "embedding_provider",
+ "embedding_model",
+ "distill_provider",
+ "distill_model",
+ "rerank_provider",
+)
+
+_SLUG_RE = re.compile(r"[^a-z0-9]+")
+
+__all__ = ["router"]
+
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+
+def _config(request: Request) -> Any:
+ return getattr(request.app.state, "config", None)
+
+
+def _uw_cfg(request: Request) -> Any:
+ return getattr(_config(request), "ultrawiki", None)
+
+
+def _service(request: Request) -> Any:
+ """The UltraWikiService from app.state, or an honest 503 while unwired."""
+ service = getattr(request.app.state, "ultrawiki", None)
+ if service is None:
+ raise HTTPException(
+ status_code=503,
+ detail=(
+ "the UltraWiki service is not wired yet — the app is still "
+ "starting, or its init failed (check the logs) — retry in a "
+ "moment"
+ ),
+ )
+ return service
+
+
+def _require_active(request: Request) -> Any:
+ """The service, but 409 (not 503) while the mode switch is off.
+
+ 409 because nothing is broken: the app deliberately answers through the
+ normal wiki until UltraWiki mode is activated.
+ """
+ service = _service(request)
+ if not bool(getattr(_uw_cfg(request), "enabled", False)):
+ raise HTTPException(status_code=409, detail=_MODE_OFF_DETAIL)
+ return service
+
+
+async def _store_of(service: Any) -> Any:
+ """The service's opened store (503 when it could not open).
+
+ The service facade does not yet expose a public store accessor, so the
+ area/delete routes reach it through the private attribute after
+ ``ensure_started()`` — a documented seam, not an invitation.
+ """
+ await service.ensure_started()
+ store = getattr(service, "_store", None)
+ if store is None:
+ raise HTTPException(
+ status_code=503,
+ detail="the UltraWiki store did not open — check the logs",
+ )
+ return store
+
+
+def _slugify(name: str) -> str:
+ return _SLUG_RE.sub("-", name.lower()).strip("-") or "area"
+
+
+def _persist_slots(values: dict[str, str]) -> tuple[bool, str]:
+ """Persist ``[ultrawiki]`` slot keys FIRST (AP-7 atomic writer).
+
+ Best-effort like the wiki-provider route: a read-only/locked TOML must not
+ break the live apply — the caller reports ``persisted`` honestly instead.
+ """
+ if not values:
+ return True, ""
+ try:
+ from jarvis.core import config_writer # noqa: PLC0415 — lazy (AP-26)
+ from jarvis.core.config import resolve_config_path # noqa: PLC0415
+
+ path = resolve_config_path()
+ for key, value in values.items():
+ config_writer.set_ultrawiki_slot(key, value, path=path)
+ except Exception as exc: # noqa: BLE001 — persist failure degrades, never 500s
+ log.warning("ultrawiki slot persist failed (live apply still runs): %s", exc)
+ return False, f"{type(exc).__name__}: {exc}"
+ return True, ""
+
+
+def _persist_enabled(enabled: bool) -> tuple[bool, str]:
+ """Persist the ``[ultrawiki] enabled`` mode switch FIRST (best-effort)."""
+ try:
+ from jarvis.core import config_writer # noqa: PLC0415 — lazy (AP-26)
+ from jarvis.core.config import resolve_config_path # noqa: PLC0415
+
+ config_writer.set_ultrawiki_enabled(enabled, path=resolve_config_path())
+ except Exception as exc: # noqa: BLE001 — persist failure degrades, never 500s
+ log.warning("ultrawiki enabled persist failed (live apply still runs): %s", exc)
+ return False, f"{type(exc).__name__}: {exc}"
+ return True, ""
+
+
+def _apply_live(request: Request, values: dict[str, str], *, enabled: bool | None = None) -> None:
+ """Mirror persisted values into the in-memory config (live apply)."""
+ uw = _uw_cfg(request)
+ if uw is None:
+ return
+ for key, value in values.items():
+ try:
+ setattr(uw, key, value)
+ except Exception as exc: # noqa: BLE001 — a frozen model is not an error
+ log.debug("in-memory ultrawiki.%s update skipped: %s", key, exc)
+ if enabled is not None:
+ try:
+ uw.enabled = enabled
+ except Exception as exc: # noqa: BLE001 — a frozen model is not an error
+ log.debug("in-memory ultrawiki.enabled update skipped: %s", exc)
+
+
+def _search_legs(cfg: Any) -> dict[str, Any]:
+ """Honest per-leg availability report (keyword / vector / rerank)."""
+ try:
+ from jarvis.ultrawiki import search as search_mod # noqa: PLC0415 — lazy
+
+ return search_mod.search_status(cfg)
+ except Exception as exc: # noqa: BLE001 — status must never 500
+ return {"error": f"search-leg probe failed ({type(exc).__name__})"}
+
+
+# ---------------------------------------------------------------------------
+# Status + providers
+# ---------------------------------------------------------------------------
+
+
[email protected]("/status", summary="UltraWiki mode status")
+async def get_status(request: Request) -> dict[str, Any]:
+ """Honest capability, backlog, and source report — answers even when the mode is off."""
+ cfg = _config(request)
+ uw = getattr(cfg, "ultrawiki", None)
+ enabled = bool(getattr(uw, "enabled", False))
+ configured_backend = str(getattr(uw, "db_backend", "sqlite") or "sqlite")
+ service = getattr(request.app.state, "ultrawiki", None)
+ if service is None:
+ return {
+ "enabled": enabled,
+ "started": False,
+ "db_backend": configured_backend,
+ "backend_in_use": "",
+ "slots": {},
+ "counts": {},
+ "pipeline": {"running": False, "processed": {}},
+ "sources": [],
+ "jobs": [],
+ "search_legs": _search_legs(cfg),
+ "degradations": [
+ "the UltraWiki service is not wired — the app is still "
+ "starting or its init failed"
+ ],
+ }
+ data = await service.status()
+ backend = dict(data.get("backend") or {})
+ slots = dict(data.get("slots") or {})
+ started = bool(data.get("started"))
+ slots["storage"] = {
+ "configured": backend.get("configured", configured_backend),
+ "in_use": backend.get("in_use", ""),
+ "ready": started,
+ "reason": "" if started else "the store has not been opened yet",
+ "vector": data.get("vector", {}),
+ }
+ return {
+ "enabled": bool(data.get("enabled", enabled)),
+ "started": started,
+ "db_backend": str(backend.get("configured") or configured_backend),
+ "backend_in_use": str(backend.get("in_use") or ""),
+ "slots": slots,
+ "counts": data.get("counts", {}),
+ "pipeline": data.get("pipeline", {}),
+ "sources": data.get("sources", []),
+ "jobs": data.get("jobs", []),
+ "search_legs": _search_legs(cfg),
+ "degradations": data.get("degradations", []),
+ }
+
+
[email protected]("/providers", summary="UltraWiki provider options per slot")
+async def list_providers(request: Request) -> dict[str, Any]:
+ """Option cards for the embedding, rerank, and storage slots (readiness-probed)."""
+ cfg = _config(request)
+
+ def _probe() -> dict[str, Any]:
+ # Credential probes walk keyring/env/.env — keep them off the loop.
+ from jarvis.ultrawiki import embeddings as embeddings_mod # noqa: PLC0415
+ from jarvis.ultrawiki import rerank as rerank_mod # noqa: PLC0415
+
+ embedding = embeddings_mod.available_backends(cfg)
+ rerank_rows = rerank_mod.available_rerankers(cfg)
+ try:
+ from jarvis.core.config import get_secret # noqa: PLC0415 — lazy
+
+ secret_present = bool(get_secret("ultrawiki_db_url"))
+ except Exception: # noqa: BLE001 — a broken keyring reports absent, never 500s
+ secret_present = False
+ return {
+ "embedding": embedding,
+ "rerank": rerank_rows,
+ "db_backends": [
+ {
+ "name": "sqlite",
+ "ready": True,
+ "reason": "",
+ "detail": (
+ "Local file under the Jarvis data directory — zero "
+ "setup, works offline on every OS."
+ ),
+ },
+ {
+ "name": "postgres",
+ "ready": secret_present,
+ "secret_present": secret_present,
+ "reason": (
+ ""
+ if secret_present
+ else (
+ "no 'ultrawiki_db_url' connection string is saved "
+ "— add it in the API-Keys view first"
+ )
+ ),
+ "detail": (
+ "PostgreSQL via connection string (own server, "
+ "Supabase, Neon, RDS, ...) for multi-device access."
+ ),
+ },
+ ],
+ }
+
+ return await asyncio.to_thread(_probe)
+
+
+# ---------------------------------------------------------------------------
+# Activation / deactivation / settings
+# ---------------------------------------------------------------------------
+
+
+class ActivateBody(BaseModel):
+ """Activation payload — the deliberate one-time capability-slot choices."""
+
+ db_backend: str = "" # "" keeps the configured value ("sqlite" default)
+ embedding_provider: str = Field(min_length=1)
+ embedding_model: str = ""
+ distill_provider: str = ""
+ distill_model: str = ""
+ rerank_provider: str = ""
+ areas: list[str] = Field(default_factory=list)
+
+
+ "/activate",
+ summary="Activate UltraWiki mode",
+ openapi_extra={"x-jarvis-dangerous": True},
+)
+async def activate_mode(body: ActivateBody, request: Request) -> dict[str, Any]:
+ """Turn UltraWiki mode on: persist the slot choices, then register the
+ default sources (consent pending — nothing is pulled)."""
+ service = _service(request)
+ cfg = _config(request)
+ from jarvis.ultrawiki import embeddings as embeddings_mod # noqa: PLC0415
+
+ provider = body.embedding_provider.strip()
+ rows = await asyncio.to_thread(embeddings_mod.available_backends, cfg)
+ row = next((r for r in rows if r.get("name") == provider), None)
+ if row is None:
+ raise HTTPException(
+ status_code=400,
+ detail=(
+ f"unknown embedding provider {provider!r} "
+ f"(available: {sorted(str(r.get('name')) for r in rows)})"
+ ),
+ )
+ if not row.get("ready"):
+ raise HTTPException(
+ status_code=409,
+ detail=(
+ f"embedding provider {provider!r} is not ready: "
+ f"{row.get('reason') or 'unknown reason'}"
+ ),
+ )
+ db_backend = body.db_backend.strip().lower()
+ if db_backend and db_backend not in ("sqlite", "postgres"):
+ raise HTTPException(
+ status_code=400, detail="db_backend must be 'sqlite' or 'postgres'"
+ )
+ rerank_provider = body.rerank_provider.strip()
+ if rerank_provider:
+ from jarvis.ultrawiki import rerank as rerank_mod # noqa: PLC0415
+
+ if rerank_provider not in rerank_mod.RERANK_BACKENDS:
+ raise HTTPException(
+ status_code=400,
+ detail=(
+ f"unknown rerank provider {rerank_provider!r} "
+ f"(available: {sorted(rerank_mod.RERANK_BACKENDS)})"
+ ),
+ )
+
+ values: dict[str, str] = {"embedding_provider": provider}
+ if db_backend:
+ values["db_backend"] = db_backend
+ for key in ("embedding_model", "distill_provider", "distill_model"):
+ value = str(getattr(body, key) or "").strip()
+ if value:
+ values[key] = value
+ if rerank_provider:
+ values["rerank_provider"] = rerank_provider
+
+ # Persist FIRST (the disk is the source of truth), then live-apply — the
+ # same discipline as PUT /api/settings/wiki-provider.
+ slots_persisted, slots_error = _persist_slots(values)
+ enabled_persisted, enabled_error = _persist_enabled(True)
+ _apply_live(request, values, enabled=True)
+
+ result = await service.activate({"areas": list(body.areas or [])})
+ response: dict[str, Any] = {
+ "ok": True,
+ "enabled": True,
+ "persisted": slots_persisted and enabled_persisted,
+ **result,
+ "next_steps": (
+ "UltraWiki is on, but nothing has been read yet: open the "
+ "sources list, approve each source you want ingested, then start "
+ "a sync. Keyword search works seconds after the first sync; "
+ "semantic answers grow as the background pipeline embeds and "
+ "distills."
+ ),
+ }
+ persist_error = slots_error or enabled_error
+ if persist_error:
+ response["persist_error"] = persist_error
+ return response
+
+
+ "/deactivate",
+ summary="Deactivate UltraWiki mode",
+ openapi_extra={"x-jarvis-dangerous": True},
+)
+async def deactivate_mode(request: Request) -> dict[str, Any]:
+ """Turn UltraWiki mode off (non-destructive) — the normal wiki answers again."""
+ service = _service(request)
+ persisted, persist_error = _persist_enabled(False)
+ _apply_live(request, {}, enabled=False)
+ try:
+ # Stops the pipeline + sync tasks and closes the store; the data stays
+ # on disk untouched. A later activation reopens it where it left off.
+ await service.shutdown()
+ except Exception as exc: # noqa: BLE001 — teardown best-effort
+ log.warning("UltraWiki shutdown during deactivate failed: %s", exc)
+ response: dict[str, Any] = {
+ "ok": True,
+ "enabled": False,
+ "persisted": persisted,
+ "non_destructive": True,
+ "detail": (
+ "UltraWiki mode is off. Nothing was deleted — every ingested "
+ "item, embedding, and source stays on disk, and re-activating "
+ "picks up exactly where you left off. The normal wiki answers "
+ "again."
+ ),
+ }
+ if persist_error:
+ response["persist_error"] = persist_error
+ return response
+
+
+class UpdateSettingsBody(BaseModel):
+ """Slot changes; an embedding change needs confirm_reembed once vectors exist."""
+
+ db_backend: str | None = None
+ embedding_provider: str | None = None
+ embedding_model: str | None = None
+ distill_provider: str | None = None
+ distill_model: str | None = None
+ rerank_provider: str | None = None
+ confirm_reembed: bool = False
+
+
+ "/settings",
+ summary="Change UltraWiki slot settings",
+ openapi_extra={"x-jarvis-dangerous": True},
+)
+async def update_settings(body: UpdateSettingsBody, request: Request) -> dict[str, Any]:
+ """Change capability-slot settings; an embedding change drops and
+ re-embeds the corpus after explicit confirmation."""
+ service = _service(request)
+ uw = _uw_cfg(request)
+ changes: dict[str, str] = {}
+ for key in _SLOT_KEYS:
+ value = getattr(body, key)
+ if value is None:
+ continue
+ value = str(value).strip()
+ if value != str(getattr(uw, key, "") or "").strip():
+ changes[key] = value
+ if not changes:
+ return {"ok": True, "changed": [], "persisted": True, "reembed_started": False}
+
+ if "db_backend" in changes and changes["db_backend"] not in ("sqlite", "postgres"):
+ raise HTTPException(
+ status_code=400, detail="db_backend must be 'sqlite' or 'postgres'"
+ )
+ if changes.get("embedding_provider"):
+ from jarvis.ultrawiki import embeddings as embeddings_mod # noqa: PLC0415
+
+ if changes["embedding_provider"] not in embeddings_mod.EMBEDDING_BACKENDS:
+ raise HTTPException(
+ status_code=400,
+ detail=(
+ f"unknown embedding provider {changes['embedding_provider']!r} "
+ f"(available: {sorted(embeddings_mod.EMBEDDING_BACKENDS)})"
+ ),
+ )
+ if changes.get("rerank_provider"):
+ from jarvis.ultrawiki import rerank as rerank_mod # noqa: PLC0415
+
+ if changes["rerank_provider"] not in rerank_mod.RERANK_BACKENDS:
+ raise HTTPException(
+ status_code=400,
+ detail=(
+ f"unknown rerank provider {changes['rerank_provider']!r} "
+ f"(available: {sorted(rerank_mod.RERANK_BACKENDS)})"
+ ),
+ )
+
+ embedding_change = any(
+ key in changes for key in ("embedding_provider", "embedding_model")
+ )
+ vector_items = 0
+ if embedding_change:
+ store = await _store_of(service)
+ counts = await store.counts()
+ vector_items = int(counts.embedded) + int(counts.distilled)
+ if vector_items and not body.confirm_reembed:
+ raise HTTPException(
+ status_code=409,
+ detail={
+ "message": (
+ "changing the embedding provider or model switches "
+ f"vector spaces: the {vector_items} already-embedded "
+ "items must be re-embedded from scratch. Repeat the "
+ "request with confirm_reembed=true to drop the "
+ "existing vectors and re-embed in the background — "
+ "keyword search keeps working meanwhile."
+ ),
+ "vector_items": vector_items,
+ },
+ )
+
+ persisted, persist_error = _persist_slots(changes)
+ _apply_live(request, changes)
+ reembed_started = False
+ if embedding_change:
+ store = await _store_of(service)
+ # Drops uw_vec + uw_embeddings, clears the model/dim pin, and resets
+ # embedded/distilled items to keyword_indexed — the running pipeline
+ # re-embeds them in the background with the new slot.
+ await store.reset_vectors()
+ reembed_started = vector_items > 0
+ response: dict[str, Any] = {
+ "ok": True,
+ "changed": sorted(changes),
+ "persisted": persisted,
+ "reembed_started": reembed_started,
+ }
+ if persist_error:
+ response["persist_error"] = persist_error
+ return response
+
+
+ "/test/{slot}",
+ summary="Test one UltraWiki capability slot",
+ openapi_extra={"x-jarvis-dangerous": True},
+)
+async def test_slot(slot: str, request: Request) -> dict[str, Any]:
+ """Run one real minimal call against a slot (embedding, distill, rerank, or storage)."""
+ cfg = _config(request)
+ started = time.perf_counter()
+
+ def _result(ok: bool, detail: str) -> dict[str, Any]:
+ return {
+ "ok": ok,
+ "detail": detail,
+ "latency_ms": round((time.perf_counter() - started) * 1000.0, 1),
+ }
+
+ if slot == "embedding":
+ provider = str(getattr(_uw_cfg(request), "embedding_provider", "") or "").strip()
+ if not provider:
+ return _result(False, "no embedding provider is configured")
+ from jarvis.ultrawiki import embeddings as embeddings_mod # noqa: PLC0415
+
+ factory = embeddings_mod.EMBEDDING_BACKENDS.get(provider)
+ if factory is None:
+ return _result(False, f"unknown embedding provider {provider!r}")
+ model = str(getattr(_uw_cfg(request), "embedding_model", "") or "").strip()
+ model = model or embeddings_mod.DEFAULT_MODELS.get(provider, "")
+ try:
+ vectors = await factory(cfg).embed(["Jarvis connectivity test"], model=model)
+ except Exception as exc: # noqa: BLE001 — a test reports, never 500s
+ return _result(False, f"{type(exc).__name__}: {exc}")
+ if not vectors or not vectors[0]:
+ return _result(False, f"{provider} returned no vector")
+ return _result(
+ True,
+ f"embedded one test text with {provider}/{model} "
+ f"({len(vectors[0])} dimensions)",
+ )
+
+ if slot == "distill":
+ from jarvis.ultrawiki.distill import distill_text # noqa: PLC0415
+
+ try:
+ result = await distill_text(
+ cfg,
+ title="Connectivity test",
+ body="The user is checking that distillation works end to end.",
+ source_kind="test",
+ )
+ except Exception as exc: # noqa: BLE001 — a test reports, never 500s
+ return _result(False, f"{type(exc).__name__}: {exc}")
+ summary = str(getattr(result, "summary", "") or "").strip()
+ return _result(True, f"distilled a test snippet ({summary[:80] or 'empty summary'})")
+
+ if slot == "rerank":
+ from jarvis.ultrawiki import rerank as rerank_mod # noqa: PLC0415
+
+ reranker = rerank_mod.resolve_reranker(cfg)
+ if reranker is None:
+ return _result(
+ False,
+ "rerank is not configured or not ready — the fusion order "
+ "stands (optional stage)",
+ )
+ try:
+ await reranker.rerank(
+ "test query",
+ ["first test document", "second test document"],
+ top_k=1,
+ )
+ except Exception as exc: # noqa: BLE001 — a test reports, never 500s
+ return _result(False, f"{type(exc).__name__}: {exc}")
+ return _result(True, f"reranked two test documents with {reranker.name}")
+
+ if slot == "storage":
+ service = _service(request)
+ backend = str(getattr(_uw_cfg(request), "db_backend", "sqlite") or "sqlite")
+ if backend.strip().lower() == "postgres":
+ try:
+ from jarvis.core.config import get_secret # noqa: PLC0415 — lazy
+
+ conn_str = await asyncio.to_thread(get_secret, "ultrawiki_db_url")
+ except Exception: # noqa: BLE001 — a broken keyring reads as absent
+ conn_str = None
+ if not conn_str:
+ return _result(
+ False,
+ "no 'ultrawiki_db_url' connection string is saved — add "
+ "it in the API-Keys view",
+ )
+ from jarvis.ultrawiki.store import PostgresStore # noqa: PLC0415
+
+ ok, reason = await PostgresStore.connect_test(conn_str)
+ return _result(bool(ok), reason or "connected to Postgres")
+ try:
+ store = await _store_of(service)
+ vec_ok, vec_reason = await store.vector_status()
+ except HTTPException as exc:
+ return _result(False, str(exc.detail))
+ except Exception as exc: # noqa: BLE001 — a test reports, never 500s
+ return _result(False, f"{type(exc).__name__}: {exc}")
+ vector_note = "vector search ready" if vec_ok else f"vector search off ({vec_reason})"
+ return _result(True, f"SQLite store open; {vector_note}")
+
+ raise HTTPException(
+ status_code=404,
+ detail="unknown slot — one of: embedding, distill, rerank, storage",
+ )
+
+
+# ---------------------------------------------------------------------------
+# Sources
+# ---------------------------------------------------------------------------
+
+
[email protected]("/sources", summary="List UltraWiki sources")
+async def list_sources(request: Request) -> dict[str, Any]:
+ """Configured sources with consent, per-stage counts, and sync state."""
+ service = _service(request)
+ status = await service.status()
+ sources = status.get("sources", [])
+ return {"sources": sources, "total": len(sources)}
+
+
+class CreateSourceBody(BaseModel):
+ """New source registration — consent starts PENDING; nothing is pulled."""
+
+ connector: str = Field(min_length=1)
+ label: str = Field(min_length=1)
+ config: dict[str, Any] = Field(default_factory=dict)
+ areas: list[str] = Field(default_factory=list)
+
+
[email protected]("/sources", status_code=201, summary="Register an UltraWiki source")
+async def create_source(body: CreateSourceBody, request: Request) -> dict[str, Any]:
+ """Register a new source with consent PENDING — approval is a separate explicit step."""
+ service = _service(request)
+ try:
+ source = await service.add_source(
+ body.connector.strip(),
+ body.label.strip(),
+ config=dict(body.config or {}),
+ area_ids=list(body.areas or []),
+ )
+ except ValueError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+ return source
+
+
+ "/sources/{source_id}/approve",
+ summary="Approve an UltraWiki source",
+ openapi_extra={"x-jarvis-dangerous": True},
+)
+async def approve_source(source_id: str, request: Request) -> dict[str, Any]:
+ """Grant consent for one source — THE gate before any byte is pulled."""
+ service = _service(request)
+ try:
+ return await service.approve_source(source_id)
+ except ValueError as exc:
+ raise HTTPException(status_code=404, detail=str(exc)) from exc
+
+
[email protected]("/sources/{source_id}/revoke", summary="Revoke an UltraWiki source")
+async def revoke_source(source_id: str, request: Request) -> dict[str, Any]:
+ """Revoke consent for one source; future syncs refuse until re-approved."""
+ service = _service(request)
+ try:
+ return await service.revoke_source(source_id)
+ except ValueError as exc:
+ raise HTTPException(status_code=404, detail=str(exc)) from exc
+
+
[email protected]("/sources/{source_id}", summary="Delete an UltraWiki source")
+async def delete_source(
+ source_id: str,
+ request: Request,
+ purge: bool = Query(
+ default=False,
+ description="Also delete the source's ingested items and derived data",
+ ),
+) -> dict[str, Any]:
+ """Remove a source registration; purge=true also deletes its ingested data."""
+ service = _service(request)
+ store = await _store_of(service)
+ if await store.get_source(source_id) is None:
+ raise HTTPException(status_code=404, detail=f"unknown source {source_id!r}")
+ await store.delete_source(source_id, purge=bool(purge))
+ return {"ok": True, "deleted": source_id, "purged": bool(purge)}
+
+
+ "/sources/{source_id}/sync",
+ status_code=201,
+ summary="Start a sync for one UltraWiki source",
+ openapi_extra={"x-jarvis-dangerous": True},
+)
+async def start_sync(source_id: str, request: Request) -> dict[str, Any]:
+ """Start a backfill/incremental sync job for one approved source (201 with the job id)."""
+ service = _service(request)
+ try:
+ job_id = await service.start_sync(source_id)
+ except ValueError as exc:
+ message = str(exc)
+ status_code = 404 if message.startswith("unknown source") else 409
+ raise HTTPException(status_code=status_code, detail=message) from exc
+ return {"job_id": job_id, "status": "queued", "source_id": source_id}
+
+
[email protected]("/bridge/candidates", summary="List plugin-bridge candidates")
+async def list_bridge_candidates() -> dict[str, Any]:
+ """Connected Jarvis integrations (plugins, MCP servers) that could become sources."""
+ from jarvis.ultrawiki.connectors import plugin_bridge # noqa: PLC0415 — lazy
+
+ candidates = plugin_bridge.list_candidates()
+ return {"candidates": candidates, "total": len(candidates)}
+
+
+# ---------------------------------------------------------------------------
+# Sync jobs
+# ---------------------------------------------------------------------------
+
+
[email protected]("/jobs", summary="List UltraWiki sync jobs")
+async def list_jobs(
+ request: Request, limit: int = Query(default=20, ge=1, le=100)
+) -> dict[str, Any]:
+ """Newest-first sync-job snapshots (active and recent terminal jobs)."""
+ service = _service(request)
+ jobs = service.list_jobs(limit)
+ return {"jobs": jobs, "total": len(jobs)}
+
+
[email protected]("/jobs/{job_id}", summary="Inspect one UltraWiki sync job")
+async def get_job(job_id: str, request: Request) -> dict[str, Any]:
+ """One sync job's snapshot (404 when unknown)."""
+ snapshot = _service(request).job_snapshot(job_id)
+ if snapshot is None:
+ raise HTTPException(status_code=404, detail="unknown job id")
+ return snapshot
+
+
+ "/jobs/{job_id}/cancel",
+ summary="Cancel one UltraWiki sync job",
+ openapi_extra={"x-jarvis-dangerous": True},
+)
+async def cancel_job(job_id: str, request: Request) -> dict[str, Any]:
+ """Cancel one active sync job (404 unknown, 409 already finished)."""
+ service = _service(request)
+ snapshot = service.job_snapshot(job_id)
+ if snapshot is None:
+ raise HTTPException(status_code=404, detail="unknown job id")
+ from jarvis.ultrawiki.service import JOB_TERMINAL_STATUSES # noqa: PLC0415
+
+ if snapshot.get("status") in JOB_TERMINAL_STATUSES:
+ raise HTTPException(
+ status_code=409,
+ detail=f"job is already terminal ({snapshot.get('status')})",
+ )
+ if not service.cancel_job(job_id):
+ raise HTTPException(
+ status_code=409,
+ detail="job has no live task (it is about to start or end)",
+ )
+ return {"job_id": job_id, "cancel_requested": True}
+
+
+# ---------------------------------------------------------------------------
+# Areas
+# ---------------------------------------------------------------------------
+
+
[email protected]("/areas", summary="List UltraWiki areas")
+async def list_areas(request: Request) -> dict[str, Any]:
+ """Named source bundles (areas) used to scope sources and search."""
+ store = await _store_of(_service(request))
+ areas = await store.list_areas()
+ return {"areas": areas, "total": len(areas)}
+
+
+class CreateAreaBody(BaseModel):
+ """New area; the id is derived from the name unless given explicitly."""
+
+ name: str = Field(min_length=1)
+ id: str = ""
+
+
[email protected]("/areas", status_code=201, summary="Create an UltraWiki area")
+async def create_area(body: CreateAreaBody, request: Request) -> dict[str, Any]:
+ """Create (or rename) an area — an idempotent upsert on the area id."""
+ store = await _store_of(_service(request))
+ name = body.name.strip()
+ area_id = body.id.strip() or _slugify(name)
+ await store.upsert_area(area_id, name)
+ return {"id": area_id, "name": name}
+
+
+# ---------------------------------------------------------------------------
+# Search
+# ---------------------------------------------------------------------------
+
+
[email protected]("/search", summary="Hybrid search over the UltraWiki store")
+async def search_ultrawiki(
+ request: Request,
+ q: str = Query(..., min_length=1, description="The search query"),
+ k: int = Query(default=10, ge=1, le=50),
+ area: str | None = Query(default=None, description="Optional area id filter"),
+) -> dict[str, Any]:
+ """Fused keyword + vector search, best hits first, each with its citation permalink."""
+ service = _require_active(request)
+ try:
+ results = await service.search(q, k=k, area_id=area)
+ except AttributeError:
+ # The service delegates to jarvis.ultrawiki.search.search(); until
+ # that wrapper lands this route calls the hybrid entry point directly.
+ from jarvis.ultrawiki import search as search_mod # noqa: PLC0415
+
+ store = await _store_of(service)
+ results = await search_mod.hybrid_search(
+ store, _config(request), q, k=k, area_id=area
+ )
+ rows = [
+ dataclasses.asdict(hit) if dataclasses.is_dataclass(hit) else dict(hit)
+ for hit in results
+ ]
+ return {"query": q, "results": rows, "total": len(rows)}
diff --git a/jarvis/ultrawiki/pipeline.py b/jarvis/ultrawiki/pipeline.py
new file mode 100644
index 0000000000..64e5680c2f
--- /dev/null
+++ b/jarvis/ultrawiki/pipeline.py
@@ -0,0 +1,443 @@
+"""UltraWiki staged pipeline worker — one loop advancing items through STATE_ORDER.
+
+Design doc 02: ingestion is a state machine in the database, never a function
+chain. Each pass claims a batch per stage, performs exactly ONE transition per
+item, and commits through the store — a crash or deploy mid-run restarts to an
+identical end state. Stages, in ladder order:
+
+- ``captured -> keyword_indexed`` (instant, no model): the FTS upsert happens
+ in the SAME store transaction as the state transition.
+- ``keyword_indexed -> embedded`` (async, cheap): the RAW document (title +
+ body, trimmed) is stored and embedded with the CONFIGURED embedding backend.
+ An unconfigured or not-ready slot means the stage claims NO work — the
+ backlog stays honest and keyword search keeps working (D-3: embeddings have
+ no cross-family fallback).
+- ``embedded -> distilled`` (async, the expensive stage): the distillation
+ cache is consulted first on ``(content_hash, PROMPT_VERSION, model)``; on a
+ miss the injected ``distill_fn`` runs, the SUMMARY document is stored with
+ its ``distill_json``, the summary text is embedded too, and the result is
+ cached so identical input is never paid for twice.
+
+Error discipline: a per-item failure goes through ``store.mark_retry`` (60s *
+4^n backoff, dead-letter after 5 attempts) and the loop NEVER dies on one item
+— it logs and continues. ``asyncio.CancelledError`` is always re-raised so the
+service's cancel-then-wait shutdown stays honest.
+
+This module imports only the stdlib and the dependency-free types module at
+import time (AP-26); heavier modules (embedding defaults, the distill prompt
+contract) are imported lazily inside the stages.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import logging
+import time
+from collections.abc import Awaitable, Callable
+from datetime import datetime
+from typing import Any
+
+from jarvis.ultrawiki.types import DocType, ItemState
+
+log = logging.getLogger(__name__)
+
+__all__ = [
+ "KEYWORD_BATCH",
+ "EMBED_BATCH",
+ "DISTILL_BATCH",
+ "IDLE_SLEEP_S",
+ "BUSY_SLEEP_S",
+ "PipelineWorker",
+]
+
+#: Per-pass claim sizes (design doc 02 batching).
+KEYWORD_BATCH = 200
+EMBED_BATCH = 32
+DISTILL_BATCH = 4
+
+#: Loop pacing: quick follow-up while there is work, gentle poll when idle.
+IDLE_SLEEP_S = 2.0
+BUSY_SLEEP_S = 0.1
+
+#: The embedding ``ready()`` probe may hit the network (Ollama); cache its
+#: verdict briefly so an idle loop does not hammer a dead endpoint.
+_READY_PROBE_TTL_S = 30.0
+
+#: Zero-arg factory returning the CONFIGURED embedding backend (an object
+#: implementing ``jarvis.ultrawiki.types.EmbeddingBackend``) or ``None`` when
+#: the slot is unconfigured — the factory owns the config decision.
+EmbeddingBackendFactory = Callable[[], Any]
+
+#: ``distill_fn(cfg, *, title, body, source_kind) -> DistillResult-like``.
+DistillFn = Callable[..., Awaitable[Any]]
+
+
+def _summary_text(
+ question: str, summary: str, resolution: str, entities: list[str]
+) -> str:
+ """Compose the embed-ready text of a SUMMARY document from its fields."""
+ parts: list[str] = []
+ if question:
+ parts.append(question)
+ if summary:
+ parts.append(summary)
+ if resolution:
+ parts.append(f"Resolution: {resolution}")
+ if entities:
+ parts.append("Entities: " + ", ".join(entities))
+ return "\n".join(parts)
+
+
+def _string_field(mapping: dict[str, Any], key: str) -> str:
+ return str(mapping.get(key) or "").strip()
+
+
+def _list_field(mapping: dict[str, Any], key: str) -> list[str]:
+ value = mapping.get(key)
+ if isinstance(value, str):
+ return [value.strip()] if value.strip() else []
+ if isinstance(value, (list, tuple)):
+ return [str(entry).strip() for entry in value if str(entry).strip()]
+ return []
+
+
+class PipelineWorker:
+ """Advance items through the staged state machine, one transition each.
+
+ ``embedding_backend_factory`` returns the configured backend or ``None``
+ (unconfigured slot). ``distill_fn`` is the distillation entry point
+ (production: ``jarvis.ultrawiki.distill.distill_text``); it is injected so
+ tests run offline. ``now_fn`` is a test seam feeding the store's
+ retry-eligibility clock; production leaves it ``None`` (real time).
+ """
+
+ def __init__(
+ self,
+ store: Any,
+ cfg: Any,
+ *,
+ embedding_backend_factory: EmbeddingBackendFactory,
+ distill_fn: DistillFn,
+ now_fn: Callable[[], datetime] | None = None,
+ ) -> None:
+ self._store = store
+ self._cfg = cfg
+ self._backend_factory = embedding_backend_factory
+ self._distill_fn = distill_fn
+ self._now_fn = now_fn
+ #: Per-stage processed counters (successful transitions only).
+ self.processed: dict[str, int] = {"keyword": 0, "embed": 0, "distill": 0}
+ self._ready_cache: tuple[float, str, bool, str] | None = None
+ self._last_slot_reason: str | None = None
+ self._source_kind_cache: dict[str, str] = {}
+
+ # -- public surface ------------------------------------------------------
+
+ def processed_counts(self) -> dict[str, int]:
+ """Copy of the per-stage processed counters."""
+ return dict(self.processed)
+
+ async def run(self, cancel_event: asyncio.Event) -> None:
+ """The worker loop: run passes until *cancel_event* is set.
+
+ A failed pass is logged and the loop continues; ``CancelledError``
+ (hard task cancel) is always re-raised.
+ """
+ log.info("UltraWiki pipeline worker started")
+ try:
+ while not cancel_event.is_set():
+ try:
+ attempted = await self.run_once()
+ except asyncio.CancelledError:
+ raise
+ except Exception:
+ log.exception("UltraWiki pipeline pass failed; continuing")
+ attempted = 0
+ delay = BUSY_SLEEP_S if attempted else IDLE_SLEEP_S
+ if cancel_event.is_set():
+ break
+ try:
+ await asyncio.wait_for(cancel_event.wait(), timeout=delay)
+ except TimeoutError:
+ pass
+ except asyncio.CancelledError:
+ log.debug("UltraWiki pipeline worker cancelled")
+ raise
+ finally:
+ log.info("UltraWiki pipeline worker stopped")
+
+ async def run_once(self) -> int:
+ """One full pass over all stages; returns the number of items worked
+ on (successes AND per-item failures — pacing counts attempts)."""
+ attempted = 0
+ attempted += await self._keyword_pass()
+ attempted += await self._embed_pass()
+ attempted += await self._distill_pass()
+ return attempted
+
+ # -- shared helpers ------------------------------------------------------
+
+ def _claim_now(self) -> datetime | None:
+ return self._now_fn() if self._now_fn is not None else None
+
+ async def _retry(self, item: dict[str, Any], stage: str, exc: BaseException) -> None:
+ log.warning(
+ "UltraWiki %s stage failed for item %s (%s): %s",
+ stage,
+ item.get("id"),
+ item.get("external_id"),
+ exc,
+ )
+ try:
+ await self._store.mark_retry(
+ int(item["id"]), f"{stage}: {exc}", now=self._claim_now()
+ )
+ except Exception:
+ log.exception(
+ "UltraWiki: mark_retry failed for item %s", item.get("id")
+ )
+
+ def _note_slot_gap(self, reason: str) -> None:
+ """Log an honest 'stage paused' line once per reason change."""
+ if reason != self._last_slot_reason:
+ self._last_slot_reason = reason
+ log.info("UltraWiki embed/distill stages paused: %s", reason)
+
+ def _embedding_slot(self) -> tuple[Any | None, str, str]:
+ """``(backend, model, reason)`` — backend is ``None`` when the slot is
+ unconfigured, unknown, model-less, or its ``ready()`` probe fails."""
+ try:
+ backend = self._backend_factory()
+ except Exception as exc: # noqa: BLE001 — a broken factory pauses, never kills
+ return None, "", f"embedding backend factory failed ({type(exc).__name__})"
+ if backend is None:
+ return None, "", (
+ "no embedding backend is configured - pick one in the "
+ "UltraWiki settings; keyword search keeps working"
+ )
+ model = str(
+ getattr(getattr(self._cfg, "ultrawiki", None), "embedding_model", "") or ""
+ ).strip()
+ if not model:
+ from jarvis.ultrawiki.embeddings import ( # noqa: PLC0415 — lazy (AP-26)
+ DEFAULT_MODELS,
+ )
+
+ model = DEFAULT_MODELS.get(getattr(backend, "name", ""), "")
+ if not model:
+ return None, "", (
+ f"embedding backend {getattr(backend, 'name', '?')!r} has no "
+ "configured or default model"
+ )
+ ok, reason = self._backend_ready(backend)
+ if not ok:
+ return None, "", reason
+ return backend, model, ""
+
+ def _backend_ready(self, backend: Any) -> tuple[bool, str]:
+ name = str(getattr(backend, "name", ""))
+ now = time.monotonic()
+ cached = self._ready_cache
+ if cached is not None and cached[1] == name and now < cached[0]:
+ return cached[2], cached[3]
+ try:
+ ok, reason = backend.ready()
+ except Exception as exc: # noqa: BLE001 — ready() must never kill the loop
+ ok, reason = False, f"embedding readiness probe failed ({type(exc).__name__})"
+ self._ready_cache = (now + _READY_PROBE_TTL_S, name, bool(ok), reason)
+ return bool(ok), reason
+
+ async def _source_kind(self, source_id: str) -> str:
+ kind = self._source_kind_cache.get(source_id)
+ if kind is not None:
+ return kind
+ try:
+ source = await self._store.get_source(source_id)
+ except Exception: # noqa: BLE001 — a lookup hiccup degrades to 'unknown'
+ source = None
+ kind = str((source or {}).get("connector") or "unknown")
+ self._source_kind_cache[source_id] = kind
+ return kind
+
+ @staticmethod
+ def _raw_text(item: dict[str, Any]) -> str:
+ title = str(item.get("title") or "")
+ body = str(item.get("body_raw") or "")
+ text = f"{title}\n\n{body}".strip()
+ return text or str(item.get("external_id") or "")
+
+ # -- stage passes --------------------------------------------------------
+
+ async def _keyword_pass(self) -> int:
+ """``captured -> keyword_indexed``: FTS upsert + state transition in
+ one store transaction (no model, instant)."""
+ items = await self._store.claim_batch(
+ ItemState.KEYWORD_INDEXED, limit=KEYWORD_BATCH, now=self._claim_now()
+ )
+ for item in items:
+ try:
+ await self._store.mark_stage_done(
+ int(item["id"]),
+ ItemState.KEYWORD_INDEXED,
+ fts_title=str(item.get("title") or ""),
+ fts_body=str(item.get("body_raw") or ""),
+ )
+ self.processed["keyword"] += 1
+ except asyncio.CancelledError:
+ raise
+ except Exception as exc: # noqa: BLE001 — one poisoned item blocks nothing
+ await self._retry(item, "keyword", exc)
+ return len(items)
+
+ async def _embed_pass(self) -> int:
+ """``keyword_indexed -> embedded``: store the RAW document and its
+ vector via the configured backend. An unusable slot claims NO work."""
+ backend, model, reason = self._embedding_slot()
+ if backend is None:
+ self._note_slot_gap(reason)
+ return 0
+ self._last_slot_reason = None
+ items = await self._store.claim_batch(
+ ItemState.EMBEDDED, limit=EMBED_BATCH, now=self._claim_now()
+ )
+ if not items:
+ return 0
+ texts = [self._raw_text(item) for item in items]
+ try:
+ vectors = await backend.embed(texts, model=model)
+ if len(vectors) != len(texts):
+ raise RuntimeError(
+ f"backend returned {len(vectors)} vectors for {len(texts)} texts"
+ )
+ except asyncio.CancelledError:
+ raise
+ except Exception as exc: # noqa: BLE001 — batch failure retries every member
+ for item in items:
+ await self._retry(item, "embed", exc)
+ return len(items)
+ for item, text, vector in zip(items, texts, vectors, strict=True):
+ try:
+ doc_id = await self._store.add_document(
+ int(item["id"]),
+ DocType.RAW,
+ text,
+ content_hash=str(item.get("content_hash") or ""),
+ )
+ await self._store.store_embedding(
+ doc_id, model=model, dim=len(vector), vector=vector
+ )
+ await self._store.mark_stage_done(int(item["id"]), ItemState.EMBEDDED)
+ self.processed["embed"] += 1
+ except asyncio.CancelledError:
+ raise
+ except Exception as exc: # noqa: BLE001 — one poisoned item blocks nothing
+ await self._retry(item, "embed", exc)
+ return len(items)
+
+ async def _distill_pass(self) -> int:
+ """``embedded -> distilled``: cache-first distillation, SUMMARY
+ document + summary embedding, result cached for determinism.
+
+ The stage needs the embedding slot too (the summary is embedded), so
+ an unusable slot claims no distill work either. Items can only reach
+ ``embedded`` while the slot works, so this gate is rarely the limiter.
+ """
+ backend, model, reason = self._embedding_slot()
+ if backend is None:
+ self._note_slot_gap(reason)
+ return 0
+ items = await self._store.claim_batch(
+ ItemState.DISTILLED, limit=DISTILL_BATCH, now=self._claim_now()
+ )
+ if not items:
+ return 0
+ for item in items:
+ try:
+ await self._distill_one(item, backend, model)
+ self.processed["distill"] += 1
+ except asyncio.CancelledError:
+ raise
+ except Exception as exc: # noqa: BLE001 — one poisoned item blocks nothing
+ await self._retry(item, "distill", exc)
+ return len(items)
+
+ def _distill_cache_model(self) -> str:
+ """The ``model`` component of the distill cache key. When no explicit
+ distill model/provider is configured the key-aware chain decides at
+ call time, so the honest deterministic key component is ``auto``."""
+ ultrawiki = getattr(self._cfg, "ultrawiki", None)
+ model = str(getattr(ultrawiki, "distill_model", "") or "").strip()
+ provider = str(getattr(ultrawiki, "distill_provider", "") or "").strip()
+ return model or provider or "auto"
+
+ async def _distill_one(self, item: dict[str, Any], backend: Any, model: str) -> None:
+ from jarvis.ultrawiki.distill import ( # noqa: PLC0415 — lazy (AP-26)
+ distill_cache_key,
+ )
+
+ title = str(item.get("title") or "")
+ body = str(item.get("body_raw") or "")
+ content_hash, prompt_version, cache_model = distill_cache_key(
+ title=title, body=body, model=self._distill_cache_model()
+ )
+
+ fields: dict[str, Any] | None = None
+ raw_json = ""
+ cached = await self._store.distill_cache_get(
+ content_hash, prompt_version, cache_model
+ )
+ if cached is not None:
+ try:
+ parsed = json.loads(cached)
+ except ValueError:
+ parsed = None
+ if isinstance(parsed, dict):
+ fields = parsed
+ raw_json = cached
+
+ fresh = fields is None
+ if fields is None:
+ source_kind = await self._source_kind(str(item.get("source_id") or ""))
+ result = await self._distill_fn(
+ self._cfg, title=title, body=body, source_kind=source_kind
+ )
+ fields = {
+ "question": getattr(result, "question", ""),
+ "summary": getattr(result, "summary", ""),
+ "resolution": getattr(result, "resolution", ""),
+ "entities": list(getattr(result, "entities", []) or []),
+ "refs": list(getattr(result, "refs", []) or []),
+ }
+ raw_json = str(getattr(result, "raw_json", "") or "")
+ if not raw_json:
+ raw_json = json.dumps(
+ fields, ensure_ascii=False, separators=(",", ":")
+ )
+
+ text = _summary_text(
+ _string_field(fields, "question"),
+ _string_field(fields, "summary"),
+ _string_field(fields, "resolution"),
+ _list_field(fields, "entities"),
+ ) or self._raw_text(item)
+
+ doc_id = await self._store.add_document(
+ int(item["id"]),
+ DocType.SUMMARY,
+ text,
+ distill_json=raw_json,
+ distill_version=prompt_version,
+ content_hash=content_hash,
+ )
+ vectors = await backend.embed([text], model=model)
+ if not vectors:
+ raise RuntimeError("backend returned no vector for the summary text")
+ await self._store.store_embedding(
+ doc_id, model=model, dim=len(vectors[0]), vector=vectors[0]
+ )
+ if fresh:
+ await self._store.distill_cache_put(
+ content_hash, prompt_version, cache_model, raw_json
+ )
+ await self._store.mark_stage_done(int(item["id"]), ItemState.DISTILLED)
diff --git a/jarvis/ultrawiki/search.py b/jarvis/ultrawiki/search.py
new file mode 100644
index 0000000000..87900a474b
--- /dev/null
+++ b/jarvis/ultrawiki/search.py
@@ -0,0 +1,345 @@
+"""UltraWiki hybrid search — RRF fusion over the store's legs + optional rerank.
+
+The read path (design doc 03): the keyword leg (FTS/tsvector in the store) and
+the vector leg (query embedding -> ANN in the store) run CONCURRENTLY, their
+ranked lists are fused with Reciprocal Rank Fusion (smoothing constant 60 —
+consensus beats a single strong vote), duplicates merge by item, results are
+capped per source before the final cut, and an optional rerank model reorders
+the top of the fused list.
+
+Degradation ladder (§3 universality — never a brick):
+
+- No embedding provider configured, a dead/keyless backend, or a store-side
+ vector degradation (missing sqlite-vec, nothing embedded yet, dim mismatch)
+ => the vector leg is skipped with a logged honest reason and keyword search
+ answers alone; ``matched_by`` on each result shows which legs actually ran.
+- No rerank provider configured, an unknown/not-ready one, or a failing rerank
+ call => the fusion order stands. A rerank failure logs once and never fails
+ the search.
+
+Heavy/optional pieces (httpx-backed embedding + rerank adapters) are imported
+lazily inside the functions (AP-26); this module itself is stdlib + types only.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+from dataclasses import replace
+from datetime import UTC, datetime
+from typing import Any
+
+from jarvis.ultrawiki.types import SearchResult
+
+log = logging.getLogger(__name__)
+
+__all__ = ["hybrid_search", "search_status"]
+
+#: RRF smoothing constant (design doc 03: score(d) = sum 1 / (60 + rank)).
+RRF_K = 60
+
+#: How many candidates each leg contributes to the fusion pool.
+LEG_POOL = 20
+
+#: How many fused candidates the optional rerank stage rescores.
+RERANK_POOL = 20
+
+#: Maximum results per source BEFORE the final top-k cut, so one chatty
+#: source cannot crowd out every other voice.
+PER_SOURCE_CAP = 5
+
+#: Recency bonus ceiling — a strict tiebreak, deliberately far below any
+#: realistic difference between two distinct RRF sums.
+_RECENCY_EPSILON = 1e-6
+
+
+async def hybrid_search(
+ store: Any,
+ cfg: Any,
+ query: str,
+ *,
+ k: int = 10,
+ area_id: str | None = None,
+) -> list[SearchResult]:
+ """Fused keyword + vector search over an UltraWiki store.
+
+ ``store`` is an :class:`~jarvis.ultrawiki.store.UltraStore` or
+ :class:`~jarvis.ultrawiki.store.PostgresStore` (same public surface).
+ Returns at most ``k`` :class:`SearchResult` rows, best first, each carrying
+ the fused score and the ``matched_by`` tuple of the legs that produced it.
+ An empty/blank query returns ``[]`` without touching any leg.
+ """
+ if not query or not query.strip():
+ return []
+ keyword_hits, vector_hits = await asyncio.gather(
+ store.keyword_search(query, k=LEG_POOL, area_id=area_id),
+ _vector_leg(store, cfg, query, area_id=area_id),
+ )
+ fused = _fuse(keyword_hits, vector_hits)
+ if not fused:
+ return []
+ capped = _cap_per_source(fused)
+ ordered = await _maybe_rerank(cfg, query, capped)
+ return ordered[: max(0, int(k))]
+
+
+async def search(
+ *,
+ store: Any,
+ cfg: Any,
+ query: str,
+ k: int = 10,
+ area_id: str | None = None,
+) -> list[SearchResult]:
+ """Keyword-only facade over :func:`hybrid_search`.
+
+ This is the seam :meth:`UltraWikiService.search` delegates to; it exists
+ so the service and the routes never depend on positional argument order.
+ """
+ return await hybrid_search(store, cfg, query, k=k, area_id=area_id)
+
+
+def search_status(cfg: Any) -> dict[str, Any]:
+ """Honest live report of the three retrieval legs, from config alone.
+
+ ``keyword`` is always available (FTS ships with the store). ``vector``
+ names the configured backend + model or the honest reason it is off.
+ ``rerank`` names the configured provider or ``"off"``.
+ """
+ ultrawiki = getattr(cfg, "ultrawiki", None)
+ status: dict[str, Any] = {"keyword": {"available": True}}
+
+ provider = str(getattr(ultrawiki, "embedding_provider", "") or "").strip()
+ if not provider:
+ status["vector"] = {
+ "available": False,
+ "reason": (
+ "no embedding provider is configured — semantic search is "
+ "off and keyword search answers alone"
+ ),
+ }
+ else:
+ from jarvis.ultrawiki.embeddings import ( # noqa: PLC0415 — lazy (AP-26)
+ DEFAULT_MODELS,
+ EMBEDDING_BACKENDS,
+ )
+
+ model = _configured_model(ultrawiki, provider, DEFAULT_MODELS)
+ factory = EMBEDDING_BACKENDS.get(provider)
+ if factory is None:
+ status["vector"] = {
+ "available": False,
+ "backend": provider,
+ "reason": f"unknown embedding provider {provider!r}",
+ }
+ else:
+ try:
+ ready, reason = factory(cfg).ready()
+ except Exception as exc: # noqa: BLE001 — a broken probe reports, never raises
+ ready, reason = False, f"readiness probe failed ({type(exc).__name__})"
+ entry: dict[str, Any] = {
+ "available": ready,
+ "backend": provider,
+ "model": model,
+ }
+ if not ready:
+ entry["reason"] = reason
+ status["vector"] = entry
+
+ rerank_provider = str(getattr(ultrawiki, "rerank_provider", "") or "").strip()
+ if not rerank_provider:
+ status["rerank"] = {"available": False, "provider": "off"}
+ else:
+ from jarvis.ultrawiki.rerank import RERANK_BACKENDS # noqa: PLC0415 — lazy (AP-26)
+
+ factory = RERANK_BACKENDS.get(rerank_provider)
+ if factory is None:
+ status["rerank"] = {
+ "available": False,
+ "provider": rerank_provider,
+ "reason": f"unknown rerank provider {rerank_provider!r}",
+ }
+ else:
+ try:
+ ready, reason = factory(cfg).ready()
+ except Exception as exc: # noqa: BLE001 — a broken probe reports, never raises
+ ready, reason = False, f"readiness probe failed ({type(exc).__name__})"
+ entry = {"available": ready, "provider": rerank_provider}
+ if not ready:
+ entry["reason"] = reason
+ status["rerank"] = entry
+
+ return status
+
+
+# ---------------------------------------------------------------------------
+# Legs
+# ---------------------------------------------------------------------------
+
+
+def _configured_model(ultrawiki: Any, provider: str, defaults: dict[str, str]) -> str:
+ model = str(getattr(ultrawiki, "embedding_model", "") or "").strip()
+ return model or defaults.get(provider, "")
+
+
+async def _vector_leg(
+ store: Any, cfg: Any, query: str, *, area_id: str | None
+) -> list[SearchResult]:
+ """Embed the query and run the store's ANN leg.
+
+ Every degraded outcome (unconfigured, unknown, dead backend, store-side
+ vector degradation) returns ``[]`` with a logged honest reason — the
+ search itself never fails because of the vector leg.
+ """
+ ultrawiki = getattr(cfg, "ultrawiki", None)
+ provider = str(getattr(ultrawiki, "embedding_provider", "") or "").strip()
+ if not provider:
+ return []
+ from jarvis.ultrawiki.embeddings import ( # noqa: PLC0415 — lazy (AP-26)
+ DEFAULT_MODELS,
+ EMBEDDING_BACKENDS,
+ EmbeddingError,
+ )
+
+ factory = EMBEDDING_BACKENDS.get(provider)
+ if factory is None:
+ log.warning("vector leg skipped: unknown embedding provider %r", provider)
+ return []
+ model = _configured_model(ultrawiki, provider, DEFAULT_MODELS)
+ try:
+ vectors = await factory(cfg).embed([query], model=model)
+ except EmbeddingError as exc:
+ log.info("vector leg skipped: %s", exc)
+ return []
+ except Exception: # noqa: BLE001 — degrade to keyword-only, never fail the search
+ log.warning(
+ "vector leg skipped: query embedding raised unexpectedly",
+ exc_info=True,
+ )
+ return []
+ if not vectors or not vectors[0]:
+ log.info("vector leg skipped: %s returned no query vector", provider)
+ return []
+ results, reason = await store.vector_search(vectors[0], k=LEG_POOL, area_id=area_id)
+ if reason:
+ log.info("vector leg degraded: %s", reason)
+ return results
+
+
+# ---------------------------------------------------------------------------
+# Fusion
+# ---------------------------------------------------------------------------
+
+
+def _recency_key(timestamp_utc: Any) -> float:
+ """Epoch seconds for the recency tiebreak; unparsable stamps sort last."""
+ try:
+ parsed = datetime.fromisoformat(str(timestamp_utc).replace("Z", "+00:00"))
+ except (TypeError, ValueError):
+ return float("-inf")
+ if parsed.tzinfo is None:
+ parsed = parsed.replace(tzinfo=UTC)
+ return parsed.timestamp()
+
+
+def _fuse(keyword_hits: list[SearchResult], vector_hits: list[SearchResult]) -> list[SearchResult]:
+ """RRF-fuse the two ranked lists; merge duplicates by ``item_id``.
+
+ The fused score is ``sum(1 / (RRF_K + rank))`` over the legs the item
+ appeared in, plus a strictly-tiebreak-sized recency bonus derived from the
+ candidates themselves (newer ``timestamp_utc`` wins ties — no extra DB
+ query). ``matched_by`` is the union of the contributing legs; snippet and
+ citation fields come from the keyword occurrence when both legs matched
+ (its snippet is query-specific).
+ """
+ rrf_score: dict[int, float] = {}
+ matched: dict[int, list[str]] = {}
+ representative: dict[int, SearchResult] = {}
+ for leg_name, hits in (("keyword", keyword_hits), ("vector", vector_hits)):
+ for rank, hit in enumerate(hits, start=1):
+ rrf_score[hit.item_id] = rrf_score.get(hit.item_id, 0.0) + 1.0 / (RRF_K + rank)
+ labels = matched.setdefault(hit.item_id, [])
+ if leg_name not in labels:
+ labels.append(leg_name)
+ representative.setdefault(hit.item_id, hit)
+ if not representative:
+ return []
+
+ by_recency = sorted(
+ representative,
+ key=lambda item_id: _recency_key(representative[item_id].timestamp_utc),
+ reverse=True,
+ )
+ total = len(by_recency)
+ recency_bonus = {
+ item_id: _RECENCY_EPSILON * (total - index) / total
+ for index, item_id in enumerate(by_recency)
+ }
+
+ fused = [
+ replace(
+ base,
+ score=rrf_score[item_id] + recency_bonus[item_id],
+ matched_by=tuple(matched[item_id]),
+ )
+ for item_id, base in representative.items()
+ ]
+ fused.sort(key=lambda result: (-result.score, result.item_id))
+ return fused
+
+
+def _cap_per_source(ranked: list[SearchResult]) -> list[SearchResult]:
+ """Keep at most :data:`PER_SOURCE_CAP` results per source, best first."""
+ kept: list[SearchResult] = []
+ per_source: dict[str, int] = {}
+ for hit in ranked:
+ count = per_source.get(hit.source_id, 0)
+ if count >= PER_SOURCE_CAP:
+ continue
+ per_source[hit.source_id] = count + 1
+ kept.append(hit)
+ return kept
+
+
+# ---------------------------------------------------------------------------
+# Optional rerank
+# ---------------------------------------------------------------------------
+
+
+def _rerank_document(hit: SearchResult) -> str:
+ return f"{hit.title}\n{hit.snippet}".strip()
+
+
+async def _maybe_rerank(cfg: Any, query: str, ranked: list[SearchResult]) -> list[SearchResult]:
+ """Reorder the top of the fused list with the configured reranker.
+
+ Skipped honestly when no provider is configured / ready. Only the ORDER
+ changes — every result keeps its fused score. On :class:`RerankError`
+ the fusion order stands (logged once, the search never fails).
+ """
+ ultrawiki = getattr(cfg, "ultrawiki", None)
+ if not str(getattr(ultrawiki, "rerank_provider", "") or "").strip():
+ return ranked
+ from jarvis.ultrawiki import rerank as rerank_mod # noqa: PLC0415 — lazy (AP-26)
+
+ reranker = rerank_mod.resolve_reranker(cfg)
+ if reranker is None:
+ # resolve_reranker already logged the honest skip reason.
+ return ranked
+ pool = ranked[:RERANK_POOL]
+ documents = [_rerank_document(hit) for hit in pool]
+ try:
+ pairs = await reranker.rerank(query, documents, top_k=len(documents))
+ except rerank_mod.RerankError as exc:
+ log.warning("rerank failed (%s) — keeping the fusion order", exc)
+ return ranked
+ reordered: list[SearchResult] = []
+ seen: set[int] = set()
+ for index, _score in pairs:
+ if 0 <= index < len(pool) and index not in seen:
+ seen.add(index)
+ reordered.append(pool[index])
+ for index, hit in enumerate(pool):
+ if index not in seen: # providers may return fewer rows than asked
+ reordered.append(hit)
+ return reordered + ranked[RERANK_POOL:]
diff --git a/jarvis/ultrawiki/service.py b/jarvis/ultrawiki/service.py
new file mode 100644
index 0000000000..aa1e07e240
--- /dev/null
+++ b/jarvis/ultrawiki/service.py
@@ -0,0 +1,836 @@
+"""UltraWikiService — the one object the web layer talks to.
+
+Lifecycle discipline (AP-26 + the WebServer.stop() teardown contract):
+
+- The constructor is CHEAP: no I/O, no store open, no heavy import. The web
+ layer constructs the service eagerly and calls :meth:`ensure_started` off
+ the boot critical path.
+- :meth:`ensure_started` opens the store (SQLite floor, or Postgres via the
+ ``ultrawiki_db_url`` secret when ``cfg.ultrawiki.db_backend`` says so —
+ falling back honestly to SQLite when the URL/driver/server is missing) and
+ starts the staged pipeline as a NAMED task held on an attribute.
+- :meth:`shutdown` follows the cancel-then-``wait_for(2 s)`` discipline for
+ the pipeline task and every running sync job, THEN closes the store —
+ never the other way around (a loop must not tick against a closed
+ connection).
+
+Consent is policy here, not in the store: :meth:`activate` registers the
+default local sources with consent PENDING and pulls NOTHING;
+:meth:`start_sync` refuses unless the source is explicitly approved AND
+UltraWiki is enabled.
+
+Sync jobs run as detached named tasks streaming connector items into
+``store.upsert_items`` in chunks with per-chunk sync-state checkpoints; the
+module-level job registry mirrors ``jarvis/harness/cu_run_registry.py``
+(bounded, in-memory, JSON-safe snapshots, never breaks a job).
+"""
+
+from __future__ import annotations
+
+import asyncio
+import dataclasses
+import logging
+import re
+import time
+import uuid
+from collections import OrderedDict
+from collections.abc import AsyncIterator, Awaitable, Callable
+from dataclasses import dataclass, field
+from datetime import UTC, datetime
+from typing import Any
+
+from jarvis.ultrawiki.types import (
+ ConnectorContext,
+ ConsentState,
+ IncrementalMode,
+ PipelineCounts,
+ RawItem,
+)
+
+log = logging.getLogger(__name__)
+
+__all__ = [
+ "SYNC_CHUNK_SIZE",
+ "JOB_ACTIVE_STATUSES",
+ "JOB_TERMINAL_STATUSES",
+ "SyncJob",
+ "UltraWikiService",
+ "clear_jobs",
+]
+
+#: Items per ``upsert_items`` transaction / sync-state checkpoint.
+SYNC_CHUNK_SIZE = 200
+
+#: The default local sources :meth:`UltraWikiService.activate` registers —
+#: source id == connector id for these singletons.
+_DEFAULT_SOURCES: tuple[tuple[str, str], ...] = (
+ ("normal-wiki", "Built-in Wiki"),
+ ("jarvis-conversations", "Jarvis Conversations"),
+)
+
+_SLUG_RE = re.compile(r"[^a-z0-9]+")
+
+
+def _slugify(name: str) -> str:
+ return _SLUG_RE.sub("-", name.lower()).strip("-") or "area"
+
+
+def _iso_now() -> str:
+ return datetime.now(UTC).strftime("%Y-%m-%dT%H:%M:%SZ")
+
+
+def _counts_dict(counts: PipelineCounts) -> dict[str, int]:
+ return {**dataclasses.asdict(counts), "total": counts.total}
+
+
+# ---------------------------------------------------------------------------
+# Bounded in-module sync-job registry (mirror of cu_run_registry.py)
+# ---------------------------------------------------------------------------
+
+#: Bounded history: the oldest TERMINAL jobs are evicted past this size.
+_MAX_JOBS = 100
+
+JOB_TERMINAL_STATUSES = frozenset({"done", "failed", "cancelled"})
+JOB_ACTIVE_STATUSES = frozenset({"queued", "running"})
+
+
+@dataclass
+class SyncJob:
+ """One sync run's control-plane view (in-memory, not history)."""
+
+ job_id: str
+ source_id: str
+ mode: str # "backfill" | "incremental"
+ status: str = "queued"
+ started_at: float = field(default_factory=time.time)
+ ended_at: float | None = None
+ chunks: int = 0
+ new: int = 0
+ changed: int = 0
+ unchanged: int = 0
+ tombstoned: int = 0
+ error: str = ""
+ #: The asyncio.Task while the job is active; cleared when it ends.
+ task: Any = None
+
+ def snapshot(self) -> dict[str, Any]:
+ """JSON-safe public view (never exposes the task)."""
+ return {
+ "job_id": self.job_id,
+ "source_id": self.source_id,
+ "mode": self.mode,
+ "status": self.status,
+ "started_at": self.started_at,
+ "ended_at": self.ended_at,
+ "chunks": self.chunks,
+ "new": self.new,
+ "changed": self.changed,
+ "unchanged": self.unchanged,
+ "tombstoned": self.tombstoned,
+ "error": self.error,
+ }
+
+
+_JOBS: OrderedDict[str, SyncJob] = OrderedDict()
+
+
+def _evict_jobs_if_needed() -> None:
+ if len(_JOBS) <= _MAX_JOBS:
+ return
+ for job_id, job in list(_JOBS.items()):
+ if len(_JOBS) <= _MAX_JOBS:
+ break
+ if job.status in JOB_TERMINAL_STATUSES:
+ _JOBS.pop(job_id, None)
+
+
+def _register_job(job: SyncJob) -> None:
+ try:
+ _JOBS[job.job_id] = job
+ _evict_jobs_if_needed()
+ except Exception: # noqa: BLE001 — the registry must never break a sync
+ log.debug("ultrawiki job register failed", exc_info=True)
+
+
+def _get_job(job_id: str) -> SyncJob | None:
+ return _JOBS.get(job_id)
+
+
+def _list_job_snapshots(limit: int = 20) -> list[dict[str, Any]]:
+ jobs = list(_JOBS.values())
+ jobs.sort(key=lambda j: j.started_at, reverse=True)
+ return [j.snapshot() for j in jobs[: max(1, int(limit))]]
+
+
+def _cancel_job(job_id: str) -> bool:
+ """Cancel ONE active job. False when unknown or already terminal."""
+ job = _JOBS.get(job_id)
+ if job is None or job.status in JOB_TERMINAL_STATUSES or job.task is None:
+ return False
+ try:
+ job.task.cancel()
+ except Exception: # noqa: BLE001 — a broken task must not 500 the API
+ log.debug("ultrawiki job cancel failed", exc_info=True)
+ return False
+ return True
+
+
+def clear_jobs() -> None:
+ """Test/teardown helper — wipes the job registry."""
+ _JOBS.clear()
+
+
+# ---------------------------------------------------------------------------
+# The service
+# ---------------------------------------------------------------------------
+
+
+class UltraWikiService:
+ """Facade over store + pipeline + connectors for the REST/CLI surface.
+
+ ``embedding_backend_factory`` and ``distill_fn`` are injectable test
+ seams; production leaves them ``None`` (the configured backend registry
+ and ``distill_text`` are resolved lazily).
+ """
+
+ def __init__(
+ self,
+ cfg: Any,
+ bus: Any = None,
+ *,
+ embedding_backend_factory: Callable[[], Any] | None = None,
+ distill_fn: Callable[..., Awaitable[Any]] | None = None,
+ ) -> None:
+ self._cfg = cfg
+ self._bus = bus
+ self._store: Any = None
+ self._backend_in_use = ""
+ self._pipeline: Any = None
+ self._pipeline_task: asyncio.Task[None] | None = None
+ self._cancel_event: asyncio.Event | None = None
+ self._start_lock = asyncio.Lock()
+ self._sync_tasks: dict[str, asyncio.Task[None]] = {}
+ self._degradations: list[str] = []
+ self._embedding_backend_factory = (
+ embedding_backend_factory or self._default_backend_factory
+ )
+ self._injected_distill_fn = distill_fn
+
+ # -- config helpers ------------------------------------------------------
+
+ def _uw_cfg(self) -> Any:
+ return getattr(self._cfg, "ultrawiki", None)
+
+ def _uw_enabled(self) -> bool:
+ return bool(getattr(self._uw_cfg(), "enabled", False))
+
+ def _note_degradation(self, reason: str) -> None:
+ if reason not in self._degradations:
+ self._degradations.append(reason)
+ log.warning("UltraWiki degraded: %s", reason)
+
+ # -- default provider seams ---------------------------------------------
+
+ def _default_backend_factory(self) -> Any:
+ """The configured embedding backend, or ``None`` (unconfigured slot)."""
+ provider = str(getattr(self._uw_cfg(), "embedding_provider", "") or "").strip()
+ if not provider:
+ return None
+ from jarvis.ultrawiki.embeddings import ( # noqa: PLC0415 — lazy (AP-26)
+ EMBEDDING_BACKENDS,
+ )
+
+ factory = EMBEDDING_BACKENDS.get(provider)
+ if factory is None:
+ log.warning(
+ "UltraWiki: unknown embedding provider %r - the embed stage "
+ "stays paused",
+ provider,
+ )
+ return None
+ return factory(self._cfg)
+
+ async def _call_distill(
+ self, cfg: Any, *, title: str, body: str, source_kind: str
+ ) -> Any:
+ if self._injected_distill_fn is not None:
+ return await self._injected_distill_fn(
+ cfg, title=title, body=body, source_kind=source_kind
+ )
+ from jarvis.ultrawiki.distill import distill_text # noqa: PLC0415 — lazy
+
+ return await distill_text(cfg, title=title, body=body, source_kind=source_kind)
+
+ # -- lifecycle -----------------------------------------------------------
+
+ async def ensure_started(self) -> None:
+ """Open the store and start the pipeline (idempotent, off boot path).
+
+ The pipeline only starts while ``cfg.ultrawiki.enabled`` is true; a
+ later enable is picked up by the next ``ensure_started`` call.
+ """
+ async with self._start_lock:
+ if self._store is None:
+ self._store = await self._open_store()
+ if self._uw_enabled() and self._pipeline_task is None:
+ from jarvis.ultrawiki.pipeline import ( # noqa: PLC0415 — lazy
+ PipelineWorker,
+ )
+
+ self._cancel_event = asyncio.Event()
+ self._pipeline = PipelineWorker(
+ self._store,
+ self._cfg,
+ embedding_backend_factory=self._embedding_backend_factory,
+ distill_fn=self._call_distill,
+ )
+ self._pipeline_task = asyncio.create_task(
+ self._pipeline.run(self._cancel_event),
+ name="ultrawiki-pipeline",
+ )
+
+ async def _open_store(self) -> Any:
+ from jarvis.ultrawiki import store as store_mod # noqa: PLC0415 — lazy
+
+ backend = str(getattr(self._uw_cfg(), "db_backend", "sqlite") or "sqlite")
+ if backend.strip().lower() == "postgres":
+ from jarvis.core.config import get_secret # noqa: PLC0415 — lazy
+
+ conn_str = get_secret("ultrawiki_db_url")
+ if not conn_str:
+ self._note_degradation(
+ "the Postgres backend is configured but no "
+ "'ultrawiki_db_url' connection string is saved - falling "
+ "back to the local SQLite store"
+ )
+ else:
+ pg_store = store_mod.PostgresStore(conn_str)
+ try:
+ await pg_store.open()
+ except Exception as exc: # noqa: BLE001 — degrade, never brick
+ self._note_degradation(
+ f"the Postgres store is unavailable ({exc}) - falling "
+ "back to the local SQLite store"
+ )
+ else:
+ self._backend_in_use = "postgres"
+ return pg_store
+ data_dir = getattr(getattr(self._cfg, "memory", None), "data_dir", None)
+ sqlite_store = store_mod.UltraStore(
+ store_mod.resolve_ultrawiki_db_path(data_dir)
+ )
+ await sqlite_store.open()
+ self._backend_in_use = "sqlite"
+ return sqlite_store
+
+ async def shutdown(self) -> None:
+ """Cancel pipeline + sync tasks (cancel, then ``wait_for(2 s)``),
+ THEN close the store."""
+ async with self._start_lock:
+ if self._cancel_event is not None:
+ self._cancel_event.set()
+ task = self._pipeline_task
+ if task is not None:
+ task.cancel()
+ try:
+ await asyncio.wait_for(task, timeout=2.0)
+ except (TimeoutError, asyncio.CancelledError):
+ pass
+ except Exception as exc: # noqa: BLE001 — shutdown best-effort
+ log.warning("UltraWiki pipeline shutdown error: %s", exc)
+ self._pipeline_task = None
+ for job_id, sync_task in list(self._sync_tasks.items()):
+ sync_task.cancel()
+ try:
+ await asyncio.wait_for(sync_task, timeout=2.0)
+ except (TimeoutError, asyncio.CancelledError):
+ pass
+ except Exception as exc: # noqa: BLE001 — shutdown best-effort
+ log.warning("UltraWiki sync %s shutdown error: %s", job_id, exc)
+ self._sync_tasks.clear()
+ if self._store is not None:
+ try:
+ await self._store.close()
+ except Exception as exc: # noqa: BLE001 — shutdown best-effort
+ log.warning("UltraWiki store close failed: %s", exc)
+ self._store = None
+ self._pipeline = None
+ self._cancel_event = None
+ self._backend_in_use = ""
+
+ def _require_store(self) -> Any:
+ if self._store is None:
+ raise RuntimeError(
+ "UltraWiki is not started - call ensure_started() first"
+ )
+ return self._store
+
+ # -- status --------------------------------------------------------------
+
+ async def status(self) -> dict[str, Any]:
+ """Honest capability + backlog report for the settings surface."""
+ started = self._store is not None
+ counts = PipelineCounts()
+ sources: list[dict[str, Any]] = []
+ vector: dict[str, Any] = {"ready": False, "reason": "store not started"}
+ if started:
+ try:
+ counts = await self._store.counts()
+ sources = [
+ self._source_summary(row)
+ for row in await self._store.list_sources()
+ ]
+ except Exception as exc: # noqa: BLE001 — status never raises
+ self._note_degradation(f"store status query failed ({exc})")
+ try:
+ vec_ok, vec_reason = await self._store.vector_status()
+ vector = {"ready": bool(vec_ok), "reason": vec_reason}
+ except Exception as exc: # noqa: BLE001 — status never raises
+ vector = {"ready": False, "reason": f"vector probe failed ({exc})"}
+ pipeline_running = (
+ self._pipeline_task is not None and not self._pipeline_task.done()
+ )
+ processed = (
+ self._pipeline.processed_counts() if self._pipeline is not None else {}
+ )
+ return {
+ "enabled": self._uw_enabled(),
+ "started": started,
+ "backend": {
+ "configured": str(
+ getattr(self._uw_cfg(), "db_backend", "sqlite") or "sqlite"
+ ),
+ "in_use": self._backend_in_use,
+ },
+ "slots": {
+ "embedding": self._embedding_slot_status(),
+ "distill": self._distill_slot_status(),
+ "rerank": self._rerank_slot_status(),
+ },
+ "vector": vector,
+ "counts": _counts_dict(counts),
+ "pipeline": {"running": pipeline_running, "processed": processed},
+ "sources": sources,
+ "jobs": _list_job_snapshots(10),
+ "degradations": list(self._degradations),
+ }
+
+ @staticmethod
+ def _source_summary(row: dict[str, Any]) -> dict[str, Any]:
+ counts = row.get("counts")
+ return {
+ "id": row.get("id"),
+ "connector": row.get("connector"),
+ "label": row.get("label"),
+ "consent": row.get("consent"),
+ "enabled": row.get("enabled"),
+ "areas": row.get("areas", []),
+ "counts": _counts_dict(counts)
+ if isinstance(counts, PipelineCounts)
+ else counts,
+ "sync_state": row.get("sync_state"),
+ "last_sync_at": row.get("last_sync_at"),
+ "last_error": row.get("last_error"),
+ }
+
+ def _embedding_slot_status(self) -> dict[str, Any]:
+ provider = str(getattr(self._uw_cfg(), "embedding_provider", "") or "").strip()
+ model = str(getattr(self._uw_cfg(), "embedding_model", "") or "").strip()
+ try:
+ from jarvis.ultrawiki import embeddings as embeddings_mod # noqa: PLC0415
+
+ available = embeddings_mod.available_backends(self._cfg)
+ except Exception as exc: # noqa: BLE001 — status never raises
+ return {
+ "provider": provider,
+ "model": model,
+ "ready": False,
+ "reason": f"embedding backend probe failed ({type(exc).__name__})",
+ "available": [],
+ }
+ row = next((r for r in available if r.get("name") == provider), None)
+ if not provider:
+ ready, reason = False, "no embedding provider is configured"
+ elif row is None:
+ ready, reason = False, f"unknown embedding provider {provider!r}"
+ else:
+ ready, reason = bool(row.get("ready")), str(row.get("reason") or "")
+ return {
+ "provider": provider,
+ "model": model or (str(row.get("default_model") or "") if row else ""),
+ "ready": ready,
+ "reason": reason,
+ "available": available,
+ }
+
+ def _distill_slot_status(self) -> dict[str, Any]:
+ provider = str(getattr(self._uw_cfg(), "distill_provider", "") or "").strip()
+ model = str(getattr(self._uw_cfg(), "distill_model", "") or "").strip()
+ try:
+ from jarvis.brain.provider_registry import ( # noqa: PLC0415 — lazy
+ BrainProviderRegistry,
+ )
+ from jarvis.memory.wiki.provider_chain import ( # noqa: PLC0415 — lazy
+ credential_ready_wiki_providers,
+ )
+
+ available = set(BrainProviderRegistry().available())
+ chain = sorted(
+ credential_ready_wiki_providers(available=available, config=self._cfg)
+ )
+ except Exception as exc: # noqa: BLE001 — status never raises
+ return {
+ "provider": provider,
+ "model": model,
+ "ready": False,
+ "reason": f"distill chain probe failed ({type(exc).__name__})",
+ "chain": [],
+ }
+ ready = bool(chain)
+ reason = (
+ ""
+ if ready
+ else "no credential-ready chat provider is available for distillation"
+ )
+ return {
+ "provider": provider,
+ "model": model,
+ "ready": ready,
+ "reason": reason,
+ "chain": chain,
+ }
+
+ def _rerank_slot_status(self) -> dict[str, Any]:
+ provider = str(getattr(self._uw_cfg(), "rerank_provider", "") or "").strip()
+ try:
+ from jarvis.ultrawiki import rerank as rerank_mod # noqa: PLC0415 — lazy
+
+ available = rerank_mod.available_rerankers(self._cfg)
+ except Exception as exc: # noqa: BLE001 — status never raises
+ return {
+ "provider": provider,
+ "ready": False,
+ "reason": f"rerank backend probe failed ({type(exc).__name__})",
+ "available": [],
+ }
+ row = next((r for r in available if r.get("name") == provider), None)
+ if not provider:
+ ready = False
+ reason = "rerank is not configured - the fusion order stands (optional stage)"
+ elif row is None:
+ ready, reason = False, f"unknown rerank provider {provider!r}"
+ else:
+ ready, reason = bool(row.get("ready")), str(row.get("reason") or "")
+ return {
+ "provider": provider,
+ "ready": ready,
+ "reason": reason,
+ "available": available,
+ }
+
+ # -- activation & sources ------------------------------------------------
+
+ async def activate(self, payload: dict[str, Any] | None = None) -> dict[str, Any]:
+ """Pure-domain activation: seed areas + register the default local
+ sources with consent PENDING. Writes NO config and pulls NOTHING —
+ approval (and any pull) is a separate, explicit user step."""
+ await self.ensure_started()
+ store = self._require_store()
+ payload = payload or {}
+ default_area = await store.ensure_default_area()
+ created_areas: list[str] = []
+ for name in payload.get("areas", []) or []:
+ label = str(name).strip()
+ if not label:
+ continue
+ slug = _slugify(label)
+ await store.upsert_area(slug, label)
+ created_areas.append(slug)
+ sources_created: list[str] = []
+ sources_existing: list[str] = []
+ for source_id, label in _DEFAULT_SOURCES:
+ if await store.get_source(source_id) is not None:
+ sources_existing.append(source_id)
+ continue
+ await store.upsert_source(
+ source_id,
+ connector=source_id,
+ label=label,
+ config={},
+ areas=[default_area],
+ )
+ sources_created.append(source_id)
+ return {
+ "default_area": default_area,
+ "areas_created": created_areas,
+ "sources_created": sources_created,
+ "sources_existing": sources_existing,
+ }
+
+ async def add_source(
+ self,
+ connector_id: str,
+ label: str,
+ config: dict[str, Any] | None = None,
+ area_ids: list[str] | None = None,
+ ) -> dict[str, Any]:
+ """Register a new source (consent PENDING — nothing is pulled)."""
+ await self.ensure_started()
+ store = self._require_store()
+ from jarvis.ultrawiki import connectors as connectors_mod # noqa: PLC0415
+
+ registry = connectors_mod.discover_connectors()
+ if connector_id not in registry:
+ raise ValueError(
+ f"unknown connector {connector_id!r} "
+ f"(available: {', '.join(sorted(registry))})"
+ )
+ source_id = f"{connector_id}-{uuid.uuid4().hex[:8]}"
+ await store.upsert_source(
+ source_id,
+ connector=connector_id,
+ label=label,
+ config=dict(config or {}),
+ areas=list(area_ids or []),
+ )
+ source = await store.get_source(source_id)
+ assert source is not None
+ return source
+
+ async def approve_source(self, source_id: str) -> dict[str, Any]:
+ return await self._set_consent(source_id, ConsentState.APPROVED)
+
+ async def revoke_source(self, source_id: str) -> dict[str, Any]:
+ return await self._set_consent(source_id, ConsentState.REVOKED)
+
+ async def _set_consent(
+ self, source_id: str, consent: ConsentState
+ ) -> dict[str, Any]:
+ await self.ensure_started()
+ store = self._require_store()
+ if await store.get_source(source_id) is None:
+ raise ValueError(f"unknown source {source_id!r}")
+ await store.set_consent(source_id, consent)
+ source = await store.get_source(source_id)
+ assert source is not None
+ return source
+
+ # -- sync jobs -----------------------------------------------------------
+
+ async def start_sync(self, source_id: str) -> str:
+ """Start a backfill/incremental sync as a detached named task.
+
+ Refuses (``ValueError``) unless UltraWiki is enabled AND the source
+ holds explicit approved consent — no connector pulls a single byte
+ before then.
+ """
+ if not self._uw_enabled():
+ raise ValueError(
+ "UltraWiki is disabled - enable it in the Wiki settings "
+ "before syncing sources"
+ )
+ await self.ensure_started()
+ store = self._require_store()
+ source = await store.get_source(source_id)
+ if source is None:
+ raise ValueError(f"unknown source {source_id!r}")
+ if source.get("consent") != ConsentState.APPROVED.value:
+ raise ValueError(
+ f"source {source_id!r} is not approved (consent is "
+ f"{source.get('consent')!r}) - nothing is pulled before the "
+ "source is explicitly approved"
+ )
+ if not source.get("enabled", False):
+ raise ValueError(f"source {source_id!r} is disabled")
+ connector = self._build_connector(str(source.get("connector") or ""))
+ sync_state = await store.get_sync_state(source_id) or {}
+ capabilities = getattr(connector, "capabilities", None)
+ incremental_mode = getattr(
+ capabilities, "incremental", IncrementalMode.NONE
+ )
+ use_incremental = bool(sync_state.get("backfill_complete_at")) and (
+ incremental_mode != IncrementalMode.NONE
+ )
+ mode = "incremental" if use_incremental else "backfill"
+ job = SyncJob(
+ job_id=uuid.uuid4().hex[:12], source_id=source_id, mode=mode
+ )
+ _register_job(job)
+ task = asyncio.create_task(
+ self._run_sync(job, source, connector, sync_state),
+ name=f"ultrawiki-sync-{source_id}-{job.job_id}",
+ )
+ job.task = task
+ self._sync_tasks[job.job_id] = task
+ task.add_done_callback(
+ lambda _t, jid=job.job_id: self._sync_tasks.pop(jid, None)
+ )
+ return job.job_id
+
+ def _build_connector(self, connector_id: str) -> Any:
+ from jarvis.ultrawiki import connectors as connectors_mod # noqa: PLC0415
+
+ factory = connectors_mod.discover_connectors().get(connector_id)
+ if factory is None:
+ raise ValueError(
+ f"no connector {connector_id!r} is installed for this source"
+ )
+ return factory()
+
+ def _connector_context(self, source: dict[str, Any]) -> ConnectorContext:
+ def _secret_get(name: str) -> str | None:
+ from jarvis.core.config import get_secret # noqa: PLC0415 — lazy
+
+ return get_secret(name)
+
+ return ConnectorContext(
+ source_id=str(source.get("id") or ""),
+ config=dict(source.get("config") or {}),
+ secret_get=_secret_get,
+ )
+
+ async def _run_sync(
+ self,
+ job: SyncJob,
+ source: dict[str, Any],
+ connector: Any,
+ sync_state: dict[str, Any],
+ ) -> None:
+ store = self._require_store()
+ source_id = job.source_id
+ ctx = self._connector_context(source)
+ job.status = "running"
+ checkpoint = sync_state.get("backfill_checkpoint")
+ # Delete-reconcile needs the COMPLETE yielded-id set, which only a
+ # backfill running from the very beginning can provide.
+ full_backfill = job.mode == "backfill" and not checkpoint
+ max_cursor = self._parse_cursor(sync_state.get("cursor"))
+ yielded_ids: set[str] = set()
+ buffer: list[RawItem] = []
+ try:
+ if job.mode == "incremental":
+ stream: AsyncIterator[RawItem] = connector.incremental(
+ ctx, sync_state.get("cursor")
+ )
+ else:
+ stream = connector.backfill(ctx, checkpoint)
+ async for item in stream:
+ buffer.append(item)
+ if job.mode == "backfill" and not item.deleted:
+ yielded_ids.add(item.external_id)
+ if len(buffer) >= SYNC_CHUNK_SIZE:
+ max_cursor = await self._flush_chunk(
+ job, source_id, buffer, max_cursor
+ )
+ buffer = []
+ if buffer:
+ max_cursor = await self._flush_chunk(
+ job, source_id, buffer, max_cursor
+ )
+ now = _iso_now()
+ if job.mode == "backfill":
+ deletes_capable = bool(
+ getattr(getattr(connector, "capabilities", None), "deletes", False)
+ )
+ if full_backfill and deletes_capable:
+ job.tombstoned += await store.reconcile_deletes(
+ source_id, yielded_ids
+ )
+ await store.set_sync_state(
+ source_id, backfill_complete_at=now, last_success_at=now
+ )
+ else:
+ await store.set_sync_state(source_id, last_success_at=now)
+ await store.set_source_status(
+ source_id, last_sync_at=now, last_error=None
+ )
+ job.status = "done"
+ except asyncio.CancelledError:
+ job.status = "cancelled"
+ raise
+ except Exception as exc: # noqa: BLE001 — the job records, never crashes callers
+ log.exception(
+ "UltraWiki sync %s for source %s failed", job.job_id, source_id
+ )
+ job.status = "failed"
+ job.error = f"{type(exc).__name__}: {exc}"
+ try:
+ await store.set_source_status(source_id, last_error=job.error)
+ except Exception: # noqa: BLE001 — best-effort bookkeeping
+ log.debug("sync error bookkeeping failed", exc_info=True)
+ finally:
+ job.ended_at = time.time()
+ job.task = None
+
+ async def _flush_chunk(
+ self,
+ job: SyncJob,
+ source_id: str,
+ items: list[RawItem],
+ max_cursor: int | None,
+ ) -> int | None:
+ store = self._require_store()
+ counts = await store.upsert_items(source_id, items)
+ job.chunks += 1
+ job.new += counts.new
+ job.changed += counts.changed
+ job.unchanged += counts.unchanged
+ job.tombstoned += counts.tombstoned
+ # Cursor advance from item metadata (connector convention: file
+ # walkers carry 'mtime_ns', jarvis-conversations carries 'max_rowid').
+ for item in items:
+ for key in ("mtime_ns", "max_rowid"):
+ value = item.metadata.get(key)
+ if value is None:
+ continue
+ try:
+ numeric = int(value)
+ except (TypeError, ValueError):
+ continue
+ if max_cursor is None or numeric > max_cursor:
+ max_cursor = numeric
+ updates: dict[str, Any] = {}
+ if job.mode == "backfill":
+ updates["backfill_checkpoint"] = items[-1].external_id
+ if max_cursor is not None:
+ updates["cursor"] = str(max_cursor)
+ if updates:
+ await store.set_sync_state(source_id, **updates)
+ return max_cursor
+
+ @staticmethod
+ def _parse_cursor(cursor: Any) -> int | None:
+ if cursor is None or cursor == "":
+ return None
+ try:
+ return int(cursor)
+ except (TypeError, ValueError):
+ return None
+
+ # -- job registry surface ------------------------------------------------
+
+ def job_snapshot(self, job_id: str) -> dict[str, Any] | None:
+ job = _get_job(job_id)
+ return job.snapshot() if job is not None else None
+
+ def list_jobs(self, limit: int = 20) -> list[dict[str, Any]]:
+ return _list_job_snapshots(limit)
+
+ def cancel_job(self, job_id: str) -> bool:
+ return _cancel_job(job_id)
+
+ # -- search --------------------------------------------------------------
+
+ async def search(self, query: str, **kwargs: Any) -> Any:
+ """Delegate to the retrieval module (built separately); lazy import
+ keeps this module cheap and decoupled from the read path."""
+ await self.ensure_started()
+ try:
+ from jarvis.ultrawiki import search as search_mod # noqa: PLC0415
+ except ImportError as exc:
+ raise RuntimeError(
+ "UltraWiki search is not available in this build"
+ ) from exc
+ return await search_mod.search(
+ store=self._require_store(), cfg=self._cfg, query=query, **kwargs
+ )
diff --git a/jarvis/ultrawiki/store.py b/jarvis/ultrawiki/store.py
new file mode 100644
index 0000000000..65f11275e7
--- /dev/null
+++ b/jarvis/ultrawiki/store.py
@@ -0,0 +1,2350 @@
+"""UltraWiki unified store — SQLite reference backend + Postgres variant.
+
+One SQL surface, two backends (design doc 01):
+
+- :class:`UltraStore` — the universal floor. Own DB file
+ ``<data_dir>/ultrawiki.db`` following the ``missions.db`` precedent
+ (ADR-0009): the staged ingest pipeline is a heavy writer and must not
+ contend with the shared ``jarvis.db`` tenants. Keyword leg is FTS5; the
+ vector leg is the sqlite-vec ``vec0`` extension, queried through plain SQL
+ (never a vector-SDK import), loaded lazily and degraded honestly when the
+ host cannot load it.
+- :class:`PostgresStore` — the cloud/self-hosted option behind the same
+ public interface. Keyword leg is a generated ``tsvector`` column + GIN
+ index; the vector leg is pgvector. The driver (``psycopg``) is an optional
+ extra and imported lazily; a missing driver raises an honest
+ ``ImportError`` naming the install command.
+
+Store discipline:
+
+- Lazy open on first use; ``schema.sql`` is applied idempotently on every
+ open and forward-only migrations under ``jarvis/ultrawiki/migrations/``
+ ride the ``PRAGMA user_version`` runner from
+ ``jarvis/memory/migration_runner.py``.
+- The staged state machine (design doc 02) lives in ``uw_items.state``;
+ workers claim a batch, perform exactly one transition, and commit. The
+ contentless-FTS delete+insert for the keyword stage happens in the SAME
+ transaction as the state transition.
+- Vectors are stored provider-neutral as little-endian float32 BLOBs in
+ ``uw_embeddings``; the ``uw_vec`` ANN index is DERIVED from that table, so
+ a host that gains the extension later backfills without re-embedding.
+- The store is policy-free: consent gating, scheduling, and provider calls
+ belong to the pipeline runtime. Nothing in this module touches the
+ network or reads credentials.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import logging
+import re
+import struct
+from collections.abc import AsyncIterator, Iterable, Sequence
+from contextlib import asynccontextmanager
+from dataclasses import dataclass
+from datetime import UTC, datetime, timedelta
+from pathlib import Path
+from typing import Any
+
+import aiosqlite
+
+from jarvis.ultrawiki.types import (
+ STATE_ORDER,
+ ConsentState,
+ DocType,
+ ItemState,
+ PipelineCounts,
+ RawItem,
+ SearchResult,
+ content_hash_for,
+)
+
+log = logging.getLogger(__name__)
+
+_SCHEMA_PATH = Path(__file__).parent / "schema.sql"
+_MIGRATIONS_DIR = Path(__file__).parent / "migrations"
+
+#: Retry policy (design doc 02): backoff 60s * 4^n, capped at 6h,
+#: dead-letter (state ``failed``) after 5 attempts.
+MAX_ATTEMPTS = 5
+BACKOFF_BASE_S = 60
+BACKOFF_CAP_S = 6 * 3600
+
+#: ``uw_meta`` keys pinning the embedding space (semi-permanent, D-3).
+META_EMBED_MODEL = "embed_model"
+META_EMBED_DIM = "embed_dim"
+
+_SNIPPET_CHARS = 240
+_IN_CHUNK = 400
+
+_FTS_QUOTE_STRIP_RE = re.compile(r'"')
+
+
+class UltraStoreError(RuntimeError):
+ """Raised for store-contract violations (e.g. embedding-dim mismatch)."""
+
+
+@dataclass(frozen=True, slots=True)
+class UpsertCounts:
+ """Result of one :meth:`UltraStore.upsert_items` batch."""
+
+ new: int = 0
+ changed: int = 0
+ unchanged: int = 0
+ tombstoned: int = 0
+
+
+# ---------------------------------------------------------------------------
+# Shared helpers (both backends)
+# ---------------------------------------------------------------------------
+
+
+def resolve_ultrawiki_db_path(data_dir: str | Path | None = None) -> Path:
+ """Return one absolute ``ultrawiki.db`` path independent of process CWD.
+
+ Mirrors ``jarvis/memory/wiki/db_path.py``: relative ``data_dir`` values
+ (the ``cfg.memory.data_dir`` default is ``./data``) are anchored at the
+ repo root, never the process CWD.
+ """
+ from jarvis.core.paths import repo_root # lazy: keep module import cheap
+
+ raw = Path(data_dir) if data_dir is not None else Path("data")
+ directory = raw if raw.is_absolute() else repo_root() / raw
+ return (directory / "ultrawiki.db").resolve(strict=False)
+
+
+def pack_vector(vector: Sequence[float]) -> bytes:
+ """Serialize a vector as little-endian float32 (the sqlite-vec format)."""
+ return struct.pack(f"<{len(vector)}f", *vector)
+
+
+def unpack_vector(blob: bytes) -> list[float]:
+ """Inverse of :func:`pack_vector`."""
+ count = len(blob) // 4
+ return list(struct.unpack(f"<{count}f", blob))
+
+
+def _import_sqlite_vec() -> Any:
+ """Import hook for the optional sqlite-vec extension (test seam)."""
+ import sqlite_vec # noqa: PLC0415 — deliberately lazy (AP-26)
+
+ return sqlite_vec
+
+
+def _import_psycopg() -> Any:
+ """Import hook for the optional Postgres driver (test seam)."""
+ try:
+ import psycopg # noqa: PLC0415 — deliberately lazy optional extra
+ except ImportError as exc:
+ raise ImportError(
+ "PostgresStore requires the 'psycopg' driver, which is not "
+ "installed. Install it with: pip install "
+ "personal-jarvis[ultrawiki-postgres]. The SQLite backend keeps "
+ "working without it."
+ ) from exc
+ return psycopg
+
+
+def _iso_utc(moment: datetime | None = None) -> str:
+ """Canonical ISO-8601 UTC second-precision string (lexicographically
+ ordered, so TEXT comparisons in SQL behave like time comparisons)."""
+ dt = moment if moment is not None else datetime.now(UTC)
+ return dt.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%SZ")
+
+
+def _coerce_now(now: str | datetime | None) -> datetime:
+ if now is None:
+ return datetime.now(UTC)
+ if isinstance(now, datetime):
+ return now if now.tzinfo is not None else now.replace(tzinfo=UTC)
+ parsed = datetime.fromisoformat(now.replace("Z", "+00:00"))
+ return parsed if parsed.tzinfo is not None else parsed.replace(tzinfo=UTC)
+
+
+def _coerce_state(state: ItemState | str) -> ItemState:
+ try:
+ return ItemState(state)
+ except ValueError as exc:
+ valid = ", ".join(s.value for s in ItemState)
+ raise ValueError(f"unknown item state {state!r} (valid: {valid})") from exc
+
+
+def _predecessor_of(target: ItemState | str) -> ItemState:
+ coerced = _coerce_state(target)
+ try:
+ index = STATE_ORDER.index(coerced)
+ except ValueError:
+ raise ValueError(
+ f"cannot claim toward {coerced.value!r} — it is outside the "
+ "forward state ladder"
+ ) from None
+ if index == 0:
+ raise ValueError(
+ "cannot claim toward 'captured' — items enter that state via "
+ "upsert_items, not a worker transition"
+ )
+ return STATE_ORDER[index - 1]
+
+
+def _retry_delay_s(attempts_before: int) -> int:
+ return min(BACKOFF_BASE_S * 4 ** max(0, attempts_before), BACKOFF_CAP_S)
+
+
+def _content_identity(item: RawItem) -> str:
+ """Content hash driving change detection (title + body)."""
+ return content_hash_for(item.title, item.body)
+
+
+def _fts_match_expr(query: str) -> str:
+ """OR-combined quoted tokens; quoting neutralizes FTS5 operators."""
+ tokens = [_FTS_QUOTE_STRIP_RE.sub("", tok) for tok in query.split() if tok.strip()]
+ return " OR ".join(f'"{tok}"' for tok in tokens if tok)
+
+
+def _normalize_bm25(raw: float) -> float:
+ """FTS5 bm25 (lower = better, usually negative) -> [0, 1] higher-is-better."""
+ return 1.0 / (1.0 + max(0.0, float(raw)))
+
+
+def _distance_score(distance: float) -> float:
+ """Monotonic distance -> [0, 1] score (works for cosine and L2)."""
+ return 1.0 / (1.0 + max(0.0, float(distance)))
+
+
+def _snippet_of(text: str) -> str:
+ collapsed = " ".join(text.split())
+ return collapsed[:_SNIPPET_CHARS]
+
+
+def _chunks(values: Sequence[Any], size: int = _IN_CHUNK) -> Iterable[Sequence[Any]]:
+ for start in range(0, len(values), size):
+ yield values[start : start + size]
+
+
+def _placeholders(count: int) -> str:
+ return ",".join("?" * count)
+
+
+def _counts_from_pairs(pairs: Iterable[tuple[str, int]]) -> PipelineCounts:
+ by_state = {state.value: 0 for state in ItemState}
+ for state_value, count in pairs:
+ if state_value in by_state:
+ by_state[state_value] = int(count)
+ return PipelineCounts(**by_state)
+
+
+_UNSET: Any = object()
+
+
+# ---------------------------------------------------------------------------
+# SQLite reference backend
+# ---------------------------------------------------------------------------
+
+
+class UltraStore:
+ """Async SQLite store for UltraWiki (the universal reference backend).
+
+ One instance = one ``aiosqlite`` connection, opened lazily on first use
+ (so the store can be constructed synchronously and opened on the right
+ event loop). Autocommit mode; multi-statement writes run inside explicit
+ ``BEGIN IMMEDIATE`` transactions serialized by an ``asyncio.Lock``.
+ """
+
+ def __init__(self, db_path: str | Path) -> None:
+ self._db_path = Path(db_path)
+ self._conn: aiosqlite.Connection | None = None
+ self._lock = asyncio.Lock()
+ # sqlite-vec bookkeeping (per instance / per connection).
+ self._vec_ext_loaded = False
+ self._vec_state: tuple[bool, str] | None = None
+ self._vec_dim: int | None = None
+
+ # -- lifecycle ---------------------------------------------------------
+
+ async def open(self) -> None:
+ """Open + apply the idempotent base schema and pending migrations."""
+ async with self._lock:
+ if self._conn is not None:
+ return
+ self._db_path.parent.mkdir(parents=True, exist_ok=True)
+ conn = await aiosqlite.connect(
+ self._db_path,
+ isolation_level=None, # autocommit — WAL is the lock manager
+ )
+ conn.row_factory = aiosqlite.Row
+ schema_sql = _SCHEMA_PATH.read_text(encoding="utf-8")
+ await conn.executescript(schema_sql)
+ from jarvis.memory.migration_runner import ( # noqa: PLC0415 — lazy
+ run_migrations,
+ )
+
+ await run_migrations(conn, directory=_MIGRATIONS_DIR)
+ self._conn = conn
+
+ async def close(self) -> None:
+ async with self._lock:
+ if self._conn is not None:
+ await self._conn.close()
+ self._conn = None
+ self._vec_ext_loaded = False
+ self._vec_state = None
+ self._vec_dim = None
+
+ async def _ensure_open(self) -> aiosqlite.Connection:
+ if self._conn is None:
+ await self.open()
+ assert self._conn is not None
+ return self._conn
+
+ @asynccontextmanager
+ async def _txn(self) -> AsyncIterator[aiosqlite.Connection]:
+ conn = await self._ensure_open()
+ async with self._lock:
+ await conn.execute("BEGIN IMMEDIATE")
+ try:
+ yield conn
+ except BaseException:
+ await conn.execute("ROLLBACK")
+ raise
+ else:
+ await conn.execute("COMMIT")
+
+ @staticmethod
+ async def _fetchall(
+ conn: aiosqlite.Connection, sql: str, params: Sequence[Any] = ()
+ ) -> list[aiosqlite.Row]:
+ cur = await conn.execute(sql, params)
+ rows = await cur.fetchall()
+ await cur.close()
+ return list(rows)
+
+ @staticmethod
+ async def _fetchone(
+ conn: aiosqlite.Connection, sql: str, params: Sequence[Any] = ()
+ ) -> aiosqlite.Row | None:
+ cur = await conn.execute(sql, params)
+ row = await cur.fetchone()
+ await cur.close()
+ return row
+
+ # -- sources & consent -------------------------------------------------
+
+ async def upsert_source(
+ self,
+ source_id: str,
+ *,
+ connector: str,
+ label: str,
+ config: dict[str, Any] | None = None,
+ areas: list[str] | None = None,
+ ) -> None:
+ """Create or update a configured source.
+
+ Consent and enablement are user-granted state and are NEVER reset by
+ an upsert; ``config``/``areas`` of ``None`` keep the existing values
+ on update.
+ """
+ now = _iso_utc()
+ async with self._txn() as conn:
+ row = await self._fetchone(
+ conn, "SELECT id FROM uw_sources WHERE id = ?", (source_id,)
+ )
+ if row is None:
+ await conn.execute(
+ "INSERT INTO uw_sources"
+ " (id, connector, label, config_json, areas_json, created_at)"
+ " VALUES (?, ?, ?, ?, ?, ?)",
+ (
+ source_id,
+ connector,
+ label,
+ json.dumps(config or {}),
+ json.dumps(areas or []),
+ now,
+ ),
+ )
+ else:
+ sets = ["connector = ?", "label = ?"]
+ params: list[Any] = [connector, label]
+ if config is not None:
+ sets.append("config_json = ?")
+ params.append(json.dumps(config))
+ if areas is not None:
+ sets.append("areas_json = ?")
+ params.append(json.dumps(areas))
+ params.append(source_id)
+ await conn.execute(
+ f"UPDATE uw_sources SET {', '.join(sets)} WHERE id = ?", # noqa: S608 — column list is a code-owned literal
+ params,
+ )
+
+ @staticmethod
+ def _source_row_to_dict(row: aiosqlite.Row) -> dict[str, Any]:
+ return {
+ "id": row["id"],
+ "connector": row["connector"],
+ "label": row["label"],
+ "config": json.loads(row["config_json"] or "{}"),
+ "areas": json.loads(row["areas_json"] or "[]"),
+ "consent": row["consent"],
+ "enabled": bool(row["enabled"]),
+ "created_at": row["created_at"],
+ "last_sync_at": row["last_sync_at"],
+ "last_error": row["last_error"],
+ }
+
+ async def get_source(self, source_id: str) -> dict[str, Any] | None:
+ conn = await self._ensure_open()
+ row = await self._fetchone(
+ conn, "SELECT * FROM uw_sources WHERE id = ?", (source_id,)
+ )
+ return None if row is None else self._source_row_to_dict(row)
+
+ async def list_sources(self) -> list[dict[str, Any]]:
+ """All sources with per-source pipeline counts and sync state."""
+ conn = await self._ensure_open()
+ rows = await self._fetchall(conn, "SELECT * FROM uw_sources ORDER BY id")
+ count_rows = await self._fetchall(
+ conn,
+ "SELECT source_id, state, COUNT(*) AS n FROM uw_items"
+ " WHERE deleted_at IS NULL GROUP BY source_id, state",
+ )
+ per_source: dict[str, list[tuple[str, int]]] = {}
+ for crow in count_rows:
+ per_source.setdefault(crow["source_id"], []).append(
+ (crow["state"], crow["n"])
+ )
+ sync_rows = await self._fetchall(conn, "SELECT * FROM uw_sync_state")
+ sync_by_id = {srow["source_id"]: dict(srow) for srow in sync_rows}
+ result = []
+ for row in rows:
+ entry = self._source_row_to_dict(row)
+ entry["counts"] = _counts_from_pairs(per_source.get(row["id"], []))
+ sync = sync_by_id.get(row["id"])
+ if sync is not None:
+ sync.pop("source_id", None)
+ entry["sync_state"] = sync
+ result.append(entry)
+ return result
+
+ async def set_consent(self, source_id: str, consent: ConsentState | str) -> None:
+ value = ConsentState(consent).value
+ conn = await self._ensure_open()
+ await conn.execute(
+ "UPDATE uw_sources SET consent = ? WHERE id = ?", (value, source_id)
+ )
+
+ async def set_enabled(self, source_id: str, enabled: bool) -> None:
+ conn = await self._ensure_open()
+ await conn.execute(
+ "UPDATE uw_sources SET enabled = ? WHERE id = ?",
+ (1 if enabled else 0, source_id),
+ )
+
+ async def set_source_status(
+ self,
+ source_id: str,
+ *,
+ last_sync_at: str | None = _UNSET,
+ last_error: str | None = _UNSET,
+ ) -> None:
+ """Partial update of the per-source sync status columns."""
+ sets: list[str] = []
+ params: list[Any] = []
+ if last_sync_at is not _UNSET:
+ sets.append("last_sync_at = ?")
+ params.append(last_sync_at)
+ if last_error is not _UNSET:
+ sets.append("last_error = ?")
+ params.append(last_error)
+ if not sets:
+ return
+ params.append(source_id)
+ conn = await self._ensure_open()
+ await conn.execute(
+ f"UPDATE uw_sources SET {', '.join(sets)} WHERE id = ?", # noqa: S608 — column list is a code-owned literal
+ params,
+ )
+
+ async def delete_source(self, source_id: str, *, purge: bool) -> None:
+ """Remove a source.
+
+ ``purge=True`` deletes the source and EVERY derived row (items,
+ documents, embeddings, FTS and vector entries, sync state).
+ ``purge=False`` disconnects only: consent is revoked and the source
+ disabled, but captured data stays in the store (the schema's
+ ``ON DELETE CASCADE`` makes a row delete inherently purging, so a
+ keep-the-data delete must keep the source row).
+ """
+ if not purge:
+ conn = await self._ensure_open()
+ await conn.execute(
+ "UPDATE uw_sources SET consent = ?, enabled = 0 WHERE id = ?",
+ (ConsentState.REVOKED.value, source_id),
+ )
+ return
+ async with self._txn() as conn:
+ rows = await self._fetchall(
+ conn, "SELECT id FROM uw_items WHERE source_id = ?", (source_id,)
+ )
+ await self._purge_derived(conn, [row["id"] for row in rows])
+ await conn.execute("DELETE FROM uw_sources WHERE id = ?", (source_id,))
+
+ # -- items: the staged state machine -----------------------------------
+
+ async def upsert_items(
+ self, source_id: str, items: Sequence[RawItem]
+ ) -> UpsertCounts:
+ """Idempotent batch upsert on ``UNIQUE (source_id, external_id)``.
+
+ - Unchanged content hash: the stored row is left completely
+ untouched (zero new work — roadmap gate P1c).
+ - Changed content: the row resets to ``captured`` and every stale
+ derived row (FTS, documents, embeddings, vector entries) is
+ removed in the same transaction.
+ - ``RawItem.deleted=True``: tombstone (``deleted_at`` set, derived
+ rows removed). Unknown deleted external ids are ignored.
+
+ The whole batch is ONE transaction: a crash mid-batch rolls back to
+ the previous consistent state and the re-run converges (gate P1a).
+ """
+ source = await self.get_source(source_id)
+ if source is None:
+ raise UltraStoreError(
+ f"unknown source {source_id!r} — call upsert_source() first"
+ )
+ areas_json = json.dumps(source["areas"])
+ now = _iso_utc()
+ new = changed = unchanged = tombstoned = 0
+ async with self._txn() as conn:
+ for item in items:
+ row = await self._fetchone(
+ conn,
+ "SELECT id, content_hash, deleted_at FROM uw_items"
+ " WHERE source_id = ? AND external_id = ?",
+ (source_id, item.external_id),
+ )
+ if item.deleted:
+ if row is not None and row["deleted_at"] is None:
+ await self._purge_derived(conn, [row["id"]])
+ await conn.execute(
+ "UPDATE uw_items SET deleted_at = ?, updated_at = ?"
+ " WHERE id = ?",
+ (now, now, row["id"]),
+ )
+ tombstoned += 1
+ continue
+ identity = _content_identity(item)
+ if row is None:
+ await conn.execute(
+ "INSERT INTO uw_items"
+ " (source_id, external_id, thread_key, author_raw, title,"
+ " body_raw, permalink, timestamp_utc, areas_json,"
+ " content_hash, state, created_at, updated_at)"
+ " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
+ (
+ source_id,
+ item.external_id,
+ item.thread_key,
+ item.author_raw,
+ item.title,
+ item.body,
+ item.permalink,
+ item.timestamp_utc,
+ areas_json,
+ identity,
+ ItemState.CAPTURED.value,
+ now,
+ now,
+ ),
+ )
+ new += 1
+ elif row["content_hash"] == identity and row["deleted_at"] is None:
+ unchanged += 1
+ else:
+ # Changed content (or a resurrected tombstone): reset to
+ # captured and drop every stale derived row.
+ await self._purge_derived(conn, [row["id"]])
+ await conn.execute(
+ "UPDATE uw_items SET thread_key = ?, author_raw = ?,"
+ " title = ?, body_raw = ?, permalink = ?,"
+ " timestamp_utc = ?, areas_json = ?, content_hash = ?,"
+ " state = ?, attempt_count = 0, next_retry_at = NULL,"
+ " last_error = NULL, deleted_at = NULL, updated_at = ?"
+ " WHERE id = ?",
+ (
+ item.thread_key,
+ item.author_raw,
+ item.title,
+ item.body,
+ item.permalink,
+ item.timestamp_utc,
+ areas_json,
+ identity,
+ ItemState.CAPTURED.value,
+ now,
+ row["id"],
+ ),
+ )
+ changed += 1
+ return UpsertCounts(
+ new=new, changed=changed, unchanged=unchanged, tombstoned=tombstoned
+ )
+
+ async def _purge_derived(
+ self, conn: aiosqlite.Connection, item_ids: Sequence[int]
+ ) -> None:
+ """Remove FTS rows, documents (cascading embeddings) and — when the
+ vec index is live on this connection — vector rows for *item_ids*.
+
+ Vector rows a session without the extension cannot delete are
+ reconciled on the next :meth:`_ensure_vec` (stale-row sweep).
+ """
+ if not item_ids:
+ return
+ for chunk in _chunks(list(item_ids)):
+ marks = _placeholders(len(chunk))
+ await conn.execute(
+ f"DELETE FROM uw_fts WHERE item_id IN ({marks})", # noqa: S608 — placeholders only
+ chunk,
+ )
+ doc_rows = await self._fetchall(
+ conn,
+ f"SELECT id FROM uw_documents WHERE item_id IN ({marks})", # noqa: S608 — placeholders only
+ chunk,
+ )
+ doc_ids = [doc["id"] for doc in doc_rows]
+ if doc_ids and self._vec_state is not None and self._vec_state[0]:
+ for doc_chunk in _chunks(doc_ids):
+ await conn.execute(
+ f"DELETE FROM uw_vec WHERE rowid IN ({_placeholders(len(doc_chunk))})", # noqa: S608 — placeholders only
+ doc_chunk,
+ )
+ await conn.execute(
+ f"DELETE FROM uw_documents WHERE item_id IN ({marks})", # noqa: S608 — placeholders only
+ chunk,
+ )
+
+ @staticmethod
+ def _item_row_to_dict(row: aiosqlite.Row) -> dict[str, Any]:
+ return {
+ "id": row["id"],
+ "source_id": row["source_id"],
+ "external_id": row["external_id"],
+ "thread_key": row["thread_key"],
+ "author_raw": row["author_raw"],
+ "title": row["title"],
+ "body_raw": row["body_raw"],
+ "permalink": row["permalink"],
+ "timestamp_utc": row["timestamp_utc"],
+ "areas": json.loads(row["areas_json"] or "[]"),
+ "content_hash": row["content_hash"],
+ "state": row["state"],
+ "attempt_count": row["attempt_count"],
+ "next_retry_at": row["next_retry_at"],
+ "last_error": row["last_error"],
+ "deleted_at": row["deleted_at"],
+ "created_at": row["created_at"],
+ "updated_at": row["updated_at"],
+ }
+
+ async def get_item(self, item_id: int) -> dict[str, Any] | None:
+ conn = await self._ensure_open()
+ row = await self._fetchone(
+ conn, "SELECT * FROM uw_items WHERE id = ?", (item_id,)
+ )
+ return None if row is None else self._item_row_to_dict(row)
+
+ async def get_item_by_external_id(
+ self, source_id: str, external_id: str
+ ) -> dict[str, Any] | None:
+ conn = await self._ensure_open()
+ row = await self._fetchone(
+ conn,
+ "SELECT * FROM uw_items WHERE source_id = ? AND external_id = ?",
+ (source_id, external_id),
+ )
+ return None if row is None else self._item_row_to_dict(row)
+
+ async def claim_batch(
+ self,
+ target_state: ItemState | str,
+ *,
+ limit: int = 50,
+ now: str | datetime | None = None,
+ ) -> list[dict[str, Any]]:
+ """Items ready to advance TO *target_state* (their state is the
+ predecessor in ``STATE_ORDER``), retry-eligible, newest first.
+
+ Claiming is read-only — the single-process pipeline claims, works,
+ then commits exactly one transition via :meth:`mark_stage_done` /
+ :meth:`mark_retry`, so a crash between claim and commit loses
+ nothing (the item is simply claimed again).
+ """
+ predecessor = _predecessor_of(target_state)
+ now_s = _iso_utc(_coerce_now(now))
+ conn = await self._ensure_open()
+ rows = await self._fetchall(
+ conn,
+ "SELECT * FROM uw_items"
+ " WHERE state = ? AND deleted_at IS NULL"
+ " AND (next_retry_at IS NULL OR next_retry_at <= ?)"
+ " ORDER BY timestamp_utc DESC, id DESC LIMIT ?",
+ (predecessor.value, now_s, int(limit)),
+ )
+ return [self._item_row_to_dict(row) for row in rows]
+
+ async def mark_stage_done(
+ self,
+ item_id: int,
+ new_state: ItemState | str,
+ *,
+ fts_title: str | None = None,
+ fts_body: str | None = None,
+ ) -> None:
+ """Commit one state transition; retry bookkeeping resets.
+
+ For the keyword stage the FTS delete+insert happens in the SAME
+ transaction as the state transition (pass ``fts_title``/``fts_body``)
+ so the index can never drift from the state column.
+ """
+ state = _coerce_state(new_state)
+ if state not in STATE_ORDER or state is ItemState.CAPTURED:
+ raise ValueError(
+ f"mark_stage_done cannot set {state.value!r} — only forward "
+ "stages after 'captured' are worker transitions"
+ )
+ now = _iso_utc()
+ async with self._txn() as conn:
+ await conn.execute(
+ "UPDATE uw_items SET state = ?, attempt_count = 0,"
+ " next_retry_at = NULL, last_error = NULL, updated_at = ?"
+ " WHERE id = ?",
+ (state.value, now, item_id),
+ )
+ if fts_body is not None or fts_title is not None:
+ await conn.execute(
+ "DELETE FROM uw_fts WHERE item_id = ?", (item_id,)
+ )
+ await conn.execute(
+ "INSERT INTO uw_fts (item_id, title, body) VALUES (?, ?, ?)",
+ (item_id, fts_title or "", fts_body or ""),
+ )
+
+ async def mark_retry(
+ self,
+ item_id: int,
+ error: str,
+ *,
+ now: str | datetime | None = None,
+ ) -> None:
+ """Record a retryable stage failure.
+
+ Attempts 1..4 keep the last good state and schedule
+ ``next_retry_at = now + 60s * 4^(attempt-1)`` (capped at 6h); the
+ 5th failure dead-letters the item (state ``failed``).
+ """
+ moment = _coerce_now(now)
+ async with self._txn() as conn:
+ row = await self._fetchone(
+ conn,
+ "SELECT attempt_count FROM uw_items WHERE id = ?",
+ (item_id,),
+ )
+ if row is None:
+ return
+ attempts_before = int(row["attempt_count"])
+ new_count = attempts_before + 1
+ if new_count >= MAX_ATTEMPTS:
+ await conn.execute(
+ "UPDATE uw_items SET state = ?, attempt_count = ?,"
+ " next_retry_at = NULL, last_error = ?, updated_at = ?"
+ " WHERE id = ?",
+ (
+ ItemState.FAILED.value,
+ new_count,
+ error,
+ _iso_utc(moment),
+ item_id,
+ ),
+ )
+ else:
+ retry_at = moment + timedelta(seconds=_retry_delay_s(attempts_before))
+ await conn.execute(
+ "UPDATE uw_items SET attempt_count = ?, next_retry_at = ?,"
+ " last_error = ?, updated_at = ? WHERE id = ?",
+ (new_count, _iso_utc(retry_at), error, _iso_utc(moment), item_id),
+ )
+
+ async def mark_failed(self, item_id: int, error: str) -> None:
+ """Dead-letter an item immediately (non-retryable poison)."""
+ now = _iso_utc()
+ conn = await self._ensure_open()
+ await conn.execute(
+ "UPDATE uw_items SET state = ?, next_retry_at = NULL,"
+ " last_error = ?, updated_at = ? WHERE id = ?",
+ (ItemState.FAILED.value, error, now, item_id),
+ )
+
+ async def counts(self) -> PipelineCounts:
+ """Per-stage backlog counts over live (non-tombstoned) items."""
+ conn = await self._ensure_open()
+ rows = await self._fetchall(
+ conn,
+ "SELECT state, COUNT(*) AS n FROM uw_items"
+ " WHERE deleted_at IS NULL GROUP BY state",
+ )
+ return _counts_from_pairs((row["state"], row["n"]) for row in rows)
+
+ async def counts_for_source(self, source_id: str) -> PipelineCounts:
+ conn = await self._ensure_open()
+ rows = await self._fetchall(
+ conn,
+ "SELECT state, COUNT(*) AS n FROM uw_items"
+ " WHERE deleted_at IS NULL AND source_id = ? GROUP BY state",
+ (source_id,),
+ )
+ return _counts_from_pairs((row["state"], row["n"]) for row in rows)
+
+ async def reconcile_deletes(
+ self, source_id: str, yielded_external_ids: set[str]
+ ) -> int:
+ """Tombstone every stored live item of *source_id* that a FULL
+ backfill did not yield (connectors emit no tombstones — delete
+ detection is runtime-side, connector convention). Returns the number
+ of items tombstoned.
+ """
+ now = _iso_utc()
+ async with self._txn() as conn:
+ rows = await self._fetchall(
+ conn,
+ "SELECT id, external_id FROM uw_items"
+ " WHERE source_id = ? AND deleted_at IS NULL",
+ (source_id,),
+ )
+ doomed = [
+ row["id"]
+ for row in rows
+ if row["external_id"] not in yielded_external_ids
+ ]
+ if doomed:
+ await self._purge_derived(conn, doomed)
+ for chunk in _chunks(doomed):
+ await conn.execute(
+ f"UPDATE uw_items SET deleted_at = ?, updated_at = ?" # noqa: S608 — placeholders only
+ f" WHERE id IN ({_placeholders(len(chunk))})",
+ [now, now, *chunk],
+ )
+ return len(doomed)
+
+ # -- documents & vectors ------------------------------------------------
+
+ async def add_document(
+ self,
+ item_id: int,
+ doc_type: DocType | str,
+ text_norm: str,
+ *,
+ distill_json: str | None = None,
+ distill_version: int = 0,
+ content_hash: str = "",
+ ) -> int:
+ """Insert a derived document, replacing any existing document of the
+ same ``(item_id, doc_type)``. Returns the new document id."""
+ kind = DocType(doc_type).value
+ now = _iso_utc()
+ async with self._txn() as conn:
+ old_rows = await self._fetchall(
+ conn,
+ "SELECT id FROM uw_documents WHERE item_id = ? AND doc_type = ?",
+ (item_id, kind),
+ )
+ old_ids = [row["id"] for row in old_rows]
+ if old_ids and self._vec_state is not None and self._vec_state[0]:
+ for chunk in _chunks(old_ids):
+ await conn.execute(
+ f"DELETE FROM uw_vec WHERE rowid IN ({_placeholders(len(chunk))})", # noqa: S608 — placeholders only
+ chunk,
+ )
+ if old_ids:
+ await conn.execute(
+ "DELETE FROM uw_documents WHERE item_id = ? AND doc_type = ?",
+ (item_id, kind),
+ )
+ cur = await conn.execute(
+ "INSERT INTO uw_documents (item_id, doc_type, text_norm,"
+ " distill_json, distill_version, content_hash, created_at)"
+ " VALUES (?, ?, ?, ?, ?, ?, ?) RETURNING id",
+ (
+ item_id,
+ kind,
+ text_norm,
+ distill_json,
+ int(distill_version),
+ content_hash,
+ now,
+ ),
+ )
+ row = await cur.fetchone()
+ await cur.close()
+ assert row is not None
+ return int(row[0])
+
+ async def _pinned_space(self) -> tuple[str | None, int | None]:
+ model = await self.get_meta(META_EMBED_MODEL)
+ dim_raw = await self.get_meta(META_EMBED_DIM)
+ return model, int(dim_raw) if dim_raw else None
+
+ async def store_embedding(
+ self,
+ document_id: int,
+ *,
+ model: str,
+ dim: int,
+ vector: Sequence[float],
+ ) -> None:
+ """Store one vector (little-endian float32 BLOB) for a document.
+
+ The first embedding pins ``embed_model``/``embed_dim`` in
+ ``uw_meta`` (semi-permanent, D-3); later writes with a different
+ model or dimension are rejected with a clear error — changing the
+ embedding space goes through :meth:`reset_vectors`.
+ """
+ if len(vector) != dim:
+ raise UltraStoreError(
+ f"vector has {len(vector)} components but dim={dim} was declared"
+ )
+ pinned_model, pinned_dim = await self._pinned_space()
+ if pinned_model is None or pinned_dim is None:
+ await self.set_meta(META_EMBED_MODEL, model)
+ await self.set_meta(META_EMBED_DIM, str(dim))
+ elif pinned_model != model or pinned_dim != dim:
+ raise UltraStoreError(
+ "embedding space mismatch: the store is pinned to "
+ f"model={pinned_model!r} dim={pinned_dim} but got "
+ f"model={model!r} dim={dim}. Changing the embedding model "
+ "requires reset_vectors() (re-embeds the corpus)."
+ )
+ vec_ok, _ = await self._ensure_vec(dim)
+ blob = pack_vector(vector)
+ now = _iso_utc()
+ async with self._txn() as conn:
+ await conn.execute(
+ "INSERT OR REPLACE INTO uw_embeddings"
+ " (document_id, model, dim, vector, created_at)"
+ " VALUES (?, ?, ?, ?, ?)",
+ (document_id, model, dim, blob, now),
+ )
+ if vec_ok:
+ await conn.execute(
+ "INSERT OR REPLACE INTO uw_vec (rowid, embedding) VALUES (?, ?)",
+ (document_id, blob),
+ )
+
+ async def _ensure_vec(self, dim: int | None) -> tuple[bool, str]:
+ """Lazily derive the sqlite-vec ``vec0`` index from ``uw_embeddings``.
+
+ Returns ``(usable, honest_reason_if_not)``. The probe result is
+ cached per instance; a host that gains the extension later gets the
+ index (and a backfill of every stored vector) on the next store
+ instance without re-embedding anything.
+ """
+ if dim is None:
+ _, dim = await self._pinned_space()
+ if dim is None:
+ return (
+ False,
+ "no embedding has been stored yet — the vector index is "
+ "created with the first embedding",
+ )
+ if self._vec_state is not None and self._vec_dim == dim:
+ return self._vec_state
+ conn = await self._ensure_open()
+ if not self._vec_ext_loaded:
+ try:
+ vec_mod = _import_sqlite_vec()
+ except ImportError as exc:
+ self._vec_state = (
+ False,
+ "semantic vector search is disabled: the sqlite-vec "
+ f"extension is not installed ({exc}). Keyword search "
+ "keeps working; install the 'sqlite-vec' package to "
+ "enable vectors — stored embeddings are kept and will "
+ "be indexed automatically.",
+ )
+ self._vec_dim = dim
+ return self._vec_state
+ try:
+ await conn.enable_load_extension(True)
+ await conn.load_extension(vec_mod.loadable_path())
+ await conn.enable_load_extension(False)
+ except Exception as exc: # pragma: no cover — build-specific
+ self._vec_state = (
+ False,
+ "semantic vector search is disabled: this Python's "
+ f"SQLite cannot load the sqlite-vec extension ({exc}). "
+ "Keyword search keeps working.",
+ )
+ self._vec_dim = dim
+ return self._vec_state
+ self._vec_ext_loaded = True
+ async with self._lock:
+ # Recreate the index when the pinned dimension changed.
+ existing = await self._fetchone(
+ conn,
+ "SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'uw_vec'",
+ )
+ if existing is not None:
+ match = re.search(r"float\[(\d+)\]", existing["sql"] or "")
+ if match and int(match.group(1)) != dim:
+ await conn.execute("DROP TABLE uw_vec")
+ existing = None
+ if existing is None:
+ await conn.execute(
+ "CREATE VIRTUAL TABLE uw_vec USING vec0"
+ f"(embedding float[{int(dim)}] distance_metric=cosine)"
+ )
+ # Sweep rows a no-extension session could not delete, then
+ # backfill vectors the index does not hold yet.
+ await conn.execute(
+ "DELETE FROM uw_vec WHERE rowid NOT IN"
+ " (SELECT document_id FROM uw_embeddings)"
+ )
+ missing = await self._fetchall(
+ conn,
+ "SELECT document_id, vector FROM uw_embeddings"
+ " WHERE document_id NOT IN (SELECT rowid FROM uw_vec)",
+ )
+ for row in missing:
+ await conn.execute(
+ "INSERT OR REPLACE INTO uw_vec (rowid, embedding) VALUES (?, ?)",
+ (row["document_id"], row["vector"]),
+ )
+ self._vec_dim = dim
+ self._vec_state = (True, "")
+ return self._vec_state
+
+ async def vector_status(self) -> tuple[bool, str]:
+ """Honest capability report for the vector leg."""
+ return await self._ensure_vec(None)
+
+ async def reset_vectors(self) -> None:
+ """The embedding-model-change path: wipe the vector index and every
+ stored embedding, clear the ``embed_model``/``embed_dim`` pin, and
+ reset ``embedded``/``distilled`` items to ``keyword_indexed`` so the
+ pipeline re-embeds (re-distillation rides the distill cache).
+ Derived documents keep their text; only vectors are discarded.
+ """
+ vec_droppable = self._vec_ext_loaded # vec0 DDL needs the extension
+ async with self._txn() as conn:
+ if vec_droppable:
+ await conn.execute("DROP TABLE IF EXISTS uw_vec")
+ await conn.execute("DELETE FROM uw_embeddings")
+ await conn.execute(
+ "DELETE FROM uw_meta WHERE key IN (?, ?)",
+ (META_EMBED_MODEL, META_EMBED_DIM),
+ )
+ await conn.execute(
+ "UPDATE uw_items SET state = ?, updated_at = ? WHERE state IN (?, ?)",
+ (
+ ItemState.KEYWORD_INDEXED.value,
+ _iso_utc(),
+ ItemState.EMBEDDED.value,
+ ItemState.DISTILLED.value,
+ ),
+ )
+ self._vec_state = None
+ self._vec_dim = None
+
+ # -- search legs (SQL only, fusion lives in the read path) --------------
+
+ async def keyword_search(
+ self, query: str, k: int = 10, *, area_id: str | None = None
+ ) -> list[SearchResult]:
+ """FTS5 keyword leg over live items; bm25 normalized to [0, 1]."""
+ match_expr = _fts_match_expr(query)
+ if not match_expr:
+ return []
+ conn = await self._ensure_open()
+ sql = (
+ "SELECT uw_fts.item_id AS item_id, i.source_id AS source_id,"
+ " i.title AS title,"
+ " snippet(uw_fts, 2, '', '', '…', 32) AS snip,"
+ " i.permalink AS permalink, i.timestamp_utc AS timestamp_utc,"
+ " bm25(uw_fts, 0.0, 3.0, 1.0) AS raw_score"
+ " FROM uw_fts JOIN uw_items i ON i.id = uw_fts.item_id"
+ " WHERE uw_fts MATCH ? AND i.deleted_at IS NULL"
+ )
+ params: list[Any] = [match_expr]
+ if area_id is not None:
+ sql += (
+ " AND EXISTS (SELECT 1 FROM json_each(i.areas_json)"
+ " WHERE json_each.value = ?)"
+ )
+ params.append(area_id)
+ sql += " ORDER BY raw_score LIMIT ?"
+ params.append(int(k))
+ rows = await self._fetchall(conn, sql, params)
+ return [
+ SearchResult(
+ item_id=int(row["item_id"]),
+ source_id=row["source_id"],
+ title=row["title"],
+ snippet=row["snip"] or "",
+ permalink=row["permalink"],
+ timestamp_utc=row["timestamp_utc"],
+ score=round(_normalize_bm25(row["raw_score"]), 4),
+ matched_by=("keyword",),
+ )
+ for row in rows
+ ]
+
+ async def vector_search(
+ self,
+ query_vector: Sequence[float],
+ k: int = 10,
+ *,
+ area_id: str | None = None,
+ ) -> tuple[list[SearchResult], str]:
+ """ANN leg via the derived ``uw_vec`` index.
+
+ Returns ``(results, reason)`` — ``reason`` is an empty string on the
+ healthy path and an honest English explanation whenever the vector
+ leg is degraded (extension unavailable, nothing embedded yet, or a
+ query-vector/pin mismatch).
+ """
+ ok, reason = await self._ensure_vec(None)
+ if not ok:
+ return [], reason
+ assert self._vec_dim is not None
+ if len(query_vector) != self._vec_dim:
+ return [], (
+ f"query vector has {len(query_vector)} components but the "
+ f"store's embedding space is pinned to dim={self._vec_dim}"
+ )
+ conn = await self._ensure_open()
+ fetch_k = min(max(int(k) * 4, int(k) + 8), 200)
+ knn_rows = await self._fetchall(
+ conn,
+ "SELECT rowid, distance FROM uw_vec WHERE embedding MATCH ? AND k = ?",
+ (pack_vector(query_vector), fetch_k),
+ )
+ if not knn_rows:
+ return [], ""
+ distance_by_doc = {int(row["rowid"]): float(row["distance"]) for row in knn_rows}
+ doc_ids = list(distance_by_doc)
+ joined: list[tuple[float, aiosqlite.Row]] = []
+ for chunk in _chunks(doc_ids):
+ sql = (
+ "SELECT d.id AS doc_id, d.text_norm AS text_norm," # noqa: S608 — the interpolation below is placeholder marks only
+ " i.id AS item_id, i.source_id AS source_id, i.title AS title,"
+ " i.permalink AS permalink, i.timestamp_utc AS timestamp_utc"
+ " FROM uw_documents d JOIN uw_items i ON i.id = d.item_id"
+ f" WHERE d.id IN ({_placeholders(len(chunk))})"
+ " AND i.deleted_at IS NULL"
+ )
+ params = list(chunk)
+ if area_id is not None:
+ sql += (
+ " AND EXISTS (SELECT 1 FROM json_each(i.areas_json)"
+ " WHERE json_each.value = ?)"
+ )
+ params.append(area_id)
+ for row in await self._fetchall(conn, sql, params):
+ joined.append((distance_by_doc[int(row["doc_id"])], row))
+ joined.sort(key=lambda pair: pair[0])
+ results: list[SearchResult] = []
+ seen_items: set[int] = set()
+ for distance, row in joined:
+ item_id = int(row["item_id"])
+ if item_id in seen_items:
+ continue # dedupe multiple documents of one item to the best
+ seen_items.add(item_id)
+ results.append(
+ SearchResult(
+ item_id=item_id,
+ source_id=row["source_id"],
+ title=row["title"],
+ snippet=_snippet_of(row["text_norm"]),
+ permalink=row["permalink"],
+ timestamp_utc=row["timestamp_utc"],
+ score=round(_distance_score(distance), 4),
+ matched_by=("vector",),
+ )
+ )
+ if len(results) >= int(k):
+ break
+ return results, ""
+
+ # -- sync state ----------------------------------------------------------
+
+ async def get_sync_state(self, source_id: str) -> dict[str, Any] | None:
+ conn = await self._ensure_open()
+ row = await self._fetchone(
+ conn, "SELECT * FROM uw_sync_state WHERE source_id = ?", (source_id,)
+ )
+ if row is None:
+ return None
+ result = dict(row)
+ result.pop("source_id", None)
+ return result
+
+ async def set_sync_state(
+ self,
+ source_id: str,
+ *,
+ cursor: str | None = _UNSET,
+ backfill_checkpoint: str | None = _UNSET,
+ backfill_complete_at: str | None = _UNSET,
+ last_success_at: str | None = _UNSET,
+ ) -> None:
+ """Partial upsert of the per-source cursor/checkpoint bookkeeping."""
+ fields = {
+ "cursor": cursor,
+ "backfill_checkpoint": backfill_checkpoint,
+ "backfill_complete_at": backfill_complete_at,
+ "last_success_at": last_success_at,
+ }
+ updates = {name: value for name, value in fields.items() if value is not _UNSET}
+ async with self._txn() as conn:
+ await conn.execute(
+ "INSERT OR IGNORE INTO uw_sync_state (source_id) VALUES (?)",
+ (source_id,),
+ )
+ if updates:
+ sets = ", ".join(f'"{name}" = ?' for name in updates)
+ await conn.execute(
+ f"UPDATE uw_sync_state SET {sets} WHERE source_id = ?", # noqa: S608 — column names are code-owned literals
+ [*updates.values(), source_id],
+ )
+
+ # -- areas ---------------------------------------------------------------
+
+ async def upsert_area(
+ self, area_id: str, name: str, *, is_default: bool = False
+ ) -> None:
+ """Create or rename an area; ``is_default=True`` claims the single
+ default slot (clearing it from every other area)."""
+ now = _iso_utc()
+ async with self._txn() as conn:
+ if is_default:
+ await conn.execute("UPDATE uw_areas SET is_default = 0")
+ await conn.execute(
+ "INSERT INTO uw_areas (id, name, is_default, created_at)"
+ " VALUES (?, ?, ?, ?)"
+ " ON CONFLICT(id) DO UPDATE SET name = excluded.name,"
+ " is_default = excluded.is_default",
+ (area_id, name, 1 if is_default else 0, now),
+ )
+
+ async def list_areas(self) -> list[dict[str, Any]]:
+ conn = await self._ensure_open()
+ rows = await self._fetchall(
+ conn, "SELECT * FROM uw_areas ORDER BY is_default DESC, id"
+ )
+ return [
+ {
+ "id": row["id"],
+ "name": row["name"],
+ "is_default": bool(row["is_default"]),
+ "created_at": row["created_at"],
+ }
+ for row in rows
+ ]
+
+ async def delete_area(self, area_id: str) -> None:
+ conn = await self._ensure_open()
+ await conn.execute("DELETE FROM uw_areas WHERE id = ?", (area_id,))
+
+ async def ensure_default_area(
+ self, area_id: str = "default", name: str = "Default"
+ ) -> str:
+ """Seed the default area when none exists; returns the default id."""
+ conn = await self._ensure_open()
+ row = await self._fetchone(
+ conn, "SELECT id FROM uw_areas WHERE is_default = 1 LIMIT 1"
+ )
+ if row is not None:
+ return str(row["id"])
+ await self.upsert_area(area_id, name, is_default=True)
+ return area_id
+
+ # -- distillation cache --------------------------------------------------
+
+ async def distill_cache_get(
+ self, content_hash: str, prompt_version: int, model: str
+ ) -> str | None:
+ conn = await self._ensure_open()
+ row = await self._fetchone(
+ conn,
+ "SELECT result_json FROM uw_distill_cache"
+ " WHERE content_hash = ? AND prompt_version = ? AND model = ?",
+ (content_hash, int(prompt_version), model),
+ )
+ return None if row is None else str(row["result_json"])
+
+ async def distill_cache_put(
+ self, content_hash: str, prompt_version: int, model: str, result_json: str
+ ) -> None:
+ conn = await self._ensure_open()
+ await conn.execute(
+ "INSERT OR REPLACE INTO uw_distill_cache"
+ " (content_hash, prompt_version, model, result_json, created_at)"
+ " VALUES (?, ?, ?, ?, ?)",
+ (content_hash, int(prompt_version), model, result_json, _iso_utc()),
+ )
+
+ # -- meta ----------------------------------------------------------------
+
+ async def get_meta(self, key: str) -> str | None:
+ conn = await self._ensure_open()
+ row = await self._fetchone(
+ conn, "SELECT value FROM uw_meta WHERE key = ?", (key,)
+ )
+ return None if row is None else str(row["value"])
+
+ async def set_meta(self, key: str, value: str) -> None:
+ conn = await self._ensure_open()
+ await conn.execute(
+ "INSERT OR REPLACE INTO uw_meta (key, value) VALUES (?, ?)",
+ (key, value),
+ )
+
+
+# ---------------------------------------------------------------------------
+# Postgres variant (same public interface)
+# ---------------------------------------------------------------------------
+
+
+class PostgresStore:
+ """Postgres backend behind the same public surface as :class:`UltraStore`.
+
+ - The keyword leg is a generated ``tsvector`` column with a GIN index,
+ so :meth:`mark_stage_done` accepts and ignores the ``fts_*`` arguments
+ (the index follows ``title``/``body_raw`` automatically).
+ - The vector leg is pgvector: ``CREATE EXTENSION IF NOT EXISTS vector``
+ is attempted lazily on first vector use and degrades honestly when the
+ server lacks the extension or the role lacks the privilege.
+ - The caller passes the RESOLVED connection string (it is a credential —
+ stored under the ``ultrawiki_db_url`` secret slot, never in config).
+
+ SQLite is the reference backend; this class mirrors its semantics.
+ """
+
+ def __init__(self, conn_str: str) -> None:
+ self._conn_str = conn_str
+ self._conn: Any = None
+ self._lock = asyncio.Lock()
+ self._vec_state: tuple[bool, str] | None = None
+ self._vec_dim: int | None = None
+
+ # -- DDL -----------------------------------------------------------------
+
+ @classmethod
+ def ddl_statements(cls) -> list[str]:
+ """Idempotent DDL derived from the logical schema (schema.sql).
+
+ CHECK value lists are DERIVED from the canonical enums in
+ ``jarvis/ultrawiki/types.py`` — never retyped (five-layer rule).
+ """
+ states = ", ".join(f"'{state.value}'" for state in ItemState)
+ consents = ", ".join(f"'{consent.value}'" for consent in ConsentState)
+ doc_types = ", ".join(f"'{doc.value}'" for doc in DocType)
+ return [
+ "CREATE TABLE IF NOT EXISTS uw_meta ("
+ " key TEXT PRIMARY KEY, value TEXT NOT NULL)",
+ "CREATE TABLE IF NOT EXISTS uw_areas ("
+ " id TEXT PRIMARY KEY, name TEXT NOT NULL,"
+ " is_default BOOLEAN NOT NULL DEFAULT FALSE,"
+ " created_at TEXT NOT NULL)",
+ "CREATE TABLE IF NOT EXISTS uw_sources ("
+ " id TEXT PRIMARY KEY, connector TEXT NOT NULL, label TEXT NOT NULL,"
+ " config_json TEXT NOT NULL DEFAULT '{}',"
+ " areas_json TEXT NOT NULL DEFAULT '[]',"
+ " consent TEXT NOT NULL DEFAULT 'pending'"
+ f" CHECK (consent IN ({consents})),"
+ " enabled BOOLEAN NOT NULL DEFAULT TRUE,"
+ " created_at TEXT NOT NULL, last_sync_at TEXT, last_error TEXT)",
+ "CREATE TABLE IF NOT EXISTS uw_sync_state ("
+ " source_id TEXT PRIMARY KEY"
+ " REFERENCES uw_sources(id) ON DELETE CASCADE,"
+ " cursor TEXT, backfill_checkpoint TEXT,"
+ " backfill_complete_at TEXT, last_success_at TEXT)",
+ "CREATE TABLE IF NOT EXISTS uw_items ("
+ " id BIGSERIAL PRIMARY KEY,"
+ " source_id TEXT NOT NULL REFERENCES uw_sources(id) ON DELETE CASCADE,"
+ " external_id TEXT NOT NULL,"
+ " thread_key TEXT NOT NULL DEFAULT '',"
+ " author_raw TEXT NOT NULL DEFAULT '',"
+ " title TEXT NOT NULL DEFAULT '',"
+ " body_raw TEXT NOT NULL, permalink TEXT NOT NULL,"
+ " timestamp_utc TEXT NOT NULL,"
+ " areas_json TEXT NOT NULL DEFAULT '[]',"
+ " content_hash TEXT NOT NULL,"
+ " state TEXT NOT NULL DEFAULT 'captured'"
+ f" CHECK (state IN ({states})),"
+ " attempt_count INTEGER NOT NULL DEFAULT 0,"
+ " next_retry_at TEXT, last_error TEXT, deleted_at TEXT,"
+ " created_at TEXT NOT NULL, updated_at TEXT NOT NULL,"
+ " search_tsv tsvector GENERATED ALWAYS AS"
+ " (to_tsvector('simple',"
+ " coalesce(title, '') || ' ' || coalesce(body_raw, ''))) STORED,"
+ " UNIQUE (source_id, external_id))",
+ "CREATE INDEX IF NOT EXISTS idx_uw_items_state"
+ " ON uw_items(state, next_retry_at)",
+ "CREATE INDEX IF NOT EXISTS idx_uw_items_source"
+ " ON uw_items(source_id, state)",
+ "CREATE INDEX IF NOT EXISTS idx_uw_items_time"
+ " ON uw_items(timestamp_utc)",
+ "CREATE INDEX IF NOT EXISTS idx_uw_items_tsv"
+ " ON uw_items USING GIN (search_tsv)",
+ "CREATE TABLE IF NOT EXISTS uw_documents ("
+ " id BIGSERIAL PRIMARY KEY,"
+ " item_id BIGINT NOT NULL REFERENCES uw_items(id) ON DELETE CASCADE,"
+ f" doc_type TEXT NOT NULL CHECK (doc_type IN ({doc_types})),"
+ " text_norm TEXT NOT NULL, distill_json TEXT,"
+ " distill_version INTEGER NOT NULL DEFAULT 0,"
+ " content_hash TEXT NOT NULL, created_at TEXT NOT NULL)",
+ "CREATE INDEX IF NOT EXISTS idx_uw_documents_item"
+ " ON uw_documents(item_id)",
+ "CREATE TABLE IF NOT EXISTS uw_embeddings ("
+ " document_id BIGINT PRIMARY KEY"
+ " REFERENCES uw_documents(id) ON DELETE CASCADE,"
+ " model TEXT NOT NULL, dim INTEGER NOT NULL,"
+ " vector BYTEA NOT NULL, created_at TEXT NOT NULL)",
+ "CREATE TABLE IF NOT EXISTS uw_distill_cache ("
+ " content_hash TEXT NOT NULL, prompt_version INTEGER NOT NULL,"
+ " model TEXT NOT NULL, result_json TEXT NOT NULL,"
+ " created_at TEXT NOT NULL,"
+ " PRIMARY KEY (content_hash, prompt_version, model))",
+ ]
+
+ # -- lifecycle -----------------------------------------------------------
+
+ @classmethod
+ async def connect_test(cls, conn_str: str) -> tuple[bool, str]:
+ """Probe a connection string: ``(ok, honest_message)``, never raises."""
+ try:
+ psycopg = _import_psycopg()
+ except ImportError as exc:
+ return False, str(exc)
+ try:
+ conn = await psycopg.AsyncConnection.connect(conn_str, connect_timeout=5)
+ except Exception as exc:
+ return False, f"Connection failed: {exc}"
+ try:
+ cur = await conn.execute("SELECT version()")
+ version_row = await cur.fetchone()
+ cur = await conn.execute(
+ "SELECT count(*) FROM pg_available_extensions WHERE name = 'vector'"
+ )
+ vec_row = await cur.fetchone()
+ vec_note = (
+ "pgvector is available"
+ if vec_row and int(vec_row[0]) > 0
+ else "pgvector is NOT available — vector search will be "
+ "disabled (keyword search still works)"
+ )
+ server = version_row[0] if version_row else "PostgreSQL"
+ return True, f"Connected: {server}; {vec_note}"
+ except Exception as exc:
+ return False, f"Connected, but the server probe failed: {exc}"
+ finally:
+ await conn.close()
+
+ async def open(self) -> None:
+ async with self._lock:
+ if self._conn is not None:
+ return
+ psycopg = _import_psycopg()
+ conn = await psycopg.AsyncConnection.connect(
+ self._conn_str, autocommit=True, row_factory=psycopg.rows.dict_row
+ )
+ async with conn.transaction():
+ for statement in self.ddl_statements():
+ await conn.execute(statement)
+ self._conn = conn
+
+ async def close(self) -> None:
+ async with self._lock:
+ if self._conn is not None:
+ await self._conn.close()
+ self._conn = None
+ self._vec_state = None
+ self._vec_dim = None
+
+ async def _ensure_open(self) -> Any:
+ if self._conn is None:
+ await self.open()
+ return self._conn
+
+ @asynccontextmanager
+ async def _txn(self) -> AsyncIterator[Any]:
+ conn = await self._ensure_open()
+ async with self._lock, conn.transaction():
+ yield conn
+
+ @staticmethod
+ async def _fetchall(conn: Any, sql: str, params: Sequence[Any] = ()) -> list[dict]:
+ cur = await conn.execute(sql, params)
+ return list(await cur.fetchall())
+
+ @staticmethod
+ async def _fetchone(
+ conn: Any, sql: str, params: Sequence[Any] = ()
+ ) -> dict | None:
+ cur = await conn.execute(sql, params)
+ return await cur.fetchone()
+
+ # -- sources & consent ---------------------------------------------------
+
+ async def upsert_source(
+ self,
+ source_id: str,
+ *,
+ connector: str,
+ label: str,
+ config: dict[str, Any] | None = None,
+ areas: list[str] | None = None,
+ ) -> None:
+ now = _iso_utc()
+ async with self._txn() as conn:
+ row = await self._fetchone(
+ conn, "SELECT id FROM uw_sources WHERE id = %s", (source_id,)
+ )
+ if row is None:
+ await conn.execute(
+ "INSERT INTO uw_sources"
+ " (id, connector, label, config_json, areas_json, created_at)"
+ " VALUES (%s, %s, %s, %s, %s, %s)",
+ (
+ source_id,
+ connector,
+ label,
+ json.dumps(config or {}),
+ json.dumps(areas or []),
+ now,
+ ),
+ )
+ else:
+ await conn.execute(
+ "UPDATE uw_sources SET connector = %s, label = %s,"
+ " config_json = COALESCE(%s, config_json),"
+ " areas_json = COALESCE(%s, areas_json) WHERE id = %s",
+ (
+ connector,
+ label,
+ None if config is None else json.dumps(config),
+ None if areas is None else json.dumps(areas),
+ source_id,
+ ),
+ )
+
+ @staticmethod
+ def _source_row_to_dict(row: dict[str, Any]) -> dict[str, Any]:
+ return {
+ "id": row["id"],
+ "connector": row["connector"],
+ "label": row["label"],
+ "config": json.loads(row["config_json"] or "{}"),
+ "areas": json.loads(row["areas_json"] or "[]"),
+ "consent": row["consent"],
+ "enabled": bool(row["enabled"]),
+ "created_at": row["created_at"],
+ "last_sync_at": row["last_sync_at"],
+ "last_error": row["last_error"],
+ }
+
+ async def get_source(self, source_id: str) -> dict[str, Any] | None:
+ conn = await self._ensure_open()
+ row = await self._fetchone(
+ conn, "SELECT * FROM uw_sources WHERE id = %s", (source_id,)
+ )
+ return None if row is None else self._source_row_to_dict(row)
+
+ async def list_sources(self) -> list[dict[str, Any]]:
+ conn = await self._ensure_open()
+ rows = await self._fetchall(conn, "SELECT * FROM uw_sources ORDER BY id")
+ count_rows = await self._fetchall(
+ conn,
+ "SELECT source_id, state, COUNT(*) AS n FROM uw_items"
+ " WHERE deleted_at IS NULL GROUP BY source_id, state",
+ )
+ per_source: dict[str, list[tuple[str, int]]] = {}
+ for crow in count_rows:
+ per_source.setdefault(crow["source_id"], []).append(
+ (crow["state"], crow["n"])
+ )
+ sync_rows = await self._fetchall(conn, "SELECT * FROM uw_sync_state")
+ sync_by_id = {srow["source_id"]: dict(srow) for srow in sync_rows}
+ result = []
+ for row in rows:
+ entry = self._source_row_to_dict(row)
+ entry["counts"] = _counts_from_pairs(per_source.get(row["id"], []))
+ sync = sync_by_id.get(row["id"])
+ if sync is not None:
+ sync.pop("source_id", None)
+ entry["sync_state"] = sync
+ result.append(entry)
+ return result
+
+ async def set_consent(self, source_id: str, consent: ConsentState | str) -> None:
+ value = ConsentState(consent).value
+ conn = await self._ensure_open()
+ await conn.execute(
+ "UPDATE uw_sources SET consent = %s WHERE id = %s", (value, source_id)
+ )
+
+ async def set_enabled(self, source_id: str, enabled: bool) -> None:
+ conn = await self._ensure_open()
+ await conn.execute(
+ "UPDATE uw_sources SET enabled = %s WHERE id = %s",
+ (bool(enabled), source_id),
+ )
+
+ async def set_source_status(
+ self,
+ source_id: str,
+ *,
+ last_sync_at: str | None = _UNSET,
+ last_error: str | None = _UNSET,
+ ) -> None:
+ conn = await self._ensure_open()
+ if last_sync_at is not _UNSET:
+ await conn.execute(
+ "UPDATE uw_sources SET last_sync_at = %s WHERE id = %s",
+ (last_sync_at, source_id),
+ )
+ if last_error is not _UNSET:
+ await conn.execute(
+ "UPDATE uw_sources SET last_error = %s WHERE id = %s",
+ (last_error, source_id),
+ )
+
+ async def delete_source(self, source_id: str, *, purge: bool) -> None:
+ if not purge:
+ conn = await self._ensure_open()
+ await conn.execute(
+ "UPDATE uw_sources SET consent = %s, enabled = FALSE WHERE id = %s",
+ (ConsentState.REVOKED.value, source_id),
+ )
+ return
+ async with self._txn() as conn:
+ if self._vec_state is not None and self._vec_state[0]:
+ await conn.execute(
+ "DELETE FROM uw_vec WHERE document_id IN"
+ " (SELECT d.id FROM uw_documents d"
+ " JOIN uw_items i ON i.id = d.item_id"
+ " WHERE i.source_id = %s)",
+ (source_id,),
+ )
+ await conn.execute(
+ "DELETE FROM uw_sources WHERE id = %s", (source_id,)
+ ) # items/documents/embeddings cascade
+
+ # -- items ---------------------------------------------------------------
+
+ async def upsert_items(
+ self, source_id: str, items: Sequence[RawItem]
+ ) -> UpsertCounts:
+ source = await self.get_source(source_id)
+ if source is None:
+ raise UltraStoreError(
+ f"unknown source {source_id!r} — call upsert_source() first"
+ )
+ areas_json = json.dumps(source["areas"])
+ now = _iso_utc()
+ new = changed = unchanged = tombstoned = 0
+ async with self._txn() as conn:
+ for item in items:
+ row = await self._fetchone(
+ conn,
+ "SELECT id, content_hash, deleted_at FROM uw_items"
+ " WHERE source_id = %s AND external_id = %s",
+ (source_id, item.external_id),
+ )
+ if item.deleted:
+ if row is not None and row["deleted_at"] is None:
+ await self._purge_derived(conn, [row["id"]])
+ await conn.execute(
+ "UPDATE uw_items SET deleted_at = %s, updated_at = %s"
+ " WHERE id = %s",
+ (now, now, row["id"]),
+ )
+ tombstoned += 1
+ continue
+ identity = _content_identity(item)
+ if row is None:
+ await conn.execute(
+ "INSERT INTO uw_items"
+ " (source_id, external_id, thread_key, author_raw, title,"
+ " body_raw, permalink, timestamp_utc, areas_json,"
+ " content_hash, state, created_at, updated_at)"
+ " VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s,"
+ " %s, %s)",
+ (
+ source_id,
+ item.external_id,
+ item.thread_key,
+ item.author_raw,
+ item.title,
+ item.body,
+ item.permalink,
+ item.timestamp_utc,
+ areas_json,
+ identity,
+ ItemState.CAPTURED.value,
+ now,
+ now,
+ ),
+ )
+ new += 1
+ elif row["content_hash"] == identity and row["deleted_at"] is None:
+ unchanged += 1
+ else:
+ await self._purge_derived(conn, [row["id"]])
+ await conn.execute(
+ "UPDATE uw_items SET thread_key = %s, author_raw = %s,"
+ " title = %s, body_raw = %s, permalink = %s,"
+ " timestamp_utc = %s, areas_json = %s, content_hash = %s,"
+ " state = %s, attempt_count = 0, next_retry_at = NULL,"
+ " last_error = NULL, deleted_at = NULL, updated_at = %s"
+ " WHERE id = %s",
+ (
+ item.thread_key,
+ item.author_raw,
+ item.title,
+ item.body,
+ item.permalink,
+ item.timestamp_utc,
+ areas_json,
+ identity,
+ ItemState.CAPTURED.value,
+ now,
+ row["id"],
+ ),
+ )
+ changed += 1
+ return UpsertCounts(
+ new=new, changed=changed, unchanged=unchanged, tombstoned=tombstoned
+ )
+
+ async def _purge_derived(self, conn: Any, item_ids: Sequence[int]) -> None:
+ """Postgres twin of the SQLite purge: the tsvector column follows the
+ row automatically, documents/embeddings cascade; only pgvector rows
+ need an explicit delete when the index is live."""
+ if not item_ids:
+ return
+ ids = list(item_ids)
+ if self._vec_state is not None and self._vec_state[0]:
+ await conn.execute(
+ "DELETE FROM uw_vec WHERE document_id IN"
+ " (SELECT id FROM uw_documents WHERE item_id = ANY(%s))",
+ (ids,),
+ )
+ await conn.execute(
+ "DELETE FROM uw_documents WHERE item_id = ANY(%s)", (ids,)
+ )
+
+ @staticmethod
+ def _item_row_to_dict(row: dict[str, Any]) -> dict[str, Any]:
+ return {
+ "id": row["id"],
+ "source_id": row["source_id"],
+ "external_id": row["external_id"],
+ "thread_key": row["thread_key"],
+ "author_raw": row["author_raw"],
+ "title": row["title"],
+ "body_raw": row["body_raw"],
+ "permalink": row["permalink"],
+ "timestamp_utc": row["timestamp_utc"],
+ "areas": json.loads(row["areas_json"] or "[]"),
+ "content_hash": row["content_hash"],
+ "state": row["state"],
+ "attempt_count": row["attempt_count"],
+ "next_retry_at": row["next_retry_at"],
+ "last_error": row["last_error"],
+ "deleted_at": row["deleted_at"],
+ "created_at": row["created_at"],
+ "updated_at": row["updated_at"],
+ }
+
+ async def get_item(self, item_id: int) -> dict[str, Any] | None:
+ conn = await self._ensure_open()
+ row = await self._fetchone(
+ conn, "SELECT * FROM uw_items WHERE id = %s", (item_id,)
+ )
+ return None if row is None else self._item_row_to_dict(row)
+
+ async def get_item_by_external_id(
+ self, source_id: str, external_id: str
+ ) -> dict[str, Any] | None:
+ conn = await self._ensure_open()
+ row = await self._fetchone(
+ conn,
+ "SELECT * FROM uw_items WHERE source_id = %s AND external_id = %s",
+ (source_id, external_id),
+ )
+ return None if row is None else self._item_row_to_dict(row)
+
+ async def claim_batch(
+ self,
+ target_state: ItemState | str,
+ *,
+ limit: int = 50,
+ now: str | datetime | None = None,
+ ) -> list[dict[str, Any]]:
+ predecessor = _predecessor_of(target_state)
+ now_s = _iso_utc(_coerce_now(now))
+ conn = await self._ensure_open()
+ rows = await self._fetchall(
+ conn,
+ "SELECT * FROM uw_items"
+ " WHERE state = %s AND deleted_at IS NULL"
+ " AND (next_retry_at IS NULL OR next_retry_at <= %s)"
+ " ORDER BY timestamp_utc DESC, id DESC LIMIT %s",
+ (predecessor.value, now_s, int(limit)),
+ )
+ return [self._item_row_to_dict(row) for row in rows]
+
+ async def mark_stage_done(
+ self,
+ item_id: int,
+ new_state: ItemState | str,
+ *,
+ fts_title: str | None = None, # noqa: ARG002 — tsvector is generated
+ fts_body: str | None = None, # noqa: ARG002 — tsvector is generated
+ ) -> None:
+ """Same contract as the SQLite twin; the ``fts_*`` arguments are
+ accepted and ignored because the keyword leg is a generated column."""
+ state = _coerce_state(new_state)
+ if state not in STATE_ORDER or state is ItemState.CAPTURED:
+ raise ValueError(
+ f"mark_stage_done cannot set {state.value!r} — only forward "
+ "stages after 'captured' are worker transitions"
+ )
+ conn = await self._ensure_open()
+ await conn.execute(
+ "UPDATE uw_items SET state = %s, attempt_count = 0,"
+ " next_retry_at = NULL, last_error = NULL, updated_at = %s"
+ " WHERE id = %s",
+ (state.value, _iso_utc(), item_id),
+ )
+
+ async def mark_retry(
+ self,
+ item_id: int,
+ error: str,
+ *,
+ now: str | datetime | None = None,
+ ) -> None:
+ moment = _coerce_now(now)
+ async with self._txn() as conn:
+ row = await self._fetchone(
+ conn,
+ "SELECT attempt_count FROM uw_items WHERE id = %s",
+ (item_id,),
+ )
+ if row is None:
+ return
+ attempts_before = int(row["attempt_count"])
+ new_count = attempts_before + 1
+ if new_count >= MAX_ATTEMPTS:
+ await conn.execute(
+ "UPDATE uw_items SET state = %s, attempt_count = %s,"
+ " next_retry_at = NULL, last_error = %s, updated_at = %s"
+ " WHERE id = %s",
+ (
+ ItemState.FAILED.value,
+ new_count,
+ error,
+ _iso_utc(moment),
+ item_id,
+ ),
+ )
+ else:
+ retry_at = moment + timedelta(seconds=_retry_delay_s(attempts_before))
+ await conn.execute(
+ "UPDATE uw_items SET attempt_count = %s, next_retry_at = %s,"
+ " last_error = %s, updated_at = %s WHERE id = %s",
+ (
+ new_count,
+ _iso_utc(retry_at),
+ error,
+ _iso_utc(moment),
+ item_id,
+ ),
+ )
+
+ async def mark_failed(self, item_id: int, error: str) -> None:
+ conn = await self._ensure_open()
+ await conn.execute(
+ "UPDATE uw_items SET state = %s, next_retry_at = NULL,"
+ " last_error = %s, updated_at = %s WHERE id = %s",
+ (ItemState.FAILED.value, error, _iso_utc(), item_id),
+ )
+
+ async def counts(self) -> PipelineCounts:
+ conn = await self._ensure_open()
+ rows = await self._fetchall(
+ conn,
+ "SELECT state, COUNT(*) AS n FROM uw_items"
+ " WHERE deleted_at IS NULL GROUP BY state",
+ )
+ return _counts_from_pairs((row["state"], row["n"]) for row in rows)
+
+ async def counts_for_source(self, source_id: str) -> PipelineCounts:
+ conn = await self._ensure_open()
+ rows = await self._fetchall(
+ conn,
+ "SELECT state, COUNT(*) AS n FROM uw_items"
+ " WHERE deleted_at IS NULL AND source_id = %s GROUP BY state",
+ (source_id,),
+ )
+ return _counts_from_pairs((row["state"], row["n"]) for row in rows)
+
+ async def reconcile_deletes(
+ self, source_id: str, yielded_external_ids: set[str]
+ ) -> int:
+ now = _iso_utc()
+ async with self._txn() as conn:
+ rows = await self._fetchall(
+ conn,
+ "SELECT id, external_id FROM uw_items"
+ " WHERE source_id = %s AND deleted_at IS NULL",
+ (source_id,),
+ )
+ doomed = [
+ row["id"]
+ for row in rows
+ if row["external_id"] not in yielded_external_ids
+ ]
+ if doomed:
+ await self._purge_derived(conn, doomed)
+ await conn.execute(
+ "UPDATE uw_items SET deleted_at = %s, updated_at = %s"
+ " WHERE id = ANY(%s)",
+ (now, now, doomed),
+ )
+ return len(doomed)
+
+ # -- documents & vectors -------------------------------------------------
+
+ async def add_document(
+ self,
+ item_id: int,
+ doc_type: DocType | str,
+ text_norm: str,
+ *,
+ distill_json: str | None = None,
+ distill_version: int = 0,
+ content_hash: str = "",
+ ) -> int:
+ kind = DocType(doc_type).value
+ now = _iso_utc()
+ async with self._txn() as conn:
+ if self._vec_state is not None and self._vec_state[0]:
+ await conn.execute(
+ "DELETE FROM uw_vec WHERE document_id IN"
+ " (SELECT id FROM uw_documents"
+ " WHERE item_id = %s AND doc_type = %s)",
+ (item_id, kind),
+ )
+ await conn.execute(
+ "DELETE FROM uw_documents WHERE item_id = %s AND doc_type = %s",
+ (item_id, kind),
+ )
+ row = await self._fetchone(
+ conn,
+ "INSERT INTO uw_documents (item_id, doc_type, text_norm,"
+ " distill_json, distill_version, content_hash, created_at)"
+ " VALUES (%s, %s, %s, %s, %s, %s, %s) RETURNING id",
+ (
+ item_id,
+ kind,
+ text_norm,
+ distill_json,
+ int(distill_version),
+ content_hash,
+ now,
+ ),
+ )
+ assert row is not None
+ return int(row["id"])
+
+ async def _pinned_space(self) -> tuple[str | None, int | None]:
+ model = await self.get_meta(META_EMBED_MODEL)
+ dim_raw = await self.get_meta(META_EMBED_DIM)
+ return model, int(dim_raw) if dim_raw else None
+
+ async def store_embedding(
+ self,
+ document_id: int,
+ *,
+ model: str,
+ dim: int,
+ vector: Sequence[float],
+ ) -> None:
+ if len(vector) != dim:
+ raise UltraStoreError(
+ f"vector has {len(vector)} components but dim={dim} was declared"
+ )
+ pinned_model, pinned_dim = await self._pinned_space()
+ if pinned_model is None or pinned_dim is None:
+ await self.set_meta(META_EMBED_MODEL, model)
+ await self.set_meta(META_EMBED_DIM, str(dim))
+ elif pinned_model != model or pinned_dim != dim:
+ raise UltraStoreError(
+ "embedding space mismatch: the store is pinned to "
+ f"model={pinned_model!r} dim={pinned_dim} but got "
+ f"model={model!r} dim={dim}. Changing the embedding model "
+ "requires reset_vectors() (re-embeds the corpus)."
+ )
+ vec_ok, _ = await self._ensure_vec(dim)
+ now = _iso_utc()
+ async with self._txn() as conn:
+ await conn.execute(
+ "INSERT INTO uw_embeddings"
+ " (document_id, model, dim, vector, created_at)"
+ " VALUES (%s, %s, %s, %s, %s)"
+ " ON CONFLICT (document_id) DO UPDATE SET model = %s,"
+ " dim = %s, vector = %s, created_at = %s",
+ (
+ document_id,
+ model,
+ dim,
+ pack_vector(vector),
+ now,
+ model,
+ dim,
+ pack_vector(vector),
+ now,
+ ),
+ )
+ if vec_ok:
+ literal = self._pgvector_literal(vector)
+ await conn.execute(
+ "INSERT INTO uw_vec (document_id, embedding)"
+ " VALUES (%s, %s::vector)"
+ " ON CONFLICT (document_id) DO UPDATE"
+ " SET embedding = %s::vector",
+ (document_id, literal, literal),
+ )
+
+ @staticmethod
+ def _pgvector_literal(vector: Sequence[float]) -> str:
+ return "[" + ",".join(f"{component:.8g}" for component in vector) + "]"
+
+ async def _ensure_vec(self, dim: int | None) -> tuple[bool, str]:
+ """Lazily enable pgvector + derive the ``uw_vec`` table; degrades
+ honestly when the server lacks the extension or the privilege."""
+ if dim is None:
+ _, dim = await self._pinned_space()
+ if dim is None:
+ return (
+ False,
+ "no embedding has been stored yet — the vector index is "
+ "created with the first embedding",
+ )
+ if self._vec_state is not None and self._vec_dim == dim:
+ return self._vec_state
+ conn = await self._ensure_open()
+ try:
+ await conn.execute("CREATE EXTENSION IF NOT EXISTS vector")
+ except Exception as exc:
+ self._vec_state = (
+ False,
+ "semantic vector search is disabled: the pgvector extension "
+ f"is not available on this PostgreSQL server ({exc}). "
+ "Keyword search keeps working; stored embeddings are kept "
+ "and will be indexed once the extension is installed.",
+ )
+ self._vec_dim = dim
+ return self._vec_state
+ await conn.execute(
+ "CREATE TABLE IF NOT EXISTS uw_vec ("
+ " document_id BIGINT PRIMARY KEY"
+ " REFERENCES uw_documents(id) ON DELETE CASCADE,"
+ f" embedding vector({int(dim)}) NOT NULL)"
+ )
+ # Backfill vectors stored while the index was unavailable.
+ missing = await self._fetchall(
+ conn,
+ "SELECT document_id, vector FROM uw_embeddings"
+ " WHERE document_id NOT IN (SELECT document_id FROM uw_vec)",
+ )
+ for row in missing:
+ literal = self._pgvector_literal(unpack_vector(bytes(row["vector"])))
+ await conn.execute(
+ "INSERT INTO uw_vec (document_id, embedding)"
+ " VALUES (%s, %s::vector) ON CONFLICT (document_id) DO NOTHING",
+ (row["document_id"], literal),
+ )
+ self._vec_dim = dim
+ self._vec_state = (True, "")
+ return self._vec_state
+
+ async def vector_status(self) -> tuple[bool, str]:
+ return await self._ensure_vec(None)
+
+ async def reset_vectors(self) -> None:
+ async with self._txn() as conn:
+ await conn.execute("DROP TABLE IF EXISTS uw_vec")
+ await conn.execute("DELETE FROM uw_embeddings")
+ await conn.execute(
+ "DELETE FROM uw_meta WHERE key IN (%s, %s)",
+ (META_EMBED_MODEL, META_EMBED_DIM),
+ )
+ await conn.execute(
+ "UPDATE uw_items SET state = %s, updated_at = %s"
+ " WHERE state IN (%s, %s)",
+ (
+ ItemState.KEYWORD_INDEXED.value,
+ _iso_utc(),
+ ItemState.EMBEDDED.value,
+ ItemState.DISTILLED.value,
+ ),
+ )
+ self._vec_state = None
+ self._vec_dim = None
+
+ # -- search legs ---------------------------------------------------------
+
+ async def keyword_search(
+ self, query: str, k: int = 10, *, area_id: str | None = None
+ ) -> list[SearchResult]:
+ if not query or not query.strip():
+ return []
+ conn = await self._ensure_open()
+ sql = (
+ "SELECT i.id AS item_id, i.source_id, i.title,"
+ " LEFT(i.body_raw, %s) AS snip, i.permalink, i.timestamp_utc,"
+ " ts_rank(i.search_tsv, websearch_to_tsquery('simple', %s)) AS rank"
+ " FROM uw_items i"
+ " WHERE i.search_tsv @@ websearch_to_tsquery('simple', %s)"
+ " AND i.deleted_at IS NULL"
+ )
+ params: list[Any] = [_SNIPPET_CHARS, query, query]
+ if area_id is not None:
+ sql += " AND i.areas_json::jsonb @> to_jsonb(%s::text)"
+ params.append(area_id)
+ sql += " ORDER BY rank DESC LIMIT %s"
+ params.append(int(k))
+ rows = await self._fetchall(conn, sql, params)
+ return [
+ SearchResult(
+ item_id=int(row["item_id"]),
+ source_id=row["source_id"],
+ title=row["title"],
+ snippet=_snippet_of(row["snip"] or ""),
+ permalink=row["permalink"],
+ timestamp_utc=row["timestamp_utc"],
+ score=round(
+ float(row["rank"]) / (1.0 + float(row["rank"])), 4
+ ),
+ matched_by=("keyword",),
+ )
+ for row in rows
+ ]
+
+ async def vector_search(
+ self,
+ query_vector: Sequence[float],
+ k: int = 10,
+ *,
+ area_id: str | None = None,
+ ) -> tuple[list[SearchResult], str]:
+ ok, reason = await self._ensure_vec(None)
+ if not ok:
+ return [], reason
+ assert self._vec_dim is not None
+ if len(query_vector) != self._vec_dim:
+ return [], (
+ f"query vector has {len(query_vector)} components but the "
+ f"store's embedding space is pinned to dim={self._vec_dim}"
+ )
+ conn = await self._ensure_open()
+ literal = self._pgvector_literal(query_vector)
+ sql = (
+ "SELECT d.item_id, i.source_id, i.title, d.text_norm,"
+ " i.permalink, i.timestamp_utc,"
+ " (v.embedding <=> %s::vector) AS distance"
+ " FROM uw_vec v"
+ " JOIN uw_documents d ON d.id = v.document_id"
+ " JOIN uw_items i ON i.id = d.item_id"
+ " WHERE i.deleted_at IS NULL"
+ )
+ params: list[Any] = [literal]
+ if area_id is not None:
+ sql += " AND i.areas_json::jsonb @> to_jsonb(%s::text)"
+ params.append(area_id)
+ sql += " ORDER BY distance LIMIT %s"
+ params.append(min(max(int(k) * 4, int(k) + 8), 200))
+ rows = await self._fetchall(conn, sql, params)
+ results: list[SearchResult] = []
+ seen_items: set[int] = set()
+ for row in rows:
+ item_id = int(row["item_id"])
+ if item_id in seen_items:
+ continue
+ seen_items.add(item_id)
+ results.append(
+ SearchResult(
+ item_id=item_id,
+ source_id=row["source_id"],
+ title=row["title"],
+ snippet=_snippet_of(row["text_norm"]),
+ permalink=row["permalink"],
+ timestamp_utc=row["timestamp_utc"],
+ score=round(_distance_score(float(row["distance"])), 4),
+ matched_by=("vector",),
+ )
+ )
+ if len(results) >= int(k):
+ break
+ return results, ""
+
+ # -- sync state / areas / cache / meta ----------------------------------
+
+ async def get_sync_state(self, source_id: str) -> dict[str, Any] | None:
+ conn = await self._ensure_open()
+ row = await self._fetchone(
+ conn, "SELECT * FROM uw_sync_state WHERE source_id = %s", (source_id,)
+ )
+ if row is None:
+ return None
+ result = dict(row)
+ result.pop("source_id", None)
+ return result
+
+ async def set_sync_state(
+ self,
+ source_id: str,
+ *,
+ cursor: str | None = _UNSET,
+ backfill_checkpoint: str | None = _UNSET,
+ backfill_complete_at: str | None = _UNSET,
+ last_success_at: str | None = _UNSET,
+ ) -> None:
+ fields = {
+ "cursor": cursor,
+ "backfill_checkpoint": backfill_checkpoint,
+ "backfill_complete_at": backfill_complete_at,
+ "last_success_at": last_success_at,
+ }
+ updates = {name: value for name, value in fields.items() if value is not _UNSET}
+ async with self._txn() as conn:
+ await conn.execute(
+ "INSERT INTO uw_sync_state (source_id) VALUES (%s)"
+ " ON CONFLICT (source_id) DO NOTHING",
+ (source_id,),
+ )
+ for name, value in updates.items():
+ await conn.execute(
+ f'UPDATE uw_sync_state SET "{name}" = %s WHERE source_id = %s', # noqa: S608 — column name from a code-owned literal dict
+ (value, source_id),
+ )
+
+ async def upsert_area(
+ self, area_id: str, name: str, *, is_default: bool = False
+ ) -> None:
+ now = _iso_utc()
+ async with self._txn() as conn:
+ if is_default:
+ await conn.execute("UPDATE uw_areas SET is_default = FALSE")
+ await conn.execute(
+ "INSERT INTO uw_areas (id, name, is_default, created_at)"
+ " VALUES (%s, %s, %s, %s)"
+ " ON CONFLICT (id) DO UPDATE SET name = EXCLUDED.name,"
+ " is_default = EXCLUDED.is_default",
+ (area_id, name, bool(is_default), now),
+ )
+
+ async def list_areas(self) -> list[dict[str, Any]]:
+ conn = await self._ensure_open()
+ rows = await self._fetchall(
+ conn, "SELECT * FROM uw_areas ORDER BY is_default DESC, id"
+ )
+ return [
+ {
+ "id": row["id"],
+ "name": row["name"],
+ "is_default": bool(row["is_default"]),
+ "created_at": row["created_at"],
+ }
+ for row in rows
+ ]
+
+ async def delete_area(self, area_id: str) -> None:
+ conn = await self._ensure_open()
+ await conn.execute("DELETE FROM uw_areas WHERE id = %s", (area_id,))
+
+ async def ensure_default_area(
+ self, area_id: str = "default", name: str = "Default"
+ ) -> str:
+ conn = await self._ensure_open()
+ row = await self._fetchone(
+ conn, "SELECT id FROM uw_areas WHERE is_default = TRUE LIMIT 1"
+ )
+ if row is not None:
+ return str(row["id"])
+ await self.upsert_area(area_id, name, is_default=True)
+ return area_id
+
+ async def distill_cache_get(
+ self, content_hash: str, prompt_version: int, model: str
+ ) -> str | None:
+ conn = await self._ensure_open()
+ row = await self._fetchone(
+ conn,
+ "SELECT result_json FROM uw_distill_cache"
+ " WHERE content_hash = %s AND prompt_version = %s AND model = %s",
+ (content_hash, int(prompt_version), model),
+ )
+ return None if row is None else str(row["result_json"])
+
+ async def distill_cache_put(
+ self, content_hash: str, prompt_version: int, model: str, result_json: str
+ ) -> None:
+ conn = await self._ensure_open()
+ await conn.execute(
+ "INSERT INTO uw_distill_cache"
+ " (content_hash, prompt_version, model, result_json, created_at)"
+ " VALUES (%s, %s, %s, %s, %s)"
+ " ON CONFLICT (content_hash, prompt_version, model)"
+ " DO UPDATE SET result_json = EXCLUDED.result_json,"
+ " created_at = EXCLUDED.created_at",
+ (content_hash, int(prompt_version), model, result_json, _iso_utc()),
+ )
+
+ async def get_meta(self, key: str) -> str | None:
+ conn = await self._ensure_open()
+ row = await self._fetchone(
+ conn, "SELECT value FROM uw_meta WHERE key = %s", (key,)
+ )
+ return None if row is None else str(row["value"])
+
+ async def set_meta(self, key: str, value: str) -> None:
+ conn = await self._ensure_open()
+ await conn.execute(
+ "INSERT INTO uw_meta (key, value) VALUES (%s, %s)"
+ " ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value",
+ (key, value),
+ )
+
+
+__all__ = [
+ "BACKOFF_BASE_S",
+ "BACKOFF_CAP_S",
+ "MAX_ATTEMPTS",
+ "META_EMBED_DIM",
+ "META_EMBED_MODEL",
+ "PostgresStore",
+ "UltraStore",
+ "UltraStoreError",
+ "UpsertCounts",
+ "pack_vector",
+ "resolve_ultrawiki_db_path",
+ "unpack_vector",
+]
diff --git a/jarvis/ultrawiki/types.py b/jarvis/ultrawiki/types.py
index 37416adfe7..f8eca14d4b 100644
--- a/jarvis/ultrawiki/types.py
+++ b/jarvis/ultrawiki/types.py
@@ -15,7 +15,7 @@ from __future__ import annotations
import hashlib
from collections.abc import AsyncIterator
from dataclasses import dataclass, field
-from enum import Enum
+from enum import StrEnum
from typing import Any, Protocol, runtime_checkable
__all__ = [
@@ -36,7 +36,7 @@ __all__ = [
]
-class ItemState(str, Enum):
+class ItemState(StrEnum):
"""Staged-pipeline state of one raw item (design doc 02).
The value is the LAST COMPLETED stage; workers advance items whose state
@@ -61,7 +61,7 @@ STATE_ORDER: tuple[ItemState, ...] = (
)
-class DocType(str, Enum):
+class DocType(StrEnum):
"""Kind of derived document stored in ``uw_documents``."""
RAW = "raw" # lightly normalized full text (pre-distillation embedding basis)
@@ -69,7 +69,7 @@ class DocType(str, Enum):
BURST = "burst" # high-signal fragment embedded with parent context
-class ConsentState(str, Enum):
+class ConsentState(StrEnum):
"""Per-source user consent. No connector pulls a single byte before
the source is explicitly approved in the UI/CLI (maintainer mandate)."""
@@ -78,7 +78,7 @@ class ConsentState(str, Enum):
REVOKED = "revoked"
-class IncrementalMode(str, Enum):
+class IncrementalMode(StrEnum):
"""How a connector keeps a source fresh after backfill."""
PUSH = "push" # platform pushes events (webhook/socket)
@@ -87,7 +87,7 @@ class IncrementalMode(str, Enum):
NONE = "none" # backfill/re-import only (e.g. export files)
-class AuthKind(str, Enum):
+class AuthKind(StrEnum):
"""What a connector needs before it can run."""
NONE = "none"
diff --git a/tests/unit/ultrawiki/test_pipeline.py b/tests/unit/ultrawiki/test_pipeline.py
new file mode 100644
index 0000000000..4f358aad43
--- /dev/null
+++ b/tests/unit/ultrawiki/test_pipeline.py
@@ -0,0 +1,314 @@
+"""PipelineWorker unit tests — real UltraStore on tmp_path, fully offline.
+
+Covers: the full captured -> keyword_indexed -> embedded -> distilled ladder
+with a fake embedding backend and fake distill_fn; the honest backlog when the
+embedding slot is unconfigured; retry-into-dead-letter for a poisoned distill
+item while healthy items pass; the distill cache short-circuit; and clean
+cancel-event / hard-cancel shutdown. No network, no credentials, no models.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import sqlite3
+from datetime import UTC, datetime, timedelta
+from pathlib import Path
+from types import SimpleNamespace
+from typing import Any
+
+import pytest
+
+from jarvis.ultrawiki.pipeline import PipelineWorker
+from jarvis.ultrawiki.store import UltraStore
+from jarvis.ultrawiki.types import ConsentState, ItemState, RawItem
+
+VECTOR = [0.1, 0.2, 0.3]
+
+
+def make_cfg() -> SimpleNamespace:
+ return SimpleNamespace(
+ ultrawiki=SimpleNamespace(
+ enabled=True,
+ db_backend="sqlite",
+ embedding_provider="fake",
+ embedding_model="fake-model",
+ distill_provider="",
+ distill_model="",
+ rerank_provider="",
+ ollama_endpoint="",
+ ),
+ memory=SimpleNamespace(data_dir="unused"),
+ brain=SimpleNamespace(primary=""),
+ )
+
+
+class FakeEmbeddingBackend:
+ """Fixed-vector backend implementing the EmbeddingBackend protocol."""
+
+ name = "fake"
+
+ def __init__(self, *, usable: bool = True) -> None:
+ self.usable = usable
+ self.embed_calls: list[list[str]] = []
+
+ def ready(self) -> tuple[bool, str]:
+ return (True, "") if self.usable else (False, "fake backend is down")
+
+ async def embed(self, texts: list[str], *, model: str) -> list[list[float]]:
+ self.embed_calls.append(list(texts))
+ return [list(VECTOR) for _ in texts]
+
+
+class FakeDistillResult:
+ """Shape-compatible stand-in for jarvis.ultrawiki.distill.DistillResult."""
+
+ def __init__(self, *, question: str, summary: str) -> None:
+ self.question = question
+ self.summary = summary
+ self.resolution = "Resolved."
+ self.entities = ["Alpha"]
+ self.refs: list[str] = []
+ self.raw_json = json.dumps(
+ {
+ "question": question,
+ "summary": summary,
+ "resolution": self.resolution,
+ "entities": self.entities,
+ "refs": self.refs,
+ }
+ )
+
+
+def make_item(index: int, *, title: str | None = None, body: str | None = None) -> RawItem:
+ return RawItem(
+ external_id=f"ext-{index:04d}",
+ body=body if body is not None else f"body text number {index}",
+ permalink=f"app://item/{index}",
+ timestamp_utc=f"2026-01-01T00:{index % 60:02d}:00Z",
+ title=title if title is not None else f"Item {index}",
+ )
+
+
+async def store(tmp_path: Path):
+ instance = UltraStore(tmp_path / "ultrawiki.db")
+ await instance.upsert_source(
+ "src1", connector="local-folder", label="Test source"
+ )
+ await instance.set_consent("src1", ConsentState.APPROVED)
+ yield instance
+ await instance.close()
+
+
+def db_scalar(db_path: Path, sql: str, params: tuple = ()) -> Any:
+ conn = sqlite3.connect(db_path)
+ try:
+ return conn.execute(sql, params).fetchone()[0]
+ finally:
+ conn.close()
+
+
+async def distill_ok(cfg: Any, *, title: str, body: str, source_kind: str) -> Any:
+ return FakeDistillResult(question=f"What about {title}?", summary=f"Summary of {title}.")
+
+
+async def distill_never(cfg: Any, *, title: str, body: str, source_kind: str) -> Any:
+ raise AssertionError("distill_fn must not be called in this test")
+
+
+# ---------------------------------------------------------------------------
+# Full ladder
+# ---------------------------------------------------------------------------
+
+
+async def test_full_ladder_captured_to_distilled(store, tmp_path):
+ await store.upsert_items("src1", [make_item(1)])
+ backend = FakeEmbeddingBackend()
+ worker = PipelineWorker(
+ store,
+ make_cfg(),
+ embedding_backend_factory=lambda: backend,
+ distill_fn=distill_ok,
+ )
+
+ attempted = await worker.run_once()
+ assert attempted >= 3 # one item worked in each of the three stages
+
+ item = await store.get_item_by_external_id("src1", "ext-0001")
+ assert item is not None
+ assert item["state"] == ItemState.DISTILLED.value
+ assert worker.processed_counts() == {"keyword": 1, "embed": 1, "distill": 1}
+
+ # RAW + SUMMARY documents exist, each with a stored embedding.
+ db_path = tmp_path / "ultrawiki.db"
+ assert db_scalar(db_path, "SELECT COUNT(*) FROM uw_documents") == 2
+ assert db_scalar(db_path, "SELECT COUNT(*) FROM uw_embeddings") == 2
+ assert (
+ db_scalar(
+ db_path,
+ "SELECT COUNT(*) FROM uw_documents WHERE doc_type = 'summary'"
+ " AND distill_json IS NOT NULL",
+ )
+ == 1
+ )
+ # Keyword leg is live from the first stage.
+ hits = await store.keyword_search("body")
+ assert hits and hits[0].item_id == item["id"]
+ # The distillation result was cached.
+ assert db_scalar(db_path, "SELECT COUNT(*) FROM uw_distill_cache") == 1
+ # The summary embedding used the composed summary text, not the raw body.
+ assert any("What about Item 1?" in texts[0] for texts in backend.embed_calls if texts)
+
+
+# ---------------------------------------------------------------------------
+# Unconfigured embedding slot — honest backlog
+# ---------------------------------------------------------------------------
+
+
+async def test_unconfigured_slot_stops_at_keyword_indexed(store):
+ await store.upsert_items("src1", [make_item(1), make_item(2)])
+ worker = PipelineWorker(
+ store,
+ make_cfg(),
+ embedding_backend_factory=lambda: None, # slot unconfigured
+ distill_fn=distill_never,
+ )
+
+ await worker.run_once()
+ await worker.run_once()
+
+ counts = await store.counts()
+ assert counts.keyword_indexed == 2
+ assert counts.embedded == 0
+ assert counts.distilled == 0
+ assert worker.processed_counts() == {"keyword": 2, "embed": 0, "distill": 0}
+
+
+async def test_not_ready_backend_claims_no_embed_work(store):
+ await store.upsert_items("src1", [make_item(1)])
+ backend = FakeEmbeddingBackend(usable=False)
+ worker = PipelineWorker(
+ store,
+ make_cfg(),
+ embedding_backend_factory=lambda: backend,
+ distill_fn=distill_never,
+ )
+
+ await worker.run_once()
+
+ counts = await store.counts()
+ assert counts.keyword_indexed == 1
+ assert counts.embedded == 0
+ assert backend.embed_calls == []
+
+
+# ---------------------------------------------------------------------------
+# Poisoned distill item — retries into failed while others pass
+# ---------------------------------------------------------------------------
+
+
+async def test_poison_distill_dead_letters_while_others_pass(store):
+ await store.upsert_items(
+ "src1",
+ [make_item(1, title="Good"), make_item(2, title="Poison")],
+ )
+
+ async def flaky_distill(cfg: Any, *, title: str, body: str, source_kind: str) -> Any:
+ if title == "Poison":
+ raise RuntimeError("provider exploded")
+ return FakeDistillResult(question="Q?", summary="S.")
+
+ clock = {"now": datetime(2026, 3, 1, 12, 0, tzinfo=UTC)}
+ worker = PipelineWorker(
+ store,
+ make_cfg(),
+ embedding_backend_factory=FakeEmbeddingBackend,
+ distill_fn=flaky_distill,
+ now_fn=lambda: clock["now"],
+ )
+
+ # Backoff ladder tops out at 3840 s before the 5th attempt dead-letters;
+ # a 2 h clock step keeps every retry eligible on the next pass.
+ for _ in range(6):
+ await worker.run_once()
+ clock["now"] += timedelta(hours=2)
+
+ good = await store.get_item_by_external_id("src1", "ext-0001")
+ poison = await store.get_item_by_external_id("src1", "ext-0002")
+ assert good is not None and good["state"] == ItemState.DISTILLED.value
+ assert poison is not None
+ assert poison["state"] == ItemState.FAILED.value
+ assert "distill" in (poison["last_error"] or "")
+ assert worker.processed_counts()["distill"] == 1
+
+ counts = await store.counts()
+ assert counts.distilled == 1
+ assert counts.failed == 1
+
+
+# ---------------------------------------------------------------------------
+# Distill cache — identical content is never paid for twice
+# ---------------------------------------------------------------------------
+
+
+async def test_distill_cache_hit_skips_the_provider_call(store):
+ twin_kwargs = {"title": "Twin", "body": "identical body content"}
+ await store.upsert_items(
+ "src1", [make_item(1, **twin_kwargs), make_item(2, **twin_kwargs)]
+ )
+ calls = {"n": 0}
+
+ async def counting_distill(cfg: Any, *, title: str, body: str, source_kind: str) -> Any:
+ calls["n"] += 1
+ return FakeDistillResult(question="Q?", summary="S.")
+
+ worker = PipelineWorker(
+ store,
+ make_cfg(),
+ embedding_backend_factory=FakeEmbeddingBackend,
+ distill_fn=counting_distill,
+ )
+
+ await worker.run_once()
+
+ assert calls["n"] == 1 # second twin rode the cache
+ counts = await store.counts()
+ assert counts.distilled == 2
+ assert worker.processed_counts()["distill"] == 2
+
+
+# ---------------------------------------------------------------------------
+# Shutdown discipline
+# ---------------------------------------------------------------------------
+
+
+async def test_cancel_event_stops_the_loop_cleanly(store):
+ worker = PipelineWorker(
+ store,
+ make_cfg(),
+ embedding_backend_factory=lambda: None,
+ distill_fn=distill_never,
+ )
+ cancel = asyncio.Event()
+ task = asyncio.create_task(worker.run(cancel), name="test-uw-pipeline")
+
+ await asyncio.sleep(0.05)
+ assert not task.done()
+ cancel.set()
+ await asyncio.wait_for(task, timeout=1.0) # wakes from the idle sleep
+ assert task.done() and not task.cancelled()
+
+
+async def test_hard_cancel_reraises_cancelled_error(store):
+ worker = PipelineWorker(
+ store,
+ make_cfg(),
+ embedding_backend_factory=lambda: None,
+ distill_fn=distill_never,
+ )
+ task = asyncio.create_task(worker.run(asyncio.Event()), name="test-uw-pipeline-2")
+ await asyncio.sleep(0.02)
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await task
diff --git a/tests/unit/ultrawiki/test_search.py b/tests/unit/ultrawiki/test_search.py
new file mode 100644
index 0000000000..e50dfd7b02
--- /dev/null
+++ b/tests/unit/ultrawiki/test_search.py
@@ -0,0 +1,511 @@
+"""Hybrid-search unit tests — real UltraStore + real FTS, fully offline.
+
+Covers: keyword-only degradation (no / dead / unknown embedding backend and
+store-side vector degradation), RRF consensus beating a single-list rank, the
+recency tiebreak, per-source capping, area-filter passthrough to BOTH legs,
+rerank reordering + RerankError fallback, empty-query/no-hit short-circuits,
+and the ``search_status`` capability report. The embedding backend is a
+hand-written fake with deterministic vectors; rerank is monkeypatched. No
+network, no credentials, no models.
+"""
+
+from __future__ import annotations
+
+import importlib.util
+import logging
+from types import SimpleNamespace
+
+import pytest
+
+import jarvis.ultrawiki.embeddings as embeddings_mod
+import jarvis.ultrawiki.rerank as rerank_mod
+from jarvis.ultrawiki.embeddings import EmbeddingError
+from jarvis.ultrawiki.rerank import RerankError
+from jarvis.ultrawiki.search import hybrid_search, search_status
+from jarvis.ultrawiki.store import UltraStore
+from jarvis.ultrawiki.types import (
+ ConsentState,
+ DocType,
+ ItemState,
+ RawItem,
+ SearchResult,
+)
+
+HAS_SQLITE_VEC = importlib.util.find_spec("sqlite_vec") is not None
+
+EMBED_MODEL = "fake-model"
+EMBED_DIM = 3
+
+
+# ---------------------------------------------------------------------------
+# Fakes + helpers
+# ---------------------------------------------------------------------------
+
+
+class FakeEmbedding:
+ """Deterministic offline embedding backend (protocol-shaped)."""
+
+ name = "fake"
+
+ def __init__(
+ self,
+ vectors_by_text: dict[str, list[float]] | None = None,
+ *,
+ default: list[float] | None = None,
+ error: Exception | None = None,
+ ) -> None:
+ self._vectors = vectors_by_text or {}
+ self._default = default if default is not None else [1.0, 0.0, 0.0]
+ self._error = error
+ self.calls: list[tuple[list[str], str]] = []
+
+ def ready(self) -> tuple[bool, str]:
+ return True, ""
+
+ async def embed(self, texts: list[str], *, model: str) -> list[list[float]]:
+ self.calls.append((list(texts), model))
+ if self._error is not None:
+ raise self._error
+ return [list(self._vectors.get(text, self._default)) for text in texts]
+
+
+class FakeReranker:
+ """Scripted reranker: returns fixed (index, score) pairs or raises."""
+
+ name = "fake"
+
+ def __init__(
+ self,
+ pairs: list[tuple[int, float]] | None = None,
+ *,
+ error: Exception | None = None,
+ ) -> None:
+ self._pairs = pairs or []
+ self._error = error
+ self.calls: list[tuple[str, list[str], int]] = []
+
+ def ready(self) -> tuple[bool, str]:
+ return True, ""
+
+ async def rerank(self, query: str, documents: list[str], top_k: int) -> list[tuple[int, float]]:
+ self.calls.append((query, list(documents), top_k))
+ if self._error is not None:
+ raise self._error
+ return list(self._pairs)
+
+
+class FakeStore:
+ """Scripted store legs, recording the arguments each leg received."""
+
+ def __init__(
+ self,
+ keyword_hits: list[SearchResult] | None = None,
+ vector_hits: list[SearchResult] | None = None,
+ ) -> None:
+ self._keyword_hits = keyword_hits or []
+ self._vector_hits = vector_hits or []
+ self.keyword_calls: list[tuple[str, int, str | None]] = []
+ self.vector_calls: list[tuple[list[float], int, str | None]] = []
+
+ async def keyword_search(
+ self, query: str, k: int = 10, *, area_id: str | None = None
+ ) -> list[SearchResult]:
+ self.keyword_calls.append((query, k, area_id))
+ return list(self._keyword_hits)
+
+ async def vector_search(
+ self, query_vector, k: int = 10, *, area_id: str | None = None
+ ) -> tuple[list[SearchResult], str]:
+ self.vector_calls.append((list(query_vector), k, area_id))
+ return list(self._vector_hits), ""
+
+
+def make_cfg(**overrides) -> SimpleNamespace:
+ values = {
+ "enabled": True,
+ "embedding_provider": "",
+ "embedding_model": "",
+ "rerank_provider": "",
+ "ollama_endpoint": "http://localhost:11434",
+ }
+ values.update(overrides)
+ return SimpleNamespace(ultrawiki=SimpleNamespace(**values))
+
+
+def make_result(
+ item_id: int,
+ *,
+ source_id: str = "src1",
+ timestamp_utc: str = "2026-01-02T10:00:00Z",
+ matched_by: tuple[str, ...] = ("keyword",),
+ score: float = 0.5,
+) -> SearchResult:
+ return SearchResult(
+ item_id=item_id,
+ source_id=source_id,
+ title=f"Item {item_id}",
+ snippet=f"snippet {item_id}",
+ permalink=f"app://item/{item_id}",
+ timestamp_utc=timestamp_utc,
+ score=score,
+ matched_by=matched_by,
+ )
+
+
+def raw_item(
+ external_id: str,
+ *,
+ body: str,
+ title: str = "",
+ timestamp_utc: str = "2026-01-02T10:00:00Z",
+) -> RawItem:
+ return RawItem(
+ external_id=external_id,
+ body=body,
+ permalink=f"app://{external_id}",
+ timestamp_utc=timestamp_utc,
+ title=title,
+ )
+
+
+async def store(tmp_path):
+ instance = UltraStore(tmp_path / "ultrawiki.db")
+ yield instance
+ await instance.close()
+
+
+async def add_source(
+ store: UltraStore, source_id: str = "src1", areas: list[str] | None = None
+) -> str:
+ await store.upsert_source(source_id, connector="local-folder", label="Test source", areas=areas)
+ await store.set_consent(source_id, ConsentState.APPROVED)
+ return source_id
+
+
+async def index_all_keyword(store: UltraStore) -> None:
+ claimed = await store.claim_batch(ItemState.KEYWORD_INDEXED, limit=500)
+ for item in claimed:
+ await store.mark_stage_done(
+ item["id"],
+ ItemState.KEYWORD_INDEXED,
+ fts_title=item["title"],
+ fts_body=item["body_raw"],
+ )
+
+
+async def item_id_of(store: UltraStore, source_id: str, external_id: str) -> int:
+ row = await store.get_item_by_external_id(source_id, external_id)
+ assert row is not None
+ return int(row["id"])
+
+
+async def embed_item(
+ store: UltraStore, item_id: int, vector: list[float], *, text: str = "summary"
+) -> None:
+ doc_id = await store.add_document(item_id, DocType.SUMMARY, text)
+ await store.store_embedding(doc_id, model=EMBED_MODEL, dim=len(vector), vector=vector)
+
+
+def register_fake_embedding(monkeypatch, fake: FakeEmbedding) -> None:
+ monkeypatch.setitem(embeddings_mod.EMBEDDING_BACKENDS, "fake", lambda cfg: fake)
+
+
+# ---------------------------------------------------------------------------
+# Empty query / no hits
+# ---------------------------------------------------------------------------
+
+
+async def test_empty_query_and_no_hits_return_empty(store):
+ await add_source(store)
+ await store.upsert_items("src1", [raw_item("a", body="alpha content")])
+ await index_all_keyword(store)
+ cfg = make_cfg()
+
+ assert await hybrid_search(store, cfg, "") == []
+ assert await hybrid_search(store, cfg, " ") == []
+ assert await hybrid_search(store, cfg, "zzzunmatchedtoken") == []
+
+
+# ---------------------------------------------------------------------------
+# Keyword-only degradation
+# ---------------------------------------------------------------------------
+
+
+async def test_keyword_only_when_no_embedding_configured(store):
+ await add_source(store)
+ await store.upsert_items(
+ "src1",
+ [
+ raw_item("a", body="alpha first"),
+ raw_item("b", body="alpha second"),
+ ],
+ )
+ await index_all_keyword(store)
+
+ results = await hybrid_search(store, make_cfg(), "alpha")
+
+ assert len(results) == 2
+ assert all(hit.matched_by == ("keyword",) for hit in results)
+
+
+async def test_keyword_only_when_embedding_backend_is_dead(store, monkeypatch):
+ await add_source(store)
+ await store.upsert_items("src1", [raw_item("a", body="alpha text")])
+ await index_all_keyword(store)
+ register_fake_embedding(
+ monkeypatch, FakeEmbedding(error=EmbeddingError("fake: backend is down"))
+ )
+ cfg = make_cfg(embedding_provider="fake", embedding_model=EMBED_MODEL)
+
+ results = await hybrid_search(store, cfg, "alpha")
+
+ assert [hit.matched_by for hit in results] == [("keyword",)]
+
+
+async def test_keyword_only_when_embedding_provider_is_unknown(store):
+ await add_source(store)
+ await store.upsert_items("src1", [raw_item("a", body="alpha text")])
+ await index_all_keyword(store)
+ cfg = make_cfg(embedding_provider="does-not-exist")
+
+ results = await hybrid_search(store, cfg, "alpha")
+
+ assert [hit.matched_by for hit in results] == [("keyword",)]
+
+
+async def test_keyword_only_when_store_vector_leg_is_degraded(store, monkeypatch):
+ """Backend healthy but the store holds no embeddings — an honest skip."""
+ await add_source(store)
+ await store.upsert_items("src1", [raw_item("a", body="alpha text")])
+ await index_all_keyword(store)
+ register_fake_embedding(monkeypatch, FakeEmbedding())
+ cfg = make_cfg(embedding_provider="fake", embedding_model=EMBED_MODEL)
+
+ results = await hybrid_search(store, cfg, "alpha")
+
+ assert [hit.matched_by for hit in results] == [("keyword",)]
+
+
+# ---------------------------------------------------------------------------
+# RRF fusion
+# ---------------------------------------------------------------------------
+
+
[email protected](not HAS_SQLITE_VEC, reason="sqlite-vec extension not installed")
+async def test_rrf_consensus_beats_single_list_rank(store, monkeypatch):
+ """An item ranked 2nd in BOTH legs outscores each leg's own #1."""
+ await add_source(store)
+ await store.upsert_items(
+ "src1",
+ [
+ # Keyword leg (query "alpha"): b (tf=3) ranks 1st, a (tf=1) 2nd.
+ raw_item("a", body="alpha one two three", timestamp_utc="2026-01-01T10:00:00Z"),
+ raw_item("b", body="alpha alpha alpha zero", timestamp_utc="2026-01-01T11:00:00Z"),
+ # c does not contain "alpha" at all — vector leg only.
+ raw_item("c", body="unrelated body text here", timestamp_utc="2026-01-01T12:00:00Z"),
+ ],
+ )
+ await index_all_keyword(store)
+ id_a = await item_id_of(store, "src1", "a")
+ id_b = await item_id_of(store, "src1", "b")
+ id_c = await item_id_of(store, "src1", "c")
+ # Vector leg (query -> [1, 0, 0]): c is an exact match (rank 1), a is
+ # close (rank 2), b has no embedding at all.
+ await embed_item(store, id_c, [1.0, 0.0, 0.0])
+ await embed_item(store, id_a, [0.9, 0.1, 0.0])
+ register_fake_embedding(monkeypatch, FakeEmbedding({"alpha": [1.0, 0.0, 0.0]}))
+ cfg = make_cfg(embedding_provider="fake", embedding_model=EMBED_MODEL)
+
+ results = await hybrid_search(store, cfg, "alpha")
+
+ assert [hit.item_id for hit in results] == [id_a, id_c, id_b]
+ by_id = {hit.item_id: hit for hit in results}
+ # Consensus winner carries both legs; single-list hits carry theirs only.
+ assert by_id[id_a].matched_by == ("keyword", "vector")
+ assert by_id[id_b].matched_by == ("keyword",)
+ assert by_id[id_c].matched_by == ("vector",)
+ # RRF arithmetic: a = 1/62 + 1/62; b and c = 1/61 each (recency-tiebroken).
+ assert by_id[id_a].score > by_id[id_c].score > by_id[id_b].score
+ assert by_id[id_a].score == pytest.approx(2 / 62, abs=1e-5)
+
+
+async def test_recency_breaks_rrf_ties_toward_newer_items(monkeypatch):
+ """Equal RRF sums (rank 1 in exactly one leg each) — newer wins."""
+ older = make_result(1, timestamp_utc="2026-01-01T10:00:00Z")
+ newer = make_result(2, timestamp_utc="2026-06-01T10:00:00Z", matched_by=("vector",))
+ fake_store = FakeStore(keyword_hits=[older], vector_hits=[newer])
+ register_fake_embedding(monkeypatch, FakeEmbedding())
+ cfg = make_cfg(embedding_provider="fake", embedding_model=EMBED_MODEL)
+
+ results = await hybrid_search(fake_store, cfg, "alpha")
+
+ assert [hit.item_id for hit in results] == [2, 1]
+
+
+async def test_area_filter_passes_through_to_both_legs(monkeypatch):
+ fake_store = FakeStore(
+ keyword_hits=[make_result(1)],
+ vector_hits=[make_result(2, matched_by=("vector",))],
+ )
+ register_fake_embedding(monkeypatch, FakeEmbedding())
+ cfg = make_cfg(embedding_provider="fake", embedding_model=EMBED_MODEL)
+
+ results = await hybrid_search(fake_store, cfg, "alpha", area_id="area-work")
+
+ assert len(results) == 2
+ assert fake_store.keyword_calls == [("alpha", 20, "area-work")]
+ assert len(fake_store.vector_calls) == 1
+ assert fake_store.vector_calls[0][2] == "area-work"
+
+
+async def test_area_filter_passthrough_real_store(store):
+ await add_source(store, "s-work", areas=["work"])
+ await add_source(store, "s-home", areas=["home"])
+ await store.upsert_items("s-work", [raw_item("w1", body="alpha work note")])
+ await store.upsert_items("s-home", [raw_item("h1", body="alpha home note")])
+ await index_all_keyword(store)
+ cfg = make_cfg()
+
+ scoped = await hybrid_search(store, cfg, "alpha", area_id="work")
+ assert {hit.source_id for hit in scoped} == {"s-work"}
+
+ unscoped = await hybrid_search(store, cfg, "alpha")
+ assert {hit.source_id for hit in unscoped} == {"s-work", "s-home"}
+
+
+async def test_per_source_cap_enforced_before_final_cut(store):
+ await add_source(store, "s-busy")
+ await add_source(store, "s-quiet")
+ await store.upsert_items(
+ "s-busy",
+ [raw_item(f"busy-{i}", body=f"alpha busy note {i}") for i in range(8)],
+ )
+ await store.upsert_items("s-quiet", [raw_item("q1", body="alpha quiet note")])
+ await index_all_keyword(store)
+
+ results = await hybrid_search(store, make_cfg(), "alpha", k=10)
+
+ per_source: dict[str, int] = {}
+ for hit in results:
+ per_source[hit.source_id] = per_source.get(hit.source_id, 0) + 1
+ # The busy source is capped at 5, so the quiet source still surfaces.
+ assert per_source == {"s-busy": 5, "s-quiet": 1}
+
+
+# ---------------------------------------------------------------------------
+# Rerank
+# ---------------------------------------------------------------------------
+
+
+async def seed_three_ranked_items(store: UltraStore) -> list[int]:
+ """Three keyword items with strictly decreasing term frequency."""
+ await add_source(store)
+ await store.upsert_items(
+ "src1",
+ [
+ raw_item("r0", body="alpha alpha alpha zero"),
+ raw_item("r1", body="alpha alpha one two"),
+ raw_item("r2", body="alpha one two three"),
+ ],
+ )
+ await index_all_keyword(store)
+ return [await item_id_of(store, "src1", ext) for ext in ("r0", "r1", "r2")]
+
+
+async def test_rerank_reorders_when_configured_and_ready(store, monkeypatch):
+ id_0, id_1, id_2 = await seed_three_ranked_items(store)
+
+ baseline = await hybrid_search(store, make_cfg(), "alpha")
+ assert [hit.item_id for hit in baseline] == [id_0, id_1, id_2]
+
+ fake = FakeReranker(pairs=[(2, 0.9), (1, 0.5), (0, 0.1)])
+ monkeypatch.setattr(rerank_mod, "resolve_reranker", lambda cfg: fake)
+ cfg = make_cfg(rerank_provider="voyage")
+
+ results = await hybrid_search(store, cfg, "alpha")
+
+ assert [hit.item_id for hit in results] == [id_2, id_1, id_0]
+ # Only the ORDER changes — every hit keeps its fused score.
+ assert {hit.item_id: hit.score for hit in results} == {
+ hit.item_id: hit.score for hit in baseline
+ }
+ # The reranker saw one call with all three snippets.
+ assert len(fake.calls) == 1
+ assert len(fake.calls[0][1]) == 3
+ # The k cut applies AFTER the rerank order.
+ top_two = await hybrid_search(store, cfg, "alpha", k=2)
+ assert [hit.item_id for hit in top_two] == [id_2, id_1]
+
+
+async def test_rerank_error_falls_back_to_fusion_order(store, monkeypatch, caplog):
+ id_0, id_1, id_2 = await seed_three_ranked_items(store)
+ fake = FakeReranker(error=RerankError("fake: HTTP 500"))
+ monkeypatch.setattr(rerank_mod, "resolve_reranker", lambda cfg: fake)
+ cfg = make_cfg(rerank_provider="voyage")
+
+ with caplog.at_level(logging.WARNING, logger="jarvis.ultrawiki.search"):
+ results = await hybrid_search(store, cfg, "alpha")
+
+ assert [hit.item_id for hit in results] == [id_0, id_1, id_2]
+ warnings = [rec for rec in caplog.records if "rerank failed" in rec.message]
+ assert len(warnings) == 1
+
+
+async def test_rerank_skipped_when_provider_not_ready(store, monkeypatch):
+ id_0, id_1, id_2 = await seed_three_ranked_items(store)
+ # resolve_reranker returning None == unconfigured/unknown/not ready.
+ monkeypatch.setattr(rerank_mod, "resolve_reranker", lambda cfg: None)
+ cfg = make_cfg(rerank_provider="voyage")
+
+ results = await hybrid_search(store, cfg, "alpha")
+
+ assert [hit.item_id for hit in results] == [id_0, id_1, id_2]
+
+
+# ---------------------------------------------------------------------------
+# search_status
+# ---------------------------------------------------------------------------
+
+
+def test_search_status_unconfigured():
+ status = search_status(make_cfg())
+
+ assert status["keyword"] == {"available": True}
+ assert status["vector"]["available"] is False
+ assert status["vector"]["reason"] # honest, non-empty English reason
+ assert status["rerank"] == {"available": False, "provider": "off"}
+
+
+def test_search_status_tolerates_missing_ultrawiki_section():
+ status = search_status(SimpleNamespace())
+
+ assert status["keyword"] == {"available": True}
+ assert status["vector"]["available"] is False
+ assert status["rerank"]["provider"] == "off"
+
+
+def test_search_status_reports_configured_legs(monkeypatch):
+ register_fake_embedding(monkeypatch, FakeEmbedding())
+ monkeypatch.setitem(rerank_mod.RERANK_BACKENDS, "fake", lambda cfg: FakeReranker())
+ cfg = make_cfg(
+ embedding_provider="fake",
+ embedding_model=EMBED_MODEL,
+ rerank_provider="fake",
+ )
+
+ status = search_status(cfg)
+
+ assert status["vector"] == {
+ "available": True,
+ "backend": "fake",
+ "model": EMBED_MODEL,
+ }
+ assert status["rerank"] == {"available": True, "provider": "fake"}
+
+
+def test_search_status_unknown_embedding_provider():
+ status = search_status(make_cfg(embedding_provider="does-not-exist"))
+
+ assert status["vector"]["available"] is False
+ assert "does-not-exist" in status["vector"]["reason"]
diff --git a/tests/unit/ultrawiki/test_service.py b/tests/unit/ultrawiki/test_service.py
new file mode 100644
index 0000000000..f0b8c30c6f
--- /dev/null
+++ b/tests/unit/ultrawiki/test_service.py
@@ -0,0 +1,331 @@
+"""UltraWikiService unit tests — tmp SQLite store, fake connectors, offline.
+
+Covers: activation registering PENDING sources without pulling a byte; the
+consent + enabled refusal gates on start_sync; a full approved sync with
+chunked upserts, per-chunk checkpoints, cursor advance, and a terminal job
+snapshot; mid-stream cancellation; and the cancel-then-close shutdown leaving
+no stray tasks. No network, no credentials, no models.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import time
+from pathlib import Path
+from types import SimpleNamespace
+from typing import Any
+
+import pytest
+
+import jarvis.ultrawiki.connectors as connectors_mod
+from jarvis.ultrawiki.service import (
+ JOB_TERMINAL_STATUSES,
+ UltraWikiService,
+ clear_jobs,
+)
+from jarvis.ultrawiki.types import (
+ AuthKind,
+ ConnectorCapabilities,
+ IncrementalMode,
+ RawItem,
+)
+
+
+def make_cfg(tmp_path: Path, *, enabled: bool = True) -> SimpleNamespace:
+ return SimpleNamespace(
+ ultrawiki=SimpleNamespace(
+ enabled=enabled,
+ db_backend="sqlite",
+ embedding_provider="",
+ embedding_model="",
+ distill_provider="",
+ distill_model="",
+ rerank_provider="",
+ ollama_endpoint="",
+ ),
+ memory=SimpleNamespace(data_dir=str(tmp_path)),
+ brain=SimpleNamespace(primary=""),
+ )
+
+
+def make_items(count: int) -> list[RawItem]:
+ return [
+ RawItem(
+ external_id=f"f-{index:04d}",
+ body=f"fake item body {index}",
+ permalink=f"fake://item/{index}",
+ timestamp_utc=f"2026-01-01T00:{index % 60:02d}:00Z",
+ title=f"Fake {index}",
+ metadata={"mtime_ns": 1000 + index},
+ )
+ for index in range(count)
+ ]
+
+
+class FakeConnector:
+ """Cursor-capable fake following the file-walker connector conventions."""
+
+ id = "fake-conn"
+ label = "Fake Connector"
+ auth = AuthKind.NONE
+ capabilities = ConnectorCapabilities(
+ backfill=True, incremental=IncrementalMode.CURSOR, deletes=True
+ )
+
+ def __init__(self, items: list[RawItem], calls: list[tuple[str, Any]]) -> None:
+ self._items = items
+ self.calls = calls
+
+ async def backfill(self, ctx: Any, checkpoint: str | None = None):
+ self.calls.append(("backfill", checkpoint))
+ for item in self._items:
+ if checkpoint and item.external_id <= checkpoint:
+ continue
+ yield item
+
+ async def incremental(self, ctx: Any, cursor: str | None = None):
+ self.calls.append(("incremental", cursor))
+ threshold = int(cursor) if cursor else 0
+ for item in self._items:
+ if int(item.metadata.get("mtime_ns", 0)) > threshold:
+ yield item
+
+
+class BlockingConnector:
+ """Yields its items, then blocks until the test releases (or cancels) it."""
+
+ id = "blocking-conn"
+ label = "Blocking Connector"
+ auth = AuthKind.NONE
+ capabilities = ConnectorCapabilities(
+ backfill=True, incremental=IncrementalMode.NONE, deletes=False
+ )
+
+ def __init__(
+ self, items: list[RawItem], gate: asyncio.Event, reached: asyncio.Event
+ ) -> None:
+ self._items = items
+ self._gate = gate
+ self._reached = reached
+
+ async def backfill(self, ctx: Any, checkpoint: str | None = None):
+ for item in self._items:
+ yield item
+ self._reached.set()
+ await self._gate.wait()
+
+ async def incremental(self, ctx: Any, cursor: str | None = None):
+ return
+ yield # pragma: no cover — makes this an async generator
+
+
+async def service(tmp_path: Path):
+ clear_jobs()
+ svc = UltraWikiService(make_cfg(tmp_path))
+ yield svc
+ await svc.shutdown()
+ clear_jobs()
+
+
+async def wait_for_job(
+ svc: UltraWikiService, job_id: str, *, deadline_s: float = 5.0
+) -> dict[str, Any]:
+ deadline = time.monotonic() + deadline_s
+ while time.monotonic() < deadline:
+ snap = svc.job_snapshot(job_id)
+ if snap is not None and snap["status"] in JOB_TERMINAL_STATUSES:
+ return snap
+ await asyncio.sleep(0.01)
+ raise AssertionError(f"job {job_id} did not finish: {svc.job_snapshot(job_id)}")
+
+
+def patch_connectors(monkeypatch: pytest.MonkeyPatch, registry: dict[str, Any]) -> None:
+ monkeypatch.setattr(connectors_mod, "discover_connectors", lambda: registry)
+
+
+# ---------------------------------------------------------------------------
+# Activation
+# ---------------------------------------------------------------------------
+
+
+async def test_activate_registers_pending_sources_and_pulls_nothing(service):
+ result = await service.activate({})
+
+ assert result["default_area"]
+ assert sorted(result["sources_created"]) == [
+ "jarvis-conversations",
+ "normal-wiki",
+ ]
+ status = await service.status()
+ assert status["started"] is True
+ assert status["backend"]["in_use"] == "sqlite"
+ by_id = {src["id"]: src for src in status["sources"]}
+ assert by_id["normal-wiki"]["consent"] == "pending"
+ assert by_id["jarvis-conversations"]["consent"] == "pending"
+ # Nothing was pulled: zero items, zero sync jobs.
+ assert status["counts"]["total"] == 0
+ assert service.list_jobs() == []
+
+ # Activation is idempotent — a second run creates nothing new.
+ again = await service.activate({})
+ assert again["sources_created"] == []
+ assert sorted(again["sources_existing"]) == [
+ "jarvis-conversations",
+ "normal-wiki",
+ ]
+
+
+async def test_activate_seeds_extra_areas(service):
+ result = await service.activate({"areas": ["Work Stuff"]})
+ assert "work-stuff" in result["areas_created"]
+ store = service._require_store()
+ area_ids = {area["id"] for area in await store.list_areas()}
+ assert "work-stuff" in area_ids
+
+
+# ---------------------------------------------------------------------------
+# Consent + enabled gates
+# ---------------------------------------------------------------------------
+
+
+async def test_start_sync_refuses_unapproved_source(service):
+ await service.activate({})
+ with pytest.raises(ValueError, match="not approved"):
+ await service.start_sync("normal-wiki")
+
+
+async def test_start_sync_refuses_when_disabled(tmp_path):
+ svc = UltraWikiService(make_cfg(tmp_path, enabled=False))
+ try:
+ with pytest.raises(ValueError, match="disabled"):
+ await svc.start_sync("anything")
+ finally:
+ await svc.shutdown()
+
+
+async def test_add_source_rejects_unknown_connector(service, monkeypatch):
+ patch_connectors(monkeypatch, {})
+ with pytest.raises(ValueError, match="unknown connector"):
+ await service.add_source("no-such-conn", "Nope")
+
+
+# ---------------------------------------------------------------------------
+# Approved sync: chunked ingest, checkpoints, cursor advance, job snapshot
+# ---------------------------------------------------------------------------
+
+
+async def test_approved_sync_ingests_with_checkpoints_and_cursor(service, monkeypatch):
+ items = make_items(450) # 3 chunks: 200 + 200 + 50
+ calls: list[tuple[str, Any]] = []
+ patch_connectors(
+ monkeypatch, {"fake-conn": lambda: FakeConnector(items, calls)}
+ )
+
+ source = await service.add_source("fake-conn", "Fake Source")
+ source_id = source["id"]
+ approved = await service.approve_source(source_id)
+ assert approved["consent"] == "approved"
+
+ job_id = await service.start_sync(source_id)
+ snap = await wait_for_job(service, job_id)
+
+ assert snap["status"] == "done"
+ assert snap["mode"] == "backfill"
+ assert snap["new"] == 450
+ assert snap["chunks"] == 3
+ assert snap["tombstoned"] == 0
+ assert snap["error"] == ""
+
+ store = service._require_store()
+ sync_state = await store.get_sync_state(source_id)
+ assert sync_state is not None
+ assert sync_state["backfill_complete_at"]
+ assert sync_state["backfill_checkpoint"] == "f-0449"
+ assert sync_state["cursor"] == str(1000 + 449) # max mtime_ns convention
+ refreshed = await store.get_source(source_id)
+ assert refreshed["last_sync_at"]
+ assert refreshed["last_error"] is None
+ counts = await store.counts_for_source(source_id)
+ assert counts.total == 450
+
+ # A second sync switches to incremental and resumes from the cursor.
+ job2_id = await service.start_sync(source_id)
+ snap2 = await wait_for_job(service, job2_id)
+ assert snap2["status"] == "done"
+ assert snap2["mode"] == "incremental"
+ assert snap2["new"] == 0
+ assert ("incremental", "1449") in calls
+
+
+# ---------------------------------------------------------------------------
+# Cancellation
+# ---------------------------------------------------------------------------
+
+
+async def test_cancel_job_mid_stream_stops_the_sync(service, monkeypatch):
+ gate = asyncio.Event()
+ reached = asyncio.Event()
+ items = make_items(250) # one full chunk lands, 50 stay buffered
+ patch_connectors(
+ monkeypatch,
+ {"blocking-conn": lambda: BlockingConnector(items, gate, reached)},
+ )
+
+ source = await service.add_source("blocking-conn", "Blocked Source")
+ await service.approve_source(source["id"])
+ job_id = await service.start_sync(source["id"])
+
+ await asyncio.wait_for(reached.wait(), timeout=5.0)
+ assert service.cancel_job(job_id) is True
+ snap = await wait_for_job(service, job_id)
+
+ assert snap["status"] == "cancelled"
+ assert snap["new"] == 200 # the flushed chunk survived, the buffer did not
+ store = service._require_store()
+ counts = await store.counts_for_source(source["id"])
+ assert counts.total == 200
+ # Cancelling a terminal job is a no-op.
+ assert service.cancel_job(job_id) is False
+
+
+# ---------------------------------------------------------------------------
+# Shutdown discipline
+# ---------------------------------------------------------------------------
+
+
+async def test_shutdown_leaves_no_stray_tasks(service, monkeypatch):
+ gate = asyncio.Event()
+ reached = asyncio.Event()
+ patch_connectors(
+ monkeypatch,
+ {"blocking-conn": lambda: BlockingConnector(make_items(10), gate, reached)},
+ )
+ await service.activate({})
+ pipeline_task = service._pipeline_task
+ assert pipeline_task is not None and not pipeline_task.done()
+
+ source = await service.add_source("blocking-conn", "Blocked Source")
+ await service.approve_source(source["id"])
+ job_id = await service.start_sync(source["id"])
+ await asyncio.wait_for(reached.wait(), timeout=5.0)
+ sync_task = service._sync_tasks[job_id]
+
+ await service.shutdown()
+
+ assert pipeline_task.done()
+ assert sync_task.done()
+ assert service._pipeline_task is None
+ assert service._sync_tasks == {}
+ assert service._store is None
+ snap = service.job_snapshot(job_id)
+ assert snap is not None and snap["status"] == "cancelled"
+
+
+async def test_ensure_started_is_idempotent(service):
+ await service.ensure_started()
+ first_store = service._store
+ first_task = service._pipeline_task
+ await service.ensure_started()
+ assert service._store is first_store
+ assert service._pipeline_task is first_task
diff --git a/tests/unit/ultrawiki/test_state_machine_gates.py b/tests/unit/ultrawiki/test_state_machine_gates.py
new file mode 100644
index 0000000000..2151821801
--- /dev/null
+++ b/tests/unit/ultrawiki/test_state_machine_gates.py
@@ -0,0 +1,207 @@
+"""The four P1 roadmap gates (UltraWiki/06-roadmap.md) as automated tests.
+
+(a) a 1000-item backfill interrupted mid-run converges to an identical end
+ state on re-run — no duplicates, no gaps;
+(b) one poisoned item dead-letters after retries while the other 999 keep
+ progressing — nothing is blocked;
+(c) a second identical upsert creates ZERO new work — no state resets, no
+ new documents (content-hash proof);
+(d) the whole file runs offline with no credentials and no optional
+ dependencies (sqlite-vec / psycopg both unavailable).
+"""
+
+from __future__ import annotations
+
+import pytest
+
+import jarvis.ultrawiki.store as store_mod
+from jarvis.ultrawiki.store import PostgresStore, UltraStore
+from jarvis.ultrawiki.types import ConsentState, DocType, ItemState, RawItem
+
+
+def make_items(count: int) -> list[RawItem]:
+ items = []
+ for index in range(count):
+ hours, rem = divmod(index, 3600)
+ minutes, seconds = divmod(rem, 60)
+ items.append(
+ RawItem(
+ external_id=f"ext-{index:04d}",
+ body=f"body text number{index} alpha",
+ permalink=f"app://item/{index}",
+ timestamp_utc=(
+ f"2026-01-01T{hours % 24:02d}:{minutes:02d}:{seconds:02d}Z"
+ ),
+ title=f"Item {index}",
+ )
+ )
+ return items
+
+
+async def store(tmp_path):
+ instance = UltraStore(tmp_path / "ultrawiki.db")
+ await instance.upsert_source(
+ "src1", connector="local-folder", label="Gate source"
+ )
+ await instance.set_consent("src1", ConsentState.APPROVED)
+ yield instance
+ await instance.close()
+
+
+async def index_keyword(store: UltraStore, claimed: dict) -> None:
+ await store.mark_stage_done(
+ claimed["id"],
+ ItemState.KEYWORD_INDEXED,
+ fts_title=claimed["title"],
+ fts_body=claimed["body_raw"],
+ )
+
+
+async def test_gate_a_interrupted_backfill_converges(store):
+ """Upsert in two chunks (simulating a mid-run kill), then re-run the
+ FULL set: identical end state, no duplicates, no gaps, no resets."""
+ items = make_items(1000)
+
+ # First run dies after 600 items ...
+ first = await store.upsert_items("src1", items[:600])
+ assert first.new == 600
+
+ # ... having already advanced 300 of them through the keyword stage.
+ for claimed in await store.claim_batch(ItemState.KEYWORD_INDEXED, limit=300):
+ await index_keyword(store, claimed)
+
+ # The restarted backfill re-yields EVERYTHING (unparsable-checkpoint
+ # convention: safe full re-yield, idempotent upserts).
+ second = await store.upsert_items("src1", items)
+ assert (second.new, second.changed, second.unchanged) == (400, 0, 600)
+
+ counts = await store.counts()
+ assert counts.total == 1000 # no dupes (UNIQUE upsert), no gaps
+ assert counts.keyword_indexed == 300 # finished work survived untouched
+ assert counts.captured == 700
+
+ # Drain the remaining work; the ladder converges completely.
+ remaining = await store.claim_batch(ItemState.KEYWORD_INDEXED, limit=2000)
+ assert len(remaining) == 700
+ for claimed in remaining:
+ await index_keyword(store, claimed)
+ counts = await store.counts()
+ assert counts.keyword_indexed == 1000
+ assert counts.captured == 0
+
+ # A third full re-run is a pure no-op.
+ third = await store.upsert_items("src1", items)
+ assert (third.new, third.changed, third.unchanged) == (0, 0, 1000)
+ assert (await store.counts()).keyword_indexed == 1000
+
+
+async def test_gate_b_poisoned_item_blocks_nothing(store):
+ """One item dead-letters after 5 retries; the other 999 progress."""
+ await store.upsert_items("src1", make_items(1000))
+
+ claimed = await store.claim_batch(ItemState.KEYWORD_INDEXED, limit=1000)
+ assert len(claimed) == 1000
+ poison, healthy = claimed[0], claimed[1:]
+
+ for _ in range(5):
+ await store.mark_retry(poison["id"], "connector exploded at this item")
+ for item in healthy:
+ await index_keyword(store, item)
+
+ counts = await store.counts()
+ assert counts.failed == 1
+ assert counts.keyword_indexed == 999
+ assert counts.captured == 0
+
+ # The dead-lettered item never reappears in any claim; the healthy 999
+ # are claimable for the next stage.
+ assert await store.claim_batch(ItemState.KEYWORD_INDEXED, limit=10) == []
+ next_stage = await store.claim_batch(ItemState.EMBEDDED, limit=2000)
+ assert len(next_stage) == 999
+ assert poison["id"] not in {item["id"] for item in next_stage}
+ failed_item = await store.get_item(poison["id"])
+ assert failed_item["state"] == ItemState.FAILED.value
+ assert failed_item["last_error"] == "connector exploded at this item"
+
+
+async def test_gate_c_second_identical_upsert_creates_zero_new_work(store):
+ """Content-hash proof: an identical re-run touches nothing at all."""
+ items = make_items(200)
+ await store.upsert_items("src1", items)
+ for claimed in await store.claim_batch(ItemState.KEYWORD_INDEXED, limit=200):
+ await index_keyword(store, claimed)
+ sample = await store.claim_batch(ItemState.EMBEDDED, limit=1)
+ doc_id = await store.add_document(
+ sample[0]["id"], DocType.SUMMARY, "distilled summary"
+ )
+
+ before = {}
+ for index in range(200):
+ item = await store.get_item_by_external_id("src1", f"ext-{index:04d}")
+ before[item["external_id"]] = item
+
+ rerun = await store.upsert_items("src1", items)
+ assert (rerun.new, rerun.changed, rerun.unchanged) == (0, 0, 200)
+
+ for index in range(200):
+ item = await store.get_item_by_external_id("src1", f"ext-{index:04d}")
+ assert item == before[item["external_id"]] # byte-identical rows
+
+ # Derived work survived (no document/FTS churn) and search still answers.
+ # With foreign_keys=ON this embedding insert would fail if the rerun had
+ # purged the document — its success proves the document row survived.
+ assert len(await store.keyword_search("number7")) == 1
+ await store.store_embedding(doc_id, model="m", dim=4, vector=[1, 0, 0, 0])
+
+
+async def test_gate_d_runs_offline_with_no_optional_deps_and_no_credentials(
+ tmp_path, monkeypatch
+):
+ """The store pipeline is complete with ZERO optional dependencies: no
+ sqlite-vec, no psycopg, no network, no credentials — the universal
+ headless-Linux floor (CLAUDE.md section 3)."""
+
+ def _no_sqlite_vec():
+ raise ImportError("sqlite-vec unavailable (gate d)")
+
+ def _no_psycopg():
+ raise ImportError(
+ "PostgresStore requires the 'psycopg' driver, which is not "
+ "installed. Install it with: pip install "
+ "personal-jarvis[ultrawiki-postgres]. The SQLite backend keeps "
+ "working without it."
+ )
+
+ monkeypatch.setattr(store_mod, "_import_sqlite_vec", _no_sqlite_vec)
+ monkeypatch.setattr(store_mod, "_import_psycopg", _no_psycopg)
+
+ store = UltraStore(tmp_path / "floor.db")
+ try:
+ await store.upsert_source("src1", connector="local-folder", label="Floor")
+ await store.set_consent("src1", ConsentState.APPROVED)
+ await store.upsert_items("src1", make_items(10))
+ for claimed in await store.claim_batch(ItemState.KEYWORD_INDEXED, limit=10):
+ await index_keyword(store, claimed)
+
+ # Keyword search: fully functional.
+ assert len(await store.keyword_search("number3")) == 1
+
+ # Embeddings accumulate; the vector leg degrades honestly.
+ item = (await store.claim_batch(ItemState.EMBEDDED, limit=1))[0]
+ doc_id = await store.add_document(item["id"], DocType.SUMMARY, "summary")
+ await store.store_embedding(doc_id, model="m", dim=4, vector=[1, 0, 0, 0])
+ results, reason = await store.vector_search([1, 0, 0, 0])
+ assert results == []
+ assert reason # an honest English explanation, never a crash
+
+ # The distillation cache works without any provider.
+ await store.distill_cache_put("h", 1, "m", "{}")
+ assert await store.distill_cache_get("h", 1, "m") == "{}"
+
+ # The Postgres option reports its missing driver honestly.
+ ok, message = await PostgresStore.connect_test("postgresql://localhost/x")
+ assert ok is False
+ assert "ultrawiki-postgres" in message
+ finally:
+ await store.close()
diff --git a/tests/unit/ultrawiki/test_state_parity.py b/tests/unit/ultrawiki/test_state_parity.py
new file mode 100644
index 0000000000..8e6efb646c
--- /dev/null
+++ b/tests/unit/ultrawiki/test_state_parity.py
@@ -0,0 +1,55 @@
+"""Five-layer drift guard (AP-4 / BUG-008): the SQL CHECK value lists must
+equal the canonical enum value sets in ``jarvis/ultrawiki/types.py`` —
+for the frozen SQLite schema AND the derived Postgres DDL."""
+
+from __future__ import annotations
+
+import re
+from pathlib import Path
+
+import jarvis.ultrawiki
+from jarvis.ultrawiki.store import PostgresStore
+from jarvis.ultrawiki.types import STATE_ORDER, ConsentState, DocType, ItemState
+
+SCHEMA_SQL = (Path(jarvis.ultrawiki.__file__).parent / "schema.sql").read_text(
+ encoding="utf-8"
+)
+POSTGRES_DDL = "\n".join(PostgresStore.ddl_statements())
+
+
+def check_values(sql: str, column: str) -> set[str]:
+ """Extract the quoted value list of ``CHECK (<column> IN (...))``."""
+ match = re.search(rf"CHECK\s*\(\s*{column}\s+IN\s*\(([^)]*)\)", sql, re.IGNORECASE)
+ assert match is not None, f"no CHECK list found for column {column!r}"
+ return set(re.findall(r"'([^']+)'", match.group(1)))
+
+
+def test_sqlite_state_check_matches_item_state_enum():
+ assert check_values(SCHEMA_SQL, "state") == {state.value for state in ItemState}
+
+
+def test_sqlite_consent_check_matches_consent_state_enum():
+ assert check_values(SCHEMA_SQL, "consent") == {
+ consent.value for consent in ConsentState
+ }
+
+
+def test_sqlite_doc_type_check_matches_doc_type_enum():
+ assert check_values(SCHEMA_SQL, "doc_type") == {doc.value for doc in DocType}
+
+
+def test_postgres_ddl_check_lists_match_enums():
+ assert check_values(POSTGRES_DDL, "state") == {state.value for state in ItemState}
+ assert check_values(POSTGRES_DDL, "consent") == {
+ consent.value for consent in ConsentState
+ }
+ assert check_values(POSTGRES_DDL, "doc_type") == {doc.value for doc in DocType}
+
+
+def test_state_order_is_the_forward_ladder_without_failed():
+ """The ladder covers every good state exactly once; ``failed`` sits
+ outside it (dead-letter, never a claim target)."""
+ ladder = {state.value for state in STATE_ORDER}
+ assert ladder == {state.value for state in ItemState} - {ItemState.FAILED.value}
+ assert len(STATE_ORDER) == len(set(STATE_ORDER))
+ assert ItemState.FAILED not in STATE_ORDER
diff --git a/tests/unit/ultrawiki/test_store.py b/tests/unit/ultrawiki/test_store.py
new file mode 100644
index 0000000000..05b384f9fc
--- /dev/null
+++ b/tests/unit/ultrawiki/test_store.py
@@ -0,0 +1,532 @@
+"""UltraStore unit tests — SQLite backend over tmp_path DBs, fully offline.
+
+Covers: schema idempotency, source CRUD + consent, idempotent item upserts,
+tombstones + reconcile, FTS lockstep with the state machine, the embedding
+pin, reset_vectors, the real sqlite-vec round-trip (when the host has the
+extension) AND the honest degraded path, plus the Postgres driver's missing-
+dependency message. No network, no credentials, no models.
+"""
+
+from __future__ import annotations
+
+import importlib.util
+import sys
+
+import pytest
+
+import jarvis.ultrawiki.store as store_mod
+from jarvis.ultrawiki.store import (
+ META_EMBED_DIM,
+ META_EMBED_MODEL,
+ PostgresStore,
+ UltraStore,
+ UltraStoreError,
+ resolve_ultrawiki_db_path,
+)
+from jarvis.ultrawiki.types import ConsentState, DocType, ItemState, RawItem
+
+HAS_SQLITE_VEC = importlib.util.find_spec("sqlite_vec") is not None
+
+
+def make_item(
+ index: int,
+ *,
+ body: str | None = None,
+ title: str | None = None,
+ deleted: bool = False,
+) -> RawItem:
+ hours, rem = divmod(index, 3600)
+ minutes, seconds = divmod(rem, 60)
+ return RawItem(
+ external_id=f"ext-{index:04d}",
+ body=body if body is not None else f"body text number{index} alpha",
+ permalink=f"app://item/{index}",
+ timestamp_utc=f"2026-01-01T{hours % 24:02d}:{minutes:02d}:{seconds:02d}Z",
+ title=title if title is not None else f"Item {index}",
+ deleted=deleted,
+ )
+
+
+async def store(tmp_path):
+ instance = UltraStore(tmp_path / "ultrawiki.db")
+ yield instance
+ await instance.close()
+
+
+async def add_source(
+ store: UltraStore, source_id: str = "src1", areas: list[str] | None = None
+) -> str:
+ await store.upsert_source(
+ source_id, connector="local-folder", label="Test source", areas=areas
+ )
+ await store.set_consent(source_id, ConsentState.APPROVED)
+ return source_id
+
+
+async def index_keyword(store: UltraStore, claimed: dict) -> None:
+ await store.mark_stage_done(
+ claimed["id"],
+ ItemState.KEYWORD_INDEXED,
+ fts_title=claimed["title"],
+ fts_body=claimed["body_raw"],
+ )
+
+
+# ---------------------------------------------------------------------------
+# Path resolution + schema idempotency
+# ---------------------------------------------------------------------------
+
+
+def test_path_resolution_is_absolute_and_cwd_independent(tmp_path):
+ relative = resolve_ultrawiki_db_path("data")
+ assert relative.is_absolute()
+ assert relative.name == "ultrawiki.db"
+ absolute = resolve_ultrawiki_db_path(tmp_path)
+ assert absolute == (tmp_path / "ultrawiki.db").resolve()
+ default = resolve_ultrawiki_db_path(None)
+ assert default.is_absolute()
+
+
+async def test_double_open_is_idempotent(tmp_path):
+ db_path = tmp_path / "ultrawiki.db"
+ first = UltraStore(db_path)
+ await first.open()
+ await first.open() # second open on the same instance is a no-op
+ await add_source(first)
+ await first.upsert_items("src1", [make_item(0)])
+ await first.close()
+
+ # A brand-new instance re-applies the idempotent schema and sees the data.
+ second = UltraStore(db_path)
+ await second.open()
+ counts = await second.counts()
+ assert counts.total == 1
+ await second.close()
+
+
+# ---------------------------------------------------------------------------
+# Sources & consent
+# ---------------------------------------------------------------------------
+
+
+async def test_source_crud_and_consent_transitions(store):
+ await store.upsert_source(
+ "src1", connector="local-folder", label="Notes", areas=["work"]
+ )
+ source = await store.get_source("src1")
+ assert source is not None
+ assert source["consent"] == ConsentState.PENDING.value
+ assert source["enabled"] is True
+ assert source["areas"] == ["work"]
+
+ await store.set_consent("src1", ConsentState.APPROVED)
+ assert (await store.get_source("src1"))["consent"] == "approved"
+ await store.set_consent("src1", "revoked") # plain string accepted
+ assert (await store.get_source("src1"))["consent"] == "revoked"
+ with pytest.raises(ValueError):
+ await store.set_consent("src1", "maybe")
+
+ await store.set_enabled("src1", False)
+ assert (await store.get_source("src1"))["enabled"] is False
+
+ # A config upsert must never reset user-granted consent/enablement.
+ await store.upsert_source("src1", connector="local-folder", label="Renamed")
+ source = await store.get_source("src1")
+ assert source["label"] == "Renamed"
+ assert source["consent"] == "revoked"
+ assert source["enabled"] is False
+ assert source["areas"] == ["work"] # None areas keeps existing
+
+ listed = await store.list_sources()
+ assert len(listed) == 1
+ assert listed[0]["counts"].total == 0
+ assert listed[0]["sync_state"] is None
+
+
+async def test_delete_source_purge_semantics(store):
+ await add_source(store)
+ await store.upsert_items("src1", [make_item(i) for i in range(3)])
+ await store.set_sync_state("src1", cursor="abc")
+
+ # purge=False disconnects but keeps captured data.
+ await store.delete_source("src1", purge=False)
+ source = await store.get_source("src1")
+ assert source is not None
+ assert source["consent"] == "revoked"
+ assert source["enabled"] is False
+ assert (await store.counts_for_source("src1")).total == 3
+
+ # purge=True removes the source and every derived row.
+ await store.delete_source("src1", purge=True)
+ assert await store.get_source("src1") is None
+ assert (await store.counts()).total == 0
+ assert await store.get_sync_state("src1") is None
+
+
+# ---------------------------------------------------------------------------
+# Item upserts, tombstones, reconcile
+# ---------------------------------------------------------------------------
+
+
+async def test_item_upsert_idempotency_counts(store):
+ await add_source(store)
+ items = [make_item(i) for i in range(5)]
+ first = await store.upsert_items("src1", items)
+ assert (first.new, first.changed, first.unchanged) == (5, 0, 0)
+
+ second = await store.upsert_items("src1", items)
+ assert (second.new, second.changed, second.unchanged) == (0, 0, 5)
+
+ edited = [make_item(0, body="edited body zeta"), *items[1:]]
+ third = await store.upsert_items("src1", edited)
+ assert (third.new, third.changed, third.unchanged) == (0, 1, 4)
+ changed_item = await store.get_item_by_external_id("src1", "ext-0000")
+ assert changed_item["state"] == ItemState.CAPTURED.value
+ assert changed_item["body_raw"] == "edited body zeta"
+
+ with pytest.raises(UltraStoreError):
+ await store.upsert_items("ghost-source", items)
+
+
+async def test_tombstones_and_reconcile_deletes(store):
+ await add_source(store)
+ await store.upsert_items("src1", [make_item(i) for i in range(4)])
+ for claimed in await store.claim_batch(ItemState.KEYWORD_INDEXED, limit=10):
+ await index_keyword(store, claimed)
+
+ # Explicit tombstone via RawItem.deleted.
+ result = await store.upsert_items("src1", [make_item(0, deleted=True)])
+ assert result.tombstoned == 1
+ assert (await store.counts()).total == 3
+ tombstoned = await store.get_item_by_external_id("src1", "ext-0000")
+ assert tombstoned["deleted_at"] is not None
+ assert await store.keyword_search("number0") == []
+
+ # A FULL backfill that no longer yields ext-0001 tombstones it.
+ survivors = {"ext-0002", "ext-0003"}
+ removed = await store.reconcile_deletes("src1", survivors)
+ assert removed == 1
+ assert (await store.counts()).total == 2
+ assert await store.keyword_search("number1") == []
+ assert len(await store.keyword_search("number2")) == 1
+
+ # Resurrection: the tombstoned item coming back is treated as changed.
+ revived = await store.upsert_items("src1", [make_item(0)])
+ assert revived.changed == 1
+ assert (await store.counts()).total == 3
+
+
+# ---------------------------------------------------------------------------
+# FTS lockstep with the state machine
+# ---------------------------------------------------------------------------
+
+
+async def test_fts_lockstep_with_keyword_stage(store):
+ await add_source(store)
+ await store.upsert_items("src1", [make_item(0)])
+
+ # Captured but not yet keyword-indexed: not findable.
+ assert await store.keyword_search("number0") == []
+
+ claimed = await store.claim_batch(ItemState.KEYWORD_INDEXED, limit=10)
+ assert len(claimed) == 1
+ await index_keyword(store, claimed[0])
+
+ hits = await store.keyword_search("number0")
+ assert len(hits) == 1
+ hit = hits[0]
+ assert hit.item_id == claimed[0]["id"]
+ assert hit.source_id == "src1"
+ assert hit.permalink == "app://item/0"
+ assert hit.matched_by == ("keyword",)
+ assert 0.0 <= hit.score <= 1.0
+
+ # Changed content resets the state AND removes the stale FTS row in the
+ # same batch; the new body is findable only after re-indexing.
+ await store.upsert_items("src1", [make_item(0, body="completely new gamma")])
+ assert await store.keyword_search("number0") == []
+ assert await store.keyword_search("gamma") == []
+ reclaimed = await store.claim_batch(ItemState.KEYWORD_INDEXED, limit=10)
+ assert len(reclaimed) == 1
+ await index_keyword(store, reclaimed[0])
+ assert await store.keyword_search("number0") == []
+ assert len(await store.keyword_search("gamma")) == 1
+
+
+# ---------------------------------------------------------------------------
+# Claim ordering, retry backoff, dead-letter
+# ---------------------------------------------------------------------------
+
+
+async def test_claim_batch_orders_newest_first_and_honors_retry(store):
+ await add_source(store)
+ await store.upsert_items("src1", [make_item(i) for i in range(3)])
+
+ claimed = await store.claim_batch(ItemState.KEYWORD_INDEXED, limit=2)
+ assert [item["external_id"] for item in claimed] == ["ext-0002", "ext-0001"]
+
+ victim = claimed[0]
+ await store.mark_retry(victim["id"], "stage blew up", now="2026-02-01T00:00:00Z")
+ after = await store.get_item(victim["id"])
+ assert after["attempt_count"] == 1
+ assert after["state"] == ItemState.CAPTURED.value # keeps last good state
+ assert after["last_error"] == "stage blew up"
+
+ # Not eligible before the 60 s backoff elapses; eligible afterwards.
+ at_failure = [
+ item["external_id"]
+ for item in await store.claim_batch(
+ ItemState.KEYWORD_INDEXED, limit=10, now="2026-02-01T00:00:30Z"
+ )
+ ]
+ assert victim["external_id"] not in at_failure
+ after_backoff = [
+ item["external_id"]
+ for item in await store.claim_batch(
+ ItemState.KEYWORD_INDEXED, limit=10, now="2026-02-01T00:01:00Z"
+ )
+ ]
+ assert victim["external_id"] in after_backoff
+
+
+async def test_mark_retry_dead_letters_after_five_attempts(store):
+ await add_source(store)
+ await store.upsert_items("src1", [make_item(0)])
+ item = (await store.claim_batch(ItemState.KEYWORD_INDEXED, limit=1))[0]
+ for _ in range(5):
+ await store.mark_retry(item["id"], "poison")
+ final = await store.get_item(item["id"])
+ assert final["state"] == ItemState.FAILED.value
+ assert final["attempt_count"] == 5
+ assert (await store.counts()).failed == 1
+ assert await store.claim_batch(ItemState.KEYWORD_INDEXED, limit=10) == []
+
+
+async def test_state_machine_input_validation(store):
+ with pytest.raises(ValueError):
+ await store.claim_batch(ItemState.CAPTURED)
+ with pytest.raises(ValueError):
+ await store.claim_batch("failed")
+ with pytest.raises(ValueError):
+ await store.claim_batch("bogus")
+ with pytest.raises(ValueError):
+ await store.mark_stage_done(1, ItemState.CAPTURED)
+ with pytest.raises(ValueError):
+ await store.mark_stage_done(1, "failed")
+
+
+# ---------------------------------------------------------------------------
+# Embedding pin + reset_vectors
+# ---------------------------------------------------------------------------
+
+
+async def _seed_embedded_item(store: UltraStore, index: int = 0) -> tuple[int, int]:
+ """Returns (item_id, document_id) with the item advanced to embedded."""
+ await store.upsert_items("src1", [make_item(index)])
+ claimed = await store.claim_batch(ItemState.KEYWORD_INDEXED, limit=100)
+ target = next(c for c in claimed if c["external_id"] == f"ext-{index:04d}")
+ await index_keyword(store, target)
+ doc_id = await store.add_document(
+ target["id"], DocType.SUMMARY, f"summary text for item {index}"
+ )
+ return target["id"], doc_id
+
+
+async def test_embedding_pin_and_dim_mismatch_rejection(store):
+ await add_source(store)
+ _, doc_id = await _seed_embedded_item(store, 0)
+ await store.store_embedding(doc_id, model="model-a", dim=4, vector=[1, 0, 0, 0])
+ assert await store.get_meta(META_EMBED_MODEL) == "model-a"
+ assert await store.get_meta(META_EMBED_DIM) == "4"
+
+ with pytest.raises(UltraStoreError, match="pinned"):
+ await store.store_embedding(doc_id, model="model-a", dim=5, vector=[0] * 5)
+ with pytest.raises(UltraStoreError, match="pinned"):
+ await store.store_embedding(doc_id, model="model-b", dim=4, vector=[0] * 4)
+ with pytest.raises(UltraStoreError, match="components"):
+ await store.store_embedding(doc_id, model="model-a", dim=4, vector=[0] * 3)
+
+
+async def test_reset_vectors_round_trip(store):
+ await add_source(store)
+ item_id, doc_id = await _seed_embedded_item(store, 0)
+ await store.store_embedding(doc_id, model="model-a", dim=4, vector=[1, 0, 0, 0])
+ await store.mark_stage_done(item_id, ItemState.EMBEDDED)
+ await store.mark_stage_done(item_id, ItemState.DISTILLED)
+
+ await store.reset_vectors()
+
+ # Pins cleared, items back at keyword_indexed, vector leg honestly empty.
+ assert await store.get_meta(META_EMBED_MODEL) is None
+ assert await store.get_meta(META_EMBED_DIM) is None
+ counts = await store.counts()
+ assert counts.keyword_indexed == 1
+ assert counts.embedded == 0 and counts.distilled == 0
+ results, reason = await store.vector_search([1, 0, 0, 0])
+ assert results == []
+ assert "no embedding has been stored yet" in reason
+
+ # The embedding-model-change path: a new pin with a new dimension works.
+ await store.store_embedding(doc_id, model="model-b", dim=8, vector=[0.5] * 8)
+ assert await store.get_meta(META_EMBED_MODEL) == "model-b"
+ assert await store.get_meta(META_EMBED_DIM) == "8"
+
+
+# ---------------------------------------------------------------------------
+# Vector leg — real extension round-trip + honest degradation
+# ---------------------------------------------------------------------------
+
+
[email protected](not HAS_SQLITE_VEC, reason="sqlite-vec not installed on this host")
+async def test_vector_search_real_roundtrip(store):
+ await add_source(store)
+ item1, doc1 = await _seed_embedded_item(store, 0)
+ item2, doc2 = await _seed_embedded_item(store, 1)
+ await store.store_embedding(doc1, model="m", dim=4, vector=[1, 0, 0, 0])
+ await store.store_embedding(doc2, model="m", dim=4, vector=[0, 1, 0, 0])
+
+ results, reason = await store.vector_search([1, 0.05, 0, 0], k=2)
+ assert reason == ""
+ assert [hit.item_id for hit in results] == [item1, item2]
+ assert results[0].score > results[1].score
+ assert results[0].matched_by == ("vector",)
+ assert results[0].permalink == "app://item/0"
+ assert all(0.0 <= hit.score <= 1.0 for hit in results)
+
+ # Tombstoned items disappear from the vector leg too.
+ await store.upsert_items("src1", [make_item(0, deleted=True)])
+ results, reason = await store.vector_search([1, 0.05, 0, 0], k=2)
+ assert reason == ""
+ assert [hit.item_id for hit in results] == [item2]
+
+ # A query vector that does not fit the pin degrades with a clear reason.
+ results, reason = await store.vector_search([1, 0, 0], k=2)
+ assert results == []
+ assert "pinned" in reason
+
+
+async def test_vector_search_degrades_honestly_without_sqlite_vec(store, monkeypatch):
+ def _broken_import():
+ raise ImportError("sqlite-vec is not installed (test)")
+
+ monkeypatch.setattr(store_mod, "_import_sqlite_vec", _broken_import)
+ await add_source(store)
+ _, doc_id = await _seed_embedded_item(store, 0)
+
+ # Embeddings still accumulate provider-neutrally without the extension.
+ await store.store_embedding(doc_id, model="m", dim=4, vector=[1, 0, 0, 0])
+ assert await store.get_meta(META_EMBED_DIM) == "4"
+
+ results, reason = await store.vector_search([1, 0, 0, 0])
+ assert results == []
+ assert "sqlite-vec" in reason
+ assert "Keyword search keeps working" in reason
+
+
[email protected](not HAS_SQLITE_VEC, reason="sqlite-vec not installed on this host")
+async def test_vectors_backfill_when_extension_appears_later(tmp_path):
+ db_path = tmp_path / "ultrawiki.db"
+
+ with pytest.MonkeyPatch.context() as mp:
+
+ def _broken_import():
+ raise ImportError("sqlite-vec is not installed (test)")
+
+ mp.setattr(store_mod, "_import_sqlite_vec", _broken_import)
+ crippled = UltraStore(db_path)
+ await add_source(crippled)
+ _, doc_id = await _seed_embedded_item(crippled, 0)
+ await crippled.store_embedding(doc_id, model="m", dim=4, vector=[1, 0, 0, 0])
+ results, reason = await crippled.vector_search([1, 0, 0, 0])
+ assert results == [] and "sqlite-vec" in reason
+ await crippled.close()
+
+ # Same DB file, extension now importable: the vec index is derived from
+ # the stored BLOBs — no re-embedding needed.
+ healed = UltraStore(db_path)
+ results, reason = await healed.vector_search([1, 0, 0, 0])
+ assert reason == ""
+ assert len(results) == 1
+ assert results[0].permalink == "app://item/0"
+ await healed.close()
+
+
+# ---------------------------------------------------------------------------
+# Areas, distill cache, sync state, meta
+# ---------------------------------------------------------------------------
+
+
+async def test_areas_crud_and_default_seeding(store):
+ default_id = await store.ensure_default_area()
+ assert default_id == "default"
+ assert await store.ensure_default_area() == "default" # idempotent
+
+ await store.upsert_area("work", "Work")
+ await store.upsert_area("work", "Work & Projects", is_default=True)
+ areas = await store.list_areas()
+ assert [area["id"] for area in areas if area["is_default"]] == ["work"]
+ assert areas[0]["name"] == "Work & Projects"
+
+ await store.delete_area("default")
+ assert [area["id"] for area in await store.list_areas()] == ["work"]
+
+
+async def test_area_scoped_keyword_search(store):
+ await add_source(store, "scoped", areas=["work"])
+ await store.upsert_items("scoped", [make_item(0)])
+ claimed = await store.claim_batch(ItemState.KEYWORD_INDEXED, limit=10)
+ await index_keyword(store, claimed[0])
+ assert len(await store.keyword_search("number0", area_id="work")) == 1
+ assert await store.keyword_search("number0", area_id="private") == []
+
+
+async def test_distill_cache_and_meta_round_trip(store):
+ assert await store.distill_cache_get("hash1", 1, "model-x") is None
+ await store.distill_cache_put("hash1", 1, "model-x", '{"summary": "s"}')
+ assert await store.distill_cache_get("hash1", 1, "model-x") == '{"summary": "s"}'
+ # A different prompt version or model is a different cache slot.
+ assert await store.distill_cache_get("hash1", 2, "model-x") is None
+ assert await store.distill_cache_get("hash1", 1, "model-y") is None
+
+ assert await store.get_meta("missing") is None
+ await store.set_meta("k", "v1")
+ await store.set_meta("k", "v2")
+ assert await store.get_meta("k") == "v2"
+
+
+async def test_sync_state_partial_updates(store):
+ await add_source(store)
+ assert await store.get_sync_state("src1") is None
+ await store.set_sync_state("src1", cursor="mtime:123")
+ state = await store.get_sync_state("src1")
+ assert state["cursor"] == "mtime:123"
+ assert state["backfill_checkpoint"] is None
+
+ await store.set_sync_state("src1", backfill_checkpoint="ext-0400")
+ state = await store.get_sync_state("src1")
+ assert state["cursor"] == "mtime:123" # untouched by the partial update
+ assert state["backfill_checkpoint"] == "ext-0400"
+
+ await store.set_sync_state(
+ "src1", backfill_complete_at="2026-01-01T00:00:00Z", cursor=None
+ )
+ state = await store.get_sync_state("src1")
+ assert state["cursor"] is None
+ assert state["backfill_complete_at"] == "2026-01-01T00:00:00Z"
+
+
+# ---------------------------------------------------------------------------
+# Postgres variant — missing driver is an honest, actionable error
+# ---------------------------------------------------------------------------
+
+
+async def test_postgres_missing_driver_names_the_extra(monkeypatch):
+ monkeypatch.setitem(sys.modules, "psycopg", None) # forces ImportError
+ with pytest.raises(ImportError, match=r"ultrawiki-postgres"):
+ await PostgresStore("postgresql://localhost/x").open()
+
+ ok, message = await PostgresStore.connect_test("postgresql://localhost/x")
+ assert ok is False
+ assert "ultrawiki-postgres" in message
+ assert "SQLite backend keeps working" in message
diff --git a/tests/unit/web/test_ultrawiki_routes.py b/tests/unit/web/test_ultrawiki_routes.py
new file mode 100644
index 0000000000..8faa552616
--- /dev/null
+++ b/tests/unit/web/test_ultrawiki_routes.py
@@ -0,0 +1,425 @@
+"""Full-app tests for the /api/ultrawiki REST surface.
+
+Pattern: a real ``WebServer`` (so the router mount, SurfaceSecurity, and the
+OpenAPI metadata are all the production ones) with a hand-wired
+``UltraWikiService`` on ``app.state.ultrawiki`` — the same manual wiring the
+task-stack integration tests use, because ``WebServer.start()`` never runs
+under ``TestClient``.
+
+Offline discipline: the service's own pipeline gets an UNCONFIGURED embedding
+factory (claims no embed work), and the tests drive a separate
+``PipelineWorker`` inline with a fake backend + fake distiller — deterministic,
+no sleeps, no network, no credentials. Provider readiness probes are
+monkeypatched at the module seams the routes import through.
+"""
+
+from __future__ import annotations
+
+import time
+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
+
+#: Routes that MUST carry the x-jarvis-dangerous OpenAPI extra.
+DANGEROUS_ROUTES = (
+ ("/api/ultrawiki/activate", "post"),
+ ("/api/ultrawiki/deactivate", "post"),
+ ("/api/ultrawiki/settings", "put"),
+ ("/api/ultrawiki/test/{slot}", "post"),
+ ("/api/ultrawiki/sources/{source_id}/approve", "post"),
+ ("/api/ultrawiki/sources/{source_id}/sync", "post"),
+ ("/api/ultrawiki/jobs/{job_id}/cancel", "post"),
+)
+
+
+class FakeEmbeddingBackend:
+ """Offline 3-dimensional embedding backend for the inline pipeline."""
+
+ name = "fake"
+
+ def ready(self) -> tuple[bool, str]:
+ return True, ""
+
+ async def embed(self, texts: list[str], *, model: str) -> list[list[float]]:
+ return [[0.1, 0.2, 0.3] for _ in texts]
+
+
+async def fake_distill(cfg, *, title, body, source_kind):
+ """Offline distiller returning a DistillResult-shaped namespace."""
+ return SimpleNamespace(
+ question=f"What is {title or 'this'} about?",
+ summary=(body or "")[:80],
+ resolution="",
+ entities=[],
+ refs=[],
+ raw_json="",
+ )
+
+
+def env(tmp_path: Path, monkeypatch):
+ """Full WebServer app + hand-wired UltraWikiService, tmp config + data dir."""
+ toml_path = tmp_path / "jarvis.toml"
+ toml_path.write_text("", encoding="utf-8")
+ # config_writer resolves through resolve_config_path(), which honours this.
+ monkeypatch.setenv("JARVIS_CONFIG", str(toml_path))
+ # Deterministic, offline provider probes at the seams the routes/service
+ # import through (no keyring walks, no localhost Ollama probe).
+ monkeypatch.setattr(
+ "jarvis.ultrawiki.embeddings.available_backends",
+ lambda cfg: [
+ {
+ "name": "gemini",
+ "ready": True,
+ "reason": "",
+ "default_model": "gemini-embedding-001",
+ },
+ {
+ "name": "openai",
+ "ready": False,
+ "reason": "no key",
+ "default_model": "text-embedding-3-small",
+ },
+ ],
+ )
+ monkeypatch.setattr(
+ "jarvis.ultrawiki.rerank.available_rerankers", lambda cfg: []
+ )
+ monkeypatch.setattr(
+ "jarvis.memory.wiki.provider_chain.credential_ready_wiki_providers",
+ lambda **_kw: [],
+ )
+
+ cfg = JarvisConfig()
+ cfg.ui.dev_mode = True
+ cfg.memory.data_dir = str(tmp_path / "data")
+ server = WebServer(cfg, bus=EventBus())
+ # ensure_started() only starts the pipeline once the mode is enabled; the
+ # unconfigured factory (None) makes that background pipeline claim no
+ # embed/distill work, so the inline driver below stays deterministic.
+ service = UltraWikiService(
+ cfg, embedding_backend_factory=lambda: None, distill_fn=fake_distill
+ )
+ server.app.state.ultrawiki = service
+ uw_service_mod.clear_jobs()
+ with TestClient(server.app) as client:
+ yield SimpleNamespace(
+ client=client,
+ service=service,
+ server=server,
+ cfg=cfg,
+ toml=toml_path,
+ tmp=tmp_path,
+ )
+ client.portal.call(service.shutdown)
+ uw_service_mod.clear_jobs()
+
+
+def _activate(env) -> dict:
+ # The explicit model matters: the inline PipelineWorker resolves the model
+ # from cfg (its fake backend has no DEFAULT_MODELS entry).
+ response = env.client.post(
+ "/api/ultrawiki/activate",
+ json={"embedding_provider": "gemini", "embedding_model": "fake-embed"},
+ )
+ assert response.status_code == 200, response.text
+ return response.json()
+
+
+def _approve_and_sync_folder(env) -> tuple[str, str]:
+ """Register + approve + sync a local-folder source; returns (source_id, job_id)."""
+ docs = env.tmp / "docs"
+ docs.mkdir(exist_ok=True)
+ (docs / "alpha.md").write_text(
+ "# Alpha\n\nThe quarterly ledger reconciliation lives here.",
+ encoding="utf-8",
+ )
+ (docs / "beta.md").write_text(
+ "# Beta\n\nNotes about the telescope maintenance schedule.",
+ encoding="utf-8",
+ )
+ created = env.client.post(
+ "/api/ultrawiki/sources",
+ json={"connector": "local-folder", "label": "Docs", "config": {"root": str(docs)}},
+ )
+ assert created.status_code == 201, created.text
+ source = created.json()
+ assert source["consent"] == "pending"
+ source_id = source["id"]
+
+ approved = env.client.post(f"/api/ultrawiki/sources/{source_id}/approve")
+ assert approved.status_code == 200, approved.text
+ assert approved.json()["consent"] == "approved"
+
+ synced = env.client.post(f"/api/ultrawiki/sources/{source_id}/sync")
+ assert synced.status_code == 201, synced.text
+ return source_id, synced.json()["job_id"]
+
+
+def _wait_for_job(env, job_id: str, timeout_s: float = 10.0) -> dict:
+ deadline = time.monotonic() + timeout_s
+ while time.monotonic() < deadline:
+ response = env.client.get(f"/api/ultrawiki/jobs/{job_id}")
+ assert response.status_code == 200, response.text
+ snapshot = response.json()
+ if snapshot["status"] in ("done", "failed", "cancelled"):
+ return snapshot
+ time.sleep(0.02)
+ raise AssertionError(f"job {job_id} did not finish within {timeout_s}s")
+
+
+def _drive_pipeline(env) -> None:
+ """Advance every item through the staged ladder inline (no sleeps)."""
+ from jarvis.ultrawiki.pipeline import PipelineWorker
+
+ async def _run() -> None:
+ store = env.service._store # noqa: SLF001 — deliberate test seam
+ assert store is not None
+ worker = PipelineWorker(
+ store,
+ env.cfg,
+ embedding_backend_factory=lambda: FakeEmbeddingBackend(),
+ distill_fn=fake_distill,
+ )
+ for _ in range(8):
+ if await worker.run_once() == 0:
+ break
+
+ env.client.portal.call(_run)
+
+
+# ---------------------------------------------------------------------------
+# Status / activation
+# ---------------------------------------------------------------------------
+
+
+def test_status_answers_while_disabled(env) -> None:
+ response = env.client.get("/api/ultrawiki/status")
+ assert response.status_code == 200, response.text
+ body = response.json()
+ assert body["enabled"] is False
+ assert body["started"] is False
+ assert body["db_backend"] == "sqlite"
+ assert "search_legs" in body
+ assert body["search_legs"]["keyword"] == {"available": True}
+ assert body["search_legs"]["vector"]["available"] is False
+
+
+def test_activate_flips_mode_and_creates_pending_sources(env) -> None:
+ body = _activate(env)
+ assert body["enabled"] is True
+ assert body["persisted"] is True
+ assert sorted(body["sources_created"]) == ["jarvis-conversations", "normal-wiki"]
+ assert body["next_steps"]
+ assert env.cfg.ultrawiki.enabled is True
+ assert env.cfg.ultrawiki.embedding_provider == "gemini"
+ toml_text = env.toml.read_text(encoding="utf-8")
+ assert "enabled = true" in toml_text
+ assert 'embedding_provider = "gemini"' in toml_text
+
+ listed = env.client.get("/api/ultrawiki/sources").json()
+ by_id = {row["id"]: row for row in listed["sources"]}
+ assert by_id["normal-wiki"]["consent"] == "pending"
+ assert by_id["jarvis-conversations"]["consent"] == "pending"
+
+
+def test_activate_unready_backend_is_409(env) -> None:
+ response = env.client.post(
+ "/api/ultrawiki/activate", json={"embedding_provider": "openai"}
+ )
+ assert response.status_code == 409
+ assert "not ready" in response.json()["detail"]
+
+
+# ---------------------------------------------------------------------------
+# Consent gate + sync jobs
+# ---------------------------------------------------------------------------
+
+
+def test_sync_on_pending_source_is_409(env) -> None:
+ _activate(env)
+ response = env.client.post("/api/ultrawiki/sources/normal-wiki/sync")
+ assert response.status_code == 409
+ assert "not approved" in response.json()["detail"]
+
+
+def test_approve_then_sync_completes_against_local_folder(env) -> None:
+ _activate(env)
+ source_id, job_id = _approve_and_sync_folder(env)
+ snapshot = _wait_for_job(env, job_id)
+ assert snapshot["status"] == "done", snapshot
+ assert snapshot["new"] == 2
+ assert snapshot["source_id"] == source_id
+
+ listed = env.client.get("/api/ultrawiki/sources").json()
+ row = next(r for r in listed["sources"] if r["id"] == source_id)
+ assert row["counts"]["total"] == 2
+
+
+def test_jobs_list_get_cancel_shapes(env) -> None:
+ _activate(env)
+ _source_id, job_id = _approve_and_sync_folder(env)
+ _wait_for_job(env, job_id)
+
+ listed = env.client.get("/api/ultrawiki/jobs")
+ assert listed.status_code == 200
+ body = listed.json()
+ assert body["total"] >= 1
+ assert any(job["job_id"] == job_id for job in body["jobs"])
+
+ assert env.client.get("/api/ultrawiki/jobs/no-such-job").status_code == 404
+ assert env.client.post("/api/ultrawiki/jobs/no-such-job/cancel").status_code == 404
+
+ # Terminal job — cancel refuses with 409, honestly.
+ response = env.client.post(f"/api/ultrawiki/jobs/{job_id}/cancel")
+ assert response.status_code == 409
+ assert "terminal" in response.json()["detail"]
+
+
+# ---------------------------------------------------------------------------
+# Search
+# ---------------------------------------------------------------------------
+
+
+def test_search_disabled_is_409_with_honest_message(env) -> None:
+ response = env.client.get("/api/ultrawiki/search", params={"q": "ledger"})
+ assert response.status_code == 409
+ assert response.json()["detail"] == (
+ "UltraWiki mode is off — the normal wiki answers today."
+ )
+
+
+def test_search_returns_fused_hits_after_inline_pipeline(env) -> None:
+ _activate(env)
+ _source_id, job_id = _approve_and_sync_folder(env)
+ _wait_for_job(env, job_id)
+ _drive_pipeline(env)
+
+ response = env.client.get("/api/ultrawiki/search", params={"q": "ledger"})
+ assert response.status_code == 200, response.text
+ body = response.json()
+ assert body["total"] >= 1
+ hit = body["results"][0]
+ assert "alpha" in hit["title"].lower()
+ assert hit["permalink"]
+ assert "keyword" in hit["matched_by"]
+ assert hit["score"] > 0
+
+
+# ---------------------------------------------------------------------------
+# Settings guard (D-3: embedding change re-embeds the corpus)
+# ---------------------------------------------------------------------------
+
+
+def test_embedding_change_without_confirm_is_409(env) -> None:
+ _activate(env)
+ _source_id, job_id = _approve_and_sync_folder(env)
+ _wait_for_job(env, job_id)
+ _drive_pipeline(env)
+
+ response = env.client.put(
+ "/api/ultrawiki/settings", json={"embedding_provider": "openai"}
+ )
+ assert response.status_code == 409
+ detail = response.json()["detail"]
+ assert detail["vector_items"] == 2
+ assert "confirm_reembed" in detail["message"]
+
+ confirmed = env.client.put(
+ "/api/ultrawiki/settings",
+ json={"embedding_provider": "openai", "confirm_reembed": True},
+ )
+ assert confirmed.status_code == 200, confirmed.text
+ body = confirmed.json()
+ assert body["changed"] == ["embedding_provider"]
+ assert body["reembed_started"] is True
+ assert env.cfg.ultrawiki.embedding_provider == "openai"
+ assert 'embedding_provider = "openai"' in env.toml.read_text(encoding="utf-8")
+
+ # The vectors were dropped: items fell back to keyword_indexed and wait
+ # for the (deliberately unconfigured) background embed stage.
+ counts = env.client.get("/api/ultrawiki/status").json()["counts"]
+ assert counts["embedded"] == 0
+ assert counts["distilled"] == 0
+ assert counts["keyword_indexed"] == 2
+
+
+def test_update_settings_without_changes_is_noop(env) -> None:
+ _activate(env)
+ response = env.client.put("/api/ultrawiki/settings", json={})
+ assert response.status_code == 200
+ assert response.json() == {
+ "ok": True,
+ "changed": [],
+ "persisted": True,
+ "reembed_started": False,
+ }
+
+
+# ---------------------------------------------------------------------------
+# Areas + providers + deactivation
+# ---------------------------------------------------------------------------
+
+
+def test_areas_list_and_create(env) -> None:
+ _activate(env)
+ listed = env.client.get("/api/ultrawiki/areas").json()
+ assert any(area["is_default"] for area in listed["areas"])
+
+ created = env.client.post("/api/ultrawiki/areas", json={"name": "Work Stuff"})
+ assert created.status_code == 201
+ assert created.json() == {"id": "work-stuff", "name": "Work Stuff"}
+
+
+def test_list_providers_reports_slots(env, monkeypatch) -> None:
+ monkeypatch.setattr("jarvis.core.config.get_secret", lambda name: None)
+ response = env.client.get("/api/ultrawiki/providers")
+ assert response.status_code == 200
+ body = response.json()
+ assert {row["name"] for row in body["embedding"]} == {"gemini", "openai"}
+ backends = {row["name"]: row for row in body["db_backends"]}
+ assert backends["sqlite"]["ready"] is True
+ assert backends["postgres"]["ready"] is False
+ assert backends["postgres"]["secret_present"] is False
+
+
+def test_deactivate_is_non_destructive(env) -> None:
+ _activate(env)
+ response = env.client.post("/api/ultrawiki/deactivate")
+ assert response.status_code == 200
+ body = response.json()
+ assert body["enabled"] is False
+ assert body["non_destructive"] is True
+ assert env.cfg.ultrawiki.enabled is False
+ assert "enabled = false" in env.toml.read_text(encoding="utf-8")
+ # Search now refuses with the mode-off message; status still answers.
+ assert env.client.get("/api/ultrawiki/search", params={"q": "x"}).status_code == 409
+ assert env.client.get("/api/ultrawiki/status").status_code == 200
+
+
+# ---------------------------------------------------------------------------
+# Contract guards (CLI-first + danger metadata + mount)
+# ---------------------------------------------------------------------------
+
+
+def test_dangerous_routes_carry_the_flag(env) -> None:
+ spec = env.server.app.openapi()
+ for path, method in DANGEROUS_ROUTES:
+ operation = spec["paths"][path][method]
+ assert operation.get("x-jarvis-dangerous") is True, (path, method)
+
+
+def test_router_import_line_exists_in_server_source() -> None:
+ import jarvis.ui.web.server as server_mod
+
+ source = Path(server_mod.__file__).read_text(encoding="utf-8")
+ assert "from .ultrawiki_routes import router as ultrawiki_router" in source
+ assert "app.include_router(ultrawiki_router)" in source