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.

refactor(skills): one scorer for UI search and voice routing

Ruben Lütke3a141ae4d8aa
diff --git a/jarvis/skills/local_search.py b/jarvis/skills/local_search.py
index e37c841cce..cdd37b2e2a 100644
--- a/jarvis/skills/local_search.py
+++ b/jarvis/skills/local_search.py
@@ -1,9 +1,31 @@
"""Local skill search + sidebar filter routing for ``POST /api/skills/query``.
-This is the module the skills REST route imports. It deliberately does **not**
-require SQLite FTS5 or an LLM: the installed skill set is small (tens of
-entries), so a single in-memory pass with token scoring is both fast and
-cloud-first (runs on a 1-vCPU VPS with no GPU, no native extension).
+This is the module the skills REST route imports. It requires no SQLite FTS5 and
+no LLM: the installed skill set is small, so ranking happens in memory and the
+call never blocks on the network (it runs on a 1-vCPU VPS with no GPU and no
+native extension).
+
+**It no longer owns a scoring function.** Ranking is delegated to
+:mod:`jarvis.skills.relevance`, the same scorer the voice path uses. That is the
+whole point of this module's current shape: two independent scorers over the same
+corpus drift, and the drift is invisible — the UI search box would keep finding
+skills the assistant cannot, or the reverse, with nothing to catch it. A parity
+test pins the two surfaces to identical scores.
+
+The old local scorer also demonstrated the cost concretely: it weighted only
+name, tags, category and description, so it had no channel for trigger literals,
+``when_to_use`` or ``intent_objects``. Searching the box for a German trigger
+word a skill genuinely declares found nothing.
+
+Two deliberate differences remain between the surfaces, and both are structural
+rather than incidental:
+
+* The UI index includes INACTIVE skills — you must be able to find a draft in
+ order to promote it. The voice index does not (AP-15). One boolean, applied at
+ index-BUILD time rather than filtered at query time, so a draft is absent from
+ the voice vocabulary entirely instead of relying on a later check.
+* The structural filters below (category / state / risk / builtin / tags) are
+ UI-only sidebar concerns and have no business in the voice scorer.
Contract expected by ``jarvis/ui/web/skills_routes.py``:
@@ -11,31 +33,14 @@ Contract expected by ``jarvis/ui/web/skills_routes.py``:
- ``LocalSkillSearch(registry=..., brain=...)`` exposing ``_registry`` and ``_brain``
- ``await searcher.query(filters) -> tuple[list[SkillHit], bool]`` where each hit
carries ``.name`` / ``.score`` / ``.reason`` and the bool is ``brain_used``.
-
-With an empty query the call acts as a pure filter router (category / state /
-risk / builtin / tags). With a query it additionally token-scores name,
-description, tags and category and drops non-matching skills.
"""
from __future__ import annotations
-import re
from dataclasses import dataclass
from typing import Any
from jarvis.skills.builtin import BUILTIN_SKILL_NAMES
-
-# Field weights for query token scoring. Name matches are the strongest signal,
-# tags next, then category and free-text description.
-_WEIGHT_NAME = 3.0
-_WEIGHT_TAG = 2.0
-_WEIGHT_CATEGORY = 1.0
-_WEIGHT_DESCRIPTION = 1.0
-
-_TOKEN_RE = re.compile(r"[a-z0-9]+")
-
-
-def _tokens(text: str) -> list[str]:
- return _TOKEN_RE.findall(text.lower())
+from jarvis.skills.relevance import build_index
@dataclass(frozen=True)
@@ -105,65 +110,45 @@ class LocalSkillSearch:
return False
return True
- def _score(self, skill: Any, query_tokens: list[str]) -> tuple[float, str]:
- """Token-overlap score + a short human-readable reason.
+ async def query(self, filters: LocalSearchFilters) -> tuple[list[SkillHit], bool]:
+ """Filter, then rank with the shared scorer. Never raises on empty data."""
+ try:
+ skills = list(self._registry.list())
+ except Exception: # noqa: BLE001 — an empty registry is not an error
+ skills = []
+
+ candidates = [s for s in skills if self._passes_filters(s, filters)]
+ if not filters.q.strip():
+ # Pure filter routing for the sidebar: no query, no ranking, so the
+ # order is deterministic by name.
+ hits = [
+ SkillHit(name=s.name, score=0.0, reason="filter match")
+ for s in sorted(candidates, key=lambda s: s.name.lower())
+ ]
+ return self._limit(hits, filters), False
+
+ # Build over the FILTERED set so IDF reflects what the user is actually
+ # searching in — narrowing to one category should make that category's
+ # shared vocabulary less distinctive, not more.
+ index = build_index(candidates)
+ ranking = index.rank(filters.q, limit=max(1, filters.limit or 30))
+ hits = [
+ SkillHit(
+ name=scored.name,
+ score=round(scored.score, 6),
+ reason=scored.reason or "matched",
+ )
+ for scored in ranking.ranked
+ ]
- Returns ``(0.0, "")`` when the query matches nothing in this skill so
- the caller can drop it.
- """
- fm = getattr(skill, "frontmatter", None)
- name_tokens = set(_tokens(skill.name))
- desc_tokens = set(_tokens(getattr(fm, "description", "") or "")) if fm else set()
- cat_tokens = set(_tokens(getattr(fm, "category", "") or "")) if fm else set()
- tag_tokens = (
- {t for tag in (getattr(fm, "tags", []) or []) for t in _tokens(tag)}
- if fm
- else set()
- )
-
- score = 0.0
- matched_fields: list[str] = []
- for tok in set(query_tokens):
- if tok in name_tokens:
- score += _WEIGHT_NAME
- matched_fields.append("name")
- if tok in tag_tokens:
- score += _WEIGHT_TAG
- matched_fields.append("tag")
- if tok in cat_tokens:
- score += _WEIGHT_CATEGORY
- matched_fields.append("category")
- if tok in desc_tokens:
- score += _WEIGHT_DESCRIPTION
- matched_fields.append("description")
-
- if score == 0.0:
- return 0.0, ""
- ordered = list(dict.fromkeys(matched_fields)) # de-dupe, keep order
- return score, "matched " + ", ".join(ordered)
+ # No LLM rerank — keep the voice/UI path off the network (cloud-first).
+ return self._limit(hits, filters), False
- async def query(self, filters: LocalSearchFilters) -> tuple[list[SkillHit], bool]:
- """Filter + (optionally) rank the registry. Never raises on empty data."""
- skills = list(self._registry.list())
- query_tokens = _tokens(filters.q)
-
- hits: list[SkillHit] = []
- for skill in skills:
- if not self._passes_filters(skill, filters):
- continue
- if query_tokens:
- score, reason = self._score(skill, query_tokens)
- if score == 0.0:
- continue
- else:
- score, reason = 0.0, "filter match"
- hits.append(SkillHit(name=skill.name, score=score, reason=reason))
-
- # Highest score first; stable tie-break by name for deterministic output.
- hits.sort(key=lambda h: (-h.score, h.name))
+ @staticmethod
+ def _limit(hits: list[SkillHit], filters: LocalSearchFilters) -> list[SkillHit]:
if filters.limit and filters.limit > 0:
- hits = hits[: filters.limit]
+ return hits[: filters.limit]
+ return hits
- # No LLM rerank — keep the voice/UI path off the network (cloud-first).
- brain_used = False
- return hits, brain_used
+
+__all__ = ["LocalSearchFilters", "LocalSkillSearch", "SkillHit"]
diff --git a/tests/unit/skills/test_scorer_parity.py b/tests/unit/skills/test_scorer_parity.py
new file mode 100644
index 0000000000..98f0a2d3fa
--- /dev/null
+++ b/tests/unit/skills/test_scorer_parity.py
@@ -0,0 +1,259 @@
+"""One scorer, two surfaces — pinned.
+
+The UI search box and the voice matcher used to rank skills with two independent
+implementations. That drift is invisible while it happens and only shows up as a
+confusing product: the box finds a skill the assistant never will, or the
+reverse, with nothing to catch either.
+
+The old local scorer also had strictly less to work with — name, tags, category
+and description only. It had no channel for the trigger literals, ``when_to_use``
+or ``intent_objects`` where the German and Spanish vocabulary actually lives, so
+searching for a trigger word a skill genuinely declares found nothing.
+
+These tests pin the unification and the two differences that are deliberate:
+the UI must see inactive skills (you cannot promote a draft you cannot find),
+and the structural sidebar filters stay UI-only.
+"""
+from __future__ import annotations
+
+from typing import Any
+
+import pytest
+
+from jarvis.skills.local_search import LocalSearchFilters, LocalSkillSearch
+from jarvis.skills.relevance import build_index
+from jarvis.skills.schema import SkillLifecycleState
+
+# Speech input under test.
+TRIGGER_WORD = "fokusmodus" # i18n-allow
+INBOX_WORD = "posteingang" # i18n-allow
+
+
+class _FakeRiskPolicy:
+ def __init__(self, tier: str = "monitor") -> None:
+ self.default_tier = tier
+
+
+class _FakeFrontmatter:
+ def __init__(
+ self,
+ *,
+ category: str = "general",
+ description: str = "",
+ when_to_use: str = "",
+ tags: list[str] | None = None,
+ tier: str = "monitor",
+ triggers: list[Any] | None = None,
+ intent_objects: list[str] | None = None,
+ ) -> None:
+ self.category = category
+ self.description = description
+ self.when_to_use = when_to_use
+ self.tags = tags or []
+ self.risk_policy = _FakeRiskPolicy(tier)
+ self.triggers = triggers or []
+ self.intent_verbs: list[str] = []
+ self.intent_objects = intent_objects or []
+
+
+class _FakeTrigger:
+ def __init__(self, pattern: str) -> None:
+ self.type = "voice"
+ self.pattern = pattern
+
+
+class _FakeSkill:
+ def __init__(
+ self,
+ name: str,
+ frontmatter: _FakeFrontmatter | None = None,
+ state: SkillLifecycleState = SkillLifecycleState.ACTIVE,
+ ) -> None:
+ self.name = name
+ self.frontmatter = frontmatter
+ self.state = state
+
+
+class _FakeRegistry:
+ def __init__(self, skills: list[_FakeSkill]) -> None:
+ self._skills = skills
+ self.generation = 1
+
+ def list(self) -> list[_FakeSkill]:
+ return list(self._skills)
+
+ def list_active(self) -> list[_FakeSkill]:
+ return [
+ s
+ for s in self._skills
+ if s.state in (SkillLifecycleState.ACTIVE, SkillLifecycleState.VALIDATED)
+ ]
+
+
+def _corpus() -> list[_FakeSkill]:
+ skills = [
+ _FakeSkill(
+ "deep-work-mode",
+ _FakeFrontmatter(
+ category="productivity",
+ description="A distraction-free focus sprint.",
+ tags=["focus", "timer"],
+ triggers=[_FakeTrigger(f"({TRIGGER_WORD})")],
+ ),
+ ),
+ _FakeSkill(
+ "plugin-gmail",
+ _FakeFrontmatter(
+ category="communication",
+ description="Read and send email.",
+ intent_objects=[INBOX_WORD, "inbox"],
+ ),
+ ),
+ ]
+ skills += [
+ _FakeSkill(
+ f"filler-{index}",
+ _FakeFrontmatter(description=f"topic{index} placeholder"),
+ )
+ for index in range(6)
+ ]
+ return skills
+
+
+# ---------------------------------------------------------------------------
+# The parity contract
+# ---------------------------------------------------------------------------
+
+
+ "query",
+ [TRIGGER_WORD, INBOX_WORD, "focus sprint", "email", "topic3"],
+)
+async def test_ui_search_scores_match_the_shared_scorer(query: str) -> None:
+ """Same corpus, same query, identical scores.
+
+ Without this, the two surfaces re-diverge within a quarter and nothing
+ reports it.
+ """
+ skills = _corpus()
+ searcher = LocalSkillSearch(_FakeRegistry(skills))
+ hits, brain_used = await searcher.query(LocalSearchFilters(q=query, limit=10))
+ assert brain_used is False
+
+ expected = build_index(skills).rank(query, limit=10)
+ assert [h.name for h in hits] == [s.name for s in expected.ranked]
+ assert [h.score for h in hits] == [round(s.score, 6) for s in expected.ranked]
+
+
+async def test_a_trigger_literal_is_now_findable_in_the_ui() -> None:
+ """The concrete regression the old scorer had.
+
+ ``fokusmodus`` exists only inside the skill's trigger regex — a field the
+ previous local scorer never looked at, so the search box could not find it.
+ """
+ searcher = LocalSkillSearch(_FakeRegistry(_corpus()))
+ hits, _ = await searcher.query(LocalSearchFilters(q=TRIGGER_WORD))
+ assert hits
+ assert hits[0].name == "deep-work-mode"
+
+
+async def test_intent_objects_are_findable_too() -> None:
+ searcher = LocalSkillSearch(_FakeRegistry(_corpus()))
+ hits, _ = await searcher.query(LocalSearchFilters(q=INBOX_WORD))
+ assert hits
+ assert hits[0].name == "plugin-gmail"
+
+
+async def test_the_reason_names_the_field_that_matched() -> None:
+ """"matched name, description" told nobody anything."""
+ searcher = LocalSkillSearch(_FakeRegistry(_corpus()))
+ hits, _ = await searcher.query(LocalSearchFilters(q=TRIGGER_WORD))
+ assert ":" in hits[0].reason
+
+
+# ---------------------------------------------------------------------------
+# The deliberate differences
+# ---------------------------------------------------------------------------
+
+
+async def test_the_ui_can_find_a_draft_so_it_can_be_promoted() -> None:
+ """AP-15 excludes drafts from the VOICE index, never from the UI."""
+ skills = _corpus()
+ skills.append(
+ _FakeSkill(
+ "secret-draft",
+ _FakeFrontmatter(tags=["draftonlyterm"]),
+ state=SkillLifecycleState.DRAFT,
+ )
+ )
+ searcher = LocalSkillSearch(_FakeRegistry(skills))
+ hits, _ = await searcher.query(LocalSearchFilters(q="draftonlyterm"))
+ assert [h.name for h in hits] == ["secret-draft"]
+
+
+async def test_structural_filters_still_narrow_the_result() -> None:
+ searcher = LocalSkillSearch(_FakeRegistry(_corpus()))
+ hits, _ = await searcher.query(
+ LocalSearchFilters(q="", category="communication", limit=10)
+ )
+ assert [h.name for h in hits] == ["plugin-gmail"]
+
+
+async def test_a_filter_narrows_the_ranked_corpus_too() -> None:
+ """Ranking happens over the FILTERED set, so IDF reflects what is searched."""
+ searcher = LocalSkillSearch(_FakeRegistry(_corpus()))
+ hits, _ = await searcher.query(
+ LocalSearchFilters(q="focus", category="communication", limit=10)
+ )
+ assert all(h.name == "plugin-gmail" for h in hits)
+
+
+async def test_an_empty_query_is_deterministic_by_name() -> None:
+ searcher = LocalSkillSearch(_FakeRegistry(_corpus()))
+ hits, _ = await searcher.query(LocalSearchFilters(q="", limit=50))
+ names = [h.name for h in hits]
+ assert names == sorted(names, key=str.lower)
+
+
+async def test_the_limit_is_respected() -> None:
+ searcher = LocalSkillSearch(_FakeRegistry(_corpus()))
+ hits, _ = await searcher.query(LocalSearchFilters(q="", limit=3))
+ assert len(hits) == 3
+
+
+async def test_a_broken_registry_returns_nothing_instead_of_raising() -> None:
+ class _Exploding:
+ def list(self) -> list[_FakeSkill]:
+ raise RuntimeError("registry is on fire")
+
+ searcher = LocalSkillSearch(_Exploding())
+ hits, brain_used = await searcher.query(LocalSearchFilters(q="anything"))
+ assert hits == []
+ assert brain_used is False
+
+
+async def test_a_skill_without_frontmatter_is_still_searchable_by_name() -> None:
+ skills = _corpus()
+ skills.append(_FakeSkill("browser-tabs", None))
+ searcher = LocalSkillSearch(_FakeRegistry(skills))
+ hits, _ = await searcher.query(LocalSearchFilters(q="browser tabs"))
+ assert hits
+ assert hits[0].name == "browser-tabs"
+
+
+def test_local_search_owns_no_scoring_function() -> None:
+ """Structural guard: a second scorer must not creep back in.
+
+ The module may filter and join; the moment it starts weighting fields again,
+ the two surfaces are free to diverge.
+ """
+ from pathlib import Path
+
+ import jarvis.skills.local_search as module
+
+ source = Path(module.__file__).read_text(encoding="utf-8")
+ code = "\n".join(
+ line for line in source.splitlines() if not line.lstrip().startswith("#")
+ )
+ assert "_WEIGHT_" not in code
+ assert "def _score" not in code