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
fix(skills): let a realtime call actually start a skill (BUG-158)
Haralddd03f994cb8d
diff --git a/docs/BUGS.md b/docs/BUGS.mdindex 1987be12d2..64504aaa6e 100644--- a/docs/BUGS.md+++ b/docs/BUGS.md@@ -11013,3 +11013,96 @@ guard and does not use this watchdog.**Guards.** `tests/unit/realtime/test_stall_native_tool.py`(`test_in_flight_native_tool_is_not_a_stalled_turn`).++## BUG-158: no skill can be started by voice in a realtime call — the live model is never told a single skill name (CRITICAL, FIXED 2026-08-20)++**Symptom (Windows live forensic, 10:52 and 11:01, `vertex-live` /+`gemini-live-2.5-flash-native-audio`, hybrid).** The user asked three+times, three ways, for the morning routine. Three different failures,+none of them "the skill ran":++| Time | Utterance | What Jarvis said | What actually happened |+|---|---|---|---|+| 10:52:04 | "Morning-Routine" | "\"Morning Routine\" ist gestartet." | `tool_calls: []` — **nothing ran, and the user was told it had** |+| 11:01:28 | "Morgenroutine" | "Was genau meinst du mit Morgenroutine?" | `ActionDenied run-skill` |+| 11:01:37 | "Skills-Morgenroutine" | "ich erreiche meinen Anbieter gerade nicht" | no provider fault occurred |+| 11:02:05 | "Okay, kannst du bitte mal ein Skill Morning Routine starten?" | "Den Skill \"Morning Routine\" habe ich nicht gefunden." | `ActionExecuted run-skill error="Unknown skill: Morning Routine"` |++<!-- i18n-allow: quoted live German utterances and replies under forensic analysis -->++`morning-routine` was installed, `validated`, switched on, and its own+voice-trigger regex matches every one of those four utterances.++**Root cause — five independent defects on one path.** Measured, not+inferred: `_session_instructions` built a 17 488-character prompt+containing the word "skill" **zero** times.++1. **No roster.** `render_available_skills_section` is called only from+ `jarvis/brain/manager.py`. The realtime session carried the+ `run-skill` tool and no catalogue, so the argument was always a+ guess from the user's words.+2. **Exact-key lookup.** `SkillRegistry.get` is a plain dict read.+ `"Morning Routine"` ≠ `"morning-routine"` → `Unknown skill`.+3. **Two naming conventions in one key space.** Builtins ship+ kebab-case slugs; `creator_service.author` wrote the model's Title+ Case display name into `name:`, and resolved collisions by+ appending `" 2"` — producing the registry key `Morning Routine 2`.+4. **A tie erased the skill reason.** The planner required+ `ranking.clear_winner` before adding `TurnReason.SKILL`. The+ authored near-duplicate put both morning routines at FIRE band, so+ installing the second skill **silently disabled routing for the+ first**. A/B measured: with the duplicate, `clear_winner=False` on+ every "Morgenroutine" variant; without it, `True`.+5. **The guard planned the same sentence differently.** The session+ passes `skill_index=` to `plan_turn`; `_tool_intent_refusal` called+ it bare. So the router routed a turn with `reasons=skill` and the+ execute-time guard refused the same turn for having no reason.++A sixth, structural: `_skill_directive` returns `""` for anything it+cannot inline, and `""` meant "no skill". Both installed morning+routines fail its conditions — `morning-routine` at 1656 chars over the+1500 cap and on the tool-word regex, `Morning Routine 2` as+`tool_backed` — so a FIRE match was dropped on the floor every time.++**Why no test caught it.** `tests/integration/test_skill_listing_in_prompt.py`+asserts the roster reaches the prompt — the *BrainManager* prompt. No+test ever asked the realtime instructions the same question.++**Fix.**+- `SkillRegistry.resolve()` — exact key, then directory slug, then+ normalized token tuple, then namespace-prefix drop. `get` stays exact.+- `render_realtime_skills_directive()` + `RealtimeVoiceSession._skills_directive`,+ wired into all three `_session_instructions` call sites. Over budget it+ drops descriptions and keeps every NAME — a listed name is callable, a+ folded one is not.+- `run-skill` resolves instead of reading, reports the *resolved* name+ downstream, and names the installed skills in its error so the model+ can correct itself inside the turn.+- `turn_planner`: a FIRE hit adds `TurnReason.SKILL` even without a clear+ winner; only the `skill:<name>` pin still requires one.+- `_tool_intent_refusal` plans with the same `skill_index` the router uses.+- `RealtimeVoiceSession._note_skill_for_delegate` hands a non-inlinable+ FIRE match to the brain via the existing `note_skill_trigger` contract+ (AD-S4), so a matched skill is inlined here or executed there, never+ neither.+- `creator_service.author` commits a slugged name and suffixes `-2`.++**Class rule.** A tool whose argument is a name from a catalogue is+half a feature until the catalogue is in the prompt — shipping the tool+without the names guarantees a guess. And two questions must not share+one answer: "is this about a skill?" is not "which skill?", so ambiguity+may cost the pin, never the route.++**Parity.** `_session_instructions` is one function shared by every+realtime transport, so `openai-realtime`, `gemini-live`, `vertex-live`,+the tool-less handoff and the self-hosted local server were equally+skill-blind and are equally fixed; the compact profile gets a names-only+roster rather than none (CLAUDE.md §3). The classic pipeline and the+chat hook already ran the `TriggerMatcher` and were never affected.++**Guards.** `tests/unit/skills/test_registry_resolve.py`,+`tests/unit/realtime/test_session_skills_roster.py`,+`tests/unit/brain/test_turn_planner_skill_ambiguity.py`,+`tests/unit/skills/test_prompt_injection.py`+(`test_realtime_directive_*`), `tests/unit/brain/test_run_skill_tool.py`+(`test_run_skill_resolves_a_display_name_to_the_installed_slug`).diff --git a/jarvis/brain/turn_planner.py b/jarvis/brain/turn_planner.pyindex 5dd6bb4223..28351f7c97 100644--- a/jarvis/brain/turn_planner.py+++ b/jarvis/brain/turn_planner.py@@ -923,13 +923,22 @@ def plan_turn(try:ranking = skill_index.rank(text, limit=1)winner = ranking.top- if (- winner is not None- and winner.score >= ranking.fire_threshold- and ranking.clear_winner- ):+ if winner is not None and winner.score >= ranking.fire_threshold:+ # A FIRE-band hit makes this a SKILL turn even when two+ # installed skills tie for it. Requiring a clear winner here+ # conflated two different questions — "is this about a skill?"+ # and "which one?" — and answered the first with the second.+ # Live 2026-08-20: an authored near-duplicate of the builtin+ # morning routine put both at FIRE band, killed the clear+ # winner, and so removed TurnReason.SKILL from every+ # "Morgenroutine" turn. Installing a second skill silently+ # disabled routing for the first one.reasons.add(TurnReason.SKILL)- required = tuple(sorted({*required, f"skill:{winner.name}"}))+ if ranking.clear_winner:+ # Only a clear winner may PIN the skill. Ambiguity travels+ # to the orchestrator, which has the trigger channel and+ # the user to disambiguate with; the planner does not.+ required = tuple(sorted({*required, f"skill:{winner.name}"}))except Exception: # noqa: BLE001# Silent by design: this module has no logger and must stay free of# side effects, and a scorer fault simply means the staticdiff --git a/jarvis/plugins/tool/run_skill.py b/jarvis/plugins/tool/run_skill.pyindex b7c6ad3a02..4c7b9b90ed 100644--- a/jarvis/plugins/tool/run_skill.py+++ b/jarvis/plugins/tool/run_skill.py@@ -131,15 +131,34 @@ class RunSkillTool:error="Skill subsystem not initialized",)- # Step 3 — resolve skill+ # Step 3 — resolve skill.+ # ``resolve`` rather than ``get``: this name was written by a model, so+ # it arrives in whatever shape the conversation had it. Live 2026-08-20,+ # three turns in a row died on ``Unknown skill: Morning Routine`` while+ # ``morning-routine`` sat installed and active. ``get`` stays exact for+ # callers that hold a real key.+ registry = skill_ctx.registry+ resolver = getattr(registry, "resolve", None)try:- skill = skill_ctx.registry.get(skill_name)+ skill = (+ resolver(skill_name) if callable(resolver) else registry.get(skill_name)+ )except KeyError:+ # Name the alternatives instead of a bare dead end: the model can+ # correct itself inside the same turn, and the user hears an answer+ # rather than "I could not find that skill".return ToolResult(success=False,output=None,- error=f"Unknown skill: {skill_name}",+ error=(+ f"Unknown skill: {skill_name}. "+ f"Installed skills: {self._installed_names(registry)}"+ ),)+ # Everything downstream — the rendered output, the SkillInvoked event,+ # the DRAFT/DISABLED refusals — must speak about the skill that was+ # actually found, never the guess that led here.+ skill_name = str(getattr(skill, "name", skill_name) or skill_name)# Step 4 — AP-1/AP-15 enforcement: refuse DRAFT/DISABLED skillsif skill.state == SkillLifecycleState.DRAFT:@@ -225,6 +244,19 @@ class RunSkillTool:# Helpers# ------------------------------------------------------------------+ @staticmethod+ def _installed_names(registry: Any, *, limit: int = 40) -> str:+ """Comma-joined names of the invocable skills, for a recovery hint."""+ try:+ names = sorted(str(s.name) for s in registry.list_active())+ except Exception: # noqa: BLE001 — a hint must never mask the real error+ return "(unavailable)"+ if not names:+ return "(none installed)"+ if len(names) > limit:+ return ", ".join(names[:limit]) + f", … and {len(names) - limit} more"+ return ", ".join(names)+def _read_resource(self, skill: Any, resource_rel: str) -> ToolResult:"""Serve a bundled skill file (L3). Fails closed on traversal."""registered: set[str] = set()diff --git a/jarvis/realtime/tools.py b/jarvis/realtime/tools.pyindex 1b4a270a2f..179b2e7c4d 100644--- a/jarvis/realtime/tools.py+++ b/jarvis/realtime/tools.py@@ -201,6 +201,26 @@ def _is_music_plugin(name: str) -> bool:return name in MUSIC_PLUGIN_IDS+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.+ """+ try:+ from jarvis.skills.relevance import get_index+ from jarvis.skills.skill_context import try_get_skill_context++ context = try_get_skill_context()+ if context is None:+ return None+ return get_index(context.registry)+ except Exception: # noqa: BLE001 — planning keeps its static fallbacks+ return None++def _turn_shape_refusal(descriptor: SupervisorToolDescriptor,name: str,@@ -277,7 +297,16 @@ def _turn_shape_refusal("or ask what they want done.")try:- has_world_reason = bool(plan_turn(text).reasons)+ # 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+ )except Exception: # noqa: BLE001 — the planner must not brick a tool callhas_world_reason = Trueif has_world_reason:diff --git a/jarvis/skills/creator_service.py b/jarvis/skills/creator_service.pyindex 99be875411..deed55228b 100644--- a/jarvis/skills/creator_service.py+++ b/jarvis/skills/creator_service.py@@ -573,19 +573,32 @@ class SkillCreatorService:draft — the deterministic skeleton is never committed from here (seethe module docstring). Raises :class:`SkillAuthoringError` when thewriter refuses (bad name, dead body, disk error). A name collision is- resolved by suffixing " 2", " 3", … — the user asked for the skill and+ resolved by suffixing "-2", "-3", … — the user asked for the skill andgets it, under a name the answer reports.++ The committed name is SLUGGED. ``name`` is the registry key, and the+ authoring prompt asks the model for a Title Case display name, so this+ path used to write keys like ``Morning Routine 2`` into a registry+ whose builtins are keyed ``morning-routine``. Two naming conventions in+ one key space is what made ``run-skill`` unable to find a skill by any+ name a human would say (live 2026-08-20). One convention, everywhere."""result = await self._draft_or_refine(inp)if not result.brain_used:raise SkillCreatorUnavailable("no brain could author the skill right now — nothing was written")+ from jarvis.skills.authoring.service import slugify+draft = dict(result.draft)- base_name = str(draft.get("name", "")).strip()+ raw_name = str(draft.get("name", "")).strip()+ # Fall back to the raw name only when it has no slugable characters at+ # all (a name in a non-Latin script); the writer then rejects it with a+ # clear message instead of this method inventing one.+ base_name = slugify(raw_name) or raw_namelast_error: SkillAuthoringError | None = Nonefor attempt in range(1, 6):- draft["name"] = base_name if attempt == 1 else f"{base_name} {attempt}"+ draft["name"] = base_name if attempt == 1 else f"{base_name}-{attempt}"try:skill = await self.commit(draft)except SkillAuthoringError as exc:@@ -593,8 +606,6 @@ class SkillCreatorService:raiselast_error = exccontinue- from jarvis.skills.authoring.service import slugify-return AuthoredSkill(skill=skill,result=SkillCreatorResult(diff --git a/jarvis/skills/prompt_injection.py b/jarvis/skills/prompt_injection.pyindex 0756efc314..742dfefae0 100644--- a/jarvis/skills/prompt_injection.py+++ b/jarvis/skills/prompt_injection.py@@ -192,3 +192,77 @@ def render_available_skills_section("full description — never `run-skill`, and never a worker.")return f"{header}\n{intro}\n{body}{outro}"+++#: Per-entry description budget for the realtime roster. The block is re-sent+#: with every per-turn session update, so it buys names first and prose second.+_REALTIME_DESC_CHARS = 70+++def render_realtime_skills_directive(+ registry: SkillRegistry,+ *,+ compact: bool = False,+ budget_chars: int = 4000,+) -> str:+ """Render the installed-skill roster for a live voice session.++ The realtime engine was skill-blind in a way no listing test caught: the+ session instructions carried the ``run-skill`` tool but never one skill+ NAME, so the model had to invent the argument from the user's words. It+ invented "Morning Routine"; the registry key was ``morning-routine``; the+ turn died on ``Unknown skill`` (live 2026-08-20). Same shape as the+ workspace roster next to it — the model cannot route a name it has never+ heard of — and it binds every realtime transport alike, because they all+ share one instruction builder.++ Names outrank prose here. When the roster does not fit ``budget_chars``+ the descriptions are dropped and every name is kept, never the other way+ round: a described skill that is missing from the list is uncallable,+ while a bare name is still enough for ``run-skill`` to resolve. ``compact``+ (small self-hosted brains) goes straight to the names-only form.++ Returns ``""`` when no skill is invocable, so the caller can drop the+ block from the instruction assembly entirely.+ """+ try:+ active = registry.list_active()+ except Exception: # noqa: BLE001 — a roster fault must never break a call+ return ""+ entries: list[tuple[str, str, bool]] = [] # (name, description, is_builtin)+ for skill in active:+ fm = getattr(skill, "frontmatter", None)+ if fm is None:+ continue+ name = str(skill.name)+ if not name:+ continue+ desc = " ".join((getattr(fm, "description", "") or "").split())+ if len(desc) > _REALTIME_DESC_CHARS:+ desc = desc[: _REALTIME_DESC_CHARS - 1].rstrip() + "…"+ entries.append((name, desc, _is_builtin(skill)))+ if not entries:+ return ""++ # User-authored skills first — same attention argument as the brain listing.+ entries.sort(key=lambda e: (e[2], e[0]))+ names_only = ", ".join(name for name, _, _ in entries)++ header = "[Installed skills — the user's saved way of doing these tasks]\n"+ rule = (+ "\nTo run one, call the run-skill tool with the name EXACTLY as spelled "+ "above — copy it character for character, never re-word it and never "+ "invent one that is not listed. If the user names a skill that is not "+ "on this list, say so instead of guessing. A matching skill always "+ "beats answering from scratch. A plain question that merely mentions "+ "the topic is not a match."+ )+ if not compact:+ listed = "\n".join(+ f"- {name} — {desc}" if desc else f"- {name}"+ for name, desc, _ in entries+ )+ block = f"{header}{listed}{rule}"+ if len(block) <= budget_chars:+ return block+ return f"{header}{names_only}{rule}"diff --git a/jarvis/skills/registry.py b/jarvis/skills/registry.pyindex 9c0407b7a2..fe3d7a565e 100644--- a/jarvis/skills/registry.py+++ b/jarvis/skills/registry.py@@ -62,6 +62,10 @@ def _rewrite_state_in_frontmatter(text: str, new_state: str) -> str:log = logging.getLogger(__name__)+#: Namespace prefixes a speaker or a model naturally drops ("the gmail skill").+#: Mirrors ``jarvis.skills.explicit_request._DROPPABLE_NAME_PREFIXES``.+_DROPPABLE_NAME_PREFIXES = frozenset({"plugin", "cli"})+class SkillRegistry:"""Holds all known skills + provides lookup by name/trigger type.@@ -117,6 +121,75 @@ class SkillRegistry:raise KeyError(f"Skill '{name}' not in registry")return self._skills[name]+ def resolve(self, name: str) -> Skill:+ """Look up a skill by a name that came from a model or a human.++ ``get`` stays an exact-key read: a caller holding a real registry key+ must never silently land on a neighbour. This is the lookup for the+ other case, where the exact key is precisely what is missing. The+ realtime model asked for ``Morning Routine`` while the key was+ ``morning-routine`` and the resulting ``Unknown skill`` ended three+ live turns in a row (2026-08-20) — the skill was installed, active and+ matched every trigger it had.++ First hit wins:++ 1. the exact registry key;+ 2. the directory slug, which is what the CLI and the UI display;+ 3. the normalized token tuple — case, spacing, hyphens, underscores+ and umlauts all fold away;+ 4. the same tuple with a ``plugin-`` / ``cli-`` namespace prefix+ dropped, because nobody asks for "the plugin-gmail skill".++ Steps 2 to 4 iterate in sorted name order, so an ambiguous name always+ resolves to the same skill instead of depending on dict order. Raises+ ``KeyError`` when nothing matches.+ """+ key = str(name or "").strip()+ if not key:+ raise KeyError("Skill name must not be empty")+ with self._thread_lock:+ snapshot = dict(self._skills)+ if key in snapshot:+ return snapshot[key]++ ordered = sorted(snapshot.values(), key=lambda s: str(s.name))++ def _slug_of(skill: Skill) -> str:+ try:+ return str(skill.path.parent.name)+ except Exception: # noqa: BLE001 — a pathless test double is fine+ return ""++ for skill in ordered:+ if _slug_of(skill) == key:+ return skill++ from .relevance import skill_name_tokens++ wanted = skill_name_tokens(key)+ if not wanted:+ raise KeyError(f"Skill '{name}' not in registry")++ def _forms(skill: Skill) -> list[tuple[str, ...]]:+ """Token tuples this skill answers to, widest last."""+ out: list[tuple[str, ...]] = []+ for raw in (str(skill.name), _slug_of(skill)):+ tokens = skill_name_tokens(raw) if raw else ()+ if not tokens or tokens in out:+ continue+ out.append(tokens)+ if len(tokens) > 1 and tokens[0] in _DROPPABLE_NAME_PREFIXES:+ shortened = tokens[1:]+ if shortened not in out:+ out.append(shortened)+ return out++ for skill in ordered:+ if wanted in _forms(skill):+ return skill+ raise KeyError(f"Skill '{name}' not in registry")+def list(self) -> list[Skill]:return list(self._skills.values())diff --git a/jarvis/skills/relevance.py b/jarvis/skills/relevance.pyindex f96ad5effa..fbc31e9740 100644--- a/jarvis/skills/relevance.py+++ b/jarvis/skills/relevance.py@@ -240,6 +240,21 @@ 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]+")+++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+ 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.+ """+ return tuple(_NAME_TOKEN_RE.findall(normalize_text(name)))++_STOPWORDS: frozenset[str] | None = Nonediff --git a/tests/unit/brain/test_run_skill_tool.py b/tests/unit/brain/test_run_skill_tool.pyindex 1e83122c3f..ac549c9834 100644--- a/tests/unit/brain/test_run_skill_tool.py+++ b/tests/unit/brain/test_run_skill_tool.py@@ -367,3 +367,90 @@ async def test_unregistered_resource_rejected(tmp_path: Path) -> None:assert result.success is Falseassert "resource" in (result.error or "").lower()+++# ----------------------------------------------------------------------+# Speech-tolerant name resolution (live regression 2026-08-20)+# ----------------------------------------------------------------------+++class _ResolvingRegistry(_FakeRegistry):+ """A registry with the real ``resolve`` + ``list_active`` surface.++ ``_FakeRegistry`` above predates ``resolve`` on purpose — it proves the+ tool still works against a registry that has only ``get`` (mock and+ headless boots). This one carries the real thing.+ """++ def resolve(self, name: str) -> Skill:+ from jarvis.skills.relevance import skill_name_tokens++ key = str(name or "").strip()+ if key in self._skills:+ return self._skills[key]+ wanted = skill_name_tokens(key)+ if wanted:+ for candidate in sorted(self._skills.values(), key=lambda s: s.name):+ if skill_name_tokens(str(candidate.name)) == wanted:+ return candidate+ raise KeyError(f"Skill '{name}' not in registry")++ def list_active(self) -> list[Skill]:+ return list(self._skills.values())+++async def test_run_skill_resolves_a_display_name_to_the_installed_slug() -> None:+ """The live failure, verbatim: the realtime model sent "Morning Routine"+ while the registry key was "morning-routine", and the user was told the+ skill did not exist three turns running."""+ skill = _make_skill(name="morning-routine")+ registry = _ResolvingRegistry({"morning-routine": skill})+ runner = _FakeRunner()+ set_skill_context(SkillContext(registry=registry, runner=runner)) # type: ignore[arg-type]++ result = await RunSkillTool().execute({"skill_name": "Morning Routine"}, _ctx())++ assert result.success is True+ assert result.output["skill_name"] == "morning-routine"+++async def test_run_skill_reports_the_resolved_name_not_the_guess() -> None:+ """Everything downstream — the spoken answer, the SkillInvoked event —+ must name the skill that ran, never the string that led to it."""+ skill = _make_skill(name="morning-routine")+ registry = _ResolvingRegistry({"morning-routine": skill})+ set_skill_context(SkillContext(registry=registry, runner=_FakeRunner())) # type: ignore[arg-type]++ result = await RunSkillTool().execute({"skill_name": "MORNING ROUTINE"}, _ctx())++ assert result.output["skill_name"] == "morning-routine"+++async def test_run_skill_unknown_name_lists_what_is_installed() -> None:+ """A bare dead end ends the turn; naming the alternatives lets the model+ correct itself before the user hears anything."""+ registry = _ResolvingRegistry({"morning-routine": _make_skill(name="morning-routine")})+ set_skill_context(SkillContext(registry=registry, runner=_FakeRunner())) # type: ignore[arg-type]++ result = await RunSkillTool().execute({"skill_name": "brew coffee"}, _ctx())++ assert result.success is False+ assert "Unknown skill: brew coffee" in result.error+ assert "morning-routine" in result.error+++async def test_run_skill_still_works_on_a_registry_without_resolve() -> None:+ """Mock and headless boots ship a reduced registry; the tool must not+ require the newer method to function."""+ skill = _make_skill(name="demo_skill")+ set_skill_context(+ SkillContext(registry=_FakeRegistry({"demo_skill": skill}), runner=_FakeRunner()) # type: ignore[arg-type]+ )++ result = await RunSkillTool().execute({"skill_name": "demo_skill"}, _ctx())++ assert result.success is Truediff --git a/tests/unit/brain/test_turn_planner_skill_ambiguity.py b/tests/unit/brain/test_turn_planner_skill_ambiguity.pynew file mode 100644index 0000000000..bb8398c115--- /dev/null+++ b/tests/unit/brain/test_turn_planner_skill_ambiguity.py@@ -0,0 +1,119 @@+"""A tie between two installed skills is still a skill turn.++Live forensic 2026-08-20. The user asked Jarvis to build a morning routine by+voice; the creator wrote one that overlapped the shipped ``morning-routine``.+From that moment both scored FIRE band on "Morgenroutine", the index reported+no clear winner, and the planner — which required one — stopped adding+``TurnReason.SKILL`` at all. Installing a second skill silently disabled+routing for the first.++The planner was answering "which skill?" when it had only been asked "is this+about a skill?". A tie is certainty about the first question and uncertainty+about the second, so the reason stands and only the ``skill:<name>`` pin drops.+"""+from __future__ import annotations++from dataclasses import dataclass++from jarvis.brain.turn_planner import TurnReason, plan_turn+++@dataclass(frozen=True)+class _Candidate:+ name: str+ score: float+++@dataclass(frozen=True)+class _Ranking:+ top: _Candidate | None+ fire_threshold: float+ clear_winner: bool+++class _FakeIndex:+ """Stand-in for ``SkillMatchIndex`` — only ``rank()`` is read."""++ def __init__(self, ranking: _Ranking) -> None:+ self._ranking = ranking+ self.calls: list[str] = []++ def rank(self, text: str, limit: int = 1) -> _Ranking:+ self.calls.append(text)+ return self._ranking+++_TIED = _Ranking(+ top=_Candidate(name="morning-routine", score=1.70),+ fire_threshold=1.18,+ clear_winner=False,+)+_CLEAR = _Ranking(+ top=_Candidate(name="morning-routine", score=1.83),+ fire_threshold=1.17,+ clear_winner=True,+)+_BELOW = _Ranking(+ top=_Candidate(name="morning-routine", score=0.40),+ fire_threshold=1.17,+ clear_winner=True,+)+++def _pins(plan: object) -> list[str]:+ caps = getattr(plan, "required_capabilities", ())+ return [c for c in caps if str(c).startswith("skill:")]+++def test_a_tie_between_two_skills_is_still_a_skill_turn() -> None:+ plan = plan_turn("Morgenroutine", skill_index=_FakeIndex(_TIED)) # i18n-allow: test input++ assert TurnReason.SKILL in plan.reasons+ assert plan.requires_orchestrator is True+++def test_a_tie_does_not_pin_a_specific_skill() -> None:+ """Ambiguity travels to the orchestrator, which can disambiguate. The+ planner must not pick a winner it does not have."""+ plan = plan_turn("Morgenroutine", skill_index=_FakeIndex(_TIED)) # i18n-allow: test input++ assert _pins(plan) == []+++def test_a_clear_winner_still_pins_its_skill() -> None:+ plan = plan_turn("Morgenroutine", skill_index=_FakeIndex(_CLEAR)) # i18n-allow: test input++ assert TurnReason.SKILL in plan.reasons+ assert _pins(plan) == ["skill:morning-routine"]+++def test_a_below_threshold_candidate_is_not_a_skill_turn() -> None:+ """The FIRE floor still decides. A NARROW candidate is a suggestion for+ the orchestrator's prompt, never a reason to route."""+ plan = plan_turn("wie geht es dir", skill_index=_FakeIndex(_BELOW)) # i18n-allow: test input++ assert TurnReason.SKILL not in plan.reasons+++def test_a_definitional_question_never_routes_to_a_skill() -> None:+ """"Was ist eine Morgenroutine?" is a question about the words, not an+ order to run the skill — the definition guard outranks any band."""+ plan = plan_turn(+ "Was ist eine Morgenroutine?", # i18n-allow: test input+ skill_index=_FakeIndex(_TIED),+ )++ assert TurnReason.SKILL not in plan.reasons+++def test_a_broken_index_falls_back_to_the_static_vocabulary() -> None:+ """A scorer fault must leave the planner exactly as it was before the+ index existed — never raise into a live turn."""++ class _Exploding:+ def rank(self, text: str, limit: int = 1): # noqa: ANN202+ raise RuntimeError("index is corrupt")++ plan = plan_turn("Morgenroutine", skill_index=_Exploding()) # i18n-allow: test input++ assert TurnReason.SKILL not in plan.reasonsdiff --git a/tests/unit/brain/test_turn_planner_skill_index.py b/tests/unit/brain/test_turn_planner_skill_index.pyindex f8dfad27d2..b5e4b7fc12 100644--- a/tests/unit/brain/test_turn_planner_skill_index.py+++ b/tests/unit/brain/test_turn_planner_skill_index.py@@ -125,8 +125,20 @@ def test_only_a_fire_band_hit_counts() -> None:assert TurnReason.SKILL not in plan.reasons-def test_an_ambiguous_winner_does_not_count() -> None:- """Two near-tied skills are ambiguity, not a decision."""+def test_an_ambiguous_winner_does_not_pin_a_skill() -> None:+ """Two near-tied skills are ambiguity about WHICH, not about WHETHER.++ This assertion used to read ``TurnReason.SKILL not in plan.reasons`` — a+ tie removed the reason altogether. That answered "is this about a skill?"+ with the answer to "which skill?", and it cost a live feature: a+ voice-authored near-duplicate of the bundled morning routine put both at+ FIRE band, so every "Morgenroutine" turn lost its skill reason and routed+ native. Installing a second skill disabled the first (BUG-158).++ The tie still costs the pin — the planner must not name a winner it does+ not have — but the turn goes to the orchestrator, which has the trigger+ channel and the user to disambiguate with.+ """class _TiedIndex:def rank(self, text: str, *, limit: int = 5) -> RelevanceRanking:@@ -141,7 +153,10 @@ def test_an_ambiguous_winner_does_not_count() -> None:)plan = plan_turn("schick eine nachricht", skill_index=_TiedIndex()) # i18n-allow- assert TurnReason.SKILL not in plan.reasons++ assert TurnReason.SKILL in plan.reasons+ assert plan.requires_orchestrator is True+ assert not [c for c in plan.required_capabilities if str(c).startswith("skill:")]# ---------------------------------------------------------------------------diff --git a/tests/unit/realtime/test_session_skills_roster.py b/tests/unit/realtime/test_session_skills_roster.pynew file mode 100644index 0000000000..3ccad511b2--- /dev/null+++ b/tests/unit/realtime/test_session_skills_roster.py@@ -0,0 +1,215 @@+"""The live session must know the names of the skills it can run.++Live forensic 2026-08-20, three turns in one call:++* "Morgenroutine" — the guard refused ``run-skill`` outright;+* "Morning-Routine" — the model answered "Morning Routine ist gestartet" with+ an empty tool-call list, so nothing ran and the user was told it had;+* "Okay, kannst du bitte mal ein Skill Morning Routine starten?" —+ ``run-skill`` ran and returned ``Unknown skill: Morning Routine``.++The realtime instructions were 17 488 characters long and contained the word+"skill" exactly zero times. The model held the tool and no catalogue, so the+argument was always a guess. The brain path had carried an ``AVAILABLE SKILLS``+section for months and a test to prove it; the realtime path had neither, and+every realtime transport shares this one instruction builder.++These tests are the drift guard for the roster reaching the prompt. Where the+skill is INJECTED once matched lives in ``test_session_skill_directive.py``.+"""+from __future__ import annotations++from pathlib import Path+from typing import Any++import pytest++from jarvis.realtime import session as session_module+from jarvis.skills import relevance+from jarvis.skills.registry import SkillRegistry+from jarvis.skills.skill_context import SkillContext, set_skill_context+++class _StubRunner:+ def render_instructions(self, skill: Any, *, args: dict | None = None) -> str:+ return "body"+++class _Session:+ """Only the collaborators the roster methods touch."""++ def __init__(self, *, compact: bool = False, brain: Any = None) -> None:+ self._bus = None+ self._brain = brain+ self._compact_instructions = compact+ self._skill_inlined_for: tuple[str, str] | None = None+ self.session_id = "roster-test"++ _skills_directive = session_module.RealtimeVoiceSession._skills_directive+ _note_skill_for_delegate = (+ session_module.RealtimeVoiceSession._note_skill_for_delegate+ )+++def _write_skill(root: Path, name: str, *, description: str = "test skill") -> None:+ folder = root / name+ folder.mkdir(parents=True, exist_ok=True)+ (folder / "SKILL.md").write_text(+ "\n".join(+ [+ "---",+ 'schema_version: "1"',+ f"name: {name}",+ f"description: {description}",+ "---",+ "",+ "## Body",+ "",+ ]+ ),+ encoding="utf-8",+ )++[email protected](autouse=True)+def _clean():+ relevance.clear_index_cache()+ set_skill_context(None)+ yield+ set_skill_context(None)+ relevance.clear_index_cache()+++def skills_root(tmp_path: Path) -> Path:+ root = tmp_path / "skills"+ root.mkdir()+ _write_skill(root, "morning-routine", description="Your day at a glance.")+ _write_skill(root, "deep-work-mode", description="A focus sprint.")+ return root+++def _install(root: Path) -> SkillRegistry:+ registry = SkillRegistry(root=root)+ registry.reload_sync()+ set_skill_context(SkillContext(registry=registry, runner=_StubRunner())) # type: ignore[arg-type]+ return registry+++# ---------------------------------------------------------------------------+# The roster reaches the instructions+# ---------------------------------------------------------------------------+++def test_the_session_instructions_name_every_installed_skill(+ skills_root: Path,+) -> None:+ """The regression that started all of this: a prompt with the tool and no+ names. If this ever reads False again, the model is guessing."""+ _install(skills_root)++ instructions = session_module._session_instructions(+ "de",+ provider="vertex-live",+ model="gemini-live-2.5-flash-native-audio",+ skills_directive=_Session()._skills_directive(),+ )++ assert "morning-routine" in instructions+ assert "deep-work-mode" in instructions+ assert "run-skill" in instructions+++def test_the_compact_profile_also_names_the_skills(skills_root: Path) -> None:+ """A small self-hosted brain gets a shorter roster, never no roster —+ provider parity is not optional (CLAUDE.md §3)."""+ _install(skills_root)++ instructions = session_module._session_instructions(+ "de",+ provider="local-realtime",+ model="qwen2.5:7b",+ skills_directive=_Session(compact=True)._skills_directive(compact=True),+ compact=True,+ )++ assert "morning-routine" in instructions+ assert "deep-work-mode" in instructions+++def test_no_skill_context_yields_no_roster_block() -> None:+ """Headless and mock boots have no registry; the prompt just loses the+ block rather than the call losing its instructions."""+ assert _Session()._skills_directive() == ""+++def test_a_registry_fault_never_breaks_the_instructions(skills_root: Path) -> None:+ """A roster fault costs a skill call. A raised exception costs the call."""++ class _Exploding:+ def list_active(self): # noqa: ANN202+ raise RuntimeError("registry is on fire")++ set_skill_context(SkillContext(registry=_Exploding(), runner=_StubRunner())) # type: ignore[arg-type]++ assert _Session()._skills_directive() == ""+++# ---------------------------------------------------------------------------+# A match that cannot be inlined still reaches the brain+# ---------------------------------------------------------------------------+++class _RecordingBrain:+ def __init__(self) -> None:+ self.noted: list[tuple[str, str]] = []++ def note_skill_trigger(+ self, skill_name: str, *, content: str = "", source: str = "trigger"+ ) -> None:+ self.noted.append((skill_name, source))+++def test_a_matched_skill_is_handed_to_the_delegated_brain_turn(+ skills_root: Path,+) -> None:+ """Both installed morning routines failed every inline condition — one over+ the body cap, one tool-backed — and the old code answered that with "".+ A FIRE match must reach the brain instead of vanishing."""+ _install(skills_root)+ brain = _RecordingBrain()++ _Session(brain=brain)._note_skill_for_delegate("morning-routine")++ assert brain.noted == [("morning-routine", "realtime_match")]+++def test_an_already_inlined_skill_is_not_handed_over_twice(+ skills_root: Path,+) -> None:+ """One instruction set per turn — two competing ones guarantee an+ incoherent reply."""+ _install(skills_root)+ brain = _RecordingBrain()+ session = _Session(brain=brain)+ session._skill_inlined_for = ("morning-routine", "morning-routine")++ session._note_skill_for_delegate("morning-routine")++ assert brain.noted == []+++def test_an_unmatched_turn_hands_over_nothing(skills_root: Path) -> None:+ _install(skills_root)+ brain = _RecordingBrain()++ _Session(brain=brain)._note_skill_for_delegate("what is the capital of Peru")++ assert brain.noted == []+++def test_a_brain_without_the_hook_is_tolerated(skills_root: Path) -> None:+ """Echo and mock brains have no ``note_skill_trigger``; the turn still runs."""+ _install(skills_root)++ _Session(brain=object())._note_skill_for_delegate("morning-routine")diff --git a/tests/unit/skills/test_creator_service.py b/tests/unit/skills/test_creator_service.pyindex 3640a20f57..588b58ffb5 100644--- a/tests/unit/skills/test_creator_service.py+++ b/tests/unit/skills/test_creator_service.py@@ -376,7 +376,10 @@ 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- assert authored.name == "Morgenroutine"+ # 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"assert authored.slug == "morgenroutine"assert authored.skill.state == SkillLifecycleState.DRAFT # AP-15on_disk = (skills_root / "morgenroutine" / "SKILL.md").read_text(encoding="utf-8")@@ -404,6 +407,9 @@ 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"- assert second.name == "Morgenroutine 2"+ 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 (skills_root / "morgenroutine-2" / "SKILL.md").exists()+ assert second.slug == "morgenroutine-2"diff --git a/tests/unit/skills/test_prompt_injection.py b/tests/unit/skills/test_prompt_injection.pyindex 62ace9b22e..6ce8d8950d 100644--- a/tests/unit/skills/test_prompt_injection.py+++ b/tests/unit/skills/test_prompt_injection.py@@ -12,7 +12,10 @@ from __future__ import annotationsfrom dataclasses import dataclass-from jarvis.skills.prompt_injection import render_available_skills_section+from jarvis.skills.prompt_injection import (+ render_available_skills_section,+ render_realtime_skills_directive,+)@dataclass@@ -381,3 +384,83 @@ def test_budget_eviction_prefers_builtins_over_user_skills() -> None:assert "- `morning-routine` — " not in outtail = next(ln for ln in out.splitlines() if ln.startswith("- …"))assert "`morning-routine`" in tail+++# ----------------------------------------------------------------------+# Realtime roster (2026-08-20 skill-blindness fix)+# ----------------------------------------------------------------------+++def test_realtime_directive_names_every_installed_skill() -> None:+ """The roster's whole job: the live model can NAME what is installed.++ The realtime instructions carried the ``run-skill`` tool and not one skill+ name, so the model invented the argument from the user's words — "Morning+ Routine" against a registry keyed ``morning-routine`` — and the turn died+ on ``Unknown skill`` three times in a row.+ """+ registry = _FakeRegistry(skills=[+ _FakeSkill(name="morning-routine", frontmatter=_FakeFrontmatter(+ description="Day overview: mail, calendar, weather.")),+ _FakeSkill(name="deep-work-mode", frontmatter=_FakeFrontmatter(+ description="DND, mute Slack, start pomodoro.")),+ ])++ out = render_realtime_skills_directive(registry) # type: ignore[arg-type]++ assert "morning-routine" in out+ assert "deep-work-mode" in out+ assert "run-skill" in out+ assert registry.calls == ["list_active"]+++def test_realtime_directive_is_empty_without_skills() -> None:+ """No invocable skill → no block, so the caller drops it from the prompt."""+ assert render_realtime_skills_directive(_FakeRegistry(skills=[])) == "" # type: ignore[arg-type]+++def test_realtime_directive_drops_descriptions_before_names() -> None:+ """Over budget, every NAME survives and the prose goes.++ A described skill missing from the roster is uncallable; a bare name still+ resolves. So the budget may never be paid for with a name.+ """+ skills = [+ _FakeSkill(name=f"skill-{i:03d}", frontmatter=_FakeFrontmatter(+ description="A deliberately long description " * 6))+ for i in range(40)+ ]+ out = render_realtime_skills_directive(+ _FakeRegistry(skills=skills), budget_chars=1200, # type: ignore[arg-type]+ )++ for i in range(40):+ assert f"skill-{i:03d}" in out+ assert "A deliberately long description" not in out+++def test_realtime_directive_compact_profile_is_names_only() -> None:+ """Small self-hosted brains get the names without paying for the prose."""+ registry = _FakeRegistry(skills=[+ _FakeSkill(name="morning-routine", frontmatter=_FakeFrontmatter(+ description="Day overview: mail, calendar, weather.")),+ ])++ out = render_realtime_skills_directive(registry, compact=True) # type: ignore[arg-type]++ assert "morning-routine" in out+ assert "Day overview" not in out+++def test_realtime_directive_skips_skills_without_frontmatter() -> None:+ """A broken entry is skipped, never crashes the instruction build."""+ registry = _FakeRegistry(skills=[+ _FakeSkill(name="broken", frontmatter=None),+ _FakeSkill(name="morning-routine", frontmatter=_FakeFrontmatter(+ description="Day overview.")),+ ])++ out = render_realtime_skills_directive(registry) # type: ignore[arg-type]++ assert "morning-routine" in out+ assert "broken" not in outdiff --git a/tests/unit/skills/test_registry_resolve.py b/tests/unit/skills/test_registry_resolve.pynew file mode 100644index 0000000000..3b856afd29--- /dev/null+++ b/tests/unit/skills/test_registry_resolve.py@@ -0,0 +1,119 @@+"""Speech-tolerant skill lookup — ``SkillRegistry.resolve``.++Live forensic 2026-08-20: the realtime model called ``run-skill`` with+``skill_name="Morning Routine"`` while the registry key was+``morning-routine``. ``get`` is an exact dict read, so the tool answered+``Unknown skill`` and the user heard "I could not find that skill" on three+consecutive turns — for a skill that was installed, validated and matched+every trigger it declared.++Two naming conventions share one key space: builtins ship kebab-case slugs,+the skill creator writes Title Case display names. ``resolve`` is the bridge+for names that arrive from a model or a human; ``get`` stays exact for callers+that hold a real key.+"""+from __future__ import annotations++from pathlib import Path++import pytest++from jarvis.skills.registry import SkillRegistry++_SKILL = """\+---+schema_version: "1"+name: {name}+version: "1.0.0"+description: Test skill.+category: productivity+---++# {name}++Do the thing.+"""+++def _write(root: Path, slug: str, name: str) -> None:+ folder = root / slug+ folder.mkdir(parents=True, exist_ok=True)+ (folder / "SKILL.md").write_text(_SKILL.format(name=name), encoding="utf-8")+++def registry(tmp_path: Path) -> SkillRegistry:+ _write(tmp_path, "morning-routine", "morning-routine")+ _write(tmp_path, "plugin-gmail", "plugin-gmail")+ _write(tmp_path, "focus", "focus")+ reg = SkillRegistry(tmp_path)+ reg.reload_sync()+ return reg+++ "spoken",+ [+ "morning-routine", # the exact key+ "Morning Routine", # what the realtime model actually sent+ "morning routine",+ "MORNING_ROUTINE",+ " Morning-Routine ",+ ],+)+def test_resolve_finds_the_skill_however_the_name_is_written(+ registry: SkillRegistry, spoken: str+) -> None:+ assert registry.resolve(spoken).name == "morning-routine"+++def test_resolve_drops_a_namespace_prefix(registry: SkillRegistry) -> None:+ """Nobody asks for "the plugin-gmail skill"."""+ assert registry.resolve("Gmail").name == "plugin-gmail"+ assert registry.resolve("gmail").name == "plugin-gmail"+++def test_resolve_raises_for_an_unknown_name(registry: SkillRegistry) -> None:+ with pytest.raises(KeyError):+ registry.resolve("a skill that was never installed")+++def test_resolve_rejects_an_empty_name(registry: SkillRegistry) -> None:+ with pytest.raises(KeyError):+ registry.resolve(" ")+++def test_resolve_does_not_match_a_mere_prefix(registry: SkillRegistry) -> None:+ """"focus pro" must not land on the skill called "focus"."""+ with pytest.raises(KeyError):+ registry.resolve("focus pro")+++def test_get_stays_exact(registry: SkillRegistry) -> None:+ """``get`` must NOT gain the tolerance — a caller holding a real registry+ key has to fail loudly rather than land on a neighbouring skill."""+ assert registry.get("morning-routine").name == "morning-routine"+ with pytest.raises(KeyError):+ registry.get("Morning Routine")+++def test_resolve_finds_a_skill_by_its_directory_slug(tmp_path: Path) -> None:+ """The CLI and the UI show the folder name, so that has to resolve too."""+ _write(tmp_path, "morning-routine-2", "Morning Routine 2")+ reg = SkillRegistry(tmp_path)+ reg.reload_sync()++ assert reg.resolve("morning-routine-2").name == "Morning Routine 2"+ assert reg.resolve("Morning Routine 2").name == "Morning Routine 2"+++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")+ _write(tmp_path, "b-thing", "focus-mode")+ reg = SkillRegistry(tmp_path)+ reg.reload_sync()++ first = reg.resolve("focus mode").name+ assert all(reg.resolve("focus mode").name == first for _ in range(20))