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.

fix(skills): close the review findings on the skill-recognition work

Harald5ab4d2519b4e
diff --git a/jarvis/realtime/session.py b/jarvis/realtime/session.py
index cf94d65299..874cb229bf 100644
--- a/jarvis/realtime/session.py
+++ b/jarvis/realtime/session.py
@@ -2458,6 +2458,9 @@ class RealtimeVoiceSession:
#: ``_skill_directive``. The delegate reads it to avoid handing the
#: brain a skill this session already put in front of the model.
self._skill_inlined_for: tuple[str, str] | None = None
+ #: ``(utterance, MatchDecision)`` — one skill evaluation per utterance,
+ #: shared by the inline injection, the NARROW hint and the delegate.
+ self._skill_decision_cache: tuple[str, Any] | None = None
# Live caption of the CURRENT unfinished utterance. Surfaces render
# it; persistence never does unless the promotion path says so
# explicitly (a mid-word partial silently recorded as the turn's
@@ -2854,14 +2857,10 @@ class RealtimeVoiceSession:
# This session already put the skill in front of the model.
return
try:
- from jarvis.skills.match_eval import BAND_FIRE, evaluate_match
- from jarvis.skills.skill_context import try_get_skill_context
+ from jarvis.skills.match_eval import BAND_FIRE
- context = try_get_skill_context()
- if context is None:
- return
- decision = evaluate_match(context.registry, utterance, limit=2)
- if decision.band != BAND_FIRE or decision.top is None:
+ decision = self._skill_decision(utterance)
+ if decision is None or decision.band != BAND_FIRE or decision.top is None:
return
skill_name = str(decision.top.skill_name)
note(skill_name, content="", source="realtime_match")
@@ -2897,7 +2896,7 @@ class RealtimeVoiceSession:
if not utterance:
return ""
try:
- from jarvis.skills.match_eval import BAND_NARROW, evaluate_match
+ from jarvis.skills.match_eval import BAND_NARROW
from jarvis.skills.prompt_injection import render_skill_candidate_hint
from jarvis.skills.skill_context import try_get_skill_context
@@ -2905,8 +2904,8 @@ class RealtimeVoiceSession:
if context is None:
return ""
limit = max(1, int(getattr(self._skills_cfg(), "narrow_candidates", 3)))
- decision = evaluate_match(context.registry, utterance, limit=limit + 2)
- if decision.band != BAND_NARROW:
+ decision = self._skill_decision(utterance)
+ if decision is None or decision.band != BAND_NARROW:
return ""
entries: list[tuple[str, str]] = []
for candidate in decision.candidates or ():
@@ -2941,13 +2940,58 @@ class RealtimeVoiceSession:
def _skills_cfg(self) -> Any:
"""The ``[skills]`` config section, or defaults."""
- section = getattr(self._config, "skills", None)
+ section = getattr(getattr(self, "_config", None), "skills", None)
if section is not None:
return section
from jarvis.core.config import SkillsConfig
return SkillsConfig()
+ def _skill_decision(self, text: str) -> Any | None:
+ """The skill match for ``text`` — evaluated once, reused for the turn.
+
+ Three call sites ask the same question about the same sentence on the
+ same turn (inline injection, the NARROW hint, and the delegate
+ hand-off), and the first two sit in the same ``update_session`` payload.
+ Scoring the corpus three times per turn on the live-voice hot path buys
+ nothing, so the answer is computed once and cached against the
+ utterance it was computed for.
+
+ Every ``[skills]`` knob travels with it. Reading only some of the
+ section is a silent config switch (CLAUDE.md §7).
+ """
+ key = str(text or "").strip()
+ if not key:
+ return None
+ # ``getattr`` rather than direct access: the cache is an optimisation,
+ # not a contract, and the bound-method test doubles in
+ # tests/unit/realtime carry only the collaborators a method needs.
+ cached = getattr(self, "_skill_decision_cache", None)
+ if cached is not None and cached[0] == key:
+ return cached[1]
+ try:
+ from jarvis.skills.match_eval import evaluate_match
+ from jarvis.skills.skill_context import try_get_skill_context
+
+ context = try_get_skill_context()
+ if context is None:
+ return None
+ cfg = self._skills_cfg()
+ limit = max(3, int(getattr(cfg, "narrow_candidates", 3)) + 2)
+ decision = evaluate_match(
+ context.registry,
+ key,
+ limit=limit,
+ use_relevance=bool(getattr(cfg, "relevance_enabled", True)),
+ fire_threshold=getattr(cfg, "fire_threshold", None),
+ hint_threshold=getattr(cfg, "hint_threshold", None),
+ )
+ except Exception: # noqa: BLE001 — a match fault must never end a call
+ log.debug("Realtime skill match unavailable", exc_info=True)
+ return None
+ self._skill_decision_cache = (key, decision)
+ return decision
+
def _skills_directive(self, *, compact: bool | None = None) -> str:
"""The installed-skill roster for this session's instructions.
@@ -3020,7 +3064,7 @@ class RealtimeVoiceSession:
return ""
try:
from jarvis.skills.autofire_policy import CLASS_INSTRUCTION, classify
- from jarvis.skills.match_eval import BAND_FIRE, evaluate_match
+ from jarvis.skills.match_eval import BAND_FIRE
from jarvis.skills.schema import SkillInvoked
from jarvis.skills.skill_context import try_get_skill_context
except Exception: # noqa: BLE001
@@ -3032,8 +3076,8 @@ class RealtimeVoiceSession:
context = try_get_skill_context()
if context is None:
return ""
- decision = evaluate_match(context.registry, text, limit=2)
- if decision.band != BAND_FIRE or decision.top is None:
+ decision = self._skill_decision(text)
+ if decision is None or decision.band != BAND_FIRE or decision.top is None:
return ""
skill = context.registry.get(decision.top.skill_name)
except Exception: # noqa: BLE001
@@ -3116,17 +3160,15 @@ class RealtimeVoiceSession:
installed skill produced no skill reason and never reached the
orchestrator that could run it.
- This is an O(1) cache read keyed on the registry's reload counter — the
- index is built lazily on first use, never here on the hot path (AP-26).
+ Delegates to the one implementation in ``jarvis.skills.skill_context``
+ so this and the execute-time tool guard cannot answer the same sentence
+ differently. A cache read keyed on the registry's reload counter; only
+ the first call after a hot reload pays for the rebuild.
"""
try:
- from jarvis.skills.relevance import get_index
- from jarvis.skills.skill_context import try_get_skill_context
+ from jarvis.skills.skill_context import current_match_index
- context = try_get_skill_context()
- if context is None:
- return None
- return get_index(context.registry)
+ return current_match_index()
except Exception: # noqa: BLE001 — planning keeps its static fallbacks
log.debug("Realtime skill match index unavailable", exc_info=True)
return None
@@ -8414,6 +8456,11 @@ class RealtimeVoiceSession:
if reason:
instruction = f"{situation} The reason reported was: {reason}"
facts: dict[str, object] | None = {"reason": reason}
+ # The composer rephrases the English cause itself — but only while
+ # it has a live model. The canned floor gets the cause already in
+ # the turn's language, so a dead flash slot cannot produce the
+ # half-German sentence of 2026-08-20.
+ spoken_reason = localize_failure_reason(reason, language)
canned = lambda: action_phrase( # noqa: E731
"action_failed_reason", language, reason=spoken_reason
)
@@ -8456,11 +8503,6 @@ class RealtimeVoiceSession:
await self._publish_turn_completed()
# Between this boundary and the transcript there is no open turn, yet the
# user is audibly mid-utterance: no follow-up may take the floor here.
- # The composer rephrases the English cause itself — but only while
- # it has a live model. The canned floor gets the cause already in
- # the turn's language, so a dead flash slot cannot produce the
- # half-German sentence of 2026-08-20.
- spoken_reason = localize_failure_reason(reason, language)
self._user_speech_active = True
# Do not open the next persisted turn on VAD alone. A cancelled provider
# response can still emit response.done after barge-in; opening here would
diff --git a/jarvis/realtime/tools.py b/jarvis/realtime/tools.py
index 79888679e7..9c2d09986f 100644
--- a/jarvis/realtime/tools.py
+++ b/jarvis/realtime/tools.py
@@ -218,19 +218,15 @@ def _is_music_plugin(name: str) -> bool:
def _skill_match_index() -> Any | None:
"""The deterministic skill index, or ``None`` when unavailable.
- Mirrors ``RealtimeSession._skill_match_index`` — an O(1) cache read keyed
- on the registry's reload counter, never a build on the hot path (AP-26).
- Both the routing decision and this execute-time guard must plan a turn
- against the SAME vocabulary, or they disagree about the same sentence.
+ Delegates to the one implementation in ``jarvis.skills.skill_context``
+ so this guard and the session's routing decision cannot drift apart —
+ a copy of it lived here and said "mirrors" in its own docstring, which
+ is the shape of a future disagreement, not a safeguard against one.
"""
try:
- from jarvis.skills.relevance import get_index
- from jarvis.skills.skill_context import try_get_skill_context
+ from jarvis.skills.skill_context import current_match_index
- context = try_get_skill_context()
- if context is None:
- return None
- return get_index(context.registry)
+ return current_match_index()
except Exception: # noqa: BLE001 — planning keeps its static fallbacks
return None
@@ -311,16 +307,21 @@ def _turn_shape_refusal(
"or ask what they want done."
)
try:
- # The skill index has to travel with the text, exactly as it does in
- # the session's own routing call. Without it the planner's vocabulary
- # only knows the literal word "skill", so an utterance that NAMES an
- # installed skill scores no reason here — and this guard refused
- # ``run-skill`` on a turn the router had already routed with
- # ``reasons=skill`` moments earlier (live 2026-08-20, "Morgenroutine").
- # One planner asked two ways is not a guard, it is a coin flip.
- has_world_reason = bool(
- plan_turn(text, skill_index=_skill_match_index()).reasons
- )
+ # The skill index travels ONLY for ``run-skill``. Without it the
+ # planner's vocabulary knows just the literal word "skill", so an
+ # utterance that NAMES an installed skill scores no reason and this
+ # guard refused ``run-skill`` on a turn the router had already routed
+ # with ``reasons=skill`` moments earlier (live 2026-08-20,
+ # "Morgenroutine"). One planner asked two ways is a coin flip.
+ #
+ # Scoped deliberately: an installed skill scoring FIRE says something
+ # about whether a SKILL applies, and nothing about whether some
+ # unrelated monitor-tier plugin call is warranted. Handing the index to
+ # every tool would let "ich brauche Konzentration" — a remark, not an
+ # order — buy a side effect for any tool the live model happened to
+ # pick, which is the exact thing this gate exists to refuse.
+ skill_index = _skill_match_index() if name == "run-skill" else None
+ has_world_reason = bool(plan_turn(text, skill_index=skill_index).reasons)
except Exception: # noqa: BLE001 — the planner must not brick a tool call
has_world_reason = True
if has_world_reason:
@@ -487,6 +488,7 @@ class RealtimeToolBridge:
else "monitor",
)
hook = getattr(tool, "risk_tier_for_args", None)
+ impact = getattr(tool, "describe_args", None)
descriptors[str(name)] = SupervisorToolDescriptor(
name=str(name),
description=str(getattr(tool, "description", "")),
@@ -494,6 +496,7 @@ class RealtimeToolBridge:
risk_tier=risk_tier,
is_action_tool=bool(getattr(tool, "is_action_tool", False)),
risk_tier_for_args=hook if callable(hook) else None,
+ describe_args=impact if callable(impact) else None,
)
return descriptors
diff --git a/jarvis/skills/creator_service.py b/jarvis/skills/creator_service.py
index deed55228b..988e08abc2 100644
--- a/jarvis/skills/creator_service.py
+++ b/jarvis/skills/creator_service.py
@@ -606,6 +606,15 @@ class SkillCreatorService:
raise
last_error = exc
continue
+ # The KEY is the slug; what the ANSWER says is the model's display
+ # name. Reporting the slug back made a spoken confirmation read
+ # "morgenroutine" for a user who had just said "Morgenroutine" —
+ # the docstring's promise is a name the answer reports, and a slug
+ # is an identifier, not a name. A collision suffix is carried over
+ # so the second skill is not announced as the first.
+ spoken_name = raw_name or draft["name"]
+ if attempt > 1:
+ spoken_name = f"{spoken_name} {attempt}"
return AuthoredSkill(
skill=skill,
result=SkillCreatorResult(
@@ -615,7 +624,7 @@ class SkillCreatorService:
brain_used=True,
brain_source=result.brain_source,
),
- name=draft["name"],
+ name=spoken_name,
slug=slugify(draft["name"]),
)
assert last_error is not None
diff --git a/jarvis/skills/eval_harness.py b/jarvis/skills/eval_harness.py
index 76cd541243..835a75b5af 100644
--- a/jarvis/skills/eval_harness.py
+++ b/jarvis/skills/eval_harness.py
@@ -24,6 +24,7 @@ from typing import Any
from jarvis.skills.guards import (
VETO_AUTHORING_REQUEST,
+ VETO_BLOCK_TIER,
VETO_LIFECYCLE_REQUEST,
evaluate_guards,
)
@@ -274,6 +275,18 @@ class Report:
}
+def _is_block_tier(skill: Any) -> bool:
+ """Mirrors ``BrainManager._skill_is_blocked`` — the ONLY gate the explicit
+ and authoring channels apply before firing."""
+ frontmatter = getattr(skill, "frontmatter", None)
+ if frontmatter is None:
+ return True
+ try:
+ return frontmatter.risk_policy.default_tier == "block"
+ except Exception: # noqa: BLE001
+ return False
+
+
def _prefer_music_service(
registry: Any, decision: Any, skill: Any, text: str
) -> tuple[Any, Any]:
@@ -291,6 +304,11 @@ def _prefer_music_service(
"""
from dataclasses import replace as _replace
+ # The whole body sits inside the try, the rewrite included: an earlier
+ # version closed it before the two ``_replace`` calls, so a registry double
+ # whose skills are not frozen dataclasses raised straight out of ``_decide``
+ # and aborted the entire run — exactly what the noqa below promises it
+ # cannot do.
try:
from jarvis.core.music_constants import MUSIC_PLUGIN_IDS
from jarvis.core.music_service import resolve_music_service
@@ -307,13 +325,13 @@ def _prefer_music_service(
)
if not target or target == plugin_id:
return decision, skill
+ # ``registry.get`` RAISES on a miss; it never returns None, so there is
+ # no None branch to write here.
sibling = registry.get(f"plugin-{target}")
+ top = _replace(decision.top, skill_name=sibling.name)
+ return _replace(decision, top=top, candidates=(top,)), sibling
except Exception: # noqa: BLE001 — a routing nicety must never break the eval
return decision, skill
- if sibling is None:
- return decision, skill
- top = _replace(decision.top, skill_name=sibling.name)
- return _replace(decision, top=top, candidates=(top,)), sibling
def _decide(registry: Any, text: str, lang: str = "auto") -> tuple[Any, str]:
@@ -330,18 +348,23 @@ def _decide(registry: Any, text: str, lang: str = "auto") -> tuple[Any, str]:
from jarvis.skills.authoring_request import resolve_skill_authoring_request
from jarvis.skills.explicit_request import resolve_explicit_skill_request
- # Channel 0 — the user NAMED a skill. Trigger-grade rights.
+ # Channel 0 — the user NAMED a skill. Trigger-grade rights: production
+ # applies ONLY the block-tier gate here and fires (manager.py:5394-5412),
+ # so running the full guard ladder would re-introduce the same
+ # ladder mismatch this function exists to remove, merely inverted — a
+ # question naming a skill would score `definitional_question` here and
+ # fire in production.
explicit = resolve_explicit_skill_request(text, registry)
if explicit is not None:
explicit_skill, explicit_decision = explicit
- ladder = evaluate_guards(
- explicit_skill, user_text=text, evidence=explicit_decision.top.evidence
+ return explicit_decision, (
+ VETO_BLOCK_TIER if _is_block_tier(explicit_skill) else ""
)
- return explicit_decision, ladder.vetoed_by
# Channel 0.5 — the user asked to CREATE or MANAGE a skill. Every service
# named inside such a request is CONTENT, never a command to that service,
- # so no domain skill may capture even when its brand regex matches.
+ # so no domain skill may capture even when its brand regex matches. Same
+ # block-tier-only gate as Channel 0 (manager.py:5458-5475).
authoring = resolve_skill_authoring_request(text, registry)
if authoring is not None:
if authoring.skill is None or authoring.kind == "lifecycle":
@@ -351,10 +374,9 @@ def _decide(registry: Any, text: str, lang: str = "auto") -> tuple[Any, str]:
else VETO_AUTHORING_REQUEST
)
return authoring.decision, veto
- ladder = evaluate_guards(
- authoring.skill, user_text=text, evidence=authoring.decision.top.evidence
+ return authoring.decision, (
+ VETO_BLOCK_TIER if _is_block_tier(authoring.skill) else ""
)
- return authoring.decision, ladder.vetoed_by
# Channel 1/2 — the author's trigger regex, then the relevance scorer.
decision = evaluate_match(registry, text, lang=lang)
diff --git a/jarvis/skills/prompt_injection.py b/jarvis/skills/prompt_injection.py
index 5ba005461f..fde089ffee 100644
--- a/jarvis/skills/prompt_injection.py
+++ b/jarvis/skills/prompt_injection.py
@@ -196,6 +196,11 @@ def render_available_skills_section(
return f"{header}\n{intro}\n{body}{outro}"
+#: Per-entry cap for a candidate blurb, applied inside the renderer so both
+#: callers get the same bound rather than each truncating to its own taste.
+_CANDIDATE_BLURB_CHARS = 400
+
+
def render_skill_candidate_hint(entries: Sequence[tuple[str, str]]) -> str:
"""The "these scored, you decide" block for a turn nothing captured.
@@ -206,14 +211,25 @@ def render_skill_candidate_hint(entries: Sequence[tuple[str, str]]) -> str:
drift, and a hint that says something different depending on which engine
is running is worse than one that is merely imperfect.
- ``entries`` is ``(skill_name, blurb)``, best first and already truncated by
- the caller. Returns ``""`` for an empty list so callers can append blindly.
+ ``entries`` is ``(skill_name, blurb)``, best first. Returns ``""`` for an
+ empty list so callers can append blindly.
+
+ Whitespace is flattened HERE, not in the callers. ``when_to_use`` is
+ routinely a YAML block scalar, so its text arrives with real newlines; a
+ caller that forgot to collapse them let a skill's own frontmatter emit
+ extra ``- `name` — …`` lines inside this block and forge candidates that
+ were never ranked. One renderer with one normalization is the whole point
+ of sharing it.
The decision explicitly stays with the model: a wrong candidate is ignored,
never executed. That is what makes this block safe to show on a merely
plausible match, where an automatic capture would not be.
"""
- lines = [f"- `{name}` — {blurb}" if blurb else f"- `{name}`" for name, blurb in entries]
+ lines = []
+ for name, blurb in entries:
+ flat_name = " ".join(str(name or "").split())
+ flat_blurb = " ".join(str(blurb or "").split())[:_CANDIDATE_BLURB_CHARS]
+ lines.append(f"- `{flat_name}` — {flat_blurb}" if flat_blurb else f"- `{flat_name}`")
if not lines:
return ""
return (
@@ -237,6 +253,15 @@ _REALTIME_RICH_CHARS = 300
_REALTIME_DESC_CHARS = 70
+#: ``(id(registry), generation, compact, budget) -> block``. The roster only
+#: changes when the registry reloads, but it is rebuilt for every per-turn
+#: session update on a live call, at three call sites. Keyed on the reload
+#: counter the registry publishes for exactly this (``SkillRegistry.generation``),
+#: the same convention ``jarvis.skills.relevance.get_index`` already uses.
+#: Single-entry: one live session has one registry and one profile.
+_REALTIME_ROSTER_CACHE: dict[tuple[int, int, bool, int], str] = {}
+
+
def render_realtime_skills_directive(
registry: SkillRegistry,
*,
@@ -269,28 +294,30 @@ def render_realtime_skills_directive(
Returns ``""`` when no skill is invocable, so the caller can drop the
block from the instruction assembly entirely.
"""
+ generation = getattr(registry, "generation", None)
+ cache_key: tuple[int, int, bool, int] | None = None
+ if isinstance(generation, int):
+ cache_key = (id(registry), generation, bool(compact), int(budget_chars))
+ cached = _REALTIME_ROSTER_CACHE.get(cache_key)
+ if cached is not None:
+ return cached
try:
active = registry.list_active()
except Exception: # noqa: BLE001 — a roster fault must never break a call
return ""
- # (name, rich blurb, short blurb, is_builtin)
+ # (name, full rich blurb, description only, is_builtin) — untruncated here;
+ # the width is chosen below against the budget.
entries: list[tuple[str, str, str, bool]] = []
for skill in active:
fm = getattr(skill, "frontmatter", None)
if fm is None:
continue
- name = str(skill.name)
+ name = " ".join(str(skill.name).split())
if not name:
continue
desc = " ".join((getattr(fm, "description", "") or "").split())
when = " ".join((getattr(fm, "when_to_use", "") or "").split())
- rich = f"{desc} {when}".strip()
- if len(rich) > _REALTIME_RICH_CHARS:
- rich = rich[: _REALTIME_RICH_CHARS - 1].rstrip() + "…"
- short = desc
- if len(short) > _REALTIME_DESC_CHARS:
- short = short[: _REALTIME_DESC_CHARS - 1].rstrip() + "…"
- entries.append((name, rich, short, _is_builtin(skill)))
+ entries.append((name, f"{desc} {when}".strip(), desc, _is_builtin(skill)))
if not entries:
return ""
@@ -310,15 +337,36 @@ def render_realtime_skills_directive(
"that merely mentions the topic is not a match."
)
+ def _finish(block: str) -> str:
+ if cache_key is not None:
+ _REALTIME_ROSTER_CACHE.clear()
+ _REALTIME_ROSTER_CACHE[cache_key] = block
+ return block
+
+ def _clip(text: str, cap: int) -> str:
+ return text if len(text) <= cap else text[: cap - 1].rstrip() + "…"
+
+ def _block(index: int, cap: int) -> str:
+ listed = "\n".join(
+ f"- {entry[0]} — {_clip(entry[index], cap)}"
+ if entry[index]
+ else f"- {entry[0]}"
+ for entry in entries
+ )
+ return f"{header}{listed}{rule}"
+
if not compact:
- for index in (1, 2): # 1 = rich blurb, 2 = short blurb
- listed = "\n".join(
- f"- {name} — {entry[index]}" if entry[index] else f"- {name}"
- for entry in entries
- for name in (entry[0],)
- )
- block = f"{header}{listed}{rule}"
+ # Narrow the blurbs before dropping them. The earlier version tried one
+ # rich width and then fell straight to description-only, so a corpus
+ # merely a few hundred characters over budget demoted EVERY skill to
+ # the 70-char description this whole renderer exists to get away from.
+ # Width degrades; the matching rule survives as long as it can.
+ for cap in (_REALTIME_RICH_CHARS, 200, 140):
+ block = _block(1, cap)
if len(block) <= budget_chars:
- return block
- names_only = ", ".join(name for name, _, _, _ in entries)
- return f"{header}{names_only}{rule}"
+ return _finish(block)
+ block = _block(2, _REALTIME_DESC_CHARS)
+ if len(block) <= budget_chars:
+ return _finish(block)
+ names_only = ", ".join(entry[0] for entry in entries)
+ return _finish(f"{header}{names_only}{rule}")
diff --git a/jarvis/skills/relevance.py b/jarvis/skills/relevance.py
index fbc31e9740..a707e36460 100644
--- a/jarvis/skills/relevance.py
+++ b/jarvis/skills/relevance.py
@@ -240,17 +240,24 @@ def normalize_text(text: str) -> str:
return "".join(ch for ch in decomposed if not unicodedata.combining(ch))
-_NAME_TOKEN_RE = re.compile(r"[a-z0-9]+")
+#: Any run of word characters except the underscore, which is a separator in a
+#: skill name. Deliberately NOT ``[a-z0-9]+``: that matched nothing in
+#: Cyrillic, Greek, Hebrew, Arabic or CJK, so every fuzzy name lookup below
+#: failed closed for those scripts and a skill authored by voice in such a
+#: language was reachable only by its exact key — the very BUG-158 failure,
+#: left open for most of the world. All locales are equal (CLAUDE.md §1).
+_NAME_TOKEN_RE = re.compile(r"[^\W_]+", re.UNICODE)
def skill_name_tokens(name: str) -> tuple[str, ...]:
"""Fold a skill name to the token tuple used to compare names.
``morning-routine``, ``Morning Routine`` and ``MORNING_ROUTINE`` all fold
- to ``("morning", "routine")``. Two naming conventions live in one registry
+ to ``("morning", "routine")``; ``Утренняя Рутина`` folds to its own two
+ tokens rather than to nothing. Two naming conventions live in one registry
keyed by this field — builtins ship kebab-case slugs while the skill
- creator writes Title Case display names — so every name comparison outside
- an exact-key read has to go through this.
+ creator writes display names — so every name comparison outside an
+ exact-key read has to go through this.
"""
return tuple(_NAME_TOKEN_RE.findall(normalize_text(name)))
diff --git a/jarvis/skills/skill_context.py b/jarvis/skills/skill_context.py
index c22a0e62f1..733019b5b7 100644
--- a/jarvis/skills/skill_context.py
+++ b/jarvis/skills/skill_context.py
@@ -77,3 +77,34 @@ def try_get_skill_context() -> SkillContext | None:
wasn't set up, such as in headless mock mode).
"""
return _CONTEXT
+
+
+def current_match_index() -> object | None:
+ """The deterministic skill index for the live registry, or ``None``.
+
+ The one home for "give the turn planner something to score skills with".
+ The realtime session's routing decision and the execute-time tool guard
+ both need it and must use the SAME vocabulary — two copies of this lookup
+ drift, and a router and a guard that disagree about one sentence is the
+ failure mode both of them exist to prevent (BUG-158).
+
+ A cache read keyed on the registry's reload counter. The index is built
+ lazily on a miss, so the first call after a hot reload does pay for the
+ rebuild; every other call is O(1). Any fault answers "no index", which
+ returns the planner to its static vocabulary rather than raising into a
+ live turn.
+ """
+ try:
+ from jarvis.skills.relevance import get_index
+
+ context = _CONTEXT
+ if context is None:
+ return None
+ return get_index(context.registry)
+ except Exception: # noqa: BLE001 — planning keeps its static fallbacks
+ import logging
+
+ logging.getLogger(__name__).debug(
+ "skill match index unavailable", exc_info=True
+ )
+ return None
diff --git a/tests/unit/realtime/test_session.py b/tests/unit/realtime/test_session.py
index c9221afddf..cd2c0fe1e9 100644
--- a/tests/unit/realtime/test_session.py
+++ b/tests/unit/realtime/test_session.py
@@ -36,12 +36,17 @@ class FakeSession:
self.text_inputs = []
self.interrupts = 0
self.closed = False
+ #: Events the session actually pulled off the stream. The direct
+ #: measure of "the pump kept pumping" — a pump blocked on a tool
+ #: call stops consuming, and nothing else in this double shows that.
+ self.received = []
async def send_audio(self, chunk):
self.sent_audio.append(chunk)
async def receive(self):
for ev in self._events:
+ self.received.append(ev)
yield ev
await asyncio.sleep(0)
@@ -6438,17 +6443,21 @@ async def test_delegate_does_not_block_pump():
await sess.handle_control({"type": "audio_start", "sample_rate": 16_000})
await sess.wait_finished()
- # The pump processed the later events while the brain turn still hangs —
- # ``wait_finished`` returned with the gate still closed, and the transcript
- # that arrived after the tool call was surfaced.
+ # The pump consumed the event AFTER the tool call while the brain turn is
+ # still hanging. That is the whole claim in the test's name, and it is the
+ # only assertion that carries it: a pump blocked at the tool call would
+ # have stopped at two events.
#
- # This used to assert an ASSISTANT transcript. It cannot any more, and that
- # is the correct behaviour, not a regression: provider chatter is held
- # while a delegate is pending, so the user does not hear a fresh-
- # conversation filler over the real answer being computed (live 2026-07-17
- # 09:23, the incident test_presence_check_during_pending_action… guards).
- # What this test is about is that the delegate does not BLOCK the pump.
- assert any(m.get("type") == "transcript" for m in jsons)
+ # This used to assert an ASSISTANT transcript reached the surface. It
+ # cannot any more, and that is correct behaviour rather than a regression:
+ # provider chatter is held while a delegate is pending, so the user does
+ # not hear a fresh-conversation filler over the real answer being computed
+ # (live 2026-07-17 09:23, which test_presence_check_during_pending_action…
+ # guards). Weakening the assertion to "some transcript exists" was worse
+ # than either — the user's own input transcript arrives BEFORE the tool
+ # call, so it stayed green even if the pump stopped dead there.
+ assert len(provider.session.received) == 3
+ assert provider.session.received[-1].type == "output_transcript_delta"
assert provider.session.tool_results == []
gate.set()
diff --git a/tests/unit/realtime/test_session_skill_directive.py b/tests/unit/realtime/test_session_skill_directive.py
index e0a57d3f1d..0b3f2c3c0a 100644
--- a/tests/unit/realtime/test_session_skill_directive.py
+++ b/tests/unit/realtime/test_session_skill_directive.py
@@ -52,11 +52,16 @@ class _Session:
def __init__(self, *, pending: bool = False) -> None:
self._bus = None
self._pending = pending
+ self._config = None
+ self._skill_decision_cache = None
def _has_pending_delegate_from_earlier_turn(self) -> bool:
return self._pending
_skill_directive = session_module.RealtimeVoiceSession._skill_directive
+ # The one skill evaluation per utterance that _skill_directive reads.
+ _skill_decision = session_module.RealtimeVoiceSession._skill_decision
+ _skills_cfg = session_module.RealtimeVoiceSession._skills_cfg
def _write_skill(
diff --git a/tests/unit/realtime/test_session_skills_roster.py b/tests/unit/realtime/test_session_skills_roster.py
index e32f186298..108caf58d1 100644
--- a/tests/unit/realtime/test_session_skills_roster.py
+++ b/tests/unit/realtime/test_session_skills_roster.py
@@ -43,12 +43,17 @@ class _Session:
self._brain = brain
self._compact_instructions = compact
self._skill_inlined_for: tuple[str, str] | None = None
+ self._skill_decision_cache = None
+ self._config = None
self.session_id = "roster-test"
_skills_directive = session_module.RealtimeVoiceSession._skills_directive
_note_skill_for_delegate = (
session_module.RealtimeVoiceSession._note_skill_for_delegate
)
+ # The one skill evaluation per utterance the directives read.
+ _skill_decision = session_module.RealtimeVoiceSession._skill_decision
+ _skills_cfg = session_module.RealtimeVoiceSession._skills_cfg
def _write_skill(
@@ -232,7 +237,6 @@ class _CfgSession(_Session):
def __init__(self, **kw) -> None:
super().__init__(**kw)
- self._config = None
def _has_pending_delegate_from_earlier_turn(self) -> bool:
return False
diff --git a/tests/unit/skills/test_creator_service.py b/tests/unit/skills/test_creator_service.py
index 588b58ffb5..f4561da110 100644
--- a/tests/unit/skills/test_creator_service.py
+++ b/tests/unit/skills/test_creator_service.py
@@ -376,11 +376,13 @@ async def test_author_commits_the_brain_draft_as_a_draft_skill(registry, skills_
brain=_FakeBrain(_ROUTINE_BRAIN_JSON), registry=registry, user_skills_root=skills_root
)
authored = await svc.author(SkillCreatorInput(intent="morgenroutine", schedule_hint="0 6 * * *")) # i18n-allow: test input
- # The committed name is the SLUG, not the model's Title Case display name:
- # ``name`` is the registry key, and a key like "Morning Routine 2" is one
- # ``run-skill`` cannot find by any name a human would say (live 2026-08-20).
- assert authored.name == "morgenroutine"
+ # The committed KEY is the slug — a key like "Morning Routine 2" is one
+ # ``run-skill`` cannot find by any name a human would say (live
+ # 2026-08-20) — while the reported NAME stays the display name, because
+ # that is what the spoken confirmation reads back to the user.
+ assert authored.name == "Morgenroutine"
assert authored.slug == "morgenroutine"
+ assert authored.skill.name == "morgenroutine"
assert authored.skill.state == SkillLifecycleState.DRAFT # AP-15
on_disk = (skills_root / "morgenroutine" / "SKILL.md").read_text(encoding="utf-8")
assert "state: draft" in on_disk
@@ -407,9 +409,10 @@ async def test_author_suffixes_the_name_on_a_collision(registry, skills_root) ->
)
first = await svc.author(SkillCreatorInput(intent="a"))
second = await svc.author(SkillCreatorInput(intent="a"))
- assert first.name == "morgenroutine"
- # "-2", not " 2": the collision suffix must keep the name a slug, or the
- # second skill lands in the registry under a key with a space in it.
- assert second.name == "morgenroutine-2"
+ assert first.name == "Morgenroutine"
+ # The KEY takes "-2" so it stays a slug; the spoken name takes " 2" so
+ # the user hears which of the two was created.
+ assert second.name == "Morgenroutine 2"
+ assert second.skill.name == "morgenroutine-2"
assert (skills_root / "morgenroutine-2" / "SKILL.md").exists()
assert second.slug == "morgenroutine-2"
diff --git a/tests/unit/skills/test_registry_resolve.py b/tests/unit/skills/test_registry_resolve.py
index 5c63e0c801..5a80174a71 100644
--- a/tests/unit/skills/test_registry_resolve.py
+++ b/tests/unit/skills/test_registry_resolve.py
@@ -137,12 +137,22 @@ def test_resolve_prefers_the_live_user_skill_over_a_disabled_builtin(
def test_resolve_is_deterministic_under_an_ambiguous_name(tmp_path: Path) -> None:
- """Two skills folding to the same tokens always resolve to the same one,
- never to whichever the dict happened to yield first."""
- _write(tmp_path, "a-thing", "Focus Mode")
+ """Two skills folding to the same tokens resolve to a NAMED one.
+
+ Asserting only that twenty calls agree proves nothing: Python's dict order
+ is stable within a process, so a resolver that iterated ``_skills`` with no
+ ordering at all would pass that. The property is that the answer is decided
+ by the documented sorted-name rule — "Focus Mode" sorts before "focus-mode"
+ (uppercase first), so it wins regardless of insertion order.
+ """
+ # Written in the reverse of the expected winner, so insertion order and
+ # sort order disagree and only the sort can produce the assertion below.
_write(tmp_path, "b-thing", "focus-mode")
+ _write(tmp_path, "a-thing", "Focus Mode")
reg = SkillRegistry(tmp_path)
reg.reload_sync()
+ assert reg.resolve("focus mode").name == "Focus Mode"
+
first = reg.resolve("focus mode").name
assert all(reg.resolve("focus mode").name == first for _ in range(20))