Skip to content

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.

chore: auto-save WIP via Claude stop-hook safety net (2026-06-30 19:51)

Ruben Lütke3a6f0108edda
diff --git a/jarvis/missions/init.py b/jarvis/missions/init.py
index 2dd2980a9b..b0793d9ca6 100644
--- a/jarvis/missions/init.py
+++ b/jarvis/missions/init.py
@@ -969,7 +969,9 @@ async def bootstrap_missions(
import shutil
from jarvis.core.config import get_provider_secret
- if not (shutil.which("gemini") or shutil.which("gemini.cmd")) and get_provider_secret("gemini"):
+ if not (
+ shutil.which("gemini") or shutil.which("gemini.cmd")
+ ) and get_provider_secret("gemini"):
logger.info(
"Mission worker -> ApiAgentWorker('gemini'): no Gemini CLI, "
"running in-process on the Gemini API key."
diff --git a/jarvis/plugins/tts/__init__.py b/jarvis/plugins/tts/__init__.py
index 228ac5e5e9..ecb5513644 100644
--- a/jarvis/plugins/tts/__init__.py
+++ b/jarvis/plugins/tts/__init__.py
@@ -269,7 +269,10 @@ def _build_provider(tts_cfg: Any, provider: str) -> Any:
allow_sapi5_fallback=allow_sapi5,
)
- if provider in ("cartesia", "cartesia-sonic", "cartesia-sonic3", "cartesia-sonic-3", "cartesia-sonic-3.5"):
+ if provider in (
+ "cartesia", "cartesia-sonic", "cartesia-sonic3", "cartesia-sonic-3",
+ "cartesia-sonic-3.5",
+ ):
try:
from jarvis.plugins.tts.cartesia_tts import (
DEFAULT_MODEL_ID,
diff --git a/jarvis/runs/analyzer.py b/jarvis/runs/analyzer.py
index 6e8aba2a8a..f2916f7348 100644
--- a/jarvis/runs/analyzer.py
+++ b/jarvis/runs/analyzer.py
@@ -15,6 +15,8 @@ from jarvis.runs.constants import (
OUTCOME_FAILED,
OUTCOME_PARTIAL,
OUTCOME_SUCCESS,
+ RATIONALE_MODEL,
+ RATIONALE_RULE,
ROLE_ERROR,
ROLE_JARVIS,
ROLE_SYSTEM,
@@ -79,34 +81,71 @@ def build_latency(events: list[VoiceEventRow]) -> list[LatencyEntry]:
return out
+def _approval_rationale(by: str) -> str:
+ """Honest plain-language reading of a CAPTURED approval source — not a guess."""
+ b = (by or "").lower()
+ if b == "whitelist":
+ return "Auto-approved — this action is on your allow-list."
+ if b == "user":
+ return "You approved this action."
+ if b == "auto":
+ return "Auto-approved — a low-risk action."
+ return f"Approved ({by})." if by else "Approved."
+
+
def build_decision_path(events: list[VoiceEventRow]) -> list[DecisionStep]:
+ """The decision path, now carrying the honest "why" per step.
+
+ The route step prefers the model's OWN words (ActionProposed.rationale,
+ captured for free) tagged ``model``; every other step gets a deterministic
+ ``rule`` explanation built from a captured fact (approval source, denial
+ reason, provider, fallback). Nothing here is fabricated."""
steps: list[DecisionStep] = []
providers_seen: list[str] = []
for e in sorted(events, key=lambda x: x.ts_ms):
p = e.payload
if e.kind == "IntentClassified":
+ intent = p.get("intent", "?")
+ risk = p.get("risk_tier", "?")
steps.append(DecisionStep(
kind=DECISION_TIER,
- label=f"intent: {p.get('intent', '?')}",
- detail=f"risk={p.get('risk_tier', '?')}",
+ label=f"intent: {intent}",
+ detail=f"risk={risk}",
+ rationale=f"Recognized as a '{intent}' request (risk tier: {risk}).",
+ rationale_source=RATIONALE_RULE,
))
elif e.kind == "ActionProposed":
+ tool = p.get("tool_name", "?")
+ risk = p.get("risk_tier", "?")
+ model_why = str(p.get("rationale", "") or "").strip()
+ if model_why:
+ rationale, source = model_why, RATIONALE_MODEL
+ else:
+ rationale, source = f"Chose the {tool} tool (risk: {risk}).", RATIONALE_RULE
steps.append(DecisionStep(
kind=DECISION_ROUTE,
- label=f"proposed: {p.get('tool_name', '?')}",
- detail=f"risk={p.get('risk_tier', '?')}",
+ label=f"proposed: {tool}",
+ detail=f"risk={risk}",
+ rationale=rationale,
+ rationale_source=source,
))
elif e.kind == "ActionApproved":
+ by = p.get("approved_by", "auto")
steps.append(DecisionStep(
kind=DECISION_RISK,
label=f"approved: {p.get('tool_name', '?')}",
- detail=f"by={p.get('approved_by', 'auto')}",
+ detail=f"by={by}",
+ rationale=_approval_rationale(by),
+ rationale_source=RATIONALE_RULE,
))
elif e.kind == "ActionDenied":
+ reason = str(p.get("reason", "")).strip()
steps.append(DecisionStep(
kind=DECISION_RISK,
label=f"denied: {p.get('tool_name', '?')}",
- detail=str(p.get("reason", "")),
+ detail=reason or None,
+ rationale=(f"Blocked — {reason}." if reason else "Blocked by a safety rule."),
+ rationale_source=RATIONALE_RULE,
))
elif e.kind == "BrainTurnStarted":
provider = str(p.get("provider", ""))
@@ -117,12 +156,19 @@ def build_decision_path(events: list[VoiceEventRow]) -> list[DecisionStep]:
kind=DECISION_BRAIN,
label=f"brain: {provider or '?'}",
detail=(f"model={model}" if model else None),
+ rationale=(
+ f"Answered by {provider}" + (f" ({model})" if model else "") + "."
+ if provider else "Answered by the configured brain."
+ ),
+ rationale_source=RATIONALE_RULE,
))
elif e.kind == "JarvisAgentTaskStarted":
steps.append(DecisionStep(
kind=DECISION_MISSION,
label="spawned sub-agent mission",
detail=str(p.get("model", "")) or None,
+ rationale="Handed the task to a background sub-agent.",
+ rationale_source=RATIONALE_RULE,
))
# A second distinct provider across the turn means the smart-fallback fired.
distinct = [p for i, p in enumerate(providers_seen) if p and p not in providers_seen[:i]]
@@ -131,10 +177,46 @@ def build_decision_path(events: list[VoiceEventRow]) -> list[DecisionStep]:
kind=DECISION_FALLBACK,
label="provider fallback",
detail=" -> ".join(distinct),
+ rationale=f"Switched provider — {distinct[0]} → {distinct[-1]} (a fallback fired).",
+ rationale_source=RATIONALE_RULE,
))
return steps
+def attach_tool_io(events: list[VoiceEventRow], tools: list[ToolCall]) -> list[ToolCall]:
+ """Surface the already-captured command + result onto the tool rows.
+
+ ``ToolCallStarted`` carries the tool name + ``args_preview`` (the command);
+ ``ToolCallCompleted`` carries ``output_preview`` (the result) but no name, so
+ it is paired with the most recent Started in chronological order. A tool seen
+ only here (no ActionProposed row) is added so its I/O is never silently
+ dropped. All fields are already redacted/length-capped upstream."""
+ by_name = {t.name: t for t in tools}
+ pending: str | None = None
+ for e in sorted(events, key=lambda x: x.ts_ms):
+ p = e.payload
+ if e.kind == "ToolCallStarted":
+ name = str(p.get("tool_name") or "")
+ cmd = str(p.get("args_preview") or "")
+ pending = name or pending
+ if name:
+ tc = by_name.get(name)
+ if tc is None:
+ tc = ToolCall(name=name)
+ tools.append(tc)
+ by_name[name] = tc
+ if cmd and not tc.command:
+ tc.command = cmd
+ elif e.kind == "ToolCallCompleted":
+ out = str(p.get("output_preview") or "")
+ if pending and out:
+ tc = by_name.get(pending)
+ if tc is not None and not tc.output:
+ tc.output = out
+ pending = None
+ return tools
+
+
def build_errors(events: list[VoiceEventRow]) -> list[ErrorEntry]:
out: list[ErrorEntry] = []
for e in events:
@@ -508,7 +590,7 @@ def _summarize(e: VoiceEventRow) -> str:
__all__ = [
"classify_latency", "build_latency", "build_decision_path", "build_errors",
"build_extras", "build_transcript", "build_timeline", "tools_from_usage",
- "merge_action_tools", "build_analytics",
+ "merge_action_tools", "attach_tool_io", "build_analytics",
"turn_outcome", "build_outcome", "outcome_from_events", "build_activity",
"feature_tags_from_events",
]
diff --git a/tests/unit/plugins/tts/test_tts_keyaware_fallback.py b/tests/unit/plugins/tts/test_tts_keyaware_fallback.py
new file mode 100644
index 0000000000..967481ba99
--- /dev/null
+++ b/tests/unit/plugins/tts/test_tts_keyaware_fallback.py
@@ -0,0 +1,120 @@
+"""Key-aware TTS fallback: a configured TTS provider with no usable key must
+cross to whatever TTS family the user DOES have a key for, instead of building a
+keyless provider that goes silently mute.
+
+Open-source resilience (AP-22): the shipped default TTS is ``gemini-flash-tts``,
+but jarvis.toml is gitignored, so a fresh downloader whose single TTS key is for
+ElevenLabs / Cartesia / Grok (or who has no Gemini key) would otherwise get a
+Gemini instance that produces no audio — leaving Jarvis mute. The factory must
+consult "is there actually a key?" and cross families, mirroring the STT path.
+"""
+from __future__ import annotations
+
+from types import SimpleNamespace
+from typing import Any
+
+import jarvis.core.config as cfg
+import jarvis.plugins.tts as tts_pkg
+
+
+def _keys(*env_names: str):
+ """Fake ``get_secret_any`` that returns a key only for the named env vars."""
+ have = set(env_names)
+
+ def fake(candidates: tuple[tuple[str, str], ...]) -> str | None:
+ for _keyring, env in candidates:
+ if env in have:
+ return "KEY"
+ return None
+
+ return fake
+
+
+def _cfg(provider: str, **over: Any) -> SimpleNamespace:
+ base = dict(provider=provider, voice_de="Charon", voice_en="Charon", use_vertex=False)
+ base.update(over)
+ return SimpleNamespace(**base)
+
+
+# --- The mute scenario: a single non-Gemini key must cross, not go silent ------
+
+
+def test_gemini_default_with_only_elevenlabs_key_crosses(monkeypatch) -> None:
+ monkeypatch.setattr(cfg, "get_secret_any", _keys("ELEVENLABS_API_KEY"))
+ name, view = tts_pkg._resolve_keyed_tts_provider("gemini-flash-tts", _cfg("gemini-flash-tts"))
+ assert name == "elevenlabs"
+ # The Gemini default voice must NOT be carried into ElevenLabs as a bogus id.
+ assert view.voice_de == ""
+ assert view.voice_en == ""
+
+
+def test_elevenlabs_configured_with_only_gemini_key_crosses(monkeypatch) -> None:
+ monkeypatch.setattr(cfg, "get_secret_any", _keys("GEMINI_API_KEY"))
+ name, view = tts_pkg._resolve_keyed_tts_provider("elevenlabs", _cfg("elevenlabs", voice_de="x", voice_en="x"))
+ assert name == "gemini-flash-tts"
+
+
+def test_only_cartesia_key_crosses_to_cartesia(monkeypatch) -> None:
+ monkeypatch.setattr(cfg, "get_secret_any", _keys("CARTESIA_API_KEY"))
+ name, _view = tts_pkg._resolve_keyed_tts_provider("gemini-flash-tts", _cfg("gemini-flash-tts"))
+ assert name == "cartesia"
+
+
+# --- The maintainer path is untouched -----------------------------------------
+
+
+def test_configured_provider_with_its_key_is_kept(monkeypatch) -> None:
+ monkeypatch.setattr(cfg, "get_secret_any", _keys("GEMINI_API_KEY"))
+ c = _cfg("gemini-flash-tts")
+ name, view = tts_pkg._resolve_keyed_tts_provider("gemini-flash-tts", c)
+ assert name == "gemini-flash-tts"
+ assert view is c # unchanged config, no voice rewrite
+
+
+def test_gemini_vertex_counts_as_credential(monkeypatch) -> None:
+ """Vertex AI uses a service account, not an API key — no cross-over."""
+ monkeypatch.setattr(cfg, "get_secret_any", _keys()) # no API keys at all
+ name, _view = tts_pkg._resolve_keyed_tts_provider(
+ "gemini-flash-tts", _cfg("gemini-flash-tts", use_vertex=True)
+ )
+ assert name == "gemini-flash-tts"
+
+
+# --- Honest degrade when NOTHING is reachable (never a silent swap) ------------
+
+
+def test_no_key_anywhere_keeps_configured_provider(monkeypatch) -> None:
+ monkeypatch.setattr(cfg, "get_secret_any", _keys()) # no key for any family
+ name, view = tts_pkg._resolve_keyed_tts_provider("gemini-flash-tts", _cfg("gemini-flash-tts"))
+ assert name == "gemini-flash-tts" # kept; degrades to SAPI5/honest mute, not a swap
+
+
+# --- Cross-family target keeps a voice that DOES belong to it ------------------
+
+
+def test_cross_to_grok_keeps_grok_voice(monkeypatch) -> None:
+ monkeypatch.setattr(cfg, "get_secret_any", _keys("XAI_API_KEY"))
+ name, view = tts_pkg._resolve_keyed_tts_provider(
+ "gemini-flash-tts", _cfg("gemini-flash-tts", voice_de="leo", voice_en="leo")
+ )
+ assert name == "grok-voice"
+ assert view.voice_de == "leo" # a real Grok voice survives the cross-over
+
+
+# --- End-to-end wiring: the factory builds the crossed-to provider -------------
+
+
+def test_factory_builds_crossed_provider(monkeypatch) -> None:
+ monkeypatch.setattr(cfg, "get_secret_any", _keys("ELEVENLABS_API_KEY"))
+ captured: dict[str, Any] = {}
+
+ def _fake_build(tts_cfg: Any, provider: str) -> Any:
+ captured["provider"] = provider
+ captured["voice_de"] = getattr(tts_cfg, "voice_de", None)
+ return SimpleNamespace(kind="built", provider=provider)
+
+ monkeypatch.setattr(tts_pkg, "_build_provider", _fake_build)
+ built = tts_pkg.build_tts_from_config(_cfg("gemini-flash-tts"))
+ assert built.provider == "elevenlabs"
+ assert captured["provider"] == "elevenlabs"
+ assert captured["voice_de"] == "" # foreign Gemini voice was blanked
diff --git a/tests/unit/runs/test_decision_log.py b/tests/unit/runs/test_decision_log.py
new file mode 100644
index 0000000000..86fd0fd313
--- /dev/null
+++ b/tests/unit/runs/test_decision_log.py
@@ -0,0 +1,91 @@
+"""Session-Decision-Log: the analyzer surfaces the honest "why" + tool I/O.
+
+The model rationale (ActionProposed.rationale) is captured for free and must be
+attached to the route step; rule-based steps (approval/denial/tier/brain/
+fallback) get a deterministic, human-readable explanation built from CAPTURED
+facts — never fabricated. The already-captured tool command/output is surfaced."""
+from jarvis.runs.analyzer import attach_tool_io, build_decision_path
+from jarvis.runs.model import ToolCall
+from jarvis.sessions.models import VoiceEventRow
+
+
+def _ev(kind, ts_ms=0, **payload):
+ return VoiceEventRow(session_id="s", turn_id="t1", ts_ms=ts_ms, kind=kind, payload=payload)
+
+
+def _step(steps, kind):
+ return next(s for s in steps if s.kind == kind)
+
+
+def test_proposed_attaches_model_rationale():
+ events = [
+ _ev("ActionProposed", ts_ms=2, tool_name="open_calendar", risk_tier="safe",
+ rationale="I open the calendar to check your schedule."),
+ ]
+ route = _step(build_decision_path(events), "route")
+ assert route.rationale.startswith("I open the calendar")
+ assert route.rationale_source == "model"
+
+
+def test_proposed_without_rationale_falls_back_to_honest_rule():
+ events = [_ev("ActionProposed", ts_ms=2, tool_name="search_web", risk_tier="safe")]
+ route = _step(build_decision_path(events), "route")
+ assert route.rationale_source == "rule"
+ assert "search_web" in route.rationale
+
+
+def test_whitelist_approval_reads_as_plain_language():
+ events = [_ev("ActionApproved", ts_ms=3, tool_name="x", approved_by="whitelist")]
+ risk = _step(build_decision_path(events), "risk")
+ assert risk.rationale_source == "rule"
+ assert "allow-list" in risk.rationale.lower()
+
+
+def test_user_approval_rationale():
+ events = [_ev("ActionApproved", ts_ms=3, tool_name="x", approved_by="user")]
+ risk = _step(build_decision_path(events), "risk")
+ assert risk.rationale_source == "rule"
+ assert "you approved" in risk.rationale.lower()
+
+
+def test_denial_rule_rationale_carries_the_captured_reason():
+ events = [_ev("ActionDenied", ts_ms=1, tool_name="rm", reason="blacklist: destructive")]
+ risk = _step(build_decision_path(events), "risk")
+ assert risk.rationale_source == "rule"
+ assert "destructive" in risk.rationale
+
+
+def test_brain_and_tier_steps_get_rule_rationale():
+ events = [
+ _ev("IntentClassified", ts_ms=1, intent="execute", risk_tier="ask"),
+ _ev("BrainTurnStarted", ts_ms=4, provider="claude-api", model="opus"),
+ ]
+ steps = build_decision_path(events)
+ assert _step(steps, "tier").rationale_source == "rule"
+ brain = _step(steps, "brain")
+ assert brain.rationale_source == "rule"
+ assert "claude-api" in brain.rationale
+
+
+def test_attach_tool_io_sets_command_and_output():
+ events = [
+ _ev("ToolCallStarted", ts_ms=1, tool_name="cli_gcloud",
+ args_preview="gcloud projects list"),
+ _ev("ToolCallCompleted", ts_ms=2, success=True, output_preview="3 projects found"),
+ ]
+ tools = [ToolCall(name="cli_gcloud")]
+ attach_tool_io(events, tools)
+ assert tools[0].command == "gcloud projects list"
+ assert tools[0].output == "3 projects found"
+
+
+def test_attach_tool_io_adds_missing_tool_from_events():
+ # A tool seen only via ToolCallStarted/Completed (no ActionProposed) still
+ # surfaces, so its command/result is never silently dropped.
+ events = [
+ _ev("ToolCallStarted", ts_ms=1, tool_name="read_file", args_preview="notes.md"),
+ _ev("ToolCallCompleted", ts_ms=2, success=True, output_preview="(file body)"),
+ ]
+ tools: list[ToolCall] = []
+ attach_tool_io(events, tools)
+ assert any(t.name == "read_file" and t.command == "notes.md" for t in tools)