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(pipeline): restore supervisor tools across runtimes
Ruben Lütkefaad6bffc20b
diff --git a/Dockerfile b/Dockerfileindex 7c97b0c9df..b7ba4dd7b5 100644--- a/Dockerfile+++ b/Dockerfile@@ -40,12 +40,14 @@ ENV PYTHONDONTWRITEBYTECODE=1 \PIP_DISABLE_PIP_VERSION_CHECK=1# build-essential/libffi: a few base deps build from sdist on slim.+# git: Jarvis-Agent lean workspaces are real isolated repositories even when+# the distribution image intentionally carries no host checkout history.# libportaudio2: backs sounddevice (a lazy-imported base dep) so any audio path# imports cleanly even though the container has no audio hardware.# curl: the HEALTHCHECK below.RUN apt-get update \&& apt-get install -y --no-install-recommends \- build-essential libffi-dev libportaudio2 curl \+ build-essential libffi-dev libportaudio2 curl git \&& rm -rf /var/lib/apt/lists/*WORKDIR /app@@ -62,7 +64,7 @@ RUN python -m pip install --upgrade pip \# Non-root. /app/data is the only writable location at runtime.RUN useradd --system --uid 1000 --shell /usr/sbin/nologin jarvis \- && mkdir -p /app/data \+ && mkdir -p /app/data/home \&& chown -R jarvis:jarvis /app/dataUSER jarvis@@ -76,7 +78,8 @@ EXPOSE 8000ENV JARVIS_BIND_HOST=0.0.0.0 \JARVIS_NONINTERACTIVE=1 \JARVIS_CONFIG=/app/data/jarvis.toml \- JARVIS_DATA_DIR=/app/data+ JARVIS_DATA_DIR=/app/data \+ HOME=/app/data/home# Generous start-period: first boot builds the brain in the background.HEALTHCHECK --interval=30s --timeout=5s --start-period=60s --retries=6 \diff --git a/docs/adr/0025-mission-scoped-worker-tool-broker.md b/docs/adr/0025-mission-scoped-worker-tool-broker.mdnew file mode 100644index 0000000000..392029ed9e--- /dev/null+++ b/docs/adr/0025-mission-scoped-worker-tool-broker.md@@ -0,0 +1,104 @@+---+title: "ADR-0025: Mission-Scoped Worker Tool Broker"+slug: adr-0025-mission-scoped-worker-tool-broker+diataxis: adr+status: active+owner: project-maintainers+last_reviewed: 2026-07-13+phase: 6+audience: developer+---++# ADR-0025 — Mission-Scoped Worker Tool Broker++**Status:** Accepted (2026-07-13)+**Phase:** 6 — Self-Healing Jarvis-Agents Orchestrator+**Reference:** ADR-0009, ADR-0011, AP-3, AP-5, AP-14, AP-21, AP-22++## Context++Mission workers run in isolated processes and worktrees. That isolation kept+the supervisor's connected Marketplace, MCP, and app-command tools out of the+worker capability surface. A tool could therefore be healthy and callable in+the main Jarvis while a delegated mission honestly reported that it was not+available. Directly copying connector configurations into every worker was not+acceptable: it exposed credentials, worked only for selected CLI backends, and+bypassed the supervisor's `ToolExecutor` safety path.++The production worker chain is provider-agnostic. Claude CLI, Codex CLI,+Gemini CLI, Google CLI, and API workers need one capability contract that does+not depend on a provider-specific MCP implementation.++## Decision++Personal Jarvis uses a process-local, mission-scoped worker tool broker. Each+mission receives a short-lived authenticated grant containing only+task-relevant MCP tools, connected native connector tools, and the restricted+app commands explicitly allowed for workers. CLI workers reach the grant+through a stdio MCP companion connected to a loopback-only HTTP endpoint; API+workers call the same binding directly.++The supervisor retains the live tool objects and all credentials. Every broker+request executes through the supervisor's `ToolExecutor`; workers never call+`Tool.execute()` directly. An ask-tier request remains suspended on its original+trace until an explicit approval or denial arrives. The pending call is exposed+through mission REST and CLI actions without adding a global waiting mission+state; approval resumes that exact call, while denial and timeout execute+nothing.++The mission controller owns one broker grant per worker iteration and closes it+as a bounded quiescence barrier before invoking the critic. The grant retains a+credential-free terminal outcome for every supervisor call. Critic review is+allowed only when no call remains active and every recorded call succeeded;+denied, cancelled, timed-out, failed, or outcome-unknown calls force the+existing worker-error mission path. A worker model therefore cannot ignore a+tool error and claim successful completion.++The grant fails closed. Recursive mission tools, skill execution, credential+surfaces, secret-reading names, and config mutation are never exported. A+missing supervisor reference, empty relevant tool set, expired token, or+unsupported runtime produces no grant rather than a partially trusted one.+Catalog descriptors are resolved from the live supervisor on each list and+execute operation, and grant closure revokes the bearer and cancels active+calls.++## Consequences++- Connected capabilities remain usable after delegation without copying OAuth+ tokens, API keys, or MCP environment blocks into a worker workspace.+- All supported worker families consume the same broker contract; no provider+ name is treated as the capability boundary.+- Risk-tier evaluation, audit events, plausibility checks, and approvals remain+ centralized in `ToolExecutor`.+- A worker receives only the capabilities relevant to its mission, not the+ supervisor's complete tool catalog.+- Consequential actions wait for an explicit user decision through the mission+ API/CLI (or an already-authorized scheduled-task decision); silence never+ becomes implicit approval.+- A successful worker transcript is insufficient evidence when its broker+ completion certificate contains an unclean call; the critic is not invoked.+- The supervisor now owns a small authenticated loopback server for the+ lifetime of active grants. Tokens are revoked on completion and bounded by a+ TTL as a crash backstop.++## Alternatives considered++- **Pass original MCP configs to every worker:** rejected because configs can+ contain credentials and support differs across provider CLIs.+- **Let workers invoke connector SDKs directly:** rejected because it bypasses+ `ToolExecutor`, duplicates auth logic, and breaks the safety audit trail.+- **Expose every supervisor tool:** rejected because it reintroduces recursive+ spawn paths, secret access, off-topic actions, and excessive model schemas.+- **Keep connected tools router-only:** rejected because heavy missions that+ genuinely need a connected source would remain unable to fulfill the task.+- **Pin the feature to Claude CLI MCP support:** rejected under AP-21/AP-22;+ capability transport must work across provider families.++## Follow-up items++- Keep provider-parity tests for every supported worker backend.+- Keep an end-to-end stdio MCP test that proves list and execute behavior across+ the authenticated loopback boundary.+- Keep the credential-free mission test covering grant selection, approval+ resume, completion certification, and revocation.+- Preserve the explicit recursive-tool and secret/config deny guards.diff --git a/docs/adr/0026-native-windows-codex-worker-sandbox.md b/docs/adr/0026-native-windows-codex-worker-sandbox.mdnew file mode 100644index 0000000000..28afe7c872--- /dev/null+++ b/docs/adr/0026-native-windows-codex-worker-sandbox.md@@ -0,0 +1,88 @@+---+title: "ADR-0026: Native Windows Codex Worker Sandbox"+slug: adr-0026-native-windows-codex-worker-sandbox+diataxis: adr+status: active+owner: project-maintainers+last_reviewed: 2026-07-13+phase: 6+audience: developer+---++# ADR-0026 — Native Windows Codex Worker Sandbox++**Status:** Accepted (2026-07-13)+**Phase:** 6 — Self-Healing Jarvis-Agents Orchestrator+**Reference:** ADR-0009, ADR-0025, AP-7, AP-10, AP-20, AP-23++## Context++`CodexDirectWorker` deliberately passes `--ignore-user-config` so a mission+cannot inherit arbitrary user plugins, MCP servers, or execution policy. On+native Windows this also removes the user's `[windows].sandbox` selection.+With Codex CLI 0.144.3, the resulting partial sandbox allowed reads but made+the file-change tool report the mission worktree as read-only. Codex then+emitted `turn.completed`, and the worker translated that transport-level event+into mission success even though the requested file did not exist.++The native Windows file-change path also remained unreliable after selecting+the fallback sandbox, while PowerShell commands inside the same ACL-bounded+worktree could write successfully. Windows PowerShell 5.1 adds a UTF-8 byte+order mark for common text-writing commands, which can corrupt TOML and other+strict text formats.++## Decision++Mission workers continue to ignore machine-global Codex configuration. On+native Windows, Jarvis explicitly selects Codex's `unelevated` sandbox while+retaining `workspace-write` and `approval_policy=never`. The worker sets the+mission worktree as the primary working directory and does not use full-access+or sandbox-bypass mode.++The Windows worker prompt carries a bounded recovery instruction: when Codex's+file-change tool reports the worktree as read-only, it may use a PowerShell+command inside the current worktree. Text writes must use BOM-free UTF-8, and+the worker must never write outside the worktree.++`turn.completed` remains a transport event, not sufficient proof of task+success. A sandbox write rejection with no later successful file or command+tool event is translated into an error result. Failed tool events do not count+as delivered work and cannot suppress cross-family recovery.++POSIX workers retain the normal `workspace-write` sandbox and receive no+Windows-specific prompt guidance.++## Consequences++- A fresh Windows install does not require administrator-approved sandbox+ setup before Codex mission workers can create artifacts.+- Native Windows workers remain bounded by the mission worktree and ACL-based+ sandbox rather than receiving full filesystem access.+- BOM-free UTF-8 is explicit on the PowerShell recovery path.+- A model turn that merely describes a rejected write can no longer be marked+ successful.+- The recovery path depends on Codex emitting command events accurately; the+ worker therefore keeps regression tests for failed patch, successful shell+ recovery, and false-success classification.++## Alternatives considered++- **Load the user's full Codex config:** rejected because it can import+ unrelated MCP servers, plugins, and policies into an unattended worker.+- **Use `danger-full-access` or bypass the sandbox:** rejected because a git+ worktree is not an operating-system security boundary.+- **Require the elevated Windows sandbox:** rejected as the universal default+ because it needs administrator-approved machine setup and can be blocked by+ enterprise policy.+- **Accept `turn.completed` as success:** rejected because it describes model+ turn completion, not successful side effects.+- **Allow PowerShell's default UTF-8 encoding:** rejected because the emitted+ byte-order mark can break strict configuration and protocol files.++## Follow-up items++- Re-probe the file-change tool when upgrading Codex CLI and remove the prompt+ recovery only after a real native Windows write smoke test passes.+- Keep Phase 6 worker smoke coverage for a real file written through the+ Claude-to-Codex cross-family fallback.+- Keep Linux/headless tests on the standard `workspace-write` path.diff --git a/docs/adr/0027-portable-mission-isolation-root.md b/docs/adr/0027-portable-mission-isolation-root.mdnew file mode 100644index 0000000000..5cec3da1b0--- /dev/null+++ b/docs/adr/0027-portable-mission-isolation-root.md@@ -0,0 +1,91 @@+---+title: "ADR-0027: Portable Mission Isolation Root"+slug: adr-0027-portable-mission-isolation-root+diataxis: adr+status: active+owner: project-maintainers+last_reviewed: 2026-07-13+phase: 6+audience: developer+---++# ADR-0027 — Portable Mission Isolation Root++**Status:** Accepted (2026-07-13)+**Phase:** 6 — Self-Healing Jarvis-Agents Orchestrator+**Reference:** ADR-0009, ADR-0025, ADR-0026, AP-10, AP-23++## Context++Desktop checkouts place mission worktrees beside the repository under+`<repo-parent>/jarvis-agent-outputs`. The same derivation is invalid for the+official non-root container: the application root is `/app`, its parent is+`/`, and only `/app/data` is writable. Mission bootstrap therefore raised+`PermissionError` while creating `/jarvis-agent-outputs`. The fast health+endpoint was already serving, which concealed the failed mission stack from a+superficial boot probe.++The distribution image also omitted the `git` executable. It could import the+mission modules but could not create the standalone repositories used by lean+Jarvis-Agent tasks. Its declared user home was `/home/jarvis`, but that+directory did not exist. Skill, document, CLI-tool, and board registries then+failed independently while trying to create their per-user state, shrinking+the tool surface even though the web server continued to answer health checks.++## Decision++Mission output-root precedence is:++1. `JARVIS_ISOLATION_ROOT`, when explicitly set;+2. `<JARVIS_DATA_DIR>/jarvis-agent-outputs` on portable/headless installs;+3. the existing checkout rule under `<repo-parent>`, including the legacy+ `sub-agents-outputs` read fallback.++The root resolver is shared by bootstrap and `WorktreeManager`, so callers do+not re-derive different paths. It returns a path but does not create it; the+existing bootstrap remains responsible for creation and error reporting.++The official runtime image installs `git`. A distribution image without host+checkout history can therefore run lean artifact tasks in an isolated+standalone repository. Tasks that require the Personal Jarvis source checkout+still require a real repository and must fail honestly when it is absent.++The container sets `HOME=/app/data/home` and creates that directory before+dropping privileges. Per-user skills, CLI metadata, documents, and related+registries therefore share the declared writable data volume rather than+trying to create an undeclared `/home/jarvis` tree.++## Consequences++- The mission stack boots under the non-root container user without writing to+ the filesystem root.+- Mission artifacts persist in the same writable data volume as the headless+ runtime state.+- Headless skill and CLI registries retain a writable per-user home and no+ longer disappear behind caught `PermissionError` exceptions.+- Desktop checkout layouts and legacy output discovery remain unchanged when+ neither environment override is present.+- The container image grows by the system `git` package and its runtime+ dependencies.+- Fast health remains useful, but headless verification must also inspect the+ mission stack or exercise workspace creation so a background bootstrap+ failure cannot be mistaken for full readiness.++## Alternatives considered++- **Make `/jarvis-agent-outputs` writable:** rejected because it adds a second+ mutable container path and bypasses the declared data volume.+- **Run the image as root:** rejected because it weakens the container security+ boundary to hide a path bug.+- **Disable missions in headless mode:** rejected because Jarvis-Agents are a+ core provider-agnostic capability, not a desktop-only feature.+- **Keep `git` optional in the official image:** rejected because lean+ workspaces cannot satisfy the isolation and diff-capture contract without it.++## Follow-up items++- Keep a non-root container smoke test that verifies the resolved output root,+ creates a lean workspace, and reaches the health endpoint.+- Keep checkout-mode tests for the repo-parent and legacy output paths.+- Surface an explicit capability error for source-dependent tasks when the+ installed runtime has no host repository history.diff --git a/docs/jarvis-cli-reference.md b/docs/jarvis-cli-reference.mdindex b575a4f84f..0ab72c3ce5 100644--- a/docs/jarvis-cli-reference.md+++ b/docs/jarvis-cli-reference.md@@ -109,12 +109,15 @@ _Generated from the curated command tree by `scripts/ci/gen_cli_reference.py`## missions+- `jarvis missions approve-tool <mission_id> <trace_id> --yes --dry-run` — Approve one paused mission tool call and resume it.- `jarvis missions cancel <mission_id> --yes --dry-run` — Cancel a running mission (kills its worker).+- `jarvis missions deny-tool <mission_id> <trace_id> --reason --dry-run` — Deny one paused mission tool call without executing it.- `jarvis missions dispatch <prompt> --language --confirmed --yes --dry-run` — Dispatch a new self-healing mission — spawns a worker (destructive: --yes).- `jarvis missions kill <worker_id> --yes --dry-run` — Hard-kill a worker process by id.- `jarvis missions list --state --limit` — List missions (optionally filtered by state).- `jarvis missions rerun <mission_id> --confirmed --yes --dry-run` — Re-dispatch a terminal mission's prompt as a new linked mission.- `jarvis missions show <mission_id>` — Show one mission with its events + verdicts.+- `jarvis missions tool-approvals <mission_id>` — List supervisor tool calls waiting for approval in a mission.## outputsdiff --git a/jarvis/__main__.py b/jarvis/__main__.pyindex 3de1b0414c..414ea41759 100644--- a/jarvis/__main__.py+++ b/jarvis/__main__.py@@ -43,6 +43,12 @@ def _build_parser() -> argparse.ArgumentParser:parser.add_argument("--wizard", action="store_true", help="Restart the setup wizard.")parser.add_argument("--check", action="store_true", help="Only show the hardware analysis.")parser.add_argument("--plugins", action="store_true", help="List the plugin registry.")+ parser.add_argument(+ "--worker-tool-broker-stdio",+ action="store_true",+ dest="worker_tool_broker_stdio",+ help=argparse.SUPPRESS,+ )parser.add_argument("--debug", action="store_true", help="Debug logging + console attach.")# Phase 5:parser.add_argument("--phase5-doctor", action="store_true", dest="phase5_doctor",@@ -479,6 +485,10 @@ def main(argv: list[str] | None = None) -> int:args = _parse_args(raw)+ if args.worker_tool_broker_stdio:+ from jarvis.missions.workers.broker_stdio import main as broker_stdio_main++ return broker_stdio_main()if args.check:return _cmd_check()if args.plugins:diff --git a/jarvis/brain/factory.py b/jarvis/brain/factory.pyindex 8e91becd74..777946f3e0 100644--- a/jarvis/brain/factory.py+++ b/jarvis/brain/factory.py@@ -689,6 +689,18 @@ def is_worker_bootstrap_failed() -> bool:return bool(_WORKER_BOOTSTRAP_FAILED[0])+def _register_runtime_manager(manager: Any) -> None:+ """Publish one Brain Manager and its public tool gateway for all surfaces."""+ try:+ from jarvis.brain.tool_gateway import BrainSupervisorToolGateway+ from jarvis.core import runtime_refs++ runtime_refs.set_brain_manager(manager)+ runtime_refs.set_supervisor_tool_gateway(BrainSupervisorToolGateway(manager))+ except Exception as exc: # noqa: BLE001 - registration never blocks boot+ log.debug("Runtime supervisor gateway registration failed: %s", exc)++def _phase2_full_brain(tier: Literal["router"] = "router",bus: Any | None = None,@@ -964,12 +976,7 @@ def _phase2_full_brain(# ``switch-provider`` tool (and the ``describe-app-settings`` snapshot) can# reach it at execute-time for a live, no-restart provider switch. Mirrors# the MissionManager singleton pattern; a headless build registers itself too.- try:- from jarvis.core import runtime_refs-- runtime_refs.set_brain_manager(manager)- except Exception as exc: # noqa: BLE001 — must never block the brain build- log.debug("runtime_refs.set_brain_manager failed: %s", exc)+ _register_runtime_manager(manager)# Wire live-reload on BrainToolsChanged (CLI connect/disconnect).try:@@ -1379,6 +1386,10 @@ def _legacy_full_brain(bus: Any | None = None) -> Any:people=people,)+ # Keep the legacy/headless path on the same public supervisor-tool boundary+ # as the primary router factory.+ _register_runtime_manager(manager)+manager._vision_provider = Nonerouter_tier = getattr(config.brain, "router", None)vision_cfg = getattr(router_tier, "vision", None) if router_tier is not None else Nonediff --git a/jarvis/brain/tool_gateway.py b/jarvis/brain/tool_gateway.pynew file mode 100644index 0000000000..f844658a95--- /dev/null+++ b/jarvis/brain/tool_gateway.py@@ -0,0 +1,174 @@+"""Public, versioned gateway to the Brain Manager's live tool catalog.++Higher layers receive only secret-free descriptors and execute by name. The+concrete ``Tool`` objects and ``ToolExecutor`` remain inside the brain layer,+and every call resolves against the current catalog immediately before use.+"""+from __future__ import annotations++import copy+import threading+from typing import Any, cast+from uuid import UUID++from jarvis.core.protocols import (+ RiskTier,+ SupervisorToolDescriptor,+ SupervisorToolRequest,+ ToolResult,+)++_VALID_RISK_TIERS = frozenset({"safe", "monitor", "ask", "block"})+++class BrainSupervisorToolGateway:+ """Adapter that keeps Brain Manager implementation details private."""++ def __init__(self, manager: Any) -> None:+ self._manager = manager+ self._lock = threading.Lock()+ self._fingerprint: tuple[tuple[str, int], ...] = ()+ self._catalog_version = 0++ def _live_tools(self) -> dict[str, Any]:+ tools = getattr(self._manager, "_tools", None)+ if not isinstance(tools, dict):+ return {}+ for _attempt in range(2):+ try:+ return dict(tools)+ except RuntimeError:+ continue+ return {}++ def catalog(self) -> tuple[SupervisorToolDescriptor, ...]:+ tools = self._live_tools()+ fingerprint = tuple(sorted((str(name), id(tool)) for name, tool in tools.items()))+ with self._lock:+ if fingerprint != self._fingerprint:+ self._fingerprint = fingerprint+ self._catalog_version += 1++ descriptors: list[SupervisorToolDescriptor] = []+ for name, tool in sorted(tools.items()):+ if not callable(getattr(tool, "execute", None)):+ continue+ schema = getattr(tool, "schema", None)+ if not isinstance(schema, dict):+ schema = {"type": "object", "properties": {}}+ raw_risk_tier = str(getattr(tool, "risk_tier", "monitor"))+ risk_tier = cast(+ RiskTier,+ raw_risk_tier if raw_risk_tier in _VALID_RISK_TIERS else "monitor",+ )+ descriptors.append(+ SupervisorToolDescriptor(+ name=str(name),+ description=str(getattr(tool, "description", "")),+ input_schema=copy.deepcopy(schema),+ risk_tier=risk_tier,+ is_action_tool=bool(getattr(tool, "is_action_tool", False)),+ )+ )+ return tuple(descriptors)++ @property+ def catalog_version(self) -> int:+ self.catalog()+ with self._lock:+ return self._catalog_version++ async def execute(+ self,+ name: str,+ arguments: dict[str, Any],+ request: SupervisorToolRequest,+ ) -> ToolResult:+ if request.cancel_token is not None and request.cancel_token.is_cancelled():+ return ToolResult(+ success=False,+ output=None,+ error=f"cancelled ({request.cancel_token.reason or 'requested'})",+ )++ tool = self._live_tools().get(name)+ executor = getattr(self._manager, "_tool_executor", None)+ if tool is None or not callable(getattr(tool, "execute", None)):+ return ToolResult(+ success=False,+ output=None,+ error="Supervisor tool is no longer available.",+ )+ if executor is None or not callable(getattr(executor, "execute", None)):+ return ToolResult(+ success=False,+ output=None,+ error="Supervisor tool gateway is not ready.",+ )++ config_snapshot = dict(request.config_snapshot)+ config_snapshot.update(+ {+ "tool_origin": request.origin,+ "mission_id": request.mission_id,+ "worker_id": request.worker_id,+ }+ )+ return await executor.execute(+ tool,+ dict(arguments),+ user_utterance=request.user_utterance,+ config_snapshot=config_snapshot,+ trace_id=request.trace_id,+ rationale=request.rationale,+ cancel_token=request.cancel_token,+ )++ async def execute_confirmed(+ self,+ trace_id: UUID,+ request: SupervisorToolRequest,+ ) -> ToolResult:+ executor = getattr(self._manager, "_tool_executor", None)+ resume = getattr(executor, "execute_confirmed", None)+ if not callable(resume):+ return ToolResult(+ success=False,+ output=None,+ error="Supervisor confirmation gateway is not ready.",+ )+ config_snapshot = dict(request.config_snapshot)+ config_snapshot.update(+ {+ "tool_origin": request.origin,+ "mission_id": request.mission_id,+ "worker_id": request.worker_id,+ }+ )+ return await resume(+ trace_id,+ user_utterance=request.user_utterance,+ config_snapshot=config_snapshot,+ )++ async def cancel_pending(self, trace_id: UUID) -> bool:+ executor = getattr(self._manager, "_tool_executor", None)+ cancel = getattr(executor, "cancel_pending", None)+ if not callable(cancel):+ return False+ return bool(await cancel(trace_id))++ async def publish_guard_denied(+ self,+ name: str,+ reason: str,+ *,+ trace_id: UUID,+ ) -> None:+ executor = getattr(self._manager, "_tool_executor", None)+ publish = getattr(executor, "publish_guard_denied", None)+ if callable(publish):+ await publish(name, reason, trace_id=trace_id)+++__all__ = ["BrainSupervisorToolGateway"]diff --git a/jarvis/cli_ctl/commands/missions.py b/jarvis/cli_ctl/commands/missions.pyindex 92457c1d85..31e282bd7e 100644--- a/jarvis/cli_ctl/commands/missions.py+++ b/jarvis/cli_ctl/commands/missions.py@@ -29,6 +29,45 @@ def show(mission_id: str = typer.Argument(..., help="Mission id.")) -> None:invoke.run("GET", f"/api/missions/{mission_id}")[email protected]("tool-approvals")+def tool_approvals(mission_id: str = typer.Argument(..., help="Mission id.")) -> None:+ """List supervisor tool calls waiting for approval in a mission."""+ invoke.run("GET", f"/api/missions/{mission_id}/tool-approvals")++[email protected]("approve-tool")+def approve_tool(+ mission_id: str = typer.Argument(..., help="Mission id."),+ trace_id: str = typer.Argument(..., help="Approval trace id."),+ yes: bool = options.yes_opt(),+ dry_run: bool = options.dry_opt(),+) -> None:+ """Approve one paused mission tool call and resume it."""+ invoke.run(+ "POST",+ f"/api/missions/{mission_id}/tool-approvals/{trace_id}/approve",+ assume_yes=yes,+ dry_run=dry_run,+ dangerous=True,+ )++[email protected]("deny-tool")+def deny_tool(+ mission_id: str = typer.Argument(..., help="Mission id."),+ trace_id: str = typer.Argument(..., help="Approval trace id."),+ reason: str = typer.Option("user_denied", "--reason", help="Audit reason."),+ dry_run: bool = options.dry_opt(),+) -> None:+ """Deny one paused mission tool call without executing it."""+ invoke.run(+ "POST",+ f"/api/missions/{mission_id}/tool-approvals/{trace_id}/deny",+ body={"reason": reason},+ dry_run=dry_run,+ )++@app.command()def dispatch(prompt: str = typer.Argument(..., help="The task for the worker."),diff --git a/jarvis/core/events.py b/jarvis/core/events.pyindex 8320d6e15e..6765ffd1f1 100644--- a/jarvis/core/events.py+++ b/jarvis/core/events.py@@ -193,6 +193,24 @@ class ActionProposed(Event):rationale: str = ""+@dataclass(frozen=True, slots=True)+class ActionApprovalRequired(Event):+ """A concrete tool call is paused until this trace receives a decision.++ ``args_preview`` is redacted and length-capped before publication. Mission+ identifiers are correlation metadata only; the mission itself remains in+ its running state while this individual call waits.+ """++ tool_name: str = ""+ risk_tier: RiskTier = "ask"+ reason: str = "risk_tier" # "risk_tier" | "plausibility"+ args_preview: str = ""+ expires_at_ns: int = 0+ mission_id: str | None = None+ worker_id: str | None = None++@dataclass(frozen=True, slots=True)class ActionApproved(Event):tool_name: str = ""diff --git a/jarvis/core/protocols.py b/jarvis/core/protocols.pyindex 57608e158b..0084278391 100644--- a/jarvis/core/protocols.py+++ b/jarvis/core/protocols.py@@ -155,6 +155,31 @@ class ToolResult:artifacts: tuple[str, ...] = field(default_factory=tuple)+@dataclass(frozen=True, slots=True)+class SupervisorToolDescriptor:+ """Secret-free description of one tool owned by the supervisor."""++ name: str+ description: str+ input_schema: dict[str, Any]+ risk_tier: RiskTier+ is_action_tool: bool = False+++@dataclass(frozen=True, slots=True)+class SupervisorToolRequest:+ """Execution metadata supplied by Realtime or a mission worker."""++ trace_id: UUID+ origin: str+ user_utterance: str+ rationale: str = ""+ mission_id: str | None = None+ worker_id: str | None = None+ config_snapshot: dict[str, Any] = field(default_factory=dict)+ cancel_token: CancelToken | None = None++# ----------------------------------------------------------------------# Protocols# ----------------------------------------------------------------------@@ -323,6 +348,39 @@ class Tool(Protocol):...+@runtime_checkable+class SupervisorToolGateway(Protocol):+ """Versioned catalog and sole safety-gated execution seam for owned tools."""++ @property+ def catalog_version(self) -> int: ...++ def catalog(self) -> tuple[SupervisorToolDescriptor, ...]: ...++ async def execute(+ self,+ name: str,+ arguments: dict[str, Any],+ request: SupervisorToolRequest,+ ) -> ToolResult: ...++ async def execute_confirmed(+ self,+ trace_id: UUID,+ request: SupervisorToolRequest,+ ) -> ToolResult: ...++ async def cancel_pending(self, trace_id: UUID) -> bool: ...++ async def publish_guard_denied(+ self,+ name: str,+ reason: str,+ *,+ trace_id: UUID,+ ) -> None: ...++@runtime_checkableclass MemoryStore(Protocol):"""Persistent-Memory-Layer (SQLite, ChromaDB, …)."""diff --git a/jarvis/core/redact.py b/jarvis/core/redact.pyindex 220dc91f8b..10c7608ab6 100644--- a/jarvis/core/redact.py+++ b/jarvis/core/redact.py@@ -69,7 +69,7 @@ _REDACTORS: tuple[tuple[str, re.Pattern[str]], ...] = ("labelled_secret",re.compile(r"(?i)(\b(?:api[_-]?key|secret(?:[_-]?key)?|password|passwd|pwd"- r"|access[_-]?token|auth[_-]?token|client[_-]?secret)\b\s*[:=]\s*)"+ r"|access[_-]?token|auth[_-]?token|client[_-]?secret)\b['\"]?\s*[:=]\s*)"r"['\"]?[^\s'\"]{8,}"),),diff --git a/jarvis/core/runtime_refs.py b/jarvis/core/runtime_refs.pyindex 30e6b54133..29fe9edc49 100644--- a/jarvis/core/runtime_refs.py+++ b/jarvis/core/runtime_refs.py@@ -32,6 +32,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] = []_SPEECH_PIPELINE: list[Any] = []_MCP_REGISTRY: list[Any] = []@@ -60,6 +61,16 @@ def get_brain_manager() -> Any | None:return _BRAIN_MANAGER[0] if _BRAIN_MANAGER else None+def set_supervisor_tool_gateway(gateway: Any) -> None:+ """Register the protocol-only gateway to supervisor-owned tools."""+ _set(_SUPERVISOR_TOOL_GATEWAY, gateway)+++def get_supervisor_tool_gateway() -> Any | None:+ """Return the live supervisor tool gateway, or ``None`` before brain wiring."""+ return _SUPERVISOR_TOOL_GATEWAY[0] if _SUPERVISOR_TOOL_GATEWAY else None++def set_speech_pipeline(pipeline: Any) -> None:"""Register the live SpeechPipeline (called from the desktop-app bootstrap)."""_set(_SPEECH_PIPELINE, pipeline)@@ -200,6 +211,7 @@ def cancel_active_chat_turn() -> bool:def _reset_for_tests() -> None:"""Clear all refs. Test-only helper (fixtures call this in teardown)."""_BRAIN_MANAGER.clear()+ _SUPERVISOR_TOOL_GATEWAY.clear()_SPEECH_PIPELINE.clear()_MCP_REGISTRY.clear()_WEB_APP.clear()diff --git a/jarvis/missions/critic/runner.py b/jarvis/missions/critic/runner.pyindex a393e0ec45..4a89d545ad 100644--- a/jarvis/missions/critic/runner.py+++ b/jarvis/missions/critic/runner.py@@ -134,6 +134,136 @@ _RE_CODEX_ACTION_ITEM = re.compile(r'"type"\s*:\s*"(command_execution|file_change|mcp_tool_call|web_search)"')+_ACTION_ITEM_TYPES: Final[frozenset[str]] = frozenset(+ {"command_execution", "file_change", "mcp_tool_call", "web_search"}+)+_FAILED_RESULT_STATUSES: Final[frozenset[str]] = frozenset(+ {+ "approval_denied",+ "blocked",+ "cancelled",+ "canceled",+ "denied",+ "error",+ "expired",+ "failed",+ "outcome_unknown",+ "rejected",+ "timed_out",+ "timeout",+ "unavailable",+ }+)+_RE_DENIED_RESULT = re.compile(+ r"^(?:approval[ _-]?denied|permission[ _-]?denied|denied|blocked|rejected|"+ r"cancelled|canceled|timed[ _-]?out|timeout|expired|outcome[ _-]?unknown)"+ r"(?:\b|[ _:-])",+ re.IGNORECASE,+)+++def _result_signals_failure(value: Any) -> bool:+ """Return whether a provider result explicitly reports non-execution.++ The mission tool broker returns structured ``success``/``status`` fields,+ while Claude-style streams commonly use ``is_error`` and some adapters+ serialize that mapping into the result's text content. All three shapes+ must override the preceding call frame: an attempted action is not proof+ that the action completed.+ """+ if isinstance(value, dict):+ is_error = value.get("is_error", value.get("isError"))+ if is_error is True or (+ isinstance(is_error, str) and is_error.strip().lower() == "true"+ ):+ return True+ for key in ("success", "ok"):+ flag = value.get(key)+ if flag is False or (+ isinstance(flag, str) and flag.strip().lower() == "false"+ ):+ return True+ for key in ("exit_code", "return_code"):+ code = value.get(key)+ if code is not None and str(code).strip() not in {"", "0"}:+ return True+ status = str(value.get("status", "")).strip().lower().replace("-", "_")+ if status in _FAILED_RESULT_STATUSES:+ return True+ error = value.get("error")+ if error not in (None, "", False, [], {}):+ return True+ return any(+ _result_signals_failure(value[key])+ for key in (+ "content",+ "result",+ "structuredContent",+ "structured_content",+ "text",+ )+ if key in value+ )+ if isinstance(value, list):+ return any(_result_signals_failure(item) for item in value)+ if not isinstance(value, str):+ return False++ text = value.strip()+ if not text:+ return False+ if "<tool_use_error>" in text.lower():+ return True+ if text[0] in "[{":+ try:+ decoded = json.loads(text)+ except (json.JSONDecodeError, ValueError):+ pass+ else:+ return _result_signals_failure(decoded)+ return _RE_DENIED_RESULT.match(text) is not None+++def _json_stream_records(worker_output: str) -> tuple[dict[str, Any], ...]:+ """Best-effort JSON/NDJSON records without interpreting quoted prose."""+ stripped = worker_output.strip()+ if not stripped:+ return ()+ try:+ decoded = json.loads(stripped)+ except (json.JSONDecodeError, ValueError):+ decoded = None+ if isinstance(decoded, dict):+ return (decoded,)+ if isinstance(decoded, list):+ return tuple(item for item in decoded if isinstance(item, dict))++ records: list[dict[str, Any]] = []+ for raw in worker_output.splitlines():+ try:+ decoded = json.loads(raw.strip())+ except (json.JSONDecodeError, ValueError):+ continue+ if isinstance(decoded, dict):+ records.append(decoded)+ elif isinstance(decoded, list):+ records.extend(item for item in decoded if isinstance(item, dict))+ return tuple(records)+++def _message_blocks(record: dict[str, Any]) -> tuple[dict[str, Any], ...]:+ """Return tool blocks from canonical and flattened provider frames."""+ if record.get("type") in {"tool_use", "tool_result"}:+ return (record,)+ message = record.get("message")+ container = message if isinstance(message, dict) else record+ content = container.get("content")+ if isinstance(content, dict):+ return (content,)+ if isinstance(content, list):+ return tuple(item for item in content if isinstance(item, dict))+ return ()+def _extract_tool_call_evidence(worker_output: str) -> tuple[str, ...]:"""Parse tool-call evidence from worker output in a defensive, format-agnostic way.@@ -146,6 +276,12 @@ def _extract_tool_call_evidence(worker_output: str) -> tuple[str, ...]:mcp_tool_call / web_search) — the matched item type doubles as theevidence name.+ A correlated failure result removes its call from the evidence set. This+ prevents a denied, blocked, cancelled, or otherwise failed attempt from+ satisfying a side-effecting capability merely because ``tool_use`` was+ emitted first. Uncorrelated call frames retain their historical treatment+ for compatibility with streaming providers that do not persist results.+If the output format is unrecognised or the text is empty, returns anempty tuple — the caller (``enforce_capability_honesty``) treats this asconservative failure for ``requires_evidence=True`` capabilities.@@ -153,11 +289,75 @@ def _extract_tool_call_evidence(worker_output: str) -> tuple[str, ...]:if not worker_output:return ()- names: list[str] = []- names.extend(_RE_TOOL_USE_NAME.findall(worker_output))+ calls: list[tuple[str | None, str]] = []+ outcomes: dict[str, bool] = {}+ saw_structured_call = False++ for record in _json_stream_records(worker_output):+ record_type = str(record.get("type", "")).strip()+ if record_type in {"item.started", "item.completed"}:+ item = record.get("item")+ if not isinstance(item, dict):+ continue+ item_type = str(item.get("type", "")).strip()+ if item_type not in _ACTION_ITEM_TYPES:+ continue+ saw_structured_call = True+ item_id = str(item.get("id", "")).strip()+ key = f"codex:{item_id}" if item_id else f"codex-anonymous:{len(calls)}"+ calls.append((key, item_type))+ if record_type == "item.completed":+ outcomes[key] = outcomes.get(key, False) or _result_signals_failure(item)+ continue++ if record_type == "dispatch-result":+ name = str(record.get("tool", "")).strip()+ if name:+ saw_structured_call = True+ key = f"dispatch:{len(calls)}"+ calls.append((key, name))+ outcomes[key] = _result_signals_failure(record)+ continue++ for block in _message_blocks(record):+ block_type = str(block.get("type", "")).strip()+ if block_type == "tool_use":+ name = str(block.get("name", "")).strip()+ if not name:+ continue+ saw_structured_call = True+ tool_id = str(block.get("id", "")).strip()+ calls.append((f"tool:{tool_id}" if tool_id else None, name))+ elif block_type == "tool_result":+ tool_id = str(+ block.get("tool_use_id")+ or block.get("tool_call_id")+ or block.get("call_id")+ or block.get("toolUseId")+ or block.get("toolCallId")+ or block.get("callId")+ or ""+ ).strip()+ if tool_id:+ key = f"tool:{tool_id}"+ outcomes[key] = outcomes.get(key, False) or _result_signals_failure(+ block+ )++ names = [+ name+ for key, name in calls+ if key is None or outcomes.get(key) is not True+ ]++ # Preserve compatibility with old, non-JSON logs. Once structured calls+ # were parsed, their correlated outcomes are authoritative and a regex+ # fallback must not accidentally re-add a failed call.+ if not saw_structured_call:+ names.extend(_RE_TOOL_USE_NAME.findall(worker_output))+ names.extend(_RE_DISPATCH_RESULT.findall(worker_output))+ names.extend(_RE_CODEX_ACTION_ITEM.findall(worker_output))names.extend(_RE_TOOL_USE_MARKER.findall(worker_output))- names.extend(_RE_DISPATCH_RESULT.findall(worker_output))- names.extend(_RE_CODEX_ACTION_ITEM.findall(worker_output))# Deduplicate while preserving first-seen order.seen: set[str] = set()diff --git a/jarvis/missions/init.py b/jarvis/missions/init.pyindex c28501ad09..ff76c74494 100644--- a/jarvis/missions/init.py+++ b/jarvis/missions/init.py@@ -314,9 +314,49 @@ def _assemble_worker_capability_inventory(task_text: str) -> WorkerCapabilityInvreturn WorkerCapabilityInventory.build(mcp_servers=_assemble_worker_mcp_servers(task_text=task_text),app_commands=restricted_worker_app_commands(),+ native_tool_names=_connected_native_worker_tools(task_text),+ task_text=task_text,)+def _connected_native_worker_tools(task_text: str) -> tuple[str, ...]:+ """Connected, task-relevant native connector tools without credentials.++ Some Marketplace connectors (for example Gmail and Vercel) use a native+ supervisor tool instead of an MCP server. Include only catalog-declared+ tools whose credential is present and healthy, and only when the mission+ names or semantically matches that connector. Any store/catalog fault+ fails closed for that connector rather than granting a phantom tool.+ """+ try:+ from jarvis.marketplace.catalog_data import load_catalog+ from jarvis.marketplace.plugin_relevance import plugin_is_relevant+ from jarvis.marketplace.token_store import TokenStore++ store = TokenStore()+ selected: list[str] = []+ for plugin in load_catalog().plugins:+ native_name = str(plugin.native_tool or "").strip()+ if not native_name:+ continue+ try:+ tokens = store.load(plugin.id)+ except Exception: # noqa: BLE001 - one broken credential stays isolated+ logger.debug(+ "missions: connector credential unreadable for %s", plugin.id+ )+ continue+ if tokens is None or not tokens.access or tokens.needs_reauth:+ continue+ evidence = [{"name": native_name, "description": plugin.description}]+ if plugin_is_relevant(task_text, plugin.id, evidence):+ selected.append(native_name)+ return tuple(dict.fromkeys(selected))+ except Exception: # noqa: BLE001 - capability discovery must not block missions+ logger.debug("missions: native connector discovery failed", exc_info=True)+ return ()++def _select_subagent_worker_kind(sub_jarvis_provider: str | None, step_model: str) -> str:"""Pure routing decision for the Heavy-Task subagent worker.diff --git a/jarvis/missions/isolation/worktree.py b/jarvis/missions/isolation/worktree.pyindex ebb44950fb..88ea9eee3f 100644--- a/jarvis/missions/isolation/worktree.py+++ b/jarvis/missions/isolation/worktree.py@@ -6,7 +6,7 @@ race conditions in the user's working tree.Path layout (Research-Doc §E point 1):- <repo_parent>/sub-agents-outputs/+ <repo_parent>/jarvis-agent-outputs/<YYYYMMDDTHHMMSS>__<mission-slug>__<short-uuid>/tasks/<NN>__<task-slug>/@@ -31,9 +31,9 @@ import subprocessimport timeimport uuidfrom collections.abc import Callable+from pathlib import Pathfrom jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS-from pathlib import Pathlogger = logging.getLogger(__name__)@@ -85,7 +85,7 @@ def read_worktree_base_sha(workspace: Path) -> str | None:# ``Kontrollierer._archive_task_artifacts`` writes live in the SAME outputs# root but hold the user's deliverables (diff.patch + artifacts/files/) and are# never git worktrees — sweeping them by age silently wipes every completed-# sub-agent's output (live 2026-05-29: 0/77 mission dirs still had files after a+# Jarvis-Agent's output (live 2026-05-29: 0/77 mission dirs still had files after a# >6 h-old restart triggered the 6 h sweep). The 14-day retention of those# archive dirs is owned by ``cleanup.startup_sweep`` instead._RUN_DIR_RE = re.compile(r"^\d{8}T\d{6}__.+__[0-9a-f]{8}$")@@ -123,11 +123,23 @@ def _slugify(value: str) -> str:def resolve_outputs_root(repo_root: Path) -> Path:"""Return the mission outputs root directory.+ ``JARVIS_ISOLATION_ROOT`` is the explicit highest-priority override.+ ``JARVIS_DATA_DIR`` places outputs under the writable application data+ volume used by headless and non-root installs.+Prefers ``<repo_root>.parent/jarvis-agent-outputs/`` (post-rename, 2026-06-29).Falls back to ``<repo_root>.parent/sub-agents-outputs/`` when that old directoryexists AND the new one does NOT — this keeps existing missions readable withoutany migration step. Does NOT create the directory; callers are responsible."""+ explicit_root = os.environ.get("JARVIS_ISOLATION_ROOT", "").strip()+ if explicit_root:+ return Path(explicit_root).expanduser().resolve()++ data_root = os.environ.get("JARVIS_DATA_DIR", "").strip()+ if data_root:+ return Path(data_root).expanduser().resolve() / "jarvis-agent-outputs"+parent = repo_root.resolve().parentnew_dir = parent / "jarvis-agent-outputs"old_dir = parent / "sub-agents-outputs"@@ -153,8 +165,8 @@ class WorktreeManager:"""Inputs:repo_root: path to the main repo (the one that contains `.git`).- outputs_root: optional override for the `sub-agents-outputs/` root- directory. Default: `<repo_root>.parent/sub-agents-outputs`.+ outputs_root: optional override for the mission outputs root.+ Default: ``resolve_outputs_root(repo_root)``."""self._repo_root = repo_root.resolve()self._outputs_root = (@@ -210,7 +222,11 @@ class WorktreeManager:short_uuid = uuid.uuid4().hex[:8]run_dir_name = f"{ts}__{mission_part}__{short_uuid}"- task_dir_name = task_part if task_part.startswith(tuple("0123456789")) else f"01__{task_part}"+ task_dir_name = (+ task_part+ if task_part.startswith(tuple("0123456789"))+ else f"01__{task_part}"+ )workspace = (self._outputs_root / run_dir_name / "tasks" / task_dir_name / "workspace"@@ -218,7 +234,7 @@ class WorktreeManager:if len(str(workspace)) > _MAX_WORKTREE_PATH_LEN:raise ValueError(- f"Worktree-Pfad zu lang ({len(str(workspace))} > "+ f"Worktree path is too long ({len(str(workspace))} > "f"{_MAX_WORKTREE_PATH_LEN}): {workspace}")@@ -444,7 +460,7 @@ class WorktreeManager:# subprocess holds file handles open past parent process teardown.# BUG-LIVE-05's retry loop catches the 80 % case but force-quits,# process crashes, and parallel-session locks leave behind directories- # under sub-agents-outputs/. Audit-team-4 counted 60 such leaks on+ # under the mission outputs root. Audit-team-4 counted 60 such leaks on# disk. Sweep at bootstrap is the simplest defense: forget the missing# entries from git's internal state, then aggressively rmtree# anything older than `max_age_hours` that no live worktree claims.@@ -456,7 +472,7 @@ class WorktreeManager:Two-step safety:1. ``git worktree prune`` removes git's internal entry for anyworktree whose directory disappeared (e.g. user `rm -rf`d it).- 2. Scan ``sub-agents-outputs/`` for run-dirs older than+ 2. Scan the mission outputs root for run-dirs older than``max_age_hours``. If git still considers any path underthat run-dir an active worktree we leave it alone (Windowspermission errors from racing workers will be retried by@@ -529,7 +545,7 @@ class WorktreeManager:# Only sweep transient worktree RUN-dirs. A persistent# ``mission_<id>`` deliverable-archive dir (or any other# non-run-dir) must never be rmtree'd here — that is the bug that- # left every completed sub-agent's Outputs view empty (2026-05-29).+ # left every completed Jarvis-Agent's Outputs view empty (2026-05-29).if not _RUN_DIR_RE.match(child.name):continuetry:diff --git a/jarvis/missions/kontrollierer/orchestrator.py b/jarvis/missions/kontrollierer/orchestrator.pyindex 423e63253a..deb273e654 100644--- a/jarvis/missions/kontrollierer/orchestrator.py+++ b/jarvis/missions/kontrollierer/orchestrator.py@@ -34,8 +34,8 @@ from typing import Any, Awaitable, Callable, Final, Literalfrom ...core.process_utils import NO_WINDOW_CREATIONFLAGSfrom ..budget import BudgetExceeded, BudgetTracker-from ..critic.reflections import ReflectionMemoryfrom ..critic.escalation import FRONTIER_MODEL+from ..critic.reflections import ReflectionMemoryfrom ..critic.runner import MAX_CRITIC_LOOPS, CriticRunnerfrom ..critic.verdict import (CriticSchemaInvalid,@@ -58,8 +58,16 @@ from ..events import (now_ms,)from ..isolation.worktree import WorktreeManager, read_worktree_base_sha-from ..worker_runtime.workspace import materialize_worker_contractfrom ..manager import MissionManager+from ..safety import (+ extract_worker_authored_text,+ filter_diff_paths,+ has_high_severity,+)+from ..safety import (+ scan as injection_scan,+)+from ..state_machine import IllegalStateTransition, MissionStatefrom ..stream_evidence import (extract_verified_commands,extract_verified_desktop_actions,@@ -67,6 +75,9 @@ from ..stream_evidence import (readonly_answer,summarize_answers,)+from ..worker_runtime.workspace import materialize_worker_contract+from ..workers.base import WorkerProtocol+from .decomposer import MissionDecomposer, MissionPlan, Stepfrom .deliverable import (build_deliverable_summary,build_delivered_summary,@@ -74,15 +85,6 @@ from .deliverable import (materialize_answer_document,)from .deliverable_paths import find_generator_scripts, is_deliverable_path-from ..safety import (- extract_worker_authored_text,- filter_diff_paths,- has_high_severity,- scan as injection_scan,-)-from ..state_machine import IllegalStateTransition, MissionState-from ..workers.base import WorkerProtocol-from .decomposer import MissionDecomposer, MissionPlan, Stepfrom .worker_prompt import compose_worker_promptlogger = logging.getLogger(__name__)@@ -1375,6 +1377,35 @@ class Kontrollierer:# "budget", everything else → "user") and log the verbatim# message at ERROR level so it shows up in jarvis_desktop.log# immediately above the failure announcement.+ if spawn_result.supervisor_tool_failed:+ error_detail = (+ spawn_result.supervisor_tool_error+ or "Supervisor tool execution did not complete successfully."+ )[:300]+ self._mission_failure_context[mission_id] = {+ "error_class": "supervisor_tool_failed",+ "error_detail": error_detail,+ "failed_provider": (+ getattr(worker, "provider", None)+ or getattr(worker, "cli", None)+ ),+ }+ logger.error(+ "Task %s iter %d: refusing critic review after an unclean "+ "supervisor tool grant: %s",+ step.task_id,+ iteration,+ error_detail,+ )+ await self._publish_worker_killed(+ mission_id=mission_id,+ worker_id=spawn_result.worker_id,+ reason="worker_error",+ error_class="supervisor_tool_failed",+ error_detail=error_detail,+ )+ return TaskOutcome.ERROR+if spawn_result.worker_error:err_lower = spawn_result.worker_error.lower()# Structured flag first (robust), result-text "timeout" as a@@ -1707,6 +1738,8 @@ class Kontrollierer:session_id: str | None,worker_error: str | None = None,worker_timed_out: bool = False,+ supervisor_tool_failed: bool = False,+ supervisor_tool_error: str | None = None,) -> None:self.worker_id = worker_idself.cost_usd = cost_usd@@ -1725,6 +1758,8 @@ class Kontrollierer:# no credentials). Used by the calling loop to fail-fast# instead of grinding through MAX_CRITIC_LOOPS retries.self.worker_error = worker_error+ self.supervisor_tool_failed = supervisor_tool_failed+ self.supervisor_tool_error = supervisor_tool_errorasync def _spawn_worker_collect(self,@@ -1755,6 +1790,33 @@ class Kontrollierer:worker_error: str | None = Noneworker_timed_out = Falselast_progress_at: float | None = None+ worker_timeout_s = (+ _ITER0_WORKER_TIMEOUT_S+ if iteration == 0+ else _CORRECTION_WORKER_TIMEOUT_S+ )+ from jarvis.missions.workers.worker_tool_broker import (+ EmptyWorkerToolBrokerBinding,+ )++ broker_binding: Any = EmptyWorkerToolBrokerBinding()+ inventory = getattr(worker, "capability_inventory", None)+ bind_broker = getattr(inventory, "bind_broker", None)+ if callable(bind_broker):+ try:+ issued_binding = bind_broker(+ ttl_s=worker_timeout_s + 60.0,+ mission_id=mission_id,+ worker_id=worker_id,+ )+ if issued_binding is not None:+ broker_binding = issued_binding+ except Exception: # noqa: BLE001 - unavailable tools degrade honestly+ logger.exception(+ "Mission %s worker %s: supervisor tool grant unavailable",+ mission_id,+ worker_id,+ )async with job:hb_stop = asyncio.Event()@@ -1782,16 +1844,14 @@ class Kontrollierer:kwargs: dict[str, Any] = {"model": step.model,"allowed_tools": step.allowed_tools,+ "mission_id": mission_id,+ "_broker_binding": broker_binding,# Degressive per-iteration budget (2026-06-10 mandate):# the main build gets the large slice, corrections the# short one — they refine an existing workspace. Workers# preserve + grade partial work on timeout, so an overrun# costs the cap, never the deliverable.- "timeout_s": (- _ITER0_WORKER_TIMEOUT_S- if iteration == 0- else _CORRECTION_WORKER_TIMEOUT_S- ),+ "timeout_s": worker_timeout_s,}if resume_session_id:kwargs["resume_session_id"] = resume_session_id@@ -1896,6 +1956,9 @@ class Kontrollierer:finally:hb_stop.set()await hb_task+ await broker_binding.aclose()++ broker_summary = broker_binding.execution_summaryreturn Kontrollierer._SpawnResult(worker_id=worker_id,@@ -1904,6 +1967,8 @@ class Kontrollierer:session_id=session_id,worker_error=worker_error,worker_timed_out=worker_timed_out,+ supervisor_tool_failed=not broker_summary.clean,+ supervisor_tool_error=broker_summary.failure_summary,)# --- Phase-5 Safety -----------------------------------------------------@@ -2592,14 +2657,15 @@ class Kontrollierer:async def _safe_transition(self, mission_id: str, to_state: MissionState, reason: str- ) -> None:- """State-machine transition with lock + idempotency tolerance."""+ ) -> bool:+ """Transition under the mission lock and report whether it committed."""lock = self._state_locks.setdefault(mission_id, asyncio.Lock())async with lock:try:await self._manager.transition_state(mission_id, to_state, reason=reason, source_actor="kontrollierer")+ return Trueexcept IllegalStateTransition:# already at the target state or further — not a crashlogger.debug(@@ -2607,6 +2673,7 @@ class Kontrollierer:mission_id,to_state.value,)+ return Falseasync def _approve_mission(self, mission_id: str, plan: MissionPlan, *, prompt: str = ""@@ -2614,7 +2681,13 @@ class Kontrollierer:# Hygiene: a retried-then-approved mission must not leak a stale# worker-failure context into a later run (mirror of _fail_mission).self._mission_failure_context.pop(mission_id, None)- await self._safe_transition(mission_id, MissionState.APPROVED, "all_tasks_approved")+ transitioned = await self._safe_transition(+ mission_id,+ MissionState.APPROVED,+ "all_tasks_approved",+ )+ if not transitioned:+ return# Point `result_uri` at the real mission directory so the Outputs# view and any voice-readback consumer can resolve it to actual# files (diff.patch + untracked file copies persisted by@@ -2747,7 +2820,8 @@ class Kontrollierer:MissionState.TIMED_OUT,):return- await self._safe_transition(mission_id, MissionState.FAILED, reason)+ if not await self._safe_transition(mission_id, MissionState.FAILED, reason):+ returnenv = EventEnvelope(mission_id=mission_id,source_actor="kontrollierer",diff --git a/jarvis/missions/tool_approvals.py b/jarvis/missions/tool_approvals.pynew file mode 100644index 0000000000..2a79d7c5c1--- /dev/null+++ b/jarvis/missions/tool_approvals.py@@ -0,0 +1,177 @@+"""Mission-scoped view and decision bridge for paused supervisor tool calls."""++from __future__ import annotations++import asyncio+import time+from dataclasses import asdict, dataclass+from uuid import UUID++from jarvis.core.bus import EventBus+from jarvis.core.events import (+ ActionApprovalRequired,+ ActionApproved,+ ActionDenied,+ ActionExecuted,+)+++@dataclass(frozen=True, slots=True)+class PendingMissionToolApproval:+ """Secret-free data needed to render and decide one paused call."""++ trace_id: UUID+ mission_id: str+ worker_id: str | None+ tool_name: str+ risk_tier: str+ reason: str+ args_preview: str+ requested_at_ns: int+ expires_at_ns: int++ def to_dict(self) -> dict[str, str | int | None]:+ payload = asdict(self)+ payload["trace_id"] = str(self.trace_id)+ return payload+++class MissionToolApprovalCoordinator:+ """Tracks mission approvals while ``ApprovalWorkflow`` owns the waiter.++ The coordinator never holds tool objects, arguments, or credentials. It is+ an in-memory projection of bus events and publishes the normal+ ``ActionApproved``/``ActionDenied`` decisions, preserving the single safety+ path through ``ToolExecutor``.+ """++ def __init__(self, bus: EventBus) -> None:+ self._bus = bus+ self._pending: dict[UUID, PendingMissionToolApproval] = {}+ self._lock = asyncio.Lock()+ bus.subscribe(ActionApprovalRequired, self._on_required)+ bus.subscribe(ActionApproved, self._on_resolved)+ bus.subscribe(ActionDenied, self._on_resolved)+ bus.subscribe(ActionExecuted, self._on_resolved)++ async def _on_required(self, event: ActionApprovalRequired) -> None:+ mission_id = str(event.mission_id or "").strip()+ if not mission_id or event.expires_at_ns <= time.time_ns():+ return+ pending = PendingMissionToolApproval(+ trace_id=event.trace_id,+ mission_id=mission_id,+ worker_id=event.worker_id,+ tool_name=event.tool_name,+ risk_tier=event.risk_tier,+ reason=event.reason,+ args_preview=event.args_preview,+ requested_at_ns=event.timestamp_ns,+ expires_at_ns=event.expires_at_ns,+ )+ async with self._lock:+ self._pending[event.trace_id] = pending++ async def _on_resolved(+ self,+ event: ActionApproved | ActionDenied | ActionExecuted,+ ) -> None:+ async with self._lock:+ self._pending.pop(event.trace_id, None)++ async def list_pending(+ self,+ mission_id: str,+ ) -> tuple[PendingMissionToolApproval, ...]:+ now_ns = time.time_ns()+ async with self._lock:+ expired = [+ trace_id+ for trace_id, item in self._pending.items()+ if item.expires_at_ns <= now_ns+ ]+ for trace_id in expired:+ self._pending.pop(trace_id, None)+ return tuple(+ sorted(+ (+ item+ for item in self._pending.values()+ if item.mission_id == mission_id+ ),+ key=lambda item: item.requested_at_ns,+ )+ )++ async def approve(+ self,+ mission_id: str,+ trace_id: UUID,+ *,+ approved_by: str,+ ) -> PendingMissionToolApproval | None:+ pending = await self._take_live(mission_id, trace_id)+ if pending is None:+ return None+ await self._bus.publish(+ ActionApproved(+ trace_id=trace_id,+ tool_name=pending.tool_name,+ approved_by=approved_by,+ )+ )+ return pending++ async def deny(+ self,+ mission_id: str,+ trace_id: UUID,+ *,+ reason: str,+ ) -> PendingMissionToolApproval | None:+ pending = await self._take_live(mission_id, trace_id)+ if pending is None:+ return None+ await self._bus.publish(+ ActionDenied(+ trace_id=trace_id,+ tool_name=pending.tool_name,+ reason=reason,+ )+ )+ return pending++ async def _take_live(+ self,+ mission_id: str,+ trace_id: UUID,+ ) -> PendingMissionToolApproval | None:+ async with self._lock:+ pending = self._pending.get(trace_id)+ if (+ pending is None+ or pending.mission_id != mission_id+ or pending.expires_at_ns <= time.time_ns()+ ):+ if pending is not None and pending.expires_at_ns <= time.time_ns():+ self._pending.pop(trace_id, None)+ return None+ self._pending.pop(trace_id, None)+ return pending++ async def deny_all(self, *, reason: str) -> None:+ """Release every waiter during orderly application shutdown."""+ async with self._lock:+ pending = tuple(self._pending.values())+ self._pending.clear()+ for item in pending:+ await self._bus.publish(+ ActionDenied(+ trace_id=item.trace_id,+ tool_name=item.tool_name,+ reason=reason,+ )+ )+++__all__ = ["MissionToolApprovalCoordinator", "PendingMissionToolApproval"]diff --git a/jarvis/missions/workers/api_agent_worker.py b/jarvis/missions/workers/api_agent_worker.pyindex 209200d938..bd627d272a 100644--- a/jarvis/missions/workers/api_agent_worker.py+++ b/jarvis/missions/workers/api_agent_worker.py@@ -159,7 +159,9 @@ _MAX_TOKENS: int = 8192_SYSTEM_PROMPT = ("You are an autonomous software worker running inside an isolated git ""workspace. Your ONLY way to deliver work is to call the provided tools — "- "Write, Edit, Read, Bash, Ls — with paths relative to the workspace root. "+ "Write, Edit, Read, Bash, Ls, plus any mission-scoped connected tools — "+ "with file paths relative to the workspace root. Connected tools are "+ "executed by the supervisor and may honestly require human approval. ""Actually CREATE and EDIT the files the task needs; never just describe what ""you would do (a text description is not a deliverable and will be rejected). ""Work autonomously without asking questions: if a detail is unspecified, pick "@@ -230,6 +232,50 @@ class ApiAgentWorker:log_dir: Path,model: str = "",max_turns: int = _MAX_TURNS,+ _broker_binding: Any | None = None,+ **_unused: Any,+ ) -> AsyncIterator[Any]:+ broker_binding = _broker_binding+ issued_here = broker_binding is None+ if issued_here:+ broker_binding = self.capability_inventory.bind_broker(+ ttl_s=_WORKER_TIMEOUT_S + 60.0,+ mission_id=_unused.get("mission_id"),+ worker_id=worker_id,+ )+ try:+ async for event in self._spawn_bound(+ prompt,+ worktree=worktree,+ env=env,+ job=job,+ worker_id=worker_id,+ log_dir=log_dir,+ model=model,+ max_turns=max_turns,+ broker_binding=broker_binding,+ **_unused,+ ):+ yield event+ finally:+ if issued_here and broker_binding is not None:+ try:+ broker_binding.close()+ except Exception: # noqa: BLE001 - cleanup must not mask cancellation+ logger.exception("ApiAgentWorker: broker binding cleanup failed")++ async def _spawn_bound(+ self,+ prompt: str,+ *,+ worktree: Path,+ env: dict[str, str], # noqa: ARG002 - in-process brain reads credentials via config+ job: Any, # noqa: ARG002 - no child PID to assign (in-process)+ worker_id: str,+ log_dir: Path,+ model: str = "",+ max_turns: int = _MAX_TURNS,+ broker_binding: Any | None,**_unused: Any,) -> AsyncIterator[Any]:session_id = str(uuid.uuid4())@@ -238,6 +284,11 @@ class ApiAgentWorker:log_dir.mkdir(parents=True, exist_ok=True) # noqa: ASYNC240 — trivial sync mkdir (mirrors sibling workers)stream_path = log_dir / "stream.jsonl"written: list[str] = []+ broker_specs = broker_binding.tool_specs if broker_binding is not None else ()+ local_names = {str(spec["name"]) for spec in WORKER_TOOL_SPECS}+ all_tool_specs = WORKER_TOOL_SPECS + tuple(+ spec for spec in broker_specs if str(spec.get("name") or "") not in local_names+ )def _emit_line(event: Any) -> None:with suppress(OSError):@@ -247,9 +298,11 @@ class ApiAgentWorker:init = ClaudeSystemInit(session_id=session_id,model=f"{self.provider}/{resolved_model}",- tools=[t["name"] for t in WORKER_TOOL_SPECS],+ tools=[t["name"] for t in all_tool_specs],cwd=str(worktree),- external_capabilities=self.capability_inventory.report_for(f"api:{self.provider}"),+ external_capabilities=self.capability_inventory.report_for(+ f"api:{self.provider}", binding=broker_binding+ ),)_emit_line(init)yield init@@ -325,7 +378,7 @@ class ApiAgentWorker:turns = turn + 1req = BrainRequest(messages=tuple(messages),- tools=WORKER_TOOL_SPECS,+ tools=all_tool_specs,system=_SYSTEM_PROMPT,max_tokens=_MAX_TOKENS,stream=True,@@ -406,10 +459,22 @@ class ApiAgentWorker:continuename = block["name"]tool_input = block["input"] if isinstance(block["input"], dict) else {}- result_text, is_error = await loop.run_in_executor(- None,- lambda n=name, i=tool_input: execute_worker_tool(n, i, worktree=worktree),- )+ if name in local_names:+ result_text, is_error = await loop.run_in_executor(+ None,+ lambda n=name, i=tool_input: execute_worker_tool(+ n, i, worktree=worktree+ ),+ )+ elif broker_binding is not None:+ broker_result = await broker_binding.execute(name, tool_input)+ result_text = json.dumps(+ broker_result, ensure_ascii=False, default=str+ )+ is_error = not bool(broker_result.get("success"))+ else:+ result_text = "Tool is not granted to this mission."+ is_error = Trueif name in ("Write", "Edit") and not is_error:fp = str(tool_input.get("file_path", ""))if fp:diff --git a/jarvis/missions/workers/broker_stdio.py b/jarvis/missions/workers/broker_stdio.pynew file mode 100644index 0000000000..320deb7cea--- /dev/null+++ b/jarvis/missions/workers/broker_stdio.py@@ -0,0 +1,135 @@+"""Stdio MCP adapter for a mission-scoped supervisor tool grant."""++from __future__ import annotations++import asyncio+import http.client+import io+import json+import os+import sys+from typing import Any+from urllib.parse import urlsplit++import anyio+from mcp import types+from mcp.server import Server+from mcp.server.stdio import stdio_server++from .worker_tool_broker import BROKER_TOKEN_ENV, BROKER_URL_ENV++_HTTP_TIMEOUT_S = 65.0+++def _endpoint() -> tuple[str, int]:+ parsed = urlsplit(os.environ.get(BROKER_URL_ENV, ""))+ if (+ parsed.scheme != "http"+ or parsed.hostname not in {"127.0.0.1", "::1", "localhost"}+ or parsed.username is not None+ or parsed.password is not None+ or parsed.port is None+ ):+ raise RuntimeError("Worker tool broker URL must be an authenticated loopback endpoint.")+ return parsed.hostname, parsed.port+++def _request(method: str, path: str, payload: dict[str, Any] | None = None) -> dict[str, Any]:+ host, port = _endpoint()+ token = os.environ.get(BROKER_TOKEN_ENV, "")+ if not token:+ raise RuntimeError("Worker tool broker grant is missing or expired.")+ body = None if payload is None else json.dumps(payload).encode("utf-8")+ headers = {"Authorization": f"Bearer {token}"}+ if body is not None:+ headers["Content-Type"] = "application/json"+ conn = http.client.HTTPConnection(host, port, timeout=_HTTP_TIMEOUT_S)+ try:+ conn.request(method, path, body=body, headers=headers)+ response = conn.getresponse()+ raw = response.read()+ finally:+ conn.close()+ data = json.loads(raw or b"{}")+ if response.status >= 400:+ raise RuntimeError(str(data.get("error") or f"broker HTTP {response.status}"))+ return data+++server = Server("jarvis-worker-tools")++[email protected]_tools()+async def list_tools() -> list[types.Tool]:+ payload = await asyncio.to_thread(_request, "GET", "/v1/tools")+ tools: list[types.Tool] = []+ for item in payload.get("tools") or []:+ if not isinstance(item, dict) or not item.get("name"):+ continue+ schema = item.get("input_schema")+ if not isinstance(schema, dict):+ schema = {"type": "object", "properties": {}}+ tools.append(+ types.Tool(+ name=str(item["name"]),+ description=str(item.get("description") or ""),+ inputSchema=schema,+ )+ )+ return tools++[email protected]_tool()+async def call_tool(name: str, arguments: dict[str, Any]) -> types.CallToolResult:+ try:+ payload = await asyncio.to_thread(+ _request,+ "POST",+ "/v1/execute",+ {"name": name, "arguments": arguments},+ )+ except Exception as exc: # noqa: BLE001 - MCP error response, never a crash+ return types.CallToolResult(+ content=[types.TextContent(type="text", text=str(exc))],+ isError=True,+ )+ text = json.dumps(payload, ensure_ascii=False, default=str)+ return types.CallToolResult(+ content=[types.TextContent(type="text", text=text)],+ structuredContent=payload,+ isError=not bool(payload.get("success")),+ )+++async def _main() -> None:+ stdin = None+ stdout = None+ # PyInstaller's windowed bootloader sets Python's standard streams to None.+ # A worker CLI still launches this internal mode with inherited pipe handles,+ # so re-wrap file descriptors 0/1 instead of requiring a separate Python+ # installation beside the desktop bundle.+ if sys.stdin is None:+ raw_stdin = os.fdopen(0, "rb", closefd=False)+ stdin = anyio.wrap_file(+ io.TextIOWrapper(raw_stdin, encoding="utf-8", errors="replace")+ )+ if sys.stdout is None:+ raw_stdout = os.fdopen(1, "wb", closefd=False)+ stdout = anyio.wrap_file(io.TextIOWrapper(raw_stdout, encoding="utf-8"))++ async with stdio_server(stdin=stdin, stdout=stdout) as (read_stream, write_stream):+ await server.run(+ read_stream,+ write_stream,+ server.create_initialization_options(),+ )+++def main() -> int:+ """Run the private stdio adapter from Python or the frozen Jarvis binary."""+ asyncio.run(_main())+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/jarvis/missions/workers/capabilities.py b/jarvis/missions/workers/capabilities.pyindex 7819401a18..08583fd3be 100644--- a/jarvis/missions/workers/capabilities.py+++ b/jarvis/missions/workers/capabilities.py@@ -1,17 +1,16 @@"""Explicit external-capability contract shared by every mission worker.-Mission workers all receive the same restricted inventory. A backend either-consumes that inventory explicitly or reports ``unsupported``; no backend may-silently discover extra app or MCP tools from a machine-global CLI config.+Mission workers all receive the same restricted inventory and consume it+through a mission-scoped supervisor broker. No backend may silently discover+extra app or MCP tools from a machine-global CLI config.Only the two app commands needed for the durable knowledge workflow are in the-initial allowlist. Spawn, review, and skill-execution commands are deliberately+initial allowlist. Spawn, review, and skill-execution commands are deliberatelyabsent (AP-5/AP-14)."""from __future__ import annotations-import jsonfrom dataclasses import dataclass, fieldfrom typing import Any@@ -38,19 +37,24 @@ _FORBIDDEN_RECURSIVE_NAMES = frozenset(class WorkerCapabilityInventory:"""Immutable, secret-safe-to-report inventory for one mission step.- The serialized MCP config is excluded from ``repr`` because it can contain- resolved OAuth tokens. Public reports expose server ids only.+ Only MCP source identifiers are retained. Resolved commands, headers, env,+ OAuth tokens, and API keys never enter the inventory."""- _mcp_json: str = field(default="{}", repr=False)+ _mcp_server_ids: tuple[str, ...] = ()app_commands: tuple[str, ...] = ()+ native_tool_names: tuple[str, ...] = ()+ task_text: str = field(default="", repr=False)@classmethoddef build(cls,*,mcp_servers: dict[str, Any] | None = None,+ mcp_server_ids: tuple[str, ...] = (),app_commands: tuple[str, ...] = (),+ native_tool_names: tuple[str, ...] = (),+ task_text: str = "",) -> WorkerCapabilityInventory:commands = tuple(dict.fromkeys(str(name) for name in app_commands if name))forbidden = _FORBIDDEN_RECURSIVE_NAMES.intersection(commands)@@ -59,46 +63,112 @@ class WorkerCapabilityInventory:"recursive tools are forbidden in worker capability inventories: "+ ", ".join(sorted(forbidden)))- payload = json.dumps(mcp_servers or {}, ensure_ascii=False, sort_keys=True)- return cls(_mcp_json=payload, app_commands=commands)+ server_ids = tuple(+ dict.fromkeys(+ str(name)+ for name in (*tuple((mcp_servers or {}).keys()), *mcp_server_ids)+ if name+ )+ )+ native = tuple(dict.fromkeys(str(name) for name in native_tool_names if name))+ forbidden_native = tuple(name for name in native if name in _FORBIDDEN_RECURSIVE_NAMES)+ if forbidden_native:+ raise ValueError(+ "recursive tools are forbidden in worker capability inventories: "+ + ", ".join(sorted(forbidden_native))+ )+ return cls(+ _mcp_server_ids=server_ids,+ app_commands=commands,+ native_tool_names=native,+ task_text=str(task_text or ""),+ )@propertydef mcp_servers(self) -> dict[str, Any]:- """Return a fresh config copy so one backend cannot mutate another's."""- value = json.loads(self._mcp_json)- return value if isinstance(value, dict) else {}+ """Compatibility view containing identifiers only, never configuration."""+ return {server_id: {} for server_id in self._mcp_server_ids}@propertydef mcp_server_ids(self) -> tuple[str, ...]:- return tuple(sorted(self.mcp_servers))+ return tuple(sorted(self._mcp_server_ids))- def report_for(self, backend: str) -> dict[str, Any]:+ def bind_broker(+ self,+ *,+ ttl_s: float = 25 * 60.0,+ mission_id: str | None = None,+ worker_id: str | None = None,+ ): # noqa: ANN201+ """Create the short-lived live grant for this mission, if reachable."""+ from .worker_tool_broker import issue_worker_tool_binding++ return issue_worker_tool_binding(+ task_text=self.task_text,+ mcp_server_ids=self.mcp_server_ids,+ app_commands=self.app_commands,+ native_tool_names=self.native_tool_names,+ ttl_s=ttl_s,+ mission_id=mission_id,+ worker_id=worker_id,+ )++ def report_for(self, backend: str, *, binding: Any | None = None) -> dict[str, Any]:"""Public capability report for a concrete worker backend.- Claude CLI is currently the only backend that can consume the assembled- Claude-format MCP config without putting resolved secrets on argv.- App-command execution is intentionally unsupported until the worker- broker can route it through ToolExecutor and the REST validation chain.+ Every supported backend consumes the same broker grant. Source MCP+ configurations are discovery-only; reports never expose their env or+ resolved credentials."""mcp_requested = bool(self.mcp_server_ids)app_requested = bool(self.app_commands)- mcp_supported = backend == "claude-cli"+ available = bool(binding is not None and binding.available)+ tool_names = list(binding.tool_names) if available else []+ mcp_available = available and any(+ name.startswith(f"{server_id}/")+ for name in tool_names+ for server_id in self.mcp_server_ids+ )+ app_available = available and any(name in self.app_commands for name in tool_names)+ native_available = available and any(+ name in self.native_tool_names for name in tool_names+ )return {"backend": backend,+ "broker": {+ "status": "available" if available else "unavailable",+ "tools": tool_names,+ },"mcp": {"status": ("available"- if mcp_requested and mcp_supported- else "unsupported"+ if mcp_requested and mcp_available+ else "unavailable"if mcp_requestedelse "not_requested"),"servers": list(self.mcp_server_ids),},"app_commands": {- "status": "unsupported" if app_requested else "not_requested",+ "status": (+ "available"+ if app_requested and app_available+ else "unavailable"+ if app_requested+ else "not_requested"+ ),"commands": list(self.app_commands),},+ "native_tools": {+ "status": (+ "available"+ if self.native_tool_names and native_available+ else "unavailable"+ if self.native_tool_names+ else "not_requested"+ ),+ "tools": list(self.native_tool_names),+ },}diff --git a/jarvis/missions/workers/claude_direct_worker.py b/jarvis/missions/workers/claude_direct_worker.pyindex e78e036577..8dd1efdb58 100644--- a/jarvis/missions/workers/claude_direct_worker.py+++ b/jarvis/missions/workers/claude_direct_worker.py@@ -298,7 +298,6 @@ class ClaudeDirectWorker:self.capability_inventory = capability_inventory or WorkerCapabilityInventory.build(mcp_servers=mcp_servers)- self._mcp_servers = self.capability_inventory.mcp_serversasync def spawn(self,@@ -320,6 +319,69 @@ class ClaudeDirectWorker:mission_id: str = "",allow_backend_fallback: bool = True,force_default_model: bool = False,+ _broker_binding: Any | None = None,+ **_unused: Any,+ ) -> AsyncIterator[Any]:+ """Run one Claude worker lifecycle under one mission-scoped grant."""+ broker_binding = _broker_binding+ issued_here = broker_binding is None+ if issued_here:+ broker_binding = self.capability_inventory.bind_broker(+ ttl_s=timeout_s + _HARDCAP_GRACE_S + 60.0,+ mission_id=mission_id or None,+ worker_id=worker_id,+ )+ try:+ async for event in self._spawn_bound(+ prompt,+ worktree=worktree,+ env=env,+ job=job,+ worker_id=worker_id,+ log_dir=log_dir,+ model=model,+ allowed_tools=allowed_tools,+ permission_mode=permission_mode,+ max_turns=max_turns,+ resume_session_id=resume_session_id,+ extra_args=extra_args,+ timeout_s=timeout_s,+ first_output_timeout_s=first_output_timeout_s,+ mission_id=mission_id,+ allow_backend_fallback=allow_backend_fallback,+ force_default_model=force_default_model,+ broker_binding=broker_binding,+ **_unused,+ ):+ yield event+ finally:+ if issued_here and broker_binding is not None:+ try:+ broker_binding.close()+ except Exception: # noqa: BLE001 - cleanup must not mask cancellation+ logger.exception("ClaudeDirectWorker: broker binding cleanup failed")++ async def _spawn_bound(+ self,+ prompt: str,+ *,+ worktree: Path,+ env: dict[str, str],+ job: Any,+ worker_id: str,+ log_dir: Path,+ model: str = "",+ allowed_tools: str = "",+ permission_mode: str = "bypassPermissions",+ max_turns: int = 20,+ resume_session_id: str | None = None,+ extra_args: tuple[str, ...] = (),+ timeout_s: float = _DEFAULT_TIMEOUT_S,+ first_output_timeout_s: float = _DEFAULT_FIRST_OUTPUT_TIMEOUT_S,+ mission_id: str = "",+ allow_backend_fallback: bool = True,+ force_default_model: bool = False,+ broker_binding: Any | None,**_unused: Any,) -> AsyncIterator[Any]:"""Spawn ``claude --print --output-format=stream-json`` with the prompt on stdin.@@ -372,6 +434,9 @@ class ClaudeDirectWorker:session_id = resume_session_id or str(uuid.uuid4())self.last_session_id = session_id+ broker_servers = (+ broker_binding.mcp_server_config() if broker_binding is not None else {}+ )# 2. Build the claude argv. ``force_default_model`` omits ``--model``# entirely so the CLI picks its own accessible default — the recovery@@ -394,10 +459,9 @@ class ClaudeDirectWorker:cmd.extend(["--model", claude_model])if allowed_tools:cmd.extend(["--allowedTools", allowed_tools])- # Connected marketplace plugins / mcp.json -> claude-cli MCP config so- # the delegated worker can actually call the plugins (AD-OE4). Written to- # log_dir (NOT the worktree) so the resolved token never lands in the diff.- cmd.extend(_build_mcp_config_args(log_dir, self._mcp_servers))+ # The CLI sees only the local broker adapter. Connector credentials stay+ # in the supervisor and never enter this config or the worker worktree.+ cmd.extend(_build_mcp_config_args(log_dir, broker_servers))cmd.extend(extra_args)yield ClaudeSystemInit(@@ -405,7 +469,9 @@ class ClaudeDirectWorker:model=f"claude-cli/{claude_model}",tools=[],cwd=str(worktree),- external_capabilities=self.capability_inventory.report_for("claude-cli"),+ external_capabilities=self.capability_inventory.report_for(+ "claude-cli", binding=broker_binding+ ),)logger.info(@@ -424,7 +490,11 @@ class ClaudeDirectWorker:proc = await create_worker_subprocess(cmd,cwd=str(worktree),- env=env,+ env=(+ broker_binding.apply_environment(env)+ if broker_binding is not None+ else env+ ),stdin=asyncio.subprocess.PIPE,stdout=asyncio.subprocess.PIPE,stderr=asyncio.subprocess.PIPE,@@ -725,6 +795,7 @@ class ClaudeDirectWorker:mission_id=mission_id,allow_backend_fallback=allow_backend_fallback,force_default_model=True,+ _broker_binding=broker_binding,):yield evreturn@@ -797,6 +868,7 @@ class ClaudeDirectWorker:timeout_s=timeout_s,mission_id=mission_id,allow_backend_fallback=False,+ _broker_binding=broker_binding,):yield evreturn@@ -866,6 +938,7 @@ class ClaudeDirectWorker:timeout_s=timeout_s,mission_id=mission_id,allow_backend_fallback=False,+ _broker_binding=broker_binding,):yield evreturndiff --git a/jarvis/missions/workers/codex_direct_worker.py b/jarvis/missions/workers/codex_direct_worker.pyindex 076c423316..b11e6183aa 100644--- a/jarvis/missions/workers/codex_direct_worker.py+++ b/jarvis/missions/workers/codex_direct_worker.py@@ -37,6 +37,7 @@ from __future__ import annotationsimport asyncioimport jsonimport logging+import osimport shutilimport timeimport uuid@@ -90,6 +91,22 @@ _HARDCAP_GRACE_S: float = 30.0# which a CLI override wins over config.toml._MISSION_REASONING_EFFORT: str = "medium"+# ``--ignore-user-config`` is required so a mission cannot inherit arbitrary+# user MCP servers or plugins, but it also removes the native Windows sandbox+# selection. Codex then starts in a partial state where shell reads work while+# the file-change tool reports the workspace as read-only. The unelevated+# implementation is available without administrator-approved setup and still+# confines shell writes to the worktree through Windows ACLs.+_WINDOWS_SANDBOX_MODE: str = "unelevated"+_WINDOWS_WRITE_GUIDANCE: str = (+ "Native Windows execution note: if the patch or file-change tool reports "+ "that the workspace is read-only, use a PowerShell shell command to write "+ "inside the current working directory instead. Write text as UTF-8 without "+ "a byte-order mark; Windows PowerShell's Set-Content can add one, so prefer "+ "System.IO.File.WriteAllText with System.Text.UTF8Encoding(false). Never "+ "write outside the current worktree."+)+def _resolve_codex_binary() -> str | None:"""Return the on-PATH ``codex`` binary, considering Windows extensions.@@ -117,8 +134,8 @@ def _resolve_codex_argv_prefix() -> list[str]:When jarvis is launched with a degraded PATH that lacks the Node.js dir(live forensic 2026-06-20: jarvis started by the hermes-agent runtime),cmd.exe dies with ``'node' is not recognized`` and exits 1 in ~25 ms —- BEFORE codex starts — so every mission fails ``task_error`` ("Der Worker ist # i18n-allow (quotes the real DE voice-readback phrase)- abgebrochen."). # i18n-allow (quotes the real DE voice-readback phrase)+ BEFORE codex starts — so every mission fails ``task_error``+ ("Der Worker ist abgebrochen."). # i18n-allow: actual DE voice readbackInvoking the JS entrypoint with an ABSOLUTE ``node`` pathbypasses the .CMD shim, the cmd.exe layer, and the inherited-PATHdependency entirely. Mirrors ``gemini_worker._resolve_gemini_argv_prefix``@@ -225,6 +242,8 @@ def _build_codex_direct_cmd(sandbox: str = "workspace-write",approval_policy: str = "never",extra_args: tuple[str, ...] = (),+ mcp_servers: dict[str, Any] | None = None,+ windows_sandbox: str | None = None,) -> list[str]:"""Compose the codex argv. Prompt arrives on stdin, not here.@@ -282,13 +301,57 @@ def _build_codex_direct_cmd("multi_agent_v2","--add-dir",str(worktree),+ "--cd",+ str(worktree),]+ if windows_sandbox:+ cmd.extend(["-c", f"windows.sandbox={json.dumps(windows_sandbox)}"])if model:cmd.extend(["--model", model])+ for server_id, server in sorted((mcp_servers or {}).items()):+ # Server ids are generated by Jarvis and contain only identifier-safe+ # characters. Values are TOML literals passed as separate argv entries;+ # the mission token is inherited via env and never appears here.+ command = str(server.get("command") or "")+ args = [str(value) for value in (server.get("args") or [])]+ if not command:+ continue+ cmd.extend(+ [+ "-c",+ f"mcp_servers.{server_id}.command={json.dumps(command)}",+ "-c",+ f"mcp_servers.{server_id}.args={json.dumps(args)}",+ ]+ )cmd.extend(extra_args)return cmd+def _prepare_codex_prompt(+ prompt: str,+ *,+ native_windows: bool | None = None,+) -> str:+ """Add the bounded Windows write recovery instruction when applicable."""+ on_windows = os.name == "nt" if native_windows is None else native_windows+ if not on_windows:+ return prompt+ return f"{_WINDOWS_WRITE_GUIDANCE}\n\n{prompt}"+++def _codex_sandbox_write_rejected(stderr_text: str) -> bool:+ """Return whether Codex reported a rejected workspace write."""+ low = stderr_text.lower()+ return any(+ marker in low+ for marker in (+ "patch rejected: writing is blocked by read-only sandbox",+ "failed to write file",+ )+ )++# Markers in a codex ``turn.failed`` / ``error`` event that mean the ChatGPT# OAuth session is dead and cannot be refreshed — the user must re-run# ``codex login``. ``codex status`` still reports connected=True (it only checks@@ -420,6 +483,67 @@ class CodexDirectWorker:first_output_timeout_s: float = _DEFAULT_FIRST_OUTPUT_TIMEOUT_S,mission_id: str = "",allow_backend_fallback: bool = True,+ _broker_binding: Any | None = None,+ **_unused: Any,+ ) -> AsyncIterator[Any]:+ """Run one Codex worker lifecycle under one mission-scoped grant."""+ broker_binding = _broker_binding+ issued_here = broker_binding is None+ if issued_here:+ broker_binding = self.capability_inventory.bind_broker(+ ttl_s=timeout_s + _HARDCAP_GRACE_S + 60.0,+ mission_id=mission_id or None,+ worker_id=worker_id,+ )+ try:+ async for event in self._spawn_bound(+ prompt,+ worktree=worktree,+ env=env,+ job=job,+ worker_id=worker_id,+ log_dir=log_dir,+ model=model,+ allowed_tools=allowed_tools,+ permission_mode=permission_mode,+ max_turns=max_turns,+ resume_session_id=resume_session_id,+ extra_args=extra_args,+ timeout_s=timeout_s,+ first_output_timeout_s=first_output_timeout_s,+ mission_id=mission_id,+ allow_backend_fallback=allow_backend_fallback,+ broker_binding=broker_binding,+ **_unused,+ ):+ yield event+ finally:+ if issued_here and broker_binding is not None:+ try:+ broker_binding.close()+ except Exception: # noqa: BLE001 - cleanup must not mask cancellation+ logger.exception("CodexDirectWorker: broker binding cleanup failed")++ async def _spawn_bound(+ self,+ prompt: str,+ *,+ worktree: Path,+ env: dict[str, str],+ job: Any,+ worker_id: str,+ log_dir: Path,+ model: str = "",+ allowed_tools: str = "", # unused -- codex has its own toolset+ permission_mode: str = "", # unused+ max_turns: int = 20, # unused -- codex turn cap is internal+ resume_session_id: str | None = None,+ extra_args: tuple[str, ...] = (),+ timeout_s: float = _DEFAULT_TIMEOUT_S,+ first_output_timeout_s: float = _DEFAULT_FIRST_OUTPUT_TIMEOUT_S,+ mission_id: str = "",+ allow_backend_fallback: bool = True,+ broker_binding: Any | None,**_unused: Any,) -> AsyncIterator[Any]:"""Spawn ``codex exec --json`` with the prompt on stdin.@@ -428,12 +552,16 @@ class CodexDirectWorker:fires upstream with a session-id), then forwards translatedcodex events, ending with a synthetic ``ClaudeResult``."""- log_dir.mkdir(parents=True, exist_ok=True)+ # This single setup mkdir happens before subprocess streaming starts.+ log_dir.mkdir(parents=True, exist_ok=True) # noqa: ASYNC240stdout_log = log_dir / "stream.jsonl"stderr_log = log_dir / "stderr.log"session_id = resume_session_id or str(uuid.uuid4())self.last_session_id = session_id+ broker_servers = (+ broker_binding.mcp_server_config() if broker_binding is not None else {}+ )# Normalize Anthropic-flavoured aliases ("sonnet", "claude-...",# ...) to empty so codex uses its ChatGPT-subscription default.@@ -444,6 +572,8 @@ class CodexDirectWorker:worktree=worktree,model=effective_model,extra_args=extra_args,+ mcp_servers=broker_servers,+ windows_sandbox=_WINDOWS_SANDBOX_MODE if os.name == "nt" else None,)# Honor both auth models (see _build_codex_env). CODEX_HOME is always@@ -451,13 +581,17 @@ class CodexDirectWorker:# is dropped only when a ChatGPT (OAuth) login exists, so the free# subscription wins; an API-key-only setup keeps the key (API mode).env_for_codex = _build_codex_env(env, oauth_available=_codex_oauth_available())+ if broker_binding is not None:+ env_for_codex = broker_binding.apply_environment(env_for_codex)yield ClaudeSystemInit(session_id=session_id,model=f"codex-cli/{model or 'default'}",tools=[],cwd=str(worktree),- external_capabilities=self.capability_inventory.report_for("codex-cli"),+ external_capabilities=self.capability_inventory.report_for(+ "codex-cli", binding=broker_binding+ ),)logger.info(@@ -506,7 +640,7 @@ class CodexDirectWorker:# Write the prompt to stdin then close to signal EOF.try:assert proc.stdin is not None # noqa: S101 -- PIPE always present- proc.stdin.write(prompt.encode("utf-8"))+ proc.stdin.write(_prepare_codex_prompt(prompt).encode("utf-8"))await proc.stdin.drain()proc.stdin.close()except (BrokenPipeError, ConnectionResetError) as exc:@@ -642,6 +776,13 @@ class CodexDirectWorker:)continueif item_type in ("file_change", "command_execution"):+ status = str(item.get("status") or "").lower()+ exit_code = item.get("exit_code")+ tool_succeeded = status != "failed" and (+ item_type != "command_execution" or exit_code in (None, 0)+ )+ if not tool_succeeded:+ continueany_tool_use = True# Synthesize a tool_use Claude-style event so the# Critic's tool-use detection (which greps the@@ -710,6 +851,18 @@ class CodexDirectWorker:except OSError as exc:logger.warning("CodexDirectWorker: stderr.log write failed: %s", exc)+ stderr_text = stderr_bytes.decode("utf-8", errors="replace")+ if (+ terminal_kind == "success"+ and not any_tool_use+ and _codex_sandbox_write_rejected(stderr_text)+ ):+ terminal_kind = "error"+ terminal_message = (+ "Codex could not write to the mission worktree because its "+ "sandbox rejected the file operation."+ )+wall_ms = int((time.perf_counter() - t0) * 1000)exit_code = proc.returncode if proc.returncode is not None else -1@@ -801,6 +954,7 @@ class CodexDirectWorker:timeout_s=timeout_s,mission_id=mission_id,allow_backend_fallback=False, # no codex->claude->codex loop+ _broker_binding=broker_binding,):yield evreturndiff --git a/jarvis/missions/workers/gemini_worker.py b/jarvis/missions/workers/gemini_worker.pyindex 158b7a78a1..b11ff31ded 100644--- a/jarvis/missions/workers/gemini_worker.py+++ b/jarvis/missions/workers/gemini_worker.py@@ -69,25 +69,30 @@ _FALLBACK_MODEL: str = "gemini-3-flash-preview"def _build_isolated_gemini_env(- env: dict[str, str], *, log_dir: Path+ env: dict[str, str],+ *,+ log_dir: Path,+ mcp_servers: dict[str, Any] | None = None,) -> tuple[dict[str, str], Path, str]:"""Apply a highest-precedence restricted config without hiding CLI auth."""settings_path = log_dir / ".jarvis-gemini-system-settings.json"- no_mcp_server = f"jarvis-no-mcp-{uuid.uuid4().hex}"+ server_names = tuple(sorted((mcp_servers or {}).keys()))+ allowed_server = server_names[0] if server_names else f"jarvis-no-mcp-{uuid.uuid4().hex}"+ settings: dict[str, Any] = {+ "hooksConfig": {"enabled": False},+ "mcp": {"allowed": list(server_names) or [allowed_server]},+ "security": {"allowedExtensions": ["(?!)"]},+ "skills": {"enabled": False},+ }+ if server_names:+ settings["mcpServers"] = dict(mcp_servers or {})settings_path.write_text(- json.dumps(- {- "hooksConfig": {"enabled": False},- "mcp": {"allowed": [no_mcp_server]},- "security": {"allowedExtensions": ["(?!)"]},- "skills": {"enabled": False},- }- ),+ json.dumps(settings),encoding="utf-8",)restricted = dict(env)restricted["GEMINI_CLI_SYSTEM_SETTINGS_PATH"] = str(settings_path)- return restricted, settings_path, no_mcp_server+ return restricted, settings_path, allowed_serverdef _stderr_signals_quota_block(stderr_bytes: bytes) -> bool:@@ -292,6 +297,59 @@ class GeminiWorker:max_turns: int = 20,resume_session_id: str | None = None,extra_args: tuple[str, ...] = (),+ _broker_binding: Any | None = None,+ **_unused: Any,+ ) -> AsyncIterator[Any]:+ """Run one Gemini worker lifecycle under one mission-scoped grant."""+ broker_binding = _broker_binding+ issued_here = broker_binding is None+ if issued_here:+ broker_binding = self.capability_inventory.bind_broker(+ ttl_s=1260.0,+ mission_id=_unused.get("mission_id"),+ worker_id=worker_id,+ )+ try:+ async for event in self._spawn_bound(+ prompt,+ worktree=worktree,+ env=env,+ job=job,+ worker_id=worker_id,+ log_dir=log_dir,+ model=model,+ allowed_tools=allowed_tools,+ permission_mode=permission_mode,+ max_turns=max_turns,+ resume_session_id=resume_session_id,+ extra_args=extra_args,+ broker_binding=broker_binding,+ **_unused,+ ):+ yield event+ finally:+ if issued_here and broker_binding is not None:+ try:+ broker_binding.close()+ except Exception: # noqa: BLE001 - cleanup must not mask cancellation+ logger.exception("GeminiWorker: broker binding cleanup failed")++ async def _spawn_bound(+ self,+ prompt: str,+ *,+ worktree: Path,+ env: dict[str, str],+ job: Any,+ worker_id: str,+ log_dir: Path,+ model: str = "gemini-3-flash-preview",+ allowed_tools: str = "", # accepted for parity, ignored by Gemini CLI+ permission_mode: str = "yolo",+ max_turns: int = 20,+ resume_session_id: str | None = None,+ extra_args: tuple[str, ...] = (),+ broker_binding: Any | None,**_unused: Any,) -> AsyncIterator[Any]:"""Spawn the Gemini CLI and emit a synthetic init + result.@@ -315,6 +373,9 @@ class GeminiWorker:# (Gemini 4, etc.) the user updates the TOML and we pick it up# automatically — no code change needed.effective_model = _resolve_gemini_model(model)+ broker_servers = (+ broker_binding.mcp_server_config() if broker_binding is not None else {}+ )cmd = _build_gemini_cmd(prompt,@@ -335,14 +396,24 @@ class GeminiWorker:model=f"gemini/{effective_model}",tools=[],cwd=str(worktree),- external_capabilities=self.capability_inventory.report_for("gemini-cli"),+ external_capabilities=self.capability_inventory.report_for(+ "gemini-cli", binding=broker_binding+ ),)(env_for_gemini,restricted_settings,no_mcp_server,- ) = _build_isolated_gemini_env(env, log_dir=log_dir)+ ) = _build_isolated_gemini_env(+ (+ broker_binding.apply_environment(env)+ if broker_binding is not None+ else env+ ),+ log_dir=log_dir,+ mcp_servers=broker_servers,+ )cmd.extend(["--allowed-mcp-server-names", no_mcp_server])logger.info(diff --git a/jarvis/missions/workers/google_cli_worker.py b/jarvis/missions/workers/google_cli_worker.pyindex a2875dbef4..9dd5fc52db 100644--- a/jarvis/missions/workers/google_cli_worker.py+++ b/jarvis/missions/workers/google_cli_worker.py@@ -26,6 +26,7 @@ official binary is driven; the OAuth token is never read into our own client.from __future__ import annotationsimport asyncio+import jsonimport loggingimport osimport shutil@@ -65,6 +66,10 @@ _DROP_ENV: tuple[str, ...] = (_WORKER_TIMEOUT_S: float = 1200.0+class BrokerMcpConfigurationError(RuntimeError):+ """Raised when the isolated Google CLI cannot receive the broker config."""++def _build_agy_worker_argv(exe: str, prompt: str, worktree: Path) -> list[str]:"""agy worker argv: one non-interactive prompt with auto-approved tools so itcan write files in the worktree.@@ -101,7 +106,9 @@ def _build_agy_worker_argv(exe: str, prompt: str, worktree: Path) -> list[str]:]-def _build_agy_worker_env(base_env: dict[str, str]) -> dict[str, str]:+def _build_agy_worker_env(+ base_env: dict[str, str], *, mcp_servers: dict[str, Any] | None = None+) -> dict[str, str]:"""Worker child env for agy: drop API keys (OAuth wins), repair PATH for agy'sinternal cmd/npm spawns, and redirect HOME to the isolated hook/mcp-free home."""env = {k: v for k, v in base_env.items() if k not in _DROP_ENV}@@ -114,6 +121,22 @@ def _build_agy_worker_env(base_env: dict[str, str]) -> dict[str, str]:)if iso:redirect_home_env(env, iso)+ if mcp_servers:+ if not iso:+ raise BrokerMcpConfigurationError(+ "the isolated Google CLI home is unavailable"+ )+ settings_path = Path(iso) / ".gemini" / "settings.json"+ try:+ settings = json.loads(settings_path.read_text(encoding="utf-8"))+ if not isinstance(settings, dict):+ raise TypeError("Google CLI settings must contain an object")+ settings["mcpServers"] = dict(mcp_servers)+ settings_path.write_text(json.dumps(settings), encoding="utf-8")+ except (OSError, ValueError, TypeError) as exc:+ raise BrokerMcpConfigurationError(+ "broker MCP settings could not be written in the isolated Google CLI home"+ ) from excreturn env@@ -152,6 +175,59 @@ class GoogleCliWorker:max_turns: int = 20,resume_session_id: str | None = None,extra_args: tuple[str, ...] = (),+ _broker_binding: Any | None = None,+ **_unused: Any,+ ) -> AsyncIterator[Any]:+ """Run one Google worker lifecycle under one mission-scoped grant."""+ broker_binding = _broker_binding+ issued_here = broker_binding is None+ if issued_here:+ broker_binding = self.capability_inventory.bind_broker(+ ttl_s=_WORKER_TIMEOUT_S + 60.0,+ mission_id=_unused.get("mission_id"),+ worker_id=worker_id,+ )+ try:+ async for event in self._spawn_bound(+ prompt,+ worktree=worktree,+ env=env,+ job=job,+ worker_id=worker_id,+ log_dir=log_dir,+ model=model,+ allowed_tools=allowed_tools,+ permission_mode=permission_mode,+ max_turns=max_turns,+ resume_session_id=resume_session_id,+ extra_args=extra_args,+ broker_binding=broker_binding,+ **_unused,+ ):+ yield event+ finally:+ if issued_here and broker_binding is not None:+ try:+ broker_binding.close()+ except Exception: # noqa: BLE001 - cleanup must not mask cancellation+ logger.exception("GoogleCliWorker: broker binding cleanup failed")++ async def _spawn_bound(+ self,+ prompt: str,+ *,+ worktree: Path,+ env: dict[str, str],+ job: Any,+ worker_id: str,+ log_dir: Path,+ model: str = "gemini-3.5-flash",+ allowed_tools: str = "", # parity, ignored by agy+ permission_mode: str = "yolo",+ max_turns: int = 20,+ resume_session_id: str | None = None,+ extra_args: tuple[str, ...] = (),+ broker_binding: Any | None,**_unused: Any,) -> AsyncIterator[Any]:cli = resolve_google_cli()@@ -207,6 +283,7 @@ class GoogleCliWorker:max_turns=max_turns,resume_session_id=resume_session_id,extra_args=extra_args,+ _broker_binding=broker_binding,**_unused,):yield ev@@ -218,14 +295,46 @@ class GoogleCliWorker:exe = cli.argv_prefix[0]log_dir.mkdir(parents=True, exist_ok=True) # noqa: ASYNC240 — trivial sync mkdir (mirrors GeminiWorker)argv = _build_agy_worker_argv(exe, prompt, worktree)- agy_env = _build_agy_worker_env(env)+ broker_servers = (+ broker_binding.mcp_server_config() if broker_binding is not None else {}+ )+ agy_base_env = (+ broker_binding.apply_environment(env)+ if broker_binding is not None+ else env+ )+ try:+ agy_env = _build_agy_worker_env(agy_base_env, mcp_servers=broker_servers)+ except BrokerMcpConfigurationError as exc:+ logger.error("GoogleCliWorker[%s]: %s", worker_id, exc)+ yield ClaudeSystemInit(+ session_id=session_id,+ model="antigravity/agy",+ tools=[],+ cwd=str(worktree),+ external_capabilities=self.capability_inventory.report_for(+ "google-cli", binding=None+ ),+ )+ yield ClaudeResult(+ subtype="error_during_execution",+ is_error=True,+ cost_usd=None,+ num_turns=None,+ session_id=session_id,+ duration_ms=0,+ result=f"GoogleCliWorker broker MCP configuration failed: {exc}",+ )+ returnyield ClaudeSystemInit(session_id=session_id,model="antigravity/agy",tools=[],cwd=str(worktree),- external_capabilities=self.capability_inventory.report_for("google-cli"),+ external_capabilities=self.capability_inventory.report_for(+ "google-cli", binding=broker_binding+ ),)logger.info("GoogleCliWorker[%s] spawn agy over PTY: cwd=%s (Google subscription, OAuth)",diff --git a/jarvis/missions/workers/worker_tool_broker.py b/jarvis/missions/workers/worker_tool_broker.pynew file mode 100644index 0000000000..43e712d540--- /dev/null+++ b/jarvis/missions/workers/worker_tool_broker.py@@ -0,0 +1,709 @@+"""Mission-scoped bridge from worker tools to the supervisor ToolExecutor.++CLI workers run the companion stdio MCP process and reach this broker over an+authenticated loopback-only HTTP endpoint. API workers use the same binding+directly as an async callback. In both cases the live supervisor owns the+actual tool object and executes it through ``ToolExecutor``; a worker never+receives connector credentials or a direct ``Tool.execute`` handle.+"""++from __future__ import annotations++import asyncio+import json+import logging+import secrets+import sys+import threading+import time+from contextlib import suppress+from dataclasses import dataclass, field+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer+from typing import Any, Literal+from uuid import uuid4++from jarvis.core import runtime_refs+from jarvis.core.protocols import SupervisorToolDescriptor, SupervisorToolRequest+from jarvis.core.redact import safe_preview++logger = logging.getLogger(__name__)++BROKER_SERVER_ID = "jarvis_worker_tools"+BROKER_TOKEN_ENV = "JARVIS_WORKER_BROKER_TOKEN" # noqa: S105 - env variable name+BROKER_URL_ENV = "JARVIS_WORKER_BROKER_URL"++_DEFAULT_TTL_S = 25 * 60.0+_EXECUTION_TIMEOUT_S = 65.0+_MAX_REQUEST_BYTES = 1024 * 1024++_FORBIDDEN_EXACT = frozenset(+ {+ "dispatch-with-review",+ "dispatch_with_review",+ "multi-spawn",+ "multi_spawn",+ "run-skill",+ "run_skill",+ "spawn-worker",+ "spawn_worker",+ }+)+_FORBIDDEN_NAME_FRAGMENTS = (+ "api-key",+ "api_key",+ "credential",+ "reveal-key",+ "reveal_key",+ "secret",+ "set-config",+ "set_config",+)++BrokerCallStatus = Literal[+ "active",+ "success",+ "denied",+ "cancelled",+ "timed_out",+ "error",+ "outcome_unknown",+]+++@dataclass(frozen=True, slots=True)+class WorkerToolCallOutcome:+ """Credential-free terminal record for one supervisor tool call."""++ trace_id: str+ tool_name: str+ status: BrokerCallStatus+ error: str = ""+++@dataclass(frozen=True, slots=True)+class WorkerToolExecutionSummary:+ """Completion certificate consumed by the mission controller."""++ calls: tuple[WorkerToolCallOutcome, ...] = ()++ @property+ def clean(self) -> bool:+ return all(call.status == "success" for call in self.calls)++ @property+ def active_count(self) -> int:+ return sum(call.status == "active" for call in self.calls)++ @property+ def 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]+ )+ 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:+ """Fail closed for recursion and credential/config mutation surfaces."""+ normalized = str(name or "").strip().lower()+ leaf = normalized.rsplit("/", 1)[-1].rsplit(":", 1)[-1].rsplit(".", 1)[-1]+ canonical_leaf = leaf.replace("_", "-")+ forbidden_leafs = {item.replace("_", "-") for item in _FORBIDDEN_EXACT}+ if not normalized or canonical_leaf in forbidden_leafs:+ return False+ return not any(part in normalized for part in _FORBIDDEN_NAME_FRAGMENTS)+++def _json_safe(value: Any) -> Any:+ try:+ json.dumps(value)+ except (TypeError, ValueError):+ return json.loads(json.dumps(value, default=str))+ return value+++def _tool_spec(descriptor: SupervisorToolDescriptor) -> dict[str, Any]:+ return {+ "name": descriptor.name,+ "description": descriptor.description,+ "input_schema": _json_safe(descriptor.input_schema),+ }+++class _ScopeCancelToken:+ def __init__(self) -> None:+ self._event = threading.Event()+ self._reason: str | None = None++ def cancel(self, reason: str) -> None:+ self._reason = reason+ self._event.set()++ def is_cancelled(self) -> bool:+ return self._event.is_set()++ @property+ def reason(self) -> str | None:+ return self._reason++ async def wait_until_cancelled(self) -> None:+ await asyncio.to_thread(self._event.wait)+++@dataclass(slots=True)+class _BrokerScope:+ task_text: str+ gateway: Any+ loop: asyncio.AbstractEventLoop+ expires_at: float+ mcp_server_ids: tuple[str, ...]+ app_commands: tuple[str, ...]+ native_tool_names: tuple[str, ...]+ mission_id: str | None = None+ worker_id: str | None = None+ _revoked: bool = False+ _state_lock: threading.Lock = field(default_factory=threading.Lock, repr=False)+ _active_tasks: set[asyncio.Task[Any]] = field(default_factory=set, repr=False)+ _cancel_token: _ScopeCancelToken = field(default_factory=_ScopeCancelToken, repr=False)+ _calls: dict[str, WorkerToolCallOutcome] = field(default_factory=dict, repr=False)++ @property+ def active(self) -> bool:+ with self._state_lock:+ return not self._revoked and time.monotonic() < self.expires_at++ def _descriptors(self) -> tuple[SupervisorToolDescriptor, ...]:+ if not self.active:+ return ()+ allowed_exact = set(self.app_commands) | set(self.native_tool_names)+ prefixes = tuple(f"{server_id}/" for server_id in self.mcp_server_ids)+ return tuple(+ descriptor+ for descriptor in self.gateway.catalog()+ if (+ descriptor.name in allowed_exact+ or any(descriptor.name.startswith(prefix) for prefix in prefixes)+ )+ and worker_tool_name_allowed(descriptor.name)+ )++ @property+ def specs(self) -> tuple[dict[str, Any], ...]:+ return tuple(_tool_spec(descriptor) for descriptor in self._descriptors())++ def revoke(self, reason: str) -> None:+ with self._state_lock:+ if self._revoked:+ return+ self._revoked = True+ active_tasks = tuple(self._active_tasks)+ for trace_id, call in tuple(self._calls.items()):+ if call.status == "active":+ self._calls[trace_id] = WorkerToolCallOutcome(+ trace_id=trace_id,+ tool_name=call.tool_name,+ status="outcome_unknown",+ error=safe_preview(reason, max_chars=120),+ )+ self._cancel_token.cancel(reason)+ for task in active_tasks:+ self.loop.call_soon_threadsafe(task.cancel)++ def _start_call(self, trace_id: str, tool_name: str) -> None:+ with self._state_lock:+ self._calls[trace_id] = WorkerToolCallOutcome(+ trace_id=trace_id,+ tool_name=tool_name,+ status="active",+ )++ def _finish_call(+ self,+ trace_id: str,+ tool_name: str,+ status: BrokerCallStatus,+ error: str = "",+ ) -> None:+ with self._state_lock:+ current = self._calls.get(trace_id)+ if current is not None and current.status == "outcome_unknown":+ return+ self._calls[trace_id] = WorkerToolCallOutcome(+ trace_id=trace_id,+ tool_name=tool_name,+ status=status,+ error=safe_preview(error, max_chars=160),+ )++ @property+ def execution_summary(self) -> WorkerToolExecutionSummary:+ with self._state_lock:+ calls = tuple(self._calls.values())+ return WorkerToolExecutionSummary(calls=calls)++ async def wait_for_idle(self, timeout_s: float = 1.0) -> None:+ """Bounded quiescence wait after cancellation/revocation."""+ deadline = self.loop.time() + max(0.0, timeout_s)+ while self.loop.time() < deadline:+ with self._state_lock:+ if not self._active_tasks:+ return+ await asyncio.sleep(0.01)++ @staticmethod+ def _denied(error: str = "Mission tool grant has expired.") -> dict[str, Any]:+ return {+ "status": "denied",+ "success": False,+ "output": None,+ "error": error,+ }++ async def execute(self, name: str, arguments: dict[str, Any]) -> dict[str, Any]:+ trace_id = uuid4()+ trace_key = str(trace_id)+ if not self.active:+ self._start_call(trace_key, name)+ self._finish_call(trace_key, name, "denied", "grant expired")+ return {**self._denied(), "trace_id": trace_key}+ granted_names = {descriptor.name for descriptor in self._descriptors()}+ if name not in granted_names or not worker_tool_name_allowed(name):+ self._start_call(trace_key, name)+ self._finish_call(trace_key, name, "denied", "tool not granted")+ return {+ **self._denied("Tool is not granted to this mission."),+ "trace_id": trace_key,+ }++ task = asyncio.current_task()+ if task is None:+ self._start_call(trace_key, name)+ self._finish_call(trace_key, name, "error", "missing task context")+ return {+ **self._denied("Mission tool execution has no task context."),+ "trace_id": trace_key,+ }+ with self._state_lock:+ if self._revoked or time.monotonic() >= self.expires_at:+ self._calls[trace_key] = WorkerToolCallOutcome(+ trace_id=trace_key,+ tool_name=name,+ status="denied",+ error="grant expired",+ )+ return {**self._denied(), "trace_id": trace_key}+ self._active_tasks.add(task)+ self._calls[trace_key] = WorkerToolCallOutcome(+ trace_id=trace_key,+ tool_name=name,+ status="active",+ )+ try:+ result = await self.gateway.execute(+ name,+ dict(arguments),+ SupervisorToolRequest(+ trace_id=trace_id,+ origin="mission_worker",+ user_utterance=self.task_text,+ rationale="Mission worker requested a supervisor-granted tool.",+ mission_id=self.mission_id,+ worker_id=self.worker_id,+ config_snapshot={+ "voice_confirm": False,+ "worker_broker": True,+ },+ cancel_token=self._cancel_token,+ ),+ )+ if not self.active:+ self._finish_call(+ trace_key,+ name,+ "outcome_unknown",+ "grant ended during execution",+ )+ return {+ **self._denied("Mission tool grant ended during execution."),+ "status": "outcome_unknown" if result.success else "denied",+ "trace_id": str(trace_id),+ }+ status = "ok" if result.success else "error"+ call_status: BrokerCallStatus = "success" if result.success else "error"+ if result.error and result.error.startswith("approval-denied"):+ status = "approval_denied"+ call_status = "denied"+ elif result.error and "cancelled" in result.error.lower():+ call_status = "cancelled"+ elif result.error and "timeout" in result.error.lower():+ call_status = "timed_out"+ self._finish_call(+ trace_key,+ name,+ call_status,+ result.error or "",+ )+ return {+ "status": status,+ "success": bool(result.success),+ "output": _json_safe(result.output),+ "error": result.error,+ "trace_id": str(trace_id),+ }+ except asyncio.CancelledError:+ self._finish_call(+ trace_key,+ name,+ "outcome_unknown",+ self._cancel_token.reason or "execution cancelled",+ )+ raise+ except TimeoutError as exc:+ self._finish_call(trace_key, name, "timed_out", str(exc))+ raise+ except Exception as exc:+ self._finish_call(trace_key, name, "error", str(exc))+ raise+ finally:+ with self._state_lock:+ self._active_tasks.discard(task)+++@dataclass(slots=True)+class WorkerToolBrokerBinding:+ """One short-lived mission grant shared by an API or CLI worker."""++ url: str+ _token: str = field(repr=False)+ _scope: _BrokerScope = field(repr=False)+ _broker: Any = field(repr=False)+ _closed: bool = field(default=False, repr=False)++ @property+ def available(self) -> bool:+ return not self._closed and self._scope.active and bool(self.tool_specs)++ @property+ def tool_specs(self) -> tuple[dict[str, Any], ...]:+ if self._closed or not self._scope.active:+ return ()+ return self._scope.specs++ @property+ def tool_names(self) -> tuple[str, ...]:+ return tuple(str(spec["name"]) for spec in self.tool_specs)++ @property+ def execution_summary(self) -> WorkerToolExecutionSummary:+ return self._scope.execution_summary++ def apply_environment(self, env: dict[str, str]) -> dict[str, str]:+ """Return a copy with the bearer in env only, never argv/config/logs."""+ out = dict(env)+ if self.available:+ out[BROKER_URL_ENV] = self.url+ out[BROKER_TOKEN_ENV] = self._token+ return out++ def mcp_server_config(self) -> dict[str, dict[str, Any]]:+ if not self.available:+ return {}+ if bool(getattr(sys, "frozen", False)):+ adapter_args = ["--worker-tool-broker-stdio"]+ else:+ adapter_args = ["-m", "jarvis.missions.workers.broker_stdio"]+ return {+ BROKER_SERVER_ID: {+ "command": sys.executable,+ "args": adapter_args,+ }+ }++ async def execute(self, name: str, arguments: dict[str, Any]) -> dict[str, Any]:+ if self._closed or not self._scope.active:+ self.close()+ return self._scope._denied()+ return await self._scope.execute(name, arguments)++ def close(self) -> None:+ if not self._closed:+ self._broker.revoke(self._token)+ self._closed = True++ async def aclose(self) -> None:+ self.close()+ await self._scope.wait_for_idle()++ def __del__(self) -> None:+ # Generator cancellation and provider fallback can skip a normal return;+ # finalization revokes the grant while the TTL remains the hard backstop.+ with suppress(Exception):+ self.close()+++@dataclass(slots=True)+class EmptyWorkerToolBrokerBinding:+ """Clean, inert grant used when an iteration has no supervisor tools."""++ available: bool = False+ tool_specs: tuple[dict[str, Any], ...] = ()+ tool_names: tuple[str, ...] = ()++ @property+ def execution_summary(self) -> WorkerToolExecutionSummary:+ return WorkerToolExecutionSummary()++ def apply_environment(self, env: dict[str, str]) -> dict[str, str]:+ return dict(env)++ def mcp_server_config(self) -> dict[str, dict[str, Any]]:+ return {}++ async def execute(self, _name: str, _arguments: dict[str, Any]) -> dict[str, Any]:+ return {+ "status": "denied",+ "success": False,+ "output": None,+ "error": "No supervisor tools are granted to this mission.",+ }++ def close(self) -> None:+ return++ async def aclose(self) -> None:+ return+++class _LoopbackServer(ThreadingHTTPServer):+ daemon_threads = True+ allow_reuse_address = False++ def __init__(self, broker: WorkerToolBroker) -> None:+ self.broker = broker+ super().__init__(("127.0.0.1", 0), _BrokerRequestHandler)+++class _BrokerRequestHandler(BaseHTTPRequestHandler):+ server: _LoopbackServer++ def log_message(self, _format: str, *_args: Any) -> None:+ # The default handler logs request paths and client data to stderr.+ # Worker grants are intentionally silent; never risk logging a bearer.+ return++ def _scope(self) -> _BrokerScope | None:+ header = self.headers.get("Authorization", "")+ prefix = "Bearer "+ if not header.startswith(prefix):+ return None+ return self.server.broker.lookup(header[len(prefix) :])++ def _send(self, status: int, payload: dict[str, Any]) -> None:+ body = json.dumps(payload, ensure_ascii=False, default=str).encode("utf-8")+ self.send_response(status)+ self.send_header("Content-Type", "application/json; charset=utf-8")+ self.send_header("Content-Length", str(len(body)))+ self.end_headers()+ self.wfile.write(body)++ def do_GET(self) -> None: # noqa: N802 - stdlib handler contract+ scope = self._scope()+ if scope is None:+ self._send(401, {"error": "unauthorized"})+ return+ if self.path != "/v1/tools":+ self._send(404, {"error": "not found"})+ return+ self._send(200, {"tools": list(scope.specs)})++ def do_POST(self) -> None: # noqa: N802 - stdlib handler contract+ scope = self._scope()+ if scope is None:+ self._send(401, {"error": "unauthorized"})+ return+ if self.path != "/v1/execute":+ self._send(404, {"error": "not found"})+ return+ try:+ size = int(self.headers.get("Content-Length", "0"))+ except ValueError:+ size = -1+ if size < 0 or size > _MAX_REQUEST_BYTES:+ self._send(413, {"error": "request too large"})+ return+ try:+ payload = json.loads(self.rfile.read(size) or b"{}")+ name = str(payload["name"])+ arguments = payload.get("arguments") or {}+ if not isinstance(arguments, dict):+ raise TypeError("arguments must be an object")+ except (KeyError, TypeError, ValueError, json.JSONDecodeError) as exc:+ self._send(400, {"error": str(exc)})+ return+ future = asyncio.run_coroutine_threadsafe(+ scope.execute(name, arguments), scope.loop+ )+ try:+ result = future.result(timeout=_EXECUTION_TIMEOUT_S)+ except TimeoutError:+ future.cancel()+ self._send(504, {"error": "supervisor tool execution timed out"})+ return+ except Exception as exc: # noqa: BLE001 - fail closed at process boundary+ logger.warning(+ "Worker tool broker request failed: %s",+ safe_preview(type(exc).__name__, max_chars=80),+ )+ self._send(500, {"error": "supervisor tool execution failed"})+ return+ self._send(200, result)+++class WorkerToolBroker:+ """Process-local registry plus a loopback-only authenticated HTTP seam."""++ def __init__(self) -> None:+ self._lock = threading.Lock()+ self._scopes: dict[str, _BrokerScope] = {}+ self._server: _LoopbackServer | None = None+ self._thread: threading.Thread | None = None++ def _ensure_server(self) -> _LoopbackServer:+ with self._lock:+ if self._server is None:+ server = _LoopbackServer(self)+ thread = threading.Thread(+ target=server.serve_forever,+ name="jarvis-worker-tool-broker",+ daemon=True,+ )+ thread.start()+ self._server = server+ self._thread = thread+ return self._server++ def issue(+ self,+ *,+ task_text: str,+ mcp_server_ids: tuple[str, ...],+ app_commands: tuple[str, ...],+ native_tool_names: tuple[str, ...],+ ttl_s: float = _DEFAULT_TTL_S,+ mission_id: str | None = None,+ worker_id: str | None = None,+ ) -> WorkerToolBrokerBinding | None:+ """Resolve a live, credential-aware grant from the supervisor tools."""+ try:+ loop = asyncio.get_running_loop()+ except RuntimeError:+ return None+ gateway = runtime_refs.get_supervisor_tool_gateway()+ if gateway is None:+ return None++ scope = _BrokerScope(+ task_text=task_text,+ gateway=gateway,+ loop=loop,+ expires_at=time.monotonic() + max(1.0, float(ttl_s)),+ mcp_server_ids=tuple(dict.fromkeys(mcp_server_ids)),+ app_commands=tuple(dict.fromkeys(app_commands)),+ native_tool_names=tuple(dict.fromkeys(native_tool_names)),+ mission_id=mission_id,+ worker_id=worker_id,+ )+ if not scope.specs:+ return None+ server = self._ensure_server()+ token = secrets.token_urlsafe(32)+ with self._lock:+ self._reap_locked()+ self._scopes[token] = scope+ host, port = server.server_address[:2]+ return WorkerToolBrokerBinding(+ url=f"http://{host}:{port}",+ _token=token,+ _scope=scope,+ _broker=self,+ )++ def _reap_locked(self) -> None:+ now = time.monotonic()+ expired = [token for token, scope in self._scopes.items() if scope.expires_at <= now]+ for token in expired:+ scope = self._scopes.pop(token, None)+ if scope is not None:+ scope.revoke("grant_expired")++ def lookup(self, token: str) -> _BrokerScope | None:+ with self._lock:+ self._reap_locked()+ # Iterate with compare_digest so token lookup has no early-exit+ # comparison on a secret supplied by an untrusted worker process.+ for expected, scope in self._scopes.items():+ if secrets.compare_digest(expected, token):+ return scope+ return None++ def revoke(self, token: str) -> None:+ with self._lock:+ scope = self._scopes.pop(token, None)+ if scope is not None:+ scope.revoke("grant_revoked")++ def reset_for_tests(self) -> None:+ with self._lock:+ scopes = tuple(self._scopes.values())+ self._scopes.clear()+ server = self._server+ self._server = None+ self._thread = None+ for scope in scopes:+ scope.revoke("broker_reset")+ if server is not None:+ server.shutdown()+ server.server_close()+++_BROKER = WorkerToolBroker()+++def issue_worker_tool_binding(+ *,+ task_text: str,+ mcp_server_ids: tuple[str, ...],+ app_commands: tuple[str, ...],+ native_tool_names: tuple[str, ...],+ ttl_s: float = _DEFAULT_TTL_S,+ mission_id: str | None = None,+ worker_id: str | None = None,+) -> WorkerToolBrokerBinding | None:+ return _BROKER.issue(+ task_text=task_text,+ mcp_server_ids=mcp_server_ids,+ app_commands=app_commands,+ native_tool_names=native_tool_names,+ ttl_s=ttl_s,+ mission_id=mission_id,+ worker_id=worker_id,+ )+++__all__ = [+ "BROKER_SERVER_ID",+ "BROKER_TOKEN_ENV",+ "BROKER_URL_ENV",+ "EmptyWorkerToolBrokerBinding",+ "WorkerToolCallOutcome",+ "WorkerToolBrokerBinding",+ "WorkerToolExecutionSummary",+ "issue_worker_tool_binding",+ "worker_tool_name_allowed",+]diff --git a/jarvis/realtime/session.py b/jarvis/realtime/session.pyindex c1440db11e..2d7ce71abd 100644--- a/jarvis/realtime/session.py+++ b/jarvis/realtime/session.py@@ -168,7 +168,7 @@ _TOOL_ROLE_DIRECTIVE = ("code, research, start background work, open a view, change a setting, ""control the computer — call the matching function instead of claiming ""you cannot act. Heavy multi-minute work (building files, coding, deep "- "research) belongs to the background-agent spawn function: start it, "+ "research) belongs to the Jarvis-Agent spawn function: start it, ""then briefly confirm what you started. If a function asks for a spoken ""confirmation, relay the question and wait for the user's answer.")@@ -313,9 +313,8 @@ class RealtimeVoiceSession:self._delegate_history: list[BrainMessage] = []self._delegate_required_for_turn = Falseself._external_update: _ExternalUpdateState | None = None- # from_brain returns None SILENTLY when the brain object carries no- # _tools/_tool_executor_ref (e.g. a bare callback was passed) — say so,- # or a tool-less session is indistinguishable from a healthy one.+ # from_brain returns None when no public supervisor gateway is ready.+ # Say so, or a tool-less session is indistinguishable from a healthy one.if self._delegate_enabled:log.info("realtime[%s] tool mode: delegate — one action function "@@ -331,7 +330,7 @@ class RealtimeVoiceSession:elif brain is not None:log.warning("realtime[%s] brain provided but NO tool bridge — object has "- "no usable _tools/_tool_executor_ref; session runs tool-less",+ "no usable supervisor tool gateway; session runs tool-less",session_id,)self._gate = ScrubHoldGate(self._language)@@ -395,8 +394,15 @@ class RealtimeVoiceSession:registry = get_registry()except Exception: # noqa: BLE001 - planner has static safe fallbackslog.debug("Realtime capability registry unavailable", exc_info=True)- tools = getattr(self._brain, "_tools", None)- tool_names = tuple(tools) if isinstance(tools, dict) else ()+ tool_names: tuple[str, ...] = ()+ try:+ from jarvis.core.runtime_refs import get_supervisor_tool_gateway++ gateway = get_supervisor_tool_gateway()+ if gateway is not None:+ tool_names = tuple(item.name for item in gateway.catalog())+ except Exception: # noqa: BLE001 - planning keeps static fallbacks+ log.debug("Realtime supervisor tool catalog unavailable", exc_info=True)evidence_cfg = getattr(getattr(self._config, "brain", None), "evidence_domains", None)@@ -1771,20 +1777,18 @@ class RealtimeVoiceSession:).strip()if reply:turn_state.last_reply = reply- if reply:result: dict[str, Any] = {"success": True, "spoken_reply": reply}+ succeeded = Trueelse:result = {- "success": True,- "spoken_reply": "",- "note": (- "The action completed without a spoken reply; "- "briefly confirm it to the user."- ),+ "success": False,+ "error": "The delegated action returned no grounded result.",}- succeeded = Trueif self._delegate_turns.get(turn_id) is turn_state:- self._executed_tool_names.add(str(_DELEGATE_DECLARATION["name"]))+ if succeeded:+ self._executed_tool_names.add(+ str(_DELEGATE_DECLARATION["name"])+ )except TimeoutError:result = {"success": False,@@ -1806,6 +1810,13 @@ class RealtimeVoiceSession:"success": False,"error": "The action failed safely and was not completed.",}+ if not succeeded:+ from jarvis.voice.action_phrases import action_phrase++ turn_state.last_reply = action_phrase(+ "action_failed_generic", self._language+ )+ result["spoken_reply"] = turn_state.last_replyturn_state.result_complete = Trueturn_state.result_success = succeededturn_state.result_payload = resultdiff --git a/jarvis/realtime/tools.py b/jarvis/realtime/tools.pyindex 7abf5d3854..7b60922ce7 100644--- a/jarvis/realtime/tools.py+++ b/jarvis/realtime/tools.py@@ -6,7 +6,7 @@ import hashlibimport jsonimport refrom dataclasses import dataclass-from typing import Any+from typing import Any, castfrom uuid import UUID, uuid4from jarvis.brain.tool_use_loop import (@@ -17,6 +17,13 @@ from jarvis.brain.tool_use_loop import (_is_stt_hallucinated,_should_block_action_as_research,)+from jarvis.core import runtime_refs+from jarvis.core.protocols import (+ RiskTier,+ SupervisorToolDescriptor,+ SupervisorToolGateway,+ SupervisorToolRequest,+)from jarvis.safety.tool_executor import VOICE_CONFIRM_SENTINELfrom jarvis.voice.echo_confirmation import classify_responsefrom jarvis.voice.tool_confirmation import format_tool_confirmation@@ -75,15 +82,20 @@ class RealtimeToolBridge:def __init__(self,*,- tools: dict[str, Any],- executor: Any,+ tools: dict[str, Any] | None = None,+ executor: Any = None,+ gateway: SupervisorToolGateway | None = None,language: str,tools_source: Any = None,) -> None:- self._tools = dict(tools)+ self._tools = dict(tools or {})self._tools_source = tools_sourceself._executor = executor+ self._gateway = gatewayself._language = language+ self._descriptors: dict[str, SupervisorToolDescriptor] = (+ self._read_descriptors()+ )self._wire_to_name: dict[str, str] = {}self._declarations: tuple[dict[str, Any], ...] = self._build_declarations()self._pending: _PendingConfirmation | None = None@@ -91,25 +103,48 @@ class RealtimeToolBridge:self._last_user_text = ""@classmethod- def from_brain(cls, brain: Any, *, language: str) -> RealtimeToolBridge | None:- tools = getattr(brain, "_tools", None)- executor = getattr(brain, "_tool_executor_ref", None)- if not isinstance(tools, dict) or not tools or executor is None:+ def from_brain(cls, _brain: Any, *, language: str) -> RealtimeToolBridge | None:+ """Build from the public supervisor gateway registered by Brain factory."""+ gateway = runtime_refs.get_supervisor_tool_gateway()+ if gateway is None or not gateway.catalog():return None- return cls(- tools=tools,- executor=executor,- language=language,- tools_source=lambda: getattr(brain, "_tools", None),- )+ return cls(gateway=gateway, language=language)- def _build_declarations(self) -> tuple[dict[str, Any], ...]:- self._wire_to_name.clear()- declarations: list[dict[str, Any]] = []- for name, tool in sorted(self._tools.items()):+ def _read_descriptors(+ self,+ tools_override: dict[str, Any] | None = None,+ ) -> dict[str, SupervisorToolDescriptor]:+ if self._gateway is not None:+ try:+ return {item.name: item for item in self._gateway.catalog()}+ except Exception: # noqa: BLE001 - a catalog refresh degrades safely+ return {}++ descriptors: dict[str, SupervisorToolDescriptor] = {}+ source_tools = self._tools if tools_override is None else tools_override+ for name, tool in source_tools.items():schema = getattr(tool, "schema", None)if not isinstance(schema, dict):continue+ raw_tier = str(getattr(tool, "risk_tier", "monitor"))+ risk_tier = cast(+ RiskTier,+ raw_tier if raw_tier in {"safe", "monitor", "ask", "block"}+ else "monitor",+ )+ descriptors[str(name)] = SupervisorToolDescriptor(+ name=str(name),+ description=str(getattr(tool, "description", "")),+ input_schema=schema,+ risk_tier=risk_tier,+ is_action_tool=bool(getattr(tool, "is_action_tool", False)),+ )+ return descriptors++ def _build_declarations(self) -> tuple[dict[str, Any], ...]:+ self._wire_to_name.clear()+ declarations: list[dict[str, Any]] = []+ for name, descriptor in sorted(self._descriptors.items()):wire = _wire_name(str(name))if wire in self._wire_to_name:continue@@ -117,10 +152,10 @@ class RealtimeToolBridge:declarations.append({"name": wire,- "description": str(getattr(tool, "description", ""))[+ "description": descriptor.description[:_MAX_DESCRIPTION_CHARS],- "parameters": schema,+ "parameters": descriptor.input_schema,})return tuple(declarations)@@ -140,25 +175,40 @@ class RealtimeToolBridge:resolves, so a concurrent registry refresh cannot strand the pending``ToolExecutor`` action."""- source = self._tools_source- if not callable(source):- return False- current = source()- if not isinstance(current, dict):- return False- try:- refreshed = dict(current)- except RuntimeError:- return False+ if self._gateway is not None:+ refreshed_descriptors = self._read_descriptors()+ refreshed_tools: dict[str, Any] | None = None+ else:+ source = self._tools_source+ if not callable(source):+ return False+ current = source()+ if not isinstance(current, dict):+ return False+ try:+ refreshed_tools = dict(current)+ except RuntimeError:+ return False+ refreshed_descriptors = self._read_descriptors(refreshed_tools)pending = self._pendingif (pending is not None- and pending.tool_name not in refreshed- and pending.tool_name in self._tools+ and pending.tool_name not in refreshed_descriptors+ and pending.tool_name in self._descriptors):- refreshed[pending.tool_name] = self._tools[pending.tool_name]+ refreshed_descriptors[pending.tool_name] = self._descriptors[+ pending.tool_name+ ]+ if (+ refreshed_tools is not None+ and pending.tool_name not in refreshed_tools+ and pending.tool_name in self._tools+ ):+ refreshed_tools[pending.tool_name] = self._tools[pending.tool_name]previous_declarations = self._declarations- self._tools = refreshed+ if refreshed_tools is not None:+ self._tools = refreshed_tools+ self._descriptors = refreshed_descriptorsself._declarations = self._build_declarations()return self._declarations != previous_declarations@@ -172,7 +222,7 @@ class RealtimeToolBridge:if verdict == "confirm":pending.confirmed = Trueelif verdict == "veto":- await self._executor.cancel_pending(pending.trace_id)+ await self._cancel_pending(pending.trace_id)self._vetoed_tool = pending.tool_nameself._pending = None@@ -184,8 +234,8 @@ class RealtimeToolBridge:trace_id: UUID | None = None,) -> tuple[str, dict[str, Any]]:name = self._wire_to_name.get(wire_name, "")- tool = self._tools.get(name)- if tool is None:+ descriptor = self._descriptors.get(name)+ if descriptor is None:await self._publish_denied(wire_name, "unknown realtime tool")return wire_name, {"success": False,@@ -196,12 +246,12 @@ class RealtimeToolBridge:"success": False,"error": "The user declined this action. Do not ask again in this turn.",}- validation_error = self._validate_arguments(tool, arguments)+ validation_error = self._validate_arguments(descriptor, arguments)if validation_error:await self._publish_denied(name, validation_error)return name, {"success": False, "error": validation_error}- guard_error = await self._guard(tool, name, arguments)+ guard_error = await self._guard(descriptor, name, arguments)if guard_error:return name, {"success": False, "error": guard_error}@@ -215,11 +265,7 @@ class RealtimeToolBridge:name, language=self._language),}- result = await self._executor.execute_confirmed(- pending.trace_id,- user_utterance=self._last_user_text,- config_snapshot={"output_language": self._language},- )+ result = await self._execute_confirmed(pending.trace_id)self._pending = Nonereturn name, _bounded_result(bool(getattr(result, "success", False)),@@ -228,17 +274,7 @@ class RealtimeToolBridge:)trace_id = trace_id or uuid4()- result = await self._executor.execute(- tool,- arguments,- user_utterance=self._last_user_text,- config_snapshot={- "output_language": self._language,- "voice_confirm": True,- },- trace_id=trace_id,- rationale="Realtime model requested an available Jarvis tool.",- )+ result = await self._execute_tool(name, arguments, trace_id)if (getattr(result, "error", None) == VOICE_CONFIRM_SENTINELand isinstance(getattr(result, "output", None), dict)@@ -259,7 +295,67 @@ class RealtimeToolBridge:getattr(result, "error", None),)- def _validate_arguments(self, tool: Any, arguments: Any) -> str:+ async def _execute_tool(+ self,+ name: str,+ arguments: dict[str, Any],+ trace_id: UUID,+ ) -> Any:+ if self._gateway is not None:+ return await self._gateway.execute(+ name,+ arguments,+ SupervisorToolRequest(+ trace_id=trace_id,+ origin="realtime",+ user_utterance=self._last_user_text,+ rationale="Realtime model requested an available Jarvis tool.",+ config_snapshot={+ "output_language": self._language,+ "voice_confirm": True,+ },+ ),+ )+ tool = self._tools[name]+ return await self._executor.execute(+ tool,+ arguments,+ user_utterance=self._last_user_text,+ config_snapshot={+ "output_language": self._language,+ "voice_confirm": True,+ },+ trace_id=trace_id,+ rationale="Realtime model requested an available Jarvis tool.",+ )++ async def _execute_confirmed(self, trace_id: UUID) -> Any:+ if self._gateway is not None:+ return await self._gateway.execute_confirmed(+ trace_id,+ SupervisorToolRequest(+ trace_id=trace_id,+ origin="realtime",+ user_utterance=self._last_user_text,+ config_snapshot={"output_language": self._language},+ ),+ )+ return await self._executor.execute_confirmed(+ trace_id,+ user_utterance=self._last_user_text,+ config_snapshot={"output_language": self._language},+ )++ async def _cancel_pending(self, trace_id: UUID) -> bool:+ if self._gateway is not None:+ return await self._gateway.cancel_pending(trace_id)+ return bool(await self._executor.cancel_pending(trace_id))++ def _validate_arguments(+ self,+ descriptor: SupervisorToolDescriptor,+ arguments: Any,+ ) -> str:if not isinstance(arguments, dict):return "Tool arguments must be a JSON object."try:@@ -268,25 +364,36 @@ class RealtimeToolBridge:return "Tool arguments are not JSON serializable."if size > _MAX_ARGUMENT_CHARS:return f"Tool arguments exceed the {_MAX_ARGUMENT_CHARS}-character limit."- schema = getattr(tool, "schema", None) or {}- required = schema.get("required", ()) if isinstance(schema, dict) else ()+ schema = descriptor.input_schema+ required = schema.get("required", ())missing = [key for key in required if key not in arguments]if missing:return f"Missing required tool arguments: {', '.join(map(str, missing))}."return ""- async def _guard(self, tool: Any, name: str, arguments: dict[str, Any]) -> str:+ async def _guard(+ self,+ descriptor: SupervisorToolDescriptor,+ name: str,+ arguments: dict[str, Any],+ ) -> str:user_text = self._last_user_textblocked, reason = _is_stt_hallucinated(name, arguments)if blocked:message = f"Suspected speech-recognition argument error: {reason}"- elif _is_instructional_question(user_text) and _is_side_effect_tool(tool):+ elif _is_instructional_question(user_text) and _is_side_effect_tool(descriptor):message = "The user asked for instructions; the side-effect tool was not run."- elif _is_self_identification(user_text) and _is_side_effect_tool(tool):+ elif _is_self_identification(user_text) and _is_side_effect_tool(descriptor):message = "The user was introducing themselves; the side-effect tool was not run."elif name == "spawn_worker" and _is_meta_debug_intent(user_text):message = "A meta/debug request must be answered directly, not delegated."- elif _should_block_action_as_research(tool, name, user_text, None, ""):+ elif _should_block_action_as_research(+ descriptor,+ name,+ user_text,+ None,+ "",+ ):message = "This sounds like research, not an action on a connected system."else:return ""@@ -294,7 +401,11 @@ class RealtimeToolBridge:return messageasync def _publish_denied(self, name: str, reason: str) -> None:- publisher = getattr(self._executor, "publish_guard_denied", None)+ publisher = getattr(+ self._gateway if self._gateway is not None else self._executor,+ "publish_guard_denied",+ None,+ )if callable(publisher):try:await publisher(name, reason, trace_id=uuid4())@@ -303,7 +414,7 @@ class RealtimeToolBridge:async def close(self) -> None:if self._pending is not None:- await self._executor.cancel_pending(self._pending.trace_id)+ await self._cancel_pending(self._pending.trace_id)self._pending = Nonediff --git a/jarvis/safety/tool_executor.py b/jarvis/safety/tool_executor.pyindex 3e97585e1a..2d44fb57e9 100644--- a/jarvis/safety/tool_executor.py+++ b/jarvis/safety/tool_executor.py@@ -18,8 +18,19 @@ from typing import TYPE_CHECKING, Anyfrom uuid import UUID, uuid4from jarvis.core.bus import EventBus-from jarvis.core.events import ActionDenied, ActionExecuted, ActionProposed-from jarvis.core.protocols import ExecutionContext, Tool, ToolResult, Transcript+from jarvis.core.events import (+ ActionApprovalRequired,+ ActionDenied,+ ActionExecuted,+ ActionProposed,+)+from jarvis.core.protocols import (+ CancelToken,+ ExecutionContext,+ Tool,+ ToolResult,+ Transcript,+)from jarvis.core.redact import safe_previewfrom .approval import ApprovalWorkflow@@ -50,6 +61,14 @@ VOICE_CONFIRM_SENTINEL = "__voice_confirm_required__"PlausibilityContextFn = Callable[[], "tuple[Transcript | None, float | None]"]+def _optional_string(value: Any) -> str | None:+ """Normalize optional correlation metadata without inventing identifiers."""+ if value is None:+ return None+ normalized = str(value).strip()+ return normalized or None++class ToolExecutor:"""Pipeline: evaluate → (plausibility) → (approve) → execute → log."""@@ -155,10 +174,18 @@ class ToolExecutor:memory_read: Any | None = None,trace_id: UUID | None = None,rationale: str = "",+ cancel_token: CancelToken | None = None,) -> ToolResult:tid = trace_id or uuid4()t_start = time.perf_counter()+ if cancel_token is not None and cancel_token.is_cancelled():+ return ToolResult(+ success=False,+ output=None,+ error=f"cancelled ({cancel_token.reason or 'requested'})",+ )+# 1. Evaluatetry:decision = self._evaluator.evaluate(tool, args)@@ -206,6 +233,30 @@ class ToolExecutor:approval_ticket.close()raise+ if approval_ticket is not None:+ reason = (+ "plausibility"+ if plaus is not None and plaus.require_confirmation+ else "risk_tier"+ )+ await self._bus.publish(+ ActionApprovalRequired(+ trace_id=tid,+ tool_name=tool.name,+ risk_tier=decision.tier,+ reason=reason,+ args_preview=safe_preview(args),+ expires_at_ns=time.time_ns()+ + int(self._default_timeout_s * 1_000_000_000),+ mission_id=_optional_string(+ (config_snapshot or {}).get("mission_id")+ ),+ worker_id=_optional_string(+ (config_snapshot or {}).get("worker_id")+ ),+ )+ )+if needs_confirm:# Two-turn confirmation on a conversational turn: do NOT block on the# UI-approval future (no voice/chat user can resolve it within the@@ -249,6 +300,18 @@ class ToolExecutor:)approved_by = who_or_reason # "user" or "auto"+ if cancel_token is not None and cancel_token.is_cancelled():+ await self._bus.publish(ActionDenied(+ trace_id=tid,+ tool_name=tool.name,+ reason=f"cancelled: {cancel_token.reason or 'requested'}",+ ))+ return ToolResult(+ success=False,+ output=None,+ error=f"cancelled ({cancel_token.reason or 'requested'})",+ )+# 4. Executectx = ExecutionContext(trace_id=tid,diff --git a/jarvis/tasks/approval_bridge.py b/jarvis/tasks/approval_bridge.pyindex 611e0e73c5..a003775bbf 100644--- a/jarvis/tasks/approval_bridge.py+++ b/jarvis/tasks/approval_bridge.py@@ -12,7 +12,7 @@ Design (Option B from the integration analysis):- The runner ``arm()``s the bridge with the turn's ``trace_id`` and theset of pre-authorized plugin ids before running the turn, then``disarm()``s in a finally.- - The bridge listens for ``ActionProposed``. On a match (same trace_id ++ - The bridge listens for ``ActionApprovalRequired``. On a match (same trace_id +the proposed tool belongs to a granted plugin) it publishes``ActionApproved`` straight onto the bus, which resolves the executor's``wait()``. The full audit trail (Proposed -> Approved -> Executed) is@@ -21,7 +21,7 @@ Design (Option B from the integration analysis):tools) is left to block and deny on timeout. Nothing is auto-approvedby default.-Concurrency-safe: a persistent ``ActionProposed`` subscriber plus a+Concurrency-safe: a persistent ``ActionApprovalRequired`` subscriber plus a``trace_id -> grant`` map, so several tasks can run at once without aper-turn subscribe/unsubscribe race."""@@ -31,7 +31,7 @@ from collections.abc import Iterablefrom uuid import UUIDfrom jarvis.core.bus import EventBus-from jarvis.core.events import ActionApproved, ActionProposed+from jarvis.core.events import ActionApprovalRequired, ActionApprovedclass TaskAutoApprover:@@ -41,7 +41,7 @@ class TaskAutoApprover:self._bus = bus# trace_id -> (granted plugin ids, audit label)self._active: dict[UUID, tuple[frozenset[str], str]] = {}- bus.subscribe(ActionProposed, self._on_proposed)+ bus.subscribe(ActionApprovalRequired, self._on_approval_required)def arm(self, trace_id: UUID, plugin_ids: Iterable[str], *, approved_by: str) -> None:"""Pre-authorize ``plugin_ids`` for the turn identified by ``trace_id``.@@ -55,7 +55,7 @@ class TaskAutoApprover:def disarm(self, trace_id: UUID) -> None:self._active.pop(trace_id, None)- async def _on_proposed(self, event: ActionProposed) -> None:+ async def _on_approval_required(self, event: ActionApprovalRequired) -> None:ctx = self._active.get(event.trace_id)if ctx is None:returndiff --git a/jarvis/ui/web/frontend/src/components/missions/ToolApprovalPanel.test.tsx b/jarvis/ui/web/frontend/src/components/missions/ToolApprovalPanel.test.tsxnew file mode 100644index 0000000000..99795b417c--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/missions/ToolApprovalPanel.test.tsx@@ -0,0 +1,189 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";++import {+ ToolApprovalPanel,+ useMissionToolApprovals,+} from "@/components/missions/ToolApprovalPanel";+import { useI18nStore } from "@/i18n";+import type { PendingMissionToolApproval } from "@/types/missions";++const MISSION_ID = "mission/one";++beforeEach(() => {+ useI18nStore.getState().setUi("en", { push: false });+});++afterEach(() => {+ cleanup();+ vi.restoreAllMocks();+ vi.unstubAllGlobals();+});++function pendingApproval(+ patch: Partial<PendingMissionToolApproval> = {},+): PendingMissionToolApproval {+ return {+ trace_id: "11111111-2222-4333-8444-555555555555",+ mission_id: MISSION_ID,+ worker_id: "worker-1",+ tool_name: "gmail/send_message",+ risk_tier: "ask",+ reason: "risk_tier",+ args_preview: "{'to': '[email protected]', 'api_key': '<redacted>'}",+ requested_at_ns: Date.now() * 1_000_000,+ expires_at_ns: (Date.now() + 30_000) * 1_000_000,+ ...patch,+ };+}++function jsonResponse(body: unknown, status = 200): Response {+ return {+ ok: status >= 200 && status < 300,+ status,+ json: async () => body,+ } as Response;+}++function Harness({ missionId = MISSION_ID }: { missionId?: string | null }) {+ const query = useMissionToolApprovals(missionId);+ return <ToolApprovalPanel missionId={missionId} query={query} />;+}++function renderPanel(missionId: string | null = MISSION_ID) {+ const client = new QueryClient({+ defaultOptions: {+ queries: { retry: false },+ mutations: { retry: false },+ },+ });+ return render(+ <QueryClientProvider client={client}>+ <Harness missionId={missionId} />+ </QueryClientProvider>,+ );+}++describe("ToolApprovalPanel", () => {+ it("requires a second explicit click before approving the paused call", async () => {+ const approval = pendingApproval();+ let active = true;+ const fetchMock = vi.fn(async (_input: RequestInfo | URL, init?: RequestInit) => {+ if (init?.method === "POST") {+ active = false;+ return jsonResponse({+ ok: true,+ mission_id: MISSION_ID,+ trace_id: approval.trace_id,+ decision: "approved",+ tool_name: approval.tool_name,+ });+ }+ return jsonResponse({+ mission_id: MISSION_ID,+ approvals: active ? [approval] : [],+ });+ });+ vi.stubGlobal("fetch", fetchMock);++ renderPanel();++ expect(await screen.findByText("gmail/send_message")).toBeTruthy();+ expect(screen.getByText("<redacted>", { exact: false })).toBeTruthy();+ fireEvent.click(screen.getByRole("button", { name: "Review approval" }));++ expect(fetchMock.mock.calls.filter((call) => call[1]?.method === "POST")).toHaveLength(0);+ expect(screen.getByRole("alert").textContent).toContain("Run this tool now?");++ fireEvent.click(screen.getByRole("button", { name: "Approve and run" }));++ await waitFor(() => {+ const postCalls = fetchMock.mock.calls.filter(+ (call) => call[1]?.method === "POST",+ );+ expect(postCalls).toHaveLength(1);+ expect(String(postCalls[0][0])).toBe(+ "/api/missions/mission%2Fone/tool-approvals/11111111-2222-4333-8444-555555555555/approve",+ );+ });+ });++ it("denies directly and sends an explicit denial reason", async () => {+ const approval = pendingApproval();+ let active = true;+ const fetchMock = vi.fn(async (_input: RequestInfo | URL, init?: RequestInit) => {+ if (init?.method === "POST") {+ active = false;+ return jsonResponse({+ ok: true,+ mission_id: MISSION_ID,+ trace_id: approval.trace_id,+ decision: "denied",+ tool_name: approval.tool_name,+ });+ }+ return jsonResponse({+ mission_id: MISSION_ID,+ approvals: active ? [approval] : [],+ });+ });+ vi.stubGlobal("fetch", fetchMock);++ renderPanel();+ fireEvent.click(await screen.findByRole("button", { name: "Deny" }));++ await waitFor(() => {+ const postCall = fetchMock.mock.calls.find(+ (call) => call[1]?.method === "POST",+ );+ expect(postCall).toBeTruthy();+ expect(String(postCall?.[0])).toContain("/deny");+ expect(JSON.parse(String(postCall?.[1]?.body))).toEqual({+ reason: "user_denied",+ });+ });+ });++ it("renders an expired request as non-decidable", async () => {+ vi.stubGlobal(+ "fetch",+ vi.fn(async () =>+ jsonResponse({+ mission_id: MISSION_ID,+ approvals: [+ pendingApproval({ expires_at_ns: (Date.now() - 1_000) * 1_000_000 }),+ ],+ }),+ ),+ );++ renderPanel();++ expect(await screen.findByText("Expired")).toBeTruthy();+ expect(screen.getByText(/can no longer be decided/i)).toBeTruthy();+ expect(screen.queryByRole("button", { name: "Review approval" })).toBeNull();+ expect(screen.queryByRole("button", { name: "Deny" })).toBeNull();+ });++ it("shows a recoverable server error and does not fetch without a mission", async () => {+ const fetchMock = vi.fn(async () =>+ jsonResponse({ detail: "Approval coordinator is warming up" }, 503),+ );+ vi.stubGlobal("fetch", fetchMock);++ const first = renderPanel();+ expect(await screen.findByText("Approvals could not be loaded.")).toBeTruthy();+ expect(screen.getByText("Approval coordinator is warming up")).toBeTruthy();+ fireEvent.click(screen.getByRole("button", { name: "Retry" }));+ await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(2));++ first.unmount();+ fetchMock.mockClear();+ renderPanel(null);+ expect(+ screen.getByText("Select a mission to review supervisor tool requests."),+ ).toBeTruthy();+ expect(fetchMock).not.toHaveBeenCalled();+ });+});diff --git a/jarvis/ui/web/frontend/src/components/missions/ToolApprovalPanel.tsx b/jarvis/ui/web/frontend/src/components/missions/ToolApprovalPanel.tsxnew file mode 100644index 0000000000..5e8d8683f1--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/missions/ToolApprovalPanel.tsx@@ -0,0 +1,425 @@+import { useEffect, useMemo, useState } from "react";+import {+ AlertTriangle,+ Check,+ CircleSlash,+ Clock3,+ Loader2,+ RefreshCw,+ ShieldAlert,+ X,+} from "lucide-react";+import {+ useMutation,+ useQuery,+ useQueryClient,+ type UseQueryResult,+} from "@tanstack/react-query";++import { Badge } from "@/components/ui/badge";+import { Button } from "@/components/ui/button";+import { ScrollArea } from "@/components/ui/scroll-area";+import { useT, useUiLanguage } from "@/i18n";+import { cn } from "@/lib/utils";+import type {+ MissionToolApprovalDecision,+ MissionToolApprovalsResponse,+ PendingMissionToolApproval,+} from "@/types/missions";+import {+ approveMissionToolCall,+ denyMissionToolCall,+ fetchMissionToolApprovals,+ missionToolApprovalsQueryKey,+} from "./api";++const APPROVAL_REFRESH_MS = 1_500;++type ApprovalQuery = UseQueryResult<MissionToolApprovalsResponse, Error>;++interface DecisionRequest {+ approval: PendingMissionToolApproval;+ decision: "approve" | "deny";+}++export function useMissionToolApprovals(+ missionId: string | null,+): ApprovalQuery {+ return useQuery({+ queryKey: missionToolApprovalsQueryKey(missionId),+ queryFn: () => fetchMissionToolApprovals(missionId as string),+ enabled: missionId !== null,+ refetchInterval: missionId === null ? false : APPROVAL_REFRESH_MS,+ });+}++export function ToolApprovalPanel({+ missionId,+ query,+}: {+ missionId: string | null;+ query: ApprovalQuery;+}) {+ const t = useT();+ const language = useUiLanguage();+ const queryClient = useQueryClient();+ const approvals = query.data?.approvals ?? [];+ const [confirmingTraceId, setConfirmingTraceId] = useState<string | null>(+ null,+ );+ const [nowMs, setNowMs] = useState(() => Date.now());+ const relativeTime = useMemo(+ () => new Intl.RelativeTimeFormat(language, { numeric: "always" }),+ [language],+ );++ useEffect(() => {+ if (approvals.length === 0) return;+ setNowMs(Date.now());+ const intervalId = window.setInterval(() => setNowMs(Date.now()), 1_000);+ return () => window.clearInterval(intervalId);+ }, [approvals.length]);++ useEffect(() => {+ if (+ confirmingTraceId !== null &&+ !approvals.some((approval) => approval.trace_id === confirmingTraceId)+ ) {+ setConfirmingTraceId(null);+ }+ }, [approvals, confirmingTraceId]);++ useEffect(() => setConfirmingTraceId(null), [missionId]);++ const decision = useMutation<+ MissionToolApprovalDecision,+ Error,+ DecisionRequest+ >({+ mutationFn: ({ approval, decision: requestedDecision }) =>+ requestedDecision === "approve"+ ? approveMissionToolCall(approval.mission_id, approval.trace_id)+ : denyMissionToolCall(approval.mission_id, approval.trace_id),+ onSuccess: (_result, request) => {+ const key = missionToolApprovalsQueryKey(request.approval.mission_id);+ queryClient.setQueryData<MissionToolApprovalsResponse>(key, (current) =>+ current+ ? {+ ...current,+ approvals: current.approvals.filter(+ (item) => item.trace_id !== request.approval.trace_id,+ ),+ }+ : current,+ );+ setConfirmingTraceId(null);+ },+ onSettled: (_result, _error, request) => {+ void queryClient.invalidateQueries({+ queryKey: missionToolApprovalsQueryKey(+ request?.approval.mission_id ?? missionId,+ ),+ });+ },+ });++ if (missionId === null) {+ return (+ <PanelMessage+ icon={ShieldAlert}+ text={t("mission_tool_approvals.select_mission")}+ />+ );+ }++ if (query.isLoading) {+ return (+ <PanelMessage+ icon={Loader2}+ iconClassName="animate-spin"+ text={t("mission_tool_approvals.loading")}+ />+ );+ }++ if (query.isError) {+ return (+ <div className="flex h-full flex-col items-center justify-center gap-3 px-4 text-center">+ <AlertTriangle className="h-7 w-7 text-destructive" />+ <div>+ <p className="text-xs font-medium text-foreground">+ {t("mission_tool_approvals.load_error")}+ </p>+ <p className="mt-1 break-words text-[11px] text-muted-foreground">+ {query.error.message}+ </p>+ </div>+ <Button variant="outline" size="sm" onClick={() => void query.refetch()}>+ <RefreshCw className="mr-1.5 h-3.5 w-3.5" />+ {t("mission_tool_approvals.retry")}+ </Button>+ </div>+ );+ }++ if (approvals.length === 0) {+ return (+ <div className="flex h-full flex-col items-center justify-center gap-2 px-4 text-center">+ <CircleSlash className="h-7 w-7 text-muted-foreground/40" />+ <p className="text-xs font-medium text-foreground/80">+ {t("mission_tool_approvals.empty_title")}+ </p>+ <p className="max-w-56 text-[11px] text-muted-foreground">+ {t("mission_tool_approvals.empty_body")}+ </p>+ </div>+ );+ }++ return (+ <ScrollArea className="h-full">+ <div className="space-y-3 p-3">+ <div className="rounded-md border border-amber-400/30 bg-amber-400/10 p-2.5 text-[11px] text-amber-100/90">+ {t("mission_tool_approvals.scope_notice")}+ </div>++ {approvals.map((approval) => {+ const expiresAtMs = approval.expires_at_ns / 1_000_000;+ const remainingSeconds = Math.ceil((expiresAtMs - nowMs) / 1_000);+ const expired = remainingSeconds <= 0;+ const isConfirming = confirmingTraceId === approval.trace_id;+ const isThisDecision =+ decision.isPending &&+ decision.variables?.approval.trace_id === approval.trace_id;+ const decisionError =+ decision.isError &&+ decision.variables?.approval.trace_id === approval.trace_id+ ? decision.error.message+ : null;++ return (+ <article+ key={approval.trace_id}+ className={cn(+ "rounded-lg border bg-card/50 p-3 shadow-sm",+ expired+ ? "border-border/60 opacity-70"+ : "border-amber-400/40",+ )}+ >+ <div className="flex items-start justify-between gap-2">+ <div className="min-w-0">+ <div className="flex items-center gap-1.5 text-[10px] font-semibold uppercase tracking-wider text-amber-300">+ <ShieldAlert className="h-3.5 w-3.5 shrink-0" />+ {t("mission_tool_approvals.pending_title")}+ </div>+ <h3 className="mt-1 break-all font-mono text-xs font-semibold text-foreground">+ {approval.tool_name}+ </h3>+ </div>+ <Badge+ variant="outline"+ className={cn(+ "shrink-0 font-mono text-[9px] uppercase",+ riskClassName(approval.risk_tier),+ )}+ >+ {t("mission_tool_approvals.risk")}: {approval.risk_tier}+ </Badge>+ </div>++ <dl className="mt-3 space-y-2 text-[11px]">+ <DetailRow+ label={t("mission_tool_approvals.reason")}+ value={formatReason(approval.reason, t)}+ />+ {approval.worker_id ? (+ <DetailRow+ label={t("mission_tool_approvals.worker")}+ value={approval.worker_id}+ mono+ />+ ) : null}+ <div>+ <dt className="text-[9px] font-medium uppercase tracking-wider text-muted-foreground">+ {t("mission_tool_approvals.arguments")}+ </dt>+ <dd className="mt-1 max-h-28 overflow-auto whitespace-pre-wrap break-all rounded border border-border/60 bg-background/60 p-2 font-mono text-[10px] text-foreground/80">+ {approval.args_preview || t("mission_tool_approvals.no_arguments")}+ </dd>+ </div>+ <div className="flex items-center justify-between gap-2">+ <dt className="flex items-center gap-1 text-[9px] font-medium uppercase tracking-wider text-muted-foreground">+ <Clock3 className="h-3 w-3" />+ {t("mission_tool_approvals.expires")}+ </dt>+ <dd+ className={cn(+ "text-right font-mono text-[10px]",+ expired ? "text-destructive" : "text-amber-300",+ )}+ title={new Date(expiresAtMs).toLocaleString(language)}+ >+ {expired+ ? t("mission_tool_approvals.expired")+ : relativeTime.format(remainingSeconds, "second")}+ </dd>+ </div>+ </dl>++ {decisionError ? (+ <p+ role="alert"+ className="mt-3 rounded border border-destructive/40 bg-destructive/10 p-2 text-[10px] text-destructive"+ >+ {t("mission_tool_approvals.decision_failed")}: {decisionError}+ </p>+ ) : null}++ {expired ? (+ <p className="mt-3 text-[10px] text-muted-foreground">+ {t("mission_tool_approvals.expired_body")}+ </p>+ ) : isConfirming ? (+ <div+ role="alert"+ className="mt-3 rounded-md border border-destructive/50 bg-destructive/10 p-2.5"+ >+ <p className="text-xs font-semibold text-destructive">+ {t("mission_tool_approvals.confirm_title")}+ </p>+ <p className="mt-1 text-[10px] text-foreground/80">+ {t("mission_tool_approvals.confirm_body")}+ </p>+ <div className="mt-2 flex justify-end gap-2">+ <Button+ variant="ghost"+ size="sm"+ onClick={() => setConfirmingTraceId(null)}+ disabled={decision.isPending}+ >+ {t("common.cancel")}+ </Button>+ <Button+ variant="destructive"+ size="sm"+ onClick={() =>+ decision.mutate({ approval, decision: "approve" })+ }+ disabled={decision.isPending}+ >+ {isThisDecision ? (+ <Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" />+ ) : (+ <Check className="mr-1.5 h-3.5 w-3.5" />+ )}+ {isThisDecision+ ? t("mission_tool_approvals.approving")+ : t("mission_tool_approvals.confirm")}+ </Button>+ </div>+ </div>+ ) : (+ <div className="mt-3 grid grid-cols-2 gap-2">+ <Button+ variant="outline"+ size="sm"+ onClick={() =>+ decision.mutate({ approval, decision: "deny" })+ }+ disabled={decision.isPending}+ >+ {isThisDecision ? (+ <Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" />+ ) : (+ <X className="mr-1.5 h-3.5 w-3.5" />+ )}+ {isThisDecision+ ? t("mission_tool_approvals.denying")+ : t("mission_tool_approvals.deny")}+ </Button>+ <Button+ variant="outline"+ size="sm"+ className="border-amber-400/50 bg-amber-400/10 text-amber-200 hover:bg-amber-400/20 hover:text-amber-100"+ onClick={() => setConfirmingTraceId(approval.trace_id)}+ disabled={decision.isPending}+ >+ <ShieldAlert className="mr-1.5 h-3.5 w-3.5" />+ {t("mission_tool_approvals.approve")}+ </Button>+ </div>+ )}+ </article>+ );+ })}+ </div>+ </ScrollArea>+ );+}++function PanelMessage({+ icon: Icon,+ iconClassName,+ text,+}: {+ icon: typeof ShieldAlert;+ iconClassName?: string;+ text: string;+}) {+ return (+ <div className="flex h-full flex-col items-center justify-center gap-2 px-4 text-center text-xs text-muted-foreground">+ <Icon className={cn("h-7 w-7 text-muted-foreground/40", iconClassName)} />+ <p>{text}</p>+ </div>+ );+}++function DetailRow({+ label,+ value,+ mono = false,+}: {+ label: string;+ value: string;+ mono?: boolean;+}) {+ return (+ <div className="flex items-start justify-between gap-3">+ <dt className="shrink-0 text-[9px] font-medium uppercase tracking-wider text-muted-foreground">+ {label}+ </dt>+ <dd+ className={cn(+ "min-w-0 break-words text-right text-foreground/80",+ mono && "break-all font-mono text-[10px]",+ )}+ >+ {value}+ </dd>+ </div>+ );+}++function riskClassName(riskTier: string): string {+ switch (riskTier) {+ case "block":+ return "border-destructive/60 bg-destructive/10 text-destructive";+ case "ask":+ return "border-amber-400/50 bg-amber-400/10 text-amber-300";+ case "monitor":+ return "border-sky-400/50 bg-sky-400/10 text-sky-300";+ default:+ return "border-emerald-400/50 bg-emerald-400/10 text-emerald-300";+ }+}++function formatReason(reason: string, t: (key: string) => string): string {+ if (reason === "risk_tier") {+ return t("mission_tool_approvals.reason_risk_tier");+ }+ if (reason === "plausibility") {+ return t("mission_tool_approvals.reason_plausibility");+ }+ return reason || t("mission_tool_approvals.reason_unspecified");+}diff --git a/jarvis/ui/web/frontend/src/components/missions/api.ts b/jarvis/ui/web/frontend/src/components/missions/api.tsindex 7436183328..ba0209c20e 100644--- a/jarvis/ui/web/frontend/src/components/missions/api.ts+++ b/jarvis/ui/web/frontend/src/components/missions/api.ts@@ -8,6 +8,8 @@ import type {EventEnvelope,MissionDetail,MissionSummary,+ MissionToolApprovalDecision,+ MissionToolApprovalsResponse,OpenClawWorkerSnapshot,} from "@/types/missions";@@ -44,6 +46,43 @@ export async function fetchMissionDetail(id: string): Promise<MissionDetail> {return { mission: data.mission, events, verdicts, worker_snapshots };}+export function missionToolApprovalsQueryKey(missionId: string | null) {+ return ["missions", "tool-approvals", missionId] as const;+}++export async function fetchMissionToolApprovals(+ missionId: string,+): Promise<MissionToolApprovalsResponse> {+ return requestJson(+ `${API_BASE}/${encodeURIComponent(missionId)}/tool-approvals`,+ );+}++export async function approveMissionToolCall(+ missionId: string,+ traceId: string,+): Promise<MissionToolApprovalDecision> {+ return requestJson(+ `${API_BASE}/${encodeURIComponent(missionId)}/tool-approvals/${encodeURIComponent(traceId)}/approve`,+ { method: "POST" },+ );+}++export async function denyMissionToolCall(+ missionId: string,+ traceId: string,+ reason = "user_denied",+): Promise<MissionToolApprovalDecision> {+ return requestJson(+ `${API_BASE}/${encodeURIComponent(missionId)}/tool-approvals/${encodeURIComponent(traceId)}/deny`,+ {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ reason }),+ },+ );+}+export async function cancelMission(id: string): Promise<void> {const res = await fetch(`${API_BASE}/${encodeURIComponent(id)}/cancel`, {method: "POST",@@ -66,3 +105,19 @@ export async function fetchAuthToken(): Promise<string | null> {return null;}}++async function requestJson<T>(url: string, init?: RequestInit): Promise<T> {+ const res = await fetch(url, init);+ const body = (await res.json().catch(() => null)) as+ | { detail?: unknown }+ | T+ | null;+ if (!res.ok) {+ const detail =+ body && typeof body === "object" && "detail" in body+ ? body.detail+ : null;+ throw new Error(typeof detail === "string" ? detail : `HTTP ${res.status}`);+ }+ return body as T;+}diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.jsonindex 3dbf2fdcb9..2c235c6162 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json@@ -2282,6 +2282,37 @@"no_critic_verdicts": "Noch keine Critic-Verdicts für diese Mission.","no_missions_yet": "Noch keine Missions. Hauptjarvis dispatched gleich…"},+ "mission_tool_approvals": {+ "tab_label": "Freigaben",+ "pending": "ausstehend",+ "select_mission": "Wähle eine Mission aus, um Tool-Anfragen des Supervisors zu prüfen.",+ "loading": "Freigaben werden geladen…",+ "load_error": "Freigaben konnten nicht geladen werden.",+ "retry": "Erneut versuchen",+ "empty_title": "Keine Aktion wartet",+ "empty_body": "Für diese Mission wartet kein Tool-Aufruf des Supervisors auf deine Entscheidung.",+ "scope_notice": "Jede Freigabe gilt nur für genau diesen pausierten Aufruf. Künftige Aufrufe werden separat geprüft.",+ "pending_title": "Aktion benötigt Freigabe",+ "risk": "Risiko",+ "reason": "Grund",+ "worker": "Worker",+ "arguments": "Argumente",+ "no_arguments": "(Keine Argumentvorschau)",+ "expires": "Läuft ab",+ "expired": "Abgelaufen",+ "expired_body": "Diese Anfrage kann nicht mehr entschieden werden. Die Liste wird automatisch aktualisiert.",+ "reason_risk_tier": "Die Tool-Richtlinie verlangt eine Bestätigung.",+ "reason_plausibility": "Die Aktion passte nicht mit ausreichender Sicherheit zur Anfrage.",+ "reason_unspecified": "Bestätigung erforderlich.",+ "decision_failed": "Entscheidung fehlgeschlagen",+ "deny": "Ablehnen",+ "denying": "Wird abgelehnt…",+ "approve": "Freigabe prüfen",+ "confirm_title": "Dieses Tool jetzt ausführen?",+ "confirm_body": "Damit wird genau eine Ausführung mit den oben angezeigten Argumenten autorisiert.",+ "confirm": "Freigeben und ausführen",+ "approving": "Wird freigegeben…"+ },"skill_finder_dialog": {"install_failed": "Installation fehlgeschlagen","title": "Skill-Finder",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.jsonindex 88c4e0d50d..55b56e1ded 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json@@ -2283,6 +2283,37 @@"no_critic_verdicts": "No critic verdicts for this mission yet.","no_missions_yet": "No missions yet. Main Jarvis will dispatch one shortly…"},+ "mission_tool_approvals": {+ "tab_label": "Approvals",+ "pending": "pending",+ "select_mission": "Select a mission to review supervisor tool requests.",+ "loading": "Loading approvals…",+ "load_error": "Approvals could not be loaded.",+ "retry": "Retry",+ "empty_title": "No action waiting",+ "empty_body": "This mission has no supervisor tool call awaiting your decision.",+ "scope_notice": "Each approval applies only to this exact paused call. Future calls are reviewed separately.",+ "pending_title": "Action needs approval",+ "risk": "Risk",+ "reason": "Reason",+ "worker": "Worker",+ "arguments": "Arguments",+ "no_arguments": "(No argument preview)",+ "expires": "Expires",+ "expired": "Expired",+ "expired_body": "This request can no longer be decided. The list will refresh automatically.",+ "reason_risk_tier": "Tool risk policy requires confirmation.",+ "reason_plausibility": "The action did not match the request with enough confidence.",+ "reason_unspecified": "Confirmation required.",+ "decision_failed": "Decision failed",+ "deny": "Deny",+ "denying": "Denying…",+ "approve": "Review approval",+ "confirm_title": "Run this tool now?",+ "confirm_body": "This authorizes exactly one execution with the arguments shown above.",+ "confirm": "Approve and run",+ "approving": "Approving…"+ },"skill_finder_dialog": {"install_failed": "Installation failed","title": "Skill Finder",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.jsonindex 4121502440..dc86e8d409 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json@@ -2282,6 +2282,37 @@"no_critic_verdicts": "Aún no hay veredictos del crítico para esta misión.","no_missions_yet": "Aún no hay misiones. Jarvis principal enviará una en breve…"},+ "mission_tool_approvals": {+ "tab_label": "Aprobaciones",+ "pending": "pendientes",+ "select_mission": "Selecciona una misión para revisar las solicitudes de herramientas del supervisor.",+ "loading": "Cargando aprobaciones…",+ "load_error": "No se pudieron cargar las aprobaciones.",+ "retry": "Reintentar",+ "empty_title": "No hay acciones en espera",+ "empty_body": "Esta misión no tiene ninguna llamada de herramienta del supervisor esperando tu decisión.",+ "scope_notice": "Cada aprobación se aplica solo a esta llamada pausada. Las llamadas futuras se revisan por separado.",+ "pending_title": "La acción necesita aprobación",+ "risk": "Riesgo",+ "reason": "Motivo",+ "worker": "Worker",+ "arguments": "Argumentos",+ "no_arguments": "(Sin vista previa de argumentos)",+ "expires": "Caduca",+ "expired": "Caducada",+ "expired_body": "Esta solicitud ya no se puede decidir. La lista se actualizará automáticamente.",+ "reason_risk_tier": "La política de riesgo de la herramienta exige confirmación.",+ "reason_plausibility": "La acción no coincidió con la solicitud con suficiente confianza.",+ "reason_unspecified": "Se requiere confirmación.",+ "decision_failed": "La decisión falló",+ "deny": "Denegar",+ "denying": "Denegando…",+ "approve": "Revisar aprobación",+ "confirm_title": "¿Ejecutar esta herramienta ahora?",+ "confirm_body": "Esto autoriza exactamente una ejecución con los argumentos mostrados arriba.",+ "confirm": "Aprobar y ejecutar",+ "approving": "Aprobando…"+ },"skill_finder_dialog": {"install_failed": "La instalación falló","title": "Buscador de habilidades",diff --git a/jarvis/ui/web/frontend/src/types/missions.ts b/jarvis/ui/web/frontend/src/types/missions.tsindex c576fa2118..590d69b744 100644--- a/jarvis/ui/web/frontend/src/types/missions.ts+++ b/jarvis/ui/web/frontend/src/types/missions.ts@@ -264,6 +264,32 @@ export interface MissionDetail {worker_snapshots: OpenClawWorkerSnapshot[];}+/** Secret-free projection of one paused supervisor tool call. */+export interface PendingMissionToolApproval {+ trace_id: string;+ mission_id: string;+ worker_id: string | null;+ tool_name: string;+ risk_tier: "safe" | "monitor" | "ask" | "block";+ reason: string;+ args_preview: string;+ requested_at_ns: number;+ expires_at_ns: number;+}++export interface MissionToolApprovalsResponse {+ mission_id: string;+ approvals: PendingMissionToolApproval[];+}++export interface MissionToolApprovalDecision {+ ok: boolean;+ mission_id: string;+ trace_id: string;+ decision: "approved" | "denied";+ tool_name: string;+}+export interface MissionStateBadgeMeta {/*** i18n key for the human-readable badge label. The label is resolved atdiff --git a/jarvis/ui/web/frontend/src/views/MissionsView.tsx b/jarvis/ui/web/frontend/src/views/MissionsView.tsxindex 0605c05d7d..c99cdf7d4d 100644--- a/jarvis/ui/web/frontend/src/views/MissionsView.tsx+++ b/jarvis/ui/web/frontend/src/views/MissionsView.tsx@@ -20,6 +20,7 @@ import {ListChecks,Map as MapIcon,MessageSquareText,+ ShieldAlert,Target,Wifi,WifiOff,@@ -40,6 +41,10 @@ import { EventTimeline } from "@/components/missions/EventTimeline";import { GlobalKillButton } from "@/components/missions/GlobalKillButton";import { MissionTree } from "@/components/missions/MissionTree";import { JarvisAgentPanel } from "@/components/missions/JarvisAgentPanel";+import {+ ToolApprovalPanel,+ useMissionToolApprovals,+} from "@/components/missions/ToolApprovalPanel";import { VerdictPanel } from "@/components/missions/VerdictPanel";import {selectActiveCount,@@ -66,6 +71,11 @@ export function MissionsView() {const connected = useMissionsStore((s) => s.connected);const totalCount = useMissionsStore(useShallow((s) => Object.keys(s.missions).length));const activeCount = useMissionsStore(useShallow(selectActiveCount));+ const toolApprovalsQuery = useMissionToolApprovals(selectedMissionId);+ const pendingApprovalCount =+ toolApprovalsQuery.data?.approvals.filter(+ (approval) => approval.expires_at_ns / 1_000_000 > Date.now(),+ ).length ?? 0;const listQuery = useQuery({queryKey: ["missions"],@@ -119,7 +129,7 @@ export function MissionsView() {/><div className="grid flex-1 grid-cols-[280px_1fr_320px] overflow-hidden">- {/* Linke Pane */}+ {/* Left pane */}<div className="flex h-full flex-col overflow-hidden border-r border-border bg-card/20"><div className="border-b border-border px-3 py-2 text-[10px] uppercase tracking-wider text-muted-foreground">{t("missions_view.tree_label")}@@ -129,7 +139,7 @@ export function MissionsView() {</div></div>- {/* Mittlere Pane */}+ {/* Center pane */}<div className="grid h-full grid-rows-[1fr_240px] overflow-hidden"><div className="overflow-hidden border-b border-border bg-background/20 p-3">{selectedWorkerId ? (@@ -153,7 +163,7 @@ export function MissionsView() {</div></div>- {/* Rechte Pane */}+ {/* Right pane */}<div className="flex h-full flex-col overflow-hidden border-l border-border bg-card/20"><Tabs defaultValue="verdicts" className="flex h-full flex-col"><div className="border-b border-border px-2 py-2">@@ -174,6 +184,23 @@ export function MissionsView() {<Cpu className="h-3.5 w-3.5" />Jarvis-Agent</TabsTrigger>+ <TabsTrigger+ value="approvals"+ className="relative gap-1.5"+ aria-label={+ pendingApprovalCount > 0+ ? `${t("mission_tool_approvals.tab_label")}: ${pendingApprovalCount} ${t("mission_tool_approvals.pending")}`+ : t("mission_tool_approvals.tab_label")+ }+ >+ <ShieldAlert className="h-3.5 w-3.5" />+ {t("mission_tool_approvals.tab_label")}+ {pendingApprovalCount > 0 ? (+ <span className="absolute -right-1 -top-1 flex min-h-4 min-w-4 items-center justify-center rounded-full bg-destructive px-1 font-mono text-[9px] leading-none text-destructive-foreground">+ {pendingApprovalCount}+ </span>+ ) : null}+ </TabsTrigger></TabsList></div><TabsContent value="verdicts" className="m-0 flex-1 overflow-hidden">@@ -188,6 +215,12 @@ export function MissionsView() {<TabsContent value="openclaw" className="m-0 flex-1 overflow-hidden"><JarvisAgentPanel /></TabsContent>+ <TabsContent value="approvals" className="m-0 flex-1 overflow-hidden">+ <ToolApprovalPanel+ missionId={selectedMissionId}+ query={toolApprovalsQuery}+ />+ </TabsContent></Tabs></div></div>diff --git a/jarvis/ui/web/missions_routes.py b/jarvis/ui/web/missions_routes.pyindex de3ac5ad84..f15d898c44 100644--- a/jarvis/ui/web/missions_routes.py+++ b/jarvis/ui/web/missions_routes.py@@ -18,6 +18,7 @@ from __future__ import annotationsimport loggingfrom typing import Any, Literal+from uuid import UUIDfrom fastapi import APIRouter, BackgroundTasks, HTTPException, Requestfrom pydantic import BaseModel@@ -29,6 +30,7 @@ from jarvis.missions.state_machine import (MissionState,is_terminal,)+from jarvis.missions.tool_approvals import MissionToolApprovalCoordinatorfrom jarvis.ui.web.missions_worker import extract_worker_missionslogger = logging.getLogger(__name__)@@ -61,6 +63,16 @@ def _optional_kontrollierer(request: Request) -> Any | None:return getattr(request.app.state, "kontrollierer", None)+def _require_tool_approvals(request: Request) -> MissionToolApprovalCoordinator:+ coordinator = getattr(request.app.state, "mission_tool_approvals", None)+ if coordinator is None:+ raise HTTPException(+ status_code=503,+ detail="Mission tool approvals are not available",+ )+ return coordinator++# ---------------------------------------------------------------------------# Body-Models# ---------------------------------------------------------------------------@@ -84,6 +96,12 @@ class RerunBody(BaseModel):confirmed: bool = False+class DenyToolApprovalBody(BaseModel):+ """Optional audit reason for denying one paused supervisor tool call."""++ reason: str = "user_denied"++# ---------------------------------------------------------------------------# Listing + Detail# ---------------------------------------------------------------------------@@ -211,6 +229,79 @@ async def get_mission(mission_id: str, request: Request) -> dict[str, Any]:}[email protected]("/{mission_id}/tool-approvals")+async def list_mission_tool_approvals(+ mission_id: str,+ request: Request,+) -> dict[str, Any]:+ """List secret-free supervisor tool calls awaiting a user decision."""+ mgr = _require_manager(request)+ if await mgr.mission(mission_id) is None:+ raise HTTPException(status_code=404, detail="Mission not found")+ pending = await _require_tool_approvals(request).list_pending(mission_id)+ return {+ "mission_id": mission_id,+ "approvals": [item.to_dict() for item in pending],+ }+++ "/{mission_id}/tool-approvals/{trace_id}/approve",+ openapi_extra={"x-jarvis-dangerous": True},+)+async def approve_mission_tool_call(+ mission_id: str,+ trace_id: UUID,+ request: Request,+) -> dict[str, Any]:+ """Approve and resume exactly one paused mission tool call."""+ pending = await _require_tool_approvals(request).approve(+ mission_id,+ trace_id,+ approved_by="user",+ )+ if pending is None:+ raise HTTPException(+ status_code=404,+ detail="Pending mission tool approval not found or expired",+ )+ return {+ "ok": True,+ "mission_id": mission_id,+ "trace_id": str(trace_id),+ "decision": "approved",+ "tool_name": pending.tool_name,+ }++[email protected]("/{mission_id}/tool-approvals/{trace_id}/deny")+async def deny_mission_tool_call(+ mission_id: str,+ trace_id: UUID,+ body: DenyToolApprovalBody,+ request: Request,+) -> dict[str, Any]:+ """Deny exactly one paused mission tool call without running it."""+ reason = body.reason.strip() or "user_denied"+ pending = await _require_tool_approvals(request).deny(+ mission_id,+ trace_id,+ reason=reason[:200],+ )+ if pending is None:+ raise HTTPException(+ status_code=404,+ detail="Pending mission tool approval not found or expired",+ )+ return {+ "ok": True,+ "mission_id": mission_id,+ "trace_id": str(trace_id),+ "decision": "denied",+ "tool_name": pending.tool_name,+ }++# ---------------------------------------------------------------------------# Dispatch + Cancel + Kill# ---------------------------------------------------------------------------@@ -234,6 +325,7 @@ async def dispatch_mission(and re-POSTs with ``confirmed: true``."""from fastapi.responses import JSONResponse+from jarvis.missions.safety.destructive_confirm import is_destructive# Phase-5 destructive_confirm gate (UI path; the voice path isn't active yet)diff --git a/jarvis/ui/web/server.py b/jarvis/ui/web/server.pyindex 90829cf1a2..7a02fab1ea 100644--- a/jarvis/ui/web/server.py+++ b/jarvis/ui/web/server.py@@ -122,6 +122,9 @@ 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++ self._mission_tool_approvals = MissionToolApprovalCoordinator(self.bus)self.app: FastAPI = self._build_app()async def _forward_preamble_to_chat(self, event: AnnouncementRequested) -> None:@@ -396,6 +399,7 @@ class WebServer:# so the REST routes return 503 instead of crashing.app.state.mission_manager = Noneapp.state.kontrollierer = None+ app.state.mission_tool_approvals = self._mission_tool_approvals# Board aggregator (personal-mastery dashboard) — the aggregator is# run as a background task in start(); the store is read-only and@@ -2729,6 +2733,13 @@ class WebServer:"In-flight mission finalize on shutdown failed")+ try:+ await self._mission_tool_approvals.deny_all(reason="app_shutdown")+ except Exception as exc: # noqa: BLE001 - shutdown remains best-effort+ logger.opt(exception=exc).warning(+ "Pending mission tool approval cleanup failed"+ )+mission_manager = getattr(self.app.state, "mission_manager", None)if mission_manager is not None:try:diff --git a/tests/integration/test_task_auto_approver.py b/tests/integration/test_task_auto_approver.pyindex 6165cdfae6..1c399fe599 100644--- a/tests/integration/test_task_auto_approver.py+++ b/tests/integration/test_task_auto_approver.py@@ -18,7 +18,7 @@ import pytestfrom jarvis.core.bus import EventBusfrom jarvis.core.config import SafetyConfig-from jarvis.core.events import ActionApproved, ActionProposed+from jarvis.core.events import ActionApprovalRequired, ActionApproved, ActionProposedfrom jarvis.core.protocols import ExecutionContext, ToolResultfrom jarvis.safety import ApprovalWorkflow, RiskTierEvaluator, ToolExecutorfrom jarvis.tasks.approval_bridge import TaskAutoApprover@@ -61,7 +61,9 @@ async def test_approves_armed_tool_on_its_trace() -> None:tid = uuid4()approver.arm(tid, ["buffer"], approved_by="scheduled-task:abc")- await bus.publish(ActionProposed(trace_id=tid, tool_name="buffer", risk_tier="ask"))+ await bus.publish(+ ActionApprovalRequired(trace_id=tid, tool_name="buffer", risk_tier="ask")+ )await asyncio.sleep(0)assert len(approvals) == 1@@ -71,7 +73,7 @@ async def test_approves_armed_tool_on_its_trace() -> None:async def test_pre_authorized_tool_executes_without_approval_race() -> None:- """An approval published from ActionProposed must reach ToolExecutor.wait."""+ """An approval published from the explicit request must reach the waiter."""bus = EventBus()approval = ApprovalWorkflow(bus, timeout_s=0.05)executor = ToolExecutor(@@ -100,7 +102,25 @@ async def test_ignores_tool_not_in_grant() -> None:tid = uuid4()approver.arm(tid, ["buffer"], approved_by="scheduled-task:abc")- await bus.publish(ActionProposed(trace_id=tid, tool_name="gmail", risk_tier="ask"))+ await bus.publish(+ ActionApprovalRequired(trace_id=tid, tool_name="gmail", risk_tier="ask")+ )+ await asyncio.sleep(0)++ assert approvals == []+++async def test_proposal_alone_never_consumes_pre_authorization() -> None:+ """Only an armed, explicit approval request may trigger approval."""+ bus = EventBus()+ approver = TaskAutoApprover(bus)+ approvals = await _collect_approvals(bus)+ tid = uuid4()+ approver.arm(tid, ["buffer"], approved_by="scheduled-task:abc")++ await bus.publish(+ ActionProposed(trace_id=tid, tool_name="buffer", risk_tier="ask")+ )await asyncio.sleep(0)assert approvals == []@@ -112,7 +132,11 @@ async def test_ignores_other_trace_id() -> None:approvals = await _collect_approvals(bus)approver.arm(uuid4(), ["buffer"], approved_by="scheduled-task:abc")- await bus.publish(ActionProposed(trace_id=uuid4(), tool_name="buffer", risk_tier="ask"))+ await bus.publish(+ ActionApprovalRequired(+ trace_id=uuid4(), tool_name="buffer", risk_tier="ask"+ )+ )await asyncio.sleep(0)assert approvals == []@@ -126,7 +150,9 @@ async def test_disarm_stops_approval() -> None:approver.arm(tid, ["buffer"], approved_by="scheduled-task:abc")approver.disarm(tid)- await bus.publish(ActionProposed(trace_id=tid, tool_name="buffer", risk_tier="ask"))+ await bus.publish(+ ActionApprovalRequired(trace_id=tid, tool_name="buffer", risk_tier="ask")+ )await asyncio.sleep(0)assert approvals == []@@ -141,7 +167,9 @@ async def test_matches_mcp_namespaced_tool() -> None:approver.arm(tid, ["gmail"], approved_by="scheduled-task:abc")await bus.publish(- ActionProposed(trace_id=tid, tool_name="gmail/send_message", risk_tier="ask")+ ActionApprovalRequired(+ trace_id=tid, tool_name="gmail/send_message", risk_tier="ask"+ ))await asyncio.sleep(0)@@ -157,7 +185,9 @@ async def test_arm_with_no_tools_is_inert() -> None:tid = uuid4()approver.arm(tid, [], approved_by="scheduled-task:abc")- await bus.publish(ActionProposed(trace_id=tid, tool_name="gmail", risk_tier="ask"))+ await bus.publish(+ ActionApprovalRequired(trace_id=tid, tool_name="gmail", risk_tier="ask")+ )await asyncio.sleep(0)assert approvals == []diff --git a/tests/integration/test_tasks_recurring.py b/tests/integration/test_tasks_recurring.pyindex 0e1faae4ea..399538d620 100644--- a/tests/integration/test_tasks_recurring.py+++ b/tests/integration/test_tasks_recurring.py@@ -225,7 +225,7 @@ async def test_runner_agent_delivers_result_as_announcement(store: TaskStore):async def test_runner_arms_auto_approver_for_write_grants(store: TaskStore):"""A write-scoped grant lets an ask-tier tool run unattended."""- from jarvis.core.events import ActionApproved, ActionProposed+ from jarvis.core.events import ActionApprovalRequired, ActionApprovedfrom jarvis.tasks.approval_bridge import TaskAutoApproverbus = EventBus()@@ -242,7 +242,9 @@ async def test_runner_arms_auto_approver_for_write_grants(store: TaskStore):async def run_task(self, *, prompt, allowed_tools, model_tier, trace_id):# Simulate the tool loop proposing an ask-tier action mid-turn.await bus.publish(- ActionProposed(trace_id=trace_id, tool_name="buffer", risk_tier="ask")+ ActionApprovalRequired(+ trace_id=trace_id, tool_name="buffer", risk_tier="ask"+ ))await asyncio.sleep(0)return "posted"@@ -263,7 +265,7 @@ async def test_runner_arms_auto_approver_for_write_grants(store: TaskStore):async def test_runner_does_not_auto_approve_read_grants(store: TaskStore):"""A read-scoped grant must NOT pre-authorize an ask-tier action."""- from jarvis.core.events import ActionApproved, ActionProposed+ from jarvis.core.events import ActionApprovalRequired, ActionApprovedfrom jarvis.tasks.approval_bridge import TaskAutoApproverbus = EventBus()@@ -279,7 +281,9 @@ async def test_runner_does_not_auto_approve_read_grants(store: TaskStore):class _Brain:async def run_task(self, *, prompt, allowed_tools, model_tier, trace_id):await bus.publish(- ActionProposed(trace_id=trace_id, tool_name="gmail", risk_tier="ask")+ ActionApprovalRequired(+ trace_id=trace_id, tool_name="gmail", risk_tier="ask"+ ))await asyncio.sleep(0)return "read done"diff --git a/tests/missions/api/test_mission_tool_approval_routes.py b/tests/missions/api/test_mission_tool_approval_routes.pynew file mode 100644index 0000000000..bea23316af--- /dev/null+++ b/tests/missions/api/test_mission_tool_approval_routes.py@@ -0,0 +1,145 @@+"""REST contracts for resumable mission supervisor-tool approvals."""++from __future__ import annotations++import time+from types import SimpleNamespace+from uuid import uuid4++import httpx+import pytest+from fastapi import FastAPI++from jarvis.core.bus import EventBus+from jarvis.core.events import ActionApprovalRequired, ActionApproved, ActionDenied+from jarvis.missions.tool_approvals import MissionToolApprovalCoordinator+from jarvis.ui.web.missions_routes import router+++class _Manager:+ async def mission(self, mission_id: str) -> object | None:+ return SimpleNamespace(id=mission_id) if mission_id == "mission-1" else None+++def _app(bus: EventBus) -> FastAPI:+ app = FastAPI()+ app.include_router(router)+ app.state.mission_manager = _Manager()+ app.state.mission_tool_approvals = MissionToolApprovalCoordinator(bus)+ return app+++async def _seed(+ bus: EventBus,+ *,+ mission_id: str = "mission-1",+) -> ActionApprovalRequired:+ event = ActionApprovalRequired(+ trace_id=uuid4(),+ tool_name="gmail/send_message",+ risk_tier="ask",+ reason="risk_tier",+ args_preview="{'to': '[email protected]', 'api_key': '<redacted>'}",+ expires_at_ns=time.time_ns() + 30_000_000_000,+ mission_id=mission_id,+ worker_id="worker-1",+ )+ await bus.publish(event)+ return event+++async def test_list_and_approve_resume_only_the_selected_trace() -> None:+ bus = EventBus()+ app = _app(bus)+ approved: list[ActionApproved] = []++ async def _capture(event: ActionApproved) -> None:+ approved.append(event)++ bus.subscribe(ActionApproved, _capture)+ pending = await _seed(bus)+ transport = httpx.ASGITransport(app=app)+ async with httpx.AsyncClient(transport=transport, base_url="http://test") as client:+ listed = await client.get("/api/missions/mission-1/tool-approvals")+ decided = await client.post(+ f"/api/missions/mission-1/tool-approvals/{pending.trace_id}/approve"+ )+ listed_after = await client.get("/api/missions/mission-1/tool-approvals")++ assert listed.status_code == 200+ assert listed.json()["approvals"] == [+ {+ "trace_id": str(pending.trace_id),+ "mission_id": "mission-1",+ "worker_id": "worker-1",+ "tool_name": "gmail/send_message",+ "risk_tier": "ask",+ "reason": "risk_tier",+ "args_preview": pending.args_preview,+ "requested_at_ns": pending.timestamp_ns,+ "expires_at_ns": pending.expires_at_ns,+ }+ ]+ assert decided.status_code == 200+ assert decided.json()["decision"] == "approved"+ assert len(approved) == 1+ assert approved[0].trace_id == pending.trace_id+ assert listed_after.json()["approvals"] == []+++async def test_deny_is_first_wins_and_wrong_mission_cannot_decide() -> None:+ bus = EventBus()+ app = _app(bus)+ denied: list[ActionDenied] = []++ async def _capture(event: ActionDenied) -> None:+ denied.append(event)++ bus.subscribe(ActionDenied, _capture)+ pending = await _seed(bus)+ transport = httpx.ASGITransport(app=app)+ async with httpx.AsyncClient(transport=transport, base_url="http://test") as client:+ wrong = await client.post(+ f"/api/missions/other/tool-approvals/{pending.trace_id}/deny",+ json={"reason": "wrong mission"},+ )+ denied_response = await client.post(+ f"/api/missions/mission-1/tool-approvals/{pending.trace_id}/deny",+ json={"reason": "user_denied"},+ )+ second = await client.post(+ f"/api/missions/mission-1/tool-approvals/{pending.trace_id}/approve"+ )++ assert wrong.status_code == 404+ assert denied_response.status_code == 200+ assert second.status_code == 404+ assert len(denied) == 1+ assert denied[0].trace_id == pending.trace_id+ assert denied[0].reason == "user_denied"+++async def test_expired_approval_is_never_listed_or_decidable() -> None:+ bus = EventBus()+ app = _app(bus)+ expired = ActionApprovalRequired(+ trace_id=uuid4(),+ tool_name="gmail/send_message",+ risk_tier="ask",+ args_preview="{}",+ expires_at_ns=time.time_ns() - 1,+ mission_id="mission-1",+ )+ await bus.publish(expired)+ transport = httpx.ASGITransport(app=app)+ async with httpx.AsyncClient(transport=transport, base_url="http://test") as client:+ listed = await client.get("/api/missions/mission-1/tool-approvals")+ decided = await client.post(+ f"/api/missions/mission-1/tool-approvals/{expired.trace_id}/approve"+ )++ assert listed.json()["approvals"] == []+ assert decided.status_code == 404diff --git a/tests/missions/critic/test_capability_honesty.py b/tests/missions/critic/test_capability_honesty.pyindex d3f413103b..5f90d03a5f 100644--- a/tests/missions/critic/test_capability_honesty.py+++ b/tests/missions/critic/test_capability_honesty.py@@ -176,6 +176,165 @@ def test_claude_tool_use_still_recognized() -> None:assert "Write" in _extract_tool_call_evidence(stream)+def _claude_tool_result_stream(result: dict) -> str:+ return "\n".join(+ (+ json.dumps(+ {+ "type": "assistant",+ "message": {+ "content": [+ {+ "type": "tool_use",+ "id": "tu_1",+ "name": "mcp__gmail__send_message",+ "input": {},+ }+ ]+ },+ }+ ),+ json.dumps(+ {+ "type": "user",+ "message": {+ "content": [+ {+ "type": "tool_result",+ "tool_use_id": "tu_1",+ **result,+ }+ ]+ },+ }+ ),+ )+ )+++def test_claude_correlated_success_result_counts_as_evidence() -> None:+ stream = _claude_tool_result_stream(+ {"content": '{"status":"ok","success":true,"message_id":"42"}'}+ )++ assert _extract_tool_call_evidence(stream) == ("mcp__gmail__send_message",)+++def test_claude_is_error_result_removes_tool_call_evidence() -> None:+ stream = _claude_tool_result_stream(+ {"content": "provider rejected the request", "is_error": True}+ )++ assert _extract_tool_call_evidence(stream) == ()+++def test_claude_success_false_result_removes_tool_call_evidence() -> None:+ stream = _claude_tool_result_stream(+ {"content": {"status": "error", "success": False, "error": "offline"}}+ )++ assert _extract_tool_call_evidence(stream) == ()+++ "content",+ (+ "denied: user did not approve this action",+ '{"status":"approval_denied","success":false}',+ {"status": "blocked", "ok": False},+ [{"type": "text", "text": '{"status":"approval_denied"}'}],+ ),+)+def test_claude_denied_result_removes_tool_call_evidence(content: object) -> None:+ stream = _claude_tool_result_stream({"content": content})++ assert _extract_tool_call_evidence(stream) == ()+++def test_successful_retry_survives_failed_call_of_same_tool() -> None:+ stream = "\n".join(+ (+ _claude_tool_result_stream({"content": "denied", "is_error": True}),+ _claude_tool_result_stream({"content": "message id 43"})+ .replace('"tu_1"', '"tu_2"'),+ )+ )++ assert _extract_tool_call_evidence(stream) == ("mcp__gmail__send_message",)+++def test_codex_failed_completion_overrides_started_action() -> None:+ stream = "\n".join(+ (+ json.dumps(+ {+ "type": "item.started",+ "item": {+ "id": "item_9",+ "type": "mcp_tool_call",+ "status": "in_progress",+ },+ }+ ),+ _codex_item_line(+ {+ "id": "item_9",+ "type": "mcp_tool_call",+ "server": "gmail",+ "tool": "send_message",+ "status": "failed",+ "result": "denied",+ }+ ),+ )+ )++ assert _extract_tool_call_evidence(stream) == ()+++def test_codex_failed_completion_without_id_is_not_evidence() -> None:+ stream = _codex_item_line(+ {+ "type": "mcp_tool_call",+ "server": "gmail",+ "tool": "send_message",+ "status": "failed",+ "result": "denied",+ }+ )++ assert _extract_tool_call_evidence(stream) == ()+++def test_codex_nonzero_command_result_is_not_evidence() -> None:+ stream = _codex_item_line(+ {+ "id": "item_11",+ "type": "command_execution",+ "command": "send-message",+ "status": "completed",+ "exit_code": 1,+ "aggregated_output": "provider unavailable",+ }+ )++ assert _extract_tool_call_evidence(stream) == ()+++def test_failed_tool_call_cannot_satisfy_side_effect_honesty_gate() -> None:+ check = enforce_capability_honesty(+ user_request="Send an email to Max",+ verdict=_approval_verdict(),+ worker_output=_claude_tool_result_stream(+ {"content": '{"status":"approval_denied","success":false}'}+ ),+ )++ assert check.honesty_overridden is True+ assert check.verdict.verdict == "revise"+ assert check.tool_call_evidence == ()++# --- full gate behaviour ---diff --git a/tests/missions/kontrollierer/test_approve_materialises_report.py b/tests/missions/kontrollierer/test_approve_materialises_report.pyindex 58f5d700e3..0dd5c97b1f 100644--- a/tests/missions/kontrollierer/test_approve_materialises_report.py+++ b/tests/missions/kontrollierer/test_approve_materialises_report.py@@ -71,8 +71,8 @@ def _build_orch(o._manager = _FakeManager()o._budget = _FakeBudget()- async def _noop_transition(*_a: object, **_k: object) -> None:- return None+ async def _noop_transition(*_a: object, **_k: object) -> bool:+ return Truemonkeypatch.setattr(o, "_safe_transition", _noop_transition)if stub_deliver:diff --git a/tests/missions/kontrollierer/test_supervisor_tool_completion_gate.py b/tests/missions/kontrollierer/test_supervisor_tool_completion_gate.pynew file mode 100644index 0000000000..d1b8b47738--- /dev/null+++ b/tests/missions/kontrollierer/test_supervisor_tool_completion_gate.py@@ -0,0 +1,237 @@+"""The critic cannot approve past an unclean supervisor-tool grant."""++from __future__ import annotations++import asyncio+from pathlib import Path+from typing import Any++import pytest+import pytest_asyncio++from jarvis.core import runtime_refs+from jarvis.core.protocols import (+ SupervisorToolDescriptor,+ SupervisorToolRequest,+ ToolResult,+)+from jarvis.missions.kontrollierer.decomposer import MissionPlan, Step+from jarvis.missions.manager import MissionManager+from jarvis.missions.state_machine import MissionState+from jarvis.missions.workers.capabilities import WorkerCapabilityInventory++from .test_loop import (+ FakeCriticRunner,+ _FakeWorkerEvent,+ _make_approve_verdict,+ _make_kontrollierer,+)+++class _Gateway:+ def __init__(self, result: ToolResult) -> None:+ self.result = result+ self.calls = 0++ def catalog(self) -> tuple[SupervisorToolDescriptor, ...]:+ return (+ SupervisorToolDescriptor(+ name="external-action",+ description="A consequential external action.",+ input_schema={"type": "object", "properties": {}},+ risk_tier="monitor",+ ),+ )++ @property+ def catalog_version(self) -> int:+ return 1++ async def execute(+ self,+ _name: str,+ _arguments: dict[str, Any],+ _request: SupervisorToolRequest,+ ) -> ToolResult:+ self.calls += 1+ return self.result+++class _BlockingGateway(_Gateway):+ def __init__(self) -> None:+ super().__init__(ToolResult(success=True, output="unreachable"))+ self.started = asyncio.Event()++ async def execute(+ self,+ _name: str,+ _arguments: dict[str, Any],+ _request: SupervisorToolRequest,+ ) -> ToolResult:+ self.calls += 1+ self.started.set()+ await asyncio.Event().wait()+ raise AssertionError("the revoked call must never resume")+++class _BrokerCallingWorker:+ cli = "claude"+ last_pid = 1234++ def __init__(self, *, leave_pending: bool = False) -> None:+ self.leave_pending = leave_pending+ self.pending_tasks: list[asyncio.Task[dict[str, Any]]] = []+ self.capability_inventory = WorkerCapabilityInventory.build(+ native_tool_names=("external-action",),+ task_text="Perform the external action.",+ )++ async def spawn(+ self,+ _prompt: str,+ *,+ log_dir: Path,+ _broker_binding: Any,+ **_kwargs: Any,+ ): # noqa: ANN202 - async-generator protocol is inferred+ log_dir.mkdir(parents=True, exist_ok=True) # noqa: ASYNC240 - tiny test fixture+ (log_dir / "stream.jsonl").write_text(+ '{"type":"result","subtype":"success"}\n',+ encoding="utf-8",+ )+ call = asyncio.create_task(_broker_binding.execute("external-action", {}))+ if self.leave_pending:+ self.pending_tasks.append(call)+ await asyncio.sleep(0)+ else:+ await call+ yield _FakeWorkerEvent()+++@pytest_asyncio.fixture+async def manager(tmp_path: Path):+ active = MissionManager(tmp_path / "missions.db")+ await active.start()+ try:+ yield active+ finally:+ await active.stop()++[email protected](autouse=True)+def _clean_runtime_refs() -> Any:+ runtime_refs._reset_for_tests()+ yield+ runtime_refs._reset_for_tests()+++async def test_worker_cannot_hide_failed_tool_call_from_approving_critic(+ manager: MissionManager,+ tmp_path: Path,+) -> None:+ gateway = _Gateway(+ ToolResult(success=False, output=None, error="connector unavailable")+ )+ runtime_refs.set_supervisor_tool_gateway(gateway)+ worker = _BrokerCallingWorker()+ critic = FakeCriticRunner(_make_approve_verdict())+ kontrollierer = _make_kontrollierer(+ manager=manager,+ tmp_path=tmp_path,+ critic=critic,+ worker_factory_fn=lambda _step: worker,+ )+ mission_id = await manager.dispatch(prompt="Perform an external action")++ state = await kontrollierer.run_mission(mission_id)++ assert state == MissionState.FAILED+ assert critic.calls == []+ assert gateway.calls == 1+ events = await manager.store.events_for_mission(mission_id)+ approved = [e for e in events if e.payload.event_type == "MissionApproved"]+ failed = [e for e in events if e.payload.event_type == "MissionFailed"]+ assert approved == []+ assert failed[-1].payload.error_class == "supervisor_tool_failed" # type: ignore[union-attr]+++async def test_pending_tool_call_is_cancelled_and_blocks_critic(+ manager: MissionManager,+ tmp_path: Path,+) -> None:+ gateway = _BlockingGateway()+ runtime_refs.set_supervisor_tool_gateway(gateway)+ worker = _BrokerCallingWorker(leave_pending=True)+ critic = FakeCriticRunner(_make_approve_verdict())+ kontrollierer = _make_kontrollierer(+ manager=manager,+ tmp_path=tmp_path,+ critic=critic,+ worker_factory_fn=lambda _step: worker,+ )+ mission_id = await manager.dispatch(prompt="Perform an external action")++ state = await kontrollierer.run_mission(mission_id)+ await asyncio.gather(*worker.pending_tasks, return_exceptions=True)++ assert state == MissionState.FAILED+ assert critic.calls == []+ assert gateway.started.is_set()+++async def test_clean_tool_certificate_allows_normal_critic_approval(+ manager: MissionManager,+ tmp_path: Path,+) -> None:+ gateway = _Gateway(ToolResult(success=True, output={"done": True}))+ runtime_refs.set_supervisor_tool_gateway(gateway)+ worker = _BrokerCallingWorker()+ critic = FakeCriticRunner(_make_approve_verdict())+ kontrollierer = _make_kontrollierer(+ manager=manager,+ tmp_path=tmp_path,+ critic=critic,+ worker_factory_fn=lambda _step: worker,+ )+ mission_id = await manager.dispatch(prompt="Perform an external action")++ state = await kontrollierer.run_mission(mission_id)++ assert state == MissionState.APPROVED+ assert len(critic.calls) == 1+ assert gateway.calls == 1+++async def test_cancelled_state_wins_without_a_late_approved_event(+ manager: MissionManager,+ tmp_path: Path,+) -> None:+ critic = FakeCriticRunner(_make_approve_verdict())+ kontrollierer = _make_kontrollierer(+ manager=manager,+ tmp_path=tmp_path,+ critic=critic,+ )+ mission_id = await manager.dispatch(prompt="Cancel before approval")+ await manager.transition_state(+ mission_id,+ MissionState.CANCELLED,+ reason="user_cancelled",+ source_actor="system",+ )+ plan = MissionPlan(+ steps=[Step(slug="task", prompt="do task")],+ n_workers=1,+ expected_output="artifact",+ )++ await kontrollierer._approve_mission(mission_id, plan)++ view = await manager.mission(mission_id)+ assert view is not None and view.state == MissionState.CANCELLED+ events = await manager.store.events_for_mission(mission_id)+ assert all(event.payload.event_type != "MissionApproved" for event in events)diff --git a/tests/missions/test_outputs_root.py b/tests/missions/test_outputs_root.pynew file mode 100644index 0000000000..2d44f80a97--- /dev/null+++ b/tests/missions/test_outputs_root.py@@ -0,0 +1,35 @@+"""Portable mission-output root selection tests."""++from __future__ import annotations++from jarvis.missions.isolation.worktree import resolve_outputs_root+++def test_headless_data_dir_keeps_outputs_in_writable_volume(+ tmp_path, monkeypatch+) -> None:+ data_dir = tmp_path / "data-volume"+ monkeypatch.delenv("JARVIS_ISOLATION_ROOT", raising=False)+ monkeypatch.setenv("JARVIS_DATA_DIR", str(data_dir))++ result = resolve_outputs_root(tmp_path / "read-only-app")++ assert result == data_dir.resolve() / "jarvis-agent-outputs"+++def test_explicit_isolation_root_wins_over_data_dir(tmp_path, monkeypatch) -> None:+ explicit = tmp_path / "explicit-outputs"+ monkeypatch.setenv("JARVIS_ISOLATION_ROOT", str(explicit))+ monkeypatch.setenv("JARVIS_DATA_DIR", str(tmp_path / "data-volume"))++ assert resolve_outputs_root(tmp_path / "repo") == explicit.resolve()+++def test_checkout_defaults_to_repo_parent_when_no_override(+ tmp_path, monkeypatch+) -> None:+ repo = tmp_path / "repo"+ monkeypatch.delenv("JARVIS_ISOLATION_ROOT", raising=False)+ monkeypatch.delenv("JARVIS_DATA_DIR", raising=False)++ assert resolve_outputs_root(repo) == tmp_path / "jarvis-agent-outputs"diff --git a/tests/missions/test_worker_capability_parity.py b/tests/missions/test_worker_capability_parity.pyindex ff43480e29..a1cf692bd3 100644--- a/tests/missions/test_worker_capability_parity.py+++ b/tests/missions/test_worker_capability_parity.py@@ -46,14 +46,20 @@ def test_every_backend_receives_the_same_restricted_inventory() -> None:assert "secret-value" not in repr(inventory)-def test_backend_reports_are_honest_about_unsupported_surfaces() -> None:+def test_backend_reports_are_honest_when_supervisor_grant_is_unavailable() -> None:inventory = _inventory()- assert inventory.report_for("claude-cli")["mcp"]["status"] == "available"- for backend in ("codex-cli", "gemini-cli", "google-cli", "api:openrouter"):+ for backend in (+ "claude-cli",+ "codex-cli",+ "gemini-cli",+ "google-cli",+ "api:openrouter",+ ):report = inventory.report_for(backend)- assert report["mcp"]["status"] == "unsupported"- assert report["app_commands"]["status"] == "unsupported"+ assert report["broker"]["status"] == "unavailable"+ assert report["mcp"]["status"] == "unavailable"+ assert report["app_commands"]["status"] == "unavailable"assert "secret-value" not in json.dumps(report)diff --git a/tests/missions/test_worker_tool_broker.py b/tests/missions/test_worker_tool_broker.pynew file mode 100644index 0000000000..bda4103d5e--- /dev/null+++ b/tests/missions/test_worker_tool_broker.py@@ -0,0 +1,384 @@+"""Contract tests for the mission-scoped supervisor tool broker."""++from __future__ import annotations++import asyncio+import json+import sys+from dataclasses import dataclass+from types import SimpleNamespace+from typing import Any++import pytest++from jarvis.brain.tool_gateway import BrainSupervisorToolGateway+from jarvis.core import runtime_refs+from jarvis.core.bus import EventBus+from jarvis.core.config import SafetyConfig+from jarvis.core.events import ActionApprovalRequired, ActionApproved, ActionDenied+from jarvis.core.protocols import ToolResult+from jarvis.mcp.client import MCPClient+from jarvis.mcp.registry import MCPServerSpec+from jarvis.missions.init import _connected_native_worker_tools+from jarvis.missions.workers import broker_stdio+from jarvis.missions.workers.capabilities import WorkerCapabilityInventory+from jarvis.missions.workers.codex_direct_worker import _build_codex_direct_cmd+from jarvis.missions.workers.gemini_worker import _build_isolated_gemini_env+from jarvis.missions.workers.worker_tool_broker import (+ _BROKER,+ BROKER_TOKEN_ENV,+ BROKER_URL_ENV,+)+from jarvis.safety import ApprovalWorkflow, RiskTierEvaluator, ToolExecutor+++@dataclass+class _Tool:+ name: str+ risk_tier: str = "monitor"+ description: str = "Test connector tool."+ schema: dict[str, Any] | None = None++ def __post_init__(self) -> None:+ if self.schema is None:+ self.schema = {+ "type": "object",+ "properties": {"value": {"type": "string"}},+ }++ async def execute(self, _args: dict[str, Any], _ctx: Any) -> ToolResult:+ raise AssertionError("The broker must never call Tool.execute directly")+++class _Executor:+ def __init__(self) -> None:+ self.calls: list[tuple[str, dict[str, Any], dict[str, Any]]] = []++ async def execute(self, tool: _Tool, args: dict[str, Any], **kwargs: Any) -> ToolResult:+ self.calls.append((tool.name, args, kwargs))+ return ToolResult(success=True, output={"called": tool.name, "args": args})+++class _ExecutingAskTool(_Tool):+ def __init__(self) -> None:+ super().__init__("gmail", risk_tier="ask")+ self.calls = 0++ async def execute(self, args: dict[str, Any], _ctx: Any) -> ToolResult:+ self.calls += 1+ return ToolResult(success=True, output={"sent": args["value"]})++[email protected](autouse=True)+def _clean_runtime_refs() -> Any:+ runtime_refs._reset_for_tests()+ _BROKER.reset_for_tests()+ yield+ runtime_refs._reset_for_tests()+ _BROKER.reset_for_tests()+++def _wire_manager(executor: _Executor) -> None:+ manager = type(+ "Manager",+ (),+ {+ "_tool_executor": executor,+ "_tools": {+ "github/list_issues": _Tool("github/list_issues"),+ "github/read_secret": _Tool("github/read_secret"),+ "wiki-ingest": _Tool("wiki-ingest"),+ "gmail": _Tool("gmail", risk_tier="ask"),+ "spawn-worker": _Tool("spawn-worker"),+ "unrelated": _Tool("unrelated"),+ },+ },+ )()+ runtime_refs.set_brain_manager(manager)+ runtime_refs.set_supervisor_tool_gateway(BrainSupervisorToolGateway(manager))+++def _inventory() -> WorkerCapabilityInventory:+ return WorkerCapabilityInventory.build(+ mcp_servers={+ "github": {+ "command": "github-mcp",+ "env": {"ACCESS_TOKEN": "must-not-leave-supervisor"},+ }+ },+ app_commands=("wiki-ingest",),+ native_tool_names=("gmail",),+ task_text="List the open GitHub issues and read my Gmail inbox.",+ )+++async def test_binding_is_filtered_and_executes_only_through_supervisor() -> None:+ executor = _Executor()+ _wire_manager(executor)++ binding = _inventory().bind_broker(+ ttl_s=30,+ mission_id="mission-123",+ worker_id="worker-456",+ )++ assert binding is not None+ assert set(binding.tool_names) == {"github/list_issues", "wiki-ingest", "gmail"}+ result = await binding.execute("github/list_issues", {"value": "open"})+ assert result["success"] is True+ assert binding.execution_summary.clean is True+ assert executor.calls[0][0] == "github/list_issues"+ assert executor.calls[0][2]["config_snapshot"]["voice_confirm"] is False+ assert executor.calls[0][2]["config_snapshot"]["tool_origin"] == "mission_worker"+ assert executor.calls[0][2]["user_utterance"].startswith("List the open")++ denied = await binding.execute("unrelated", {})+ assert denied["status"] == "denied"+ assert len(executor.calls) == 1+++async def test_ask_tier_waits_then_resumes_the_exact_call_after_approval() -> None:+ bus = EventBus()+ approval = ApprovalWorkflow(bus, timeout_s=1.0)+ executor = ToolExecutor(+ bus,+ RiskTierEvaluator(SafetyConfig()),+ approval,+ default_timeout_s=1.0,+ )+ tool = _ExecutingAskTool()+ manager = SimpleNamespace(_tool_executor=executor, _tools={tool.name: tool})+ runtime_refs.set_brain_manager(manager)+ runtime_refs.set_supervisor_tool_gateway(BrainSupervisorToolGateway(manager))+ requested = asyncio.Event()+ request: ActionApprovalRequired | None = None++ async def _capture(event: ActionApprovalRequired) -> None:+ nonlocal request+ request = event+ requested.set()++ bus.subscribe(ActionApprovalRequired, _capture)+ binding = _inventory().bind_broker(+ ttl_s=30,+ mission_id="mission-123",+ worker_id="worker-456",+ )+ assert binding is not None++ call = asyncio.create_task(binding.execute("gmail", {"value": "send"}))+ await asyncio.wait_for(requested.wait(), timeout=1.0)++ assert request is not None+ assert request.mission_id == "mission-123"+ assert request.worker_id == "worker-456"+ assert call.done() is False+ assert tool.calls == 0+ assert binding.execution_summary.clean is False+ assert binding.execution_summary.active_count == 1+ await bus.publish(+ ActionApproved(+ trace_id=request.trace_id,+ tool_name=request.tool_name,+ approved_by="user",+ )+ )+ result = await asyncio.wait_for(call, timeout=1.0)++ assert result["status"] == "ok"+ assert result["success"] is True+ assert result["trace_id"] == str(request.trace_id)+ assert tool.calls == 1+ assert binding.execution_summary.clean is True+++async def test_denied_ask_tier_never_executes_the_tool() -> None:+ bus = EventBus()+ approval = ApprovalWorkflow(bus, timeout_s=1.0)+ executor = ToolExecutor(+ bus,+ RiskTierEvaluator(SafetyConfig()),+ approval,+ default_timeout_s=1.0,+ )+ tool = _ExecutingAskTool()+ manager = SimpleNamespace(_tool_executor=executor, _tools={tool.name: tool})+ runtime_refs.set_brain_manager(manager)+ runtime_refs.set_supervisor_tool_gateway(BrainSupervisorToolGateway(manager))+ requested: asyncio.Queue[ActionApprovalRequired] = asyncio.Queue()+ bus.subscribe(ActionApprovalRequired, requested.put)+ binding = _inventory().bind_broker(ttl_s=30)+ assert binding is not None++ call = asyncio.create_task(binding.execute("gmail", {"value": "send"}))+ request = await asyncio.wait_for(requested.get(), timeout=1.0)+ await bus.publish(+ ActionDenied(+ trace_id=request.trace_id,+ tool_name=request.tool_name,+ reason="user_denied",+ )+ )+ result = await asyncio.wait_for(call, timeout=1.0)++ assert result["status"] == "approval_denied"+ assert result["success"] is False+ assert tool.calls == 0+ assert binding.execution_summary.clean is False+ assert binding.execution_summary.calls[-1].status == "denied"+++async def test_loopback_http_requires_env_bearer_and_revocation_is_immediate(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ executor = _Executor()+ _wire_manager(executor)+ binding = _inventory().bind_broker(ttl_s=30)+ assert binding is not None+ env = binding.apply_environment({})+ monkeypatch.setenv(BROKER_URL_ENV, env[BROKER_URL_ENV])+ monkeypatch.setenv(BROKER_TOKEN_ENV, env[BROKER_TOKEN_ENV])++ listed = await asyncio.to_thread(broker_stdio._request, "GET", "/v1/tools")+ assert {tool["name"] for tool in listed["tools"]} == set(binding.tool_names)+ result = await asyncio.to_thread(+ broker_stdio._request,+ "POST",+ "/v1/execute",+ {"name": "wiki-ingest", "arguments": {"value": "fact"}},+ )+ assert result["success"] is True++ binding.close()+ with pytest.raises(RuntimeError, match="unauthorized"):+ await asyncio.to_thread(broker_stdio._request, "GET", "/v1/tools")+++async def test_cli_configs_contain_only_adapter_while_token_stays_in_env(tmp_path) -> None:+ executor = _Executor()+ _wire_manager(executor)+ inventory = _inventory()+ binding = inventory.bind_broker(ttl_s=30)+ assert binding is not None++ server_config = binding.mcp_server_config()+ serialized = json.dumps(server_config)+ child_env = binding.apply_environment({"PATH": "test"})+ assert "must-not-leave-supervisor" not in serialized+ assert BROKER_TOKEN_ENV not in serialized+ assert child_env[BROKER_TOKEN_ENV]++ codex_cmd = _build_codex_direct_cmd(+ worktree=tmp_path,+ model=None,+ mcp_servers=server_config,+ )+ assert "mcp_servers.jarvis_worker_tools.command" in " ".join(codex_cmd)+ assert child_env[BROKER_TOKEN_ENV] not in " ".join(codex_cmd)++ gemini_env, settings_path, allowed = _build_isolated_gemini_env(+ child_env,+ log_dir=tmp_path,+ mcp_servers=server_config,+ )+ settings = json.loads(settings_path.read_text(encoding="utf-8"))+ assert allowed == "jarvis_worker_tools"+ assert settings["mcpServers"] == server_config+ assert BROKER_TOKEN_ENV not in settings_path.read_text(encoding="utf-8")+ assert gemini_env[BROKER_TOKEN_ENV] == child_env[BROKER_TOKEN_ENV]+++async def test_frozen_bundle_uses_its_internal_stdio_adapter(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ executor = _Executor()+ _wire_manager(executor)+ binding = _inventory().bind_broker(ttl_s=30)+ assert binding is not None+ monkeypatch.setattr(sys, "frozen", True, raising=False)++ config = binding.mcp_server_config()["jarvis_worker_tools"]++ assert config["command"] == sys.executable+ assert config["args"] == ["--worker-tool-broker-stdio"]+++async def test_stdio_mcp_adapter_lists_and_calls_the_scoped_tools() -> None:+ executor = _Executor()+ _wire_manager(executor)+ binding = _inventory().bind_broker(ttl_s=30)+ assert binding is not None+ env = binding.apply_environment({})+ client = MCPClient(+ MCPServerSpec(+ name="jarvis-worker-tools-test",+ display="Jarvis worker tools",+ description="Test broker adapter",+ install_command=[+ sys.executable,+ "-m",+ "jarvis.missions.workers.broker_stdio",+ ],+ ),+ env_overrides={+ BROKER_URL_ENV: env[BROKER_URL_ENV],+ BROKER_TOKEN_ENV: env[BROKER_TOKEN_ENV],+ },+ )+ try:+ await asyncio.wait_for(client.start(), timeout=10)+ listed = await client.list_tools()+ assert {tool["name"] for tool in listed} == set(binding.tool_names)+ result = await client.call_tool("github/list_issues", {"value": "open"})+ assert result.structuredContent["success"] is True+ finally:+ await client.stop()+ binding.close()+++async def test_missing_supervisor_degrades_to_no_grant() -> None:+ inventory = _inventory()+ assert inventory.bind_broker() is None+ report = inventory.report_for("api:openrouter")+ assert report["broker"]["status"] == "unavailable"+ assert report["mcp"]["status"] == "unavailable"+++def test_native_connector_discovery_is_relevance_and_credential_aware(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ from jarvis.marketplace import catalog_data, plugin_relevance, token_store++ plugins = [+ SimpleNamespace(id="gmail", native_tool="gmail", description="Email"),+ SimpleNamespace(id="vercel", native_tool="vercel", description="Deployments"),+ SimpleNamespace(id="docs", native_tool=None, description="Docs"),+ ]+ token_by_id = {+ "gmail": SimpleNamespace(access="token", needs_reauth=False),+ "vercel": SimpleNamespace(access="token", needs_reauth=True),+ }+ monkeypatch.setattr(+ catalog_data, "load_catalog", lambda: SimpleNamespace(plugins=plugins)+ )+ monkeypatch.setattr(+ token_store,+ "TokenStore",+ lambda: SimpleNamespace(load=lambda plugin_id: token_by_id.get(plugin_id)),+ )+ monkeypatch.setattr(+ plugin_relevance,+ "plugin_is_relevant",+ lambda text, plugin_id, _tools: plugin_id in text.lower(),+ )++ assert _connected_native_worker_tools("Read my Gmail inbox") == ("gmail",)+ assert _connected_native_worker_tools("Inspect Vercel") == ()diff --git a/tests/missions/test_worker_tool_broker_lifecycle.py b/tests/missions/test_worker_tool_broker_lifecycle.pynew file mode 100644index 0000000000..640b5a76b3--- /dev/null+++ b/tests/missions/test_worker_tool_broker_lifecycle.py@@ -0,0 +1,276 @@+"""Lifecycle regressions for mission-scoped worker tool grants."""++from __future__ import annotations++import asyncio+from dataclasses import dataclass+from types import SimpleNamespace+from typing import Any++import pytest++from jarvis.brain.tool_gateway import BrainSupervisorToolGateway+from jarvis.core import runtime_refs+from jarvis.core.protocols import ToolResult+from jarvis.missions.workers import worker_tool_broker as broker_module+from jarvis.missions.workers.worker_tool_broker import WorkerToolBroker+from jarvis.safety import tool_executor as _tool_executor # noqa: F401+++@dataclass+class _Tool:+ name: str+ description: str = "Lifecycle test tool."+ schema: dict[str, Any] | None = None++ def __post_init__(self) -> None:+ if self.schema is None:+ self.schema = {"type": "object", "properties": {}}++ async def execute(self, _args: dict[str, Any], _ctx: Any) -> ToolResult:+ raise AssertionError("The broker must execute tools only through ToolExecutor")+++class _RecordingExecutor:+ def __init__(self) -> None:+ self.calls: list[str] = []++ async def execute(+ self,+ tool: _Tool,+ _arguments: dict[str, Any],+ **_kwargs: Any,+ ) -> ToolResult:+ self.calls.append(tool.name)+ return ToolResult(success=True, output={"called": tool.name})+++class _BlockingExecutor(_RecordingExecutor):+ def __init__(self) -> None:+ super().__init__()+ self.started = asyncio.Event()+ self.release = asyncio.Event()+ self.cancelled = asyncio.Event()++ async def execute(+ self,+ tool: _Tool,+ _arguments: dict[str, Any],+ **_kwargs: Any,+ ) -> ToolResult:+ self.calls.append(tool.name)+ self.started.set()+ try:+ await self.release.wait()+ except asyncio.CancelledError:+ self.cancelled.set()+ raise+ return ToolResult(success=True, output={"called": tool.name})++[email protected](autouse=True)+def _clean_runtime_refs() -> Any:+ runtime_refs._reset_for_tests()+ yield+ runtime_refs._reset_for_tests()+++def broker(monkeypatch: pytest.MonkeyPatch) -> WorkerToolBroker:+ """Build a broker without opening a real loopback listener."""+ instance = WorkerToolBroker()+ server = SimpleNamespace(server_address=("127.0.0.1", 1))+ monkeypatch.setattr(instance, "_ensure_server", lambda: server)+ return instance+++def _wire_manager(+ executor: _RecordingExecutor,+ tools: dict[str, _Tool],+) -> SimpleNamespace:+ manager = SimpleNamespace(_tool_executor=executor, _tools=tools)+ runtime_refs.set_brain_manager(manager)+ runtime_refs.set_supervisor_tool_gateway(BrainSupervisorToolGateway(manager))+ return manager+++def _issue(+ broker: WorkerToolBroker,+ *,+ ttl_s: float = 30.0,+ executor: _RecordingExecutor | None = None,+ tools: dict[str, _Tool] | None = None,+): # noqa: ANN202 - the concrete binding type is an implementation detail+ active_executor = executor or _RecordingExecutor()+ active_tools = tools or {"github/list_issues": _Tool("github/list_issues")}+ manager = _wire_manager(active_executor, active_tools)+ binding = broker.issue(+ task_text="Inspect the connected GitHub project.",+ mcp_server_ids=("github",),+ app_commands=(),+ native_tool_names=(),+ ttl_s=ttl_s,+ )+ assert binding is not None+ return binding, manager, active_executor+++async def test_binding_available_becomes_false_after_ttl_without_registry_lookup(+ broker: WorkerToolBroker,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ now = [100.0]+ monkeypatch.setattr(+ broker_module,+ "time",+ SimpleNamespace(monotonic=lambda: now[0]),+ )+ binding, _manager, _executor = _issue(broker, ttl_s=1.0)++ now[0] = 102.0++ assert binding.available is False+ assert binding.mcp_server_config() == {}+ assert broker_module.BROKER_TOKEN_ENV not in binding.apply_environment({})+++async def test_direct_binding_execution_rejects_an_expired_grant(+ broker: WorkerToolBroker,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ now = [200.0]+ monkeypatch.setattr(+ broker_module,+ "time",+ SimpleNamespace(monotonic=lambda: now[0]),+ )+ binding, _manager, executor = _issue(broker, ttl_s=1.0)++ now[0] = 202.0+ result = await binding.execute("github/list_issues", {})++ assert result["status"] == "denied"+ assert result["success"] is False+ assert executor.calls == []+++async def test_scope_resolved_before_revoke_cannot_start_a_tool_call(+ broker: WorkerToolBroker,+) -> None:+ binding, _manager, executor = _issue(broker)+ resolved_scope = broker.lookup(binding._token)+ assert resolved_scope is not None++ broker.revoke(binding._token)+ result = await resolved_scope.execute("github/list_issues", {})++ assert result["status"] == "denied"+ assert result["success"] is False+ assert executor.calls == []+++async def test_closing_binding_cancels_or_rejects_an_in_flight_call(+ broker: WorkerToolBroker,+) -> None:+ executor = _BlockingExecutor()+ binding, _manager, _executor = _issue(broker, executor=executor)+ call = asyncio.create_task(binding.execute("github/list_issues", {}))+ await asyncio.wait_for(executor.started.wait(), timeout=1.0)++ try:+ aclose = getattr(binding, "aclose", None)+ if callable(aclose):+ await aclose()+ else:+ binding.close()+ await asyncio.sleep(0)++ if not call.done():+ executor.release.set()+ try:+ result = await asyncio.wait_for(call, timeout=1.0)+ except asyncio.CancelledError:+ result = None++ assert executor.cancelled.is_set() or (+ result is not None+ and result["success"] is False+ and result["status"] == "denied"+ )+ assert binding.execution_summary.clean is False+ assert binding.execution_summary.calls[-1].status == "outcome_unknown"+ finally:+ executor.release.set()+ if not call.done():+ call.cancel()+ await asyncio.gather(call, return_exceptions=True)+++async def test_catalog_and_execution_drop_a_tool_removed_from_live_manager(+ broker: WorkerToolBroker,+) -> None:+ tools = {+ "github/list_issues": _Tool("github/list_issues"),+ "github/get_issue": _Tool("github/get_issue"),+ }+ binding, manager, executor = _issue(broker, tools=tools)+ assert set(binding.tool_names) == set(tools)++ del manager._tools["github/get_issue"]++ assert set(binding.tool_names) == {"github/list_issues"}+ result = await binding.execute("github/get_issue", {})+ assert result["status"] == "denied"+ assert executor.calls == []+++async def test_catalog_discovers_new_live_tool_matching_original_source_grant(+ broker: WorkerToolBroker,+) -> None:+ binding, manager, executor = _issue(broker)++ manager._tools["github/get_issue"] = _Tool("github/get_issue")++ assert set(binding.tool_names) == {"github/list_issues", "github/get_issue"}+ result = await binding.execute("github/get_issue", {})+ assert result["success"] is True+ assert executor.calls == ["github/get_issue"]+++async def test_namespaced_recursive_tools_never_enter_a_worker_grant(+ broker: WorkerToolBroker,+) -> None:+ recursive = {+ "github/dispatch-with-review",+ "github/multi_spawn",+ "github/run-skill",+ "github/spawn_worker",+ }+ tools = {name: _Tool(name) for name in recursive}+ tools["github/list_issues"] = _Tool("github/list_issues")++ binding, _manager, _executor = _issue(broker, tools=tools)++ assert set(binding.tool_names) == {"github/list_issues"}+ for name in recursive:+ result = await binding.execute(name, {})+ assert result["status"] == "denied"+++async def test_dynamic_catalog_filters_recursive_tools_added_after_issue(+ broker: WorkerToolBroker,+) -> None:+ binding, manager, _executor = _issue(broker)++ manager._tools["github/get_issue"] = _Tool("github/get_issue")+ manager._tools["github/spawn-worker"] = _Tool("github/spawn-worker")++ assert set(binding.tool_names) == {"github/list_issues", "github/get_issue"}diff --git a/tests/missions/test_worktree.py b/tests/missions/test_worktree.pyindex 57ce396439..562409a944 100644--- a/tests/missions/test_worktree.py+++ b/tests/missions/test_worktree.py@@ -275,7 +275,7 @@ def test_lean_create_respects_path_length_cap(workspaces too (files written inside must still fit under MAX_PATH)."""very_deep = tmp_path / ("x" * 220)mgr = WorktreeManager(repo_root=tmp_git_repo, outputs_root=very_deep)- with pytest.raises(ValueError, match="zu lang"):+ with pytest.raises(ValueError, match="too long"):mgr.create(mission_slug="m", task_id="01", needs_repo=False)@@ -303,11 +303,11 @@ def test_create_path_layout_matches_spec(manager: WorktreeManager, tmp_path: Patdef test_create_raises_when_path_too_long(tmp_git_repo: Path, tmp_path: Path) -> None:- """Pfad-Length-Cap: wirft ValueError wenn Worktree-Wurzel >200 Chars."""+ """The path-length cap raises ValueError above 200 characters."""# Very deep outputs_root to exceed the capvery_deep = tmp_path / ("x" * 220)mgr = WorktreeManager(repo_root=tmp_git_repo, outputs_root=very_deep)- with pytest.raises(ValueError, match="zu lang"):+ with pytest.raises(ValueError, match="too long"):mgr.create(mission_slug="m", task_id="01")diff --git a/tests/missions/workers/test_api_agent_worker.py b/tests/missions/workers/test_api_agent_worker.pyindex d001b73be5..6921bb9ecb 100644--- a/tests/missions/workers/test_api_agent_worker.py+++ b/tests/missions/workers/test_api_agent_worker.py@@ -280,6 +280,41 @@ async def test_unknown_provider_returns_clean_error(tmp_path: Path) -> None:assert events[-1].is_error is True+async def test_init_failure_revokes_worker_tool_grant(tmp_path: Path) -> None:+ """An early provider failure must not leave a live bearer grant behind."""++ class _Binding:+ tool_specs: tuple[dict[str, object], ...] = ()+ closed = False++ def close(self) -> None:+ self.closed = True++ class _Inventory:+ def __init__(self, binding: _Binding) -> None:+ self.binding = binding++ def bind_broker(self, **_kwargs): # noqa: ANN003, ANN201+ return self.binding++ def report_for(self, _backend: str, **_kwargs): # noqa: ANN003, ANN201+ return {}++ binding = _Binding()+ worker = ApiAgentWorker(+ "definitely-not-a-provider",+ capability_inventory=_Inventory(binding), # type: ignore[arg-type]+ )++ await _drain(+ worker, prompt="x", worktree=tmp_path, env={}, job=None,+ worker_id="m::0", log_dir=tmp_path / "_logs",+ )++ assert binding.closed is True++@pytest.mark.asyncioasync def test_stream_jsonl_is_valid_ndjson(monkeypatch: pytest.MonkeyPatch, tmp_path: Pathdiff --git a/tests/missions/workers/test_codex_auth_fallback.py b/tests/missions/workers/test_codex_auth_fallback.pyindex a4f30d9c8d..c4da154e52 100644--- a/tests/missions/workers/test_codex_auth_fallback.py+++ b/tests/missions/workers/test_codex_auth_fallback.py@@ -406,6 +406,63 @@ async def test_codex_success_clears_quota_cooldown(assert codex_in_quota_cooldown() is False+async def test_codex_rejected_write_is_not_reported_as_success(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ """A completed model turn is not success when its only write was rejected."""+ stdout = (+ b'{"type":"item.completed","item":{"type":"agent_message",'+ b'"text":"I could not create the requested file."}}\n'+ b'{"type":"turn.completed","usage":{"input_tokens":10,"output_tokens":5}}\n'+ )+ stderr = b"patch rejected: writing is blocked by read-only sandbox"++ async def _fake_exec(*_a: Any, **_k: Any) -> _FakeProc:+ return _FakeProc(stdout, returncode=0, stderr=stderr)++ monkeypatch.setattr(cdw.asyncio, "create_subprocess_exec", _fake_exec)++ events = await _drive(CodexDirectWorker(), tmp_path)++ final = events[-1]+ assert final.is_error is True+ assert "sandbox rejected" in final.result.lower()+++async def test_codex_shell_write_recovers_from_failed_patch(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ """A later successful shell write supersedes a failed Windows patch attempt."""+ stdout = (+ b'{"type":"item.completed","item":{"type":"file_change",'+ b'"status":"failed","changes":[{"path":"hello.txt"}]}}\n'+ b'{"type":"item.completed","item":{"type":"command_execution",'+ b'"status":"completed","exit_code":0,"command":"write hello.txt"}}\n'+ b'{"type":"item.completed","item":{"type":"agent_message",'+ b'"text":"Created hello.txt."}}\n'+ b'{"type":"turn.completed","usage":{"input_tokens":10,"output_tokens":5}}\n'+ )+ stderr = b"Failed to write file hello.txt"++ async def _fake_exec(*_a: Any, **_k: Any) -> _FakeProc:+ return _FakeProc(stdout, returncode=0, stderr=stderr)++ monkeypatch.setattr(cdw.asyncio, "create_subprocess_exec", _fake_exec)++ events = await _drive(CodexDirectWorker(), tmp_path)++ final = events[-1]+ assert final.is_error is False+ assert any(+ block.get("type") == "tool_use" and block.get("name") == "Bash"+ for event in events+ for block in (getattr(event, "message", {}) or {}).get("content", [])+ if isinstance(block, dict)+ )++@pytest.mark.asyncioasync def test_codex_hardcap_timeout_preserves_work_and_flags_timed_out(tmp_path: Path, monkeypatch: pytest.MonkeyPatch@@ -444,7 +501,7 @@ async def test_codex_hardcap_timeout_preserves_work_and_flags_timed_out(self.stderr = _FakeStream()async def communicate(self) -> tuple[bytes, bytes]:- raise asyncio.TimeoutError # legacy path — not used by streaming+ raise TimeoutError # legacy path — not used by streamingasync def wait(self) -> int:return -9diff --git a/tests/missions/workers/test_codex_model_normalization.py b/tests/missions/workers/test_codex_model_normalization.pyindex aa66cb724a..3e68b91b30 100644--- a/tests/missions/workers/test_codex_model_normalization.py+++ b/tests/missions/workers/test_codex_model_normalization.py@@ -1,4 +1,4 @@-"""Codex-Worker model-slug normalization (Welle 6 BUG-LIVE follow-up).+"""Codex-Worker model-slug normalization (Wave 6 BUG-LIVE follow-up).Live repro 2026-05-18 mission_019e3c52-0acd:Codex with ChatGPT account returned HTTP 400 because the@@ -17,14 +17,18 @@ that via ``if model:`` gating."""from __future__ import annotations+import re+from pathlib import Path+import pytestfrom jarvis.missions.workers.codex_direct_worker import (_CLAUDE_MODEL_ALIASES,+ _build_codex_direct_cmd,_normalize_model_for_codex,+ _prepare_codex_prompt,)-# --- Anthropic-flavoured aliases (legacy decomposer defaults) ---@@ -104,29 +108,48 @@ def test_claude_alias_set_is_exactly_three() -> None:assert _CLAUDE_MODEL_ALIASES == frozenset({"sonnet", "opus", "haiku"})-# --- D9 recursion guard: codex must not spawn NESTED sub-agents ---+# --- D9 recursion guard: codex must not spawn NESTED Jarvis-Agents ----from pathlib import Path # noqa: E402-from jarvis.missions.workers.codex_direct_worker import ( # noqa: E402- _build_codex_direct_cmd,-)+def test_codex_cmd_restores_native_windows_sandbox_after_config_isolation() -> None:+ """Ignoring user config must not silently erase the Windows sandbox mode."""+ worktree = Path("C:/mission/worktree")+ cmd = _build_codex_direct_cmd(+ worktree=worktree,+ model=None,+ windows_sandbox="unelevated",+ )++ assert "--ignore-user-config" in cmd+ assert 'windows.sandbox="unelevated"' in cmd+ assert cmd[cmd.index("--cd") + 1] == str(worktree)+++def test_codex_prompt_adds_bounded_windows_write_recovery() -> None:+ prompt = _prepare_codex_prompt("Create hello.txt.", native_windows=True)++ assert "PowerShell shell command" in prompt+ assert "UTF-8 without a byte-order mark" in prompt+ assert "System.Text.UTF8Encoding(false)" in prompt+ assert "Never write outside the current worktree" in prompt+ assert prompt.endswith("Create hello.txt.")+ assert _prepare_codex_prompt("Analyze only.", native_windows=False) == "Analyze only."def test_codex_cmd_disables_multi_agent_collab_tools() -> None:- """A mission worker IS the sub-agent — it must NEVER use codex's native+ """A mission worker IS the Jarvis-Agent — it must NEVER use codex's nativemulti_agent collaboration tools (spawn_agent / wait) to spawn a NESTED codexagent and block on it.Live mission 019ec708 (2026-06-14): the prompt was phrased "spawn a- sub-agent which will help me plan a trip from London to Taiwan"; the codex+ Jarvis-Agent which will help me plan a trip from London to Taiwan"; codexworker called spawn_agent("Hooke") then `wait` and hung for the full workertimeout (frozen stream, no WorkerDraftReady for 7+ min). Jarvis's D9recursion guard (AP-5 / AP-14: no spawn tool in any worker set) governsJarvis's own tool registry — codex's native feature bypasses it, so theargv must disable it. `--disable <FEATURE>` == `-c features.<name>=false`."""- cmd = _build_codex_direct_cmd(worktree=Path("/tmp/wt"), model=None)+ cmd = _build_codex_direct_cmd(worktree=Path("test-worktree"), model=None)disabled = [cmd[i + 1]for i, a in enumerate(cmd)@@ -139,13 +162,11 @@ def test_codex_cmd_disables_multi_agent_collab_tools() -> None:def test_codex_cmd_caps_reasoning_effort_for_speed() -> None:"""Mission latency (live mission 019ec742, 2026-06-14): the codex worker ran452s then 399s at the user's `~/.codex/config.toml` `model_reasoning_effort- = "xhigh"` → 899s critic_loop_exhausted. A sub-agent mission worker re-runs+ = "xhigh"` → 899s critic_loop_exhausted. A Jarvis-Agent mission worker re-runsacross up to MAX_CRITIC_LOOPS iterations, so a 7-minute xhigh pass per run isunacceptable. The argv MUST override config.toml to a FAST tier via`-c model_reasoning_effort=<low|medium>`, never inheriting xhigh."""- import re-- cmd = _build_codex_direct_cmd(worktree=Path("/tmp/wt"), model=None)+ cmd = _build_codex_direct_cmd(worktree=Path("test-worktree"), model=None)joined = " ".join(cmd)m = re.search(r"model_reasoning_effort=(\w+)", joined)assert m, f"no reasoning-effort cap in argv (inherits config xhigh): {cmd}"@@ -166,7 +187,7 @@ def test_codex_cmd_enables_web_search_for_research() -> None:confirmed it returns current data (a WSJ URL dated today). The worker argvMUST enable it so research/current-events missions can produce SOURCED work:``-c tools.web_search=true``."""- cmd = _build_codex_direct_cmd(worktree=Path("/tmp/wt"), model=None)+ cmd = _build_codex_direct_cmd(worktree=Path("test-worktree"), model=None)assert "tools.web_search=true" in " ".join(cmd), (f"web_search not enabled in argv (worker cannot research): {cmd}")diff --git a/tests/missions/workers/test_worker_broker_binding_cleanup.py b/tests/missions/workers/test_worker_broker_binding_cleanup.pynew file mode 100644index 0000000000..958dce0ddd--- /dev/null+++ b/tests/missions/workers/test_worker_broker_binding_cleanup.py@@ -0,0 +1,461 @@+"""Mission worker grants are single-owner resources across every exit path."""++from __future__ import annotations++import asyncio+from collections.abc import Callable+from pathlib import Path+from typing import Any++import pytest++import jarvis.claude_auth_state as claude_auth_state+import jarvis.codex_auth_state as codex_auth_state+import jarvis.codex_quota_state as codex_quota_state+import jarvis.missions.init as missions_init+import jarvis.missions.workers.claude_direct_worker as claude_module+import jarvis.missions.workers.codex_direct_worker as codex_module+import jarvis.missions.workers.google_cli_worker as google_module+from jarvis.google_cli.resolver import GoogleCli+from jarvis.missions.workers.api_agent_worker import ApiAgentWorker+from jarvis.missions.workers.claude_direct_worker import ClaudeDirectWorker+from jarvis.missions.workers.codex_direct_worker import CodexDirectWorker+from jarvis.missions.workers.gemini_worker import GeminiWorker+from jarvis.missions.workers.google_cli_worker import (+ BrokerMcpConfigurationError,+ GoogleCliWorker,+ _build_agy_worker_env,+)+++class _CountingBinding:+ tool_specs: tuple[dict[str, object], ...] = ()+ tool_names: tuple[str, ...] = ("github/list_issues",)+ available = True++ def __init__(self) -> None:+ self.close_calls = 0++ def close(self) -> None:+ self.close_calls += 1++ def mcp_server_config(self) -> dict[str, dict[str, object]]:+ return {+ "jarvis_worker_tools": {+ "command": "python",+ "args": ["-m", "jarvis.missions.workers.broker_stdio"],+ }+ }++ def apply_environment(self, env: dict[str, str]) -> dict[str, str]:+ return dict(env)+++class _CountingInventory:+ def __init__(self, binding: _CountingBinding) -> None:+ self.binding = binding+ self.bind_calls = 0++ def bind_broker(self, **_kwargs: Any) -> _CountingBinding:+ self.bind_calls += 1+ return self.binding++ def report_for(+ self, backend: str, *, binding: _CountingBinding | None = None+ ) -> dict[str, object]:+ return {+ "backend": backend,+ "broker": {"status": "available" if binding is not None else "unavailable"},+ }+++class _FakeStream:+ def __init__(self, data: bytes = b"") -> None:+ self._data = data+ self._lines = data.splitlines(keepends=True)+ self._line_index = 0+ self._read = False++ async def read(self, _size: int = -1) -> bytes:+ if self._read:+ return b""+ self._read = True+ return self._data++ async def readline(self) -> bytes:+ if self._line_index >= len(self._lines):+ return b""+ line = self._lines[self._line_index]+ self._line_index += 1+ return line++ def write(self, _data: bytes) -> None:+ return None++ async def drain(self) -> None:+ return None++ def close(self) -> None:+ return None+++class _FakeProcess:+ def __init__(self, stdout: bytes, *, returncode: int) -> None:+ self.pid = 4242+ self.returncode = returncode+ self.stdin = _FakeStream()+ self.stdout = _FakeStream(stdout)+ self.stderr = _FakeStream()++ async def wait(self) -> int:+ return self.returncode++ def kill(self) -> None:+ self.returncode = -9+++class _Job:+ def assign(self, _pid: int) -> None:+ return None+++WorkerFactory = Callable[[_CountingInventory], Any]+++_WORKERS: tuple[tuple[str, WorkerFactory], ...] = (+ (+ "api",+ lambda inventory: ApiAgentWorker(+ "openai",+ capability_inventory=inventory, # type: ignore[arg-type]+ ),+ ),+ (+ "claude",+ lambda inventory: ClaudeDirectWorker(+ capability_inventory=inventory # type: ignore[arg-type]+ ),+ ),+ (+ "codex",+ lambda inventory: CodexDirectWorker(+ capability_inventory=inventory # type: ignore[arg-type]+ ),+ ),+ (+ "gemini",+ lambda inventory: GeminiWorker(+ capability_inventory=inventory # type: ignore[arg-type]+ ),+ ),+ (+ "google",+ lambda inventory: GoogleCliWorker(+ capability_inventory=inventory # type: ignore[arg-type]+ ),+ ),+)+++def _spawn(worker: Any, tmp_path: Path): # noqa: ANN202+ return worker.spawn(+ "complete the mission",+ worktree=tmp_path,+ env={},+ job=object(),+ worker_id="mission::0",+ log_dir=tmp_path / "logs",+ )++[email protected]("_name,worker_factory", _WORKERS, ids=lambda value: str(value))+async def test_binding_closes_once_after_normal_completion(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+ _name: str,+ worker_factory: WorkerFactory,+) -> None:+ binding = _CountingBinding()+ inventory = _CountingInventory(binding)+ worker = worker_factory(inventory)++ async def _normal(*_args: Any, **kwargs: Any): # noqa: ANN202+ assert kwargs["broker_binding"] is binding+ yield "init"+ yield "result"++ monkeypatch.setattr(worker, "_spawn_bound", _normal)+ stream = _spawn(worker, tmp_path)+ assert [event async for event in stream] == ["init", "result"]+ await stream.aclose()++ assert inventory.bind_calls == 1+ assert binding.close_calls == 1++[email protected]("_name,worker_factory", _WORKERS, ids=lambda value: str(value))+async def test_binding_closes_once_after_empty_early_return(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+ _name: str,+ worker_factory: WorkerFactory,+) -> None:+ binding = _CountingBinding()+ worker = worker_factory(_CountingInventory(binding))++ async def _empty(*_args: Any, **_kwargs: Any): # noqa: ANN202+ if False:+ yield None++ monkeypatch.setattr(worker, "_spawn_bound", _empty)+ assert [event async for event in _spawn(worker, tmp_path)] == []+ assert binding.close_calls == 1++[email protected]("_name,worker_factory", _WORKERS, ids=lambda value: str(value))+async def test_binding_closes_once_after_worker_exception(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+ _name: str,+ worker_factory: WorkerFactory,+) -> None:+ binding = _CountingBinding()+ worker = worker_factory(_CountingInventory(binding))++ async def _broken(*_args: Any, **_kwargs: Any): # noqa: ANN202+ if False:+ yield None+ raise RuntimeError("worker failed")++ monkeypatch.setattr(worker, "_spawn_bound", _broken)+ with pytest.raises(RuntimeError, match="worker failed"):+ _ = [event async for event in _spawn(worker, tmp_path)]+ assert binding.close_calls == 1++[email protected]("_name,worker_factory", _WORKERS, ids=lambda value: str(value))+async def test_binding_closes_once_when_consumer_closes_generator(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+ _name: str,+ worker_factory: WorkerFactory,+) -> None:+ binding = _CountingBinding()+ worker = worker_factory(_CountingInventory(binding))++ async def _long_running(*_args: Any, **_kwargs: Any): # noqa: ANN202+ yield "init"+ await asyncio.Event().wait()++ monkeypatch.setattr(worker, "_spawn_bound", _long_running)+ stream = _spawn(worker, tmp_path)+ assert await anext(stream) == "init"+ await stream.aclose()++ assert binding.close_calls == 1++[email protected]("_name,worker_factory", _WORKERS, ids=lambda value: str(value))+async def test_binding_closes_once_when_active_read_is_cancelled(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+ _name: str,+ worker_factory: WorkerFactory,+) -> None:+ binding = _CountingBinding()+ worker = worker_factory(_CountingInventory(binding))+ waiting = asyncio.Event()++ async def _long_running(*_args: Any, **_kwargs: Any): # noqa: ANN202+ yield "init"+ waiting.set()+ await asyncio.Event().wait()++ monkeypatch.setattr(worker, "_spawn_bound", _long_running)+ stream = _spawn(worker, tmp_path)+ assert await anext(stream) == "init"+ read = asyncio.create_task(anext(stream))+ await waiting.wait()+ read.cancel()+ with pytest.raises(asyncio.CancelledError):+ await read+ await stream.aclose()++ assert binding.close_calls == 1+++async def test_google_to_gemini_fallback_reuses_outer_binding(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ binding = _CountingBinding()+ inventory = _CountingInventory(binding)+ monkeypatch.setattr(+ google_module,+ "resolve_google_cli",+ lambda: GoogleCli(kind="gemini", argv_prefix=["gemini"]),+ )+ seen: list[object] = []++ async def _gemini_bound(_self: Any, *_args: Any, **kwargs: Any): # noqa: ANN202+ seen.append(kwargs["broker_binding"])+ yield "gemini-result"++ monkeypatch.setattr(GeminiWorker, "_spawn_bound", _gemini_bound)+ worker = GoogleCliWorker(capability_inventory=inventory) # type: ignore[arg-type]++ assert [event async for event in _spawn(worker, tmp_path)] == ["gemini-result"]+ assert seen == [binding]+ assert inventory.bind_calls == 1+ assert binding.close_calls == 1+++async def test_claude_to_codex_fallback_reuses_outer_binding(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ binding = _CountingBinding()+ inventory = _CountingInventory(binding)+ auth_failure = (+ b'{"type":"result","subtype":"error_during_execution",'+ b'"is_error":true,"result":"Failed to authenticate. API Error: 401",'+ b'"session_id":"claude-dead"}\n'+ )++ async def _claude_process(*_args: Any, **_kwargs: Any) -> _FakeProcess:+ return _FakeProcess(auth_failure, returncode=1)++ seen: list[object] = []++ async def _codex_bound(_self: Any, *_args: Any, **kwargs: Any): # noqa: ANN202+ seen.append(kwargs["broker_binding"])+ yield "codex-result"++ monkeypatch.setattr(claude_module, "create_worker_subprocess", _claude_process)+ monkeypatch.setattr(claude_module, "_resolve_claude_argv_prefix", lambda: ["claude"])+ monkeypatch.setattr(claude_module, "_resolve_provider_chain", lambda: ())+ monkeypatch.setattr(codex_module, "_codex_oauth_available", lambda: True)+ monkeypatch.setattr(codex_auth_state, "codex_needs_reauth", lambda: False)+ monkeypatch.setattr(codex_quota_state, "codex_in_quota_cooldown", lambda: False)+ monkeypatch.setattr(claude_auth_state, "mark_claude_auth_dead", lambda **_kwargs: None)+ monkeypatch.setattr(CodexDirectWorker, "_spawn_bound", _codex_bound)++ worker = ClaudeDirectWorker(capability_inventory=inventory) # type: ignore[arg-type]+ events = [+ event+ async for event in worker.spawn(+ "complete the mission",+ worktree=tmp_path,+ env={"CLAUDE_CODE_OAUTH_TOKEN": "test-token"},+ job=_Job(),+ worker_id="mission::0",+ log_dir=tmp_path / "logs",+ timeout_s=5.0,+ first_output_timeout_s=5.0,+ )+ ]++ assert events[-1] == "codex-result"+ assert seen == [binding]+ assert inventory.bind_calls == 1+ assert binding.close_calls == 1+++async def test_codex_to_claude_fallback_reuses_outer_binding(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ binding = _CountingBinding()+ inventory = _CountingInventory(binding)+ auth_failure = b'{"type":"error","message":"Failed to refresh token. Please log in again."}\n'++ async def _codex_process(*_args: Any, **_kwargs: Any) -> _FakeProcess:+ return _FakeProcess(auth_failure, returncode=1)++ seen: list[object] = []++ async def _claude_bound(_self: Any, *_args: Any, **kwargs: Any): # noqa: ANN202+ seen.append(kwargs["broker_binding"])+ yield "claude-result"++ monkeypatch.setattr(codex_module, "create_worker_subprocess", _codex_process)+ monkeypatch.setattr(claude_module, "_resolve_claude_binary", lambda: "claude")+ monkeypatch.setattr(missions_init, "_claude_cli_auth_viable", lambda: True)+ monkeypatch.setattr(codex_auth_state, "mark_codex_needs_reauth", lambda: None)+ monkeypatch.setattr(ClaudeDirectWorker, "_spawn_bound", _claude_bound)++ worker = CodexDirectWorker(capability_inventory=inventory) # type: ignore[arg-type]+ events = [+ event+ async for event in worker.spawn(+ "complete the mission",+ worktree=tmp_path,+ env={},+ job=_Job(),+ worker_id="mission::0",+ log_dir=tmp_path / "logs",+ timeout_s=5.0,+ first_output_timeout_s=5.0,+ )+ ]++ assert events[-1] == "claude-result"+ assert seen == [binding]+ assert inventory.bind_calls == 1+ assert binding.close_calls == 1+++def test_agy_mcp_settings_failure_raises_typed_error(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ monkeypatch.setattr(+ google_module, "ensure_isolated_home", lambda **_kwargs: str(tmp_path / "missing")+ )+ with pytest.raises(BrokerMcpConfigurationError, match="could not be written"):+ _build_agy_worker_env(+ {},+ mcp_servers={"jarvis_worker_tools": {"command": "python", "args": []}},+ )+++async def test_agy_reports_broker_unavailable_when_mcp_injection_fails(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ binding = _CountingBinding()+ inventory = _CountingInventory(binding)+ monkeypatch.setattr(+ google_module,+ "resolve_google_cli",+ lambda: GoogleCli(kind="agy", argv_prefix=["agy.exe"]),+ )+ monkeypatch.setattr(google_module, "_oauth_login_present", lambda *_args: True)+ monkeypatch.setattr(+ google_module, "ensure_isolated_home", lambda **_kwargs: str(tmp_path / "missing")+ )+ monkeypatch.setattr(+ google_module,+ "run_cli_over_pty",+ lambda *_args, **_kwargs: (_ for _ in ()).throw(+ AssertionError("agy must not start without its broker MCP configuration")+ ),+ )++ events = [+ event+ async for event in _spawn(+ GoogleCliWorker(capability_inventory=inventory), # type: ignore[arg-type]+ tmp_path,+ )+ ]++ assert events[0].external_capabilities["broker"]["status"] == "unavailable"+ assert events[-1].is_error is True+ assert events[-1].result.startswith("GoogleCliWorker broker MCP configuration failed:")+ assert inventory.bind_calls == 1+ assert binding.close_calls == 1diff --git a/tests/unit/brain/test_factory_supervisor_gateway.py b/tests/unit/brain/test_factory_supervisor_gateway.pynew file mode 100644index 0000000000..d7cadba606--- /dev/null+++ b/tests/unit/brain/test_factory_supervisor_gateway.py@@ -0,0 +1,43 @@+"""Factory registration guards for the shared supervisor-tool gateway."""++from __future__ import annotations++from types import SimpleNamespace++import pytest++from jarvis.brain.factory import _register_runtime_manager+from jarvis.brain.tool_gateway import BrainSupervisorToolGateway+from jarvis.core import runtime_refs+from jarvis.core.protocols import ToolResult+++class _Tool:+ name = "health"+ description = "Read the current health status."+ schema = {"type": "object", "properties": {}}+ risk_tier = "safe"++ async def execute(self, _arguments, _context):+ return ToolResult(success=True, output="ok")++[email protected](autouse=True)+def _clean_runtime_refs():+ runtime_refs._reset_for_tests()+ yield+ runtime_refs._reset_for_tests()+++def test_factory_registration_publishes_manager_and_public_gateway() -> None:+ manager = SimpleNamespace(+ _tools={"health": _Tool()},+ _tool_executor=SimpleNamespace(),+ )++ _register_runtime_manager(manager)++ assert runtime_refs.get_brain_manager() is manager+ gateway = runtime_refs.get_supervisor_tool_gateway()+ assert isinstance(gateway, BrainSupervisorToolGateway)+ assert [descriptor.name for descriptor in gateway.catalog()] == ["health"]diff --git a/tests/unit/brain/test_tool_gateway.py b/tests/unit/brain/test_tool_gateway.pynew file mode 100644index 0000000000..6718fd9d14--- /dev/null+++ b/tests/unit/brain/test_tool_gateway.py@@ -0,0 +1,141 @@+"""Public supervisor tool gateway catalog and execution contracts."""+from __future__ import annotations++from dataclasses import dataclass+from types import SimpleNamespace+from typing import Any+from uuid import uuid4++import pytest++from jarvis.brain.tool_gateway import BrainSupervisorToolGateway+from jarvis.core.protocols import SupervisorToolRequest, ToolResult+++@dataclass+class _Tool:+ name: str+ description: str = "Gateway test tool."+ schema: dict[str, Any] | None = None+ risk_tier: str = "monitor"++ def __post_init__(self) -> None:+ if self.schema is None:+ self.schema = {"type": "object", "properties": {}}++ async def execute(self, _args: dict[str, Any], _ctx: Any) -> ToolResult:+ raise AssertionError("The gateway must use ToolExecutor")+++class _Executor:+ def __init__(self) -> None:+ self.calls: list[tuple[_Tool, dict[str, Any], dict[str, Any]]] = []+ self.confirmed: list[tuple[Any, dict[str, Any]]] = []+ self.cancelled: list[Any] = []+ self.denied: list[tuple[str, str, Any]] = []++ async def execute(+ self,+ tool: _Tool,+ arguments: dict[str, Any],+ **kwargs: Any,+ ) -> ToolResult:+ self.calls.append((tool, arguments, kwargs))+ return ToolResult(success=True, output=tool.name)++ async def execute_confirmed(self, trace_id: Any, **kwargs: Any) -> ToolResult:+ self.confirmed.append((trace_id, kwargs))+ return ToolResult(success=True, output="confirmed")++ async def cancel_pending(self, trace_id: Any) -> bool:+ self.cancelled.append(trace_id)+ return True++ async def publish_guard_denied(+ self,+ name: str,+ reason: str,+ *,+ trace_id: Any,+ ) -> None:+ self.denied.append((name, reason, trace_id))+++def _request() -> SupervisorToolRequest:+ return SupervisorToolRequest(+ trace_id=uuid4(),+ origin="test",+ user_utterance="Use the connected tool.",+ )+++def test_catalog_is_secret_free_dynamic_and_versioned() -> None:+ tools = {"github/list": _Tool("github/list")}+ gateway = BrainSupervisorToolGateway(+ SimpleNamespace(_tools=tools, _tool_executor=_Executor())+ )++ first = gateway.catalog()+ first_version = gateway.catalog_version+ tools["github/get"] = _Tool("github/get")+ second = gateway.catalog()++ assert [item.name for item in first] == ["github/list"]+ assert [item.name for item in second] == ["github/get", "github/list"]+ assert gateway.catalog_version > first_version+ assert not hasattr(first[0], "execute")+++async def test_execute_resolves_the_current_tool_through_executor() -> None:+ executor = _Executor()+ original = _Tool("github/list")+ replacement = _Tool("github/list", description="Replacement")+ tools = {original.name: original}+ gateway = BrainSupervisorToolGateway(+ SimpleNamespace(_tools=tools, _tool_executor=executor)+ )+ tools[original.name] = replacement++ result = await gateway.execute(original.name, {"state": "open"}, _request())++ assert result.success is True+ assert executor.calls[0][0] is replacement+ assert executor.calls[0][1] == {"state": "open"}+++async def test_execute_fails_closed_after_tool_removal() -> None:+ gateway = BrainSupervisorToolGateway(+ SimpleNamespace(_tools={}, _tool_executor=_Executor())+ )++ result = await gateway.execute("github/list", {}, _request())++ assert result.success is False+ assert "no longer available" in str(result.error)+++async def test_confirmation_and_denial_operations_stay_behind_gateway() -> None:+ executor = _Executor()+ gateway = BrainSupervisorToolGateway(+ SimpleNamespace(_tools={}, _tool_executor=executor)+ )+ request = _request()++ confirmed = await gateway.execute_confirmed(request.trace_id, request)+ cancelled = await gateway.cancel_pending(request.trace_id)+ await gateway.publish_guard_denied(+ "gmail",+ "blocked for test",+ trace_id=request.trace_id,+ )++ assert confirmed.success is True+ assert cancelled is True+ assert executor.confirmed[0][0] == request.trace_id+ assert executor.cancelled == [request.trace_id]+ assert executor.denied == [+ ("gmail", "blocked for test", request.trace_id)+ ]diff --git a/tests/unit/cli_ctl/test_commands_missions.py b/tests/unit/cli_ctl/test_commands_missions.pyindex c61e738a22..3e5abd04bc 100644--- a/tests/unit/cli_ctl/test_commands_missions.py+++ b/tests/unit/cli_ctl/test_commands_missions.py@@ -19,6 +19,41 @@ def test_show(capture_api):assert capture_api["calls"][-1]["path"] == "/api/missions/m1"+def test_tool_approvals(capture_api):+ runner.invoke(app, ["missions", "tool-approvals", "m1"])+ call = capture_api["calls"][-1]+ assert call["method"] == "GET"+ assert call["path"] == "/api/missions/m1/tool-approvals"+++def test_approve_tool_requires_yes(capture_api):+ result = runner.invoke(app, ["missions", "approve-tool", "m1", "t1"])+ assert result.exit_code == 1+ assert capture_api["calls"] == []+++def test_approve_tool_with_yes(capture_api):+ result = runner.invoke(+ app,+ ["missions", "approve-tool", "m1", "t1", "--yes"],+ )+ assert result.exit_code == 0+ call = capture_api["calls"][-1]+ assert call["method"] == "POST"+ assert call["path"] == "/api/missions/m1/tool-approvals/t1/approve"+++def test_deny_tool_sends_audit_reason(capture_api):+ result = runner.invoke(+ app,+ ["missions", "deny-tool", "m1", "t1", "--reason", "not-now"],+ )+ assert result.exit_code == 0+ call = capture_api["calls"][-1]+ assert call["path"] == "/api/missions/m1/tool-approvals/t1/deny"+ assert call["body"] == {"reason": "not-now"}++def test_dispatch_requires_yes(capture_api):res = runner.invoke(app, ["missions", "dispatch", "do a thing"])assert res.exit_code == 1diff --git a/tests/unit/cli_ctl/test_dispatch.py b/tests/unit/cli_ctl/test_dispatch.pyindex 8f0a26dff9..e9d63cc523 100644--- a/tests/unit/cli_ctl/test_dispatch.py+++ b/tests/unit/cli_ctl/test_dispatch.py@@ -36,6 +36,7 @@ def test_launcher_invocations_not_routed():assert not is_control_invocation(["--wizard"])assert not is_control_invocation(["--check"])assert not is_control_invocation(["--debug"])+ assert not is_control_invocation(["--worker-tool-broker-stdio"])def test_control_invocations_routed():@@ -67,3 +68,11 @@ def test_main_does_not_route_launcher(monkeypatch):monkeypatch.setattr(jm, "_cmd_check", lambda: 0)rc = jm.main(["--check"])assert rc == 0+++def test_main_routes_frozen_worker_broker_mode(monkeypatch):+ from jarvis.missions.workers import broker_stdio++ monkeypatch.setattr(broker_stdio, "main", lambda: 17)++ assert jm.main(["--worker-tool-broker-stdio"]) == 17diff --git a/tests/unit/core/test_container_persistence_contract.py b/tests/unit/core/test_container_persistence_contract.pyindex 92212e456e..2889df20bf 100644--- a/tests/unit/core/test_container_persistence_contract.py+++ b/tests/unit/core/test_container_persistence_contract.py@@ -7,6 +7,7 @@ from pathlib import Path, PurePosixPath_REPO_ROOT = Path(__file__).resolve().parents[3]_DATA_DIR = PurePosixPath("/app/data")_CONFIG_PATH = _DATA_DIR / "jarvis.toml"+_HOME_DIR = _DATA_DIR / "home"def test_non_root_image_keeps_config_inside_the_persisted_writable_volume() -> None:@@ -16,11 +17,14 @@ def test_non_root_image_keeps_config_inside_the_persisted_writable_volume() -> Nassert f"JARVIS_CONFIG={_CONFIG_PATH.as_posix()}" in dockerfileassert f"JARVIS_DATA_DIR={_DATA_DIR.as_posix()}" in dockerfile+ assert f"HOME={_HOME_DIR.as_posix()}" in dockerfileassert _CONFIG_PATH.parent == _DATA_DIRassert f"jarvis-data:{_DATA_DIR.as_posix()}" in composechown_data = "chown -R jarvis:jarvis /app/data"non_root_user = "USER jarvis"assert chown_data in dockerfile+ assert "mkdir -p /app/data/home" in dockerfile+ assert "libportaudio2 curl git" in dockerfileassert non_root_user in dockerfileassert dockerfile.index(chown_data) < dockerfile.index(non_root_user)diff --git a/tests/unit/core/test_redact.py b/tests/unit/core/test_redact.pyindex 265868e134..6bee94cd41 100644--- a/tests/unit/core/test_redact.py+++ b/tests/unit/core/test_redact.py@@ -43,6 +43,18 @@ def test_labelled_secret_keeps_label_drops_value() -> None:assert "<redacted:labelled_secret>" in out+def test_labelled_secret_masks_python_and_json_mapping_previews() -> None:+ value = "supersecretvalue123"++ python_preview = safe_preview({"api_key": value})+ json_preview = safe_preview('{"access_token": "supersecretvalue123"}')++ assert value not in python_preview+ assert value not in json_preview+ assert "<redacted:labelled_secret>" in python_preview+ assert "<redacted:labelled_secret>" in json_preview++def test_git_sha1_is_not_treated_as_a_secret() -> None:# A 40-char hex is a git commit SHA — legitimate, must NOT be masked.sha = "a" * 40diff --git a/tests/unit/realtime/test_session.py b/tests/unit/realtime/test_session.pyindex d3a3cb7a44..4a07a4ab1b 100644--- a/tests/unit/realtime/test_session.py+++ b/tests/unit/realtime/test_session.py@@ -2,6 +2,8 @@ import asyncioimport pytest+from jarvis.brain.tool_gateway import BrainSupervisorToolGateway+from jarvis.core import runtime_refsfrom jarvis.core.events import (LatencyPhase,LatencySpan,@@ -1578,7 +1580,7 @@ async def test_instructions_carry_tool_role_when_bridge_active():instructions = provider.opened_with.instructionsassert "call the matching function" in instructions- assert "background-agent spawn" in instructions+ assert "Jarvis-Agent spawn" in instructions@pytest.mark.asyncio@@ -1639,6 +1641,9 @@ class _StubTool:risk_tier = "monitor"schema = {"type": "object", "properties": {}}+ async def execute(self, *_args, **_kwargs):+ raise AssertionError("Realtime must execute through the supervisor gateway")+class _StubExecutor:async def execute(self, _tool, _arguments, **_kwargs):@@ -1686,6 +1691,19 @@ def _session()+def wire_supervisor_gateway():+ previous = runtime_refs.get_supervisor_tool_gateway()++ def _wire(brain, executor):+ brain._tool_executor = executor+ gateway = BrainSupervisorToolGateway(brain)+ runtime_refs.set_supervisor_tool_gateway(gateway)++ yield _wire+ runtime_refs.set_supervisor_tool_gateway(previous)++@pytest.mark.asyncioasync def test_delegate_mode_declares_single_action_function():provider = FakeProvider([RealtimeEvent(type="turn_complete")])@@ -1930,10 +1948,10 @@ async def test_barge_in_detaches_late_delegate_result_from_new_turn():@pytest.mark.asyncio-async def test_direct_mode_builds_bridge_from_brain():+async def test_direct_mode_builds_bridge_from_brain(wire_supervisor_gateway):brain = FakeBrain()brain._tools = {"open_app": _StubTool()}- brain._tool_executor_ref = object()+ wire_supervisor_gateway(brain, _StubExecutor())provider = FakeProvider([RealtimeEvent(type="turn_complete")])sess = _session(provider, brain=brain, tool_mode="direct")@@ -1948,10 +1966,12 @@ async def test_direct_mode_builds_bridge_from_brain():@pytest.mark.asyncio-async def test_direct_mode_pushes_live_brain_tool_replacements_to_provider():+async def test_direct_mode_pushes_live_brain_tool_replacements_to_provider(+ wire_supervisor_gateway,+):brain = FakeBrain()brain._tools = {"old_tool": _StubTool()}- brain._tool_executor_ref = _StubExecutor()+ wire_supervisor_gateway(brain, _StubExecutor())provider = FakeProvider([RealtimeEvent(@@ -2168,11 +2188,13 @@ async def test_delegate_conversation_turn_keeps_the_session_response_event():@pytest.mark.asyncio-async def test_direct_tool_turn_keeps_the_session_response_event():+async def test_direct_tool_turn_keeps_the_session_response_event(+ wire_supervisor_gateway,+):bus = FakeBus()brain = FakeBrain(bus=bus)brain._tools = {"open_app": _StubTool()}- brain._tool_executor_ref = _StubExecutor()+ wire_supervisor_gateway(brain, _StubExecutor())provider = FakeProvider([RealtimeEvent(type="input_transcript", text="open it", is_final=True),@@ -2272,6 +2294,33 @@ async def test_delegate_failure_leaves_the_spoken_error_as_the_only_response():await sess.end(reason="test")+async def test_delegate_empty_brain_result_cannot_claim_action_success():+ brain = FakeBrain(replies=("",))+ provider = ToolResultGatedProvider(+ [+ RealtimeEvent(type="input_transcript", text="do it", is_final=True),+ RealtimeEvent(+ type="tool_call",+ call_id="empty-result-1",+ tool_name="jarvis_action",+ tool_args={"request": "do it"},+ ),+ ],+ [RealtimeEvent(type="turn_complete")],+ )+ sess = _session(provider, brain=brain)++ await sess.handle_control({"type": "audio_start", "sample_rate": 16_000})+ await sess.wait_finished()++ result = provider.session.tool_results[0][2]+ assert result["success"] is False+ assert "no grounded result" in result["error"]+ assert result["spoken_reply"]+ await sess.end(reason="test")++@pytest.mark.asyncioasync def test_delegate_timeout_cancels_brain_and_cannot_publish_late(monkeypatch):monkeypatch.setattr("jarvis.realtime.session._DELEGATE_TIMEOUT_S", 0.01)diff --git a/tests/unit/realtime/test_tools.py b/tests/unit/realtime/test_tools.pyindex a4aa18cebd..431e1a1e3e 100644--- a/tests/unit/realtime/test_tools.py+++ b/tests/unit/realtime/test_tools.py@@ -6,6 +6,8 @@ from types import SimpleNamespaceimport pytest+from jarvis.brain.tool_gateway import BrainSupervisorToolGateway+from jarvis.core import runtime_refsfrom jarvis.realtime.tools import RealtimeToolBridgefrom jarvis.safety.tool_executor import VOICE_CONFIRM_SENTINEL@@ -55,6 +57,19 @@ class FakeExecutor:self.denied.append((name, reason, trace_id))+def wire_gateway():+ previous = runtime_refs.get_supervisor_tool_gateway()++ def _wire(brain):+ gateway = BrainSupervisorToolGateway(brain)+ runtime_refs.set_supervisor_tool_gateway(gateway)+ return gateway++ yield _wire+ runtime_refs.set_supervisor_tool_gateway(previous)++def _bridge(*, name: str = "open_app", confirmation_required: bool = False):tool = FakeTool(name)executor = FakeExecutor(confirmation_required=confirmation_required)@@ -162,14 +177,17 @@ def test_bridge_declarations_keep_the_full_json_schema() -> None:@pytest.mark.asyncio-async def test_bridge_refreshes_replaced_brain_tools_and_denies_removed_tool():+async def test_bridge_refreshes_replaced_brain_tools_and_denies_removed_tool(+ wire_gateway,+):executor = FakeExecutor()old_tool = FakeTool("old_tool")new_tool = FakeTool("new_tool")brain = SimpleNamespace(_tools={"old_tool": old_tool},- _tool_executor_ref=executor,+ _tool_executor=executor,)+ wire_gateway(brain)bridge = RealtimeToolBridge.from_brain(brain, language="en")assert bridge is not None@@ -188,13 +206,16 @@ async def test_bridge_refreshes_replaced_brain_tools_and_denies_removed_tool():@pytest.mark.asyncio-async def test_bridge_refresh_retains_a_tool_awaiting_voice_confirmation():+async def test_bridge_refresh_retains_a_tool_awaiting_voice_confirmation(+ wire_gateway,+):executor = FakeExecutor(confirmation_required=True)pending_tool = FakeTool("pending_tool")brain = SimpleNamespace(_tools={"pending_tool": pending_tool},- _tool_executor_ref=executor,+ _tool_executor=executor,)+ wire_gateway(brain)bridge = RealtimeToolBridge.from_brain(brain, language="en")assert bridge is not Noneawait bridge.handle_user_transcript("Open Calculator")diff --git a/tests/unit/safety/test_tool_executor_voice_confirm.py b/tests/unit/safety/test_tool_executor_voice_confirm.pyindex f6ac0e81a9..d1fe909ee5 100644--- a/tests/unit/safety/test_tool_executor_voice_confirm.py+++ b/tests/unit/safety/test_tool_executor_voice_confirm.py@@ -17,7 +17,7 @@ import pytestfrom jarvis.core.bus import EventBusfrom jarvis.core.config import SafetyConfig-from jarvis.core.events import ActionExecuted+from jarvis.core.events import ActionApprovalRequired, ActionExecutedfrom jarvis.core.protocols import ExecutionContext, ToolResultfrom jarvis.safety.approval import ApprovalWorkflowfrom jarvis.safety.risk_tier import RiskTierEvaluator@@ -153,6 +153,41 @@ async def test_without_voice_confirm_ask_tier_still_blocks_on_approval() -> Noneassert result.success is True+async def test_non_conversational_approval_request_is_safe_and_correlated() -> None:+ executor, _approval, bus = _executor()+ requests: list[ActionApprovalRequired] = []++ async def _capture(event: ActionApprovalRequired) -> None:+ requests.append(event)++ bus.subscribe(ActionApprovalRequired, _capture)+ tool = _AskTool()+ trace_id = uuid4()++ result = await executor.execute(+ tool,+ args={"to": "[email protected]", "api_key": "sk-secret-value"},+ config_snapshot={+ "voice_confirm": False,+ "mission_id": "mission-123",+ "worker_id": "worker-456",+ },+ trace_id=trace_id,+ )++ assert result.success is True+ assert len(requests) == 1+ request = requests[0]+ assert request.trace_id == trace_id+ assert request.tool_name == tool.name+ assert request.reason == "risk_tier"+ assert request.mission_id == "mission-123"+ assert request.worker_id == "worker-456"+ assert request.expires_at_ns > request.timestamp_ns+ assert "sk-secret-value" not in request.args_preview++@pytest.mark.asyncioasync def test_safe_tier_is_not_deferred_even_with_voice_confirm() -> None:"""A tool that needs no confirmation runs immediately, never deferred."""@@ -172,8 +207,10 @@ async def test_gmail_read_is_not_deferred_for_voice_confirm() -> None:"""Repro 2026-06-19 (session dc533e39): a read-only gmail call (themorning-routine "check unread mail" step) must NOT trigger the sendconfirmation on a voice turn. Before the per-action risk fix the whole- gmail tool was ask-tier, so "Was habe ich heute auf dem Plan?" produced # i18n-allow: quotes the actual German voice utterance/output forensic bug content- "Soll ich die E-Mail wirklich senden?".""" # i18n-allow: quotes the actual German voice utterance/output forensic bug content+ gmail tool was ask-tier, so this input and response reproduced it:+ "Was habe ich heute auf dem Plan?" # i18n-allow: quoted runtime voice input+ "Soll ich die E-Mail wirklich senden?" # i18n-allow: quoted runtime voice output+ """import httpxfrom jarvis.plugins.tool.gmail_rest import GmailRestTool