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
feat(brain): app-command router tool — validated executor over the command registry
Ruben Lütkeead67a067555
diff --git a/docs/adr/0011-router-pure-dispatcher.md b/docs/adr/0011-router-pure-dispatcher.mdindex df1b413472..790fe2e842 100644--- a/docs/adr/0011-router-pure-dispatcher.md+++ b/docs/adr/0011-router-pure-dispatcher.md@@ -759,3 +759,46 @@ present (`warn_if_phantom_openclaw`).- `tests/unit/core/test_capabilities.py::test_dispatch_to_harness_capability_removed`/ `::test_no_capability_advertises_openclaw` / `::test_harness_adapters_present`- `tests/integration/test_dispatch_to_harness.py::test_unknown_harness_returns_neutral_error_no_inventory_leak`++## Amendment — `app-command` tool (Command Registry executor, 2026-07-09)++**Context.** Voice-driven app control had three uneven paths: the deterministic+pre-LLM gates (fast, but only for a hand-picked set), the self-mod+`set_config_value` tools, and free-form `cli_jarvisctl` strings composed by the+LLM — the least-validated route and the primary source of "the command did+something else" failures. Meanwhile the app's command surface lived in four+independent, hand-maintained registries (UI nav, CLI, brain tools, mirrored+constants — the AP-4 drift class).++**Decision.** `ROUTER_TOOLS` gains **`app-command`**+(`jarvis/plugins/tool/app_command.py`): a single structured executor over the+new Command Registry (`jarvis/commands/registry.py`). Constraints:++- `command_id` is **enum-constrained** to the curated registry — the LLM cannot+ invent a target; arguments are validated against the command's JSON schema+ BEFORE anything is sent.+- Execution goes through the SAME mounted REST endpoint the desktop UI uses,+ in-process via httpx `ASGITransport` (`runtime_refs.get_web_app()`) — one+ validation chain for voice, UI, and CLI.+- Registry commands flagged `dangerous` escalate to risk tier `ask` via+ `risk_tier_for_args` (ToolExecutor two-turn voice confirm); the rest run at+ `monitor`.+- The readback is composed from the SERVER RESPONSE (echo-verify), never from+ the model's intent.+- **No spawn path:** mission dispatch is deliberately NOT a registry command+ (spawning stays with `spawn-worker`); `app-command` is a direct gated action+ and must never enter a worker tool set (AP-5/AP-14).++The deterministic pre-LLM gates stay untouched — they remain the zero-latency+first line; `app-command` covers the validated long tail. `cli_jarvisctl`+remains as fallback for actions outside the registry.++### Regression guards++- `tests/unit/brain/test_routing.py::test_router_tools_is_pure_dispatcher_set`+ (exact-match set updated to include `app-command`)+- `tests/unit/brain/test_routing.py::test_factory_wires_app_command_into_router_set`+- `tests/unit/plugins/tool/test_app_command.py` — schema/enum validation,+ ASGI execution against a fake app, dangerous→ask escalation, server-response+ readback, honest no-server error.+- `tests/unit/commands/test_registry_parity.py` — registry↔OpenAPI/UI parity.diff --git a/jarvis/brain/factory.py b/jarvis/brain/factory.pyindex d31536d410..642130725d 100644--- a/jarvis/brain/factory.py+++ b/jarvis/brain/factory.py@@ -78,6 +78,13 @@ ROUTER_TOOLS = frozenset({# frontend listener moves the UI. Pure UI action, risk safe, NO spawn —# never in a worker set (AP-5/AP-14). See ADR-0011 amendment "Navigate tool"."navigate",+ # Command Registry executor (2026-07-09): run ONE curated app command+ # (jarvis/commands/registry.py) through the SAME REST endpoint the UI+ # uses, in-process via ASGI transport. Enum-constrained command_id ++ # schema-validated args; dangerous commands escalate to risk "ask"+ # (two-turn voice confirm). Direct gated action, never a spawn — never in+ # a worker set (AP-5/AP-14). See ADR-0011 amendment "app-command tool".+ "app-command",# Phase A1: synchronous state read on the AwarenessManager (Plan §5).# NO brain call, NO IO — property read only."awareness-snapshot",diff --git a/jarvis/brain/manager.py b/jarvis/brain/manager.pyindex 90b1647f2b..c0b5b12ab8 100644--- a/jarvis/brain/manager.py+++ b/jarvis/brain/manager.py@@ -1641,12 +1641,15 @@ _SELF_CONTROL_NOUN_RE = re.compile(_SELF_CONTROL_DIRECTIVE = ("SELF-CONTROL: The user is asking to change or control Jarvis's OWN settings, ""configuration, providers, voice, language, or behavior. You have full "- "control over this. Use the `cli_jarvisctl` tool — it performs ANY Jarvis "- "action via the local API (e.g. `jarvisctl brain switch <provider>`, "- "`jarvisctl config set <key> <value>`) — or `set_config_value` for a simple "- "setting. NEVER say you lack access or permission to change a Jarvis setting, "- "and never claim the change without actually calling the tool: call it and "- "confirm success only AFTER it returns."+ "control over this. PREFER the `app-command` tool — it runs a validated "+ "registry command (provider switches, wake word, languages, volume, "+ "missions/tasks, restart) with schema-checked arguments, so it cannot hit "+ "the wrong target. For a simple config key use `set_config_value`; only "+ "for actions NOT covered by either, fall back to the `cli_jarvisctl` tool "+ "(e.g. `jarvisctl config set <key> <value>`). NEVER say you lack access "+ "or permission to change a Jarvis setting, and never claim the change "+ "without actually calling the tool: call it and confirm success only "+ "AFTER it returns, using the values the tool actually reports.")diff --git a/jarvis/core/runtime_refs.py b/jarvis/core/runtime_refs.pyindex 1354ff79fe..30e6b54133 100644--- a/jarvis/core/runtime_refs.py+++ b/jarvis/core/runtime_refs.py@@ -80,6 +80,23 @@ def get_mcp_registry() -> Any | None:return _MCP_REGISTRY[0] if _MCP_REGISTRY else None+# The live FastAPI app (set by WebServer._build_app). The ``app-command`` tool+# executes Command-Registry commands through it in-process (httpx ASGI+# transport — full route validation, no TCP), so a voice command runs the+# exact same code path as the UI button for the same action.+_WEB_APP: list[Any] = []+++def set_web_app(app: Any) -> None:+ """Register the live FastAPI app (called from the WebServer build)."""+ _set(_WEB_APP, app)+++def get_web_app() -> Any | None:+ """The live FastAPI app, or ``None`` before the server is built."""+ return _WEB_APP[0] if _WEB_APP else None++# Wake-model load coordination (boot speed). When a CUSTOM wake phrase boots,# the light base/cpu wake model load competes for CPU/disk with non-urgent# boot-storm housekeeping (the deferred DocRegistry/SkillRegistry disk scans).@@ -185,6 +202,7 @@ def _reset_for_tests() -> None:_BRAIN_MANAGER.clear()_SPEECH_PIPELINE.clear()_MCP_REGISTRY.clear()+ _WEB_APP.clear()_ACTIVE_CHAT_TURN.clear()_WAKE_MODEL_EXPECTED.clear()_WAKE_MODEL_READY.clear()diff --git a/jarvis/plugins/tool/app_command.py b/jarvis/plugins/tool/app_command.pynew file mode 100644index 0000000000..ac780b6a97--- /dev/null+++ b/jarvis/plugins/tool/app_command.py@@ -0,0 +1,280 @@+"""``app-command`` — execute a Command-Registry command by voice/chat.++Router-tier. The ONE structured path for the LLM to drive app settings and+actions: the command id is enum-constrained to the curated registry+(``jarvis/commands/registry.py``), arguments are validated against the+command's JSON schema BEFORE anything is sent, and execution goes through the+SAME already-mounted REST endpoint the desktop UI uses (in-process ASGI+transport — full route validation, no TCP). A voice command therefore can+never behave differently from the UI button for the same action, and the+readback the brain speaks is composed from the SERVER RESPONSE (what actually+changed), never from the model's intent — echo-verify.++Dangerous commands (registry ``dangerous: true``) surface as risk tier+``ask`` via ``risk_tier_for_args``, which triggers the ToolExecutor's+two-turn spoken confirmation; everything else runs at ``monitor`` (audited,+reversible, no friction).++Security: the registry contains no raw-secret writes (AP-2) and no spawn+commands (mission dispatch stays with the dedicated spawn-worker tool,+AP-5/AP-14) — this tool must never enter a worker tool set.+"""+from __future__ import annotations++from typing import Any+from urllib.parse import quote++from jarvis.core.protocols import ToolResult++_TYPE_CHECKS: dict[str, type | tuple[type, ...]] = {+ "string": str,+ "boolean": bool,+ "number": (int, float),+ "integer": int,+ "object": dict,+}+++def _validate_args(schema: dict[str, Any], args: dict[str, Any]) -> list[str]:+ """Minimal, dependency-free JSON-schema check: unknown keys, required,+ enum membership, primitive types, string length, numeric range."""+ props = schema.get("properties", {}) if schema else {}+ errors: list[str] = []+ for key in args:+ if key not in props:+ errors.append(f"unknown argument {key!r} (valid: {sorted(props)})")+ for req in schema.get("required", []) if schema else []:+ if req not in args:+ errors.append(f"missing required argument {req!r}")+ for key, value in args.items():+ spec = props.get(key)+ if spec is None:+ continue+ enum = spec.get("enum")+ if enum and value not in enum:+ errors.append(f"{key!r} must be one of {enum}, got {value!r}")+ expected = _TYPE_CHECKS.get(spec.get("type", ""))+ if expected is not None:+ ok = isinstance(value, expected)+ # bool is an int subclass — do not let True pass as a number.+ if spec.get("type") in ("number", "integer") and isinstance(value, bool):+ ok = False+ if not ok:+ errors.append(f"{key!r} must be a {spec['type']}, got {type(value).__name__}")+ continue+ if isinstance(value, str):+ if "minLength" in spec and len(value) < spec["minLength"]:+ errors.append(f"{key!r} is too short (min {spec['minLength']})")+ if "maxLength" in spec and len(value) > spec["maxLength"]:+ errors.append(f"{key!r} is too long (max {spec['maxLength']})")+ if isinstance(value, (int, float)) and not isinstance(value, bool):+ if "minimum" in spec and value < spec["minimum"]:+ errors.append(f"{key!r} must be >= {spec['minimum']}")+ if "maximum" in spec and value > spec["maximum"]:+ errors.append(f"{key!r} must be <= {spec['maximum']}")+ return errors+++def _summarize(title: str, data: Any) -> str:+ """One honest sentence from the server's actual response payload."""+ if isinstance(data, dict):+ # Provider-switch family: name the real old -> new transition.+ new = data.get("active") or data.get("new_provider")+ if new:+ old = data.get("old_provider")+ summary = (+ f"{title}: {old} -> {new}." if old and old != new+ else f"{title}: now {new}."+ )+ if data.get("requires_restart") or data.get("restart_required"):+ summary += " Takes effect after the next restart."+ elif data.get("persisted") is False:+ summary += " Applied live only (not persisted to disk)."+ return summary+ if data.get("requires_restart") or data.get("restart_required"):+ return f"{title} done — takes effect after the next restart."+ return f"{title} succeeded."+++class AppCommandTool:+ """Execute a curated app command through its REST endpoint, in-process."""++ name: str = "app-command"+ risk_tier: str = "monitor"++ def __init__(+ self,+ app_resolver: Any | None = None,+ control_key_resolver: Any | None = None,+ transport: 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_resolver+ self._control_key_resolver = control_key_resolver+ self._transport = transport+ from jarvis.commands.registry import get_registry++ commands = get_registry()+ lines = "\n".join(+ f"- {c.id}: {c.description}" + (" [requires confirmation]" if c.dangerous else "")+ for c in commands+ )+ self.description = (+ "Run ONE app command from the command registry — the structured, "+ "validated way to change app settings or query app state by "+ "voice/chat (provider switches, wake word, languages, volume, "+ "missions/tasks, restart). Pass the command id in 'command_id' and "+ "its arguments in 'args' (see each command's schema via GET "+ "/api/commands). Prefer this over composing raw CLI strings. "+ "Commands:\n" + lines+ )+ self.schema: dict[str, Any] = {+ "type": "object",+ "properties": {+ "command_id": {+ "type": "string",+ "enum": [c.id for c in commands],+ "description": "The registry command to execute.",+ },+ "args": {+ "type": "object",+ "description": (+ "Arguments for the command, matching its params schema "+ "(e.g. {\"provider\": \"claude-api\"} for brain-switch)."+ ),+ },+ },+ "required": ["command_id"],+ }++ # ------------------------------------------------------------------+ # Risk refinement: dangerous registry commands need the two-turn confirm.+ # ------------------------------------------------------------------+ def risk_tier_for_args(self, args: dict[str, Any]) -> str:+ from jarvis.commands.registry import get_command++ cmd = get_command(str(args.get("command_id", "")))+ if cmd is None:+ return self.risk_tier+ return "ask" if cmd.dangerous else self.risk_tier++ # ------------------------------------------------------------------+ def _resolve_transport(self) -> Any | None:+ if self._transport is not None:+ return self._transport+ from jarvis.core import runtime_refs++ app = (+ self._app_resolver() if self._app_resolver is not None+ else runtime_refs.get_web_app()+ )+ if app is None:+ return None+ import httpx++ return httpx.ASGITransport(app=app)++ def _control_key(self) -> str | None:+ if self._control_key_resolver is not None:+ return self._control_key_resolver()+ try:+ from jarvis.core import control_key++ return control_key.get_control_key()+ except Exception: # noqa: BLE001 - most routes need no auth; degrade+ return None++ async def execute(self, args: dict[str, Any], ctx: Any) -> ToolResult:+ from jarvis.commands.registry import get_command, get_registry++ command_id = str(args.get("command_id", ""))+ cmd = get_command(command_id)+ if cmd is None:+ return ToolResult(+ success=False,+ output={"requested": command_id},+ error=(+ f"Unknown command id {command_id!r}. Valid ids: "+ + ", ".join(c.id for c in get_registry())+ ),+ )++ cmd_args = args.get("args") or {}+ if not isinstance(cmd_args, dict):+ return ToolResult(+ success=False, output=None,+ error="'args' must be an object of command arguments.",+ )+ problems = _validate_args(cmd.params, cmd_args)+ if problems:+ return ToolResult(+ success=False,+ output={"command_id": cmd.id, "args": cmd_args},+ error=(+ f"Invalid arguments for {cmd.id}: " + "; ".join(problems)+ + ". Nothing was executed."+ ),+ )++ url_path = cmd.path+ payload = dict(cmd_args)+ for p in cmd.path_params:+ url_path = url_path.replace(+ "{" + p + "}", quote(str(payload.pop(p)), safe="")+ )++ transport = self._resolve_transport()+ if transport is None:+ return ToolResult(+ success=False, output=None,+ error=(+ "The app server is not available in this runtime — use "+ "the desktop UI or the jarvis CLI instead."+ ),+ )++ import httpx++ headers = {}+ key = self._control_key()+ if key:+ headers["Authorization"] = f"Bearer {key}"+ try:+ async with httpx.AsyncClient(+ transport=transport, base_url="http://jarvis.internal",+ headers=headers, timeout=30.0,+ ) as client:+ if cmd.method.upper() == "GET":+ resp = await client.get(url_path, params=payload or None)+ else:+ resp = await client.request(+ cmd.method.upper(), url_path, json=payload or {}+ )+ except httpx.HTTPError as exc:+ return ToolResult(+ success=False, output={"command_id": cmd.id},+ error=f"{cmd.title} failed: transport error: {exc}",+ )++ try:+ data = resp.json() if resp.content else None+ except ValueError:+ data = resp.text++ if resp.status_code >= 400:+ detail = data.get("detail", data) if isinstance(data, dict) else data+ return ToolResult(+ success=False,+ output={"command_id": cmd.id, "status": resp.status_code},+ error=f"{cmd.title} failed: HTTP {resp.status_code}: {detail}",+ )++ return ToolResult(+ success=True,+ output={+ "command_id": cmd.id,+ "summary": _summarize(cmd.title, data),+ "response": data,+ },+ )diff --git a/jarvis/ui/web/server.py b/jarvis/ui/web/server.pyindex e7f55ae883..aee87039a4 100644--- a/jarvis/ui/web/server.py+++ b/jarvis/ui/web/server.py@@ -441,6 +441,13 @@ class WebServer:self._register_static_or_spa(app)+ # Publish the live app for in-process consumers: the app-command brain+ # tool executes Command-Registry commands through it via ASGI transport+ # (same routes + validation as the UI, no TCP).+ from jarvis.core import runtime_refs++ runtime_refs.set_web_app(app)+return appasync def _voice_ready_watchdog(self, deadline_s: float = 45.0) -> None:diff --git a/pyproject.toml b/pyproject.tomlindex a98dbc27e0..73aca6f693 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -428,6 +428,12 @@ inspect-pointer = "jarvis.plugins.tool.inspect_pointer:InspectPointerTool"# Publishes NavigateSidebar; the frontend switches the section. Never a spawn# (AP-5/AP-14). See ADR-0011 amendment "Navigate tool".navigate = "jarvis.plugins.tool.navigate:NavigateTool"+# Command Registry executor (2026-07-09) — run ONE curated app command+# (provider switch, wake word, language, volume, missions/tasks, restart)+# through the SAME REST endpoint the UI uses, in-process via ASGI. Enum-+# constrained + schema-validated; dangerous commands confirm (risk "ask").+# Never a spawn (AP-5/AP-14). See ADR-0011 amendment "app-command tool".+app-command = "jarvis.plugins.tool.app_command:AppCommandTool"# Phase A1 — Awareness layer L1 (synchronous state read for the router).awareness-snapshot = "jarvis.plugins.tool.awareness_snapshot:AwarenessSnapshotTool"# Phase A3 — Awareness-Layer L3 (BM25 search across recent episodes).diff --git a/tests/unit/brain/test_routing.py b/tests/unit/brain/test_routing.pyindex 60ee528c46..5fdbb4ec7f 100644--- a/tests/unit/brain/test_routing.py+++ b/tests/unit/brain/test_routing.py@@ -884,6 +884,37 @@ def test_factory_wires_navigate_into_router_set() -> None:assert tools["navigate"].risk_tier == "safe"+def test_factory_wires_app_command_into_router_set() -> None:+ """End-to-end wiring for the app-command tool: entry-point + ROUTER_TOOLS ++ default construction. A missing entry-point line or a failing registry+ import would silently drop the Command Registry from the router schema."""+ from jarvis.brain.factory import _load_tools_for_tier++ tools = _load_tools_for_tier(+ "router",+ bus=EventBus(),+ executor=None,+ harness_manager=None,+ user_profile=None,+ people=None,+ config=JarvisConfig(),+ )++ assert "app-command" in tools+ tool = tools["app-command"]+ assert tool.name == "app-command"+ assert tool.risk_tier == "monitor"+ # Dangerous registry commands escalate to the two-turn confirm tier.+ assert tool.risk_tier_for_args({"command_id": "app-restart"}) == "ask"+ assert tool.risk_tier_for_args({"command_id": "brain-switch"}) == "monitor"+ # The command ids the LLM may pick are enum-pinned to the registry.+ from jarvis.commands.registry import get_registry++ assert set(tool.schema["properties"]["command_id"]["enum"]) == {+ c.id for c in get_registry()+ }++def test_inspect_pointer_is_not_a_spawn_in_local_action_set() -> None:"""The AI-Pointer tool is a router-tier read, never in the worker fast-path."""from jarvis.brain.factory import _load_local_action_tools@@ -1602,6 +1633,11 @@ def test_router_tools_is_pure_dispatcher_set() -> None:# voice/chat. Pure UI action (risk safe), publishes NavigateSidebar,# never a spawn (AP-5/AP-14). See ADR-0011 amendment "Navigate tool"."navigate",+ # Command Registry executor (2026-07-09): one curated app command+ # through the same REST endpoint the UI uses (in-process ASGI).+ # Enum-constrained + schema-validated; dangerous -> risk "ask".+ # Never a spawn (AP-5/AP-14). ADR-0011 amendment "app-command tool".+ "app-command","awareness-snapshot",# Awareness Phase A3 (BM25 search over recent episode log)."awareness-recall",diff --git a/tests/unit/plugins/tool/test_app_command.py b/tests/unit/plugins/tool/test_app_command.pynew file mode 100644index 0000000000..38c26efa35--- /dev/null+++ b/tests/unit/plugins/tool/test_app_command.py@@ -0,0 +1,203 @@+"""app-command tool: enum/schema validation, in-process ASGI execution,+server-response readback (echo-verify), and honest degradation."""+from __future__ import annotations++import httpx+from fastapi import FastAPI, HTTPException++from jarvis.plugins.tool.app_command import AppCommandTool, _validate_args+++def _fake_app(calls: dict) -> FastAPI:+ app = FastAPI()++ @app.post("/api/brain/switch")+ async def brain_switch(body: dict) -> dict:+ calls["brain_switch"] = body+ return {+ "ok": True, "active": body["provider"], "old_provider": "openai",+ "persisted": True, "requires_restart": False,+ }++ @app.post("/api/tasks/{task_id}/cancel")+ async def cancel_task(task_id: str) -> dict:+ calls["cancel_task"] = task_id+ return {"ok": True}++ @app.get("/api/settings/wake-word")+ async def get_wake_word() -> dict:+ return {"phrase": "jarvis", "enabled": True}++ @app.post("/api/tts/switch")+ async def tts_switch(body: dict) -> dict:+ raise HTTPException(status_code=409, detail="no key stored")++ return app+++def _tool(calls: dict | None = None) -> AppCommandTool:+ app = _fake_app(calls if calls is not None else {})+ return AppCommandTool(+ transport=httpx.ASGITransport(app=app),+ control_key_resolver=lambda: None,+ )+++async def test_unknown_command_id_rejected_nothing_sent() -> None:+ calls: dict = {}+ result = await _tool(calls).execute({"command_id": "wipe-disk"}, None)+ assert result.success is False+ assert "Unknown command id" in (result.error or "")+ assert "brain-switch" in (result.error or "") # teaches valid ids+ assert calls == {}+++async def test_enum_violation_rejected_nothing_sent() -> None:+ """The exact 'switches to something completely different' failure mode:+ a provider outside the catalog must be rejected BEFORE any request."""+ calls: dict = {}+ result = await _tool(calls).execute(+ {"command_id": "brain-switch", "args": {"provider": "skynet"}}, None+ )+ assert result.success is False+ assert "must be one of" in (result.error or "")+ assert calls == {}+++async def test_missing_required_and_unknown_args_rejected() -> None:+ calls: dict = {}+ tool = _tool(calls)+ result = await tool.execute({"command_id": "brain-switch", "args": {}}, None)+ assert result.success is False+ assert "missing required argument" in (result.error or "")++ result = await tool.execute(+ {"command_id": "wake-word-get", "args": {"nonsense": 1}}, None+ )+ assert result.success is False+ assert "unknown argument" in (result.error or "")+ assert calls == {}+++async def test_post_executes_and_readback_uses_server_response() -> None:+ calls: dict = {}+ result = await _tool(calls).execute(+ {"command_id": "brain-switch", "args": {"provider": "openrouter"}}, None+ )+ assert result.success is True+ assert calls["brain_switch"]["provider"] == "openrouter"+ # Echo-verify: the summary names the transition the SERVER reported.+ assert "openai -> openrouter" in result.output["summary"]+ assert result.output["response"]["active"] == "openrouter"+++async def test_path_param_substitution() -> None:+ calls: dict = {}+ result = await _tool(calls).execute(+ {"command_id": "task-cancel", "args": {"task_id": "t-42"}}, None+ )+ assert result.success is True+ assert calls["cancel_task"] == "t-42"+++async def test_get_command_works() -> None:+ result = await _tool().execute({"command_id": "wake-word-get"}, None)+ assert result.success is True+ assert result.output["response"]["phrase"] == "jarvis"+++async def test_http_error_surfaces_detail() -> None:+ result = await _tool().execute(+ {"command_id": "tts-switch", "args": {"provider": "elevenlabs"}}, None+ )+ assert result.success is False+ assert "HTTP 409" in (result.error or "")+ assert "no key stored" in (result.error or "")+++async def test_no_server_available_is_honest() -> None:+ tool = AppCommandTool(+ app_resolver=lambda: None, control_key_resolver=lambda: None+ )+ result = await tool.execute(+ {"command_id": "brain-switch", "args": {"provider": "openrouter"}}, None+ )+ assert result.success is False+ assert "not available" in (result.error or "")+++def test_validator_covers_types_and_ranges() -> None:+ schema = {+ "type": "object",+ "properties": {+ "volume": {"type": "number", "minimum": 0.0, "maximum": 1.0},+ "phrase": {"type": "string", "minLength": 1, "maxLength": 4},+ "persist": {"type": "boolean"},+ },+ "required": ["volume"],+ }+ assert _validate_args(schema, {"volume": 0.5}) == []+ assert _validate_args(schema, {"volume": 2.0}) # above maximum+ assert _validate_args(schema, {"volume": True}) # bool is not a number+ assert _validate_args(schema, {"volume": 0.1, "phrase": ""}) # too short+ assert _validate_args(schema, {"volume": 0.1, "phrase": "abcde"}) # too long+ assert _validate_args(schema, {"volume": 0.1, "persist": "yes"}) # not bool+ assert _validate_args(schema, {}) # missing required+++async def test_dangerous_command_escalates_to_ask_tier() -> None:+ tool = _tool()+ assert tool.risk_tier == "monitor"+ assert tool.risk_tier_for_args({"command_id": "app-restart"}) == "ask"+ assert tool.risk_tier_for_args({"command_id": "mission-cancel"}) == "ask"+ assert tool.risk_tier_for_args({"command_id": "brain-switch"}) == "monitor"+ assert tool.risk_tier_for_args({"command_id": "nope"}) == "monitor"+++async def test_end_to_end_against_real_webserver_app() -> None:+ """The full chain: registry command -> ASGI -> the REAL /api/brain/switch+ route (shared app_control validation) -> readback from the route's+ response. Uses a fake live brain on app.state."""+ from jarvis.core import config as cfg_mod+ from jarvis.core.bus import EventBus+ from jarvis.core.config import JarvisConfig+ from jarvis.ui.web.server import WebServer++ class _FakeBrain:+ active_provider = "openai"+ last_persist_ok = False++ def available_providers(self):+ return ["openai", "openrouter"]++ async def switch(self, provider: str, *, persist: bool = False) -> None:+ self.active_provider = provider++ cfg = JarvisConfig()+ cfg.ui.dev_mode = True+ server = WebServer(cfg, bus=EventBus())+ server.app.state.brain = _FakeBrain()+ server.app.state.cfg = cfg++ real_get_secret = cfg_mod.get_secret+ cfg_mod.get_secret = lambda key, env_fallback=None: (+ "sk-test" if key == "openrouter_api_key" else None+ )+ try:+ tool = AppCommandTool(+ transport=httpx.ASGITransport(app=server.app),+ control_key_resolver=lambda: None,+ )+ result = await tool.execute(+ {"command_id": "brain-switch",+ "args": {"provider": "openrouter", "persist": False}},+ None,+ )+ finally:+ cfg_mod.get_secret = real_get_secret++ assert result.success is True, result.error+ assert result.output["response"]["active"] == "openrouter"+ # old_provider comes from cfg.brain.primary (shared app_control logic),+ # so only pin the destination side of the transition here.+ assert "-> openrouter" in result.output["summary"]