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(security): enforce execution, credential and lifecycle boundaries (#358)
Ruben Lütke473e21777016
diff --git a/board-backend/board_backend/background.py b/board-backend/board_backend/background.pyindex 077aa7bdf5..5fee904c92 100644--- a/board-backend/board_backend/background.py+++ b/board-backend/board_backend/background.py@@ -102,18 +102,59 @@ class FederationPuller:self._http = http_clientself._owns_http = http_client is Noneself._tasks: dict[str, asyncio.Task[None]] = {}+ self._targets: dict[str, tuple[str, int]] = {}self._last_results: dict[str, dict[str, Any]] = {}+ self._changed = asyncio.Event()+ self._scheduler: asyncio.Task[None] | None = None+ self._loop: asyncio.AbstractEventLoop | None = Noneasync def start(self) -> None:if self._http is None:self._http = httpx.AsyncClient(timeout=10.0)- # Poll all active friends.+ self._loop = asyncio.get_running_loop()+ await self._reconcile()+ if self._scheduler is None or self._scheduler.done():+ self._scheduler = asyncio.create_task(self._schedule(), name="fed-scheduler")++ def friends_changed(self) -> None:+ """Wake the scheduler safely from synchronous route threads."""+ if self._loop is not None:+ self._loop.call_soon_threadsafe(self._changed.set)++ async def _schedule(self) -> None:+ while True:+ try:+ await asyncio.wait_for(self._changed.wait(), timeout=60)+ except TimeoutError:+ pass # Periodic reconciliation also catches out-of-band DB edits.+ self._changed.clear()+ try:+ await self._reconcile()+ except Exception:+ log.exception("federation scheduler reconciliation failed")++ async def _reconcile(self) -> None:with self._sf() as session:friends = session.query(Friend).all()- for f in friends:- self._spawn_for(f)+ desired = {f"{f.owner_pubkey}|{f.friend_pubkey}": f for f in friends}+ for key, task in list(self._tasks.items()):+ friend = desired.get(key)+ target = (friend.friend_url, friend.pull_interval_s) if friend else None+ if target != self._targets[key] or task.done():+ task.cancel()+ await asyncio.gather(task, return_exceptions=True)+ del self._tasks[key]+ del self._targets[key]+ self._last_results.pop(key, None)+ for friend in friends:+ self._spawn_for(friend)async def stop(self) -> None:+ self._loop = None+ if self._scheduler is not None:+ self._scheduler.cancel()+ await asyncio.gather(self._scheduler, return_exceptions=True)+ self._scheduler = Nonefor t in list(self._tasks.values()):t.cancel()for t in list(self._tasks.values()):@@ -122,30 +163,41 @@ class FederationPuller:except (asyncio.CancelledError, Exception):passself._tasks.clear()+ self._targets.clear()if self._owns_http and self._http is not None:await self._http.aclose()+ self._http = Nonedef _spawn_for(self, friend: Friend) -> None:key = f"{friend.owner_pubkey}|{friend.friend_pubkey}"if key in self._tasks and not self._tasks[key].done():returnself._tasks[key] = asyncio.create_task(- self._friend_loop(friend.friend_pubkey, friend.friend_url, friend.pull_interval_s),+ self._friend_loop(+ friend.owner_pubkey, friend.friend_pubkey,+ friend.friend_url, friend.pull_interval_s,+ ),name=f"fed-pull-{friend.friend_pubkey[:8]}",)+ self._targets[key] = (friend.friend_url, friend.pull_interval_s)- async def _friend_loop(self, friend_pubkey: str, friend_url: str, interval_s: int) -> None:+ async def _friend_loop(+ self, owner_pubkey: str, friend_pubkey: str, friend_url: str, interval_s: int,+ ) -> None:+ key = f"{owner_pubkey}|{friend_pubkey}"while True:try:items = await self._pull_once(friend_url)- self._last_results[friend_pubkey] = {+ self._last_results[key] = {"items_count": len(items),"fetched_at": datetime.now(timezone.utc).isoformat(),+ "ok": True,}- self._update_last_pull(friend_pubkey)+ self._update_last_pull(owner_pubkey, friend_pubkey)except asyncio.CancelledError:raiseexcept Exception: # noqa: BLE001+ self._last_results[key] = {"ok": False, "error": "pull_failed"}log.exception("federation pull from %s failed", friend_url)try:await asyncio.sleep(max(60, interval_s))@@ -153,25 +205,19 @@ class FederationPuller:raiseasync def _pull_once(self, friend_url: str) -> list[Any]:- """Anonymous pull — the feed itself filters visibility=public.-- For an authenticated friend pull we'd need the local privkey +- pubkey, which the backend doesn't have (see the reactions note).- Phase D MVP: public items only. Phase D full build-out: the local- Jarvis supplies the backend a scoped auth header per friend.- """+ """Pull the explicitly public feed; signed friend data stays separate."""assert self._http is not None- resp = await self._http.get(f"{friend_url.rstrip('/')}/api/v1/federation/feed",+ resp = await self._http.get(f"{friend_url.rstrip('/')}/api/v1/federation/public-feed",params={"sort": "interesting"})- if resp.status_code != 200:- return []- return resp.json().get("items", [])+ resp.raise_for_status()+ items = resp.json()["items"]+ if not isinstance(items, list):+ raise ValueError("invalid federation feed")+ return items- def _update_last_pull(self, friend_pubkey: str) -> None:+ def _update_last_pull(self, owner_pubkey: str, friend_pubkey: str) -> None:with self._sf() as session:- row = session.query(Friend).filter(- Friend.friend_pubkey == friend_pubkey- ).first()+ row = session.get(Friend, (owner_pubkey, friend_pubkey))if row is not None:row.last_pull_at = datetime.now(timezone.utc)session.commit()diff --git a/board-backend/board_backend/routes/activity.py b/board-backend/board_backend/routes/activity.pyindex aba4261094..7cf03fed5e 100644--- a/board-backend/board_backend/routes/activity.py+++ b/board-backend/board_backend/routes/activity.py@@ -156,6 +156,22 @@ def federation_feed(``server_now`` of their last pull and pass it in as ``since`` on thenext one, so the backend only has to serialize the diffs."""+ return _federation_feed(request, sort, since, viewer_pubkey=auth.viewer_pubkey)+++@fed_router.get("/public-feed", response_model=FeedResponse)+def public_federation_feed(+ request: Request,+ sort: str = Query("interesting", pattern=r"^(interesting|latest)$"),+ since: str | None = Query(None),+) -> FeedResponse:+ """Anonymous background synchronization of public activity only."""+ return _federation_feed(request, sort, since, viewer_pubkey="")+++def _federation_feed(+ request: Request, sort: str, since: str | None, *, viewer_pubkey: str,+) -> FeedResponse:since_dt = Noneif since is not None:try:@@ -167,8 +183,10 @@ def federation_feed(with get_db(request) as session:owner = get_owner_identity(session)- is_owner = (auth.viewer_pubkey == owner.pubkey)- is_friend = is_owner or _is_friend(session, owner.pubkey, auth.viewer_pubkey)+ is_owner = bool(viewer_pubkey) and viewer_pubkey == owner.pubkey+ is_friend = is_owner or (+ bool(viewer_pubkey) and _is_friend(session, owner.pubkey, viewer_pubkey)+ )# SQL filter — Plan §D ALGORITHM TRANSPARENT BY DESIGNclauses = [ActivityItem.visibility == "public"]@@ -192,7 +210,7 @@ def federation_feed(_item_to_dto(it,owner_display=owner.display_name,- viewer_pubkey=auth.viewer_pubkey,+ viewer_pubkey=viewer_pubkey,counts=_count_reactions(session, it.id),session=session,)@@ -296,4 +314,4 @@ def _item_to_dto(expires_at=item.expires_at,reaction_counts=counts if is_owner else None,has_reactions=any(v > 0 for v in counts.values()),- )\ No newline at end of file+ )diff --git a/board-backend/board_backend/routes/forget_me.py b/board-backend/board_backend/routes/forget_me.pyindex f2bb6a4719..edb06728b0 100644--- a/board-backend/board_backend/routes/forget_me.py+++ b/board-backend/board_backend/routes/forget_me.py@@ -60,6 +60,9 @@ def forget_me(session.commit()+ puller = getattr(request.app.state, "federation_puller", None)+ if puller is not None:+ puller.friends_changed()return ForgetMeAck(deleted_friendship=deleted_friendship,deleted_activities=deleted_activities,diff --git a/board-backend/board_backend/routes/pair.py b/board-backend/board_backend/routes/pair.pyindex f953780c34..c8f95dfa98 100644--- a/board-backend/board_backend/routes/pair.py+++ b/board-backend/board_backend/routes/pair.py@@ -118,6 +118,7 @@ def accept(request: Request, payload: PairAcceptRequest) -> PairAcceptResponse:session.commit()+ _notify_puller(request)public_url = _public_url_for_owner(request)return PairAcceptResponse(accepted=True,@@ -180,6 +181,7 @@ def update_friend(row.pull_interval_s = body.pull_interval_ssession.commit()session.refresh(row)+ _notify_puller(request)return FriendItem(pubkey=row.friend_pubkey,url=row.friend_url,@@ -194,6 +196,12 @@ def update_friend(# Helpers# ----------------------------------------------------------------------+def _notify_puller(request: Request) -> None:+ puller = getattr(request.app.state, "federation_puller", None)+ if puller is not None:+ puller.friends_changed()++def _aware(dt: datetime) -> datetime:"""SQLite returns datetimes without a tz — we add UTC."""if dt.tzinfo is None:@@ -212,4 +220,4 @@ def _public_url_for_owner(request: Request) -> str:forwarded_host = request.headers.get("x-forwarded-host")scheme = forwarded_proto or request.url.schemehost = forwarded_host or request.headers.get("host") or "localhost:8765"- return f"{scheme}://{host}"\ No newline at end of file+ return f"{scheme}://{host}"diff --git a/board-backend/tests/test_federation_puller.py b/board-backend/tests/test_federation_puller.pynew file mode 100644index 0000000000..2e60a06656--- /dev/null+++ b/board-backend/tests/test_federation_puller.py@@ -0,0 +1,110 @@+"""Two isolated backends agree on anonymous public-feed synchronization."""++import asyncio+from datetime import UTC, datetime, timedelta++import httpx+import pytest+from board_backend.background import FederationPuller+from board_backend.config import Settings+from board_backend.main import create_app+from board_backend.models import ActivityItem, Friend, Identity+++def backend(path, owner):+ app = create_app(settings=Settings(admin_token="fixture-admin", db_path=path)) # noqa: S106+ app.state.disable_background = True+ with app.state.session_factory() as session:+ session.add(Identity(pubkey=owner, display_name="Fixture"))+ session.commit()+ return app+++async def until(predicate):+ async with asyncio.timeout(2):+ while not predicate(): # noqa: ASYNC110 - bounded polling of scheduler state under test+ await asyncio.sleep(0.01)+++async def test_public_pull_sync_and_live_friend_rescheduling(tmp_path):+ local = backend(tmp_path / "local.db", "a" * 64)+ remote = backend(tmp_path / "remote.db", "b" * 64)+ sf = local.state.session_factory+ with remote.state.session_factory() as session:+ for visibility in ("public", "friends", "private"):+ session.add(+ ActivityItem(+ id=visibility, author_pubkey="b" * 64, kind="milestone", visibility=visibility+ )+ )+ session.add(+ ActivityItem(+ id="expired",+ author_pubkey="b" * 64,+ kind="story",+ visibility="public",+ expires_at=datetime.now(UTC) - timedelta(hours=1),+ )+ )+ session.commit()+ async with httpx.AsyncClient(+ transport=httpx.ASGITransport(app=remote), base_url="http://remote"+ ) as client:+ puller = FederationPuller(session_factory=sf, http_client=client)+ await puller.start()+ try:+ # The signed endpoint keeps its existing authentication contract.+ assert (await client.get("/api/v1/federation/feed")).status_code == 422+ assert [item["id"] for item in await puller._pull_once("http://remote")] == ["public"]+ with sf() as session:+ session.add(+ Friend(+ owner_pubkey="a" * 64, friend_pubkey="b" * 64, friend_url="http://remote"+ )+ )+ session.commit()+ puller.friends_changed()+ key = "a" * 64 + "|" + "b" * 64+ await until(lambda: puller.last_results.get(key, {}).get("ok"))+ first_task = puller._tasks[key]+ with sf() as session:+ friend = session.get(Friend, ("a" * 64, "b" * 64))+ assert friend.last_pull_at is not None+ friend.pull_interval_s = 300+ session.commit()+ puller.friends_changed()+ await until(lambda: puller._tasks.get(key) is not first_task)+ assert first_task.done()+ with sf() as session:+ session.delete(session.get(Friend, ("a" * 64, "b" * 64)))+ session.commit()+ puller.friends_changed()+ await until(lambda: not puller._tasks)+ finally:+ await puller.stop()+ assert puller._scheduler is None+++async def test_rejected_pull_does_not_record_success(tmp_path):+ local = backend(tmp_path / "local.db", "a" * 64)+ sf = local.state.session_factory+ with sf() as session:+ session.add(+ Friend(owner_pubkey="a" * 64, friend_pubkey="b" * 64, friend_url="http://remote")+ )+ session.commit()+ async with httpx.AsyncClient(+ transport=httpx.MockTransport(lambda request: httpx.Response(401))+ ) as client:+ puller = FederationPuller(session_factory=sf, http_client=client)+ await puller.start()+ try:+ key = "a" * 64 + "|" + "b" * 64+ await until(lambda: key in puller.last_results)+ assert puller.last_results[key] == {"ok": False, "error": "pull_failed"}+ with sf() as session:+ assert session.get(Friend, ("a" * 64, "b" * 64)).last_pull_at is None+ finally:+ await puller.stop()diff --git a/jarvis/agent_chat/folder_tools.py b/jarvis/agent_chat/folder_tools.pyindex f229378f72..db88b0fea4 100644--- a/jarvis/agent_chat/folder_tools.py+++ b/jarvis/agent_chat/folder_tools.py@@ -54,6 +54,7 @@ class FolderTool:self.description: str = str(spec.get("description") or self.name)self.schema: dict[str, Any] = dict(spec.get("input_schema") or {"type": "object"})self.risk_tier: RiskTier = risk_tier+ self.read_only = self.name in folder.READ_ONLY_TOOLSself._cwd = cwd@property@@ -96,21 +97,13 @@ def folder_tools(cwd: Path, *, stance: str = "ask") -> dict[str, Tool]:def plan_filter(tools: dict[str, Tool]) -> dict[str, Tool]:"""Plan mode's tool surface: whatever only reads.- Keeps a tool whose static tier is ``safe`` — reads, lookups, recall —- and drops everything that acts (``monitor`` and up). A tool with a- per-call tier hook (``risk_tier_for_args``) is treated by its static- tier: a mixed tool whose default is a read stays, one whose default is- an action goes.+ Only tools with an explicit read capability are offered. Mixed tools+ declare an argument-aware capability, which the executor checks again+ for the actual call. Risk tiers and display summaries grant no authority."""from jarvis.core.tool_read_only import allows_read- return {- name: tool- for name, tool in tools.items()- if allows_read(tool)- or name not in FOLDER_RISK_TIERS- and callable(getattr(tool, "describe_args", None))- }+ return {name: tool for name, tool in tools.items() if allows_read(tool)}__all__ = ["FOLDER_RISK_TIERS", "PLAN_STANCE", "FolderTool", "folder_tools", "plan_filter"]diff --git a/jarvis/brain/tools/self_mod_tools.py b/jarvis/brain/tools/self_mod_tools.pyindex d592eda2a2..2698974e4d 100644--- a/jarvis/brain/tools/self_mod_tools.py+++ b/jarvis/brain/tools/self_mod_tools.py@@ -90,6 +90,8 @@ class ListMutableSettingsTool:`set_config_value` and Phase-7.5 skill authoring)."""+ read_only = True+name: ClassVar[str] = "list_mutable_settings"risk_tier: ClassVar[str] = "safe"description: ClassVar[str] = (@@ -155,6 +157,8 @@ class GetConfigValueTool:Denies `security.*` paths even for reads (Plan-§AP-9 hash-leak protection)."""+ read_only = True+name: ClassVar[str] = "get_config_value"risk_tier: ClassVar[str] = "safe"description: ClassVar[str] = (@@ -167,7 +171,7 @@ class GetConfigValueTool:"path": {"type": "string","minLength": 1,- "description": "Dotted-Pfad in jarvis.toml, z.B. 'tts.provider'.",+ "description": "Dotted path in jarvis.toml, e.g. 'tts.provider'.",},},"required": ["path"],@@ -285,8 +289,8 @@ class SetConfigValueTool:"reason": {"type": "string","description": (- "Kurzer human-readable Grund. Leerer String erlaubt, aber "- "Pflicht-Feld (strict-Mode)."+ "Short human-readable reason. An empty string is allowed, "+ "but the field is required in strict mode."),},},diff --git a/jarvis/brain/workspace_tool.py b/jarvis/brain/workspace_tool.pyindex ed6c017acc..6af3159407 100644--- a/jarvis/brain/workspace_tool.py+++ b/jarvis/brain/workspace_tool.py@@ -183,6 +183,9 @@ class WorkspaceOrchestrationTool:reads = {"inspect", "resolve", "context", "observe"}return "safe" if args.get("action") in reads else "monitor"+ def read_only_for_args(self, args: dict) -> bool:+ return args.get("action") in {"inspect", "resolve", "context", "observe"}+def describe_args(self, args: dict) -> dict:return {"level": "read" if self.risk_tier_for_args(args) == "safe" else "modify",diff --git a/jarvis/core/tool_read_only.py b/jarvis/core/tool_read_only.pyindex e4d9e9c0b6..cdefb9c3f6 100644--- a/jarvis/core/tool_read_only.py+++ b/jarvis/core/tool_read_only.py@@ -20,13 +20,18 @@ def chat_is_read_only(session_id: str) -> bool:def allows_read(tool: Any, args: dict[str, Any] | None = None) -> bool:- # A safe-tier message sender is still an action. Tier alone is not a read proof.- describe = getattr(tool, "describe_args", None)- if args is not None and callable(describe):+ """Use trusted tool metadata, never a presentation/command heuristic.++ Mixed tools declare a separate argument-aware capability. Neither risk+ tiers nor remote presentation metadata establish read authority.+ """+ capability = getattr(tool, "read_only_for_args", None)+ if callable(capability):+ if args is None:+ return Truetry:- description = describe(args)+ return capability(args) is Trueexcept Exception:- # Unclassifiable calls are refused in this restrictive mode.+ # A broken capability cannot grant permissions in a restrictive mode.return False- return isinstance(description, dict) and description.get("level") == "read"- return not getattr(tool, "is_action_tool", False) and getattr(tool, "risk_tier", None) == "safe"+ return getattr(tool, "read_only", False) is Truediff --git a/jarvis/marketplace/catalog_data.py b/jarvis/marketplace/catalog_data.pyindex 1c8d9f96b1..1c17b0b899 100644--- a/jarvis/marketplace/catalog_data.py+++ b/jarvis/marketplace/catalog_data.py@@ -276,5 +276,12 @@ def load_catalog(path: Path | None = None) -> PluginCatalog:return PluginCatalog.model_validate(raw)+@lru_cache(maxsize=1)+def load_seed_catalog() -> PluginCatalog:+ """Package-owned identities and endpoints, without runtime overrides."""+ return _read(_PACKAGE_SEED_PATH)++def clear_cache() -> None:load_catalog.cache_clear()+ load_seed_catalog.cache_clear()diff --git a/jarvis/marketplace/connect_helpers.py b/jarvis/marketplace/connect_helpers.pyindex beffebc9a1..17536b164a 100644--- a/jarvis/marketplace/connect_helpers.py+++ b/jarvis/marketplace/connect_helpers.py@@ -58,19 +58,27 @@ _OAUTH_CLIENT_FAMILY: dict[str, str] = {def oauth_client_family(plugin_id: str) -> str | None:"""Return the BYO-OAuth-client secret family for a plugin, or ``None``.- Catalog field first, legacy table second. One resolver so the connect- route, the refresh scheduler and the frontend cannot drift apart.+ Shared secrets belong only to package-owned identities and exact OAuth+ endpoints. Community metadata and custom endpoints cannot claim a family.+ The connect, refresh and grant-sharing paths use this same boundary."""try:- from jarvis.marketplace.catalog_data import load_catalog+ from jarvis.marketplace.catalog_data import load_catalog, load_seed_catalogspec = load_catalog().by_id(plugin_id)+ trusted = load_seed_catalog().by_id(plugin_id)except Exception: # noqa: BLE001 - a broken catalog must not break refresh- spec = None- declared = getattr(spec, "oauth_client_family", None) if spec else None- if declared:- return str(declared)- return _OAUTH_CLIENT_FAMILY.get(plugin_id)+ log.warning("OAuth family resolution unavailable for %s", plugin_id)+ return None+ if spec is None or trusted is None or getattr(spec, "source", None) != "seed":+ return None+ for field in ("mode", "authorization_url", "token_url", "device_url", "verify_url"):+ if getattr(spec.auth, field, None) != getattr(trusted.auth, field, None):+ return None+ family = trusted.oauth_client_family or _OAUTH_CLIENT_FAMILY.get(plugin_id)+ if spec.oauth_client_family not in (None, family):+ return None+ return familydef is_placeholder_client_id(value: str | None) -> bool:diff --git a/jarvis/plugins/tool/app_action.py b/jarvis/plugins/tool/app_action.pyindex e3cadd5e12..bea49ab5c2 100644--- a/jarvis/plugins/tool/app_action.py+++ b/jarvis/plugins/tool/app_action.py@@ -54,6 +54,8 @@ def _in_area(entries: list[Any], area: str) -> list[Any]:class FindAppActionTool:"""Search every action of the Jarvis app by keywords."""+ read_only = True+name: str = "find-app-action"risk_tier: str = "safe"description: str = (diff --git a/jarvis/plugins/tool/contact_lookup.py b/jarvis/plugins/tool/contact_lookup.pyindex dd94bc80b8..75bf5a3264 100644--- a/jarvis/plugins/tool/contact_lookup.py+++ b/jarvis/plugins/tool/contact_lookup.py@@ -46,6 +46,8 @@ log = logging.getLogger(__name__)class ContactLookupTool:"""Router-tier resolver: name/alias -> a contact's e-mails/phones/address."""+ read_only = True+name: str = "contact-lookup"description: str = ("Look up a saved contact by name or alias and return their e-mail "diff --git a/jarvis/plugins/tool/describe_app_settings.py b/jarvis/plugins/tool/describe_app_settings.pyindex 765fddd653..dc2a46427f 100644--- a/jarvis/plugins/tool/describe_app_settings.py+++ b/jarvis/plugins/tool/describe_app_settings.py@@ -24,6 +24,8 @@ log = logging.getLogger(__name__)class DescribeAppSettingsTool:"""Read-only overview of the live Desktop App configuration."""+ read_only = True+name: ClassVar[str] = "describe-app-settings"risk_tier: ClassVar[str] = "safe"description: ClassVar[str] = (diff --git a/jarvis/plugins/tool/inspect_pointer.py b/jarvis/plugins/tool/inspect_pointer.pyindex 0746237c77..b4e2273190 100644--- a/jarvis/plugins/tool/inspect_pointer.py+++ b/jarvis/plugins/tool/inspect_pointer.py@@ -26,6 +26,8 @@ ResolveFn = Callable[[], Awaitable[PointerContext]]class InspectPointerTool:"""Read the accessibility element currently under the mouse cursor."""+ read_only = True+name: str = "inspect-pointer"risk_tier: str = "safe"description: str = (diff --git a/jarvis/plugins/tool/product_help.py b/jarvis/plugins/tool/product_help.pyindex 1a205a7974..0875ff4fbd 100644--- a/jarvis/plugins/tool/product_help.py+++ b/jarvis/plugins/tool/product_help.py@@ -59,6 +59,8 @@ def _guide(doc: Any) -> dict[str, Any]:class ProductHelpTool:+ read_only = True+name = "product_help"description = ("Read Personal Jarvis's built-in user guide: what a feature does, how to set it up, "diff --git a/jarvis/plugins/tool/read_visible_ui_state.py b/jarvis/plugins/tool/read_visible_ui_state.pyindex df0bb5b4b8..d93ee7550a 100644--- a/jarvis/plugins/tool/read_visible_ui_state.py+++ b/jarvis/plugins/tool/read_visible_ui_state.py@@ -18,6 +18,8 @@ from jarvis.core.protocols import ExecutionContext, ToolResultclass ReadVisibleUIStateTool:+ read_only = True+name: str = "read_visible_ui_state"risk_tier: str = "safe"description: str = (diff --git a/jarvis/plugins/tool/run_shell.py b/jarvis/plugins/tool/run_shell.pyindex 5a18d7da13..faaaaa18b5 100644--- a/jarvis/plugins/tool/run_shell.py+++ b/jarvis/plugins/tool/run_shell.py@@ -35,7 +35,7 @@ from typing import Anyfrom jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGSfrom jarvis.core.protocols import ExecutionContext, ToolResultfrom jarvis.safety.command_impact import DESTRUCTIVE, classify_command-from jarvis.safety.explicit_intent import utterance_confirms_destruction+from jarvis.safety.explicit_intent import command_confirms_destructionif sys.platform == "win32":_SHELL_LABEL = "Windows PowerShell 5.1"@@ -123,6 +123,7 @@ def _powershell_argv(command: str) -> list[str]:class RunShellTool:name: str = "run_shell"+ read_only: bool = Falserisk_tier: str = "monitor"description: str = (f"Runs a shell command via {_SHELL_LABEL} on this machine. "@@ -170,17 +171,14 @@ class RunShellTool:def intent_confirms_args(self, args: dict[str, Any], utterance: str) -> bool:"""True when the user's own words already authorize this command.- Claude-Code permission model: a destructive command the USER asked- for by name ("delete the folder Urlaub") needs no second question —- the ToolExecutor consults this hook before arming a confirmation.- Only the destruction verb-class is matched (deterministic vocabulary,- no entity matching — STT garbles names); a brain-initiated deletion- whose utterance never mentioned deleting still confirms.+ Only an unambiguous single deletion of the exact absolute path named+ by the user can waive approval. Inferred targets and general shell+ programs keep the ordinary confirmation workflow."""command = (args.get("command") or "").strip()if not command or classify_command(command).level != DESTRUCTIVE:return False- return utterance_confirms_destruction(utterance)+ return command_confirms_destruction(command, utterance)def describe_args(self, args: dict[str, Any]) -> dict[str, str] | None:"""Plain-language impact summary for the confirmation question.diff --git a/jarvis/plugins/tool/search_web.py b/jarvis/plugins/tool/search_web.pyindex 264aa08a29..e218f7ae5e 100644--- a/jarvis/plugins/tool/search_web.py+++ b/jarvis/plugins/tool/search_web.py@@ -299,9 +299,11 @@ async def _weather_results(query: str, client: Any) -> list[dict[str, Any]] | Noclass SearchWebTool:+ read_only = True+name: str = "search_web"risk_tier: str = "safe"- # [Frische-Grenze, 2026-06-20] search_web is for FRESH, time-sensitive facts+ # [Freshness boundary, 2026-06-20] search_web is for FRESH, time-sensitive facts# ONLY — evergreen / general knowledge is answered directly by the brain.# Forensic: "what do I need to consider when emigrating abroad?" fired# search_web 3x with an empty answer (sessions.db voice session e0898d6e,diff --git a/jarvis/plugins/tool/wait_for_element.py b/jarvis/plugins/tool/wait_for_element.pyindex 6879159fc3..3355bca55d 100644--- a/jarvis/plugins/tool/wait_for_element.py+++ b/jarvis/plugins/tool/wait_for_element.py@@ -29,6 +29,8 @@ _MAX_TIMEOUT_S = 60.0class WaitForElementTool:+ read_only = True+name: str = "wait_for_element"risk_tier: str = "safe"description: str = (diff --git a/jarvis/plugins/tool/wait_for_ui_state.py b/jarvis/plugins/tool/wait_for_ui_state.pyindex b3b50ea946..743d7bc508 100644--- a/jarvis/plugins/tool/wait_for_ui_state.py+++ b/jarvis/plugins/tool/wait_for_ui_state.py@@ -24,6 +24,8 @@ _MAX_TIMEOUT_S = 60.0class WaitForUIStateTool:+ read_only = True+name: str = "wait_for_ui_state"risk_tier: str = "safe"description: str = (diff --git a/jarvis/plugins/tool/whoami.py b/jarvis/plugins/tool/whoami.pyindex 8b5ef7581d..88e127fa5f 100644--- a/jarvis/plugins/tool/whoami.py+++ b/jarvis/plugins/tool/whoami.py@@ -19,6 +19,8 @@ from jarvis.memory.user_profile import UserProfileclass WhoAmITool:+ read_only = True+name: str = "whoami"risk_tier: str = "safe"description: str = (@@ -92,7 +94,7 @@ class WhoAmITool:return ToolResult(success=True, output=text)# ------------------------------------------------------------------- # Rendering — bewusst als reine Logik, damit unit-testbar+ # Rendering stays pure so it can be unit tested.# ------------------------------------------------------------------def _render_summary(self, meta: dict[str, Any], detail_level: str) -> str:diff --git a/jarvis/plugins/tool/wiki_list.py b/jarvis/plugins/tool/wiki_list.pyindex d9ba659636..770da8be45 100644--- a/jarvis/plugins/tool/wiki_list.py+++ b/jarvis/plugins/tool/wiki_list.py@@ -78,6 +78,8 @@ def _first_heading_and_meta(path: Path) -> tuple[str, bool]:class WikiListTool:"""Router-tier ground-truth listing of the long-term Obsidian wiki vault."""+ read_only = True+name: str = "wiki-list"description: str = ("List what ACTUALLY exists in the user's long-term Obsidian wiki "diff --git a/jarvis/plugins/tool/wiki_page_read.py b/jarvis/plugins/tool/wiki_page_read.pyindex d33be8c1ab..09d00d305f 100644--- a/jarvis/plugins/tool/wiki_page_read.py+++ b/jarvis/plugins/tool/wiki_page_read.py@@ -73,6 +73,8 @@ def _frontmatter_declares_meta(content: str) -> bool:class WikiPageReadTool:"""Router-tier full-page reader for the long-term Obsidian wiki vault."""+ read_only = True+name: str = "wiki-page-read"description: str = ("Read a single page from the user's long-term Obsidian wiki, in full. "diff --git a/jarvis/plugins/tool/wiki_recall.py b/jarvis/plugins/tool/wiki_recall.pyindex 450d4d2e34..f7b5b9da8f 100644--- a/jarvis/plugins/tool/wiki_recall.py+++ b/jarvis/plugins/tool/wiki_recall.py@@ -46,6 +46,8 @@ log = logging.getLogger(__name__)class WikiRecallTool:"""Router-tier keyword search over the long-term Obsidian wiki vault."""+ read_only = True+name: str = "wiki-recall"description: str = ("Search the user's long-term Obsidian wiki for notes matching keywords. "diff --git a/jarvis/safety/explicit_intent.py b/jarvis/safety/explicit_intent.pyindex 88f3d6c82b..a91170180d 100644--- a/jarvis/safety/explicit_intent.py+++ b/jarvis/safety/explicit_intent.py@@ -1,54 +1,56 @@-"""Deterministic check: did the USER explicitly ask for the destructive act?+"""Conservative, target-bound authorization for a single shell deletion.-The Claude-Code permission model, adapted for voice (Ruben's mandate,-2026-08-08): harmless commands run silently, destructive commands confirm —-UNLESS the user's own utterance already named the destruction ("lösch den-Ordner Urlaub"). Asking "do you really want me to delete?" right after the-user said "delete" is confirmation fatigue, the exact failure the whitelist-era was built to avoid. The flip side stays protected: when the brain decides-ON ITS OWN that deleting something is a useful step (the utterance never-mentioned it), the confirmation fires.--Deliberately dumb: a word-boundary vocabulary match, no LLM (AP-11 — the-safety path must be deterministic and fast). The vocabulary is speech-input-vocabulary in de/en/es (AGENTS.md §1 — registered in the german-allowlist);-it covers DESTRUCTION verbs only. STT-confidence doubts are not this-module's job: a plausibility-forced confirmation is never skipped (see-ToolExecutor).+Free-form mentions, negation, inferred names, relative paths and compound shell+programs cannot waive confirmation. Only an imperative naming the exact absolute+operand can do so. Ambiguous requests use the ordinary approval workflow."""+from __future__ import annotationsimport re+import sys+from pathlib import PurePosixPath, PureWindowsPath-# Word stems that only appear when the speaker explicitly asks for deletion,-# formatting, or a machine power action. Stems (not full words) so German-# inflection ("lösch", "lösche", "löschst", "gelöscht") matches without a-# morphology engine; the \w* tail absorbs endings. Compiled once.-_DESTRUCTION_STEMS: tuple[str, ...] = (- # German- "lösch", "gelöscht", "entfern", "entfernt", "wegwerfen", "wegschmeiß",- "papierkorb", "formatier", "runterfahren", "herunterfahren", "neustart",- "neu starten",- # English- "delete", "remove", "erase", "wipe", "trash", "uninstall", "format",- "shut down", "shutdown", "restart", "reboot", "power off",- # Spanish- "borra", "borrar", "elimina", "eliminar", "quita", "quitar", "formatea",- "apaga", "apagar", "reinicia", "reiniciar",+# No evaluation, globbing, redirection, options, provider paths or quote escapes.+_PATH = r"(?:[A-Za-z]:[\\/]|/)[\w ./\\-]+"+_OPERAND = (+ rf"(?:'(?P<single>{_PATH})'|\"(?P<double>{_PATH})\"|(?P<bare>(?:[A-Za-z]:[\\/]|/)[\w./\\-]+))")--_PATTERN = re.compile(- r"\b(?:" + "|".join(re.escape(stem) + r"\w*" for stem in _DESTRUCTION_STEMS) + r")",+_REQUEST = re.compile(+ r"(?:(?:please|bitte|por favor)\s+)?"+ r"(?:delete|remove|erase|lösch|lösche|entferne|borra|elimina)\s+"+ r"(?:(?:the file|the folder|the directory|die Datei|den Ordner|el archivo|la carpeta)\s+)?"+ + _OPERAND,+ re.IGNORECASE,+)+_COMMAND = re.compile(+ r"(?:rm\s+(?:(?:-r|--recursive)\s+)?(?:--\s+)?|Remove-Item\s+(?:-LiteralPath\s+)?)"+ + _OPERAND+ + r"(?:\s+-Recurse)?",re.IGNORECASE,)-def utterance_confirms_destruction(utterance: str) -> bool:- """True when the utterance itself explicitly asks for a destructive act.-- Empty/whitespace utterances (API calls, missions without a spoken turn)- never confirm — the confirmation question stays the default there.- """- if not utterance or not utterance.strip():+def command_confirms_destruction(+ command: str, utterance: str, *, windows: bool | None = None+) -> bool:+ """Match one deletion and its exact, literal absolute target, or fail closed."""+ if any(char.isspace() and char not in " \t" for char in command):+ return False+ request = _REQUEST.fullmatch(utterance.strip())+ invocation = _COMMAND.fullmatch(command.strip())+ if request is None or invocation is None:+ return False+ requested = next(value for value in request.groups() if value is not None)+ operand = next(value for value in invocation.groups() if value is not None)+ # Do not normalize paths: shell/platform semantics can differ. Exact spelling+ # is required, and an entire filesystem is never implicit consent.+ if operand != requested or ".." in operand.replace("\\", "/").split("/"):+ return False+ if windows is None:+ windows = sys.platform == "win32"+ if not windows and "\\" in operand and invocation.group("single") is None:+ # POSIX unquoted/double-quoted backslashes can change the actual operand.return False- return bool(_PATTERN.search(utterance))+ path = PureWindowsPath(operand) if windows else PurePosixPath(operand)+ return path.is_absolute() and str(path) != path.anchordiff --git a/jarvis/society/conversation_tool.py b/jarvis/society/conversation_tool.pyindex b174f3e13e..66fef3eafc 100644--- a/jarvis/society/conversation_tool.py+++ b/jarvis/society/conversation_tool.py@@ -56,6 +56,8 @@ class ConversationRecallTool:class RoutineListTool:+ read_only = True+name = "society_routines"risk_tier = "safe"description = (diff --git a/jarvis/ui/web/fast_bootstrap.py b/jarvis/ui/web/fast_bootstrap.pyindex 2e77645424..6f72561ead 100644--- a/jarvis/ui/web/fast_bootstrap.py+++ b/jarvis/ui/web/fast_bootstrap.py@@ -117,16 +117,7 @@ class FastBootstrap:@propertydef app(self) -> Any:- """The SECURED bootstrap entry, for tests and external embedders.-- NOT what :meth:`serve` binds. Production serves :meth:`_asgi` directly- (see the comment in :meth:`_start_server`): the warming surface is- deliberately credential-free — static shell, health, onboarding- fastpath, accept-then-close 1013 websockets — and every held request- delegates to the real app, which applies its own SurfaceSecurity.- This wrapped variant adds the boundary in front of the SAME warming- surface for callers that embed the bootstrap somewhere less trusted.- """+ """The shared secured entry for production, tests and embedders."""return self._entry_appasync def _entry_app(self, scope: dict, receive: Any, send: Any) -> None:@@ -478,17 +469,13 @@ class FastBootstrap:# it as ``app(scope)`` and crash. A module-level-style closure is# correctly detected as ASGI3.#- # DELIBERATELY ``_asgi`` and not the secured ``self.app``: the warming- # surface must stay credential-free. Gating it on the session cookie- # would race the desktop token injection at every boot (AuthGate would- # 401 before pywebview delivers the token) and would go dark for- # WebKit websockets entirely (BUG-065). Everything held during warm-up- # is delegated to the real app afterwards, which enforces its own- # SurfaceSecurity — so nothing protected is ever served from here.+ # Use the same boundary as embedders and tests. Public shell/health+ # reads and warming websocket 1013 responses remain credential-free;+ # setup mutations must pass Host, Origin and write authorization._self = selfasync def _asgi3(scope: dict, receive: Any, send: Any) -> None:- await _self._asgi(scope, receive, send)+ await _self.app(scope, receive, send)self._server = uvicorn.Server(uvicorn.Config(diff --git a/jarvis/ui/web/onboarding_routes.py b/jarvis/ui/web/onboarding_routes.pyindex 2ea51e072b..f6426c8328 100644--- a/jarvis/ui/web/onboarding_routes.py+++ b/jarvis/ui/web/onboarding_routes.py@@ -29,6 +29,7 @@ router = APIRouter(prefix="/api/onboarding", tags=["onboarding"])# Tests override this to redirect the state file; production leaves it None# (state.py resolves the default data/setup_state.json)._STATE_PATH_OVERRIDE: Path | None = None+_COMPLETE_LOCK = threading.Lock()def _path() -> Path | None:@@ -149,8 +150,13 @@ def post_complete(request: Request) -> dict:require_interactive_desktop_action(request, action="restart", require_origin=True)- st.mark_onboarding_complete(_path())- restarting = _schedule_fresh_restart(request)+ # Sync routes run in a thread pool: serialize the check and transition so+ # simultaneous clicks cannot each schedule a restart.+ with _COMPLETE_LOCK:+ if st.is_onboarding_complete(_path()):+ return {"ok": True, "restarting": False}+ st.mark_onboarding_complete(_path())+ restarting = _schedule_fresh_restart(request)return {"ok": True, "restarting": restarting}diff --git a/jarvis/ui/web/surface_security.py b/jarvis/ui/web/surface_security.pyindex 370406ff3a..8b9b712ec7 100644--- a/jarvis/ui/web/surface_security.py+++ b/jarvis/ui/web/surface_security.py@@ -759,11 +759,9 @@ def _http_auth_exception(path: str, method: str) -> bool:_is_static_request(path, method)or (path == "/api/health" and method == "GET")or (path == "/api/ui/shell-painted" and method == "POST")- # First-boot contract: onboarding must answer before any credential- # exists (headless fresh install has no token to present). Parity with- # the serve-first bootstrap, which serves /api/onboarding/* unauthenticated- # via jarvis.setup.onboarding_fastpath; the routes carry setup state only.- or path.startswith("/api/onboarding/")+ # First-boot reads remain public. Mutations use the same authenticated+ # session / trusted local-open policy as other application writes.+ or (method == "GET" and path in {"/api/onboarding/state", "/api/onboarding/terms"})or _external_http_auth(path, method))diff --git a/jarvis/ui/web/telephony_routes.py b/jarvis/ui/web/telephony_routes.pyindex adf0448291..f8e579a214 100644--- a/jarvis/ui/web/telephony_routes.py+++ b/jarvis/ui/web/telephony_routes.py@@ -781,10 +781,14 @@ async def media_socket(ws: WebSocket) -> None:continueif event == "start":+ if call_sid:+ # A socket owns one authenticated identity for its lifetime.+ await ws.close(code=1008, reason="duplicate start")+ breakstart = data.get("start", {})stream_sid = start.get("streamSid", "") or data.get("streamSid", "")custom = start.get("customParameters", {}) or {}- call_sid = custom.get("call_sid", "") or start.get("callSid", "")+ requested_call_sid = custom.get("call_sid", "") or start.get("callSid", "")secret = custom.get("secret", "")language = custom.get("language", "") or (getattr(twilio, "language_code", "de-DE") if twilio else "de-DE"@@ -797,21 +801,24 @@ async def media_socket(ws: WebSocket) -> None:# Validate the per-call WS secret unless skipped for tests.skip = bool(getattr(state, "telephony_skip_signature", False))if not skip:- pending = mgr.consume_pending(call_sid, secret)+ pending = mgr.consume_pending(requested_call_sid, secret)if pending is None or not constant_time_equals(pending.secret if pending else "", secret):- log.warning("telephony: media socket secret mismatch for %s", call_sid)- record_status = CALL_FAILED+ log.warning("telephony: media socket secret mismatch")await ws.close(code=1008, reason="bad secret")breakfrom_number = pending.from_numberto_number = pending.to_numberelse:- pending = mgr.peek_pending(call_sid)+ pending = mgr.peek_pending(requested_call_sid)from_number = pending.from_number if pending else custom.get("from", "")to_number = pending.to_number if pending else custom.get("to", "")+ if not requested_call_sid or mgr.active_session(requested_call_sid) is not None:+ await ws.close(code=1008, reason="call already active or missing")+ break+ call_sid = requested_call_sidsession = _build_session(state=state,cfg=cfg,@@ -875,7 +882,9 @@ async def media_socket(ws: WebSocket) -> None:await session.end(reason="socket_closed", status=record_status)record_status = session.statusif call_sid:- mgr.unregister_active(call_sid)+ # Only remove the session this socket registered, never a replacement.+ if session is not None and mgr.active_session(call_sid) is session:+ mgr.unregister_active(call_sid)duration = session.duration_s if session is not None else time.time() - started_atturns = session.turns if session is not None else 0from_number = getattr(session, "from_number", "") if session else ""diff --git a/keyproxy/passthrough.py b/keyproxy/passthrough.pyindex 45a1b23d73..769ded94d5 100644--- a/keyproxy/passthrough.py+++ b/keyproxy/passthrough.py@@ -52,7 +52,10 @@ _HOP_BY_HOP = frozenset(_INBOUND_AUTH = frozenset({"authorization", "x-api-key", "x-goog-api-key"})# Never copy the inbound Host (it is the proxy host, not the vendor's) or the# request's content-length (httpx recomputes it for the new body).-_DROP_REQUEST_HEADERS = _HOP_BY_HOP | _INBOUND_AUTH | {"host", "content-length"}+_DROP_REQUEST_HEADERS = _HOP_BY_HOP | _INBOUND_AUTH | {+ "host", "content-length", "accept-encoding",+}+_DECODED_ENCODINGS = frozenset({"identity", "gzip", "deflate"})# Hop-by-hop response headers + ones httpx/Starlette will set themselves._DROP_RESPONSE_HEADERS = _HOP_BY_HOP | {"content-length", "content-encoding"}@@ -144,6 +147,9 @@ async def handle_passthrough(# 4. Build the upstream request.body = await request.body()out_headers = _safe_request_headers(request.headers)+ # gzip/deflate decoders ship with httpx. Optional Brotli/zstd packages may+ # not exist on this proxy even when the downstream browser supports them.+ out_headers["accept-encoding"] = "gzip, deflate"out_query = dict(query_params)# Strip the inbound gemini ?key= before placement (defence in depth — the# placement function also pops it).@@ -182,11 +188,22 @@ async def handle_passthrough(status_code=502,)+ encoding = upstream_response.headers.get("content-encoding", "")+ if encoding and any(+ part.strip().lower() not in _DECODED_ENCODINGS for part in encoding.split(",")+ ):+ await upstream_response.aclose()+ return JSONResponse(+ {"error": "unsupported_encoding", "detail": "unsupported upstream content encoding"},+ status_code=502,+ )+usage_buffer = bytearray()async def body_iterator():try:- async for chunk in upstream_response.aiter_raw():+ # Headers describe decoded content; meter and forward the same bytes.+ async for chunk in upstream_response.aiter_bytes():if len(usage_buffer) < _USAGE_BUFFER_CAP:usage_buffer.extend(chunk[: _USAGE_BUFFER_CAP - len(usage_buffer)])yield chunkdiff --git a/keyproxy/tests/test_passthrough.py b/keyproxy/tests/test_passthrough.pyindex a36a261916..47a0f9aee3 100644--- a/keyproxy/tests/test_passthrough.py+++ b/keyproxy/tests/test_passthrough.py@@ -7,7 +7,9 @@ via ``httpx.ASGITransport``.from __future__ import annotations+import gzipimport json+import zlibimport httpximport pytest@@ -77,6 +79,68 @@ def client_for(app) -> httpx.AsyncClient:)[email protected]("encoding", ["gzip", "deflate"])[email protected]("streaming", [False, True])+async def test_compressed_response_is_decoded_and_metered(encoding, streaming) -> None:+ payload = json.dumps({"model": "test", "usage": {+ "prompt_tokens": 5, "completion_tokens": 7, "total_tokens": 12,+ }}).encode()+ body = b"data: " + payload + b"\n\ndata: [DONE]\n\n" if streaming else payload+ compressed = gzip.compress(body) if encoding == "gzip" else zlib.compress(body)+ responses = []++ def upstream(_request):+ assert _request.headers["accept-encoding"] == "gzip, deflate"+ response = stream_response(200, compressed, chunk_size=7, headers={+ "content-type": "text/event-stream" if streaming else "application/json",+ "content-encoding": encoding,+ "content-length": str(len(compressed)),+ })+ responses.append(response)+ return response++ app, tokens, usage = build_harness(upstream)+ issued = tokens.issue("compression-test")+ async with app.state.upstream, client_for(app) as client:+ response = await client.post("/p/openai/chat/completions", headers={+ "authorization": f"Bearer {issued.plaintext}",+ "accept-encoding": "br, zstd",+ })+ assert response.status_code == 200+ assert response.content == body+ assert "content-encoding" not in response.headers+ assert "content-length" not in response.headers+ assert responses[0].is_closed+ assert usage.recent()[0]["prompt_tokens"] == 5+ assert usage.recent()[0]["completion_tokens"] == 7++[email protected]("encoding", ["br", "zstd", "gzip, br"])+async def test_unnegotiated_encoding_is_rejected_without_forwarding_garbage(encoding):+ responses = []++ def upstream(request):+ assert request.headers["accept-encoding"] == "gzip, deflate"+ response = stream_response(200, b"unsupported-compressed-fixture", headers={+ "content-type": "application/json", "content-encoding": encoding,+ })+ responses.append(response)+ return response++ app, tokens, usage = build_harness(upstream)+ issued = tokens.issue("encoding-test")+ async with app.state.upstream, client_for(app) as client:+ response = await client.post("/p/openai/chat/completions", headers={+ "authorization": f"Bearer {issued.plaintext}", "accept-encoding": encoding,+ })+ assert response.status_code == 502+ assert response.json()["error"] == "unsupported_encoding"+ assert responses[0].is_closed+ assert usage.recent() == []++# --------------------------------------------------------------------------# Fail-closed auth / provider# --------------------------------------------------------------------------diff --git a/tests/unit/agent_chat/test_folder_tools.py b/tests/unit/agent_chat/test_folder_tools.pyindex 8a2f92d757..9695463da8 100644--- a/tests/unit/agent_chat/test_folder_tools.py+++ b/tests/unit/agent_chat/test_folder_tools.py@@ -5,6 +5,8 @@ from __future__ import annotationsfrom pathlib import Pathfrom uuid import uuid4+import pytest+from jarvis.agent_chat import folder_tools as ftfrom jarvis.agent_chat.tools import READ_ONLY_TOOLS, TOOL_SPECSfrom jarvis.core.protocols import ExecutionContext, ToolResult@@ -68,6 +70,7 @@ def test_plan_filter_keeps_safe_tools_only(tmp_path: Path):def __init__(self, name: str, tier: str) -> None:self.name = nameself.risk_tier = tier+ self.read_only = tier == "safe"surface = {**ft.folder_tools(tmp_path),@@ -78,3 +81,73 @@ def test_plan_filter_keeps_safe_tools_only(tmp_path: Path):}kept = ft.plan_filter(surface) # type: ignore[arg-type]assert set(kept) == set(READ_ONLY_TOOLS) | {"wiki-recall"}++[email protected]("name,args", [+ ("Read", {"file_path": "hello.txt"}),+ ("Ls", {"path": "."}),+ ("Glob", {"pattern": "*.txt"}),+ ("Grep", {"pattern": "hello", "path": "."}),+ ("Write", {"file_path": "marker", "content": "x"}),+ ("Edit", {"file_path": "hello.txt", "old_string": "hello", "new_string": "changed"}),+ ("RunCommand", {"command": "echo changed > marker"}),+])+async def test_plan_discovery_matches_real_execution(tmp_path, name, args):+ from jarvis.core.bus import EventBus+ from jarvis.core.config import SafetyConfig+ from jarvis.safety.approval import ApprovalWorkflow+ from jarvis.safety.risk_tier import RiskTierEvaluator+ from jarvis.safety.tool_executor import ToolExecutor++ (tmp_path / "hello.txt").write_text("hello", encoding="utf-8")+ bus = EventBus()+ executor = ToolExecutor(bus, RiskTierEvaluator(SafetyConfig()), ApprovalWorkflow(bus))+ tools = ft.folder_tools(tmp_path)+ result = await executor.execute(tools[name], args, config_snapshot={"chat_read_only": True})+ assert result.success == (name in ft.plan_filter(tools))+ assert (tmp_path / "hello.txt").read_text(encoding="utf-8") == "hello"+ assert not (tmp_path / "marker").exists()++[email protected]("command", [+ "echo $(touch marker)", "git config --file marker audit.plan escaped",+ "echo $(New-Item marker)", "echo innocent", "touch marker",+])+async def test_plan_shell_cannot_write_even_when_described_as_read(tmp_path, command):+ from jarvis.core.bus import EventBus+ from jarvis.core.config import SafetyConfig+ from jarvis.plugins.tool.run_shell import RunShellTool+ from jarvis.safety.approval import ApprovalWorkflow+ from jarvis.safety.risk_tier import RiskTierEvaluator+ from jarvis.safety.tool_executor import ToolExecutor++ shell = RunShellTool()+ assert shell.name not in ft.plan_filter({shell.name: shell})+ bus = EventBus()+ executor = ToolExecutor(bus, RiskTierEvaluator(SafetyConfig()), ApprovalWorkflow(bus))+ result = await executor.execute(shell, {"command": command, "cwd": str(tmp_path)},+ config_snapshot={"chat_read_only": True})+ assert result.error == "Plan mode permits reads only"+ assert not list(tmp_path.iterdir())+++def test_safe_tier_or_display_text_alone_never_grants_plan_authority():+ from types import SimpleNamespace++ from jarvis.core.tool_read_only import allows_read++ tool = SimpleNamespace(risk_tier="safe", describe_args=lambda args: {"level": "read"})+ assert not allows_read(tool)+ assert not allows_read(tool, {})+++def test_workspace_plan_capability_only_allows_observation():+ from jarvis.brain.workspace_tool import WorkspaceOrchestrationTool+ from jarvis.core.tool_read_only import allows_read++ tool = WorkspaceOrchestrationTool(None)+ assert allows_read(tool)+ for action in ("inspect", "resolve", "context", "observe"):+ assert allows_read(tool, {"action": action})+ for action in ("create", "send", "keys", "stop", "close", "unknown", None):+ assert not allows_read(tool, {"action": action})diff --git a/tests/unit/marketplace/test_connect_helpers.py b/tests/unit/marketplace/test_connect_helpers.pyindex 56977ae72e..d22ca43059 100644--- a/tests/unit/marketplace/test_connect_helpers.py+++ b/tests/unit/marketplace/test_connect_helpers.py@@ -23,6 +23,8 @@ class _Spec:def __init__(self, plugin_id: str, auth: object = None) -> None:self.id = plugin_idself.auth = auth+ self.source = "seed"+ self.oauth_client_family = Noneclass _Catalog:diff --git a/tests/unit/marketplace/test_oauth_family_boundary.py b/tests/unit/marketplace/test_oauth_family_boundary.pynew file mode 100644index 0000000000..afe10bf911--- /dev/null+++ b/tests/unit/marketplace/test_oauth_family_boundary.py@@ -0,0 +1,105 @@+"""Family metadata cannot delegate another provider's confidential client."""++from types import SimpleNamespace++import httpx+import pytest++from jarvis.marketplace import catalog_data+from jarvis.marketplace.auth.oauth_pkce_loopback import _PendingPkceFlow+from jarvis.marketplace.connect_helpers import build_handler_from_catalog, oauth_client_family+from jarvis.marketplace.publisher_clients import resolve_publisher_client++[email protected]("source", ["community", "local", "seed"])[email protected]("auth_method", ["client_secret_post", "client_secret_basic"])[email protected]("provisioning", ["own", "publisher"])+async def test_untrusted_token_endpoint_never_receives_family_secret(+ monkeypatch, source, auth_method, provisioning+):+ seed = catalog_data.load_seed_catalog()+ original = seed.by_id("gmail")+ plugin_id = "gmail" if source == "seed" else "community-mail"+ auth = original.auth.model_copy(+ update={+ "authorization_url": "https://community.invalid/authorize",+ "token_url": "https://community.invalid/token",+ "client_id": "community-client",+ "client_secret": "community-own-secret",+ "client_auth_method": auth_method,+ }+ )+ spec = original.model_copy(update={"id": plugin_id, "source": source, "auth": auth})+ monkeypatch.setattr(+ catalog_data, "load_catalog", lambda: SimpleNamespace(by_id=lambda pid: spec)+ )+ secret_reads = []++ def secret(key, env=None):+ secret_reads.append(key)+ prefix = "google" if provisioning == "own" else "publisher_google"+ return {+ f"{prefix}_oauth_client_id": "unrelated-client",+ f"{prefix}_oauth_client_secret": "unrelated-secret",+ }.get(key)++ monkeypatch.setattr("jarvis.core.config.get_secret", secret)+ assert oauth_client_family(plugin_id) is None+ assert resolve_publisher_client(plugin_id, auth.client_id, auth.client_secret) == (+ "community-client",+ "community-own-secret",+ "catalog",+ )+ handler = build_handler_from_catalog(plugin_id)+ requests = []++ def capture(request):+ requests.append(request)+ return httpx.Response(200, json={"access_token": "synthetic-access"})++ real_client = httpx.AsyncClient+ monkeypatch.setattr(+ httpx,+ "AsyncClient",+ lambda **kwargs: real_client(transport=httpx.MockTransport(capture), **kwargs),+ )+ pending = _PendingPkceFlow(+ handler._config, None, "synthetic-verifier", "http://127.0.0.1/callback"+ )+ result = await handler._exchange(pending, code="synthetic-code")+ assert result.access == "synthetic-access"+ assert len(requests) == 1+ assert "unrelated" not in requests[0].content.decode()+ assert handler._config.client_secret == "community-own-secret" # noqa: S105 - synthetic fixture+ assert secret_reads == []++[email protected]("plugin_id", ["gmail", "google_drive", "google_calendar"])[email protected]("provisioning", ["own", "publisher"])+def test_trusted_siblings_keep_shared_clients(monkeypatch, plugin_id, provisioning):+ seed = catalog_data.load_seed_catalog()+ monkeypatch.setattr(catalog_data, "load_catalog", lambda: seed)+ prefix = "google" if provisioning == "own" else "publisher_google"+ secrets = {+ f"{prefix}_oauth_client_id": "trusted-client",+ f"{prefix}_oauth_client_secret": "trusted-secret",+ }+ monkeypatch.setattr("jarvis.core.config.get_secret", lambda key, env=None: secrets.get(key))+ assert oauth_client_family(plugin_id) == "google"+ assert resolve_publisher_client(plugin_id, "placeholder", None) == (+ "trusted-client",+ "trusted-secret",+ provisioning,+ )+++def test_unreadable_seed_disables_secret_sharing(monkeypatch):+ def broken():+ raise ValueError("bad seed")++ monkeypatch.setattr(catalog_data, "load_seed_catalog", broken)+ monkeypatch.setattr(+ "jarvis.core.config.get_secret",+ lambda *args: pytest.fail("secret read on untrusted catalog"),+ )+ assert oauth_client_family("gmail") is Nonediff --git a/tests/unit/safety/test_explicit_intent.py b/tests/unit/safety/test_explicit_intent.pyindex 78f19ec8f9..9ef0ed501e 100644--- a/tests/unit/safety/test_explicit_intent.py+++ b/tests/unit/safety/test_explicit_intent.py@@ -1,82 +1,113 @@-"""Explicit-intent vocabulary: the user's own words authorize the destruction.+"""Deletion consent must bind a single operation to its literal target."""-Claude-Code permission model (mandate 2026-08-08): "lösch den Ordner Urlaub"-must not be answered with "do you really want me to delete?". The check is a-deterministic de/en/es verb-stem match — no LLM, no entity matching.-"""from __future__ import annotations+import sys+import pytest+from jarvis.core.bus import EventBus+from jarvis.core.config import SafetyConfigfrom jarvis.plugins.tool.run_shell import RunShellTool-from jarvis.safety.explicit_intent import utterance_confirms_destruction+from jarvis.safety.approval import ApprovalWorkflow+from jarvis.safety.explicit_intent import command_confirms_destruction+from jarvis.safety.risk_tier import RiskTierEvaluator+from jarvis.safety.tool_executor import ToolExecutor@pytest.mark.parametrize("utterance",[- "Lösch den Ordner Urlaub vom Desktop.",- "Bitte lösche die alte Datei",- "kannst du das entfernen",- "wirf das in den Papierkorb",- "formatier den Stick",- "fahr den Rechner runterfahren", # STT word salad still carries the stem- "delete the old build folder",- "please remove that file",- "wipe the temp directory",- "shut down the computer",- "borra la carpeta vieja",- "elimina ese archivo",- "apaga el ordenador",+ "List this directory. Do not delete any files.",+ "Do not delete /tmp/keep-me",+ "Bitte lösche /tmp/keep-me nicht",+ "No borres /tmp/keep-me",+ 'The instructions say "delete /tmp/keep-me"',+ "Did you delete /tmp/keep-me?",+ "I deleted /tmp/keep-me yesterday",+ "delete /tmp/something-else",+ "delete keep-me",+ "delete /tmp/keep-me and keep /tmp/other",+ "",+ ],+)+def test_mentions_and_unbound_targets_do_not_authorize(utterance):+ assert not command_confirms_destruction("rm /tmp/keep-me", utterance)+++ "command",+ [+ "rm /tmp/keep-me; rm /tmp/other",+ "rm /tmp/keep-me /tmp/other",+ "rm /tmp/*",+ "rm $(echo /tmp/keep-me)",+ "rm /tmp/keep-me > /tmp/other",+ "sh -c 'rm /tmp/keep-me'",+ "rm -rf /tmp/keep-me",],)-def test_destruction_verbs_confirm(utterance: str) -> None:- assert utterance_confirms_destruction(utterance) is True+def test_compound_or_ambiguous_shell_keeps_confirmation(command):+ assert not command_confirms_destruction(command, "delete /tmp/keep-me")@pytest.mark.parametrize("utterance",[- "",- " ",- "Leg einen Ordner Urlaub auf dem Desktop an.",- "Was liegt auf meinem Desktop?",- "Räum die Dateien in Unterordner", # organizing is NOT deleting- "create a folder called delete-me-later"- .replace("delete-me-later", "archive"), # no destruction verb at all- "Stelle einen Timer auf acht Minuten.",+ "delete /tmp/keep-me",+ "please remove the file /tmp/keep-me",+ "Bitte lösche die Datei /tmp/keep-me",+ "borra el archivo /tmp/keep-me",],)-def test_harmless_utterances_do_not_confirm(utterance: str) -> None:- assert utterance_confirms_destruction(utterance) is False---class TestRunShellIntentHook:- def test_destructive_command_with_spoken_delete_confirms(self) -> None:- tool = RunShellTool()- assert tool.intent_confirms_args(- {"command": "Remove-Item -Recurse C:\\Users\\x\\Desktop\\Urlaub"},- "Lösch den Ordner Urlaub vom Desktop.",- ) is True-- def test_brain_initiated_deletion_does_not_confirm(self) -> None:- # The utterance never mentioned deleting — the brain chose rm on its- # own as a means to an end. The confirmation must stay.- tool = RunShellTool()- assert tool.intent_confirms_args(- {"command": "rm -rf ./build"},- "mach das Projekt startklar",- ) is False-- def test_non_destructive_command_never_needs_the_shortcut(self) -> None:- tool = RunShellTool()- assert tool.intent_confirms_args(- {"command": "ls -la"},- "lösch nachher mal was",- ) is False-- def test_empty_utterance_never_confirms(self) -> None:- tool = RunShellTool()- assert tool.intent_confirms_args(- {"command": "rm -rf ./build"}, "",- ) is False+def test_exact_single_deletion_is_authorized(utterance):+ assert command_confirms_destruction("rm -- /tmp/keep-me", utterance, windows=False)+++def test_windows_literal_target_and_mismatch():+ assert command_confirms_destruction(+ "Remove-Item -LiteralPath 'C:/test/old folder' -Recurse",+ "delete the folder 'C:/test/old folder'",+ windows=True,+ )+ assert not command_confirms_destruction(+ "Remove-Item -LiteralPath C:/test/other",+ "delete C:/test/old",+ )+ assert not command_confirms_destruction("rm /", "delete /")+ assert not command_confirms_destruction("rm C:/test/file", "delete C:/test/file", windows=False)+ assert not command_confirms_destruction("rm /test/file", "delete /test/file", windows=True)+++def test_shell_parsing_cannot_change_the_authorized_operation_or_target():+ target = r"/tmp/keep\me"+ assert not command_confirms_destruction(f"rm {target}", f"delete '{target}'", windows=False)+ assert command_confirms_destruction(f"rm '{target}'", f"delete '{target}'", windows=False)+ assert not command_confirms_destruction("rm\n/tmp/command", "delete /tmp/command", windows=False)++[email protected]("authorized", [False, True])+async def test_real_executor_leaves_protected_file_and_deletes_authorized_target(+ tmp_path, authorized+):+ target = tmp_path / "keep-me"+ target.write_text("fixture", encoding="utf-8")+ operand = target.as_posix()+ command = (+ f"Remove-Item -LiteralPath '{operand}'" if sys.platform == "win32" else f"rm -- '{operand}'"+ )+ utterance = (+ f"delete '{operand}'" if authorized else "List this directory. Do not delete any files."+ )+ bus = EventBus()+ executor = ToolExecutor(bus, RiskTierEvaluator(SafetyConfig()), ApprovalWorkflow(bus))+ result = await executor.execute(+ RunShellTool(),+ {"command": command},+ user_utterance=utterance,+ config_snapshot={"approval_surface": "unattended"},+ )+ assert result.success is authorized+ assert target.exists() is not authorized+ if not authorized:+ assert "approval" in result.error.lower()diff --git a/tests/unit/telephony/test_media_ownership.py b/tests/unit/telephony/test_media_ownership.pynew file mode 100644index 0000000000..1b48a634c2--- /dev/null+++ b/tests/unit/telephony/test_media_ownership.py@@ -0,0 +1,90 @@+"""Rejected media sockets never acquire call-registry authority."""++from types import SimpleNamespace++import pytest+from fastapi import FastAPI+from fastapi.testclient import TestClient++from jarvis.telephony.status import CallRecord, TelephonyManager+from jarvis.ui.web import telephony_routes++pytestmark = pytest.mark.no_auto_web_auth+++def make_app():+ app = FastAPI()+ app.include_router(telephony_routes.router)+ app.state.config = SimpleNamespace(integrations=SimpleNamespace(twilio=None))+ app.state.telephony_manager = TelephonyManager()+ return app+++def start(call_sid, secret):+ return {+ "event": "start",+ "start": {+ "callSid": call_sid,+ "streamSid": "stream",+ "customParameters": {"secret": secret},+ },+ }++[email protected]("requested", ["known-active", "known-finished", "unknown"])+def test_invalid_secret_leaves_all_call_state_unchanged(requested, monkeypatch):+ app = make_app()+ mgr = app.state.telephony_manager+ active = object()+ mgr.register_active("known-active", active)+ mgr.register_pending("known-active", "valid-secret")+ pending = mgr.peek_pending("known-active")+ mgr.record_call(CallRecord(call_sid="known-finished", status="completed", turns=3))+ before = mgr.recent_calls()++ def never_build(**kwargs):+ pytest.fail("unauthenticated socket reached session factory")++ monkeypatch.setattr(telephony_routes, "_build_session", never_build)+ with TestClient(app) as client:+ with client.websocket_connect("/api/telephony/media") as ws:+ ws.send_json(start(requested, "invalid"))+ assert ws.receive()["code"] == 1008+ assert mgr.active_session("known-active") is active+ assert mgr.peek_pending("known-active") is pending+ assert mgr.recent_calls() == before++[email protected]("second_start", [False, True])+def test_valid_socket_records_its_identity_once(monkeypatch, second_start):+ app = make_app()+ mgr = app.state.telephony_manager+ mgr.register_pending("valid-call", "valid-secret", from_number="from", to_number="to")+ mgr.register_pending("other-call", "other-secret")+ ended = []++ class Session:+ ended = False+ status = "completed"+ duration_s = 1+ turns = 2+ from_number = "from"+ to_number = "to"++ async def end(self, **kwargs):+ self.ended = True+ ended.append(1)++ async def speak_intro(self):+ return None++ monkeypatch.setattr(telephony_routes, "_build_session", lambda **kwargs: Session())+ with TestClient(app) as client:+ with client.websocket_connect("/api/telephony/media") as ws:+ ws.send_json(start("valid-call", "valid-secret"))+ ws.send_json(start("other-call", "other-secret") if second_start else {"event": "stop"})+ assert ws.receive()["type"] == "websocket.close"+ assert ended == [1]+ assert mgr.active_calls == 0+ assert mgr.peek_pending("other-call") is not None+ assert [record["call_sid"] for record in mgr.recent_calls()] == ["valid-call"]diff --git a/tests/unit/ui/test_onboarding_authorization.py b/tests/unit/ui/test_onboarding_authorization.pynew file mode 100644index 0000000000..cdc153ba9f--- /dev/null+++ b/tests/unit/ui/test_onboarding_authorization.py@@ -0,0 +1,119 @@+"""Production setup boundaries preserve public reads without public writes."""++from types import SimpleNamespace++import pytest+from fastapi import FastAPI+from fastapi.testclient import TestClient++from jarvis.setup import onboarding_fastpath, state+from jarvis.ui.web import onboarding_routes, surface_security+from jarvis.ui.web.fast_bootstrap import FastBootstrap++pytestmark = pytest.mark.no_auto_web_auth++[email protected]("desktop", [False, True])+def test_locked_completion_requires_session_and_restarts_only_once(tmp_path, monkeypatch, desktop):+ path = tmp_path / "state.json"+ monkeypatch.setattr(onboarding_routes, "_STATE_PATH_OVERRIDE", path)+ monkeypatch.setattr(surface_security, "browser_login_required", lambda: True)+ monkeypatch.delenv("JARVIS_FORCE_ONBOARDING", raising=False)+ restarts = []+ app = FastAPI()+ app.include_router(onboarding_routes.router)+ if desktop:+ app.state.desktop_app = SimpleNamespace(request_restart=lambda: restarts.append(1) or True)+ secured = surface_security.SurfaceSecurity(+ app,+ session_validator=lambda value: value == "fixture-session",+ control_key_validator=lambda value: False,+ )+ with TestClient(secured, base_url="http://127.0.0.1", client=("198.51.100.25", 1234)) as client:+ assert client.get("/api/onboarding/state").status_code == 200+ for route in ("complete", "accept-terms", "acknowledge-wake-word", "decline-terms"):+ assert (+ client.post(+ f"/api/onboarding/{route}", headers={"Origin": "http://127.0.0.1"}+ ).status_code+ == 401+ )+ assert restarts == [] and not state.is_onboarding_complete(path)+ headers = {"Origin": "http://127.0.0.1", "Cookie": "jarvis_session=fixture-session"}+ first = client.post("/api/onboarding/complete", headers=headers)+ second = client.post("/api/onboarding/complete", headers=headers)+ assert first.json() == {"ok": True, "restarting": desktop}+ assert second.json() == {"ok": True, "restarting": False}+ assert (+ client.post(+ "/api/onboarding/complete", headers={"Origin": "http://127.0.0.1"}+ ).status_code+ == 401+ )+ assert state.is_onboarding_complete(path)+ assert restarts == ([1] if desktop else [])+++ "headers",+ [+ [(b"host", b"127.0.0.1"), (b"origin", b"https://foreign.invalid")],+ [(b"host", b"127.0.0.1"), (b"origin", b"null")],+ [+ (b"host", b"127.0.0.1"),+ (b"origin", b"http://127.0.0.1"),+ (b"origin", b"http://127.0.0.1"),+ ],+ [(b"host", b"untrusted.invalid"), (b"origin", b"http://untrusted.invalid")],+ [(b"host", b"127.0.0.1")],+ ],+)+async def test_actual_listener_callable_guards_warming_setup(tmp_path, monkeypatch, headers):+ import uvicorn++ path = tmp_path / "state.json"+ monkeypatch.setattr(onboarding_fastpath, "_STATE_PATH_OVERRIDE", path)+ monkeypatch.setattr(surface_security, "browser_login_required", lambda: False)++ class Server:+ def __init__(self, config):+ self.config = config+ self.started = True++ async def serve(self):+ return None++ monkeypatch.setattr(uvicorn, "Server", Server)+ boot = FastBootstrap(dist_dir=tmp_path)+ await boot._start_server("127.0.0.1", 47111)+ await boot._task+ entry = boot._server.config.app++ async def drive(request_headers):+ messages = []++ async def receive():+ return {"type": "http.request", "body": b"", "more_body": False}++ async def send(message):+ messages.append(message)++ await entry(+ {+ "type": "http",+ "method": "POST",+ "path": "/api/onboarding/complete",+ "scheme": "http",+ "headers": request_headers,+ "client": ("127.0.0.1", 1234),+ "server": ("127.0.0.1", 80),+ },+ receive,+ send,+ )+ return messages[0]["status"]++ assert await drive(headers) in (400, 403)+ assert not state.is_onboarding_complete(path)+ assert await drive([(b"host", b"127.0.0.1"), (b"origin", b"http://127.0.0.1")]) == 200+ assert state.is_onboarding_complete(path)