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.

fix(wake): self-heal wedged ctranslate2 transcription; harden custom-word wake (BUG-036)

Ruben Lütke26d1421ec445
diff --git a/AGENTS.md b/AGENTS.md
index 722611a0e9..1ca8d47d7c 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -1,415 +1,113 @@
# CLAUDE.md
-Guidance for OpenClaw (claude.ai/code) and any sub-agent working in this repository.
+Binding guidance for any coding agent working in this repository. This file is
+deliberately lean — it holds the rules you must respect on **every** change.
+Product/architecture reference detail lives in
+[`docs/architecture-overview.md`](docs/architecture-overview.md).
---
-## ⚠️ THE GitHub repository — ONE public repo + mandatory privacy gate (BINDING, updated 2026-06-19)
+## 0. CLAUDE.md ≡ AGENTS.md (mirror rule — BINDING)
-**There is ONE project repo: the public flagship `https://github.com/PersonalJarvis/PersonalJarvis`** (PascalCase). EVERY maintainer "commit / push / save to GitHub / sichere den Stand" targets THIS repo and no other. <!-- i18n-allow: quoted German maintainer trigger phrase --> The lowercase `personal-jarvis` (git remote `origin`) is kept ONLY as a **silent local backup / safety net** — it is not "the project" and is never the deliverable. Never ask "which repo"; it is always the public flagship.
-
-### Nothing reaches the public repo raw — the fail-closed privacy gate (MANDATORY on EVERY push)
-
-The public repo only ever receives a **depersonalized snapshot**, never the raw working tree. Every push runs the full gate, in order, fail-closed (any uncertainty STOPS the push):
-
-1. **Tracked-files-only export** — `.gitignore` exclusions enforced for free: no `data/`, `.env`, `jarvis.toml`, Vault, keys.
-2. **Distribution denylist** — internal dev docs, scratch scripts, signing keys removed.
-3. **Deterministic PII scrub** — real name, personal paths, project ids masked.
-4. **🔍 Mandatory sub-agent privacy review (the maintainer's hard requirement, 2026-06-19)** — before any push, a dedicated sub-agent reads the ENTIRE staged snapshot and reports anything personal or sensitive the deterministic scanners might miss: API keys / tokens / secrets, credentials, personal data, private paths / emails, internal-only content. It may only ADD blocking findings; it can never clear what the deterministic gate blocks. A non-empty finding STOPS the push.
-5. **Deterministic secret/PII scan** — fail-closed, real-credential-length regexes.
-6. **Human review** — explicit maintainer go before any network write.
-
-This whole gate is the `ship-public-release` skill; the public push runs from a separate clean clone, so the working tree is never touched and raw state cannot leak.
-
-### Two volumes on the SAME gate
-
-- **Discreet (DEFAULT)** — "Push nach GitHub", "push", "commit and push", "sichere den Stand", "update GitHub". → Clean snapshot through the full gate above, committed to the public repo, with **no SemVer bump, no git tag, no GitHub Release, no announcement**. Just the current clean state, quietly updated. <!-- i18n-allow: quoted German maintainer trigger phrases -->
-- **Release (explicit only)** — "Neue Version shippen", "Mach ein Release", "Publish release", "veröffentliche eine neue Version". → the same gate **plus** a MAJOR/MINOR/PATCH bump + git tag + CHANGELOG entry. <!-- i18n-allow: quoted German maintainer trigger phrases -->
-
-When the volume is ambiguous, default to **discreet** (snapshot, no version bump).
-
-### Guardrails that stay in force
-
-- **Never `git push` raw working state to `PersonalJarvis/PersonalJarvis`.** The pre-push guard (`scripts/ci/guard_no_raw_public_push.py` + `scripts/ci/privacy_pre_push.py`, wired into `.githooks/pre-push`, `core.hooksPath=.githooks`) HARD-BLOCKS a raw push to the public repo. It protects you precisely *because* the legitimate snapshot pushes from a separate clone — the guard only ever catches an *accidental* raw push. Do not remove it.
-- The silent `origin` backup may receive raw dev commits as infrastructure, but that is never what "get my work onto GitHub" means — the deliverable is always the clean public snapshot.
-- **Skill routing:** any maintainer "push / commit / save to GitHub" in this repo is the `ship-public-release` skill (discreet mode by default). `save-to-github` and `github-version` share those trigger phrases but MUST NOT run here — they would push raw state to `origin` / cut a tag, bypassing the privacy gate. They are out of scope for this repo.
-
-Full mechanism: the `ship-public-release` skill (`.claude/skills/ship-public-release/SKILL.md`). Repo doctrine + history: [`CLOUD.md`](CLOUD.md) § "Canonical repositories".
-
----
-
-## Output Language Policy (HIGHEST PRIORITY)
-
-**Every artifact an agent produces in this repo is English.** No exceptions.
-
-This covers code, comments, docstrings, log/exception messages, Markdown (READMEs, ADRs, plans, `BUGS.md` entries, handoffs), `SKILL.md` files, commit messages, PR titles/bodies, test names + docstrings, CLI help text, FastAPI route descriptions, error responses, JSON schema `description` fields, audit-log entries, telemetry event names, and any new UI strings (i18n key + English source — never German source).
-
-This rule overrides historical "Sprache: Deutsch" sections in this file and any memory entry asking for German artifacts. If unsure: **default to English**.
-
-**What stays German:** the user-facing chat reply written by the assistant in conversation (per global `~/.claude/CLAUDE.md`), TTS output (bilingual DE+EN auto-detect at runtime), and already-committed German content (do not retro-translate unless asked).
-
-**Enforced in CI (not just documented):** the `language-policy` job in `.github/workflows/ci.yml` blocks any *newly added* German line from merging to `main` (diff-based, so the in-flight DE→EN backlog stays green). It is a required status check. Intentionally-German exceptions: an inline `i18n-allow` marker on the line, or a glob in `scripts/ci/german-allowlist.txt`. See `docs/superpowers/specs/2026-05-30-ci-language-policy-gate-design.md`.
+`CLAUDE.md` and `AGENTS.md` are **byte-identical twins**. `AGENTS.md` is the
+cross-tool standard name other agents read; `CLAUDE.md` is the canonical source.
+**Every edit to this file is mirrored into `AGENTS.md` automatically — you do not
+need to be asked, and you must never let them drift.** The sync engine is
+`scripts/ci/sync_agents_md.py` (live `PostToolUse` hook + `.githooks/pre-commit
+--stage` + a `--check` CI gate). After editing either file, run the sync (or just
+copy one onto the other) so the tree stays in sync before you commit.
---
-## Runtime Output Language (voice + chat) — BINDING
+## 1. Language — an international, English-first project
-This is the **runtime** language contract for what Jarvis *speaks and writes back to the user*. It is the sibling of the Output Language Policy above and does **not** weaken it: source artifacts stay English; the live spoken/written reply is multilingual product surface. (Forensic that motivated this section: 2026-06-18 — a German utterance was mis-transcribed by STT as English text, and because the language decision was re-derived per layer with no authoritative pin, the *entire* chain — ack preamble, answer, status line, TTS voice — went English. See `docs/BUGS.md`.)
+**Personal Jarvis is an international open-source project. Its working language is English — not German, not any other single human language.** Assume contributors and downloaders worldwide; never bias the codebase, docs, or defaults toward one locale. Every artifact an agent produces in this repo is English, full stop.
-**The rule (every supported language equally — de, en, es, and any future locale; never a German- or English-only bias):**
+- **Artifacts = English, always.** This covers code, comments, docstrings, log/exception messages, Markdown (READMEs, ADRs, plans, `BUGS.md` entries, handoffs), `SKILL.md` files, commit messages, PR titles/bodies, test names + docstrings, CLI help text, FastAPI route descriptions, error responses, JSON-schema `description` fields, audit-log entries, telemetry event names, and any new UI strings (i18n key + English source — never a non-English source). If unsure, default to English. This overrides any historical "Sprache: Deutsch" note. Enforced by the diff-based `language-policy` CI job (escape hatch: an inline `i18n-allow` marker or a glob in `scripts/ci/german-allowlist.txt`).
+- **The chat / conversation language is each contributor's own choice, NOT something this repo dictates.** How an agent talks to *you* in chat is set in your personal global config (`~/.claude/CLAUDE.md` / `AGENTS.md`) — a German maintainer, a Spanish contributor, and an English one each set their own. This project neither requires nor assumes any particular chat language; it only fixes the artifacts as English.
+- **Exempt from the English rule:** already-committed non-English content (don't retro-translate), and the runtime TTS/voice product surface (below), which is multilingual by design.
-1. **A turn's output language is decided exactly once, by one authoritative resolver, and every output layer consumes that one decision.** The resolver is `jarvis/core/turn_language.py::resolve_output_language(reply_language, stt_language, text, *, default, conversation_language)`. Precedence, highest first:
- - an explicit **`brain.reply_language` pin** (`de`/`en`/`es`) — the user-selected language wins over everything, regardless of what STT heard;
- - else **conversation stickiness**: a *thin* turn (a one- or two-word interjection like "Now"/"Stop"/"jetzt", or a lone loanword — `is_substantive_turn`) is spoken in the running `conversation_language` and must NOT flip it; only a *substantive* turn switches the language. The `BrainManager` owns `conversation_language` (updated only on substantive turns), exposes it to the speech pipeline, and threads it — via `ExecutionContext.config["output_language"]` stamped by the tool-use loop — to deterministic tool readbacks (e.g. `computer_use` "On it"/"Done"). Forensic 2026-06-18: a lone English "Now" in a German voice chat flipped the whole turn (CU ack + status + readback) to English;
- - else the **detected input language** of the turn (text heuristic first, STT tag breaks ties — `resolve_turn_language`);
- - else the **configured default locale** (`turn_language.DEFAULT_LOCALE`) — never a per-layer hardcoded constant.
-2. **The rule applies to ALL user-facing output, with no exception for "intermediate" surfaces:** the deep-brain reply, the ack-brain preamble, spawn announcements, every canned status / error / clarify / timeout / provider-down / STT-unavailable phrase, every deterministic Computer-Use / local-action readback, **and** the TTS voice / BCP-47 selection. A status or error line like "Something went wrong" must come out in the same language as the answer would have. An unprompted mid-session language switch between layers is a bug.
-3. **No layer may re-derive the language on its own terms.** Specifically forbidden: a binary `"de" if _looks_german(...) else "en"` shortcut (it silently drops `es`); a phrase table keyed `de`/`en` only (an `es` speaker then hears the wrong language); a per-layer hardcoded default (`"en"` in one place, `"de"` in another → layers diverge); any spoken/written path that ignores the `brain.reply_language` pin. When you add a new spoken/written phrase table, it carries **all** supported languages, and you resolve its key through the one resolver.
-4. **Honesty over guessing.** When a layer genuinely cannot determine the language, it falls back to `DEFAULT_LOCALE` — it does not invent a different default. Pure-auto mode cannot fully defend against a confident STT mis-transcription (German speech → clean English text); the durable guarantee for a single-language user is to **set `brain.reply_language`**, which pins every layer.
+### Runtime output language (voice + chat) — BINDING
-`brain.reply_language` is the single user-facing control (`auto` | `de` | `en` | `es`), editable from the desktop **Languages** view (`PUT /api/settings/reply-language`, hot-reloads, no restart). `auto` mirrors the spoken/written input language; a pin forces the selected language across the whole chain. Regression guards live in `tests/unit/core/test_turn_language.py`, `tests/unit/speech/test_phrase_language.py`, and the `tests/unit/brain/test_*language*.py` set — extend them whenever you touch a spoken path.
+This governs what Jarvis **speaks/writes back to the user** (a multilingual product surface — it does NOT weaken the English-artifact rule). Supported languages are equal — `de`, `en`, `es`, and any future locale; never a German- or English-only bias.
-**Coverage today (2026-06-18) and the one known gap.** The deep-brain reply, the speech-pipeline output-language resolution + every canned status / error / clarify / timeout / brain-unavailable / STT-unavailable phrase, the deterministic Computer-Use / local-action readbacks, the leak-recovery + evidence-unfulfilled + provider-down honesty phrases, and the TTS voice pin all resolve through `resolve_output_language` and cover **de / en / es**. The one layer still **de / en only** is the Ack-Brain pre-thinking *preamble persona* (`jarvis/brain/ack_brain/persona_prompt.py`) and the *spawn-announcement composer* (`spawn_announcement.py`): an `es` turn there falls back (preamble → German persona; spawn → English/pool). These two are **not** a free edit — `PERSONA_PROMPT_DE/EN` are constants locked to the flash-brain spec (`docs/superpowers/specs/2026-05-11-pre-thinking-ack-flash-brain-design.md`), so adding a Spanish preamble persona requires amending that spec first. Bringing the Ack-Brain surfaces to `es` is the tracked follow-up to fully satisfy this doctrine; until then, an `es`-pinned user still gets the correct language everywhere except the optional sub-second preamble.
+1. **A turn's output language is decided exactly once, by one resolver — `jarvis/core/turn_language.py::resolve_output_language` — and every output layer consumes that one decision.** Precedence: explicit `brain.reply_language` pin → conversation stickiness (a thin one/two-word interjection is spoken in the running `conversation_language` and must NOT flip it; only a substantive turn switches) → detected input language → configured `DEFAULT_LOCALE`.
+2. **It applies to ALL user-facing output** — deep reply, ack preamble, spawn announcements, every canned status/error/clarify/timeout/provider-down phrase, every deterministic Computer-Use/local-action readback, AND the TTS voice/BCP-47 pick. A mid-session language flip between layers is a bug.
+3. **No layer may re-derive the language on its own** — no `"de" if _looks_german() else "en"` shortcut (drops `es`), no `de`/`en`-only phrase table, no per-layer hardcoded default, no path that ignores the pin. New phrase tables carry **all** supported languages and resolve their key through the one resolver.
+4. **Honesty over guessing** — a layer that genuinely cannot tell falls back to `DEFAULT_LOCALE`. The durable guarantee for a single-language user is to set `brain.reply_language` (`auto` | `de` | `en` | `es`), editable from the desktop **Languages** view. Regression guards: `tests/unit/core/test_turn_language.py`, `tests/unit/speech/test_phrase_language.py`, `tests/unit/brain/test_*language*.py`.
---
-## Cloud-First Philosophy (BINDING — overrides historical "Windows 11" framing)
-
-**Target runtime is any €5 / month VPS or low-spec laptop** with a modern browser. *Not* the maintainer's RTX 5070 Ti / Windows 11 workstation. Every architectural decision, default value, doc paragraph, dependency, and PR from 2026-05-18 forward is evaluated against the VPS user — the maintainer's machine represents fewer than 0.1 % of the install base this project is being designed for.
-
-**Top-level charter:** [`CLOUD.md`](CLOUD.md) (Rule #1 = cross-platform). **Full doctrine:** [`docs/PHILOSOPHY.md`](docs/PHILOSOPHY.md). On conflict between this file and `PHILOSOPHY.md`, the doctrine wins. On conflict between the doctrine and the binding plan, the doctrine wins on hardware assumptions, the plan wins on architectural decisions.
-
-The short version:
-
-- **RULE #1 — everything we build must run on Linux, macOS, AND Windows (plus headless Linux server).** No platform is second-class; a feature that only works on one OS is *incomplete*, not "done with a known limitation". The base `pip install` + boot must succeed on a fresh `python:3.11-slim` Linux container, on macOS, and on Windows. OS-specific code is allowed only behind (a) a runtime capability check, (b) an extras group, and (c) a graceful English-message no-op on the other platforms. Use `pathlib`, capability probes, and UTF-8 by default — never hardcode `C:\Users\...` or assume cp1252. See [`CLOUD.md`](CLOUD.md).
-- **All five provider classes (Brain, STT, TTS, Vision, Wake) must have a fully cloud-reachable default path** — no required local GPU, no required local model, no required Windows API, no required microphone, no required speaker.
-- **No new hard dependency on Windows-specific or GPU-specific packages.** New imports of `pywin32`, `pywinauto`, `pyautogui`, `sounddevice`, `faster-whisper`, `onnxruntime-gpu`, `openwakeword`, `global-hotkeys`, `mss`, `pywebview` go into a `[desktop]` extras group, *not* the base install.
-- **The maintainer's setup is a power-user profile, not a baseline.** Tray app, Orb overlay, global-hotkey wake, local Whisper, Silero-VAD-in-process, drift-guard PowerShell daemon, Computer-Use harness — **all opt-in extras**, all degrade gracefully (with a clear English-language message) when the extras are not installed.
-- **Headless VPS + browser UI is a first-class runtime.** A user opening the FastAPI / WebSocket frontend in any browser, using the browser's microphone and speakers (or a channel adapter — Telegram, Discord, SMS, webhook), must reach the full Router-Brain → Worker-Critic → Mission-Manager experience without installing a Windows binary, a CUDA toolkit, or a native audio driver.
-- **Documentation, defaults, install instructions, and onboarding lead with the VPS path.** Windows-desktop instructions are a footnote inside an "Optional power-user extras" section. Re-order the doc when in doubt.
-
-**Pre-existing code that violates this doctrine is grandfathered until touched.** A code path that already hardcodes a local-hardware assumption does not need to be rewritten in a panic — but any *touch* of that path is an opportunity to migrate it toward the cloud-first default, not extend the violation.
-
-**Maintainer dev tooling (`scripts/preflight.ps1`, `run.bat`, `scripts/drift-guard-daemon.ps1`, `scripts/check-working-tree.ps1`, `scripts/auto-push-eod.ps1`) may stay Windows-PowerShell-only.** That is the maintainer's *developer* environment, not the consumer's *runtime*. The line is drawn at the boundary between `scripts/` (developer tools — fair game to stay Windows-only) and the importable `jarvis/` package (runtime — must run on a Linux VPS).
-
-**Decision lens for any PR:** *Would this PR work, end-to-end, for a user on a fresh `python:3.11-slim` Linux container with 1 vCPU, 1 GB RAM, no GPU, no audio hardware, no Windows APIs, and only a network connection?* If yes → merge. If no → either (a) the local-only portion is correctly gated behind an extras group with a graceful no-op fallback in the base install, or (b) split the PR.
-
----
-
-## Project
-
-**Personal Jarvis** — voice-driven meta-orchestrator for Windows 11. Not a classical voice assistant: the core pattern is **Supervisor-Agent** that dispatches work to interchangeable harnesses (OpenClaw subprocess, Codex CLI, Open Interpreter, MCP servers). The voice layer is just the interface.
-
-**Master plan:** `~/.claude/plans/also-er-muss-auch-lexical-pond.md` — binding for all design decisions. On conflict between plan and code, the plan wins; code deviations must be documented back in the plan.
-
-**Binding architecture contracts:**
-- [`docs/openclaw-bridge.md`](docs/openclaw-bridge.md) — OpenClaw harness contract (AD-1..AD-21, AP-OC1..AP-OC14). Welle 1 (spike) + Welle 4 (sub-jarvis deletion) are done; Welle 2 (live bridge in default voice path) + Welle 3 (full live mode) remain.
-- [`docs/anti-drift-three-layer.md`](docs/anti-drift-three-layer.md) — five-layer enum pattern (Python ↔ SQL ↔ Pydantic ↔ TS ↔ UI). Mandatory for any string crossing module boundaries.
-
-**Bug register:** [`docs/BUGS.md`](docs/BUGS.md). Read before larger edits — the recurring bug classes (restore-trap, multi-layer enum drift, config drift, subprocess flicker, audio host-API) are catalogued there.
-
----
-
-## Phase Status
-
-| Phase | Live? | Pointers |
-|---|---|---|
-| **0–4 — Foundations** | ✅ | Plugin system + protocols, FastAPI/React desktop app, speech pipeline, skill system, tool-use loop, risk-tier executor, core memory, harness dispatch. Detail in `docs/phase{0,1,1a,1c,2,4}-*.md`. |
-| **5 — Vision/Action/Admin/Async/Control + Tiered Routing** | ✅ | `jarvis/{vision,admin,tasks,control,telemetry}/`. Computer-Use enabled. Tiered routing via `ROUTER_TOOLS` frozenset. ADR-0001..0011. |
-| **6 — Self-Healing Worker-Critic** | ✅ | `jarvis/missions/` (event store, manager, recovery, state machine, budget, cleanup, workers, critic, kontrollierer, safety, voice, isolation). ADR-0009, `docs/phase6-*.md`. Wired into REST + voice path via `bootstrap_missions`. **Live progress (2026-06-15):** both the Codex worker and `ClaudeDirectWorker` stream stdout line-by-line; the orchestrator drain loop emits throttled `WorkerProgress` (`jarvis/missions/events.py`) → WS → `ReasoningPanel` (the chain was dormant before). **Re-run (2026-06-15):** `POST /api/missions/{id}/rerun` re-dispatches a terminal mission's stored prompt as a NEW mission linked via `parent_mission_id` ("Continue" cancelled / "Restart" failed) — the source card is untouched audit; **no state-machine or idempotency change** (deliberate, avoids AP-14). |
-| **7 — Self-Mod (foundation + writer + tools)** | ✅ | `jarvis/core/self_mod/` (audit, errors, pending, registry, schema, writer). Three router-tier tools: `list_mutable_settings`, `get_config_value`, `set_config_value`. ADR + writeup in `docs/self_mod.md`. **7.5 `spawn-skill-author` IS now registered** (`pyproject.toml` → `jarvis.brain.tools.skill_authoring:SpawnSkillAuthorTool`, router-tier, `ask`; spawns the `SkillAuthoringRunner`). Generated skills land as `state="draft"` and are never auto-activated (AP-15). |
-| **Awareness A0–A5** | ✅ | `jarvis/awareness/` (state, story, salience, verdichter, working_set, episode, recall_store, watchers, probes). Router-tier tools `awareness-snapshot` (A1) + `awareness-recall` (A3). ADR-0009/0010/0012. Hard rule: **never on the voice critical path**. |
-| **Wiki B0/B1/B2/B3/B5/B7/B8/B9** | ✅ | `jarvis/memory/wiki/` (curator, atomic_writer, page_repository, integration, session_rollup, voice_bridge, telemetry, scheduler). Three router-tier tools: `wiki-recall`, `wiki-page-read`, `wiki-ingest`. ADR-0013/0014/0015. B2 = `docs/obsidian-setup.md` + B9-Wizard. B3 = `WikiView.tsx` + 6-endpoint `wiki_routes.py` + `wiki_ws.py` live-reload. **B4 soft-disabled** 2026-05-17 via `[memory.legacy_curator] enabled = false` — legacy Curator package + `data/workspace/` snapshot stay on disk; Hart-Cut (vault migration + reader refactor + package delete) remains open. **B6 not started**. |
-| **OpenClaw bridge** | ⚙ Welle 1+4 done | `jarvis/plugins/harness/openclaw.py`, `jarvis/missions/openclaw/`. `[harness.openclaw].enabled=true`. Welle 2 (live bridge as default) + Welle 3 (live-mode wrap) open. |
-| **Ack-Brain (pre-thinking)** | ✅ | `jarvis/brain/ack_brain/` — sub-second butler ACK before the deep brain replies. Gemini 3.1 Flash Lite primary, Grok fallback. UI preamble bubble. Suppress-if-fast gate at 2000ms (`[ack_brain].suppress_if_brain_faster_than_ms`). ADR-0014 (flash-brain). |
-| **CLI catalog + terminal view** | ✅ | `jarvis/clis/` (catalog, installer, loader, prober, registry, risk_integration, usage_log) + `jarvis/terminal/` (cross-platform PTY via `terminal.backend.make_pty_backend` — ConPTY/`pywinpty` on Windows, `ptyprocess` on POSIX). Router tool `cli-tools` (virtual loader → one `cli_<name>` tool per connected CLI). UI views: `ClisView`, `TerminalView`. **`spawn-cli-worker` was REMOVED 2026-05-24** (dead entry point; heavy multi-step CLI work goes through `spawn-worker`, single-step through the `cli_<name>` tools — never re-add a CLI spawn tool, it is a D9 recursion vector, AP-5/AP-14). |
-| **Board / Profile ("Knows-you" dashboard)** | ✅ | `jarvis/board/` (aggregator, store, achievements, evaluator, bio prompts, scheduler, `schema.sql`) → `data/board/personal.db`. Parses FlightRecorder JSONL into daily stats / personal records / 10 achievements + an anti-cliché AI-bio. Routes `board_routes.py` (`/api/board/*`) + `profile_routes.py`; views `BoardView.tsx`, `ProfileView.tsx`, `frontend/src/views/profile/`. Deterministic profile writes via the `update-profile` tool. Separate standalone service stub in `board-backend/` (FastAPI + Docker). CHANGELOG `v1.0.0-board`. |
-| **Channels (Web / Telegram / Discord)** | ✅ | `jarvis/channels/` (`base.py` ChannelAdapter, `manager.py`, `bootstrap.py` `bootstrap_channels`, `chat_bridge.py`, `web.py`/`telegram.py`/`discord.py`). Bridges a DM/guild message into the normal Jarvis chat path. Entry points `web` (base), `telegram` (base dep `python-telegram-bot`), `discord` (optional `[channels]` extra, lazy-imported, graceful `ChannelStartError` when absent). Tokens via Credential Manager. |
-| **Friends + Socials** | ✅ | `jarvis/friends/` (`registry.py` `FriendRegistry` on `aiosqlite`, `status_publisher.py`, `status_filter.py`, `messages.py`, `schemas.py`). Routes `friends_routes.py` + `socials_routes.py`; views `FriendsView.tsx`, `frontend/src/views/friends/` + `socials/`. Telegram channel is the live transport (F-FRIENDS F0/F1). |
-| **Contacts + Telephony** | ✅ | `jarvis/contacts/` (`store.py`, `schema.py`, `notify.py`) — contacts mirror to guaranteed Wiki person pages `people/<slug>.md` on `ContactChanged` (PII stays out of the page). Tools `contact-lookup` (safe), `contact-upsert` (monitor, write), `call-contact` (ask, echo-confirm). `jarvis/telephony/` (`outbound.py`, `twiml.py`, `provisioning.py`, `security.py`, `session.py`) places real outbound calls via Twilio. **Twilio is the optional `[telephony]` extra** — routes (`telephony_routes.py`) + `TelephonyManager` degrade gracefully when absent (AD-T8). Views `TelephonyView.tsx`, `frontend/src/views/contacts/`. |
-| **Marketplace plugins** | ✅ | `jarvis/marketplace/` (catalog + `auth/` OAuth + `oauth_callback_server.py` + `plugin_loader.py`/`plugin_registry.py`/`plugin_relevance.py` + `mcp_bridge.py`). The `plugin-tools` entry-point loader expands connected marketplace plugins into live brain tools. Native REST tools where a catalog transport was insufficient: `gmail` (`gmail_rest`, ask — send is consequential) + `vercel` (`vercel_rest`, monitor — read-only). Router-tier, never a spawn (AP-5/AP-14). Route `marketplace_routes.py`; views `PluginsView.tsx`, `ExtensionsView.tsx`. |
-| **Workflows** | ✅ | `jarvis/workflows/` (`runner.py`, `scheduler.py`, `store.py`, `schema.sql`, `seed.py`). Imperative cron/manual-triggered multi-step pipelines (brain-prompt / harness-dispatch / shell / tool-call / speak steps) — distinct from Phase-6 *missions* (single persistent self-healing action). Route `workflows_routes.py` (CRUD); `bootstrap_workflows` on `app.state`. View `WorkflowsView.tsx`. |
-| **Conductor** | ✅ | **Separate root package `conductor/`** (`api/`, `core/`, `jobs/`, `seed/`, `cli.py`) with its own SQLite store — a YAML-first agentic-workflow canvas (shell/http/agent jobs, cron/webhook/manual triggers, timeline view). Jarvis mounts the Conductor router inside its own FastAPI server → `ConductorView.tsx`. Do not confuse with **Workflows** (imperative, in-`jarvis/`) — Conductor is YAML-first and standalone-capable. |
-| **Sub-Agents / Outputs** | ✅ | `jarvis/agents/registry.py` builds an in-RAM sub-agent event tree from the EventBus (OpenClaw/Brain/Tool signals; TTL-cached, no DB) → `sub_agents_routes.py` (`/api/sub-agents/tree`) + `SubAgentsView.tsx`. **Outputs** (`outputs_routes.py` + `OutputsView.tsx`) list a mission's *deliverables* from the filesystem (`<repo_parent>/sub-agents-outputs/<slug>/`, NOT a DB). An "artifact" is a `.md`/PDF/HTML/code file a worker produced. Per-artifact download (`Content-Disposition` attachment) / view (server-rendered markdown→HTML under a strict `default-src 'none'` CSP) / desktop-only reveal+open-with-default-app via `jarvis/platform/open_path.py`; native actions are off on headless/VPS (`native_file_actions` launcher flag). |
-| **Frontier (model auto-switch)** | ✅ | `jarvis/brain/frontier_{resolver,autoswitch}.py` query each provider's `/v1/models` at boot, detect newer models, and propose switching `BrainProviderConfig`; the user acknowledges via a modal → `POST /api/frontier/ack`. Route `frontier_routes.py` (`/api/frontier/{pending,ack}`); cache `data/frontier_cache.json` (24h TTL). Aligns with the "frontier-quality-before-cost" user preference. |
-| **Preview / Pointer / Federation** | ✅ | `jarvis/preview/registry.py` + `preview_routes.py` — registry of dev-server iframes (Vite `:5173`, Storybook) surfaced in the sidebar; paired with the `start-preview-server` / `verify-localhost` self-verification tools. `jarvis/pointer/` (`intent.py`, `context.py`, `turn.py`) — "AI Pointer": resolves the UI element under the mouse cursor via the OS accessibility tree (not a screenshot), attached only on deictic intent ("what's that", "click there"); router tool `inspect-pointer`. `federation_proxy_routes.py` — local signing proxy to the Board-federation backend (frontend has no privkey; signs with the Credential-Manager key; path-whitelist anti-traversal). |
-
-Infra-only (no UI, consumed internally): `jarvis/hardware/detection.py` (CPU/GPU/VRAM/CUDA probe + Whisper-model sizing for the wizard / `--check`); `jarvis/orchestrator/` (currently a thin L6 seam — most supervisor logic lives in `jarvis/missions/`); `jarvis/diagnostics/`.
-
-Still unrowed (verify with `ls jarvis/ui/web/*routes*.py` + `git log`): `chats`/`sessions`. Treat the absence of a row as "undocumented, not absent" — the filesystem + `git log -- <module>` is the source of truth.
-
-Status drift moves fast. Verify with `git log -- <module>` rather than trusting this table. *(Table cross-checked against the working tree on 2026-06-16; the rows above were added that day after confirming each module's files + route + view exist.)*
-
----
-
-## Architecture (the parts an agent must respect)
-
-### 8-Layer model
-
-```
-L7 UI/UX Tray, Toasts, Admin-API, Desktop-App (FastAPI+React+pywebview), Orb-Overlay
-L6 Orchestrator State-Machine, Router, BrainManager, Supervisor, Mission-Manager
-L5 Harness-Adapter OpenClaw, Codex, Open Interpreter, Python-Script, MCP-Remote
-L4 Brain 5 providers (Claude-API, OpenRouter, OpenAI, Gemini, Grok) + Ack-Brain sub-second tier
-L3 Intent/Risk Classifier, Risk-Tier-Policy, Approval, Rate-Limit-Tracker
-L2 Speech Wake → VAD (Silero) → STT (faster-whisper / Google) → TTS (Gemini Flash / Grok-Voice / SAPI5)
-L1 Audio I/O WASAPI via sounddevice, Device-Routing, Chime-Feedback
-L0 OS/Hardware Win32, CUDA, Mic/Speakers, global-hotkeys
-```
-
-**Dependency rule (strict):** higher layers reach lower layers **only via protocols** (`jarvis/core/protocols.py`). Lateral communication is **only** via typed events on `EventBus` (`jarvis/core/bus.py`) with `frozen=True` dataclasses carrying `trace_id` + `timestamp_ns`. Subscriber exceptions are swallowed in `_safe_dispatch` — they must never propagate.
-
-### Plugin system (structural, not nominal)
-
-Plugins live under `jarvis/plugins/<group>/<name>.py`, register via `pyproject.toml` `[project.entry-points."jarvis.<group>"]`, and **must not import from `jarvis.*`** inside the plugin module — only structural compatibility with the protocol (registry at `jarvis/core/registry.py`). After editing entry-points: `pip install -e . --no-deps`.
-
-Groups (frozen in `PLUGIN_GROUPS`): `jarvis.wakeword`, `jarvis.stt`, `jarvis.tts`, `jarvis.brain`, `jarvis.harness`, `jarvis.tool`, `jarvis.channel`.
-
-### Streaming first
-
-All `Brain`, `STT`, `TTS`, `Harness` provider methods return `AsyncIterator[...]`. Non-streaming providers yield exactly one element. Consumers always write `async for chunk in provider.xxx()`.
-
-### Event-Bus
+## 2. GitHub — ONE public repo + mandatory privacy gate (BINDING)
-- Events are `frozen=True` dataclasses (`jarvis/core/events.py`) with `trace_id: UUID` + `timestamp_ns`. Immutability enables flight-recorder replay.
-- `subscribe_all` receives every event — the flight recorder is a wildcard subscriber.
-- A broken subscriber is logged, never propagated.
+**There is ONE project repo: the public flagship `https://github.com/PersonalJarvis/PersonalJarvis`** (PascalCase). EVERY maintainer "commit / push / save to GitHub / sichere den Stand" targets THIS repo and no other. <!-- i18n-allow: quoted German maintainer trigger phrase --> The lowercase `personal-jarvis` (git remote `origin`) is kept ONLY as a **silent local backup** — never the deliverable. Never ask "which repo"; it is always the public flagship.
-### Secrets
+**Why the gate exists:** the public repo's history is world-readable forever. One leaked API key, real name, personal path (`C:\Users\<name>\...`), private email, internal project id, or Windows SID that lands in a single commit is permanent — deleting it later does NOT un-publish it (it survives in clones, forks, and caches). So nothing reaches the public repo raw: every push is rebuilt as a **depersonalized snapshot** that runs the full gate below, in order, **fail-closed** — at any step, any uncertainty STOPS the push rather than letting a questionable line through.
-Access via `jarvis.core.config.get_secret(key, env_fallback)` only. Hierarchy: Windows Credential Manager (service `personal-jarvis`) → ENV → `.env` (dev fallback). The wizard (`jarvis/setup/wizard.py`) populates Credential Manager. **Never** put API keys in code, `jarvis.toml`, commits, or `.claude/` files. Voice/chat must never accept secrets (AP-2 — STT log leak vector).
+1. **Tracked-files-only export** — only git-tracked files are exported, so `.gitignore` is the first cut for free: `data/`, `.env`, `jarvis.toml`, the Vault, and key material are never even candidates.
+2. **Distribution denylist** — strips files that ARE tracked but must not ship publicly: internal dev docs, scratch/experiment scripts, signing keys, red-team notes.
+3. **Deterministic PII scrub** — pattern-based masking of the maintainer's real name, personal filesystem paths, machine/user identifiers, and internal project ids across every staged file.
+4. **Mandatory sub-agent privacy review** — a dedicated sub-agent reads the ENTIRE staged snapshot end-to-end and reports anything personal/sensitive the regex scanners could miss (keys, tokens, credentials, personal data, private paths/emails, internal-only content). It is **additive-only**: it can ADD a blocking finding but can never clear what the deterministic gate flagged. A single non-empty finding STOPS the push.
+5. **Deterministic secret/PII scan** — a final regex sweep tuned to real credential shapes/lengths (catches an actual key, not every random hex string), fail-closed.
+6. **Human review** — an explicit maintainer go-ahead before any byte crosses the network. No silent auto-publish.
-### Brain providers + ack-brain
+**Isolation (so the gate can't be bypassed by accident):** the push runs from a **separate clean clone**, never your live working tree — the working tree is never touched and the raw, un-scrubbed state physically cannot leak through. As a hard backstop, the pre-push guard (`scripts/ci/guard_no_raw_public_push.py` + `privacy_pre_push.py`, wired via `.githooks/pre-push`, `core.hooksPath=.githooks`) HARD-BLOCKS any attempt to `git push` raw working state straight to the public repo. Do not remove or weaken it — it has already caught a real leak (a Windows SID that reached public history was blocked, then purged with filter-repo). This whole gate is the `ship-public-release` skill.
-Multi-provider is mandatory — **never hardcode** Anthropic/Claude. Config under `[brain.providers.*]` in `jarvis.toml`. Runtime switch via voice ("Jarvis, switch to Gemini") is a plan requirement; `BrainManager` must support it. Smart fallback chain in `jarvis/brain/manager.py`. Workers use `claude-cli` backend via Claude Max OAuth (user has no Anthropic API account).
+**Two volumes, same gate:** *Discreet (DEFAULT)* — "push", "sichere den Stand", "update GitHub" → clean snapshot through the gate, **no version bump / tag / release / announcement**. *Release (explicit only)* — "Mach ein Release", "Publish release" → the same gate **plus** a SemVer bump + git tag + CHANGELOG entry. <!-- i18n-allow: quoted German maintainer trigger phrases --> When ambiguous, default to discreet.
-#### Provider-agnostic features (no provider/model hardcoding) — BINDING
-
-Every feature must work with **whatever brain provider the user has selected/activated**, and across all configured providers — there are five API providers (`claude-api`, `openrouter`, `openai`, `gemini`, `grok`) plus two subscription-CLI brains (`codex` over ChatGPT, `antigravity` over the Google login), and any of them may be the active one. **Never branch on a provider name or a model id to enable or disable behavior** — no `if provider == "grok"`, no hardcoded `grok-4.3`, no provider-specific code path. Gate on a **capability** instead: `supports_vision`, `supports_tools`, the runtime `can_call_tools()` (and codex's runtime `supports_vision`). If the capability you need doesn't exist yet, **add a capability flag — do not name-check the provider**.
-
-When the active/selected provider lacks a needed capability — e.g. a text-only CLI brain (`antigravity` / `codex-CLI`) cannot see images for Computer-Use — fall through to the first **available** provider that *has* the capability, provider-agnostically and never pinned to a favorite; if none is available, degrade gracefully with an honest message. A provider or model literal may appear **only** as a documented default/fallback (a plugin's own `DEFAULT_MODEL`) or behind a runtime capability probe — never as the gate that decides whether a feature runs. The Computer-Use "no vision" incident was a *capability-flag* bug (grok's `supports_vision` was wrongly `False`) — the correct fix was to set the flag, **not** to pin Computer-Use to grok. This generalizes AP-6 (don't hardcode Claude) to **don't hardcode *any* provider** and is the operational form of the multi-provider mandate above (see AP-21).
-
-Ack-Brain (`jarvis/brain/ack_brain/`) emits a sub-second butler-style preamble before the deep brain replies. Suppress-if-fast gate at 2000ms keeps it out of the way when the deep brain is already fast.
-
-**Persona / custom system prompt:** the live persona comes from `jarvis/brain/persona_loader.py`. `load_effective_persona_prompt()` returns an editable override (`data/custom_system_prompt.md`, written atomically via the Settings UI / `settings_routes.py`) when present, else the packaged `JARVIS_PERSONA.md`. Edits apply on the **next turn** (no restart); `invalidate_cache()` clears the in-process cache. Never hardcode the persona string elsewhere.
-
-### Risk-Tier system
-
-Four levels: `safe` / `monitor` / `ask` / `block`. Priority is **blacklist > whitelist > tool default** (`jarvis/safety/risk_tier.py`). Whitelist downgrades a tier to `safe` with `approved_by="whitelist"` — this is the anti-confirmation-fatigue contract. **Direct calls to `Tool.execute()` are a bug**; only `ToolExecutor.execute()` is authorized.
-
-### Router discipline (binding, ADR-0011 amended)
-
-The router-tier brain is a **pure dispatcher**. Tool surface is the `ROUTER_TOOLS` frozenset in `jarvis/brain/factory.py`. Direct actions outside this set are delegated to OpenClaw via `spawn_openclaw`.
-
-Force-spawn heuristic in `BrainManager._should_force_openclaw`:
-- Smalltalk allowlist wins → never spawn.
-- Action verb (`lies/baue/installiere/öffne/mach/zeig` + repair words) → spawn.
-- External-system marker (PR/Repo/GitHub/Issue) → spawn.
-
-Patterns configurable under `[brain.routing]`. **The sub-jarvis tier was deleted in Welle 4 — only `"router"` remains.** Resurrecting `SUB_TOOLS` or adding `spawn-openclaw`/`dispatch-with-review`/`run-skill` to any worker set breaks the D9 recursion guard. When extending `ROUTER_TOOLS`: amend ADR-0011 + extend `tests/unit/brain/test_routing.py`.
-
-### Output filter discipline (voice path)
-
-Brain output → TTS goes through `scrub_for_voice` in `jarvis/brain/output_filter.py` — **regex only, no LLM calls** (latency mandate). Two TTS paths are wired through scrub:
-- `_handle_utterance` → `_speak()` → `tts.synthesize` (`pipeline.py:1330`).
-- `_on_announcement` (skill/sub-agent announcements, OpenClaw `summary_de` readback) (`pipeline.py:647`).
-
-Whitelist (sacred, never scrubbed): `Datei, Email, Browser, Terminal, Notiz, Termin, Kalender`. Hyphen-compounds preserved (`Browser-Provider` stays). For the full blacklist (tool leaks, jargon, Sir-opener, markdown, self-reference, echo paraphrase, fillers, post-scrub fallback): see the module docstring and `tests/unit/brain/test_output_filter.py` (40 cases). ADR-0010.
-
-### Web search (`search_web`, router-tier)
-
-The `search-web` tool (`jarvis/plugins/tool/search_web.py`) runs a **priority backend chain** in `jarvis/plugins/tool/search_backends.py` (added 2026-06-15): keyed Brave API (if a key is set) → **real DuckDuckGo SERP via the key-free `ddgs` dependency (default)** → DuckDuckGo Instant Answer (last-resort encyclopedic abstract). Backend preference is `[search].backend`; the chain stays key-free so the base VPS install still searches. **Honesty contract:** each attempt returns a `SearchOutcome` with status `ok` / `empty` / `unavailable`. `empty` = searched, genuinely nothing; `unavailable` = backend unreachable — the brain must NOT say "no results" for `unavailable`, it must say search is down. Do not re-flatten these into one reply (that was the charts/weather "found nothing" forensic). The old Instant-Answer-only backend had no real-time index, so freshness queries (charts, news, prices, sports) always came back empty.
-
-### Atomic config writes
-
-Mutations of `jarvis.toml` go via `jarvis/core/config_writer.py` only — `tomlkit`-based (preserves comments), `_WRITE_LOCK` mutex, BOM-aware read/write, tempfile + `os.replace`. For Phase-7 self-mod, the pipeline is **non-negotiable**: Allowlist → Read → Apply → Pre-Validate (`JarvisConfig.model_validate`) → Backup → Tempfile+replace → sync reload-test → Rollback-on-fail → `ConfigReloaded` dispatch → Backup GC → Audit (AD-5; AP-3/4/5/13/14).
-
-Backup directory must be **outside** the watchdog scope (AP-13). Reload-test is **synchronous**, not watchdog-driven (AP-14).
-
-### Multi-layer enum drift prevention
-
-When a vocabulary spans Python ↔ SQL ↔ Pydantic ↔ TypeScript ↔ UI label (e.g. `HangupReason`), use the five-layer pattern from `docs/anti-drift-three-layer.md`. Reference: `jarvis/sessions/constants.py` is the single source of truth; `models.py` runtime-asserts the Pydantic `Literal` against it. Regression guards: `tests/unit/sessions/test_hangup_reason_parity.py` + `tests/integration/test_sessions_db_compatibility.py`. **BUG-008 recurred four times because this scaffolding was missing — apply it preemptively for any new wire-format enum (mission status, skill lifecycle, voice tier).**
-
-### Phase-6 isolation invariants
-
-- Every worker runs in a fresh `git worktree add -b agent/<task-slug>` under `<repo_parent>/sub-agents-outputs/` (≤200-char path cap). No writes to the user's working tree.
-- Every worker subprocess is contained for kill-on-crash: Windows via a Job Object with `JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE` (kernel guarantee — no zombies even on a hard kill); macOS/Linux via a POSIX process-group reaper (`start_new_session` + `os.killpg`-on-close) that reaps the worker tree on a clean shutdown / cancel / timeout / exception but, being userspace, leaks on a hard `kill -9` of the orchestrator itself (Linux follow-up: `PR_SET_PDEATHSIG`; no macOS equivalent).
-- `MAX_CRITIC_LOOPS = 3` is hardcoded. Not parameterizable. Changing requires a new ADR via `/skill phase6-adr-update`.
-- Action/Observation invariant (ADR-0009): the LLM never authors its own Observation. Voice readback reads only Kontrollierer-signed `MissionApproved.summary_de`, never `correction_instruction` from the Critic-LLM.
+**Guardrails:** **Do not PUSH unless the maintainer asks** (local auto-commit is fine and is governed by the Git-workflow rules in §9). `save-to-github` and `github-version` MUST NOT run in this repo — they push raw state and bypass the privacy gate above. Repo doctrine: [`CLOUD.md`](CLOUD.md).
---
-## Optimistic Execution & the "Oops" Protocol (binding)
-
-The core UX contract is **one uninterrupted spoken conversation**. The Talker (router-brain + ack-brain) acknowledges optimistically and never blocks on an MCP round-trip; the Heavy-Duty Worker (Mission-Manager + `claude-cli` Sonnet) executes in the background off the chat transcript. Seed vision: `Architektur-Spezifikation v1.0`. Reality-aligned close-the-gap plan + KPIs (M1–M5) + 4-wave execution: [`docs/plans/optimistic-execution-v1/README.md`](docs/plans/optimistic-execution-v1/README.md). The pillars below are partly live (ack-brain, force-spawn, mission store) and partly open (guaranteed-ACK-before-dispatch, the closed Oops loop, p95 SLO gates).
+## 3. Open-source universality — the maintainer's config is NEVER the baseline (BINDING)
-### Architecture Decisions
-- **AD-OE1** The optimistic ACK ("Geht klar") is emitted **before** the worker dispatch returns — never after. Audit every `_handle_utterance` return path (BUG-007/BUG-020 territory).
-- **AD-OE2** The Talker never `await`s an MCP/network call on the voice path. The talker↔worker queue is the in-process `EventBus` + mission event store — no external broker (cloud-first €5-VPS doctrine, no new hard dep).
-- **AD-OE3** Dumb tools (local scripts) resolve in-process via `local_action_gate`; they MUST NOT wake the worker (false-spawn rate = 0).
-- **AD-OE4** Smart tools: the **worker** issues the MCP call, never the Talker.
-- **AD-OE5** Oops loop: worker failure → frozen `WorkerCorrectionNeeded` event → inject into Talker context → speak ONLY at the next Silero-VAD turn-boundary → through `scrub_for_voice`. Never interrupt mid-utterance.
-- **AD-OE6** Zero silent drops: every worker/MCP failure yields a silent retry OR a spoken correction OR an audited apology (anti-BUG-020 invariant).
-
-### Coding Standards
-- Latency budgets are SLO-gated: p95 wake→ACK < 1.2 s, intent→ACK < 3.0 s, router decision < 150 ms. Regressions fail CI.
-- Every spoken path (utterance + announcement) goes through `scrub_for_voice` (regex only, no LLM call — AP-11).
-- New wire-format vocab (correction reasons, mission status) uses the five-layer enum pattern (`docs/anti-drift-three-layer.md`) + parity test.
-- `ROUTER_TOOLS` stays a frozenset; no spawn-tool ever enters a worker set (AP-5/AP-14). Every subprocess uses `NO_WINDOW_CREATIONFLAGS` (AP-1). Config writes go through `config_writer` (lock + tempfile + BOM-safe, AP-7).
-
----
+The recurring, expensive bug class on this project is **building/testing a feature against the maintainer's own machine, keys, providers, and OS — then shipping it broken for everyone else.** Two faces of ONE rule: **assume an arbitrary downloader, never the maintainer.** It governs the WHOLE product surface, and specifically the **entire API-Keys / credential / integration surface — not just brain providers:** STT, TTS, Vision, Wake, **Telephony (Twilio), Channels (Telegram/Discord), Marketplace plugins (OAuth + MCP), AND credential STORAGE itself.** Every one must:
-## Cross-platform desktop features (the six ports, behind `jarvis/platform/`)
+- **work with WHATEVER single key / login / account the user has** — no provider, model, or integration is load-bearing; a missing / empty / depleted / rate-limited (429) / out-of-credit (402) / unreachable one degrades or crosses to a **different family** with an honest message, and never bricks a core path (router, ack/flash, STT, sub-agent worker, mission critic). A tier whose primary AND fallback resolve to the same family is a single-provider brick (AP-22). Gate on **capability**, never a provider name or model id (AP-21).
+- **work on EVERY OS, including a headless `python:3.11-slim` VPS** with no OS keyring, no D-Bus Secret Service, no GPU, no audio, no Windows APIs. The base `pip install` + boot must succeed there. OS-specific code is allowed only behind (a) a runtime capability check, (b) an extras group, and (c) a graceful English-message no-op elsewhere. Use `pathlib` + capability probes + UTF-8; never hardcode `C:\Users\...` or assume cp1252.
+- **be recoverable IN-APP** — entering / switching / connecting a credential, and recovering from a dead one, happens inside the app, never by hand-editing `jarvis.toml`, exporting an ENV var, or spinning up a cloud instance.
+- **store credentials portably** — the OS keyring when present, else ENV/.env, else the local-file fallback (`config._ensure_keyring_backend`). A save/connect must never 500 on a host without a Secret Service.
-The six desktop power-user features that were historically Windows-only are now **cross-platform behind the shared `jarvis/platform/` capability seam** (`detect_platform()` + a cached frozen `Capabilities` snapshot, AD-5). Each feature is one `Protocol` + one per-OS implementation + a `sys.platform` factory + a graceful logged null-fallback (AD-6); the Windows implementations are **untouched** (AD-7 — they carry the BUG-009/012/014/030 fixes). The migration plan is `docs/plans/cross-platform-mac-linux/`; **ADR-0020 (cross-platform elevation) supersedes ADR-0001** but reuses the HMAC / Pydantic-argv / `shell=False` security core unchanged.
+**Definition of done (NON-NEGOTIABLE).** A change touching config, credentials, a provider/integration, or OS-specific code is NOT "done" — and must not be claimed done — until you verify, with a test or an honest manual trace, the THREE paths that are NOT the maintainer's:
+1. **Fresh install, ONE arbitrary key** — a downloader whose only credential is for a DIFFERENT provider reaches a working path (chat + voice + sub-agent + the touched feature), entirely in-app.
+2. **Headless Linux** — base `pip install` + boot + the touched feature work on `python:3.11-slim`; local-only parts degrade to a logged no-op.
+3. **Cross-family fallback** — when the configured provider/integration is absent or dead, the path crosses to whatever the user actually has, or degrades honestly — never dead-ends on the maintainer's favorite.
-| Feature | Factory | Windows | macOS | Linux | Verification |
-|---|---|---|---|---|---|
-| Terminal (PTY) | `terminal.backend.make_pty_backend` | ConPTY (`pywinpty`) | `ptyprocess` | `ptyprocess` | CI-provable (real PTY, EK-4) |
-| App-launch | `plugins.tool.app_resolver.resolve_app_launch_target` | App Paths | `open -a` | `xdg-open`/exec | CI-provable (resolution) |
-| UI-element-click | `vision.tree_factory.make_ui_tree_source` | UIA | AX (`pyobjc`) | AT-SPI (`pyatspi`) | live sign-off (AX/AT-SPI tree) |
-| Orb overlay | `overlay.surface.make_overlay_surface` | Tk color-key | Tk `-transparentcolor` | best-effort + tray | live sign-off (transparency) |
-| Hotkey | `trigger.backends.make_hotkey_backend` | `global-hotkeys` | `pynput` | `pynput` (X11); Wayland no-op | live sign-off (capture) |
-| Admin/elevation | `admin.transport.make_admin_transport` + `admin.elevator.make_elevator` | UAC + SDDL pipe | Authorization Services + unix socket | pkexec/sudo + unix socket | live sign-off (prompt); never CI-E2E |
-
-**Verification is honestly labelled per feature in `docs/plans/cross-platform-mac-linux/SIGNOFF-LOG.md`.** As of this writing the maintainer has Windows only and nothing is pushed, so every macOS/Linux **live** GUI/permission behavior is `unverified-on-real-desktop` and the `ci.yml` matrix is `CI-configured` (first green run pending push) — **never** claim "CI-verified" or "live-verified" until that log says so. Operators run `scripts/crossplatform/signoff_probe.py` on a real device to fill it in.
-
-- **Dependency reality (AD-14 — do not "fix" this):** `pynput` + `ptyprocess` live in the `[desktop]` extra (no platform marker; `ptyprocess` gated `sys_platform != 'win32'`); `pyobjc-framework-{Quartz,ApplicationServices,Accessibility}` in `[desktop-macos]` (`sys_platform == 'darwin'`). **Linux `pyatspi` is NOT on PyPI — never add it as a pip dependency.** It is GObject-Introspection, distro-packaged (`apt install python3-pyatspi gir1.2-atspi-2.0`), surfaced via the `capabilities.has_ax_tree` runtime probe. A future agent "fixing" a missing-pyatspi pip dep would be wrong.
-- **Doctrine intact:** the headless €5-VPS base install ships **none** of these desktop extras and still boots on a fresh `python:3.11-slim` Linux container — every port is extras-gated and degrades to a logged no-op (AD-6) when its capability is absent. These labels say *which* extras now also work on Mac/Linux, never that any of them are required.
-
-## Windows specifics (do not skip)
-
-- **Unicode stdout:** cp1252 default. New CLI modules must call `sys.stdout.reconfigure(encoding='utf-8')` or stick to ASCII.
-- **Subprocess hygiene:** every `subprocess.*` / `asyncio.create_subprocess_exec` call must pass `creationflags=NO_WINDOW_CREATIONFLAGS` from `jarvis/core/process_utils.py`. Missing this triggers the BUG-012 flicker storm under `pythonw.exe`.
-- **Audio:** WASAPI via `sounddevice`. **WDM-KS host-API is forbidden** (`_FORBIDDEN_OUTPUT_HOSTAPIS` in `jarvis/audio/player.py`) — PortAudio's blocking write API crashes there (BUG-014). Pattern-match device names on shortest unique token (`"PRO X"`), not marketing name.
-- **Hotkeys:** `global-hotkeys`. Avoid `Alt+F4`, `Ctrl+C`, `Win+*`. Safe combos: `ctrl+right_alt+<letter>`.
-- **No Windows Service.** SYSTEM user has no headset/mic access. Jarvis is a tray app in the user session under `pythonw.exe`; autostart via shortcut in `shell:startup`.
-- **UAC manifest:** `asInvoker`. Elevate per-action, never globally.
+**"It works on my machine" is the *defect*, not the evidence.** The maintainer's RTX-5070-Ti / Windows box with Gemini + OpenRouter keys is <0.1 % of the install base. When in doubt, gate behind an extras group with a graceful no-op and lead the docs with the VPS path. Full doctrine: [`CLOUD.md`](CLOUD.md) + [`docs/PHILOSOPHY.md`](docs/PHILOSOPHY.md) (on conflict, the doctrine wins). See AP-21/22/23.
---
-## Brand mark / logo (BINDING)
+## 4. Naming — the agent/mission system is "Jarvis-Agents"
-**The official Jarvis logo is the Gigi GHOST mascot** — the black ghost character with glowing yellow eyes (`jarvis-gigi-256.png` == the maintainer's master `Jarvis-Logo (1).png` at the repo root, md5 `7de0a930`; also served to the frontend as `/jarvis-logo.png`). **The gold four-point star (`jarvis-mark-256.png` / `jarvis.ico` md5 `73bd5837`) is "AI-slop" the maintainer rejects — do NOT use it** as the brand mark anywhere (UI avatar, titlebar/taskbar icon, marketing, videos, intro/onboarding films). Titlebar/taskbar icon must be the ghost (`assets/icons/jarvis.ico`); sidebar avatar is `Sidebar.tsx <img src="/jarvis-logo.png">`. When a feature needs "the Jarvis logo", it is always the ghost mascot.
+The internal agent/mission/harness system is named **Jarvis-Agents** (singular **Jarvis-Agent**) everywhere a human or an LLM could read it — UI labels, docs, comments, new code identifiers, log/voice text. Do not introduce other names for it. (A repo-wide rename of older internal terms to this brand is in progress; write new surfaces as Jarvis-Agents.)
---
-## Screenshots & scratch captures
+## 5. Architecture essentials (respect on every change)
-**All development/verification screenshots go in `screenshots/` at the repo root** — never the repo root itself, never a random cwd. `jarvis/core/screenshots.py` defines `screenshots_dir()` plus a boot sweep (`sweep_screenshots`, wired into `SingleInstance._on_primary_claim`) that (a) consolidates any stray root-level image into `screenshots/` and (b) prunes captures older than **10 days** by mtime. App-runtime Vision frames are separate — they live in `data/flight_recorder/blobs/` and are pruned by `jarvis/telemetry/retention.py`. When an agent or tool saves a UI capture, target `screenshots/`; the folder is git-ignored and self-tidying.
+Full model + module catalog: [`docs/architecture-overview.md`](docs/architecture-overview.md). The rules you cannot break:
----
-
-## Commands
-
-```bash
-# Install
-pip install -e . --no-deps # makes entry_points active (BUG-006/014 recovery)
-pip install -r requirements.txt # full runtime deps
-pip install -e ".[dev]" # adds pytest, ruff, mypy, pyinstaller
-
-# Console scripts (from [project.scripts])
-jarvis # tray app or first-run wizard
-jarvis-ask # one-shot prompt CLI
-jarvis-review-gc # Phase 8.5 review-pipeline GC
-jarvis-review-eval # Phase 8.6 eval harness (--quick/--real/--bucket)
-
-# python -m jarvis (root CLI)
-python -m jarvis --version
-python -m jarvis --wizard # re-run setup wizard
-python -m jarvis --check # hardware analysis
-python -m jarvis --plugins # entry_points registry dump
-python -m jarvis --debug # console logging + config dump
-python -m jarvis --phase5-doctor # vision/admin/CU/HMAC/cost status
-python -m jarvis --install-admin-helper # generate HMAC secret in Credential Manager
-
-# Desktop-App launcher
-python -m jarvis.ui.web.launcher # FastAPI + pywebview + voice + Orb
-python -m jarvis.ui.web.launcher --headless # API+WS only, no window, Mock-Brain
-python -m jarvis.ui.web.launcher --dev # frontend from Vite dev server :5173
-python -m jarvis.ui.web.launcher --no-lock # disable single-instance lock (parallel dev)
-
-# run.bat (root, recommended)
-run.bat # pythonw + voice + Orb
-run.bat --debug # console visible, JARVIS_DEBUG=1
-run.bat --dev # Vite hot-reload
-run.bat --headless # API only, no voice
-# Pre-boot hook: invokes scripts\check-working-tree.ps1 automatically (BUG-014 guard).
-# Voice opt-out: set JARVIS_VOICE=0 before launch.
-
-# Lint/format
-ruff check jarvis/
-ruff format jarvis/
-mypy jarvis/
-
-# Frontend (jarvis/ui/web/frontend/)
-npm install
-npm run dev # http://localhost:5173
-npm run build # → jarvis/ui/web/dist
-npm run test # vitest
-
-# Mandatory worktree preflight (BUG-006/014/015 guard)
-pwsh scripts/preflight.ps1 # exit non-zero → fix before coding
-
-# Operational scripts
-powershell scripts/auto-push-eod.ps1 [-DryRun] # nightly tag+push safety net
-powershell scripts/install-auto-push-task.ps1 -Time "22:00" # register Task Scheduler job
-powershell scripts/drift-guard-daemon.ps1 # config drift defense (BUG-010)
-powershell scripts/install-config-drift-guard-task.ps1
-powershell scripts/check-working-tree.ps1 # working-tree drift recovery
-
-# Smoke / probe scripts
-python scripts/smoke_brain_e2e.py
-python scripts/smoke_phase6_p{1,2,2_jobkill,3,3_real}.py
-python scripts/voice_e2e_probe.py
-python scripts/voice_compare.py
-python scripts/awareness_smoke_a{1,2}.py
-```
+- **8-layer dependency rule:** higher layers reach lower ones **only via protocols** (`jarvis/core/protocols.py`); lateral communication **only** via typed `frozen=True` events on `EventBus` (`jarvis/core/bus.py`) carrying `trace_id` + `timestamp_ns`. A broken subscriber is logged in `_safe_dispatch`, never propagated (AP-18).
+- **Plugins are structural:** under `jarvis/plugins/<group>/<name>.py`, registered via `pyproject.toml` entry-points, and **must not import `jarvis.*`** in the plugin module. After editing entry-points: `pip install -e . --no-deps`. Groups: wakeword, stt, tts, brain, harness, tool, channel.
+- **Streaming first:** all Brain/STT/TTS/Harness methods return `AsyncIterator[...]` (non-streaming yields one element).
+- **Secrets** only via `jarvis.core.config.get_secret`: OS keyring → ENV → `.env` → local-file fallback. Never put keys in code / `jarvis.toml` / commits / `.claude/`. Voice/chat must never accept secrets (AP-2).
+- **Brain is multi-provider** — never hardcode Anthropic/Claude (AP-6); gate features on a **capability** (`supports_vision`, `supports_tools`, `can_call_tools()`), never a provider name/model id (AP-21). Persona comes from `jarvis/brain/persona_loader.py` (editable override → packaged `JARVIS_PERSONA.md`); never hardcode it.
+- **Router discipline (ADR-0011):** the router-tier brain is a pure dispatcher over the `ROUTER_TOOLS` frozenset (`jarvis/brain/factory.py`). No spawn tool ever enters a worker set (AP-5/AP-14). Extending `ROUTER_TOOLS` → amend ADR-0011 + `tests/unit/brain/test_routing.py`.
+- **Voice scrub:** brain→TTS goes through `scrub_for_voice` (`jarvis/brain/output_filter.py`) — **regex only, no LLM call** (AP-11). ADR-0010.
+- **Atomic config writes:** mutate `jarvis.toml` only via `jarvis/core/config_writer.py` (lock + tempfile + BOM-safe, AP-7). Self-mod pipeline (Allowlist→Pre-Validate→Backup→replace→sync reload-test→Rollback→Audit) is non-negotiable (AP-13/14).
+- **Multi-layer enum drift:** any value crossing Python ↔ SQL ↔ Pydantic ↔ TS ↔ UI uses the five-layer pattern (`docs/anti-drift-three-layer.md`) + a parity test, preemptively (BUG-008 recurred 4×).
+- **Worker isolation:** every mission worker runs in a fresh `git worktree` under `<repo_parent>/sub-agents-outputs/` with a kill-on-crash containment (Job Object on Windows; process-group reaper on POSIX). `MAX_CRITIC_LOOPS = 3` is fixed.
+- **Platform gotchas:** UTF-8 stdout (cp1252 default on Windows); every subprocess passes `NO_WINDOW_CREATIONFLAGS` (AP-1); WASAPI audio, WDM-KS forbidden (BUG-014); no Windows Service (SYSTEM has no mic); UAC `asInvoker`, elevate per-action.
---
-## Testing conventions
+## 6. Safety / risk tiers
-```bash
-# Buckets
-pytest tests/ # full suite (asyncio_mode=auto)
-pytest tests/contract/ -v # protocol contract tests (parametrised)
-pytest tests/unit/ -v # per-module
-pytest tests/integration/ -v # phase-level E2E
-pytest tests/e2e/ -v # self-mod + voice review
-pytest tests/missions/ -v # Phase 6
-pytest tests/voice_routing/ tests/voice_latency/ -v
-
-# Markers (from [tool.pytest.ini_options])
-pytest -m phase5 # Phase-5 integration
-pytest -m e2e # Phase-7 E2E
-pytest -m voice_latency # Phase-L latency
-pytest -m eval # golden-query eval
-pytest -m integration # real subprocesses / live external services (Codex OAuth, OpenClaw); self-skips when prereqs missing
-pytest -m "not slow" # fast subset
-pytest -m skip_ci # tests that need desktop/admin/click
-# NOTE: the registered markers are exactly: phase5, skip_ci, e2e, voice_latency,
-# eval, slow, integration (see [tool.pytest.ini_options]). The historical
-# `phase6` / `openclaw_live` markers are NOT registered and select 0 tests today —
-# run those buckets by path instead (`pytest tests/missions/`, `tests/integration/`).
-
-# Layer-targeted
-pytest -k test_tier1_speed # latency regression
-pytest tests/unit/brain/test_routing.py -v # 26-case router discipline
-pytest tests/unit/brain/test_output_filter.py # 40-case scrubber
-pytest tests/unit/awareness/ -v
-pytest tests/unit/memory/wiki/ -v
-pytest tests/unit/sessions/test_hangup_reason_parity.py # BUG-008 drift guard
-pytest tests/unit/plugins/tool/test_wiki_tools.py
-pytest tests/integration/test_openclaw_e2e.py
-pytest tests/integration/test_openclaw_lazy_bootstrap.py
-```
-
-**Conventions:** fakes (not `unittest.mock`) in `tests/fakes/`; audio fixtures under `tests/fixtures/audio/`; trace replays under `tests/fixtures/traces/`; new STT/Brain/Tool/Channel providers must pass the contract suite.
+Four tiers: `safe` / `monitor` / `ask` / `block`, priority **blacklist > whitelist > tool default** (`jarvis/safety/risk_tier.py`). Whitelist downgrades to `safe` — the anti-confirmation-fatigue contract. **Direct `Tool.execute()` is a bug; only `ToolExecutor.execute()` is authorized (AP-3).** Generated skills land as `state="draft"` and are never auto-activated (AP-15).
---
-## Critical anti-patterns (do not do this)
+## 7. Critical anti-patterns (do not do this)
| # | If you do this... | ...you get this bug |
|---|---|---|
@@ -417,7 +115,7 @@ pytest tests/integration/test_openclaw_lazy_bootstrap.py
| AP-2 | Accept API keys via voice/chat | STT log leak — credential exfiltration vector |
| AP-3 | Call `Tool.execute()` directly (bypassing `ToolExecutor`) | Risk-tier/whitelist/plausibility skipped |
| AP-4 | Add a new `hangup_reason`/mission-status string in one site only | BUG-008 recurrence: HTTP 500, empty UI |
-| AP-5 | Put `spawn-openclaw`/`dispatch-with-review`/`run-skill` in a worker tool set | D9 recursion: worker spawns supervisor, infinite loop |
+| AP-5 | Put the harness-spawn / `dispatch-with-review` / `run-skill` tool in a worker tool set | D9 recursion: worker spawns supervisor, infinite loop |
| AP-6 | Hardcode `Claude`/`Anthropic` API client | User has no Anthropic API account; breaks `cfg.brain.primary` |
| AP-7 | Write `jarvis.toml` without `_WRITE_LOCK` + tempfile + BOM handling | BUG-018: BOM-corrupted TOML, backend won't boot |
| AP-8 | Skip `scripts/preflight.ps1` in a new worktree | BUG-006/014: edits go to a worktree the live Python doesn't import from |
@@ -426,70 +124,96 @@ pytest tests/integration/test_openclaw_lazy_bootstrap.py
| AP-11 | Add an LLM call inside `scrub_for_voice` | TTS latency tank |
| AP-12 | Encode API keys in `jarvis.toml` or commit `.env` | Credential leak; bypasses `keyring` audit trail |
| AP-13 | Block on watchdog reload for atomic-write verification | Race: file half-applied, no sync rollback |
-| AP-14 | Re-add a Sub-Jarvis tier or `SUB_TOOLS` set | Welle 4 deleted it; resurrection breaks the OpenClaw-bridge contract |
+| AP-14 | Re-add a sub-tier or `SUB_TOOLS` set | Welle 4 deleted it; resurrection breaks the agent-harness bridge contract |
| AP-15 | Auto-activate generated skills (`state` ≠ `draft`) | Lateral-movement vector; skills run without review |
| AP-16 | Add `[phase6.*]`/`[memory.wiki.*]` keys without `ConfigDict(extra="allow")` | Pre-validate rejects → boot fails after self-mod |
| AP-17 | Run Jarvis as a Windows Service | SYSTEM has no mic/headset access |
| AP-18 | Propagate a subscriber exception from `EventBus._safe_dispatch` | One handler kills the pipeline |
-| AP-19 | Reuse a process-global progress counter in a stall/heartbeat watchdog without resetting it per unit of work | BUG-032: watchdog measures the idle gap *between* turns → spuriously aborts a fresh TTS answer before its first frame ("Jarvis listens forever") |
-| AP-20 | `continue` (instead of `break`) a WS receive loop on an error that isn't `WebSocketDisconnect` | Unclean client disconnects raise `RuntimeError("WebSocket is not connected")`, not `WebSocketDisconnect` → the loop re-reads a dead socket forever → ~9 MB/s log storm + app self-restart that kills in-flight missions. Catch `RuntimeError` and `break` (`server.py` `_handle_ws`, fixed 1793ceaf) |
-| AP-21 | Pin a feature to a provider **name** or a **model id** (`if provider == "grok"`, hardcoded `grok-4.3`, a provider-specific branch) instead of gating on a **capability** | The feature silently breaks for every other provider and for whatever provider the user selected — the multi-provider mandate (AP-6) generalized to *any* provider. Gate on `supports_vision` / `supports_tools` / `can_call_tools()`; if the flag is wrong or missing, fix/add the capability (e.g. grok's `supports_vision` was wrongly `False` → Computer-Use died "no vision"; the fix was the flag, not pinning CU to grok) |
+| AP-19 | Reuse a process-global progress counter in a stall/heartbeat watchdog without resetting it per unit of work | BUG-032: watchdog measures the idle gap *between* turns → spuriously aborts a fresh TTS answer before its first frame |
+| AP-20 | `continue` (instead of `break`) a WS receive loop on an error that isn't `WebSocketDisconnect` | Unclean disconnects raise `RuntimeError` → loop re-reads a dead socket forever → log storm + self-restart. Catch `RuntimeError` and `break` |
+| AP-21 | Pin a feature to a provider **name** or **model id** instead of gating on a **capability** | The feature silently breaks for every other provider and for whatever the user selected. Gate on `supports_vision` / `supports_tools` / `can_call_tools()`; if a flag is wrong/missing, fix/add the capability — don't pin the feature |
+| AP-22 | Configure a tier (router / ack / STT / TTS / worker / critic / fallback) whose primary AND fallback resolve to the SAME provider family, or build a fallback chain from hardcoded provider NAMES | Single-provider brick: one missing key / 429 / 402 / outage takes the whole tier down even when the user has a healthy DIFFERENT provider. Resolve every tier through one key-aware chain that skips the dead/keyless provider, crosses families, and degrades honestly only when NO family is reachable — recoverable in-app |
+| AP-23 | Build or TEST a feature only against the maintainer's own config / keys / provider / OS and claim it done | The whole API-Keys section silently bricked for every other downloader and on a headless VPS (credentials couldn't even be SAVED, ENV keys read as "not configured", channels/plugins/OAuth 500'd). "Works on my machine" is the defect — verify the three non-maintainer paths in §3 |
+| AP-24 | Call a shared native inference engine (ctranslate2 / faster-whisper, an ONNX / torch session) concurrently from two callers, OR "recover" a hung inference with only a timeout that re-polls the SAME wedged engine | `WhisperModel.transcribe` is NOT thread-safe: the wake poll loop + the VAD probe sharing one provider hung it forever; a hung `to_thread` can't be cancelled, so a timeout only BOUNDS, never RECOVERS. Fix: a non-blocking per-instance inference lock (2nd call → skip) + a `recover()` that rebuilds a FRESH model after N failures (BUG-036) |
---
-## Recurring bug classes (must internalize)
+## 8. Recurring bug classes (must internalize)
-Detail in [`docs/BUGS.md`](docs/BUGS.md). Seven classes recur — recognize the signal, apply the defense:
+Detail in [`docs/BUGS.md`](docs/BUGS.md). Recognize the signal, apply the defense:
-1. **Four-layer restore trap** (BUG-006 → -014 → -015): worktree + frontend build + RAM + **editable-install pin to a deleted clone**. Signal: fix "works in tests" but Jarvis behavior unchanged after restart. Defense: `pwsh scripts/preflight.ps1` + `python -c "import jarvis; print(jarvis.__file__)"`.
-2. **Multi-layer enum drift** (BUG-008, 4 episodes): empty UI list while DB has rows, HTTP 500, `literal_error` in Pydantic. Defense: `docs/anti-drift-three-layer.md` pattern + parity test.
-3. **Config drift** (BUG-010 triple-defense): parallel sessions rewriting `jarvis.toml`, silently rolling back provider switches. Defense: `scripts/drift-guard-daemon.ps1` (5-min cron) + ENV overrides + read-only TOML + BOM-safe writer (`UTF8Encoding($false)`).
-4. **Subprocess console flicker** (BUG-012): missing `NO_WINDOW_CREATIONFLAGS` on `pythonw.exe`. Defense: every new subprocess call imports from `jarvis.core.process_utils`.
-5. **Audio host-API blocking-write trap** (BUG-014): WDM-KS picked by auto-resolver, PortAudio blocking API crashes. Defense: `_FORBIDDEN_OUTPUT_HOSTAPIS` filter; shortest-unique-token device matching.
-6. **Watchdog stale cross-unit counter** (BUG-032): a stall/heartbeat watchdog reads a process-global progress counter (`last_write_ns`) that is never reset per unit, so it measures idle time *between* units and fires spuriously — e.g. the TTS playback watchdog aborted a fresh answer before its first frame ("Jarvis listens forever / never speaks") whenever the brain thought longer than the 5 s stall window. Signal: a "wedge" abort whose timestamps are impossible (fires earlier than the threshold; the resource responds *after* the abort). Defense: reset the counter at unit start (before any lock wait); re-arm the "not started yet" guard per unit, not at construction; guards in `tests/unit/audio/test_player_stall_recovery.py` + `tests/unit/speech/test_speak_playback_timeout.py`.
-7. **Loop on an unexpected teardown error** (AP-20, WS dead-socket): a receive/stream loop catches the *expected* clean-disconnect exception but `continue`s on any other error, so an unclean teardown that raises a *different* exception (here `RuntimeError` from FastAPI, not `WebSocketDisconnect`) spins forever — log storm + self-restart. Signal: runaway CPU/log growth + ErrorOccurred every turn after a client drops. Defense: on the socket loop, treat any read error as terminal — `break`, never `continue`.
+1. **Restore trap** (BUG-006/014/015): worktree + frontend build + RAM + editable-install pinned to a deleted clone. Signal: fix "works in tests" but behavior unchanged after restart. Defense: `pwsh scripts/preflight.ps1` + `python -c "import jarvis; print(jarvis.__file__)"`.
+2. **Multi-layer enum drift** (BUG-008): empty UI list while DB has rows, HTTP 500, Pydantic `literal_error`. Defense: five-layer pattern + parity test.
+3. **Config drift** (BUG-010): parallel sessions rewriting `jarvis.toml`, silently rolling back provider switches. Defense: `scripts/drift-guard-daemon.ps1` + ENV overrides + BOM-safe writer.
+4. **Subprocess console flicker** (BUG-012): missing `NO_WINDOW_CREATIONFLAGS`. Defense: import from `jarvis.core.process_utils`.
+5. **Audio host-API blocking-write trap** (BUG-014): WDM-KS auto-picked, PortAudio crashes. Defense: `_FORBIDDEN_OUTPUT_HOSTAPIS` + shortest-unique-token matching.
+6. **Watchdog stale cross-unit counter** (BUG-032): a stall watchdog reads a process-global counter never reset per unit → fires spuriously between units. Defense: reset the counter at unit start; re-arm the "not started" guard per unit.
+7. **Loop on an unexpected teardown error** (AP-20): a socket loop `continue`s on a non-`WebSocketDisconnect` error → spins on a dead socket. Defense: treat any read error as terminal — `break`.
+8. **Wedged un-cancellable native inference** (BUG-036): a shared ctranslate2/faster-whisper model called concurrently hangs unrecoverably; every later transcribe re-polls the dead engine forever. Defense: serialize with a non-blocking lock; self-heal by rebuilding a fresh model (AP-24).
---
-## Working tree is frequently SHARED (operational reality)
-
-This repo's working tree is routinely edited by **several parallel agent sessions at once** (the MEMORY.md history is full of "shared tree", "a parallel session swept my index", "broke HEAD"). Treat the index as contested:
-
-- **Never assume the staged diff is only yours.** Before committing, stage and commit **hunk-isolated** (`git add -p` / pathspec-scoped commits) so you don't sweep another session's in-flight work into your commit.
-- A large uncommitted diff (this snapshot opened with ~65 changed files across `jarvis/`, `tests/`, frontend, docs) is the **normal** state, not a signal that something is broken. Most belong to other sessions; touch only what your task owns.
-- If the index or HEAD looks corrupted by a concurrent write, the recovery pattern that has worked here is a **temp-index commit + `update-ref` CAS + safety branch** (see the custom-system-prompt and mission-rerun memory entries). Reach for `git-rescue` when it is repo-wide disorder.
-- App restart is **`POST /api/settings/restart-app`**, not `Stop-Process` (which returns Access Denied under the tray `pythonw.exe`). Most uncommitted fixes are loaded via the editable install but still need this restart to take effect.
+## 9. Operational reality & Git workflow
----
-
-## Memory + Wiki
+- **The working tree is frequently SHARED** — several parallel agent sessions edit it at once. Never assume the staged diff is only yours; commit **hunk-isolated** (`git add -p` / pathspec-scoped). A large uncommitted diff is the **normal** state. If the index/HEAD looks corrupted by a concurrent write, recover via temp-index commit + `update-ref` CAS + safety branch (reach for `git-rescue` on repo-wide disorder).
+- **App restart is `POST /api/settings/restart-app`**, not `Stop-Process` (Access Denied under the tray `pythonw.exe`). Editable-install fixes still need this restart to take effect.
+- **New worktree:** run `pwsh scripts/preflight.ps1` before writing code; exit non-zero → fix first (BUG-006/014).
+- **Memory:** check `MEMORY.md` (`~/.claude/projects/.../memory/`) before larger decisions — stable user preferences live there.
+- **Plan vs. code:** on conflict, the plan wins (`~/.claude/plans/also-er-muss-auch-lexical-pond.md`); code deviations get documented back in the plan.
-This project has an auto-memory at `~/.claude/projects/C--Users-Administrator-Desktop-Personal-Jarvis/memory/`. **Check `MEMORY.md` before larger decisions** — stable user preferences (multi-provider brain, hybrid privacy, bilingual, anti-confirmation-fatigue, no-Anthropic-API, frontier-quality-before-cost) live there.
+### Git workflow
-The Knowledge Wiki is the long-term memory tier (B0/B1/B5/B7/B8/B9 live). Three router-tier tools: `wiki-recall` (search), `wiki-page-read` (read by vault path), `wiki-ingest` (deterministic save-fact). Vault root configured in `[wiki_integration].vault_root`; default `wiki/obsidian-vault/`. Telemetry snapshot at `GET /api/wiki/telemetry`. Trigger contract in ADR-0014.
+*(The maintainer already pins these in their personal global config; they are restated here at the project level so every contributor and agent in this repo follows the same workflow.)*
-The legacy Curator-Merger is soft-disabled since 2026-05-17 (`[memory.legacy_curator] enabled = false`, gated in `jarvis/brain/factory.py`). The `data/workspace/` snapshot stays on disk and 35 reader sites (Whoami-Tool, ProfileView, OpenClaw-Workspace setup, etc.) keep rendering it — but no new writes land there. Searching the wrong path still returns frozen-in-time hits. Hart-Cut (migrate snapshot to `wiki/obsidian-vault/`, refactor readers, delete `jarvis/memory/curator/`) remains open and can be triggered by flipping `enabled = true` ↔ false during the rewrite.
+- **Auto-commit after each completed logical step**, without being asked. BUT because the working tree is shared (above), stage only **your own** changed files by explicit path or `git add -p`, hunk-isolated — **never** `git add -A` / `git add .` (that sweeps another session's in-flight, possibly unfinished or secret-bearing work into your commit, and is the main concurrency hazard here).
+- **Use meaningful Conventional-Commit messages** (`feat:`, `fix:`, `refactor:`, `docs:`, `chore:`).
+- **Never push to the remote automatically** — push only when the maintainer explicitly says so (and a public push still runs the privacy gate in §2).
+- **Never commit secrets, `.env` files, keys, tokens, or credentials.** If any appear untracked, STOP, flag them to the maintainer, and do not commit them.
+- **Never `git add -A` / `git add .`** without first scanning the staged set for secrets and for files that belong to another session.
---
-## Worktree activation checklist
+## 10. Run & test
+
+```bash
+# Install / activate entry-points (BUG-006/014 recovery) + full deps + dev tools
+pip install -e . --no-deps
+pip install -r requirements.txt
+pip install -e ".[dev]" # pytest, ruff, mypy
-Before writing any code in a new worktree: **`pwsh scripts/preflight.ps1`**. If it exits non-zero, fix the reported issue before proceeding. Reference: BUG-006, BUG-014.
+# Launch
+run.bat # tray app + voice + Orb (recommended)
+run.bat --headless # API/WS only, no voice
+python -m jarvis.ui.web.launcher --dev # frontend from Vite :5173
+python -m jarvis --wizard | --check | --plugins | --debug | --phase5-doctor
----
+# Lint / typecheck
+ruff check jarvis/ && ruff format jarvis/ && mypy jarvis/
-## Pointers (no need to inline)
+# Frontend (jarvis/ui/web/frontend/)
+npm install && npm run dev # build → npm run build ; tests → npm run test
+```
-- ADRs: `docs/adr/0001..0023` (0009/0010/0014 carry legacy duplicates — see `tests/unit/docs/test_adr_uniqueness.py`). **ADR-0001 (admin IPC named-pipe + HMAC) is superseded by ADR-0020** (cross-platform elevation: `AdminTransport` + `Elevator` seams; the HMAC/envelope/Pydantic-argv security core is reused unchanged; per-OS op vocabulary in `jarvis/admin/schema_unix.py`).
-- Phase docs: `docs/phase{0,1,1a,1c,2,4,5,6}-*.md`.
-- Architecture contracts: `docs/openclaw-bridge.md`, `docs/anti-drift-three-layer.md`.
-- Operational: `scripts/README-auto-push.md`, `scripts/preflight.ps1`, `scripts/drift-guard-daemon.ps1`.
-- Self-Mod: `docs/self_mod.md`.
-- Bug register: `docs/BUGS.md`.
-- Jarvis CLI (drive a running Jarvis from the terminal / an external coding agent / Jarvis itself): `docs/jarvis-cli.md` + generated `docs/jarvis-cli-reference.md`. Thin HTTP client over the REST API in `jarvis/cli_ctl/` (binaries `jarvis`/`jarvisctl`/`jctl`); the dynamic `jarvis api <tag> <op>` layer covers every mounted endpoint, curated `jarvis <group> <command>` groups add ergonomics. Registered in the CLI catalog as `jarvisctl` so Jarvis self-controls via `cli_jarvisctl` (dangerous/recursive verbs blocked). New REST routes must stay mounted — enforced by `scripts/ci/check_cli_coverage.py` (pre-push + the `jarvisctl` CI job). Skills: `.claude/skills/generate-cli-command` + `.claude/skills/drive-jarvis-cli`.
+```bash
+# Tests (asyncio_mode=auto; fakes in tests/fakes/, not unittest.mock)
+pytest tests/ # full suite
+pytest tests/unit/ -v # per-module
+pytest tests/integration/ -v # phase-level E2E (real subprocesses; self-skips when prereqs missing)
+pytest tests/missions/ -v # Phase 6
+pytest -m "not slow" # fast subset
+# Registered markers: phase5, skip_ci, e2e, voice_latency, eval, slow, integration.
+# Targeted guards: test_routing.py (router), test_output_filter.py (scrubber),
+# test_hangup_reason_parity.py (enum drift). New STT/Brain/Tool/Channel providers
+# must pass tests/contract/.
+```
---
-## Plan vs. code
+## 11. Pointers
-On conflict, the plan wins (`~/.claude/plans/also-er-muss-auch-lexical-pond.md`, `docs/openclaw-bridge.md`). Code deviations must be documented back in the plan, not silently accepted.
+- **Architecture + module catalog + product detail:** [`docs/architecture-overview.md`](docs/architecture-overview.md).
+- **Doctrine:** [`CLOUD.md`](CLOUD.md) (cross-platform charter), [`docs/PHILOSOPHY.md`](docs/PHILOSOPHY.md).
+- **Bug register:** [`docs/BUGS.md`](docs/BUGS.md). **Anti-drift:** [`docs/anti-drift-three-layer.md`](docs/anti-drift-three-layer.md). **Self-Mod:** [`docs/self_mod.md`](docs/self_mod.md).
+- **ADRs:** `docs/adr/0001..0023` (ADR-0001 superseded by ADR-0020). **Phase docs:** `docs/phase{0,1,1a,1c,2,4,5,6}-*.md`.
+- **Operational scripts:** `scripts/preflight.ps1`, `scripts/drift-guard-daemon.ps1`, `scripts/README-auto-push.md`.
+- **Jarvis control CLI** (drive a running Jarvis from the terminal / an agent / itself): `docs/jarvis-cli.md` + generated `docs/jarvis-cli-reference.md` (`jarvis/cli_ctl/`, binaries `jarvis`/`jarvisctl`/`jctl`). New REST routes must stay mounted — enforced by `scripts/ci/check_cli_coverage.py`.
diff --git a/CLAUDE.md b/CLAUDE.md
index 722611a0e9..1ca8d47d7c 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -1,415 +1,113 @@
# CLAUDE.md
-Guidance for OpenClaw (claude.ai/code) and any sub-agent working in this repository.
+Binding guidance for any coding agent working in this repository. This file is
+deliberately lean — it holds the rules you must respect on **every** change.
+Product/architecture reference detail lives in
+[`docs/architecture-overview.md`](docs/architecture-overview.md).
---
-## ⚠️ THE GitHub repository — ONE public repo + mandatory privacy gate (BINDING, updated 2026-06-19)
+## 0. CLAUDE.md ≡ AGENTS.md (mirror rule — BINDING)
-**There is ONE project repo: the public flagship `https://github.com/PersonalJarvis/PersonalJarvis`** (PascalCase). EVERY maintainer "commit / push / save to GitHub / sichere den Stand" targets THIS repo and no other. <!-- i18n-allow: quoted German maintainer trigger phrase --> The lowercase `personal-jarvis` (git remote `origin`) is kept ONLY as a **silent local backup / safety net** — it is not "the project" and is never the deliverable. Never ask "which repo"; it is always the public flagship.
-
-### Nothing reaches the public repo raw — the fail-closed privacy gate (MANDATORY on EVERY push)
-
-The public repo only ever receives a **depersonalized snapshot**, never the raw working tree. Every push runs the full gate, in order, fail-closed (any uncertainty STOPS the push):
-
-1. **Tracked-files-only export** — `.gitignore` exclusions enforced for free: no `data/`, `.env`, `jarvis.toml`, Vault, keys.
-2. **Distribution denylist** — internal dev docs, scratch scripts, signing keys removed.
-3. **Deterministic PII scrub** — real name, personal paths, project ids masked.
-4. **🔍 Mandatory sub-agent privacy review (the maintainer's hard requirement, 2026-06-19)** — before any push, a dedicated sub-agent reads the ENTIRE staged snapshot and reports anything personal or sensitive the deterministic scanners might miss: API keys / tokens / secrets, credentials, personal data, private paths / emails, internal-only content. It may only ADD blocking findings; it can never clear what the deterministic gate blocks. A non-empty finding STOPS the push.
-5. **Deterministic secret/PII scan** — fail-closed, real-credential-length regexes.
-6. **Human review** — explicit maintainer go before any network write.
-
-This whole gate is the `ship-public-release` skill; the public push runs from a separate clean clone, so the working tree is never touched and raw state cannot leak.
-
-### Two volumes on the SAME gate
-
-- **Discreet (DEFAULT)** — "Push nach GitHub", "push", "commit and push", "sichere den Stand", "update GitHub". → Clean snapshot through the full gate above, committed to the public repo, with **no SemVer bump, no git tag, no GitHub Release, no announcement**. Just the current clean state, quietly updated. <!-- i18n-allow: quoted German maintainer trigger phrases -->
-- **Release (explicit only)** — "Neue Version shippen", "Mach ein Release", "Publish release", "veröffentliche eine neue Version". → the same gate **plus** a MAJOR/MINOR/PATCH bump + git tag + CHANGELOG entry. <!-- i18n-allow: quoted German maintainer trigger phrases -->
-
-When the volume is ambiguous, default to **discreet** (snapshot, no version bump).
-
-### Guardrails that stay in force
-
-- **Never `git push` raw working state to `PersonalJarvis/PersonalJarvis`.** The pre-push guard (`scripts/ci/guard_no_raw_public_push.py` + `scripts/ci/privacy_pre_push.py`, wired into `.githooks/pre-push`, `core.hooksPath=.githooks`) HARD-BLOCKS a raw push to the public repo. It protects you precisely *because* the legitimate snapshot pushes from a separate clone — the guard only ever catches an *accidental* raw push. Do not remove it.
-- The silent `origin` backup may receive raw dev commits as infrastructure, but that is never what "get my work onto GitHub" means — the deliverable is always the clean public snapshot.
-- **Skill routing:** any maintainer "push / commit / save to GitHub" in this repo is the `ship-public-release` skill (discreet mode by default). `save-to-github` and `github-version` share those trigger phrases but MUST NOT run here — they would push raw state to `origin` / cut a tag, bypassing the privacy gate. They are out of scope for this repo.
-
-Full mechanism: the `ship-public-release` skill (`.claude/skills/ship-public-release/SKILL.md`). Repo doctrine + history: [`CLOUD.md`](CLOUD.md) § "Canonical repositories".
-
----
-
-## Output Language Policy (HIGHEST PRIORITY)
-
-**Every artifact an agent produces in this repo is English.** No exceptions.
-
-This covers code, comments, docstrings, log/exception messages, Markdown (READMEs, ADRs, plans, `BUGS.md` entries, handoffs), `SKILL.md` files, commit messages, PR titles/bodies, test names + docstrings, CLI help text, FastAPI route descriptions, error responses, JSON schema `description` fields, audit-log entries, telemetry event names, and any new UI strings (i18n key + English source — never German source).
-
-This rule overrides historical "Sprache: Deutsch" sections in this file and any memory entry asking for German artifacts. If unsure: **default to English**.
-
-**What stays German:** the user-facing chat reply written by the assistant in conversation (per global `~/.claude/CLAUDE.md`), TTS output (bilingual DE+EN auto-detect at runtime), and already-committed German content (do not retro-translate unless asked).
-
-**Enforced in CI (not just documented):** the `language-policy` job in `.github/workflows/ci.yml` blocks any *newly added* German line from merging to `main` (diff-based, so the in-flight DE→EN backlog stays green). It is a required status check. Intentionally-German exceptions: an inline `i18n-allow` marker on the line, or a glob in `scripts/ci/german-allowlist.txt`. See `docs/superpowers/specs/2026-05-30-ci-language-policy-gate-design.md`.
+`CLAUDE.md` and `AGENTS.md` are **byte-identical twins**. `AGENTS.md` is the
+cross-tool standard name other agents read; `CLAUDE.md` is the canonical source.
+**Every edit to this file is mirrored into `AGENTS.md` automatically — you do not
+need to be asked, and you must never let them drift.** The sync engine is
+`scripts/ci/sync_agents_md.py` (live `PostToolUse` hook + `.githooks/pre-commit
+--stage` + a `--check` CI gate). After editing either file, run the sync (or just
+copy one onto the other) so the tree stays in sync before you commit.
---
-## Runtime Output Language (voice + chat) — BINDING
+## 1. Language — an international, English-first project
-This is the **runtime** language contract for what Jarvis *speaks and writes back to the user*. It is the sibling of the Output Language Policy above and does **not** weaken it: source artifacts stay English; the live spoken/written reply is multilingual product surface. (Forensic that motivated this section: 2026-06-18 — a German utterance was mis-transcribed by STT as English text, and because the language decision was re-derived per layer with no authoritative pin, the *entire* chain — ack preamble, answer, status line, TTS voice — went English. See `docs/BUGS.md`.)
+**Personal Jarvis is an international open-source project. Its working language is English — not German, not any other single human language.** Assume contributors and downloaders worldwide; never bias the codebase, docs, or defaults toward one locale. Every artifact an agent produces in this repo is English, full stop.
-**The rule (every supported language equally — de, en, es, and any future locale; never a German- or English-only bias):**
+- **Artifacts = English, always.** This covers code, comments, docstrings, log/exception messages, Markdown (READMEs, ADRs, plans, `BUGS.md` entries, handoffs), `SKILL.md` files, commit messages, PR titles/bodies, test names + docstrings, CLI help text, FastAPI route descriptions, error responses, JSON-schema `description` fields, audit-log entries, telemetry event names, and any new UI strings (i18n key + English source — never a non-English source). If unsure, default to English. This overrides any historical "Sprache: Deutsch" note. Enforced by the diff-based `language-policy` CI job (escape hatch: an inline `i18n-allow` marker or a glob in `scripts/ci/german-allowlist.txt`).
+- **The chat / conversation language is each contributor's own choice, NOT something this repo dictates.** How an agent talks to *you* in chat is set in your personal global config (`~/.claude/CLAUDE.md` / `AGENTS.md`) — a German maintainer, a Spanish contributor, and an English one each set their own. This project neither requires nor assumes any particular chat language; it only fixes the artifacts as English.
+- **Exempt from the English rule:** already-committed non-English content (don't retro-translate), and the runtime TTS/voice product surface (below), which is multilingual by design.
-1. **A turn's output language is decided exactly once, by one authoritative resolver, and every output layer consumes that one decision.** The resolver is `jarvis/core/turn_language.py::resolve_output_language(reply_language, stt_language, text, *, default, conversation_language)`. Precedence, highest first:
- - an explicit **`brain.reply_language` pin** (`de`/`en`/`es`) — the user-selected language wins over everything, regardless of what STT heard;
- - else **conversation stickiness**: a *thin* turn (a one- or two-word interjection like "Now"/"Stop"/"jetzt", or a lone loanword — `is_substantive_turn`) is spoken in the running `conversation_language` and must NOT flip it; only a *substantive* turn switches the language. The `BrainManager` owns `conversation_language` (updated only on substantive turns), exposes it to the speech pipeline, and threads it — via `ExecutionContext.config["output_language"]` stamped by the tool-use loop — to deterministic tool readbacks (e.g. `computer_use` "On it"/"Done"). Forensic 2026-06-18: a lone English "Now" in a German voice chat flipped the whole turn (CU ack + status + readback) to English;
- - else the **detected input language** of the turn (text heuristic first, STT tag breaks ties — `resolve_turn_language`);
- - else the **configured default locale** (`turn_language.DEFAULT_LOCALE`) — never a per-layer hardcoded constant.
-2. **The rule applies to ALL user-facing output, with no exception for "intermediate" surfaces:** the deep-brain reply, the ack-brain preamble, spawn announcements, every canned status / error / clarify / timeout / provider-down / STT-unavailable phrase, every deterministic Computer-Use / local-action readback, **and** the TTS voice / BCP-47 selection. A status or error line like "Something went wrong" must come out in the same language as the answer would have. An unprompted mid-session language switch between layers is a bug.
-3. **No layer may re-derive the language on its own terms.** Specifically forbidden: a binary `"de" if _looks_german(...) else "en"` shortcut (it silently drops `es`); a phrase table keyed `de`/`en` only (an `es` speaker then hears the wrong language); a per-layer hardcoded default (`"en"` in one place, `"de"` in another → layers diverge); any spoken/written path that ignores the `brain.reply_language` pin. When you add a new spoken/written phrase table, it carries **all** supported languages, and you resolve its key through the one resolver.
-4. **Honesty over guessing.** When a layer genuinely cannot determine the language, it falls back to `DEFAULT_LOCALE` — it does not invent a different default. Pure-auto mode cannot fully defend against a confident STT mis-transcription (German speech → clean English text); the durable guarantee for a single-language user is to **set `brain.reply_language`**, which pins every layer.
+### Runtime output language (voice + chat) — BINDING
-`brain.reply_language` is the single user-facing control (`auto` | `de` | `en` | `es`), editable from the desktop **Languages** view (`PUT /api/settings/reply-language`, hot-reloads, no restart). `auto` mirrors the spoken/written input language; a pin forces the selected language across the whole chain. Regression guards live in `tests/unit/core/test_turn_language.py`, `tests/unit/speech/test_phrase_language.py`, and the `tests/unit/brain/test_*language*.py` set — extend them whenever you touch a spoken path.
+This governs what Jarvis **speaks/writes back to the user** (a multilingual product surface — it does NOT weaken the English-artifact rule). Supported languages are equal — `de`, `en`, `es`, and any future locale; never a German- or English-only bias.
-**Coverage today (2026-06-18) and the one known gap.** The deep-brain reply, the speech-pipeline output-language resolution + every canned status / error / clarify / timeout / brain-unavailable / STT-unavailable phrase, the deterministic Computer-Use / local-action readbacks, the leak-recovery + evidence-unfulfilled + provider-down honesty phrases, and the TTS voice pin all resolve through `resolve_output_language` and cover **de / en / es**. The one layer still **de / en only** is the Ack-Brain pre-thinking *preamble persona* (`jarvis/brain/ack_brain/persona_prompt.py`) and the *spawn-announcement composer* (`spawn_announcement.py`): an `es` turn there falls back (preamble → German persona; spawn → English/pool). These two are **not** a free edit — `PERSONA_PROMPT_DE/EN` are constants locked to the flash-brain spec (`docs/superpowers/specs/2026-05-11-pre-thinking-ack-flash-brain-design.md`), so adding a Spanish preamble persona requires amending that spec first. Bringing the Ack-Brain surfaces to `es` is the tracked follow-up to fully satisfy this doctrine; until then, an `es`-pinned user still gets the correct language everywhere except the optional sub-second preamble.
+1. **A turn's output language is decided exactly once, by one resolver — `jarvis/core/turn_language.py::resolve_output_language` — and every output layer consumes that one decision.** Precedence: explicit `brain.reply_language` pin → conversation stickiness (a thin one/two-word interjection is spoken in the running `conversation_language` and must NOT flip it; only a substantive turn switches) → detected input language → configured `DEFAULT_LOCALE`.
+2. **It applies to ALL user-facing output** — deep reply, ack preamble, spawn announcements, every canned status/error/clarify/timeout/provider-down phrase, every deterministic Computer-Use/local-action readback, AND the TTS voice/BCP-47 pick. A mid-session language flip between layers is a bug.
+3. **No layer may re-derive the language on its own** — no `"de" if _looks_german() else "en"` shortcut (drops `es`), no `de`/`en`-only phrase table, no per-layer hardcoded default, no path that ignores the pin. New phrase tables carry **all** supported languages and resolve their key through the one resolver.
+4. **Honesty over guessing** — a layer that genuinely cannot tell falls back to `DEFAULT_LOCALE`. The durable guarantee for a single-language user is to set `brain.reply_language` (`auto` | `de` | `en` | `es`), editable from the desktop **Languages** view. Regression guards: `tests/unit/core/test_turn_language.py`, `tests/unit/speech/test_phrase_language.py`, `tests/unit/brain/test_*language*.py`.
---
-## Cloud-First Philosophy (BINDING — overrides historical "Windows 11" framing)
-
-**Target runtime is any €5 / month VPS or low-spec laptop** with a modern browser. *Not* the maintainer's RTX 5070 Ti / Windows 11 workstation. Every architectural decision, default value, doc paragraph, dependency, and PR from 2026-05-18 forward is evaluated against the VPS user — the maintainer's machine represents fewer than 0.1 % of the install base this project is being designed for.
-
-**Top-level charter:** [`CLOUD.md`](CLOUD.md) (Rule #1 = cross-platform). **Full doctrine:** [`docs/PHILOSOPHY.md`](docs/PHILOSOPHY.md). On conflict between this file and `PHILOSOPHY.md`, the doctrine wins. On conflict between the doctrine and the binding plan, the doctrine wins on hardware assumptions, the plan wins on architectural decisions.
-
-The short version:
-
-- **RULE #1 — everything we build must run on Linux, macOS, AND Windows (plus headless Linux server).** No platform is second-class; a feature that only works on one OS is *incomplete*, not "done with a known limitation". The base `pip install` + boot must succeed on a fresh `python:3.11-slim` Linux container, on macOS, and on Windows. OS-specific code is allowed only behind (a) a runtime capability check, (b) an extras group, and (c) a graceful English-message no-op on the other platforms. Use `pathlib`, capability probes, and UTF-8 by default — never hardcode `C:\Users\...` or assume cp1252. See [`CLOUD.md`](CLOUD.md).
-- **All five provider classes (Brain, STT, TTS, Vision, Wake) must have a fully cloud-reachable default path** — no required local GPU, no required local model, no required Windows API, no required microphone, no required speaker.
-- **No new hard dependency on Windows-specific or GPU-specific packages.** New imports of `pywin32`, `pywinauto`, `pyautogui`, `sounddevice`, `faster-whisper`, `onnxruntime-gpu`, `openwakeword`, `global-hotkeys`, `mss`, `pywebview` go into a `[desktop]` extras group, *not* the base install.
-- **The maintainer's setup is a power-user profile, not a baseline.** Tray app, Orb overlay, global-hotkey wake, local Whisper, Silero-VAD-in-process, drift-guard PowerShell daemon, Computer-Use harness — **all opt-in extras**, all degrade gracefully (with a clear English-language message) when the extras are not installed.
-- **Headless VPS + browser UI is a first-class runtime.** A user opening the FastAPI / WebSocket frontend in any browser, using the browser's microphone and speakers (or a channel adapter — Telegram, Discord, SMS, webhook), must reach the full Router-Brain → Worker-Critic → Mission-Manager experience without installing a Windows binary, a CUDA toolkit, or a native audio driver.
-- **Documentation, defaults, install instructions, and onboarding lead with the VPS path.** Windows-desktop instructions are a footnote inside an "Optional power-user extras" section. Re-order the doc when in doubt.
-
-**Pre-existing code that violates this doctrine is grandfathered until touched.** A code path that already hardcodes a local-hardware assumption does not need to be rewritten in a panic — but any *touch* of that path is an opportunity to migrate it toward the cloud-first default, not extend the violation.
-
-**Maintainer dev tooling (`scripts/preflight.ps1`, `run.bat`, `scripts/drift-guard-daemon.ps1`, `scripts/check-working-tree.ps1`, `scripts/auto-push-eod.ps1`) may stay Windows-PowerShell-only.** That is the maintainer's *developer* environment, not the consumer's *runtime*. The line is drawn at the boundary between `scripts/` (developer tools — fair game to stay Windows-only) and the importable `jarvis/` package (runtime — must run on a Linux VPS).
-
-**Decision lens for any PR:** *Would this PR work, end-to-end, for a user on a fresh `python:3.11-slim` Linux container with 1 vCPU, 1 GB RAM, no GPU, no audio hardware, no Windows APIs, and only a network connection?* If yes → merge. If no → either (a) the local-only portion is correctly gated behind an extras group with a graceful no-op fallback in the base install, or (b) split the PR.
-
----
-
-## Project
-
-**Personal Jarvis** — voice-driven meta-orchestrator for Windows 11. Not a classical voice assistant: the core pattern is **Supervisor-Agent** that dispatches work to interchangeable harnesses (OpenClaw subprocess, Codex CLI, Open Interpreter, MCP servers). The voice layer is just the interface.
-
-**Master plan:** `~/.claude/plans/also-er-muss-auch-lexical-pond.md` — binding for all design decisions. On conflict between plan and code, the plan wins; code deviations must be documented back in the plan.
-
-**Binding architecture contracts:**
-- [`docs/openclaw-bridge.md`](docs/openclaw-bridge.md) — OpenClaw harness contract (AD-1..AD-21, AP-OC1..AP-OC14). Welle 1 (spike) + Welle 4 (sub-jarvis deletion) are done; Welle 2 (live bridge in default voice path) + Welle 3 (full live mode) remain.
-- [`docs/anti-drift-three-layer.md`](docs/anti-drift-three-layer.md) — five-layer enum pattern (Python ↔ SQL ↔ Pydantic ↔ TS ↔ UI). Mandatory for any string crossing module boundaries.
-
-**Bug register:** [`docs/BUGS.md`](docs/BUGS.md). Read before larger edits — the recurring bug classes (restore-trap, multi-layer enum drift, config drift, subprocess flicker, audio host-API) are catalogued there.
-
----
-
-## Phase Status
-
-| Phase | Live? | Pointers |
-|---|---|---|
-| **0–4 — Foundations** | ✅ | Plugin system + protocols, FastAPI/React desktop app, speech pipeline, skill system, tool-use loop, risk-tier executor, core memory, harness dispatch. Detail in `docs/phase{0,1,1a,1c,2,4}-*.md`. |
-| **5 — Vision/Action/Admin/Async/Control + Tiered Routing** | ✅ | `jarvis/{vision,admin,tasks,control,telemetry}/`. Computer-Use enabled. Tiered routing via `ROUTER_TOOLS` frozenset. ADR-0001..0011. |
-| **6 — Self-Healing Worker-Critic** | ✅ | `jarvis/missions/` (event store, manager, recovery, state machine, budget, cleanup, workers, critic, kontrollierer, safety, voice, isolation). ADR-0009, `docs/phase6-*.md`. Wired into REST + voice path via `bootstrap_missions`. **Live progress (2026-06-15):** both the Codex worker and `ClaudeDirectWorker` stream stdout line-by-line; the orchestrator drain loop emits throttled `WorkerProgress` (`jarvis/missions/events.py`) → WS → `ReasoningPanel` (the chain was dormant before). **Re-run (2026-06-15):** `POST /api/missions/{id}/rerun` re-dispatches a terminal mission's stored prompt as a NEW mission linked via `parent_mission_id` ("Continue" cancelled / "Restart" failed) — the source card is untouched audit; **no state-machine or idempotency change** (deliberate, avoids AP-14). |
-| **7 — Self-Mod (foundation + writer + tools)** | ✅ | `jarvis/core/self_mod/` (audit, errors, pending, registry, schema, writer). Three router-tier tools: `list_mutable_settings`, `get_config_value`, `set_config_value`. ADR + writeup in `docs/self_mod.md`. **7.5 `spawn-skill-author` IS now registered** (`pyproject.toml` → `jarvis.brain.tools.skill_authoring:SpawnSkillAuthorTool`, router-tier, `ask`; spawns the `SkillAuthoringRunner`). Generated skills land as `state="draft"` and are never auto-activated (AP-15). |
-| **Awareness A0–A5** | ✅ | `jarvis/awareness/` (state, story, salience, verdichter, working_set, episode, recall_store, watchers, probes). Router-tier tools `awareness-snapshot` (A1) + `awareness-recall` (A3). ADR-0009/0010/0012. Hard rule: **never on the voice critical path**. |
-| **Wiki B0/B1/B2/B3/B5/B7/B8/B9** | ✅ | `jarvis/memory/wiki/` (curator, atomic_writer, page_repository, integration, session_rollup, voice_bridge, telemetry, scheduler). Three router-tier tools: `wiki-recall`, `wiki-page-read`, `wiki-ingest`. ADR-0013/0014/0015. B2 = `docs/obsidian-setup.md` + B9-Wizard. B3 = `WikiView.tsx` + 6-endpoint `wiki_routes.py` + `wiki_ws.py` live-reload. **B4 soft-disabled** 2026-05-17 via `[memory.legacy_curator] enabled = false` — legacy Curator package + `data/workspace/` snapshot stay on disk; Hart-Cut (vault migration + reader refactor + package delete) remains open. **B6 not started**. |
-| **OpenClaw bridge** | ⚙ Welle 1+4 done | `jarvis/plugins/harness/openclaw.py`, `jarvis/missions/openclaw/`. `[harness.openclaw].enabled=true`. Welle 2 (live bridge as default) + Welle 3 (live-mode wrap) open. |
-| **Ack-Brain (pre-thinking)** | ✅ | `jarvis/brain/ack_brain/` — sub-second butler ACK before the deep brain replies. Gemini 3.1 Flash Lite primary, Grok fallback. UI preamble bubble. Suppress-if-fast gate at 2000ms (`[ack_brain].suppress_if_brain_faster_than_ms`). ADR-0014 (flash-brain). |
-| **CLI catalog + terminal view** | ✅ | `jarvis/clis/` (catalog, installer, loader, prober, registry, risk_integration, usage_log) + `jarvis/terminal/` (cross-platform PTY via `terminal.backend.make_pty_backend` — ConPTY/`pywinpty` on Windows, `ptyprocess` on POSIX). Router tool `cli-tools` (virtual loader → one `cli_<name>` tool per connected CLI). UI views: `ClisView`, `TerminalView`. **`spawn-cli-worker` was REMOVED 2026-05-24** (dead entry point; heavy multi-step CLI work goes through `spawn-worker`, single-step through the `cli_<name>` tools — never re-add a CLI spawn tool, it is a D9 recursion vector, AP-5/AP-14). |
-| **Board / Profile ("Knows-you" dashboard)** | ✅ | `jarvis/board/` (aggregator, store, achievements, evaluator, bio prompts, scheduler, `schema.sql`) → `data/board/personal.db`. Parses FlightRecorder JSONL into daily stats / personal records / 10 achievements + an anti-cliché AI-bio. Routes `board_routes.py` (`/api/board/*`) + `profile_routes.py`; views `BoardView.tsx`, `ProfileView.tsx`, `frontend/src/views/profile/`. Deterministic profile writes via the `update-profile` tool. Separate standalone service stub in `board-backend/` (FastAPI + Docker). CHANGELOG `v1.0.0-board`. |
-| **Channels (Web / Telegram / Discord)** | ✅ | `jarvis/channels/` (`base.py` ChannelAdapter, `manager.py`, `bootstrap.py` `bootstrap_channels`, `chat_bridge.py`, `web.py`/`telegram.py`/`discord.py`). Bridges a DM/guild message into the normal Jarvis chat path. Entry points `web` (base), `telegram` (base dep `python-telegram-bot`), `discord` (optional `[channels]` extra, lazy-imported, graceful `ChannelStartError` when absent). Tokens via Credential Manager. |
-| **Friends + Socials** | ✅ | `jarvis/friends/` (`registry.py` `FriendRegistry` on `aiosqlite`, `status_publisher.py`, `status_filter.py`, `messages.py`, `schemas.py`). Routes `friends_routes.py` + `socials_routes.py`; views `FriendsView.tsx`, `frontend/src/views/friends/` + `socials/`. Telegram channel is the live transport (F-FRIENDS F0/F1). |
-| **Contacts + Telephony** | ✅ | `jarvis/contacts/` (`store.py`, `schema.py`, `notify.py`) — contacts mirror to guaranteed Wiki person pages `people/<slug>.md` on `ContactChanged` (PII stays out of the page). Tools `contact-lookup` (safe), `contact-upsert` (monitor, write), `call-contact` (ask, echo-confirm). `jarvis/telephony/` (`outbound.py`, `twiml.py`, `provisioning.py`, `security.py`, `session.py`) places real outbound calls via Twilio. **Twilio is the optional `[telephony]` extra** — routes (`telephony_routes.py`) + `TelephonyManager` degrade gracefully when absent (AD-T8). Views `TelephonyView.tsx`, `frontend/src/views/contacts/`. |
-| **Marketplace plugins** | ✅ | `jarvis/marketplace/` (catalog + `auth/` OAuth + `oauth_callback_server.py` + `plugin_loader.py`/`plugin_registry.py`/`plugin_relevance.py` + `mcp_bridge.py`). The `plugin-tools` entry-point loader expands connected marketplace plugins into live brain tools. Native REST tools where a catalog transport was insufficient: `gmail` (`gmail_rest`, ask — send is consequential) + `vercel` (`vercel_rest`, monitor — read-only). Router-tier, never a spawn (AP-5/AP-14). Route `marketplace_routes.py`; views `PluginsView.tsx`, `ExtensionsView.tsx`. |
-| **Workflows** | ✅ | `jarvis/workflows/` (`runner.py`, `scheduler.py`, `store.py`, `schema.sql`, `seed.py`). Imperative cron/manual-triggered multi-step pipelines (brain-prompt / harness-dispatch / shell / tool-call / speak steps) — distinct from Phase-6 *missions* (single persistent self-healing action). Route `workflows_routes.py` (CRUD); `bootstrap_workflows` on `app.state`. View `WorkflowsView.tsx`. |
-| **Conductor** | ✅ | **Separate root package `conductor/`** (`api/`, `core/`, `jobs/`, `seed/`, `cli.py`) with its own SQLite store — a YAML-first agentic-workflow canvas (shell/http/agent jobs, cron/webhook/manual triggers, timeline view). Jarvis mounts the Conductor router inside its own FastAPI server → `ConductorView.tsx`. Do not confuse with **Workflows** (imperative, in-`jarvis/`) — Conductor is YAML-first and standalone-capable. |
-| **Sub-Agents / Outputs** | ✅ | `jarvis/agents/registry.py` builds an in-RAM sub-agent event tree from the EventBus (OpenClaw/Brain/Tool signals; TTL-cached, no DB) → `sub_agents_routes.py` (`/api/sub-agents/tree`) + `SubAgentsView.tsx`. **Outputs** (`outputs_routes.py` + `OutputsView.tsx`) list a mission's *deliverables* from the filesystem (`<repo_parent>/sub-agents-outputs/<slug>/`, NOT a DB). An "artifact" is a `.md`/PDF/HTML/code file a worker produced. Per-artifact download (`Content-Disposition` attachment) / view (server-rendered markdown→HTML under a strict `default-src 'none'` CSP) / desktop-only reveal+open-with-default-app via `jarvis/platform/open_path.py`; native actions are off on headless/VPS (`native_file_actions` launcher flag). |
-| **Frontier (model auto-switch)** | ✅ | `jarvis/brain/frontier_{resolver,autoswitch}.py` query each provider's `/v1/models` at boot, detect newer models, and propose switching `BrainProviderConfig`; the user acknowledges via a modal → `POST /api/frontier/ack`. Route `frontier_routes.py` (`/api/frontier/{pending,ack}`); cache `data/frontier_cache.json` (24h TTL). Aligns with the "frontier-quality-before-cost" user preference. |
-| **Preview / Pointer / Federation** | ✅ | `jarvis/preview/registry.py` + `preview_routes.py` — registry of dev-server iframes (Vite `:5173`, Storybook) surfaced in the sidebar; paired with the `start-preview-server` / `verify-localhost` self-verification tools. `jarvis/pointer/` (`intent.py`, `context.py`, `turn.py`) — "AI Pointer": resolves the UI element under the mouse cursor via the OS accessibility tree (not a screenshot), attached only on deictic intent ("what's that", "click there"); router tool `inspect-pointer`. `federation_proxy_routes.py` — local signing proxy to the Board-federation backend (frontend has no privkey; signs with the Credential-Manager key; path-whitelist anti-traversal). |
-
-Infra-only (no UI, consumed internally): `jarvis/hardware/detection.py` (CPU/GPU/VRAM/CUDA probe + Whisper-model sizing for the wizard / `--check`); `jarvis/orchestrator/` (currently a thin L6 seam — most supervisor logic lives in `jarvis/missions/`); `jarvis/diagnostics/`.
-
-Still unrowed (verify with `ls jarvis/ui/web/*routes*.py` + `git log`): `chats`/`sessions`. Treat the absence of a row as "undocumented, not absent" — the filesystem + `git log -- <module>` is the source of truth.
-
-Status drift moves fast. Verify with `git log -- <module>` rather than trusting this table. *(Table cross-checked against the working tree on 2026-06-16; the rows above were added that day after confirming each module's files + route + view exist.)*
-
----
-
-## Architecture (the parts an agent must respect)
-
-### 8-Layer model
-
-```
-L7 UI/UX Tray, Toasts, Admin-API, Desktop-App (FastAPI+React+pywebview), Orb-Overlay
-L6 Orchestrator State-Machine, Router, BrainManager, Supervisor, Mission-Manager
-L5 Harness-Adapter OpenClaw, Codex, Open Interpreter, Python-Script, MCP-Remote
-L4 Brain 5 providers (Claude-API, OpenRouter, OpenAI, Gemini, Grok) + Ack-Brain sub-second tier
-L3 Intent/Risk Classifier, Risk-Tier-Policy, Approval, Rate-Limit-Tracker
-L2 Speech Wake → VAD (Silero) → STT (faster-whisper / Google) → TTS (Gemini Flash / Grok-Voice / SAPI5)
-L1 Audio I/O WASAPI via sounddevice, Device-Routing, Chime-Feedback
-L0 OS/Hardware Win32, CUDA, Mic/Speakers, global-hotkeys
-```
-
-**Dependency rule (strict):** higher layers reach lower layers **only via protocols** (`jarvis/core/protocols.py`). Lateral communication is **only** via typed events on `EventBus` (`jarvis/core/bus.py`) with `frozen=True` dataclasses carrying `trace_id` + `timestamp_ns`. Subscriber exceptions are swallowed in `_safe_dispatch` — they must never propagate.
-
-### Plugin system (structural, not nominal)
-
-Plugins live under `jarvis/plugins/<group>/<name>.py`, register via `pyproject.toml` `[project.entry-points."jarvis.<group>"]`, and **must not import from `jarvis.*`** inside the plugin module — only structural compatibility with the protocol (registry at `jarvis/core/registry.py`). After editing entry-points: `pip install -e . --no-deps`.
-
-Groups (frozen in `PLUGIN_GROUPS`): `jarvis.wakeword`, `jarvis.stt`, `jarvis.tts`, `jarvis.brain`, `jarvis.harness`, `jarvis.tool`, `jarvis.channel`.
-
-### Streaming first
-
-All `Brain`, `STT`, `TTS`, `Harness` provider methods return `AsyncIterator[...]`. Non-streaming providers yield exactly one element. Consumers always write `async for chunk in provider.xxx()`.
-
-### Event-Bus
+## 2. GitHub — ONE public repo + mandatory privacy gate (BINDING)
-- Events are `frozen=True` dataclasses (`jarvis/core/events.py`) with `trace_id: UUID` + `timestamp_ns`. Immutability enables flight-recorder replay.
-- `subscribe_all` receives every event — the flight recorder is a wildcard subscriber.
-- A broken subscriber is logged, never propagated.
+**There is ONE project repo: the public flagship `https://github.com/PersonalJarvis/PersonalJarvis`** (PascalCase). EVERY maintainer "commit / push / save to GitHub / sichere den Stand" targets THIS repo and no other. <!-- i18n-allow: quoted German maintainer trigger phrase --> The lowercase `personal-jarvis` (git remote `origin`) is kept ONLY as a **silent local backup** — never the deliverable. Never ask "which repo"; it is always the public flagship.
-### Secrets
+**Why the gate exists:** the public repo's history is world-readable forever. One leaked API key, real name, personal path (`C:\Users\<name>\...`), private email, internal project id, or Windows SID that lands in a single commit is permanent — deleting it later does NOT un-publish it (it survives in clones, forks, and caches). So nothing reaches the public repo raw: every push is rebuilt as a **depersonalized snapshot** that runs the full gate below, in order, **fail-closed** — at any step, any uncertainty STOPS the push rather than letting a questionable line through.
-Access via `jarvis.core.config.get_secret(key, env_fallback)` only. Hierarchy: Windows Credential Manager (service `personal-jarvis`) → ENV → `.env` (dev fallback). The wizard (`jarvis/setup/wizard.py`) populates Credential Manager. **Never** put API keys in code, `jarvis.toml`, commits, or `.claude/` files. Voice/chat must never accept secrets (AP-2 — STT log leak vector).
+1. **Tracked-files-only export** — only git-tracked files are exported, so `.gitignore` is the first cut for free: `data/`, `.env`, `jarvis.toml`, the Vault, and key material are never even candidates.
+2. **Distribution denylist** — strips files that ARE tracked but must not ship publicly: internal dev docs, scratch/experiment scripts, signing keys, red-team notes.
+3. **Deterministic PII scrub** — pattern-based masking of the maintainer's real name, personal filesystem paths, machine/user identifiers, and internal project ids across every staged file.
+4. **Mandatory sub-agent privacy review** — a dedicated sub-agent reads the ENTIRE staged snapshot end-to-end and reports anything personal/sensitive the regex scanners could miss (keys, tokens, credentials, personal data, private paths/emails, internal-only content). It is **additive-only**: it can ADD a blocking finding but can never clear what the deterministic gate flagged. A single non-empty finding STOPS the push.
+5. **Deterministic secret/PII scan** — a final regex sweep tuned to real credential shapes/lengths (catches an actual key, not every random hex string), fail-closed.
+6. **Human review** — an explicit maintainer go-ahead before any byte crosses the network. No silent auto-publish.
-### Brain providers + ack-brain
+**Isolation (so the gate can't be bypassed by accident):** the push runs from a **separate clean clone**, never your live working tree — the working tree is never touched and the raw, un-scrubbed state physically cannot leak through. As a hard backstop, the pre-push guard (`scripts/ci/guard_no_raw_public_push.py` + `privacy_pre_push.py`, wired via `.githooks/pre-push`, `core.hooksPath=.githooks`) HARD-BLOCKS any attempt to `git push` raw working state straight to the public repo. Do not remove or weaken it — it has already caught a real leak (a Windows SID that reached public history was blocked, then purged with filter-repo). This whole gate is the `ship-public-release` skill.
-Multi-provider is mandatory — **never hardcode** Anthropic/Claude. Config under `[brain.providers.*]` in `jarvis.toml`. Runtime switch via voice ("Jarvis, switch to Gemini") is a plan requirement; `BrainManager` must support it. Smart fallback chain in `jarvis/brain/manager.py`. Workers use `claude-cli` backend via Claude Max OAuth (user has no Anthropic API account).
+**Two volumes, same gate:** *Discreet (DEFAULT)* — "push", "sichere den Stand", "update GitHub" → clean snapshot through the gate, **no version bump / tag / release / announcement**. *Release (explicit only)* — "Mach ein Release", "Publish release" → the same gate **plus** a SemVer bump + git tag + CHANGELOG entry. <!-- i18n-allow: quoted German maintainer trigger phrases --> When ambiguous, default to discreet.
-#### Provider-agnostic features (no provider/model hardcoding) — BINDING
-
-Every feature must work with **whatever brain provider the user has selected/activated**, and across all configured providers — there are five API providers (`claude-api`, `openrouter`, `openai`, `gemini`, `grok`) plus two subscription-CLI brains (`codex` over ChatGPT, `antigravity` over the Google login), and any of them may be the active one. **Never branch on a provider name or a model id to enable or disable behavior** — no `if provider == "grok"`, no hardcoded `grok-4.3`, no provider-specific code path. Gate on a **capability** instead: `supports_vision`, `supports_tools`, the runtime `can_call_tools()` (and codex's runtime `supports_vision`). If the capability you need doesn't exist yet, **add a capability flag — do not name-check the provider**.
-
-When the active/selected provider lacks a needed capability — e.g. a text-only CLI brain (`antigravity` / `codex-CLI`) cannot see images for Computer-Use — fall through to the first **available** provider that *has* the capability, provider-agnostically and never pinned to a favorite; if none is available, degrade gracefully with an honest message. A provider or model literal may appear **only** as a documented default/fallback (a plugin's own `DEFAULT_MODEL`) or behind a runtime capability probe — never as the gate that decides whether a feature runs. The Computer-Use "no vision" incident was a *capability-flag* bug (grok's `supports_vision` was wrongly `False`) — the correct fix was to set the flag, **not** to pin Computer-Use to grok. This generalizes AP-6 (don't hardcode Claude) to **don't hardcode *any* provider** and is the operational form of the multi-provider mandate above (see AP-21).
-
-Ack-Brain (`jarvis/brain/ack_brain/`) emits a sub-second butler-style preamble before the deep brain replies. Suppress-if-fast gate at 2000ms keeps it out of the way when the deep brain is already fast.
-
-**Persona / custom system prompt:** the live persona comes from `jarvis/brain/persona_loader.py`. `load_effective_persona_prompt()` returns an editable override (`data/custom_system_prompt.md`, written atomically via the Settings UI / `settings_routes.py`) when present, else the packaged `JARVIS_PERSONA.md`. Edits apply on the **next turn** (no restart); `invalidate_cache()` clears the in-process cache. Never hardcode the persona string elsewhere.
-
-### Risk-Tier system
-
-Four levels: `safe` / `monitor` / `ask` / `block`. Priority is **blacklist > whitelist > tool default** (`jarvis/safety/risk_tier.py`). Whitelist downgrades a tier to `safe` with `approved_by="whitelist"` — this is the anti-confirmation-fatigue contract. **Direct calls to `Tool.execute()` are a bug**; only `ToolExecutor.execute()` is authorized.
-
-### Router discipline (binding, ADR-0011 amended)
-
-The router-tier brain is a **pure dispatcher**. Tool surface is the `ROUTER_TOOLS` frozenset in `jarvis/brain/factory.py`. Direct actions outside this set are delegated to OpenClaw via `spawn_openclaw`.
-
-Force-spawn heuristic in `BrainManager._should_force_openclaw`:
-- Smalltalk allowlist wins → never spawn.
-- Action verb (`lies/baue/installiere/öffne/mach/zeig` + repair words) → spawn.
-- External-system marker (PR/Repo/GitHub/Issue) → spawn.
-
-Patterns configurable under `[brain.routing]`. **The sub-jarvis tier was deleted in Welle 4 — only `"router"` remains.** Resurrecting `SUB_TOOLS` or adding `spawn-openclaw`/`dispatch-with-review`/`run-skill` to any worker set breaks the D9 recursion guard. When extending `ROUTER_TOOLS`: amend ADR-0011 + extend `tests/unit/brain/test_routing.py`.
-
-### Output filter discipline (voice path)
-
-Brain output → TTS goes through `scrub_for_voice` in `jarvis/brain/output_filter.py` — **regex only, no LLM calls** (latency mandate). Two TTS paths are wired through scrub:
-- `_handle_utterance` → `_speak()` → `tts.synthesize` (`pipeline.py:1330`).
-- `_on_announcement` (skill/sub-agent announcements, OpenClaw `summary_de` readback) (`pipeline.py:647`).
-
-Whitelist (sacred, never scrubbed): `Datei, Email, Browser, Terminal, Notiz, Termin, Kalender`. Hyphen-compounds preserved (`Browser-Provider` stays). For the full blacklist (tool leaks, jargon, Sir-opener, markdown, self-reference, echo paraphrase, fillers, post-scrub fallback): see the module docstring and `tests/unit/brain/test_output_filter.py` (40 cases). ADR-0010.
-
-### Web search (`search_web`, router-tier)
-
-The `search-web` tool (`jarvis/plugins/tool/search_web.py`) runs a **priority backend chain** in `jarvis/plugins/tool/search_backends.py` (added 2026-06-15): keyed Brave API (if a key is set) → **real DuckDuckGo SERP via the key-free `ddgs` dependency (default)** → DuckDuckGo Instant Answer (last-resort encyclopedic abstract). Backend preference is `[search].backend`; the chain stays key-free so the base VPS install still searches. **Honesty contract:** each attempt returns a `SearchOutcome` with status `ok` / `empty` / `unavailable`. `empty` = searched, genuinely nothing; `unavailable` = backend unreachable — the brain must NOT say "no results" for `unavailable`, it must say search is down. Do not re-flatten these into one reply (that was the charts/weather "found nothing" forensic). The old Instant-Answer-only backend had no real-time index, so freshness queries (charts, news, prices, sports) always came back empty.
-
-### Atomic config writes
-
-Mutations of `jarvis.toml` go via `jarvis/core/config_writer.py` only — `tomlkit`-based (preserves comments), `_WRITE_LOCK` mutex, BOM-aware read/write, tempfile + `os.replace`. For Phase-7 self-mod, the pipeline is **non-negotiable**: Allowlist → Read → Apply → Pre-Validate (`JarvisConfig.model_validate`) → Backup → Tempfile+replace → sync reload-test → Rollback-on-fail → `ConfigReloaded` dispatch → Backup GC → Audit (AD-5; AP-3/4/5/13/14).
-
-Backup directory must be **outside** the watchdog scope (AP-13). Reload-test is **synchronous**, not watchdog-driven (AP-14).
-
-### Multi-layer enum drift prevention
-
-When a vocabulary spans Python ↔ SQL ↔ Pydantic ↔ TypeScript ↔ UI label (e.g. `HangupReason`), use the five-layer pattern from `docs/anti-drift-three-layer.md`. Reference: `jarvis/sessions/constants.py` is the single source of truth; `models.py` runtime-asserts the Pydantic `Literal` against it. Regression guards: `tests/unit/sessions/test_hangup_reason_parity.py` + `tests/integration/test_sessions_db_compatibility.py`. **BUG-008 recurred four times because this scaffolding was missing — apply it preemptively for any new wire-format enum (mission status, skill lifecycle, voice tier).**
-
-### Phase-6 isolation invariants
-
-- Every worker runs in a fresh `git worktree add -b agent/<task-slug>` under `<repo_parent>/sub-agents-outputs/` (≤200-char path cap). No writes to the user's working tree.
-- Every worker subprocess is contained for kill-on-crash: Windows via a Job Object with `JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE` (kernel guarantee — no zombies even on a hard kill); macOS/Linux via a POSIX process-group reaper (`start_new_session` + `os.killpg`-on-close) that reaps the worker tree on a clean shutdown / cancel / timeout / exception but, being userspace, leaks on a hard `kill -9` of the orchestrator itself (Linux follow-up: `PR_SET_PDEATHSIG`; no macOS equivalent).
-- `MAX_CRITIC_LOOPS = 3` is hardcoded. Not parameterizable. Changing requires a new ADR via `/skill phase6-adr-update`.
-- Action/Observation invariant (ADR-0009): the LLM never authors its own Observation. Voice readback reads only Kontrollierer-signed `MissionApproved.summary_de`, never `correction_instruction` from the Critic-LLM.
+**Guardrails:** **Do not PUSH unless the maintainer asks** (local auto-commit is fine and is governed by the Git-workflow rules in §9). `save-to-github` and `github-version` MUST NOT run in this repo — they push raw state and bypass the privacy gate above. Repo doctrine: [`CLOUD.md`](CLOUD.md).
---
-## Optimistic Execution & the "Oops" Protocol (binding)
-
-The core UX contract is **one uninterrupted spoken conversation**. The Talker (router-brain + ack-brain) acknowledges optimistically and never blocks on an MCP round-trip; the Heavy-Duty Worker (Mission-Manager + `claude-cli` Sonnet) executes in the background off the chat transcript. Seed vision: `Architektur-Spezifikation v1.0`. Reality-aligned close-the-gap plan + KPIs (M1–M5) + 4-wave execution: [`docs/plans/optimistic-execution-v1/README.md`](docs/plans/optimistic-execution-v1/README.md). The pillars below are partly live (ack-brain, force-spawn, mission store) and partly open (guaranteed-ACK-before-dispatch, the closed Oops loop, p95 SLO gates).
+## 3. Open-source universality — the maintainer's config is NEVER the baseline (BINDING)
-### Architecture Decisions
-- **AD-OE1** The optimistic ACK ("Geht klar") is emitted **before** the worker dispatch returns — never after. Audit every `_handle_utterance` return path (BUG-007/BUG-020 territory).
-- **AD-OE2** The Talker never `await`s an MCP/network call on the voice path. The talker↔worker queue is the in-process `EventBus` + mission event store — no external broker (cloud-first €5-VPS doctrine, no new hard dep).
-- **AD-OE3** Dumb tools (local scripts) resolve in-process via `local_action_gate`; they MUST NOT wake the worker (false-spawn rate = 0).
-- **AD-OE4** Smart tools: the **worker** issues the MCP call, never the Talker.
-- **AD-OE5** Oops loop: worker failure → frozen `WorkerCorrectionNeeded` event → inject into Talker context → speak ONLY at the next Silero-VAD turn-boundary → through `scrub_for_voice`. Never interrupt mid-utterance.
-- **AD-OE6** Zero silent drops: every worker/MCP failure yields a silent retry OR a spoken correction OR an audited apology (anti-BUG-020 invariant).
-
-### Coding Standards
-- Latency budgets are SLO-gated: p95 wake→ACK < 1.2 s, intent→ACK < 3.0 s, router decision < 150 ms. Regressions fail CI.
-- Every spoken path (utterance + announcement) goes through `scrub_for_voice` (regex only, no LLM call — AP-11).
-- New wire-format vocab (correction reasons, mission status) uses the five-layer enum pattern (`docs/anti-drift-three-layer.md`) + parity test.
-- `ROUTER_TOOLS` stays a frozenset; no spawn-tool ever enters a worker set (AP-5/AP-14). Every subprocess uses `NO_WINDOW_CREATIONFLAGS` (AP-1). Config writes go through `config_writer` (lock + tempfile + BOM-safe, AP-7).
-
----
+The recurring, expensive bug class on this project is **building/testing a feature against the maintainer's own machine, keys, providers, and OS — then shipping it broken for everyone else.** Two faces of ONE rule: **assume an arbitrary downloader, never the maintainer.** It governs the WHOLE product surface, and specifically the **entire API-Keys / credential / integration surface — not just brain providers:** STT, TTS, Vision, Wake, **Telephony (Twilio), Channels (Telegram/Discord), Marketplace plugins (OAuth + MCP), AND credential STORAGE itself.** Every one must:
-## Cross-platform desktop features (the six ports, behind `jarvis/platform/`)
+- **work with WHATEVER single key / login / account the user has** — no provider, model, or integration is load-bearing; a missing / empty / depleted / rate-limited (429) / out-of-credit (402) / unreachable one degrades or crosses to a **different family** with an honest message, and never bricks a core path (router, ack/flash, STT, sub-agent worker, mission critic). A tier whose primary AND fallback resolve to the same family is a single-provider brick (AP-22). Gate on **capability**, never a provider name or model id (AP-21).
+- **work on EVERY OS, including a headless `python:3.11-slim` VPS** with no OS keyring, no D-Bus Secret Service, no GPU, no audio, no Windows APIs. The base `pip install` + boot must succeed there. OS-specific code is allowed only behind (a) a runtime capability check, (b) an extras group, and (c) a graceful English-message no-op elsewhere. Use `pathlib` + capability probes + UTF-8; never hardcode `C:\Users\...` or assume cp1252.
+- **be recoverable IN-APP** — entering / switching / connecting a credential, and recovering from a dead one, happens inside the app, never by hand-editing `jarvis.toml`, exporting an ENV var, or spinning up a cloud instance.
+- **store credentials portably** — the OS keyring when present, else ENV/.env, else the local-file fallback (`config._ensure_keyring_backend`). A save/connect must never 500 on a host without a Secret Service.
-The six desktop power-user features that were historically Windows-only are now **cross-platform behind the shared `jarvis/platform/` capability seam** (`detect_platform()` + a cached frozen `Capabilities` snapshot, AD-5). Each feature is one `Protocol` + one per-OS implementation + a `sys.platform` factory + a graceful logged null-fallback (AD-6); the Windows implementations are **untouched** (AD-7 — they carry the BUG-009/012/014/030 fixes). The migration plan is `docs/plans/cross-platform-mac-linux/`; **ADR-0020 (cross-platform elevation) supersedes ADR-0001** but reuses the HMAC / Pydantic-argv / `shell=False` security core unchanged.
+**Definition of done (NON-NEGOTIABLE).** A change touching config, credentials, a provider/integration, or OS-specific code is NOT "done" — and must not be claimed done — until you verify, with a test or an honest manual trace, the THREE paths that are NOT the maintainer's:
+1. **Fresh install, ONE arbitrary key** — a downloader whose only credential is for a DIFFERENT provider reaches a working path (chat + voice + sub-agent + the touched feature), entirely in-app.
+2. **Headless Linux** — base `pip install` + boot + the touched feature work on `python:3.11-slim`; local-only parts degrade to a logged no-op.
+3. **Cross-family fallback** — when the configured provider/integration is absent or dead, the path crosses to whatever the user actually has, or degrades honestly — never dead-ends on the maintainer's favorite.
-| Feature | Factory | Windows | macOS | Linux | Verification |
-|---|---|---|---|---|---|
-| Terminal (PTY) | `terminal.backend.make_pty_backend` | ConPTY (`pywinpty`) | `ptyprocess` | `ptyprocess` | CI-provable (real PTY, EK-4) |
-| App-launch | `plugins.tool.app_resolver.resolve_app_launch_target` | App Paths | `open -a` | `xdg-open`/exec | CI-provable (resolution) |
-| UI-element-click | `vision.tree_factory.make_ui_tree_source` | UIA | AX (`pyobjc`) | AT-SPI (`pyatspi`) | live sign-off (AX/AT-SPI tree) |
-| Orb overlay | `overlay.surface.make_overlay_surface` | Tk color-key | Tk `-transparentcolor` | best-effort + tray | live sign-off (transparency) |
-| Hotkey | `trigger.backends.make_hotkey_backend` | `global-hotkeys` | `pynput` | `pynput` (X11); Wayland no-op | live sign-off (capture) |
-| Admin/elevation | `admin.transport.make_admin_transport` + `admin.elevator.make_elevator` | UAC + SDDL pipe | Authorization Services + unix socket | pkexec/sudo + unix socket | live sign-off (prompt); never CI-E2E |
-
-**Verification is honestly labelled per feature in `docs/plans/cross-platform-mac-linux/SIGNOFF-LOG.md`.** As of this writing the maintainer has Windows only and nothing is pushed, so every macOS/Linux **live** GUI/permission behavior is `unverified-on-real-desktop` and the `ci.yml` matrix is `CI-configured` (first green run pending push) — **never** claim "CI-verified" or "live-verified" until that log says so. Operators run `scripts/crossplatform/signoff_probe.py` on a real device to fill it in.
-
-- **Dependency reality (AD-14 — do not "fix" this):** `pynput` + `ptyprocess` live in the `[desktop]` extra (no platform marker; `ptyprocess` gated `sys_platform != 'win32'`); `pyobjc-framework-{Quartz,ApplicationServices,Accessibility}` in `[desktop-macos]` (`sys_platform == 'darwin'`). **Linux `pyatspi` is NOT on PyPI — never add it as a pip dependency.** It is GObject-Introspection, distro-packaged (`apt install python3-pyatspi gir1.2-atspi-2.0`), surfaced via the `capabilities.has_ax_tree` runtime probe. A future agent "fixing" a missing-pyatspi pip dep would be wrong.
-- **Doctrine intact:** the headless €5-VPS base install ships **none** of these desktop extras and still boots on a fresh `python:3.11-slim` Linux container — every port is extras-gated and degrades to a logged no-op (AD-6) when its capability is absent. These labels say *which* extras now also work on Mac/Linux, never that any of them are required.
-
-## Windows specifics (do not skip)
-
-- **Unicode stdout:** cp1252 default. New CLI modules must call `sys.stdout.reconfigure(encoding='utf-8')` or stick to ASCII.
-- **Subprocess hygiene:** every `subprocess.*` / `asyncio.create_subprocess_exec` call must pass `creationflags=NO_WINDOW_CREATIONFLAGS` from `jarvis/core/process_utils.py`. Missing this triggers the BUG-012 flicker storm under `pythonw.exe`.
-- **Audio:** WASAPI via `sounddevice`. **WDM-KS host-API is forbidden** (`_FORBIDDEN_OUTPUT_HOSTAPIS` in `jarvis/audio/player.py`) — PortAudio's blocking write API crashes there (BUG-014). Pattern-match device names on shortest unique token (`"PRO X"`), not marketing name.
-- **Hotkeys:** `global-hotkeys`. Avoid `Alt+F4`, `Ctrl+C`, `Win+*`. Safe combos: `ctrl+right_alt+<letter>`.
-- **No Windows Service.** SYSTEM user has no headset/mic access. Jarvis is a tray app in the user session under `pythonw.exe`; autostart via shortcut in `shell:startup`.
-- **UAC manifest:** `asInvoker`. Elevate per-action, never globally.
+**"It works on my machine" is the *defect*, not the evidence.** The maintainer's RTX-5070-Ti / Windows box with Gemini + OpenRouter keys is <0.1 % of the install base. When in doubt, gate behind an extras group with a graceful no-op and lead the docs with the VPS path. Full doctrine: [`CLOUD.md`](CLOUD.md) + [`docs/PHILOSOPHY.md`](docs/PHILOSOPHY.md) (on conflict, the doctrine wins). See AP-21/22/23.
---
-## Brand mark / logo (BINDING)
+## 4. Naming — the agent/mission system is "Jarvis-Agents"
-**The official Jarvis logo is the Gigi GHOST mascot** — the black ghost character with glowing yellow eyes (`jarvis-gigi-256.png` == the maintainer's master `Jarvis-Logo (1).png` at the repo root, md5 `7de0a930`; also served to the frontend as `/jarvis-logo.png`). **The gold four-point star (`jarvis-mark-256.png` / `jarvis.ico` md5 `73bd5837`) is "AI-slop" the maintainer rejects — do NOT use it** as the brand mark anywhere (UI avatar, titlebar/taskbar icon, marketing, videos, intro/onboarding films). Titlebar/taskbar icon must be the ghost (`assets/icons/jarvis.ico`); sidebar avatar is `Sidebar.tsx <img src="/jarvis-logo.png">`. When a feature needs "the Jarvis logo", it is always the ghost mascot.
+The internal agent/mission/harness system is named **Jarvis-Agents** (singular **Jarvis-Agent**) everywhere a human or an LLM could read it — UI labels, docs, comments, new code identifiers, log/voice text. Do not introduce other names for it. (A repo-wide rename of older internal terms to this brand is in progress; write new surfaces as Jarvis-Agents.)
---
-## Screenshots & scratch captures
+## 5. Architecture essentials (respect on every change)
-**All development/verification screenshots go in `screenshots/` at the repo root** — never the repo root itself, never a random cwd. `jarvis/core/screenshots.py` defines `screenshots_dir()` plus a boot sweep (`sweep_screenshots`, wired into `SingleInstance._on_primary_claim`) that (a) consolidates any stray root-level image into `screenshots/` and (b) prunes captures older than **10 days** by mtime. App-runtime Vision frames are separate — they live in `data/flight_recorder/blobs/` and are pruned by `jarvis/telemetry/retention.py`. When an agent or tool saves a UI capture, target `screenshots/`; the folder is git-ignored and self-tidying.
+Full model + module catalog: [`docs/architecture-overview.md`](docs/architecture-overview.md). The rules you cannot break:
----
-
-## Commands
-
-```bash
-# Install
-pip install -e . --no-deps # makes entry_points active (BUG-006/014 recovery)
-pip install -r requirements.txt # full runtime deps
-pip install -e ".[dev]" # adds pytest, ruff, mypy, pyinstaller
-
-# Console scripts (from [project.scripts])
-jarvis # tray app or first-run wizard
-jarvis-ask # one-shot prompt CLI
-jarvis-review-gc # Phase 8.5 review-pipeline GC
-jarvis-review-eval # Phase 8.6 eval harness (--quick/--real/--bucket)
-
-# python -m jarvis (root CLI)
-python -m jarvis --version
-python -m jarvis --wizard # re-run setup wizard
-python -m jarvis --check # hardware analysis
-python -m jarvis --plugins # entry_points registry dump
-python -m jarvis --debug # console logging + config dump
-python -m jarvis --phase5-doctor # vision/admin/CU/HMAC/cost status
-python -m jarvis --install-admin-helper # generate HMAC secret in Credential Manager
-
-# Desktop-App launcher
-python -m jarvis.ui.web.launcher # FastAPI + pywebview + voice + Orb
-python -m jarvis.ui.web.launcher --headless # API+WS only, no window, Mock-Brain
-python -m jarvis.ui.web.launcher --dev # frontend from Vite dev server :5173
-python -m jarvis.ui.web.launcher --no-lock # disable single-instance lock (parallel dev)
-
-# run.bat (root, recommended)
-run.bat # pythonw + voice + Orb
-run.bat --debug # console visible, JARVIS_DEBUG=1
-run.bat --dev # Vite hot-reload
-run.bat --headless # API only, no voice
-# Pre-boot hook: invokes scripts\check-working-tree.ps1 automatically (BUG-014 guard).
-# Voice opt-out: set JARVIS_VOICE=0 before launch.
-
-# Lint/format
-ruff check jarvis/
-ruff format jarvis/
-mypy jarvis/
-
-# Frontend (jarvis/ui/web/frontend/)
-npm install
-npm run dev # http://localhost:5173
-npm run build # → jarvis/ui/web/dist
-npm run test # vitest
-
-# Mandatory worktree preflight (BUG-006/014/015 guard)
-pwsh scripts/preflight.ps1 # exit non-zero → fix before coding
-
-# Operational scripts
-powershell scripts/auto-push-eod.ps1 [-DryRun] # nightly tag+push safety net
-powershell scripts/install-auto-push-task.ps1 -Time "22:00" # register Task Scheduler job
-powershell scripts/drift-guard-daemon.ps1 # config drift defense (BUG-010)
-powershell scripts/install-config-drift-guard-task.ps1
-powershell scripts/check-working-tree.ps1 # working-tree drift recovery
-
-# Smoke / probe scripts
-python scripts/smoke_brain_e2e.py
-python scripts/smoke_phase6_p{1,2,2_jobkill,3,3_real}.py
-python scripts/voice_e2e_probe.py
-python scripts/voice_compare.py
-python scripts/awareness_smoke_a{1,2}.py
-```
+- **8-layer dependency rule:** higher layers reach lower ones **only via protocols** (`jarvis/core/protocols.py`); lateral communication **only** via typed `frozen=True` events on `EventBus` (`jarvis/core/bus.py`) carrying `trace_id` + `timestamp_ns`. A broken subscriber is logged in `_safe_dispatch`, never propagated (AP-18).
+- **Plugins are structural:** under `jarvis/plugins/<group>/<name>.py`, registered via `pyproject.toml` entry-points, and **must not import `jarvis.*`** in the plugin module. After editing entry-points: `pip install -e . --no-deps`. Groups: wakeword, stt, tts, brain, harness, tool, channel.
+- **Streaming first:** all Brain/STT/TTS/Harness methods return `AsyncIterator[...]` (non-streaming yields one element).
+- **Secrets** only via `jarvis.core.config.get_secret`: OS keyring → ENV → `.env` → local-file fallback. Never put keys in code / `jarvis.toml` / commits / `.claude/`. Voice/chat must never accept secrets (AP-2).
+- **Brain is multi-provider** — never hardcode Anthropic/Claude (AP-6); gate features on a **capability** (`supports_vision`, `supports_tools`, `can_call_tools()`), never a provider name/model id (AP-21). Persona comes from `jarvis/brain/persona_loader.py` (editable override → packaged `JARVIS_PERSONA.md`); never hardcode it.
+- **Router discipline (ADR-0011):** the router-tier brain is a pure dispatcher over the `ROUTER_TOOLS` frozenset (`jarvis/brain/factory.py`). No spawn tool ever enters a worker set (AP-5/AP-14). Extending `ROUTER_TOOLS` → amend ADR-0011 + `tests/unit/brain/test_routing.py`.
+- **Voice scrub:** brain→TTS goes through `scrub_for_voice` (`jarvis/brain/output_filter.py`) — **regex only, no LLM call** (AP-11). ADR-0010.
+- **Atomic config writes:** mutate `jarvis.toml` only via `jarvis/core/config_writer.py` (lock + tempfile + BOM-safe, AP-7). Self-mod pipeline (Allowlist→Pre-Validate→Backup→replace→sync reload-test→Rollback→Audit) is non-negotiable (AP-13/14).
+- **Multi-layer enum drift:** any value crossing Python ↔ SQL ↔ Pydantic ↔ TS ↔ UI uses the five-layer pattern (`docs/anti-drift-three-layer.md`) + a parity test, preemptively (BUG-008 recurred 4×).
+- **Worker isolation:** every mission worker runs in a fresh `git worktree` under `<repo_parent>/sub-agents-outputs/` with a kill-on-crash containment (Job Object on Windows; process-group reaper on POSIX). `MAX_CRITIC_LOOPS = 3` is fixed.
+- **Platform gotchas:** UTF-8 stdout (cp1252 default on Windows); every subprocess passes `NO_WINDOW_CREATIONFLAGS` (AP-1); WASAPI audio, WDM-KS forbidden (BUG-014); no Windows Service (SYSTEM has no mic); UAC `asInvoker`, elevate per-action.
---
-## Testing conventions
+## 6. Safety / risk tiers
-```bash
-# Buckets
-pytest tests/ # full suite (asyncio_mode=auto)
-pytest tests/contract/ -v # protocol contract tests (parametrised)
-pytest tests/unit/ -v # per-module
-pytest tests/integration/ -v # phase-level E2E
-pytest tests/e2e/ -v # self-mod + voice review
-pytest tests/missions/ -v # Phase 6
-pytest tests/voice_routing/ tests/voice_latency/ -v
-
-# Markers (from [tool.pytest.ini_options])
-pytest -m phase5 # Phase-5 integration
-pytest -m e2e # Phase-7 E2E
-pytest -m voice_latency # Phase-L latency
-pytest -m eval # golden-query eval
-pytest -m integration # real subprocesses / live external services (Codex OAuth, OpenClaw); self-skips when prereqs missing
-pytest -m "not slow" # fast subset
-pytest -m skip_ci # tests that need desktop/admin/click
-# NOTE: the registered markers are exactly: phase5, skip_ci, e2e, voice_latency,
-# eval, slow, integration (see [tool.pytest.ini_options]). The historical
-# `phase6` / `openclaw_live` markers are NOT registered and select 0 tests today —
-# run those buckets by path instead (`pytest tests/missions/`, `tests/integration/`).
-
-# Layer-targeted
-pytest -k test_tier1_speed # latency regression
-pytest tests/unit/brain/test_routing.py -v # 26-case router discipline
-pytest tests/unit/brain/test_output_filter.py # 40-case scrubber
-pytest tests/unit/awareness/ -v
-pytest tests/unit/memory/wiki/ -v
-pytest tests/unit/sessions/test_hangup_reason_parity.py # BUG-008 drift guard
-pytest tests/unit/plugins/tool/test_wiki_tools.py
-pytest tests/integration/test_openclaw_e2e.py
-pytest tests/integration/test_openclaw_lazy_bootstrap.py
-```
-
-**Conventions:** fakes (not `unittest.mock`) in `tests/fakes/`; audio fixtures under `tests/fixtures/audio/`; trace replays under `tests/fixtures/traces/`; new STT/Brain/Tool/Channel providers must pass the contract suite.
+Four tiers: `safe` / `monitor` / `ask` / `block`, priority **blacklist > whitelist > tool default** (`jarvis/safety/risk_tier.py`). Whitelist downgrades to `safe` — the anti-confirmation-fatigue contract. **Direct `Tool.execute()` is a bug; only `ToolExecutor.execute()` is authorized (AP-3).** Generated skills land as `state="draft"` and are never auto-activated (AP-15).
---
-## Critical anti-patterns (do not do this)
+## 7. Critical anti-patterns (do not do this)
| # | If you do this... | ...you get this bug |
|---|---|---|
@@ -417,7 +115,7 @@ pytest tests/integration/test_openclaw_lazy_bootstrap.py
| AP-2 | Accept API keys via voice/chat | STT log leak — credential exfiltration vector |
| AP-3 | Call `Tool.execute()` directly (bypassing `ToolExecutor`) | Risk-tier/whitelist/plausibility skipped |
| AP-4 | Add a new `hangup_reason`/mission-status string in one site only | BUG-008 recurrence: HTTP 500, empty UI |
-| AP-5 | Put `spawn-openclaw`/`dispatch-with-review`/`run-skill` in a worker tool set | D9 recursion: worker spawns supervisor, infinite loop |
+| AP-5 | Put the harness-spawn / `dispatch-with-review` / `run-skill` tool in a worker tool set | D9 recursion: worker spawns supervisor, infinite loop |
| AP-6 | Hardcode `Claude`/`Anthropic` API client | User has no Anthropic API account; breaks `cfg.brain.primary` |
| AP-7 | Write `jarvis.toml` without `_WRITE_LOCK` + tempfile + BOM handling | BUG-018: BOM-corrupted TOML, backend won't boot |
| AP-8 | Skip `scripts/preflight.ps1` in a new worktree | BUG-006/014: edits go to a worktree the live Python doesn't import from |
@@ -426,70 +124,96 @@ pytest tests/integration/test_openclaw_lazy_bootstrap.py
| AP-11 | Add an LLM call inside `scrub_for_voice` | TTS latency tank |
| AP-12 | Encode API keys in `jarvis.toml` or commit `.env` | Credential leak; bypasses `keyring` audit trail |
| AP-13 | Block on watchdog reload for atomic-write verification | Race: file half-applied, no sync rollback |
-| AP-14 | Re-add a Sub-Jarvis tier or `SUB_TOOLS` set | Welle 4 deleted it; resurrection breaks the OpenClaw-bridge contract |
+| AP-14 | Re-add a sub-tier or `SUB_TOOLS` set | Welle 4 deleted it; resurrection breaks the agent-harness bridge contract |
| AP-15 | Auto-activate generated skills (`state` ≠ `draft`) | Lateral-movement vector; skills run without review |
| AP-16 | Add `[phase6.*]`/`[memory.wiki.*]` keys without `ConfigDict(extra="allow")` | Pre-validate rejects → boot fails after self-mod |
| AP-17 | Run Jarvis as a Windows Service | SYSTEM has no mic/headset access |
| AP-18 | Propagate a subscriber exception from `EventBus._safe_dispatch` | One handler kills the pipeline |
-| AP-19 | Reuse a process-global progress counter in a stall/heartbeat watchdog without resetting it per unit of work | BUG-032: watchdog measures the idle gap *between* turns → spuriously aborts a fresh TTS answer before its first frame ("Jarvis listens forever") |
-| AP-20 | `continue` (instead of `break`) a WS receive loop on an error that isn't `WebSocketDisconnect` | Unclean client disconnects raise `RuntimeError("WebSocket is not connected")`, not `WebSocketDisconnect` → the loop re-reads a dead socket forever → ~9 MB/s log storm + app self-restart that kills in-flight missions. Catch `RuntimeError` and `break` (`server.py` `_handle_ws`, fixed 1793ceaf) |
-| AP-21 | Pin a feature to a provider **name** or a **model id** (`if provider == "grok"`, hardcoded `grok-4.3`, a provider-specific branch) instead of gating on a **capability** | The feature silently breaks for every other provider and for whatever provider the user selected — the multi-provider mandate (AP-6) generalized to *any* provider. Gate on `supports_vision` / `supports_tools` / `can_call_tools()`; if the flag is wrong or missing, fix/add the capability (e.g. grok's `supports_vision` was wrongly `False` → Computer-Use died "no vision"; the fix was the flag, not pinning CU to grok) |
+| AP-19 | Reuse a process-global progress counter in a stall/heartbeat watchdog without resetting it per unit of work | BUG-032: watchdog measures the idle gap *between* turns → spuriously aborts a fresh TTS answer before its first frame |
+| AP-20 | `continue` (instead of `break`) a WS receive loop on an error that isn't `WebSocketDisconnect` | Unclean disconnects raise `RuntimeError` → loop re-reads a dead socket forever → log storm + self-restart. Catch `RuntimeError` and `break` |
+| AP-21 | Pin a feature to a provider **name** or **model id** instead of gating on a **capability** | The feature silently breaks for every other provider and for whatever the user selected. Gate on `supports_vision` / `supports_tools` / `can_call_tools()`; if a flag is wrong/missing, fix/add the capability — don't pin the feature |
+| AP-22 | Configure a tier (router / ack / STT / TTS / worker / critic / fallback) whose primary AND fallback resolve to the SAME provider family, or build a fallback chain from hardcoded provider NAMES | Single-provider brick: one missing key / 429 / 402 / outage takes the whole tier down even when the user has a healthy DIFFERENT provider. Resolve every tier through one key-aware chain that skips the dead/keyless provider, crosses families, and degrades honestly only when NO family is reachable — recoverable in-app |
+| AP-23 | Build or TEST a feature only against the maintainer's own config / keys / provider / OS and claim it done | The whole API-Keys section silently bricked for every other downloader and on a headless VPS (credentials couldn't even be SAVED, ENV keys read as "not configured", channels/plugins/OAuth 500'd). "Works on my machine" is the defect — verify the three non-maintainer paths in §3 |
+| AP-24 | Call a shared native inference engine (ctranslate2 / faster-whisper, an ONNX / torch session) concurrently from two callers, OR "recover" a hung inference with only a timeout that re-polls the SAME wedged engine | `WhisperModel.transcribe` is NOT thread-safe: the wake poll loop + the VAD probe sharing one provider hung it forever; a hung `to_thread` can't be cancelled, so a timeout only BOUNDS, never RECOVERS. Fix: a non-blocking per-instance inference lock (2nd call → skip) + a `recover()` that rebuilds a FRESH model after N failures (BUG-036) |
---
-## Recurring bug classes (must internalize)
+## 8. Recurring bug classes (must internalize)
-Detail in [`docs/BUGS.md`](docs/BUGS.md). Seven classes recur — recognize the signal, apply the defense:
+Detail in [`docs/BUGS.md`](docs/BUGS.md). Recognize the signal, apply the defense:
-1. **Four-layer restore trap** (BUG-006 → -014 → -015): worktree + frontend build + RAM + **editable-install pin to a deleted clone**. Signal: fix "works in tests" but Jarvis behavior unchanged after restart. Defense: `pwsh scripts/preflight.ps1` + `python -c "import jarvis; print(jarvis.__file__)"`.
-2. **Multi-layer enum drift** (BUG-008, 4 episodes): empty UI list while DB has rows, HTTP 500, `literal_error` in Pydantic. Defense: `docs/anti-drift-three-layer.md` pattern + parity test.
-3. **Config drift** (BUG-010 triple-defense): parallel sessions rewriting `jarvis.toml`, silently rolling back provider switches. Defense: `scripts/drift-guard-daemon.ps1` (5-min cron) + ENV overrides + read-only TOML + BOM-safe writer (`UTF8Encoding($false)`).
-4. **Subprocess console flicker** (BUG-012): missing `NO_WINDOW_CREATIONFLAGS` on `pythonw.exe`. Defense: every new subprocess call imports from `jarvis.core.process_utils`.
-5. **Audio host-API blocking-write trap** (BUG-014): WDM-KS picked by auto-resolver, PortAudio blocking API crashes. Defense: `_FORBIDDEN_OUTPUT_HOSTAPIS` filter; shortest-unique-token device matching.
-6. **Watchdog stale cross-unit counter** (BUG-032): a stall/heartbeat watchdog reads a process-global progress counter (`last_write_ns`) that is never reset per unit, so it measures idle time *between* units and fires spuriously — e.g. the TTS playback watchdog aborted a fresh answer before its first frame ("Jarvis listens forever / never speaks") whenever the brain thought longer than the 5 s stall window. Signal: a "wedge" abort whose timestamps are impossible (fires earlier than the threshold; the resource responds *after* the abort). Defense: reset the counter at unit start (before any lock wait); re-arm the "not started yet" guard per unit, not at construction; guards in `tests/unit/audio/test_player_stall_recovery.py` + `tests/unit/speech/test_speak_playback_timeout.py`.
-7. **Loop on an unexpected teardown error** (AP-20, WS dead-socket): a receive/stream loop catches the *expected* clean-disconnect exception but `continue`s on any other error, so an unclean teardown that raises a *different* exception (here `RuntimeError` from FastAPI, not `WebSocketDisconnect`) spins forever — log storm + self-restart. Signal: runaway CPU/log growth + ErrorOccurred every turn after a client drops. Defense: on the socket loop, treat any read error as terminal — `break`, never `continue`.
+1. **Restore trap** (BUG-006/014/015): worktree + frontend build + RAM + editable-install pinned to a deleted clone. Signal: fix "works in tests" but behavior unchanged after restart. Defense: `pwsh scripts/preflight.ps1` + `python -c "import jarvis; print(jarvis.__file__)"`.
+2. **Multi-layer enum drift** (BUG-008): empty UI list while DB has rows, HTTP 500, Pydantic `literal_error`. Defense: five-layer pattern + parity test.
+3. **Config drift** (BUG-010): parallel sessions rewriting `jarvis.toml`, silently rolling back provider switches. Defense: `scripts/drift-guard-daemon.ps1` + ENV overrides + BOM-safe writer.
+4. **Subprocess console flicker** (BUG-012): missing `NO_WINDOW_CREATIONFLAGS`. Defense: import from `jarvis.core.process_utils`.
+5. **Audio host-API blocking-write trap** (BUG-014): WDM-KS auto-picked, PortAudio crashes. Defense: `_FORBIDDEN_OUTPUT_HOSTAPIS` + shortest-unique-token matching.
+6. **Watchdog stale cross-unit counter** (BUG-032): a stall watchdog reads a process-global counter never reset per unit → fires spuriously between units. Defense: reset the counter at unit start; re-arm the "not started" guard per unit.
+7. **Loop on an unexpected teardown error** (AP-20): a socket loop `continue`s on a non-`WebSocketDisconnect` error → spins on a dead socket. Defense: treat any read error as terminal — `break`.
+8. **Wedged un-cancellable native inference** (BUG-036): a shared ctranslate2/faster-whisper model called concurrently hangs unrecoverably; every later transcribe re-polls the dead engine forever. Defense: serialize with a non-blocking lock; self-heal by rebuilding a fresh model (AP-24).
---
-## Working tree is frequently SHARED (operational reality)
-
-This repo's working tree is routinely edited by **several parallel agent sessions at once** (the MEMORY.md history is full of "shared tree", "a parallel session swept my index", "broke HEAD"). Treat the index as contested:
-
-- **Never assume the staged diff is only yours.** Before committing, stage and commit **hunk-isolated** (`git add -p` / pathspec-scoped commits) so you don't sweep another session's in-flight work into your commit.
-- A large uncommitted diff (this snapshot opened with ~65 changed files across `jarvis/`, `tests/`, frontend, docs) is the **normal** state, not a signal that something is broken. Most belong to other sessions; touch only what your task owns.
-- If the index or HEAD looks corrupted by a concurrent write, the recovery pattern that has worked here is a **temp-index commit + `update-ref` CAS + safety branch** (see the custom-system-prompt and mission-rerun memory entries). Reach for `git-rescue` when it is repo-wide disorder.
-- App restart is **`POST /api/settings/restart-app`**, not `Stop-Process` (which returns Access Denied under the tray `pythonw.exe`). Most uncommitted fixes are loaded via the editable install but still need this restart to take effect.
+## 9. Operational reality & Git workflow
----
-
-## Memory + Wiki
+- **The working tree is frequently SHARED** — several parallel agent sessions edit it at once. Never assume the staged diff is only yours; commit **hunk-isolated** (`git add -p` / pathspec-scoped). A large uncommitted diff is the **normal** state. If the index/HEAD looks corrupted by a concurrent write, recover via temp-index commit + `update-ref` CAS + safety branch (reach for `git-rescue` on repo-wide disorder).
+- **App restart is `POST /api/settings/restart-app`**, not `Stop-Process` (Access Denied under the tray `pythonw.exe`). Editable-install fixes still need this restart to take effect.
+- **New worktree:** run `pwsh scripts/preflight.ps1` before writing code; exit non-zero → fix first (BUG-006/014).
+- **Memory:** check `MEMORY.md` (`~/.claude/projects/.../memory/`) before larger decisions — stable user preferences live there.
+- **Plan vs. code:** on conflict, the plan wins (`~/.claude/plans/also-er-muss-auch-lexical-pond.md`); code deviations get documented back in the plan.
-This project has an auto-memory at `~/.claude/projects/C--Users-Administrator-Desktop-Personal-Jarvis/memory/`. **Check `MEMORY.md` before larger decisions** — stable user preferences (multi-provider brain, hybrid privacy, bilingual, anti-confirmation-fatigue, no-Anthropic-API, frontier-quality-before-cost) live there.
+### Git workflow
-The Knowledge Wiki is the long-term memory tier (B0/B1/B5/B7/B8/B9 live). Three router-tier tools: `wiki-recall` (search), `wiki-page-read` (read by vault path), `wiki-ingest` (deterministic save-fact). Vault root configured in `[wiki_integration].vault_root`; default `wiki/obsidian-vault/`. Telemetry snapshot at `GET /api/wiki/telemetry`. Trigger contract in ADR-0014.
+*(The maintainer already pins these in their personal global config; they are restated here at the project level so every contributor and agent in this repo follows the same workflow.)*
-The legacy Curator-Merger is soft-disabled since 2026-05-17 (`[memory.legacy_curator] enabled = false`, gated in `jarvis/brain/factory.py`). The `data/workspace/` snapshot stays on disk and 35 reader sites (Whoami-Tool, ProfileView, OpenClaw-Workspace setup, etc.) keep rendering it — but no new writes land there. Searching the wrong path still returns frozen-in-time hits. Hart-Cut (migrate snapshot to `wiki/obsidian-vault/`, refactor readers, delete `jarvis/memory/curator/`) remains open and can be triggered by flipping `enabled = true` ↔ false during the rewrite.
+- **Auto-commit after each completed logical step**, without being asked. BUT because the working tree is shared (above), stage only **your own** changed files by explicit path or `git add -p`, hunk-isolated — **never** `git add -A` / `git add .` (that sweeps another session's in-flight, possibly unfinished or secret-bearing work into your commit, and is the main concurrency hazard here).
+- **Use meaningful Conventional-Commit messages** (`feat:`, `fix:`, `refactor:`, `docs:`, `chore:`).
+- **Never push to the remote automatically** — push only when the maintainer explicitly says so (and a public push still runs the privacy gate in §2).
+- **Never commit secrets, `.env` files, keys, tokens, or credentials.** If any appear untracked, STOP, flag them to the maintainer, and do not commit them.
+- **Never `git add -A` / `git add .`** without first scanning the staged set for secrets and for files that belong to another session.
---
-## Worktree activation checklist
+## 10. Run & test
+
+```bash
+# Install / activate entry-points (BUG-006/014 recovery) + full deps + dev tools
+pip install -e . --no-deps
+pip install -r requirements.txt
+pip install -e ".[dev]" # pytest, ruff, mypy
-Before writing any code in a new worktree: **`pwsh scripts/preflight.ps1`**. If it exits non-zero, fix the reported issue before proceeding. Reference: BUG-006, BUG-014.
+# Launch
+run.bat # tray app + voice + Orb (recommended)
+run.bat --headless # API/WS only, no voice
+python -m jarvis.ui.web.launcher --dev # frontend from Vite :5173
+python -m jarvis --wizard | --check | --plugins | --debug | --phase5-doctor
----
+# Lint / typecheck
+ruff check jarvis/ && ruff format jarvis/ && mypy jarvis/
-## Pointers (no need to inline)
+# Frontend (jarvis/ui/web/frontend/)
+npm install && npm run dev # build → npm run build ; tests → npm run test
+```
-- ADRs: `docs/adr/0001..0023` (0009/0010/0014 carry legacy duplicates — see `tests/unit/docs/test_adr_uniqueness.py`). **ADR-0001 (admin IPC named-pipe + HMAC) is superseded by ADR-0020** (cross-platform elevation: `AdminTransport` + `Elevator` seams; the HMAC/envelope/Pydantic-argv security core is reused unchanged; per-OS op vocabulary in `jarvis/admin/schema_unix.py`).
-- Phase docs: `docs/phase{0,1,1a,1c,2,4,5,6}-*.md`.
-- Architecture contracts: `docs/openclaw-bridge.md`, `docs/anti-drift-three-layer.md`.
-- Operational: `scripts/README-auto-push.md`, `scripts/preflight.ps1`, `scripts/drift-guard-daemon.ps1`.
-- Self-Mod: `docs/self_mod.md`.
-- Bug register: `docs/BUGS.md`.
-- Jarvis CLI (drive a running Jarvis from the terminal / an external coding agent / Jarvis itself): `docs/jarvis-cli.md` + generated `docs/jarvis-cli-reference.md`. Thin HTTP client over the REST API in `jarvis/cli_ctl/` (binaries `jarvis`/`jarvisctl`/`jctl`); the dynamic `jarvis api <tag> <op>` layer covers every mounted endpoint, curated `jarvis <group> <command>` groups add ergonomics. Registered in the CLI catalog as `jarvisctl` so Jarvis self-controls via `cli_jarvisctl` (dangerous/recursive verbs blocked). New REST routes must stay mounted — enforced by `scripts/ci/check_cli_coverage.py` (pre-push + the `jarvisctl` CI job). Skills: `.claude/skills/generate-cli-command` + `.claude/skills/drive-jarvis-cli`.
+```bash
+# Tests (asyncio_mode=auto; fakes in tests/fakes/, not unittest.mock)
+pytest tests/ # full suite
+pytest tests/unit/ -v # per-module
+pytest tests/integration/ -v # phase-level E2E (real subprocesses; self-skips when prereqs missing)
+pytest tests/missions/ -v # Phase 6
+pytest -m "not slow" # fast subset
+# Registered markers: phase5, skip_ci, e2e, voice_latency, eval, slow, integration.
+# Targeted guards: test_routing.py (router), test_output_filter.py (scrubber),
+# test_hangup_reason_parity.py (enum drift). New STT/Brain/Tool/Channel providers
+# must pass tests/contract/.
+```
---
-## Plan vs. code
+## 11. Pointers
-On conflict, the plan wins (`~/.claude/plans/also-er-muss-auch-lexical-pond.md`, `docs/openclaw-bridge.md`). Code deviations must be documented back in the plan, not silently accepted.
+- **Architecture + module catalog + product detail:** [`docs/architecture-overview.md`](docs/architecture-overview.md).
+- **Doctrine:** [`CLOUD.md`](CLOUD.md) (cross-platform charter), [`docs/PHILOSOPHY.md`](docs/PHILOSOPHY.md).
+- **Bug register:** [`docs/BUGS.md`](docs/BUGS.md). **Anti-drift:** [`docs/anti-drift-three-layer.md`](docs/anti-drift-three-layer.md). **Self-Mod:** [`docs/self_mod.md`](docs/self_mod.md).
+- **ADRs:** `docs/adr/0001..0023` (ADR-0001 superseded by ADR-0020). **Phase docs:** `docs/phase{0,1,1a,1c,2,4,5,6}-*.md`.
+- **Operational scripts:** `scripts/preflight.ps1`, `scripts/drift-guard-daemon.ps1`, `scripts/README-auto-push.md`.
+- **Jarvis control CLI** (drive a running Jarvis from the terminal / an agent / itself): `docs/jarvis-cli.md` + generated `docs/jarvis-cli-reference.md` (`jarvis/cli_ctl/`, binaries `jarvis`/`jarvisctl`/`jctl`). New REST routes must stay mounted — enforced by `scripts/ci/check_cli_coverage.py`.
diff --git a/docs/BUGS.md b/docs/BUGS.md
index 4e6f1a9de0..fe0528cf5d 100644
--- a/docs/BUGS.md
+++ b/docs/BUGS.md
@@ -1,10 +1,10 @@
---
-title: Bug Register Sub-Agent Pipeline
+title: Bug Register Jarvis-Agent Pipeline
date: 2026-04-29
-scope: Voice → Router → Sub-Jarvis-Spawn → Harness-Dispatch
+scope: Voice → Router → Jarvis-Agent-Spawn → Harness-Dispatch
---
-# Bug Register: Sub-Agent Pipeline (2026-04-29)
+# Bug Register: Jarvis-Agent Pipeline (2026-04-29)
This register documents every root cause found and fixed around the
"Spawn sub-agents." voice failures. Per bug: symptom (what the user hears),
@@ -805,7 +805,7 @@ Expected: speech unit suite green; a normal response ends with
`speak`/`tool_call` actions terminate with `failed` + a clear
error message. `after_delay`/`at_time` triggers work; the
tasks view is fully functional. Voice/tool wiring comes in the
- Phase-5 brain-tool step (`schedule_task` as a Sub-Jarvis tool).
+ Phase-5 brain-tool step (`schedule_task` as a Jarvis-Agent tool).
- **Brain tool to create one is missing** — the voice command "Erinner mich in 2h" ("Remind me in 2 hours")
does not work yet; tasks can currently only be created via REST
(or a future form UI).
@@ -1468,7 +1468,7 @@ See also: `docs/anti-drift-three-layer.md` for the general pattern.
additions.
2. Closed two new gaps that grew in after the original fix:
- `jarvis/core/paths.py:141` — `subprocess.run([...mklink...])` ran
- without `creationflags` for every Sub-Agent-output session.
+ without `creationflags` for every Jarvis-Agent-output session.
- `jarvis/missions/kontrollierer/orchestrator.py:517` —
`subprocess.run(["git", "diff", "HEAD"])` ran without
`creationflags` on every mission completion.
@@ -1770,7 +1770,7 @@ See also: `docs/anti-drift-three-layer.md` for the general pattern.
to fail. A defensive `try/except ImportError` plus a fallback
would have downgraded this to a soft warning instead of a backend
crash. Worth considering for AD-15 in
- `docs/openclaw-bridge.md` or its overlay equivalent.
+ `docs/jarvis-agents-bridge.md` or its overlay equivalent.
3. **Server-hangs need lifecycle checks.** Inside
`_run_backend`, the import of `start_overlay` happens between two
`loop.run_until_complete` calls. Any exception there silently
@@ -1893,7 +1893,7 @@ have caught it.
``jarvis/sessions/recorder.py::_on_transcript_final`` always wrote
``current_turn.user_text = event.transcript.text`` and never closed
the turn. Turn boundaries are normally drawn by ``_on_system_state``
- on the SPEAKING→LISTENING transition, but in OpenClaw-routed turns
+ on the SPEAKING→LISTENING transition, but in Jarvis-Agents-routed turns
the brain returns ``finish_reason="suppress_response"`` and the
state goes THINKING→LISTENING (no SPEAKING). The auto-turn therefore
stays open across every utterance in the session, and the text
@@ -2194,7 +2194,7 @@ Three decoupled layers each contribute independently:
deep brain even runs.
3. **Critic layer:** The Critic currently ratifies empty diffs for non-file
- tasks (AD-9 in `docs/openclaw-bridge.md`). An OpenClaw worker can produce
+ tasks (AD-9 in `docs/jarvis-agents-bridge.md`). A Jarvis-Agent worker can produce
`success=True` with no tool-call evidence, purely from a text claim. The
Critic reads the worker's unverified assertion and signs it off.
@@ -2213,7 +2213,7 @@ analysis and the three-layer fix.
with the deterministic response. The brain is never called.
- `jarvis/brain/manager.py` — sibling `_capability_resolves(text)` check
alongside `_should_force_openclaw`. If action-intent and no matching
- capability and not smalltalk: skip brain + OpenClaw, emit UNSUPPORTED.
+ capability and not smalltalk: skip brain + Jarvis-Agent, emit UNSUPPORTED.
3. **Dynamic system prompt.** The hardcoded `NUTZE: search_web` block is
replaced with `registry.render_for_prompt(lang)`. If a capability is not
@@ -2227,7 +2227,7 @@ analysis and the three-layer fix.
5. **Critic capability-honesty gate.** For capabilities with
`requires_evidence=True`, `CriticVerdict.success=False` when no tool-call
evidence is present. `summary_de` is derived from tool-call evidence, not
- from the worker's unverified text claim. For Welle-2 mock OpenClaw (no
+ from the worker's unverified text claim. For Welle-2 mock Jarvis-Agents (no
telemetry), the Critic defaults conservative-fail.
### Regression Test
@@ -2256,7 +2256,7 @@ pytest tests/integration/test_capability_coupling_e2e.py -v
- [docs/plans/capability-coupling/EXTENSIBILITY.md](plans/capability-coupling/EXTENSIBILITY.md) — contributor guide for adding new capabilities.
- `docs/anti-drift-three-layer.md` — cross-reference section comparing this
pattern to the anti-drift and visible-feedback patterns.
-- AD-9 in `docs/openclaw-bridge.md` — Critic + risk-tier preconditions that
+- AD-9 in `docs/jarvis-agents-bridge.md` — Critic + risk-tier preconditions that
BUG-028 exposes as insufficient for non-file tasks.
## BUG-029: Long dictation truncated — VAD 8 s max-utterance cut + no downstream accumulation (HIGH, 2026-05-24)
@@ -2341,9 +2341,9 @@ sometimes "succeeded" (`applied_live=true`); the second swap reliably crashed.
### Root cause
-Each overlay surface (`WhisperBarOverlay`, mascot `OrbOverlay`) owns its own
+Each overlay surface (`JarvisBarOverlay`, mascot `OrbOverlay`) owns its own
`tk.Tk()` root, created on a short-lived named daemon thread
-(`whisperbar-tk-mainloop` / `orb-tk-mainloop`). A "live swap" tried to tear the
+(`jarvisbar-tk-mainloop` / `orb-tk-mainloop`). A "live swap" tried to tear the
old root down (`stop()` → `root.after(0, root.destroy)` + thread join) and build
a new one. Tkinter / `_tkinter` keeps **process-global, per-thread** Tcl
interpreter state. When the destroyed root's Python wrapper object is later
@@ -2523,7 +2523,7 @@ not just that the artifact is present — and prefer the scheduler subsystem
(Task Scheduler / launchd / systemd-user) over the desktop-shell startup queue
when promptness matters. Guards: `tests/unit/autostart/test_windows_task.py`.
-## BUG-035: "Listens forever" #4 — explicit Sub-Agent command hijacked by a topical skill match, then a beheaded mute turn ends in silence (HIGH, 2026-06-10)
+## BUG-035: "Listens forever" #4 — explicit Jarvis-Agent command hijacked by a topical skill match, then a beheaded mute turn ends in silence (HIGH, 2026-06-10)
### Symptom
@@ -2635,3 +2635,77 @@ test_forced_cut_then_false_start_blip_still_flushes_tail,
test_forced_cut_then_user_resumes_no_extra_tail_flush}` +
`tests/unit/speech/test_long_dictation_accumulation.py::{test_empty_tail_flush_finalizes_carry,
test_empty_flush_without_carry_skips_stt}`.
+
+---
+
+## BUG-036: Custom wake word permanently dead — wedged ctranslate2 transcription (2026-06-29)
+
+- **Date:** 2026-06-29 · **Scope:** `jarvis/plugins/stt/fwhisper.py`,
+ `jarvis/speech/rolling_whisper_wake.py` (custom-phrase `stt_match` wake path)
+
+### Symptom (what the user experiences)
+
+A custom wake word ("Hey Nico", any name on the `stt_match` / `RollingWhisperWake`
+path) stops working **entirely**: no orb, no bar, no reaction — for HOURS — no
+matter how loud or how often the word is spoken, and **even an app restart does
+not clear it**. User report: "I have to shout it ten times", then "I restarted and
+it's still dead, it doesn't work at all, with any wake word".
+
+### Root cause (code path)
+
+The local faster-whisper wake model (`FasterWhisperProvider`, ctranslate2 backend)
+is shared by TWO callers — the `RollingWhisperWake` poll loop AND the VAD
+"listening bubble" probe (`pipeline._probe_stt = self._stt` for a custom phrase).
+Both call `transcribe_pcm`, which runs `model.transcribe` in a worker thread
+(`asyncio.to_thread`). **ctranslate2's `WhisperModel` is NOT thread-safe for
+concurrent `transcribe` on one model object** — two overlapping calls corrupt its
+internal state and the call HANGS forever. An `asyncio.to_thread` worker cannot be
+cancelled, so:
+
+1. Every later `transcribe_pcm` times out at 8 s, is abandoned, re-polled, and
+ hangs again — an infinite `Transkription nach 8.0s abgebrochen (hung STT)` loop.
+ The heartbeat `transcribed`/`matched` counters FREEZE while `windows` keeps
+ climbing. Live forensic (`data/jarvis_desktop.log`): `transcribed=10 matched=2`
+ frozen for ~2 h while `windows` climbed to 20889; zero wakes the whole time.
+2. The hung, un-killable threads **exhaust the default thread pool**, which also
+ starves the in-app Restart endpoint's own `asyncio.to_thread` — so the Restart
+ button hangs "Restarting…" forever. That is why a soft restart did NOT clear it;
+ only a HARD process kill (Task Manager → end `pythonw.exe`) + relaunch worked.
+
+The 8 s timeout (added earlier) only BOUNDED each hang (re-poll the SAME wedged
+engine) — it never RECOVERED the model, so the wake stayed permanently dead.
+
+### Fix (file:line + test)
+
+1. **Prevent the corruption** — `jarvis/plugins/stt/fwhisper.py`
+ `FasterWhisperProvider._transcribe_sync`: a NON-BLOCKING per-instance inference
+ lock. A second concurrent call raises `TranscribeBusy` and is skipped (the
+ caller re-polls) instead of running `model.transcribe` concurrently or piling
+ worker threads up behind a hung call.
+2. **Self-heal the wedge** — `FasterWhisperProvider.recover()` drops the (possibly
+ hung) model + its lock so the next `transcribe_pcm` rebuilds a FRESH engine; the
+ hung thread keeps the OLD object/lock alive (orphaned, never blocks the fresh
+ path). `RollingWhisperWake.detect` counts consecutive transcribe failures and
+ calls `recover()` after `_WEDGE_RECOVER_AFTER_FAILS = 5` (resets on any success)
+ — a wedge now self-heals in seconds, NO restart needed.
+3. **Unwedge the Restart button** (parallel fix) — the restart endpoint runs on a
+ dedicated thread (`_run_off_pool`) so hung wake threads can no longer starve it.
+ A hard kill is still required for an ALREADY-wedged old process.
+
+Tests: `tests/unit/plugins/stt/test_fwhisper_concurrency.py`
+(`test_concurrent_transcribe_calls_never_overlap`, `test_busy_lock_raises_transcribe_busy`,
+`test_recover_drops_model_and_swaps_in_a_fresh_lock`) +
+`tests/unit/speech/test_rolling_whisper_wake.py::test_wake_self_heals_a_wedged_model_via_recover`.
+
+### Defense (bug class) — see AP-24
+
+Any shared single-threaded NATIVE inference engine (ctranslate2 / faster-whisper,
+and most ONNX / torch sessions) must NEVER be called concurrently — serialize with
+a NON-BLOCKING guard (concurrent call → skip, never overlap). And because a hung
+native `to_thread` call cannot be cancelled, a wedge must be RECOVERABLE (rebuild a
+fresh object), not merely timeout-bounded. **A timeout that re-polls the SAME
+wedged engine is a permanent-dead-state in disguise.** Signal: `transcribed` /
+`matched` heartbeat counters frozen while `windows` climbs; "hung STT" every
+timeout; a restart that does not help (the un-killable threads can even starve
+other thread pools, including the Restart button). Production restart after this
+fix: required (a HARD kill for an already-wedged old process).
diff --git a/jarvis/plugins/stt/fwhisper.py b/jarvis/plugins/stt/fwhisper.py
index 98328f5b48..fc9f325121 100644
--- a/jarvis/plugins/stt/fwhisper.py
+++ b/jarvis/plugins/stt/fwhisper.py
@@ -9,8 +9,11 @@ Auf RTX 5070 Ti liefert distil-large-v3 für eine 5-Sekunden-Utterance
"""
from __future__ import annotations
+import contextlib
import logging
-from collections.abc import AsyncIterator
+import sys
+import threading
+from collections.abc import AsyncIterator, Iterator
from typing import Any
import numpy as np
@@ -21,6 +24,52 @@ from jarvis.core.protocols import AudioChunk, Transcript
log = logging.getLogger(__name__)
+class TranscribeBusy(Exception):
+ """Raised when a transcription is skipped because another is already in
+ flight on the SAME (shared) model. ctranslate2 is not thread-safe for
+ concurrent transcribe, so the wake poll loop and the VAD probe must not run
+ the model at once. The caller treats this as a transient miss and re-polls;
+ a run of these means the in-flight call is wedged (see ``recover``)."""
+
+
+def inference_only_import_shield() -> Iterator[None]:
+ """Block ``transformers`` + ``torch`` ONLY while ctranslate2 imports.
+
+ ``import ctranslate2`` (pulled in transitively by ``faster_whisper``) eagerly
+ runs ``from ctranslate2 import converters`` at the bottom of its ``__init__``,
+ and ``ctranslate2.converters.transformers`` imports the full **transformers**
+ (~1.5 s) → **torch** (~1.3 s) stack. Those are model-*conversion* code paths
+ (HuggingFace → CTranslate2 format) that the inference engine (wake match +
+ utterance STT) NEVER touches. Stubbing both modules as un-importable for the
+ duration of the import makes the converter shim's guarded import skip them,
+ cutting the faster_whisper/ctranslate2 import from **~2.9 s warm / ~14 s cold
+ to ~0.17 s** (measured 2026-06-28) — the single biggest cost on the wake
+ "ready to talk" path. Cross-platform (pure ``sys.modules`` manipulation).
+
+ Safety: only stubs a module that is **not already really imported** (so it can
+ never clobber a torch loaded first by Silero-VAD), and on exit removes ONLY
+ the stub it set — leaving any real module another thread imported meanwhile.
+ Inference was verified to still work and a later real ``import torch`` to
+ succeed after the shield (the VAD path). This relies on the wake-model load
+ being serialized before the VAD/TTS loads (pipeline ``_warmup_deferred_loaders``
+ pre-warms the wake model first and alone) so there is no concurrent real
+ torch import racing the stub.
+ """
+ saved: list[str] = []
+ for name in ("transformers", "torch"):
+ if name not in sys.modules:
+ sys.modules[name] = None # type: ignore[assignment]
+ saved.append(name)
+ try:
+ yield
+ finally:
+ for name in saved:
+ # Remove ONLY our stub; if real code imported it meanwhile, keep it.
+ if sys.modules.get(name) is None:
+ sys.modules.pop(name, None)
+
+
def _normalize_model_name(model: str) -> str:
"""Map known-invalid OpenAI-style aliases to faster-whisper model ids.
@@ -37,6 +86,47 @@ def _normalize_model_name(model: str) -> str:
return model
+# Known faster-whisper checkpoints that can ONLY transcribe English. The whole
+# Distil-Whisper family is English-only by design, and any plain Whisper size
+# carrying the ``.en`` suffix is the English-only variant. Fed German/Spanish
+# audio they do not error — they phonetically mangle it into English words
+# ("Kannst du mir bitte" -> "Can't you me please"), which is far worse than an
+# honest failure because the garbage flows straight to the brain.
+_ENGLISH_ONLY_MODELS = frozenset(
+ {
+ "distil-large-v3",
+ "distil-large-v3.5",
+ "distil-large-v2",
+ "distil-medium.en",
+ "distil-small.en",
+ }
+)
+
+
+def _multilingual_equivalent(model: str) -> str | None:
+ """Return a multilingual replacement when ``model`` is English-only, else None.
+
+ Used by the constructor guard so a bilingual / auto-detect / German / Spanish
+ user is never silently stuck on an English-only model. HuggingFace repo ids
+ (containing ``/``) are opaque — we cannot reason about their language coverage,
+ so they are left untouched.
+
+ Mapping:
+ * a plain ``<size>.en`` model -> the same size without the suffix
+ (``base.en`` -> ``base``), which is the multilingual variant at the same
+ speed/accuracy tier;
+ * any Distil-Whisper model (all English-only, no multilingual distil exists)
+ -> ``large-v3-turbo``, the fast multilingual checkpoint.
+ """
+ if "/" in model:
+ return None
+ if model.endswith(".en") and not model.startswith("distil-"):
+ return model[: -len(".en")]
+ if model in _ENGLISH_ONLY_MODELS or model.startswith("distil-"):
+ return "large-v3-turbo"
+ return None
+
+
def _cpu_safe_compute_type(compute_type: str) -> str:
"""Downgrade CUDA-only compute types to a CPU-compatible one.
@@ -53,9 +143,12 @@ def _new_whisper_model(model_name: str, device: str, compute_type: str) -> Any:
The heavy ``faster_whisper`` import stays lazy here so importing this module
on a host without it is cheap; tests monkeypatch this function to avoid the
- import + a real model build.
+ import + a real model build. The import shield skips ctranslate2's
+ transformers+torch converter stack (inference doesn't need it) — see
+ :func:`inference_only_import_shield`.
"""
- from faster_whisper import WhisperModel
+ with inference_only_import_shield():
+ from faster_whisper import WhisperModel
return WhisperModel(model_name, device=device, compute_type=compute_type)
@@ -83,11 +176,40 @@ class FasterWhisperProvider:
self._device = device
self._compute_type = compute_type
self._language = language if language and language != "auto" else None
+ # Defense-in-depth (forensic 2026-06-28): an English-only model fed
+ # non-English audio mangles it into English words. Unless the user has
+ # DELIBERATELY pinned English (``self._language == "en"``), swap an
+ # English-only checkpoint for a multilingual one so auto-detect / a de/es
+ # pin actually transcribes the spoken language. A "en" pin keeps the fast
+ # English-only model. The swap covers every construction path (config
+ # factory, bare default, wake builder, CLI) in one place.
+ if self._language != "en":
+ multilingual = _multilingual_equivalent(self._model_name)
+ if multilingual is not None and multilingual != self._model_name:
+ log.warning(
+ "STT model %r is English-only but the recognition language is "
+ "%r — using multilingual %r instead so non-English speech is "
+ "not mangled into English.",
+ self._model_name,
+ self._language or "auto",
+ multilingual,
+ )
+ self._model_name = multilingual
self._beam_size = beam_size
self._vad_filter = vad_filter
self._initial_prompt = initial_prompt
self._no_speech_threshold = no_speech_threshold
self._model: Any = None # lazy
+ # Serialize the actual ctranslate2 inference. ``transcribe_pcm`` runs
+ # ``model.transcribe`` in a worker thread (asyncio.to_thread), and the
+ # SAME provider instance is shared by the rolling-whisper wake poll loop
+ # AND the VAD "listening bubble" probe (``_probe_stt = _stt`` for a custom
+ # wake phrase). ctranslate2's ``WhisperModel`` is NOT thread-safe for
+ # concurrent ``transcribe`` on one model object — two overlapping calls
+ # hang (the 12-minute custom-wake "Hey Nico" silent wedge, forensic
+ # 2026-06-29) or return garbage. This lock makes the model call mutually
+ # exclusive per instance so the two callers serialize instead of racing.
+ self._infer_lock = threading.Lock()
def _ensure_model(self) -> None:
if self._model is not None:
@@ -111,6 +233,61 @@ class FasterWhisperProvider:
)
self._model = _new_whisper_model(model_name, fb_device, fb_ct)
+ def recover(self) -> None:
+ """Self-heal a WEDGED inference engine without an app restart.
+
+ ctranslate2's ``transcribe`` can hang unrecoverably (the concurrent-call
+ corruption this provider's lock now prevents, but a model already wedged
+ before the fix — or any future driver/resource hiccup — stays hung). The
+ worker thread running it cannot be cancelled, so the ONLY way back is a
+ fresh model object. Drop the (possibly hung) model AND its lock: the next
+ ``transcribe_pcm`` rebuilds a clean model under a clean lock, while any
+ thread still stuck in the old ``model.transcribe`` keeps the OLD object +
+ OLD lock alive (orphaned — it never blocks the fresh path, and is freed
+ if/when it ever returns). Called by the wake loop after a run of
+ consecutive transcribe time-outs (the wedge signature). Cheap + instant:
+ it only clears references; the ~load happens lazily on the next call."""
+ log.warning(
+ "FasterWhisperProvider.recover(): dropping a wedged model + lock so "
+ "the next transcription rebuilds a fresh engine (self-heal)."
+ )
+ self._model = None
+ self._infer_lock = threading.Lock()
+
+ def warm_up(self) -> None:
+ """Prime the engine with one throwaway inference so the FIRST live
+ transcription isn't cold.
+
+ ``_ensure_model`` only constructs the ``WhisperModel`` (weights into
+ VRAM). On a faster-whisper / CTranslate2 CUDA backend the FIRST actual
+ ``model.transcribe`` pays a one-off cost — CUDA kernel selection/JIT,
+ cuDNN algo search, memory-pool setup — of several seconds; steady state
+ is ~100 ms. For the rolling-window custom-phrase wake (this provider IS
+ the wake model) that cold inference lands on the user's first
+ "Hey Jarvis": the wake loop blocks on it long enough that the wake audio
+ rolls out of the rolling buffer before the transcript returns, so the
+ first wake is missed and the user has to repeat it (forensic 2026-06-28).
+ Running one inference here, before the model goes live, moves that cost
+ off the wake path.
+
+ Synchronous (call it via ``asyncio.to_thread`` off the event loop, like
+ ``_ensure_model``). Idempotent — a second call reuses the loaded model.
+ Best-effort: a warm-up failure is swallowed (the model still lazy-works
+ on the first real transcribe), so priming never breaks boot.
+ """
+ self._ensure_model()
+ try:
+ # ~1 s of very low-amplitude noise: enough signal to exercise the
+ # full encoder + decoder/beam kernels (pure zeros can early-exit on
+ # no-speech and leave the decode path cold). Harmless content — a
+ # random mis-hear can never match the strict wake matcher, and this
+ # transcript is discarded.
+ rng = np.random.default_rng(0)
+ warm_audio = rng.standard_normal(16_000).astype(np.float32) * 0.001
+ self._transcribe_sync(warm_audio, 16_000)
+ except Exception as exc: # noqa: BLE001 — priming is best-effort
+ log.debug("Whisper warm-up inference skipped: %s", exc)
+
async def transcribe(self, audio: AsyncIterator[AudioChunk]) -> Transcript:
"""Sammelt alle Chunks, transkribiert am Stück.
@@ -156,7 +333,6 @@ class FasterWhisperProvider:
self, audio_np: np.ndarray, sample_rate: int,
language: str | None = None,
) -> Transcript:
- assert self._model is not None
# faster-whisper akzeptiert np.ndarray float32 direkt wenn 16 kHz
if sample_rate != 16_000:
# Resample wäre hier nötig — wir erwarten aber 16 kHz von Capture
@@ -165,17 +341,37 @@ class FasterWhisperProvider:
# Per-Call-Override hat Vorrang vor self._language
effective_lang = language if language is not None else self._language
- segments_iter, info = self._model.transcribe(
- audio_np,
- language=effective_lang,
- beam_size=self._beam_size,
- vad_filter=self._vad_filter,
- condition_on_previous_text=False,
- initial_prompt=self._initial_prompt,
- no_speech_threshold=self._no_speech_threshold,
- )
- # segments_iter ist generator — durchiterieren materialisiert
- segments = list(segments_iter)
+ # NON-BLOCKING acquire across BOTH the transcribe() call and the lazy
+ # generator materialization (``list(segments_iter)`` runs the actual
+ # ctranslate2 decode). The SAME instance is shared by the rolling-whisper
+ # wake poll loop AND the VAD "listening bubble" probe; ctranslate2 is not
+ # thread-safe for concurrent transcribe on one model. A *blocking* lock
+ # would let a HUNG call (the 2-hour "Hey Nico" wedge, forensic 2026-06-29:
+ # every transcribe timed out at 8 s forever) pile every later call up
+ # behind it. Non-blocking instead: if a call is already in flight, skip
+ # (raise ``TranscribeBusy``) so the caller re-polls; a run of these is the
+ # wedge signal that drives ``recover()``. Capture the lock locally so a
+ # concurrent ``recover()`` swapping in a fresh lock still releases THIS one.
+ lock = self._infer_lock
+ if not lock.acquire(blocking=False):
+ raise TranscribeBusy("a transcription is already in flight on this model")
+ try:
+ self._ensure_model() # rebuild a fresh model if recover() cleared it
+ model = self._model
+ assert model is not None
+ segments_iter, info = model.transcribe(
+ audio_np,
+ language=effective_lang,
+ beam_size=self._beam_size,
+ vad_filter=self._vad_filter,
+ condition_on_previous_text=False,
+ initial_prompt=self._initial_prompt,
+ no_speech_threshold=self._no_speech_threshold,
+ )
+ # segments_iter ist generator — durchiterieren materialisiert
+ segments = list(segments_iter)
+ finally:
+ lock.release()
text = "".join(s.text for s in segments).strip()
# Segment-Tuples als Meta für Debugging/Flight-Recorder
diff --git a/jarvis/plugins/wake/openwakeword_provider.py b/jarvis/plugins/wake/openwakeword_provider.py
index c1fa398918..915e2027b6 100644
--- a/jarvis/plugins/wake/openwakeword_provider.py
+++ b/jarvis/plugins/wake/openwakeword_provider.py
@@ -15,6 +15,7 @@ from __future__ import annotations
import asyncio
import logging
import time
+from collections import deque
from collections.abc import AsyncIterator
import numpy as np
@@ -34,6 +35,14 @@ OWW_FRAME_SAMPLES = 1280 # openWakeWord erwartet genau diese Frame-Länge
# busy-loop of STT calls. See ``note_rejected_candidate``.
_REJECT_REFRACTORY_S = 0.8
+# How often the always-on detector emits a cumulative-counter heartbeat at INFO
+# (activation attempts, suppression reasons, loudest confidence this session).
+# This is the user-facing "why didn't my wake word fire?" instrument: a live
+# log line like "frames=… max_score=0.12 … triggers=0 (threshold 0.15)" shows
+# at a glance that audio IS arriving and being scored, just below the bar — and
+# a frames-stuck-at-N line makes a genuinely dead detector obvious.
+_STATS_LOG_INTERVAL_S = 10.0
+
# Production wake threshold for this project's quiet-mic hardware, wired by
# jarvis/ui/desktop_app.py. Empirically derived from the 2026-05-24 idle-
# telemetry log (data/jarvis_desktop.log): ambient speech and bare "Hallo"
@@ -52,6 +61,90 @@ _REJECT_REFRACTORY_S = 0.8
PRODUCTION_WAKE_THRESHOLD = 0.15
+# Threshold + hysteresis strategy (single, documented contract):
+# * FIRE bar — a frame scores >= ``activation_threshold`` (default
+# ``PRODUCTION_WAKE_THRESHOLD``). ``WakeGainNormalizer`` lifts a quiet wake
+# into this band so a normal-volume utterance crosses it without shouting.
+# * DEBOUNCE — after a real trigger the detector stays quiet for ``cooldown_s``
+# so ONE spoken wake word yields exactly once (no machine-gun re-fire).
+# * REJECT REFRACTORY — when the pipeline's STT prefix-verify rejects a
+# candidate (``note_rejected_candidate``), the long debounce is cut to a
+# short ``_REJECT_REFRACTORY_S`` so a genuine wake spoken right after a false
+# positive still gets through, while continuous jarvis-like background audio
+# cannot spin a reject->retrigger busy-loop.
+# There is no separate "release" threshold: the cooldown IS the hysteresis that
+# keeps a sustained near-threshold score from chattering, and the BUG-009 floor
+# (>= 0.10, pinned by tests/unit/speech/test_wake_threshold.py) keeps the FIRE
+# bar above the ambient false-fire band.
+
+
+class WakeGainNormalizer:
+ """Amplify-only, noise-gated, capped streaming AGC for the OWW wake path.
+
+ Root cause of "the wake word only triggers when I shout" (2026-06-28): in the
+ default lightweight config the fast openWakeWord detector is the SOLE wake
+ path (the ``RollingWhisperWake`` low-volume backstop is a power-user opt-in
+ behind ``cfg.trigger.heavy_local_whisper``), and it fed RAW int16 frames into
+ the neural model. openWakeWord's activation score scales with input level, so
+ on this project's documented quiet-mic hardware (normal-speech rms ~0.01-0.02)
+ a genuine "Hey Jarvis" peaks at ~0.10-0.14 — just *below* the pinned 0.15
+ threshold. Only shouting lifted the level over the bar.
+
+ The threshold cannot move (``test_wake_threshold`` pins the BUG-009 floor), so
+ this brings the SAME peak normalization the ``RollingWhisperWake`` backstop
+ already uses to the default OWW path. Per-frame behaviour:
+
+ * the gain is derived from a rolling peak over the last ``window_s`` of audio
+ (not the single frame) so it stays stable across the wake phrase and the
+ intra-phrase envelope the model relies on is preserved;
+ * it is AMPLIFY-ONLY — an already-loud wake is never turned down, so the
+ genuine-peak band the threshold was calibrated on never regresses;
+ * it is gated by ``noise_floor_peak`` — digital silence / idle hiss below the
+ floor is returned UNCHANGED so the AGC can never manufacture an ambient
+ false-fire band (the AGC-level analogue of the BUG-009 guard);
+ * the gain is capped at ``max_gain_db`` so a near-silent floor cannot be blown
+ up to full scale.
+
+ Pure mechanism — no I/O, no model. ``reset()`` clears the rolling envelope so
+ a stale loud burst does not suppress the gain on the next quiet utterance.
+ """
+
+ def __init__(
+ self,
+ target_peak_dbfs: float = -3.0,
+ max_gain_db: float = 20.0,
+ noise_floor_peak: float = 0.02,
+ window_s: float = 1.5,
+ sample_rate: int = OWW_SAMPLE_RATE,
+ frame_samples: int = OWW_FRAME_SAMPLES,
+ ) -> None:
+ self._target_peak = float(10.0 ** (target_peak_dbfs / 20.0)) # -3 dBFS ≈ 0.707
+ self._max_gain = float(10.0 ** (max_gain_db / 20.0)) # 20 dB = 10x
+ self._noise_floor = float(noise_floor_peak)
+ frame_s = frame_samples / sample_rate # 80 ms
+ self._window_frames = max(1, int(round(window_s / frame_s)))
+ self._recent_peaks: deque[float] = deque(maxlen=self._window_frames)
+
+ def reset(self) -> None:
+ """Forget the rolling envelope (called on detector stop / re-arm)."""
+ self._recent_peaks.clear()
+
+ def process(self, frame: np.ndarray) -> np.ndarray:
+ """Return ``frame`` (int16) amplified toward the target peak, or
+ unchanged when below the noise floor / already loud enough."""
+ f32 = frame.astype(np.float32) / 32768.0
+ frame_peak = float(np.max(np.abs(f32))) if f32.size else 0.0
+ self._recent_peaks.append(frame_peak)
+ rolling_peak = max(self._recent_peaks) if self._recent_peaks else frame_peak
+ if rolling_peak < self._noise_floor:
+ return frame # silence / sub-floor hiss — leave it alone (gain 1.0)
+ gain = min(self._target_peak / rolling_peak, self._max_gain)
+ if gain <= 1.0:
+ return frame # already loud enough — amplify-only, never attenuate
+ boosted = np.clip(f32 * gain, -1.0, 1.0)
+ return (boosted * 32767.0).astype(np.int16)
+
+
class OpenWakeWordProvider:
"""Wake-Word-Detector — strukturell `WakeWordProvider`-kompatibel.
@@ -66,9 +159,14 @@ class OpenWakeWordProvider:
def __init__(
self,
keywords: tuple[str, ...] = ("hey_jarvis",),
+ # The FIRE bar. Defaults to the documented, data-driven
+ # PRODUCTION_WAKE_THRESHOLD so omitting it gives the SAME behaviour the
+ # desktop app wires explicitly — one consistent threshold, not a quieter
+ # ad-hoc 0.10 that drifts the detector into the ambient false-fire band.
# BUG-009: real-mic peaks for "Hey Jarvis" land at 0.10–0.20 on this
- # hardware, not the textbook 0.35-0.65.
- activation_threshold: float = 0.10,
+ # hardware (not the textbook 0.35-0.65); WakeGainNormalizer lifts a quiet
+ # wake into that band. The 0.10 floor is pinned by test_wake_threshold.
+ activation_threshold: float = PRODUCTION_WAKE_THRESHOLD,
cooldown_s: float = 2.0,
inference_framework: str = "onnx",
# Diagnose-Log: alles >= diesem Wert loggen. 0.05 ist bewusst niedrig,
@@ -81,6 +179,15 @@ class OpenWakeWordProvider:
# The shared melspec/embedding backbones are still reused from the
# in-repo bundle so any model loads offline. None = bundled hey_jarvis.
model_path: str | None = None,
+ # Volume-robust wake (root cause of "only triggers when shouted",
+ # 2026-06-28): openWakeWord's score is amplitude-dependent, so on a quiet
+ # mic a normal-volume "Hey Jarvis" under-scores against the threshold and
+ # only a shouted utterance crosses it. When ``gain_normalization`` is True
+ # (default) each frame is routed through ``WakeGainNormalizer`` — an
+ # amplify-only, noise-gated, capped streaming AGC — BEFORE
+ # ``model.predict()`` so the score reflects the wake *pattern*, not the
+ # volume. Set False to restore the legacy raw-PCM behaviour (escape hatch).
+ gain_normalization: bool = True,
) -> None:
self._keywords = keywords
self._threshold = activation_threshold
@@ -91,6 +198,70 @@ class OpenWakeWordProvider:
self._model = None # lazy
self._last_trigger_ns: int = 0
self._residual = np.empty(0, dtype=np.int16)
+ # Volume-robust wake: lift quiet input toward a target peak before
+ # scoring (None = escape hatch, raw PCM straight to the model).
+ self._gain = WakeGainNormalizer() if gain_normalization else None
+ # Per-session debug counters (reset on each detect() entry). They make
+ # "the wake word never fires / sometimes stops entirely" diagnosable:
+ # the user can see frames ARE arriving and being scored, how loud the
+ # loudest was, and exactly why each near-hit was dropped (below the FIRE
+ # bar vs swallowed by the cooldown debounce). Exposed via ``stats()``.
+ self._frames_seen = 0
+ self._max_score = 0.0
+ self._last_score = 0.0
+ self._attempts_above_threshold = 0
+ self._suppressed_below_threshold = 0
+ self._suppressed_cooldown = 0
+ self._triggers = 0
+ self._stats_window_start_ns = 0
+
+ def _reset_session_stats(self) -> None:
+ """Zero the per-session counters and re-arm the heartbeat window."""
+ self._frames_seen = 0
+ self._max_score = 0.0
+ self._last_score = 0.0
+ self._attempts_above_threshold = 0
+ self._suppressed_below_threshold = 0
+ self._suppressed_cooldown = 0
+ self._triggers = 0
+ self._stats_window_start_ns = time.time_ns()
+
+ def stats(self) -> dict[str, float]:
+ """Snapshot of the current listen session's activation counters.
+
+ Keys: ``frames_seen``, ``max_score``, ``last_score``,
+ ``attempts_above_threshold``, ``suppressed_below_threshold``,
+ ``suppressed_cooldown``, ``triggers``, ``threshold``. Consumed by the
+ heartbeat log and the wake diagnostics surface.
+ """
+ return {
+ "frames_seen": self._frames_seen,
+ "max_score": self._max_score,
+ "last_score": self._last_score,
+ "attempts_above_threshold": self._attempts_above_threshold,
+ "suppressed_below_threshold": self._suppressed_below_threshold,
+ "suppressed_cooldown": self._suppressed_cooldown,
+ "triggers": self._triggers,
+ "threshold": self._threshold,
+ }
+
+ def _maybe_log_stats_heartbeat(self) -> None:
+ """Emit the cumulative counter snapshot at INFO every interval."""
+ now_ns = time.time_ns()
+ if now_ns - self._stats_window_start_ns < _STATS_LOG_INTERVAL_S * 1e9:
+ return
+ log.info(
+ "wake stats: frames=%d max_score=%.3f attempts>=thr=%d "
+ "suppressed[below_thr=%d cooldown=%d] triggers=%d (threshold %.2f)",
+ self._frames_seen,
+ self._max_score,
+ self._attempts_above_threshold,
+ self._suppressed_below_threshold,
+ self._suppressed_cooldown,
+ self._triggers,
+ self._threshold,
+ )
+ self._stats_window_start_ns = now_ns
def _model_kwargs(self) -> dict:
"""Build the openWakeWord ``Model(...)`` kwargs.
@@ -162,6 +333,8 @@ class OpenWakeWordProvider:
async def stop(self) -> None:
self._model = None
self._residual = np.empty(0, dtype=np.int16)
+ if self._gain is not None:
+ self._gain.reset()
def _cooldown_ok(self, now_ns: int) -> bool:
"""True if the debounce window since the last yielded trigger elapsed.
@@ -197,6 +370,18 @@ class OpenWakeWordProvider:
self._ensure_model()
assert self._model is not None
+ # Per-session reset (the "no dead state blocks waking" guard): start each
+ # listen from clean audio + counter state so a stale loud gain envelope
+ # or leftover residual from the PREVIOUS interaction can never
+ # under-amplify (and thus silently swallow) the next quiet wake. The
+ # debounce stamp (_last_trigger_ns) is deliberately NOT reset — the
+ # cooldown must persist across re-arm so a just-fired wake does not
+ # immediately re-fire.
+ self._residual = np.empty(0, dtype=np.int16)
+ if self._gain is not None:
+ self._gain.reset()
+ self._reset_session_stats()
+
async for chunk in chunks:
# Int16-View auf die Bytes — openWakeWord erwartet int16 arrays
int16 = np.frombuffer(chunk.pcm, dtype=np.int16)
@@ -211,8 +396,17 @@ class OpenWakeWordProvider:
self._residual = buf[n_full * OWW_FRAME_SAMPLES:]
for frame in frames:
+ # Volume-robust wake: lift a quiet frame toward the target peak
+ # so a normal-volume "Hey Jarvis" reaches the score band the
+ # threshold expects (no shouting). Amplify-only + noise-floor gated.
+ norm_frame = self._gain.process(frame) if self._gain is not None else frame
# predict() gibt dict zurück: {"hey_jarvis": score_float, ...}
- scores = await asyncio.to_thread(self._model.predict, frame)
+ scores = await asyncio.to_thread(self._model.predict, norm_frame)
+ self._frames_seen += 1
+ frame_max = max(scores.values()) if scores else 0.0
+ self._last_score = frame_max
+ if frame_max > self._max_score:
+ self._max_score = frame_max
for keyword, score in scores.items():
# Live-Debugging: alles über `score_log_threshold` loggen,
# damit der User beim Testen sieht wie nah er am Hit dran ist.
@@ -220,12 +414,31 @@ class OpenWakeWordProvider:
log.info("wake score %s = %.3f (threshold %.2f)",
keyword, score, self._threshold)
if score < self._threshold:
+ self._suppressed_below_threshold += 1
continue
+ # Cleared the FIRE bar — record the attempt before the
+ # debounce decides whether it actually yields.
+ self._attempts_above_threshold += 1
now_ns = time.time_ns()
if not self._cooldown_ok(now_ns):
+ self._suppressed_cooldown += 1
+ log.info(
+ "wake suppressed: cooldown — %s score=%.3f >= %.2f "
+ "(%.1fs since last trigger, need %.1fs)",
+ keyword, score, self._threshold,
+ (now_ns - self._last_trigger_ns) / 1e9,
+ self._cooldown_s,
+ )
continue
self._last_trigger_ns = now_ns
+ self._triggers += 1
+ log.info(
+ "wake ACCEPTED: %s score=%.3f >= threshold %.2f",
+ keyword, score, self._threshold,
+ )
yield self._canonical_keyword(keyword)
+ break # one yield per frame (multi-keyword models)
+ self._maybe_log_stats_heartbeat()
async def stream(self) -> AsyncIterator[float]:
"""Protocol-Pflicht: Confidence-Stream. Nicht die primäre API hier."""
diff --git a/jarvis/speech/pipeline.py b/jarvis/speech/pipeline.py
index 07605b55ef..bc612664a1 100644
--- a/jarvis/speech/pipeline.py
+++ b/jarvis/speech/pipeline.py
@@ -60,6 +60,7 @@ from jarvis.core.events import (
VoiceMuteToggleRequested,
VoiceSessionEnded,
VoiceSessionStarted,
+ WakeCandidateDetected,
WakeWordDetected,
)
from jarvis.core.protocols import AudioChunk, Transcript
@@ -70,7 +71,10 @@ from jarvis.core.turn_language import (
)
from jarvis.plugins.stt.fwhisper import FasterWhisperProvider
from jarvis.plugins.tts.gemini_flash_tts import GEMINI_TTS_SAMPLE_RATE, GeminiFlashTTS
-from jarvis.plugins.wake.openwakeword_provider import OpenWakeWordProvider
+from jarvis.plugins.wake.openwakeword_provider import (
+ PRODUCTION_WAKE_THRESHOLD,
+ OpenWakeWordProvider,
+)
from jarvis.sessions.constants import (
HANGUP_ERROR,
HANGUP_HOTKEY,
@@ -1579,18 +1583,40 @@ class SpeechPipeline:
self._whisper_wake._pattern = self._wake_matcher # noqa: SLF001
self._whisper_wake_enabled = False
else: # stt_match — arbitrary phrase via local-Whisper transcript match
- self._openwakeword_enabled = False
if self._stt is not None:
+ self._openwakeword_enabled = False
self._whisper_wake = RollingWhisperWake(
self._stt, pattern=self._wake_matcher
)
self._whisper_wake_enabled = True
else:
- # No local Whisper available: cannot detect an arbitrary phrase.
+ # No local Whisper could be built: rather than disable BOTH
+ # detectors — a SILENT DEAD LISTENER that only an app restart
+ # could recover ("Hey/Neko sometimes stops waking entirely") —
+ # fall back to the bundled hey_rhasspy OWW model so the wake path
+ # stays ALIVE. The user keeps a working wake word (the neutral
+ # offline phrase "Hey Rhasspy") instead of a dead custom one, and
+ # a later set_wake_plan with a buildable Whisper re-arms the
+ # custom phrase. AP-22 + the mission's "no dead state blocks
+ # waking": a missing capability must degrade, never brick.
+ from jarvis.speech.wake_constants import resolve_oww_model_path
+
+ rhasspy_path = resolve_oww_model_path("hey_rhasspy")
+ self._wake = OpenWakeWordProvider(
+ keywords=("hey_rhasspy",),
+ activation_threshold=getattr(
+ plan, "threshold", PRODUCTION_WAKE_THRESHOLD
+ ),
+ model_path=rhasspy_path,
+ )
+ self._openwakeword_enabled = True
self._whisper_wake_enabled = False
log.warning(
- "Wake-Live-Switch: stt_match requested but no local Whisper; "
- "wake detection is now inactive until restart."
+ "Wake-Live-Switch: stt_match requested but no local Whisper "
+ "could be built — degrading to the bundled 'Hey Rhasspy' "
+ "offline model so the wake stays alive (say 'Hey Rhasspy'). "
+ "Install the [desktop] extra or supply a custom .onnx to use "
+ "the custom phrase."
)
log.info(
@@ -2133,11 +2159,17 @@ class SpeechPipeline:
"ENABLED" if new_value else "disabled",
event.source or "unknown",
)
- if new_value:
- try:
- self._player.stop()
- except Exception: # noqa: BLE001
- log.debug("player.stop on mute swallowed", exc_info=True)
+ # Mute is INPUT-ONLY (maintainer intent 2026-06-29: "mute my mic FOR
+ # Jarvis, do NOT mute Jarvis — other things keep working"). We deliberately
+ # do NOT call self._player.stop() here: that ran Pa_AbortStream
+ # (stream.abort) mid-TTS-write, which (a) contradicted the input-only
+ # intent and (b) wedged the shared WASAPI device — the next wake-mic then
+ # opened "successfully" but delivered only dead/silent frames (no
+ # rolling-whisper, no 3 s Mic-Stall fire), so "Hey <wake>" silently
+ # stopped working after a mute-during-speech + hangup. Jarvis finishes the
+ # current sentence; new _speak() calls are still suppressed while muted,
+ # and the user's input frames are dropped at our boundary — the OS mic is
+ # untouched. Forensic: data/jarvis_desktop.log 2026-06-29 14:09–14:12.
if self._bus is None:
return
try:
@@ -3220,8 +3252,10 @@ class SpeechPipeline:
"""Publish a VoiceBootStatus on the bus (guarded — never breaks boot).
``ready=False`` is emitted at the very start of warm-up; ``ready=True``
- the moment the critical listening path (Phase A) is live, *before* the
- background confirmation-audio render finishes.
+ only once ALL deferred loaders (wake model + VAD + TTS client) have
+ completed, from ``_warmup_deferred_loaders`` — the first honest moment
+ the user can both be heard AND get a spoken reply. (It runs after Phase A
+ has returned, so the wake loop is already listening by then.)
"""
if self._bus is None:
return
@@ -3233,10 +3267,12 @@ class SpeechPipeline:
async def _cancel_warmup_background(self) -> None:
"""Cancel + await the fire-and-forget warm-up tasks on shutdown.
- Two background tasks run off the wake-critical path: Phase B (the ACK +
- task-ack confirmation-audio pre-render) and the deferred VAD/STT/TTS
- loaders. When ``run()`` is cancelled (the normal desktop-shutdown path)
- both must be cancelled and awaited, otherwise they are orphaned: under
+ Three background tasks run off the wake-critical path: Phase B (the ACK +
+ task-ack confirmation-audio pre-render), the deferred wake/VAD/TTS
+ loaders (``_warmup_deferred_loaders``), and the boot-ready audio cue
+ (``_warmup_ready_cue_task``, created at the end of the deferred loaders).
+ When ``run()`` is cancelled (the normal desktop-shutdown path) all must
+ be cancelled and awaited, otherwise they are orphaned: under
``pythonw.exe`` there is no stderr to surface the "Task exception was
never retrieved" warning, and a late TTS render could write stale PCM
into ``_ack_pcm`` / ``_task_ack_pcm`` after a live TTS-provider switch
@@ -3262,26 +3298,32 @@ class SpeechPipeline:
log.info("Warm-up: Whisper / Silero / Wake-Word / TTS …")
await self._emit_boot_status(ready=False, detail="warmup_start")
- # --- Phase A: the critical listening path -------------------------
- # Audio-device stabilization, VAD + OpenWakeWord loads and the TTS
- # client init are mutually independent (each touches only its own
- # object), so they run concurrently instead of one-after-another. When
- # this finishes, voice is genuinely ready to hear "Hey Jarvis".
+ # --- Phase A: start the wake LOOP, nothing else -------------------
+ # Phase A blocks on the absolute minimum so the wake loop is listening
+ # fast: the audio-device table settling (BUG-014 guard) and the wake
+ # start. The heavy VAD / STT / TTS loads are deliberately NOT here — they
+ # move to the background ``_warmup_deferred_loaders`` so they never gate
+ # wake-loop start. NOTE: a started wake loop is NOT the same as "ready to
+ # converse"; honest readiness (incl. TTS) is signalled later, from the
+ # deferred loaders (see below).
phase_a_start = time.monotonic()
await self._warmup_phase_a()
phase_a_ms = (time.monotonic() - phase_a_start) * 1000.0
log.info("Warm-up Phase A (critical listening path) done in %.0f ms.", phase_a_ms)
- await self._emit_boot_status(ready=True, detail="phase_a_done")
-
- # Audible "ready" cue: tells the user exactly when listening starts
- # after a (cold) boot. It is intentionally fire-and-forget: a slow or
- # wedged output device must not sit between ready=True and the wake loop.
- self._warmup_ready_cue_task = asyncio.create_task(
- self._play_ready_cue(), name="warmup-ready-cue"
- )
- self._warmup_ready_cue_task.add_done_callback(
- self._log_warmup_ready_cue_done
- )
+ # Honest readiness (2026-06-29): Phase A only starts the wake LOOP — it
+ # does NOT mean the user can hold a conversation yet (VAD + TTS, and the
+ # custom-wake Whisper model, are still loading in
+ # _warmup_deferred_loaders below). Readiness is therefore NOT signalled
+ # here. BOTH the VoiceBootStatus(ready=True) and the audible "you can
+ # speak" cue now fire at the END of _warmup_deferred_loaders — the first
+ # moment wake (model) + VAD + TTS are ALL genuinely up. Previously the
+ # openWakeWord path flipped ready in Phase A and the custom-phrase path
+ # flipped it right after the wake model alone — either way the UI said
+ # "ready" while TTS was still loading, so the user spoke and nothing came
+ # back ("it says ready but I can't talk"). ready=False was already
+ # emitted at warmup_start above, so the UI stays in its honest
+ # "starting up / preparing to listen" state until the deferred loaders
+ # complete.
# --- Phase B: confirmation audio, off the critical path -----------
# Pre-rendering the ACK + ~20 task-ack phrases used to dominate warm-up
@@ -3356,46 +3398,110 @@ class SpeechPipeline:
)
async def _warmup_deferred_loaders(self) -> None:
- """Background pre-load of VAD + STT + TTS client — never gates wake
- readiness (see ``_warmup_phase_a``).
-
- VAD is the soonest thing needed after a wake (utterance endpointing), so
- it is loaded first; the local-Whisper STT (if any) and the TTS client
- follow. Each load is isolated (``return_exceptions=True``) so one
- slow/failing load never breaks the others, and every object's
- ``_ensure_*`` is idempotent — a concurrent lazy load on first use is a
- harmless no-op once this has run.
+ """Background pre-load of the FULL conversational stack (wake model +
+ VAD + TTS), then signal HONEST readiness.
+
+ Runs OFF the wake-critical path (see ``_warmup_phase_a``): the wake loop
+ is already listening by the time this starts, so a wake mid-load just
+ triggers a one-off lazy load on the VAD/STT/TTS object. What this owns is
+ the *honest* readiness signal — ``VoiceBootStatus(ready=True)`` and the
+ audible "you can speak" cue fire ONLY at the very end, once wake (model),
+ VAD endpointing AND the TTS reply path are all initialized. Flipping
+ ready before TTS was up was the "it says ready but I can't talk" bug
+ (2026-06-29).
+
+ Ordering / GIL: the wake-model load is the one heavy CUDA/GIL step, kept
+ FIRST and ALONE (racing it against the VAD load serialized both on the
+ import + CUDA-init lock to ~11.8 s — forensic 2026-06-22). The TTS client
+ init is network-bound (releases the GIL on I/O), so it is kicked off
+ CONCURRENTLY with the wake warm-up to overlap its latency instead of
+ paying it sequentially afterwards. VAD loads after the wake model. Every
+ load is guarded so one slow/failing load never strands readiness — it
+ will lazy-load / fall back on first use.
"""
- async def _load_vad() -> None:
- await asyncio.to_thread(self._vad._ensure_model)
-
- async def _load_stt() -> None:
- # Lightweight path has no local Whisper to pre-load.
- if self._stt is not None:
- await asyncio.to_thread(self._stt._ensure_model)
+ deferred_t0 = time.monotonic()
+ # TTS client init is network-bound → overlap it with the (CUDA-heavy)
+ # wake warm-up rather than adding it on afterwards. Idempotent: a later
+ # lazy ``_ensure_client`` on first synth is a harmless no-op.
async def _init_tts() -> None:
await asyncio.to_thread(self._tts._ensure_client)
- timings, results = await _gather_timed(
- [
- ("vad-load", _load_vad),
- ("stt-load", _load_stt),
- ("tts-init", _init_tts),
- ]
- )
- log.info(
- "Warm-up deferred loaders (ms): %s",
- ", ".join(
- f"{name}={timings[name]:.0f}"
- for name in sorted(timings, key=lambda n: -timings[n])
- ),
- )
- for name, res in zip(
- ("vad-load", "stt-load", "tts-init"), results, strict=True
- ):
- if isinstance(res, Exception):
- log.warning("Warm-up deferred loader '%s' failed: %s", name, res)
+ tts_task = asyncio.create_task(_init_tts(), name="warmup-tts-init")
+ try:
+ # PRIORITY: pre-warm the WAKE model FIRST and ALONE. For a custom wake
+ # phrase (stt_match / rolling-whisper) ``self._stt`` IS the wake model,
+ # and until it is in memory + warmed the wake loop cannot transcribe.
+ # Prime with one REAL inference (not just the model load): the first
+ # transcribe is cold (CUDA kernel JIT / cuDNN algo search), and that
+ # cost used to land on the user's first "Hey Jarvis" (swallowed wake,
+ # forensic 2026-06-28). ``warm_up`` pays it here; falls back to
+ # ``_ensure_model``.
+ if self._stt is not None:
+ _wake_t0 = time.monotonic()
+ try:
+ _prime = getattr(self._stt, "warm_up", None)
+ await asyncio.to_thread(
+ _prime if callable(_prime) else self._stt._ensure_model
+ )
+ log.info(
+ "Wake-model pre-warm done in %.0f ms (priority, no GIL race).",
+ (time.monotonic() - _wake_t0) * 1000.0,
+ )
+ except Exception as exc: # noqa: BLE001 — lazy load on first use still works
+ log.warning("Wake-model pre-warm failed (will lazy-load): %s", exc)
+
+ # VAD after the wake model (both touch heavy C-extensions; serialize
+ # to dodge the import/CUDA-init lock contention measured above).
+ _vad_t0 = time.monotonic()
+ try:
+ await asyncio.to_thread(self._vad._ensure_model)
+ log.info("VAD load done in %.0f ms.", (time.monotonic() - _vad_t0) * 1000.0)
+ except Exception as exc: # noqa: BLE001 — lazy load on first use still works
+ log.warning("Warm-up deferred loader 'vad-load' failed: %s", exc)
+
+ # Join the concurrently-running TTS init (started before the wake warm).
+ tts_err: Exception | None = None
+ try:
+ await tts_task
+ except Exception as exc: # noqa: BLE001 — lazy load on first synth still works
+ tts_err = exc
+ log.warning("Warm-up deferred loader 'tts-init' failed: %s", exc)
+
+ log.info(
+ "Warm-up deferred loaders done in %.0f ms (tts-init=%s).",
+ (time.monotonic() - deferred_t0) * 1000.0,
+ "ok" if tts_err is None else "failed",
+ )
+
+ # --- HONEST READINESS: the full stack is up (or attempted) ------
+ # Wake model warmed + VAD loaded + TTS client init done → the user
+ # can now actually be heard AND get a spoken reply. Signal ready and
+ # play the audible cue here, exactly once, at the first truthful
+ # moment. Even on a failed VAD/TTS load we still flip ready (each
+ # lazy-loads / falls back on first use) rather than stranding the UI
+ # in "starting up" forever. The cue is fire-and-forget so a
+ # slow/wedged output device never sits between ready=True and a
+ # responsive wake loop.
+ await self._emit_boot_status(ready=True, detail="listening")
+ self._warmup_ready_cue_task = asyncio.create_task(
+ self._play_ready_cue(), name="warmup-ready-cue"
+ )
+ self._warmup_ready_cue_task.add_done_callback(self._log_warmup_ready_cue_done)
+ finally:
+ # Never orphan the concurrently-started TTS init: if this deferred
+ # task is cancelled (desktop shutdown) before the ``await tts_task``
+ # join above is reached, CancelledError propagates straight here. Cancel
+ # + await it so a late ``_ensure_client`` failure can't surface as an
+ # unretrieved-exception warning under pythonw.exe. No-op on the normal
+ # path (tts_task already awaited → done). Swallowed; re-raises the
+ # original CancelledError after cleanup.
+ if not tts_task.done():
+ tts_task.cancel()
+ try:
+ await tts_task
+ except (asyncio.CancelledError, Exception): # noqa: BLE001 — shutdown swallow
+ pass
async def _warmup_phase_b(self) -> None:
"""Background pre-render of confirmation audio (never blocks ready).
@@ -3604,7 +3710,7 @@ class SpeechPipeline:
def request_hangup(self) -> None:
"""End the live voice session from outside the audio path.
- The whisper-bar's hover-to-close cross calls this (and any future UI
+ The jarvis-bar's hover-to-close cross calls this (and any future UI
close affordance). Thread-safe like ``request_voice_session``: it routes
through the single hangup chokepoint, whose primitives (``Event.set``,
player stop, CU-cancel) are safe to invoke from the Tk thread. A no-op
@@ -3615,7 +3721,7 @@ class SpeechPipeline:
self._trigger_voice_hangup()
def request_ptt_toggle(self) -> None:
- """Toggle endpoint-free dictation — the whisper-bar's square button.
+ """Toggle endpoint-free dictation — the jarvis-bar's square button.
First call opens a mic with NO silence-endpoint (speak as long as you
want, pauses included); the second call submits. Thread-safe like the
@@ -3630,6 +3736,22 @@ class SpeechPipeline:
else:
self._on_ptt_press() # open an endpoint-free mic
+ def is_session_active(self) -> bool:
+ """Ground truth for "a live voice session is in progress right now".
+
+ The jarvis-bar uses this to decide whether a close-X click is a real
+ hang-up or a useless no-op. The bar's visual mode can get stuck in the
+ active "listen" look when a wake popped it but the post-hangup wake-lock
+ cooldown rejected the session — no ``VoiceSessionStarted`` is published
+ and no ``IDLE`` state follows, so nothing resets the bar (freeze
+ forensic 2026-06-28). The turn-state is the authoritative signal: it is
+ ``IDLE`` iff no ``_active_session`` loop is running.
+ """
+ return (
+ getattr(self, "_turn_state", TurnTakingState.IDLE)
+ is not TurnTakingState.IDLE
+ )
+
def _trigger_voice_hangup(self, *, stop_player: bool = True) -> None:
"""Hard-stop the voice channel — the single hangup chokepoint.
@@ -3708,20 +3830,42 @@ class SpeechPipeline:
"on" if self._whisper_wake_enabled else "off",
"open" if self._activation_allowed() else "closed",
)
- if not self._wake_listening_enabled():
+ # Both detectors off: PARK, do not die. The old code did
+ # ``await asyncio.Event().wait()`` on a FRESH event nobody ever sets —
+ # a permanent sleep that not even a later live wake-word change could
+ # re-arm (only an app restart). Wait on ``_wake_reload_event`` instead so
+ # a ``set_wake_plan`` that re-enables a detector wakes the loop back up,
+ # in-app. The 30 s timeout re-logs the parked state so a genuinely dead
+ # listener stays visible without busy-spinning. (Mission: "no dead state
+ # blocks waking"; AP-22: recovery must be reachable in-app, not a restart.)
+ while not self._wake_listening_enabled():
log.warning(
- "Beide Wake-Detektoren deaktiviert — Wake-Loop schlaeft permanent. "
- "Voice geht nur per Hotkey."
+ "Both wake detectors are disabled — wake is PARKED until a "
+ "wake-word change re-enables one (voice still works via hotkey). "
+ "Waiting on a live wake-plan reload, not sleeping forever."
)
- await asyncio.Event().wait()
+ try:
+ await asyncio.wait_for(self._wake_reload_event.wait(), timeout=30.0)
+ except asyncio.TimeoutError:
+ pass
+ finally:
+ self._wake_reload_event.clear()
gate_blocked_logged_at = 0.0
while True:
if not self._activation_allowed():
now = time.time()
if now - gate_blocked_logged_at > 30.0:
+ # Name the REAL reason: mute is checked first in
+ # _activation_allowed, so a muted user must not be told the
+ # window is hidden (that misled a live freeze diagnosis).
+ reason = (
+ "voice is muted"
+ if getattr(self, "_muted", False)
+ else "desktop window not visible?"
+ )
log.info(
- "Wake-Loop wartet — Activation-Gate geschlossen "
- "(Desktop-Fenster nicht sichtbar?)."
+ "Wake-Loop wartet — Activation-Gate geschlossen (%s).",
+ reason,
)
gate_blocked_logged_at = now
await asyncio.sleep(0.25)
@@ -3744,13 +3888,14 @@ class SpeechPipeline:
leading up to an OpenWakeWord hit actually contained "hey/hi/hallo +
jarv". Returns True if the strict prefix is in the transcript.
- Failure modes degrade open (return True with a warning) so that a
- misconfigured STT, a network blip, or a rate-limit response cannot
- brick the wake on a quiet hardware setup — we'd rather accept the
- occasional bare-"Jarvis" false positive than have the user shout into
- a dead listener. ``verify_wake_with_stt`` itself returns False on STT
- exceptions, which is the desired suppression behaviour for transient
- errors when an STT is wired up.
+ Failure modes degrade OPEN (return True with a log line) so a
+ misconfigured STT, a network blip, a rate-limit, or a known
+ silence/noise hallucination cannot brick the wake — we'd rather accept
+ the occasional bare-"Jarvis" false positive than have the user shout
+ into a dead listener. The ONLY no-transcript case that still suppresses
+ is an EMPTY capture buffer (nothing was recorded). A clear, non-matching
+ transcript (genuine other speech) also suppresses, preserving the
+ bare-"Jarvis" BUG-009 guard.
"""
if not self._require_hey_prefix:
return True
@@ -3768,12 +3913,60 @@ class SpeechPipeline:
"require_hey_prefix=True but no utterance STT — accepting OWW hit"
)
return True
- matched, _ = await verify_wake_with_stt(
+ # Nothing captured yet (empty ring buffer) — there is genuinely no audio
+ # to confirm the wake, so reject without an STT round-trip. This is the
+ # ONLY no-transcript case that suppresses: a NON-empty buffer the STT
+ # could not turn into text is treated as an outage below (degrade open).
+ if not pcm_snapshot:
+ return False
+ matched, text = await verify_wake_with_stt(
self._utterance_stt,
pcm_snapshot,
matcher=getattr(self, "_wake_matcher", None),
)
- return matched
+ if matched:
+ return True
+ text = (text or "").strip()
+ # Degrade OPEN on a KNOWN STT hallucination. A silence/noise boilerplate
+ # transcript ("Untertitelung des ZDF, 2020", "Vielen Dank.") means the
+ # STT failed to transcribe the real audio — NOT that the user didn't say
+ # the wake word. OWW already fired strongly, so this is the same case as
+ # the transient-STT-failure path (which degrades open above): accept
+ # rather than drop a real "Hey Jarvis". Forensic 2026-06-28: short
+ # "Hey Jarvis" buffers made the verify STT hallucinate these phrases for
+ # ~half of all valid wakes, so the wake "stopped working" intermittently.
+ # An arbitrary non-matching transcript (genuine OTHER speech) still
+ # suppresses, so the bare-"Jarvis" false-positive guard (BUG-009) stays.
+ if text and _STT_HALLUCINATION_RE.search(text) is not None:
+ log.info(
+ "wake-verify: STT hallucination %r on a strong OWW hit — "
+ "accepting (degrade-open, not a real rejection)",
+ text[:80],
+ )
+ return True
+ # Degrade OPEN when the verify STT yielded NO usable transcript for real
+ # captured audio. ``verify_wake_with_stt`` collapses a persistent STT
+ # failure (Groq 429/503/timeout) AND an empty transcription to "" — and
+ # since OWW already fired strongly on audio we DID capture, an absent
+ # transcript is an STT problem, not the user staying silent. Accepting
+ # here is what keeps the wake alive through a single-provider outage
+ # (AP-22 / open-source resilience: one dead provider must never brick a
+ # core path, and recovery must be reachable in-app, never via a restart).
+ # This is the runtime-failure twin of the hallucination degrade-open just
+ # above; the documented honesty cost is the occasional bare-"Jarvis"
+ # false positive while the STT is down. A CLEAR non-matching transcript
+ # still suppresses below, so the BUG-009 guard is unaffected.
+ if not text:
+ log.info(
+ "wake-verify: verify STT returned no transcript on a strong OWW "
+ "hit — accepting (degrade-open; an STT outage must not brick the "
+ "wake, AP-22)"
+ )
+ return True
+ log.info(
+ "wake-verify: suppressed — transcript %r has no wake prefix", text[:80]
+ )
+ return False
async def _run_parallel_wake(self) -> None:
"""Öffnet ein Mic, fannt zu 2 Detector-Queues, wartet auf ersten Hit."""
@@ -3797,6 +3990,13 @@ class SpeechPipeline:
async def _fanout(mic: MicrophoneCapture) -> None:
async for chunk in mic.stream():
+ # Input mute (Jarvis-scoped): if the user mutes while a wake
+ # session is already mid-wait, stop feeding the detectors so
+ # Jarvis goes deaf immediately — without touching the OS mic.
+ # (A fresh mute while IDLE is already handled by _wake_loop's
+ # _activation_allowed() gate, which never opens the mic.)
+ if getattr(self, "_muted", False):
+ continue
ring_bytes.extend(chunk.pcm)
if len(ring_bytes) > RING_MAX:
del ring_bytes[: len(ring_bytes) - RING_MAX]
@@ -3904,8 +4104,27 @@ class SpeechPipeline:
# already enforces the same pattern, so its hits skip
# the second stage. See ``_verify_oww_hit``.
if result.startswith("oww:"):
+ # Optimistic VISUAL reveal: pop the overlay bar NOW,
+ # before the slow STT prefix-verify below, so the bar
+ # feels instant on "Hey Jarvis". This is visual-only
+ # (WakeCandidateDetected never opens a session turn),
+ # so a rejected candidate costs a brief bar flash, not
+ # a phantom session — retracted just below on reject.
+ show_candidate = self._state == PipelineState.IDLE
+ if show_candidate:
+ await self._publish_event(
+ WakeCandidateDetected(
+ source_layer="speech", active=True
+ )
+ )
verified = await self._verify_oww_hit(bytes(ring_bytes))
if not verified:
+ if show_candidate:
+ await self._publish_event(
+ WakeCandidateDetected(
+ source_layer="speech", active=False
+ )
+ )
log.info(
"🚫 WAKE verworfen — kein 'Hey'-Prefix im "
"Transkript der letzten ~3 s"
@@ -3922,6 +4141,37 @@ class SpeechPipeline:
break
log.info("🎙 WAKE bestätigt über %s", result)
if self._state == PipelineState.IDLE:
+ # The state-loop SILENTLY drops a wake that arrives
+ # inside the post-hangup echo lock (or when the app
+ # is not activatable) — it just ``continue``s. But
+ # _emit_wake below publishes WakeWordDetected, which
+ # flips the overlay bar to its "listen" look. Emitting
+ # for a wake the loop will then drop leaves the bar
+ # stuck "listening" with no session behind it, and the
+ # user is ignored ("wake triggers, nothing happens").
+ # Mirror the loop's gate HERE, before _emit_wake, and
+ # retract the optimistic candidate instead of lying.
+ now = time.time()
+ locked = now < self._wake_lock_until
+ if locked or not self._activation_allowed():
+ if locals().get("show_candidate"):
+ await self._publish_event(
+ WakeCandidateDetected(
+ source_layer="speech", active=False
+ )
+ )
+ if locked:
+ log.info(
+ "🔒 Wake-Lock aktiv — Emit verworfen "
+ "(noch %.1fs)",
+ max(0.0, self._wake_lock_until - now),
+ )
+ else:
+ log.info(
+ "Wake-Emit verworfen — App nicht "
+ "aktivierbar."
+ )
+ break
# Event-Bus: WakeWordDetected + Supervisor-State
# werden fuer UI-Feedback gebraucht (Orb einblenden).
keyword = result.split(":", 1)[-1] if ":" in result else result
@@ -4041,7 +4291,7 @@ class SpeechPipeline:
"Sound effects" master switch applies live (no restart). Defensive
default ``True`` — a missing field must never silence tones.
"""
- ui = getattr(self._config, "ui", None)
+ ui = getattr(getattr(self, "_config", None), "ui", None)
return bool(getattr(ui, "sound_effects", True))
async def _play_earcon(
@@ -4409,6 +4659,16 @@ class SpeechPipeline:
except RuntimeError:
log.warning("start_dictation: no running loop.")
return False
+ # A fresh dictation session must NOT inherit a stale hangup. ``_hangup_event``
+ # is set by every "auflegen" and is otherwise only cleared when the next
+ # VOICE session is accepted (``_run_session``). The dictation lane shares
+ # that event in its ``asyncio.wait`` gate, so a leftover hangup from an
+ # earlier voice call would finalize this session on its first tick — the
+ # mic appears to "stop the instant you click it". Clear it here, mirroring
+ # the voice-path ``self._hangup_event.clear()`` at session accept.
+ hangup = getattr(self, "_hangup_event", None)
+ if hangup is not None:
+ hangup.clear()
self._dictation_stop_event = asyncio.Event()
self._dictation_task = loop.create_task(
self._dictation_session(), name="chat-dictation"
@@ -4540,6 +4800,14 @@ class SpeechPipeline:
"""Filtert Mic-Frames, die waehrend/nach Jarvis-TTS aufgenommen wurden."""
dropped = 0
async for chunk in chunks:
+ # Input mute (Jarvis-scoped): while muted, drop the user's audio at
+ # OUR input boundary so Jarvis stops hearing them mid-session —
+ # without touching the OS microphone, so every other app keeps the
+ # mic. The mute flag already gated wake activation + TTS output; this
+ # closes the active-session input gap ("ich rede, aber er hoert mich
+ # trotzdem", 2026-06-28). # i18n-allow
+ if getattr(self, "_muted", False):
+ continue
if self._should_drop_session_input(chunk):
dropped += 1
continue
diff --git a/jarvis/speech/rolling_whisper_wake.py b/jarvis/speech/rolling_whisper_wake.py
index 1bc82dca07..ea0d85b499 100644
--- a/jarvis/speech/rolling_whisper_wake.py
+++ b/jarvis/speech/rolling_whisper_wake.py
@@ -53,6 +53,28 @@ log = logging.getLogger("jarvis.wake.rolling")
# Watchdog-Verzeichnis für Debug-WAVs
DEBUG_DIR = Path(os.environ.get("JARVIS_DEBUG_DIR", "./data/wake_debug"))
+# Production default is OFF. The watchdog WAV dump writes ONE WAV file per
+# transcribed wake window SYNCHRONOUSLY inside the poll loop. Left on, it both
+# (a) accumulates unbounded — a live box reached 218k files in data/wake_debug/
+# 2026-06-29 — and (b) on Windows, writing into a directory that large is slow,
+# so the disk I/O lands ON the wake hot path and adds latency to every poll
+# (the user's "no delay" requirement). Opt in for debugging with
+# JARVIS_WAKE_DEBUG_WAVS=1; otherwise the wake path never touches the disk.
+_DEBUG_WAVS_ENV = os.environ.get("JARVIS_WAKE_DEBUG_WAVS", "").strip().lower() in (
+ "1", "true", "yes", "on",
+)
+
+# After this many CONSECUTIVE transcription failures (a timeout = the local
+# Whisper hung, or a "busy" skip because a prior call is wedged holding the
+# model), rebuild the wake model fresh via ``stt.recover()``. Forensic
+# 2026-06-29: a custom wake ("Hey Nico") went dead for 2 HOURS — every transcribe
+# timed out at 8 s, abandoned, retried, hung again, forever; an app restart did
+# not even clear it. The timeout only BOUNDS a hang; it never RECOVERS. A run of
+# failures with zero successes is the wedge signature (a legitimate VAD-probe
+# overlap clears in 1-2 polls and resets the counter on the next success), so a
+# small threshold self-heals fast without firing on a transient overlap.
+_WEDGE_RECOVER_AFTER_FAILS = 5
+
def _save_wav(pcm_bytes: bytes, sample_rate: int, path: Path) -> None:
"""Schreibt int16-PCM als gültiges WAV-File."""
@@ -118,8 +140,16 @@ class RollingWhisperWake:
# Whisper wird dabei etwas oefter aufgerufen (mehr GPU-Last), aber das
# Trigger-Verhalten ist korrekt — genau was der User will.
min_rms: float = 0.003,
- min_peak: float = 0.02,
- save_debug_wavs: bool = True, # Watchdog-Modus
+ # 2026-06-29 (mission "wake only triggers when shouting"): the raw peak
+ # gate runs BEFORE transcription on a quiet mic, so a normal-volume
+ # custom wake ("Hey Nico") whose window peaks below the legacy 0.02 was
+ # dropped silently — only a shout cleared it. Lowered to 0.012 so a
+ # genuinely quiet wake reaches Whisper; the ``min_rms`` silence guard
+ # (pinned >= 0.003 by test_wake_hallucination_guard) still rejects digital
+ # silence/idle hiss, and the confidence + no_speech + pattern gates below
+ # are the real false-positive guards on whatever does reach Whisper.
+ min_peak: float = 0.012,
+ save_debug_wavs: bool = False, # Watchdog-Modus — OFF in prod (env opt-in)
heartbeat_interval_s: float = 3.0,
# Peak-Normalization statt fester Gain: misst Audio-Peak, wendet
# dynamisch den Gain an, der nötig ist um auf -3 dBFS zu kommen.
@@ -139,8 +169,28 @@ class RollingWhisperWake:
# ``max_no_speech_prob`` gate below still rejects silence/noise. Keep only
# a low sanity floor that still drops a near-zero-confidence transcript
# (regression: a 0.2-confidence match must stay rejected).
- min_wake_confidence: float = 0.28,
+ # 2026-06-29 (mission "wake fails repeatedly / only when shouting"): 0.28
+ # sat at the very BOTTOM of the measured genuine-wake band (0.28-0.52), so
+ # a quiet-but-correct wake under-scored it and was rejected — louder =
+ # higher confidence = accepted, which IS the "only when shouting" symptom.
+ # Lowered to 0.22: still strictly above the 0.2 hallucination floor the
+ # regression test pins, but it no longer clips the quiet tail of genuine
+ # wakes. The phrase pattern + no_speech gate remain the real guards.
+ min_wake_confidence: float = 0.22,
max_no_speech_prob: float = 0.6,
+ # Hard ceiling on a SINGLE transcription. Live forensic 2026-06-29
+ # (data/jarvis_desktop.log): the local faster-whisper ``transcribe_pcm``
+ # hung mid-session (no error, no return) and, with no cap, the poll loop
+ # blocked on that one ``await`` forever — the chunk consumer stayed alive
+ # (audio kept flowing, max-rms up to 0.27 while the user spoke) but ZERO
+ # transcripts were produced for 12 min and the custom wake word ("Hey
+ # Nico") was permanently dead. A genuine transcription of a ~1.8 s window
+ # is ~0.1 s (GPU) to ~1 s (CPU base), so a multi-second cap never cuts a
+ # real one but lets the loop ABANDON a hung call and re-poll fresh audio
+ # (self-healing — the "no dead state blocks waking" guarantee). Mirrors
+ # the OWW prefix-verifier's _WAKE_VERIFY_TIMEOUT_S. Set high enough to
+ # tolerate a slow/loaded CPU box (€5-VPS doctrine); <= 0 disables the cap.
+ transcribe_timeout_s: float = 8.0,
) -> None:
self._stt = stt
self._pattern = pattern
@@ -149,7 +199,9 @@ class RollingWhisperWake:
self._cooldown_s = cooldown_s
self._sample_rate = sample_rate
self._min_rms = min_rms
- self._save_debug_wavs = save_debug_wavs
+ # Caller flag OR the env opt-in. Default OFF so the wake poll loop never
+ # does synchronous disk I/O (latency) or accretes a huge WAV dir in prod.
+ self._save_debug_wavs = bool(save_debug_wavs) or _DEBUG_WAVS_ENV
self._heartbeat_interval_s = heartbeat_interval_s
self._target_peak = float(10.0 ** (target_peak_dbfs / 20.0)) # -3 dBFS ≈ 0.707
self._max_gain_factor = float(10.0 ** (max_gain_db / 20.0)) # 40 dB = 100x
@@ -160,12 +212,51 @@ class RollingWhisperWake:
self._language: str | None = language
self._min_wake_confidence = min_wake_confidence
self._max_no_speech_prob = max_no_speech_prob
+ self._transcribe_timeout_s = float(transcribe_timeout_s)
# Statistik für Heartbeat
self._chunks_seen = 0
self._total_bytes = 0
self._max_rms = 0.0
self._last_transcript = ""
self._last_heartbeat_t = time.time()
+ # Per-session debug counters (mirrors OpenWakeWordProvider.stats() so the
+ # two wake paths report the same way). They make the stt_match path's
+ # "wake never fires / sometimes stops entirely" diagnosable: a user can
+ # see how many windows were evaluated, how many were too quiet to even
+ # transcribe (gated_peak / gated_rms), how many reached Whisper, and why
+ # each transcript was dropped — instead of a silent dead listener.
+ self._stat_windows_polled = 0
+ self._stat_gated_rms = 0
+ self._stat_gated_peak = 0
+ self._stat_transcribed = 0
+ self._stat_empty = 0
+ self._stat_rejected_unreliable = 0
+ self._stat_rejected_no_match = 0
+ self._stat_matched = 0
+ self._stat_suppressed_cooldown = 0
+
+ def stats(self) -> dict[str, int]:
+ """Snapshot of this listen session's wake-evaluation counters.
+
+ Keys: ``windows_polled`` (snapshots that reached the audio gates),
+ ``gated_rms`` / ``gated_peak`` (dropped as silence / sub-speech BEFORE
+ Whisper), ``transcribed`` (Whisper calls), ``empty`` (blank transcript),
+ ``rejected_unreliable`` (confidence/no_speech gate), ``rejected_no_match``
+ (transcript did not contain the wake phrase), ``matched`` (wake yielded),
+ ``suppressed_cooldown`` (in the debounce window). Surfaced in the
+ heartbeat log; the analogue of ``OpenWakeWordProvider.stats()``.
+ """
+ return {
+ "windows_polled": self._stat_windows_polled,
+ "gated_rms": self._stat_gated_rms,
+ "gated_peak": self._stat_gated_peak,
+ "transcribed": self._stat_transcribed,
+ "empty": self._stat_empty,
+ "rejected_unreliable": self._stat_rejected_unreliable,
+ "rejected_no_match": self._stat_rejected_no_match,
+ "matched": self._stat_matched,
+ "suppressed_cooldown": self._stat_suppressed_cooldown,
+ }
async def detect(
self, chunks: AsyncIterator[AudioChunk]
@@ -212,12 +303,24 @@ class RollingWhisperWake:
dbfs = 20.0 * np.log10(max(self._max_rms, 1e-12))
log.info(
"💓 wake-heartbeat: chunks=%d bytes=%dKB "
- "max-rms=%.4f (%.1f dBFS) last-transcript=%r",
+ "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)",
self._chunks_seen,
self._total_bytes // 1024,
self._max_rms,
dbfs,
self._last_transcript[:80],
+ self._stat_windows_polled,
+ self._stat_gated_rms,
+ self._stat_gated_peak,
+ self._stat_transcribed,
+ self._stat_rejected_unreliable,
+ self._stat_rejected_no_match,
+ self._stat_matched,
+ self._min_wake_confidence,
+ self._min_peak,
)
self._chunks_seen = 0
self._total_bytes = 0
@@ -239,6 +342,30 @@ class RollingWhisperWake:
consumer = asyncio.create_task(_consume(), name="rolling-whisper-consume")
last_trigger_t = 0.0
+ # Self-heal counter: consecutive transcribe failures with no success.
+ # Reset on any successful transcription; a run of these triggers a fresh
+ # model rebuild (see _WEDGE_RECOVER_AFTER_FAILS) so a wedged local Whisper
+ # can never leave the wake permanently dead.
+ consecutive_fail = 0
+
+ def _note_transcribe_fail() -> int:
+ nonlocal consecutive_fail
+ consecutive_fail += 1
+ if consecutive_fail >= _WEDGE_RECOVER_AFTER_FAILS:
+ recover = getattr(self._stt, "recover", None)
+ if callable(recover):
+ log.error(
+ "rolling-whisper: %d consecutive transcribe failures — "
+ "rebuilding the wedged wake model (self-heal, no restart).",
+ consecutive_fail,
+ )
+ try:
+ recover()
+ except Exception as exc: # noqa: BLE001 — heal must never crash
+ log.warning("rolling-whisper: model recover() failed: %s", exc)
+ consecutive_fail = 0
+ return consecutive_fail
+
try:
while not stopped.is_set():
# Wall-clock poll cadence — independent of the chunk arrival rate
@@ -248,6 +375,7 @@ class RollingWhisperWake:
now = time.time()
# Cooldown nach letztem Trigger
if now - last_trigger_t < self._cooldown_s:
+ self._stat_suppressed_cooldown += 1
continue
# Noch nicht genug Audio im Buffer
if buf_len[0] < self._sample_rate: # mind. 1 Sek
@@ -261,16 +389,27 @@ class RollingWhisperWake:
audio_np = np.concatenate(list(buffer))
if len(audio_np) < self._sample_rate:
continue
+ # A full window reached the audio gates — this is one wake
+ # evaluation attempt (the denominator for the gate counters).
+ self._stat_windows_polled += 1
# Lautstärke-Check (RMS) — kein Whisper-Call bei Stille
rms = float(np.sqrt(np.mean(audio_np * audio_np) + 1e-12))
if rms < self._min_rms:
+ self._stat_gated_rms += 1
continue
# Peak-Gate: bei reinem Rauschen gar nicht erst Whisper bemühen
peak = float(np.max(np.abs(audio_np)))
if peak < self._min_peak:
- # Kein Whisper-Call — zu leise für Sprache
+ # Kein Whisper-Call — zu leise für Sprache. 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 += 1
+ log.debug(
+ "rolling-whisper: window gated (peak=%.4f < %.4f) — too quiet",
+ peak, self._min_peak,
+ )
continue
# Whisper-Call mit Peak-Normalization (dynamischer Gain)
@@ -286,11 +425,41 @@ class RollingWhisperWake:
np.clip(boosted, -1.0, 1.0) * 32767.0
).astype(np.int16).tobytes()
log.debug("whisper-gain applied=%.1f dB (peak-in=%.3f)", applied_db, peak)
- transcript = await self._stt.transcribe_pcm(
- pcm_bytes, language=self._language
+ # Bounded transcription: a hung local-Whisper call must not
+ # freeze the poll loop forever (the 12-min silent-wedge
+ # forensic). On timeout we abandon THIS call and re-poll fresh
+ # audio so the wake self-heals instead of dying. timeout<=0
+ # disables the cap. We use ``asyncio.timeout`` (3.11+), NOT
+ # ``asyncio.wait_for``: wait_for SWALLOWS an external
+ # cancellation when the inner coroutine completes in the same
+ # tick (a fast/instant STT), which would make detect() ignore
+ # its own ``aclose``/cancel and loop forever on shutdown.
+ # ``asyncio.timeout`` raises TimeoutError only on ITS deadline
+ # and lets an external CancelledError propagate untouched.
+ if self._transcribe_timeout_s > 0:
+ async with asyncio.timeout(self._transcribe_timeout_s):
+ transcript = await self._stt.transcribe_pcm(
+ pcm_bytes, language=self._language
+ )
+ else:
+ transcript = await self._stt.transcribe_pcm(
+ pcm_bytes, language=self._language
+ )
+ self._stat_transcribed += 1
+ consecutive_fail = 0 # a success clears the wedge streak
+ except TimeoutError:
+ log.warning(
+ "Rolling-Whisper Transkription nach %.1fs abgebrochen "
+ "(hung STT, %d in Folge) — re-poll, Wake bleibt lebendig",
+ self._transcribe_timeout_s,
+ _note_transcribe_fail(),
)
+ continue
except Exception as exc: # noqa: BLE001
- log.warning("Rolling-Whisper Transkription fehlgeschlagen: %s", exc)
+ log.warning(
+ "Rolling-Whisper Transkription fehlgeschlagen (%d in Folge): %s",
+ _note_transcribe_fail(), exc,
+ )
continue
text = transcript.text.strip()
@@ -310,6 +479,7 @@ class RollingWhisperWake:
log.warning("WAV-Save fehlgeschlagen: %s", exc)
if not text:
+ self._stat_empty += 1
log.info("rolling-whisper: rms=%.4f text=<leer>", rms)
continue
@@ -318,11 +488,13 @@ class RollingWhisperWake:
min_confidence=self._min_wake_confidence,
max_no_speech_prob=self._max_no_speech_prob,
):
+ self._stat_rejected_unreliable += 1
log.info(
"rolling-whisper: rejected unreliable wake transcript "
- "rms=%.4f confidence=%.3f no_speech=%r text=%r",
+ "rms=%.4f confidence=%.3f (floor %.2f) no_speech=%r text=%r",
rms,
float(getattr(transcript, "confidence", 0.0) or 0.0),
+ self._min_wake_confidence,
_segment_no_speech_probs(transcript),
text,
)
@@ -331,8 +503,12 @@ class RollingWhisperWake:
log.info("rolling-whisper: rms=%.4f text=%r", rms, text)
m = self._pattern.search(text)
if m:
+ self._stat_matched += 1
last_trigger_t = now
+ log.info("rolling-whisper: WAKE matched %r in %r", m.group(0), text)
yield m.group(0)
+ else:
+ self._stat_rejected_no_match += 1
finally:
consumer.cancel()
try:
diff --git a/jarvis/speech/wake_phrase.py b/jarvis/speech/wake_phrase.py
index 6d9ada34c2..0a301df2c2 100644
--- a/jarvis/speech/wake_phrase.py
+++ b/jarvis/speech/wake_phrase.py
@@ -57,8 +57,10 @@ def sensitivity_to_threshold(sensitivity: float) -> float:
"""
s = max(0.0, min(1.0, float(sensitivity)))
if s <= 0.5:
- return _THRESHOLD_CEILING + (PRODUCTION_WAKE_THRESHOLD - _THRESHOLD_CEILING) * (s / 0.5)
- return PRODUCTION_WAKE_THRESHOLD + (_THRESHOLD_FLOOR - PRODUCTION_WAKE_THRESHOLD) * ((s - 0.5) / 0.5)
+ span = PRODUCTION_WAKE_THRESHOLD - _THRESHOLD_CEILING
+ return _THRESHOLD_CEILING + span * (s / 0.5)
+ span = _THRESHOLD_FLOOR - PRODUCTION_WAKE_THRESHOLD
+ return PRODUCTION_WAKE_THRESHOLD + span * ((s - 0.5) / 0.5)
class _FuzzyMatch:
@@ -105,6 +107,26 @@ class WakeMatcher:
def is_jarvis_default(self) -> bool:
return self._is_jarvis
+ def _effective_ratio(self, core_token: str) -> float:
+ """The match ratio required for one core token.
+
+ Short proper-noun wake words ("Neko", "Mia", "Leo") are penalised
+ hardest by ``SequenceMatcher``: a single STT mishearing ("Neko" ->
+ "Niko") is a one-character substitution, which on a 4-char token drops
+ the ratio to ~0.75 — just under the 0.8 default, so the word "never
+ works". For short cores we therefore relax the bar to allow ~one
+ character of drift (never below an absolute 0.6 floor so it cannot
+ become a hair-trigger). A core of 6+ chars keeps the configured ratio
+ unchanged, so a longer word — or an explicitly strict matcher on one —
+ stays as strict as before (the configurable-ratio contract is intact).
+ """
+ n = len(core_token)
+ if n >= 6:
+ return self._ratio
+ # ratio of an n-char token vs the same token with one char substituted.
+ one_sub_ratio = (n - 1) / n if n else 1.0
+ return min(self._ratio, max(0.6, one_sub_ratio - 0.01))
+
def search(self, text: str) -> Any | None:
"""Return a match object (``.group(0)``) or ``None``. Never raises."""
if not text:
@@ -115,12 +137,17 @@ class WakeMatcher:
n = len(self._core)
if n == 0 or len(tokens) < n:
return None
+ # Length-aware threshold: average the per-core-token required ratios so a
+ # short name tolerates a little pronunciation drift while a longer one
+ # (or a multi-word phrase with long tokens) keeps the strict bar.
+ threshold = sum(self._effective_ratio(c) for c in self._core) / n
for i in range(0, len(tokens) - n + 1):
window = tokens[i : i + n]
score = sum(
- SequenceMatcher(None, c, w).ratio() for c, w in zip(self._core, window)
+ SequenceMatcher(None, c, w).ratio()
+ for c, w in zip(self._core, window, strict=False)
) / n
- if score >= self._ratio:
+ if score >= threshold:
return _FuzzyMatch(" ".join(window))
return None
@@ -129,16 +156,28 @@ def compile_wake_matcher(phrase: str, *, fuzzy_ratio: float = 0.8) -> WakeMatche
"""Build a :class:`WakeMatcher` for ``phrase``.
The default "Hey Jarvis" (and any jarvis-only phrase) is matched by the
- strict legacy pattern. Other phrases are fuzzy-matched on their core tokens
- unless the user explicitly included a wake prefix ("Hey", "Hallo", "Ok",
- ...), in which case the prefix is part of the match contract.
+ strict legacy pattern. Every other phrase fuzzy-matches on its CORE tokens —
+ the distinctive word(s) after any leading wake prefix ("Hey", "Hallo", "Ok",
+ ...). So "Hey Nico" fires on "nico", whether or not the "Hey" prefix made it
+ into the transcript.
+
+ Why the prefix is OPTIONAL, not required (live forensic 2026-06-29, custom
+ wake "Hey Nico"): the rolling-whisper poll transcribes ~1.8 s windows, and on
+ a slow local model the effective cadence (~1.7 s) is close to the window
+ length, so a short spoken "Hey Nico" routinely lands SPLIT across snapshots —
+ one window catches only "Hey", the next only "…nico". Requiring "hey"+"nico"
+ ADJACENT then drops both halves and the user has to repeat the wake many
+ times ("I have to say it ten times"). Matching the distinctive core alone
+ catches the "…nico" / "nico" windows too, which is exactly the user's
+ "trigger super easily" mandate. The cost is that the bare name spoken in
+ ambient speech while IDLE can wake the listener — an accepted trade ("lieber
+ leichter triggern als schwer"); the no_speech / RMS / fuzzy guards still
+ reject silence and unrelated words, and the wake loop only listens when IDLE.
"""
- tokens = normalize_phrase_for_match(phrase)
core = phrase_core_for_match(phrase)
if core == ["jarvis"]:
return WakeMatcher(pattern=JARVIS_WAKE_PATTERN, is_jarvis_default=True)
- match_tokens = tokens if tokens and core and len(core) < len(tokens) else core
- return WakeMatcher(core_tokens=match_tokens, fuzzy_ratio=fuzzy_ratio)
+ return WakeMatcher(core_tokens=core, fuzzy_ratio=fuzzy_ratio)
def _canonical_keyword(phrase: str) -> str:
diff --git a/tests/unit/core/test_wake_word_config.py b/tests/unit/core/test_wake_word_config.py
index 7a5791304a..1f350e44ad 100644
--- a/tests/unit/core/test_wake_word_config.py
+++ b/tests/unit/core/test_wake_word_config.py
@@ -10,9 +10,12 @@ from jarvis.core.config import TriggerConfig, WakeWordConfig
from jarvis.speech import wake_constants
-def test_defaults_are_hey_jarvis_auto() -> None:
+def test_defaults_are_neutral_empty_auto() -> None:
+ # Shipped default is a BLANK phrase (neutral pre-onboarding; the user must
+ # opt in to a wake word — no trademarked/branded default). See
+ # wake_constants.DEFAULT_WAKE_PHRASE and test_default_wake_phrase_is_empty.
c = WakeWordConfig()
- assert c.phrase == "Hey Jarvis"
+ assert c.phrase == ""
assert c.engine == "auto"
assert c.sensitivity == 0.5
assert c.fuzzy_match_ratio == 0.8
@@ -37,13 +40,13 @@ def test_legacy_porcupine_keys_still_load() -> None:
c = WakeWordConfig(
provider="porcupine", keyword="jarvis", custom_keyword_file=""
)
- assert c.phrase == "Hey Jarvis" # new SoT default, unaffected
+ assert c.phrase == "" # new SoT default (neutral blank), unaffected by legacy keys
def test_trigger_config_embeds_wake_word() -> None:
t = TriggerConfig()
assert isinstance(t.wake_word, WakeWordConfig)
- assert t.wake_word.phrase == "Hey Jarvis"
+ assert t.wake_word.phrase == "" # neutral blank default (no branded wake word)
def test_phrase_round_trips_arbitrary_value() -> None:
diff --git a/tests/unit/plugins/stt/test_fwhisper_concurrency.py b/tests/unit/plugins/stt/test_fwhisper_concurrency.py
new file mode 100644
index 0000000000..31a4709f99
--- /dev/null
+++ b/tests/unit/plugins/stt/test_fwhisper_concurrency.py
@@ -0,0 +1,116 @@
+"""faster-whisper transcription must never run concurrently on one model, and a
+WEDGED model must self-heal.
+
+Live forensic 2026-06-29 (custom wake "Hey Nico"): the wake went dead for HOURS —
+every transcribe timed out at 8 s, was abandoned, retried, hung again, forever;
+an app restart did not even clear it. Root cause: the wake poll loop and the VAD
+"listening bubble" probe share ONE ``FasterWhisperProvider`` (``_probe_stt =
+_stt`` for a custom phrase) and both call ``transcribe_pcm`` — ``model.transcribe``
+runs in a worker thread, so two concurrent calls hit ctranslate2's WhisperModel
+at once, which is NOT thread-safe → a permanent hang.
+
+Two contracts pinned here:
+1. A non-blocking per-model lock so two concurrent calls NEVER overlap (the
+ second is skipped with ``TranscribeBusy`` instead of corrupting the model or
+ piling up behind a hung call).
+2. ``recover()`` drops the (possibly hung) model + its lock so the next call
+ rebuilds a fresh engine — the self-heal that ends the permanent wedge.
+"""
+from __future__ import annotations
+
+import asyncio
+import threading
+import time
+from types import SimpleNamespace
+
+from jarvis.plugins.stt.fwhisper import FasterWhisperProvider, TranscribeBusy
+
+PCM_1S = b"\x00\x00" * 16_000
+
+
+class _ConcurrencyProbeModel:
+ """Stand-in WhisperModel that records the peak number of concurrent
+ ``transcribe`` calls. ctranslate2 would corrupt/hang here; we just measure."""
+
+ def __init__(self) -> None:
+ self._active = 0
+ self.max_active = 0
+ self.calls = 0
+ self._lock = threading.Lock()
+
+ def transcribe(self, audio, **kwargs): # noqa: ANN001, ANN003
+ with self._lock:
+ self._active += 1
+ self.calls += 1
+ self.max_active = max(self.max_active, self._active)
+ time.sleep(0.1) # hold long enough that an unserialized 2nd call overlaps
+ with self._lock:
+ self._active -= 1
+ info = SimpleNamespace(language="de")
+ return iter(()), info # no segments -> empty transcript, confidence 0
+
+
+async def test_concurrent_transcribe_calls_never_overlap() -> None:
+ prov = FasterWhisperProvider(device="cpu", compute_type="int8")
+ probe = _ConcurrencyProbeModel()
+ prov._model = probe # noqa: SLF001 — inject the fake model (skip the real load)
+
+ # Two concurrent transcriptions on the SAME provider (the wake poll loop and
+ # the VAD probe in production). The non-blocking lock means model.transcribe
+ # is NEVER entered twice at once — the loser is skipped, not run concurrently.
+ results = await asyncio.gather(
+ prov.transcribe_pcm(PCM_1S),
+ prov.transcribe_pcm(PCM_1S),
+ return_exceptions=True,
+ )
+
+ assert probe.max_active == 1, (
+ f"model.transcribe ran concurrently (peak {probe.max_active}) — the "
+ "ctranslate2 wedge race is not prevented"
+ )
+ # A skipped call is a clean TranscribeBusy, never a crash.
+ for r in results:
+ assert (not isinstance(r, Exception)) or isinstance(r, TranscribeBusy), r
+
+
+async def test_single_transcribe_still_works() -> None:
+ # Regression: the guard must not break a normal single transcription.
+ prov = FasterWhisperProvider(device="cpu", compute_type="int8")
+ prov._model = _ConcurrencyProbeModel() # noqa: SLF001
+ t = await prov.transcribe_pcm(PCM_1S)
+ assert t.text == "" # empty segments -> empty text, no crash
+
+
+async def test_busy_lock_raises_transcribe_busy() -> None:
+ # A prior call already holds the inference lock (e.g. a hung transcribe).
+ # The next call must skip with TranscribeBusy, NOT block/pile up behind it.
+ prov = FasterWhisperProvider(device="cpu", compute_type="int8")
+ prov._model = _ConcurrencyProbeModel() # noqa: SLF001
+ prov._infer_lock.acquire() # simulate an in-flight / wedged call
+ try:
+ raised = False
+ try:
+ await prov.transcribe_pcm(PCM_1S)
+ except TranscribeBusy:
+ raised = True
+ assert raised, "a transcribe while the lock is held must raise TranscribeBusy"
+ finally:
+ prov._infer_lock.release()
+
+
+def test_recover_drops_model_and_swaps_in_a_fresh_lock() -> None:
+ # recover() must orphan the (possibly hung) model + lock so the next call
+ # rebuilds a clean engine under a lock that is NOT held by the hung thread.
+ prov = FasterWhisperProvider(device="cpu", compute_type="int8")
+ prov._model = object() # pretend a wedged model is loaded # noqa: SLF001
+ old_lock = prov._infer_lock
+ old_lock.acquire() # a hung worker thread "holds" the old lock
+
+ prov.recover()
+
+ assert prov._model is None, "recover() must drop the model so it rebuilds" # noqa: SLF001
+ assert prov._infer_lock is not old_lock, "recover() must swap in a fresh lock" # noqa: SLF001
+ # The fresh lock is free even though the old one is still held by the wedge.
+ assert prov._infer_lock.acquire(blocking=False) is True # noqa: SLF001
+ prov._infer_lock.release() # noqa: SLF001
+ old_lock.release()
diff --git a/tests/unit/plugins/wake/test_openwakeword_bundled.py b/tests/unit/plugins/wake/test_openwakeword_bundled.py
index 50d6468c0d..7fe3df421f 100644
--- a/tests/unit/plugins/wake/test_openwakeword_bundled.py
+++ b/tests/unit/plugins/wake/test_openwakeword_bundled.py
@@ -15,7 +15,9 @@ def test_model_kwargs_uses_bundled_onnx_paths() -> None:
assert kw["inference_framework"] == "onnx"
assert len(kw["wakeword_models"]) == 1
- assert kw["wakeword_models"][0].endswith("hey_jarvis_v0.1.onnx")
+ # Neutral shipped default is the bundled hey_rhasspy model (no branded/
+ # trademarked default wake word). See jarvis.assets.bundled_wakeword_models.
+ assert kw["wakeword_models"][0].endswith("hey_rhasspy_v0.1.onnx")
assert kw["melspec_model_path"].endswith("melspectrogram.onnx")
assert kw["embedding_model_path"].endswith("embedding_model.onnx")
diff --git a/tests/unit/plugins/wake/test_openwakeword_configurable.py b/tests/unit/plugins/wake/test_openwakeword_configurable.py
index 6fbc67fd73..7cd5fc05c8 100644
--- a/tests/unit/plugins/wake/test_openwakeword_configurable.py
+++ b/tests/unit/plugins/wake/test_openwakeword_configurable.py
@@ -28,8 +28,9 @@ def test_explicit_model_path_canonicalises_keyword() -> None:
assert provider._canonical_keyword("alexa_v0.1") == "alexa"
-def test_default_still_uses_bundled_hey_jarvis() -> None:
- # Regression: the zero-arg construction path is unchanged.
+def test_default_still_uses_bundled_neutral_model() -> None:
+ # Regression: the zero-arg construction path loads the neutral bundled
+ # default (hey_rhasspy — no branded/trademarked default wake word).
provider = OpenWakeWordProvider()
kw = provider._model_kwargs()
- assert kw["wakeword_models"][0].endswith("hey_jarvis_v0.1.onnx")
+ assert kw["wakeword_models"][0].endswith("hey_rhasspy_v0.1.onnx")
diff --git a/tests/unit/plugins/wake/test_openwakeword_gain.py b/tests/unit/plugins/wake/test_openwakeword_gain.py
new file mode 100644
index 0000000000..29243a22ff
--- /dev/null
+++ b/tests/unit/plugins/wake/test_openwakeword_gain.py
@@ -0,0 +1,165 @@
+"""Unit-level guard for ``WakeGainNormalizer`` — the wake-path input AGC.
+
+Root cause of "the wake word only triggers when I shout" (2026-06-28): the fast
+OpenWakeWord detector is the sole wake path in the default lightweight config
+(the RollingWhisperWake low-volume backstop is a power-user opt-in). That fast
+path fed RAW int16 frames into the neural model — no gain. The model's
+activation score scales with input level, so on this project's documented
+quiet-mic hardware (normal-speech rms ~0.01-0.02) a genuine "Hey Jarvis" peaks
+at ~0.10-0.14, just *below* the pinned 0.15 threshold. Only shouting lifted the
+level over the bar.
+
+The threshold cannot move (``test_wake_threshold`` pins the BUG-009 floor), so
+the fix is the same peak normalization the RollingWhisperWake backstop already
+uses, brought to the default OWW path: a lightweight, amplify-only, noise-gated,
+capped streaming AGC. This file pins the mechanism in isolation; the companion
+``test_openwakeword_normalization.py`` pins the provider-level outcome (a quiet
+wake actually clears the threshold and fires).
+
+Pinned behaviour:
+
+* a quiet *above-floor* frame is amplified toward the target (so normal-volume
+ speech reaches the level the model + threshold expect);
+* pure silence and *sub-floor* noise are NOT amplified (no idle false-fire
+ storm — the AGC-level analogue of the BUG-009 ambient guard);
+* a loud frame is never attenuated (amplify-only — loud already works);
+* the gain is capped (a near-silent noise floor can't be blown to full scale);
+* ``reset()`` clears the rolling envelope so a stale loud burst cannot suppress
+ the gain on the next quiet wake;
+* the provider routes frames through the AGC before scoring, and the escape
+ hatch (``gain_normalization=False``) passes raw audio unchanged.
+"""
+from __future__ import annotations
+
+from collections.abc import AsyncIterator
+
+import numpy as np
+
+from jarvis.core.protocols import AudioChunk
+from jarvis.plugins.wake.openwakeword_provider import (
+ OWW_FRAME_SAMPLES,
+ OpenWakeWordProvider,
+ WakeGainNormalizer,
+)
+
+
+def _sine_int16(peak: float, n: int = OWW_FRAME_SAMPLES) -> np.ndarray:
+ """A 440 Hz sine of ``n`` int16 samples whose float peak is ``peak`` (0..1)."""
+ t = np.arange(n, dtype=np.float32)
+ wave = np.sin(2.0 * np.pi * 440.0 * t / 16_000.0) * float(peak)
+ return (np.clip(wave, -1.0, 1.0) * 32767.0).astype(np.int16)
+
+
+def _float_peak(frame: np.ndarray) -> float:
+ return float(np.max(np.abs(frame.astype(np.float32) / 32768.0)))
+
+
+# ---------------------------------------------------------------------------
+# WakeGainNormalizer — the pure mechanism
+# ---------------------------------------------------------------------------
+
+def test_quiet_above_floor_frame_is_amplified_toward_target() -> None:
+ norm = WakeGainNormalizer()
+ frame = _sine_int16(peak=0.06)
+ out = norm.process(frame)
+ in_peak = _float_peak(frame)
+ out_peak = _float_peak(out)
+ assert out_peak > in_peak * 1.5, (
+ f"normal-volume speech must be lifted, got {in_peak:.3f} -> {out_peak:.3f}"
+ )
+ assert out_peak <= 0.95, "must not clip hard against full scale"
+
+
+def test_pure_silence_is_returned_unchanged() -> None:
+ norm = WakeGainNormalizer()
+ frame = np.zeros(OWW_FRAME_SAMPLES, dtype=np.int16)
+ out = norm.process(frame)
+ assert np.array_equal(out, frame)
+
+
+def test_subfloor_noise_is_not_amplified_into_the_speech_band() -> None:
+ # Below the noise floor: idle hiss / room rumble must stay quiet so the AGC
+ # cannot manufacture an ambient false-fire band (the BUG-009 guard).
+ norm = WakeGainNormalizer()
+ frame = _sine_int16(peak=0.008)
+ out = norm.process(frame)
+ assert _float_peak(out) < 0.05
+
+
+def test_loud_frame_is_not_attenuated() -> None:
+ # Amplify-only: a shout already triggers; the AGC must never turn it DOWN.
+ norm = WakeGainNormalizer()
+ frame = _sine_int16(peak=0.8)
+ out = norm.process(frame)
+ assert _float_peak(out) >= 0.79
+
+
+def test_gain_is_capped_at_max_gain_db() -> None:
+ # cap = 6 dB == 2x. A 0.05-peak frame must reach ~0.10, NOT the -3 dBFS
+ # (0.707) target a >10x uncapped gain would produce.
+ norm = WakeGainNormalizer(target_peak_dbfs=-3.0, max_gain_db=6.0)
+ frame = _sine_int16(peak=0.05)
+ out = norm.process(frame)
+ out_peak = _float_peak(out)
+ assert 0.05 * 2 * 0.9 <= out_peak <= 0.05 * 2 * 1.05
+
+
+def test_reset_clears_the_envelope_state() -> None:
+ norm = WakeGainNormalizer()
+ norm.process(_sine_int16(peak=0.8)) # arm a high rolling peak
+ norm.reset()
+ # After reset a quiet frame is amplified as if it were the first one (the
+ # stale loud envelope would otherwise suppress the gain).
+ out = norm.process(_sine_int16(peak=0.06))
+ assert _float_peak(out) > 0.06 * 1.5
+
+
+# ---------------------------------------------------------------------------
+# OpenWakeWordProvider integration
+# ---------------------------------------------------------------------------
+
+class _PeakSpyModel:
+ """Records the float peak of every frame handed to ``predict`` and never
+ fires, so we can assert what the model actually saw."""
+
+ def __init__(self) -> None:
+ self.peaks: list[float] = []
+
+ def predict(self, frame: np.ndarray) -> dict[str, float]:
+ self.peaks.append(_float_peak(np.asarray(frame)))
+ return {"hey_jarvis": 0.0}
+
+
+async def _one_frame(peak: float) -> AsyncIterator[AudioChunk]:
+ pcm = _sine_int16(peak=peak).tobytes()
+ yield AudioChunk(pcm=pcm, sample_rate=16_000, timestamp_ns=0)
+
+
+async def _drain(provider: OpenWakeWordProvider, peak: float) -> _PeakSpyModel:
+ spy = _PeakSpyModel()
+ provider._model = spy # noqa: SLF001 — inject the fake model (as test_wake_threshold does)
+ async for _ in provider.detect(_one_frame(peak)):
+ pass
+ return spy
+
+
+async def test_provider_amplifies_quiet_input_before_scoring() -> None:
+ spy = await _drain(OpenWakeWordProvider(gain_normalization=True), peak=0.06)
+ assert spy.peaks, "model should have been asked to score one frame"
+ assert spy.peaks[0] > 0.06 * 1.5, (
+ f"the model must see boosted audio, saw peak {spy.peaks[0]:.3f}"
+ )
+
+
+async def test_provider_gain_off_passes_raw_audio() -> None:
+ spy = await _drain(OpenWakeWordProvider(gain_normalization=False), peak=0.06)
+ assert spy.peaks
+ assert abs(spy.peaks[0] - 0.06) < 0.01, (
+ f"escape hatch must pass raw audio, saw peak {spy.peaks[0]:.3f}"
+ )
+
+
+async def test_gain_normalization_is_on_by_default() -> None:
+ spy = await _drain(OpenWakeWordProvider(), peak=0.06)
+ assert spy.peaks
+ assert spy.peaks[0] > 0.06 * 1.5
diff --git a/tests/unit/plugins/wake/test_openwakeword_normalization.py b/tests/unit/plugins/wake/test_openwakeword_normalization.py
new file mode 100644
index 0000000000..5a9a4766ed
--- /dev/null
+++ b/tests/unit/plugins/wake/test_openwakeword_normalization.py
@@ -0,0 +1,71 @@
+"""End-to-end: input normalization lets a quiet wake clear the threshold.
+
+Companion to ``test_openwakeword_gain.py`` (which pins the ``WakeGainNormalizer``
+mechanism in isolation). These tests close the loop on the user-visible symptom
+("the wake word only triggers when I shout", mission 2026-06-28): they wire a
+level-sensitive fake model — a genuine wake pattern is assumed present and the
+score scales with the input frame's peak — so the normalization stage is what
+decides whether the score actually clears the pinned 0.15 activation threshold.
+
+Without normalization the quiet wake stays below threshold (the bug); with it
+(the default), the same quiet "Hey Jarvis" wakes — without shouting.
+"""
+from __future__ import annotations
+
+from collections.abc import AsyncIterator
+
+import numpy as np
+
+from jarvis.core.protocols import AudioChunk
+from jarvis.plugins.wake.openwakeword_provider import (
+ OWW_FRAME_SAMPLES,
+ OpenWakeWordProvider,
+)
+
+_THRESHOLD = 0.15
+
+
+class _LevelSensitiveModel:
+ """Mimics openWakeWord's amplitude sensitivity: ``score = min(1, peak * k)``.
+
+ Assumes the genuine wake pattern is present; only the LEVEL varies, so the
+ provider's normalization stage decides whether the score clears threshold.
+ """
+
+ def __init__(self, gain_to_score: float) -> None:
+ self._k = gain_to_score
+
+ def predict(self, frame: object) -> dict[str, float]:
+ arr = np.asarray(frame, dtype=np.float32) / 32768.0
+ peak = float(np.max(np.abs(arr))) if arr.size else 0.0
+ return {"hey_jarvis": min(1.0, peak * self._k)}
+
+
+def _quiet_wake_frame(peak_amp: float) -> bytes:
+ """One OWW frame of int16 audio at the given peak amplitude [0, 1]."""
+ val = int(round(peak_amp * 32767.0))
+ return np.full(OWW_FRAME_SAMPLES, val, dtype=np.int16).tobytes()
+
+
+async def _chunks(frames: list[bytes]) -> AsyncIterator[AudioChunk]:
+ for i, pcm in enumerate(frames):
+ yield AudioChunk(pcm=pcm, sample_rate=16_000, timestamp_ns=i)
+
+
+async def test_normalization_lets_a_quiet_wake_trigger() -> None:
+ # peak 0.05 -> raw score 0.05 * 2 = 0.10 < 0.15 threshold. After amplify-only
+ # normalization the frame is lifted to ~0.5, so the score clears the
+ # threshold and the wake fires WITHOUT shouting.
+ prov = OpenWakeWordProvider(activation_threshold=_THRESHOLD) # gain on by default
+ prov._model = _LevelSensitiveModel(gain_to_score=2.0) # noqa: SLF001
+ wakes = [kw async for kw in prov.detect(_chunks([_quiet_wake_frame(0.05)]))]
+ assert wakes == ["hey_jarvis"]
+
+
+async def test_without_normalization_the_quiet_wake_is_missed() -> None:
+ # Documents the bug: with gain off the same quiet wake stays below threshold
+ # — exactly the "only works when shouted" symptom.
+ prov = OpenWakeWordProvider(activation_threshold=_THRESHOLD, gain_normalization=False)
+ prov._model = _LevelSensitiveModel(gain_to_score=2.0) # noqa: SLF001
+ wakes = [kw async for kw in prov.detect(_chunks([_quiet_wake_frame(0.05)]))]
+ assert wakes == []
diff --git a/tests/unit/plugins/wake/test_openwakeword_stats.py b/tests/unit/plugins/wake/test_openwakeword_stats.py
new file mode 100644
index 0000000000..e0542ca870
--- /dev/null
+++ b/tests/unit/plugins/wake/test_openwakeword_stats.py
@@ -0,0 +1,153 @@
+"""Debug counters + suppression-reason visibility for the OWW wake path.
+
+Mission 2026-06-29 ("wake never triggers / sometimes stops entirely"): the
+fast OpenWakeWord detector used to ``continue`` silently whenever a frame was
+below threshold or inside the cooldown, so a user testing the wake word had no
+way to see *why* nothing happened — was the score close? was a stale cooldown
+deafening the detector? The provider now keeps per-session counters and exposes
+a ``stats()`` snapshot, and ``detect()`` resets its per-session audio state on
+entry so a stale-loud gain envelope from the previous interaction can never
+under-amplify (and thus block) the next quiet wake (the "no dead state blocks
+waking" requirement).
+
+These pin:
+* every scored frame is counted;
+* a below-threshold frame is counted as a below-threshold suppression;
+* an above-threshold frame that the cooldown swallows is counted separately
+ (so "I said it twice and only the first worked" is explainable, not silent);
+* the loudest score this session is tracked (the "confidence scores" log);
+* ``detect()`` resets the gain envelope on entry (the dead-state guard).
+"""
+from __future__ import annotations
+
+from collections.abc import AsyncIterator
+
+import numpy as np
+import pytest
+
+from jarvis.core.protocols import AudioChunk
+from jarvis.plugins.wake.openwakeword_provider import (
+ OWW_FRAME_SAMPLES,
+ PRODUCTION_WAKE_THRESHOLD,
+ OpenWakeWordProvider,
+)
+
+
+class _ScriptedModel:
+ """Returns one scripted score per ``predict`` call (like test_wake_threshold)."""
+
+ def __init__(self, scores: tuple[float, ...]) -> None:
+ self._scores = iter(scores)
+
+ def predict(self, _frame: object) -> dict[str, float]:
+ return {"hey_jarvis": next(self._scores, 0.0)}
+
+
+def _silent_frame_bytes() -> bytes:
+ return b"\x00\x00" * OWW_FRAME_SAMPLES
+
+
+async def _one_chunk_per_score(n: int) -> AsyncIterator[AudioChunk]:
+ pcm = _silent_frame_bytes()
+ for i in range(n):
+ yield AudioChunk(pcm=pcm, sample_rate=16_000, timestamp_ns=i)
+
+
+async def _drain(prov: OpenWakeWordProvider, scores: tuple[float, ...]) -> list[str]:
+ prov._model = _ScriptedModel(scores) # noqa: SLF001 — inject the fake model
+ return [kw async for kw in prov.detect(_one_chunk_per_score(len(scores)))]
+
+
+# ---------------------------------------------------------------------------
+# Counters
+# ---------------------------------------------------------------------------
+
+async def test_stats_count_frames_below_threshold_and_one_trigger() -> None:
+ prov = OpenWakeWordProvider(activation_threshold=0.15)
+ wakes = await _drain(prov, (0.05, 0.09, 0.20))
+ s = prov.stats()
+ assert wakes == ["hey_jarvis"]
+ assert s["frames_seen"] == 3
+ assert s["triggers"] == 1
+ assert s["suppressed_below_threshold"] == 2
+ assert s["max_score"] == pytest.approx(0.20)
+
+
+async def test_stats_count_cooldown_suppression_separately() -> None:
+ # Two genuine scores back-to-back: the first fires, the cooldown swallows
+ # the second. That second swallow must be visible as a cooldown suppression,
+ # NOT a below-threshold one (it cleared the bar — the cooldown ate it).
+ prov = OpenWakeWordProvider(activation_threshold=0.15, cooldown_s=2.0)
+ wakes = await _drain(prov, (0.20, 0.21))
+ s = prov.stats()
+ assert wakes == ["hey_jarvis"]
+ assert s["triggers"] == 1
+ assert s["attempts_above_threshold"] == 2
+ assert s["suppressed_cooldown"] == 1
+ assert s["suppressed_below_threshold"] == 0
+
+
+async def test_stats_start_at_zero_before_any_audio() -> None:
+ prov = OpenWakeWordProvider()
+ s = prov.stats()
+ assert s["frames_seen"] == 0
+ assert s["triggers"] == 0
+ assert s["suppressed_below_threshold"] == 0
+ assert s["suppressed_cooldown"] == 0
+
+
+# ---------------------------------------------------------------------------
+# Per-session state reset — the "no dead state blocks waking" guard
+# ---------------------------------------------------------------------------
+
+def _sine_int16(peak: float, n: int = OWW_FRAME_SAMPLES) -> np.ndarray:
+ t = np.arange(n, dtype=np.float32)
+ wave = np.sin(2.0 * np.pi * 440.0 * t / 16_000.0) * float(peak)
+ return (np.clip(wave, -1.0, 1.0) * 32767.0).astype(np.int16)
+
+
+def _float_peak(frame: np.ndarray) -> float:
+ return float(np.max(np.abs(np.asarray(frame).astype(np.float32) / 32768.0)))
+
+
+class _PeakSpyModel:
+ def __init__(self) -> None:
+ self.peaks: list[float] = []
+
+ def predict(self, frame: np.ndarray) -> dict[str, float]:
+ self.peaks.append(_float_peak(frame))
+ return {"hey_jarvis": 0.0}
+
+
+async def _one_frame(peak: float) -> AsyncIterator[AudioChunk]:
+ yield AudioChunk(pcm=_sine_int16(peak=peak).tobytes(), sample_rate=16_000, timestamp_ns=0)
+
+
+async def test_detect_resets_stale_loud_gain_envelope_on_entry() -> None:
+ # A loud burst at the END of the previous interaction (e.g. Jarvis's own
+ # TTS bleeding into the mic, or a door slam) arms the rolling-peak envelope.
+ # If that envelope survived into the next listen, a normal-volume "Hey
+ # Jarvis" would be left UN-amplified for ~1.5 s and under-score the
+ # threshold — the wake "randomly stops working". detect() must reset the
+ # envelope on entry so the first quiet frame is amplified as if it were the
+ # first one ever.
+ prov = OpenWakeWordProvider(gain_normalization=True)
+ prov._gain.process(_sine_int16(peak=0.9)) # noqa: SLF001 — arm a loud peak
+ spy = _PeakSpyModel()
+ prov._model = spy # noqa: SLF001
+ async for _ in prov.detect(_one_frame(0.06)):
+ pass
+ assert spy.peaks, "model should have scored one frame"
+ assert spy.peaks[0] > 0.06 * 1.5, (
+ f"stale loud envelope blocked the quiet-wake boost: saw {spy.peaks[0]:.3f}"
+ )
+
+
+# ---------------------------------------------------------------------------
+# Threshold consistency — omitting the threshold == the documented production
+# value, not a quieter ad-hoc default.
+# ---------------------------------------------------------------------------
+
+def test_default_threshold_is_the_documented_production_value() -> None:
+ prov = OpenWakeWordProvider()
+ assert prov._threshold == pytest.approx(PRODUCTION_WAKE_THRESHOLD) # noqa: SLF001
diff --git a/tests/unit/speech/test_rolling_whisper_wake.py b/tests/unit/speech/test_rolling_whisper_wake.py
index c15ce70d2e..87c743dc4a 100644
--- a/tests/unit/speech/test_rolling_whisper_wake.py
+++ b/tests/unit/speech/test_rolling_whisper_wake.py
@@ -267,7 +267,7 @@ async def test_detect_rejects_matching_low_confidence_transcript() -> None:
try:
try:
kw = await asyncio.wait_for(_first_keyword(), timeout=0.7)
- except asyncio.TimeoutError:
+ except TimeoutError:
kw = ""
assert kw == ""
finally:
@@ -317,7 +317,7 @@ async def test_detect_rejects_matching_high_no_speech_transcript() -> None:
try:
try:
kw = await asyncio.wait_for(_first_keyword(), timeout=0.7)
- except asyncio.TimeoutError:
+ except TimeoutError:
kw = ""
assert kw == ""
finally:
@@ -401,3 +401,71 @@ async def test_consumer_keeps_draining_while_transcription_is_in_flight() -> Non
await t
except (asyncio.CancelledError, Exception): # noqa: BLE001, S110
pass
+
+
+class _HangingThenRecoverSTT:
+ """transcribe_pcm hangs forever (models a wedged local Whisper); records how
+ often the wake loop asked it to ``recover()``."""
+
+ def __init__(self) -> None:
+ self.recovered = 0
+
+ async def transcribe_pcm(self, pcm, sample_rate=16000, language=None): # noqa: ANN001
+ await asyncio.Event().wait() # never returns -> the timeout fires
+
+ def recover(self) -> None:
+ self.recovered += 1
+
+
+async def test_wake_self_heals_a_wedged_model_via_recover() -> None:
+ """Forensic 2026-06-29: a wedged local Whisper hung on EVERY transcribe (8 s
+ timeout, forever) and an app restart did not clear it — the custom wake was
+ dead for HOURS. After a run of consecutive timeouts the wake loop must call
+ ``stt.recover()`` to rebuild the model, so a wedge can never leave the wake
+ permanently dead ("no dead state blocks waking")."""
+ import re
+
+ stt = _HangingThenRecoverSTT()
+ wake = RollingWhisperWake(
+ stt,
+ pattern=re.compile(r"nico", re.IGNORECASE),
+ poll_interval_s=0.01,
+ cooldown_s=0.0,
+ save_debug_wavs=False,
+ min_rms=0.0,
+ min_peak=0.0,
+ transcribe_timeout_s=0.02, # fast timeout so the wedge is detected quickly
+ )
+
+ src: asyncio.Queue = asyncio.Queue()
+ stop = asyncio.Event()
+
+ async def _iter():
+ while True:
+ chunk = await src.get()
+ if chunk is None:
+ return
+ yield chunk
+
+ async def _drive() -> None:
+ async for _kw in wake.detect(_iter()):
+ pass
+
+ feeder = asyncio.create_task(_feed_until(src, stop))
+ drive = asyncio.create_task(_drive())
+ try:
+ for _ in range(300):
+ if stt.recovered >= 1:
+ break
+ await asyncio.sleep(0.02)
+ assert stt.recovered >= 1, "a wedged model never self-healed via recover()"
+ finally:
+ stop.set()
+ await src.put(None)
+ drive.cancel()
+ feeder.cancel()
+ for t in (drive, feeder):
+ try:
+ await t
+ except (asyncio.CancelledError, Exception): # noqa: BLE001, S110
+ pass
diff --git a/tests/unit/speech/test_rolling_whisper_wake_sensitivity.py b/tests/unit/speech/test_rolling_whisper_wake_sensitivity.py
new file mode 100644
index 0000000000..7b055763ad
--- /dev/null
+++ b/tests/unit/speech/test_rolling_whisper_wake_sensitivity.py
@@ -0,0 +1,240 @@
+"""Sensitivity, audio-gating and debug-counter contract for RollingWhisperWake.
+
+Mission 2026-06-29 ("wake only triggers when shouting / fails repeatedly /
+sometimes stops entirely", custom wake words like "Neko"): a user who sets a
+custom phrase with no pretrained openWakeWord model falls onto the ``stt_match``
+path, which is ``RollingWhisperWake``. On that path two volume-coupled gates and
+a confidence floor silently swallowed normal-volume wakes on a quiet mic:
+
+* the raw ``min_peak`` gate dropped a genuinely quiet window *before* it ever
+ reached Whisper (no transcription, no log) — only a shout cleared it;
+* the ``min_wake_confidence`` floor sat at the very bottom of the measured
+ genuine-wake confidence band, so a quiet-but-correct wake under-scored it.
+
+This file pins the relaxed-but-still-safe gates and the new ``stats()`` debug
+counters (mirroring the OpenWakeWordProvider.stats() instrument) so a user can
+see WHY a window was dropped instead of facing a silent dead listener.
+"""
+from __future__ import annotations
+
+import asyncio
+import re
+
+import numpy as np
+
+from jarvis.core.protocols import AudioChunk, Transcript
+from jarvis.speech.rolling_whisper_wake import RollingWhisperWake
+
+
+def _const_chunk(value: int, n: int = 1600) -> AudioChunk:
+ """A 100 ms @ 16 kHz chunk of constant int16 ``value`` (rms == peak == |v|/32768)."""
+ arr = np.full(n, value, dtype=np.int16)
+ return AudioChunk(pcm=arr.tobytes(), sample_rate=16000, timestamp_ns=0)
+
+
+class _PhraseSTT:
+ """Always transcribes the same phrase; records how often it was called."""
+
+ def __init__(self, phrase: str, *, confidence: float = 0.9,
+ no_speech_prob: float | None = 0.05) -> None:
+ self._phrase = phrase
+ self._confidence = confidence
+ self._no_speech_prob = no_speech_prob
+ self.calls = 0
+
+ async def transcribe_pcm(self, pcm: bytes, sample_rate: int = 16000,
+ language: str | None = None) -> Transcript:
+ self.calls += 1
+ segments = ()
+ if self._no_speech_prob is not None:
+ segments = ({"no_speech_prob": self._no_speech_prob},)
+ return Transcript(text=self._phrase, language="de",
+ confidence=self._confidence, segments=segments)
+
+
+class _NeverMatch:
+ def search(self, text: str): # noqa: ANN001 - duck-typed re.Pattern
+ return None
+
+
+async def _iter(src: asyncio.Queue):
+ while True:
+ chunk = await src.get()
+ if chunk is None:
+ return
+ yield chunk
+
+
+async def _feed_until(src: asyncio.Queue, stop: asyncio.Event, chunk: AudioChunk) -> None:
+ while not stop.is_set():
+ await src.put(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 ""
+
+
+# ---------------------------------------------------------------------------
+# Audio gating — a genuinely quiet (but above silence) wake reaches Whisper.
+# ---------------------------------------------------------------------------
+
+async def test_quiet_wake_above_silence_floor_reaches_transcription() -> None:
+ # peak ~0.015 — above the silence floor, BELOW the legacy 0.02 peak gate that
+ # blocked it on a quiet mic. With the relaxed gate it must reach Whisper and
+ # wake. Uses the DEFAULT gates (no min_peak override) — that is the point.
+ 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()
+ feeder = asyncio.create_task(_feed_until(src, stop, _const_chunk(491))) # peak 0.015
+ try:
+ kw = await asyncio.wait_for(_first_keyword(wake, src), timeout=3.0)
+ assert kw == "nico"
+ assert stt.calls >= 1, "quiet wake never reached Whisper — peak gate too high"
+ finally:
+ stop.set()
+ await src.put(None)
+ feeder.cancel()
+ try:
+ await feeder
+ except (asyncio.CancelledError, Exception): # noqa: BLE001, S110
+ pass
+
+
+# ---------------------------------------------------------------------------
+# Confidence floor — a quiet but correct wake just under the legacy floor wakes.
+# ---------------------------------------------------------------------------
+
+async def test_quiet_genuine_wake_below_legacy_confidence_floor_is_accepted() -> None:
+ # Live base/cpu model scores a clean quiet wake at ~0.25 — under the legacy
+ # 0.28 floor (rejected before) but well above a near-zero hallucination. With
+ # real-speech no_speech_prob it must wake. Uses the DEFAULT confidence floor.
+ stt = _PhraseSTT("Hey Nico", confidence=0.25, no_speech_prob=0.05)
+ wake = RollingWhisperWake(
+ stt,
+ pattern=re.compile(r"hey\W+nico", re.IGNORECASE),
+ poll_interval_s=0.01,
+ cooldown_s=0.0,
+ save_debug_wavs=False,
+ min_rms=0.0,
+ min_peak=0.0,
+ )
+ src: asyncio.Queue = asyncio.Queue()
+ stop = asyncio.Event()
+ feeder = asyncio.create_task(_feed_until(src, stop, _const_chunk(12000)))
+ try:
+ kw = await asyncio.wait_for(_first_keyword(wake, src), timeout=3.0)
+ assert kw.lower() == "hey nico"
+ finally:
+ stop.set()
+ await src.put(None)
+ feeder.cancel()
+ try:
+ await feeder
+ except (asyncio.CancelledError, Exception): # noqa: BLE001, S110
+ pass
+
+
+# ---------------------------------------------------------------------------
+# Gate contract — the relaxed defaults keep the silence guard, lower the rest.
+# ---------------------------------------------------------------------------
+
+def test_default_gates_let_quiet_speech_through_but_still_guard_silence() -> None:
+ from jarvis.plugins.stt.fwhisper import FasterWhisperProvider
+
+ wake = RollingWhisperWake(FasterWhisperProvider())
+ # Silence guard preserved (pinned independently by the hallucination guard).
+ assert wake._min_rms >= 0.003 # noqa: SLF001
+ # Peak gate lowered below the legacy 0.02 so a quiet mic is not deafened.
+ assert wake._min_peak <= 0.012 # noqa: SLF001
+ # Confidence floor lowered below the legacy 0.28, but never to zero (a
+ # near-zero-confidence hallucination must still be rejected).
+ assert 0.0 < wake._min_wake_confidence <= 0.22 # noqa: SLF001
+
+
+# ---------------------------------------------------------------------------
+# Debug counters — make "why didn't it wake?" visible (mirrors OWW stats()).
+# ---------------------------------------------------------------------------
+
+def test_stats_start_at_zero() -> None:
+ from jarvis.plugins.stt.fwhisper import FasterWhisperProvider
+
+ s = RollingWhisperWake(FasterWhisperProvider()).stats()
+ assert s["windows_polled"] == 0
+ assert s["transcribed"] == 0
+ assert s["matched"] == 0
+ assert s["gated_peak"] == 0
+
+
+async def test_stats_count_a_sub_peak_window_as_gated_without_calling_whisper() -> None:
+ # A window below the peak gate (room hiss) must be counted as gated_peak and
+ # must NOT spend a Whisper call — the user can see audio is arriving but too
+ # quiet, instead of a silent nothing.
+ stt = _PhraseSTT("hey nico") # would match if ever called
+ wake = RollingWhisperWake(
+ stt,
+ pattern=_NeverMatch(),
+ poll_interval_s=0.01,
+ cooldown_s=0.0,
+ save_debug_wavs=False,
+ )
+ src: asyncio.Queue = asyncio.Queue()
+ stop = asyncio.Event()
+ feeder = asyncio.create_task(_feed_until(src, stop, _const_chunk(150))) # peak ~0.0046
+ drive = asyncio.create_task(_first_keyword(wake, src))
+ try:
+ await asyncio.sleep(0.3)
+ s = wake.stats()
+ assert s["windows_polled"] >= 1, "poll loop never evaluated a window"
+ assert s["gated_peak"] >= 1, "sub-peak window was not counted as gated"
+ assert s["transcribed"] == 0
+ assert stt.calls == 0, "a sub-peak window must not spend a Whisper call"
+ finally:
+ stop.set()
+ await src.put(None)
+ drive.cancel()
+ feeder.cancel()
+ for t in (drive, feeder):
+ try:
+ await t
+ except (asyncio.CancelledError, Exception): # noqa: BLE001, S110
+ pass
+
+
+async def test_stats_count_a_match_as_matched_and_transcribed() -> None:
+ 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,
+ min_rms=0.0,
+ min_peak=0.0,
+ )
+ src: asyncio.Queue = asyncio.Queue()
+ stop = asyncio.Event()
+ feeder = asyncio.create_task(_feed_until(src, stop, _const_chunk(12000)))
+ try:
+ kw = await asyncio.wait_for(_first_keyword(wake, src), timeout=3.0)
+ assert kw == "nico"
+ s = wake.stats()
+ assert s["matched"] == 1
+ assert s["transcribed"] >= 1
+ finally:
+ stop.set()
+ await src.put(None)
+ feeder.cancel()
+ try:
+ await feeder
+ except (asyncio.CancelledError, Exception): # noqa: BLE001, S110
+ pass
diff --git a/tests/unit/speech/test_wake_dead_state.py b/tests/unit/speech/test_wake_dead_state.py
new file mode 100644
index 0000000000..3cefc9d24d
--- /dev/null
+++ b/tests/unit/speech/test_wake_dead_state.py
@@ -0,0 +1,137 @@
+"""No dead state may block waking (mission "Done when": "no dead state blocks
+waking").
+
+Two concrete permanent-dead-state paths found in the wake plumbing:
+
+1. ``_wake_loop`` used to ``await asyncio.Event().wait()`` on a FRESH event that
+ nobody ever sets when both detectors are disabled — a permanent sleep that
+ not even a later live wake-word change could re-arm (only an app restart).
+ The loop must instead park on ``_wake_reload_event`` so a ``set_wake_plan``
+ re-enabling a detector wakes it back up, in-app.
+
+2. ``set_wake_plan(engine="stt_match")`` on a box where the local Whisper engine
+ cannot be built used to disable BOTH detectors → the silent dead listener
+ above. It must instead degrade to the bundled hey_rhasspy OWW model so the
+ wake stays alive (AP-22: a missing capability must degrade, never brick).
+"""
+from __future__ import annotations
+
+import asyncio
+from types import SimpleNamespace
+
+from jarvis.plugins.wake.openwakeword_provider import OpenWakeWordProvider
+from jarvis.speech.pipeline import PipelineState, SpeechPipeline
+from jarvis.speech.wake_phrase import resolve_wake_plan
+
+
+def _cfg(**kw: object) -> SimpleNamespace:
+ base = dict(
+ phrase="Neko",
+ engine="auto",
+ custom_model_path="",
+ sensitivity=0.5,
+ fuzzy_match_ratio=0.8,
+ )
+ base.update(kw)
+ return SimpleNamespace(**base)
+
+
+async def test_wake_loop_parks_recoverably_when_both_detectors_disabled() -> None:
+ """With both detectors off, the loop must PARK on the reload event (not a
+ dead one). Re-enabling a detector + flipping _wake_reload_event must re-arm
+ it — proving recovery is reachable in-app with no restart."""
+ pipe = SpeechPipeline.__new__(SpeechPipeline)
+ pipe._openwakeword_enabled = False
+ pipe._whisper_wake_enabled = False
+ pipe._wake_reload_event = asyncio.Event()
+ pipe._state = PipelineState.IDLE
+ pipe._muted = False
+ pipe._activation_gate = lambda: True
+ pipe._wake_phrase_label = "Neko"
+
+ ran = asyncio.Event()
+
+ async def _fake_run_parallel_wake() -> None:
+ ran.set()
+ await asyncio.sleep(3600) # park so the loop doesn't spin
+
+ pipe._run_parallel_wake = _fake_run_parallel_wake # type: ignore[method-assign]
+
+ task = asyncio.create_task(pipe._wake_loop())
+ try:
+ await asyncio.sleep(0.05)
+ assert not ran.is_set(), "loop ran wake while both detectors disabled"
+
+ # In-app recovery: a live wake-plan change enables a detector + signals.
+ pipe._openwakeword_enabled = True
+ pipe._wake_reload_event.set()
+
+ await asyncio.wait_for(ran.wait(), timeout=2.0) # re-armed, not dead
+ finally:
+ task.cancel()
+ try:
+ await task
+ except (asyncio.CancelledError, Exception): # noqa: BLE001, S110
+ pass
+
+
+def _shell_for_set_wake_plan() -> SpeechPipeline:
+ pipe = SpeechPipeline.__new__(SpeechPipeline)
+ pipe._wake_plan = None
+ pipe._wake_matcher = None
+ pipe._wake_phrase_label = None
+ pipe._stt = None
+ pipe._probe_stt = None
+ pipe._whisper_wake = None
+ pipe._openwakeword_enabled = False
+ pipe._whisper_wake_enabled = False
+ pipe._wake_reload_event = asyncio.Event()
+ pipe._config = SimpleNamespace(stt=SimpleNamespace(language=None))
+ return pipe
+
+
+def test_set_wake_plan_stt_match_without_whisper_degrades_to_rhasspy(monkeypatch) -> None:
+ """A live switch to a custom phrase on a box where the wake Whisper cannot be
+ built must NOT disable both detectors (the silent dead listener). It degrades
+ to the bundled hey_rhasspy OWW model so wake stays alive."""
+ import jarvis.plugins.stt as stt_pkg
+
+ def _boom(*_a: object, **_k: object) -> object:
+ raise RuntimeError("no faster-whisper installed")
+
+ monkeypatch.setattr(stt_pkg, "build_wake_whisper", _boom, raising=False)
+
+ plan = resolve_wake_plan(_cfg(phrase="Neko"), local_whisper_available=True)
+ assert plan.engine == "stt_match" and plan.needs_local_whisper is True
+
+ pipe = _shell_for_set_wake_plan()
+ pipe.set_wake_plan(plan)
+
+ # Wake must stay ALIVE — at least one detector enabled, never both off.
+ assert pipe._wake_listening_enabled() is True
+ assert pipe._openwakeword_enabled is True
+ assert pipe._whisper_wake_enabled is False
+ assert isinstance(pipe._wake, OpenWakeWordProvider)
+ assert pipe._wake._keywords == ("hey_rhasspy",) # neutral offline fallback
+
+
+def test_set_wake_plan_stt_match_with_whisper_uses_rolling_wake(monkeypatch) -> None:
+ """Control: when a wake Whisper CAN be built, the custom phrase still routes
+ to the RollingWhisperWake transcript matcher (no regression)."""
+ import jarvis.plugins.stt as stt_pkg
+
+ class _FakeWakeWhisper:
+ async def transcribe_pcm(self, *_a: object, **_k: object) -> object:
+ return SimpleNamespace(text="", confidence=0.0, segments=())
+
+ monkeypatch.setattr(
+ stt_pkg, "build_wake_whisper", lambda *a, **k: _FakeWakeWhisper(), raising=False
+ )
+
+ plan = resolve_wake_plan(_cfg(phrase="Neko"), local_whisper_available=True)
+ pipe = _shell_for_set_wake_plan()
+ pipe.set_wake_plan(plan)
+
+ assert pipe._openwakeword_enabled is False
+ assert pipe._whisper_wake_enabled is True
+ assert pipe._wake_listening_enabled() is True
diff --git a/tests/unit/speech/test_wake_phrase.py b/tests/unit/speech/test_wake_phrase.py
index b721208389..44f01aae4f 100644
--- a/tests/unit/speech/test_wake_phrase.py
+++ b/tests/unit/speech/test_wake_phrase.py
@@ -114,12 +114,29 @@ def test_arbitrary_phrase_tolerates_diacritic_transcription_drift() -> None:
assert m.search("hey rubén") is not None
-def test_prefix_phrase_requires_prefix_before_core_word() -> None:
- # "Hey Athena" must not fire on bare "athena". Otherwise a name mention in
- # ambient speech or Jarvis output re-triggers the listener without wake-up.
+def test_prefix_phrase_also_fires_on_bare_core() -> None:
+ # Mission 2026-06-29 ("trigger super easily" / "I say it ten times"): the
+ # leading wake prefix is OPTIONAL. The slow rolling-whisper poll routinely
+ # splits a short "Hey Nico" so one window holds only "Hey" and the next only
+ # "…nico"; requiring "hey"+"athena" ADJACENT drops both halves. Firing on the
+ # distinctive CORE ("athena"/"nico") alone catches the partial windows — the
+ # accepted easy-trigger trade. Still matches the full phrase too.
m = compile_wake_matcher("Hey Athena")
- assert m.search("athena") is None
- assert m.search("hey athena") is not None
+ assert m.search("hey athena") is not None # full phrase still fires
+ assert m.search("athena") is not None # bare core now fires (easy trigger)
+ assert m.search("the weather is nice") is None # unrelated still rejected
+
+
+def test_hey_nico_fires_on_partial_and_drifted_windows() -> None:
+ # The user's real phrase. The prefix-split windows + STT drift that made it
+ # "need ten tries" must now all wake: full phrase, bare name, name-only tail,
+ # and a one-char mishearing — while unrelated speech is still rejected.
+ m = compile_wake_matcher("Hey Nico")
+ assert m.search("hey nico") is not None # full phrase
+ assert m.search("nico") is not None # prefix split — name-only window
+ assert m.search("ja nico komm") is not None # name mid-utterance
+ assert m.search("niko") is not None # STT drift (one char)
+ assert m.search("wie spät ist es") is None # unrelated -> no wake
def test_multi_word_core_phrase_matches_in_order() -> None:
@@ -135,6 +152,35 @@ def test_fuzzy_ratio_is_configurable() -> None:
assert loose.search("athene") is not None
+def test_short_custom_name_tolerates_one_char_pronunciation_drift() -> None:
+ # Mission 2026-06-29: short proper-noun wake words ("Neko") are penalised
+ # hardest by SequenceMatcher — a single STT mishearing ("Neko" -> "Niko")
+ # drops a 4-char word to ratio 0.75, just under the 0.8 default, so the word
+ # "never works". The matcher must allow ~one character of drift for short
+ # cores so a normal pronunciation variance still wakes.
+ m = compile_wake_matcher("Neko")
+ assert m.search("niko") is not None
+ assert m.search("neeko") is not None
+ assert m.search("hey neko") is not None
+
+
+def test_short_custom_name_still_rejects_unrelated_words() -> None:
+ # The short-name relaxation must NOT become a hair-trigger: an unrelated
+ # word (even a short one) must still be rejected (false-positive guard).
+ m = compile_wake_matcher("Neko")
+ assert m.search("taco") is None
+ assert m.search("hello there") is None
+ assert m.search("the cat sat down") is None
+
+
+def test_long_phrase_keeps_strict_ratio_for_short_name_relaxation() -> None:
+ # The relaxation is length-aware: it only loosens SHORT cores. A long core
+ # word keeps the configured ratio, so an explicit strict matcher on a long
+ # word still rejects its drift (the configurable-ratio contract is intact).
+ strict = compile_wake_matcher("Athena", fuzzy_ratio=0.99)
+ assert strict.search("athene") is None
+
+
# --------------------------------------------------------------------------
# sensitivity -> OWW threshold mapping (anchored on PRODUCTION_WAKE_THRESHOLD)
# --------------------------------------------------------------------------
diff --git a/tests/unit/speech/test_wake_prefix_gating.py b/tests/unit/speech/test_wake_prefix_gating.py
index ccd093c3ba..289541ba6c 100644
--- a/tests/unit/speech/test_wake_prefix_gating.py
+++ b/tests/unit/speech/test_wake_prefix_gating.py
@@ -12,8 +12,6 @@ from collections.abc import AsyncIterator
from dataclasses import dataclass
from types import SimpleNamespace
-import pytest
-
from jarvis.core.config import STTConfig, TriggerConfig
from jarvis.speech.pipeline import SpeechPipeline
@@ -107,6 +105,80 @@ async def test_gate_rejects_empty_pcm_without_stt_call() -> None:
assert stt.calls == 0
+async def test_gate_degrades_open_on_stt_hallucination() -> None:
+ """REGRESSION (live 2026-06-28): a strong OWW hit whose verify STT returns a
+ KNOWN silence/noise hallucination ("Untertitelung des ZDF", "Vielen Dank.")
+ must DEGRADE OPEN. Such a transcript means the STT failed to transcribe the
+ real "Hey Jarvis" — it is NOT evidence the user stayed silent. Dropping these
+ made the wake "stop working" for ~half of valid utterances (24 ok / 31 fail
+ in one afternoon). Same intent as the transient-STT-failure degrade-open."""
+ for phrase in (
+ "Untertitelung des ZDF, 2020",
+ "Vielen Dank.",
+ "Thanks for watching",
+ ):
+ stt = _FakeSTT(phrase)
+ pipe = _bare_pipeline(require_hey_prefix=True, utterance_stt=stt)
+ assert await pipe._verify_oww_hit(PCM_2S_16K) is True, phrase
+ assert stt.calls == 1
+
+
+async def test_gate_still_rejects_genuine_other_speech() -> None:
+ """The hallucination degrade-open must NOT accept arbitrary non-wake speech:
+ genuine other words (no "hey + jarv", not a known hallucination) are still
+ suppressed, so the bare-"Jarvis" false-positive guard (BUG-009) stays."""
+ stt = _FakeSTT("wie spät ist es")
+ pipe = _bare_pipeline(require_hey_prefix=True, utterance_stt=stt)
+
+ assert await pipe._verify_oww_hit(PCM_2S_16K) is False
+ assert stt.calls == 1
+
+
+class _RaisingSTT:
+ """transcribe_pcm always raises — models a persistent Groq 503/timeout."""
+
+ def __init__(self, exc: Exception) -> None:
+ self._exc = exc
+ self.calls = 0
+
+ async def transcribe_pcm(
+ self, pcm_bytes: bytes, sample_rate: int = 16_000, language: str | None = None
+ ) -> _FakeTranscript:
+ self.calls += 1
+ raise self._exc
+
+
+async def test_gate_degrades_open_on_empty_transcript_with_real_audio(monkeypatch) -> None:
+ """REGRESSION ("Hey Jarvis sometimes stops working entirely"): a strong OWW
+ hit captured real audio (non-empty buffer) but the verify STT came back with
+ NO transcript — a momentary outage / rate-limit / silence-mis-transcription.
+ That is not evidence the user stayed silent, so it must DEGRADE OPEN (accept)
+ rather than brick the wake while the STT recovers (AP-22). This is distinct
+ from empty PCM (nothing captured yet), which still rejects."""
+ import jarvis.speech.wake_verifier as wv
+
+ monkeypatch.setattr(wv, "_WAKE_VERIFY_BACKOFF_S", 0.0, raising=False)
+ stt = _FakeSTT("") # STT returned nothing for genuine captured audio
+ pipe = _bare_pipeline(require_hey_prefix=True, utterance_stt=stt)
+
+ assert await pipe._verify_oww_hit(PCM_2S_16K) is True
+ assert stt.calls == 1
+
+
+async def test_gate_degrades_open_when_stt_persistently_fails(monkeypatch) -> None:
+ """A persistently failing verify STT (every attempt raises) on a strong OWW
+ hit must degrade open, not suppress — the wake survives a provider outage and
+ recovers in-app with no restart (AP-22). The empty-PCM reject is unchanged."""
+ import jarvis.speech.wake_verifier as wv
+
+ monkeypatch.setattr(wv, "_WAKE_VERIFY_BACKOFF_S", 0.0, raising=False)
+ stt = _RaisingSTT(RuntimeError("groq 503"))
+ pipe = _bare_pipeline(require_hey_prefix=True, utterance_stt=stt)
+
+ assert await pipe._verify_oww_hit(PCM_2S_16K) is True
+ assert stt.calls >= 1
+
+
# ---------------------------------------------------------------------------
# Real construction: require_hey_prefix flows from config into the pipeline.
# ---------------------------------------------------------------------------