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(safety): arm approvals before proposal events
Ruben Lütke958876bf303e
diff --git a/jarvis/safety/approval.py b/jarvis/safety/approval.pyindex dad5465615..e0ada592b3 100644--- a/jarvis/safety/approval.py+++ b/jarvis/safety/approval.py@@ -23,6 +23,37 @@ from jarvis.core.bus import EventBusfrom jarvis.core.events import ActionApproved, ActionDenied+class ApprovalTicket:+ """One armed approval decision that cannot lose an early bus response."""++ def __init__(+ self,+ workflow: ApprovalWorkflow,+ trace_id: UUID,+ future: asyncio.Future[tuple[bool, str]],+ ) -> None:+ self._workflow = workflow+ self.trace_id = trace_id+ self._future = future+ self._closed = False++ async def wait(self, timeout_s: float) -> tuple[bool, str]:+ """Wait for the first decision, defaulting safely to deny on timeout."""+ try:+ return await asyncio.wait_for(self._future, timeout=timeout_s)+ except TimeoutError:+ return (False, "timeout")+ finally:+ self.close()++ def close(self) -> None:+ """Remove an unresolved ticket so cancellation cannot leak state."""+ if self._closed:+ return+ self._closed = True+ self._workflow._discard(self.trace_id, self._future)++class ApprovalWorkflow:"""Holds one future per `trace_id` that waits for approve/deny."""@@ -34,10 +65,35 @@ class ApprovalWorkflow:bus.subscribe(ActionDenied, self._on_denied)def _resolve(self, trace_id: UUID, approved: bool, who_or_reason: str) -> None:- fut = self._pending.pop(trace_id, None)+ fut = self._pending.get(trace_id)if fut is not None and not fut.done():fut.set_result((approved, who_or_reason))+ def arm(self, trace_id: UUID) -> ApprovalTicket:+ """Register the decision future before an approval request is published.++ An approval received before this call is deliberately ignored. A trace+ may have only one active ticket, which keeps first-wins semantics and+ prevents unrelated events from pre-authorizing a future action.+ """+ if trace_id in self._pending:+ raise RuntimeError(f"approval trace {trace_id} is already armed")+ future: asyncio.Future[tuple[bool, str]] = (+ asyncio.get_running_loop().create_future()+ )+ self._pending[trace_id] = future+ return ApprovalTicket(self, trace_id, future)++ def _discard(+ self,+ trace_id: UUID,+ future: asyncio.Future[tuple[bool, str]],+ ) -> None:+ if self._pending.get(trace_id) is future:+ self._pending.pop(trace_id, None)+ if not future.done():+ future.cancel()+async def _on_approved(self, event: ActionApproved) -> None:self._resolve(event.trace_id, True, event.approved_by or "user")@@ -51,14 +107,13 @@ class ApprovalWorkflow:(approved: bool, who_or_reason: str)"""timeout = timeout_s if timeout_s is not None else self._timeout_s- loop = asyncio.get_running_loop()- fut: asyncio.Future[tuple[bool, str]] = loop.create_future()- self._pending[trace_id] = fut- try:- return await asyncio.wait_for(fut, timeout=timeout)- except TimeoutError:- self._pending.pop(trace_id, None)- return (False, "timeout")+ future = self._pending.get(trace_id)+ ticket = (+ ApprovalTicket(self, trace_id, future)+ if future is not None+ else self.arm(trace_id)+ )+ return await ticket.wait(timeout)# ------------------------------------------------------------------# Convenience: synthetic approve/deny for tests & the CLI launcherdiff --git a/jarvis/safety/tool_executor.py b/jarvis/safety/tool_executor.pyindex 7a067e2525..3e97585e1a 100644--- a/jarvis/safety/tool_executor.py+++ b/jarvis/safety/tool_executor.py@@ -60,7 +60,7 @@ class ToolExecutor:approval: ApprovalWorkflow,*,default_timeout_s: float = 60.0,- plausibility_config: "BrainPlausibilityConfig | None" = None,+ plausibility_config: BrainPlausibilityConfig | None = None,plausibility_context_fn: PlausibilityContextFn | None = None,) -> None:self._bus = bus@@ -90,7 +90,7 @@ class ToolExecutor:self,tool: Tool,decision: Any,- ) -> "PlausibilityDecision | None":+ ) -> PlausibilityDecision | None:"""Fetches the current plausibility context and checks it.Returns ``None`` if no context provider is registered, or the@@ -170,20 +170,8 @@ class ToolExecutor:))return ToolResult(success=False, output=None, error=str(exc))- # 2. Proposed event (the UI can use this as a live indicator). The brain's- # rationale rides along for the Session-Decision-Log — redacted + capped- # here so no raw secret reaches the bus / session DB / local diary.- await self._bus.publish(ActionProposed(- trace_id=tid,- tool_name=tool.name,- args=args,- risk_tier=decision.tier,- rationale=safe_preview(rationale),- ))-- # 2.5 Plausibility check (Phase 4): between the tier decision and- # approval. The result can force ``require_confirmation`` even- # when the tier workflow doesn't call for it (e.g. for ``monitor``).+ # 2. Plausibility check (Phase 4): the result can force confirmation+ # even when the tier workflow does not (for example, ``monitor``).plaus = self._evaluate_plausibility(tool, decision)if plaus is not None and plaus.reason != "ok":log.info(@@ -191,11 +179,33 @@ class ToolExecutor:tool.name, decision.tier, plaus.reason, plaus.require_confirmation,)- # 3. Approval (only if the tier workflow OR plausibility wants it)+ # 3. Arm approval BEFORE publishing ActionProposed. Subscribers such as+ # TaskAutoApprover may answer synchronously from that event; registering+ # afterward loses the answer and turns a valid grant into a timeout.approved_by = decision.approved_by or "auto"needs_confirm = self._evaluator.needs_user_confirmation(decision) or (plaus is not None and plaus.require_confirmation)+ voice_confirm = bool((config_snapshot or {}).get("voice_confirm"))+ approval_ticket = None+ if needs_confirm and not voice_confirm:+ approval_ticket = self._approval.arm(tid)++ # 3.5 Proposed event (the UI can use this as a live indicator). The+ # rationale is redacted and capped so no raw secret reaches the bus.+ try:+ await self._bus.publish(ActionProposed(+ trace_id=tid,+ tool_name=tool.name,+ args=args,+ risk_tier=decision.tier,+ rationale=safe_preview(rationale),+ ))+ except BaseException:+ if approval_ticket is not None:+ approval_ticket.close()+ raise+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@@ -204,7 +214,7 @@ class ToolExecutor:# ``execute_confirmed`` (AD-OE: the talker never awaits heavy/blocking# work on the turn). ``needs_confirm`` already excludes whitelist# downgrades, so this fires only for genuinely consequential tools.- if bool((config_snapshot or {}).get("voice_confirm")):+ if voice_confirm:self._pending_voice[tid] = (tool, dict(args))log.info("voice-confirm: deferring %s (tier=%s) for two-turn confirmation",@@ -219,14 +229,24 @@ class ToolExecutor:},error=VOICE_CONFIRM_SENTINEL,)- approved, who_or_reason = await self._approval.wait(tid, self._default_timeout_s)+ try:+ approved, who_or_reason = await self._approval.wait(+ tid, self._default_timeout_s+ )+ finally:+ if approval_ticket is not None:+ approval_ticket.close()if not approved:await self._bus.publish(ActionDenied(trace_id=tid,tool_name=tool.name,reason=who_or_reason,))- return ToolResult(success=False, output=None, error=f"approval-denied ({who_or_reason})")+ return ToolResult(+ success=False,+ output=None,+ error=f"approval-denied ({who_or_reason})",+ )approved_by = who_or_reason # "user" or "auto"# 4. Executediff --git a/tests/integration/test_task_auto_approver.py b/tests/integration/test_task_auto_approver.pyindex 44b99930b7..6165cdfae6 100644--- a/tests/integration/test_task_auto_approver.py+++ b/tests/integration/test_task_auto_approver.py@@ -11,17 +11,38 @@ block.from __future__ import annotationsimport asyncio+from typing import Anyfrom uuid import uuid4import pytestfrom jarvis.core.bus import EventBus+from jarvis.core.config import SafetyConfigfrom jarvis.core.events import ActionApproved, ActionProposed+from jarvis.core.protocols import ExecutionContext, ToolResult+from jarvis.safety import ApprovalWorkflow, RiskTierEvaluator, ToolExecutorfrom jarvis.tasks.approval_bridge import TaskAutoApproverpytestmark = pytest.mark.phase5+class _AskTool:+ name = "buffer"+ risk_tier = "ask"+ schema: dict[str, Any] = {"type": "object", "properties": {}}++ def __init__(self) -> None:+ self.calls = 0+ self.approved_by = ""++ async def execute(+ self, _args: dict[str, Any], ctx: ExecutionContext+ ) -> ToolResult:+ self.calls += 1+ self.approved_by = ctx.approved_by+ return ToolResult(success=True, output="executed")++async def _collect_approvals(bus: EventBus) -> list[ActionApproved]:got: list[ActionApproved] = []@@ -49,6 +70,29 @@ async def test_approves_armed_tool_on_its_trace() -> None:assert approvals[0].approved_by == "scheduled-task:abc"+async def test_pre_authorized_tool_executes_without_approval_race() -> None:+ """An approval published from ActionProposed must reach ToolExecutor.wait."""+ bus = EventBus()+ approval = ApprovalWorkflow(bus, timeout_s=0.05)+ executor = ToolExecutor(+ bus,+ RiskTierEvaluator(SafetyConfig()),+ approval,+ default_timeout_s=0.05,+ )+ approver = TaskAutoApprover(bus)+ tool = _AskTool()+ trace_id = uuid4()+ approver.arm(trace_id, [tool.name], approved_by="scheduled-task:abc")++ result = await executor.execute(tool, {}, trace_id=trace_id)++ assert result.success is True+ assert result.output == "executed"+ assert tool.calls == 1+ assert tool.approved_by == "scheduled-task:abc"++async def test_ignores_tool_not_in_grant() -> None:bus = EventBus()approver = TaskAutoApprover(bus)diff --git a/tests/unit/safety/test_approval_workflow.py b/tests/unit/safety/test_approval_workflow.pynew file mode 100644index 0000000000..ec01654010--- /dev/null+++ b/tests/unit/safety/test_approval_workflow.py@@ -0,0 +1,47 @@+"""Race and cleanup guards for the first-wins approval workflow."""++from __future__ import annotations++from uuid import uuid4++import pytest++from jarvis.core.bus import EventBus+from jarvis.safety.approval import ApprovalWorkflow+++async def test_armed_ticket_keeps_a_decision_that_arrives_before_wait() -> None:+ workflow = ApprovalWorkflow(EventBus())+ trace_id = uuid4()+ workflow.arm(trace_id)++ await workflow.approve(trace_id, who="test-user")+ approved, who = await workflow.wait(trace_id, timeout_s=0.01)++ assert approved is True+ assert who == "test-user"+++async def test_decision_before_arm_never_pre_authorizes_future_action() -> None:+ workflow = ApprovalWorkflow(EventBus())+ trace_id = uuid4()++ await workflow.approve(trace_id, who="too-early")+ approved, reason = await workflow.wait(trace_id, timeout_s=0.01)++ assert approved is False+ assert reason == "timeout"+++async def test_duplicate_arm_is_rejected() -> None:+ workflow = ApprovalWorkflow(EventBus())+ trace_id = uuid4()+ ticket = workflow.arm(trace_id)+ try:+ with pytest.raises(RuntimeError, match="already armed"):+ workflow.arm(trace_id)+ finally:+ ticket.close()