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(wiki): Jarvis stops offering a wiki tool whose mode is switched off, and reaches for the wiki that works
rubenluetke10-beep5dd3a1f68106
diff --git a/docs/BUGS.md b/docs/BUGS.mdindex fbf5f06f79..7cc891915c 100644--- a/docs/BUGS.md+++ b/docs/BUGS.md@@ -12223,3 +12223,90 @@ supervisor and the supervised were on the same thread. And "it is taking toolong" is not a diagnosis: replacing a worker only helps when the worker isstuck, never when it is merely loading. Patience needs evidence, so the enginehad to say which one it was.+## BUG-175: "ask him what Jarvis version 2 can do" answers nothing — the model was handed a wiki tool whose mode is switched off, and the wiki that WAS working sat unused beside it (HIGH, FIXED 2026-08-24)++**Symptom (maintainer, 2026-08-24).** A question typed into the chat, sixteen+seconds of thinking, and one red row: `ultrawiki_ask · what Jarvis Version 2 can+do — FAILED 0.0s`. No answer, no second attempt. The maintainer's reading was+that "the wiki tool is broken"; measured, the wiki was fine and every part of+this failure was in the tool set.++**Timeline (`data/jarvis_desktop.log`).**++```+09:04:12 ultrawiki: service constructed (mode disabled — dormant)+10:13:58.280 gemini-live: function call(s) ultrawiki_ask_55466fa18d+10:13:58.737 POST http://127.0.0.1/api/ultrawiki/ask "HTTP/1.1 409 Conflict"+10:13:58.739 gemini-live: tool response sent (model_generating=True)+```++0.0 s is the tell: nothing was searched. `_require_active` refuses before any+retrieval, by design — `[ultrawiki] enabled = false` in this install.++**Root cause: a tool set that promised what the app had switched off.**+`AppCommandTool.expand()` turned EVERY Command-Registry entry into a callable+tool, unconditionally. Four of them are `/api/ultrawiki/*` routes+(`ultrawiki-ask`, `people-list`, `person-profile`, `identity-queue-list`), and+that whole family answers 409 while the mode is off. So the model was offered+four tools that could not succeed, with nothing in their schemas to say so —+the registry description reads "Answer one question from UltraWiki evidence",+which is exactly what had been asked for.++Verified on the live app: `GET /api/tools` listed all four alongside the+classic wiki tools. `wiki-recall` was in the same set the whole time and+answers that question from the Obsidian vault in 13 ms (27 entities, hits with+scores). The knowledge was there; the tool set pointed at the one locked door.++This is AP-21 (gate on the capability, never on a name) applied to tools rather+than providers: a tool's presence is a claim that it can answer.++**Root cause, second defect: the section that would not open.** Reported in the+same breath — "sometimes I go into the section and it does not come up". The+Wiki view renders NEITHER body until `GET /api/ultrawiki/status` answers, and+that route probed the search legs on every call: a credential walk plus a+request to the local embedding endpoint. Measured 2026-08-24 against the live+app: 0.7-2.1 s per call, where every other wiki route is under 150 ms+(`/api/wiki/tree` 13 ms, `/api/wiki/health` 66 ms). While the mode is off+nothing renders those legs — only the Ultra body does, and it is not mounted —+so the wait bought nothing. A visit with no remembered mode paid it in full,+staring at an empty section.++**Fix.**++* `jarvis/commands/capabilities.py` resolves a command's `requires` against the+ LIVE config (the mode switch mutates it in place, so a toggle counts at+ once). `AppCommand.requires` is backend-only — the UI and CLI catalogs still+ list every command, because both of those surfaces can turn the mode ON.+ Only the LLM tool set, which cannot, is filtered.+* The gate FAILS OPEN. An unreadable config leaves the tool in place: a wrong+ "available" is caught by the execute-time re-check, while a wrong+ "unavailable" would silently remove the tool for the whole session.+* `RegistryCommandTool.execute()` re-checks before sending, because the mode+ applies live and a session can hold a tool built while it was on. The refusal+ carries a redirect naming `wiki-recall` / `wiki-list` / `wiki-page-read`, so+ the model has somewhere to go inside the same turn instead of ending it on a+ failure — the behaviour `ultrawiki-search` already had and `ultrawiki-ask`+ never did.+* Switching the mode publishes `BrainToolsChanged`, so activation brings the+ four commands BACK without a restart. Without it the gate would have traded+ one missing-tool bug for its mirror image.+* `/api/ultrawiki/status` skips the leg probe while the mode is off and says+ `search_legs.probed: false` with a reason, rather than reporting legs nobody+ measured. `/health` — which grades those legs, and would read an absent+ keyword leg as "search cannot answer" — asks for the probe explicitly.++**Tests.** `tests/unit/commands/test_capabilities.py` pins mode-off, fail-open,+that the steer names tools that actually work, and — the one that matters in a+year — derives the gated set from the registry's own PATHS, so a future+`/api/ultrawiki/*` command that forgets `requires=` fails the build.+`tests/unit/plugins/tool/test_app_command.py` pins the withheld four, their+return when the mode is on, and the mid-session steer that sends nothing to the+endpoint. `tests/unit/web/test_ultrawiki_routes.py` pins that status does not+probe while off, that `/health` still does, and that both toggle directions+publish `BrainToolsChanged`.++**Lesson.** A tool in the set is a promise. The model cannot see a config flag,+so anything the app has switched off must be absent, not merely failing — and+when it does fail anyway, the failure has to name the door that IS open. Both+defects here came from the same habit of answering "is it wired?" when the+question was "can it answer?".diff --git a/jarvis/commands/capabilities.py b/jarvis/commands/capabilities.pynew file mode 100644index 0000000000..a7922b100f--- /dev/null+++ b/jarvis/commands/capabilities.py@@ -0,0 +1,120 @@+"""Runtime capability gate for Command-Registry entries.++Why this exists+---------------+Most registry commands run whenever the app runs. A few are bound to a mode+the user can switch off, and their endpoint then refuses the call outright —+``/api/ultrawiki/*`` answers 409 while UltraWiki mode is off. Handing such a+command to a language model as a callable tool is a promise the app cannot+keep, and the model has no way to see that from the schema.++Measured live 2026-08-24 10:13 (``data/jarvis_desktop.log``): asked what+Jarvis version 2 can do, the realtime model picked ``ultrawiki_ask``, got+``409 Conflict`` in 0.0 s, and stopped — while ``wiki-recall`` sat in the same+tool set and answers that question from the Obsidian vault in 13 ms. The+knowledge WAS there; the tool set pointed at the one door that was locked.++So this module answers one question — "can this capability answer right now?"+— against the LIVE config, which is what the mode switch mutates in place+(``ultrawiki_routes._apply_live``). Reading the live object rather than the+TOML is what makes a mode toggled during a session take effect without a+rebuild of the tool set.++Fail-open on purpose+--------------------+An unreadable config returns ``True``. Losing a working tool because the+probe itself failed is strictly worse than offering one that might refuse:+the refusal path is covered by :func:`steer_for`, which turns the 409 into an+instruction the model can act on in the same turn. Absence of evidence that a+capability is off is not evidence that it is off.++This is the AP-21 rule applied to tools: gate on the capability, never on a+name someone typed twice.+"""++from __future__ import annotations++import logging+from typing import Any, Final++log = logging.getLogger(__name__)++#: Capability name -> the ``[section] enabled`` flag on the live config that+#: decides it. One entry per mode a user can switch off from the UI.+_CONFIG_FLAGS: Final[dict[str, str]] = {"ultrawiki": "ultrawiki"}++#: What the model should do INSTEAD, said in the imperative so it can act on+#: it within the same turn rather than reporting a failure to the user. The+#: classic wiki tools are always loaded and answer the same questions from the+#: Obsidian vault, so an UltraWiki refusal is a redirect, never a dead end.+_STEERS: Final[dict[str, str]] = {+ "ultrawiki": (+ "UltraWiki mode is switched off, so the semantic knowledge base "+ "cannot answer. The normal wiki holds the same knowledge and is "+ "available right now: call wiki-recall to search it, wiki-list to see "+ "what it contains, and wiki-page-read to read one page in full. Do "+ "that instead of reporting a failure, and only say the knowledge base "+ "is unavailable if those tools also come back empty."+ ),+}+++def _live_config() -> Any | None:+ """The config object the running WebServer holds, or ``None``.++ Lazy import and attribute-walked: this runs inside a tool call, long after+ boot, and must never be the reason a tool cannot be built (AP-26).+ """+ try:+ from jarvis.core import runtime_refs # noqa: PLC0415 — lazy, boot-safe++ app = runtime_refs.get_web_app()+ return getattr(getattr(app, "state", None), "config", None)+ except Exception as exc: # noqa: BLE001 — fail open, see module docstring+ log.debug("capability probe could not reach the live config: %s", exc)+ return None+++def is_available(capability: str, *, config: Any | None = None) -> bool:+ """Can ``capability`` answer a call right now?++ An empty or unknown capability name is available — the gate only ever+ subtracts for modes it actually knows how to check.+ """+ name = (capability or "").strip()+ if not name:+ return True+ section = _CONFIG_FLAGS.get(name)+ if section is None:+ log.debug("unknown capability %r treated as available", name)+ return True+ cfg = config if config is not None else _live_config()+ if cfg is None:+ return True # fail open — steer_for still covers the refusal+ return bool(getattr(getattr(cfg, section, None), "enabled", False))+++def steer_for(capability: str) -> str:+ """The instruction to hand a model whose call was refused by the gate.++ Falls back to a generic sentence so a capability added without a steer+ still produces something the model can reason about.+ """+ name = (capability or "").strip()+ return _STEERS.get(+ name,+ f"The {name} mode is switched off, so this command cannot run. Tell "+ "the user it is off rather than retrying.",+ )+++def unavailable_capability(command: Any, *, config: Any | None = None) -> str:+ """The capability blocking ``command``, or ``""`` when it can run.++ Takes the command rather than the name so callers stay a one-liner and+ a command with no ``requires`` needs no special-casing at the call site.+ """+ needed = str(getattr(command, "requires", "") or "").strip()+ if not needed or is_available(needed, config=config):+ return ""+ return neededdiff --git a/jarvis/commands/registry.py b/jarvis/commands/registry.pyindex e234711d49..0eff67ec2a 100644--- a/jarvis/commands/registry.py+++ b/jarvis/commands/registry.py@@ -53,6 +53,19 @@ class AppCommand:worker_allowed: bool = False # Explicit least-privilege Jarvis-Agent grantui_section: str = "settings" # sidebar section hosting the same actionvoice_aliases: dict[str, tuple[str, ...]] = field(default_factory=dict)+ #: Capability this command's endpoint needs before it can answer at all.+ #:+ #: Empty for the vast majority: they run whenever the app runs. A named+ #: capability means the backing route refuses the call outright while that+ #: mode is off, so offering the command as a tool is a promise the app+ #: cannot keep. ``jarvis.commands.capabilities`` resolves the name against+ #: the live config, and the ``app-command`` loader drops what is off.+ #:+ #: Backend-only on purpose, hence its absence from :meth:`as_dict`: the+ #: catalog the UI and CLI read still lists every command, because both of+ #: those surfaces can (and do) turn the mode ON. Only the LLM tool set,+ #: which cannot, is filtered.+ requires: str = ""def as_dict(self) -> dict[str, Any]:return {@@ -514,6 +527,7 @@ def _build_registry() -> tuple[AppCommand, ...]:method="POST",path="/api/ultrawiki/ask",worker_allowed=True,+ requires="ultrawiki",params={"type": "object","properties": {@@ -554,6 +568,7 @@ def _build_registry() -> tuple[AppCommand, ...]:),method="GET",path="/api/ultrawiki/identity/people",+ requires="ultrawiki",params={"type": "object","properties": {@@ -587,6 +602,7 @@ def _build_registry() -> tuple[AppCommand, ...]:),method="GET",path="/api/ultrawiki/identity/people/{entity_id}",+ requires="ultrawiki",params={"type": "object","properties": {@@ -617,6 +633,7 @@ def _build_registry() -> tuple[AppCommand, ...]:),method="GET",path="/api/ultrawiki/identity/queue",+ requires="ultrawiki",params={"type": "object","properties": {diff --git a/jarvis/plugins/tool/app_command.py b/jarvis/plugins/tool/app_command.pyindex cbd5295254..58528b868e 100644--- a/jarvis/plugins/tool/app_command.py+++ b/jarvis/plugins/tool/app_command.py@@ -27,11 +27,14 @@ configuration mutation and dangerous commands remain supervisor-only."""from __future__ import annotations+import loggingfrom typing import Anyfrom urllib.parse import quotefrom jarvis.core.protocols import ToolResult+log = logging.getLogger(__name__)+_TYPE_CHECKS: dict[str, type | tuple[type, ...]] = {"string": str,"boolean": bool,@@ -215,12 +218,21 @@ class _Runtime:app_resolver: Any | None = None,control_key_resolver: Any | None = None,transport: Any | None = None,+ config_resolver: Any | None = None,) -> None:# Lazy resolvers (spawn-worker pattern): the FastAPI app is built after# the brain, so it must be looked up at execute time, not now.self._app_resolver = app_resolverself._control_key_resolver = control_key_resolverself._transport = transport+ # Same lazy shape for the capability gate. Left unset it reads the live+ # config off the running app, which is what makes a mode toggled during+ # a session take effect; a caller that supplies one gets a deterministic+ # answer without a running app.+ self._config_resolver = config_resolver++ def config(self) -> Any | None:+ return self._config_resolver() if self._config_resolver is not None else Nonedef resolve_transport(self) -> Any | None:if self._transport is not None:@@ -271,6 +283,19 @@ class RegistryCommandTool:async def execute(self, args: dict[str, Any], ctx: Any) -> ToolResult:cmd = self._cmd+ # The mode may have been switched off since this tool set was built+ # (the switch applies live, no rebuild). Answer with the redirect the+ # endpoint's 409 cannot carry, so the model reaches for the wiki tools+ # that do work instead of ending the turn on a failure.+ from jarvis.commands.capabilities import steer_for, unavailable_capability++ blocked_by = unavailable_capability(cmd, config=self._runtime.config())+ if blocked_by:+ return ToolResult(+ success=False,+ output={"command_id": cmd.id, "capability": blocked_by},+ error=steer_for(blocked_by),+ )cmd_args = _with_defaults(cmd.params, args or {})cmd_args = _apply_visible_terminal_context(cmd.id, cmd_args, ctx)problems = _validate_args(cmd.params, cmd_args)@@ -367,10 +392,41 @@ class AppCommandTool:app_resolver: Any | None = None,control_key_resolver: Any | None = None,transport: Any | None = None,+ config_resolver: Any | None = None,) -> None:- self._runtime = _Runtime(app_resolver, control_key_resolver, transport)+ self._runtime = _Runtime(+ app_resolver, control_key_resolver, transport, config_resolver+ )def expand(self) -> list[RegistryCommandTool]:+ """Every registry command whose capability can actually answer.++ A command bound to a switched-off mode is dropped rather than offered:+ its endpoint refuses the call, and a tool that cannot succeed is worse+ than an absent one — the model spends its turn on it and stops, instead+ of reaching for the tool that would have worked (see+ :mod:`jarvis.commands.capabilities` for the live forensic).++ Evaluated at build time, which is when the tool set is composed. A mode+ switched during a session leaves this set stale until the next brain+ build, so :meth:`RegistryCommandTool.execute` re-checks and steers.+ """+ from jarvis.commands.capabilities import unavailable_capabilityfrom jarvis.commands.registry import get_registry- return [RegistryCommandTool(cmd, self._runtime) for cmd in get_registry()]+ cfg = self._runtime.config()+ tools: list[RegistryCommandTool] = []+ dropped: list[str] = []+ for cmd in get_registry():+ blocked_by = unavailable_capability(cmd, config=cfg)+ if blocked_by:+ dropped.append(f"{cmd.id} ({blocked_by} off)")+ continue+ tools.append(RegistryCommandTool(cmd, self._runtime))+ if dropped:+ log.info(+ "app-command: %d command(s) withheld from the tool set: %s",+ len(dropped),+ ", ".join(dropped),+ )+ return toolsdiff --git a/jarvis/ui/web/frontend/src/lib/ultrawikiApi.ts b/jarvis/ui/web/frontend/src/lib/ultrawikiApi.tsindex f8a0097367..15ead3f9d2 100644--- a/jarvis/ui/web/frontend/src/lib/ultrawikiApi.ts+++ b/jarvis/ui/web/frontend/src/lib/ultrawikiApi.ts@@ -490,6 +490,15 @@ export interface UltraWikiStatus {vector?: UltraWikiSearchLeg;rerank?: UltraWikiSearchLeg;error?: string;+ /**+ * `false` when the legs were deliberately not measured — the mode is off,+ * nothing renders them, and the probe is what made opening the Wiki+ * section wait (0.7-2.1 s against <150 ms for every other wiki route).+ * Absent on a probed answer. Never read a missing leg as a broken one:+ * check this first, then `reason`.+ */+ probed?: boolean;+ reason?: string;};degradations: string[];}diff --git a/jarvis/ui/web/ultrawiki_routes.py b/jarvis/ui/web/ultrawiki_routes.pyindex e62031cc9b..a891e83bf2 100644--- a/jarvis/ui/web/ultrawiki_routes.py+++ b/jarvis/ui/web/ultrawiki_routes.py@@ -39,6 +39,19 @@ router = APIRouter(prefix="/api/ultrawiki", tags=["ultrawiki"])_MODE_OFF_DETAIL = "UltraWiki mode is off — the normal wiki answers today."+#: ``search_legs`` when the probe was deliberately not run. Says so instead of+#: reporting absent legs: an empty dict reads as "keyword search is down" to+#: ``jarvis.ultrawiki.health._search_check``, and a mode that is simply off is+#: not an outage. The probe costs a credential walk plus a call to the local+#: embedding endpoint, which nothing renders while the mode is off.+_LEGS_NOT_PROBED: dict[str, Any] = {+ "probed": False,+ "reason": (+ "UltraWiki mode is off, so the search legs were not measured — "+ "switching the mode on probes them."+ ),+}+#: The flat ``[ultrawiki]`` slot keys the settings surface may change._SLOT_KEYS = ("db_backend",@@ -221,6 +234,39 @@ def _apply_live(request: Request, values: dict[str, str], *, enabled: bool | Nonuw.enabled = enabledexcept Exception as exc: # noqa: BLE001 — a frozen model is not an errorlog.debug("in-memory ultrawiki.enabled update skipped: %s", exc)+ else:+ _publish_brain_tools_changed(+ request, f"ultrawiki_mode:{'on' if enabled else 'off'}"+ )+++def _publish_brain_tools_changed(request: Request, reason: str) -> None:+ """Tell the live brain its tool set just changed shape.++ The mode decides whether the four ``/api/ultrawiki/*`` commands can answer+ at all, and the tool set is composed once per brain build. Without this+ event, switching the mode ON left them missing until the next restart —+ the mirror image of the bug the gate fixes, and the reason the gate can+ afford to subtract at all.++ Same convention as ``mcp_routes._publish_brain_tools_changed``; a missing+ bus (headless, early boot) is a silent no-op, and a failure to notify must+ never turn a successful mode switch into an error.+ """+ bus = getattr(request.app.state, "bus", None)+ if bus is None:+ return+ from jarvis.core.events import BrainToolsChanged # noqa: PLC0415 — lazy (AP-26)++ event = BrainToolsChanged(source_layer="ultrawiki_routes", reason=reason)+ try:+ result = bus.publish(event)+ if asyncio.iscoroutine(result):+ # Called from sync helpers on the loop's own thread: hand the+ # coroutine to the loop rather than awaiting it here.+ asyncio.create_task(result, name="ultrawiki-brain-tools-changed")+ except Exception as exc: # noqa: BLE001 — notification, never the outcome+ log.debug("BrainToolsChanged publish failed: %s", exc)def _is_configured(uw: Any) -> bool:@@ -371,10 +417,35 @@ def _embed_eta_phrase(throughput: dict[str, Any] | None) -> str:@router.get("/status", summary="UltraWiki mode status")async def get_status(request: Request) -> dict[str, Any]:- """Honest capability, backlog, and source report — answers even when the mode is off."""+ """Honest capability, backlog, and source report — answers even when the mode is off.++ The leg probe is skipped while the mode is OFF, because nothing renders it+ then and the wait is paid by the one screen that must not wait. This route+ is what the Wiki section asks before it can draw either body, and the probe+ walks credentials and touches the local embedding endpoint: measured+ 2026-08-24 at 0.7-2.1 s per call on a warm backend, against under 150 ms+ for every other wiki route. On a first visit with no remembered answer the+ section renders nothing at all for that whole span — the "I open the Wiki+ and it does not come up" report. ``search_legs`` therefore says it was not+ probed rather than reporting legs nobody measured; ``/health``, the one+ caller that genuinely needs them, asks for the probe explicitly.+ """+ return await _status_payload(request, probe_legs=None)+++async def _status_payload(+ request: Request, *, probe_legs: bool | None+) -> dict[str, Any]:+ """The status body. ``probe_legs=None`` means "probe only if the mode is on"."""cfg = _config(request)uw = getattr(cfg, "ultrawiki", None)enabled = bool(getattr(uw, "enabled", False))+ want_legs = enabled if probe_legs is None else bool(probe_legs)++ async def legs() -> dict[str, Any]:+ if want_legs:+ return await _search_legs_async(cfg)+ return dict(_LEGS_NOT_PROBED)configured_backend = str(getattr(uw, "db_backend", "sqlite") or "sqlite")service = getattr(request.app.state, "ultrawiki", None)if service is None:@@ -406,7 +477,7 @@ async def get_status(request: Request) -> dict[str, Any]:},"sources": [],"jobs": [],- "search_legs": await _search_legs_async(cfg),+ "search_legs": await legs(),"degradations": ["the UltraWiki service is not wired — the app is still ""starting or its init failed"@@ -446,7 +517,7 @@ async def get_status(request: Request) -> dict[str, Any]:"sources": data.get("sources", []),"jobs": data.get("jobs", []),"search_legs": _apply_reembed_to_legs(- await _search_legs_async(cfg), reembed, data.get("throughput") or {}+ await legs(), reembed, data.get("throughput") or {}),"degradations": data.get("degradations", []),}@@ -466,7 +537,10 @@ async def get_health(request: Request) -> dict[str, Any]:"""from jarvis.ultrawiki import health as health_mod # noqa: PLC0415 — lazy (AP-26)- status = await get_status(request)+ # The checklist grades the search legs, so it pays for the probe the+ # status route skips while the mode is off — this is the one caller that+ # would otherwise read "not measured" as "keyword search is down".+ status = await _status_payload(request, probe_legs=True)def _candidates() -> list[dict[str, Any]]:# Walks the keyring + mcp.json; keep it off the event loop.diff --git a/tests/unit/commands/test_capabilities.py b/tests/unit/commands/test_capabilities.pynew file mode 100644index 0000000000..0307e1da71--- /dev/null+++ b/tests/unit/commands/test_capabilities.py@@ -0,0 +1,83 @@+"""The capability gate that decides which registry commands may be tools.++Pinned behaviour, in the order it matters:++1. a command bound to a switched-off mode is unavailable,+2. an unreadable config leaves it available (fail open),+3. the refusal always carries somewhere else to go.+"""+from __future__ import annotations++from types import SimpleNamespace++from jarvis.commands import capabilities+from jarvis.commands.registry import get_registry+++def _cfg(*, ultrawiki: bool) -> SimpleNamespace:+ return SimpleNamespace(ultrawiki=SimpleNamespace(enabled=ultrawiki))+++def test_mode_off_makes_the_capability_unavailable() -> None:+ assert capabilities.is_available("ultrawiki", config=_cfg(ultrawiki=False)) is False+ assert capabilities.is_available("ultrawiki", config=_cfg(ultrawiki=True)) is True+++def test_a_command_without_a_requirement_is_always_available() -> None:+ plain = SimpleNamespace(id="brain-switch")+ assert capabilities.unavailable_capability(plain, config=_cfg(ultrawiki=False)) == ""+ assert capabilities.is_available("") is True+++def test_unknown_capability_names_do_not_subtract() -> None:+ """The gate only ever removes for modes it knows how to check."""+ unknown = SimpleNamespace(id="x", requires="something-nobody-registered")+ assert capabilities.unavailable_capability(unknown, config=_cfg(ultrawiki=False)) == ""+++def test_unreadable_config_fails_open(monkeypatch) -> None:+ """Losing a working tool to a failed probe is worse than a refusal.++ The execute-time re-check turns a wrong "available" into a redirect; a+ wrong "unavailable" silently removes the tool for the whole session.+ """+ monkeypatch.setattr(capabilities, "_live_config", lambda: None)+ assert capabilities.is_available("ultrawiki") is True+++def test_the_steer_names_tools_that_actually_work() -> None:+ """A refusal the model cannot act on is how the turn died in the first place."""+ steer = capabilities.steer_for("ultrawiki")+ assert "wiki-recall" in steer+ # The classic tools are the point: they are always loaded and answer the+ # same questions from the Obsidian vault.+ assert "wiki-page-read" in steer+ assert "wiki-list" in steer+++def test_every_declared_requirement_is_resolvable() -> None:+ """No command may demand a capability the gate cannot check or explain.++ Without this, a typo in `requires=` silently becomes "always available"+ and the tool goes back to failing live.+ """+ for cmd in get_registry():+ needed = getattr(cmd, "requires", "")+ if not needed:+ continue+ assert needed in capabilities._CONFIG_FLAGS, (+ f"{cmd.id} requires {needed!r}, which the gate cannot resolve"+ )+ assert needed in capabilities._STEERS, (+ f"{cmd.id} requires {needed!r}, which has no steer for the model"+ )+++def test_the_ultrawiki_commands_are_the_ones_that_declare_it() -> None:+ """Every /api/ultrawiki route in the registry is gated — none was missed."""+ gated = {c.id for c in get_registry() if getattr(c, "requires", "") == "ultrawiki"}+ ultrawiki_routes = {+ c.id for c in get_registry() if c.path.startswith("/api/ultrawiki/")+ }+ assert gated == ultrawiki_routes+ assert "ultrawiki-ask" in gateddiff --git a/tests/unit/plugins/tool/test_app_command.py b/tests/unit/plugins/tool/test_app_command.pyindex 2f0b1cb736..a5b499f5f5 100644--- a/tests/unit/plugins/tool/test_app_command.py+++ b/tests/unit/plugins/tool/test_app_command.py@@ -63,17 +63,31 @@ def _fake_app(calls: dict) -> FastAPI:return app-def _tools(calls: dict | None = None) -> dict[str, object]:+def _config(*, ultrawiki: bool = True) -> SimpleNamespace:+ """A config stub for the capability gate.++ Passed explicitly so expansion never depends on whatever app a previously+ imported test left in ``runtime_refs`` — the gate reads the LIVE config by+ design, which makes it order-dependent unless a test pins it.+ """+ return SimpleNamespace(ultrawiki=SimpleNamespace(enabled=ultrawiki))+++def _tools(calls: dict | None = None, *, ultrawiki: bool = True) -> dict[str, object]:app = _fake_app(calls if calls is not None else {})loader = AppCommandTool(transport=httpx.ASGITransport(app=app),control_key_resolver=lambda: None,+ config_resolver=lambda: _config(ultrawiki=ultrawiki),)return {t.name: t for t in loader.expand()}def test_loader_expands_one_flat_tool_per_registry_command() -> None:- loader = AppCommandTool(control_key_resolver=lambda: None)+ loader = AppCommandTool(+ control_key_resolver=lambda: None,+ config_resolver=lambda: _config(ultrawiki=True),+ )assert loader.is_virtual_loader is Truetools = {t.name: t for t in loader.expand()}assert set(tools) == {c.id for c in get_registry()}@@ -424,3 +438,62 @@ async def test_installing_a_wallpaper_by_name_reports_what_landed() -> None:# verdict, not just an `ok: true` the model would have to interpret.assert response["state"] == "installed"assert response["ready"] is True+++# ---------------------------------------------------------------------------+# Capability gate — the 2026-08-24 "ultrawiki_ask FAILED 0.0s" forensic+# ---------------------------------------------------------------------------+++def test_ultrawiki_commands_withheld_while_the_mode_is_off() -> None:+ """A tool whose endpoint always refuses must not be offered at all.++ Live 10:13 (data/jarvis_desktop.log): asked what Jarvis version 2 can do,+ the realtime model called `ultrawiki_ask`, took `409 Conflict` in 0.0 s and+ ended the turn — with `wiki-recall` sitting unused in the same tool set.+ """+ off = _tools(ultrawiki=False)+ for command_id in (+ "ultrawiki-ask", "people-list", "person-profile", "identity-queue-list",+ ):+ assert command_id not in off++ # Everything that does not depend on the mode is untouched.+ assert "brain-switch" in off+ assert "wiki-ingest" in off+++def test_ultrawiki_commands_return_when_the_mode_is_on() -> None:+ """The gate subtracts only while the mode is off — it is not a deletion."""+ on = _tools(ultrawiki=True)+ assert "ultrawiki-ask" in on+ assert "people-list" in on+++async def test_mode_switched_off_mid_session_steers_to_the_wiki_tools() -> None:+ """A stale tool set must redirect, not fail.++ The mode switch applies live, so a session can hold a tool built while the+ mode was on. Re-checking at execute time turns the dead end into an+ instruction the model can act on within the same turn.+ """+ calls: dict = {}+ app = _fake_app(calls)+ # Built with the mode ON (the tool exists), executed with it OFF.+ enabled = {"value": True}+ loader = AppCommandTool(+ transport=httpx.ASGITransport(app=app),+ control_key_resolver=lambda: None,+ config_resolver=lambda: _config(ultrawiki=enabled["value"]),+ )+ tool = {t.name: t for t in loader.expand()}["ultrawiki-ask"]+ enabled["value"] = False++ result = await tool.execute({"question": "what can version 2 do"}, SimpleNamespace())++ assert result.success is False+ # The redirect names the tools that DO work, so the model has somewhere to go.+ assert "wiki-recall" in result.error+ assert result.output["capability"] == "ultrawiki"+ # Nothing was sent to the endpoint that would have refused it.+ assert calls == {}diff --git a/tests/unit/web/test_ultrawiki_routes.py b/tests/unit/web/test_ultrawiki_routes.pyindex 7c882d5b8b..3e362c570a 100644--- a/tests/unit/web/test_ultrawiki_routes.py+++ b/tests/unit/web/test_ultrawiki_routes.py@@ -25,6 +25,7 @@ import pytestfrom fastapi.testclient import TestClientfrom jarvis.core.bus import EventBus+from jarvis.core.events import BrainToolsChangedfrom jarvis.core.config import JarvisConfigfrom jarvis.ui.web.server import WebServerfrom jarvis.ui.web.ultrawiki_routes import ULTRAWIKI_ANSWER_STATUSES@@ -220,9 +221,62 @@ def test_status_answers_while_disabled(env) -> None:assert body["enabled"] is Falseassert body["started"] is Falseassert body["db_backend"] == "sqlite"- assert "search_legs" in body- assert body["search_legs"]["keyword"] == {"available": True}- assert body["search_legs"]["vector"]["available"] is False+ # The legs are NOT measured while the mode is off — see the next test.+ assert body["search_legs"]["probed"] is False+++def test_status_does_not_probe_the_search_legs_while_the_mode_is_off(+ env, monkeypatch+) -> None:+ """The probe is what made opening the Wiki section feel broken.++ This route is what the section asks before it can draw either body, and the+ leg probe walks credentials and touches the local embedding endpoint:+ measured 2026-08-24 at 0.7-2.1 s against under 150 ms for every other wiki+ route. On a first visit with nothing remembered, the section renders+ nothing for that whole span. Nothing reads the legs while the mode is off+ (only the Ultra body does, and it is not mounted), so the wait bought+ nothing at all.+ """+ from jarvis.ui.web import ultrawiki_routes++ probes: list[int] = []++ def _never(cfg): # pragma: no cover - the assertion is that this is unused+ probes.append(1)+ return {"keyword": {"available": True}}++ monkeypatch.setattr(ultrawiki_routes, "_search_legs", _never)++ body = env.client.get("/api/ultrawiki/status").json()++ assert probes == []+ assert body["search_legs"]["probed"] is False+ # Honest about WHY, so no client reads a missing leg as a broken one.+ assert "mode is off" in body["search_legs"]["reason"]+++def test_health_still_measures_the_legs_while_the_mode_is_off(env, monkeypatch) -> None:+ """The one caller that grades the legs must still pay for the probe.++ `health._search_check` reads an absent keyword leg as "search cannot+ answer" — a blocked verdict. A mode that is simply off is not an outage,+ so the checklist asks for the real measurement explicitly.+ """+ from jarvis.ui.web import ultrawiki_routes++ probes: list[int] = []++ def _probe(cfg):+ probes.append(1)+ return {"keyword": {"available": True}, "vector": {"available": False}}++ monkeypatch.setattr(ultrawiki_routes, "_search_legs", _probe)++ response = env.client.get("/api/ultrawiki/health")++ assert response.status_code == 200, response.text+ assert probes == [1]def test_activate_flips_mode_and_creates_pending_sources(env) -> None:@@ -1928,3 +1982,26 @@ def test_a_folder_source_that_imported_nothing_says_why(env) -> None:row = next(r for r in listing.json()["sources"] if r["id"] == source_id)assert row["last_notice"], "an empty import must explain itself"assert "folder" in row["last_notice"].lower()+++def test_switching_the_mode_tells_the_live_brain_its_tools_changed(env) -> None:+ """Activation must bring the UltraWiki tools BACK without a restart.++ The tool set is composed once per brain build, and the capability gate in+ `jarvis.commands.capabilities` withholds the four `/api/ultrawiki/*`+ commands while the mode is off. Without this event, switching the mode ON+ would leave them missing until the app restarts — the mirror image of the+ bug the gate exists to fix.+ """+ seen: list[str] = []+ env.server.bus.subscribe(+ BrainToolsChanged, lambda event: seen.append(event.reason)+ )++ _activate(env)++ assert any(reason == "ultrawiki_mode:on" for reason in seen), seen++ response = env.client.post("/api/ultrawiki/deactivate")+ assert response.status_code == 200, response.text+ assert any(reason == "ultrawiki_mode:off" for reason in seen), seen