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(brain): check the attached tools before refusing a request
Haraldf083a16bf48b
diff --git a/jarvis/brain/evidence_gate.py b/jarvis/brain/evidence_gate.pyindex 07a4d86a72..a8fa247a48 100644--- a/jarvis/brain/evidence_gate.py+++ b/jarvis/brain/evidence_gate.py@@ -15,13 +15,16 @@ Verdicts:from __future__ import annotations+import loggingimport re-from collections.abc import Callable, Mapping, Sequence+from collections.abc import Callable, Iterable, Mapping, Sequencefrom dataclasses import dataclassfrom typing import Any, Literalfrom jarvis.core.capabilities import _normalize+log = logging.getLogger(__name__)+# A domain keyword alone must not trigger (hard negative: "Ich habe dir das# per Mail geschickt" mentions mail in passing). The utterance must also look# like a question/lookup or a read-imperative on the domain.@@ -47,6 +50,117 @@ _OWNERSHIP_RE = re.compile()+# Everything that is not a letter or a digit separates two identifier tokens:+# "mcp__google_calendar__list-events" carries the tokens that matter.+_SEPARATOR_RE = re.compile(r"[^a-z0-9]+")++# Below this length a separator-free substring match is noise ("pr" would hit+# "switch_provider"), so short terms are matched as whole tokens only. Four is+# the lowest useful bar: it is what makes "mail" find the tool named "gmail".+_MIN_SQUASHED_TERM_LEN = 4++# Words that name the SAME system. Purely lexical — the user says "Termin",+# the tool is called "google_calendar"; the user says "E-Mail", the tool is+# called "gmail". Without this bridge a name-only match misses the most common+# real integrations, which is precisely the false refusal being fixed. Each+# group is one system: WhatsApp and Telegram stay apart, because handing a+# Telegram tool a WhatsApp request would be a wrong call, not a lenient one.+_SYSTEM_SYNONYMS: tuple[frozenset[str], ...] = (+ frozenset({+ "mail", "mails", "e-mail", "e-mails", "email", "emails", "gmail",+ "outlook", "postfach", "posteingang", "inbox", "mailbox",+ }),+ frozenset({+ "kalender", "calendar", "termin", "termine", "appointment",+ "appointments", "meeting", "meetings", "gcal",+ }),+ frozenset({+ "aufgabe", "aufgaben", "todo", "todos", "to-do", "task", "tasks",+ "reminder", "reminders", "todoist",+ }),+ frozenset({+ "repo", "repos", "repository", "repositories", "pull request",+ "pull requests", "issue", "issues", "github", "gitlab",+ }),+ frozenset({"spotify", "musik", "music"}),+ frozenset({"twitter", "x", "tweet", "tweets"}),+ frozenset({+ "pizza", "lieferando", "doordash", "uber eats", "ubereats", "wolt",+ "lieferservice",+ }),+ frozenset({+ "flug", "fluege", "flight", "flights", "hotel", "hotels", "airbnb",+ "booking", "trip", "trips", "reise", "reisen", "travel", "ticket",+ "tickets",+ }),+ frozenset({+ "tisch", "restaurant", "reservierung", "reservation", "opentable",+ "resy",+ }),+ frozenset({"deployment", "deployments", "deploy", "vercel", "netlify"}),+)++_SYNONYM_INDEX: dict[str, frozenset[str]] = {+ _normalize(word): group for group in _SYSTEM_SYNONYMS for word in group+}+++def live_surface_covers(terms: Iterable[str], tool_names: Iterable[str]) -> bool:+ """True when a tool ATTACHED TO THIS TURN plausibly serves ``terms``.++ Ground truth for every honest refusal (GT-16/GT-17). The refusals used to+ consult the capability registry alone, and that registry lags reality: a+ plugin, CLI or MCP server connected mid-session is callable immediately+ while the registry still knows nothing about it, so the user was told "I+ can't do that" with the tool sitting right there in the tool surface.++ The rule is deliberately shallow. A tool's REGISTERED NAME is its identity+ — "gmail", "google_calendar", "spotify", "mcp__todoist__add_task" — and a+ connected integration is named after the system it serves. A term matches+ when its tokens appear as a run inside the name, or, from+ ``_MIN_SQUASHED_TERM_LEN`` characters up, when the separator-free forms+ overlap, so "whats-app" still finds a tool called ``whatsapp``. Each term+ is first widened by ``_SYSTEM_SYNONYMS``, the lexical bridge between what+ the user says and what the tool is called.++ Descriptions are NOT searched: everyday words from the domain lists+ ("task", "post", "repository", "issue") appear in the prose of unrelated+ tools and would silently disable every refusal — trading one dishonest+ answer for another. This is not a second guessing layer: it decides only+ whether to SPEAK a refusal, never which tool to call. A false positive+ costs one ordinary model turn; a false negative is the bug being fixed.+ """+ haystacks: list[tuple[str, str]] = []+ for raw_name in tool_names:+ name = _normalize(str(raw_name or ""))+ spaced = _SEPARATOR_RE.sub(" ", name).strip()+ if spaced:+ haystacks.append((spaced, _SEPARATOR_RE.sub("", name)))+ if not haystacks:+ return False++ wanted: set[str] = set()+ for raw_term in terms:+ term = _normalize(str(raw_term or "")).strip()+ if not term:+ continue+ wanted.add(term)+ wanted.update(_SYNONYM_INDEX.get(term, ()))++ for term in wanted:+ spaced_term = _SEPARATOR_RE.sub(" ", term).strip()+ if not spaced_term:+ continue+ squashed_term = _SEPARATOR_RE.sub("", term)+ token_re = re.compile(r"\b" + re.escape(spaced_term) + r"\b")+ for name_spaced, name_squashed in haystacks:+ if token_re.search(name_spaced):+ return True+ if len(squashed_term) >= _MIN_SQUASHED_TERM_LEN and squashed_term in name_squashed:+ return True+ return False++@dataclass(frozen=True)class EvidenceVerdict:kind: Literal["pass", "require_tool", "honest_refusal"]@@ -105,8 +219,16 @@ def check_evidence_domain(capability_registry: Any,domain_tool_map: Mapping[str, str],refusal_hint_fn: Callable[[str, str], str] | None = None,+ live_tool_names: Sequence[str] = (),) -> EvidenceVerdict:- """Classify one utterance against the evidence-required domains."""+ """Classify one utterance against the evidence-required domains.++ ``live_tool_names`` are the names of the tools attached to THIS turn, read+ at decision time. They are the last word before a refusal is spoken: a+ matching tool on the live surface beats an empty registry (see+ :func:`live_surface_covers`). Defaulting to ``()`` keeps every existing+ caller on the registry-only behaviour.+ """if not enabled:return _PASSt = (text or "").strip()@@ -160,6 +282,20 @@ def check_evidence_domain(if matched_domain in objs or objs.intersection(domain_keywords):return _PASS+ # Last stop before the refusal (GT-16): the registry said "nothing covers+ # this domain", but the registry is a cache and the tool surface is the+ # truth. A plugin/CLI/MCP tool connected seconds ago is callable now and+ # unknown to the registry — refusing then is the exact bug the maintainer+ # reported. Stand down and let the model call the tool; if it turns out+ # dead, the tool's own result still fails honestly.+ if live_surface_covers([matched_domain, *domains[matched_domain]], live_tool_names):+ log.info(+ "Evidence gate stood down: domain=%s is covered by a tool on the "+ "live surface, so the honest refusal would have been wrong.",+ matched_domain,+ )+ return _PASS+lang = _detect_lang(t)base = (_REFUSAL_DE.get(matched_domain, _REFUSAL_DE_FALLBACK)@@ -179,4 +315,4 @@ def check_evidence_domain()-__all__ = ["EvidenceVerdict", "check_evidence_domain"]+__all__ = ["EvidenceVerdict", "check_evidence_domain", "live_surface_covers"]diff --git a/jarvis/brain/local_action_gate.py b/jarvis/brain/local_action_gate.pyindex 689ab8ea5f..c247180987 100644--- a/jarvis/brain/local_action_gate.py+++ b/jarvis/brain/local_action_gate.py@@ -8,6 +8,7 @@ runs the in-process screenshot/click/keyboard loopfrom __future__ import annotationsimport re+from collections.abc import Sequencefrom dataclasses import dataclass, fieldfrom enum import Enumfrom typing import Any, Literal, Protocol, runtime_checkable@@ -697,6 +698,41 @@ def requires_external_integration(text: str) -> bool:return False+def external_integration_terms(text: str) -> tuple[str, ...]:+ """Name the SPECIFIC external systems an utterance asks for.++ Companion to :func:`requires_external_integration`: that function answers+ *whether* a dedicated integration is needed, this one answers *which* one.+ The terms are what the live tool surface is checked against before any+ refusal is spoken (GT-16) — the registry may be stale, an attached tool+ named after the system is not.+ """+ t = text or ""+ terms = [m.group(0).lower() for m in _EXTERNAL_INTEGRATION_NOUN_RE.finditer(t)]+ if re.search(r"\b(?:auf|on)\s+x\b", t, re.I):+ # The Twitter/X rebrand hides the platform behind a single letter —+ # hand the matcher the names a connected tool would actually carry.+ terms.extend(("twitter", "x"))+ return tuple(dict.fromkeys(terms))+++def _live_surface_covers(terms: Sequence[str], tool_names: Sequence[str]) -> bool:+ """Thin wrapper around ``evidence_gate.live_surface_covers``.++ Late import for the same reason as :func:`_get_capability_registry` — this+ module stays importable without pulling in ``jarvis.core.capabilities``.+ A fault here must never turn into a refusal, so it degrades to "not+ covered" only when the helper itself is missing.+ """+ if not tool_names or not terms:+ return False+ try:+ from jarvis.brain.evidence_gate import live_surface_covers+ except ImportError: # pragma: no cover — module always ships with the gate+ return False+ return live_surface_covers(terms, tool_names)++def _get_capability_registry() -> _CapabilityRegistryLike | None:"""Return the global capability registry singleton, or *None* if Agent A'smodule has not been installed yet.@@ -717,6 +753,7 @@ def match_local_action(lang: Literal["de", "en"] = "de",*,_registry: _CapabilityRegistryLike | None = _SENTINEL, # type: ignore[assignment]+ live_tool_names: Sequence[str] = (),) -> LocalActionPlan | None:"""Return a deterministic local action plan for narrow local commands.@@ -732,6 +769,12 @@ def match_local_action(registry to exercise the UNSUPPORTED path without importing the real``jarvis.core.capabilities`` module. When omitted the productionsingleton is loaded via a late import.+ live_tool_names:+ Names of the tools attached to the CURRENT turn, read live by the+ caller. They veto the UNSUPPORTED refusal: a tool named after the+ requested system is proof the capability exists, whatever the registry+ believes (GT-16). Empty means "caller knows of no tools" and leaves+ the historical registry-only behaviour untouched."""original = text.strip()if not original:@@ -769,6 +812,15 @@ def match_local_action(# it must NOT be refused here — it falls through to the force-spawn# path (the sub-agent is the universal capability for generic work).and requires_external_integration(normalized)+ # GT-16: the registry is a cache, the attached tools are the truth.+ # A plugin/CLI/MCP server connected mid-session is callable long+ # before ``resolve_intent`` learns about it — refusing then is the+ # live complaint ("I'm told it's impossible while the capability is+ # right there"). A tool named after the requested system stands the+ # refusal down; the turn proceeds and the tool answers for itself.+ and not _live_surface_covers(+ external_integration_terms(normalized), live_tool_names+ )):return LocalActionPlan(mode=LocalActionMode.UNSUPPORTED,diff --git a/jarvis/brain/manager.py b/jarvis/brain/manager.pyindex 56b0787aeb..2529a93c42 100644--- a/jarvis/brain/manager.py+++ b/jarvis/brain/manager.py@@ -92,12 +92,14 @@ from .assistant_name import (resolve_assistant_name,)from .dispatcher import BrainDispatcher+from .evidence_gate import live_surface_coversfrom .intent_router import RoutingDecision, classifyfrom .local_action_gate import (HARNESS_NAME,LocalActionMode,LocalToolCall,_looks_like_desktop_control,+ external_integration_terms,is_open_app_intent,match_local_action,requires_external_integration,@@ -4519,6 +4521,21 @@ class BrainManager:self._jarvis_agent_status_fn = status_fnself._jarvis_agent_cancel_fn = cancel_fn+ def _live_tool_names(self) -> tuple[str, ...]:+ """Names of every tool attached RIGHT NOW — the honest-refusal evidence.++ Read fresh on every call and never cached: ``refresh_tools()`` replaces+ ``self._tools`` wholesale each time a CLI or MCP server connects, so a+ snapshot taken earlier in the turn would be exactly the stale picture+ the refusals are being fixed for (GT-16). ``_local_action_tools`` is+ included because the deterministic fast path can serve a request just+ as well as the brain surface can. The ``getattr`` guards tolerate+ __init__-bypassing tests, like the other readers of ``_tools``.+ """+ names = set(getattr(self, "_tools", None) or {})+ names.update(getattr(self, "_local_action_tools", None) or {})+ return tuple(sorted(names))+def _check_unsupported_intent(self, user_text: str) -> str | None:"""Agent-C capability gate: return a deterministic refusal when theutterance has an action intent that no registered capability covers.@@ -4575,6 +4592,22 @@ class BrainManager:if not requires_external_integration(t):return Noneif reg.has_action_intent(t) and reg.resolve_intent(t) is None:+ # GT-16: `resolve_intent` speaks for the registry, and the+ # registry lags the tool surface — a plugin/CLI/MCP server+ # connected mid-session is callable while the registry still+ # knows nothing. Ask the LIVE tools before speaking a refusal;+ # a tool named after the requested system means the capability+ # is there and the turn must proceed. A wrong tool call is+ # recoverable, a false "I can't do that" is the bug.+ wanted = external_integration_terms(t)+ if live_surface_covers(wanted, self._live_tool_names()):+ log.info(+ "Unsupported-intent refusal stood down: a tool on the "+ "live surface covers %s — proceeding instead of "+ "refusing (registry had not caught up).",+ ", ".join(wanted) or "the request",+ )+ return None# Detect user language from text heuristic (simple: if latin# chars + german umlaut present → DE, else EN)._de_markers = re.search(r"[äöüÄÖÜß]|(?:bitte|kannst|schick|trag|sende)", t, re.I)@@ -4660,6 +4693,11 @@ class BrainManager:capability_registry=get_registry(),domain_tool_map=domain_map,refusal_hint_fn=_hint,+ # Read HERE, at decision time (GT-16): refresh_tools() swaps+ # self._tools out wholesale on every CLI/MCP connect, so any+ # earlier snapshot is the stale picture that made the gate+ # refuse a domain it could actually serve.+ live_tool_names=self._live_tool_names(),)except Exception: # noqa: BLE001log.debug("evidence gate degraded to PASS", exc_info=True)@@ -7830,7 +7868,7 @@ class BrainManager:if self._tool_executor is None:return None- plan = match_local_action(user_text)+ plan = match_local_action(user_text, live_tool_names=self._live_tool_names())if plan is None:return None@@ -9913,7 +9951,9 @@ class BrainManager:# keeps its skill, and a non-app skill turn ("starte die Morgenroutine",# gate → None) is untouched.if self._skill_turn_match is not None:- _gate_plan = match_local_action(user_text)+ _gate_plan = match_local_action(+ user_text, live_tool_names=self._live_tool_names()+ )_claiming = _gate_plan is not None and _gate_plan.mode in (LocalActionMode.DIRECT,LocalActionMode.COMPUTER_USE,diff --git a/tests/unit/brain/test_computer_use_offload.py b/tests/unit/brain/test_computer_use_offload.pyindex c2639b7a03..44d7cfc6bc 100644--- a/tests/unit/brain/test_computer_use_offload.py+++ b/tests/unit/brain/test_computer_use_offload.py@@ -76,7 +76,9 @@ async def test_computer_use_acks_immediately_not_blocking_on_harness(monkeypatchplan = LocalActionPlan(mode=LocalActionMode.COMPUTER_USE, harness="computer-use", prompt="open chrome")- monkeypatch.setattr("jarvis.brain.manager.match_local_action", lambda _t: plan)+ monkeypatch.setattr(+ "jarvis.brain.manager.match_local_action", lambda _t, **_kw: plan+ )start = time.monotonic()reply = await mgr._run_local_action_fast_path("öffne chrome") # i18n-allow@@ -109,7 +111,9 @@ async def test_computer_use_result_announced_when_done(monkeypatch) -> None:plan = LocalActionPlan(mode=LocalActionMode.COMPUTER_USE, harness="computer-use", prompt="open chrome")- monkeypatch.setattr("jarvis.brain.manager.match_local_action", lambda _t: plan)+ monkeypatch.setattr(+ "jarvis.brain.manager.match_local_action", lambda _t, **_kw: plan+ )await mgr._run_local_action_fast_path("öffne chrome") # i18n-allowawait asyncio.gather(*getattr(mgr, "_cu_background_tasks", set()))@@ -135,7 +139,9 @@ async def test_computer_use_failure_is_announced_not_dropped(monkeypatch) -> Nonplan = LocalActionPlan(mode=LocalActionMode.COMPUTER_USE, harness="computer-use", prompt="open chrome")- monkeypatch.setattr("jarvis.brain.manager.match_local_action", lambda _t: plan)+ monkeypatch.setattr(+ "jarvis.brain.manager.match_local_action", lambda _t, **_kw: plan+ )await mgr._run_local_action_fast_path("öffne chrome") # i18n-allowawait asyncio.gather(*getattr(mgr, "_cu_background_tasks", set()))@@ -176,7 +182,9 @@ async def test_user_cancel_offload_is_silent_not_announced(monkeypatch) -> None:harness="computer-use",prompt="screenshot the repo",)- monkeypatch.setattr("jarvis.brain.manager.match_local_action", lambda _t: plan)+ monkeypatch.setattr(+ "jarvis.brain.manager.match_local_action", lambda _t, **_kw: plan+ )await mgr._run_local_action_fast_path("mach einen screenshot")await asyncio.gather(*getattr(mgr, "_cu_background_tasks", set()))@@ -205,7 +213,9 @@ async def test_three_parallel_cancels_speak_nothing(monkeypatch) -> None:plan = LocalActionPlan(mode=LocalActionMode.COMPUTER_USE, harness="computer-use", prompt="do it")- monkeypatch.setattr("jarvis.brain.manager.match_local_action", lambda _t: plan)+ monkeypatch.setattr(+ "jarvis.brain.manager.match_local_action", lambda _t, **_kw: plan+ )# Each turn spawns its own background mission off a shared manager.executor = _SlowHarnessExecutor(@@ -259,7 +269,9 @@ async def test_cu_failure_outcome_is_written_back_to_history(monkeypatch) -> Nonplan = LocalActionPlan(mode=LocalActionMode.COMPUTER_USE, harness="computer-use", prompt="open spotify")- monkeypatch.setattr("jarvis.brain.manager.match_local_action", lambda _t: plan)+ monkeypatch.setattr(+ "jarvis.brain.manager.match_local_action", lambda _t, **_kw: plan+ )await mgr._run_local_action_fast_path("öffne mein spotify und spiel das lied") # i18n-allowawait asyncio.gather(*getattr(mgr, "_cu_background_tasks", set()))@@ -294,7 +306,9 @@ async def test_cu_success_outcome_is_written_back_to_history(monkeypatch) -> Nonplan = LocalActionPlan(mode=LocalActionMode.COMPUTER_USE, harness="computer-use", prompt="open spotify")- monkeypatch.setattr("jarvis.brain.manager.match_local_action", lambda _t: plan)+ monkeypatch.setattr(+ "jarvis.brain.manager.match_local_action", lambda _t, **_kw: plan+ )await mgr._run_local_action_fast_path("öffne spotify und spiel das lied") # i18n-allowawait asyncio.gather(*getattr(mgr, "_cu_background_tasks", set()))@@ -325,7 +339,9 @@ async def test_cu_user_cancel_writes_nothing_to_history(monkeypatch) -> None:plan = LocalActionPlan(mode=LocalActionMode.COMPUTER_USE, harness="computer-use", prompt="do it")- monkeypatch.setattr("jarvis.brain.manager.match_local_action", lambda _t: plan)+ monkeypatch.setattr(+ "jarvis.brain.manager.match_local_action", lambda _t, **_kw: plan+ )await mgr._run_local_action_fast_path("mach einen screenshot")await asyncio.gather(*getattr(mgr, "_cu_background_tasks", set()))@@ -481,7 +497,9 @@ async def test_cu_goal_carries_recent_conversation_context(monkeypatch) -> None:plan = LocalActionPlan(mode=LocalActionMode.COMPUTER_USE, harness="computer-use", prompt=utterance)- monkeypatch.setattr("jarvis.brain.manager.match_local_action", lambda _t: plan)+ monkeypatch.setattr(+ "jarvis.brain.manager.match_local_action", lambda _t, **_kw: plan+ )token = _TURN_HISTORY_OVERRIDE.set((BrainMessage(@@ -516,7 +534,9 @@ async def test_cu_goal_without_history_stays_bare(monkeypatch) -> None:plan = LocalActionPlan(mode=LocalActionMode.COMPUTER_USE, harness="computer-use", prompt="open chrome")- monkeypatch.setattr("jarvis.brain.manager.match_local_action", lambda _t: plan)+ monkeypatch.setattr(+ "jarvis.brain.manager.match_local_action", lambda _t, **_kw: plan+ )await mgr._run_local_action_fast_path("öffne chrome") # i18n-allowawait asyncio.gather(*getattr(mgr, "_cu_background_tasks", set()))@@ -540,7 +560,9 @@ async def test_cu_goal_context_falls_back_to_live_history(monkeypatch) -> None:plan = LocalActionPlan(mode=LocalActionMode.COMPUTER_USE, harness="computer-use", prompt=utterance)- monkeypatch.setattr("jarvis.brain.manager.match_local_action", lambda _t: plan)+ monkeypatch.setattr(+ "jarvis.brain.manager.match_local_action", lambda _t, **_kw: plan+ )await mgr._run_local_action_fast_path(utterance)await asyncio.gather(*getattr(mgr, "_cu_background_tasks", set()))diff --git a/tests/unit/brain/test_cu_fast_path_unwired.py b/tests/unit/brain/test_cu_fast_path_unwired.pyindex 4819b988bb..ba5bbab2e3 100644--- a/tests/unit/brain/test_cu_fast_path_unwired.py+++ b/tests/unit/brain/test_cu_fast_path_unwired.py@@ -70,7 +70,9 @@ def _pin_cu_plan(monkeypatch) -> None:plan = LocalActionPlan(mode=LocalActionMode.COMPUTER_USE, harness="computer-use", prompt="open chrome")- monkeypatch.setattr("jarvis.brain.manager.match_local_action", lambda _t: plan)+ monkeypatch.setattr(+ "jarvis.brain.manager.match_local_action", lambda _t, **_kw: plan+ )@pytest.mark.asynciodiff --git a/tests/unit/brain/test_evidence_gate.py b/tests/unit/brain/test_evidence_gate.pyindex 51640ee68c..b4944e6b20 100644--- a/tests/unit/brain/test_evidence_gate.py+++ b/tests/unit/brain/test_evidence_gate.py@@ -1,5 +1,5 @@"""Evidence gate verdicts + hard negatives (AD-CLI4..AD-CLI8)."""-from jarvis.brain.evidence_gate import check_evidence_domain+from jarvis.brain.evidence_gate import check_evidence_domain, live_surface_coversfrom jarvis.core.capabilities import Capability, CapabilityRegistryDOMAINS = {@@ -9,7 +9,15 @@ DOMAINS = {}-def _gate(text, *, registry=None, tool_map=None, hint_fn=None, enabled=True):+def _gate(+ text,+ *,+ registry=None,+ tool_map=None,+ hint_fn=None,+ enabled=True,+ live_tools=(),+):return check_evidence_domain(text,enabled=enabled,@@ -17,6 +25,7 @@ def _gate(text, *, registry=None, tool_map=None, hint_fn=None, enabled=True):capability_registry=registry if registry is not None else CapabilityRegistry(),domain_tool_map=tool_map or {},refusal_hint_fn=hint_fn,+ live_tool_names=live_tools,)@@ -255,3 +264,59 @@ def test_broken_registry_degrades_to_pass():v = _gate("Was steht heute noch an?", registry=_Broken())assert v.kind == "pass"+++# --- live tool surface beats the stale registry (GT-16) ----------------------+#+# The registry is a cache; the tools attached to the turn are the truth. A+# plugin/CLI/MCP server connected mid-session is callable immediately and+# unknown to the registry, so a registry-only refusal tells the user "I can't"+# while the tool sits right there. Same utterance, same empty registry — only+# the live surface differs between the two tests below.+++def test_calendar_refusal_fires_when_no_tool_is_attached():+ v = _gate("Was steht heute noch an?", live_tools=("spawn_worker", "search_web"))+ assert v.kind == "honest_refusal"+ assert "Kalenderzugriff" in v.refusal_text+++def test_calendar_question_proceeds_when_a_calendar_tool_is_attached():+ v = _gate(+ "Was steht heute noch an?",+ live_tools=("spawn_worker", "google_calendar", "search_web"),+ )+ assert v.kind == "pass", (+ "a connected calendar tool must stand the refusal down, whatever the "+ "capability registry believes"+ )+++def test_namespaced_mcp_tool_also_counts_as_coverage():+ # MCP servers arrive namespaced; the domain word still sits in the name.+ v = _gate("Hab ich neue Mails?", live_tools=("mcp__fastmail__list_inbox",))+ assert v.kind == "pass"+++def test_unrelated_tool_names_do_not_cancel_the_refusal():+ # The matcher must stay narrow enough that the refusal survives an ordinary+ # tool surface — an honest refusal beats a hallucinated success.+ v = _gate(+ "Hab ich neue Mails?",+ live_tools=("spawn_worker", "open_app", "click", "reset_orb_position"),+ )+ assert v.kind == "honest_refusal"+++def test_live_surface_covers_matching_rule():+ # Token run inside a separator-split name, and the separator-free form for+ # terms of five characters and up ("whats-app" -> "whatsapp").+ assert live_surface_covers(["calendar"], ["mcp__google_calendar__list-events"])+ assert live_surface_covers(["whats-app"], ["whatsapp"])+ assert live_surface_covers(["pull request"], ["cli_pull_request"])+ # Short terms are whole-token only: "pr" must not hit "switch_provider".+ assert not live_surface_covers(["pr"], ["switch_provider"])+ assert live_surface_covers(["pr"], ["gh_pr"])+ # Nothing attached, or nothing related, is not coverage.+ assert not live_surface_covers(["calendar"], [])+ assert not live_surface_covers(["calendar"], ["spawn_worker", "search_web"])diff --git a/tests/unit/brain/test_explicit_computer_use_routing.py b/tests/unit/brain/test_explicit_computer_use_routing.pyindex b583f28ca3..a8d780b5a1 100644--- a/tests/unit/brain/test_explicit_computer_use_routing.py+++ b/tests/unit/brain/test_explicit_computer_use_routing.py@@ -174,7 +174,9 @@ async def test_repro_phrase_actually_dispatches_and_executes_harness(# Use the REAL routing logic, pinned hermetic (no capability-registry singleton).monkeypatch.setattr("jarvis.brain.manager.match_local_action",- lambda text: real_match_local_action(text, _registry=None),+ lambda text, **kwargs: real_match_local_action(+ text, _registry=None, **kwargs+ ),)bus = _FakeBus()diff --git a/tests/unit/brain/test_failure_readback_no_exit_token.py b/tests/unit/brain/test_failure_readback_no_exit_token.pyindex 22fd4004c5..0af98514b8 100644--- a/tests/unit/brain/test_failure_readback_no_exit_token.py+++ b/tests/unit/brain/test_failure_readback_no_exit_token.py@@ -114,7 +114,7 @@ def _make_manager(executor, *, reply_language: str = "auto") -> BrainManager:return mgr-def _direct_plan(_text: str) -> LocalActionPlan:+def _direct_plan(_text: str, **_kwargs: object) -> LocalActionPlan:return LocalActionPlan(mode=LocalActionMode.DIRECT,tool_calls=(LocalToolCall(name="open_app", args={"app_name": "x"}),),diff --git a/tests/unit/brain/test_local_action_ack_language.py b/tests/unit/brain/test_local_action_ack_language.pyindex c0cc387dfd..a10b929aae 100644--- a/tests/unit/brain/test_local_action_ack_language.py+++ b/tests/unit/brain/test_local_action_ack_language.py@@ -60,7 +60,7 @@ def _make_direct_manager(*, reply_language: str = "auto", turn_lang: str = ""):return mgr-def _direct_open_explorer_plan(_text: str) -> LocalActionPlan:+def _direct_open_explorer_plan(_text: str, **_kwargs: object) -> LocalActionPlan:return LocalActionPlan(mode=LocalActionMode.DIRECT,tool_calls=(LocalToolCall(name="open_app", args={"app_name": "explorer"}),),diff --git a/tests/unit/brain/test_local_action_gate.py b/tests/unit/brain/test_local_action_gate.pyindex dbfe6803d4..49c53d1c50 100644--- a/tests/unit/brain/test_local_action_gate.py+++ b/tests/unit/brain/test_local_action_gate.py@@ -8,6 +8,7 @@ from jarvis.brain.local_action_gate import (LocalToolCall,_CapabilityRegistryLike,_unsupported_response,+ external_integration_terms,is_open_app_intent,match_local_action,requires_external_integration,@@ -1061,3 +1062,70 @@ def test_open_prefixed_product_names_do_not_hijack_the_cu_gate(utterance) -> Nondef test_real_english_open_verbs_still_route(utterance, mode) -> None:plan = match_local_action(utterance)assert plan is not None and plan.mode is mode+++# ---------------------------------------------------------------------------+# The live tool surface beats the stale registry (GT-16)+#+# ``resolve_intent`` speaks for the capability registry, and that registry+# lags reality: a plugin/CLI/MCP server connected mid-session is callable long+# before it is registered. The UNSUPPORTED refusal used to fire anyway, which+# is the maintainer's complaint — "I'm told it's impossible while the+# capability is right there". The pairs below run the SAME utterance against+# the SAME unresolving registry; only the attached tools differ.+# ---------------------------------------------------------------------------+++ ("utterance", "tool_name"),+ [+ ("schick eine email an [email protected]", "gmail"),+ ("trag einen termin morgen 10 uhr ein", "google_calendar"),+ ("sende eine whatsapp an mama", "mcp__whatsapp__send_message"),+ ],+)+def test_attached_tool_stands_the_unsupported_refusal_down(+ utterance: str, tool_name: str+) -> None:+ """A tool named after the requested system means the capability exists."""+ plan = match_local_action(+ utterance, _registry=_FAKE_REG, live_tool_names=(tool_name, "spawn_worker")+ )++ assert plan is None or plan.mode != LocalActionMode.UNSUPPORTED, (+ f"{utterance!r} must not be refused while {tool_name!r} is attached"+ )+++ "utterance",+ [+ "schick eine email an [email protected]",+ "trag einen termin morgen 10 uhr ein",+ "sende eine whatsapp an mama",+ ],+)+def test_unsupported_refusal_still_fires_without_a_matching_tool(+ utterance: str,+) -> None:+ """The refusal is correct when the capability genuinely is absent — an+ honest refusal beats a hallucinated success. An ordinary tool surface must+ not cancel it."""+ plan = match_local_action(+ utterance,+ _registry=_FAKE_REG,+ live_tool_names=("spawn_worker", "open_app", "click", "search_web"),+ )++ assert plan is not None+ assert plan.mode == LocalActionMode.UNSUPPORTED+ assert plan.response_text+++def test_external_integration_terms_names_the_matched_systems() -> None:+ assert external_integration_terms("schick eine email an mama") == ("email",)+ assert external_integration_terms("bestell eine pizza") == ("pizza",)+ # The Twitter/X rebrand hides the platform behind a bare letter — the+ # matcher needs the product names a connected tool would carry.+ assert "twitter" in external_integration_terms("poste das auf X")+ assert external_integration_terms("analysier das repo") == ()diff --git a/tests/unit/brain/test_routing.py b/tests/unit/brain/test_routing.pyindex 049e1951e0..908eb970d0 100644--- a/tests/unit/brain/test_routing.py+++ b/tests/unit/brain/test_routing.py@@ -1918,6 +1918,13 @@ def test_router_tools_is_pure_dispatcher_set() -> None:# MCP server block, so it must be router-visible directly; per-action# risk gating (reads safe, writes monitor, share/delete ask)."google_drive",+ # Spotify Marketplace plugin (2026-08-17): native REST tool, same+ # rationale as gmail — Spotify publishes no MCP server at all, so it+ # must be router-visible directly; otherwise connected Spotify is+ # not callable by voice, which is the entire point of a music+ # plugin. risk_tier "monitor" (starting music is audible and+ # instantly undone). Never a spawn (AP-5/AP-14).+ "spotify",# Computer-Use (Wave 1, 2026-05-29): first-class tool to drive the# live desktop. Router-tier only — a direct safe-gated action (the# loop gates each action via ToolExecutor, ADR-0008), never a spawn,@@ -2320,11 +2327,9 @@ def test_check_unsupported_intent_fires_for_unregistered_action() -> None:resolve_intent=lambda _t: None,render_for_prompt=lambda lang="de": "",)- mock_module = types.ModuleType("jarvis.core.capabilities")- mock_module.get_registry = lambda: mock_reg # type: ignore[attr-defined]-original = sys.modules.get("jarvis.core.capabilities")- sys.modules["jarvis.core.capabilities"] = mock_module+ # Delegating mock, not a bare ModuleType — see _capabilities_mock_module.+ sys.modules["jarvis.core.capabilities"] = _capabilities_mock_module(mock_reg)try:manager, _executor = _manager_with_spawn()result = manager._check_unsupported_intent(@@ -2433,6 +2438,31 @@ def test_check_unsupported_intent_returns_none_when_registry_empty() -> None:# ---------------------------------------------------------------------------+def _capabilities_mock_module(mock_reg):+ """A ``jarvis.core.capabilities`` stand-in that overrides ONLY+ ``get_registry`` and delegates every other attribute to the real module.++ A bare ``ModuleType`` shadows the real module completely, so the first+ LAZY importer of anything else from it fails inside the code under test:+ ``_check_unsupported_intent`` imports ``jarvis.brain.evidence_gate``, whose+ module body does ``from jarvis.core.capabilities import _normalize``. Under+ a bare mock that raises ImportError, which the method's broad ``except``+ turns into ``return None`` — every refusal silently became "supported" and+ the guard tests failed with no visible reason. Whether it fired at all+ depended on test ORDER (an earlier import of evidence_gate hides it via the+ module cache), which is exactly what makes this shape worth a helper.+ """+ import importlib+ import types++ real = importlib.import_module("jarvis.core.capabilities")+ module = types.ModuleType("jarvis.core.capabilities")+ module.get_registry = lambda: mock_reg # type: ignore[attr-defined]+ # PEP 562: only consulted for attributes the mock does not define itself.+ module.__getattr__ = lambda name: getattr(real, name) # type: ignore[attr-defined]+ return module++def _strict_manager_with_mock_registry(*, has_action: bool = True, resolves: bool = False, populated: bool = True):@@ -2451,9 +2481,7 @@ def _strict_manager_with_mock_registry(resolve_intent=lambda _t: (object() if resolves else None),render_for_prompt=lambda lang="de": "",)- mock_module = types.ModuleType("jarvis.core.capabilities")- mock_module.get_registry = lambda: mock_reg # type: ignore[attr-defined]- sys.modules["jarvis.core.capabilities"] = mock_module+ sys.modules["jarvis.core.capabilities"] = _capabilities_mock_module(mock_reg)manager, _executor = _manager_with_spawn(force_spawn_mode="strict")return manager@@ -3610,3 +3638,96 @@ def test_agentic_ide_gate_is_fault_tolerant() -> None:manager._hide_agentic_ide_tools_without_workspace(sentinel) # type: ignore[arg-type]is sentinel)+++# ---------------------------------------------------------------------------+# GT-16: the honest refusal must consult the LIVE tool surface+#+# `_check_unsupported_intent` asks the capability registry, and the registry+# lags reality: a plugin/CLI/MCP server connected mid-session is callable long+# before it is registered. The refusal fired anyway — the maintainer's exact+# complaint, "I ask for something and am told it is impossible while the+# capability sits right there". Both tests below run the SAME utterance+# against the SAME unresolving registry; only the attached tools differ.+# ---------------------------------------------------------------------------+++class _FakeGmailTool:+ name = "gmail"+ schema: dict[str, Any] = {}+++def _unresolving_registry_module():+ import types++ mock_reg = types.SimpleNamespace(+ all=lambda: (object(),), # seeded, but nothing resolves+ has_action_intent=lambda _t: True,+ resolve_intent=lambda _t: None,+ render_for_prompt=lambda lang="de": "",+ )+ module = types.ModuleType("jarvis.core.capabilities")+ module.get_registry = lambda: mock_reg # type: ignore[attr-defined]+ return module+++def test_unsupported_refusal_fires_when_no_tool_covers_the_request() -> None:+ """Nothing on the surface serves mail — the honest refusal is correct."""+ import sys++ original = sys.modules.get("jarvis.core.capabilities")+ sys.modules["jarvis.core.capabilities"] = _unresolving_registry_module()+ try:+ manager, _executor = _manager_with_spawn()+ result = manager._check_unsupported_intent(+ "Schick bitte eine E-Mail an Beispielkontakt"+ )+ assert result is not None and "kann ich noch nicht" in result+ finally:+ if original is not None:+ sys.modules["jarvis.core.capabilities"] = original+ else:+ sys.modules.pop("jarvis.core.capabilities", None)+++def test_unsupported_refusal_stands_down_for_a_freshly_connected_tool() -> None:+ """Same utterance, same stale registry — but the Gmail plugin is attached.++ The tool arrives the way it does live: `refresh_tools()` replaces+ `self._tools` wholesale after the connect, so the surface read at decision+ time is the only truthful one. The turn must proceed and let the model call+ the tool instead of speaking "Das kann ich noch nicht".+ """+ import sys++ original = sys.modules.get("jarvis.core.capabilities")+ sys.modules["jarvis.core.capabilities"] = _unresolving_registry_module()+ try:+ manager, _executor = _manager_with_spawn()+ utterance = "Schick bitte eine E-Mail an Beispielkontakt"+ assert manager._check_unsupported_intent(utterance) is not None++ # The Gmail plugin connects mid-session (what refresh_tools() does).+ manager._tools = {"spawn_worker": _FakeTool(), "gmail": _FakeGmailTool()}++ assert manager._check_unsupported_intent(utterance) is None, (+ "a connected gmail tool must stand the refusal down"+ )+ finally:+ if original is not None:+ sys.modules["jarvis.core.capabilities"] = original+ else:+ sys.modules.pop("jarvis.core.capabilities", None)+++def test_live_tool_names_reads_both_surfaces_fresh() -> None:+ """The evidence is read live and covers the local-action tools too."""+ manager, _executor = _manager_with_local_actions()+ names = manager._live_tool_names()+ assert "spawn_worker" in names and "open_app" in names++ manager._tools = {"gmail": _FakeGmailTool()}+ assert "gmail" in manager._live_tool_names()+ assert "spawn_worker" not in manager._live_tool_names(), (+ "_live_tool_names must never serve a cached snapshot"+ )