Skip to content

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

feat(wiki): carry frontmatter + preview on search hits (language-bridge groundwork)

Ruben Lütkeeb76fe6a3c40
diff --git a/jarvis/brain/wiki_context.py b/jarvis/brain/wiki_context.py
index 9b1438ee11..6acd5d0956 100644
--- a/jarvis/brain/wiki_context.py
+++ b/jarvis/brain/wiki_context.py
@@ -318,12 +318,16 @@ class WikiContextInjector:
chars_used = 0
hits_included = 0
for hit in hits:
- entry = f"**{hit.title}**: {hit.snippet}"
+ # A page found through a frontmatter alias (the language bridge)
+ # 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 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
if remaining >= 40: # only worth including if enough chars remain
- entry = f"**{hit.title}**: {hit.snippet[:remaining]}…"
+ entry = f"**{hit.title}**: {text[:remaining]}…"
else:
break
context_parts.append(entry)
diff --git a/jarvis/brain/wiki_relevance.py b/jarvis/brain/wiki_relevance.py
index 7d49d46f3d..269c07cecd 100644
--- a/jarvis/brain/wiki_relevance.py
+++ b/jarvis/brain/wiki_relevance.py
@@ -229,6 +229,13 @@ def relevant_hits(
score in this same call. Relative, never absolute: scores are documented
as incomparable across calls.
+ Coverage is judged over title + snippet + frontmatter. Including the
+ frontmatter is load-bearing, not incidental: a page found through a
+ ``search_aliases`` entry (the language bridge — a German question reaching
+ an English page) matches ONLY in the frontmatter column and therefore has
+ no body snippet at all. Judging such a hit on title+snippet alone would
+ discard precisely the hits aliases exist to produce.
+
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.
@@ -248,7 +255,11 @@ def relevant_hits(
for hit, score in zip(hits, scores, strict=False):
if score < floor:
continue
- haystack = _fold(f"{getattr(hit, 'title', '') or ''} {getattr(hit, 'snippet', '') or ''}")
+ haystack = _fold(
+ f"{getattr(hit, 'title', '') or ''} "
+ f"{getattr(hit, 'snippet', '') or ''} "
+ f"{getattr(hit, 'frontmatter', '') or ''}"
+ )
if sum(1 for term in terms if _covers(haystack, term)) >= needed:
kept.append(hit)
return kept
diff --git a/jarvis/memory/wiki/search.py b/jarvis/memory/wiki/search.py
index 03dce56e7b..1d4fad95a0 100644
--- a/jarvis/memory/wiki/search.py
+++ b/jarvis/memory/wiki/search.py
@@ -70,12 +70,26 @@ class SearchHit:
score:
Float in [0.0, 1.0]. Higher is better. Monotonic within a
single call; not comparable across calls.
+ frontmatter:
+ The page's flattened frontmatter values — the same text the FTS
+ ``frontmatter`` column indexes, including any ``search_aliases``.
+ A hit matched via an alias has NO body snippet, so a consumer
+ judging relevance on title+snippet alone would discard exactly the
+ hits aliases exist to produce; it needs this to see WHY the page
+ matched. Empty string when the page has no frontmatter.
+ preview:
+ Leading body text of the page, always populated regardless of where
+ the match occurred. Gives frontmatter-only hits something to show;
+ ``snippet`` keeps its legacy "empty unless the body matched"
+ contract.
"""
title: str
path: Path
snippet: str
score: float
+ frontmatter: str = ""
+ preview: str = ""
class VaultSearch:
@@ -202,7 +216,8 @@ class VaultSearch:
title,
snippet(wiki_fts, 3, '', '', '…', 32) AS snippet,
body,
- bm25(wiki_fts, 0.0, 3.0, 2.0, 1.0, 0.0) AS bm25_score
+ bm25(wiki_fts, 0.0, 3.0, 2.0, 1.0, 0.0) AS bm25_score,
+ frontmatter
FROM wiki_fts
WHERE wiki_fts MATCH ?
ORDER BY bm25_score
@@ -216,7 +231,7 @@ class VaultSearch:
]
hits: list[SearchHit] = []
for row in cursor:
- rel_path_str, title, snippet, body, bm25_raw = row
+ rel_path_str, title, snippet, body, bm25_raw, frontmatter = row
abs_path = self._root / rel_path_str
score = _normalise_bm25(bm25_raw)
# SQLite's snippet() returns the body column text even when the
@@ -231,6 +246,8 @@ class VaultSearch:
path=abs_path,
snippet=snippet or "",
score=round(score, 4),
+ frontmatter=frontmatter or "",
+ preview=_leading_text(body),
)
)
log.debug(
@@ -267,6 +284,31 @@ def _build_match_expr(tokens: list[str]) -> str:
return " OR ".join(quoted)
+#: How much leading body text ``SearchHit.preview`` carries.
+_PREVIEW_CHARS = 200
+
+
+def _leading_text(body: str | None, limit: int = _PREVIEW_CHARS) -> str:
+ """First meaningful prose of a page, for hits with no body snippet.
+
+ Skips the H1 and any blank/heading lines so the preview starts at real
+ content rather than at "# Title" — a frontmatter-only hit otherwise shows
+ the reader nothing it did not already know from the title.
+ """
+ if not body:
+ return ""
+ parts: list[str] = []
+ for line in body.splitlines():
+ stripped = line.strip()
+ if not stripped or stripped.startswith("#") or stripped.startswith("---"):
+ continue
+ parts.append(stripped)
+ if sum(len(p) for p in parts) >= limit:
+ break
+ text = " ".join(parts)
+ return text[:limit].rstrip() + "…" if len(text) > limit else text
+
+
def _normalise_bm25(raw: float) -> float:
"""Normalise FTS5 BM25 to [0.0, 1.0] higher-is-better.
diff --git a/tests/unit/brain/test_wiki_language_bridge.py b/tests/unit/brain/test_wiki_language_bridge.py
new file mode 100644
index 0000000000..e48398bbb7
--- /dev/null
+++ b/tests/unit/brain/test_wiki_language_bridge.py
@@ -0,0 +1,163 @@
+"""The language bridge: a question in the user's language must reach a page
+written in another one.
+
+Measured 2026-07-25 against the maintainer's real vault: German questions
+scored 0/7, the SAME questions phrased in English scored 7/7 — the vault is
+written in English by the fact extractor while the user speaks German, and a
+keyword index cannot cross that on its own ("Flugzeuge" never matches
+"aircraft").
+
+The bridge is a ``search_aliases`` frontmatter list. It needs no schema or
+indexer change: the indexer already flattens every frontmatter value into the
+indexed ``frontmatter`` column. What it DOES need is for the relevance filter
+to see it — an alias hit matches only in the frontmatter and therefore carries
+no body snippet, so a filter judging title+snippet alone would throw away
+exactly the hits aliases exist to produce.
+
+These tests drive the real indexer, the real search and the real injector
+against a throwaway vault.
+"""
+
+from __future__ import annotations
+
+import sqlite3
+from pathlib import Path
+
+import pytest
+
+from jarvis.brain.wiki_context import WikiContextInjector
+from jarvis.memory.wiki.fts_index import ensure_schema, index_vault
+from jarvis.memory.wiki.search import VaultSearch
+
+BASE_PROMPT = "You are Personal Jarvis."
+
+# An English page, as the fact extractor writes them today.
+GPU_PAGE_PLAIN = """---
+type: entity
+slug: nvidia-geforce-rtx-5070-ti
+---
+
+# NVIDIA GeForce RTX 5070 Ti
+
+## Summary
+The user's GPU, used for local inference workloads.
+"""
+
+# The same page with the bridge in place.
+GPU_PAGE_BRIDGED = """---
+type: entity
+slug: nvidia-geforce-rtx-5070-ti
+search_aliases: [Grafikkarte, Graka, Grafikprozessor, tarjeta grafica]
+---
+
+# NVIDIA GeForce RTX 5070 Ti
+
+## Summary
+The user's GPU, used for local inference workloads.
+"""
+
+
+def _vault(tmp_path: Path, pages: dict[str, str]) -> tuple[Path, sqlite3.Connection]:
+ root = tmp_path / "vault"
+ (root / "entities").mkdir(parents=True)
+ for name, text in pages.items():
+ (root / "entities" / name).write_text(text, encoding="utf-8")
+ # check_same_thread=False mirrors what VaultSearch does for its own
+ # connections: the injector runs the (synchronous) search in an executor
+ # thread, so a thread-bound connection would fail there.
+ conn = sqlite3.connect(":memory:", check_same_thread=False)
+ ensure_schema(conn)
+ index_vault(root, conn)
+ return root, conn
+
+
+def test_without_aliases_a_german_question_finds_nothing(tmp_path: Path) -> None:
+ """Pins the defect itself — if this ever starts passing, the vault
+ language changed and the bridge may no longer be needed."""
+ root, conn = _vault(tmp_path, {"gpu.md": GPU_PAGE_PLAIN})
+ hits = VaultSearch(root, conn=conn).search("Grafikkarte", k=5)
+ assert hits == []
+
+
+def test_aliases_bridge_the_question_to_the_page(tmp_path: Path) -> None:
+ root, conn = _vault(tmp_path, {"gpu.md": GPU_PAGE_BRIDGED})
+ hits = VaultSearch(root, conn=conn).search("Grafikkarte", k=5)
+ assert [h.path.stem for h in hits] == ["gpu"]
+
+
+ "query", ["Grafikkarte", "Graka", "Grafikprozessor", "tarjeta grafica"]
+)
+def test_every_alias_including_other_languages_resolves(
+ tmp_path: Path, query: str
+) -> None:
+ """Aliases are not a German feature — any supported language may be listed."""
+ root, conn = _vault(tmp_path, {"gpu.md": GPU_PAGE_BRIDGED})
+ assert VaultSearch(root, conn=conn).search(query, k=5)
+
+
+def test_alias_hit_carries_frontmatter_and_a_preview(tmp_path: Path) -> None:
+ """An alias hit has no body snippet; it must still expose WHY it matched
+ and something to show."""
+ root, conn = _vault(tmp_path, {"gpu.md": GPU_PAGE_BRIDGED})
+ hit = VaultSearch(root, conn=conn).search("Grafikkarte", k=1)[0]
+
+ assert hit.snippet == "", "an alias match is a frontmatter match by contract"
+ assert "Grafikkarte" in hit.frontmatter
+ assert "GPU" in hit.preview or "inference" in hit.preview
+ assert not hit.preview.startswith("#"), "preview must skip the H1"
+
+
+async def test_relevance_gate_does_not_discard_alias_hits(tmp_path: Path) -> None:
+ """The regression this file exists for.
+
+ The relevance filter scores coverage of the question's terms. An alias hit
+ matches in the frontmatter only, so judging title+snippet alone would drop
+ it — the language bridge and the relevance gate would cancel out.
+ """
+ root, conn = _vault(tmp_path, {"gpu.md": GPU_PAGE_BRIDGED})
+ injector = WikiContextInjector(
+ search=VaultSearch(root, conn=conn), latency_budget_ms=2000
+ )
+
+ result = await injector.maybe_inject(
+ user_text="Welche Grafikkarte habe ich?", # i18n-allow: German input under test
+ system_prompt=BASE_PROMPT,
+ )
+
+ assert result != BASE_PROMPT, "the alias hit must survive the relevance gate"
+ assert "RTX 5070 Ti" in result
+ assert "**NVIDIA GeForce RTX 5070 Ti**: " in result
+ # ...and the entry must carry content, not a bare title with nothing after it.
+ entry_line = next(
+ line for line in result.splitlines() if line.startswith("**NVIDIA")
+ )
+ assert len(entry_line.split(": ", 1)[1].strip()) > 10
+
+
+async def test_the_bridge_does_not_reopen_the_irrelevance_hole(tmp_path: Path) -> None:
+ """Aliases must not become a back door for unrelated personal facts."""
+ car_page = """---
+type: entity
+slug: bugatti-divo
+search_aliases: [Auto, Sportwagen, Wagen]
+---
+
+# Bugatti Divo
+
+## Summary
+The user owns six of them.
+"""
+ root, conn = _vault(tmp_path, {"car.md": car_page})
+ injector = WikiContextInjector(
+ search=VaultSearch(root, conn=conn), latency_budget_ms=2000
+ )
+
+ result = await injector.maybe_inject(
+ user_text="Was ist das schnellste Auto der Welt?", # i18n-allow: German input under test
+ system_prompt=BASE_PROMPT,
+ )
+
+ assert result == BASE_PROMPT, "general knowledge still never consults memory"