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.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
test(skills): provider-free routing eval + calibrated thresholds (AP-27 gate)
Ruben Lütkebf905f00a783
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 698cf6937e..601f9b735a 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -190,6 +190,27 @@ jobs:if: matrix.os == 'ubuntu-latest'run: python scripts/ci/assert_min_passed.py report.xml+ # Its OWN blocking step, on purpose, and two traps avoided deliberately:+ #+ # * NOT carrying the `eval` marker. The suite above filters+ # `-m "not ... and not eval"`, so an `eval`-marked routing test would+ # silently never run — which is exactly how scripts/skill_routing_eval.py+ # became invisible.+ # * NOT folded into the pytest step above, which ends in `|| echo` and+ # therefore swallows failures until the min-passed floor moves.+ #+ # Measures precision AND recall together. Watching only precision is how+ # the wake-word subsystem destroyed its own recall twice without anyone+ # noticing (AP-27); recall may not drop without editing the committed+ # BASELINE.json in the same change, which puts it in the diff.+ - name: Skill routing eval (BLOCKING — precision AND recall)+ if: matrix.os == 'ubuntu-latest'+ shell: bash+ run: |+ python -m pytest tests/unit/skills/test_skill_routing_offline.py \+ -q -p no:cacheprovider+ python scripts/skill_relevance_calibrate.py+# jarvisctl control-CLI unit suite across the three supported desktops.# jarvisctl is a thin cross-platform HTTP client (paths via platformdirs,# UTF-8 I/O, no Windows APIs); this job proves it imports + its unit testsdiff --git a/jarvis/skills/eval_harness.py b/jarvis/skills/eval_harness.pynew file mode 100644index 0000000000..d5bbe3e55b--- /dev/null+++ b/jarvis/skills/eval_harness.py@@ -0,0 +1,451 @@+"""Offline routing eval — provider-free, importable, CI-runnable.++The point of this module is that it calls **exactly** the functions the runtime+calls: :func:`jarvis.skills.match_eval.evaluate_match` for the decision and+:func:`jarvis.skills.guards.evaluate_guards` for the vetoes. A harness that+re-implements the algorithm measures the harness, not the product — and the+number it prints would drift away from reality without anyone noticing.++It replaces nothing: ``scripts/skill_routing_eval.py`` still measures the+LLM-judged path against a live provider, which is a different question. This+one measures the deterministic layer, needs no key, no network and no+``BrainManager``, and therefore can block a pull request.++Why both precision and recall, always, in the same report: the wake-word+subsystem twice destroyed its own recall while tightening precision, and the+collapse was invisible because only precision was being watched (AP-27). A+report that shows one number is how that happens again.+"""+from __future__ import annotations++from dataclasses import dataclass, field+from pathlib import Path+from typing import Any++from jarvis.skills.guards import evaluate_guards+from jarvis.skills.match_eval import BAND_NONE, band_at_least, evaluate_match++#: Repo-relative location of the golden set.+GOLDEN_PATH = (+ Path(__file__).resolve().parents[2]+ / "tests"+ / "fixtures"+ / "skill_routing"+ / "golden.yaml"+)+BASELINE_PATH = GOLDEN_PATH.parent / "BASELINE.json"+++# ---------------------------------------------------------------------------+# Fixture loading+# ---------------------------------------------------------------------------+++@dataclass(frozen=True, slots=True)+class Positive:+ skill: str+ text: str+ lang: str = "auto"+ min_band: str = "narrow"+ source: str = "authored"+ #: Which layer MUST handle this utterance: ``trigger`` (the author's own+ #: regex) or ``relevance`` (the deterministic paraphrase channel).+ #:+ #: This field exists because the first run of this eval reported 100 %+ #: recall while 31 of 43 positives were merely echoing an unanchored+ #: plugin trigger — they would have passed in 2025 and proved nothing+ #: about the new layer. Declaring the channel makes that impossible to+ #: hide: a relevance positive silently falling back to a trigger match+ #: (or the reverse) now fails.+ channel: str = "relevance"+ #: A known, accepted gap. Reported prominently, never counted as a pass,+ #: never fails CI. Bounded by a test so it cannot become a dumping ground.+ known_gap: bool = False+++@dataclass(frozen=True, slots=True)+class Negative:+ text: str+ reason: str = ""+ #: Skill this is a hard negative FOR; empty means "for every skill".+ skill: str = ""+++@dataclass(frozen=True, slots=True)+class GoldenSet:+ positives: tuple[Positive, ...] = ()+ hard_negatives: tuple[Negative, ...] = ()+ global_negatives: tuple[Negative, ...] = ()++ @property+ def skills(self) -> tuple[str, ...]:+ return tuple(sorted({p.skill for p in self.positives}))+++def load_golden(path: Path | None = None) -> GoldenSet:+ """Parse the golden YAML. Raises loudly — a broken fixture must fail CI."""+ import yaml++ raw = yaml.safe_load((path or GOLDEN_PATH).read_text(encoding="utf-8")) or {}+ positives: list[Positive] = []+ hard: list[Negative] = []+ for skill, entry in (raw.get("skills") or {}).items():+ for item in (entry or {}).get("positives") or ():+ positives.append(+ Positive(+ skill=skill,+ text=str(item["text"]),+ lang=str(item.get("lang", "auto")),+ min_band=str(item.get("min_band", "narrow")),+ source=str(item.get("source", "authored")),+ channel=str(item.get("channel", "relevance")),+ known_gap=bool(item.get("known_gap", False)),+ )+ )+ for item in (entry or {}).get("hard_negatives") or ():+ hard.append(+ Negative(+ text=str(item["text"]),+ reason=str(item.get("reason", "")),+ skill=skill,+ )+ )+ globals_ = [+ Negative(text=str(item["text"]), reason=str(item.get("reason", "")))+ for item in (raw.get("global_negatives") or ())+ ]+ return GoldenSet(+ positives=tuple(positives),+ hard_negatives=tuple(hard),+ global_negatives=tuple(globals_),+ )+++# ---------------------------------------------------------------------------+# Registry under test — repo builtins ONLY+# ---------------------------------------------------------------------------+++class _StaticRegistry:+ """Minimal registry over a fixed skill list (no watchdog, no disk watch)."""++ def __init__(self, skills: list[Any]) -> None:+ self._skills = list(skills)+ self.generation = 1++ def list(self) -> list[Any]:+ return list(self._skills)++ def list_active(self) -> list[Any]:+ from jarvis.skills.schema import SkillLifecycleState++ return [+ s+ for s in self._skills+ if s.state+ in (SkillLifecycleState.ACTIVE, SkillLifecycleState.VALIDATED)+ ]++ def by_trigger(self, kind: str) -> list[Any]:+ out = []+ for skill in self._skills:+ frontmatter = getattr(skill, "frontmatter", None)+ if frontmatter is None:+ continue+ if any(t.type == kind for t in frontmatter.triggers):+ out.append(skill)+ return out++ def get(self, name: str) -> Any:+ for skill in self._skills:+ if skill.name == name:+ return skill+ raise KeyError(name)+++def builtin_registry() -> _StaticRegistry:+ """A registry over the SHIPPED builtin skills.++ Two deliberate exclusions, both about reproducibility:++ * Never ``user_skills_dir()`` — CI has no user directory, and the+ maintainer's own half-finished skills must not be able to turn a shared+ pipeline red.+ * Only names in ``BUILTIN_SKILL_NAMES``, not everything on disk. The+ working tree is shared with parallel sessions, so ``builtin/`` routinely+ contains untracked in-flight skills that do not exist in a fresh clone.+ Scoring against them would make the committed baseline unreproducible in+ CI and let another session's work-in-progress fail this gate.+ """+ from jarvis.skills.builtin import BUILTIN_SKILL_NAMES+ from jarvis.skills.loader import discover_skills++ root = Path(__file__).resolve().parent / "builtin"+ shipped = set(BUILTIN_SKILL_NAMES)+ return _StaticRegistry(+ [s for s in discover_skills(root) if s.name in shipped]+ )+++# ---------------------------------------------------------------------------+# Running+# ---------------------------------------------------------------------------+++@dataclass(frozen=True, slots=True)+class Outcome:+ """What the matcher actually did for one utterance."""++ text: str+ expected: str+ winner: str+ band: str+ source: str+ score: float+ vetoed_by: str+ passed: bool+ detail: str = ""+ #: Channel that actually handled it, vs the one the fixture demanded.+ channel: str = ""+ expected_channel: str = ""+ known_gap: bool = False+++@dataclass+class Report:+ positives: list[Outcome] = field(default_factory=list)+ negatives: list[Outcome] = field(default_factory=list)++ @property+ def scored_positives(self) -> list[Outcome]:+ """Positives that count — known gaps are reported, never scored."""+ return [o for o in self.positives if not o.known_gap]++ @property+ def known_gaps(self) -> list[Outcome]:+ return [o for o in self.positives if o.known_gap]++ @property+ def recall(self) -> float:+ scored = self.scored_positives+ if not scored:+ return 0.0+ return sum(o.passed for o in scored) / len(scored)++ @property+ def relevance_recall(self) -> float:+ """Recall over ONLY the positives the new layer is responsible for.++ This is the number that says whether the paraphrase channel works.+ Overall recall is inflated by the author-written triggers, which+ already worked before any of this existed.+ """+ scored = [o for o in self.scored_positives if o.expected_channel == "relevance"]+ if not scored:+ return 0.0+ return sum(o.passed for o in scored) / len(scored)++ @property+ def wrong_channel(self) -> list[Outcome]:+ return [+ o+ for o in self.scored_positives+ if o.winner and o.channel and o.channel != o.expected_channel+ ]++ @property+ def false_fires(self) -> list[Outcome]:+ return [o for o in self.negatives if not o.passed]++ @property+ def precision_ok(self) -> bool:+ return not self.false_fires++ def per_skill_recall(self) -> dict[str, float]:+ buckets: dict[str, list[bool]] = {}+ for outcome in self.positives:+ buckets.setdefault(outcome.expected, []).append(outcome.passed)+ return {+ skill: sum(values) / len(values) for skill, values in sorted(buckets.items())+ }+++def _decide(registry: Any, text: str, lang: str = "auto") -> tuple[Any, str]:+ """Run the real matcher + the real guards. Returns (decision, veto_reason)."""+ decision = evaluate_match(registry, text, lang=lang)+ if decision.top is None:+ return decision, ""+ try:+ skill = registry.get(decision.top.skill_name)+ except Exception: # noqa: BLE001+ return decision, ""+ ladder = evaluate_guards(+ skill,+ user_text=text,+ evidence=decision.top.evidence,+ )+ return decision, ladder.vetoed_by+++def run_eval(golden: GoldenSet | None = None, registry: Any | None = None) -> Report:+ """Score the golden set against the live deterministic matcher."""+ golden = golden or load_golden()+ registry = registry or builtin_registry()+ report = Report()++ for positive in golden.positives:+ decision, veto = _decide(registry, positive.text, positive.lang)+ winner = decision.top.skill_name if decision.top else ""+ effective_band = BAND_NONE if veto else decision.band+ passed = (+ not veto+ and winner == positive.skill+ and band_at_least(effective_band, positive.min_band)+ and decision.source == positive.channel+ )+ report.positives.append(+ Outcome(+ text=positive.text,+ expected=positive.skill,+ winner=winner,+ band=effective_band,+ source=decision.source,+ score=decision.top.score if decision.top else 0.0,+ vetoed_by=veto,+ passed=passed,+ channel=decision.source,+ expected_channel=positive.channel,+ known_gap=positive.known_gap,+ )+ )++ # A negative fails only when the matcher would CAPTURE the turn — a+ # narrow-band suggestion is free, because the model still decides.+ def _check_negative(text: str, reason: str, only_for: str = "") -> None:+ decision, veto = _decide(registry, text)+ winner = decision.top.skill_name if decision.top else ""+ fires = bool(decision.fired and not veto)+ if only_for:+ fires = fires and winner == only_for+ report.negatives.append(+ Outcome(+ text=text,+ expected=only_for or "(nothing)",+ winner=winner,+ band=BAND_NONE if veto else decision.band,+ source=decision.source,+ score=decision.top.score if decision.top else 0.0,+ vetoed_by=veto,+ passed=not fires,+ detail=reason,+ )+ )++ for negative in golden.global_negatives:+ _check_negative(negative.text, negative.reason)+ for negative in golden.hard_negatives:+ _check_negative(negative.text, negative.reason, only_for=negative.skill)++ # Cross-skill negatives, generated: every positive is a hard negative for+ # every OTHER skill. Free coverage, and the best defence against two skills+ # whose vocabulary collides.+ for positive in golden.positives:+ decision, veto = _decide(registry, positive.text, positive.lang)+ if not decision.fired or veto:+ continue+ winner = decision.top.skill_name if decision.top else ""+ if winner == positive.skill:+ continue+ report.negatives.append(+ Outcome(+ text=positive.text,+ expected=positive.skill,+ winner=winner,+ band=decision.band,+ source=decision.source,+ score=decision.top.score if decision.top else 0.0,+ vetoed_by=veto,+ passed=False,+ detail=f"cross-skill: fired {winner} instead of {positive.skill}",+ )+ )++ return report+++def format_report(report: Report) -> str:+ """Human-readable summary — printed by CI so a red run names the skill."""+ lines: list[str] = []+ lines.append("Skill routing eval (deterministic layer, no provider)")+ lines.append("=" * 62)+ scored = report.scored_positives+ relevance = [o for o in scored if o.expected_channel == "relevance"]+ lines.append(+ f" recall (all) : {report.recall:.0%} "+ f"({sum(o.passed for o in scored)}/{len(scored)})"+ )+ lines.append(+ f" recall (relevance): {report.relevance_recall:.0%} "+ f"({sum(o.passed for o in relevance)}/{len(relevance)}) <- the new layer"+ )+ lines.append(+ f" false fires : {len(report.false_fires)} "+ f"of {len(report.negatives)} negatives"+ )+ if report.known_gaps:+ lines.append(f" known gaps : {len(report.known_gaps)} (reported, not scored)")+ lines.append("")+ lines.append(" per-skill recall:")+ for skill, value in report.per_skill_recall().items():+ flag = " " if value >= 0.5 else "!!"+ lines.append(f" {flag} {skill:26} {value:.0%}")+ misses = [o for o in report.scored_positives if not o.passed]+ if misses:+ lines.append("")+ lines.append(" missed positives:")+ for outcome in misses:+ got = outcome.winner or "(nothing)"+ veto = f" vetoed={outcome.vetoed_by}" if outcome.vetoed_by else ""+ lines.append(+ f" {outcome.expected:22} <- {outcome.text[:46]:46} "+ f"got {got} [{outcome.band}]{veto}"+ )+ if report.wrong_channel:+ lines.append("")+ lines.append(" WRONG CHANNEL (a fixture claim no longer holds):")+ for outcome in report.wrong_channel:+ lines.append(+ f" {outcome.text[:44]:44} expected {outcome.expected_channel}, "+ f"got {outcome.channel}"+ )+ if report.known_gaps:+ lines.append("")+ lines.append(" known gaps (not scored — the next work item):")+ for outcome in report.known_gaps:+ got = outcome.winner or "(nothing)"+ lines.append(+ f" {outcome.expected:22} <- {outcome.text[:44]:44} got {got}"+ )+ if report.false_fires:+ lines.append("")+ lines.append(" FALSE FIRES:")+ for outcome in report.false_fires:+ lines.append(+ f" {outcome.text[:46]:46} -> {outcome.winner} ({outcome.detail})"+ )+ return "\n".join(lines)+++__all__ = [+ "BASELINE_PATH",+ "GOLDEN_PATH",+ "GoldenSet",+ "Negative",+ "Outcome",+ "Positive",+ "Report",+ "builtin_registry",+ "format_report",+ "load_golden",+ "run_eval",+]diff --git a/jarvis/skills/match_eval.py b/jarvis/skills/match_eval.pyindex 148b5f44b5..201edc1726 100644--- a/jarvis/skills/match_eval.py+++ b/jarvis/skills/match_eval.py@@ -162,6 +162,61 @@ def _trigger_decision(registry: Any, user_text: str, lang: str) -> MatchDecision)+def _relevance_decision(registry: Any, user_text: str, *, limit: int) -> MatchDecision:+ """Deterministic relevance pass — the paraphrase channel.++ Bands are applied HERE rather than inside the scorer, so+ :mod:`jarvis.skills.relevance` stays a pure ranking function that knows+ nothing about capture policy, and the dependency stays one-directional.+ """+ try:+ from jarvis.skills.relevance import get_index++ index = get_index(registry)+ ranking = index.rank(user_text, limit=limit)+ except Exception: # noqa: BLE001 — matching must never break a turn+ return MatchDecision()+ if ranking.top is None:+ return MatchDecision()++ candidates = tuple(+ MatchCandidate(+ skill_name=scored.name,+ score=round(scored.score, 6),+ band=_band_for(scored.score, ranking),+ source=SOURCE_RELEVANCE,+ evidence=scored.evidence,+ reason=scored.reason,+ signals=(+ ("token", round(scored.token_score, 6)),+ ("trigram", round(scored.trigram_score, 6)),+ ),+ )+ for scored in ranking.ranked+ )+ top = candidates[0]+ # FIRE additionally requires a CLEAR winner. Two near-tied skills are+ # genuine ambiguity ("send a message" → slack or discord?) and must degrade+ # so the model disambiguates from a short list instead of the matcher+ # guessing and hijacking the turn.+ band = top.band if (top.band != BAND_FIRE or ranking.clear_winner) else BAND_NARROW+ return MatchDecision(+ band=band,+ source=SOURCE_RELEVANCE,+ top=top if band != BAND_NONE else None,+ candidates=candidates,+ margin=round(ranking.margin, 6),+ )+++def _band_for(score: float, ranking: Any) -> str:+ if score >= ranking.fire_threshold:+ return BAND_FIRE+ if score >= ranking.hint_threshold:+ return BAND_NARROW+ return BAND_NONE++def evaluate_match(registry: Any,user_text: str,@@ -206,10 +261,7 @@ def evaluate_match(if trigger is not None:return _stamp(trigger)- # Deterministic relevance fallback — wired in a later phase. Until then the- # behaviour below is exactly today's: a trigger miss is a total miss.- _ = limit- return _stamp(MatchDecision())+ return _stamp(_relevance_decision(registry, user_text, limit=limit))__all__ = [diff --git a/jarvis/skills/relevance.py b/jarvis/skills/relevance.pyindex 6adc845649..f96ad5effa 100644--- a/jarvis/skills/relevance.py+++ b/jarvis/skills/relevance.py@@ -124,11 +124,18 @@ MARGIN_REL = 0.25#: bare floats so they stay meaningful from a 5-skill fresh install to a#: 60-skill power user (see :meth:`SkillMatchIndex.fire_threshold`).#:-#: PLACEHOLDERS pending the offline calibration sweep, which picks the smallest-#: threshold with zero false positives over the hard-negative set and then-#: REPORTS the resulting recall. Do not hand-tune these to fix a single-#: over-fire; add a hard negative and re-run the sweep.-FIRE_COEFFICIENT = 0.62+#: Set by ``scripts/skill_relevance_calibrate.py``, which picks the smallest+#: FIRE threshold with ZERO false positives over the hard-negative set and then+#: REPORTS the recall that costs. Do not hand-tune these to make a single+#: over-fire go away — add a hard negative to the golden set and re-run the+#: sweep, so the trade-off lands in a diff instead of in someone's head.+#:+#: Calibrated 2026-07-25 against the shipped builtin corpus: the strongest+#: negative scored 1.139 while the configured FIRE threshold was 1.057, i.e.+#: below it — only the clear-winner margin rule was preventing a capture. Too+#: thin to rely on, so FIRE was raised to sit above the negative distribution+#: on its own.+FIRE_COEFFICIENT = 0.68HINT_COEFFICIENT = 0.22# ---------------------------------------------------------------------------diff --git a/scripts/ci/german-allowlist.txt b/scripts/ci/german-allowlist.txtindex 9586d1252e..3dd0e0d2f3 100644--- a/scripts/ci/german-allowlist.txt+++ b/scripts/ci/german-allowlist.txt@@ -375,3 +375,11 @@ docs/superpowers/specs/2026-07-06-interim-ack-redesign-design.md# --- TTS evaluation corpus: the German sentences ARE the evaluation data the# speech synthesis is scored on (product-surface test fixtures, reason 4) ---jarvis/speech/tts_eval/corpus.py++# --- Skill-routing golden set: every `text:` value is a simulated user+# utterance, i.e. the speech input the matcher is scored on. The file has+# no prose to translate — a future entry is, by construction, another+# fixture utterance, so this is not a "narrow it later" exemption (reason+# 4, same shape as tts_eval/corpus.py above). The harness and tests that+# READ this file are NOT exempt and stay English-checked. ---+tests/fixtures/skill_routing/golden.yamldiff --git a/scripts/skill_relevance_calibrate.py b/scripts/skill_relevance_calibrate.pynew file mode 100644index 0000000000..274d9d6d50--- /dev/null+++ b/scripts/skill_relevance_calibrate.py@@ -0,0 +1,170 @@+"""Calibrate the skill-relevance thresholds — offline, no provider, no network.++Answers one question with a number instead of a hunch: where do FIRE and NARROW+belong?++The operating point is chosen deliberately and stated out loud:++ T_FIRE = the SMALLEST threshold at which false positives over the hard+ negatives is EXACTLY ZERO — and then the resulting recall is+ REPORTED, never hidden.++Zero, not "low", because a wrong capture rewrites the turn's instructions and+removes the model's ability to decline; the maintainer notices that immediately,+while a missed skill is silent. Reporting the recall that this costs is the+other half — it is precisely the number the wake-word subsystem stopped+watching twice, and both times recall collapsed unnoticed (AP-27).++**The standing rule, and it matters more than the numbers:** if the zero-FP+threshold lands above the 60th percentile of the positive score distribution,+the ALGORITHM is not good enough. Fix the field weights or the skills'+vocabulary. Do NOT loosen the threshold, and do not hand-tune a coefficient to+make one over-fire go away — add a hard negative to the golden set and re-run+this.++Usage:+ python scripts/skill_relevance_calibrate.py # report+ python scripts/skill_relevance_calibrate.py --write-baseline+"""+from __future__ import annotations++import argparse+import json+import sys+from pathlib import Path++REPO = Path(__file__).resolve().parent.parent+sys.path.insert(0, str(REPO))++if sys.platform == "win32": # UTF-8 stdout; cp1252 is the Windows default+ for _stream in (sys.stdout, sys.stderr):+ reconfigure = getattr(_stream, "reconfigure", None)+ if reconfigure is not None:+ reconfigure(encoding="utf-8", errors="replace")+++def _percentile(values: list[float], fraction: float) -> float:+ if not values:+ return 0.0+ ordered = sorted(values)+ index = max(0, min(len(ordered) - 1, int(round(fraction * (len(ordered) - 1)))))+ return ordered[index]+++def main() -> int:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument(+ "--write-baseline",+ action="store_true",+ help="write tests/fixtures/skill_routing/BASELINE.json from this run",+ )+ args = parser.parse_args()++ from jarvis.skills.eval_harness import (+ BASELINE_PATH,+ builtin_registry,+ format_report,+ load_golden,+ run_eval,+ )+ from jarvis.skills.relevance import get_index++ golden = load_golden()+ registry = builtin_registry()+ index = get_index(registry)+ report = run_eval(golden, registry)++ print(format_report(report))+ print()+ print("Corpus")+ print("=" * 62)+ print(f" skills indexed : {index.size}")+ print(f" distinct tokens : {len(index.postings)}")+ print(f" idf(unknown term) : {index.idf_unknown:.3f}")+ print(f" T_FIRE (in effect) : {index.fire_threshold:.3f}")+ print(f" T_HINT (in effect) : {index.hint_threshold:.3f}")++ # --- score distributions ------------------------------------------------+ positive_scores: list[float] = []+ for positive in golden.positives:+ if positive.channel != "relevance" or positive.known_gap:+ continue+ ranking = index.rank(positive.text)+ hit = next((s for s in ranking.ranked if s.name == positive.skill), None)+ if hit is not None:+ positive_scores.append(hit.score)++ negative_scores: list[float] = []+ for negative in (*golden.global_negatives, *golden.hard_negatives):+ ranking = index.rank(negative.text)+ if ranking.top is not None:+ negative_scores.append(ranking.top.score)++ print()+ print("Score distributions (relevance channel only)")+ print("=" * 62)+ if positive_scores:+ print(+ f" positives n={len(positive_scores):3} "+ f"min={min(positive_scores):.3f} p25={_percentile(positive_scores, 0.25):.3f} "+ f"p60={_percentile(positive_scores, 0.60):.3f} max={max(positive_scores):.3f}"+ )+ if negative_scores:+ print(+ f" negatives n={len(negative_scores):3} "+ f"min={min(negative_scores):.3f} p75={_percentile(negative_scores, 0.75):.3f} "+ f"max={max(negative_scores):.3f}"+ )++ # --- the operating point ------------------------------------------------+ print()+ print("Operating point")+ print("=" * 62)+ zero_fp = (max(negative_scores) if negative_scores else 0.0) + 1e-6+ p60 = _percentile(positive_scores, 0.60)+ print(f" smallest zero-false-positive T_FIRE : {zero_fp:.3f}")+ print(f" 60th percentile of positives : {p60:.3f}")+ kept = sum(1 for s in positive_scores if s >= zero_fp)+ total = len(positive_scores) or 1+ print(f" recall AT that threshold : {kept}/{total} ({kept / total:.0%})")++ if positive_scores and zero_fp > p60:+ print()+ print(" VERDICT: the zero-FP threshold sits ABOVE the 60th percentile of")+ print(" positives. Per the standing rule this is an ALGORITHM problem, not")+ print(" a threshold problem. Fix field weights or the skills' vocabulary —")+ print(" do NOT loosen the threshold to make this line go away.")+ else:+ print()+ print(" VERDICT: negatives separate cleanly from positives; the configured")+ print(" thresholds have headroom on both sides.")++ if args.write_baseline:+ payload = {+ "note": (+ "Committed baseline for tests/unit/skills/"+ "test_skill_routing_offline.py. Lowering any number here is a "+ "RECALL REGRESSION and must be justified in the same change."+ ),+ "macro_recall": round(report.recall, 6),+ "relevance_recall": round(report.relevance_recall, 6),+ "false_fires": len(report.false_fires),+ "known_gaps": len(report.known_gaps),+ "positives_scored": len(report.scored_positives),+ "negatives": len(report.negatives),+ "per_skill": {+ skill: round(value, 6)+ for skill, value in report.per_skill_recall().items()+ },+ }+ BASELINE_PATH.write_text(+ json.dumps(payload, indent=2, ensure_ascii=False) + "\n", encoding="utf-8"+ )+ print()+ print(f" wrote {BASELINE_PATH.relative_to(REPO)}")++ return 0 if (report.precision_ok and not report.wrong_channel) else 1+++if __name__ == "__main__":+ sys.exit(main())diff --git a/tests/fixtures/skill_routing/BASELINE.json b/tests/fixtures/skill_routing/BASELINE.jsonnew file mode 100644index 0000000000..bda3ca25bb--- /dev/null+++ b/tests/fixtures/skill_routing/BASELINE.json@@ -0,0 +1,35 @@+{+ "note": "Committed baseline for tests/unit/skills/test_skill_routing_offline.py. Lowering any number here is a RECALL REGRESSION and must be justified in the same change.",+ "macro_recall": 1.0,+ "relevance_recall": 1.0,+ "false_fires": 0,+ "known_gaps": 2,+ "positives_scored": 54,+ "negatives": 23,+ "per_skill": {+ "cli-gcloud": 1.0,+ "control-api": 0.0,+ "deep-work-mode": 1.0,+ "morning-routine": 1.0,+ "plugin-airtable": 1.0,+ "plugin-asana": 1.0,+ "plugin-cal_com": 1.0,+ "plugin-canva": 1.0,+ "plugin-clickup": 1.0,+ "plugin-cloudflare": 1.0,+ "plugin-discord": 1.0,+ "plugin-dropbox": 1.0,+ "plugin-github": 1.0,+ "plugin-gmail": 1.0,+ "plugin-google_calendar": 1.0,+ "plugin-google_drive": 0.5,+ "plugin-linear": 1.0,+ "plugin-notion": 1.0,+ "plugin-slack": 1.0,+ "plugin-stripe": 1.0,+ "plugin-supabase": 1.0,+ "plugin-todoist": 1.0,+ "plugin-vercel": 1.0,+ "skill-creator": 1.0+ }+}diff --git a/tests/fixtures/skill_routing/golden.yaml b/tests/fixtures/skill_routing/golden.yamlnew file mode 100644index 0000000000..fa9754a63b--- /dev/null+++ b/tests/fixtures/skill_routing/golden.yaml@@ -0,0 +1,549 @@+# Golden routing set for the deterministic skill matcher.+#+# Every `text` here is a SIMULATED USER UTTERANCE — matching data, the content+# under test, not project prose. That is why this file is German-heavy.+#+# Rules this file must obey (enforced by tests/unit/skills/test_skill_routing_offline.py):+#+# 1. A positive must NOT match the skill's own voice-trigger regex. If it+# does, it proves nothing about the relevance layer — it would have fired+# in 2025 already. The anti-echo test rejects such entries.+# 2. `min_band` records the WEAKEST acceptable outcome, and it is a MEASURED+# baseline, not an aspiration. Raising one is a real improvement; lowering+# one is a regression that must be visible in a diff.+# 3. Cross-skill negatives are GENERATED, not written: every skill's positives+# are automatically hard negatives for every other skill.+# 4. `global_negatives` must reach band `none` for EVERY skill. These are the+# turns the assistant owns itself — smalltalk, knowledge questions, coding+# help, and the local-action commands the deterministic desktop gate owns.+#+# Provenance markers: `authored` = written for this file, `eval` = lifted from+# scripts/skill_routing_eval.py, `forensic` = a real utterance quoted in a bug+# comment. A skill whose positives are 100 % `authored` gets a warning: real+# paraphrases come from real transcripts.++skills:+ deep-work-mode:+ positives:+ - text: "aktiviere bitte den konzentrationsmodus"+ channel: relevance+ lang: de+ min_band: fire+ source: authored+ - text: "ich will jetzt in den fokus modus"+ channel: relevance+ lang: de+ min_band: narrow+ source: authored+ - text: "put me into deep work for the next hour"+ channel: relevance+ lang: en+ min_band: narrow+ source: authored+ - text: "starte mir bitte einen fokus sprint"+ channel: relevance+ lang: de+ min_band: narrow+ source: authored+ hard_negatives:+ - text: "was bedeutet eigentlich deep work als konzept"+ reason: definitional question about the topic, not a request to enter it+ - text: "erzaehl mir was ueber konzentration und produktivitaet"+ reason: knowledge question, no activation intent++ morning-routine:+ positives:+ - text: "gib mir bitte den tagesueberblick"+ channel: trigger+ lang: de+ min_band: narrow+ source: authored+ - text: "mach mir mein morgen briefing"+ channel: trigger+ lang: de+ min_band: narrow+ source: authored+ - text: "run my morning briefing please"+ channel: trigger+ lang: en+ min_band: narrow+ source: authored+ hard_negatives:+ - text: "was ist eine morgenroutine ueberhaupt"+ reason: definitional question++ plugin-gmail:+ positives:+ - text: "lies mir meine neuen nachrichten im posteingang vor"+ channel: trigger+ lang: de+ min_band: fire+ source: authored+ - text: "gibt es was neues in meinem postfach"+ channel: trigger+ lang: de+ min_band: narrow+ source: authored+ - text: "check my inbox for anything important"+ channel: relevance+ lang: en+ min_band: narrow+ source: authored+ - text: "schreib eine mail an das team"+ channel: relevance+ lang: de+ min_band: narrow+ source: authored+ hard_negatives:+ - text: "was ist Gmail eigentlich fuer ein dienst"+ reason: definitional question about the app++ plugin-github:+ positives:+ - text: "zeig mir meine offenen pull requests"+ channel: trigger+ lang: de+ min_band: narrow+ source: authored+ - text: "gibt es neue kommentare am repository"+ channel: trigger+ lang: de+ min_band: narrow+ source: authored+ - text: "list the open issues in the repo"+ channel: trigger+ lang: en+ min_band: narrow+ source: authored+ hard_negatives:+ - text: "was ist eigentlich GitHub fuer eine plattform?"+ reason: definitional question (negative control, skill-routing eval)++ plugin-google_calendar:+ positives:+ - text: "was steht denn heute so im kalender"+ channel: trigger+ lang: de+ min_band: narrow+ source: authored+ - text: "verschieb meinen termin auf morgen nachmittag"+ channel: trigger+ lang: de+ min_band: narrow+ source: authored+ - text: "do i have any meetings this afternoon"+ channel: trigger+ lang: en+ min_band: narrow+ source: authored++ plugin-slack:+ positives:+ - text: "poste das kurz in den slack kanal"+ channel: trigger+ lang: de+ min_band: narrow+ source: authored+ - text: "any new messages in my slack workspace"+ channel: trigger+ lang: en+ min_band: narrow+ source: authored++ plugin-stripe:+ positives:+ - text: "wie sieht mein guthaben bei stripe aus"+ channel: trigger+ lang: de+ min_band: narrow+ source: authored+ - text: "zeig mir die offenen rechnungen und zahlungen"+ channel: trigger+ lang: de+ min_band: narrow+ source: authored+ - text: "show me this month's payments and refunds"+ channel: trigger+ lang: en+ min_band: narrow+ source: authored+ hard_negatives:+ - text: "was ist Stripe ueberhaupt und wofuer nutzt man das?"+ reason: definitional question (negative control, skill-routing eval)++ cli-gcloud:+ positives:+ - text: "wie viel kostet mich gerade meine google cloud diesen monat?"+ channel: relevance+ lang: de+ min_band: narrow+ source: eval+ - text: "zeig mir meine gcloud projekte und buckets"+ channel: relevance+ lang: de+ min_band: narrow+ source: authored+ - text: "what is my google cloud billing at right now"+ channel: relevance+ lang: en+ min_band: narrow+ source: authored++ plugin-notion:+ positives:+ - text: "such mir die seite in notion raus"+ channel: trigger+ lang: de+ min_band: narrow+ source: authored+ - text: "add this to my notion database"+ channel: trigger+ lang: en+ min_band: narrow+ source: authored++ plugin-linear:+ positives:+ - text: "welche linear tickets sind mir zugewiesen"+ channel: trigger+ lang: de+ min_band: narrow+ source: authored+ - text: "close that linear issue for me"+ channel: trigger+ lang: en+ min_band: narrow+ source: authored++ plugin-vercel:+ positives:+ - text: "ist das letzte deployment durchgelaufen"+ channel: trigger+ lang: de+ min_band: narrow+ source: authored+ - text: "check the vercel build status"+ channel: trigger+ lang: en+ min_band: narrow+ source: authored++ plugin-supabase:+ positives:+ - text: "fuehr mir die migration auf der supabase datenbank aus"+ channel: trigger+ lang: de+ min_band: narrow+ source: authored+ - text: "query the supabase table for me"+ channel: trigger+ lang: en+ min_band: narrow+ source: authored++ plugin-discord:+ positives:+ - text: "schreib das in den discord kanal"+ channel: trigger+ lang: de+ min_band: narrow+ source: authored+ - text: "read the latest messages on my discord server"+ channel: trigger+ lang: en+ min_band: narrow+ source: authored++ plugin-asana:+ positives:+ - text: "welche asana aufgaben stehen noch offen"+ channel: trigger+ lang: de+ min_band: narrow+ source: authored+ - text: "assign that asana task to me"+ channel: trigger+ lang: en+ min_band: narrow+ source: authored++ plugin-cloudflare:+ positives:+ - text: "aendere den dns eintrag bei cloudflare"+ channel: trigger+ lang: de+ min_band: narrow+ source: authored+ - text: "check my cloudflare zone settings"+ channel: trigger+ lang: en+ min_band: narrow+ source: authored++ plugin-google_drive:+ positives:+ - text: "such die datei in meinem google drive"+ channel: trigger+ lang: de+ min_band: narrow+ source: authored+ # Genuine cross-skill collision, not a scorer defect: since plugin-dropbox+ # started shipping, "share that <x> folder" describes both skills equally+ # well and Dropbox wins on "share"/"folder". A human would ask which one+ # too. Recorded as a gap rather than papered over with a threshold change.+ - text: "share that drive folder with the team"+ channel: relevance+ lang: en+ min_band: narrow+ source: authored+ known_gap: true++ plugin-dropbox:+ positives:+ - text: "lade die datei in meine dropbox hoch"+ channel: trigger+ lang: de+ min_band: narrow+ source: authored+ - text: "share the dropbox link with me"+ channel: trigger+ lang: en+ min_band: narrow+ source: authored++ plugin-todoist:+ positives:+ - text: "trag das bitte in todoist ein"+ channel: trigger+ lang: de+ min_band: narrow+ source: authored+ - text: "what is on my todoist list today"+ channel: trigger+ lang: en+ min_band: narrow+ source: authored++ plugin-clickup:+ positives:+ - text: "zeig mir die offenen clickup tasks"+ channel: trigger+ lang: de+ min_band: narrow+ source: authored+ - text: "create a clickup task for that"+ channel: trigger+ lang: en+ min_band: narrow+ source: authored++ plugin-airtable:+ positives:+ - text: "schreib die zeile in die airtable basis"+ channel: trigger+ lang: de+ min_band: narrow+ source: authored+ - text: "read the airtable records for me"+ channel: trigger+ lang: en+ min_band: narrow+ source: authored++ plugin-canva:+ positives:+ - text: "mach mir ein neues design in canva"+ channel: trigger+ lang: de+ min_band: narrow+ source: authored+ - text: "export that canva design as a pdf"+ channel: trigger+ lang: en+ min_band: narrow+ source: authored++ plugin-cal_com:+ positives:+ - text: "wann ist mein naechster termin bei cal com"+ channel: trigger+ lang: de+ min_band: narrow+ source: authored+ - text: "book a slot in cal com"+ channel: trigger+ lang: en+ min_band: narrow+ source: authored++ plugin-todoist:+ positives:+ - text: "setz milch auf meine todoist liste"+ channel: trigger+ lang: de+ min_band: narrow+ source: authored+ - text: "what's due in todoist today"+ channel: trigger+ lang: en+ min_band: narrow+ source: authored++ plugin-clickup:+ positives:+ - text: "zeig mir meine clickup aufgaben"+ channel: trigger+ lang: de+ min_band: narrow+ source: authored+ - text: "create a clickup task for the rewrite"+ channel: trigger+ lang: en+ min_band: narrow+ source: authored++ plugin-dropbox:+ positives:+ - text: "such den vertrag in meiner dropbox"+ channel: trigger+ lang: de+ min_band: narrow+ source: authored+ - text: "share that dropbox folder with anna"+ channel: trigger+ lang: en+ min_band: narrow+ source: authored++ plugin-canva:+ positives:+ - text: "mach mir ein canva poster fuer den vortrag"+ channel: trigger+ lang: de+ min_band: narrow+ source: authored+ - text: "export my canva design as a pdf"+ channel: trigger+ lang: en+ min_band: narrow+ source: authored++ plugin-airtable:+ positives:+ - text: "welche eintraege stehen in meiner airtable basis"+ channel: trigger+ lang: de+ min_band: narrow+ source: authored+ - text: "update that airtable record"+ channel: trigger+ lang: en+ min_band: narrow+ source: authored++ plugin-cal_com:+ positives:+ - text: "welche buchungen habe ich morgen in calcom"+ channel: trigger+ lang: de+ min_band: narrow+ source: authored+ - text: "cancel my calcom booking on friday"+ channel: trigger+ lang: en+ min_band: narrow+ source: authored++ skill-creator:+ positives:+ - text: "ich moechte einen neuen skill bauen"+ channel: relevance+ lang: de+ min_band: narrow+ source: authored+ - text: "turn this workflow into a skill"+ channel: relevance+ lang: en+ min_band: narrow+ source: authored++ # --- Known gaps -------------------------------------------------------+ # This skill carries no voice trigger AND thin, English-only vocabulary, so+ # a German request loses to a plugin whose product noun happens to collide.+ # Reported by the eval, never scored, never silently dropped. The fix is the+ # skill's own vocabulary, not a threshold change — which is exactly what the+ # quality gate is for.+ #+ # (jarvis-doc-author would belong here too, but it is on disk WITHOUT being+ # in BUILTIN_SKILL_NAMES, so a fresh install never receives it. The registry+ # coverage test caught that; do not add it back without shipping it first.)+ control-api:+ positives:+ - text: "aendere die antwortsprache auf englisch"+ channel: relevance+ lang: de+ min_band: narrow+ source: authored+ known_gap: true++# ---------------------------------------------------------------------------+# Utterances that must fire NOTHING, whatever is installed.+# ---------------------------------------------------------------------------+global_negatives:+ # -- smalltalk / conversation -------------------------------------------+ - text: "wie ist das wetter heute in berlin"+ channel: relevance+ reason: smalltalk+ - text: "erzaehl mir einen witz"+ channel: relevance+ reason: smalltalk+ - text: "guten abend, wie war dein tag"+ channel: relevance+ reason: smalltalk+ - text: "danke dir, das war sehr hilfreich"+ channel: relevance+ reason: acknowledgement+ # -- knowledge questions -------------------------------------------------+ - text: "kannst du mir kurz erklaeren wie photosynthese funktioniert"+ channel: relevance+ reason: knowledge question+ - text: "was haeltst du von rust als programmiersprache"+ channel: relevance+ reason: opinion question+ - text: "wer hat den zweiten weltkrieg beendet"+ channel: relevance+ reason: knowledge question+ - text: "was ist die hauptstadt von australien"+ channel: relevance+ reason: knowledge question+ # -- deliberation the assistant must answer, never act on ----------------+ - text: "kann ich dagegen rechtlich eigentlich was machen?"+ channel: relevance+ reason: forensic — user deliberating, not tasking (turn_planner)+ - text: "soll ich es einfach kaufen oder noch warten"+ channel: relevance+ reason: decision help, not an action request+ - text: "ich hab da mal eine frage, was wuerdest du mir empfehlen?"+ channel: relevance+ reason: forensic — conversational opener (manager.py force-spawn bug)+ # -- coding help ---------------------------------------------------------+ - text: "schreib mir eine funktion die eine liste sortiert"+ channel: relevance+ reason: coding request, no skill involved+ - text: "warum wirft mein python skript einen keyerror"+ channel: relevance+ reason: debugging question+ # -- local actions the deterministic desktop gate owns -------------------+ - text: "mach mal lauter"+ channel: relevance+ reason: local action, owned by the local-action gate+ - text: "mach einen screenshot"+ channel: relevance+ reason: local action+ - text: "schliess das fenster"+ channel: relevance+ reason: local action+ # -- mission vocabulary (AD-S9 owns these) -------------------------------+ - text: "spawne einen sub-agent der das recherchiert"+ channel: relevance+ reason: explicit heavy-work request, the mission path owns itdiff --git a/tests/unit/skills/test_skill_routing_offline.py b/tests/unit/skills/test_skill_routing_offline.pynew file mode 100644index 0000000000..0917fcf087--- /dev/null+++ b/tests/unit/skills/test_skill_routing_offline.py@@ -0,0 +1,268 @@+"""The blocking routing gate — precision AND recall, no provider required.++This is the AP-27 tripwire. The wake-word subsystem twice destroyed its own+recall while tightening precision, and both times the collapse was invisible+because only precision was being watched: "fires when it shouldn't" and "never+fires" share one root, so a fix aimed at one silently eats the other.++Three assertions of DIFFERENT kinds, deliberately:++1. recall floor — every golden positive still reaches its skill.+2. precision floor — zero captures on negatives.+3. no-regression — both numbers compared against a COMMITTED baseline.++(1) and (2) alone become a rubber stamp the moment someone tunes a threshold+until green. (3) alone lets both numbers drift down together. Together, a+precision fix that costs recall cannot land without literally writing the lower+number into BASELINE.json in the same change — which puts it in the diff and in+front of a reviewer.++Plus the anti-rubber-stamp tests, which are what decide whether any of this is+real. The first run of this eval reported 100 % recall while 31 of 43 positives+were merely echoing an unanchored plugin trigger — they would have passed in+2025 and proved nothing. That is why every positive now declares the channel+that must handle it.+"""+from __future__ import annotations++import json+import re++import pytest++from jarvis.skills import eval_harness+from jarvis.skills.eval_harness import (+ BASELINE_PATH,+ builtin_registry,+ format_report,+ load_golden,+ run_eval,+)+from jarvis.skills.match_eval import MATCH_BANDS, MATCH_SOURCES++#: Known gaps are reported but not scored. Bounded so the field cannot become+#: a place to bury failures — past this many, fix the skills instead.+MAX_KNOWN_GAPS = 6++#: Minimum sizes, so the set cannot be quietly hollowed out.+MIN_POSITIVES_PER_SKILL = 1+MIN_RELEVANCE_POSITIVES = 10+MIN_GLOBAL_NEGATIVES = 15++[email protected](scope="module")+def report() -> eval_harness.Report:+ return run_eval()++[email protected](scope="module")+def golden() -> eval_harness.GoldenSet:+ return load_golden()+++# ---------------------------------------------------------------------------+# 1 + 2: the floors+# ---------------------------------------------------------------------------+++def test_recall_floor_every_positive_reaches_its_skill(+ report: eval_harness.Report,+) -> None:+ misses = [o for o in report.scored_positives if not o.passed]+ assert not misses, "\n" + format_report(report)+++def test_precision_floor_no_negative_is_ever_captured(+ report: eval_harness.Report,+) -> None:+ """A NARROW suggestion on a negative is fine — the model still decides.++ Only a capture (band FIRE, surviving the guards) counts as a failure,+ because only a capture rewrites the turn's instructions.+ """+ assert not report.false_fires, "\n" + format_report(report)+++# ---------------------------------------------------------------------------+# 3: no regression against the committed baseline+# ---------------------------------------------------------------------------+++def test_no_regression_vs_baseline(report: eval_harness.Report) -> None:+ """Recall may not drop without editing BASELINE.json in the same change.++ That is the whole mechanism: a threshold tweak that buys precision by+ quietly costing recall becomes a visible number in the diff.+ """+ assert BASELINE_PATH.exists(), (+ f"{BASELINE_PATH.name} is missing — regenerate it with "+ "`python scripts/skill_relevance_calibrate.py --write-baseline`"+ )+ baseline = json.loads(BASELINE_PATH.read_text(encoding="utf-8"))++ assert report.recall >= baseline["macro_recall"] - 1e-9, (+ f"overall recall dropped from {baseline['macro_recall']:.0%} to "+ f"{report.recall:.0%}\n" + format_report(report)+ )+ assert report.relevance_recall >= baseline["relevance_recall"] - 1e-9, (+ f"RELEVANCE-channel recall dropped from "+ f"{baseline['relevance_recall']:.0%} to {report.relevance_recall:.0%} — "+ "this is the number that says whether the paraphrase layer works\n"+ + format_report(report)+ )+ assert len(report.false_fires) <= baseline["false_fires"], (+ "false fires increased\n" + format_report(report)+ )++ regressed = {+ skill: value+ for skill, value in report.per_skill_recall().items()+ if value < baseline["per_skill"].get(skill, 0.0) - 1e-9+ }+ assert not regressed, f"per-skill recall regressed: {regressed}"+++# ---------------------------------------------------------------------------+# Anti-rubber-stamp — the tests that test the tests+# ---------------------------------------------------------------------------+++def test_positives_route_through_their_declared_channel(+ report: eval_harness.Report,+) -> None:+ """A relevance positive must not be rescued by an author's regex.++ Without this, the eval measures 2025's behaviour and calls it a win: on the+ first run 31 of 43 positives were unanchored plugin-trigger echoes.+ """+ assert not report.wrong_channel, "\n" + format_report(report)+++def test_the_relevance_channel_carries_real_weight(+ report: eval_harness.Report, golden: eval_harness.GoldenSet+) -> None:+ """Enough positives must actually exercise the new layer."""+ relevance = [p for p in golden.positives if p.channel == "relevance"]+ assert len(relevance) >= MIN_RELEVANCE_POSITIVES+ assert report.relevance_recall > 0.0+++def test_a_relevance_positive_does_not_match_its_own_trigger_regex(+ golden: eval_harness.GoldenSet,+) -> None:+ """Structural version of the anti-echo rule, independent of the matcher.++ Checked against the raw regex rather than the match result, so it still+ holds if the trigger matcher itself is changed.+ """+ registry = builtin_registry()+ echoes: list[str] = []+ for positive in golden.positives:+ if positive.channel != "relevance":+ continue+ try:+ skill = registry.get(positive.skill)+ except KeyError:+ continue+ frontmatter = getattr(skill, "frontmatter", None)+ if frontmatter is None:+ continue+ for trigger in frontmatter.triggers:+ if trigger.type != "voice" or not trigger.pattern:+ continue+ try:+ if re.search(trigger.pattern, positive.text, re.IGNORECASE):+ echoes.append(f"{positive.skill}: {positive.text!r}")+ except re.error:+ continue+ assert not echoes, (+ "these 'relevance' positives are really trigger echoes and prove "+ "nothing about the new layer:\n " + "\n ".join(echoes)+ )+++def test_the_eval_detects_a_broken_matcher(monkeypatch: pytest.MonkeyPatch) -> None:+ """An eval that stays green against a crippled matcher is decoration.++ Cripple the scorer so it can never rank anything, and assert the suite+ NOTICES. This is the only test here that tests the test.+ """+ from jarvis.skills import relevance++ class _DeadIndex:+ names = ()++ def rank(self, text: str, *, limit: int = 5): # noqa: ANN202, ARG002+ return relevance.RelevanceRanking()++ monkeypatch.setattr(relevance, "get_index", lambda *a, **k: _DeadIndex())+ crippled = run_eval()++ assert crippled.relevance_recall == 0.0, (+ "the eval did not notice a completely dead relevance scorer — "+ "it is measuring the trigger path only"+ )+ assert crippled.recall < 1.0+++# ---------------------------------------------------------------------------+# Fixture hygiene+# ---------------------------------------------------------------------------+++def test_known_gaps_are_bounded(report: eval_harness.Report) -> None:+ """`known_gap` must stay an honest note, not a dumping ground."""+ assert len(report.known_gaps) <= MAX_KNOWN_GAPS+++def test_every_golden_skill_exists_in_the_registry(+ golden: eval_harness.GoldenSet,+) -> None:+ registry = builtin_registry()+ known = {s.name for s in registry.list()}+ unknown = [s for s in golden.skills if s not in known]+ assert not unknown, f"golden set names skills that no longer exist: {unknown}"+++def test_every_builtin_with_a_trigger_has_a_golden_entry(+ golden: eval_harness.GoldenSet,+) -> None:+ """A new builtin must not land without routing coverage."""+ registry = builtin_registry()+ covered = set(golden.skills)+ missing: list[str] = []+ for skill in registry.list():+ frontmatter = getattr(skill, "frontmatter", None)+ if frontmatter is None or skill.name in covered:+ continue+ if getattr(frontmatter, "state", None) == "disabled":+ continue+ if any(t.type == "voice" for t in frontmatter.triggers):+ missing.append(skill.name)+ assert not missing, (+ "these builtin skills have a voice trigger but no golden entry: "+ f"{missing} — add positives to tests/fixtures/skill_routing/golden.yaml"+ )+++def test_the_golden_set_is_big_enough(golden: eval_harness.GoldenSet) -> None:+ assert len(golden.global_negatives) >= MIN_GLOBAL_NEGATIVES+ per_skill: dict[str, int] = {}+ for positive in golden.positives:+ per_skill[positive.skill] = per_skill.get(positive.skill, 0) + 1+ thin = {k: v for k, v in per_skill.items() if v < MIN_POSITIVES_PER_SKILL}+ assert not thin, f"skills with too few positives: {thin}"+++def test_fixture_values_are_in_the_closed_vocabularies(+ golden: eval_harness.GoldenSet,+) -> None:+ for positive in golden.positives:+ assert positive.min_band in MATCH_BANDS, positive.text+ assert positive.channel in MATCH_SOURCES, positive.text+++def test_negatives_carry_a_reason(golden: eval_harness.GoldenSet) -> None:+ """A negative without a stated reason cannot be reviewed later."""+ missing = [n.text for n in golden.global_negatives if not n.reason.strip()]+ assert not missing, f"global negatives with no reason: {missing}"