Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(wiki): retrieval-first relevance gates and explicit-recall delegation
rubenluetke10-beep7eaad27b7176
diff --git a/AGENTS.md b/AGENTS.mdindex 2a26374807..5a0d709b28 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -1,566 +1,101 @@# CLAUDE.md-Binding rules for any coding agent in this repo — respect them on **every**-change. Architecture and product detail:-[`docs/architecture-overview.md`](docs/architecture-overview.md).-------## 0. Mirror rule — CLAUDE.md ≡ AGENTS.md, .claude/ ≡ .agents/ (BINDING)--`CLAUDE.md` is canonical; `AGENTS.md` is its **byte-identical twin** for other-tools. The same holds for the versioned agent-knowledge trees:-`.claude/{agents,commands,skills}/` ↔ `.agents/{agents,commands,skills}/` —-everything in them addresses **every** coding agent (Codex, Gemini CLI, ...),-never Claude Code alone; write it accordingly. Sync engines-`scripts/ci/sync_agents_md.py` / `sync_agents_dir.py` run as a live-`PostToolUse` hook, `.githooks/pre-commit --stage`, and a `--check` CI gate;-after editing either side, sync before committing. Deletions propagate.-Gitignored/private entries (e.g. `.claude/skills/security-github/`) stay out-of the mirror on both sides.-------## 1. Language — English-only artifacts, fail-closed (BINDING, HIGHEST PRIORITY)--Personal Jarvis is an international open-source project — assume an arbitrary-downloader anywhere on earth. **Everything an agent commits is English**: code,-comments, docstrings, log/exception/error messages, Markdown (READMEs, ADRs,-plans, handoffs, forensic docs), `SKILL.md`, commit messages, PR/issue text,-test names and docstrings, CLI help, route/schema descriptions, telemetry-names, UI strings (i18n key + **English** source). When in doubt, English.-Never invent a new German-allowed category — ask instead of committing German.--**The ONLY German permitted — the multilingual product surface (CLOSED list):**--1. **Runtime voice/TTS + chat output** — governed by the resolver below.-2. **i18n / locale source files + the website's localized copy** — German- there *is* the product.-3. **Speech-recognition input vocabulary** — German tokens a classifier must- literally contain to match German utterances. Matching *data*, not prose.-4. **Tests / fixtures + forensic voice-bug deep-dives** quoting 1–3 as the- content under test.--Materialized file-by-file in `scripts/ci/german-allowlist.txt` — a curated,-justified register, never a free pass: every entry names its reason, and an-inline `i18n-allow` comment on the one load-bearing line beats a whole-file-exemption. **Pre-existing German is backlog, not protected:** when you edit a-file and pass non-product-surface German, translate it on the way through —-never preserve or extend it. The CI gate (`scripts/ci/check_no_new_german.py`)-only sees what a diff ADDS, so the agent is the first line of defense.-Conversation language is each contributor's own choice (personal global-config); the repo fixes only the artifacts.--### Runtime output language (voice + chat) — BINDING--Supported locales are equal — `de`, `en`, `es`, any future one; never a-German- or English-only bias. This governs what Jarvis speaks/writes back and-does NOT weaken the English-artifact rule.--1. **One resolver decides a turn's output language** —- `jarvis/core/turn_language.py::resolve_output_language`. Precedence:- `brain.reply_language` pin → conversation stickiness (a one/two-word- interjection must NOT flip it; only a substantive turn switches) → detected- input language → `DEFAULT_LOCALE`.-2. It applies to **ALL user-facing output**: deep reply, ack preamble, spawn- announcements, every canned status/error/clarify phrase, deterministic- readbacks, AND the TTS voice/BCP-47 pick. A mid-session flip between- layers is a bug.-3. **No layer re-derives the language** — no `_looks_german()`-style- heuristics (drops `es`), no de/en-only phrase table, no per-layer default.- New phrase tables carry ALL supported languages and resolve through the- one resolver.-4. A layer that genuinely can't tell falls back to `DEFAULT_LOCALE`. Durable- pin: `brain.reply_language` (`auto` | `de` | `en` | `es`), editable in the- desktop **Languages** view. Guards: `tests/unit/core/test_turn_language.py`,- `tests/unit/speech/test_phrase_language.py`,- `tests/unit/brain/test_*language*.py`.-------## 2. GitHub — ONE public repo, fail-closed credential protection (BINDING)--The ONE project repo is the public flagship-**`https://github.com/PersonalJarvis/PersonalJarvis`**; every maintainer-"commit / push / save to GitHub / sichere den Stand" targets it — never ask-"which repo". <!-- i18n-allow: quoted German maintainer trigger phrase -->-Lowercase `personal-jarvis` (remote `origin`) is a silent local backup, never-the deliverable. The former depersonalization/snapshot gate is RETIRED-(maintainer directive 2026-07-17): ONE shared git history, every machine-pushes and pulls it normally.--**A push is `git push`.** This repo is an ordinary open-source project and-ships like one. Forbidden as part of pushing (maintainer directive-2026-08-05, after a measured ~440k tokens per push): building a parallel-"clean" staging tree, cloning the target repo to reconcile into, running-`npm ci`/a frontend build, and above all dispatching a sub-agent to read-every file in the tree looking for personal data. That audit re-read 5,481-already-published files on every push; a regex scan, `.gitignore`, and-GitHub's own push protection already cover it. If you find yourself-preparing a snapshot instead of pushing a commit, stop — that is the-retired gate growing back.--What remains, fail-closed:--1. **`.gitignore` first** — `data/`, `.env`, `jarvis.toml`, the Vault, and- key material are never tracked. This is the load-bearing layer: nothing- personal is in the tree, so nothing personal can be pushed.-2. **Never commit credentials** — API keys, tokens, private keys (incl.- `*.key.enc`, AP-29), passphrases. `check_no_private_keys.py` + the secret- sweep stay wired in pre-commit and pre-push.-3. **GitHub secret scanning + push protection stay ON.** A blocked push is a- real finding: stop and fix — never bypass or allowlist around it.-4. **Trademark/brand review is a human release checkpoint** — flag concerns- to the maintainer instead of shipping them.--**Gate placement is a rule, not a preference.** A check that reads the whole-tree belongs in CI (`.github/workflows/ci.yml`), never in `pre-push`. Only a-check that (a) judges the pushed change alone and (b) guards something-unrecoverable — a leaked credential — may block a push. Everything else-reports on GitHub's runners, where a red result costs a notification rather-than a debugging session. Adding a gate to `.githooks/pre-push` requires the-maintainer's explicit say-so; adding one to CI does not.--**Two volumes:** *Update (DEFAULT)* — "push", "sichere den Stand" → normal-push, no bump/tag/release. *Release (explicit only)* — "Mach ein Release",-"mach eine neue Version" → SemVer bump + tag + CHANGELOG, shipping the ENTIRE-current local state (reconcile with `public/main` first; never knowingly ship-a release lacking local fixes without saying so). <!-- i18n-allow: quoted German maintainer trigger phrases -->-When ambiguous, update. **Pre-tag gate:** run-`python scripts/ci/check_release_completeness.py` before tagging and again-with `--verify-release` after publishing — a pushed tag without a *published*-GitHub Release updates no managed install.--**Do not PUSH unless the maintainer asks** (local auto-commit per §9).-Releases are cut from the dev-machine line; a session on another machine-ports its work back to `main` instead of cutting its own releases. Doctrine:-[`CLOUD.md`](CLOUD.md).-------## 3. Open-source universality — the maintainer's config is NEVER the baseline (BINDING)--**Assume an arbitrary downloader, never the maintainer.** This governs the-whole product surface and the entire credential/integration surface — brains,-STT, TTS, Vision, Wake, Telephony, Channels, Marketplace plugins (OAuth +-MCP), and credential STORAGE itself. Every one must:--- **Work with WHATEVER single key/login the user has** — no provider, model,- or integration is load-bearing; a missing / depleted / 429 / 402 /- unreachable one degrades or crosses to a **different family** with an- honest message, never bricking a core path. Primary AND fallback in the- same family = a single-provider brick (AP-22); gate on **capability**,- never a provider name/model id (AP-21).-- **Work on EVERY OS, incl. a headless `python:3.11-slim` VPS** with no- keyring, GPU, audio, or Windows APIs — base `pip install` + boot must- succeed there. Use `pathlib` + capability probes + UTF-8; never hardcode- `C:\Users\...` or assume cp1252. **Base install stays torch-/GPU-free**,- enforced by `check_requirements_sync.py` + `check_lockfile_universal.py`- (GPU/torch deps live only in the opt-in `[local-voice]` extra); regenerate- the lock only with `uv pip compile --universal`. The ONE advertised install- path is the `[full]` profile; the torch-free base is the internal floor for- CI and tiny servers (`--headless`).-- **Be recoverable IN-APP** — entering/switching/recovering a credential- never requires hand-editing `jarvis.toml` or exporting ENV vars.-- **Store credentials portably** — OS keyring → ENV/.env → local-file- fallback (`config._ensure_keyring_backend`); a save/connect must never 500- on a host without a Secret Service.--### OS feature parity — macOS and Linux are first-class (BINDING)--Every feature ships working on **all three OSes in the SAME change**, never-as a "later" follow-up. OS-specific backends live behind ONE capability probe-(Win32/UIA ↔ AppleScript/Quartz/AXUIElement ↔ xdotool/AT-SPI/D-Bus);-`sys.platform == "win32"` with silent nothing elsewhere is a defect. Where a-backend is genuinely impossible (headless), degrade to a clearly-messaged-English no-op. A Windows-only implementation lands ONLY with the capability-gate + honest degradation + a tracked entry in-[`docs/os-parity.md`](docs/os-parity.md).--**Definition of done** for any change touching config, credentials, a-provider/integration, or OS-specific code — verify the FOUR non-maintainer-paths (test or honest manual trace):--1. **Fresh install, ONE arbitrary key** reaches a working path (chat + voice- + Jarvis-Agent + the touched feature), entirely in-app.-2. **Headless Linux** — base install + boot + the feature on- `python:3.11-slim`; local-only parts degrade to a logged no-op.-3. **macOS** — works there, or degrades honestly + `docs/os-parity.md` entry.-4. **Cross-family fallback** — a dead/absent configured provider crosses to- whatever the user actually has, or degrades honestly.--"It works on my machine" is the *defect* — the maintainer's box is <0.1 % of-the install base. Doctrine: [`CLOUD.md`](CLOUD.md) +-[`docs/PHILOSOPHY.md`](docs/PHILOSOPHY.md) (doctrine wins). See AP-21/22/23.--### Device-parity triage ritual (BINDING)--"Works on the dev box, broken on device X" has THREE independent causes —-check in order, name the layer (runbook:-[`docs/device-parity-debugging.md`](docs/device-parity-debugging.md)):--1. **Version lag** — compare `GET /api/update/status` → `current` vs the dev- box; uncommitted/unpublished work exists nowhere else, and the in-app- updater only moves between **published** GitHub Releases.-2. **Setup divergence** — config, keys, and data never travel with the code;- key-aware fallbacks (AP-22) degrade QUIETLY, so "broken" is usually- "downgraded for lack of a key". Align providers, mode, and wake word- in-app before debugging.-3. **OS gap** — assumed only after 1+2 match; then the parity rules above- apply.-------## 4. Naming — internal "Jarvis-Agents", user-visible brand is DYNAMIC (BINDING)--1. **Internal name** (code identifiers, files, docs, comments, commits, log- lines, i18n KEYS, API paths): **Jarvis-Agents** / singular- **Jarvis-Agent**. No other internal names.-2. **User-visible brand** (UI labels, TTS output, transcript labels, API- strings the UI displays, tool-schema prose spoken by the router): derived- from the configured wake word — "Hey Ruben" → **"Ruben-Agent(s)"**, any- wake word likewise, neutral fallback **"Assistant-Agent"**. NEVER hardcode- a fixed name in a user-visible string. Plumbing: i18n token `{name}-Agent`;- `agentBrand`/`useAgentBrand` (`src/lib/agentBrand.ts`);- `agent_brand`/`agent_brand_from_name`- (`jarvis/brain/assistant_name.py`). Tests pin an arbitrary brand (e.g.- "Nova-Agent"), never the host's live wake-word config.--**Glossary:** the retired internal codenames ("Subagents" / "sub_jarvis" /-the old bridge codename) stay dead repo-wide. The old bridge codename-survives ONLY where functional: (a) the external `openclaw` npm worker-binary — an outside project; invocation strings, env vars, and install-commands stay literal; (b) read-time back-compat aliases that keep old-installs booting (`[brain.worker]`/`[harness.jarvis_agent]` still accept-`[brain.sub_jarvis]`/`[harness.openclaw]`; legacy `openclaw_state` dirs are-recognized) plus their pinning tests. Do not reintroduce it elsewhere — and-do not "clean up" those aliases or literal binary strings either.-------## 5. Architecture essentials (respect on every change)--Full model + module catalog:-[`docs/architecture-overview.md`](docs/architecture-overview.md).--- **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:** `jarvis/plugins/<group>/<name>.py`, registered- via `pyproject.toml` entry-points, no `jarvis.*` import in the plugin- module. After editing entry-points: `pip install -e . --no-deps`. Groups:- wakeword, stt, tts, brain, harness, tool, channel.-- **Streaming first:** Brain/STT/TTS/Harness methods return- `AsyncIterator[...]` (non-streaming yields one element).-- **Secrets** only via `jarvis.core.config.get_secret` (keyring → ENV →- `.env` → local file). Never in code / `jarvis.toml` / commits /- `.claude/`. Installer signing PRIVATE keys live ONLY in GitHub Actions- secrets (AP-29). Voice/chat must never accept secrets (AP-2).-- **Brain is multi-provider** — never hardcode Anthropic/Claude (AP-6); gate- on capabilities (`supports_vision`, `supports_tools`, `can_call_tools()`),- never provider/model ids (AP-21). Persona via- `jarvis/brain/persona_loader.py`, never hardcoded.-- **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). The- self-mod pipeline (Allowlist → Pre-Validate → Backup → replace → sync- reload-test → Rollback → Audit) is non-negotiable (AP-13/14).-- **CLI-first feature contract (mandate 2026-07-11):** every user-facing- capability ships its actions as REST routes under- `jarvis/ui/web/*_routes.py`, mounted + tagged (enforced by- `scripts/ci/check_cli_coverage.py`) — each action becomes a- `jarvis api <tag> <op>` CLI command automatically. UI-only / internal-only- / brain-tool-only features are NOT done. On top: voice/agent-relevant- actions add a Command-Registry entry (`jarvis/commands/registry.py`,- drift-gated by `gen_commands_reference.py --check`); destructive routes- declare `openapi_extra={"x-jarvis-dangerous": True}`- (`check_danger_metadata.py`); high-value routes get a curated- `jarvis <group> <command>` (checklist: the `generate-cli-command` skill).-- **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>/jarvis-agent-outputs/` (legacy `sub-agents-outputs/`- read as fallback) with kill-on-crash containment (Job Object on Windows,- process-group reaper on POSIX). Headless installs keep outputs + per-user- `HOME` under `JARVIS_DATA_DIR` (ADR-0027). `MAX_CRITIC_LOOPS = 3` is fixed.-- **Worker tool broker:** tools delegated to mission workers use a- short-lived, mission-scoped supervisor grant (ADR-0025); tool objects and- credentials stay in the supervisor; every call runs through `ToolExecutor`.- Recursive/skill/secret/config-mutation tools are never exported; an- unattended ask-tier action never becomes an implicit yes.-- **Native Windows Codex workers:** keep `--ignore-user-config`, use the- ACL-bounded `unelevated` sandbox, recover rejected file-change tools only- through BOM-free UTF-8 writes inside the current worktree (ADR-0026).-- **Platform gotchas:** UTF-8 stdout (Windows defaults cp1252); 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.-------## 6. Safety / risk tiers--Four tiers `safe` / `monitor` / `ask` / `block`, priority **blacklist >-whitelist > tool default** (`jarvis/safety/risk_tier.py`); whitelist-downgrades to `safe` (anti-confirmation-fatigue contract). Direct-`Tool.execute()` is a bug — only `ToolExecutor.execute()` is authorized-(AP-3). Generated skills land as `state="draft"`, never auto-activated-(AP-15).-------## 7. Critical anti-patterns (do not do this)--| # | If you do this... | ...you get this bug |-|---|---|---|-| AP-1 | `subprocess.Popen` without `NO_WINDOW_CREATIONFLAGS` | BUG-012 flicker storm under `pythonw.exe` |-| AP-2 | Accept API keys via voice/chat | STT log leak — credential exfiltration |-| AP-3 | Call `Tool.execute()` directly | Risk-tier/whitelist/plausibility skipped |-| AP-4 | Add a `hangup_reason`/mission-status string in one site only | BUG-008: HTTP 500, empty UI |-| AP-5 | Put a spawn/`dispatch-with-review`/`run-skill` tool in a worker tool set | Recursion: worker spawns supervisor |-| AP-6 | Hardcode the `Claude`/`Anthropic` API client | Breaks `cfg.brain.primary` for non-Anthropic users |-| AP-7 | Write `jarvis.toml` without `_WRITE_LOCK` + tempfile + BOM handling | BUG-018: corrupted TOML, backend won't boot |-| AP-8 | Skip `scripts/preflight.ps1` in a new worktree | BUG-006/014: edits go where live Python doesn't import from |-| AP-9 | Run awareness/wiki code in the voice critical path | Latency regression — awareness stays off the hot path |-| AP-10 | Write a worker without `git worktree` + Job Object | Races + zombie processes on crash |-| 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 |-| AP-13 | Block on watchdog reload for atomic-write verification | Race: file half-applied, no sync rollback |-| AP-14 | Re-add a sub-tier or `SUB_TOOLS` set | Breaks the agent-harness bridge contract |-| AP-15 | Auto-activate generated skills (`state` ≠ `draft`) | 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 watchdog without per-unit reset | BUG-032: watchdog fires between units, aborts a fresh answer |-| AP-20 | `continue` a WS receive loop on a non-`WebSocketDisconnect` error | Loop spins on a dead socket; catch `RuntimeError` and `break` |-| AP-21 | Pin a feature to a provider name/model id instead of a capability | Breaks for every other provider; fix the capability flag instead |-| AP-22 | Give a tier a primary AND fallback in the SAME provider family, or hardcode provider names in a chain | Single-provider brick; resolve every tier through one key-aware, family-crossing chain that degrades honestly |-| AP-23 | Build or test only against the maintainer's config/keys/OS and claim done | Whole surface bricked for every other downloader; verify §3's paths |-| AP-30 | Catch an exception and neither log, re-raise, nor say why silence is right | The feature just does nothing and nobody can tell it failed — the single largest source of "it only half works" (gate: `check_silent_exception_handlers.py`) |-| AP-31 | Add a config field nothing reads, or leave a switch whose value is ignored | `jarvis.toml` and the settings screen promise behaviour that does not exist (gate: `check_config_switches_wired.py`) |--### AP-24 — Never share a native inference engine between concurrent callers--ctranslate2/faster-whisper and ONNX/torch sessions are not thread-safe; a-concurrent call wedges them permanently, and a timeout only BOUNDS a hung-`to_thread`, never recovers it. Fix: a non-blocking per-instance inference-lock (second caller skips) + a `recover()` that rebuilds a FRESH model after-N failures (BUG-036). Never "recover" by re-polling the same wedged engine.--### AP-25 — Never enable GPU wake on CUDA *presence* or a hardware name--CUDA presence and CUDA *usability* diverge (a present-but-broken runtime once-left wake permanently deaf). Gate the GPU wake upgrade ONLY on the-out-of-process **inference probe**-(`jarvis.plugins.stt._wake_gpu_inference_verified`: one real turbo/cuda-transcribe in a killable subprocess, stdout-marker verdict — never the exit-code; cached per ctranslate2 version in `data/wake_gpu_probe.json`). Keep the-probe off the boot path (background hot-swap only), a FIXED `cpu_threads` on-the CPU floor, and the live backstop (a wedge swaps back to the retained-cpu fallback + `mark_wake_gpu_bad()`). `[stt].wake_high_accuracy=false` is-the hard opt-out. Truly instant custom-word wake needs a trained neural KWS-model, not transcription. Detail:-`docs/local-wakeword/WAKE-RELIABILITY-DEEPDIVE.md`.--### AP-26 — Never put a feature's init/import on the startup critical path--Nothing initializes before `APP_INTERACTIVE` / `VOICE_USABLE`: no sync load-in `_run_backend`, the `WebServer` ctor, or `_start_speech_and_orb`; no-module-level heavy import. New subsystems hook into `_heavy_backend_bg`, a-deferred registry scan, or a post-ready task; heavy imports stay lazy; routes-answer 503/None while warming. Measured by the BOOT BUDGET harness-(`scripts/ci/check_boot_budget.py`: window ≤ 8 s, voice-usable +-app-interactive ≤ 20 s). It is an **on-demand local command**, not a push-gate (2026-08-05): it boots the whole application, so as a pre-push hook it-cost a full cold boot per push and counted the inevitable failed boot of a-dependency-less fresh worktree as a budget violation. It has no CI home-either — a GitHub runner has no audio device, so the harness cannot measure-`VOICE_USABLE` there and would either self-skip or false-fail. Run it by-hand after touching the startup path:-`python scripts/ci/check_boot_budget.py`. Doctrine:-`docs/diagnostics/BOOT-TTU-NOTES.md`.--### AP-27 — Never gate a wake word on transcript CONTENT--This is a property of EVERY wake engine that verifies via a transcript, not-an engine quirk: a bias-primed model hallucinates the phrase on silence AND-garbles it on real speech, and every wake word is out-of-vocabulary for some-installed language model — so any content rule that suppresses ghosts also-rejects genuine wakes ("fires on silence" and "goes deaf" share ONE root),-and no spelling threshold can separate them. Verify only on WORD-AGNOSTIC-properties: raw audio ENERGY at the match site (`stt_match`:-`RollingWhisperWake._match_min_rms`; keep the bias-echo confirm PERMISSIVE-and skip it on a loud window) and the SHAPE of the candidate span-(`vosk_kws`: `candidate_shape_ok` — duration, word count, free-decoder-confidence, all derived from the configured phrase, never its spelling). A-spelling match may only ever ACCEPT (bonus path), never reject. Guards:-`tests/unit/speech/test_rolling_whisper_wake_silence_ghost.py`,-`tests/unit/plugins/wake/test_vosk_wake_word_agnostic.py`. Measurements +-history: `docs/local-wakeword/WAKE-RELIABILITY-DEEPDIVE.md`, BUG-037.--### AP-28 — Never gate CI checks on `isinstance` against an unpinned third-party lib--CI installs newest; the lib's next release changes internals and the gate-false-fails in CI while green locally (Typer 0.26 vendored its own Click,-fix 621f837a). Discriminate by CAPABILITY (`.commands`, Click's stable-`param_type_name`), never concrete type. Before anything goes public: CI must-be green and every red cause understood — reproduce against the SAME unpinned-versions CI installs, not your local pins.--### AP-29 — Never commit a signing PRIVATE key, its passphrase, or a `*.key.enc` copy--Installer signing private keys (Wave 2 Ed25519, Wave 4 ML-DSA-65) live ONLY-in GitHub Actions secrets (`WAVE2_OFFLINE_KEY_B64` / `WAVE4_MLDSA65_KEY_B64`),-backup in the maintainer's password manager; the repo holds ONLY public keys-(`install/keys/*.pub*`) + inlined verifier copies. (An earlier in-repo-"encrypted at rest" scheme leaked its passphrase into 14 permanent public-snapshots.) Rotation = new keypair → `gh secret set` → swap public keys +-verifier blocks + fingerprints. Enforced by-`scripts/ci/check_no_private_keys.py` (pre-commit + pre-push). Doctrine:-`docs/supply-chain/wave2-key-ceremony.md`.-------## 8. Recurring bug classes (signal → defense)--Detail in [`docs/BUGS.md`](docs/BUGS.md):--1. **Restore trap** (BUG-006/014/015) — fix "works in tests" but behavior- unchanged after restart → `pwsh scripts/preflight.ps1` +- `python -c "import jarvis; print(jarvis.__file__)"`.-2. **Enum drift** (BUG-008) — empty UI list while the DB has rows, Pydantic- `literal_error` → five-layer pattern + parity test.-3. **Config drift** (BUG-010) — parallel sessions silently rolling back- `jarvis.toml` switches → `scripts/drift-guard-daemon.ps1` + ENV overrides- + BOM-safe writer.-4. **Console flicker** (BUG-012) — import `NO_WINDOW_CREATIONFLAGS` from- `jarvis.core.process_utils`.-5. **Audio host-API trap** (BUG-014) — WDM-KS auto-picked, PortAudio crashes- → `_FORBIDDEN_OUTPUT_HOSTAPIS` + shortest-unique-token matching.-6. **Stale watchdog counter** (BUG-032) — watchdog fires between units →- reset the counter per unit of work (AP-19).-7. **Socket loop on teardown error** — treat any read error as terminal,- `break` (AP-20).-8. **Wedged native inference** (BUG-036) — non-blocking lock + rebuild a- fresh model (AP-24).-9. **Wake transcript traps** (BUG-037) — "fires on silence" / "goes deaf on- its own wake word" share one root; word-agnostic verification only- (AP-27).-------## 9. Operational reality & Git workflow--- **The working tree is frequently SHARED** — several 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 normal. On a- corrupted-looking index/HEAD, recover via temp-index commit + `update-ref`- CAS + safety branch (`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 need- this restart to take effect.-- **Jarvis is used as a DESKTOP APP, not a browser tab.** The window is an- embedded WebView (`jarvis/ui/desktop_app.py`) with no address bar, no- reload button and no dev tools, so "press Ctrl+R / F5", "hard-refresh",- "clear the browser cache" and "open the console" are instructions that- cannot be followed — never end a frontend change with one. A frontend fix- reaches the user in exactly two steps: `npm run build` in- `jarvis/ui/web/frontend/` (the app serves the built `dist/`, never Vite),- then the **Restart** button in the app's top bar, which is on every screen- and posts to the endpoint above. Say that, and say that a restart takes- live terminal panes with it — they reattach or resume, but it is not free.- Running from a browser against `--dev` is a contributor path, not the- maintainer's.-- **New worktree:** run `pwsh scripts/preflight.ps1` before writing code;- non-zero exit → fix first (BUG-006/014).-- **Memory:** check `MEMORY.md` (`~/.claude/projects/.../memory/`) before- larger decisions.-- **Plan vs. code:** on conflict, the plan wins- (`~/.claude/plans/also-er-muss-auch-lexical-pond.md`); deviations get <!-- i18n-allow -->- documented back in the plan.--### Git workflow--*(Also pinned in the maintainer's personal global config; restated here so-every contributor and agent follows it.)*--- **Auto-commit after each completed logical step**, staging only YOUR files- by explicit path or `git add -p` — never `git add -A` / `git add .`- (sweeps another session's in-flight, possibly secret-bearing work in).-- **Conventional-Commit messages** (`feat:`, `fix:`, `refactor:`, `docs:`,- `chore:`).-- **Never push automatically** — only when the maintainer explicitly says so- (still honoring §2).-- **Never commit secrets / `.env` / keys / tokens.** If any appear- untracked: stop, flag, don't commit.-- **Pushing is one command.** `git push <remote> <branch>` — nothing is built,- copied, cloned, or audited on the way (§2). The hooks take about a second- and a half; if a push turns into a work session, something regrew that- belongs in CI. When a hook does block, it found a credential: fix the- finding, never reach for `--no-verify` as the first move.-----+Binding rules for every coding agent — compressed index. The FULL contract+(same section numbers, unabridged wording + rationale) lives in+[`docs/agent-contract.md`](docs/agent-contract.md); read it before deep work.++## 0. Mirror rule (BINDING)+`CLAUDE.md` ≡ `AGENTS.md` (byte-identical twins); `.claude/{agents,commands,skills}/`+≡ `.agents/{...}`. Sync engines run as hook, pre-commit, and CI gate. Everything+in them addresses EVERY coding agent, never Claude Code alone.++## 1. Language (BINDING, HIGHEST PRIORITY)+Every committed artifact is ENGLISH — code, comments, docs, commits, tests, CLI+help, UI source strings. German ONLY on the closed product surface (runtime+voice/chat output, i18n files, speech-input vocabulary, tests quoting them);+register: `scripts/ci/german-allowlist.txt` / inline `i18n-allow`. Translate+legacy German you touch. Runtime output language: ONE resolver+(`jarvis/core/turn_language.py::resolve_output_language`) decides each turn for+ALL layers (reply, acks, canned phrases, TTS voice); no layer re-derives it;+all locales (de/en/es/…) are equal.++## 2. GitHub (BINDING)+ONE public repo: `github.com/PersonalJarvis/PersonalJarvis`. **A push is+`git push`** — no staging trees, clones, builds, or file-by-file audits.+Protection: `.gitignore` first (data/, .env, jarvis.toml, Vault, keys never+tracked); never commit credentials; secret scanning stays ON; whole-tree checks+belong in CI, never pre-push. Default = plain push; Release ONLY when+explicitly asked (SemVer + tag + CHANGELOG + published GitHub Release;+`check_release_completeness.py` before tagging and `--verify-release` after).+Never push unless the maintainer asks.++## 3. Open-source universality (BINDING)+Assume an arbitrary downloader, never the maintainer: ANY single key/provider+works (capability-gated, cross-family fallback, honest degradation, AP-21/22);+every OS incl. headless `python:3.11-slim` (base install stays torch-free; GPU+deps only in `[local-voice]`); credentials recoverable IN-APP, stored keyring →+ENV → file. macOS/Linux ship in the SAME change behind one capability probe or+degrade honestly (+ `docs/os-parity.md` entry). Definition of done = the four+non-maintainer paths (§3 detail). Device triage order: version lag → setup+divergence → OS gap (`docs/device-parity-debugging.md`).++## 4. Naming (BINDING)+Internal: **Jarvis-Agents**. User-visible brand is DYNAMIC from the wake word+(`{name}-Agent`, fallback "Assistant-Agent") — never hardcode a name in a+user-visible string. Retired codenames stay dead; the external `openclaw`+binary strings and the read-time back-compat aliases stay AS-IS.++## 5. Architecture essentials+8-layer rule (protocols downward, frozen events on `EventBus` laterally);+plugins via entry-points, no `jarvis.*` import inside (after entry-point edits:+`pip install -e . --no-deps`); streaming-first (`AsyncIterator`); secrets only+via `get_secret`; brain is multi-provider + capability-gated (never hardcode a+provider/model); router = pure dispatcher over `ROUTER_TOOLS` (ADR-0011);+`scrub_for_voice` is regex-only; `jarvis.toml` only via `config_writer.py`;+CLI-first contract (every feature ships REST routes → auto-CLI + registry entry++ danger metadata); five-layer enum pattern for any cross-layer value; mission+workers in fresh git worktrees with kill-on-crash + tool broker (ADR-0025/26);+UTF-8 + `NO_WINDOW_CREATIONFLAGS` on every subprocess. Safety: tiers+safe/monitor/ask/block, blacklist > whitelist > default; only+`ToolExecutor.execute()`; generated skills stay `state="draft"`.++## 7. Anti-patterns AP-1..AP-31 (BINDING)+Full register with the bug each causes: `docs/agent-contract.md` §7. Essence:+no subprocess without `NO_WINDOW_CREATIONFLAGS`; no keys via voice/chat; enum+strings land in ALL five layers; no spawn tools in worker sets; atomic TOML+writes only; preflight every new worktree; nothing heavy on the boot critical+path; no LLM in the voice scrubber; native inference engines get a per-instance+lock + fresh-model recover; GPU wake gates ONLY on the inference probe; wake+verification is word-agnostic, never transcript content; no `isinstance` gates+on unpinned libs; signing private keys ONLY in GitHub Actions secrets; no+silent `except`; no config switch nothing reads.++## 8. Recurring bug classes+Restore trap (`pwsh scripts/preflight.ps1` + `python -c "import jarvis;+print(jarvis.__file__)"`), enum drift, config drift, console flicker, WDM-KS+audio, stale watchdog counters, socket teardown loops, wedged native+inference, wake transcript traps → [`docs/BUGS.md`](docs/BUGS.md).++## 9. Operational reality & git+The working tree is SHARED by parallel sessions: stage only YOUR files+(`git add -p` / pathspec, never `git add -A` / `git add .`); auto-commit each+logical step with Conventional-Commit messages; never push automatically;+never commit secrets. App restart = `POST /api/settings/restart-app` (never+`Stop-Process`); the app is a desktop WebView without F5/console — a frontend+fix = `npm run build` in `jarvis/ui/web/frontend/` + the in-app Restart+button. Check `MEMORY.md` before larger decisions.## 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--# 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/--# Frontend (jarvis/ui/web/frontend/)-npm install && npm run dev # build → npm run build ; tests → npm run test-```--```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 (self-skips when prereqs missing)-pytest tests/missions/ -v # Phase 6-pytest -m "not slow" # fast subset-# 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/.-```-----+Install: `pip install -e . --no-deps` + `pip install -r requirements.txt` ++`pip install -e ".[dev]"`. Launch: `run.bat` (`--headless` = API/WS only).+Lint: `ruff check jarvis/ && ruff format jarvis/ && mypy jarvis/`. Tests:+`pytest tests/` (fakes in `tests/fakes/`, not mocks; fast: `-m "not slow"`);+guards `test_routing.py`, `test_output_filter.py`,+`test_hangup_reason_parity.py`; new providers pass `tests/contract/`.## 11. Pointers--- **Architecture + module catalog:**- [`docs/architecture-overview.md`](docs/architecture-overview.md).-- **Doctrine:** [`CLOUD.md`](CLOUD.md),- [`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 a terminal/agent):- `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`.+[`docs/agent-contract.md`](docs/agent-contract.md) (FULL contract) ·+[`docs/architecture-overview.md`](docs/architecture-overview.md) ·+[`CLOUD.md`](CLOUD.md) · [`docs/PHILOSOPHY.md`](docs/PHILOSOPHY.md) ·+[`docs/BUGS.md`](docs/BUGS.md) · `docs/adr/` ·+[`docs/jarvis-cli.md`](docs/jarvis-cli.md).diff --git a/CLAUDE.md b/CLAUDE.mdindex 2a26374807..5a0d709b28 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -1,566 +1,101 @@# CLAUDE.md-Binding rules for any coding agent in this repo — respect them on **every**-change. Architecture and product detail:-[`docs/architecture-overview.md`](docs/architecture-overview.md).-------## 0. Mirror rule — CLAUDE.md ≡ AGENTS.md, .claude/ ≡ .agents/ (BINDING)--`CLAUDE.md` is canonical; `AGENTS.md` is its **byte-identical twin** for other-tools. The same holds for the versioned agent-knowledge trees:-`.claude/{agents,commands,skills}/` ↔ `.agents/{agents,commands,skills}/` —-everything in them addresses **every** coding agent (Codex, Gemini CLI, ...),-never Claude Code alone; write it accordingly. Sync engines-`scripts/ci/sync_agents_md.py` / `sync_agents_dir.py` run as a live-`PostToolUse` hook, `.githooks/pre-commit --stage`, and a `--check` CI gate;-after editing either side, sync before committing. Deletions propagate.-Gitignored/private entries (e.g. `.claude/skills/security-github/`) stay out-of the mirror on both sides.-------## 1. Language — English-only artifacts, fail-closed (BINDING, HIGHEST PRIORITY)--Personal Jarvis is an international open-source project — assume an arbitrary-downloader anywhere on earth. **Everything an agent commits is English**: code,-comments, docstrings, log/exception/error messages, Markdown (READMEs, ADRs,-plans, handoffs, forensic docs), `SKILL.md`, commit messages, PR/issue text,-test names and docstrings, CLI help, route/schema descriptions, telemetry-names, UI strings (i18n key + **English** source). When in doubt, English.-Never invent a new German-allowed category — ask instead of committing German.--**The ONLY German permitted — the multilingual product surface (CLOSED list):**--1. **Runtime voice/TTS + chat output** — governed by the resolver below.-2. **i18n / locale source files + the website's localized copy** — German- there *is* the product.-3. **Speech-recognition input vocabulary** — German tokens a classifier must- literally contain to match German utterances. Matching *data*, not prose.-4. **Tests / fixtures + forensic voice-bug deep-dives** quoting 1–3 as the- content under test.--Materialized file-by-file in `scripts/ci/german-allowlist.txt` — a curated,-justified register, never a free pass: every entry names its reason, and an-inline `i18n-allow` comment on the one load-bearing line beats a whole-file-exemption. **Pre-existing German is backlog, not protected:** when you edit a-file and pass non-product-surface German, translate it on the way through —-never preserve or extend it. The CI gate (`scripts/ci/check_no_new_german.py`)-only sees what a diff ADDS, so the agent is the first line of defense.-Conversation language is each contributor's own choice (personal global-config); the repo fixes only the artifacts.--### Runtime output language (voice + chat) — BINDING--Supported locales are equal — `de`, `en`, `es`, any future one; never a-German- or English-only bias. This governs what Jarvis speaks/writes back and-does NOT weaken the English-artifact rule.--1. **One resolver decides a turn's output language** —- `jarvis/core/turn_language.py::resolve_output_language`. Precedence:- `brain.reply_language` pin → conversation stickiness (a one/two-word- interjection must NOT flip it; only a substantive turn switches) → detected- input language → `DEFAULT_LOCALE`.-2. It applies to **ALL user-facing output**: deep reply, ack preamble, spawn- announcements, every canned status/error/clarify phrase, deterministic- readbacks, AND the TTS voice/BCP-47 pick. A mid-session flip between- layers is a bug.-3. **No layer re-derives the language** — no `_looks_german()`-style- heuristics (drops `es`), no de/en-only phrase table, no per-layer default.- New phrase tables carry ALL supported languages and resolve through the- one resolver.-4. A layer that genuinely can't tell falls back to `DEFAULT_LOCALE`. Durable- pin: `brain.reply_language` (`auto` | `de` | `en` | `es`), editable in the- desktop **Languages** view. Guards: `tests/unit/core/test_turn_language.py`,- `tests/unit/speech/test_phrase_language.py`,- `tests/unit/brain/test_*language*.py`.-------## 2. GitHub — ONE public repo, fail-closed credential protection (BINDING)--The ONE project repo is the public flagship-**`https://github.com/PersonalJarvis/PersonalJarvis`**; every maintainer-"commit / push / save to GitHub / sichere den Stand" targets it — never ask-"which repo". <!-- i18n-allow: quoted German maintainer trigger phrase -->-Lowercase `personal-jarvis` (remote `origin`) is a silent local backup, never-the deliverable. The former depersonalization/snapshot gate is RETIRED-(maintainer directive 2026-07-17): ONE shared git history, every machine-pushes and pulls it normally.--**A push is `git push`.** This repo is an ordinary open-source project and-ships like one. Forbidden as part of pushing (maintainer directive-2026-08-05, after a measured ~440k tokens per push): building a parallel-"clean" staging tree, cloning the target repo to reconcile into, running-`npm ci`/a frontend build, and above all dispatching a sub-agent to read-every file in the tree looking for personal data. That audit re-read 5,481-already-published files on every push; a regex scan, `.gitignore`, and-GitHub's own push protection already cover it. If you find yourself-preparing a snapshot instead of pushing a commit, stop — that is the-retired gate growing back.--What remains, fail-closed:--1. **`.gitignore` first** — `data/`, `.env`, `jarvis.toml`, the Vault, and- key material are never tracked. This is the load-bearing layer: nothing- personal is in the tree, so nothing personal can be pushed.-2. **Never commit credentials** — API keys, tokens, private keys (incl.- `*.key.enc`, AP-29), passphrases. `check_no_private_keys.py` + the secret- sweep stay wired in pre-commit and pre-push.-3. **GitHub secret scanning + push protection stay ON.** A blocked push is a- real finding: stop and fix — never bypass or allowlist around it.-4. **Trademark/brand review is a human release checkpoint** — flag concerns- to the maintainer instead of shipping them.--**Gate placement is a rule, not a preference.** A check that reads the whole-tree belongs in CI (`.github/workflows/ci.yml`), never in `pre-push`. Only a-check that (a) judges the pushed change alone and (b) guards something-unrecoverable — a leaked credential — may block a push. Everything else-reports on GitHub's runners, where a red result costs a notification rather-than a debugging session. Adding a gate to `.githooks/pre-push` requires the-maintainer's explicit say-so; adding one to CI does not.--**Two volumes:** *Update (DEFAULT)* — "push", "sichere den Stand" → normal-push, no bump/tag/release. *Release (explicit only)* — "Mach ein Release",-"mach eine neue Version" → SemVer bump + tag + CHANGELOG, shipping the ENTIRE-current local state (reconcile with `public/main` first; never knowingly ship-a release lacking local fixes without saying so). <!-- i18n-allow: quoted German maintainer trigger phrases -->-When ambiguous, update. **Pre-tag gate:** run-`python scripts/ci/check_release_completeness.py` before tagging and again-with `--verify-release` after publishing — a pushed tag without a *published*-GitHub Release updates no managed install.--**Do not PUSH unless the maintainer asks** (local auto-commit per §9).-Releases are cut from the dev-machine line; a session on another machine-ports its work back to `main` instead of cutting its own releases. Doctrine:-[`CLOUD.md`](CLOUD.md).-------## 3. Open-source universality — the maintainer's config is NEVER the baseline (BINDING)--**Assume an arbitrary downloader, never the maintainer.** This governs the-whole product surface and the entire credential/integration surface — brains,-STT, TTS, Vision, Wake, Telephony, Channels, Marketplace plugins (OAuth +-MCP), and credential STORAGE itself. Every one must:--- **Work with WHATEVER single key/login the user has** — no provider, model,- or integration is load-bearing; a missing / depleted / 429 / 402 /- unreachable one degrades or crosses to a **different family** with an- honest message, never bricking a core path. Primary AND fallback in the- same family = a single-provider brick (AP-22); gate on **capability**,- never a provider name/model id (AP-21).-- **Work on EVERY OS, incl. a headless `python:3.11-slim` VPS** with no- keyring, GPU, audio, or Windows APIs — base `pip install` + boot must- succeed there. Use `pathlib` + capability probes + UTF-8; never hardcode- `C:\Users\...` or assume cp1252. **Base install stays torch-/GPU-free**,- enforced by `check_requirements_sync.py` + `check_lockfile_universal.py`- (GPU/torch deps live only in the opt-in `[local-voice]` extra); regenerate- the lock only with `uv pip compile --universal`. The ONE advertised install- path is the `[full]` profile; the torch-free base is the internal floor for- CI and tiny servers (`--headless`).-- **Be recoverable IN-APP** — entering/switching/recovering a credential- never requires hand-editing `jarvis.toml` or exporting ENV vars.-- **Store credentials portably** — OS keyring → ENV/.env → local-file- fallback (`config._ensure_keyring_backend`); a save/connect must never 500- on a host without a Secret Service.--### OS feature parity — macOS and Linux are first-class (BINDING)--Every feature ships working on **all three OSes in the SAME change**, never-as a "later" follow-up. OS-specific backends live behind ONE capability probe-(Win32/UIA ↔ AppleScript/Quartz/AXUIElement ↔ xdotool/AT-SPI/D-Bus);-`sys.platform == "win32"` with silent nothing elsewhere is a defect. Where a-backend is genuinely impossible (headless), degrade to a clearly-messaged-English no-op. A Windows-only implementation lands ONLY with the capability-gate + honest degradation + a tracked entry in-[`docs/os-parity.md`](docs/os-parity.md).--**Definition of done** for any change touching config, credentials, a-provider/integration, or OS-specific code — verify the FOUR non-maintainer-paths (test or honest manual trace):--1. **Fresh install, ONE arbitrary key** reaches a working path (chat + voice- + Jarvis-Agent + the touched feature), entirely in-app.-2. **Headless Linux** — base install + boot + the feature on- `python:3.11-slim`; local-only parts degrade to a logged no-op.-3. **macOS** — works there, or degrades honestly + `docs/os-parity.md` entry.-4. **Cross-family fallback** — a dead/absent configured provider crosses to- whatever the user actually has, or degrades honestly.--"It works on my machine" is the *defect* — the maintainer's box is <0.1 % of-the install base. Doctrine: [`CLOUD.md`](CLOUD.md) +-[`docs/PHILOSOPHY.md`](docs/PHILOSOPHY.md) (doctrine wins). See AP-21/22/23.--### Device-parity triage ritual (BINDING)--"Works on the dev box, broken on device X" has THREE independent causes —-check in order, name the layer (runbook:-[`docs/device-parity-debugging.md`](docs/device-parity-debugging.md)):--1. **Version lag** — compare `GET /api/update/status` → `current` vs the dev- box; uncommitted/unpublished work exists nowhere else, and the in-app- updater only moves between **published** GitHub Releases.-2. **Setup divergence** — config, keys, and data never travel with the code;- key-aware fallbacks (AP-22) degrade QUIETLY, so "broken" is usually- "downgraded for lack of a key". Align providers, mode, and wake word- in-app before debugging.-3. **OS gap** — assumed only after 1+2 match; then the parity rules above- apply.-------## 4. Naming — internal "Jarvis-Agents", user-visible brand is DYNAMIC (BINDING)--1. **Internal name** (code identifiers, files, docs, comments, commits, log- lines, i18n KEYS, API paths): **Jarvis-Agents** / singular- **Jarvis-Agent**. No other internal names.-2. **User-visible brand** (UI labels, TTS output, transcript labels, API- strings the UI displays, tool-schema prose spoken by the router): derived- from the configured wake word — "Hey Ruben" → **"Ruben-Agent(s)"**, any- wake word likewise, neutral fallback **"Assistant-Agent"**. NEVER hardcode- a fixed name in a user-visible string. Plumbing: i18n token `{name}-Agent`;- `agentBrand`/`useAgentBrand` (`src/lib/agentBrand.ts`);- `agent_brand`/`agent_brand_from_name`- (`jarvis/brain/assistant_name.py`). Tests pin an arbitrary brand (e.g.- "Nova-Agent"), never the host's live wake-word config.--**Glossary:** the retired internal codenames ("Subagents" / "sub_jarvis" /-the old bridge codename) stay dead repo-wide. The old bridge codename-survives ONLY where functional: (a) the external `openclaw` npm worker-binary — an outside project; invocation strings, env vars, and install-commands stay literal; (b) read-time back-compat aliases that keep old-installs booting (`[brain.worker]`/`[harness.jarvis_agent]` still accept-`[brain.sub_jarvis]`/`[harness.openclaw]`; legacy `openclaw_state` dirs are-recognized) plus their pinning tests. Do not reintroduce it elsewhere — and-do not "clean up" those aliases or literal binary strings either.-------## 5. Architecture essentials (respect on every change)--Full model + module catalog:-[`docs/architecture-overview.md`](docs/architecture-overview.md).--- **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:** `jarvis/plugins/<group>/<name>.py`, registered- via `pyproject.toml` entry-points, no `jarvis.*` import in the plugin- module. After editing entry-points: `pip install -e . --no-deps`. Groups:- wakeword, stt, tts, brain, harness, tool, channel.-- **Streaming first:** Brain/STT/TTS/Harness methods return- `AsyncIterator[...]` (non-streaming yields one element).-- **Secrets** only via `jarvis.core.config.get_secret` (keyring → ENV →- `.env` → local file). Never in code / `jarvis.toml` / commits /- `.claude/`. Installer signing PRIVATE keys live ONLY in GitHub Actions- secrets (AP-29). Voice/chat must never accept secrets (AP-2).-- **Brain is multi-provider** — never hardcode Anthropic/Claude (AP-6); gate- on capabilities (`supports_vision`, `supports_tools`, `can_call_tools()`),- never provider/model ids (AP-21). Persona via- `jarvis/brain/persona_loader.py`, never hardcoded.-- **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). The- self-mod pipeline (Allowlist → Pre-Validate → Backup → replace → sync- reload-test → Rollback → Audit) is non-negotiable (AP-13/14).-- **CLI-first feature contract (mandate 2026-07-11):** every user-facing- capability ships its actions as REST routes under- `jarvis/ui/web/*_routes.py`, mounted + tagged (enforced by- `scripts/ci/check_cli_coverage.py`) — each action becomes a- `jarvis api <tag> <op>` CLI command automatically. UI-only / internal-only- / brain-tool-only features are NOT done. On top: voice/agent-relevant- actions add a Command-Registry entry (`jarvis/commands/registry.py`,- drift-gated by `gen_commands_reference.py --check`); destructive routes- declare `openapi_extra={"x-jarvis-dangerous": True}`- (`check_danger_metadata.py`); high-value routes get a curated- `jarvis <group> <command>` (checklist: the `generate-cli-command` skill).-- **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>/jarvis-agent-outputs/` (legacy `sub-agents-outputs/`- read as fallback) with kill-on-crash containment (Job Object on Windows,- process-group reaper on POSIX). Headless installs keep outputs + per-user- `HOME` under `JARVIS_DATA_DIR` (ADR-0027). `MAX_CRITIC_LOOPS = 3` is fixed.-- **Worker tool broker:** tools delegated to mission workers use a- short-lived, mission-scoped supervisor grant (ADR-0025); tool objects and- credentials stay in the supervisor; every call runs through `ToolExecutor`.- Recursive/skill/secret/config-mutation tools are never exported; an- unattended ask-tier action never becomes an implicit yes.-- **Native Windows Codex workers:** keep `--ignore-user-config`, use the- ACL-bounded `unelevated` sandbox, recover rejected file-change tools only- through BOM-free UTF-8 writes inside the current worktree (ADR-0026).-- **Platform gotchas:** UTF-8 stdout (Windows defaults cp1252); 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.-------## 6. Safety / risk tiers--Four tiers `safe` / `monitor` / `ask` / `block`, priority **blacklist >-whitelist > tool default** (`jarvis/safety/risk_tier.py`); whitelist-downgrades to `safe` (anti-confirmation-fatigue contract). Direct-`Tool.execute()` is a bug — only `ToolExecutor.execute()` is authorized-(AP-3). Generated skills land as `state="draft"`, never auto-activated-(AP-15).-------## 7. Critical anti-patterns (do not do this)--| # | If you do this... | ...you get this bug |-|---|---|---|-| AP-1 | `subprocess.Popen` without `NO_WINDOW_CREATIONFLAGS` | BUG-012 flicker storm under `pythonw.exe` |-| AP-2 | Accept API keys via voice/chat | STT log leak — credential exfiltration |-| AP-3 | Call `Tool.execute()` directly | Risk-tier/whitelist/plausibility skipped |-| AP-4 | Add a `hangup_reason`/mission-status string in one site only | BUG-008: HTTP 500, empty UI |-| AP-5 | Put a spawn/`dispatch-with-review`/`run-skill` tool in a worker tool set | Recursion: worker spawns supervisor |-| AP-6 | Hardcode the `Claude`/`Anthropic` API client | Breaks `cfg.brain.primary` for non-Anthropic users |-| AP-7 | Write `jarvis.toml` without `_WRITE_LOCK` + tempfile + BOM handling | BUG-018: corrupted TOML, backend won't boot |-| AP-8 | Skip `scripts/preflight.ps1` in a new worktree | BUG-006/014: edits go where live Python doesn't import from |-| AP-9 | Run awareness/wiki code in the voice critical path | Latency regression — awareness stays off the hot path |-| AP-10 | Write a worker without `git worktree` + Job Object | Races + zombie processes on crash |-| 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 |-| AP-13 | Block on watchdog reload for atomic-write verification | Race: file half-applied, no sync rollback |-| AP-14 | Re-add a sub-tier or `SUB_TOOLS` set | Breaks the agent-harness bridge contract |-| AP-15 | Auto-activate generated skills (`state` ≠ `draft`) | 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 watchdog without per-unit reset | BUG-032: watchdog fires between units, aborts a fresh answer |-| AP-20 | `continue` a WS receive loop on a non-`WebSocketDisconnect` error | Loop spins on a dead socket; catch `RuntimeError` and `break` |-| AP-21 | Pin a feature to a provider name/model id instead of a capability | Breaks for every other provider; fix the capability flag instead |-| AP-22 | Give a tier a primary AND fallback in the SAME provider family, or hardcode provider names in a chain | Single-provider brick; resolve every tier through one key-aware, family-crossing chain that degrades honestly |-| AP-23 | Build or test only against the maintainer's config/keys/OS and claim done | Whole surface bricked for every other downloader; verify §3's paths |-| AP-30 | Catch an exception and neither log, re-raise, nor say why silence is right | The feature just does nothing and nobody can tell it failed — the single largest source of "it only half works" (gate: `check_silent_exception_handlers.py`) |-| AP-31 | Add a config field nothing reads, or leave a switch whose value is ignored | `jarvis.toml` and the settings screen promise behaviour that does not exist (gate: `check_config_switches_wired.py`) |--### AP-24 — Never share a native inference engine between concurrent callers--ctranslate2/faster-whisper and ONNX/torch sessions are not thread-safe; a-concurrent call wedges them permanently, and a timeout only BOUNDS a hung-`to_thread`, never recovers it. Fix: a non-blocking per-instance inference-lock (second caller skips) + a `recover()` that rebuilds a FRESH model after-N failures (BUG-036). Never "recover" by re-polling the same wedged engine.--### AP-25 — Never enable GPU wake on CUDA *presence* or a hardware name--CUDA presence and CUDA *usability* diverge (a present-but-broken runtime once-left wake permanently deaf). Gate the GPU wake upgrade ONLY on the-out-of-process **inference probe**-(`jarvis.plugins.stt._wake_gpu_inference_verified`: one real turbo/cuda-transcribe in a killable subprocess, stdout-marker verdict — never the exit-code; cached per ctranslate2 version in `data/wake_gpu_probe.json`). Keep the-probe off the boot path (background hot-swap only), a FIXED `cpu_threads` on-the CPU floor, and the live backstop (a wedge swaps back to the retained-cpu fallback + `mark_wake_gpu_bad()`). `[stt].wake_high_accuracy=false` is-the hard opt-out. Truly instant custom-word wake needs a trained neural KWS-model, not transcription. Detail:-`docs/local-wakeword/WAKE-RELIABILITY-DEEPDIVE.md`.--### AP-26 — Never put a feature's init/import on the startup critical path--Nothing initializes before `APP_INTERACTIVE` / `VOICE_USABLE`: no sync load-in `_run_backend`, the `WebServer` ctor, or `_start_speech_and_orb`; no-module-level heavy import. New subsystems hook into `_heavy_backend_bg`, a-deferred registry scan, or a post-ready task; heavy imports stay lazy; routes-answer 503/None while warming. Measured by the BOOT BUDGET harness-(`scripts/ci/check_boot_budget.py`: window ≤ 8 s, voice-usable +-app-interactive ≤ 20 s). It is an **on-demand local command**, not a push-gate (2026-08-05): it boots the whole application, so as a pre-push hook it-cost a full cold boot per push and counted the inevitable failed boot of a-dependency-less fresh worktree as a budget violation. It has no CI home-either — a GitHub runner has no audio device, so the harness cannot measure-`VOICE_USABLE` there and would either self-skip or false-fail. Run it by-hand after touching the startup path:-`python scripts/ci/check_boot_budget.py`. Doctrine:-`docs/diagnostics/BOOT-TTU-NOTES.md`.--### AP-27 — Never gate a wake word on transcript CONTENT--This is a property of EVERY wake engine that verifies via a transcript, not-an engine quirk: a bias-primed model hallucinates the phrase on silence AND-garbles it on real speech, and every wake word is out-of-vocabulary for some-installed language model — so any content rule that suppresses ghosts also-rejects genuine wakes ("fires on silence" and "goes deaf" share ONE root),-and no spelling threshold can separate them. Verify only on WORD-AGNOSTIC-properties: raw audio ENERGY at the match site (`stt_match`:-`RollingWhisperWake._match_min_rms`; keep the bias-echo confirm PERMISSIVE-and skip it on a loud window) and the SHAPE of the candidate span-(`vosk_kws`: `candidate_shape_ok` — duration, word count, free-decoder-confidence, all derived from the configured phrase, never its spelling). A-spelling match may only ever ACCEPT (bonus path), never reject. Guards:-`tests/unit/speech/test_rolling_whisper_wake_silence_ghost.py`,-`tests/unit/plugins/wake/test_vosk_wake_word_agnostic.py`. Measurements +-history: `docs/local-wakeword/WAKE-RELIABILITY-DEEPDIVE.md`, BUG-037.--### AP-28 — Never gate CI checks on `isinstance` against an unpinned third-party lib--CI installs newest; the lib's next release changes internals and the gate-false-fails in CI while green locally (Typer 0.26 vendored its own Click,-fix 621f837a). Discriminate by CAPABILITY (`.commands`, Click's stable-`param_type_name`), never concrete type. Before anything goes public: CI must-be green and every red cause understood — reproduce against the SAME unpinned-versions CI installs, not your local pins.--### AP-29 — Never commit a signing PRIVATE key, its passphrase, or a `*.key.enc` copy--Installer signing private keys (Wave 2 Ed25519, Wave 4 ML-DSA-65) live ONLY-in GitHub Actions secrets (`WAVE2_OFFLINE_KEY_B64` / `WAVE4_MLDSA65_KEY_B64`),-backup in the maintainer's password manager; the repo holds ONLY public keys-(`install/keys/*.pub*`) + inlined verifier copies. (An earlier in-repo-"encrypted at rest" scheme leaked its passphrase into 14 permanent public-snapshots.) Rotation = new keypair → `gh secret set` → swap public keys +-verifier blocks + fingerprints. Enforced by-`scripts/ci/check_no_private_keys.py` (pre-commit + pre-push). Doctrine:-`docs/supply-chain/wave2-key-ceremony.md`.-------## 8. Recurring bug classes (signal → defense)--Detail in [`docs/BUGS.md`](docs/BUGS.md):--1. **Restore trap** (BUG-006/014/015) — fix "works in tests" but behavior- unchanged after restart → `pwsh scripts/preflight.ps1` +- `python -c "import jarvis; print(jarvis.__file__)"`.-2. **Enum drift** (BUG-008) — empty UI list while the DB has rows, Pydantic- `literal_error` → five-layer pattern + parity test.-3. **Config drift** (BUG-010) — parallel sessions silently rolling back- `jarvis.toml` switches → `scripts/drift-guard-daemon.ps1` + ENV overrides- + BOM-safe writer.-4. **Console flicker** (BUG-012) — import `NO_WINDOW_CREATIONFLAGS` from- `jarvis.core.process_utils`.-5. **Audio host-API trap** (BUG-014) — WDM-KS auto-picked, PortAudio crashes- → `_FORBIDDEN_OUTPUT_HOSTAPIS` + shortest-unique-token matching.-6. **Stale watchdog counter** (BUG-032) — watchdog fires between units →- reset the counter per unit of work (AP-19).-7. **Socket loop on teardown error** — treat any read error as terminal,- `break` (AP-20).-8. **Wedged native inference** (BUG-036) — non-blocking lock + rebuild a- fresh model (AP-24).-9. **Wake transcript traps** (BUG-037) — "fires on silence" / "goes deaf on- its own wake word" share one root; word-agnostic verification only- (AP-27).-------## 9. Operational reality & Git workflow--- **The working tree is frequently SHARED** — several 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 normal. On a- corrupted-looking index/HEAD, recover via temp-index commit + `update-ref`- CAS + safety branch (`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 need- this restart to take effect.-- **Jarvis is used as a DESKTOP APP, not a browser tab.** The window is an- embedded WebView (`jarvis/ui/desktop_app.py`) with no address bar, no- reload button and no dev tools, so "press Ctrl+R / F5", "hard-refresh",- "clear the browser cache" and "open the console" are instructions that- cannot be followed — never end a frontend change with one. A frontend fix- reaches the user in exactly two steps: `npm run build` in- `jarvis/ui/web/frontend/` (the app serves the built `dist/`, never Vite),- then the **Restart** button in the app's top bar, which is on every screen- and posts to the endpoint above. Say that, and say that a restart takes- live terminal panes with it — they reattach or resume, but it is not free.- Running from a browser against `--dev` is a contributor path, not the- maintainer's.-- **New worktree:** run `pwsh scripts/preflight.ps1` before writing code;- non-zero exit → fix first (BUG-006/014).-- **Memory:** check `MEMORY.md` (`~/.claude/projects/.../memory/`) before- larger decisions.-- **Plan vs. code:** on conflict, the plan wins- (`~/.claude/plans/also-er-muss-auch-lexical-pond.md`); deviations get <!-- i18n-allow -->- documented back in the plan.--### Git workflow--*(Also pinned in the maintainer's personal global config; restated here so-every contributor and agent follows it.)*--- **Auto-commit after each completed logical step**, staging only YOUR files- by explicit path or `git add -p` — never `git add -A` / `git add .`- (sweeps another session's in-flight, possibly secret-bearing work in).-- **Conventional-Commit messages** (`feat:`, `fix:`, `refactor:`, `docs:`,- `chore:`).-- **Never push automatically** — only when the maintainer explicitly says so- (still honoring §2).-- **Never commit secrets / `.env` / keys / tokens.** If any appear- untracked: stop, flag, don't commit.-- **Pushing is one command.** `git push <remote> <branch>` — nothing is built,- copied, cloned, or audited on the way (§2). The hooks take about a second- and a half; if a push turns into a work session, something regrew that- belongs in CI. When a hook does block, it found a credential: fix the- finding, never reach for `--no-verify` as the first move.-----+Binding rules for every coding agent — compressed index. The FULL contract+(same section numbers, unabridged wording + rationale) lives in+[`docs/agent-contract.md`](docs/agent-contract.md); read it before deep work.++## 0. Mirror rule (BINDING)+`CLAUDE.md` ≡ `AGENTS.md` (byte-identical twins); `.claude/{agents,commands,skills}/`+≡ `.agents/{...}`. Sync engines run as hook, pre-commit, and CI gate. Everything+in them addresses EVERY coding agent, never Claude Code alone.++## 1. Language (BINDING, HIGHEST PRIORITY)+Every committed artifact is ENGLISH — code, comments, docs, commits, tests, CLI+help, UI source strings. German ONLY on the closed product surface (runtime+voice/chat output, i18n files, speech-input vocabulary, tests quoting them);+register: `scripts/ci/german-allowlist.txt` / inline `i18n-allow`. Translate+legacy German you touch. Runtime output language: ONE resolver+(`jarvis/core/turn_language.py::resolve_output_language`) decides each turn for+ALL layers (reply, acks, canned phrases, TTS voice); no layer re-derives it;+all locales (de/en/es/…) are equal.++## 2. GitHub (BINDING)+ONE public repo: `github.com/PersonalJarvis/PersonalJarvis`. **A push is+`git push`** — no staging trees, clones, builds, or file-by-file audits.+Protection: `.gitignore` first (data/, .env, jarvis.toml, Vault, keys never+tracked); never commit credentials; secret scanning stays ON; whole-tree checks+belong in CI, never pre-push. Default = plain push; Release ONLY when+explicitly asked (SemVer + tag + CHANGELOG + published GitHub Release;+`check_release_completeness.py` before tagging and `--verify-release` after).+Never push unless the maintainer asks.++## 3. Open-source universality (BINDING)+Assume an arbitrary downloader, never the maintainer: ANY single key/provider+works (capability-gated, cross-family fallback, honest degradation, AP-21/22);+every OS incl. headless `python:3.11-slim` (base install stays torch-free; GPU+deps only in `[local-voice]`); credentials recoverable IN-APP, stored keyring →+ENV → file. macOS/Linux ship in the SAME change behind one capability probe or+degrade honestly (+ `docs/os-parity.md` entry). Definition of done = the four+non-maintainer paths (§3 detail). Device triage order: version lag → setup+divergence → OS gap (`docs/device-parity-debugging.md`).++## 4. Naming (BINDING)+Internal: **Jarvis-Agents**. User-visible brand is DYNAMIC from the wake word+(`{name}-Agent`, fallback "Assistant-Agent") — never hardcode a name in a+user-visible string. Retired codenames stay dead; the external `openclaw`+binary strings and the read-time back-compat aliases stay AS-IS.++## 5. Architecture essentials+8-layer rule (protocols downward, frozen events on `EventBus` laterally);+plugins via entry-points, no `jarvis.*` import inside (after entry-point edits:+`pip install -e . --no-deps`); streaming-first (`AsyncIterator`); secrets only+via `get_secret`; brain is multi-provider + capability-gated (never hardcode a+provider/model); router = pure dispatcher over `ROUTER_TOOLS` (ADR-0011);+`scrub_for_voice` is regex-only; `jarvis.toml` only via `config_writer.py`;+CLI-first contract (every feature ships REST routes → auto-CLI + registry entry++ danger metadata); five-layer enum pattern for any cross-layer value; mission+workers in fresh git worktrees with kill-on-crash + tool broker (ADR-0025/26);+UTF-8 + `NO_WINDOW_CREATIONFLAGS` on every subprocess. Safety: tiers+safe/monitor/ask/block, blacklist > whitelist > default; only+`ToolExecutor.execute()`; generated skills stay `state="draft"`.++## 7. Anti-patterns AP-1..AP-31 (BINDING)+Full register with the bug each causes: `docs/agent-contract.md` §7. Essence:+no subprocess without `NO_WINDOW_CREATIONFLAGS`; no keys via voice/chat; enum+strings land in ALL five layers; no spawn tools in worker sets; atomic TOML+writes only; preflight every new worktree; nothing heavy on the boot critical+path; no LLM in the voice scrubber; native inference engines get a per-instance+lock + fresh-model recover; GPU wake gates ONLY on the inference probe; wake+verification is word-agnostic, never transcript content; no `isinstance` gates+on unpinned libs; signing private keys ONLY in GitHub Actions secrets; no+silent `except`; no config switch nothing reads.++## 8. Recurring bug classes+Restore trap (`pwsh scripts/preflight.ps1` + `python -c "import jarvis;+print(jarvis.__file__)"`), enum drift, config drift, console flicker, WDM-KS+audio, stale watchdog counters, socket teardown loops, wedged native+inference, wake transcript traps → [`docs/BUGS.md`](docs/BUGS.md).++## 9. Operational reality & git+The working tree is SHARED by parallel sessions: stage only YOUR files+(`git add -p` / pathspec, never `git add -A` / `git add .`); auto-commit each+logical step with Conventional-Commit messages; never push automatically;+never commit secrets. App restart = `POST /api/settings/restart-app` (never+`Stop-Process`); the app is a desktop WebView without F5/console — a frontend+fix = `npm run build` in `jarvis/ui/web/frontend/` + the in-app Restart+button. Check `MEMORY.md` before larger decisions.## 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--# 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/--# Frontend (jarvis/ui/web/frontend/)-npm install && npm run dev # build → npm run build ; tests → npm run test-```--```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 (self-skips when prereqs missing)-pytest tests/missions/ -v # Phase 6-pytest -m "not slow" # fast subset-# 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/.-```-----+Install: `pip install -e . --no-deps` + `pip install -r requirements.txt` ++`pip install -e ".[dev]"`. Launch: `run.bat` (`--headless` = API/WS only).+Lint: `ruff check jarvis/ && ruff format jarvis/ && mypy jarvis/`. Tests:+`pytest tests/` (fakes in `tests/fakes/`, not mocks; fast: `-m "not slow"`);+guards `test_routing.py`, `test_output_filter.py`,+`test_hangup_reason_parity.py`; new providers pass `tests/contract/`.## 11. Pointers--- **Architecture + module catalog:**- [`docs/architecture-overview.md`](docs/architecture-overview.md).-- **Doctrine:** [`CLOUD.md`](CLOUD.md),- [`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 a terminal/agent):- `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`.+[`docs/agent-contract.md`](docs/agent-contract.md) (FULL contract) ·+[`docs/architecture-overview.md`](docs/architecture-overview.md) ·+[`CLOUD.md`](CLOUD.md) · [`docs/PHILOSOPHY.md`](docs/PHILOSOPHY.md) ·+[`docs/BUGS.md`](docs/BUGS.md) · `docs/adr/` ·+[`docs/jarvis-cli.md`](docs/jarvis-cli.md).diff --git a/jarvis/brain/factory.py b/jarvis/brain/factory.pyindex a1f9983d68..4c440bbb23 100644--- a/jarvis/brain/factory.py+++ b/jarvis/brain/factory.py@@ -1353,6 +1353,16 @@ def _phase2_full_brain(# fallback only (see _resolve_wiki_vault_root).vault_path = _resolve_wiki_vault_root(config)search = VaultSearch(vault_path)+ # Warm the lazy SQLite connection off the critical path+ # (AP-26): the first per-turn search otherwise pays the+ # open+schema check against its own latency budget.+ import threading++ threading.Thread(+ target=search.warm_up,+ name="wiki-vault-warmup",+ daemon=True,+ ).start()from jarvis.brain.wiki_context import ( # noqa: PLC0415 — sibling import, kept local like the class import aboveDEFAULT_ULTRA_LATENCY_BUDGET_MS,)@@ -1360,10 +1370,13 @@ def _phase2_full_brain(manager._wiki_injector = WikiContextInjector(search=search,max_chars=getattr(wiki_cfg, "max_chars", 1500),- latency_budget_ms=getattr(wiki_cfg, "latency_budget_ms", 80),+ latency_budget_ms=getattr(wiki_cfg, "latency_budget_ms", 150),min_keyword_length=getattr(wiki_cfg, "min_keyword_length", 4),relevance_gate=bool(getattr(wiki_cfg, "relevance_gate", True)),min_coverage=float(getattr(wiki_cfg, "min_coverage", 0.5)),+ strict_min_coverage=float(+ getattr(wiki_cfg, "strict_min_coverage", 0.75)+ ),min_relative_score=float(getattr(wiki_cfg, "min_relative_score", 0.35)),@@ -1378,7 +1391,7 @@ def _phase2_full_brain(log.info("WikiContextInjector active (vault=%s, budget=%dms, gate=%s)",vault_path,- getattr(wiki_cfg, "latency_budget_ms", 80),+ getattr(wiki_cfg, "latency_budget_ms", 150),"on" if getattr(wiki_cfg, "relevance_gate", True) else "off",)except ImportError:diff --git a/jarvis/brain/turn_planner.py b/jarvis/brain/turn_planner.pyindex 44e9a38d9b..f21888b531 100644--- a/jarvis/brain/turn_planner.py+++ b/jarvis/brain/turn_planner.py@@ -88,6 +88,29 @@ _OWNERSHIP_RE = re.compile(r"mein\w*|unser\w*|mir|wir|ueber mich|uber mich|erinner\w* mich|" # i18n-allow: speech inputr"mi|mis|mio|nuestr\w*|sobre mi|recuerd\w* de mi)\b" # i18n-allow: speech input)+# Explicit recall of the user's own past ("weisst du noch", "wann war ich",+# "was war nochmal ...") — the one personal-data shape that carries NO+# possessive, so the ownership+lookup rule above never saw it and the turn+# was answered natively by a model that cannot know the answer (recall audit+# 2026-08-04). Built from the curated STRONG subset of the memory gate's+# recollection vocabulary: those phrases are unambiguous enough to be worth a+# delegation round trip, while broad members of the full recollection set+# ("habe ich") are not. The vocabulary is pre-folded in the same ae/oe/ue+# convention `_normalize` produces. # i18n-allow: names quoted German recall idioms+_RECALL_RE: re.Pattern[str] | None+try:+ from jarvis.brain.wiki_relevance_vocab import STRONG_RECALL_PHRASES++ _RECALL_RE = re.compile(+ r"\b(?:"+ + "|".join(+ re.escape(phrase)+ for phrase in sorted(set(STRONG_RECALL_PHRASES), key=len, reverse=True)+ )+ + r")\b"+ )+except Exception: # noqa: BLE001 — planner must import even if the vocab moves+ _RECALL_RE = None# Colloquial temporal particles (German "gerade", "eben", "vorhin",# "soeben") are deliberately NOT in this vocabulary: in spoken language they# are discourse fillers, not freshness claims, and treating them as@@ -614,6 +637,13 @@ def plan_turn(and not (deliberative or opinion or why_question)):reasons.add(TurnReason.PRIVATE_DATA)+ # Recall of the user's own past is STRONG evidence, deliberately outside+ # the suppressors: "wann war ich zuletzt beim Zahnarzt?" reads as+ # first-person smalltalk to every weak heuristic, yet only the+ # orchestrator (Wiki memory / awareness episodes) can answer+ # it. # i18n-allow: quoted German recall utterance+ if _RECALL_RE is not None and _RECALL_RE.search(normalized):+ reasons.add(TurnReason.PRIVATE_DATA)if _LOCAL_STATE_RE.search(normalized) and not definition:reasons.add(TurnReason.LOCAL_STATE)if (diff --git a/jarvis/brain/wiki_context.py b/jarvis/brain/wiki_context.pyindex 5e2adcac35..ea9173a2f2 100644--- a/jarvis/brain/wiki_context.py+++ b/jarvis/brain/wiki_context.py@@ -13,17 +13,21 @@ Relevance contract (``jarvis.brain.wiki_relevance``):back is what welds unrelated personal facts onto general-knowledge answers.Three gates, in order:- 1. BEFORE searching, ``should_consult_memory`` skips turns that neither ask- about the user's own life nor ask for a course of action for them- (planning / recommendation / decision turns, where the right answer- depends on who is asking). A general-knowledge question never touches- the vault at all — no latency, no context, no non-sequitur.+ 1. BEFORE searching, ``should_consult_memory`` skips only fragments too+ short to mean anything. Every other turn searches (retrieval-first —+ the vault query is local and single-digit milliseconds); the verdict+ instead grades HOW STRICT gate 2 must be: recollection / planning /+ personal turns keep the standard coverage bar, world-shaped and+ anchor-less turns must clear the strict bar before anything rides+ along. The 2026-08-04 recall audit found the old refuse-to-search+ default produced two full live days without one injected turn.2. AFTER searching, ``relevant_hits`` drops hits that merely share a common- word with the question.+ word with the question (strict verdicts: hits must cover nearly the+ whole question).3. AT injection, ``frame_context_block`` states that the notes may beirrelevant and that the model must ignore them if so.- When the gate declines a turn the knowledge is not lost: the router brain+ When the gates decline a turn the knowledge is not lost: the router brainholds the ``wiki-recall`` tool and can look something up deliberately.UltraWiki mode (decision D-5, either-or):@@ -85,66 +89,17 @@ if TYPE_CHECKING:from jarvis.brain.wiki_relevance import (DEFAULT_MIN_COVERAGE,DEFAULT_MIN_RELATIVE_SCORE,+ DEFAULT_STRICT_MIN_COVERAGE,+ fold_text,frame_context_block,relevant_hits,should_consult_memory,)+from jarvis.brain.wiki_relevance_vocab import STOPWORDSfrom jarvis.memory.wiki.telemetry import telemetrylog = logging.getLogger(__name__)-# ----------------------------------------------------------------------------# Stopword set (German + English, inlined — no nltk dependency)-# -----------------------------------------------------------------------------_STOPWORDS: frozenset[str] = frozenset({- # German- "aber", "alle", "allem", "allen", "aller", "alles", "also", "ander",- "andere", "anderem", "anderen", "anderer", "anderes", "anderm", "andern",- "anderr", "anders", "auch", "auf", "aus", "bald", "beime", "beim", # i18n-allow: German stopword list, matched against user text for wiki relevance scoring- "bereits", "bin", "bist", "bitte", "bzw", "dabei", "dadurch", "damit",- "dann", "dass", "dein", "deine", "deinem", "deinen", "deiner", "deines",- "denen", "denn", "derer", "dessen", "dies", "diese", "diesem", "diesen",- "dieser", "dieses", "doch", "durch", "ein", "eine", "einem", "einen", # i18n-allow: same German stopword list- "einer", "eines", "einig", "einige", "einigem", "einigen", "einiger",- "einiges", "einmal", "erst", "etwa", "euch", "euer", "eure", "eurem",- "euren", "eurer", "eures", "falls", "fast", "fuer", "ganz", "gemacht", # i18n-allow: same German stopword list- "gibt", "hatte", "haben", "habe", "habt", "hier", "hinter", "ihnen", # i18n-allow: same German stopword list- "ihrer", "ihrem", "ihres", "ihren", "indem", "irgend", "ist", "jede",- "jedem", "jeden", "jeder", "jedes", "jetzt", "kein", "keine", "keinem", # i18n-allow: same German stopword list- "keinen", "keiner", "keines", "kann", "kannst", "konnte", "koennen", # i18n-allow: same German stopword list- "macht", "manche", "manchem", "manchen", "mancher", "manches", "mein",- "meine", "meinem", "meinen", "meiner", "meines", "mehr", "mich", "muss", # i18n-allow: same German stopword list- "nach", "nicht", "noch", "oder", "ohne", "sehr", "sein", "seine", # i18n-allow: same German stopword list- "seinem", "seinen", "seiner", "seines", "seit", "selbst", "sich", "sie",- "sind", "soll", "sollen", "sollte", "sondern", "sonst", "ueber", "und", # i18n-allow: same German stopword list- "unser", "unsere", "unserem", "unseren", "unserer", "unseres", "unter",- "viel", "viele", "vielem", "vielen", "vieler", "vieles", "vom", "von", # i18n-allow: same German stopword list- "vor", "wann", "ward", "warum", "was", "weg", "weil", "welche", "welchem",- "welchen", "welcher", "welches", "wenn", "wer", "werden", "wie", "wieder", # i18n-allow: same German stopword list- "will", "wird", "wirst", "wohl", "worden", "wurden", "wurde", "wird", # i18n-allow: same German stopword list- "zwar", "zwischen",- # English- "about", "above", "after", "again", "against", "among", "any",- "are", "because", "been", "before", "being", "between", "both", "but",- "came", "can", "come", "could", "did", "does", "doing", "done", "down",- "during", "each", "few", "for", "from", "further", "gave", "get", "give",- "goes", "going", "gone", "got", "had", "has", "have", "having", "here",- "him", "his", "how", "into", "its", "just", "know", "like", "long",- "look", "make", "many", "more", "most", "much", "must", "need", "new",- "next", "not", "now", "old", "once", "only", "other", "our", "out",- "over", "same", "say", "should", "since", "some", "still", "such",- "tell", "than", "that", "the", "their", "them", "then", "there", "these",- "they", "this", "those", "though", "through", "time", "told", "too",- "under", "until", "upon", "use", "used", "using", "very", "want", "well", "were", "what", "when", "where", "which", "while", "who", "whom",- "why", "with", "would", "you", "your",- # Short German articles and pronouns- "das", "dem", "den", "der", "des", "die", "dir", "du", "ein", # i18n-allow: same German stopword list- "hat", "ich", "ihm", "ihn", "ihr", "ins", "man", "mir", "mit",- "nun", "nur", "pro", "sei", "uns", "war", "wir", "wen",- "zum", "zur", # i18n-allow: same German stopword list-})-# Tokenize on whitespace and common punctuation_TOKEN_RE = re.compile(r"[^\w\s]|\s+", re.UNICODE)@@ -189,12 +144,15 @@ def _extract_keywords("""raw_tokens = _TOKEN_RE.sub(" ", text).split()- # Filter by length and stopwords+ # Filter by length and stopwords. The stopword register is PRE-FOLDED+ # ("fuer", "ueber"), so the token must be folded the same way before the # i18n-allow: folded stopword forms+ # lookup — comparing ``tok.lower()`` let every real umlaut+ # spelling through as a junk keyword. # i18n-allow: folded stopword formscandidates: list[str] = []- for i, tok in enumerate(raw_tokens):+ for tok in raw_tokens:if len(tok) < min_length:continue- if tok.lower() in _STOPWORDS:+ if fold_text(tok) in STOPWORDS:continue# Skip leading token of the sentence (likely a greeting/verb, not a noun)# unless the whole utterance is very short (fewer than 4 tokens total)@@ -248,14 +206,21 @@ class WikiContextInjector:*,search: VaultSearch | None,max_chars: int = 1500,- latency_budget_ms: int = 80,+ latency_budget_ms: int = 150,min_keyword_length: int = 4,relevance_gate: bool = True,min_coverage: float = DEFAULT_MIN_COVERAGE,+ strict_min_coverage: float = DEFAULT_STRICT_MIN_COVERAGE,min_relative_score: float = DEFAULT_MIN_RELATIVE_SCORE,ultra_latency_budget_ms: int = DEFAULT_ULTRA_LATENCY_BUDGET_MS,ultra_k: int = DEFAULT_ULTRA_K,) -> None:+ # 150 ms (was 80): the vault leg opens its SQLite connection lazily+ # INSIDE the budget, so the first qualifying turn of a process paid+ # the open+schema check against 80 ms and logged reason=timeout.+ # The factory warms the connection in the background at boot; the+ # wider budget covers the cold path when that race is lost, and is+ # far below anything audible next to a multi-second brain call.self._search = searchself._max_chars = max_charsself._latency_budget_ms = latency_budget_ms@@ -268,6 +233,7 @@ class WikiContextInjector:# by patching code — the defaults stay on.self._relevance_gate = relevance_gateself._min_coverage = min_coverage+ self._strict_min_coverage = strict_min_coverageself._min_relative_score = min_relative_scoredef _miss(self, t0: float, reason: str) -> None:@@ -316,15 +282,27 @@ class WikiContextInjector:self._miss(t0, "no_search")return system_prompt- # Gate 1 (pre-retrieval): is this a question about the user's own life- # at all? A general-knowledge question must never reach the vault —- # that is what produces personalized non-sequiturs. Regex-only, so the- # skip path costs microseconds and SAVES the search latency.+ # Gate 1 (pre-retrieval): retrieval-first — only fragments too short+ # to mean anything skip the search. The verdict's job is grading gate+ # 2: a recollection/planning/personal turn keeps the standard+ # coverage bar, a world-shaped or anchor-less turn must clear the+ # strict one. Regex-only either way (AP-9).+ strict = False+ verdict_reason = "gate_off"if self._relevance_gate:verdict = should_consult_memory(user_text)if not verdict.consult:self._miss(t0, verdict.reason)return system_prompt+ strict = verdict.strict+ verdict_reason = verdict.reason+ # The strict probe is a retrieval-first bet that only pays where+ # looking is free — the local FTS vault. The UltraWiki leg may+ # embed the query through a cloud provider on every search, and+ # an unanchored turn is not worth that spend per turn.+ if strict and ultra_service is not None:+ self._miss(t0, "ultra_probe_skipped")+ return system_prompt# Extract keywordskeywords = _extract_keywords(@@ -342,16 +320,21 @@ class WikiContextInjector:budget_ms = self._ultra_latency_budget_ms if ultra else self._latency_budget_msstage_timings: dict[str, float] = {}try:- hits = await asyncio.wait_for(- _run_ultra_search(+ if ultra:+ retrieval = _run_ultra_search(ultra_service,query,self._ultra_k,budget_s=budget_ms / 1000.0,timings=stage_timings,)- if ultra- else _run_search(self._search, query),+ elif self._search is not None:+ retrieval = _run_search(self._search, query)+ else: # unreachable: the no-memory fast path returned above+ self._miss(t0, "no_search")+ return system_prompt+ hits = await asyncio.wait_for(+ retrieval,timeout=budget_ms / 1000.0,)except TimeoutError:@@ -393,11 +376,16 @@ class WikiContextInjector:hits = relevant_hits(hits,query,- min_coverage=self._min_coverage,+ min_coverage=self._strict_min_coverage+ if strict+ else self._min_coverage,min_relative_score=0.0 if ultra else self._min_relative_score,)if not hits:- self._miss(t0, "no_relevant_hits")+ self._miss(+ t0,+ "no_relevant_hits_strict" if strict else "no_relevant_hits",+ )return system_promptlatency_ms = int((time.monotonic() - t0) * 1000)@@ -440,10 +428,13 @@ class WikiContextInjector:telemetry.inc("wiki_context_hits")log.info(- "WikiContextInjector injected=True hits=%d latency_ms=%d source=%s%s",+ "WikiContextInjector injected=True hits=%d latency_ms=%d source=%s "+ "verdict=%s mode=%s%s",hits_included,latency_ms,"ultrawiki" if ultra else "vault",+ verdict_reason,+ "strict" if strict else "standard",f" stages={_stage_summary(stage_timings)}" if stage_timings else "",)return augmenteddiff --git a/jarvis/brain/wiki_relevance.py b/jarvis/brain/wiki_relevance.pyindex dd806767b0..c07dc6e52b 100644--- a/jarvis/brain/wiki_relevance.py+++ b/jarvis/brain/wiki_relevance.py@@ -18,28 +18,31 @@ answer arrives welded to the user's belongings.Three independent layers, each useful on its own:-1. :func:`should_consult_memory` — BEFORE retrieval. General-knowledge and- definitional questions with no personal marker never search at all. Saves- the search latency and removes the failure mode at its root. Three turn- classes DO earn a look: explicit recollection, a personal lookup, and —- since the ambient-knowledge pass — planning/recommendation/decision turns,- where the right answer depends on who is asking. Widening this gate is- safe precisely because gates 2 and 3 are unchanged: more turns get to ask- the memory, none of them get to inject an irrelevant answer.+1. :func:`should_consult_memory` — BEFORE retrieval. Retrieval-first since the+ 2026-08-04 recall audit (a whole two-day live log without a single injected+ turn): the local FTS search costs single-digit milliseconds, so refusing to+ even LOOK was pure loss. Only sub-``_MIN_TOKENS`` fragments still skip.+ Every other turn searches; what the verdict now decides is HOW STRICT the+ post-retrieval filter is. Explicit recollection, planning and personal+ lookups keep the standard coverage bar; world-knowledge-shaped and+ anchor-less turns get a STRICT bar (``strict=True`` →+ :data:`DEFAULT_STRICT_MIN_COVERAGE`), so the tallest-tower case stays+ uninjected not because nobody looked but because nothing retrieved covers+ the question.2. :func:`relevant_hits` — AFTER retrieval. Coverage of the question's contentterms plus a within-call relative floor. Deliberately NOT an absolute scorethreshold: ``SearchHit.score`` is documented as comparable only within a- single call, so a fixed cutoff would be noise.+ single call, so a fixed cutoff would be noise. Coverage counts only+ non-stopword terms — a generic question verb ("heisst", "called") in the+ denominator once made the bar unreachable for real German questions.3. :func:`frame_context_block` — AT injection. The block states what it is andgrants explicit permission to ignore it, instead of arriving as bare textthe model reads as an instruction.-Policy note — the default is to NOT inject. When the gate is unsure, the turn-proceeds without memory context, because the router brain holds the-``wiki-recall`` tool and can look something up deliberately when it notices it-needs to. A miss therefore degrades to "the model asks the memory itself",-not to "the knowledge is unreachable" — while a false injection degrades every-answer it touches. Recall the tool can recover; relevance it cannot.+Policy note — a WRONG injection is still the worse failure, but the defense+is the strict coverage bar plus the framing contract, no longer a refusal to+search. The router brain additionally holds the ``wiki-recall`` tool and can+look something up deliberately when the injected context is not enough.Languages: the matcher carries de/en/es tokens as equal peers (CLAUDE.md §1closed-list item 3 — speech-recognition input vocabulary, matching data rather@@ -61,6 +64,7 @@ from jarvis.brain.wiki_relevance_vocab import (PERSONAL_MARKERS,PLANNING_PHRASES,RECOLLECTION_PHRASES,+ STOPWORDS,)__all__ = [@@ -69,6 +73,7 @@ __all__ = ["relevant_hits","frame_context_block","content_terms",+ "fold_text",]@@ -76,19 +81,37 @@ __all__ = [# Folding# ---------------------------------------------------------------------------+# German umlauts must become their transliterated digraphs (ä -> ae, ö -> oe, # i18n-allow: quoted umlaut fold forms+# ü -> ue) because every German vocabulary entry is written in that form # i18n-allow: quoted umlaut fold forms+# ("wofuer", "erzaehl", "vorschlaege"). A plain NFKD combining-strip produces+# the OTHER ascii form ("wofur", "erzahl") and silently disabled every+# umlaut-carrying German phrase against real STT output — the exact defect+# ``turn_planner._normalize`` documents and fixed for the delegation+# vocabulary; the memory gate never received the same fix.+_UMLAUT_TRANSLITERATION = str.maketrans(+ {"ä": "ae", "ö": "oe", "ü": "ue"} # i18n-allow: umlaut mapping data+)+-def _fold(text: str) -> str:- """Lower-case and strip umlauts/accents so one pattern matches all spellings.+def fold_text(text: str) -> str:+ """Lower-case and fold umlauts/accents so one pattern matches all spellings.- The German sharp-s is expanded to a double s before the accent strip,- because NFKD decomposition leaves that character untouched; without the- expansion the folded patterns below could never match it.+ The German sharp-s is expanded to a double s and the umlauts to their+ digraphs BEFORE the NFKD accent strip (which handles the remaining+ diacritics, e.g. Spanish accents). Public because keyword extraction in+ ``wiki_context`` must fold with exactly these rules to hit the same+ pre-folded :data:`~jarvis.brain.wiki_relevance_vocab.STOPWORDS`."""lowered = text.lower().replace("ß", "ss") # i18n-allow: sharp-s input folding+ lowered = lowered.translate(_UMLAUT_TRANSLITERATION)decomposed = unicodedata.normalize("NFKD", lowered)return "".join(ch for ch in decomposed if not unicodedata.combining(ch))+# Internal shorthand kept for readability of the matchers below.+_fold = fold_text++# ---------------------------------------------------------------------------# Patterns (all written already folded — no umlauts, no accents)# ---------------------------------------------------------------------------@@ -137,45 +160,52 @@ _WORD_RE = re.compile(r"\w+", re.UNICODE)class MemoryVerdict:"""Outcome of the pre-retrieval gate.- ``consult`` is the decision; ``reason`` is a short machine-stable slug for- logging and telemetry, never user-facing prose.+ ``consult`` is the decision to search; ``strict`` asks the caller to apply+ the strict coverage bar (:data:`DEFAULT_STRICT_MIN_COVERAGE`) to whatever+ comes back — the retrieval-first stand-in for the old refusal to search.+ ``reason`` is a short machine-stable slug for logging and telemetry,+ never user-facing prose."""consult: boolreason: str+ strict: bool = False_SKIP_TOO_SHORT = MemoryVerdict(False, "too_short")-_SKIP_GENERAL_KNOWLEDGE = MemoryVerdict(False, "general_knowledge")-_SKIP_NO_PERSONAL_ANCHOR = MemoryVerdict(False, "no_personal_anchor")_CONSULT_RECOLLECTION = MemoryVerdict(True, "recollection_phrase")_CONSULT_PLANNING = MemoryVerdict(True, "planning_advice")_CONSULT_PERSONAL_LOOKUP = MemoryVerdict(True, "personal_lookup")+_PROBE_WORLD_SHAPE = MemoryVerdict(True, "world_shape_probe", strict=True)+_PROBE_NO_ANCHOR = MemoryVerdict(True, "no_anchor_probe", strict=True)def should_consult_memory(user_text: str) -> MemoryVerdict:- """Decide whether this turn should search the personal memory at all.+ """Decide how this turn consults the personal memory.- Order matters:+ Retrieval-first: the only turns that skip the (single-digit-millisecond,+ local) search are fragments too short to mean anything. Everything else+ searches, and the verdict grades the injection bar instead:1. Too short / no words -> skip (greetings, "ok", "danke").- 2. Explicit recollection phrasing -> consult, even without a possessive- ("do you remember where we were?").- 3. Planning / recommendation / decision phrasing -> consult, also without a- possessive ("what should I do", "what is the fastest way to X", "any- ideas for the weekend"). Advice is where knowing the person changes the- answer, so this turn class earns a look. Checked BEFORE step 4 because+ 2. Explicit recollection phrasing -> consult, standard bar, even without a+ possessive ("do you remember where we were?").+ 3. Planning / recommendation / decision phrasing -> consult, standard bar+ ("what should I do", "any ideas for the weekend"): advice is where+ knowing the person changes the answer. Checked before step 5 becausethe two shapes overlap and the advice reading is the useful one.- 4. General-knowledge shape WITHOUT a personal marker -> skip. This is the- tallest-tower case and the whole reason the gate exists.- 5. Personal marker AND a lookup shape -> consult.- 6. Anything else -> skip, and let the brain reach for ``wiki-recall`` if it- decides it needs the memory (see the policy note in the module docstring).+ 4. Personal marker AND a lookup shape -> consult, standard bar.+ 5. General-knowledge shape without a personal marker -> consult with the+ STRICT bar. The tallest-tower case: a weather question finds nothing+ that covers it and stays clean, while "who is <person in the vault>?"+ — the same grammatical shape — finally gets its page.+ 6. Anything else -> consult with the STRICT bar. Statements ("Bruno hat+ morgen Geburtstag") used to be dropped unsearched; now the vault gets+ to offer a page that genuinely covers them. # i18n-allow: quoted German utteranceOpening the gate is not injecting: every consult verdict still has to pass- :func:`relevant_hits` and arrives wrapped by :func:`frame_context_block`,- so a planning turn with nothing relevant in the vault produces exactly the- same silence it produced before this class existed.+ :func:`relevant_hits` (strict verdicts against the strict coverage bar)+ and arrives wrapped by :func:`frame_context_block`.Never raises: an unusable input degrades to a skip verdict."""@@ -189,11 +219,11 @@ def should_consult_memory(user_text: str) -> MemoryVerdict:if _PLANNING_RE.search(folded):return _CONSULT_PLANNINGpersonal = bool(_PERSONAL_RE.search(folded))- if _WORLD_KNOWLEDGE_RE.search(folded) and not personal:- return _SKIP_GENERAL_KNOWLEDGEif personal and _LOOKUP_RE.search(folded):return _CONSULT_PERSONAL_LOOKUP- return _SKIP_NO_PERSONAL_ANCHOR+ if _WORLD_KNOWLEDGE_RE.search(folded) and not personal:+ return _PROBE_WORLD_SHAPE+ return _PROBE_NO_ANCHOR# ---------------------------------------------------------------------------@@ -205,6 +235,12 @@ def should_consult_memory(user_text: str) -> MemoryVerdict:#: four is what produces an unrelated page that merely shares a common word.DEFAULT_MIN_COVERAGE = 0.5+#: The coverage bar for STRICT verdicts (world-shaped or anchor-less turns+#: that only search because retrieval is cheap). A page must cover nearly the+#: whole question before it may ride along uninvited — "Berlin weather+#: tomorrow" must not inject the Berlin travel page on one shared word.+DEFAULT_STRICT_MIN_COVERAGE = 0.75+#: A hit must also score at least this share of the best hit in the SAME call.#: Within one call the scores are documented as monotonic, so a relative floor#: is meaningful where an absolute cutoff would not be.@@ -212,11 +248,17 @@ DEFAULT_MIN_RELATIVE_SCORE = 0.35def content_terms(query: str, *, min_length: int = 3) -> tuple[str, ...]:- """Folded, deduplicated content words of a query, order preserved."""+ """Folded, deduplicated content words of a query, order preserved.++ Stopwords (function words plus generic question verbs, shared with the+ keyword extractor) are excluded: they inflate the coverage denominator+ without pointing at any page — "wie hiess mein Zahnarzt nochmal" must be+ judged on "zahnarzt", not on "hiess"/"nochmal". # i18n-allow: quoted German utterance+ """seen: set[str] = set()terms: list[str] = []for token in _WORD_RE.findall(_fold(query)):- if len(token) < min_length or token in seen:+ if len(token) < min_length or token in seen or token in STOPWORDS:continueseen.add(token)terms.append(token)diff --git a/jarvis/brain/wiki_relevance_vocab.py b/jarvis/brain/wiki_relevance_vocab.pyindex 807c1947d0..6a3c9ff1a8 100644--- a/jarvis/brain/wiki_relevance_vocab.py+++ b/jarvis/brain/wiki_relevance_vocab.py@@ -7,8 +7,8 @@ navigation-intent and wake-trigger vocabularies (CLAUDE.md §1, closed-listitem 3). Translating these tokens would make the gate deaf in that language.All tokens are written PRE-FOLDED: lower-case, no umlauts, no accents, sharp-s-expanded. ``jarvis.brain.wiki_relevance._fold`` applies the same folding to-incoming text, so "Wofür" and "wofuer" both reach the "wofuer" token here.+expanded. ``jarvis.brain.wiki_relevance.fold_text`` applies the same folding+to incoming text, so "Wofür" and "wofuer" both reach the "wofuer" token here.de / en / es are equal peers. Adding a language means adding its tokens toevery tuple below — never a new branch in the logic module.@@ -19,9 +19,11 @@ from __future__ import annotations__all__ = ["PERSONAL_MARKERS","RECOLLECTION_PHRASES",+ "STRONG_RECALL_PHRASES","PLANNING_PHRASES","GENERAL_KNOWLEDGE_PHRASES","LOOKUP_MARKERS",+ "STOPWORDS",]@@ -51,6 +53,35 @@ RECOLLECTION_PHRASES: tuple[str, ...] = ("were we", "did we", "what did i", "when did i", "when was i",# es"te acuerdas", "recuerdas", "cuando fui", "cuando estuve",+ # "again"-shaped re-ask, all languages: the user once knew the answer and+ # is asking the memory to restore it ("wie hiess das nochmal", "what was+ # that called again", "como se llamaba"). The bare adverb is enough as a+ # RECALL signal because gates 2+3 still decide what may be injected.+ "nochmal", "nochmals", "noch mal", "noch gleich",+ "was that again", "called again", "name again",+ "como se llamaba", "otra vez como",+)++#: The UNAMBIGUOUS subset of the recollection phrasing, for callers where a+#: false positive is expensive (the realtime turn planner: a delegation costs+#: the user many seconds of silence, so broad members of+#: :data:`RECOLLECTION_PHRASES` like "habe ich" must not force one). Every+#: token here is a shape that practically only occurs when the user asks the+#: assistant to bring back something from their own past.+STRONG_RECALL_PHRASES: tuple[str, ...] = (+ # de+ "weisst du noch", "erinnerst du dich", "erinnerst du",+ "wann war ich", "wann waren wir", "wann hatte ich", "wann hatten wir",+ "wie hiess", "wie hiess nochmal", "was war nochmal", "wer war nochmal",+ "wie heisst nochmal", "wie war nochmal", "was ist nochmal",+ "was habe ich dir", "was hatte ich",+ # en+ "do you remember", "remember when", "when did i", "when was i",+ "when were we", "what was that again", "what was it again",+ "called again", "what did i tell you",+ # es+ "te acuerdas", "recuerdas cuando", "cuando fui", "cuando estuve",+ "como se llamaba",)#: Planning / recommendation / decision shape — the second turn class that is@@ -140,3 +171,82 @@ LOOKUP_MARKERS: tuple[str, ...] = ("como", "por que", "cuanto", "cuanta", "cuantas","dime", "muestrame",)++#: Function words and generic question verbs, PRE-FOLDED like everything in+#: this module. Shared by keyword extraction (``wiki_context``) and coverage+#: counting (``wiki_relevance.content_terms``): a term that appears in every+#: second sentence carries no evidence about WHICH page answers the question,+#: so keeping it in a query or a coverage denominator only dilutes both.+#: Lived in ``wiki_context`` before, where it was compared against UNFOLDED+#: input — real umlaut spellings sailed straight past entries like "fuer" and+#: "ueber" and became junk keywords (root cause of the injector's+#: ``no_relevant_hits`` misses on German turns).+STOPWORDS: frozenset[str] = frozenset({+ # German+ "aber", "alle", "allem", "allen", "aller", "alles", "also", "ander",+ "andere", "anderem", "anderen", "anderer", "anderes", "anderm", "andern",+ "anderr", "anders", "auch", "auf", "aus", "bald", "beime", "beim",+ "bereits", "bin", "bist", "bitte", "bzw", "dabei", "dadurch", "damit",+ "dann", "dass", "dein", "deine", "deinem", "deinen", "deiner", "deines",+ "denen", "denn", "derer", "dessen", "dies", "diese", "diesem", "diesen",+ "dieser", "dieses", "doch", "durch", "ein", "eine", "einem", "einen",+ "einer", "eines", "einig", "einige", "einigem", "einigen", "einiger",+ "einiges", "einmal", "erst", "etwa", "euch", "euer", "eure", "eurem",+ "euren", "eurer", "eures", "falls", "fast", "fuer", "ganz", "gemacht",+ "gibt", "hatte", "haben", "habe", "habt", "hier", "hinter", "ihnen",+ "ihrer", "ihrem", "ihres", "ihren", "indem", "irgend", "ist", "jede",+ "jedem", "jeden", "jeder", "jedes", "jetzt", "kein", "keine", "keinem",+ "keinen", "keiner", "keines", "kann", "kannst", "konnte", "koennen",+ "macht", "manche", "manchem", "manchen", "mancher", "manches", "mein",+ "meine", "meinem", "meinen", "meiner", "meines", "mehr", "mich", "muss",+ "nach", "nicht", "noch", "oder", "ohne", "sehr", "sein", "seine",+ "seinem", "seinen", "seiner", "seines", "seit", "selbst", "sich", "sie",+ "sind", "soll", "sollen", "sollte", "sondern", "sonst", "ueber", "und",+ "unser", "unsere", "unserem", "unseren", "unserer", "unseres", "unter",+ "viel", "viele", "vielem", "vielen", "vieler", "vieles", "vom", "von",+ "vor", "wann", "ward", "warum", "was", "weg", "weil", "welche", "welchem",+ "welchen", "welcher", "welches", "wenn", "wer", "werden", "wie", "wieder",+ "will", "wird", "wirst", "wohl", "worden", "wurden", "wurde",+ "zwar", "zwischen",+ # Generic German question/event verbs — "wie hiess X nochmal", "was ist+ # bei Y passiert": the verb names the QUESTION SHAPE, never the page.+ "heisst", "heissen", "hiess", "hiessen", "genannt", "nochmal",+ "nochmals", "passiert", "passierte", "gewesen", "geworden", "gehabt",+ "brauche", "brauchst", "brauchen", "gebraucht",+ # German pronominal question adverbs and discourse fillers — pure+ # question shape ("Wofür brauche ich X?" is about X, never about+ # "wofuer"). # i18n-allow: quoted German utterance+ "wofuer", "worueber", "woran", "worauf", "womit", "wovon", "wobei",+ "wonach", "worin", "woher", "wohin", "wieso", "weshalb",+ "eigentlich", "zuletzt", "uebrigens", "vielleicht",+ # English+ "about", "above", "after", "again", "against", "among", "any",+ "are", "because", "been", "before", "being", "between", "both", "but",+ "came", "can", "come", "could", "did", "does", "doing", "done", "down",+ "during", "each", "few", "for", "from", "further", "gave", "get", "give",+ "goes", "going", "gone", "got", "had", "has", "have", "having", "here",+ "him", "his", "how", "into", "its", "just", "know", "like", "long",+ "look", "make", "many", "more", "most", "much", "must", "need", "new",+ "next", "not", "now", "old", "once", "only", "other", "our", "out",+ "over", "same", "say", "should", "since", "some", "still", "such",+ "tell", "than", "that", "the", "their", "them", "then", "there", "these",+ "they", "this", "those", "though", "through", "time", "told", "too",+ "under", "until", "upon", "use", "used", "using", "very", "want", "well",+ "were", "what", "when", "where", "which", "while", "who", "whom",+ "why", "with", "would", "you", "your",+ # Generic English question/event verbs and fillers (mirror of the German+ # block above)+ "called", "named", "happened", "happen", "actually", "really",+ "basically", "anyway", "maybe",+ # Short German articles and pronouns+ "das", "dem", "den", "der", "des", "die", "dir", "du",+ "hat", "ich", "ihm", "ihn", "ihr", "ins", "man", "mir", "mit",+ "nun", "nur", "pro", "sei", "uns", "war", "wir", "wen",+ "zum", "zur",+ # Spanish function words and generic question verbs — es is an equal peer+ "para", "pero", "porque", "como", "cuando", "donde", "quien", "cual",+ "esta", "este", "esto", "estas", "estos", "son", "una", "uno", "unos",+ "unas", "los", "las", "del", "con", "sin", "sobre", "entre", "desde",+ "hasta", "muy", "mas", "menos", "tambien", "llama", "llamaba", "paso",+ "pasado", "realmente", "necesito", "necesitas", "quizas",+})diff --git a/jarvis/memory/wiki/search.py b/jarvis/memory/wiki/search.pyindex e90bbd4ab6..fb92c2a12d 100644--- a/jarvis/memory/wiki/search.py+++ b/jarvis/memory/wiki/search.py@@ -171,6 +171,28 @@ class VaultSearch:log.warning("VaultSearch: unexpected error during search: %s", exc)return []+ def warm_up(self) -> None:+ """Open the connection and run one throwaway FTS query.++ The lazy ``_get_conn`` (open + ``ensure_schema``) otherwise runs+ INSIDE the injector's per-turn latency budget, and losing that race+ on the first qualifying turn of a process cost the turn its context+ (logged ``reason=timeout``). Meant to be called once from a+ background thread at boot — never on the startup critical path+ (AP-26). Failures are non-fatal: the next ``search`` simply pays the+ cold open itself.+ """+ try:+ conn = self._get_conn()+ conn.execute(+ "SELECT rowid FROM wiki_fts WHERE wiki_fts MATCH ? LIMIT 1",+ ('"warmup"',),+ ).fetchall()+ except Exception as exc: # noqa: BLE001+ # Missing table = index not built yet; anything else is the same+ # degraded-but-working state search() already tolerates.+ log.debug("VaultSearch warm_up skipped: %s", exc)+def close(self) -> None:"""Close the owned DB connection, if any."""if self._owns_conn and self._conn is not None:@@ -336,17 +358,20 @@ def _leading_text(body: str | None, limit: int = _PREVIEW_CHARS) -> str:def _normalise_bm25(raw: float) -> float:- """Normalise FTS5 BM25 to [0.0, 1.0] higher-is-better.+ """Normalise FTS5 BM25 to [0.0, 1.0) higher-is-better.- FTS5 BM25 returns lower (more negative) values for better matches.- Formula: ``1.0 / (1.0 + max(0.0, raw))``.+ FTS5 BM25 returns NEGATIVE values for real matches, more negative =+ better. Formula: ``m / (1.0 + m)`` with ``m = max(0.0, -raw)``, a+ monotonic map of match strength onto [0.0, 1.0).- - raw <= 0 (good match): score → close to 1.0- - raw == 0 (exact): score == 1.0- - raw > 0 (impossible in practice for a real match, but clamped):- score < 1.0+ The previous formula (``1.0 / (1.0 + max(0.0, raw))``) clamped every+ negative raw value to the SAME score 1.0 — believable at a glance+ because "good match → close to 1.0" held, but with zero spread the+ relative-score floor in ``wiki_relevance.relevant_hits`` compared+ every hit against ``1.0 * factor`` and could never drop anything."""- return 1.0 / (1.0 + max(0.0, float(raw)))+ strength = max(0.0, -float(raw))+ return strength / (1.0 + strength)def _default_db_path() -> Path:diff --git a/tests/unit/brain/test_turn_planner.py b/tests/unit/brain/test_turn_planner.pyindex 28478156be..0101a5d4c5 100644--- a/tests/unit/brain/test_turn_planner.py+++ b/tests/unit/brain/test_turn_planner.py@@ -561,3 +561,40 @@ def test_no_open_workspace_changes_nothing() -> None:assert plan_turn("Was hat Dana gemacht?", workspace_names=()).path is (TurnPath.NATIVE_REALTIME)+++ "utterance",+ [+ # No possessive anywhere — the ownership+lookup rule never saw these,+ # so they were answered natively by a model that cannot know the+ # answer (recall audit 2026-08-04). Real umlaut spellings on purpose.+ "Wann war ich zuletzt beim Zahnarzt?", # i18n-allow: German speech-input fixture+ "Weißt du noch, wo wir letztes Jahr im Urlaub waren?", # i18n-allow: German fixture+ "Wie hieß das Restaurant nochmal?", # i18n-allow: German speech-input fixture+ "Was ist nochmal bei dem Serverumzug passiert?", # i18n-allow: German fixture+ "Do you remember what I told you about the boat?",+ "When was I last in Berlin?",+ ],+)+def test_recall_of_the_users_past_delegates_as_private_data(utterance: str) -> None:+ """Explicit recall of the user's own past is strong evidence: only the+ orchestrator (Wiki memory / awareness episodes) can answer it."""+ plan = plan_turn(utterance)+ assert plan.path is TurnPath.ORCHESTRATOR+ assert TurnReason.PRIVATE_DATA in plan.reasons+ assert plan.requires_evidence is True+++ "utterance",+ [+ # First-person past forms that are NOT unambiguous recall — they occur+ # in ordinary storytelling and must not pay a delegation round trip.+ "Ich habe gestern einen tollen Film gesehen.", # i18n-allow: German speech-input fixture+ "Gestern war ich im Kino und es war super.", # i18n-allow: German speech-input fixture+ "I have been thinking about that a lot.",+ ],+)+def test_storytelling_past_tense_stays_native(utterance: str) -> None:+ assert plan_turn(utterance).path is TurnPath.NATIVE_REALTIMEdiff --git a/tests/unit/brain/test_wiki_context_relevance.py b/tests/unit/brain/test_wiki_context_relevance.pyindex 6459d129dc..37e8d45afc 100644--- a/tests/unit/brain/test_wiki_context_relevance.py+++ b/tests/unit/brain/test_wiki_context_relevance.py@@ -48,8 +48,10 @@ CAR_NOTE = FakeHit(@pytest.mark.asyncio-async def test_general_knowledge_question_never_searches_the_vault() -> None:- """The reported case: no search, no context, no personalized answer."""+async def test_general_knowledge_question_never_injects_unrelated_notes() -> None:+ """The reported case. Retrieval-first: the vault IS searched now (a+ world-shaped question can name a vault person), but an unrelated note+ must still never reach the prompt — the strict bar carries the defense."""search = FakeVaultSearch([CAR_NOTE])injector = WikiContextInjector(search=search, latency_budget_ms=500)@@ -59,7 +61,7 @@ async def test_general_knowledge_question_never_searches_the_vault() -> None:)assert result == BASE_PROMPT, "an unrelated question must not be given context"- assert search.queries == [], "the vault must not even be searched"+ assert search.queries, "retrieval-first: the vault is searched"assert "Bugatti" not in result@@ -74,7 +76,55 @@ async def test_english_general_knowledge_question_is_also_clean() -> None:)assert result == BASE_PROMPT- assert search.queries == []+ assert search.queries, "retrieval-first: the vault is searched"+ assert "Bugatti" not in result+++async def test_world_shaped_question_about_a_vault_person_gets_its_page() -> None:+ """ "Who is X?" has a general-knowledge shape and used to be dropped+ unsearched — the exact class of miss the recall audit found. When X is a+ vault entity, the page covers the question fully and clears the strict bar."""+ bruno = FakeHit(+ title="Bruno",+ snippet="Bruno is the user's climbing partner from Hamburg.",+ score=0.9,+ )+ search = FakeVaultSearch([bruno])+ injector = WikiContextInjector(search=search, latency_budget_ms=500)++ result = await injector.maybe_inject(+ user_text="Wer ist eigentlich Bruno?", # i18n-allow: German user input under test+ system_prompt=BASE_PROMPT,+ )++ assert "climbing partner" in result+ assert search.queries, "the vault is searched for the strict probe"+++async def test_umlaut_spelling_reaches_the_vault() -> None:+ """Real STT output carries umlauts. Regression for the fold defect that+ made every umlaut phrase ("Wofür", "Worüber") invisible to the gate and+ kept umlaut stopwords ("für") alive as junk keywords."""+ project = FakeHit(+ title="Zweitrechner", # i18n-allow: German vault page title under test+ snippet="Der Zweitrechner dient als Render-Knoten.", # i18n-allow: German vault content+ score=0.9,+ )+ search = FakeVaultSearch([project])+ injector = WikiContextInjector(search=search, latency_budget_ms=500)++ result = await injector.maybe_inject(+ user_text="Wofür brauche ich meinen Zweitrechner?", # i18n-allow: German input+ system_prompt=BASE_PROMPT,+ )++ assert "Render-Knoten" in result+ assert search.queries == ["Zweitrechner"], (+ "the umlaut question word and the possessive must be filtered, "+ f"got {search.queries}"+ )@pytest.mark.asynciodiff --git a/tests/unit/brain/test_wiki_relevance.py b/tests/unit/brain/test_wiki_relevance.pyindex a4f77121e2..64fd545c2c 100644--- a/tests/unit/brain/test_wiki_relevance.py+++ b/tests/unit/brain/test_wiki_relevance.py@@ -4,6 +4,11 @@ The headline case ("the Bugatti case", maintainer report 2026-07-25): ageneral-knowledge question must never drag an unrelated personal fact into theanswer. Asking for the tallest tower in the world must not produce advice aboutwhat the user owns.++Since the 2026-08-04 recall audit the gate is retrieval-first: the defense+against the Bugatti case is no longer a refusal to search but the STRICT+coverage bar (``MemoryVerdict.strict``) — world-shaped turns search too, and+only a page covering nearly the whole question may be injected."""from __future__ import annotations@@ -13,7 +18,9 @@ from dataclasses import dataclassimport pytestfrom jarvis.brain.wiki_relevance import (+ DEFAULT_STRICT_MIN_COVERAGE,content_terms,+ fold_text,frame_context_block,relevant_hits,should_consult_memory,@@ -30,7 +37,7 @@ class FakeHit:# ----------------------------------------------------------------------------# Pre-retrieval gate — general knowledge never consults the memory+# Pre-retrieval gate — general knowledge searches, but only behind the strict bar# ---------------------------------------------------------------------------@@ -49,16 +56,21 @@ class FakeHit:"Explain reciprocal rank fusion.",],)-def test_general_knowledge_never_consults_memory(utterance: str) -> None:+def test_general_knowledge_probes_only_behind_the_strict_bar(utterance: str) -> None:+ """Retrieval-first: the turn may search ("who is X" can be a vault+ person), but anything found must clear the strict coverage bar."""verdict = should_consult_memory(utterance)- assert verdict.consult is False- assert verdict.reason == "general_knowledge"+ assert verdict.consult is True+ assert verdict.strict is True+ assert verdict.reason == "world_shape_probe"-def test_possessive_turns_a_definitional_question_into_a_memory_question() -> None:- """ "What are the rules" is world knowledge; "my rules" is personal."""- assert should_consult_memory("What are the billing rules?").consult is False- assert should_consult_memory("What are my billing rules?").consult is True+def test_possessive_relaxes_the_bar_of_a_definitional_question() -> None:+ """ "What are the rules" is world-shaped (strict); "my rules" is personal."""+ world = should_consult_memory("What are the billing rules?")+ assert (world.consult, world.strict) == (True, True)+ personal = should_consult_memory("What are my billing rules?")+ assert (personal.consult, personal.strict) == (True, False)@pytest.mark.parametrize(@@ -70,10 +82,31 @@ def test_possessive_turns_a_definitional_question_into_a_memory_question() -> No"Do you remember where we stayed?","Wie heisst mein Zahnarzt?", # i18n-allow: German user input under test"¿Te acuerdas de mi vuelo?", # i18n-allow: Spanish user input under test+ # REAL umlaut spellings, exactly as STT produces them. Regression for+ # the fold defect: NFKD alone turned "wofür" into "wofur", which the+ # pre-folded vocabulary ("wofuer") could never match — every+ # umlaut-carrying German phrase was dead against real speech.+ "Wofür brauche ich meinen Zweitrechner?", # i18n-allow: German user input under test+ "Worüber haben wir gestern gesprochen?", # i18n-allow: German user input under test+ "Was würdest du mir für den Umzug empfehlen?", # i18n-allow: German user input under test+ # The "again"-shaped re-ask the maintainer quoted in the recall audit.+ "Wie hieß das Restaurant nochmal?", # i18n-allow: German user input under test+ "Was ist nochmal bei dem Projekt passiert?", # i18n-allow: German user input under test],)-def test_personal_questions_do_consult_memory(utterance: str) -> None:- assert should_consult_memory(utterance).consult is True+def test_personal_questions_consult_with_the_standard_bar(utterance: str) -> None:+ verdict = should_consult_memory(utterance)+ assert verdict.consult is True+ assert verdict.strict is False+++def test_fold_text_matches_the_prefolded_vocabulary_convention() -> None:+ """Umlauts become digraphs (ae/oe/ue), sharp-s becomes ss, Spanish+ accents strip — the same convention ``turn_planner._normalize`` uses."""+ assert fold_text("Wofür") == "wofuer" # i18n-allow: German input under test+ assert fold_text("erzähl") == "erzaehl" # i18n-allow: German input under test+ assert fold_text("heißt") == "heisst" # i18n-allow: German input under test+ assert fold_text("¿Qué?") == "¿que?" # i18n-allow: Spanish input under test@pytest.mark.parametrize(@@ -100,11 +133,24 @@ def test_smalltalk_and_fragments_skip(utterance: str) -> None:assert should_consult_memory(utterance).consult is False-def test_action_requests_skip() -> None:- """An imperative is not a lookup — no memory search, no injected context."""+def test_action_requests_probe_only_behind_the_strict_bar() -> None:+ """An imperative may search (retrieval is cheap) but never injects+ loosely — nothing in the vault covers "turn on the light" strongly."""turn_on_the_light_de = "Mach das Licht an" # i18n-allow: German input under test- assert should_consult_memory(turn_on_the_light_de).consult is False- assert should_consult_memory("Turn on the kitchen light").consult is False+ for utterance in (turn_on_the_light_de, "Turn on the kitchen light"):+ verdict = should_consult_memory(utterance)+ assert verdict.consult is True+ assert verdict.strict is True+ assert verdict.reason == "no_anchor_probe"+++def test_statements_probe_with_the_strict_bar() -> None:+ """A statement mentioning a vault entity earns a strict-bar look — the+ old gate dropped it unsearched ("no_personal_anchor")."""+ bruno_birthday_de = "Bruno hat morgen Geburtstag" # i18n-allow: German input under test+ verdict = should_consult_memory(bruno_birthday_de)+ assert verdict.consult is True+ assert verdict.strict is Truedef test_gate_never_raises_on_odd_input() -> None:@@ -161,10 +207,38 @@ def test_filter_tolerates_hits_missing_attributes() -> None:assert relevant_hits([Bare()], "dinner Example Contact") == []-def test_content_terms_folds_and_deduplicates() -> None:+def test_content_terms_folds_deduplicates_and_drops_stopwords() -> None:+ """Function words and generic question verbs leave the coverage+ denominator; only page-pointing terms remain."""mixed_case_de = "Über über ÜBER Reise" # i18n-allow: German input under test- assert content_terms(mixed_case_de) == ("uber", "reise")+ assert content_terms(mixed_case_de) == ("reise",)assert "?" not in "".join(content_terms("Wann? Wo?")) # i18n-allow: German input+ # "wie hiess mein Zahnarzt nochmal" must be judged on "zahnarzt" alone.+ dentist_de = "Wie hieß mein Zahnarzt nochmal?" # i18n-allow: German input under test+ assert content_terms(dentist_de) == ("zahnarzt",)+ assert content_terms("What was the dentist called again?") == ("dentist",)+++def test_strict_coverage_bar_requires_near_full_coverage() -> None:+ """The retrieval-first replacement for refusing to search: a page sharing+ one word with a three-term world question stays out under the strict bar,+ while a page that genuinely covers the question gets in."""+ berlin_travel = FakeHit(+ title="Berlin travel notes",+ snippet="Ideas for the next Berlin trip",+ score=0.9,+ )+ query = "Berlin Wetter morgen" # i18n-allow: German query under test+ assert (+ relevant_hits([berlin_travel], query, min_coverage=DEFAULT_STRICT_MIN_COVERAGE)+ == []+ )+ bruno_page = FakeHit(+ title="Bruno", snippet="Bruno is the user's climbing partner.", score=0.9+ )+ assert relevant_hits(+ [bruno_page], "Bruno", min_coverage=DEFAULT_STRICT_MIN_COVERAGE+ ) == [bruno_page]# ---------------------------------------------------------------------------diff --git a/tests/unit/brain/test_wiki_relevance_planning_gate.py b/tests/unit/brain/test_wiki_relevance_planning_gate.pyindex 6a3e11bc48..38e41b6b92 100644--- a/tests/unit/brain/test_wiki_relevance_planning_gate.py+++ b/tests/unit/brain/test_wiki_relevance_planning_gate.py@@ -67,7 +67,7 @@ def test_planning_beats_the_general_knowledge_skip() -> None:# ----------------------------------------------------------------------------# Stays shut: general knowledge, smalltalk, quiz superlatives+# Stays strict: general knowledge, smalltalk, quiz superlatives# ---------------------------------------------------------------------------@@ -88,10 +88,26 @@ def test_planning_beats_the_general_knowledge_skip() -> None:"Wie funktioniert ein Dieselmotor?", # i18n-allow: German speech input under test],)-def test_general_knowledge_still_never_consults_memory(utterance: str) -> None:+def test_general_knowledge_gets_only_the_strict_probe(utterance: str) -> None:+ """Retrieval-first: these turns may search, but never with the standard+ bar — a vault page must cover nearly the whole question to ride along."""verdict = should_consult_memory(utterance)- assert verdict.consult is False, utterance- assert verdict.reason == "general_knowledge", utterance+ assert verdict.consult is True, utterance+ assert verdict.strict is True, utterance+ assert verdict.reason == "world_shape_probe", utterance+++ "utterance",+ [+ "ok",+ "",+ " ",+ "danke dir", # i18n-allow: German smalltalk under test+ ],+)+def test_fragments_skip_entirely(utterance: str) -> None:+ assert should_consult_memory(utterance).consult is False, utterance@pytest.mark.parametrize(@@ -103,13 +119,15 @@ def test_general_knowledge_still_never_consults_memory(utterance: str) -> None:"Alles klar bei dir?", # i18n-allow: German smalltalk under test"Hey there, good morning","thanks a lot for that",- "ok",- "",- " ",],)-def test_smalltalk_never_consults_memory(utterance: str) -> None:- assert should_consult_memory(utterance).consult is False, utterance+def test_smalltalk_gets_at_most_the_strict_probe(utterance: str) -> None:+ """Retrieval-first: sentence-length smalltalk may search the (free,+ local) vault, but only behind the strict bar — no greeting shares enough+ content terms with a page to inject anything."""+ verdict = should_consult_memory(utterance)+ assert verdict.consult is True, utterance+ assert verdict.strict is True, utterancedef test_the_older_turn_classes_are_untouched() -> None:@@ -120,9 +138,9 @@ def test_the_older_turn_classes_are_untouched() -> None:assert should_consult_memory("What are my billing rules?").reason == ("personal_lookup")- assert should_consult_memory("Turn on the kitchen light").reason == (- "no_personal_anchor"- )+ anchorless = should_consult_memory("Turn on the kitchen light")+ assert anchorless.reason == "no_anchor_probe"+ assert anchorless.strict is Truedef test_widened_gate_never_raises_on_odd_input() -> None: