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): extract capture guards + one shared match entry point

Ruben Lütkec00eb78be088
diff --git a/jarvis/skills/guards.py b/jarvis/skills/guards.py
new file mode 100644
index 0000000000..51172e1656
--- /dev/null
+++ b/jarvis/skills/guards.py
@@ -0,0 +1,362 @@
+"""Skill-capture guards — ONE definition, shared by every consumer.
+
+A "guard" answers a single question: *may this skill capture this turn?* Until
+now each answer lived inline in ``jarvis/brain/manager.py`` as a private method
+or a module-level helper, which meant the REST layer and any eval harness had
+to re-implement them — and a re-implementation eventually lies. That is the
+whole reason this module exists: ``manager.py``, ``POST /api/skills/match-test``
+and the offline routing eval all import the SAME functions, so the panel can
+never disagree with what the brain actually did.
+
+Design constraints (all load-bearing):
+
+* **Zero ``jarvis.*`` imports.** ``jarvis.brain`` already imports
+ ``jarvis.skills``; importing back would close a cycle. Guards that need a
+ brain-side verdict (the local-action gate, the force-spawn heuristic) receive
+ it as plain data from the caller instead of reaching for it. Everything here
+ is pure: same inputs, same verdict, no IO, no clock, no globals.
+* **Duck-typed skills.** ``skill`` is read via ``getattr`` exactly as
+ ``prompt_injection.py`` and ``local_search.py`` already do, so a test fake or
+ a dict-ish stub works without importing the schema.
+* **A closed veto vocabulary.** Every string a guard can return is a member of
+ :data:`VETO_REASONS`. A guard inventing an unlisted reason renders as a blank
+ cell in the UI — the silent version of a multi-layer drift bug — so a parity
+ test asserts the set matches the TypeScript union.
+
+Behaviour is deliberately identical to the inline originals; this module is a
+move, not a redesign. The one improvement is resolution: the old
+``_skill_is_blocked`` folded "no frontmatter" and "block tier" into a single
+boolean, and callers could not tell which fired. Here they are distinct
+reasons with the same verdict.
+"""
+from __future__ import annotations
+
+import re
+from dataclasses import dataclass
+from typing import Any, Literal
+
+# ---------------------------------------------------------------------------
+# Veto vocabulary (closed set — mirrored in TypeScript, pinned by a parity test)
+# ---------------------------------------------------------------------------
+
+VETO_DEFINITIONAL = "definitional_question"
+VETO_NO_FRONTMATTER = "no_frontmatter"
+VETO_BLOCK_TIER = "block_tier"
+VETO_DRAFT_STATE = "draft_state"
+VETO_DISABLED_STATE = "disabled_state"
+VETO_LOCAL_ACTION = "local_action_gate"
+VETO_EXPLICIT_HEAVY = "explicit_heavy_request"
+VETO_DISPATCHING_CLASS = "class_dispatching"
+VETO_AUTO_FIRE_NEVER = "auto_fire_never"
+VETO_BAND_BELOW_FLOOR = "band_below_floor"
+VETO_KILL_SWITCH = "kill_switch"
+VETO_SHADOW_MODE = "shadow_mode"
+
+VETO_REASONS: frozenset[str] = frozenset({
+ VETO_DEFINITIONAL,
+ VETO_NO_FRONTMATTER,
+ VETO_BLOCK_TIER,
+ VETO_DRAFT_STATE,
+ VETO_DISABLED_STATE,
+ VETO_LOCAL_ACTION,
+ VETO_EXPLICIT_HEAVY,
+ VETO_DISPATCHING_CLASS,
+ VETO_AUTO_FIRE_NEVER,
+ VETO_BAND_BELOW_FLOOR,
+ VETO_KILL_SWITCH,
+ VETO_SHADOW_MODE,
+})
+
+#: Guard identifiers, in the order the ladder evaluates them. Exposed so the
+#: Test-Match panel can render a stable ladder even when nothing vetoes.
+GUARD_ORDER: tuple[str, ...] = (
+ "frontmatter_present",
+ "lifecycle_state",
+ "risk_block_tier",
+ "definitional_question",
+ "explicit_heavy_request",
+ "local_action_gate",
+)
+
+Verdict = Literal["pass", "veto", "skipped"]
+
+
+# ---------------------------------------------------------------------------
+# Definitional-question guard (moved verbatim from manager.py:869-896)
+# ---------------------------------------------------------------------------
+
+# A bare-name plugin trigger ("Discord", "Stripe", "GitHub") fires on ANY
+# mention — including when the app is merely the SUBJECT of a knowledge
+# question ("was ist GitHub?", "what is Stripe?"). Such a turn must be
+# ANSWERED, not captured by the skill (live skill-routing eval 2026-06-24: both
+# negative controls over-fired here). Precision over recall: suppress ONLY when
+# the matched trigger token is the predicate of a copula in a definitional
+# opener — so a real data request that merely starts with "was ist" ("was ist
+# in meinem Posteingang?", token "posteingang") is NOT suppressed, because there
+# the token does not sit directly after the copula (the "in"/"mein" data context
+# breaks the predicate run).
+_DEFINITIONAL_OPENER_RE = re.compile(
+ r"^\s*(?:was\s+(?:ist|sind|bedeutet|war|waren)" # i18n-allow: speech-input matching data
+ r"|wof[üu]r\s+(?:ist|steht|braucht|nutzt|benutzt|verwendet)" # i18n-allow: speech input
+ r"|erkl[äa]r(?:e|st|en)?\b" # i18n-allow: speech input
+ r"|what(?:'s|\s+is|\s+are|\s+does)\b"
+ r"|tell\s+me\s+(?:about|what)\b"
+ r")",
+ re.IGNORECASE,
+)
+# Copula → (optional adverb, but NOT a data-context word) → optional article →
+# the matched token. ``%s`` is filled with the re.escape'd trigger token.
+# Words that mark a DATA context rather than a definition, and so break the
+# predicate run ("was ist IN MEINEM Posteingang" is a request, not a question
+# about what an inbox is).
+_DATA_CONTEXT = (
+ "in|auf|an|aus|von|mein|meine|meinem|meinen|my|on|from|of" # i18n-allow: speech input
+)
+_DEFINITIONAL_PREDICATE_TMPL = (
+ r"\b(?:ist|sind|war|waren|is|are|was|were|bedeutet|means)\s+" # i18n-allow: speech input
+ rf"(?:(?!\b(?:{_DATA_CONTEXT})\b)"
+ r"\w+\s+){0,2}"
+ r"(?:ein(?:e|er|en)?\s+|a\s+|an\s+|the\s+)?%s\b"
+)
+
+# Compiled predicate patterns are cached per token: the token comes from a
+# bounded vocabulary (trigger literals / skill names), so the cache cannot grow
+# with user input the way a per-utterance cache would.
+_PREDICATE_CACHE: dict[str, re.Pattern[str]] = {}
+_PREDICATE_CACHE_MAX = 512
+
+
+def is_definitional_question_about(user_text: str, token: str) -> bool:
+ """True when ``user_text`` is a definitional question whose subject IS the
+ matched trigger ``token`` — so firing that skill would be wrong.
+
+ ``token`` MUST be the raw span as it appeared in ``user_text`` (the regex
+ below does ``re.escape`` + ``\\b`` against the untouched text). Handing it a
+ normalized/transliterated token silently disables the guard for every
+ umlaut word.
+ """
+ if not user_text or not token:
+ return False
+ if not _DEFINITIONAL_OPENER_RE.match(user_text):
+ return False
+ pat = _PREDICATE_CACHE.get(token)
+ if pat is None:
+ pat = re.compile(_DEFINITIONAL_PREDICATE_TMPL % re.escape(token), re.IGNORECASE)
+ if len(_PREDICATE_CACHE) >= _PREDICATE_CACHE_MAX:
+ _PREDICATE_CACHE.clear()
+ _PREDICATE_CACHE[token] = pat
+ return bool(pat.search(user_text))
+
+
+# ---------------------------------------------------------------------------
+# Skill-state guards
+# ---------------------------------------------------------------------------
+
+#: Lifecycle states a skill may capture a turn in. Mirrors
+#: ``TriggerMatcher._is_matchable`` and ``SkillRegistry.list_active``.
+MATCHABLE_STATES: frozenset[str] = frozenset({"active", "validated"})
+
+
+def _state_value(skill: Any) -> str:
+ """Lifecycle state as a plain lowercase string, for enum or str alike."""
+ state = getattr(skill, "state", None)
+ return str(getattr(state, "value", state) or "").lower()
+
+
+def _risk_tier(skill: Any) -> str:
+ """``risk_policy.default_tier`` as a plain string, "" when unreadable."""
+ frontmatter = getattr(skill, "frontmatter", None)
+ if frontmatter is None:
+ return ""
+ policy = getattr(frontmatter, "risk_policy", None)
+ tier = getattr(policy, "default_tier", None)
+ return str(getattr(tier, "value", tier) or "").lower()
+
+
+def frontmatter_veto(skill: Any) -> str | None:
+ """Veto a skill whose frontmatter failed to parse.
+
+ Mirrors the ``fm is None -> True`` branch of the old ``_skill_is_blocked``:
+ without frontmatter there is no risk policy to consult, so the safe reading
+ is "blocked". Reported separately from :func:`block_tier_veto` purely so the
+ Test-Match panel can say *which* of the two fired.
+ """
+ return None if getattr(skill, "frontmatter", None) is not None else VETO_NO_FRONTMATTER
+
+
+def block_tier_veto(skill: Any) -> str | None:
+ """Veto a ``risk_policy.default_tier: block`` skill.
+
+ A block-tier skill must never capture a turn — it stays visible in the
+ listing and in UI search, and ``run-skill`` refuses it at execution time.
+ """
+ if getattr(skill, "frontmatter", None) is None:
+ return None # frontmatter_veto owns that case
+ return VETO_BLOCK_TIER if _risk_tier(skill) == "block" else None
+
+
+def lifecycle_veto(skill: Any) -> str | None:
+ """Veto a DRAFT or DISABLED skill (AP-15).
+
+ DRAFT skills are either parse failures or agent-authored drafts awaiting
+ review; DISABLED skills were explicitly turned off. Neither may fire
+ automatically, ever, by any path.
+ """
+ state = _state_value(skill)
+ if state in MATCHABLE_STATES:
+ return None
+ if state == "disabled":
+ return VETO_DISABLED_STATE
+ return VETO_DRAFT_STATE
+
+
+# ---------------------------------------------------------------------------
+# Brain-side guards — verdicts arrive as plain data (no reverse import)
+# ---------------------------------------------------------------------------
+
+#: Local-action gate modes that claim a turn outright. A DIRECT open or a
+#: COMPUTER_USE plan owns the turn; a pure dispatch (``None`` / ``UNSUPPORTED``)
+#: leaves it to the skill.
+LOCAL_ACTION_CLAIMING_MODES: frozenset[str] = frozenset({"direct", "computer_use"})
+
+
+def local_action_veto(local_action_mode: str | None) -> str | None:
+ """Veto when the deterministic desktop-control gate claims the turn.
+
+ Sibling of the explicit-heavy guard: a plugin skill that merely keyword-
+ matched an APP NAME ("Discord", "Spotify") must not suppress Computer-Use,
+ the universal GUI integration. Live bug 2026-06-21: ``plugin-discord``
+ matched the bare word "Discord", and the tool-less deep brain then claimed
+ it had no Discord access.
+
+ ``local_action_mode`` is the caller's already-computed
+ ``LocalActionMode.value`` (or ``None`` when the gate did not claim). Passed
+ in rather than computed here so this module keeps zero ``jarvis.*`` imports.
+ """
+ mode = (local_action_mode or "").lower()
+ return VETO_LOCAL_ACTION if mode in LOCAL_ACTION_CLAIMING_MODES else None
+
+
+def explicit_heavy_veto(is_explicit_heavy: bool) -> str | None:
+ """Veto when the utterance names a heavy-work vehicle (AD-S9).
+
+ An utterance that names the execution vehicle belongs to the mission path,
+ not the inline skill prompt. Forensic example:
+ "spawne einen Sub-Agent für Gmail". <!-- i18n-allow: forensic quote -->
+
+ The predicate is computed by the caller (it depends on live brain state:
+ the force-spawn pattern is built from the registered tool surface).
+ """
+ return VETO_EXPLICIT_HEAVY if is_explicit_heavy else None
+
+
+# ---------------------------------------------------------------------------
+# The ladder
+# ---------------------------------------------------------------------------
+
+
+@dataclass(frozen=True, slots=True)
+class GuardResult:
+ """One guard's outcome, for the Test-Match ladder."""
+
+ guard: str
+ verdict: Verdict
+ detail: str = ""
+
+
+@dataclass(frozen=True, slots=True)
+class GuardLadder:
+ """Every guard's outcome plus the first veto, if any.
+
+ ``vetoed_by`` is ``""`` when the skill may capture the turn. Guards after
+ the first veto are still reported, with verdict ``skipped``, so the panel
+ shows a stable ladder instead of a list that shrinks as vetoes fire.
+ """
+
+ results: tuple[GuardResult, ...] = ()
+ vetoed_by: str = ""
+
+ @property
+ def passed(self) -> bool:
+ return not self.vetoed_by
+
+
+def evaluate_guards(
+ skill: Any,
+ *,
+ user_text: str = "",
+ evidence: str = "",
+ local_action_mode: str | None = None,
+ is_explicit_heavy: bool = False,
+) -> GuardLadder:
+ """Run every capture guard and report the full ladder.
+
+ Args:
+ skill: The candidate skill (duck-typed: ``state``, ``frontmatter``).
+ user_text: The raw utterance, untouched — the definitional guard
+ matches against it directly.
+ evidence: The RAW matched span from the utterance (a regex trigger's
+ ``group(0)``, or the relevance winner's matched surface). Must not
+ be normalized, or the definitional guard goes blind on umlauts.
+ local_action_mode: ``LocalActionMode.value`` when the deterministic
+ desktop gate claimed the turn, else ``None``.
+ is_explicit_heavy: Caller's AD-S9 verdict.
+
+ Returns:
+ A :class:`GuardLadder`. ``ladder.passed`` is the single boolean the
+ brain needs; ``ladder.results`` is what the Test-Match panel renders.
+ """
+ checks: tuple[tuple[str, str | None], ...] = (
+ ("frontmatter_present", frontmatter_veto(skill)),
+ ("lifecycle_state", lifecycle_veto(skill)),
+ ("risk_block_tier", block_tier_veto(skill)),
+ ("definitional_question", (
+ VETO_DEFINITIONAL
+ if is_definitional_question_about(user_text, evidence)
+ else None
+ )),
+ ("explicit_heavy_request", explicit_heavy_veto(is_explicit_heavy)),
+ ("local_action_gate", local_action_veto(local_action_mode)),
+ )
+
+ results: list[GuardResult] = []
+ vetoed_by = ""
+ for name, reason in checks:
+ if vetoed_by:
+ results.append(GuardResult(guard=name, verdict="skipped"))
+ continue
+ if reason is None:
+ results.append(GuardResult(guard=name, verdict="pass"))
+ continue
+ vetoed_by = reason
+ results.append(GuardResult(guard=name, verdict="veto", detail=reason))
+ return GuardLadder(results=tuple(results), vetoed_by=vetoed_by)
+
+
+__all__ = [
+ "GUARD_ORDER",
+ "LOCAL_ACTION_CLAIMING_MODES",
+ "MATCHABLE_STATES",
+ "VETO_AUTO_FIRE_NEVER",
+ "VETO_BAND_BELOW_FLOOR",
+ "VETO_BLOCK_TIER",
+ "VETO_DEFINITIONAL",
+ "VETO_DISABLED_STATE",
+ "VETO_DISPATCHING_CLASS",
+ "VETO_DRAFT_STATE",
+ "VETO_EXPLICIT_HEAVY",
+ "VETO_KILL_SWITCH",
+ "VETO_LOCAL_ACTION",
+ "VETO_NO_FRONTMATTER",
+ "VETO_REASONS",
+ "VETO_SHADOW_MODE",
+ "GuardLadder",
+ "GuardResult",
+ "block_tier_veto",
+ "evaluate_guards",
+ "explicit_heavy_veto",
+ "frontmatter_veto",
+ "is_definitional_question_about",
+ "lifecycle_veto",
+ "local_action_veto",
+]
diff --git a/jarvis/skills/match_eval.py b/jarvis/skills/match_eval.py
new file mode 100644
index 0000000000..148b5f44b5
--- /dev/null
+++ b/jarvis/skills/match_eval.py
@@ -0,0 +1,230 @@
+"""One entry point for "which skill, if any, owns this utterance?".
+
+Every consumer — the brain's per-turn probe, ``POST /api/skills/match-test``,
+and the offline routing eval — calls :func:`evaluate_match` and reads the same
+:class:`MatchDecision`. That is the point: a Test-Match panel that re-implements
+the decision eventually disagrees with the brain, and a disagreeing debugger is
+worse than none.
+
+This module owns the *vocabulary* (bands, candidate and decision records) and
+the *orchestration*. It does not own a scoring algorithm — the deterministic
+relevance scorer lives in :mod:`jarvis.skills.relevance` and is consulted only
+when the author-written regex triggers miss.
+
+Layering, in evaluation order:
+
+1. **Author regex triggers** (:mod:`jarvis.skills.trigger_matcher`) — absolute
+ precedence. A hit is not scored and not second-guessed; it is the skill
+ author stating verbatim what the user says. Keeping this first is what makes
+ the relevance layer additive: no currently-working utterance changes
+ behaviour.
+2. **Deterministic relevance** — the paraphrase channel. Wired in a later
+ phase; until then this module reports ``NONE`` on a trigger miss, which is
+ exactly today's behaviour, so the eval harness can baseline the *current*
+ system honestly before the algorithm exists.
+
+Guards are NOT applied here. :func:`evaluate_match` answers "what matched";
+:mod:`jarvis.skills.guards` answers "may it capture the turn". Callers run both
+and report the ladder, so a suppressed match stays visible as *suppressed*
+rather than vanishing — the single biggest reason "my skill never fires" has
+been undebuggable.
+"""
+from __future__ import annotations
+
+import time
+from dataclasses import dataclass
+from typing import Any, Literal
+
+# ---------------------------------------------------------------------------
+# Band vocabulary (closed set — mirrored in TypeScript, pinned by a parity test)
+# ---------------------------------------------------------------------------
+
+BAND_FIRE = "fire"
+BAND_NARROW = "narrow"
+BAND_NONE = "none"
+
+#: Ordered strongest → weakest. Order is meaningful: :func:`band_at_least`
+#: compares by index.
+MATCH_BANDS: tuple[str, ...] = (BAND_FIRE, BAND_NARROW, BAND_NONE)
+
+Band = Literal["fire", "narrow", "none"]
+
+#: Where a decision came from. ``trigger`` is the author's regex, ``relevance``
+#: the deterministic scorer, ``none`` means nothing matched.
+SOURCE_TRIGGER = "trigger"
+SOURCE_RELEVANCE = "relevance"
+SOURCE_NONE = "none"
+
+MATCH_SOURCES: tuple[str, ...] = (SOURCE_TRIGGER, SOURCE_RELEVANCE, SOURCE_NONE)
+
+#: Score reported for an author-regex hit. A trigger match is absolute, not
+#: ranked — this value exists so the record has a number, and must never be
+#: compared against a relevance score (different scales entirely). Read
+#: ``candidate.source`` before reading ``candidate.score``.
+TRIGGER_MATCH_SCORE = 1.0
+
+
+def band_at_least(band: str, floor: str) -> bool:
+ """True when ``band`` is at least as strong as ``floor``.
+
+ ``band_at_least("fire", "narrow")`` is True; the reverse is False. Unknown
+ strings compare as the weakest band, so a typo fails closed.
+ """
+ def _rank(value: str) -> int:
+ try:
+ return MATCH_BANDS.index(value)
+ except ValueError:
+ return len(MATCH_BANDS)
+ return _rank(band) <= _rank(floor)
+
+
+# ---------------------------------------------------------------------------
+# Records
+# ---------------------------------------------------------------------------
+
+
+@dataclass(frozen=True, slots=True)
+class MatchCandidate:
+ """One ranked skill.
+
+ ``evidence`` is the RAW span from the utterance that caused the match —
+ untouched, not normalized. Downstream guards ``re.escape`` it against the
+ original text, so a transliterated token would silently blind them on every
+ umlaut word.
+ """
+
+ skill_name: str
+ score: float = 0.0
+ band: str = BAND_NONE
+ source: str = SOURCE_NONE
+ evidence: str = ""
+ reason: str = ""
+ #: ``(field, contribution)`` pairs — what made this skill score. Empty for a
+ #: trigger hit, which has no per-field breakdown.
+ signals: tuple[tuple[str, float], ...] = ()
+
+
+@dataclass(frozen=True, slots=True)
+class MatchDecision:
+ """The full outcome of one match evaluation.
+
+ ``band`` is the decision; ``candidates`` is the ranked field behind it, kept
+ even when the band is ``none`` so the Test-Match panel can show *near
+ misses* — "nothing matched" and "three skills nearly matched" are very
+ different diagnoses and the log must distinguish them.
+ """
+
+ band: str = BAND_NONE
+ source: str = SOURCE_NONE
+ top: MatchCandidate | None = None
+ candidates: tuple[MatchCandidate, ...] = ()
+ #: Gap between the best and the runner-up. ``0.0`` when there is no
+ #: runner-up or the decision came from a trigger.
+ margin: float = 0.0
+ elapsed_us: int = 0
+
+ @property
+ def fired(self) -> bool:
+ """True when this decision alone would capture the turn (pre-guards)."""
+ return self.band == BAND_FIRE and self.top is not None
+
+
+# ---------------------------------------------------------------------------
+# Evaluation
+# ---------------------------------------------------------------------------
+
+
+def _trigger_decision(registry: Any, user_text: str, lang: str) -> MatchDecision | None:
+ """Author-regex pass. ``None`` on a miss, so the caller can fall through."""
+ try:
+ from jarvis.skills.trigger_matcher import TriggerMatcher
+
+ hit = TriggerMatcher(registry).match_voice_with_match(user_text, lang=lang)
+ except Exception: # noqa: BLE001 — matching must never break a turn
+ return None
+ if hit is None:
+ return None
+ skill, match = hit
+ evidence = match.group(0) if match is not None else ""
+ candidate = MatchCandidate(
+ skill_name=str(getattr(skill, "name", "")),
+ score=TRIGGER_MATCH_SCORE,
+ band=BAND_FIRE,
+ source=SOURCE_TRIGGER,
+ evidence=evidence,
+ reason=f"voice trigger matched {evidence!r}",
+ )
+ return MatchDecision(
+ band=BAND_FIRE,
+ source=SOURCE_TRIGGER,
+ top=candidate,
+ candidates=(candidate,),
+ )
+
+
+def evaluate_match(
+ registry: Any,
+ user_text: str,
+ *,
+ lang: str = "auto",
+ limit: int = 5,
+) -> MatchDecision:
+ """Decide which skill, if any, owns ``user_text``.
+
+ Pure CPU: no LLM call, no disk access, no network (AP-9/AP-11). Never
+ raises — a broken skill subsystem degrades to "nothing matched" rather than
+ breaking the turn.
+
+ Args:
+ registry: The live ``SkillRegistry`` (duck-typed).
+ user_text: The raw utterance, untouched.
+ lang: Language hint forwarded to the trigger matcher; ``"auto"``
+ considers every language's triggers.
+ limit: How many ranked candidates to keep for diagnostics.
+
+ Returns:
+ A :class:`MatchDecision`. Guards are the caller's job — see
+ :func:`jarvis.skills.guards.evaluate_guards`.
+ """
+ started = time.perf_counter_ns()
+
+ def _stamp(decision: MatchDecision) -> MatchDecision:
+ elapsed = max(0, (time.perf_counter_ns() - started) // 1_000)
+ return MatchDecision(
+ band=decision.band,
+ source=decision.source,
+ top=decision.top,
+ candidates=decision.candidates,
+ margin=decision.margin,
+ elapsed_us=elapsed,
+ )
+
+ if not user_text or registry is None:
+ return _stamp(MatchDecision())
+
+ trigger = _trigger_decision(registry, user_text, lang)
+ 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())
+
+
+__all__ = [
+ "BAND_FIRE",
+ "BAND_NARROW",
+ "BAND_NONE",
+ "MATCH_BANDS",
+ "MATCH_SOURCES",
+ "SOURCE_NONE",
+ "SOURCE_RELEVANCE",
+ "SOURCE_TRIGGER",
+ "TRIGGER_MATCH_SCORE",
+ "Band",
+ "MatchCandidate",
+ "MatchDecision",
+ "band_at_least",
+ "evaluate_match",
+]
diff --git a/jarvis/skills/registry.py b/jarvis/skills/registry.py
index 98072ebf70..9c0407b7a2 100644
--- a/jarvis/skills/registry.py
+++ b/jarvis/skills/registry.py
@@ -85,6 +85,12 @@ class SkillRegistry:
# toggle survives restarts. ``None`` → legacy behaviour (no overrides).
self._state_prefs_loader = state_prefs_loader
self._skills: dict[str, Skill] = {}
+ # Monotonic reload counter. Derived caches (e.g. the relevance match
+ # index) key on it so they rebuild lazily after a hot reload instead of
+ # the registry having to know they exist — and so a rebuild never runs
+ # inside the reload itself, where it would sit on the boot path (AP-26)
+ # and thrash while the watchdog fires on every keystroke in a SKILL.md.
+ self._generation: int = 0
self._async_lock = asyncio.Lock()
self._thread_lock = threading.Lock()
self._observer: Any | None = None
@@ -96,6 +102,16 @@ class SkillRegistry:
# Lookup
# ------------------------------------------------------------------
+ @property
+ def generation(self) -> int:
+ """Reload counter — bumped on every successful (re)load.
+
+ Derived read-only caches use ``(id(registry), generation)`` as their key
+ so a hot reload invalidates them without the registry holding a
+ reference to anything.
+ """
+ return self._generation
+
def get(self, name: str) -> Skill:
if name not in self._skills:
raise KeyError(f"Skill '{name}' not in registry")
@@ -292,6 +308,7 @@ class SkillRegistry:
skills = self._apply_state_overrides(discover_skills(self.root))
with self._thread_lock:
self._skills = {s.name: s for s in skills}
+ self._generation += 1
self._sync_paired_capabilities()
self._emit_reloaded()
@@ -304,6 +321,7 @@ class SkillRegistry:
skills = self._apply_state_overrides(skills)
with self._thread_lock:
self._skills = {s.name: s for s in skills}
+ self._generation += 1
self._sync_paired_capabilities()
self._emit_reloaded()
diff --git a/tests/unit/skills/test_guards.py b/tests/unit/skills/test_guards.py
new file mode 100644
index 0000000000..dbecdbb149
--- /dev/null
+++ b/tests/unit/skills/test_guards.py
@@ -0,0 +1,313 @@
+"""Characterization + contract tests for jarvis.skills.guards.
+
+``guards.py`` is a MOVE, not a redesign: the definitional-question guard, the
+block-tier check and the lifecycle filter used to live inline in
+``jarvis/brain/manager.py`` and ``jarvis/skills/trigger_matcher.py``. The first
+test below proves the move preserved behaviour by running both implementations
+over the same corpus and comparing verdicts — including the live forensic
+utterances the original guards were written for.
+
+The rest pin the contract every other layer depends on: a closed veto
+vocabulary (an unlisted reason renders as a blank cell in the Test-Match panel)
+and a stable-length guard ladder (a list that shrinks as vetoes fire is useless
+for "why didn't my skill fire?").
+"""
+from __future__ import annotations
+
+import pytest
+
+from jarvis.skills import guards
+
+# ---------------------------------------------------------------------------
+# Fakes (mirroring tests/unit/skills/test_local_search.py)
+# ---------------------------------------------------------------------------
+
+
+class _FakeRiskPolicy:
+ def __init__(self, tier: str = "monitor") -> None:
+ self.default_tier = tier
+
+
+class _FakeFrontmatter:
+ def __init__(self, tier: str = "monitor") -> None:
+ self.risk_policy = _FakeRiskPolicy(tier)
+
+
+class _FakeState:
+ def __init__(self, value: str) -> None:
+ self.value = value
+
+
+class _FakeSkill:
+ def __init__(
+ self,
+ name: str = "demo",
+ state: str = "active",
+ tier: str = "monitor",
+ *,
+ frontmatter: object | None = _FakeFrontmatter,
+ ) -> None:
+ self.name = name
+ self.state = _FakeState(state)
+ if frontmatter is _FakeFrontmatter:
+ self.frontmatter: object | None = _FakeFrontmatter(tier)
+ else:
+ self.frontmatter = frontmatter
+
+
+# ---------------------------------------------------------------------------
+# Characterization: the move preserved behaviour exactly
+# ---------------------------------------------------------------------------
+
+# Every case the original guard was written against, plus the near-misses that
+# make it non-trivial. Sources: the negative controls in
+# scripts/skill_routing_eval.py and the forensic comments at manager.py:860-885.
+_DEFINITIONAL_CORPUS: tuple[tuple[str, str], ...] = (
+ # (utterance, matched trigger token) — every German string below is a
+ # simulated user utterance, i.e. the speech input under test.
+ ("was ist eigentlich GitHub fuer eine plattform?", "GitHub"), # i18n-allow: speech input
+ ("was ist Stripe ueberhaupt und wofuer nutzt man das?", "Stripe"), # i18n-allow: speech input
+ ("was ist Discord?", "Discord"), # i18n-allow: speech input
+ ("what is Stripe?", "Stripe"),
+ ("what's gmail actually", "gmail"),
+ ("erkläre mir Notion", "Notion"), # i18n-allow: speech input
+ ("wofür ist Linear da", "Linear"), # i18n-allow: speech input
+ ("tell me about Vercel", "Vercel"),
+ # NOT definitional — a real data request that merely opens with "was ist".
+ # The data-context word breaks the predicate run, so these must NOT veto.
+ ("was ist in meinem Posteingang?", "Posteingang"), # i18n-allow: speech input
+ ("was ist auf meinem Kalender heute", "Kalender"), # i18n-allow: speech input
+ ("was ist mein naechster Termin", "Termin"), # i18n-allow: speech input
+ # Plain commands — no definitional opener at all.
+ ("starte die Morgenroutine", "Morgenroutine"), # i18n-allow: speech input
+ ("schick eine Nachricht auf Discord", "Discord"), # i18n-allow: speech input
+ ("oeffne Discord", "Discord"), # i18n-allow: speech input
+ ("lies meine neuen Mails", "Mails"), # i18n-allow: speech input
+ # Umlaut token: the guard re.escapes the RAW span, so a transliterated
+ # token would silently stop matching here.
+ ("was ist Fähigkeit", "Fähigkeit"), # i18n-allow: speech input
+ ("was ist der Tagesüberblick", "Tagesüberblick"), # i18n-allow: speech input
+ # Degenerate inputs.
+ ("", "Discord"),
+ ("was ist das", ""), # i18n-allow: speech input
+)
+
+
[email protected](("utterance", "token"), _DEFINITIONAL_CORPUS)
+def test_definitional_guard_matches_the_manager_implementation(
+ utterance: str, token: str
+) -> None:
+ """The extracted guard must agree with the inline original on every case.
+
+ This is the whole justification for calling Phase 0 a no-behaviour-change
+ refactor. If it ever fails, the extraction changed routing.
+ """
+ from jarvis.brain.manager import _is_definitional_question_about as original
+
+ assert guards.is_definitional_question_about(utterance, token) == original(
+ utterance, token
+ )
+
+
+def test_definitional_guard_suppresses_a_knowledge_question() -> None:
+ assert guards.is_definitional_question_about("was ist Discord?", "Discord") is True
+
+
+def test_definitional_guard_allows_a_data_request_with_the_same_opener() -> None:
+ """"was ist in meinem Posteingang?" is a request, not a definition."""
+ assert (
+ guards.is_definitional_question_about(
+ "was ist in meinem Posteingang?", "Posteingang"
+ )
+ is False
+ )
+
+
+def test_definitional_guard_needs_the_raw_span_not_a_normalized_token() -> None:
+ """Feeding a transliterated token blinds the guard — pin that it matters.
+
+ Documents WHY MatchCandidate.evidence must carry the untouched span: the
+ guard escapes the token into a pattern run against the original text.
+ """
+ spoken = "was ist Fähigkeit" # i18n-allow: speech input
+ raw_span = "Fähigkeit" # i18n-allow: speech input
+ transliterated = "Faehigkeit" # i18n-allow: speech input
+ assert guards.is_definitional_question_about(spoken, raw_span) is True
+ assert guards.is_definitional_question_about(spoken, transliterated) is False
+
+
+def test_definitional_predicate_cache_is_bounded() -> None:
+ """The compiled-pattern cache must not grow without bound."""
+ guards._PREDICATE_CACHE.clear()
+ for index in range(guards._PREDICATE_CACHE_MAX + 25):
+ guards.is_definitional_question_about(f"was ist tok{index}", f"tok{index}")
+ assert len(guards._PREDICATE_CACHE) <= guards._PREDICATE_CACHE_MAX
+
+
+# ---------------------------------------------------------------------------
+# Lifecycle / risk guards
+# ---------------------------------------------------------------------------
+
+
[email protected]("state", ["active", "validated"])
+def test_matchable_states_pass_the_lifecycle_guard(state: str) -> None:
+ assert guards.lifecycle_veto(_FakeSkill(state=state)) is None
+
+
+def test_draft_never_passes_the_lifecycle_guard() -> None:
+ """AP-15: an agent-authored draft must never fire automatically."""
+ assert guards.lifecycle_veto(_FakeSkill(state="draft")) == guards.VETO_DRAFT_STATE
+
+
+def test_disabled_reports_its_own_reason() -> None:
+ """A user-disabled skill and a draft are both vetoed, but not the same way."""
+ assert (
+ guards.lifecycle_veto(_FakeSkill(state="disabled"))
+ == guards.VETO_DISABLED_STATE
+ )
+
+
+def test_block_tier_is_vetoed() -> None:
+ assert guards.block_tier_veto(_FakeSkill(tier="block")) == guards.VETO_BLOCK_TIER
+
+
[email protected]("tier", ["safe", "monitor", "ask"])
+def test_non_block_tiers_pass(tier: str) -> None:
+ assert guards.block_tier_veto(_FakeSkill(tier=tier)) is None
+
+
+def test_missing_frontmatter_is_vetoed_separately_from_block_tier() -> None:
+ """Resolution the old boolean _skill_is_blocked could not express.
+
+ Both still veto — the verdict is unchanged — but the panel can now say
+ which one fired.
+ """
+ broken = _FakeSkill(frontmatter=None)
+ assert guards.frontmatter_veto(broken) == guards.VETO_NO_FRONTMATTER
+ assert guards.block_tier_veto(broken) is None
+
+
+def test_block_tier_verdict_matches_the_manager_implementation() -> None:
+ """Old ``_skill_is_blocked`` == (frontmatter_veto or block_tier_veto)."""
+ from jarvis.brain.manager import BrainManager
+
+ for skill in (
+ _FakeSkill(tier="block"),
+ _FakeSkill(tier="safe"),
+ _FakeSkill(tier="monitor"),
+ _FakeSkill(tier="ask"),
+ _FakeSkill(frontmatter=None),
+ ):
+ extracted = bool(
+ guards.frontmatter_veto(skill) or guards.block_tier_veto(skill)
+ )
+ assert extracted == BrainManager._skill_is_blocked(skill)
+
+
+# ---------------------------------------------------------------------------
+# Brain-side guards (verdicts arrive as plain data — no reverse import)
+# ---------------------------------------------------------------------------
+
+
[email protected]("mode", ["direct", "computer_use", "DIRECT"])
+def test_local_action_gate_claims_the_turn(mode: str) -> None:
+ """Live bug 2026-06-21: plugin-discord must not suppress Computer-Use."""
+ assert guards.local_action_veto(mode) == guards.VETO_LOCAL_ACTION
+
+
[email protected]("mode", [None, "", "unsupported"])
+def test_a_pure_dispatch_keeps_its_skill(mode: str | None) -> None:
+ assert guards.local_action_veto(mode) is None
+
+
+def test_explicit_heavy_request_stands_the_skill_down() -> None:
+ """AD-S9: an utterance naming the vehicle is a mission, not a skill.
+
+ Forensic example: "spawne einen Sub-Agent für Gmail". <!-- i18n-allow -->
+ """
+ assert guards.explicit_heavy_veto(True) == guards.VETO_EXPLICIT_HEAVY
+ assert guards.explicit_heavy_veto(False) is None
+
+
+def test_guards_module_has_no_jarvis_imports() -> None:
+ """A reverse import would close the jarvis.brain -> jarvis.skills cycle."""
+ from pathlib import Path
+
+ import jarvis.skills.guards as module
+
+ source = Path(module.__file__).read_text(encoding="utf-8")
+ code = "\n".join(
+ line for line in source.splitlines() if not line.strip().startswith(("#", "*"))
+ )
+ assert "import jarvis" not in code
+ assert "from jarvis" not in code
+
+
+# ---------------------------------------------------------------------------
+# The ladder
+# ---------------------------------------------------------------------------
+
+
+def test_ladder_passes_a_clean_skill() -> None:
+ ladder = guards.evaluate_guards(
+ _FakeSkill(), user_text="starte die Morgenroutine", evidence="Morgenroutine"
+ )
+ assert ladder.passed
+ assert ladder.vetoed_by == ""
+ assert all(result.verdict == "pass" for result in ladder.results)
+
+
+def test_ladder_reports_every_guard_even_after_a_veto() -> None:
+ """A ladder that shrinks as vetoes fire cannot answer "what else checked?"."""
+ ladder = guards.evaluate_guards(_FakeSkill(state="draft"))
+ assert len(ladder.results) == len(guards.GUARD_ORDER)
+ assert tuple(r.guard for r in ladder.results) == guards.GUARD_ORDER
+ assert ladder.vetoed_by == guards.VETO_DRAFT_STATE
+ assert [r.verdict for r in ladder.results].count("veto") == 1
+
+
+def test_ladder_reports_the_first_veto_in_evaluation_order() -> None:
+ """A draft block-tier skill reports the lifecycle veto, not the tier one."""
+ ladder = guards.evaluate_guards(_FakeSkill(state="draft", tier="block"))
+ assert ladder.vetoed_by == guards.VETO_DRAFT_STATE
+
+
+def test_ladder_catches_the_definitional_over_fire() -> None:
+ ladder = guards.evaluate_guards(
+ _FakeSkill(name="plugin-discord"),
+ user_text="was ist Discord?",
+ evidence="Discord",
+ )
+ assert ladder.vetoed_by == guards.VETO_DEFINITIONAL
+ assert not ladder.passed
+
+
+def test_every_reachable_veto_string_is_in_the_closed_vocabulary() -> None:
+ """An unlisted reason renders as a blank cell in the UI — the silent
+ version of a multi-layer drift bug."""
+ produced = {
+ guards.frontmatter_veto(_FakeSkill(frontmatter=None)),
+ guards.block_tier_veto(_FakeSkill(tier="block")),
+ guards.lifecycle_veto(_FakeSkill(state="draft")),
+ guards.lifecycle_veto(_FakeSkill(state="disabled")),
+ guards.local_action_veto("direct"),
+ guards.explicit_heavy_veto(True),
+ }
+ produced.discard(None)
+ assert produced <= guards.VETO_REASONS
+
+
+def test_ladder_vetoes_are_always_in_the_closed_vocabulary() -> None:
+ cases = (
+ guards.evaluate_guards(_FakeSkill(frontmatter=None)),
+ guards.evaluate_guards(_FakeSkill(state="draft")),
+ guards.evaluate_guards(_FakeSkill(state="disabled")),
+ guards.evaluate_guards(_FakeSkill(tier="block")),
+ guards.evaluate_guards(_FakeSkill(), is_explicit_heavy=True),
+ guards.evaluate_guards(_FakeSkill(), local_action_mode="computer_use"),
+ guards.evaluate_guards(
+ _FakeSkill(), user_text="was ist Discord?", evidence="Discord"
+ ),
+ )
+ for ladder in cases:
+ assert ladder.vetoed_by in guards.VETO_REASONS
diff --git a/tests/unit/skills/test_match_eval.py b/tests/unit/skills/test_match_eval.py
new file mode 100644
index 0000000000..b4b7a6e2a8
--- /dev/null
+++ b/tests/unit/skills/test_match_eval.py
@@ -0,0 +1,241 @@
+"""Contract tests for jarvis.skills.match_eval.
+
+``evaluate_match`` is the ONE entry point the brain, the Test-Match route and
+the offline eval all call. These tests pin the two properties that make sharing
+it safe: it never raises (a broken skill subsystem must degrade to "nothing
+matched", never break a turn) and the author's regex triggers keep absolute
+precedence over anything added later.
+
+At this phase the relevance fallback is not wired yet, so a trigger miss is a
+total miss — exactly today's behaviour. That is deliberate: the offline eval
+must be able to baseline the CURRENT system, including its near-zero
+paraphrase recall, before the new algorithm exists. Without that baseline there
+is nothing to compare against and a recall regression is invisible.
+"""
+from __future__ import annotations
+
+import pytest
+
+from jarvis.skills import match_eval
+from jarvis.skills.schema import SkillLifecycleState
+
+# ---------------------------------------------------------------------------
+# Fakes shaped for TriggerMatcher (which reads real lifecycle enums)
+# ---------------------------------------------------------------------------
+
+
+class _FakeTrigger:
+ def __init__(
+ self, pattern: str, kind: str = "voice", language: list[str] | None = None
+ ) -> None:
+ self.type = kind
+ self.pattern = pattern
+ self.language = language or []
+ self.combo = None
+ self.cron = None
+
+
+class _FakeFrontmatter:
+ def __init__(self, triggers: list[_FakeTrigger]) -> None:
+ self.triggers = triggers
+
+
+class _FakeSkill:
+ def __init__(
+ self,
+ name: str,
+ patterns: list[str],
+ state: SkillLifecycleState = SkillLifecycleState.ACTIVE,
+ ) -> None:
+ self.name = name
+ self.state = state
+ self.frontmatter = _FakeFrontmatter([_FakeTrigger(p) for p in patterns])
+
+
+class _FakeRegistry:
+ def __init__(self, skills: list[_FakeSkill]) -> None:
+ self._skills = skills
+
+ def list(self) -> list[_FakeSkill]:
+ return list(self._skills)
+
+ def by_trigger(self, kind: str) -> list[_FakeSkill]:
+ return [
+ s
+ for s in self._skills
+ if any(t.type == kind for t in s.frontmatter.triggers)
+ ]
+
+
+class _ExplodingRegistry:
+ def by_trigger(self, kind: str) -> list[_FakeSkill]:
+ raise RuntimeError("registry is on fire")
+
+ def list(self) -> list[_FakeSkill]:
+ raise RuntimeError("registry is on fire")
+
+
+# Trigger vocabulary under test — mirrors the real builtin patterns.
+_MORNING_PATTERN = (
+ r"(morgenroutine|morning routine|tages(ue|ü)berblick)" # i18n-allow: speech input
+)
+_FOCUS_PATTERN = r"(fokusmodus|deep work mode)" # i18n-allow: speech input
+
+
+def _registry() -> _FakeRegistry:
+ return _FakeRegistry(
+ [
+ _FakeSkill("morning-routine", [_MORNING_PATTERN]),
+ _FakeSkill("deep-work-mode", [_FOCUS_PATTERN]),
+ ]
+ )
+
+
+# ---------------------------------------------------------------------------
+# Band vocabulary
+# ---------------------------------------------------------------------------
+
+
+def test_bands_are_ordered_strongest_first() -> None:
+ assert match_eval.MATCH_BANDS == ("fire", "narrow", "none")
+
+
+ ("band", "floor", "expected"),
+ [
+ ("fire", "fire", True),
+ ("fire", "narrow", True),
+ ("narrow", "fire", False),
+ ("narrow", "narrow", True),
+ ("none", "narrow", False),
+ ("bogus", "narrow", False), # unknown fails closed
+ ],
+)
+def test_band_at_least(band: str, floor: str, expected: bool) -> None:
+ assert match_eval.band_at_least(band, floor) is expected
+
+
+# ---------------------------------------------------------------------------
+# Trigger path
+# ---------------------------------------------------------------------------
+
+
+def test_a_voice_trigger_fires() -> None:
+ decision = match_eval.evaluate_match(_registry(), "starte die morgenroutine")
+ assert decision.band == match_eval.BAND_FIRE
+ assert decision.source == match_eval.SOURCE_TRIGGER
+ assert decision.top is not None
+ assert decision.top.skill_name == "morning-routine"
+ assert decision.fired is True
+
+
+def test_the_decision_carries_the_raw_matched_span() -> None:
+ """``evidence`` feeds the definitional guard, which re-escapes it against
+ the ORIGINAL text — so it must be the untouched span, not a normalized one."""
+ spoken = "gib mir den Tagesüberblick" # i18n-allow: speech input
+ decision = match_eval.evaluate_match(_registry(), spoken)
+ assert decision.top is not None
+ assert decision.top.evidence == "Tagesüberblick" # i18n-allow: speech input
+
+
+def test_a_draft_skill_never_fires() -> None:
+ """AP-15 — enforced by TriggerMatcher, pinned here at the shared entry point."""
+ registry = _FakeRegistry(
+ [
+ _FakeSkill(
+ "morning-routine",
+ [r"morgenroutine"],
+ state=SkillLifecycleState.DRAFT,
+ )
+ ]
+ )
+ assert match_eval.evaluate_match(registry, "starte die morgenroutine").band == (
+ match_eval.BAND_NONE
+ )
+
+
+def test_a_disabled_skill_never_fires() -> None:
+ registry = _FakeRegistry(
+ [
+ _FakeSkill(
+ "deep-work-mode",
+ [r"fokusmodus"],
+ state=SkillLifecycleState.DISABLED,
+ )
+ ]
+ )
+ assert match_eval.evaluate_match(registry, "fokusmodus").band == (
+ match_eval.BAND_NONE
+ )
+
+
+# ---------------------------------------------------------------------------
+# Current-behaviour baseline: a paraphrase misses (this is the bug)
+# ---------------------------------------------------------------------------
+
+
+def test_a_natural_paraphrase_still_misses_at_this_phase() -> None:
+ """Documents the gap the relevance layer closes.
+
+ "ich brauch jetzt ruhe zum arbeiten" is unmistakably deep-work-mode to a
+ human and matches none of its regexes. When the relevance fallback lands,
+ THIS is the test that flips — and the offline eval measures how far.
+ """
+ decision = match_eval.evaluate_match(
+ _registry(), "ich brauch jetzt ruhe zum arbeiten"
+ )
+ assert decision.band == match_eval.BAND_NONE
+ assert decision.top is None
+
+
+# ---------------------------------------------------------------------------
+# Degradation — matching must never break a turn
+# ---------------------------------------------------------------------------
+
+
[email protected]("text", ["", " "])
+def test_empty_input_is_a_clean_miss(text: str) -> None:
+ assert match_eval.evaluate_match(_registry(), text).band == match_eval.BAND_NONE
+
+
+def test_missing_registry_is_a_clean_miss() -> None:
+ assert match_eval.evaluate_match(None, "morgenroutine").band == (
+ match_eval.BAND_NONE
+ )
+
+
+def test_a_broken_registry_degrades_instead_of_raising() -> None:
+ decision = match_eval.evaluate_match(_ExplodingRegistry(), "morgenroutine")
+ assert decision.band == match_eval.BAND_NONE
+ assert decision.top is None
+
+
+def test_an_invalid_regex_does_not_break_the_evaluation() -> None:
+ registry = _FakeRegistry(
+ [
+ _FakeSkill("broken", [r"([unclosed"]),
+ _FakeSkill("deep-work-mode", [r"fokusmodus"]),
+ ]
+ )
+ decision = match_eval.evaluate_match(registry, "fokusmodus")
+ assert decision.top is not None
+ assert decision.top.skill_name == "deep-work-mode"
+
+
+def test_elapsed_is_recorded_for_every_decision() -> None:
+ """The decision log needs a cost number even on a miss."""
+ hit = match_eval.evaluate_match(_registry(), "fokusmodus")
+ miss = match_eval.evaluate_match(_registry(), "wie ist das wetter") # i18n-allow: speech input
+ assert hit.elapsed_us >= 0
+ assert miss.elapsed_us >= 0
+
+
+def test_records_are_frozen() -> None:
+ """Decisions travel onto the bus and into the ring buffer — immutability
+ keeps a subscriber from mutating another's copy (bus event contract)."""
+ decision = match_eval.evaluate_match(_registry(), "fokusmodus")
+ with pytest.raises((AttributeError, TypeError)):
+ decision.band = "fire" # type: ignore[misc]
+ assert decision.top is not None
+ with pytest.raises((AttributeError, TypeError)):
+ decision.top.score = 9.0 # type: ignore[misc]
diff --git a/tests/unit/skills/test_registry_generation.py b/tests/unit/skills/test_registry_generation.py
new file mode 100644
index 0000000000..1eeedc9737
--- /dev/null
+++ b/tests/unit/skills/test_registry_generation.py
@@ -0,0 +1,94 @@
+"""The registry's monotonic reload counter.
+
+Derived read-only caches (the relevance match index) key on
+``(id(registry), generation)`` so a hot reload invalidates them lazily. That
+indirection is deliberate: building the index *inside* the reload would put
+CPU on the deferred boot scan (AP-26) and thrash while the watchdog fires on
+every keystroke in an open SKILL.md.
+
+The counter therefore has exactly one contract — it must change whenever the
+skill set might have changed, and never go backwards. A reload that forgets to
+bump it serves a stale index forever, which reads as "my edited skill still
+doesn't match".
+"""
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+
+from jarvis.skills.registry import SkillRegistry
+
+_SKILL = """---
+schema_version: "1"
+name: {name}
+version: "1.0.0"
+description: A test skill for the generation counter.
+category: general
+---
+
+# {name}
+
+Do the thing.
+"""
+
+
+def _write_skill(root: Path, name: str) -> None:
+ folder = root / name
+ folder.mkdir(parents=True, exist_ok=True)
+ (folder / "SKILL.md").write_text(_SKILL.format(name=name), encoding="utf-8")
+
+
+def test_generation_starts_at_zero(tmp_path: Path) -> None:
+ assert SkillRegistry(tmp_path).generation == 0
+
+
+def test_sync_reload_bumps_the_generation(tmp_path: Path) -> None:
+ _write_skill(tmp_path, "alpha")
+ registry = SkillRegistry(tmp_path)
+
+ registry.reload_sync()
+ first = registry.generation
+ assert first == 1
+
+ registry.reload_sync()
+ assert registry.generation == first + 1
+
+
+async def test_async_reload_bumps_the_generation(tmp_path: Path) -> None:
+ _write_skill(tmp_path, "alpha")
+ registry = SkillRegistry(tmp_path)
+
+ await registry.reload()
+ first = registry.generation
+ assert first == 1
+
+ await registry.reload()
+ assert registry.generation == first + 1
+
+
+def test_generation_changes_when_a_skill_is_added(tmp_path: Path) -> None:
+ """The case a cache actually depends on: new skill, new generation."""
+ _write_skill(tmp_path, "alpha")
+ registry = SkillRegistry(tmp_path)
+ registry.reload_sync()
+ before = registry.generation
+
+ _write_skill(tmp_path, "beta")
+ registry.reload_sync()
+
+ assert registry.generation != before
+ assert {s.name for s in registry.list()} == {"alpha", "beta"}
+
+
+def test_generation_is_monotonic_and_read_only(tmp_path: Path) -> None:
+ registry = SkillRegistry(tmp_path)
+ seen = [registry.generation]
+ for _ in range(5):
+ registry.reload_sync()
+ seen.append(registry.generation)
+ assert seen == sorted(seen)
+ assert len(set(seen)) == len(seen)
+
+ with pytest.raises(AttributeError):
+ registry.generation = 99 # type: ignore[misc]