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(missions): mission-scoped tool pre-authorization (ADR-0031)
Ruben Lütkeae81b9636a06
diff --git a/docs/adr/0031-mission-scoped-tool-preauthorization.md b/docs/adr/0031-mission-scoped-tool-preauthorization.mdnew file mode 100644index 0000000000..1a80cf2545--- /dev/null+++ b/docs/adr/0031-mission-scoped-tool-preauthorization.md@@ -0,0 +1,107 @@+---+title: "ADR-0031: Mission-Scoped Tool Pre-Authorization"+slug: adr-0031-mission-scoped-tool-preauthorization+diataxis: adr+status: active+owner: project-maintainers+last_reviewed: 2026-07-25+phase: 6+audience: developer+---++# ADR-0031 — Mission-Scoped Tool Pre-Authorization++**Status:** Accepted (2026-07-25)+**Phase:** 6 — Self-Healing Jarvis-Agents Orchestrator+**Reference:** ADR-0025, ADR-0009, AP-3, AP-5, AP-14; BUG-096 four-facts rule++## Context++Brokered worker tool calls (ADR-0025) run through `ToolExecutor` with+`voice_confirm=False`. An ask-tier call therefore armed an approval ticket,+published `ActionApprovalRequired`, and blocked until a human decided — or the+60-second default timeout denied it. Unattended missions have no human present:+every non-pre-approved ask-tier call was structurally guaranteed to stall for+a minute and come back denied. Before the observed-refusal split (W3,+`WorkerToolExecutionSummary.integrity_compromised`), that single denial also+failed the whole iteration.++Scheduled tasks solved the same problem earlier with+`jarvis.tasks.approval_bridge.TaskAutoApprover` ("Option B"): a bridge that+listens for `ActionApprovalRequired` and ANSWERS the gate by publishing+`ActionApproved` for pre-authorized tools on the task's own trace — never+bypassing the executor. `ToolExecutor` deliberately arms the approval ticket+BEFORE publishing the event so such a synchronous bus answer is never lost.++## Decision++A `MissionToolAutoApprover` (`jarvis/missions/tool_approvals.py`) answers the+approval gate for tools pre-authorized to one mission:++1. **Armed by the broker, exactly for the lifetime of a grant.**+ `WorkerToolBroker.issue()` arms `(mission_id, grant_key)` with the+ auto-approvable name set; every revocation path (explicit revoke, TTL+ reaper, test reset) disarms it. `grant_key` is a truncated SHA-256 of the+ bearer token — the secret itself never leaves the broker.+2. **The auto-approvable set is `granted ∩ allowlist`.** `granted` is the+ grant's spec names (already filtered by the Command-Registry+ `worker_allowed ∧ ¬dangerous` rule and the broker denylist). The allowlist+ is `[phase6.safety].auto_approve_tool_families`: exact tool names or an+ MCP server family written as `server/`. Config resolution is fail-closed —+ any error yields the empty set.+3. **Approval predicate (all must hold, fail-closed):** the event carries the+ armed `mission_id`; `risk_tier ∈ {ask, monitor}` (never `block`);+ `reason ∈ {risk_tier, plausibility}` — the plausibility guard is a+ voice-context heuristic with no signal for an unattended worker;+ `worker_tool_name_allowed(tool)` re-checked at approval time; tool name+ matches the armed set exactly or by `server/` prefix.+4. **The gate is answered, never bypassed.** The approver publishes+ `ActionApproved(approved_by="mission-grant:<id>")` onto the bus. The full+ `Proposed → ApprovalRequired → Approved → Executed` audit chain is+ preserved, and `MissionToolApprovalCoordinator` clears its pending entry+ through its normal `_on_resolved` subscription — the UI surface stays+ consistent.+5. **Feature flag + timeout knob.** `[phase6.safety].worker_tool_auto_approve+ = false` restores the previous behavior wholesale. The (previously+ hardcoded) approval wait is now `[safety].tool_approval_timeout_s`+ (default 60 s, passed to every `ToolExecutor` construction site). The+ default stays short on purpose: with the W3 refusal semantics, a+ non-pre-authorized call should fail fast and honestly rather than burn the+ worker's iteration budget blocked inside the MCP call.++`[phase6.safety]` is the first Pydantic-modeled slice of the `[phase6.*]`+tables (`Phase6SafetyConfig` / `Phase6Config`, both `extra="allow"` per+AP-16); the other tables remain raw TOML consumed via `bootstrap_missions`+defaults.++## Consequences++* Unattended missions can complete flows that need pre-authorized ask-tier+ tools without a human in the loop, per explicit operator configuration.+* The shipped default allowlist contains only read-only knowledge tools+ (`search_web`, the wiki quartet, `session-latest-turn`) — these are+ safe/monitor tier anyway, so out of the box the approver only prevents+ plausibility-escalated stalls. Real autonomy gains are an explicit operator+ opt-in per tool family.+* Messaging / mail / social-send families are deliberately NOT in the default+ and the config comment says so.+* Residual risk: an allowlisted `server/` family silently covers every future+ tool that server adds, including destructive ones. Mitigation: the default+ contains no family prefixes, the config comment recommends exact names, and+ the broker denylist plus the registry `¬dangerous` rule still bound the+ reachable surface.+* The spawn-gate mandate (agents spawn only on explicit user request) is+ untouched — this ADR governs what an already-authorized mission may do.++## Alternatives considered++* **Per-dispatch autonomy flag on `DispatchBody`** — rejected as the primary+ mechanism: missions arrive via voice, task bridge, CLI, and REST; the+ dominant voice path would have stayed unattended-broken. The config surface+ leaves room for a per-mission override later.+* **Blanket `ToolExecutor` bypass for `worker_broker=True` calls** — rejected:+ it would skip the gate instead of answering it, destroying the audit chain+ and violating the TaskAutoApprover precedent.+* **Raising the approval timeout for workers** — rejected: a longer stall+ helps nobody unattended; the W3 refusal path plus pre-authorization is+ strictly better.diff --git a/jarvis.toml.example b/jarvis.toml.exampleindex 4b85843628..7ecbae6703 100644--- a/jarvis.toml.example+++ b/jarvis.toml.example@@ -157,3 +157,23 @@ enabled = true# Phase-5/6 features (vision, computer_use, admin, missions, board, telephony)# default to enabled = false in code. Enable them individually once configured;# see jarvis/core/config.py for every available section and its defaults.++# -- Mission workers: tool pre-authorization (ADR-0031) --+# Tools listed here are auto-approved for a mission's OWN supervisor-granted+# calls (the gate is answered on the event bus with a full audit trail, never+# bypassed). Entries are exact tool names, or an MCP server family written+# with a trailing slash (e.g. "github/"). Prefer exact names: a family prefix+# silently authorizes every future tool that server adds. Keep messaging /+# mail / social-send tools OUT unless you explicitly accept unattended sends.+# Set worker_tool_auto_approve = false to restore "every ask-tier call waits+# for a human" behavior.+[phase6.safety]+worker_tool_auto_approve = true+auto_approve_tool_families = [+ "search_web",+ "wiki-list",+ "wiki-recall",+ "wiki-page-read",+ "wiki-ingest",+ "session-latest-turn",+]diff --git a/jarvis/brain/launcher.py b/jarvis/brain/launcher.pyindex 1620c1b520..5a7b3402bc 100644--- a/jarvis/brain/launcher.py+++ b/jarvis/brain/launcher.py@@ -92,7 +92,10 @@ async def _run(args: argparse.Namespace) -> int:config.safety, extra_patterns_fn=make_cli_patterns_fn(),)approval = ApprovalWorkflow(bus)- tool_executor = ToolExecutor(bus, evaluator, approval)+ tool_executor = ToolExecutor(+ bus, evaluator, approval,+ default_timeout_s=config.safety.tool_approval_timeout_s,+ )tools = _load_tools()manager = BrainManager(diff --git a/jarvis/core/runtime_refs.py b/jarvis/core/runtime_refs.pyindex 29fe9edc49..a301a88f97 100644--- a/jarvis/core/runtime_refs.py+++ b/jarvis/core/runtime_refs.py@@ -33,6 +33,7 @@ from loguru import logger# Each ref is a 1-element list so the setter can rebind without ``global``._BRAIN_MANAGER: list[Any] = []_SUPERVISOR_TOOL_GATEWAY: list[Any] = []+_MISSION_TOOL_AUTO_APPROVER: list[Any] = []_SPEECH_PIPELINE: list[Any] = []_MCP_REGISTRY: list[Any] = []@@ -71,6 +72,21 @@ def get_supervisor_tool_gateway() -> Any | None:return _SUPERVISOR_TOOL_GATEWAY[0] if _SUPERVISOR_TOOL_GATEWAY else None+def set_mission_tool_auto_approver(approver: Any) -> None:+ """Register the mission-scoped tool pre-authorizer (ADR-0031).++ Set by the web-server bootstrap next to the MissionToolApprovalCoordinator;+ read by the WorkerToolBroker (which lives below the web layer, same pattern+ as the supervisor tool gateway) to arm/disarm per-grant auto-approval.+ """+ _set(_MISSION_TOOL_AUTO_APPROVER, approver)+++def get_mission_tool_auto_approver() -> Any | None:+ """The live MissionToolAutoApprover, or ``None`` before server wiring."""+ return _MISSION_TOOL_AUTO_APPROVER[0] if _MISSION_TOOL_AUTO_APPROVER else None++def set_speech_pipeline(pipeline: Any) -> None:"""Register the live SpeechPipeline (called from the desktop-app bootstrap)."""_set(_SPEECH_PIPELINE, pipeline)@@ -212,6 +228,7 @@ def _reset_for_tests() -> None:"""Clear all refs. Test-only helper (fixtures call this in teardown)."""_BRAIN_MANAGER.clear()_SUPERVISOR_TOOL_GATEWAY.clear()+ _MISSION_TOOL_AUTO_APPROVER.clear()_SPEECH_PIPELINE.clear()_MCP_REGISTRY.clear()_WEB_APP.clear()diff --git a/jarvis/missions/tool_approvals.py b/jarvis/missions/tool_approvals.pyindex 2a79d7c5c1..4ea1f7080f 100644--- a/jarvis/missions/tool_approvals.py+++ b/jarvis/missions/tool_approvals.py@@ -3,10 +3,13 @@from __future__ import annotationsimport asyncio+import threadingimport timefrom dataclasses import asdict, dataclassfrom uuid import UUID+from loguru import logger+from jarvis.core.bus import EventBusfrom jarvis.core.events import (ActionApprovalRequired,@@ -174,4 +177,116 @@ class MissionToolApprovalCoordinator:)-__all__ = ["MissionToolApprovalCoordinator", "PendingMissionToolApproval"]+class MissionToolAutoApprover:+ """Answers approval gates for tools pre-authorized to one mission (ADR-0031).++ Modeled on ``jarvis.tasks.approval_bridge.TaskAutoApprover``: on a matching+ ``ActionApprovalRequired`` it publishes ``ActionApproved`` onto the bus —+ this ANSWERS the gate, it never bypasses it, so the full+ Proposed → ApprovalRequired → Approved → Executed audit chain is preserved+ and the ``MissionToolApprovalCoordinator``'s pending entry clears through+ its normal ``_on_resolved`` subscription.++ Arming is owned by the ``WorkerToolBroker``: one arm per issued grant+ (keyed ``mission_id`` + a non-secret grant key), disarmed on every+ revocation path, so auto-approval lives exactly as long as a grant. The+ armed set is already triple-filtered upstream (registry ``worker_allowed ∧+ ¬dangerous`` → broker denylist → ``granted ∩ [phase6.safety]+ auto_approve_tool_families``); this class re-checks fail-closed anyway.++ Thread-safety: ``arm``/``disarm`` are called from broker code paths that+ may run off the event loop (reaper via the HTTP thread, ``__del__``+ finalizers), so the grant map is guarded by a ``threading.Lock``. The bus+ handler runs on the loop and only reads under the same lock.+ """++ def __init__(self, bus: EventBus) -> None:+ self._bus = bus+ self._mutex = threading.Lock()+ # mission_id -> grant_key -> auto-approvable tool names for that grant.+ self._grants: dict[str, dict[str, frozenset[str]]] = {}+ bus.subscribe(ActionApprovalRequired, self._on_approval_required)++ def arm(+ self,+ mission_id: str,+ grant_key: str,+ tool_names: frozenset[str],+ ) -> None:+ """Pre-authorize ``tool_names`` while the grant ``grant_key`` is live.++ An empty set is a valid no-op arm (keeps arm/disarm symmetric for+ grants whose intersection with the allowlist is empty).+ """+ mission = str(mission_id or "").strip()+ if not mission:+ return+ with self._mutex:+ self._grants.setdefault(mission, {})[grant_key] = frozenset(tool_names)++ def disarm(self, mission_id: str, grant_key: str) -> None:+ mission = str(mission_id or "").strip()+ with self._mutex:+ grants = self._grants.get(mission)+ if grants is None:+ return+ grants.pop(grant_key, None)+ if not grants:+ self._grants.pop(mission, None)++ async def _on_approval_required(self, event: ActionApprovalRequired) -> None:+ mission_id = str(event.mission_id or "").strip()+ if not mission_id:+ return+ # Never a "block" answer; approve both gate reasons — the plausibility+ # guard is a voice-context heuristic (transcript confidence / wake+ # age) that carries no signal for an unattended worker whose+ # "utterance" is the mission task text.+ if event.risk_tier not in ("ask", "monitor"):+ return+ if event.reason not in ("risk_tier", "plausibility"):+ return+ with self._mutex:+ grant_sets = tuple(self._grants.get(mission_id, {}).values())+ granted: frozenset[str] = frozenset().union(*grant_sets) if grant_sets else frozenset()+ if not granted:+ return+ tool_name = event.tool_name+ # Defense in depth: even an armed name must still pass the broker+ # denylist (catalog drift between arm and call).+ from jarvis.missions.workers.worker_tool_broker import worker_tool_name_allowed++ if not worker_tool_name_allowed(tool_name):+ return+ if not self._tool_is_granted(tool_name, granted):+ return+ approved_by = f"mission-grant:{mission_id[:13]}"+ logger.info(+ "MissionToolAutoApprover: approving {} for mission {} ({})",+ tool_name,+ mission_id,+ event.reason,+ )+ await self._bus.publish(+ ActionApproved(+ trace_id=event.trace_id,+ tool_name=tool_name,+ approved_by=approved_by,+ )+ )++ @staticmethod+ def _tool_is_granted(tool_name: str, granted: frozenset[str]) -> bool:+ """Exact name, or the MCP ``server/`` prefix (mirror of+ ``TaskAutoApprover._tool_is_granted``)."""+ if tool_name in granted:+ return True+ prefix = tool_name.split("/", 1)[0]+ return prefix in granted+++__all__ = [+ "MissionToolApprovalCoordinator",+ "MissionToolAutoApprover",+ "PendingMissionToolApproval",+]diff --git a/jarvis/missions/workers/worker_tool_broker.py b/jarvis/missions/workers/worker_tool_broker.pyindex c08a34c205..ff096981b5 100644--- a/jarvis/missions/workers/worker_tool_broker.py+++ b/jarvis/missions/workers/worker_tool_broker.py@@ -10,6 +10,7 @@ receives connector credentials or a direct ``Tool.execute`` handle.from __future__ import annotationsimport asyncio+import hashlibimport jsonimport loggingimport secrets@@ -117,6 +118,28 @@ class WorkerToolCallOutcome:error: str = ""+# Statuses the worker OBSERVED as an in-stream error response (broker_stdio+# returns isError=True; API workers get the error dict directly) — the worker+# had the chance to adapt, so these are honest refusals, not integrity holes.+_OBSERVED_REFUSAL_STATUSES: tuple[str, ...] = ("denied", "cancelled", "timed_out", "error")+# Statuses where the supervisor cannot certify what actually happened: the+# call was still running when the grant closed, or its outcome was rewritten+# to unknown at revocation.+_INTEGRITY_STATUSES: tuple[str, ...] = ("outcome_unknown", "active")+++def _outcome_preview(calls: list["WorkerToolCallOutcome"]) -> str | None:+ if not calls:+ return None+ preview = "; ".join(+ f"{call.tool_name}: {call.status}" + (f" ({call.error})" if call.error else "")+ for call in calls[:3]+ )+ if len(calls) > 3:+ preview += f"; +{len(calls) - 3} more"+ return safe_preview(preview, max_chars=300)++@dataclass(frozen=True, slots=True)class WorkerToolExecutionSummary:"""Completion certificate consumed by the mission controller."""@@ -127,23 +150,34 @@ class WorkerToolExecutionSummary:def clean(self) -> bool:return all(call.status == "success" for call in self.calls)+ @property+ def integrity_compromised(self) -> bool:+ """True when the supervisor cannot certify what actually happened.++ Only these outcomes abort an iteration before critic review. Honest+ refusals (:data:`_OBSERVED_REFUSAL_STATUSES`) keep the iteration+ reviewable — per the BUG-096 class rule, worker execution and critic+ approval are separate facts, and the critic judges the deliverable+ WITH knowledge of the refusals (see ``refusal_summary``).+ """+ return any(call.status in _INTEGRITY_STATUSES for call in self.calls)+@propertydef active_count(self) -> int:return sum(call.status == "active" for call in self.calls)@propertydef failure_summary(self) -> str | None:- failed = [call for call in self.calls if call.status != "success"]- if not failed:- return None- preview = "; ".join(- f"{call.tool_name}: {call.status}"- + (f" ({call.error})" if call.error else "")- for call in failed[:3]+ return _outcome_preview(+ [call for call in self.calls if call.status != "success"]+ )++ @property+ def refusal_summary(self) -> str | None:+ """Bounded preview of the observed refusals, for the critic's context."""+ return _outcome_preview(+ [call for call in self.calls if call.status in _OBSERVED_REFUSAL_STATUSES])- if len(failed) > 3:- preview += f"; +{len(failed) - 3} more"- return safe_preview(preview, max_chars=300)def worker_tool_name_allowed(name: str) -> bool:@@ -625,6 +659,75 @@ class WorkerToolBroker:self._thread = threadreturn self._server+ @staticmethod+ def _grant_key(token: str) -> str:+ """Non-secret derivative of the bearer used to key auto-approval arms.++ The raw token must never leave the broker; a truncated digest is+ collision-safe enough for a handful of concurrent grants.+ """+ return hashlib.sha256(token.encode("utf-8")).hexdigest()[:16]++ @staticmethod+ def _auto_approve_names(scope: _BrokerScope) -> frozenset[str]:+ """``granted ∩ [phase6.safety].auto_approve_tool_families`` (ADR-0031).++ Fail-closed on every edge: feature off, empty allowlist, config+ unreadable, or a name failing the broker denylist all yield the empty+ set (arm becomes a symmetric no-op). Allowlist entries are exact tool+ names or an MCP server family written as ``server/`` (trailing slash).+ """+ try:+ from jarvis.core.config import load_config # noqa: PLC0415 — lazy, boot-safe++ safety = load_config().phase6.safety+ if not safety.worker_tool_auto_approve:+ return frozenset()+ allow = [+ str(entry).strip()+ for entry in safety.auto_approve_tool_families+ if str(entry).strip()+ ]+ if not allow:+ return frozenset()+ granted = {+ str(spec.get("name") or "").strip()+ for spec in scope.specs+ if str(spec.get("name") or "").strip()+ }+ approved: set[str] = set()+ for name in granted:+ if not worker_tool_name_allowed(name):+ continue+ for entry in allow:+ if name == entry or (+ entry.endswith("/") and name.startswith(entry)+ ):+ approved.add(name)+ break+ return frozenset(approved)+ except Exception: # noqa: BLE001 — pre-authorization must fail closed+ logger.debug("auto-approve set resolution failed (fail-closed)", exc_info=True)+ return frozenset()++ def _arm_auto_approval(self, token: str, scope: _BrokerScope) -> None:+ if not scope.mission_id:+ return+ approver = runtime_refs.get_mission_tool_auto_approver()+ if approver is None:+ return+ with suppress(Exception):+ approver.arm(scope.mission_id, self._grant_key(token), self._auto_approve_names(scope))++ def _disarm_auto_approval(self, token: str, scope: _BrokerScope) -> None:+ if not scope.mission_id:+ return+ approver = runtime_refs.get_mission_tool_auto_approver()+ if approver is None:+ return+ with suppress(Exception):+ approver.disarm(scope.mission_id, self._grant_key(token))+def issue(self,*,@@ -672,6 +775,9 @@ class WorkerToolBroker:with self._lock:self._reap_locked()self._scopes[token] = scope+ # Auto-approval lives exactly as long as the grant: armed here,+ # disarmed on every revocation path (revoke / reaper / test reset).+ self._arm_auto_approval(token, scope)host, port = server.server_address[:2]return WorkerToolBrokerBinding(url=f"http://{host}:{port}",@@ -687,6 +793,7 @@ class WorkerToolBroker:scope = self._scopes.pop(token, None)if scope is not None:scope.revoke("grant_expired")+ self._disarm_auto_approval(token, scope)def lookup(self, token: str) -> _BrokerScope | None:with self._lock:@@ -703,16 +810,18 @@ class WorkerToolBroker:scope = self._scopes.pop(token, None)if scope is not None:scope.revoke("grant_revoked")+ self._disarm_auto_approval(token, scope)def reset_for_tests(self) -> None:with self._lock:- scopes = tuple(self._scopes.values())+ scoped = tuple(self._scopes.items())self._scopes.clear()server = self._serverself._server = Noneself._thread = None- for scope in scopes:+ for token, scope in scoped:scope.revoke("broker_reset")+ self._disarm_auto_approval(token, scope)if server is not None:server.shutdown()server.server_close()diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.jsonindex 0dfce1453c..67b04e8766 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json@@ -1005,16 +1005,6 @@"integration_bad_note": "Provider konnte nicht erreicht werden.","failed": "Test fehlgeschlagen"},- "apikeys_base_url": {- "label": "Server-URL",- "placeholder_required": "z. B. http://localhost:8000 — erforderlich",- "save": "Speichern",- "saving": "Speichere…",- "saved": "Server-URL gespeichert",- "cleared": "Server-URL auf den Standard zurückgesetzt",- "hint_default": "Leer lassen, um die oben gezeigte Standard-Adresse zu verwenden.",- "hint_required": "Dieser Anbieter braucht eine Server-URL — trage ein, wo dein lokaler Server läuft."- },"apikeys_model": {"heading": "Modell","recommended_tag": "Empfohlen",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.jsonindex e9a684963c..d298c0667a 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json@@ -1006,16 +1006,6 @@"integration_bad_note": "The provider could not be reached.","failed": "Test failed"},- "apikeys_base_url": {- "label": "Server URL",- "placeholder_required": "e.g. http://localhost:8000 — required",- "save": "Save",- "saving": "Saving…",- "saved": "Server URL saved",- "cleared": "Server URL reset to the default",- "hint_default": "Leave empty to use the default address shown above.",- "hint_required": "This provider needs a server URL — enter where your local server runs."- },"apikeys_model": {"heading": "Model","recommended_tag": "Recommended",diff --git a/jarvis/ui/web/server.py b/jarvis/ui/web/server.pyindex 2a8b25373f..8b600edd55 100644--- a/jarvis/ui/web/server.py+++ b/jarvis/ui/web/server.py@@ -135,9 +135,20 @@ class WebServer:# unchanged. See docs/superpowers/specs/2026-05-11-pre-thinking-ack-# flash-brain-design.md §4.self.bus.subscribe(AnnouncementRequested, self._forward_preamble_to_chat)- from jarvis.missions.tool_approvals import MissionToolApprovalCoordinator+ from jarvis.core import runtime_refs+ from jarvis.missions.tool_approvals import (+ MissionToolApprovalCoordinator,+ MissionToolAutoApprover,+ )self._mission_tool_approvals = MissionToolApprovalCoordinator(self.bus)+ # Mission-scoped tool pre-authorization (ADR-0031): answers the+ # approval gate for tools a mission's broker grant pre-authorizes+ # ([phase6.safety].auto_approve_tool_families), full audit chain+ # preserved. Registered in runtime_refs because the WorkerToolBroker+ # lives below the web layer (same pattern as the supervisor gateway).+ self._mission_tool_auto_approver = MissionToolAutoApprover(self.bus)+ runtime_refs.set_mission_tool_auto_approver(self._mission_tool_auto_approver)self.app: FastAPI = self._build_app()self.app.state.refresh_scheduler = Nonediff --git a/tests/missions/test_mission_tool_auto_approver.py b/tests/missions/test_mission_tool_auto_approver.pynew file mode 100644index 0000000000..edee3f4053--- /dev/null+++ b/tests/missions/test_mission_tool_auto_approver.py@@ -0,0 +1,396 @@+"""MissionToolAutoApprover — mission-scoped tool pre-authorization (ADR-0031).++While a mission's broker grant is live, ask-tier calls for tools in+``granted ∩ [phase6.safety].auto_approve_tool_families`` are answered on the+bus (ActionApproved with a ``mission-grant:`` audit label) — the gate is+answered, never bypassed. Everything else keeps today's behavior: block and+deny on timeout. Arming is owned by the WorkerToolBroker and lives exactly as+long as the grant.+"""++from __future__ import annotations++import asyncio+from types import SimpleNamespace+from typing import Any+from uuid import uuid4++import pytest++from jarvis.core import runtime_refs+from jarvis.core.bus import EventBus+from jarvis.core.config import Phase6SafetyConfig, SafetyConfig+from jarvis.core.events import ActionApprovalRequired, ActionApproved+from jarvis.core.protocols import (+ ExecutionContext,+ SupervisorToolDescriptor,+ SupervisorToolRequest,+ ToolResult,+)+from jarvis.missions.tool_approvals import MissionToolAutoApprover+from jarvis.missions.workers.capabilities import WorkerCapabilityInventory+from jarvis.missions.workers.worker_tool_broker import _BROKER+from jarvis.safety import ApprovalWorkflow, RiskTierEvaluator, ToolExecutor+++async def _collect_approvals(bus: EventBus) -> list[ActionApproved]:+ got: list[ActionApproved] = []++ async def _cap(ev: object) -> None:+ if isinstance(ev, ActionApproved):+ got.append(ev)++ bus.subscribe_all(_cap)+ return got+++def _required(+ *,+ mission_id: str | None,+ tool_name: str,+ risk_tier: str = "ask",+ reason: str = "risk_tier",+) -> ActionApprovalRequired:+ return ActionApprovalRequired(+ trace_id=uuid4(),+ tool_name=tool_name,+ risk_tier=risk_tier, # type: ignore[arg-type]+ reason=reason,+ mission_id=mission_id,+ worker_id="w1",+ )+++# ------------------------------------------------------------- unit level+++async def test_approves_armed_tool_for_its_mission() -> None:+ bus = EventBus()+ approver = MissionToolAutoApprover(bus)+ approvals = await _collect_approvals(bus)+ approver.arm("m1", "grant-a", frozenset({"external-action"}))++ await bus.publish(_required(mission_id="m1", tool_name="external-action"))+ await asyncio.sleep(0)++ assert len(approvals) == 1+ assert approvals[0].tool_name == "external-action"+ assert approvals[0].approved_by == "mission-grant:m1"+++async def test_ignores_unarmed_mission_and_missing_mission_id() -> None:+ bus = EventBus()+ approver = MissionToolAutoApprover(bus)+ approvals = await _collect_approvals(bus)+ approver.arm("m1", "grant-a", frozenset({"external-action"}))++ await bus.publish(_required(mission_id="other", tool_name="external-action"))+ await bus.publish(_required(mission_id=None, tool_name="external-action"))+ await asyncio.sleep(0)++ assert approvals == []+++async def test_ignores_tool_outside_the_armed_set() -> None:+ bus = EventBus()+ approver = MissionToolAutoApprover(bus)+ approvals = await _collect_approvals(bus)+ approver.arm("m1", "grant-a", frozenset({"external-action"}))++ await bus.publish(_required(mission_id="m1", tool_name="gmail/send_message"))+ await asyncio.sleep(0)++ assert approvals == []+++async def test_forbidden_broker_names_are_never_approved_even_if_armed() -> None:+ """Defense in depth: the broker denylist is re-checked at approval time,+ so a bad arm can never authorize run-shell / spawn / credential tools."""+ bus = EventBus()+ approver = MissionToolAutoApprover(bus)+ approvals = await _collect_approvals(bus)+ approver.arm(+ "m1",+ "grant-a",+ frozenset({"run-shell", "spawn-worker", "reveal-key-tool"}),+ )++ for name in ("run-shell", "spawn-worker", "reveal-key-tool"):+ await bus.publish(_required(mission_id="m1", tool_name=name))+ await asyncio.sleep(0)++ assert approvals == []+++async def test_never_answers_block_tier_or_foreign_reasons() -> None:+ bus = EventBus()+ approver = MissionToolAutoApprover(bus)+ approvals = await _collect_approvals(bus)+ approver.arm("m1", "grant-a", frozenset({"external-action"}))++ await bus.publish(+ _required(mission_id="m1", tool_name="external-action", risk_tier="block")+ )+ await bus.publish(+ _required(mission_id="m1", tool_name="external-action", reason="something-else")+ )+ await asyncio.sleep(0)++ assert approvals == []+++async def test_plausibility_reason_is_answered() -> None:+ """The plausibility guard is a voice heuristic — meaningless for an+ unattended worker, so a plausibility-escalated call is answered too."""+ bus = EventBus()+ approver = MissionToolAutoApprover(bus)+ approvals = await _collect_approvals(bus)+ approver.arm("m1", "grant-a", frozenset({"external-action"}))++ await bus.publish(+ _required(+ mission_id="m1",+ tool_name="external-action",+ risk_tier="monitor",+ reason="plausibility",+ )+ )+ await asyncio.sleep(0)++ assert len(approvals) == 1+++async def test_server_prefix_grant_covers_namespaced_tool() -> None:+ bus = EventBus()+ approver = MissionToolAutoApprover(bus)+ approvals = await _collect_approvals(bus)+ approver.arm("m1", "grant-a", frozenset({"github"}))++ await bus.publish(_required(mission_id="m1", tool_name="github/list_issues"))+ await asyncio.sleep(0)++ assert len(approvals) == 1+++async def test_disarm_is_per_grant_not_per_mission() -> None:+ """Two live grants for one mission: disarming one must not kill the other;+ disarming both must."""+ bus = EventBus()+ approver = MissionToolAutoApprover(bus)+ approvals = await _collect_approvals(bus)+ approver.arm("m1", "grant-a", frozenset({"external-action"}))+ approver.arm("m1", "grant-b", frozenset({"other-tool"}))++ approver.disarm("m1", "grant-b")+ await bus.publish(_required(mission_id="m1", tool_name="external-action"))+ await asyncio.sleep(0)+ assert len(approvals) == 1++ approver.disarm("m1", "grant-a")+ await bus.publish(_required(mission_id="m1", tool_name="external-action"))+ await asyncio.sleep(0)+ assert len(approvals) == 1 # unchanged — fully disarmed+++# ------------------------------------------------ end-to-end ToolExecutor+++class _AskTool:+ name = "external-action"+ risk_tier = "ask"+ schema: dict[str, Any] = {"type": "object", "properties": {}}++ def __init__(self) -> None:+ self.calls = 0+ self.approved_by = ""++ async def execute(+ self, _args: dict[str, Any], ctx: ExecutionContext+ ) -> ToolResult:+ self.calls += 1+ self.approved_by = ctx.approved_by+ return ToolResult(success=True, output="executed")+++async def test_armed_mission_call_executes_without_human() -> None:+ bus = EventBus()+ executor = ToolExecutor(+ bus,+ RiskTierEvaluator(SafetyConfig()),+ ApprovalWorkflow(bus, timeout_s=0.05),+ default_timeout_s=0.05,+ )+ approver = MissionToolAutoApprover(bus)+ tool = _AskTool()+ approver.arm("m-e2e", "grant-a", frozenset({tool.name}))++ result = await executor.execute(+ tool,+ {},+ config_snapshot={"mission_id": "m-e2e", "worker_id": "w1", "voice_confirm": False},+ )++ assert result.success is True+ assert tool.calls == 1+ assert tool.approved_by == "mission-grant:m-e2e"+++async def test_unarmed_mission_call_still_denies_on_timeout() -> None:+ bus = EventBus()+ executor = ToolExecutor(+ bus,+ RiskTierEvaluator(SafetyConfig()),+ ApprovalWorkflow(bus, timeout_s=0.05),+ default_timeout_s=0.05,+ )+ MissionToolAutoApprover(bus) # constructed but never armed+ tool = _AskTool()++ result = await executor.execute(+ tool,+ {},+ config_snapshot={"mission_id": "m-e2e", "worker_id": "w1", "voice_confirm": False},+ )++ assert result.success is False+ assert "approval-denied" in (result.error or "")+ assert tool.calls == 0+++# ------------------------------------------------- broker arm/disarm wiring+++class _Gateway:+ def catalog(self) -> tuple[SupervisorToolDescriptor, ...]:+ return (+ SupervisorToolDescriptor(+ name="external-action",+ description="A consequential external action.",+ input_schema={"type": "object", "properties": {}},+ risk_tier="ask",+ ),+ SupervisorToolDescriptor(+ name="other-tool",+ description="Another tool, not allowlisted.",+ input_schema={"type": "object", "properties": {}},+ risk_tier="ask",+ ),+ )++ @property+ def catalog_version(self) -> int:+ return 1++ async def execute(+ self,+ _name: str,+ _arguments: dict[str, Any],+ _request: SupervisorToolRequest,+ ) -> ToolResult:+ return ToolResult(success=True, output="ok")+++class _RecorderApprover:+ def __init__(self) -> None:+ self.armed: list[tuple[str, str, set[str]]] = []+ self.disarmed: list[tuple[str, str]] = []++ def arm(self, mission_id: str, grant_key: str, names: frozenset[str]) -> None:+ self.armed.append((mission_id, grant_key, set(names)))++ def disarm(self, mission_id: str, grant_key: str) -> None:+ self.disarmed.append((mission_id, grant_key))+++def _clean_broker_state(monkeypatch: pytest.MonkeyPatch):+ runtime_refs._reset_for_tests()+ yield+ _BROKER.reset_for_tests()+ runtime_refs._reset_for_tests()+++async def test_broker_grant_arms_intersection_and_disarms_on_close(+ monkeypatch: pytest.MonkeyPatch,+ _clean_broker_state: None,+) -> None:+ recorder = _RecorderApprover()+ runtime_refs.set_supervisor_tool_gateway(_Gateway())+ runtime_refs.set_mission_tool_auto_approver(recorder)+ cfg = SimpleNamespace(+ phase6=SimpleNamespace(+ safety=Phase6SafetyConfig(+ worker_tool_auto_approve=True,+ auto_approve_tool_families=["external-action"],+ )+ )+ )+ monkeypatch.setattr("jarvis.core.config.load_config", lambda *a, **k: cfg)++ inventory = WorkerCapabilityInventory.build(+ native_tool_names=("external-action", "other-tool"),+ task_text="Perform the external action.",+ )+ binding = inventory.bind_broker(ttl_s=60.0, mission_id="m1", worker_id="w1")+ assert binding.available++ assert len(recorder.armed) == 1+ mission_id, grant_key, names = recorder.armed[0]+ assert mission_id == "m1"+ # Intersection: granted ∩ allowlist — the non-allowlisted grant member+ # must not be armed.+ assert names == {"external-action"}++ binding.close()+ assert recorder.disarmed == [("m1", grant_key)]+++async def test_broker_arm_is_empty_when_feature_disabled(+ monkeypatch: pytest.MonkeyPatch,+ _clean_broker_state: None,+) -> None:+ recorder = _RecorderApprover()+ runtime_refs.set_supervisor_tool_gateway(_Gateway())+ runtime_refs.set_mission_tool_auto_approver(recorder)+ cfg = SimpleNamespace(+ phase6=SimpleNamespace(+ safety=Phase6SafetyConfig(+ worker_tool_auto_approve=False,+ auto_approve_tool_families=["external-action"],+ )+ )+ )+ monkeypatch.setattr("jarvis.core.config.load_config", lambda *a, **k: cfg)++ inventory = WorkerCapabilityInventory.build(+ native_tool_names=("external-action",),+ task_text="Perform the external action.",+ )+ binding = inventory.bind_broker(ttl_s=60.0, mission_id="m1", worker_id="w1")++ assert len(recorder.armed) == 1+ assert recorder.armed[0][2] == set() # symmetric no-op arm, nothing approved+ binding.close()+++# --------------------------------------------------------- config surface+++def test_shipped_default_allowlist_is_read_only_knowledge() -> None:+ safety = Phase6SafetyConfig()+ assert safety.worker_tool_auto_approve is True+ assert set(safety.auto_approve_tool_families) == {+ "search_web",+ "wiki-list",+ "wiki-recall",+ "wiki-page-read",+ "wiki-ingest",+ "session-latest-turn",+ }+ # No server-family prefixes in the shipped default (a prefix silently+ # authorizes every future tool that server adds).+ assert not any(entry.endswith("/") for entry in safety.auto_approve_tool_families)+++def test_safety_config_carries_approval_timeout() -> None:+ assert SafetyConfig().tool_approval_timeout_s == 60.0