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): search-alias language bridge + prefix matching

Ruben Lütke3399072e1463
diff --git a/jarvis/core/config.py b/jarvis/core/config.py
index a90a06cfdd..fa0df46d72 100644
--- a/jarvis/core/config.py
+++ b/jarvis/core/config.py
@@ -1245,6 +1245,45 @@ class SafetyConfig(BaseModel):
always_block_tiers: list[RiskTier] = Field(default_factory=lambda: ["block"])
whitelist: SafetyWhitelistConfig = Field(default_factory=SafetyWhitelistConfig)
blacklist: SafetyBlacklistConfig = Field(default_factory=SafetyBlacklistConfig)
+ # How long an armed approval gate waits for a decision before the default
+ # deny. Deliberately short: an unattended, non-pre-authorized ask-tier
+ # call should fail fast and honestly (the worker observes the denial and
+ # adapts, ADR-0031/W3) instead of burning its iteration budget blocked.
+ tool_approval_timeout_s: float = Field(default=60.0, ge=5.0, le=600.0)
+
+
+class SkillsConfig(BaseModel):
+ """Deterministic skill matching (2026-07-25).
+
+ Author-written voice triggers are unaffected by everything here; these knobs
+ govern only the relevance layer that catches paraphrases.
+ """
+
+ #: Master switch for the deterministic relevance layer. Off = exactly the
+ #: pre-2026-07-25 behaviour (author regex + the LLM listing).
+ relevance_enabled: bool = True
+
+ #: While true, a FIRE-band relevance match is RECORDED but does not capture
+ #: the turn — the narrowed candidate hint still ships. Default true for the
+ #: first release: the maintainer reviews a day of real decisions via
+ #: ``GET /api/skills/match-log`` and flips this off on measured numbers,
+ #: rather than on a hunch about a layer that can rewrite a turn's
+ #: instructions.
+ relevance_shadow: bool = True
+
+ #: Weakest band allowed to capture a turn. Anything below stays a
+ #: suggestion the model may ignore.
+ auto_fire_min_band: Literal["fire", "narrow"] = "fire"
+
+ #: Optional threshold overrides. ``None`` keeps the calibrated
+ #: corpus-derived defaults from jarvis/skills/relevance.py — set these only
+ #: with a number from scripts/skill_relevance_calibrate.py, never to make a
+ #: single over-fire go away (AP-27).
+ fire_threshold: float | None = None
+ hint_threshold: float | None = None
+
+ #: How many narrowed candidates ride the per-turn context on a NARROW turn.
+ narrow_candidates: int = 3
class JarvisAgentNotificationConfig(BaseModel):
@@ -2082,6 +2121,16 @@ class WikiIntegrationConfig(BaseModel):
subscribe_idle: bool = True # listen for IdleEntered
fallback_to_direct_ingest: bool = True # when scheduler is missing
+ # Languages the search-alias bridge writes into each page
+ # (jarvis/memory/wiki/search_aliases.py). Pages are written in English by
+ # the fact extractor, so a user who ASKS in another language cannot reach
+ # them by keyword ("Flugzeuge" never matches "aircraft"). Listing that
+ # language here makes every page carry the words its owner would actually
+ # say. Empty = derive from the other language signals (reply_language, UI,
+ # STT); those are frequently all "en"/"auto" even for a non-English
+ # speaker, which is why this explicit list exists rather than a guess.
+ search_alias_languages: list[str] = Field(default_factory=list)
+
class UltraWikiConfig(BaseModel):
"""UltraWiki — the semantic memory mode (design: UltraWiki/*.md).
@@ -2387,6 +2436,58 @@ class TeamProxyConfig(BaseModel):
model_config = {"extra": "allow"}
+class Phase6SafetyConfig(BaseModel):
+ """``[phase6.safety]`` — mission-worker safety knobs (ADR-0031).
+
+ First Pydantic-modeled slice of the ``[phase6.*]`` tables (they were
+ documentation-plus-intent before; ``bootstrap_missions`` kwargs stay the
+ wiring for the older flags). ``extra="allow"`` so pre-existing raw keys
+ keep loading (AP-16).
+ """
+
+ model_config = ConfigDict(extra="allow")
+
+ injection_scanner_enabled: bool = True
+ destructive_confirm_enabled: bool = True
+ extra_blocked_globs: list[str] = Field(default_factory=list)
+ # Mission-scoped tool pre-authorization (ADR-0031). When enabled, tools a
+ # mission's broker grant contains AND that appear below are auto-approved
+ # for THAT mission's calls only — the gate is answered on the bus (full
+ # Proposed→Approved→Executed audit), never bypassed. ``False`` restores
+ # the pre-ADR-0031 behavior (every ask-tier call waits for a human).
+ worker_tool_auto_approve: bool = True
+ # Exact tool names, or an MCP server family as ``server/`` (trailing
+ # slash). Prefer EXACT names: a server prefix silently authorizes every
+ # future tool that server adds, including destructive ones. Messaging /
+ # mail / social-send families deliberately stay OUT of the default —
+ # widen only by explicit operator choice. The shipped default lists
+ # read-only knowledge tools so a plausibility-escalated call can never
+ # stall an unattended mission.
+ auto_approve_tool_families: list[str] = Field(
+ default_factory=lambda: [
+ "search_web",
+ "wiki-list",
+ "wiki-recall",
+ "wiki-page-read",
+ "wiki-ingest",
+ "session-latest-turn",
+ ]
+ )
+
+
+class Phase6Config(BaseModel):
+ """``[phase6]`` root — mission subsystem configuration.
+
+ Only ``safety`` is typed so far; the other tables (orchestrator, budget,
+ voice, cleanup) remain raw TOML consumed via ``bootstrap_missions``
+ defaults and stay loadable through ``extra="allow"`` (AP-16).
+ """
+
+ model_config = ConfigDict(extra="allow")
+
+ safety: Phase6SafetyConfig = Field(default_factory=Phase6SafetyConfig)
+
+
class JarvisConfig(BaseModel):
"""Root config model."""
# populate_by_name=True lets callers use Python field names alongside
@@ -2401,6 +2502,7 @@ class JarvisConfig(BaseModel):
brain: BrainConfig = Field(default_factory=BrainConfig)
memory: MemoryConfig = Field(default_factory=MemoryConfig)
safety: SafetyConfig = Field(default_factory=SafetyConfig)
+ skills: SkillsConfig = Field(default_factory=SkillsConfig)
harness: HarnessConfig = Field(default_factory=HarnessConfig)
mcp_server: MCPServerConfig = Field(default_factory=MCPServerConfig)
audio: AudioConfig = Field(default_factory=AudioConfig)
@@ -2431,6 +2533,8 @@ class JarvisConfig(BaseModel):
local_action: LocalActionConfig = Field(default_factory=LocalActionConfig)
# Phase 8.4 — review pipeline configuration.
review: ReviewConfig = Field(default_factory=ReviewConfig)
+ # Phase 6 — mission subsystem ([phase6.safety] typed; rest raw, AP-16).
+ phase6: Phase6Config = Field(default_factory=Phase6Config)
# Latency sprint 1 (2026-04-30) — master switches for performance levers.
performance: PerformanceConfig = Field(default_factory=PerformanceConfig)
# Wave 0 (omni-latency) — hot-path latency span instrumentation toggle.
diff --git a/jarvis/memory/wiki/search.py b/jarvis/memory/wiki/search.py
index 1d4fad95a0..e90bbd4ab6 100644
--- a/jarvis/memory/wiki/search.py
+++ b/jarvis/memory/wiki/search.py
@@ -225,8 +225,11 @@ class VaultSearch:
"""
cursor = conn.execute(sql, (match_expr, k))
# Lowercased bare tokens for the "did body actually contain a hit?" check.
+ # Strip the quotes AND the prefix marker: '"drogen"*' and '"drogen"'
+ # both reduce to 'drogen', so the body check below stays a plain
+ # substring test and a prefix-only hit is judged on its stem.
bare_tokens = [
- _FTS5_SPECIAL_STRIP_RE.sub("", tok).lower()
+ _FTS5_SPECIAL_STRIP_RE.sub("", tok).rstrip("*").lower()
for tok in match_expr.split(" OR ")
]
hits: list[SearchHit] = []
@@ -264,6 +267,12 @@ class VaultSearch:
# ---------------------------------------------------------------------------
+#: Shortest token that may be searched as a prefix. Below this a prefix match
+#: is indiscriminate ("ab*" hits half the vault) and costs precision for no
+#: recall worth having.
+_PREFIX_MIN_LEN = 4
+
+
def _build_match_expr(tokens: list[str]) -> str:
"""Build an FTS5 MATCH expression from a list of tokens.
@@ -271,17 +280,34 @@ def _build_match_expr(tokens: list[str]) -> str:
double-quotes) so that FTS5 special characters are treated as literals.
Tokens are combined with OR.
+ Tokens of at least :data:`_PREFIX_MIN_LEN` characters additionally get a
+ PREFIX variant (``"drogen"*``). FTS5 matches whole tokens, which is a poor
+ fit for a compounding language: measured on the real vault, "Drogen" did
+ not find a page whose term was the corresponding German compound, and a
+ singular did not find its own plural. Every compound and every inflection
+ was a
+ separate, unreachable word. The prefix variant is OR-ed IN ADDITION to the
+ exact token, so exact matches keep their higher BM25 rank and the change
+ can only add recall, never reorder a hit that already worked.
+
Examples
--------
>>> _build_match_expr(["foo", "bar"])
'"foo" OR "bar"'
+ >>> _build_match_expr(["drogen"])
+ '"drogen" OR "drogen"*'
>>> _build_match_expr(['a:b'])
'"a:b"'
- >>> _build_match_expr(['"foo*bar"'])
- '"foo*bar"'
"""
- quoted = [f'"{_FTS5_SPECIAL_STRIP_RE.sub("", tok)}"' for tok in tokens]
- return " OR ".join(quoted)
+ parts: list[str] = []
+ for tok in tokens:
+ cleaned = _FTS5_SPECIAL_STRIP_RE.sub("", tok)
+ if not cleaned:
+ continue
+ parts.append(f'"{cleaned}"')
+ if len(cleaned) >= _PREFIX_MIN_LEN:
+ parts.append(f'"{cleaned}"*')
+ return " OR ".join(parts)
#: How much leading body text ``SearchHit.preview`` carries.
diff --git a/jarvis/memory/wiki/search_aliases.py b/jarvis/memory/wiki/search_aliases.py
new file mode 100644
index 0000000000..ae32fff2d2
--- /dev/null
+++ b/jarvis/memory/wiki/search_aliases.py
@@ -0,0 +1,427 @@
+"""Search aliases — the language bridge between the user and their vault.
+
+The problem, measured
+---------------------
+The fact extractor writes vault pages in English; the user asks in their own
+language. A keyword index cannot cross that gap: "Flugzeuge" never matches
+"aircraft", and a page called ``nvidia-geforce-rtx-5070-ti`` is unreachable
+from the word "Grafikkarte". Against the maintainer's real 26-page vault on
+2026-07-25, twelve ordinary questions about his own life recalled the right
+page 4 times; a controlled probe put German at 0/7 and the SAME questions in
+English at 7/7. The knowledge was there — only the key was in another
+language.
+
+The bridge
+----------
+Each page carries a ``search_aliases`` frontmatter list holding the words a
+user would actually SAY when looking for it, in every language they use. The
+indexer already flattens every frontmatter value (lists included) into the
+indexed ``frontmatter`` column, weighted above body text, so nothing about
+the schema or the index has to change — writing the field is enough.
+
+Design rule: **pay at write time, not at ask time.** Generating aliases costs
+one small LLM call, made rarely and in the background; answering then costs
+nothing at all. The alternative — translating the query on every question —
+would put a model call on the latency path of every single turn, which is
+exactly what the voice budget cannot afford (AP-9/AP-26).
+
+Universality (§3): the generator degrades to "no aliases" whenever no
+provider is reachable — never an exception, never a blocked write. A vault
+without aliases behaves exactly as it does today. Provider selection goes
+through the shared key-aware wiki chain, so a dead or throttled provider
+crosses to another family instead of bricking the feature (AP-22).
+"""
+
+from __future__ import annotations
+
+import logging
+import re
+from typing import Any
+
+from jarvis.core.turn_language import DEFAULT_LOCALE
+
+log = logging.getLogger(__name__)
+
+__all__ = [
+ "ALIAS_FIELD",
+ "MAX_ALIASES",
+ "backfill_vault",
+ "build_alias_prompt",
+ "generate_aliases",
+ "merge_aliases",
+ "parse_alias_response",
+ "target_languages",
+]
+
+#: Frontmatter key holding the bridge terms.
+ALIAS_FIELD = "search_aliases"
+
+#: Upper bound per page. Aliases are weighted above body text, so an
+#: unbounded list would let one page shadow the whole vault.
+MAX_ALIASES = 12
+
+#: Longest single alias worth indexing. Anything longer is a sentence, not a
+#: search term, and only dilutes the page's frontmatter column.
+_MAX_ALIAS_CHARS = 40
+
+#: Aliases are matching data, never prose — reject anything with markup,
+#: separators, or list syntax that indicates the model returned a sentence.
+_ALIAS_RE = re.compile(r"^[\w\s\-']{2,}$", re.UNICODE)
+
+#: Pronouns and bare function words are worthless as aliases and actively
+#: harmful: they appear in almost every personal question, so a page carrying
+#: them becomes a magnet that surfaces for anything. Observed on the first
+#: real run — the user's own entity page was offered "ich", "me", "myself".
+#: Kept deliberately tiny: this rejects words that identify NO page, not words
+#: that merely feel generic ("auto" genuinely identifies a car page).
+_USELESS_ALIASES: frozenset[str] = frozenset(
+ {
+ # de
+ "ich", "mir", "mich", "wir", "uns", "du", "er", "sie", "es", "man",
+ "mein", "meine", "selbst",
+ # en
+ "i", "me", "my", "mine", "myself", "we", "us", "our", "you", "it",
+ "self", "own", "thing", "stuff",
+ # es ("me"/"mi" already listed above)
+ "yo", "nosotros", "tu", "el", "ella", "eso",
+ }
+)
+
+
+#: Language signals to harvest, most authoritative first. Each is a dotted
+#: config path; "auto"/empty values are ignored.
+_LANGUAGE_SIGNALS: tuple[str, ...] = (
+ "brain.reply_language", # what Jarvis is pinned to SPEAK
+ "ui.language", # the interface the user chose
+ "stt.language", # what the recogniser is pinned to HEAR
+ "stt.wake_language", # the wake-word language — often the only honest hint
+)
+
+
+def _config_path(cfg: Any, dotted: str) -> str:
+ node: Any = cfg
+ for part in dotted.split("."):
+ node = getattr(node, part, None)
+ if node is None:
+ return ""
+ return str(node).strip().lower()[:2]
+
+
+def target_languages(cfg: Any) -> tuple[str, ...]:
+ """Languages a page's aliases should cover, most important first.
+
+ There is no single field that states which language the user actually
+ speaks, and guessing from one of them is how this feature silently does
+ nothing: on the maintainer's own box ``reply_language`` is "auto",
+ ``ui.language`` and ``stt.language`` are both "en", and only
+ ``wake_language`` reveals a German speaker. Resolving from
+ ``reply_language`` alone produced English aliases for an already-English
+ vault — a bridge to nowhere.
+
+ So the explicit ``wiki_integration.search_alias_languages`` list wins when
+ set, and otherwise every signal is harvested rather than ranked-and-picked.
+ English is always included last because the vault itself is written in it:
+ an English alias costs nothing and keeps English questions working.
+ """
+ langs: list[str] = []
+ explicit = getattr(
+ getattr(cfg, "wiki_integration", None), "search_alias_languages", None
+ )
+ for item in explicit or []:
+ code = str(item).strip().lower()[:2]
+ if code and code not in langs:
+ langs.append(code)
+ if not langs:
+ for path in _LANGUAGE_SIGNALS:
+ value = _config_path(cfg, path)
+ if value and value != "au" and value not in langs: # "auto" -> "au"
+ langs.append(value)
+ if not langs:
+ langs.append((DEFAULT_LOCALE or "en").lower()[:2])
+ if "en" in langs:
+ langs.remove("en")
+ langs.append("en")
+ return tuple(langs)
+
+
+def build_alias_prompt(*, title: str, body: str, languages: tuple[str, ...]) -> str:
+ """Instruction for the alias model call.
+
+ Deliberately asks for SEARCH TERMS, not translations: the user does not
+ look for "aircraft" translated, they look for "Flugzeuge", "Jet", or
+ "fliegen". Everyday words and the obvious category word beat a faithful
+ rendering of the title.
+ """
+ langs = ", ".join(languages)
+ excerpt = body.strip()[:1200]
+ return (
+ "You generate SEARCH ALIASES for a page in a personal knowledge vault.\n"
+ "\n"
+ "The vault is written in English, but its owner searches in their own "
+ f"language. Produce the words they would actually SAY or TYPE when "
+ f"looking for this page, in these languages: {langs}.\n"
+ "\n"
+ "Rules:\n"
+ "- Everyday words, not translations of the title. A page about an "
+ "'NVIDIA GeForce RTX 5070 Ti' should yield the category word for a "
+ "graphics card in each language, not a transliterated product name.\n"
+ "- Include the obvious category word, common synonyms, and the "
+ "colloquial short form people really use.\n"
+ "- Include the VERB people use when asking, not only nouns. Someone "
+ "asks 'where do I live', not 'residence' — so a page about where its "
+ "owner lives needs the verb form ('wohnen'), and one about a planned "
+ "move needs 'umziehen', not just 'Umzug'. Give the plain dictionary "
+ "form of the verb; matching handles the endings.\n"
+ f"- At most {MAX_ALIASES} terms, each at most three words.\n"
+ "- No sentences, no explanations, no markdown, no numbering.\n"
+ "- Do NOT repeat words already in the title — those are already "
+ "searchable.\n"
+ "- If nothing useful applies, return nothing at all.\n"
+ "\n"
+ "Answer with ONE term per line and nothing else.\n"
+ "\n"
+ f"Title: {title}\n"
+ f"Content:\n{excerpt}\n"
+ )
+
+
+def parse_alias_response(text: str, *, title: str = "") -> list[str]:
+ """Turn a model answer into a clean, bounded alias list.
+
+ Tolerant of the usual model habits (bullets, numbering, quotes, a stray
+ "Here are the terms:" line) because a malformed answer must degrade to
+ fewer aliases, never to an exception on the write path.
+ """
+ if not text:
+ return []
+ title_words = {w.lower() for w in re.findall(r"\w+", title)}
+ out: list[str] = []
+ seen: set[str] = set()
+ for raw_line in text.splitlines():
+ # Strip the list marker BEFORE the quotes: a quoted item behind a
+ # marker ('2) "Graka"') still has its quotes attached at this point,
+ # so stripping quotes first would leave them embedded and the term
+ # would be rejected as markup.
+ line = re.sub(r"^\s*(?:[-*•]|\d+[.)])\s*", "", raw_line.strip()).strip()
+ line = line.strip("\"'").strip()
+ if not line or len(line) > _MAX_ALIAS_CHARS:
+ continue
+ if not _ALIAS_RE.match(line) or len(line.split()) > 3:
+ continue
+ key = line.lower()
+ # A term the title already contains adds nothing — it is indexed
+ # anyway, at a higher weight. A pronoun identifies no page at all.
+ if key in seen or key in title_words or key in _USELESS_ALIASES:
+ continue
+ seen.add(key)
+ out.append(line)
+ if len(out) >= MAX_ALIASES:
+ break
+ return out
+
+
+def merge_aliases(existing: Any, generated: list[str]) -> list[str]:
+ """Union of hand-written and generated aliases, existing ones first.
+
+ Never drops what a human put there: the field is user-editable in
+ Obsidian, and a regeneration that silently deleted a curated term would
+ make the feature untrustworthy.
+ """
+ out: list[str] = []
+ seen: set[str] = set()
+ for source in (existing if isinstance(existing, list) else [], generated):
+ for item in source:
+ term = str(item).strip()
+ if not term or term.lower() in seen:
+ continue
+ seen.add(term.lower())
+ out.append(term)
+ return out[:MAX_ALIASES]
+
+
+async def generate_aliases(
+ *,
+ title: str,
+ body: str,
+ cfg: Any,
+ registry: Any,
+ languages: tuple[str, ...] | None = None,
+ timeout_s: float = 30.0,
+) -> list[str]:
+ """Search terms for one page, or ``[]`` when no provider is reachable.
+
+ Never raises. Every failure mode — no configured provider, no credential,
+ the whole chain exhausted, a malformed answer — returns an empty list with
+ a logged reason, because a page without aliases is merely as findable as
+ it is today, while a raising generator would block the write itself.
+ """
+ if not title.strip() and not body.strip():
+ return []
+ langs = languages or target_languages(cfg)
+
+ from jarvis.core.protocols import BrainMessage, BrainRequest # noqa: PLC0415
+ from jarvis.memory.wiki.provider_chain import ( # noqa: PLC0415
+ build_wiki_provider_chain,
+ complete_with_fallback,
+ credential_ready_wiki_providers,
+ )
+
+ # Same key-aware chain the curator uses: lead with the configured wiki
+ # provider, then every other registered provider that actually holds a
+ # credential (AP-22 — never a single-provider brick).
+ try:
+ available = set(registry.available())
+ chain = build_wiki_provider_chain(
+ primary=str(getattr(getattr(cfg, "brain", None), "primary", "") or ""),
+ model_override="",
+ available=available,
+ credential_ready=credential_ready_wiki_providers(
+ available=available, config=cfg
+ ),
+ )
+ except Exception: # noqa: BLE001 — a broken chain build must not block a write
+ log.warning("search_aliases: could not build a provider chain", exc_info=True)
+ return []
+ if not chain:
+ log.info(
+ "search_aliases: no credential-ready provider — page indexed "
+ "without a language bridge"
+ )
+ return []
+
+ prompt = build_alias_prompt(title=title, body=body, languages=langs)
+ request = BrainRequest(
+ messages=(BrainMessage(role="user", content=prompt),),
+ max_tokens=300,
+ temperature=0.2,
+ reasoning_effort="none",
+ )
+
+ # The chain awaits ``aggregate(stream)``, so this must be the shared ASYNC
+ # stream consumer — a synchronous one raises TypeError on every provider
+ # in the chain and looks like a total provider outage.
+ from jarvis.brain.streaming import aggregate # noqa: PLC0415
+
+ try:
+ result = await complete_with_fallback(
+ registry=registry,
+ chain=chain,
+ request=request,
+ timeout_s=timeout_s,
+ label="wiki-search-aliases",
+ aggregate=aggregate,
+ )
+ except Exception: # noqa: BLE001 — degrade to no aliases, never fail the write
+ log.warning("search_aliases: alias call raised", exc_info=True)
+ return []
+
+ if result is None:
+ log.info("search_aliases: provider chain exhausted — no aliases for %r", title)
+ return []
+ agg, provider = result
+ aliases = parse_alias_response(getattr(agg, "text", "") or "", title=title)
+ log.info(
+ "search_aliases: %d term(s) for %r via %s (%s)",
+ len(aliases),
+ title,
+ provider,
+ ",".join(langs),
+ )
+ return aliases
+
+
+# ---------------------------------------------------------------------------
+# Backfill over an existing vault
+# ---------------------------------------------------------------------------
+
+
+async def backfill_vault(
+ *,
+ vault_root: Any,
+ cfg: Any,
+ registry: Any,
+ dry_run: bool = True,
+ limit: int | None = None,
+ overwrite: bool = False,
+ skip_dirs: frozenset[str] | None = None,
+) -> dict[str, Any]:
+ """Add ``search_aliases`` to pages in an existing vault.
+
+ Existing vaults were written before the bridge existed, so their pages are
+ reachable only through their English words. This walks them once.
+
+ ``dry_run`` (the default) reports what WOULD change and writes nothing —
+ the field lands in the user's own Obsidian files, so the destructive
+ direction must be the one they opt into. ``overwrite`` regenerates pages
+ that already carry aliases; by default those are left alone, which makes
+ the run resumable and cheap to repeat after a partial failure.
+
+ Returns a summary dict; per-page failures are counted, never raised, so
+ one unreadable page cannot abort the whole run.
+ """
+ from pathlib import Path # noqa: PLC0415
+
+ from jarvis.memory.frontmatter import parse_frontmatter, write_frontmatter # noqa: PLC0415
+ from jarvis.memory.wiki.fts_index import SKIP_INDEX_DIRS # noqa: PLC0415
+
+ root = Path(vault_root)
+ skip = skip_dirs if skip_dirs is not None else SKIP_INDEX_DIRS
+ summary: dict[str, Any] = {
+ "scanned": 0,
+ "updated": 0,
+ "skipped_existing": 0,
+ "no_aliases": 0,
+ "failed": 0,
+ "dry_run": bool(dry_run),
+ "languages": list(target_languages(cfg)),
+ "pages": [],
+ }
+
+ # noqa ASYNC240: this is an offline maintenance sweep, not a request path.
+ # It is invoked from a background job / CLI where a blocking directory walk
+ # is correct and an anyio dependency would buy nothing.
+ for path in sorted(root.rglob("*.md")): # noqa: ASYNC240
+ if any(part in skip for part in path.relative_to(root).parts[:-1]):
+ continue
+ if limit is not None and summary["updated"] >= limit:
+ break
+ summary["scanned"] += 1
+ try:
+ raw = path.read_text(encoding="utf-8")
+ meta, body = parse_frontmatter(raw)
+ if meta.get(ALIAS_FIELD) and not overwrite:
+ summary["skipped_existing"] += 1
+ continue
+
+ title_match = re.search(r"^\s{0,3}#\s+(.+)", body, re.MULTILINE)
+ title = title_match.group(1).strip() if title_match else path.stem
+ generated = await generate_aliases(
+ title=title, body=body, cfg=cfg, registry=registry
+ )
+ if not generated:
+ summary["no_aliases"] += 1
+ continue
+
+ merged = merge_aliases(meta.get(ALIAS_FIELD), generated)
+ summary["pages"].append(
+ {"path": path.relative_to(root).as_posix(), "aliases": merged}
+ )
+ if not dry_run:
+ meta[ALIAS_FIELD] = merged
+ path.write_text(write_frontmatter(meta, body), encoding="utf-8")
+ summary["updated"] += 1
+ except Exception: # noqa: BLE001 — one bad page must not abort the run
+ summary["failed"] += 1
+ log.warning("search_aliases: backfill failed for %s", path, exc_info=True)
+
+ log.info(
+ "search_aliases backfill: scanned=%d updated=%d skipped=%d none=%d failed=%d "
+ "dry_run=%s",
+ summary["scanned"],
+ summary["updated"],
+ summary["skipped_existing"],
+ summary["no_aliases"],
+ summary["failed"],
+ dry_run,
+ )
+ return summary
diff --git a/tests/unit/brain/test_wiki_language_bridge.py b/tests/unit/brain/test_wiki_language_bridge.py
index e48398bbb7..c49633d0a6 100644
--- a/tests/unit/brain/test_wiki_language_bridge.py
+++ b/tests/unit/brain/test_wiki_language_bridge.py
@@ -108,6 +108,48 @@ def test_alias_hit_carries_frontmatter_and_a_preview(tmp_path: Path) -> None:
assert not hit.preview.startswith("#"), "preview must skip the H1"
+COMPOUND_PAGE = """---
+type: project
+slug: drugs-in-schools-project
+search_aliases: [Drogenprävention, Suchtprävention] # i18n-allow: German compound under test
+---
+
+# Drugs in schools
+
+## Summary
+A prevention project.
+"""
+
+
+def test_prefix_matching_reaches_into_compounds(tmp_path: Path) -> None:
+ """FTS5 matches whole tokens, which strands every German compound.
+
+ Measured on the real vault: a question using the first half of a German
+ compound did not find the page whose alias was the whole compound. Prefix
+ variants close that, and they matter for plurals too.
+ """
+ root, conn = _vault(tmp_path, {"drugs.md": COMPOUND_PAGE})
+ hits = VaultSearch(root, conn=conn).search("Drogen", k=5)
+ assert [h.path.stem for h in hits] == ["drugs"]
+
+
+def test_prefix_matching_does_not_fire_on_tiny_tokens(tmp_path: Path) -> None:
+ """A two- or three-letter prefix would match half the vault for nothing."""
+ from jarvis.memory.wiki.search import _build_match_expr
+
+ assert "*" not in _build_match_expr(["ab"])
+ assert _build_match_expr(["drogen"]) == '"drogen" OR "drogen"*'
+
+
+def test_exact_token_is_still_searched_alongside_the_prefix(tmp_path: Path) -> None:
+ """The prefix is OR-ed IN ADDITION, so exact matches keep their rank."""
+ from jarvis.memory.wiki.search import _build_match_expr
+
+ expr = _build_match_expr(["dinner", "viktoria"])
+ assert '"dinner"' in expr and '"dinner"*' in expr
+ assert '"viktoria"' in expr and '"viktoria"*' in expr
+
+
@pytest.mark.asyncio
async def test_relevance_gate_does_not_discard_alias_hits(tmp_path: Path) -> None:
"""The regression this file exists for.
diff --git a/tests/unit/memory/wiki/test_search_aliases.py b/tests/unit/memory/wiki/test_search_aliases.py
new file mode 100644
index 0000000000..db6f9e32b8
--- /dev/null
+++ b/tests/unit/memory/wiki/test_search_aliases.py
@@ -0,0 +1,352 @@
+"""Guards for the search-alias language bridge.
+
+Fully offline: no provider, no credential, no network. The model call is
+replaced by a fake so the parsing, merging, degradation and backfill logic is
+what gets tested.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+from typing import Any
+
+import pytest
+
+from jarvis.memory.frontmatter import parse_frontmatter
+from jarvis.memory.wiki import search_aliases as sa
+
+PAGE = """---
+type: entity
+slug: nvidia-geforce-rtx-5070-ti
+---
+
+# NVIDIA GeForce RTX 5070 Ti
+
+## Summary
+The user's GPU, used for local inference workloads.
+"""
+
+PAGE_WITH_ALIASES = """---
+type: entity
+slug: ruben
+search_aliases: [Handgepflegt]
+---
+
+# Ruben
+
+## Facts
+- Lives in San Francisco.
+"""
+
+
+class FakeCfg:
+ class brain: # noqa: N801 — mirrors the config attribute path
+ primary = "fake"
+ reply_language = "de"
+
+
+class FakeRegistry:
+ def available(self) -> list[str]:
+ return ["fake"]
+
+
+# ---------------------------------------------------------------------------
+# Language targeting
+# ---------------------------------------------------------------------------
+
+
+def test_pinned_reply_language_drives_the_bridge() -> None:
+ assert sa.target_languages(FakeCfg()) == ("de", "en")
+
+
+def test_english_user_gets_no_redundant_second_language() -> None:
+ class EnglishCfg:
+ class brain: # noqa: N801
+ primary = "fake"
+ reply_language = "en"
+
+ assert sa.target_languages(EnglishCfg()) == ("en",)
+
+
+def test_auto_falls_back_to_the_default_locale() -> None:
+ class AutoCfg:
+ class brain: # noqa: N801
+ primary = "fake"
+ reply_language = "auto"
+
+ assert sa.target_languages(AutoCfg()) == ("en",)
+
+
+# ---------------------------------------------------------------------------
+# Response parsing — a model answer is untrusted input
+# ---------------------------------------------------------------------------
+
+
+def test_parses_a_clean_list() -> None:
+ assert sa.parse_alias_response("Grafikkarte\nGraka\nGPU") == [
+ "Grafikkarte",
+ "Graka",
+ "GPU",
+ ]
+
+
+def test_tolerates_bullets_numbering_and_quotes() -> None:
+ messy = '- Grafikkarte\n2) "Graka"\n* GPU\n'
+ assert sa.parse_alias_response(messy) == ["Grafikkarte", "Graka", "GPU"]
+
+
+def test_rejects_sentences_and_markup() -> None:
+ noisy = (
+ "Here are the search terms you asked for:\n"
+ "Grafikkarte\n"
+ "This page is about a graphics card used for local inference work\n"
+ "**GPU**\n"
+ )
+ assert sa.parse_alias_response(noisy) == ["Grafikkarte"]
+
+
+def test_drops_terms_already_in_the_title() -> None:
+ """A word in the title is already indexed at a HIGHER weight."""
+ out = sa.parse_alias_response("NVIDIA\nGrafikkarte", title="NVIDIA GeForce RTX")
+ assert out == ["Grafikkarte"]
+
+
+def test_drops_pronouns_that_would_make_a_page_a_magnet() -> None:
+ """Observed on the first real run: the user's own entity page was offered
+ "ich"/"me"/"myself" — words present in almost every personal question."""
+ out = sa.parse_alias_response("ich\nme\nmyself\nBesitzer\nProfil")
+ assert out == ["Besitzer", "Profil"]
+
+
+def test_a_generic_but_identifying_word_survives() -> None:
+ """The pronoun filter must not become a general "sounds vague" filter —
+ "Auto" genuinely identifies a car page."""
+ assert "Auto" in sa.parse_alias_response("Auto\nSportwagen")
+
+
+def test_caps_the_alias_count() -> None:
+ many = "\n".join(f"term{i}" for i in range(50))
+ assert len(sa.parse_alias_response(many)) == sa.MAX_ALIASES
+
+
+def test_empty_and_garbage_responses_are_safe() -> None:
+ assert sa.parse_alias_response("") == []
+ assert sa.parse_alias_response("\n\n \n") == []
+
+
+# ---------------------------------------------------------------------------
+# Merging — never destroy what a human curated
+# ---------------------------------------------------------------------------
+
+
+def test_merge_keeps_handwritten_aliases_first() -> None:
+ assert sa.merge_aliases(["Handgepflegt"], ["Grafikkarte"]) == [
+ "Handgepflegt",
+ "Grafikkarte",
+ ]
+
+
+def test_merge_deduplicates_case_insensitively() -> None:
+ assert sa.merge_aliases(["GPU"], ["gpu", "Graka"]) == ["GPU", "Graka"]
+
+
+def test_merge_handles_a_missing_or_odd_existing_field() -> None:
+ assert sa.merge_aliases(None, ["a"]) == ["a"]
+ assert sa.merge_aliases("not-a-list", ["a"]) == ["a"]
+
+
+# ---------------------------------------------------------------------------
+# Degradation — a keyless install must still write pages
+# ---------------------------------------------------------------------------
+
+
+async def test_no_reachable_provider_yields_no_aliases_and_no_error(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """§3 universality: without a credential the page is simply as findable
+ as it is today — never an exception on the write path."""
+ monkeypatch.setattr(
+ "jarvis.memory.wiki.provider_chain.credential_ready_wiki_providers",
+ lambda **_: set(),
+ )
+ out = await sa.generate_aliases(
+ title="X", body="y", cfg=FakeCfg(), registry=FakeRegistry()
+ )
+ assert out == []
+
+
+async def test_an_exhausted_chain_yields_no_aliases(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ async def dead_chain(**_: Any) -> None:
+ return None
+
+ monkeypatch.setattr(
+ "jarvis.memory.wiki.provider_chain.credential_ready_wiki_providers",
+ lambda **_: {"fake"},
+ )
+ monkeypatch.setattr(
+ "jarvis.memory.wiki.provider_chain.complete_with_fallback", dead_chain
+ )
+ out = await sa.generate_aliases(
+ title="X", body="y", cfg=FakeCfg(), registry=FakeRegistry()
+ )
+ assert out == []
+
+
+async def test_a_raising_provider_never_escapes(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ async def boom(**_: Any) -> None:
+ raise RuntimeError("provider on fire")
+
+ monkeypatch.setattr(
+ "jarvis.memory.wiki.provider_chain.credential_ready_wiki_providers",
+ lambda **_: {"fake"},
+ )
+ monkeypatch.setattr("jarvis.memory.wiki.provider_chain.complete_with_fallback", boom)
+ out = await sa.generate_aliases(
+ title="X", body="y", cfg=FakeCfg(), registry=FakeRegistry()
+ )
+ assert out == []
+
+
+# ---------------------------------------------------------------------------
+# Backfill
+# ---------------------------------------------------------------------------
+
+
+def fake_model(monkeypatch: pytest.MonkeyPatch):
+ """Replace the whole generator with a deterministic stand-in."""
+
+ async def fake_generate(*, title: str, body: str, **_: Any) -> list[str]:
+ return ["Grafikkarte", "Graka"]
+
+ monkeypatch.setattr(sa, "generate_aliases", fake_generate)
+
+
+async def test_dry_run_reports_but_writes_nothing(
+ tmp_path: Path, fake_model: None
+) -> None:
+ page = tmp_path / "entities" / "gpu.md"
+ page.parent.mkdir(parents=True)
+ page.write_text(PAGE, encoding="utf-8")
+ before = page.read_text(encoding="utf-8")
+
+ summary = await sa.backfill_vault(
+ vault_root=tmp_path, cfg=FakeCfg(), registry=FakeRegistry(), dry_run=True
+ )
+
+ assert summary["updated"] == 1
+ assert summary["dry_run"] is True
+ assert page.read_text(encoding="utf-8") == before, "dry run must not write"
+
+
+async def test_apply_writes_the_field_and_keeps_the_body(
+ tmp_path: Path, fake_model: None
+) -> None:
+ page = tmp_path / "entities" / "gpu.md"
+ page.parent.mkdir(parents=True)
+ page.write_text(PAGE, encoding="utf-8")
+
+ await sa.backfill_vault(
+ vault_root=tmp_path, cfg=FakeCfg(), registry=FakeRegistry(), dry_run=False
+ )
+
+ meta, body = parse_frontmatter(page.read_text(encoding="utf-8"))
+ assert meta[sa.ALIAS_FIELD] == ["Grafikkarte", "Graka"]
+ assert meta["slug"] == "nvidia-geforce-rtx-5070-ti", "existing keys survive"
+ assert "local inference workloads" in body, "body untouched"
+
+
+async def test_pages_that_already_have_aliases_are_left_alone(
+ tmp_path: Path, fake_model: None
+) -> None:
+ page = tmp_path / "entities" / "ruben.md"
+ page.parent.mkdir(parents=True)
+ page.write_text(PAGE_WITH_ALIASES, encoding="utf-8")
+
+ summary = await sa.backfill_vault(
+ vault_root=tmp_path, cfg=FakeCfg(), registry=FakeRegistry(), dry_run=False
+ )
+
+ assert summary["skipped_existing"] == 1
+ meta, _ = parse_frontmatter(page.read_text(encoding="utf-8"))
+ assert meta[sa.ALIAS_FIELD] == ["Handgepflegt"], "curated aliases preserved"
+
+
+async def test_overwrite_merges_instead_of_replacing(
+ tmp_path: Path, fake_model: None
+) -> None:
+ page = tmp_path / "entities" / "ruben.md"
+ page.parent.mkdir(parents=True)
+ page.write_text(PAGE_WITH_ALIASES, encoding="utf-8")
+
+ await sa.backfill_vault(
+ vault_root=tmp_path,
+ cfg=FakeCfg(),
+ registry=FakeRegistry(),
+ dry_run=False,
+ overwrite=True,
+ )
+
+ meta, _ = parse_frontmatter(page.read_text(encoding="utf-8"))
+ assert meta[sa.ALIAS_FIELD][0] == "Handgepflegt", "human term still first"
+ assert "Grafikkarte" in meta[sa.ALIAS_FIELD]
+
+
+async def test_one_unreadable_page_does_not_abort_the_run(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, fake_model: None
+) -> None:
+ (tmp_path / "entities").mkdir(parents=True)
+ (tmp_path / "entities" / "good.md").write_text(PAGE, encoding="utf-8")
+ (tmp_path / "entities" / "bad.md").write_text(PAGE, encoding="utf-8")
+
+ real_parse = sa.__dict__.get("parse_frontmatter") # not imported at module level
+
+ def exploding_parse(text: str):
+ if "bad-marker" in text:
+ raise ValueError("corrupt frontmatter")
+ from jarvis.memory.frontmatter import parse_frontmatter as p
+
+ return p(text)
+
+ (tmp_path / "entities" / "bad.md").write_text(
+ PAGE.replace("slug:", "slug: bad-marker #"), encoding="utf-8"
+ )
+ monkeypatch.setattr("jarvis.memory.frontmatter.parse_frontmatter", exploding_parse)
+
+ summary = await sa.backfill_vault(
+ vault_root=tmp_path, cfg=FakeCfg(), registry=FakeRegistry(), dry_run=True
+ )
+
+ assert summary["scanned"] == 2
+ assert summary["failed"] + summary["updated"] == 2
+ assert real_parse is None # sanity: module keeps its import lazy
+
+
+async def test_limit_bounds_the_number_of_pages(
+ tmp_path: Path, fake_model: None
+) -> None:
+ (tmp_path / "entities").mkdir(parents=True)
+ for i in range(5):
+ (tmp_path / "entities" / f"p{i}.md").write_text(PAGE, encoding="utf-8")
+
+ summary = await sa.backfill_vault(
+ vault_root=tmp_path,
+ cfg=FakeCfg(),
+ registry=FakeRegistry(),
+ dry_run=True,
+ limit=2,
+ )
+ assert summary["updated"] == 2