Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(runs): capture tool output + brain rationale for the Session-Decision-Log
Ruben Lütke6fdc775a021e
diff --git a/jarvis/brain/tool_use_loop.py b/jarvis/brain/tool_use_loop.pyindex 125e3db3aa..7e66de1c7e 100644--- a/jarvis/brain/tool_use_loop.py+++ b/jarvis/brain/tool_use_loop.py@@ -665,6 +665,10 @@ class ToolUseLoop:"voice_confirm": voice_confirm,},trace_id=tid,+ # Session-Decision-Log: the model's natural-language text+ # emitted alongside this tool call IS the "why". Captured+ # for free (no extra call); the executor redacts + caps it.+ rationale=agg.text or "",)# Two-turn voice/chat confirmation: the executor deferred this# consequential tool instead of blocking. Speak a shortdiff --git a/jarvis/core/events.py b/jarvis/core/events.pyindex 391b9a7751..9a13c8fd4b 100644--- a/jarvis/core/events.py+++ b/jarvis/core/events.py@@ -185,6 +185,12 @@ class ActionProposed(Event):tool_name: str = ""args: dict[str, Any] = field(default_factory=dict)risk_tier: RiskTier = "safe"+ # Session-Decision-Log: the brain's natural-language rationale emitted+ # alongside this tool call (the model's ``text`` block next to the+ # ``tool_use`` block). Captured "for free" — no extra model call — so the+ # Run Inspector + local diary can show *why* Jarvis chose this action.+ # Already redacted + length-capped by the ToolExecutor before publish.+ rationale: str = ""@dataclass(frozen=True, slots=True)@@ -205,6 +211,11 @@ class ActionExecuted(Event):success: bool = Falseduration_ms: int = 0error: str | None = None+ # Session-Decision-Log: a short preview of what the tool returned+ # (``ToolResult.output``). Already redacted + length-capped by the+ # ToolExecutor before publish (``jarvis.core.redact.safe_preview``) so no+ # raw secret reaches the bus / session DB / local diary.+ output_preview: str = ""# ----------------------------------------------------------------------diff --git a/jarvis/core/redact.py b/jarvis/core/redact.pynew file mode 100644index 0000000000..7b41134a68--- /dev/null+++ b/jarvis/core/redact.py@@ -0,0 +1,115 @@+"""Redact-and-cap helper for telemetry previews (decision-log / Run Inspector).++The Session-Decision-Log persists, per action, a short preview of what a tool+returned (``ActionExecuted.output_preview``) and the brain's natural-language+rationale (``ActionProposed.rationale``). Both are derived from live data that+could *theoretically* echo a credential (a tool that printed an API key, a model+that quoted a token back), and both land on disk in ``data/sessions.db`` and in+the local Markdown diary. So neither may be persisted raw.++``safe_preview`` is the single gate every such preview passes before it touches+an event/the DB/the diary: stringify -> mask credential shapes -> cap length.++It is **regex-only** (no LLM call) so it is safe to run inline on the bus-publish+path without adding latency (cf. AP-11 on the voice path). The credential shapes+mirror ``jarvis/memory/wiki/secret_guard.py`` (the wiki write-guard) and the+provider key shapes in ``jarvis/core/config.py`` — kept here as an independent+copy because this module lives in the lowest layer (``jarvis.core``) and must not+import upward into ``jarvis.memory``. The two differ in intent: ``secret_guard``+*detects and blocks*; this *masks and keeps* a usable, secret-free preview.+"""+from __future__ import annotations++import re+from typing import Any++# Default cap for a persisted preview. Big enough to be useful when scrolling+# back through the decision log, small enough that a tool cannot smuggle a large+# blob (a screenshot data-URI, a giant JSON dump) into the session DB / diary.+DEFAULT_PREVIEW_CHARS = 2048++# --- credential shapes (mirror of secret_guard._PATTERNS, for substitution) ---+_REDACTORS: tuple[tuple[str, re.Pattern[str]], ...] = (+ # OpenAI-style keys: sk-, sk-proj-, sk-ant-, sk-or-, sk-live-, >=20 trailing.+ ("openai_key", re.compile(r"\bsk-(?:proj-|ant-|or-|live-)?[A-Za-z0-9_-]{20,}\b")),+ # Provider keys: AIza… (Google), xai-…, gsk_… (Groq), gh[pousr]_ (GitHub).+ (+ "provider_key",+ re.compile(+ r"\b(?:AIza[0-9A-Za-z_-]{30,}"+ r"|xai-[A-Za-z0-9]{20,}"+ r"|gsk_[A-Za-z0-9]{20,}"+ r"|gh[pousr]_[A-Za-z0-9]{30,})\b"+ ),+ ),+ # Bearer / Authorization tokens.+ ("bearer_token", re.compile(r"\b[Bb]earer\s+[A-Za-z0-9._\-]{16,}\b")),+ (+ "authorization_header",+ re.compile(r"(?im)^\s*authorization\s*[:=]\s*\S{12,}\s*$"),+ ),+ # Inline "api_key = …" / "password: …" / "secret = …" / "token: …".+ (+ "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"['\"]?[^\s'\"]{8,}"+ ),+ ),+ # JWT (three base64url segments separated by dots).+ ("jwt", re.compile(r"\beyJ[A-Za-z0-9_-]{6,}\.eyJ[A-Za-z0-9_-]{3,}\.[A-Za-z0-9_-]{3,}\b")),+ # Private-key PEM headers (mask the whole block start marker).+ ("pem_private_key", re.compile(r"-----BEGIN (?:RSA |EC |OPENSSH |DSA |PGP )?PRIVATE KEY-----")),+ # Long opaque secrets: >=64 contiguous hex (SHA-256 is 64, a git SHA-1 is 40+ # and stays untouched) or >=64 contiguous base64.+ ("long_hex_secret", re.compile(r"\b[0-9a-fA-F]{64,}\b")),+ ("long_base64_secret", re.compile(r"\b[A-Za-z0-9+/]{64,}={0,2}\b")),+)++# The ``labelled_secret`` pattern keeps its label group (so "api_key=" stays+# readable) and only masks the value; every other pattern masks the whole match.+_KEEP_PREFIX = frozenset({"labelled_secret"})+++def redact_secrets(text: str) -> str:+ """Mask credential-shaped substrings, leaving the rest of ``text`` intact.++ Pure function. Each credential shape is replaced by ``<redacted:NAME>`` so a+ human reading the decision log still sees *that* a secret was there (and of+ what kind) without the value. The ``labelled_secret`` shape keeps its label+ (``api_key=<redacted:labelled_secret>``) for readability.+ """+ if not text:+ return text+ out = text+ for name, pat in _REDACTORS:+ replacement = (+ (r"\1" + f"<redacted:{name}>") if name in _KEEP_PREFIX else f"<redacted:{name}>"+ )+ out = pat.sub(replacement, out)+ return out+++def safe_preview(value: Any, *, max_chars: int = DEFAULT_PREVIEW_CHARS) -> str:+ """Stringify ``value`` -> mask credential shapes -> cap to ``max_chars``.++ The one gate every persisted telemetry preview passes. Never raises: a value+ whose ``str()`` blows up degrades to its type name. The cap appends a+ ``… (+N more chars)`` marker so a truncated preview is honest about being+ truncated rather than silently cut.+ """+ if value is None:+ return ""+ try:+ text = value if isinstance(value, str) else str(value)+ except Exception: # noqa: BLE001 — a preview must never crash the caller+ return f"<{type(value).__name__}>"+ text = redact_secrets(text)+ if max_chars > 0 and len(text) > max_chars:+ dropped = len(text) - max_chars+ text = text[:max_chars] + f"… (+{dropped} more chars)"+ return text+++__all__ = ["DEFAULT_PREVIEW_CHARS", "redact_secrets", "safe_preview"]diff --git a/jarvis/safety/tool_executor.py b/jarvis/safety/tool_executor.pyindex 110f68eb66..c8444183a0 100644--- a/jarvis/safety/tool_executor.py+++ b/jarvis/safety/tool_executor.py@@ -20,6 +20,7 @@ from uuid import UUID, uuid4from jarvis.core.bus import EventBusfrom jarvis.core.events import ActionDenied, ActionExecuted, ActionProposedfrom jarvis.core.protocols import ExecutionContext, Tool, ToolResult, Transcript+from jarvis.core.redact import safe_previewfrom .approval import ApprovalWorkflowfrom .risk_tier import ActionBlocked, RiskTierEvaluator@@ -126,6 +127,7 @@ class ToolExecutor:config_snapshot: dict[str, Any] | None = None,memory_read: Any | None = None,trace_id: UUID | None = None,+ rationale: str = "",) -> ToolResult:tid = trace_id or uuid4()t_start = time.perf_counter()@@ -141,12 +143,15 @@ class ToolExecutor:))return ToolResult(success=False, output=None, error=str(exc))- # 2. Proposed-Event (UI kann das als Live-Indikator nutzen)+ # 2. Proposed-Event (UI kann das als Live-Indikator nutzen). 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): zwischen Tier-Decision und@@ -225,6 +230,7 @@ class ToolExecutor:success=result.success,duration_ms=duration_ms,error=result.error,+ output_preview=safe_preview(result.output),))return result@@ -286,6 +292,7 @@ class ToolExecutor:success=result.success,duration_ms=duration_ms,error=result.error,+ output_preview=safe_preview(result.output),))return resultdiff --git a/jarvis/sessions/recorder.py b/jarvis/sessions/recorder.pyindex 381c2248ff..d61e976f94 100644--- a/jarvis/sessions/recorder.py+++ b/jarvis/sessions/recorder.py@@ -764,6 +764,10 @@ def _payload_for(event: Event) -> dict[str, Any]:"tool_name","args_preview","output_preview",+ # Session-Decision-Log: the brain's rationale on ActionProposed (the+ # "why"). Already redacted + capped at publish time by the ToolExecutor,+ # so persisting it raw here is safe — no unredacted secret can arrive.+ "rationale","success","duration_ms","duration_s",diff --git a/tests/unit/core/test_redact.py b/tests/unit/core/test_redact.pynew file mode 100644index 0000000000..75619b6e31--- /dev/null+++ b/tests/unit/core/test_redact.py@@ -0,0 +1,76 @@+"""``jarvis.core.redact`` — the redact-and-cap gate for decision-log previews.++Every persisted telemetry preview (a tool's ``output_preview``, the brain's+``rationale``) passes through ``safe_preview`` before it reaches the bus / the+session DB / the local Markdown diary. These tests pin the two guarantees that+make persisting such previews safe: credential shapes are masked, and the length+is capped so a tool cannot smuggle a large blob into the log.+"""+from __future__ import annotations++from jarvis.core.redact import DEFAULT_PREVIEW_CHARS, redact_secrets, safe_preview+++def test_plain_text_passes_through_untouched() -> None:+ text = "Listed 3 GCP projects: alpha, beta, gamma. Total spend last month: 12.40 EUR."+ assert safe_preview(text) == text+++def test_openai_style_key_is_masked() -> None:+ leaked = "your key is sk-proj-AbCdEf0123456789ghijKLmnopQRstuv and it works"+ out = safe_preview(leaked)+ assert "sk-proj-AbCdEf0123456789ghijKLmnopQRstuv" not in out+ assert "<redacted:openai_key>" in out+ # The surrounding prose survives so the log stays readable.+ assert out.startswith("your key is ")+++def test_provider_and_bearer_tokens_are_masked() -> None:+ google = "AIzaSyA1234567890abcdefghijklmnopqrstuvwx"+ bearer = "Bearer abcDEF1234567890ghijKL"+ out = safe_preview(f"google={google}\nauth={bearer}")+ assert google not in out+ assert "abcDEF1234567890ghijKL" not in out+ assert "<redacted:provider_key>" in out+ assert "<redacted:bearer_token>" in out+++def test_labelled_secret_keeps_label_drops_value() -> None:+ out = safe_preview("api_key=supersecretvalue123")+ assert "supersecretvalue123" not in out+ # Label survives for readability; value is gone.+ assert "api_key=" in out+ assert "<redacted:labelled_secret>" in out+++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" * 40+ assert sha in safe_preview(f"committed at {sha}")+++def test_length_is_capped_with_honest_marker() -> None:+ # Spaced prose so it is long without being one 64+ char credential-shaped run.+ big = "word " * (DEFAULT_PREVIEW_CHARS) # ~5x over the cap+ out = safe_preview(big)+ assert len(out) <= DEFAULT_PREVIEW_CHARS + 40 # cap + short marker+ assert "more chars)" in out+++def test_custom_cap_is_respected() -> None:+ out = safe_preview("abcdefghij", max_chars=4)+ assert out.startswith("abcd")+ assert "more chars)" in out+++def test_none_and_non_string_values_are_stringified() -> None:+ assert safe_preview(None) == ""+ assert safe_preview({"projects": 3}) == "{'projects': 3}"+ assert safe_preview(42) == "42"+++def test_redact_secrets_is_pure_and_idempotent() -> None:+ once = redact_secrets("token: eyJabcdef.eyJ123456.sigABC123")+ twice = redact_secrets(once)+ assert once == twice+ assert "<redacted:jwt>" in oncediff --git a/tests/unit/safety/test_tool_executor_decision_log.py b/tests/unit/safety/test_tool_executor_decision_log.pynew file mode 100644index 0000000000..79c1409d90--- /dev/null+++ b/tests/unit/safety/test_tool_executor_decision_log.py@@ -0,0 +1,133 @@+"""Session-Decision-Log capture in the ``ToolExecutor``.++The executor is the one authorized tool chokepoint, so it is where the two+decision-log data points are captured: the tool's output (onto+``ActionExecuted.output_preview``) and the brain's rationale (onto+``ActionProposed.rationale``). Both must be redacted + capped at publish time so+no raw secret rides the bus into the session DB / local diary.+"""+from __future__ import annotations++import asyncio+from typing import Any+from uuid import uuid4++import pytest++from jarvis.core.bus import EventBus+from jarvis.core.config import SafetyConfig+from jarvis.core.events import ActionExecuted, ActionProposed+from jarvis.core.protocols import ExecutionContext, ToolResult+from jarvis.safety.approval import ApprovalWorkflow+from jarvis.safety.risk_tier import RiskTierEvaluator+from jarvis.safety.tool_executor import ToolExecutor+++class _SafeTool:+ name = "cli_gcloud"+ risk_tier = "safe"+ schema: dict[str, Any] = {}++ def __init__(self, output: Any = "ok") -> None:+ self._output = output++ async def execute(self, args: dict[str, Any], ctx: ExecutionContext) -> ToolResult:+ return ToolResult(success=True, output=self._output)+++def _executor(bus: EventBus) -> ToolExecutor:+ return ToolExecutor(+ bus=bus,+ evaluator=RiskTierEvaluator(SafetyConfig()),+ approval=ApprovalWorkflow(bus),+ )+++async def _drain(bus: EventBus) -> None:+ await asyncio.sleep(0)+ await asyncio.sleep(0)+++async def test_output_preview_is_published_on_action_executed() -> None:+ bus = EventBus()+ seen: list[ActionExecuted] = []++ async def _cap(e: ActionExecuted) -> None:+ seen.append(e)++ bus.subscribe(ActionExecuted, _cap) # type: ignore[arg-type]+ await _executor(bus).execute(+ _SafeTool(output="Billing for project alpha: 12.40 EUR"), args={}, trace_id=uuid4(),+ )+ await _drain(bus)+ assert seen and seen[0].output_preview == "Billing for project alpha: 12.40 EUR"+++async def test_output_preview_is_redacted() -> None:+ bus = EventBus()+ seen: list[ActionExecuted] = []++ async def _cap(e: ActionExecuted) -> None:+ seen.append(e)++ bus.subscribe(ActionExecuted, _cap) # type: ignore[arg-type]+ secret = "sk-proj-AbCdEf0123456789ghijKLmnopQRstuv"+ await _executor(bus).execute(+ _SafeTool(output=f"token echoed back: {secret}"), args={}, trace_id=uuid4(),+ )+ await _drain(bus)+ assert seen+ assert secret not in seen[0].output_preview+ assert "<redacted:openai_key>" in seen[0].output_preview+++async def test_output_preview_is_length_capped() -> None:+ bus = EventBus()+ seen: list[ActionExecuted] = []++ async def _cap(e: ActionExecuted) -> None:+ seen.append(e)++ bus.subscribe(ActionExecuted, _cap) # type: ignore[arg-type]+ # Spaced prose: long, but not one credential-shaped 64+ char run.+ await _executor(bus).execute(+ _SafeTool(output="result row " * 1000), args={}, trace_id=uuid4(),+ )+ await _drain(bus)+ assert seen+ assert len(seen[0].output_preview) < 11_000+ assert "more chars)" in seen[0].output_preview+++async def test_rationale_is_published_on_action_proposed() -> None:+ bus = EventBus()+ seen: list[ActionProposed] = []++ async def _cap(e: ActionProposed) -> None:+ seen.append(e)++ bus.subscribe(ActionProposed, _cap) # type: ignore[arg-type]+ why = "You asked for your GCP spend, so I call the billing CLI instead of guessing."+ await _executor(bus).execute(+ _SafeTool(), args={}, trace_id=uuid4(), rationale=why,+ )+ await _drain(bus)+ assert seen and seen[0].rationale == why+++async def test_rationale_defaults_empty_when_not_supplied() -> None:+ bus = EventBus()+ seen: list[ActionProposed] = []++ async def _cap(e: ActionProposed) -> None:+ seen.append(e)++ bus.subscribe(ActionProposed, _cap) # type: ignore[arg-type]+ await _executor(bus).execute(_SafeTool(), args={}, trace_id=uuid4())+ await _drain(bus)+ assert seen and seen[0].rationale == ""diff --git a/tests/unit/sessions/test_recorder_decision_log.py b/tests/unit/sessions/test_recorder_decision_log.pynew file mode 100644index 0000000000..e7f9c9f9a7--- /dev/null+++ b/tests/unit/sessions/test_recorder_decision_log.py@@ -0,0 +1,30 @@+"""The Run Inspector + local diary read the decision-log fields out of+voice_events. Guards that the recorder whitelist carries the brain rationale+(ActionProposed.rationale) and the tool output preview (ActionExecuted.output_preview)+so they survive into the persisted event stream."""+from jarvis.core.events import ActionExecuted, ActionProposed+from jarvis.sessions.recorder import _payload_for+++def test_payload_carries_rationale_from_action_proposed():+ p = _payload_for(ActionProposed(+ tool_name="cli_gcloud", risk_tier="ask",+ rationale="You asked for spend, so I call the billing CLI.",+ ))+ assert p["rationale"] == "You asked for spend, so I call the billing CLI."+++def test_payload_carries_output_preview_from_action_executed():+ p = _payload_for(ActionExecuted(+ tool_name="cli_gcloud", success=True, duration_ms=120,+ output_preview="Billing for project alpha: 12.40 EUR",+ ))+ assert p["output_preview"] == "Billing for project alpha: 12.40 EUR"+++def test_empty_rationale_is_harmless():+ # No rationale -> empty string in the payload (the recorder skips None, not+ # "", and must keep recoverable=False). An empty rationale is just absent+ # signal, never raw noise.+ p = _payload_for(ActionProposed(tool_name="cli_gcloud", risk_tier="safe"))+ assert p.get("rationale", "") == ""