Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

fix(wiki): gate personal-memory injection on relevance, not on retrieval

Ruben Lütkead1ca2f81c62
diff --git a/jarvis/brain/factory.py b/jarvis/brain/factory.py
index dc5a2e0022..f8872d4ab0 100644
--- a/jarvis/brain/factory.py
+++ b/jarvis/brain/factory.py
@@ -1330,11 +1330,17 @@ def _phase2_full_brain(
max_chars=getattr(wiki_cfg, "max_chars", 1500),
latency_budget_ms=getattr(wiki_cfg, "latency_budget_ms", 80),
min_keyword_length=getattr(wiki_cfg, "min_keyword_length", 4),
+ relevance_gate=bool(getattr(wiki_cfg, "relevance_gate", True)),
+ min_coverage=float(getattr(wiki_cfg, "min_coverage", 0.5)),
+ min_relative_score=float(
+ getattr(wiki_cfg, "min_relative_score", 0.35)
+ ),
)
log.info(
- "WikiContextInjector active (vault=%s, budget=%dms)",
+ "WikiContextInjector active (vault=%s, budget=%dms, gate=%s)",
vault_path,
getattr(wiki_cfg, "latency_budget_ms", 80),
+ "on" if getattr(wiki_cfg, "relevance_gate", True) else "off",
)
except ImportError:
# Agent B's search module not yet merged — fallback to no-op.
diff --git a/jarvis/brain/wiki_context.py b/jarvis/brain/wiki_context.py
index aa953f1a1e..9b1438ee11 100644
--- a/jarvis/brain/wiki_context.py
+++ b/jarvis/brain/wiki_context.py
@@ -1,15 +1,34 @@
"""Wiki context injector for the brain system prompt.
Performs a fast, latency-bounded vault search before each brain turn and
-prepends the top matching snippets to the system prompt as a ``## Wiki context``
-section. If the search exceeds the latency budget, or if no useful keywords can
-be extracted from the user text, or if the vault returns no hits, the original
-system prompt is returned unchanged.
+prepends the surviving snippets to the system prompt as a framed personal-memory
+section. If the relevance gate declines the turn, if the search exceeds the
+latency budget, if no useful keywords can be extracted from the user text, or if
+nothing retrieved is relevant enough, the original system prompt is returned
+unchanged.
+
+Relevance contract (``jarvis.brain.wiki_relevance``):
+ Retrieval has no null element — a keyword search always returns a ranked
+ list, and "best match" never means "good match". Injecting whatever came
+ back is what welds unrelated personal facts onto general-knowledge answers.
+ Three gates, in order:
+
+ 1. BEFORE searching, ``should_consult_memory`` skips turns that are not
+ questions about the user's own life. A general-knowledge question never
+ touches the vault at all — no latency, no context, no non-sequitur.
+ 2. AFTER searching, ``relevant_hits`` drops hits that merely share a common
+ word with the question.
+ 3. AT injection, ``frame_context_block`` states that the notes may be
+ irrelevant and that the model must ignore them if so.
+
+ When the gate declines a turn the knowledge is not lost: the router brain
+ holds the ``wiki-recall`` tool and can look something up deliberately.
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).
Fallback contract:
When ``search`` is ``None`` (Agent B not yet merged), the injector silently
@@ -27,6 +46,13 @@ from typing import TYPE_CHECKING
if TYPE_CHECKING:
from jarvis.memory.wiki.search import VaultSearch
+from jarvis.brain.wiki_relevance import (
+ DEFAULT_MIN_COVERAGE,
+ DEFAULT_MIN_RELATIVE_SCORE,
+ frame_context_block,
+ relevant_hits,
+ should_consult_memory,
+)
from jarvis.memory.wiki.telemetry import telemetry
log = logging.getLogger(__name__)
@@ -166,11 +192,30 @@ class WikiContextInjector:
max_chars: int = 1500,
latency_budget_ms: int = 80,
min_keyword_length: int = 4,
+ relevance_gate: bool = True,
+ min_coverage: float = DEFAULT_MIN_COVERAGE,
+ min_relative_score: float = DEFAULT_MIN_RELATIVE_SCORE,
) -> None:
self._search = search
self._max_chars = max_chars
self._latency_budget_ms = latency_budget_ms
self._min_keyword_length = min_keyword_length
+ # 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
+ # by patching code — the defaults stay on.
+ self._relevance_gate = relevance_gate
+ self._min_coverage = min_coverage
+ self._min_relative_score = min_relative_score
+
+ def _miss(self, t0: float, reason: str) -> None:
+ """Record one skipped injection: telemetry + the single INFO line."""
+ telemetry.inc("wiki_context_misses")
+ log.info(
+ "WikiContextInjector injected=False hits=0 latency_ms=%d reason=%s",
+ int((time.monotonic() - t0) * 1000),
+ reason,
+ )
async def maybe_inject(
self,
@@ -200,26 +245,26 @@ class WikiContextInjector:
# Fast-path: no search engine available (Agent B not merged yet)
if self._search is None:
- latency_ms = int((time.monotonic() - t0) * 1000)
- telemetry.inc("wiki_context_misses")
- log.info(
- "WikiContextInjector injected=False hits=0 latency_ms=%d",
- latency_ms,
- )
+ self._miss(t0, "no_search")
return system_prompt
+ # Gate 1 (pre-retrieval): is this a question about the user's own life
+ # at all? A general-knowledge question must never reach the vault —
+ # that is what produces personalized non-sequiturs. Regex-only, so the
+ # skip path costs microseconds and SAVES the search latency.
+ if self._relevance_gate:
+ verdict = should_consult_memory(user_text)
+ if not verdict.consult:
+ self._miss(t0, verdict.reason)
+ return system_prompt
+
# Extract keywords
keywords = _extract_keywords(
user_text,
min_length=self._min_keyword_length,
)
if not keywords:
- latency_ms = int((time.monotonic() - t0) * 1000)
- telemetry.inc("wiki_context_misses")
- log.info(
- "WikiContextInjector injected=False hits=0 latency_ms=%d",
- latency_ms,
- )
+ self._miss(t0, "no_keywords")
return system_prompt
query = " ".join(keywords)
@@ -231,43 +276,43 @@ class WikiContextInjector:
timeout=self._latency_budget_ms / 1000.0,
)
except TimeoutError:
- latency_ms = int((time.monotonic() - t0) * 1000)
log.warning(
"WikiContextInjector timed out after %dms (budget=%dms) — "
"skipping wiki context for this turn",
- latency_ms,
+ int((time.monotonic() - t0) * 1000),
self._latency_budget_ms,
)
- telemetry.inc("wiki_context_misses")
- log.info(
- "WikiContextInjector injected=False hits=0 latency_ms=%d",
- latency_ms,
- )
+ self._miss(t0, "timeout")
return system_prompt
except Exception: # noqa: BLE001
- latency_ms = int((time.monotonic() - t0) * 1000)
log.warning(
"WikiContextInjector search raised unexpectedly — "
"skipping wiki context",
exc_info=True,
)
- telemetry.inc("wiki_context_misses")
- log.info(
- "WikiContextInjector injected=False hits=0 latency_ms=%d",
- latency_ms,
- )
+ self._miss(t0, "search_error")
return system_prompt
- latency_ms = int((time.monotonic() - t0) * 1000)
-
if not hits:
- telemetry.inc("wiki_context_misses")
- log.info(
- "WikiContextInjector injected=False hits=0 latency_ms=%d",
- latency_ms,
- )
+ self._miss(t0, "no_hits")
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._min_coverage,
+ min_relative_score=self._min_relative_score,
+ )
+ if not hits:
+ self._miss(t0, "no_relevant_hits")
+ return system_prompt
+
+ latency_ms = int((time.monotonic() - t0) * 1000)
+
# Build the context block, capped at max_chars
context_parts: list[str] = []
chars_used = 0
@@ -286,15 +331,13 @@ class WikiContextInjector:
hits_included += 1
if not context_parts:
- telemetry.inc("wiki_context_misses")
- log.info(
- "WikiContextInjector injected=False hits=0 latency_ms=%d",
- latency_ms,
- )
+ self._miss(t0, "empty_block")
return system_prompt
- wiki_block = "## Wiki context\n" + "\n".join(context_parts)
- augmented = system_prompt + "\n\n" + wiki_block
+ # Gate 3 (at injection): the block carries its own usage contract, so
+ # the model knows the notes are a guess and is explicitly allowed to
+ # ignore them. A bare context block reads as an instruction to use it.
+ augmented = system_prompt + "\n\n" + frame_context_block(context_parts)
telemetry.inc("wiki_context_hits")
log.info(
diff --git a/jarvis/brain/wiki_relevance.py b/jarvis/brain/wiki_relevance.py
new file mode 100644
index 0000000000..7d49d46f3d
--- /dev/null
+++ b/jarvis/brain/wiki_relevance.py
@@ -0,0 +1,283 @@
+"""Relevance gate for personal-memory context injection.
+
+Deterministic, LLM-free, IO-free guard that decides whether a turn should
+consult the personal memory (wiki vault today, UltraWiki later) at all, and
+which retrieved hits are strong enough to be worth putting in front of the
+model. Pure regex + set arithmetic — no disk, no network, no provider call
+(AP-9/AP-11), so it is safe on the voice critical path and costs microseconds.
+
+Why this exists
+---------------
+Retrieval has no null element. A similarity or keyword search always returns a
+ranked list; "most similar" never means "similar enough". Injecting whatever
+came back turns every unrelated question into a personalized non-sequitur —
+the model sees a context block in its prompt and assumes it is meant to be
+used. The observed failure mode: a general-knowledge question ("what is the
+tallest tower in the world?") retrieves an unrelated personal note and the
+answer arrives welded to the user's belongings.
+
+Three independent layers, each useful on its own:
+
+1. :func:`should_consult_memory` — BEFORE retrieval. General-knowledge and
+ definitional questions with no personal marker never search at all. Saves
+ the search latency and removes the failure mode at its root.
+2. :func:`relevant_hits` — AFTER retrieval. Coverage of the question's content
+ terms plus a within-call relative floor. Deliberately NOT an absolute score
+ threshold: ``SearchHit.score`` is documented as comparable only within a
+ single call, so a fixed cutoff would be noise.
+3. :func:`frame_context_block` — AT injection. The block states what it is and
+ grants explicit permission to ignore it, instead of arriving as bare text
+ the model reads as an instruction.
+
+Policy note — the default is to NOT inject. When the gate is unsure, the turn
+proceeds without memory context, because the router brain holds the
+``wiki-recall`` tool and can look something up deliberately when it notices it
+needs to. A miss therefore degrades to "the model asks the memory itself",
+not to "the knowledge is unreachable" — while a false injection degrades every
+answer it touches. Recall the tool can recover; relevance it cannot.
+
+Languages: the matcher carries de/en/es tokens as equal peers (CLAUDE.md §1
+closed-list item 3 — speech-recognition input vocabulary, matching data rather
+than prose). Input is case-, umlaut- and accent-folded before matching, so
+the German and Spanish spellings of a word reach the same pattern whether or
+not the speech recogniser produced its diacritics.
+"""
+
+from __future__ import annotations
+
+import re
+import unicodedata
+from dataclasses import dataclass
+from typing import Any
+
+from jarvis.brain.wiki_relevance_vocab import (
+ GENERAL_KNOWLEDGE_PHRASES,
+ LOOKUP_MARKERS,
+ PERSONAL_MARKERS,
+ RECOLLECTION_PHRASES,
+)
+
+__all__ = [
+ "MemoryVerdict",
+ "should_consult_memory",
+ "relevant_hits",
+ "frame_context_block",
+ "content_terms",
+]
+
+
+# ---------------------------------------------------------------------------
+# Folding
+# ---------------------------------------------------------------------------
+
+
+def _fold(text: str) -> str:
+ """Lower-case and strip umlauts/accents so one pattern matches all spellings.
+
+ The German sharp-s is expanded to a double s before the accent strip,
+ because NFKD decomposition leaves that character untouched; without the
+ expansion the folded patterns below could never match it.
+ """
+ lowered = text.lower().replace("ß", "ss") # i18n-allow: sharp-s input folding
+ decomposed = unicodedata.normalize("NFKD", lowered)
+ return "".join(ch for ch in decomposed if not unicodedata.combining(ch))
+
+
+# ---------------------------------------------------------------------------
+# Patterns (all written already folded — no umlauts, no accents)
+# ---------------------------------------------------------------------------
+
+def _alternation(tokens: tuple[str, ...]) -> re.Pattern[str]:
+ """Compile a word-bounded alternation over pre-folded vocabulary tokens.
+
+ Longest first, so a multi-word phrase wins over a single word that is its
+ prefix ("wie lange" must not be shadowed by "wie").
+ """
+ ordered = sorted(set(tokens), key=len, reverse=True)
+ return re.compile(r"\b(?:" + "|".join(re.escape(t) for t in ordered) + r")\b")
+
+
+# Ownership / self-reference: separates "the billing rules" from "MY rules".
+_PERSONAL_RE = _alternation(PERSONAL_MARKERS)
+
+# Explicit recollection phrasing — an unambiguous request to the memory,
+# strong enough to consult even without an ownership marker.
+_MEMORY_RE = _alternation(RECOLLECTION_PHRASES)
+
+# General-knowledge / definitional shape. On its own this is the world's
+# knowledge, not the user's — the tallest-tower case. Only an ownership
+# marker turns it into a memory question.
+_WORLD_KNOWLEDGE_RE = _alternation(GENERAL_KNOWLEDGE_PHRASES)
+
+# Question / lookup shape. Combined with an ownership marker this is a memory
+# question; without one it is not enough on its own.
+_LOOKUP_RE = _alternation(LOOKUP_MARKERS)
+
+#: Utterances shorter than this (in tokens) are greetings, acknowledgements or
+#: fragments — never worth a memory lookup.
+_MIN_TOKENS = 3
+
+_WORD_RE = re.compile(r"\w+", re.UNICODE)
+
+
+@dataclass(frozen=True)
+class MemoryVerdict:
+ """Outcome of the pre-retrieval gate.
+
+ ``consult`` is the decision; ``reason`` is a short machine-stable slug for
+ logging and telemetry, never user-facing prose.
+ """
+
+ consult: bool
+ reason: str
+
+
+_SKIP_TOO_SHORT = MemoryVerdict(False, "too_short")
+_SKIP_GENERAL_KNOWLEDGE = MemoryVerdict(False, "general_knowledge")
+_SKIP_NO_PERSONAL_ANCHOR = MemoryVerdict(False, "no_personal_anchor")
+_CONSULT_RECOLLECTION = MemoryVerdict(True, "recollection_phrase")
+_CONSULT_PERSONAL_LOOKUP = MemoryVerdict(True, "personal_lookup")
+
+
+def should_consult_memory(user_text: str) -> MemoryVerdict:
+ """Decide whether this turn should search the personal memory at all.
+
+ Order matters:
+
+ 1. Too short / no words -> skip (greetings, "ok", "danke").
+ 2. Explicit recollection phrasing -> consult, even without a possessive
+ ("do you remember where we were?").
+ 3. General-knowledge shape WITHOUT a personal marker -> skip. This is the
+ tallest-tower case and the whole reason the gate exists.
+ 4. Personal marker AND a lookup shape -> consult.
+ 5. Anything else -> skip, and let the brain reach for ``wiki-recall`` if it
+ decides it needs the memory (see the policy note in the module docstring).
+
+ Never raises: an unusable input degrades to a skip verdict.
+ """
+ if not user_text or not user_text.strip():
+ return _SKIP_TOO_SHORT
+ folded = _fold(user_text)
+ if len(_WORD_RE.findall(folded)) < _MIN_TOKENS:
+ return _SKIP_TOO_SHORT
+ if _MEMORY_RE.search(folded):
+ return _CONSULT_RECOLLECTION
+ personal = bool(_PERSONAL_RE.search(folded))
+ if _WORLD_KNOWLEDGE_RE.search(folded) and not personal:
+ return _SKIP_GENERAL_KNOWLEDGE
+ if personal and _LOOKUP_RE.search(folded):
+ return _CONSULT_PERSONAL_LOOKUP
+ return _SKIP_NO_PERSONAL_ANCHOR
+
+
+# ---------------------------------------------------------------------------
+# Post-retrieval filtering
+# ---------------------------------------------------------------------------
+
+#: A hit must cover at least this share of the question's content terms.
+#: With two terms that means both; with three, two. One term matching out of
+#: four is what produces an unrelated page that merely shares a common word.
+DEFAULT_MIN_COVERAGE = 0.5
+
+#: A hit must also score at least this share of the best hit in the SAME call.
+#: Within one call the scores are documented as monotonic, so a relative floor
+#: is meaningful where an absolute cutoff would not be.
+DEFAULT_MIN_RELATIVE_SCORE = 0.35
+
+
+def content_terms(query: str, *, min_length: int = 3) -> tuple[str, ...]:
+ """Folded, deduplicated content words of a query, order preserved."""
+ seen: set[str] = set()
+ terms: list[str] = []
+ for token in _WORD_RE.findall(_fold(query)):
+ if len(token) < min_length or token in seen:
+ continue
+ seen.add(token)
+ terms.append(token)
+ return tuple(terms)
+
+
+def _covers(haystack: str, term: str) -> bool:
+ """True when *term* appears in *haystack*, tolerating simple inflection.
+
+ Substring containment on folded text handles the common German/Spanish
+ endings ("dinner"/"dinners", "reise"/"reisen") without a stemmer
+ dependency. Terms shorter than four characters must match as whole words,
+ since a three-letter substring hits almost anything.
+ """
+ if len(term) < 4:
+ return re.search(rf"\b{re.escape(term)}\b", haystack) is not None
+ return term in haystack
+
+
+def relevant_hits(
+ hits: list[Any],
+ query: str,
+ *,
+ min_coverage: float = DEFAULT_MIN_COVERAGE,
+ min_relative_score: float = DEFAULT_MIN_RELATIVE_SCORE,
+) -> list[Any]:
+ """Keep only the hits that actually answer *query*, order preserved.
+
+ Each hit must satisfy BOTH:
+
+ - **Coverage** — its title plus snippet contains at least ``min_coverage``
+ of the query's content terms. A keyword index matches on ANY term, so a
+ page sharing one common word with the question is otherwise indis-
+ tinguishable from one that is on topic.
+ - **Relative score** — at least ``min_relative_score`` of the best hit's
+ score in this same call. Relative, never absolute: scores are documented
+ as incomparable across calls.
+
+ Hits are expected to expose ``title``, ``snippet`` and ``score``; anything
+ missing an attribute is treated as empty/zero rather than raising, so a
+ future hit type cannot break the voice path.
+ """
+ if not hits:
+ return []
+ terms = content_terms(query)
+ if not terms:
+ return list(hits)
+
+ scores = [float(getattr(hit, "score", 0.0) or 0.0) for hit in hits]
+ best = max(scores) if scores else 0.0
+ floor = best * min_relative_score if best > 0 else 0.0
+ needed = max(1, round(len(terms) * min_coverage))
+
+ kept: list[Any] = []
+ for hit, score in zip(hits, scores, strict=False):
+ if score < floor:
+ continue
+ haystack = _fold(f"{getattr(hit, 'title', '') or ''} {getattr(hit, 'snippet', '') or ''}")
+ if sum(1 for term in terms if _covers(haystack, term)) >= needed:
+ kept.append(hit)
+ return kept
+
+
+# ---------------------------------------------------------------------------
+# Framing
+# ---------------------------------------------------------------------------
+
+#: Heading + usage contract for the injected block. The permission to ignore
+#: is the point: a bare context block reads to a model as an instruction to
+#: use it, which is how unrelated personal facts end up welded onto general
+#: answers.
+_CONTEXT_HEADER = (
+ "## Wiki context — possibly relevant notes from the user's personal memory\n"
+ "These were retrieved automatically by keyword and may have nothing to do "
+ "with the question. Use a note only if it directly helps answer what was "
+ "actually asked. If it does not, ignore it completely and do not mention "
+ "it, allude to it, or work it into the answer. Never volunteer a personal "
+ "detail the question did not ask for."
+)
+
+
+def frame_context_block(entries: list[str]) -> str:
+ """Wrap rendered ``**Title**: snippet`` entries in the usage contract.
+
+ Returns an empty string for an empty list, so the caller can append
+ unconditionally.
+ """
+ if not entries:
+ return ""
+ return _CONTEXT_HEADER + "\n\n" + "\n".join(entries)
diff --git a/jarvis/brain/wiki_relevance_vocab.py b/jarvis/brain/wiki_relevance_vocab.py
new file mode 100644
index 0000000000..f7e893cd82
--- /dev/null
+++ b/jarvis/brain/wiki_relevance_vocab.py
@@ -0,0 +1,87 @@
+"""Input vocabulary for the personal-memory relevance gate.
+
+MATCHING DATA, NOT PROSE. Every token below is a fragment the speech
+recogniser may literally produce, which a classifier must contain in order to
+recognise the corresponding utterance — the same category as the router,
+navigation-intent and wake-trigger vocabularies (CLAUDE.md §1, closed-list
+item 3). Translating these tokens would make the gate deaf in that language.
+
+All tokens are written PRE-FOLDED: lower-case, no umlauts, no accents, sharp-s
+expanded. ``jarvis.brain.wiki_relevance._fold`` applies the same folding to
+incoming text, so "Wofür" and "wofuer" both reach the "wofuer" token here.
+
+de / en / es are equal peers. Adding a language means adding its tokens to
+every tuple below — never a new branch in the logic module.
+"""
+
+from __future__ import annotations
+
+__all__ = [
+ "PERSONAL_MARKERS",
+ "RECOLLECTION_PHRASES",
+ "GENERAL_KNOWLEDGE_PHRASES",
+ "LOOKUP_MARKERS",
+]
+
+
+#: Ownership / self-reference. What separates "what are the billing rules"
+#: (world knowledge) from "what are MY billing rules" (a memory question).
+PERSONAL_MARKERS: tuple[str, ...] = (
+ # de
+ "mein", "meine", "meinem", "meinen", "meiner", "meines",
+ "ich", "mir", "mich",
+ "wir", "uns", "unser", "unsere", "unserem", "unseren", "unserer", "unseres",
+ # en
+ "my", "mine", "our", "ours", "i", "me", "we", "us",
+ # es
+ "mi", "mis", "mio", "mia", "nuestro", "nuestra", "nuestros", "nuestras",
+ "yo", "nosotros",
+)
+
+#: Explicit recollection phrasing — an unambiguous request to the memory,
+#: strong enough to consult even without an ownership marker.
+RECOLLECTION_PHRASES: tuple[str, ...] = (
+ # de
+ "weisst du noch", "erinnerst du", "erinnere ich", "erinnerung",
+ "hatten wir", "waren wir", "war ich", "hab ich", "habe ich",
+ "wann war", "wann hatte", "wie hiess", "wie heisst",
+ # en
+ "do you remember", "remember when", "did i", "have i", "was i",
+ "were we", "did we", "what did i", "when did i", "when was i",
+ # es
+ "te acuerdas", "recuerdas", "cuando fui", "cuando estuve",
+)
+
+#: Definitional / general-knowledge shape. On its own this asks about the
+#: world, not about the user — the tallest-tower case. Only an ownership
+#: marker turns such a question into a memory question.
+GENERAL_KNOWLEDGE_PHRASES: tuple[str, ...] = (
+ # de
+ "was ist", "was sind", "was war", "was bedeutet", "wofuer steht",
+ "wer ist", "wer war", "wer hat", "wie funktioniert",
+ "wie viel", "wie viele", "wie hoch", "wie gross", "wie weit", "wie lange",
+ "warum ist", "warum gibt", "wo liegt", "wo befindet", "erklaer",
+ # en
+ "what is", "what are", "what was", "what does", "what do",
+ "who is", "who was", "how does", "how do", "how much", "how many",
+ "how high", "how tall", "how big", "how far", "how long",
+ "why is", "where is", "explain", "define",
+ # es
+ "que es", "que son", "que significa", "quien es", "quien fue",
+ "como funciona", "cuanto mide", "cuantos", "donde esta", "explica",
+)
+
+#: Question / lookup shape. Combined with an ownership marker this is a memory
+#: question; on its own it is not enough.
+LOOKUP_MARKERS: tuple[str, ...] = (
+ # de
+ "wann", "was", "wer", "welche", "welcher", "welches", "wo", "wie",
+ "warum", "wieso", "kennst du", "zeig", "zeige", "nenn", "nenne",
+ "erzaehl", "erzaehle", "sag mir", "liste",
+ # en
+ "when", "what", "who", "which", "where", "how", "why",
+ "do you know", "tell me", "show me", "list", "remind me",
+ # es
+ "cuando", "que", "quien", "cual", "donde", "como", "por que",
+ "dime", "muestrame",
+)
diff --git a/jarvis/core/config.py b/jarvis/core/config.py
index ec0eb9acd3..2f537885e2 100644
--- a/jarvis/core/config.py
+++ b/jarvis/core/config.py
@@ -2136,6 +2136,18 @@ class WikiContextConfig(BaseModel):
latency_budget_ms: int = 80
min_keyword_length: int = 4
+ # Relevance gate (jarvis/brain/wiki_relevance.py). Retrieval always
+ # returns a ranked list, so without a gate every unrelated question gets
+ # a personal note welded onto its answer. ``relevance_gate = false``
+ # restores the pre-gate behaviour: search every turn, inject every hit.
+ relevance_gate: bool = True
+ # Share of the question's content terms a hit must cover to be injected.
+ min_coverage: float = 0.5
+ # Share of the best hit's score (within the SAME search call) a hit must
+ # reach. Relative by design — the vault's scores are only comparable
+ # within one call, so an absolute cutoff would be noise.
+ min_relative_score: float = 0.35
+
class VoiceConfig(BaseModel):
"""Voice-flow knobs that are not STT/TTS/Trigger-specific.
diff --git a/scripts/ci/german-allowlist.txt b/scripts/ci/german-allowlist.txt
index 62cc611172..9586d1252e 100644
--- a/scripts/ci/german-allowlist.txt
+++ b/scripts/ci/german-allowlist.txt
@@ -137,6 +137,19 @@ tests/unit/voice/test_action_phrases.py
jarvis/brain/local_action_gate.py
jarvis/missions/stream_evidence.py
+# --- Personal-memory relevance gate, VOCABULARY ONLY (reason 3: the German
+# tokens a classifier must literally contain to match German utterances).
+# Deliberately split from jarvis/brain/wiki_relevance.py so the LOGIC file
+# stays fully checked — only the token tuples are exempt, and any future
+# German prose in the gate itself is still caught ---
+jarvis/brain/wiki_relevance_vocab.py
+
+# --- Relevance-gate tests: the German/Spanish utterances and vault fixtures
+# ARE the content under test (reason 4) — the tallest-tower regression
+# only means anything in the language it was reported in ---
+tests/unit/brain/test_wiki_relevance.py
+tests/unit/brain/test_wiki_context_relevance.py
+
# --- Screen-narration guard test: the German voice fixtures and the assertions
# on the German persona/system-prompt content are the behaviour under test ---
tests/unit/brain/test_screen_narration_guard.py
diff --git a/tests/unit/brain/test_wiki_context_relevance.py b/tests/unit/brain/test_wiki_context_relevance.py
new file mode 100644
index 0000000000..6459d129dc
--- /dev/null
+++ b/tests/unit/brain/test_wiki_context_relevance.py
@@ -0,0 +1,162 @@
+"""End-to-end guard: the injector must not personalize unrelated questions.
+
+Reported case (maintainer, 2026-07-25): asking for the tallest building in the
+world came back as advice to drive there in the cars the user owns. The vault
+genuinely contains the car fact; the defect is that an unrelated question
+retrieved it and the model treated the injected block as relevant.
+
+These tests drive the real ``WikiContextInjector`` against a fake vault search,
+so they cover the wiring (gate -> search -> filter -> framing), not just the
+gate helpers.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+
+import pytest
+
+from jarvis.brain.wiki_context import WikiContextInjector
+
+BASE_PROMPT = "You are Personal Jarvis."
+
+
+@dataclass(frozen=True)
+class FakeHit:
+ title: str
+ snippet: str
+ score: float
+
+
+class FakeVaultSearch:
+ """Records every query it is asked for and replays canned hits."""
+
+ def __init__(self, hits: list[FakeHit] | None = None) -> None:
+ self._hits = hits or []
+ self.queries: list[str] = []
+
+ def search(self, query: str, *, k: int = 5) -> list[FakeHit]:
+ self.queries.append(query)
+ return list(self._hits[:k])
+
+
+CAR_NOTE = FakeHit(
+ title="Cars",
+ snippet="The user owns six Bugattis and keeps them in the world's nicest garage.",
+ score=0.9,
+)
+
+
+async def test_general_knowledge_question_never_searches_the_vault() -> None:
+ """The reported case: no search, no context, no personalized answer."""
+ search = FakeVaultSearch([CAR_NOTE])
+ injector = WikiContextInjector(search=search, latency_budget_ms=500)
+
+ result = await injector.maybe_inject(
+ user_text="Was ist der hoechste Turm der Welt?", # i18n-allow: German user input under test
+ system_prompt=BASE_PROMPT,
+ )
+
+ assert result == BASE_PROMPT, "an unrelated question must not be given context"
+ assert search.queries == [], "the vault must not even be searched"
+ assert "Bugatti" not in result
+
+
+async def test_english_general_knowledge_question_is_also_clean() -> None:
+ search = FakeVaultSearch([CAR_NOTE])
+ injector = WikiContextInjector(search=search, latency_budget_ms=500)
+
+ result = await injector.maybe_inject(
+ user_text="What is the tallest tower in the world?",
+ system_prompt=BASE_PROMPT,
+ )
+
+ assert result == BASE_PROMPT
+ assert search.queries == []
+
+
+async def test_a_genuine_personal_question_still_gets_its_context() -> None:
+ """The gate must not be a mute button — real memory questions still work."""
+ hit = FakeHit(
+ title="Zahnarzt", # i18n-allow: German vault page title under test
+ snippet="Zahnarzt Dr. Meier, Praxis am Markt.", # i18n-allow: German vault content
+ score=0.9,
+ )
+ search = FakeVaultSearch([hit])
+ injector = WikiContextInjector(search=search, latency_budget_ms=500)
+
+ 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
+ assert "Dr. Meier" in result
+ assert search.queries, "a personal question must reach the vault"
+
+
+async def test_injected_block_carries_permission_to_ignore_it() -> None:
+ hit = FakeHit(
+ title="Zahnarzt", snippet="Dr. Meier", score=0.9
+ ) # i18n-allow: German vault page title under test
+ injector = WikiContextInjector(search=FakeVaultSearch([hit]), latency_budget_ms=500)
+
+ result = await injector.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_irrelevant_hit_on_a_personal_question_is_filtered_out() -> None:
+ """Gate 2: the question is personal, but what came back is not an answer."""
+ search = FakeVaultSearch([CAR_NOTE])
+ injector = WikiContextInjector(search=search, latency_budget_ms=500)
+
+ result = await injector.maybe_inject(
+ user_text="Wann war ich zuletzt beim Zahnarzt Meier?", # i18n-allow: German input
+ system_prompt=BASE_PROMPT,
+ )
+
+ assert search.queries, "the question is personal, so the search does run"
+ assert result == BASE_PROMPT, "but an unrelated hit must not be injected"
+ assert "Bugatti" not in result
+
+
+async def test_gate_can_be_switched_off_from_config() -> None:
+ """The escape hatch restores the old behaviour, provably."""
+ search = FakeVaultSearch([CAR_NOTE])
+ injector = WikiContextInjector(search=search, latency_budget_ms=500, relevance_gate=False)
+
+ result = await injector.maybe_inject(
+ user_text="Was ist der hoechste Turm der Welt?", # i18n-allow: German user input under test
+ system_prompt=BASE_PROMPT,
+ )
+
+ assert search.queries, "gate off => the vault is searched on every turn"
+ assert "Bugatti" in result, "gate off => the old unfiltered behaviour"
+
+
+async def test_a_broken_search_never_breaks_the_turn() -> None:
+ class ExplodingSearch:
+ def search(self, query: str, *, k: int = 5):
+ raise RuntimeError("vault is on fire")
+
+ injector = WikiContextInjector(search=ExplodingSearch(), latency_budget_ms=500)
+
+ 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
diff --git a/tests/unit/brain/test_wiki_relevance.py b/tests/unit/brain/test_wiki_relevance.py
new file mode 100644
index 0000000000..54fb21f21f
--- /dev/null
+++ b/tests/unit/brain/test_wiki_relevance.py
@@ -0,0 +1,164 @@
+"""Guards for the personal-memory relevance gate.
+
+The headline case ("the Bugatti case", maintainer report 2026-07-25): a
+general-knowledge question must never drag an unrelated personal fact into the
+answer. Asking for the tallest tower in the world must not produce advice about
+what the user owns.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+
+import pytest
+
+from jarvis.brain.wiki_relevance import (
+ content_terms,
+ frame_context_block,
+ relevant_hits,
+ should_consult_memory,
+)
+
+
+@dataclass(frozen=True)
+class FakeHit:
+ """Stand-in for ``jarvis.memory.wiki.search.SearchHit`` (fakes, not mocks)."""
+
+ title: str
+ snippet: str
+ score: float
+
+
+# ---------------------------------------------------------------------------
+# Pre-retrieval gate — general knowledge never consults the memory
+# ---------------------------------------------------------------------------
+
+
+ "utterance",
+ [
+ # The reported case, in every supported language.
+ "Was ist der hoechste Turm der Welt?", # i18n-allow: German user input under test
+ "Was ist der höchste Turm der Welt?", # i18n-allow: German user input under test
+ "What is the tallest tower in the world?",
+ "¿Qué es la torre más alta del mundo?", # i18n-allow: Spanish user input under test
+ # Other plain general-knowledge questions.
+ "Wie funktioniert ein Dieselmotor?", # i18n-allow: German user input under test
+ "How does a diesel engine work?",
+ "Who was Ada Lovelace?",
+ "Explain reciprocal rank fusion.",
+ ],
+)
+def test_general_knowledge_never_consults_memory(utterance: str) -> None:
+ verdict = should_consult_memory(utterance)
+ assert verdict.consult is False
+ assert verdict.reason == "general_knowledge"
+
+
+def test_possessive_turns_a_definitional_question_into_a_memory_question() -> None:
+ """ "What are the rules" is world knowledge; "my rules" is personal."""
+ assert should_consult_memory("What are the billing rules?").consult is False
+ assert should_consult_memory("What are my billing rules?").consult is True
+
+
+ "utterance",
+ [
+ "Wann war ich mit Viktoria essen?", # i18n-allow: German user input under test
+ "When did I meet Viktoria?",
+ "Weisst du noch, wo wir letztes Jahr waren?", # i18n-allow: German user input under test
+ "Do you remember where we stayed?",
+ "Wie heisst mein Zahnarzt?", # i18n-allow: German user input under test
+ "¿Te acuerdas de mi vuelo?", # i18n-allow: Spanish user input under test
+ ],
+)
+def test_personal_questions_do_consult_memory(utterance: str) -> None:
+ assert should_consult_memory(utterance).consult is True
+
+
+ "utterance",
+ ["Hallo", "ok", "danke dir", "", " "], # i18n-allow: German user input under test
+)
+def test_smalltalk_and_fragments_skip(utterance: str) -> None:
+ assert should_consult_memory(utterance).consult is False
+
+
+def test_action_requests_skip() -> None:
+ """An imperative is not a lookup — no memory search, no injected context."""
+ turn_on_the_light_de = "Mach das Licht an" # i18n-allow: German input under test
+ assert should_consult_memory(turn_on_the_light_de).consult is False
+ assert should_consult_memory("Turn on the kitchen light").consult is False
+
+
+def test_gate_never_raises_on_odd_input() -> None:
+ for weird in ["???", "\n\n", "🚗🚗🚗", "a b", "1 2 3 4 5"]:
+ assert should_consult_memory(weird).consult in (True, False)
+
+
+# ---------------------------------------------------------------------------
+# Post-retrieval filter — a shared common word is not relevance
+# ---------------------------------------------------------------------------
+
+
+def test_hit_sharing_only_one_common_word_is_dropped() -> None:
+ """The keyword index matches on ANY term; coverage is what filters."""
+ hits = [
+ FakeHit(title="Trestle dinner", snippet="dinner with Viktoria in San Francisco", score=0.9),
+ FakeHit(title="Car collection", snippet="thoughts about the world of engines", score=0.8),
+ ]
+ kept = relevant_hits(hits, "dinner Viktoria Francisco")
+ assert [hit.title for hit in kept] == ["Trestle dinner"]
+
+
+def test_weak_hit_below_the_relative_floor_is_dropped() -> None:
+ strong = FakeHit(title="Viktoria dinner", snippet="dinner with Viktoria", score=0.9)
+ weak = FakeHit(title="Viktoria dinner note", snippet="dinner with Viktoria", score=0.01)
+ kept = relevant_hits([strong, weak], "dinner Viktoria")
+ assert kept == [strong]
+
+
+def test_relative_floor_never_uses_an_absolute_cutoff() -> None:
+ """Scores are only comparable within one call — a uniformly low-scoring
+ call must still return its hits rather than being wiped by a fixed floor."""
+ hits = [
+ FakeHit(title="Viktoria dinner", snippet="dinner with Viktoria", score=0.05),
+ FakeHit(title="Viktoria dinner two", snippet="dinner with Viktoria", score=0.04),
+ ]
+ assert len(relevant_hits(hits, "dinner Viktoria")) == 2
+
+
+def test_empty_hits_and_termless_queries_are_safe() -> None:
+ assert relevant_hits([], "anything") == []
+ hits = [FakeHit(title="t", snippet="s", score=1.0)]
+ assert relevant_hits(hits, "?? ..") == hits
+
+
+def test_filter_tolerates_hits_missing_attributes() -> None:
+ class Bare:
+ pass
+
+ assert relevant_hits([Bare()], "dinner Viktoria") == []
+
+
+def test_content_terms_folds_and_deduplicates() -> None:
+ mixed_case_de = "Über über ÜBER Reise" # i18n-allow: German input under test
+ assert content_terms(mixed_case_de) == ("uber", "reise")
+ assert "?" not in "".join(content_terms("Wann? Wo?")) # i18n-allow: German input
+
+
+# ---------------------------------------------------------------------------
+# Framing — the block must grant permission to ignore itself
+# ---------------------------------------------------------------------------
+
+
+def test_framed_block_tells_the_model_it_may_be_irrelevant() -> None:
+ block = frame_context_block(["**Cars**: six of them"])
+ assert "**Cars**: six of them" in block
+ lowered = block.lower()
+ assert "ignore it completely" in lowered
+ assert "may have nothing to do" in lowered
+
+
+def test_framing_an_empty_list_yields_nothing_to_append() -> None:
+ assert frame_context_block([]) == ""