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(skills): match-test + match-log routes — make the matcher inspectable

Ruben Lütkede67c017c987
diff --git a/jarvis/ui/web/skills_routes.py b/jarvis/ui/web/skills_routes.py
index eb67582cb3..096475debd 100644
--- a/jarvis/ui/web/skills_routes.py
+++ b/jarvis/ui/web/skills_routes.py
@@ -555,6 +555,227 @@ async def reorder_skills(body: SkillOrderBody, request: Request) -> dict[str, An
return {"ok": True, "order": prefs.load_order()}
+# ----------------------------------------------------------------------
+# Match diagnostics — "why did (or didn't) my skill fire?"
+# ----------------------------------------------------------------------
+
+
+class MatchTestRequest(BaseModel):
+ """Body for ``POST /api/skills/match-test``.
+
+ POST rather than GET on purpose: an utterance is free text with umlauts,
+ slashes and newlines, and it has no business in a URL or an access log.
+ """
+
+ utterance: str = Field(..., min_length=1, max_length=2000)
+ lang: str = "auto"
+ include_disabled: bool = False
+
+
[email protected]("/match-test", openapi_extra={"x-jarvis-readonly": True})
+async def match_test(request: Request, body: MatchTestRequest) -> dict[str, Any]:
+ """Dry-run the skill matcher against an utterance and explain the verdict.
+
+ This is the affordance whose absence made the whole problem invisible: the
+ Skills view could list, enable, edit, reorder and link-check skills, but
+ there was no way to ask "would this sentence reach my skill?" short of
+ talking to the assistant and hoping.
+
+ Calls the SAME functions the brain calls — ``evaluate_match`` for the
+ decision, ``evaluate_guards`` for the vetoes, ``autofire_policy`` for
+ capture rights. A panel that re-implemented any of that would eventually
+ disagree with the brain, and a debugger that lies is worse than none.
+
+ Executes NOTHING. No ``render_instructions`` (that evaluates Jinja — a dry
+ run which evaluates templates is not dry), no ``SkillInvoked``, no bus
+ publish. It appends to the decision ring flagged ``dry_run`` so the panel
+ shows it while the durable trail stays honest.
+ """
+ registry = _require_registry(request)
+
+ from jarvis.skills import match_log
+ from jarvis.skills.autofire_policy import classify, may_capture
+ from jarvis.skills.guards import GUARD_ORDER, evaluate_guards
+ from jarvis.skills.match_eval import BAND_NONE, evaluate_match
+ from jarvis.skills.prefs import load_autofire_prefs
+ from jarvis.skills.relevance import get_index
+
+ config = getattr(request.app.state, "config", None)
+ skills_cfg = getattr(config, "skills", None)
+ min_band = str(getattr(skills_cfg, "auto_fire_min_band", "fire"))
+ shadow = bool(getattr(skills_cfg, "relevance_shadow", True))
+ enabled = bool(getattr(skills_cfg, "relevance_enabled", True))
+
+ decision = evaluate_match(
+ registry,
+ body.utterance,
+ lang=body.lang,
+ limit=8,
+ use_relevance=enabled,
+ fire_threshold=getattr(skills_cfg, "fire_threshold", None),
+ hint_threshold=getattr(skills_cfg, "hint_threshold", None),
+ )
+ overrides = load_autofire_prefs()
+
+ def _describe(name: str, band: str, evidence: str) -> dict[str, Any]:
+ try:
+ skill = registry.get(name)
+ except Exception: # noqa: BLE001
+ return {
+ "skill_name": name,
+ "state": "unknown",
+ "autofire_class": "",
+ "would_fire": False,
+ "vetoed_by": "unknown_skill",
+ }
+ ladder = evaluate_guards(
+ skill, user_text=body.utterance, evidence=evidence
+ )
+ allowed, capture_veto = may_capture(
+ skill, band, override=overrides.get(name), min_band=min_band
+ )
+ veto = ladder.vetoed_by or capture_veto
+ state = getattr(skill.state, "value", skill.state)
+ return {
+ "skill_name": name,
+ "state": str(state),
+ "autofire_class": classify(skill),
+ "auto_fire": overrides.get(name, "auto"),
+ "would_fire": bool(allowed and ladder.passed and band != BAND_NONE),
+ "vetoed_by": veto or None,
+ }
+
+ candidates: list[dict[str, Any]] = []
+ for candidate in decision.candidates:
+ entry = _describe(candidate.skill_name, candidate.band, candidate.evidence)
+ entry.update(
+ {
+ "score": round(float(candidate.score), 4),
+ "band": candidate.band,
+ "source": candidate.source,
+ "reason": candidate.reason,
+ "matched_terms": [
+ term for term, _ in (candidate.signals or ())
+ ],
+ "signals": {name: value for name, value in (candidate.signals or ())},
+ }
+ )
+ candidates.append(entry)
+
+ # The full ladder for the winner, every guard with its verdict — not just
+ # the one that fired. When the answer is "nothing matched", knowing WHICH of
+ # the checks ate it is the entire point.
+ guards_evaluated: list[dict[str, Any]] = []
+ winner = decision.top.skill_name if decision.top is not None else ""
+ if winner:
+ try:
+ ladder = evaluate_guards(
+ registry.get(winner),
+ user_text=body.utterance,
+ evidence=decision.top.evidence if decision.top else "",
+ )
+ guards_evaluated = [
+ {"guard": r.guard, "verdict": r.verdict, "detail": r.detail or None}
+ for r in ladder.results
+ ]
+ except Exception: # noqa: BLE001
+ guards_evaluated = []
+ else:
+ guards_evaluated = [
+ {"guard": name, "verdict": "skipped", "detail": None}
+ for name in GUARD_ORDER
+ ]
+
+ top_entry = candidates[0] if candidates else None
+ would_fire = bool(top_entry and top_entry["would_fire"] and not shadow)
+
+ index = get_index(registry, include_inactive=body.include_disabled)
+ match_log.record(
+ utterance=body.utterance,
+ decision=decision,
+ lang=body.lang,
+ vetoed_by=(top_entry or {}).get("vetoed_by") or "",
+ autofire_class=(top_entry or {}).get("autofire_class") or "",
+ fired=False,
+ dry_run=True,
+ )
+
+ return {
+ "utterance": body.utterance,
+ "lang": body.lang,
+ "elapsed_us": decision.elapsed_us,
+ "winner": winner or None,
+ "band": decision.band,
+ "source": decision.source,
+ "margin": round(float(decision.margin), 4),
+ "would_fire": would_fire,
+ "shadow_mode": shadow,
+ "relevance_enabled": enabled,
+ "autofire_class": (top_entry or {}).get("autofire_class") or None,
+ "vetoed_by": (top_entry or {}).get("vetoed_by"),
+ "candidates": candidates,
+ "guards_evaluated": guards_evaluated,
+ "thresholds": {
+ "fire": round(index.fire_threshold, 4),
+ "hint": round(index.hint_threshold, 4),
+ "min_band": min_band,
+ },
+ "corpus": {
+ "skills_indexed": index.size,
+ "distinct_terms": len(index.postings),
+ },
+ }
+
+
[email protected]("/match-log", openapi_extra={"x-jarvis-readonly": True})
+async def match_log_recent(
+ request: Request,
+ limit: int = 50,
+ skill: str = "",
+ fired: bool | None = None,
+) -> dict[str, Any]:
+ """Recent skill-match decisions, newest first.
+
+ Reads the process-local ring — no disk, no query. The ``vetoed_by`` column
+ is the feature: it turns "I said something and nothing happened" into "the
+ definitional guard suppressed plugin-github", which is the difference
+ between a guess and a diagnosis.
+ """
+ from jarvis.skills import match_log
+
+ entries = match_log.recent(limit=limit, skill=skill, fired=fired)
+ return {
+ "total": match_log.size(),
+ "capacity": match_log.MAX_ENTRIES,
+ "entries": [
+ {
+ "utterance_preview": entry.utterance_preview,
+ "utterance_hash": entry.utterance_hash,
+ "lang": entry.lang,
+ "source": entry.source,
+ "band": entry.band,
+ "winner": entry.winner or None,
+ "autofire_class": entry.autofire_class or None,
+ "vetoed_by": entry.vetoed_by or None,
+ "fired": entry.fired,
+ "shadow": entry.shadow,
+ "dry_run": entry.dry_run,
+ "elapsed_us": entry.elapsed_us,
+ "candidates": [
+ {
+ "skill_name": c.skill_name,
+ "score": round(float(c.score), 4),
+ "band": c.band,
+ "reason": c.reason,
+ }
+ for c in entry.candidates
+ ],
+ }
+ for entry in entries
+ ],
+ }
+
+
@router.get("/{name}")
async def get_skill(name: str, request: Request) -> dict[str, Any]:
reg = _require_registry(request)
diff --git a/tests/unit/ui/web/test_skills_match_routes.py b/tests/unit/ui/web/test_skills_match_routes.py
new file mode 100644
index 0000000000..4978776d70
--- /dev/null
+++ b/tests/unit/ui/web/test_skills_match_routes.py
@@ -0,0 +1,280 @@
+"""The match diagnostics endpoints — the "why didn't my skill fire?" surface.
+
+These two routes exist because their absence is what made the problem
+invisible for years: the Skills view could list, enable, edit, reorder and
+link-check skills, but there was no way to ask "would this sentence reach my
+skill?" without talking to the assistant and guessing from the answer.
+
+The properties under test are therefore about TRUST, not features:
+
+* the panel runs the same code the brain runs, so it cannot lie;
+* it executes nothing — no template rendering, no invocation event;
+* it reports EVERY guard's verdict, not only the one that vetoed, because when
+ the answer is "nothing matched", which check ate it is the whole question.
+"""
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+from jarvis.core.config import JarvisConfig
+from jarvis.skills import match_log, prefs, relevance
+from jarvis.skills.guards import GUARD_ORDER
+from jarvis.skills.registry import SkillRegistry
+
+# Speech input under test — the fixture vocabulary.
+FOCUS_TAGS = "[konzentrationsmodus, fokus]" # i18n-allow
+FIRE_UTTERANCE = "aktiviere den fokus und den konzentrationsmodus" # i18n-allow
+UNRELATED_UTTERANCE = "wie ist das wetter in berlin" # i18n-allow
+
+
[email protected](autouse=True)
+def _isolate(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("LOCALAPPDATA", str(tmp_path))
+ relevance.clear_index_cache()
+ match_log.clear()
+ yield
+ relevance.clear_index_cache()
+ match_log.clear()
+
+
+def _make_skill(
+ root: Path,
+ name: str,
+ *,
+ tags: str | None = None,
+ description: str = "test skill",
+ execution: str | None = None,
+ tier: str | None = None,
+) -> None:
+ folder = root / name
+ folder.mkdir(parents=True, exist_ok=True)
+ lines = [
+ "---",
+ 'schema_version: "1"',
+ f"name: {name}",
+ f"description: {description}",
+ ]
+ if tags:
+ lines.append(f"tags: {tags}")
+ if execution:
+ lines.append(f"execution: {execution}")
+ if tier:
+ lines += ["risk_policy:", f" default_tier: {tier}"]
+ lines += ["---", "", "## Body", ""]
+ (folder / "SKILL.md").write_text("\n".join(lines), encoding="utf-8")
+
+
+def _client(root: Path, *, shadow: bool = False) -> TestClient:
+ from jarvis.ui.web.skills_routes import router
+
+ registry = SkillRegistry(
+ root, bus=None, state_prefs_loader=prefs.load_state_overrides
+ )
+ registry.reload_sync()
+ config = JarvisConfig()
+ config.skills.relevance_shadow = shadow
+ app = FastAPI()
+ app.state.skill_registry = registry
+ app.state.config = config
+ app.include_router(router)
+ return TestClient(app)
+
+
+def skills_root(tmp_path: Path) -> Path:
+ root = tmp_path / "skills_src"
+ root.mkdir()
+ _make_skill(root, "focus", tags=FOCUS_TAGS)
+ for index in range(6):
+ _make_skill(root, f"filler-{index}", description=f"topic{index}")
+ return root
+
+
+# ---------------------------------------------------------------------------
+# match-test
+# ---------------------------------------------------------------------------
+
+
+def test_match_test_explains_a_hit(skills_root: Path) -> None:
+ client = _client(skills_root)
+ response = client.post("/api/skills/match-test", json={"utterance": FIRE_UTTERANCE})
+ assert response.status_code == 200
+ body = response.json()
+
+ assert body["winner"] == "focus"
+ assert body["band"] == "fire"
+ assert body["source"] == "relevance"
+ assert body["would_fire"] is True
+ assert body["autofire_class"] == "instruction"
+ assert body["vetoed_by"] is None
+ assert body["candidates"][0]["skill_name"] == "focus"
+ assert body["candidates"][0]["score"] > 0
+
+
+def test_match_test_reports_a_total_miss_without_pretending(
+ skills_root: Path,
+) -> None:
+ client = _client(skills_root)
+ body = client.post(
+ "/api/skills/match-test", json={"utterance": UNRELATED_UTTERANCE}
+ ).json()
+
+ assert body["winner"] is None
+ assert body["band"] == "none"
+ assert body["would_fire"] is False
+ # Even with nothing matched, the ladder is present so the maintainer can see
+ # that no guard was the reason — the corpus simply had no signal.
+ assert [g["guard"] for g in body["guards_evaluated"]] == list(GUARD_ORDER)
+ assert all(g["verdict"] == "skipped" for g in body["guards_evaluated"])
+
+
+def test_match_test_names_the_guard_that_suppressed_a_match(
+ skills_root: Path,
+) -> None:
+ """The single most useful field in the whole response."""
+ _make_skill(skills_root, "plugin-github", tags="[github]")
+ client = _client(skills_root)
+
+ body = client.post(
+ "/api/skills/match-test", json={"utterance": "was ist GitHub?"}
+ ).json()
+
+ assert body["winner"] == "plugin-github"
+ assert body["would_fire"] is False
+ assert body["vetoed_by"] == "definitional_question"
+ vetoed = [g for g in body["guards_evaluated"] if g["verdict"] == "veto"]
+ assert [g["guard"] for g in vetoed] == ["definitional_question"]
+
+
+def test_match_test_shows_a_dispatching_skill_as_ranked_but_barred(
+ skills_root: Path,
+) -> None:
+ """cloud-debug's shape: visible in the ranking, never allowed to fire."""
+ _make_skill(
+ skills_root,
+ "cloud-debug",
+ tags="[debugsprint]",
+ description="Dispatch a bug hunt to the background worker.",
+ execution="mission",
+ )
+ client = _client(skills_root)
+
+ body = client.post(
+ "/api/skills/match-test", json={"utterance": "mach mal einen debugsprint"}
+ ).json()
+
+ assert body["winner"] == "cloud-debug"
+ assert body["autofire_class"] == "dispatching"
+ assert body["would_fire"] is False
+ assert body["vetoed_by"] == "class_dispatching"
+
+
+def test_match_test_reports_shadow_mode_honestly(skills_root: Path) -> None:
+ """A maintainer must not read "would_fire: true" while shadow is on."""
+ client = _client(skills_root, shadow=True)
+ body = client.post(
+ "/api/skills/match-test", json={"utterance": FIRE_UTTERANCE}
+ ).json()
+
+ assert body["shadow_mode"] is True
+ assert body["band"] == "fire"
+ assert body["would_fire"] is False, "shadow mode must be reflected, not hidden"
+
+
+def test_match_test_exposes_the_thresholds_it_used(skills_root: Path) -> None:
+ client = _client(skills_root)
+ body = client.post(
+ "/api/skills/match-test", json={"utterance": FIRE_UTTERANCE}
+ ).json()
+
+ assert body["thresholds"]["fire"] > body["thresholds"]["hint"] > 0
+ assert body["thresholds"]["min_band"] == "fire"
+ assert body["corpus"]["skills_indexed"] >= 7
+
+
+def test_match_test_executes_nothing(skills_root: Path) -> None:
+ """No invocation event, and no Jinja rendering.
+
+ A "dry run" that evaluates templates is not dry — so the response carries no
+ rendered instructions at all.
+ """
+ client = _client(skills_root)
+ body = client.post(
+ "/api/skills/match-test", json={"utterance": FIRE_UTTERANCE}
+ ).json()
+
+ assert "instructions" not in body
+ assert "directive" not in body
+ entry = match_log.recent(1)[0]
+ assert entry.dry_run is True
+ assert entry.fired is False
+
+
+def test_match_test_rejects_an_empty_utterance(skills_root: Path) -> None:
+ client = _client(skills_root)
+ assert client.post("/api/skills/match-test", json={"utterance": ""}).status_code == 422
+
+
+def test_match_test_needs_a_registry() -> None:
+ from fastapi import FastAPI as _FastAPI
+
+ from jarvis.ui.web.skills_routes import router
+
+ app = _FastAPI()
+ app.include_router(router)
+ client = TestClient(app)
+ assert (
+ client.post("/api/skills/match-test", json={"utterance": "x"}).status_code == 503
+ )
+
+
+# ---------------------------------------------------------------------------
+# match-log
+# ---------------------------------------------------------------------------
+
+
+def test_match_log_starts_empty_and_records_decisions(skills_root: Path) -> None:
+ client = _client(skills_root)
+ assert client.get("/api/skills/match-log").json()["entries"] == []
+
+ client.post("/api/skills/match-test", json={"utterance": FIRE_UTTERANCE})
+ body = client.get("/api/skills/match-log").json()
+
+ assert body["total"] == 1
+ assert body["capacity"] == match_log.MAX_ENTRIES
+ entry = body["entries"][0]
+ assert entry["winner"] == "focus"
+ assert entry["dry_run"] is True
+ assert "konzentrationsmodus" in entry["utterance_preview"]
+ assert len(entry["utterance_hash"]) == 12
+
+
+def test_match_log_is_newest_first(skills_root: Path) -> None:
+ client = _client(skills_root)
+ client.post("/api/skills/match-test", json={"utterance": UNRELATED_UTTERANCE})
+ client.post("/api/skills/match-test", json={"utterance": FIRE_UTTERANCE})
+
+ entries = client.get("/api/skills/match-log").json()["entries"]
+ assert entries[0]["winner"] == "focus"
+ assert entries[1]["winner"] is None
+
+
+def test_match_log_filters_by_skill(skills_root: Path) -> None:
+ client = _client(skills_root)
+ client.post("/api/skills/match-test", json={"utterance": FIRE_UTTERANCE})
+ client.post("/api/skills/match-test", json={"utterance": UNRELATED_UTTERANCE})
+
+ filtered = client.get("/api/skills/match-log?skill=focus").json()["entries"]
+ assert len(filtered) == 1
+ assert filtered[0]["winner"] == "focus"
+
+
+def test_match_log_respects_the_limit(skills_root: Path) -> None:
+ client = _client(skills_root)
+ for _ in range(5):
+ client.post("/api/skills/match-test", json={"utterance": FIRE_UTTERANCE})
+ assert len(client.get("/api/skills/match-log?limit=2").json()["entries"]) == 2