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.

feat(skills): inline conditional instructions on a clear NARROW match

rubenluetke10-beep0ea42d4f0d18
diff --git a/jarvis/brain/manager.py b/jarvis/brain/manager.py
index 5d1225e36a..f6e1de9186 100644
--- a/jarvis/brain/manager.py
+++ b/jarvis/brain/manager.py
@@ -5265,15 +5265,37 @@ class BrainManager:
return tools
return {k: v for k, v in tools.items() if k != "run-skill"}
- def _render_skill_candidate_hint(self) -> str | None:
+ #: Cap on the conditionally-injected instruction text for a NARROW match.
+ #: Bounded so one pathological skill body cannot flood a voice turn.
+ _NARROW_INJECTION_CHAR_CAP = 6_000
+
+ def _render_skill_candidate_hint(self, user_text: str = "") -> 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
+ that all the listed skills look equally plausible while ~26k tokens of
+ tool schemas compete for attention. This block puts the candidates that
+ actually scored right next to the user's message, where recency is
worth more than position in a long cached list.
+ 2026-08-12 escalation ("skills never fire" rework): a name-and-blurb
+ hint measurably did nothing — 60 NARROW hints shipped over 14 live days
+ and the model called run-skill exactly zero times. The fast router
+ model does not convert a suggestion into a tool round trip. So for a
+ CLEAR top candidate that cannot dispatch anything, the hint now carries
+ the skill's full rendered instructions in a conditional frame — the
+ model only has to decide "is this what the user meant", not decide AND
+ remember to call a tool (mirrors Claude Code loading a skill's whole
+ instruction body once selected). The decision explicitly stays with
+ the model: a wrong candidate is ignored, never executed, so a skill is
+ still only ever used when it serves the request.
+
+ A dispatching-class candidate (mission execution, block tier, macro
+ body) NEVER gets its instructions inlined off an inferred match — its
+ body is a process-start directive, and no matcher may authorize that
+ (same line ``autofire_policy.may_capture`` draws). It keeps the plain
+ named hint, where the model must consciously call ``run-skill``.
+
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.
@@ -5301,9 +5323,10 @@ class BrainManager:
except Exception: # noqa: BLE001
return None
- lines: list[str] = []
+ # (candidate, skill, blurb) triples for every scoring candidate.
+ scored: list[tuple[Any, Any, str]] = []
for candidate in candidates:
- if len(lines) >= limit:
+ if len(scored) >= limit:
break
if getattr(candidate, "band", BAND_NONE) == BAND_NONE:
continue
@@ -5318,10 +5341,17 @@ class BrainManager:
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:
+ scored.append((candidate, skill, blurb))
+ if not scored:
return None
+ conditional = self._render_conditional_narrow_injection(
+ scored, ctx, user_text, decision
+ )
+ if conditional is not None:
+ return conditional
+
+ lines = [f"- `{getattr(s, 'name', '')}` — {b}" for _, s, b in scored]
return (
"[Skill candidates] The user's request scored against these "
"installed skills. If one genuinely fits, call the `run-skill` tool "
@@ -5330,6 +5360,76 @@ class BrainManager:
"ranked suggestions, not a verdict.\n" + "\n".join(lines)
)
+ def _render_conditional_narrow_injection(
+ self,
+ scored: list[tuple[Any, Any, str]],
+ ctx: Any,
+ user_text: str,
+ decision: Any,
+ ) -> str | None:
+ """Full instructions for a clear, non-dispatching top candidate.
+
+ Returns ``None`` whenever the escalation conditions do not hold, so the
+ caller falls back to the plain named hint. Never raises.
+ """
+ try:
+ from jarvis.skills.autofire_policy import CLASS_DISPATCHING, classify
+ from jarvis.skills.relevance import MARGIN_ABS
+
+ top_candidate, top_skill, top_blurb = scored[0]
+ if classify(top_skill) == CLASS_DISPATCHING:
+ return None
+ # Clear winner only: two near-tied candidates are genuine ambiguity
+ # and stay a short list the model disambiguates from.
+ margin = float(getattr(decision, "margin", 0.0) or 0.0)
+ if len(scored) > 1 and margin < MARGIN_ABS:
+ return None
+ instructions = ctx.runner.render_instructions(
+ top_skill,
+ args={
+ "content": "",
+ "utterance": user_text,
+ "_trigger": "relevance-hint",
+ },
+ )
+ except Exception: # noqa: BLE001
+ log.debug("conditional narrow injection failed", exc_info=True)
+ return None
+ if not instructions or not str(instructions).strip():
+ return None
+ text = str(instructions).strip()
+ if len(text) > self._NARROW_INJECTION_CHAR_CAP:
+ text = text[: self._NARROW_INJECTION_CHAR_CAP - 1] + "…"
+
+ name = getattr(top_skill, "name", "")
+ runner_up_lines = [
+ f"- `{getattr(s, 'name', '')}` — {b}" for _, s, b in scored[1:]
+ ]
+ tail = (
+ (
+ "\nLower-scored alternatives (ranked suggestions, not a "
+ "verdict):\n" + "\n".join(runner_up_lines) + "\n"
+ "If one of those fits the request better, call the `run-skill` "
+ "tool with that name instead."
+ )
+ if runner_up_lines
+ else ""
+ )
+ return (
+ f"[Likely skill match — decide, then act] The user's request "
+ f"scored closest to the installed skill `{name}` — {top_blurb}\n"
+ "Judge from the user's ACTUAL words: if they are asking for what "
+ "this skill does — even loosely, in wording that is not the "
+ "trigger phrase — follow the instructions below NOW with your "
+ "available tools instead of answering freely, and never read them "
+ "aloud. If the request is genuinely about something else, ignore "
+ "this entire block and answer normally; do not mention the skill. "
+ "A skill is only ever used when it truly serves the request.\n"
+ f"--- skill instructions (`{name}`) ---\n"
+ f"{text}\n"
+ f"--- end of skill instructions ---{tail}"
+ )
+
def _render_skill_turn_injection(self, user_text: str) -> str | None:
"""Render the matched skill's instructions for direct turn injection.
@@ -10197,7 +10297,7 @@ class BrainManager:
# 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()
+ _narrow_block = self._render_skill_candidate_hint(user_text)
if _narrow_block:
turn_context = (
f"{turn_context}\n\n{_narrow_block}"
diff --git a/tests/unit/brain/test_skill_relevance_routing.py b/tests/unit/brain/test_skill_relevance_routing.py
index d3c2cecfce..fb558245a4 100644
--- a/tests/unit/brain/test_skill_relevance_routing.py
+++ b/tests/unit/brain/test_skill_relevance_routing.py
@@ -405,8 +405,17 @@ def test_a_trigger_match_keeps_its_historical_rights(tmp_path: Path) -> None:
# ---------------------------------------------------------------------------
-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."""
+def test_narrow_does_not_capture_but_injects_conditional_instructions(
+ tmp_path: Path,
+) -> None:
+ """NARROW_UTTERANCE is measured to land in the NARROW band on this corpus.
+
+ 2026-08-12 escalation: a clear, non-dispatching top candidate carries its
+ FULL rendered instructions in a conditional frame — 60 name-only hints
+ shipped over 14 live days converted to zero run-skill calls, so the fast
+ router model needs the instructions in hand, not a tool round trip. The
+ decision (follow vs ignore) explicitly stays with the model.
+ """
_write_skill(tmp_path, "focus", tags=FOCUS_TAGS)
for filler in range(6):
_write_skill(tmp_path, f"filler-{filler}", description=f"topic{filler}")
@@ -419,11 +428,95 @@ def test_narrow_does_not_capture_but_does_narrow(tmp_path: Path) -> 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()
+ hint = manager._render_skill_candidate_hint(NARROW_UTTERANCE)
+ assert hint is not None
+ assert "focus" in hint
+ # The stub runner's rendered body rides inline, conditionally framed.
+ assert "Do the thing." in hint
+ assert "--- skill instructions" in hint
+ assert "ignore this entire block" in hint, (
+ "the model must know it may ignore this"
+ )
+ # No capture side effects: run-skill stays visible for this turn.
+ assert manager._skill_injected_inline is False
+
+
+def test_a_dispatching_candidate_gets_a_named_hint_never_instructions(
+ tmp_path: Path,
+) -> None:
+ """A mission skill's body is a process-start directive. Off an INFERRED
+ match it may be named, never inlined — the same line may_capture draws.
+ """
+ _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()
+ manager._skill_turn_match = manager._match_skill_for_turn(
+ "mach mal einen debugsprint"
+ )
+ assert manager._skill_turn_match is None
+
+ hint = manager._render_skill_candidate_hint("mach mal einen debugsprint")
+ assert hint is not None
+ assert "cloud-debug" in hint
+ assert "ranked suggestions" in hint
+ assert "--- skill instructions" not in hint
+ assert "Do the thing." not in hint
+
+
+def test_a_near_tie_gets_a_short_list_not_instructions(tmp_path: Path) -> None:
+ """Two near-tied candidates are genuine ambiguity — the model picks from a
+ short list; the harness must not inline either one's instructions.
+ """
+ _write_skill(tmp_path, "focus-a", tags=["konzentrationsmodus"])
+ _write_skill(tmp_path, "focus-b", tags=["konzentrationsmodus"])
+ 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_turn_match is None
+
+ hint = manager._render_skill_candidate_hint(NARROW_UTTERANCE)
+ assert hint is not None
+ assert "focus-a" in hint and "focus-b" in hint
+ assert "--- skill instructions" not in hint
+
+
+def test_a_render_failure_falls_back_to_the_named_hint(tmp_path: Path) -> None:
+ """A broken Jinja body must degrade to the old hint, never to silence."""
+
+ class _RaisingRunner:
+ def render_instructions(
+ self, skill: Any, *, args: dict | None = None
+ ) -> str:
+ raise RuntimeError("template exploded")
+
+ _write_skill(tmp_path, "focus", tags=FOCUS_TAGS)
+ for filler in range(6):
+ _write_skill(tmp_path, f"filler-{filler}", description=f"topic{filler}")
+ registry = SkillRegistry(root=tmp_path)
+ registry.reload_sync()
+ set_skill_context(SkillContext(registry=registry, runner=_RaisingRunner())) # type: ignore[arg-type]
+
+ manager = _make_manager()
+ manager._skill_turn_match = manager._match_skill_for_turn(NARROW_UTTERANCE)
+ assert manager._skill_turn_match is None
+
+ hint = manager._render_skill_candidate_hint(NARROW_UTTERANCE)
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"
+ assert "ranked suggestions" in hint
+ assert "--- skill instructions" not in hint
def test_the_hint_is_absent_on_a_captured_turn(tmp_path: Path) -> None: