Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(ultrawiki): connector framework + provider slots (embeddings, distill, rerank)
Ruben Lütke9fc108fa48e3
diff --git a/jarvis/ultrawiki/connectors/__init__.py b/jarvis/ultrawiki/connectors/__init__.pynew file mode 100644index 0000000000..4cfb008a29--- /dev/null+++ b/jarvis/ultrawiki/connectors/__init__.py@@ -0,0 +1,147 @@+"""UltraWiki connector registry + entry-point discovery.++Built-in connectors live in this package and are core code; third-party+connectors register under the ``jarvis.uw_connector`` entry-point group+and must not import ``jarvis.*`` at module level (see+:class:`jarvis.ultrawiki.types.UWConnector`).++The registry maps connector id → zero-argument factory. Consumers call+the factory ONCE PER USE so every sync run gets a fresh, stateless+connector instance. Connector modules are imported lazily inside the+factories — importing this package stays boot-cheap (AP-26).++Discovery never raises for a broken entry point: failures are recorded+(imitating ``jarvis/brain/provider_registry.py``) and readable via+:func:`discovery_failures`, so one broken third-party connector cannot+take down the whole source catalog.+"""++from __future__ import annotations++import logging+from collections.abc import Callable++from jarvis.ultrawiki.types import UWConnector++log = logging.getLogger(__name__)++ENTRY_POINT_GROUP = "jarvis.uw_connector"++#: A zero-argument callable returning a fresh connector instance.+ConnectorFactory = Callable[[], UWConnector]++# Failures recorded by the most recent discover_connectors() call.+_discovery_failures: dict[str, str] = {}+++def _make_obsidian_vault() -> UWConnector:+ from jarvis.ultrawiki.connectors.obsidian_vault import ObsidianVaultConnector++ return ObsidianVaultConnector()+++def _make_local_folder() -> UWConnector:+ from jarvis.ultrawiki.connectors.local_folder import LocalFolderConnector++ return LocalFolderConnector()+++def _make_jarvis_conversations() -> UWConnector:+ from jarvis.ultrawiki.connectors.jarvis_conversations import (+ JarvisConversationsConnector,+ )++ return JarvisConversationsConnector()+++def _make_normal_wiki() -> UWConnector:+ from jarvis.ultrawiki.connectors.normal_wiki import NormalWikiConnector++ return NormalWikiConnector()+++def _make_plugin_bridge() -> UWConnector:+ from jarvis.ultrawiki.connectors.plugin_bridge import PluginBridgeConnector++ return PluginBridgeConnector()+++def builtin_connectors() -> dict[str, ConnectorFactory]:+ """The five built-in connectors, keyed by connector id."""+ return {+ "obsidian-vault": _make_obsidian_vault,+ "local-folder": _make_local_folder,+ "jarvis-conversations": _make_jarvis_conversations,+ "normal-wiki": _make_normal_wiki,+ "plugin-bridge": _make_plugin_bridge,+ }+++def _class_factory(cls: type) -> ConnectorFactory:+ def _factory() -> UWConnector:+ return cls()++ return _factory+++def discover_connectors() -> dict[str, ConnectorFactory]:+ """Built-ins plus every loadable ``jarvis.uw_connector`` entry point.++ A failing entry point is recorded in :func:`discovery_failures` and+ skipped, never raised. An entry point whose name collides with a+ built-in id is ignored (the built-in wins) and recorded as a failure.+ """+ global _discovery_failures+ failures: dict[str, str] = {}+ registry = builtin_connectors()++ try:+ from importlib.metadata import entry_points++ eps = list(entry_points(group=ENTRY_POINT_GROUP))+ except Exception as exc:+ failures["<entry-points>"] = f"{type(exc).__name__}: {exc}"+ log.warning("uw_connector entry-point enumeration failed: %s", exc)+ eps = []++ for ep in eps:+ if ep.name in registry:+ failures[ep.name] = "entry point name collides with a built-in connector; ignored"+ log.warning(+ "uw_connector entry point %r collides with a built-in; ignored",+ ep.name,+ )+ continue+ try:+ loaded = ep.load()+ except Exception as exc:+ failures[ep.name] = f"{type(exc).__name__}: {exc}"+ log.warning("uw_connector entry point %r failed to load: %s", ep.name, exc)+ continue+ if isinstance(loaded, type):+ registry[ep.name] = _class_factory(loaded)+ elif callable(loaded):+ registry[ep.name] = loaded+ else:+ failures[ep.name] = "entry point is neither a class nor a factory callable"+ log.warning(+ "uw_connector entry point %r is neither a class nor a callable",+ ep.name,+ )++ _discovery_failures = failures+ return registry+++def discovery_failures() -> dict[str, str]:+ """Entry-point failures recorded by the last ``discover_connectors()``."""+ return dict(_discovery_failures)+++__all__ = [+ "ENTRY_POINT_GROUP",+ "ConnectorFactory",+ "builtin_connectors",+ "discover_connectors",+ "discovery_failures",+]diff --git a/jarvis/ultrawiki/connectors/jarvis_conversations.py b/jarvis/ultrawiki/connectors/jarvis_conversations.pynew file mode 100644index 0000000000..94dfb217e7--- /dev/null+++ b/jarvis/ultrawiki/connectors/jarvis_conversations.py@@ -0,0 +1,272 @@+"""Jarvis-conversations connector: read the shared message store as a source.++Reads the existing ``data/jarvis.db`` ``messages`` table (see+``jarvis/memory/schema.sql``) strictly READ-ONLY through its own+``mode=ro`` SQLite URI connection — this connector never writes to the+shared store and never blocks its tenants.++Chunking: messages are grouped into ONE raw item per (conversation, day):++- conversation id = ``thread_id`` when set, else ``trace_id``;+- day = the UTC calendar date of the message timestamp;+- ``external_id`` = ``"<conversation_id>:<YYYY-MM-DD>"``;+- body = chronological ``role: text`` lines;+- ``thread_key`` = the conversation id;+- ``permalink`` = ``jarvis://chats/<conversation_id>`` (app deep link);+- ``timestamp_utc`` = the LAST message of the chunk.++Cursor / checkpoint contract (documented honestly):++- ``incremental(ctx, cursor)``: the cursor is the highest ``messages``+ rowid seen so far, as a string. Every yielded chunk carries+ ``metadata["max_rowid"]`` so the runtime can advance the cursor to the+ maximum of the yielded values. Incremental re-chunks and re-yields the+ WHOLE day of every (conversation, day) touched by newer rows, so the+ stored chunk always reflects the complete current day (upserts are+ idempotent on ``(source_id, external_id)``).+- ``backfill(ctx, checkpoint)``: chunks stream in deterministic order+ (conversation id, then day). ``checkpoint`` is the ``external_id`` of+ the last persisted chunk; chunks ordering at or before it are skipped+ so an interrupted backfill resumes.+- A missing database file is not an error: backfill/incremental log once+ per path and yield nothing (honest degradation, CLAUDE.md §3).+- ``capabilities.deletes = False``: the message store is append-only from+ this connector's point of view; no tombstones are emitted.+"""++from __future__ import annotations++import logging+import re+import sqlite3+from collections.abc import AsyncIterator, Iterator+from datetime import UTC, datetime+from pathlib import Path+from typing import Any++from jarvis.ultrawiki.types import (+ AuthKind,+ ConnectorCapabilities,+ ConnectorContext,+ IncrementalMode,+ RawItem,+)++log = logging.getLogger(__name__)++_DAY_RE = re.compile(r"\d{4}-\d{2}-\d{2}")+_NS_PER_SECOND = 1_000_000_000+_NS_PER_DAY = 86_400 * _NS_PER_SECOND++# One honest "database missing" log per path per process — not per poll.+_MISSING_DB_LOGGED: set[str] = set()++# The conversation id is thread_id when set, else trace_id — the SQL+# expression COALESCE(NULLIF(thread_id, ''), trace_id) appears verbatim in+# each query below (plain literals, only ? placeholders carry values).++_BACKFILL_QUERY = (+ "SELECT id, COALESCE(NULLIF(thread_id, ''), trace_id) AS conversation_id, "+ "timestamp_ns, role, text FROM messages "+ "ORDER BY conversation_id, timestamp_ns, id"+)++_TOUCHED_QUERY = (+ "SELECT COALESCE(NULLIF(thread_id, ''), trace_id) AS conversation_id, "+ "timestamp_ns FROM messages WHERE id > ?"+)++_DAY_QUERY = (+ "SELECT id, COALESCE(NULLIF(thread_id, ''), trace_id) AS conversation_id, "+ "timestamp_ns, role, text FROM messages "+ "WHERE COALESCE(NULLIF(thread_id, ''), trace_id) = ? "+ "AND timestamp_ns >= ? AND timestamp_ns < ? "+ "ORDER BY timestamp_ns, id"+)++# Row shape: (id, conversation_id, timestamp_ns, role, text)+_Row = tuple[int, str, int, str, str]+++def _day_utc(timestamp_ns: int) -> str:+ return datetime.fromtimestamp(timestamp_ns // _NS_PER_SECOND, tz=UTC).date().isoformat()+++def _day_bounds_ns(day: str) -> tuple[int, int]:+ start = datetime.strptime(day, "%Y-%m-%d").replace(tzinfo=UTC)+ start_ns = int(start.timestamp()) * _NS_PER_SECOND+ return start_ns, start_ns + _NS_PER_DAY+++def _iso_utc_from_ns(timestamp_ns: int) -> str:+ return datetime.fromtimestamp(timestamp_ns // _NS_PER_SECOND, tz=UTC).strftime(+ "%Y-%m-%dT%H:%M:%SZ"+ )+++def _chunk_item(conversation_id: str, day: str, rows: list[_Row]) -> RawItem:+ lines = [f"{role}: {text}" for (_rowid, _conv, _ts, role, text) in rows if text]+ return RawItem(+ external_id=f"{conversation_id}:{day}",+ body="\n".join(lines),+ permalink=f"jarvis://chats/{conversation_id}",+ timestamp_utc=_iso_utc_from_ns(rows[-1][2]),+ title=f"Conversation on {day}",+ thread_key=conversation_id,+ metadata={+ "max_rowid": max(row[0] for row in rows),+ "message_count": len(rows),+ },+ )+++def _checkpoint_key(checkpoint: str | None) -> tuple[str, str] | None:+ """Split ``"<conversation_id>:<YYYY-MM-DD>"`` into its ordering key."""+ if not checkpoint:+ return None+ conversation_id, sep, day = checkpoint.rpartition(":")+ if not sep or not _DAY_RE.fullmatch(day):+ log.warning(+ "jarvis-conversations: unusable backfill checkpoint %r; "+ "restarting from the beginning (idempotent upserts make this safe)",+ checkpoint,+ )+ return None+ return (conversation_id, day)+++def _parse_rowid_cursor(cursor: str | None) -> int:+ if cursor is None or cursor == "":+ return 0+ try:+ return int(cursor)+ except ValueError:+ log.warning(+ "jarvis-conversations: unusable incremental cursor %r; "+ "re-yielding every touched day (idempotent upserts make this safe)",+ cursor,+ )+ return 0+++class JarvisConversationsConnector:+ """Stream the shared conversation store as per-day thread chunks."""++ id = "jarvis-conversations"+ label = "Jarvis Conversations"+ auth = AuthKind.NONE+ capabilities = ConnectorCapabilities(+ backfill=True,+ incremental=IncrementalMode.CURSOR,+ deletes=False,+ )++ # ------------------------------------------------------------------+ # Protocol surface+ # ------------------------------------------------------------------++ async def backfill(+ self, ctx: ConnectorContext, checkpoint: str | None = None+ ) -> AsyncIterator[RawItem]:+ conn = self._open_ro(self._resolve_db_path(ctx))+ if conn is None:+ return+ try:+ resume_after = _checkpoint_key(checkpoint)+ for conversation_id, day, rows in _iter_day_chunks(conn):+ if resume_after is not None and (conversation_id, day) <= resume_after:+ continue+ yield _chunk_item(conversation_id, day, rows)+ finally:+ conn.close()++ async def incremental(+ self, ctx: ConnectorContext, cursor: str | None = None+ ) -> AsyncIterator[RawItem]:+ conn = self._open_ro(self._resolve_db_path(ctx))+ if conn is None:+ return+ try:+ min_rowid = _parse_rowid_cursor(cursor)+ for conversation_id, day in _touched_days(conn, min_rowid):+ rows = _rows_for_day(conn, conversation_id, day)+ if rows:+ yield _chunk_item(conversation_id, day, rows)+ finally:+ conn.close()++ # ------------------------------------------------------------------+ # Sync helpers (blocking I/O stays out of the async frames)+ # ------------------------------------------------------------------++ def _resolve_db_path(self, ctx: ConnectorContext) -> Path:+ raw: Any = ctx.config.get("db_path")+ if raw:+ return Path(str(raw))+ # Same canonical resolution every wiki consumer uses (lazy import+ # keeps this package boot-cheap, AP-26).+ from jarvis.memory.wiki.db_path import resolve_wiki_db_path++ return resolve_wiki_db_path(ctx.config.get("data_dir"))++ def _open_ro(self, db_path: Path) -> sqlite3.Connection | None:+ if not db_path.is_file():+ key = str(db_path)+ if key not in _MISSING_DB_LOGGED:+ _MISSING_DB_LOGGED.add(key)+ log.info(+ "%s: conversation store %s does not exist yet; yielding nothing",+ self.id,+ db_path,+ )+ return None+ uri = f"{db_path.resolve().as_uri()}?mode=ro"+ try:+ return sqlite3.connect(uri, uri=True)+ except sqlite3.Error as exc:+ log.warning(+ "%s: could not open conversation store %s read-only: %s",+ self.id,+ db_path,+ exc,+ )+ return None+++def _iter_day_chunks(+ conn: sqlite3.Connection,+) -> Iterator[tuple[str, str, list[_Row]]]:+ """Stream (conversation_id, day, rows) groups in deterministic order."""+ current_key: tuple[str, str] | None = None+ rows: list[_Row] = []+ for row in conn.execute(_BACKFILL_QUERY):+ typed: _Row = (int(row[0]), str(row[1]), int(row[2]), str(row[3]), str(row[4]))+ key = (typed[1], _day_utc(typed[2]))+ if key != current_key:+ if current_key is not None and rows:+ yield current_key[0], current_key[1], rows+ current_key = key+ rows = []+ rows.append(typed)+ if current_key is not None and rows:+ yield current_key[0], current_key[1], rows+++def _touched_days(conn: sqlite3.Connection, min_rowid: int) -> list[tuple[str, str]]:+ """(conversation_id, day) pairs touched by rows newer than ``min_rowid``."""+ touched = {+ (str(conversation_id), _day_utc(int(timestamp_ns)))+ for conversation_id, timestamp_ns in conn.execute(_TOUCHED_QUERY, (min_rowid,))+ }+ return sorted(touched)+++def _rows_for_day(conn: sqlite3.Connection, conversation_id: str, day: str) -> list[_Row]:+ start_ns, end_ns = _day_bounds_ns(day)+ return [+ (int(row[0]), str(row[1]), int(row[2]), str(row[3]), str(row[4]))+ for row in conn.execute(_DAY_QUERY, (conversation_id, start_ns, end_ns))+ ]+++__all__ = ["JarvisConversationsConnector"]diff --git a/jarvis/ultrawiki/connectors/local_folder.py b/jarvis/ultrawiki/connectors/local_folder.pynew file mode 100644index 0000000000..3168b9cdd5--- /dev/null+++ b/jarvis/ultrawiki/connectors/local_folder.py@@ -0,0 +1,252 @@+"""Local-folder connector: stream text files from a user-chosen directory.++This module also hosts the shared file-walk machinery reused by the+Obsidian-vault and normal-wiki connectors (both are "a folder of text+files with extra rules"). Connectors yield :class:`RawItem` only — no+store, no LLM, no embedding (design doc 02, hard rule 1).++Cursor / checkpoint contract (documented honestly):++- ``backfill(ctx, checkpoint)`` walks the tree in deterministic order+ (sorted by POSIX relative path). ``checkpoint`` is the ``external_id``+ of the last item the runtime persisted; files sorting at or before it+ are skipped so an interrupted backfill resumes instead of restarting.+- ``incremental(ctx, cursor)`` uses a cursor that is the highest+ ``st_mtime_ns`` seen so far, as a string. Every yielded item carries+ ``metadata["mtime_ns"]`` so the runtime can advance the cursor to the+ maximum of the yielded values. Only files with a modification time+ strictly greater than the cursor are re-yielded. An unparsable cursor+ logs an honest warning and re-yields everything — safe, because item+ writes are idempotent upserts on ``(source_id, external_id)``.+- Deletion detection: a file walk only sees files that still exist, so+ this connector cannot emit tombstone items from the walk itself.+ ``capabilities.deletes = True`` means deletions are detectable by the+ RUNTIME during a full backfill (reconcile pass, design doc 02): the+ runtime compares its stored ``external_id`` set for the source against+ the ids yielded by the walk and tombstones the difference. Incremental+ runs never detect deletions.+"""++from __future__ import annotations++import logging+import os+import re+from collections.abc import AsyncIterator+from datetime import UTC, datetime+from pathlib import Path++from jarvis.ultrawiki.types import (+ AuthKind,+ ConnectorCapabilities,+ ConnectorContext,+ IncrementalMode,+ RawItem,+)++log = logging.getLogger(__name__)++#: Matches an H1 markdown heading ("# Title") at the start of a line.+_H1_RE = re.compile(r"^# +(.+?)\s*$", re.MULTILINE)+++def first_h1_heading(body: str) -> str:+ """Return the first ``# ...`` heading of a markdown body, or ``""``."""+ match = _H1_RE.search(body)+ return match.group(1).strip() if match else ""+++def iso_utc_from_timestamp(seconds: float) -> str:+ """Render a POSIX timestamp as an ISO-8601 UTC string (second precision)."""+ return datetime.fromtimestamp(int(seconds), tz=UTC).strftime("%Y-%m-%dT%H:%M:%SZ")+++def parse_mtime_cursor(cursor: str | None, *, connector_id: str) -> int:+ """Parse an mtime-ns cursor; unparsable values honestly degrade to 0."""+ if cursor is None or cursor == "":+ return 0+ try:+ return int(cursor)+ except ValueError:+ log.warning(+ "%s: unusable incremental cursor %r; re-yielding everything "+ "(idempotent upserts make this safe)",+ connector_id,+ cursor,+ )+ return 0+++class LocalFolderConnector:+ """Stream text files from ``ctx.config['root']`` as raw items.++ Config keys:++ - ``root`` (required): directory to walk.+ - ``extensions`` (optional): list of file extensions to include,+ default ``[".md", ".txt"]``. Entries may omit the leading dot.++ Files larger than :attr:`MAX_FILE_BYTES` are skipped with a log line.+ Bodies are read as UTF-8 with ``errors="replace"`` so a stray binary+ or wrongly-encoded file never aborts a walk.+ """++ id = "local-folder"+ label = "Local Folder"+ auth = AuthKind.LOCAL_PATH+ capabilities = ConnectorCapabilities(+ backfill=True,+ incremental=IncrementalMode.CURSOR,+ deletes=True,+ )++ DEFAULT_EXTENSIONS: tuple[str, ...] = (".md", ".txt")+ #: Directory names skipped in addition to hidden (dot-prefixed) ones.+ SKIP_DIR_NAMES: frozenset[str] = frozenset()+ MAX_FILE_BYTES: int = 2 * 1024 * 1024++ # ------------------------------------------------------------------+ # Protocol surface+ # ------------------------------------------------------------------++ async def backfill(+ self, ctx: ConnectorContext, checkpoint: str | None = None+ ) -> AsyncIterator[RawItem]:+ root = self._resolve_root(ctx)+ if root is None:+ return+ extensions = self._extensions(ctx)+ for path in self._sorted_files(root, extensions):+ external_id = self._external_id_for(root, path)+ if checkpoint and external_id <= checkpoint:+ continue+ item = self._item_for(root, path)+ if item is not None:+ yield item++ async def incremental(+ self, ctx: ConnectorContext, cursor: str | None = None+ ) -> AsyncIterator[RawItem]:+ root = self._resolve_root(ctx)+ if root is None:+ return+ threshold = parse_mtime_cursor(cursor, connector_id=self.id)+ extensions = self._extensions(ctx)+ for path in self._sorted_files(root, extensions):+ mtime_ns = self._mtime_ns(path)+ if mtime_ns is None or mtime_ns <= threshold:+ continue+ item = self._item_for(root, path)+ if item is not None:+ yield item++ # ------------------------------------------------------------------+ # Hooks (overridden by the Obsidian and normal-wiki subclasses)+ # ------------------------------------------------------------------++ def _resolve_root(self, ctx: ConnectorContext) -> Path | None:+ raw = ctx.config.get("root")+ if not raw:+ log.warning(+ "%s: source %s has no 'root' configured; yielding nothing",+ self.id,+ ctx.source_id,+ )+ return None+ root = Path(str(raw)).expanduser()+ if not root.is_dir():+ log.warning(+ "%s: configured root %s does not exist or is not a directory; yielding nothing",+ self.id,+ root,+ )+ return None+ return root++ def _extensions(self, ctx: ConnectorContext) -> tuple[str, ...]:+ raw = ctx.config.get("extensions")+ if not raw:+ return self.DEFAULT_EXTENSIONS+ normalized: list[str] = []+ for entry in raw:+ text = str(entry).strip().lower()+ if not text:+ continue+ normalized.append(text if text.startswith(".") else f".{text}")+ return tuple(normalized) or self.DEFAULT_EXTENSIONS++ def _sorted_files(self, root: Path, extensions: tuple[str, ...]) -> list[Path]:+ """All matching files under ``root``, sorted by POSIX relative path.++ Hidden directories and files (dot-prefixed) plus :attr:`SKIP_DIR_NAMES`+ are excluded. Symlinked directories are not followed.+ """+ matches: list[tuple[str, Path]] = []+ for dirpath, dirnames, filenames in os.walk(root):+ dirnames[:] = sorted(+ d for d in dirnames if not d.startswith(".") and d not in self.SKIP_DIR_NAMES+ )+ base = Path(dirpath)+ for name in filenames:+ if name.startswith("."):+ continue+ path = base / name+ if path.suffix.lower() not in extensions:+ continue+ matches.append((path.relative_to(root).as_posix(), path))+ matches.sort(key=lambda pair: pair[0])+ return [path for _rel, path in matches]++ def _external_id_for(self, root: Path, path: Path) -> str:+ return path.relative_to(root).as_posix()++ def _title_for(self, path: Path, body: str) -> str:+ return path.stem++ # ------------------------------------------------------------------+ # Item construction (sync helpers keep blocking I/O out of async frames)+ # ------------------------------------------------------------------++ def _mtime_ns(self, path: Path) -> int | None:+ try:+ return path.stat().st_mtime_ns+ except OSError as exc:+ log.debug("%s: stat failed for %s: %s", self.id, path, exc)+ return None++ def _item_for(self, root: Path, path: Path) -> RawItem | None:+ try:+ stat = path.stat()+ except OSError as exc:+ log.debug("%s: stat failed for %s: %s", self.id, path, exc)+ return None+ if stat.st_size > self.MAX_FILE_BYTES:+ log.info(+ "%s: skipping %s (%d bytes exceeds the %d-byte limit)",+ self.id,+ path,+ stat.st_size,+ self.MAX_FILE_BYTES,+ )+ return None+ try:+ body = path.read_text(encoding="utf-8", errors="replace")+ except OSError as exc:+ log.debug("%s: read failed for %s: %s", self.id, path, exc)+ return None+ return RawItem(+ external_id=self._external_id_for(root, path),+ body=body,+ permalink=path.resolve().as_uri(),+ timestamp_utc=iso_utc_from_timestamp(stat.st_mtime),+ title=self._title_for(path, body),+ metadata={"mtime_ns": stat.st_mtime_ns, "size_bytes": stat.st_size},+ )+++__all__ = [+ "LocalFolderConnector",+ "first_h1_heading",+ "iso_utc_from_timestamp",+ "parse_mtime_cursor",+]diff --git a/jarvis/ultrawiki/connectors/normal_wiki.py b/jarvis/ultrawiki/connectors/normal_wiki.pynew file mode 100644index 0000000000..a0f820ef9c--- /dev/null+++ b/jarvis/ultrawiki/connectors/normal_wiki.py@@ -0,0 +1,103 @@+"""Normal-wiki connector: read the built-in wiki vault as an UltraWiki source.++UltraWiki treats the zero-dependency wiki's Obsidian vault as a READ-ONLY+source (design doc 01, "why the normal wiki survives untouched"). The+vault root resolves through the one canonical resolver+(:func:`jarvis.memory.wiki.vault_root.resolve_vault_root`) — never through+``Path.cwd()`` — honoring an explicit ``ctx.config['vault_root']`` when+the runtime passes one.++Only pages under the four interactive page-kind directories+(``entities/``, ``concepts/``, ``projects/``, ``sessions/``) are yielded:++- ``external_id`` — ``"<kind>/<slug>"`` (e.g. ``"entities/viktoria"``).+- ``title`` — frontmatter ``title:`` value, else the first ``# `` heading,+ else the slug.+- ``permalink`` — ``file://`` URI of the page.++Cursor / checkpoint / deletion semantics are inherited from+:mod:`jarvis.ultrawiki.connectors.local_folder` (mtime-ns cursor;+deletions detected by the runtime's reconcile pass during full backfill).+"""++from __future__ import annotations++import logging+from pathlib import Path++from jarvis.ultrawiki.connectors.local_folder import (+ LocalFolderConnector,+ first_h1_heading,+)+from jarvis.ultrawiki.types import AuthKind, ConnectorContext++log = logging.getLogger(__name__)++_FRONTMATTER_SCAN_LINES = 50+++def _frontmatter_title(body: str) -> str:+ """Extract a ``title:`` value from a leading YAML frontmatter block."""+ if not body.startswith("---"):+ return ""+ for line in body.splitlines()[1:_FRONTMATTER_SCAN_LINES]:+ if line.strip() == "---":+ break+ if line.startswith("title:"):+ return line.partition(":")[2].strip().strip("\"'")+ return ""+++class NormalWikiConnector(LocalFolderConnector):+ """Read-only stream of the built-in wiki's vault pages."""++ id = "normal-wiki"+ label = "Built-in Wiki"+ auth = AuthKind.NONE # the vault root resolves from config, no user path needed++ DEFAULT_EXTENSIONS = (".md",)+ PAGE_KINDS: tuple[str, ...] = ("entities", "concepts", "projects", "sessions")++ def _resolve_root(self, ctx: ConnectorContext) -> Path | None:+ # Lazy import: keeps 'import jarvis.ultrawiki.connectors' boot-cheap+ # (AP-26) — vault_root pulls in jarvis.core.paths.+ from jarvis.memory.wiki.vault_root import resolve_vault_root++ resolution = resolve_vault_root(ctx.config.get("vault_root"))+ root = resolution.path+ if not root.is_dir():+ log.warning(+ "%s: wiki vault root %s does not exist; yielding nothing",+ self.id,+ root,+ )+ return None+ return root++ def _extensions(self, ctx: ConnectorContext) -> tuple[str, ...]:+ return self.DEFAULT_EXTENSIONS++ def _sorted_files(self, root: Path, extensions: tuple[str, ...]) -> list[Path]:+ matches: list[Path] = []+ for kind in self.PAGE_KINDS:+ sub = root / kind+ if not sub.is_dir():+ continue+ for path in sub.rglob("*"):+ if not path.is_file() or path.suffix.lower() not in extensions:+ continue+ rel_parts = path.relative_to(root).parts+ if any(part.startswith(".") for part in rel_parts):+ continue+ matches.append(path)+ matches.sort(key=lambda p: p.relative_to(root).as_posix())+ return matches++ def _external_id_for(self, root: Path, path: Path) -> str:+ return path.relative_to(root).with_suffix("").as_posix()++ def _title_for(self, path: Path, body: str) -> str:+ return _frontmatter_title(body) or first_h1_heading(body) or path.stem+++__all__ = ["NormalWikiConnector"]diff --git a/jarvis/ultrawiki/connectors/obsidian_vault.py b/jarvis/ultrawiki/connectors/obsidian_vault.pynew file mode 100644index 0000000000..d0550c9c97--- /dev/null+++ b/jarvis/ultrawiki/connectors/obsidian_vault.py@@ -0,0 +1,52 @@+"""Obsidian-vault connector: stream every markdown note of a vault.++Walks ``ctx.config['root']`` recursively for ``*.md`` files, skipping+hidden directories (``.obsidian``, ``.trash``, and any other dot-prefixed+directory). Yields one :class:`~jarvis.ultrawiki.types.RawItem` per note:++- ``external_id`` — POSIX relative path inside the vault (stable across+ runs; a rename is a delete + add, resolved by the reconcile pass).+- ``title`` — first ``# `` heading, falling back to the file name.+- ``timestamp_utc`` — file modification time.+- ``permalink`` — ``file://`` URI of the note.++Cursor / checkpoint / deletion semantics are inherited from+:mod:`jarvis.ultrawiki.connectors.local_folder` and documented there:+the incremental cursor is the highest ``st_mtime_ns`` seen (as a string,+advanced by the runtime from ``metadata["mtime_ns"]``), and deletions are+detected only by the runtime's stored-vs-yielded ``external_id``+comparison during a FULL backfill — a file walk cannot see files that no+longer exist, so no tombstone items are emitted here.+"""++from __future__ import annotations++from pathlib import Path++from jarvis.ultrawiki.connectors.local_folder import (+ LocalFolderConnector,+ first_h1_heading,+)+from jarvis.ultrawiki.types import ConnectorContext+++class ObsidianVaultConnector(LocalFolderConnector):+ """Markdown-only local walk with Obsidian-specific skip rules."""++ id = "obsidian-vault"+ label = "Obsidian Vault"+ # auth / capabilities inherited: LOCAL_PATH, backfill + CURSOR + deletes.++ DEFAULT_EXTENSIONS = (".md",)+ SKIP_DIR_NAMES = frozenset({".obsidian", ".trash"})++ def _extensions(self, ctx: ConnectorContext) -> tuple[str, ...]:+ # An Obsidian vault is markdown by definition; ignore any+ # 'extensions' config to keep the source honest.+ return self.DEFAULT_EXTENSIONS++ def _title_for(self, path: Path, body: str) -> str:+ return first_h1_heading(body) or path.stem+++__all__ = ["ObsidianVaultConnector"]diff --git a/jarvis/ultrawiki/connectors/plugin_bridge.py b/jarvis/ultrawiki/connectors/plugin_bridge.pynew file mode 100644index 0000000000..8a1588583b--- /dev/null+++ b/jarvis/ultrawiki/connectors/plugin_bridge.py@@ -0,0 +1,220 @@+"""Plugin-bridge connector: pull from every connected Jarvis integration.++This is the generic gateway of design doc 02's "Jarvis plugin/CLI bridge"+family: ONE connector that adapts any Jarvis-side integration into the+``RawItem`` stream, instead of a bespoke connector per tool.++Candidate enumeration (module-level helper, NOT part of the connector+protocol): :func:`list_candidates` lists the CONNECTED integrations a user+could turn into UltraWiki sources —++- marketplace plugin connections ("connected" = a token is stored and not+ flagged ``needs_reauth``, the same rule the marketplace UI applies), and+- MCP servers configured (and enabled) in the user's ``mcp.json``.++Every probe is wrapped so a half-configured install (no keyring service,+corrupt catalog, missing mcp.json) shortens the list instead of crashing+it. All imports of the marketplace/MCP machinery are lazy (AP-26).++Prototype honesty: the connector instance takes+``ctx.config['integration_id']`` (a candidate ``id`` such as+``"plugin:github"`` or ``"mcp:filesystem"``) and yields items ONLY when a+pull adapter for that integration is registered. Where no pull adapter+exists yet, ``backfill`` logs one honest structured line and yields+NOTHING — the source still registers, consent still gates it+(``uw_sources.consent``), and the UI can show "pull adapter pending" via+:func:`has_pull_adapter`. No data is ever faked.++Extension contract — how a real per-integration pull adapter plugs in+later:++1. An adapter is a callable ``(ctx, checkpoint) -> AsyncIterator[RawItem]``+ (an async generator function is the natural shape). It owns the+ integration-specific "list items since X" logic — driving the plugin's+ MCP tools, REST client, or CLI — and maps each record to a ``RawItem``+ with a stable ``external_id``, a real ``permalink`` (the platform's+ deep link), and an ISO-8601 UTC ``timestamp_utc``.+2. It registers itself under the candidate id via+ :func:`register_pull_adapter` (idempotent overwrite), typically from+ the runtime's bootstrap — never at import time of this module.+3. The bridge stays a pure pass-through: consent, scheduling, batching,+ and checkpoint persistence remain the runtime's job; adapters must not+ touch the store, embed, or call an LLM (design doc 02, hard rule 1).+"""++from __future__ import annotations++import logging+from collections.abc import AsyncIterator, Callable+from typing import Any++from jarvis.ultrawiki.types import (+ AuthKind,+ ConnectorCapabilities,+ ConnectorContext,+ IncrementalMode,+ RawItem,+)++log = logging.getLogger(__name__)++#: A pull adapter: ``(ctx, checkpoint) -> AsyncIterator[RawItem]``.+PullAdapter = Callable[[ConnectorContext, "str | None"], AsyncIterator[RawItem]]++_PULL_ADAPTERS: dict[str, PullAdapter] = {}+++def register_pull_adapter(integration_id: str, adapter: PullAdapter) -> None:+ """Register (or replace) the pull adapter for one integration id."""+ _PULL_ADAPTERS[integration_id] = adapter+++def unregister_pull_adapter(integration_id: str) -> None:+ """Remove a registered pull adapter; missing ids are a no-op."""+ _PULL_ADAPTERS.pop(integration_id, None)+++def has_pull_adapter(integration_id: str) -> bool:+ """True when a pull adapter is registered for the integration id."""+ return integration_id in _PULL_ADAPTERS+++def _adapter_note(integration_id: str) -> str:+ return "pull adapter available" if has_pull_adapter(integration_id) else "pull adapter pending"+++def _marketplace_candidates() -> list[dict[str, str]]:+ candidates: list[dict[str, str]] = []+ try:+ from jarvis.marketplace.catalog_data import load_catalog+ from jarvis.marketplace.token_store import TokenStore++ catalog = load_catalog()+ store = TokenStore()+ except Exception as exc:+ log.debug("plugin-bridge: marketplace catalog unavailable: %s", exc)+ return candidates+ for spec in catalog.plugins:+ try:+ tokens = store.load(spec.id)+ except Exception as exc:+ log.debug("plugin-bridge: token probe failed for plugin %s: %s", spec.id, exc)+ continue+ if tokens is None or tokens.needs_reauth:+ continue+ integration_id = f"plugin:{spec.id}"+ candidates.append(+ {+ "id": integration_id,+ "kind": "plugin",+ "label": spec.display_name,+ "detail": (+ f"connected marketplace plugin ({spec.category}); "+ f"{_adapter_note(integration_id)}"+ ),+ }+ )+ return candidates+++def _mcp_candidates() -> list[dict[str, str]]:+ candidates: list[dict[str, str]] = []+ try:+ from jarvis.mcp.state import load_config++ config = load_config()+ servers: Any = config.get("mcpServers") or {}+ except Exception as exc:+ log.debug("plugin-bridge: mcp.json unavailable: %s", exc)+ return candidates+ if not isinstance(servers, dict):+ return candidates+ for name, entry in servers.items():+ try:+ if not isinstance(entry, dict):+ continue+ if not entry.get("enabled", True):+ continue+ integration_id = f"mcp:{name}"+ label = str(entry.get("display") or str(name).replace("-", " ").title())+ description = str(entry.get("description") or "").strip()+ detail = "configured MCP server"+ if description:+ detail += f" ({description})"+ detail += f"; {_adapter_note(integration_id)}"+ candidates.append(+ {+ "id": integration_id,+ "kind": "mcp",+ "label": label,+ "detail": detail,+ }+ )+ except Exception as exc:+ log.debug("plugin-bridge: skipping mcp.json entry %r: %s", name, exc)+ continue+ return candidates+++def list_candidates() -> list[dict[str, str]]:+ """CONNECTED integrations a user could turn into UltraWiki sources.++ Each entry: ``{"id", "kind", "label", "detail"}`` where ``kind`` is+ ``"plugin"`` (marketplace) or ``"mcp"`` (mcp.json server). Never+ raises — a broken registry merely shortens the list.+ """+ return _marketplace_candidates() + _mcp_candidates()+++class PluginBridgeConnector:+ """Adapt one connected Jarvis integration into the ``RawItem`` stream."""++ id = "plugin-bridge"+ label = "Connected Integrations"+ # Auth is owned by the underlying integration (marketplace token / MCP+ # server config); the bridge itself needs no credential of its own.+ auth = AuthKind.NONE+ capabilities = ConnectorCapabilities(+ backfill=True,+ incremental=IncrementalMode.NONE, # prototype: freshness = re-run backfill+ deletes=False,+ )++ async def backfill(+ self, ctx: ConnectorContext, checkpoint: str | None = None+ ) -> AsyncIterator[RawItem]:+ integration_id = str(ctx.config.get("integration_id") or "")+ if not integration_id:+ log.warning(+ "plugin-bridge: source %s has no 'integration_id' configured; yielding nothing",+ ctx.source_id,+ )+ return+ adapter = _PULL_ADAPTERS.get(integration_id)+ if adapter is None:+ log.info(+ "plugin-bridge: pull adapter pending integration_id=%s source_id=%s yielded=0",+ integration_id,+ ctx.source_id,+ )+ return+ async for item in adapter(ctx, checkpoint):+ yield item++ async def incremental(+ self, ctx: ConnectorContext, cursor: str | None = None+ ) -> AsyncIterator[RawItem]:+ # capabilities.incremental is NONE: the scheduler re-runs backfill+ # instead. Kept as an empty async generator for protocol parity.+ return+ yield # pragma: no cover - unreachable; marks this as an async generator+++__all__ = [+ "PluginBridgeConnector",+ "PullAdapter",+ "has_pull_adapter",+ "list_candidates",+ "register_pull_adapter",+ "unregister_pull_adapter",+]diff --git a/jarvis/ultrawiki/distill.py b/jarvis/ultrawiki/distill.pynew file mode 100644index 0000000000..a4383dd537--- /dev/null+++ b/jarvis/ultrawiki/distill.py@@ -0,0 +1,274 @@+"""UltraWiki distillation — turn one raw item into a normalized memory document.++The "distill before you embed" principle (design doc 01): what gets embedded is+not the raw fragmentary text but an LLM-normalized document — a searchable+question, a summary, the resolution, mentioned entities, and references. The+prompt uses XML-tagged sections (per the Anthropic prompting guidance cited in+the Cerebras write-up) and demands strict minified JSON output.++Provider resolution is key-aware and cross-family (AP-22), reusing the wiki+provider chain directly: when ``cfg.ultrawiki.distill_provider`` is set, that+provider (with ``distill_model`` or its cheap router-tier default) leads the+chain; every other credential-ready provider follows as fallback. On total+chain failure :class:`DistillError` is raised — the staged pipeline owns+retries and dead-lettering.++Caching contract (design doc 02, determinism economics): results are cached on+``(content_hash, PROMPT_VERSION, model)``. Bump :data:`PROMPT_VERSION` on ANY+prompt change so improved prompts re-enrich incrementally instead of serving+stale cached distillations.+"""++from __future__ import annotations++import json+import logging+import re+from dataclasses import dataclass, field+from typing import Any++from jarvis.brain.streaming import aggregate+from jarvis.core.protocols import BrainMessage, BrainRequest+from jarvis.memory.wiki.provider_chain import (+ build_wiki_provider_chain,+ complete_with_fallback,+ credential_ready_wiki_providers,+)+from jarvis.ultrawiki.types import content_hash_for++log = logging.getLogger(__name__)++__all__ = [+ "PROMPT_VERSION",+ "DistillError",+ "DistillResult",+ "build_distill_prompt",+ "distill_cache_key",+ "distill_text",+]++#: Part of the distillation cache key — bump on EVERY prompt change.+PROMPT_VERSION = 1++#: Raw bodies are truncated before prompting; a distillation summarizes, it+#: does not need six-figure transcripts, and the marker keeps the cut honest.+_BODY_TRUNCATE_CHARS = 8000+_TRUNCATION_MARKER = "\n[... input truncated for distillation ...]"++_DEFAULT_TIMEOUT_S = 90.0++_SYSTEM_PROMPT = (+ "You are a precise archival distiller inside a personal memory system. "+ "You turn one raw captured item into a normalized, searchable memory "+ "document. You answer with STRICT minified JSON only - no prose, no "+ "markdown fences, no keys beyond the requested ones. You never invent "+ "facts that are not in the source item."+)+++class DistillError(RuntimeError):+ """The whole provider chain failed to produce parseable distillation JSON.++ Retryable: the pipeline keeps the item's last good state and retries later.+ """+++@dataclass(slots=True)+class DistillResult:+ """Salvaged distillation output. Keys the model omitted arrive empty —+ a partially-filled document is still worth embedding."""++ question: str = ""+ summary: str = ""+ resolution: str = ""+ entities: list[str] = field(default_factory=list)+ refs: list[str] = field(default_factory=list)+ raw_json: str = "" # the JSON exactly as the provider produced it+++def _truncate_body(body: str) -> str:+ if len(body) <= _BODY_TRUNCATE_CHARS:+ return body+ return body[:_BODY_TRUNCATE_CHARS] + _TRUNCATION_MARKER+++def build_distill_prompt(*, title: str, body: str, source_kind: str) -> str:+ """The normalized user prompt: XML-tagged sections, strict-JSON contract."""+ return (+ "<task>\n"+ "Distill the source item below into one normalized memory document\n"+ "for semantic search over a personal knowledge base.\n"+ "</task>\n"+ f'<source kind="{source_kind}">\n'+ f"<title>{title}</title>\n"+ f"<body>\n{_truncate_body(body)}\n</body>\n"+ "</source>\n"+ "<output_format>\n"+ "Return STRICT minified JSON on a single line with exactly these keys:\n"+ '{"question":"the question this item answers, phrased as a user would '+ 'ask it","summary":"a 2-4 sentence factual summary","resolution":"the '+ 'outcome, decision, or answer; empty string if none","entities":'+ '["mentioned people, places, organizations, projects, systems"],'+ '"refs":["explicit references to other documents, URLs, or ids"]}\n'+ "Rules: no markdown fences; no additional keys; entities and refs are\n"+ "arrays of short strings; use empty values where the item provides\n"+ "nothing; never invent facts.\n"+ "</output_format>"+ )+++def distill_cache_key(*, title: str, body: str, model: str) -> tuple[str, int, str]:+ """``(content_hash, prompt_version, model)`` — the ``uw_distill_cache`` key.++ The hash covers the TRUNCATED body (what is actually distilled), so two+ inputs differing only beyond the truncation point share one cache row.+ """+ return content_hash_for(title, _truncate_body(body)), PROMPT_VERSION, model+++_JSON_FENCE_RE = re.compile(r"```(?:json)?\s*(.*?)```", re.DOTALL)+++def _extract_json_object(text: str) -> tuple[str, dict[str, Any]] | None:+ """Best-effort extraction of the first JSON object from model output.++ Returns ``(raw_json_text, parsed_dict)`` or ``None``. Tolerates markdown+ fences and surrounding prose — providers wrap JSON despite instructions.+ """+ candidates = [text.strip()]+ for match in _JSON_FENCE_RE.finditer(text):+ candidates.append(match.group(1).strip())+ for candidate in list(candidates):+ start = candidate.find("{")+ end = candidate.rfind("}")+ if start >= 0 and end > start:+ candidates.append(candidate[start : end + 1])+ for candidate in candidates:+ if not candidate:+ continue+ try:+ parsed = json.loads(candidate)+ except ValueError:+ continue+ if isinstance(parsed, dict):+ return candidate, parsed+ return None+++def _string_list(value: Any) -> list[str]:+ """Salvage a JSON value into ``list[str]`` — scalars wrap, junk drops."""+ if isinstance(value, str):+ stripped = value.strip()+ return [stripped] if stripped else []+ if isinstance(value, (list, tuple)):+ out: list[str] = []+ for entry in value:+ text = entry if isinstance(entry, str) else str(entry)+ text = text.strip()+ if text:+ out.append(text)+ return out+ return []+++def _result_from(raw_json: str, parsed: dict[str, Any]) -> DistillResult:+ """Salvage whatever keys arrived; missing keys become empty values."""+ return DistillResult(+ question=str(parsed.get("question") or "").strip(),+ summary=str(parsed.get("summary") or "").strip(),+ resolution=str(parsed.get("resolution") or "").strip(),+ entities=_string_list(parsed.get("entities")),+ refs=_string_list(parsed.get("refs")),+ raw_json=raw_json,+ )+++def _validate_distill_response(agg: Any) -> str | None:+ """Chain validator: a transport success without parseable JSON is unusable+ output — the chain then tries the next provider family."""+ text = getattr(agg, "text", "") or ""+ if _extract_json_object(text) is None:+ return "distillation output holds no parseable JSON object"+ return None+++async def distill_text(+ cfg: Any,+ *,+ title: str,+ body: str,+ source_kind: str,+ registry: Any = None,+ timeout_s: float = _DEFAULT_TIMEOUT_S,+) -> DistillResult:+ """Distill one raw item through the key-aware cross-family provider chain.++ ``registry`` (a ``BrainProviderRegistry``) is injectable for tests; the+ default builds the entry-point registry lazily.++ Raises :class:`DistillError` when the whole chain fails; the caller (the+ staged pipeline) schedules the retry.+ """+ if registry is None:+ from jarvis.brain.provider_registry import BrainProviderRegistry++ registry = BrainProviderRegistry()++ ultrawiki = getattr(cfg, "ultrawiki", None)+ configured_provider = str(getattr(ultrawiki, "distill_provider", "") or "").strip()+ configured_model = str(getattr(ultrawiki, "distill_model", "") or "").strip()++ available = set(registry.available())+ credential_ready = credential_ready_wiki_providers(available=available, config=cfg)++ # An explicit distill provider leads the chain with its explicit model (or+ # its cheap router-tier default); otherwise the brain primary leads. Every+ # other credential-ready provider family follows either way (AP-22).+ primary = configured_provider or str(getattr(cfg.brain, "primary", "") or "")+ chain = build_wiki_provider_chain(+ primary=primary,+ model_override=configured_model if configured_provider else "",+ available=available,+ credential_ready=credential_ready,+ )++ request = BrainRequest(+ messages=(+ BrainMessage(+ role="user",+ content=build_distill_prompt(+ title=title, body=body, source_kind=source_kind+ ),+ ),+ ),+ system=_SYSTEM_PROMPT,+ temperature=0.1, # normalization, not creativity+ max_tokens=1600,+ stream=True,+ )++ result = await complete_with_fallback(+ registry=registry,+ chain=chain,+ request=request,+ timeout_s=timeout_s,+ label="UltraWikiDistiller",+ aggregate=aggregate,+ validate=_validate_distill_response,+ )+ if result is None:+ raise DistillError(+ "distillation failed: no configured provider returned parseable "+ "JSON - the item keeps its state and will be retried later"+ )++ agg, provider = result+ extracted = _extract_json_object(getattr(agg, "text", "") or "")+ if extracted is None: # defensive: validate() already guaranteed this+ raise DistillError(+ f"distillation failed: provider {provider} passed validation but "+ "no JSON object could be extracted"+ )+ raw_json, parsed = extracted+ log.debug("distilled item via provider %s (%d chars of JSON)", provider, len(raw_json))+ return _result_from(raw_json, parsed)diff --git a/jarvis/ultrawiki/embeddings.py b/jarvis/ultrawiki/embeddings.pynew file mode 100644index 0000000000..d4c966c623--- /dev/null+++ b/jarvis/ultrawiki/embeddings.py@@ -0,0 +1,403 @@+"""UltraWiki embedding backends — six thin httpx adapters, one frozen protocol.++Every backend implements the frozen :class:`jarvis.ultrawiki.types.EmbeddingBackend`+protocol: ``name``, ``ready() -> (bool, reason)``, ``async embed(texts, *, model)``.+All adapters are plain HTTP (httpx) — no provider SDKs — and resolve credentials+through :func:`jarvis.core.config.get_secret` / ``get_secret_any`` (OS keyring →+ENV → ``.env`` → local-file fallback), so they work identically on Windows,+macOS, and a headless Linux server.++Design rule D-3 (BINDING for this slot): **embeddings have NO cross-family+fallback.** The embedding pair ``(backend, model)`` pins the vector space of the+whole corpus; silently crossing to a different provider mid-ingest would mix+incompatible vector spaces and corrupt semantic search. A dead or keyless+backend therefore pauses the embed stage honestly (``ready()`` reports why,+``embed()`` raises :class:`EmbeddingError` and the pipeline retries later) while+keyword search keeps working. This is deliberately different from the chat+tiers' AP-22 cross-family chains.++Probes are capability/credential checks only (AP-21): ``ready()`` never raises,+never performs a paid call, and never special-cases provider names beyond each+backend's own adapter.+"""++from __future__ import annotations++import logging+from collections.abc import Callable, Iterator+from typing import Any++import httpx++from jarvis.core.config import get_secret, get_secret_any++log = logging.getLogger(__name__)++__all__ = [+ "EmbeddingError",+ "OllamaEmbedding",+ "GeminiEmbedding",+ "OpenAIEmbedding",+ "VoyageEmbedding",+ "MistralEmbedding",+ "CohereEmbedding",+ "EMBEDDING_BACKENDS",+ "DEFAULT_MODELS",+ "available_backends",+]+++class EmbeddingError(RuntimeError):+ """A single embed() call failed (HTTP, transport, or response parse).++ The staged pipeline owns retries: this error keeps the item's last good+ state and schedules ``next_retry_at`` — it is never swallowed silently.+ """+++#: Maximum texts per single HTTP request; larger inputs are chunked.+#: 96 is the smallest hard batch ceiling across the supported providers+#: (Cohere v2 caps at 96; Gemini batchEmbedContents at 100).+_CHUNK_SIZE = 96++#: Embedding calls move real payloads; a local Ollama on CPU can be slow.+_EMBED_TIMEOUT = httpx.Timeout(connect=5.0, read=120.0, write=30.0, pool=5.0)++#: ready() must answer fast — an offline endpoint may not stall anything.+_PROBE_TIMEOUT = httpx.Timeout(connect=2.0, read=2.0, write=2.0, pool=2.0)++_DEFAULT_OLLAMA_ENDPOINT = "http://localhost:11434"++#: Any-of credential candidates for Gemini embeddings, mirroring the core+#: ``PROVIDER_SECRET_CANDIDATES["gemini"]`` generic slots.+_GEMINI_KEY_CANDIDATES: tuple[tuple[str, str], ...] = (+ ("gemini_api_key", "GEMINI_API_KEY"),+ ("google_aistudio_api_key", "GOOGLE_AIStudio_API_KEY"),+ ("google_api_key", "GOOGLE_API_KEY"),+)+++def _chunks(texts: list[str], size: int) -> Iterator[list[str]]:+ for start in range(0, len(texts), size):+ yield texts[start : start + size]+++class _HttpEmbedding:+ """Shared httpx plumbing for every backend.++ ``transport`` is injectable so tests run fully offline through+ ``httpx.MockTransport``; production callers leave it ``None``.+ """++ name = "base"++ def __init__(self, *, transport: httpx.BaseTransport | None = None) -> None:+ self._transport = transport++ def _async_client(self) -> httpx.AsyncClient:+ return httpx.AsyncClient(timeout=_EMBED_TIMEOUT, transport=self._transport)++ async def _post_json(+ self,+ url: str,+ *,+ headers: dict[str, str] | None,+ payload: dict[str, Any],+ ) -> Any:+ """POST and return the parsed JSON body, mapping every failure to+ :class:`EmbeddingError` with an honest, credential-free message."""+ try:+ async with self._async_client() as client:+ response = await client.post(url, headers=headers, json=payload)+ response.raise_for_status()+ return response.json()+ except httpx.HTTPStatusError as exc:+ raise EmbeddingError(+ f"{self.name}: embedding request failed with "+ f"HTTP {exc.response.status_code}"+ ) from exc+ except httpx.HTTPError as exc:+ raise EmbeddingError(+ f"{self.name}: embedding request failed ({type(exc).__name__})"+ ) from exc+ except ValueError as exc: # response body is not JSON+ raise EmbeddingError(+ f"{self.name}: embedding response is not valid JSON"+ ) from exc++ def _check_count(self, vectors: list[list[float]], expected: int) -> list[list[float]]:+ if len(vectors) != expected:+ raise EmbeddingError(+ f"{self.name}: expected {expected} vectors, got {len(vectors)}"+ )+ return vectors+++class OllamaEmbedding(_HttpEmbedding):+ """Local Ollama — the keyless, offline-friendly option.++ ``ready()`` is a fast ``GET {endpoint}/api/version`` with a 2 s connect+ timeout, mirroring the honest-timeout style of the ack flash-brain Ollama+ adapter: an offline daemon answers "not ready" quickly, never stalls.+ """++ name = "ollama"++ def __init__(+ self,+ endpoint: str = _DEFAULT_OLLAMA_ENDPOINT,+ *,+ transport: httpx.BaseTransport | None = None,+ ) -> None:+ super().__init__(transport=transport)+ self._endpoint = (endpoint or _DEFAULT_OLLAMA_ENDPOINT).rstrip("/")++ def ready(self) -> tuple[bool, str]:+ url = f"{self._endpoint}/api/version"+ try:+ with httpx.Client(timeout=_PROBE_TIMEOUT, transport=self._transport) as client:+ client.get(url).raise_for_status()+ return True, ""+ except Exception as exc: # noqa: BLE001 — ready() never raises+ return False, (+ f"Ollama endpoint {self._endpoint} is unreachable "+ f"({type(exc).__name__}); is 'ollama serve' running?"+ )++ async def embed(self, texts: list[str], *, model: str) -> list[list[float]]:+ vectors: list[list[float]] = []+ for chunk in _chunks(texts, _CHUNK_SIZE):+ data = await self._post_json(+ f"{self._endpoint}/api/embed",+ headers=None,+ payload={"model": model, "input": chunk},+ )+ try:+ got = [list(map(float, vec)) for vec in data["embeddings"]]+ except (KeyError, TypeError, ValueError) as exc:+ raise EmbeddingError(+ f"{self.name}: unexpected embedding response shape"+ ) from exc+ vectors.extend(self._check_count(got, len(chunk)))+ return vectors+++class GeminiEmbedding(_HttpEmbedding):+ """Google AI Studio (Gemini) via REST ``batchEmbedContents``."""++ name = "gemini"++ _BASE = "https://generativelanguage.googleapis.com/v1beta"++ def _key(self) -> str | None:+ return get_secret_any(_GEMINI_KEY_CANDIDATES)++ def ready(self) -> tuple[bool, str]:+ if self._key():+ return True, ""+ return False, (+ "No Gemini API key is configured - save gemini_api_key in the "+ "API-Keys view or set the GEMINI_API_KEY environment variable."+ )++ async def embed(self, texts: list[str], *, model: str) -> list[list[float]]:+ key = self._key()+ if not key:+ raise EmbeddingError(f"{self.name}: no API key configured")+ url = f"{self._BASE}/models/{model}:batchEmbedContents"+ vectors: list[list[float]] = []+ for chunk in _chunks(texts, _CHUNK_SIZE):+ data = await self._post_json(+ url,+ headers={"x-goog-api-key": key},+ payload={+ "requests": [+ {+ "model": f"models/{model}",+ "content": {"parts": [{"text": text}]},+ }+ for text in chunk+ ]+ },+ )+ try:+ got = [list(map(float, entry["values"])) for entry in data["embeddings"]]+ except (KeyError, TypeError, ValueError) as exc:+ raise EmbeddingError(+ f"{self.name}: unexpected embedding response shape"+ ) from exc+ vectors.extend(self._check_count(got, len(chunk)))+ return vectors+++class _OpenAIShapedEmbedding(_HttpEmbedding):+ """Shared adapter for the OpenAI-compatible ``/v1/embeddings`` shape+ (OpenAI, Voyage, Mistral): Bearer auth, ``{"model", "input": [...]}``,+ response ``{"data": [{"index", "embedding"}]}``."""++ _URL = ""+ _SECRET_SLOT = ""+ _KEY_LABEL = ""++ def _key(self) -> str | None:+ return get_secret(self._SECRET_SLOT)++ def ready(self) -> tuple[bool, str]:+ if self._key():+ return True, ""+ return False, (+ f"No {self._KEY_LABEL} API key is configured - save "+ f"{self._SECRET_SLOT} in the API-Keys view or set the "+ f"{self._SECRET_SLOT.upper()} environment variable."+ )++ async def embed(self, texts: list[str], *, model: str) -> list[list[float]]:+ key = self._key()+ if not key:+ raise EmbeddingError(f"{self.name}: no API key configured")+ vectors: list[list[float]] = []+ for chunk in _chunks(texts, _CHUNK_SIZE):+ data = await self._post_json(+ self._URL,+ headers={"Authorization": f"Bearer {key}"},+ payload={"model": model, "input": chunk},+ )+ try:+ rows = list(data["data"])+ rows.sort(key=lambda row: int(row.get("index", 0)))+ got = [list(map(float, row["embedding"])) for row in rows]+ except (KeyError, TypeError, ValueError) as exc:+ raise EmbeddingError(+ f"{self.name}: unexpected embedding response shape"+ ) from exc+ vectors.extend(self._check_count(got, len(chunk)))+ return vectors+++class OpenAIEmbedding(_OpenAIShapedEmbedding):+ name = "openai"+ _URL = "https://api.openai.com/v1/embeddings"+ _SECRET_SLOT = "openai_api_key" # noqa: S105 — secret slot NAME, not a value+ _KEY_LABEL = "OpenAI"+++class VoyageEmbedding(_OpenAIShapedEmbedding):+ name = "voyage"+ _URL = "https://api.voyageai.com/v1/embeddings"+ _SECRET_SLOT = "voyage_api_key" # noqa: S105 — secret slot NAME, not a value+ _KEY_LABEL = "Voyage AI"+++class MistralEmbedding(_OpenAIShapedEmbedding):+ name = "mistral"+ _URL = "https://api.mistral.ai/v1/embeddings"+ _SECRET_SLOT = "mistral_api_key" # noqa: S105 — secret slot NAME, not a value+ _KEY_LABEL = "Mistral"+++class CohereEmbedding(_HttpEmbedding):+ """Cohere v2 embed. ``input_type`` distinguishes stored documents from+ query-time embeddings; the ingest pipeline keeps the default."""++ name = "cohere"++ _URL = "https://api.cohere.com/v2/embed"++ def __init__(+ self,+ *,+ input_type: str = "search_document",+ transport: httpx.BaseTransport | None = None,+ ) -> None:+ super().__init__(transport=transport)+ self._input_type = input_type++ def _key(self) -> str | None:+ return get_secret("cohere_api_key")++ def ready(self) -> tuple[bool, str]:+ if self._key():+ return True, ""+ return False, (+ "No Cohere API key is configured - save cohere_api_key in the "+ "API-Keys view or set the COHERE_API_KEY environment variable."+ )++ async def embed(self, texts: list[str], *, model: str) -> list[list[float]]:+ key = self._key()+ if not key:+ raise EmbeddingError(f"{self.name}: no API key configured")+ vectors: list[list[float]] = []+ for chunk in _chunks(texts, _CHUNK_SIZE):+ data = await self._post_json(+ self._URL,+ headers={"Authorization": f"Bearer {key}"},+ payload={+ "model": model,+ "texts": chunk,+ "input_type": self._input_type,+ "embedding_types": ["float"],+ },+ )+ try:+ got = [list(map(float, vec)) for vec in data["embeddings"]["float"]]+ except (KeyError, TypeError, ValueError) as exc:+ raise EmbeddingError(+ f"{self.name}: unexpected embedding response shape"+ ) from exc+ vectors.extend(self._check_count(got, len(chunk)))+ return vectors+++def _make_ollama(cfg: Any) -> OllamaEmbedding:+ endpoint = _DEFAULT_OLLAMA_ENDPOINT+ ultrawiki = getattr(cfg, "ultrawiki", None)+ if ultrawiki is not None:+ endpoint = getattr(ultrawiki, "ollama_endpoint", endpoint) or endpoint+ return OllamaEmbedding(endpoint=endpoint)+++#: name -> factory(cfg). The cfg argument feeds backend-local settings only+#: (today: the Ollama endpoint); credentials always ride the secret chain.+EMBEDDING_BACKENDS: dict[str, Callable[[Any], Any]] = {+ "ollama": _make_ollama,+ "gemini": lambda cfg: GeminiEmbedding(),+ "openai": lambda cfg: OpenAIEmbedding(),+ "voyage": lambda cfg: VoyageEmbedding(),+ "mistral": lambda cfg: MistralEmbedding(),+ "cohere": lambda cfg: CohereEmbedding(),+}++#: Sensible current default model per backend, surfaced by the settings UI.+DEFAULT_MODELS: dict[str, str] = {+ "ollama": "bge-m3",+ "gemini": "gemini-embedding-001",+ "openai": "text-embedding-3-small",+ "voyage": "voyage-3.5",+ "mistral": "mistral-embed",+ "cohere": "embed-v4.0",+}+++def available_backends(cfg: Any) -> list[dict[str, Any]]:+ """Readiness report over every registered backend, via ``ready()`` only.++ Purely capability/credential probes (AP-21): no paid calls, no provider+ special-casing beyond each backend's own adapter, never raises.+ """+ rows: list[dict[str, Any]] = []+ for name, factory in EMBEDDING_BACKENDS.items():+ try:+ usable, reason = factory(cfg).ready()+ except Exception as exc: # noqa: BLE001 — a broken probe reports, never raises+ usable, reason = False, f"readiness probe failed ({type(exc).__name__})"+ log.debug("embedding backend %s readiness probe failed", name, exc_info=True)+ rows.append(+ {+ "name": name,+ "ready": usable,+ "reason": reason,+ "default_model": DEFAULT_MODELS.get(name, ""),+ }+ )+ return rowsdiff --git a/jarvis/ultrawiki/migrations/README.md b/jarvis/ultrawiki/migrations/README.mdnew file mode 100644index 0000000000..cadb374dd9--- /dev/null+++ b/jarvis/ultrawiki/migrations/README.md@@ -0,0 +1,29 @@+# UltraWiki migrations++Forward-only schema migrations for the UltraWiki store (`data/ultrawiki.db`),+tracked via SQLite's `PRAGMA user_version` — the same engine contract as+`jarvis/memory/migration_runner.py`, which `store.py` invokes with this+directory.++The contract:++- `jarvis/ultrawiki/schema.sql` is the idempotent BASE schema+ (`CREATE ... IF NOT EXISTS`), applied on every open. It can never alter a+ table that already exists (for example widening a `CHECK` constraint).+- Any change to an existing table ships as an `NNNN_<slug>.sql` file in this+ directory, numbered `0001`, `0002`, ... strictly ascending. The runner+ applies every file whose number exceeds the database's current+ `user_version`, then bumps the pragma to the highest applied number —+ re-running is a no-op.+- Migrations are FORWARD-ONLY. Never edit or delete a shipped migration file;+ ship a new numbered file instead. Thousands of independent installs sit on+ different schema versions, and a rewritten historical file silently diverges+ them.+- Each migration file wraps its own statements in `BEGIN` / `COMMIT`. A+ failure leaves `user_version` at the previous head, so the next open retries+ from the same point.+- Files that do not match `NNNN_<slug>.sql` are ignored (this README included).++No migration files exist yet — the base schema is current. The Postgres+backend applies its DDL idempotently from `PostgresStore.ddl_statements()` and+receives its own version tracking when its first migration ships.diff --git a/jarvis/ultrawiki/rerank.py b/jarvis/ultrawiki/rerank.pynew file mode 100644index 0000000000..d4830c3846--- /dev/null+++ b/jarvis/ultrawiki/rerank.py@@ -0,0 +1,214 @@+"""UltraWiki rerank backends — thin httpx adapters for Voyage and Cohere.++Rerank is an OPTIONAL retrieval stage (design doc 03): a small scoring model+re-scores the fused top-N candidates against the actual question. When no+rerank-capable provider is configured or the configured one is not ready, the+caller skips the stage honestly and the fusion order stands — never a brick.++Adapters are plain HTTP (no SDKs); credentials resolve through+:func:`jarvis.core.config.get_secret`. ``ready()`` is a credential-presence+probe only (AP-21): never raises, never performs a paid call. A failing rerank+call raises :class:`RerankError`; the retrieval path catches it and falls back+to fusion order.+"""++from __future__ import annotations++import logging+from collections.abc import Callable+from typing import Any++import httpx++from jarvis.core.config import get_secret++log = logging.getLogger(__name__)++__all__ = [+ "RerankError",+ "VoyageReranker",+ "CohereReranker",+ "RERANK_BACKENDS",+ "DEFAULT_RERANK_MODELS",+ "available_rerankers",+ "resolve_reranker",+]+++class RerankError(RuntimeError):+ """A rerank call failed (HTTP, transport, or response parse). The caller+ skips the stage and keeps the fusion order."""+++_RERANK_TIMEOUT = httpx.Timeout(connect=5.0, read=30.0, write=10.0, pool=5.0)++#: Sensible current default model per backend.+DEFAULT_RERANK_MODELS: dict[str, str] = {+ "voyage": "rerank-2.5",+ "cohere": "rerank-v3.5",+}+++class _HttpReranker:+ """Shared httpx plumbing; ``transport`` is injectable for offline tests."""++ name = "base"+ _URL = ""+ _SECRET_SLOT = ""+ _KEY_LABEL = ""++ def __init__(+ self,+ *,+ model: str | None = None,+ transport: httpx.BaseTransport | None = None,+ ) -> None:+ self._model = model or DEFAULT_RERANK_MODELS.get(self.name, "")+ self._transport = transport++ def _key(self) -> str | None:+ return get_secret(self._SECRET_SLOT)++ def ready(self) -> tuple[bool, str]:+ if self._key():+ return True, ""+ return False, (+ f"No {self._KEY_LABEL} API key is configured - save "+ f"{self._SECRET_SLOT} in the API-Keys view or set the "+ f"{self._SECRET_SLOT.upper()} environment variable."+ )++ def _payload(self, query: str, documents: list[str], top_k: int) -> dict[str, Any]:+ raise NotImplementedError++ def _parse(self, data: Any) -> list[tuple[int, float]]:+ raise NotImplementedError++ async def rerank(+ self, query: str, documents: list[str], top_k: int+ ) -> list[tuple[int, float]]:+ """Score ``documents`` against ``query``; return ``(index, score)``+ pairs, best first, at most ``top_k`` entries."""+ if not documents:+ return []+ key = self._key()+ if not key:+ raise RerankError(f"{self.name}: no API key configured")+ try:+ async with httpx.AsyncClient(+ timeout=_RERANK_TIMEOUT, transport=self._transport+ ) as client:+ response = await client.post(+ self._URL,+ headers={"Authorization": f"Bearer {key}"},+ json=self._payload(query, documents, top_k),+ )+ response.raise_for_status()+ data = response.json()+ except httpx.HTTPStatusError as exc:+ raise RerankError(+ f"{self.name}: rerank request failed with "+ f"HTTP {exc.response.status_code}"+ ) from exc+ except httpx.HTTPError as exc:+ raise RerankError(+ f"{self.name}: rerank request failed ({type(exc).__name__})"+ ) from exc+ except ValueError as exc:+ raise RerankError(f"{self.name}: rerank response is not valid JSON") from exc+ try:+ return self._parse(data)+ except (KeyError, TypeError, ValueError) as exc:+ raise RerankError(f"{self.name}: unexpected rerank response shape") from exc+++class VoyageReranker(_HttpReranker):+ """Voyage AI ``POST /v1/rerank``."""++ name = "voyage"+ _URL = "https://api.voyageai.com/v1/rerank"+ _SECRET_SLOT = "voyage_api_key" # noqa: S105 — secret slot NAME, not a value+ _KEY_LABEL = "Voyage AI"++ def _payload(self, query: str, documents: list[str], top_k: int) -> dict[str, Any]:+ return {+ "model": self._model,+ "query": query,+ "documents": documents,+ "top_k": top_k,+ }++ def _parse(self, data: Any) -> list[tuple[int, float]]:+ return [+ (int(row["index"]), float(row["relevance_score"])) for row in data["data"]+ ]+++class CohereReranker(_HttpReranker):+ """Cohere ``POST /v2/rerank``."""++ name = "cohere"+ _URL = "https://api.cohere.com/v2/rerank"+ _SECRET_SLOT = "cohere_api_key" # noqa: S105 — secret slot NAME, not a value+ _KEY_LABEL = "Cohere"++ def _payload(self, query: str, documents: list[str], top_k: int) -> dict[str, Any]:+ return {+ "model": self._model,+ "query": query,+ "documents": documents,+ "top_n": top_k,+ }++ def _parse(self, data: Any) -> list[tuple[int, float]]:+ return [+ (int(row["index"]), float(row["relevance_score"]))+ for row in data["results"]+ ]+++#: name -> factory(cfg). cfg is unused today (keys ride the secret chain) but+#: keeps the registry shape identical to the embedding slot.+RERANK_BACKENDS: dict[str, Callable[[Any], Any]] = {+ "voyage": lambda cfg: VoyageReranker(),+ "cohere": lambda cfg: CohereReranker(),+}+++def available_rerankers(cfg: Any) -> list[dict[str, Any]]:+ """Readiness report over every rerank backend, via ``ready()`` only."""+ rows: list[dict[str, Any]] = []+ for name, factory in RERANK_BACKENDS.items():+ try:+ usable, reason = factory(cfg).ready()+ except Exception as exc: # noqa: BLE001 — a broken probe reports, never raises+ usable, reason = False, f"readiness probe failed ({type(exc).__name__})"+ log.debug("rerank backend %s readiness probe failed", name, exc_info=True)+ rows.append(+ {+ "name": name,+ "ready": usable,+ "reason": reason,+ "default_model": DEFAULT_RERANK_MODELS.get(name, ""),+ }+ )+ return rows+++def resolve_reranker(cfg: Any) -> Any | None:+ """The configured, ready reranker — or ``None``, telling the caller to+ skip the stage honestly (unconfigured, unknown, or not ready)."""+ ultrawiki = getattr(cfg, "ultrawiki", None)+ name = str(getattr(ultrawiki, "rerank_provider", "") or "").strip()+ if not name:+ return None+ factory = RERANK_BACKENDS.get(name)+ if factory is None:+ log.warning("unknown rerank provider %r - skipping the rerank stage", name)+ return None+ backend = factory(cfg)+ usable, reason = backend.ready()+ if not usable:+ log.info("rerank provider %s not ready (%s) - skipping the stage", name, reason)+ return None+ return backenddiff --git a/tests/contract/test_uw_connector_protocol.py b/tests/contract/test_uw_connector_protocol.pynew file mode 100644index 0000000000..8611c3580c--- /dev/null+++ b/tests/contract/test_uw_connector_protocol.py@@ -0,0 +1,110 @@+"""Contract tests for all UWConnector implementations.++Parametrized over :func:`discover_connectors` — the five built-ins are+always present, and every installed ``jarvis.uw_connector`` entry-point+plugin joins the same matrix. Third-party checks skip gracefully when no+entry-point plugins are installed (mirroring+``tests/contract/test_channel_adapter_contract.py``).+"""++from __future__ import annotations++import inspect+import re+from pathlib import Path++import pytest++from jarvis.ultrawiki.connectors import builtin_connectors, discover_connectors+from jarvis.ultrawiki.types import (+ AuthKind,+ ConnectorCapabilities,+ ConnectorContext,+ IncrementalMode,+ UWConnector,+)++_REGISTRY = discover_connectors()+_PARAMS = sorted(_REGISTRY.items())+_BUILTIN_NAMES = frozenset(builtin_connectors())+_ENTRY_POINT_PARAMS = [+ (name, factory) for name, factory in _PARAMS if name not in _BUILTIN_NAMES+] or [("skip", None)]++# Matches a MODULE-LEVEL (unindented) jarvis import; lazy in-function+# imports are the sanctioned pattern and stay allowed.+_MODULE_LEVEL_JARVIS_IMPORT = re.compile(+ r"^(?:import jarvis\b|from jarvis[.\s])", re.MULTILINE+)+++def _ctx() -> ConnectorContext:+ return ConnectorContext(source_id="contract-test", config={})+++async def _close_quietly(gen) -> None:+ aclose = getattr(gen, "aclose", None)+ if aclose is not None:+ await aclose()++[email protected]("name,factory", _PARAMS)+def test_connector_satisfies_the_frozen_protocol(name, factory):+ instance = factory()+ assert isinstance(instance, UWConnector), (+ f"{name} does not satisfy the UWConnector protocol"+ )+ assert isinstance(instance.id, str) and instance.id+ assert isinstance(instance.label, str) and instance.label+ assert isinstance(instance.auth, AuthKind)+ assert isinstance(instance.capabilities, ConnectorCapabilities)+ assert isinstance(instance.capabilities.backfill, bool)+ assert isinstance(instance.capabilities.incremental, IncrementalMode)+ assert isinstance(instance.capabilities.deletes, bool)++[email protected]("name,factory", _PARAMS)+def test_factory_returns_a_fresh_instance_per_use(name, factory):+ assert factory() is not factory()++[email protected]("name,factory", _PARAMS)+async def test_backfill_and_incremental_are_async_generators(name, factory):+ instance = factory()+ ctx = _ctx()++ backfill_gen = instance.backfill(ctx)+ assert hasattr(backfill_gen, "__aiter__") and hasattr(backfill_gen, "__anext__"), (+ f"{name}.backfill(ctx) must return an async iterator"+ )+ await _close_quietly(backfill_gen)++ incremental_gen = instance.incremental(ctx, None)+ assert hasattr(incremental_gen, "__aiter__") and hasattr(+ incremental_gen, "__anext__"+ ), f"{name}.incremental(ctx, cursor) must return an async iterator"+ await _close_quietly(incremental_gen)++[email protected]("name,factory", _PARAMS)+def test_backfill_accepts_the_optional_checkpoint(name, factory):+ signature = inspect.signature(factory().backfill)+ parameters = list(signature.parameters.values())+ assert len(parameters) >= 2, (+ f"{name}.backfill must accept (ctx, checkpoint=None)"+ )++[email protected]("name,factory", _ENTRY_POINT_PARAMS)+def test_entry_point_connector_has_no_module_level_jarvis_import(name, factory):+ """Third-party connectors stay decoupled via structural typing."""+ if factory is None:+ pytest.skip("no third-party jarvis.uw_connector entry points installed")+ module = inspect.getmodule(type(factory()))+ module_file = getattr(module, "__file__", None)+ if module_file is None:+ pytest.skip(f"source file for {name} is unavailable")+ source = Path(module_file).read_text(encoding="utf-8", errors="replace")+ assert not _MODULE_LEVEL_JARVIS_IMPORT.search(source), (+ f"entry-point connector {name} must not import jarvis.* at module level"+ )diff --git a/tests/fixtures/ultrawiki/README.md b/tests/fixtures/ultrawiki/README.mdnew file mode 100644index 0000000000..3511540d4d--- /dev/null+++ b/tests/fixtures/ultrawiki/README.md@@ -0,0 +1,14 @@+# UltraWiki connector test fixtures++Tiny, committed source trees the connector tests walk read-only:++- `obsidian_vault/` — a minimal Obsidian vault: two visible notes plus a+ `.obsidian/` config dir and a `.trash/` note that connectors must skip.+- `local_folder/` — a mixed folder: markdown + plain text (yielded by the+ default extension filter) and a `.bin` file (excluded by default).+- `wiki_vault/` — a minimal built-in-wiki vault with one page under+ `entities/` and one under `concepts/`.++Tests that need controlled modification times (cursor round-trips) build+their trees in `tmp_path` instead; these committed trees only pin the+walk, skip, id, title, and permalink behavior.diff --git a/tests/fixtures/ultrawiki/local_folder/image.bin b/tests/fixtures/ultrawiki/local_folder/image.binnew file mode 100644index 0000000000..a05c6af427--- /dev/null+++ b/tests/fixtures/ultrawiki/local_folder/image.bin@@ -0,0 +1 @@+NOT-TEXT: binary placeholder excluded by the default extension filter.diff --git a/tests/fixtures/ultrawiki/local_folder/notes.txt b/tests/fixtures/ultrawiki/local_folder/notes.txtnew file mode 100644index 0000000000..54793e0260--- /dev/null+++ b/tests/fixtures/ultrawiki/local_folder/notes.txt@@ -0,0 +1 @@+Plain text notes: remember to water the plants.diff --git a/tests/fixtures/ultrawiki/local_folder/readme.md b/tests/fixtures/ultrawiki/local_folder/readme.mdnew file mode 100644index 0000000000..157b806dcf--- /dev/null+++ b/tests/fixtures/ultrawiki/local_folder/readme.md@@ -0,0 +1,3 @@+# Read Me++A markdown file inside a plain local folder.diff --git a/tests/fixtures/ultrawiki/obsidian_vault/.obsidian/app.json b/tests/fixtures/ultrawiki/obsidian_vault/.obsidian/app.jsonnew file mode 100644index 0000000000..0967ef424b--- /dev/null+++ b/tests/fixtures/ultrawiki/obsidian_vault/.obsidian/app.json@@ -0,0 +1 @@+{}diff --git a/tests/fixtures/ultrawiki/obsidian_vault/.trash/old.md b/tests/fixtures/ultrawiki/obsidian_vault/.trash/old.mdnew file mode 100644index 0000000000..1e92096605--- /dev/null+++ b/tests/fixtures/ultrawiki/obsidian_vault/.trash/old.md@@ -0,0 +1,3 @@+# Deleted Note++This note sits in the trash and must never be ingested.diff --git a/tests/fixtures/ultrawiki/obsidian_vault/daily/idea.md b/tests/fixtures/ultrawiki/obsidian_vault/daily/idea.mdnew file mode 100644index 0000000000..9b03ab9b84--- /dev/null+++ b/tests/fixtures/ultrawiki/obsidian_vault/daily/idea.md@@ -0,0 +1,3 @@+# Project Idea++Build a semantic memory index over every source.diff --git a/tests/fixtures/ultrawiki/obsidian_vault/note.md b/tests/fixtures/ultrawiki/obsidian_vault/note.mdnew file mode 100644index 0000000000..21945350ea--- /dev/null+++ b/tests/fixtures/ultrawiki/obsidian_vault/note.md@@ -0,0 +1,3 @@+# Meeting Notes++Dinner with Viktoria at seven, downtown.diff --git a/tests/fixtures/ultrawiki/wiki_vault/concepts/hybrid-retrieval.md b/tests/fixtures/ultrawiki/wiki_vault/concepts/hybrid-retrieval.mdnew file mode 100644index 0000000000..b569f32378--- /dev/null+++ b/tests/fixtures/ultrawiki/wiki_vault/concepts/hybrid-retrieval.md@@ -0,0 +1,7 @@+---+type: concept+slug: hybrid-retrieval+title: Hybrid Retrieval+---++Keyword and vector lists fused with reciprocal rank fusion.diff --git a/tests/fixtures/ultrawiki/wiki_vault/entities/ada-lovelace.md b/tests/fixtures/ultrawiki/wiki_vault/entities/ada-lovelace.mdnew file mode 100644index 0000000000..557b1dd466--- /dev/null+++ b/tests/fixtures/ultrawiki/wiki_vault/entities/ada-lovelace.md@@ -0,0 +1,8 @@+---+type: entity+slug: ada-lovelace+---++# Ada Lovelace++Wrote the first published algorithm.diff --git a/tests/unit/ultrawiki/__init__.py b/tests/unit/ultrawiki/__init__.pynew file mode 100644index 0000000000..7abee7f433--- /dev/null+++ b/tests/unit/ultrawiki/__init__.py@@ -0,0 +1 @@+"""Unit tests for the UltraWiki semantic memory mode."""diff --git a/tests/unit/ultrawiki/test_connectors.py b/tests/unit/ultrawiki/test_connectors.pynew file mode 100644index 0000000000..b60273c8e4--- /dev/null+++ b/tests/unit/ultrawiki/test_connectors.py@@ -0,0 +1,439 @@+"""Unit tests for the UltraWiki local-first connectors.++Covers the registry, the file-walk connectors (obsidian-vault,+local-folder, normal-wiki), the jarvis-conversations chunker against a+handmade SQLite store using the REAL ``messages`` DDL, and the+plugin-bridge gateway. Everything runs offline with no credentials.+"""++from __future__ import annotations++import logging+import os+import re+import sqlite3+from datetime import UTC, datetime+from pathlib import Path++import pytest++from jarvis.ultrawiki.connectors import (+ builtin_connectors,+ discover_connectors,+ discovery_failures,+)+from jarvis.ultrawiki.connectors import plugin_bridge as plugin_bridge_module+from jarvis.ultrawiki.connectors.jarvis_conversations import (+ JarvisConversationsConnector,+)+from jarvis.ultrawiki.connectors.local_folder import LocalFolderConnector+from jarvis.ultrawiki.connectors.normal_wiki import NormalWikiConnector+from jarvis.ultrawiki.connectors.obsidian_vault import ObsidianVaultConnector+from jarvis.ultrawiki.connectors.plugin_bridge import (+ PluginBridgeConnector,+ list_candidates,+ register_pull_adapter,+ unregister_pull_adapter,+)+from jarvis.ultrawiki.types import ConnectorContext, RawItem++TESTS_ROOT = Path(__file__).resolve().parents[2]+FIXTURES = TESTS_ROOT / "fixtures" / "ultrawiki"+REPO_ROOT = TESTS_ROOT.parent++_ISO_UTC_RE = re.compile(r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z")+_NS = 10**9+++async def _collect(agen) -> list[RawItem]:+ return [item async for item in agen]+++def _ctx(config: dict) -> ConnectorContext:+ return ConnectorContext(source_id="test-source", config=config)+++# ---------------------------------------------------------------------------+# Registry+# ---------------------------------------------------------------------------+++class TestRegistry:+ def test_builtin_connectors_expose_five_fresh_factories(self):+ registry = builtin_connectors()+ assert set(registry) == {+ "obsidian-vault",+ "local-folder",+ "jarvis-conversations",+ "normal-wiki",+ "plugin-bridge",+ }+ for name, factory in registry.items():+ first, second = factory(), factory()+ assert first is not second, f"{name} must be instantiated fresh per use"+ assert first.id == name++ def test_discover_includes_builtins_and_records_failures(self):+ discovered = discover_connectors()+ assert set(builtin_connectors()) <= set(discovered)+ assert isinstance(discovery_failures(), dict)+++# ---------------------------------------------------------------------------+# Obsidian vault+# ---------------------------------------------------------------------------+++class TestObsidianVault:+ async def test_backfill_yields_visible_notes_with_stable_ids(self):+ root = FIXTURES / "obsidian_vault"+ items = await _collect(+ ObsidianVaultConnector().backfill(_ctx({"root": str(root)}))+ )+ assert [item.external_id for item in items] == ["daily/idea.md", "note.md"]+ note = next(item for item in items if item.external_id == "note.md")+ assert note.title == "Meeting Notes"+ assert "Viktoria" in note.body+ assert note.permalink == (root / "note.md").resolve().as_uri()+ for item in items:+ assert _ISO_UTC_RE.fullmatch(item.timestamp_utc)+ assert isinstance(item.metadata["mtime_ns"], int)++ async def test_hidden_and_trash_dirs_are_skipped(self):+ root = FIXTURES / "obsidian_vault"+ items = await _collect(+ ObsidianVaultConnector().backfill(_ctx({"root": str(root)}))+ )+ assert all(".obsidian" not in item.external_id for item in items)+ assert all(".trash" not in item.external_id for item in items)++ async def test_cursor_roundtrip_incremental_reyields_only_touched_file(+ self, tmp_path: Path+ ):+ (tmp_path / "a.md").write_text("# Alpha\nBody A.\n", encoding="utf-8")+ (tmp_path / "b.md").write_text("# Beta\nBody B.\n", encoding="utf-8")+ base_ns = 1_700_000_000 * _NS+ os.utime(tmp_path / "a.md", ns=(base_ns, base_ns))+ os.utime(tmp_path / "b.md", ns=(base_ns + _NS, base_ns + _NS))+ connector = ObsidianVaultConnector()+ ctx = _ctx({"root": str(tmp_path)})++ items = await _collect(connector.backfill(ctx))+ assert [item.external_id for item in items] == ["a.md", "b.md"]+ cursor = str(max(item.metadata["mtime_ns"] for item in items))++ assert await _collect(connector.incremental(ctx, cursor)) == []++ touched_ns = base_ns + 5 * _NS+ os.utime(tmp_path / "a.md", ns=(touched_ns, touched_ns))+ changed = await _collect(connector.incremental(ctx, cursor))+ assert [item.external_id for item in changed] == ["a.md"]++ async def test_checkpoint_resumes_after_last_seen_id(self, tmp_path: Path):+ (tmp_path / "a.md").write_text("# A\n", encoding="utf-8")+ (tmp_path / "b.md").write_text("# B\n", encoding="utf-8")+ ctx = _ctx({"root": str(tmp_path)})+ resumed = await _collect(+ ObsidianVaultConnector().backfill(ctx, checkpoint="a.md")+ )+ assert [item.external_id for item in resumed] == ["b.md"]++ async def test_missing_root_yields_nothing_and_logs(+ self, tmp_path: Path, caplog: pytest.LogCaptureFixture+ ):+ ctx = _ctx({"root": str(tmp_path / "absent")})+ with caplog.at_level(logging.WARNING):+ assert await _collect(ObsidianVaultConnector().backfill(ctx)) == []+ assert "does not exist" in caplog.text++ async def test_unparsable_cursor_reyields_everything(+ self, tmp_path: Path, caplog: pytest.LogCaptureFixture+ ):+ (tmp_path / "a.md").write_text("# A\n", encoding="utf-8")+ ctx = _ctx({"root": str(tmp_path)})+ with caplog.at_level(logging.WARNING):+ items = await _collect(+ ObsidianVaultConnector().incremental(ctx, "not-a-number")+ )+ assert [item.external_id for item in items] == ["a.md"]+ assert "unusable incremental cursor" in caplog.text+++# ---------------------------------------------------------------------------+# Local folder+# ---------------------------------------------------------------------------+++class TestLocalFolder:+ async def test_default_extensions_yield_md_and_txt_only(self):+ root = FIXTURES / "local_folder"+ items = await _collect(+ LocalFolderConnector().backfill(_ctx({"root": str(root)}))+ )+ assert [item.external_id for item in items] == ["notes.txt", "readme.md"]++ async def test_custom_extensions_config(self):+ root = FIXTURES / "local_folder"+ ctx = _ctx({"root": str(root), "extensions": ["bin"]})+ items = await _collect(LocalFolderConnector().backfill(ctx))+ assert [item.external_id for item in items] == ["image.bin"]++ async def test_oversized_file_is_skipped(+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+ ):+ monkeypatch.setattr(LocalFolderConnector, "MAX_FILE_BYTES", 16)+ (tmp_path / "small.txt").write_text("tiny", encoding="utf-8")+ (tmp_path / "big.txt").write_text("x" * 64, encoding="utf-8")+ items = await _collect(+ LocalFolderConnector().backfill(_ctx({"root": str(tmp_path)}))+ )+ assert [item.external_id for item in items] == ["small.txt"]++ async def test_non_utf8_bytes_are_replaced_not_raised(self, tmp_path: Path):+ (tmp_path / "weird.txt").write_bytes(b"caf\xe9 latin-1")+ items = await _collect(+ LocalFolderConnector().backfill(_ctx({"root": str(tmp_path)}))+ )+ assert len(items) == 1+ assert "caf" in items[0].body++ async def test_missing_root_config_yields_nothing_and_logs(+ self, caplog: pytest.LogCaptureFixture+ ):+ with caplog.at_level(logging.WARNING):+ assert await _collect(LocalFolderConnector().backfill(_ctx({}))) == []+ assert "no 'root' configured" in caplog.text+++# ---------------------------------------------------------------------------+# Jarvis conversations+# ---------------------------------------------------------------------------+++def _messages_ddl() -> str:+ """The REAL messages DDL, extracted from jarvis/memory/schema.sql."""+ schema = (REPO_ROOT / "jarvis" / "memory" / "schema.sql").read_text(+ encoding="utf-8"+ )+ match = re.search(+ r"CREATE TABLE IF NOT EXISTS messages \(.*?\);", schema, re.DOTALL+ )+ assert match is not None, "messages DDL not found in jarvis/memory/schema.sql"+ return match.group(0)+++def _ns_at(day: str, hour: int, minute: int = 0) -> int:+ moment = datetime.strptime(day, "%Y-%m-%d").replace(+ hour=hour, minute=minute, tzinfo=UTC+ )+ return int(moment.timestamp()) * _NS+++def conversations_db(tmp_path: Path) -> Path:+ """A tiny handmade store with the real messages schema."""+ db_path = tmp_path / "jarvis.db"+ conn = sqlite3.connect(db_path)+ try:+ conn.execute(_messages_ddl())+ conn.executemany(+ "INSERT INTO messages (trace_id, thread_id, timestamp_ns, role, text) "+ "VALUES (?, ?, ?, ?, ?)",+ [+ ("tr-1", "t1", _ns_at("2026-01-05", 9), "user", "hello"),+ ("tr-1", "t1", _ns_at("2026-01-05", 9, 1), "assistant", "hi there"),+ ("tr-1", "t1", _ns_at("2026-01-06", 8), "user", "next day"),+ ("tr-2", None, _ns_at("2026-01-05", 12), "user", "standalone"),+ ],+ )+ conn.commit()+ finally:+ conn.close()+ return db_path+++class TestJarvisConversations:+ async def test_backfill_chunks_per_conversation_and_day(+ self, conversations_db: Path+ ):+ connector = JarvisConversationsConnector()+ items = await _collect(+ connector.backfill(_ctx({"db_path": str(conversations_db)}))+ )+ assert [item.external_id for item in items] == [+ "t1:2026-01-05",+ "t1:2026-01-06",+ "tr-2:2026-01-05",+ ]+ first = items[0]+ assert first.body == "user: hello\nassistant: hi there"+ assert first.thread_key == "t1"+ assert first.permalink == "jarvis://chats/t1"+ assert first.timestamp_utc == "2026-01-05T09:01:00Z"+ assert first.metadata["message_count"] == 2+ # The trace_id fallback names the conversation when thread_id is NULL.+ assert items[2].permalink == "jarvis://chats/tr-2"++ async def test_incremental_rechunks_only_touched_days(+ self, conversations_db: Path+ ):+ connector = JarvisConversationsConnector()+ ctx = _ctx({"db_path": str(conversations_db)})+ items = await _collect(connector.backfill(ctx))+ cursor = str(max(item.metadata["max_rowid"] for item in items))++ assert await _collect(connector.incremental(ctx, cursor)) == []++ conn = sqlite3.connect(conversations_db)+ try:+ conn.execute(+ "INSERT INTO messages (trace_id, thread_id, timestamp_ns, role, text) "+ "VALUES (?, ?, ?, ?, ?)",+ ("tr-1", "t1", _ns_at("2026-01-05", 10), "user", "later addition"),+ )+ conn.commit()+ finally:+ conn.close()++ changed = await _collect(connector.incremental(ctx, cursor))+ assert [item.external_id for item in changed] == ["t1:2026-01-05"]+ # The whole day is re-chunked, in chronological order.+ assert changed[0].body == (+ "user: hello\nassistant: hi there\nuser: later addition"+ )+ assert changed[0].metadata["max_rowid"] > int(cursor)++ async def test_backfill_checkpoint_resumes_after_chunk(+ self, conversations_db: Path+ ):+ connector = JarvisConversationsConnector()+ ctx = _ctx({"db_path": str(conversations_db)})+ resumed = await _collect(connector.backfill(ctx, checkpoint="t1:2026-01-05"))+ assert [item.external_id for item in resumed] == [+ "t1:2026-01-06",+ "tr-2:2026-01-05",+ ]++ async def test_missing_db_yields_nothing(self, tmp_path: Path):+ connector = JarvisConversationsConnector()+ ctx = _ctx({"db_path": str(tmp_path / "absent.db")})+ assert await _collect(connector.backfill(ctx)) == []+ assert await _collect(connector.incremental(ctx, None)) == []+ assert not (tmp_path / "absent.db").exists(), "read-only probe must not create the db"+++# ---------------------------------------------------------------------------+# Normal wiki+# ---------------------------------------------------------------------------+++class TestNormalWiki:+ async def test_backfill_yields_kind_slug_ids_and_titles(self):+ root = FIXTURES / "wiki_vault"+ items = await _collect(+ NormalWikiConnector().backfill(_ctx({"vault_root": str(root)}))+ )+ by_id = {item.external_id: item for item in items}+ assert set(by_id) == {"concepts/hybrid-retrieval", "entities/ada-lovelace"}+ assert by_id["entities/ada-lovelace"].title == "Ada Lovelace"+ assert by_id["concepts/hybrid-retrieval"].title == "Hybrid Retrieval"+ assert (+ by_id["entities/ada-lovelace"].permalink+ == (root / "entities" / "ada-lovelace.md").resolve().as_uri()+ )++ async def test_ignores_pages_outside_the_four_kind_dirs(self, tmp_path: Path):+ (tmp_path / "entities").mkdir()+ (tmp_path / "attachments").mkdir()+ (tmp_path / "entities" / "x.md").write_text("# X\n", encoding="utf-8")+ (tmp_path / "attachments" / "y.md").write_text("# Y\n", encoding="utf-8")+ (tmp_path / "log.md").write_text("# Log\n", encoding="utf-8")+ items = await _collect(+ NormalWikiConnector().backfill(_ctx({"vault_root": str(tmp_path)}))+ )+ assert [item.external_id for item in items] == ["entities/x"]++ async def test_incremental_uses_mtime_cursor(self, tmp_path: Path):+ (tmp_path / "concepts").mkdir()+ page = tmp_path / "concepts" / "alpha.md"+ page.write_text("# Alpha\n", encoding="utf-8")+ base_ns = 1_700_000_000 * _NS+ os.utime(page, ns=(base_ns, base_ns))+ connector = NormalWikiConnector()+ ctx = _ctx({"vault_root": str(tmp_path)})+ items = await _collect(connector.backfill(ctx))+ cursor = str(items[0].metadata["mtime_ns"])+ assert await _collect(connector.incremental(ctx, cursor)) == []+ os.utime(page, ns=(base_ns + _NS, base_ns + _NS))+ changed = await _collect(connector.incremental(ctx, cursor))+ assert [item.external_id for item in changed] == ["concepts/alpha"]+++# ---------------------------------------------------------------------------+# Plugin bridge+# ---------------------------------------------------------------------------+++class TestPluginBridge:+ def test_list_candidates_returns_a_list_on_this_host(self):+ result = list_candidates()+ assert isinstance(result, list)+ for entry in result:+ assert set(entry) == {"id", "kind", "label", "detail"}+ assert all(isinstance(value, str) for value in entry.values())+ assert entry["kind"] in {"plugin", "mcp"}++ def test_list_candidates_survives_broken_registries(+ self, monkeypatch: pytest.MonkeyPatch+ ):+ import jarvis.marketplace.catalog_data as catalog_data+ import jarvis.mcp.state as mcp_state++ def _boom(*_args, **_kwargs):+ raise RuntimeError("registry down")++ monkeypatch.setattr(catalog_data, "load_catalog", _boom)+ monkeypatch.setattr(mcp_state, "load_config", _boom)+ assert plugin_bridge_module.list_candidates() == []++ async def test_backfill_without_adapter_logs_pending_and_yields_nothing(+ self, caplog: pytest.LogCaptureFixture+ ):+ connector = PluginBridgeConnector()+ ctx = _ctx({"integration_id": "plugin:does-not-exist"})+ with caplog.at_level(logging.INFO):+ assert await _collect(connector.backfill(ctx)) == []+ assert "pull adapter pending" in caplog.text+ assert "plugin:does-not-exist" in caplog.text++ async def test_backfill_without_integration_id_warns(+ self, caplog: pytest.LogCaptureFixture+ ):+ with caplog.at_level(logging.WARNING):+ assert await _collect(PluginBridgeConnector().backfill(_ctx({}))) == []+ assert "no 'integration_id' configured" in caplog.text++ async def test_registered_pull_adapter_streams_items(self):+ async def fake_adapter(ctx, checkpoint):+ assert checkpoint is None+ yield RawItem(+ external_id="record-1",+ body="hello from the integration",+ permalink="https://example.invalid/records/1",+ timestamp_utc="2026-01-01T00:00:00Z",+ )++ register_pull_adapter("plugin:fake", fake_adapter)+ try:+ assert plugin_bridge_module.has_pull_adapter("plugin:fake")+ items = await _collect(+ PluginBridgeConnector().backfill(_ctx({"integration_id": "plugin:fake"}))+ )+ finally:+ unregister_pull_adapter("plugin:fake")+ assert [item.external_id for item in items] == ["record-1"]+ assert not plugin_bridge_module.has_pull_adapter("plugin:fake")++ async def test_incremental_is_an_empty_stream(self):+ items = await _collect(PluginBridgeConnector().incremental(_ctx({}), None))+ assert items == []diff --git a/tests/unit/ultrawiki/test_distill.py b/tests/unit/ultrawiki/test_distill.pynew file mode 100644index 0000000000..f065d27469--- /dev/null+++ b/tests/unit/ultrawiki/test_distill.py@@ -0,0 +1,276 @@+"""Offline unit tests for the UltraWiki distillation slot.++The provider chain is faked by monkeypatching ``complete_with_fallback`` /+``build_wiki_provider_chain`` / ``credential_ready_wiki_providers`` at the+distill module's import site — no network, no credentials, no real providers.+"""++from __future__ import annotations++from dataclasses import dataclass+from types import SimpleNamespace++import pytest++import jarvis.ultrawiki.distill as distill_mod+from jarvis.ultrawiki.distill import (+ PROMPT_VERSION,+ DistillError,+ DistillResult,+ build_distill_prompt,+ distill_cache_key,+ distill_text,+)+++@dataclass+class FakeAggregate:+ """Duck-type of the streaming aggregate the chain hands back."""++ text: str+++class FakeRegistry:+ def available(self) -> list[str]:+ return ["gemini", "openai"]+++def _cfg(distill_provider: str = "", distill_model: str = "", primary: str = "gemini"):+ return SimpleNamespace(+ ultrawiki=SimpleNamespace(+ distill_provider=distill_provider, distill_model=distill_model+ ),+ brain=SimpleNamespace(primary=primary),+ )+++def chain_env(monkeypatch):+ """Fake the whole provider-chain surface; capture what distill passes in."""+ captured: dict = {}++ monkeypatch.setattr(+ distill_mod,+ "credential_ready_wiki_providers",+ lambda *, available, config: set(available),+ )++ def fake_build_chain(*, primary, model_override, available, credential_ready=None):+ captured["primary"] = primary+ captured["model_override"] = model_override+ captured["available"] = set(available)+ return [(primary or "gemini", model_override or "cheap-default")]++ monkeypatch.setattr(distill_mod, "build_wiki_provider_chain", fake_build_chain)++ def script(result_text: str | None):+ async def fake_complete(**kwargs):+ captured.update(kwargs)+ if result_text is None:+ return None+ return FakeAggregate(text=result_text), "gemini"++ monkeypatch.setattr(distill_mod, "complete_with_fallback", fake_complete)++ captured["script"] = script+ return captured+++GOOD_JSON = (+ '{"question":"When was the deploy fixed?",'+ '"summary":"The deploy failed on a missing key and was fixed.",'+ '"resolution":"Rotated the key and redeployed.",'+ '"entities":["Deploy Pipeline","Alice"],'+ '"refs":["https://example.test/run/42"]}'+)+++# ----------------------------------------------------------------------+# Happy path + salvage+# ----------------------------------------------------------------------+++async def test_distill_happy_path_parses_all_fields(chain_env):+ chain_env["script"](GOOD_JSON)++ result = await distill_text(+ _cfg(), title="Deploy incident", body="the raw log", source_kind="chat",+ registry=FakeRegistry(),+ )++ assert isinstance(result, DistillResult)+ assert result.question == "When was the deploy fixed?"+ assert result.summary.startswith("The deploy failed")+ assert result.resolution == "Rotated the key and redeployed."+ assert result.entities == ["Deploy Pipeline", "Alice"]+ assert result.refs == ["https://example.test/run/42"]+ assert result.raw_json == GOOD_JSON+++async def test_distill_salvages_json_inside_markdown_fences(chain_env):+ chain_env["script"](f"Here is the document:\n```json\n{GOOD_JSON}\n```\nDone.")++ result = await distill_text(+ _cfg(), title="t", body="b", source_kind="note", registry=FakeRegistry(),+ )++ assert result.question == "When was the deploy fixed?"+++async def test_distill_salvages_json_embedded_in_prose(chain_env):+ chain_env["script"](f"Sure! {GOOD_JSON} Anything else?")++ result = await distill_text(+ _cfg(), title="t", body="b", source_kind="note", registry=FakeRegistry(),+ )++ assert result.summary.startswith("The deploy failed")+++async def test_distill_missing_keys_become_empty_values(chain_env):+ chain_env["script"]('{"summary":"only a summary arrived"}')++ result = await distill_text(+ _cfg(), title="t", body="b", source_kind="mail", registry=FakeRegistry(),+ )++ assert result.summary == "only a summary arrived"+ assert result.question == ""+ assert result.resolution == ""+ assert result.entities == []+ assert result.refs == []+++async def test_distill_scalar_entities_are_wrapped_into_a_list(chain_env):+ chain_env["script"]('{"summary":"s","entities":"Alice","refs":["", "r1", 42]}')++ result = await distill_text(+ _cfg(), title="t", body="b", source_kind="mail", registry=FakeRegistry(),+ )++ assert result.entities == ["Alice"]+ assert result.refs == ["r1", "42"] # empty entries drop, scalars stringify+++async def test_distill_total_chain_failure_raises_distill_error(chain_env):+ chain_env["script"](None)++ with pytest.raises(DistillError):+ await distill_text(+ _cfg(), title="t", body="b", source_kind="chat", registry=FakeRegistry(),+ )+++# ----------------------------------------------------------------------+# Provider resolution+# ----------------------------------------------------------------------+++async def test_configured_distill_provider_leads_the_chain(chain_env):+ chain_env["script"](GOOD_JSON)++ await distill_text(+ _cfg(distill_provider="openai", distill_model="gpt-cheap"),+ title="t", body="b", source_kind="chat", registry=FakeRegistry(),+ )++ assert chain_env["primary"] == "openai"+ assert chain_env["model_override"] == "gpt-cheap"+++async def test_unset_distill_provider_falls_back_to_brain_primary(chain_env):+ chain_env["script"](GOOD_JSON)++ await distill_text(+ _cfg(distill_provider="", distill_model="ignored", primary="claude-api"),+ title="t", body="b", source_kind="chat", registry=FakeRegistry(),+ )++ assert chain_env["primary"] == "claude-api"+ # distill_model belongs to distill_provider; without one it does not pin+ # the generic chain's lead model.+ assert chain_env["model_override"] == ""+++async def test_validate_callback_rejects_non_json_and_accepts_json(chain_env):+ chain_env["script"](GOOD_JSON)+ await distill_text(+ _cfg(), title="t", body="b", source_kind="chat", registry=FakeRegistry(),+ )++ validate = chain_env["validate"]+ assert validate(FakeAggregate(text="no json here, sorry")) is not None+ assert validate(FakeAggregate(text=GOOD_JSON)) is None+++# ----------------------------------------------------------------------+# Prompt + truncation+# ----------------------------------------------------------------------+++def test_prompt_carries_xml_sections_and_strict_json_contract():+ prompt = build_distill_prompt(title="My title", body="body text", source_kind="chat")++ assert "<task>" in prompt+ assert '<source kind="chat">' in prompt+ assert "<title>My title</title>" in prompt+ assert "<output_format>" in prompt+ assert "minified JSON" in prompt+ for key in ('"question"', '"summary"', '"resolution"', '"entities"', '"refs"'):+ assert key in prompt+++def test_prompt_truncates_long_bodies_with_a_marker():+ long_body = "x" * 20_000++ prompt = build_distill_prompt(title="t", body=long_body, source_kind="note")++ assert "truncated for distillation" in prompt+ assert len(prompt) < 10_000+++async def test_request_sent_to_chain_carries_the_truncated_prompt(chain_env):+ chain_env["script"](GOOD_JSON)++ await distill_text(+ _cfg(), title="t", body="y" * 20_000, source_kind="chat",+ registry=FakeRegistry(),+ )++ request = chain_env["request"]+ user_content = request.messages[0].content+ assert "truncated for distillation" in user_content+ assert request.system # the system prompt rides along+++# ----------------------------------------------------------------------+# Cache key+# ----------------------------------------------------------------------+++def test_cache_key_carries_prompt_version_and_model():+ content_hash, version, model = distill_cache_key(+ title="t", body="b", model="gemini-2.5-flash"+ )++ assert version == PROMPT_VERSION+ assert model == "gemini-2.5-flash"+ assert len(content_hash) == 64 # sha256 hex+++def test_cache_key_changes_with_prompt_version(monkeypatch):+ before = distill_cache_key(title="t", body="b", model="m")+ monkeypatch.setattr(distill_mod, "PROMPT_VERSION", PROMPT_VERSION + 1)+ after = distill_mod.distill_cache_key(title="t", body="b", model="m")++ assert before[0] == after[0] # same content+ assert before[1] != after[1] # version bump invalidates the cache row+++def test_cache_key_is_stable_and_content_sensitive():+ assert distill_cache_key(title="t", body="b", model="m") == distill_cache_key(+ title="t", body="b", model="m"+ )+ assert distill_cache_key(title="t", body="b", model="m") != distill_cache_key(+ title="t", body="other", model="m"+ )diff --git a/tests/unit/ultrawiki/test_embeddings.py b/tests/unit/ultrawiki/test_embeddings.pynew file mode 100644index 0000000000..bf119f0195--- /dev/null+++ b/tests/unit/ultrawiki/test_embeddings.py@@ -0,0 +1,354 @@+"""Offline unit tests for the UltraWiki embedding backends.++All HTTP goes through ``httpx.MockTransport`` injected via each adapter's+``transport`` parameter; secrets are monkeypatched at the module's import+site. No network, no credentials, no SDKs.+"""++from __future__ import annotations++import json+from types import SimpleNamespace++import httpx+import pytest++import jarvis.ultrawiki.embeddings as emb+from jarvis.ultrawiki.embeddings import (+ DEFAULT_MODELS,+ EMBEDDING_BACKENDS,+ CohereEmbedding,+ EmbeddingError,+ GeminiEmbedding,+ MistralEmbedding,+ OllamaEmbedding,+ OpenAIEmbedding,+ VoyageEmbedding,+ available_backends,+)+from jarvis.ultrawiki.types import EmbeddingBackend++FAKE_KEY = "unit-test-key-123"+++def no_secrets(monkeypatch):+ monkeypatch.setattr(emb, "get_secret", lambda key, env_fallback=None: None)+ monkeypatch.setattr(emb, "get_secret_any", lambda candidates: None)+++def fake_secrets(monkeypatch):+ monkeypatch.setattr(emb, "get_secret", lambda key, env_fallback=None: FAKE_KEY)+ monkeypatch.setattr(emb, "get_secret_any", lambda candidates: FAKE_KEY)+++def _json_handler(payload, captured, status=200):+ def handler(request: httpx.Request) -> httpx.Response:+ captured.append(request)+ return httpx.Response(status, json=payload)++ return handler+++def _body(request: httpx.Request) -> dict:+ return json.loads(request.content.decode("utf-8"))+++# ----------------------------------------------------------------------+# Protocol conformance + registry shape+# ----------------------------------------------------------------------+++def test_every_backend_satisfies_the_frozen_protocol():+ cfg = SimpleNamespace(ultrawiki=SimpleNamespace(ollama_endpoint="http://x:1"))+ for name, factory in EMBEDDING_BACKENDS.items():+ backend = factory(cfg)+ assert isinstance(backend, EmbeddingBackend)+ assert backend.name == name+++def test_registry_and_default_models_cover_the_same_six_backends():+ expected = {"ollama", "gemini", "openai", "voyage", "mistral", "cohere"}+ assert set(EMBEDDING_BACKENDS) == expected+ assert set(DEFAULT_MODELS) == expected+ assert all(DEFAULT_MODELS[name] for name in expected)+++# ----------------------------------------------------------------------+# Ollama+# ----------------------------------------------------------------------+++async def test_ollama_embed_posts_batch_and_parses_vectors():+ captured: list[httpx.Request] = []+ handler = _json_handler({"embeddings": [[0.1, 0.2], [0.3, 0.4]]}, captured)+ backend = OllamaEmbedding(+ endpoint="http://ollama.test:11434", transport=httpx.MockTransport(handler)+ )++ vectors = await backend.embed(["alpha", "beta"], model="bge-m3")++ assert vectors == [[0.1, 0.2], [0.3, 0.4]]+ assert str(captured[0].url) == "http://ollama.test:11434/api/embed"+ assert _body(captured[0]) == {"model": "bge-m3", "input": ["alpha", "beta"]}+++def test_ollama_ready_probes_the_version_endpoint():+ captured: list[httpx.Request] = []+ handler = _json_handler({"version": "0.5.0"}, captured)+ backend = OllamaEmbedding(+ endpoint="http://ollama.test:11434", transport=httpx.MockTransport(handler)+ )++ assert backend.ready() == (True, "")+ assert str(captured[0].url) == "http://ollama.test:11434/api/version"+++def test_ollama_ready_unreachable_endpoint_is_false_with_honest_reason():+ def refuse(request: httpx.Request) -> httpx.Response:+ raise httpx.ConnectError("connection refused")++ backend = OllamaEmbedding(+ endpoint="http://ollama.test:11434", transport=httpx.MockTransport(refuse)+ )++ usable, reason = backend.ready()+ assert usable is False+ assert "http://ollama.test:11434" in reason+ assert reason # honest English message, never empty on failure+++async def test_ollama_embed_maps_transport_error_to_embedding_error():+ def refuse(request: httpx.Request) -> httpx.Response:+ raise httpx.ConnectError("connection refused")++ backend = OllamaEmbedding(+ endpoint="http://ollama.test:11434", transport=httpx.MockTransport(refuse)+ )+ with pytest.raises(EmbeddingError):+ await backend.embed(["alpha"], model="bge-m3")+++async def test_ollama_embed_vector_count_mismatch_raises():+ handler = _json_handler({"embeddings": [[0.1]]}, [])+ backend = OllamaEmbedding(transport=httpx.MockTransport(handler))+ with pytest.raises(EmbeddingError):+ await backend.embed(["alpha", "beta"], model="bge-m3")+++async def test_embed_chunks_input_at_96_texts_per_call():+ captured: list[httpx.Request] = []++ def handler(request: httpx.Request) -> httpx.Response:+ captured.append(request)+ count = len(_body(request)["input"])+ return httpx.Response(200, json={"embeddings": [[1.0]] * count})++ backend = OllamaEmbedding(transport=httpx.MockTransport(handler))+ vectors = await backend.embed([f"text {i}" for i in range(100)], model="bge-m3")++ assert len(vectors) == 100+ assert len(captured) == 2+ assert len(_body(captured[0])["input"]) == 96+ assert len(_body(captured[1])["input"]) == 4+++async def test_embed_empty_input_returns_empty_without_http():+ captured: list[httpx.Request] = []+ handler = _json_handler({"embeddings": []}, captured)+ backend = OllamaEmbedding(transport=httpx.MockTransport(handler))++ assert await backend.embed([], model="bge-m3") == []+ assert captured == []+++# ----------------------------------------------------------------------+# Gemini+# ----------------------------------------------------------------------+++async def test_gemini_embed_uses_batch_endpoint_header_key_and_parses(fake_secrets):+ captured: list[httpx.Request] = []+ handler = _json_handler(+ {"embeddings": [{"values": [1.0, 2.0]}, {"values": [3.0, 4.0]}]}, captured+ )+ backend = GeminiEmbedding(transport=httpx.MockTransport(handler))++ vectors = await backend.embed(["one", "two"], model="gemini-embedding-001")++ assert vectors == [[1.0, 2.0], [3.0, 4.0]]+ request = captured[0]+ assert str(request.url).endswith(+ "/v1beta/models/gemini-embedding-001:batchEmbedContents"+ )+ assert request.headers["x-goog-api-key"] == FAKE_KEY+ body = _body(request)+ assert body["requests"][0]["model"] == "models/gemini-embedding-001"+ assert body["requests"][0]["content"]["parts"] == [{"text": "one"}]+ assert body["requests"][1]["content"]["parts"] == [{"text": "two"}]+++def test_gemini_ready_without_key_is_false_with_honest_reason(no_secrets):+ usable, reason = GeminiEmbedding().ready()+ assert usable is False+ assert "gemini_api_key" in reason+++# ----------------------------------------------------------------------+# OpenAI-shaped backends (openai, voyage, mistral)+# ----------------------------------------------------------------------+++async def test_openai_embed_posts_bearer_payload_and_restores_index_order(fake_secrets):+ captured: list[httpx.Request] = []+ handler = _json_handler(+ {+ "data": [+ {"index": 1, "embedding": [3.0]},+ {"index": 0, "embedding": [1.0]},+ ]+ },+ captured,+ )+ backend = OpenAIEmbedding(transport=httpx.MockTransport(handler))++ vectors = await backend.embed(["a", "b"], model="text-embedding-3-small")++ assert vectors == [[1.0], [3.0]] # re-sorted by index+ request = captured[0]+ assert str(request.url) == "https://api.openai.com/v1/embeddings"+ assert request.headers["authorization"] == f"Bearer {FAKE_KEY}"+ assert _body(request) == {"model": "text-embedding-3-small", "input": ["a", "b"]}+++async def test_voyage_embed_targets_voyage_url(fake_secrets):+ captured: list[httpx.Request] = []+ handler = _json_handler({"data": [{"index": 0, "embedding": [0.5]}]}, captured)+ backend = VoyageEmbedding(transport=httpx.MockTransport(handler))++ vectors = await backend.embed(["a"], model="voyage-3.5")++ assert vectors == [[0.5]]+ assert str(captured[0].url) == "https://api.voyageai.com/v1/embeddings"+ assert captured[0].headers["authorization"] == f"Bearer {FAKE_KEY}"+ assert _body(captured[0])["model"] == "voyage-3.5"+++async def test_mistral_embed_targets_mistral_url(fake_secrets):+ captured: list[httpx.Request] = []+ handler = _json_handler({"data": [{"index": 0, "embedding": [0.7]}]}, captured)+ backend = MistralEmbedding(transport=httpx.MockTransport(handler))++ vectors = await backend.embed(["a"], model="mistral-embed")++ assert vectors == [[0.7]]+ assert str(captured[0].url) == "https://api.mistral.ai/v1/embeddings"+ assert _body(captured[0])["model"] == "mistral-embed"+++async def test_openai_http_error_maps_to_embedding_error(fake_secrets):+ handler = _json_handler({"error": {"message": "server exploded"}}, [], status=500)+ backend = OpenAIEmbedding(transport=httpx.MockTransport(handler))+ with pytest.raises(EmbeddingError, match="HTTP 500"):+ await backend.embed(["a"], model="text-embedding-3-small")+++async def test_embed_without_key_raises_embedding_error(no_secrets):+ backend = OpenAIEmbedding(transport=httpx.MockTransport(_json_handler({}, [])))+ with pytest.raises(EmbeddingError, match="no API key"):+ await backend.embed(["a"], model="text-embedding-3-small")+++# ----------------------------------------------------------------------+# Cohere+# ----------------------------------------------------------------------+++async def test_cohere_embed_requests_float_type_and_parses(fake_secrets):+ captured: list[httpx.Request] = []+ handler = _json_handler({"embeddings": {"float": [[0.9, 0.8]]}}, captured)+ backend = CohereEmbedding(transport=httpx.MockTransport(handler))++ vectors = await backend.embed(["a"], model="embed-v4.0")++ assert vectors == [[0.9, 0.8]]+ request = captured[0]+ assert str(request.url) == "https://api.cohere.com/v2/embed"+ assert request.headers["authorization"] == f"Bearer {FAKE_KEY}"+ body = _body(request)+ assert body["texts"] == ["a"]+ assert body["embedding_types"] == ["float"]+ assert body["input_type"] == "search_document"+++async def test_cohere_unexpected_shape_maps_to_embedding_error(fake_secrets):+ handler = _json_handler({"embeddings": {}}, [])+ backend = CohereEmbedding(transport=httpx.MockTransport(handler))+ with pytest.raises(EmbeddingError, match="response shape"):+ await backend.embed(["a"], model="embed-v4.0")+++# ----------------------------------------------------------------------+# ready() without keys + available_backends+# ----------------------------------------------------------------------+++ "backend_class",+ [GeminiEmbedding, OpenAIEmbedding, VoyageEmbedding, MistralEmbedding, CohereEmbedding],+)+def test_keyed_backend_ready_without_key_is_false_and_honest(no_secrets, backend_class):+ usable, reason = backend_class().ready()+ assert usable is False+ assert reason # never an empty reason on a not-ready verdict+ assert "API-Keys" in reason # in-app recovery hint (recoverable in-app rule)+++ "backend_class",+ [GeminiEmbedding, OpenAIEmbedding, VoyageEmbedding, MistralEmbedding, CohereEmbedding],+)+def test_keyed_backend_ready_with_key_is_true(fake_secrets, backend_class):+ assert backend_class().ready() == (True, "")+++def test_available_backends_reports_all_six_with_honest_reasons(no_secrets):+ # Port 9 (discard) on loopback refuses instantly on every OS — the Ollama+ # probe stays offline-safe and fast.+ cfg = SimpleNamespace(ultrawiki=SimpleNamespace(ollama_endpoint="http://127.0.0.1:9"))++ rows = available_backends(cfg)++ assert [row["name"] for row in rows] == list(EMBEDDING_BACKENDS)+ for row in rows:+ assert row["ready"] is False+ assert row["reason"]+ assert row["default_model"] == DEFAULT_MODELS[row["name"]]+++def test_available_backends_uses_configured_ollama_endpoint(monkeypatch, no_secrets):+ seen: dict[str, str] = {}++ class _Probe:+ name = "ollama"++ def ready(self):+ return True, ""++ def fake_factory(endpoint="", **kwargs):+ seen["endpoint"] = endpoint+ return _Probe()++ monkeypatch.setattr(emb, "OllamaEmbedding", fake_factory)+ cfg = SimpleNamespace(ultrawiki=SimpleNamespace(ollama_endpoint="http://box:9999"))++ rows = available_backends(cfg)++ assert seen["endpoint"] == "http://box:9999"+ assert rows[0] == {+ "name": "ollama",+ "ready": True,+ "reason": "",+ "default_model": DEFAULT_MODELS["ollama"],+ }diff --git a/tests/unit/ultrawiki/test_rerank.py b/tests/unit/ultrawiki/test_rerank.pynew file mode 100644index 0000000000..f76697b409--- /dev/null+++ b/tests/unit/ultrawiki/test_rerank.py@@ -0,0 +1,190 @@+"""Offline unit tests for the UltraWiki rerank backends.++HTTP rides ``httpx.MockTransport`` through the injectable ``transport``+parameter; secrets are monkeypatched at the rerank module's import site.+"""++from __future__ import annotations++import json+from types import SimpleNamespace++import httpx+import pytest++import jarvis.ultrawiki.rerank as rr+from jarvis.ultrawiki.rerank import (+ DEFAULT_RERANK_MODELS,+ RERANK_BACKENDS,+ CohereReranker,+ RerankError,+ VoyageReranker,+ available_rerankers,+ resolve_reranker,+)++FAKE_KEY = "unit-test-key-456"+++def no_secrets(monkeypatch):+ monkeypatch.setattr(rr, "get_secret", lambda key, env_fallback=None: None)+++def fake_secrets(monkeypatch):+ monkeypatch.setattr(rr, "get_secret", lambda key, env_fallback=None: FAKE_KEY)+++def _json_handler(payload, captured, status=200):+ def handler(request: httpx.Request) -> httpx.Response:+ captured.append(request)+ return httpx.Response(status, json=payload)++ return handler+++def _body(request: httpx.Request) -> dict:+ return json.loads(request.content.decode("utf-8"))+++# ----------------------------------------------------------------------+# Happy paths+# ----------------------------------------------------------------------+++async def test_voyage_rerank_posts_payload_and_parses_index_score_pairs(fake_secrets):+ captured: list[httpx.Request] = []+ handler = _json_handler(+ {+ "data": [+ {"index": 2, "relevance_score": 0.91},+ {"index": 0, "relevance_score": 0.42},+ ]+ },+ captured,+ )+ backend = VoyageReranker(transport=httpx.MockTransport(handler))++ result = await backend.rerank("what broke?", ["a", "b", "c"], top_k=2)++ assert result == [(2, 0.91), (0, 0.42)]+ request = captured[0]+ assert str(request.url) == "https://api.voyageai.com/v1/rerank"+ assert request.headers["authorization"] == f"Bearer {FAKE_KEY}"+ assert _body(request) == {+ "model": "rerank-2.5",+ "query": "what broke?",+ "documents": ["a", "b", "c"],+ "top_k": 2,+ }+++async def test_cohere_rerank_posts_top_n_payload_and_parses_results(fake_secrets):+ captured: list[httpx.Request] = []+ handler = _json_handler(+ {"results": [{"index": 1, "relevance_score": 0.88}]}, captured+ )+ backend = CohereReranker(transport=httpx.MockTransport(handler))++ result = await backend.rerank("who is Alice?", ["x", "y"], top_k=1)++ assert result == [(1, 0.88)]+ request = captured[0]+ assert str(request.url) == "https://api.cohere.com/v2/rerank"+ assert request.headers["authorization"] == f"Bearer {FAKE_KEY}"+ assert _body(request) == {+ "model": "rerank-v3.5",+ "query": "who is Alice?",+ "documents": ["x", "y"],+ "top_n": 1,+ }+++async def test_rerank_empty_documents_short_circuits_without_http(fake_secrets):+ captured: list[httpx.Request] = []+ backend = VoyageReranker(+ transport=httpx.MockTransport(_json_handler({}, captured))+ )++ assert await backend.rerank("q", [], top_k=5) == []+ assert captured == []+++# ----------------------------------------------------------------------+# Errors + readiness+# ----------------------------------------------------------------------+++async def test_rerank_http_error_maps_to_rerank_error(fake_secrets):+ handler = _json_handler({"message": "rate limited"}, [], status=429)+ backend = VoyageReranker(transport=httpx.MockTransport(handler))+ with pytest.raises(RerankError, match="HTTP 429"):+ await backend.rerank("q", ["a"], top_k=1)+++async def test_rerank_unexpected_shape_maps_to_rerank_error(fake_secrets):+ handler = _json_handler({"unexpected": []}, [])+ backend = CohereReranker(transport=httpx.MockTransport(handler))+ with pytest.raises(RerankError, match="response shape"):+ await backend.rerank("q", ["a"], top_k=1)+++async def test_rerank_without_key_raises_rerank_error(no_secrets):+ backend = VoyageReranker(transport=httpx.MockTransport(_json_handler({}, [])))+ with pytest.raises(RerankError, match="no API key"):+ await backend.rerank("q", ["a"], top_k=1)++[email protected]("backend_class", [VoyageReranker, CohereReranker])+def test_ready_without_key_is_false_with_honest_reason(no_secrets, backend_class):+ usable, reason = backend_class().ready()+ assert usable is False+ assert reason+ assert "API-Keys" in reason # in-app recovery hint++[email protected]("backend_class", [VoyageReranker, CohereReranker])+def test_ready_with_key_is_true(fake_secrets, backend_class):+ assert backend_class().ready() == (True, "")+++# ----------------------------------------------------------------------+# Registry + honest skip+# ----------------------------------------------------------------------+++def test_registry_and_default_models_cover_the_same_backends():+ assert set(RERANK_BACKENDS) == {"voyage", "cohere"}+ assert set(DEFAULT_RERANK_MODELS) == {"voyage", "cohere"}+++def test_available_rerankers_without_keys_reports_all_not_ready(no_secrets):+ rows = available_rerankers(SimpleNamespace())++ assert [row["name"] for row in rows] == list(RERANK_BACKENDS)+ for row in rows:+ assert row["ready"] is False+ assert row["reason"]+ assert row["default_model"] == DEFAULT_RERANK_MODELS[row["name"]]+++def test_resolve_reranker_unconfigured_returns_none_for_honest_skip(fake_secrets):+ cfg = SimpleNamespace(ultrawiki=SimpleNamespace(rerank_provider=""))+ assert resolve_reranker(cfg) is None+++def test_resolve_reranker_unknown_provider_returns_none(fake_secrets):+ cfg = SimpleNamespace(ultrawiki=SimpleNamespace(rerank_provider="does-not-exist"))+ assert resolve_reranker(cfg) is None+++def test_resolve_reranker_keyless_provider_returns_none(no_secrets):+ cfg = SimpleNamespace(ultrawiki=SimpleNamespace(rerank_provider="voyage"))+ assert resolve_reranker(cfg) is None+++def test_resolve_reranker_ready_provider_returns_backend(fake_secrets):+ cfg = SimpleNamespace(ultrawiki=SimpleNamespace(rerank_provider="cohere"))+ backend = resolve_reranker(cfg)+ assert isinstance(backend, CohereReranker)