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(wiki): find wiki pages by meaning, next to the word search (#625)
Ruben Lütke902912f9ece9
diff --git a/docs/os-parity.md b/docs/os-parity.mdindex 4f257437d6..59253f1d69 100644--- a/docs/os-parity.md+++ b/docs/os-parity.md@@ -1288,6 +1288,7 @@ experiences today.| P-18 | Low | Overlay drop | Dropping a file ONTO the floating bar/mascot uses two backends: tkdnd on the Tk surfaces (Windows/Linux) and native Qt drag events on the macOS Qt bar (added 2026-07-27 — before that, dropping on the bar did nothing at all on a Mac). The bundled `libtkdnd*.so` links against X11 libs, so a Linux host without them registers no drop target | `jarvis/overlay/drop_target.py`, `jarvis/ui/jarvisbar/qt_overlay.py::dropEvent` | macOS and Windows: full parity. Linux desktop: needs `libxcursor1 libxrender1 libxext6` + `python3-tk` (otherwise `register()` returns False and it is a logged no-op). Headless: no overlay exists — the in-app dock (`POST /api/chat/drop`) carries the feature on every OS || P-19 | — | Overlay drop | RESOLVED 2026-07-27. The macOS bar runs in a companion process, whose drop bridge had no handler — the parent's is the real one. A file dropped on the macOS bar was accepted by the window (the OS even showed the "copy" cursor) and then silently discarded; it never became conversation context. Windows/Linux were unaffected (their bar is in-process). Fixed by forwarding the drop over the existing host protocol and returning the intake's verdict as `drop_result` | `jarvis/ui/jarvisbar/host.py::_wire_drop_forwarding`, `jarvis/ui/jarvisbar/subprocess_overlay.py::_dispatch_drop_event` | All three OSes deliver a dropped file into the conversation context and confirm it on the bar. Guards: `tests/unit/ui/jarvisbar/test_host_drop_roundtrip.py` || P-16 | Low | Wiki | `VaultLock` dead-owner fast-steal is POSIX-only (`os.kill(pid, 0)` liveness probe; on Windows `os.kill` cannot probe — a non-CTRL signal terminates the target) | `jarvis/memory/wiki/lock.py::_pid_alive` | Windows: a lock left by a crashed/restarted process is stolen only after the `stale_after_seconds` wall-clock window (300 s) — the pre-fix behavior everywhere; a Win32 `OpenProcess` probe could close this |+| P-48 | Low | Wiki semantic search | The optional search by meaning (off by default; the user switches it on in Profile > Memory) runs a sentence encoder through the base install's CPU `onnxruntime`. That package has no prebuilt wheel for Intel macOS and for macOS on Python 3.14, so it is not installed there | `jarvis/memory/wiki/semantic_model.py::runtime_available`, `pyproject.toml` (the `onnxruntime` markers) | On those two macOS setups the switch is disabled and says the feature is not available on this system; nothing is downloaded. The word search, the recall tool and the per-turn wiki context work exactly as before. Windows, Linux (including `python:3.11-slim`) and Apple Silicon macOS on Python 3.11-3.13 run it; verified live on Windows only || P-17 | Low | JarvisBar | "Follow the mouse to the active monitor" has per-OS monitor backends (Windows `MonitorFromPoint`+`rcWork`, macOS Qt available-geometry / Quartz, Linux X11 `xrandr`) but no Wayland backend — Wayland exposes no reliable global monitor geometry without portal support | `jarvis/platform/monitors.py::work_area_at`, `jarvis/ui/jarvisbar/overlay.py`, `qt_overlay.py` | Wayland: `work_area_at` returns `None`, so the bar keeps the single-monitor behaviour (it does not migrate; a cross-monitor drag pins to the primary work area). The feature is a graceful no-op there, never a crash || P-18 | Low | Agent accounts | Multi-subscription switching gives each account its own CLI config directory (`CLAUDE_CONFIG_DIR` / `CODEX_HOME`) — the CLIs' own documented override. On macOS, Claude Code keeps its credentials in the **Keychain** rather than in that directory, and whether a second config dir earns a second Keychain entry is UNVERIFIED on this hardware (everything here was measured on Windows) | `jarvis/agent_accounts.py::describe`, `env_overrides` | Windows/Linux: a second Claude seat works as designed (its `.credentials.json` lives in its own folder). macOS: the added account may come back reporting **"Not signed in"** after a completed sign-in — which is the honest outcome, not a crash: the switcher never claims a login it cannot read, so a pane is never silently routed to the first account's credentials. Codex is unaffected on all three OSes (`auth.json` is a plain file). Next Mac session: add a second Claude account, sign in, and check whether `describe()` reports it connected |diff --git a/jarvis/brain/factory.py b/jarvis/brain/factory.pyindex 16708cb315..71a5210b19 100644--- a/jarvis/brain/factory.py+++ b/jarvis/brain/factory.py@@ -1357,8 +1357,13 @@ def _phase2_full_brain(name="wiki-vault-warmup",daemon=True,).start()+ from jarvis.memory.wiki.semantic_search import get_active+manager._wiki_injector = WikiContextInjector(search=search,+ # The provider returns None until the user switches+ # semantic search on; nothing is loaded here.+ semantic_search=get_active,max_chars=getattr(wiki_cfg, "max_chars", 1500),latency_budget_ms=getattr(wiki_cfg, "latency_budget_ms", 150),min_keyword_length=getattr(wiki_cfg, "min_keyword_length", 3),diff --git a/jarvis/brain/wiki_context.py b/jarvis/brain/wiki_context.pyindex ef0d407742..9376eb7f87 100644--- a/jarvis/brain/wiki_context.py+++ b/jarvis/brain/wiki_context.py@@ -30,6 +30,17 @@ Relevance contract (``jarvis.brain.wiki_relevance``):When the gates decline a turn the knowledge is not lost: the router brainholds the ``wiki-recall`` tool and can look something up deliberately.+Semantic search (optional, off unless the user switched it on):+ The word search finds a page by the words it shares with the question. A+ question phrased differently from the note, or asked in another language,+ shares none. With semantic search active the injector also asks for pages+ that MEAN something close to the whole question and appends the ones the+ word search did not already bring. The two legs are independent: the word+ search runs exactly as it does without semantic search, a slow or broken+ semantic leg costs the turn nothing but its own hits, and a turn with no+ personal anchor (the strict verdict) gets no semantic hits at all, because+ for this kind of search a "nearest page" exists for every question.+Latency contract:The whole ``maybe_inject`` coroutine must complete in <= ``latency_budget_ms``milliseconds. It uses ``asyncio.wait_for`` to enforce this. A slow vault@@ -47,7 +58,8 @@ import asyncioimport loggingimport reimport time-from typing import TYPE_CHECKING+from collections.abc import Callable+from typing import TYPE_CHECKING, Anyif TYPE_CHECKING:from jarvis.memory.wiki.search import VaultSearch@@ -66,6 +78,18 @@ from jarvis.memory.wiki.telemetry import telemetrylog = logging.getLogger(__name__)+#: Similarity a page must reach to ride along on a turn nobody asked it into.+#: Measured on a real vault with the multilingual model: questions about the+#: user's own notes score 0.45 to 0.65 against the right page, while unrelated+#: questions with a personal ring ("tell me a joke") stay below 0.40.+SEMANTIC_MIN_SCORE = 0.42++#: A further semantic hit must come close to the best one of the same turn.+SEMANTIC_RELATIVE_FLOOR = 0.85++#: Pages the semantic leg may add to one turn.+SEMANTIC_MAX_HITS = 3+# Tokenize on whitespace and common punctuation_TOKEN_RE = re.compile(r"[^\w\s]|\s+", re.UNICODE)@@ -153,6 +177,7 @@ class WikiContextInjector:self,*,search: VaultSearch | None,+ semantic_search: Callable[[], Any] | None = None,max_chars: int = 12_000,latency_budget_ms: int = 150,min_keyword_length: int = 4,@@ -168,6 +193,10 @@ class WikiContextInjector:# wider budget covers the cold path when that race is lost, and is# far below anything audible next to a multi-second brain call.self._search = search+ # A provider, not an instance: the user can switch semantic search on+ # or off while the app runs, and the injector must follow without+ # being rebuilt. It returns ``None`` while the feature is off.+ self._semantic_search = semantic_searchself._max_chars = max_charsself._latency_budget_ms = latency_budget_msself._min_keyword_length = min_keyword_length@@ -247,61 +276,79 @@ class WikiContextInjector:user_text,min_length=self._min_keyword_length,)- if not keywords:+ semantic = self._semantic_for_turn(strict)+ if not keywords and semantic is None:self._miss(t0, "no_keywords")return system_promptquery = " ".join(keywords)-- # Run search with a strict latency budgetbudget_ms = self._latency_budget_ms- try:- retrieval = _run_search(self._search, query)- hits = await asyncio.wait_for(- retrieval,- timeout=budget_ms / 1000.0,- )- except TimeoutError:- log.warning(- "WikiContextInjector timed out after %dms (budget=%dms) — "- "skipping wiki context for this turn",- int((time.monotonic() - t0) * 1000),- budget_ms,- )- self._miss(t0, "timeout")- return system_prompt- except Exception: # noqa: BLE001- log.warning(- "WikiContextInjector search raised unexpectedly — "- "skipping wiki context",- exc_info=True,- )- self._miss(t0, "search_error")- return system_prompt+ # Started before the word search is awaited so both run side by side+ # inside the one budget. It embeds the whole question, not keywords.+ semantic_task = (+ asyncio.ensure_future(_run_semantic(semantic, user_text))+ if semantic is not None+ else None+ )+ try:+ hits: list = []+ miss_reason = "no_keywords"+ if keywords:+ # Run search with a strict latency budget+ try:+ retrieval = _run_search(self._search, query)+ hits = await asyncio.wait_for(+ retrieval,+ timeout=budget_ms / 1000.0,+ )+ except TimeoutError:+ log.warning(+ "WikiContextInjector timed out after %dms (budget=%dms) — "+ "skipping wiki context for this turn",+ int((time.monotonic() - t0) * 1000),+ budget_ms,+ )+ self._miss(t0, "timeout")+ return system_prompt+ except Exception: # noqa: BLE001+ log.warning(+ "WikiContextInjector search raised unexpectedly — "+ "skipping wiki context",+ exc_info=True,+ )+ self._miss(t0, "search_error")+ return system_prompt++ miss_reason = "no_hits"+ # Gate 2 (post-retrieval): the index matches on ANY query term, so+ # a page sharing one common word arrives looking just like one+ # that is on topic. Coverage + a within-call relative floor+ # separate them.+ if hits and self._relevance_gate:+ hits = relevant_hits(+ hits,+ query,+ min_coverage=self._strict_min_coverage+ if strict+ else self._min_coverage,+ min_relative_score=self._min_relative_score,+ )+ if not hits:+ miss_reason = (+ "no_relevant_hits_strict" if strict else "no_relevant_hits"+ )++ semantic_hits = await self._semantic_hits(semantic_task, t0, hits)+ finally:+ # Every way out, a cancelled turn included: the lookup must not+ # outlive the turn that asked for it. A finished one ignores this.+ _abandon(semantic_task)+ hits = [*hits, *semantic_hits]if not hits:- self._miss(t0, "no_hits")+ self._miss(t0, miss_reason)return system_prompt- # Gate 2 (post-retrieval): the index matches on ANY query term, so a- # page sharing one common word arrives looking just like one that is- # on topic. Coverage + a within-call relative floor separate them.- if self._relevance_gate:- hits = relevant_hits(- hits,- query,- min_coverage=self._strict_min_coverage- if strict- else self._min_coverage,- min_relative_score=self._min_relative_score,- )- if not hits:- self._miss(- t0,- "no_relevant_hits_strict" if strict else "no_relevant_hits",- )- return system_prompt-latency_ms = int((time.monotonic() - t0) * 1000)# Build the context block, capped at max_chars@@ -336,16 +383,71 @@ class WikiContextInjector:augmented = system_prompt + "\n\n" + frame_context_block(context_parts)telemetry.inc("wiki_context_hits")+ if semantic_hits:+ telemetry.inc("wiki_context_semantic_hits")log.info("WikiContextInjector injected=True hits=%d latency_ms=%d "- "verdict=%s mode=%s",+ "verdict=%s mode=%s semantic=%d",hits_included,latency_ms,verdict_reason,"strict" if strict else "standard",+ len(semantic_hits),)return augmented+ def _semantic_for_turn(self, strict: bool) -> Any | None:+ """The semantic search to ask this turn, or ``None``.++ A strict verdict means the turn carries no personal anchor. The word+ search may still answer it when a page covers nearly the whole+ question; a similarity score cannot make that distinction, so the+ semantic leg stays out of such turns.+ """+ if self._semantic_search is None or strict:+ return None+ try:+ semantic = self._semantic_search()+ except Exception: # noqa: BLE001 - an optional engine never breaks a turn+ log.debug("Semantic wiki search is unavailable this turn", exc_info=True)+ return None+ # The two engines must look at the same vault, or a hit would name a+ # page the word search's vault does not have.+ own_root = getattr(self._search, "_root", None)+ other_root = getattr(semantic, "vault_root", None)+ if own_root is not None and other_root is not None and own_root != other_root:+ return None+ return semantic++ async def _semantic_hits(+ self, task: asyncio.Future | None, t0: float, lexical_hits: list+ ) -> list:+ """Semantic hits for pages the word search did not already bring."""+ if task is None:+ return []+ remaining = self._latency_budget_ms / 1000.0 - (time.monotonic() - t0)+ try:+ found = await asyncio.wait_for(task, timeout=max(remaining, 0.005))+ except TimeoutError:+ log.debug("Semantic wiki search missed the turn's budget; skipped")+ return []+ except Exception: # noqa: BLE001 - the word search result stands on its own+ log.debug("Semantic wiki search failed this turn", exc_info=True)+ return []+ if not found:+ return []+ floor = found[0].score * SEMANTIC_RELATIVE_FLOOR+ # Path objects, not strings: on Windows the same page can arrive in two+ # spellings that differ only in case.+ taken = {getattr(hit, "path", None) for hit in lexical_hits}+ extra: list = []+ for hit in found:+ if hit.score < floor or hit.path in taken:+ continue+ taken.add(hit.path)+ extra.append(hit)+ return extra+async def _run_search(search: VaultSearch, query: str) -> list:"""Thin async wrapper around VaultSearch.search.@@ -355,3 +457,18 @@ async def _run_search(search: VaultSearch, query: str) -> list:"""loop = asyncio.get_event_loop()return await loop.run_in_executor(None, search.search, query)+++async def _run_semantic(search: Any, text: str) -> list:+ """Ask the semantic engine without ever waiting for its model."""+ loop = asyncio.get_event_loop()+ return await loop.run_in_executor(+ None,+ lambda: search.search(text, k=SEMANTIC_MAX_HITS, min_score=SEMANTIC_MIN_SCORE),+ )+++def _abandon(task: asyncio.Future | None) -> None:+ """Stop waiting for a semantic lookup whose turn already ended."""+ if task is not None:+ task.cancel()diff --git a/jarvis/core/config.py b/jarvis/core/config.pyindex b2f69f6fb9..cdfba745e4 100644--- a/jarvis/core/config.py+++ b/jarvis/core/config.py@@ -3231,6 +3231,13 @@ class WikiContextConfig(BaseModel):# within one call, so an absolute cutoff would be noise.min_relative_score: float = 0.35+ # Semantic search (jarvis/memory/wiki/semantic_search.py): find pages by+ # what they mean, across languages, next to the word search. Off unless+ # the user switches it on in the app, because switching it on downloads a+ # 135 MB model once and keeps it in memory. Written only by the app's own+ # switch (config_writer.set_wiki_semantic_search).+ semantic_search: bool = False+# Ambient personal knowledge — the standing identity card# (jarvis/brain/identity_card.py). Unlike the per-turn snippets above this# is a precomputed, LLM-free distillation of the user's own profile thatdiff --git a/jarvis/core/config_writer.py b/jarvis/core/config_writer.pyindex 8ad1aa3c8c..16df75e450 100644--- a/jarvis/core/config_writer.py+++ b/jarvis/core/config_writer.py@@ -1104,6 +1104,20 @@ def set_missions_paid_api_fallback(enabled: bool, *, path: Path = DEFAULT_CONFIG_patch_table(path, "missions", "paid_api_fallback", enabled)+def set_wiki_semantic_search(+ enabled: bool, *, path: Path = DEFAULT_CONFIG_FILE+) -> None:+ """Persist ``[wiki_context] semantic_search`` (search the wiki by meaning).++ The only writer of this key, called from ``PUT /api/wiki/semantic-search``.+ The route starts or stops the search engine itself, so the change applies+ at once; this write makes it survive a restart.+ """+ if not isinstance(enabled, bool):+ raise TypeError("semantic_search must be a bool")+ _patch_table(path, "wiki_context", "semantic_search", enabled)++def set_reply_language(name: str, *, path: Path = DEFAULT_CONFIG_FILE) -> None:"""Persist the user-facing reply-language pin in ``[brain] reply_language``.diff --git a/jarvis/memory/wiki/semantic_index.py b/jarvis/memory/wiki/semantic_index.pynew file mode 100644index 0000000000..d9456d28f1--- /dev/null+++ b/jarvis/memory/wiki/semantic_index.py@@ -0,0 +1,312 @@+"""Sentence vectors of the vault's pages, kept in the wiki database.++The word index (``fts_index``) finds a page by the words it contains. This+index finds it by what it says: every page is cut into short passages, each+passage becomes one vector from :class:`~jarvis.memory.wiki.semantic_model.SemanticEncoder`,+and a question is answered by the passages whose vectors point the same way.++The two indexes are independent. They share the database file and the rules+for which files count as pages, nothing else: the word index is rebuilt on+every start because that is cheap, this one is only ever brought up to date,+because computing a vector is the expensive part. A page is encoded again only+when its modification time or the model changed.+"""+from __future__ import annotations++import logging+import re+import sqlite3+from collections.abc import Callable+from dataclasses import dataclass+from pathlib import Path+from typing import Any++from jarvis.memory.wiki import fts_index+from jarvis.memory.wiki.semantic_model import EMBEDDING_DIMENSIONS, MODEL_REVISION++log = logging.getLogger(__name__)++_SCHEMA = """+CREATE TABLE IF NOT EXISTS wiki_semantic_pages (+ path TEXT PRIMARY KEY,+ mtime TEXT NOT NULL,+ model TEXT NOT NULL+);+CREATE TABLE IF NOT EXISTS wiki_semantic_chunks (+ path TEXT NOT NULL,+ chunk INTEGER NOT NULL,+ title TEXT NOT NULL,+ text TEXT NOT NULL,+ embedding BLOB NOT NULL,+ PRIMARY KEY (path, chunk)+);+"""++#: A passage shorter than this is a stray mark, not a statement. Kept low on+#: purpose: "Age: 34" is a whole fact once the page title stands in front.+_MIN_PASSAGE_CHARS = 6++#: The model reads about this much text; a longer passage is cut so its tail+#: is not silently ignored.+_MAX_PASSAGE_CHARS = 480++#: Upper bound per page, so one pathological file (a pasted log) cannot take+#: the index over.+_MAX_PASSAGES_PER_PAGE = 200++_HEADING_RE = re.compile(r"^#{1,6}\s+(.*\S)\s*$")+_BULLET_RE = re.compile(r"^\s*(?:[-*+]|\d+[.)])\s+")+_WIKILINK_RE = re.compile(r"\[\[([^\]|]+)(?:\|([^\]]+))?\]\]")+_MD_LINK_RE = re.compile(r"\[([^\]]+)\]\([^)]*\)")+_MARKUP_RE = re.compile(r"[*_`]+")+_SPACE_RE = re.compile(r"\s+")+_SENTENCE_END_RE = re.compile(r"(?<=[.!?;:])\s+")+++@dataclass(frozen=True, slots=True)+class SyncResult:+ """What one pass over the vault did."""++ pages: int+ encoded: int+ removed: int+ failed: int = 0+++def ensure_schema(conn: sqlite3.Connection) -> None:+ conn.executescript(_SCHEMA)+++def passages(title: str, body: str) -> list[tuple[str, str]]:+ """Cut a page into ``(passage, text to encode)`` pairs.++ A wiki page is mostly a list of facts under a few headings. Each list+ item and each paragraph becomes its own passage, because one vector for a+ whole list of unrelated facts matches none of them well. The encoded text+ carries the page title and the heading, so "born 1961" under "Harald"+ is findable as a fact about Harald.+ """+ out: list[tuple[str, str]] = []+ heading = ""+ paragraph: list[str] = []+ in_code = False++ def emit(raw: str) -> None:+ text = _plain(raw)+ if len(text) < _MIN_PASSAGE_CHARS:+ return+ context = ": ".join(part for part in (title, heading) if part)+ for piece in _split_long(text):+ if len(out) < _MAX_PASSAGES_PER_PAGE:+ out.append((piece, f"{context}: {piece}" if context else piece))++ def flush() -> None:+ if paragraph:+ emit(" ".join(paragraph))+ paragraph.clear()++ for line in body.splitlines():+ stripped = line.strip()+ if stripped.startswith("```"):+ flush()+ in_code = not in_code+ continue+ if in_code:+ continue+ if not stripped:+ flush()+ continue+ match = _HEADING_RE.match(stripped)+ if match:+ flush()+ found = _plain(match.group(1))+ heading = "" if found == title else found+ continue+ if _BULLET_RE.match(line):+ flush()+ emit(_BULLET_RE.sub("", line, count=1))+ continue+ paragraph.append(stripped)+ flush()+ return out+++def upsert_page(+ conn: sqlite3.Connection, vault_root: Path, abs_path: Path, *, encoder: Any+) -> bool:+ """Encode one page and replace its rows. Returns False when it is skipped."""+ parsed = fts_index._parse_page_data(abs_path, vault_root)+ if parsed is None:+ return False+ rel_path, title, _frontmatter, body, mtime = parsed+ cut = passages(title, body)+ vectors = encoder.encode([encoded for _text, encoded in cut]) if cut else None+ conn.execute("DELETE FROM wiki_semantic_chunks WHERE path = ?", (rel_path,))+ if vectors is not None:+ conn.executemany(+ "INSERT INTO wiki_semantic_chunks (path, chunk, title, text, embedding) "+ "VALUES (?, ?, ?, ?, ?)",+ [+ (rel_path, index, title, text, vectors[index].tobytes())+ for index, (text, _encoded) in enumerate(cut)+ ],+ )+ conn.execute(+ "INSERT OR REPLACE INTO wiki_semantic_pages (path, mtime, model) VALUES (?, ?, ?)",+ (rel_path, mtime, MODEL_REVISION),+ )+ conn.commit()+ return True+++def page_key(vault_root: Path, abs_path: Path) -> str:+ """The vault-relative path a page is stored under."""+ return fts_index._relative_posix(vault_root, abs_path)+++def remove_page(conn: sqlite3.Connection, vault_root: Path, abs_path: Path) -> None:+ rel_path = page_key(vault_root, abs_path)+ conn.execute("DELETE FROM wiki_semantic_chunks WHERE path = ?", (rel_path,))+ conn.execute("DELETE FROM wiki_semantic_pages WHERE path = ?", (rel_path,))+ conn.commit()+++def plan_sync(conn: sqlite3.Connection, vault_root: Path) -> tuple[list[str], int, int]:+ """Compare the index with the vault and clear out what no longer belongs.++ Returns ``(stale, pages, removed)``: the vault-relative paths that are new+ or changed and still have to be encoded, the number of pages in the vault,+ and how many pages' rows were dropped. The rows of pages that are gone, or+ that belong to a vault that is no longer the active one, are deleted here+ and now, before anything is encoded: a search must never see passages of+ the previous vault next to those of the new one.+ """+ ensure_schema(conn)+ known = {+ path: (mtime, model)+ for path, mtime, model in conn.execute(+ "SELECT path, mtime, model FROM wiki_semantic_pages"+ )+ }+ current = fts_index.vault_page_mtimes(vault_root)+ gone = sorted(set(known) - set(current))+ for rel_path in gone:+ conn.execute("DELETE FROM wiki_semantic_chunks WHERE path = ?", (rel_path,))+ conn.execute("DELETE FROM wiki_semantic_pages WHERE path = ?", (rel_path,))+ conn.commit()+ stale = [+ rel_path+ for rel_path, mtime in current.items()+ if known.get(rel_path) != (str(mtime), MODEL_REVISION)+ ]+ return stale, len(current), len(gone)+++def sync_vault(+ conn: sqlite3.Connection,+ vault_root: Path,+ *,+ encoder: Any,+ progress: Callable[[int, int], None] | None = None,+) -> SyncResult:+ """Bring the index up to date with the vault on disk.++ Encodes the pages that are new or changed, drops the rows of pages that+ are gone, and leaves everything else untouched. A page that cannot be+ encoded is logged and counted, and the run goes on with the next one.+ ``progress`` receives stale pages handled so far and their total.+ """+ stale, pages, removed = plan_sync(conn, vault_root)+ encoded = failed = 0+ for done, rel_path in enumerate(stale, start=1):+ try:+ if upsert_page(conn, vault_root, vault_root / rel_path, encoder=encoder):+ encoded += 1+ except Exception as exc: # noqa: BLE001 - one bad page must not end the run+ conn.rollback()+ failed += 1+ log.warning("Semantic wiki index: %s could not be encoded: %s", rel_path, exc)+ if progress is not None:+ progress(done, len(stale))+ return SyncResult(pages=pages, encoded=encoded, removed=removed, failed=failed)+++def load_passages(+ conn: sqlite3.Connection, *, path: str | None = None+) -> tuple[Any, list[tuple[str, str, str]]]:+ """Stored vectors as one matrix, with ``(path, title, text)`` per row.++ Every page by default; only the passages of one page when *path* is given.+ """+ import numpy as np++ rows: list[tuple[str, str, str]] = []+ blobs: list[bytes] = []+ width = EMBEDDING_DIMENSIONS * 4+ query = "SELECT path, title, text, embedding FROM wiki_semantic_chunks"+ cursor = (+ conn.execute(f"{query} ORDER BY path, chunk")+ if path is None+ else conn.execute(f"{query} WHERE path = ? ORDER BY chunk", (path,))+ )+ for row_path, title, text, blob in cursor:+ if len(blob) != width:+ continue # written by another model size; the next sync replaces it+ rows.append((row_path, title, text))+ blobs.append(blob)+ matrix = np.frombuffer(b"".join(blobs), dtype=np.float32).reshape(+ len(rows), EMBEDDING_DIMENSIONS+ )+ return matrix, rows+++def counts(conn: sqlite3.Connection) -> tuple[int, int]:+ """``(pages, passages)`` currently in the index."""+ pages = conn.execute("SELECT COUNT(*) FROM wiki_semantic_pages").fetchone()[0]+ chunks = conn.execute("SELECT COUNT(*) FROM wiki_semantic_chunks").fetchone()[0]+ return int(pages), int(chunks)+++def _plain(text: str) -> str:+ """Markdown to the words a reader sees."""+ text = _WIKILINK_RE.sub(lambda m: m.group(2) or m.group(1).rsplit("/", 1)[-1], text)+ text = _MD_LINK_RE.sub(r"\1", text)+ text = _MARKUP_RE.sub("", text)+ return _SPACE_RE.sub(" ", text).strip()+++def _split_long(text: str) -> list[str]:+ """Cut *text* at sentence ends into pieces the model reads in full."""+ if len(text) <= _MAX_PASSAGE_CHARS:+ return [text]+ pieces: list[str] = []+ current = ""+ for sentence in _SENTENCE_END_RE.split(text):+ while len(sentence) > _MAX_PASSAGE_CHARS:+ if current:+ pieces.append(current)+ current = ""+ pieces.append(sentence[:_MAX_PASSAGE_CHARS])+ sentence = sentence[_MAX_PASSAGE_CHARS:]+ if current and len(current) + 1 + len(sentence) > _MAX_PASSAGE_CHARS:+ pieces.append(current)+ current = sentence+ else:+ current = f"{current} {sentence}".strip()+ if current:+ pieces.append(current)+ return pieces+++__all__ = [+ "SyncResult",+ "counts",+ "ensure_schema",+ "load_passages",+ "page_key",+ "passages",+ "plan_sync",+ "remove_page",+ "sync_vault",+ "upsert_page",+]diff --git a/jarvis/memory/wiki/semantic_model.py b/jarvis/memory/wiki/semantic_model.pynew file mode 100644index 0000000000..ed327e2e49--- /dev/null+++ b/jarvis/memory/wiki/semantic_model.py@@ -0,0 +1,359 @@+"""The local sentence encoder behind the wiki's semantic search.++One multilingual model, the same one the terminal search in the Agentic IDE+runs in the browser: 384-dimensional sentence vectors for about fifty+languages, quantized, 135 MB on disk. It is not part of the install. The user+switches semantic search on, the two files are fetched once from the pinned+revision, checked against their SHA-256, and from then on everything runs on+this machine; no page text ever leaves it.++Three things live here because they describe the same artefact:++* where the model sits on disk and whether it is complete (:func:`model_dir`,+ :func:`model_present`),+* how it gets there (:func:`download_model`),+* how text becomes vectors (:class:`SemanticEncoder`).++The encoder owns a native inference session. A native session must never be+entered by two callers at once, and a caller on the turn path must never queue+behind a slow one (AP-24): :meth:`SemanticEncoder.encode` therefore takes a+per-instance lock, the turn path asks without waiting, and+:meth:`SemanticEncoder.recover` drops a session that stopped answering so the+next call builds a fresh one.+"""+from __future__ import annotations++import hashlib+import importlib.util+import logging+import os+import threading+import time+from collections.abc import Callable, Sequence+from dataclasses import dataclass, field+from pathlib import Path+from typing import Any++from jarvis.memory.wiki.db_path import resolve_wiki_db_path++log = logging.getLogger(__name__)++#: Model identity. ``tests/unit/memory/wiki/test_semantic_model.py`` pins these+#: to the constants of the browser-side terminal search so the app never ends+#: up with two different search models.+MODEL_REPO = "Xenova/paraphrase-multilingual-MiniLM-L12-v2"+MODEL_REVISION = "2c4055b12046f11709e9df2c122e59ffbdc2f900"+EMBEDDING_DIMENSIONS = 384++#: The model reads at most this many tokens of one text.+MAX_TOKENS = 128++_FILE_URL = "https://huggingface.co/{repo}/resolve/{revision}/{path}"+_CHUNK_BYTES = 1 << 20++#: Texts encoded per inference call. Small on purpose: one call is the unit a+#: waiting query has to sit out, and a batch pads every text to its longest.+_BATCH_SIZE = 8++#: A lock held this long is not a slow batch any more, it is a session that+#: stopped answering. A batch of eight texts takes well under ten seconds on a+#: slow laptop core.+_WEDGE_SECONDS = 120.0++#: Pause between two batches of one call. A lock that is released and taken+#: again at once by the same thread can starve every other caller for a whole+#: index run; this gap is what lets a waiting query or page update in.+_YIELD_SECONDS = 0.002+++@dataclass(frozen=True, slots=True)+class ModelFile:+ """One file of the pinned model revision."""++ path: str+ size: int+ sha256: str+++MODEL_FILES: tuple[ModelFile, ...] = (+ ModelFile(+ "tokenizer.json",+ 17_082_913,+ "b60b6b43406a48bf3638526314f3d232d97058bc93472ff2de930d43686fa441",+ ),+ ModelFile(+ "onnx/model_quantized.onnx",+ 118_308_126,+ "66fc00f5f29afcaff34092e1bdd20008ca3918265a82fb9695a551e510cc4ebc",+ ),+)++DOWNLOAD_BYTES = sum(item.size for item in MODEL_FILES)+++def model_dir(data_dir: str | Path | None = None) -> Path:+ """Folder that holds the model, next to the wiki database."""+ return resolve_wiki_db_path(data_dir).parent / "models" / "wiki-semantic-search"+++def model_present(data_dir: str | Path | None = None) -> bool:+ """True when every model file is on disk with its full size.++ Size, not hash: this runs on status polls, and hashing 135 MB there would+ be the heavy work a status read must not do. The hash is checked once, at+ download time, before a file is moved into place.+ """+ root = model_dir(data_dir)+ try:+ return all((root / item.path).stat().st_size == item.size for item in MODEL_FILES)+ except OSError: # a missing file is the answer "not present", not a fault+ return False+++def runtime_available() -> bool:+ """True when this install can run the model at all.++ The inference runtime ships with the base install wherever a prebuilt+ package exists for the platform. Where none exists the switch says so+ instead of offering a download that could never be used.+ """+ try:+ return (+ importlib.util.find_spec("onnxruntime") is not None+ and importlib.util.find_spec("numpy") is not None+ )+ except Exception as exc: # noqa: BLE001 - a broken sys.path is "not available"+ log.debug("semantic search runtime probe failed: %s", exc)+ return False+++def download_model(+ data_dir: str | Path | None = None,+ *,+ progress: Callable[[int, int], None] | None = None,+) -> None:+ """Fetch the model files that are missing. Raises with a usable message.++ Each file is streamed to a ``.part`` sibling, hashed while it arrives and+ moved into place only when the hash matches, so an interrupted or tampered+ download can never be mistaken for the model. ``progress`` receives the+ bytes fetched so far and the total over all files.+ """+ import httpx++ root = model_dir(data_dir)+ done = 0+ for item in MODEL_FILES:+ target = root / item.path+ try:+ if target.stat().st_size == item.size:+ done += item.size+ continue+ except OSError: # not on disk yet, which is what this function is here to fix+ pass+ target.parent.mkdir(parents=True, exist_ok=True)+ # The process id keeps two running copies of the app from writing+ # into each other's half-finished file.+ partial = target.with_name(f"{target.name}.{os.getpid()}.part")+ digest = hashlib.sha256()+ received = 0+ url = _FILE_URL.format(repo=MODEL_REPO, revision=MODEL_REVISION, path=item.path)+ try:+ with httpx.stream("GET", url, follow_redirects=True, timeout=60.0) as response:+ response.raise_for_status()+ with partial.open("wb") as handle:+ for chunk in response.iter_bytes(_CHUNK_BYTES):+ received += len(chunk)+ if received > item.size:+ raise RuntimeError(+ f"{item.path} is larger than the pinned file. Try again."+ )+ handle.write(chunk)+ digest.update(chunk)+ done += len(chunk)+ if progress is not None:+ progress(done, DOWNLOAD_BYTES)+ if digest.hexdigest() != item.sha256:+ raise RuntimeError(+ f"{item.path} arrived damaged (checksum mismatch). Try again."+ )+ os.replace(partial, target)+ finally:+ partial.unlink(missing_ok=True)+++@dataclass(slots=True)+class _Gate:+ """The session's lock and the moment its current holder took it.++ One object, so that replacing a session that stopped answering replaces+ both at once: a thread still stuck in the old session keeps the old gate+ and can never clear the timestamp of whoever holds the new one.+ """++ lock: threading.Lock = field(default_factory=threading.Lock)+ held_since: float | None = None+++class SemanticEncoder:+ """Text to unit-length sentence vectors, on this machine's CPU."""++ def __init__(self, data_dir: str | Path | None = None) -> None:+ self._data_dir = data_dir+ self._gate = _Gate()+ self._session: Any = None+ self._tokenizer: Any = None+ self._input_names: frozenset[str] = frozenset()+ self._loader: threading.Thread | None = None+ self._closed = False++ @property+ def loaded(self) -> bool:+ return self._session is not None++ def warm_up(self) -> None:+ """Load the model on a background thread; returns at once."""+ if self._closed or self._session is not None:+ return+ if self._loader is not None and self._loader.is_alive():+ return+ self._loader = threading.Thread(+ target=self._load_quietly, name="wiki-semantic-load", daemon=True+ )+ self._loader.start()++ def encode(self, texts: Sequence[str], *, wait: bool = True) -> Any | None:+ """Vectors for *texts* as a ``(len(texts), 384)`` float32 array.++ ``wait=False`` is the turn path's contract: when the model is not+ loaded yet or another caller is inside the session, return ``None``+ right away. The caller then answers without semantic hits; a turn+ never waits for a model.+ """+ import numpy as np++ if not texts:+ return np.zeros((0, EMBEDDING_DIMENSIONS), dtype=np.float32)+ if not wait and self._session is None:+ self.warm_up()+ return None+ rows: list[Any] = []+ for start in range(0, len(texts), _BATCH_SIZE):+ if start:+ time.sleep(_YIELD_SECONDS)+ batch = self._encode_batch(texts[start : start + _BATCH_SIZE], wait=wait)+ if batch is None:+ return None+ rows.append(batch)+ return np.concatenate(rows, axis=0)++ def recover(self) -> None:+ """Drop a session that stopped answering, together with its lock.++ A thread stuck inside the old session keeps the old objects alive and+ can never block the fresh path; the next ``encode`` loads a new model+ under a new lock.+ """+ log.warning("Semantic search encoder stopped answering; rebuilding it on next use.")+ self._session = None+ self._tokenizer = None+ self._gate = _Gate()++ def close(self) -> None:+ """Retire this encoder and let go of the model. Never waits.++ It does not take the session lock: whoever is inside the session keeps+ its own references and finishes its batch, and a session that stopped+ answering must not be able to hold a shutdown up. A closed encoder+ stays closed; switching the search on again builds a new one.+ """+ self._closed = True+ self._session = None+ self._tokenizer = None++ def _encode_batch(self, texts: Sequence[str], *, wait: bool) -> Any | None:+ import numpy as np++ gate = self._gate+ if not gate.lock.acquire(blocking=wait):+ held_since = gate.held_since+ if held_since is not None and time.monotonic() - held_since > _WEDGE_SECONDS:+ self.recover()+ return None+ try:+ gate.held_since = time.monotonic()+ if self._closed:+ if wait:+ raise RuntimeError("semantic search was switched off")+ return None+ session, tokenizer = self._session, self._tokenizer+ if session is None or tokenizer is None:+ session, tokenizer = self._load()+ encoded = [tokenizer.encode(text, max_tokens=MAX_TOKENS) for text in texts]+ width = max(len(ids) for ids in encoded)+ input_ids = np.zeros((len(encoded), width), dtype=np.int64)+ mask = np.zeros((len(encoded), width), dtype=np.int64)+ for row, ids in enumerate(encoded):+ input_ids[row, : len(ids)] = ids+ mask[row, : len(ids)] = 1+ feeds = {"input_ids": input_ids, "attention_mask": mask}+ if "token_type_ids" in self._input_names:+ feeds["token_type_ids"] = np.zeros_like(input_ids)+ hidden = session.run(None, feeds)[0]+ weights = mask[:, :, None].astype(np.float32)+ pooled = (hidden * weights).sum(axis=1) / weights.sum(axis=1)+ norms = np.linalg.norm(pooled, axis=1, keepdims=True)+ return (pooled / np.maximum(norms, 1e-12)).astype(np.float32)+ finally:+ gate.held_since = None+ gate.lock.release()++ def _load_quietly(self) -> None:+ try:+ with self._gate.lock:+ if self._session is None and not self._closed:+ self._load()+ except Exception as exc: # noqa: BLE001 - the next encode retries and reports+ log.warning("Semantic search model could not be loaded: %s", exc)++ def _load(self) -> tuple[Any, Any]:+ """Build the session and tokenizer; the caller holds the gate."""+ import onnxruntime++ from jarvis.memory.wiki.semantic_tokenizer import UnigramTokenizer++ root = model_dir(self._data_dir)+ options = onnxruntime.SessionOptions()+ # Two threads at most: retrieval shares the machine with speech+ # recognition and must not take every core for a background index run.+ options.intra_op_num_threads = min(2, os.cpu_count() or 1)+ options.inter_op_num_threads = 1+ started = time.monotonic()+ tokenizer = UnigramTokenizer.from_file(root / "tokenizer.json")+ session = onnxruntime.InferenceSession(+ str(root / "onnx" / "model_quantized.onnx"),+ sess_options=options,+ providers=["CPUExecutionProvider"],+ )+ self._input_names = frozenset(item.name for item in session.get_inputs())+ if not self._closed:+ self._tokenizer = tokenizer+ self._session = session+ log.info("Semantic search model loaded in %.1fs", time.monotonic() - started)+ return session, tokenizer+++__all__ = [+ "DOWNLOAD_BYTES",+ "EMBEDDING_DIMENSIONS",+ "MAX_TOKENS",+ "MODEL_FILES",+ "MODEL_REPO",+ "MODEL_REVISION",+ "ModelFile",+ "SemanticEncoder",+ "download_model",+ "model_dir",+ "model_present",+ "runtime_available",+]diff --git a/jarvis/memory/wiki/semantic_search.py b/jarvis/memory/wiki/semantic_search.pynew file mode 100644index 0000000000..e64bae8fb2--- /dev/null+++ b/jarvis/memory/wiki/semantic_search.py@@ -0,0 +1,336 @@+"""``SemanticVaultSearch`` — find wiki pages by meaning, next to the word search.++``VaultSearch`` answers "which pages contain these words". This class answers+"which pages say something like this question", in whatever language either+side is written. It returns the same ``SearchHit`` records, so a caller can+show or merge the two result lists without knowing which engine found what.++The word search does not depend on this module in any way. Semantic search is+an optional second engine: off unless the user switched it on, silent when its+model is missing, busy or broken. Every public method degrades to "no semantic+hits" instead of raising, and a caller on the turn path never waits for it.++One instance is active per process (:func:`activate`, :func:`get_active`): the+turn injector, the recall tool, the wiki routes and the file watcher all reach+the same model and the same in-memory copy of the vectors.+"""+from __future__ import annotations++import logging+import sqlite3+import threading+from collections.abc import Callable+from pathlib import Path+from typing import Any++from jarvis.memory.wiki import semantic_index+from jarvis.memory.wiki.db_path import resolve_wiki_db_path+from jarvis.memory.wiki.search import SearchHit+from jarvis.memory.wiki.semantic_model import SemanticEncoder++log = logging.getLogger(__name__)++#: Cosine similarity below which two texts are unrelated for this model, even+#: when one is the other's nearest neighbour. The terminal search in the+#: Agentic IDE uses the same model and the same floor.+MIN_SIMILARITY = 0.29++_SNIPPET_CHARS = 200++#: Pages a deliberate lookup may gain from the semantic engine on top of the+#: word search's own hits.+_EXTRA_HITS = 3+++class SemanticVaultSearch:+ """Meaning-based search over one vault.++ Parameters+ ----------+ vault_root:+ Absolute path of the vault whose pages are indexed.+ db_path:+ The wiki database. Defaults to the shared ``data/jarvis.db``.+ encoder:+ Anything with ``encode(texts, wait=...)``, ``warm_up()`` and+ ``close()``. Tests pass a fake; production builds the real model.+ """++ def __init__(+ self,+ vault_root: Path,+ *,+ db_path: Path | None = None,+ data_dir: str | Path | None = None,+ encoder: Any = None,+ ) -> None:+ self._root = Path(vault_root)+ self._db_path = db_path or resolve_wiki_db_path(data_dir)+ self._encoder = encoder if encoder is not None else SemanticEncoder(data_dir)+ # One writer at a time: a full sync and a watcher update must not+ # interleave their deletes and inserts for the same page.+ self._write_lock = threading.Lock()+ self._passages: tuple[Any, list[tuple[str, str, str]]] | None = None++ @property+ def vault_root(self) -> Path:+ return self._root++ def search(+ self,+ query: str,+ *,+ k: int = 5,+ min_score: float = MIN_SIMILARITY,+ wait: bool = False,+ ) -> list[SearchHit]:+ """Up to *k* pages, best first, each with its best-matching passage.++ ``score`` is the cosine similarity of that passage, comparable across+ calls. ``wait=False`` (the default, and the turn path's setting)+ returns ``[]`` at once while the model is loading or busy.+ """+ if not query or not query.strip():+ return []+ try:+ loaded = self._passages+ if loaded is None:+ if not wait:+ # Reading every vector from disk is not turn-path work.+ return []+ loaded = self.refresh()+ matrix, rows = loaded+ if not rows:+ return []+ vector = self._encoder.encode([query], wait=wait)+ if vector is None:+ return []+ scores = matrix @ vector[0]+ except Exception as exc: # noqa: BLE001 - semantic search never breaks a caller+ log.warning("Semantic wiki search failed: %s", exc)+ return []++ best: dict[str, int] = {}+ for index in scores.argsort()[::-1]:+ score = float(scores[index])+ if score < min_score or len(best) >= k:+ break+ best.setdefault(rows[index][0], int(index))+ hits: list[SearchHit] = []+ for rel_path, index in best.items():+ _path, title, text = rows[index]+ hits.append(+ SearchHit(+ title=title or Path(rel_path).stem,+ path=self._root / rel_path,+ snippet=_clip(text),+ score=round(float(scores[index]), 4),+ preview=_clip(text),+ )+ )+ return hits++ def warm_up(self) -> None:+ """Load the model and the vectors. For a background thread at boot."""+ try:+ self._encoder.warm_up()+ self.refresh()+ except Exception as exc: # noqa: BLE001 - the next search retries+ log.debug("Semantic wiki search warm-up skipped: %s", exc)++ def sync(+ self, *, progress: Callable[[int, int], None] | None = None+ ) -> semantic_index.SyncResult:+ """Encode new and changed pages. Minutes on a first run: never on a turn.++ The write lock is taken per page, not for the run: a page the watcher+ saw change waits for one page at most, not for a whole first run. A+ page that cannot be encoded is logged and counted and the run goes on.+ ``progress`` may raise to end the run early; nothing is left half+ written, because every page is its own transaction.+ """+ encoded = failed = 0+ with self._connect() as conn:+ with self._write_lock:+ stale, pages, removed = semantic_index.plan_sync(conn, self._root)+ for done, rel_path in enumerate(stale, start=1):+ try:+ with self._write_lock:+ if semantic_index.upsert_page(+ conn, self._root, self._root / rel_path, encoder=self._encoder+ ):+ encoded += 1+ except Exception as exc: # noqa: BLE001 - one bad page must not end the run+ conn.rollback()+ failed += 1+ log.warning("Semantic wiki index: %s could not be encoded: %s", rel_path, exc)+ if progress is not None:+ progress(done, len(stale))+ self.refresh()+ return semantic_index.SyncResult(+ pages=pages, encoded=encoded, removed=removed, failed=failed+ )++ def index_page(self, abs_path: Path) -> None:+ """Re-encode one page after it changed on disk."""+ with self._write_lock, self._connect() as conn:+ semantic_index.ensure_schema(conn)+ semantic_index.upsert_page(conn, self._root, abs_path, encoder=self._encoder)+ self._reload_page(conn, abs_path)++ def remove_page(self, abs_path: Path) -> None:+ with self._write_lock, self._connect() as conn:+ semantic_index.ensure_schema(conn)+ semantic_index.remove_page(conn, self._root, abs_path)+ self._reload_page(conn, abs_path)++ def refresh(self) -> tuple[Any, list[tuple[str, str, str]]]:+ """Read every vector from the database into memory.++ Under the write lock, so a reload can never publish a snapshot that is+ older than a page update which finished while it was reading.+ """+ with self._write_lock, self._connect() as conn:+ semantic_index.ensure_schema(conn)+ loaded = semantic_index.load_passages(conn)+ self._passages = loaded+ return loaded++ def _reload_page(self, conn: sqlite3.Connection, abs_path: Path) -> None:+ """Swap one page's passages in the in-memory copy; the caller holds the lock.++ One saved file must not cost a reload of the whole vault's vectors.+ """+ loaded = self._passages+ if loaded is None:+ return # nothing in memory yet; the first reader loads everything+ import numpy as np++ matrix, rows = loaded+ rel_path = semantic_index.page_key(self._root, abs_path)+ keep = [index for index, row in enumerate(rows) if row[0] != rel_path]+ fresh_matrix, fresh_rows = semantic_index.load_passages(conn, path=rel_path)+ self._passages = (+ np.concatenate([matrix[keep], fresh_matrix], axis=0),+ [rows[index] for index in keep] + fresh_rows,+ )++ def counts(self) -> tuple[int, int]:+ """``(pages, passages)`` in the index; ``(0, 0)`` when unreadable."""+ try:+ with self._connect() as conn:+ semantic_index.ensure_schema(conn)+ return semantic_index.counts(conn)+ except Exception as exc: # noqa: BLE001 - a status read must not raise+ log.debug("Semantic wiki index count failed: %s", exc)+ return 0, 0++ def close(self) -> None:+ """Release the model and the in-memory vectors."""+ self._passages = None+ try:+ self._encoder.close()+ except Exception as exc: # noqa: BLE001 - nothing to salvage on shutdown+ log.debug("Semantic wiki encoder close failed: %s", exc)++ def _connect(self) -> _Connection:+ return _Connection(self._db_path)+++class _Connection:+ """A short-lived connection that is closed, not just committed, on exit."""++ def __init__(self, db_path: Path) -> None:+ self._db_path = db_path+ self._conn: sqlite3.Connection | None = None++ def __enter__(self) -> sqlite3.Connection:+ self._db_path.parent.mkdir(parents=True, exist_ok=True)+ self._conn = sqlite3.connect(str(self._db_path), timeout=5.0)+ return self._conn++ def __exit__(self, *_exc: object) -> None:+ if self._conn is not None:+ self._conn.close()+ self._conn = None+++def _clip(text: str) -> str:+ return text if len(text) <= _SNIPPET_CHARS else text[: _SNIPPET_CHARS - 1].rstrip() + "…"+++# ---------------------------------------------------------------------------+# The one active instance+# ---------------------------------------------------------------------------++_active: SemanticVaultSearch | None = None+_active_guard = threading.Lock()+++def get_active() -> SemanticVaultSearch | None:+ """The running semantic search, or ``None`` while it is switched off."""+ return _active+++def activate(+ vault_root: Path,+ *,+ db_path: Path | None = None,+ data_dir: str | Path | None = None,+ encoder: Any = None,+) -> SemanticVaultSearch:+ """Make semantic search available for *vault_root*; idempotent per vault."""+ global _active+ with _active_guard:+ current = _active+ if current is not None and current.vault_root == Path(vault_root):+ return current+ if current is not None:+ current.close()+ _active = SemanticVaultSearch(+ vault_root, db_path=db_path, data_dir=data_dir, encoder=encoder+ )+ return _active+++def deactivate() -> None:+ """Switch semantic search off and free the model's memory."""+ global _active+ with _active_guard:+ current, _active = _active, None+ if current is not None:+ current.close()+++def with_semantic_hits(+ hits: list[SearchHit],+ query: str,+ *,+ vault_root: Path,+ wait: bool = False,+) -> list[SearchHit]:+ """*hits* from the word search, plus pages found by meaning only.++ The word search's hits keep their order and are never dropped. Returns+ *hits* unchanged while semantic search is off or serves another vault.+ """+ active = get_active()+ if active is None or active.vault_root != Path(vault_root):+ return hits+ seen = {hit.path for hit in hits}+ extra = [+ hit+ for hit in active.search(query, k=_EXTRA_HITS, wait=wait)+ if hit.path not in seen+ ]+ return [*hits, *extra]+++__all__ = [+ "MIN_SIMILARITY",+ "SemanticVaultSearch",+ "activate",+ "deactivate",+ "get_active",+ "with_semantic_hits",+]diff --git a/jarvis/memory/wiki/semantic_setup.py b/jarvis/memory/wiki/semantic_setup.pynew file mode 100644index 0000000000..b9ddc1410f--- /dev/null+++ b/jarvis/memory/wiki/semantic_setup.py@@ -0,0 +1,276 @@+"""Switching the wiki's semantic search on and off, and saying how far it is.++Semantic search is opt-in. Switching it on is one click in the app and then+three steps the user only watches: fetch the model once, load it, encode the+vault. Each step can fail on its own (no network, a full disk, a platform+without an inference runtime), and each failure has to stay retryable, so the+work runs on a daemon thread and reports through a small state the UI polls,+the same way the local speech engines install.++The switch itself is ``[wiki_context] semantic_search``. It records what the+user asked for; :func:`status` reports what is actually true on this machine.+After a restart :func:`resume` picks the work up again from wherever it+stopped, including a download the previous run did not finish.++Every start and every stop raises a generation number. A worker carries the+number it was started with and checks it at each step, so switching the search+off ends a download or an encoding run within one chunk or one page, and a+worker that was overtaken never publishes a state or leaves a model loaded.+"""+from __future__ import annotations++import logging+import threading+from dataclasses import dataclass, field+from pathlib import Path+from typing import Any, Literal++from jarvis.memory.wiki import semantic_model, semantic_search++log = logging.getLogger(__name__)++SetupState = Literal["off", "downloading", "indexing", "ready", "error"]+++class _Cancelled(Exception):+ """Raised inside a worker whose run was switched off or replaced."""+++@dataclass+class _Run:+ """Progress of the one setup run, guarded by ``lock``."""++ state: SetupState = "off"+ message: str = ""+ progress: float | None = None+ lock: threading.Lock = field(default_factory=threading.Lock)+ thread: threading.Thread | None = None+ generation: int = 0+ #: The generation ``thread`` was started for. It differs from+ #: ``generation`` once a stop overtook that thread.+ thread_generation: int = -1+++_run = _Run()+++def enabled_in(config: Any) -> bool:+ """True when the user switched semantic search on."""+ return bool(getattr(getattr(config, "wiki_context", None), "semantic_search", False))+++def status(config: Any) -> dict[str, Any]:+ """What the switch shows: the wish, the facts, and the step in progress.++ ``enabled`` with state ``off`` is the short moment between the app coming+ up and :func:`resume` running; every lasting condition has its own state.+ """+ data_dir = _data_dir(config)+ active = semantic_search.get_active()+ pages, passages = active.counts() if active is not None else (0, 0)+ with _run.lock:+ state, message, progress = _run.state, _run.message, _run.progress+ if not enabled_in(config):+ state, message, progress = "off", "", None+ return {+ "enabled": enabled_in(config),+ "available": semantic_model.runtime_available(),+ "state": state,+ "message": message,+ "progress": progress,+ "model_present": semantic_model.model_present(data_dir),+ "download_bytes": semantic_model.DOWNLOAD_BYTES,+ "pages": pages,+ "passages": passages,+ }+++def start(config: Any) -> bool:+ """Begin (or join) the setup run. Returns False when it cannot run here.++ Idempotent: a call while a current run is in flight changes nothing, and a+ call when everything is already in place only brings the index up to date.+ A run that a stop has overtaken is not joined: a new one is started and+ waits for the old one to wind down first, so two runs never write the same+ file.+ """+ if not semantic_model.runtime_available():+ return _refuse(+ "Semantic search needs a component that is not available for "+ "this system. The word search keeps working as before."+ )+ if not getattr(getattr(config, "wiki_integration", None), "enabled", True):+ return _refuse("The wiki is switched off, so there is nothing to search.")+ vault_root = _vault_root(config)+ if vault_root is None:+ return _refuse("No wiki folder is set up yet, so there is nothing to search.")+ data_dir = _data_dir(config)+ with _run.lock:+ alive = _run.thread is not None and _run.thread.is_alive()+ if alive and _run.thread_generation == _run.generation:+ return True+ previous = _run.thread if alive else None+ _run.generation += 1+ _run.thread_generation = _run.generation+ _run.state = "indexing" if semantic_model.model_present(data_dir) else "downloading"+ _run.message = ""+ _run.progress = 0.0+ _run.thread = threading.Thread(+ target=_work,+ args=(_run.generation, previous, vault_root, data_dir),+ name="wiki-semantic-setup",+ daemon=True,+ )+ _run.thread.start()+ return True+++def resume(config: Any) -> None:+ """Pick semantic search up at start when the user had it switched on."""+ if enabled_in(config):+ start(config)+++def stop() -> None:+ """Switch semantic search off and free the model's memory. Never waits.++ A download or an encoding run in flight ends at its next chunk or page.+ The downloaded model and the stored vectors stay on disk, so switching it+ on again costs seconds, not a second download.+ """+ with _run.lock:+ _run.generation += 1+ _run.state = "off"+ _run.message = ""+ _run.progress = None+ semantic_search.deactivate()+++def _refuse(message: str) -> bool:+ with _run.lock:+ _run.generation += 1+ _run.state = "error"+ _run.message = message+ _run.progress = None+ semantic_search.deactivate()+ return False+++def _work(+ generation: int,+ previous: threading.Thread | None,+ vault_root: Path,+ data_dir: str | Path | None,+) -> None:+ """Download, load, encode; then publish a terminal state. Never raises."""+ if previous is not None:+ previous.join()++ def note(done: int, total: int) -> None:+ with _run.lock:+ if _run.generation != generation:+ raise _Cancelled+ _run.progress = min(done / total, 1.0) if total > 0 else None++ search: semantic_search.SemanticVaultSearch | None = None+ try:+ if not semantic_model.model_present(data_dir):+ semantic_model.download_model(data_dir, progress=note)+ if not _publish(generation, "indexing", progress=0.0):+ return+ search = semantic_search.activate(vault_root, data_dir=data_dir)+ result = search.sync(progress=note)+ if result.failed and not result.encoded and search.counts()[1] == 0:+ raise RuntimeError(f"none of the {result.failed} wiki pages could be read")+ except _Cancelled: # switched off or replaced on purpose: there is nothing to report+ _retire(search)+ return+ except Exception as exc: # noqa: BLE001 - surfaced as a retryable state, not a crash+ log.warning("Semantic wiki search setup failed: %s", exc, exc_info=True)+ # A search that could not be set up must not stay half alive, with the+ # watcher still feeding it pages while the switch says it failed.+ _retire(search)+ _publish(generation, "error", message=_explain(exc))+ return+ if not _publish(generation, "ready", progress=1.0):+ _retire(search)+ return+ log.info(+ "Semantic wiki search ready: %d page(s), %d newly encoded, %d removed, %d failed",+ result.pages,+ result.encoded,+ result.removed,+ result.failed,+ )+++def _retire(search: semantic_search.SemanticVaultSearch | None) -> None:+ """Take this run's instance down, unless a newer run already replaced it."""+ if search is not None and semantic_search.get_active() is search:+ semantic_search.deactivate()+++def _publish(+ generation: int,+ state: SetupState,+ *,+ message: str = "",+ progress: float | None = None,+) -> bool:+ """Record a step of run *generation*; False when it was overtaken."""+ with _run.lock:+ if _run.generation != generation:+ return False+ _run.state = state+ _run.message = message+ _run.progress = progress+ return True+++def _explain(exc: Exception) -> str:+ """One English sentence a person can act on.++ A fixed sentence per kind of failure, never the exception's own text: the+ state is served over the API, and an exception can carry local paths. The+ full error is in the log, written by the caller.+ """+ try:+ import httpx++ if isinstance(exc, httpx.HTTPStatusError):+ return (+ "The search model could not be downloaded: the server refused "+ "the request. Switch it on again later."+ )+ if isinstance(exc, httpx.TransportError):+ return (+ "The search model could not be downloaded. Check the internet "+ "connection and switch it on again."+ )+ except ImportError:+ log.debug("httpx is unavailable; reporting a general setup error")+ if isinstance(exc, OSError):+ return (+ "The search model could not be stored on this disk. Check the free "+ "space and switch it on again."+ )+ return "Semantic search could not be set up. The log has the details."+++def _data_dir(config: Any) -> str | None:+ return getattr(getattr(config, "memory", None), "data_dir", None)+++def _vault_root(config: Any) -> Path | None:+ from jarvis.memory.wiki.vault_root import resolve_vault_root++ raw = getattr(getattr(config, "wiki_integration", None), "vault_root", None)+ try:+ root = resolve_vault_root(raw).path+ except Exception as exc: # noqa: BLE001 - an unusable setting is "no vault"+ log.debug("Semantic wiki search: vault root could not be resolved: %s", exc)+ return None+ return root if root.is_dir() else None+++__all__ = ["enabled_in", "resume", "start", "status", "stop"]diff --git a/jarvis/memory/wiki/semantic_tokenizer.py b/jarvis/memory/wiki/semantic_tokenizer.pynew file mode 100644index 0000000000..54e65d1acc--- /dev/null+++ b/jarvis/memory/wiki/semantic_tokenizer.py@@ -0,0 +1,171 @@+"""Sentence tokenizer for the wiki's semantic search model, in plain Python.++The search model reads token ids, and the ids come from a SentencePiece+unigram vocabulary stored in the model's ``tokenizer.json``. Segmenting a word+against that vocabulary is a short dynamic program, so this module does it+directly instead of pulling a native tokenizer package into the install: the+feature then needs nothing beyond what the base install already carries.++The pipeline is the one the vocabulary file declares:++1. normalize the text (NFKC, control characters dropped, every kind of+ whitespace folded to a plain space);+2. split on whitespace and mark each word start with ``U+2581``;+3. pick, per word, the segmentation with the highest total piece score;+4. wrap the ids in the sentence start and end markers.++A character no vocabulary piece covers becomes the unknown id, and a run of+such characters collapses into a single unknown id.+"""+from __future__ import annotations++import json+import unicodedata+from pathlib import Path++#: The word-start marker SentencePiece vocabularies use.+_WORD_START = "▁"++#: How far below the worst vocabulary score an uncovered character is rated,+#: so a real piece always beats the unknown fallback.+_UNKNOWN_PENALTY = 10.0++#: Segmentations kept per tokenizer. Words repeat heavily inside a vault, and+#: one cached word costs a few dozen bytes.+_WORD_CACHE_LIMIT = 50_000++_BOS = "<s>"+_EOS = "</s>"+++def normalize(text: str) -> str:+ """Fold *text* to the form the vocabulary was trained on."""+ folded: list[str] = []+ for char in unicodedata.normalize("NFKC", text):+ if char.isspace():+ folded.append(" ")+ continue+ category = unicodedata.category(char)+ # Control and format characters (zero-width joiners, soft hyphens,+ # byte order marks) carry no meaning for retrieval.+ if category in ("Cc", "Cf"):+ continue+ folded.append(char)+ return "".join(folded)+++class UnigramTokenizer:+ """Turn text into the token ids of one unigram vocabulary."""++ def __init__(+ self,+ vocab: list[tuple[str, float]],+ *,+ unk_id: int,+ bos_id: int,+ eos_id: int,+ ) -> None:+ if not vocab:+ raise ValueError("the tokenizer vocabulary is empty")+ self._ids: dict[str, int] = {}+ self._scores: dict[str, float] = {}+ for index, (piece, score) in enumerate(vocab):+ # The first entry wins, exactly as a lookup by position would.+ if piece not in self._ids:+ self._ids[piece] = index+ self._scores[piece] = float(score)+ self._unk_id = unk_id+ self._bos_id = bos_id+ self._eos_id = eos_id+ self._max_piece_chars = max(len(piece) for piece in self._ids)+ self._unknown_score = min(self._scores.values()) - _UNKNOWN_PENALTY+ self._word_cache: dict[str, tuple[int, ...]] = {}++ @classmethod+ def from_file(cls, path: Path) -> UnigramTokenizer:+ """Load the vocabulary from a ``tokenizer.json`` file."""+ data = json.loads(Path(path).read_text(encoding="utf-8"))+ model = data.get("model") or {}+ if model.get("type") != "Unigram":+ raise ValueError("tokenizer.json does not hold a unigram vocabulary")+ vocab = [(str(piece), float(score)) for piece, score in model["vocab"]]+ ids = {piece: index for index, (piece, _score) in reversed(list(enumerate(vocab)))}+ if _BOS not in ids or _EOS not in ids:+ raise ValueError("tokenizer.json lacks the sentence start or end marker")+ return cls(+ vocab,+ unk_id=int(model.get("unk_id", 0)),+ bos_id=ids[_BOS],+ eos_id=ids[_EOS],+ )++ def encode(self, text: str, *, max_tokens: int = 128) -> list[int]:+ """Token ids for *text*, markers included, at most *max_tokens* long.++ A longer text keeps its first ``max_tokens - 1`` ids and the end+ marker, which is how the model was trained to read a cut sentence.+ """+ ids = [self._bos_id]+ budget = max(max_tokens - 2, 0)+ for word in normalize(text).split():+ if len(ids) - 1 >= budget:+ break+ ids.extend(self._encode_word(word))+ del ids[budget + 1 :]+ ids.append(self._eos_id)+ return ids++ def _encode_word(self, word: str) -> tuple[int, ...]:+ cached = self._word_cache.get(word)+ if cached is not None:+ return cached+ ids = self._segment(_WORD_START + word)+ if len(self._word_cache) < _WORD_CACHE_LIMIT:+ self._word_cache[word] = ids+ return ids++ def _segment(self, text: str) -> tuple[int, ...]:+ """Best-scoring split of one marked word into vocabulary pieces."""+ length = len(text)+ best_score = [float("-inf")] * (length + 1)+ best_start = [-1] * (length + 1)+ best_id = [self._unk_id] * (length + 1)+ best_score[0] = 0.0+ scores = self._scores+ for start in range(length):+ base = best_score[start]+ if base == float("-inf"):+ continue+ single_piece = False+ for end in range(start + 1, min(length, start + self._max_piece_chars) + 1):+ piece = text[start:end]+ score = scores.get(piece)+ if score is None:+ continue+ if end == start + 1:+ single_piece = True+ candidate = base + score+ if best_start[end] < 0 or candidate > best_score[end]:+ best_score[end] = candidate+ best_start[end] = start+ best_id[end] = self._ids[piece]+ if not single_piece:+ candidate = base + self._unknown_score+ end = start + 1+ if best_start[end] < 0 or candidate > best_score[end]:+ best_score[end] = candidate+ best_start[end] = start+ best_id[end] = self._unk_id+ ids: list[int] = []+ position = length+ while position > 0:+ token = best_id[position]+ # A run of uncovered characters is one unknown token, not many.+ if not (token == self._unk_id and ids and ids[-1] == self._unk_id):+ ids.append(token)+ position = best_start[position]+ ids.reverse()+ return tuple(ids)+++__all__ = ["UnigramTokenizer", "normalize"]diff --git a/jarvis/memory/wiki/watcher.py b/jarvis/memory/wiki/watcher.pyindex fb047ff6c8..4324b6cbaf 100644--- a/jarvis/memory/wiki/watcher.py+++ b/jarvis/memory/wiki/watcher.py@@ -418,6 +418,7 @@ class WikiWatcher:operation=operation,path=rel_path,)+ self._maintain_semantic_index(abs_path, operation, rel_path)except Exception as exc: # noqa: BLE001log.warning("wiki_watcher_index_failed",@@ -435,6 +436,31 @@ class WikiWatcher:log.debug("wiki_watcher: health recording failed", exc_info=True)+ def _maintain_semantic_index(self, abs_path: Path, operation: str, rel_path: str) -> None:+ """Keep the semantic index in step with the same change, when it is on.++ Outside the word index's lock and its error handling on purpose: the+ word index is already correct at this point, and encoding a page+ takes long enough that it must not hold other page timers up.+ """+ try:+ from jarvis.memory.wiki.semantic_search import get_active++ active = get_active()+ if active is None or active.vault_root != self.vault_root:+ return+ if operation == "remove":+ active.remove_page(abs_path)+ else:+ active.index_page(abs_path)+ except Exception: # noqa: BLE001 - the next start brings the index up to date+ log.warning(+ "wiki_watcher_semantic_index_failed",+ exc_info=True,+ extra={"path": rel_path},+ )++class _WatchdogBridge(FileSystemEventHandler): # type: ignore[misc]"""Adapter from watchdog's per-event callbacks to ``WikiWatcher``."""diff --git a/jarvis/plugins/tool/wiki_recall.py b/jarvis/plugins/tool/wiki_recall.pyindex cb4acb2453..90b9fe6ef1 100644--- a/jarvis/plugins/tool/wiki_recall.py+++ b/jarvis/plugins/tool/wiki_recall.py@@ -31,6 +31,7 @@ Vault-root resolution (§6 AGENT-B, spec A7):"""from __future__ import annotations+import asyncioimport loggingfrom pathlib import Pathfrom typing import TYPE_CHECKING, Any@@ -119,6 +120,10 @@ class WikiRecallTool:)hits = self._search.search(query, k=k)+ # With semantic search switched on, add pages that mean the same but+ # share no word with the query. Never waits for the model, and runs+ # off the event loop: encoding the query is CPU work.+ hits = await asyncio.to_thread(_with_semantic_hits, hits, query, vault_root)log.info("wiki-recall: %d hit(s) for query (k=%d)", len(hits), k)@@ -143,6 +148,16 @@ class WikiRecallTool:return ToolResult(success=True, output="\n".join(lines))+def _with_semantic_hits(hits: list[Any], query: str, vault_root: Path) -> list[Any]:+ try:+ from jarvis.memory.wiki.semantic_search import with_semantic_hits++ return with_semantic_hits(hits, query, vault_root=vault_root)+ except Exception as exc: # noqa: BLE001 - the word search result stands on its own+ log.debug("wiki-recall: semantic search skipped: %s", exc)+ return hits++def _build_search_instance() -> VaultSearch:"""Build a ``VaultSearch`` with the configured vault root.diff --git a/jarvis/ui/web/frontend/src/components/wiki/WikiSearch.test.tsx b/jarvis/ui/web/frontend/src/components/wiki/WikiSearch.test.tsxindex eb8a237253..6ea37febbd 100644--- a/jarvis/ui/web/frontend/src/components/wiki/WikiSearch.test.tsx+++ b/jarvis/ui/web/frontend/src/components/wiki/WikiSearch.test.tsx@@ -215,6 +215,65 @@ describe("WikiSearch", () => {});});+ it("labels a hit that semantic search found, and only that one", async () => {+ // Such a hit shares no word with the query, so nothing in its snippet is+ // highlighted; the label is what tells the reader why it is in the list.+ vi.stubGlobal(+ "fetch",+ vi.fn(async () =>+ new Response(+ JSON.stringify({+ ok: true,+ query: "sister birthday",+ hits: [+ {+ slug: "party",+ title: "Party",+ path: "projects/party.md",+ snippet: "The birthday party is in May.",+ score: 0.8,+ by_meaning: false,+ },+ {+ slug: "anna",+ title: "Anna",+ path: "entities/anna.md",+ snippet: "Meine Schwester, Geburtstag am 4. Mai.",+ score: 0.7,+ by_meaning: true,+ },+ ],+ }),+ { status: 200, headers: { "content-type": "application/json" } },+ ),+ ),+ );++ const client = makeClient();+ render(+ <Wrapper client={client}>+ <WikiSearch onResultClick={() => {}} />+ </Wrapper>,+ );+ await act(async () => {+ fireEvent.keyDown(window, { key: "k", ctrlKey: true });+ });+ const input = await screen.findByTestId("wiki-search-input");+ await act(async () => {+ fireEvent.change(input, { target: { value: "sister birthday" } });+ });+ await act(async () => {+ vi.advanceTimersByTime(250);+ });++ await waitFor(() => expect(screen.getAllByTestId("wiki-search-hit")).toHaveLength(2));+ const labels = screen.getAllByTestId("wiki-search-by-meaning");+ expect(labels).toHaveLength(1);+ expect(labels[0].closest('[data-testid="wiki-search-hit"]')?.getAttribute("data-slug")).toBe(+ "anna",+ );+ });+it("marks every occurrence of the query term in a snippet", async () => {// Regression: highlighting used `pattern.test(part)` with a /g regex,// whose `lastIndex` carried over between calls — so it alternateddiff --git a/jarvis/ui/web/frontend/src/components/wiki/WikiSearch.tsx b/jarvis/ui/web/frontend/src/components/wiki/WikiSearch.tsxindex 1e20bc390f..176c510b40 100644--- a/jarvis/ui/web/frontend/src/components/wiki/WikiSearch.tsx+++ b/jarvis/ui/web/frontend/src/components/wiki/WikiSearch.tsx@@ -32,6 +32,8 @@ interface SearchHit {path: string;snippet: string;score: number;+ /** Found by semantic search, so the snippet has no query word to highlight. */+ by_meaning?: boolean;}interface SearchResponse {@@ -365,6 +367,14 @@ export const WikiSearch = forwardRef<WikiSearchHandle, WikiSearchProps>(function<span className="flex items-center gap-2.5"><KindGlyph group={groupOfPath(hit.path)} className="h-2.5 w-2.5 text-foreground-faint" /><span className="truncate text-foreground">{cleanTitle(hit.title, hit.slug)}</span>+ {hit.by_meaning ? (+ <span+ data-testid="wiki-search-by-meaning"+ className="shrink-0 rounded-sm border border-border px-1.5 text-xs text-muted-foreground"+ >+ {t("wiki_search.by_meaning")}+ </span>+ ) : null}<span className="ml-auto truncate text-sm text-foreground-faint">{hit.path}</span></span><span className="line-clamp-2 pl-5 text-sm text-muted-foreground">diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.jsonindex b56b0b8055..5a7697c384 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json@@ -2532,6 +2532,15 @@"wiki_links": "{0} Verweise","wiki_empty_body": "Noch keine Seite. Das Wiki legt eine an, sobald eure Gespräche etwas hergeben.","wiki_needs_name": "Trag deinen Namen ein, dann kann das Wiki eine Seite über dich anlegen.",+ "semantic_title": "Nach Bedeutung suchen",+ "semantic_off": "Findet Notizen, die dasselbe meinen wie deine Frage, auch mit anderen Worten oder in einer anderen Sprache. Beim Einschalten wird einmalig ein Suchmodell mit {0} MB geladen; es läuft nur auf diesem Computer.",+ "semantic_starting": "Startet…",+ "semantic_downloading": "Suchmodell wird geladen… {0} %",+ "semantic_indexing": "Deine Wiki-Seiten werden gelesen… {0} %",+ "semantic_ready": "An. {0} Seiten lassen sich nach Bedeutung finden.",+ "semantic_unavailable": "Auf diesem System nicht verfügbar. Die Wortsuche funktioniert wie bisher.",+ "semantic_failed": "Die Einrichtung ist fehlgeschlagen. Schalte es aus und wieder ein, um es erneut zu versuchen.",+ "semantic_save_failed": "Die Einstellung konnte nicht gespeichert werden.","file_title": "Profildatei","file_hint": "USER.md, die Datei hinter dieser Seite","file_hint_dated": "USER.md · geändert am {0}",@@ -4051,7 +4060,8 @@"unavailable": "Suche gerade nicht verfügbar.","no_hits_prefix": "Keine Treffer für ","no_hits_suffix": ". Versuche andere Stichworte oder schau in den Graph.",- "hits_heading": "Treffer"+ "hits_heading": "Treffer",+ "by_meaning": "Nach Bedeutung"},"wiki_graph": {"empty_prefix": "Dein Memory-Graph ist noch leer. Sobald ",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.jsonindex 243e4f3707..8fc84c95f4 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json@@ -2532,6 +2532,15 @@"wiki_links": "{0} links","wiki_empty_body": "No page yet. The wiki starts one once your conversations give it something to record.","wiki_needs_name": "Add your name and the wiki can start a page about you.",+ "semantic_title": "Search by meaning",+ "semantic_off": "Finds notes that mean the same as your question, in other words or another language. Switching it on downloads a {0} MB search model once; it runs only on this computer.",+ "semantic_starting": "Starting…",+ "semantic_downloading": "Downloading the search model… {0}%",+ "semantic_indexing": "Reading your wiki pages… {0}%",+ "semantic_ready": "On. {0} pages can be found by meaning.",+ "semantic_unavailable": "Not available on this system. The word search works as before.",+ "semantic_failed": "It could not be set up. Switch it off and on again to retry.",+ "semantic_save_failed": "The setting could not be saved.","file_title": "Profile file","file_hint": "USER.md, the file behind this page","file_hint_dated": "USER.md · changed {0}",@@ -4051,7 +4060,8 @@"unavailable": "Search is currently unavailable.","no_hits_prefix": "No matches for ","no_hits_suffix": ". Try other keywords or look in the graph.",- "hits_heading": "Matches"+ "hits_heading": "Matches",+ "by_meaning": "By meaning"},"wiki_graph": {"empty_prefix": "Your memory graph is still empty. As soon as ",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.jsonindex 056020a4d1..d41c004ff0 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json@@ -2532,6 +2532,15 @@"wiki_links": "{0} enlaces","wiki_empty_body": "Aún no hay página. La wiki crea una cuando vuestras conversaciones aportan algo.","wiki_needs_name": "Añade tu nombre y la wiki podrá crear una página sobre ti.",+ "semantic_title": "Buscar por significado",+ "semantic_off": "Encuentra notas que significan lo mismo que tu pregunta, con otras palabras o en otro idioma. Al activarlo se descarga una sola vez un modelo de búsqueda de {0} MB; funciona solo en este ordenador.",+ "semantic_starting": "Iniciando…",+ "semantic_downloading": "Descargando el modelo de búsqueda… {0} %",+ "semantic_indexing": "Leyendo tus páginas de la wiki… {0} %",+ "semantic_ready": "Activado. {0} páginas se pueden encontrar por significado.",+ "semantic_unavailable": "No disponible en este sistema. La búsqueda por palabras funciona como antes.",+ "semantic_failed": "No se pudo configurar. Desactívalo y vuelve a activarlo para reintentarlo.",+ "semantic_save_failed": "No se pudo guardar el ajuste.","file_title": "Archivo de perfil","file_hint": "USER.md, el archivo detrás de esta página","file_hint_dated": "USER.md · cambiado el {0}",@@ -4051,7 +4060,8 @@"unavailable": "La búsqueda no está disponible en este momento.","no_hits_prefix": "Sin coincidencias para ","no_hits_suffix": ". Prueba otras palabras clave o consulta el grafo.",- "hits_heading": "Coincidencias"+ "hits_heading": "Coincidencias",+ "by_meaning": "Por significado"},"wiki_graph": {"empty_prefix": "Tu grafo de memoria aún está vacío. En cuanto ",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/pt.json b/jarvis/ui/web/frontend/src/i18n/locales/pt.jsonindex 6dea725898..532497eb10 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/pt.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/pt.json@@ -2532,6 +2532,15 @@"wiki_links": "{0} ligações","wiki_empty_body": "Ainda sem página. A wiki cria uma quando as tuas conversas lhe derem algo para registar.","wiki_needs_name": "Adiciona o teu nome e a wiki pode criar uma página sobre ti.",+ "semantic_title": "Pesquisar por significado",+ "semantic_off": "Encontra notas que significam o mesmo que a tua pergunta, por outras palavras ou noutra língua. Ao ativar, é transferido uma única vez um modelo de pesquisa de {0} MB; funciona apenas neste computador.",+ "semantic_starting": "A iniciar…",+ "semantic_downloading": "A transferir o modelo de pesquisa… {0}%",+ "semantic_indexing": "A ler as tuas páginas da wiki… {0}%",+ "semantic_ready": "Ativado. {0} páginas podem ser encontradas por significado.",+ "semantic_unavailable": "Não disponível neste sistema. A pesquisa por palavras funciona como antes.",+ "semantic_failed": "Não foi possível configurar. Desativa e volta a ativar para tentar de novo.",+ "semantic_save_failed": "Não foi possível guardar a definição.","file_title": "Ficheiro de perfil","file_hint": "USER.md, o ficheiro por trás desta página","file_hint_dated": "USER.md · alterado {0}",@@ -4051,7 +4060,8 @@"unavailable": "A pesquisa não está disponível de momento.","no_hits_prefix": "Sem resultados para ","no_hits_suffix": ". Experimenta outras palavras-chave ou procura no grafo.",- "hits_heading": "Resultados"+ "hits_heading": "Resultados",+ "by_meaning": "Por significado"},"wiki_graph": {"empty_prefix": "O teu grafo de memória ainda está vazio. Assim que o ",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/zh.json b/jarvis/ui/web/frontend/src/i18n/locales/zh.jsonindex 558892c602..2d396c6ea0 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/zh.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/zh.json@@ -2532,6 +2532,15 @@"wiki_links": "{0} 个链接","wiki_empty_body": "还没有页面。等你们的对话中有值得记录的内容,知识库就会创建一个页面。","wiki_needs_name": "添加你的名字后,知识库就可以为你创建页面。",+ "semantic_title": "按含义搜索",+ "semantic_off": "找到与你的问题意思相同的笔记,即使用词不同或语言不同。开启时会一次性下载一个 {0} MB 的搜索模型;它只在这台电脑上运行。",+ "semantic_starting": "正在启动…",+ "semantic_downloading": "正在下载搜索模型… {0}%",+ "semantic_indexing": "正在读取你的知识库页面… {0}%",+ "semantic_ready": "已开启。{0} 个页面可以按含义找到。",+ "semantic_unavailable": "此系统不支持。关键词搜索照常可用。",+ "semantic_failed": "设置失败。请关闭后重新开启以重试。",+ "semantic_save_failed": "无法保存该设置。","file_title": "个人资料文件","file_hint": "USER.md,此页面背后的文件","file_hint_dated": "USER.md · 修改于 {0}",@@ -4051,7 +4060,8 @@"unavailable": "搜索暂时不可用。","no_hits_prefix": "没有找到匹配 ","no_hits_suffix": " 的结果。试试其他关键词,或在图谱中查找。",- "hits_heading": "匹配结果"+ "hits_heading": "匹配结果",+ "by_meaning": "按含义"},"wiki_graph": {"empty_prefix": "你的记忆图谱还是空的。一旦 ",diff --git a/jarvis/ui/web/frontend/src/lib/wikiApi.ts b/jarvis/ui/web/frontend/src/lib/wikiApi.tsindex 7570e579f1..5f87b87f0f 100644--- a/jarvis/ui/web/frontend/src/lib/wikiApi.ts+++ b/jarvis/ui/web/frontend/src/lib/wikiApi.ts@@ -94,6 +94,8 @@ export interface WikiSearchHit {path: string;snippet: string;score: number;+ /** Found by semantic search: the page means the same but shares no word. */+ by_meaning?: boolean;}export interface WikiSearchResponse {@@ -217,6 +219,48 @@ export async function fetchWikiHealth(): Promise<WikiHealthSnapshot | null> {}}+export type WikiSemanticSearchState = "off" | "downloading" | "indexing" | "ready" | "error";++/** `GET/PUT /api/wiki/semantic-search`: the switch, the facts, the step in progress. */+export interface WikiSemanticSearchStatus {+ enabled: boolean;+ /** False where this system cannot run the search model at all. */+ available: boolean;+ state: WikiSemanticSearchState;+ message: string;+ /** 0..1 within the current step, or null when there is nothing to measure. */+ progress: number | null;+ model_present: boolean;+ download_bytes: number;+ pages: number;+ passages: number;+}++/**+ * State of semantic search. `null` means the backend has no such setting (an+ * older one answers 404), and then there is simply no row. Every other failure+ * throws, so a poll that fails once keeps the last state on screen instead of+ * making the row vanish in the middle of a download.+ */+export async function fetchWikiSemanticSearch(): Promise<WikiSemanticSearchStatus | null> {+ const res = await fetch("/api/wiki/semantic-search");+ if (res.status === 404) return null;+ if (!res.ok) throw new Error(`HTTP ${res.status} ${res.statusText}`);+ return (await res.json()) as WikiSemanticSearchStatus;+}++export async function setWikiSemanticSearch(enabled: boolean): Promise<WikiSemanticSearchStatus> {+ const res = await fetch("/api/wiki/semantic-search", {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ enabled }),+ });+ if (!res.ok) {+ throw new Error(`HTTP ${res.status} ${res.statusText}`);+ }+ return (await res.json()) as WikiSemanticSearchStatus;+}+export async function rebuildWikiIndex(): Promise<WikiReindexResponse> {const res = await fetch("/api/wiki/reindex", { method: "POST" });if (!res.ok) {diff --git a/jarvis/ui/web/frontend/src/views/profile/MemorySection.tsx b/jarvis/ui/web/frontend/src/views/profile/MemorySection.tsxindex 12b6baf4c8..a8935a5805 100644--- a/jarvis/ui/web/frontend/src/views/profile/MemorySection.tsx+++ b/jarvis/ui/web/frontend/src/views/profile/MemorySection.tsx@@ -2,10 +2,11 @@* Memory and privacy — where the rest of what the assistant knows lives, and* what it will never keep.*- * Four rows, each pointing at a real source:+ * Five rows, each pointing at a real source:* - your standing rules ({name}.md), edited in their own section;* - the wiki's long-form page about you, when the vault has one (the slug* comes from your name, so a nameless profile asks for nothing);+ * - the switch for searching the wiki by meaning (`SemanticSearchRow`);* - the profile file itself, USER.md, which opens in place;* - the `## Do Not Record` categories, quoted from that file rather than* restated in code, so the page can never promise more than the file says.@@ -20,6 +21,7 @@ import { useI18nStore, useT } from "@/i18n";import { localeForUiLanguage } from "@/components/runs/format";import { useEventStore } from "@/store/events";import { ProfileGroup, SettingRow } from "@/views/profile/ProfileGroup";+import { SemanticSearchRow } from "@/views/profile/SemanticSearchRow";import { parseDoNotRecord, shortenCategory } from "@/views/profile/provenance";interface WikiPage {@@ -179,6 +181,8 @@ export function MemorySection({}/>+ <SemanticSearchRow />+<SettingRowtestId="source-row"label={<RowLabel icon={<FileText />}>{t("profile_view.file_title")}</RowLabel>}diff --git a/jarvis/ui/web/frontend/src/views/profile/SemanticSearchRow.test.tsx b/jarvis/ui/web/frontend/src/views/profile/SemanticSearchRow.test.tsxnew file mode 100644index 0000000000..6482b12493--- /dev/null+++ b/jarvis/ui/web/frontend/src/views/profile/SemanticSearchRow.test.tsx@@ -0,0 +1,164 @@+/**+ * The semantic search switch: it shows what the server holds, says which step+ * is running, and never pretends a change that was not saved.+ */+import { afterEach, describe, expect, it, vi } from "vitest";+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";++import type { WikiSemanticSearchStatus } from "@/lib/wikiApi";+import { SemanticSearchRow } from "@/views/profile/SemanticSearchRow";++afterEach(() => {+ cleanup();+ vi.restoreAllMocks();+});++const OFF: WikiSemanticSearchStatus = {+ enabled: false,+ available: true,+ state: "off",+ message: "",+ progress: null,+ model_present: false,+ download_bytes: 135_391_039,+ pages: 0,+ passages: 0,+};++interface Reply {+ status?: number;+ body?: unknown;+}++function installBackend(get: Reply, put: Reply = {}) {+ const calls: { method: string; body: unknown }[] = [];+ const fetchMock = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {+ expect(String(input)).toBe("/api/wiki/semantic-search");+ const method = init?.method ?? "GET";+ calls.push({ method, body: init?.body ? JSON.parse(String(init.body)) : null });+ const { status = 200, body = null } = method === "PUT" ? put : get;+ return {+ ok: status >= 200 && status < 300,+ status,+ statusText: status === 200 ? "OK" : "Error",+ json: async () => body,+ } as Response;+ });+ (globalThis as unknown as { fetch: typeof fetch }).fetch = fetchMock as unknown as typeof fetch;+ return calls;+}++function renderRow() {+ const client = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 0 } } });+ return render(+ <QueryClientProvider client={client}>+ <SemanticSearchRow />+ </QueryClientProvider>,+ );+}++describe("SemanticSearchRow", () => {+ it("is absent when the backend has no such setting", async () => {+ const calls = installBackend({ status: 404 });+ const { container } = renderRow();+ await waitFor(() => expect(calls.length).toBe(1));+ expect(container.querySelector('[data-testid="semantic-search-row"]')).toBeNull();+ });++ it("is off at first and says what switching it on costs", async () => {+ installBackend({ body: OFF });+ renderRow();+ const status = await screen.findByTestId("semantic-search-status");+ expect(status.textContent).toContain("135 MB");+ expect(status.textContent).toContain("only on this computer");+ expect(screen.getByTestId("semantic-search-switch").getAttribute("aria-checked")).toBe("false");+ });++ it("switches on through the server and shows the download", async () => {+ const downloading = { ...OFF, enabled: true, state: "downloading", progress: 0.4 };+ const calls = installBackend({ body: OFF }, { body: downloading });+ renderRow();+ fireEvent.click(await screen.findByTestId("semantic-search-switch"));++ await waitFor(() =>+ expect(screen.getByTestId("semantic-search-status").textContent).toContain("40%"),+ );+ expect(calls.find((call) => call.method === "PUT")?.body).toEqual({ enabled: true });+ expect(screen.getByTestId("semantic-search-switch").getAttribute("aria-checked")).toBe("true");+ });++ it("reports how many pages are covered once it is ready", async () => {+ installBackend({ body: { ...OFF, enabled: true, state: "ready", progress: 1, pages: 70 } });+ renderRow();+ const status = await screen.findByTestId("semantic-search-status");+ expect(status.textContent).toContain("70 pages");+ });++ it("names the encoding step while the wiki is being read", async () => {+ installBackend({ body: { ...OFF, enabled: true, state: "indexing", progress: 0.25 } });+ renderRow();+ const status = await screen.findByTestId("semantic-search-status");+ expect(status.textContent).toContain("Reading your wiki pages");+ expect(status.textContent).toContain("25%");+ });++ it("cannot be switched on where the system cannot run it", async () => {+ installBackend({ body: { ...OFF, available: false } });+ renderRow();+ const status = await screen.findByTestId("semantic-search-status");+ expect(status.textContent).toContain("Not available on this system");+ expect(screen.getByTestId("semantic-search-switch").hasAttribute("disabled")).toBe(true);+ });++ it("offers a retry after a failed setup", async () => {+ installBackend({ body: { ...OFF, enabled: true, state: "error", message: "boom" } });+ renderRow();+ const status = await screen.findByTestId("semantic-search-status");+ expect(status.textContent).toContain("could not be set up");+ expect(screen.getByTestId("semantic-search-switch").hasAttribute("disabled")).toBe(false);+ });++ it("stays off and says so when the change could not be saved", async () => {+ installBackend({ body: OFF }, { status: 500 });+ renderRow();+ fireEvent.click(await screen.findByTestId("semantic-search-switch"));++ const alert = await screen.findByRole("alert");+ expect(alert.textContent).toContain("could not be saved");+ expect(screen.getByTestId("semantic-search-switch").getAttribute("aria-checked")).toBe("false");+ });++ it("keeps the last state on screen when one poll fails", async () => {+ const downloading = { ...OFF, enabled: true, state: "downloading", progress: 0.4 };+ let requests = 0;+ const fetchMock = vi.fn(async () => {+ requests += 1;+ if (requests > 1) throw new Error("network blip");+ return { ok: true, status: 200, statusText: "OK", json: async () => downloading } as Response;+ });+ (globalThis as unknown as { fetch: typeof fetch }).fetch = fetchMock as unknown as typeof fetch;+ renderRow();+ await screen.findByTestId("semantic-search-status");++ await waitFor(() => expect(requests).toBeGreaterThan(1), { timeout: 3000 });+ expect(screen.getByTestId("semantic-search-status").textContent).toContain("40%");+ });++ it("keeps asking while it is switched on but not picked up yet", async () => {+ const pending = { ...OFF, enabled: true, state: "off" };+ const ready = { ...OFF, enabled: true, state: "ready", progress: 1, pages: 3 };+ let requests = 0;+ const fetchMock = vi.fn(async () => {+ requests += 1;+ const body = requests > 1 ? ready : pending;+ return { ok: true, status: 200, statusText: "OK", json: async () => body } as Response;+ });+ (globalThis as unknown as { fetch: typeof fetch }).fetch = fetchMock as unknown as typeof fetch;+ renderRow();+ const status = await screen.findByTestId("semantic-search-status");+ expect(status.textContent).toContain("Starting");++ await waitFor(() => expect(status.textContent).toContain("3 pages"), { timeout: 3000 });+ });+});diff --git a/jarvis/ui/web/frontend/src/views/profile/SemanticSearchRow.tsx b/jarvis/ui/web/frontend/src/views/profile/SemanticSearchRow.tsxnew file mode 100644index 0000000000..8999a4390d--- /dev/null+++ b/jarvis/ui/web/frontend/src/views/profile/SemanticSearchRow.tsx@@ -0,0 +1,122 @@+/**+ * The switch for the wiki's semantic search.+ *+ * Off by default. Switching it on downloads a search model once and then+ * reads the wiki pages on this computer; the row says which of those steps is+ * running and how far it is, and polls only while one is. The switch shows+ * what the server holds: it flips once the server confirmed the change and+ * springs back with a sentence when the save failed.+ *+ * A backend without the route answers nothing, and then there is no row.+ */+import { useState } from "react";+import { useQuery, useQueryClient } from "@tanstack/react-query";+import { Loader2, Sparkles } from "lucide-react";++import { Switch } from "@/components/ui/switch";+import { useT } from "@/i18n";+import {+ fetchWikiSemanticSearch,+ setWikiSemanticSearch,+ type WikiSemanticSearchStatus,+} from "@/lib/wikiApi";+import { SettingRow } from "@/views/profile/ProfileGroup";++export const SEMANTIC_SEARCH_KEY = ["wiki", "semantic-search"] as const;++const POLL_MS = 1000;++function working(status: WikiSemanticSearchStatus | null | undefined): boolean {+ return status?.state === "downloading" || status?.state === "indexing";+}++/** Switched on, but the app has not picked the work up yet (the moment after a start). */+function pending(status: WikiSemanticSearchStatus | null | undefined): boolean {+ return !!status?.enabled && status.state === "off";+}++function percent(progress: number | null): string {+ return String(Math.round(Math.min(Math.max(progress ?? 0, 0), 1) * 100));+}++export function SemanticSearchRow() {+ const t = useT();+ const client = useQueryClient();+ const [saving, setSaving] = useState(false);+ const [saveFailed, setSaveFailed] = useState(false);+ const query = useQuery({+ queryKey: SEMANTIC_SEARCH_KEY,+ queryFn: fetchWikiSemanticSearch,+ retry: false,+ // Keeps polling through a failed request: react-query holds the last good+ // state, and that state still says a step is running.+ refetchInterval: ({ state }) => (working(state.data) || pending(state.data) ? POLL_MS : false),+ });+ const status = query.data ?? null;+ if (status === null) return null;++ const megabytes = String(Math.round(status.download_bytes / 1_000_000));+ let hint: string;+ if (!status.available) hint = t("profile_view.semantic_unavailable");+ else if (!status.enabled) hint = t("profile_view.semantic_off").replace("{0}", megabytes);+ else if (status.state === "downloading")+ hint = t("profile_view.semantic_downloading").replace("{0}", percent(status.progress));+ else if (status.state === "indexing")+ hint = t("profile_view.semantic_indexing").replace("{0}", percent(status.progress));+ else if (status.state === "ready")+ hint = t("profile_view.semantic_ready").replace("{0}", String(status.pages));+ else if (status.state === "error") hint = t("profile_view.semantic_failed");+ else hint = t("profile_view.semantic_starting");++ const toggle = async (enabled: boolean) => {+ setSaving(true);+ setSaveFailed(false);+ try {+ client.setQueryData(SEMANTIC_SEARCH_KEY, await setWikiSemanticSearch(enabled));+ } catch {+ setSaveFailed(true);+ } finally {+ setSaving(false);+ }+ };++ return (+ <SettingRow+ testId="semantic-search-row"+ label={+ <span className="flex items-center gap-2.5">+ <span aria-hidden className="text-muted-foreground [&>svg]:h-4 [&>svg]:w-4">+ <Sparkles />+ </span>+ {t("profile_view.semantic_title")}+ </span>+ }+ hint={+ <span className="block pl-[1.625rem]">+ <span data-testid="semantic-search-status" aria-live="polite">+ {hint}+ </span>+ {saveFailed ? (+ <span role="alert" className="block text-destructive">+ {t("profile_view.semantic_save_failed")}+ </span>+ ) : null}+ </span>+ }+ control={+ <>+ {(saving || working(status) || pending(status)) && (+ <Loader2 aria-hidden className="h-4 w-4 animate-spin text-muted-foreground" />+ )}+ <Switch+ data-testid="semantic-search-switch"+ aria-label={t("profile_view.semantic_title")}+ checked={status.enabled}+ disabled={saving || (!status.available && !status.enabled)}+ onCheckedChange={(next) => void toggle(next)}+ />+ </>+ }+ />+ );+}diff --git a/jarvis/ui/web/server.py b/jarvis/ui/web/server.pyindex 474970640f..266e648f87 100644--- a/jarvis/ui/web/server.py+++ b/jarvis/ui/web/server.py@@ -3439,8 +3439,23 @@ class WebServer:from jarvis.memory.wiki.db_path import resolve_wiki_db_pathfrom jarvis.memory.wiki.fts_index import rebuild_index+ def _resume_semantic_search() -> None:+ # Semantic search, when the user switched it on: its own thread+ # loads the model and encodes only the pages that changed. Called+ # on every way out of this function, so the switch always learns+ # an honest state, also when there is no vault to search.+ try:+ from jarvis.memory.wiki import semantic_setup++ semantic_setup.resume(self.cfg)+ except Exception: # noqa: BLE001 - the word search stands on its own+ logger.opt(exception=True).warning(+ "wiki_boot_index: semantic search could not be resumed"+ )+wiki_cfg = self.cfg.wiki_integrationif not wiki_cfg.enabled:+ _resume_semantic_search()returnfrom jarvis.memory.wiki.vault_root import resolve_vault_root@@ -3448,6 +3463,7 @@ class WebServer:vault_root = resolve_vault_root(wiki_cfg.vault_root).pathif not vault_root.is_dir():logger.info("wiki_boot_index: vault missing — skipping ({})", vault_root)+ _resume_semantic_search()returndb_path = resolve_wiki_db_path(self.cfg.memory.data_dir)@@ -3475,6 +3491,8 @@ class WebServer:logger.debug("wiki index health recording failed", exc_info=True)finally:conn.close()+ # Behind the word index, so it never competes with start-up (AP-26).+ _resume_semantic_search()if background:thread = threading.Thread(diff --git a/jarvis/ui/web/wiki_routes.py b/jarvis/ui/web/wiki_routes.pyindex 88a808ab97..516a86cae0 100644--- a/jarvis/ui/web/wiki_routes.py+++ b/jarvis/ui/web/wiki_routes.py@@ -43,6 +43,7 @@ from typing import Anyfrom fastapi import APIRouter, HTTPException, Query, Requestfrom pydantic import BaseModel, Field+from jarvis.memory.wiki import semantic_setupfrom jarvis.memory.wiki.ingest_service import (MAX_INGEST_CHARS,MAX_SOURCE_CHARS,@@ -57,6 +58,7 @@ from jarvis.memory.wiki.page import parse_markdownfrom jarvis.memory.wiki.prompt import resolve_user_entity_slugfrom jarvis.memory.wiki.protocols import WikiPagefrom jarvis.memory.wiki.search import VaultSearch+from jarvis.memory.wiki.semantic_search import with_semantic_hitsfrom jarvis.memory.wiki.telemetry import telemetry as _telemetryfrom jarvis.memory.wiki.vault_root import resolve_vault_rootfrom jarvis.memory.wiki.wikilink import (@@ -117,6 +119,17 @@ class WikiIngestResponse(BaseModel):pages_touched: list[str]+#: How long the wiki search waits for semantic hits before it answers with+#: the word hits alone.+_SEMANTIC_SEARCH_TIMEOUT_S = 2.0+++class WikiSemanticSearchBody(BaseModel):+ """The semantic search switch."""++ enabled: bool++class WikiBackfillRequest(BaseModel):"""Bounded, evidence-only Realtime session review request."""@@ -706,8 +719,25 @@ async def get_search(log.warning("wiki_route_failed route=/search q=%r error=%s", q, exc)return {"ok": False, "error": "search failed"}+ # Pages the word search missed but that mean the same, when the user+ # switched semantic search on. Appended, never reordered in, and on its+ # own clock: the word hits above are the answer even when the model is+ # busy encoding the vault or still loading.+ by_words = len(hits)+ try:+ hits = await asyncio.wait_for(+ asyncio.to_thread(+ with_semantic_hits, hits, sanitised, vault_root=vault_root, wait=True+ ),+ timeout=_SEMANTIC_SEARCH_TIMEOUT_S,+ )+ except TimeoutError:+ log.info("wiki search: semantic hits skipped, the model did not answer in time")+ except Exception as exc: # noqa: BLE001 - the word search result stands on its own+ log.warning("wiki search: semantic hits skipped: %s", exc)+rendered: list[dict[str, Any]] = []- for hit in hits:+ for index, hit in enumerate(hits):path = Path(hit.path)rel_path = _relative_to_vault(path, vault_root)rendered.append(@@ -717,6 +747,7 @@ async def get_search("path": rel_path,"snippet": hit.snippet,"score": hit.score,+ "by_meaning": index >= by_words,})@@ -1096,6 +1127,10 @@ async def reindex_wiki(conn.close()before, indexed = await asyncio.to_thread(_run)+ if not dry_run and config is not None:+ # The word index was rebuilt from the vault on disk; bring the+ # semantic one up to date in the background as well, if it is on.+ semantic_setup.resume(config)return {"ok": True,"dry_run": dry_run,@@ -1106,6 +1141,51 @@ async def reindex_wiki(}[email protected]("/semantic-search")+def get_semantic_search(request: Request) -> dict[str, Any]:+ """State of semantic search: switched on or off, whether its model is on+ this machine, the setup step in progress and how many pages are covered.+ Read-only; never downloads or loads anything."""+ return semantic_setup.status(_require_config(request))++[email protected]("/semantic-search", openapi_extra={"x-jarvis-risk-tier": "monitor"})+def put_semantic_search(body: WikiSemanticSearchBody, request: Request) -> dict[str, Any]:+ """Switch semantic search on or off.++ ON: downloads a 135 MB multilingual search model once (from the pinned+ public revision, checksummed), then encodes the wiki pages on this machine+ in the background; nothing leaves the machine and no API key is used.+ Questions then also find pages that mean the same in other words or in+ another language. OFF: frees the model's memory; the downloaded model+ stays on disk. The word search works the same either way. Poll the GET+ for progress.+ """+ from jarvis.core.config_writer import set_wiki_semantic_search++ config = _require_config(request)+ try:+ set_wiki_semantic_search(body.enabled)+ except (OSError, ValueError) as exc:+ log.exception("wiki semantic search: could not persist the switch")+ raise HTTPException(+ status_code=500, detail="The setting could not be saved."+ ) from exc+ config.wiki_context.semantic_search = body.enabled+ if body.enabled:+ semantic_setup.start(config)+ else:+ semantic_setup.stop()+ return semantic_setup.status(config)+++def _require_config(request: Request) -> Any:+ config = getattr(request.app.state, "config", None)+ if config is None or getattr(config, "wiki_context", None) is None:+ raise HTTPException(status_code=503, detail="The app configuration is not loaded.")+ return config++@router.post("/search-aliases/backfill",openapi_extra={"x-jarvis-dangerous": True},diff --git a/tests/fakes/fake_semantic_encoder.py b/tests/fakes/fake_semantic_encoder.pynew file mode 100644index 0000000000..9949bb3ec8--- /dev/null+++ b/tests/fakes/fake_semantic_encoder.py@@ -0,0 +1,63 @@+"""A stand-in for the wiki's sentence encoder that needs no model.++The real encoder maps texts with the same meaning to nearby vectors, whatever+their wording or language. This fake does the same for a handful of concepts+it is told about: every text becomes a unit vector over those concepts, so+"when is my sister's birthday" and a German note about the sister's birthday+land on the same axes while a note about pizza lands elsewhere.++It also honours the encoder's contract the callers rely on: ``wait=False``+returns ``None`` while ``busy`` is set, and every call is recorded.+"""+from __future__ import annotations++from collections.abc import Sequence+from typing import Any++import numpy as np++from jarvis.memory.wiki.semantic_model import EMBEDDING_DIMENSIONS++#: Concept -> the words that express it, in any language the tests use.+DEFAULT_CONCEPTS: dict[str, tuple[str, ...]] = {+ "sister": ("sister", "schwester"),+ "birthday": ("birthday", "geburtstag", "born"),+ "food": ("pizza", "food", "essen", "eat", "meal"),+ "travel": ("flight", "travel", "reise", "trip", "paris"),+ "testing": ("testing", "validating", "integrations", "connections"),+}+++class FakeSemanticEncoder:+ def __init__(self, concepts: dict[str, tuple[str, ...]] | None = None) -> None:+ self._concepts = concepts or DEFAULT_CONCEPTS+ self.calls: list[list[str]] = []+ self.busy = False+ self.warmed = 0+ self.closed = 0++ def encode(self, texts: Sequence[str], *, wait: bool = True) -> Any | None:+ if self.busy and not wait:+ return None+ self.calls.append(list(texts))+ out = np.zeros((len(texts), EMBEDDING_DIMENSIONS), dtype=np.float32)+ for row, text in enumerate(texts):+ lowered = text.lower()+ for axis, words in enumerate(self._concepts.values()):+ if any(word in lowered for word in words):+ out[row, axis] = 1.0+ if not out[row].any():+ # Unrelated text points somewhere no concept does.+ out[row, EMBEDDING_DIMENSIONS - 1] = 1.0+ out[row] /= np.linalg.norm(out[row])+ return out++ def warm_up(self) -> None:+ self.warmed += 1++ def close(self) -> None:+ self.closed += 1++ @property+ def texts_encoded(self) -> int:+ return sum(len(call) for call in self.calls)diff --git a/tests/unit/brain/test_wiki_context_semantic.py b/tests/unit/brain/test_wiki_context_semantic.pynew file mode 100644index 0000000000..c19993d660--- /dev/null+++ b/tests/unit/brain/test_wiki_context_semantic.py@@ -0,0 +1,235 @@+"""The turn injector's optional semantic leg.++The word search must behave exactly as it does without semantic search, and a+slow, busy or broken semantic engine may cost a turn nothing but its own hits.+"""+from __future__ import annotations++import time+from dataclasses import dataclass+from pathlib import Path+from typing import Any++import pytest++from jarvis.brain.wiki_context import SEMANTIC_MIN_SCORE, WikiContextInjector++BASE_PROMPT = "You are the assistant."+PERSONAL = "What approach do I prefer when validating new connections?"+WORLD = "What is the capital of Australia?"+++@dataclass(frozen=True)+class Hit:+ title: str+ snippet: str+ score: float+ path: Path = Path("page.md")+ frontmatter: str = ""+ preview: str = ""+++class WordSearch:+ def __init__(self, hits: list[Hit] | None = None) -> None:+ self._hits = hits or []+ self.queries: list[str] = []++ def search(self, query: str, *, k: int = 5) -> list[Hit]:+ self.queries.append(query)+ return list(self._hits[:k])+++class MeaningSearch:+ def __init__(self, hits: list[Hit] | None = None, *, delay_s: float = 0.0) -> None:+ self._hits = hits or []+ self._delay_s = delay_s+ self.fail = False+ self.calls: list[tuple[str, int, float]] = []++ def search(self, query: str, *, k: int = 5, min_score: float = 0.0) -> list[Hit]:+ self.calls.append((query, k, min_score))+ if self._delay_s:+ time.sleep(self._delay_s)+ if self.fail:+ raise RuntimeError("native session died")+ return [hit for hit in self._hits if hit.score >= min_score][:k]+++STEP_BY_STEP = Hit(+ title="Working style",+ snippet="Tests integrations one concrete step at a time.",+ score=0.61,+ path=Path("concepts/working-style.md"),+)+++def _injector(words: WordSearch, meaning: Any, **kwargs: Any) -> WikiContextInjector:+ return WikiContextInjector(+ search=words, # type: ignore[arg-type]+ semantic_search=(lambda: meaning),+ latency_budget_ms=kwargs.pop("latency_budget_ms", 500),+ **kwargs,+ )+++async def test_a_paraphrased_question_finds_the_note_the_word_search_missed() -> None:+ meaning = MeaningSearch([STEP_BY_STEP])+ result = await _injector(WordSearch(), meaning).maybe_inject(+ user_text=PERSONAL, system_prompt=BASE_PROMPT+ )++ assert "one concrete step at a time" in result+ assert result.startswith(BASE_PROMPT)+ [(query, _k, min_score)] = meaning.calls+ assert query == PERSONAL, "the whole question is embedded, not its keywords"+ assert min_score == SEMANTIC_MIN_SCORE+++async def test_a_question_without_a_personal_anchor_gets_no_semantic_hits() -> None:+ meaning = MeaningSearch([STEP_BY_STEP])+ result = await _injector(WordSearch(), meaning).maybe_inject(+ user_text=WORLD, system_prompt=BASE_PROMPT+ )++ assert result == BASE_PROMPT+ assert meaning.calls == [], "a nearest page exists for every question; it is not asked"+++async def test_switched_off_the_injector_behaves_as_before() -> None:+ words = WordSearch()+ off = WikiContextInjector(+ search=words, # type: ignore[arg-type]+ semantic_search=lambda: None,+ latency_budget_ms=500,+ )+ assert await off.maybe_inject(user_text=PERSONAL, system_prompt=BASE_PROMPT) == BASE_PROMPT+ assert len(words.queries) == 1, "the word search still ran"+++async def test_word_hits_come_first_and_a_page_is_not_repeated() -> None:+ by_words = Hit(+ title="Connections",+ snippet="approach prefer validating connections: one step at a time",+ score=0.9,+ path=Path("concepts/working-style.md"),+ )+ other = Hit(+ title="Review habits",+ snippet="Reviews every integration before it ships.",+ score=0.58,+ path=Path("concepts/review.md"),+ )+ meaning = MeaningSearch([STEP_BY_STEP, other])++ result = await _injector(WordSearch([by_words]), meaning).maybe_inject(+ user_text=PERSONAL, system_prompt=BASE_PROMPT+ )++ assert result.index("Connections") < result.index("Review habits")+ assert "Working style" not in result, "same page as the word hit"+++async def test_a_distant_second_page_does_not_ride_along() -> None:+ weak = Hit(title="Trip", snippet="Flight to Paris.", score=0.43, path=Path("trip.md"))+ result = await _injector(WordSearch(), MeaningSearch([STEP_BY_STEP, weak])).maybe_inject(+ user_text=PERSONAL, system_prompt=BASE_PROMPT+ )+ assert "Working style" in result+ assert "Trip" not in result+++async def test_a_slow_semantic_engine_does_not_cost_the_turn_its_word_hits() -> None:+ by_words = Hit(+ title="Connections",+ snippet="approach prefer validating connections: one step at a time",+ score=0.9,+ path=Path("concepts/connections.md"),+ )+ slow = MeaningSearch([STEP_BY_STEP], delay_s=0.6)+ injector = _injector(WordSearch([by_words]), slow, latency_budget_ms=150)++ started = time.monotonic()+ result = await injector.maybe_inject(user_text=PERSONAL, system_prompt=BASE_PROMPT)+ elapsed = time.monotonic() - started++ assert "Connections" in result+ assert "Working style" not in result+ assert elapsed < 0.45, "the turn did not wait for the semantic engine"+++async def test_a_failing_semantic_engine_leaves_the_word_search_result_standing() -> None:+ by_words = Hit(+ title="Connections",+ snippet="approach prefer validating connections: one step at a time",+ score=0.9,+ path=Path("concepts/connections.md"),+ )+ broken = MeaningSearch([STEP_BY_STEP])+ broken.fail = True++ result = await _injector(WordSearch([by_words]), broken).maybe_inject(+ user_text=PERSONAL, system_prompt=BASE_PROMPT+ )++ assert "Connections" in result+++async def test_a_provider_that_raises_is_treated_as_switched_off() -> None:+ def provider() -> Any:+ raise RuntimeError("registry not ready")++ injector = WikiContextInjector(+ search=WordSearch(), # type: ignore[arg-type]+ semantic_search=provider,+ latency_budget_ms=500,+ )+ assert await injector.maybe_inject(user_text=PERSONAL, system_prompt=BASE_PROMPT) == BASE_PROMPT+++async def test_a_semantic_engine_for_another_vault_is_not_asked() -> None:+ words = WordSearch()+ words._root = Path("vault-a") # type: ignore[attr-defined]+ meaning = MeaningSearch([STEP_BY_STEP])+ meaning.vault_root = Path("vault-b") # type: ignore[attr-defined]++ result = await _injector(words, meaning).maybe_inject(+ user_text=PERSONAL, system_prompt=BASE_PROMPT+ )++ assert result == BASE_PROMPT+ assert meaning.calls == []+++async def test_a_cancelled_turn_does_not_leave_the_semantic_lookup_running() -> None:+ import asyncio++ class SlowWords(WordSearch):+ def search(self, query: str, *, k: int = 5) -> list[Hit]:+ time.sleep(0.3)+ return []++ injector = _injector(SlowWords(), MeaningSearch([STEP_BY_STEP], delay_s=0.3))+ before = {task for task in asyncio.all_tasks() if not task.done()}++ turn = asyncio.ensure_future(+ injector.maybe_inject(user_text=PERSONAL, system_prompt=BASE_PROMPT)+ )+ await asyncio.sleep(0.05)+ turn.cancel()+ with pytest.raises(asyncio.CancelledError):+ await turn+ await asyncio.sleep(0)++ left = {task for task in asyncio.all_tasks() if not task.done()} - before+ left.discard(asyncio.current_task())+ assert left == set(), "no lookup task outlives the cancelled turn"diff --git a/tests/unit/memory/wiki/test_semantic_index.py b/tests/unit/memory/wiki/test_semantic_index.pynew file mode 100644index 0000000000..454d4cd1fc--- /dev/null+++ b/tests/unit/memory/wiki/test_semantic_index.py@@ -0,0 +1,162 @@+"""The semantic index encodes each page once and follows the vault on disk."""+from __future__ import annotations++import os+import sqlite3+from pathlib import Path++import pytest++from jarvis.memory.wiki import semantic_index+from tests.fakes.fake_semantic_encoder import FakeSemanticEncoder+++def _page(vault: Path, rel: str, body: str) -> Path:+ path = vault / rel+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(f"---\ntype: entity\n---\n{body}", encoding="utf-8")+ return path+++def vault(tmp_path: Path) -> Path:+ root = tmp_path / "vault"+ facts = "- Sister of the user\n- Birthday on 4 May\n"+ _page(root, "entities/anna.md", f"# Anna\n\n## Facts\n{facts}")+ _page(root, "concepts/food.md", "# Food\n\nPizza with mushrooms is the favourite meal.\n")+ return root+++def conn(tmp_path: Path) -> sqlite3.Connection:+ connection = sqlite3.connect(str(tmp_path / "wiki.db"))+ yield connection+ connection.close()+++def test_a_list_page_becomes_one_passage_per_fact() -> None:+ cut = semantic_index.passages("Anna", "# Anna\n\n## Facts\n- Sister of the user\n- Born 1961\n")+ assert [text for text, _encoded in cut] == ["Sister of the user", "Born 1961"]+ # The encoded text carries the page and the heading the fact stands under.+ assert cut[1][1] == "Anna: Facts: Born 1961"+++def test_markup_is_reduced_to_the_words_a_reader_sees() -> None:+ body = "Works with [[projects/apollo|Apollo]] and **likes** `tea`, see [notes](http://x.test)."+ [(text, _encoded)] = semantic_index.passages("Page", body)+ assert text == "Works with Apollo and likes tea, see notes."+++def test_code_blocks_and_stray_marks_are_not_passages() -> None:+ body = "Real sentence about the project.\n\n```\nprint('x')\n```\n\n- ok\n"+ assert [text for text, _ in semantic_index.passages("Page", body)] == [+ "Real sentence about the project."+ ]+++def test_a_long_paragraph_is_cut_so_no_part_is_ignored() -> None:+ sentence = "This sentence describes one detail of the plan in plain words. "+ cut = semantic_index.passages("Plan", sentence * 30)+ assert len(cut) > 1+ assert all(len(text) <= 480 for text, _ in cut)+ assert "".join(text for text, _ in cut).count("detail") == 30+++def test_sync_encodes_every_page_once(vault: Path, conn: sqlite3.Connection) -> None:+ encoder = FakeSemanticEncoder()+ first = semantic_index.sync_vault(conn, vault, encoder=encoder)+ assert (first.pages, first.encoded, first.removed) == (2, 2, 0)+ assert semantic_index.counts(conn) == (2, 3)++ encoded_before = encoder.texts_encoded+ second = semantic_index.sync_vault(conn, vault, encoder=encoder)+ assert (second.pages, second.encoded) == (2, 0)+ assert encoder.texts_encoded == encoded_before, "an unchanged vault costs no inference"+++def test_sync_re_encodes_only_the_page_that_changed(vault: Path, conn: sqlite3.Connection) -> None:+ encoder = FakeSemanticEncoder()+ semantic_index.sync_vault(conn, vault, encoder=encoder)+ changed = _page(vault, "concepts/food.md", "# Food\n\nNow the favourite meal is soup.\n")+ later = changed.stat().st_mtime + 5+ os.utime(changed, (later, later))++ result = semantic_index.sync_vault(conn, vault, encoder=encoder)++ assert result.encoded == 1+ assert encoder.calls[-1] == ["Food: Now the favourite meal is soup."]+++def test_sync_drops_pages_that_are_gone(vault: Path, conn: sqlite3.Connection) -> None:+ encoder = FakeSemanticEncoder()+ semantic_index.sync_vault(conn, vault, encoder=encoder)+ (vault / "entities" / "anna.md").unlink()++ result = semantic_index.sync_vault(conn, vault, encoder=encoder)++ assert result.removed == 1+ _matrix, rows = semantic_index.load_passages(conn)+ assert {path for path, _title, _text in rows} == {"concepts/food.md"}+++def test_sync_against_another_vault_leaves_no_row_of_the_old_one(+ vault: Path, conn: sqlite3.Connection, tmp_path: Path+) -> None:+ encoder = FakeSemanticEncoder()+ semantic_index.sync_vault(conn, vault, encoder=encoder)+ other = tmp_path / "other"+ _page(other, "notes/trip.md", "# Trip\n\nThe flight to Paris leaves in the morning.\n")++ semantic_index.sync_vault(conn, other, encoder=encoder)++ _matrix, rows = semantic_index.load_passages(conn)+ assert {path for path, _title, _text in rows} == {"notes/trip.md"}+++def test_rows_of_the_old_vault_are_gone_before_anything_is_encoded(+ vault: Path, conn: sqlite3.Connection, tmp_path: Path+) -> None:+ semantic_index.sync_vault(conn, vault, encoder=FakeSemanticEncoder())+ other = tmp_path / "other"+ _page(other, "notes/trip.md", "# Trip\n\nThe flight to Paris leaves in the morning.\n")++ stale, pages, removed = semantic_index.plan_sync(conn, other)++ assert (stale, pages, removed) == (["notes/trip.md"], 1, 2)+ assert semantic_index.counts(conn) == (0, 0), "no search can mix the two vaults"+++def test_one_page_that_cannot_be_encoded_does_not_end_the_run(+ vault: Path, conn: sqlite3.Connection+) -> None:+ class Flaky(FakeSemanticEncoder):+ def encode(self, texts, *, wait=True): # type: ignore[no-untyped-def]+ if any("Pizza" in text for text in texts):+ raise RuntimeError("inference failed")+ return super().encode(texts, wait=wait)++ result = semantic_index.sync_vault(conn, vault, encoder=Flaky())++ assert (result.encoded, result.failed) == (1, 1)+ _matrix, rows = semantic_index.load_passages(conn)+ assert {path for path, _title, _text in rows} == {"entities/anna.md"}+++def test_one_page_can_be_read_back_on_its_own(vault: Path, conn: sqlite3.Connection) -> None:+ semantic_index.sync_vault(conn, vault, encoder=FakeSemanticEncoder())+ matrix, rows = semantic_index.load_passages(conn, path="entities/anna.md")+ assert matrix.shape == (2, 384)+ assert {path for path, _title, _text in rows} == {"entities/anna.md"}+++def test_stored_vectors_come_back_as_one_matrix(vault: Path, conn: sqlite3.Connection) -> None:+ semantic_index.sync_vault(conn, vault, encoder=FakeSemanticEncoder())+ matrix, rows = semantic_index.load_passages(conn)+ assert matrix.shape == (3, 384)+ assert [title for _path, title, _text in rows] == ["Food", "Anna", "Anna"]+++def test_remove_page_forgets_its_passages(vault: Path, conn: sqlite3.Connection) -> None:+ semantic_index.sync_vault(conn, vault, encoder=FakeSemanticEncoder())+ semantic_index.remove_page(conn, vault, vault / "entities" / "anna.md")+ assert semantic_index.counts(conn) == (1, 1)diff --git a/tests/unit/memory/wiki/test_semantic_model.py b/tests/unit/memory/wiki/test_semantic_model.pynew file mode 100644index 0000000000..8e78962be4--- /dev/null+++ b/tests/unit/memory/wiki/test_semantic_model.py@@ -0,0 +1,299 @@+"""The search model: one identity, a checked download, a guarded session."""+from __future__ import annotations++import hashlib+import re+import threading+from pathlib import Path+from typing import Any++import httpx+import numpy as np+import pytest++from jarvis.core.paths import repo_root+from jarvis.memory.wiki import semantic_model+from jarvis.memory.wiki.semantic_model import ModelFile, SemanticEncoder++FILES = {"tokenizer.json": b"vocabulary", "onnx/model_quantized.onnx": b"weights" * 100}+++def small_model(monkeypatch: pytest.MonkeyPatch) -> dict[str, bytes]:+ """Shrink the pinned files so a test can download and store them."""+ entries = tuple(+ ModelFile(path, len(data), hashlib.sha256(data).hexdigest())+ for path, data in FILES.items()+ )+ monkeypatch.setattr(semantic_model, "MODEL_FILES", entries)+ monkeypatch.setattr(semantic_model, "DOWNLOAD_BYTES", sum(item.size for item in entries))+ return dict(FILES)+++class _FakeStream:+ """What ``httpx.stream`` hands back, serving bytes from a dict."""++ def __init__(self, served: dict[str, bytes], requested: list[str], url: str) -> None:+ requested.append(url)+ self._data = next(data for path, data in served.items() if url.endswith(path))++ def __enter__(self) -> _FakeStream:+ return self++ def __exit__(self, *_exc: object) -> None:+ return None++ def raise_for_status(self) -> None:+ return None++ def iter_bytes(self, _chunk_size: int) -> Any:+ yield self._data[: len(self._data) // 2]+ yield self._data[len(self._data) // 2 :]+++def _serve(monkeypatch: pytest.MonkeyPatch, served: dict[str, bytes]) -> list[str]:+ requested: list[str] = []++ def stream(_method: str, url: str, **_kwargs: Any) -> _FakeStream:+ return _FakeStream(served, requested, url)++ monkeypatch.setattr(httpx, "stream", stream)+ return requested+++def test_python_and_browser_use_the_same_model_revision() -> None:+ source = (+ repo_root()+ / "jarvis/ui/web/frontend/src/components/agentic/sidePanel/agentSearch.ts"+ ).read_text(encoding="utf-8")+ model = re.search(r'AGENT_SEARCH_MODEL = "([^"]+)"', source)+ revision = re.search(r'AGENT_SEARCH_REVISION = "([^"]+)"', source)+ assert model and revision+ assert semantic_model.MODEL_REPO == model.group(1)+ assert semantic_model.MODEL_REVISION == revision.group(1)+++def test_the_model_is_present_only_when_every_file_is_complete(+ tmp_path: Path, small_model: dict[str, bytes]+) -> None:+ assert not semantic_model.model_present(tmp_path)+ root = semantic_model.model_dir(tmp_path)+ (root / "onnx").mkdir(parents=True)+ (root / "tokenizer.json").write_bytes(small_model["tokenizer.json"])+ (root / "onnx" / "model_quantized.onnx").write_bytes(b"cut off")+ assert not semantic_model.model_present(tmp_path), "a partial file is not the model"+ (root / "onnx" / "model_quantized.onnx").write_bytes(small_model["onnx/model_quantized.onnx"])+ assert semantic_model.model_present(tmp_path)+++def test_download_fetches_the_pinned_revision_and_reports_progress(+ tmp_path: Path, small_model: dict[str, bytes], monkeypatch: pytest.MonkeyPatch+) -> None:+ requested = _serve(monkeypatch, small_model)+ seen: list[tuple[int, int]] = []++ semantic_model.download_model(tmp_path, progress=lambda done, total: seen.append((done, total)))++ assert semantic_model.model_present(tmp_path)+ assert all(semantic_model.MODEL_REVISION in url for url in requested)+ assert seen[-1] == (semantic_model.DOWNLOAD_BYTES, semantic_model.DOWNLOAD_BYTES)+ assert not list(semantic_model.model_dir(tmp_path).rglob("*.part"))+++def test_download_skips_files_that_are_already_there(+ tmp_path: Path, small_model: dict[str, bytes], monkeypatch: pytest.MonkeyPatch+) -> None:+ _serve(monkeypatch, small_model)+ semantic_model.download_model(tmp_path)+ requested = _serve(monkeypatch, small_model)++ semantic_model.download_model(tmp_path)++ assert requested == []+++def test_a_damaged_download_is_refused_and_leaves_nothing_behind(+ tmp_path: Path, small_model: dict[str, bytes], monkeypatch: pytest.MonkeyPatch+) -> None:+ _serve(monkeypatch, {**small_model, "tokenizer.json": b"vocabulerY"})++ with pytest.raises(RuntimeError, match="checksum"):+ semantic_model.download_model(tmp_path)++ assert not semantic_model.model_present(tmp_path)+ assert not list(semantic_model.model_dir(tmp_path).rglob("*"))[1:], "no file, no .part"+++def test_a_file_larger_than_the_pinned_one_is_cut_off(+ tmp_path: Path, small_model: dict[str, bytes], monkeypatch: pytest.MonkeyPatch+) -> None:+ _serve(monkeypatch, {**small_model, "tokenizer.json": b"vocabulary" * 1000})++ with pytest.raises(RuntimeError, match="larger than the pinned file"):+ semantic_model.download_model(tmp_path)++ assert not list(semantic_model.model_dir(tmp_path).rglob("*.part"))+++def test_a_download_that_is_told_to_stop_leaves_no_half_file(+ tmp_path: Path, small_model: dict[str, bytes], monkeypatch: pytest.MonkeyPatch+) -> None:+ _serve(monkeypatch, small_model)++ class Stop(Exception):+ pass++ def progress(_done: int, _total: int) -> None:+ raise Stop++ with pytest.raises(Stop):+ semantic_model.download_model(tmp_path, progress=progress)++ assert not semantic_model.model_present(tmp_path)+ assert not list(semantic_model.model_dir(tmp_path).rglob("*.part"))+++class _Tokenizer:+ def encode(self, text: str, *, max_tokens: int) -> list[int]:+ return [0, *range(10, 10 + len(text.split())), 2][:max_tokens]+++class _Session:+ """Returns, per token, a vector whose first value is the token id."""++ def __init__(self) -> None:+ self.batches: list[int] = []++ def run(self, _outputs: Any, feeds: dict[str, np.ndarray]) -> list[np.ndarray]:+ ids = feeds["input_ids"]+ self.batches.append(ids.shape[0])+ hidden = np.zeros((*ids.shape, semantic_model.EMBEDDING_DIMENSIONS), dtype=np.float32)+ hidden[:, :, 0] = ids+ hidden[:, :, 1] = 1.0+ return [hidden]+++class _StubEncoder(SemanticEncoder):+ """The real encoder with the native session swapped for a recording one."""++ def __init__(self) -> None:+ super().__init__()+ self.loads = 0+ self.session = _Session()++ def _load(self) -> tuple[Any, Any]:+ self.loads += 1+ self._tokenizer = _Tokenizer()+ self._session = self.session+ self._input_names = frozenset({"input_ids", "attention_mask"})+ return self._session, self._tokenizer+++def test_vectors_are_unit_length_and_ignore_padding() -> None:+ encoder = _StubEncoder()+ vectors = encoder.encode(["one", "one two three four"])+ assert vectors.shape == (2, semantic_model.EMBEDDING_DIMENSIONS)+ assert np.allclose(np.linalg.norm(vectors, axis=1), 1.0)+ # "one" is ids [0, 10, 2]: mean 4. Padding to five tokens must not drag it down.+ alone = encoder.encode(["one"])+ assert np.allclose(vectors[0], alone[0])+++def test_many_texts_are_encoded_in_small_batches() -> None:+ encoder = _StubEncoder()+ vectors = encoder.encode([f"text {n}" for n in range(19)])+ assert vectors.shape[0] == 19+ assert encoder.session.batches == [8, 8, 3]+ assert encoder.loads == 1+++def test_the_turn_path_never_waits_for_a_model_that_is_not_loaded() -> None:+ encoder = _StubEncoder()+ assert encoder.encode(["question"], wait=False) is None+ encoder._loader.join(timeout=5)+ assert encoder.loaded+ assert encoder.encode(["question"], wait=False) is not None+++def test_a_second_caller_does_not_enter_the_session() -> None:+ encoder = _StubEncoder()+ encoder.encode(["warm"])+ encoder._gate.lock.acquire()+ try:+ assert encoder.encode(["question"], wait=False) is None+ finally:+ encoder._gate.lock.release()+ assert encoder.encode(["question"], wait=False) is not None+++def test_a_session_that_stopped_answering_is_replaced(monkeypatch: pytest.MonkeyPatch) -> None:+ encoder = _StubEncoder()+ encoder.encode(["warm"])+ wedged = encoder._gate+ wedged.lock.acquire() # a caller that never comes back+ wedged.held_since = 0.0+ monkeypatch.setattr(semantic_model.time, "monotonic", lambda: 10_000.0)++ assert encoder.encode(["question"], wait=False) is None+ assert encoder._gate is not wedged, "the fresh path gets a fresh lock"+ assert not encoder.loaded++ assert encoder.encode(["question"]) is not None+ assert encoder.loads == 2++ # The stuck caller coming back late must not disturb the new holder.+ encoder._gate.held_since = 123.0+ wedged.held_since = None+ wedged.lock.release()+ assert encoder._gate.held_since == 123.0+++def test_close_never_waits_for_a_caller_inside_the_session() -> None:+ encoder = _StubEncoder()+ encoder.encode(["warm"])+ encoder._gate.lock.acquire() # someone is encoding, or stuck+ try:+ encoder.close() # returns at once instead of queueing behind it+ finally:+ encoder._gate.lock.release()+ assert not encoder.loaded+++def test_a_closed_encoder_stays_closed() -> None:+ encoder = _StubEncoder()+ encoder.encode(["warm"])+ encoder.close()++ assert encoder.encode(["question"], wait=False) is None+ with pytest.raises(RuntimeError, match="switched off"):+ encoder.encode(["question"])+ encoder.warm_up()+ assert not encoder.loaded+ assert encoder.loads == 1, "nothing reloads a model the user switched off"+++def test_concurrent_callers_are_serialised() -> None:+ encoder = _StubEncoder()+ inside = 0+ peak = 0+ guard = threading.Lock()+ original = encoder.session.run++ def run(outputs: Any, feeds: dict[str, np.ndarray]) -> list[np.ndarray]:+ nonlocal inside, peak+ with guard:+ inside += 1+ peak = max(peak, inside)+ try:+ return original(outputs, feeds)+ finally:+ with guard:+ inside -= 1++ encoder.session.run = run # type: ignore[method-assign]+ threads = [threading.Thread(target=encoder.encode, args=(["a b c"],)) for _ in range(8)]+ for thread in threads:+ thread.start()+ for thread in threads:+ thread.join(timeout=5)+ assert peak == 1diff --git a/tests/unit/memory/wiki/test_semantic_search.py b/tests/unit/memory/wiki/test_semantic_search.pynew file mode 100644index 0000000000..4713a9c574--- /dev/null+++ b/tests/unit/memory/wiki/test_semantic_search.py@@ -0,0 +1,222 @@+"""Semantic search finds pages by meaning and never gets in a caller's way."""+from __future__ import annotations++from collections.abc import Iterator+from pathlib import Path++import pytest++from jarvis.memory.wiki import semantic_search+from jarvis.memory.wiki.search import SearchHit+from jarvis.memory.wiki.semantic_search import SemanticVaultSearch, with_semantic_hits+from tests.fakes.fake_semantic_encoder import FakeSemanticEncoder+++def _page(vault: Path, rel: str, body: str) -> Path:+ path = vault / rel+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(f"---\ntype: entity\n---\n{body}", encoding="utf-8")+ return path++[email protected](autouse=True)+def _no_active_search() -> Iterator[None]:+ semantic_search.deactivate()+ yield+ semantic_search.deactivate()+++def vault(tmp_path: Path) -> Path:+ root = tmp_path / "vault"+ _page(+ root,+ "entities/anna.md",+ "# Anna\n\n## Facts\n- Meine Schwester\n- Geburtstag am 4. Mai\n- Likes pizza\n",+ )+ _page(root, "concepts/trip.md", "# Trip\n\nThe flight to Paris leaves in the morning.\n")+ return root+++def encoder() -> FakeSemanticEncoder:+ return FakeSemanticEncoder()+++def search(vault: Path, tmp_path: Path, encoder: FakeSemanticEncoder) -> SemanticVaultSearch:+ instance = SemanticVaultSearch(vault, db_path=tmp_path / "wiki.db", encoder=encoder)+ instance.sync()+ return instance+++def test_a_question_finds_the_note_written_in_another_language(+ search: SemanticVaultSearch, vault: Path+) -> None:+ hits = search.search("when is my sister's birthday")+ assert [hit.path for hit in hits] == [vault / "entities" / "anna.md"]+ assert hits[0].title == "Anna"+ assert hits[0].score > 0.5+++def test_each_page_appears_once_with_its_best_passage(search: SemanticVaultSearch) -> None:+ hits = search.search("birthday of my sister, and pizza", k=5)+ assert [hit.title for hit in hits].count("Anna") == 1+++def test_an_unrelated_question_returns_nothing(search: SemanticVaultSearch) -> None:+ assert search.search("how tall is the Eiffel tower") == []+++def test_blank_queries_touch_neither_disk_nor_model(+ search: SemanticVaultSearch, encoder: FakeSemanticEncoder+) -> None:+ before = len(encoder.calls)+ assert search.search(" ") == []+ assert len(encoder.calls) == before+++def test_the_turn_path_does_not_read_the_vectors_from_disk(+ vault: Path, tmp_path: Path, encoder: FakeSemanticEncoder+) -> None:+ SemanticVaultSearch(vault, db_path=tmp_path / "wiki.db", encoder=encoder).sync()+ fresh = SemanticVaultSearch(vault, db_path=tmp_path / "wiki.db", encoder=encoder)++ assert fresh.search("sister birthday") == [], "not loaded yet, and it must not wait"++ fresh.warm_up()+ assert [hit.title for hit in fresh.search("sister birthday")] == ["Anna"]+ assert encoder.warmed == 1+++def test_a_busy_model_costs_the_turn_only_its_semantic_hits(+ search: SemanticVaultSearch, encoder: FakeSemanticEncoder+) -> None:+ encoder.busy = True+ assert search.search("sister birthday") == []+ assert [hit.title for hit in search.search("sister birthday", wait=True)] == ["Anna"]+++def test_a_broken_model_is_no_hits_not_an_error(vault: Path, tmp_path: Path) -> None:+ class Broken(FakeSemanticEncoder):+ def encode(self, texts, *, wait=True): # type: ignore[no-untyped-def]+ if len(self.calls) >= 1:+ raise RuntimeError("native session died")+ return super().encode(texts, wait=wait)++ broken = Broken()+ instance = SemanticVaultSearch(vault, db_path=tmp_path / "wiki.db", encoder=broken)+ # The first page encodes, the second fails; the run goes on and counts it.+ result = instance.sync()+ assert (result.encoded, result.failed) == (1, 1)+ assert instance.search("sister birthday") == []+++def test_a_page_update_does_not_wait_for_a_whole_sync(+ vault: Path, tmp_path: Path, encoder: FakeSemanticEncoder+) -> None:+ """The write lock is per page, so the watcher gets in between two pages."""+ instance = SemanticVaultSearch(vault, db_path=tmp_path / "wiki.db", encoder=encoder)+ seen_free: list[bool] = []++ def progress(_done: int, _total: int) -> None:+ free = instance._write_lock.acquire(blocking=False)+ seen_free.append(free)+ if free:+ instance._write_lock.release()++ instance.sync(progress=progress)++ assert seen_free == [True, True]+++def test_a_sync_that_is_told_to_stop_ends_at_the_next_page(+ vault: Path, tmp_path: Path, encoder: FakeSemanticEncoder+) -> None:+ class Stop(Exception):+ pass++ def progress(_done: int, _total: int) -> None:+ raise Stop++ instance = SemanticVaultSearch(vault, db_path=tmp_path / "wiki.db", encoder=encoder)+ with pytest.raises(Stop):+ instance.sync(progress=progress)++ assert instance.counts()[0] == 1, "one page was written whole, the rest not at all"+++def test_a_page_update_patches_memory_without_reloading_the_vault(+ search: SemanticVaultSearch, vault: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ from jarvis.memory.wiki import semantic_index++ reads: list[str | None] = []+ real = semantic_index.load_passages++ def spy(conn, *, path=None): # type: ignore[no-untyped-def]+ reads.append(path)+ return real(conn, path=path)++ monkeypatch.setattr(semantic_index, "load_passages", spy)+ page = _page(vault, "concepts/meal.md", "# Meal\n\nPizza is the favourite food.\n")++ search.index_page(page)++ assert reads == ["concepts/meal.md"], "only the changed page is read back"+ assert search.counts() == (3, 5)+ assert "Meal" in [hit.title for hit in search.search("what do I like to eat")]+++def test_a_changed_page_is_searchable_at_once(+ search: SemanticVaultSearch, vault: Path+) -> None:+ page = _page(vault, "concepts/meal.md", "# Meal\n\nPizza is the favourite food.\n")+ search.index_page(page)+ assert "Meal" in [hit.title for hit in search.search("what do I like to eat")]++ search.remove_page(page)+ assert "Meal" not in [hit.title for hit in search.search("what do I like to eat")]+++def test_counts_report_pages_and_passages(search: SemanticVaultSearch) -> None:+ assert search.counts() == (2, 4)+++def test_one_instance_is_active_per_vault(+ vault: Path, tmp_path: Path, encoder: FakeSemanticEncoder+) -> None:+ assert semantic_search.get_active() is None+ first = semantic_search.activate(vault, db_path=tmp_path / "wiki.db", encoder=encoder)+ assert semantic_search.activate(vault, db_path=tmp_path / "wiki.db") is first++ other = semantic_search.activate(+ tmp_path / "other", db_path=tmp_path / "wiki.db", encoder=FakeSemanticEncoder()+ )+ assert other is not first+ assert encoder.closed == 1, "the previous vault's model is released"++ semantic_search.deactivate()+ assert semantic_search.get_active() is None+++def test_semantic_hits_are_appended_to_the_word_search_result(+ vault: Path, tmp_path: Path, encoder: FakeSemanticEncoder+) -> None:+ active = semantic_search.activate(vault, db_path=tmp_path / "wiki.db", encoder=encoder)+ active.sync()+ by_words = [SearchHit(title="Trip", path=vault / "concepts" / "trip.md", snippet="", score=0.9)]++ merged = with_semantic_hits(by_words, "sister birthday and the flight", vault_root=vault)++ assert [hit.title for hit in merged] == ["Trip", "Anna"], "word hits first, no duplicate"+++def test_the_word_search_result_is_untouched_while_semantic_search_is_off(+ vault: Path, tmp_path: Path, encoder: FakeSemanticEncoder+) -> None:+ by_words = [SearchHit(title="Trip", path=vault / "concepts" / "trip.md", snippet="", score=0.9)]+ assert with_semantic_hits(by_words, "sister birthday", vault_root=vault) is by_words++ semantic_search.activate(tmp_path / "other", db_path=tmp_path / "wiki.db", encoder=encoder)+ assert with_semantic_hits(by_words, "sister birthday", vault_root=vault) is by_wordsdiff --git a/tests/unit/memory/wiki/test_semantic_setup.py b/tests/unit/memory/wiki/test_semantic_setup.pynew file mode 100644index 0000000000..385144afcd--- /dev/null+++ b/tests/unit/memory/wiki/test_semantic_setup.py@@ -0,0 +1,314 @@+"""Switching semantic search on and off: honest states, retryable failures."""+from __future__ import annotations++import threading+from collections.abc import Iterator+from pathlib import Path+from types import SimpleNamespace+from typing import Any++import httpx+import pytest++from jarvis.memory.wiki import semantic_model, semantic_search, semantic_setup+from tests.fakes.fake_semantic_encoder import FakeSemanticEncoder++[email protected](autouse=True)+def _fresh_state(monkeypatch: pytest.MonkeyPatch) -> Iterator[None]:+ monkeypatch.setattr(semantic_setup, "_run", semantic_setup._Run())+ semantic_search.deactivate()+ yield+ semantic_search.deactivate()+++def config(tmp_path: Path) -> SimpleNamespace:+ vault = tmp_path / "vault"+ (vault / "entities").mkdir(parents=True)+ (vault / "entities" / "anna.md").write_text(+ "---\ntype: entity\n---\n# Anna\n\n- My sister\n- Birthday on 4 May\n", encoding="utf-8"+ )+ return SimpleNamespace(+ wiki_context=SimpleNamespace(semantic_search=True),+ wiki_integration=SimpleNamespace(vault_root=vault),+ memory=SimpleNamespace(data_dir=str(tmp_path / "data")),+ )+++class _Machine:+ """The parts of this computer the setup touches, under the test's control."""++ def __init__(self, monkeypatch: pytest.MonkeyPatch) -> None:+ self.runtime = True+ self.model_on_disk = False+ self.downloads = 0+ self.download_error: Exception | None = None+ self.hold_download = threading.Event()+ self.hold_download.set()+ self.encoder = FakeSemanticEncoder()+ real_activate = semantic_search.activate++ def download(_data_dir: Any = None, *, progress: Any = None) -> None:+ self.downloads += 1+ self.hold_download.wait(timeout=5)+ if self.download_error is not None:+ raise self.download_error+ if progress is not None:+ progress(1, 2) # raises when the run was switched off meanwhile+ self.model_on_disk = True++ def activate(vault_root: Path, **kwargs: Any) -> Any:+ return real_activate(vault_root, **{**kwargs, "encoder": self.encoder})++ monkeypatch.setattr(semantic_model, "runtime_available", lambda: self.runtime)+ monkeypatch.setattr(semantic_model, "model_present", lambda _d=None: self.model_on_disk)+ monkeypatch.setattr(semantic_model, "download_model", download)+ monkeypatch.setattr(semantic_search, "activate", activate)+++def machine(monkeypatch: pytest.MonkeyPatch) -> _Machine:+ return _Machine(monkeypatch)+++def _finish() -> None:+ thread = semantic_setup._run.thread+ assert thread is not None+ thread.join(timeout=10)+ assert not thread.is_alive()+++def test_it_is_off_until_the_user_switches_it_on(+ config: SimpleNamespace, machine: _Machine+) -> None:+ config.wiki_context.semantic_search = False+ semantic_setup.resume(config)++ report = semantic_setup.status(config)++ assert report["enabled"] is False+ assert report["state"] == "off"+ assert machine.downloads == 0, "nothing is fetched that nobody asked for"+ assert semantic_search.get_active() is None+++def test_switching_it_on_downloads_once_and_encodes_the_vault(+ config: SimpleNamespace, machine: _Machine+) -> None:+ assert semantic_setup.start(config) is True+ _finish()++ report = semantic_setup.status(config)+ assert report["state"] == "ready"+ assert report["model_present"] is True+ assert (report["pages"], report["passages"]) == (1, 2)+ assert machine.downloads == 1+ assert semantic_search.get_active() is not None+++def test_a_restart_with_the_model_on_disk_downloads_nothing(+ config: SimpleNamespace, machine: _Machine+) -> None:+ machine.model_on_disk = True+ semantic_setup.resume(config)+ _finish()++ assert machine.downloads == 0+ assert semantic_setup.status(config)["state"] == "ready"+++def test_a_failed_download_is_reported_and_can_be_retried(+ config: SimpleNamespace, machine: _Machine+) -> None:+ machine.download_error = httpx.ConnectError("no route to host")+ semantic_setup.start(config)+ _finish()++ report = semantic_setup.status(config)+ assert report["state"] == "error"+ assert "internet connection" in report["message"]+ assert semantic_search.get_active() is None++ machine.download_error = None+ semantic_setup.start(config)+ _finish()+ assert semantic_setup.status(config)["state"] == "ready"+++def test_a_system_without_the_runtime_says_so_and_fetches_nothing(+ config: SimpleNamespace, machine: _Machine+) -> None:+ machine.runtime = False++ assert semantic_setup.start(config) is False++ report = semantic_setup.status(config)+ assert report["available"] is False+ assert report["state"] == "error"+ assert "word search keeps working" in report["message"]+ assert machine.downloads == 0+++def test_a_missing_wiki_folder_is_an_honest_error(+ config: SimpleNamespace, machine: _Machine, tmp_path: Path+) -> None:+ config.wiki_integration.vault_root = tmp_path / "nowhere"+ assert semantic_setup.start(config) is False+ assert semantic_setup.status(config)["state"] == "error"+ assert machine.downloads == 0+++def test_switching_it_off_during_the_download_never_activates_it(+ config: SimpleNamespace, machine: _Machine+) -> None:+ machine.hold_download.clear()+ semantic_setup.start(config)+ assert semantic_setup.status(config)["state"] == "downloading"++ config.wiki_context.semantic_search = False+ semantic_setup.stop()+ machine.hold_download.set()+ _finish()++ assert semantic_search.get_active() is None+ assert semantic_setup.status(config)["state"] == "off"+++def test_switching_it_off_releases_the_model(+ config: SimpleNamespace, machine: _Machine+) -> None:+ semantic_setup.start(config)+ _finish()++ semantic_setup.stop()++ assert semantic_search.get_active() is None+ assert machine.encoder.closed == 1+++def test_a_second_start_joins_the_run_in_flight(+ config: SimpleNamespace, machine: _Machine+) -> None:+ machine.hold_download.clear()+ semantic_setup.start(config)+ first = semantic_setup._run.thread+ semantic_setup.start(config)+ assert semantic_setup._run.thread is first+ machine.hold_download.set()+ _finish()+ assert machine.downloads == 1+++def test_off_and_on_again_during_the_download_still_ends_ready(+ config: SimpleNamespace, machine: _Machine+) -> None:+ machine.hold_download.clear()+ semantic_setup.start(config)+ first = semantic_setup._run.thread++ semantic_setup.stop()+ semantic_setup.start(config)+ assert semantic_setup._run.thread is not first, "an overtaken run is not joined"++ machine.hold_download.set()+ _finish()+ assert first is not None and not first.is_alive()+ assert semantic_setup.status(config)["state"] == "ready"+ assert semantic_search.get_active() is not None+++class _HoldingEncoder(FakeSemanticEncoder):+ """Blocks inside the first page until the test lets it go."""++ def __init__(self) -> None:+ super().__init__()+ self.entered = threading.Event()+ self.release = threading.Event()++ def encode(self, texts, *, wait=True): # type: ignore[no-untyped-def]+ self.entered.set()+ self.release.wait(timeout=5)+ return super().encode(texts, wait=wait)+++def test_switching_it_off_while_the_vault_is_read_ends_the_run_at_that_page(+ config: SimpleNamespace, machine: _Machine+) -> None:+ vault = config.wiki_integration.vault_root+ for name in ("bea", "cleo", "dana"):+ (vault / "entities" / f"{name}.md").write_text(+ f"---\ntype: entity\n---\n# {name}\n\n- A friend of the family\n", encoding="utf-8"+ )+ machine.model_on_disk = True+ machine.encoder = _HoldingEncoder()+ semantic_setup.start(config)+ assert machine.encoder.entered.wait(timeout=5)+ assert semantic_setup.status(config)["state"] == "indexing"++ semantic_setup.stop()+ machine.encoder.release.set()+ _finish()++ assert len(machine.encoder.calls) == 1, "the other three pages were never encoded"+ assert semantic_search.get_active() is None+ assert semantic_setup.status(config)["state"] == "off"+++def test_a_model_that_cannot_read_any_page_is_an_error_and_is_taken_down(+ config: SimpleNamespace, machine: _Machine+) -> None:+ class Dead(FakeSemanticEncoder):+ def encode(self, texts, *, wait=True): # type: ignore[no-untyped-def]+ raise RuntimeError("the model file is damaged")++ machine.model_on_disk = True+ machine.encoder = Dead()+ semantic_setup.start(config)+ _finish()++ report = semantic_setup.status(config)+ assert report["state"] == "error"+ assert "could not be set up" in report["message"]+ assert semantic_search.get_active() is None, "no half-alive search behind a failed switch"+++def test_a_wiki_that_is_switched_off_is_an_honest_error(+ config: SimpleNamespace, machine: _Machine+) -> None:+ config.wiki_integration.enabled = False+ assert semantic_setup.start(config) is False+ report = semantic_setup.status(config)+ assert report["state"] == "error"+ assert "wiki is switched off" in report["message"]+ assert machine.downloads == 0+++def test_a_server_that_refuses_the_file_is_not_blamed_on_the_connection(+ config: SimpleNamespace, machine: _Machine+) -> None:+ request = httpx.Request("GET", "https://example.test/model")+ machine.download_error = httpx.HTTPStatusError(+ "gone", request=request, response=httpx.Response(404, request=request)+ )+ semantic_setup.start(config)+ _finish()++ message = semantic_setup.status(config)["message"]+ assert "server refused" in message+ assert "internet connection" not in message+++def test_the_state_never_carries_an_exception_text(+ config: SimpleNamespace, machine: _Machine+) -> None:+ """The state is served over the API; an error text can hold local paths."""+ machine.download_error = PermissionError(13, "denied", "/home/someone/secret/model.part")+ semantic_setup.start(config)+ _finish()++ report = semantic_setup.status(config)+ assert report["state"] == "error"+ assert "stored on this disk" in report["message"]+ assert "someone" not in report["message"]+ assert "denied" not in report["message"]diff --git a/tests/unit/memory/wiki/test_semantic_tokenizer.py b/tests/unit/memory/wiki/test_semantic_tokenizer.pynew file mode 100644index 0000000000..9b15aafc47--- /dev/null+++ b/tests/unit/memory/wiki/test_semantic_tokenizer.py@@ -0,0 +1,91 @@+"""The plain-Python tokenizer segments like the vocabulary's reference does.++The real vocabulary has 250,000 pieces and is downloaded with the model, so+these tests run on a small hand-made one. Each case pins one rule of the+algorithm; agreement with the reference library on real text was measured+separately on 2,300 passages of a live vault.+"""+from __future__ import annotations++import json+from pathlib import Path++import pytest++from jarvis.memory.wiki.semantic_tokenizer import UnigramTokenizer, normalize++W = "▁" # the word-start marker++VOCAB: list[tuple[str, float]] = [+ ("<s>", 0.0),+ ("<pad>", 0.0),+ ("</s>", 0.0),+ ("<unk>", 0.0),+ (W, -3.0),+ (f"{W}un", -2.0),+ (f"{W}unhappy", -9.0),+ ("happy", -2.5),+ ("h", -6.0),+ ("a", -6.0),+ ("p", -6.0),+ ("y", -6.0),+ (f"{W}a", -2.0),+ (f"{W}b", -2.0),+ ("b", -5.0),+]+ID = {piece: index for index, (piece, _score) in enumerate(VOCAB)}+++def tokenizer() -> UnigramTokenizer:+ return UnigramTokenizer(VOCAB, unk_id=3, bos_id=0, eos_id=2)+++def test_picks_the_segmentation_with_the_best_total_score(tokenizer: UnigramTokenizer) -> None:+ # "_un" + "happy" scores -4.5 and beats the single piece "_unhappy" at -9.+ assert tokenizer.encode("unhappy") == [0, ID[f"{W}un"], ID["happy"], 2]+++def test_every_word_starts_with_the_marker(tokenizer: UnigramTokenizer) -> None:+ assert tokenizer.encode("a b") == [0, ID[f"{W}a"], ID[f"{W}b"], 2]+++def test_a_run_of_uncovered_characters_is_one_unknown(tokenizer: UnigramTokenizer) -> None:+ # "z" and "q" are in no piece; together they become a single unknown id.+ assert tokenizer.encode("azqb") == [0, ID[f"{W}a"], 3, ID["b"], 2]+++def test_empty_and_blank_text_is_just_the_markers(tokenizer: UnigramTokenizer) -> None:+ assert tokenizer.encode("") == [0, 2]+ assert tokenizer.encode(" \t\n ") == [0, 2]+++def test_a_long_text_keeps_its_start_and_the_end_marker(tokenizer: UnigramTokenizer) -> None:+ ids = tokenizer.encode("a " * 50, max_tokens=8)+ assert len(ids) == 8+ assert ids[0] == 0 and ids[-1] == 2+ assert ids[1:-1] == [ID[f"{W}a"]] * 6+++def test_normalize_folds_width_whitespace_and_invisible_characters() -> None:+ assert normalize("ab") == "ab" # full-width letters+ assert normalize("a b\tc\nd") == "a b c d" # every whitespace is a space+ assert normalize("abc") == "abc" # zero width, soft hyphen, BOM+ assert normalize("fi") == "fi" # ligature+++def test_loads_the_vocabulary_from_a_tokenizer_file(tmp_path: Path) -> None:+ path = tmp_path / "tokenizer.json"+ path.write_text(+ json.dumps({"model": {"type": "Unigram", "unk_id": 3, "vocab": VOCAB}}),+ encoding="utf-8",+ )+ loaded = UnigramTokenizer.from_file(path)+ assert loaded.encode("unhappy") == [0, ID[f"{W}un"], ID["happy"], 2]+++def test_rejects_a_file_that_is_not_a_unigram_vocabulary(tmp_path: Path) -> None:+ path = tmp_path / "tokenizer.json"+ path.write_text(json.dumps({"model": {"type": "WordPiece", "vocab": {}}}), encoding="utf-8")+ with pytest.raises(ValueError, match="unigram"):+ UnigramTokenizer.from_file(path)diff --git a/tests/unit/memory/wiki/test_semantic_wiring.py b/tests/unit/memory/wiki/test_semantic_wiring.pynew file mode 100644index 0000000000..4905b15d4c--- /dev/null+++ b/tests/unit/memory/wiki/test_semantic_wiring.py@@ -0,0 +1,121 @@+"""Semantic search reaches the watcher, the recall tool and the config file."""+from __future__ import annotations++import asyncio+import tomllib+from collections.abc import Iterator+from pathlib import Path++import pytest++from jarvis.core.bus import EventBus+from jarvis.core.config import WikiContextConfig+from jarvis.core.config_writer import set_wiki_semantic_search+from jarvis.memory.wiki import semantic_search+from jarvis.memory.wiki.search import VaultSearch+from jarvis.memory.wiki.watcher import WikiWatcher+from jarvis.plugins.tool.wiki_recall import WikiRecallTool+from tests.fakes.fake_semantic_encoder import FakeSemanticEncoder++[email protected](autouse=True)+def _no_active_search() -> Iterator[None]:+ semantic_search.deactivate()+ yield+ semantic_search.deactivate()+++def vault(tmp_path: Path) -> Path:+ root = tmp_path / "vault"+ (root / "entities").mkdir(parents=True)+ return root+++def _write(vault: Path, name: str, body: str) -> Path:+ path = vault / "entities" / name+ path.write_text(f"---\ntype: entity\n---\n{body}", encoding="utf-8")+ return path+++def test_semantic_search_ships_switched_off() -> None:+ assert WikiContextConfig().semantic_search is False+++def test_the_switch_is_written_as_one_key(tmp_path: Path) -> None:+ path = tmp_path / "jarvis.toml"+ path.write_text("[wiki_context]\nenabled = true\n", encoding="utf-8")++ set_wiki_semantic_search(True, path=path)++ block = tomllib.loads(path.read_text(encoding="utf-8"))["wiki_context"]+ assert block == {"enabled": True, "semantic_search": True}+++def test_the_switch_rejects_anything_but_a_boolean(tmp_path: Path) -> None:+ path = tmp_path / "jarvis.toml"+ path.write_text("", encoding="utf-8")+ with pytest.raises(TypeError):+ set_wiki_semantic_search("yes", path=path) # type: ignore[arg-type]+ assert path.read_text(encoding="utf-8") == ""+++def test_a_page_the_watcher_sees_change_is_searchable_by_meaning(+ vault: Path, tmp_path: Path+) -> None:+ db_path = tmp_path / "wiki.db"+ active = semantic_search.activate(vault, db_path=db_path, encoder=FakeSemanticEncoder())+ active.sync()+ watcher = WikiWatcher(vault, EventBus(), db_path=db_path)+ page = _write(vault, "anna.md", "# Anna\n\n- Meine Schwester\n- Geburtstag am 4. Mai\n")++ watcher._maintain_index(page, "modified", "entities/anna.md")+ assert [hit.title for hit in active.search("when is my sister's birthday")] == ["Anna"]++ page.unlink()+ watcher._maintain_index(page, "deleted", "entities/anna.md")+ assert active.search("when is my sister's birthday") == []+++def test_the_watcher_leaves_a_search_for_another_vault_alone(+ vault: Path, tmp_path: Path+) -> None:+ encoder = FakeSemanticEncoder()+ semantic_search.activate(tmp_path / "other", db_path=tmp_path / "wiki.db", encoder=encoder)+ watcher = WikiWatcher(vault, EventBus(), db_path=tmp_path / "wiki.db")+ page = _write(vault, "anna.md", "# Anna\n\n- Meine Schwester\n")++ watcher._maintain_index(page, "modified", "entities/anna.md")++ assert encoder.calls == []+++def test_the_watcher_works_unchanged_while_semantic_search_is_off(+ vault: Path, tmp_path: Path+) -> None:+ db_path = tmp_path / "wiki.db"+ watcher = WikiWatcher(vault, EventBus(), db_path=db_path)+ page = _write(vault, "anna.md", "# Anna\n\n- Meine Schwester\n")++ watcher._maintain_index(page, "modified", "entities/anna.md")++ assert [hit.title for hit in VaultSearch(vault, db_path=db_path).search("Schwester")] == [+ "Anna"+ ]+++def test_the_recall_tool_adds_pages_found_by_meaning(vault: Path, tmp_path: Path) -> None:+ db_path = tmp_path / "wiki.db"+ _write(vault, "anna.md", "# Anna\n\n- Meine Schwester\n- Geburtstag am 4. Mai\n")+ tool = WikiRecallTool(VaultSearch(vault, db_path=db_path))+ query = {"query": "sister birthday"}++ before = asyncio.run(tool.execute(query, None))+ assert "No wiki matches" in before.output++ active = semantic_search.activate(vault, db_path=db_path, encoder=FakeSemanticEncoder())+ active.sync()++ after = asyncio.run(tool.execute(query, None))+ assert "**Anna**" in after.output+ assert "entities" in after.outputdiff --git a/tests/unit/ui/web/test_wiki_semantic_routes.py b/tests/unit/ui/web/test_wiki_semantic_routes.pynew file mode 100644index 0000000000..c489aef389--- /dev/null+++ b/tests/unit/ui/web/test_wiki_semantic_routes.py@@ -0,0 +1,200 @@+"""The semantic search switch over REST, and its effect on the wiki search route."""+from __future__ import annotations++from collections.abc import Iterator+from pathlib import Path+from types import SimpleNamespace+from typing import Any++import pytest+from fastapi import FastAPI+from fastapi.testclient import TestClient++from jarvis.core import config_writer+from jarvis.memory.wiki import fts_index, semantic_model, semantic_search, semantic_setup+from jarvis.memory.wiki.db_path import resolve_wiki_db_path+from jarvis.ui.web.wiki_routes import router as wiki_router+from tests.fakes.fake_semantic_encoder import FakeSemanticEncoder++[email protected](autouse=True)+def _fresh_state(monkeypatch: pytest.MonkeyPatch) -> Iterator[None]:+ monkeypatch.setattr(semantic_setup, "_run", semantic_setup._Run())+ semantic_search.deactivate()+ yield+ semantic_search.deactivate()+++def saved(monkeypatch: pytest.MonkeyPatch) -> list[bool]:+ """Record what the route persists instead of touching a real config file."""+ writes: list[bool] = []+ monkeypatch.setattr(config_writer, "set_wiki_semantic_search", writes.append)+ return writes+++def client(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> TestClient:+ vault = tmp_path / "vault"+ (vault / "entities").mkdir(parents=True)+ (vault / "entities" / "anna.md").write_text(+ "---\ntype: entity\n---\n# Anna\n\n- Meine Schwester\n- Geburtstag am 4. Mai\n",+ encoding="utf-8",+ )+ data_dir = tmp_path / "data"+ db_path = resolve_wiki_db_path(data_dir)+ db_path.parent.mkdir(parents=True)+ import sqlite3++ conn = sqlite3.connect(str(db_path))+ try:+ fts_index.rebuild_index(vault, conn)+ finally:+ conn.close()++ encoder = FakeSemanticEncoder()+ real_activate = semantic_search.activate++ def activate(vault_root: Path, **kwargs: Any) -> Any:+ return real_activate(vault_root, **{**kwargs, "encoder": encoder})++ # The search route opens the word index from the default database path.+ monkeypatch.setattr("jarvis.memory.wiki.search._default_db_path", lambda: db_path)+ monkeypatch.setattr(semantic_model, "runtime_available", lambda: True)+ monkeypatch.setattr(semantic_model, "model_present", lambda _d=None: True)+ monkeypatch.setattr(semantic_search, "activate", activate)++ app = FastAPI()+ app.include_router(wiki_router)+ app.state.config = SimpleNamespace(+ wiki_context=SimpleNamespace(semantic_search=False),+ wiki_integration=SimpleNamespace(vault_root=vault),+ memory=SimpleNamespace(data_dir=data_dir),+ )+ return TestClient(app)+++def _finish() -> None:+ thread = semantic_setup._run.thread+ assert thread is not None+ thread.join(timeout=10)+++def test_the_switch_is_off_on_a_fresh_install(client: TestClient) -> None:+ body = client.get("/api/wiki/semantic-search").json()+ assert body["enabled"] is False+ assert body["state"] == "off"+ assert body["download_bytes"] == semantic_model.DOWNLOAD_BYTES+++def test_switching_it_on_persists_the_choice_and_reports_progress(+ client: TestClient, saved: list[bool]+) -> None:+ body = client.put("/api/wiki/semantic-search", json={"enabled": True}).json()+ assert body["enabled"] is True+ assert body["state"] in {"downloading", "indexing", "ready"}+ assert saved == [True]++ _finish()+ body = client.get("/api/wiki/semantic-search").json()+ assert body["state"] == "ready"+ assert (body["pages"], body["passages"]) == (1, 2)+++def test_the_wiki_search_gains_pages_found_by_meaning(+ client: TestClient, saved: list[bool]+) -> None:+ question = "when is my sister's birthday"+ before = client.get("/api/wiki/search", params={"q": question}).json()+ assert before["hits"] == [], "no word of the question is in the German note"++ client.put("/api/wiki/semantic-search", json={"enabled": True})+ _finish()++ after = client.get("/api/wiki/search", params={"q": question}).json()+ assert [(hit["slug"], hit["by_meaning"]) for hit in after["hits"]] == [("anna", True)]+++def test_word_hits_are_marked_as_such(client: TestClient, saved: list[bool]) -> None:+ client.put("/api/wiki/semantic-search", json={"enabled": True})+ _finish()++ body = client.get("/api/wiki/search", params={"q": "Schwester"}).json()++ assert [(hit["slug"], hit["by_meaning"]) for hit in body["hits"]] == [("anna", False)]+++def test_switching_it_off_stops_the_engine_and_persists_the_choice(+ client: TestClient, saved: list[bool]+) -> None:+ client.put("/api/wiki/semantic-search", json={"enabled": True})+ _finish()++ body = client.put("/api/wiki/semantic-search", json={"enabled": False}).json()++ assert body["enabled"] is False+ assert body["state"] == "off"+ assert saved == [True, False]+ assert semantic_search.get_active() is None+ assert client.app.state.config.wiki_context.semantic_search is False # type: ignore[attr-defined]+++def test_a_setting_that_cannot_be_saved_changes_nothing(+ client: TestClient, monkeypatch: pytest.MonkeyPatch+) -> None:+ def refuse(_enabled: bool) -> None:+ raise OSError("disk is read-only")++ monkeypatch.setattr(config_writer, "set_wiki_semantic_search", refuse)++ response = client.put("/api/wiki/semantic-search", json={"enabled": True})++ assert response.status_code == 500+ assert semantic_search.get_active() is None+ assert client.app.state.config.wiki_context.semantic_search is False # type: ignore[attr-defined]+++def test_the_body_must_be_a_boolean(client: TestClient) -> None:+ assert client.put("/api/wiki/semantic-search", json={"enabled": "maybe"}).status_code == 422+++def test_a_busy_model_does_not_hold_the_word_hits_back(+ client: TestClient, saved: list[bool], monkeypatch: pytest.MonkeyPatch+) -> None:+ import time++ from jarvis.memory.wiki.search import SearchHit+ from jarvis.ui.web import wiki_routes++ client.put("/api/wiki/semantic-search", json={"enabled": True})+ _finish()++ def slow(hits: list[Any], _query: str, **_kwargs: Any) -> list[Any]:+ time.sleep(0.5)+ late = SearchHit(title="Late", path=Path("late.md"), snippet="", score=0.9)+ return [*hits, late]++ monkeypatch.setattr(wiki_routes, "with_semantic_hits", slow)+ monkeypatch.setattr(wiki_routes, "_SEMANTIC_SEARCH_TIMEOUT_S", 0.05)++ body = client.get("/api/wiki/search", params={"q": "Schwester"}).json()++ # The answer went out with the word hits alone; had the route waited for+ # the model, the late hit would be in it.+ assert [(hit["slug"], hit["by_meaning"]) for hit in body["hits"]] == [("anna", False)]+++def test_a_failing_semantic_engine_leaves_the_word_hits_standing(+ client: TestClient, monkeypatch: pytest.MonkeyPatch+) -> None:+ from jarvis.ui.web import wiki_routes++ def broken(*_args: Any, **_kwargs: Any) -> list[Any]:+ raise RuntimeError("native session died")++ monkeypatch.setattr(wiki_routes, "with_semantic_hits", broken)++ body = client.get("/api/wiki/search", params={"q": "Schwester"}).json()++ assert body["ok"] is True+ assert [hit["slug"] for hit in body["hits"]] == ["anna"]