Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(ultrawiki): couple the brain — mode-aware recall tool + context injector
Ruben Lütkee1ea7a868fbd
diff --git a/jarvis/brain/wiki_context.py b/jarvis/brain/wiki_context.pyindex 6acd5d0956..a7135bc1f0 100644--- a/jarvis/brain/wiki_context.py+++ b/jarvis/brain/wiki_context.py@@ -24,16 +24,50 @@ Relevance contract (``jarvis.brain.wiki_relevance``):When the gate declines a turn the knowledge is not lost: the router brainholds the ``wiki-recall`` tool and can look something up deliberately.+UltraWiki mode (decision D-5, either-or):+ While UltraWiki mode is ON and its store is open, the candidates come from+ the UltraWiki store instead of the vault — never from both. Only the+ RETRIEVAL changes; the three gates above still decide what may be injected,+ because this surface is unsolicited and the Bugatti mandate is retrieval-+ agnostic: silence beats a personal fact nobody asked for.++ Two gates are mapped honestly onto UltraWiki's different score semantics:++ * The within-call relative floor is REPLACED by a keyword-leg requirement.+ An UltraWiki ``score`` is an RRF fusion rank — ordinal by construction, so+ a relative floor over it certifies nothing (a fusion over garbage still+ produces a confident-looking number one). A candidate that only the vector+ leg produced has no lexical evidence at all, so the deterministic+ substitute is: the keyword leg must have seen it too.+ * Coverage of the question's content terms is applied unchanged — it never+ depended on scores in the first place.++ The absolute measure UltraWiki does have (the rerank grade, which+ ``enforce_floor`` gates on) is deliberately NOT used here: grading costs a+ model call, which is exactly what may not happen on this path (AP-9). Design+ doc 03 anticipates that case — an ungraded candidate stays the caller's+ deterministic gate's responsibility, which is this module plus+ ``wiki_relevance``.+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- (cold filesystem, network FS, etc.) therefore cannot block the voice path.- The relevance gate itself is regex-only and IO-free (AP-9/AP-11).+ milliseconds (``ultra_latency_budget_ms`` for the UltraWiki path). It uses+ ``asyncio.wait_for`` to enforce this. A slow vault (cold filesystem, network+ FS, etc.) therefore cannot block the voice path. The relevance gate itself+ is regex-only and IO-free (AP-9/AP-11).++ The UltraWiki path gets its own, larger budget because it is a database+ query rather than a grep, and because its vector leg embeds the query text+ when an embedding provider is configured — cheap on a local endpoint,+ a network round-trip on a cloud one. The rerank stage (a second model call)+ is switched off outright. Whatever exceeds the budget is dropped: the turn+ proceeds with NO context rather than waiting.Fallback contract:- When ``search`` is ``None`` (Agent B not yet merged), the injector silently- does nothing. Pass ``search=None`` from the factory; every ``maybe_inject``- call returns the prompt unchanged.+ When ``search`` is ``None`` (Agent B not yet merged) and no UltraWiki+ service is available, the injector silently does nothing. Pass+ ``search=None`` from the factory; every ``maybe_inject`` call returns the+ prompt unchanged."""from __future__ import annotations@@ -41,7 +75,7 @@ import asyncioimport loggingimport reimport time-from typing import TYPE_CHECKING+from typing import TYPE_CHECKING, Anyif TYPE_CHECKING:from jarvis.memory.wiki.search import VaultSearch@@ -112,6 +146,22 @@ _STOPWORDS: frozenset[str] = frozenset({# Tokenize on whitespace and common punctuation_TOKEN_RE = re.compile(r"[^\w\s]|\s+", re.UNICODE)+#: Time budget for the UltraWiki retrieval leg. Its own knob because it is a+#: store query (plus a possible query embedding) rather than the vault's grep;+#: design doc 03 allots <= 150 ms to the fan-out inside a <= 900 ms+#: to-first-spoken-token budget, and this stays in that order of magnitude.+DEFAULT_ULTRA_LATENCY_BUDGET_MS = 250++#: How many UltraWiki candidates the gates get to judge. Small on purpose: the+#: block is capped at ``max_chars`` anyway and every extra candidate is one more+#: chance for an off-topic personal fact to slip past.+DEFAULT_ULTRA_K = 5++#: The retrieval leg that must have seen an UltraWiki candidate before it may+#: be injected — the deterministic stand-in for an absolute score (see the+#: module docstring).+_KEYWORD_LEG = "keyword"+def _extract_keywords(text: str,@@ -195,11 +245,15 @@ class WikiContextInjector:relevance_gate: bool = True,min_coverage: float = DEFAULT_MIN_COVERAGE,min_relative_score: float = DEFAULT_MIN_RELATIVE_SCORE,+ ultra_latency_budget_ms: int = DEFAULT_ULTRA_LATENCY_BUDGET_MS,+ ultra_k: int = DEFAULT_ULTRA_K,) -> None:self._search = searchself._max_chars = max_charsself._latency_budget_ms = latency_budget_msself._min_keyword_length = min_keyword_length+ self._ultra_latency_budget_ms = ultra_latency_budget_ms+ self._ultra_k = ultra_k# Escape hatch: ``relevance_gate=False`` restores the pre-gate# behaviour (search every turn, inject every hit). Kept so a user who# believes the gate is too strict can prove it from config rather than@@ -225,10 +279,11 @@ class WikiContextInjector:) -> str:"""Return system_prompt unchanged on any of:- * ``search is None``+ * no memory at all (``search is None`` and no UltraWiki service)* no extractable keywords from ``user_text``- * ``VaultSearch.search`` exceeds ``latency_budget_ms``- * search returns zero hits+ * the retrieval exceeds its latency budget+ * retrieval returns zero hits+ * nothing survives the relevance gatesOtherwise returns::@@ -239,12 +294,17 @@ class WikiContextInjector:Logs exactly one line per call at INFO::- WikiContextInjector injected=<bool> hits=<n> latency_ms=<int>+ WikiContextInjector injected=<bool> hits=<n> latency_ms=<int> …"""t0 = time.monotonic()- # Fast-path: no search engine available (Agent B not merged yet)- if self._search is None:+ # Which memory answers this turn — UltraWiki when the mode is on and+ # its store is open, the vault otherwise. Never both (D-5).+ ultra_service = _active_ultrawiki_service()++ # Fast-path: no memory available at all (Agent B not merged yet, and+ # no UltraWiki service in this runtime)+ if ultra_service is None and self._search is None:self._miss(t0, "no_search")return system_prompt@@ -270,19 +330,24 @@ class WikiContextInjector:query = " ".join(keywords)# Run search with a strict latency budget+ ultra = ultra_service is not None+ budget_ms = self._ultra_latency_budget_ms if ultra else self._latency_budget_mstry:hits = await asyncio.wait_for(- _run_search(self._search, query),- timeout=self._latency_budget_ms / 1000.0,+ _run_ultra_search(ultra_service, query, self._ultra_k)+ if ultra+ else _run_search(self._search, query),+ timeout=budget_ms / 1000.0,)except TimeoutError:log.warning(- "WikiContextInjector timed out after %dms (budget=%dms) — "- "skipping wiki context for this turn",+ "WikiContextInjector timed out after %dms (budget=%dms, "+ "source=%s) — skipping wiki context for this turn",int((time.monotonic() - t0) * 1000),- self._latency_budget_ms,+ budget_ms,+ "ultrawiki" if ultra else "vault",)- self._miss(t0, "timeout")+ self._miss(t0, "ultra_timeout" if ultra else "timeout")return system_promptexcept Exception: # noqa: BLE001log.warning(@@ -290,7 +355,7 @@ class WikiContextInjector:"skipping wiki context",exc_info=True,)- self._miss(t0, "search_error")+ self._miss(t0, "ultra_search_error" if ultra else "search_error")return system_promptif not hits:@@ -301,11 +366,19 @@ class WikiContextInjector:# 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:+ if ultra:+ # An RRF score is ordinal, so the relative floor is neutralised+ # (0.0) and the keyword leg carries that half of the gate+ # instead — see the module docstring.+ hits = [hit for hit in hits if _has_keyword_leg(hit)]+ if not hits:+ self._miss(t0, "no_keyword_leg")+ return system_prompthits = relevant_hits(hits,query,min_coverage=self._min_coverage,- min_relative_score=self._min_relative_score,+ min_relative_score=0.0 if ultra else self._min_relative_score,)if not hits:self._miss(t0, "no_relevant_hits")@@ -322,12 +395,18 @@ class WikiContextInjector:# has no body snippet by contract — fall back to its leading text# so the entry carries content instead of just a bare title.text = hit.snippet or getattr(hit, "preview", "") or ""- entry = f"**{hit.title}**: {text}"+ if ultra:+ # An UltraWiki snippet can span lines; the block is one entry+ # per line. An ingested item may also carry no title at all,+ # in which case its source is the only honest label.+ text = " ".join(text.split())+ title = hit.title or (getattr(hit, "source_id", "") if ultra else "")+ entry = f"**{title}**: {text}"if chars_used + len(entry) + 1 > self._max_chars:# Try trimming to fit the remaining budget- remaining = self._max_chars - chars_used - len(f"**{hit.title}**: ") - 1+ remaining = self._max_chars - chars_used - len(f"**{title}**: ") - 1if remaining >= 40: # only worth including if enough chars remain- entry = f"**{hit.title}**: {text[:remaining]}…"+ entry = f"**{title}**: {text[:remaining]}…"else:breakcontext_parts.append(entry)@@ -345,9 +424,10 @@ class WikiContextInjector:telemetry.inc("wiki_context_hits")log.info(- "WikiContextInjector injected=True hits=%d latency_ms=%d",+ "WikiContextInjector injected=True hits=%d latency_ms=%d source=%s",hits_included,latency_ms,+ "ultrawiki" if ultra else "vault",)return augmented@@ -360,3 +440,52 @@ async def _run_search(search: VaultSearch, query: str) -> list:"""loop = asyncio.get_event_loop()return await loop.run_in_executor(None, search.search, query)+++def _active_ultrawiki_service() -> Any | None:+ """The live UltraWiki service while it can answer, else ``None``.++ Lazy import (AP-26): with the mode off this is one ``sys.modules`` lookup+ per turn and nothing else — no config read, no disk, no network.+ """+ try:+ from jarvis.ultrawiki.service import active_search_service++ return active_search_service()+ except Exception: # noqa: BLE001 — an unavailable mode is not an error here+ log.debug("WikiContextInjector: UltraWiki lookup failed", exc_info=True)+ return None+++async def _run_ultra_search(service: Any, query: str, k: int) -> list:+ """Candidate retrieval from the UltraWiki store — cheap legs only.++ ``rerank=False`` keeps the grading model call off this path (AP-9);+ ``expand_context=False`` skips the neighbour lookups, which are evidence+ for an answer the user asked for, not for a prompt hint. ``enforce_floor``+ would be a no-op without grades and is left off deliberately: the gates in+ :meth:`WikiContextInjector.maybe_inject` are what stands in for it.+ """+ return await service.search(+ query=query,+ k=k,+ rerank=False,+ enforce_floor=False,+ expand_context=False,+ )+++def _has_keyword_leg(hit: Any) -> bool:+ """True when the keyword leg produced this candidate.++ A vector-only candidate matched on embedding proximity alone. Nothing in+ an RRF score can tell "close in meaning" from "closest of a bad lot", so+ an unsolicited surface must not inject it. Hits from a store that reports+ no legs at all are treated as keyword hits — the keyword leg is the one+ that always runs (search.py), so an absent label is a missing report, not+ evidence of a vector-only match.+ """+ legs = getattr(hit, "matched_by", None)+ if not legs:+ return True+ return _KEYWORD_LEG in tuple(legs)diff --git a/jarvis/plugins/tool/wiki_recall.py b/jarvis/plugins/tool/wiki_recall.pyindex 6015d69beb..ce3962a16a 100644--- a/jarvis/plugins/tool/wiki_recall.py+++ b/jarvis/plugins/tool/wiki_recall.py@@ -28,9 +28,29 @@ Vault-root resolution (§6 AGENT-B, spec A7):root anchors to the repo root, never the process CWD. If the configfield is unavailable at construction time, the tool falls back to theresolver's default vault location and logs a single WARNING.++Mode awareness — UltraWiki (decision D-5, either-or):+ While UltraWiki mode is ON and its store is open, this tool searches the+ UltraWiki store instead of the vault: that store is where the user's+ knowledge actually lives in Ultra mode, and answering from the vault would+ make the brain claim ignorance of thousands of ingested items. The two+ memories are never merged — the mode picks exactly one.++ No relevance floor is applied here. The user (or the brain acting on the+ user's explicit question) ASKED for this lookup, which is the Ask-view+ semantics of design doc 03: hiding evidence from someone who searched is a+ different defect than volunteering it unasked. The unsolicited surface —+ the system-prompt context injector — carries the gate instead.++ Every UltraWiki failure mode degrades to the vault search with one log+ line, and the whole UltraWiki call is bounded by+ :data:`_ULTRA_TIMEOUT_S`, so a cold store or a dead embedding endpoint can+ never leave the brain with a dead tool. With the mode off, nothing below+ runs and the behaviour is exactly what it was before."""from __future__ import annotations+import asyncioimport loggingfrom pathlib import Pathfrom typing import TYPE_CHECKING, Any@@ -42,6 +62,17 @@ if TYPE_CHECKING:log = logging.getLogger(__name__)+#: Hard ceiling for the whole UltraWiki lookup (fan-out + rerank + context+#: expansion). Generous compared to the injector's budget because this is a+#: deliberate tool call the brain is already waiting on, but still bounded:+#: past it the vault answers instead of the turn stalling.+_ULTRA_TIMEOUT_S = 2.5++#: Per-hit snippet cap. Vault snippets are short by construction; an UltraWiki+#: snippet can be a whole message or wiki section, and five of them unbounded+#: would crowd the router prompt.+_ULTRA_SNIPPET_CHARS = 240+class WikiRecallTool:"""Router-tier keyword search over the long-term Obsidian wiki vault."""@@ -90,20 +121,32 @@ class WikiRecallTool:Paths are rendered relative to ``vault_root`` so the brain sees``10-notes/Harald.md``, not an absolute Windows path.+ In UltraWiki mode the same block is rendered from the UltraWiki store,+ with the source, timestamp and permalink in the citation slot the+ vault path fills with a relative page path.+Returns-------ToolResult(success=True, output=<markdown>)When hits are found.ToolResult(success=True, output="No matches …")- When the vault is available but nothing matches.+ When the memory is available but nothing matches.ToolResult(success=False, error="vault unavailable")- When the vault root does not exist at execute time.+ When UltraWiki is not the active memory and the vault root does+ not exist at execute time."""query = str(args.get("query", "")).strip()k = int(args.get("k", 5))# Clamp defensively — schema validation may not have run upstream.k = max(1, min(k, 10))+ # UltraWiki mode owns the answer when it is on and ready (D-5); a+ # None here is either "mode off" or "UltraWiki could not answer", and+ # both continue into the unchanged vault path below.+ ultra_output = await _ultrawiki_block(query, k)+ if ultra_output is not None:+ return ToolResult(success=True, output=ultra_output)+vault_root = self._search._root # type: ignore[attr-defined]# Privacy: query is DEBUG only.@@ -141,6 +184,99 @@ class WikiRecallTool:return ToolResult(success=True, output="\n".join(lines))+def _active_ultrawiki_service() -> Any | None:+ """The live UltraWiki service while it can answer, else ``None``.++ Lazy import (AP-26 + the plugin no-module-level-``jarvis``-import rule):+ with UltraWiki off this costs one module lookup and nothing else.+ """+ try:+ from jarvis.ultrawiki.service import active_search_service++ return active_search_service()+ except Exception: # noqa: BLE001 — an unavailable mode is never an error here+ log.debug("wiki-recall: UltraWiki service lookup failed", exc_info=True)+ return None+++async def _ultrawiki_block(query: str, k: int) -> str | None:+ """The rendered UltraWiki answer, or ``None`` to fall back to the vault.++ ``None`` means one of: the mode is off, the store is not open, the lookup+ timed out, or it raised. An UltraWiki search that ran and found nothing is+ NOT a fallback — it is an honest empty answer from the active memory, and+ returns the same "no matches" line the vault path would.+ """+ service = _active_ultrawiki_service()+ if service is None:+ return None+ try:+ hits = await asyncio.wait_for(+ service.search(+ query=query,+ k=k,+ rerank=True,+ enforce_floor=False,+ expand_context=True,+ ),+ timeout=_ULTRA_TIMEOUT_S,+ )+ except TimeoutError:+ log.warning(+ "wiki-recall: UltraWiki search exceeded %.1fs — answering from the "+ "wiki vault instead",+ _ULTRA_TIMEOUT_S,+ )+ return None+ except Exception as exc: # noqa: BLE001 — degrade to the vault, never a dead tool+ log.warning(+ "wiki-recall: UltraWiki search failed (%s) — answering from the "+ "wiki vault instead",+ exc,+ )+ return None++ hits = list(hits or ())+ log.info("wiki-recall: %d UltraWiki hit(s) for query (k=%d)", len(hits), k)+ if not hits:+ return f'No wiki matches found for "{query}".'+ lines = [f'## Wiki hits for "{query}"']+ lines.extend(_render_ultrawiki_hit(hit) for hit in hits[:k])+ return "\n".join(lines)+++def _render_ultrawiki_hit(hit: Any) -> str:+ """One hit in the tool's established line shape.++ ``- **Title** — snippet (citation)``, where the citation slot carries the+ source, the timestamp and the permalink instead of the vault's relative+ page path. Keeping the shape stable matters: the router prompt has been+ tuned against it.+ """+ source = str(getattr(hit, "source_id", "") or "")+ title = str(getattr(hit, "title", "") or "").strip() or source or "(untitled)"+ text = " ".join(str(getattr(hit, "snippet", "") or "").split())+ if not text:+ # A hit whose own snippet is empty still carries its neighbouring+ # evidence from the context-expansion stage — better than a bare title.+ context = getattr(hit, "context", ()) or ()+ text = " ".join(str(context[0]).split()) if context else ""+ if len(text) > _ULTRA_SNIPPET_CHARS:+ text = text[:_ULTRA_SNIPPET_CHARS].rstrip() + "…"+ citation = " · ".join(+ part+ for part in (+ source,+ str(getattr(hit, "timestamp_utc", "") or ""),+ str(getattr(hit, "permalink", "") or ""),+ )+ if part+ )+ snippet_part = f" — {text}" if text else ""+ citation_part = f" ({citation})" if citation else ""+ return f"- **{title}**{snippet_part}{citation_part}"++def _build_search_instance() -> VaultSearch:"""Build a ``VaultSearch`` with the configured vault root.diff --git a/jarvis/ui/web/server.py b/jarvis/ui/web/server.pyindex 6d4063ac74..c63e09d685 100644--- a/jarvis/ui/web/server.py+++ b/jarvis/ui/web/server.py@@ -350,6 +350,7 @@ class WebServer:from .wiki_ws import router as wiki_ws_routerfrom .workflows_routes import router as workflows_routerfrom .workspace_routes import router as workspace_router+ from .agentic_ide_routes import router as agentic_ide_router# Conductor is an external package in the same monorepo. Import# defensively — anyone who checks out the repo without conductor would# otherwise get an ImportError here at server boot.@@ -421,6 +422,12 @@ class WebServer:# Provides agent detection, workspace launch planning, and PTY WebSocket# for in-app Claude Code / Codex terminals (xterm panes, not OS windows).app.include_router(workspace_router)+ # Agentic IDE (/api/agentic-ide/*) — a chosen folder plus named terminals+ # running Claude Code / Codex, addressable by voice ("what is Mika+ # doing?") and promptable from Jarvis. Reuses the same PTY stack as the+ # workspace above; adds the folder picker, call-signs, transcripts, and+ # the focused coding mode.+ app.include_router(agentic_ide_router)# Contacts section — user-curated address book (pure file store, no Brain dep).app.include_router(contacts_router)app.include_router(dictionary_router)@@ -2672,10 +2679,14 @@ class WebServer:otherwise a store could finish opening after the shutdown that wassupposed to close it, and leak the connection."""- from jarvis.ultrawiki.service import UltraWikiService+ from jarvis.ultrawiki.service import UltraWikiService, set_active_serviceservice = UltraWikiService(self.cfg, bus=self.bus)self.app.state.ultrawiki = service+ # The brain's memory surfaces (wiki-recall, the context injector) live+ # below the web layer and cannot read app.state — the module-level seam+ # is how they reach the live service (runtime_refs pattern).+ set_active_service(service)if bool(getattr(getattr(self.cfg, "ultrawiki", None), "enabled", False)):task = asyncio.create_task(service.ensure_started(), name="ultrawiki-start"@@ -3126,6 +3137,15 @@ class WebServer:)self._ultrawiki_start_task = None+ # Clear the brain-facing seam BEFORE the shutdown, so no memory surface+ # can start a search against a store that is about to close.+ try:+ from jarvis.ultrawiki.service import set_active_service++ set_active_service(None)+ except Exception as exc: # noqa: BLE001 — shutdown best-effort+ logger.opt(exception=exc).debug("UltraWiki seam clear failed: {}", exc)+ultrawiki_service = getattr(self.app.state, "ultrawiki", None)if ultrawiki_service is not None:try:diff --git a/jarvis/ultrawiki/service.py b/jarvis/ultrawiki/service.pyindex 876e59a1f3..87ae1bd9ae 100644--- a/jarvis/ultrawiki/service.py+++ b/jarvis/ultrawiki/service.py@@ -60,7 +60,10 @@ __all__ = ["SyncAlreadyRunningError","SyncJob","UltraWikiService",+ "active_search_service","clear_jobs",+ "get_active_service",+ "set_active_service",]#: The honest pipeline states reported by :meth:`UltraWikiService.status`.@@ -1462,3 +1465,73 @@ class UltraWikiService:return await search_mod.search(store=self._require_store(), cfg=self._cfg, query=query, **kwargs)+++# ---------------------------------------------------------------------------+# Active-service seam+# ---------------------------------------------------------------------------+#+# The brain's memory surfaces — the ``wiki-recall`` tool and the system-prompt+# context injector — sit BELOW the web layer and cannot reach ``app.state``.+# This is the same write-once-at-bootstrap handle registry+# ``jarvis/core/runtime_refs.py`` keeps for the BrainManager and the MCP+# registry: the WebServer registers the instance it constructed, and the lower+# layers ask for it instead of importing upward.+#+# A one-element list lets the setter rebind without ``global``. Assigning a+# single object reference is atomic in CPython and this is written once at+# bootstrap and read many times afterwards, so no lock is involved.++_ACTIVE_SERVICE: list[Any] = []+++def set_active_service(service: UltraWikiService | None) -> None:+ """Register the live service, or clear the registration with ``None``."""+ if _ACTIVE_SERVICE:+ _ACTIVE_SERVICE[0] = service+ else:+ _ACTIVE_SERVICE.append(service)+++def get_active_service() -> UltraWikiService | None:+ """The live service, or ``None`` when this runtime has none.++ Falls back to the handle the WebServer parks on ``app.state``, so a+ process that built a service without passing through+ :func:`set_active_service` still answers. ``None`` therefore means "there+ is genuinely no service here" (headless brain, tests, boot still in+ flight), never "the registration was missed".+ """+ service = _ACTIVE_SERVICE[0] if _ACTIVE_SERVICE else None+ if service is not None:+ return service+ try:+ from jarvis.core import runtime_refs # noqa: PLC0415 — lazy (AP-26)++ app = runtime_refs.get_web_app()+ except Exception: # noqa: BLE001 — a missing runtime is a None, never a raise+ return None+ return getattr(getattr(app, "state", None), "ultrawiki", None)+++def active_search_service() -> UltraWikiService | None:+ """The live service ONLY while it can actually answer a search.++ Three conditions, every one of them IO-free because this is consulted per+ brain turn on the voice path (AP-9): a service exists, UltraWiki mode is+ ON in the config object that service holds (the same object the routes+ mutate on an in-app toggle, so a mode switch needs no restart), and its+ store is open. Anything else answers ``None`` and the caller keeps its+ pre-UltraWiki behaviour unchanged.+ """+ service = get_active_service()+ if service is None:+ return None+ try:+ if not service._uw_enabled():+ return None+ if service._store is None:+ return None+ except Exception: # noqa: BLE001 — an unreadable handle is simply not ready+ return None+ return servicediff --git a/tests/unit/brain/test_wiki_context_ultrawiki.py b/tests/unit/brain/test_wiki_context_ultrawiki.pynew file mode 100644index 0000000000..c4fbb70f82--- /dev/null+++ b/tests/unit/brain/test_wiki_context_ultrawiki.py@@ -0,0 +1,320 @@+"""The context injector in UltraWiki mode — same discipline, other memory.++Two things must hold at once here, and they pull in opposite directions:++1. In UltraWiki mode the injector must actually SEE the ingested store,+ otherwise the brain keeps claiming ignorance of thousands of items.+2. It must stay as silent as the vault path was after the "Bugatti case" fix+ (2026-07-25): an unsolicited surface never volunteers a personal fact the+ question did not ask for. UltraWiki's fused score is ordinal and cannot+ certify relevance, so the gates that survive here are the ones that never+ depended on a score — the keyword leg and query-term coverage.+"""++from __future__ import annotations++import asyncio+from dataclasses import dataclass, field, replace+from typing import Any++import pytest++from jarvis.brain.wiki_context import WikiContextInjector+from jarvis.ultrawiki.service import set_active_service++BASE_PROMPT = "You are Personal Jarvis."+++@dataclass(frozen=True)+class _VaultHit:+ title: str+ snippet: str+ score: float+++class _SpyVaultSearch:+ def __init__(self, hits: list[_VaultHit] | None = None) -> None:+ self._hits = hits or []+ self.queries: list[str] = []++ def search(self, query: str, *, k: int = 5) -> list[_VaultHit]:+ self.queries.append(query)+ return list(self._hits[:k])+++@dataclass(frozen=True)+class _UltraHit:+ """Shaped like ``jarvis.ultrawiki.types.SearchResult``."""++ title: str+ snippet: str+ score: float = 0.031+ source_id: str = "jarvis-conversations"+ matched_by: tuple[str, ...] = field(default_factory=lambda: ("keyword", "vector"))+ permalink: str = "uw://item/1"+ timestamp_utc: str = "2026-07-20T10:00:00Z"+++DENTIST = _UltraHit(+ title="Zahnarzt", # i18n-allow: German vault page title under test+ snippet="Zahnarzt Dr. Meier, Praxis am Markt.", # i18n-allow: German content+)+CAR_NOTE = _UltraHit(+ title="Cars",+ snippet="The user owns six Bugattis and keeps them in a very nice garage.",+)+++class _FakeUltraService:+ def __init__(+ self,+ hits: list[Any] | None = None,+ *,+ error: Exception | None = None,+ delay_s: float = 0.0,+ ) -> None:+ self._hits = hits if hits is not None else []+ self._error = error+ self._delay_s = delay_s+ self._store = object()+ self.calls: list[dict[str, Any]] = []++ def _uw_enabled(self) -> bool:+ return True++ async def search(self, **kwargs: Any) -> list[Any]:+ self.calls.append(dict(kwargs))+ if self._delay_s:+ await asyncio.sleep(self._delay_s)+ if self._error is not None:+ raise self._error+ return list(self._hits)++[email protected](autouse=True)+def _clean_seam(monkeypatch: pytest.MonkeyPatch):+ from jarvis.core import runtime_refs++ monkeypatch.setattr(runtime_refs, "get_web_app", lambda: None)+ set_active_service(None)+ yield+ set_active_service(None)+++def _injector(vault: _SpyVaultSearch, **kwargs: Any) -> WikiContextInjector:+ kwargs.setdefault("latency_budget_ms", 500)+ kwargs.setdefault("ultra_latency_budget_ms", 500)+ return WikiContextInjector(search=vault, **kwargs)+++# ---------------------------------------------------------------------------+# Retrieval switches, gates do not+# ---------------------------------------------------------------------------+++async def test_ultra_mode_injects_from_the_store_and_skips_the_vault() -> None:+ vault = _SpyVaultSearch([_VaultHit("Stale", "old vault text", 0.9)])+ ultra = _FakeUltraService([DENTIST])+ set_active_service(ultra)++ result = await _injector(vault).maybe_inject(+ user_text="Wie heisst mein Zahnarzt?", # i18n-allow: German user input under test+ system_prompt=BASE_PROMPT,+ )++ assert "Dr. Meier" in result+ assert vault.queries == [], "Ultra mode must not also read the vault (D-5)"+ assert "old vault text" not in result+++async def test_retrieval_stays_cheap_no_rerank_no_expansion() -> None:+ ultra = _FakeUltraService([DENTIST])+ set_active_service(ultra)++ await _injector(_SpyVaultSearch()).maybe_inject(+ user_text="Wie heisst mein Zahnarzt?", # i18n-allow: German user input under test+ system_prompt=BASE_PROMPT,+ )++ assert ultra.calls, "the store must be queried"+ call = ultra.calls[0]+ assert call["rerank"] is False, "a rerank call is a model call on the voice path"+ assert call["expand_context"] is False+ assert call["enforce_floor"] is False+ assert call["k"] <= 5+++async def test_the_injected_block_still_carries_permission_to_ignore_it() -> None:+ set_active_service(_FakeUltraService([DENTIST]))++ result = await _injector(_SpyVaultSearch()).maybe_inject(+ user_text="Wie heisst mein Zahnarzt?", # i18n-allow: German user input under test+ system_prompt=BASE_PROMPT,+ )++ lowered = result.lower()+ assert "may have nothing to do" in lowered+ assert "ignore it completely" in lowered+++async def test_general_knowledge_never_reaches_the_store() -> None:+ """Gate 1 is retrieval-agnostic — it runs before either memory."""+ ultra = _FakeUltraService([CAR_NOTE])+ set_active_service(ultra)++ result = await _injector(_SpyVaultSearch()).maybe_inject(+ user_text="What is the tallest tower in the world?",+ system_prompt=BASE_PROMPT,+ )++ assert result == BASE_PROMPT+ assert ultra.calls == [], "an unrelated question must not even query the store"+++async def test_an_off_topic_store_hit_is_not_injected() -> None:+ """The Bugatti case, through UltraWiki: retrieval always returns something."""+ ultra = _FakeUltraService([CAR_NOTE])+ set_active_service(ultra)++ result = await _injector(_SpyVaultSearch()).maybe_inject(+ user_text="Wann war ich zuletzt beim Zahnarzt Meier?", # i18n-allow: German input+ system_prompt=BASE_PROMPT,+ )++ assert ultra.calls, "the question is personal, so the store IS queried"+ assert result == BASE_PROMPT+ assert "Bugatti" not in result+++async def test_a_vector_only_hit_is_not_injected() -> None:+ """No lexical evidence and an ordinal score cannot certify relevance."""+ hit = _UltraHit(+ title="Zahnarzt", # i18n-allow: German vault page title under test+ snippet="Zahnarzt Dr. Meier, Praxis am Markt.", # i18n-allow: German content+ matched_by=("vector",),+ )+ set_active_service(_FakeUltraService([hit]))++ result = await _injector(_SpyVaultSearch()).maybe_inject(+ user_text="Wie heisst mein Zahnarzt?", # i18n-allow: German user input under test+ system_prompt=BASE_PROMPT,+ )++ assert result == BASE_PROMPT+ assert "Dr. Meier" not in result+++async def test_a_hit_that_reports_no_legs_is_judged_on_coverage_alone() -> None:+ """A store that does not label its legs must not be silently muted."""+ set_active_service(_FakeUltraService([replace(DENTIST, matched_by=())]))++ result = await _injector(_SpyVaultSearch()).maybe_inject(+ user_text="Wie heisst mein Zahnarzt?", # i18n-allow: German user input under test+ system_prompt=BASE_PROMPT,+ )++ assert "Dr. Meier" in result+++# ---------------------------------------------------------------------------+# The turn is never blocked+# ---------------------------------------------------------------------------+++async def test_a_slow_store_injects_nothing_and_raises_nothing() -> None:+ ultra = _FakeUltraService([DENTIST], delay_s=1.0)+ set_active_service(ultra)+ injector = _injector(_SpyVaultSearch(), ultra_latency_budget_ms=20)++ result = await injector.maybe_inject(+ user_text="Wie heisst mein Zahnarzt?", # i18n-allow: German user input under test+ system_prompt=BASE_PROMPT,+ )++ assert result == BASE_PROMPT+++async def test_a_broken_store_injects_nothing_and_raises_nothing() -> None:+ set_active_service(_FakeUltraService(error=RuntimeError("store gone")))++ result = await _injector(_SpyVaultSearch()).maybe_inject(+ user_text="Wie heisst mein Zahnarzt?", # i18n-allow: German user input under test+ system_prompt=BASE_PROMPT,+ )++ assert result == BASE_PROMPT+++async def test_an_empty_store_injects_nothing() -> None:+ set_active_service(_FakeUltraService([]))++ result = await _injector(_SpyVaultSearch()).maybe_inject(+ user_text="Wie heisst mein Zahnarzt?", # i18n-allow: German user input under test+ system_prompt=BASE_PROMPT,+ )++ assert result == BASE_PROMPT+++# ---------------------------------------------------------------------------+# Mode off+# ---------------------------------------------------------------------------+++async def test_mode_off_still_reads_the_vault() -> None:+ vault = _SpyVaultSearch(+ [+ _VaultHit(+ title="Zahnarzt", # i18n-allow: German vault page title under test+ snippet="Zahnarzt Dr. Meier, Praxis am Markt.", # i18n-allow: German+ score=0.9,+ )+ ]+ )++ result = await _injector(vault).maybe_inject(+ user_text="Wie heisst mein Zahnarzt?", # i18n-allow: German user input under test+ system_prompt=BASE_PROMPT,+ )++ assert vault.queries, "with the mode off the vault is the memory"+ assert "Dr. Meier" in result+++async def test_a_registered_but_disabled_service_leaves_the_vault_in_charge() -> None:+ class _Disabled(_FakeUltraService):+ def _uw_enabled(self) -> bool:+ return False++ vault = _SpyVaultSearch(+ [+ _VaultHit(+ title="Zahnarzt", # i18n-allow: German vault page title under test+ snippet="Zahnarzt Dr. Meier, Praxis am Markt.", # i18n-allow: German+ score=0.9,+ )+ ]+ )+ ultra = _Disabled([CAR_NOTE])+ set_active_service(ultra)++ result = await _injector(vault).maybe_inject(+ user_text="Wie heisst mein Zahnarzt?", # i18n-allow: German user input under test+ system_prompt=BASE_PROMPT,+ )++ assert ultra.calls == []+ assert vault.queries+ assert "Dr. Meier" in resultdiff --git a/tests/unit/plugins/tool/test_wiki_recall_ultrawiki.py b/tests/unit/plugins/tool/test_wiki_recall_ultrawiki.pynew file mode 100644index 0000000000..7c23358455--- /dev/null+++ b/tests/unit/plugins/tool/test_wiki_recall_ultrawiki.py@@ -0,0 +1,263 @@+"""``wiki-recall`` must answer from whichever memory is actually live.++The reported defect (maintainer, 2026-07-25): UltraWiki mode is on with+thousands of ingested items, and the brain's recall tool still reads the old+vault only — so Jarvis says it knows nothing about material it has indexed.++Pinned here: the mode picks exactly ONE memory (decision D-5), the switch is+invisible to the prompt (same rendered block shape), and no UltraWiki failure+mode may leave the brain with a dead tool.+"""++from __future__ import annotations++import asyncio+from dataclasses import dataclass, field+from pathlib import Path+from typing import Any++import pytest++from jarvis.plugins.tool import wiki_recall as mod+from jarvis.plugins.tool.wiki_recall import WikiRecallTool+from jarvis.ultrawiki.service import set_active_service+++@dataclass(frozen=True)+class _VaultHit:+ title: str+ snippet: str+ path: Path+++class _SpyVaultSearch:+ """Records every vault query so "the vault was not touched" is provable."""++ def __init__(self, root: Path, hits: list[_VaultHit] | None = None) -> None:+ self._root = root+ self._hits = hits or []+ self.queries: list[tuple[str, int]] = []++ def search(self, query: str, *, k: int = 5) -> list[_VaultHit]:+ self.queries.append((query, k))+ return list(self._hits[:k])+++@dataclass(frozen=True)+class _UltraHit:+ item_id: int = 1+ source_id: str = "obsidian-vault"+ title: str = "Project Phoenix"+ snippet: str = "Phoenix is the ingestion rewrite that started in June."+ permalink: str = "uw://item/1"+ timestamp_utc: str = "2026-07-20T10:00:00Z"+ score: float = 0.031+ matched_by: tuple[str, ...] = field(default_factory=lambda: ("keyword", "vector"))+ context: tuple[str, ...] = ()+++class _FakeUltraService:+ def __init__(+ self,+ hits: list[Any] | None = None,+ *,+ error: Exception | None = None,+ delay_s: float = 0.0,+ ) -> None:+ self._hits = hits if hits is not None else [_UltraHit()]+ self._error = error+ self._delay_s = delay_s+ self._store = object()+ self.calls: list[dict[str, Any]] = []++ def _uw_enabled(self) -> bool:+ return True++ async def search(self, **kwargs: Any) -> list[Any]:+ self.calls.append(dict(kwargs))+ if self._delay_s:+ await asyncio.sleep(self._delay_s)+ if self._error is not None:+ raise self._error+ return list(self._hits)++[email protected](autouse=True)+def _clean_seam(monkeypatch: pytest.MonkeyPatch):+ from jarvis.core import runtime_refs++ monkeypatch.setattr(runtime_refs, "get_web_app", lambda: None)+ set_active_service(None)+ yield+ set_active_service(None)+++def vault(tmp_path: Path) -> Path:+ (tmp_path / "10-notes").mkdir()+ (tmp_path / "10-notes" / "phoenix.md").write_text("# Phoenix\n", encoding="utf-8")+ return tmp_path+++# ---------------------------------------------------------------------------+# Mode off — byte-identical old behaviour+# ---------------------------------------------------------------------------+++async def test_mode_off_uses_the_vault_unchanged(vault: Path) -> None:+ search = _SpyVaultSearch(+ vault,+ [_VaultHit("Phoenix", "the ingestion rewrite", vault / "10-notes/phoenix.md")],+ )+ tool = WikiRecallTool(search)++ result = await tool.execute({"query": "phoenix", "k": 3}, ctx=None)++ rel = Path("10-notes/phoenix.md") # rendered with the host separator+ assert search.queries == [("phoenix", 3)]+ assert result.success is True+ assert result.output == (+ '## Wiki hits for "phoenix"\n'+ f"- **Phoenix** — the ingestion rewrite ({rel})"+ )+++async def test_mode_off_still_reports_a_missing_vault(tmp_path: Path) -> None:+ search = _SpyVaultSearch(tmp_path / "gone")+ tool = WikiRecallTool(search)++ result = await tool.execute({"query": "phoenix"}, ctx=None)++ assert result.success is False+ assert result.error == "vault unavailable"+++# ---------------------------------------------------------------------------+# Mode on — UltraWiki owns the answer+# ---------------------------------------------------------------------------+++async def test_mode_on_answers_from_ultrawiki_and_leaves_the_vault_alone(+ vault: Path,+) -> None:+ search = _SpyVaultSearch(vault, [_VaultHit("Stale", "old vault text", vault)])+ ultra = _FakeUltraService()+ set_active_service(ultra)+ tool = WikiRecallTool(search)++ result = await tool.execute({"query": "phoenix", "k": 3}, ctx=None)++ assert search.queries == [], "Ultra mode must not also read the vault (D-5)"+ assert result.success is True+ assert result.output.startswith('## Wiki hits for "phoenix"')+ assert "**Project Phoenix**" in result.output+ assert "ingestion rewrite" in result.output+ assert "obsidian-vault" in result.output # source label+ assert "2026-07-20T10:00:00Z" in result.output # timestamp+ assert "uw://item/1" in result.output # permalink+ assert "old vault text" not in result.output+++async def test_the_explicit_call_passes_no_relevance_floor(vault: Path) -> None:+ """The user asked — Ask-view semantics, gates belong to the injector."""+ ultra = _FakeUltraService()+ set_active_service(ultra)+ tool = WikiRecallTool(_SpyVaultSearch(vault))++ await tool.execute({"query": "phoenix", "k": 4}, ctx=None)++ assert ultra.calls == [+ {+ "query": "phoenix",+ "k": 4,+ "rerank": True,+ "enforce_floor": False,+ "expand_context": True,+ }+ ]+++async def test_empty_ultrawiki_result_is_an_honest_answer_not_a_fallback(+ vault: Path,+) -> None:+ search = _SpyVaultSearch(vault, [_VaultHit("Stale", "old vault text", vault)])+ set_active_service(_FakeUltraService(hits=[]))+ tool = WikiRecallTool(search)++ result = await tool.execute({"query": "phoenix"}, ctx=None)++ assert result.success is True+ assert result.output == 'No wiki matches found for "phoenix".'+ assert search.queries == [], "an empty active memory is an answer, not a failure"+++async def test_a_titleless_item_is_labelled_by_its_source(vault: Path) -> None:+ set_active_service(_FakeUltraService(hits=[_UltraHit(title="")]))+ tool = WikiRecallTool(_SpyVaultSearch(vault))++ result = await tool.execute({"query": "phoenix"}, ctx=None)++ assert "**obsidian-vault**" in result.output+++async def test_a_snippetless_item_falls_back_to_its_expanded_context(+ vault: Path,+) -> None:+ hit = _UltraHit(snippet="", context=("the neighbouring paragraph",))+ set_active_service(_FakeUltraService(hits=[hit]))+ tool = WikiRecallTool(_SpyVaultSearch(vault))++ result = await tool.execute({"query": "phoenix"}, ctx=None)++ assert "the neighbouring paragraph" in result.output+++# ---------------------------------------------------------------------------+# Mode on, UltraWiki cannot answer — honest vault fallback, never a dead tool+# ---------------------------------------------------------------------------+++async def test_an_ultrawiki_error_falls_back_to_the_vault(+ vault: Path, caplog: pytest.LogCaptureFixture+) -> None:+ search = _SpyVaultSearch(+ vault, [_VaultHit("Phoenix", "vault text", vault / "10-notes/phoenix.md")]+ )+ set_active_service(_FakeUltraService(error=RuntimeError("store gone")))+ tool = WikiRecallTool(search)++ with caplog.at_level("WARNING", logger=mod.log.name):+ result = await tool.execute({"query": "phoenix"}, ctx=None)++ assert result.success is True+ assert "vault text" in result.output+ assert search.queries == [("phoenix", 5)]+ assert any("store gone" in record.getMessage() for record in caplog.records)+++async def test_a_slow_ultrawiki_falls_back_to_the_vault(+ vault: Path, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture+) -> None:+ monkeypatch.setattr(mod, "_ULTRA_TIMEOUT_S", 0.05)+ search = _SpyVaultSearch(+ vault, [_VaultHit("Phoenix", "vault text", vault / "10-notes/phoenix.md")]+ )+ set_active_service(_FakeUltraService(delay_s=1.0))+ tool = WikiRecallTool(search)++ with caplog.at_level("WARNING", logger=mod.log.name):+ result = await tool.execute({"query": "phoenix"}, ctx=None)++ assert result.success is True+ assert "vault text" in result.output+ assert search.queries == [("phoenix", 5)]+ assert any("exceeded" in record.getMessage() for record in caplog.records)diff --git a/tests/unit/ultrawiki/test_active_service_seam.py b/tests/unit/ultrawiki/test_active_service_seam.pynew file mode 100644index 0000000000..1f3d140495--- /dev/null+++ b/tests/unit/ultrawiki/test_active_service_seam.py@@ -0,0 +1,145 @@+"""The active-service seam the brain's memory surfaces resolve through.++``wiki-recall`` and the system-prompt context injector live below the web+layer and cannot read ``app.state``. These tests pin the contract they depend+on: a registered service is found, a cleared one is gone, and a service that+cannot answer (mode off, store not open) is reported as absent rather than+handed out — because both callers treat "present" as "this memory answers now".+"""++from __future__ import annotations++from types import SimpleNamespace++import pytest++from jarvis.ultrawiki import service as service_mod+from jarvis.ultrawiki.service import (+ UltraWikiService,+ active_search_service,+ get_active_service,+ set_active_service,+)+++class _FakeService:+ """Minimal stand-in exposing exactly what the readiness check reads."""++ def __init__(self, *, enabled: bool = True, started: bool = True) -> None:+ self._enabled = enabled+ self._store = object() if started else None++ def _uw_enabled(self) -> bool:+ return self._enabled++[email protected](autouse=True)+def _clean_seam(monkeypatch: pytest.MonkeyPatch):+ """Isolate the process-global seam and the app-state fallback."""+ from jarvis.core import runtime_refs++ monkeypatch.setattr(runtime_refs, "get_web_app", lambda: None)+ set_active_service(None)+ yield+ set_active_service(None)+++def test_register_and_clear_round_trip() -> None:+ service = _FakeService()+ set_active_service(service)+ assert get_active_service() is service++ set_active_service(None)+ assert get_active_service() is None+++def test_unregistered_seam_falls_back_to_app_state(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """A runtime that never called the setter still resolves its service."""+ from jarvis.core import runtime_refs++ sentinel = object()+ monkeypatch.setattr(+ runtime_refs,+ "get_web_app",+ lambda: SimpleNamespace(state=SimpleNamespace(ultrawiki=sentinel)),+ )+ assert get_active_service() is sentinel+++def test_ready_service_is_handed_out() -> None:+ service = _FakeService(enabled=True, started=True)+ set_active_service(service)+ assert active_search_service() is service+++def test_mode_off_reads_as_no_service() -> None:+ set_active_service(_FakeService(enabled=False, started=True))+ assert active_search_service() is None+++def test_unopened_store_reads_as_no_service() -> None:+ set_active_service(_FakeService(enabled=True, started=False))+ assert active_search_service() is None+++def test_readiness_never_raises_on_a_broken_handle() -> None:+ class _Broken:+ def _uw_enabled(self) -> bool:+ raise RuntimeError("handle is toast")++ set_active_service(_Broken())+ assert active_search_service() is None+++def test_a_real_service_with_the_mode_off_is_not_handed_out() -> None:+ """Same answer through the real class, not just the fake."""+ cfg = SimpleNamespace(ultrawiki=SimpleNamespace(enabled=False))+ set_active_service(UltraWikiService(cfg))+ assert active_search_service() is None+++# ---------------------------------------------------------------------------+# Server wiring+# ---------------------------------------------------------------------------+++async def test_server_init_registers_the_constructed_service() -> None:+ """The WebServer's UltraWiki init must publish its instance to the seam."""+ from jarvis.ui.web.server import WebServer++ stub = SimpleNamespace(+ cfg=SimpleNamespace(ultrawiki=SimpleNamespace(enabled=False)),+ bus=None,+ app=SimpleNamespace(state=SimpleNamespace()),+ _ultrawiki_start_task=None,+ )+ await WebServer._init_ultrawiki(stub)++ assert isinstance(stub.app.state.ultrawiki, UltraWikiService)+ assert get_active_service() is stub.app.state.ultrawiki+++def test_server_stop_clears_the_seam() -> None:+ """Teardown must retract the handle before the store closes.++ Asserted on the source because ``stop()`` tears down the whole server and+ cannot be driven from a stub — but the seam clear is exactly the line that+ would be silently dropped in a future refactor, leaving the brain holding a+ service whose store is closed.+ """+ import inspect++ from jarvis.ui.web.server import WebServer++ source = inspect.getsource(WebServer.stop)+ assert "set_active_service(None)" in source+ assert source.index("set_active_service(None)") < source.index(+ "ultrawiki_service.shutdown()"+ ), "the seam must be cleared BEFORE the service shuts down"+++def test_seam_is_exported() -> None:+ for name in ("set_active_service", "get_active_service", "active_search_service"):+ assert name in service_mod.__all__