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
chore: auto-save WIP via Claude stop-hook safety net (2026-07-09 20:51)
Ruben Lütke4d37a01f1717
diff --git a/.githooks/pre-push b/.githooks/pre-pushindex 2bf3716ee0..0b2a8a5feb 100755--- a/.githooks/pre-push+++ b/.githooks/pre-push@@ -104,6 +104,20 @@ if [ -f "$cli_gate" ]; thenfifi+# --- 3b) DANGER METADATA gate (FAIL-CLOSED) ------------------------------------+# A mutating route whose path matches a destructive marker (/restart, /kill,+# /outbound, ...) must declare openapi_extra x-jarvis-dangerous, so the CLI's+# dynamic layer and the Command Registry demand an explicit --yes/confirmation.+# Static + stdlib-only; safe to run on every push.+danger_gate="scripts/ci/check_danger_metadata.py"+if [ -f "$danger_gate" ]; then+ "$PY" "$danger_gate" </dev/null+ if [ "$?" -ne 0 ]; then+ status=1+ danger_meta_hit=1+ fi+fi+# --- 4) CLI DOCGEN drift gate (FAIL-CLOSED) -----------------------------------# docs/jarvis-cli-reference.md is generated from the curated command tree; this# fails the push if a command was added/changed without regenerating it. Static@@ -220,6 +234,10 @@ if [ "$status" -ne 0 ]; thenecho "pre-push BLOCKED: CLI COVERAGE gate (a route module is not mounted)."echo " Mount it in jarvis/ui/web/server.py — see the findings above."fi+ if [ "${danger_meta_hit:-0}" -ne 0 ]; then+ echo "pre-push BLOCKED: DANGER METADATA gate (destructive route without x-jarvis-dangerous)."+ echo " Add openapi_extra={\"x-jarvis-dangerous\": True} to the route decorator."+ fiif [ "${docgen_hit:-0}" -ne 0 ]; thenecho "pre-push BLOCKED: CLI DOCGEN drift (jarvis-cli-reference.md out of date)."echo " Run: python scripts/ci/gen_cli_reference.py and commit the result."diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 13790d57b6..d8320ff88d 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -208,6 +208,12 @@ jobs:# pre-push hook so a contributor without the hook can't bypass it.run: python scripts/ci/check_cli_coverage.py+ - name: Danger-metadata gate (destructive routes declare x-jarvis-dangerous)+ # Static + stdlib-only: a mutating route whose path matches a+ # destructive marker must carry openapi_extra x-jarvis-dangerous so the+ # CLI dynamic layer + Command Registry gate it. Mirrors pre-push.+ run: python scripts/ci/check_danger_metadata.py+- name: CLI reference drift gate (docs in sync with command tree)# Fails if a curated command was added/changed without regenerating# docs/jarvis-cli-reference.md. Mirrors the pre-push docgen gate.diff --git a/jarvis/audio/mic_level.py b/jarvis/audio/mic_level.pyindex c8bcbf2fd5..1e487476c6 100644--- a/jarvis/audio/mic_level.py+++ b/jarvis/audio/mic_level.py@@ -27,8 +27,13 @@ _lock = threading.Lock()_subscribers: list[Callable[[float], None]] = []# Floors — prevent div-by-~0 and runaway gain on absolute silence (muted mic).-_MIN_NOISE_FLOOR = 0.001-_MIN_PEAK = 0.01+# Sized for the QUIETEST real input path, not the maintainer's mic+# (fresh-machine forensics Bug 17): a quiet laptop puts hiss at ~0.0005 and+# real speech at ~0.002-0.006 rms — with the old floors (0.001 / 0.01) that+# whole band rendered near-zero bars while STT/wake heard it fine. Digital+# mute (~1e-5) still sits far below both floors, so a muted mic stays dark.+_MIN_NOISE_FLOOR = 0.0002+_MIN_PEAK = 0.004class LevelNormalizer:@@ -39,7 +44,11 @@ class LevelNormalizer:def __init__(self) -> None:self._noise_floor = 0.005- self._peak = 0.05+ # Start the auto-gain reference AT the floor: the attack path raises it+ # to the true peak within one loud frame, while a high start (0.05)+ # would take ~800 decay frames (~27 s) to reach a quiet mic's speech+ # level — the bars would read near-dead for the whole first session.+ self._peak = _MIN_PEAKself._smoothed = 0.0def push(self, rms: float) -> float:@@ -66,7 +75,7 @@ class LevelNormalizer:def reset(self) -> None:self._noise_floor = 0.005- self._peak = 0.05+ self._peak = _MIN_PEAKself._smoothed = 0.0diff --git a/jarvis/cli_ctl/dynamic.py b/jarvis/cli_ctl/dynamic.pyindex 0a50e59f3e..c2ca193c0e 100644--- a/jarvis/cli_ctl/dynamic.py+++ b/jarvis/cli_ctl/dynamic.py@@ -95,6 +95,12 @@ def _build_command())+ # Server-declared danger metadata (route `openapi_extra`): the authoritative+ # signal for the safety gate. `None` (absent) falls back to the method+path+ # heuristic in safety.is_dangerous — the flag can only ADD strictness here,+ # never clear it (fail-closed).+ flagged_dangerous: bool | None = True if op.get("x-jarvis-dangerous") else None+def callback(**kwargs: Any) -> None:assume_yes = bool(kwargs.pop("yes", False))dry_run = bool(kwargs.pop("dry_run", False))@@ -119,7 +125,8 @@ def _build_command(json_out = as_json()if not safety.gate_request(method, url_path, body=body,- assume_yes=assume_yes, dry_run=dry_run, as_json=json_out,+ assume_yes=assume_yes, dry_run=dry_run,+ dangerous=flagged_dangerous, as_json=json_out,):return # dry run: preview already printed, nothing sentresult = runner(method, url_path, query, body)diff --git a/jarvis/cli_ctl/safety.py b/jarvis/cli_ctl/safety.pyindex b23298aa37..805f2c7e96 100644--- a/jarvis/cli_ctl/safety.py+++ b/jarvis/cli_ctl/safety.py@@ -18,9 +18,12 @@ surface, so the CLI adds defense in depth on the client side:be sent (method, path, body, whether auth is attached) and sends nothing. This isthe safe introspection path for an agent.-The model is method-based plus a small path denylist — predictable and-independent of per-route risk metadata, which REST routes do not carry (risk-tiers live at the brain-tool layer the routes sit behind).+Three signals mark a request destructive, strictest wins: every ``DELETE``+(method alone), the small path denylist below (legacy floor), and the+server-declared ``x-jarvis-dangerous`` OpenAPI flag that the dynamic layer+reads per operation and passes in as ``dangerous=True`` (authoritative for+new routes; enforced repo-wide by ``scripts/ci/check_danger_metadata.py``).+A flag can only ADD strictness — nothing downgrades the denylist."""from __future__ import annotationsdiff --git a/jarvis/speech/rolling_whisper_wake.py b/jarvis/speech/rolling_whisper_wake.pyindex efa375bb7e..d849f07b4b 100644--- a/jarvis/speech/rolling_whisper_wake.py+++ b/jarvis/speech/rolling_whisper_wake.py@@ -129,6 +129,73 @@ _MATCH_MIN_SPEECH_RMS = 0.006# cheaply by the raw energy gate (``_MATCH_MIN_SPEECH_RMS``)._ECHO_CONFIRM_SKIP_RMS = 0.02+# Session-relative noise-floor calibration (fresh-machine forensics Bug 17 /+# AP-23 audit finding 9). The absolute gates above were measured on the+# maintainer's mic (idle hiss ~0.0046 rms); a quieter laptop input path puts+# REAL speech at 0.003-0.006 rms — below _MATCH_MIN_SPEECH_RMS and partly+# below ``min_peak`` — so a genuine wake was dropped silently. Each energy+# gate is therefore calibrated against the SESSION's own noise floor,+# strictly LOWER-ONLY:+#+# effective = min(configured_absolute, max(K * floor, absolute_minimum))+#+# On the maintainer's mic every effective gate equals the legacy absolute+# (floor ~0.0046 puts K*floor above each cap), so all historical+# measurements and pins above stay valid. On a quiet mic the gates scale+# down with the floor — and the AP-27 discriminator survives BY+# CONSTRUCTION: a bias-primed silence hallucination sits AT the noise floor+# while the match gate sits at ``_MATCH_GATE_K`` x the floor, on ANY mic+# gain. The absolute minimums keep a muted mic's digital silence+# (rms ~1e-5) below every gate forever.+_FLOOR_INIT = 0.004 # ~the maintainer hiss: gates START at legacy values+_FLOOR_ABS_MIN = 0.0002 # digital-mute numeric noise never defines a floor+_FLOOR_ALPHA = 0.05 # EMA weight per quiet polled window+_FLOOR_QUIET_BAND = 1.5 # a window this close to the floor counts as quiet+_MATCH_GATE_K = 1.4 # ghost ≈ 1.0x floor, quiet genuine wake ≥ ~2x floor+_MATCH_GATE_ABS_MIN = 0.0015+_RMS_GATE_K = 1.2+_RMS_GATE_ABS_MIN = 0.001+_PEAK_GATE_K = 2.5+_PEAK_GATE_ABS_MIN = 0.002+++class SessionNoiseFloor:+ """EMA estimate of the session's noise floor over per-window RMS values.++ Only windows in the quiet band (below ``quiet_band`` x the current floor)+ update the estimate, so speech never drags the floor up; the floor may+ drift up slowly when the ROOM gets noisier (each step is bounded by the+ band) and is clamped to ``abs_min`` so a muted mic cannot zero it.+ """++ def __init__(+ self,+ initial: float = _FLOOR_INIT,+ abs_min: float = _FLOOR_ABS_MIN,+ alpha: float = _FLOOR_ALPHA,+ quiet_band: float = _FLOOR_QUIET_BAND,+ ) -> None:+ self._floor = float(initial)+ self._abs_min = float(abs_min)+ self._alpha = float(alpha)+ self._quiet_band = float(quiet_band)++ @property+ def floor(self) -> float:+ return self._floor++ def update(self, rms: float) -> None:+ if rms < self._floor * self._quiet_band:+ floor = (1.0 - self._alpha) * self._floor + self._alpha * rms+ self._floor = max(floor, self._abs_min)++ def gate(self, configured: float, k: float, abs_min: float) -> float:+ """Lower-only effective gate: never above ``configured``; a+ ``configured <= 0`` keeps the caller's explicit opt-out."""+ if configured <= 0.0:+ return configured+ return min(configured, max(k * self._floor, abs_min))+def _save_wav(pcm_bytes: bytes, sample_rate: int, path: Path) -> None:"""Writes int16 PCM as a valid WAV file."""@@ -293,6 +360,8 @@ class RollingWhisperWake:self._max_no_speech_prob = max_no_speech_probself._transcribe_timeout_s = float(transcribe_timeout_s)self._match_min_rms = float(match_min_rms)+ # Session-relative gate calibration — see SessionNoiseFloor above.+ self._noise_floor = SessionNoiseFloor()# Statistics for the heartbeatself._chunks_seen = 0self._total_bytes = 0@@ -317,6 +386,17 @@ class RollingWhisperWake:self._stat_suppressed_echo = 0self._stat_suppressed_silence = 0+ def _effective_min_rms(self) -> float:+ return self._noise_floor.gate(self._min_rms, _RMS_GATE_K, _RMS_GATE_ABS_MIN)++ def _effective_min_peak(self) -> float:+ return self._noise_floor.gate(self._min_peak, _PEAK_GATE_K, _PEAK_GATE_ABS_MIN)++ def _effective_match_min_rms(self) -> float:+ return self._noise_floor.gate(+ self._match_min_rms, _MATCH_GATE_K, _MATCH_GATE_ABS_MIN+ )+def stats(self) -> dict[str, int]:"""Snapshot of this listen session's wake-evaluation counters.@@ -468,7 +548,7 @@ class RollingWhisperWake:"max-rms=%.4f (%.1f dBFS) last-transcript=%r | ""windows=%d gated[rms=%d peak=%d] transcribed=%d ""rejected[unreliable=%d no_match=%d] matched=%d "- "(conf_floor=%.2f peak_gate=%.3f)",+ "(conf_floor=%.2f peak_gate=%.3f noise_floor=%.4f)",self._chunks_seen,self._total_bytes // 1024,self._max_rms,@@ -482,7 +562,8 @@ class RollingWhisperWake:self._stat_rejected_no_match,self._stat_matched,self._min_wake_confidence,- self._min_peak,+ self._effective_min_peak(),+ self._noise_floor.floor,)self._chunks_seen = 0self._total_bytes = 0@@ -687,22 +768,27 @@ class RollingWhisperWake:# evaluation attempt (the denominator for the gate counters).self._stat_windows_polled += 1- # Volume check (RMS) — no Whisper call during silence+ # Volume check (RMS) — no Whisper call during silence. Every+ # polled window first feeds the session noise-floor estimate+ # (quiet windows only — see SessionNoiseFloor), which scales+ # the energy gates down on a quiet mic, lower-only.rms = float(np.sqrt(np.mean(audio_np * audio_np) + 1e-12))- if rms < self._min_rms:+ self._noise_floor.update(rms)+ if rms < self._effective_min_rms():self._stat_gated_rms += 1continue# Peak gate: don't bother Whisper at all on pure noisepeak = float(np.max(np.abs(audio_np)))- if peak < self._min_peak:+ effective_min_peak = self._effective_min_peak()+ if peak < effective_min_peak:# No Whisper call — too quiet for speech. Log the measured# peak so "wake stopped working" on a quiet mic is visible as# "your audio peaks below the gate", not silent nothing.self._stat_gated_peak += 1log.debug("rolling-whisper: window gated (peak=%.4f < %.4f) — too quiet",- peak, self._min_peak,+ peak, effective_min_peak,)continue@@ -852,13 +938,14 @@ class RollingWhisperWake:# exact-phrase echo confirm misses: a hallucination with# extra invented words (which skips the confirm) or one the# confirm accepts because its second pass errored.- if self._match_min_rms > 0.0 and rms < self._match_min_rms:+ match_gate = self._effective_match_min_rms()+ if match_gate > 0.0 and rms < match_gate:self._stat_suppressed_silence += 1log.info("rolling-whisper: SUPPRESSED near-silent match %r in ""%r (rms=%.4f < %.4f) — bias-prompt hallucination on ""silence, not a spoken wake",- m.group(0), joined, rms, self._match_min_rms,+ m.group(0), joined, rms, match_gate,)continue# Bias-echo gate: a candidate whose transcript is EXACTLYdiff --git a/jarvis/ui/web/control_routes.py b/jarvis/ui/web/control_routes.pyindex d5fb3bbfed..66285a72bb 100644--- a/jarvis/ui/web/control_routes.py+++ b/jarvis/ui/web/control_routes.py@@ -233,7 +233,7 @@ def _apply_config_write(return _pending_envelope(pending)[email protected]("/config", dependencies=[Depends(require_control_key)])[email protected]("/config", dependencies=[Depends(require_control_key)], openapi_extra={"x-jarvis-dangerous": True})async def put_config(body: ConfigWriteBody, request: Request) -> dict[str, Any]:store = _pending_store(request)return _apply_config_write(store, body.path, body.value, body.reason)@@ -346,7 +346,7 @@ async def list_secrets() -> dict[str, Any]:return {"secrets": items}[email protected]("/secrets/{key}", dependencies=[Depends(require_control_key)])[email protected]("/secrets/{key}", dependencies=[Depends(require_control_key)], openapi_extra={"x-jarvis-dangerous": True})async def set_secret_value(key: str, body: SecretBody, request: Request) -> dict[str, Any]:if key not in ALLOWED_SECRET_KEYS:raise HTTPException(status_code=404, detail=f"Unknown secret key: {key}")@@ -384,7 +384,7 @@ async def get_api_key(request: Request) -> dict[str, Any]:return {"key": key, "masked": control_key.mask_control_key(key)}[email protected]("/api-key/rotate", dependencies=[Depends(require_control_key_or_loopback)])[email protected]("/api-key/rotate", dependencies=[Depends(require_control_key_or_loopback)], openapi_extra={"x-jarvis-dangerous": True})async def rotate_api_key(body: RotateBody) -> dict[str, Any]:if not body.confirm:raise HTTPException(diff --git a/jarvis/ui/web/missions_routes.py b/jarvis/ui/web/missions_routes.pyindex a08831cbb4..de3ac5ad84 100644--- a/jarvis/ui/web/missions_routes.py+++ b/jarvis/ui/web/missions_routes.py@@ -216,7 +216,7 @@ async def get_mission(mission_id: str, request: Request) -> dict[str, Any]:# ---------------------------------------------------------------------------[email protected]("/dispatch", status_code=201)[email protected]("/dispatch", status_code=201, openapi_extra={"x-jarvis-dangerous": True})async def dispatch_mission(body: DispatchBody,request: Request,@@ -273,7 +273,7 @@ async def dispatch_mission(return {"mission_id": mission_id, "started": str(started).lower()}[email protected]("/{mission_id}/cancel")[email protected]("/{mission_id}/cancel", openapi_extra={"x-jarvis-dangerous": True})async def cancel_mission(mission_id: str, request: Request) -> dict[str, Any]:"""Cancel a mission: terminal state transition + kill the in-flight run.@@ -359,7 +359,7 @@ _TERMINAL_STATE_VALUES: frozenset[str] = frozenset()[email protected]("/{mission_id}/rerun")[email protected]("/{mission_id}/rerun", openapi_extra={"x-jarvis-dangerous": True})async def rerun_mission(mission_id: str,body: RerunBody,@@ -512,7 +512,7 @@ async def rerun_mission(}[email protected]("/kill/{worker_id}")[email protected]("/kill/{worker_id}", openapi_extra={"x-jarvis-dangerous": True})async def kill_worker(worker_id: str, request: Request) -> dict[str, Any]:"""Best-effort worker kill (stub for the Phase-4 MVP).diff --git a/jarvis/ui/web/provider_routes.py b/jarvis/ui/web/provider_routes.pyindex ae2e7bde70..ed2f489891 100644--- a/jarvis/ui/web/provider_routes.py+++ b/jarvis/ui/web/provider_routes.py@@ -1577,7 +1577,7 @@ _RESTART_REQUIRED_SECRET_KEYS: frozenset[str] = frozenset({})[email protected]("/secrets/{key}")[email protected]("/secrets/{key}", openapi_extra={"x-jarvis-dangerous": True})async def set_secret_value(key: str, body: SecretBody, request: Request) -> dict[str, Any]:if key not in ALLOWED_SECRET_KEYS:raise HTTPException(status_code=404, detail=f"Unbekannter Secret-Key: {key}")diff --git a/jarvis/ui/web/provider_spec.py b/jarvis/ui/web/provider_spec.pyindex 57a145a361..8b77e3cf44 100644--- a/jarvis/ui/web/provider_spec.py+++ b/jarvis/ui/web/provider_spec.py@@ -121,7 +121,74 @@ _GEMINI_VERTEX = AltCredential(PROVIDERS: tuple[ProviderSpec, ...] = (- # ── Brain: Klassischer API-Key ────────────────────────────────────────+ # ── Brain: providers (Brain-tab card render order) ────────────────────+ # The Brain tab renders switchable providers in this tuple order; Gemini+ # leads as the maintainer-recommended default, then OpenRouter, Claude,+ # OpenAI, NVIDIA. The OAuth-subscription siblings (antigravity/codex,+ # brain_switchable=False) sit next to their API-key kin and surface only in+ # the Jarvis-Agents section, never this tab.+ ProviderSpec(+ id="gemini",+ label="Google Gemini",+ tier="brain",+ auth_mode="api_key",+ secret_keys=("gemini_api_key",),+ dashboard_url="https://aistudio.google.com/app/apikey",+ credential_help=(+ "Google AI Studio API key (starts with AIza or AQ.). Pay-as-you-go "+ "on your AI Studio project. For higher quota, use the Vertex AI "+ "service-account path instead — it bills a different account."+ ),+ alt_credential=_GEMINI_VERTEX,+ # Maintainer-recommended brain (2026-06-22): best real-world experience.+ # Badge on the brain card; the model picker highlights gemini-3.5-flash.+ recommended=True,+ recommended_model="gemini-3.5-flash",+ ),+ # ── Brain: Google subscription via the official Antigravity/Gemini CLI ──+ # OAuth-only (no API-key slot): we drive the official ``agy``/``gemini`` CLI+ # as a subprocess over the user's "Sign in with Google" login — billed+ # against the Google subscription, no Gemini API key. Mirror of the Codex+ # ChatGPT-login path. The UI renders an OAuth connect widget (auth_mode).+ ProviderSpec(+ id="antigravity",+ label="Antigravity (Google subscription)",+ tier="brain",+ auth_mode="antigravity",+ # Dual billing, mirror of Codex: the Google subscription login OR a+ # Gemini API key (the Google Cloud credential). The key slot reuses the+ # shared ``gemini_api_key`` — the same key the Gemini provider uses — so+ # a user who already set it gets per-token Antigravity billing for free.+ # Carrying a secret_key flips provider_billing → subscription_or_api.+ secret_keys=("gemini_api_key",),+ dashboard_url="https://antigravity.google",+ # agy has NO `login` subcommand (verified 2026-06-21) — the bare binary+ # drops into the interactive "Sign in with Google" flow. The Connect+ # button drives POST /api/antigravity/login (start_login → bare run).+ login_cli=("agy",),+ install_hint="Install Antigravity (agy) or sign in with the Gemini CLI",+ credential_path_hint="~/.gemini/oauth_creds.json",+ brain_switchable=False,+ signup_url="https://antigravity.google",+ credential_help=(+ "Sign in with your Google account to run heavy subagent tasks over "+ "your Google subscription via the Antigravity/Gemini CLI — no API "+ "key, billed to your subscription. Or set a Gemini API key to bill "+ "per token instead."+ ),+ ),+ ProviderSpec(+ id="openrouter",+ label="OpenRouter",+ tier="brain",+ auth_mode="api_key",+ secret_keys=("openrouter_api_key",),+ dashboard_url="https://openrouter.ai/keys",+ credential_help=(+ "OpenRouter API key (starts with sk-or-). One key reaches many "+ "models; billed per token on your OpenRouter account."+ ),+ ),ProviderSpec(id="claude-api",label="Claude (API-Key)",@@ -163,18 +230,6 @@ PROVIDERS: tuple[ProviderSpec, ...] = ("API key to bill per token instead."),),- ProviderSpec(- id="openrouter",- label="OpenRouter",- tier="brain",- auth_mode="api_key",- secret_keys=("openrouter_api_key",),- dashboard_url="https://openrouter.ai/keys",- credential_help=(- "OpenRouter API key (starts with sk-or-). One key reaches many "- "models; billed per token on your OpenRouter account."- ),- ),ProviderSpec(id="nvidia",label="NVIDIA NIM",@@ -194,61 +249,11 @@ PROVIDERS: tuple[ProviderSpec, ...] = ("background tasks, sluggish as your main or voice brain."),),- # ── Brain: Google subscription via the official Antigravity/Gemini CLI ──- # OAuth-only (no API-key slot): we drive the official ``agy``/``gemini`` CLI- # as a subprocess over the user's "Sign in with Google" login — billed- # against the Google subscription, no Gemini API key. Mirror of the Codex- # ChatGPT-login path. The UI renders an OAuth connect widget (auth_mode).- ProviderSpec(- id="antigravity",- label="Antigravity (Google subscription)",- tier="brain",- auth_mode="antigravity",- # Dual billing, mirror of Codex: the Google subscription login OR a- # Gemini API key (the Google Cloud credential). The key slot reuses the- # shared ``gemini_api_key`` — the same key the Gemini provider uses — so- # a user who already set it gets per-token Antigravity billing for free.- # Carrying a secret_key flips provider_billing → subscription_or_api.- secret_keys=("gemini_api_key",),- dashboard_url="https://antigravity.google",- # agy has NO `login` subcommand (verified 2026-06-21) — the bare binary- # drops into the interactive "Sign in with Google" flow. The Connect- # button drives POST /api/antigravity/login (start_login → bare run).- login_cli=("agy",),- install_hint="Install Antigravity (agy) or sign in with the Gemini CLI",- credential_path_hint="~/.gemini/oauth_creds.json",- brain_switchable=False,- signup_url="https://antigravity.google",- credential_help=(- "Sign in with your Google account to run heavy subagent tasks over "- "your Google subscription via the Antigravity/Gemini CLI — no API "- "key, billed to your subscription. Or set a Gemini API key to bill "- "per token instead."- ),- ),- ProviderSpec(- id="gemini",- label="Google Gemini",- tier="brain",- auth_mode="api_key",- secret_keys=("gemini_api_key",),- dashboard_url="https://aistudio.google.com/app/apikey",- credential_help=(- "Google AI Studio API key (starts with AIza or AQ.). Pay-as-you-go "- "on your AI Studio project. For higher quota, use the Vertex AI "- "service-account path instead — it bills a different account."- ),- alt_credential=_GEMINI_VERTEX,- # Maintainer-recommended brain (2026-06-22): best real-world experience.- # Badge on the brain card; the model picker highlights gemini-3.5-flash.- recommended=True,- recommended_model="gemini-3.5-flash",- ),# xAI Grok was removed as a BRAIN and SUB-AGENT provider on 2026-06-22# (maintainer decision: Grok stays only as a TTS voice). The `grok-voice`# TTS spec below is intentionally kept, and the `grok_api_key` credential it# shares with the (now TTS-only) xAI key remains.- # Ollama-Provider 2026-04-21 entfernt — reine API-Provider-Chain.+ # Ollama provider removed 2026-04-21 — pure API-provider chain.# ── TTS ───────────────────────────────────────────────────────────────# Voice-Output cards render in this tuple order. OpenRouter leads (one key# reaches many vetted speech models); Inworld sits last as a premiumdiff --git a/jarvis/ui/web/settings_routes.py b/jarvis/ui/web/settings_routes.pyindex 6a9b7b84ea..3774bbfc0e 100644--- a/jarvis/ui/web/settings_routes.py+++ b/jarvis/ui/web/settings_routes.py@@ -1509,7 +1509,7 @@ async def _run_off_pool(fn: Callable[[], object]) -> object:return await fut[email protected]("/restart-app")[email protected]("/restart-app", openapi_extra={"x-jarvis-dangerous": True})async def restart_app(request: Request, force: bool = False) -> dict[str, object]:"""Cleanly self-restart the desktop app.diff --git a/jarvis/ui/web/tasks_routes.py b/jarvis/ui/web/tasks_routes.pyindex 29f38265b6..6fddde1f4a 100644--- a/jarvis/ui/web/tasks_routes.py+++ b/jarvis/ui/web/tasks_routes.py@@ -115,7 +115,7 @@ async def get_task(task_id: str, request: Request) -> dict[str, Any]:return task_out[email protected]("/{task_id}/cancel")[email protected]("/{task_id}/cancel", openapi_extra={"x-jarvis-dangerous": True})async def cancel_task(task_id: str, request: Request) -> dict[str, Any]:"""Soft cancel: removes the task from the heap/event index and setsits state to ``cancelled``. Does **not** abort a hard CU loop — that'sdiff --git a/jarvis/ui/web/telephony_routes.py b/jarvis/ui/web/telephony_routes.pyindex d5562de4e9..b6f57f094e 100644--- a/jarvis/ui/web/telephony_routes.py+++ b/jarvis/ui/web/telephony_routes.py@@ -491,7 +491,7 @@ class OutboundCall(BaseModel):opening: str = ""[email protected]("/outbound")[email protected]("/outbound", openapi_extra={"x-jarvis-dangerous": True})async def post_outbound(request: Request, body: OutboundCall) -> JSONResponse:"""Place a real outbound call to a raw E.164 number; speak ``opening`` first.diff --git a/scripts/ci/check_danger_metadata.py b/scripts/ci/check_danger_metadata.pynew file mode 100644index 0000000000..9af89a552f--- /dev/null+++ b/scripts/ci/check_danger_metadata.py@@ -0,0 +1,109 @@+"""Danger-metadata gate.++Destructive REST routes must declare themselves: a mutating route (POST/PUT/+PATCH) whose path matches one of the known destructive markers MUST carry+``openapi_extra={"x-jarvis-dangerous": True}`` on its decorator. The flag is+what the CLI's dynamic ``jarvis api ...`` layer (and, via the Command+Registry, every other surface) uses to demand an explicit ``--yes`` /+confirmation — without it, a new destructive route silently ships under-gated+(the exact failure mode of a hand-maintained denylist).++DELETE routes are exempt: the method alone marks them dangerous everywhere+(``jarvis.cli_ctl.safety.is_dangerous``), no per-route flag needed.++The marker list is a deliberate stdlib-only copy of+``jarvis.cli_ctl.safety._DANGEROUS_MARKERS`` (this gate must stay importable+without the package installed); a parity test+(``tests/unit/cli_ctl/test_danger_metadata.py``) asserts the two never drift.++Static analysis only — never boots the app. Run from pre-push and CI.+"""+from __future__ import annotations++import re+import sys+from pathlib import Path++_REPO = Path(__file__).resolve().parents[2]+_WEB = _REPO / "jarvis" / "ui" / "web"++# Copy of jarvis.cli_ctl.safety._DANGEROUS_MARKERS — parity-tested, see above.+DANGEROUS_MARKERS: tuple[str, ...] = (+ "/restart",+ "/call",+ "/outbound",+ "/dispatch",+ "/rerun",+ "/kill",+ "/cancel",+ "/config/set",+ "/secret",+)++FLAG = "x-jarvis-dangerous"++_MUTATING_DECORATOR = re.compile(r"@\w+\.(post|put|patch)\(")+_ROUTER_PREFIX = re.compile(r"APIRouter\([^)]*prefix\s*=\s*[\"']([^\"']+)[\"']")+_FIRST_STRING = re.compile(r"[\"']([^\"']*)[\"']")+++def _decorator_blocks(src: str) -> list[tuple[str, str]]:+ """(method, full-argument-text) for every mutating route decorator,+ balanced-paren scanned so multi-line decorators are captured whole."""+ blocks: list[tuple[str, str]] = []+ for m in _MUTATING_DECORATOR.finditer(src):+ i = m.end()+ depth = 1+ start = i+ while i < len(src) and depth > 0:+ ch = src[i]+ if ch == "(":+ depth += 1+ elif ch == ")":+ depth -= 1+ i += 1+ blocks.append((m.group(1), src[start : i - 1]))+ return blocks+++def _matches_marker(path: str, prefixes: list[str]) -> bool:+ candidates = [path] + [prefix + path for prefix in prefixes]+ low = [c.lower() for c in candidates]+ return any(marker in c for c in low for marker in DANGEROUS_MARKERS)+++def unflagged_dangerous_routes() -> list[str]:+ """'file:METHOD path' for every marker-matching mutating route without+ the x-jarvis-dangerous flag."""+ offenders: list[str] = []+ for module in sorted(_WEB.glob("*_routes.py")):+ src = module.read_text(encoding="utf-8")+ prefixes = _ROUTER_PREFIX.findall(src)+ for method, block in _decorator_blocks(src):+ path_match = _FIRST_STRING.search(block)+ if not path_match:+ continue+ path = path_match.group(1)+ if _matches_marker(path, prefixes) and FLAG not in block:+ offenders.append(f"{module.name}: {method.upper()} {path}")+ return offenders+++def main() -> int:+ offenders = unflagged_dangerous_routes()+ if offenders:+ print("Danger-metadata gate FAILED — destructive route(s) missing the flag:")+ for off in offenders:+ print(f" - {off}")+ print(+ "\nAdd openapi_extra={\"x-jarvis-dangerous\": True} to the route "+ "decorator so the CLI safety gate and the Command Registry treat "+ "it as destructive (explicit --yes / confirmation required)."+ )+ return 1+ print("Danger-metadata gate OK — every destructive route declares the flag.")+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/tests/unit/audio/test_mic_level.py b/tests/unit/audio/test_mic_level.pyindex d982bbfaed..6f0d5543aa 100644--- a/tests/unit/audio/test_mic_level.py+++ b/tests/unit/audio/test_mic_level.py@@ -50,6 +50,37 @@ def test_release_smoothing_decays_after_speech_stops():mic_level.reset_for_tests()+def test_quiet_laptop_mic_speech_is_clearly_visible():+ """Fresh-machine forensics Bug 17: on a quiet laptop input path (hiss+ ~0.0005, speech ~0.004 rms) STT/wake work fine but the bars sat at zero —+ the meter's absolute floors (_MIN_NOISE_FLOOR/_MIN_PEAK) were calibrated+ on a louder mic. After floor adaptation, quiet-mic speech must render a+ clearly visible level, not a dead meter."""+ mic_level.reset_for_tests()+ got: list[float] = []+ mic_level.subscribe(got.append)++ for _ in range(80):+ mic_level.feed(0.0005) # quiet laptop hiss — floor settles here+ for _ in range(15):+ mic_level.feed(0.004) # normal speech on that mic++ assert got[-1] > 0.25, f"speech on a quiet mic reads near-dead: {got[-1]:.3f}"+ mic_level.reset_for_tests()+++def test_muted_mic_stays_dark():+ """Runaway-gain guard: digital near-silence (muted mic) must NOT produce+ dancing bars even with the lowered floors."""+ mic_level.reset_for_tests()+ got: list[float] = []+ mic_level.subscribe(got.append)+ for _ in range(120):+ mic_level.feed(0.00003)+ assert got[-1] < 0.05, f"muted mic shows a level: {got[-1]:.3f}"+ mic_level.reset_for_tests()++def test_failing_subscriber_is_swallowed():mic_level.reset_for_tests()diff --git a/tests/unit/cli_ctl/test_danger_metadata.py b/tests/unit/cli_ctl/test_danger_metadata.pynew file mode 100644index 0000000000..3c9f16f171--- /dev/null+++ b/tests/unit/cli_ctl/test_danger_metadata.py@@ -0,0 +1,90 @@+"""Danger-metadata contract: server-declared x-jarvis-dangerous drives the+CLI safety gate, and the CI gate's marker list never drifts from safety.py."""+from __future__ import annotations++import importlib.util+from pathlib import Path++import click+from click.testing import CliRunner++from jarvis.cli_ctl import safety+from jarvis.cli_ctl.dynamic import build_api_group++_REPO = Path(__file__).resolve().parents[3]+++def _load_gate_module():+ spec = importlib.util.spec_from_file_location(+ "check_danger_metadata", _REPO / "scripts" / "ci" / "check_danger_metadata.py"+ )+ mod = importlib.util.module_from_spec(spec)+ assert spec.loader is not None+ spec.loader.exec_module(mod)+ return mod+++def test_gate_markers_match_safety_denylist() -> None:+ """The CI script keeps a stdlib-only copy of the marker list; this is the+ parity test that copy relies on."""+ gate = _load_gate_module()+ assert tuple(gate.DANGEROUS_MARKERS) == tuple(safety._DANGEROUS_MARKERS)+++def test_gate_passes_on_current_tree() -> None:+ gate = _load_gate_module()+ assert gate.unflagged_dangerous_routes() == []+++def _spec_with_flag(flagged: bool) -> dict:+ op = {+ "tags": ["demo"],+ "operationId": "wipe_everything_api_demo_wipe_post",+ "summary": "Wipe",+ }+ if flagged:+ op["x-jarvis-dangerous"] = True+ return {+ "openapi": "3.1.0",+ "info": {"version": "1"},+ "paths": {"/api/demo/wipe": {"post": op}},+ }+++def _invoke(spec: dict, args: list[str]):+ calls: list[tuple] = []++ def runner(method, path, params, body):+ calls.append((method, path))+ return {"ok": True}++ group = build_api_group(spec, runner)+ root = click.Group("jarvis")+ root.add_command(group)+ result = CliRunner().invoke(root, args)+ return result, calls+++def test_flagged_op_requires_yes_even_without_marker_match(monkeypatch) -> None:+ """/api/demo/wipe matches NO legacy marker — only the x-jarvis-dangerous+ flag makes it destructive. Non-interactive without --yes must fail closed+ and send nothing."""+ monkeypatch.delenv("JARVIS_CLI_ASSUME_YES", raising=False)+ result, calls = _invoke(_spec_with_flag(True), ["api", "demo", "wipe-everything"])+ assert result.exit_code == 1+ assert calls == []++ result, calls = _invoke(+ _spec_with_flag(True), ["api", "demo", "wipe-everything", "--yes"]+ )+ assert result.exit_code == 0+ assert calls == [("post", "/api/demo/wipe")]+++def test_unflagged_op_keeps_heuristic_behavior(monkeypatch) -> None:+ """Without the flag, a marker-free POST is a plain reversible mutation:+ it proceeds without --yes (agent-first), exactly as before."""+ monkeypatch.delenv("JARVIS_CLI_ASSUME_YES", raising=False)+ result, calls = _invoke(_spec_with_flag(False), ["api", "demo", "wipe-everything"])+ assert result.exit_code == 0+ assert calls == [("post", "/api/demo/wipe")]diff --git a/tests/unit/speech/test_rolling_whisper_wake_noise_floor_calibration.py b/tests/unit/speech/test_rolling_whisper_wake_noise_floor_calibration.pynew file mode 100644index 0000000000..74042fdb0b--- /dev/null+++ b/tests/unit/speech/test_rolling_whisper_wake_noise_floor_calibration.py@@ -0,0 +1,227 @@+"""Session-relative noise-floor calibration of the wake energy gates (AP-23 #9).++The absolute gates (``min_rms=0.003``, ``min_peak=0.008``,+``_MATCH_MIN_SPEECH_RMS=0.006``) were measured on the maintainer's mic (idle+hiss ~0.0046 rms). On a quieter laptop input path real speech lands at+0.003-0.006 rms — below the match gate and partly below the peak gate — so a+genuine wake is dropped silently (fresh-machine forensics Bug 17 / AP-23+audit finding 9).++The fix calibrates the gates against the SESSION's own noise floor,+**lower-only**: an effective gate is ``min(configured_absolute,+max(k * floor, absolute_minimum))``. On the maintainer's mic (floor ~0.0046)+every effective gate equals the legacy absolute — behavior unchanged, all+existing pins hold. On a quiet mic the gates scale down with the floor, and+the AP-27 discriminator survives BY CONSTRUCTION: a silence hallucination+sits AT the floor, the match gate sits at 1.4x the floor above it.+"""+from __future__ import annotations++import asyncio+import re++import numpy as np+import pytest++from jarvis.core.protocols import AudioChunk, Transcript+from jarvis.speech.rolling_whisper_wake import (+ RollingWhisperWake,+ SessionNoiseFloor,+)+++def _const_chunk(value: int, n: int = 1600) -> AudioChunk:+ arr = np.full(n, value, dtype=np.int16)+ return AudioChunk(pcm=arr.tobytes(), sample_rate=16000, timestamp_ns=0)+++def _spiky_chunk(base: int, spike: int, n: int = 1600, spikes: int = 8) -> AudioChunk:+ """Noise-like chunk: low RMS but a distinctly higher peak (breath/rustle)."""+ arr = np.full(n, base, dtype=np.int16)+ arr[:: max(1, n // spikes)] = spike+ return AudioChunk(pcm=arr.tobytes(), sample_rate=16000, timestamp_ns=0)+++class _PhraseSTT:+ """Always transcribes the given phrase — models both a genuine wake and a+ bias-primed hallucination; the ENERGY gates must tell them apart."""++ def __init__(self, phrase: str) -> None:+ self._phrase = phrase+ self.calls = 0++ async def transcribe_pcm(+ self, pcm: bytes, sample_rate: int = 16000, language: str | None = None+ ) -> Transcript:+ self.calls += 1+ return Transcript(+ text=self._phrase, language="de", confidence=0.9,+ segments=({"no_speech_prob": 0.05},),+ )+++async def _iter(src: asyncio.Queue):+ while True:+ chunk = await src.get()+ if chunk is None:+ return+ yield chunk+++async def _feed_switchable(+ src: asyncio.Queue, stop: asyncio.Event, holder: dict[str, AudioChunk]+) -> None:+ while not stop.is_set():+ await src.put(holder["chunk"])+ await asyncio.sleep(0.002)+++async def _first_keyword(wake: RollingWhisperWake, src: asyncio.Queue) -> str:+ async for kw in wake.detect(_iter(src)):+ return kw+ return ""+++# --- The fix: a quiet laptop mic wakes at its own normal speaking volume ----+++async def test_quiet_laptop_mic_wake_fires_after_floor_calibration() -> None:+ """Speech at rms/peak ~0.004 — real 'quiet laptop' volume, BELOW the legacy+ absolute peak gate (0.008) and match gate (0.006) — must fire once the+ session floor has settled on that mic's much lower hiss (~0.0008)."""+ stt = _PhraseSTT("hey nico")+ wake = RollingWhisperWake(+ stt,+ pattern=re.compile(r"nico", re.IGNORECASE),+ poll_interval_s=0.01,+ cooldown_s=0.0,+ save_debug_wavs=False,+ )+ src: asyncio.Queue = asyncio.Queue()+ stop = asyncio.Event()+ holder = {"chunk": _const_chunk(25)} # hiss ~0.0008 — calibration phase+ feeder = asyncio.create_task(_feed_switchable(src, stop, holder))+ try:+ detect = asyncio.create_task(_first_keyword(wake, src))+ await asyncio.sleep(1.0) # let the floor settle on the quiet hiss+ assert not detect.done(), "hiss alone must never wake"+ holder["chunk"] = _const_chunk(130) # speech ~0.004 rms/peak+ kw = await asyncio.wait_for(detect, timeout=5.0)+ assert kw == "nico", "quiet-laptop wake was dropped by absolute gates"+ assert stt.calls >= 1, "speech window never reached Whisper"+ finally:+ stop.set()+ await src.put(None)+ feeder.cancel()+ try:+ await feeder+ except (asyncio.CancelledError, Exception): # noqa: BLE001, S110+ pass+++async def test_hallucination_at_quiet_mic_floor_stays_suppressed() -> None:+ """AP-27 pin on the LOWERED gates: on a quiet mic (floor ~0.0008) a+ breath/rustle window (rms ~0.0014, peak ~0.0026) whose transcript+ hallucinates the phrase must NOT fire — it sits below 1.4x-floor-derived+ match gate. Silence can never fire, on ANY mic."""+ stt = _PhraseSTT("hey nico") # every transcription "hears" the phrase+ wake = RollingWhisperWake(+ stt,+ pattern=re.compile(r"nico", re.IGNORECASE),+ poll_interval_s=0.01,+ cooldown_s=0.0,+ save_debug_wavs=False,+ )+ src: asyncio.Queue = asyncio.Queue()+ stop = asyncio.Event()+ holder = {"chunk": _const_chunk(25)} # hiss ~0.0008 — calibration phase+ feeder = asyncio.create_task(_feed_switchable(src, stop, holder))+ try:+ detect = asyncio.create_task(_first_keyword(wake, src))+ await asyncio.sleep(1.0)+ holder["chunk"] = _spiky_chunk(45, 85) # rms ~0.0014, peak ~0.0026+ await asyncio.sleep(1.5)+ assert not detect.done(), (+ "floor-level noise fired the wake — the relative match gate leaks"+ )+ detect.cancel()+ try:+ await detect+ except asyncio.CancelledError:+ pass+ finally:+ stop.set()+ await src.put(None)+ feeder.cancel()+ try:+ await feeder+ except (asyncio.CancelledError, Exception): # noqa: BLE001, S110+ pass+++# --- Effective gates: lower-only, maintainer parity, opt-outs preserved -----+++def _wake_with_floor(floor: float, **kwargs) -> RollingWhisperWake:+ wake = RollingWhisperWake(+ _PhraseSTT("hey nico"), pattern=re.compile(r"nico"), **kwargs+ )+ wake._noise_floor._floor = floor+ return wake+++def test_effective_gates_equal_legacy_absolutes_on_maintainer_mic() -> None:+ # Floor ~0.0046 (the maintainer's idle hiss): every relative gate lands+ # ABOVE its legacy absolute and is capped there — behavior is bit-identical+ # to before the calibration, so all historical measurements stay valid.+ wake = _wake_with_floor(0.0046)+ assert wake._effective_match_min_rms() == pytest.approx(0.006)+ assert wake._effective_min_rms() == pytest.approx(0.003)+ assert wake._effective_min_peak() == pytest.approx(0.008)+++def test_effective_gates_scale_down_on_a_quiet_mic() -> None:+ wake = _wake_with_floor(0.0008)+ assert wake._effective_match_min_rms() == pytest.approx(0.0015) # abs min+ assert wake._effective_min_rms() == pytest.approx(0.001) # abs min+ assert wake._effective_min_peak() == pytest.approx(0.002) # abs min+ # The gates never collapse to zero — a muted mic's digital silence stays+ # below every absolute minimum, so hallucinations on mute cannot fire.+ muted = _wake_with_floor(0.0)+ assert muted._effective_match_min_rms() >= 0.0015+ assert muted._effective_min_rms() >= 0.001+ assert muted._effective_min_peak() >= 0.002+++def test_explicit_gate_opt_outs_are_preserved() -> None:+ # Tests and callers that DISABLE a gate (<= 0) keep that semantic; callers+ # that override a gate lower than the relative value keep their cap.+ wake = _wake_with_floor(0.02, min_rms=0.0, min_peak=0.0, match_min_rms=0.0)+ assert wake._effective_match_min_rms() == 0.0+ assert wake._effective_min_rms() == 0.0+ assert wake._effective_min_peak() == 0.0+++# --- SessionNoiseFloor unit behavior ----------------------------------------+++def test_noise_floor_adapts_down_on_quiet_windows() -> None:+ nf = SessionNoiseFloor()+ for _ in range(200):+ nf.update(0.0008)+ assert nf.floor == pytest.approx(0.0008, rel=0.15)+++def test_noise_floor_ignores_speech_windows() -> None:+ nf = SessionNoiseFloor()+ start = nf.floor+ for _ in range(200):+ nf.update(0.05) # clear speech — far above the quiet band+ assert nf.floor == start+++def test_noise_floor_never_drops_below_absolute_minimum() -> None:+ nf = SessionNoiseFloor()+ for _ in range(500):+ nf.update(0.0) # muted mic / digital silence+ assert nf.floor >= 0.0002