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
feat(skills): relevance layer live — narrowing on, self-firing in shadow
Ruben Lütke4270a896c269
diff --git a/jarvis/brain/manager.py b/jarvis/brain/manager.pyindex 761c6a16d4..1b06c6100a 100644--- a/jarvis/brain/manager.py+++ b/jarvis/brain/manager.py@@ -4590,35 +4590,91 @@ class BrainManager:self._skill_turn_content = contentself._skill_turn_source = source+ def _skills_config(self) -> Any:+ """The ``[skills]`` config section.++ Reads ``self._config`` directly rather than through a defensive+ ``getattr`` chain: an earlier draft looked up a mistyped attribute name+ and silently fell back to defaults, which left shadow mode permanently+ on and made every capture test fail for a reason nothing reported. A+ wrong config read must be a crash, not a quiet behaviour change.++ The section fallback stays, because an older ``jarvis.toml`` parsed by a+ newer binary genuinely can lack it.+ """+ from jarvis.core.config import SkillsConfig++ section = getattr(self._config, "skills", None)+ return section if section is not None else SkillsConfig()+def _match_skill_for_turn(self, user_text: str, lang: str = "auto") -> Any | None:"""Deterministic skill-match probe (AD-S3). Returns the matched Skill or None.- Uses the TriggerMatcher (incl. its tolerant filler-stripping pass) over- the live SkillContext registry. Never raises — routing must not break- when the skill subsystem is absent (headless/mock boots).+ Two channels, in strict order, through the ONE shared entry point+ (``jarvis.skills.match_eval.evaluate_match``):++ 1. The author's voice-trigger regex — absolute precedence, unchanged.+ Every utterance that worked before this method grew a second channel+ still takes exactly the same path.+ 2. The deterministic relevance scorer — the paraphrase channel. Only+ reached on a trigger MISS, so it is purely additive.++ The relevance fallback is nested HERE rather than added as another gate+ in ``generate()`` for one reason: every guard below (definitional+ question, block tier, and — via the caller — AD-S9 and the local-action+ stand-down) is then inherited structurally instead of re-implemented,+ and the call site does not move.++ Never raises — routing must not break when the skill subsystem is+ absent (headless/mock boots)."""+ self._skill_relevance = None+ self._skill_match_band = "none"+ self._skill_match_class = ""try:+ from jarvis.skills import guards, match_eval, match_log+ from jarvis.skills.autofire_policy import classify, may_capturefrom jarvis.skills.skill_context import try_get_skill_context- from jarvis.skills.trigger_matcher import TriggerMatcherctx = try_get_skill_context()if ctx is None:return None- res = TriggerMatcher(ctx.registry).match_voice_with_match(- user_text, lang=lang++ cfg = self._skills_config()+ decision = match_eval.evaluate_match(+ ctx.registry,+ user_text,+ lang=lang,+ limit=max(3, int(getattr(cfg, "narrow_candidates", 3)) + 2),+ use_relevance=bool(getattr(cfg, "relevance_enabled", True)),+ fire_threshold=getattr(cfg, "fire_threshold", None),+ hint_threshold=getattr(cfg, "hint_threshold", None),)- if res is None:+ if decision.top is None:+ self._record_skill_decision(user_text, decision, lang=lang)+ return None++ try:+ skill = ctx.registry.get(decision.top.skill_name)+ except Exception: # noqa: BLE001+ self._record_skill_decision(user_text, decision, lang=lang)return None- skill = res[0]- # Definitional-question guard: a bare-name plugin trigger must not- # capture a "was ist <App>?" knowledge turn (2026-06-24 eval).- matched_token = res[1].group(0) if res[1] is not None else ""- if _is_definitional_question_about(user_text, matched_token):++ # Unchanged guards, now shared by both channels. `evidence` is the+ # RAW matched span, never a normalized token — the definitional+ # guard re-escapes it against the original text, so a+ # transliterated token would blind it on every umlaut word.+ evidence = decision.top.evidence+ if _is_definitional_question_about(user_text, evidence):log.info("skill %s matched token %r but the turn is a definitional ""question about it — not captured (answer it instead)",getattr(skill, "name", "?"),- matched_token,+ evidence,+ )+ self._record_skill_decision(+ user_text, decision, lang=lang,+ vetoed_by=guards.VETO_DEFINITIONAL, skill=skill,)return Noneif self._skill_is_blocked(skill):@@ -4626,11 +4682,138 @@ class BrainManager:"skill %s matched but is block-tier — turn not captured",getattr(skill, "name", "?"),)+ self._record_skill_decision(+ user_text, decision, lang=lang,+ vetoed_by=guards.VETO_BLOCK_TIER, skill=skill,+ )+ return None++ self._skill_match_band = decision.band+ self._skill_match_class = classify(skill)++ # A trigger hit keeps its historical unconditional capture: the+ # author wrote that phrase precisely so it would fire, and changing+ # that would be a behaviour regression, not a safety win.+ if decision.source == match_eval.SOURCE_TRIGGER:+ self._record_skill_decision(+ user_text, decision, lang=lang, skill=skill, fired=True,+ )+ return skill++ # --- relevance channel: capture is a privilege, not a default ---+ self._skill_relevance = decision+ allowed, veto = may_capture(+ skill,+ decision.band,+ override=self._skill_autofire_override(skill),+ min_band=str(getattr(cfg, "auto_fire_min_band", "fire")),+ )+ if not allowed:+ log.info(+ "relevance match %s (band=%s, class=%s) does not capture: %s",+ getattr(skill, "name", "?"),+ decision.band,+ self._skill_match_class,+ veto,+ )+ self._record_skill_decision(+ user_text, decision, lang=lang, vetoed_by=veto, skill=skill,+ )return None++ if bool(getattr(cfg, "relevance_shadow", True)):+ # Shadow mode: record what WOULD have happened, change nothing.+ # The narrowed candidate hint still ships, so the model keeps+ # the benefit while the maintainer reviews real decisions.+ log.info(+ "relevance match %s (band=%s) SHADOWED — would have captured "+ "the turn; review GET /api/skills/match-log",+ getattr(skill, "name", "?"),+ decision.band,+ )+ self._record_skill_decision(+ user_text, decision, lang=lang, skill=skill,+ vetoed_by=guards.VETO_SHADOW_MODE, shadow=True,+ )+ return None++ self._record_skill_decision(+ user_text, decision, lang=lang, skill=skill, fired=True,+ )return skillexcept Exception: # noqa: BLE001return None+ def _skill_autofire_override(self, skill: Any) -> str | None:+ """The user's persisted per-skill auto-fire choice, if any."""+ try:+ from jarvis.skills.prefs import load_autofire_prefs++ return load_autofire_prefs().get(getattr(skill, "name", ""))+ except Exception: # noqa: BLE001+ return None++ def _record_skill_decision(+ self,+ user_text: str,+ decision: Any,+ *,+ lang: str = "auto",+ vetoed_by: str = "",+ skill: Any | None = None,+ fired: bool = False,+ shadow: bool = False,+ ) -> None:+ """Log the decision to the ring and the bus. Never raises, never blocks.++ Emitted on EVERY evaluation, including "nothing matched" and every veto.+ That completeness is the point: until now each veto was a ``log.info``+ nobody reads, which is exactly why "my skill never fires" could not be+ diagnosed.+ """+ try:+ from jarvis.skills import match_log+ from jarvis.skills.autofire_policy import classify++ autofire_class = classify(skill) if skill is not None else ""+ match_log.record(+ utterance=user_text,+ decision=decision,+ lang=lang,+ vetoed_by=vetoed_by,+ autofire_class=autofire_class,+ fired=fired,+ shadow=shadow,+ )+ except Exception: # noqa: BLE001+ return+ try:+ from jarvis.skills.match_log import utterance_hash+ from jarvis.skills.schema import SkillMatchEvaluated++ top = getattr(decision, "top", None)+ event = SkillMatchEvaluated(+ source_layer="brain.manager",+ utterance_hash=utterance_hash(user_text),+ lang=lang,+ source=str(getattr(decision, "source", "none")),+ band=str(getattr(decision, "band", "none")),+ winner=str(getattr(top, "skill_name", "") if top is not None else ""),+ autofire_class=autofire_class,+ vetoed_by=vetoed_by,+ fired=fired,+ shadow=shadow,+ elapsed_us=int(getattr(decision, "elapsed_us", 0) or 0),+ candidates=tuple(+ (getattr(c, "skill_name", ""), round(float(getattr(c, "score", 0.0)), 4))+ for c in (getattr(decision, "candidates", ()) or ())[:3]+ ),+ )+ loop = asyncio.get_running_loop()+ loop.create_task(self._bus.publish(event))+ except Exception: # noqa: BLE001+ log.debug("SkillMatchEvaluated publish failed", exc_info=True)+def _previous_user_turn_text(self, *, use_history: bool) -> str:"""Return the latest bounded user message from this task's history."""override = _TURN_HISTORY_OVERRIDE.get()@@ -4707,6 +4890,35 @@ class BrainManager:"clearly wrong.")+ def _skill_stand_downs_allowed(self) -> bool:+ """May this turn's matched skill suppress the other deterministic paths?++ True for the historical case — an author's trigger, or an+ instruction-only skill at FIRE — and False for anything the relevance+ layer merely inferred about a tool-backed skill. In the False case the+ skill still injects its instructions, but ``run-skill`` stays visible and+ the local-action gate keeps precedence, which turns a wrong match from a+ turn hijack into a suggestion the model can decline.++ This distinction is the single most important safety property of the+ relevance layer: capture is not all-or-nothing.+ """+ skill = self._skill_turn_match+ if skill is None:+ return False+ try:+ from jarvis.skills.autofire_policy import stand_downs_allowed+ from jarvis.skills.match_eval import BAND_FIRE, SOURCE_TRIGGER+ except Exception: # noqa: BLE001+ return True+ # An author-written trigger keeps its unconditional historical rights.+ if getattr(self, "_skill_relevance", None) is None:+ return True+ decision = self._skill_relevance+ if getattr(decision, "source", "") == SOURCE_TRIGGER:+ return True+ return stand_downs_allowed(skill, getattr(decision, "band", BAND_FIRE))+def _drop_run_skill_when_inline_injected(self, tools: Any) -> Any:"""Hide ``run-skill`` once a matched skill's instructions are already onthe turn context (``_skill_injected_inline``).@@ -4718,13 +4930,86 @@ class BrainManager:model-agnostic: every model just follows the injected instructions, notool call required. No-op when the skill was not inline-injected, or thetool set is not a dict (intelligent-router lead path).++ Kept ONLY while the turn's match is entitled to the full stand-down. A+ relevance-inferred match on a tool-backed skill leaves ``run-skill``+ visible on purpose: dropping it is what removes the model's ability to+ signal "wrong skill", and the model needs that escape hatch exactly when+ nobody stated an intent for this skill."""if not getattr(self, "_skill_injected_inline", False):return toolsif not isinstance(tools, dict):return tools+ if not self._skill_stand_downs_allowed():+ return toolsreturn {k: v for k, v in tools.items() if k != "run-skill"}+ def _render_skill_candidate_hint(self) -> str | None:+ """Narrow the skill choice for a turn the matcher did NOT capture.++ The router's real problem was never that skills are invisible — it is+ that all twenty listed skills look equally plausible while ~26k tokens+ of tool schemas compete for attention. This block names the one to three+ that actually scored, right next to the user's message, where recency is+ worth more than position in a long cached list.++ Deliberately rides the PER-TURN context and never the cached system+ prefix: rewriting that prefix per turn would break prompt caching on+ every single turn, which costs far more than it could ever save.++ Returns ``None`` on a captured turn, a dead scorer, or a weak ranking —+ so the common case adds nothing at all.+ """+ decision = getattr(self, "_skill_relevance", None)+ if decision is None or self._skill_turn_match is not None:+ return None+ candidates = getattr(decision, "candidates", ()) or ()+ if not candidates:+ return None++ cfg = self._skills_config()+ limit = max(1, int(getattr(cfg, "narrow_candidates", 3)))+ try:+ from jarvis.skills.match_eval import BAND_NONE+ from jarvis.skills.skill_context import try_get_skill_context++ ctx = try_get_skill_context()+ if ctx is None:+ return None+ registry = ctx.registry+ except Exception: # noqa: BLE001+ return None++ lines: list[str] = []+ for candidate in candidates:+ if len(lines) >= limit:+ break+ if getattr(candidate, "band", BAND_NONE) == BAND_NONE:+ continue+ name = getattr(candidate, "skill_name", "")+ try:+ skill = registry.get(name)+ except Exception: # noqa: BLE001+ continue+ frontmatter = getattr(skill, "frontmatter", None)+ if frontmatter is None:+ continue+ description = (getattr(frontmatter, "description", "") or "").strip()+ when_to_use = (getattr(frontmatter, "when_to_use", "") or "").strip()+ blurb = f"{description} {when_to_use}".strip()[:400]+ lines.append(f"- `{name}` — {blurb}")+ if not lines:+ return None++ return (+ "[Skill candidates] The user's request scored against these "+ "installed skills. If one genuinely fits, call the `run-skill` tool "+ "with that name FIRST and follow the returned instructions. If none "+ "fits, ignore this block entirely and answer normally — these are "+ "ranked suggestions, not a verdict.\n" + "\n".join(lines)+ )+def _render_skill_turn_injection(self, user_text: str) -> str | None:"""Render the matched skill's instructions for direct turn injection.@@ -7598,10 +7883,19 @@ class BrainManager:# gate → None) is untouched.if self._skill_turn_match is not None:_gate_plan = match_local_action(user_text)- if _gate_plan is not None and _gate_plan.mode in (+ _claiming = _gate_plan is not None and _gate_plan.mode in (LocalActionMode.DIRECT,LocalActionMode.COMPUTER_USE,- ):+ )+ # A relevance-channel match that is not instruction-only yields to+ # the desktop gate on ANY plan, not just a claiming one. The author+ # of a trigger asked for their phrase to win, so trigger matches keep+ # the narrower historical rule verbatim — this widening is additive+ # and applies only to the new, inferred channel, where nobody stated+ # an intent for the skill to beat local control.+ if not _claiming and _gate_plan is not None and not self._skill_stand_downs_allowed():+ _claiming = True+ if _claiming and _gate_plan is not None:log.info("Skill match %s stands down — the deterministic local-action ""gate claims this turn as %s; Computer-Use owns it "@@ -7973,7 +8267,18 @@ class BrainManager:turn_context = (f"{turn_context}\n\n{_skill_block}" if turn_context else _skill_block)-+ else:+ # No capture, but the deterministic scorer may still have found+ # plausible candidates. Narrowing 20 undifferentiated bullets down+ # to the 1-3 that actually score is the cheapest part of this whole+ # change and the part with no blast radius: the model still decides.+ _narrow_block = self._render_skill_candidate_hint()+ if _narrow_block:+ turn_context = (+ f"{turn_context}\n\n{_narrow_block}"+ if turn_context+ else _narrow_block+ )# AI Pointer (deictic push): collect the result of the resolution started# above. When the utterance points at the mouse cursor ("was ist das da?") # i18n-allow# the resolved element rides on this turn's context + a tight crop is@@ -9045,7 +9350,10 @@ class BrainManager:extra_patterns_fn=make_cli_patterns_fn(),)approval = ApprovalWorkflow(self._bus)- executor = ToolExecutor(self._bus, evaluator, approval)+ executor = ToolExecutor(+ self._bus, evaluator, approval,+ default_timeout_s=self._config.safety.tool_approval_timeout_s,+ )harness_manager = HarnessManager(bus=self._bus)diff --git a/jarvis/skills/autofire_policy.py b/jarvis/skills/autofire_policy.pynew file mode 100644index 0000000000..071986e04f--- /dev/null+++ b/jarvis/skills/autofire_policy.py@@ -0,0 +1,217 @@+"""Which skills may capture a turn on their own, and which never may.++A matched skill is not an addition to a turn — it is a takeover. Once+``BrainManager`` accepts a match it renders the skill's body into the turn+context, REMOVES ``run-skill`` from the tool set (so the model has no way to+signal "wrong skill"), stands the deterministic local-action fast path down,+stands the evidence gate down, and — for ``execution: mission`` — dispatches a+worker and returns before the model sees anything at all.++That asymmetry is the whole reason this module exists. A wrong suggestion is+free. A wrong takeover spends money, suppresses Computer-Use, and makes the+assistant confidently claim a capability it does not have.++This is not theoretical. ``cloud-debug`` ships as ``execution: mission`` with+``default_tier: monitor`` and **no triggers at all**: unreachable by matching+today, and a fuzzy layer makes it reachable. A paraphrase match would start an+unrequested Claude Code worker in a git worktree and hand the user an+optimistic acknowledgement, with no model and no confirmation anywhere on the+path.++So capture permission is DERIVED from what the skill actually does, never+merely declared:++* ``instruction`` — adds words to a turn. Blast radius: one turn's tone.+* ``tool_backed`` — will reach for an integration. Survivable, but only while+ the model can still refuse, so the stand-downs stay disarmed for it.+* ``dispatching`` — starts a process or is explicitly blocked. Never captures+ automatically; the model must ask for it via ``run-skill``, or the user must+ name it.++Pure and dependency-free (stdlib only, duck-typed skills), so the brain, the+REST layer and the offline eval all reach the same verdict.+"""+from __future__ import annotations++import re+from typing import Any, Literal++CLASS_INSTRUCTION = "instruction"+CLASS_TOOL_BACKED = "tool_backed"+CLASS_DISPATCHING = "dispatching"++#: Closed set — mirrored in TypeScript, pinned by a parity test.+AUTOFIRE_CLASSES: tuple[str, ...] = (+ CLASS_INSTRUCTION,+ CLASS_TOOL_BACKED,+ CLASS_DISPATCHING,+)++AutoFireClass = Literal["instruction", "tool_backed", "dispatching"]++#: Frontmatter override vocabulary. ``auto`` (the default, and what every+#: existing skill has by virtue of not carrying the field) means "the class+#: table decides".+AUTO_FIRE_AUTO = "auto"+AUTO_FIRE_ALWAYS = "always"+AUTO_FIRE_NEVER = "never"+AUTO_FIRE_MODES: tuple[str, ...] = (AUTO_FIRE_AUTO, AUTO_FIRE_ALWAYS, AUTO_FIRE_NEVER)++#: Risk tiers an ``instruction`` skill may carry. ``ask`` needs the voice+#: confirmation machinery that lives in the orchestrator, so it is excluded and+#: falls through to ``tool_backed``.+_INSTRUCTION_SAFE_TIERS = frozenset({"safe", "monitor", ""})++#: Legacy ``TOOL:`` macro lines in a skill body. A body containing them was+#: written for the retired macro executor and may name arbitrary tools, so it is+#: treated as dispatching regardless of what the frontmatter claims.+_TOOL_LINE_RE = re.compile(r"^\s*TOOL:\s*\S", re.MULTILINE)+++def _risk_tier(skill: Any) -> str:+ 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 _execution(skill: Any) -> str:+ frontmatter = getattr(skill, "frontmatter", None)+ if frontmatter is None:+ return "inline"+ return str(getattr(frontmatter, "execution", "inline") or "inline").lower()+++def body_has_macro_lines(skill: Any) -> bool:+ """True when the body carries legacy ``TOOL:`` macro lines."""+ body = getattr(skill, "body", "") or ""+ return bool(_TOOL_LINE_RE.search(body))+++def classify(skill: Any) -> str:+ """Return this skill's auto-fire class. Never raises.++ A skill whose frontmatter failed to parse is ``dispatching``: unknown+ intent must not be granted capture rights.+ """+ frontmatter = getattr(skill, "frontmatter", None)+ if frontmatter is None:+ return CLASS_DISPATCHING++ tier = _risk_tier(skill)+ if tier == "block" or _execution(skill) == "mission":+ return CLASS_DISPATCHING+ if body_has_macro_lines(skill):+ return CLASS_DISPATCHING++ requires_tools = tuple(getattr(frontmatter, "requires_tools", ()) or ())+ plugin_id = getattr(frontmatter, "plugin_id", None)+ if requires_tools or plugin_id or tier == "ask":+ return CLASS_TOOL_BACKED++ if tier in _INSTRUCTION_SAFE_TIERS:+ return CLASS_INSTRUCTION+ # An unrecognised tier is not a licence — fail toward the safer class.+ return CLASS_TOOL_BACKED+++def auto_fire_mode(skill: Any, *, override: str | None = None) -> str:+ """Resolve the skill's ``auto`` / ``always`` / ``never`` setting.++ ``override`` is the user's persisted choice from the prefs sidecar, which+ wins over frontmatter — builtin skills need an admin password to edit and+ are re-copied by bootstrap, so a user preference cannot live in their+ frontmatter.+ """+ for candidate in (override, getattr(getattr(skill, "frontmatter", None), "auto_fire", None)):+ value = str(candidate or "").strip().lower()+ if value in AUTO_FIRE_MODES:+ return value+ return AUTO_FIRE_AUTO+++def may_capture(+ skill: Any,+ band: str,+ *,+ override: str | None = None,+ min_band: str = "fire",+) -> tuple[bool, str]:+ """May this skill take over the turn at ``band``?++ Returns ``(allowed, veto_reason)``; ``veto_reason`` is a member of+ :data:`jarvis.skills.guards.VETO_REASONS` when denied.++ Args:+ skill: The matched skill (duck-typed).+ band: The match band — ``"fire"`` or ``"narrow"``.+ override: The user's persisted per-skill auto-fire choice, if any.+ min_band: Configured floor. Defaults to ``fire``, i.e. a NARROW match+ never captures unless the deployment deliberately opens it up.+ """+ from jarvis.skills.guards import (+ VETO_AUTO_FIRE_NEVER,+ VETO_BAND_BELOW_FLOOR,+ VETO_DISPATCHING_CLASS,+ )+ from jarvis.skills.match_eval import BAND_FIRE, BAND_NARROW, band_at_least++ if band not in (BAND_FIRE, BAND_NARROW):+ return False, VETO_BAND_BELOW_FLOOR++ mode = auto_fire_mode(skill, override=override)+ if mode == AUTO_FIRE_NEVER:+ return False, VETO_AUTO_FIRE_NEVER++ kind = classify(skill)+ if kind == CLASS_DISPATCHING:+ # The one line no configuration may cross: a frontmatter field must+ # never authorize a deterministic matcher to start a process. `always`+ # is checked AFTER this on purpose.+ return False, VETO_DISPATCHING_CLASS++ if not band_at_least(band, min_band):+ # `always` promotes a tool-backed skill into the weaker band; it can+ # never promote a dispatching one (handled above).+ if mode != AUTO_FIRE_ALWAYS:+ return False, VETO_BAND_BELOW_FLOOR++ return True, ""+++def stand_downs_allowed(skill: Any, band: str) -> bool:+ """May a captured turn suppress the other deterministic fast paths?++ Only an ``instruction`` skill at FIRE gets the historical full stand-down.+ Everything weaker keeps ``run-skill`` visible and leaves the local-action+ gate and the evidence gate armed, which turns a wrong match from a hijack+ into a suggestion the model can ignore.++ Live precedent for why this matters (2026-06-21): ``plugin-discord``+ keyword-matched the bare word "Discord", suppressed the local-action fast+ path, and a tool-less deep brain then told the user it had no Discord+ access.+ """+ from jarvis.skills.match_eval import BAND_FIRE++ return band == BAND_FIRE and classify(skill) == CLASS_INSTRUCTION+++__all__ = [+ "AUTOFIRE_CLASSES",+ "AUTO_FIRE_ALWAYS",+ "AUTO_FIRE_AUTO",+ "AUTO_FIRE_MODES",+ "AUTO_FIRE_NEVER",+ "CLASS_DISPATCHING",+ "CLASS_INSTRUCTION",+ "CLASS_TOOL_BACKED",+ "AutoFireClass",+ "auto_fire_mode",+ "body_has_macro_lines",+ "classify",+ "may_capture",+ "stand_downs_allowed",+]diff --git a/jarvis/skills/match_eval.py b/jarvis/skills/match_eval.pyindex 201edc1726..b3ac6b2b40 100644--- a/jarvis/skills/match_eval.py+++ b/jarvis/skills/match_eval.py@@ -32,7 +32,7 @@ been undebuggable.from __future__ import annotationsimport time-from dataclasses import dataclass+from dataclasses import dataclass, replacefrom typing import Any, Literal# ---------------------------------------------------------------------------@@ -162,7 +162,14 @@ def _trigger_decision(registry: Any, user_text: str, lang: str) -> MatchDecision)-def _relevance_decision(registry: Any, user_text: str, *, limit: int) -> MatchDecision:+def _relevance_decision(+ registry: Any,+ user_text: str,+ *,+ limit: int,+ fire_threshold: float | None = None,+ hint_threshold: float | None = None,+) -> MatchDecision:"""Deterministic relevance pass — the paraphrase channel.Bands are applied HERE rather than inside the scorer, so@@ -178,6 +185,16 @@ def _relevance_decision(registry: Any, user_text: str, *, limit: int) -> MatchDereturn MatchDecision()if ranking.top is None:return MatchDecision()+ if fire_threshold is not None or hint_threshold is not None:+ ranking = replace(+ ranking,+ fire_threshold=(+ fire_threshold if fire_threshold is not None else ranking.fire_threshold+ ),+ hint_threshold=(+ hint_threshold if hint_threshold is not None else ranking.hint_threshold+ ),+ )candidates = tuple(MatchCandidate(@@ -223,6 +240,9 @@ def evaluate_match(*,lang: str = "auto",limit: int = 5,+ use_relevance: bool = True,+ fire_threshold: float | None = None,+ hint_threshold: float | None = None,) -> MatchDecision:"""Decide which skill, if any, owns ``user_text``.@@ -236,6 +256,10 @@ def evaluate_match(lang: Language hint forwarded to the trigger matcher; ``"auto"``considers every language's triggers.limit: How many ranked candidates to keep for diagnostics.+ use_relevance: When False, only the author's regex triggers run — the+ exact pre-relevance behaviour, which is what the kill switch buys.+ fire_threshold: Override the corpus-derived FIRE cut-off.+ hint_threshold: Override the corpus-derived NARROW cut-off.Returns:A :class:`MatchDecision`. Guards are the caller's job — see@@ -261,7 +285,17 @@ def evaluate_match(if trigger is not None:return _stamp(trigger)- return _stamp(_relevance_decision(registry, user_text, limit=limit))+ if not use_relevance:+ return _stamp(MatchDecision())+ return _stamp(+ _relevance_decision(+ registry,+ user_text,+ limit=limit,+ fire_threshold=fire_threshold,+ hint_threshold=hint_threshold,+ )+ )__all__ = [diff --git a/jarvis/skills/match_log.py b/jarvis/skills/match_log.pynew file mode 100644index 0000000000..4bb1c69739--- /dev/null+++ b/jarvis/skills/match_log.py@@ -0,0 +1,167 @@+"""In-memory ring of recent skill-match decisions.++The reason "my skill never fires" has been undebuggable is not that the system+is silent — it is that every veto is a ``log.info`` nobody reads. Four separate+sites in ``BrainManager`` log a suppressed match and then move on+(``manager.py`` around the definitional guard, the block-tier check, the AD-S9+stand-down and the local-action stand-down). None of it is queryable, so the+only available diagnosis was "I said something and nothing happened".++This module is the answer, and it is deliberately the cheapest possible one:++* A process-local ``collections.deque`` with a fixed maximum. Appending is a+ handful of nanoseconds and touches no disk, so it is safe to call on every+ turn from the voice path (AP-9/AP-11).+* Dies with the process. That is fine — the durable copy rides the bus as a+ frozen event and lands in the flight recorder, which already buffers and+ flushes at most once per second.++Privacy split, and it is load-bearing: the ring keeps a short utterance+PREVIEW, because a maintainer cannot debug "why didn't it fire" without seeing+what they said. The bus event carries only a hash, so nothing that a+public-release scrub would have to chase ends up in+``data/flight_recorder/*.jsonl``.+"""+from __future__ import annotations++import hashlib+from collections import deque+from dataclasses import dataclass, field+from typing import Any++#: How many decisions to keep. Small on purpose: this answers "what just+#: happened", not "what happened last week" — that is the recorder's job.+MAX_ENTRIES = 200++#: Utterance preview length kept in memory.+PREVIEW_CHARS = 80+++@dataclass(frozen=True, slots=True)+class CandidateRecord:+ """One ranked candidate as it appeared in a decision."""++ skill_name: str+ score: float = 0.0+ band: str = "none"+ reason: str = ""+++@dataclass(frozen=True, slots=True)+class DecisionRecord:+ """One match evaluation, exactly as the brain saw it."""++ utterance_preview: str = ""+ utterance_hash: str = ""+ lang: str = ""+ source: str = "none"+ band: str = "none"+ winner: str = ""+ autofire_class: str = ""+ #: Empty when nothing vetoed. This single field is the feature — it turns+ #: "nothing happened" into "the definitional guard suppressed plugin-github".+ vetoed_by: str = ""+ fired: bool = False+ shadow: bool = False+ dry_run: bool = False+ elapsed_us: int = 0+ candidates: tuple[CandidateRecord, ...] = field(default_factory=tuple)+++_RING: deque[DecisionRecord] = deque(maxlen=MAX_ENTRIES)+++def utterance_hash(text: str) -> str:+ """Short stable hash — what travels on the bus instead of the text."""+ digest = hashlib.sha256((text or "").encode("utf-8", "replace")).hexdigest()+ return digest[:12]+++def record(+ *,+ utterance: str,+ decision: Any,+ lang: str = "auto",+ vetoed_by: str = "",+ autofire_class: str = "",+ fired: bool = False,+ shadow: bool = False,+ dry_run: bool = False,+) -> DecisionRecord:+ """Append a decision to the ring and return it. Never raises.++ Synchronous by design: a deque append is cheaper than the branch that would+ decide whether to defer it.+ """+ try:+ candidates = tuple(+ CandidateRecord(+ skill_name=getattr(c, "skill_name", ""),+ score=float(getattr(c, "score", 0.0)),+ band=str(getattr(c, "band", "none")),+ reason=str(getattr(c, "reason", "")),+ )+ for c in (getattr(decision, "candidates", ()) or ())+ )+ top = getattr(decision, "top", None)+ entry = DecisionRecord(+ utterance_preview=(utterance or "")[:PREVIEW_CHARS],+ utterance_hash=utterance_hash(utterance),+ lang=lang,+ source=str(getattr(decision, "source", "none")),+ band=str(getattr(decision, "band", "none")),+ winner=str(getattr(top, "skill_name", "") if top is not None else ""),+ autofire_class=autofire_class,+ vetoed_by=vetoed_by,+ fired=fired,+ shadow=shadow,+ dry_run=dry_run,+ elapsed_us=int(getattr(decision, "elapsed_us", 0) or 0),+ candidates=candidates,+ )+ except Exception: # noqa: BLE001 — diagnostics must never break a turn+ entry = DecisionRecord(+ utterance_preview=(utterance or "")[:PREVIEW_CHARS],+ utterance_hash=utterance_hash(utterance),+ vetoed_by=vetoed_by,+ )+ _RING.append(entry)+ return entry+++def recent(+ limit: int = 50, *, skill: str = "", fired: bool | None = None+) -> list[DecisionRecord]:+ """Most recent decisions first, optionally filtered."""+ out: list[DecisionRecord] = []+ for entry in reversed(_RING):+ if skill and entry.winner != skill:+ continue+ if fired is not None and entry.fired is not fired:+ continue+ out.append(entry)+ if len(out) >= max(1, limit):+ break+ return out+++def clear() -> None:+ """Drop the ring (tests, and an explicit user reset)."""+ _RING.clear()+++def size() -> int:+ return len(_RING)+++__all__ = [+ "MAX_ENTRIES",+ "PREVIEW_CHARS",+ "CandidateRecord",+ "DecisionRecord",+ "clear",+ "recent",+ "record",+ "size",+ "utterance_hash",+]diff --git a/jarvis/skills/prefs.py b/jarvis/skills/prefs.pyindex 8ff845bde2..fb54c4bb4a 100644--- a/jarvis/skills/prefs.py+++ b/jarvis/skills/prefs.py@@ -40,6 +40,8 @@ log = logging.getLogger(__name__)STATE_ON = "active"STATE_OFF = "disabled"_LEGAL_STATES = frozenset({STATE_ON, STATE_OFF})+#: Legal per-skill auto-fire modes; mirrors autofire_policy.AUTO_FIRE_MODES.+_LEGAL_AUTOFIRE = frozenset({"auto", "always", "never"})# Serializes the read-modify-write of skill_prefs.json. Callers are sync (FastAPI# threadpool / registry reload), so a threading.Lock is the right primitive.@@ -52,6 +54,12 @@ class SkillPrefs:order: list[str] = field(default_factory=list)state: dict[str, str] = field(default_factory=dict)+ #: Per-skill deterministic auto-fire choice, ``{name: "auto"|"always"|"never"}``.+ #: Lives here rather than in frontmatter for the same reason the on/off state+ #: does: builtin skills need an admin password to edit and are re-copied by+ #: bootstrap, so a user preference written into their frontmatter would be+ #: silently reverted.+ autofire: dict[str, str] = field(default_factory=dict)# ----------------------------------------------------------------------@@ -71,11 +79,18 @@ def _read_raw() -> dict[str, Any]:return data if isinstance(data, dict) else {}-def _write_raw(order: list[str], state: dict[str, str]) -> None:+def _write_raw(+ order: list[str], state: dict[str, str], autofire: dict[str, str] | None = None+) -> None:"""Atomic write: tempfile in the parent dir → ``os.replace``."""path = skill_prefs_path()payload = json.dumps(- {"version": 1, "order": order, "state": state},+ {+ "version": 1,+ "order": order,+ "state": state,+ "autofire": autofire or {},+ },ensure_ascii=False,indent=2,)@@ -112,7 +127,13 @@ def load_prefs() -> SkillPrefs:for name, value in state_raw.items():if isinstance(name, str) and value in _LEGAL_STATES:state[name] = value- return SkillPrefs(order=order, state=state)+ autofire_raw = raw.get("autofire")+ autofire: dict[str, str] = {}+ if isinstance(autofire_raw, dict):+ for name, value in autofire_raw.items():+ if isinstance(name, str) and value in _LEGAL_AUTOFIRE:+ autofire[name] = value+ return SkillPrefs(order=order, state=state, autofire=autofire)def load_state_overrides() -> dict[str, str]:@@ -125,6 +146,11 @@ def load_order() -> list[str]:return load_prefs().order+def load_autofire_prefs() -> dict[str, str]:+ """``{skill_name: "auto" | "always" | "never"}``. Empty when never set."""+ return load_prefs().autofire++# ----------------------------------------------------------------------# Mutate (read-modify-write under the lock)# ----------------------------------------------------------------------@@ -136,7 +162,7 @@ def set_state(name: str, on: bool) -> None:prefs = load_prefs()state = dict(prefs.state)state[name] = STATE_ON if on else STATE_OFF- _write_raw(prefs.order, state)+ _write_raw(prefs.order, state, prefs.autofire)def set_order(names: list[str]) -> None:@@ -144,7 +170,23 @@ def set_order(names: list[str]) -> None:clean = [s for s in names if isinstance(s, str)]with _LOCK:prefs = load_prefs()- _write_raw(clean, prefs.state)+ _write_raw(clean, prefs.state, prefs.autofire)+++def set_autofire(name: str, mode: str) -> None:+ """Record the user's deterministic auto-fire choice for ``name``.++ An unknown mode clears the entry rather than persisting garbage, so a bad+ API call degrades to "use the derived default".+ """+ with _LOCK:+ prefs = load_prefs()+ autofire = dict(prefs.autofire)+ if mode in _LEGAL_AUTOFIRE:+ autofire[name] = mode+ else:+ autofire.pop(name, None)+ _write_raw(prefs.order, prefs.state, autofire)def remove_skill(name: str) -> None:@@ -153,10 +195,13 @@ def remove_skill(name: str) -> None:prefs = load_prefs()order = [s for s in prefs.order if s != name]state = {k: v for k, v in prefs.state.items() if k != name}- _write_raw(order, state)+ autofire = {k: v for k, v in prefs.autofire.items() if k != name}+ _write_raw(order, state, autofire)__all__ = [+ "load_autofire_prefs",+ "set_autofire","STATE_ON","STATE_OFF","SkillPrefs",diff --git a/jarvis/skills/schema.py b/jarvis/skills/schema.pyindex c9cc3bb973..5b01f60ab4 100644--- a/jarvis/skills/schema.py+++ b/jarvis/skills/schema.py@@ -122,6 +122,17 @@ class SkillFrontmatter(BaseModel):# skills are dispatched as background worker briefs.when_to_use: str | None = Noneexecution: Literal["inline", "mission"] = "inline"+ # Deterministic auto-fire override (2026-07-25). "auto" — the default, and+ # what every skill authored before this field has — means the derived class+ # in jarvis/skills/autofire_policy.py decides. That default is deliberate:+ # a pure opt-in field would leave every one of the maintainer's installed+ # skills unable to fire while the release notes claimed the problem was+ # solved, which is the AP-27 shape (a precision default that silently zeroes+ # recall). "never" opts out of the deterministic relevance layer only —+ # author-written triggers keep working. "always" promotes a tool-backed+ # skill into the weaker band, and can NEVER promote a dispatching one; no+ # configuration may authorize a matcher to start a background process.+ auto_fire: Literal["auto", "always", "never"] = "auto"@field_validator("name")@classmethod@@ -291,6 +302,38 @@ class SkillInvoked(Event):source: str = ""+@dataclass(frozen=True, slots=True)+class SkillMatchEvaluated(Event):+ """Every skill-match evaluation, including the ones that matched NOTHING.++ ``SkillInvoked`` answers "did a skill fire?". This answers the question that+ was actually unanswerable: "why did nothing fire?" Emitted on every turn —+ no match, weak match, and vetoed match alike — because a decision that+ leaves no trace is exactly what made "my skill never triggers" impossible+ to diagnose. Today each veto is a ``log.info`` nobody reads.++ Carries the utterance HASH, never the text: the durable sink is the flight+ recorder on disk, and a public-release scrub must not have to chase spoken+ content through it. The readable 80-char preview stays in the in-memory ring+ (:mod:`jarvis.skills.match_log`).++ ``vetoed_by`` is a member of ``jarvis.skills.guards.VETO_REASONS`` or "".+ """+ utterance_hash: str = ""+ lang: str = ""+ source: str = "none" # trigger | relevance | none+ band: str = "none" # fire | narrow | none+ winner: str = ""+ autofire_class: str = "" # instruction | tool_backed | dispatching+ vetoed_by: str = ""+ fired: bool = False+ shadow: bool = False+ elapsed_us: int = 0+ #: ``(skill_name, rounded_score)`` for the top candidates — enough to see a+ #: near-miss without carrying the whole ranking onto the bus.+ candidates: tuple[tuple[str, float], ...] = ()++@dataclass(frozen=True, slots=True)class SkillDirectTriggered(Event):"""Skill was directly activated via the TriggerMatcher (pre-brain hook).diff --git a/scripts/skill_relevance_calibrate.py b/scripts/skill_relevance_calibrate.pyindex 274d9d6d50..d96249d6a8 100644--- a/scripts/skill_relevance_calibrate.py+++ b/scripts/skill_relevance_calibrate.py@@ -43,6 +43,14 @@ if sys.platform == "win32": # UTF-8 stdout; cp1252 is the Windows defaultreconfigure(encoding="utf-8", errors="replace")+def _guard_veto(registry: object, skill_name: str, text: str, evidence: str) -> str:+ """The veto the runtime's own guards would return, or "" if none."""+ from jarvis.skills.guards import evaluate_guards++ skill = registry.get(skill_name) # type: ignore[attr-defined]+ return evaluate_guards(skill, user_text=text, evidence=evidence).vetoed_by++def _percentile(values: list[float], fraction: float) -> float:if not values:return 0.0@@ -94,11 +102,32 @@ def main() -> int:if hit is not None:positive_scores.append(hit.score)+ # Only negatives that SURVIVE the guards belong in the threshold+ # calculation. This distinction is load-bearing, and getting it wrong is the+ # AP-27 trap in miniature: the five strongest-scoring negatives are all+ # definitional questions ("what is <product>, actually?"), which score high+ # for the correct reason — the utterance really is about that skill's topic —+ # and are suppressed by the definitional-question guard, not by a threshold.+ # Counting them here would recommend raising FIRE from ~1.16 to ~1.59 and+ # cut relevance recall from 100 % to 29 % while the report still claimed+ # "zero false positives". Scoring is content-agnostic; the guards are where+ # semantics belong. Keep them in separate columns.negative_scores: list[float] = []+ guarded_away: list[tuple[float, str, str]] = []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)+ if ranking.top is None:+ continue+ winner = ranking.top.name+ veto = ""+ try:+ veto = _guard_veto(registry, winner, negative.text, ranking.top.evidence)+ except Exception: # noqa: BLE001+ veto = ""+ if veto:+ guarded_away.append((ranking.top.score, winner, veto))+ continue+ negative_scores.append(ranking.top.score)print()print("Score distributions (relevance channel only)")@@ -113,8 +142,24 @@ def main() -> int: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}"+ f"max={max(negative_scores):.3f} (guard survivors only)"+ )+ if guarded_away:+ print()+ print(+ f" {len(guarded_away)} negative(s) scored high but were VETOED by a "+ "guard, not by a threshold —"+ )+ print(+ " excluded from the calculation on purpose. Folding them in would "+ "recommend a"+ )+ print(+ " much higher FIRE cut-off and quietly destroy recall (AP-27). "+ "Strongest:")+ for score, winner, veto in sorted(guarded_away, reverse=True)[:5]:+ print(f" {score:.3f} {winner:26} vetoed_by={veto}")# --- the operating point ------------------------------------------------print()diff --git a/tests/fixtures/skill_routing/BASELINE.json b/tests/fixtures/skill_routing/BASELINE.jsonindex bda3ca25bb..48d7109698 100644--- a/tests/fixtures/skill_routing/BASELINE.json+++ b/tests/fixtures/skill_routing/BASELINE.json@@ -4,8 +4,8 @@"relevance_recall": 1.0,"false_fires": 0,"known_gaps": 2,- "positives_scored": 54,- "negatives": 23,+ "positives_scored": 69,+ "negatives": 24,"per_skill": {"cli-gcloud": 1.0,"control-api": 0.0,@@ -23,6 +23,7 @@"plugin-gmail": 1.0,"plugin-google_calendar": 1.0,"plugin-google_drive": 0.5,+ "plugin-home_assistant": 1.0,"plugin-linear": 1.0,"plugin-notion": 1.0,"plugin-slack": 1.0,diff --git a/tests/fixtures/skill_routing/golden.yaml b/tests/fixtures/skill_routing/golden.yamlindex fa9754a63b..4c199e728c 100644--- a/tests/fixtures/skill_routing/golden.yaml+++ b/tests/fixtures/skill_routing/golden.yaml@@ -310,106 +310,102 @@ skills:lang: enmin_band: narrowsource: authored-- plugin-todoist:- positives:- - text: "trag das bitte in todoist ein"+ - text: "such den vertrag in meiner dropbox"channel: triggerlang: demin_band: narrowsource: authored- - text: "what is on my todoist list today"+ - text: "share that dropbox folder with anna"channel: triggerlang: enmin_band: narrowsource: authored- plugin-clickup:+ plugin-home_assistant:positives:- - text: "zeig mir die offenen clickup tasks"- channel: trigger+ - text: "mach bitte das licht im wohnzimmer aus"+ channel: relevancelang: demin_band: narrowsource: authored- - text: "create a clickup task for that"- channel: trigger+ - text: "turn the kitchen lights off please"+ channel: relevancelang: enmin_band: narrowsource: authored+ - text: "stell die heizung im schlafzimmer auf 21 grad"+ channel: relevance+ lang: de+ min_band: narrow+ source: authored+ hard_negatives:+ - text: "was ist home assistant eigentlich fuer eine software"+ reason: definitional question about the product, not a request to act- plugin-airtable:+ plugin-todoist:positives:- - text: "schreib die zeile in die airtable basis"+ - text: "trag das bitte in todoist ein"channel: triggerlang: demin_band: narrowsource: authored- - text: "read the airtable records for me"+ - text: "what is on my todoist list today"channel: triggerlang: enmin_band: narrowsource: authored-- plugin-canva:- positives:- - text: "mach mir ein neues design in canva"+ - text: "setz milch auf meine todoist liste"channel: triggerlang: demin_band: narrowsource: authored- - text: "export that canva design as a pdf"+ - text: "what's due in todoist today"channel: triggerlang: enmin_band: narrowsource: authored- plugin-cal_com:+ plugin-clickup:positives:- - text: "wann ist mein naechster termin bei cal com"+ - text: "zeig mir die offenen clickup tasks"channel: triggerlang: demin_band: narrowsource: authored- - text: "book a slot in cal com"+ - text: "create a clickup task for that"channel: triggerlang: enmin_band: narrowsource: authored-- plugin-todoist:- positives:- - text: "setz milch auf meine todoist liste"+ - text: "zeig mir meine clickup aufgaben"channel: triggerlang: demin_band: narrowsource: authored- - text: "what's due in todoist today"+ - text: "create a clickup task for the rewrite"channel: triggerlang: enmin_band: narrowsource: authored- plugin-clickup:+ plugin-airtable:positives:- - text: "zeig mir meine clickup aufgaben"+ - text: "schreib die zeile in die airtable basis"channel: triggerlang: demin_band: narrowsource: authored- - text: "create a clickup task for the rewrite"+ - text: "read the airtable records for me"channel: triggerlang: enmin_band: narrowsource: authored-- plugin-dropbox:- positives:- - text: "such den vertrag in meiner dropbox"+ - text: "welche eintraege stehen in meiner airtable basis"channel: triggerlang: demin_band: narrowsource: authored- - text: "share that dropbox folder with anna"+ - text: "update that airtable record"channel: triggerlang: enmin_band: narrow@@ -417,6 +413,16 @@ skills: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- text: "mach mir ein canva poster fuer den vortrag"channel: triggerlang: de@@ -428,21 +434,18 @@ skills:min_band: narrowsource: authored- plugin-airtable:+ plugin-cal_com:positives:- - text: "welche eintraege stehen in meiner airtable basis"+ - text: "wann ist mein naechster termin bei cal com"channel: triggerlang: demin_band: narrowsource: authored- - text: "update that airtable record"+ - text: "book a slot in cal com"channel: triggerlang: enmin_band: narrowsource: authored-- plugin-cal_com:- positives:- text: "welche buchungen habe ich morgen in calcom"channel: triggerlang: dediff --git a/tests/unit/brain/test_skill_relevance_routing.py b/tests/unit/brain/test_skill_relevance_routing.pynew file mode 100644index 0000000000..d3c2cecfce--- /dev/null+++ b/tests/unit/brain/test_skill_relevance_routing.py@@ -0,0 +1,511 @@+"""The relevance layer wired into BrainManager — additive, guarded, reversible.++The whole claim of this change is that it ADDS a channel without touching the+one that already works, and that a match inferred by a scorer has strictly+fewer rights than a match an author asked for. These tests are that claim,+written as assertions.++The prompt-caching test at the bottom is the quiet one that matters most: the+narrowed candidate hint must ride the per-turn context and never the cached+system prefix, or the change would break caching on every turn and cost far+more than it saves.+"""+from __future__ import annotations++from pathlib import Path+from typing import Any++import pytest++from jarvis.brain.manager import BrainManager+from jarvis.core.bus import EventBus+from jarvis.core.config import JarvisConfig+from jarvis.core.protocols import ToolResult+from jarvis.skills import match_log, relevance+from jarvis.skills.registry import SkillRegistry+from jarvis.skills.skill_context import SkillContext, set_skill_context+++class _FakeSpawnTool:+ name = "spawn_worker"+ schema: dict[str, Any] = {}+++class _FakeRunSkillTool:+ name = "run-skill"+ schema: dict[str, Any] = {}+++class _RecordingExecutor:+ def __init__(self) -> None:+ self.calls: list[tuple[Any, dict[str, Any], str]] = []++ async def execute(+ self,+ tool: Any,+ args: dict[str, Any],+ *,+ user_utterance: str = "",+ trace_id: Any = None,+ **_: Any,+ ) -> ToolResult:+ self.calls.append((tool, args, user_utterance))+ return ToolResult(success=True, output="ok")+++class _StubRunner:+ def render_instructions(self, skill: Any, *, args: dict | None = None) -> str:+ return f"# {skill.name}\nDo the thing."+++def _write_skill(+ root: Path,+ name: str,+ *,+ pattern: str | None = None,+ description: str = "Demo skill for relevance-routing tests.",+ tags: list[str] | None = None,+ state: str | None = None,+ tier: str | None = None,+ execution: str | None = None,+ requires_tools: list[str] | None = None,+ auto_fire: str | None = None,+) -> None:+ folder = root / name+ folder.mkdir(parents=True, exist_ok=True)+ lines = [+ "---",+ 'schema_version: "1"',+ f"name: {name}",+ f"description: {description}",+ ]+ if tags:+ lines.append(f"tags: [{', '.join(tags)}]")+ if pattern:+ lines += ["triggers:", " - type: voice", f' pattern: "{pattern}"']+ if state:+ lines.append(f"state: {state}")+ if tier:+ lines += ["risk_policy:", f" default_tier: {tier}"]+ if execution:+ lines.append(f"execution: {execution}")+ if requires_tools is not None:+ lines.append(f"requires_tools: [{', '.join(requires_tools)}]")+ if auto_fire:+ lines.append(f"auto_fire: {auto_fire}")+ lines += ["---", "", f"# {name}", "", "Follow the steps.", ""]+ (folder / "SKILL.md").write_text("\n".join(lines), encoding="utf-8")+++#: Utterances MEASURED against the small fixture corpus below, not guessed.+#: With seven skills the FIRE cut-off lands near 0.98: a bare+#: "aktiviere den konzentrationsmodus" scores 0.74 (NARROW), while naming+#: both indexed terms scores 1.05 (FIRE). Re-measure with+#: scripts/skill_relevance_calibrate.py if the fixture changes.+FIRE_UTTERANCE = "aktiviere den fokus und den konzentrationsmodus" # i18n-allow++#: Both terms the FIRE utterance names must be indexed, or it scores as a+#: single-term NARROW hit instead.+FOCUS_TAGS = ["konzentrationsmodus", "fokus"]+NARROW_UTTERANCE = "aktiviere den konzentrationsmodus" # i18n-allow+#: Matches no skill at all — the "nothing happened" case.+UNRELATED_UTTERANCE = "wie ist das wetter in berlin" # i18n-allow+++def _make_manager(+ *, shadow: bool = False, enabled: bool = True, min_band: str = "fire"+) -> BrainManager:+ config = JarvisConfig()+ config.skills.relevance_enabled = enabled+ config.skills.relevance_shadow = shadow+ config.skills.auto_fire_min_band = min_band+ return BrainManager(+ config=config,+ bus=EventBus(),+ tools={+ "spawn_worker": _FakeSpawnTool(),+ "run-skill": _FakeRunSkillTool(),+ },+ tool_executor=_RecordingExecutor(), # type: ignore[arg-type]+ )+++def _install(root: Path) -> None:+ registry = SkillRegistry(root=root)+ registry.reload_sync()+ set_skill_context(SkillContext(registry=registry, runner=_StubRunner())) # type: ignore[arg-type]++[email protected](autouse=True)+def _clean() -> None:+ relevance.clear_index_cache()+ match_log.clear()+ set_skill_context(None)+ yield+ set_skill_context(None)+ relevance.clear_index_cache()+ match_log.clear()+++# ---------------------------------------------------------------------------+# The trigger channel keeps absolute precedence+# ---------------------------------------------------------------------------+++def test_a_trigger_hit_wins_over_a_stronger_relevance_candidate(+ tmp_path: Path,+) -> None:+ """Zero behaviour change for anything that already worked.++ ``fokusmodus`` is the deep-work trigger AND a strong relevance term for the+ decoy, which stuffs it into name, tags and description. The author's regex+ must still win.+ """+ _write_skill(tmp_path, "deep-work-mode", pattern="(fokusmodus)")+ _write_skill(+ tmp_path,+ "fokusmodus-decoy",+ description="fokusmodus fokusmodus fokusmodus",+ tags=["fokusmodus"],+ )+ for filler in range(6):+ _write_skill(tmp_path, f"filler-{filler}", description=f"topic{filler}")+ _install(tmp_path)++ manager = _make_manager()+ matched = manager._match_skill_for_turn("fokusmodus")+ assert matched is not None+ assert matched.name == "deep-work-mode"+ assert manager._skill_relevance is None, "trigger path must not consult the scorer"+++def test_the_kill_switch_restores_pre_relevance_behaviour(tmp_path: Path) -> None:+ _write_skill(tmp_path, "focus", tags=FOCUS_TAGS)+ for filler in range(6):+ _write_skill(tmp_path, f"filler-{filler}", description=f"topic{filler}")+ _install(tmp_path)++ assert (+ _make_manager(enabled=True)._match_skill_for_turn(FIRE_UTTERANCE)+ is not None+ )+ assert _make_manager(enabled=False)._match_skill_for_turn(FIRE_UTTERANCE) is None+++# ---------------------------------------------------------------------------+# The relevance channel captures a paraphrase the anchored trigger cannot+# ---------------------------------------------------------------------------+++def test_a_paraphrase_reaches_an_anchored_trigger_skill(tmp_path: Path) -> None:+ """The maintainer's actual case.++ deep-work-mode ships an ANCHORED trigger (``^...$``), so any extra word+ breaks it — "aktiviere bitte den konzentrationsmodus" could never fire.+ """+ _write_skill(+ tmp_path,+ "deep-work-mode",+ pattern="^(fokusmodus|konzentrationsmodus)$",+ tags=FOCUS_TAGS,+ )+ for filler in range(6):+ _write_skill(tmp_path, f"filler-{filler}", description=f"topic{filler}")+ _install(tmp_path)++ manager = _make_manager()++ # The anchored trigger only ever fires on the bare word.+ assert manager._match_skill_for_turn("konzentrationsmodus") is not None+ assert manager._skill_relevance is None, "bare word is a trigger hit"++ # One extra word breaks the anchor — the relevance layer catches it.+ matched = manager._match_skill_for_turn(FIRE_UTTERANCE)+ assert matched is not None+ assert matched.name == "deep-work-mode"+ assert manager._skill_relevance is not None+ assert manager._skill_relevance.source == "relevance"+++# ---------------------------------------------------------------------------+# Guards are inherited, not re-implemented+# ---------------------------------------------------------------------------+++def test_a_draft_skill_never_fires_however_strongly_it_scores(tmp_path: Path) -> None:+ """AP-15, enforced structurally: a draft is not in the voice index at all."""+ _write_skill(+ tmp_path,+ "secret-draft",+ description="konzentrationsmodus fokus",+ tags=FOCUS_TAGS,+ state="draft",+ )+ for filler in range(6):+ _write_skill(tmp_path, f"filler-{filler}", description=f"topic{filler}")+ _install(tmp_path)++ manager = _make_manager(min_band="narrow")+ assert manager._match_skill_for_turn(NARROW_UTTERANCE) is None+++def test_a_block_tier_skill_never_captures_via_relevance(tmp_path: Path) -> None:+ _write_skill(+ tmp_path, "locked", tags=FOCUS_TAGS, tier="block"+ )+ for filler in range(6):+ _write_skill(tmp_path, f"filler-{filler}", description=f"topic{filler}")+ _install(tmp_path)++ manager = _make_manager(min_band="narrow")+ assert manager._match_skill_for_turn(NARROW_UTTERANCE) is None+ assert match_log.recent(1)[0].vetoed_by == "block_tier"+++def test_a_definitional_question_is_still_suppressed(tmp_path: Path) -> None:+ """The guard needs the RAW span, which is why evidence is never normalized."""+ _write_skill(tmp_path, "plugin-github", tags=["github"])+ for filler in range(6):+ _write_skill(tmp_path, f"filler-{filler}", description=f"topic{filler}")+ _install(tmp_path)++ manager = _make_manager(min_band="narrow")+ assert manager._match_skill_for_turn("was ist GitHub?") is None+ assert match_log.recent(1)[0].vetoed_by == "definitional_question"+++def test_a_mission_skill_never_captures_via_relevance(tmp_path: Path) -> None:+ """cloud-debug's shape: a paraphrase must not start a background worker."""+ _write_skill(+ tmp_path,+ "cloud-debug",+ description="Dispatch a bug hunt to the background worker.",+ tags=["debugsprint"],+ execution="mission",+ )+ for filler in range(6):+ _write_skill(tmp_path, f"filler-{filler}", description=f"topic{filler}")+ _install(tmp_path)++ manager = _make_manager(min_band="narrow")+ assert manager._match_skill_for_turn("mach mal einen debugsprint") is None+ assert match_log.recent(1)[0].vetoed_by == "class_dispatching"+++def test_an_explicit_opt_out_is_honoured(tmp_path: Path) -> None:+ _write_skill(+ tmp_path, "focus", tags=FOCUS_TAGS, auto_fire="never"+ )+ for filler in range(6):+ _write_skill(tmp_path, f"filler-{filler}", description=f"topic{filler}")+ _install(tmp_path)++ manager = _make_manager(min_band="narrow")+ assert manager._match_skill_for_turn(NARROW_UTTERANCE) is None+ assert match_log.recent(1)[0].vetoed_by == "auto_fire_never"+++# ---------------------------------------------------------------------------+# Shadow mode+# ---------------------------------------------------------------------------+++def test_shadow_mode_records_but_does_not_capture(tmp_path: Path) -> None:+ _write_skill(tmp_path, "focus", tags=FOCUS_TAGS)+ for filler in range(6):+ _write_skill(tmp_path, f"filler-{filler}", description=f"topic{filler}")+ _install(tmp_path)++ manager = _make_manager(shadow=True)+ assert manager._match_skill_for_turn(FIRE_UTTERANCE) is None++ entry = match_log.recent(1)[0]+ assert entry.shadow is True+ assert entry.vetoed_by == "shadow_mode"+ assert entry.winner == "focus", "the decision itself is still recorded"+ # The narrowed hint must still ship — that is what makes shadow mode useful+ # rather than merely inert.+ assert manager._skill_relevance is not None+++# ---------------------------------------------------------------------------+# Stand-down rights+# ---------------------------------------------------------------------------+++def test_a_tool_backed_relevance_match_keeps_run_skill_visible(+ tmp_path: Path,+) -> None:+ """Dropping run-skill removes the model's only way to say "wrong skill".++ It may only be dropped where an author asked for the match, or where the+ skill can do nothing but add words.+ """+ _write_skill(+ tmp_path,+ "plugin-gmail",+ tags=["posteingangscheck"],+ requires_tools=["gmail"],+ )+ for filler in range(6):+ _write_skill(tmp_path, f"filler-{filler}", description=f"topic{filler}")+ _install(tmp_path)++ manager = _make_manager(min_band="narrow")+ manager._skill_turn_match = manager._match_skill_for_turn(+ "mach mal einen posteingangscheck"+ )+ assert manager._skill_turn_match is not None+ assert manager._skill_stand_downs_allowed() is False++ manager._skill_injected_inline = True+ tools = manager._drop_run_skill_when_inline_injected(dict(manager._tools))+ assert "run-skill" in tools+++def test_an_instruction_only_relevance_match_keeps_the_full_stand_down(+ tmp_path: Path,+) -> None:+ _write_skill(tmp_path, "focus", tags=FOCUS_TAGS, requires_tools=[])+ for filler in range(6):+ _write_skill(tmp_path, f"filler-{filler}", description=f"topic{filler}")+ _install(tmp_path)++ manager = _make_manager()+ manager._skill_turn_match = manager._match_skill_for_turn(FIRE_UTTERANCE)+ assert manager._skill_turn_match is not None+ assert manager._skill_stand_downs_allowed() is True++ manager._skill_injected_inline = True+ tools = manager._drop_run_skill_when_inline_injected(dict(manager._tools))+ assert "run-skill" not in tools+++def test_a_trigger_match_keeps_its_historical_rights(tmp_path: Path) -> None:+ _write_skill(+ tmp_path,+ "plugin-gmail",+ pattern="(posteingang)",+ requires_tools=["gmail"],+ )+ for filler in range(6):+ _write_skill(tmp_path, f"filler-{filler}", description=f"topic{filler}")+ _install(tmp_path)++ manager = _make_manager()+ manager._skill_turn_match = manager._match_skill_for_turn(+ "schau mal in den posteingang"+ )+ assert manager._skill_turn_match is not None+ assert manager._skill_stand_downs_allowed() is True+++# ---------------------------------------------------------------------------+# NARROW: a suggestion, not a capture+# ---------------------------------------------------------------------------+++def test_narrow_does_not_capture_but_does_narrow(tmp_path: Path) -> None:+ """NARROW_UTTERANCE is measured to land in the NARROW band on this corpus."""+ _write_skill(tmp_path, "focus", tags=FOCUS_TAGS)+ for filler in range(6):+ _write_skill(tmp_path, f"filler-{filler}", description=f"topic{filler}")+ _install(tmp_path)++ manager = _make_manager()+ manager._skill_turn_match = manager._match_skill_for_turn(NARROW_UTTERANCE)++ assert manager._skill_relevance is not None+ assert manager._skill_relevance.band == "narrow"+ assert manager._skill_turn_match is None, "NARROW must never capture by default"++ hint = manager._render_skill_candidate_hint()+ assert hint is not None+ assert "focus" in hint+ assert "run-skill" in hint+ assert "ranked suggestions" in hint, "the model must know it may ignore this"+++def test_the_hint_is_absent_on_a_captured_turn(tmp_path: Path) -> None:+ _write_skill(tmp_path, "focus", tags=FOCUS_TAGS)+ for filler in range(6):+ _write_skill(tmp_path, f"filler-{filler}", description=f"topic{filler}")+ _install(tmp_path)++ manager = _make_manager()+ manager._skill_turn_match = manager._match_skill_for_turn(FIRE_UTTERANCE)+ assert manager._skill_turn_match is not None+ assert manager._render_skill_candidate_hint() is None+++# ---------------------------------------------------------------------------+# Prompt caching — the quiet regression guard+# ---------------------------------------------------------------------------+++def test_the_cached_system_prefix_is_identical_across_bands(tmp_path: Path) -> None:+ """The narrowed hint must ride the per-turn context, never the prefix.++ Rewriting the cached system prompt per turn would break prompt caching on+ EVERY turn — a far larger cost than anything narrowing could save. This test+ is the only thing standing between that mistake and production.+ """+ _write_skill(tmp_path, "focus", tags=FOCUS_TAGS)+ _write_skill(tmp_path, "plugin-gmail", tags=["inbox"])+ for filler in range(6):+ _write_skill(tmp_path, f"filler-{filler}", description=f"topic{filler}")+ _install(tmp_path)++ manager = _make_manager()++ manager._match_skill_for_turn(UNRELATED_UTTERANCE)+ prefix_none = manager._build_system_prompt()++ manager._match_skill_for_turn("irgendwas mit inbox hier drin")+ prefix_narrow = manager._build_system_prompt()++ manager._match_skill_for_turn(FIRE_UTTERANCE)+ prefix_fire = manager._build_system_prompt()++ assert prefix_none == prefix_narrow == prefix_fire+++# ---------------------------------------------------------------------------+# The decision log+# ---------------------------------------------------------------------------+++def test_every_evaluation_is_recorded_including_a_total_miss(tmp_path: Path) -> None:+ """"Nothing happened" must leave a trace, or it stays undiagnosable."""+ _write_skill(tmp_path, "focus", tags=FOCUS_TAGS)+ for filler in range(6):+ _write_skill(tmp_path, f"filler-{filler}", description=f"topic{filler}")+ _install(tmp_path)++ manager = _make_manager()+ manager._match_skill_for_turn(UNRELATED_UTTERANCE)+ entries = match_log.recent(5)+ assert entries, "a miss must still be recorded"+ assert entries[0].winner == ""+++def test_the_log_keeps_a_readable_preview_but_hashes_for_the_bus(+ tmp_path: Path,+) -> None:+ _write_skill(tmp_path, "focus", tags=FOCUS_TAGS)+ for filler in range(6):+ _write_skill(tmp_path, f"filler-{filler}", description=f"topic{filler}")+ _install(tmp_path)++ manager = _make_manager()+ manager._match_skill_for_turn(FIRE_UTTERANCE)+ entry = match_log.recent(1)[0]+ assert "konzentrationsmodus" in entry.utterance_preview+ assert entry.utterance_hash+ assert len(entry.utterance_hash) == 12+++def test_matching_never_raises_without_a_skill_context() -> None:+ """Headless and mock boots have no skill subsystem at all."""+ manager = _make_manager()+ assert manager._match_skill_for_turn(FIRE_UTTERANCE) is Nonediff --git a/tests/unit/skills/test_autofire_policy.py b/tests/unit/skills/test_autofire_policy.pynew file mode 100644index 0000000000..571b83a1ca--- /dev/null+++ b/tests/unit/skills/test_autofire_policy.py@@ -0,0 +1,284 @@+"""Capture permission — who may take over a turn, and who never may.++A matched skill does not add to a turn, it takes it over: the body is injected,+``run-skill`` is removed so the model cannot decline, the local-action fast path+and the evidence gate stand down, and a mission skill dispatches a worker and+returns before the model sees anything. These tests pin the asymmetry that+follows from that — a wrong suggestion is free, a wrong takeover is not.++The concrete case that shaped the class table: ``cloud-debug`` ships as+``execution: mission`` with ``default_tier: monitor`` and NO triggers. It is+unreachable by matching today, and a fuzzy layer makes it reachable — so a+paraphrase could start an unrequested background worker in a git worktree.+"""+from __future__ import annotations++import pytest++from jarvis.skills import autofire_policy as policy+from jarvis.skills.guards import (+ VETO_AUTO_FIRE_NEVER,+ VETO_BAND_BELOW_FLOOR,+ VETO_DISPATCHING_CLASS,+ VETO_REASONS,+)+from jarvis.skills.match_eval import BAND_FIRE, BAND_NARROW, BAND_NONE+++class _FakeRiskPolicy:+ def __init__(self, tier: str = "monitor") -> None:+ self.default_tier = tier+++class _FakeFrontmatter:+ def __init__(+ self,+ *,+ tier: str = "monitor",+ execution: str = "inline",+ requires_tools: list[str] | None = None,+ plugin_id: str | None = None,+ auto_fire: str = "auto",+ ) -> None:+ self.risk_policy = _FakeRiskPolicy(tier)+ self.execution = execution+ self.requires_tools = requires_tools or []+ self.plugin_id = plugin_id+ self.auto_fire = auto_fire+++class _FakeSkill:+ def __init__(+ self,+ name: str = "demo",+ frontmatter: _FakeFrontmatter | None = None,+ body: str = "# Demo\n\nDo the thing.\n",+ ) -> None:+ self.name = name+ self.frontmatter = frontmatter if frontmatter is not None else _FakeFrontmatter()+ self.body = body+++# ---------------------------------------------------------------------------+# Classification+# ---------------------------------------------------------------------------+++def test_a_plain_inline_skill_is_instruction_class() -> None:+ assert policy.classify(_FakeSkill()) == policy.CLASS_INSTRUCTION++[email protected]("tier", ["safe", "monitor"])+def test_safe_and_monitor_tiers_stay_instruction(tier: str) -> None:+ skill = _FakeSkill(frontmatter=_FakeFrontmatter(tier=tier))+ assert policy.classify(skill) == policy.CLASS_INSTRUCTION+++def test_requiring_a_tool_makes_it_tool_backed() -> None:+ skill = _FakeSkill(frontmatter=_FakeFrontmatter(requires_tools=["cli_gcloud"]))+ assert policy.classify(skill) == policy.CLASS_TOOL_BACKED+++def test_a_paired_plugin_skill_is_tool_backed() -> None:+ skill = _FakeSkill(frontmatter=_FakeFrontmatter(plugin_id="gmail"))+ assert policy.classify(skill) == policy.CLASS_TOOL_BACKED+++def test_ask_tier_is_tool_backed_not_instruction() -> None:+ """`ask` needs the voice-confirm machinery that lives in the orchestrator."""+ skill = _FakeSkill(frontmatter=_FakeFrontmatter(tier="ask"))+ assert policy.classify(skill) == policy.CLASS_TOOL_BACKED+++def test_a_mission_skill_is_dispatching() -> None:+ """The cloud-debug shape: mission + monitor tier + no triggers."""+ skill = _FakeSkill(+ "cloud-debug", _FakeFrontmatter(execution="mission", tier="monitor")+ )+ assert policy.classify(skill) == policy.CLASS_DISPATCHING+++def test_block_tier_is_dispatching() -> None:+ skill = _FakeSkill(frontmatter=_FakeFrontmatter(tier="block"))+ assert policy.classify(skill) == policy.CLASS_DISPATCHING+++def test_a_legacy_macro_body_is_dispatching() -> None:+ """A body written for the retired macro executor may name arbitrary tools."""+ skill = _FakeSkill(body="# Old\n\nTOOL: run-shell {\"cmd\": \"rm -rf /\"}\n")+ assert policy.classify(skill) == policy.CLASS_DISPATCHING+++def test_missing_frontmatter_is_dispatching() -> None:+ """Unknown intent is not granted capture rights."""+ skill = _FakeSkill()+ skill.frontmatter = None+ assert policy.classify(skill) == policy.CLASS_DISPATCHING+++def test_an_unrecognised_tier_fails_toward_the_safer_class() -> None:+ skill = _FakeSkill(frontmatter=_FakeFrontmatter(tier="weird-new-tier"))+ assert policy.classify(skill) == policy.CLASS_TOOL_BACKED+++# ---------------------------------------------------------------------------+# The tri-state override+# ---------------------------------------------------------------------------+++def test_the_default_is_auto_not_opt_in() -> None:+ """A pure opt-in default would be the AP-27 shape.++ None of the maintainer's installed skills carry the field, so shipping+ opt-in would leave the answer to "has a skill ever fired?" at *no* while+ the release notes claimed otherwise.+ """+ assert policy.auto_fire_mode(_FakeSkill()) == policy.AUTO_FIRE_AUTO+ allowed, veto = policy.may_capture(_FakeSkill(), BAND_FIRE)+ assert allowed is True+ assert veto == ""+++def test_never_opts_out_of_the_relevance_layer() -> None:+ skill = _FakeSkill(frontmatter=_FakeFrontmatter(auto_fire="never"))+ allowed, veto = policy.may_capture(skill, BAND_FIRE)+ assert allowed is False+ assert veto == VETO_AUTO_FIRE_NEVER+++def test_a_user_override_beats_frontmatter() -> None:+ """Builtins need an admin password to edit and are re-copied by bootstrap,+ so the user's choice cannot live in their frontmatter."""+ skill = _FakeSkill(frontmatter=_FakeFrontmatter(auto_fire="auto"))+ assert policy.auto_fire_mode(skill, override="never") == policy.AUTO_FIRE_NEVER+ allowed, veto = policy.may_capture(skill, BAND_FIRE, override="never")+ assert allowed is False+ assert veto == VETO_AUTO_FIRE_NEVER+++def test_an_invalid_override_falls_back_to_the_derived_default() -> None:+ assert policy.auto_fire_mode(_FakeSkill(), override="yolo") == policy.AUTO_FIRE_AUTO+++# ---------------------------------------------------------------------------+# Capture permission+# ---------------------------------------------------------------------------+++def test_narrow_does_not_capture_by_default() -> None:+ allowed, veto = policy.may_capture(_FakeSkill(), BAND_NARROW)+ assert allowed is False+ assert veto == VETO_BAND_BELOW_FLOOR+++def test_narrow_captures_when_the_deployment_opens_it_up() -> None:+ allowed, veto = policy.may_capture(_FakeSkill(), BAND_NARROW, min_band="narrow")+ assert allowed is True+ assert veto == ""+++def test_always_promotes_a_tool_backed_skill_into_the_weaker_band() -> None:+ skill = _FakeSkill(+ frontmatter=_FakeFrontmatter(requires_tools=["gmail"], auto_fire="always")+ )+ allowed, _ = policy.may_capture(skill, BAND_NARROW)+ assert allowed is True+++def test_always_can_never_promote_a_dispatching_skill() -> None:+ """The one line no configuration may cross.++ No frontmatter field may authorize a deterministic matcher to start a+ background process — so `always` is checked AFTER the class veto, not before.+ """+ skill = _FakeSkill(+ "cloud-debug",+ _FakeFrontmatter(execution="mission", auto_fire="always"),+ )+ for band in (BAND_FIRE, BAND_NARROW):+ allowed, veto = policy.may_capture(skill, band, min_band="narrow")+ assert allowed is False+ assert veto == VETO_DISPATCHING_CLASS+++def test_a_dispatching_skill_never_captures_even_at_fire() -> None:+ skill = _FakeSkill("cloud-debug", _FakeFrontmatter(execution="mission"))+ allowed, veto = policy.may_capture(skill, BAND_FIRE)+ assert allowed is False+ assert veto == VETO_DISPATCHING_CLASS+++def test_band_none_never_captures() -> None:+ allowed, veto = policy.may_capture(_FakeSkill(), BAND_NONE)+ assert allowed is False+ assert veto == VETO_BAND_BELOW_FLOOR+++def test_every_veto_is_in_the_closed_vocabulary() -> None:+ cases = (+ policy.may_capture(_FakeSkill(), BAND_NONE),+ policy.may_capture(_FakeSkill(), BAND_NARROW),+ policy.may_capture(+ _FakeSkill(frontmatter=_FakeFrontmatter(auto_fire="never")), BAND_FIRE+ ),+ policy.may_capture(+ _FakeSkill("m", _FakeFrontmatter(execution="mission")), BAND_FIRE+ ),+ )+ for allowed, veto in cases:+ assert allowed is False+ assert veto in VETO_REASONS+++# ---------------------------------------------------------------------------+# Stand-downs+# ---------------------------------------------------------------------------+++def test_only_instruction_at_fire_gets_the_full_stand_down() -> None:+ assert policy.stand_downs_allowed(_FakeSkill(), BAND_FIRE) is True+++def test_a_tool_backed_skill_never_gets_the_full_stand_down() -> None:+ """Live bug 2026-06-21: plugin-discord suppressed the local-action fast path+ and a tool-less deep brain then claimed it had no Discord access."""+ skill = _FakeSkill("plugin-discord", _FakeFrontmatter(plugin_id="discord"))+ assert policy.stand_downs_allowed(skill, BAND_FIRE) is False+++def test_narrow_never_gets_the_full_stand_down() -> None:+ assert policy.stand_downs_allowed(_FakeSkill(), BAND_NARROW) is False+++def test_class_vocabulary_is_closed() -> None:+ for skill in (+ _FakeSkill(),+ _FakeSkill(frontmatter=_FakeFrontmatter(requires_tools=["x"])),+ _FakeSkill(frontmatter=_FakeFrontmatter(execution="mission")),+ ):+ assert policy.classify(skill) in policy.AUTOFIRE_CLASSES+++def test_the_real_cloud_debug_skill_can_never_auto_fire() -> None:+ """End-to-end against the shape as it actually ships."""+ from jarvis.skills.schema import SkillFrontmatter++ frontmatter = SkillFrontmatter(+ name="cloud-debug",+ version="1.0.0",+ description="Dispatch a bug hunt to the background worker.",+ execution="mission",+ )++ class _Real:+ pass++ skill = _Real()+ skill.name = "cloud-debug" # type: ignore[attr-defined]+ skill.frontmatter = frontmatter # type: ignore[attr-defined]+ skill.body = "# Cloud Debug\n\nFind the root cause.\n" # type: ignore[attr-defined]++ assert policy.classify(skill) == policy.CLASS_DISPATCHING+ allowed, veto = policy.may_capture(skill, BAND_FIRE, min_band="narrow")+ assert allowed is False+ assert veto == VETO_DISPATCHING_CLASS