Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
chore(i18n): translate committed German to English in tests + jarvis + other (isolated drain, partial)
Ruben Lütkeacaf9ef9343b
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yamlindex 51f3405cea..07bdcb5810 100644--- a/.pre-commit-config.yaml+++ b/.pre-commit-config.yaml@@ -27,15 +27,15 @@ repos:- repo: localhooks:- # Plan §6.6 — Quick-Subset (max 5 Queries) der Review-Pipeline-Eval.- # Default: Mock-Modus (kein claude-Spawn, keine Kosten, < 5s).- # Threshold 60% — laxer als die Voll-Suite (80%), weil Quick-Subset- # schmal ist und kleiner Sampling-Bias erlaubt sein muss.+ # Plan §6.6 — quick subset (max 5 queries) of the review-pipeline eval.+ # Default: mock mode (no claude spawn, no cost, < 5s).+ # Threshold 60% — laxer than the full suite (80%) because the quick+ # subset is narrow and needs to tolerate a small sampling bias.- id: review-eval-quickname: review-pipeline eval (quick subset, mock)entry: jarvis-review-eval --quick --mock --threshold 0.6language: systempass_filenames: falsealways_run: false- # Nur triggern wenn review-relevante Files berührt werden.+ # Only triggers when review-relevant files are touched.files: ^(jarvis/core/review/|jarvis/plugins/tool/dispatch_with_review\.py|tests/eval/review_quality/queries\.json)diff --git a/.tmp_research/vision_latency_probe.py b/.tmp_research/vision_latency_probe.pyindex 61c315b801..e9a08c593d 100644--- a/.tmp_research/vision_latency_probe.py+++ b/.tmp_research/vision_latency_probe.py@@ -1,12 +1,12 @@-"""Latenz-Messung Phase 5 Stop-Bedingung — VisionEngine.observe(mode='ui_tree') x5.+"""Latency measurement, Phase 5 stop condition — VisionEngine.observe(mode='ui_tree') x5.-Mandat-Phase-5-Stop-Bedingung:- Wenn p95 > 250 ms auf Ziel-Hardware -> deferred-Vermerk + skip Phase 5.- Wenn p95 <= 250 ms -> Implementierung commit.+Mandated Phase-5 stop condition:+ If p95 > 250 ms on target hardware -> deferred note + skip Phase 5.+ If p95 <= 250 ms -> commit the implementation.Run: python .tmp_research/vision_latency_probe.py-Output: 5 Einzel-Messungen + p95 + Verdict (go/deferred).+Output: 5 individual measurements + p95 + verdict (go/deferred)."""from __future__ import annotations@@ -43,23 +43,23 @@ async def main() -> int:print("=" * 60)if not samples_ms:- print("Keine Messungen — VisionEngine schlug komplett fehl.")+ print("No measurements — VisionEngine failed completely.")return 1mn = min(samples_ms)mx = max(samples_ms)avg = sum(samples_ms) / len(samples_ms)- # p95 bei 5 samples = der höchste Wert (4. + 5. von 5 Samples ist faktisch max)+ # p95 at 5 samples = the highest value (the 4th + 5th of 5 samples is effectively the max)sorted_ms = sorted(samples_ms)- # statistics.quantiles braucht n>=2; für 5 Samples nehmen wir den höchsten- # als p95 (konservativ)+ # statistics.quantiles needs n>=2; for 5 samples we take the highest+ # as p95 (conservative)p95 = sorted_ms[-1]median = statistics.median(samples_ms)print(f"Min: {mn:7.2f} ms")print(f"Median: {median:7.2f} ms")print(f"Avg: {avg:7.2f} ms")- print(f"p95: {p95:7.2f} ms (hoechster der 5 Samples)")+ print(f"p95: {p95:7.2f} ms (highest of the 5 samples)")print(f"Max: {mx:7.2f} ms")print()threshold_ms = 250.0diff --git a/OS-Level/QUICKSTART.md b/OS-Level/QUICKSTART.mdindex eca48603d1..07b40a36a3 100644--- a/OS-Level/QUICKSTART.md+++ b/OS-Level/QUICKSTART.md@@ -128,8 +128,8 @@ run.bat --debug| **idle** | Mascot only, no glow | Default after boot || **listening** | Mascot pulses slightly brighter | Say "Jarvis" (wake word) || **thinking** | Mascot pulses faster | Ask a question |-| **typing** | Yellow rotating edge stroke + bottom sweep per keystroke | "Jarvis, tippe Hallo Welt in Notepad" |-| **clicking** | Faster edge stroke + yellow ripple on every click | "Jarvis, klick auf den OK-Button" |+| **typing** | Yellow rotating edge stroke + bottom sweep per keystroke | "Jarvis, type Hello World in Notepad" |+| **clicking** | Faster edge stroke + yellow ripple on every click | "Jarvis, click the OK button" || **error** | Brief red flash | When an action fails |---diff --git a/OS-Level/overlay-ui/edge-glow.html b/OS-Level/overlay-ui/edge-glow.htmlindex 38f73c2bfc..a71eeabb70 100644--- a/OS-Level/overlay-ui/edge-glow.html+++ b/OS-Level/overlay-ui/edge-glow.html@@ -6,18 +6,18 @@<meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>Edge Glow</title><!--- qwebchannel.js wird von Qt aus dem qrc-Resource-Path bereitgestellt,- sobald die Page in QWebEngineView geladen ist. bridge.ts laedt es- lazy via JS — so muss Vite das URL nicht analysieren.+ qwebchannel.js is provided by Qt from the qrc resource path as+ soon as the page is loaded in QWebEngineView. bridge.ts loads it+ lazily via JS — that way Vite doesn't need to resolve the URL.--></head><body>- <!-- Edge-Glow Container — main.ts buildLayers() haengt 5 Layer-Divs- hier rein. CSS in edge-glow.css macht den Rest. -->+ <!-- Edge-Glow container — main.ts buildLayers() appends 5 layer divs+ in here. CSS in edge-glow.css does the rest. --><div class="edge-glow" role="presentation"></div>- <!-- Diagnose-Marker. Per Default via CSS display:none; sichtbar mit- ?debug=1 in der URL. Plan §7 + Phase-9.4-Vorgabe. -->+ <!-- Diagnostic marker. Hidden by default via CSS display:none; visible+ with ?debug=1 in the URL. Plan §7 + Phase-9.4 spec. --><div id="state-display" role="presentation"><span class="state">init</span></div>diff --git a/OS-Level/overlay-ui/mascot.html b/OS-Level/overlay-ui/mascot.htmlindex 0292693b23..56269a5b9b 100644--- a/OS-Level/overlay-ui/mascot.html+++ b/OS-Level/overlay-ui/mascot.html@@ -5,11 +5,11 @@<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; connect-src qrc:; worker-src blob:;" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>Mascot</title>- <!-- qwebchannel.js wird von bridge.ts lazy geladen. -->+ <!-- qwebchannel.js is loaded lazily by bridge.ts. --></head><body>- <!-- Rive-Canvas wird per Default gerendert, fail-over auf <img>- (PNG-Fallback) wenn Rive-Asset nicht laed. Plan §13 + AD-16. -->+ <!-- Rive canvas is rendered by default, fails over to <img>+ (PNG fallback) when the Rive asset doesn't load. Plan §13 + AD-16. --><div class="mascot-host" role="img" aria-label="Jarvis status indicator"><canvas id="mascot-canvas" width="320" height="320" hidden></canvas><img id="mascot-fallback" alt="" src="" hidden />diff --git a/OS-Level/overlay-ui/src/bridge.ts b/OS-Level/overlay-ui/src/bridge.tsindex 216fe425d2..e84add50e5 100644--- a/OS-Level/overlay-ui/src/bridge.ts+++ b/OS-Level/overlay-ui/src/bridge.ts@@ -1,18 +1,18 @@-// Typed-Wrapper um qwebchannel.js. Qt liefert qwebchannel.js out of the-// box ueber QWebEngineScript / qrc:///qtwebchannel/qwebchannel.js — wir-// laden es im HTML-Head als <script src=...>. Hier nur der Promise--// Wrapper + die Subscribe-Helper damit der Renderer keine Globals direkt-// anfasst.+// Typed wrapper around qwebchannel.js. Qt provides qwebchannel.js out of+// the box via QWebEngineScript / qrc:///qtwebchannel/qwebchannel.js — we+// load it in the HTML head as <script src=...>. This is just the promise+// wrapper + the subscribe helpers so the renderer never touches globals+// directly.import { StateChangeSchema, StateNameSchema, type StateName } from "./schema";const QWEBCHANNEL_URL = "qrc:///qtwebchannel/qwebchannel.js";/**- * qwebchannel.js wird vom Qt-Runtime aus dem qrc-Resource-Path- * geliefert. Wir laden es lazy via DOM-Script-Insertion damit Vite- * das HTML nicht analysieren muss (sonst Build-Warning "qrc:/// can't- * be bundled").+ * qwebchannel.js is delivered by the Qt runtime from the qrc resource+ * path. We load it lazily via DOM script insertion so Vite doesn't+ * need to resolve the HTML (otherwise it triggers a build warning+ * "qrc:/// can't be bundled").*/function loadQWebChannelScript(): Promise<void> {if (typeof globalThis.QWebChannel === "function") {@@ -44,7 +44,7 @@ function loadQWebChannelScript(): Promise<void> {});}-// Minimal-Type fuer das, was QWebChannel exposed.+// Minimal type for what QWebChannel exposes.interface StateBridgeQObject {// Qt-Signal -> {connect(callback): void}stateChanged: {@@ -100,7 +100,7 @@ export interface ClickEventData {export interface OverlayBridge {currentState(): Promise<StateName>;onStateChange(handler: (change: { old: StateName; next: StateName; reason: string }) => void): void;- /** Phase 9.5 — wird non-null wenn die effectsBridge registriert ist. */+ /** Phase 9.5 — becomes non-null once the effectsBridge is registered. */onClickEvent(handler: (ev: ClickEventData) => void): void;onCursorMoved(handler: (x: number, y: number) => void): void;onActionStarted(handler: (kind: string, durationHintMs: number) => void): void;@@ -110,8 +110,8 @@ export interface OverlayBridge {/*** Connect to QWebChannel and resolve with a typed bridge.*- * Wird aus main.ts gerufen. Falls qwebchannel.js noch nicht geladen ist- * (Race bei pre-build dev-mode), pollt der Wrapper kurz auf+ * Called from main.ts. If qwebchannel.js hasn't loaded yet (a race in+ * pre-build dev mode), the wrapper briefly polls for* `window.qt.webChannelTransport`.** @remarks@@ -125,7 +125,7 @@ export interface OverlayBridge {* registered handlers.*/export async function connectBridge(timeoutMs = 5000): Promise<OverlayBridge> {- // Lazy load qwebchannel.js — Vite ignoriert das qrc:/// URL dadurch.+ // Lazy load qwebchannel.js — this way Vite ignores the qrc:/// URL.await loadQWebChannelScript();return new Promise((resolve, reject) => {const start = performance.now();diff --git a/OS-Level/overlay-ui/src/edge-glow/cursor-trail-worker.ts b/OS-Level/overlay-ui/src/edge-glow/cursor-trail-worker.tsindex 975a7cf651..9235cf6906 100644--- a/OS-Level/overlay-ui/src/edge-glow/cursor-trail-worker.ts+++ b/OS-Level/overlay-ui/src/edge-glow/cursor-trail-worker.ts@@ -1,16 +1,16 @@// cursor-trail-worker.ts — OffscreenCanvas Worker. Plan §15.2.//-// Empfaengt:+// Receives:// - { type: "init", canvas: OffscreenCanvas, dpr: number }// - { type: "resize", width: number, height: number, dpr: number }// - { type: "push", x: number, y: number }-// // x, y sind PHYSICAL px; Worker konvertiert-// // selbst per dpr in CSS-px.-// - { type: "clear" } // bei action_ended+// // x, y are PHYSICAL px; the worker itself+// // converts them to CSS px via dpr.+// - { type: "clear" } // on action_ended//-// Maintained einen Ring-Buffer von 20 Punkten + zeichnet jeden Frame-// mit fading opacity (Plan §15.1). Punkte verblassen nach-// ``POINT_LIFETIME_MS`` linear.+// Maintains a ring buffer of 20 points and draws every frame with+// fading opacity (Plan §15.1). Points fade out linearly after+// ``POINT_LIFETIME_MS``.interface InitMsg {type: "init";@@ -48,7 +48,7 @@ let canvas: OffscreenCanvas | null = null;let ctx: OffscreenCanvasRenderingContext2D | null = null;let dpr = 1;-// Ring buffer — feste Groesse, head pointer.+// Ring buffer — fixed size, head pointer.const buf: TrailPoint[] = [];let head = 0;@@ -64,8 +64,8 @@ function pushPoint(physX: number, physY: number): void {buf[head] = point;head = (head + 1) % TRAIL_LENGTH;}- // Self-stopping RAF (Plan §17): falls drawFrame sich beim letzten- // leeren Frame selbst angehalten hat, jetzt wieder anwerfen.+ // Self-stopping RAF (Plan §17): if drawFrame stopped itself on the+ // last empty frame, kick it off again now.if (rafHandle === 0 && ctx !== null) {rafHandle = requestAnimationFrame(drawFrame);}@@ -82,11 +82,11 @@ function clearTrail(): void {function drawFrame(): void {if (ctx === null || canvas === null) return;- // Self-stopping RAF (Plan §17): wenn Trail leer ist, pausiere die- // RAF-Schleife komplett — kein clearRect-GPU-Round-Trip pro Frame- // fuer Blank-Canvas. Wieder-Start erfolgt in pushPoint().+ // Self-stopping RAF (Plan §17): pause the RAF loop entirely once the+ // trail is empty — no clearRect GPU round-trip per frame for a blank+ // canvas. Restart happens in pushPoint().if (buf.length === 0) {- cancelAnimationFrame(rafHandle); // defensive — RAF hat sich u.U. gerade selbst gefired+ cancelAnimationFrame(rafHandle); // defensive — the RAF may have just self-firedrafHandle = 0;return;}@@ -94,8 +94,8 @@ function drawFrame(): void {rafHandle = requestAnimationFrame(drawFrame);ctx.clearRect(0, 0, canvas.width, canvas.height);- // Plan §15.2: globalCompositeOperation = 'lighter' fuer luminoses- // Akkumulieren.+ // Plan §15.2: globalCompositeOperation = 'lighter' for luminous+ // accumulation.ctx.globalCompositeOperation = "lighter";ctx.fillStyle = "#FFC700"; // Plan §7.1 yellow-primarydiff --git a/OS-Level/overlay-ui/src/edge-glow/cursor-trail.ts b/OS-Level/overlay-ui/src/edge-glow/cursor-trail.tsindex 9269a0b86e..319e28d69c 100644--- a/OS-Level/overlay-ui/src/edge-glow/cursor-trail.ts+++ b/OS-Level/overlay-ui/src/edge-glow/cursor-trail.ts@@ -1,19 +1,19 @@-// cursor-trail.ts — Main-Thread-Coordinator. Plan §15.+// cursor-trail.ts — Main-thread coordinator. Plan §15.//-// Erzeugt OffscreenCanvas, transferControlToOffscreen() in Worker,-// forwarded Cursor-Updates per postMessage. Worker macht das eigentliche-// Drawing (siehe cursor-trail-worker.ts).+// Creates the OffscreenCanvas, transferControlToOffscreen() to the worker,+// forwards cursor updates via postMessage. The worker does the actual+// drawing (see cursor-trail-worker.ts).//-// Quelle der Cursor-Updates: cursorBridge.cursorMoved-Signal aus dem-// Python-SHM-Reader-Thread (siehe OS-Level/src/overlay/window_glow.py).-// Wir bekommen physical px (Plan §11.2 / §15.3) und reichen sie-// unveraendert an den Worker — der konvertiert dpr-aware.+// Source of the cursor updates: the cursorBridge.cursorMoved signal from+// the Python SHM reader thread (see OS-Level/src/overlay/window_glow.py).+// We receive physical px (Plan §11.2 / §15.3) and pass them through+// unchanged to the worker — which converts them dpr-aware.let worker: Worker | null = null;let canvas: HTMLCanvasElement | null = null;-// Modul-level Resize-Handler — als named function, damit teardown ihn-// per ``removeEventListener`` wieder abmelden kann (Hot-Reload-Leak-Fix).+// Module-level resize handler — as a named function so teardown can+// unregister it via ``removeEventListener`` (hot-reload leak fix).function _onWindowResize(): void {if (canvas === null || worker === null) return;resizeCanvasToViewport(canvas);@@ -26,15 +26,15 @@ function _onWindowResize(): void {}interface InitOptions {- /** Container fuer das Canvas. Default: ``document.body``. */+ /** Container for the canvas. Default: ``document.body``. */container?: HTMLElement;}/**- * Initialisiert Canvas + Worker. Idempotent.+ * Initializes the canvas + worker. Idempotent.*- * Muss VOR ``pushCursorPoint`` aufgerufen werden — sonst sind die- * Pushes silent dropped.+ * Must be called BEFORE ``pushCursorPoint`` — otherwise pushes are+ * silently dropped.*/export function initCursorTrail(options: InitOptions = {}): void {if (worker !== null) return;@@ -43,11 +43,11 @@ export function initCursorTrail(options: InitOptions = {}): void {canvas = document.createElement("canvas");canvas.className = "cursor-trail-canvas";- // Fullscreen-Surface, click-through.+ // Fullscreen surface, click-through.resizeCanvasToViewport(canvas);container.appendChild(canvas);- // OffscreenCanvas + Worker — Plan §15.2.+ // OffscreenCanvas + worker — Plan §15.2.const offscreen = canvas.transferControlToOffscreen();worker = new Worker(@@ -61,8 +61,8 @@ export function initCursorTrail(options: InitOptions = {}): void {[offscreen],);- // Resize-Listener — Edge-Glow-Window kann durch Monitor-Hotplug- // umgeresizt werden. Named handler, damit teardown ihn entfernen kann.+ // Resize listener — the Edge-Glow window can get resized by monitor+ // hotplug. Named handler so teardown can remove it.window.addEventListener("resize", _onWindowResize);}@@ -77,8 +77,8 @@ function resizeCanvasToViewport(c: HTMLCanvasElement): void {}/**- * Pushed einen Cursor-Punkt. Coords sind PHYSICAL px (Plan §11.2);- * der Worker konvertiert per dpr.+ * Pushes a cursor point. Coords are PHYSICAL px (Plan §11.2);+ * the worker converts via dpr.*/export function pushCursorPoint(physicalX: number, physicalY: number): void {if (worker === null) return;@@ -86,7 +86,7 @@ export function pushCursorPoint(physicalX: number, physicalY: number): void {}/**- * Cleart den Trail (z.B. bei action_ended).+ * Clears the trail (e.g. on action_ended).*/export function clearCursorTrail(): void {if (worker === null) return;@@ -94,12 +94,12 @@ export function clearCursorTrail(): void {}/**- * Test-Helper: tear-down zwischen Tests.+ * Test helper: tear-down between tests.*/export function teardownCursorTrail(): void {- // Resize-Listener zuerst abmelden — sonst feuert er noch waehrend- // worker/canvas null-en und triggert keine Aktion, leakt aber den- // Listener-Slot (Hot-Reload-Akkumulation).+ // Unregister the resize listener first — otherwise it can still fire+ // while worker/canvas are being nulled out; it won't trigger any+ // action, but it leaks the listener slot (hot-reload accumulation).window.removeEventListener("resize", _onWindowResize);if (worker !== null) {worker.terminate();diff --git a/OS-Level/overlay-ui/src/edge-glow/edge-glow.css b/OS-Level/overlay-ui/src/edge-glow/edge-glow.cssindex 39c4d8611d..284f2dc10e 100644--- a/OS-Level/overlay-ui/src/edge-glow/edge-glow.css+++ b/OS-Level/overlay-ui/src/edge-glow/edge-glow.css@@ -1,21 +1,21 @@/* edge-glow.css — Plan §7 Visual Design System** Hard rules:- * - Palette §7.1 strict: nur Yellow + Black + Error-Red.- * - Glow AKTIV nur in data-state="typing" oder "clicking". (Plan §6.1)- * - Animations strict gemaess §7.3:- * Conic-Sweep rotation: linear (alles andere stottert)- * Halo-Breathing: cubic-bezier(0.25, 0.46, 0.45, 0.94) iOS Default- * State-Change: 250ms cubic-bezier(0.4, 0, 0.2, 1) Material Standard- * - Hue-Drift bleibt innerhalb der Palette (+/- 15 deg).- * - prefers-reduced-motion: static low-intensity Glow opacity 0.4.- * - contain: strict am Overlay-Root.- * - will-change: transform, filter NUR auf .edge-glow Layern.+ * - Palette §7.1 strict: only yellow + black + error-red.+ * - Glow ACTIVE only in data-state="typing" or "clicking". (Plan §6.1)+ * - Animations strict per §7.3:+ * Conic-sweep rotation: linear (anything else stutters)+ * Halo-breathing: cubic-bezier(0.25, 0.46, 0.45, 0.94) iOS default+ * State-change: 250ms cubic-bezier(0.4, 0, 0.2, 1) Material standard+ * - Hue-drift stays within the palette (+/- 15 deg).+ * - prefers-reduced-motion: static low-intensity glow opacity 0.4.+ * - contain: strict on the overlay root.+ * - will-change: transform, filter ONLY on .edge-glow layers.*/-/* @property --angle erlaubt CSS-Animationen auf Custom-Properties.- * Ohne diese Deklaration kann conic-gradient(from var(--angle)) NICHT- * vom Compositor animiert werden. */+/* @property --angle allows CSS animations on custom properties.+ * Without this declaration, conic-gradient(from var(--angle)) CANNOT+ * be animated by the compositor. */@property --angle {syntax: "<angle>";inherits: false;@@ -41,15 +41,15 @@}:root {- /* Plan §7.1 Palette — STRIKT, keine anderen Farben. */+ /* Plan §7.1 palette — STRICT, no other colors. */--jarvis-yellow-primary: #ffc700;--jarvis-yellow-soft: #ffe066;--jarvis-yellow-amber: #ffb300;--jarvis-black: #0a0a0a;--jarvis-error-red: #ff4d4d;- /* Live-modulierte Properties — werden von noise.ts 12x/s gesetzt.- * Initial-Values via @property oben. */+ /* Live-modulated properties — set by noise.ts 12x/s.+ * Initial values via @property above. */--intensity: 1;}@@ -63,39 +63,39 @@ body {color: var(--jarvis-yellow-primary);font-family: -apple-system, "Segoe UI", system-ui, sans-serif;overflow: hidden;- /* Plan §7 + §17: contain: strict sperrt Layout/Paint/Style ein und- * gibt dem Compositor maximale Optimierungs-Freiheit. */+ /* Plan §7 + §17: contain: strict scopes layout/paint/style and+ * gives the compositor maximum optimization freedom. */contain: strict;}-/* Edge-Glow Container — Plan §7.4 Multi-Layer-Composition.- * Default: nicht sichtbar. Aktiv nur via data-state typing/clicking. */+/* Edge-Glow container — Plan §7.4 multi-layer composition.+ * Default: not visible. Active only via data-state typing/clicking. */.edge-glow {position: fixed;inset: 0;pointer-events: none;- /* Plan §7.6 SVG Bloom-Filter wird inline im HTML geladen. */+ /* Plan §7.6 SVG bloom filter is loaded inline in the HTML. */filter: url(#jarvis-glow);opacity: 0;- /* Plan §7.3: 250ms Material Standard fuer State-Change. */+ /* Plan §7.3: 250ms Material standard for state-change. */transition: opacity 250ms cubic-bezier(0.4, 0, 0.2, 1);- /* Schreibt der Compositor sich, nicht der Renderer-Thread. */+ /* The compositor writes this itself, not the renderer thread. */will-change: opacity, filter;- /* a11y: Glow ist kein interaktives Element, Screen-Reader skip. */+ /* a11y: the glow is not an interactive element, screen readers skip it. */z-index: 0;}-/* 5 Layer mit Phase-Offset — Plan §7.4 Punkt 1 + 2.- * Jeder Layer hat eigene Periode-Variante via animation-delay; alle- * teilen sich das @keyframes rotate aber starten verschoben. */+/* 5 layers with phase offset — Plan §7.4 items 1 + 2.+ * Each layer has its own period variant via animation-delay; they all+ * share the @keyframes rotate but start staggered. */.edge-glow .layer {position: absolute;inset: 0;- /* Plan §7.2: 14px Edge-Band-Width @ 1x DPI. */+ /* Plan §7.2: 14px edge-band width @ 1x DPI. */padding: 14px;box-sizing: border-box;- /* Conic-Gradient als rotating yellow stroke. Plan §7.5 Reference-- * Algo nimmt 4 stops aus der Palette. */+ /* Conic gradient as a rotating yellow stroke. Plan §7.5 reference+ * algo takes 4 stops from the palette. */background: conic-gradient(from var(--angle),transparent 0deg,@@ -105,8 +105,8 @@ body {var(--jarvis-yellow-primary) 340deg,transparent 360deg);- /* Mask-Composite "exclude" punched die innere Flaeche raus, sodass- * nur der 14px Rand-Stroke uebrig bleibt. Plan §7.2. */+ /* Mask-composite "exclude" punches out the inner area, so only+ * the 14px edge stroke remains. Plan §7.2. */-webkit-mask:linear-gradient(#000, #000) content-box,linear-gradient(#000, #000);@@ -115,28 +115,27 @@ body {linear-gradient(#000, #000) content-box,linear-gradient(#000, #000);mask-composite: exclude;- /* Plan §7.2: plus-lighter sammelt mehrere Layer zu luminoser- * Akkumulation (Chrome 105+). */+ /* Plan §7.2: plus-lighter accumulates multiple layers into a luminous+ * blend (Chrome 105+). */mix-blend-mode: plus-lighter;- /* Hue-Drift: noise.ts modulated. Plan §7.4 Punkt 3 — bleibt innerhalb- * der Palette weil der Wert auf +/- 15deg geclamped wird (in JS). */+ /* Hue-drift: modulated by noise.ts. Plan §7.4 item 3 — stays within+ * the palette because the value is clamped to +/- 15deg (in JS). */filter: hue-rotate(var(--hue-drift));- /* Phase 9.4: will-change strict NUR hier, NICHT global. */+ /* Phase 9.4: will-change strict ONLY here, NOT global. */will-change: transform, filter, opacity;}-/* @keyframes drei separate Perioden um den Phase-Offset visuell zu- * differenzieren ohne dass alle Layer exact-step laufen. */+/* @keyframes uses three separate periods to visually differentiate the+ * phase offset without all layers running in exact lockstep. */@keyframes rotate-edge {to {--angle: 360deg;}}-/* Halo-Breathing per §7.3: 4.2s mit iOS easing.- * Bewegt zwischen --halo-a und --halo-b — beide werden 12 Hz von- * noise.ts moduliert, sodass die Atmung niemals exakt periodisch- * wirkt. */+/* Halo-breathing per §7.3: 4.2s with iOS easing.+ * Moves between --halo-a and --halo-b — both are modulated at 12 Hz by+ * noise.ts, so the breathing never feels exactly periodic. */@keyframes halo-breathe {0%,100% {@@ -147,7 +146,7 @@ body {}}-/* Layer-Defaults — Phase-Offset per Plan §7.4: ca. 200ms je Ecke. */+/* Layer defaults — phase offset per Plan §7.4: approx. 200ms per corner. */.edge-glow .layer.l1 {animation:rotate-edge var(--rot-period, 1.6s) linear infinite,@@ -180,7 +179,7 @@ body {}/* ----------------------------------------------------------------------- * State-driven Activation — Plan §6.1: Glow nur typing/clicking/error.+ * State-driven activation — Plan §6.1: glow only typing/clicking/error.* ---------------------------------------------------------------------- */:root[data-state="typing"] .edge-glow {@@ -193,7 +192,7 @@ body {--rot-period: 0.9s;}-/* Error-Flash: kurz rot, schneller. Plan §6.1 + §7.1 (error-red). */+/* Error flash: briefly red, faster. Plan §6.1 + §7.1 (error-red). */:root[data-state="error"] .edge-glow {opacity: 1;--rot-period: 0.6s;@@ -206,18 +205,19 @@ body {var(--jarvis-error-red) 240deg,transparent 360deg);- /* Hue-Drift greift im Error-Pfad nicht — konsistent rotes Tint. */+ /* Hue-drift doesn't apply on the error path — consistent red tint. */filter: none;}/* idle / listening / thinking / speaking / hidden: opacity 0 default.- * Reicht damit der Glow off ist. Layers laufen weiter im Compositor —- * wirken null-cost weil opacity:0 + will-change:opacity vom Compositor- * trivial gehandled wird. Phase 9.7 throttled FPS via setSuspended. */+ * That's enough to keep the glow off. Layers keep running in the+ * compositor — effectively zero cost because opacity:0 + will-change:opacity+ * is handled trivially by the compositor. Phase 9.7 throttles FPS via+ * setSuspended. *//* ----------------------------------------------------------------------- * Reduced-Motion — Plan §19.1 + §19.2- * Static low-intensity Glow opacity 0.4, keine Animationen.+ * Reduced motion — Plan §19.1 + §19.2+ * Static low-intensity glow opacity 0.4, no animations.* ---------------------------------------------------------------------- */@media (prefers-reduced-motion: reduce) {@@ -232,7 +232,7 @@ body {}/* ----------------------------------------------------------------------- * High-Contrast — Plan §19.4+ * High contrast — Plan §19.4* forced-colors: drop bloom, simple 4px CanvasText border.* ---------------------------------------------------------------------- */@@ -248,24 +248,25 @@ body {}/* ----------------------------------------------------------------------- * Phase 9.5 — Action Effects: Click-Ripple, Cursor-Trail, Typing-Sweep+ * Phase 9.5 — Action effects: click ripple, cursor trail, typing sweep* ---------------------------------------------------------------------- */-/* Ripple-Layer — fullscreen pointer-events:none Container fuer den- * 8er-Pool von Ripple-Divs. Plan §14.2. */+/* Ripple layer — fullscreen pointer-events:none container for the+ * pool of 8 ripple divs. Plan §14.2. */.ripple-layer {position: fixed;inset: 0;pointer-events: none;- z-index: 2; /* ueber dem .edge-glow Layer */+ z-index: 2; /* above the .edge-glow layer */overflow: hidden;}-/* Single Ripple-Slot im Pool. Outer-Div positioniert sich via inline- * ``transform: translate(x, y)`` am Click-Coord (8x8 Bounding-Box).- * Inner pseudo-::before macht die ``scale(40) + opacity 1->0``- * Animation — so ueberschreibt scale nicht den Position-translate.- * Plan §14.1: 8x8 px Kreis, expandiert zu scale(40), opacity 1 -> 0,+/* Single ripple slot in the pool. The outer div positions itself via+ * inline ``transform: translate(x, y)`` at the click coordinate (8x8+ * bounding box). The inner pseudo-::before does the+ * ``scale(40) + opacity 1->0`` animation — that way scale doesn't+ * override the position translate.+ * Plan §14.1: 8x8 px circle, expands to scale(40), opacity 1 -> 0,* 600 ms cubic-bezier(0.2, 0.7, 0.3, 1). */.ripple {position: absolute;@@ -273,7 +274,7 @@ body {left: 0;width: 8px;height: 8px;- margin-left: -4px; /* visual-center auf translate-coord */+ margin-left: -4px; /* visual center on the translate coord */margin-top: -4px;pointer-events: none;will-change: transform;@@ -311,8 +312,8 @@ body {}}-/* Cursor-Trail-Canvas — Worker rendert OffscreenCanvas, Plan §15.2.- * Fullscreen, click-through, ueber dem Edge-Glow aber unter Ripple. */+/* Cursor-trail canvas — the worker renders the OffscreenCanvas, Plan §15.2.+ * Fullscreen, click-through, above the edge glow but below the ripple. */.cursor-trail-canvas {position: fixed;inset: 0;@@ -322,7 +323,7 @@ body {z-index: 1;}-/* Typing-Sweep — Bottom-Edge 4px line. Plan §16.1.+/* Typing sweep — bottom-edge 4px line. Plan §16.1.* -100% -> +100% via translateX, 200ms linear. */.typing-sweep {position: fixed;@@ -332,8 +333,8 @@ body {height: 4px;pointer-events: none;z-index: 2;- /* Yellow gradient mit zentral-fokussiertem Highlight — Sweep-Effekt- * entsteht durch translateX einer Mid-Highlight-Surface. */+ /* Yellow gradient with a centrally-focused highlight — the sweep+ * effect comes from translateX-ing a mid-highlight surface. */background: linear-gradient(90deg,transparent 0%,@@ -368,7 +369,7 @@ body {}}-/* Reduced-Motion: Effekte ebenfalls dimmen. Plan §19.1. */+/* Reduced motion: dim the effects too. Plan §19.1. */@media (prefers-reduced-motion: reduce) {.ripple,.typing-sweep {@@ -381,8 +382,8 @@ body {}/* ----------------------------------------------------------------------- * Debug State-Display — nur via ?debug=1 sichtbar.- * main.ts setzt :root[data-debug="1"] beim Boot.+ * Debug state display — only visible via ?debug=1.+ * main.ts sets :root[data-debug="1"] at boot.* ---------------------------------------------------------------------- */#state-display {diff --git a/OS-Level/overlay-ui/src/edge-glow/glow.ts b/OS-Level/overlay-ui/src/edge-glow/glow.tsindex a0c06c159f..664b4aa3f1 100644--- a/OS-Level/overlay-ui/src/edge-glow/glow.ts+++ b/OS-Level/overlay-ui/src/edge-glow/glow.ts@@ -1,13 +1,13 @@-// glow.ts — State-driven Edge-Glow Setup. Plan §6.1 + §7.4.+// glow.ts — State-driven Edge-Glow setup. Plan §6.1 + §7.4.//-// Aufgaben:-// - Inline-SVG-Filter beim Boot in document.body injecten.-// - data-state-Attribut auf <html> setzen (StateMachine -> CSS-Selectors).-// - data-debug-Attribut wenn ?debug=1 in der URL.-// - State-Display-Text fuer Diagnose, gegated via debug-Flag.+// Responsibilities:+// - Inject the inline SVG filter into document.body at boot.+// - Set the data-state attribute on <html> (state machine -> CSS selectors).+// - Set the data-debug attribute when ?debug=1 is in the URL.+// - State-display text for diagnostics, gated by the debug flag.//-// Keine Animations-Steuerung hier — die laeuft komplett im CSS-// (@property-Compositor-Animation). noise.ts macht die 12 Hz Modulation.+// No animation control here — that all runs in CSS+// (@property compositor animation). noise.ts does the 12 Hz modulation.import glowSvgRaw from "./glow.svg?raw";@@ -16,15 +16,16 @@ import type { StateName } from "../schema";const ROOT = document.documentElement;/**- * Inline-SVG-Filter ins DOM injecten. Plan §7.6 — der Filter muss vor- * dem ersten Frame da sein, sonst hat `filter: url(#jarvis-glow)` einen- * Frame lang nichts zum Auflösen.+ * Injects the inline SVG filter into the DOM. Plan §7.6 — the filter+ * must be there before the first frame, otherwise `filter:+ * url(#jarvis-glow)` has nothing to resolve for one frame.*/export function injectGlowFilter(): void {if (document.getElementById("jarvis-glow")) return;- // DOMParser statt innerHTML — Defense-in-Depth gegen Supply-Chain-XSS- // (auch wenn glowSvgRaw via ?raw aus dem Build kommt). DOMParser markiert- // nicht-SVG-Inhalt mit einem <parsererror>-Element, das wir abfangen.+ // DOMParser instead of innerHTML — defense in depth against+ // supply-chain XSS (even though glowSvgRaw comes from the build via+ // ?raw). DOMParser marks non-SVG content with a <parsererror>+ // element, which we catch.const doc = new DOMParser().parseFromString(glowSvgRaw, "image/svg+xml");const svg = doc.documentElement;if (svg.getElementsByTagName("parsererror").length > 0) return;@@ -34,9 +35,9 @@ export function injectGlowFilter(): void {}/**- * 5 Layer-Divs in den `.edge-glow` Container haengen. Plan §7.4 —- * Multi-Layer-Composition mit Phase-Offset (5 Layers, je 200 ms- * versetzt via animation-delay im CSS).+ * Appends 5 layer divs into the `.edge-glow` container. Plan §7.4 —+ * multi-layer composition with a phase offset (5 layers, each staggered+ * by 200 ms via animation-delay in the CSS).*/export function buildLayers(container: HTMLElement): void {if (container.children.length > 0) return;@@ -48,7 +49,7 @@ export function buildLayers(container: HTMLElement): void {}/**- * Setzt das ``data-state``-Attribut auf `<html>` — CSS reagiert darauf+ * Sets the ``data-state`` attribute on `<html>` — CSS reacts to it* via `:root[data-state="typing"] .edge-glow { ... }`.*/export function applyState(state: StateName): void {@@ -56,8 +57,8 @@ export function applyState(state: StateName): void {}/**- * Optional: explicit intensity-Modulation. Default 1.0 — Phase 9.5- * koennte das fuer Activity-Bursts auf 1.2 hochziehen.+ * Optional: explicit intensity modulation. Default 1.0 — Phase 9.5+ * might bump this to 1.2 for activity bursts.*/export function setIntensity(value: number): void {const clamped = Math.max(0, Math.min(2, value));@@ -65,8 +66,9 @@ export function setIntensity(value: number): void {}/**- * ?debug=1 im URL-Query → State-Display-Marker oben rechts sichtbar.- * Sonst bleibt #state-display via CSS display:none.+ * ?debug=1 in the URL query → the state-display marker in the top+ * right becomes visible. Otherwise #state-display stays hidden via+ * CSS display:none.*/export function applyDebugFlag(): boolean {const params = new URLSearchParams(window.location.search);@@ -80,9 +82,9 @@ export function applyDebugFlag(): boolean {}/**- * Schreibt den aktuellen State + reason in #state-display. Im- * Production-Pfad (kein ?debug=1) ist das Element via CSS hidden — der- * Update kostet trotzdem nichts ausser einem dataset-write.+ * Writes the current state + reason into #state-display. On the+ * production path (no ?debug=1) the element is hidden via CSS — the+ * update still costs nothing besides a dataset write.*/export function setStateDisplay(state: StateName, reason: string): void {const el = document.getElementById("state-display");diff --git a/OS-Level/overlay-ui/src/edge-glow/main.ts b/OS-Level/overlay-ui/src/edge-glow/main.tsindex f7bb7d40da..f80bfa235a 100644--- a/OS-Level/overlay-ui/src/edge-glow/main.ts+++ b/OS-Level/overlay-ui/src/edge-glow/main.ts@@ -1,22 +1,22 @@// Edge-Glow Renderer Entry — Phase 9.5.//-// Boot-Sequenz:-// 1. CSS importieren (Vite injected den Style-Tag).-// 2. SVG-Filter ins DOM injecten (vor dem ersten Frame!).-// 3. 5 Layer-Divs in den .edge-glow Container haengen.-// 4. ?debug=1 Flag auf <html> setzen.-// 5. Effekt-Surfaces aufbauen (ripple-pool, cursor-trail-canvas,-// typing-sweep).-// 6. Noise-Runner starten (12 Hz, ausser bei prefers-reduced-motion).-// 7. QWebChannel-Bridge connecten.-// - State -> data-state Attribut auf <html>.+// Boot sequence:+// 1. Import the CSS (Vite injects the style tag).+// 2. Inject the SVG filter into the DOM (before the first frame!).+// 3. Append 5 layer divs into the .edge-glow container.+// 4. Set the ?debug=1 flag on <html>.+// 5. Build the effect surfaces (ripple pool, cursor-trail canvas,+// typing sweep).+// 6. Start the noise runner (12 Hz, except with prefers-reduced-motion).+// 7. Connect the QWebChannel bridge.+// - State -> data-state attribute on <html>.// - Click -> ripple.triggerRipple.// - Cursor -> cursor-trail.pushCursorPoint.// - Action started/ended (kind=typing) -> typing-sweep.scheduleSweepBurst.//-// Glow-Aktivierung erfolgt komplett ueber data-state-Attribute auf-// <html> — siehe edge-glow.css. JS pusht nur State-Strings, kein-// imperatives Animation-Driving.+// Glow activation happens entirely via data-state attributes on+// <html> — see edge-glow.css. JS only pushes state strings, no+// imperative animation driving.import "./edge-glow.css";@@ -65,20 +65,20 @@ async function boot(): Promise<void> {`[edge-glow] booting (debug=${env.debug}, reduced-motion=${env.reducedMotion})`,);- // Sofort idle als Default — matched die StateMachine.IDLE-Initial.+ // Idle immediately as the default — matches StateMachine.IDLE's initial.applyState("idle");setStateDisplay("idle", "");- // 12 Hz Simplex-Noise — startNoise no-op'd bei reduced-motion.+ // 12 Hz simplex noise — startNoise no-ops with reduced motion.const noiseRunner = startNoise();- // Power-Saving: Wenn die WebView versteckt wird (z.B. Overlay aus, Workspace-- // Wechsel), stoppen wir den 12-Hz-setInterval-Tick. Sonst laeuft er die- // gesamte WebView-Lifetime und schreibt CSS-Custom-Properties auch im- // hidden-State (Style-Recalc-Kosten ohne sichtbaren Effekt). stop() ist- // idempotent + macht no-op wenn nicht gestartet (reduced-motion-Pfad).- // Re-start bei visible ist nicht in scope — sichtbar werden bedeutet- // Page-Reload.+ // Power saving: when the WebView is hidden (e.g. overlay off, workspace+ // switch), we stop the 12-Hz setInterval tick. Otherwise it keeps running+ // for the whole WebView lifetime and writes CSS custom properties even in+ // the hidden state (style-recalc cost with no visible effect). stop() is+ // idempotent + no-ops if it was never started (reduced-motion path).+ // Restarting on visible is out of scope — becoming visible means a+ // page reload.document.addEventListener("visibilitychange", () => {if (document.hidden) {noiseRunner.stop();@@ -116,7 +116,7 @@ async function boot(): Promise<void> {if (durationHintMs > 0) {scheduleSweepBurst(durationHintMs);} else {- // Kein Hint -> einzelner Sweep beim Start.+ // No hint -> a single sweep at the start.scheduleSweepBurst(0);}}@@ -128,8 +128,8 @@ async function boot(): Promise<void> {clearCursorTrail();});} catch (err) {- // Standalone-Vite-Dev oder QWebChannel-Boot-Race: idle bleibt- // gesetzt (siehe oben), wir aktualisieren nur das Diagnose-Tag.+ // Standalone Vite dev or a QWebChannel boot race: idle stays set+ // (see above), we only update the diagnostic tag.console.warn("[edge-glow] bridge unavailable", err);setStateDisplay("idle", "no-bridge");}diff --git a/OS-Level/overlay-ui/src/edge-glow/noise.ts b/OS-Level/overlay-ui/src/edge-glow/noise.tsindex c2653a2945..ceb1543668 100644--- a/OS-Level/overlay-ui/src/edge-glow/noise.ts+++ b/OS-Level/overlay-ui/src/edge-glow/noise.ts@@ -1,31 +1,31 @@-// noise.ts — 12 Hz Simplex-Noise auf 3 CSS-Custom-Properties.-// Plan §7.4 Punkt 5: Organic Randomness via Simplex-Noise.+// noise.ts — 12 Hz simplex noise on 3 CSS custom properties.+// Plan §7.4 item 5: organic randomness via simplex noise.//-// Driften (Werte clamped):-// --hue-drift : -15deg .. +15deg (Plan-Constraint, bleibt in der Palette)-// --halo-a : 0.25 .. 0.45 (innerer Halo-Layer)-// --halo-b : 0.45 .. 0.65 (aeusserer Halo-Layer)+// Drift ranges (values clamped):+// --hue-drift : -15deg .. +15deg (plan constraint, stays within the palette)+// --halo-a : 0.25 .. 0.45 (inner halo layer)+// --halo-b : 0.45 .. 0.65 (outer halo layer)//-// 12 Hz = ~83.3 ms Period. Wir nutzen setInterval — der Frame-Drift ist-// fuer organic-noise gewollt und braucht keine rAF-Praezision. Setting-// Custom-Properties ist mikrosekunden-cheap; keine Style-Recalc weil die-// Properties registered (@property) sind.+// 12 Hz = ~83.3 ms period. We use setInterval — the frame drift is+// intentional for organic noise and doesn't need rAF precision. Setting+// custom properties is microsecond-cheap; no style recalc because the+// properties are registered (@property).//-// prefers-reduced-motion: Driften wird komplett ausgesetzt — Werte-// bleiben statisch beim CSS-Default.+// prefers-reduced-motion: drift is suspended entirely — values stay+// static at the CSS default.import { createNoise2D } from "simplex-noise";const ROOT = document.documentElement;-// Plan-Constraints — Hue-Drift NIE ausserhalb +/- 15 deg.+// Plan constraints — hue-drift NEVER outside +/- 15 deg.const HUE_AMPLITUDE_DEG = 15;const HALO_A_MIN = 0.25;const HALO_A_MAX = 0.45;const HALO_B_MIN = 0.45;const HALO_B_MAX = 0.65;-// 12 Hz, leicht jittered damit der Pattern nicht perfekt periodisch ist.+// 12 Hz, slightly jittered so the pattern isn't perfectly periodic.const PERIOD_MS = 1000 / 12;interface NoiseRunner {@@ -40,11 +40,11 @@ function lerp(min: number, max: number, t: number): number {}/**- * Startet die 12-Hz-Modulation. Returnt einen Handle mit ``stop()``.+ * Starts the 12-Hz modulation. Returns a handle with ``stop()``.*- * Wenn der Browser ``prefers-reduced-motion: reduce`` meldet, wird der- * Runner gar nicht erst gestartet — die Custom-Properties bleiben auf- * ihren CSS-Defaults und der Glow ist statisch (Plan §19.1).+ * If the browser reports ``prefers-reduced-motion: reduce``, the+ * runner never starts in the first place — the custom properties stay+ * at their CSS defaults and the glow is static (Plan §19.1).*/export function startNoise(): NoiseRunner {const reducedMotion =@@ -62,15 +62,15 @@ export function startNoise(): NoiseRunner {};}- // 3 unabhaengige Noise-Funktionen damit hue/halo-a/halo-b nicht- // miteinander korreliert sind.+ // 3 independent noise functions so hue/halo-a/halo-b aren't+ // correlated with each other.const hueNoise = createNoise2D();const haloANoise = createNoise2D();const haloBNoise = createNoise2D();let t = 0;const intervalId = window.setInterval(() => {- t += 0.05; // langsamer Walk durch das Noise-Feld+ t += 0.05; // slow walk through the noise fieldconst hue = hueNoise(t, 0) * HUE_AMPLITUDE_DEG;const haloA = lerp(HALO_A_MIN, HALO_A_MAX, haloANoise(t, 1));const haloB = lerp(HALO_B_MIN, HALO_B_MAX, haloBNoise(t, 2));diff --git a/OS-Level/overlay-ui/src/edge-glow/ripple.ts b/OS-Level/overlay-ui/src/edge-glow/ripple.tsindex bf11f3e42a..27e25ec660 100644--- a/OS-Level/overlay-ui/src/edge-glow/ripple.ts+++ b/OS-Level/overlay-ui/src/edge-glow/ripple.ts@@ -1,12 +1,12 @@-// ripple.ts — Click-Ripple-Effect. Plan §14.+// ripple.ts — Click-ripple effect. Plan §14.//-// Pre-warm Pool von 8 Divs (Plan §14.2) damit Burst-Clicks keinen-// appendChild/Layout-Jank ausloesen. Animation laeuft komplett im CSS+// Pre-warms a pool of 8 divs (Plan §14.2) so burst clicks don't trigger+// appendChild/layout jank. The animation runs entirely in CSS// (transform+opacity, compositor-only).//-// Coords vom Hauptjarvis sind PHYSICAL pixels (Plan §14.4). Wir-// rechnen am Renderer-Boundary in CSS-logical um — ein Punkt, kein-// verstreuter Off-by-DPI-Bug.+// Coords from Hauptjarvis are PHYSICAL pixels (Plan §14.4). We convert+// to CSS-logical at the renderer boundary — one spot, not an+// off-by-DPI bug scattered everywhere.const POOL_SIZE = 8;const RIPPLE_LIFETIME_MS = 600; // Plan §14.1@@ -21,12 +21,12 @@ let pool: RippleSlot[] | null = null;let layer: HTMLElement | null = null;/**- * Erzeugt den Pool. Idempotent — mehrere Aufrufe sind no-op.+ * Creates the pool. Idempotent — repeated calls are no-ops.*- * Container muss eine ``.ripple-layer``-Surface sein (per CSS- * pointer-events:none, position:fixed inset:0). buildRipplePool laesst- * sie an ``document.body`` haengen; der Caller kann auch eigenes- * Container-Element uebergeben (testbar).+ * The container must be a ``.ripple-layer`` surface (per CSS+ * pointer-events:none, position:fixed inset:0). buildRipplePool+ * appends it to ``document.body``; the caller can also pass its own+ * container element (testable).*/export function buildRipplePool(container?: HTMLElement): void {if (pool !== null) return;@@ -43,7 +43,7 @@ export function buildRipplePool(container?: HTMLElement): void {const el = document.createElement("div");el.className = "ripple";el.dataset["slot"] = String(i);- // Initial off-screen + invisible — nimmt keinen Platz ein.+ // Initial off-screen + invisible — takes up no space.el.style.opacity = "0";el.style.transform = "translate(-9999px, -9999px) scale(0)";layer.appendChild(el);@@ -52,23 +52,23 @@ export function buildRipplePool(container?: HTMLElement): void {}/**- * Spawnt ein Ripple am Click-Coord. Plan §14.4 — physical px in,- * CSS-px out via ``window.devicePixelRatio``.+ * Spawns a ripple at the click coordinate. Plan §14.4 — physical px in,+ * CSS px out via ``window.devicePixelRatio``.*- * Returnt ``true`` wenn ein Pool-Slot verfuegbar war, ``false`` wenn- * alle 8 Slots aktiv sind (Burst > 8 Klicks innerhalb 600 ms — der- * 9. wird droppt; akzeptabler Edge-Case).+ * Returns ``true`` if a pool slot was available, ``false`` if all 8+ * slots are active (a burst of > 8 clicks within 600 ms — the 9th+ * gets dropped; an acceptable edge case).*/export function triggerRipple(physicalX: number, physicalY: number): boolean {if (pool === null) {buildRipplePool();}- // pool wurde gerade gebaut, sicher non-null.+ // pool was just built, guaranteed non-null.const p = pool as RippleSlot[];const slot = p.find((s) => !s.inUse);if (slot === undefined) {- // Alle 8 Slots in-use. Plan §14.5 (Edge-Case) sagt "akzeptabel".+ // All 8 slots in use. Plan §14.5 (edge case) says "acceptable".return false;}@@ -77,9 +77,9 @@ export function triggerRipple(physicalX: number, physicalY: number): boolean {const cssY = physicalY / dpr;slot.inUse = true;- // Re-trigger der CSS-Animation: erst zuruecksetzen, dann setzen.- // Force reflow zwischen den beiden Klassen-Toggles damit die Animation- // wirklich neu startet (wichtig beim Pool-Reuse).+ // Re-trigger the CSS animation: reset first, then set.+ // Force reflow between the two class toggles so the animation+ // actually restarts (important on pool reuse).slot.el.classList.remove("active");slot.el.style.transform = `translate(${cssX}px, ${cssY}px) scale(0)`;slot.el.style.opacity = "1";@@ -87,7 +87,7 @@ export function triggerRipple(physicalX: number, physicalY: number): boolean {void slot.el.offsetWidth;slot.el.classList.add("active");- // Reset-Timer: nach 600 ms zurueck in den Pool.+ // Reset timer: back into the pool after 600 ms.if (slot.resetTimer !== null) {window.clearTimeout(slot.resetTimer);}@@ -103,7 +103,7 @@ export function triggerRipple(physicalX: number, physicalY: number): boolean {}/**- * Test-Helper: aktuelle Pool-Auslastung. Production nicht relevant.+ * Test helper: current pool utilization. Not relevant to production.*/export function ripplePoolStats(): { total: number; inUse: number } {if (pool === null) return { total: 0, inUse: 0 };@@ -114,7 +114,7 @@ export function ripplePoolStats(): { total: number; inUse: number } {}/**- * Test-Helper: Pool resetten zwischen Tests.+ * Test helper: reset the pool between tests.*/export function resetRipplePool(): void {if (pool !== null) {diff --git a/OS-Level/overlay-ui/src/edge-glow/typing-sweep.ts b/OS-Level/overlay-ui/src/edge-glow/typing-sweep.tsindex ce1c05228b..cdb98ea1d7 100644--- a/OS-Level/overlay-ui/src/edge-glow/typing-sweep.ts+++ b/OS-Level/overlay-ui/src/edge-glow/typing-sweep.ts@@ -1,12 +1,12 @@-// typing-sweep.ts — Bottom-Edge Sweep pro Tastendruck. Plan §16.+// typing-sweep.ts — Bottom-edge sweep per keystroke. Plan §16.//-// Single Sweep-Div am Bottom (4 px tall). triggerSweep() macht eine-// 200-ms-Animation (-100% -> +100% via translateX) und bumpt-// --intensity von 0.85 auf 1.2 fuer 200 ms.+// Single sweep div at the bottom (4 px tall). triggerSweep() runs a+// 200-ms animation (-100% -> +100% via translateX) and bumps+// --intensity from 0.85 to 1.2 for 200 ms.//-// scheduleSweepBurst(durationHintMs, n) verteilt n Sweeps gleichmaessig-// ueber die Action-Duration (Plan: "pulse N/100 Sweeps spread evenly").-// Das ist die Ambient-Variante fuer eine ganze Tipp-Phase.+// scheduleSweepBurst(durationHintMs, n) distributes n sweeps evenly+// over the action duration (Plan: "pulse N/100 sweeps spread evenly").+// This is the ambient variant for an entire typing phase.const SWEEP_DURATION_MS = 200; // Plan §16.1const INTENSITY_BOOST = 1.2;@@ -20,7 +20,7 @@ const burstHandles: number[] = [];let burstIntervalId: number | null = null;/**- * Erzeugt das Sweep-Div. Idempotent. Container default: ``document.body``.+ * Creates the sweep div. Idempotent. Container default: ``document.body``.*/export function buildTypingSweep(container?: HTMLElement): void {if (sweepEl !== null) return;@@ -31,20 +31,20 @@ export function buildTypingSweep(container?: HTMLElement): void {}/**- * Triggert ein einzelnes Sweep + Intensity-Bump. Re-trigger-fest:- * cancelt einen laufenden Sweep und startet neu.+ * Triggers a single sweep + intensity bump. Re-trigger safe:+ * cancels a running sweep and starts a new one.*/export function triggerSweep(): void {if (sweepEl === null) buildTypingSweep();const el = sweepEl as HTMLElement;const root = document.documentElement;- // Sweep neu starten — class entfernen, reflow, class wieder setzen.+ // Restart the sweep — remove class, reflow, re-add class.el.classList.remove("active");void el.offsetWidth;el.classList.add("active");- // Intensity-Bump.+ // Intensity bump.root.style.setProperty("--intensity", String(INTENSITY_BOOST));if (intensityResetTimer !== null) {window.clearTimeout(intensityResetTimer);@@ -64,11 +64,11 @@ export function triggerSweep(): void {}/**- * Ambient-Burst: pulst ``ceil(durationHintMs / 100)`` Sweeps verteilt- * ueber die action-Duration. Plan: "pulse N/100 Sweeps spread evenly".+ * Ambient burst: pulses ``ceil(durationHintMs / 100)`` sweeps spread+ * over the action duration. Plan: "pulse N/100 sweeps spread evenly".*- * Cancelt eine laufende Burst (z.B. wenn ein neuer typing-Action den- * laufenden ueberlappt).+ * Cancels a running burst (e.g. when a new typing action overlaps+ * the running one).*/export function scheduleSweepBurst(durationHintMs: number): void {cancelSweepBurst();@@ -76,11 +76,11 @@ export function scheduleSweepBurst(durationHintMs: number): void {triggerSweep();return;}- // 1 Sweep pro 100 ms, mindestens 1.+ // 1 sweep per 100 ms, at least 1.const total = Math.max(1, Math.ceil(durationHintMs / 100));const interval = durationHintMs / total;- // Ersten Sweep sofort, danach intervall-based.+ // First sweep immediately, then interval-based.triggerSweep();let fired = 1;burstIntervalId = window.setInterval(() => {@@ -94,8 +94,8 @@ export function scheduleSweepBurst(durationHintMs: number): void {}/**- * Bricht einen laufenden Burst ab. Sweep-Animation laeuft aus, aber- * keine weiteren werden gespawnt.+ * Aborts a running burst. The sweep animation runs out, but no+ * further sweeps get spawned.*/export function cancelSweepBurst(): void {if (burstIntervalId !== null) {@@ -109,10 +109,10 @@ export function cancelSweepBurst(): void {}/**- * Lower-Bound der Intensity zwischen Sweep-Bursts (action_started bis- * action_ended bleibt --intensity bei INTENSITY_LOWER damit der Glow- * dimmer wirkt zwischen Tastenanschlaegen). Optional — main.ts ruft- * das auf typing-action_started auf.+ * Lower bound of intensity between sweep bursts (from action_started+ * to action_ended, --intensity stays at INTENSITY_LOWER so the glow+ * looks dimmer between keystrokes). Optional — main.ts calls this on+ * typing-action_started.*/export function applySweepBaseline(active: boolean): void {document.documentElement.style.setProperty(@@ -122,7 +122,7 @@ export function applySweepBaseline(active: boolean): void {}/**- * Test-Helper: tear-down.+ * Test helper: tear-down.*/export function teardownTypingSweep(): void {cancelSweepBurst();diff --git a/OS-Level/overlay-ui/src/mascot/main.ts b/OS-Level/overlay-ui/src/mascot/main.tsindex 8ce85e28b8..bf12de5a5d 100644--- a/OS-Level/overlay-ui/src/mascot/main.ts+++ b/OS-Level/overlay-ui/src/mascot/main.ts@@ -1,20 +1,20 @@// Mascot Renderer Entry. Plan §13 + AD-16.//-// Phase 9.6 ENTSCHEIDUNG (im Commit dokumentiert): PNG-Fallback only.-// Begruendung: Rive-Files (.riv) sind ein proprietaeres Binary-Format-// das nur im Rive-Editor erstellt werden kann; ich kann das nicht-// generativ produzieren. Plan AD-16 erlaubt explizit den Fallback.-// Ein echtes Rive-Asset kann spaeter via 'overlay-ui/src/mascot/-// mascot.riv' nachgereicht werden — der Code-Pfad unten lade-versucht-// es zuerst und faellt auf das PNG zurueck wenn nicht da.+// Phase 9.6 DECISION (documented in the commit): PNG fallback only.+// Rationale: Rive files (.riv) are a proprietary binary format that+// can only be created in the Rive editor; it can't be produced+// generatively. Plan AD-16 explicitly allows the fallback.+// A real Rive asset can be supplied later via 'overlay-ui/src/mascot/+// mascot.riv' — the code path below tries to load it first and falls+// back to the PNG if it's not there.//// Boot:-// 1. CSS importieren.-// 2. PNG via fallback.png import (Vite hashed das URL).-// 3. Versuche mascot.riv zu laden mit @rive-app/canvas-lite. Wenn-// das Asset nicht da ist (404 oder Decode-Fail), zeige PNG.-// 4. QWebChannel connecten -> data-state Attribut auf <html> setzen.-// Bei Rive: zusaetzlich State-Machine-Inputs triggern.+// 1. Import the CSS.+// 2. PNG via fallback.png import (Vite hashes the URL).+// 3. Try to load mascot.riv with @rive-app/canvas-lite. If the+// asset isn't there (404 or decode failure), show the PNG.+// 4. Connect QWebChannel -> set the data-state attribute on <html>.+// With Rive: additionally trigger state-machine inputs.import "./mascot.css";@@ -24,9 +24,9 @@ import { connectBridge } from "../bridge";import type { StateName } from "../schema";const ROOT = document.documentElement;-// Vite ignoriert das URL — wir wollen explizit Optional-File-Lookup-// zur Laufzeit. Ohne @vite-ignore wuerde Vite eine Build-Warning-// emittieren weil das Asset noch nicht existiert.+// Vite ignores the URL — we explicitly want an optional file lookup at+// runtime. Without @vite-ignore, Vite would emit a build warning+// because the asset doesn't exist yet.const RIVE_ASSET_URL = new URL(/* @vite-ignore */ "./mascot.riv",import.meta.url,@@ -59,8 +59,8 @@ function showFallback(): void {}async function attemptRiveLoad(): Promise<boolean> {- // Lazy-import damit @rive-app/canvas-lite nicht in den Main-Bundle- // muss wenn das Asset fehlt.+ // Lazy import so @rive-app/canvas-lite doesn't have to end up in the+ // main bundle when the asset is missing.let RiveModule: { Rive: new (cfg: Record<string, unknown>) => RiveLikeRuntime; Layout?: unknown };try {RiveModule = (await import("@rive-app/canvas-lite")) as unknown as typeof RiveModule;@@ -69,10 +69,10 @@ async function attemptRiveLoad(): Promise<boolean> {return false;}- // Kein HEAD-Preflight: vermeidet Console-Network-Errors bei file://-URLs- // (QtWebEngine-Production) und potenzielle Network-Leaks bei remote URLs.- // Rive's onLoadError Callback (unten) ist der canonical Path fuer 404 ->- // PNG-Fallback.+ // No HEAD preflight: avoids console network errors on file:// URLs+ // (QtWebEngine production) and potential network leaks on remote URLs.+ // Rive's onLoadError callback (below) is the canonical path for+ // 404 -> PNG fallback.const canvas = document.getElementById("mascot-canvas") as HTMLCanvasElement | null;if (canvas === null) {console.warn("[mascot] canvas#mascot-canvas missing");@@ -107,7 +107,7 @@ function applyStateToRive(state: StateName): void {if (rive === null) return;const inputs = rive.stateMachineInputs("State Machine 1");if (inputs === null) return;- // Plan §13.2: trigger-named-Input je State.+ // Plan §13.2: trigger-named input per state.const triggerName = state === "typing" || state === "clicking" ? "acting" : state;for (const inp of inputs) {if (inp.name === triggerName && typeof inp.fire === "function") {diff --git a/OS-Level/overlay-ui/src/mascot/mascot.css b/OS-Level/overlay-ui/src/mascot/mascot.cssindex 6668bb3fc4..ac9c6d9999 100644--- a/OS-Level/overlay-ui/src/mascot/mascot.css+++ b/OS-Level/overlay-ui/src/mascot/mascot.css@@ -1,9 +1,9 @@/* mascot.css — Plan §13.*- * Body + Window sind transparent, Mascot fuellt das volle 160x160- * Window. Rive-Canvas oder PNG-Fallback wird als 100%-Surface- * eingespannt; CSS animiert nur einen leichten idle-Pulse fuer den- * Fall dass weder Rive noch State-Animation greift.+ * Body + window are transparent, the mascot fills the full 160x160+ * window. The Rive canvas or PNG fallback is stretched to a 100%+ * surface; CSS only animates a subtle idle pulse for the case where+ * neither Rive nor a state animation applies.*/html,@@ -14,9 +14,9 @@ body {height: 100vh;background: transparent;overflow: hidden;- /* Plan §17: contain: strict am Mascot-Root. */+ /* Plan §17: contain: strict on the mascot root. */contain: strict;- /* Mascot ist drag/right-click-empfindlich — pointer-events default. */+ /* The mascot is drag/right-click-sensitive — pointer-events default. */}.mascot-host {@@ -25,8 +25,8 @@ body {display: flex;align-items: center;justify-content: center;- /* Subtle idle-Pulse via opacity. Plan §13.1 sagt "gentle, not eye-- * catching". Transform-only animation = compositor-thread. */+ /* Subtle idle pulse via opacity. Plan §13.1 says "gentle, not eye-+ * catching". Transform-only animation = compositor thread. */animation: mascot-idle-pulse 8s ease-in-out infinite;}@@ -34,8 +34,8 @@ body {#mascot-fallback {width: 100%;height: 100%;- /* Pixel-art bzw. PNG soll knack-scharf bleiben wenn der User- * eine andere Mascot-Groesse waehlt. */+ /* Pixel art / PNG should stay crisp-sharp when the user+ * picks a different mascot size. */image-rendering: pixelated;image-rendering: crisp-edges;user-select: none;@@ -60,9 +60,9 @@ body {}}-/* State-driven Tweaks — Plan §13.2 mappt OverlayState auf Rive-Inputs;- * im Fallback machen wir einen statischen Tint via CSS-Filter so dass- * der User zumindest die State-Aenderung subtil sieht. */+/* State-driven tweaks — Plan §13.2 maps OverlayState onto Rive inputs;+ * in the fallback we apply a static tint via CSS filter so the user+ * at least sees the state change subtly. */:root[data-state="error"] .mascot-host {animation:mascot-idle-pulse 8s ease-in-out infinite,@@ -95,7 +95,7 @@ body {}}-/* prefers-reduced-motion: Mascot-Animationen pausieren, statisch. */+/* prefers-reduced-motion: pause mascot animations, static. */@media (prefers-reduced-motion: reduce) {.mascot-host,.mascot-host * {diff --git a/OS-Level/overlay-ui/src/schema.ts b/OS-Level/overlay-ui/src/schema.tsindex 5fad7690b9..6ade9c8ee6 100644--- a/OS-Level/overlay-ui/src/schema.ts+++ b/OS-Level/overlay-ui/src/schema.ts@@ -1,7 +1,7 @@-// Zod-Schemas, gespiegelt zu den Pydantic-v2-Modellen in-// OS-Level/src/overlay/schema.py. Symmetrie ist Plan AD-15. Phase 9.3-// braucht nur den State-Slice; weitere Envelopes wandern hierher mit-// 9.4ff.+// Zod schemas, mirrored to the Pydantic v2 models in+// OS-Level/src/overlay/schema.py. Symmetry is Plan AD-15. Phase 9.3+// only needs the state slice; more envelopes will move here in+// 9.4 and beyond.import { z } from "zod";@@ -18,8 +18,8 @@ export const StateNameSchema = z.enum([export type StateName = z.infer<typeof StateNameSchema>;-// (old, new, reason) — passend zur Signatur von StateBridge.stateChanged-// auf der Python-Seite (window_glow.py).+// (old, new, reason) — matches the signature of StateBridge.stateChanged+// on the Python side (window_glow.py).export const StateChangeSchema = z.object({old: StateNameSchema,next: StateNameSchema,diff --git a/OS-Level/overlay-ui/src/vite-env.d.ts b/OS-Level/overlay-ui/src/vite-env.d.tsindex dc95ff5092..f042c5c7f7 100644--- a/OS-Level/overlay-ui/src/vite-env.d.ts+++ b/OS-Level/overlay-ui/src/vite-env.d.ts@@ -1,5 +1,5 @@-// Ambient declarations fuer Vite-spezifische Imports.-// Strict-Mode wuerde sonst meckern dass der Default-Export untyped ist.+// Ambient declarations for Vite-specific imports.+// Otherwise strict mode would complain that the default export is untyped.declare module "*.svg?raw" {const content: string;diff --git a/OS-Level/overlay-ui/vite.config.ts b/OS-Level/overlay-ui/vite.config.tsindex 73c55073fb..ea4937b6a6 100644--- a/OS-Level/overlay-ui/vite.config.ts+++ b/OS-Level/overlay-ui/vite.config.ts@@ -1,8 +1,8 @@import { defineConfig } from "vite";import { resolve } from "path";-// Multi-Entry: edge-glow.html und (spaeter) mascot.html. Vite legt sie-// flach in dist/ ab — window_glow.py laedt dist/edge-glow.html via+// Multi-entry: edge-glow.html and (later) mascot.html. Vite places them+// flat in dist/ — window_glow.py loads dist/edge-glow.html via// QUrl.fromLocalFile.export default defineConfig({base: "./",@@ -16,8 +16,8 @@ export default defineConfig({"mascot": resolve(__dirname, "mascot.html"),},output: {- // Flache Output-Struktur, damit QtWebEngine relative Pfade- // einfach aufloesen kann (assets/ als Geschwister-Ordner zur HTML).+ // Flat output structure, so QtWebEngine can resolve relative+ // paths easily (assets/ as a sibling folder to the HTML).entryFileNames: "assets/[name]-[hash].js",chunkFileNames: "assets/[name]-[hash].js",assetFileNames: "assets/[name]-[hash][extname]",diff --git a/OS-Level/pyproject.toml b/OS-Level/pyproject.tomlindex 0f4591f361..de7d5a6b93 100644--- a/OS-Level/pyproject.toml+++ b/OS-Level/pyproject.toml@@ -5,7 +5,7 @@ build-backend = "setuptools.build_meta"[project]name = "overlay"version = "0.1.0"-description = "OS-Level Edge-Glow Overlay für Personal Jarvis (Phase 9)"+description = "OS-Level Edge-Glow Overlay for Personal Jarvis (Phase 9)"readme = "README.md"requires-python = ">=3.11"license = { text = "Proprietary" }diff --git a/OS-Level/src/overlay/__main__.py b/OS-Level/src/overlay/__main__.pyindex 84ac82975c..ae22ca83aa 100644--- a/OS-Level/src/overlay/__main__.py+++ b/OS-Level/src/overlay/__main__.py@@ -1,15 +1,15 @@-"""Entry-Point fuer ``python -m overlay``."""+"""Entry point for ``python -m overlay``."""from __future__ import annotationsimport faulthandlerimport sys-# Native-Crash-Forensik: Qt-Aborts (qFatal, STATUS_BREAKPOINT 0x80000003)-# drucken normalerweise NICHTS auf stderr — der Process stirbt einfach.-# faulthandler.enable() haengt einen Signal-Handler ein, der bei Native--# Crash einen Python-Stack-Trace nach stderr schreibt. Ohne das ist-# Subprocess-Diagnose unmoeglich.+# Native-crash forensics: Qt aborts (qFatal, STATUS_BREAKPOINT 0x80000003)+# normally print NOTHING to stderr — the process just dies.+# faulthandler.enable() installs a signal handler that writes a Python+# stack trace to stderr on a native crash. Without it, subprocess+# diagnosis is impossible.faulthandler.enable()from .main import main # noqa: E402diff --git a/OS-Level/src/overlay/config.py b/OS-Level/src/overlay/config.pyindex 1ef5bda296..0141846b8f 100644--- a/OS-Level/src/overlay/config.py+++ b/OS-Level/src/overlay/config.py@@ -1,6 +1,6 @@-"""OverlayConfig — Pydantic v2 Modell gemaess Plan §21.1.+"""OverlayConfig — Pydantic v2 model per Plan §21.1.-Hot-Reload ist Phase 9.2-Thema. Hier nur das Modell + ``from_toml``.+Hot-reload is a Phase 9.2 topic. This only has the model + ``from_toml``."""from __future__ import annotations@@ -18,12 +18,12 @@ _LOOPBACK_HOSTS: frozenset[str] = frozenset({"127.0.0.1", "::1", "localhost"})def _validate_hex_color(value: str) -> str:if not _HEX_COLOR_RE.match(value):- raise ValueError(f"erwartet '#RRGGBB', bekommen: {value!r}")+ raise ValueError(f"expected '#RRGGBB', got: {value!r}")return valueclass OverlayThemeConfig(BaseModel):- """Farben & Glow-Geometrie. Plan §7.1, §7.2, §21.1."""+ """Colors & glow geometry. Plan §7.1, §7.2, §21.1."""model_config = ConfigDict(extra="forbid")@@ -41,7 +41,7 @@ class OverlayThemeConfig(BaseModel):class OverlayMascotConfig(BaseModel):- """Maskottchen-Position + Drag-Verhalten. Plan §13.4, §21.1."""+ """Mascot position + drag behavior. Plan §13.4, §21.1."""model_config = ConfigDict(extra="forbid")@@ -55,7 +55,7 @@ class OverlayMascotConfig(BaseModel):class OverlayConfig(BaseModel):- """Top-Level [overlay]-Section. Plan §21.1."""+ """Top-level [overlay] section. Plan §21.1."""model_config = ConfigDict(extra="forbid")@@ -93,12 +93,12 @@ class OverlayConfig(BaseModel):@classmethoddef _check_loopback(cls, v: str) -> str:if v not in _LOOPBACK_HOSTS:- raise ValueError(f"ws_host muss Loopback sein, bekommen: {v!r}")+ raise ValueError(f"ws_host must be loopback, got: {v!r}")return v@classmethoddef from_toml(cls, path: str | Path) -> "OverlayConfig":- """Lese ``[overlay]``-Section aus TOML. Wenn fehlt: Defaults (Plan §21.4)."""+ """Read the ``[overlay]`` section from TOML. If missing: use defaults (Plan §21.4)."""toml_path = Path(path)with toml_path.open("rb") as f:data: dict[str, Any] = tomllib.load(f)diff --git a/OS-Level/src/overlay/cursor_shm.py b/OS-Level/src/overlay/cursor_shm.pyindex 068139321e..a664d8eebe 100644--- a/OS-Level/src/overlay/cursor_shm.py+++ b/OS-Level/src/overlay/cursor_shm.py@@ -1,10 +1,10 @@-"""Cursor-Stream Shared-Memory Layout + Reader. Plan §11 + AD-5.+"""Cursor-stream shared-memory layout + reader. Plan §11 + AD-5.-32-Byte fixed-layout Block, single-writer (Hauptjarvis) /-single-reader (Overlay). Lock-frei via Seqlock-Pattern (odd seq =+32-byte fixed-layout block, single-writer (Hauptjarvis) /+single-reader (overlay). Lock-free via a seqlock pattern (odd seq =writer mid-write, even seq = quiescent).-Plan §11.2 Layout (little-endian, total 32 bytes):+Plan §11.2 layout (little-endian, total 32 bytes):| offset | size | type | field || 0 | 8 | int64 LE | ts_ns | Unix-epoch ns@@ -14,17 +14,17 @@ Plan §11.2 Layout (little-endian, total 32 bytes):| 20 | 4 | uint32 LE | monitor_idx | screen index| 24 | 8 | - | reserved | padding to 32-Reader-Pattern (Plan §11.3): seq_before, dann Daten, dann seq_after.-Wenn seq_before & 1 -> Writer mid-write, retry. Wenn seq_before !=-seq_after -> torn read, retry. Sonst Frame valid.+Reader pattern (Plan §11.3): seq_before, then data, then seq_after.+If seq_before & 1 -> writer mid-write, retry. If seq_before !=+seq_after -> torn read, retry. Otherwise the frame is valid.-Writer-Pattern (Plan §11.4): _seq+1 als ungerade BUSY publishen,-Daten schreiben, _seq+2 als gerade DONE publishen.+Writer pattern (Plan §11.4): publish _seq+1 as odd BUSY, write data,+publish _seq+2 as even DONE.-Diese Datei enthaelt BEIDE Klassen (Reader + Writer) damit das-Layout an genau einer Stelle definiert ist. Hauptjarvis-side gibt es-``jarvis/overlay/cursor_writer.py`` als Convenience-Wrapper inkl.-Streamer-Thread; der nutzt diesen Writer hier.+This file contains BOTH classes (reader + writer) so the layout is+defined in exactly one place. On the Hauptjarvis side there's+``jarvis/overlay/cursor_writer.py`` as a convenience wrapper including+the streamer thread; it uses this writer under the hood."""from __future__ import annotations@@ -40,7 +40,7 @@ from typing import Optionallogger = logging.getLogger(__name__)-# Plan §11.1 — fixed 32-Byte Block.+# Plan §11.1 — fixed 32-byte block.CURSOR_SHM_SIZE: int = 32# struct.pack/unpack format:@@ -55,7 +55,7 @@ CURSOR_SHM_SIZE: int = 32CURSOR_SHM_STRUCT: str = "<qiiII8s"assert struct.calcsize(CURSOR_SHM_STRUCT) == CURSOR_SHM_SIZE-# Offsets fuer Single-Field-Reads (Reader pattern braucht seq-only Reads).+# Offsets for single-field reads (the reader pattern needs seq-only reads)._OFFSET_TS = 0_OFFSET_X = 8_OFFSET_Y = 12@@ -65,13 +65,13 @@ _PADDING_BYTES = bytes(8) # zero-paddingdef make_cursor_shm_name() -> str:- """Plan §11.1: ``jarvis-cursor-{8 hex chars}`` random-per-session."""+ """Plan §11.1: ``jarvis-cursor-{8 hex chars}`` random per session."""return f"jarvis-cursor-{secrets.token_hex(4)}"@dataclass(frozen=True)class CursorFrame:- """Ein erfolgreich gelesener Cursor-Frame."""+ """A successfully read cursor frame."""ts_ns: intx: int@@ -81,7 +81,7 @@ class CursorFrame:class CursorShmReader:- """Overlay-Side Reader. Nicht-blockierend, Seqlock-Pattern.+ """Overlay-side reader. Non-blocking, seqlock pattern.Lifecycle::@@ -95,10 +95,10 @@ class CursorShmReader:finally:reader.close()- ``attach()`` bindet an einen existierenden Block — wirft- ``FileNotFoundError`` wenn der Writer (Hauptjarvis) noch nicht- publiziert hat. ``close()`` released nur die Reader-Referenz; der- Writer (Owner) ist fuer ``unlink()`` verantwortlich.+ ``attach()`` binds to an existing block — raises+ ``FileNotFoundError`` if the writer (Hauptjarvis) hasn't published+ yet. ``close()`` only releases the reader reference; the writer+ (owner) is responsible for ``unlink()``."""def __init__(self, shm: shared_memory.SharedMemory) -> None:@@ -110,29 +110,29 @@ class CursorShmReader:@classmethoddef attach(cls, name: str) -> "CursorShmReader":- """Bindet an einen existierenden Block. ``FileNotFoundError`` wenn weg."""+ """Binds to an existing block. ``FileNotFoundError`` if it's gone."""shm = shared_memory.SharedMemory(name=name, create=False)return cls(shm)def read(self) -> Optional[CursorFrame]:- """Plan §11.3 Seqlock-Read.-- Returnt:- * ``CursorFrame`` bei sauberem Read mit neuen Daten.- * ``None`` wenn:- - Writer mid-write (seq odd)- - keine neuen Daten (seq == last_seq)- - torn read (seq vorher != nachher)+ """Plan §11.3 seqlock read.++ Returns:+ * ``CursorFrame`` on a clean read with new data.+ * ``None`` if:+ - the writer is mid-write (seq odd)+ - there is no new data (seq == last_seq)+ - it was a torn read (seq before != after)"""- # Wir koennen direkt per memoryview slicen; struct.unpack_from- # ist genauso schnell und liest native int Types.+ # We can slice directly via memoryview; struct.unpack_from+ # is just as fast and reads native int types.seq_before = struct.unpack_from("<I", self._buf, _OFFSET_SEQ)[0]if seq_before & 1:- return None # Writer mid-write+ return None # writer mid-writeif seq_before == self._last_seq:- return None # nichts Neues+ return None # nothing newif seq_before == 0:- # Block ist initialized aber Writer hat noch nie publiziert.+ # Block is initialized but the writer has never published.return Nonets_ns = struct.unpack_from("<q", self._buf, _OFFSET_TS)[0]@@ -142,7 +142,7 @@ class CursorShmReader:seq_after = struct.unpack_from("<I", self._buf, _OFFSET_SEQ)[0]if seq_before != seq_after:- return None # Writer schrieb waehrend wir lasen -> torn+ return None # writer wrote while we were reading -> tornself._last_seq = seq_afterreturn CursorFrame(@@ -158,11 +158,11 @@ class CursorShmReader:return self._last_seqdef close(self) -> None:- """Released die Reader-Sicht. Macht KEIN unlink (Writer is owner)."""+ """Releases the reader view. Does NOT unlink (the writer is owner)."""try:self._buf.release()except (ValueError, BufferError):- # memoryview bereits released — OK.+ # memoryview already released — OK.passtry:self._shm.close()@@ -171,15 +171,15 @@ class CursorShmReader:class CursorShmWriter:- """Producer-Side Writer. Plan §11.4 Seqlock-Pattern.+ """Producer-side writer. Plan §11.4 seqlock pattern.- Owner of the SHM block — ``close()`` ruft ``unlink()`` damit der- Block nach Process-Exit nicht leakt (relevant fuer Linux; Windows- GC'd das eh wenn alle Handles weg sind).+ Owner of the SHM block — ``close()`` calls ``unlink()`` so the+ block doesn't leak after process exit (relevant for Linux; Windows+ GCs it anyway once all handles are gone).- Wird hier in OS-Level definiert damit Layout an einer Stelle lebt.- Hauptjarvis nutzt ``jarvis.overlay.cursor_writer.CursorStreamer``- der diesen Writer wrapped.+ Defined here in OS-Level so the layout lives in one place.+ Hauptjarvis uses ``jarvis.overlay.cursor_writer.CursorStreamer``,+ which wraps this writer."""def __init__(self, shm: shared_memory.SharedMemory, *, owner: bool = True) -> None:@@ -188,31 +188,31 @@ class CursorShmWriter:self._shm = shmself._buf = shm.bufself._owner = owner- # Plan §11.4: ``_seq`` startet bei 0 (gerade), erstes- # publiziertes Frame endet mit seq=2.+ # Plan §11.4: ``_seq`` starts at 0 (even), the first+ # published frame ends with seq=2.self._seq: int = 0- # Initialer Block-Inhalt: alles 0 (seq=0 -> "noch nie publiziert").- # ``shared_memory.SharedMemory(create=True)`` liefert das auf- # POSIX/Windows bereits zero'd.+ # Initial block content: all 0 (seq=0 -> "never published yet").+ # ``shared_memory.SharedMemory(create=True)`` already delivers+ # that zero'd on POSIX/Windows.@classmethoddef create(cls, name: Optional[str] = None) -> "CursorShmWriter":- """Erzeugt einen NEUEN Block. Standard-Name via ``make_cursor_shm_name()``."""+ """Creates a NEW block. Default name via ``make_cursor_shm_name()``."""if name is None:name = make_cursor_shm_name()shm = shared_memory.SharedMemory(name=name, create=True, size=CURSOR_SHM_SIZE)- # Sicherstellen dass die ersten 32 Bytes 0 sind (POSIX ist garantiert,- # Windows ist es auch — aber explizit ist robuster).+ # Make sure the first 32 bytes are 0 (guaranteed on POSIX,+ # true on Windows too — but explicit is more robust).shm.buf[:CURSOR_SHM_SIZE] = bytes(CURSOR_SHM_SIZE)return cls(shm, owner=True)def write(self, x: int, y: int, monitor_idx: int) -> int:- """Plan §11.4 Seqlock-Write. Returnt die finale ``seq``.+ """Plan §11.4 seqlock write. Returns the final ``seq``.- Pattern: seq_busy (ungerade) -> Daten -> seq_done (gerade).- Nach diesem Call ist ``self._seq`` gerade und = neuer Wert.+ Pattern: seq_busy (odd) -> data -> seq_done (even).+ After this call, ``self._seq`` is even and equals the new value."""- seq_busy = self._seq + 1 # ungerade+ seq_busy = self._seq + 1 # oddstruct.pack_into("<I", self._buf, _OFFSET_SEQ, seq_busy)ts_ns = time.time_ns()struct.pack_into("<q", self._buf, _OFFSET_TS, ts_ns)@@ -220,7 +220,7 @@ class CursorShmWriter:struct.pack_into("<i", self._buf, _OFFSET_Y, int(y))struct.pack_into("<I", self._buf, _OFFSET_MONITOR, int(monitor_idx))struct.pack_into("<8s", self._buf, 24, _PADDING_BYTES)- seq_done = seq_busy + 1 # gerade+ seq_done = seq_busy + 1 # evenstruct.pack_into("<I", self._buf, _OFFSET_SEQ, seq_done)self._seq = seq_donereturn seq_done@@ -234,7 +234,7 @@ class CursorShmWriter:return self._seqdef close(self) -> None:- """Schliesst + unlinked (wenn owner)."""+ """Closes + unlinks (if owner)."""try:self._buf.release()except (ValueError, BufferError):@@ -247,9 +247,9 @@ class CursorShmWriter:try:self._shm.unlink()except (FileNotFoundError, Exception): # noqa: BLE001- # Auf Windows ist unlink ein no-op (resource_tracker- # handled das); FileNotFoundError ok wenn doppelt- # geschlossen.+ # On Windows, unlink is a no-op (resource_tracker+ # handles that); FileNotFoundError is fine if closed+ # twice.passdiff --git a/OS-Level/src/overlay/event_router.py b/OS-Level/src/overlay/event_router.pyindex 82df4d922d..e0cd2f26b6 100644--- a/OS-Level/src/overlay/event_router.py+++ b/OS-Level/src/overlay/event_router.py@@ -1,15 +1,15 @@-"""IPC-Envelope -> StateMachine-Transition Mapping. Plan §6.3.+"""IPC envelope -> StateMachine transition mapping. Plan §6.3.-Der EventRouter ist die einzige Komponente die IPC-Wire-Format-Wissen mit-State-Semantik verbindet. Er kennt KEINE Qt- und KEINE asyncio-APIs —-das macht ihn unabhaengig testbar und in Subprocess- wie Worker-Thread--Kontexten verwendbar.+The EventRouter is the only component that connects IPC wire-format+knowledge with state semantics. It knows NO Qt and NO asyncio APIs —+that makes it independently testable and usable in both subprocess and+worker-thread contexts.-Mapping (gemaess Plan §6.3):+Mapping (per Plan §6.3):| Envelope | Transition ||----------------------------|----------------------------------|-| StateEnvelope | direkt nach payload.state |+| StateEnvelope | direct, from payload.state || ActionStartedEnvelope | TYPING (kind in {type, hotkey}) || | CLICKING (kind in {click, move, || | navigate, scroll}) |@@ -41,32 +41,32 @@ from .state import OverlayState, StateMachinelogger = logging.getLogger(__name__)-# Action-Kind -> State Buckets. Plan §6.3 listet nur TYPING und CLICKING-# als Action-States; alle 6 Computer-Use-Kinds werden auf eines davon-# gemappt damit jeder Action-Started-Event auch wirklich Glow ausloest.+# Action-kind -> state buckets. Plan §6.3 lists only TYPING and CLICKING+# as action states; all 6 Computer-Use kinds are mapped onto one of+# those two so every action-started event actually triggers the glow.TYPING_KINDS: frozenset[str] = frozenset({"type", "hotkey"})CLICKING_KINDS: frozenset[str] = frozenset({"click", "move", "navigate", "scroll"})-# Reasons fuer programmatic Transitions — Plan-Erlaubt: ``StateReason`` Literal.+# Reasons for programmatic transitions — plan-allowed: ``StateReason`` literal.REASON_TOOL = "tool"REASON_ERROR = "error"class EventRouter:- """Konvertiert IPC-Envelopes nach StateMachine-Transitionen.+ """Converts IPC envelopes into StateMachine transitions.- Plan AD-8: State-Logic lebt im Overlay-Prozess — diese Klasse ist die- Bruecke zwischen Wire-Format (``schema.py``) und State-Holder- (``state.py``).+ Plan AD-8: state logic lives in the overlay process — this class is+ the bridge between the wire format (``schema.py``) and the state+ holder (``state.py``).- Aufruf typischerweise via ``WSClient.set_on_message(router.handle)``.+ Typically invoked via ``WSClient.set_on_message(router.handle)``."""def __init__(self, machine: StateMachine) -> None:self._machine = machine- # Phase 9.5 Effect-Hooks. Subscriber bekommen das Envelope-Objekt- # selbst (nicht nur Payload) damit sie auf alle Felder zugreifen- # koennen.+ # Phase 9.5 effect hooks. Subscribers receive the envelope+ # object itself (not just the payload) so they can access all+ # fields.self._click_hooks: list[Any] = []self._action_started_hooks: list[Any] = []self._action_ended_hooks: list[Any] = []@@ -77,19 +77,19 @@ class EventRouter:return self._machinedef add_click_hook(self, fn: Any) -> None:- """Wird mit ``ClickEnvelope`` gerufen, sync, im Caller-Thread."""+ """Called with ``ClickEnvelope``, sync, on the caller thread."""self._click_hooks.append(fn)def add_action_started_hook(self, fn: Any) -> None:- """Wird mit ``ActionStartedEnvelope`` gerufen."""+ """Called with ``ActionStartedEnvelope``."""self._action_started_hooks.append(fn)def add_action_ended_hook(self, fn: Any) -> None:- """Wird mit ``ActionEndedEnvelope`` gerufen."""+ """Called with ``ActionEndedEnvelope``."""self._action_ended_hooks.append(fn)def add_cursor_hook(self, fn: Any) -> None:- """Wird mit ``CursorEnvelope`` gerufen (WS-Fallback wenn SHM aus)."""+ """Called with ``CursorEnvelope`` (WS fallback when SHM is off)."""self._cursor_hooks.append(fn)def _safe_dispatch(self, hooks: list[Any], envelope: Any) -> None:@@ -100,12 +100,12 @@ class EventRouter:logger.exception("EventRouter hook raised on %s", type(envelope).__name__)def handle(self, envelope: Any) -> bool:- """Verarbeitet einen einzelnen Envelope.+ """Processes a single envelope.- Returnt ``True`` wenn eine echte State-Transition ausgeloest wurde,- ``False`` bei No-Op (Heartbeat, Coalescing-Hit, unbekannter Type).+ Returns ``True`` if a real state transition was triggered,+ ``False`` on a no-op (heartbeat, coalescing hit, unknown type)."""- # StateEnvelope: Hauptjarvis sagt explizit "neuer State".+ # StateEnvelope: Hauptjarvis explicitly says "new state".if isinstance(envelope, StateEnvelope):try:target = OverlayState(envelope.payload.state)@@ -119,7 +119,7 @@ class EventRouter:target, reason=envelope.payload.reason)- # ActionStarted: Hauptjarvis bedient Maus/Tastatur -> Glow an.+ # ActionStarted: Hauptjarvis is operating the mouse/keyboard -> glow on.if isinstance(envelope, ActionStartedEnvelope):self._safe_dispatch(self._action_started_hooks, envelope)kind = envelope.payload.kind@@ -131,36 +131,37 @@ class EventRouter:return self._machine.transition_to(OverlayState.CLICKING, reason=REASON_TOOL)- logger.debug("EventRouter: action_started kind %r ohne Mapping", kind)+ logger.debug("EventRouter: action_started kind %r has no mapping", kind)return False- # ActionEnded: Action vorbei -> zurueck nach IDLE.- # Hoehere Layer (Wakeword/STT/TTS) restoren danach selbst die- # naechste Action-State per eigenem Event.+ # ActionEnded: action is over -> back to IDLE.+ # Higher layers (wakeword/STT/TTS) then restore the next action+ # state themselves via their own event.if isinstance(envelope, ActionEndedEnvelope):self._safe_dispatch(self._action_ended_hooks, envelope)return self._machine.transition_to(OverlayState.IDLE, reason=REASON_TOOL)- # ClickEvent: Atomare Klick-Notification (Plan §6.3 +- # Click-Visualization §14). State-Bump nach CLICKING + Hook- # fires fuer Ripple-Trigger.+ # ClickEvent: atomic click notification (Plan §6.3 ++ # click-visualization §14). State bump to CLICKING + hook+ # fires for the ripple trigger.if isinstance(envelope, ClickEnvelope):self._safe_dispatch(self._click_hooks, envelope)return self._machine.transition_to(OverlayState.CLICKING, reason=REASON_TOOL)- # Cursor: WS-Fallback Plan §11.5 — wenn SHM disabled. Hook- # forwarded coords. KEIN State-Change.+ # Cursor: WS fallback Plan §11.5 — when SHM is disabled. Hook+ # forwards the coords. NO state change.if isinstance(envelope, CursorEnvelope):self._safe_dispatch(self._cursor_hooks, envelope)return False- # Recoverable Error -> ERROR State (kurze Amber/Red-Phase, Plan- # §6.1). Non-recoverable wird nicht visualisiert weil Hauptjarvis- # ohnehin gleich crasht; Supervisor fangt das auf Process-Level.+ # Recoverable error -> ERROR state (brief amber/red phase, Plan+ # §6.1). Non-recoverable isn't visualized because Hauptjarvis+ # is about to crash anyway; the supervisor catches that at the+ # process level.if isinstance(envelope, ErrorEnvelope):if envelope.payload.recoverable:return self._machine.transition_to(@@ -168,10 +169,10 @@ class EventRouter:)return False- # No-Op-Envelope-Typen — explizit gelistet damit unbekannte- # Envelope-Klassen unten als WARNING auffliegen. (CursorEnvelope- # ist oben behandelt, weil es nur Hook-fired aber kein State-- # Change.)+ # No-op envelope types — listed explicitly so unknown envelope+ # classes surface as a WARNING below. (CursorEnvelope is+ # handled above because it only fires a hook but has no state+ # change.)if isinstance(envelope,(HeartbeatEnvelope, ConfigEnvelope, AckEnvelope),diff --git a/OS-Level/src/overlay/fullscreen_detect.py b/OS-Level/src/overlay/fullscreen_detect.pyindex 0ef5302331..939902edcf 100644--- a/OS-Level/src/overlay/fullscreen_detect.py+++ b/OS-Level/src/overlay/fullscreen_detect.py@@ -1,13 +1,13 @@"""SHQueryUserNotificationState polling. Plan §12.6 + §20.2.-Pollt alle 2 Sekunden auf einem Daemon-Thread mit-``THREAD_PRIORITY_LOWEST`` (best effort). Wenn der State zu einem-"hide-worthy" Code wechselt (D3D-Fullscreen, Presentation-Mode oder-optional Busy), feuert eine Callback. Klassischer Pull-Polling--Ansatz weil Windows kein Push-Event fuer diesen Status hat.--Keine PySide6-Dependency damit der Polling-Thread auch in Test--Setups ohne QApplication laufen kann.+Polls every 2 seconds on a daemon thread with+``THREAD_PRIORITY_LOWEST`` (best effort). When the state changes to a+"hide-worthy" code (D3D fullscreen, presentation mode, or optionally+busy), it fires a callback. A classic pull-polling approach because+Windows has no push event for this status.++No PySide6 dependency, so the polling thread can also run in test+setups without a QApplication."""from __future__ import annotations@@ -33,7 +33,7 @@ class UserNotificationState(IntEnum):APP = 7 # QUNS_APP-# Plan §12.6: Default-Hide-Codes (BUSY ist optional via ignore_busy_state).+# Plan §12.6: default hide codes (BUSY is optional via ignore_busy_state)._HARD_HIDE_STATES: frozenset[UserNotificationState] = frozenset({UserNotificationState.RUNNING_D3D_FULL_SCREEN, UserNotificationState.PRESENTATION_MODE})@@ -44,20 +44,20 @@ _SOFT_HIDE_STATES: frozenset[UserNotificationState] = frozenset(@dataclass(frozen=True)class FullscreenStatus:- """Schnappschuss vom letzten Polling-Tick."""+ """Snapshot of the last polling tick."""state: UserNotificationStateshould_hide: bool-# Callback-Signatur: (FullscreenStatus) -> None.+# Callback signature: (FullscreenStatus) -> None.StatusCallback = Callable[[FullscreenStatus], None]def query_state() -> Optional[UserNotificationState]:"""Plan §12.6 — SHQueryUserNotificationState via ctypes.- Returnt None wenn nicht-Windows oder API nicht verfuegbar.+ Returns None on non-Windows or when the API isn't available."""if sys.platform != "win32":return None@@ -84,9 +84,9 @@ def query_state() -> Optional[UserNotificationState]:def should_hide_for_state(state: UserNotificationState, *, ignore_busy_state: bool) -> bool:- """Mapping State -> hide. Plan §12.6:- - immer hide bei RUNNING_D3D_FULL_SCREEN, PRESENTATION_MODE- - hide bei BUSY nur wenn ignore_busy_state == False (Default)+ """Mapping state -> hide. Plan §12.6:+ - always hide on RUNNING_D3D_FULL_SCREEN, PRESENTATION_MODE+ - hide on BUSY only when ignore_busy_state == False (default)"""if state in _HARD_HIDE_STATES:return True@@ -96,9 +96,9 @@ def should_hide_for_state(class FullscreenDetector:- """Polling-Thread um SHQueryUserNotificationState.+ """Polling thread around SHQueryUserNotificationState.- Plan §12.6: Low-Prio Daemon-Thread, 2 s Intervall, sauberer Exit.+ Plan §12.6: low-prio daemon thread, 2 s interval, clean exit.Lifecycle::@@ -133,15 +133,15 @@ class FullscreenDetector:return self._thread is not None and self._thread.is_alive()def set_ignore_busy_state(self, ignore: bool) -> None:- """Runtime-Toggle (z.B. wenn Config-Reload kommt)."""+ """Runtime toggle (e.g. when a config reload happens)."""self._ignore_busy_state = ignoredef set_callback(self, callback: Optional[StatusCallback]) -> None:self._callback = callbackdef poll_once(self) -> Optional[FullscreenStatus]:- """Synchroner Poll-Cycle. Returnt FullscreenStatus oder None- (Nicht-Windows / API-Fehler)."""+ """Synchronous poll cycle. Returns FullscreenStatus or None+ (non-Windows / API error)."""state = self._query_fn()if state is None:return None@@ -177,7 +177,7 @@ class FullscreenDetector:self._thread.join(timeout=2.0)def _run(self) -> None:- # Best-effort: Thread-Priority absenken auf Windows.+ # Best effort: lower the thread priority on Windows.if sys.platform == "win32":try:import ctypesdiff --git a/OS-Level/src/overlay/ipc_pipe.py b/OS-Level/src/overlay/ipc_pipe.pyindex 835f47349e..1495bc93d6 100644--- a/OS-Level/src/overlay/ipc_pipe.py+++ b/OS-Level/src/overlay/ipc_pipe.py@@ -1,11 +1,11 @@-"""Named-Pipe-Fallback. Plan §5 AD-5 + §10.+"""Named-pipe fallback. Plan §5 AD-5 + §10.-Skeleton: Connect-Helper + send/recv-Roundtrip. Vollstaendige Auto--Failover-Logik (WS down + Pipe up) ist Phase 9.7-Thema. Hier nur die-Bausteine, damit die Tests den Pipe-Pfad simulieren koennen.+Skeleton: connect helper + send/recv roundtrip. The full auto-failover+logic (WS down + pipe up) is a Phase 9.7 topic. This only has the+building blocks, so tests can simulate the pipe path.-Fuer Non-Windows-Umgebungen: ``CAPABLE`` ist ``False``, ``connect`` und-``send_recv`` raisen ``RuntimeError``. Tests skippen entsprechend.+For non-Windows environments: ``CAPABLE`` is ``False``, ``connect``+and ``send_recv`` raise ``RuntimeError``. Tests skip accordingly."""from __future__ import annotations@@ -19,7 +19,7 @@ logger = logging.getLogger(__name__)DEFAULT_PIPE_NAME = r"\\.\pipe\jarvis-overlay"-# Pipe-Buffer-Defaults — unkritisch, beide Richtungen je 64 KiB.+# Pipe buffer defaults — uncritical, 64 KiB each direction._BUF = 64 * 1024@@ -28,15 +28,15 @@ def _is_windows() -> bool:def _import_win32() -> tuple[Any, Any]:- """Lazy-Import. Gibt (win32file, win32pipe) zurueck."""+ """Lazy import. Returns (win32file, win32pipe)."""if not _is_windows():- raise RuntimeError("Named-Pipe ist Windows-only")+ raise RuntimeError("Named pipes are Windows-only")try:import win32file # type: ignore[import-not-found]import win32pipe # type: ignore[import-not-found]except ImportError as exc:raise RuntimeError(- "pywin32 nicht installiert — `pip install pywin32`"+ "pywin32 not installed — `pip install pywin32`") from excreturn win32file, win32pipe@@ -46,20 +46,20 @@ CAPABLE: bool = _is_windows()@contextmanagerdef open_client(pipe_name: str = DEFAULT_PIPE_NAME, *, timeout_ms: int = 5000) -> Iterator[Any]:- """Verbindet als Client zur existierenden Pipe.+ """Connects as a client to the existing pipe.- Yieldet das ``HANDLE``. Schliesst es sauber im Exit-Branch. Raised- ``RuntimeError`` falls die Pipe nicht existiert oder wir auf Non-- Windows laufen.+ Yields the ``HANDLE``. Closes it cleanly in the exit branch. Raises+ ``RuntimeError`` if the pipe doesn't exist or we're running on+ non-Windows."""win32file, win32pipe = _import_win32()import pywintypes # type: ignore[import-not-found]import time as _time- # ``WaitNamedPipe`` ist auf Win11 unreliable (returnt False obwohl der- # Server in ``ConnectNamedPipe`` blockiert). Robusterer Pfad: direkt- # ``CreateFile`` aufrufen und bei ``ERROR_PIPE_BUSY``/``FILE_NOT_FOUND``- # in kurzen Abstaenden retry-en.+ # ``WaitNamedPipe`` is unreliable on Win11 (returns False even+ # though the server is blocked in ``ConnectNamedPipe``). A more+ # robust path: call ``CreateFile`` directly and retry at short+ # intervals on ``ERROR_PIPE_BUSY``/``FILE_NOT_FOUND``.deadline = _time.monotonic() + (timeout_ms / 1000.0)last_err: Exception | None = Nonehandle = None@@ -79,14 +79,14 @@ def open_client(pipe_name: str = DEFAULT_PIPE_NAME, *, timeout_ms: int = 5000) -last_err = excif _time.monotonic() >= deadline:raise RuntimeError(- f"Named-Pipe Connect-Fehler: {pipe_name} ({exc})"+ f"Named-pipe connect error: {pipe_name} ({exc})") from exc_time.sleep(0.025)assert handle is not None, "unreachable: handle must be set after loop"del last_err # unused outside looptry:- # PIPE_READMODE_MESSAGE: jede WriteFile entspricht einer ReadFile.+ # PIPE_READMODE_MESSAGE: every WriteFile corresponds to one ReadFile.win32pipe.SetNamedPipeHandleState(handle, win32pipe.PIPE_READMODE_MESSAGE, None, None)@@ -99,11 +99,11 @@ def open_client(pipe_name: str = DEFAULT_PIPE_NAME, *, timeout_ms: int = 5000) -def create_server_pipe(pipe_name: str = DEFAULT_PIPE_NAME) -> Any:- """Reine ``CreateNamedPipe``. Returnt das Handle ohne zu blockieren.+ """Pure ``CreateNamedPipe``. Returns the handle without blocking.- ``accept_server_connection(handle)`` blockiert dann separat bis ein- Client verbindet. Splittet das Lifecycle damit Tests den Race vor- ``WaitNamedPipe`` nicht durch Sleep loesen muessen.+ ``accept_server_connection(handle)`` then blocks separately until a+ client connects. Splits the lifecycle so tests don't have to+ resolve the race before ``WaitNamedPipe`` via sleep."""win32file, win32pipe = _import_win32()return win32pipe.CreateNamedPipe(@@ -121,13 +121,13 @@ def create_server_pipe(pipe_name: str = DEFAULT_PIPE_NAME) -> Any:def accept_server_connection(handle: Any) -> None:- """Blockiert auf ``ConnectNamedPipe(handle)``."""+ """Blocks on ``ConnectNamedPipe(handle)``."""_, win32pipe = _import_win32()win32pipe.ConnectNamedPipe(handle, None)def close_server_pipe(handle: Any) -> None:- """Disconnect + Close-Handle. Idempotent."""+ """Disconnect + close handle. Idempotent."""win32file, win32pipe = _import_win32()try:win32pipe.DisconnectNamedPipe(handle)@@ -141,11 +141,11 @@ def close_server_pipe(handle: Any) -> None:@contextmanagerdef open_server(pipe_name: str = DEFAULT_PIPE_NAME) -> Iterator[Any]:- """Server-seitige Pipe. Erzeugt sie und blockiert auf ``ConnectNamedPipe``.+ """Server-side pipe. Creates it and blocks on ``ConnectNamedPipe``.- Wird in Phase 9.7 durch eine Multi-Connection-Variante ersetzt; hier- nur das Single-Connection-Skelett, damit Tests den Roundtrip pruefen- koennen. Fuer feinere Test-Kontrolle siehe ``create_server_pipe`` ++ Gets replaced by a multi-connection variant in Phase 9.7; this is+ only the single-connection skeleton, so tests can verify the+ roundtrip. For finer test control see ``create_server_pipe`` +``accept_server_connection``."""handle = create_server_pipe(pipe_name)@@ -157,7 +157,7 @@ def open_server(pipe_name: str = DEFAULT_PIPE_NAME) -> Iterator[Any]:def send(handle: Any, payload: bytes) -> int:- """Schreibt eine Message. Returnt geschriebene Bytes."""+ """Writes a message. Returns the number of bytes written."""win32file, _ = _import_win32()err, written = win32file.WriteFile(handle, payload)if err != 0:@@ -166,7 +166,7 @@ def send(handle: Any, payload: bytes) -> int:def recv(handle: Any, max_bytes: int = _BUF) -> bytes:- """Liest eine Message. Returnt rohe Bytes (UTF-8 JSON erwartet)."""+ """Reads a message. Returns the raw bytes (UTF-8 JSON expected)."""win32file, _ = _import_win32()err, data = win32file.ReadFile(handle, max_bytes)if err != 0:diff --git a/OS-Level/src/overlay/ipc_ws.py b/OS-Level/src/overlay/ipc_ws.pyindex bfffac194a..f6eae9fba1 100644--- a/OS-Level/src/overlay/ipc_ws.py+++ b/OS-Level/src/overlay/ipc_ws.py@@ -1,12 +1,12 @@-"""WS-Client. Verbindet zum Hauptjarvis-WS-Server.--Plan §10.5 — Lifecycle:-- Initial-Connect: probiert Ports ``[ws_port..ws_port_range_max]`` durch.-- Heartbeat: client sendet alle 1s, erwartet ebenfalls 1s-Frequenz vom- Server. Wenn 3s lang KEIN Frame ankommt -> Connection als broken markieren.-- Reconnect-Backoff: 0.5, 1, 2, 4, 8, 30 Sekunden mit +/- 20% Jitter.-- State-Resync: erstes Frame vom Server nach Connect ist der aktuelle- State; wir reichen ihn unaendert an ``on_message`` durch.+"""WS client. Connects to the Hauptjarvis WS server.++Plan §10.5 — lifecycle:+- Initial connect: tries ports ``[ws_port..ws_port_range_max]`` in order.+- Heartbeat: the client sends every 1s, and also expects a 1s cadence+ from the server. If NO frame arrives for 3s -> mark the connection broken.+- Reconnect backoff: 0.5, 1, 2, 4, 8, 30 seconds with +/- 20% jitter.+- State resync: the first frame from the server after connect is the+ current state; we pass it through unchanged to ``on_message``."""from __future__ import annotations@@ -28,7 +28,7 @@ from .schema import (logger = logging.getLogger(__name__)-# Plan §10.5 — fixed backoff slots in Sekunden.+# Plan §10.5 — fixed backoff slots in seconds.BACKOFF_SCHEDULE: tuple[float, ...] = (0.5, 1.0, 2.0, 4.0, 8.0, 30.0)JITTER_FRACTION = 0.2@@ -43,7 +43,7 @@ def _backoff_with_jitter(slot: int, *, rng: random.Random | None = None) -> floaclass WSClient:- """Self-restarting WS-Client.+ """Self-restarting WS client.Usage::@@ -124,16 +124,16 @@ class WSClient:logger.warning("WSClient outbox still full after evict — drop new")async def run(self) -> None:- """Hauptloop. Returnt nach ``aclose()``."""+ """Main loop. Returns after ``aclose()``."""slot = 0while not self._stop.is_set():ws = await self._try_connect_any()if ws is None:- # Kein Port im Range erreichbar -> Backoff und retry.+ # No port in range reachable -> backoff and retry.await self._sleep_backoff(slot)slot = min(slot + 1, len(BACKOFF_SCHEDULE) - 1)continue- slot = 0 # Reset bei erfolgreicher Connection.+ slot = 0 # Reset on a successful connection.self._connection_count += 1self._connected_evt.set()try:@@ -169,11 +169,11 @@ class WSClient:try:await asyncio.wait_for(self._stop.wait(), timeout=delay)except asyncio.TimeoutError:- return # Backoff abgelaufen, weiter.+ return # Backoff expired, continue.async def _serve_connection(self, ws) -> None:loop = asyncio.get_running_loop()- self._last_recv_ns = loop.time() * 1e9 # nutzt monotonic clock fuers Timeout+ self._last_recv_ns = loop.time() * 1e9 # uses the monotonic clock for the timeoutself._active_ws = wshb_task = asyncio.create_task(self._heartbeat_loop(ws), name="ipcws-hb")watchdog = asyncio.create_task(self._watchdog_loop(ws), name="ipcws-watchdog")@@ -236,11 +236,11 @@ class WSClient:continueasync def _watchdog_loop(self, ws) -> None:- """Schliesst ``ws`` wenn ``heartbeat_timeout_s`` lang nichts kommt.+ """Closes ``ws`` when nothing arrives for ``heartbeat_timeout_s``.- Plan §10.5: Das forciert die ``async for`` Schleife im- ``_serve_connection`` zu beenden, ``run()`` triggert dann den- Reconnect-Pfad mit Backoff.+ Plan §10.5: this forces the ``async for`` loop in+ ``_serve_connection`` to end, then ``run()`` triggers the+ reconnect path with backoff."""loop = asyncio.get_running_loop()check_interval = max(0.05, self._heartbeat_timeout / 3)diff --git a/OS-Level/src/overlay/main.py b/OS-Level/src/overlay/main.pyindex 4529c6946b..1ff7ba3f6d 100644--- a/OS-Level/src/overlay/main.py+++ b/OS-Level/src/overlay/main.py@@ -1,4 +1,4 @@-"""Overlay Entry-Point. Spaetere Phasen fuellen ``setup_*()`` Bodies."""+"""Overlay entry point. Later phases fill in the ``setup_*()`` bodies."""from __future__ import annotations@@ -14,7 +14,7 @@ logger = logging.getLogger(__name__)def setup_dpi_awareness() -> None:- """Per-Monitor DPI. MUSS vor QApplication laufen — Plan §12.3."""+ """Per-monitor DPI. MUST run before QApplication — Plan §12.3."""set_per_monitor_dpi_awareness()@@ -45,20 +45,20 @@ def _setup_app_identity_and_icon() -> Optional["object"]:def setup_windows(app, config, state_machine=None, effects_bridge=None) -> list:- """Edge-Glow Windows pro Screen.+ """Edge-Glow windows, one per screen.- Plan §12.1 + §12.5: ein Window pro Screen wenn ``all_monitors=True``,- sonst nur Primary. Hotplug haengen wir an den ``MonitorManager``.+ Plan §12.1 + §12.5: one window per screen when ``all_monitors=True``,+ otherwise only primary. We hook hotplug into the ``MonitorManager``.- ``state_machine`` (optional, neu in 9.3): Wird durchgereicht an- ``EdgeGlowWindow``, das eine ``StateBridge`` ueber QWebChannel- exposed. Ein Window pro Screen subscribed unabhaengig — Subscriber-- Liste der StateMachine ist threadsafe.+ ``state_machine`` (optional, new in 9.3): passed through to+ ``EdgeGlowWindow``, which exposes a ``StateBridge`` over QWebChannel.+ Each window subscribes independently — the StateMachine's subscriber+ list is thread-safe.- ``effects_bridge`` (optional, neu in 9.5): wird gleichzeitig als- ``effectsBridge`` am QWebChannel registriert. Selbe Instanz pro- Window — alle Windows feuern gegen dieselbe Bridge, der Renderer- pro Window subscribed unabhaengig.+ ``effects_bridge`` (optional, new in 9.5): simultaneously registered+ as ``effectsBridge`` on the QWebChannel. Same instance per window —+ all windows fire against the same bridge, and the renderer per+ window subscribes independently."""from PySide6.QtGui import QGuiApplication@@ -99,40 +99,38 @@ def setup_windows(app, config, state_machine=None, effects_bridge=None) -> list:def _on_screen_removed(screen) -> None:for w in list(windows):- # ``w.screen()`` kann nach Remove None liefern — defensiv vergleichen.+ # ``w.screen()`` can return None after removal — compare defensively.try:if w.screen() is screen:w.close()windows.remove(w)- except RuntimeError: # pragma: no cover — Window bereits weg+ except RuntimeError: # pragma: no cover — window already goneif w in windows:windows.remove(w)manager = MonitorManager(_on_screen_added, _on_screen_removed)manager.attach()- # Manager am App-Object parken, damit er nicht GC'd wird.+ # Park the manager on the app object so it doesn't get GC'd.app._overlay_monitor_manager = manager # type: ignore[attr-defined]return windowsdef setup_ipc(app, config, on_message=None) -> Any:- """WS-Client in dediziertem asyncio-Thread.-- Qt-Event-Loop und asyncio koexistieren hier ueber einen Worker-Thread- statt qasync — das vermeidet eine zusaetzliche Dependency und macht- den Pfad besser testbar (asyncio kann unabhaengig vom Qt-Loop- gestartet/gestoppt werden).-- Plan §10.5: Reconnect-Logic + Heartbeat sind komplett im- ``WSClient.run()`` gekapselt. Wir parken den Thread + Loop am- ``app``-Objekt damit nichts GC'd wird und der Shutdown-Hook das- Stop-Event setzen kann.-- ``on_message`` (optional, neu in 9.3): Async-Callback der jedes- validierte IPC-Envelope bekommt. setup_state_machine() laesst hier- den ``EventRouter.handle`` durch — er ist sync, wir wrappen ihn- dort.+ """WS client on a dedicated asyncio thread.++ The Qt event loop and asyncio coexist here via a worker thread+ instead of qasync — that avoids an extra dependency and makes the+ path easier to test (asyncio can be started/stopped independently+ of the Qt loop).++ Plan §10.5: reconnect logic + heartbeat are fully encapsulated in+ ``WSClient.run()``. We park the thread + loop on the ``app`` object+ so nothing gets GC'd and the shutdown hook can set the stop event.++ ``on_message`` (optional, new in 9.3): async callback that receives+ every validated IPC envelope. setup_state_machine() passes+ ``EventRouter.handle`` through here — it's sync, we wrap it there."""import threading@@ -186,17 +184,16 @@ def setup_ipc(app, config, on_message=None) -> Any:def setup_state_machine(app, config) -> Any:- """State Machine + EventRouter. Phase 9.3.+ """State machine + EventRouter. Phase 9.3.- Returnt ``{"machine": StateMachine, "router": EventRouter,- "on_message": Callable}``. Die ``on_message``-Coroutine wird an- ``setup_ipc`` durchgereicht; die ``machine`` an ``setup_windows``,- damit jedes ``EdgeGlowWindow`` eine eigene QWebChannel-Bridge- aufbauen kann.+ Returns ``{"machine": StateMachine, "router": EventRouter,+ "on_message": Callable}``. The ``on_message`` coroutine is passed+ through to ``setup_ipc``; the ``machine`` goes to ``setup_windows``,+ so each ``EdgeGlowWindow`` can build its own QWebChannel bridge.- Plan AD-8: State-Logic lebt im Overlay-Prozess. Der Router ist die- einzige Komponente die Wire-Format kennt — die StateMachine bleibt- IPC-unwissend.+ Plan AD-8: state logic lives in the overlay process. The router is+ the only component that knows the wire format — the StateMachine+ stays IPC-agnostic."""from .event_router import EventRouterfrom .state import StateMachine@@ -205,8 +202,8 @@ def setup_state_machine(app, config) -> Any:router = EventRouter(machine)async def on_message(envelope: Any) -> None:- # Router.handle ist sync und schnell (dict-Lookup +- # Locks). Wir rufen es direkt — kein await noetig.+ # Router.handle is sync and fast (dict lookup + locks). We call+ # it directly — no await needed.try:router.handle(envelope)except Exception: # noqa: BLE001@@ -222,22 +219,22 @@ def setup_state_machine(app, config) -> Any:def setup_effects(app, config, router=None) -> Any:- """Action-Effects: Cursor-SHM-Reader + Ripple/Action-Bridge. Phase 9.5.+ """Action effects: cursor SHM reader + ripple/action bridge. Phase 9.5.- Returnt ``{"bridge": EffectsBridge, "shm_thread": Optional[Thread],+ Returns ``{"bridge": EffectsBridge, "shm_thread": Optional[Thread],"shm_reader": Optional[CursorShmReader], "shm_stop": Event}``.Lifecycle:- - ``EffectsBridge`` wird sofort instantiiert, an ``app`` geparkt- und vom Caller via ``setup_windows(effects_bridge=...)`` an alle- Windows gehaengt.- - ``router.add_click_hook/add_action_started_hook/...`` werden- gehookt sodass IPC-Events durch die Bridge ans JS gehen.- - Wenn ``config.cursor_trail_enabled`` und ein- ``shm_cursor_name``-String per Config-IPC bekannt wird (vom- Hauptjarvis), startet ein 60-Hz-Reader-Thread und emittiert- ``cursorMoved``-Signals. Phase 9.5 polled den Config-Block- beim Start einmalig — dynamische Reconfig kommt mit 9.7+.+ - ``EffectsBridge`` is instantiated immediately, parked on ``app``,+ and attached to all windows by the caller via+ ``setup_windows(effects_bridge=...)``.+ - ``router.add_click_hook/add_action_started_hook/...`` are hooked+ so IPC events flow through the bridge to the JS side.+ - When ``config.cursor_trail_enabled`` and a ``shm_cursor_name``+ string becomes known via config IPC (from Hauptjarvis), a 60-Hz+ reader thread starts and emits ``cursorMoved`` signals. Phase+ 9.5 polls the config block once at startup — dynamic reconfig+ arrives with 9.7+."""import threading@@ -245,7 +242,7 @@ def setup_effects(app, config, router=None) -> Any:bridge = EffectsBridge()- # Hook-Wiring an EventRouter: jedes IPC-Event durchreichen.+ # Hook wiring to EventRouter: pass every IPC event through.if router is not None:router.add_click_hook(lambda env: bridge.emit_click(@@ -261,15 +258,15 @@ def setup_effects(app, config, router=None) -> Any:))router.add_action_ended_hook(lambda env: bridge.emit_action_ended())- # Cursor via WS-Fallback (Plan §11.5) — wenn SHM aus, kommen- # CursorEnvelope durch und wir leiten weiter.+ # Cursor via WS fallback (Plan §11.5) — when SHM is off,+ # CursorEnvelope comes through and we forward it.router.add_cursor_hook(lambda env: bridge.emit_cursor(env.payload.x, env.payload.y))- # SHM-Reader-Thread — nur wenn Trail enabled UND ein Name verfuegbar.- # Der Name kommt typischerweise per Config-IPC vom Hauptjarvis.- # Phase 9.5 startet den Thread DEFERRED via shm_attach()-Helper unten.+ # SHM reader thread — only when the trail is enabled AND a name is+ # available. The name typically comes via config IPC from Hauptjarvis.+ # Phase 9.5 starts the thread DEFERRED via the shm_attach() helper below.handle = {"bridge": bridge,"shm_thread": None,@@ -279,8 +276,8 @@ def setup_effects(app, config, router=None) -> Any:}def shm_attach(name: str, hz: int = 60) -> bool:- """Attached an einen existierenden SHM-Block und startet den- 60-Hz-Reader-Thread. Returnt False wenn block fehlt."""+ """Attaches to an existing SHM block and starts the 60-Hz+ reader thread. Returns False if the block is missing."""from .cursor_shm import CursorShmReadertry:@@ -328,9 +325,9 @@ def setup_effects(app, config, router=None) -> Any:def _monitor_str_to_idx(monitor: str) -> int:- """ClickPayload.monitor ist String (frei-form). Wenn parse-bar als- int -> direkt; sonst 0 als Default. Phase-9.7-Mascot-Wiring kann- das verfeinern wenn echte Monitor-IDs reinkommen."""+ """ClickPayload.monitor is a string (free-form). If parseable as+ int -> use directly; otherwise default to 0. Phase-9.7 mascot+ wiring can refine this once real monitor IDs come in."""if not monitor:return 0try:@@ -340,20 +337,19 @@ def _monitor_str_to_idx(monitor: str) -> int:def setup_mascot(app, config, state_machine=None, toml_path=None, ipc=None) -> Any:- """Mascot-Window. Phase 9.6.+ """Mascot window. Phase 9.6.- Returnt ``{"window": MascotWindow | None, "position": ResolvedPlacement | None}``.+ Returns ``{"window": MascotWindow | None, "position": ResolvedPlacement | None}``.- Wenn ``config.mascot_enabled`` False ist, wird kein Window erzeugt- (Plan §13.5 — TOML-Toggle disabled mascot komplett).+ If ``config.mascot_enabled`` is False, no window is created+ (Plan §13.5 — the TOML toggle disables the mascot entirely).- Position wird per ``mascot_position.resolve_placement`` aus dem- persistierten ``[overlay.mascot]`` ermittelt; Recovery wenn der- Monitor weg ist landet auf primary (Plan §13.4 step 3).+ Position is determined via ``mascot_position.resolve_placement``+ from the persisted ``[overlay.mascot]``; recovery when the monitor+ is gone falls back to primary (Plan §13.4 step 3).- Plus: ``hideRequested`` / ``resetRequested`` Signals werden auf- sinnvolle Defaults verkabelt (hide -> close, reset -> primary- default position).+ Plus: ``hideRequested`` / ``resetRequested`` signals are wired to+ sensible defaults (hide -> close, reset -> primary default position)."""if not getattr(config, "mascot_enabled", True):logger.info("Mascot disabled via config.mascot_enabled=false")@@ -378,13 +374,13 @@ def setup_mascot(app, config, state_machine=None, toml_path=None, ipc=None) -> Asize_px = getattr(mascot_section, "size_px", 160) if mascot_section else 160snap_px = getattr(mascot_section, "snap_to_edges_px", 16) if mascot_section else 16- # Position laden — Default ist jarvis.toml im Working-Dir. Tests- # und Hauptjarvis-Bootstrap koennen toml_path explizit uebergeben.+ # Load position — default is jarvis.toml in the working dir. Tests+ # and the Hauptjarvis bootstrap can pass toml_path explicitly.config_path = Path(toml_path) if toml_path is not None else Path("jarvis.toml")persisted = load_position_from_toml(config_path)if persisted is None and mascot_section is not None:- # Fallback: Werte aus dem in-memory config (z.B. erster Start- # ohne TOML-Edit).+ # Fallback: values from the in-memory config (e.g. first start+ # without a TOML edit).persisted = MascotPosition(monitor=getattr(mascot_section, "position_monitor", "") or "",x_relative=getattr(mascot_section, "position_x_relative", DEFAULT_X_RELATIVE),@@ -467,16 +463,16 @@ def setup_mascot(app, config, state_machine=None, toml_path=None, ipc=None) -> Adef setup_throttling(app, config, state_machine=None, windows=None) -> Any:- """Fullscreen-Detection + Power-Monitor + Throttler-Wiring. Phase 9.7.+ """Fullscreen detection + power monitor + throttler wiring. Phase 9.7.Inputs:- - ``state_machine`` (Pflicht fuer den Throttler — er subscribed- State-Changes fuer Idle-Reset).- - ``windows`` (optional, Liste der EdgeGlowWindow-Instanzen).- Throttler-Subscriber toggled auf jedem Window die- ``set_view_visible``-Methode bei Hide-Timeout.+ - ``state_machine`` (required for the throttler — it subscribes+ to state changes for idle reset).+ - ``windows`` (optional, list of EdgeGlowWindow instances).+ The throttler subscriber calls each window's+ ``set_view_visible`` method on a hide timeout.- Returnt::+ Returns::{"throttler": Throttler,@@ -485,8 +481,8 @@ def setup_throttling(app, config, state_machine=None, windows=None) -> Any:"shutdown": Callable[[], None],}- Wenn keine StateMachine geliefert: nur fullscreen+power, kein- Throttler. (z.B. Headless-Tests.)+ If no StateMachine is supplied: only fullscreen+power, no+ throttler. (e.g. headless tests.)"""from PySide6.QtCore import QTimer@@ -501,12 +497,12 @@ def setup_throttling(app, config, state_machine=None, windows=None) -> Any:Throttler,)- # Qt-Cross-Thread-Marshall: FullscreenDetector und PowerMonitor laufen- # in eigenen Daemon-Threads. Ihre Callbacks duerfen NICHT direkt auf- # Qt-Widgets (setVisible, transition_to_*) zugreifen — Qt asserted hart- # mit STATUS_BREAKPOINT 0x80000003 und der Subprocess crasht. Wir routen- # alle Worker-Callbacks via QTimer.singleShot(0, ...) auf den Qt-Main-- # Thread, der QApplication.exec() haelt.+ # Qt cross-thread marshalling: FullscreenDetector and PowerMonitor run+ # on their own daemon threads. Their callbacks must NOT touch Qt+ # widgets directly (setVisible, transition_to_*) — Qt hard-asserts+ # with STATUS_BREAKPOINT 0x80000003 and the subprocess crashes. We+ # route all worker callbacks via QTimer.singleShot(0, ...) onto the+ # Qt main thread that holds QApplication.exec().def _post_to_main(fn) -> None:QTimer.singleShot(0, fn)@@ -533,11 +529,12 @@ def setup_throttling(app, config, state_machine=None, windows=None) -> Any:)handle["throttler"] = throttler- # Window-Visibility-Toggling: throttler-snapshot.should_hide_view- # spiegelt sich auf jeden Edge-Glow-View (WebView setVisible).- # MUSS auf Qt-Main-Thread marshallen — Throttler kann den Subscriber- # synchron aus einem Worker-Thread aufrufen (Crash-Stack zeigt- # Detector → state_machine → throttler.recompute → _on_throttle).+ # Window visibility toggling: throttler-snapshot.should_hide_view+ # is mirrored onto each Edge-Glow view (WebView setVisible).+ # MUST be marshalled onto the Qt main thread — the throttler can+ # call the subscriber synchronously from a worker thread (the+ # crash stack shows Detector → state_machine → throttler.recompute+ # → _on_throttle).if windows is not None:def _on_throttle(snapshot) -> None:visible = not snapshot.should_hide_view@@ -556,11 +553,11 @@ def setup_throttling(app, config, state_machine=None, windows=None) -> Any:throttler.subscribe(_on_throttle)- # Fullscreen-Detection. Toggled HIDDEN-State.- # FullscreenDetector callback laeuft in seinem eigenen Daemon-Thread —- # state_machine.transition_* publiziert synchron an Subscriber, die- # ihrerseits Qt-Widgets anfassen. Komplette Logik via _post_to_main- # auf Qt-Main-Thread schicken.+ # Fullscreen detection. Toggles the HIDDEN state.+ # The FullscreenDetector callback runs on its own daemon thread —+ # state_machine.transition_* publishes synchronously to subscribers,+ # which in turn touch Qt widgets. Route the entire logic through+ # _post_to_main onto the Qt main thread.def _on_fullscreen(status) -> None:if state_machine is None:return@@ -569,11 +566,11 @@ def setup_throttling(app, config, state_machine=None, windows=None) -> Any:if status.should_hide:state_machine.transition_to_hidden(reason="timeout")else:- # Recovery: zurueck nach IDLE wenn vorher HIDDEN durch- # Fullscreen war. Wenn manueller HIDDEN gesetzt wurde, nicht- # ueberschreiben — wir koennen das aktuell nicht- # unterscheiden, also bleibt der konservative Pfad: nur in- # IDLE wechseln wenn aktuell HIDDEN.+ # Recovery: back to IDLE if HIDDEN was previously caused+ # by fullscreen. If HIDDEN was set manually, don't+ # override it — we currently can't distinguish the two,+ # so we keep the conservative path: only switch to IDLE+ # if currently HIDDEN.if state_machine.state.value == "hidden":from .state import OverlayState@@ -592,10 +589,11 @@ def setup_throttling(app, config, state_machine=None, windows=None) -> Any:fullscreen.start()handle["fullscreen"] = fullscreen- # Power-Monitor. Halbiert FPS auf Battery.- # PowerMonitor.callback laeuft in eigenem Worker-Thread; throttler.set_on_battery- # publiziert synchron an _on_throttle-Subscriber (siehe oben). Auch hier auf- # Qt-Main-Thread marshallen, sonst gleiches Crash-Risiko bei AC/DC-Wechsel.+ # Power monitor. Halves FPS on battery.+ # PowerMonitor.callback runs on its own worker thread; throttler.set_on_battery+ # publishes synchronously to the _on_throttle subscriber (see above). Also+ # marshalled onto the Qt main thread here, otherwise the same crash risk+ # applies on an AC/DC switch.def _on_power(status) -> None:if throttler is None:return@@ -639,7 +637,7 @@ def main() -> int:return run_self_test()- setup_dpi_awareness() # vor QApplication+ setup_dpi_awareness() # before QApplication# AUMID before QApplication so the taskbar group is fixed from the first# window registration (otherwise Qt's class inherits the python.exe icon).@@ -660,11 +658,11 @@ def main() -> int:# Cosmetic only; never block the overlay on icon issues.pass- # Wire-Reihenfolge: state-machine zuerst (kein Side-effect ausser- # Object-Konstruktion), dann effects (haengen Hooks an router), dann- # windows mit machine + bridge, dann IPC mit on_message Callback.- # So gibt es keine Phase wo IPC schon Events liefert aber kein- # Subscriber dranhaengt.+ # Wiring order: state machine first (no side effect besides object+ # construction), then effects (attaches hooks to the router), then+ # windows with machine + bridge, then IPC with the on_message+ # callback. This way there's no phase where IPC is already delivering+ # events but no subscriber is attached yet._state = setup_state_machine(app, config)_effects = setup_effects(app, config, router=_state["router"])_windows = setup_windows(diff --git a/OS-Level/src/overlay/mascot_position.py b/OS-Level/src/overlay/mascot_position.pyindex 9e972afa92..c92ec4ed54 100644--- a/OS-Level/src/overlay/mascot_position.py+++ b/OS-Level/src/overlay/mascot_position.py@@ -1,19 +1,19 @@-"""Mascot Position-Persistence + Monitor-Recovery. Plan §13.4 + §20.4.--Persistiert ``[overlay.mascot] position_monitor / x_relative / y_relative``-nach ``jarvis.toml`` via Atomic-Write (AD-11). Beim Boot:- - Wenn ``position_monitor`` in EnumDisplayMonitors gefunden:- Mascot dort an (rcWork.left + x_rel, rcWork.top + y_rel).- - Wenn nicht (Laptop undocked, port-swap, monitor unplugged):- deterministischer Fallback auf primary monitor + default (200, 80).--Wir umgehen ctypes hier — Qt's QGuiApplication.screens() liefert-``screen.name()`` was unter Win32 dem Device-Name (``\\.\DISPLAY1``)-entspricht. Das hat den Vorteil dass Tests headless laufen koennen-ohne Win32-Mock.--Atomic-Write nutzt tomllib + manuelles Schreiben (kein tomli_w noetig-weil wir nur eine bekannte Section editieren).+"""Mascot position persistence + monitor recovery. Plan §13.4 + §20.4.++Persists ``[overlay.mascot] position_monitor / x_relative / y_relative``+to ``jarvis.toml`` via atomic write (AD-11). On boot:+ - If ``position_monitor`` is found in EnumDisplayMonitors:+ place the mascot there at (rcWork.left + x_rel, rcWork.top + y_rel).+ - If not (laptop undocked, port swap, monitor unplugged):+ deterministic fallback to the primary monitor + default (200, 80).++We avoid ctypes here — Qt's QGuiApplication.screens() returns+``screen.name()``, which matches the device name (``\\.\DISPLAY1``)+under Win32. This has the advantage that tests can run headless+without a Win32 mock.++Atomic write uses tomllib + manual writing (no tomli_w needed+since we only edit one known section)."""from __future__ import annotations@@ -31,7 +31,7 @@ logger = logging.getLogger(__name__)@dataclass(frozen=True)class MascotPosition:- """Persistierte Position. ``monitor`` = Win32 device name (``\\\\.\\DISPLAY1``)."""+ """Persisted position. ``monitor`` = Win32 device name (``\\\\.\\DISPLAY1``)."""monitor: strx_relative: int@@ -40,32 +40,32 @@ class MascotPosition:@dataclass(frozen=True)class ResolvedPlacement:- """Ergebnis von ``resolve_placement()`` — wo das Window tatsaechlich hin soll."""+ """Result of ``resolve_placement()`` — where the window should actually go."""abs_x: intabs_y: intmonitor: str- recovered: bool # True wenn primary-fallback gegriffen hat+ recovered: bool # True if the primary fallback kicked in-# Plan §13.4: defaults wenn die persistierte Position nicht restorbar ist.+# Plan §13.4: defaults when the persisted position cannot be restored.DEFAULT_X_RELATIVE: int = 200DEFAULT_Y_RELATIVE: int = 80-DEFAULT_MARGIN_PX: int = 16 # rcWork-Clamp + Snap-Toleranz+DEFAULT_MARGIN_PX: int = 16 # rcWork clamp + snap tolerance@dataclass(frozen=True)class _ScreenSnapshot:- """Plattform-frei. Aus ``QGuiApplication.screens()`` befuellt."""+ """Platform-agnostic. Populated from ``QGuiApplication.screens()``."""- name: str # Win32 device name unter Windows; auf Linux/macOS sym. id+ name: str # Win32 device name on Windows; symbolic id on Linux/macOSgeometry: tuple[int, int, int, int] # (x, y, w, h) work-area in logical pxis_primary: booldef screens_from_qt() -> list[_ScreenSnapshot]:- """Qt-screens snapshot fuer resolve_placement(). Lazy-import damit- der Loader auch headless ohne PySide6 importierbar bleibt."""+ """Qt screens snapshot for resolve_placement(). Lazy import so+ the loader stays importable headless without PySide6."""from PySide6.QtGui import QGuiApplicationapp = QGuiApplication.instance()@@ -74,8 +74,8 @@ def screens_from_qt() -> list[_ScreenSnapshot]:primary = QGuiApplication.primaryScreen()out: list[_ScreenSnapshot] = []for screen in QGuiApplication.screens():- # availableGeometry = work-area (ohne Taskbar). Plan §13.4 nutzt- # rcWork — Qt's availableGeometry mappt 1:1.+ # availableGeometry = work area (without taskbar). Plan §13.4 uses+ # rcWork — Qt's availableGeometry maps 1:1.geo = screen.availableGeometry()out.append(_ScreenSnapshot(@@ -93,19 +93,19 @@ def resolve_placement(*,mascot_size_px: int = 160,) -> ResolvedPlacement:- """Plan §13.4 — die kanonische 5-Schritt-Recovery.-- 1. Wenn ``persisted.monitor`` in screens enthalten:- Restore an (rcWork.left + x_rel, rcWork.top + y_rel) mit Clamp- in rcWork minus 16-px-Margin minus mascot_size.- 2. Wenn nicht:- Pick primary monitor, default (200, 80) Position.- ``recovered=True`` damit Caller das loggen kann.- 3. Wenn keine Screens (Headless / Tests): default (0, 0)- relative + leerer Monitor-Name; Caller muss damit umgehen.+ """Plan §13.4 — the canonical 5-step recovery.++ 1. If ``persisted.monitor`` is present in screens:+ restore at (rcWork.left + x_rel, rcWork.top + y_rel) clamped+ into rcWork minus a 16 px margin minus mascot_size.+ 2. If not:+ pick the primary monitor, default (200, 80) position.+ ``recovered=True`` so the caller can log it.+ 3. If there are no screens (headless / tests): default (0, 0)+ relative + empty monitor name; the caller must handle that."""if not screens:- # Tests / headless ohne Qt-App.+ # Tests / headless without a Qt app.return ResolvedPlacement(abs_x=DEFAULT_X_RELATIVE,abs_y=DEFAULT_Y_RELATIVE,@@ -118,9 +118,9 @@ def resolve_placement(if persisted is not None and persisted.monitor in by_name:screen = by_name[persisted.monitor]sx, sy, sw, sh = screen.geometry- # Clamp der relativen Coords in rcWork minus Margin minus- # mascot_size — verhindert dass Mascot beim Restore von einem- # Resolution-Change off-screen landet.+ # Clamp the relative coords into rcWork minus margin minus+ # mascot_size — prevents the mascot from landing off-screen+ # on restore after a resolution change.max_rel_x = max(0, sw - mascot_size_px - DEFAULT_MARGIN_PX)max_rel_y = max(0, sh - mascot_size_px - DEFAULT_MARGIN_PX)rel_x = max(DEFAULT_MARGIN_PX, min(persisted.x_relative, max_rel_x))@@ -132,7 +132,7 @@ def resolve_placement(recovered=False,)- # Persisted-Monitor nicht da — primary fallback.+ # Persisted monitor not present — primary fallback.primary = next((s for s in screens if s.is_primary), screens[0])sx, sy, _sw, _sh = primary.geometryreturn ResolvedPlacement(@@ -151,15 +151,15 @@ def snap_to_edges(mascot_size_px: int = 160,snap_tolerance_px: int = 16,) -> tuple[int, int]:- """Plan §13.3 — Edge-Snap innerhalb 16 px Toleranz.+ """Plan §13.3 — edge snap within a 16 px tolerance.- Berechnet die nearest snap fuer top/bottom/left/right Kanten und- snapt wenn innerhalb Toleranz. Returnt (snapped_x, snapped_y).+ Computes the nearest snap for the top/bottom/left/right edges and+ snaps if within tolerance. Returns (snapped_x, snapped_y)."""sx, sy, sw, sh = monitor_geometrysnapped_x, snapped_y = abs_x, abs_y- # Distanz zur linken / rechten Kante.+ # Distance to the left / right edge.dist_left = abs_x - sxdist_right = (sx + sw) - (abs_x + mascot_size_px)if 0 <= dist_left <= snap_tolerance_px:@@ -167,7 +167,7 @@ def snap_to_edges(elif 0 <= dist_right <= snap_tolerance_px:snapped_x = sx + sw - mascot_size_px- # Distanz zur top / bottom Kante.+ # Distance to the top / bottom edge.dist_top = abs_y - sydist_bottom = (sy + sh) - (abs_y + mascot_size_px)if 0 <= dist_top <= snap_tolerance_px:@@ -186,9 +186,9 @@ def clamp_to_work_area(mascot_size_px: int = 160,margin_px: int = DEFAULT_MARGIN_PX,) -> tuple[int, int]:- """Verhindert Off-Screen-Drag. Plan §13.3 + §20.4.+ """Prevents off-screen drag. Plan §13.3 + §20.4.- Mascot bleibt komplett innerhalb rcWork minus Margin.+ Mascot stays fully inside rcWork minus the margin."""sx, sy, sw, sh = monitor_geometrymin_x = sx + margin_px@@ -204,8 +204,8 @@ def clamp_to_work_area(def load_position_from_toml(path: Path) -> Optional[MascotPosition]:- """Liest ``[overlay.mascot]``-Felder aus ``jarvis.toml``. None- wenn File fehlt oder Section/Felder nicht da."""+ """Reads the ``[overlay.mascot]`` fields from ``jarvis.toml``. None+ if the file is missing or the section/fields aren't there."""if not path.is_file():return Nonetry:@@ -225,20 +225,20 @@ def load_position_from_toml(path: Path) -> Optional[MascotPosition]:def save_position_to_toml(path: Path, position: MascotPosition) -> None:- """Atomic-Write der drei Position-Felder. Plan §21.3 light:- 1. read existing TOML als Text- 2. ersetze die drei Felder via line-based regex+ """Atomic write of the three position fields. Plan §21.3 light:+ 1. read existing TOML as text+ 2. replace the three fields via line-based regex3. tempfile + os.replace()- Wir schreiben TOML manuell (text-based) statt mit tomli_w weil das- Format dann den User-Whitespace und Comments beibehalt — wichtig- weil ``jarvis.toml`` user-editable ist und wir keine- Comments fressen wollen.+ We write TOML manually (text-based) instead of using tomli_w+ because that preserves the user's whitespace and comments —+ important because ``jarvis.toml`` is user-editable and we don't+ want to eat comments."""import reif not path.is_file():- # Fresh File — minimal initial section schreiben.+ # Fresh file — write a minimal initial section.new_text = ("[overlay.mascot]\n"f'position_monitor = "{_escape_toml_str(position.monitor)}"\n'@@ -250,7 +250,7 @@ def save_position_to_toml(path: Path, position: MascotPosition) -> None:text = path.read_text(encoding="utf-8")- # Section [overlay.mascot] muss existieren oder wir appenden.+ # Section [overlay.mascot] must exist, otherwise we append.section_re = re.compile(r"^\[overlay\.mascot\]\s*$", re.MULTILINE)if not section_re.search(text):if not text.endswith("\n"):@@ -264,7 +264,7 @@ def save_position_to_toml(path: Path, position: MascotPosition) -> None:_atomic_write_text(path, text)return- # Section da. Ersetze die drei Felder, oder appendiere wenn fehlen.+ # Section present. Replace the three fields, or append if missing.text = _replace_or_append_field(text,section_header="[overlay.mascot]",@@ -288,7 +288,7 @@ def save_position_to_toml(path: Path, position: MascotPosition) -> None:def _atomic_write_text(path: Path, text: str) -> None:- """tempfile + os.replace() (atomic auf Win32)."""+ """tempfile + os.replace() (atomic on Win32)."""path.parent.mkdir(parents=True, exist_ok=True)fd, tmp_name = tempfile.mkstemp(prefix=path.name + ".", suffix=".tmp", dir=str(path.parent)@@ -306,18 +306,18 @@ def _atomic_write_text(path: Path, text: str) -> None:def _escape_toml_str(s: str) -> str:- """Minimal TOML-string-escape: backslashes + double-quotes."""+ """Minimal TOML string escape: backslashes + double-quotes."""return s.replace("\\", "\\\\").replace('"', '\\"')def _replace_or_append_field(text: str, *, section_header: str, field: str, value: str) -> str:- """Ersetzt ``field = ...`` innerhalb ``[section]``. Wenn das Feld- nicht existiert, wird es direkt unter dem Section-Header eingefuegt.+ """Replaces ``field = ...`` within ``[section]``. If the field+ doesn't exist, it is inserted directly under the section header.- Region-grenze: bis zum naechsten ``\\n[`` (= naechster Section)- oder Ende-of-File.+ Region boundary: up to the next ``\\n[`` (= next section)+ or end of file."""import re@@ -328,7 +328,7 @@ def _replace_or_append_field()region_m = region_re.search(text)if region_m is None:- return text # caller stellte sicher dass section da ist+ return text # caller made sure the section is presentregion_text = region_m.group(2)@@ -343,7 +343,7 @@ def _replace_or_append_field(count=1,)else:- # Feld am Section-Anfang einfuegen.+ # Insert the field at the start of the section.new_region = f"{field} = {value}\n" + region_textreturn text[: region_m.start(2)] + new_region + text[region_m.end(2) :]diff --git a/OS-Level/src/overlay/monitors.py b/OS-Level/src/overlay/monitors.pyindex ba07d7c10a..2865665bb9 100644--- a/OS-Level/src/overlay/monitors.py+++ b/OS-Level/src/overlay/monitors.py@@ -1,8 +1,8 @@-"""Monitor-Enumeration via Qt + Hotplug-Subscription. Plan §12.3, §12.5.+"""Monitor enumeration via Qt + hotplug subscription. Plan §12.3, §12.5.-Qt liefert ``screenAdded``/``screenRemoved``-Signals; wir kapseln das in-einen kleinen Manager, damit Phase 9.1 die Windows-pro-Screen verwaltet-und Phase 9.2+ Position-Recovery (Mascot, Plan §13.4) andocken kann.+Qt provides ``screenAdded``/``screenRemoved`` signals; we wrap that in+a small manager so Phase 9.1 can manage the windows-per-screen and+Phase 9.2+ can hook in position recovery (mascot, Plan §13.4)."""from __future__ import annotations@@ -17,22 +17,22 @@ if TYPE_CHECKING: # pragma: no cover@dataclass(frozen=True)class MonitorInfo:- """Snapshot eines Monitors, plattform-frei."""+ """Snapshot of a monitor, platform-agnostic."""name: str- geometry: tuple[int, int, int, int] # (x, y, w, h) logische Pixel+ geometry: tuple[int, int, int, int] # (x, y, w, h) logical pixelsdevice_pixel_ratio: floatis_primary: booldef enumerate_monitors() -> list[MonitorInfo]:- """Snapshot aller live Monitore.+ """Snapshot of all live monitors.- Greift auf ``QGuiApplication.screens()`` zu — vorher muss eine- QApplication existieren (siehe ``main.py``). Test-Code mockt das- QGuiApplication-Modul.+ Accesses ``QGuiApplication.screens()`` — a QApplication must+ already exist (see ``main.py``). Test code mocks the+ QGuiApplication module."""- from PySide6.QtGui import QGuiApplication # lazy: keine Qt-Imports im Self-Test+ from PySide6.QtGui import QGuiApplication # lazy: no Qt imports in the self-testapp = QGuiApplication.instance()if app is None:@@ -53,10 +53,10 @@ def enumerate_monitors() -> list[MonitorInfo]:class MonitorManager:- """Subscribed auf ``QGuiApplication`` Hotplug-Signals.+ """Subscribes to ``QGuiApplication`` hotplug signals.- Phase 9.1 nutzt nur ``on_screen_added`` / ``on_screen_removed`` als- Hooks; Window-Lifecycle steckt in ``main.setup_windows``.+ Phase 9.1 only uses ``on_screen_added`` / ``on_screen_removed`` as+ hooks; window lifecycle lives in ``main.setup_windows``."""def __init__(@@ -69,12 +69,12 @@ class MonitorManager:self._app: Optional["QObject"] = Nonedef attach(self) -> None:- """Verbindet Hotplug-Signals. Idempotent."""+ """Connects hotplug signals. Idempotent."""from PySide6.QtGui import QGuiApplication # lazyapp = QGuiApplication.instance()if app is None:- raise RuntimeError("MonitorManager.attach: keine QGuiApplication")+ raise RuntimeError("MonitorManager.attach: no QGuiApplication")if self._app is app:returnif self._on_added is not None:@@ -84,7 +84,7 @@ class MonitorManager:self._app = appdef detach(self) -> None:- """Trennt Signals. Vor App-Quit aufrufen, sonst Dangling-Callbacks."""+ """Disconnects signals. Call before app quit, otherwise dangling callbacks."""if self._app is None:returnif self._on_added is not None:diff --git a/OS-Level/src/overlay/power.py b/OS-Level/src/overlay/power.pyindex e1dbc7053a..9ec27f477b 100644--- a/OS-Level/src/overlay/power.py+++ b/OS-Level/src/overlay/power.py@@ -1,17 +1,17 @@-"""GetSystemPowerStatus Polling. Plan §17.3 Throttling-Strategy.+"""GetSystemPowerStatus polling. Plan §17.3 throttling strategy.-AC vs Battery -> FPS halbieren. Polling alle 30 s auf Daemon-Thread.+AC vs battery -> halve the FPS. Polling every 30 s on a daemon thread.SYSTEM_POWER_STATUS struct (winbase.h):BYTE ACLineStatus // 0=offline, 1=online, 255=unknownBYTE BatteryFlag // 0..8 bit-mask- BYTE BatteryLifePercent // 0..100 oder 255 (unknown)- BYTE SystemStatusFlag // 1 = Battery-Saver an- DWORD BatteryLifeTime // Sekunden bis empty oder 0xFFFFFFFF- DWORD BatteryFullLifeTime // dito+ BYTE BatteryLifePercent // 0..100 or 255 (unknown)+ BYTE SystemStatusFlag // 1 = battery saver on+ DWORD BatteryLifeTime // seconds until empty or 0xFFFFFFFF+ DWORD BatteryFullLifeTime // ditto-Wir lesen primaer ACLineStatus + SystemStatusFlag.+We primarily read ACLineStatus + SystemStatusFlag."""from __future__ import annotations@@ -29,7 +29,7 @@ logger = logging.getLogger(__name__)class PowerStatus:on_battery: boolbattery_saver: bool- battery_percent: Optional[int] # None wenn unknown+ battery_percent: Optional[int] # None if unknownPowerCallback = Callable[[PowerStatus], None]@@ -38,7 +38,7 @@ PowerCallback = Callable[[PowerStatus], None]def query_status() -> Optional[PowerStatus]:"""Plan §17.3 — GetSystemPowerStatus via ctypes.- Returnt None auf Nicht-Windows oder bei API-Fehler.+ Returns None on non-Windows or on an API error."""if sys.platform != "win32":return None@@ -82,7 +82,7 @@ def query_status() -> Optional[PowerStatus]:class PowerMonitor:- """30-Sekunden-Polling-Thread fuer SYSTEM_POWER_STATUS.+ """30-second polling thread for SYSTEM_POWER_STATUS.Lifecycle::@@ -139,8 +139,8 @@ class PowerMonitor:if self.is_running:returnself._stop.clear()- # Initial sofort poll'en damit der Caller den Status nicht erst- # nach 30 s bekommt.+ # Poll immediately on start so the caller doesn't have to wait+ # 30 s for the first status.self.poll_once()self._thread = threading.Thread(target=self._run, name="overlay-power-monitor", daemon=Truediff --git a/OS-Level/src/overlay/schema.py b/OS-Level/src/overlay/schema.pyindex 488f09225a..8094bae18c 100644--- a/OS-Level/src/overlay/schema.py+++ b/OS-Level/src/overlay/schema.py@@ -1,16 +1,16 @@-"""IPC Pydantic-v2-Schemas — Single-Source. Plan §10.+"""IPC Pydantic v2 schemas — single source of truth. Plan §10.-Wire-Envelope (§10.1):+Wire envelope (§10.1):{v, type, id, ts_ns, target, payload}-``type`` ist der Discriminator fuer ``payload``. Die saubere Pydantic-v2--Variante: pro Message-Type ein eigenes Envelope-Modell mit ``type`` als-``Literal``-Field; die Union darueber wird mit ``Field(discriminator="type")``-typisiert. ``IPCMessage`` ist die runtime-validierende ``TypeAdapter``--Instanz.+``type`` is the discriminator for ``payload``. The clean Pydantic v2+approach: one dedicated envelope model per message type with ``type``+as a ``Literal`` field; the union over them is typed with+``Field(discriminator="type")``. ``IPCMessage`` is the runtime-validating+``TypeAdapter`` instance.-AD-15: Pydantic v2 (Python) und Zod (TS) symmetrisch — Phase 9.4 leitet-das Zod-Schema aus dem JSON-Schema-Export hier ab.+AD-15: Pydantic v2 (Python) and Zod (TS) stay symmetric — Phase 9.4+derives the Zod schema from the JSON-schema export here."""from __future__ import annotations@@ -27,10 +27,10 @@ from pydantic import ()from ulid import ULID-# Schema-Major-Version. Forward-Compat: Empfaenger warnen wenn != 1.+# Schema major version. Forward compat: receivers warn if != 1.SCHEMA_VERSION = 1-# Discriminator-Werte (auch von der State-Machine in 9.3 referenziert).+# Discriminator values (also referenced by the state machine in 9.3).StateName = Literal["idle","listening",@@ -48,12 +48,12 @@ StateReason = Literal["wakeword", "user", "tool", "timeout", "error"]def now_ns() -> int:- """Unix-epoch ns. Kompatibel mit SHM-Cursor + WS-Envelopes (§11.4)."""+ """Unix epoch ns. Compatible with the SHM cursor + WS envelopes (§11.4)."""return time.time_ns()def new_ulid() -> str:- """Frische ULID als Wire-String (26 Crockford-Base32 chars)."""+ """Fresh ULID as a wire string (26 Crockford Base32 chars)."""return str(ULID())@@ -99,7 +99,7 @@ class ActionEndedPayload(BaseModel):class CursorPayload(BaseModel):- """WS-Fallback wenn SHM nicht verfuegbar (§11.5)."""+ """WS fallback when SHM isn't available (§11.5)."""model_config = ConfigDict(extra="forbid")@@ -121,9 +121,9 @@ class HeartbeatPayload(BaseModel):class ConfigPayload(BaseModel):- """Hauptjarvis -> Overlay nach Config-Reload (§10.2)."""+ """Main-Jarvis -> overlay after a config reload (§10.2)."""- model_config = ConfigDict(extra="allow") # forward-compat, neue Theme-Keys+ model_config = ConfigDict(extra="allow") # forward-compat, new theme keystheme: dict[str, Any] = Field(default_factory=dict)mascot_enabled: bool = True@@ -168,12 +168,12 @@ class MascotEventPayload(BaseModel):# ------------------------------------------------------------------------------# Envelope — §10.1, eine Klasse pro type, Discriminated Union+# Envelope — §10.1, one class per type, discriminated union# -----------------------------------------------------------------------------class _BaseEnvelope(BaseModel):- """Gemeinsame Envelope-Felder. ``type`` setzt jede Subklasse selbst."""+ """Shared envelope fields. Each subclass sets ``type`` itself."""model_config = ConfigDict(extra="forbid")@@ -185,9 +185,9 @@ class _BaseEnvelope(BaseModel):@field_validator("v")@classmethoddef _check_version(cls, value: int) -> int:- # Forward-Compat: hoechere Versionen werden in IPC-Layer geloggt,- # hier akzeptieren wir alles >=1, damit ein neueres Overlay vom- # alten Hauptjarvis empfangen kann.+ # Forward compat: higher versions are logged in the IPC layer,+ # here we accept anything >=1 so a newer overlay can receive+ # from an older Main-Jarvis.if value < 1:raise ValueError(f"schema-version v={value} < 1")return value@@ -259,14 +259,14 @@ IPCEnvelope = Annotated[Field(discriminator="type"),]-# Runtime-Validator. ``IPCMessage.validate_python(d)`` /-# ``IPCMessage.validate_json(b)`` waehlen anhand des ``type``-Felds das-# richtige Envelope-Modell.+# Runtime validator. ``IPCMessage.validate_python(d)`` /+# ``IPCMessage.validate_json(b)`` pick the right envelope model based+# on the ``type`` field.IPCMessage: TypeAdapter[Any] = TypeAdapter(IPCEnvelope)-# State-Sets, die Plan §6.1 in Code abbildet — auch von der 9.3-State--# Machine konsumiert.+# State sets that mirror Plan §6.1 in code — also consumed by the+# 9.3 state machine.NON_STATE_TYPES: frozenset[str] = frozenset({"cursor",@@ -283,7 +283,7 @@ STATE_TYPES: frozenset[str] = frozenset({"state", "config"})def is_state_type(envelope_type: str) -> bool:- """Backpressure-Hint: ``False`` -> kann gedroppt werden (§10.4)."""+ """Backpressure hint: ``False`` -> can be dropped (§10.4)."""return envelope_type in STATE_TYPESdiff --git a/OS-Level/src/overlay/self_test.py b/OS-Level/src/overlay/self_test.pyindex 7e3c2b61b3..b9f6da1197 100644--- a/OS-Level/src/overlay/self_test.py+++ b/OS-Level/src/overlay/self_test.py@@ -1,7 +1,7 @@-"""Self-Test ohne GUI-Dependencies.+"""Self-test without GUI dependencies.-Importiert NUR Foundation-Module (config, state, schema). Beruehrt KEIN Qt,-damit headless-CI-Runs ohne Display funktionieren.+Imports ONLY foundation modules (config, state, schema). Touches NO Qt,+so headless CI runs without a display work."""from __future__ import annotations@@ -14,7 +14,7 @@ def run() -> int:from .config import OverlayConfigfrom .state import OverlayState- # Pydantic-Default-Roundtrip als Sanity-Check.+ # Pydantic default roundtrip as a sanity check.cfg = OverlayConfig()assert cfg.enabled is Trueassert OverlayState.IDLE.value == "idle"diff --git a/OS-Level/src/overlay/state.py b/OS-Level/src/overlay/state.pyindex ab73ab82e0..445f4f3731 100644--- a/OS-Level/src/overlay/state.py+++ b/OS-Level/src/overlay/state.py@@ -1,8 +1,8 @@-"""OverlayState Enum + StateMachine gemaess Plan §6.+"""OverlayState enum + StateMachine per Plan §6.-Plan §6.1: 8 States, Glow ist NUR aktiv in TYPING und CLICKING.-Plan AD-8: State-Machine lebt im Overlay-Prozess (nicht im Hauptjarvis).-Plan AD-17: 16 ms Coalescing fuer identische Folge-Transitionen.+Plan §6.1: 8 states, glow is ONLY active in TYPING and CLICKING.+Plan AD-8: the state machine lives in the overlay process (not in Main-Jarvis).+Plan AD-17: 16 ms coalescing for identical consecutive transitions."""from __future__ import annotations@@ -17,7 +17,7 @@ logger = logging.getLogger(__name__)class OverlayState(str, Enum):- """8 States laut Plan §6.1. String-Werte sind stable Wire-Format."""+ """8 states per Plan §6.1. String values are the stable wire format."""IDLE = "idle"LISTENING = "listening"@@ -34,35 +34,35 @@ GLOW_ACTIVE_STATES: frozenset[OverlayState] = frozenset()-# Plan AD-17 — 16 ms = 1 Frame @ 60 Hz.+# Plan AD-17 — 16 ms = 1 frame @ 60 Hz.COALESCE_WINDOW_NS: int = 16_000_000-# (old, new, reason) — reason kann None sein wenn keine angegeben wurde.+# (old, new, reason) — reason can be None if none was given.StateChangeCallback = Callable[[OverlayState, OverlayState, Optional[str]], None]class StateMachine:- """Authoritative state holder fuer das Overlay.+ """Authoritative state holder for the overlay.- Plan AD-8: lebt im Overlay-Prozess. Hauptjarvis sendet Events ueber- IPC, der EventRouter mappt sie auf ``transition_to()``-Aufrufe.+ Plan AD-8: lives in the overlay process. Main-Jarvis sends events+ over IPC, and the EventRouter maps them to ``transition_to()`` calls.- Plan §6.2 Coalescing-Regel: ``any -> same state within 16 ms : ignored``.- Identische Folge-Transitionen innerhalb von ``COALESCE_WINDOW_NS`` sind- no-op und feuern keine Subscriber.+ Plan §6.2 coalescing rule: ``any -> same state within 16 ms : ignored``.+ Identical consecutive transitions within ``COALESCE_WINDOW_NS`` are+ a no-op and do not fire subscribers.- Subscriber-Callbacks werden SYNCHRON im Caller-Thread von- ``transition_to()`` aufgerufen — Subscriber muessen schnell sein und- nicht blockieren. Wenn ein Callback aus einem Worker-Thread feuert,- ist Marshalling auf den Qt-Thread Aufgabe des Subscribers (z.B. ueber- ``QMetaObject.invokeMethod`` oder Qt-Signals).+ Subscriber callbacks are called SYNCHRONOUSLY on the caller thread+ of ``transition_to()`` — subscribers must be fast and non-blocking.+ If a callback fires from a worker thread, marshalling onto the Qt+ thread is the subscriber's responsibility (e.g. via+ ``QMetaObject.invokeMethod`` or Qt signals)."""def __init__(self, *, initial: OverlayState = OverlayState.IDLE) -> None:self._state = initial- # monotonic_ns() ist immun gegen Wallclock-Skews — hier sicherer- # als time.time_ns() weil es nur fuer Coalescing-Diff dient.+ # monotonic_ns() is immune to wallclock skew — safer here than+ # time.time_ns() since it's only used for the coalescing diff.self._last_transition_ns: int = 0self._lock = threading.RLock()self._subscribers: list[StateChangeCallback] = []@@ -73,7 +73,7 @@ class StateMachine:return self._statedef subscribe(self, callback: StateChangeCallback) -> Callable[[], None]:- """Registriert einen Subscriber, returnt eine ``unsubscribe``-Funktion."""+ """Registers a subscriber, returns an ``unsubscribe`` function."""with self._lock:self._subscribers.append(callback)@@ -90,21 +90,21 @@ class StateMachine:*,reason: Optional[str] = None,) -> bool:- """Wechselt nach ``target``. Returnt ``True`` wenn echte Transition.+ """Switches to ``target``. Returns ``True`` if it was a real transition.- Coalescing-Regeln:- - ``target == current`` und letzter Wechsel < 16 ms -> ignoriert.- - ``target == current`` aber letzter Wechsel >= 16 ms -> ebenfalls- ignoriert (kein State-Change), aber das ist kein Coalescing-Hit.- - ``target != current`` -> immer transitionieren.+ Coalescing rules:+ - ``target == current`` and the last change was < 16 ms ago -> ignored.+ - ``target == current`` but the last change was >= 16 ms ago -> also+ ignored (no state change), but that is not a coalescing hit.+ - ``target != current`` -> always transitions."""now_ns = time.monotonic_ns()with self._lock:old = self._stateif target == old:- # Kein State-Change. Coalescing-Spec ist hier streng- # genommen redundant, aber wir loggen den Hit damit- # Drift-Diagnose moeglich bleibt.+ # No state change. The coalescing spec is strictly+ # speaking redundant here, but we log the hit so+ # drift diagnosis stays possible.if (now_ns - self._last_transition_ns) < COALESCE_WINDOW_NS:logger.debug("state coalesced: %s -> %s within %d ns",@@ -117,8 +117,8 @@ class StateMachine:self._last_transition_ns = now_nssubscribers_snapshot = list(self._subscribers)- # Subscriber-Dispatch ausserhalb des Locks — verhindert Deadlocks- # falls ein Subscriber re-entrant transition_to() ruft.+ # Subscriber dispatch outside the lock — prevents deadlocks+ # in case a subscriber re-entrantly calls transition_to().for cb in subscribers_snapshot:try:cb(old, target, reason)@@ -132,8 +132,8 @@ class StateMachine:def transition_to_hidden(self, *, reason: Optional[str] = None) -> bool:- """Plan §17.3 + §20.2 — Convenience fuer Fullscreen-Detector- und Hide-Timeout-Pfade."""+ """Plan §17.3 + §20.2 — convenience for the fullscreen detector+ and hide-timeout paths."""return self.transition_to(OverlayState.HIDDEN, reason=reason)diff --git a/OS-Level/src/overlay/throttler.py b/OS-Level/src/overlay/throttler.pyindex edee3000d2..fb5bfbb8f2 100644--- a/OS-Level/src/overlay/throttler.py+++ b/OS-Level/src/overlay/throttler.py@@ -1,29 +1,29 @@-"""Throttler — Single Source of Truth fuer FPS-Targets + Visibility.+"""Throttler — single source of truth for FPS targets + visibility.Plan §17.2 + §17.3. Inputs:- - aktueller OverlayState (idle/listening/.../typing/clicking/...)+ - current OverlayState (idle/listening/.../typing/clicking/...)- on_battery (PowerMonitor)- - last_state_change_ts (von StateMachine subscriber)+ - last_state_change_ts (from the StateMachine subscriber)- fullscreen_should_hide (FullscreenDetector)Outputs:- - get_target_fps() -> int (passt FPS-Cap)- - should_hide_view() -> bool (5-min-Idle-Pfad: View komplett hidden)- - subscribe(callback) (callback feuert wenn target_fps oder- should_hide_view sich aendert)+ - get_target_fps() -> int (the FPS cap)+ - should_hide_view() -> bool (5-min idle path: view fully hidden)+ - subscribe(callback) (callback fires when target_fps or+ should_hide_view changes)-Plan §17.2 FPS-Targets pro State:+Plan §17.2 FPS targets per state:hidden -> 0idle (30s+) -> fps_idle (default 1)listening / thinking / speaking / error -> fps_active (30)typing / clicking -> fps_burst (60)- error-flash -> fps_burst fuer 600 ms, dann zurueck+ error-flash -> fps_burst for 600 ms, then back-Plan §17.3 Throttling-Strategy:- AC vs Battery: on_battery -> alle FPS halbieren.- Idle Detection: 30 s no events -> fps_idle.- Hide on Idle: 5 min no events -> should_hide_view=True.- Wake on Event: jeder State-Change resettet Idle-Timer.+Plan §17.3 throttling strategy:+ AC vs battery: on_battery -> halve all FPS.+ Idle detection: 30 s no events -> fps_idle.+ Hide on idle: 5 min no events -> should_hide_view=True.+ Wake on event: every state change resets the idle timer."""from __future__ import annotations@@ -39,15 +39,15 @@ from .state import OverlayState, StateMachinelogger = logging.getLogger(__name__)-# Plan §17.2 + §21.1 default Werte.+# Plan §17.2 + §21.1 default values.DEFAULT_FPS_IDLE: int = 1DEFAULT_FPS_ACTIVE: int = 30DEFAULT_FPS_BURST: int = 60DEFAULT_IDLE_TIMEOUT_S: float = 30.0-DEFAULT_HIDE_TIMEOUT_S: float = 300.0 # 5 Minuten+DEFAULT_HIDE_TIMEOUT_S: float = 300.0 # 5 minutes-# State -> FPS-Bucket Mapping. Plan §17.2.+# State -> FPS bucket mapping. Plan §17.2._BURST_STATES: frozenset[OverlayState] = frozenset({OverlayState.TYPING, OverlayState.CLICKING})@@ -59,12 +59,12 @@ _ACTIVE_STATES: frozenset[OverlayState] = frozenset(OverlayState.ERROR,})-# IDLE selbst zaehlt als active solange < idle_timeout; danach idle-bucket.+# IDLE itself counts as active as long as < idle_timeout; after that, idle bucket.@dataclass(frozen=True)class ThrottleSnapshot:- """Aktueller Output. Subscriber bekommen das."""+ """Current output. Subscribers receive this."""target_fps: intshould_hide_view: bool@@ -78,10 +78,10 @@ ThrottleCallback = Callable[[ThrottleSnapshot], None]class Throttler:- """Berechnet Target-FPS + Hide-Decision aus State + Power + Idle.+ """Computes the target FPS + hide decision from state + power + idle.- Idempotent + Thread-safe (RLock). ``recompute()`` ist der einzige- Entry-Point der Subscriber feuert.+ Idempotent + thread-safe (RLock). ``recompute()`` is the only+ entry point that fires subscribers."""def __init__(@@ -127,14 +127,14 @@ class Throttler:self.recompute()def subscribe(self, callback: ThrottleCallback) -> Callable[[], None]:- """Registriert Callback. Sofort einmal mit aktuellem Snapshot- aufgerufen damit der Subscriber initial den Zustand kennt.-- Reihenfolge wichtig: erst recompute() (ohne den neuen- Subscriber in der Liste), dann initial-callback einmal feuern,- DANN in die Subscriber-Liste aufnehmen. Sonst doppelter- Initial-Fire (recompute ruft alle Subscriber inkl. dem neuen,- plus expliziter initial-call hier).+ """Registers the callback. Immediately called once with the+ current snapshot so the subscriber knows the initial state.++ Order matters: first recompute() (without the new subscriber+ in the list), then fire the initial callback once, THEN add+ it to the subscriber list. Otherwise it would fire twice+ initially (recompute calls all subscribers including the new+ one, plus the explicit initial call here)."""snap = self.recompute()try:@@ -169,8 +169,8 @@ class Throttler:return self.recompute().should_hide_viewdef recompute(self) -> ThrottleSnapshot:- """Berechnet den aktuellen Snapshot. Feuert Subscriber wenn- sich was geaendert hat. Idempotent."""+ """Computes the current snapshot. Fires subscribers if+ something changed. Idempotent."""with self._lock:state = self._machine.stateidle_s = self.idle_seconds@@ -203,7 +203,7 @@ class Throttler:state is OverlayState.IDLE and idle_s >= self._hide_timeout)if should_hide_view:- # Hidden-View braucht keinen Compositor-Tick.+ # A hidden view doesn't need a compositor tick.target = 0snapshot = ThrottleSnapshot(@@ -234,16 +234,16 @@ class Throttler:def _on_state_change(self, _old: OverlayState, _new: OverlayState, _reason: Optional[str]) -> None:- # Plan §17.3: Wake on Event -> Idle-Timer reset.+ # Plan §17.3: wake on event -> idle timer reset.with self._lock:self._last_change_ns = time.monotonic_ns()self.recompute()def _snapshot_changed(a: ThrottleSnapshot, b: ThrottleSnapshot) -> bool:- """Subscriber feuern nur wenn FPS oder Visibility sich aendern.- idle_seconds aendert sich kontinuierlich — das wuerde sonst- Subscriber-Spam ausloesen."""+ """Subscribers only fire if FPS or visibility change.+ idle_seconds changes continuously — firing on that would+ otherwise trigger subscriber spam."""return (a.target_fps != b.target_fpsor a.should_hide_view is not b.should_hide_view@@ -253,7 +253,7 @@ def _snapshot_changed(a: ThrottleSnapshot, b: ThrottleSnapshot) -> bool:)-# Re-export fuer Subscriber-Tests die ohne expliziten replace() arbeiten.+# Re-export for subscriber tests that work without an explicit replace().__all__ = ["DEFAULT_FPS_ACTIVE","DEFAULT_FPS_BURST",diff --git a/OS-Level/src/overlay/transparency.py b/OS-Level/src/overlay/transparency.pyindex 9220f3b5e9..b020f43396 100644--- a/OS-Level/src/overlay/transparency.py+++ b/OS-Level/src/overlay/transparency.py@@ -1,13 +1,13 @@-"""ctypes-Wrappers fuer Win32-Window-Flags.+"""ctypes wrappers for Win32 window flags.-Plan §12.1 / §12.4: Transparente Click-Through Layered-Windows mit-``WDA_EXCLUDEFROMCAPTURE`` damit Screen-Sharing und OBS das Overlay nicht-mit-aufnehmen. Qt setzt ``WindowTransparentForInput`` selbst, der ctypes-Pfad-hier ist (a) Defense-in-Depth fuer Affinity, (b) bereitet Phase 9.6 vor-(Mascot braucht selektiv ``WS_EX_NOACTIVATE``).+Plan §12.1 / §12.4: transparent click-through layered windows with+``WDA_EXCLUDEFROMCAPTURE`` so screen sharing and OBS don't pick up the+overlay. Qt sets ``WindowTransparentForInput`` itself; the ctypes path+here is (a) defense-in-depth for affinity, (b) prepares for Phase 9.6+(mascot needs ``WS_EX_NOACTIVATE`` selectively).-Auf Nicht-Windows-Hosts sind alle Funktionen No-Ops, damit Tests headless-auf jeder Plattform durchlaufen koennen.+On non-Windows hosts all functions are no-ops, so tests can run+headless on any platform."""from __future__ import annotations@@ -16,7 +16,7 @@ import ctypesimport sysfrom ctypes import wintypes-# Win32-Konstanten — Plan §12.1, §12.2.+# Win32 constants — Plan §12.1, §12.2.GWL_EXSTYLE = -20WS_EX_LAYERED = 0x00080000WS_EX_TRANSPARENT = 0x00000020@@ -33,17 +33,17 @@ def _is_windows() -> bool:return sys.platform == "win32"-def get_user32(): # pragma: no cover — Plattform-Branch- """Lazy-Loader. Nur auf Windows aufrufen."""+def get_user32(): # pragma: no cover — platform branch+ """Lazy loader. Only call on Windows."""if not _is_windows():- raise RuntimeError("user32 ist Windows-only")+ raise RuntimeError("user32 is Windows-only")return ctypes.windll.user32def apply_click_through(hwnd: int) -> None:- """Ergaenzt ``WS_EX_LAYERED | WS_EX_TRANSPARENT`` an einem HWND.+ """Adds ``WS_EX_LAYERED | WS_EX_TRANSPARENT`` to an HWND.- Idempotent: bestehende Style-Bits werden mit OR ergaenzt, nichts geloescht.+ Idempotent: existing style bits are OR'd in, nothing is cleared."""if not _is_windows():return@@ -61,10 +61,10 @@ def apply_click_through(hwnd: int) -> None:def apply_mascot_styles(hwnd: int) -> None:- """Mascot-Window — Plan §12.2: Layered + NoActivate + Toolwindow.+ """Mascot window — Plan §12.2: layered + no-activate + tool window.- Bewusst KEIN ``WS_EX_TRANSPARENT``, damit Klicks/Drag durchkommen.- Phase 9.6 nutzt das.+ Deliberately NO ``WS_EX_TRANSPARENT``, so clicks/drag come through.+ Phase 9.6 uses this."""if not _is_windows():return@@ -84,8 +84,8 @@ def apply_mascot_styles(hwnd: int) -> None:def exclude_from_capture(hwnd: int) -> bool:"""``SetWindowDisplayAffinity(hwnd, WDA_EXCLUDEFROMCAPTURE)``.- Returnt ``True`` bei Erfolg, ``False`` falls unsupported (alte Win10-Builds)- oder Aufruf auf Nicht-Windows.+ Returns ``True`` on success, ``False`` if unsupported (old Win10 builds)+ or when called on non-Windows."""if not _is_windows():return False@@ -99,13 +99,13 @@ def exclude_from_capture(hwnd: int) -> bool:def reapply_capture_affinity(hwnd: int) -> bool:- """Plan §18.1 — Reapply WDA_EXCLUDEFROMCAPTURE.+ """Plan §18.1 — reapply WDA_EXCLUDEFROMCAPTURE.- Identisch zu ``exclude_from_capture``, aber als named entry-point- fuer Window-Hooks (showEvent, screenChanged, screenAdded). DWM- cacht das Affinity-Flag nicht ueber Re-Composite-Boundaries; nach- DPI-Wechseln oder Monitor-Hotplug hat das Flag schon mal verloren- gewirkt. Daher idempotent re-applien.+ Identical to ``exclude_from_capture``, but exposed as a named entry+ point for window hooks (showEvent, screenChanged, screenAdded). DWM+ doesn't cache the affinity flag across re-composite boundaries; after+ DPI changes or a monitor hotplug the flag has been observed to get+ lost. Hence re-apply it idempotently."""return exclude_from_capture(hwnd)@@ -113,9 +113,9 @@ def reapply_capture_affinity(hwnd: int) -> bool:def set_per_monitor_dpi_awareness() -> None:"""``SetProcessDpiAwareness(2)`` — PROCESS_PER_MONITOR_DPI_AWARE.- Muss VOR der QApplication-Erzeugung laufen (Plan §12.3). Schluckt alle- Fehler, weil der Aufruf bei bereits gesetztem Awareness-Level- ``E_ACCESSDENIED`` zurueckgibt.+ Must run BEFORE the QApplication is created (Plan §12.3). Swallows+ all errors, since the call returns ``E_ACCESSDENIED`` when the+ awareness level is already set."""if not _is_windows():returndiff --git a/OS-Level/src/overlay/window_glow.py b/OS-Level/src/overlay/window_glow.pyindex fab7cee9d3..ba4cf6014a 100644--- a/OS-Level/src/overlay/window_glow.py+++ b/OS-Level/src/overlay/window_glow.py@@ -1,15 +1,15 @@-"""EdgeGlowWindow — transparentes click-through Frameless-Fenster pro Screen.+"""EdgeGlowWindow — transparent click-through frameless window per screen.-Phase 9.3: Test-Quadrat ist raus, statt dessen rendert ein-``QWebEngineView`` die ``overlay-ui/dist/edge-glow.html``. Eine-``StateBridge`` wird via ``QWebChannel`` als ``stateBridge`` exposed —-der TS-Renderer subscribed auf ``stateChanged`` und liest ``currentState``.+Phase 9.3: the test square is gone; instead a ``QWebEngineView`` renders+``overlay-ui/dist/edge-glow.html``. A ``StateBridge`` is exposed via+``QWebChannel`` as ``stateBridge`` — the TS renderer subscribes to+``stateChanged`` and reads ``currentState``.-Window-Flags strikt nach Plan §12.1.+Window flags strictly follow Plan §12.1.-WICHTIG: Wenn ``overlay-ui/dist/edge-glow.html`` nicht existiert (z.B.-weil noch nie gebuildet), laedt der View ``about:blank`` und loggt eine-Warnung. Das verhindert Crashes in CI/Smoke-Pfaden ohne Frontend-Build.+IMPORTANT: if ``overlay-ui/dist/edge-glow.html`` doesn't exist (e.g.+because it was never built), the view loads ``about:blank`` and logs a+warning. This prevents crashes in CI/smoke paths without a frontend build."""from __future__ import annotations@@ -44,26 +44,26 @@ if TYPE_CHECKING: # pragma: no coverlogger = logging.getLogger(__name__)-# Plan §22 — Vite-Build legt das HTML genau hier ab.+# Plan §22 — the Vite build places the HTML exactly here._EDGE_GLOW_HTML = (Path(__file__).resolve().parents[2] / "overlay-ui" / "dist" / "edge-glow.html")class StateBridge(QObject):- """QObject das via QWebChannel als ``stateBridge`` exposed wird.+ """QObject exposed via QWebChannel as ``stateBridge``.- Der TS-Renderer (``overlay-ui/src/edge-glow/main.ts``) verbindet- seinen Handler auf ``stateChanged`` und ruft ``currentState`` fuer das- initiale Frame.+ The TS renderer (``overlay-ui/src/edge-glow/main.ts``) connects+ its handler to ``stateChanged`` and calls ``currentState`` for the+ initial frame.- Das Object MUSS im GUI-Thread instantiiert werden — Qt-Signals werden- automatisch per ``QueuedConnection`` an die GUI-Thread-Slots- marshalled, wenn ``emit()`` aus dem IPC-Thread kommt.+ This object MUST be instantiated on the GUI thread — Qt signals are+ automatically marshalled to the GUI thread slots via+ ``QueuedConnection`` when ``emit()`` is called from the IPC thread."""- # (old, new, reason) — alle drei strings, weil JS-Signal-Routing nur- # primitive Typen sauber serialisiert.+ # (old, new, reason) — all three strings, since JS signal routing+ # only cleanly serializes primitive types.stateChanged = Signal(str, str, str)def __init__(@@ -71,8 +71,9 @@ class StateBridge(QObject):) -> None:super().__init__(parent)self._machine = machine- # Subscriber wird sync vom StateMachine-Caller-Thread aufgerufen.- # Wir feuern hier nur das Qt-Signal — Qt marshalled es selbst.+ # The subscriber is called synchronously on the StateMachine+ # caller thread. We only fire the Qt signal here — Qt marshals+ # it itself.self._unsubscribe = machine.subscribe(self._on_state_change)def _on_state_change(@@ -84,8 +85,8 @@ class StateBridge(QObject):try:self.stateChanged.emit(old.value, new.value, reason or "")except RuntimeError:- # Window wurde bereits zerstoert -> Subscriber wird gleich- # detached; harmlos.+ # Window has already been destroyed -> the subscriber is+ # about to be detached; harmless.logger.debug("StateBridge.emit on dead QObject")@Slot(result=str)@@ -93,27 +94,27 @@ class StateBridge(QObject):return self._machine.state.valuedef shutdown(self) -> None:- """Unsubscribe vom StateMachine — aufrufen vor ``deleteLater()``."""+ """Unsubscribe from the StateMachine — call before ``deleteLater()``."""if self._unsubscribe is not None:self._unsubscribe()self._unsubscribe = Noneclass EffectsBridge(QObject):- """QObject das via QWebChannel als ``effectsBridge`` exposed wird.- Phase 9.5 — feuert die Action-Effects (Click-Ripple, Cursor-Trail,- Typing-Sweep).+ """QObject exposed via QWebChannel as ``effectsBridge``.+ Phase 9.5 — fires the action effects (click ripple, cursor trail,+ typing sweep).- Signale gehen 1:1 zum TS-Renderer (Plan §14/§15/§16). Coords sind- immer PHYSICAL px (Plan §14.4 + §11.2); Renderer konvertiert per+ Signals go 1:1 to the TS renderer (Plan §14/§15/§16). Coords are+ always PHYSICAL px (Plan §14.4 + §11.2); the renderer converts viadevicePixelRatio."""# x, y physical px, monitor_idx, button.clickEvent = Signal(int, int, int, str)- # x, y physical px (aus SHM oder WS-Fallback).+ # x, y physical px (from SHM or the WS fallback).cursorMoved = Signal(int, int)- # kind, duration_hint_ms (-1 wenn nicht gesetzt).+ # kind, duration_hint_ms (-1 if not set).actionStarted = Signal(str, int)actionEnded = Signal()@@ -146,11 +147,11 @@ class EffectsBridge(QObject):class _TransparentWebPage(QWebEnginePage):- """Page mit transparentem Hintergrund.+ """Page with a transparent background.- Ohne diesen Override rendert Chromium einen weissen Background- selbst wenn ``body { background: transparent }`` gesetzt ist. Plan- §12.1 + AD-1 fordern echte Compositor-Transparenz.+ Without this override, Chromium renders a white background even+ when ``body { background: transparent }`` is set. Plan §12.1 + AD-1+ require true compositor transparency."""def __init__(self, parent: Optional[QObject] = None) -> None:@@ -159,11 +160,11 @@ class _TransparentWebPage(QWebEnginePage):class EdgeGlowWindow(QWidget):- """Frameless, transparent, click-through, immer oben.+ """Frameless, transparent, click-through, always on top.- Geometrie deckt den vollen Monitor ab. Im Gegensatz zur 9.1-Version- rendert hier ein ``QWebEngineView`` die echte HTML/CSS-Pipeline; das- statische Test-Quadrat ist entfernt.+ Geometry covers the full monitor. Unlike the 9.1 version, a+ ``QWebEngineView`` renders the real HTML/CSS pipeline here; the+ static test square has been removed."""def __init__(@@ -182,8 +183,8 @@ class EdgeGlowWindow(QWidget):self._state_machine = state_machineself._effects_bridge = effects_bridgeself._html_path = html_path or _EDGE_GLOW_HTML- # Plan §18.1 — screenChanged-Signal wird in showEvent verbunden,- # weil windowHandle() vor show() None sein kann.+ # Plan §18.1 — the screenChanged signal is connected in showEvent,+ # since windowHandle() can be None before show().self._screen_change_connected: bool = False# Plan §12.1 — exakt diese Flag-Kombination.@@ -202,23 +203,23 @@ class EdgeGlowWindow(QWidget):self.setScreen(screen)self.setGeometry(screen.geometry())- # Layout + WebView. Margins 0 damit der Render-Surface die volle- # Window-Geometrie nutzt — sonst gibt es einen 9-px Default-Rand.+ # Layout + WebView. Margins 0 so the render surface uses the+ # full window geometry — otherwise there's a 9 px default margin.layout = QVBoxLayout(self)layout.setContentsMargins(0, 0, 0, 0)self._view = QWebEngineView(self)- # Kein Background-Repaint vom Widget selbst.+ # No background repaint from the widget itself.self._view.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground, True)self._view.setAttribute(Qt.WidgetAttribute.WA_TransparentForMouseEvents, True)page = _TransparentWebPage(self._view)self._view.setPage(page)- # WebChannel + StateBridge wenn StateMachine geliefert wurde.- # Das ist optional damit Phase-9.1-Smoke-Tests ohne Machine- # weiter laufen. Phase 9.5 haengt zusaetzlich die effectsBridge- # an wenn ``effects_bridge`` gesetzt ist.+ # WebChannel + StateBridge if a StateMachine was supplied.+ # This is optional so Phase 9.1 smoke tests keep working+ # without a machine. Phase 9.5 additionally attaches the+ # effectsBridge if ``effects_bridge`` is set.self._channel: Optional[QWebChannel] = Noneself._bridge: Optional[StateBridge] = Noneif state_machine is not None:@@ -229,14 +230,14 @@ class EdgeGlowWindow(QWidget):self._channel.registerObject("effectsBridge", effects_bridge)page.setWebChannel(self._channel)- # HTML laden — wenn nicht vorhanden: about:blank + Warnung.+ # Load HTML — if it doesn't exist: about:blank + warning.if self._html_path.is_file():url = QUrl.fromLocalFile(str(self._html_path))self._view.setUrl(url)else:logger.warning(- "edge-glow.html nicht gefunden unter %s — "- "rendere about:blank (vergiss `npm run build` im overlay-ui/?)",+ "edge-glow.html not found at %s — "+ "rendering about:blank (did you forget `npm run build` in overlay-ui/?)",self._html_path,)self._view.setUrl(QUrl("about:blank"))@@ -244,18 +245,18 @@ class EdgeGlowWindow(QWidget):layout.addWidget(self._view)def showEvent(self, event) -> None: # type: ignore[override]- """Setzt Win32-Affinity nachdem das HWND existiert."""+ """Sets the Win32 affinity after the HWND exists."""super().showEvent(event)hwnd = int(self.winId())- # Defense-in-Depth: Qt setzt WS_EX_TRANSPARENT durch- # WindowTransparentForInput — wir setzen es nochmal explizit, falls- # ein spaeterer setWindowFlags-Call das Bit clearen sollte.+ # Defense-in-depth: Qt sets WS_EX_TRANSPARENT via+ # WindowTransparentForInput — we set it again explicitly in case+ # a later setWindowFlags() call clears the bit.apply_click_through(hwnd)if self._hide_from_capture:exclude_from_capture(hwnd)- # Plan §18.1 — bei screenChanged + DPI-Wechseln re-applien.- # Wir verbinden das Signal hier (nach winId() existiert), nicht- # in __init__, weil windowHandle() vor showEvent None sein kann.+ # Plan §18.1 — re-apply on screenChanged + DPI changes.+ # We connect the signal here (after winId() exists), not in+ # __init__, since windowHandle() can be None before showEvent.if not self._screen_change_connected:handle = self.windowHandle()if handle is not None:@@ -263,7 +264,7 @@ class EdgeGlowWindow(QWidget):self._screen_change_connected = Truedef _on_screen_changed(self, _screen) -> None:- """Reapply Affinity nach DPI-Wechsel oder Monitor-Hotplug.+ """Reapply affinity after a DPI change or monitor hotplug.Plan §18.1."""if not self._hide_from_capture:return@@ -274,8 +275,8 @@ class EdgeGlowWindow(QWidget):reapply_capture_affinity(hwnd)def set_view_visible(self, visible: bool) -> None:- """Plan §17.3 — Hide-on-5-min-Idle macht WebView IsVisible False- damit Chromium den View komplett pausiert."""+ """Plan §17.3 — hide-on-5-min-idle sets the WebView's IsVisible+ to False so Chromium fully pauses the view."""self._view.setVisible(visible)def closeEvent(self, event) -> None: # type: ignore[override]diff --git a/OS-Level/src/overlay/window_mascot.py b/OS-Level/src/overlay/window_mascot.pyindex 142d1e938b..4f05b4aa4b 100644--- a/OS-Level/src/overlay/window_mascot.py+++ b/OS-Level/src/overlay/window_mascot.py@@ -1,14 +1,14 @@-"""MascotWindow — separates transparentes Frameless-Window. Plan §12.2 + §13.+"""MascotWindow — separate transparent frameless window. Plan §12.2 + §13.-Im Gegensatz zum EdgeGlowWindow ist Mascot NICHT click-through. Es-faengt Drag (linke Maustaste) und Right-Click (Kontextmenu).-QtWebEngineView rendert die Mascot-HTML (Rive oder PNG-Fallback).+Unlike EdgeGlowWindow, the mascot is NOT click-through. It catches+drag (left mouse button) and right-click (context menu).+QtWebEngineView renders the mascot HTML (Rive or PNG fallback).-Hit-Testing per Plan §12.2: setMask(QRegion ellipse) damit transparente-Ecken der 160x160 Box klick-passthrough sind.+Hit-testing per Plan §12.2: setMask(QRegion ellipse) so the transparent+corners of the 160x160 box are click-passthrough.-Position-Persistence + Monitor-Recovery sind in mascot_position.py-ausgelagert; dieses Modul ist nur die Window-Mechanik.+Position persistence + monitor recovery live in mascot_position.py;+this module is only the window mechanics."""from __future__ import annotations@@ -50,19 +50,19 @@ if TYPE_CHECKING: # pragma: no coverlogger = logging.getLogger(__name__)-# Plan §22 — Vite-Build legt das HTML genau hier ab.+# Plan §22 — the Vite build places the HTML exactly here._MASCOT_HTML = (Path(__file__).resolve().parents[2] / "overlay-ui" / "dist" / "mascot.html")class MascotStateBridge(QObject):- """QWebChannel-Bridge fuer den Mascot. Plan §13.2 mappt- OverlayStates auf Rive-Inputs.+ """QWebChannel bridge for the mascot. Plan §13.2 maps+ OverlayStates to Rive inputs.- Wir feuern dieselbe stateChanged-Signatur wie StateBridge fuer den- EdgeGlow, sodass der Mascot-Renderer dieselbe Bridge-Mechanik- verwenden kann (typed Wrapper in bridge.ts).+ We fire the same stateChanged signature as StateBridge for the+ EdgeGlow, so the mascot renderer can use the same bridge mechanics+ (typed wrapper in bridge.ts)."""stateChanged = Signal(str, str, str) # old, new, reason@@ -93,21 +93,21 @@ class MascotStateBridge(QObject):class _TransparentWebPage(QWebEnginePage):- """Page mit transparentem Hintergrund. Identisch zur EdgeGlow-- Variante — Chromium rendert sonst weiss obwohl body transparent."""+ """Page with a transparent background. Identical to the EdgeGlow+ variant — otherwise Chromium renders white even though body is transparent."""def __init__(self, parent: Optional[QObject] = None) -> None:super().__init__(parent)self.setBackgroundColor(QColor(0, 0, 0, 0))-# Position-Save Callback Signatur: (MascotPosition) -> None.-# Caller (setup_mascot) injiziert eine save-to-toml Funktion.+# Position-save callback signature: (MascotPosition) -> None.+# The caller (setup_mascot) injects a save-to-toml function.PositionSaveCallback = Callable[[MascotPosition], None]class MascotWindow(QWidget):- """Single-instance frameless transparent Window. Plan §12.2.+ """Single-instance frameless transparent window. Plan §12.2.Lifecycle::@@ -119,11 +119,11 @@ class MascotWindow(QWidget):win.show()"""- # Wird gefired wenn der User per Right-Click "Hide for session" waehlt.+ # Fired when the user picks "Hide for session" via right-click.hideRequested = Signal()- # User-triggered "Move to default" — Caller berechnet neue Position.+ # User-triggered "Move to default" — the caller computes the new position.resetRequested = Signal()- # User-triggered "Settings..." — Caller oeffnet Settings-Dialog.+ # User-triggered "Settings..." — the caller opens the settings dialog.settingsRequested = Signal()# User double-clicked the mascot. Caller forwards this upstream as# a MascotEventEnvelope(kind="mute_toggle") so the main jarvis@@ -155,7 +155,7 @@ class MascotWindow(QWidget):self._on_position_saved = on_position_savedself._html_path = html_path or _MASCOT_HTML- # Plan §12.2: KEIN WindowTransparentForInput (Klicks erwartet).+ # Plan §12.2: NO WindowTransparentForInput (clicks are expected).self.setWindowFlags(Qt.WindowType.FramelessWindowHint| Qt.WindowType.WindowStaysOnTopHint@@ -165,16 +165,16 @@ class MascotWindow(QWidget):self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground, True)self.setAttribute(Qt.WidgetAttribute.WA_NoSystemBackground, True)self.setAttribute(Qt.WidgetAttribute.WA_ShowWithoutActivating, True)- # KEIN WA_TransparentForMouseEvents — Mascot fangt Maus-Input.+ # NO WA_TransparentForMouseEvents — the mascot catches mouse input.self.setFixedSize(size_px, size_px)- # Plan §12.2: setMask(QRegion ellipse) damit transparente Ecken- # nicht Klicks fangen. Re-applied in resizeEvent fuer Sicherheit.+ # Plan §12.2: setMask(QRegion ellipse) so the transparent corners+ # don't catch clicks. Re-applied in resizeEvent for safety.self.setMask(QRegion(QRect(0, 0, size_px, size_px), QRegion.RegionType.Ellipse))self.move(initial_x, initial_y)- # Layout + WebView fuer Rive/PNG.+ # Layout + WebView for Rive/PNG.layout = QVBoxLayout(self)layout.setContentsMargins(0, 0, 0, 0)self._view = QWebEngineView(self)@@ -182,7 +182,7 @@ class MascotWindow(QWidget):page = _TransparentWebPage(self._view)self._view.setPage(page)- # WebChannel + StateBridge wenn StateMachine geliefert wurde.+ # WebChannel + StateBridge if a StateMachine was supplied.self._channel: Optional[QWebChannel] = Noneself._bridge: Optional[MascotStateBridge] = Noneif state_machine is not None:@@ -195,14 +195,14 @@ class MascotWindow(QWidget):self._view.setUrl(QUrl.fromLocalFile(str(self._html_path)))else:logger.warning(- "mascot.html nicht gefunden unter %s — `npm run build` im overlay-ui/?",+ "mascot.html not found at %s — did you run `npm run build` in overlay-ui/?",self._html_path,)self._view.setUrl(QUrl("about:blank"))layout.addWidget(self._view)- # Drag-State.+ # Drag state.self._drag_offset: Optional[QPoint] = Noneself._dragging: bool = False# Local visual mute indicator — toggled on every doubleClick so the@@ -212,7 +212,7 @@ class MascotWindow(QWidget):self._muted_visual: bool = Falseself._opacity_normal: float = 1.0self._opacity_muted: float = 0.45- # Plan §18.1 — screenChanged-Hook wird in showEvent verbunden.+ # Plan §18.1 — the screenChanged hook is connected in showEvent.self._screen_change_connected: bool = False# --- Lifecycle / Win32-Affinity ---@@ -224,7 +224,7 @@ class MascotWindow(QWidget):apply_mascot_styles(hwnd)if self._hide_from_capture:exclude_from_capture(hwnd)- # Plan §18.1 — Reapply auf screenChanged.+ # Plan §18.1 — reapply on screenChanged.if not self._screen_change_connected:handle = self.windowHandle()if handle is not None:@@ -247,7 +247,7 @@ class MascotWindow(QWidget):def resizeEvent(self, event) -> None: # type: ignore[override]super().resizeEvent(event)- # Mask neu setzen falls jemand size_px aendert.+ # Re-apply the mask in case someone changes size_px.self.setMask(QRegion(QRect(0, 0, self.width(), self.height()),@@ -363,10 +363,10 @@ class MascotWindow(QWidget):# --- Position-Persistence ---def _finalize_drag(self) -> None:- """Snap-to-edge + Clamp + Persist. Plan §13.3 + §13.4."""+ """Snap-to-edge + clamp + persist. Plan §13.3 + §13.4."""from PySide6.QtGui import QGuiApplication- # Welcher Monitor enthaelt das Mascot jetzt?+ # Which monitor now contains the mascot?center = self.pos() + QPoint(self.width() // 2, self.height() // 2)screen = QGuiApplication.screenAt(center) or QGuiApplication.primaryScreen()if screen is None:@@ -375,8 +375,8 @@ class MascotWindow(QWidget):geo = screen.availableGeometry()monitor_geo = (geo.x(), geo.y(), geo.width(), geo.height())- # Snap zuerst — Snap kann das Mascot ueber die Kante schieben,- # daher danach clampen.+ # Snap first — snapping can push the mascot past the edge,+ # so clamp afterwards.snapped_x, snapped_y = snap_to_edges(self.x(),self.y(),@@ -393,7 +393,7 @@ class MascotWindow(QWidget):if (clamped_x, clamped_y) != (self.x(), self.y()):self.move(clamped_x, clamped_y)- # Relative zum work-area-Top-Left persistieren.+ # Persist relative to the work area's top-left.rel_x = clamped_x - geo.x()rel_y = clamped_y - geo.y()position = MascotPosition(diff --git a/board-backend/board_backend/__init__.py b/board-backend/board_backend/__init__.pyindex 2800a3b4df..a063e207df 100644--- a/board-backend/board_backend/__init__.py+++ b/board-backend/board_backend/__init__.py@@ -1,9 +1,9 @@"""Jarvis Board Federation Backend (Phase C).-Standalone FastAPI-Service. Speichert pro registrierter Identity (Ed25519--Pubkey) eingehende, signierte Stats-Pushes vom lokalen Jarvis. Kein Kontakt-mit Voice-Transcripts oder Tool-Inhalten — der Server erzwingt einen PII--Filter beim Sync-Endpoint.+Standalone FastAPI service. Stores, per registered identity (Ed25519+pubkey), incoming signed stats pushes from the local Jarvis. No contact+with voice transcripts or tool content — the server enforces a PII+filter at the sync endpoint."""__version__ = "0.1.0"diff --git a/board-backend/board_backend/auth.py b/board-backend/board_backend/auth.pyindex 7bc6aff688..0c5534c290 100644--- a/board-backend/board_backend/auth.py+++ b/board-backend/board_backend/auth.py@@ -1,17 +1,17 @@-"""Auth-Dependencies fuer das Backend.+"""Auth dependencies for the backend.-Drei Gates:+Three gates:-1. ``require_admin_token`` — fuer ``/identity/register``. Constant-time-Vergleich- gegen ``settings.admin_token``. Plus Rate-Limit (10/min/IP).-2. ``require_signed_request`` — fuer ``/sync``, ``/me``: prueft Pubkey ist- registriert, verifiziert Signatur, prueft Replay-Window.-3. PII-Filter: implizit via Pydantic-Schema ``extra='forbid'`` (Plan §C-Sec).+1. ``require_admin_token`` — for ``/identity/register``. Constant-time+ comparison against ``settings.admin_token``. Plus a rate limit (10/min/IP).+2. ``require_signed_request`` — for ``/sync``, ``/me``: checks that the+ pubkey is registered, verifies the signature, checks the replay window.+3. PII filter: implicit via the Pydantic schema ``extra='forbid'`` (Plan §C-Sec).-Die Sig-Verify-Reihenfolge ist:+The signature-verify order is:``schema-validate → pubkey-registered? → signature-valid? → ts within window?``-Schema und Pubkey-Lookup sind billig; die Crypto erst danach.+Schema and pubkey lookup are cheap; the crypto only runs after that."""from __future__ import annotations@@ -33,7 +33,7 @@ log = logging.getLogger(__name__)# -----------------------------------------------------------------------# Settings + RateLimit aus app.state ziehen+# Pull settings + rate limit from app.state# ----------------------------------------------------------------------def get_settings(request: Request) -> Settings:@@ -47,7 +47,7 @@ def get_session(request: Request):def get_register_rate_limiter(request: Request) -> RateLimiter:- """Lazy-init pro App-Instance."""+ """Lazy init per app instance."""rl = getattr(request.app.state, "register_rl", None)if rl is None:s: Settings = request.app.state.settings@@ -57,7 +57,7 @@ def get_register_rate_limiter(request: Request) -> RateLimiter:# -----------------------------------------------------------------------# Admin-Token-Gate+# Admin token gate# ----------------------------------------------------------------------def require_admin_token(@@ -66,7 +66,7 @@ def require_admin_token(settings: Settings = Depends(get_settings),rl: RateLimiter = Depends(get_register_rate_limiter),) -> None:- """Constant-time-Vergleich + Rate-Limit pro Client-IP."""+ """Constant-time comparison + rate limit per client IP."""client_ip = (request.client.host if request.client else "unknown")if not rl.allow(client_ip):raise HTTPException(@@ -75,19 +75,19 @@ def require_admin_token()expected = settings.admin_tokenif not expected or not hmac.compare_digest(x_admin_token, expected):- # Konsistent 401 — keine Side-Channel-Information ueber Token-Laenge.+ # Consistent 401 — no side-channel information about token length.raise HTTPException(status_code=401, detail="invalid admin token")# -----------------------------------------------------------------------# Signed-Request-Gate+# Signed-request gate# ----------------------------------------------------------------------class SignedAuth:- """Container, den signed Routes per ``Depends`` bekommen.+ """Container that signed routes receive via ``Depends``.- Liefert die geparsten Daten + die ``Identity`` aus der DB. Routes- arbeiten dann auf ``auth.identity`` und ``auth.payload``.+ Provides the parsed data + the ``Identity`` from the DB. Routes+ then work on ``auth.identity`` and ``auth.payload``."""def __init__(self, *, identity: Identity, payload: dict, body_bytes: bytes) -> None:@@ -102,10 +102,11 @@ async def require_signed_request(x_jarvis_sig: str = Header(..., alias="X-Jarvis-Sig"),settings: Settings = Depends(get_settings),) -> SignedAuth:- """Signaturpruefung + Replay-Schutz.+ """Signature check + replay protection.- Liest den raw-body, parsed JSON, prueft Pubkey ist registriert,- verifiziert Sig, und vergleicht ``payload.ts_ms`` mit Server-Now.+ Reads the raw body, parses JSON, checks that the pubkey is+ registered, verifies the signature, and compares ``payload.ts_ms``+ to the server's current time."""body_bytes = await request.body()try:@@ -115,7 +116,7 @@ async def require_signed_request(if not isinstance(payload, dict):raise HTTPException(status_code=400, detail="payload must be a JSON object")- # 1. Pubkey muss registriert sein+ # 1. Pubkey must be registeredfactory = request.app.state.session_factorywith factory() as session:ident = session.get(Identity, x_pubkey)@@ -125,7 +126,7 @@ async def require_signed_request(# Detach so the dep-result can be used outside the session blocksession.expunge(ident)- # 2. Signatur-Verify+ # 2. Signature verifyif not verify_with_recanonicalize(pubkey_hex=x_pubkey,signature_hex=x_jarvis_sig,@@ -133,7 +134,7 @@ async def require_signed_request():raise HTTPException(status_code=401, detail="invalid signature")- # 3. Replay-Schutz+ # 3. Replay protectionts_ms = payload.get("ts_ms")if not isinstance(ts_ms, int):raise HTTPException(status_code=400, detail="payload.ts_ms missing")@@ -148,7 +149,7 @@ async def require_signed_request(return SignedAuth(identity=ident, payload=payload, body_bytes=body_bytes)-# Re-export fuer routes-Module+# Re-export for the routes module__all__ = ["SignedAuth","get_settings",@@ -159,20 +160,20 @@ __all__ = [def get_db(request: Request) -> Session:- """Convenience: session-per-call (nicht via FastAPI-yield-Dep, weil wir- sie in den Routes oft nur fuer eine kurze Transaktion brauchen).+ """Convenience: session-per-call (not via a FastAPI yield-dep, since+ routes often only need it for a short transaction)."""factory = request.app.state.session_factoryreturn factory()def get_owner_identity(session: Session) -> Identity:- """Liefert die einzige ``Identity``-Row dieses Backends.+ """Returns this backend's single ``Identity`` row.- Phase-C-Decision-2: Single-Tenant. Wenn keine oder mehrere Rows- existieren, raisen wir 503 — der Container ist dann fehl-konfiguriert.+ Phase-C-Decision-2: single-tenant. If there are zero or multiple+ rows, we raise 503 — the container is then misconfigured."""- from sqlalchemy import select # local import — vermeidet Zyklus+ from sqlalchemy import select # local import — avoids a cyclerows = session.execute(select(Identity)).scalars().all()if not rows:raise HTTPException(status_code=503, detail="no identity registered yet")@@ -182,18 +183,18 @@ def get_owner_identity(session: Session) -> Identity:# -----------------------------------------------------------------------# Federation-Variant: signed but pubkey is NOT in identity-Table+# Federation variant: signed but pubkey is NOT in the identity table# (a friend's backend talking to us, NOT our own client)# ----------------------------------------------------------------------class FederationAuth:- """Container fuer signed inbound Federation-Requests.+ """Container for signed inbound federation requests.- Anders als ``SignedAuth`` lookuped diese Variant den Pubkey NICHT in- der Identity-Tabelle — der Caller ist ein Friend-Backend, das einen- eigenen Pubkey hat. Wir verifizieren nur Sig + Replay-Window. Wer- der Caller wirklich ist, bestimmt der Endpoint anhand der ``friends``-- Tabelle (z.B. „nur friends duerfen dem feed pullen").+ Unlike ``SignedAuth``, this variant does NOT look up the pubkey in+ the identity table — the caller is a friend's backend that has its+ own pubkey. We only verify the signature + replay window. Who the+ caller really is is decided by the endpoint based on the ``friends``+ table (e.g. "only friends may pull the feed")."""def __init__(self, *, viewer_pubkey: str, payload: dict, body_bytes: bytes) -> None:@@ -208,11 +209,11 @@ async def require_federation_signed(x_jarvis_sig: str = Header(..., alias="X-Jarvis-Sig"),settings: Settings = Depends(get_settings),) -> FederationAuth:- """Wie ``require_signed_request``, aber **ohne** Identity-Pflicht.+ """Like ``require_signed_request``, but **without** an identity requirement.- Eingesetzt fuer ``/federation/feed``, ``/federation/reactions/inbound``,- ``/federation/identity/{pubkey}`` DELETE — alles Calls von Friend-- Backends, deren Pubkey wir gar nicht selbst registriert haben.+ Used for ``/federation/feed``, ``/federation/reactions/inbound``,+ ``/federation/identity/{pubkey}`` DELETE — all calls from friend+ backends whose pubkey we never registered ourselves."""body_bytes = await request.body()try:@@ -222,7 +223,7 @@ async def require_federation_signed(if not isinstance(payload, dict):raise HTTPException(status_code=400, detail="payload must be a JSON object")- # Pubkey-Format pruefen (Sig-Verify wuerde sonst mit ValueError sterben).+ # Check the pubkey format (otherwise sig-verify would die with a ValueError).if len(x_pubkey) != 64 or not all(c in "0123456789abcdef" for c in x_pubkey.lower()):raise HTTPException(status_code=401, detail="invalid pubkey format")diff --git a/board-backend/board_backend/background.py b/board-backend/board_backend/background.pyindex bae0468feb..077aa7bdf5 100644--- a/board-backend/board_backend/background.py+++ b/board-backend/board_backend/background.py@@ -1,12 +1,12 @@-"""Background-Tasks im Backend (Phase D).+"""Background tasks in the backend (Phase D).-- ``StoriesCleanup`` — nightly job, loescht ``activity_items`` mit- abgelaufener ``expires_at``.-- ``FederationPuller`` — pollt jede Friend-URL ihrem konfigurierten- Intervall nach (Default 120 s, per-Friend ueberschreibbar).+- ``StoriesCleanup`` — nightly job that deletes ``activity_items`` with+ an expired ``expires_at``.+- ``FederationPuller`` — polls each friend URL at its configured+ interval (default 120 s, overridable per friend).-Beide laufen als ``asyncio.Task``, attached an die FastAPI-App via-``startup``/``shutdown``-Lifespan.+Both run as an ``asyncio.Task``, attached to the FastAPI app via the+``startup``/``shutdown`` lifespan."""from __future__ import annotations@@ -24,15 +24,15 @@ log = logging.getLogger(__name__)# -----------------------------------------------------------------------# Stories-Cleanup+# Stories cleanup# ----------------------------------------------------------------------class StoriesCleanup:- """Loescht abgelaufene ``activity_items`` (typ. Stories nach 24 h).+ """Deletes expired ``activity_items`` (typically stories after 24 h).- Tickt alle ``interval_s`` (Default 1 h). Plan §D nennt „nightly" — das- ist ungefaehr; ein 1h-Tick toleriert App-Restarts und gibt schnellere- Cleanup-Garantie ohne signifikanten DB-Cost.+ Ticks every ``interval_s`` (default 1 h). Plan §D calls this+ "nightly" — that's approximate; a 1 h tick tolerates app restarts+ and gives a faster cleanup guarantee without a significant DB cost."""def __init__(self, *, session_factory, interval_s: float = 3600.0) -> None:@@ -55,7 +55,7 @@ class StoriesCleanup:self._task = Noneasync def _loop(self) -> None:- # Erster Run sofort, danach Intervall.+ # First run immediately, then at the interval.while True:try:self.run_once()@@ -69,7 +69,7 @@ class StoriesCleanup:raisedef run_once(self) -> int:- """Synchron + idempotent. Returns count gelöschter Items."""+ """Synchronous + idempotent. Returns the count of deleted items."""now = datetime.now(timezone.utc)with self._sf() as session:expired = session.query(ActivityItem).filter(@@ -83,18 +83,18 @@ class StoriesCleanup:# -----------------------------------------------------------------------# Federation-Puller+# Federation puller# ----------------------------------------------------------------------class FederationPuller:- """Polled jede Friend-URL gemaess ``Friend.pull_interval_s``.+ """Polls each friend URL per ``Friend.pull_interval_s``.- Pro Friend ein eigener ``asyncio.Task`` — wenn ein Friend offline ist,- blockiert er die anderen nicht.+ One ``asyncio.Task`` per friend — if a friend is offline, it doesn't+ block the others.- Aktuell: pullt nur den Feed (``/api/v1/federation/feed``) und persistiert- NICHT — der Output dient dem UI, nicht der DB. Phase E koennte einen- Cache-Layer dazwischen schalten.+ Currently: only pulls the feed (``/api/v1/federation/feed``) and does+ NOT persist it — the output serves the UI, not the DB. Phase E could+ insert a cache layer in between."""def __init__(self, *, session_factory, http_client: httpx.AsyncClient | None = None) -> None:@@ -107,7 +107,7 @@ class FederationPuller:async def start(self) -> None:if self._http is None:self._http = httpx.AsyncClient(timeout=10.0)- # Alle aktiven Friends pollen.+ # Poll all active friends.with self._sf() as session:friends = session.query(Friend).all()for f in friends:@@ -153,12 +153,12 @@ class FederationPuller:raiseasync def _pull_once(self, friend_url: str) -> list[Any]:- """Anonymer Pull — der Feed selbst filtert visibility=public.+ """Anonymous pull — the feed itself filters visibility=public.- Fuer einen authenticated friend-Pull braeuchten wir den lokalen- Privkey + Pubkey, die das Backend nicht hat (siehe Reactions-Note).- Phase D-MVP: nur public items. Phase D-Vollausbau: lokales Jarvis- liefert dem Backend einen scoped Auth-Header pro Friend.+ For an authenticated friend pull we'd need the local privkey ++ pubkey, which the backend doesn't have (see the reactions note).+ Phase D MVP: public items only. Phase D full build-out: the local+ Jarvis supplies the backend a scoped auth header per friend."""assert self._http is not Noneresp = await self._http.get(f"{friend_url.rstrip('/')}/api/v1/federation/feed",diff --git a/board-backend/board_backend/config.py b/board-backend/board_backend/config.pyindex d5a2c426bd..98190d9356 100644--- a/board-backend/board_backend/config.py+++ b/board-backend/board_backend/config.py@@ -1,8 +1,8 @@-"""Backend-Settings via Environment.+"""Backend settings via environment.-Designprinzip: keine Defaults fuer sicherheitsrelevante Werte (``ADMIN_TOKEN``).-Wenn er fehlt, faellt das Backend beim Startup ueber. Lieber lautstark als-heimlich „leer".+Design principle: no defaults for security-relevant values (``ADMIN_TOKEN``).+If it's missing, the backend fails at startup. Better loud than silently+"empty"."""from __future__ import annotations@@ -13,7 +13,7 @@ from pydantic_settings import BaseSettings, SettingsConfigDictclass Settings(BaseSettings):- """Aus ENV-Variablen geladen (oder ``board-backend/.env``)."""+ """Loaded from ENV variables (or ``board-backend/.env``)."""model_config = SettingsConfigDict(env_prefix="JARVIS_BOARD_",@@ -24,29 +24,29 @@ class Settings(BaseSettings):admin_token: str = Field(default="",- description="Token fuer /api/v1/identity/register. Pflicht zum Start.",+ description="Token for /api/v1/identity/register. Required at startup.",)db_path: Path = Field(default=Path("/data/board.db"),- description="SQLite-DB-Path. Container-Default ist /data/board.db, "- "lokal in Tests via tmp_path ueberschrieben.",+ description="SQLite DB path. The container default is /data/board.db, "+ "overridden locally in tests via tmp_path.",)register_rate_limit_per_minute: int = Field(default=10,- description="Max Requests pro IP pro Minute auf /identity/register.",+ description="Max requests per IP per minute on /identity/register.",)replay_window_seconds: int = Field(default=300,- description="Max Alter eines signed payloads (5 min, Plan §C-Sec).",+ description="Max age of a signed payload (5 min, Plan §C-Sec).",)- bind_host: str = "0.0.0.0" # noqa: S104 — Container-Bind, hinter Reverse-Proxy+ bind_host: str = "0.0.0.0" # noqa: S104 — container bind, behind a reverse proxybind_port: int = 8765def require_admin_token(self) -> str:if not self.admin_token:raise RuntimeError(- "JARVIS_BOARD_ADMIN_TOKEN ist nicht gesetzt — Backend-Start "- "verweigert. Entweder im docker-compose.yml unter `environment:` "- "setzen oder beim Test ueber den Settings-Override injecten.",+ "JARVIS_BOARD_ADMIN_TOKEN is not set — backend startup "+ "refused. Either set it in docker-compose.yml under `environment:` "+ "or inject it via the settings override in tests.",)return self.admin_tokendiff --git a/board-backend/board_backend/crypto.py b/board-backend/board_backend/crypto.pyindex 794ded5465..e5c60d1f67 100644--- a/board-backend/board_backend/crypto.py+++ b/board-backend/board_backend/crypto.py@@ -1,16 +1,16 @@-"""Ed25519-Crypto + Canonical-JSON.+"""Ed25519 crypto + canonical JSON.Pattern:-- Client kanonisiert ``payload_dict`` zu Bytes via ``canonical_json``.-- Client signiert die Bytes mit seinem Privkey, sendet ``X-Pubkey`` (hex)- + ``X-Jarvis-Sig`` (hex) als Header und das **rohe** JSON als Body.-- Server liest den raw-Body, kanonisiert nochmal (Schutz gegen- Whitespace-Differenzen) und prueft die Signatur.--Die Re-Kanonisierung auf Server-Seite ist wichtig: HTTP-Frameworks-duerfen den raw-body nicht modifizieren, aber Reverse-Proxies (Caddy,-nginx) tun's manchmal an Whitespace. Mit ``canonical_json`` auf beiden-Seiten ist die Signatur unter Whitespace-Veraenderungen stabil.+- The client canonicalizes ``payload_dict`` to bytes via ``canonical_json``.+- The client signs the bytes with its privkey, sends ``X-Pubkey`` (hex)+ + ``X-Jarvis-Sig`` (hex) as headers and the **raw** JSON as the body.+- The server reads the raw body, re-canonicalizes it (protection against+ whitespace differences), and checks the signature.++Re-canonicalizing on the server side matters: HTTP frameworks aren't+supposed to modify the raw body, but reverse proxies (Caddy, nginx)+sometimes touch whitespace. With ``canonical_json`` on both sides, the+signature stays stable across whitespace changes."""from __future__ import annotations@@ -22,35 +22,35 @@ from nacl.signing import SigningKey, VerifyKeydef canonical_json(payload: Any) -> bytes:- """Deterministische, signatur-freundliche JSON-Serialisierung.+ """Deterministic, signature-friendly JSON serialization.- - sortierte Keys auf jeder Ebene- - keine ueberfluessigen Whitespaces- - UTF-8, kein ASCII-Escape (Sonderzeichen bleiben als UTF-8)+ - sorted keys at every level+ - no superfluous whitespace+ - UTF-8, no ASCII escaping (special characters stay as UTF-8)"""return json.dumps(payload, sort_keys=True, separators=(",", ":"),ensure_ascii=False).encode("utf-8")def generate_keypair() -> tuple[str, str]:- """Erzeugt ein neues Ed25519-Paar.+ """Generates a new Ed25519 keypair.Returns-------(privkey_hex, pubkey_hex)- Beide 64 Zeichen hex (32 Bytes raw).+ Both 64 hex characters (32 raw bytes)."""sk = SigningKey.generate()return sk.encode().hex(), sk.verify_key.encode().hex()def sign(payload: Any, *, privkey_hex: str) -> str:- """Signiert ``payload`` (dict oder bereits-encoded bytes).+ """Signs ``payload`` (dict or already-encoded bytes).Returns-------str- 128-Zeichen Hex (64 Bytes raw signature).+ 128 hex characters (64 raw signature bytes)."""sk = SigningKey(bytes.fromhex(privkey_hex))body = payload if isinstance(payload, (bytes, bytearray)) else canonical_json(payload)@@ -64,11 +64,12 @@ def verify(signature_hex: str,body: bytes,) -> bool:- """Prueft ``body`` gegen ``signature_hex`` mit ``pubkey_hex``.+ """Checks ``body`` against ``signature_hex`` using ``pubkey_hex``.- ``body`` ist der raw HTTP-Body (Bytes). Caller koennen vor dem Aufruf- optional via ``re_canonicalize=True`` re-kanonisieren — das machen- wir hier nicht automatisch, weil ``body`` schon canonical sein sollte.+ ``body`` is the raw HTTP body (bytes). Callers can optionally+ re-canonicalize before calling this via ``re_canonicalize=True`` —+ we don't do that automatically here, since ``body`` should already+ be canonical."""try:vk = VerifyKey(bytes.fromhex(pubkey_hex))@@ -84,17 +85,16 @@ def verify_with_recanonicalize(signature_hex: str,parsed_payload: Any,) -> bool:- """Verify-Variante, die den geparsten Payload re-kanonisiert.+ """Verify variant that re-canonicalizes the parsed payload.- Sicherer Default fuer den HTTP-Pfad: wir muessen den Body sowieso- parsen, um Schema-Validation und Replay-Check zu machen — und der- Re-Canonicalize-Schritt isoliert uns gegen Body-Manipulation durch- Reverse-Proxies (LF/CRLF, trailing whitespace etc.).+ The safe default for the HTTP path: we have to parse the body+ anyway to do schema validation and the replay check — and the+ re-canonicalize step isolates us from body manipulation by+ reverse proxies (LF/CRLF, trailing whitespace, etc.).- WICHTIG: Eine Tampering-Attacke, die nach dem Signieren ein Feld- aendert, wird trotzdem erkannt — der re-kanonisierte Payload hat- dann andere Bytes als beim Signieren, und die Signatur stimmt nicht- mehr.+ IMPORTANT: a tampering attack that changes a field after signing is+ still detected — the re-canonicalized payload then has different+ bytes than at signing time, and the signature no longer matches."""body = canonical_json(parsed_payload)return verify(pubkey_hex=pubkey_hex, signature_hex=signature_hex, body=body)diff --git a/board-backend/board_backend/db.py b/board-backend/board_backend/db.pyindex bdf2e8f36f..37dc5390c1 100644--- a/board-backend/board_backend/db.py+++ b/board-backend/board_backend/db.py@@ -1,8 +1,8 @@-"""SQLAlchemy-Engine + Session-Factory.+"""SQLAlchemy engine + session factory.-Synchron, weil das Backend mit ein paar Hundert Pushes pro Tag laeuft —-async-SQLAlchemy waere Overkill, und die Hot-Path-Queries sind alle-indexed. WAL-Modus fuer concurrent Reader.+Synchronous, because the backend runs with a few hundred pushes per+day — async SQLAlchemy would be overkill, and the hot-path queries are+all indexed. WAL mode for concurrent readers."""from __future__ import annotations@@ -16,8 +16,8 @@ from .config import Settingsdef make_engine(settings: Settings):- """Baut die SQLAlchemy-Engine. Eigene Funktion, damit Tests sie ohne- File-Side-Effect ueberschreiben koennen (in-memory ``sqlite:///:memory:``).+ """Builds the SQLAlchemy engine. A dedicated function so tests can+ override it without a file side effect (in-memory ``sqlite:///:memory:``)."""settings.db_path.parent.mkdir(parents=True, exist_ok=True)url = f"sqlite:///{settings.db_path}"@@ -45,7 +45,7 @@ def make_session_factory(engine) -> sessionmaker[Session]: # noqa: ANN001def session_dep(session_factory: sessionmaker[Session]):- """FastAPI-Dependency-Factory. Liefert eine kurzlebige Session pro Request."""+ """FastAPI dependency factory. Provides a short-lived session per request."""def _dep() -> Iterator[Session]:with session_factory() as session:yield session@@ -53,6 +53,6 @@ def session_dep(session_factory: sessionmaker[Session]):def init_schema(engine) -> None: # noqa: ANN001- """Schema additiv aufbauen. Kein Alembic — additive ``create_all`` reicht."""+ """Build the schema additively. No Alembic — an additive ``create_all`` is enough."""from . import models # noqa: F401 (registers tables on Base)models.Base.metadata.create_all(bind=engine)diff --git a/board-backend/board_backend/main.py b/board-backend/board_backend/main.pyindex c441aa5f7b..7bc01a488c 100644--- a/board-backend/board_backend/main.py+++ b/board-backend/board_backend/main.py@@ -1,7 +1,7 @@-"""FastAPI-App-Factory.+"""FastAPI app factory.-Wird vom Uvicorn-CLI als ``board_backend.main:app`` referenziert. Tests-benutzen stattdessen ``create_app(settings=...)`` mit injizierten Settings.+Referenced by the Uvicorn CLI as ``board_backend.main:app``. Tests use+``create_app(settings=...)`` with injected settings instead."""from __future__ import annotations@@ -19,17 +19,16 @@ log = logging.getLogger(__name__)def create_app(settings: Settings | None = None) -> FastAPI:- """Baut eine FastAPI-Instanz.+ """Builds a FastAPI instance.- ``settings`` kann fuer Tests ueberschrieben werden. Wenn None: aus- der Environment laden. Routes werden lazy importiert, damit Test-- Setups die Settings erstmal anzeigen koennen, ohne dass Module-- Level-Code DB anlegt.+ ``settings`` can be overridden for tests. If None: loaded from the+ environment. Routes are imported lazily so test setups can inspect+ the settings first, without module-level code creating the DB."""if settings is None:settings = Settings()- settings.require_admin_token() # frueher Tod statt later quirk+ settings.require_admin_token() # fail fast instead of a later quirkengine = make_engine(settings)init_schema(engine)@@ -52,10 +51,10 @@ def create_app(settings: Settings | None = None) -> FastAPI:def _attach_background(app: FastAPI) -> None:- """Stories-Cleanup + FederationPuller als asyncio-Tasks via Lifespan.+ """StoriesCleanup + FederationPuller as asyncio tasks via the lifespan.- Tests koennen das ueberspringen indem sie ``app.state.disable_background = True``- setzen — der Hook checkt das ein.+ Tests can skip this by setting ``app.state.disable_background = True``+ — the hook checks for that."""from .background import FederationPuller, StoriesCleanup@@ -82,7 +81,7 @@ def _attach_background(app: FastAPI) -> None:def _attach_routes(app: FastAPI) -> None:- """Lazy-Import-Pfad — vermeidet Zyklen + erlaubt Skeleton-only-Tests."""+ """Lazy import path — avoids cycles + allows skeleton-only tests."""from .routes import (activity as activity_route,forget_me as forget_me_route,@@ -108,7 +107,7 @@ def _attach_routes(app: FastAPI) -> None:def _attach_error_handlers(app: FastAPI) -> None:- """Default-Handler fuer alle Exceptions — niemals Stacktrace zum Client."""+ """Default handler for all exceptions — never a stacktrace to the client."""@app.exception_handler(Exception)async def _unhandled(request, exc: Exception): # noqa: ANN001log.exception("unhandled error", exc_info=exc)@@ -118,12 +117,12 @@ def _attach_error_handlers(app: FastAPI) -> None:)-# Modul-Level-App fuer ``uvicorn board_backend.main:app``.+# Module-level app for ``uvicorn board_backend.main:app``.#-# ASGI-Lazy: wenn ADMIN_TOKEN beim Import noch nicht gesetzt ist (z.B. in-# Tests, die ``create_app(settings=...)`` direkt aufrufen), bauen wir die-# App nicht. Im produktiven Container setzt docker-compose den Token via-# Environment, dann laeuft der Import mit App durch.+# ASGI-lazy: if ADMIN_TOKEN isn't set yet at import time (e.g. in tests+# that call ``create_app(settings=...)`` directly), we don't build the+# app. In the production container, docker-compose sets the token via+# the environment, and the import then succeeds with an app.app: FastAPI | Nonetry:app = create_app()diff --git a/board-backend/board_backend/models.py b/board-backend/board_backend/models.pyindex e41bb16674..4c8db62b29 100644--- a/board-backend/board_backend/models.py+++ b/board-backend/board_backend/models.py@@ -1,9 +1,9 @@-"""SQLAlchemy-Models.+"""SQLAlchemy models.Phase C: Identity + PushLog.Phase D: Friend + PairToken + ActivityItem + Reaction.-Schema bleibt additiv via ``create_all`` — keine Migration noetig.+The schema stays additive via ``create_all`` — no migration needed."""from __future__ import annotations@@ -30,11 +30,11 @@ def _utc_now() -> datetime:class Identity(Base):- """Eine registrierte Jarvis-Instanz (User).+ """A registered Jarvis instance (user).- ``pubkey`` ist der einzige Identitaets-Anker (Plan §C-Decision-2: Pubkey-- only). Der ``display_name`` darf sich pro Push aendern — er wird- deshalb auch hier geupdatet und ist nicht der Primary Key.+ ``pubkey`` is the only identity anchor (Plan §C-Decision-2: pubkey+ only). The ``display_name`` may change per push — that's why it's+ updated here too and is not the primary key."""__tablename__ = "identity"@@ -47,12 +47,12 @@ class Identity(Base):class PushLog(Base):- """Audit-Log eines erfolgreichen Sync-Calls.+ """Audit log of a successful sync call.- Wir speichern bewusst NUR Metadaten (welcher Pubkey, wann, wie viele- Tage / Achievements im Payload), nicht den Payload selbst. Phase D wird- den Payload in `friends_activity` umsortieren — bis dahin ist der- Sync-Inhalt nur ein Acknowledge.+ We deliberately store ONLY metadata (which pubkey, when, how many+ days / achievements in the payload), not the payload itself. Phase D+ will re-sort the payload into `friends_activity` — until then the+ sync content is just an acknowledge."""__tablename__ = "push_log"@@ -73,12 +73,12 @@ Index("ix_pushlog_pubkey_received", PushLog.pubkey, PushLog.received_at)# ----------------------------------------------------------------------class Friend(Base):- """Freundschaftsverbindung des Owners zu einem anderen Backend.+ """The owner's friendship link to another backend.- Single-Tenant-Modell (siehe Plan §C-Decision-2): es gibt **eine**- Identity pro Backend, ``owner_pubkey`` ist also derselbe fuer alle- ``Friend``-Rows. Wir speichern ihn trotzdem explizit, damit das Schema- in der Zukunft skalierbar ist.+ Single-tenant model (see Plan §C-Decision-2): there is **one**+ identity per backend, so ``owner_pubkey`` is the same for all+ ``Friend`` rows. We still store it explicitly so the schema stays+ scalable in the future."""__tablename__ = "friends"@@ -96,10 +96,10 @@ class Friend(Base):class PairToken(Base):- """Time-limited Pair-Token. Plan §D-Decision-1: 10 min Gueltigkeit.+ """Time-limited pair token. Plan §D-Decision-1: 10 min validity.- Einmal-Verwendung: ``used_at`` wird beim Accept gesetzt, ein zweiter- Accept mit demselben Token failed mit 401.+ Single use: ``used_at`` is set on accept, a second accept with the+ same token fails with 401."""__tablename__ = "pair_tokens"@@ -114,15 +114,15 @@ class PairToken(Base):class ActivityItem(Base):- """Eine Aktivitaet auf dem Owner-Board: achievement_unlocked, story, …+ """An activity on the owner's board: achievement_unlocked, story, …- ``visibility`` ist die Plan-§D-Sichtbarkeitsachse: ``private`` (nur- Owner), ``friends`` (paired Friends), ``public`` (jeder).+ ``visibility`` is the Plan-§D visibility axis: ``private`` (owner+ only), ``friends`` (paired friends), ``public`` (everyone).- ``payload`` ist ein JSON-String mit kind-spezifischem Inhalt — z.B.- ``{"achievement_id": "tool_master"}`` oder ``{"text": "what I worked on"}``.+ ``payload`` is a JSON string with kind-specific content — e.g.+ ``{"achievement_id": "tool_master"}`` or ``{"text": "what I worked on"}``.- ``expires_at`` ist nur fuer Stories gesetzt (24 h, Plan §D).+ ``expires_at`` is only set for stories (24 h, Plan §D)."""__tablename__ = "activity_items"@@ -142,11 +142,11 @@ Index("ix_activity_visibility_created", ActivityItem.visibility, ActivityItem.crclass Reaction(Base):- """Reaktion auf einen Activity-Item.+ """A reaction to an activity item.- Plan §D §0: Owner sieht eigene Reaction-Counts mit Zahl, andere User- sehen nur die Reaction-Icons. Die Tabelle speichert die Rohdaten —- die Visibility-Logik passiert beim Query.+ Plan §D §0: the owner sees their own reaction counts as a number,+ other users only see the reaction icons. The table stores the raw+ data — the visibility logic happens at query time."""__tablename__ = "reactions"diff --git a/board-backend/board_backend/rate_limit.py b/board-backend/board_backend/rate_limit.pyindex 8d07da5a1c..158784f2fa 100644--- a/board-backend/board_backend/rate_limit.py+++ b/board-backend/board_backend/rate_limit.py@@ -1,12 +1,12 @@-"""Sehr kleiner In-Memory-Rate-Limiter.+"""A very small in-memory rate limiter.-Einfaches Sliding-Window — pro IP halten wir eine Liste der letzten-``timestamps`` und droppen alle ausserhalb des Fensters. Das reicht fuer-die einzige rate-limited Route (``/identity/register``), die ein paar-Requests pro Minute sehen wird.+Simple sliding window — per IP we keep a list of the last+``timestamps`` and drop everything outside the window. That's enough+for the only rate-limited route (``/identity/register``), which will+see a handful of requests per minute.-Fuer ein Multi-Worker-Deployment muesste das auf Redis o.ae. wandern;-fuer einen Single-Worker-Container ist In-Memory korrekt.+For a multi-worker deployment this would need to move to Redis or+similar; for a single-worker container, in-memory is correct."""from __future__ import annotations@@ -22,7 +22,7 @@ class RateLimiter:self._lock = threading.Lock()def allow(self, key: str) -> bool:- """``True`` wenn der Request jetzt durch darf, sonst ``False``."""+ """``True`` if the request may pass now, ``False`` otherwise."""now = time.monotonic()cutoff = now - 60.0with self._lock:diff --git a/board-backend/board_backend/routes/activity.py b/board-backend/board_backend/routes/activity.pyindex 03c3d0d29d..aba4261094 100644--- a/board-backend/board_backend/routes/activity.py+++ b/board-backend/board_backend/routes/activity.py@@ -1,15 +1,15 @@-"""Activity-Routes (Phase D).--- ``POST /api/v1/activities`` (signed by owner) — Owner erstellt eine neue- Activity-Item (Achievement, Story, Milestone) mit Visibility.-- ``GET /api/v1/activities`` (signed by owner) — Owner sieht eigene- Items inkl. Reaction-Counts.-- ``GET /api/v1/federation/feed`` (signed by viewer) — friend ODER- anonymer Caller pullt das Owner-Board. Visibility-Filter im SQL.--Reaction-Visibility (Plan §D §0):-- Owner sieht ``reaction_counts: {rocket: 3, brain: 1, fire: 0}``.-- Andere sehen ``reaction_counts: null, has_reactions: true|false``.+"""Activity routes (Phase D).++- ``POST /api/v1/activities`` (signed by owner) — the owner creates a new+ activity item (achievement, story, milestone) with a visibility.+- ``GET /api/v1/activities`` (signed by owner) — the owner sees their own+ items including reaction counts.+- ``GET /api/v1/federation/feed`` (signed by viewer) — a friend OR an+ anonymous caller pulls the owner's board. Visibility filter in SQL.++Reaction visibility (Plan §D §0):+- The owner sees ``reaction_counts: {rocket: 3, brain: 1, fire: 0}``.+- Others see ``reaction_counts: null, has_reactions: true|false``."""from __future__ import annotations@@ -47,7 +47,7 @@ STORY_DEFAULT_HOURS = 24# -----------------------------------------------------------------------# Owner-Side: create + list+# Owner side: create + list# ----------------------------------------------------------------------@router.post("/activities", response_model=ActivityItemDTO)@@ -93,12 +93,12 @@ def create_story(request: Request,auth: SignedAuth = Depends(require_signed_request),) -> ActivityItemDTO:- """Plan §D-Spec: separate Route fuer Stories (24 h Lebensdauer)."""+ """Plan §D spec: a separate route for stories (24 h lifetime)."""try:body = StoryCreateRequest.model_validate(auth.payload)except Exception as exc: # noqa: BLE001raise HTTPException(status_code=422, detail=str(exc)) from exc- # Auf ActivityCreateRequest mappen — gleiche Logic, gleicher Pfad.+ # Map onto ActivityCreateRequest — same logic, same path.activity_payload = {"ts_ms": body.ts_ms,"kind": "story",@@ -106,7 +106,7 @@ def create_story("visibility": body.visibility,"expires_in_hours": 24,}- # Re-use create_activity-Logic durch direkten Call mit gepatchtem auth-payload.+ # Reuse the create_activity logic via a direct call with a patched auth payload.auth.payload = activity_payloadreturn create_activity(request, auth)@@ -135,7 +135,7 @@ def list_own_activities(# -----------------------------------------------------------------------# Federation-Side: GET feed+# Federation side: GET feed# ----------------------------------------------------------------------@fed_router.get("/feed", response_model=FeedResponse)@@ -143,18 +143,18 @@ def federation_feed(request: Request,sort: str = Query("interesting", pattern=r"^(interesting|latest)$"),since: str | None = Query(None, description="ISO-8601 timestamp (UTC). "- "Items mit created_at < since werden ausgefiltert."),+ "Items with created_at < since are filtered out."),auth=Depends(require_federation_signed),) -> FeedResponse:- """Liefert die Activity-Items des Owners, gefiltert nach Visibility.+ """Returns the owner's activity items, filtered by visibility.- - ``visibility=public`` -> immer sichtbar- - ``visibility=friends`` -> nur wenn ``viewer`` in ``friends``-Tabelle- - ``visibility=private`` -> nur wenn ``viewer == owner``+ - ``visibility=public`` -> always visible+ - ``visibility=friends`` -> only if ``viewer`` is in the ``friends`` table+ - ``visibility=private`` -> only if ``viewer == owner``- ``since`` (Plan §D-Spec): inkrementeller Pull. Friends speichern den- ``server_now`` ihres letzten Pulls und reichen ihn beim naechsten als- ``since`` rein, sodass der Backend nur die Diffs serialisieren muss.+ ``since`` (Plan §D spec): incremental pull. Friends store the+ ``server_now`` of their last pull and pass it in as ``since`` on the+ next one, so the backend only has to serialize the diffs."""since_dt = Noneif since is not None:@@ -170,7 +170,7 @@ def federation_feed(is_owner = (auth.viewer_pubkey == owner.pubkey)is_friend = is_owner or _is_friend(session, owner.pubkey, auth.viewer_pubkey)- # SQL-Filter — Plan §D ALGORITHM TRANSPARENT BY DESIGN+ # SQL filter — Plan §D ALGORITHM TRANSPARENT BY DESIGNclauses = [ActivityItem.visibility == "public"]if is_friend:clauses.append(ActivityItem.visibility == "friends")@@ -211,9 +211,9 @@ def interesting_score(reactions_total: int, age_hours: float) -> float:interesting = reactions * exp(-age_hours / 24)- Deterministisch, parameterlos, in einer einzigen Zeile berechnet. Das- halbe Lebensdauer-Window (24 h) ist hardcoded, sodass es kein Tunable- gibt, das via A/B-Test heimlich optimiert wird (Plan §0).+ Deterministic, parameterless, computed in a single line. The+ half-life window (24 h) is hardcoded, so there's no tunable that+ could be secretly optimized via A/B testing (Plan §0)."""return reactions_total * math.exp(-age_hours / 24.0)@@ -227,7 +227,7 @@ def _sort_items(items: list[ActivityItemDTO], sort: str) -> list[ActivityItemDTOdef _score(i: ActivityItemDTO) -> tuple[float, datetime]:age_h = max(0.0, (now - i.created_at).total_seconds() / 3600.0)total = sum((i.reaction_counts or {}).values())- # Tie-Break: created_at, damit Reihenfolge bei reactions=0 deterministisch ist.+ # Tie-break: created_at, so the order is deterministic when reactions=0.return (-interesting_score(total, age_h), -i.created_at.timestamp())return sorted(items, key=_score)diff --git a/board-backend/board_backend/routes/forget_me.py b/board-backend/board_backend/routes/forget_me.pyindex ef48eb000a..f2bb6a4719 100644--- a/board-backend/board_backend/routes/forget_me.py+++ b/board-backend/board_backend/routes/forget_me.py@@ -1,9 +1,9 @@"""Right-to-be-forgotten — DELETE /api/v1/federation/identity/{pubkey}.-GDPR-mässig: ein Friend signiert mit seinem Privkey einen DELETE-Request,-der seine eigene Identity (= seine Friendship-Spur + alle seine Reaktionen)-auf unserem Backend löscht. Activity-Items des Friends gibt es bei uns-gar nicht (er hostet die selbst), aber wir cleanen seine Reactions.+GDPR-style: a friend signs a DELETE request with their privkey, which+deletes their own identity (= their friendship trace + all their+reactions) on our backend. We don't have the friend's activity items+at all (they host those themselves), but we do clean up their reactions."""from __future__ import annotations@@ -25,10 +25,10 @@ def forget_me(auth: FederationAuth = Depends(require_federation_signed),request: Request = None,) -> ForgetMeAck:- """Friend selbst-loescht alle seine Spuren bei uns.+ """The friend self-deletes all their traces at our end.- Plan §D: signed by friend. ``pubkey`` im Path muss == ``viewer_pubkey``- aus der Sig sein, sonst 403.+ Plan §D: signed by friend. ``pubkey`` in the path must == ``viewer_pubkey``+ from the signature, otherwise 403."""if pubkey.lower() != auth.viewer_pubkey.lower():raise HTTPException(@@ -38,14 +38,14 @@ def forget_me(with get_db(request) as session:owner = get_owner_identity(session)- # Friendship loeschen+ # Delete the friendshipfriend_row = session.get(Friend, (owner.pubkey, pubkey))deleted_friendship = Falseif friend_row is not None:session.delete(friend_row)deleted_friendship = True- # Reactions des Reactors loeschen+ # Delete the reactor's reactionsreactions = session.query(Reaction).filter(Reaction.reactor_pubkey == pubkey).all()@@ -53,9 +53,9 @@ def forget_me(for r in reactions:session.delete(r)- # Activity-Items: wir hosten nur eigene Items, der friend hat hier- # keine Items (sein author_pubkey kommt im ActivityItem-Schema nicht- # als author vor, weil author == owner). Daher 0.+ # Activity items: we only host our own items, the friend has no+ # items here (their author_pubkey never shows up as author in the+ # ActivityItem schema, since author == owner). Hence 0.deleted_activities = 0session.commit()diff --git a/board-backend/board_backend/routes/health.py b/board-backend/board_backend/routes/health.pyindex cccc5bc3c9..cc9f9b2fb5 100644--- a/board-backend/board_backend/routes/health.py+++ b/board-backend/board_backend/routes/health.py@@ -1,6 +1,6 @@-"""``GET /healthz`` — public, kein Auth.+"""``GET /healthz`` — public, no auth.-Liefert nur Liveness/Schema-Status. Wird von Docker-Healthchecks gepollt.+Returns only liveness/schema status. Polled by Docker healthchecks."""from __future__ import annotationsdiff --git a/board-backend/board_backend/routes/identity.py b/board-backend/board_backend/routes/identity.pyindex 717bcb0cb4..dc7ad6a2df 100644--- a/board-backend/board_backend/routes/identity.py+++ b/board-backend/board_backend/routes/identity.py@@ -1,4 +1,4 @@-"""``POST /api/v1/identity/register`` — Admin-only Identitaets-Anlage."""+"""``POST /api/v1/identity/register`` — admin-only identity creation."""from __future__ import annotationsimport logging@@ -19,11 +19,11 @@ router = APIRouter(prefix="/api/v1/identity", tags=["identity"])dependencies=[Depends(require_admin_token)],)def register(request: Request, payload: RegisterRequest) -> RegisterResponse:- """Registriert einen neuen Pubkey beim Backend.+ """Registers a new pubkey with the backend.- Wenn der Pubkey schon existiert, aktualisieren wir lediglich den- ``display_name`` — kein 409, weil das Re-Pairing bei Geraete-Wechsel- eine sinnvolle Aktion ist und der Admin-Token ja vorhanden war.+ If the pubkey already exists, we simply update the ``display_name``+ — no 409, since re-pairing on a device change is a reasonable+ action and the admin token was present anyway."""with get_db(request) as session:ident = session.get(Identity, payload.pubkey)diff --git a/board-backend/board_backend/routes/me.py b/board-backend/board_backend/routes/me.pyindex 9d2b56adfe..c9abf44ee8 100644--- a/board-backend/board_backend/routes/me.py+++ b/board-backend/board_backend/routes/me.py@@ -1,4 +1,4 @@-"""``GET /api/v1/me`` — Eigene Identitaet + Sync-Statistiken."""+"""``GET /api/v1/me`` — own identity + sync statistics."""from __future__ import annotationsfrom fastapi import APIRouter, Depends, Request@@ -15,7 +15,7 @@ router = APIRouter(prefix="/api/v1", tags=["me"])def me(request: Request, auth: SignedAuth = Depends(require_signed_request)) -> MeResponse:with get_db(request) as session:ident = session.get(Identity, auth.identity.pubkey)- assert ident is not None # auth-dep hat das schon geprueft+ assert ident is not None # the auth dep already checked thispush_count = session.scalar(select(func.count(PushLog.id)).where(PushLog.pubkey == ident.pubkey),) or 0diff --git a/board-backend/board_backend/routes/pair.py b/board-backend/board_backend/routes/pair.pyindex fdc79b7525..f953780c34 100644--- a/board-backend/board_backend/routes/pair.py+++ b/board-backend/board_backend/routes/pair.py@@ -1,16 +1,16 @@-"""Pair-Routes (Phase D).+"""Pair routes (Phase D).-Plan §D-Decision-1: URL-Token-basiertes Pairing mit 10 min Gueltigkeit.+Plan §D-Decision-1: URL-token-based pairing with 10 min validity.Flow:-1. Owner ruft ``POST /api/v1/pair/initiate`` (admin-token) → bekommt- ``{token, url, expires_at}``. Owner schickt URL via Privatkanal an- Friend.-2. Friend besucht URL → Friend's Backend ruft Owner's- ``POST /api/v1/pair/accept`` mit ``{token, friend_pubkey, friend_url,- friend_display_name}``. Owner registriert Friendship und antwortet- mit eigenem ``{owner_pubkey, owner_url, owner_display_name}``. Friend's- Backend registriert seinerseits (in seiner ``friends``-Tabelle).+1. The owner calls ``POST /api/v1/pair/initiate`` (admin token) → gets+ ``{token, url, expires_at}``. The owner sends the URL to the friend+ via a private channel.+2. The friend visits the URL → the friend's backend calls the owner's+ ``POST /api/v1/pair/accept`` with ``{token, friend_pubkey, friend_url,+ friend_display_name}``. The owner registers the friendship and+ responds with its own ``{owner_pubkey, owner_url, owner_display_name}``.+ The friend's backend in turn registers it (in its ``friends`` table)."""from __future__ import annotations@@ -42,7 +42,7 @@ log = logging.getLogger(__name__)router = APIRouter(prefix="/api/v1/pair", tags=["pair"])PAIR_TTL = timedelta(minutes=10)-PAIR_TOKEN_BYTES = 24 # 24 Bytes -> 48 hex chars (>= 16 Min-Length)+PAIR_TOKEN_BYTES = 24 # 24 bytes -> 48 hex chars (>= 16 min length)@router.post(@@ -75,10 +75,10 @@ def initiate(request: Request, payload: PairInitiateRequest) -> PairInitiateResp@router.post("/accept", response_model=PairAcceptResponse)def accept(request: Request, payload: PairAcceptRequest) -> PairAcceptResponse:- """Friend's Backend ruft das hier mit dem Token an.+ """The friend's backend calls this with the token.- NICHT signature-authenticated — der Friend ist hier noch unbekannt.- Der Token IST die Auth (single-use, 10 min).+ NOT signature-authenticated — the friend is still unknown here.+ The token IS the auth (single-use, 10 min)."""now = datetime.now(timezone.utc)with get_db(request) as session:@@ -93,13 +93,13 @@ def accept(request: Request, payload: PairAcceptRequest) -> PairAcceptResponse:owner = get_owner_identity(session)if tok.owner_pubkey != owner.pubkey:- # Defensiv: Owner hat sich zwischen initiate und accept geaendert+ # Defensive: the owner changed between initiate and acceptraise HTTPException(status_code=503, detail="owner mismatch")if payload.friend_pubkey == owner.pubkey:raise HTTPException(status_code=400, detail="cannot pair with self")- # Token verbrauchen+ # Consume the tokentok.used_at = nowexisting = session.get(Friend, (owner.pubkey, payload.friend_pubkey))@@ -137,7 +137,7 @@ friends_router = APIRouter(prefix="/api/v1", tags=["friends"])@friends_router.get("/friends", response_model=FriendsListResponse)def list_friends(request: Request, _=Depends(require_signed_request)) -> FriendsListResponse:- """Owner listet seine Friends. Signed durch Owner-Pubkey."""+ """The owner lists their friends. Signed by the owner's pubkey."""with get_db(request) as session:owner = get_owner_identity(session)rows = session.query(Friend).filter(Friend.owner_pubkey == owner.pubkey).all()@@ -160,11 +160,11 @@ def update_friend(friend_pubkey: str,auth=Depends(require_signed_request),) -> FriendItem:- """Per-Friend-Sync-Interval aktualisieren (Plan §D-Spec).+ """Updates the per-friend sync interval (Plan §D spec).- Body: ``{ts_ms, pull_interval_s}`` signed by owner. Andere Friend-Felder- (URL, paired_at) sind nicht ueber diese Route aenderbar — die kommen- durch ein neues Pair-Roundtrip.+ Body: ``{ts_ms, pull_interval_s}`` signed by owner. Other friend+ fields (URL, paired_at) are not changeable via this route — those+ come through a new pair roundtrip."""try:body = FriendUpdateRequest.model_validate(auth.payload)@@ -195,18 +195,18 @@ def update_friend(# ----------------------------------------------------------------------def _aware(dt: datetime) -> datetime:- """SQLite gibt Datetimes ohne tz zurueck — wir ergaenzen UTC."""+ """SQLite returns datetimes without a tz — we add UTC."""if dt.tzinfo is None:return dt.replace(tzinfo=timezone.utc)return dtdef _public_url_for_owner(request: Request) -> str:- """Best-Effort: nimm den ``Host``-Header und Scheme.+ """Best effort: use the ``Host`` header and scheme.- In Production sitzt typischerweise Caddy davor, der setzt ``Forwarded``-- Header. Phase D nimmt das aber nicht zwingend an; lokaler Localhost-- Test funktioniert mit ``http://<host>``.+ In production, Caddy typically sits in front and sets the+ ``Forwarded`` header. Phase D doesn't strictly assume that though;+ a local localhost test works with ``http://<host>``."""forwarded_proto = request.headers.get("x-forwarded-proto")forwarded_host = request.headers.get("x-forwarded-host")diff --git a/board-backend/board_backend/routes/reactions.py b/board-backend/board_backend/routes/reactions.pyindex 6d0924c01f..658f58eb29 100644--- a/board-backend/board_backend/routes/reactions.py+++ b/board-backend/board_backend/routes/reactions.py@@ -1,13 +1,13 @@-"""Reactions-Routes (Phase D).+"""Reactions routes (Phase D).-- ``POST /api/v1/reactions`` (signed by owner) — Owner reagiert auf einen- Item, dessen Author ein Friend ist. Owner's Backend forwardet die Reaction- zum Friend-Backend via ``POST /api/v1/federation/reactions/inbound``.+- ``POST /api/v1/reactions`` (signed by owner) — the owner reacts to an+ item whose author is a friend. The owner's backend forwards the reaction+ to the friend's backend via ``POST /api/v1/federation/reactions/inbound``.- ``POST /api/v1/federation/reactions/inbound`` (signed by friend) —- Friend's Backend pusht eine Reaction auf einen Item, dessen Author das- Owner-Backend ist. Wir verifizieren, dass der ``viewer_pubkey`` ein- bekannter Friend ist, und persistieren.+ the friend's backend pushes a reaction to an item whose author is the+ owner's backend. We verify that ``viewer_pubkey`` is a known friend, then+ persist."""from __future__ import annotations@@ -39,7 +39,7 @@ fed_router = APIRouter(prefix="/api/v1/federation", tags=["federation"])# -----------------------------------------------------------------------# Owner side — eine Reaktion auf einen Friend-Item+# Owner side — a reaction to a friend's item# ----------------------------------------------------------------------@router.post("/reactions", response_model=ReactionAck)@@ -59,7 +59,7 @@ async def post_reaction(raise HTTPException(status_code=403, detail="not the owner")if body.author_pubkey == owner.pubkey:- # Self-Reaction (selten, aber moeglich): direkt persistieren.+ # Self-reaction (rare, but possible): persist directly.local_item = session.get(ActivityItem, body.item_id)if local_item is None:raise HTTPException(status_code=404, detail="item not found")@@ -72,8 +72,8 @@ async def post_reaction(raise HTTPException(status_code=404, detail="not a friend")target_url = friend.friend_url- # HTTP-Forward ausserhalb der Session. ``auth.body_bytes`` enthaelt den- # bereits gelesenen raw-Body (require_signed_request konsumiert ihn).+ # HTTP forward outside the session. ``auth.body_bytes`` holds the+ # raw body already read (require_signed_request consumes it).ok = await _forward_reaction(request, target_url, auth.body_bytes)if not ok:raise HTTPException(status_code=502, detail="friend backend unreachable")@@ -81,7 +81,7 @@ async def post_reaction(# -----------------------------------------------------------------------# Federation side — eine eingehende Reaktion vom Friend-Backend+# Federation side — an incoming reaction from the friend's backend# ----------------------------------------------------------------------@fed_router.post("/reactions/inbound", response_model=ReactionAck)@@ -96,7 +96,7 @@ def reactions_inbound(with get_db(request) as session:owner = get_owner_identity(session)- # Reactor muss ein friend sein.+ # Reactor must be a friend.friend = session.get(Friend, (owner.pubkey, auth.viewer_pubkey))if friend is None:raise HTTPException(status_code=403, detail="not a friend")@@ -113,7 +113,7 @@ def reactions_inbound(# ----------------------------------------------------------------------def _persist_reaction(session, item_id: str, reactor_pubkey: str, reaction: str) -> None:- """Idempotent insert via UNIQUE-Constraint."""+ """Idempotent insert via UNIQUE constraint."""from sqlalchemy.exc import IntegrityErrorsession.add(Reaction(item_id=item_id,@@ -124,22 +124,23 @@ def _persist_reaction(session, item_id: str, reactor_pubkey: str, reaction: str)session.flush()except IntegrityError:session.rollback()- # bereits vorhanden, OK+ # already present, OKasync def _forward_reaction(request: Request, target_url: str, raw_body: bytes) -> bool:- """Forwardet den signed Body 1:1 an Friend-Backend.-- Owner-Backend hat **keinen Privkey** — die Sig wurde im Frontend (oder- im lokalen Jarvis-Client) generiert und im X-Jarvis-Sig-Header- geliefert. Wir leiten den raw-Body + die Sig-Header weiter; Friend-- Backend verifiziert mit dem (gleichen) Owner-Pubkey.-- Sicherer Pfad, weil der Friend-Empfaenger ``InboundReactionRequest``- mit ``extra='forbid'`` validiert und die Sig gegen den Reactor-Pubkey- aus dem ``X-Pubkey``-Header prueft — also gegen den Owner. Der- Friend-Backend muss diesen Owner als ``Friend`` registriert haben,- sonst 403.+ """Forwards the signed body 1:1 to the friend's backend.++ The owner's backend has **no private key** — the signature was+ generated in the frontend (or the local Jarvis client) and delivered+ in the X-Jarvis-Sig header. We pass the raw body + the signature+ header through as-is; the friend's backend verifies against the+ (same) owner pubkey.++ This is a safe path because the friend receiver validates+ ``InboundReactionRequest`` with ``extra='forbid'`` and checks the+ signature against the reactor pubkey from the ``X-Pubkey`` header —+ i.e. against the owner. The friend's backend must have this owner+ registered as a ``Friend``, otherwise 403."""headers_pass = {"Content-Type": "application/json",@@ -148,8 +149,8 @@ async def _forward_reaction(request: Request, target_url: str, raw_body: bytes)}timeout = httpx.Timeout(5.0)try:- # Tests koennen ueber app.state.federation_http einen MockTransport- # injizieren — Production nutzt den Default.+ # Tests can inject a MockTransport via app.state.federation_http —+ # production uses the default.forwarder = getattr(request.app.state, "federation_http", None)if forwarder is None:async with httpx.AsyncClient(timeout=timeout) as client:diff --git a/board-backend/board_backend/routes/sync.py b/board-backend/board_backend/routes/sync.pyindex 0a256e25b3..fb9004bb63 100644--- a/board-backend/board_backend/routes/sync.py+++ b/board-backend/board_backend/routes/sync.py@@ -1,13 +1,13 @@-"""``POST /api/v1/sync`` — signed Stats-Push.+"""``POST /api/v1/sync`` — signed stats push.-Auth via ``require_signed_request`` (Pubkey + Sig + Replay-Window).-PII-Filter via Pydantic-``extra='forbid'`` im ``SyncPayload``.+Auth via ``require_signed_request`` (pubkey + signature + replay window).+PII filter via Pydantic ``extra='forbid'`` on ``SyncPayload``.-Schreibt:-- ``identity.display_name`` + ``identity.bio`` werden bei jedem Push- aktualisiert (Plan §C-Decision-2: display_name pro Push).-- ``identity.last_sync_at`` wird gesetzt.-- ``push_log`` bekommt eine Audit-Zeile mit Counts (kein Inhalt).+Writes:+- ``identity.display_name`` + ``identity.bio`` are updated on every push+ (Plan §C-Decision-2: display_name per push).+- ``identity.last_sync_at`` is set.+- ``push_log`` gets an audit row with counts (no content)."""from __future__ import annotations@@ -30,14 +30,14 @@ def sync(request: Request,auth: SignedAuth = Depends(require_signed_request),) -> SyncAck:- # Pydantic validiert das Body-Dict — extra-keys wie "text" oder- # "transcript" → 422 mit "Extra inputs are not permitted".+ # Pydantic validates the body dict — extra keys such as "text" or+ # "transcript" → 422 with "Extra inputs are not permitted".try:body = SyncPayload.model_validate(auth.payload)except ValidationError as exc:- # Bewusst 422 mit detaillierter Pydantic-Message — der Client kann- # daraus lernen, welches Feld er nicht haette schicken sollen.- # Aber niemals den Body selbst echoen — nur die Pfade.+ # Deliberately 422 with a detailed Pydantic message — the client+ # can learn from it which field it should not have sent.+ # But never echo the body itself — only the paths.forbidden = [".".join(str(x) for x in err["loc"])for err in exc.errors() if err.get("type") == "extra_forbidden"@@ -54,7 +54,7 @@ def sync(with get_db(request) as session:ident = session.get(Identity, auth.identity.pubkey)if ident is None:- # Race: zwischen Auth und hier wurde die Identity geloescht.+ # Race: the identity was deleted between auth and here.raise HTTPException(status_code=401, detail="identity revoked")ident.display_name = body.display_nameident.last_sync_at = received_atdiff --git a/board-backend/board_backend/schemas.py b/board-backend/board_backend/schemas.pyindex 907f79240c..7ddfef2bec 100644--- a/board-backend/board_backend/schemas.py+++ b/board-backend/board_backend/schemas.py@@ -1,11 +1,11 @@-"""Pydantic-Request/Response-Modelle.--Sicherheit: ``SyncPayload`` enthaelt **explizit nur** sichere Aggregat--Felder. Wenn ein Sync-Call Felder mit verbotenen Namen mitsendet-(``text``, ``transcript``, ``args``, ``output_preview`` …), wird er vom-``models_extra='forbid'`` abgelehnt. Das ist die Server-seitige Spiegelung-von ``BoardAggregator.export_all_for_federation()`` (Plan §A-Smoke-„test_no_pii_in_aggregated_stats").+"""Pydantic request/response models.++Security: ``SyncPayload`` **explicitly contains only** safe aggregate+fields. If a sync call sends fields with disallowed names+(``text``, ``transcript``, ``args``, ``output_preview`` …), it is+rejected by ``models_extra='forbid'``. This is the server-side mirror+of ``BoardAggregator.export_all_for_federation()`` (Plan §A-Smoke+"test_no_pii_in_aggregated_stats")."""from __future__ import annotations@@ -51,8 +51,8 @@ class RegisterResponse(BaseModel):# ----------------------------------------------------------------------class DailyStatsItem(BaseModel):- """Eine Tages-Aggregation. Spiegelt das BoardAggregator-Format aus- ``export_all_for_federation()`` — sichere Felder only.+ """A daily aggregation. Mirrors the BoardAggregator format from+ ``export_all_for_federation()`` — safe fields only."""model_config = ConfigDict(extra="forbid")@@ -75,13 +75,14 @@ class AchievementItem(BaseModel):class SyncPayload(BaseModel):- """Eingehende Sync-Daten. ``extra='forbid'`` ist die zentrale PII-Wand.-- Pflichtfelder:- - ``ts_ms``: Client-Sendezeit in Millisekunden seit Epoch (UTC).- Server lehnt ab, wenn |now - ts_ms| > replay_window.- - ``display_name``: redundant zur ``identity``-Tabelle, weil der User- ihn ohne Re-Registrierung aendern koennen muss (Plan §C-Decision-2).+ """Incoming sync data. ``extra='forbid'`` is the central PII wall.++ Required fields:+ - ``ts_ms``: client send time in milliseconds since epoch (UTC).+ Server rejects when |now - ts_ms| > replay_window.+ - ``display_name``: redundant with the ``identity`` table, because the+ user must be able to change it without re-registering (Plan+ §C-Decision-2)."""model_config = ConfigDict(extra="forbid")@@ -112,7 +113,7 @@ class MeResponse(BaseModel):# -----------------------------------------------------------------------# Generischer Error+# Generic error# ----------------------------------------------------------------------class ErrorResponse(BaseModel):@@ -126,7 +127,7 @@ class ErrorResponse(BaseModel):# ----------------------------------------------------------------------class PairInitiateRequest(BaseModel):- """Admin generiert Pair-URL. Display-Name optional fuer Debug-Anzeigen."""+ """Admin generates a pair URL. Display name optional for debug displays."""note: str | None = None@@ -138,7 +139,7 @@ class PairInitiateResponse(BaseModel):class PairAcceptRequest(BaseModel):- """Friend's Backend ruft Owner's /pair/accept mit dem Token + eigenen Daten."""+ """Friend's backend calls owner's /pair/accept with the token + its own data."""model_config = ConfigDict(extra="forbid")token: Annotated[str, StringConstraints(min_length=16, max_length=64)]@@ -180,11 +181,11 @@ VisibilityStr = Annotated[class ActivityCreateRequest(BaseModel):- """Erstellung einer neuen Activity vom Owner.+ """Creation of a new activity by the owner.- Server-extra='forbid'-Wand verhindert Kontamination mit Tool-Outputs- oder Voice-Texten — der Owner-Frontend muss das selbst saubern, der- Server akzeptiert keine zusaetzlichen Felder.+ The server's extra='forbid' wall prevents contamination with tool+ outputs or voice text — the owner's frontend must sanitize that+ itself; the server accepts no additional fields."""model_config = ConfigDict(extra="forbid")@@ -192,7 +193,7 @@ class ActivityCreateRequest(BaseModel):kind: Annotated[str, StringConstraints(pattern=r"^(achievement_unlocked|story|milestone)$")]payload: dict[str, Any] = Field(default_factory=dict)visibility: VisibilityStr = "friends"- # Stories: 24h (Server enforced). Andere Kinds: None.+ # Stories: 24h (server enforced). Other kinds: None.expires_in_hours: int | None = Field(default=None, ge=1, le=168)@@ -205,7 +206,7 @@ class ActivityItemDTO(BaseModel):created_at: datetimevisibility: VisibilityStrexpires_at: datetime | None- # Owner sieht Counts mit Zahlen, andere bekommen nur ``reactions_seen=true|false``.+ # Owner sees counts as numbers, others only get ``reactions_seen=true|false``.reaction_counts: dict[str, int] | None = Nonehas_reactions: bool = False@@ -221,13 +222,13 @@ class FeedResponse(BaseModel):# ----------------------------------------------------------------------class ReactionRequest(BaseModel):- """Reactor → Owner. Reactor's Backend forwardet das hier zur Author-API.+ """Reactor → owner. Reactor's backend forwards this to the author's API.- ``author_pubkey`` referenziert den Item-Author. Owner-Backend nutzt das,- um in seiner ``friends``-Tabelle den richtigen Friend-Backend zu finden.- Die Sig wird auf diesem ganzen body gemacht — wenn das Frontend hier- luegt, scheitert die Sig-Verify auf Friend-Seite (item_id stimmt nicht- zum signierten payload).+ ``author_pubkey`` references the item author. The owner's backend uses+ this to find the right friend's backend in its ``friends`` table. The+ signature is computed over this whole body — if the frontend lies+ here, the signature verification fails on the friend's side (item_id+ doesn't match the signed payload)."""model_config = ConfigDict(extra="forbid")@@ -246,10 +247,10 @@ class ReactionAck(BaseModel):# ----------------------------------------------------------------------class InboundReactionRequest(BaseModel):- """Friend's Backend pusht eine Reaktion an Owner's Backend.+ """Friend's backend pushes a reaction to the owner's backend.- Identische Felder wie ``ReactionRequest`` — nur die Sig wird beim- Empfaenger gegen den Reactor's Pubkey verifiziert.+ Identical fields to ``ReactionRequest`` — only the signature is+ verified by the receiver against the reactor's pubkey."""model_config = ConfigDict(extra="forbid")@@ -270,11 +271,12 @@ class ForgetMeAck(BaseModel):# ----------------------------------------------------------------------class StoryCreateRequest(BaseModel):- """Wrapper um ``ActivityCreateRequest`` mit fixem kind=story.+ """Wrapper around ``ActivityCreateRequest`` with a fixed kind=story.- Fuer den Owner ist ``POST /api/v1/stories`` semantisch klarer als ein- generischer activity-call mit kind-Parameter. Server intern bauen wir- daraus einen ``ActivityCreateRequest(kind='story', expires_in_hours=24)``.+ For the owner, ``POST /api/v1/stories`` is semantically clearer than a+ generic activity call with a kind parameter. Internally the server+ builds an ``ActivityCreateRequest(kind='story', expires_in_hours=24)``+ from this."""model_config = ConfigDict(extra="forbid")@@ -288,7 +290,7 @@ class StoryCreateRequest(BaseModel):# ----------------------------------------------------------------------class FriendUpdateRequest(BaseModel):- """Per-Friend-Sync-Interval-Setting (Plan §D-Spec)."""+ """Per-friend sync interval setting (Plan §D-Spec)."""model_config = ConfigDict(extra="forbid")ts_ms: int = Field(ge=0)diff --git a/board-backend/docker-compose.yml b/board-backend/docker-compose.ymlindex 327eb23c62..e2525449bc 100644--- a/board-backend/docker-compose.yml+++ b/board-backend/docker-compose.yml@@ -1,11 +1,11 @@-# Lokales Compose-File fuer das Board-Backend.+# Local compose file for the board backend.## Start:-# cp .env.example .env # ADMIN_TOKEN setzen!+# cp .env.example .env # set ADMIN_TOKEN!# docker compose up -d --build# curl http://localhost:8765/healthz#-# Multi-Arch-Build (amd64 + arm64):+# Multi-arch build (amd64 + arm64):# docker buildx build --platform linux/amd64,linux/arm64 \# -t jarvis-board-backend:0.1.0 . --push@@ -18,7 +18,7 @@ services:container_name: jarvis-board-backendrestart: unless-stoppedenvironment:- JARVIS_BOARD_ADMIN_TOKEN: ${JARVIS_BOARD_ADMIN_TOKEN:?ADMIN_TOKEN ist nicht gesetzt — siehe .env.example}+ JARVIS_BOARD_ADMIN_TOKEN: ${JARVIS_BOARD_ADMIN_TOKEN:?ADMIN_TOKEN is not set — see .env.example}JARVIS_BOARD_DB_PATH: /data/board.dbJARVIS_BOARD_REGISTER_RATE_LIMIT_PER_MINUTE: ${JARVIS_BOARD_RATE_LIMIT:-10}JARVIS_BOARD_REPLAY_WINDOW_SECONDS: ${JARVIS_BOARD_REPLAY_WINDOW:-300}diff --git a/board-backend/pyproject.toml b/board-backend/pyproject.tomlindex a4d0b79647..1262af981d 100644--- a/board-backend/pyproject.toml+++ b/board-backend/pyproject.toml@@ -18,8 +18,8 @@ dependencies = ["pydantic-settings>=2.4","pynacl>=1.5","python-multipart>=0.0.9",- # Phase D: pair.py / reactions.py / background.py forwarden HTTP- # zu Friend-Backends — daher Production-Dependency, nicht nur dev.+ # Phase D: pair.py / reactions.py / background.py forward HTTP+ # to friend backends — hence a production dependency, not just dev."httpx>=0.27",]diff --git a/board-backend/tests/conftest.py b/board-backend/tests/conftest.pyindex 2b2f6fa604..2391000497 100644--- a/board-backend/tests/conftest.py+++ b/board-backend/tests/conftest.py@@ -1,7 +1,8 @@-"""Test-Fixtures fuers Backend.+"""Test fixtures for the backend.-Pattern: pro Test eine ``Settings``-Override mit ``tmp_path`` als DB-Pfad,-damit kein File-Side-Effect ueberlebt. Admin-Token ist immer ``test-admin``.+Pattern: one ``Settings`` override per test with ``tmp_path`` as the DB+path, so no file side effect survives. Admin token is always+``test-admin``."""from __future__ import annotations@@ -27,9 +28,9 @@ def settings(tmp_path: Path) -> Settings:@pytest.fixturedef app(settings: Settings):app = create_app(settings=settings)- # Background-Tasks (StoriesCleanup, FederationPuller) im Test-Setup- # ueberspringen — sonst spawnen wir bei jedem Test einen httpx.AsyncClient- # + Tasks, die der TestClient teardown nicht sauber abräumt.+ # Skip background tasks (StoriesCleanup, FederationPuller) in the test+ # setup — otherwise every test spawns an httpx.AsyncClient + tasks+ # that the TestClient teardown doesn't clean up properly.app.state.disable_background = Truereturn appdiff --git a/board-backend/tests/test_activity.py b/board-backend/tests/test_activity.pyindex 78c7995262..4c625b7624 100644--- a/board-backend/tests/test_activity.py+++ b/board-backend/tests/test_activity.py@@ -1,6 +1,6 @@-"""Activity-Feed + Visibility + Story + interesting-Algorithmus.+"""Activity feed + visibility + story + interesting algorithm.-Smoke-Tests aus Plan §D:+Smoke tests from Plan §D:- test_feed_excludes_non_friend_items (friends-only Items)- test_visibility_private_never_appears_in_feed- test_visibility_public_appears_in_feed_for_anyone@@ -94,8 +94,8 @@ def _create_item(# ----------------------------------------------------------------------def test_feed_excludes_non_friend_items(client: TestClient) -> None:- """Plan-Smoke: ein non-friend pullt → friends-Items NICHT enthalten,- public/Items aber schon."""+ """Plan smoke: a non-friend pulling → friends items NOT included,+ but public items are."""owner_priv, owner_pub = generate_keypair()_, friend_pub = generate_keypair()_, stranger_pub = generate_keypair()@@ -112,7 +112,7 @@ def test_feed_excludes_non_friend_items(client: TestClient) -> None:stranger_priv, _ = generate_keypair()stranger_priv = stranger_priv # noqa- # Stranger-Keypair separat+ # Separate stranger keypairsp_priv, sp_pub = generate_keypair()resp = _signed_get(client, "/api/v1/federation/feed", priv=sp_priv, pub=sp_pub)assert resp.status_code == 200@@ -131,7 +131,7 @@ def test_visibility_private_never_appears_in_feed(client: TestClient) -> None:pr_id = _create_item(client, priv=owner_priv, pub=owner_pub,kind="milestone", visibility="private")- # Friend schaut: KEIN private item.+ # Friend looks: NO private item.resp = _signed_get(client, "/api/v1/federation/feed", priv=fp_priv, pub=fp_pub)assert resp.status_code == 200ids = {i["id"] for i in resp.json()["items"]}@@ -144,7 +144,7 @@ def test_visibility_public_appears_in_feed_for_anyone(client: TestClient) -> Nonpub_id = _create_item(client, priv=owner_priv, pub=owner_pub,kind="milestone", visibility="public")- # Random Stranger pullt — sieht das public-Item.+ # Random stranger pulls — sees the public item.sp_priv, sp_pub = generate_keypair()resp = _signed_get(client, "/api/v1/federation/feed", priv=sp_priv, pub=sp_pub)assert resp.status_code == 200@@ -153,7 +153,7 @@ def test_visibility_public_appears_in_feed_for_anyone(client: TestClient) -> Nondef test_owner_sees_own_private_via_federation(client: TestClient) -> None:- """Owner pulling its own feed sieht alles (inkl. private)."""+ """Owner pulling its own feed sees everything (incl. private)."""owner_priv, owner_pub = generate_keypair()_setup_owner(client, owner_pub)pr_id = _create_item(client, priv=owner_priv, pub=owner_pub,@@ -166,7 +166,7 @@ def test_owner_sees_own_private_via_federation(client: TestClient) -> None:# -----------------------------------------------------------------------# Stories-Expiry+# Stories expiry# ----------------------------------------------------------------------def test_story_creates_expires_at_24h(client: TestClient) -> None:@@ -186,7 +186,7 @@ def test_story_creates_expires_at_24h(client: TestClient) -> None:def test_story_expires_after_24h(client: TestClient) -> None:- """Plan-Smoke: nach Time-Travel +25h verschwindet die Story aus dem Feed."""+ """Plan smoke: after a +25h time travel, the story disappears from the feed."""owner_priv, owner_pub = generate_keypair()fp_priv, fp_pub = generate_keypair()_setup_owner(client, owner_pub)@@ -194,13 +194,13 @@ def test_story_expires_after_24h(client: TestClient) -> None:sid = _create_item(client, priv=owner_priv, pub=owner_pub,kind="story", visibility="friends",- payload={"text": "vergaenglich"})+ payload={"text": "ephemeral"})- # Jetzt sichtbar.+ # Visible now.r1 = _signed_get(client, "/api/v1/federation/feed", priv=fp_priv, pub=fp_pub)assert sid in {i["id"] for i in r1.json()["items"]}- # In der DB die expires_at auf 1 min in der Vergangenheit setzen.+ # Set expires_at in the DB to 1 minute in the past.factory = client.app.state.session_factorywith factory() as session:item = session.get(ActivityItem, sid)@@ -212,11 +212,11 @@ def test_story_expires_after_24h(client: TestClient) -> None:# -----------------------------------------------------------------------# Reaction-Visibility+# Reaction visibility# ----------------------------------------------------------------------def test_owner_sees_own_reaction_counts(client: TestClient) -> None:- """Plan §D §0: Owner sieht Counts mit Zahl, andere nicht."""+ """Plan §D §0: owner sees counts as a number, others don't."""from board_backend.models import Reactionowner_priv, owner_pub = generate_keypair()@@ -232,17 +232,17 @@ def test_owner_sees_own_reaction_counts(client: TestClient) -> None:session.add(Reaction(item_id=iid, reactor_pubkey=fp_pub, reaction="fire"))session.commit()- # Owner pulled eigenen Feed.+ # Owner pulls its own feed.own = _signed_get(client, "/api/v1/activities",priv=owner_priv, pub=owner_pub).json()own_item = next(i for i in own["items"] if i["id"] == iid)assert own_item["reaction_counts"] == {"rocket": 1, "brain": 0, "fire": 1}- # Friend pulled federation-feed → counts MUST BE None- fp_priv = None # erzeugen+ # Friend pulled federation feed → counts MUST BE None+ fp_priv = None # generatefp_priv, fp_pub2 = generate_keypair()- # reuse fp_pub from above? Wir haben nur den pubkey hinzugefuegt; brauchen- # den priv. Generiere neu, fuege als zweiten friend hinzu.+ # reuse fp_pub from above? We only added the pubkey; we need+ # the priv. Generate a new one, add as a second friend._add_friend(client, owner_pub, fp_pub2)fed = _signed_get(client, "/api/v1/federation/feed",@@ -253,11 +253,11 @@ def test_owner_sees_own_reaction_counts(client: TestClient) -> None:# -----------------------------------------------------------------------# Interesting-Algorithm — Plan-Smoke+# Interesting algorithm — plan smoke# ----------------------------------------------------------------------def test_interesting_algorithm_is_deterministic() -> None:- """Plan-Smoke: same input → same order. Pure-function check."""+ """Plan smoke: same input → same order. Pure-function check."""a = interesting_score(reactions_total=5, age_hours=10)b = interesting_score(reactions_total=5, age_hours=10)assert a == b@@ -273,7 +273,7 @@ def test_interesting_sorts_recent_higher_for_equal_reactions(client: TestClient)_setup_owner(client, owner_pub)older_id = _create_item(client, priv=owner_priv, pub=owner_pub,kind="milestone", visibility="public")- # Setze created_at zurueck.+ # Set created_at back.factory = client.app.state.session_factorywith factory() as session:item = session.get(ActivityItem, older_id)@@ -310,11 +310,11 @@ def test_latest_sort_is_strict_chronological(client: TestClient) -> None:# -----------------------------------------------------------------------# Activity-Create-Pflichten+# Activity-create requirements# ----------------------------------------------------------------------def test_activity_create_rejects_extra_fields(client: TestClient) -> None:- """PII-Wand: extra='forbid' wirkt auch hier."""+ """PII wall: extra='forbid' also applies here."""owner_priv, owner_pub = generate_keypair()_setup_owner(client, owner_pub)body = {@@ -322,7 +322,7 @@ def test_activity_create_rejects_extra_fields(client: TestClient) -> None:"kind": "milestone","payload": {},"visibility": "friends",- "raw_transcript": "secret", # extra-Feld+ "raw_transcript": "secret", # extra field}resp = _signed_post(client, "/api/v1/activities",priv=owner_priv, pub=owner_pub, payload=body)diff --git a/board-backend/tests/test_crypto.py b/board-backend/tests/test_crypto.pyindex 4f86c94108..b00c1acd30 100644--- a/board-backend/tests/test_crypto.py+++ b/board-backend/tests/test_crypto.py@@ -1,4 +1,4 @@-"""Crypto-Tests fuer das Backend-Skeleton (Phase C, Commit 1)."""+"""Crypto tests for the backend skeleton (Phase C, Commit 1)."""from __future__ import annotationsimport json@@ -37,9 +37,9 @@ def test_canonical_json_handles_nested_structures() -> None:def test_canonical_json_utf8_passthrough() -> None:- out = canonical_json({"de": "Hallo Welt mit Umlaut: aeoeue ß"})+ out = canonical_json({"de": "Hallo Welt mit Umlaut: aeoeue ß"}) # i18n-allowparsed = json.loads(out.decode("utf-8"))- assert parsed["de"] == "Hallo Welt mit Umlaut: aeoeue ß"+ assert parsed["de"] == "Hallo Welt mit Umlaut: aeoeue ß" # i18n-allow# ----------------------------------------------------------------------@@ -90,16 +90,16 @@ def test_verify_fails_on_garbage_signature() -> None:def test_verify_raw_body_path() -> None:- """Der Server-Pfad: parse Body, re-kanonisieren, verify.+ """The server path: parse body, re-canonicalize, verify.- Demonstrates dass die Re-Kanonisierung gegen Whitespace-Manipulation- durch Proxies robust ist.+ Demonstrates that re-canonicalization is robust against whitespace+ manipulation by proxies."""priv, pub = generate_keypair()payload = {"a": 1, "b": "x"}sig = sign(payload, privkey_hex=priv)- # Simuliert einen Reverse-Proxy, der irrelevant whitespace einfuegt.+ # Simulates a reverse proxy that inserts irrelevant whitespace.raw_with_extra_ws = b'{"a": 1,\n "b": "x"}'parsed = json.loads(raw_with_extra_ws)@@ -109,11 +109,11 @@ def test_verify_raw_body_path() -> None:def test_verify_low_level_strict_bytes() -> None:- """Die Low-Level-``verify``-API ohne Re-Canonicalize bleibt streng."""+ """The low-level ``verify`` API without re-canonicalize stays strict."""priv, pub = generate_keypair()body = canonical_json({"x": 1})sig = sign(body, privkey_hex=priv)assert verify(pubkey_hex=pub, signature_hex=sig, body=body) is True- # Whitespace-Variante laesst die Low-Level-API durchfallen, was OK ist —- # der HTTP-Pfad ruft immer verify_with_recanonicalize.+ # The whitespace variant fails the low-level API, which is OK —+ # the HTTP path always calls verify_with_recanonicalize.assert verify(pubkey_hex=pub, signature_hex=sig, body=b'{"x": 1}') is Falsediff --git a/board-backend/tests/test_pair.py b/board-backend/tests/test_pair.pyindex 2ecf44b5e1..156ae0a5ce 100644--- a/board-backend/tests/test_pair.py+++ b/board-backend/tests/test_pair.py@@ -1,4 +1,4 @@-"""Pair-Tests fuer Phase D, Commit 1."""+"""Pair tests for Phase D, Commit 1."""from __future__ import annotationsimport time@@ -15,7 +15,7 @@ from board_backend.models import Friend, PairToken# -----------------------------------------------------------------------# Helpers + Fixtures fuer einen "owner"-registrierten Backend+# Helpers + fixtures for an "owner"-registered backend# ----------------------------------------------------------------------def _register_owner(client: TestClient, pubkey: str, name: str = "Owner") -> None:@@ -54,7 +54,7 @@ def owner_client(client: TestClient, owner_keys) -> TestClient:# -----------------------------------------------------------------------# Pair-Tests+# Pair tests# ----------------------------------------------------------------------def test_pair_initiate_returns_token_and_url(owner_client: TestClient) -> None:@@ -80,9 +80,10 @@ def test_pair_initiate_requires_admin(owner_client: TestClient) -> None:def test_pair_creates_bidirectional_friendship(owner_client: TestClient, friend_keys: tuple[str, str]) -> None:- """Plan-Smoke #1: nach erfolgreichem accept ist der Owner-Backend-friendly- mit dem Friend. (Bidirektional auf Owner-Seite — die Friend-Seite haengt- von dessen Backend ab; das testen wir in test_two_backends_pair.)"""+ """Plan smoke #1: after a successful accept, the owner's backend is+ friends with the friend. (Bidirectional on the owner's side — the+ friend's side depends on their backend; we test that in+ test_two_backends_pair.)"""init = owner_client.post("/api/v1/pair/initiate", json={},headers={"X-Admin-Token": "test-admin"},@@ -113,13 +114,13 @@ def test_pair_creates_bidirectional_friendship(def test_pair_token_expires_after_10min(owner_client: TestClient, friend_keys: tuple[str, str], settings: Settings,) -> None:- """Plan-Smoke #2: Token > 10 min alt → 401."""+ """Plan smoke #2: token > 10 min old → 401."""init = owner_client.post("/api/v1/pair/initiate", json={},headers={"X-Admin-Token": "test-admin"},).json()- # In der DB die expires_at-Zeile auf 11 min in der Vergangenheit ziehen.+ # Move the expires_at row in the DB to 11 min in the past.factory = owner_client.app.state.session_factorywith factory() as session:tok = session.get(PairToken, init["token"])@@ -191,7 +192,7 @@ def test_pair_self_pubkey_rejected(def test_friends_list_endpoint(owner_client: TestClient, owner_keys: tuple[str, str], friend_keys: tuple[str, str]) -> None:- """GET /api/v1/friends mit signed owner-request listet die Friend(s)."""+ """GET /api/v1/friends with a signed owner request lists the friend(s)."""owner_priv, owner_pub = owner_keysinit = owner_client.post("/api/v1/pair/initiate", json={},diff --git a/board-backend/tests/test_phase_d_gaps.py b/board-backend/tests/test_phase_d_gaps.pyindex 56d7ec14bf..aa429c198c 100644--- a/board-backend/tests/test_phase_d_gaps.py+++ b/board-backend/tests/test_phase_d_gaps.py@@ -1,4 +1,4 @@-"""Tests fuer Phase-D-Spec-Luecken: /stories, since-Param, friend-PATCH."""+"""Tests for Phase D spec gaps: /stories, since param, friend PATCH."""from __future__ import annotationsimport time@@ -35,7 +35,7 @@ def _setup_owner(client: TestClient, pub: str, name: str = "Alice") -> None:# -----------------------------------------------------------------------# /stories — separate Route+# /stories — separate route# ----------------------------------------------------------------------def test_stories_route_creates_story_with_24h_expiry(client: TestClient) -> None:@@ -43,17 +43,17 @@ def test_stories_route_creates_story_with_24h_expiry(client: TestClient) -> None_setup_owner(client, pub)body = {"ts_ms": _now_ms(),- "text": "Heute viel Code geschrieben.",+ "text": "Wrote a lot of code today.","visibility": "friends",}resp = _signed("POST", client, "/api/v1/stories", priv=priv, pub=pub, payload=body)assert resp.status_code == 200, resp.textitem = resp.json()assert item["kind"] == "story"- assert item["payload"]["text"] == "Heute viel Code geschrieben."+ assert item["payload"]["text"] == "Wrote a lot of code today."assert item["expires_at"] is not None- # 24h-Default verifizieren.+ # Verify the 24h default.factory = client.app.state.session_factorywith factory() as session:row = session.get(ActivityItem, item["id"])@@ -92,29 +92,29 @@ def test_stories_rejects_extra_fields(client: TestClient) -> None:# ----------------------------------------------------------------------def test_feed_since_filters_old_items(client: TestClient) -> None:- """Plan §D-Spec: ``since`` filtert items mit created_at < since raus."""+ """Plan §D-Spec: ``since`` filters out items with created_at < since."""priv, pub = generate_keypair()_setup_owner(client, pub)- # Item 1: alt+ # Item 1: oldold = _signed("POST", client, "/api/v1/activities",priv=priv, pub=pub,payload={"ts_ms": _now_ms(), "kind": "milestone","payload": {}, "visibility": "public"}).json()["id"]- # Item-1 created_at zurueckdatieren.+ # Backdate item 1's created_at.factory = client.app.state.session_factorywith factory() as session:row = session.get(ActivityItem, old)row.created_at = datetime.now(timezone.utc) - timedelta(days=2)session.commit()- # Item 2: neu+ # Item 2: newnew = _signed("POST", client, "/api/v1/activities",priv=priv, pub=pub,payload={"ts_ms": _now_ms(), "kind": "milestone","payload": {}, "visibility": "public"}).json()["id"]- # Pull mit since=gestern soll nur das neue Item liefern.+ # Pulling with since=yesterday should only return the new item.sp_priv, sp_pub = generate_keypair()yesterday = (datetime.now(timezone.utc) - timedelta(days=1)).isoformat()resp = _signed("GET", client, "/api/v1/federation/feed",diff --git a/board-backend/tests/test_reactions_forget.py b/board-backend/tests/test_reactions_forget.pyindex 7e22a9c97d..fcd3a3f936 100644--- a/board-backend/tests/test_reactions_forget.py+++ b/board-backend/tests/test_reactions_forget.py@@ -1,4 +1,4 @@-"""Tests fuer Reactions-Forwarding, Inbound-Reactions, Forget-Me, Cleanup."""+"""Tests for reactions forwarding, inbound reactions, forget-me, cleanup."""from __future__ import annotationsimport time@@ -47,17 +47,17 @@ def _create_local_item(client: TestClient, *, priv: str, pub: str, vis: str = "f# -----------------------------------------------------------------------# Forwarding-Test mit MockTransport+# Forwarding test with MockTransport# ----------------------------------------------------------------------@pytest.mark.asyncioasync def test_reaction_propagates_to_author_backend(client: TestClient) -> None:- """Plan-Smoke: Owner reagiert auf Friend-Item, Friend-Backend bekommt- /federation/reactions/inbound forwarded."""+ """Plan smoke: owner reacts to a friend's item, the friend's backend+ gets /federation/reactions/inbound forwarded."""owner_priv, owner_pub = generate_keypair()_setup_owner(client, owner_pub)- # Friend (B) registrieren in Owner's friends-Tabelle.+ # Register friend (B) in the owner's friends table._, friend_pub = generate_keypair()factory = client.app.state.session_factorywith factory() as session:@@ -69,7 +69,7 @@ async def test_reaction_propagates_to_author_backend(client: TestClient) -> None))session.commit()- # Mock-Transport, der den Forward fängt.+ # Mock transport that catches the forward.captured: dict = {}async def _handler(req: httpx.Request) -> httpx.Response:@@ -84,7 +84,7 @@ async def test_reaction_propagates_to_author_backend(client: TestClient) -> Nonetransport=transport, base_url="http://x", timeout=5.0,)try:- # Owner reagiert auf Item-ID, das auf Friend's Backend lebt.+ # Owner reacts to an item ID that lives on the friend's backend.body = {"ts_ms": _now_ms(),"item_id": "fakeitem123",@@ -103,12 +103,12 @@ async def test_reaction_propagates_to_author_backend(client: TestClient) -> Nonedef test_inbound_reaction_persists_when_friend(client: TestClient) -> None:- """Friend (B) signed eine inbound Reaction → Owner-Backend speichert."""+ """Friend (B) signs an inbound reaction → owner's backend stores it."""owner_priv, owner_pub = generate_keypair()friend_priv, friend_pub = generate_keypair()_setup_owner(client, owner_pub)- # B als Friend registrieren.+ # Register B as a friend.factory = client.app.state.session_factorywith factory() as session:session.add(Friend(@@ -182,7 +182,7 @@ def test_inbound_reaction_idempotent(client: TestClient) -> None:assert r2.status_code == 200with factory() as session:rows = session.query(Reaction).filter(Reaction.item_id == iid).all()- # UNIQUE constraint hat zweite Reaction blockiert.+ # UNIQUE constraint blocked the second reaction.assert len(rows) == 1@@ -191,13 +191,13 @@ def test_inbound_reaction_idempotent(client: TestClient) -> None:# ----------------------------------------------------------------------def test_right_to_be_forgotten_removes_all_traces(client: TestClient) -> None:- """Plan-Smoke: signed DELETE /federation/identity/{pubkey} loescht- Friendship + Reactions + Activities von dem Pubkey."""+ """Plan smoke: signed DELETE /federation/identity/{pubkey} deletes+ friendship + reactions + activities for that pubkey."""owner_priv, owner_pub = generate_keypair()friend_priv, friend_pub = generate_keypair()_setup_owner(client, owner_pub)- # Friend B registrieren + Reactions hinterlassen.+ # Register friend B + leave reactions.factory = client.app.state.session_factoryiid = _create_local_item(client, priv=owner_priv, pub=owner_pub)with factory() as session:@@ -239,7 +239,7 @@ def test_right_to_be_forgotten_removes_all_traces(client: TestClient) -> None:def test_forget_me_path_and_signature_must_match(client: TestClient) -> None:- """Wenn DELETE-Path-Pubkey != X-Pubkey im Header → 403."""+ """If the DELETE path pubkey != X-Pubkey in the header → 403."""owner_priv, owner_pub = generate_keypair()friend_priv, friend_pub = generate_keypair()other_priv, other_pub = generate_keypair()@@ -260,7 +260,7 @@ def test_forget_me_path_and_signature_must_match(client: TestClient) -> None:# -----------------------------------------------------------------------# Stories-Cleanup+# Stories cleanup# ----------------------------------------------------------------------def test_stories_cleanup_removes_only_expired(client: TestClient) -> None:@@ -268,7 +268,7 @@ def test_stories_cleanup_removes_only_expired(client: TestClient) -> None:_setup_owner(client, owner_pub)factory = client.app.state.session_factory- # Eine Story mit expires_at in der Vergangenheit + ein Achievement ohne expires.+ # A story with expires_at in the past + an achievement without expires.expired_id = _create_local_item(client, priv=owner_priv, pub=owner_pub, vis="friends")keep_id = _create_local_item(client, priv=owner_priv, pub=owner_pub, vis="friends")with factory() as session:diff --git a/board-backend/tests/test_routes.py b/board-backend/tests/test_routes.pyindex 5daea0ba84..add3c2f8f8 100644--- a/board-backend/tests/test_routes.py+++ b/board-backend/tests/test_routes.py@@ -1,4 +1,4 @@-"""Route-Tests fuer Phase C, Commit 2 — Sicherheitsanforderungen aus PLAN.md."""+"""Route tests for Phase C, Commit 2 — security requirements from PLAN.md."""from __future__ import annotationsimport json@@ -104,8 +104,8 @@ def test_register_rejects_non_hex_pubkey(client: TestClient) -> None:def test_register_rate_limit_enforced(client: TestClient) -> None:- """11. Request in einer Minute → 429 (Limit ist 10)."""- headers = {"X-Admin-Token": "wrong"} # invalid token, aber Rate-Limit greift VOR der Token-Pruefung+ """11th request in one minute → 429 (limit is 10)."""+ headers = {"X-Admin-Token": "wrong"} # invalid token, but rate limit kicks in BEFORE token checklast = Nonefor i in range(12):resp = client.post(@@ -160,7 +160,7 @@ def test_signed_sync_rejects_tampered_payload(client: TestClient) -> None:}]sig = sign(payload, privkey_hex=priv)- # Manipulate after signing — typischer Replay-Tamper-Vector.+ # Manipulate after signing — a typical replay-tamper vector.tampered = dict(payload)tampered["daily_stats"] = [{**payload["daily_stats"][0], "tasks_completed": 99999}]body = canonical_json(tampered)@@ -185,18 +185,18 @@ def test_signed_sync_rejects_unregistered_pubkey(client: TestClient) -> None:def test_signed_sync_rejects_old_timestamp(client: TestClient) -> None:- """Plan §C-Sec: Replay-Protection bei ts > 5min Vergangenheit."""+ """Plan §C-Sec: replay protection when ts is > 5min in the past."""priv, pub = generate_keypair()_register(client, pubkey=pub)payload = _minimal_payload()- payload["ts_ms"] = _now_ms() - 6 * 60 * 1000 # 6 min alt+ payload["ts_ms"] = _now_ms() - 6 * 60 * 1000 # 6 min oldresp = _signed_post(client, "/api/v1/sync", priv=priv, pub=pub, payload=payload)assert resp.status_code == 401assert "replay" in resp.json()["detail"].lower()def test_signed_sync_rejects_future_timestamp(client: TestClient) -> None:- """Drift in beide Richtungen — Plan §C-Sec implizit."""+ """Drift in both directions — implicit in Plan §C-Sec."""priv, pub = generate_keypair()_register(client, pubkey=pub)payload = _minimal_payload()@@ -215,21 +215,21 @@ def test_signed_sync_missing_signature_header(client: TestClient) -> None:content=body,headers={"X-Pubkey": pub, "Content-Type": "application/json"},)- assert resp.status_code == 422 # FastAPI Header-Pflichtfeld+ assert resp.status_code == 422 # FastAPI required header field# -----------------------------------------------------------------------# PII-Filter — Plan §C-Sec, kein Voice-Text/Tool-IO am Backend+# PII filter — Plan §C-Sec, no voice text / tool I/O on the backend# ----------------------------------------------------------------------def test_no_pii_in_sync_payload(client: TestClient) -> None:- """Forbidden-Phrases-Liste analog zu Phase A test_no_pii_in_aggregated_stats."""+ """Forbidden-phrases list analogous to Phase A test_no_pii_in_aggregated_stats."""priv, pub = generate_keypair()_register(client, pubkey=pub)payload = _minimal_payload()- # Bewusster PII-Leak-Versuch: extra Top-Level-Feld- payload["voice_transcript"] = "Mein passwort ist hunter2"+ # Deliberate PII leak attempt: extra top-level field+ payload["voice_transcript"] = "My password is hunter2"resp = _signed_post(client, "/api/v1/sync", priv=priv, pub=pub, payload=payload)assert resp.status_code == 422@@ -254,7 +254,7 @@ def test_no_pii_in_daily_stats_extra_field(client: TestClient) -> None:def test_pushlog_contains_no_payload_inhalte(client: TestClient) -> None:- """Server speichert nur Metadaten, keinen Payload-Inhalt."""+ """Server stores only metadata, no payload content."""priv, pub = generate_keypair()_register(client, pubkey=pub)@@ -271,7 +271,7 @@ def test_pushlog_contains_no_payload_inhalte(client: TestClient) -> None:resp = _signed_post(client, "/api/v1/sync", priv=priv, pub=pub, payload=payload)assert resp.status_code == 200- # Inspiziere die DB direkt via app.state.engine+ # Inspect the DB directly via app.state.enginefrom sqlalchemy import selectfrom board_backend.models import PushLogfactory = client.app.state.session_factory@@ -279,7 +279,7 @@ def test_pushlog_contains_no_payload_inhalte(client: TestClient) -> None:rows = session.execute(select(PushLog)).scalars().all()assert len(rows) == 1row = rows[0]- # Kein Inhalt-Feld in PushLog-Schema vorhanden+ # No content field present in the PushLog schemaassert not hasattr(row, "payload")assert not hasattr(row, "tools_used")assert row.daily_stats_count == 1@@ -305,7 +305,7 @@ def test_me_returns_identity_after_register(client: TestClient) -> None:def test_me_push_count_increments(client: TestClient) -> None:priv, pub = generate_keypair()_register(client, pubkey=pub)- # Drei Pushes+ # Three pushesfor _ in range(3):payload = _minimal_payload()payload["ts_ms"] = _now_ms()@@ -321,14 +321,15 @@ def test_me_push_count_increments(client: TestClient) -> None:# ----------------------------------------------------------------------def test_signature_replay_with_changed_body_rejected(client: TestClient) -> None:- """Klassischer Replay-Vector: Sig + Body von vorhin, ts neu — sig matcht- aber den re-canonicalized body nicht (weil ts geaendert wurde)."""+ """Classic replay vector: signature + body from before, new ts — the+ signature matches but not the re-canonicalized body (because ts+ changed)."""priv, pub = generate_keypair()_register(client, pubkey=pub)payload = _minimal_payload()sig = sign(payload, privkey_hex=priv)- # Replay: ts_ms ueberschreiben → Sig matcht nicht mehr+ # Replay: overwrite ts_ms → signature no longer matchesreplayed = dict(payload)replayed["ts_ms"] = _now_ms() + 1body = canonical_json(replayed)diff --git a/conductor/__init__.py b/conductor/__init__.pyindex 2b3dba374c..969b34556a 100644--- a/conductor/__init__.py+++ b/conductor/__init__.py@@ -1,27 +1,27 @@-"""Conductor — eine bessere Canvas fuer agentic Workflows.+"""Conductor — a better canvas for agentic workflows.-Conductor ist ein **eigenstaendiges Open-Source-Tool**, das in diesem-Monorepo entstanden ist, aber nicht an Jarvis gebunden ist:+Conductor is a **standalone open-source tool** that originated in this+monorepo but is not tied to Jarvis:-- Standalone-Modus: ``python -m conductor serve`` startet einen eigenen- FastAPI-Server auf Port 7777 mit SQLite in ``~/.conductor/``.-- Embedded-Modus: Jarvis importiert das Package, mountet den Router in- seinen eigenen FastAPI-Server und zeigt eine Dashboard-View.+- Standalone mode: ``python -m conductor serve`` starts its own+ FastAPI server on port 7777 with SQLite in ``~/.conductor/``.+- Embedded mode: Jarvis imports the package, mounts the router in+ its own FastAPI server, and shows a dashboard view.-Es ist bewusst kein n8n-Clone — keine Drag-and-Drop-Nodes, kein Graph.-Stattdessen:+It is deliberately not an n8n clone — no drag-and-drop nodes, no graph.+Instead:-- **Jobs sind YAML** — git-freundlich, copy-pasteable, diffbar.-- **Timeline-View** — alle Runs chronologisch statt raeumlich.-- **Drei Job-Types**: shell, http, agent. Das deckt 95 % aller Scheduled-- Task + Agentic-Workflow-Use-Cases ab.-- **Built-in Observability** — jeder Run hat Live-Logs, Duration,- Exit-Code, Tokens, Cost (wenn Agent) — nichts davon muss extra- aktiviert werden.+- **Jobs are YAML** — git-friendly, copy-pasteable, diffable.+- **Timeline view** — all runs chronological instead of spatial.+- **Three job types**: shell, http, agent. That covers 95% of all+ scheduled-task + agentic-workflow use cases.+- **Built-in observability** — every run has live logs, duration,+ exit code, tokens, cost (if agent) — none of it needs to be+ activated separately.Public API:- ``ConductorStore``, ``Runner``, ``Scheduler``, ``Job``, ``Run`` und- die drei ``JobHandler``-Implementations.+ ``ConductorStore``, ``Runner``, ``Scheduler``, ``Job``, ``Run``, and+ the three ``JobHandler`` implementations."""from __future__ import annotationsdiff --git a/conductor/__main__.py b/conductor/__main__.pyindex e111b5e88a..23fc33d7da 100644--- a/conductor/__main__.py+++ b/conductor/__main__.py@@ -1,7 +1,7 @@-"""``python -m conductor`` — CLI-Entry.+"""``python -m conductor`` — CLI entry point.-Delegiert an ``conductor.cli.main``. Pattern ist bewusst schlank: die-eigentliche Logik liegt in ``cli.py``, hier nur der Dispatch.+Delegates to ``conductor.cli.main``. The pattern is deliberately thin:+the actual logic lives in ``cli.py``, here it's only the dispatch."""from __future__ import annotationsdiff --git a/conductor/api/__init__.py b/conductor/api/__init__.pyindex 40f1f4d0dd..26f1e67c13 100644--- a/conductor/api/__init__.py+++ b/conductor/api/__init__.py@@ -1,14 +1,14 @@-"""Conductor-API — FastAPI-Router.+"""Conductor API — FastAPI router.-Zwei Deployment-Modi:+Two deployment modes:-1. **Standalone** — ``conductor.api.app.create_app()`` gibt eine fertig- konfigurierte ``FastAPI``-App. CLI ``python -m conductor serve`` nutzt- das.+1. **Standalone** — ``conductor.api.app.create_app()`` returns a fully+ configured ``FastAPI`` app. The CLI ``python -m conductor serve`` uses+ this.-2. **Embedded** — nur der ``router`` wird von Jarvis (oder einem anderen- Host) importiert und via ``app.include_router(router)`` eingehaengt.- Jarvis' WebServer macht genau das.+2. **Embedded** — only the ``router`` is imported by Jarvis (or another+ host) and mounted via ``app.include_router(router)``. Jarvis's+ web server does exactly that."""from __future__ import annotationsdiff --git a/conductor/api/app.py b/conductor/api/app.pyindex 85ba0ba94d..e3d2731952 100644--- a/conductor/api/app.py+++ b/conductor/api/app.py@@ -1,8 +1,8 @@-"""Standalone-FastAPI-App — fuer ``python -m conductor serve``.+"""Standalone FastAPI app — for ``python -m conductor serve``.-Im Embedded-Modus (Jarvis hat einen WebServer) wird nur ``router`` aus-``routes.py`` importiert; diese App hier ist der Entry-Point fuer reinen-Conductor-Betrieb.+In embedded mode (Jarvis has a web server), only ``router`` is imported+from ``routes.py``; this app here is the entry point for a standalone+Conductor deployment."""from __future__ import annotations@@ -19,10 +19,10 @@ def create_app(store: ConductorStore | None = None,start_scheduler: bool = True,) -> FastAPI:- """Erzeugt eine standalone FastAPI-App inkl. Store + Runner + Scheduler.+ """Creates a standalone FastAPI app including store + runner + scheduler.- Lifecycle wird ueber Startup/Shutdown-Events verdrahtet. ``store`` darf- vorgegeben werden (z.B. Tests mit tmp-DB); default ist+ Lifecycle is wired via startup/shutdown events. ``store`` can be+ provided explicitly (e.g. tests with a tmp DB); the default is``~/.conductor/conductor.sqlite``."""app = FastAPI(@@ -33,7 +33,7 @@ def create_app()app.add_middleware(CORSMiddleware,- allow_origins=["*"], # OSS-Default; per Env-Var kuerzbar in v0.2+ allow_origins=["*"], # OSS default; can be narrowed via env var in v0.2allow_credentials=True,allow_methods=["*"],allow_headers=["*"],@@ -52,14 +52,14 @@ def create_app(async def _startup() -> None:await active_store.init()await active_store.cleanup_interrupted_runs()- # Seed-Jobs beim ersten Start pflanzen.+ # Plant seed jobs on first startup.from ..core.seed import ensure_seed_jobstry:added = await ensure_seed_jobs(active_store)if added:import logginglogging.getLogger(__name__).info(- "Conductor-Seed: %d Jobs pflanzen", added,+ "Conductor seed: planting %d jobs", added,)except Exception: # noqa: BLE001passdiff --git a/conductor/api/routes.py b/conductor/api/routes.pyindex 445d0de5b1..7ae9da54a2 100644--- a/conductor/api/routes.py+++ b/conductor/api/routes.py@@ -1,11 +1,11 @@-"""REST-Endpoints fuer Conductor.+"""REST endpoints for Conductor.-Erwartet drei Objekte auf ``request.app.state``:+Expects three objects on ``request.app.state``:- ``conductor_store`` (``ConductorStore``)- ``conductor_runner`` (``Runner``)- ``conductor_scheduler`` (``Scheduler``) — optional-Ohne Store: 503.+Without a store: 503."""from __future__ import annotations@@ -27,14 +27,14 @@ router = APIRouter(prefix="/api/conductor", tags=["conductor"])def _require_store(request: Request) -> Any:store = getattr(request.app.state, "conductor_store", None)if store is None:- raise HTTPException(status_code=503, detail="ConductorStore nicht verfuegbar")+ raise HTTPException(status_code=503, detail="ConductorStore not available")return storedef _require_runner(request: Request) -> Any:runner = getattr(request.app.state, "conductor_runner", None)if runner is None:- raise HTTPException(status_code=503, detail="Conductor Runner nicht verfuegbar")+ raise HTTPException(status_code=503, detail="Conductor Runner not available")return runner@@ -95,7 +95,7 @@ async def list_jobs(request: Request) -> dict[str, Any]:@router.post("/jobs", status_code=201)async def create_job(job: Job, request: Request) -> dict[str, Any]:store = _require_store(request)- # Wenn Schedule ein Webhook ist ohne Token: eins generieren.+ # If the schedule is a webhook without a token: generate one.if job.schedule.type == "webhook" and len(job.schedule.token) < 16:new_token = secrets.token_urlsafe(24)job = job.model_copy(@@ -110,7 +110,7 @@ async def get_job(job_id: str, request: Request) -> dict[str, Any]:store = _require_store(request)row = await store.get_job(job_id)if row is None:- raise HTTPException(status_code=404, detail="Job nicht gefunden")+ raise HTTPException(status_code=404, detail="Job not found")summary = _row_to_summary(row)summary["recent_runs"] = await store.list_runs(job_id=job_id, limit=20)return summary@@ -123,7 +123,7 @@ async def patch_job(store = _require_store(request)row = await store.get_job(job_id)if row is None:- raise HTTPException(status_code=404, detail="Job nicht gefunden")+ raise HTTPException(status_code=404, detail="Job not found")if "enabled" in payload:await store.set_enabled(job_id, bool(payload["enabled"]))if not payload["enabled"]:@@ -136,7 +136,7 @@ async def delete_job(job_id: str, request: Request) -> dict[str, Any]:store = _require_store(request)ok = await store.delete_job(job_id)if not ok:- raise HTTPException(status_code=404, detail="Job nicht gefunden")+ raise HTTPException(status_code=404, detail="Job not found")return {"ok": True, "id": job_id}@@ -174,12 +174,12 @@ async def get_run(run_id: str, request: Request) -> dict[str, Any]:store = _require_store(request)run = await store.get_run(run_id)if run is None:- raise HTTPException(status_code=404, detail="Run nicht gefunden")+ raise HTTPException(status_code=404, detail="Run not found")return run# -----------------------------------------------------------------------# Webhook-Trigger (public, token-authenticated)+# Webhook trigger (public, token-authenticated)# ----------------------------------------------------------------------@router.post("/hooks/{token}")@@ -187,16 +187,16 @@ async def webhook_trigger(token: str, request: Request,body: dict[str, Any] = Body(default_factory=dict),) -> dict[str, Any]:- """Webhook-URL fuer extern gehostete Trigger. Token ist die Auth.+ """Webhook URL for externally hosted triggers. The token is the auth.- Beispiel: ``curl -X POST https://your-jarvis/api/conductor/hooks/<token>``+ Example: ``curl -X POST https://your-jarvis/api/conductor/hooks/<token>``"""store = _require_store(request)runner = _require_runner(request)row = await store.get_job_by_webhook_token(token)if row is None:- raise HTTPException(status_code=404, detail="Unbekannter Webhook-Token")+ raise HTTPException(status_code=404, detail="Unknown webhook token")if not row.get("enabled"):- raise HTTPException(status_code=409, detail="Job deaktiviert")+ raise HTTPException(status_code=409, detail="Job disabled")run_id = await runner.trigger(row["id"], trigger="webhook", input_data=body or {})return {"ok": True, "run_id": run_id, "job_id": row["id"]}diff --git a/conductor/cli.py b/conductor/cli.pyindex c54beca334..62d2757b86 100644--- a/conductor/cli.py+++ b/conductor/cli.py@@ -1,16 +1,16 @@-"""Conductor-CLI.+"""Conductor CLI.Subcommands:-- ``list`` — alle Jobs-- ``show <id>`` — Detail inkl. letzte Runs-- ``add <yaml>`` — Job aus YAML-File einlesen und upsert-en-- ``run <id>`` — Manual trigger; wartet auf Terminal-State-- ``runs`` — Run-Timeline (letzte 30)-- ``toggle <id>`` — enabled flippen-- ``delete <id>`` — Job entfernen-- ``serve [--port]`` — Standalone FastAPI auf Port 7777--DB-Pfad: ``~/.conductor/conductor.sqlite`` (oder ``CONDUCTOR_DB_PATH``).+- ``list`` — all jobs+- ``show <id>`` — detail incl. recent runs+- ``add <yaml>`` — read a job from a YAML file and upsert it+- ``run <id>`` — manual trigger; waits for the terminal state+- ``runs`` — run timeline (last 30)+- ``toggle <id>`` — flip enabled+- ``delete <id>`` — remove a job+- ``serve [--port]`` — standalone FastAPI on port 7777++DB path: ``~/.conductor/conductor.sqlite`` (or ``CONDUCTOR_DB_PATH``)."""from __future__ import annotations@@ -22,7 +22,7 @@ import sysfrom pathlib import Pathfrom typing import Any-# Windows-UTF-8+# Windows UTF-8if sys.platform == "win32":try:sys.stdout.reconfigure(encoding="utf-8", errors="replace") # type: ignore[union-attr]@@ -47,14 +47,14 @@ async def _with_store(fn):# -----------------------------------------------------------------------# Subcommand-Handler+# Subcommand handlers# ----------------------------------------------------------------------async def cmd_list(_: argparse.Namespace) -> int:async def _run(store):rows = await store.list_jobs()if not rows:- print("Keine Jobs. 'python -m conductor add <yaml>' legt welche an.")+ print("No jobs yet. 'python -m conductor add <yaml>' creates some.")return 0_print_jobs_table(rows)return 0@@ -65,7 +65,7 @@ async def cmd_show(args: argparse.Namespace) -> int:async def _run(store):row = await store.get_job(args.id)if row is None:- print(f"Job {args.id} nicht gefunden", file=sys.stderr)+ print(f"Job {args.id} not found", file=sys.stderr)return 1print(json.dumps({"id": row["id"],@@ -94,7 +94,7 @@ async def cmd_show(args: argparse.Namespace) -> int:async def cmd_add(args: argparse.Namespace) -> int:path = Path(args.yaml_file)if not path.exists():- print(f"Datei nicht gefunden: {path}", file=sys.stderr)+ print(f"File not found: {path}", file=sys.stderr)return 1from .core.seed import load_job_from_yaml@@ -103,11 +103,11 @@ async def cmd_add(args: argparse.Namespace) -> int:try:job = await load_job_from_yaml(path)except Exception as exc: # noqa: BLE001- print(f"YAML-Parse/Validate fehlgeschlagen: {exc}",+ print(f"YAML parse/validate failed: {exc}",file=sys.stderr)return 1jid = await store.upsert_job(job)- print(f"Job angelegt/aktualisiert: {jid} ({job.name})")+ print(f"Job created/updated: {jid} ({job.name})")return 0return await _with_store(_run)@@ -118,10 +118,10 @@ async def cmd_run(args: argparse.Namespace) -> int:async def _run(store):job = await store.get_job(args.id)if job is None:- print(f"Job {args.id} nicht gefunden", file=sys.stderr)+ print(f"Job {args.id} not found", file=sys.stderr)return 1- # Simple-Callback: loggt Lifecycle auf stderr+ # Simple callback: logs lifecycle to stderrdef _cb(event: str, payload: dict) -> None:print(f"[{event}] {json.dumps(payload, ensure_ascii=False)[:200]}",file=sys.stderr)@@ -136,16 +136,16 @@ async def cmd_run(args: argparse.Namespace) -> int:return 1run_id = await runner.trigger(args.id, trigger="manual",input_data=input_data)- print(f"Run gestartet: {run_id}", file=sys.stderr)+ print(f"Run started: {run_id}", file=sys.stderr)- # Poll bis Terminal-State+ # Poll until terminal statefor _ in range(args.timeout * 2):await asyncio.sleep(0.5)run = await store.get_run(run_id)if run and run["state"] in ("completed", "failed", "cancelled"):breakelse:- print("Timeout beim Warten auf Terminal-State", file=sys.stderr)+ print("Timeout waiting for terminal state", file=sys.stderr)return 2run = await store.get_run(run_id)@@ -154,7 +154,7 @@ async def cmd_run(args: argparse.Namespace) -> int:if run["state"] == "completed":print(run["output"])return 0- print(f"Run fehlgeschlagen: {run.get('error') or 'unknown'}",+ print(f"Run failed: {run.get('error') or 'unknown'}",file=sys.stderr)if run["output"]:print(run["output"])@@ -166,7 +166,7 @@ async def cmd_runs(args: argparse.Namespace) -> int:async def _run(store):runs = await store.list_runs(limit=args.limit)if not runs:- print("Noch keine Runs.")+ print("No runs yet.")return 0print(f"{'STATE':<10} {'TRIGGER':<9} {'STARTED':<20} "f"{'EXIT':<5} {'JOB':<36}")@@ -190,7 +190,7 @@ async def cmd_toggle(args: argparse.Namespace) -> int:async def _run(store):row = await store.get_job(args.id)if row is None:- print(f"Job {args.id} nicht gefunden", file=sys.stderr)+ print(f"Job {args.id} not found", file=sys.stderr)return 1new_enabled = not bool(row["enabled"])await store.set_enabled(args.id, new_enabled)@@ -205,31 +205,31 @@ async def cmd_delete(args: argparse.Namespace) -> int:async def _run(store):ok = await store.delete_job(args.id)if not ok:- print(f"Job {args.id} nicht gefunden", file=sys.stderr)+ print(f"Job {args.id} not found", file=sys.stderr)return 1- print(f"Job {args.id} entfernt")+ print(f"Job {args.id} removed")return 0return await _with_store(_run)async def cmd_seed(args: argparse.Namespace) -> int:- """Pflanzt die Seed-YAMLs aus conductor/seed/. --force uebrschreibt."""+ """Plants the seed YAMLs from conductor/seed/. --force overwrites."""from .core.seed import ensure_seed_jobsasync def _run(store):added = await ensure_seed_jobs(store, force=args.force)- verb = "ueberschrieben" if args.force else "neu angelegt"- print(f"{added} Seed-Jobs {verb}.")+ verb = "overwritten" if args.force else "newly created"+ print(f"{added} seed jobs {verb}.")return 0return await _with_store(_run)def cmd_serve(args: argparse.Namespace) -> int:- """Standalone FastAPI-Server. Nicht async — uvicorn.run ist blocking."""+ """Standalone FastAPI server. Not async — uvicorn.run is blocking."""try:import uvicornexcept ImportError:- print("uvicorn nicht installiert — pip install uvicorn[standard]",+ print("uvicorn not installed — pip install uvicorn[standard]",file=sys.stderr)return 1from .api.app import create_app@@ -240,7 +240,7 @@ def cmd_serve(args: argparse.Namespace) -> int:# -----------------------------------------------------------------------# Pretty-Print+# Pretty print# ----------------------------------------------------------------------def _print_jobs_table(rows: list[dict]) -> None:@@ -269,36 +269,36 @@ def main(argv: list[str] | None = None) -> int:)sub = p.add_subparsers(dest="cmd", required=True)- sub.add_parser("list", help="Alle Jobs auflisten")+ sub.add_parser("list", help="List all jobs")- show = sub.add_parser("show", help="Job-Detail")+ show = sub.add_parser("show", help="Job detail")show.add_argument("id")- add = sub.add_parser("add", help="Job aus YAML anlegen/aktualisieren")- add.add_argument("yaml_file", help="Pfad zur YAML-Datei")+ add = sub.add_parser("add", help="Create/update a job from YAML")+ add.add_argument("yaml_file", help="Path to the YAML file")- run_p = sub.add_parser("run", help="Job manuell triggern + auf Ende warten")+ run_p = sub.add_parser("run", help="Manually trigger a job + wait for it to finish")run_p.add_argument("id")run_p.add_argument("--input-json", default=None,- help="Optional: JSON-String als Input fuer den Run.")+ help="Optional: JSON string as input for the run.")run_p.add_argument("--timeout", type=int, default=120,- help="Max Wartezeit in Sekunden (Default 120).")+ help="Max wait time in seconds (default 120).")- runs = sub.add_parser("runs", help="Run-Timeline")+ runs = sub.add_parser("runs", help="Run timeline")runs.add_argument("--limit", type=int, default=30)- tog = sub.add_parser("toggle", help="enabled flippen")+ tog = sub.add_parser("toggle", help="Flip enabled")tog.add_argument("id")- dele = sub.add_parser("delete", help="Job entfernen")+ dele = sub.add_parser("delete", help="Remove a job")dele.add_argument("id")seed = sub.add_parser("seed",- help="Seed-YAMLs pflanzen (--force ueberschreibt)")+ help="Plant seed YAMLs (--force overwrites)")seed.add_argument("--force", action="store_true",- help="Bestehende Jobs mit gleicher ID ueberschreiben.")+ help="Overwrite existing jobs with the same ID.")- serve = sub.add_parser("serve", help="Standalone FastAPI auf 7777")+ serve = sub.add_parser("serve", help="Standalone FastAPI on 7777")serve.add_argument("--host", default="127.0.0.1")serve.add_argument("--port", type=int, default=7777)diff --git a/conductor/core/runner.py b/conductor/core/runner.pyindex a2987bc99b..5057dbdb6d 100644--- a/conductor/core/runner.py+++ b/conductor/core/runner.py@@ -1,10 +1,10 @@-"""Runner — dispatcht einen Job an seinen Handler und persistiert den Run.+"""Runner — dispatches a job to its handler and persists the run.-Ein Runner = viele gleichzeitige Runs. Jeder Run wird als eigener-``asyncio.Task`` gestartet; der Store bekommt die Terminal-State--Updates. Observer werden per ``on_event``-Callback informiert — so kann-Jarvis (oder jede andere Embed-Situation) Live-Updates im Frontend-rendern ohne vom Conductor-Package abhaengig zu sein.+One runner = many concurrent runs. Each run is started as its own+``asyncio.Task``; the store gets the terminal-state updates. Observers+are informed via the ``on_event`` callback — so Jarvis (or any other+embed situation) can render live updates in the frontend without+depending on the Conductor package."""from __future__ import annotations@@ -23,12 +23,12 @@ if TYPE_CHECKING:log = logging.getLogger(__name__)-#: Callback-Signatur — (event_name, payload)+#: Callback signature — (event_name, payload)EventCallback = Callable[[str, dict[str, Any]], Any]class Runner:- """Fuehrt einen Job-Run end-to-end aus und persistiert alles."""+ """Runs a job end-to-end and persists everything."""def __init__(self,@@ -50,10 +50,10 @@ class Runner:trigger: str = "manual",input_data: dict[str, Any] | None = None,) -> str:- """Startet einen neuen Run (fire-and-forget). Returnt die Run-ID."""+ """Starts a new run (fire-and-forget). Returns the run ID."""job_row = await self._store.get_job(job_id)if job_row is None:- raise KeyError(f"Job {job_id} nicht gefunden")+ raise KeyError(f"Job {job_id} not found")run_id = await self._store.create_run(job_id, trigger=trigger, input_data=input_data,)@@ -75,10 +75,10 @@ class Runner:job_id = job_row["id"]spec_json = job_row["spec_json"]- # JobSpec aus JSON zurueckbauen — wir wissen den Typ aus 'type'+ # Reconstruct JobSpec from JSON — we know the type from 'type'try:spec_data = json.loads(spec_json)- # Pydantic-Discriminator macht die Typ-Zuordnung selbst.+ # Pydantic's discriminator handles the type mapping itself.from pydantic import TypeAdapterspec = TypeAdapter(JobSpec).validate_python(spec_data)except Exception as exc: # noqa: BLE001@@ -95,7 +95,7 @@ class Runner:if handler is None:await self._store.update_run(run_id, state="failed",- error=f"kein Handler fuer type={spec.type}",+ error=f"no handler for type={spec.type}",)self._emit("run.failed", {"run_id": run_id, "job_id": job_id,@@ -153,7 +153,7 @@ class Runner:returntry:res = self._on_event(event, payload)- # Async callback ist ok — wir warten nicht, aber starten ihn.+ # An async callback is fine — we don't await it, but we start it.if asyncio.iscoroutine(res):asyncio.create_task(res)except Exception as exc: # noqa: BLE001diff --git a/conductor/core/scheduler.py b/conductor/core/scheduler.pyindex f6b822b649..ae11faa1a4 100644--- a/conductor/core/scheduler.py+++ b/conductor/core/scheduler.py@@ -1,10 +1,10 @@-"""Scheduler — poll-basierte Cron+Interval-Ausfuehrung.+"""Scheduler — poll-based cron+interval execution.-Simpelstes funktionales Design: ein asyncio-Loop, der pro Tick alle-aktiven Jobs inspiziert und schaut, welches ``next_run_at_ns`` faellig-ist. Keine eigene Heap-Struktur — die Job-Anzahl pro Conductor-Instanz-liegt realistisch bei <100, und SQLite-Query ist bei der Groesse nicht-der Flaschenhals.+The simplest possible functional design: an asyncio loop that, on each+tick, inspects all active jobs and checks which ``next_run_at_ns`` is+due. No dedicated heap structure — the job count per Conductor instance+realistically stays below 100, and at that size the SQLite query is+not the bottleneck."""from __future__ import annotations@@ -89,8 +89,8 @@ class Scheduler:if stored_next <= now_ns:due_ids.append(row["id"])- # neuen next_run_at_ns setzen, bevor wir triggern,- # damit keine Doppel-Triggering bei langsamer Ausfuehrung.+ # Set a new next_run_at_ns before we trigger, so slow+ # execution doesn't cause a double trigger.next_after = _compute_next(sched_type, expr,max(now_ns + 60_000_000_000, stored_next),@@ -107,7 +107,7 @@ class Scheduler:try:await self._runner.trigger(jid, trigger=trigger)except Exception as exc: # noqa: BLE001- log.warning("Scheduler-Trigger fuer %s failed: %s", jid, exc)+ log.warning("Scheduler trigger for %s failed: %s", jid, exc)if upcoming_min is None:return 30.0@@ -123,7 +123,7 @@ class Scheduler:# -----------------------------------------------------------------------# Next-Run-Berechnung+# Next-run computation# ----------------------------------------------------------------------def _compute_next(sched_type: str, expr: str, base_ns: int) -> int | None:diff --git a/conductor/core/schema.py b/conductor/core/schema.pyindex 1247bb7035..9c071d9ced 100644--- a/conductor/core/schema.py+++ b/conductor/core/schema.py@@ -1,18 +1,18 @@-"""Pydantic-Schema — Jobs, Runs, Schedules.+"""Pydantic schema — jobs, runs, schedules.-Drei zentrale Design-Entscheidungen:+Three central design decisions:-1. **Jobs als Discriminated-Union von JobSpecs.** Neue Job-Types sind- eine 3-Datei-Aenderung (Spec-Model, Handler, YAML-Beispiel). Kein- Plugin-System noetig fuer MVP.+1. **Jobs as a discriminated union of JobSpecs.** A new job type is+ a 3-file change (spec model, handler, YAML example). No plugin+ system needed for the MVP.-2. **Schedule ebenfalls als Discriminated-Union.** Cron, Interval,- Manual, Webhook — das deckt alles vom User-Klick bis zum externen- Push-Trigger ab.+2. **Schedule is also a discriminated union.** Cron, interval,+ manual, webhook — that covers everything from a user click to an+ external push trigger.-3. **Runs haben Steps**, auch wenn aktuell jeder Job nur einen Step hat.- Das macht uns v0.2-ready fuer Multi-Step-Agenten (LLM-Tool-Use-Loop,- bei dem jeder Tool-Call eigener Step ist).+3. **Runs have steps**, even though currently every job has only one+ step. That makes us v0.2-ready for multi-step agents (an LLM+ tool-use loop where every tool call is its own step)."""from __future__ import annotations@@ -27,40 +27,40 @@ from pydantic import BaseModel, ConfigDict, Field# ---------------------------------------------------------------------class CronSchedule(BaseModel):- """Cron-Expression mit 5 Feldern (Standard-Syntax, via croniter)."""+ """Cron expression with 5 fields (standard syntax, via croniter)."""model_config = ConfigDict(frozen=True, extra="forbid")type: Literal["cron"] = "cron"expression: str = Field(min_length=9, max_length=128,- description="z.B. '0 9 * * *' fuer 9:00 taeglich")+ description="e.g. '0 9 * * *' for 9:00 daily")timezone: str = Field(default="local")class IntervalSchedule(BaseModel):- """Wiederholung alle N Sekunden — simpler als Cron."""+ """Repeats every N seconds — simpler than cron."""model_config = ConfigDict(frozen=True, extra="forbid")type: Literal["interval"] = "interval"seconds: int = Field(ge=10, le=30 * 24 * 3600,- description="Minimum 10s (Rate-Limit-Schutz), "- "Max 30 Tage.")+ description="Minimum 10s (rate-limit protection), "+ "max 30 days.")class ManualSchedule(BaseModel):- """Nur auf Knopfdruck / CLI-Run."""+ """Only on button press / CLI run."""model_config = ConfigDict(frozen=True, extra="forbid")type: Literal["manual"] = "manual"class WebhookSchedule(BaseModel):- """Trigger via HTTP-POST auf ``/api/conductor/hooks/<token>``.+ """Trigger via HTTP POST to ``/api/conductor/hooks/<token>``.- Der ``token`` wird beim Anlegen generiert, damit die Webhook-URL- unguessable ist. Runs bekommen den POST-Body als ``input``.+ The ``token`` is generated on creation so the webhook URL is+ unguessable. Runs get the POST body as ``input``."""model_config = ConfigDict(frozen=True, extra="forbid")type: Literal["webhook"] = "webhook"token: str = Field(min_length=16, max_length=64,- description="URL-safe Hex-Token, wird beim Anlegen "- "generiert.")+ description="URL-safe hex token, generated on "+ "creation.")Schedule = Annotated[@@ -70,11 +70,11 @@ Schedule = Annotated[# ----------------------------------------------------------------------# Job-Specs — was beim Trigger ausgefuehrt wird+# Job specs — what runs when triggered# ---------------------------------------------------------------------class ShellJobSpec(BaseModel):- """Shell-Command mit Args, Timeout, Working-Directory."""+ """Shell command with args, timeout, working directory."""model_config = ConfigDict(frozen=True, extra="forbid")type: Literal["shell"] = "shell"command: str = Field(min_length=1, max_length=4096)@@ -84,10 +84,10 @@ class ShellJobSpec(BaseModel):class HttpJobSpec(BaseModel):- """HTTP-Request — GET/POST/PUT/DELETE.+ """HTTP request — GET/POST/PUT/DELETE.- Response-Body (string, max 64 KB) wird als Run-Output persistiert.- ``expect_status`` definiert Success-Kriterium; default ``2xx``.+ The response body (string, max 64 KB) is persisted as the run output.+ ``expect_status`` defines the success criterion; default ``2xx``."""model_config = ConfigDict(frozen=True, extra="forbid")type: Literal["http"] = "http"@@ -97,25 +97,25 @@ class HttpJobSpec(BaseModel):body: str | None = Nonetimeout_s: float = Field(default=30.0, ge=1.0, le=300.0)expect_status: str = Field(default="2xx",- description="'2xx', '200', '3xx' oder exakter Code.")+ description="'2xx', '200', '3xx', or an exact code.")class AgentJobSpec(BaseModel):- """LLM-Agent-Call — single-turn in v0.1, tool-use in v0.2.+ """LLM agent call — single-turn in v0.1, tool-use in v0.2.Providers:- - ``gemini`` — **Google-AI-Studio-Default.** Nutzt ``google-genai``-- SDK, Key aus ``GEMINI_API_KEY`` oder ``GOOGLE_AIStudio_API_KEY``.- Default-Model ``gemini-3.1-pro`` (Frontier).- - ``anthropic`` — fuer User mit OpenClaw-Subscription. Shellt das- lokale ``claude``-CLI (OAuth-Session des Max-Plan-Login), braucht- keinen API-Key. Modelle: ``sonnet``, ``opus``, ``haiku``, oder- voller Name (``claude-sonnet-4-6``).- - ``anthropic`` — direkter API-Call via ``ANTHROPIC_API_KEY`` ENV.- Fuer User ohne Subscription.+ - ``gemini`` — **Google AI Studio default.** Uses the ``google-genai``+ SDK, key from ``GEMINI_API_KEY`` or ``GOOGLE_AIStudio_API_KEY``.+ Default model ``gemini-3.1-pro`` (frontier).+ - ``anthropic`` — for users with an OpenClaw subscription. Shells out+ to the local ``claude`` CLI (OAuth session from the Max-plan login),+ needs no API key. Models: ``sonnet``, ``opus``, ``haiku``, or the+ full name (``claude-sonnet-4-6``).+ - ``anthropic`` — direct API call via the ``ANTHROPIC_API_KEY`` env var.+ For users without a subscription.- ``openai`` — ``OPENAI_API_KEY``.- - ``ollama`` — lokal, kein Key. Default-Host ``http://localhost:11434``.+ - ``ollama`` — local, no key. Default host ``http://localhost:11434``."""model_config = ConfigDict(frozen=True, extra="forbid")type: Literal["agent"] = "agent"@@ -124,9 +124,9 @@ class AgentJobSpec(BaseModel):] = "gemini"model: str = Field(default="gemini-3.1-pro", min_length=1, max_length=128,- description="Alias ('sonnet', 'opus') oder full name "+ description="Alias ('sonnet', 'opus') or full name ""('gemini-3.1-pro', 'claude-sonnet-4-6', 'gpt-4o', 'llama3.1'). "- "Default: gemini-3.1-pro (passend zum Default-Provider 'gemini').",+ "Default: gemini-3.1-pro (matching the default provider 'gemini').",)system_prompt: str = Field(default="", max_length=8192)user_prompt: str = Field(min_length=1, max_length=32_768)@@ -148,10 +148,10 @@ RunState = Literal["pending", "running", "completed", "failed", "cancelled"]class Job(BaseModel):- """Blueprint eines wiederholbaren Jobs — persistiert in ``jobs``-Tabelle.+ """Blueprint of a repeatable job — persisted in the ``jobs`` table.- Die ``spec`` ist der komplette Job-Payload (Typ + Args) und wird als- JSON serialisiert. Der ``schedule`` ebenfalls.+ The ``spec`` is the complete job payload (type + args) and is+ serialized as JSON. So is ``schedule``."""model_config = ConfigDict(frozen=True, extra="forbid")@@ -166,7 +166,7 @@ class Job(BaseModel):class Run(BaseModel):- """Ein konkreter Lauf eines Jobs."""+ """One concrete run of a job."""model_config = ConfigDict(frozen=True, extra="forbid")id: UUID = Field(default_factory=uuid4)@@ -183,7 +183,7 @@ class Run(BaseModel):class RunStep(BaseModel):- """Sub-Step eines Runs — fuer v0.2 Multi-Step-Agents."""+ """Sub-step of a run — for v0.2 multi-step agents."""model_config = ConfigDict(frozen=True, extra="forbid")run_id: UUIDdiff --git a/conductor/core/seed.py b/conductor/core/seed.pyindex 6a68c373b1..998f969c6c 100644--- a/conductor/core/seed.py+++ b/conductor/core/seed.py@@ -1,11 +1,11 @@-"""Seed-Jobs laden — YAML-Dateien aus ``conductor/seed/``.+"""Load seed jobs — YAML files from ``conductor/seed/``.-Anders als bei Jarvis-Workflows (hardcoded Python-Factories) pflegen wir-die Conductor-Seeds als **YAML-Dateien**. Das ist der Job-Format, das-auch User eintippen — wir sind damit unser eigener Testfall.+Unlike Jarvis workflows (hardcoded Python factories), we maintain the+Conductor seeds as **YAML files**. That's the same job format users+type in themselves — we're our own test case for it.-Idempotenz: Die UUID jedes Seed-Jobs steht im YAML und wird bei-wiederholtem Aufruf respektiert.+Idempotency: each seed job's UUID lives in the YAML and is respected+across repeated calls."""from __future__ import annotations@@ -24,7 +24,7 @@ SEED_YAML_DIR = Path(__file__).resolve().parent.parent / "seed"async def load_job_from_yaml(yaml_path: Path) -> Job:- """Parsed eine YAML-Datei in ein validiertes ``Job``-Modell."""+ """Parses a YAML file into a validated ``Job`` model."""data: dict[str, Any] = yaml.safe_load(yaml_path.read_text(encoding="utf-8"))return Job.model_validate(data)@@ -35,16 +35,16 @@ async def ensure_seed_jobs(*,force: bool = False,) -> int:- """Liest alle ``*.yaml`` aus ``seed_dir`` und upsert-ed Jobs.+ """Reads all ``*.yaml`` files from ``seed_dir`` and upserts jobs.Args:- store: Persistenz-Store.- seed_dir: Override fuer den Seed-Ordner.- force: Wenn True, bestehende Jobs werden ueberschrieben (nuetzlich- nach einem Seed-YAML-Update). Default False: fehlende Jobs- anlegen, bestehende in Ruhe lassen.+ store: The persistence store.+ seed_dir: Override for the seed folder.+ force: If True, existing jobs are overwritten (useful after a+ seed YAML update). Default False: create missing jobs,+ leave existing ones alone.- Returnt die Anzahl tatsaechlich geschriebener Jobs.+ Returns the number of jobs actually written."""root = seed_dir or SEED_YAML_DIRif not root.exists():@@ -54,7 +54,7 @@ async def ensure_seed_jobs(try:job = await load_job_from_yaml(yaml_file)except Exception as exc: # noqa: BLE001- log.warning("Seed-YAML %s ignoriert: %s", yaml_file.name, exc)+ log.warning("Seed YAML %s ignored: %s", yaml_file.name, exc)continueexisting = await store.get_job(str(job.id))if existing is not None and not force:@@ -62,6 +62,6 @@ async def ensure_seed_jobs(await store.upsert_job(job)added += 1if added:- log.info("Conductor-Seed: %d Jobs %s aus %s",- added, "force-upgedatet" if force else "angelegt", root)+ log.info("Conductor seed: %d jobs %s from %s",+ added, "force-updated" if force else "created", root)return addeddiff --git a/conductor/core/store.py b/conductor/core/store.pyindex d22687ed44..2e9ae2bca2 100644--- a/conductor/core/store.py+++ b/conductor/core/store.py@@ -1,10 +1,10 @@-"""ConductorStore — aiosqlite-Persistenz.+"""ConductorStore — aiosqlite persistence.-Pattern identisch zu ``jarvis.workflows.store``: Lazy-Init via ``init()``,-Context-Manager-Support, additives Schema via ``executescript``.+Pattern identical to ``jarvis.workflows.store``: lazy init via ``init()``,+context-manager support, additive schema via ``executescript``.-Default-DB-Path: ``~/.conductor/conductor.sqlite`` — bewusst separat von-Jarvis, damit Conductor auch ohne Jarvis-Installation laeuft.+Default DB path: ``~/.conductor/conductor.sqlite`` — deliberately+separate from Jarvis, so Conductor also runs without a Jarvis install."""from __future__ import annotations@@ -63,8 +63,8 @@ class ConductorStore:def _require_conn(self) -> aiosqlite.Connection:if self._conn is None:raise RuntimeError(- "ConductorStore nicht initialisiert — rufe init() oder "- "nutze 'async with'."+ "ConductorStore not initialized — call init() or "+ "use 'async with'.")return self._conn@@ -73,11 +73,11 @@ class ConductorStore:# ------------------------------------------------------------------async def upsert_job(self, job: Job) -> str:- """Legt einen Job an oder ueberschreibt eine bestehende ID.+ """Creates a job or overwrites an existing ID.- Schreibt auch denormalisierte Felder (``type``, ``schedule_type``,- ``schedule_expr``, ``webhook_token``) die der Scheduler fuer- schnelle Queries braucht.+ Also writes denormalized fields (``type``, ``schedule_type``,+ ``schedule_expr``, ``webhook_token``) that the scheduler needs+ for fast queries."""conn = self._require_conn()spec = job.spec@@ -248,8 +248,8 @@ class ConductorStore:if not sets:returnparams.append(run_id)- # ``sets`` wird statisch aus Literal-Fragmenten aufgebaut — kein- # User-Input fliesst in den SQL-String.+ # ``sets`` is built statically from literal fragments — no+ # user input flows into the SQL string.sql = f"UPDATE runs SET {', '.join(sets)} WHERE id = ?" # noqa: S608await conn.execute(sql, tuple(params))@@ -295,7 +295,7 @@ class ConductorStore:return [dict(r) for r in rows]async def cleanup_interrupted_runs(self) -> int:- """Startup: alle running/pending → failed (app-exit detected)."""+ """Startup: all running/pending → failed (app-exit detected)."""conn = self._require_conn()cur = await conn.execute("""diff --git a/conductor/jobs/__init__.py b/conductor/jobs/__init__.pyindex 7aede47ade..b54b4e18a9 100644--- a/conductor/jobs/__init__.py+++ b/conductor/jobs/__init__.py@@ -1,8 +1,8 @@-"""Job-Handler — drei Implementations, alle via ``JobHandler``-Protocol.+"""Job handlers — three implementations, all via the ``JobHandler`` protocol.-Registry-Pattern: ``HANDLERS[spec.type]`` gibt den passenden Handler-zurueck. Neue Job-Types sind eine 2-Datei-Aenderung (Spec-Model in-``core/schema.py`` + Handler hier).+Registry pattern: ``HANDLERS[spec.type]`` returns the matching handler.+A new job type is a 2-file change (spec model in ``core/schema.py`` ++handler here)."""from __future__ import annotationsdiff --git a/conductor/jobs/agent.py b/conductor/jobs/agent.pyindex aad2c2cf0a..80feea177f 100644--- a/conductor/jobs/agent.py+++ b/conductor/jobs/agent.py@@ -1,17 +1,17 @@-"""AgentHandler — Single-Turn LLM-Call fuer drei Provider.+"""AgentHandler — single-turn LLM call for three providers.-v0.1 ist Single-Turn: kein Tool-Use, kein Multi-Step. Das deckt 80% der-Agent-Jobs ab ("Fasse Log zusammen", "Schreibe Standup", "Analysiere-Metrik"). Tool-Use kommt v0.2 als eigener RunStep-Loop.+v0.1 is single-turn: no tool use, no multi-step. That covers 80% of+agent jobs ("summarize this log", "write a standup", "analyze this+metric"). Tool use arrives in v0.2 as its own RunStep loop.-Provider-Env-Vars:+Provider env vars:- ``anthropic`` → ``ANTHROPIC_API_KEY``- ``openai`` → ``OPENAI_API_KEY``- ``ollama`` → ``OLLAMA_HOST`` (default http://localhost:11434)-Kosten-Tracking: ``input_tokens`` + ``output_tokens`` werden aus der-Provider-Response extrahiert. Fuer USD-Cost brauchen wir Pricing-Tables-pro Modell — v0.2. Aktuell nur Token-Counts in Metrics.+Cost tracking: ``input_tokens`` + ``output_tokens`` are extracted from+the provider response. For USD cost we'd need per-model pricing+tables — v0.2. Currently only token counts in metrics."""from __future__ import annotations@@ -61,10 +61,10 @@ class AgentHandler:self, model: str, system: str, user: str,max_tokens: int, temperature: float,) -> HandlerResult:- """Single-turn Google-AI-Studio-Call via google-genai SDK.+ """Single-turn Google AI Studio call via the google-genai SDK.- Key wird in Reihenfolge probiert: GEMINI_API_KEY, GOOGLE_AIStudio_- API_KEY, GOOGLE_API_KEY. Default-Model wenn leer: ``gemini-3.1-pro``.+ Key is tried in order: GEMINI_API_KEY, GOOGLE_AIStudio_+ API_KEY, GOOGLE_API_KEY. Default model when empty: ``gemini-3.1-pro``."""api_key: str | None = Nonefor env_var in ("GEMINI_API_KEY", "GOOGLE_AIStudio_API_KEY",@@ -77,9 +77,9 @@ class AgentHandler:return HandlerResult(success=False, output="", exit_code=-1,error=(- "Kein Gemini-API-Key gesetzt — "- "setx GEMINI_API_KEY <key> und Terminal neu starten. "- "Key holen: https://aistudio.google.com/apikey"+ "No Gemini API key set — "+ "run setx GEMINI_API_KEY <key> and restart your terminal. "+ "Get a key at: https://aistudio.google.com/apikey"),)@@ -88,7 +88,7 @@ class AgentHandler:except ImportError:return HandlerResult(success=False, output="", exit_code=-1,- error="google-genai-Package fehlt: pip install google-genai",+ error="google-genai package missing: pip install google-genai",)effective_model = model or "gemini-3.1-pro"@@ -117,8 +117,8 @@ class AgentHandler:duration_ms = int((time.perf_counter() - start) * 1000)text = ""- # google-genai: resp.text ist der konsolidierte Text, oder manuell- # aus candidates[0].content.parts extrahieren.+ # google-genai: resp.text is the consolidated text, or extract+ # manually from candidates[0].content.parts.text = getattr(resp, "text", None) or ""if not text:for cand in getattr(resp, "candidates", None) or []:@@ -162,14 +162,14 @@ class AgentHandler:if not api_key:return HandlerResult(success=False, output="", exit_code=-1,- error="ANTHROPIC_API_KEY nicht gesetzt — setx ANTHROPIC_API_KEY <key>",+ error="ANTHROPIC_API_KEY not set — run setx ANTHROPIC_API_KEY <key>",)try:import anthropicexcept ImportError:return HandlerResult(success=False, output="", exit_code=-1,- error="anthropic-Package fehlt: pip install anthropic",+ error="anthropic package missing: pip install anthropic",)start = time.perf_counter()@@ -220,14 +220,14 @@ class AgentHandler:if not api_key:return HandlerResult(success=False, output="", exit_code=-1,- error="OPENAI_API_KEY nicht gesetzt",+ error="OPENAI_API_KEY not set",)try:import openaiexcept ImportError:return HandlerResult(success=False, output="", exit_code=-1,- error="openai-Package fehlt: pip install openai",+ error="openai package missing: pip install openai",)start = time.perf_counter()@@ -330,7 +330,7 @@ _TEMPLATE_RE = re.compile(r"\{\{\s*([^}]+?)\s*\}\}")def _expand_template(s: str, input_data: dict[str, Any]) -> str:- """``{{input.X}}`` → Wert aus dem Input-Dict."""+ """``{{input.X}}`` → value from the input dict."""def repl(m: re.Match[str]) -> str:token = m.group(1).strip()if token.startswith("input."):diff --git a/conductor/jobs/base.py b/conductor/jobs/base.pyindex 93d2fce540..d9be0fd7ba 100644--- a/conductor/jobs/base.py+++ b/conductor/jobs/base.py@@ -1,4 +1,4 @@-"""Handler-Protocol: jeder Job-Type implementiert ``async def execute(spec, input)``."""+"""Handler protocol: every job type implements ``async def execute(spec, input)``."""from __future__ import annotationsfrom dataclasses import dataclass, field@@ -7,11 +7,11 @@ from typing import Any, Protocol, runtime_checkable@dataclassclass HandlerResult:- """Was ein Handler zurueckgibt.+ """What a handler returns.- Der Runner persistiert das zu einer Run-Zeile. ``output`` ist der- Primaer-Payload (stdout / response-body / LLM-text). ``metrics`` ist- strukturierte Side-Info (http-status, tokens, cost, duration).+ The runner persists this to a run row. ``output`` is the primary+ payload (stdout / response body / LLM text). ``metrics`` is+ structured side info (http status, tokens, cost, duration)."""success: booloutput: str@@ -22,14 +22,14 @@ class HandlerResult:@runtime_checkableclass JobHandler(Protocol):- """Strukturelles Protocol — jeder Handler ist runtime-checkable."""+ """Structural protocol — every handler is runtime-checkable."""async def execute(self,spec: Any,input_data: dict[str, Any],) -> HandlerResult:- """Fuehrt einen Job aus. ``spec`` ist das jeweilige JobSpec-Modell,- ``input_data`` kommt aus manual-trigger / webhook-body / cron-default.+ """Runs a job. ``spec`` is the respective JobSpec model,+ ``input_data`` comes from a manual trigger / webhook body / cron default."""...diff --git a/conductor/jobs/shell.py b/conductor/jobs/shell.pyindex 3e46ce7198..1d2cf1ed98 100644--- a/conductor/jobs/shell.py+++ b/conductor/jobs/shell.py@@ -1,4 +1,4 @@-"""ShellHandler — startet einen Subprozess, capture stdout/stderr."""+"""ShellHandler — starts a subprocess, captures stdout/stderr."""from __future__ import annotationsimport asyncio@@ -18,7 +18,7 @@ class ShellHandler:async def execute(self,spec: Any,- input_data: dict[str, Any], # noqa: ARG002 — fuer einheitliches Protocol+ input_data: dict[str, Any], # noqa: ARG002 — for a uniform protocol) -> HandlerResult:try:argv = shlex.split(spec.command, posix=False)@@ -27,8 +27,9 @@ class ShellHandler:success=False, output="", exit_code=-1,error=f"command parse error: {exc}",)- # Auf Windows laesst shlex posix=False die aeusseren Quotes im- # Token — strippen, sonst meint subprocess den Filename incl. "".+ # On Windows, shlex posix=False leaves the outer quotes in the+ # token — strip them, otherwise subprocess treats the filename+ # as including the "".argv = [a[1:-1] if len(a) >= 2 and a[0] == a[-1] and a[0] in ('"', "'")else adiff --git a/conductor/seed/daily_standup.yaml b/conductor/seed/daily_standup.yamlindex e92b71c685..6cb29964a2 100644--- a/conductor/seed/daily_standup.yaml+++ b/conductor/seed/daily_standup.yaml@@ -1,11 +1,11 @@-# Demo-Job 2 — LLM-Agent schreibt jeden Werktag 9:00 eine Standup-Notiz.-# Default-Provider: gemini mit gemini-3.1-pro (Frontier). Voraussetzung:-# GEMINI_API_KEY gesetzt (Key von https://aistudio.google.com/apikey).+# Demo job 2 — an LLM agent writes a standup note every weekday at 9:00.+# Default provider: gemini with gemini-3.1-pro (frontier). Requires+# GEMINI_API_KEY to be set (get a key at https://aistudio.google.com/apikey).id: 7b4d7e01-5c11-4c57-9c1d-10cc00000002name: Daily Standupdescription: >- Werktags 9:00 — Gemini 3.1 Pro generiert eine kurze Standup-Notiz.- Standard-Provider ist gemini via Google AI Studio API-Key.+ Weekdays 9:00 — Gemini 3.1 Pro generates a short standup note.+ Default provider is gemini via a Google AI Studio API key.enabled: truetags: [demo, agent, gemini]spec:@@ -13,12 +13,11 @@ spec:provider: geminimodel: gemini-3.1-prosystem_prompt: >- Du bist ein knapper, praegnanter Work-Coach. Keine Einleitung,- kein Small-Talk — nur die Notiz selbst.+ You are a terse, to-the-point work coach. No introduction,+ no small talk — just the note itself.user_prompt: >- Schreibe eine 3-Punkte-Standup-Notiz fuer heute. Jeder Punkt- maximal ein Satz, auf Deutsch. Thema: Fokus-Arbeit an einem- Software-Projekt.+ Write a 3-point standup note for today. Each point at most+ one sentence. Topic: focused work on a software project.max_output_tokens: 400temperature: 0.7schedule:diff --git a/conductor/seed/log_cleanup.yaml b/conductor/seed/log_cleanup.yamlindex 6bad255e20..9f43936845 100644--- a/conductor/seed/log_cleanup.yaml+++ b/conductor/seed/log_cleanup.yaml@@ -1,10 +1,10 @@-# Demo-Job 3 — Shell-Command, manueller Trigger.-# Zeigt wie man einen OS-nativen Befehl als Conductor-Job rahmt.+# Demo job 3 — shell command, manual trigger.+# Shows how to frame an OS-native command as a Conductor job.id: 7b4d7e01-5c11-4c57-9c1d-10cc00000003name: Data-Dir Listingdescription: >- Listet das Jarvis-Data-Verzeichnis auf. Demo-Shell-Job, manuell- triggerbar. Kein destruktives Kommando — wir loeschen nichts.+ Lists the Jarvis data directory. Demo shell job, manually+ triggerable. No destructive command — we delete nothing.enabled: truetags: [demo, shell]spec:diff --git a/conductor/seed/url_healthcheck.yaml b/conductor/seed/url_healthcheck.yamlindex 107bb8b22d..e47cddae1f 100644--- a/conductor/seed/url_healthcheck.yaml+++ b/conductor/seed/url_healthcheck.yaml@@ -1,10 +1,10 @@-# Demo-Job 1 — HTTP-Healthcheck alle 5 Minuten.-# Dieses YAML ist exakt das Pydantic-Job-Modell.+# Demo job 1 — HTTP healthcheck every 5 minutes.+# This YAML is exactly the Pydantic job model.id: 7b4d7e01-5c11-4c57-9c1d-10cc00000001name: GitHub-API Zendescription: >- Pingt github.com/zen alle 5 Minuten und checkt 2xx. Minimaler- Live-Demo-Job; zeigt wie HTTP-Monitoring aussieht.+ Pings github.com/zen every 5 minutes and checks for 2xx. A minimal+ live demo job; shows what HTTP monitoring looks like.enabled: truetags: [demo, monitor, http]spec:diff --git a/conductor/seed/webhook_demo.yaml b/conductor/seed/webhook_demo.yamlindex 75d96b16d3..a895dbae3e 100644--- a/conductor/seed/webhook_demo.yaml+++ b/conductor/seed/webhook_demo.yaml@@ -1,12 +1,12 @@-# Demo-Job 4 — Webhook-triggered Shell. URL ist im Dashboard sichtbar:+# Demo job 4 — webhook-triggered shell. URL is visible in the dashboard:# POST http://127.0.0.1:47821/api/conductor/hooks/<token>id: 7b4d7e01-5c11-4c57-9c1d-10cc00000004name: Webhook-Pingdescription: >- Beispiel fuer extern-getriggerte Jobs. Ruf die Webhook-URL von- wo auch immer (GitHub-Action, Zapier, Shortcuts.app, curl) — dieser- Job fired dann einmalig. Der Token wird beim Seeding auf den- hier hinterlegten gesetzt; fuer Production neu generieren lassen.+ Example of an externally-triggered job. Call the webhook URL from+ wherever (GitHub Action, Zapier, Shortcuts.app, curl) — this+ job fires once. The token is set to the one stored here during+ seeding; regenerate it for production.enabled: truetags: [demo, webhook]spec:diff --git a/conftest.py b/conftest.pyindex 0a5bc24bff..588f8a9f05 100644--- a/conftest.py+++ b/conftest.py@@ -1,8 +1,8 @@-"""Repo-Root-conftest fuer Pytest-Discovery.+"""Repo-root conftest for pytest discovery.-Pytest laedt diese Datei VOR allen Test-Modulen und VOR `tests/conftest.py`.-Wir nutzen das, um den Repo-Root in `sys.path` aufzunehmen, damit Tests-Top-Level-Module wie `ui.orb.bus_bridge` importieren koennen.+Pytest loads this file BEFORE all test modules and BEFORE `tests/conftest.py`.+We use this to add the repo root to `sys.path` so tests can import+top-level modules like `ui.orb.bus_bridge`."""from __future__ import annotationsdiff --git a/pyproject.toml b/pyproject.tomlindex b8f213a3a3..18dea382fa 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -13,7 +13,7 @@ authors = [{ name = "Personal Jarvis Maintainers" }]dependencies = ["anthropic>=0.96",- "openai>=1.30", # 1.30+ ist Mindestversion fuer stream_options (Juni 2024)+ "openai>=1.30", # 1.30+ is the minimum version required for stream_options (June 2024)"google-genai>=1.0","pydantic>=2.9,<3.0","pydantic-settings>=2.6",@@ -77,12 +77,12 @@ dependencies = ["croniter>=6.0","gitpython>=3.1","watchdog>=5.0",- # Atomare TOML-Edits aus der Desktop-App (Phase 1b: Provider-Persistenz)+ # Atomic TOML edits from the desktop app (Phase 1b: provider persistence)"tomlkit>=0.12",# === F-FRIENDS [F0+F1] · feature/friends-section · ruben-2026-04-30 ===- # Phase F0 — async SQLite fuer FriendRegistry (vorher transitive via chromadb).+ # Phase F0 — async SQLite for FriendRegistry (previously transitive via chromadb)."aiosqlite>=0.21",- # Phase F1 — Telegram-Channel-Bot via long-polling (ChannelAdapter).+ # Phase F1 — Telegram channel bot via long-polling (ChannelAdapter)."python-telegram-bot>=22,<23",]@@ -217,8 +217,8 @@ jarvis-review-eval = "jarvis.cli.review_eval:main"jarvisctl = "jarvis.cli_ctl.__main__:main"jctl = "jarvis.cli_ctl.__main__:main"-# Plugin-Entry-Points — alle Slots sind schon jetzt deklariert.-# Neue Plugins werden ohne Core-Änderung discovered.+# Plugin entry points — all slots are already declared.+# New plugins are discovered without any core changes.[project.entry-points."jarvis.wakeword"]openwakeword = "jarvis.plugins.wake.openwakeword_provider:OpenWakeWordProvider"@@ -255,8 +255,8 @@ python-script = "jarvis.plugins.harness.python_script:PythonScriptHarness"screenshot = "jarvis.plugins.harness.computer_use:ComputerUseHarness"[project.entry-points."jarvis.channel"]-# Transport-Adapter zwischen UI-Layer und Orchestrator (Plan §17.3).-# Web-Channel ist der erste; Telegram/WhatsApp folgen in Phase 8+.+# Transport adapter between the UI layer and the orchestrator (Plan §17.3).+# Web channel is the first; Telegram/WhatsApp follow in Phase 8+.web = "jarvis.channels.web:WebChannel"# === F-FRIENDS [F1] · feature/friends-section · ruben-2026-04-30 ===# Phase F1 — bidirektionaler Telegram-Bot-Channel (long-polling).@@ -352,7 +352,7 @@ inspect-pointer = "jarvis.plugins.tool.inspect_pointer:InspectPointerTool"# Publishes NavigateSidebar; the frontend switches the section. Never a spawn# (AP-5/AP-14). See ADR-0011 amendment "Navigate tool".navigate = "jarvis.plugins.tool.navigate:NavigateTool"-# Phase A1 — Awareness-Layer L1 (synchroner State-Read fuer Router).+# Phase A1 — Awareness layer L1 (synchronous state read for the router).awareness-snapshot = "jarvis.plugins.tool.awareness_snapshot:AwarenessSnapshotTool"# Phase A3 — Awareness-Layer L3 (BM25 search across recent episodes).awareness-recall = "jarvis.plugins.tool.awareness_recall:AwarenessRecallTool"@@ -421,8 +421,8 @@ select = ["E", "F", "I", "UP", "B", "ASYNC", "S", "A"]ignore = ["S101", "S603", "S607"][tool.ruff.lint.per-file-ignores]-# Verdichter-System-Prompt enthaelt bewusst lange Few-Shot-Beispiele-# (Tournament 2026-04-26 Pick) — String-Content, NICHT umformatierbar.+# The Verdichter system prompt intentionally contains long few-shot examples+# (Tournament 2026-04-26 pick) — string content, must NOT be reformatted."jarvis/awareness/prompts.py" = ["E501"]# Telephony tests parse our OWN generated TwiML (trusted input, not untrusted# network data) and use the literal word "secret" / fake fixture tokens that@@ -436,7 +436,7 @@ testpaths = ["tests"]pythonpath = ["."]markers = ["phase5: Phase-5-Integration-Tests (isoliert fahrbar via `pytest -m phase5`).",- "skip_ci: Tests die echtes Desktop/Admin/Live-Klicken brauchen — nicht in CI.",+ "skip_ci: tests that need real desktop/admin/live clicking — not run in CI.","e2e: Phase-7-End-to-End-Tests (Plan-§7.6, manuell via `pytest -m e2e`).","voice_latency: Phase-L Voice-Latency-Tests (Plan §6.1; manuell via `pytest -m voice_latency`).","eval: Phase-8.6 Eval-Harness — Golden-Query-Suite (manuell via `pytest -m eval`).",diff --git a/scripts/_build_excalidraw_jarvis.py b/scripts/_build_excalidraw_jarvis.pyindex 256e1546d3..3c6469f612 100644--- a/scripts/_build_excalidraw_jarvis.py+++ b/scripts/_build_excalidraw_jarvis.py@@ -114,7 +114,7 @@ text("hero_title", 60, 50,"PERSONAL JARVIS — OpenClaw Mission-Engine & ChatGPT-Migration",size=58, color=C["ink"], bold_family=True)text("hero_sub", 62, 135,- "Was wurde gebaut: Voice → Force-Spawn → Mission-Manager → Worker/Critic-Loop → APPROVED → Voice-Readback · plus die ChatGPT/Codex-Umstellung (Welle 6) und 18+ Live-Bugs",+ "What was built: Voice → Force-Spawn → Mission-Manager → Worker/Critic-Loop → APPROVED → Voice-Readback · plus the ChatGPT/Codex migration (Welle 6) and 18+ live bugs",size=20, color=C["sub"])# info badges in herodef badge(eid, x, y, label, fill, stroke):@@ -129,7 +129,7 @@ badge("hb6", 2820, 190, "No Anthropic API · No login needed", C["orange"], C["o# Summary flow (the 10-second overview) — y ~ 300sy = 320-text("sum_h", 60, sy - 36, "① SUMMARY FLOW — der ganze Weg in einem Blick", size=22, color=C["ink"], bold_family=True)+text("sum_h", 60, sy - 36, "① SUMMARY FLOW — the whole path at a glance", size=22, color=C["ink"], bold_family=True)sum_nodes = [("sf_voice", "Voice /\nText", C["blue"], C["blue_s"], 60),("sf_brain", "Brain-Router\n(force-spawn?)", C["purple"], C["purple_s"], 320),@@ -310,7 +310,7 @@ for eid, title, fill, st, x, rows in cols:# SECTION 4 — THE 3-CHAINED ChatGPT-MIGRATION BUGS (Welle 6)# ===========================================================================cy = 960-text("chain_h", tx, cy - 38, "④ WELLE 6 — die 3 verketteten Live-Bugs der ChatGPT-Umstellung",+text("chain_h", tx, cy - 38, "④ WELLE 6 — the 3 chained live bugs of the ChatGPT migration",size=24, color=C["ink"], bold_family=True)chain = [("ch1", "C1 · CODEX_HOME leak", "per-mission CODEX_HOME ohne auth.json",@@ -334,7 +334,7 @@ for eid, title, rc, sym, fix, x in chain:arrow("ch_a1", tx + 500, cy + 100, 40, 0, stroke=C["red_s"], sw=3)arrow("ch_a2", tx + 1040, cy + 100, 40, 0, stroke=C["red_s"], sw=3)text("ch_proof", tx, cy + 220,- "Live-Beweis: mission_019e3c51 + 019e3c52 stream.jsonl → HTTP 400 'sonnet not supported' · nach Fix: /goal E2E grün in 48s",+ "Live proof: mission_019e3c51 + 019e3c52 stream.jsonl → HTTP 400 'sonnet not supported' · after fix: /goal E2E green in 48s",size=13, color=C["sub"])# ===========================================================================@@ -456,19 +456,19 @@ for i, t in enumerate(inv):dgx = 1320dgy = 2680rect("dg_panel", dgx, dgy, 1080, 360, stroke=C["blue_s"], bg="#f1f8ff", sw=2)-text("dg_h", dgx + 20, dgy + 16, "⑨ DEEPGRAM-RECHERCHE (2026-05-20) — nur Research, kein Code",+text("dg_h", dgx + 20, dgy + 16, "⑨ DEEPGRAM RESEARCH (2026-05-20) — research only, no code",size=22, color=C["ink"], bold_family=True)-text("dg_q1", dgx + 20, dgy + 62, "Frage 1 — Auth anders als Groq?", size=15, color=C["blue_s"], bold_family=True)+text("dg_q1", dgx + 20, dgy + 62, "Question 1 — Auth different from Groq?", size=15, color=C["blue_s"], bold_family=True)text("dg_a1", dgx + 20, dgy + 88,- "JA: 'Token <key>' statt 'Bearer' + optionale Kurzzeit-JWTs (POST /v1/auth/grant, 30s–1h).\nServer-seitig aber 1-Zeilen-Unterschied. Ephemerer JWT-Flow nur für Browser-Clients nötig.",+ "YES: 'Token <key>' instead of 'Bearer' + optional short-lived JWTs (POST /v1/auth/grant, 30s-1h).\nServer-side it's a 1-line difference, though. Ephemeral JWT flow is only needed for browser clients.",size=13, color=C["sub"])-text("dg_q2", dgx + 20, dgy + 150, "Frage 2 — Tokens während du sprichst?", size=15, color=C["blue_s"], bold_family=True)+text("dg_q2", dgx + 20, dgy + 150, "Question 2 — tokens while you're speaking?", size=15, color=C["blue_s"], bold_family=True)text("dg_a2", dgx + 20, dgy + 176,- "JA: interim_results=true → erste Tokens ~150ms WÄHREND des Sprechens. is_final/speech_final-Flags.\nFlux-Modell: EagerEndOfTurn → LLM startet bevor du fertig bist. Nova-3 DE+EN, Flux EN-only.",+ "YES: interim_results=true → first tokens ~150ms WHILE speaking. is_final/speech_final flags.\nFlux model: EagerEndOfTurn → the LLM starts before you're done. Nova-3 DE+EN, Flux EN-only.",size=13, color=C["sub"])-text("dg_q3", dgx + 20, dgy + 238, "Überraschung — Repo-Realität:", size=15, color=C["red_s"], bold_family=True)+text("dg_q3", dgx + 20, dgy + 238, "Surprise — repo reality:", size=15, color=C["red_s"], bold_family=True)text("dg_a3", dgx + 20, dgy + 264,- "Deepgram existiert NICHT — 3 entry-points in pyproject.toml zeigen auf nicht-vorhandene Dateien\n('ghost registrations'). Pipeline ist batch-only: _handle_utterance → transcribe_pcm(ganzer Satz).\nEchtes Live-Mithören braucht Plugin-Bau UND Pipeline-Umbau.",+ "Deepgram does NOT exist — 3 entry points in pyproject.toml point to non-existent files\n('ghost registrations'). The pipeline is batch-only: _handle_utterance → transcribe_pcm(whole sentence).\nReal live listen-along needs a plugin build AND a pipeline rework.",size=13, color=C["sub"])badge("dg_st", dgx + 20, dgy + 320 - 4, "Decision: from-scratch build, not finish-the-stub", C["yellow"], C["yellow_s"])@@ -478,17 +478,17 @@ badge("dg_st", dgx + 20, dgy + 320 - 4, "Decision: from-scratch build, not finisgx = 60gy = 3700rect("goal_panel", gx, gy, 1160, 300, stroke=C["green_s"], bg="#ebfbee", sw=2)-text("goal_h", gx + 20, gy + 16, "⑩ /goal LIVE-E2E-BEWEIS — der ganze Stack grün",+text("goal_h", gx + 20, gy + 16, "⑩ /goal LIVE E2E PROOF — the whole stack green",size=22, color=C["ink"], bold_family=True)text("goal_f", gx + 20, gy + 56, "tests/integration/test_voice_mission_e2e_chatgpt.py", size=14, color=C["sub"], font=3)gchecks = [- "bootstrap_missions → echter Stack hochgefahren",+ "bootstrap_missions → real stack spun up","manager.dispatch + kontrollierer.run_mission",- "CodexDirectWorker spawnt echtes codex exec (kein Mock)",+ "CodexDirectWorker spawns a real codex exec (no mock)","Critic via _invoke_via_codex_direct (read-only)","Mission-DB state == APPROVED",- "Beweis-Datei mit exaktem Inhalt (aus diff.patch)",- "CriticVerdictReady(verdict='approve') Bus-Event",+ "Proof file with exact content (from diff.patch)",+ "CriticVerdictReady(verdict='approve') bus event",]for i, t in enumerate(gchecks):y = gy + 92 + i * 28diff --git a/scripts/_capture_obsidian_printwindow.py b/scripts/_capture_obsidian_printwindow.pyindex fd6e9853d5..e7812c5964 100644--- a/scripts/_capture_obsidian_printwindow.py+++ b/scripts/_capture_obsidian_printwindow.py@@ -11,7 +11,7 @@ Flow:user's other vault.3. Write a solo obsidian.json with only our vault.4. Launch Obsidian; wait for the vault picker.- 5. Send Alt+O to focus the 'Öffnen' button via pywinauto's PostMessage,+ 5. Send Alt+O to focus the German-localized 'Öffnen' (Open) button via pywinauto's PostMessage, # i18n-allow: quotes the real button label of Obsidian's German-localized UIthen dispatch a click on the Obsidian HWND directly.Honestly the cleanest path is: register the vault path in obsidian.jsondiff --git a/scripts/_final_validate_1_dispatch.py b/scripts/_final_validate_1_dispatch.pyindex 06f879672e..af1aacddb6 100644--- a/scripts/_final_validate_1_dispatch.py+++ b/scripts/_final_validate_1_dispatch.py@@ -77,7 +77,7 @@ def probe_stage_2_action_verbs() -> list[tuple[str, bool, bool]]:"Erstelle Datei test.md mit Hello","Analysiere die letzte Mission","Schreib mir eine Zusammenfassung",- "Mach einen Screenshot vom Code",+ "Mach einen Screenshot vom Code", # i18n-allow: simulated German user utterance under test (force-spawn router probe)"Spawn einen OpenClaw-Agenten",]rows: list[tuple[str, bool, bool]] = []@@ -89,7 +89,7 @@ def probe_stage_2_action_verbs() -> list[tuple[str, bool, bool]]:def probe_stage_2_smalltalk() -> list[tuple[str, bool]]:mgr = make_manager_with_spawn_tool()- prompts = ["Hallo", "Wie geht's", "Danke", "Was ist Hauptstadt von Frankreich"]+ prompts = ["Hallo", "Wie geht's", "Danke", "Was ist Hauptstadt von Frankreich"] # i18n-allow: simulated German user utterances under test (smalltalk/knowledge router probe)rows: list[tuple[str, bool]] = []for p in prompts:out = mgr._should_force_openclaw(p)@@ -106,7 +106,7 @@ def probe_stage_2_permissive_mode() -> list[tuple[str, bool]]:"Erstelle Datei test.md mit Hello","Analysiere die letzte Mission","Schreib mir eine Zusammenfassung",- "Mach einen Screenshot vom Code",+ "Mach einen Screenshot vom Code", # i18n-allow: simulated German user utterance under test (permissive-mode router probe)]rows: list[tuple[str, bool]] = []for p in prompts:@@ -159,15 +159,15 @@ def probe_drift() -> tuple[str | None, str | None]:except Exception as exc: # noqa: BLE001toml_provider = f"<error: {exc}>"- soll_provider: str | None = None+ soll_provider: str | None = None # i18n-allow: identifier name, mirrors the config-soll.json filename; not translatable prosetry:- with open(ROOT / "scripts" / "config-soll.json", encoding="utf-8") as f:+ with open(ROOT / "scripts" / "config-soll.json", encoding="utf-8") as f: # i18n-allow: filename identifier, not translatable prosedoc = json.load(f)- soll_provider = doc.get("brain.sub_jarvis", {}).get("provider")+ soll_provider = doc.get("brain.sub_jarvis", {}).get("provider") # i18n-allow: identifier name, not translatable proseexcept Exception as exc: # noqa: BLE001- soll_provider = f"<error: {exc}>"+ soll_provider = f"<error: {exc}>" # i18n-allow: identifier name, not translatable prose- return toml_provider, soll_provider+ return toml_provider, soll_provider # i18n-allow: identifier name, not translatable prose# ---- main ----@@ -227,14 +227,14 @@ def main() -> int:if not ok:fails.append(f"worker_factory({prov}) -> {got}, want {want}")- print("\n=== Drift: jarvis.toml vs scripts/config-soll.json ===")- toml_p, soll_p = probe_drift()+ print("\n=== Drift: jarvis.toml vs scripts/config-soll.json ===") # i18n-allow: filename identifier, not translatable prose+ toml_p, soll_p = probe_drift() # i18n-allow: identifier name, not translatable proseprint(f" jarvis.toml [brain.sub_jarvis].provider = {toml_p!r}")- print(f" config-soll.json brain.sub_jarvis.provider = {soll_p!r}")+ print(f" config-soll.json brain.sub_jarvis.provider = {soll_p!r}") # i18n-allow: filename identifier, not translatable proseif toml_p == soll_p == "claude-api":print(" PASS (both = claude-api)")else:- fails.append(f"drift: toml={toml_p}, soll={soll_p}")+ fails.append(f"drift: toml={toml_p}, soll={soll_p}") # i18n-allow: identifier name, not translatable proseprint(" FAIL drift detected")print("\n=== SUMMARY ===")diff --git a/scripts/add_useT_inner.py b/scripts/add_useT_inner.pyindex 6ca52fa304..950c6e793c 100644--- a/scripts/add_useT_inner.py+++ b/scripts/add_useT_inner.py@@ -39,7 +39,7 @@ add_to_function("views/SkillsView.tsx", "SkillEditor")add_to_function("views/SkillsView.tsx", "TopHits")# SessionList - need it on hangupLabel too -- wait, hangupLabel is not a React component; it's a regular function.-# Pass t in or use a different approach: revert "läuft" to a global string-translator helper.+# Pass t in or use a different approach: revert "läuft" to a global string-translator helper. # i18n-allow: quotes the literal source string being referenced# For simplicity let me check the SessionList line 117:fp = os.path.join(BASE, "components/sessions/SessionList.tsx").replace("\\", "/")diff --git a/scripts/awareness_smoke_a1.py b/scripts/awareness_smoke_a1.pyindex c71a8aaeb7..08586e7b63 100644--- a/scripts/awareness_smoke_a1.py+++ b/scripts/awareness_smoke_a1.py@@ -1,15 +1,15 @@-"""Live-Smoke fuer Phase A1 — Awareness L1 Live Frame.+"""Live smoke test for Phase A1 — Awareness L1 live frame.-Initialisiert ``AwarenessManager`` + Watchers (WindowFocusWatcher +-IdleDetector), laeuft N Sekunden (Default 30s), loggt jedes-``FrameUpdated``- und ``IdleEntered/Exited``-Event auf stdout.+Initializes ``AwarenessManager`` + watchers (WindowFocusWatcher ++IdleDetector), runs for N seconds (default 30s), logs every+``FrameUpdated`` and ``IdleEntered/Exited`` event to stdout.-Saubereres Shutdown via Ctrl+C: ``signal.signal(SIGINT, ...)`` setzt ein-asyncio.Event, das die main-Coroutine zum Aufwachen bringt; danach-``await manager.stop()`` mit 2s-Timeout (siehe Plan §5 Hard-Negative).+Cleaner shutdown via Ctrl+C: ``signal.signal(SIGINT, ...)`` sets an+asyncio.Event that wakes the main coroutine; afterwards+``await manager.stop()`` with a 2s timeout (see Plan §5 hard negative).-Manuell: 5x das Foreground-Window wechseln (Alt+Tab oder Klick auf-andere App), die Window-Titles/Processes erscheinen in der Ausgabe.+Manual: switch the foreground window 5x (Alt+Tab or click on+another app); the window titles/processes appear in the output.Usage:python scripts/awareness_smoke_a1.py [--seconds 30]@@ -35,9 +35,9 @@ from jarvis.core.events import (async def _auto_trigger_window_switches(log: logging.Logger, count: int = 5) -> None:- """Oeffnet/schliesst N-mal notepad.exe — triggert reproduzierbar- EVENT_SYSTEM_FOREGROUND. Genutzt fuer CI-tauglichen Selbsttest ohne- User-Interaction.+ """Opens/closes notepad.exe N times — reproducibly triggers+ EVENT_SYSTEM_FOREGROUND. Used for a CI-suitable self-test without+ user interaction."""for i in range(count):await asyncio.sleep(1.0)@@ -109,9 +109,9 @@ async def run_smoke(seconds: int, auto_trigger: bool, debug: bool) -> int:)await manager.start()log.info(- "OK — Watchers aktiv (count=%d). %ds Lauf-Zeit. "- "Bitte Foreground-Window 5x wechseln (Alt+Tab oder Klick). "- "Ctrl+C beendet sofort.",+ "OK — watchers active (count=%d). %ds run time. "+ "Please switch the foreground window 5x (Alt+Tab or click). "+ "Ctrl+C stops immediately.",len(manager._watchers), seconds,)@@ -145,10 +145,10 @@ async def run_smoke(seconds: int, auto_trigger: bool, debug: bool) -> int:try:await trigger_taskexcept (asyncio.CancelledError, Exception): # noqa: BLE001, S110- # Smoke-Cleanup — kein logging noetig, das Skript endet ohnehin.+ # Smoke cleanup — no logging needed, the script is ending anyway.pass- # Watcher-Stats VOR stop() sammeln — danach ist die Liste leer.+ # Collect watcher stats BEFORE stop() — the list is empty afterwards.watcher_stats = [(type(w).__name__, getattr(w, "_drops", None), getattr(w, "_last_hwnd", None))for w in (getattr(manager, "_watchers", []) or [])@@ -177,7 +177,7 @@ def main() -> int:)parser.add_argument("--debug", action="store_true",- help="DEBUG-Level Logging fuer jarvis.awareness.*",+ help="DEBUG-level logging for jarvis.awareness.*",)args = parser.parse_args()diff --git a/scripts/awareness_smoke_a2.py b/scripts/awareness_smoke_a2.pyindex 4e61d780f4..dc8a55a2be 100644--- a/scripts/awareness_smoke_a2.py+++ b/scripts/awareness_smoke_a2.py@@ -1,22 +1,22 @@-"""Live-Smoke fuer Phase A2 — L2 Story Tracker (Bus-Replay).+"""Live smoke test for Phase A2 — L2 Story Tracker (bus replay).-Plan §6 Smoke-Test ist eigentlich "30min manuell arbeiten" — unrealistisch-fuer einen Smoke. Stattdessen replayt dieses Skript eine realistische-Bus-Sequenz (FrameUpdated + IdleEntered) gegen einen vollverdrahteten-StoryTracker mit echtem Verdichter (Haiku-Brain-Call, falls API-Key da)-oder FakeVerdichter (kein Key gefunden).+The Plan §6 smoke test is really "work manually for 30min" — unrealistic+for a smoke test. Instead, this script replays a realistic+bus sequence (FrameUpdated + IdleEntered) against a fully wired+StoryTracker with a real Verdichter (Haiku brain call, if an API key is present)+or a FakeVerdichter (no key found).-Was das Skript verifiziert:-- StoryTracker akkumuliert salient Frames im Builder-- App-Switch + Min-Duration triggert Verdichter-Call-- Episode landet in tmp-SQLite + FTS-Index ist befuellt-- state.last_episode_summary wird gesetzt-- EpisodeRecorded-Event wird publiziert+What the script verifies:+- StoryTracker accumulates salient frames in the builder+- app switch + min-duration triggers a Verdichter call+- episode lands in tmp SQLite + the FTS index is populated+- state.last_episode_summary is set+- EpisodeRecorded event is publishedUsage::python scripts/awareness_smoke_a2.py- python scripts/awareness_smoke_a2.py --use-real-haiku # Brain-Call statt Fake+ python scripts/awareness_smoke_a2.py --use-real-haiku # brain call instead of fake"""from __future__ import annotations@@ -42,7 +42,7 @@ from jarvis.memory.recall import RecallStore@dataclassclass FakeVerdichter:- summary: str = (+ summary: str = ( # i18n-allow: simulated Verdichter output — the real Verdichter's summary is German by design (VERDICHTER_SYSTEM_PROMPT)"Der Nutzer war 8min in Code.exe mit pipeline.py aktiv, ""wechselte kurz zu Chrome.exe (GitHub-PR-Tab) und kehrte zurueck. ""Aktueller Fokus: pipeline.py."@@ -125,7 +125,7 @@ async def run_smoke(use_real_haiku: bool) -> int:verdichter=verdichter, config=cfg,)- # Bus-Subscriber fuer Stats+ # Bus subscriber for statsreceived: list[EpisodeRecorded] = []async def collect(ev: EpisodeRecorded) -> None:@@ -134,7 +134,7 @@ async def run_smoke(use_real_haiku: bool) -> int:await tracker.start()- log.info("=== Replay: 6 Frames ueber ~2.5s, dann IdleEntered ===")+ log.info("=== Replay: 6 frames over ~2.5s, then IdleEntered ===")base_ts = time.time_ns() - 2_500_000_000sequence: list[tuple[str, str, bool]] = [diff --git a/scripts/build_frontend.py b/scripts/build_frontend.pyindex 6538aeabbb..b5504502f1 100644--- a/scripts/build_frontend.py+++ b/scripts/build_frontend.py@@ -1,4 +1,4 @@-"""Baut React-Frontend. Wird vor PyInstaller und optional in CI aufgerufen."""+"""Builds the React frontend. Runs before PyInstaller and optionally in CI."""import subprocessimport sysfrom pathlib import Pathdiff --git a/scripts/config-soll.json b/scripts/config-soll.jsonindex ab8cf5d7bc..823eeed4f3 100644--- a/scripts/config-soll.json+++ b/scripts/config-soll.json@@ -1,5 +1,5 @@{- "_comment": "Desired-state values for jarvis.toml. The config-drift-guard reads THIS file every 5 minutes and corrects any jarvis.toml value (and JARVIS__* User-scope ENV override) that drifts away from what is pinned here. This file is the moving source of truth: the guard only READS it, it never writes it. IMPORTANT (changed 2026-05-28): brain.primary is now ALSO written automatically by the desktop app's provider switch (the API/Settings section in the UI). When you switch the active Brain provider in the UI, the app writes all three layers at once -- jarvis.toml [brain].primary, this config-soll.json brain.primary, and the JARVIS__BRAIN__PRIMARY User-scope ENV var -- so all three agree on the new value and the drift-guard sees NO drift and will NOT revert your choice. Editing brain.primary here by hand still works, but the UI provider switch is the normal way to change the active provider. The drift-guard's job is to PROTECT whatever value is set here against rogue parallel sessions (which only touch jarvis.toml, not this file). Keys use dot-notation, exactly as the TOML section header reads. Paths in Punkt-Notation, exakt wie in der TOML.",+ "_comment": "Desired-state values for jarvis.toml. The config-drift-guard reads THIS file every 5 minutes and corrects any jarvis.toml value (and JARVIS__* User-scope ENV override) that drifts away from what is pinned here. This file is the moving source of truth: the guard only READS it, it never writes it. IMPORTANT (changed 2026-05-28): brain.primary is now ALSO written automatically by the desktop app's provider switch (the API/Settings section in the UI). When you switch the active Brain provider in the UI, the app writes all three layers at once -- jarvis.toml [brain].primary, this config-soll.json brain.primary, and the JARVIS__BRAIN__PRIMARY User-scope ENV var -- so all three agree on the new value and the drift-guard sees NO drift and will NOT revert your choice. Editing brain.primary here by hand still works, but the UI provider switch is the normal way to change the active provider. The drift-guard's job is to PROTECT whatever value is set here against rogue parallel sessions (which only touch jarvis.toml, not this file). Keys use dot-notation, exactly as the TOML section header reads.","_updated": "2026-06-21","_reason": "2026-06-21: ack_brain re-aligned after the spawn-announcement 'contextless stock phrase' report. The grounded LLM-composed spawn announcement was speaking generic pool phrases ('Hab ich. Das ist etwas umfangreicher...') instead of context-aware text. Root cause: ack_brain.enabled was pinned false (to silence the separate speculative PREAMBLE, which now has its own preamble_enabled sub-switch), but enabled is the SUBSYSTEM MASTER that also gates the grounded spawn announcer; and ack_brain.provider was pinned to gemini, which is billing-exhausted (429 RESOURCE_EXHAUSTED). Fix: enabled=true (restores the grounded spawn announcer; the speculative preamble stays off via preamble_enabled=false default), provider=grok (live, grok-4-fast-non-reasoning, ~0.8-1.6s, verified context-aware), fallback_provider=gemini (auto-recovers when credits return; consumed by the now-wired spawn-path failover). 2026-06-14: heavy tier moved from claude-fable-5 to claude-opus-4-8 (explicit model id, the configured frontier) — the Claude Max subscription lost CLI access to Fable ('Claude Fable 5 is currently unavailable', approved-access-only), so every worker AND critic spawn wasted ~2s probing the unavailable model before the adaptive retry fell back to the CLI default (which IS opus-4-8). Maintainer approved the direct opus-4-8 pin on 2026-06-14; the worker/critic keep the retry-without-model safety net if opus ever becomes inaccessible too. PRIOR 2026-06-10: heavy tier pinned to claude-fable-5 (user mandate: no automatic claude-opus-* fallback anywhere). brain.providers.claude-api.deep_model=claude-fable-5; brain.sub_jarvis switched openai-codex -> claude-api with an explicit model pin claude-fable-5 so worker AND critic (same chain resolver) run fable via the Claude Max OAuth claude CLI. EARLIER 2026-05-28: sub-agent heavy-worker LLM upgraded Opus 4.7 -> 4.8 (current Anthropic frontier; both verified live under Claude Max OAuth). Pinned brain.providers.claude-api.deep_model=claude-opus-4-8 here so the drift-guard enforces it (it was previously unpinned). 2026-05-28: brain.primary is now ALSO written by the desktop-app UI provider switch as a three-layer sync (jarvis.toml [brain].primary + this config-soll.json brain.primary + the JARVIS__BRAIN__PRIMARY User-scope env var) so the drift-guard sees no drift and never reverts a deliberate switch; the guard was hardened to be a true no-op when all three layers already agree, and a latent PowerShell foreach scope-leak that left the ENV-drift check inert was fixed. 2026-05-27: Cartesia.ai Sonic 3.5 added as a selectable TTS provider with per-language native voice mapping (Sebastian/Daniel/Pedro for DE/EN/ES) synced to the reply_language pin + per-utterance auto-detect. Earlier 2026-05-26 (Vertex AI): tts.use_vertex + vertex_project + vertex_location + service_account_path added — routes Gemini Flash TTS through Vertex AI on the user's billed GCP project instead of Google AI Studio. AI Studio enforces a 100-RPD cap on the Preview model gemini-3.1-flash-tts-preview that is independent of Pay-as-you-go billing; once hit, the Sibling-Bridge auto-switches to gemini-2.5-flash-preview-tts and the perceived Charon voice shifts mid-session, breaking the 2026-05-24 single-voice user mandate. Vertex AI on a billed project does not have the Preview RPD cap. Auth runs via a service-account JSON at ~/.config/jarvis/vertex-sa.json (dedicated SA, role roles/aiplatform.user, key on disk). The plugin strips GOOGLE_API_KEY + GEMINI_API_KEY at client-build time so the AI-Studio path cannot be accidentally re-routed when both auth modes are present. The Sibling-Bridge stays wired as defence-in-depth but will not trigger on Vertex. Earlier 2026-05-26: stt.bias_prompt added — Whisper-prompt vocabulary biasing for the Groq cloud STT plugin. Without it, Whisper falls onto phonetically nearby everyday words for proper nouns and tech vocabulary. The prompt is a comma-separated word list (NOT full sentences — Whisper would re-emit those verbatim on silent tail audio) and is capped to 1024 chars inside the plugin. Earlier 2026-05-26: computer_use.show_virtual_cursor pinned to false after the black-screen incident. Earlier 2026-05-24: trigger.single_turn_mode switched true -> false (USER mandate). EARLIER 2026-05-20: brain.sub_jarvis.provider switched from chatgpt back to claude-api. Earlier 2026-05-20: main Jarvis voice brain switched to Gemini 3.5 Flash (GA, model id `gemini-3.5-flash`, 1M-token context). Earlier 2026-05-18: voice single-turn mandate. Earlier 2026-05-15: all brain layers on Gemini.","trigger": {diff --git a/scripts/e2e_latency_turn.py b/scripts/e2e_latency_turn.pyindex 1e3711fece..3232261313 100644--- a/scripts/e2e_latency_turn.py+++ b/scripts/e2e_latency_turn.py@@ -47,7 +47,7 @@ from jarvis.core.events import ( # noqa: E402TranscriptionUpdate,)-QUESTION = "Was ist die Hauptstadt von Frankreich?"+QUESTION = "Was ist die Hauptstadt von Frankreich?" # i18n-allow: simulated German user utterance fed through the live voice pipeline for the latency benchmarkTTS_RATE = 24_000diff --git a/scripts/export_ws_schema.py b/scripts/export_ws_schema.pyindex 28141d1341..dd6bf81d9b 100644--- a/scripts/export_ws_schema.py+++ b/scripts/export_ws_schema.py@@ -1,4 +1,4 @@-"""Exportiert Pydantic-Modelle aus jarvis.ui.web.schema als JSON-Schema."""+"""Exports Pydantic models from jarvis.ui.web.schema as JSON schema."""import jsonimport sysfrom pathlib import Path@@ -16,7 +16,7 @@ def main() -> int:WSWelcome,)except ImportError:- print("Agent-2s schema.py noch nicht da. Skip.", file=sys.stderr)+ print("Agent-2's schema.py not there yet. Skip.", file=sys.stderr)return 0OUT.parent.mkdir(parents=True, exist_ok=True)OUT.write_text(diff --git a/scripts/feature_verify_all.py b/scripts/feature_verify_all.pyindex d18ffac4c1..64b3536958 100644--- a/scripts/feature_verify_all.py+++ b/scripts/feature_verify_all.py@@ -156,12 +156,12 @@ def main() -> int:report: dict = {"started": None, "cases": []}# --- Computer-use (Calculator: clean process delta) ---- report["cases"].append(cu_case("calculator", "Öffne den Rechner."))+ report["cases"].append(cu_case("calculator", "Öffne den Rechner.")) # i18n-allow: simulated German user command driving a live computer-use probe# --- Sub-agent missions ---report["cases"].append(mission_case("mission_file",- "Schreib eine 120-Wörter-Geschichte über einen Roboter namens Beacon "+ "Schreib eine 120-Wörter-Geschichte über einen Roboter namens Beacon " # i18n-allow: simulated German user command driving a live mission-spawn probe"und speichere sie in eine Datei."))report["cases"].append(mission_case("mission_answer", "Which city would you recommend for a trip to Australia?"))@@ -171,7 +171,7 @@ def main() -> int:# --- Provider switch ---sw1 = run_probe("Wechsel zu Grok.", secs=40, idle=15)chk = run_probe("Sag bitte kurz hallo.", secs=40, idle=15)- sw2 = run_probe("Wechsel zurück zu Gemini.", secs=40, idle=15)+ sw2 = run_probe("Wechsel zurück zu Gemini.", secs=40, idle=15) # i18n-allow: simulated German user command driving a live provider-switch probereport["cases"].append({"label": "provider_switch", "switch_to_grok": sw1,"after_switch_provider": chk.get("provider"),"after_switch_verdict": chk, "switch_back": sw2})diff --git a/scripts/install_shortcuts.py b/scripts/install_shortcuts.pyindex 46963c59fd..76ab9b7d5c 100644--- a/scripts/install_shortcuts.py+++ b/scripts/install_shortcuts.py@@ -1,18 +1,18 @@-"""Erzeugt Jarvis-Icon + Desktop-Shortcut + Autostart-Shortcut.+"""Creates the Jarvis icon + desktop shortcut + autostart shortcut.-Einmalig ausführen:+Run once:python scripts/install_shortcuts.py-Ergebnis:- 1. assets/icons/jarvis.ico — Multi-size Windows-Icon (Schwarz + Signal-Yellow)- 2. Desktop\\Personal Jarvis.lnk — Doppelklick öffnet das Fenster- 3. shell:startup\\Personal Jarvis.lnk — startet Jarvis beim Windows-Login+Result:+ 1. assets/icons/jarvis.ico — multi-size Windows icon (black + signal yellow)+ 2. Desktop\\Personal Jarvis.lnk — double-click opens the window+ 3. shell:startup\\Personal Jarvis.lnk — starts Jarvis at Windows login-Beide Shortcuts zeigen auf run.bat im Projekt-Ordner. run.bat nutzt-pythonw.exe, damit kein Console-Fenster aufpoppt.+Both shortcuts point to run.bat in the project folder. run.bat uses+pythonw.exe, so no console window pops up.-Deinstallieren:+Uninstall:python scripts/install_shortcuts.py --uninstall"""@@ -33,9 +33,9 @@ RUN_BAT = PROJECT_ROOT / "run.bat"SHORTCUT_NAME = "Personal Jarvis.lnk"APP_USER_MODEL_ID = "PersonalJarvis.PersonalJarvis"-DESCRIPTION = "Personal Jarvis — voice-gesteuerter Meta-Orchestrator"+DESCRIPTION = "Personal Jarvis — voice-controlled meta-orchestrator"-# Jarvis-Launcher-Modul (pywebview-Fenster, kein Console)+# Jarvis launcher module (pywebview window, no console)LAUNCHER_MODULE = "jarvis.ui.web.launcher"@@ -65,7 +65,7 @@ def generate_icon() -> None:size = 512master = Image.new("RGBA", (size, size), (0, 0, 0, 0))- # Glow-Layer (separater Canvas, dann blurren und unter das Icon legen)+ # Glow layer (separate canvas, then blur and place beneath the icon)glow = Image.new("RGBA", (size, size), (0, 0, 0, 0))glow_draw = ImageDraw.Draw(glow)glow_draw.ellipse((40, 40, size - 40, size - 40), fill=(255, 214, 10, 90))@@ -105,28 +105,28 @@ def generate_icon() -> None:sizes = [(16, 16), (24, 24), (32, 32), (48, 48), (64, 64), (128, 128), (256, 256)]master.save(ICON_PATH, format="ICO", sizes=sizes)- print(f"[ok] Icon geschrieben: {ICON_PATH}")+ print(f"[ok] Icon written: {ICON_PATH}")def _detect_pythonw() -> Path:- """Findet pythonw.exe — bevorzugt ein venv im Projekt, sonst sys.executable.+ """Finds pythonw.exe — prefers a venv in the project, else sys.executable.- Grund für pythonw statt python: python.exe zeigt eine schwarze Console-- Fenster für die Lebensdauer des Prozesses. pythonw.exe ist ein Windows-- GUI-Subsystem-Binary → kein Console-Fenster, nur das pywebview-Fenster.+ Why pythonw instead of python: python.exe shows a black console+ window for the lifetime of the process. pythonw.exe is a Windows+ GUI-subsystem binary → no console window, just the pywebview window."""- # 1. Venv im Projekt+ # 1. Venv in the projectvenv_pyw = PROJECT_ROOT / ".venv" / "Scripts" / "pythonw.exe"if venv_pyw.exists():return venv_pyw- # 2. System-Python neben sys.executable+ # 2. System Python next to sys.executablesys_py = Path(sys.executable)candidate = sys_py.with_name("pythonw.exe")if candidate.exists():return candidate- # 3. Letzter Fallback: PATH-Search via where.exe+ # 3. Last fallback: PATH search via where.exetry:result = subprocess.run(["where", "pythonw.exe"],@@ -142,13 +142,13 @@ def _detect_pythonw() -> Path:passraise RuntimeError(- "pythonw.exe nicht gefunden. Shortcut würde Console-Fenster zeigen. "- "Installiere Python mit 'tcl/tk and IDLE'-Option oder nutze ein .venv.",+ "pythonw.exe not found. The shortcut would show a console window. "+ "Install Python with the 'tcl/tk and IDLE' option or use a .venv.",)def _set_shortcut_app_id(link: Path) -> bool:- """Best-effort: schreibt die AppUserModelID in den .lnk-PropertyStore."""+ """Best-effort: writes the AppUserModelID into the .lnk property store."""try:import pywintypes # type: ignore[import-not-found]from win32com.propsys import propsys, pscon # type: ignore[import-not-found]@@ -166,7 +166,7 @@ def _set_shortcut_app_id(link: Path) -> bool:store.Commit()return Trueexcept Exception as exc: # noqa: BLE001- print(f"[warn] Shortcut-AppID nicht gesetzt: {exc}")+ print(f"[warn] Shortcut AppID not set: {exc}")return False@@ -180,14 +180,14 @@ def create_shortcut(description: str,window_style: int = 1,) -> None:- """Legt einen .lnk-Shortcut via PowerShell/WScript.Shell an.+ """Creates a .lnk shortcut via PowerShell/WScript.Shell.- Kein pywin32 nötig — WScript.Shell ist seit Windows 2000 eingebaut.- WindowStyle=1 = Normal, 7 = Minimized (Autostart-/Tray-friendly).+ No pywin32 needed — WScript.Shell has been built in since Windows 2000.+ WindowStyle=1 = normal, 7 = minimized (autostart-/tray-friendly)."""link.parent.mkdir(parents=True, exist_ok=True)- # PowerShell-Script als Heredoc — Pfade werden via PS-String-Quoting eingesetzt+ # PowerShell script as a heredoc — paths are inserted via PS string quotingps_script = ("$ErrorActionPreference = 'Stop'\n""$ws = New-Object -ComObject WScript.Shell\n"@@ -253,23 +253,23 @@ def uninstall() -> None:dp.unlink()print(f"[rm] {dp}")else:- print(f"[--] nicht vorhanden: {dp}")+ print(f"[--] not present: {dp}")# Autostart entry — delegate to the port (also clears the persisted toggle# and any legacy .bat/.lnk names)._disable_autostart_via_port()def main() -> int:- parser = argparse.ArgumentParser(description="Jarvis-Shortcuts installieren")+ parser = argparse.ArgumentParser(description="Install Jarvis shortcuts")parser.add_argument("--uninstall",action="store_true",- help="Entfernt Desktop- und Autostart-Shortcut",+ help="Removes the desktop and autostart shortcut",)parser.add_argument("--no-autostart",action="store_true",- help="Nur Desktop-Shortcut, kein Autostart",+ help="Desktop shortcut only, no autostart",)args = parser.parse_args()@@ -278,13 +278,13 @@ def main() -> int:return 0if sys.platform != "win32":- print("Fehler: nur Windows unterstützt.", file=sys.stderr)+ print("Error: only Windows is supported.", file=sys.stderr)return 1try:pythonw = _detect_pythonw()except RuntimeError as exc:- print(f"Fehler: {exc}", file=sys.stderr)+ print(f"Error: {exc}", file=sys.stderr)return 2print(f"[ok] Launcher: {pythonw}")@@ -309,10 +309,10 @@ def main() -> int:_enable_autostart_via_port()else:_disable_autostart_via_port()- print("\nAutostart übersprungen — nur Desktop-Shortcut angelegt.")+ print("\nAutostart skipped — desktop shortcut created only.")- print(f"\nDoppelklick auf '{SHORTCUT_NAME}' auf dem Desktop startet Jarvis.")- print("(pythonw.exe -> kein Console-Fenster, nur die Jarvis-App)")+ print(f"\nDouble-clicking '{SHORTCUT_NAME}' on the desktop starts Jarvis.")+ print("(pythonw.exe -> no console window, just the Jarvis app)")return 0diff --git a/scripts/latency_bench.py b/scripts/latency_bench.pyindex 5d5d7a16df..5939162373 100644--- a/scripts/latency_bench.py+++ b/scripts/latency_bench.py@@ -41,17 +41,17 @@ from jarvis.core.events import BrainTTFT, LatencySpan # noqa: E402# (category, utterance). Mix of the turn classes the suite cares about: cheap# smalltalk/knowledge turns (snappiness-sensitive), screen-reference turns# (must keep vision), and action turns (force-spawn path).-SCENARIOS: list[tuple[str, str]] = [+SCENARIOS: list[tuple[str, str]] = [ # i18n-allow: simulated German user utterances driving the router latency probe("smalltalk", "hallo jarvis"),- ("smalltalk", "wie spät ist es"),+ ("smalltalk", "wie spät ist es"), # i18n-allow: simulated German user utterance under test("smalltalk", "danke dir"),- ("knowledge", "was ist die hauptstadt von frankreich"),- ("knowledge", "erklär mir kurz was ein vektor ist"),- ("screen_ref", "was siehst du hier auf dem bildschirm"),- ("screen_ref", "was ist das hier"),- ("action", "öffne den browser"),+ ("knowledge", "was ist die hauptstadt von frankreich"), # i18n-allow: simulated German user utterance under test+ ("knowledge", "erklär mir kurz was ein vektor ist"), # i18n-allow: simulated German user utterance under test+ ("screen_ref", "was siehst du hier auf dem bildschirm"), # i18n-allow: simulated German user utterance under test+ ("screen_ref", "was ist das hier"), # i18n-allow: simulated German user utterance under test+ ("action", "öffne den browser"), # i18n-allow: simulated German user utterance under test("action", "repariere den bug in main.py"),- ("action", "starte einen subagenten für die recherche"),+ ("action", "starte einen subagenten für die recherche"), # i18n-allow: simulated German user utterance under test]diff --git a/scripts/measure_voice_stages.py b/scripts/measure_voice_stages.pyindex 0f841fe675..1474f68bd8 100644--- a/scripts/measure_voice_stages.py+++ b/scripts/measure_voice_stages.py@@ -34,7 +34,7 @@ if str(REPO) not in sys.path:from jarvis.core.config import load_config # noqa: E402-PROBE_SENTENCE = "Es ist gerade kurz nach sieben Uhr abends, Chef."+PROBE_SENTENCE = "Es ist gerade kurz nach sieben Uhr abends, Chef." # i18n-allow: sample TTS voice output text used to benchmark the voice pipeline stagesPROBE_QUESTION_PCM_RATE = 24_000 # Gemini TTS output ratediff --git a/scripts/migrate_adrs.py b/scripts/migrate_adrs.pyindex 8d4295049a..43e2a08826 100644--- a/scripts/migrate_adrs.py+++ b/scripts/migrate_adrs.py@@ -1,11 +1,11 @@-"""Einmaliges Migrations-Skript: Frontmatter zu allen ADR-Files ergaenzen.+"""One-off migration script: add frontmatter to all ADR files.-Idempotent — wenn ein Frontmatter schon existiert, wird die Datei nicht-angefasst. Pro ADR werden ``title`` aus dem ersten H1 extrahiert,-``slug`` aus dem Dateinamen, ``diataxis: adr``, plus eine grobe Phasen--Zuordnung aus einer Hand-Mapping-Tabelle.+Idempotent — if frontmatter already exists, the file is not+touched. Per ADR, ``title`` is extracted from the first H1,+``slug`` from the filename, ``diataxis: adr``, plus a rough phase+assignment from a hand-mapping table.-Aufruf:+Usage:python scripts/migrate_adrs.py"""from __future__ import annotations@@ -16,7 +16,7 @@ from pathlib import PathREPO = Path(__file__).resolve().parents[1]ADR_DIR = REPO / "docs" / "adr"-# Hand-Mapping: ADR-Nr -> Master-Plan-Phase. Aus Inhaltslesung erkannt.+# Hand mapping: ADR number -> master-plan phase. Determined by reading the content.PHASE_MAP: dict[str, str] = {"0001": "5", # IPC Named Pipe — Admin"0002": "5", # UIA Tree — Vision@@ -31,14 +31,14 @@ PHASE_MAP: dict[str, str] = {"0011": "5", # Router Pure Dispatcher — Persona/Phase 5}-# Heutiges Datum als ``last_reviewed``-Default. ADRs sind in Phasen-# entstanden, aber wir markieren sie heute als reviewed (sie waren in den-# Phasen-Reviews mit drin).+# Today's date as the ``last_reviewed`` default. ADRs were created across+# phases, but we mark them as reviewed today (they were part of the+# phase reviews).TODAY = "2026-04-29"def extract_title(body: str) -> str:- """Liest den ersten ``# H1``-Text und liefert ihn ohne ``#`` und Whitespace."""+ """Reads the first ``# H1`` text and returns it without ``#`` and whitespace."""m = re.search(r"^#\s+(.+?)\s*$", body, re.MULTILINE)return m.group(1).strip() if m else "ADR"@@ -78,7 +78,7 @@ def build_frontmatter(adr_num: str, title: str, slug: str) -> str:def main() -> None:if not ADR_DIR.is_dir():- raise SystemExit(f"ADR-Dir nicht gefunden: {ADR_DIR}")+ raise SystemExit(f"ADR dir not found: {ADR_DIR}")migrated = 0skipped = 0diff --git a/scripts/probe_prompt_cost.py b/scripts/probe_prompt_cost.pyindex cb03c4ab9a..d4edd2eedd 100644--- a/scripts/probe_prompt_cost.py+++ b/scripts/probe_prompt_cost.py@@ -27,7 +27,7 @@ os.chdir(REPO)from jarvis.core.bus import EventBus # noqa: E402from jarvis.core.config import load_config # noqa: E402-UTTERANCE = "Was ist die Hauptstadt von Frankreich?"+UTTERANCE = "Was ist die Hauptstadt von Frankreich?" # i18n-allow: simulated German user utterance used to probe prompt costRUNS = 3diff --git a/scripts/probe_tts_streaming.py b/scripts/probe_tts_streaming.pyindex 0e2bf1dde7..0905c71d5c 100644--- a/scripts/probe_tts_streaming.py+++ b/scripts/probe_tts_streaming.py@@ -23,7 +23,7 @@ if str(REPO) not in sys.path:from jarvis.core.config import load_config # noqa: E402-TEXT = "Es ist gerade kurz nach sieben Uhr abends, Chef. Soll ich noch etwas vorbereiten?"+TEXT = "Es ist gerade kurz nach sieben Uhr abends, Chef. Soll ich noch etwas vorbereiten?" # i18n-allow: sample TTS voice output text used to probe streamingasync def main() -> int:diff --git a/scripts/shorten_adr_titles.py b/scripts/shorten_adr_titles.pyindex 25d4124880..3d0a555fa1 100644--- a/scripts/shorten_adr_titles.py+++ b/scripts/shorten_adr_titles.py@@ -1,11 +1,11 @@-"""ADR-Titel kuerzen — Frontmatter-``title`` auf prägnante Form bringen.+"""Shorten ADR titles — bring the frontmatter ``title`` into a concise form.-User-Mandat 2026-04-29: Display-Titel in der DocsView-Sidebar muss-vollstaendig lesbar sein (max 60 Zeichen, empfohlen 50). Body-H1 bleibt-unveraendert — der lange Erklaerungs-Titel im Body ist eigenstaendig.+User mandate 2026-04-29: the display title in the DocsView sidebar must+be fully readable (max 60 characters, 50 recommended). The body H1 stays+unchanged — the long explanatory title in the body is independent.-Idempotent: wenn ein ADR schon einen kurzen Titel hat, wird er-uebersprungen. Pflegt nur das ``title``-Field, alles andere bleibt.+Idempotent: if an ADR already has a short title, it is+skipped. Only maintains the ``title`` field; everything else is left alone."""from __future__ import annotations@@ -15,10 +15,10 @@ from pathlib import PathREPO = Path(__file__).resolve().parents[1]ADR_DIR = REPO / "docs" / "adr"-# Hand-kuratierte Kurz-Titel pro ADR-Nummer.-# Format: ``ADR-NNNN: <prägnant>`` — Diataxis-Pill liefert das ADR-Label-# zusaetzlich, aber wir lassen die Nummer im Titel weil sie der-# Identifier ist.+# Hand-curated short titles per ADR number.+# Format: ``ADR-NNNN: <concise>`` — the Diataxis pill supplies the ADR label+# additionally, but we keep the number in the title because it is the+# identifier.SHORT_TITLES: dict[str, str] = {"0001": "ADR-0001: IPC via Named Pipe + HMAC","0002": "ADR-0002: UIA-Tree-Pruning",@@ -40,8 +40,8 @@ def adr_number(filename: str) -> str:def replace_title_in_frontmatter(text: str, new_title: str) -> str:- """Ersetzt ``title: "..."`` in der Frontmatter-Section. Idempotent —- wenn das title-Field schon den new_title traegt, return unveraendert."""+ """Replaces ``title: "..."`` in the frontmatter section. Idempotent —+ if the title field already carries the new_title, returns unchanged."""if not text.startswith("---"):return textparts = text.split("---", 2)@@ -49,34 +49,34 @@ def replace_title_in_frontmatter(text: str, new_title: str) -> str:return textfm = parts[1]body = parts[2]- # Match `title: "..."` Zeile+ # Match the `title: "..."` linetitle_re = re.compile(r'(?m)^title\s*:\s*"[^"]*"\s*$')quoted = f'title: "{new_title}"'if title_re.search(fm):new_fm = title_re.sub(quoted, fm)else:- # Falls kein title vorhanden: anhaengen+ # If no title is present: append itnew_fm = fm.rstrip() + f"\n{quoted}\n"return f"---{new_fm}---{body}"def main() -> None:if not ADR_DIR.is_dir():- raise SystemExit(f"ADR-Dir nicht gefunden: {ADR_DIR}")+ raise SystemExit(f"ADR dir not found: {ADR_DIR}")updated = 0skipped = 0for path in sorted(ADR_DIR.glob("*.md")):num = adr_number(path.name)if num not in SHORT_TITLES:- print(f" skip {path.name} (kein Kurz-Titel hinterlegt)")+ print(f" skip {path.name} (no short title on file)")skipped += 1continuenew_title = SHORT_TITLES[num]text = path.read_text(encoding="utf-8")- # Pruefen, ob schon der Kurz-Titel drin ist+ # Check whether the short title is already presentif f'title: "{new_title}"' in text:- print(f" skip {path.name} (schon kurz)")+ print(f" skip {path.name} (already short)")skipped += 1continuenew_text = replace_title_in_frontmatter(text, new_title)diff --git a/scripts/skill_routing_eval.py b/scripts/skill_routing_eval.pyindex ef5c335951..a0b6b44f5f 100644--- a/scripts/skill_routing_eval.py+++ b/scripts/skill_routing_eval.py@@ -51,19 +51,19 @@ if sys.platform == "win32":# voice-trigger tokens, so only the model-judged path can fire it.GOLDEN: list[tuple[str, str | None]] = [("fass mir mal kurz zusammen was heute alles ansteht", "morning-routine"),- ("ich brauch jetzt ruhe zum arbeiten, blende mir die ablenkungen aus",+ ("ich brauch jetzt ruhe zum arbeiten, blende mir die ablenkungen aus", # i18n-allow: simulated German user utterance under test"deep-work-mode"),- ("schau mal ob heute schon was wichtiges per e-mail reingekommen ist",+ ("schau mal ob heute schon was wichtiges per e-mail reingekommen ist", # i18n-allow: simulated German user utterance under test"plugin-gmail"),("wie viel kostet mich gerade meine google cloud diesen monat?","cli-gcloud"),- ("sind bei mir eigentlich noch issues offen, die ich angehen muss?",+ ("sind bei mir eigentlich noch issues offen, die ich angehen muss?", # i18n-allow: simulated German user utterance under test"plugin-github"),("wie viel hab ich diesen monat eigentlich eingenommen?", "plugin-stripe"),# --- negative controls: the app is only the SUBJECT of a knowledge# question; the definitional guard must keep the skill from firing ---- ("was ist eigentlich GitHub fuer eine plattform?", None),- ("was ist Stripe ueberhaupt und wofuer nutzt man das?", None),+ ("was ist eigentlich GitHub fuer eine plattform?", None), # i18n-allow: simulated German user utterance under test (negative control)+ ("was ist Stripe ueberhaupt und wofuer nutzt man das?", None), # i18n-allow: simulated German user utterance under test (negative control)]PER_TURN_TIMEOUT_S = 60.0diff --git a/scripts/smoke_boot.py b/scripts/smoke_boot.pyindex 9c50712ca0..8b6def02ec 100644--- a/scripts/smoke_boot.py+++ b/scripts/smoke_boot.py@@ -396,10 +396,10 @@ def _is_diagnostic_reply(text: str) -> bool:return (t.startswith("brain unavailable")or t.startswith("brain error")- or t.startswith("brain-fehler")- or t.startswith("kein brain-key gefunden")- or t.startswith("keine brain-provider")- or t.startswith("brain nicht verfuegbar")+ or t.startswith("brain-fehler") # i18n-allow: matches a literal string the production diagnostic fallback may emit+ or t.startswith("kein brain-key gefunden") # i18n-allow: matches a literal string the production diagnostic fallback may emit+ or t.startswith("keine brain-provider") # i18n-allow: matches a literal string the production diagnostic fallback may emit+ or t.startswith("brain nicht verfuegbar") # i18n-allow: matches a literal string the production diagnostic fallback may emitor "brainunavailable" in t)diff --git a/scripts/smoke_brain_e2e.py b/scripts/smoke_brain_e2e.pyindex 03fd8c3853..b2bfc174ed 100644--- a/scripts/smoke_brain_e2e.py+++ b/scripts/smoke_brain_e2e.py@@ -1,10 +1,10 @@-"""End-to-End-Smoke (2026-04-29): direkter Brain-Call ohne Backend.+"""End-to-end smoke test (2026-04-29): direct brain call without a backend.-Verifiziert dass die API-Key-Fixes im echten Stack greifen:-1. Pre-Boot-Key-Check filtert Provider ohne Key.-2. Gemini-Schema-Sanitizer funktioniert (kein 11-validation-error mehr).-3. account_blocked-Klassifikation greift (Anthropic credit / xAI tier).-4. _format_provider_chain_error liefert user-actionable Message.+Verifies that the API-key fixes take effect in the real stack:+1. Pre-boot key check filters out providers without a key.+2. Gemini schema sanitizer works (no more 11-validation-error).+3. account_blocked classification kicks in (Anthropic credit / xAI tier).+4. _format_provider_chain_error returns a user-actionable message.Usage:python scripts/smoke_brain_e2e.py@@ -72,10 +72,10 @@ async def main() -> int:# 3. Live-Brain-Call mit Test-Frageprint("\n--- Step 3: Live-Brain-Call ---")- print(" Frage: 'Antworte mit genau einem Wort: ja oder nein.'")+ print(" Question: 'Antworte mit genau einem Wort: ja oder nein.'") # i18n-allow: quotes the simulated German user utterance sent belowtry:response = await bm.generate(- "Antworte mit genau einem Wort: ja oder nein.",+ "Antworte mit genau einem Wort: ja oder nein.", # i18n-allow: simulated German user utterance under testuse_history=False,)except Exception as exc:@@ -84,8 +84,8 @@ async def main() -> int:print(f"\n Response: {response[:400]!r}")- # 4. Verdict — basiert auf Response-String (nicht auf bm-Attributen,- # weil BrainManager keine public last_provider/last_model Attribute hat).+ # 4. Verdict — based on the response string (not on bm attributes,+ # because BrainManager has no public last_provider/last_model attributes).print("\n--- Step 4: Verdict ---")rc = 0failure_indicators = ("Account-Problem", "Brain-Key", "Sidebar", "Setup")@@ -94,12 +94,12 @@ async def main() -> int:print(" (Bug-API-1-Fix wirkt: account_blocked-Klassifikation aktiv,")print(" User bekommt Billing-URL statt 'Netzwerk pruefen')")elif "unerreichbar" in response.lower() and "Account" not in response:- print(" [X] Generischer 'Provider unerreichbar'-String — Fix greift NICHT")+ print(" [X] Generic 'Provider unreachable' string — the fix is NOT working")rc = 1else:STALE = {"grok-3", "grok-2", "gpt-4o", "gpt-4o-mini", "gemini-2.5-flash","gemini-2.5-pro", "claude-3-opus", "claude-3-haiku"}- # Erfolgreiche Antwort — kein STALE-Marker im Text+ # Successful response — no STALE marker in the textfor stale in STALE:if stale in response.lower():print(f" [WARN] STALE-Marker im Response-Text: {stale}")diff --git a/scripts/smoke_cu_open_chrome.py b/scripts/smoke_cu_open_chrome.pyindex 5fc16fa99e..d45f1bcb35 100644--- a/scripts/smoke_cu_open_chrome.py+++ b/scripts/smoke_cu_open_chrome.py@@ -1,4 +1,4 @@-"""Live Computer-Use smoke — the user-reported "Öffne Chrome" failure case.+"""Live Computer-Use smoke — the user-reported "Öffne Chrome" failure case. # i18n-allow: quotes the real German user command that reproduces the bugDrives the REAL wired ComputerUseHarness end-to-end with the exact goal thatused to fail (the agent typed "Chrome" into a search box, never clicked the@@ -64,7 +64,7 @@ def foreground_title() -> str:async def main() -> int:print("=" * 64)- print('LIVE COMPUTER-USE SMOKE — goal: "Öffne Chrome"')+ print('LIVE COMPUTER-USE SMOKE — goal: "Öffne Chrome"') # i18n-allow: quotes the real German user command under testprint("=" * 64)pids_before = chrome_pids()@@ -98,7 +98,7 @@ async def main() -> int:return 3task = HarnessTask(- prompt="Öffne Chrome",+ prompt="Öffne Chrome", # i18n-allow: simulated German user command under testtimeout_s=180,risk_tier="monitor",allow_computer_use=True,diff --git a/scripts/smoke_frontier.py b/scripts/smoke_frontier.pyindex 544f87a72d..93d5a63314 100644--- a/scripts/smoke_frontier.py+++ b/scripts/smoke_frontier.py@@ -1,13 +1,13 @@-"""Smoke-Test fuer Frontier-Brain-Stack (2026-04-29).+"""Smoke test for the frontier brain stack (2026-04-29).-Verifiziert:-1. BrainManager wird mit Frontier-IDs instantiiert (nicht grok-3/gpt-4o/2.5).-2. Pre-Boot-Key-Check filtert Provider ohne Key aus _dead_providers.-3. voice_turns-DB nimmt nur den ERFOLGREICHEN Provider auf (Bug C).+Verifies:+1. BrainManager is instantiated with frontier IDs (not grok-3/gpt-4o/2.5).+2. Pre-boot key check filters providers without a key out of _dead_providers.+3. The voice_turns DB only records the SUCCESSFUL provider (Bug C).Usage:- python scripts/smoke_frontier.py # alle Checks- python scripts/smoke_frontier.py --no-db # ohne historische DB-Pruefung+ python scripts/smoke_frontier.py # all checks+ python scripts/smoke_frontier.py --no-db # without historical DB checkExit-Code 0 = OK, !=0 = STALE-Modell oder Halluzinations-Tag erkannt."""@@ -40,7 +40,7 @@ STALE_MODELS = {def check_toml() -> int:- """Liest jarvis.toml und prueft dass alle [brain.providers.*] Frontier sind."""+ """Reads jarvis.toml and checks that all [brain.providers.*] are frontier."""from jarvis.core.config import load_configcfg = load_config()@@ -61,12 +61,12 @@ def check_toml() -> int:issues.append(f" sub_jarvis.fallback_model_2 = {sub.fallback_model_2!r} (STALE)")if issues:- print("FAIL: STALE-Modelle in jarvis.toml:")+ print("FAIL: STALE models in jarvis.toml:")for i in issues:print(i)return 1- print("OK: jarvis.toml ist Frontier-konform.")+ print("OK: jarvis.toml is frontier-compliant.")print(f" primary={cfg.brain.primary}")for name in ("claude-api", "gemini", "grok", "openai"):p = cfg.brain.providers.get(name)@@ -78,24 +78,24 @@ def check_toml() -> int:def check_db(post_restart_only: bool = True) -> int:- """Prueft data/sessions.db: STALE-Modelle in den letzten N voice_turns.+ """Checks data/sessions.db: STALE models in the last N voice_turns.- Wenn ``post_restart_only=True`` (Default): nur Turns nach Backend-- Restart-Marker (ENV ``JARVIS_RESTART_TS_MS`` oder Cache-File-mtime).- Historische Turns vor Backend-Restart werden ignoriert (sie sind- pre-fix-Daten und kein Indikator fuer aktuellen Zustand).+ When ``post_restart_only=True`` (default): only turns after the backend+ restart marker (ENV ``JARVIS_RESTART_TS_MS`` or cache-file mtime).+ Historical turns from before the backend restart are ignored (they are+ pre-fix data and not an indicator of the current state)."""db = REPO / "data" / "sessions.db"if not db.exists():- print("INFO: data/sessions.db fehlt — kein DB-Check moeglich. (skip)")+ print("INFO: data/sessions.db missing — DB check not possible. (skip)")return 0- # Restart-Marker: Cache-File-mtime ist ein guter Proxy. Wenn es nicht- # existiert oder leer ist, hat es noch keinen Restart gegeben.+ # Restart marker: cache-file mtime is a good proxy. If it doesn't+ # exist or is empty, there hasn't been a restart yet.cache = REPO / "data" / "frontier_cache.json"cutoff_ms = 0if post_restart_only and cache.exists():- # mtime in ms — Turns davor sind pre-restart-Daten.+ # mtime in ms — turns before this are pre-restart data.cutoff_ms = int(cache.stat().st_mtime * 1000)conn = sqlite3.connect(str(db))@@ -110,9 +110,9 @@ def check_db(post_restart_only: bool = True) -> int:if not rows:print(- f"INFO: Keine voice_turns nach Cutoff (cutoff_ms={cutoff_ms}). "- f"Backend wurde noch nicht neu gestartet ODER es gab keine Voice-Session "- f"seit Restart. Smoke akzeptiert (post-restart-Daten fehlen, kein Fail)."+ f"INFO: No voice_turns after cutoff (cutoff_ms={cutoff_ms}). "+ f"The backend hasn't been restarted yet OR there was no voice session "+ f"since the restart. Smoke accepted (post-restart data missing, not a fail).")return 0@@ -122,12 +122,12 @@ def check_db(post_restart_only: bool = True) -> int:issues.append(f" {tid[:24]}... provider={prov} model={model}")if issues:- print("FAIL: STALE-Modelle in voice_turns NACH Restart:")+ print("FAIL: STALE models in voice_turns AFTER restart:")for i in issues:print(i)return 1- print(f"OK: {len(rows)} post-restart voice_turns gepruft, keine STALE-IDs.")+ print(f"OK: {len(rows)} post-restart voice_turns checked, no STALE IDs.")for tid, prov, model in rows[:3]:print(f" {tid[:32]} {prov}/{model}")return 0diff --git a/scripts/smoke_phase6_p1.py b/scripts/smoke_phase6_p1.pyindex 648f0f4b29..15631b331b 100644--- a/scripts/smoke_phase6_p1.py+++ b/scripts/smoke_phase6_p1.py@@ -1,19 +1,19 @@-"""Smoke-Test Phase 1: Foundation (Event-Schema + Bus + Store + Manager + Recovery).+"""Smoke test Phase 1: Foundation (event schema + bus + store + manager + recovery).-Laeuft End-to-End ohne pytest, prueft die Acceptance-Kriterien aus-docs/phase6-prompt-chain.md fuer Phase 1. Exit 0 bei Erfolg, Exit 1 bei Fehler.+Runs end-to-end without pytest, checks the acceptance criteria from+docs/phase6-prompt-chain.md for Phase 1. Exit 0 on success, exit 1 on failure.-Was wird verifiziert:-1. Clean start ohne pre-existing Missions liefert recovery=[].-2. Happy-Path PENDING -> RUNNING -> CRITIQUING -> APPROVED emittiert 4 Events.-3. seq ist monoton 1..N, lueckenlos.-4. Crash-Simulation (manager.stop() ohne Endzustand) + Restart ist+What is verified:+1. Clean start without pre-existing missions returns recovery=[].+2. Happy path PENDING -> RUNNING -> CRITIQUING -> APPROVED emits 4 events.+3. seq is monotonic 1..N, with no gaps.+4. Crash simulation (manager.stop() without a terminal state) + restart isACTIVITY-AWARE (fix 9f5e043b): a mission whose last event is recent ispresumed owned by a live orchestrator and is SKIPPED (not swept), while agenuinely stale orphan (no activity past the window) is swept to FAILED withMissionStateChanged + MissionFailed on the new bus.-5. Terminale Missions (APPROVED) werden NICHT recovered.-6. events_since(0) liefert lueckenlos alle persistierten Events.+5. Terminal missions (APPROVED) are NOT recovered.+6. events_since(0) returns all persisted events with no gaps."""from __future__ import annotations@@ -25,7 +25,7 @@ from pathlib import Pathif sys.stdout.encoding != "utf-8":sys.stdout.reconfigure(encoding="utf-8") # type: ignore[attr-defined]-# Repo-Root in sys.path damit `from jarvis.missions...` funktioniert+# Repo root in sys.path so `from jarvis.missions...` workssys.path.insert(0, str(Path(__file__).resolve().parent.parent))from jarvis.missions.events import EventEnvelope, now_ms # noqa: E402@@ -51,7 +51,7 @@ async def smoke() -> int:m1 = MissionManager(db_path)recovered = await m1.start()if recovered != []:- failures.append(f"start ohne pre-state liefert recovery={recovered}")+ failures.append(f"start without pre-state returns recovery={recovered}")else:print(f"{OK} clean start, no recovery")@@ -64,13 +64,13 @@ async def smoke() -> int:events1 = await m1.store.events_for_mission(mid1)if len(events1) != 4:- failures.append(f"happy-path liefert {len(events1)} events, erwartet 4")+ failures.append(f"happy path returns {len(events1)} events, expected 4")else:print(f"{OK} happy-path emits 4 events")seqs1 = [e.seq for e in events1]if seqs1 != [1, 2, 3, 4]:- failures.append(f"seq nicht [1,2,3,4]: {seqs1}")+ failures.append(f"seq not [1,2,3,4]: {seqs1}")else:print(f"{OK} seq monoton [1,2,3,4]")@@ -84,7 +84,7 @@ async def smoke() -> int:if types1 != expected_types:failures.append(f"event-types {types1} != {expected_types}")else:- print(f"{OK} event-types konsistent")+ print(f"{OK} event types consistent")# --- Section 2: crash-simulation + ACTIVITY-AWARE recovery ---# (fix 9f5e043b: a fresh crashed mission is presumed owned by a live@@ -93,7 +93,7 @@ async def smoke() -> int:mid2 = await m1.dispatch(prompt="will-crash")await m1.transition_state(mid2, MissionState.RUNNING, reason="worker-spawn")await m1.stop()- print(f"{OK} crash-simulation: stop ohne endzustand")+ print(f"{OK} crash simulation: stop without a terminal state")m2 = MissionManager(db_path)bus_received: list[EventEnvelope] = []@@ -109,19 +109,19 @@ async def smoke() -> int:recovered_fresh = await m2.start()if mid2 in recovered_fresh:failures.append(- f"FRESH crashed mission faelschlich gesweept: {recovered_fresh}"+ f"FRESH crashed mission incorrectly swept: {recovered_fresh}")else:- print(f"{OK} activity-guard: frische crashed mission NICHT gesweept")+ print(f"{OK} activity-guard: fresh crashed mission NOT swept")view_fresh = await m2.mission(mid2)if view_fresh is None or view_fresh.state != MissionState.RUNNING:failures.append(- f"geschuetzte mission state "+ f"protected mission state "f"{view_fresh.state if view_fresh else None} != RUNNING")else:- print(f"{OK} geschuetzte mission bleibt RUNNING")+ print(f"{OK} protected mission stays RUNNING")# 2b: a GENUINELY stale orphan (its last event is older than the window)# IS a real crash and gets swept to FAILED. We model "past the window" by@@ -132,7 +132,7 @@ async def smoke() -> int:if mid2 not in recovered_stale:failures.append(- f"stale orphan NICHT gesweept: {recovered_stale}"+ f"stale orphan NOT swept: {recovered_stale}")else:print(f"{OK} stale orphan -> recovered")@@ -144,7 +144,7 @@ async def smoke() -> int:f"{view_stale.state if view_stale else None} != FAILED")else:- print(f"{OK} stale orphan ist FAILED nach recovery")+ print(f"{OK} stale orphan is FAILED after recovery")recovery_types = [e.payload.event_type for e in bus_received]if (@@ -155,32 +155,32 @@ async def smoke() -> int:f"recovery emits {recovery_types}, missing MissionFailed/StateChange")else:- print(f"{OK} recovery emits MissionFailed + MissionStateChanged auf bus")+ print(f"{OK} recovery emits MissionFailed + MissionStateChanged on the bus")- # mid1 ist APPROVED — darf in KEINEM der beiden Sweeps recovered werden+ # mid1 is APPROVED — must NOT be recovered in EITHER of the two sweepsif mid1 in recovered_fresh or mid1 in recovered_stale:failures.append(- "recovered enthaelt faelschlich mid1 (APPROVED)"+ "recovered incorrectly contains mid1 (APPROVED)")else:- print(f"{OK} terminal missions nicht recovered")+ print(f"{OK} terminal missions not recovered")- # --- Section 3: events_since(0) lueckenlos ---+ # --- Section 3: events_since(0) has no gaps ---all_events = await m2.store.events_since(0)# mid1: 4 (dispatch + 3 state-changes), terminal -> never swept.# mid2: 2 (dispatch + 1 state-change) + 2 stale-recovery (state-change +# failed). The fresh-guard pass in 2a emits nothing. = 8 total.if len(all_events) != 8:- failures.append(f"events_since(0) liefert {len(all_events)}, erwartet 8")+ failures.append(f"events_since(0) returns {len(all_events)}, expected 8")else:- print(f"{OK} events_since(0) liefert alle 8 events")+ print(f"{OK} events_since(0) returns all 8 events")all_seqs = [e.seq for e in all_events]if all_seqs != list(range(1, 9)):- failures.append(f"global seq nicht 1..8: {all_seqs}")+ failures.append(f"global seq not 1..8: {all_seqs}")else:- print(f"{OK} global seq monoton 1..8")+ print(f"{OK} global seq monotonic 1..8")await m2.stop()diff --git a/scripts/smoke_phase6_p2.py b/scripts/smoke_phase6_p2.pyindex 2969992d9e..66e1172859 100644--- a/scripts/smoke_phase6_p2.py+++ b/scripts/smoke_phase6_p2.py@@ -1,24 +1,24 @@-"""Smoke-Test Phase 6 / Prompt 2: Worker-Layer End-to-End gegen echte claude-Binary.--Verifiziert die T1+T2-API-Surface in einem realistischen Mini-Lauf:--1. `claude` muss im PATH sein. Wenn nicht: `[SKIP]` + exit 0 (KEIN Failure).-2. `git rev-parse --show-toplevel` als Basis fuer den Worktree.-3. `WorktreeManager.create(mission_slug='smoke', task_id='p2')` legt einen- frischen Branch + Workspace-Verzeichnis an.-4. `WindowsJobObject('smoke-p2')` als async-Context-Manager — auf Nicht-Windows- No-Op, der Smoke laeuft trotzdem (Worker spawnt regulaer, kein Reaping).-5. `ClaudeDirectWorker.spawn(prompt, ..., max_turns=3)` mit Cost-Cap (--max-turns- ist Cost-Guardrail #1 laut Research-Doc §B). Stream wird gedrained bis- `result`-Event. (OpenClawWorker wurde im OpenClaw/UFO3-Removal entfernt —- `f9fa1c2f`; ClaudeDirectWorker ist der produktive claude-CLI-Worker.)-6. Verifiziere `(workspace / 'hello.txt').exists()` UND content == 'world'- (mit/ohne Trailing-Newline).-7. Verifiziere via `psutil.pid_exists(pid)`, dass der Worker-Subprocess sauber- beendet wurde.+"""Smoke test Phase 6 / Prompt 2: worker layer end-to-end against the real claude binary.++Verifies the T1+T2 API surface in a realistic mini run:++1. `claude` must be on PATH. If not: `[SKIP]` + exit 0 (NOT a failure).+2. `git rev-parse --show-toplevel` as the basis for the worktree.+3. `WorktreeManager.create(mission_slug='smoke', task_id='p2')` creates a+ fresh branch + workspace directory.+4. `WindowsJobObject('smoke-p2')` as an async context manager — on non-Windows+ it's a no-op, the smoke still runs (worker spawns normally, no reaping).+5. `ClaudeDirectWorker.spawn(prompt, ..., max_turns=3)` with a cost cap (--max-turns+ is cost guardrail #1 per the research doc §B). The stream is drained until the+ `result` event. (OpenClawWorker was removed in the OpenClaw/UFO3 removal —+ `f9fa1c2f`; ClaudeDirectWorker is the production claude-CLI worker.)+6. Verify `(workspace / 'hello.txt').exists()` AND content == 'world'+ (with/without a trailing newline).+7. Verify via `psutil.pid_exists(pid)` that the worker subprocess terminated+ cleanly.8. Cleanup: `WorktreeManager.remove(workspace, force=True)`.-Exit 0 bei Erfolg ODER bei `[SKIP]`. Exit 1 nur bei echten Failures.+Exit 0 on success OR on `[SKIP]`. Exit 1 only on real failures."""from __future__ import annotations@@ -31,7 +31,7 @@ from pathlib import Pathif sys.stdout.encoding != "utf-8":sys.stdout.reconfigure(encoding="utf-8") # type: ignore[attr-defined]-# Repo-Root in sys.path damit `from jarvis.missions...` funktioniert+# Repo root in sys.path so `from jarvis.missions...` workssys.path.insert(0, str(Path(__file__).resolve().parent.parent))OK = "[OK]"@@ -40,7 +40,7 @@ SKIP = "[SKIP]"def _repo_root() -> Path:- """Liefert das Repo-Root via `git rev-parse --show-toplevel`."""+ """Returns the repo root via `git rev-parse --show-toplevel`."""out = subprocess.run(["git", "rev-parse", "--show-toplevel"],check=True,@@ -51,7 +51,7 @@ def _repo_root() -> Path:def _read_hello(workspace: Path) -> str | None:- """Liest workspace/hello.txt — None falls nicht vorhanden."""+ """Reads workspace/hello.txt — None if not present."""target = workspace / "hello.txt"if not target.exists():return None@@ -64,19 +64,19 @@ async def smoke() -> int:# --- Section 1: claude im PATH? ---claude_path = shutil.which("claude")if claude_path is None:- print(f"{SKIP} claude not in PATH — Phase-6-Worker-Smoke uebersprungen")+ print(f"{SKIP} claude not in PATH — Phase 6 worker smoke skipped")return 0print(f"{OK} claude found at {claude_path}")- # --- Section 2: psutil verfuegbar? ---+ # --- Section 2: psutil available? ---try:import psutil # noqa: PLC0415except ImportError:- print(f"{SKIP} psutil nicht installiert — `pip install psutil` empfohlen")+ print(f"{SKIP} psutil not installed — `pip install psutil` recommended")return 0- print(f"{OK} psutil {psutil.__version__} importiert")+ print(f"{OK} psutil {psutil.__version__} imported")- # --- Section 3: Repo-Root + Worktree anlegen ---+ # --- Section 3: create repo root + worktree ---from jarvis.missions.isolation import ( # noqa: PLC0415WindowsJobObject,WorktreeManager,diff --git a/scripts/smoke_phase6_p3_real.py b/scripts/smoke_phase6_p3_real.pyindex 7267381081..ab2095798e 100644--- a/scripts/smoke_phase6_p3_real.py+++ b/scripts/smoke_phase6_p3_real.py@@ -1,23 +1,23 @@-"""Smoke-Test Phase 3 — REAL Critic-Call (kostet ~$0.20).+"""Smoke test phase 3 — REAL critic call (costs ~$0.20).-End-to-End mit echtem `openclaw agent --json-schema ...`-Subprocess. Skipt-sauber wenn die claude-CLI nicht installiert/authentifiziert ist-(gleicher Pattern wie smoke_phase6_p2.py). Exit 0 bei Erfolg ODER SKIP,-Exit 1 nur bei echtem Fehler.+End-to-end test with a real `openclaw agent --json-schema ...` subprocess.+Skips cleanly when the claude CLI is not installed/authenticated+(same pattern as smoke_phase6_p2.py). Exit 0 on success OR SKIP,+exit 1 only on a real failure.-Was wird verifiziert:-1. claude-CLI ist installiert und authentifiziert (sonst SKIP).-2. CriticRunner.run() spawnt einen echten claude-Subprocess mit:+What gets verified:+1. The claude CLI is installed and authenticated (otherwise SKIP).+2. CriticRunner.run() spawns a real claude subprocess with:- --output-format json- --json-schema <CRITIC_JSON_SCHEMA>- --model sonnet- --max-turns 1- --permission-mode plan- - [--bare] wenn ANTHROPIC_API_KEY in env-3. Der Critic liefert ein schema-valides CriticVerdict.-4. Der Verdict-Text enthaelt den anchor-token (mission_prompt verbatim).+ - [--bare] when ANTHROPIC_API_KEY is in env+3. The critic returns a schema-valid CriticVerdict.+4. The verdict text contains the anchor token (mission_prompt verbatim).-Ausfuehrung:+Run:cd <repo-root>python scripts/smoke_phase6_p3_real.py"""@@ -43,11 +43,11 @@ FAIL = "[FAIL]"SKIP = "[SKIP]"-# --- Mini-Mission ---+# --- Mini mission ---MISSION_PROMPT = (- "Schreibe eine Python-Funktion `is_palindrome(s: str) -> bool`, "- "die Whitespace und Case ignoriert. Inkludiere doctests."+ "Write a Python function `is_palindrome(s: str) -> bool` "+ "that ignores whitespace and case. Include doctests.")WORKER_DIFF = """\@@ -56,7 +56,7 @@ new file mode 100644+++ b/palindrome.py@@ -0,0 +1,5 @@+def is_palindrome(s: str) -> bool:-+ \"\"\"Returns True wenn s ein palindrom ist.\"\"\"++ \"\"\"Returns True if s is a palindrome.\"\"\"+ cleaned = ''.join(c.lower() for c in s if not c.isspace())+ return cleaned == cleaned[::-1]"""@@ -69,33 +69,33 @@ WORKER_LOG = """\def claude_available() -> bool:- """Schneller existence-check fuer die claude-CLI."""+ """Quick existence check for the claude CLI."""return shutil.which("claude") is not Noneasync def smoke_real() -> int:if not claude_available():- print(f"{SKIP} claude-CLI nicht im PATH — Real-Smoke uebersprungen.")+ print(f"{SKIP} claude CLI not in PATH — real smoke test skipped.")print(f" Install: https://docs.claude.com/en/docs/openclaw")return 0has_api_key = bool(os.environ.get("ANTHROPIC_API_KEY"))if not has_api_key:print(- f"{SKIP} kein ANTHROPIC_API_KEY — Real-Smoke benoetigt entweder "- "den Key (fuer --bare-Pfad) oder eine bestehende OAuth-Session via "- "`claude /login`. Bei OAuth: Test laeuft ohne --bare. Continuing..."+ f"{SKIP} no ANTHROPIC_API_KEY — real smoke test needs either "+ "the key (for the --bare path) or an existing OAuth session via "+ "`claude /login`. With OAuth: test runs without --bare. Continuing...")with tempfile.TemporaryDirectory() as tmp:worktree = Path(tmp) / "wt"worktree.mkdir()- env = dict(os.environ) # erbt nutzbare Auth (OAuth-Tokens, Keychain-Refs)+ env = dict(os.environ) # inherits usable auth (OAuth tokens, keychain refs)runner = CriticRunner(timeout_seconds=120.0)- print(f"{OK} spawning real critic ({'--bare' if has_api_key else 'OAuth-Pfad'}) ...")+ print(f"{OK} spawning real critic ({'--bare' if has_api_key else 'OAuth path'}) ...")try:verdict: CriticVerdict = await runner.run(mission_prompt=MISSION_PROMPT,@@ -110,7 +110,7 @@ async def smoke_real() -> int:print(f"{FAIL} critic-run raised: {type(exc).__name__}: {exc}")return 1- # Validierungen+ # Validationsprint(f"{OK} verdict received: {verdict.verdict}, confidence={verdict.confidence:.2f}")if verdict.verdict not in ("approve", "revise", "reject"):print(f"{FAIL} unknown verdict {verdict.verdict!r}")@@ -119,7 +119,7 @@ async def smoke_real() -> int:print(f"{FAIL} verdict has empty summary")return 1if not verdict.summary_de:- print(f"{FAIL} verdict has empty summary_de — TTS-Pfad waere broken")+ print(f"{FAIL} verdict has empty summary_de — TTS path would be broken")return 1print(f"{OK} verdict has summary + summary_de")print(f" summary: {verdict.summary[:120]}")@@ -127,7 +127,7 @@ async def smoke_real() -> int:print(f" issues: {len(verdict.issues)}, suggested_action: {verdict.suggested_next_action}")print()- print(f"{OK} REAL-SMOKE GREEN — Critic-Loop ist production-ready.")+ print(f"{OK} REAL SMOKE GREEN — critic loop is production-ready.")return 0diff --git a/scripts/tts_brain_endtoend.py b/scripts/tts_brain_endtoend.pyindex d19016f8c2..9fe07f53b9 100644--- a/scripts/tts_brain_endtoend.py+++ b/scripts/tts_brain_endtoend.py@@ -1,10 +1,10 @@-"""End-to-End-Test: Brain → TTS → Speaker OHNE Voice-Pipeline.+"""End-to-end test: Brain → TTS → Speaker WITHOUT the voice pipeline.-Simuliert was der Watchdog machen würde: nimmt User-Text, ruft Brain,-ruft TTS, spielt Audio. Wenn Gemini 429 → SAPI5-Fallback sollte greifen.+Simulates what the watchdog would do: takes user text, calls Brain,+calls TTS, plays audio. If Gemini returns 429 → the SAPI5 fallback should kick in.Usage:- python scripts/tts_brain_endtoend.py "Hallo Jarvis, sag etwas"+ python scripts/tts_brain_endtoend.py "Hello Jarvis, say something""""from __future__ import annotations@@ -25,7 +25,7 @@ async def main(user_text: str) -> int:from jarvis.brain.factory import build_default_brainfrom jarvis.plugins.tts.gemini_flash_tts import GeminiFlashTTS- print(f"[1] Brain starten...")+ print(f"[1] Starting Brain...")brain = build_default_brain()print(f" Provider: {brain.active_provider}")print(f" Tools: {sorted(brain._tools.keys())}")@@ -36,22 +36,22 @@ async def main(user_text: str) -> int:dt = time.perf_counter() - t0print(f" Response ({dt:.2f}s): {response[:200]}")if not response:- print(" !! LEER — Brain hat nichts zurückgegeben.")+ print(" !! EMPTY — Brain returned nothing.")return 1- print(f"[3] TTS starten...")+ print(f"[3] Starting TTS...")tts = GeminiFlashTTS(default_voice="Charon", language_code="de-DE")- print(f"[4] Audio ausgeben...")+ print(f"[4] Playing audio...")player = AudioPlayer()t1 = time.perf_counter()try:chunks = tts.synthesize(response, language_code="de-DE")await player.play_chunks(chunks)dt2 = time.perf_counter() - t1- print(f" OK ({dt2:.2f}s) — User sollte das gehört haben.")+ print(f" OK ({dt2:.2f}s) — the user should have heard that.")except Exception as exc:- print(f" !! TTS-Error: {type(exc).__name__}: {exc}")+ print(f" !! TTS error: {type(exc).__name__}: {exc}")return 1await brain._brain_cache[list(brain._brain_cache.keys())[0]].close() if hasattr(@@ -60,5 +60,5 @@ async def main(user_text: str) -> int:if __name__ == "__main__":- text = sys.argv[1] if len(sys.argv) > 1 else "Sag kurz Hallo."+ text = sys.argv[1] if len(sys.argv) > 1 else "Say a brief hello."sys.exit(asyncio.run(main(text)))diff --git a/scripts/tts_output_sanity.py b/scripts/tts_output_sanity.pyindex 9a539a0dd6..07bb031fd0 100644--- a/scripts/tts_output_sanity.py+++ b/scripts/tts_output_sanity.py@@ -1,15 +1,15 @@-"""TTS-Output-Sanity-Check: spricht einen festen Satz via SAPI5-Fallback.+"""TTS output sanity check: speaks a fixed sentence via the SAPI5 fallback.-Benutzung:+Usage:python scripts/tts_output_sanity.py-Nutze das wenn du:-- Watchdog startest und nichts hörst-- Nicht sicher bist ob das richtige Output-Device aktiv ist-- Wissen willst ob Windows-TTS (Hedda) überhaupt spielbar ist+Use this when you:+- Start the watchdog and hear nothing+- Aren't sure whether the right output device is active+- Want to know whether Windows TTS (Hedda) can play at all-Das Script umgeht Gemini komplett und nutzt direkt den Windows-nativen-SAPI5-Fallback aus `jarvis/plugins/tts/gemini_flash_tts.py`.+This script bypasses Gemini entirely and directly uses the native Windows+SAPI5 fallback from `jarvis/plugins/tts/gemini_flash_tts.py`."""from __future__ import annotations@@ -30,19 +30,19 @@ async def main() -> int:from jarvis.plugins.tts.gemini_flash_tts import SAPI5_SAMPLE_RATE, _sapi5_synthesizetext = (- "Test eins zwei drei. Wenn du mich hörst, ist dein Audio-Output "- "korrekt eingerichtet und Windows-TTS funktioniert."+ "Test eins zwei drei. Wenn du mich hörst, ist dein Audio-Output " # i18n-allow+ "korrekt eingerichtet und Windows-TTS funktioniert." # i18n-allow)- print(f"[1] SAPI5-Synthese starten: {text!r}")+ print(f"[1] Starting SAPI5 synthesis: {text!r}")pcm = await asyncio.to_thread(_sapi5_synthesize, text, "de-DE")if not pcm:- print(" !! SAPI5 lieferte keine Bytes. Prüfe ob pywin32 installiert ist:")+ print(" !! SAPI5 returned no bytes. Check whether pywin32 is installed:")print(" pip install pywin32")return 1print(f" OK: {len(pcm)} bytes PCM ({len(pcm) / 2 / SAPI5_SAMPLE_RATE:.2f}s)")- print("[2] Audio abspielen auf System-Default-Output …")+ print("[2] Playing audio on the system default output …")player = AudioPlayer()chunk = AudioChunk(pcm=pcm,@@ -55,12 +55,12 @@ async def main() -> int:yield chunkawait player.play_chunks(_gen())- print("[3] Fertig. Hast du den Test-Satz gehört?")+ print("[3] Done. Did you hear the test sentence?")print()- print(" - JA → TTS + Audio-Pfad stimmt. Wenn Jarvis trotzdem stumm,")- print(" liegt's am Brain oder an der Pipeline-Verdrahtung.")- print(" - NEIN → Audio-Device ist falsch. Windows-Sound-Einstellungen:")- print(" Rechtsklick Lautsprecher-Icon → 'Audioausgabe auswählen'.")+ print(" - YES → TTS + audio path is fine. If Jarvis is still silent,")+ print(" the problem is in the Brain or the pipeline wiring.")+ print(" - NO → the audio device is wrong. Windows sound settings:")+ print(" right-click the speaker icon → 'Choose audio output'.")return 0diff --git a/scripts/vision_smoke.py b/scripts/vision_smoke.pyindex 7ec1b5cf36..2793d394f4 100644--- a/scripts/vision_smoke.py+++ b/scripts/vision_smoke.py@@ -1,19 +1,19 @@-"""Smoke-Skript fuer router-permanent-vision (Wave-3 Phase B + D).+"""Smoke script for router-permanent-vision (Wave 3 phase B + D).-Bootstrapped einen Mock-Stack (FakeVisionEngine + RouterBrain +-FakeBrain) und fuehrt zwei Messungen:+Bootstraps a mock stack (FakeVisionEngine + RouterBrain ++FakeBrain) and runs two measurements:-1. Happy-Path-Smoke: 1 Brain-Call mit User-Text "was siehst du auf- meinem screen" — assertet dass ImageBlock ankommt und Hash != leer.+1. Happy-path smoke: 1 Brain call with user text "was siehst du auf+ meinem screen" — asserts that an ImageBlock arrives and the hash is non-empty. # i18n-allow-2. Latency-Benchmark: 20 Brain-Calls mit Vision + 20 ohne. Miss- mean/p95 Inject-Overhead + mean Image-Bytes pro Call.+2. Latency benchmark: 20 Brain calls with vision + 20 without. Measures+ mean/p95 inject overhead + mean image bytes per call.-Startet in <5s auf normalem Dev-Setup. Keine echten API-Keys, keine-Audio-Aufnahme.+Starts in <5s on a normal dev setup. No real API keys, no+audio recording.-Ausgabe: JSON auf stdout + Human-readable Summary. Bei Fehler:-Exit-Code != 0.+Output: JSON on stdout + a human-readable summary. On error:+exit code != 0."""from __future__ import annotations@@ -30,7 +30,7 @@ from pathlib import Pathfrom typing import Anyfrom uuid import uuid4-# Repo-Root in sys.path, falls Skript aus scripts/ aufgerufen wird+# Add repo root to sys.path in case the script is invoked from scripts/_REPO_ROOT = Path(__file__).resolve().parent.parentif str(_REPO_ROOT) not in sys.path:sys.path.insert(0, str(_REPO_ROOT))@@ -129,7 +129,7 @@ async def _build_router(vision_provider: Any | None = None):async def phase_smoke(png_path: str) -> dict[str, Any]:- """Happy-Path-Smoke: 1 Brain-Call mit Vision aktiv."""+ """Happy-path smoke: 1 Brain call with vision active."""from jarvis.vision.context_provider import VisionContextProviderengine = FakeVisionEngine(png_path, png_hash="smoke-hash-abc")@@ -140,17 +140,17 @@ async def phase_smoke(png_path: str) -> dict[str, Any]:router, recorder = await _build_router(vision_provider=provider)t0 = time.perf_counter()- [_ async for _ in router.handle("was siehst du auf meinem screen")]+ [_ async for _ in router.handle("was siehst du auf meinem screen")] # i18n-allowdt_ms = (time.perf_counter() - t0) * 1000await provider.stop()- assert len(recorder.calls) == 1, "Recorder hat keinen Dispatch-Call gesehen"+ assert len(recorder.calls) == 1, "Recorder did not see a dispatch call"images = recorder.calls[0]["images"]- assert len(images) == 1, f"Erwarte genau 1 Image, bekam {len(images)}"+ assert len(images) == 1, f"Expected exactly 1 image, got {len(images)}"img = images[0]assert img.source_hash == "smoke-hash-abc", f"Hash mismatch: {img.source_hash}"- assert img.data_b64, "ImageBlock hat keine Daten"+ assert img.data_b64, "ImageBlock has no data"return {"status": "PASS",@@ -161,10 +161,10 @@ async def phase_smoke(png_path: str) -> dict[str, Any]:async def phase_benchmark(png_path: str, n: int = 20) -> dict[str, Any]:- """N Calls mit Vision, N ohne. Messung: mean + p95 Inject-Overhead."""+ """N calls with vision, N without. Measurement: mean + p95 inject overhead."""from jarvis.vision.context_provider import VisionContextProvider- # Mit Vision+ # With visionengine = FakeVisionEngine(png_path)provider = VisionContextProvider(engine, refresh_interval_s=0.05)await provider.start()@@ -177,13 +177,13 @@ async def phase_benchmark(png_path: str, n: int = 20) -> dict[str, Any]:t0 = time.perf_counter()[_ async for _ in router_with.handle("ping")]times_with.append((time.perf_counter() - t0) * 1000)- # Bytes vom letzten Call+ # Bytes from the last callfor c in rec_with.calls:if c["images"]:bytes_list.append(len(base64.b64decode(c["images"][0].data_b64)))await provider.stop()- # Ohne Vision+ # Without visionrouter_without, _ = await _build_router(vision_provider=None)times_without: list[float] = []for _ in range(n):@@ -218,7 +218,7 @@ async def phase_benchmark(png_path: str, n: int = 20) -> dict[str, Any]:async def main() -> int:start = time.perf_counter()- # 50-KB PNG als realistischer Mock-Screenshot+ # 50 KB PNG as a realistic mock screenshotpng_path, png_data = _make_png_file(size_kb=50)try:@@ -240,20 +240,20 @@ async def main() -> int:print(f"Image Hash: {smoke['image_hash']}")print(f"Image Bytes (raw): {smoke['image_raw_bytes']}")print()- print(f"Benchmark ({bench['n']} Calls je Branch):")+ print(f"Benchmark ({bench['n']} calls per branch):")print(f" With-Vision: mean {bench['with_vision']['mean_ms']} ms, p95 {bench['with_vision']['p95_ms']} ms")print(f" Without-Vision: mean {bench['without_vision']['mean_ms']} ms, p95 {bench['without_vision']['p95_ms']} ms")- print(f" Inject-Overhead: mean {bench['inject_overhead']['mean_ms']} ms, p95 {bench['inject_overhead']['p95_ms']} ms")+ print(f" Inject overhead: mean {bench['inject_overhead']['mean_ms']} ms, p95 {bench['inject_overhead']['p95_ms']} ms")print(f" Bytes/Call: mean {bench['bytes_per_call']['mean']} bytes")- print(f"Total-Duration: {total_s:.2f} s")+ print(f"Total duration: {total_s:.2f} s")print("=" * 60)if smoke["status"] != "PASS":return 1if bench["inject_overhead"]["mean_ms"] > 50.0:- print("WARN: Inject-Overhead > 50 ms — ueber Plan-Budget!", file=sys.stderr)+ print("WARN: inject overhead > 50 ms — over the plan budget!", file=sys.stderr)if total_s > 5.0:- print(f"WARN: Total-Duration {total_s:.1f}s > 5s — Plan-Limit ueberschritten.", file=sys.stderr)+ print(f"WARN: total duration {total_s:.1f}s > 5s — plan limit exceeded.", file=sys.stderr)return 0finally:try:diff --git a/scripts/voice_e2e_probe.py b/scripts/voice_e2e_probe.pyindex 88eaa19e5d..e670aa77fd 100644--- a/scripts/voice_e2e_probe.py+++ b/scripts/voice_e2e_probe.py@@ -1,26 +1,27 @@-"""Text-E2E-Abnahme des Persona-Refactors.+"""Text E2E acceptance test for the persona refactor.-Ruft den BrainManager im Router-Tier mit den Probe-Szenarien auf, sammelt-die Responses und prueft einfache Heuristiken gegen die erwarteten-Sprechmuster. Kein TTS, kein Mic — reiner Text-Pfad.+Calls the BrainManager in the router tier with the probe scenarios, collects+the responses, and checks simple heuristics against the expected+speech patterns. No TTS, no mic — pure text path.Setup:-- Persona-Mandat Phase 1: Output-Filter (``scrub_for_voice``) am TTS-Pfad —- hier nicht aktiv, weil das Skript den TTS-Pfad nicht durchlaeuft. Filter-- Tests sind separat in ``tests/unit/brain/test_output_filter.py``.-- Persona-Mandat Phase 2: ANTI_PATTERNS um Echo-/Hedging-/Filler-Strings- erweitert; Szenarien 11-13 fuer Echo-Trap, Tool-Output-Leak und- Self-Reference-Trap.-- Persona-Mandat Phase 3: ``build_default_brain(tier="router")`` aktiviert- den Pure-Dispatcher inkl. ROUTER DISCIPLINE-Prompt und der- deterministischen Force-Spawn-Heuristik.--Aufruf:+- Persona mandate phase 1: the output filter (``scrub_for_voice``) sits on+ the TTS path — not active here because the script never goes through the+ TTS path. Filter tests live separately in+ ``tests/unit/brain/test_output_filter.py``.+- Persona mandate phase 2: ANTI_PATTERNS extended with echo/hedging/filler+ strings; scenarios 11-13 cover the echo trap, tool-output leak, and+ self-reference trap.+- Persona mandate phase 3: ``build_default_brain(tier="router")`` activates+ the pure dispatcher including the ROUTER DISCIPLINE prompt and the+ deterministic force-spawn heuristic.++Run:python scripts/voice_e2e_probe.pyENV:-- ``JARVIS_PROBE_LANG=de|en|both`` Default: both. Steuert ob beide- Sprach-Varianten getestet werden (sofern definiert).+- ``JARVIS_PROBE_LANG=de|en|both`` Default: both. Controls whether both+ language variants are tested (where defined)."""from __future__ import annotations@@ -30,13 +31,13 @@ import sysfrom dataclasses import dataclassfrom pathlib import Path-# Repo-Root auf sys.path falls das Skript ausserhalb von ``cd <repo>`` laeuft.+# Add repo root to sys.path in case the script runs outside ``cd <repo>``.REPO = Path(__file__).resolve().parents[1]if str(REPO) not in sys.path:sys.path.insert(0, str(REPO))-# Persona-Loader fehlt auf Branch ``router-permanent-vision`` — defensiv-# importieren, damit das Skript trotzdem laeuft. Auf ``main`` waere er da.+# The persona loader is missing on the ``router-permanent-vision`` branch —+# import it defensively so the script still runs. It would be present on ``main``.try:from jarvis.brain.persona_loader import invalidate_cache, load_persona_prompt # type: ignoreHAS_PERSONA_LOADER = True@@ -52,10 +53,10 @@ except ModuleNotFoundError:@dataclass(frozen=True)class Scenario:- """Ein Probe-Szenario, optional bilingual.+ """A probe scenario, optionally bilingual.- ``user_en`` ist optional — wenn ``None``, wird nur ``user_de`` gefahren.- Sonst beide Sprachen, wenn ``JARVIS_PROBE_LANG`` das zulaesst.+ ``user_en`` is optional — if ``None``, only ``user_de`` is run.+ Otherwise both languages, if ``JARVIS_PROBE_LANG`` allows it."""id: strtag: str@@ -66,70 +67,70 @@ class Scenario:SCENARIOS: tuple[Scenario, ...] = (Scenario("01", "routine-status",- user_de="Ist die Datei gespeichert?",- pattern="Fakt zuerst, kein Name (Pattern 1, 2)"),+ user_de="Ist die Datei gespeichert?", # i18n-allow+ pattern="Fact first, no name (Pattern 1, 2)"),Scenario("02", "formal-greeting",- user_de="Guten Morgen.",- pattern="Formelle Zustandsmeldung mit Name (Pattern 2)"),+ user_de="Guten Morgen.", # i18n-allow+ pattern="Formal status update with name (Pattern 2)"),Scenario("03", "open-question",- user_de="Wie kann ich das beschleunigen?",- pattern="Shall-I-Frageform statt offener Rueckfrage (Pattern 3)"),+ user_de="Wie kann ich das beschleunigen?", # i18n-allow+ pattern="Shall-I question form instead of an open follow-up question (Pattern 3)"),Scenario("04", "risky-command",- user_de="Loesche alle Logs von gestern.",- pattern="One-Warning mit Fakt, dann Ausfuehrung (Pattern 4)"),+ user_de="Loesche alle Logs von gestern.", # i18n-allow+ pattern="One warning with fact, then execution (Pattern 4)"),Scenario("05", "reckless-action",- user_de="Ich starte jetzt den Deploy auf Prod ohne Tests.",- pattern="Trockener Kommentar mit Anker (Pattern 5)"),+ user_de="Ich starte jetzt den Deploy auf Prod ohne Tests.", # i18n-allow+ pattern="Dry comment with an anchor (Pattern 5)"),Scenario("06", "proactive-context",- user_de="Wie warm ist es draussen?",- pattern="Fakt + EIN Zusatzsatz (Pattern 6)"),+ user_de="Wie warm ist es draussen?", # i18n-allow+ pattern="Fact + ONE additional sentence (Pattern 6)"),Scenario("07", "long-task-start",- user_de="Analysiere das gesamte Projektverzeichnis.",- pattern="Initiative-Ankuendigung in 3 Teilen (Pattern 7)"),+ user_de="Analysiere das gesamte Projektverzeichnis.", # i18n-allow+ pattern="Initiative announcement in 3 parts (Pattern 7)"),Scenario("08", "bad-news",- user_de="Hat der Build funktioniert?",- pattern="Bad news ohne Polsterung (Pattern 8)"),+ user_de="Hat der Build funktioniert?", # i18n-allow+ pattern="Bad news without padding (Pattern 8)"),Scenario("09", "high-pressure",- user_de="Schnell, die Praesentation beginnt gleich!",- pattern="Kuerzer unter Druck, Register bricht nicht (Pattern 9)"),+ user_de="Schnell, die Praesentation beginnt gleich!", # i18n-allow+ pattern="Shorter under pressure, register doesn't break (Pattern 9)"),Scenario("10", "hangup",- user_de="Das war's, danke.",- pattern="Exakt der Hangup-Contract"),- # Persona-Mandat Phase 2 — drei neue Szenarien fuer Echo-Trap,- # Tool-Output-Leak und Self-Reference-Trap, jeweils bilingual.+ user_de="Das war's, danke.", # i18n-allow+ pattern="Exact hangup contract"),+ # Persona mandate phase 2 — three new scenarios for the echo trap,+ # tool-output leak, and self-reference trap, each bilingual.Scenario("11", "echo-trap",- user_de="Ich möchte wissen, wie spät es ist.",+ user_de="Ich möchte wissen, wie spät es ist.", # i18n-allowuser_en="I want to know what time it is.",- pattern="Direkte Zeit-Antwort, KEIN 'Du möchtest also wissen...'"),+ pattern="Direct time answer, NO 'So you'd like to know...'"),Scenario("12", "tool-spawn-output-leak",- user_de="Lies die Datei jarvis.toml und sag mir was drin steht.",+ user_de="Lies die Datei jarvis.toml und sag mir was drin steht.", # i18n-allowuser_en="Read the file jarvis.toml and tell me what's inside.",- pattern="Inhalt zusammengefasst, keine Tool-Args, kein dispatch_to_harness JSON"),+ pattern="Content summarized, no tool args, no dispatch_to_harness JSON"),Scenario("13", "self-reference-trap",- user_de="Was bist du eigentlich?",+ user_de="Was bist du eigentlich?", # i18n-allowuser_en="What are you actually?",- pattern="Butler-Identitaet, KEIN 'Ich bin ein Sprachmodell'"),+ pattern="Butler identity, NO 'I am a language model'"),)-# Anti-Patterns — werden case-insensitiv gegen jede Brain-Response gematcht.-# Jedes Vorkommen zaehlt als DRIFT. Erweitert in Persona-Mandat Phase 2 um-# Echo-Paraphrase, Hedging, Filler-Selbstreferenz, Polster.+# Anti-patterns — matched case-insensitively against every Brain response.+# Each occurrence counts as DRIFT. Extended in persona mandate phase 2 with+# echo paraphrase, hedging, filler self-reference, padding.ANTI_PATTERNS = [- # Klassisch (Phase 0)- "grossartige frage", "tolle frage",- "als ki", "als sprachmodell",- "ich hoffe, das hilft",- # Echo-Paraphrase (Phase 2)- "du möchtest also", "ich verstehe, dass",+ # Classic (phase 0)+ "grossartige frage", "tolle frage", # i18n-allow+ "als ki", "als sprachmodell", # i18n-allow+ "ich hoffe, das hilft", # i18n-allow+ # Echo paraphrase (phase 2)+ "du möchtest also", "ich verstehe, dass", # i18n-allow"if i understand correctly", "you'd like me to",- # Hedging (Phase 2)- "ich glaube", "vermutlich", "möglicherweise",+ # Hedging (phase 2)+ "ich glaube", "vermutlich", "möglicherweise", # i18n-allow"i think", "perhaps", "i believe",- # Filler-Selbstreferenz (Phase 2)- "lass mich kurz", "let me think",- # Polster (Phase 2)- "es tut mir leid, aber", "i'm so sorry to say",+ # Filler self-reference (phase 2)+ "lass mich kurz", "let me think", # i18n-allow+ # Padding (phase 2)+ "es tut mir leid, aber", "i'm so sorry to say", # i18n-allow]@@ -139,45 +140,45 @@ async def probe() -> int:from jarvis.core.bus import EventBusfrom jarvis.core.config import load_config- print(f"Persona-Loader vorhanden: {HAS_PERSONA_LOADER}")+ print(f"Persona loader present: {HAS_PERSONA_LOADER}")invalidate_cache()persona = load_persona_prompt()- print(f"Persona-Block geladen: {len(persona)} chars")+ print(f"Persona block loaded: {len(persona)} chars")cfg = load_config(Path("jarvis.toml"))primary = cfg.brain.primaryprimary_provider = cfg.brain.providers.get(primary)primary_model = primary_provider.model if primary_provider else "?"- print(f"Primary Brain: {primary} / {primary_model}")+ print(f"Primary brain: {primary} / {primary_model}")bus = EventBus()- # Bevorzugt: build_default_brain(tier='router') — voller Voice-Pfad mit- # Tools + Force-Spawn-Heuristik. Fallback: direkter BrainManager mit- # Router-Prompt — wenn das Tool-Loading scheitert (z.B. wegen fehlendem- # ``jarvis.clis.risk_integration`` auf der aktuellen Branch).+ # Preferred: build_default_brain(tier='router') — full voice path with+ # tools + force-spawn heuristic. Fallback: direct BrainManager with the+ # router prompt — used when tool loading fails (e.g. because+ # ``jarvis.clis.risk_integration`` is missing on the current branch).bm: BrainManager | None = Nonetry:from jarvis.brain.factory import build_default_brainbm = build_default_brain(tier="router", bus=bus)- print("Brain-Setup: build_default_brain(tier='router') ✓")+ print("Brain setup: build_default_brain(tier='router') ✓")except Exception as exc: # noqa: BLE001- print(f"Brain-Setup-Fallback: factory failed ({type(exc).__name__}: {exc})")+ print(f"Brain setup fallback: factory failed ({type(exc).__name__}: {exc})")bm = BrainManager(config=cfg, bus=bus, tools={}, tool_executor=None)try:from jarvis.brain.router import SYSTEM_PROMPT as ROUTER_SYSTEM_PROMPTbm._system_prompt_extra = ROUTER_SYSTEM_PROMPT # type: ignore[attr-defined]- print("Brain-Setup: direkter BrainManager + ROUTER SYSTEM_PROMPT manuell ✓")+ print("Brain setup: direct BrainManager + ROUTER SYSTEM_PROMPT manually ✓")except Exception as exc2: # noqa: BLE001- print(f"Router-Prompt-Inject fehlgeschlagen: {exc2}")+ print(f"Router prompt injection failed: {exc2}")prompt = ""try:prompt = bm._build_system_prompt() # type: ignore[attr-defined]except AttributeError:prompt = getattr(bm, "_system_prompt_extra", "")- print(f"System-Prompt: {len(prompt)} chars")- print(f" Enthaelt 'ROUTER DISCIPLINE': {'ROUTER DISCIPLINE' in prompt}")- print(f" Enthaelt 'ECHO-PARAPHRASE': {'ECHO-PARAPHRASE' in prompt}")+ print(f"System prompt: {len(prompt)} chars")+ print(f" Contains 'ROUTER DISCIPLINE': {'ROUTER DISCIPLINE' in prompt}")+ print(f" Contains 'ECHO-PARAPHRASE': {'ECHO-PARAPHRASE' in prompt}")print()lang_mode = (os.environ.get("JARVIS_PROBE_LANG") or "both").lower()@@ -203,30 +204,30 @@ async def probe() -> int:raw_response = await bm(user_text)except Exception as exc: # noqa: BLE001raw_response = f"<ERROR: {type(exc).__name__}: {exc}>"- # Phase-1-Filter im Probe spiegelt das wider, was der User- # tatsaechlich hoert: Brain-Output -> scrub_for_voice -> TTS.+ # The phase-1 filter in the probe mirrors what the user+ # actually hears: Brain output -> scrub_for_voice -> TTS.scrubbed = scrub_for_voice(raw_response, language=lang)response = scrubbed.cleanedif scrubbed.actions:print(f"Filter: {scrubbed.actions} (fallback={scrubbed.fallback_used})")print(f"Jarvis: {response}")- print(f"Erwartet: {s.pattern}")+ print(f"Expected: {s.pattern}")print()results.append((s.id, lang, s.tag, user_text, response, s.pattern))print("=" * 60)- print("HEURISTIK-CHECKS")+ print("HEURISTIC CHECKS")print("=" * 60)total = len(results)if total == 0:- print("Keine Szenarien ausgefuehrt.")+ print("No scenarios were run.")return 0with_name = sum(1 for r in results if "Ruben" in r[4])name_ratio = with_name / total- print(f"Name-Frequenz: {with_name}/{total} ({name_ratio:.0%}) — Ziel <= 33 %.")- print(f" Ergebnis: {'OK' if name_ratio <= 0.34 else 'DRIFT'}")+ print(f"Name frequency: {with_name}/{total} ({name_ratio:.0%}) — target <= 33%.")+ print(f" Result: {'OK' if name_ratio <= 0.34 else 'DRIFT'}")too_long = [r[0] for r in results if len(r[4]) > 220]print(f"Responses > 220 chars: {len(too_long)} {too_long}")@@ -235,33 +236,33 @@ async def probe() -> int:(r[0], r[1], pat) for r in resultsfor pat in ANTI_PATTERNS if pat in r[4].lower()]- print(f"Anti-Pattern-Treffer: {len(anti_hits)} {anti_hits}")+ print(f"Anti-pattern hits: {len(anti_hits)} {anti_hits}")sie_hits = [(r[0], r[1]) for r in results- if any(tok in r[4] for tok in (" Sie ", " Ihnen ", " Ihre ", "Sie möchten"))+ if any(tok in r[4] for tok in (" Sie ", " Ihnen ", " Ihre ", "Sie möchten")) # i18n-allow]- print(f"Siezen-Vorkommen: {len(sie_hits)} {sie_hits}")+ print(f"Formal 'Sie' occurrences: {len(sie_hits)} {sie_hits}")filler_as_opener = [(r[0], r[1]) for r in resultsif r[4].strip().startswith((- "Einen Moment, Ruben", "Einen Augenblick", "Ich schaue gleich nach",+ "Einen Moment, Ruben", "Einen Augenblick", "Ich schaue gleich nach", # i18n-allow)) and r[0] not in ("06",)]- print(f"Filler-als-Opener (nicht-Tool-Scenarios): {len(filler_as_opener)} {filler_as_opener}")+ print(f"Filler-as-opener (non-tool scenarios): {len(filler_as_opener)} {filler_as_opener}")- # Hangup-Contract: Szenario 10 muss exakt eine der beiden Phrasen liefern.+ # Hangup contract: scenario 10 must return exactly one of the two phrases.hangup_de_runs = [r for r in results if r[0] == "10" and r[1] == "de"]if hangup_de_runs:hangup = hangup_de_runs[0][4]- hangup_ok = "auf wiedersehen, ruben" in hangup.lower()- print(f"Hangup-Contract DE (Szenario 10): {'OK' if hangup_ok else 'MISS'}")+ hangup_ok = "auf wiedersehen, ruben" in hangup.lower() # i18n-allow+ print(f"Hangup contract DE (scenario 10): {'OK' if hangup_ok else 'MISS'}")hangup_en_runs = [r for r in results if r[0] == "10" and r[1] == "en"]if hangup_en_runs:hangup_en = hangup_en_runs[0][4]hangup_en_ok = "goodbye, ruben" in hangup_en.lower()- print(f"Hangup-Contract EN (Szenario 10): {'OK' if hangup_en_ok else 'MISS'}")+ print(f"Hangup contract EN (scenario 10): {'OK' if hangup_en_ok else 'MISS'}")return 0diff --git a/scripts/voice_style_eval.py b/scripts/voice_style_eval.pyindex d81c9d6c87..791a4acb99 100644--- a/scripts/voice_style_eval.py+++ b/scripts/voice_style_eval.py@@ -68,14 +68,14 @@ class Scenario:# Realistic, conversational turns that SHOULD get a full-sentence spoken answer# and do NOT depend on a tool (so the style, not a tool round-trip, is measured).SCENARIOS: tuple[Scenario, ...] = (- Scenario("01", "greeting", "Guten Morgen, wie geht es dir?"),- Scenario("02", "smalltalk", "Ich bin heute echt ein bisschen gestresst."),- Scenario("03", "opinion-80s", "Was hältst du eigentlich von Musik aus den Achtzigern?"),- Scenario("04", "explain", "Erklär mir mal, warum der Himmel blau ist."),- Scenario("05", "advice", "Hast du einen Tipp, wie ich morgens besser in die Gänge komme?"),- Scenario("06", "knowledge", "Erzähl mir was Interessantes über den Mond."),- Scenario("07", "compare", "Was ist der Unterschied zwischen Nebel und Wolken?"),- Scenario("08", "chitchat", "Puh, war ein langer Tag. Womit kennst du dich eigentlich gut aus?"),+ Scenario("01", "greeting", "Guten Morgen, wie geht es dir?"), # i18n-allow+ Scenario("02", "smalltalk", "Ich bin heute echt ein bisschen gestresst."), # i18n-allow+ Scenario("03", "opinion-80s", "Was hältst du eigentlich von Musik aus den Achtzigern?"), # i18n-allow+ Scenario("04", "explain", "Erklär mir mal, warum der Himmel blau ist."), # i18n-allow+ Scenario("05", "advice", "Hast du einen Tipp, wie ich morgens besser in die Gänge komme?"), # i18n-allow+ Scenario("06", "knowledge", "Erzähl mir was Interessantes über den Mond."), # i18n-allow+ Scenario("07", "compare", "Was ist der Unterschied zwischen Nebel und Wolken?"), # i18n-allow+ Scenario("08", "chitchat", "Puh, war ein langer Tag. Womit kennst du dich eigentlich gut aus?"), # i18n-allow)diff --git a/scripts/wiki_migrate_v0_to_v1.py b/scripts/wiki_migrate_v0_to_v1.pyindex f75e12bd1e..18d9b22d57 100644--- a/scripts/wiki_migrate_v0_to_v1.py+++ b/scripts/wiki_migrate_v0_to_v1.py@@ -76,10 +76,10 @@ def slugify(name: str) -> str:"""Map a free-form name to a kebab-case ASCII slug."""s = name.strip().lower()s = (- s.replace("ä", "ae")- .replace("ö", "oe")- .replace("ü", "ue")- .replace("ß", "ss")+ s.replace("ä", "ae") # i18n-allow+ .replace("ö", "oe") # i18n-allow+ .replace("ü", "ue") # i18n-allow+ .replace("ß", "ss") # i18n-allow)s = _SLUG_RE.sub("-", s).strip("-")return s or "unnamed"diff --git a/skillbook/src/skillbook/ace_core/llm.py b/skillbook/src/skillbook/ace_core/llm.pyindex 5950c0034a..34fffde7b6 100644--- a/skillbook/src/skillbook/ace_core/llm.py+++ b/skillbook/src/skillbook/ace_core/llm.py@@ -22,7 +22,7 @@ The previous in-tree ``MockLLM`` deterministic fallback lives in``tests/fakes/llm.py:FakeLLM`` per ADR-0010 — production paths never fallback to test doubles. The original ADR-0004 named Anthropic as the onlyproduction LLM; that was the wrong default for this project (parent-``MEMORY.md``: "kein Anthropic-Konto, alles über cfg.brain.primary =+``MEMORY.md``: "no Anthropic account, everything via cfg.brain.primary =Gemini"). The multi-provider design here makes the active-brain choiceexplicit at the call site."""diff --git a/tests/integration/test_frontier_autoswitch.py b/tests/integration/test_frontier_autoswitch.pyindex a84373aaa3..51a02ea5e3 100644--- a/tests/integration/test_frontier_autoswitch.py+++ b/tests/integration/test_frontier_autoswitch.py@@ -1,13 +1,13 @@-"""Integration-Test fuer den Frontier-Autoswitch-Boot-Hook.--Mit gemocktem FrontierResolver verifizieren wir:-1. Bei neuerem Modell: ProviderConfig wird mutiert + Bus-Event emittiert +- Pending-Eintrag liegt in der Modal-Queue.-2. Bei gleichem Modell: keine Mutation, kein Event, keine Pending.-3. Bei Resolver-Crash: keine Mutation, kein Event, kein Pending —- silent Fallback auf TOML-Default.-4. Sub-Jarvis-Override (`[brain.sub_jarvis] model = "..."`) bleibt- unangetastet.+"""Integration test for the Frontier-Autoswitch boot hook.++With a mocked FrontierResolver we verify:+1. On a newer model: ProviderConfig is mutated + a bus event is emitted ++ a pending entry lands in the modal queue.+2. On the same model: no mutation, no event, no pending.+3. On a resolver crash: no mutation, no event, no pending —+ silent fallback to the TOML default.+4. The Sub-Jarvis override (`[brain.sub_jarvis] model = "..."`) stays+ untouched."""from __future__ import annotations@@ -26,7 +26,7 @@ from jarvis.core.events import FrontierModelSwitchedclass _StubResolver:- """Resolver-Stub: returns vorgegebene Werte pro (provider, tier)."""+ """Resolver stub: returns pre-set values per (provider, tier)."""def __init__(self, mapping: dict[tuple[str, str], str | None]) -> None:self._map = mapping@@ -38,14 +38,14 @@ class _StubResolver:class _CrashingResolver:- """Resolver-Stub der bei jedem Call crasht."""+ """Resolver stub that crashes on every call."""async def resolve_latest(self, provider: str, tier: str) -> str | None:raise RuntimeError("simulated provider down")def _make_config_with_old_models() -> JarvisConfig:- """Baut eine JarvisConfig mit alten Hauptjarvis-Modellen + Sub-Jarvis-Pin."""+ """Builds a JarvisConfig with old Hauptjarvis models + a Sub-Jarvis pin."""cfg = JarvisConfig.model_validate({"brain": {"primary": "claude-api",@@ -83,10 +83,10 @@ def _clear_pending_between_tests() -> Any:@pytest.fixture(autouse=True)def _mock_toml_persist(monkeypatch: pytest.MonkeyPatch) -> list[tuple[str, dict[str, str | None]]]:- """Verhindert, dass Tests die echte jarvis.toml beschreiben.+ """Prevents tests from writing the real jarvis.toml.- Returns die Liste der Calls, damit Tests verifizieren koennen dass- persist tatsaechlich aufgerufen wurde.+ Returns the list of calls so tests can verify that+ persist was actually invoked."""calls: list[tuple[str, dict[str, str | None]]] = []@@ -109,8 +109,8 @@ async def test_apply_switches_when_resolver_returns_newer_models(("gemini", "fast"): "gemini-3-flash",("gemini", "deep"): "gemini-3.1-pro-preview",("openai", "fast"): "gpt-5.5",- ("claude-api", "fast"): "claude-sonnet-4-6", # unverändert- ("claude-api", "deep"): "claude-opus-4-7", # unverändert+ ("claude-api", "fast"): "claude-sonnet-4-6", # unchanged+ ("claude-api", "deep"): "claude-opus-4-7", # unchanged})bus = EventBus()received: list[FrontierModelSwitched] = []@@ -118,7 +118,7 @@ async def test_apply_switches_when_resolver_returns_newer_models(switches = await apply_frontier_resolution(cfg, resolver, bus)- # Verifiziere dass TOML-Persist auch gerufen wurde (3 Switches → 3 Calls).+ # Verify that TOML persist was also called (3 switches → 3 calls).assert len(_mock_toml_persist) == 3persist_providers = {p for p, _ in _mock_toml_persist}assert persist_providers == {"gemini", "openai"}@@ -139,7 +139,7 @@ async def test_apply_switches_when_resolver_returns_newer_models(assert cfg.brain.worker is not Noneassert cfg.brain.worker.model == "gemini-2.5-pro"- # Bus-Events publisht (event-loop-tick fuer subscribe-async)+ # Bus events published (event-loop tick for subscribe-async)import asyncioawait asyncio.sleep(0.01)assert len(received) == 3@@ -160,7 +160,7 @@ async def test_disabled_by_default_is_noop(_mock_toml_persist: list[tuple[str, dict[str, str | None]]],) -> None:"""With ``brain.frontier_auto_apply`` unset (default False) the boot hook is- a complete no-op: no resolver call, no TOML/soll persist, no mutation, no+ a complete no-op: no resolver call, no TOML/soll persist, no mutation, no # i18n-allow — "soll" = config-soll.json, not German proseevent, no pending — even though newer models are available. User mandate2026-06-20: providers/models must NOT switch by themselves."""@@ -180,7 +180,7 @@ async def test_disabled_by_default_is_noop(assert switches == []assert resolver.calls == [] # resolver never queried- assert _mock_toml_persist == [] # nothing persisted to TOML/soll+ assert _mock_toml_persist == [] # nothing persisted to TOML/soll # i18n-allow — "soll" = config-soll.jsonassert cfg.brain.providers["gemini"].model == "gemini-2.5-flash" # unmutatedassert get_pending_switches() == []import asyncio@@ -217,7 +217,7 @@ async def test_resolver_crash_does_not_mutate_config() -> None:resolver = _CrashingResolver()bus = EventBus()- # Sollte nicht raisen — Auto-Switch ist defensive.+ # Should not raise — auto-switch is defensive.switches = await apply_frontier_resolution(cfg, resolver, bus)assert switches == []@@ -227,12 +227,12 @@ async def test_resolver_crash_does_not_mutate_config() -> None:@pytest.mark.asyncioasync def test_resolver_returns_none_no_switch() -> None:- """Wenn Resolver fuer einen Provider None liefert (z.B. kein API-Key),- soll fuer diesen Provider nichts passieren — andere Provider weiterhin OK.+ """When the resolver returns None for a provider (e.g. no API key),+ nothing should happen for that provider — other providers stay OK."""cfg = _make_config_with_old_models()resolver = _StubResolver({- ("gemini", "fast"): None, # kein Key+ ("gemini", "fast"): None, # no key("gemini", "deep"): None,("openai", "fast"): "gpt-5.5", # OK("claude-api", "fast"): "claude-sonnet-4-6",diff --git a/tests/integration/test_haiku_multi_tool_live.py b/tests/integration/test_haiku_multi_tool_live.pyindex 094d12f7c9..a85d4f719f 100644--- a/tests/integration/test_haiku_multi_tool_live.py+++ b/tests/integration/test_haiku_multi_tool_live.py@@ -1,7 +1,7 @@-"""Live-Integration-Test: Haiku + Multi-Tool ("5 terminals" usecase).+"""Live integration test: Haiku + multi-tool ("5 terminals" use case).-Skipped by default wenn kein Claude-OAuth-Token da — kein CI-Flakiness.-Laufen mit: pytest tests/integration/test_haiku_multi_tool_live.py -v --run-live+Skipped by default when there's no Claude OAuth token — no CI flakiness.+Run with: pytest tests/integration/test_haiku_multi_tool_live.py -v --run-live"""from __future__ import annotations@@ -16,7 +16,7 @@ def _api_key_available() -> bool:@pytest.mark.voice_latency[email protected](not _api_key_available(), reason="kein Brain-API-Key")[email protected](not _api_key_available(), reason="no brain API key")@pytest.mark.asyncioasync def test_haiku_speed_under_5s():from jarvis.brain.factory import build_default_brain@@ -30,25 +30,25 @@ async def test_haiku_speed_under_5s():@pytest.mark.voice_latency[email protected](not _api_key_available(), reason="kein Brain-API-Key")[email protected](not _api_key_available(), reason="no brain API key")@pytest.mark.asyncioasync def test_haiku_spawn_multiple_terminals():- """Latenz-Test: Wie lang braucht das Brain für einen komplexen Multi-Task-Request?+ """Latency test: how long does the brain need for a complex multi-task request?- Ergebnis kann ein Tool-Call oder eine erklärende Antwort sein — Hauptsache- das Brain antwortet innerhalb der Deadline. (open_app wurde in älteren Builds- als Assertion-Anker genutzt; der Tool wurde entfernt — jetzt pure Latenz.)+ The result can be a tool call or an explanatory answer — the point is+ that the brain answers within the deadline. (open_app used to be the+ assertion anchor in older builds; the tool was removed — now pure latency.)"""from jarvis.brain.factory import build_default_brainbrain = build_default_brain()t0 = time.perf_counter()r = await asyncio.wait_for(- brain.generate("Öffne bitte 3 Terminals (Windows Terminal, wt)."),+ brain.generate("Öffne bitte 3 Terminals (Windows Terminal, wt)."), # i18n-allowtimeout=45,)dt = time.perf_counter() - t0print(f"\nMulti-Request-Latenz: {dt:.2f}s")print(f"Response: {r[:200]}")- assert r, "Brain muss eine Antwort liefern"+ assert r, "brain must return a response"assert dt < 30.0, f"Brain zu langsam: {dt}s"diff --git a/tests/integration/test_jarvis_agent_model_drift.py b/tests/integration/test_jarvis_agent_model_drift.pyindex ac9707cce2..4403bb14c9 100644--- a/tests/integration/test_jarvis_agent_model_drift.py+++ b/tests/integration/test_jarvis_agent_model_drift.py@@ -4,16 +4,16 @@ approved-access-only / unreachable model (BUG-010 config-drift class).History (2026-06-14): the heavy-worker model was migrated claude-fable-5 ->claude-opus-4-8 because the Claude Max subscription lost CLI access to Fable("Claude Fable 5 is currently unavailable", 404 model_not_found). The migration-updated ``config-soll.json`` (the drift-guard's desired state) and the Python+updated ``config-soll.json`` (the drift-guard's desired state) and the Python # i18n-allowdefault ``_DEFAULT_CLAUDE_MODEL`` — but NOT the value the resolver actually readsfirst, ``[brain.sub_jarvis].model`` in ``jarvis.toml``. ``jarvis.toml`` isread-only and nothing reconciled the approved value down into it, so the two-files silently disagreed: soll said opus, toml said fable, and every worker+files silently disagreed: soll said opus, toml said fable, and every worker # i18n-allowspawned ``claude --model claude-fable-5`` -> 404 -> ``task_error``. The fix wentinto a layer the live path never consults, which is why "the Fable bug cameback".-These tests fail loudly the moment ``jarvis.toml`` and ``config-soll.json``+These tests fail loudly the moment ``jarvis.toml`` and ``config-soll.json`` # i18n-allowdisagree on the worker/critic model pins, or the moment an unreachable model ispinned in the tracked source-of-truth. The existing``test_subagent_model_route.py`` mocks the config writer and so could never have@@ -29,7 +29,7 @@ import pytest_REPO_ROOT = Path(__file__).resolve().parents[2]_JARVIS_TOML = _REPO_ROOT / "jarvis.toml"-_CONFIG_SOLL = _REPO_ROOT / "scripts" / "config-soll.json"+_CONFIG_SOLL = _REPO_ROOT / "scripts" / "config-soll.json" # i18n-allow# Models the Claude Max subscription cannot reach via the ``claude`` CLI. Pinning# any of these on the worker/critic path is a guaranteed 404 -> task_error.@@ -39,14 +39,14 @@ _UNREACHABLE_CLAUDE_MODELS = frozenset({"claude-fable-5"})_MODEL_KEYS = (# Renamed from brain.sub_jarvis → brain.worker in the 2026-06-29# Jarvis-Agents rename; both the TOML section header and the- # config-soll.json flat key now use "brain.worker".+ # config-soll.json flat key now use "brain.worker". # i18n-allow("brain.worker", "model"),("brain.providers.claude-api", "deep_model"),)-def _load_soll() -> dict:- return json.loads(_CONFIG_SOLL.read_text(encoding="utf-8-sig"))+def _load_soll() -> dict: # i18n-allow+ return json.loads(_CONFIG_SOLL.read_text(encoding="utf-8-sig")) # i18n-allowdef _load_toml() -> dict:@@ -54,10 +54,10 @@ def _load_toml() -> dict:return tomllib.loads(_JARVIS_TOML.read_text(encoding="utf-8-sig"))-def _soll_value(soll: dict, dotted: str, key: str) -> str | None:- block = soll.get(dotted)+def _soll_value(soll: dict, dotted: str, key: str) -> str | None: # i18n-allow+ block = soll.get(dotted) # i18n-allowif block is None: # some entries are nested instead of dotted- cur: object = soll+ cur: object = soll # i18n-allowfor part in dotted.split("."):if not isinstance(cur, dict):return None@@ -93,17 +93,17 @@ def _toml_value(toml: dict, dotted: str, key: str) -> str | None:return val-def test_soll_worker_model_pins_are_reachable() -> None:+def test_soll_worker_model_pins_are_reachable() -> None: # i18n-allow"""The tracked drift-guard source-of-truth must not pin an unreachable model.- config-soll.json ships in git (cloud-first), so this always runs — including- on a fresh VPS checkout — and guards against re-pinning Fable in the soll.+ config-soll.json ships in git (cloud-first), so this always runs — including # i18n-allow+ on a fresh VPS checkout — and guards against re-pinning Fable in the soll. # i18n-allow"""- soll = _load_soll()+ soll = _load_soll() # i18n-allowfor dotted, key in _MODEL_KEYS:- value = _soll_value(soll, dotted, key)+ value = _soll_value(soll, dotted, key) # i18n-allowassert value not in _UNREACHABLE_CLAUDE_MODELS, (- f"config-soll.json {dotted}.{key} = {value!r} is approved-access-only "+ f"config-soll.json {dotted}.{key} = {value!r} is approved-access-only " # i18n-allowf"and unreachable via the Claude Max CLI; every worker/critic spawn "f"would 404 -> task_error. Pin a reachable model (e.g. claude-opus-4-8).")@@ -111,37 +111,37 @@ def test_soll_worker_model_pins_are_reachable() -> None:@pytest.mark.skipif(not _JARVIS_TOML.exists(),- reason="no local jarvis.toml (fresh checkout / headless VPS) — soll guard covers it",+ reason="no local jarvis.toml (fresh checkout / headless VPS) — soll guard covers it", # i18n-allow)-def test_jarvis_toml_model_pins_match_soll() -> None:+def test_jarvis_toml_model_pins_match_soll() -> None: # i18n-allow"""``jarvis.toml`` (what ``load_config`` reads) must agree with the approved- ``config-soll.json`` on every worker/critic model pin.+ ``config-soll.json`` on every worker/critic model pin. # i18n-allow- This is the exact invariant that broke on 2026-06-14: soll updated to+ This is the exact invariant that broke on 2026-06-14: soll updated to # i18n-allowclaude-opus-4-8, jarvis.toml left stale at claude-fable-5. Because theresolver reads jarvis.toml first and returns it verbatim, the stale valuewon and the mission 404'd. A 3-layer ``config_writer.set_sub_jarvis_model``keeps them in lock-step; a raw TOML-only edit (or a drift-guard that neverran) reintroduces the split this test catches."""- soll = _load_soll()+ soll = _load_soll() # i18n-allowtoml = _load_toml()mismatches: list[str] = []for dotted, key in _MODEL_KEYS:toml_val = _toml_value(toml, dotted, key)- soll_val = _soll_value(soll, dotted, key)+ soll_val = _soll_value(soll, dotted, key) # i18n-allow# A missing pin on either side must FAIL — otherwise a renamed/typo'd key# that vanishes from BOTH files makes `None == None` pass vacuously and# the guard silently stops guarding (the very BUG-010 regression it# exists to catch).- if toml_val is None or soll_val is None:+ if toml_val is None or soll_val is None: # i18n-allowmismatches.append(f" {dotted}.{key}: missing pin (jarvis.toml={toml_val!r}, "- f"config-soll={soll_val!r}) — both must define it"+ f"config-soll={soll_val!r}) — both must define it" # i18n-allow)- elif toml_val != soll_val:+ elif toml_val != soll_val: # i18n-allowmismatches.append(- f" {dotted}.{key}: jarvis.toml={toml_val!r} != config-soll={soll_val!r}"+ f" {dotted}.{key}: jarvis.toml={toml_val!r} != config-soll={soll_val!r}" # i18n-allow)assert not mismatches, ("jarvis.toml drifted from config-soll.json on worker/critic model "diff --git a/tests/integration/test_jarvis_agent_model_route.py b/tests/integration/test_jarvis_agent_model_route.pyindex afa885caf2..0277853149 100644--- a/tests/integration/test_jarvis_agent_model_route.py+++ b/tests/integration/test_jarvis_agent_model_route.py@@ -3,7 +3,7 @@The API-Keys "Subagent" section lets the user pin which MODEL the heavy-tasksub-agents run, separate from the router brain. Write side:``POST /api/jarvis-agent/model`` -> 3-layer ``config_writer.set_sub_jarvis_model``-(TOML + config-soll + ENV — ``brain.sub_jarvis.model`` is drift-guard pinned).+(TOML + config-soll + ENV — ``brain.sub_jarvis.model`` is drift-guard pinned). # i18n-allowRead side: ``GET /api/openclaw/status`` exposes ``sub_model_override`` and theeffective ``model_resolved`` (override wins, else the provider's deep model)."""@@ -30,7 +30,7 @@ def server() -> Iterator[WebServer]:@pytest.fixture(autouse=True)def _no_toml_write(monkeypatch: pytest.MonkeyPatch) -> list[str]:- """Capture persistence instead of writing the real jarvis.toml/soll/ENV."""+ """Capture persistence instead of writing the real jarvis.toml/soll/ENV.""" # i18n-allowcalls: list[str] = []from jarvis.core import config_writerdiff --git a/tests/integration/test_launcher_headless.py b/tests/integration/test_launcher_headless.pyindex 262512e8b1..60fd08ef33 100644--- a/tests/integration/test_launcher_headless.py+++ b/tests/integration/test_launcher_headless.py@@ -1,11 +1,11 @@-"""Integration-Test für `_run_headless` mit Mock-WebServer.+"""Integration test for `_run_headless` with a mock WebServer.-Simuliert: Launcher startet, wird gecancelt → sauberer Shutdown.+Simulates: launcher starts, gets cancelled → clean shutdown.-Alle schweren Abhängigkeiten (uvicorn, WebServer, ChatStore, Supervisor,-MCPRegistry, load_config, …) werden durch leichte Stubs ersetzt, damit-der Test rein den START/STOP-Lebenszyklus von _run_headless prüft und-weder echten Port bindet noch auf laufende Dienste angewiesen ist.+All heavyweight dependencies (uvicorn, WebServer, ChatStore, Supervisor,+MCPRegistry, load_config, …) are replaced by lightweight stubs so the+test purely checks the START/STOP lifecycle of _run_headless and+neither binds a real port nor depends on running services."""from __future__ import annotations@@ -22,7 +22,7 @@ import pytestclass _FakeBus:- """Minimal event-bus — subscribe / publish sind keine-ops."""+ """Minimal event bus — subscribe / publish are no-ops."""def subscribe(self, *args: object, **kwargs: object) -> None:pass@@ -36,7 +36,7 @@ class _FakeState:class _FakeApp:- """Minimales ASGI-App-Objekt mit veränderbarem state-Bag."""+ """Minimal ASGI app object with a mutable state bag."""def __init__(self) -> None:self.state = _FakeState()@@ -51,7 +51,7 @@ class _FakeApp:class _MockWebServer:- """Stand-in für jarvis.ui.web.server.WebServer."""+ """Stand-in for jarvis.ui.web.server.WebServer."""instances: list["_MockWebServer"] = []@@ -257,7 +257,7 @@ def _make_args(port: int = 18123) -> SimpleNamespace:def test_headless_starts_and_stops_on_signal() -> None:- """_run_headless durchläuft start → wait → cancel → stop sauber."""+ """_run_headless goes through start → wait → cancel → stop cleanly."""from jarvis.ui.web import launcher # noqa: PLC0415args = _make_args()@@ -287,7 +287,7 @@ def test_headless_starts_and_stops_on_signal() -> None:def test_headless_stop_event_path() -> None:- """Zweiter Pfad: Task wird erst nach kurzer Pause gecancelt."""+ """Second path: the task is only cancelled after a short pause."""from jarvis.ui.web import launcher # noqa: PLC0415args = _make_args(port=18222)diff --git a/tests/integration/test_memory_recall.py b/tests/integration/test_memory_recall.pyindex 0682e35ffc..434bab4c21 100644--- a/tests/integration/test_memory_recall.py+++ b/tests/integration/test_memory_recall.py@@ -23,7 +23,7 @@ async def test_recorder_auto_logs_on_bus(recall):MessageRecorder(recall).attach(bus)await bus.publish(MessageSent(text="hallo", role="user"))- await bus.publish(ResponseGenerated(text="Hi! Wie kann ich helfen?"))+ await bus.publish(ResponseGenerated(text="Hi! How can I help?"))await bus.publish(MessageSent(text="python programmieren"))# Beide geschriebendiff --git a/tests/integration/test_multi_spawn.py b/tests/integration/test_multi_spawn.pyindex 17803a670b..8fe6d3f516 100644--- a/tests/integration/test_multi_spawn.py+++ b/tests/integration/test_multi_spawn.py@@ -1,8 +1,8 @@"""Integration-Test: MultiSpawnTool (CL-10, Phase 5).-Nutzt FakeHarness statt echter openclaw/codex-CLI. HarnessManager wird-mit injizierten Fakes bestückt, damit Tests deterministisch und offline-laufen.+Uses FakeHarness instead of a real openclaw/codex CLI. HarnessManager is+equipped with injected fakes so tests run deterministically and+offline."""from __future__ import annotations@@ -18,9 +18,9 @@ from tests.fixtures.harness.fake_harness import FakeHarnessdef _make_manager_with_fake(bus: EventBus, harness_name: str, fake: FakeHarness) -> HarnessManager:- """Baut einen HarnessManager, der `harness_name` immer als Fresh-Copy- der gegebenen FakeHarness instanziiert — sodass `dispatch` N-fach- dieselbe Fake-Klasse abruft ohne Konflikt."""+ """Builds a HarnessManager that always instantiates `harness_name` as a+ fresh copy of the given FakeHarness — so `dispatch` can call the+ same fake class N times without conflict."""mgr = HarnessManager(bus=bus)mgr._loaded = Truemgr._classes[harness_name] = type(fake)@@ -50,9 +50,9 @@ async def test_three_parallel_openclaw_calls(ctx):{"harness": "openclaw","prompts": [- "schreib die Tests für modul X",- "schreib die Impl für modul X",- "schreib die Docstrings für modul X",+ "write the tests for module X",+ "write the implementation for module X",+ "write the docstrings for module X",],"aggregation": "merge",},@@ -94,7 +94,7 @@ async def test_aggregation_merge_joins_all_outputs(ctx):@pytest.mark.asyncioasync def test_aggregation_first_success_returns_first_ok(ctx):- """first_success-Mode returnt nur die gewinnende Section."""+ """first_success mode returns only the winning section."""bus = EventBus()fake = FakeHarness(scripted_output="winner-output")mgr = _make_manager_with_fake(bus, "openclaw", fake)@@ -180,7 +180,7 @@ async def test_too_few_prompts_fails(ctx):@pytest.mark.asyncioasync def test_merge_failure_propagates(ctx):- """Wenn ein Section-Exit != 0, wird success=False gesetzt."""+ """When a section exit != 0, success=False is set."""bus = EventBus()fake = FakeHarness(fail=True)mgr = _make_manager_with_fake(bus, "openclaw", fake)diff --git a/tests/integration/test_phase1a_smoke.py b/tests/integration/test_phase1a_smoke.pyindex 05f3905e27..23bfc21297 100644--- a/tests/integration/test_phase1a_smoke.py+++ b/tests/integration/test_phase1a_smoke.py@@ -1,21 +1,21 @@-"""Phase 1a Smoke-Test: WebServer startet, WS-Echo funktioniert, Shutdown sauber.+"""Phase 1a smoke test: WebServer starts, WS echo works, clean shutdown.-Ohne Frontend-Build — testet nur das Backend + REST + WebSocket-Pfad.-Wenn Agents 1-6 ihre Files noch nicht gemerged haben, skippt der Test graceful.+Without a frontend build — only tests the backend + REST + WebSocket path.+If agents 1-6 haven't merged their files yet, the test skips gracefully."""from __future__ import annotationsimport pytest-# Gemeinsames Import-Skip-Setup: fehlende Backend-Files führen zu Skip,-# nicht zu Crash — damit dieser Test grün bleibt, bis Agents 1-6 fertig sind.+# Shared import-skip setup: missing backend files lead to a skip,+# not a crash — so this test stays green until agents 1-6 are done.def _try_import_webserver():try:from jarvis.ui.web.server import WebServer # type: ignorereturn WebServerexcept Exception as exc:- pytest.skip(f"WebServer noch nicht verfügbar: {exc!r}")+ pytest.skip(f"WebServer not available yet: {exc!r}")def _try_import_config():@@ -23,7 +23,7 @@ def _try_import_config():from jarvis.core.config import JarvisConfig # type: ignorereturn JarvisConfigexcept Exception as exc:- pytest.skip(f"JarvisConfig nicht ladbar: {exc!r}")+ pytest.skip(f"JarvisConfig cannot be loaded: {exc!r}")def _try_import_testclient():@@ -31,7 +31,7 @@ def _try_import_testclient():from fastapi.testclient import TestClient # type: ignorereturn TestClientexcept Exception as exc:- pytest.skip(f"fastapi.testclient nicht verfügbar: {exc!r}")+ pytest.skip(f"fastapi.testclient not available: {exc!r}")@pytest.fixture@@ -40,7 +40,7 @@ def test_config():try:return JarvisConfig()except Exception as exc:- pytest.skip(f"JarvisConfig() kann nicht instanziiert werden: {exc!r}")+ pytest.skip(f"JarvisConfig() cannot be instantiated: {exc!r}")@pytest.mark.integration@@ -50,7 +50,7 @@ async def test_webserver_starts_and_stops(test_config):srv = WebServer(test_config)await srv.start()try:- assert getattr(srv, "running", True), "WebServer.running sollte True sein"+ assert getattr(srv, "running", True), "WebServer.running should be True"finally:await srv.stop()@@ -85,7 +85,7 @@ def test_rest_api_plugins(test_config):def test_websocket_event_echo(test_config):- """Kernstück: Bus-Event landet im WS-Client."""+ """Core piece: a bus event reaches the WS client."""WebServer = _try_import_webserver()TestClient = _try_import_testclient()srv = WebServer(test_config)@@ -96,7 +96,7 @@ def test_websocket_event_echo(test_config):try:ws_ctx = client.websocket_connect("/ws")except Exception as exc:- pytest.skip(f"/ws nicht verfügbar: {exc!r}")+ pytest.skip(f"/ws not available: {exc!r}")with ws_ctx as ws:welcome = ws.receive_json()assert welcome.get("type") == "welcome"@@ -104,7 +104,7 @@ def test_websocket_event_echo(test_config):# Feuere ein Event via REST-Debug-Endpointr = client.post("/api/debug/emit-test-event")if r.status_code == 404:- pytest.skip("Debug-Endpoint /api/debug/emit-test-event nicht implementiert")+ pytest.skip("debug endpoint /api/debug/emit-test-event not implemented")assert r.status_code in (200, 202, 204)envelope = ws.receive_json()diff --git a/tests/overlay/test_bridge.py b/tests/overlay/test_bridge.pyindex e5599cf7fb..33c1b134a0 100644--- a/tests/overlay/test_bridge.py+++ b/tests/overlay/test_bridge.py@@ -26,7 +26,7 @@ def test_outbox_drops_oldest_non_state_when_full() -> None:box.put("click", b"c1")box.put("click", b"c2")box.put("click", b"c3")- # Voll. Naechster click: c1 wird gedroppt.+ # Full. Next click: c1 gets dropped.box.put("click", b"c4")assert box.dropped == 1assert len(box) == 3@@ -38,8 +38,8 @@ def test_outbox_state_messages_are_protected() -> None:box.put("click", b"c1")box.put("click", b"c2")box.put("click", b"c3")- # Voll. Click drueckt rein -> aelteste non-state (c1) raus.- # state s1 BLEIBT.+ # Full. Click pushes in -> oldest non-state (c1) drops out.+ # state s1 STAYS.assert box.dropped == 1assert len(box) == 3@@ -63,7 +63,7 @@ async def test_outbox_get_blocks_until_item() -> None:# -------------------------------------------------------------------------# emit_state / emit_action_started / emit_action_ended / emit_click /-# emit_error — alle produzieren korrekt schema'd Envelopes auf der Queue.+# emit_error — all produce correctly schema'd envelopes on the queue.# -------------------------------------------------------------------------@@ -154,7 +154,7 @@ async def test_emit_error_produces_error_envelope() -> None:@pytest.mark.asyncioasync def test_state_emit_caches_last_state_envelope() -> None:- """§10.5 Resync — last state envelope wird beim Reconnect zuerst gesendet."""+ """§10.5 Resync — last state envelope is sent first on reconnect."""bridge = OverlayBridge()await bridge.start()try:diff --git a/tests/overlay/test_capture_affinity.py b/tests/overlay/test_capture_affinity.pyindex d609229b95..c64aee5d30 100644--- a/tests/overlay/test_capture_affinity.py+++ b/tests/overlay/test_capture_affinity.py@@ -1,4 +1,4 @@-"""Capture-Affinity-Reapply auf show + screenChanged. Plan §18.1."""+"""Capture-affinity reapply on show + screenChanged. Plan §18.1."""from __future__ import annotations@@ -12,8 +12,8 @@ pytest.importorskip("PySide6.QtWidgets")def test_reapply_capture_affinity_calls_set_window_display_affinity(monkeypatch: pytest.MonkeyPatch,) -> None:- """Plan §18.1: reapply_capture_affinity() muss- SetWindowDisplayAffinity(hwnd, WDA_EXCLUDEFROMCAPTURE) feuern."""+ """Plan §18.1: reapply_capture_affinity() must fire+ SetWindowDisplayAffinity(hwnd, WDA_EXCLUDEFROMCAPTURE)."""from overlay import transparencyfake_user32 = mock.MagicMock()@@ -26,7 +26,7 @@ def test_reapply_capture_affinity_calls_set_window_display_affinity(assert result is Truefake_user32.SetWindowDisplayAffinity.assert_called_once()args, _ = fake_user32.SetWindowDisplayAffinity.call_args- # Erstes arg ist HWND wrapper, zweites WDA_EXCLUDEFROMCAPTURE wrapper.+ # First arg is the HWND wrapper, second the WDA_EXCLUDEFROMCAPTURE wrapper.assert int(args[1].value) == transparency.WDA_EXCLUDEFROMCAPTURE@@ -47,7 +47,7 @@ def test_reapply_capture_affinity_noop_on_non_windows(def test_edge_glow_window_calls_exclude_from_capture_on_show(qapp, monkeypatch: pytest.MonkeyPatch) -> None:- """Plan §18.1: showEvent muss exclude_from_capture rufen."""+ """Plan §18.1: showEvent must call exclude_from_capture."""from PySide6.QtGui import QGuiApplicationfrom overlay import window_glow@@ -94,7 +94,7 @@ def test_edge_glow_window_skips_affinity_when_disabled(def test_edge_glow_screen_change_reapplies_affinity(qapp, monkeypatch: pytest.MonkeyPatch) -> None:- """Plan §18.1: screenChanged muss reapply_capture_affinity rufen."""+ """Plan §18.1: screenChanged must call reapply_capture_affinity."""from PySide6.QtGui import QGuiApplicationfrom overlay import window_glow@@ -111,8 +111,8 @@ def test_edge_glow_screen_change_reapplies_affinity(try:win.show()qapp.processEvents()- # Direkter Aufruf des Handlers — wir koennen den Qt-screenChanged-- # Signal nicht zuverlaessig im offscreen-Plattform-Test triggern.+ # Direct call to the handler — we can't reliably trigger the Qt+ # screenChanged signal in the offscreen-platform test.win._on_screen_changed(primary)assert len(reapplied) == 1finally:@@ -149,8 +149,8 @@ def test_mascot_screen_change_reapplies_affinity(def test_set_view_visible_toggles_webview(qapp) -> None:- """Plan §17.3 — Hide-on-Idle 5min muss set_view_visible(False) auf- den WebView durchreichen."""+ """Plan §17.3 — Hide-on-Idle 5min must pass set_view_visible(False)+ through to the WebView."""from PySide6.QtGui import QGuiApplicationfrom overlay import window_glowdiff --git a/tests/overlay/test_cursor_shm.py b/tests/overlay/test_cursor_shm.pyindex 15822b584c..7fa344bb8d 100644--- a/tests/overlay/test_cursor_shm.py+++ b/tests/overlay/test_cursor_shm.py@@ -1,10 +1,10 @@-"""Cursor SHM Round-Trip — Plan §11 Layout + Seqlock.+"""Cursor SHM round-trip — Plan §11 layout + seqlock.-1000-Frame-Producer/Consumer-Test mit zwei Threads. Verifiziert:- - Layout-Konstanten (32 Bytes, struct format).- - Writer published korrekt (seq monoton, gerade nach Write).- - Reader skipped torn reads sauber (kein gemischter Frame).- - Reader sieht nichts mehr nach Writer-close (block ggf. weg).+1000-frame producer/consumer test with two threads. Verifies:+ - Layout constants (32 bytes, struct format).+ - Writer publishes correctly (seq monotonic, even after write).+ - Reader cleanly skips torn reads (no mixed frame).+ - Reader sees nothing after writer close (block possibly gone)."""from __future__ import annotations@@ -26,7 +26,7 @@ from overlay.cursor_shm import (# --------------------------------------------------------------------------# Konstanten+# Constants# -------------------------------------------------------------------------@@ -54,7 +54,7 @@ def test_make_name_is_unique_pattern() -> None:def test_writer_first_write_yields_seq_2() -> None:- """Plan §11.4: ``_seq`` startet bei 0, erstes Frame endet mit seq=2."""+ """Plan §11.4: ``_seq`` starts at 0, first frame ends with seq=2."""w = CursorShmWriter.create()try:seq = w.write(100, 200, 0)@@ -69,7 +69,7 @@ def test_reader_returns_none_when_no_data_yet() -> None:try:r = CursorShmReader.attach(w.name)try:- assert r.read() is None # seq=0 -> noch nie publiziert+ assert r.read() is None # seq=0 -> never published yetfinally:r.close()finally:@@ -103,7 +103,7 @@ def test_reader_returns_none_on_no_new_seq() -> None:try:w.write(1, 1, 0)assert r.read() is not None- # nochmal lesen ohne neuen Write -> None.+ # read again without a new write -> None.assert r.read() is Nonefinally:r.close()@@ -112,16 +112,16 @@ def test_reader_returns_none_on_no_new_seq() -> None:# --------------------------------------------------------------------------# Producer/Consumer Threading-Stress (1000 Frames, kein Torn-Read)+# Producer/consumer threading stress (1000 frames, no torn read)# -------------------------------------------------------------------------def test_thousand_frames_no_torn_read() -> None:- """Plan §11.3: Reader darf NIE einen halb-geschriebenen Frame sehen.+ """Plan §11.3: the reader must NEVER see a half-written frame.- Wir schreiben 1000 Frames mit predictable Werten (x = i, y = i*2,- monitor = i % 4) und verifizieren reader-side dass jeder gelesene- Frame intern konsistent ist (y == 2*x, monitor == x % 4).+ We write 1000 frames with predictable values (x = i, y = i*2,+ monitor = i % 4) and verify reader-side that every frame read+ is internally consistent (y == 2*x, monitor == x % 4)."""w = CursorShmWriter.create()received: list[CursorFrame] = []@@ -130,13 +130,13 @@ def test_thousand_frames_no_torn_read() -> None:def producer() -> None:for i in range(1, 1001):w.write(i, i * 2, i % 4)- # kein sleep — wir wollen tight loop um Race-Bedingungen- # zu erzwingen.+ # no sleep — we want a tight loop to force+ # race conditions.def consumer() -> None:r = CursorShmReader.attach(w.name)try:- # Polling bis Producer fertig; ggf. ein paar Frames mehr.+ # Poll until producer is done; possibly a few extra frames.poll_count = 0while not stop.is_set() or poll_count < 10:f = r.read()@@ -153,16 +153,16 @@ def test_thousand_frames_no_torn_read() -> None:try:producer()finally:- # Bischen Zeit damit der Consumer die letzten Frames noch- # einsammelt, dann stop.+ # A bit of time so the consumer still collects the last frames,+ # then stop.time.sleep(0.05)stop.set()consumer_thread.join(timeout=2.0)- # Wir koennen NICHT garantieren dass alle 1000 Frames gelesen wurden- # (Reader ist langsamer als Writer, frames werden ueberschrieben). Was- # wir garantieren: jeder GELESENE Frame ist intern konsistent UND- # die Sequenz monoton steigend.+ # We CANNOT guarantee that all 1000 frames were read+ # (the reader is slower than the writer, frames get overwritten). What+ # we DO guarantee: every frame READ is internally consistent AND+ # the sequence is monotonically increasing.assert len(received) > 0last_seq = 0for f in received:@@ -182,16 +182,16 @@ def test_thousand_frames_no_torn_read() -> None:def test_reader_skips_odd_seq_mid_write() -> None:- """Manueller Pin: setze seq auf ungerade -> Reader returns None."""+ """Manual pin: set seq to odd -> reader returns None."""w = CursorShmWriter.create()try:r = CursorShmReader.attach(w.name)try:- # Erst sauber publishen+ # First publish cleanlyw.write(10, 20, 0)- assert r.read() is not None # seq=2 jetzt last_seq+ assert r.read() is not None # seq=2 is now last_seq- # Manuell odd seq setzen — busy marker.+ # Manually set odd seq — busy marker.struct.pack_into("<I", w._buf, 16, 3) # noqa: SLF001 — test reads private bufassert r.read() is Nonefinally:diff --git a/tests/overlay/test_cursor_writer.py b/tests/overlay/test_cursor_writer.pyindex 13ee6439ed..a7a93aeb39 100644--- a/tests/overlay/test_cursor_writer.py+++ b/tests/overlay/test_cursor_writer.py@@ -1,10 +1,10 @@-"""Hauptjarvis-side CursorStreamer + mouse.py-Hook.+"""Main-Jarvis-side CursorStreamer + mouse.py hook.-Testet:- - Writer schreibt korrekt ins SHM (Layout-symmetrisch zur Reader-Seite).- - Streamer pollt nur waehrend ``streaming=True``.- - mouse.click/move_to/scroll triggern start_streaming/stop_streaming- wenn ein Streamer gesetzt ist.+Tests:+ - Writer writes correctly into the SHM (layout-symmetric to the reader side).+ - Streamer only polls while ``streaming=True``.+ - mouse.click/move_to/scroll trigger start_streaming/stop_streaming+ when a streamer is set."""from __future__ import annotations@@ -27,8 +27,8 @@ from overlay.cursor_shm import CursorShmReader# --------------------------------------------------------------------------# Layout-Symmetrie: Writer aus jarvis.overlay schreibt, Reader aus-# OS-Level liest -> beide Seiten muessen denselben struct format kennen.+# Layout symmetry: writer from jarvis.overlay writes, reader from+# OS-Level reads -> both sides must know the same struct format.# -------------------------------------------------------------------------@@ -43,7 +43,7 @@ def test_writer_layout_constants_match_reader() -> None:def test_writer_round_trip_to_reader() -> None:- """Hauptjarvis-Writer + OS-Level-Reader symmetrisch."""+ """Main-Jarvis writer + OS-Level reader symmetric."""w = CursorShmWriter.create()try:r = CursorShmReader.attach(w.name)@@ -68,12 +68,12 @@ def test_writer_round_trip_to_reader() -> None:@pytest.fixture()def streamer() -> Iterator[CursorStreamer]:- """Streamer mit Fake-Position-Reader (kein pyautogui-Aufruf)."""+ """Streamer with a fake position reader (no pyautogui call)."""state = {"x": 100, "y": 200}def fake_pos() -> tuple[int, int]:- # Bewegt den Cursor jeden Tick um +1, damit man im Reader- # tatsaechlich Aenderungen sieht.+ # Moves the cursor by +1 each tick, so the reader+ # actually sees changes.state["x"] += 1state["y"] += 2return state["x"], state["y"]@@ -90,11 +90,11 @@ def test_streamer_does_not_write_when_not_streaming() -> None:r = CursorShmReader.attach(streamer.name)try:- # 50 ms warten — keine Schreibvorgaenge erwartet (start_streaming- # nicht gerufen).+ # Wait 50 ms — no writes expected (start_streaming+ # not called).time.sleep(0.05)assert r.read() is None- # Internal Writer-seq sollte 0 sein.+ # Internal writer seq should be 0.assert streamer.writer.seq == 0finally:r.close()@@ -104,7 +104,7 @@ def test_streamer_writes_during_streaming(streamer: CursorStreamer) -> None:r = CursorShmReader.attach(streamer.name)try:streamer.start_streaming(monitor_idx=1)- # 80 ms @ 120 Hz = ~9 Frames; reichlich.+ # 80 ms @ 120 Hz = ~9 frames; plenty.time.sleep(0.08)streamer.stop_streaming()@@ -118,7 +118,7 @@ def test_streamer_writes_during_streaming(streamer: CursorStreamer) -> None:time.sleep(0.005)assert len(seen) >= 1- # Frames muessen monitor_idx=1 haben.+ # Frames must have monitor_idx=1.for f in seen:assert f.monitor_idx == 1finally:@@ -135,13 +135,13 @@ def test_streamer_idempotent_start(streamer: CursorStreamer) -> None:# --------------------------------------------------------------------------# mouse.py-Hook: click/move_to triggern den Streamer+# mouse.py hook: click/move_to trigger the streamer# -------------------------------------------------------------------------@pytest.fixture()def fake_pyautogui(monkeypatch: pytest.MonkeyPatch) -> mock.MagicMock:- """Faked pyautogui-Modul ueber sys.modules."""+ """Fake pyautogui module via sys.modules."""fake = types.ModuleType("pyautogui")fake.click = mock.MagicMock() # type: ignore[attr-defined]fake.moveTo = mock.MagicMock() # type: ignore[attr-defined]@@ -164,9 +164,9 @@ def test_click_triggers_streamer_start_stop(try:assert streamer.is_streaming is Falsemouse.click(x=100, y=200, monitor_idx=1)- # Nach click ist streaming wieder aus (stop wurde gerufen).+ # After click, streaming is off again (stop was called).assert streamer.is_streaming is False- # pyautogui.click wurde gerufen.+ # pyautogui.click was called.fake_pyautogui.click.assert_called_once_with(x=100, y=200, button="left", clicks=1, interval=0.0)@@ -179,7 +179,7 @@ def test_click_triggers_streamer_start_stop(def test_move_to_streams_during_animation(fake_pyautogui: mock.MagicMock,) -> None:- """Verifiziert dass start_streaming gerufen wird BEVOR pyautogui.moveTo."""+ """Verifies that start_streaming is called BEFORE pyautogui.moveTo."""from jarvis.control import mousecall_order: list[str] = []@@ -214,13 +214,13 @@ def test_move_to_streams_during_animation(finally:streamer.shutdown()- # Erwartete Reihenfolge: start, moveTo, stop.+ # Expected order: start, moveTo, stop.assert call_order == ["start", "moveTo", "stop"], call_orderdef test_no_streamer_no_op(fake_pyautogui: mock.MagicMock) -> None:- """Wenn kein Streamer gesetzt ist, laeuft mouse.click trotzdem- sauber durch (Headless / Production-ohne-Overlay)."""+ """When no streamer is set, mouse.click still runs+ cleanly through (headless / production without overlay)."""from jarvis.control import mousemouse.set_cursor_streamer(None)diff --git a/tests/overlay/test_e2e_kill_parent.py b/tests/overlay/test_e2e_kill_parent.pyindex 71e7ffe46b..cd05db183d 100644--- a/tests/overlay/test_e2e_kill_parent.py+++ b/tests/overlay/test_e2e_kill_parent.py@@ -1,11 +1,11 @@-"""E2E Job-Object Kill-Parent. Plan AD-9 — Hauptjarvis-Crash killt Overlay.+"""E2E job-object kill-parent. Plan AD-9 — Main-Jarvis crash kills the overlay.-Strategie: Wir starten einen "Parent-Process" der einen "Child-Process"-spawned und unter ein Job-Object haengt mit JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE.-Dann taskkillen wir den Parent hart und assert dass der Child innerhalb-1 s ebenfalls weg ist.+Strategy: we start a "parent process" that spawns a "child process"+and attaches it to a job object with JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE.+Then we hard taskkill the parent and assert that the child is also+gone within 1 s.-Windows-only — auf anderen Plattformen ist das ein Skip.+Windows-only — a skip on other platforms."""from __future__ import annotations@@ -19,12 +19,12 @@ import timeimport pytestif sys.platform != "win32":- pytest.skip("Job-Object ist Windows-only", allow_module_level=True)+ pytest.skip("Job object is Windows-only", allow_module_level=True)try:import psutil # noqa: F401except ImportError: # pragma: no cover- pytest.skip("psutil benoetigt fuer Process-Watch", allow_module_level=True)+ pytest.skip("psutil required for process watch", allow_module_level=True)PARENT_SCRIPT = textwrap.dedent("""@@ -39,12 +39,12 @@ PARENT_SCRIPT = textwrap.dedent("""JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE = 0x2000- # Spawn child: laueft 30 s.+ # Spawn child: runs for 30 s.child = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(30)"])- # Job-Object aufsetzen.+ # Set up the job object.job = win32job.CreateJobObject(None, "")info = win32job.QueryInformationJobObject(job, win32job.JobObjectExtendedLimitInformation@@ -62,21 +62,21 @@ PARENT_SCRIPT = textwrap.dedent("""win32job.AssignProcessToJobObject(job, proc_h)win32api.CloseHandle(proc_h)- # PID des childs ausgeben damit der Test ihn watchen kann.+ # Print the child's PID so the test can watch it.sys.stdout.write(str(child.pid) + chr(10))sys.stdout.flush()- # Endlos-loop damit der Test uns killen kann.+ # Endless loop so the test can kill us.while True:time.sleep(1)""")def test_kill_parent_kills_child_within_one_second() -> None:- """Plan AD-9: KILL_ON_JOB_CLOSE garantiert no zombies."""+ """Plan AD-9: KILL_ON_JOB_CLOSE guarantees no zombies."""import psutil- # Parent spawnen.+ # Spawn the parent.parent = subprocess.Popen([sys.executable, "-c", PARENT_SCRIPT],stdout=subprocess.PIPE,@@ -85,37 +85,37 @@ def test_kill_parent_kills_child_within_one_second() -> None:)try:- # Erste Zeile = child PID.+ # First line = child PID.line = parent.stdout.readline().strip()try:child_pid = int(line)except ValueError:- pytest.fail(f"Parent gab keine child PID aus: {line!r}")- assert psutil.pid_exists(child_pid), f"child PID {child_pid} nicht da"+ pytest.fail(f"Parent did not print a child PID: {line!r}")+ assert psutil.pid_exists(child_pid), f"child PID {child_pid} not present"- # Parent hart killen via taskkill /F.+ # Hard-kill the parent via taskkill /F.subprocess.run(["taskkill", "/F", "/PID", str(parent.pid), "/T"],check=False,capture_output=True,)- # Plan AD-9: child sollte innerhalb 1 s weg sein.+ # Plan AD-9: child should be gone within 1 s.deadline = time.monotonic() + 2.0while time.monotonic() < deadline:if not psutil.pid_exists(child_pid):# done.child_exit_time = time.monotonic()- # 1 s ist Plan-Vorgabe; +500ms toleranz fuer Test-Slack+ # 1 s is the plan spec; +500ms tolerance for test slackassert Truereturntime.sleep(0.05)pytest.fail(- f"child PID {child_pid} lebt noch 2 s nach parent-kill — "- "Job-Object hat nicht gekilled"+ f"child PID {child_pid} is still alive 2 s after parent kill — "+ "job object did not kill it")finally:- # Cleanup parent (falls noch alive).+ # Cleanup parent (if still alive).try:parent.terminate()parent.wait(timeout=2)diff --git a/tests/overlay/test_event_router.py b/tests/overlay/test_event_router.pyindex 862eefdcb8..20c2a1a478 100644--- a/tests/overlay/test_event_router.py+++ b/tests/overlay/test_event_router.py@@ -196,7 +196,7 @@ def test_ack_is_noop(router: EventRouter, machine: StateMachine) -> None:def test_unknown_envelope_is_noop(router: EventRouter, machine: StateMachine) -> None:- """Wenn jemand etwas Fremdes durchschiebt, kein Crash, einfach False."""+ """When something foreign is pushed through, no crash, just False."""class _Foreign:passdiff --git a/tests/overlay/test_fullscreen_detect.py b/tests/overlay/test_fullscreen_detect.pyindex 6019555d2b..0b14cefca3 100644--- a/tests/overlay/test_fullscreen_detect.py+++ b/tests/overlay/test_fullscreen_detect.py@@ -58,7 +58,7 @@ def test_normal_states_do_not_hide() -> None:# --------------------------------------------------------------------------# FullscreenDetector — sync poll_once + Callback nur bei Wechsel+# FullscreenDetector — sync poll_once + callback only on change# -------------------------------------------------------------------------@@ -118,7 +118,7 @@ def test_query_returning_none_does_not_crash() -> None:def test_thread_starts_and_stops_cleanly() -> None:- """2-Sekunden-Polling-Thread shutdown muss schnell sein (<200 ms)."""+ """2-second polling-thread shutdown must be fast (<200 ms)."""states = [UserNotificationState.NOT_PRESENT]det = FullscreenDetector(diff --git a/tests/overlay/test_ipc_pipe.py b/tests/overlay/test_ipc_pipe.pyindex d000dd8df9..5805b65fc2 100644--- a/tests/overlay/test_ipc_pipe.py+++ b/tests/overlay/test_ipc_pipe.py@@ -26,10 +26,10 @@ def test_default_pipe_name() -> None:def test_send_recv_roundtrip() -> None:- """Server in Thread, Client in Main-Thread: schickt JSON, empfaengt back.+ """Server in a thread, client in the main thread: sends JSON, receives it back.- Pipe wird im Main-Thread erzeugt (CreateNamedPipe), erst dann startet- der Server-Thread auf ConnectNamedPipe. So gibt es keinen Race vor+ The pipe is created in the main thread (CreateNamedPipe), only then does+ the server thread start on ConnectNamedPipe. That way there's no race beforeWaitNamedPipe."""pytest.importorskip("win32pipe")diff --git a/tests/overlay/test_ipc_ws.py b/tests/overlay/test_ipc_ws.pyindex 5a1e42d7cc..993d8452b1 100644--- a/tests/overlay/test_ipc_ws.py+++ b/tests/overlay/test_ipc_ws.py@@ -1,7 +1,7 @@-"""WS-Server (jarvis.overlay.server + bridge) und WS-Client (overlay.ipc_ws).+"""WS server (jarvis.overlay.server + bridge) and WS client (overlay.ipc_ws).-End-to-End-Roundtrip ueber 127.0.0.1, plus Backpressure-/Drop-Policy--Tests gegen die Bridge-Outbox direkt.+End-to-end round-trip over 127.0.0.1, plus backpressure/drop-policy+tests directly against the bridge outbox."""from __future__ import annotations@@ -29,8 +29,8 @@ from overlay.schema import (from jarvis.overlay.bridge import OverlayBridge, _BoundedOutboxfrom jarvis.overlay.server import IPCServerHandle, start_ipc_server-# pytest-asyncio ``asyncio_mode = "auto"`` (in pyproject.toml) markiert-# async-Funktionen automatisch — kein Modul-pytestmark noetig.+# pytest-asyncio ``asyncio_mode = "auto"`` (in pyproject.toml) marks+# async functions automatically — no module pytestmark needed.# -----------------------------------------------------------------------------@@ -42,7 +42,7 @@ def test_backoff_slot_progression() -> None:rng = random.Random(0)delays = [_backoff_with_jitter(i, rng=rng) for i in range(10)]assert len(delays) == 10- # Slot 0..5 traegt linear an, ab 6 cap auf 30.+ # Slot 0..5 ramps up linearly, from 6 on capped at 30.assert all(d > 0 for d in delays)cap_band = (30 * (1 - JITTER_FRACTION), 30 * (1 + JITTER_FRACTION))assert cap_band[0] <= delays[-1] <= cap_band[1]@@ -74,7 +74,7 @@ async def test_outbox_drops_oldest_non_state_first() -> None:box.put("state", b"S0") # statebox.put("cursor", b"C1") # non-state, oldest non-statebox.put("heartbeat", b"H2") # non-state- # Voll. Ein neuer Eintrag (egal welcher Typ) muss zuerst C1 droppen.+ # Full. A new entry (regardless of type) must drop C1 first.assert box.put("click", b"X3") is Trueout = []while len(box):@@ -90,7 +90,7 @@ async def test_outbox_drops_state_only_if_no_non_state() -> None:box = _BoundedOutbox(maxsize=2)box.put("state", b"S0")box.put("state", b"S1")- # Voll, alles state. Neuer state -> aeltesten state droppen.+ # Full, all state. New state -> drop the oldest state.assert box.put("state", b"S2") is Trueout = [await box.get(), await box.get()]assert b"S0" not in out@@ -101,7 +101,7 @@ async def test_outbox_rejects_new_non_state_when_only_state_in_buf() -> None:box = _BoundedOutbox(maxsize=2)box.put("state", b"S0")box.put("state", b"S1")- # Voll, alles state. Neuer non-state -> wird selbst gedroppt.+ # Full, all state. New non-state -> gets dropped itself.assert box.put("cursor", b"C2") is Falseassert box.dropped == 1out = [await box.get(), await box.get()]@@ -130,12 +130,12 @@ async def test_bridge_send_nowait_returns_bool() -> None:bridge = OverlayBridge(outbound_queue_max=2)await bridge.start()try:- # Zwei State-Frames passen rein.+ # Two state frames fit in.e1 = StateEnvelope(payload=StatePayload(state="idle"))e2 = StateEnvelope(payload=StatePayload(state="typing"))assert bridge.send_nowait(e1) is Trueassert bridge.send_nowait(e2) is True- # Drittes State -> evictet aelteste state, akzeptiert.+ # Third state -> evicts the oldest state, accepted.assert bridge.send_nowait(e1) is Truefinally:await bridge.stop()@@ -163,13 +163,13 @@ async def test_server_picks_free_port() -> None:async def test_server_raises_when_no_port_free() -> None:- """Wenn port_range_max < port -> sofortiger ValueError."""+ """When port_range_max < port -> immediate ValueError."""with pytest.raises(ValueError):await start_ipc_server(host="127.0.0.1", port=18100, port_range_max=18099)async def test_client_connects_and_receives_state_resync() -> None:- """Plan §10.5: erstes Frame nach Connect ist der zuletzt bekannte State."""+ """Plan §10.5: first frame after connect is the last known state."""handle = await _start_test_server()handle.bridge.emit_state("clicking", intensity=1.0, reason="tool")try:@@ -207,7 +207,7 @@ async def test_client_connects_and_receives_state_resync() -> None:async def test_client_reconnects_after_server_restart() -> None:- """Server stirbt -> Client reconnected mit Backoff (§10.5)."""+ """Server dies -> client reconnects with backoff (§10.5)."""handle1 = await _start_test_server()port = handle1.port@@ -226,15 +226,15 @@ async def test_client_reconnects_after_server_restart() -> None:try:assert await client.wait_connected(timeout=3.0)first_count = client.connection_count- # Server stoppen.+ # Stop the server.await handle1.stop()- # Mit demselben Port wieder hochziehen.+ # Bring it back up with the same port.await asyncio.sleep(0.3)handle2 = await start_ipc_server(host="127.0.0.1", port=port, port_range_max=port)try:- # Geben dem Client Zeit zum reconnecten (Backoff <= 1.2s + Jitter).+ # Give the client time to reconnect (backoff <= 1.2s + jitter).for _ in range(40):await asyncio.sleep(0.1)if client.connection_count > first_count:@@ -251,11 +251,11 @@ async def test_client_reconnects_after_server_restart() -> None:async def test_invalid_json_dropped_and_logged(caplog) -> None:- """Server muss invalides JSON loggen + droppen, nicht crashen.+ """Server must log + drop invalid JSON, not crash.- Wir senden Schrott und erwarten danach trotzdem mind. ein gueltiges- StateEnvelope (gepushed nach dem Schrott). Andere Frames (Heartbeat,- Resync) duerfen dazwischen liegen.+ We send garbage and still expect at least one valid+ StateEnvelope afterward (pushed after the garbage). Other frames+ (heartbeat, resync) may occur in between."""import websockets@@ -264,7 +264,7 @@ async def test_invalid_json_dropped_and_logged(caplog) -> None:async with websockets.connect(f"ws://127.0.0.1:{handle.port}/overlay") as ws:await ws.send("definitely-not-json")handle.bridge.emit_state("idle")- # Drain bis zum naechsten StateEnvelope (max ~3s Heartbeats).+ # Drain until the next StateEnvelope (max ~3s of heartbeats).seen_state = Falsefor _ in range(30):try:@@ -275,13 +275,13 @@ async def test_invalid_json_dropped_and_logged(caplog) -> None:if isinstance(msg, StateEnvelope) and msg.payload.state == "idle":seen_state = Truebreak- assert seen_state, "kein StateEnvelope nach Schrott-Frame empfangen"+ assert seen_state, "no StateEnvelope received after the garbage frame"finally:await handle.stop()async def test_client_sends_heartbeats() -> None:- """Client schickt Heartbeats, die der Server validiert."""+ """Client sends heartbeats that the server validates."""received_types: list[str] = []handle = await _start_test_server()@@ -299,7 +299,7 @@ async def test_client_sends_heartbeats() -> None:run_task = asyncio.create_task(client.run())try:assert await client.wait_connected(timeout=3.0)- # Warten bis mindestens ein Heartbeat empfangen wurde.+ # Wait until at least one heartbeat has been received.for _ in range(40):await asyncio.sleep(0.05)if "heartbeat" in received_types:diff --git a/tests/overlay/test_jarvis_agent_noop.py b/tests/overlay/test_jarvis_agent_noop.pyindex 97846358dc..ca11f8cde4 100644--- a/tests/overlay/test_jarvis_agent_noop.py+++ b/tests/overlay/test_jarvis_agent_noop.py@@ -1,8 +1,8 @@-"""Sub-Agent No-Op-Pfad. Plan §8.7 + AD-6.+"""Sub-agent no-op path. Plan §8.7 + AD-6.-Wenn ``JARVIS_DEPTH > 0`` env, ist die OverlayBridge ein No-Op-Stub.-Caller-Code sieht das gleiche Interface, aber Events werden nirgendwo-hingesendet.+When the ``JARVIS_DEPTH > 0`` env var is set, the OverlayBridge is a no-op+stub. Caller code sees the same interface, but events are not sent+anywhere."""from __future__ import annotations@@ -65,7 +65,7 @@ def test_get_overlay_returns_noop_stub_in_sub_agent(# --------------------------------------------------------------------------# NoOpOverlayBridge — alle emit-Methoden sind no-ops, kein IPC-Traffic+# NoOpOverlayBridge — all emit methods are no-ops, no IPC traffic# -------------------------------------------------------------------------diff --git a/tests/overlay/test_mascot_position.py b/tests/overlay/test_mascot_position.pyindex cfe801a480..ff89e29809 100644--- a/tests/overlay/test_mascot_position.py+++ b/tests/overlay/test_mascot_position.py@@ -58,7 +58,7 @@ def test_resolve_falls_back_to_primary_when_monitor_missing() -> None:monitor="\\\\.\\DISPLAY99", x_relative=500, y_relative=400)placement = resolve_placement(persisted, screens)- # Default-Position auf primary, NICHT der gespeicherte Offset.+ # Default position on primary, NOT the stored offset.assert placement.abs_x == 100 + DEFAULT_X_RELATIVEassert placement.abs_y == 200 + DEFAULT_Y_RELATIVEassert placement.monitor == "\\\\.\\DISPLAY2"diff --git a/tests/overlay/test_monitors.py b/tests/overlay/test_monitors.pyindex 48be2d0019..da79dc96c5 100644--- a/tests/overlay/test_monitors.py+++ b/tests/overlay/test_monitors.py@@ -72,7 +72,7 @@ def test_monitor_manager_connects_callbacks(qapp) -> None:on_screen_removed=removed_calls.append,)mgr.attach()- # Idempotent — zweiter attach() darf nicht doppelt connecten.+ # Idempotent — a second attach() must not connect twice.mgr.attach()mgr.detach()# Detach idempotent.diff --git a/tests/overlay/test_ripple_e2e.py b/tests/overlay/test_ripple_e2e.pyindex 6a3c0d2d36..b21d761b89 100644--- a/tests/overlay/test_ripple_e2e.py+++ b/tests/overlay/test_ripple_e2e.py@@ -1,14 +1,14 @@-"""Ripple-E2E. Plan §14.3 — Click-Event ⇒ DOM-Update ≤ 50 ms.+"""Ripple E2E. Plan §14.3 — click event ⇒ DOM update ≤ 50 ms.-Wir koennen die echte EffectsBridge nicht easy starten ohne ganze-QtWebEngine-App, also simulieren wir den Bridge-Path indem wir den-``triggerRipple``-Export direkt aus der gebauten JS-Bundle aufrufen.+We can't easily start the real EffectsBridge without the whole+QtWebEngine app, so we simulate the bridge path by calling the+``triggerRipple`` export directly from the built JS bundle.Tests:- - Pool baut sich auf (8 Slots).- - triggerRipple fuegt eine .active-CSS-Klasse hinzu.- - Animation startet ≤ 50 ms nach JS-Call.- - Reduced-motion-Pfad: keine Animation.+ - Pool builds up (8 slots).+ - triggerRipple adds an .active CSS class.+ - Animation starts ≤ 50 ms after the JS call.+ - Reduced-motion path: no animation."""from __future__ import annotations@@ -31,7 +31,7 @@ EDGE_GLOW_HTML = DIST_DIR / "edge-glow.html"def _skip_if_no_build() -> None:if not EDGE_GLOW_HTML.is_file():- pytest.skip(f"edge-glow.html nicht gefunden — npm run build?")+ pytest.skip(f"edge-glow.html not found — npm run build?")class _SilentHandler(http.server.SimpleHTTPRequestHandler):@@ -73,7 +73,7 @@ def browser_ctx():yield browserbrowser.close()except Exception as exc: # noqa: BLE001- pytest.skip(f"Playwright-Browser nicht verfuegbar: {exc!r}")+ pytest.skip(f"Playwright browser not available: {exc!r}")def test_ripple_pool_built(browser_ctx, page_url: str) -> None:@@ -93,7 +93,7 @@ def test_ripple_pool_built(browser_ctx, page_url: str) -> None:def test_ripple_triggers_within_50ms(browser_ctx, page_url: str) -> None:- """Plan §14.3: Click-Event -> Ripple sichtbar in DOM ≤ 50 ms."""+ """Plan §14.3: click event -> ripple visible in DOM ≤ 50 ms."""page = browser_ctx.new_page()try:page.goto(page_url)@@ -101,22 +101,22 @@ def test_ripple_triggers_within_50ms(browser_ctx, page_url: str) -> None:"document.querySelectorAll('.ripple-layer .ripple').length === 8",timeout=2000,)- # Zeit messen zwischen JS-Trigger und sichtbarem ".active"-Slot.+ # Measure time between JS trigger and the visible ".active" slot.elapsed_ms = page.evaluate("""async () => {const { triggerRipple } = await import('/assets/edge-glow-DPwwKrEp.js').catch(() => ({ triggerRipple: null }));- // Fallback: ueber globale Helpers — nicht expose, also- // wir nutzen direct DOM-Manipulation um den Effekt zu simulieren.+ // Fallback: via global helpers — not exposed, so+ // we use direct DOM manipulation to simulate the effect.const t0 = performance.now();- // Triggere ueber den Pool-CSS-Pattern: erste leere Slot- // mit .active-Klasse.+ // Trigger via the pool CSS pattern: first empty slot+ // gets the .active class.const slot = document.querySelector('.ripple-layer .ripple');if (!slot) return -1;slot.classList.add('active');slot.style.transform = 'translate(100px, 100px) scale(0)';slot.style.opacity = '1';- // Forced reflow + ein Frame warten.+ // Forced reflow + wait one frame.void slot.offsetWidth;await new Promise(r => requestAnimationFrame(r));const t1 = performance.now();@@ -124,14 +124,14 @@ def test_ripple_triggers_within_50ms(browser_ctx, page_url: str) -> None:return isActive ? (t1 - t0) : -1;}""")- assert elapsed_ms >= 0, "active-class nie gesetzt"+ assert elapsed_ms >= 0, "active class never set"assert elapsed_ms < 50, f"Ripple-Activation {elapsed_ms} ms > 50 ms"finally:page.close()def test_ripple_reduced_motion_no_animation(browser_ctx, page_url: str) -> None:- """Plan §19.1: prefers-reduced-motion -> Ripple-opacity 0."""+ """Plan §19.1: prefers-reduced-motion -> ripple opacity 0."""page = browser_ctx.new_page()page.emulate_media(reduced_motion="reduce")try:@@ -140,7 +140,7 @@ def test_ripple_reduced_motion_no_animation(browser_ctx, page_url: str) -> None:"document.querySelectorAll('.ripple-layer .ripple').length === 8",timeout=2000,)- # Setze .active manuell und schaue ob computed opacity 0 ist.+ # Set .active manually and check whether computed opacity is 0.opacity = page.evaluate("""() => {const slot = document.querySelector('.ripple-layer .ripple');@@ -154,7 +154,7 @@ def test_ripple_reduced_motion_no_animation(browser_ctx, page_url: str) -> None:def test_typing_sweep_present(browser_ctx, page_url: str) -> None:- """Phase 9.5: typing-sweep-Element existiert als Singleton."""+ """Phase 9.5: typing-sweep element exists as a singleton."""page = browser_ctx.new_page()try:page.goto(page_url)@@ -170,14 +170,14 @@ def test_typing_sweep_present(browser_ctx, page_url: str) -> None:def test_cursor_trail_canvas_present(browser_ctx, page_url: str) -> None:- """Phase 9.5: cursor-trail-canvas existiert."""+ """Phase 9.5: cursor-trail-canvas exists."""page = browser_ctx.new_page()try:page.goto(page_url)page.wait_for_function("document.querySelector('.cursor-trail-canvas') !== null", timeout=2000)- # Canvas ist fullscreen.+ # Canvas is fullscreen.rect = page.evaluate("""() => {const c = document.querySelector('.cursor-trail-canvas');diff --git a/tests/overlay/test_schema.py b/tests/overlay/test_schema.pyindex ba77fdeca8..d3142d0a69 100644--- a/tests/overlay/test_schema.py+++ b/tests/overlay/test_schema.py@@ -151,8 +151,8 @@ def test_envelope_v_must_be_at_least_1() -> None:def test_higher_version_accepted_for_forward_compat() -> None:- # Forward-Compat: Empfaenger laesst v=2 durch (loggt nur Warning beim- # IPC-Layer); das Pydantic-Modell selbst darf nicht raisen.+ # Forward compat: receiver lets v=2 through (only logs a warning at+ # the IPC layer); the Pydantic model itself must not raise.msg = IPCMessage.validate_python({"type": "state",@@ -167,7 +167,7 @@ def test_higher_version_accepted_for_forward_compat() -> None:def test_jarvis_re_export_identical() -> None:- """``jarvis.overlay.schema`` muss exakt dieselben Klassen reexportieren."""+ """``jarvis.overlay.schema`` must re-export exactly the same classes."""from jarvis.overlay.schema import IPCMessage as JIPCfrom jarvis.overlay.schema import StateEnvelope as JSEdiff --git a/tests/overlay/test_schema_symmetry.py b/tests/overlay/test_schema_symmetry.pyindex 9ab0d67e37..019ba52fdd 100644--- a/tests/overlay/test_schema_symmetry.py+++ b/tests/overlay/test_schema_symmetry.py@@ -1,27 +1,28 @@-"""JSON-Schema-Export als CI-Gate fuer Phase 9.4 Zod-Symmetrie (AD-15).+"""JSON schema export as a CI gate for Phase 9.4 Zod symmetry (AD-15).-Phase 9.2 liefert die Pydantic-Seite. Phase 9.4 wird das Zod-Schema-generieren und dieser Test prueft dann strukturelle Gleichheit. Hier-verifizieren wir vorerst nur, dass:+Phase 9.2 delivers the Pydantic side. Phase 9.4 will generate the Zod+schema and this test will then check structural equality. For now we+only verify that:-1. Pydantic ein vollstaendiges JSON-Schema fuer ``IPCMessage``- exportieren kann.-2. Jeder Envelope-Type einen unique discriminator-Wert hat.-3. Alle erwarteten Type-Werte praesent sind.-4. Jeder Envelope-Type funktional roundtrip-faehig ist+1. Pydantic can export a complete JSON schema for ``IPCMessage``.+2. Every envelope type has a unique discriminator value.+3. All expected type values are present.+4. Every envelope type is functionally round-trip-capable(serialize -> deserialize via ``IPCMessage.validate_json``).-5. Die TS-Seite (``OS-Level/overlay-ui/src/schema.ts``) dokumentiert die- Phase-9.4-Scope-Limitation explizit (nur State-Slice gespiegelt).--Phase-9.10+-TODO (echte Zod<->Pydantic-Symmetrie):- Eine vollstaendige strukturelle Gleichheit zwischen Pydantic-JSON-- Schema und Zod-Schema ist erst sinnvoll, wenn alle 9 Envelopes auf- der TS-Seite gespiegelt sind. Dann muesste der Test einen- ``tsc/node``-Subprocess fahren (Zod-Schema -> JSON-Schema via- ``zod-to-json-schema``) und gegen den Pydantic-Export diff'en. Das- ist zur Phase 9.4 Overhead ohne Gegenwert: der Renderer braucht- aktuell nur den State-Slice. Geplant ab Phase 9.10, wenn Overlay- selbst Click/Cursor/Action-Envelopes konsumiert.+5. The TS side (``OS-Level/overlay-ui/src/schema.ts``) explicitly+ documents the Phase-9.4 scope limitation (only the state slice is+ mirrored).++Phase-9.10+ TODO (real Zod<->Pydantic symmetry):+ Full structural equality between the Pydantic JSON schema and the+ Zod schema only makes sense once all 9 envelopes are mirrored on+ the TS side. At that point the test would need to run a+ ``tsc/node`` subprocess (Zod schema -> JSON schema via+ ``zod-to-json-schema``) and diff it against the Pydantic export.+ For Phase 9.4 that would be overhead without payoff: the renderer+ currently only needs the state slice. Planned from Phase 9.10+ onward, once the overlay itself consumes click/cursor/action+ envelopes."""from __future__ import annotations@@ -52,16 +53,16 @@ EXPECTED_TYPES = frozenset(def test_json_schema_exportable() -> None:schema = IPCMessage.json_schema()assert isinstance(schema, dict)- # Pydantic v2 emittiert oneOf/discriminator fuer Discriminated Unions.+ # Pydantic v2 emits oneOf/discriminator for discriminated unions.blob = json.dumps(schema)for t in EXPECTED_TYPES:- assert f'"{t}"' in blob, f"type={t!r} fehlt in JSON-Schema"+ assert f'"{t}"' in blob, f"type={t!r} missing from JSON schema"def test_all_expected_types_present() -> None:- """Jeder Envelope-Type muss validierbar sein."""+ """Every envelope type must be validatable."""for t in EXPECTED_TYPES:- # Minimaler Roh-Payload pro Type.+ # Minimal raw payload per type.sample = _sample_for(t)msg = IPCMessage.validate_python(sample)assert msg.type == t@@ -85,33 +86,33 @@ def _sample_for(t: str) -> dict:def test_discriminator_field_in_schema() -> None:schema = IPCMessage.json_schema()- # Pydantic v2: ``discriminator`` Property unter ``oneOf``-Wrapper oder im- # Top-Level. Wir akzeptieren beides — wichtig ist, dass das Feld ``type``- # den Discriminator-Hinweis traegt.+ # Pydantic v2: the ``discriminator`` property is either under the ``oneOf``+ # wrapper or at the top level. We accept both — what matters is that the+ # ``type`` field carries the discriminator hint.blob = json.dumps(schema)assert "discriminator" in blob or "propertyName" in blob or '"type":' in blobdef test_schema_export_stable_for_drift_detection(tmp_path) -> None:- """Snapshot des JSON-Schemas. Phase 9.4 vergleicht gegen Zod-Output."""+ """Snapshot of the JSON schema. Phase 9.4 compares against the Zod output."""schema = IPCMessage.json_schema()snapshot = tmp_path / "ipc-schema.json"snapshot.write_text(json.dumps(schema, indent=2, sort_keys=True), encoding="utf-8")- # Sanity: nicht leer, parseable.+ # Sanity: not empty, parseable.parsed = json.loads(snapshot.read_text(encoding="utf-8"))assert isinstance(parsed, dict)# ------------------------------------------------------------------------------# Neue Tests (MAJOR #9 — Plan §10.3 + AD-15 Symmetrie-Audit)+# New tests (MAJOR #9 — Plan §10.3 + AD-15 symmetry audit)# -----------------------------------------------------------------------------def _find_overlay_ui_schema_ts() -> Path | None:- """Sucht ``OS-Level/overlay-ui/src/schema.ts`` von der Test-Datei aus.+ """Looks for ``OS-Level/overlay-ui/src/schema.ts`` from the test file.- Wir laufen u.U. aus verschiedenen Roots (``Personal Jarvis`` vs.- ``Personal Jarvis-main``); also mehrere Kandidaten-Pfade pruefen.+ We may run from different roots (``Personal Jarvis`` vs.+ ``Personal Jarvis-main``), so check multiple candidate paths."""here = Path(__file__).resolve()candidates: list[Path] = []@@ -124,25 +125,25 @@ def _find_overlay_ui_schema_ts() -> Path | None:def test_zod_schema_file_documents_phase94_limitation() -> None:- """``schema.ts`` MUSS die Phase-9.4-Scope-Limitation explizit dokumentieren.+ """``schema.ts`` MUST explicitly document the Phase-9.4 scope limitation.- Plan AD-15 fordert symmetrische Pydantic<->Zod-Schemas. Phase 9.4- spiegelt jedoch nur den State-Slice (StateName + StateChange), nicht- alle 9 Envelopes. Diese Scope-Begrenzung muss im TS-File als- Kommentar/TODO sichtbar sein, sonst entsteht stille Drift.+ Plan AD-15 demands symmetric Pydantic<->Zod schemas. Phase 9.4,+ however, only mirrors the state slice (StateName + StateChange), not+ all 9 envelopes. This scope limitation must be visible as a+ comment/TODO in the TS file, otherwise silent drift creeps in."""schema_ts = _find_overlay_ui_schema_ts()if schema_ts is None:pytest.skip(- "OS-Level/overlay-ui/src/schema.ts nicht gefunden — "- "Phase 9.4 Frontend-Tree fehlt in diesem Checkout."+ "OS-Level/overlay-ui/src/schema.ts not found — "+ "Phase 9.4 frontend tree is missing in this checkout.")text = schema_ts.read_text(encoding="utf-8")head = "\n".join(text.splitlines()[:30]).lower()- # Akzeptiert: Phase-9.4-Hinweis ODER expliziter TODO/limitation/scope-Hinweis- # auf weitere Envelopes (oder AD-15 referenziert).+ # Accepted: a Phase-9.4 hint OR an explicit TODO/limitation/scope hint+ # about additional envelopes (or a reference to AD-15).phase_marker = any(token in headfor token in (@@ -159,7 +160,7 @@ def test_zod_schema_file_documents_phase94_limitation() -> None:token in headfor token in ("envelope",- "weitere envelopes",+ "weitere envelopes", # i18n-allow: matched literally against schema.ts content"additional envelopes","more envelopes","state-slice",@@ -169,47 +170,47 @@ def test_zod_schema_file_documents_phase94_limitation() -> None:if not (phase_marker and envelope_marker):pytest.fail(- "AD-15 Symmetrie-Audit fehlt: schema.ts dokumentiert die Phase-9.4-"- "Scope-Limitation nicht. Bitte 1-5 Zeilen Kommentar oben einfuegen, "- "der erklaert dass nur der State-Slice gespiegelt ist und weitere "- "Envelopes mit Phase 9.10+ folgen.\n"- f"Datei: {schema_ts}\n"- f"Erste 30 Zeilen:\n{head}"+ "AD-15 symmetry audit missing: schema.ts does not document the "+ "Phase-9.4 scope limitation. Please add a 1-5 line comment at the "+ "top explaining that only the state slice is mirrored and "+ "further envelopes follow from Phase 9.10+.\n"+ f"File: {schema_ts}\n"+ f"First 30 lines:\n{head}")def test_envelope_round_trip_each_type() -> None:- """Jeder der 9 Envelope-Types muss JSON-Roundtrip-faehig sein.+ """Each of the 9 envelope types must be JSON-round-trip-capable.- Serialize ein Sample -> validate_json -> assert ``type`` und alle- Payload-Keys identisch. Verhindert dass ein zukuenftiger Pydantic-- Refactor die Discriminated-Union sprengt, ohne dass ein Test laut- wird.+ Serialize a sample -> validate_json -> assert ``type`` and all+ payload keys are identical. Prevents a future Pydantic refactor+ from breaking the discriminated union without any test making+ noise."""for t in EXPECTED_TYPES:sample = _sample_for(t)- # Bytes-Pfad (real-life Wire-Format).+ # Bytes path (real-life wire format).raw = json.dumps(sample).encode("utf-8")msg = IPCMessage.validate_json(raw)- # Discriminator muss erhalten bleiben.- assert msg.type == t, f"type-Mismatch fuer {t!r}: got {msg.type!r}"+ # Discriminator must be preserved.+ assert msg.type == t, f"type mismatch for {t!r}: got {msg.type!r}"- # Payload-Keys aus dem Sample muessen alle im deserialisierten- # Objekt landen (extra="forbid" auf den Payloads sichert die- # Gegenrichtung — kein Key wandert verloren).+ # All payload keys from the sample must end up in the+ # deserialized object (extra="forbid" on the payloads secures+ # the reverse direction — no key gets lost).sample_payload = sample["payload"]deserialized_payload = msg.payload.model_dump()for key, expected in sample_payload.items():assert key in deserialized_payload, (- f"Payload-Key {key!r} fehlt nach Roundtrip fuer type={t!r}"+ f"Payload key {key!r} missing after round trip for type={t!r}")assert deserialized_payload[key] == expected, (- f"Payload-Wert fuer {key!r} weicht ab fuer type={t!r}: "- f"erwartet {expected!r}, bekommen {deserialized_payload[key]!r}"+ f"Payload value for {key!r} differs for type={t!r}: "+ f"expected {expected!r}, got {deserialized_payload[key]!r}")- # Envelope-Felder muessen identisch sein.+ # Envelope fields must be identical.assert msg.v == sample["v"]assert msg.id == sample["id"]assert msg.ts_ns == sample["ts_ns"]diff --git a/tests/overlay/test_state.py b/tests/overlay/test_state.pyindex ada85f0fcf..38c7a73e9d 100644--- a/tests/overlay/test_state.py+++ b/tests/overlay/test_state.py@@ -25,13 +25,13 @@ def test_stable_string_values() -> None:def test_str_enum_inherits_string() -> None:- # Wichtig fuer JSON-Serialisierung in Phase 9.2.+ # Important for JSON serialization in Phase 9.2.assert isinstance(OverlayState.IDLE.value, str)assert OverlayState.IDLE == "idle"def test_glow_active_only_in_typing_clicking() -> None:- # Plan §6.1 — Glow ist NUR in TYPING und CLICKING aktiv.+ # Plan §6.1 — glow is ONLY active in TYPING and CLICKING.assert GLOW_ACTIVE_STATES == frozenset({OverlayState.TYPING, OverlayState.CLICKING})diff --git a/tests/overlay/test_state_machine.py b/tests/overlay/test_state_machine.pyindex 2e0f25db8f..a594a3304b 100644--- a/tests/overlay/test_state_machine.py+++ b/tests/overlay/test_state_machine.py@@ -1,6 +1,6 @@"""StateMachine — Plan §6 + AD-8 + AD-17.-Tests fuer Coalescing, Subscriber-Dispatch, Re-entrancy.+Tests for coalescing, subscriber dispatch, re-entrancy."""from __future__ import annotations@@ -19,7 +19,7 @@ from overlay.state import (# --------------------------------------------------------------------------# Konstruktion + Initial-State+# Construction + initial state# -------------------------------------------------------------------------@@ -110,7 +110,7 @@ def test_subscriber_runs_in_caller_thread() -> None:def test_reentrant_transition_is_safe() -> None:- """Subscriber darf state lesen UND wieder transition_to rufen."""+ """Subscriber may read state AND call transition_to again."""sm = StateMachine()chain: list[OverlayState] = []@@ -118,7 +118,7 @@ def test_reentrant_transition_is_safe() -> None:def chained(_old: OverlayState, new: OverlayState, _r: str | None) -> None:chain.append(new)if new is OverlayState.LISTENING:- # Re-entrant Call — RLock muss das tragen.+ # Re-entrant call — the RLock must support this.sm.transition_to(OverlayState.THINKING, reason="chained")sm.subscribe(chained)@@ -136,35 +136,35 @@ def test_reentrant_transition_is_safe() -> None:def test_same_state_within_coalesce_window_returns_false() -> None:sm = StateMachine()sm.transition_to(OverlayState.LISTENING)- # Sofort nochmal LISTENING -> coalesced.+ # Immediately LISTENING again -> coalesced.assert sm.transition_to(OverlayState.LISTENING) is Falsedef test_different_state_within_coalesce_window_transitions() -> None:sm = StateMachine()sm.transition_to(OverlayState.LISTENING)- # Andere Ziel-State innerhalb 16 ms -> immer durchlassen.+ # Different target state within 16 ms -> always let through.assert sm.transition_to(OverlayState.THINKING) is Trueassert sm.state is OverlayState.THINKINGdef test_coalesce_window_is_16_ms() -> None:- # Sanity: Konstante = 16 ms.+ # Sanity: constant = 16 ms.assert COALESCE_WINDOW_NS == 16_000_000def test_same_state_after_coalesce_window_still_returns_false() -> None:- """Plan §6.2: kein State-Change bleibt no-op auch nach 16 ms."""+ """Plan §6.2: no state change stays a no-op even after 16 ms."""sm = StateMachine()sm.transition_to(OverlayState.LISTENING)- # 25 ms warten — ueber dem Coalescing-Window — aber gleicher Target.+ # Wait 25 ms — beyond the coalescing window — but same target.time.sleep(0.025)assert sm.transition_to(OverlayState.LISTENING) is False# --------------------------------------------------------------------------# Glow-State-Set+# Glow state set# -------------------------------------------------------------------------diff --git a/tests/overlay/test_supervisor.py b/tests/overlay/test_supervisor.pyindex 287ca8faf8..77899fcdd5 100644--- a/tests/overlay/test_supervisor.py+++ b/tests/overlay/test_supervisor.py@@ -1,4 +1,4 @@-"""OverlaySupervisor — Job-Object + Backoff + Cap. Plan §4.3 + AD-9 + AD-10."""+"""OverlaySupervisor — job object + backoff + cap. Plan §4.3 + AD-9 + AD-10."""from __future__ import annotations@@ -17,7 +17,7 @@ from jarvis.overlay.supervisor import (# --------------------------------------------------------------------------# _backoff_delay — AD-10 Formel+# _backoff_delay — AD-10 formula# -------------------------------------------------------------------------@@ -29,7 +29,7 @@ def test_backoff_first_failure_around_half_second() -> None:def test_backoff_caps_at_30_seconds() -> None:- """Plan AD-10: ``min(30, ...)`` — egal wie viele failures."""+ """Plan AD-10: ``min(30, ...)`` — no matter how many failures."""rng = random.Random(0)for f in [10, 20, 50, 100]:delay = _backoff_delay(f, rng=rng)@@ -43,7 +43,7 @@ def test_backoff_grows_exponentially() -> None:for f in [0, 1, 2, 3]:samples = [_backoff_delay(f, rng=rng) for _ in range(50)]avg.append(sum(samples) / len(samples))- # Jeder weitere step ungefaehr verdoppelt.+ # Each further step roughly doubles.assert avg[1] > 1.5 * avg[0]assert avg[2] > 1.5 * avg[1]assert avg[3] > 1.5 * avg[2]@@ -55,7 +55,7 @@ def test_backoff_grows_exponentially() -> None:def _make_mock_proc(alive: bool = True, pid: int = 1234) -> mock.MagicMock:- """Mock-Popen: poll() returnt None wenn alive, 0 wenn beendet."""+ """Mock Popen: poll() returns None when alive, 0 when finished."""proc = mock.MagicMock()proc.pid = pidproc.poll = mock.MagicMock(return_value=None if alive else 0)@@ -77,7 +77,7 @@ async def test_spawn_calls_subprocess_with_python_and_overlay_args() -> None:sup = OverlaySupervisor(ws_port=7842, spawn_fn=spawn_fn)try:await sup.start()- # Direkt nach start ist proc da.+ # Right after start, the proc is there.assert sup.is_aliveassert "args" in captured# Args: python sys.executable -m overlay --ws-port=7842@@ -88,7 +88,7 @@ async def test_spawn_calls_subprocess_with_python_and_overlay_args() -> None:@pytest.mark.asyncioasync def test_spawn_subprocess_env_unsets_jarvis_depth() -> None:- """Plan: Overlay-Process selbst ist NICHT Sub-Agent."""+ """Plan: the overlay process itself is NOT a sub-agent."""captured = {}def spawn_fn(args: list[str], **kwargs: Any) -> mock.MagicMock:@@ -106,11 +106,11 @@ async def test_spawn_subprocess_env_unsets_jarvis_depth() -> None:@pytest.mark.asyncioasync def test_subprocess_creationflags_on_win32() -> None:- """Plan: CREATE_NEW_PROCESS_GROUP | CREATE_NO_WINDOW auf Windows."""+ """Plan: CREATE_NEW_PROCESS_GROUP | CREATE_NO_WINDOW on Windows."""import sysif sys.platform != "win32":- pytest.skip("creationflags Pflichtig nur auf Windows")+ pytest.skip("creationflags required only on Windows")captured = {}@@ -121,7 +121,7 @@ async def test_subprocess_creationflags_on_win32() -> None:sup = OverlaySupervisor(spawn_fn=spawn_fn)try:await sup.start()- # Sollte beide Bits enthalten.+ # Should contain both bits.cf = captured["creationflags"]assert cf & 0x00000200 # CREATE_NEW_PROCESS_GROUPassert cf & 0x08000000 # CREATE_NO_WINDOW@@ -136,7 +136,7 @@ async def test_subprocess_creationflags_on_win32() -> None:@pytest.mark.asyncioasync def test_heartbeat_timeout_triggers_respawn() -> None:- """Wenn 3 s lang keine Heartbeat: kill + respawn mit backoff."""+ """When no heartbeat for 3 s: kill + respawn with backoff."""spawn_count = [0]def spawn_fn(args: list[str], **kwargs: Any) -> mock.MagicMock:@@ -145,14 +145,14 @@ async def test_heartbeat_timeout_triggers_respawn() -> None:sup = OverlaySupervisor(spawn_fn=spawn_fn,- heartbeat_timeout_s=0.05, # 50 ms fuer Test+ heartbeat_timeout_s=0.05, # 50 ms for the testrng=random.Random(0),)try:await sup.start()assert spawn_count[0] == 1- # Warten bis monitor-loop Heartbeat-Timeout sieht + respawnt.- # 50 ms timeout + 0.5s monitor-tick + ~0.5s backoff = ca 1.5 s.+ # Wait until the monitor loop sees the heartbeat timeout + respawns.+ # 50 ms timeout + 0.5s monitor tick + ~0.5s backoff = ~1.5 s.await asyncio.sleep(2.5)assert spawn_count[0] >= 2, f"expected >=2 spawns, got {spawn_count[0]}"finally:@@ -161,7 +161,7 @@ async def test_heartbeat_timeout_triggers_respawn() -> None:@pytest.mark.asyncioasync def test_notify_heartbeat_prevents_respawn() -> None:- """Wenn Heartbeats fleissig kommen, kein Respawn."""+ """When heartbeats keep coming steadily, no respawn."""spawn_count = [0]def spawn_fn(args: list[str], **kwargs: Any) -> mock.MagicMock:@@ -175,11 +175,11 @@ async def test_notify_heartbeat_prevents_respawn() -> None:)try:await sup.start()- # 6x heartbeat ueber 0.6 s.+ # 6x heartbeat over 0.6 s.for _ in range(6):sup.notify_heartbeat()await asyncio.sleep(0.05)- # Sollte immer noch genau 1 spawn sein.+ # Should still be exactly 1 spawn.assert spawn_count[0] == 1finally:await sup.stop()@@ -192,8 +192,8 @@ async def test_notify_heartbeat_prevents_respawn() -> None:@pytest.mark.asyncioasync def test_cap_fired_after_too_many_restarts() -> None:- """Plan AD-10: Cap nach 5 Restarts in Default-Window. Wir nutzen- cap_count=2 + tiny backoff fuer Test-Speed; die Logik ist die gleiche."""+ """Plan AD-10: cap after 5 restarts in the default window. We use+ cap_count=2 + a tiny backoff for test speed; the logic is the same."""cap_called = [0]spawn_count = [0]@@ -202,22 +202,22 @@ async def test_cap_fired_after_too_many_restarts() -> None:spawn_count[0] += 1return _make_mock_proc()- # Mit cap_count=2 fired Cap beim 3. spawn-attempt.+ # With cap_count=2, the cap fires on the 3rd spawn attempt.sup = OverlaySupervisor(spawn_fn=spawn_fn,heartbeat_timeout_s=0.02,restart_cap_count=2,restart_cap_window_s=30.0,cap_fired_callback=lambda: cap_called.__setitem__(0, cap_called[0] + 1),- # Deterministischer kleiner Backoff — wir wollen schnell zum Cap.+ # Deterministic small backoff — we want to reach the cap quickly.rng=random.Random(0),)- # Backoff-Override: deutlich kuerzer fuer Test-Performance.- sup._stable_reset = 9999.0 # noqa: SLF001 — keine Stable-Resets im Test+ # Backoff override: significantly shorter for test performance.+ sup._stable_reset = 9999.0 # noqa: SLF001 — no stable resets in the testtry:await sup.start()# 4 attempts: initial + 3 restarts. Backoff 0.5+1+2 = ~3.5 s, plus- # monitor-tick Latenz. Geben wir 6 s.+ # monitor-tick latency. We give it 6 s.await asyncio.sleep(6.0)assert sup.cap_active is True, f"cap not fired (spawns={spawn_count[0]})"assert cap_called[0] == 1@@ -228,7 +228,7 @@ async def test_cap_fired_after_too_many_restarts() -> None:@pytest.mark.asyncioasync def test_manual_reset_clears_cap_state() -> None:sup = OverlaySupervisor(spawn_fn=lambda *a, **k: _make_mock_proc())- # Direkt cap setzen ohne Spawn-Loop.+ # Set the cap directly without the spawn loop.sup._cap_active = True # noqa: SLF001sup._failures = 99 # noqa: SLF001sup.manual_reset()diff --git a/tests/overlay/test_throttler.py b/tests/overlay/test_throttler.pyindex f6d4eab12b..7f2f80c936 100644--- a/tests/overlay/test_throttler.py+++ b/tests/overlay/test_throttler.py@@ -92,9 +92,9 @@ def test_back_to_ac_restores_full_fps(machine: StateMachine) -> None:def test_idle_timeout_drops_to_idle_fps(machine: StateMachine) -> None:- """Plan §17.3 — 30 s no events -> fps_idle. Wir nutzen 50 ms zum Testen."""+ """Plan §17.3 — 30 s no events -> fps_idle. We use 50 ms for testing."""t = Throttler(machine, idle_timeout_s=0.05)- # IDLE start, sofort: noch active.+ # IDLE start, immediately: still active.assert t.get_target_fps() == DEFAULT_FPS_ACTIVEtime.sleep(0.07)assert t.get_target_fps() == DEFAULT_FPS_IDLE@@ -105,7 +105,7 @@ def test_state_change_resets_idle_timer(machine: StateMachine) -> None:time.sleep(0.07)assert t.get_target_fps() == DEFAULT_FPS_IDLE # idle bucketmachine.transition_to(OverlayState.LISTENING)- # Nach State-Change ist der Timer reset -> nicht mehr idle bucket.+ # After a state change, the timer resets -> no longer in the idle bucket.assert t.get_target_fps() == DEFAULT_FPS_ACTIVE@@ -157,7 +157,7 @@ def test_fullscreen_release_returns_to_state_fps(machine: StateMachine) -> None:# --------------------------------------------------------------------------# Subscriber feuert nur bei echtem Wechsel+# Subscriber only fires on a real change# -------------------------------------------------------------------------@@ -171,13 +171,13 @@ def test_subscriber_fires_on_initial(machine: StateMachine) -> None:def test_subscriber_does_not_fire_on_idle_seconds_drift(machine: StateMachine,) -> None:- """idle_seconds aendert sich kontinuierlich — ohne Wechsel der- target_fps oder should_hide_view kein Subscriber-Spam."""+ """idle_seconds changes continuously — without a change in+ target_fps or should_hide_view, no subscriber spam."""fired = []t = Throttler(machine)t.subscribe(lambda s: fired.append(s))initial_count = len(fired)- # 5x recompute in kurzer Folge — keine echten Wechsel.+ # 5x recompute in quick succession — no real changes.for _ in range(5):t.recompute()assert len(fired) == initial_count@@ -198,5 +198,5 @@ def test_subscriber_fires_on_state_change(machine: StateMachine) -> None:t.subscribe(lambda s: fired.append(s))initial = len(fired)machine.transition_to(OverlayState.TYPING)- # Muss mind. einmal mehr feuern.+ # Must fire at least once more.assert len(fired) > initialdiff --git a/tests/overlay/test_transparency.py b/tests/overlay/test_transparency.pyindex dcd8abfea8..25584a02d4 100644--- a/tests/overlay/test_transparency.py+++ b/tests/overlay/test_transparency.py@@ -1,4 +1,4 @@-"""ctypes-Wrappers: Mock user32, Flag-Kombinationen verifizieren."""+"""ctypes wrappers: mock user32, verify flag combinations."""from __future__ import annotations@@ -24,7 +24,7 @@ from overlay.transparency import (def fake_user32():"""Faked user32 — capture last GetWindowLongW return + SetWindowLongW args."""user32 = MagicMock()- user32.GetWindowLongW.return_value = 0 # baseline: keine Flags gesetzt+ user32.GetWindowLongW.return_value = 0 # baseline: no flags setuser32.SetWindowLongW.return_value = 0user32.SetWindowDisplayAffinity.return_value = 1 # successreturn user32@@ -45,7 +45,7 @@ def test_apply_click_through_sets_layered_and_transparent(fake_user32, monkeypatdef test_apply_click_through_idempotent(fake_user32, monkeypatch) -> None:- """Wenn beide Flags schon gesetzt sind, wird KEIN SetWindowLongW gerufen."""+ """When both flags are already set, SetWindowLongW is NOT called."""monkeypatch.setattr(transparency, "_is_windows", lambda: True)monkeypatch.setattr(transparency, "get_user32", lambda: fake_user32)fake_user32.GetWindowLongW.return_value = WS_EX_LAYERED | WS_EX_TRANSPARENT@@ -67,7 +67,7 @@ def test_apply_mascot_styles_sets_three_flags(fake_user32, monkeypatch) -> None:assert new_style & WS_EX_LAYEREDassert new_style & WS_EX_NOACTIVATEassert new_style & WS_EX_TOOLWINDOW- # Mascot DARF NICHT click-through sein.+ # Mascot must NOT be click-through.assert not (new_style & WS_EX_TRANSPARENT)@@ -85,7 +85,7 @@ def test_exclude_from_capture_calls_with_correct_constant(fake_user32, monkeypatdef test_noop_on_non_windows(monkeypatch) -> None:monkeypatch.setattr(transparency, "_is_windows", lambda: False)- # Darf nicht crashen, darf user32 nicht laden.+ # Must not crash, must not load user32.apply_click_through(hwnd=0x1)apply_mascot_styles(hwnd=0x1)assert exclude_from_capture(hwnd=0x1) is False@@ -98,5 +98,5 @@ def test_set_per_monitor_dpi_awareness_swallows_errors(monkeypatch) -> None:fake_windll = MagicMock(shcore=fake_shcore)with patch("overlay.transparency.ctypes") as mock_ctypes:mock_ctypes.windll = fake_windll- # Darf nicht raisen.+ # Must not raise.transparency.set_per_monitor_dpi_awareness()diff --git a/tests/overlay/test_triggers.py b/tests/overlay/test_triggers.pyindex 358736c6e9..60f6e660de 100644--- a/tests/overlay/test_triggers.py+++ b/tests/overlay/test_triggers.py@@ -19,8 +19,8 @@ from jarvis.overlay import (@pytest.fixture()def fake_bridge() -> mock.MagicMock:- """Mock-Bridge mit allen emit_* Methods. Wird in jarvis.overlay- set_overlay() injected, danach reset auf None."""+ """Mock bridge with all emit_* methods. Injected into jarvis.overlay via+ set_overlay(), then reset to None afterward."""b = mock.MagicMock()b.emit_action_started = mock.MagicMock(return_value="action-id-001")b.emit_action_ended = mock.MagicMock(return_value=True)@@ -80,14 +80,14 @@ def test_sync_decorator_emits_error_on_exception(with pytest.raises(RuntimeError, match="boom"):doit()fake_bridge.emit_error.assert_called_once()- # Action-ended muss TROTZDEM gerufen werden (finally).+ # action_ended must STILL be called (finally).fake_bridge.emit_action_ended.assert_called_once()args, kwargs = fake_bridge.emit_error.call_argsassert "boom" in args[0]def test_sync_decorator_no_bridge_is_no_op() -> None:- """Wenn set_overlay(None), laeuft die Function ohne Crash."""+ """When set_overlay(None), the function runs without crashing."""set_overlay(None)called = []@@ -178,7 +178,7 @@ async def test_scope_emits_error_on_exception(fake_bridge: mock.MagicMock) -> Nodef test_mouse_click_emits_click_event_before_pyautogui_call(fake_bridge: mock.MagicMock, monkeypatch: pytest.MonkeyPatch) -> None:- """Plan §14.3 + §8.8 — emit_click muss VOR pyautogui.click feuern."""+ """Plan §14.3 + §8.8 — emit_click must fire BEFORE pyautogui.click."""import sysimport types@@ -198,10 +198,10 @@ def test_mouse_click_emits_click_event_before_pyautogui_call(from jarvis.control import mouse- mouse.set_cursor_streamer(None) # kein Streamer noetig+ mouse.set_cursor_streamer(None) # no streamer neededmouse.click(x=100, y=200)- # Decorator emits started; mouse.click emits emit_click; dann pyautogui.click.- # emit_click muss VOR pyautogui.click sein.+ # Decorator emits started; mouse.click emits emit_click; then pyautogui.click.+ # emit_click must come BEFORE pyautogui.click.emit_idx = call_order.index("emit_click")pyautogui_idx = call_order.index("pyautogui.click")assert emit_idx < pyautogui_idxdiff --git a/tests/overlay/test_visual_regression.py b/tests/overlay/test_visual_regression.pyindex caf51d1438..cf493736c4 100644--- a/tests/overlay/test_visual_regression.py+++ b/tests/overlay/test_visual_regression.py@@ -1,21 +1,21 @@-"""Phase 9.4 — Visual-Regression mit Playwright.+"""Phase 9.4 — visual regression with Playwright.-Skipt komplett wenn:- - Playwright nicht installiert (``pytest.importorskip``)- - overlay-ui/dist/edge-glow.html fehlt (kein npm run build gelaufen)- - PLAYWRIGHT_BROWSERS_PATH zeigt auf nichts (Browser nicht- installiert)+Skips entirely when:+ - Playwright is not installed (``pytest.importorskip``)+ - overlay-ui/dist/edge-glow.html is missing (no npm run build was run)+ - PLAYWRIGHT_BROWSERS_PATH points at nothing (browser not+ installed)-Tests pruefen:- - typing/clicking States haben sichtbaren Edge-Glow (opacity > 0.3)- - idle/listening/thinking/speaking/hidden haben KEINEN Glow+Tests verify:+ - typing/clicking states have a visible edge glow (opacity > 0.3)+ - idle/listening/thinking/speaking/hidden have NO glow(opacity ~0)- - prefers-reduced-motion ersetzt Animation durch static opacity 0.4- - State-Display ist hidden ohne ?debug=1, sichtbar mit ?debug=1+ - prefers-reduced-motion replaces the animation with static opacity 0.4+ - the state display is hidden without ?debug=1, visible with ?debug=1-Snapshots landen unter ``tests/overlay/__visual__/``. Per Default werden-keine Snapshots gespeichert — Tests messen Computed-Style, nicht Pixel.-Pixel-Vergleich kommt mit Phase 9.6+ wenn das Mascot dazu kommt.+Snapshots land under ``tests/overlay/__visual__/``. By default no+snapshots are stored — tests measure computed style, not pixels.+Pixel comparison arrives with Phase 9.6+ once the mascot is added."""from __future__ import annotations@@ -39,18 +39,18 @@ EDGE_GLOW_HTML = DIST_DIR / "edge-glow.html"def _skip_if_no_build() -> None:if not EDGE_GLOW_HTML.is_file():- pytest.skip(f"edge-glow.html nicht gefunden unter {EDGE_GLOW_HTML} — `npm run build`?")+ pytest.skip(f"edge-glow.html not found under {EDGE_GLOW_HTML} — `npm run build`?")def _skip_if_no_browser() -> None:- # Playwright wirft Executable-not-found wenn der Browser fehlt.- # Wir koennen vorab nicht zuverlaessig pruefen — fangen den Fehler- # beim launch() ab und skippen dann.+ # Playwright throws executable-not-found when the browser is missing.+ # We can't reliably check upfront — we catch the error+ # at launch() and skip then.passclass _SilentHandler(http.server.SimpleHTTPRequestHandler):- """SimpleHTTPRequestHandler ohne stderr-Spam."""+ """SimpleHTTPRequestHandler without stderr spam."""def log_message(self, format: str, *args: object) -> None: # noqa: A002return@@ -58,8 +58,8 @@ class _SilentHandler(http.server.SimpleHTTPRequestHandler):@pytest.fixture(scope="module")def http_server():- """Lokaler HTTP-Server fuer ``dist/``. Chromium blockt ES-Modules- ueber ``file://`` per CORS — daher serven."""+ """Local HTTP server for ``dist/``. Chromium blocks ES modules+ over ``file://`` via CORS — so we serve them."""_skip_if_no_build()cwd = str(DIST_DIR)@@ -94,7 +94,7 @@ def browser_ctx():yield browserbrowser.close()except Exception as exc: # noqa: BLE001- pytest.skip(f"Playwright-Browser nicht verfuegbar: {exc!r}")+ pytest.skip(f"Playwright browser not available: {exc!r}")def _opacity_of(page, selector: str) -> float:@@ -106,13 +106,13 @@ def _opacity_of(page, selector: str) -> float:@pytest.mark.skipif(os.environ.get("CI") == "true" and os.environ.get("PLAYWRIGHT_HAS_BROWSER") != "1",- reason="CI ohne Playwright-Browser-Install",+ reason="CI without Playwright browser install",)def test_idle_has_no_glow(browser_ctx, page_url: str) -> None:page = browser_ctx.new_page()try:page.goto(page_url)- # Init-State (kein Bridge -> applyState('idle')).+ # Initial state (no bridge -> applyState('idle')).page.wait_for_function("document.documentElement.dataset.state === 'idle'", timeout=2000)@@ -123,7 +123,7 @@ def test_idle_has_no_glow(browser_ctx, page_url: str) -> None:@pytest.mark.skipif(os.environ.get("CI") == "true" and os.environ.get("PLAYWRIGHT_HAS_BROWSER") != "1",- reason="CI ohne Playwright-Browser-Install",+ reason="CI without Playwright browser install",)@pytest.mark.parametrize("state", ["typing", "clicking"])def test_glow_active_in_action_states(browser_ctx, page_url: str, state: str) -> None:@@ -131,7 +131,7 @@ def test_glow_active_in_action_states(browser_ctx, page_url: str, state: str) ->try:page.goto(page_url)page.evaluate(f"document.documentElement.dataset.state = '{state}'")- # Kurz auf transition warten.+ # Briefly wait for the transition.page.wait_for_timeout(300)assert _opacity_of(page, ".edge-glow") > 0.5finally:@@ -140,7 +140,7 @@ def test_glow_active_in_action_states(browser_ctx, page_url: str, state: str) ->@pytest.mark.skipif(os.environ.get("CI") == "true" and os.environ.get("PLAYWRIGHT_HAS_BROWSER") != "1",- reason="CI ohne Playwright-Browser-Install",+ reason="CI without Playwright browser install",)@pytest.mark.parametrize("state", ["listening", "thinking", "speaking", "hidden"]@@ -160,7 +160,7 @@ def test_no_glow_in_non_action_states(@pytest.mark.skipif(os.environ.get("CI") == "true" and os.environ.get("PLAYWRIGHT_HAS_BROWSER") != "1",- reason="CI ohne Playwright-Browser-Install",+ reason="CI without Playwright browser install",)def test_state_display_hidden_without_debug_flag(browser_ctx, page_url: str@@ -181,7 +181,7 @@ def test_state_display_hidden_without_debug_flag(@pytest.mark.skipif(os.environ.get("CI") == "true" and os.environ.get("PLAYWRIGHT_HAS_BROWSER") != "1",- reason="CI ohne Playwright-Browser-Install",+ reason="CI without Playwright browser install",)def test_state_display_visible_with_debug_flag(browser_ctx, page_url: str@@ -202,10 +202,10 @@ def test_state_display_visible_with_debug_flag(@pytest.mark.skipif(os.environ.get("CI") == "true" and os.environ.get("PLAYWRIGHT_HAS_BROWSER") != "1",- reason="CI ohne Playwright-Browser-Install",+ reason="CI without Playwright browser install",)def test_reduced_motion_uses_static_glow(browser_ctx, page_url: str) -> None:- """Plan §19.1: prefers-reduced-motion -> opacity 0.4 statt animation."""+ """Plan §19.1: prefers-reduced-motion -> opacity 0.4 instead of animation."""page = browser_ctx.new_page()page.emulate_media(reduced_motion="reduce")try:diff --git a/tests/overlay/test_window_glow_smoke.py b/tests/overlay/test_window_glow_smoke.pyindex 38e5fea78d..39dc93cbf3 100644--- a/tests/overlay/test_window_glow_smoke.py+++ b/tests/overlay/test_window_glow_smoke.py@@ -1,4 +1,4 @@-"""EdgeGlowWindow Smoke-Test — instantiiert headless, ohne ``show()``."""+"""EdgeGlowWindow smoke test — instantiates headless, without ``show()``."""from __future__ import annotations@@ -14,11 +14,11 @@ def test_edge_glow_window_instantiates_headless(qapp) -> None:from overlay.window_glow import EdgeGlowWindowprimary = QGuiApplication.primaryScreen()- assert primary is not None, "offscreen platform muss einen Screen liefern"+ assert primary is not None, "offscreen platform must provide a screen"win = EdgeGlowWindow(primary, hide_from_capture=False)try:- # Sanity: Flags sind gesetzt — KEIN show() (Plan-Vorgabe).+ # Sanity: flags are set — NO show() (per the plan).flags = win.windowFlags()assert flags & Qt.WindowType.FramelessWindowHintassert flags & Qt.WindowType.WindowStaysOnTopHint@@ -31,7 +31,7 @@ def test_edge_glow_window_instantiates_headless(qapp) -> None:assert win.testAttribute(Qt.WidgetAttribute.WA_NoSystemBackground)assert win.testAttribute(Qt.WidgetAttribute.WA_ShowWithoutActivating)- # Geometrie matcht den Screen.+ # Geometry matches the screen.assert win.geometry() == primary.geometry()finally:win.deleteLater()diff --git a/tests/overlay/test_window_mascot_smoke.py b/tests/overlay/test_window_mascot_smoke.pyindex d027d34cd8..3203fc8ac5 100644--- a/tests/overlay/test_window_mascot_smoke.py+++ b/tests/overlay/test_window_mascot_smoke.py@@ -1,4 +1,4 @@-"""MascotWindow smoke — instantiiert headless, ohne show()."""+"""MascotWindow smoke — instantiates headless, without show()."""from __future__ import annotations@@ -31,7 +31,7 @@ def test_mascot_window_instantiates_headless(qapp, tmp_path) -> None:)try:flags = win.windowFlags()- # Plan §12.2 — exakt diese Flag-Kombination, OHNE+ # Plan §12.2 — exactly this flag combination, WITHOUT# WindowTransparentForInput.assert flags & Qt.WindowType.FramelessWindowHintassert flags & Qt.WindowType.WindowStaysOnTopHint@@ -42,14 +42,14 @@ def test_mascot_window_instantiates_headless(qapp, tmp_path) -> None:assert win.testAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)assert win.testAttribute(Qt.WidgetAttribute.WA_NoSystemBackground)assert win.testAttribute(Qt.WidgetAttribute.WA_ShowWithoutActivating)- # WICHTIG: Mascot ist NICHT TransparentForMouseEvents.+ # IMPORTANT: mascot is NOT TransparentForMouseEvents.assert not win.testAttribute(Qt.WidgetAttribute.WA_TransparentForMouseEvents)# Geometry + Mask.assert win.size().width() == 160assert win.size().height() == 160- # Mask ist gesetzt (kann nicht direkt verglichen werden,- # nur dass mask().isEmpty() False ist).+ # Mask is set (can't be compared directly,+ # just that mask().isEmpty() is False).assert not win.mask().isEmpty()# Position.@@ -70,7 +70,7 @@ def test_mascot_window_skips_state_bridge_without_machine(qapp) -> None:hide_from_capture=False,)try:- # Bridge sollte None sein wenn keine Machine.+ # Bridge should be None when there's no machine.assert win._bridge is None # noqa: SLF001assert win._channel is None # noqa: SLF001finally:diff --git a/tests/review/test_audit.py b/tests/review/test_audit.pyindex 1a550e74ca..177706a3f9 100644--- a/tests/review/test_audit.py+++ b/tests/review/test_audit.py@@ -1,7 +1,7 @@-"""Tests fuer ReviewAudit JSON-Lines-Logger (Phase 8.1).+"""Tests for the ReviewAudit JSON-lines logger (Phase 8.1).-Plan-Referenz: §6.1 Akzeptanzkriterium 3 — Concurrent-Write-Test-(10 Threads x 100 Eintraege), kein Datenverlust.+Plan reference: §6.1 acceptance criterion 3 — concurrent-write test+(10 threads x 100 entries), no data loss."""from __future__ import annotations@@ -41,12 +41,12 @@ def _make_record(# -----------------------------------------------------------------------# Path-Override+# Path override# ----------------------------------------------------------------------def test_constructor_path_override(tmp_path: Path) -> None:- """Plan-§6.1: Default-Pfad ist hardcoded, ueberschreibbar via ctor."""+ """Plan §6.1: default path is hardcoded, overridable via the ctor."""custom = tmp_path / "subdir" / "review.log"audit = ReviewAudit(path=custom)assert audit.path == custom@@ -64,12 +64,12 @@ def test_constructor_accepts_string_path(tmp_path: Path) -> None:# -----------------------------------------------------------------------# Single-Write+# Single write# ----------------------------------------------------------------------def test_append_iteration_single_write(tmp_path: Path) -> None:- """Eine append_iteration -> exakt eine Zeile, parsebar."""+ """One append_iteration -> exactly one line, parseable."""log = tmp_path / "review.log"audit = ReviewAudit(path=log)record = _make_record()@@ -92,7 +92,7 @@ def test_append_iteration_single_write(tmp_path: Path) -> None:def test_append_iteration_creates_parent_dir(tmp_path: Path) -> None:- """Parent-Dir wird angelegt, falls fehlend."""+ """Parent dir is created if missing."""log = tmp_path / "deep" / "nested" / "review.log"audit = ReviewAudit(path=log)audit.append_iteration(_make_record())@@ -100,7 +100,7 @@ def test_append_iteration_creates_parent_dir(tmp_path: Path) -> None:def test_append_iteration_appends_not_overwrites(tmp_path: Path) -> None:- """Mehrere Records -> mehrere Zeilen, alphabetisch geordnet wie geschrieben."""+ """Multiple records -> multiple lines, ordered as written."""log = tmp_path / "review.log"audit = ReviewAudit(path=log)@@ -115,7 +115,7 @@ def test_append_iteration_appends_not_overwrites(tmp_path: Path) -> None:def test_append_iteration_with_optional_fields_omitted(tmp_path: Path) -> None:- """Pre-Check-Failure schreibt ohne score/tokens — Defaults greifen."""+ """Pre-check failure writes without score/tokens — defaults kick in."""log = tmp_path / "review.log"audit = ReviewAudit(path=log)@@ -136,12 +136,12 @@ def test_append_iteration_with_optional_fields_omitted(tmp_path: Path) -> None:# -----------------------------------------------------------------------# Concurrent-Write (10 Threads x 100 Eintraege)+# Concurrent write (10 threads x 100 entries)# ----------------------------------------------------------------------def test_concurrent_write_no_corruption(tmp_path: Path) -> None:- """Plan-§6.1 AC: 10 Threads x 100 Eintraege -> 1000 Zeilen, alle parsebar."""+ """Plan §6.1 AC: 10 threads x 100 entries -> 1000 lines, all parseable."""log = tmp_path / "review.log"audit = ReviewAudit(path=log)@@ -172,15 +172,15 @@ def test_concurrent_write_no_corruption(tmp_path: Path) -> None:raw_text = log.read_text(encoding="utf-8")lines = [line for line in raw_text.splitlines() if line.strip()]- # Keine Korruption, keine fehlenden Zeilen+ # No corruption, no missing linesassert len(lines) == n_threads * per_thread, (f"expected {n_threads * per_thread} lines, got {len(lines)}")- # Alle Zeilen sind valides JSON+ # All lines are valid JSONparsed = [json.loads(line) for line in lines]- # Pro Thread genau `per_thread` Eintraege+ # Exactly `per_thread` entries per threadby_thread: dict[str, list[int]] = {}for p in parsed:by_thread.setdefault(p["run_id"], []).append(p["iteration"])@@ -220,12 +220,12 @@ def test_tail_zero_returns_empty(tmp_path: Path) -> None:def test_tail_skips_corrupt_lines(tmp_path: Path) -> None:- """Korrupte JSON-Zeilen werden uebersprungen, nicht propagiert."""+ """Corrupt JSON lines are skipped, not propagated."""log = tmp_path / "review.log"log.parent.mkdir(parents=True, exist_ok=True)audit = ReviewAudit(path=log)audit.append_iteration(_make_record(iteration=1))- # Kunstvolle Korruption haengen wir manuell an+ # We manually append artificial corruptionwith log.open("a", encoding="utf-8") as fh:fh.write("this is { not valid json\n")audit.append_iteration(_make_record(iteration=2))@@ -236,7 +236,7 @@ def test_tail_skips_corrupt_lines(tmp_path: Path) -> None:# -----------------------------------------------------------------------# AuditRecord-Validation+# AuditRecord validation# ----------------------------------------------------------------------@@ -290,7 +290,7 @@ def test_audit_record_score_out_of_range_rejected() -> None:def test_audit_record_to_jsonline_no_newline() -> None:- """to_jsonline darf KEIN Trailing-Newline enthalten — das fuegt der Logger an."""+ """to_jsonline must NOT contain a trailing newline — the logger adds that."""record = _make_record()line = record.to_jsonline()assert "\n" not in linediff --git a/tests/review/test_checks.py b/tests/review/test_checks.pyindex 41b1b7a28b..17255121e5 100644--- a/tests/review/test_checks.py+++ b/tests/review/test_checks.py@@ -1,7 +1,7 @@-"""Tests fuer Pre/Post-Check-Runner und Built-In-Checks (Phase 8.1).+"""Tests for the pre/post check runner and built-in checks (Phase 8.1).-Plan-Referenz: §6.1 Akzeptanzkriterium 2 — alle 5 Built-Ins,-Pre-Fail-Short-Circuit.+Plan reference: §6.1 acceptance criterion 2 — all 5 built-ins,+pre-fail short circuit."""from __future__ import annotations@@ -27,27 +27,27 @@ from jarvis.core.review.checks import (def test_task_not_empty_positive() -> None:- """Task >10 Chars (gestrippt) ist ok."""- result = task_not_empty("schreib mir ein Skript das X tut")+ """Task >10 chars (stripped) is ok."""+ result = task_not_empty("write me a script that does X")assert result.ok is Trueassert result.name == "task_not_empty"def test_task_not_empty_negative_short() -> None:- """Task <=10 Chars (gestrippt) wird abgelehnt."""+ """Task <=10 chars (stripped) is rejected."""result = task_not_empty("hi")assert result.ok is Falseassert "task too short" in result.messagedef test_task_not_empty_negative_only_whitespace() -> None:- """Whitespace-only zaehlt als 0 Chars."""+ """Whitespace-only counts as 0 chars."""result = task_not_empty(" \n\t ")assert result.ok is Falsedef test_task_not_empty_boundary_exactly_11() -> None:- """Schwellwert ist `> 10`, also 11 ist ok, 10 nicht."""+ """Threshold is `> 10`, so 11 is ok, 10 is not."""assert task_not_empty("a" * 11).ok is Trueassert task_not_empty("a" * 10).ok is False@@ -80,7 +80,7 @@ def test_output_within_budget_positive() -> None:def test_output_within_budget_negative_at_limit() -> None:- """`<` (strikt) — bei genau `max_output_chars` muss abgelehnt werden."""+ """`<` (strict) — at exactly `max_output_chars` it must be rejected."""check = make_output_budget_check(100)assert check("a" * 100).ok is False@@ -130,13 +130,13 @@ def test_no_stub_code_negative_each_marker(marker: str) -> None:def test_no_stub_code_inline_comment_allowed() -> None:- """Inline-Kommentare wie `x = 1 # TODO` sind keine Stub-Lines."""+ """Inline comments like `x = 1 # TODO` are not stub lines."""code = "x = 1 # TODO: add docstring later\n"assert no_stub_code(code).ok is Truedef test_no_stub_code_word_in_string_allowed() -> None:- """`pass` als Substring in legitimem Code ist erlaubt."""+ """`pass` as a substring in legitimate code is allowed."""code = 'msg = "Please pass the test"\n'assert no_stub_code(code).ok is True@@ -175,14 +175,14 @@ def test_valid_json_negative_empty() -> None:def test_pre_runner_all_pass() -> None:runner = PreCheckRunner([task_not_empty])- result = runner.run("ein hinreichend langer Task")+ result = runner.run("a sufficiently long task")assert result.ok is Trueassert result.failed is Noneassert len(result.executed) == 1def test_pre_runner_short_circuit() -> None:- """Plan-§6.1 AC: zweiter Check wird nicht aufgerufen wenn erster failt."""+ """Plan §6.1 AC: the second check is not called when the first fails."""calls: list[str] = []def first(payload: str) -> CheckResult:@@ -198,12 +198,12 @@ def test_pre_runner_short_circuit() -> None:assert result.ok is Falseassert result.failed is not Noneassert result.failed.name == "first"- assert calls == ["first"] # second wurde NICHT aufgerufen+ assert calls == ["first"] # second was NOT calledassert len(result.executed) == 1def test_pre_runner_empty_list_passes() -> None:- """Leere Check-Liste = trivial bestanden."""+ """Empty check list = trivially passed."""runner = PreCheckRunner([])result = runner.run("anything")assert result.ok is True@@ -216,7 +216,7 @@ def test_pre_runner_empty_list_passes() -> None:def test_post_runner_short_circuit_at_third() -> None:- """Short-Circuit funktioniert auch im PostRunner, an beliebiger Stelle."""+ """Short circuit also works in the PostRunner, at any position."""calls: list[str] = []def make(name: str, ok: bool) -> Check:@@ -236,7 +236,7 @@ def test_post_runner_short_circuit_at_third() -> None:def test_post_runner_with_real_builtins() -> None:- """End-to-End mit drei echten Built-Ins."""+ """End-to-end with three real built-ins."""runner = PostCheckRunner([output_not_empty, make_output_budget_check(1000), no_stub_code])@@ -251,32 +251,32 @@ def test_post_runner_with_real_builtins() -> None:def test_post_runner_with_valid_json_optional() -> None:- """valid_json ist nur aktiv, wenn der Caller ihn in den Runner einfuegt."""+ """valid_json is only active when the caller adds it to the runner."""runner_with_json = PostCheckRunner([output_not_empty, valid_json])assert runner_with_json.run('{"x": 1}').ok is Trueassert runner_with_json.run("not json").ok is Falserunner_without_json = PostCheckRunner([output_not_empty])- assert runner_without_json.run("not json").ok is True # optional uebersprungen+ assert runner_without_json.run("not json").ok is True # optional, skipped# -----------------------------------------------------------------------# Smoke: Built-In-Checks zusammen mit json-Loads-Konsistenz+# Smoke: built-in checks together with json.loads consistency# ----------------------------------------------------------------------def test_valid_json_negative_message_format() -> None:- """Sicherstellen, dass die Fehler-Message eine Zeilennummer enthaelt."""+ """Ensure that the error message contains a line number."""result = valid_json("{ invalid")assert result.ok is False- # JSONDecodeError liefert mind. die Position; wir testen dass das nicht- # explodiert wenn man sie formatiert.+ # JSONDecodeError at least provides the position; we test that this+ # doesn't blow up when formatted.assert isinstance(result.message, str)assert "line" in result.messagedef test_valid_json_with_real_verdict_json_passes() -> None:- """Realistischer Reviewer-Output ist gueltiges JSON."""+ """Realistic reviewer output is valid JSON."""payload = json.dumps({"status": "pass", "summary": "ok", "issues": [], "score": 1.0})diff --git a/tests/review/test_config_review_section.py b/tests/review/test_config_review_section.pyindex 1a188f1e0e..b813d995c8 100644--- a/tests/review/test_config_review_section.py+++ b/tests/review/test_config_review_section.py@@ -1,7 +1,7 @@-"""Tests fuer ReviewConfig-Pydantic-Validation (Phase 8.4).+"""Tests for ReviewConfig Pydantic validation (Phase 8.4).-Plan-Referenz: §6.4 — `[review]`-Section in jarvis.toml, Pydantic--Validation grün.+Plan reference: §6.4 — `[review]` section in jarvis.toml, Pydantic+validation green."""from __future__ import annotations@@ -29,7 +29,7 @@ def test_default_review_config() -> None:assert cfg.worker_model == "sonnet"assert cfg.reviewer_model == "opus"assert cfg.default_rubric == "default"- # 4 Rubrics aus Plan §6.4+ # 4 rubrics from Plan §6.4assert set(cfg.rubrics.keys()) == {"default","code_generation",@@ -53,7 +53,7 @@ def test_default_rubrics_have_items() -> None:@pytest.mark.parametrize("bad_max", [0, 6, 10, -1])def test_max_iterations_out_of_range_rejected(bad_max: int) -> None:- """AD-4 hard ceiling 5; werte > 5 oder < 1 werden abgelehnt."""+ """AD-4 hard ceiling 5; values > 5 or < 1 are rejected."""with pytest.raises(ValidationError):ReviewConfig(max_iterations=bad_max)@@ -77,27 +77,27 @@ def test_rubric_items_not_empty() -> None:# -----------------------------------------------------------------------# Roundtrip mit jarvis.toml+# Round trip with jarvis.toml# ----------------------------------------------------------------------def test_jarvis_toml_review_section_exists_and_validates() -> None:- """End-to-End: Die echte jarvis.toml muss eine [review]-Section haben,- die ReviewConfig.model_validate akzeptiert."""+ """End-to-end: the real jarvis.toml must have a [review] section+ that ReviewConfig.model_validate accepts."""jarvis_toml = REPO_ROOT / "jarvis.toml"assert jarvis_toml.exists()raw = tomllib.loads(jarvis_toml.read_text(encoding="utf-8"))- assert "review" in raw, "jarvis.toml hat keine [review]-Section"+ assert "review" in raw, "jarvis.toml has no [review] section"cfg = ReviewConfig.model_validate(raw["review"])- # Werte aus Plan §6.4+ # Values from Plan §6.4assert cfg.enabled is Trueassert cfg.max_iterations == 3assert cfg.hard_ceiling == 5assert cfg.default_rubric == "default"- # Alle 4 Rubrics aus Plan §6.4+ # All 4 rubrics from Plan §6.4assert set(cfg.rubrics.keys()) == {"default","code_generation",diff --git a/tests/review/test_dispatch_tool.py b/tests/review/test_dispatch_tool.pyindex 3dc1b45d5b..01be672660 100644--- a/tests/review/test_dispatch_tool.py+++ b/tests/review/test_dispatch_tool.py@@ -1,7 +1,7 @@-"""Tests fuer DispatchWithReviewTool (Phase 8.4).+"""Tests for DispatchWithReviewTool (Phase 8.4).-Plan-Referenz: §6.4 — Tool-Aufruf mit Trivial-Task, gemockte Pipeline,-ToolResult-Format-Verifikation.+Plan reference: §6.4 — tool call with a trivial task, mocked pipeline,+ToolResult format verification."""from __future__ import annotations@@ -41,7 +41,7 @@ def _make_ctx() -> ExecutionContext:def _make_pipeline_with_pass(audit: ReviewAudit) -> ReviewPipeline:- """Pipeline mit Mocks: Worker liefert Output, Reviewer liefert pass."""+ """Pipeline with mocks: worker delivers output, reviewer delivers pass."""async def worker_spawn(state: RunState, i: int) -> str:return "produced artifact"@@ -97,7 +97,7 @@ def _make_pipeline_with_cap_fire(audit: ReviewAudit) -> ReviewPipeline:def test_tool_schema_is_strict() -> None:- """Plan-§AD-9: strict=True, additionalProperties=false."""+ """Plan §AD-9: strict=True, additionalProperties=false."""tool = DispatchWithReviewTool()schema = tool.schemaassert schema["type"] == "object"@@ -110,7 +110,7 @@ def test_tool_schema_max_iterations_bounded() -> None:tool = DispatchWithReviewTool()mi = tool.schema["properties"]["max_iterations"]assert mi["minimum"] == 1- assert mi["maximum"] == 5 # AD-4 Hard-Ceiling+ assert mi["maximum"] == 5 # AD-4 hard ceilingassert mi["default"] == 3@@ -127,13 +127,13 @@ def test_tool_schema_rubric_enum_matches_plan() -> None:def test_tool_description_contains_selective_activation_hint() -> None:- """Description ist die einzige Schaltstelle für selektive Aktivierung- (Plan §AD-6) — Smalltalk-Negativ-Hinweis muss drin stehen."""+ """Description is the only switch point for selective activation+ (Plan §AD-6) — the smalltalk negative hint must be present."""tool = DispatchWithReviewTool()desc = tool.description.lower()- assert "user-irreversibel" in desc or "user_irreversibel" in desc+ assert "user-irreversibel" in desc or "user_irreversibel" in desc # i18n-allow: matches the German tool description under testassert "smalltalk" in desc- assert "konversation" in desc+ assert "konversation" in desc # i18n-allow: matches the German tool description under test# ----------------------------------------------------------------------@@ -151,7 +151,7 @@ def test_execute_success_returns_tool_result(tmp_path: Path) -> None:result = asyncio.run(tool.execute(- {"task": "schreib ein Python-Skript das Hello World ausgibt", "rubric_id": "default"},+ {"task": "write a python script that prints hello world", "rubric_id": "default"},_make_ctx(),))@@ -177,12 +177,12 @@ def test_execute_cap_fired_returns_warnings(tmp_path: Path) -> None:result = asyncio.run(tool.execute(- {"task": "schreib eine Funktion die zwei Listen mergt"},+ {"task": "write a function that merges two lists"},_make_ctx(),))- # Cap-Fire ist `success=True` mit Warnings (Plan §AD-7: nie fail-closed)+ # Cap fire is `success=True` with warnings (Plan §AD-7: never fail-closed)assert result.success is Trueassert result.output is not Noneassert result.output["cap_fired"] is True@@ -196,17 +196,17 @@ def test_execute_cap_fired_returns_warnings(tmp_path: Path) -> None:def test_execute_rejects_short_task(tmp_path: Path) -> None:- """task < 20 chars wird vor Pipeline-Aufruf abgelehnt."""+ """task < 20 chars is rejected before the pipeline call."""tool = DispatchWithReviewTool(runs_root=tmp_path / "runs",audit_log_path=tmp_path / "review.log",)result = asyncio.run(- tool.execute({"task": "kurz"}, _make_ctx())+ tool.execute({"task": "short"}, _make_ctx()))assert result.success is False- assert result.error and "20 zeichen" in result.error.lower()+ assert result.error and "20 zeichen" in result.error.lower() # i18n-allow: matches the German tool error message under testdef test_execute_rejects_unknown_rubric_id(tmp_path: Path) -> None:@@ -217,7 +217,7 @@ def test_execute_rejects_unknown_rubric_id(tmp_path: Path) -> None:result = asyncio.run(tool.execute({- "task": "schreib eine Python-Funktion die zwei Zahlen addiert",+ "task": "write a python function that adds two numbers","rubric_id": "totally_made_up",},_make_ctx(),@@ -229,7 +229,7 @@ def test_execute_rejects_unknown_rubric_id(tmp_path: Path) -> None:def test_execute_handles_pipeline_exception(tmp_path: Path) -> None:- """Pipeline-Crash wird zu ToolResult.success=False, NICHT propagiert."""+ """Pipeline crash becomes ToolResult.success=False, NOT propagated."""audit = ReviewAudit(path=tmp_path / "review.log")async def crashing_worker(state: RunState, i: int) -> str:@@ -253,7 +253,7 @@ def test_execute_handles_pipeline_exception(tmp_path: Path) -> None:)result = asyncio.run(tool.execute(- {"task": "schreib ein Bash-Skript das die Festplatte säubert"},+ {"task": "write a bash script that cleans the hard drive"},_make_ctx(),))@@ -278,7 +278,7 @@ def test_entry_point_registered() -> None:def test_router_tools_includes_dispatch_with_review() -> None:- """Plan-§AD-14 / Phase 8.4: ROUTER_TOOLS enthält dispatch-with-review."""+ """Plan §AD-14 / Phase 8.4: ROUTER_TOOLS contains dispatch-with-review."""# NB: ``SUB_TOOLS`` was deleted in Welle 4 (the Sub-Jarvis tier no longer# exists — only "router" remains). The former recursion-guard assertion# against SUB_TOOLS is obsolete; updated 2026-06-28.diff --git a/tests/review/test_jarvis_agent_files.py b/tests/review/test_jarvis_agent_files.pyindex 609ee042f2..c9ec838663 100644--- a/tests/review/test_jarvis_agent_files.py+++ b/tests/review/test_jarvis_agent_files.py@@ -1,8 +1,8 @@-"""Tests fuer .claude/agents/jarvis-{worker,reviewer}.md (Phase 8.2).+"""Tests for .claude/agents/jarvis-{worker,reviewer}.md (Phase 8.2).-Plan-Referenz: §6.2 Akzeptanzkriterium 1, §AD-2 (Reviewer read-only),-Anthropic-Doc-Footgun: ohne `tools:`-Frontmatter erbt der Subagent-das volle Toolset des Parent.+Plan reference: §6.2 acceptance criterion 1, §AD-2 (reviewer read-only),+Anthropic doc footgun: without a `tools:` frontmatter, the sub-agent+inherits the parent's full toolset."""from __future__ import annotations@@ -18,9 +18,9 @@ REVIEWER_FILE = AGENTS_DIR / "jarvis-reviewer.md"def _split_frontmatter(text: str) -> tuple[dict, str]:- """Trennt YAML-Frontmatter vom Markdown-Body.+ """Splits the YAML frontmatter from the Markdown body.- Erwartet das ueblich Pandoc-/MkDocs-/OpenClaw-Format:+ Expects the usual Pandoc/MkDocs/OpenClaw format:---key: value---@@ -42,12 +42,12 @@ def _split_frontmatter(text: str) -> tuple[dict, str]:def test_agents_dir_exists() -> None:- assert AGENTS_DIR.is_dir(), f"{AGENTS_DIR} fehlt"+ assert AGENTS_DIR.is_dir(), f"{AGENTS_DIR} is missing"@pytest.mark.parametrize("path", [WORKER_FILE, REVIEWER_FILE])def test_subagent_file_exists(path: Path) -> None:- assert path.is_file(), f"{path} fehlt"+ assert path.is_file(), f"{path} is missing"# ----------------------------------------------------------------------@@ -62,7 +62,7 @@ def test_reviewer_frontmatter_strict() -> None:assert isinstance(fm.get("description"), str) and fm["description"].strip()assert fm.get("model") == "opus"- # AD-2: tools EXAKT "Read, Grep, Glob" — nicht mehr, nicht weniger.+ # AD-2: tools EXACTLY "Read, Grep, Glob" — no more, no less.tools_raw = fm.get("tools")assert isinstance(tools_raw, str), (f"tools must be a string in YAML, got {type(tools_raw).__name__}"@@ -70,23 +70,23 @@ def test_reviewer_frontmatter_strict() -> None:parsed_tools = [t.strip() for t in tools_raw.split(",")]assert parsed_tools == ["Read", "Grep", "Glob"], (f"Reviewer tool-allowlist drift: {parsed_tools!r} "- "— AD-2 verlangt EXAKT [Read, Grep, Glob]"+ "— AD-2 requires EXACTLY [Read, Grep, Glob]")assert body.strip(), "reviewer body must contain the system-prompt"def test_reviewer_body_contains_hard_rules() -> None:- """Smoke-Check: Reviewer-Prompt enthaelt die kritischen Anweisungen."""+ """Smoke check: reviewer prompt contains the critical instructions."""body = REVIEWER_FILE.read_text(encoding="utf-8")assert "DO NOT solve the task" in bodyassert "DO NOT write code" in bodyassert "DO NOT edit files" in body- # JSON-only Output-Constraint+ # JSON-only output constraintassert "JSON only" in body or "Output ONLY valid JSON" in body- # Status-Enum sichtbar+ # Status enum visibleassert "needs_revision" in body- # Cap-Fire-relevante Severity-Werte+ # Cap-fire-relevant severity valuesassert "critical" in bodyassert "warning" in bodyassert "suggestion" in body@@ -107,7 +107,7 @@ def test_worker_frontmatter() -> None:tools_raw = fm.get("tools")assert isinstance(tools_raw, str), "tools must be a YAML scalar string"parsed = {t.strip() for t in tools_raw.split(",")}- # Plan-§6.2 worker tools: Read, Write, Edit, Bash, Grep, Glob+ # Plan §6.2 worker tools: Read, Write, Edit, Bash, Grep, Globassert parsed == {"Read", "Write", "Edit", "Bash", "Grep", "Glob"}, (f"Worker tool-allowlist drift: {parsed!r}")@@ -116,10 +116,10 @@ def test_worker_frontmatter() -> None:def test_worker_body_mentions_feedback_block() -> None:- """Worker muss verstehen wie Feedback aus Vor-Iterationen aussieht."""+ """Worker must understand what feedback from previous iterations looks like."""body = WORKER_FILE.read_text(encoding="utf-8")- # Whitespace-normalisieren, weil der Plan-Wortlaut nach- # `Reviewer feedback from` umbricht.+ # Normalize whitespace, because the plan wording wraps+ # after `Reviewer feedback from`.flat = " ".join(body.split())assert "Reviewer feedback from iteration" in flatassert "hard requirement" in flatdiff --git a/tests/review/test_pipeline_cap.py b/tests/review/test_pipeline_cap.pyindex 734d4871e2..ab8eeabad7 100644--- a/tests/review/test_pipeline_cap.py+++ b/tests/review/test_pipeline_cap.py@@ -1,12 +1,12 @@-"""Tests fuer ReviewPipeline-Cap-Fire mit Best-Of-Pick (Phase 8.2).+"""Tests for ReviewPipeline cap-fire with best-of pick (Phase 8.2).-Plan-Referenz: §6.2 Akzeptanzkriterium 4, §AD-7 — bei Cap-Fire-Fallback-wird der beste Kandidat anhand der gewichteten Score-Heuristik ausgeliefert-(NIE fail-closed).+Plan reference: §6.2 acceptance criterion 4, §AD-7 — on the cap-fire+fallback, the best candidate is delivered based on the weighted score+heuristic (NEVER fail-closed).-Score-Heuristik (Phase-8.2-Prompt):+Score heuristic (Phase-8.2 prompt):score - 0.5 * critical_count - 0.2 * warning_count-Bei Gleichstand: spätere Iteration gewinnt.+On a tie: the later iteration wins."""from __future__ import annotations@@ -54,7 +54,7 @@ def _verdict(def test_cap_fire_returns_best_of(tmp_path: Path) -> None:- """Reviewer liefert immer needs_revision — Cap=3 → Best-Of-Pick.+ """Reviewer always returns needs_revision — cap=3 → best-of pick.Iter 1: score=0.4, 1 critical → effective = 0.4 - 0.5 = -0.1Iter 2: score=0.5, 1 warning → effective = 0.5 - 0.2 = 0.3 ← winner@@ -84,20 +84,20 @@ def test_cap_fire_returns_best_of(tmp_path: Path) -> None:max_iterations=3,)- result = asyncio.run(pipeline.run("ein hinreichend langer Task"))+ result = asyncio.run(pipeline.run("a sufficiently long task"))assert result.outcome is PipelineOutcome.CAP_FIREDassert result.cap_fired is Trueassert len(result.iterations) == 3- # Best-Of: Iter 2+ # Best of: iter 2assert result.final_artifact == "output iter 2"assert result.final_verdict is not Noneassert result.final_verdict.summary == "iter 2"def test_cap_fire_tie_break_prefers_later_iteration(tmp_path: Path) -> None:- """Bei Score-Gleichstand gewinnt die spätere Iteration (mehr Feedback)."""- # Drei Iterationen, identischer effective-Score 0.5+ """On a score tie, the later iteration wins (more feedback)."""+ # Three iterations, identical effective score 0.5verdicts = [_verdict(score=0.5, summary="iter 1"),_verdict(score=0.5, summary="iter 2"),@@ -121,7 +121,7 @@ def test_cap_fire_tie_break_prefers_later_iteration(tmp_path: Path) -> None:audit=ReviewAudit(path=tmp_path / "r.log"),max_iterations=3,)- result = asyncio.run(pipeline.run("ein hinreichend langer Task"))+ result = asyncio.run(pipeline.run("a sufficiently long task"))assert result.cap_fired is Trueassert result.final_artifact == "out3"@@ -130,7 +130,7 @@ def test_cap_fire_tie_break_prefers_later_iteration(tmp_path: Path) -> None:def test_cap_fire_with_critical_dominates(tmp_path: Path) -> None:- """Iteration mit critical wird selbst bei höherem score schlechter."""+ """An iteration with critical scores worse even with a higher score."""# Iter 1: score=0.9, 2 critical → 0.9 - 1.0 = -0.1# Iter 2: score=0.5, 0 critical, 1 warning → 0.5 - 0.2 = 0.3 ← winner# Iter 3: score=0.6, 1 critical → 0.6 - 0.5 = 0.1@@ -157,7 +157,7 @@ def test_cap_fire_with_critical_dominates(tmp_path: Path) -> None:audit=ReviewAudit(path=tmp_path / "r.log"),max_iterations=3,)- result = asyncio.run(pipeline.run("ein hinreichend langer Task"))+ result = asyncio.run(pipeline.run("a sufficiently long task"))assert result.cap_fired is Trueassert result.final_verdict is not None@@ -165,7 +165,7 @@ def test_cap_fire_with_critical_dominates(tmp_path: Path) -> None:def test_cap_fire_respects_hard_ceiling(tmp_path: Path) -> None:- """run(max_iterations=10) darf nicht > Hard-Ceiling 5 fahren."""+ """run(max_iterations=10) must not exceed hard ceiling 5."""iters: list[int] = []async def worker_spawn(state: RunState, i: int) -> str:@@ -183,7 +183,7 @@ def test_cap_fire_respects_hard_ceiling(tmp_path: Path) -> None:audit=ReviewAudit(path=tmp_path / "r.log"),max_iterations=3,)- # Per-Run-Override versucht 10 — wird auf 5 geclamped.+ # Per-run override tries 10 — gets clamped to 5.result = asyncio.run(pipeline.run("ein hinreichend langer Task", max_iterations=10))diff --git a/tests/review/test_pipeline_e2e.py b/tests/review/test_pipeline_e2e.pyindex cc7aaf650e..0ee659be91 100644--- a/tests/review/test_pipeline_e2e.py+++ b/tests/review/test_pipeline_e2e.py@@ -1,15 +1,15 @@-"""E2E-Test gegen echtes `claude` CLI (Phase 8.3).+"""E2E test against the real `claude` CLI (Phase 8.3).-Plan-Referenz: §6.3 Akzeptanzkriterium 2 — Single-Iteration-Run mit-echtem Sub-Jarvis auf Trivial-Task. < 60s p95.+Plan reference: §6.3 acceptance criterion 2 — single-iteration run with+the real Sub-Jarvis on a trivial task. < 60s p95.-Skip-Bedingungen:-- `claude` nicht im PATH → skip (kein CI ohne CLI).-- Kein Login (bei `--bare` ist nur ANTHROPIC_API_KEY-basierter Auth zulässig)- → der Test wird vom claude-CLI selbst mit non-zero exit beendet, was als- Pipeline-Failure auftaucht. Wir testen *nicht* die Auth-Konfiguration des- Hosts, sondern dass der Pipeline-Pfad bei korrekter Auth grün ist.-- Markiert mit `pytest.mark.e2e`, läuft NICHT im normalen pytest-Lauf+Skip conditions:+- `claude` not in PATH → skip (no CI without the CLI).+- No login (with `--bare`, only ANTHROPIC_API_KEY-based auth is allowed)+ → the test is terminated by the claude CLI itself with a non-zero exit, which+ shows up as a pipeline failure. We are *not* testing the host's auth+ configuration, but that the pipeline path is green given correct auth.+- Marked with `pytest.mark.e2e`, does NOT run in the normal pytest run(`pytest -m "not e2e"`)."""from __future__ import annotations@@ -54,10 +54,10 @@ pytestmark = [def test_pipeline_e2e_trivial_task(tmp_path: Path) -> None:- """Pipeline-Single-Iteration-Run gegen echten claude-CLI.+ """Pipeline single-iteration run against the real claude CLI.- Trivial-Task; Worker schreibt eine Funktion + Test in eine Datei,- Reviewer prüft, Pipeline liefert SUCCESS in Iter 1.+ Trivial task; worker writes a function + test to a file,+ reviewer checks it, pipeline returns SUCCESS in iter 1."""runs_root = tmp_path / "review_runs"audit = ReviewAudit(path=tmp_path / "review.log")@@ -84,9 +84,9 @@ def test_pipeline_e2e_trivial_task(tmp_path: Path) -> None:)task = (- "Schreibe eine Python-Funktion `add(a, b)` die ihre Argumente "- "addiert und gib eine 1-2-Zeilen-Bestätigung auf stdout aus. "- "Schreibe das Artefakt in die vorgegebene Pfad-Datei."+ "Write a Python function `add(a, b)` that adds its arguments "+ "and prints a 1-2-line confirmation to stdout. "+ "Write the artifact to the given path file.")t0 = time.monotonic()@@ -96,18 +96,18 @@ def test_pipeline_e2e_trivial_task(tmp_path: Path) -> None:# Plan-Latenz-Anforderung: < 90s lokal (DoD)assert elapsed < 90.0, f"e2e run too slow: {elapsed:.1f}s"- # Pipeline soll mindestens den Worker erfolgreich gespawnt haben.- # Reviewer kann pass / needs_revision liefern — Trivial-Task könnte- # auch needs_revision werden (z.B. "no tests written"). Wir testen- # daher robust: outcome ist SUCCESS oder CAP_FIRED, nicht PRECHECK_FAIL.+ # Pipeline should have spawned at least the worker successfully.+ # Reviewer can return pass / needs_revision — a trivial task could+ # also end up as needs_revision (e.g. "no tests written"). So we test+ # robustly: outcome is SUCCESS or CAP_FIRED, not PRECHECK_FAIL.assert result.outcome in (PipelineOutcome.SUCCESS,PipelineOutcome.CAP_FIRED,PipelineOutcome.FAIL,)assert len(result.iterations) >= 1- # Worker.out muss persistiert sein+ # worker.out must be persistedassert (runs_root / result.run_id / "iter-1" / "worker.out").exists()- # Verdict.json muss vorhanden sein, falls Reviewer durchgelaufen ist+ # verdict.json must exist if the reviewer ran throughif result.iterations[0].verdict is not None:assert (runs_root / result.run_id / "iter-1" / "verdict.json").exists()diff --git a/tests/review/test_pipeline_e2e_multi_iter.py b/tests/review/test_pipeline_e2e_multi_iter.pyindex e94e7f5671..678c815a9a 100644--- a/tests/review/test_pipeline_e2e_multi_iter.py+++ b/tests/review/test_pipeline_e2e_multi_iter.py@@ -1,8 +1,8 @@-"""E2E-Test mit echtem Worker und gemocktem Reviewer (Phase 8.3).+"""E2E test with a real worker and a mocked reviewer (Phase 8.3).-Verifiziert Feedback-Block-Komposition für die zweite Iteration —-das ist der wichtigste Punkt der Multi-Iter-Loop, ohne dass wir den-echten Reviewer-Spawn doppelt zahlen müssen.+Verifies feedback-block composition for the second iteration —+that's the most important point of the multi-iter loop, without us+having to pay for a real reviewer spawn twice."""from __future__ import annotations@@ -44,9 +44,9 @@ pytestmark = [def test_multi_iter_feedback_block_reaches_worker(tmp_path: Path) -> None:- """Iter-1: Worker echt + Reviewer-Mock liefert needs_revision mit- konkretem Issue. Iter-2: Worker echt — wir capturen den Worker-Prompt- und verifizieren, dass das Feedback aus Iter-1 enthalten ist.+ """Iter 1: real worker + reviewer mock returns needs_revision with+ a concrete issue. Iter 2: real worker — we capture the worker prompt+ and verify that the feedback from iter 1 is included."""runs_root = tmp_path / "review_runs"audit = ReviewAudit(path=tmp_path / "review.log")@@ -59,20 +59,20 @@ def test_multi_iter_feedback_block_reaches_worker(tmp_path: Path) -> None:)async def worker_spawn(state: RunState, iteration: int) -> str:- # Wrap real spawner mit Capture für die Verifikation. Der Worker-- # Prompt selbst entsteht im real_worker; wir lesen ihn aus- # state.iterations vor dem Call (Iter 2: state hat Iter-1 mit Verdict).+ # Wrap the real spawner with capture for verification. The worker+ # prompt itself is built inside real_worker; we read it from+ # state.iterations before the call (iter 2: state has iter 1 with verdict).if iteration > 1:- # Capture Feedback-Sichtbarkeit — der Spawner build den Prompt- # gleich; wir verifizieren über das logische Vorliegen der- # Vor-Iteration.+ # Capture feedback visibility — the spawner builds the prompt+ # the same way; we verify via the logical presence of the+ # previous iteration.assert any(r.verdict is not None for r in state.iterations)result = await real_worker.spawn(state, iteration)- # Lese den tatsächlichen Prompt aus iter-N/worker.out + RunDirectory+ # Read the actual prompt from iter-N/worker.out + RunDirectoryreturn resultreviewer_calls = {"count": 0}- issue_text = "die Funktion hat keinen docstring"+ issue_text = "the function has no docstring"async def reviewer_mock(state: RunState, worker_output: str, iteration: int@@ -81,13 +81,13 @@ def test_multi_iter_feedback_block_reaches_worker(tmp_path: Path) -> None:if reviewer_calls["count"] == 1:return ReviewVerdict(status=ReviewStatus.NEEDS_REVISION,- summary="Funktion fehlt docstring",+ summary="Function is missing a docstring",issues=[ReviewIssue(severity="warning",description=issue_text,location="add()",- fix_hint="Füge eine 1-Zeilen-docstring hinzu.",+ fix_hint="Add a 1-line docstring.",)],score=0.6,@@ -106,16 +106,16 @@ def test_multi_iter_feedback_block_reaches_worker(tmp_path: Path) -> None:)task = (- "Schreibe eine Python-Funktion `add(a, b)` die ihre Argumente "- "addiert und gib eine 1-Zeilen-Bestätigung auf stdout aus."+ "Write a Python function `add(a, b)` that adds its arguments "+ "and prints a 1-line confirmation to stdout.")result = asyncio.run(pipeline.run(task, max_iterations=2))- # Iter 2 sollte pass gewesen sein+ # Iter 2 should have passedassert result.outcome is PipelineOutcome.SUCCESSassert reviewer_calls["count"] == 2assert len(result.iterations) == 2- # Iter 1 hatte ein needs_revision-Verdict in state.iterations+ # Iter 1 had a needs_revision verdict in state.iterationsassert (result.iterations[0].verdict is not Noneand result.iterations[0].verdict.status is ReviewStatus.NEEDS_REVISIONdiff --git a/tests/review/test_pipeline_fail.py b/tests/review/test_pipeline_fail.pyindex 9831005ee8..521b870bc1 100644--- a/tests/review/test_pipeline_fail.py+++ b/tests/review/test_pipeline_fail.py@@ -1,7 +1,7 @@-"""Tests fuer ReviewPipeline-Fast-Stop bei status=fail (Phase 8.2).+"""Tests for ReviewPipeline fast-stop on status=fail (Phase 8.2).-Plan-Referenz: §AD-3 — `fail` heißt Architektur-Defekt, kein Retry-sinnvoll. Pipeline stoppt sofort, KEIN Iter-2.+Plan reference: §AD-3 — `fail` means an architectural defect, no retry+makes sense. Pipeline stops immediately, NO iter-2."""from __future__ import annotations@@ -50,7 +50,7 @@ def test_fail_status_stops_immediately(tmp_path: Path) -> None:max_iterations=3,)- result = asyncio.run(pipeline.run("ein hinreichend langer Task"))+ result = asyncio.run(pipeline.run("a sufficiently long task"))assert result.outcome is PipelineOutcome.FAILassert result.success is False@@ -60,7 +60,7 @@ def test_fail_status_stops_immediately(tmp_path: Path) -> None:assert reviewer_calls == [1]assert result.final_verdict is not Noneassert result.final_verdict.status is ReviewStatus.FAIL- # Final-Artifact ist der einzige produzierte Output+ # final_artifact is the only produced outputassert result.final_artifact == "output 1"@@ -88,10 +88,10 @@ def test_fail_audit_contains_one_reviewer_entry_with_fail(tmp_path: Path) -> Nonmax_iterations=3,)- asyncio.run(pipeline.run("ein hinreichend langer Task"))+ asyncio.run(pipeline.run("a sufficiently long task"))entries = audit.tail()- # 2 Eintraege: worker_spawn + reviewer_spawn (Iter 1)+ # 2 entries: worker_spawn + reviewer_spawn (iter 1)assert len(entries) == 2assert entries[1]["phase"] == "reviewer_spawn"assert entries[1]["status"] == "fail"diff --git a/tests/review/test_pipeline_loop.py b/tests/review/test_pipeline_loop.pyindex 39b5221189..106bd84cd1 100644--- a/tests/review/test_pipeline_loop.py+++ b/tests/review/test_pipeline_loop.py@@ -1,8 +1,8 @@-"""Tests fuer ReviewPipeline-Loop: Multi-Iteration-Feedback-Chain (Phase 8.2).+"""Tests for the ReviewPipeline loop: multi-iteration feedback chain (Phase 8.2).-Plan-Referenz: §6.2 Akzeptanzkriterium 3 — gemockter HarnessManager-liefert needs_revision, needs_revision, pass; Pipeline returnt success in-Iteration 3 und der Worker sieht das Feedback der Vor-Iteration.+Plan reference: §6.2 acceptance criterion 3 — a mocked HarnessManager+returns needs_revision, needs_revision, pass; the pipeline returns success in+iteration 3 and the worker sees the feedback from the previous iteration."""from __future__ import annotations@@ -42,13 +42,13 @@ def _pass() -> ReviewVerdict:def test_three_iter_feedback_chain(tmp_path: Path) -> None:- """Reviewer liefert needs_revision x2, dann pass — success in Iter 3."""+ """Reviewer returns needs_revision x2, then pass — success in iter 3."""visible_state_per_call: list[list[str]] = []async def worker_spawn(state: RunState, i: int) -> str:- # Worker inspiziert state — verifiziert dass die Vor-Iterationen mit- # Feedback im RunState sichtbar sind. Phase 8.3 baut daraus den- # Feedback-Block; Phase 8.2 verifiziert nur die Sichtbarkeit.+ # Worker inspects state — verifies that previous iterations with+ # feedback are visible in RunState. Phase 8.3 builds the+ # feedback block from this; Phase 8.2 only verifies visibility.visible = [r.verdict.issues[0].descriptionfor r in state.reviewed_iterations()@@ -79,19 +79,19 @@ def test_three_iter_feedback_chain(tmp_path: Path) -> None:)result = asyncio.run(- pipeline.run("ein hinreichend langer Task fuer Loop-Test")+ pipeline.run("a sufficiently long task for the loop test"))- # Erfolg in Iter 3+ # Success in iter 3assert result.success is Trueassert len(result.iterations) == 3assert result.iterations[-1].verdict is not Noneassert result.iterations[-1].verdict.status is ReviewStatus.PASSassert result.final_artifact == "worker output iter=3"- # Feedback-Sichtbarkeit pro Iteration- assert visible_state_per_call[0] == [] # Iter 1: kein Vor-Feedback- assert visible_state_per_call[1] == ["rename x to user_id"] # Iter 2 sieht Iter-1-Issue+ # Feedback visibility per iteration+ assert visible_state_per_call[0] == [] # iter 1: no previous feedback+ assert visible_state_per_call[1] == ["rename x to user_id"] # iter 2 sees the iter-1 issueassert visible_state_per_call[2] == ["rename x to user_id","add docstring to foo()",@@ -99,7 +99,7 @@ def test_three_iter_feedback_chain(tmp_path: Path) -> None:def test_audit_log_records_all_iterations(tmp_path: Path) -> None:- """3 Worker-Spawns + 3 Reviewer-Spawns = 6 Audit-Eintraege."""+ """3 worker spawns + 3 reviewer spawns = 6 audit entries."""log = tmp_path / "review.log"verdicts = [@@ -127,7 +127,7 @@ def test_audit_log_records_all_iterations(tmp_path: Path) -> None:max_iterations=3,)- asyncio.run(pipeline.run("ein hinreichend langer Task"))+ asyncio.run(pipeline.run("a sufficiently long task"))entries = audit.tail()assert len(entries) == 6@@ -140,13 +140,13 @@ def test_audit_log_records_all_iterations(tmp_path: Path) -> None:"worker_spawn","reviewer_spawn",]- # Reviewer-Statuses spiegeln die Verdict-Kette+ # Reviewer statuses mirror the verdict chainreviewer_statuses = [e["status"] for e in entries if e["phase"] == "reviewer_spawn"]assert reviewer_statuses == ["needs_revision", "needs_revision", "pass"]- # Reviewer-Audit hat issue_count gesetzt+ # Reviewer audit has issue_count setrev_eintraege = [e for e in entries if e["phase"] == "reviewer_spawn"]assert rev_eintraege[0]["issue_count"] == 1assert rev_eintraege[1]["issue_count"] == 1- assert rev_eintraege[2]["issue_count"] == 0 # pass-Verdict ohne Issues+ assert rev_eintraege[2]["issue_count"] == 0 # pass verdict has no issuesdiff --git a/tests/review/test_pipeline_skeleton.py b/tests/review/test_pipeline_skeleton.pyindex 88f1d75bcc..e075eac7b4 100644--- a/tests/review/test_pipeline_skeleton.py+++ b/tests/review/test_pipeline_skeleton.py@@ -1,7 +1,7 @@-"""Tests fuer ReviewPipeline-Skelett: trivialer Single-Iteration-Run (Phase 8.2).+"""Tests for the ReviewPipeline skeleton: trivial single-iteration run (Phase 8.2).-Plan-Referenz: §6.2 Akzeptanzkriterium 2 — Mock-HarnessManager liefert-immer pass, Pipeline returnt success in Iteration 1.+Plan reference: §6.2 acceptance criterion 2 — the mock HarnessManager always+returns pass, the pipeline returns success in iteration 1."""from __future__ import annotations@@ -29,13 +29,13 @@ def _pass_verdict(*, score: float = 1.0) -> ReviewVerdict:def test_single_iteration_pass(tmp_path: Path) -> None:- """Worker liefert Output, Reviewer pass — return success in iter 1."""+ """Worker returns output, reviewer passes — return success in iter 1."""worker_calls: list[int] = []reviewer_calls: list[tuple[int, str]] = []async def worker_spawn(state: RunState, i: int) -> str:worker_calls.append(i)- # Vor der ersten Iteration sind keine Vor-Records da.+ # Before the first iteration there are no previous records.assert state.iterations == []return f"produced artifact iter {i}"@@ -55,7 +55,7 @@ def test_single_iteration_pass(tmp_path: Path) -> None:max_iterations=3,)- result = asyncio.run(pipeline.run("ein hinreichend langer Task fuer die Pipeline"))+ result = asyncio.run(pipeline.run("a sufficiently long task for the pipeline"))assert result.outcome is PipelineOutcome.SUCCESSassert result.success is True@@ -70,8 +70,8 @@ def test_single_iteration_pass(tmp_path: Path) -> None:def test_audit_records_three_lines_per_iteration(tmp_path: Path) -> None:- """Pro Iteration: worker_spawn + reviewer_spawn (postcheck nur bei Fail).- Single-Pass = 2 Audit-Zeilen.+ """Per iteration: worker_spawn + reviewer_spawn (postcheck only on fail).+ Single pass = 2 audit lines."""log = tmp_path / "review.log"@@ -91,7 +91,7 @@ def test_audit_records_three_lines_per_iteration(tmp_path: Path) -> None:audit=audit,)- asyncio.run(pipeline.run("ein hinreichend langer Task"))+ asyncio.run(pipeline.run("a sufficiently long task"))entries = audit.tail()phases = [e["phase"] for e in entries]@@ -115,8 +115,8 @@ def test_run_id_is_unique_per_run(tmp_path: Path) -> None:audit=ReviewAudit(path=tmp_path / "r.log"),)- r1 = asyncio.run(pipeline.run("hinreichend langer Task A"))- r2 = asyncio.run(pipeline.run("hinreichend langer Task B"))+ r1 = asyncio.run(pipeline.run("sufficiently long task A"))+ r2 = asyncio.run(pipeline.run("sufficiently long task B"))assert r1.run_id != r2.run_id@@ -144,12 +144,12 @@ def test_max_iterations_invalid_rejected(tmp_path: Path) -> None:worker_spawn=noop_w,reviewer_spawn=noop_r,audit=ReviewAudit(path=tmp_path / "r.log"),- max_iterations=10, # ueber Hard-Ceiling 5+ max_iterations=10, # above the hard ceiling of 5)def test_precheck_failure_short_circuits(tmp_path: Path) -> None:- """Pre-Check fail → kein Worker-Spawn, kein Reviewer-Spawn."""+ """Pre-check fail → no worker spawn, no reviewer spawn."""worker_calls: list[int] = []reviewer_calls: list[int] = []@@ -166,11 +166,11 @@ def test_precheck_failure_short_circuits(tmp_path: Path) -> None:pipeline = ReviewPipeline(worker_spawn=worker_spawn,reviewer_spawn=reviewer_spawn,- prechecks=PreCheckRunner([task_not_empty]), # task_not_empty failt auf <=10 chars+ prechecks=PreCheckRunner([task_not_empty]), # task_not_empty fails on <=10 charsaudit=ReviewAudit(path=tmp_path / "r.log"),)- result = asyncio.run(pipeline.run("kurz")) # <10 chars+ result = asyncio.run(pipeline.run("short")) # <10 charsassert result.outcome is PipelineOutcome.PRECHECK_FAILassert result.precheck_failure is not None@@ -183,7 +183,7 @@ def test_precheck_failure_short_circuits(tmp_path: Path) -> None:def test_max_iterations_param_overrides_default(tmp_path: Path) -> None:- """Pro-Run-Override per `run(..., max_iterations=2)`."""+ """Per-run override via `run(..., max_iterations=2)`."""iters: list[int] = []async def worker_spawn(state: RunState, i: int) -> str:@@ -207,7 +207,7 @@ def test_max_iterations_param_overrides_default(tmp_path: Path) -> None:)asyncio.run(- pipeline.run("ein hinreichend langer Task", max_iterations=2)+ pipeline.run("a sufficiently long task", max_iterations=2))assert iters == [1, 2]diff --git a/tests/review/test_review_gc.py b/tests/review/test_review_gc.pyindex 86bfcbf4c1..46cc1558b5 100644--- a/tests/review/test_review_gc.py+++ b/tests/review/test_review_gc.py@@ -1,8 +1,8 @@-"""Tests fuer den Review-Pipeline-GC-CLI (Phase 8.5).+"""Tests for the review-pipeline GC CLI (Phase 8.5).-Plan-Referenz: §6.5 Akzeptanzkriterium 2 — temp-Verzeichnis mit fake-Run-Dirs unterschiedlichen Alters, GC-Aufruf, verifiziert dass nur die-richtigen gelöscht wurden.+Plan reference: §6.5 acceptance criterion 2 — a temp directory with fake+run dirs of different ages, a GC call, verifies that only the+correct ones were deleted."""from __future__ import annotations@@ -29,7 +29,7 @@ def _make_run(final: dict | None = None,age_days: float = 0.0,) -> Path:- """Legt ein Fake-Run-Dir an, optional mit final.json und mtime-Backdate."""+ """Creates a fake run dir, optionally with final.json and an mtime backdate."""run_dir = runs_root / run_idrun_dir.mkdir(parents=True, exist_ok=True)(run_dir / "iter-1").mkdir(exist_ok=True)@@ -74,7 +74,7 @@ def test_parse_duration_invalid() -> None:def test_should_delete_skips_incomplete(tmp_path: Path) -> None:- """Run ohne final.json wird NIE gelöscht (Recovery-Buffer)."""+ """A run without final.json is NEVER deleted (recovery buffer)."""runs_root = tmp_path / "runs"runs_root.mkdir()run_dir = _make_run(runs_root, "incomplete", final=None)@@ -160,7 +160,7 @@ def test_run_gc_dry_run_does_not_delete(tmp_path: Path) -> None:keep_cap_fired=False,)assert stats["deleted"] == ["old"]- # Aber: Verzeichnis ist NOCH da (dry_run)+ # But: the directory is STILL there (dry_run)assert (runs_root / "old").is_dir()@@ -211,7 +211,7 @@ def test_run_gc_writes_gc_log(tmp_path: Path) -> None:def test_run_gc_does_not_touch_audit_log(tmp_path: Path) -> None:- """Plan-§AD-11: GC darf Audit-Log NICHT anrühren."""+ """Plan §AD-11: GC must NOT touch the audit log."""runs_root = tmp_path / "runs"runs_root.mkdir()_make_run(runs_root, "x", final={"outcome": "success"}, age_days=60)diff --git a/tests/review/test_review_policy.py b/tests/review/test_review_policy.pyindex afcfdd9b9d..482c68a2da 100644--- a/tests/review/test_review_policy.py+++ b/tests/review/test_review_policy.py@@ -1,7 +1,7 @@-"""Tests fuer ReviewPolicy-Klassifikation (Phase 8.4).+"""Tests for ReviewPolicy classification (Phase 8.4).-Plan-Referenz: §AD-6 (selektive Aktivierung). Klassifikations-Matrix-mit 10+ Test-Queries pro Erwartung; Pass-Rate 100% auf den Cases.+Plan reference: §AD-6 (selective activation). Classification matrix+with 10+ test queries per expectation; 100% pass rate on the cases."""from __future__ import annotations@@ -10,58 +10,61 @@ import pytestfrom jarvis.core.review.policy import PolicyDecision, ReviewPolicy# -----------------------------------------------------------------------# Klassifikations-Matrix+# Classification matrix# -----------------------------------------------------------------------# Tasks die als "review" klassifiziert werden müssen (Aktions-Keywords,-# user-irreversibel oder Multi-Schritt-Synthese).+# Tasks that must be classified as "review" (action keywords,+# user-irreversible, or multi-step synthesis).+# NOTE: the task strings below are simulated German user utterances —+# they are the content under test for ReviewPolicy's German keyword+# matcher (jarvis/core/review/policy.py) and must stay German.SHOULD_REVIEW_CASES: list[tuple[str, str]] = [(- "schreibe ein Python-Script in scripts/foo.py das alle .md-Files umbenennt",- "schreib + Datei-Schreib-Aktion",+ "schreibe ein Python-Script in scripts/foo.py das alle .md-Files umbenennt", # i18n-allow+ "write + file-write action",),(- "erstelle einen Skill der Spotify pausiert wenn ich rede",- "erstelle + skill",+ "erstelle einen Skill der Spotify pausiert wenn ich rede", # i18n-allow+ "create + skill",),(- "generiere mir einen FastAPI-Endpoint mit Pydantic-Validation",- "generier + code-spezifisch",+ "generiere mir einen FastAPI-Endpoint mit Pydantic-Validation", # i18n-allow+ "generate + code-specific",),(- "refactor jarvis/core/protocols.py — extract HarnessTask in eigenes Modul",+ "refactor jarvis/core/protocols.py — extract HarnessTask in eigenes Modul", # i18n-allow"refactor + code-edit",),(- "schreib mir Tests für die neue ReviewPipeline mit pytest",- "schreib + script",+ "schreib mir Tests für die neue ReviewPipeline mit pytest", # i18n-allow+ "write + script",),(- "modifizier die TTS-Provider-Config — wechsle auf gemini-flash und teste die Latenz",- "modifizier + datei-mutation",+ "modifizier die TTS-Provider-Config — wechsle auf gemini-flash und teste die Latenz", # i18n-allow+ "modify + file mutation",),(- "erstelle einen Workflow der jeden Morgen meine Mails triagiert",- "erstelle + skill-äquivalent",+ "erstelle einen Workflow der jeden Morgen meine Mails triagiert", # i18n-allow+ "create + skill-equivalent",),(- "schreib eine SKILL.md für einen Excalidraw-Diagram-Skill",- "schreib + skill",+ "schreib eine SKILL.md für einen Excalidraw-Diagram-Skill", # i18n-allow+ "write + skill",),]-# Tasks die NICHT reviewt werden (Smalltalk, Trivial-Aufrufe, Konversation).+# Tasks that must NOT be reviewed (smalltalk, trivial calls, conversation).SHOULD_NOT_REVIEW_CASES: list[tuple[str, str]] = [- ("hi", "smalltalk + zu kurz"),- ("hallo Jarvis", "smalltalk pattern"),- ("danke", "thanks pattern"),- ("was ist die hauptstadt von frankreich", "wissensfrage smalltalk"),- ("wer ist der bundespräsident", "smalltalk pattern"),- ("wie spät ist es", "wie spät pattern"),- ("kurz", "<30 chars"),- ("erzähl einen Witz über Programmierer", "konversation, kein review-keyword"),- ("wie geht's dir heute", "smalltalk, kein review-keyword"),- ("welcher Tag ist heute", "smalltalk wissensfrage"),+ ("hi", "smalltalk + too short"),+ ("hallo Jarvis", "smalltalk pattern"), # i18n-allow+ ("danke", "thanks pattern"), # i18n-allow+ ("was ist die hauptstadt von frankreich", "knowledge-question smalltalk"), # i18n-allow+ ("wer ist der bundespräsident", "smalltalk pattern"), # i18n-allow+ ("wie spät ist es", "'wie spät' keyword pattern"), # i18n-allow+ ("short", "<30 chars"),+ ("erzähl einen Witz über Programmierer", "conversation, no review keyword"), # i18n-allow+ ("wie geht's dir heute", "smalltalk, no review keyword"), # i18n-allow+ ("welcher Tag ist heute", "smalltalk knowledge-question"), # i18n-allow]@@ -113,9 +116,9 @@ def test_whitespace_only_no_review() -> None:def test_smalltalk_beats_action_keyword() -> None:- """Tasks mit Smalltalk-Pattern UND Action-Keyword werden als- Smalltalk klassifiziert (Smalltalk-Allowlist gewinnt — Plan-§AD-6- Persona-Mandat: Smalltalk-Allowlist ist der erste Cut).+ """Tasks with a smalltalk pattern AND an action keyword are classified+ as smalltalk (the smalltalk allowlist wins — plan §AD-6 persona+ mandate: the smalltalk allowlist is the first cut)."""policy = ReviewPolicy()decision = policy.should_review(@@ -126,20 +129,20 @@ def test_smalltalk_beats_action_keyword() -> None:def test_word_boundary_does_not_match_substring() -> None:- """`code` als Substring in `decode` matcht NICHT — word boundary."""+ """`code` as a substring of `decode` does NOT match — word boundary."""policy = ReviewPolicy()decision = policy.should_review(- "ich kann den decoder ausgabewert nicht interpretieren bitte hilf mir mal damit"+ "ich kann den decoder ausgabewert nicht interpretieren bitte hilf mir mal damit" # i18n-allow)- # 'decode' soll nicht als 'code' triggern+ # 'decode' should not trigger as 'code'assert decision.should_review is False, decisiondef test_default_no_review_without_keywords() -> None:- """Plan-§AD-6: Default ist konservativ — ohne Match → kein Review."""+ """Plan §AD-6: default is conservative — no match → no review."""policy = ReviewPolicy()decision = policy.should_review(- "Was war die Antwort auf meine letzte Frage von gestern Abend?"+ "Was war die Antwort auf meine letzte Frage von gestern Abend?" # i18n-allow)assert decision.should_review is False@@ -153,13 +156,13 @@ def test_decision_reason_is_specific() -> None:assert "smalltalk" in d_smalltalk.reason.lower()d_action = policy.should_review(- "schreibe ein Python-Module das die Datenbank migriert"+ "schreibe ein Python-Module das die Datenbank migriert" # i18n-allow)assert "action" in d_action.reason.lower()def test_custom_keywords_override() -> None:- """Caller kann eigene Keyword-Listen mitgeben (Phase 8.4-API)."""+ """Caller can supply custom keyword lists (Phase 8.4 API)."""policy = ReviewPolicy(review_keywords=("nuke", "bomb"),noreview_keywords=("foo",),diff --git a/tests/review/test_self_mod_excludes_review.py b/tests/review/test_self_mod_excludes_review.pyindex 0645c571df..aaef80e0ff 100644--- a/tests/review/test_self_mod_excludes_review.py+++ b/tests/review/test_self_mod_excludes_review.py@@ -1,8 +1,8 @@-"""Selbst-Mod-Allowlist enthält KEINE review.*-Pfade (Phase 8.4).+"""Self-mod allowlist contains NO review.* paths (Phase 8.4).-Plan-Referenz: §AD-1 (Allowlist statt Denylist), Plan-§6.4 — review.*-darf NIE per Voice/Chat mutiert werden, nur Datei-Edit + Code-Review.-Das verhindert Constraint-Self-Bypass via Tool-Choice.+Plan reference: §AD-1 (allowlist instead of denylist), plan §6.4 — review.*+must NEVER be mutated via voice/chat, only via file edit + code review.+This prevents a constraint self-bypass via tool choice."""from __future__ import annotations@@ -38,7 +38,7 @@ def test_review_reviewer_model_not_in_allowlist() -> None:def test_no_review_path_in_explicit_allowlist() -> None:- """Defense-in-Depth: kein einziger ALLOWED-Spec hat review-prefix."""+ """Defense-in-depth: not a single ALLOWED spec has a review prefix."""review_specs = [spec for spec in SelfModRegistry.list_all() if spec.path.startswith("review.")]diff --git a/tests/review/test_spawns_unit.py b/tests/review/test_spawns_unit.pyindex 53a31b2504..924a737ffd 100644--- a/tests/review/test_spawns_unit.py+++ b/tests/review/test_spawns_unit.py@@ -1,8 +1,8 @@-"""Unit-Tests fuer WorkerSpawner / ReviewerSpawner mit gemocktem+"""Unit tests for WorkerSpawner / ReviewerSpawner with a mockedHarnessManager (Phase 8.3).-Plan-Referenz: §6.3 Akzeptanzkriterien — CLI-Argumente, Prompt-Inhalt,-RunDirectory-Layout, Verdict-Parse + Schema-Reject.+Plan reference: §6.3 acceptance criteria — CLI arguments, prompt content,+RunDirectory layout, verdict parsing + schema rejection."""from __future__ import annotations@@ -39,11 +39,11 @@ from jarvis.core.review.verdict import ReviewStatusclass FakeHarnessManager:- """Drop-in-Ersatz für HarnessManager — kein Subprocess, gibt scripted Result.+ """Drop-in replacement for HarnessManager — no subprocess, returns a scripted result.- Pro Aufruf wird eine vorbereitete `script`-Sequenz konsumiert; dadurch- kann ein Test mehrere aufeinanderfolgende dispatch()-Aufrufe (Worker- + Reviewer) mit unterschiedlichen Outputs scriptien.+ Each call consumes one prepared `script` sequence entry; this lets+ a test script several consecutive dispatch() calls (worker+ + reviewer) with different outputs."""def __init__(self, scripts: list[dict[str, Any]] | None = None) -> None:@@ -110,14 +110,14 @@ def test_worker_spawner_calls_openclaw_harness(tmp_path: Path) -> None:assert isinstance(task, HarnessTask)assert "Original task" in task.promptassert state.task in task.prompt- # Worker-Prompt enthält Pfad-Hinweis (AD-9)+ # worker prompt contains a path hint (AD-9)assert "iter-1" in task.prompt and "worker.out" in task.promptassert isinstance(result, str) and result.strip()def test_worker_spawner_writes_iter_n_worker_out(tmp_path: Path) -> None:- """Wenn der Worker selbst nicht schreibt, persistiert der Spawner stdout."""+ """If the worker itself doesn't write, the spawner persists stdout."""fake = FakeHarnessManager([{"stdout": "summary line\n", "exit_code": 0}])@@ -133,13 +133,13 @@ def test_worker_spawner_writes_iter_n_worker_out(tmp_path: Path) -> None:def test_worker_spawner_keeps_self_written_artifact(tmp_path: Path) -> None:- """Wenn der Worker SELBST in worker.out schreibt, persistiert Spawner- NICHT den stdout drüber.+ """If the worker itself writes to worker.out, the spawner does NOT+ overwrite it with stdout."""runs_root = tmp_path / "runs"state = _make_state(run_id="abc")- # Pre-create worker.out (simuliert Worker-Tool-Use)+ # Pre-create worker.out (simulates worker tool use)pre_dir = RunDirectory(runs_root, "abc").ensure()pre_dir.write_worker_output(1, "self-written artifact body")@@ -164,7 +164,7 @@ def test_worker_spawner_raises_on_nonzero_exit(tmp_path: Path) -> None:def test_worker_spawner_includes_feedback_block_on_iter2(tmp_path: Path) -> None:- """Iter-2-Spawn muss den Feedback-Block aus Iter-1 enthalten."""+ """Iter-2 spawn must include the feedback block from iter 1."""from jarvis.core.review.verdict import ReviewIssue, ReviewVerdictfake = FakeHarnessManager([{"stdout": "summary\n", "exit_code": 0}@@ -208,8 +208,8 @@ def test_reviewer_spawner_passes_schema_and_low_effort(tmp_path: Path) -> None:{"stdout": json.dumps(_valid_verdict_dict()), "exit_code": 0}])runs_root = tmp_path / "runs"- # worker.out muss für den Reviewer-Prompt-Pfad existieren — wird vom- # WorkerSpawner geschrieben; in unit-tests mocken wir das.+ # worker.out must exist for the reviewer prompt path — it's written by+ # WorkerSpawner; in unit tests we mock this.RunDirectory(runs_root, "abc").ensure().write_worker_output(1, "x")spawner = ReviewerSpawner(harness_manager=fake, runs_root=runs_root)@@ -286,7 +286,7 @@ def test_reviewer_spawner_raises_parse_error_on_invalid_json(def test_reviewer_spawner_raises_parse_error_on_schema_violation(tmp_path: Path,) -> None:- """JSON valide, aber score=2.0 verletzt das Schema."""+ """JSON is valid, but score=2.0 violates the schema."""bad = {"status": "pass","summary": "ok",@@ -306,7 +306,7 @@ def test_reviewer_spawner_raises_parse_error_on_schema_violation(def test_reviewer_spawner_handles_prose_prefix(tmp_path: Path) -> None:- """Reviewer ignoriert Prosa vor dem JSON (robustness gegen --output-format-Drift)."""+ """Reviewer ignores prose before the JSON (robustness against --output-format drift)."""payload = _valid_verdict_dict()fake = FakeHarnessManager([{"stdout": "Here is my verdict:\n" + json.dumps(payload), "exit_code": 0}@@ -346,5 +346,5 @@ def test_extract_non_json_returns_none() -> None:def test_extract_array_at_top_returns_none() -> None:- """Top-level ist ein Array, kein Object — Reviewer-Verdict muss Object sein."""+ """Top level is an array, not an object — reviewer verdict must be an object."""assert _extract_verdict_json("[1, 2, 3]") is Nonediff --git a/tests/review/test_ui_routes.py b/tests/review/test_ui_routes.pyindex 6649bf55d4..40db80a365 100644--- a/tests/review/test_ui_routes.py+++ b/tests/review/test_ui_routes.py@@ -1,13 +1,13 @@-"""Tests fuer Review-UI-API-Routes (Phase 8.5).+"""Tests for the review-UI API routes (Phase 8.5).-Plan-Referenz: §6.5 Akzeptanzkriterium 1 — alle 4 GET-Endpunkte gegen-gemocktes Audit-Log und gemockte Run-Directories.+Plan reference: §6.5 acceptance criterion 1 — all 4 GET endpoints against+a mocked audit log and mocked run directories.-Skip-Bedingung: lokale fastapi==0.119.1 + starlette==1.0.0 sind nicht-kompatibel (Starlette hat `on_startup` entfernt; FastAPI reicht es noch-durch). Pre-existing — gleicher Bug in tests/missions/api/*,-tests/board/*, tests/unit/test_voice_bridge_routes.py. Auf einem-kompatiblen Stack laufen die Tests durch.+Skip condition: the local fastapi==0.119.1 + starlette==1.0.0 are not+compatible (Starlette removed `on_startup`; FastAPI still passes it+through). Pre-existing — same bug in tests/missions/api/*,+tests/board/*, tests/unit/test_voice_bridge_routes.py. On a+compatible stack the tests run through."""from __future__ import annotations@@ -15,8 +15,8 @@ from pathlib import Pathimport pytest-# Module-level skip wenn der pre-existing FastAPI/Starlette-Versions-Drift-# das ganze APIRouter-Import-Pattern blockiert.+# Module-level skip when the pre-existing FastAPI/Starlette version drift+# blocks the whole APIRouter import pattern.try:from fastapi import APIRouter as _APIRouter@@ -55,7 +55,7 @@ def _build_app(audit: ReviewAudit, runs_root: Path) -> FastAPI:def _seed_audit(audit: ReviewAudit, run_id: str, *, statuses: list[str]) -> None:- """Schreibt für `run_id` worker_spawn + reviewer_spawn pro Iter."""+ """Writes worker_spawn + reviewer_spawn per iter for `run_id`."""for iteration, status_value in enumerate(statuses, start=1):audit.append_iteration(AuditRecord(@@ -83,7 +83,7 @@ def _seed_audit(audit: ReviewAudit, run_id: str, *, statuses: list[str]) -> None@pytest.fixturedef client_factory(tmp_path: Path):- """Factory die einen TestClient + audit + runs_root liefert."""+ """Factory that returns a TestClient + audit + runs_root."""def make() -> tuple[TestClient, ReviewAudit, Path]:audit = ReviewAudit(path=tmp_path / "review.log")@@ -124,7 +124,7 @@ def test_runs_aggregates_audit_to_summary(client_factory) -> None:assert by_id["abc-2"]["iterations"] == 3assert by_id["abc-2"]["final_status"] == "pass"- # Latency-Summen kommen aus den Audit-Einträgen+ # Latency sums come from the audit entriesassert by_id["abc-2"]["total_latency_ms"] > 0@@ -140,7 +140,7 @@ def test_runs_pagination_limit(client_factory) -> None:def test_runs_cap_fired_classified(client_factory) -> None:client, audit, _ = client_factory()- # Drei needs_revision-Verdicts → cap_fired+ # Three needs_revision verdicts → cap_fired_seed_audit(audit, "cap-run", statuses=["needs_revision"] * 3)res = client.get("/api/review/runs")assert res.status_code == 200@@ -165,9 +165,9 @@ def test_run_detail_includes_iteration_data(client_factory) -> None:client, audit, runs_root = client_factory()_seed_audit(audit, "detail-run", statuses=["pass"])- # Run-Dir mit task.json + iter-1/worker.out + iter-1/verdict.json+ # Run dir with task.json + iter-1/worker.out + iter-1/verdict.jsonrun_dir = RunDirectory(runs_root, "detail-run").ensure()- run_dir.write_task(task="schreibe ein test-script", rubric_id="code_generation")+ run_dir.write_task(task="write a test script", rubric_id="code_generation")run_dir.write_worker_output(1, "produced artifact body" * 5)run_dir.write_verdict(1,@@ -184,7 +184,7 @@ def test_run_detail_includes_iteration_data(client_factory) -> None:assert res.status_code == 200data = res.json()assert data["run_id"] == "detail-run"- assert data["task"] == "schreibe ein test-script"+ assert data["task"] == "write a test script"assert data["rubric_id"] == "code_generation"assert data["final_status"] == "pass"assert len(data["iterations_detail"]) == 1@@ -226,7 +226,7 @@ def test_audit_returns_entries(client_factory) -> None:assert res.status_code == 200data = res.json()assert isinstance(data, list)- # 2 Einträge pro Iter (worker + reviewer), 1 Iter+ # 2 entries per iter (worker + reviewer), 1 iterassert len(data) == 2phases = {e["phase"] for e in data}assert phases == {"worker_spawn", "reviewer_spawn"}@@ -236,7 +236,7 @@ def test_audit_limit_parameter(client_factory) -> None:client, audit, _ = client_factory()for i in range(5):_seed_audit(audit, f"r{i}", statuses=["pass"])- # Insgesamt 10 Audit-Einträge, limit=3 → 3+ # 10 audit entries total, limit=3 → 3res = client.get("/api/review/audit?limit=3")assert res.status_code == 200assert len(res.json()) == 3@@ -267,9 +267,9 @@ def test_stats_aggregates_pass_rate(client_factory) -> None:assert res.status_code == 200data = res.json()assert data["runs_total"] == 3- # 2 pass aus 3 → 0.6667+ # 2 pass out of 3 → 0.6667assert data["pass_rate"] == pytest.approx(2 / 3, abs=0.01)- # 1 cap_fired aus 3+ # 1 cap_fired out of 3assert data["cap_fire_rate"] == pytest.approx(1 / 3, abs=0.01)@@ -283,10 +283,10 @@ def test_stats_window_days_invalid_rejected(client_factory) -> None:def test_stats_cached_within_60s(client_factory, monkeypatch) -> None:- """Wiederholter Aufruf mit gleichem window_days → Cache-Hit (kein Re-Read)."""+ """Repeated call with the same window_days → cache hit (no re-read)."""from jarvis.ui.web import review_routes- # Cache leeren falls vom anderen Test gefüllt+ # Clear the cache in case another test filled itreview_routes._STATS_CACHE.clear()client, audit, _ = client_factory()@@ -294,8 +294,8 @@ def test_stats_cached_within_60s(client_factory, monkeypatch) -> None:res1 = client.get("/api/review/stats?window_days=7")assert res1.status_code == 200- # Audit modifizieren — neuer Run hinzu+ # Modify the audit — add a new run_seed_audit(audit, "y", statuses=["pass"])res2 = client.get("/api/review/stats?window_days=7")- # Wegen Cache: gleicher runs_total wie res1 (nicht 2)+ # Because of the cache: same runs_total as res1 (not 2)assert res2.json()["runs_total"] == res1.json()["runs_total"]diff --git a/tests/review/test_verdict_schema.py b/tests/review/test_verdict_schema.pyindex ed379f902c..f3188f6bbf 100644--- a/tests/review/test_verdict_schema.py+++ b/tests/review/test_verdict_schema.py@@ -1,7 +1,7 @@-"""Tests fuer ReviewVerdict-Pydantic-Modelle (Phase 8.1).+"""Tests for the ReviewVerdict Pydantic models (Phase 8.1).-Plan-Referenz: §6.1 Akzeptanzkriterium 1 — Roundtrip JSON↔Pydantic,-Status-Enum-Reject auf invalide Werte.+Plan reference: §6.1 acceptance criterion 1 — JSON↔Pydantic roundtrip,+status-enum rejection on invalid values."""from __future__ import annotations@@ -21,7 +21,7 @@ from jarvis.core.review.verdict import (def test_review_status_values() -> None:- """Plan-§AD-3: genau drei lowercase string values."""+ """Plan §AD-3: exactly three lowercase string values."""assert ReviewStatus.PASS.value == "pass"assert ReviewStatus.NEEDS_REVISION.value == "needs_revision"assert ReviewStatus.FAIL.value == "fail"@@ -29,8 +29,8 @@ def test_review_status_values() -> None:def test_review_status_str_subclass() -> None:- """ReviewStatus ist `str, Enum` — Vergleich mit Strings funktioniert."""- assert ReviewStatus.PASS == "pass" # noqa: S105 — Status-Wert+ """ReviewStatus is `str, Enum` — comparison with strings works."""+ assert ReviewStatus.PASS == "pass" # noqa: S105 — status valueassert ReviewStatus("pass") is ReviewStatus.PASS@@ -66,7 +66,7 @@ def _full_verdict_dict() -> dict:def test_review_verdict_roundtrip_full() -> None:- """Pydantic <-> JSON Roundtrip mit voll besetztem Verdict."""+ """Pydantic <-> JSON roundtrip with a fully populated verdict."""payload = _full_verdict_dict()verdict = ReviewVerdict.model_validate(payload)assert verdict.status is ReviewStatus.NEEDS_REVISION@@ -75,14 +75,14 @@ def test_review_verdict_roundtrip_full() -> None:assert verdict.issues[0].location == "scripts/foo.py:42"assert verdict.score == 0.55- # JSON-Roundtrip: dump -> load -> dump muss idempotent sein+ # JSON roundtrip: dump -> load -> dump must be idempotentserialized = verdict.model_dump(mode="json")reparsed = ReviewVerdict.model_validate(serialized)assert reparsed.model_dump(mode="json") == serializeddef test_review_verdict_minimal() -> None:- """Default-Factories: issues/rubric_results sind leere Listen."""+ """Default factories: issues/rubric_results are empty lists."""verdict = ReviewVerdict(status=ReviewStatus.PASS,summary="All good.",@@ -98,9 +98,9 @@ def test_review_verdict_minimal() -> None:def test_invalid_status_rejected() -> None:- """Plan-§6.1 AC: Reject auf invalide Status-Strings."""+ """Plan §6.1 AC: rejects invalid status strings."""payload = _full_verdict_dict()- payload["status"] = "approved" # nicht im Enum+ payload["status"] = "approved" # not in the enumwith pytest.raises(ValidationError) as exc:ReviewVerdict.model_validate(payload)assert "status" in str(exc.value).lower()@@ -121,7 +121,7 @@ def test_invalid_status_variants_rejected(bad: str) -> None:@pytest.mark.parametrize("bad_score", [-0.01, 1.01, 1.5, 2.0, -1.0])def test_score_out_of_range_rejected(bad_score: float) -> None:- """Plan-§6.1: score muss in [0.0, 1.0] liegen."""+ """Plan §6.1: score must lie in [0.0, 1.0]."""payload = _full_verdict_dict()payload["score"] = bad_scorewith pytest.raises(ValidationError) as exc:@@ -131,7 +131,7 @@ def test_score_out_of_range_rejected(bad_score: float) -> None:@pytest.mark.parametrize("good_score", [0.0, 0.5, 1.0])def test_score_boundary_values_accepted(good_score: float) -> None:- """Grenzwerte 0.0 und 1.0 sind inklusiv erlaubt."""+ """Boundary values 0.0 and 1.0 are inclusively allowed."""payload = _full_verdict_dict()payload["score"] = good_scoreverdict = ReviewVerdict.model_validate(payload)@@ -139,7 +139,7 @@ def test_score_boundary_values_accepted(good_score: float) -> None:def test_score_required() -> None:- """score ist Pflicht (kein Default)."""+ """score is required (no default)."""payload = _full_verdict_dict()del payload["score"]with pytest.raises(ValidationError):@@ -153,7 +153,7 @@ def test_score_required() -> None:@pytest.mark.parametrize("bad_severity", ["info", "error", "fatal", "", "WARNING"])def test_invalid_severity_rejected(bad_severity: str) -> None:- """Severity ist Literal['critical','warning','suggestion']."""+ """Severity is Literal['critical','warning','suggestion']."""with pytest.raises(ValidationError) as exc:ReviewIssue(severity=bad_severity, description="x") # type: ignore[arg-type]assert "severity" in str(exc.value).lower()@@ -171,7 +171,7 @@ def test_valid_severities() -> None:def test_summary_max_length_enforced() -> None:- """Plan-§9.2: summary maxLength=200 — Voice-Tauglichkeit."""+ """Plan §9.2: summary maxLength=200 — voice suitability."""payload = _full_verdict_dict()payload["summary"] = "x" * 201with pytest.raises(ValidationError) as exc:diff --git a/tests/test_launcher_args.py b/tests/test_launcher_args.pyindex 0d3c2efc84..e0e0fb917e 100644--- a/tests/test_launcher_args.py+++ b/tests/test_launcher_args.py@@ -1,4 +1,4 @@-"""Pure-Unit-Tests für den Argparse-Parser des Standalone-Launchers."""+"""Pure unit tests for the standalone launcher's argparse parser."""from __future__ import annotationsdiff --git a/tests/unit/admin/test_client_destructive_prompt.py b/tests/unit/admin/test_client_destructive_prompt.pyindex a91f2dce40..0ee75ac9e9 100644--- a/tests/unit/admin/test_client_destructive_prompt.py+++ b/tests/unit/admin/test_client_destructive_prompt.py@@ -1,7 +1,7 @@-"""AdminClient: destruktive Ops triggern DestructiveRequiresApproval.+"""AdminClient: destructive ops trigger DestructiveRequiresApproval.-Wir nutzen ein FakePipeClient-Pattern — kein echter Named-Pipe-Traffic,-nur die Dispatch-Logik.+We use a FakePipeClient pattern — no real named-pipe traffic,+just the dispatch logic."""from __future__ import annotations@@ -35,7 +35,7 @@ from jarvis.core.events import (class _FakePipeClient:- """Minimale Fake-Implementation. Antwortet mit success=True."""+ """Minimal fake implementation. Responds with success=True."""def __init__(self) -> None:self.sends: list[AdminOperation] = []@@ -54,7 +54,7 @@ def _make_client(bus: EventBus | None = None,def _representative(op_type: str) -> AdminOperation:- """Baut eine gueltige Op-Instanz fuer den gegebenen Op-Type."""+ """Builds a valid op instance for the given op type."""match op_type:case "install_winget":return InstallWingetOp(package_id="7zip.7zip")@@ -130,7 +130,7 @@ async def test_destructive_ops_raise_without_approval(op_type):with pytest.raises(DestructiveRequiresApproval) as exc:await client.execute(op)assert exc.value.op_type == op_type- # Fake-Pipe darf NICHT aufgerufen worden sein.+ # The fake pipe must NOT have been called.assert fake.sends == []diff --git a/tests/unit/admin/test_executor_winget.py b/tests/unit/admin/test_executor_winget.pyindex a2354711a5..152b259e08 100644--- a/tests/unit/admin/test_executor_winget.py+++ b/tests/unit/admin/test_executor_winget.py@@ -1,9 +1,9 @@-"""Executor-Tests: winget-Dispatch mit gemocktem Subprocess.+"""Executor tests: winget dispatch with a mocked subprocess.-Wichtig:-- Die Command-Line wird auf Liste-Argumente geprueft (keine Shell).-- package_id-Injection ist durch Pydantic-Regex + fehlendes `shell=True`- doppelt abgefangen.+Important:+- The command line is checked as list arguments (no shell).+- package_id injection is caught twice, by the Pydantic regex + the+ missing `shell=True`."""from __future__ import annotations@@ -21,9 +21,9 @@ from jarvis.admin.schema import (class _SubprocessRecorder:- """Ersatz fuer ``AdminExecutor._run_subprocess``.+ """Replacement for ``AdminExecutor._run_subprocess``.- Speichert die argv-Aufrufe und liefert scripted Return-Werte.+ Records the argv calls and returns scripted return values."""def __init__(self, scripted: list[tuple[int, str, str]] | None = None) -> None:@@ -49,7 +49,7 @@ async def test_install_winget_command_line_no_shell_meta():assert resp.success is Trueassert len(rec.calls) == 1argv, _to = rec.calls[0]- # Argumente als Liste — keine Shell-Metazeichen, kein shell=True.+ # Arguments as a list — no shell metacharacters, no shell=True.assert argv[0] == "winget"assert argv[1] == "install"assert "--id" in argv@@ -57,7 +57,7 @@ async def test_install_winget_command_line_no_shell_meta():assert "--silent" in argvassert "--accept-package-agreements" in argvassert "--accept-source-agreements" in argv- # Kein einziges Argument darf ein Semikolon oder &&-artigen Meta haben.+ # Not a single argument may contain a semicolon or &&-style meta char.for a in argv:assert ";" not in aassert "&&" not in a@@ -139,10 +139,10 @@ async def test_run_subprocess_rejects_non_str_argv():@pytest.mark.asyncioasync def test_read_registry_hkcu_environment_smoke(monkeypatch):- """``read_registry`` auf HKCU\\Environment sollte zumindest eine- Response liefern — ob success=True haengt davon ab, ob PATH o.ae.- auf der Test-Maschine gesetzt ist. Wir pruefen nur: keine Exception,- richtiger Response-Typ, error_code bei key-not-found ist korrekt.+ """``read_registry`` on HKCU\\Environment should at least return a+ response — whether success=True depends on whether PATH or similar+ is set on the test machine. We only check: no exception,+ the correct response type, error_code is correct on key-not-found."""ex = AdminExecutor()op = ReadRegistryOp(hive="HKCU", key_path="Environment",diff --git a/tests/unit/admin/test_hmac_replay.py b/tests/unit/admin/test_hmac_replay.pyindex c9eee2987e..31757b0f54 100644--- a/tests/unit/admin/test_hmac_replay.py+++ b/tests/unit/admin/test_hmac_replay.py@@ -1,7 +1,7 @@-"""HMAC-Verifikation + Nonce-Replay-Schutz + Timestamp-Window (ADR-0001).+"""HMAC verification + nonce replay protection + timestamp window (ADR-0001).-Die Tests prueften ``AdminPipeServer._decode_request`` direkt auf-Bytes-Ebene — so brauchen wir weder echte Named-Pipe noch UAC-Elevation.+The tests exercise ``AdminPipeServer._decode_request`` directly at the+byte level — this way we need neither a real named pipe nor UAC elevation."""from __future__ import annotations@@ -68,17 +68,17 @@ def test_hmac_invalid_rejected():def test_nonce_replay_rejected():- """H5-Fix: Cache-Key ist (nonce, timestamp_ns). Replay = exakt derselbe- Envelope ein zweites Mal. Ein Angreifer, der die gesnifferte Message- wiederholt, sendet identische Bytes. Mit neuer Nonce oder neuem- Timestamp waere die HMAC ohnehin anders und wuerde separat scheitern."""+ """H5 fix: the cache key is (nonce, timestamp_ns). Replay = the exact same+ envelope a second time. An attacker who replays the sniffed message+ sends identical bytes. With a new nonce or new timestamp the HMAC+ would be different anyway and would fail separately."""server = _make_server()op = InstallWingetOp(package_id="7zip.7zip")nonce = "deadbeef" * 4raw = _build_envelope(op, nonce=nonce)- # Erster Call ok+ # First call okserver._decode_request(raw)- # Zweiter Call mit EXAKT demselben Envelope → Replay+ # Second call with the EXACT same envelope → replaywith pytest.raises(_AuthFailure) as exc:server._decode_request(raw)assert "nonce_replay" in str(exc.value)@@ -104,8 +104,8 @@ def test_wrong_secret_rejected():def test_tampered_op_args_breaks_hmac():- """HMAC deckt die Args mit ab — Manipulation an package_id nach Signatur- muss scheitern."""+ """HMAC also covers the args — tampering with package_id after signing+ must fail."""server = _make_server()op = InstallWingetOp(package_id="HarmlessPkg")op_dump = op.model_dump(mode="json")@@ -114,7 +114,7 @@ def test_tampered_op_args_breaks_hmac():args_json = _canonical_args_json(op_dump)sig = _compute_hmac(SECRET, nonce, ts, op_dump["type"],op_dump["op_id"], args_json)- # Angriff: nach Signatur die package_id auf was Boeses patchen.+ # Attack: after signing, patch package_id to something malicious.op_dump_tampered = {**op_dump, "package_id": "7zip.7zip"}env = {"nonce": nonce, "timestamp_ns": ts, "hmac": sig,"op": op_dump_tampered}@@ -125,20 +125,20 @@ def test_tampered_op_args_breaks_hmac():def test_lru_evicts_oldest_nonce():- """Nach mehr als LRU-Groesse Eintraegen wird der aelteste verdraengt.-- Seit dem H5-Fix ist der Cache-Key ``(nonce, timestamp_ns)`` — selbst- wenn eine Nonce verdraengt wird, kann sie nur replayed werden wenn- ALSO der exakte Timestamp wiederverwendet wird, was ausserhalb des- 30s-Fensters ohnehin scheitert. Der Test deckt nur die Evict-Mechanik- ab, nicht das Replay-Szenario selbst (das ist durch den Timestamp-- Check separat gesichert).+ """Once more than the LRU size worth of entries is added, the oldest is evicted.++ Since the H5 fix, the cache key is ``(nonce, timestamp_ns)`` — even+ if a nonce is evicted, it can only be replayed if the exact+ timestamp is ALSO reused, which fails separately anyway outside the+ 30s window. This test only covers the eviction mechanics,+ not the replay scenario itself (that is secured separately by the+ timestamp check)."""server = _make_server()lru_size = 10_000- # Wir pruefen die Evict-Logik an einer kleineren Grenze: wir- # fuellen LRU_SIZE + 5 Eintraege und checken die ersten 5 sind weg.- # Das gibt dem Test eine konstante Laufzeit.+ # We test the eviction logic at a smaller boundary: we+ # fill LRU_SIZE + 5 entries and check that the first 5 are gone.+ # This gives the test a constant runtime.ts = 1_000_000_000for i in range(lru_size + 5):server._check_and_record_nonce(f"n{i:06d}", ts + i)@@ -156,20 +156,20 @@ def test_envelope_not_object_rejected():def test_compute_hmac_is_constant_time_compare():- """Sanity: `_compute_hmac` ist deterministisch und die Verifikation- nutzt `hmac.compare_digest` statt `==` — das pruefen wir indirekt,- indem wir identische Aufrufe vergleichen."""+ """Sanity: `_compute_hmac` is deterministic and the verification+ uses `hmac.compare_digest` instead of `==` — we check this indirectly+ by comparing identical calls."""sig1 = _compute_hmac(SECRET, "n", 123, "t", "id", "{}")sig2 = _compute_hmac(SECRET, "n", 123, "t", "id", "{}")assert _hmac.compare_digest(sig1, sig2)- # Und noch: Laenge wie erwartet (sha256 hex = 64 chars).+ # And also: length as expected (sha256 hex = 64 chars).assert len(sig1) == 64- # Sanity-Check: nicht mit blossen sha256 identisch.+ # Sanity check: not identical to a plain sha256.assert sig1 != hashlib.sha256(b"whatever").hexdigest()def test_read_registry_envelope_happy_path():- """Auch non-install Ops gehen durch."""+ """Non-install ops go through too."""server = _make_server()op = ReadRegistryOp(hive="HKCU", key_path="Environment")raw = _build_envelope(op)diff --git a/tests/unit/agents/test_registry.py b/tests/unit/agents/test_registry.pyindex 675a66f3e3..a00863d0a4 100644--- a/tests/unit/agents/test_registry.py+++ b/tests/unit/agents/test_registry.py@@ -1,14 +1,14 @@-"""Unit-Tests fuer jarvis.agents.registry.JarvisAgentRegistry.--Deckt:-- Event-Ingestion pro Event-Typ (9 Typen: OpenClawTask*, BrainTurn*, ToolCall*,- Harness* — zwei letztere als kombinierte Paare).-- Parent-Child-Linking ueber ``parent_trace_id``.-- Heuristisches Parent-Linking fuer HarnessDispatched (juengster running- OpenClaw-Worker).+"""Unit tests for jarvis.agents.registry.JarvisAgentRegistry.++Covers:+- Event ingestion per event type (9 types: OpenClawTask*, BrainTurn*, ToolCall*,+ Harness* — the latter two as combined pairs).+- Parent-child linking via ``parent_trace_id``.+- Heuristic parent linking for HarnessDispatched (newest running+ OpenClaw worker).- tree() vs. snapshot() vs. to_json().-- TTL-basiertes Removal nach Completion.-- Tolerantes Verhalten bei Orphan-Events (parent not yet registered).+- TTL-based removal after completion.+- Tolerant behavior on orphan events (parent not yet registered)."""from __future__ import annotations@@ -44,7 +44,7 @@ def registry(bus: EventBus) -> JarvisAgentRegistry:# ────────────────────────────────────────────────────────────────-# Sub-Jarvis-Lifecycle+# Sub-Jarvis lifecycle# ────────────────────────────────────────────────────────────────@pytest.mark.asyncio@@ -55,7 +55,7 @@ async def test_openclaw_task_started_creates_running_node(await bus.publish(JarvisAgentTaskStarted(trace_id=tid,- utterance="bau mir eine Flask-App",+ utterance="build me a Flask app",context_hints=["Port 8000", "single file"],provider="gemini",model="opus",@@ -67,7 +67,7 @@ async def test_openclaw_task_started_creates_running_node(node = snap[tid.hex]assert node.kind == "jarvis_agent"assert node.status == "running"- assert node.utterance == "bau mir eine Flask-App"+ assert node.utterance == "build me a Flask app"assert node.context_hints == ["Port 8000", "single file"]assert node.provider == "gemini"assert node.model == "opus"@@ -89,7 +89,7 @@ async def test_openclaw_task_completed_marks_success_with_metrics(JarvisAgentTaskCompleted(trace_id=tid,success=True,- summary="Fertig",+ summary="Done",full_log_len=1200,duration_s=14.2,cost_estimate_usd=0.034,@@ -99,7 +99,7 @@ async def test_openclaw_task_completed_marks_success_with_metrics(assert node.status == "completed"assert node.duration_ms == pytest.approx(14200.0)assert node.cost_usd == pytest.approx(0.034)- assert any("Fertig" in p for p in node.prompts)+ assert any("Done" in p for p in node.prompts)@pytest.mark.asyncio@@ -134,7 +134,7 @@ async def test_review_triggered_updates_iteration_counter(# ────────────────────────────────────────────────────────────────-# Brain-Turn-Aggregation (in den juengsten Sub-Jarvis)+# Brain-turn aggregation (into the newest Sub-Jarvis)# ────────────────────────────────────────────────────────────────@pytest.mark.asyncio@@ -149,7 +149,7 @@ async def test_brain_turn_tokens_aggregate_into_newest_openclaw(parent_trace_id=sj,provider="gemini",model="opus",- system_prompt_preview="Du bist der Sub-Jarvis",+ system_prompt_preview="You are the Sub-Jarvis",))await bus.publish(@@ -159,12 +159,12 @@ async def test_brain_turn_tokens_aggregate_into_newest_openclaw(assert node.tokens_in == 1400assert node.tokens_out == 320assert node.cost_usd == pytest.approx(0.034)- # Der system_prompt_preview landete in parent.prompts- assert any("Du bist der Sub-Jarvis" in p for p in node.prompts)+ # The system_prompt_preview ended up in parent.prompts+ assert any("You are the Sub-Jarvis" in p for p in node.prompts)# ────────────────────────────────────────────────────────────────-# Tool-Call-Listen+# Tool-call lists# ────────────────────────────────────────────────────────────────@pytest.mark.asyncio@@ -211,7 +211,7 @@ async def test_tool_call_completed_updates_matching_entry(# ────────────────────────────────────────────────────────────────-# Harness (Child-Heuristik)+# Harness (child heuristic)# ────────────────────────────────────────────────────────────────@pytest.mark.asyncio@@ -227,7 +227,7 @@ async def test_harness_dispatched_links_to_newest_running_openclaw(assert harness.hex in snapassert snap[harness.hex].kind == "harness"assert snap[harness.hex].parent_trace_id == sj.hex- # Parent-Seite: Harness in children_trace_ids+ # Parent side: harness in children_trace_idsassert harness.hex in snap[sj.hex].children_trace_ids@@ -254,7 +254,7 @@ async def test_harness_completed_nonzero_exit_marks_failed(# ────────────────────────────────────────────────────────────────-# Tree / snapshot / JSON-Serialisierung+# Tree / snapshot / JSON serialization# ────────────────────────────────────────────────────────────────@pytest.mark.asyncio@@ -283,7 +283,7 @@ async def test_to_json_is_serializable_shape(assert "server_ts_ns" in payloadassert payload["count"] == 1assert payload["server_ts_ns"] > 0- # Alle Roots sind JSON-safe dicts+ # All roots are JSON-safe dictsfor root in payload["roots"]:assert isinstance(root, dict)assert "trace_id" in root@@ -307,12 +307,12 @@ async def test_clear_removes_all_nodes(@pytest.mark.asyncioasync def test_ttl_removes_completed_node_after_timeout(bus: EventBus) -> None:- # Sehr kurzes TTL fuer den Test+ # Very short TTL for the testreg = JarvisAgentRegistry(bus, ttl_completed_s=0).attach()tid = uuid4()await bus.publish(JarvisAgentTaskStarted(trace_id=tid))await bus.publish(JarvisAgentTaskCompleted(trace_id=tid, success=True))- # Event-Loop Runde lassen, damit der Cleanup-Task laeuft+ # Yield an event-loop round so the cleanup task runsawait asyncio.sleep(0.05)assert tid.hex not in reg.snapshot()@@ -321,18 +321,18 @@ async def test_ttl_removes_completed_node_after_timeout(bus: EventBus) -> None:async def test_orphan_child_tolerated_without_parent(bus: EventBus, registry: JarvisAgentRegistry) -> None:- # HarnessDispatched ohne running Sub-Jarvis → Harness als Root (parent=None)+ # HarnessDispatched without a running Sub-Jarvis → harness as root (parent=None)h = uuid4()await bus.publish(HarnessDispatched(trace_id=h, harness="openclaw"))node = registry.snapshot()[h.hex]assert node.parent_trace_id is None- # tree() sollte ihn als Root zeigen+ # tree() should show it as a rootassert any(r.trace_id == h.hex for r in registry.tree())@pytest.mark.asyncioasync def test_agent_node_default_fields_are_empty() -> None:- """Regressions-Guard: AgentNode-Defaults sind JSON-safe und leer."""+ """Regression guard: AgentNode defaults are JSON-safe and empty."""node = AgentNode(trace_id="x", kind="openclaw", name="test")assert node.context_hints == []assert node.prompts == []@@ -390,7 +390,7 @@ async def test_mission_bus_bridge_creates_openclaw_node(tokens_used=1234,cost_usd=0.42,wall_ms=5000,- summary_de="fertig",+ summary_de="fertig", # i18n-allowsummary_en="done",),)@@ -399,7 +399,7 @@ async def test_mission_bus_bridge_creates_openclaw_node(node = registry.snapshot()[tid]assert node.status == "completed"assert node.cost_usd == pytest.approx(0.42)- assert any("fertig" in p for p in node.prompts)+ assert any("fertig" in p for p in node.prompts) # i18n-allow@pytest.mark.asynciodiff --git a/tests/unit/awareness/test_awareness_snapshot_tool.py b/tests/unit/awareness/test_awareness_snapshot_tool.pyindex 95f4371c60..c23773ddb7 100644--- a/tests/unit/awareness/test_awareness_snapshot_tool.py+++ b/tests/unit/awareness/test_awareness_snapshot_tool.py@@ -1,9 +1,9 @@-"""Tests fuer jarvis.plugins.tool.awareness_snapshot.AwarenessSnapshotTool.+"""Tests for jarvis.plugins.tool.awareness_snapshot.AwarenessSnapshotTool.-Verbindlich aus Plan §5: Tool ist SYNCHRON, KEIN Brain-Call, KEIN IO.-Plus zwei Hard-Negatives:- 1. Tool MUSS in ROUTER_TOOLS sein.- 2. Tool DARF NICHT in SUB_TOOLS sein (Sub-Jarvis ist stateless).+Binding from plan §5: the tool is SYNCHRONOUS, NO brain call, NO IO.+Plus two hard negatives:+ 1. Tool MUST be in ROUTER_TOOLS.+ 2. Tool MUST NOT be in SUB_TOOLS (Sub-Jarvis is stateless)."""from __future__ import annotations@@ -42,13 +42,13 @@ def test_risk_tier_is_safe() -> None:def test_schema_is_empty() -> None:- """Plan §5: Tool nimmt keine Args."""+ """Plan §5: the tool takes no args."""tool = AwarenessSnapshotTool(manager=AwarenessManager(AwarenessConfig.default()))assert tool.schema == {"type": "object", "properties": {}, "required": []}def test_description_mentions_state_first_use() -> None:- """Plan §5 description: 'NUTZE das BEVOR du den User nach Kontext fragst'."""+ """Plan §5 description: 'USE this BEFORE asking the user for context'."""tool = AwarenessSnapshotTool(manager=AwarenessManager(AwarenessConfig.default()))assert "BEVOR" in tool.description or "vor" in tool.description.lower()@@ -57,7 +57,7 @@ def test_description_mentions_state_first_use() -> None:@pytest.mark.asyncioasync def test_returns_synchronously_without_brain_call() -> None:- """Tool gibt sofort zurueck — Output enthaelt window_title."""+ """Tool returns immediately — output contains window_title."""tool = AwarenessSnapshotTool(manager=_make_manager_with_frame())result = await tool.execute({}, ctx=None)assert result.success is True@@ -66,7 +66,7 @@ async def test_returns_synchronously_without_brain_call() -> None:@pytest.mark.asyncioasync def test_returns_empty_string_when_no_frame() -> None:- """Ohne current_frame: snapshot_for_prompt liefert '' — Tool meldet success=True."""+ """Without current_frame: snapshot_for_prompt returns '' — tool reports success=True."""tool = AwarenessSnapshotTool(manager=AwarenessManager(AwarenessConfig.default()))result = await tool.execute({}, ctx=None)assert result.success is True@@ -75,7 +75,7 @@ async def test_returns_empty_string_when_no_frame() -> None:@pytest.mark.asyncioasync def test_1000_calls_under_50ms_p95() -> None:- """Plan §5 AC: 1000 Calls in <50ms-p95."""+ """Plan §5 AC: 1000 calls in <50ms p95."""tool = AwarenessSnapshotTool(manager=_make_manager_with_frame())durations_ms: list[float] = []for _ in range(1000):@@ -91,14 +91,14 @@ async def test_1000_calls_under_50ms_p95() -> None:# --- Hard-Negatives (Plan §5 verbindlich) -----------------------------------def test_NOT_in_SUB_TOOLS() -> None:- """Plan §5 Hard-Negative: Sub-Jarvis ist stateless — kein awareness-snapshot."""+ """Plan §5 hard negative: Sub-Jarvis is stateless — no awareness-snapshot."""from jarvis.brain import factorysub_tools = getattr(factory, "SUB_TOOLS", frozenset())assert "awareness-snapshot" not in sub_toolsdef test_in_ROUTER_TOOLS() -> None:- """Plan §5: awareness-snapshot ist Router-Tier-Only."""+ """Plan §5: awareness-snapshot is router-tier only."""from jarvis.brain import factoryrouter_tools = getattr(factory, "ROUTER_TOOLS", frozenset())assert "awareness-snapshot" in router_toolsdiff --git a/tests/unit/awareness/test_config.py b/tests/unit/awareness/test_config.pyindex a8a73c87ca..0da2e1bf50 100644--- a/tests/unit/awareness/test_config.py+++ b/tests/unit/awareness/test_config.py@@ -1,10 +1,10 @@-"""Tests fuer jarvis.awareness.config.AwarenessConfig.+"""Tests for jarvis.awareness.config.AwarenessConfig.-A0-Scope:-- Pydantic-Model laedt mit Defaults (default()-Helper).-- Default-Blacklist matcht Plan §4 Wortlaut.-- Backward-Compat: jarvis.toml ohne [awareness]-Block laedt sauber.-- Custom-TOML ueberschreibt Defaults.+A0 scope:+- The Pydantic model loads with defaults (default() helper).+- The default blacklist matches the plan §4 wording.+- Backward compat: jarvis.toml without an [awareness] block loads cleanly.+- Custom TOML overrides the defaults."""from __future__ import annotations@@ -15,7 +15,7 @@ from jarvis.awareness.config import AwarenessConfigdef test_default_loads_clean() -> None:- """AwarenessConfig.default() ohne Argumente, ohne Errors."""+ """AwarenessConfig.default() with no arguments, no errors."""cfg = AwarenessConfig.default()assert cfg.enabled is Trueassert cfg.privacy is not None@@ -24,7 +24,7 @@ def test_default_loads_clean() -> None:def test_default_blacklist_matches_plan_section_4() -> None:- """Default-Blacklist enthaelt exakt die §4-Patterns."""+ """The default blacklist contains exactly the §4 patterns."""cfg = AwarenessConfig.default()blocked_procs = cfg.privacy.blocked_processesassert "1password*" in blocked_procs@@ -39,11 +39,11 @@ def test_default_blacklist_matches_plan_section_4() -> None:"*Passwort*", "*Password*Manager*","*Inkognito*", "*Private Browsing*",):- assert pattern in blocked_titles, f"Plan-Pattern fehlt: {pattern}"+ assert pattern in blocked_titles, f"plan pattern missing: {pattern}"def test_default_allowed_processes_matches_plan() -> None:- """Default-Allowlist enthaelt Coding-Apps aus §4."""+ """The default allowlist contains coding apps from §4."""cfg = AwarenessConfig.default()for proc in ("code.exe", "cursor.exe", "windsurf.exe","WindowsTerminal.exe", "pwsh.exe", "cmd.exe"):@@ -51,13 +51,13 @@ def test_default_allowed_processes_matches_plan() -> None:def test_default_when_unknown_is_hybrid() -> None:- """D-A1 Default: Hybrid-Strategy."""+ """D-A1 default: hybrid strategy."""cfg = AwarenessConfig.default()assert cfg.privacy.default_when_unknown == "block_for_browsers_allow_for_others"def test_watchers_defaults_for_a1_forward_compat() -> None:- """Watchers-Defaults sind hier definiert, werden in A1 verwendet."""+ """Watchers defaults are defined here, used in A1."""cfg = AwarenessConfig.default()assert cfg.watchers.enable_window is Trueassert cfg.watchers.enable_idle is True@@ -65,14 +65,14 @@ def test_watchers_defaults_for_a1_forward_compat() -> None:def test_quotas_defaults() -> None:- """Quotas-Defaults: 50 MiB / 1000 Episoden."""+ """Quotas defaults: 50 MiB / 1000 episodes."""cfg = AwarenessConfig.default()assert cfg.quotas.max_bytes == 50 * 1024 * 1024assert cfg.quotas.max_episodes == 1000def test_loads_from_toml_overrides_defaults() -> None:- """Custom-TOML ueberschreibt Defaults Feld fuer Feld."""+ """Custom TOML overrides defaults field by field."""raw = textwrap.dedent("""enabled = false@@ -101,9 +101,9 @@ def test_loads_from_toml_overrides_defaults() -> None:def test_partial_toml_keeps_defaults_for_missing_keys() -> None:- """Backward-Compat: nur einige Felder gesetzt → Rest bleibt Default."""+ """Backward compat: only some fields set → the rest stays default."""data = tomllib.loads('enabled = false\n')cfg = AwarenessConfig(**data)assert cfg.enabled is False- # Privacy-Defaults wurden NICHT veraendert+ # Privacy defaults were NOT changedassert "1password*" in cfg.privacy.blocked_processesdiff --git a/tests/unit/awareness/test_context_resolution.py b/tests/unit/awareness/test_context_resolution.pyindex a1bc17b15d..b11e89a664 100644--- a/tests/unit/awareness/test_context_resolution.py+++ b/tests/unit/awareness/test_context_resolution.py@@ -1,14 +1,14 @@-"""Unit-Tests fuer Phase A4 ``resolve_context`` (jarvis/awareness/context.py).+"""Unit tests for phase A4 ``resolve_context`` (jarvis/awareness/context.py).-Spec: JARVIS_AWARENESS_PLAN.md §8 Heuristik-Reihenfolge.+Spec: JARVIS_AWARENESS_PLAN.md §8 heuristic order.-Testet:+Tests:- IDE_SET (code.exe / cursor.exe / windsurf.exe) → cwd via psutil.-- Browser (chrome.exe / msedge.exe) → Hostname aus Window-Title.+- Browser (chrome.exe / msedge.exe) → hostname from the window title.- Terminal (WindowsTerminal.exe / pwsh.exe) → cwd via psutil.-- Fallback unbekannter Process → process_name.-- task_label = erste 5 Worte des Title.-- Lazy-Import von psutil + Fail-Silent bei psutil-Failures.+- Fallback for an unknown process → process_name.+- task_label = first 5 words of the title.+- Lazy import of psutil + fail-silent on psutil failures."""from __future__ import annotations@@ -38,7 +38,7 @@ def _frame()-# ---- Heuristik-Tabellen ----------------------------------------------------+# ---- Heuristic tables -------------------------------------------------------def test_ide_set_contains_known_editors() -> None:@@ -72,7 +72,7 @@ def test_ide_resolves_cwd_via_psutil() -> None:def test_ide_falls_back_to_process_name_when_cwd_fails() -> None:- """psutil-Failure → fallback auf process_name."""+ """psutil failure → fallback to process_name."""with patch("jarvis.awareness.context._safe_cwd", return_value=None):ctx = resolve_context(_frame(process="code.exe"))assert ctx.project_root == "code.exe"@@ -98,7 +98,7 @@ def test_browser_resolves_domain_in_title() -> None:def test_browser_falls_back_when_no_url_in_title() -> None:- """Title ohne Domain → fallback auf process_name."""+ """Title without a domain → fallback to process_name."""ctx = resolve_context(_frame(process="chrome.exe",title="Stack Overflow - Google Chrome",@@ -128,7 +128,7 @@ def test_terminal_falls_back_when_cwd_fails() -> None:def test_unknown_process_falls_back_to_process_name() -> None:- """Unbekannter Process: process_name ist Fallback-Identity-Key."""+ """Unknown process: process_name is the fallback identity key."""ctx = resolve_context(_frame(process="random_app.exe",title="Random App Window",@@ -145,7 +145,7 @@ def test_empty_process_name_uses_unknown_sentinel() -> None:def test_task_label_truncated_to_five_words() -> None:- """Plan §8: erste 5 Worte des Window-Titles."""+ """Plan §8: first 5 words of the window title."""ctx = resolve_context(_frame(process="random_app.exe",title="word1 word2 word3 word4 word5 word6 word7",@@ -179,7 +179,7 @@ def test_hostname_from_title_extracts_domain() -> None:def test_hostname_from_title_strips_browser_suffix() -> None:- """Browser-Suffix darf nicht als Domain interpretiert werden."""+ """A browser suffix must not be interpreted as a domain."""assert _hostname_from_title("Login - Mozilla Firefox") is None@@ -192,7 +192,7 @@ def test_hostname_from_title_returns_none_for_no_domain() -> None:def test_safe_cwd_returns_none_on_invalid_pid() -> None:- """pid <= 0 → None ohne psutil-Aufruf."""+ """pid <= 0 → None without a psutil call."""from jarvis.awareness.context import _safe_cwdassert _safe_cwd(0) is None@@ -201,12 +201,12 @@ def test_safe_cwd_returns_none_on_invalid_pid() -> None:def test_safe_cwd_returns_none_on_psutil_exception() -> None:"""psutil.Process raises (NoSuchProcess, AccessDenied, OSError, ...)- → fallback to None ohne Crash.+ → fallback to None without a crash."""from jarvis.awareness.context import _safe_cwd- # Patch psutil-Modul Lazy-Import via sys.modules. Wenn psutil nicht- # installiert ist, schluckt der except auch ImportError.+ # Patch the psutil module lazy import via sys.modules. If psutil is+ # not installed, the except also swallows ImportError.with patch("jarvis.awareness.context._safe_cwd", wraps=_safe_cwd):# Direct call — _safe_cwd has its own try/except; we simulate# via patched psutil module raising an exception.@@ -217,7 +217,7 @@ def test_safe_cwd_returns_none_on_psutil_exception() -> None:mock_proc.side_effect = RuntimeError("nope")assert _safe_cwd(99999) is Noneexcept ImportError:- # psutil nicht installiert → _safe_cwd liefert None via except ImportError+ # psutil not installed → _safe_cwd returns None via except ImportErrorassert _safe_cwd(99999) is None@@ -225,9 +225,9 @@ def test_safe_cwd_returns_none_on_psutil_exception() -> None:def test_a_then_b_then_a_yields_distinct_then_resumed_contexts() -> None:- """Plan §8 Acceptance: Wechsel A→B→A liefert A's Episode-Snippet,- nicht B's. Hier nur Resolver-Side: A und B kriegen distinkte- project_roots, A re-resolved gibt das gleiche A wieder.+ """Plan §8 acceptance: switching A→B→A returns A's episode snippet,+ not B's. Here only the resolver side: A and B get distinct+ project_roots, A re-resolved gives back the same A."""with patch("jarvis.awareness.context._safe_cwd",side_effect=["C:\\a", "C:\\b", "C:\\a"]):@@ -238,6 +238,6 @@ def test_a_then_b_then_a_yields_distinct_then_resumed_contexts() -> None:assert a_first.project_root == "C:\\a"assert b.project_root == "C:\\b"assert a_again.project_root == "C:\\a"- # task_label aus dem zweiten A ist anders → Resolver bleibt deterministisch- # gegen Title-Aenderung.+ # task_label from the second A is different → the resolver stays deterministic+ # against a title change.assert a_again.task_label == "a.py - again"diff --git a/tests/unit/awareness/test_episode.py b/tests/unit/awareness/test_episode.pyindex 61a9538281..1b139bcc66 100644--- a/tests/unit/awareness/test_episode.py+++ b/tests/unit/awareness/test_episode.py@@ -1,6 +1,6 @@-"""Tests fuer jarvis.awareness.episode — Episode + EpisodeBuilder.+"""Tests for jarvis.awareness.episode — Episode + EpisodeBuilder.-Spec: Plan §6 + TASKS.md "Slice B".+Spec: plan §6 + TASKS.md "Slice B"."""from __future__ import annotations@@ -20,7 +20,7 @@ def _make_frame(pid: int = 1000,timestamp_ns: int = 1_000_000_000,) -> FrameSnapshot:- """Bequemer Constructor — sinnvolle Defaults."""+ """Convenient constructor — sensible defaults."""return FrameSnapshot(timestamp_ns=timestamp_ns,active_window_title=title,@@ -33,7 +33,7 @@ def _make_frame(# --- Episode (frozen) -------------------------------------------------------def test_episode_is_frozen() -> None:- """Episode ist frozen — kein Re-Assignment moeglich."""+ """Episode is frozen — no re-assignment possible."""ep = Episode(started_at_ns=1,ended_at_ns=2,@@ -47,7 +47,7 @@ def test_episode_is_frozen() -> None:def test_episode_has_slots() -> None:- """slots=True ⇒ kein __dict__."""+ """slots=True ⇒ no __dict__."""ep = Episode(started_at_ns=1,ended_at_ns=2,@@ -61,7 +61,7 @@ def test_episode_has_slots() -> None:def test_episode_token_defaults_zero() -> None:- """tokens_in / tokens_out default auf 0 (Empty-Episode oder Timeout)."""+ """tokens_in / tokens_out default to 0 (empty episode or timeout)."""ep = Episode(started_at_ns=1,ended_at_ns=2,@@ -77,7 +77,7 @@ def test_episode_token_defaults_zero() -> None:# --- EpisodeBuilder lifecycle ----------------------------------------------def test_builder_starts_empty() -> None:- """Frischer Builder hat keine Frames/Events."""+ """A fresh builder has no frames/events."""builder = EpisodeBuilder(started_at_ns=1)assert builder.frame_count == 0@@ -87,7 +87,7 @@ def test_builder_starts_empty() -> None:def test_add_frame_increments_count() -> None:- """add_frame() bumpt frame_count und ist im frames-Property sichtbar."""+ """add_frame() bumps frame_count and is visible in the frames property."""builder = EpisodeBuilder(started_at_ns=1)frame = _make_frame()@@ -99,7 +99,7 @@ def test_add_frame_increments_count() -> None:def test_add_event_makes_builder_non_empty() -> None:- """Auch ein Event allein reicht ⇒ is_empty=False."""+ """An event alone is enough ⇒ is_empty=False."""builder = EpisodeBuilder(started_at_ns=1)builder.add_event("FileSaved", salience=40, payload={"path": "foo.py"})@@ -115,17 +115,17 @@ def test_add_event_makes_builder_non_empty() -> None:def test_events_returns_independent_copy() -> None:- """builder.events liefert Kopie — Mutation darf den Builder nicht- beeinflussen."""+ """builder.events returns a copy — mutation must not affect the+ builder."""builder = EpisodeBuilder(started_at_ns=1)builder.add_event("FileSaved", salience=40, payload={"path": "x.py"})snap1 = builder.eventssnap1.clear() # mutate top-level listsnap1_again = builder.events- assert len(snap1_again) == 1 # Builder unbeeinflusst+ assert len(snap1_again) == 1 # builder unaffected- # Ist auch die Payload-Dict eine Kopie? (defensive)+ # Is the payload dict also a copy? (defensive)snap2 = builder.eventssnap2[0]["payload"]["new_key"] = "leaked"snap3 = builder.events@@ -133,25 +133,25 @@ def test_events_returns_independent_copy() -> None:def test_frames_returns_independent_copy() -> None:- """builder.frames liefert Kopie der Liste."""+ """builder.frames returns a copy of the list."""builder = EpisodeBuilder(started_at_ns=1)builder.add_frame(_make_frame(), salience=50)snap = builder.framessnap.clear()- assert builder.frame_count == 1 # Builder unbeeinflusst+ assert builder.frame_count == 1 # builder unaffected# --- primary_app -----------------------------------------------------------def test_primary_app_empty_builder() -> None:- """Leerer Builder ⇒ leerer String."""+ """Empty builder ⇒ empty string."""builder = EpisodeBuilder(started_at_ns=1)assert builder.primary_app == ""def test_primary_app_single_frame() -> None:- """Mit nur 1 Frame: dessen process_name (Dwell ist 0)."""+ """With only 1 frame: its process_name (dwell is 0)."""builder = EpisodeBuilder(started_at_ns=1)builder.add_frame(_make_frame(process="notepad.exe"), salience=50)@@ -159,26 +159,26 @@ def test_primary_app_single_frame() -> None:def test_primary_app_most_dwelltime() -> None:- """3 Frames: Notepad 5s → Code 30s → Notepad 10s ⇒ 'code.exe' gewinnt- (groesste kumulative Dwell-Zeit)."""+ """3 frames: Notepad 5s → Code 30s → Notepad 10s ⇒ 'code.exe' wins+ (largest cumulative dwell time)."""builder = EpisodeBuilder(started_at_ns=0)- # t=0: Notepad startet+ # t=0: Notepad startsbuilder.add_frame(_make_frame(process="notepad.exe", timestamp_ns=0), salience=30,)- # t=5s: Code startet ⇒ Notepad-Dwell = 5s+ # t=5s: Code starts ⇒ Notepad dwell = 5sbuilder.add_frame(_make_frame(process="code.exe", timestamp_ns=5_000_000_000), salience=50,)- # t=35s: Notepad startet wieder ⇒ Code-Dwell = 30s+ # t=35s: Notepad starts again ⇒ Code dwell = 30sbuilder.add_frame(_make_frame(process="notepad.exe", timestamp_ns=35_000_000_000), salience=50,)- # t=45s: letzter Frame (zaehlt 0 Beitrag) ⇒ Notepad-Dwell zusaetzlich 10s- # WAIT: laut Spec wird die Dwell zwischen aufeinanderfolgenden Frames- # berechnet, der letzte traegt 0 bei. Also Notepad insgesamt 5+10=15s,- # Code 30s ⇒ Code gewinnt.+ # t=45s: last frame (contributes 0) ⇒ Notepad dwell +10s additionally+ # WAIT: per spec, dwell is computed between consecutive frames,+ # the last one contributes 0. So Notepad totals 5+10=15s,+ # Code 30s ⇒ Code wins.builder.add_frame(_make_frame(process="notepad.exe", timestamp_ns=45_000_000_000), salience=30,)@@ -187,11 +187,11 @@ def test_primary_app_most_dwelltime() -> None:def test_primary_app_tie_first_wins() -> None:- """Bei Gleichstand gewinnt der zuerst eingefuegte Process- (Insertion-Order)."""+ """On a tie, the first-inserted process wins+ (insertion order)."""builder = EpisodeBuilder(started_at_ns=0)- # Notepad: 10s, Code: 10s ⇒ Tie ⇒ Notepad (zuerst eingefuegt) gewinnt.+ # Notepad: 10s, Code: 10s ⇒ tie ⇒ Notepad (inserted first) wins.builder.add_frame(_make_frame(process="notepad.exe", timestamp_ns=0), salience=30,)@@ -208,7 +208,7 @@ def test_primary_app_tie_first_wins() -> None:# --- build() ----------------------------------------------------------------def test_build_returns_immutable_episode() -> None:- """build() liefert frozen Episode — Mutation crashed."""+ """build() returns a frozen Episode — mutation crashes."""builder = EpisodeBuilder(started_at_ns=1_000)builder.add_frame(_make_frame(), salience=50)@@ -219,7 +219,7 @@ def test_build_returns_immutable_episode() -> None:def test_build_preserves_all_fields() -> None:- """Alle 8 Felder landen korrekt in der Episode."""+ """All 8 fields land correctly in the Episode."""builder = EpisodeBuilder(started_at_ns=100)builder.add_frame(_make_frame(process="code.exe", timestamp_ns=100), salience=50,@@ -230,25 +230,25 @@ def test_build_preserves_all_fields() -> None:episode = builder.build(ended_at_ns=999,- summary="Du hast in code.exe gearbeitet.",+ summary="You worked in code.exe.",tokens_in=123,tokens_out=45,)assert episode.started_at_ns == 100assert episode.ended_at_ns == 999- assert episode.summary == "Du hast in code.exe gearbeitet."+ assert episode.summary == "You worked in code.exe."assert episode.frame_count == 2assert episode.primary_app == "code.exe"assert episode.tokens_in == 123assert episode.tokens_out == 45- # trigger_kind wird vom Caller (StoryTracker) gesetzt — Builder kennt- # ihn nicht und liefert hier den Sentinel-Default leerer String.+ # trigger_kind is set by the caller (StoryTracker) — the builder doesn't+ # know it and returns the sentinel default empty string here.assert episode.trigger_kind == ""def test_build_token_defaults_zero() -> None:- """build() ohne tokens_* ⇒ 0 in der Episode (Empty/Timeout-Pfad)."""+ """build() without tokens_* ⇒ 0 in the Episode (empty/timeout path)."""builder = EpisodeBuilder(started_at_ns=1)episode = builder.build(ended_at_ns=2, summary="")assert episode.tokens_in == 0@@ -258,11 +258,11 @@ def test_build_token_defaults_zero() -> None:# --- duration_ns ------------------------------------------------------------def test_duration_ns_is_plausible() -> None:- """duration_ns = time.time_ns() - started_at_ns — positiv und plausibel."""- started = time.time_ns() - 5_000_000_000 # 5s in der Vergangenheit+ """duration_ns = time.time_ns() - started_at_ns — positive and plausible."""+ started = time.time_ns() - 5_000_000_000 # 5s in the pastbuilder = EpisodeBuilder(started_at_ns=started)duration = builder.duration_ns- # >= 5s, aber < 10s (Test laeuft schnell).+ # >= 5s, but < 10s (test runs fast).assert 5_000_000_000 <= duration < 10_000_000_000diff --git a/tests/unit/awareness/test_episode_persistence.py b/tests/unit/awareness/test_episode_persistence.pyindex 953cfa3fc6..d2b06981c4 100644--- a/tests/unit/awareness/test_episode_persistence.py+++ b/tests/unit/awareness/test_episode_persistence.py@@ -1,13 +1,13 @@-"""Unit-Tests fuer die Awareness-L2-Persistence (Phase A2 Slice A, Plan §6).+"""Unit tests for the awareness L2 persistence (phase A2 slice A, plan §6).-Deckt schema.sql-Idempotenz, FTS5-Trigger-Sync, Round-Trip-Konsistenz und-ORDER/LIMIT-Verhalten von `record_frame`, `record_episode`, `recent_episodes`-und `search_episodes` ab.+Covers schema.sql idempotency, FTS5 trigger sync, round-trip consistency, and+the ORDER/LIMIT behavior of `record_frame`, `record_episode`, `recent_episodes`+and `search_episodes`.-Plus: B2-Atomic-Buffer-Regression (Codex-BLOCKER B2-Fix, 2026-05-11).-Verifiziert end-to-end ueber den StoryTracker mit echter ``RecallStore``,-dass ein Frame der WAEHREND eines Flushs gepusht wird in der NAECHSTEN-Episode landet, nicht in der aktuellen und niemals verloren geht.+Plus: B2 atomic-buffer regression (Codex BLOCKER B2 fix, 2026-05-11).+Verifies end-to-end via the StoryTracker with a real ``RecallStore``,+that a frame pushed WHILE a flush is in progress lands in the NEXT+episode, not the current one, and is never lost."""from __future__ import annotations@@ -30,13 +30,13 @@ from jarvis.memory import RecallStore@pytest_asyncio.fixtureasync def tmp_db_path(tmp_path: Path) -> Path:- """Pro-Test isolierter DB-Pfad — vermeidet Cross-Test-Bleed."""+ """Per-test isolated DB path — avoids cross-test bleed."""return tmp_path / "awareness.db"@pytest_asyncio.fixtureasync def recall_store(tmp_db_path: Path):- """RecallStore async-Context-Manager als Fixture (open + close)."""+ """RecallStore async context manager as a fixture (open + close)."""store = RecallStore(tmp_db_path)await store.open()yield store@@ -44,11 +44,11 @@ async def recall_store(tmp_db_path: Path):async def test_schema_idempotent(tmp_db_path: Path) -> None:- """`open()` zweimal nacheinander darf nicht crashen — IF NOT EXISTS-Garantie.+ """Calling `open()` twice in a row must not crash — the IF NOT EXISTS guarantee.- Simuliert App-Restart: die DB existiert bereits mit allen Tabellen, ein- erneutes `executescript(schema.sql)` darf die bestehenden Daten und- Definitionen nicht stoeren.+ Simulates an app restart: the DB already exists with all tables, a+ repeated `executescript(schema.sql)` must not disturb the existing+ data and definitions."""store_a = RecallStore(tmp_db_path)await store_a.open()@@ -62,7 +62,7 @@ async def test_schema_idempotent(tmp_db_path: Path) -> None:)await store_a.close()- # Zweiter open() — keine Exception, Daten bleiben erhalten.+ # Second open() — no exception, data is preserved.store_b = RecallStore(tmp_db_path)await store_b.open()rows = await store_b.recent_episodes(limit=10)@@ -72,12 +72,12 @@ async def test_schema_idempotent(tmp_db_path: Path) -> None:async def test_record_episode_returns_id(recall_store: RecallStore) -> None:- """`record_episode` returnt eine positive Integer-rowid."""+ """`record_episode` returns a positive integer rowid."""episode_id = await recall_store.record_episode(started_at_ns=1_000_000_000,ended_at_ns=1_500_000_000,trigger_kind="window_switch",- summary="Du arbeitest an pipeline.py in VS Code.",+ summary="You are working on pipeline.py in VS Code.",frame_count=12,primary_app="Code.exe",)@@ -86,9 +86,9 @@ async def test_record_episode_returns_id(recall_store: RecallStore) -> None:async def test_recent_episodes_descending(recall_store: RecallStore) -> None:- """`recent_episodes(limit=2)` liefert die 2 juengsten in DESC-Reihenfolge."""+ """`recent_episodes(limit=2)` returns the 2 newest in DESC order."""base_ns = 1_000_000_000_000- # Drei Episodes mit aufsteigender Start-Zeit+ # Three episodes with ascending start timefor i in range(3):await recall_store.record_episode(started_at_ns=base_ns + i * 1_000_000_000,@@ -101,14 +101,14 @@ async def test_recent_episodes_descending(recall_store: RecallStore) -> None:rows = await recall_store.recent_episodes(limit=2)assert len(rows) == 2- # Neueste zuerst → Index 2, dann 1+ # Newest first → index 2, then 1assert rows[0]["summary"] == "episode-2"assert rows[1]["summary"] == "episode-1"assert rows[0]["started_at_ns"] > rows[1]["started_at_ns"]async def test_recent_episodes_since_ns_filter(recall_store: RecallStore) -> None:- """`since_ns=mid` filtert auf >=-Vergleich → nur 2 von 3 Episodes."""+ """`since_ns=mid` filters on a >= comparison → only 2 of 3 episodes."""base_ns = 1_000_000_000_000timestamps = [base_ns, base_ns + 1_000_000_000, base_ns + 2_000_000_000]for i, ts in enumerate(timestamps):@@ -121,7 +121,7 @@ async def test_recent_episodes_since_ns_filter(recall_store: RecallStore) -> Nonprimary_app="x.exe",)- # since=mittlerer Timestamp → ep-1 und ep-2 (>= mid)+ # since=middle timestamp → ep-1 and ep-2 (>= mid)rows = await recall_store.recent_episodes(limit=10, since_ns=timestamps[1])assert len(rows) == 2summaries = {r["summary"] for r in rows}@@ -129,12 +129,12 @@ async def test_recent_episodes_since_ns_filter(recall_store: RecallStore) -> Nonasync def test_search_episodes_fts_match(recall_store: RecallStore) -> None:- """FTS5-MATCH ueber Summary trifft nur die passende Episode."""+ """FTS5 MATCH over the summary hits only the matching episode."""await recall_store.record_episode(started_at_ns=1_000_000_000,ended_at_ns=1_500_000_000,trigger_kind="window_switch",- summary="Python coding session in VS Code mit Tests",+ summary="Python coding session in VS Code with tests",frame_count=20,primary_app="Code.exe",)@@ -142,7 +142,7 @@ async def test_search_episodes_fts_match(recall_store: RecallStore) -> None:started_at_ns=2_000_000_000,ended_at_ns=2_500_000_000,trigger_kind="idle_entered",- summary="Cooking dinner break, Browser auf Rezeptseite",+ summary="Cooking dinner break, browser on a recipe page",frame_count=8,primary_app="firefox.exe",)@@ -154,7 +154,7 @@ async def test_search_episodes_fts_match(recall_store: RecallStore) -> None:async def test_record_frame_persists(recall_store: RecallStore) -> None:- """`record_frame` schreibt den Row und die Daten lassen sich direkt lesen."""+ """`record_frame` writes the row and the data can be read back directly."""frame_id = await recall_store.record_frame(window_title="pipeline.py - Visual Studio Code",process_name="Code.exe",@@ -177,36 +177,36 @@ async def test_record_frame_persists(recall_store: RecallStore) -> None:assert row["process_name"] == "Code.exe"assert row["timestamp_ns"] == 1_234_567_890_000assert row["salience_score"] == 75- # metadata_json ist JSON-encoded+ # metadata_json is JSON-encodedimport jsonmeta = json.loads(row["metadata_json"])assert meta == {"git_branch": "awareness/phase-a2", "lines": 250}# -----------------------------------------------------------------------------# B2-Atomic-Buffer-Regression (Codex-BLOCKER, 2026-05-11)+# B2 atomic-buffer regression (Codex BLOCKER, 2026-05-11)# ----------------------------------------------------------------------------#-# Vorher (Bug): EpisodeBuilder akkumulierte Frames in einer gemeinsamen-# Liste; bei concurrent Flush + neuem FrameUpdated konnte ein Frame zwischen-# Snapshot und Buffer-Reset verloren gehen.-# Nachher (Fix): EpisodeBuilder.detach_frames/detach_events tauschen die-# internen Listen atomar mit fresh Buckets aus; StoryTracker._extract_snapshot_locked-# nutzt diese, dann setzt es _builder=None. Ein concurrent on_frame_updated-# bekommt den Lock erst nach dem Snapshot — und sieht builder=None, was zu-# einem frischen Builder fuer den naechsten Frame fuehrt.+# Before (bug): EpisodeBuilder accumulated frames in a shared+# list; with a concurrent flush + a new FrameUpdated, a frame could be lost+# between the snapshot and the buffer reset.+# After (fix): EpisodeBuilder.detach_frames/detach_events atomically swap the+# internal lists for fresh buckets; StoryTracker._extract_snapshot_locked+# uses these, then sets _builder=None. A concurrent on_frame_updated only+# gets the lock after the snapshot — and sees builder=None, which leads to+# a fresh builder for the next frame.#-# Test-Aufbau: StoryTracker + echte RecallStore + Slow-Verdichter, der-# 300ms blockt. Frame 1 vor Flush, Frame 2 WAEHREND des Verdichter-Sleeps.-# AC: Episode 1 enthaelt Frame 1, Frame 2 lebt in neuem Builder; nach-# stop() wird Episode 2 mit Frame 2 persistiert. Keine Frame verschwindet.+# Test setup: StoryTracker + a real RecallStore + a slow verdichter that+# blocks for 300ms. Frame 1 before the flush, frame 2 WHILE the verdichter+# sleeps. AC: episode 1 contains frame 1, frame 2 lives in the new builder;+# after stop(), episode 2 is persisted with frame 2. No frame disappears.@dataclassclass _SlowB2Verdichter:- """Verdichter-Fake fuer den B2-Test — schlaeft ``sleep_s`` waehrend- ``call`` und gibt eine eindeutige Summary zurueck, damit die- persistierten Episoden im Test-Assert eindeutig zuzuordnen sind.+ """Verdichter fake for the B2 test — sleeps for ``sleep_s`` during+ ``call`` and returns a unique summary so the persisted episodes can be+ unambiguously matched in the test assertions."""sleep_s: float = 0.3calls: list[dict[str, Any]] = field(default_factory=list)@@ -234,7 +234,7 @@ def _make_frame_for_b2(process: str = "Code.exe",ts_ns: int | None = None,) -> FrameSnapshot:- """Helper — minimaler FrameSnapshot fuer den B2-Test."""+ """Helper — minimal FrameSnapshot for the B2 test."""return FrameSnapshot(timestamp_ns=ts_ns if ts_ns is not None else time.time_ns(),active_window_title=title,@@ -247,20 +247,20 @@ def _make_frame_for_b2(async def test_frame_during_flush_lands_in_next_episode_buffer(tmp_db_path: Path,) -> None:- """B2-AC: Frame, der waehrend des Flushs eingereiht wird, landet im- NAECHSTEN Episode-Buffer — nicht verloren, nicht im aktuellen Snapshot.-- End-to-End mit echter ``RecallStore``. Verifiziert die volle- Persistence-Kette:- 1. Frame F1 (``frame-1.py``) oeffnet Builder.- 2. ``IdleEntered`` triggert Flush; Verdichter sleeps 300ms.- 3. WAEHREND der Verdichter sleeps wird F2 (``frame-2.py``) gepusht.- 4. Erwartet:- - Verdichter-Call sieht NUR F1 (1 frame).- - Live-Builder am Ende des Pushs enthaelt F2.- - Nach Verdichter-Completion: Episode 1 in DB mit summary ``summary-1``.- - Nach ``stop()``: Episode 2 in DB mit summary ``summary-2``.- - Keine Frame in beiden Episoden, keine verschwunden.+ """B2 AC: a frame enqueued WHILE the flush is running lands in the+ NEXT episode buffer — not lost, not in the current snapshot.++ End-to-end with a real ``RecallStore``. Verifies the full+ persistence chain:+ 1. Frame F1 (``frame-1.py``) opens the builder.+ 2. ``IdleEntered`` triggers a flush; the verdichter sleeps 300ms.+ 3. WHILE the verdichter sleeps, F2 (``frame-2.py``) is pushed.+ 4. Expected:+ - The verdichter call sees ONLY F1 (1 frame).+ - The live builder at the end of the push contains F2.+ - After verdichter completion: episode 1 in the DB with summary ``summary-1``.+ - After ``stop()``: episode 2 in the DB with summary ``summary-2``.+ - No frame is in both episodes, none disappears."""store = RecallStore(tmp_db_path)await store.open()@@ -278,7 +278,7 @@ async def test_frame_during_flush_lands_in_next_episode_buffer(await tracker.start()try:- # F1 vor Flush — opens builder.+ # F1 before the flush — opens the builder.f1 = _make_frame_for_b2(title="frame-1.py", ts_ns=time.time_ns())manager.state.current_frame = f1await tracker._on_frame_updated(FrameUpdated(@@ -288,7 +288,7 @@ async def test_frame_during_flush_lands_in_next_episode_buffer())await asyncio.sleep(1.1) # cross min_duration- # Idle triggert Flush in eigenem Task — Verdichter sleeps 300ms.+ # Idle triggers a flush in its own task — the verdichter sleeps 300ms.flush_task = asyncio.create_task(tracker._on_idle_entered(IdleEntered(idle_since_ns=time.time_ns()),))@@ -301,9 +301,9 @@ async def test_frame_during_flush_lands_in_next_episode_buffer("Pre-condition: verdichter must be mid-flight")- # F2 WAEHREND Verdichter sleeps. B2-Fix: muss in NEUEN Builder- # gehen, NICHT in den bereits gesnapshotteten Buffer und nicht- # verloren.+ # F2 WHILE the verdichter sleeps. B2 fix: must go into the NEW+ # builder, NOT into the already snapshotted buffer, and must+ # not be lost.f2 = _make_frame_for_b2(title="frame-2.py", ts_ns=time.time_ns())manager.state.current_frame = f2await tracker._on_frame_updated(FrameUpdated(@@ -312,11 +312,11 @@ async def test_frame_during_flush_lands_in_next_episode_buffer(pid=f2.active_pid, is_capture_allowed=True,))- # Verdichter sah nur F1.+ # The verdichter saw only F1.assert verdichter.calls[0]["frames_n"] == 1assert verdichter.calls[0]["titles"] == ["frame-1.py"]- # F2 lebt im neuen Builder.+ # F2 lives in the new builder.assert tracker._builder is not Nonelive_titles = [f.active_window_title for f in tracker._builder.frames@@ -326,19 +326,19 @@ async def test_frame_during_flush_lands_in_next_episode_buffer(f"has {live_titles!r}")- # Verdichter-Sleep abwarten, Episode 1 persistiert.+ # Wait out the verdichter sleep, episode 1 is persisted.await asyncio.wait_for(flush_task, timeout=2.0)finally:- # Force-flush des verbleibenden Builders via stop()-Trigger.+ # Force-flush the remaining builder via the stop() trigger.await tracker.stop()- # Zwei Episoden persistiert: Episode 1 (idle, F1), Episode 2 (stop, F2).+ # Two episodes persisted: episode 1 (idle, F1), episode 2 (stop, F2).rows = await store.recent_episodes(limit=10)assert len(rows) == 2, (- f"B2-AC: erwartet 2 persistierte Episoden, gefunden "- f"{len(rows)} — Frame F2 ging verloren?"+ f"B2 AC: expected 2 persisted episodes, found "+ f"{len(rows)} — did frame F2 get lost?")- # recent_episodes ist DESC nach started_at_ns → [F2-Episode, F1-Episode]+ # recent_episodes is DESC by started_at_ns → [F2 episode, F1 episode]assert rows[0]["summary"] == "summary-2"assert rows[0]["trigger_kind"] == "stop"assert rows[0]["frame_count"] == 1@@ -350,12 +350,12 @@ async def test_frame_during_flush_lands_in_next_episode_buffer(async def test_record_episode_round_trip(recall_store: RecallStore) -> None:- """Alle 8 Felder von `record_episode` landen 1:1 in `recent_episodes`."""+ """All 8 fields of `record_episode` land 1:1 in `recent_episodes`."""payload = {"started_at_ns": 5_000_000_000,"ended_at_ns": 5_900_000_000,"trigger_kind": "brain_turn",- "summary": "Round-trip-Test mit allen Feldern.",+ "summary": "Round-trip test with all fields.","frame_count": 17,"primary_app": "wezterm-gui.exe","tokens_in": 642,@@ -367,4 +367,4 @@ async def test_record_episode_round_trip(recall_store: RecallStore) -> None:assert len(rows) == 1row = rows[0]for key, expected in payload.items():- assert row[key] == expected, f"Feld {key} nicht erhalten: {row[key]!r} != {expected!r}"+ assert row[key] == expected, f"field {key} not preserved: {row[key]!r} != {expected!r}"diff --git a/tests/unit/awareness/test_filesystem_probe.py b/tests/unit/awareness/test_filesystem_probe.pyindex 976b153e76..44f8e9860c 100644--- a/tests/unit/awareness/test_filesystem_probe.py+++ b/tests/unit/awareness/test_filesystem_probe.py@@ -1,7 +1,7 @@-"""Phase A5 Slice B — FileSystemProbe Tests.+"""Phase A5 slice B — FileSystemProbe tests.-Mit echtem watchdog gegen tmp_path (Fakes statt Mocks). Real-FS-Events-mit kurzen Sleep-Window fuer Watchdog-Latency.+With a real watchdog against tmp_path (fakes instead of mocks). Real FS events+with a short sleep window for watchdog latency."""from __future__ import annotations@@ -21,12 +21,12 @@ from jarvis.core.events import FileSavedasync def _wait_for_event(events: list[FileSaved],n: int = 1,- timeout: float = 2.0, # noqa: ASYNC109 - intentional Polling-Window pro Test+ timeout: float = 2.0, # noqa: ASYNC109 - intentional per-test polling window) -> None:- """Pollt bis events.length >= n oder timeout.+ """Polls until events.length >= n or timeout.- ASYNC109: timeout-Parameter ist hier intentional — Test-Helper braucht- konfigurierbares Polling-Window pro Testfall, nicht asyncio.timeout-Cancel.+ ASYNC109: the timeout parameter is intentional here — the test helper needs+ a configurable polling window per test case, not asyncio.timeout cancellation."""deadline = time.monotonic() + timeoutwhile time.monotonic() < deadline:@@ -72,8 +72,8 @@ async def test_watch_then_save_emits_filesaved_event(tmp_path: Path) -> None:try:ok = p.watch(str(tmp_path))assert ok is True- # File-write triggert event- await asyncio.sleep(0.1) # watchdog-Init-Window+ # File write triggers an event+ await asyncio.sleep(0.1) # watchdog init window(tmp_path / "test.py").write_text("print('hello')")await _wait_for_event(received, n=1, timeout=3.0)assert len(received) >= 1@@ -96,12 +96,12 @@ async def test_debounce_collapses_rapid_saves(tmp_path: Path) -> None:p.watch(str(tmp_path))await asyncio.sleep(0.1)f = tmp_path / "rapid.py"- # 5 rapid writes innerhalb 100ms — debounce (200ms) sollte alle bis auf 1 droppen+ # 5 rapid writes within 100ms — debounce (200ms) should drop all but 1for _ in range(5):f.write_text("x")await asyncio.sleep(0.01)- await asyncio.sleep(0.5) # warten bis debounce-window abgelaufen- # Erwartung: max 2 events (1 fuer ersten save + evtl. 1 nach debounce-window)+ await asyncio.sleep(0.5) # wait for the debounce window to elapse+ # Expectation: max 2 events (1 for the first save + possibly 1 after the debounce window)rapid_events = [e for e in received if "rapid.py" in e.path]assert len(rapid_events) <= 2finally:@@ -125,7 +125,7 @@ async def test_blacklist_skips_git_directory(tmp_path: Path) -> None:(tmp_path / ".git" / "ignored.txt").write_text("x")(tmp_path / "real_file.py").write_text("real")await _wait_for_event(received, n=1, timeout=2.0)- # Nur real_file.py, NICHT ignored.txt+ # Only real_file.py, NOT ignored.txtpaths = [e.path for e in received]assert any("real_file.py" in p for p in paths)assert not any(".git" in p and "ignored.txt" in p for p in paths)@@ -150,7 +150,7 @@ async def test_unwatch_stops_events(tmp_path: Path) -> None:await asyncio.sleep(0.1)(tmp_path / "should_not_emit.py").write_text("x")await asyncio.sleep(0.5)- # Keine events fuer should_not_emit.py+ # No events for should_not_emit.pypaths = [e.path for e in received]assert not any("should_not_emit.py" in p for p in paths)finally:@@ -162,12 +162,12 @@ async def test_max_watched_roots_cap(tmp_path: Path) -> None:p = FileSystemProbe(bus=bus)await p.start()try:- # Erstelle MAX+1 directories und versuche alle zu watchen+ # Create MAX+1 directories and try to watch all of themfor i in range(_MAX_WATCHED_ROOTS):d = tmp_path / f"root_{i}"d.mkdir()assert p.watch(str(d)) is True- # Cap+1 muss False returnen+ # Cap+1 must return Falsed_extra = tmp_path / "root_extra"d_extra.mkdir()assert p.watch(str(d_extra)) is Falsediff --git a/tests/unit/awareness/test_git_probe.py b/tests/unit/awareness/test_git_probe.pyindex 70fb778612..8ad17d9396 100644--- a/tests/unit/awareness/test_git_probe.py+++ b/tests/unit/awareness/test_git_probe.py@@ -1,12 +1,12 @@-"""Phase A5 Slice A — GitProbe Tests.+"""Phase A5 slice A — GitProbe tests.-Konvention: Fakes statt Mocks (CLAUDE.md). Echtes ``git init`` im tmp-Path-fuer realistische Tests; Subprocess-Failure-Modes laufen ueber den-realen git-Binary, nicht ueber unittest.mock.+Convention: fakes instead of mocks (CLAUDE.md). A real ``git init`` in the+tmp path for realistic tests; subprocess failure modes run through the+real git binary, not unittest.mock.-Subprocess-Setup-Helpers (``_git``, ``_commit``) sind sync und werden-bewusst aus den async Tests aufgerufen — das ist Test-Fixture-Setup,-kein Runtime-IO. Daher ``# noqa: ASYNC221``.+The subprocess setup helpers (``_git``, ``_commit``) are sync and are+deliberately called from the async tests — this is test fixture setup,+not runtime IO. Hence ``# noqa: ASYNC221``."""from __future__ import annotations@@ -18,12 +18,12 @@ import pytestfrom jarvis.awareness.probes.git import GitProbe-# --- Sync subprocess-helpers (Test-Setup, kein Runtime-Code) ---+# --- Sync subprocess helpers (test setup, not runtime code) ---def _git(repo: Path, *args: str) -> subprocess.CompletedProcess[bytes]:"""Run ``git -C <repo> <args>`` synchronously for test setup."""- return subprocess.run( # noqa: ASYNC221 (sync test setup, kein async runtime)+ return subprocess.run( # noqa: ASYNC221 (sync test setup, not async runtime)["git", "-C", str(repo), *args],check=True,capture_output=True,@@ -31,7 +31,7 @@ def _git(repo: Path, *args: str) -> subprocess.CompletedProcess[bytes]:def _commit_init(repo: Path, filename: str = "init.txt") -> None:- """Erste Commit fuer einen frisch initialisierten Repo (damit Branches existieren)."""+ """First commit for a freshly initialized repo (so branches exist)."""(repo / filename).write_text("init")_git(repo, "add", ".")_git(@@ -42,12 +42,12 @@ def _commit_init(repo: Path, filename: str = "init.txt") -> None:)-# --- Fixture: realer git-init im tmp-Path ---+# --- Fixture: real git init in the tmp path ---@pytest.fixturedef git_repo(tmp_path: Path) -> Path:- """Erstellt echtes git-Repo via subprocess (sync, tmp-Setup)."""+ """Creates a real git repo via subprocess (sync, tmp setup)."""subprocess.run( # noqa: ASYNC221["git", "init", "--initial-branch=main", str(tmp_path)],check=True,@@ -78,7 +78,7 @@ async def test_probe_real_git_repo_returns_branch(git_repo: Path) -> None:async def test_probe_branch_after_checkout(git_repo: Path) -> None:- """Wechsle Branch und verifizere dass die Aenderung sichtbar ist."""+ """Switch branch and verify that the change is visible."""_commit_init(git_repo, "test.txt")_git(git_repo, "checkout", "-b", "feature/x")p = GitProbe()@@ -87,7 +87,7 @@ async def test_probe_branch_after_checkout(git_repo: Path) -> None:async def test_probe_detached_head_returns_sha_prefix(git_repo: Path) -> None:- """Detached HEAD: returnt 8-char SHA-prefix statt None."""+ """Detached HEAD: returns an 8-char SHA prefix instead of None."""_commit_init(git_repo, "x.txt")sha_result = subprocess.run( # noqa: ASYNC221["git", "-C", str(git_repo), "rev-parse", "HEAD"],@@ -99,7 +99,7 @@ async def test_probe_detached_head_returns_sha_prefix(git_repo: Path) -> None:_git(git_repo, "checkout", sha)p = GitProbe()result = await p.probe(cwd=str(git_repo))- # Erwartung: 8-char prefix, nicht None+ # Expectation: 8-char prefix, not Noneassert result["git_branch"] is not Noneassert len(result["git_branch"]) == 8assert sha.startswith(result["git_branch"])@@ -108,7 +108,7 @@ async def test_probe_detached_head_returns_sha_prefix(git_repo: Path) -> None:async def test_probe_worktree_repo_resolves_gitdir(git_repo: Path, tmp_path: Path) -> None:- """Worktree: ``.git`` ist file mit ``gitdir: ...``-Inhalt."""+ """Worktree: ``.git`` is a file with ``gitdir: ...`` content."""_commit_init(git_repo, "a.txt")wt_path = tmp_path / "worktree"_git(git_repo, "worktree", "add", str(wt_path), "-b", "wt-branch")@@ -119,26 +119,26 @@ async def test_probe_worktree_repo_resolves_gitdir(async def test_probe_invalid_cwd_returns_none() -> None:- """Nicht-existierender Pfad -> None, kein Crash."""+ """Nonexistent path -> None, no crash."""p = GitProbe()result = await p.probe(cwd="C:/Nonexistent/Path/Definitely/Not/Here_xyzz")assert result == {"git_branch": None}async def test_probe_handles_corrupted_head_file(git_repo: Path) -> None:- """``.git/HEAD`` mit Garbage -> None oder valider String, kein Crash."""+ """``.git/HEAD`` with garbage -> None or a valid string, no crash."""head_file = git_repo / ".git" / "HEAD"head_file.write_text("\x00\x01\x02 not a valid HEAD")p = GitProbe()result = await p.probe(cwd=str(git_repo))- # Sollte entweder via subprocess success returnen ODER None — beides OK,- # Hauptsache kein Crash+ # Should either return success via subprocess OR None — either is fine,+ # the main thing is no crashassert isinstance(result, dict)assert "git_branch" in resultasync def test_probe_completes_under_total_budget(git_repo: Path) -> None:- """Plan §9 AC: 200ms hard timeout pro Probe-Call."""+ """Plan §9 AC: 200ms hard timeout per probe call."""p = GitProbe()start = time.monotonic()await p.probe(cwd=str(git_repo))diff --git a/tests/unit/awareness/test_idle_detector.py b/tests/unit/awareness/test_idle_detector.pyindex c85372f803..06a507df5e 100644--- a/tests/unit/awareness/test_idle_detector.py+++ b/tests/unit/awareness/test_idle_detector.py@@ -1,14 +1,14 @@-"""Tests fuer jarvis.awareness.watchers.idle.IdleDetector.+"""Tests for jarvis.awareness.watchers.idle.IdleDetector.-Strategie: Mock von ``_get_idle_seconds`` plus direkter Aufruf von-``_tick_once()``. Damit laufen Tests <100ms ohne echten 5min-Wait und-ohne Win32 — pytest funktioniert auf jeder Plattform.+Strategy: mock ``_get_idle_seconds`` plus a direct call to+``_tick_once()``. This lets tests run <100ms without a real 5min wait and+without Win32 — pytest works on any platform.-Architektur-Annahmen die der Implementation in Welle 2 vorgeben:-- ``_tick_once()`` ist eine isolierbare Method (1 Tick = 1 GetLastInputInfo- + Transition-Check + Event-Publish). ``_run()`` ruft sie in Schleife- mit ``asyncio.sleep(1)`` zwischen Ticks.-- ``_get_idle_seconds()`` ist staticmethod — patchbar via+Architecture assumptions that the wave-2 implementation is bound to:+- ``_tick_once()`` is an isolable method (1 tick = 1 GetLastInputInfo+ + transition check + event publish). ``_run()`` calls it in a loop+ with ``asyncio.sleep(1)`` between ticks.+- ``_get_idle_seconds()`` is a staticmethod — patchable via``patch.object(IdleDetector, "_get_idle_seconds", ...)``."""from __future__ import annotations@@ -31,7 +31,7 @@ def _make_manager() -> AwarenessManager:def _async_collect(target: list):- """Test-Helper: gibt einen async Handler zurueck der Events an die Liste anhaengt."""+ """Test helper: returns an async handler that appends events to the list."""async def _handler(ev):target.append(ev)return _handler@@ -39,7 +39,7 @@ def _async_collect(target: list):@pytest.mark.asyncioasync def test_active_to_idle_transition_emits_event() -> None:- """Wenn _get_idle_seconds >= threshold: IdleEntered + state.is_idle=True."""+ """When _get_idle_seconds >= threshold: IdleEntered + state.is_idle=True."""bus = EventBus()received: list[IdleEntered] = []bus.subscribe(IdleEntered, _async_collect(received))@@ -57,7 +57,7 @@ async def test_active_to_idle_transition_emits_event() -> None:@pytest.mark.asyncioasync def test_idle_to_active_transition_emits_exited() -> None:- """Sobald _get_idle_seconds < threshold und vorher idle: IdleExited."""+ """As soon as _get_idle_seconds < threshold and it was idle before: IdleExited."""bus = EventBus()exited: list[IdleExited] = []bus.subscribe(IdleExited, _async_collect(exited))@@ -65,12 +65,12 @@ async def test_idle_to_active_transition_emits_exited() -> None:manager = _make_manager()detector = IdleDetector(manager=manager, bus=bus, threshold_s=5)- # Erst idle machen+ # First make it idlewith patch.object(IdleDetector, "_get_idle_seconds", staticmethod(lambda: 6.0)):await detector._tick_once()assert manager.state.is_idle is True- # Dann wieder aktiv+ # Then active againwith patch.object(IdleDetector, "_get_idle_seconds", staticmethod(lambda: 1.0)):await detector._tick_once()@@ -81,7 +81,7 @@ async def test_idle_to_active_transition_emits_exited() -> None:@pytest.mark.asyncioasync def test_idle_since_ns_propagates_into_current_frame() -> None:- """Wenn current_frame existiert: idle_since_ns wird via dataclasses.replace gesetzt."""+ """If current_frame exists: idle_since_ns is set via dataclasses.replace."""bus = EventBus()manager = _make_manager()manager.state.current_frame = FrameSnapshot(@@ -99,14 +99,14 @@ async def test_idle_since_ns_propagates_into_current_frame() -> None:cur = manager.state.current_frameassert cur is not Noneassert cur.idle_since_ns is not None- # Original-Felder bleiben — replace, nicht overwrite+ # Original fields remain — replace, not overwriteassert cur.active_window_title == "VS Code"assert cur.active_process_name == "code.exe"@pytest.mark.asyncioasync def test_no_event_when_below_threshold() -> None:- """Mehrere Ticks unter threshold → keine Events."""+ """Multiple ticks below threshold → no events."""bus = EventBus()received: list[IdleEntered] = []bus.subscribe(IdleEntered, _async_collect(received))@@ -123,7 +123,7 @@ async def test_no_event_when_below_threshold() -> None:@pytest.mark.asyncioasync def test_no_double_idle_event_within_same_idle_phase() -> None:- """Bleibt idle ueber mehrere Ticks → genau 1 IdleEntered."""+ """Stays idle over multiple ticks → exactly 1 IdleEntered."""bus = EventBus()received: list[IdleEntered] = []bus.subscribe(IdleEntered, _async_collect(received))@@ -139,7 +139,7 @@ async def test_no_double_idle_event_within_same_idle_phase() -> None:@pytest.mark.asyncioasync def test_start_idempotent() -> None:- """Doppelter start() ist no-op."""+ """A double start() is a no-op."""bus = EventBus()detector = IdleDetector(manager=_make_manager(), bus=bus, threshold_s=300)with patch.object(IdleDetector, "_get_idle_seconds", staticmethod(lambda: 0.0)):@@ -150,7 +150,7 @@ async def test_start_idempotent() -> None:@pytest.mark.asyncioasync def test_stop_idempotent_and_fast() -> None:- """stop() bricht in <1s ab. Doppelter stop() ist no-op."""+ """stop() completes in <1s. A double stop() is a no-op."""bus = EventBus()detector = IdleDetector(manager=_make_manager(), bus=bus, threshold_s=300)with patch.object(IdleDetector, "_get_idle_seconds", staticmethod(lambda: 0.0)):diff --git a/tests/unit/awareness/test_manager.py b/tests/unit/awareness/test_manager.pyindex 26cdd7e58a..23ada1819b 100644--- a/tests/unit/awareness/test_manager.py+++ b/tests/unit/awareness/test_manager.py@@ -1,4 +1,4 @@-"""Tests fuer jarvis.awareness.manager.AwarenessManager (extended in A1)."""+"""Tests for jarvis.awareness.manager.AwarenessManager (extended in A1)."""from __future__ import annotationsimport time@@ -12,7 +12,7 @@ from jarvis.core.bus import EventBus@pytest.mark.asyncioasync def test_a0_backward_compat_no_bus_no_crash() -> None:- """A0-Stub-Use: Manager ohne Bus laeuft fuer pure-Read-Use-Cases."""+ """A0 stub use: a manager without a bus works for pure read use cases."""cfg = AwarenessConfig.default()manager = AwarenessManager(cfg)assert manager.state is not None@@ -21,7 +21,7 @@ async def test_a0_backward_compat_no_bus_no_crash() -> None:@pytest.mark.asyncioasync def test_start_with_disabled_config_skips_watchers() -> None:- """enabled=False → start() ist no-op."""+ """enabled=False → start() is a no-op."""cfg = AwarenessConfig(enabled=False)bus = EventBus()manager = AwarenessManager(cfg, bus=bus)@@ -32,7 +32,7 @@ async def test_start_with_disabled_config_skips_watchers() -> None:@pytest.mark.asyncioasync def test_start_idempotent() -> None:- """Doppelter start() = no-op."""+ """A double start() = no-op."""cfg = AwarenessConfig(enabled=False)manager = AwarenessManager(cfg, bus=EventBus())await manager.start()@@ -42,7 +42,7 @@ async def test_start_idempotent() -> None:@pytest.mark.asyncioasync def test_stop_idempotent() -> None:- """Doppelter stop() = no-op."""+ """A double stop() = no-op."""cfg = AwarenessConfig(enabled=False)manager = AwarenessManager(cfg, bus=EventBus())await manager.start()@@ -52,7 +52,7 @@ async def test_stop_idempotent() -> None:@pytest.mark.asyncioasync def test_stop_completes_within_2s() -> None:- """Plan §5 + §10 Hard-Negative: stop() <2s."""+ """Plan §5 + §10 hard negative: stop() <2s."""cfg = AwarenessConfig(enabled=False)manager = AwarenessManager(cfg, bus=EventBus())await manager.start()@@ -65,7 +65,7 @@ async def test_stop_completes_within_2s() -> None:@pytest.mark.asyncioasync def test_state_property_returns_same_instance() -> None:- """manager.state ist stabile Instanz (kein neues Objekt pro Read)."""+ """manager.state is a stable instance (no new object per read)."""manager = AwarenessManager(AwarenessConfig.default())s1 = manager.states2 = manager.statediff --git a/tests/unit/awareness/test_privacy.py b/tests/unit/awareness/test_privacy.pyindex 3061cb6138..13b4d97397 100644--- a/tests/unit/awareness/test_privacy.py+++ b/tests/unit/awareness/test_privacy.py@@ -1,10 +1,10 @@-"""Tests fuer jarvis.awareness.privacy.PrivacyFilter.+"""Tests for jarvis.awareness.privacy.PrivacyFilter.-Plan §4 Smoke-Erwartungen + Hybrid-Default-Verhalten + User-Patterns-Additivitaet.+Plan §4 smoke expectations + hybrid default behavior + user-patterns additivity.-PrivacyFilter spiegelt jarvis.safety.risk_tier: SYSTEM-Patterns sind hart,-USER kann nur additiv blocken (nie System-Defaults entfernen). Reihenfolge:-BLOCK > ALLOW > Default-Hybrid (block-for-browsers).+PrivacyFilter mirrors jarvis.safety.risk_tier: SYSTEM patterns are hard,+USER can only block additively (never remove system defaults). Order:+BLOCK > ALLOW > default hybrid (block-for-browsers)."""from __future__ import annotations@@ -16,23 +16,23 @@ def _filter() -> PrivacyFilter:return PrivacyFilter(AwarenessConfig.default())-# --- Plan §4 Smoke-Test (verbindlich) --------------------------------------+# --- Plan §4 smoke test (binding) ------------------------------------------def test_blocks_banking_title() -> None:- """Plan-Smoke 1: Sparkasse-Online-Banking → BLOCKED, reason matcht."""+ """Plan smoke 1: Sparkasse-Online-Banking → BLOCKED, reason matches."""pf = _filter()allowed, reason = pf.is_allowed(- window_title="Sparkasse Online-Banking - Mozilla Firefox",+ window_title="Sparkasse Online-Banking - Mozilla Firefox", # i18n-allowprocess_name="firefox.exe",)assert allowed is Falseassert reason.startswith("matched_blocked_title:")- # Ein Banking-Pattern muss matchen — entweder *Banking* oder *Sparkasse* oder *Online-Banking*- assert any(p in reason for p in ("*Banking*", "*Sparkasse*", "*Online-Banking*"))+ # A banking pattern must match — either *Banking* or *Sparkasse* or *Online-Banking*+ assert any(p in reason for p in ("*Banking*", "*Sparkasse*", "*Online-Banking*")) # i18n-allowdef test_allows_vscode() -> None:- """Plan-Smoke 2: VS Code → ALLOWED, reason matcht."""+ """Plan smoke 2: VS Code → ALLOWED, reason matches."""pf = _filter()allowed, reason = pf.is_allowed(window_title="pipeline.py - jarvis - Visual Studio Code",@@ -42,10 +42,10 @@ def test_allows_vscode() -> None:assert reason == "matched_allowed_process:code.exe"-# --- Hybrid-Default (D-A1) -------------------------------------------------+# --- Hybrid default (D-A1) --------------------------------------------------def test_browser_without_explicit_block_still_blocked_via_hybrid() -> None:- """D-A1: Browser ohne Title-Match → BLOCKED (default block_for_browsers)."""+ """D-A1: a browser without a title match → BLOCKED (default block_for_browsers)."""pf = _filter()allowed, reason = pf.is_allowed(window_title="Wikipedia — The Free Encyclopedia",@@ -56,7 +56,7 @@ def test_browser_without_explicit_block_still_blocked_via_hybrid() -> None:def test_unknown_non_browser_allowed_via_hybrid() -> None:- """D-A1: Notepad o.ae. → ALLOWED (default allow_for_others)."""+ """D-A1: Notepad or similar → ALLOWED (default allow_for_others)."""pf = _filter()allowed, reason = pf.is_allowed(window_title="Untitled - Notepad",@@ -67,7 +67,7 @@ def test_unknown_non_browser_allowed_via_hybrid() -> None:def test_chrome_blocked_by_hybrid() -> None:- """Chrome zaehlt als Browser → Hybrid-Default blockt."""+ """Chrome counts as a browser → the hybrid default blocks it."""pf = _filter()allowed, _ = pf.is_allowed(window_title="GitHub - Mozilla Firefox",@@ -76,10 +76,10 @@ def test_chrome_blocked_by_hybrid() -> None:assert allowed is False-# --- BLOCK trumpft ALLOW + Reihenfolge -------------------------------------+# --- BLOCK trumps ALLOW + order ---------------------------------------------def test_blocked_process_trumps_allowed_process() -> None:- """1password-Title in code.exe → BLOCK gewinnt (process-blacklist greift)."""+ """1password title in code.exe → BLOCK wins (the process blacklist applies)."""pf = _filter()allowed, reason = pf.is_allowed(window_title="My Vault - 1Password",@@ -90,20 +90,20 @@ def test_blocked_process_trumps_allowed_process() -> None:def test_blocked_title_trumps_allowed_process() -> None:- """Banking-Title in code.exe (z.B. PDF-View) → Title-Blacklist gewinnt."""+ """Banking title in code.exe (e.g. a PDF view) → the title blacklist wins."""pf = _filter()allowed, reason = pf.is_allowed(- window_title="Sparkasse Statement.pdf - Code",+ window_title="Sparkasse Statement.pdf - Code", # i18n-allowprocess_name="code.exe",)assert allowed is Falseassert reason.startswith("matched_blocked_title:")-# --- User-Patterns sind additiv --------------------------------------------+# --- User patterns are additive ----------------------------------------------def test_user_patterns_can_add_blocks() -> None:- """User kann eigene blocked_processes ergaenzen — additiv zum System."""+ """The user can add their own blocked_processes — additive to the system."""cfg = AwarenessConfig.default()def user_patterns() -> tuple[list[str], list[str], list[str]]:@@ -120,31 +120,31 @@ def test_user_patterns_can_add_blocks() -> None:def test_user_patterns_cannot_remove_system_blocks() -> None:- """User-Patterns sind ADDITIV — leere User-Liste laesst System-Defaults- aktiv. 1password bleibt blockiert auch wenn User nichts hinzufuegt."""+ """User patterns are ADDITIVE — an empty user list leaves the system+ defaults active. 1password stays blocked even if the user adds nothing."""cfg = AwarenessConfig.default()def user_patterns() -> tuple[list[str], list[str], list[str]]:- return ([], [], []) # User loescht nichts; kann auch nicht+ return ([], [], []) # user deletes nothing; can't anywaypf = PrivacyFilter(cfg, user_patterns_fn=user_patterns)allowed, _ = pf.is_allowed(window_title="My Vault",process_name="1password.exe",)- assert allowed is False # System-Default 1password* greift weiterhin+ assert allowed is False # system default 1password* still appliesdef test_user_patterns_callback_errors_are_swallowed() -> None:- """Wenn user_patterns_fn raised: behandeln wie leere Liste, nicht crashen.- Spiegelt jarvis.safety.risk_tier._collect_patterns try/except."""+ """If user_patterns_fn raises: treat it like an empty list, don't crash.+ Mirrors jarvis.safety.risk_tier._collect_patterns try/except."""cfg = AwarenessConfig.default()def broken() -> tuple[list[str], list[str], list[str]]:raise RuntimeError("user-toml-broken")pf = PrivacyFilter(cfg, user_patterns_fn=broken)- # Crasht nicht; System-Defaults greifen normal+ # Doesn't crash; system defaults apply normallyallowed, _ = pf.is_allowed(window_title="Untitled - Notepad",process_name="notepad.exe",@@ -152,10 +152,10 @@ def test_user_patterns_callback_errors_are_swallowed() -> None:assert allowed is True-# --- reason-String-Format (Plan §4 Smoke-Spec) -----------------------------+# --- reason string format (plan §4 smoke spec) ------------------------------def test_reason_format_for_blocked_title() -> None:- """reason-Format: matched_blocked_title:<pattern>."""+ """reason format: matched_blocked_title:<pattern>."""pf = _filter()_, reason = pf.is_allowed(window_title="PayPal Login",@@ -165,7 +165,7 @@ def test_reason_format_for_blocked_title() -> None:def test_reason_format_for_allowed_process() -> None:- """reason-Format: matched_allowed_process:<pattern>."""+ """reason format: matched_allowed_process:<pattern>."""pf = _filter()_, reason = pf.is_allowed(window_title="Untitled-1 - Visual Studio Code",@@ -175,10 +175,10 @@ def test_reason_format_for_allowed_process() -> None:def test_case_insensitive_matching() -> None:- """Patterns matchen case-insensitive (wie risk_tier.py:105)."""+ """Patterns match case-insensitively (like risk_tier.py:105)."""pf = _filter()allowed, _ = pf.is_allowed(- window_title="Meine SPARKASSE Online-Banking Sitzung",+ window_title="Meine SPARKASSE Online-Banking Sitzung", # i18n-allowprocess_name="firefox.exe",)assert allowed is Falsediff --git a/tests/unit/awareness/test_quotas.py b/tests/unit/awareness/test_quotas.pyindex 31bb3f0c29..82ebcc6950 100644--- a/tests/unit/awareness/test_quotas.py+++ b/tests/unit/awareness/test_quotas.py@@ -1,7 +1,7 @@-"""Tests fuer jarvis.awareness.quotas.StorageQuota.+"""Tests for jarvis.awareness.quotas.StorageQuota.-A0-Scope: reine Datenklasse mit would_exceed-Verdict. A2 verwendet das-beim Episode-Persistieren als Pre-Insert-Check.+A0 scope: a pure dataclass with a would_exceed verdict. A2 uses it+during episode persistence as a pre-insert check."""from __future__ import annotations@@ -9,14 +9,14 @@ from jarvis.awareness.quotas import StorageQuotadef test_default_thresholds() -> None:- """Defaults: 50 MiB Bytes, 1000 Episoden."""+ """Defaults: 50 MiB bytes, 1000 episodes."""q = StorageQuota()assert q.max_bytes == 50 * 1024 * 1024assert q.max_episodes == 1000def test_would_exceed_below_caps() -> None:- """Beide Werte unter Cap → (False, '')."""+ """Both values under the cap → (False, '')."""q = StorageQuota()exceeded, reason = q.would_exceed(current_bytes=1024, current_episode_count=10)assert exceeded is False@@ -24,7 +24,7 @@ def test_would_exceed_below_caps() -> None:def test_would_exceed_at_byte_cap() -> None:- """current_bytes erreicht max_bytes → blockt."""+ """current_bytes reaches max_bytes → blocks."""q = StorageQuota(max_bytes=1000, max_episodes=100)exceeded, reason = q.would_exceed(current_bytes=1000, current_episode_count=0)assert exceeded is True@@ -32,7 +32,7 @@ def test_would_exceed_at_byte_cap() -> None:def test_would_exceed_at_episode_cap() -> None:- """current_episode_count erreicht max_episodes → blockt."""+ """current_episode_count reaches max_episodes → blocks."""q = StorageQuota(max_bytes=10**9, max_episodes=5)exceeded, reason = q.would_exceed(current_bytes=0, current_episode_count=5)assert exceeded is True@@ -40,7 +40,7 @@ def test_would_exceed_at_episode_cap() -> None:def test_would_exceed_byte_takes_priority_when_both_full() -> None:- """Wenn beide Caps voll: Bytes-Reason gewinnt (Disk-Risk > Count-Risk)."""+ """When both caps are full: the bytes reason wins (disk risk > count risk)."""q = StorageQuota(max_bytes=100, max_episodes=10)exceeded, reason = q.would_exceed(current_bytes=100, current_episode_count=10)assert exceeded is True@@ -48,7 +48,7 @@ def test_would_exceed_byte_takes_priority_when_both_full() -> None:def test_would_exceed_above_caps_still_blocks() -> None:- """Auch Werte ueber Cap (Race-Condition) → blockt."""+ """Values above the cap too (race condition) → blocks."""q = StorageQuota(max_bytes=100, max_episodes=10)exceeded, reason = q.would_exceed(current_bytes=200, current_episode_count=20)assert exceeded is True@@ -56,7 +56,7 @@ def test_would_exceed_above_caps_still_blocks() -> None:def test_storagequota_is_frozen() -> None:- """Quotas sind Konfig-Snapshots — frozen verhindert Mutation."""+ """Quotas are config snapshots — frozen prevents mutation."""import dataclassesimport pytestdiff --git a/tests/unit/awareness/test_salience.py b/tests/unit/awareness/test_salience.pyindex e6d06d30f6..92c01ad0b5 100644--- a/tests/unit/awareness/test_salience.py+++ b/tests/unit/awareness/test_salience.py@@ -1,7 +1,7 @@-"""Tests fuer jarvis.awareness.salience — SalienceScorer.+"""Tests for jarvis.awareness.salience — SalienceScorer.-Pure-Function-Tests, keine Bus / kein I/O. Spec: Plan §6-"Salience Scorer (verbindlich, rule-based)".+Pure function tests, no bus / no I/O. Spec: plan §6+"Salience Scorer (binding, rule-based)"."""from __future__ import annotations@@ -21,7 +21,7 @@ def _make_frame(timestamp_ns: int = 1_000_000_000,git_branch: str | None = None,) -> FrameSnapshot:- """Bequemer Constructor — alle Felder mit sinnvollen Defaults."""+ """Convenient constructor — all fields with sensible defaults."""return FrameSnapshot(timestamp_ns=timestamp_ns,active_window_title=title,@@ -32,21 +32,21 @@ def _make_frame()-# --- score_frame: prev=None ------------------------------------------------+# --- score_frame: prev=None --------------------------------------------------def test_score_frame_no_prev_returns_neutral() -> None:- """Erster Frame ohne prev → deterministisch ein Mid-Score-Default."""+ """First frame with no prev → deterministically a mid-score default."""scorer = SalienceScorer()frame = _make_frame()score = scorer.score_frame(frame, prev=None)- # Default Base = 50, kein BORING, kein Bonus → 50.+ # Default base = 50, no BORING, no bonus → 50.assert score == 50def test_score_frame_no_prev_boring_still_penalised() -> None:- """Auch ohne prev gewinnt die BORING-Penalty."""+ """Even without prev, the BORING penalty still applies."""scorer = SalienceScorer()frame = _make_frame(process="explorer.exe")@@ -56,23 +56,23 @@ def test_score_frame_no_prev_boring_still_penalised() -> None:assert score == 0-# --- score_frame: deltas ---------------------------------------------------+# --- score_frame: deltas ------------------------------------------------------def test_score_frame_process_switch_adds_20() -> None:- """Process-Wechsel ⇒ +20 (App-Switch)."""+ """Process switch ⇒ +20 (app switch)."""scorer = SalienceScorer()prev = _make_frame(process="notepad.exe", title="A.txt")frame = _make_frame(process="code.exe", title="B.py", timestamp_ns=2_000_000_000)score = scorer.score_frame(frame, prev=prev)- # Process changed = +20. Title ungleich, aber das wird nur gezaehlt- # wenn Process gleich bleibt — sonst Doppelzaehlung.+ # Process changed = +20. Title differs, but that's only counted+ # when the process stays the same — otherwise it's double-counted.assert score == 20def test_score_frame_title_switch_same_process_adds_30() -> None:- """Title-Wechsel bei gleichem Process ⇒ +30 (Datei-/Tab-Wechsel)."""+ """Title switch with the same process ⇒ +30 (file/tab switch)."""scorer = SalienceScorer()prev = _make_frame(process="code.exe", title="main.py - VS Code")frame = _make_frame(@@ -85,7 +85,7 @@ def test_score_frame_title_switch_same_process_adds_30() -> None:def test_score_frame_git_branch_change_adds_20() -> None:- """Git-Branch-Wechsel ⇒ +20 (beide non-None erforderlich)."""+ """Git branch switch ⇒ +20 (both non-None required)."""scorer = SalienceScorer()prev = _make_frame(git_branch="main")frame = _make_frame(@@ -94,12 +94,12 @@ def test_score_frame_git_branch_change_adds_20() -> None:score = scorer.score_frame(frame, prev=prev)- # Process+Title gleich ⇒ keine Boni dort, nur Branch +20.+ # Process+title same ⇒ no bonuses there, just branch +20.assert score == 20def test_score_frame_git_branch_one_none_no_bonus() -> None:- """git_branch nur in einem Frame gesetzt ⇒ kein Bonus."""+ """git_branch set in only one frame ⇒ no bonus."""scorer = SalienceScorer()prev = _make_frame(git_branch=None)frame = _make_frame(git_branch="main", timestamp_ns=2_000_000_000)@@ -110,35 +110,35 @@ def test_score_frame_git_branch_one_none_no_bonus() -> None:def test_score_frame_long_dwell_adds_10() -> None:- """Frame >2min nach prev ⇒ +10 (Verweildauer)."""+ """Frame >2min after prev ⇒ +10 (dwell time)."""scorer = SalienceScorer()prev = _make_frame(timestamp_ns=0)frame = _make_frame(timestamp_ns=121_000_000_000) # >2minscore = scorer.score_frame(frame, prev=prev)- # Process+Title gleich ⇒ nur Dwell-Bonus.+ # Process+title same ⇒ only the dwell bonus.assert score == 10def test_score_frame_short_dwell_no_bonus() -> None:- """Frame <=2min nach prev ⇒ kein Dwell-Bonus."""+ """Frame <=2min after prev ⇒ no dwell bonus."""scorer = SalienceScorer()prev = _make_frame(timestamp_ns=0)- frame = _make_frame(timestamp_ns=120_000_000_000) # exakt 2min+ frame = _make_frame(timestamp_ns=120_000_000_000) # exactly 2minscore = scorer.score_frame(frame, prev=prev)assert score == 0-# --- score_frame: BORING-Penalty ------------------------------------------+# --- score_frame: BORING penalty ---------------------------------------------def test_score_frame_boring_process_subtracts_50() -> None:- """Explorer.exe ⇒ -50 Penalty (zieht den Score nach unten)."""+ """Explorer.exe ⇒ -50 penalty (pulls the score down)."""scorer = SalienceScorer()prev = _make_frame(process="code.exe")- # Process-Switch ⇒ +20, dann -50 ⇒ -30 ⇒ clamped zu 0.+ # Process switch ⇒ +20, then -50 ⇒ -30 ⇒ clamped to 0.frame = _make_frame(process="explorer.exe", timestamp_ns=2_000_000_000)score = scorer.score_frame(frame, prev=prev)@@ -147,11 +147,11 @@ def test_score_frame_boring_process_subtracts_50() -> None:def test_score_frame_case_insensitive_boring() -> None:- """BORING_PROCESSES matchen case-insensitive."""+ """BORING_PROCESSES match case-insensitively."""scorer = SalienceScorer()prev = _make_frame(process="code.exe")- # Beide Variants muessen denselben Score erzeugen.+ # Both variants must produce the same score.frame_lower = _make_frame(process="explorer.exe", timestamp_ns=2_000_000_000)frame_upper = _make_frame(process="Explorer.exe", timestamp_ns=2_000_000_000)frame_mixed = _make_frame(process="ExPlOrEr.ExE", timestamp_ns=2_000_000_000)@@ -164,34 +164,34 @@ def test_score_frame_case_insensitive_boring() -> None:def test_score_frame_clamped_to_0_100() -> None:- """Extreme Combos respektieren die [0, 100]-Klammer."""+ """Extreme combos respect the [0, 100] clamp."""scorer = SalienceScorer()- # Alle Boni: process+20, branch+20, dwell+10 = +50 (max realistisch).- # Wir koennen score nicht > 100 forcen via score_frame — daher Test- # primaer fuer untere Grenze (BORING + No-Boni).+ # All bonuses: process+20, branch+20, dwell+10 = +50 (realistic max).+ # We can't force score > 100 via score_frame — so this test is+ # primarily for the lower bound (BORING + no bonuses).prev = _make_frame(process="code.exe", git_branch="main")frame = _make_frame(process="explorer.exe", # +20 process, -50 BORINGtitle="other",- git_branch="main", # gleich, kein Bonus+ git_branch="main", # same, no bonustimestamp_ns=2_000_000_000, # short dwell)score = scorer.score_frame(frame, prev=prev)- # Score muss in [0, 100] liegen, hier konkret 0 (clamped from -30).+ # Score must lie in [0, 100], here concretely 0 (clamped from -30).assert 0 <= score <= 100assert score == 0def test_score_frame_max_combo_not_above_100() -> None:- """Auch der Maximal-Boni-Stack bleibt <= 100."""+ """Even the max bonus stack stays <= 100."""scorer = SalienceScorer()prev = _make_frame(process="notepad.exe", title="A.txt", git_branch="main", timestamp_ns=0,)- # Process-Wechsel (+20), branch (+20), dwell >2min (+10), kein BORING.- # Title-Wechsel zaehlt nicht weil Process bereits wechselt.+ # Process switch (+20), branch (+20), dwell >2min (+10), no BORING.+ # Title switch doesn't count because the process already switched.frame = _make_frame(process="code.exe",title="main.py",@@ -205,7 +205,7 @@ def test_score_frame_max_combo_not_above_100() -> None:assert 0 <= score <= 100-# --- score_event ------------------------------------------------------------+# --- score_event ---------------------------------------------------------------def test_score_event_known_kinds() -> None:"""FileSaved=40, BrainTurnCompleted=50, IdleExited=20."""@@ -217,7 +217,7 @@ def test_score_event_known_kinds() -> None:def test_score_event_terminal_exit_with_payload() -> None:- """TerminalExit: exit_code=0 ⇒ 20, sonst ⇒ 60."""+ """TerminalExit: exit_code=0 ⇒ 20, otherwise ⇒ 60."""scorer = SalienceScorer()assert scorer.score_event("TerminalExit", {"exit_code": 0}) == 20@@ -226,7 +226,7 @@ def test_score_event_terminal_exit_with_payload() -> None:def test_score_event_terminal_exit_default_zero_exit_code() -> None:- """TerminalExit ohne payload ⇒ default exit_code=0 ⇒ 20."""+ """TerminalExit without a payload ⇒ default exit_code=0 ⇒ 20."""scorer = SalienceScorer()assert scorer.score_event("TerminalExit") == 20@@ -235,7 +235,7 @@ def test_score_event_terminal_exit_default_zero_exit_code() -> None:def test_score_event_unknown_default_zero() -> None:- """Unbekannter event_kind ⇒ 0."""+ """Unknown event_kind ⇒ 0."""scorer = SalienceScorer()assert scorer.score_event("WhateverElse") == 0@@ -243,15 +243,15 @@ def test_score_event_unknown_default_zero() -> None:assert scorer.score_event("RandomEventName", {"foo": "bar"}) == 0-# --- Module-level constants -------------------------------------------------+# --- Module-level constants ---------------------------------------------------def test_threshold_constant_value() -> None:- """SALIENCE_THRESHOLD ist 30 (Plan §6)."""+ """SALIENCE_THRESHOLD is 30 (plan §6)."""assert SALIENCE_THRESHOLD == 30def test_boring_processes_lowercase() -> None:- """Alle BORING_PROCESSES-Eintraege sind lowercase- (Caller .lower()-vergleicht — sonst silently no-match)."""+ """All BORING_PROCESSES entries are lowercase+ (the caller compares with .lower() — otherwise a silent no-match)."""for entry in BORING_PROCESSES:assert entry == entry.lower(), f"BORING entry not lowercase: {entry!r}"diff --git a/tests/unit/awareness/test_state.py b/tests/unit/awareness/test_state.pyindex ca4f8a6e1c..8175749197 100644--- a/tests/unit/awareness/test_state.py+++ b/tests/unit/awareness/test_state.py@@ -1,7 +1,7 @@-"""Tests fuer jarvis.awareness.state — FrameSnapshot + AwarenessState.+"""Tests for jarvis.awareness.state — FrameSnapshot + AwarenessState.-A0-Scope: Datenklassen + Default-Verhalten. snapshot_for_prompt() ist-A0-Placeholder (leerer String); echte Rendering-Logik kommt in A1.+A0 scope: data classes + default behavior. snapshot_for_prompt() is an+A0 placeholder (empty string); real rendering logic arrives in A1."""from __future__ import annotations@@ -28,7 +28,7 @@ def test_framesnapshot_is_frozen() -> None:def test_framesnapshot_has_slots() -> None:- """slots=True → kein __dict__, nur die deklarierten Felder."""+ """slots=True → no __dict__, only the declared fields."""snap = FrameSnapshot(timestamp_ns=1,active_window_title="x",@@ -41,7 +41,7 @@ def test_framesnapshot_has_slots() -> None:def test_framesnapshot_optional_fields_default_none() -> None:- """git_branch / open_file_hint / idle_since_ns sind in A0 immer None."""+ """git_branch / open_file_hint / idle_since_ns are always None in A0."""snap = FrameSnapshot(timestamp_ns=1,active_window_title="x",@@ -57,11 +57,11 @@ def test_framesnapshot_optional_fields_default_none() -> None:# --- AwarenessState --------------------------------------------------------def test_awarenessstate_default_init() -> None:- """AwarenessState() ohne Args ist valid und hat sinnvolle Defaults.+ """AwarenessState() with no args is valid and has sensible defaults.- A4-Refactor: ``working_set`` ist nicht mehr ``list``, sondern ein- optionaler ``WorkingSet | None``. Default = None — wird vom- AwarenessManager-Constructor gesetzt.+ A4 refactor: ``working_set`` is no longer a ``list`` but an+ optional ``WorkingSet | None``. Default = None — set by the+ AwarenessManager constructor."""state = AwarenessState()assert state.current_frame is None@@ -72,7 +72,7 @@ def test_awarenessstate_default_init() -> None:def test_awarenessstate_is_mutable() -> None:- """AwarenessState ist NICHT frozen — Watchers schreiben rein."""+ """AwarenessState is NOT frozen — watchers write into it."""state = AwarenessState()state.is_idle = Truestate.last_episode_summary = "hello"@@ -81,9 +81,9 @@ def test_awarenessstate_is_mutable() -> None:def test_awarenessstate_working_set_is_per_instance() -> None:- """A4: ``working_set`` ist eine WorkingSet-Reference vom Manager (nicht- shared default). Wir verifizieren dass zwei AwarenessState-Instanzen- voneinander unabhaengig sind, wenn jede ihren eigenen WorkingSet bekommt.+ """A4: ``working_set`` is a WorkingSet reference from the manager (not a+ shared default). We verify that two AwarenessState instances are+ independent of each other when each gets its own WorkingSet."""from jarvis.awareness.working_set import WorkingSet@@ -91,7 +91,7 @@ def test_awarenessstate_working_set_is_per_instance() -> None:b = AwarenessState()a.working_set = WorkingSet()b.working_set = WorkingSet()- # Mutation von a.working_set darf b nicht beeinflussen.+ # Mutating a.working_set must not affect b.from jarvis.awareness.context import Contexta.working_set.observe(Context(project_root="x", task_label=""))assert a.working_set.size == 1@@ -99,7 +99,7 @@ def test_awarenessstate_working_set_is_per_instance() -> None:def test_snapshot_for_prompt_a0_placeholder() -> None:- """A0: snapshot_for_prompt liefert leeren String. A1 ersetzt das."""+ """A0: snapshot_for_prompt returns an empty string. A1 replaces this."""state = AwarenessState()assert state.snapshot_for_prompt() == ""assert state.snapshot_for_prompt(max_chars=100) == ""diff --git a/tests/unit/awareness/test_story_tracker.py b/tests/unit/awareness/test_story_tracker.pyindex f5924c847b..07a5c7e8aa 100644--- a/tests/unit/awareness/test_story_tracker.py+++ b/tests/unit/awareness/test_story_tracker.py@@ -1,12 +1,12 @@"""Phase A2 — StoryTracker (jarvis/awareness/story.py).-Tests die Trigger-Logik (Salience-Filter, App-Switch, Idle, Hard-Timer,-Buffer-Overflow), den End-to-End-Pfad (Verdichter -> Recall -> State-Update--> Bus-Event) sowie alle §6 Hard-Negatives (PrivacyFilter-Block,-Min-Duration-Skip, Verdichter-Exception-Handling).+Tests the trigger logic (salience filter, app switch, idle, hard timer,+buffer overflow), the end-to-end path (Verdichter -> Recall -> state+update -> bus event), and all §6 hard negatives (PrivacyFilter block,+min-duration skip, Verdichter exception handling).-Konvention: Fakes statt Mocks (CLAUDE.md). FakeRecall + FakeVerdichter-implementieren genau die Methoden die der Tracker aufruft.+Convention: fakes instead of mocks (CLAUDE.md). FakeRecall + FakeVerdichter+implement exactly the methods the tracker calls."""from __future__ import annotations@@ -32,7 +32,7 @@ from jarvis.core.events import (@dataclassclass FakeRecall:- """Fake fuer RecallStore — sammelt record_episode-Calls."""+ """Fake for RecallStore — collects record_episode calls."""episodes: list[dict[str, Any]] = field(default_factory=list)next_id: int = 1raise_on_record: bool = False@@ -48,7 +48,7 @@ class FakeRecall:@dataclassclass FakeVerdichter:- """Fake fuer Verdichter — gibt deterministische Summary + Usage zurueck."""+ """Fake for Verdichter — returns a deterministic summary + usage."""summary: str = "Fake summary"tokens_in: int = 100tokens_out: int = 50@@ -131,10 +131,10 @@ async def test_start_subscribes_to_bus() -> None:tracker, _, bus, _, _ = _make_tracker()await tracker.start()try:- # Bus sollte jetzt subscriber fuer die 3 Event-Typen haben.- # Wir testen das indirekt: publish ein Event und pruefe ob handler- # called (via _on_response_generated → builder.add_event)- # Erst Builder oeffnen via Frame:+ # Bus should now have subscribers for the 3 event types.+ # We test this indirectly: publish an event and check whether the+ # handler was called (via _on_response_generated → builder.add_event)+ # First open the builder via a frame:frame = _make_frame()tracker._manager.state.current_frame = frameawait bus.publish(FrameUpdated(@@ -172,7 +172,7 @@ async def test_stop_idempotent() -> None:async def test_privacy_blocked_frame_not_buffered() -> None:- """Hard Negative §6: PrivacyFilter-blockierte Frames NIE in Verdichter-Input."""+ """Hard negative §6: PrivacyFilter-blocked frames NEVER enter Verdichter input."""tracker, manager, _, _, _ = _make_tracker()manager.state.current_frame = _make_frame(capture_allowed=False)ev = FrameUpdated(@@ -185,10 +185,10 @@ async def test_privacy_blocked_frame_not_buffered() -> None:async def test_low_salience_frame_dropped() -> None:- """Frames mit Score < SALIENCE_THRESHOLD landen NICHT im Builder."""+ """Frames with score < SALIENCE_THRESHOLD do NOT end up in the builder."""tracker, manager, _, _, _ = _make_tracker()- # Boring-Process (Explorer.exe) → -50 Penalty → unter Threshold.- boring = _make_frame(process="Explorer.exe", title="Datei-Explorer")+ # Boring process (Explorer.exe) → -50 penalty → below threshold.+ boring = _make_frame(process="Explorer.exe", title="File-Explorer")manager.state.current_frame = boringev = FrameUpdated(window_title=boring.active_window_title,@@ -197,14 +197,14 @@ async def test_low_salience_frame_dropped() -> None:is_capture_allowed=True,)await tracker._on_frame_updated(ev)- # _prev_frame wird trotzdem updated (fuer naechsten Vergleich)+ # _prev_frame is still updated (for the next comparison)assert tracker._prev_frame is not None- # ABER kein Builder geoeffnet+ # BUT no builder is openedassert tracker._builder is Noneasync def test_high_salience_frame_buffered() -> None:- """High-salience Frame oeffnet Builder + landet drin."""+ """High-salience frame opens the builder and ends up in it."""tracker, manager, _, _, _ = _make_tracker()frame = _make_frame()manager.state.current_frame = frame@@ -223,7 +223,7 @@ async def test_high_salience_frame_buffered() -> None:async def test_app_switch_after_min_duration_triggers_flush() -> None:- """Process-Wechsel + duration >= 60s → flush via Verdichter."""+ """Process switch + duration >= 60s → flush via Verdichter."""tracker, manager, _, recall, verdichter = _make_tracker(story_cfg=AwarenessStoryConfig(episode_min_duration_s=1),)@@ -245,15 +245,15 @@ async def test_app_switch_after_min_duration_triggers_flush() -> None:process_name=f2.active_process_name,pid=f2.active_pid, is_capture_allowed=True,))- # Verdichter MUSS gerufen worden sein+ # Verdichter MUST have been calledassert len(verdichter.calls) == 1- # Episode persistiert+ # Episode persistedassert len(recall.episodes) == 1assert recall.episodes[0]["trigger_kind"] == "window_switch"async def test_short_episode_skipped_on_app_switch() -> None:- """App-Switch + duration < min → kein Flush, builder reset."""+ """App switch + duration < min → no flush, builder reset."""tracker, manager, _, recall, verdichter = _make_tracker(story_cfg=AwarenessStoryConfig(episode_min_duration_s=60),)@@ -264,7 +264,7 @@ async def test_short_episode_skipped_on_app_switch() -> None:process_name=f1.active_process_name,pid=f1.active_pid, is_capture_allowed=True,))- # KEIN sleep — duration ~0s+ # NO sleep — duration ~0sf2 = _make_frame(process="Chrome.exe", title="other")manager.state.current_frame = f2await tracker._on_frame_updated(FrameUpdated(@@ -272,16 +272,16 @@ async def test_short_episode_skipped_on_app_switch() -> None:process_name=f2.active_process_name,pid=f2.active_pid, is_capture_allowed=True,))- # Verdichter NICHT gerufen, recall NICHT befuellt+ # Verdichter NOT called, recall NOT populatedassert verdichter.calls == []assert recall.episodes == []- # Builder wurde aber reset (nicht None weil neuer Frame eingefuegt)- # — wir testen: builder.frame_count ist 0 oder builder ist None+ # Builder was reset though (not None, since a new frame was inserted)+ # — we test: builder.frame_count is 0 or builder is Noneassert tracker._builder is None or tracker._builder.frame_count == 0async def test_idle_entered_flushes_long_episode() -> None:- """IdleEntered nach >= min_duration → flush."""+ """IdleEntered after >= min_duration → flush."""tracker, manager, _, recall, verdichter = _make_tracker(story_cfg=AwarenessStoryConfig(episode_min_duration_s=1),)@@ -299,7 +299,7 @@ async def test_idle_entered_flushes_long_episode() -> None:async def test_idle_entered_skips_short_episode() -> None:- """IdleEntered bei zu kurzer Episode → reset, kein Flush."""+ """IdleEntered on a too-short episode → reset, no flush."""tracker, manager, _, recall, verdichter = _make_tracker(story_cfg=AwarenessStoryConfig(episode_min_duration_s=60),)@@ -335,7 +335,7 @@ async def test_buffer_overflow_forces_flush() -> None:process_name=f.active_process_name,pid=f.active_pid, is_capture_allowed=True,))- # Buffer-overflow ab Frame 4 → flush mit trigger="buffer_overflow"+ # Buffer overflow from frame 4 onward → flush with trigger="buffer_overflow"assert len(verdichter.calls) >= 1assert any(ep["trigger_kind"] == "buffer_overflow" for ep in recall.episodes@@ -346,9 +346,9 @@ async def test_buffer_overflow_forces_flush() -> None:async def test_response_generated_adds_event_to_builder() -> None:- """ResponseGenerated → builder.add_event mit kind='BrainTurnCompleted'."""+ """ResponseGenerated → builder.add_event with kind='BrainTurnCompleted'."""tracker, manager, _, _, _ = _make_tracker()- # Erst Frame, damit Builder existiert+ # First a frame, so the builder existsf = _make_frame()manager.state.current_frame = fawait tracker._on_frame_updated(FrameUpdated(@@ -356,19 +356,19 @@ async def test_response_generated_adds_event_to_builder() -> None:process_name=f.active_process_name,pid=f.active_pid, is_capture_allowed=True,))- # Jetzt ResponseGenerated+ # Now ResponseGeneratedawait tracker._on_response_generated(- ResponseGenerated(text="Antwort vom Brain", language="de"),+ ResponseGenerated(text="Reply from the brain", language="de"),)assert tracker._builder is not Noneevents = tracker._builder.eventsassert len(events) == 1assert events[0]["kind"] == "BrainTurnCompleted"- assert events[0]["payload"]["text_len"] == len("Antwort vom Brain")+ assert events[0]["payload"]["text_len"] == len("Reply from the brain")async def test_response_generated_without_builder_is_noop() -> None:- """ResponseGenerated ohne offenen Builder → no-op (kein Crash)."""+ """ResponseGenerated without an open builder → no-op (no crash)."""tracker, *_ = _make_tracker()# Builder ist Noneawait tracker._on_response_generated(@@ -381,7 +381,7 @@ async def test_response_generated_without_builder_is_noop() -> None:async def test_flush_updates_state_last_episode_summary() -> None:- """Nach flush: manager.state.last_episode_summary + last_episode_id."""+ """After flush: manager.state.last_episode_summary + last_episode_id."""tracker, manager, _, recall, verdichter = _make_tracker(story_cfg=AwarenessStoryConfig(episode_min_duration_s=1),fake_verdichter=FakeVerdichter(summary="Test summary X"),@@ -400,7 +400,7 @@ async def test_flush_updates_state_last_episode_summary() -> None:async def test_flush_publishes_episode_recorded_event() -> None:- """Nach flush: bus.publish(EpisodeRecorded(...))."""+ """After flush: bus.publish(EpisodeRecorded(...))."""tracker, manager, bus, _, _ = _make_tracker(story_cfg=AwarenessStoryConfig(episode_min_duration_s=1),fake_verdichter=FakeVerdichter(summary="Hello world"),@@ -431,7 +431,7 @@ async def test_flush_publishes_episode_recorded_event() -> None:async def test_verdichter_exception_handled_gracefully() -> None:- """Verdichter wirft → empty summary, Episode trotzdem persistiert."""+ """Verdichter raises → empty summary, episode persisted anyway."""tracker, manager, _, recall, _ = _make_tracker(story_cfg=AwarenessStoryConfig(episode_min_duration_s=1),fake_verdichter=FakeVerdichter(raise_exc=RuntimeError("brain dead")),@@ -445,14 +445,14 @@ async def test_verdichter_exception_handled_gracefully() -> None:))await asyncio.sleep(1.1)await tracker._on_idle_entered(IdleEntered(idle_since_ns=time.time_ns()))- # Episode wurde persistiert MIT empty summary+ # Episode was persisted WITH empty summaryassert len(recall.episodes) == 1assert recall.episodes[0]["summary"] == ""assert recall.episodes[0]["tokens_in"] == 0async def test_recall_exception_drops_episode_no_crash() -> None:- """recall.record_episode wirft → episode lost, kein Crash, no state-update."""+ """recall.record_episode raises → episode lost, no crash, no state update."""tracker, manager, _, recall, _ = _make_tracker(story_cfg=AwarenessStoryConfig(episode_min_duration_s=1),fake_recall=FakeRecall(raise_on_record=True),@@ -466,13 +466,13 @@ async def test_recall_exception_drops_episode_no_crash() -> None:))await asyncio.sleep(1.1)await tracker._on_idle_entered(IdleEntered(idle_since_ns=time.time_ns()))- # State NICHT updated weil persist failed+ # State NOT updated because persist failedassert manager.state.last_episode_summary == ""assert recall.episodes == []async def test_stop_force_flushes_remaining_builder() -> None:- """stop() flush ungeachtet von duration (trigger='stop' zwingt flush)."""+ """stop() flushes regardless of duration (trigger='stop' forces a flush)."""tracker, manager, _, recall, verdichter = _make_tracker(story_cfg=AwarenessStoryConfig(episode_min_duration_s=999),)@@ -484,7 +484,7 @@ async def test_stop_force_flushes_remaining_builder() -> None:process_name=f.active_process_name,pid=f.active_pid, is_capture_allowed=True,))- # KEIN sleep — duration ~0s. Aber stop forciert flush.+ # NO sleep — duration ~0s. But stop() forces a flush.await tracker.stop()assert len(verdichter.calls) == 1assert recall.episodes[0]["trigger_kind"] == "stop"@@ -492,11 +492,11 @@ async def test_stop_force_flushes_remaining_builder() -> None:async def test_stale_state_blocked_frame_does_not_leak() -> None:- """M2-Fix: blocked Frame in state.current_frame darf NIE im Builder landen,- auch wenn das Event als allowed kam (Race-Window).+ """M2 fix: a blocked frame in state.current_frame must NEVER end up in+ the builder, even if the event arrived marked allowed (race window)."""tracker, manager, _, _, _ = _make_tracker()- # Setup: state hat blocked Frame, Event sagt aber allowed=True+ # Setup: state has a blocked frame, but the event says allowed=Trueblocked_frame = _make_frame(title="Banking", process="chrome.exe",capture_allowed=False,@@ -504,7 +504,7 @@ async def test_stale_state_blocked_frame_does_not_leak(manager.state.current_frame = blocked_frameev = FrameUpdated(window_title="something_else", process_name="Code.exe",- pid=1, is_capture_allowed=True, # Event sagt allowed+ pid=1, is_capture_allowed=True, # Event says allowed)await tracker._on_frame_updated(ev)# M2-Defense: re-check stops the leak@@ -512,14 +512,14 @@ async def test_stale_state_blocked_frame_does_not_leak(async def test_hard_timer_path_persists_episode_with_correct_trigger() -> None:- """AC-3 Trigger-Path: _maybe_flush(trigger_kind='hard_timer') persistiert- Episode mit trigger_kind='hard_timer'. Wir simulieren den Timer-Tick- direkt statt 5min real-time zu warten.+ """AC-3 trigger path: _maybe_flush(trigger_kind='hard_timer') persists+ the episode with trigger_kind='hard_timer'. We simulate the timer tick+ directly instead of waiting 5 real-time minutes."""tracker, manager, _, recall, _ = _make_tracker(story_cfg=AwarenessStoryConfig(episode_min_duration_s=1),)- base_ns = time.time_ns() - 2_000_000_000 # 2s in der Vergangenheit+ base_ns = time.time_ns() - 2_000_000_000 # 2s in the pastf = _make_frame(ts_ns=base_ns)manager.state.current_frame = fawait tracker._on_frame_updated(FrameUpdated(@@ -527,15 +527,15 @@ async def test_hard_timer_path_persists_episode_with_correct_trigger() -> None:process_name=f.active_process_name,pid=f.active_pid, is_capture_allowed=True,))- # B1-Refactor: _maybe_flush nimmt seinen Lock selbst — Caller darf- # NICHT mehr den Lock halten (sonst Deadlock auf asyncio.Lock).+ # B1 refactor: _maybe_flush acquires its own lock — the caller must+ # NOT hold the lock anymore (otherwise deadlock on asyncio.Lock).await tracker._maybe_flush(trigger_kind="hard_timer")assert recall.episodes[0]["trigger_kind"] == "hard_timer"async def test_hard_timer_loop_lifecycle_starts_and_cancels_cleanly() -> None:- """AC-3 Lifecycle: _hard_timer_loop laeuft im Background-Task und cancelt- sauber bei stop() — kein hanging Task, kein Resource-Leak.+ """AC-3 lifecycle: _hard_timer_loop runs as a background task and cancels+ cleanly on stop() — no hanging task, no resource leak."""tracker, *_ = _make_tracker()assert tracker._timer_task is None@@ -543,24 +543,24 @@ async def test_hard_timer_loop_lifecycle_starts_and_cancels_cleanly() -> None:assert tracker._timer_task is not Noneassert not tracker._timer_task.done()await tracker.stop()- assert tracker._timer_task is None # nach stop ist Task abgeraeumt+ assert tracker._timer_task is None # after stop the task is cleaned upasync def test_max_duration_triggers_flush() -> None:- """m4-Fix: Episode > episode_max_duration_min → forced flush.+ """m4 fix: episode > episode_max_duration_min → forced flush.- Single-Frame-Setup: ts_ns liegt 2min in der Vergangenheit, sodass die- Builder.duration_ns gleich beim ersten add_frame > max_duration_min*60s- ist. Damit haben wir genau 1 Verdichter-Call (deterministisch).+ Single-frame setup: ts_ns is 2min in the past, so Builder.duration_ns+ already exceeds max_duration_min*60s on the very first add_frame. This+ gives us exactly 1 Verdichter call (deterministic)."""tracker, manager, _, recall, verdichter = _make_tracker(story_cfg=AwarenessStoryConfig(- episode_min_duration_s=999, # min = high, sonst Flush via min- episode_max_duration_min=1, # max = 1min fuer Test+ episode_min_duration_s=999, # min = high, otherwise flush via min+ episode_max_duration_min=1, # max = 1min for the testbuffer_max=999, # buffer wide enough),)- base_ns = time.time_ns() - (2 * 60 * 1_000_000_000) # 2min in der Vergangenheit+ base_ns = time.time_ns() - (2 * 60 * 1_000_000_000) # 2min in the pastf = _make_frame(title="long_session.py", ts_ns=base_ns)manager.state.current_frame = fawait tracker._on_frame_updated(FrameUpdated(@@ -568,8 +568,8 @@ async def test_max_duration_triggers_flush() -> None:process_name=f.active_process_name,pid=f.active_pid, is_capture_allowed=True,))- # max_duration trigger feuert direkt nach add_frame —- # Builder.duration_ns ≈ 2min > 1min Hard-Cap.+ # max_duration trigger fires right after add_frame —+ # Builder.duration_ns ≈ 2min > 1min hard cap.assert len(verdichter.calls) == 1assert recall.episodes[0]["trigger_kind"] == "max_duration"@@ -579,11 +579,11 @@ async def test_max_duration_triggers_flush() -> None:@dataclassclass SlowVerdichter:- """Fake-Verdichter, der seinen Call ``sleep_s`` blockiert.+ """Fake Verdichter whose call blocks for ``sleep_s``.- Genutzt um die B1-Lock-Holding-Pattern zu reproduzieren — ohne den- B1-Fix wuerde der Lock 5s gehalten und parallele _on_frame_updated- serialisiert ausfuehren.+ Used to reproduce the B1 lock-holding pattern — without the B1 fix+ the lock would be held for 5s and parallel _on_frame_updated calls+ would execute serially."""sleep_s: float = 0.5summary: str = "slow summary"@@ -607,16 +607,16 @@ class SlowVerdichter:async def test_b1_lock_free_during_verdichter_call() -> None:- """B1-Regression (AC-strict): Mock-Verdichter blockt 5s, 50 parallele- Frame-Pushes — Throughput im Test < 100ms gesamt (nicht 5s seriell).-- Plan-AC (JARVIS_AWARENESS_PLAN §6 Folge-AC, Codex-BLOCKER B1):- - Verdichter sleep = 5.0s (harter AC-Wert aus dem Spike-Prompt).- - 50 parallele Pushes muessen in <0.1s (100ms) durch sein. Ohne den- B1-Fix wuerde Push #1 die ganzen 5s auf dem Lock warten; alle 50- seriell waeren ~ 5s * 50 = 250s.- - Mit B1-Fix wird der Lock VOR dem 5s sleep released — die 50 Pushes- laufen in <100ms durch.+ """B1 regression (AC-strict): mock Verdichter blocks for 5s, 50 parallel+ frame pushes — test throughput < 100ms total (not 5s serial).++ Plan AC (JARVIS_AWARENESS_PLAN §6 follow-up AC, Codex blocker B1):+ - Verdichter sleep = 5.0s (hard AC value from the spike prompt).+ - 50 parallel pushes must complete in <0.1s (100ms). Without the+ B1 fix, push #1 alone would wait the full 5s on the lock; all 50+ serially would take ~5s * 50 = 250s.+ - With the B1 fix the lock is released BEFORE the 5s sleep — the 50+ pushes complete in <100ms."""slow = SlowVerdichter(sleep_s=5.0)tracker, manager, _, _, _ = _make_tracker(@@ -661,8 +661,8 @@ async def test_b1_lock_free_during_verdichter_call() -> None:elapsed = time.monotonic() - start# AC-strict: 50 pushes in <100ms while verdichter still sleeps. Without- # the B1-fix Push #1 alone would wait 5s on the lock — alle 50 zusammen- # haetten 250s+ gedauert.+ # the B1 fix, push #1 alone would wait 5s on the lock — all 50 together+ # would have taken 250s+.assert elapsed < 0.1, (f"B1-Regression: {elapsed:.3f}s for 50 frame updates while verdichter "f"blocks 5s (AC: <0.1s — Lock is held over verdichter.call)"@@ -674,10 +674,10 @@ async def test_b1_lock_free_during_verdichter_call() -> None:async def test_b1_idle_handler_does_not_block_frame_handler() -> None:- """B1: idle-flush + frame-update interleaved → frame-update returnt sofort.+ """B1: idle-flush + frame-update interleaved → frame-update returns immediately.- Direkter Stress-Test: idle-handler haelt internen run_flush busy via- SlowVerdichter; ein paralleler frame-update darf nicht warten.+ Direct stress test: the idle handler keeps internal run_flush busy via+ SlowVerdichter; a parallel frame update must not wait."""slow = SlowVerdichter(sleep_s=0.4)tracker, manager, _, _, _ = _make_tracker(@@ -720,16 +720,16 @@ async def test_b1_idle_handler_does_not_block_frame_handler() -> None:async def test_b2_no_frame_loss_during_concurrent_flush() -> None:- """B2-Regression: Frame, der waehrend Flush gepusht wird, MUSS in- irgendeiner Episode landen (alte oder naechste) — niemals "lost".-- Setup: Frame 1 öffnet Builder, Idle triggert Flush (Verdichter blockt- 300ms). Während des Flush wird ein zweiter Frame gepusht. Wir- erwarten:- - Episode 1 enthaelt Frame 1 (frame_count == 1).- - Frame 2 startet Episode 2 (neuer Builder, da _builder=None nach- atomic detach im B1-Snapshot).- - Final-Flush via stop() persistiert Episode 2 mit Frame 2.+ """B2 regression: a frame pushed while a flush is in progress MUST end up+ in some episode (old or next) — never "lost".++ Setup: frame 1 opens the builder, idle triggers a flush (Verdichter+ blocks for 300ms). While the flush is in progress, a second frame is+ pushed. We expect:+ - Episode 1 contains frame 1 (frame_count == 1).+ - Frame 2 starts episode 2 (a new builder, since _builder=None after+ the atomic detach in the B1 snapshot).+ - The final flush via stop() persists episode 2 with frame 2."""slow = SlowVerdichter(sleep_s=0.3, summary="ep1")tracker, manager, _, recall, _ = _make_tracker(@@ -799,8 +799,8 @@ async def test_b2_no_frame_loss_during_concurrent_flush() -> None:async def test_b2_extract_snapshot_locked_resets_builder() -> None:- """B2: nach _extract_snapshot_locked ist der Builder None und alle- Frames/Events sind im Snapshot — kein Doppel-Bookkeeping.+ """B2: after _extract_snapshot_locked, the builder is None and all+ frames/events are in the snapshot — no double bookkeeping."""tracker, manager, _, _, _ = _make_tracker(story_cfg=AwarenessStoryConfig(episode_min_duration_s=1),diff --git a/tests/unit/awareness/test_system_prompt_injection.py b/tests/unit/awareness/test_system_prompt_injection.pyindex 5212ff777d..2fbb923ad1 100644--- a/tests/unit/awareness/test_system_prompt_injection.py+++ b/tests/unit/awareness/test_system_prompt_injection.py@@ -1,12 +1,12 @@-"""Phase A1 — System-Prompt-Injection des Awareness-Snapshots.+"""Phase A1 — system-prompt injection of the awareness snapshot.-Plan §5 'Files to Modify' verlangt, dass ``BrainManager._build_system_prompt``-einen kompakten Live-Snapshot aus ``AwarenessManager.state`` injiziert —-als Fallback fuer den Fall dass das LLM das ``awareness-snapshot``-Tool-NICHT ruft.+Plan §5 'Files to Modify' requires that ``BrainManager._build_system_prompt``+injects a compact live snapshot from ``AwarenessManager.state`` — as a+fallback for the case where the LLM does NOT call the+``awareness-snapshot`` tool.-AC-5 (Plan-Verifier): Hauptjarvis (Router) bekommt das Tool im Schema und-hat den State auch passiv im Prompt; Sub-Jarvis bekommt KEIN+AC-5 (plan verifier): the main Jarvis (router) gets the tool in its schema+and also has the state passively in the prompt; Sub-Jarvis gets NO``awareness_manager`` (stateless)."""from __future__ import annotations@@ -37,17 +37,17 @@ def _make_brain(awareness_manager: AwarenessManager | None) -> BrainManager:def test_no_awareness_manager_no_snapshot_in_prompt() -> None:- """Backward-Compat: ohne ``awareness_manager`` darf NICHTS injiziert werden."""+ """Backward compat: without ``awareness_manager``, NOTHING may be injected."""brain = _make_brain(awareness_manager=None)prompt = brain._build_system_prompt()assert "AKTUELLER KONTEXT" not in promptdef test_awareness_manager_with_empty_state_no_snapshot() -> None:- """``state.snapshot_for_prompt()`` returnt '' wenn ``current_frame is None``.+ """``state.snapshot_for_prompt()`` returns '' when ``current_frame is None``.- In dem Fall darf der Injection-Block KEIN leeres ``AKTUELLER KONTEXT:``-- Marker emittieren — der Prompt soll sauber bleiben.+ In that case the injection block must NOT emit an empty+ ``AKTUELLER KONTEXT:`` marker — the prompt should stay clean."""mgr = AwarenessManager(AwarenessConfig.default())assert mgr.state.current_frame is None@@ -57,7 +57,7 @@ def test_awareness_manager_with_empty_state_no_snapshot() -> None:def test_awareness_manager_with_frame_injects_snapshot() -> None:- """Ein gesetzter ``current_frame`` muss als ``AKTUELLER KONTEXT`` im Prompt landen."""+ """A set ``current_frame`` must land in the prompt as ``AKTUELLER KONTEXT``."""mgr = AwarenessManager(AwarenessConfig.default())mgr.state.current_frame = FrameSnapshot(timestamp_ns=time.time_ns(),@@ -77,8 +77,8 @@ def test_awareness_manager_with_frame_injects_snapshot() -> None:def test_snapshot_failure_does_not_break_prompt_build() -> None:- """Defensive try/except: ein kaputter ``snapshot_for_prompt`` darf den- System-Prompt-Build nicht kippen."""+ """Defensive try/except: a broken ``snapshot_for_prompt`` must not+ topple the system-prompt build."""mgr = AwarenessManager(AwarenessConfig.default())class _BadState:@@ -88,7 +88,7 @@ def test_snapshot_failure_does_not_break_prompt_build() -> None:mgr._state = _BadState() # type: ignore[assignment]brain = _make_brain(awareness_manager=mgr)- # Darf nicht raisen+ # Must not raiseprompt = brain._build_system_prompt()assert isinstance(prompt, str)assert len(prompt) > 0diff --git a/tests/unit/awareness/test_verdichter.py b/tests/unit/awareness/test_verdichter.pyindex b15f001049..b45c327035 100644--- a/tests/unit/awareness/test_verdichter.py+++ b/tests/unit/awareness/test_verdichter.py@@ -1,11 +1,11 @@-"""Tests fuer jarvis.awareness.verdichter.Verdichter.+"""Tests for jarvis.awareness.verdichter.Verdichter.Plan §6 AC:-- Verdichter-Call mit FakeBrain returnt deterministische Summary-- Timeout (5s) liefert empty summary + error_reason="timeout", crashed nicht-- Token-Cap: bei len(frames+events) > 30 werden 30 neueste genommen-- Empty input (frames=[], events=[]) -> skip mit error_reason="empty_input"-- Verdichter NIEMALS via spawn_worker-Mechanik (direct BrainProviderRegistry)+- Verdichter call with FakeBrain returns a deterministic summary+- Timeout (5s) yields an empty summary + error_reason="timeout", does not crash+- Token cap: for len(frames+events) > 30, the 30 newest are kept+- Empty input (frames=[], events=[]) -> skip with error_reason="empty_input"+- Verdichter NEVER goes through the spawn_worker mechanism (direct BrainProviderRegistry)"""from __future__ import annotations@@ -48,14 +48,14 @@ def _event(ts_ns: int, kind: str = "FileSaved", payload: dict | None = None) ->def _default_config(**overrides) -> AwarenessVerdichterConfig:- """AwarenessVerdichterConfig mit kurzem Timeout fuer Tests."""+ """AwarenessVerdichterConfig with a short timeout for tests."""base = {"enabled": True,"provider": "claude-api","model": "claude-haiku-4-5-20251001","max_input_tokens": 800,"max_output_tokens": 200,- "timeout_s": 1.0, # kurz fuer schnelle Tests+ "timeout_s": 1.0, # short, for fast tests}base.update(overrides)return AwarenessVerdichterConfig(**base)@@ -81,12 +81,12 @@ async def test_call_with_fake_brain_returns_summary() -> None:assert summary == "Du arbeitest seit 12min an pipeline.py in VS Code."assert usage["error_reason"] is None- assert usage["tokens_in"] == 0 # FakeBrain emittet keine usage+ assert usage["tokens_in"] == 0 # FakeBrain does not emit usageassert usage["tokens_out"] == 0assert usage["duration_ms"] >= 0- # FakeBrain wurde EINMAL aufgerufen (kein Sub-Jarvis-Spawn-Loop)+ # FakeBrain was called ONCE (no Sub-Jarvis spawn loop)assert len(brain.calls) == 1- # Verifiziere dass System-Prompt aus prompts.py uebergeben wurde+ # Verify that the system prompt from prompts.py was passed throughassert brain.calls[0].system == VERDICHTER_SYSTEM_PROMPT@@ -96,7 +96,7 @@ async def test_call_with_fake_brain_returns_summary() -> None:@pytest.mark.asyncioasync def test_call_with_empty_input_returns_empty_input_reason() -> None:- """frames=[] + events=[] -> ('', error_reason='empty_input'), kein Brain-Call."""+ """frames=[] + events=[] -> ('', error_reason='empty_input'), no brain call."""brain = FakeBrain(text_response="should not be called")cfg = _default_config()verdichter = Verdichter(brain=brain, config=cfg)@@ -110,7 +110,7 @@ async def test_call_with_empty_input_returns_empty_input_reason() -> None:assert usage["tokens_in"] == 0assert usage["tokens_out"] == 0assert usage["duration_ms"] == 0- # KEIN Brain-Call bei Empty-Input+ # NO brain call on empty inputassert len(brain.calls) == 0@@ -119,7 +119,7 @@ async def test_call_with_empty_input_returns_empty_input_reason() -> None:# ----------------------------------------------------------------------class _SlowBrain:- """Brain das absichtlich laenger schlaeft als der Timeout."""+ """Brain that deliberately sleeps longer than the timeout."""name: str = "slow-brain"context_window: int = 8192@@ -166,7 +166,7 @@ async def test_call_with_timeout_returns_timeout_reason() -> None:# ----------------------------------------------------------------------class _SpyBrain:- """Brain das den uebergebenen Prompt fuer Inspection speichert."""+ """Brain that stores the passed-in prompt for inspection."""name: str = "spy-brain"context_window: int = 8192@@ -179,7 +179,7 @@ class _SpyBrain:async def complete(self, req: BrainRequest) -> AsyncIterator[BrainDelta]:self.calls.append(req)- # Letzte Message (User-Prompt) speichern+ # Store the last message (user prompt)for msg in req.messages:if msg.role == "user" and isinstance(msg.content, str):self.last_prompt = msg.content@@ -193,12 +193,12 @@ class _SpyBrain:async def test_call_caps_to_30_frames_plus_events() -> None:"""50 Frames + 0 Events -> nur 30 Frames im finalen Prompt.- Strategy: NEUESTE 30 (chronological tail). Die aeltesten 20 Frames- werden gedroppt — das verifizieren wir indem wir die "alte" und- "neue" Marker im Prompt suchen.+ Strategy: NEWEST 30 (chronological tail). The oldest 20 frames are+ dropped — we verify this by looking for the "old" and "new" markers+ in the prompt."""brain = _SpyBrain()- cfg = _default_config(max_input_tokens=10_000) # gross genug, kein Trunc+ cfg = _default_config(max_input_tokens=10_000) # large enough, no truncationverdichter = Verdichter(brain=brain, config=cfg)base_ts = 1_700_000_000_000_000_000@@ -215,12 +215,12 @@ async def test_call_caps_to_30_frames_plus_events() -> None:assert summary == "ok"# Cap: max 30 Frames+Events. 50 Frames -> 30 neueste.assert MAX_FRAMES_PLUS_EVENTS == 30- # Pruefen: die alten Frames file_00..file_19 fehlen, file_20..file_49 sind drin.+ # Check: the old frames file_00..file_19 are missing, file_20..file_49 are present.prompt = brain.last_prompt- assert "file_49.py" in prompt, "Neuester Frame muss im Prompt sein"- assert "file_20.py" in prompt, "Erster nicht-getrimmter Frame muss da sein"- assert "file_19.py" not in prompt, "file_19 sollte gedroppt sein (zu alt)"- assert "file_00.py" not in prompt, "file_00 sollte gedroppt sein (aeltester)"+ assert "file_49.py" in prompt, "Newest frame must be in the prompt"+ assert "file_20.py" in prompt, "First non-trimmed frame must be present"+ assert "file_19.py" not in prompt, "file_19 should have been dropped (too old)"+ assert "file_00.py" not in prompt, "file_00 should have been dropped (oldest)"# Genau 30 Frame-Zeilenframe_lines = re.findall(r"^- \[\d\d:\d\d:\d\d\] Code\.exe: file_\d\d\.py$",prompt, flags=re.MULTILINE)@@ -288,7 +288,7 @@ def test_build_verdichter_prompt_truncation() -> None:prompt = build_verdichter_prompt(frames=frames, events=[], primary_app="Code.exe",- max_chars=500, # zu klein fuer alles+ max_chars=500, # too small for everything)assert "[...]" in prompt, f"Truncation-Marker fehlt im Prompt:\n{prompt!r}"@@ -302,12 +302,12 @@ def test_build_verdichter_prompt_truncation() -> None:# ----------------------------------------------------------------------def _strip_string_literals_and_comments(src: str) -> str:- """Entfernt Python-Docstrings/String-Literals und Kommentare aus src.+ """Strips Python docstrings/string literals and comments out of src.- Tokenize-basiert. Wird im NEVER-spawn-Test genutzt, damit Hard-Negative-- Erwaehnungen in Docstrings (z.B. "NIEMALS spawn_worker") nicht- falsch positiv triggern. Wir wollen nur tatsaechliche Code-References- (Imports, Function-Calls, Identifier).+ Tokenize-based. Used in the NEVER-spawn test so that hard-negative+ mentions in docstrings (e.g. "NEVER spawn_worker") don't false-positive+ trigger. We only want actual code references (imports, function+ calls, identifiers)."""import ioimport token as _token_mod@@ -327,65 +327,65 @@ def _strip_string_literals_and_comments(src: str) -> str:def test_verdichter_NEVER_calls_spawn_worker() -> None:- """Hard Negative §6: Verdichter darf NICHT via spawn_worker laufen.-- Welle-4-Migration: vorher hiess das Tool ``spawn_sub_jarvis``. Die- Regression-Guards bleiben fuer beide Namen aktiv, um zu verhindern dass- je wieder eine Spawn-Abhaengigkeit eingeschleust wird.-- Pruefung 1 (Code, nicht Docstrings): Source-Code von Verdichter +- prompts.py enthaelt KEINE Code-Reference auf spawn_worker /- spawn_sub_jarvis / SubJarvisManager / jarvis.sub_jarvis. Docstring-- Erwaehnungen sind erlaubt — wir strippen Strings + Kommentare via- tokenize bevor wir matchen.- Pruefung 2: Verdichter.__init__ akzeptiert ``brain`` + ``config``- direkt — kein Hidden-Manager-Wiring.+ """Hard negative §6: Verdichter must NOT run via spawn_worker.++ Welle-4 migration: the tool used to be called ``spawn_sub_jarvis``. The+ regression guards stay active for both names, to prevent a spawn+ dependency from ever being reintroduced.++ Check 1 (code, not docstrings): the source code of Verdichter ++ prompts.py contains NO code reference to spawn_worker /+ spawn_sub_jarvis / SubJarvisManager / jarvis.sub_jarvis. Docstring+ mentions are allowed — we strip strings + comments via tokenize+ before matching.+ Check 2: Verdichter.__init__ accepts ``brain`` + ``config``+ directly — no hidden manager wiring."""- # Pruefung 1: Source des Moduls (Code-Only, keine Docstrings)+ # Check 1: source of the module (code-only, no docstrings)import jarvis.awareness.verdichter as v_modsrc_code = _strip_string_literals_and_comments(inspect.getsource(v_mod))assert "spawn_worker" not in src_code, (- "Verdichter-CODE darf spawn_worker nicht referenzieren "- "(Docstring-Erwaehnungen waeren OK)"+ "Verdichter CODE must not reference spawn_worker "+ "(docstring mentions would be OK)")assert "SubJarvisManager" not in src_code, (- "Verdichter-CODE darf SubJarvisManager nicht importieren/instanziieren"+ "Verdichter CODE must not import/instantiate SubJarvisManager")assert "jarvis.sub_jarvis" not in src_code, (- "Verdichter-CODE darf jarvis.sub_jarvis nicht importieren"+ "Verdichter CODE must not import jarvis.sub_jarvis")- # Pruefung 2: prompts.py auch sauber (Code-Only)+ # Check 2: prompts.py is also clean (code-only)import jarvis.awareness.prompts as p_modp_code = _strip_string_literals_and_comments(inspect.getsource(p_mod))assert "spawn_worker" not in p_codeassert "jarvis.sub_jarvis" not in p_codeassert "SubJarvisManager" not in p_code- # Pruefung 3: Verdichter-Klasse haengt direkt am Brain-Protocol, nicht- # an einem Manager. inspect.signature(__init__) muss "brain" haben.+ # Check 3: the Verdichter class hangs directly off the Brain protocol,+ # not off a manager. inspect.signature(__init__) must have "brain".sig = inspect.signature(Verdichter.__init__)- assert "brain" in sig.parameters, "Verdichter.__init__ muss brain= akzeptieren"- assert "config" in sig.parameters, "Verdichter.__init__ muss config= akzeptieren"+ assert "brain" in sig.parameters, "Verdichter.__init__ must accept brain="+ assert "config" in sig.parameters, "Verdichter.__init__ must accept config="assert "manager" not in sig.parameters, (- "Verdichter.__init__ darf KEINEN manager= haben (sonst Sub-Jarvis-Wiring)"+ "Verdichter.__init__ must NOT have a manager= (otherwise Sub-Jarvis wiring)")- # Pruefung 4: Source-File existiert und ist im awareness-Modul+ # Check 4: source file exists and lives in the awareness modulesrc_file = Path(inspect.getfile(v_mod))assert src_file.exists()assert src_file.parent.name == "awareness", (- f"verdichter.py muss in jarvis/awareness/ liegen, ist in {src_file.parent}"+ f"verdichter.py must live in jarvis/awareness/, is in {src_file.parent}")@pytest.mark.asyncioasync def test_verdichter_brain_call_uses_brain_complete_directly() -> None:- """Behavior-Check: Verdichter.call() ruft brain.complete() EINMAL.+ """Behavior check: Verdichter.call() calls brain.complete() ONCE.- Sub-Jarvis-Spawn wuerde mehrere Brain-Calls + Tool-Use-Loop ausloesen.- Ein einzelner brain.complete()-Call ist der Beweis dass es ein direkter- Brain-Call ist (Hard Negative §6).+ A Sub-Jarvis spawn would trigger multiple brain calls + a tool-use loop.+ A single brain.complete() call is the proof that this is a direct+ brain call (hard negative §6)."""brain = FakeBrain(text_response="ok")cfg = _default_config()@@ -397,29 +397,30 @@ async def test_verdichter_brain_call_uses_brain_complete_directly() -> None:frames=frames, events=[], primary_app="Code.exe",)- # GENAU EIN Brain-Call (kein Tool-Use-Loop, kein Spawn-Loop)+ # EXACTLY ONE brain call (no tool-use loop, no spawn loop)assert len(brain.calls) == 1, (- f"Verdichter darf nur 1 Brain-Call machen, gefunden {len(brain.calls)}. "- "Mehr Calls = Tool-Use-Loop = vermutlich Sub-Jarvis-Spawn."+ f"Verdichter must make only 1 brain call, found {len(brain.calls)}. "+ "More calls = tool-use loop = probably a Sub-Jarvis spawn.")- # Request hat KEINE Tools (Sub-Jarvis-Spawn waere ein Tool)+ # Request has NO tools (a Sub-Jarvis spawn would be a tool)assert brain.calls[0].tools == (), (- "Verdichter-BrainRequest darf KEINE Tools haben (sonst Tool-Use-Loop)"+ "Verdichter BrainRequest must NOT have tools (otherwise tool-use loop)")assert summary == "ok"async def test_verdichter_latency_p95_under_2s() -> None:- """Plan §6 AC: Verdichter-Call p95 < 2s.+ """Plan §6 AC: Verdichter call p95 < 2s.- 100 Calls mit FakeBrain (deterministische Response, kein Network).- Verifiziert dass die Verdichter-Implementation selbst (Prompt-Build,- Stream-Aggregate, asyncio-Overhead) keinen Pfad-Latency > 2s einfuehrt.+ 100 calls with FakeBrain (deterministic response, no network).+ Verifies that the Verdichter implementation itself (prompt build,+ stream aggregate, asyncio overhead) does not introduce a path latency+ > 2s.- Echte Latency-Regression gegen Anthropic-API ist out-of-scope (braucht- API-Key, ist netzwerkabhaengig). Dieser Test schuetzt vor Verdichter-- Implementations-Regressions (z.B. unbeschraenkte Schleife im Prompt-- Builder, blocking I/O das den asyncio-Loop staut).+ Real latency regression against the Anthropic API is out of scope+ (needs an API key, is network-dependent). This test guards against+ Verdichter implementation regressions (e.g. an unbounded loop in the+ prompt builder, blocking I/O that stalls the asyncio loop)."""import time as _timediff --git a/tests/unit/awareness/test_window_watcher.py b/tests/unit/awareness/test_window_watcher.pyindex d025b4e06f..5e68f35ec4 100644--- a/tests/unit/awareness/test_window_watcher.py+++ b/tests/unit/awareness/test_window_watcher.py@@ -1,15 +1,15 @@-"""Tests fuer jarvis.awareness.watchers.window.WindowFocusWatcher.--Strategie: Fake-Pump (kein echter Win32-Hook) plus injiziertes-``_resolve_window_meta`` plus direkter Aufruf von ``_drain_once()``. Damit-laufen Tests auf jeder Plattform; echte Hook-Lifecycle ist im Integration--Test ``test_a1_e2e.py``.--Architektur-Annahmen die der Implementation in Welle 3 vorgeben:-- ``_drain_once()`` ist isolierbar (eine Iteration der Drain-Loop).-- ``_safe_enqueue((ts_ns, hwnd))`` schiebt Items in die Queue (asyncio-thread-safe).-- ``_resolve_window_meta(hwnd)`` ist staticmethod — patchbar.-- ``_loop`` ist Property die in Tests vor _safe_enqueue gesetzt wird.+"""Tests for jarvis.awareness.watchers.window.WindowFocusWatcher.++Strategy: fake pump (no real Win32 hook) plus an injected+``_resolve_window_meta`` plus a direct call to ``_drain_once()``. This lets+tests run on any platform; the real hook lifecycle is in the integration+test ``test_a1_e2e.py``.++Architecture assumptions the Wave 3 implementation dictates:+- ``_drain_once()`` is isolatable (one iteration of the drain loop).+- ``_safe_enqueue((ts_ns, hwnd))`` pushes items onto the queue (asyncio-thread-safe).+- ``_resolve_window_meta(hwnd)`` is a staticmethod — patchable.+- ``_loop`` is a property set in tests before _safe_enqueue."""from __future__ import annotations@@ -37,7 +37,7 @@ def _make_components() -> tuple[EventBus, AwarenessManager, PrivacyFilter]:def _async_collect(target: list):- """Test-Helper: gibt einen async Handler zurueck der Events an die Liste anhaengt."""+ """Test helper: returns an async handler that appends events to the list."""async def _handler(ev):target.append(ev)return _handler@@ -66,7 +66,7 @@ async def test_drain_routes_allowed_to_frame_updated() -> None:@pytest.mark.asyncioasync def test_drain_routes_blocked_to_capture_blocked() -> None:- """Frame mit Banking-Title → AwarenessCaptureBlocked, KEIN FrameUpdated."""+ """Frame with a banking title → AwarenessCaptureBlocked, NO FrameUpdated."""bus, manager, privacy = _make_components()blocked: list[AwarenessCaptureBlocked] = []updated: list[FrameUpdated] = []@@ -89,7 +89,7 @@ async def test_drain_routes_blocked_to_capture_blocked() -> None:@pytest.mark.asyncioasync def test_dedupe_50ms_window() -> None:- """Doppelter hwnd <50ms apart wird gedropt — Win32 emittiert manchmal 2-3."""+ """Duplicate hwnd <50ms apart gets dropped — Win32 sometimes emits 2-3."""bus, manager, privacy = _make_components()received: list[FrameUpdated] = []bus.subscribe(FrameUpdated, _async_collect(received))@@ -111,7 +111,7 @@ async def test_dedupe_50ms_window() -> None:@pytest.mark.asyncioasync def test_dedupe_does_not_drop_different_hwnd() -> None:- """Verschiedene hwnds in <50ms werden NICHT dedupliziert."""+ """Different hwnds within <50ms are NOT deduplicated."""bus, manager, privacy = _make_components()received: list[FrameUpdated] = []bus.subscribe(FrameUpdated, _async_collect(received))@@ -133,7 +133,7 @@ async def test_dedupe_does_not_drop_different_hwnd() -> None:@pytest.mark.asyncioasync def test_queue_full_increments_drops_no_crash() -> None:- """Bei voller Queue: drop-counter +1, kein Crash, kein Exception."""+ """When the queue is full: drop counter +1, no crash, no exception."""bus, manager, privacy = _make_components()watcher = WindowFocusWatcher(manager=manager, privacy=privacy, bus=bus)watcher._loop = asyncio.get_running_loop()@@ -147,7 +147,7 @@ async def test_queue_full_increments_drops_no_crash() -> None:@pytest.mark.asyncioasync def test_publish_updates_state_current_frame() -> None:- """Nach Drain: manager.state.current_frame ist gesetzt."""+ """After drain: manager.state.current_frame is set."""bus, manager, privacy = _make_components()watcher = WindowFocusWatcher(manager=manager, privacy=privacy, bus=bus)with patch.object(@@ -165,13 +165,13 @@ async def test_publish_updates_state_current_frame() -> None:@pytest.mark.asyncioasync def test_start_idempotent_on_linux() -> None:- """Auf Linux: start() ist no-op, kein Win32-Crash, doppelter call ok."""+ """On Linux: start() is a no-op, no Win32 crash, a duplicate call is ok."""if os.name == "nt":pytest.skip("Linux-only — Win32-start startet echten Pump-Thread")bus, manager, privacy = _make_components()watcher = WindowFocusWatcher(manager=manager, privacy=privacy, bus=bus)await watcher.start()- await watcher.start() # kein Crash+ await watcher.start() # no crashawait watcher.stop()@@ -180,13 +180,13 @@ async def test_stop_idempotent_no_start() -> None:"""stop() ohne start() ist no-op."""bus, manager, privacy = _make_components()watcher = WindowFocusWatcher(manager=manager, privacy=privacy, bus=bus)- await watcher.stop() # kein Crash, kein Hang+ await watcher.stop() # no crash, no hangawait watcher.stop()@pytest.mark.asyncioasync def test_resolve_meta_failure_skips_frame_no_crash() -> None:- """Wenn _resolve_window_meta raised: Frame wird gedropt, kein Crash."""+ """If _resolve_window_meta raises: the frame is dropped, no crash."""bus, manager, privacy = _make_components()received: list[FrameUpdated] = []bus.subscribe(FrameUpdated, _async_collect(received))diff --git a/tests/unit/awareness/test_working_set.py b/tests/unit/awareness/test_working_set.pyindex 1336516d4a..603265d898 100644--- a/tests/unit/awareness/test_working_set.py+++ b/tests/unit/awareness/test_working_set.py@@ -1,15 +1,15 @@-"""Unit-Tests fuer Phase A4 ``WorkingSet`` (jarvis/awareness/working_set.py).+"""Unit tests for Phase A4 ``WorkingSet`` (jarvis/awareness/working_set.py).Spec: JARVIS_AWARENESS_PLAN.md §8.-Testet:-- LRU-Eviction bei voller Kapazitaet (>5 Slots).-- Re-Promotion bei Re-Activation (A → B → A).-- ``set_episode`` Verknuepfung mit dem aktiven Slot.-- Eviction loescht KEINE Episoden (nur RAM-Pointer).-- Render-Format fuer System-Prompt (multi-context vs. single-context).+Tests:+- LRU eviction at full capacity (>5 slots).+- Re-promotion on re-activation (A → B → A).+- ``set_episode`` linkage with the active slot.+- Eviction deletes NO episodes (only the RAM pointer).+- Render format for the system prompt (multi-context vs. single-context).-Konvention: Fakes statt Mocks, pure unit-tests ohne async/IO.+Convention: fakes instead of mocks, pure unit tests without async/IO."""from __future__ import annotations@@ -105,11 +105,11 @@ def test_observe_evicts_oldest_when_full() -> None:def test_observe_seven_contexts_with_max_five_evicts_oldest_two() -> None:- """7 Context-Wechsel mit max=5: aeltester Slot fliegt raus, 5 bleiben.+ """7 context switches with max=5: the oldest slot flies out, 5 remain.- Acceptance Criterion: "Test mit 7 Context-Wechseln: ältester- Context-Eintrag fliegt aus dem Working-Set, alle 7 Episoden in DB- unverändert."+ Acceptance criterion: "Test with 7 context switches: the oldest+ context entry flies out of the working set, all 7 episodes in the+ DB unchanged.""""ws = WorkingSet(max_slots=5)inserted = ["c1", "c2", "c3", "c4", "c5", "c6", "c7"]@@ -118,7 +118,7 @@ def test_observe_seven_contexts_with_max_five_evicts_oldest_two() -> None:evicted = ws.observe(_ctx(r))if evicted is not None:evicted_roots.append(evicted.project_root)- # c1 wird durch c6 evictet, c2 durch c7.+ # c1 is evicted by c6, c2 by c7.assert evicted_roots == ["c1", "c2"]assert ws.size == 5assert [ctx.project_root for ctx in ws.contexts()] == ["c7", "c6", "c5", "c4", "c3"]@@ -135,7 +135,7 @@ def test_promote_a_then_b_then_a() -> None:ws.observe(_ctx("a", label="a-work-resumed"))assert ws.current.project_root == "a"- # task_label aus dem letzten observe ueberschreibt+ # task_label from the last observe overwritesassert ws.current.task_label == "a-work-resumed"@@ -150,25 +150,25 @@ def test_set_episode_updates_existing_slot() -> None:def test_set_episode_returns_false_for_unknown_root() -> None:- """Wenn der Slot evictet ist, schluckt set_episode silent."""+ """If the slot has been evicted, set_episode swallows it silently."""ws = WorkingSet(max_slots=2)ws.observe(_ctx("a"))ws.observe(_ctx("b"))- ws.observe(_ctx("c")) # evictet "a"+ ws.observe(_ctx("c")) # evicts "a"assert ws.set_episode("a", 99) is False- # b und c sind unverändert+ # b and c are unchangedassert ws.get("b").last_episode_id is Nonedef test_set_episode_does_not_promote() -> None:- """set_episode updated nur die Episode-ID, NICHT die LRU-Order."""+ """set_episode only updates the episode ID, NOT the LRU order."""ws = WorkingSet(max_slots=3)ws.observe(_ctx("a"))ws.observe(_ctx("b"))ws.observe(_ctx("c"))- # c ist current, a ist aeltester.+ # c is current, a is the oldest.ws.set_episode("a", 11)- # Order unverändert: c bleibt MRU, a bleibt LRU.+ # Order unchanged: c stays MRU, a stays LRU.assert [ctx.project_root for ctx in ws.contexts()] == ["c", "b", "a"]@@ -214,7 +214,7 @@ def test_render_for_prompt_multi_slot_includes_all_contexts() -> None:assert "Active contexts" in textassert "repo-jarvis" in textassert "slack.com" in text- # Episode-IDs werden mit angezeigt+ # Episode IDs are displayed tooassert "Episode #42" in textassert "Episode #43" in text@@ -235,19 +235,19 @@ def test_render_for_prompt_truncates_to_max_chars() -> None:def test_eviction_does_not_affect_episode_id_field() -> None:- """Plan §8 Hard Negative: Eviction = nur RAM-Pointer weg, Episode bleibt- in DB. Hier: beim Evicten geht nur der WorkingSet-Slot weg, der- last_episode_id-Wert ist im evicted-Object noch sichtbar (verifiziert- dass wir keinen Daten-Wipe machen).+ """Plan §8 hard negative: eviction = only the RAM pointer goes away, the+ episode stays in the DB. Here: on eviction only the WorkingSet slot+ goes away, the last_episode_id value is still visible on the evicted+ object (verifies that we do not wipe data)."""ws = WorkingSet(max_slots=2)ws.observe(_ctx("a"))ws.set_episode("a", 100)ws.observe(_ctx("b"))- evicted = ws.observe(_ctx("c")) # evictet "a"+ evicted = ws.observe(_ctx("c")) # evicts "a"assert evicted is not Noneassert evicted.project_root == "a"- # Die Episode-ID des evicted slots ist noch da — Caller koennte- # darauf reagieren (z.B. Audit). Wir verifizieren NUR dass keine- # Loesch-Aufrufe geschehen — der Test selbst hat keine DB.+ # The episode ID of the evicted slot is still there — a caller could+ # react to it (e.g. audit). We ONLY verify that no delete calls+ # happen — the test itself has no DB.assert evicted.last_episode_id == 100diff --git a/tests/unit/brain/test_ack_brain/test_preferences.py b/tests/unit/brain/test_ack_brain/test_preferences.pyindex 2d127b7694..80538cb624 100644--- a/tests/unit/brain/test_ack_brain/test_preferences.py+++ b/tests/unit/brain/test_ack_brain/test_preferences.py@@ -52,7 +52,7 @@ async def test_ack_prompt_includes_user_preferences_when_set() -> None:breaker=CircuitBreaker(threshold=3, cooldown_s=60),preferences_provider=lambda: "PREFS-MARKER-XYZZY",)- await gen.run("öffne mein Gmail und räum auf", language="de")+ await gen.run("öffne mein Gmail und räum auf", language="de") # i18n-allowassert provider.persona_prompts, "the provider should have been called"prompt = provider.persona_prompts[0]assert "PREFS-MARKER-XYZZY" in prompt@@ -67,7 +67,7 @@ async def test_ack_prompt_is_base_persona_when_no_preferences() -> None:breaker=CircuitBreaker(threshold=3, cooldown_s=60),preferences_provider=lambda: "",)- await gen.run("such Flüge nach Berlin", language="de")+ await gen.run("such Flüge nach Berlin", language="de") # i18n-allowassert provider.persona_prompts[0] == get_persona_prompt("de")@@ -83,7 +83,7 @@ async def test_ack_prompt_unaffected_when_provider_raises() -> None:breaker=CircuitBreaker(threshold=3, cooldown_s=60),preferences_provider=_boom,)- await gen.run("such Flüge nach Berlin", language="de")+ await gen.run("such Flüge nach Berlin", language="de") # i18n-allowassert provider.persona_prompts[0] == get_persona_prompt("de")@@ -93,14 +93,14 @@ async def test_ack_prompt_unaffected_when_provider_raises() -> None:async def test_spawn_llm_prompt_includes_user_preferences_when_set() -> None:- provider = _RecordingProvider(reply="Chef, ich schaue gründlich in dein Gmail.")+ provider = _RecordingProvider(reply="Chef, ich schaue gründlich in dein Gmail.") # i18n-allowcomposer = SpawnAnnouncementComposer(provider=provider,config=_ack_config(),breaker=None,preferences_provider=lambda: "SPAWN-PREFS-MARKER",)- await composer.compose(utterance="öffne mein Gmail und räum auf", language="de")+ await composer.compose(utterance="öffne mein Gmail und räum auf", language="de") # i18n-allowassert provider.persona_prompts, "the LLM path should have been taken"prompt = provider.persona_prompts[0]assert "SPAWN-PREFS-MARKER" in prompt@@ -108,12 +108,12 @@ async def test_spawn_llm_prompt_includes_user_preferences_when_set() -> None:async def test_spawn_llm_prompt_is_base_persona_when_no_preferences() -> None:- provider = _RecordingProvider(reply="Ich schaue gründlich in dein Gmail.")+ provider = _RecordingProvider(reply="Ich schaue gründlich in dein Gmail.") # i18n-allowcomposer = SpawnAnnouncementComposer(provider=provider,config=_ack_config(),breaker=None,preferences_provider=lambda: "",)- await composer.compose(utterance="öffne mein Gmail und räum auf", language="de")+ await composer.compose(utterance="öffne mein Gmail und räum auf", language="de") # i18n-allowassert provider.persona_prompts[0] == get_spawn_persona("de")diff --git a/tests/unit/brain/test_ack_generator.py b/tests/unit/brain/test_ack_generator.pyindex fa848975e5..54e8b4bec3 100644--- a/tests/unit/brain/test_ack_generator.py+++ b/tests/unit/brain/test_ack_generator.py@@ -77,7 +77,7 @@ class TestVoiceControlDetection:"wechsel auf gemini","denk gruendlich","what is the capital of france",- "still im gespraech", # 'still' inside other context — no leading match+ "still im gespraech", # 'still' inside other context — no leading match # i18n-allow"lauter applaus war zu hoeren", # noun, not command],)@@ -269,14 +269,14 @@ class TestShouldPrependMarker:assert should_prepend_marker(None) is Truedef test_substantive_text_wants_marker(self) -> None:- assert should_prepend_marker("Die App laeuft auf Port 8000.") is True+ assert should_prepend_marker("Die App laeuft auf Port 8000.") is True # i18n-allowassert should_prepend_marker("Ich habe drei Dateien gefunden.") is True@pytest.mark.parametrize("opener",[- "Erledigt — die App laeuft.",- "Fertig.",+ "Erledigt — die App laeuft.", # i18n-allow+ "Fertig.", # i18n-allow"Okay, das hab ich gemacht.","OK, sieht gut aus.","Done. The server is up.",diff --git a/tests/unit/brain/test_action_say_do_guard.py b/tests/unit/brain/test_action_say_do_guard.pyindex 5fe023070d..458e0362d9 100644--- a/tests/unit/brain/test_action_say_do_guard.py+++ b/tests/unit/brain/test_action_say_do_guard.py@@ -22,8 +22,8 @@ def test_action_unfulfilled_answer_is_honest_and_localized():# Never claims the save happened.for txt in (de, en, es):assert txt.strip()- assert "gespeichert habe ich" not in txt.lower()- assert "noch nicht" in de.lower() # "not yet saved"+ assert "gespeichert habe ich" not in txt.lower() # i18n-allow+ assert "noch nicht" in de.lower() # "not yet saved" # i18n-allowassert "haven't" in en.lower() or "not" in en.lower()assert "todav" in es.lower() or "aún" in es.lower() or "no he" in es.lower()@@ -64,7 +64,7 @@ def test_write_mandate_clarifying_question_is_kept():out = _unfulfilled_replacement(required_tool="contact-upsert",executed=set(),- response_text="Wie lautet Haralds vollständige E-Mail-Adresse?",+ response_text="Wie lautet Haralds vollständige E-Mail-Adresse?", # i18n-allowsuppressed=False,is_write=True,lang="de",@@ -76,7 +76,7 @@ def test_write_mandate_with_executed_tool_stands():out = _unfulfilled_replacement(required_tool="contact-upsert",executed={"contact-upsert"},- response_text="Hab ich gespeichert.",+ response_text="Hab ich gespeichert.", # i18n-allowsuppressed=False,is_write=True,lang="de",diff --git a/tests/unit/brain/test_agent_instructions.py b/tests/unit/brain/test_agent_instructions.pyindex 07022839e0..4ea90e00b5 100644--- a/tests/unit/brain/test_agent_instructions.py+++ b/tests/unit/brain/test_agent_instructions.py@@ -58,7 +58,7 @@ def test_filename_falls_back_to_assistant_when_unset():def test_filename_transliterates_umlauts():- assert agent_instructions.instructions_filename(make_config(name="Jürgen")) == "Juergen.md"+ assert agent_instructions.instructions_filename(make_config(name="Jürgen")) == "Juergen.md" # i18n-allowdef test_filename_strips_path_separators_and_unsafe_chars():@@ -119,7 +119,7 @@ def test_whitespace_only_reads_as_none():def test_save_is_utf8_without_bom_and_roundtrips_unicode(_isolate_data_dir):cfg = make_config(name="Ruben")- text = "Grüße — café ✓ 日本語"+ text = "Grüße — café ✓ 日本語" # i18n-allowagent_instructions.save_agent_instructions(cfg, text)raw = (_isolate_data_dir / "agent_instructions" / "Ruben.md").read_bytes()assert raw.startswith(b"\xef\xbb\xbf") is False # no BOM (AP-7)diff --git a/tests/unit/brain/test_artifact_build_routing.py b/tests/unit/brain/test_artifact_build_routing.pyindex f581b8a106..1e76512647 100644--- a/tests/unit/brain/test_artifact_build_routing.py+++ b/tests/unit/brain/test_artifact_build_routing.py@@ -68,8 +68,8 @@ def test_build_an_html_file_routes_to_a_mission() -> None:_BUILD_DELIVERABLE = ["Build me a website about my startup","Create a PDF report about the AI market",- "Bau mir eine Webseite über meinen Urlaub",- "Erstell mir ein interaktives Dashboard mit den wichtigsten Zahlen",+ "Bau mir eine Webseite über meinen Urlaub", # i18n-allow+ "Erstell mir ein interaktives Dashboard mit den wichtigsten Zahlen", # i18n-allow"Write me an HTML page that visualizes my expenses","Generate a landing page for the product launch",]diff --git a/tests/unit/brain/test_chosen_model_no_foreign_default.py b/tests/unit/brain/test_chosen_model_no_foreign_default.pyindex ee1ccad5cf..9508171261 100644--- a/tests/unit/brain/test_chosen_model_no_foreign_default.py+++ b/tests/unit/brain/test_chosen_model_no_foreign_default.py@@ -4,7 +4,7 @@ model, never a hardcoded foreign-family default.Live forensic 2026-06-29 (session 18:09:59): the user's brain was OpenRouter with``model = "nvidia/nemotron-3-ultra-550b-a55b:free"`` — a FREE model that answersHTTP 200 with the current key. Yet every turn spoke the provider-down apology-("Entschuldige, ich komme gerade nicht an mein Sprachmodell"). Root cause: the+("Entschuldige, ich komme gerade nicht an mein Sprachmodell"). Root cause: the # i18n-allowOpenRouter account had hit its per-key spend limit, so PAID models 403'd("Key limit exceeded (total limit)") while the chosen FREE model kept working.But the fallback chain never tried the free model for the deep slot:diff --git a/tests/unit/brain/test_codex_brain.py b/tests/unit/brain/test_codex_brain.pyindex 0b5820fb59..00dcb98045 100644--- a/tests/unit/brain/test_codex_brain.py+++ b/tests/unit/brain/test_codex_brain.py@@ -49,7 +49,7 @@ def _system_with_empty_standing_instructions() -> str:def test_cli_prompt_includes_standing_instructions_without_heavy_router_prompt() -> None:req = BrainRequest(- messages=(BrainMessage(role="user", content="Was ist das wertvollste Unternehmen?"),),+ messages=(BrainMessage(role="user", content="Was ist das wertvollste Unternehmen?"),), # i18n-allowsystem=_system_with_standing_instructions(),)@@ -89,8 +89,8 @@ def test_cli_prompt_puts_current_empty_state_after_stale_history() -> None:req = BrainRequest(messages=(BrainMessage(role="user", content="Wasketup"),- BrainMessage(role="assistant", content="schef, alles laeuft."),- BrainMessage(role="user", content="Du musst das nicht mehr sagen."),+ BrainMessage(role="assistant", content="schef, alles laeuft."), # i18n-allow+ BrainMessage(role="user", content="Du musst das nicht mehr sagen."), # i18n-allow),system=_system_with_empty_standing_instructions(),)diff --git a/tests/unit/brain/test_computer_use_offload.py b/tests/unit/brain/test_computer_use_offload.pyindex a6c7088c5c..71b6ac4178 100644--- a/tests/unit/brain/test_computer_use_offload.py+++ b/tests/unit/brain/test_computer_use_offload.py@@ -70,7 +70,7 @@ async def test_computer_use_acks_immediately_not_blocking_on_harness(monkeypatchmonkeypatch.setattr("jarvis.brain.manager.match_local_action", lambda _t: plan)start = time.monotonic()- reply = await mgr._run_local_action_fast_path("öffne chrome")+ reply = await mgr._run_local_action_fast_path("öffne chrome") # i18n-allowelapsed = time.monotonic() - start# The voice turn must NOT block on the 0.5 s harness — it ACKs and returns.@@ -102,7 +102,7 @@ async def test_computer_use_result_announced_when_done(monkeypatch) -> None:)monkeypatch.setattr("jarvis.brain.manager.match_local_action", lambda _t: plan)- await mgr._run_local_action_fast_path("öffne chrome")+ await mgr._run_local_action_fast_path("öffne chrome") # i18n-allowawait asyncio.gather(*getattr(mgr, "_cu_background_tasks", set()))assert executor.called@@ -128,7 +128,7 @@ async def test_computer_use_failure_is_announced_not_dropped(monkeypatch) -> Non)monkeypatch.setattr("jarvis.brain.manager.match_local_action", lambda _t: plan)- await mgr._run_local_action_fast_path("öffne chrome")+ await mgr._run_local_action_fast_path("öffne chrome") # i18n-allowawait asyncio.gather(*getattr(mgr, "_cu_background_tasks", set()))completions = [e for e in bus.published if getattr(e, "kind", None) == "completion"]@@ -144,7 +144,7 @@ async def test_user_cancel_offload_is_silent_not_announced(monkeypatch) -> None:immediately-silent kill-switch), so the cancel readback is redundant — andwith N parallel offloaded missions it spams the phrase N times. Live forensic2026-06-27: three CU missions all cancelled by one F1+F2 hangup spoke- "Die Aktion am Bildschirm wurde abgebrochen." three times. The cancel is the+ "Die Aktion am Bildschirm wurde abgebrochen." three times. The cancel is the # i18n-allowreceipt of an abort the user already made — not a result they are waiting on,so AD-OE6's zero-silent-drop (which protects real outcomes) does not apply."""@@ -204,7 +204,7 @@ async def test_three_parallel_cancels_speak_nothing(monkeypatch) -> None:)mgr = _make_manager(executor, bus)for _ in range(3):- await mgr._run_local_action_fast_path("öffentlich, dann screenshot")+ await mgr._run_local_action_fast_path("öffentlich, dann screenshot") # i18n-allowawait asyncio.gather(*getattr(mgr, "_cu_background_tasks", set()))completions = [e for e in bus.published if getattr(e, "kind", None) == "completion"]@@ -252,7 +252,7 @@ async def test_cu_failure_outcome_is_written_back_to_history(monkeypatch) -> Non)monkeypatch.setattr("jarvis.brain.manager.match_local_action", lambda _t: plan)- await mgr._run_local_action_fast_path("öffne mein spotify und spiel das lied")+ await mgr._run_local_action_fast_path("öffne mein spotify und spiel das lied") # i18n-allowawait asyncio.gather(*getattr(mgr, "_cu_background_tasks", set()))# The failed screen action must be grounded in the live history so the model@@ -287,7 +287,7 @@ async def test_cu_success_outcome_is_written_back_to_history(monkeypatch) -> Non)monkeypatch.setattr("jarvis.brain.manager.match_local_action", lambda _t: plan)- await mgr._run_local_action_fast_path("öffne spotify und spiel das lied")+ await mgr._run_local_action_fast_path("öffne spotify und spiel das lied") # i18n-allowawait asyncio.gather(*getattr(mgr, "_cu_background_tasks", set()))assert mgr._history, "a successful CU outcome must also be recorded in history"diff --git a/tests/unit/brain/test_contact_intent.py b/tests/unit/brain/test_contact_intent.pyindex 8686d4a529..af35c8bfc1 100644--- a/tests/unit/brain/test_contact_intent.py+++ b/tests/unit/brain/test_contact_intent.py@@ -1,8 +1,8 @@"""Contact write-intent detection — the input side of the say-do honesty guard.-The recurring failure (voice session 2026-06-30): Jarvis offered "Soll ich die-anlegen?", the user confirmed "ja, legt die mal an … die Mailadresse von Harald-ist …", and Jarvis replied "Okay, sehr gut" WITHOUT ever calling the+The recurring failure (voice session 2026-06-30): Jarvis offered "Soll ich die # i18n-allow+anlegen?", the user confirmed "ja, legt die mal an … die Mailadresse von Harald # i18n-allow+ist …", and Jarvis replied "Okay, sehr gut" WITHOUT ever calling the # i18n-allow``contact-upsert`` tool — the address book stayed empty. The detector belowmandates the real tool on a contact-write turn so the read-style evidence gate'sbackstop can catch a fake confirmation. Pure regex, no LLM (AP-9/AP-11).@@ -23,7 +23,7 @@ def test_reported_transcript_turn_fires():# The exact utterance from the live session (save verb + dictated detail).assert (detect_contact_write_intent(- "Ähm, ja, legt die mal an. Also die Mailadresse von Harald ist harald.10.de."+ "Ähm, ja, legt die mal an. Also die Mailadresse von Harald ist harald.10.de." # i18n-allow)is True)@@ -38,7 +38,7 @@ def test_genitive_detail_alone_fires():def test_save_verb_plus_contact_noun_fires():assert detect_contact_write_intent("Speichere Laura als Kontakt.") is Trueassert detect_contact_write_intent("Leg Tom als Kontakt an.") is True- assert detect_contact_write_intent("Füge Anna zu meinen Kontakten hinzu.") is True+ assert detect_contact_write_intent("Füge Anna zu meinen Kontakten hinzu.") is True # i18n-allowdef test_english_and_spanish_fire():@@ -54,7 +54,7 @@ def test_lookup_questions_do_not_fire():assert detect_contact_write_intent("Was steht heute in meinem Kalender?") is Falseassert detect_contact_write_intent("Habe ich irgendwelche Kontakte?") is Falseassert detect_contact_write_intent("Was geht ab?") is False- assert detect_contact_write_intent("Wie ist das Wetter?") is False+ assert detect_contact_write_intent("Wie ist das Wetter?") is False # i18n-allowdef test_send_or_call_actions_do_not_fire():@@ -65,9 +65,9 @@ def test_send_or_call_actions_do_not_fire():def test_bare_detail_statement_does_not_fire():# A non-possessive "the number is wrong" must not be mistaken for a save.- assert detect_contact_write_intent("Die Nummer ist falsch.") is False+ assert detect_contact_write_intent("Die Nummer ist falsch.") is False # i18n-allowassert detect_contact_write_intent("Harald ist 1976 geboren.") is False- assert detect_contact_write_intent("Die Adresse von Berlin ist zentral.") is False+ assert detect_contact_write_intent("Die Adresse von Berlin ist zentral.") is False # i18n-allowdef test_empty_input_is_safe():@@ -92,18 +92,18 @@ def test_directive_forces_the_real_tool_and_clarifies_bad_fields():def test_memory_save_intent_fires_on_explicit_remember():- assert detect_memory_save_intent("Merk dir, dass Harald gerne Fußball schaut.") is True+ assert detect_memory_save_intent("Merk dir, dass Harald gerne Fußball schaut.") is True # i18n-allowassert detect_memory_save_intent("Notier dir, dass Joy am 14. August Geburtstag hat.") is Trueassert detect_memory_save_intent("Remember that Tom prefers tea over coffee.") is Trueassert (- detect_memory_save_intent("Behalte im Hinterkopf, dass ich allergisch gegen Nüsse bin.")+ detect_memory_save_intent("Behalte im Hinterkopf, dass ich allergisch gegen Nüsse bin.") # i18n-allowis True)def test_memory_save_intent_needs_a_remember_cue_and_substance():assert detect_memory_save_intent("Was geht ab?") is False- assert detect_memory_save_intent("Wie ist das Wetter?") is False+ assert detect_memory_save_intent("Wie ist das Wetter?") is False # i18n-allow# "speichere die Datei" is file/config, not a personal memory note.assert detect_memory_save_intent("Speichere die Datei.") is Falseassert detect_memory_save_intent("Merk.") is False # no real content@@ -114,7 +114,7 @@ def test_memory_save_intent_needs_a_remember_cue_and_substance():def test_resolve_save_mandate_routes_contact_data_to_contact_upsert():mandate = resolve_save_mandate(- "Ähm, ja, legt die mal an. Also die Mailadresse von Harald ist harald.10.de."+ "Ähm, ja, legt die mal an. Also die Mailadresse von Harald ist harald.10.de." # i18n-allow)assert mandate is not Nonetool, directive = mandate@@ -123,7 +123,7 @@ def test_resolve_save_mandate_routes_contact_data_to_contact_upsert():def test_resolve_save_mandate_routes_general_fact_to_wiki_ingest():- mandate = resolve_save_mandate("Merk dir, dass Harald gerne Fußball schaut.")+ mandate = resolve_save_mandate("Merk dir, dass Harald gerne Fußball schaut.") # i18n-allowassert mandate is not Nonetool, directive = mandateassert tool == "wiki-ingest"diff --git a/tests/unit/brain/test_cu_vs_spawn_routing.py b/tests/unit/brain/test_cu_vs_spawn_routing.pyindex 2269a5d39c..907be29f5d 100644--- a/tests/unit/brain/test_cu_vs_spawn_routing.py+++ b/tests/unit/brain/test_cu_vs_spawn_routing.py@@ -1,7 +1,7 @@"""Computer-Use-vs-sub-agent-spawn routing (force-spawn depth-marker overlap).-Live bug: "Mach einen Deep Dive mit Computer Use in meinem Chrome Browser und-such mir den neuesten Post von Elon Musk raus" was force-spawned into a+Live bug: "Mach einen Deep Dive mit Computer Use in meinem Chrome Browser und # i18n-allow+such mir den neuesten Post von Elon Musk raus" was force-spawned into a # i18n-allowbackground sub-agent mission instead of reaching the Computer-Use path.Root cause (evidence, not guess): ``BrainManager._should_force_spawn`` hoists any@@ -10,12 +10,12 @@ sees the turn. That phrase list mixes two semantically different things:* **vehicle names** (``subagent`` / ``spawn`` / ``openclaw`` / ``delegate``) —the user named the worker. Unambiguous; absolute priority (mandate 2026-06-15).-* **depth markers** (``deep dive`` / ``gründlich`` / ``umfassend`` / …) — these+* **depth markers** (``deep dive`` / ``gründlich`` / ``umfassend`` / …) — these # i18n-allowdescribe thoroughness, NOT a vehicle, and OVERLAP with computer-use requests.A depth marker must not override an explicit on-screen/computer/browser request:the computer-use-vs-spawn call is the LLM router's (it owns ``computer_use`` plus-the SYSTEM_PROMPT rule "Bildschirm/Browser bedienen ist computer_use, kein+the SYSTEM_PROMPT rule "Bildschirm/Browser bedienen ist computer_use, kein # i18n-allowspawn_worker"). The deterministic gate only decides whether to FORCE a spawn —for an ambiguous depth marker + a computer-use request it must stand down and letthe LLM decide. A genuine depth/research request WITHOUT a screen signal still@@ -70,8 +70,8 @@ def _manager() -> BrainManager:# computer-use / browser request. Must NOT force-spawn — it routes to the LLM# router which picks computer_use.FAILING_UTTERANCE = (- "Mach einen Deep Dive mit Computer Use in meinem Chrome Browser und "- "such mir den neuesten Post von Elon Musk raus"+ "Mach einen Deep Dive mit Computer Use in meinem Chrome Browser und " # i18n-allow+ "such mir den neuesten Post von Elon Musk raus" # i18n-allow)@@ -107,8 +107,8 @@ def test_computer_use_is_reachable_by_the_router() -> None:# depth marker — must NOT force-spawn (they reach the LLM router -> computer_use)._REACH_COMPUTER_USE = [FAILING_UTTERANCE,- # depth marker ("gründliche") + explicit screen control ("Bildschirm"/"klick")- "Mach eine gründliche Analyse auf meinem Bildschirm und klick dich durch",+ # depth marker ("gründliche") + explicit screen control ("Bildschirm"/"klick") # i18n-allow+ "Mach eine gründliche Analyse auf meinem Bildschirm und klick dich durch", # i18n-allow# English depth marker + browser"Do a deep dive in my browser and click through the open tabs",# a plain pc-control request (no depth marker at all) must also stay off the@@ -131,13 +131,13 @@ _STILL_SPAWNS = [# contract: 'deep dive' over a CLI capability still spawns)"Mach einen Deep Dive in meine Google Cloud Kosten",# depth research, no screen signal- "Mach eine umfassende Recherche über die KI-News der letzten Woche",+ "Mach eine umfassende Recherche über die KI-News der letzten Woche", # i18n-allow# explicit vehicle name — absolute priority (mandate 2026-06-15)- "Spawne einen Subagenten der die Logs analysiert",- "Delegier das an einen Subagenten",+ "Spawne einen Subagenten der die Logs analysiert", # i18n-allow+ "Delegier das an einen Subagenten", # i18n-allow# explicit vehicle name DESPITE a screen signal — naming the vehicle wins# over the computer-use stand-down (the mandate must survive the fix)- "Spawne einen Subagenten der in Chrome klickt und mir einen Report baut",+ "Spawne einen Subagenten der in Chrome klickt und mir einen Report baut", # i18n-allow]@@ -150,7 +150,7 @@ def test_genuine_background_work_still_force_spawns(utterance: str) -> None:# Smalltalk never spawns.-_SMALLTALK = ["Hallo", "Wie geht's?", "Danke", "Was ist die Hauptstadt von Frankreich?"]+_SMALLTALK = ["Hallo", "Wie geht's?", "Danke", "Was ist die Hauptstadt von Frankreich?"] # i18n-allow@pytest.mark.parametrize("utterance", _SMALLTALK)@@ -167,8 +167,8 @@ def test_vehicle_plus_screen_signal_distinguishes_from_depth_plus_screen() -> Noa blanket keyword match but a vehicle-vs-depth distinction that hands theambiguous case to the LLM."""manager = _manager()- vehicle = "Spawne einen Subagenten der in Chrome klickt und mir einen Report baut"- depth = "Mach einen Deep Dive und klick dich durch Chrome"+ vehicle = "Spawne einen Subagenten der in Chrome klickt und mir einen Report baut" # i18n-allow+ depth = "Mach einen Deep Dive und klick dich durch Chrome" # i18n-allowassert _looks_like_pc_control(vehicle) is Trueassert _looks_like_pc_control(depth) is Trueassert manager._should_force_spawn(vehicle) is True, "vehicle name must still spawn"diff --git a/tests/unit/brain/test_custom_system_prompt.py b/tests/unit/brain/test_custom_system_prompt.pyindex 9ca794bdaa..344fcb050e 100644--- a/tests/unit/brain/test_custom_system_prompt.py+++ b/tests/unit/brain/test_custom_system_prompt.py@@ -63,7 +63,7 @@ def test_whitespace_only_custom_is_treated_as_no_custom() -> None:def test_save_roundtrips_unicode_exactly() -> None:- text = "Du bist BÄRBEL — höflich, präzise, mit Glück 🍀 und Größe."+ text = "Du bist BÄRBEL — höflich, präzise, mit Glück 🍀 und Größe." # i18n-allowpersona_loader.save_custom_prompt(text)assert persona_loader.read_custom_prompt() == text# No BOM corruption (AP-7 lesson): the raw bytes start with the real text.diff --git a/tests/unit/brain/test_evidence_gate_conversational_standdown.py b/tests/unit/brain/test_evidence_gate_conversational_standdown.pyindex 47dd0e50fe..b54dc8104d 100644--- a/tests/unit/brain/test_evidence_gate_conversational_standdown.py+++ b/tests/unit/brain/test_evidence_gate_conversational_standdown.py@@ -2,7 +2,7 @@Live 2026-06-30 (Bora-Bora voice session, ``voice-session-2026-06-30_17-58``):the user asked a plain travel question — "...bin jetzt bei meinem Budget bei so-25.000 Euro für zwei Personen, passt es?". The word **"budget"** sat in the+25.000 Euro für zwei Personen, passt es?". The word **"budget"** sat in the # i18n-allowGoogle-Cloud-billing keyword list, so the evidence gate FORCED ``cli_gcloud``;the model answered the travel question without that (irrelevant) tool, and thehonesty backstop then VOIDED the good answer with a canned failure phrase@@ -25,11 +25,11 @@ from jarvis.core.capabilities import CapabilityRegistryfrom jarvis.core.config import EvidenceDomainsConfig_RECOMBINED_BORA = (- "Was geht ab? Was ist morgen für ein Tag? Guten Tag, ich habe noch eine "- "Frage an dich und zwar möchte ich nach Bora Bora, was würdest du mir "- "empfehlen, was ich für den Urlaub brauche? Ich hab jetzt so für zwei "- "Wochen geplant und bin jetzt bei meinem Budget bei so 25.000 Euro für "- "zwei Personen, passt es?"+ "Was geht ab? Was ist morgen für ein Tag? Guten Tag, ich habe noch eine " # i18n-allow+ "Frage an dich und zwar möchte ich nach Bora Bora, was würdest du mir " # i18n-allow+ "empfehlen, was ich für den Urlaub brauche? Ich hab jetzt so für zwei " # i18n-allow+ "Wochen geplant und bin jetzt bei meinem Budget bei so 25.000 Euro für " # i18n-allow+ "zwei Personen, passt es?" # i18n-allow)@@ -50,7 +50,7 @@ def _cloud_gate(text: str):def test_bare_travel_budget_does_not_force_gcloud():# A travel / household / project budget is not a cloud bill (mirror of the# existing "was kostet X" hard negative).- v = _cloud_gate("Was ist mit meinem Budget für den Urlaub?")+ v = _cloud_gate("Was ist mit meinem Budget für den Urlaub?") # i18n-allowassert v.kind == "pass"@@ -73,7 +73,7 @@ def test_conversational_turn_suppresses_read_mandate():# The exact Bora-Bora turn (continuation-recombined) is opinion/advice.assert _conversational_turn_suppresses_read_mandate(_RECOMBINED_BORA) is Trueassert _conversational_turn_suppresses_read_mandate(- "Was würdest du mir empfehlen für meinen Urlaub?"+ "Was würdest du mir empfehlen für meinen Urlaub?" # i18n-allow) is Truediff --git a/tests/unit/brain/test_explicit_computer_use_routing.py b/tests/unit/brain/test_explicit_computer_use_routing.pyindex e397125569..581b2b5dcf 100644--- a/tests/unit/brain/test_explicit_computer_use_routing.py+++ b/tests/unit/brain/test_explicit_computer_use_routing.py@@ -1,8 +1,8 @@"""Explicit "use Computer-Use" requests must reach the screenshot harness.-Live repro (user, 2026-06-21): "Kannst du für mich bitte mit Computer-Use in-Spotify das Lied Perfect von Ed Sheeran abspielen?" was only ACKNOWLEDGED-("Ich schau gerade in Spotify nach dem Lied …") — the Computer-Use action never+Live repro (user, 2026-06-21): "Kannst du für mich bitte mit Computer-Use in # i18n-allow+Spotify das Lied Perfect von Ed Sheeran abspielen?" was only ACKNOWLEDGED # i18n-allow+("Ich schau gerade in Spotify nach dem Lied …") — the Computer-Use action never # i18n-allowdispatched or executed.Root cause: the deterministic ``match_local_action`` gate had no pattern for an@@ -39,18 +39,18 @@ from jarvis.brain.local_action_gate import (# The exact live utterance that broke, plus adjacent explicit-CU phrasings that# carry NO open verb (so the open-app fallback can never save them).REPRO_PHRASE = (- "Kannst du für mich bitte mit Computer-Use in Spotify das Lied Perfect "+ "Kannst du für mich bitte mit Computer-Use in Spotify das Lied Perfect " # i18n-allow"von Ed Sheeran abspielen?")_EXPLICIT_CU_UTTERANCES = [REPRO_PHRASE,- "Spiel mit Computer-Use das nächste Lied",+ "Spiel mit Computer-Use das nächste Lied", # i18n-allow"Mach das per Computer-Use",- "Erledige das über Computer-Use",- "Nutze Computer-Use und like den obersten Post",- "Benutze die Computer-Use Funktion dafür",- "Verwende Computer-Use um durch mein Spotify zu blättern",+ "Erledige das über Computer-Use", # i18n-allow+ "Nutze Computer-Use und like den obersten Post", # i18n-allow+ "Benutze die Computer-Use Funktion dafür", # i18n-allow+ "Verwende Computer-Use um durch mein Spotify zu blättern", # i18n-allow"Use computer use to skip to the next track in Spotify","Do it with computer use","Using computer use, pause the music",@@ -85,11 +85,11 @@ def test_explicit_computer_use_request_routes_to_harness(utterance: str) -> None# How-to / explain mentions are NOT a command to drive the screen."Was ist Computer-Use?","Wie funktioniert Computer-Use?",- "Erklär mir Computer-Use",+ "Erklär mir Computer-Use", # i18n-allow"What is computer use",# No harness mention at all — unaffected normal answers.- "schreib mir ein Gedicht über den Herbst",- "was ist die Hauptstadt von Frankreich",+ "schreib mir ein Gedicht über den Herbst", # i18n-allow+ "was ist die Hauptstadt von Frankreich", # i18n-allow],)def test_non_command_computer_use_mentions_do_not_route_to_harness(diff --git a/tests/unit/brain/test_failure_readback_no_exit_token.py b/tests/unit/brain/test_failure_readback_no_exit_token.pyindex cfa58378e0..22fd4004c5 100644--- a/tests/unit/brain/test_failure_readback_no_exit_token.py+++ b/tests/unit/brain/test_failure_readback_no_exit_token.py@@ -153,10 +153,10 @@ async def test_english_pin_failure_is_not_hardcoded_german(monkeypatch) -> None:reply = await mgr._run_local_action_fast_path("do the thing")- # The historical German hardcoded fallbacks ("nicht geklappt", "Aktion")+ # The historical German hardcoded fallbacks ("nicht geklappt", "Aktion") # i18n-allow# must not surface on an English-pinned turn.assert "geklappt" not in reply.lower()- assert "konnte nicht" not in reply.lower()+ assert "konnte nicht" not in reply.lower() # i18n-allow# ---------------------------------------------------------------------------diff --git a/tests/unit/brain/test_frontier_resolver.py b/tests/unit/brain/test_frontier_resolver.pyindex 14a8043050..5a3ea22883 100644--- a/tests/unit/brain/test_frontier_resolver.py+++ b/tests/unit/brain/test_frontier_resolver.py@@ -1,9 +1,9 @@-"""Tests fuer jarvis.brain.frontier_resolver.+"""Tests for jarvis.brain.frontier_resolver.-Drei Schwerpunkte:-1. Provider-Picker (deterministisch, gegen statische Modell-Listen).-2. Cache-TTL (fresh = no fetch, stale = fetch).-3. HTTP-Failure → Cache-Fallback / None.+Three areas of focus:+1. Provider picker (deterministic, against static model lists).+2. Cache TTL (fresh = no fetch, stale = fetch).+3. HTTP failure → cache fallback / None."""from __future__ import annotations@@ -48,7 +48,7 @@ class TestPickAnthropic:assert _pick_anthropic(models, "deep") == "claude-opus-4-7"def test_no_match_returns_none(self) -> None:- # Nur Sonnet-Modelle, keine Haiku/Opus.+ # Only Sonnet models, no Haiku/Opus.models = ["claude-sonnet-4-6", "claude-sonnet-4-5"]assert _pick_anthropic(models, "fast") is Noneassert _pick_anthropic(models, "deep") is None@@ -78,7 +78,7 @@ class TestPickGemini:"gemini-3-pro","gemini-3.1-pro-lite", # synthetisch — falls Google das releast]- # Sollte 3-pro picken, nicht den lite.+ # Should pick 3-pro, not the lite one.assert _pick_gemini(models, "deep") == "gemini-3-pro"def test_fast_excludes_pro(self) -> None:@@ -188,7 +188,7 @@ class TestResolveLatest:self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch,) -> None:resolver = FrontierResolver(cache_path=tmp_path / "c.json")- # Cache-Hit fuer (gemini, fast)+ # Cache hit for (gemini, fast)resolver._cache["gemini"] = {"fast": FrontierModel(provider="gemini", tier="fast",@@ -214,7 +214,7 @@ class TestResolveLatest:resolver = FrontierResolver(cache_path=tmp_path / "c.json", ttl_hours=0, # alle stale)- # Stale Cache-Eintrag+ # Stale cache entryresolver._cache["gemini"] = {"fast": FrontierModel(provider="gemini", tier="fast",@@ -247,11 +247,11 @@ class TestResolveLatest:assert resolver._cache["gemini"]["fast"].model_id == "gemini-3-flash"-# Synthetischer Exception-Type fuer den HTTP-Failure-Test.+# Synthetic exception type for the HTTP failure test.class httpx_RequestError(Exception):passdef test_event_loop_fixture_works() -> None:- """Sanity-check: sync test laeuft (keine async-fixture-issue)."""+ """Sanity check: sync test runs (no async-fixture issue)."""assert asyncio.iscoroutinefunction(FrontierResolver.resolve_latest)diff --git a/tests/unit/brain/test_gemini_stale_cache_bug019.py b/tests/unit/brain/test_gemini_stale_cache_bug019.pyindex 40d4e21764..ae9ee5c74a 100644--- a/tests/unit/brain/test_gemini_stale_cache_bug019.py+++ b/tests/unit/brain/test_gemini_stale_cache_bug019.py@@ -3,7 +3,7 @@Voice-Session 2026-05-11 starting at 17:22 went silent: Jarvis listened,moved to THINKING, but never spoke. Log evidence:- Brain gemini(gemini-3-flash-preview) fehlgeschlagen:+ Brain gemini(gemini-3-flash-preview) fehlgeschlagen: # i18n-allow403 Forbidden. {"error": {"code": 403,"message": "CachedContent not found (or permission denied)","status": "PERMISSION_DENIED"}}@@ -275,8 +275,8 @@ async def test_automatic_function_calling_is_disabled() -> None:forensic 2026-06-27: a voice "switch the worker from antigravity to codex"triggered AFC ("AFC is enabled with max remote calls: 10"), the call leaked,the recovery path ran the WRONG tool (list_mutable_settings), and the turn- stalled 108 s into the brain-timeout fallback ("ich habe die Antwort nicht- rechtzeitig fertigbekommen"). disable=True makes Gemini return a clean+ stalled 108 s into the brain-timeout fallback ("ich habe die Antwort nicht # i18n-allow+ rechtzeitig fertigbekommen"). disable=True makes Gemini return a clean # i18n-allowstructured function_call the stream loop consumes directly — fast and exact."""provider = GeminiBrain(model="gemini-3-flash-preview")diff --git a/tests/unit/brain/test_intelligent_router.py b/tests/unit/brain/test_intelligent_router.pyindex 7b2d5f9441..61156596e5 100644--- a/tests/unit/brain/test_intelligent_router.py+++ b/tests/unit/brain/test_intelligent_router.py@@ -127,7 +127,7 @@ async def test_router_with_no_tool_falls_through_to_chosen_talker() -> None:mgr._brain_cache[(TALKER_PROVIDER, TALKER_MODEL)] = talkerreply = await mgr.generate(- "Erzähl mir bitte etwas über die Geschichte von Rom", use_history=False+ "Erzähl mir bitte etwas über die Geschichte von Rom", use_history=False # i18n-allow)assert "TALKER_ANSWER" in reply, "must fall through to the chosen talker's voice"@@ -160,7 +160,7 @@ async def test_streaming_path_does_not_double_speak_the_router_lead() -> None:chunks: list[str] = []async for c in mgr.generate_stream(- "Erzähl mir bitte etwas über die Geschichte von Rom", use_history=False+ "Erzähl mir bitte etwas über die Geschichte von Rom", use_history=False # i18n-allow):chunks.append(c)streamed = "".join(chunks)diff --git a/tests/unit/brain/test_leaked_spawn_recovery.py b/tests/unit/brain/test_leaked_spawn_recovery.pyindex 75b27854f6..e029d9e0fb 100644--- a/tests/unit/brain/test_leaked_spawn_recovery.py+++ b/tests/unit/brain/test_leaked_spawn_recovery.py@@ -2,7 +2,7 @@Some providers (notably Gemini) intermittently emit a ``spawn_worker``tool_use block as the response *text* instead of executing it. Without the-recovery path the raw JSON reaches TTS as "Es trat ein Fehler auf" and the+recovery path the raw JSON reaches TTS as "Es trat ein Fehler auf" and the # i18n-allowdelegated Opus-4.7 sub-agent never runs — even though the brain decided todelegate. These tests pin the detector + the recovery execution.@@ -28,7 +28,7 @@ from jarvis.core.config import JarvisConfig# Canonical fragments of the leak-recovery "couldn't execute" fallback. A# recovered read tool that produced a usable result must NEVER speak these.-_FAILURE_FRAGMENTS = ("konnte sie aber nicht", "couldn't execute")+_FAILURE_FRAGMENTS = ("konnte sie aber nicht", "couldn't execute") # i18n-allowdef test_extract_detects_leaked_spawn_variants() -> None:@@ -73,7 +73,7 @@ def _manager_with_fake_spawn(captured: dict) -> BrainManager:captured["user_utterance"] = user_utterancereturn SimpleNamespace(success=True,- output="Mach ich, ich kümmere mich im Hintergrund darum.",+ output="Mach ich, ich kümmere mich im Hintergrund darum.", # i18n-allowerror=None,)@@ -99,7 +99,7 @@ async def test_recover_executes_leaked_spawn_and_returns_ack() -> None:user_text="erstelle mir eine Datei test-opus.md",trace_id=uuid4(),)- assert out == "Mach ich, ich kümmere mich im Hintergrund darum."+ assert out == "Mach ich, ich kümmere mich im Hintergrund darum." # i18n-allow# The leaked utterance is forwarded to the spawn tool.assert captured["args"]["utterance"] == "erstelle mir eine Datei test-opus.md"assert captured["tool"].name == "spawn_worker"@@ -110,7 +110,7 @@ async def test_recover_returns_none_for_normal_response() -> None:captured: dict = {}mgr = _manager_with_fake_spawn(captured)out = await mgr._recover_leaked_spawn(- "Alles erledigt, ich habe das im Hintergrund übernommen.",+ "Alles erledigt, ich habe das im Hintergrund übernommen.", # i18n-allowuser_text="erstelle mir eine Datei",trace_id=uuid4(),)@@ -121,13 +121,13 @@ async def test_recover_returns_none_for_normal_response() -> None:# ---------------------------------------------------------------------------# Leaked READ-tool (search_web) recovery (live repro 2026-06-14).#-# "Was hältst du von exp.com?" — an opinion question — made Gemini leak a+# "Was hältst du von exp.com?" — an opinion question — made Gemini leak a # i18n-allow# ``search_web`` tool_use block as TEXT. The recovery ran the search and got a# usable eXp-Realty result, but returned ``str(result.output)`` — and# search_web's output is a dict, so the string started with ``{``. The# streaming guard ``_looks_like_tool_use_leak`` then mistook that ANSWER for# another tool-use leak, dropped it, and the user heard the canned-# "Ich habe die Aktion erkannt, konnte sie aber nicht ausführen." A recovered+# "Ich habe die Aktion erkannt, konnte sie aber nicht ausführen." A recovered # i18n-allow# read tool must yield a SPEAKABLE answer, never a raw dict and never the# failure phrase.# ---------------------------------------------------------------------------@@ -173,8 +173,8 @@ def test_render_recovered_tool_output_renders_search_results_speakable() -> Nonedef test_render_recovered_tool_output_passes_through_plain_string() -> None:- # String-output tools (open_app -> "Gestartet: chrome") stay byte-identical.- assert _render_recovered_tool_output("Gestartet: chrome") == "Gestartet: chrome"+ # String-output tools (open_app -> "Gestartet: chrome") stay byte-identical. # i18n-allow+ assert _render_recovered_tool_output("Gestartet: chrome") == "Gestartet: chrome" # i18n-allowdef test_render_recovered_tool_output_empty_results_is_empty_not_repr() -> None:@@ -200,7 +200,7 @@ async def test_recover_leaked_search_web_speaks_answer_not_failure_phrase() -> N'"name":"search_web","input":{"query":"exp.com"}}]')out = await mgr._recover_leaked_tool(- leaked, user_text="Was hältst du von exp.com?", trace_id=uuid4(),+ leaked, user_text="Was hältst du von exp.com?", trace_id=uuid4(), # i18n-allow)# The search actually ran with the leaked query.assert captured["args"]["query"] == "exp.com"@@ -219,7 +219,7 @@ async def test_recover_leaked_search_web_empty_results_is_spoken_fallback() -> N)leaked = '{"type":"tool_use","name":"search_web","input":{"query":"zzz"}}'out = await mgr._recover_leaked_tool(- leaked, user_text="Was hältst du von zzz?", trace_id=uuid4(),+ leaked, user_text="Was hältst du von zzz?", trace_id=uuid4(), # i18n-allow)assert out is not Noneassert not any(frag in out.lower() for frag in _FAILURE_FRAGMENTS)diff --git a/tests/unit/brain/test_manager_vision.py b/tests/unit/brain/test_manager_vision.pyindex 8a94383890..263c3cab50 100644--- a/tests/unit/brain/test_manager_vision.py+++ b/tests/unit/brain/test_manager_vision.py@@ -1,4 +1,4 @@-"""Regression-Tests fuer Vision-Inject im produktiven BrainManager-Pfad."""+"""Regression tests for vision inject in the production BrainManager path."""from __future__ import annotationsimport base64@@ -163,7 +163,7 @@ async def test_brain_manager_skips_vision_when_paused() -> None:@pytest.mark.asyncioasync def test_brain_manager_continues_on_vision_failure(caplog) -> None:manager, recorder = _manager_with_recorder()- manager._vision_provider = _FakeVisionProvider(exc=ValueError("kein screenshot_path"))+ manager._vision_provider = _FakeVisionProvider(exc=ValueError("no screenshot_path"))# Non-smalltalk utterance so the Wave-1 conditional-vision gate keeps the# screenshot and actually exercises the vision-failure path (smalltalk like@@ -172,4 +172,4 @@ async def test_brain_manager_continues_on_vision_failure(caplog) -> None:await manager.generate("was siehst du", use_history=False)assert recorder.calls[0]["images"] == ()- assert any("Vision-Inject fehlgeschlagen" in rec.message for rec in caplog.records)+ assert any("Vision-Inject fehlgeschlagen" in rec.message for rec in caplog.records) # i18n-allowdiff --git a/tests/unit/brain/test_manager_worker_commands.py b/tests/unit/brain/test_manager_worker_commands.pyindex 736591ad02..450e710cc0 100644--- a/tests/unit/brain/test_manager_worker_commands.py+++ b/tests/unit/brain/test_manager_worker_commands.py@@ -1,10 +1,10 @@-"""Integration: BrainManager.generate() short-circuit fuer OpenClaw-Commands.+"""Integration: BrainManager.generate() short-circuit for OpenClaw commands.-AD-12 + AP-OC5: Status-/Cancel-Phrasen DUERFEN keinen Force-Spawn ausloesen,-auch wenn ihr Verb in der ``spawn_verbs``-Allowlist haengt ("brich" bzw.-ein Action-Verb-Kompositum). Der Test stellt sicher dass der Pattern--Matcher VOR der Force-Spawn-Heuristik greift, wenn Handler verdrahtet-sind, und dass ohne Handler der normale Pfad weiterlaeuft.+AD-12 + AP-OC5: status/cancel phrases must NOT trigger a force-spawn, even+when their verb hangs off the ``spawn_verbs`` allowlist ("brich" i.e. an+action-verb compound). The test ensures the pattern matcher takes effect+BEFORE the force-spawn heuristic when handlers are wired, and that the+normal path continues when no handler is set."""from __future__ import annotations@@ -23,36 +23,36 @@ def _bare_manager() -> BrainManager:@pytest.mark.asyncioasync def test_status_short_circuits_to_handler() -> None:- """Status-Phrase ruft den Handler statt einen Spawn anzustossen."""+ """A status phrase calls the handler instead of triggering a spawn."""manager = _bare_manager()calls: list[str | None] = []async def status_fn(mission_id: str | None) -> str:calls.append(mission_id)- return "Eine Mission laeuft seit drei Minuten."+ return "Eine Mission laeuft seit drei Minuten." # i18n-allowasync def cancel_fn(mission_id: str | None) -> str:- raise AssertionError("cancel_fn darf bei Status-Intent NICHT laufen")+ raise AssertionError("cancel_fn must NOT run on a status intent")manager.set_mission_command_handlers(status_fn=status_fn,cancel_fn=cancel_fn,)- result = await manager.generate("Laeuft das noch?", use_history=False)+ result = await manager.generate("Laeuft das noch?", use_history=False) # i18n-allow- assert result == "Eine Mission laeuft seit drei Minuten."- assert calls == [None] # keine Mission-ID im Text+ assert result == "Eine Mission laeuft seit drei Minuten." # i18n-allow+ assert calls == [None] # no mission ID in the text@pytest.mark.asyncioasync def test_cancel_short_circuits_to_handler() -> None:- """Cancel-Phrase ruft den Cancel-Handler statt einen Spawn anzustossen."""+ """A cancel phrase calls the cancel handler instead of triggering a spawn."""manager = _bare_manager()calls: list[str | None] = []async def status_fn(mission_id: str | None) -> str:- raise AssertionError("status_fn darf bei Cancel-Intent NICHT laufen")+ raise AssertionError("status_fn must NOT run on a cancel intent")async def cancel_fn(mission_id: str | None) -> str:calls.append(mission_id)@@ -90,12 +90,12 @@ async def test_mission_id_propagated_to_handler() -> None:@pytest.mark.asyncioasync def test_history_appended_for_status_response() -> None:- """Die kurze Status-Antwort landet im History-Buffer (sonst kein- Conversation-Memory beim naechsten Turn)."""+ """The short status answer lands in the history buffer (otherwise no+ conversation memory on the next turn)."""manager = _bare_manager()async def status_fn(mission_id: str | None) -> str:- return "Laeuft seit fuenf Minuten."+ return "Laeuft seit fuenf Minuten." # i18n-allowmanager.set_mission_command_handlers(status_fn=status_fn, cancel_fn=None,@@ -107,13 +107,13 @@ async def test_history_appended_for_status_response() -> None:assert manager._history[0].role == "user"assert manager._history[0].content == "Wie weit bist du?"assert manager._history[1].role == "assistant"- assert manager._history[1].content == "Laeuft seit fuenf Minuten."+ assert manager._history[1].content == "Laeuft seit fuenf Minuten." # i18n-allow@pytest.mark.asyncioasync def test_no_handler_falls_through(monkeypatch) -> None:- """Wenn keine Handler injiziert sind, greift der normale Spawn-Pfad- (kein Crash, kein leerer Return)."""+ """When no handlers are injected, the normal spawn path takes over+ (no crash, no empty return)."""manager = _bare_manager()spawn_called: list[str] = []@@ -123,7 +123,7 @@ async def test_no_handler_falls_through(monkeypatch) -> None:spawn_called.append(user_text)return "spawned-result"- # Keine Handler verdrahtet — Pattern matcht zwar, fall through.+ # No handlers wired — the pattern does match, but falls through.monkeypatch.setattr(manager, "_force_spawn_worker", fake_force_spawn)result = await manager.generate("Brich die Mission ab", use_history=False)@@ -134,8 +134,8 @@ async def test_no_handler_falls_through(monkeypatch) -> None:@pytest.mark.asyncioasync def test_smalltalk_does_not_trigger_handler() -> None:- """Smalltalk wie 'Wie geht's?' darf den Status-Handler NICHT triggern.- Sonst wuerde jede Begruessung einen MissionManager-Read ausloesen."""+ """Smalltalk like 'Wie geht's?' must NOT trigger the status handler.+ Otherwise every greeting would trigger a MissionManager read."""manager = _bare_manager()triggered: list[str] = []@@ -150,26 +150,26 @@ async def test_smalltalk_does_not_trigger_handler() -> None:async def fake_force_spawn(user_text: str, *, trace_id=None, source_layer=None) -> str | None:- return None # Smalltalk → keine Spawn+ return None # smalltalk → no spawnmanager.set_mission_command_handlers(status_fn=status_fn, cancel_fn=cancel_fn,)- # Force-Spawn-Pfad mocken; Dispatcher wird gar nicht erst gerufen weil- # der nachfolgende Code-Pfad einen leeren Provider-Chain erkennt und- # zurueckkehrt.+ # Mock the force-spawn path; the dispatcher never even gets called+ # because the subsequent code path detects an empty provider chain+ # and returns.manager._force_spawn_worker = fake_force_spawn # type: ignore[method-assign]await manager.generate("Hallo Jarvis", use_history=False)- assert triggered == [], "Status-/Cancel-Handler wurde bei Smalltalk gerufen"+ assert triggered == [], "status/cancel handler was called on smalltalk"@pytest.mark.asyncioasync def test_status_handler_falls_through_when_only_cancel_set() -> None:- """Wenn der User nach Status fragt, aber nur cancel_fn gesetzt ist,- fallen wir nicht auf cancel zurueck — wir delegieren an den normalen- Pfad. (Sonst wuerden falsche Cancellations passieren.)"""+ """When the user asks for status but only cancel_fn is set, we do not+ fall back to cancel — we delegate to the normal path. (Otherwise+ false cancellations would happen.)"""manager = _bare_manager()cancel_called: list[str | None] = []diff --git a/tests/unit/brain/test_mission_command_gate.py b/tests/unit/brain/test_mission_command_gate.pyindex 6af543ab81..89f5c62ba5 100644--- a/tests/unit/brain/test_mission_command_gate.py+++ b/tests/unit/brain/test_mission_command_gate.py@@ -1,10 +1,10 @@-"""Tests fuer ``jarvis.brain.mission_command_gate.match_mission_command``.+"""Tests for ``jarvis.brain.mission_command_gate.match_mission_command``.-AD-12 + AP-OC5 (siehe ``docs/openclaw-bridge.md``):-- Status-Phrasen muessen erkannt werden, Spawn unterdrueckt.-- Cancel-Phrasen muessen erkannt werden, Mission-Cancel statt Spawn.-- Smalltalk-/Kontextfreie-Phrasen DUERFEN NICHT matchen (False-Positive- waere eine Regression auf das ehemalige Spawn-Reflex-Problem).+AD-12 + AP-OC5 (see ``docs/openclaw-bridge.md``):+- Status phrases must be recognized, spawn suppressed.+- Cancel phrases must be recognized, mission-cancel instead of spawn.+- Smalltalk / context-free phrases must NOT match (a false positive+ would be a regression of the former spawn-reflex problem)."""from __future__ import annotations@@ -17,33 +17,33 @@ from jarvis.brain.mission_command_gate import (# ----------------------------------------------------------------------------# Status-Erkennung (positive cases)+# Status detection (positive cases)# ---------------------------------------------------------------------------@pytest.mark.parametrize("phrase",[- "läuft das noch?",- "Läuft das noch?",- "laeuft das noch",- "Läuft die Mission noch?",+ "läuft das noch?", # i18n-allow+ "Läuft das noch?", # i18n-allow+ "laeuft das noch", # i18n-allow+ "Läuft die Mission noch?", # i18n-allow"Status?","status","Jarvis, status",- "Status der Mission",- "Status vom Sub",- "Wie weit?",- "Wie weit bist du?",- "Wie weit sind wir?",- "Wo stehen wir?",- "Wo steht die Mission?",- "Noch am Laufen?",- "Immer noch dran?",+ "Status der Mission", # i18n-allow+ "Status vom Sub", # i18n-allow+ "Wie weit?", # i18n-allow+ "Wie weit bist du?", # i18n-allow+ "Wie weit sind wir?", # i18n-allow+ "Wo stehen wir?", # i18n-allow+ "Wo steht die Mission?", # i18n-allow+ "Noch am Laufen?", # i18n-allow+ "Immer noch dran?", # i18n-allow],)def test_status_de_positive(phrase: str) -> None:m = match_mission_command(phrase)- assert m is not None, f"erwartet Match fuer: {phrase!r}"+ assert m is not None, f"expected match for: {phrase!r}"assert m.intent == "status"assert m.language == "de"@@ -65,37 +65,37 @@ def test_status_de_positive(phrase: str) -> None:)def test_status_en_positive(phrase: str) -> None:m = match_mission_command(phrase)- assert m is not None, f"erwartet Match fuer: {phrase!r}"+ assert m is not None, f"expected match for: {phrase!r}"assert m.intent == "status"assert m.language == "en"# ----------------------------------------------------------------------------# Cancel-Erkennung (positive cases)+# Cancel detection (positive cases)# ---------------------------------------------------------------------------@pytest.mark.parametrize("phrase",[- "brich ab",- "Brich ab",- "Jarvis, brich ab",- "Brich die Mission ab",- "Brich den Auftrag ab",- "Brich alles ab",- "Stoppe die Mission",- "Stop die Mission",- "Stoppe OpenClaw",- "Mission abbrechen",- "Mission bitte abbrechen",- "Auftrag abbrechen",- "Abbruch der Mission",- "Abbruch OpenClaw",+ "brich ab", # i18n-allow+ "Brich ab", # i18n-allow+ "Jarvis, brich ab", # i18n-allow+ "Brich die Mission ab", # i18n-allow+ "Brich den Auftrag ab", # i18n-allow+ "Brich alles ab", # i18n-allow+ "Stoppe die Mission", # i18n-allow+ "Stop die Mission", # i18n-allow+ "Stoppe OpenClaw", # i18n-allow+ "Mission abbrechen", # i18n-allow+ "Mission bitte abbrechen", # i18n-allow+ "Auftrag abbrechen", # i18n-allow+ "Abbruch der Mission", # i18n-allow+ "Abbruch OpenClaw", # i18n-allow],)def test_cancel_de_positive(phrase: str) -> None:m = match_mission_command(phrase)- assert m is not None, f"erwartet Match fuer: {phrase!r}"+ assert m is not None, f"expected match for: {phrase!r}"assert m.intent == "cancel"assert m.language == "de"@@ -120,13 +120,13 @@ def test_cancel_de_positive(phrase: str) -> None:)def test_cancel_en_positive(phrase: str) -> None:m = match_mission_command(phrase)- assert m is not None, f"erwartet Match fuer: {phrase!r}"+ assert m is not None, f"expected match for: {phrase!r}"assert m.intent == "cancel"assert m.language == "en"# ----------------------------------------------------------------------------# Negative cases — DUERFEN NICHT matchen+# Negative cases — must NOT match# ---------------------------------------------------------------------------@pytest.mark.parametrize(@@ -134,48 +134,48 @@ def test_cancel_en_positive(phrase: str) -> None:[""," ",- "Hallo Jarvis",- "Wie geht es dir?",- "Was ist die Hauptstadt von Deutschland?",- "Erzähl mir einen Witz",- "Wie weit ist Berlin von Muenchen?", # 'wie weit' aber ohne Mission-Kontext-Wort- "Status der Wirtschaft", # Status, aber kein Mission-Bezug- "Stoppe die Musik", # 'stop' aber Musik, nicht Mission- "Lass das stoppen, das Lied", # generic stop- "Hör auf damit", # generic- "Spiele weiter", # weiter, aber kein Status-Pattern- "Cancel my dinner reservation", # 'cancel' aber kein Mission/Task- "Kill the music", # 'kill' aber Musik- "Run the script", # 'run' aber kein Status+ "Hallo Jarvis", # i18n-allow+ "Wie geht es dir?", # i18n-allow+ "Was ist die Hauptstadt von Deutschland?", # i18n-allow+ "Erzähl mir einen Witz", # i18n-allow+ "Wie weit ist Berlin von Muenchen?", # 'wie weit' but no mission-context word # i18n-allow+ "Status der Wirtschaft", # status, but no mission reference # i18n-allow+ "Stoppe die Musik", # 'stop' but music, not mission # i18n-allow+ "Lass das stoppen, das Lied", # generic stop # i18n-allow+ "Hör auf damit", # generic # i18n-allow+ "Spiele weiter", # 'continue', but no status pattern # i18n-allow+ "Cancel my dinner reservation", # 'cancel' but no mission/task+ "Kill the music", # 'kill' but music+ "Run the script", # 'run' but no status"Open my browser", # generic action- "Schreib eine E-Mail an Anna", # action verb, kein Status- "What's the weather?", # status-like, aber nicht 'the status'+ "Schreib eine E-Mail an Anna", # action verb, no status # i18n-allow+ "What's the weather?", # status-like, but not 'the status'],)def test_negative_no_match(phrase: str) -> None:m = match_mission_command(phrase)- assert m is None, f"unerwarteter Match fuer: {phrase!r} -> {m!r}"+ assert m is None, f"unexpected match for: {phrase!r} -> {m!r}"# ----------------------------------------------------------------------------# Cancel hat Prioritaet vor Status bei Doppel-Match+# Cancel takes priority over status on a double match# ---------------------------------------------------------------------------def test_cancel_wins_over_status() -> None:- """Wenn beide Patterns matchen wuerden, gewinnt Cancel — explizite- Stop-Anweisung darf nicht zu einem Status-Read degradiert werden."""- m = match_mission_command("Stop OpenClaw, wie weit bist du eigentlich?")+ """When both patterns would match, cancel wins — an explicit stop+ instruction must not be degraded to a status read."""+ m = match_mission_command("Stop OpenClaw, wie weit bist du eigentlich?") # i18n-allowassert m is not Noneassert m.intent == "cancel"# ----------------------------------------------------------------------------# Mission-ID-Extraktion+# Mission-ID extraction# ---------------------------------------------------------------------------def test_extract_uuid_v7() -> None:m = match_mission_command(- "Status der Mission 0190f7a3-1234-7abc-9def-0123456789ab"+ "Status der Mission 0190f7a3-1234-7abc-9def-0123456789ab" # i18n-allow)assert m is not Noneassert m.intent == "status"@@ -183,7 +183,7 @@ def test_extract_uuid_v7() -> None:def test_extract_uuid_normalized() -> None:- """UUID ohne Bindestriche wird auf das Standardformat gemapped."""+ """A UUID without hyphens is mapped to the standard format."""m = match_mission_command("stop mission 0190f7a312347abc9def0123456789ab")@@ -193,21 +193,21 @@ def test_extract_uuid_normalized() -> None:def test_extract_short_alias() -> None:- """Kurze Aliase ('mission build-foo') werden roh weitergereicht."""- m = match_mission_command("Status der Mission build-foo")+ """Short aliases ('mission build-foo') are passed through raw."""+ m = match_mission_command("Status der Mission build-foo") # i18n-allowassert m is not Noneassert m.mission_id == "build-foo"def test_no_mission_id_means_all_active() -> None:- """Ohne Mission-Hinweis ist mission_id None — Caller filtert auf alle aktiven."""- m = match_mission_command("Läuft das noch?")+ """Without a mission hint, mission_id is None — the caller filters over all active missions."""+ m = match_mission_command("Läuft das noch?") # i18n-allowassert m is not Noneassert m.mission_id is None# ----------------------------------------------------------------------------# Frozen-Dataclass-Vertrag+# Frozen dataclass contract# ---------------------------------------------------------------------------def test_match_is_frozen() -> None:diff --git a/tests/unit/brain/test_on_screen_routing.py b/tests/unit/brain/test_on_screen_routing.pyindex 6a87b580de..063221b323 100644--- a/tests/unit/brain/test_on_screen_routing.py+++ b/tests/unit/brain/test_on_screen_routing.py@@ -53,9 +53,9 @@ def _manager() -> BrainManager:_ON_SCREEN = [- "Mach das für mich am Bildschirm",- "Mach es auf dem Bildschirm",- "Bediene das am Bildschirm für mich",+ "Mach das für mich am Bildschirm", # i18n-allow+ "Mach es auf dem Bildschirm", # i18n-allow+ "Bediene das am Bildschirm für mich", # i18n-allow"Do it on screen for me","On my screen, find the latest post",]@@ -88,9 +88,9 @@ def test_build_and_show_on_screen_still_spawns_a_mission() -> None:"""A build-a-deliverable request that ALSO mentions the screen must stillspawn the mission — the build wins over the pc-control stand-down."""assert _manager()._should_force_spawn(- "Bau mir eine Website und zeig sie mir am Bildschirm"+ "Bau mir eine Website und zeig sie mir am Bildschirm" # i18n-allow) is Truedef test_screen_knowledge_question_does_not_force_spawn() -> None:- assert _manager()._should_force_spawn("Was ist ein Bildschirm?") is False+ assert _manager()._should_force_spawn("Was ist ein Bildschirm?") is False # i18n-allowdiff --git a/tests/unit/brain/test_output_filter.py b/tests/unit/brain/test_output_filter.pyindex 803bcde4f1..2d695cf1bf 100644--- a/tests/unit/brain/test_output_filter.py+++ b/tests/unit/brain/test_output_filter.py@@ -1,17 +1,17 @@-"""Tests fuer ``jarvis.brain.output_filter.scrub_for_voice``.--Persona-Mandat Phase 1: Output-Filter am Brain->TTS-Pfad scrubbt Tool-JSON,-Stacktraces, Engineering-Jargon, Self-Reference, Echo-Paraphrase und-Filler-Opener — bevor der Text an die TTS-Synthese geht.--Mandat-Anforderungen an die Tests:-- 5 Positiv-Cases (sauberer Text bleibt unveraendert)-- 5 Schwarzliste-Treffer (jedes Pattern mind. 1x)-- 3 Mixed-Cases (Stacktrace + Markdown + sauberer Text)-- 2 Whitelist-Schutz-Cases (User-Konzept-Worte wie "Datei" duerfen NIE- als Engineering-Jargon scrubbt werden)-- Failure-Mode-6-Test: Echo-Paraphrase NUR Opener-Position (erste 60- Zeichen) — mid-sentence Echo darf NICHT abgeschnitten werden.+"""Tests for ``jarvis.brain.output_filter.scrub_for_voice``.++Persona mandate phase 1: the output filter on the Brain->TTS path scrubs tool+JSON, stacktraces, engineering jargon, self-reference, echo paraphrase, and+filler openers — before the text goes to TTS synthesis.++Mandate requirements for the tests:+- 5 positive cases (clean text passes through unchanged)+- 5 blacklist hits (each pattern at least once)+- 3 mixed cases (stacktrace + markdown + clean text)+- 2 whitelist-protection cases (user concept words like "Datei" must NEVER+ be scrubbed as engineering jargon)+- Failure-mode-6 test: echo paraphrase ONLY at opener position (first 60+ characters) — mid-sentence echo must NOT be cut off."""from __future__ import annotations@@ -21,16 +21,16 @@ from jarvis.brain.output_filter import ScrubResult, scrub_for_voice# ----------------------------------------------------------------------------# 5 Positiv-Cases — sauberer Text muss UNVERAENDERT durchgehen.+# 5 positive cases — clean text must pass through UNCHANGED.# ---------------------------------------------------------------------------POSITIVE_CASES = [pytest.param("Halb drei.", id="terse-fact"),pytest.param(- "Die Datei deklariert vier Brain-Provider und enthält den Voice-Stack-Block.",+ "Die Datei deklariert vier Brain-Provider und enthält den Voice-Stack-Block.", # i18n-allowid="file-summary",),- pytest.param("Soll ich den Termin verschieben?", id="shall-i-question"),+ pytest.param("Soll ich den Termin verschieben?", id="shall-i-question"), # i18n-allowpytest.param("Es ist warm draussen.", id="weather-fact"),pytest.param("Goodbye, Ruben.", id="hangup-contract"),]@@ -38,7 +38,7 @@ POSITIVE_CASES = [@pytest.mark.parametrize("text", POSITIVE_CASES)def test_clean_text_passes_through_unchanged(text: str) -> None:- """Sauberer Text wird nicht modifiziert, kein fallback_used."""+ """Clean text is not modified, no fallback_used."""result = scrub_for_voice(text)assert isinstance(result, ScrubResult)assert result.cleaned == text@@ -47,25 +47,25 @@ def test_clean_text_passes_through_unchanged(text: str) -> None:# ----------------------------------------------------------------------------# 5 Schwarzliste-Treffer — jedes Pattern mind. einmal.+# 5 blacklist hits — each pattern at least once.# ---------------------------------------------------------------------------def test_tool_json_is_removed() -> None:- """Tool-Call-JSON in der Mitte des Texts wird komplett rausgeschnitten."""- text = 'Sub-Jarvis startet: spawn_worker({"utterance": "test"}) — bitte warten.'+ """Tool-call JSON in the middle of the text is cut out entirely."""+ text = 'Sub-Jarvis startet: spawn_worker({"utterance": "test"}) — bitte warten.' # i18n-allowresult = scrub_for_voice(text)assert '{"utterance"' not in result.cleanedassert "spawn_worker(" not in result.cleanedassert "removed_tool_json" in result.actions or "removed_tool_call" in result.actions- # Resttext sollte erhalten sein- assert "bitte warten" in result.cleaned.lower()+ # The rest of the text should be preserved+ assert "bitte warten" in result.cleaned.lower() # i18n-allowdef test_tool_call_python_keyword_args_is_removed() -> None:- """Python-style keyword-args (``tool(key='val', ...)``) — Probe-Drift 03."""+ """Python-style keyword args (``tool(key='val', ...)``) — probe drift 03."""text = (- "spawn_worker(utterance='Wie kann ich das beschleunigen?', "+ "spawn_worker(utterance='Wie kann ich das beschleunigen?', " # i18n-allow"context_hints=['x', 'y'], action='analyze', target='')")result = scrub_for_voice(text)@@ -75,35 +75,35 @@ def test_tool_call_python_keyword_args_is_removed() -> None:def test_tool_xml_tags_are_removed() -> None:- """XML-Tool-Tags inkl. Inner-Content — Probe-Drift 12."""+ """XML tool tags including inner content — probe drift 12."""text = (- "Ich delegiere das. <spawn_worker> <utterance>Lies die Datei</utterance>"- " <action>x</action> </spawn_worker> Fertig."+ "Ich delegiere das. <spawn_worker> <utterance>Lies die Datei</utterance>" # i18n-allow+ " <action>x</action> </spawn_worker> Fertig." # i18n-allow)result = scrub_for_voice(text)assert "<spawn_worker" not in result.cleanedassert "<utterance>" not in result.cleanedassert "removed_tool_json" in result.actions- # Resttext bleibt- assert "Fertig" in result.cleaned+ # The rest of the text remains+ assert "Fertig" in result.cleaned # i18n-allowdef test_tool_kw_pattern_does_not_break_harmless_python() -> None:- """Harmlose Python-Beispiele (``print(x=1)``) duerfen NICHT zerschossen werden.+ """Harmless Python examples (``print(x=1)``) must NOT be destroyed.- TOOL_CALL_KW_RE ist tool-name-spezifisch — nur bekannte Tool-Namen- matchen, nicht jeder ``\\w+(...)``-Aufruf.+ TOOL_CALL_KW_RE is tool-name-specific — only known tool names+ match, not every ``\\w+(...)`` call."""text = "Use print(x=1) to debug."result = scrub_for_voice(text)- # 'print' ist nicht in TOOL_NAMES — bleibt erhalten+ # 'print' is not in TOOL_NAMES — stays intactassert "print(x=1)" in result.cleaneddef test_stacktrace_is_replaced_with_fallback_phrase() -> None:- """Stacktrace -> 'Es trat ein Fehler auf.' + fallback_used=True."""+ """A stacktrace becomes the fallback phrase 'Es trat ein Fehler auf.' + fallback_used=True."""text = (- "Hier der Fehler:\n"+ "Hier der Fehler:\n" # i18n-allow'Traceback (most recent call last):\n'' File "/x/y.py", line 42, in run\n'" raise ValueError('boom')\n"@@ -113,33 +113,33 @@ def test_stacktrace_is_replaced_with_fallback_phrase() -> None:assert "Traceback" not in result.cleanedassert 'File "' not in result.cleanedassert "ValueError" not in result.cleaned- assert "Es trat ein Fehler auf" in result.cleaned+ assert "Es trat ein Fehler auf" in result.cleaned # i18n-allowassert result.fallback_used is Trueassert "replaced_stacktrace" in result.actionsdef test_markdown_is_stripped() -> None:- """Markdown-Reste (``**``, ``##``, code-fences, list-bullets) werden entfernt."""- text = "## Bericht\n\n**Wichtig:** Die Datei ist da.\n\n- Punkt eins\n- Punkt zwei"+ """Leftover markdown (``**``, ``##``, code fences, list bullets) is removed."""+ text = "## Bericht\n\n**Wichtig:** Die Datei ist da.\n\n- Punkt eins\n- Punkt zwei" # i18n-allowresult = scrub_for_voice(text)assert "**" not in result.cleanedassert "##" not in result.cleanedassert "- Punkt" not in result.cleaned- # Inhalt bleibt — nur das Markup ist weg+ # Content remains — only the markup is goneassert "Wichtig" in result.cleanedassert "Datei" in result.cleanedassert "stripped_markdown" in result.actionsdef test_self_reference_is_removed() -> None:- """``Als KI`` / ``Ich bin nur ein Sprachmodell`` werden gescrubbt."""- text = "Als KI kann ich das natuerlich pruefen. Halb drei."+ """``Als KI`` / ``Ich bin nur ein Sprachmodell`` are scrubbed."""+ text = "Als KI kann ich das natuerlich pruefen. Halb drei." # i18n-allowresult = scrub_for_voice(text)low = result.cleaned.lower()assert "als ki" not in lowassert "als sprachmodell" not in lowassert "ich bin nur" not in low- # Kerninhalt bleibt+ # Core content remainsassert "halb drei" in lowassert "removed_self_reference" in result.actions@@ -149,11 +149,11 @@ def test_self_reference_is_removed() -> None:[# The maintainer never wants Jarvis to SAY it is noting / reviewing the# last transcription — it happens silently in the background.- ("Verstanden. Ich notiere mir das. Das Wetter ist sonnig.", "de",+ ("Verstanden. Ich notiere mir das. Das Wetter ist sonnig.", "de", # i18n-allow"notiere", "sonnig"),- ("Ich schaue mir die letzte Transkription an. Die Hauptstadt ist Rom.",+ ("Ich schaue mir die letzte Transkription an. Die Hauptstadt ist Rom.", # i18n-allow"de", "transkription", "rom"),- ("Ich merke mir das. Hier ist die Antwort.", "de", "merke mir", "antwort"),+ ("Ich merke mir das. Hier ist die Antwort.", "de", "merke mir", "antwort"), # i18n-allow("Got it. I am noting that down. The capital is Rome.", "en","noting", "rome"),("Sure. Let me look at the last transcription. It is 25 degrees.", "en",@@ -164,7 +164,7 @@ def test_self_reference_is_removed() -> None:def test_background_action_narration_is_removed(text: str, language: str, gone: str, kept: str,) -> None:- """Noting / 'review the last transcription' narration is stripped (DE/EN/ES)."""+ """Noting / "review the last transcription" narration is stripped (DE/EN/ES)."""result = scrub_for_voice(text, language=language)low = result.cleaned.lower()assert gone not in low@@ -177,9 +177,9 @@ def test_background_action_narration_is_removed([# Must NOT be stripped: content lead-ins + legit save/check confirmations.("Looking at the data, the answer is 42.", "en"),- ("Ich schaue gleich nach dem Wetter und melde mich.", "de"),+ ("Ich schaue gleich nach dem Wetter und melde mich.", "de"), # i18n-allow("I'm saving the file now.", "en"),- ("Die Datei ist gespeichert.", "de"),+ ("Die Datei ist gespeichert.", "de"), # i18n-allow("I will check the weather for you.", "en"),],)@@ -192,8 +192,8 @@ def test_background_action_narration_no_false_positive(def test_echo_paraphrase_in_opener_is_cut() -> None:- """Echo-Paraphrase am Satzanfang wird abgeschnitten — Antwort ist die Substanz."""- text = "Du möchtest also wissen, wie spät es ist. Halb drei."+ """Echo paraphrase at the start of a sentence is cut off — the answer is the substance."""+ text = "Du möchtest also wissen, wie spät es ist. Halb drei." # i18n-allowresult = scrub_for_voice(text)low = result.cleaned.lower()assert "du möchtest also" not in low@@ -202,8 +202,8 @@ def test_echo_paraphrase_in_opener_is_cut() -> None:def test_filler_opener_is_removed() -> None:- """``Großartige Frage`` / ``Tolle Frage`` als Opener werden entfernt."""- text = "Großartige Frage! Es ist halb drei."+ """``Großartige Frage`` / ``Tolle Frage`` as an opener is removed."""+ text = "Großartige Frage! Es ist halb drei." # i18n-allowresult = scrub_for_voice(text)low = result.cleaned.lower()assert "großartige frage" not in low@@ -213,26 +213,26 @@ def test_filler_opener_is_removed() -> None:def test_engineering_jargon_is_removed() -> None:- """``MCP``/``Subprocess``/``Provider`` als Standalone-Worte werden gescrubbt."""- text = "Der Subprocess wurde via MCP-Provider gestartet."+ """``MCP``/``Subprocess``/``Provider`` as standalone words are scrubbed."""+ text = "Der Subprocess wurde via MCP-Provider gestartet." # i18n-allowresult = scrub_for_voice(text)low = result.cleaned.lower()- # Substanz-Worte verschwinden ODER werden umschrieben — wichtig ist:- # keines der drei Jargon-Worte als Standalone-Wort verbleibt.- assert "mcp" not in low.split() # nicht als Wort+ # The substance words disappear OR get paraphrased — what matters is:+ # none of the three jargon words remains as a standalone word.+ assert "mcp" not in low.split() # not as a wordassert "subprocess" not in lowassert "removed_engineering_jargon" in result.actions# ----------------------------------------------------------------------------# 3 Mixed-Cases — mehrere Patterns gleichzeitig.+# 3 mixed cases — several patterns at once.# ---------------------------------------------------------------------------def test_mixed_stacktrace_with_markdown() -> None:- """Stacktrace + Markdown -> Stacktrace gewinnt (fallback_used=True)."""+ """Stacktrace + markdown -> stacktrace wins (fallback_used=True)."""text = (- "## Fehler\n\n"+ "## Fehler\n\n" # i18n-allow"**Detail:** Traceback (most recent call last):\n"' File "/x/y.py", line 1, in <module>\n'" raise RuntimeError('x')"@@ -245,75 +245,76 @@ def test_mixed_stacktrace_with_markdown() -> None:def test_mixed_tool_json_with_clean_text() -> None:- """Tool-JSON mid-sentence + sauberer Text -> Tool-JSON raus, Text bleibt."""- text = 'Bitte: dispatch_to_admin({"op": "shutdown"}) ist nicht erlaubt.'+ """Tool JSON mid-sentence + clean text -> tool JSON removed, text remains."""+ text = 'Bitte: dispatch_to_admin({"op": "shutdown"}) ist nicht erlaubt.' # i18n-allowresult = scrub_for_voice(text)assert "dispatch_to_admin" not in result.cleanedassert "{\"op\"" not in result.cleaned- assert "ist nicht erlaubt" in result.cleaned.lower()+ assert "ist nicht erlaubt" in result.cleaned.lower() # i18n-allowdef test_mixed_filler_with_clean_rest() -> None:- """Filler-Opener + saubere Antwort -> Filler raus, Rest bleibt unveraendert.+ """Filler opener + clean answer -> filler removed, the rest stays unchanged.- Bewusst keine Jargon-Worte (Provider/Subprocess/MCP/Harness) im Resttext,- damit der Test nur die Filler-Entfernung isoliert prueft. Compounds wie- "Brain-Modelle" sind durch das Bindestrich-Lookbehind in JARGON_RE- ohnehin geschuetzt.+ Deliberately no jargon words (Provider/Subprocess/MCP/Harness) in the+ remaining text, so this test isolates only the filler-removal check.+ Compounds like "Brain-Modelle" are protected anyway by the hyphen+ lookbehind in JARGON_RE."""- text = "Tolle Frage! Die Datei jarvis.toml hat vier Brain-Modelle."+ text = "Tolle Frage! Die Datei jarvis.toml hat vier Brain-Modelle." # i18n-allowresult = scrub_for_voice(text)assert "Tolle Frage" not in result.cleaned- # User-Konzept-Worte (Datei) duerfen NICHT verschwinden+ # User concept words (Datei) must NOT disappearassert "Datei" in result.cleanedassert "jarvis.toml" in result.cleanedassert "vier Brain-Modelle" in result.cleaned# ----------------------------------------------------------------------------# 2 Whitelist-Schutz-Cases — User-Konzept-Worte sind heilig.+# 2 whitelist-protection cases — user concept words are sacred.# ---------------------------------------------------------------------------def test_whitelist_datei_is_protected() -> None:- """``Datei`` wird NIE gescrubbt, auch nicht als Jargon-Lookalike."""- text = "Die Datei wurde gespeichert."+ """``Datei`` is NEVER scrubbed, not even as a jargon lookalike."""+ text = "Die Datei wurde gespeichert." # i18n-allowresult = scrub_for_voice(text)assert result.cleaned == textassert result.actions == []def test_whitelist_user_concepts_protected() -> None:- """``Browser``/``Email``/``Terminal``/``Notiz``/``Termin``/``Kalender`` bleiben."""- text = "Browser geöffnet, Email versendet, Termin im Kalender eingetragen, Notiz im Terminal gespeichert."+ """``Browser``/``Email``/``Terminal``/``Notiz``/``Termin``/``Kalender`` remain."""+ text = "Browser geöffnet, Email versendet, Termin im Kalender eingetragen, Notiz im Terminal gespeichert." # i18n-allowresult = scrub_for_voice(text)for concept in ("Browser", "Email", "Termin", "Kalender", "Notiz", "Terminal"):- assert concept in result.cleaned, f"Whitelist-Wort {concept!r} wurde gescrubbt"+ assert concept in result.cleaned, f"whitelist word {concept!r} was scrubbed"# ----------------------------------------------------------------------------# Failure-Mode-6-Test: Echo-Paraphrase NUR Opener-Position.+# Failure-mode-6 test: echo paraphrase ONLY at opener position.# ---------------------------------------------------------------------------def test_echo_paraphrase_mid_sentence_is_kept() -> None:- """Mid-sentence Echo-Pattern (nach 60 Zeichen) DARF NICHT gescrubbt werden.+ """A mid-sentence echo pattern (after 60 characters) must NOT be scrubbed.- Mandat-Failure-Mode 6: Manchmal will der User wirklich eine Bestaetigung- im Echo-Stil ('Du moechtest also den Termin verschieben? Ja oder nein?').- Filter NUR auf Opener-Position (erste 60 Zeichen) anwenden.+ Mandate failure mode 6: sometimes the user genuinely wants an+ echo-style confirmation ('Du moechtest also den Termin verschieben?+ Ja oder nein?'). Apply the filter ONLY at the opener position (first+ 60 characters)."""- # Echo-Pattern in der Mitte (nach >60 Zeichen sauberen Texts)+ # Echo pattern in the middle (after >60 characters of clean text)text = (- "Ich habe den Termin am Freitag im Kalender und einen Konflikt erkannt. "+ "Ich habe den Termin am Freitag im Kalender und einen Konflikt erkannt. " # i18n-allow"Du möchtest also den Termin verschieben? Ja oder nein?")- # Sicherheitscheck: Echo-Pattern liegt nach Position 60+ # Sanity check: the echo pattern sits after position 60echo_pos = text.lower().find("du möchtest also")- assert echo_pos > 60, f"Test-Setup-Bug: Echo-Pattern bei Position {echo_pos}"+ assert echo_pos > 60, f"test-setup bug: echo pattern at position {echo_pos}"result = scrub_for_voice(text)- # Mid-sentence Echo bleibt erhalten+ # Mid-sentence echo is preservedassert "möchtest also" in result.cleaned.lower()assert "rephrased_echo" not in result.actions@@ -333,10 +334,10 @@ def test_em_dash_becomes_comma() -> None:def test_en_dash_becomes_comma() -> None:- text = "Alles bereit – wir können sofort loslegen."+ text = "Alles bereit – wir können sofort loslegen." # i18n-allowresult = scrub_for_voice(text)assert "–" not in result.cleaned- assert "Alles bereit, wir können" in result.cleaned+ assert "Alles bereit, wir können" in result.cleaned # i18n-allowdef test_hyphen_compound_survives_em_dash_filter() -> None:@@ -358,9 +359,9 @@ def test_ascii_double_hyphen_dash_aside_becomes_comma() -> None:same hard TTS pause as an em dash — collapse it to a comma too. TheUnicode-only scrub missed it, and several canned phrases / LLM outputs use' -- ' (live forensic 2026-06-30)."""- result = scrub_for_voice("Mach ich -- ich sage Bescheid, sobald es fertig ist.")+ result = scrub_for_voice("Mach ich -- ich sage Bescheid, sobald es fertig ist.") # i18n-allowassert "--" not in result.cleaned- assert "Mach ich, ich sage Bescheid" in result.cleaned+ assert "Mach ich, ich sage Bescheid" in result.cleaned # i18n-allowdef test_ascii_hyphen_compound_and_range_survive_double_hyphen_filter() -> None:@@ -372,15 +373,15 @@ def test_ascii_hyphen_compound_and_range_survive_double_hyphen_filter() -> None:def test_fallback_used_true_only_for_stacktrace() -> None:- """``fallback_used`` nur ``True`` wenn der gesamte Text durch Standard-- Phrase ersetzt wurde (Stacktrace), nicht bei Teil-Scrub."""- # Ein Filler-Opener entfernt nur einen Teil — kein Fallback- result = scrub_for_voice("Großartige Frage! Halb drei.")+ """``fallback_used`` is only ``True`` when the whole text was replaced by+ the standard phrase (stacktrace), not on a partial scrub."""+ # A filler opener only removes a part — no fallback+ result = scrub_for_voice("Großartige Frage! Halb drei.") # i18n-allowassert result.fallback_used is Falsedef test_empty_input_returns_empty() -> None:- """Leerer Input -> leeres Output, keine Exception."""+ """Empty input -> empty output, no exception."""result = scrub_for_voice("")assert result.cleaned == ""assert result.actions == []@@ -388,32 +389,32 @@ def test_empty_input_returns_empty() -> None:# ----------------------------------------------------------------------------# Phase-1-Erweiterungen aus Research-Report 2026-04-28 Sektion 1.3.+# Phase-1 extensions from research report 2026-04-28 section 1.3.#-# Vier neue Drift-Klassen, die die ursprueeglich Mandat-Phase-1-Schwarzliste-# nicht abdeckte aber genau in den Filter-Scope passen:+# Four new drift classes that the original mandate phase-1 blacklist did not+# cover but that fit exactly into the filter's scope:#-# 1. A1 "Sir"-Anrede (Szenarien 03/07 der Probe vom 2026-04-28).-# 2. "Sub-Agent"/"Supervisor-Agent" als Engineering-Reveal.-# 3. Tool-Args-Body-Leak in YAML-/key:value-Form.-# 4. Post-Scrub-Muell (z.B. einzelnes `}`) -> fallback_used=True.+# 1. A1 "Sir" address (scenarios 03/07 of the 2026-04-28 probe).+# 2. "Sub-Agent"/"Supervisor-Agent" as an engineering reveal.+# 3. Tool-args body leak in YAML-/key:value form.+# 4. Post-scrub residue (e.g. a lone `}`) -> fallback_used=True.# ---------------------------------------------------------------------------def test_sir_anrede_is_removed() -> None:- """A1: 'Sir' als Anrede wird gescrubbt — Mandat A1 (Ruben statt Sir)."""- text = "Sir, ich starte die Analyse."+ """A1: 'Sir' as a form of address is scrubbed — mandate A1 (Ruben instead of Sir)."""+ text = "Sir, ich starte die Analyse." # i18n-allowresult = scrub_for_voice(text)low = result.cleaned.lower()- assert "sir" not in low.split(",")[0].split() # nicht als Wort im Opener+ assert "sir" not in low.split(",")[0].split() # not as a word in the openerassert "sir" not in low- assert "ich starte die analyse" in low+ assert "ich starte die analyse" in low # i18n-allowassert "removed_anrede_drift" in result.actionsdef test_sir_anrede_mid_sentence_is_removed() -> None:- """A1: 'Sir' auch mitten im Satz (nach Komma) wird entfernt."""- text = "Erledigt, Sir. Die Datei ist gespeichert."+ """A1: 'Sir' is also removed mid-sentence (after a comma)."""+ text = "Erledigt, Sir. Die Datei ist gespeichert." # i18n-allowresult = scrub_for_voice(text)assert "Sir" not in result.cleanedassert "Datei" in result.cleaned@@ -421,58 +422,58 @@ def test_sir_anrede_mid_sentence_is_removed() -> None:def test_legitimate_sir_in_quote_is_kept() -> None:- """Innerhalb von Anfuehrungszeichen bleibt 'Sir' erhalten (Zitat-Schutz).+ """'Sir' is preserved inside quotation marks (quote protection).- Wenn der User Jarvis bittet, einen Songtext oder ein Zitat vorzulesen, in- dem 'Sir' vorkommt, soll der Filter das nicht zerschiessen. Heuristik:- 'Sir' direkt in Quotes wird nicht gescrubbt.+ If the user asks Jarvis to read out a song lyric or a quote that+ contains 'Sir', the filter must not destroy it. Heuristic: 'Sir'+ directly inside quotes is not scrubbed."""- text = 'Im Lied steht: "Yes, Sir, I can boogie." — kennst du das?'+ text = 'Im Lied steht: "Yes, Sir, I can boogie." — kennst du das?' # i18n-allowresult = scrub_for_voice(text)- assert "Sir" in result.cleaned, "Sir in Quote wurde faelschlich gescrubbt"+ assert "Sir" in result.cleaned, "Sir in a quote was wrongly scrubbed"def test_sub_agent_jargon_is_removed() -> None:- """'Sub-Agent' als Engineering-Reveal wird entfernt — Probe-Drift 03/07."""- text = "Ich starte einen Sub-Agent, der die Datei analysiert."+ """'Sub-Agent' as an engineering reveal is removed — probe drift 03/07."""+ text = "Ich starte einen Sub-Agent, der die Datei analysiert." # i18n-allowresult = scrub_for_voice(text)assert "Sub-Agent" not in result.cleanedassert "sub-agent" not in result.cleaned.lower()- # Kerninhalt bleibt- assert "analysiert" in result.cleaned.lower()+ # Core content remains+ assert "analysiert" in result.cleaned.lower() # i18n-allowassert "removed_engineering_jargon" in result.actionsdef test_supervisor_agent_jargon_is_removed() -> None:- """'Supervisor-Agent' als Engineering-Reveal wird entfernt — Probe-Drift 13."""- text = "Dein persoenlicher Supervisor-Agent erledigt das."+ """'Supervisor-Agent' as an engineering reveal is removed — probe drift 13."""+ text = "Dein persoenlicher Supervisor-Agent erledigt das." # i18n-allowresult = scrub_for_voice(text)assert "Supervisor-Agent" not in result.cleanedassert "supervisor-agent" not in result.cleaned.lower()- assert "erledigt" in result.cleaned.lower()+ assert "erledigt" in result.cleaned.lower() # i18n-allowassert "removed_engineering_jargon" in result.actionsdef test_tool_args_yaml_block_is_removed() -> None:- """Tool-Args-Body-Leak als YAML/key:value-Block — Probe-Drift 03 Body.+ """Tool-args body leak as a YAML/key:value block — probe drift 03 body.- Die Probe vom 2026-04-28 hat in Szenario 03 den vollstaendigen- Sub-Jarvis-Tool-Aufruf-Body durchgeleakt:+ The 2026-04-28 probe leaked the entire Sub-Jarvis tool-call body in+ scenario 03:utterance: "Wie kann ich das beschleunigen?"context_hints:- Unklar ...- Benoetigt Kontext ...action: "die Beschleunigung ..."target: ""- Diese YAML-aehnliche Form ist von TOOL_JSON_RE nicht gefangen.+ This YAML-like form is not caught by TOOL_JSON_RE."""text = (- "Ich starte die Analyse.\n"- '"Wie kann ich das beschleunigen?"\n'+ "Ich starte die Analyse.\n" # i18n-allow+ '"Wie kann ich das beschleunigen?"\n' # i18n-allow"context_hints:\n"- "Unklar, was beschleunigt werden soll.\n"- "Benoetigt Kontext zur aktuellen Aufgabe oder zum System.\n"- 'action: "die Beschleunigung einer unklaren Aufgabe analysiert"\n'+ "Unklar, was beschleunigt werden soll.\n" # i18n-allow+ "Benoetigt Kontext zur aktuellen Aufgabe oder zum System.\n" # i18n-allow+ 'action: "die Beschleunigung einer unklaren Aufgabe analysiert"\n' # i18n-allow'target: ""')result = scrub_for_voice(text)@@ -480,57 +481,57 @@ def test_tool_args_yaml_block_is_removed() -> None:assert "action:" not in result.cleanedassert "target:" not in result.cleanedassert "removed_tool_json" in result.actions- # Der Resttext ('Ich starte die Analyse.') bleibt erhalten+ # The rest of the text ('Ich starte die Analyse.') remainsassert "Analyse" in result.cleaneddef test_post_scrub_residue_triggers_fallback() -> None:- """Wenn nach allen Scrubs nur Muell uebrig bleibt -> fallback_used=True.+ """When only residue is left after all scrubs -> fallback_used=True.- Probe-Drift 12: Tool-Filter zerschoss alles bis auf '}', das geht- unkommentiert an TTS und der User hoert quasi nichts. Wenn der- gefilterte Text weniger als 3 alphanumerische Chars enthaelt,- soll der Filter auf die Standard-Fehler-Phrase zurueckfallen.+ Probe drift 12: the tool filter tore everything apart except a '}',+ which went to TTS uncommented and the user heard practically nothing.+ When the filtered text contains fewer than 3 alphanumeric characters,+ the filter should fall back to the standard error phrase."""- # Nur ein '}' uebrig — mehr nicht+ # Only a '}' remains — nothing moretext = '<spawn_worker>{"utterance": "test"}</spawn_worker>}'result = scrub_for_voice(text)- # Entweder fallback_used=True ODER cleaned ist leer (beides akzeptabel)+ # Either fallback_used=True OR cleaned is empty (both acceptable)assert (result.fallback_used and result.cleaned), (- f"Post-Scrub-Muell {result.cleaned!r} wurde nicht durch Fallback ersetzt"+ f"post-scrub residue {result.cleaned!r} was not replaced by the fallback")- assert "Es trat ein Fehler auf" in result.cleaned or result.cleaned.strip() == ""+ assert "Es trat ein Fehler auf" in result.cleaned or result.cleaned.strip() == "" # i18n-allowdef test_post_scrub_meaningful_text_no_fallback() -> None:- """Defense gegen den Fallback-Trigger: substanzieller Resttext loest KEIN- fallback_used aus."""- text = "Erledigt. Die Datei ist da."+ """Defense against the fallback trigger: substantial remaining text does+ NOT trigger fallback_used."""+ text = "Erledigt. Die Datei ist da." # i18n-allowresult = scrub_for_voice(text)assert result.fallback_used is Falseassert "Datei" in result.cleaned# ----------------------------------------------------------------------------# Phase-1-Erweiterung 2 (2026-04-28 spaeter):-# Anthropic-Internal-Tag-Drifts aus der Re-Probe — Brain leakt:+# Phase-1 extension 2 (2026-04-28, later):+# Anthropic-internal tag drifts from the re-probe — the brain leaks:# 1. ``<function_calls>...<invoke name="...">...</invoke></function_calls>``-# 2. Generische ``<tool_call>...</tool_call>`` / ``<tool_response>...</tool_response>``-# 3. Base64-Image-Strings als Body-Leak+# 2. Generic ``<tool_call>...</tool_call>`` / ``<tool_response>...</tool_response>``+# 3. Base64 image strings as a body leak# ---------------------------------------------------------------------------def test_anthropic_function_calls_block_is_removed() -> None:- """Anthropic-internes ``<function_calls><invoke name='...'>``-Format —- Re-Probe-Drift Szenario 12 vom 2026-04-28."""+ """Anthropic-internal ``<function_calls><invoke name='...'>`` format —+ re-probe drift scenario 12 from 2026-04-28."""text = (- 'Hier: <function_calls>\n'+ 'Hier: <function_calls>\n' # i18n-allow'<invoke name="spawn_worker">\n'- '<parameter name="utterance">Lies die Datei</parameter>\n'+ '<parameter name="utterance">Lies die Datei</parameter>\n' # i18n-allow'<parameter name="action">x</parameter>\n''</invoke>\n''</function_calls>\n'- 'Fertig.'+ 'Fertig.' # i18n-allow)result = scrub_for_voice(text)assert "<function_calls>" not in result.cleaned@@ -538,21 +539,21 @@ def test_anthropic_function_calls_block_is_removed() -> None:assert "<parameter" not in result.cleanedassert "spawn_worker" not in result.cleanedassert "removed_tool_json" in result.actions- assert "Hier:" in result.cleaned- assert "Fertig" in result.cleaned+ assert "Hier:" in result.cleaned # i18n-allow+ assert "Fertig" in result.cleaned # i18n-allowdef test_generic_tool_call_tags_are_removed() -> None:- """``<tool_call>{}</tool_call>`` mit irgendwelchem Content — Re-Probe+ """``<tool_call>{}</tool_call>`` with arbitrary content — re-probe01/06/11."""text = (- 'Lass mich schauen. <tool_call>\n'+ 'Lass mich schauen. <tool_call>\n' # i18n-allow'}\n''</tool_call>\n''<tool_response>\n''{"status": "ok"}\n''</tool_response>\n'- '09:17 Uhr.'+ '09:17 Uhr.' # i18n-allow)result = scrub_for_voice(text)assert "<tool_call>" not in result.cleaned@@ -560,40 +561,41 @@ def test_generic_tool_call_tags_are_removed() -> None:assert "<tool_response>" not in result.cleanedassert "</tool_response>" not in result.cleanedassert "removed_tool_json" in result.actions- # Kerninhalt bleibt+ # Core content remainsassert "09:17" in result.cleaneddef test_base64_image_block_is_removed() -> None:- """Base64-Image-String (sehr lange ASCII-Sequenz) — Re-Probe 08."""- # Realistischer Trigger: data-URI mit langer Base64-Sequenz+ """Base64 image string (very long ASCII sequence) — re-probe 08."""+ # Realistic trigger: data-URI with a long base64 sequencetext = (- 'Hier das Bild: data:image/webp;base64,'+ 'Hier das Bild: data:image/webp;base64,' # i18n-allow+ 'A' * 800- + '. Fertig.'+ + '. Fertig.' # i18n-allow)result = scrub_for_voice(text)- # Base64-Block ist weg- assert ("A" * 200) not in result.cleaned, "Lange Base64-Sequenz nicht entfernt"+ # The base64 block is gone+ assert ("A" * 200) not in result.cleaned, "long base64 sequence not removed"assert "data:image" not in result.cleanedassert "removed_tool_json" in result.actions- assert "Fertig" in result.cleaned+ assert "Fertig" in result.cleaned # i18n-allowdef test_short_clean_alphanumeric_is_kept() -> None:- """Defense gegen Base64-False-Positive: kurze alphanumerische Strings- (z.B. Datei-Namen, Hashes, Tokens in normaler Kommunikation) bleiben."""- text = "Die Datei abc123def456 wurde gespeichert."+ """Defense against a base64 false positive: short alphanumeric strings+ (e.g. file names, hashes, tokens in normal communication) remain."""+ text = "Die Datei abc123def456 wurde gespeichert." # i18n-allowresult = scrub_for_voice(text)assert "abc123def456" in result.cleanedassert result.actions == []# ----------------------------------------------------------------------------# Phase-2-Anti-Pattern-Filter — die in voice_e2e_probe.py:ANTI_PATTERNS-# gelisteten Strings sollen vom Filter VOR der Probe-Heuristik gescrubbt-# werden, nicht nur als Probe-Detection-Pattern dienen. Sonst zaehlt jeder-# Brain-Output mit Anti-Pattern als DRIFT, obwohl der User es nie hoert.+# Phase-2 anti-pattern filter — the strings listed in+# voice_e2e_probe.py:ANTI_PATTERNS should be scrubbed by the filter BEFORE+# the probe heuristic runs, not merely serve as a probe-detection pattern.+# Otherwise every brain output containing an anti-pattern counts as DRIFT,+# even though the user never hears it.# ---------------------------------------------------------------------------@@ -604,19 +606,19 @@ def test_short_clean_alphanumeric_is_kept() -> None:("Let me think.", "It's halb drei."),])def test_filler_selbstreferenz_opener_is_removed(opener: str, rest: str) -> None:- """Phase-2-Anti-Pattern: 'Lass mich kurz' / 'Let me think' als Opener.+ """Phase-2 anti-pattern: 'Lass mich kurz' / 'Let me think' as an opener.- Diese Phrasen sind in voice_e2e_probe.py:ANTI_PATTERNS unter- 'Filler-Selbstreferenz' gelistet. Der Filter muss sie wegschneiden,- sonst loest die Probe-Heuristik einen DRIFT-Treffer aus, obwohl der- User die Phrase ohnehin nicht hoeren soll.+ These phrases are listed in voice_e2e_probe.py:ANTI_PATTERNS under+ 'Filler-Selbstreferenz'. The filter must cut them off, otherwise the+ probe heuristic triggers a DRIFT hit even though the user was never+ going to hear the phrase anyway."""text = f"{opener} {rest}"result = scrub_for_voice(text)low = result.cleaned.lower()assert "lass mich kurz" not in lowassert "let me think" not in low- # Kerninhalt (rest minus Opener-Komma) bleibt erhalten+ # Core content (rest minus the opener comma) is preservedrest_substantive = rest.split(".", 1)[-1].strip().lower()if rest_substantive:assert rest_substantive in low@@ -624,20 +626,20 @@ def test_filler_selbstreferenz_opener_is_removed(opener: str, rest: str) -> Nonedef test_filler_selbstreferenz_mid_sentence_is_kept() -> None:- """Failure-Mode-6-analog: mid-sentence 'lass mich kurz' bleibt erhalten.+ """Failure-mode-6 analog: mid-sentence 'lass mich kurz' is preserved.- Wenn der User wirklich darum bittet ('Schau dir das an, lass mich kurz- mal nachdenken, dann sage ich es dir'), darf der Filter das nicht- zerschiessen. Wie bei Echo-Paraphrase nur am Opener (<= 60 Zeichen).+ If the user genuinely asks for it ('Schau dir das an, lass mich kurz+ mal nachdenken, dann sage ich es dir'), the filter must not destroy+ it. Same as echo paraphrase: only at the opener (<= 60 characters)."""- # Mind. 61 Zeichen vor 'lass mich kurz' damit Failure-Mode-6 greift.+ # At least 61 characters before 'lass mich kurz' so failure-mode-6 applies.text = ("Ich gehe das systematisch durch, ""und im naechsten Schritt soll ich lass mich kurz nachdenken, ""und dann antworte ich.")pos = text.lower().find("lass mich kurz")- assert pos > 60, f"Test-Setup-Bug: pos={pos}"+ assert pos > 60, f"test-setup bug: pos={pos}"result = scrub_for_voice(text)assert "lass mich kurz" in result.cleaned.lower()@@ -645,25 +647,26 @@ def test_filler_selbstreferenz_mid_sentence_is_kept() -> None:# ----------------------------------------------------------------------------# Audit F-AUDIT-4 (2026-04-29): prosaisch geschriebene Tool-Args.-# Brain leakte in Probe-Run vom 2026-04-29 Szenario 07 wortlich:+# Audit F-AUDIT-4 (2026-04-29): tool args written as prose.+# The brain leaked, verbatim, in the 2026-04-29 probe run scenario 07:# "spawn_worker with utterance is Analysiere... context_hints is [...]# action is ... target is ..."-# Der Filter musste um dieses natuerlichsprachige Format erweitert werden.+# The filter had to be extended to cover this natural-language format.# ---------------------------------------------------------------------------def test_tool_call_prose_with_keys_is_removed() -> None:- """spawn_worker with utterance is X context_hints is Y → gescrubbt.+ """spawn_worker with utterance is X context_hints is Y → scrubbed.- Realistischer Probe-Output 2026-04-29 Szenario 07. Filter muss den- ganzen Tool-Call-Block bis Satzende rausschneiden. Resttext bleibt.+ Realistic probe output from 2026-04-29 scenario 07. The filter must+ cut the entire tool-call block up to the end of the sentence. The+ rest of the text remains."""text = (- "Okay. spawn_worker with utterance is Analysiere das gesamte "+ "Okay. spawn_worker with utterance is Analysiere das gesamte " # i18n-allow"Projektverzeichnis context_hints is Vollstaendige Projektstruktur "- "erfassen action is das Projekt analysiert target is Arbeitsordner. "- "Fertig."+ "erfassen action is das Projekt analysiert target is Arbeitsordner. " # i18n-allow+ "Fertig." # i18n-allow)result = scrub_for_voice(text)assert "spawn_worker" not in result.cleaned@@ -671,32 +674,32 @@ def test_tool_call_prose_with_keys_is_removed() -> None:assert "context_hints" not in result.cleanedassert "action is" not in result.cleanedassert "removed_tool_json" in result.actions- # Resttext bleibt+ # The rest of the text remainsassert "Okay" in result.cleaned- assert "Fertig" in result.cleaned+ assert "Fertig" in result.cleaned # i18n-allowdef test_tool_args_prose_without_tool_name_is_removed() -> None:- """'utterance is X' allein (ohne Tool-Name-Prefix) wird auch gescrubbt."""- text = "Ich versuche es. utterance is lies die Datei. Fertig."+ """'utterance is X' alone (without a tool-name prefix) is also scrubbed."""+ text = "Ich versuche es. utterance is lies die Datei. Fertig." # i18n-allowresult = scrub_for_voice(text)assert "utterance is" not in result.cleanedassert "removed_tool_json" in result.actions- assert "Ich versuche es" in result.cleaned- assert "Fertig" in result.cleaned+ assert "Ich versuche es" in result.cleaned # i18n-allow+ assert "Fertig" in result.cleaned # i18n-allowdef test_legitimate_is_sentence_is_kept() -> None:- """Defense gegen False-Positive: legitime 'X is Y'-Saetze bleiben.+ """Defense against a false positive: legitimate 'X is Y' sentences remain.- Wenn der User sagt 'Die Hauptstadt ist Paris', oder Brain antwortet- 'Es ist halb drei' — KEIN Match auf TOOL_ARGS_PROSE_RE, weil 'Die- Hauptstadt' und 'Es' keine Tool-Arg-Schluessel sind.+ If the user says 'Die Hauptstadt ist Paris', or the brain answers+ 'Es ist halb drei' — NO match on TOOL_ARGS_PROSE_RE, because 'Die+ Hauptstadt' and 'Es' are not tool-arg keys."""- text = "Es ist halb drei. Die Datei ist gespeichert."+ text = "Es ist halb drei. Die Datei ist gespeichert." # i18n-allowresult = scrub_for_voice(text)assert "ist halb drei" in result.cleaned- assert "Datei ist gespeichert" in result.cleaned+ assert "Datei ist gespeichert" in result.cleaned # i18n-allowassert "removed_tool_json" not in result.actions@@ -712,7 +715,7 @@ def test_legitimate_is_sentence_is_kept() -> None:def test_openclaw_brand_name_is_scrubbed() -> None:"""OpenClaw must NOT survive voice output anymore (2026-05-24 reversal)."""text = (- "Mach ich, ich lasse dafür einen OpenClaw-Subagent "+ "Mach ich, ich lasse dafür einen OpenClaw-Subagent " # i18n-allow"ein Hello-World-Programm schreiben.")result = scrub_for_voice(text)@@ -722,8 +725,8 @@ def test_openclaw_brand_name_is_scrubbed() -> None:def test_bare_subagent_still_scrubbed_without_brand_prefix() -> None:- """Bare 'Subagent' / 'Sub-Agent' ohne Brand-Praefix bleibt gescrubbt."""- text = "Ich aktiviere einen Subagent für die Aufgabe."+ """Bare 'Subagent' / 'Sub-Agent' without the brand prefix is still scrubbed."""+ text = "Ich aktiviere einen Subagent für die Aufgabe." # i18n-allowresult = scrub_for_voice(text)assert "Subagent" not in result.cleanedassert "removed_engineering_jargon" in result.actions@@ -731,15 +734,15 @@ def test_bare_subagent_still_scrubbed_without_brand_prefix() -> None:def test_openclaw_compound_prefix_stripped_but_noun_kept() -> None:"""'OpenClaw-Mission' -> 'Mission' (brand prefix removed, noun stays)."""- text = "Die OpenClaw-Mission ist fertig."+ text = "Die OpenClaw-Mission ist fertig." # i18n-allowresult = scrub_for_voice(text)assert "OpenClaw" not in result.cleanedassert "Mission" in result.cleaneddef test_openclaw_subagenten_plural_also_scrubbed() -> None:- """Plural 'OpenClaw-Subagenten' muss ebenfalls gescrubbt werden."""- text = "Mehrere OpenClaw-Subagenten arbeiten parallel."+ """The plural 'OpenClaw-Subagenten' must be scrubbed too."""+ text = "Mehrere OpenClaw-Subagenten arbeiten parallel." # i18n-allowresult = scrub_for_voice(text)assert "OpenClaw" not in result.cleanedassert "Subagenten" not in result.cleaned@@ -748,9 +751,9 @@ def test_openclaw_subagenten_plural_also_scrubbed() -> None:def test_scrub_strips_end_call_sentinel() -> None:from jarvis.speech.hangup import END_CALL_SIGNAL- result = scrub_for_voice(f"Bis später, Ruben. {END_CALL_SIGNAL}", language="de")+ result = scrub_for_voice(f"Bis später, Ruben. {END_CALL_SIGNAL}", language="de") # i18n-allowassert END_CALL_SIGNAL not in result.cleaned- assert result.cleaned.strip() == "Bis später, Ruben."+ assert result.cleaned.strip() == "Bis später, Ruben." # i18n-allowassert "stripped_end_signal" in result.actions@@ -765,7 +768,7 @@ def test_scrub_strips_end_call_sentinel() -> None:def test_http_url_is_stripped_from_voice() -> None:"""A spoken answer must never read out an http(s) URL."""- text = "Die Prüfung dauert 190 Minuten. Mehr unter https://www.km.bayern.de/schueler.html"+ text = "Die Prüfung dauert 190 Minuten. Mehr unter https://www.km.bayern.de/schueler.html" # i18n-allowresult = scrub_for_voice(text)assert "http" not in result.cleaned.lower()assert "km.bayern.de" not in result.cleaned.lower()@@ -797,7 +800,7 @@ def test_bare_www_domain_is_stripped_from_voice() -> None:def test_clean_answer_without_sources_is_untouched() -> None:"""Defense against false positives: a normal spoken answer with no URL /domain / SERP footer must pass through unchanged (no source-artifact pass)."""- text = "Morgen schreiben alle Realschüler in Bayern ihre Mathe-Abschlussprüfung."+ text = "Morgen schreiben alle Realschüler in Bayern ihre Mathe-Abschlussprüfung." # i18n-allowresult = scrub_for_voice(text)assert result.cleaned == textassert "removed_source_artifacts" not in result.actions@@ -897,16 +900,16 @@ def test_fallback_phrase_localized_to_spanish() -> None:def test_scrub_keeps_humanized_readback_with_quotes() -> None:"""No false positive: a clean readback that merely quotes a UI label (andcontains an apostrophe + colon-free) must pass through untouched."""- text = "Erledigt — die Einstellungen sind auf 'Bluetooth und Geräte' offen."+ text = "Erledigt — die Einstellungen sind auf 'Bluetooth und Geräte' offen." # i18n-allowresult = scrub_for_voice(text, language="de")assert result.fallback_used is False- assert "Bluetooth und Geräte" in result.cleaned+ assert "Bluetooth und Geräte" in result.cleaned # i18n-allowdef test_scrub_keeps_sentence_with_inline_brace_not_a_dump() -> None:"""A sentence that happens to mention a brace mid-text is NOT a dump (itdoes not OPEN with a container) — must pass."""- text = "Ich habe die Funktion test() geprüft, alles in Ordnung."+ text = "Ich habe die Funktion test() geprüft, alles in Ordnung." # i18n-allowresult = scrub_for_voice(text, language="de")assert result.fallback_used is Falseassert "test()" in result.cleaned or "test" in result.cleaned@@ -915,8 +918,8 @@ def test_scrub_keeps_sentence_with_inline_brace_not_a_dump() -> None:# ---------------------------------------------------------------------------# Raw shell / PowerShell command guard (live bug 2026-06-28): the fast tier# emitted a SendKeys PowerShell command as its reply and TTS read it aloud-# "mit Sonderzeichen und allem". A raw command is code, never a spoken-# sentence -> fail-closed to the standard phrase, like a stacktrace.+# "with special characters and everything". A raw command is code, never a+# spoken sentence -> fail-closed to the standard phrase, like a stacktrace.# ---------------------------------------------------------------------------SHELL_COMMAND_CASES = [@@ -945,10 +948,10 @@ def test_raw_shell_command_is_never_spoken(text: str) -> None:@pytest.mark.parametrize("clean",[- "Schau bitte im Browser-Verlauf nach.",+ "Schau bitte im Browser-Verlauf nach.", # i18n-allow"Das kostet 5-10 Euro.",- "Die E-Mail ist raus.",- "Ich habe die Datei gespeichert.",+ "Die E-Mail ist raus.", # i18n-allow+ "Ich habe die Datei gespeichert.", # i18n-allow"Ruf Anna an und sag ihr Bescheid.",],)diff --git a/tests/unit/brain/test_persona_loader.py b/tests/unit/brain/test_persona_loader.pyindex c5eac6a8f8..8d23c5aafc 100644--- a/tests/unit/brain/test_persona_loader.py+++ b/tests/unit/brain/test_persona_loader.py@@ -1,19 +1,19 @@-"""Unit-Tests für den Persona-Loader (`jarvis.brain.persona_loader`).+"""Unit tests for the persona loader (`jarvis.brain.persona_loader`).-Deckt ab:-- Extraktion des ersten Code-Fence nach `## System-Prompt`.-- Cache-Verhalten (lru_cache + invalidate).-- Fehlende Datei / fehlender Fence → leerer String (kein Raise).+Covers:+- Extraction of the first code fence after `## System-Prompt`.+- Cache behavior (lru_cache + invalidate).+- Missing file / missing fence → empty string (no raise)."""from __future__ import annotationsimport importlib.utilfrom pathlib import Path-# `jarvis.brain.__init__` zieht den BrainManager + Safety-Chain mit —-# letztere hat zur Refactor-Zeit WIP-Dependencies ausserhalb dieses Scopes.-# Der Persona-Loader selbst hat keine Brain-Imports, daher isolieren wir-# ihn mit `importlib.util` aus dem Datei-Pfad.+# `jarvis.brain.__init__` pulls in the BrainManager + safety chain —+# the latter had WIP dependencies outside this scope at refactor time.+# The persona loader itself has no brain imports, so we isolate it+# with `importlib.util` from the file path._loader_spec = importlib.util.spec_from_file_location("jarvis.brain.persona_loader",Path(__file__).resolve().parents[3]@@ -46,7 +46,7 @@ def test_extract_fence_returns_code_block_body() -> None:block = _extract_fence_after_marker(md)assert "You are JARVIS." in blockassert "Be concise." in block- # Quellen-Sektion danach darf nicht drin sein+ # The "Quellen" section after it must not be includedassert "Quellen" not in block@@ -76,10 +76,11 @@ def test_extract_fence_missing_fence_returns_empty() -> None:def test_load_persona_prompt_extracts_real_persona(monkeypatch) -> None:- """Integrationstest gegen die echte JARVIS_PERSONA.md im Repo.+ """Integration test against the real JARVIS_PERSONA.md in the repo.- Geprueft werden Sektionen, die seit Persona-Mandat-Phase-2 (2026-04-25)- in der MD live sind — kritisch fuer Hangup-Contract und Echo-Schutz.+ Checks sections that have been live in the MD since persona mandate+ phase 2 (2026-04-25) — critical for the hangup contract and echo+ protection."""invalidate_cache()try:@@ -94,16 +95,17 @@ def test_load_persona_prompt_extracts_real_persona(monkeypatch) -> None:assert "JARVIS" not in promptassert "voice companion" in promptassert "LANGUAGE POLICY" in prompt- # Mandat-Phase-2: ECHO-PARAPHRASE-Sektion direkt nach OUTPUT RULES+ # Mandate phase 2: ECHO-PARAPHRASE section right after OUTPUT RULESassert "ECHO-PARAPHRASE" in prompt- # Hangup-Contract muss im Persona-Block sein, sonst kommt er nie beim- # Brain an (Probe-Drift Szenario 10: 'Bis dann.' statt einem klaren Abschied).+ # The hangup contract must be in the persona block, otherwise it never+ # reaches the brain (probe drift scenario 10: 'Bis dann.' instead of a+ # clear farewell).# The farewell is now profile-name-driven — no hardcoded owner name.- assert "Goodbye" in prompt or "Auf Wiedersehen" in prompt+ assert "Goodbye" in prompt or "Auf Wiedersehen" in prompt # i18n-allowdef test_load_persona_prompt_missing_file_returns_empty(monkeypatch, tmp_path) -> None:- """Wenn die MD fehlt, liefert der Loader leeren String — kein Raise."""+ """When the MD is missing, the loader returns an empty string — no raise."""invalidate_cache()fake_missing = tmp_path / "does_not_exist.md"monkeypatch.setattr(pl, "_persona_md_path", lambda: fake_missing)@@ -114,7 +116,7 @@ def test_load_persona_prompt_missing_file_returns_empty(monkeypatch, tmp_path) -def test_load_persona_prompt_cache_reuses_read(monkeypatch, tmp_path) -> None:- """`load_persona_prompt` liest die Datei nur einmal pro Cache-Fenster."""+ """`load_persona_prompt` reads the file only once per cache window."""invalidate_cache()md_file = tmp_path / "JARVIS_PERSONA.md"md_file.write_text(@@ -124,12 +126,12 @@ def test_load_persona_prompt_cache_reuses_read(monkeypatch, tmp_path) -> None:try:first = load_persona_prompt()assert "First version." in first- # Datei ändern — ohne invalidate bleibt der Cache-Wert.+ # Change the file — without invalidate, the cached value stays.md_file.write_text("## System-Prompt\n```\nSecond version.\n```\n", encoding="utf-8")cached = load_persona_prompt()- assert cached == first # Cache-Hit+ assert cached == first # cache hitinvalidate_cache()fresh = load_persona_prompt()assert "Second version." in fresh@@ -138,7 +140,7 @@ def test_load_persona_prompt_cache_reuses_read(monkeypatch, tmp_path) -> None:def test_load_persona_prompt_crlf_normalized(monkeypatch, tmp_path) -> None:- """Windows-CRLF wird als LF verarbeitet."""+ """Windows CRLF is processed as LF."""invalidate_cache()md_file = tmp_path / "JARVIS_PERSONA.md"md_file.write_bytes(@@ -153,10 +155,10 @@ def test_load_persona_prompt_crlf_normalized(monkeypatch, tmp_path) -> None:def test_persona_loader_path_points_to_real_file() -> None:- """Sanity: Der Default-Pfad zeigt auf eine existierende Datei."""+ """Sanity: the default path points to an existing file."""path = pl._persona_md_path()assert isinstance(path, Path)- assert path.exists(), f"Erwartet: {path} existiert"+ assert path.exists(), f"expected: {path} exists"def test_persona_fence_carries_end_call_sentinel() -> None:diff --git a/tests/unit/brain/test_plausibility.py b/tests/unit/brain/test_plausibility.pyindex 3e1e6d7843..c7783acbf3 100644--- a/tests/unit/brain/test_plausibility.py+++ b/tests/unit/brain/test_plausibility.py@@ -1,17 +1,18 @@-"""Tests fuer ``jarvis.brain.plausibility.check_plausibility`` (Phase 4).+"""Tests for ``jarvis.brain.plausibility.check_plausibility`` (phase 4).-Persona-Mandat Phase 4: Vor jeder Tool-Execution mit ``risk_tier ∈ {ask,-monitor}`` prueft der Plausibility-Guard zwei Signale:+Persona mandate phase 4: before every tool execution with ``risk_tier ∈+{ask, monitor}``, the plausibility guard checks two signals:- - Whisper-Confidence des aktuellen Turns (``Transcript.confidence``)- - Wake-Time-Differenz (``wake_age_s`` seit letztem Wake-Trigger)+ - Whisper confidence of the current turn (``Transcript.confidence``)+ - Wake-time difference (``wake_age_s`` since the last wake trigger)-Bei niedriger Confidence (< Threshold) ODER stale Wake (> stale_seconds):- - ``ask``-Tier: zusaetzliche Voice-Bestaetigung (require_confirmation=True)- - ``monitor``-Tier: nur Log-Warning, kein Block (require_confirmation=False)+On low confidence (< threshold) OR a stale wake (> stale_seconds):+ - ``ask`` tier: additional voice confirmation (require_confirmation=True)+ - ``monitor`` tier: log-warning only, no block (require_confirmation=False)-Plausibility ist KEIN Risk-Tier — Whitelist-downgraded Tools (``safe``)-laufen weiter ohne Plausibility-Check, sonst ist die Whitelist sinnlos.+Plausibility is NOT a risk tier — whitelist-downgraded tools (``safe``)+keep running without a plausibility check, otherwise the whitelist would+be pointless."""from __future__ import annotations@@ -25,12 +26,12 @@ from jarvis.core.protocols import Transcriptdef _t(confidence: float | None) -> Transcript:- """Hilfs-Konstruktor fuer Test-Transcripts.+ """Helper constructor for test transcripts.- Akzeptiert ``None`` fuer Failure-Mode-3 (manche STT-Provider liefern- keine Confidence). ``Transcript`` ist als ``float`` typisiert, aber wir- castet defensiv — der Plausibility-Guard muss sowohl float als auch- None vertragen.+ Accepts ``None`` for failure mode 3 (some STT providers do not report+ a confidence). ``Transcript`` is typed as ``float``, but we cast+ defensively — the plausibility guard must tolerate both a float and+ None."""return Transcript(text="test",@@ -41,7 +42,7 @@ def _t(confidence: float | None) -> Transcript:# ----------------------------------------------------------------------------# 5 Cases aus dem Mandat+# 5 cases from the mandate# ---------------------------------------------------------------------------@@ -82,8 +83,8 @@ def test_low_confidence_stale_wake_ask_requires_confirmation() -> None:)assert decision.proceed is Trueassert decision.require_confirmation is True- # Low confidence dominiert ueber stale_wake — beides triggert, aber- # die Confidence-Diagnose ist informativer fuer Debugging.+ # Low confidence dominates over stale_wake — both trigger, but the+ # confidence diagnosis is more informative for debugging.assert decision.reason == "low_confidence_ask"@@ -101,7 +102,7 @@ def test_high_confidence_stale_wake_monitor_log_only() -> None:def test_low_confidence_safe_tier_passes_through() -> None:- """Case 5: low confidence + ANY + safe → durchwinken, Plausibility tut nichts."""+ """Case 5: low confidence + ANY + safe → waved through, plausibility does nothing."""decision = check_plausibility(tool_name="search_web",risk_tier="safe",@@ -114,16 +115,16 @@ def test_low_confidence_safe_tier_passes_through() -> None:# ----------------------------------------------------------------------------# Failure-Mode-3-Test: Transcript.confidence == None konservativ als 0.0+# Failure-mode-3 test: Transcript.confidence == None treated conservatively as 0.0# ---------------------------------------------------------------------------def test_none_confidence_treated_as_zero_for_ask_tier() -> None:- """``Transcript.confidence`` kann ``None`` sein (Failure-Mode 3 Mandat).+ """``Transcript.confidence`` can be ``None`` (failure-mode 3 mandate).- Konservative Behandlung: ``None`` → 0.0 → triggert require_confirmation- bei ``ask``-Tier. Verhindert, dass ein STT-Provider ohne Confidence-- Reporting die Plausibility-Schicht stillschweigend deaktiviert.+ Conservative handling: ``None`` → 0.0 → triggers require_confirmation+ at the ``ask`` tier. Prevents an STT provider without confidence+ reporting from silently disabling the plausibility layer."""decision = check_plausibility(tool_name="run_shell",@@ -137,7 +138,7 @@ def test_none_confidence_treated_as_zero_for_ask_tier() -> None:def test_none_confidence_treated_as_zero_for_monitor_tier() -> None:- """``None``-Confidence bei monitor → log-only, kein Block."""+ """``None`` confidence at monitor → log-only, no block."""decision = check_plausibility(tool_name="open_app",risk_tier="monitor",@@ -150,7 +151,7 @@ def test_none_confidence_treated_as_zero_for_monitor_tier() -> None:def test_no_transcript_treated_as_zero_confidence() -> None:- """Fehlender Transcript (None) wird wie None-Confidence behandelt."""+ """A missing transcript (None) is treated like a None confidence."""decision = check_plausibility(tool_name="run_shell",risk_tier="ask",@@ -163,12 +164,12 @@ def test_no_transcript_treated_as_zero_confidence() -> None:# ----------------------------------------------------------------------------# Konfigurierbarkeits-Tests: Threshold/Stale-Seconds aus Config+# Configurability tests: threshold/stale-seconds from config# ---------------------------------------------------------------------------def test_custom_confidence_threshold() -> None:- """Threshold von 0.8 (statt Default 0.5) macht 0.6 zu low_confidence."""+ """A threshold of 0.8 (instead of the default 0.5) makes 0.6 low_confidence."""from jarvis.core.config import BrainPlausibilityConfigcfg = BrainPlausibilityConfig(confidence_threshold=0.8)@@ -184,7 +185,7 @@ def test_custom_confidence_threshold() -> None:def test_custom_stale_wake_seconds() -> None:- """``stale_wake_seconds=10`` macht 15s zu stale, was bei monitor log-only triggert."""+ """``stale_wake_seconds=10`` makes 15s stale, which triggers log-only at monitor."""from jarvis.core.config import BrainPlausibilityConfigcfg = BrainPlausibilityConfig(stale_wake_seconds=10.0)@@ -201,12 +202,12 @@ def test_custom_stale_wake_seconds() -> None:# ----------------------------------------------------------------------------# Edge-Case: Confidence genau an der Schwelle.+# Edge case: confidence exactly at the threshold.# ---------------------------------------------------------------------------def test_confidence_exactly_at_threshold_passes() -> None:- """Confidence genau == Threshold gilt als ausreichend (>=, nicht >)."""+ """A confidence exactly == threshold counts as sufficient (>=, not >)."""decision = check_plausibility(tool_name="run_shell",risk_tier="ask",@@ -218,7 +219,7 @@ def test_confidence_exactly_at_threshold_passes() -> None:def test_wake_age_exactly_at_threshold_passes() -> None:- """Wake-Age genau == 30s gilt als nicht-stale (<=, nicht <)."""+ """A wake age exactly == 30s counts as not stale (<=, not <)."""decision = check_plausibility(tool_name="run_shell",risk_tier="ask",diff --git a/tests/unit/brain/test_plugin_relevance_wiring.py b/tests/unit/brain/test_plugin_relevance_wiring.pyindex 6524058590..115f5ff777 100644--- a/tests/unit/brain/test_plugin_relevance_wiring.py+++ b/tests/unit/brain/test_plugin_relevance_wiring.py@@ -19,7 +19,7 @@ def test_apply_plugin_relevance_drops_irrelevant():}for i in range(20):tools[f"github/tool_{i}"] = _T(f"github/tool_{i}")- out = mgr._apply_plugin_relevance("was habe ich heute für termine", tools)+ out = mgr._apply_plugin_relevance("was habe ich heute für termine", tools) # i18n-allowassert "run-shell" in outassert "google_calendar/list_events" in outassert not any(n.startswith("github/") for n in out)diff --git a/tests/unit/brain/test_plugin_tool_spawn_hide.py b/tests/unit/brain/test_plugin_tool_spawn_hide.pyindex dd27ce70f3..0b9c322f06 100644--- a/tests/unit/brain/test_plugin_tool_spawn_hide.py+++ b/tests/unit/brain/test_plugin_tool_spawn_hide.py@@ -2,10 +2,11 @@not spawn a worker that can't reach it.Forensic 2026-06-27 (voice 17:44): "Schau mal nach was in meinem Google Calendar-am 29. ist" spawned a worker ("umfangreicheres Stueck Arbeit") which has no-google_calendar tool (plugin tools are router-tier only, AP-5/AP-14) and answered-"kann ich nicht". ``_hide_spawn_when_plugin_tool_handles_turn`` drops the spawn-vehicles on a calendar (plugin-tool) turn so the router calls the tool inline."""+am 29. ist" (a German request to check the calendar) spawned a worker+("a larger chunk of work") which has no google_calendar tool (plugin tools are+router-tier only, AP-5/AP-14) and answered "I can't do that". ``_hide_spawn_when_+plugin_tool_handles_turn`` drops the spawn vehicles on a calendar (plugin-tool)+turn so the router calls the tool inline."""from __future__ import annotationsimport re@@ -33,7 +34,7 @@ def _surface() -> dict:def test_calendar_turn_hides_spawn_keeps_tool():m = _mgr()out = m._hide_spawn_when_plugin_tool_handles_turn(- _surface(), "Was habe ich heute für Termine?"+ _surface(), "Was habe ich heute für Termine?" # i18n-allow)assert "google_calendar" in outassert "search_web" in out # inline answer path stays open@@ -45,7 +46,7 @@ def test_exact_failing_utterance_now_hides_spawn():m = _mgr()out = m._hide_spawn_when_plugin_tool_handles_turn(_surface(),- "Schau mal bitte nach, was in meinem Google Calendar am 29. für Termine sind",+ "Schau mal bitte nach, was in meinem Google Calendar am 29. für Termine sind", # i18n-allow)assert "spawn_worker" not in out and "multi_spawn" not in outassert "google_calendar" in out@@ -54,7 +55,7 @@ def test_exact_failing_utterance_now_hides_spawn():def test_non_calendar_turn_keeps_spawn():m = _mgr()surface = _surface()- out = m._hide_spawn_when_plugin_tool_handles_turn(surface, "Erzähl mir einen Witz")+ out = m._hide_spawn_when_plugin_tool_handles_turn(surface, "Erzähl mir einen Witz") # i18n-allowassert out == surface # untouched — no plugin keyword matched@@ -82,6 +83,6 @@ def test_no_plugin_tool_in_surface_keeps_spawn():m = _mgr()surface = {"search_web": object(), "spawn_worker": object()}out = m._hide_spawn_when_plugin_tool_handles_turn(- surface, "Was habe ich heute für Termine?"+ surface, "Was habe ich heute für Termine?" # i18n-allow)assert "spawn_worker" in out # no calendar tool present => don't hidediff --git a/tests/unit/brain/test_provider_multimodal.py b/tests/unit/brain/test_provider_multimodal.pyindex 078c1d4d30..351bae99ec 100644--- a/tests/unit/brain/test_provider_multimodal.py+++ b/tests/unit/brain/test_provider_multimodal.py@@ -1,13 +1,13 @@-"""Multimodal-Encoding-Tests für Brain-Provider (Wave-1 B3).+"""Multimodal encoding tests for brain providers (wave-1 B3).-Testet dass BrainMessage.images korrekt in das jeweilige Provider--API-Format übersetzt wird:+Tests that BrainMessage.images is correctly translated into the+respective provider API format:- Anthropic: `{"type": "image", "source": {"type": "base64", ...}}`- Gemini: `{"inline_data": {"mime_type": ..., "data": ...}}`- OpenAI: `{"type": "image_url", "image_url": {"url": "data:<mime>;base64,..."}}`-Backwards-Compat: Messages ohne images müssen sich identisch zu vor-Wave-1 B3 verhalten (string content bleibt string).+Backwards compat: messages without images must behave identically to+before wave-1 B3 (string content stays a string)."""from __future__ import annotations@@ -24,16 +24,16 @@ def sample_block() -> ImageBlock:def test_anthropic_encodes_image_as_base64_source(sample_block):from jarvis.plugins.brain._anthropic_base import _to_anthropic_messages- msgs = (BrainMessage(role="user", content="was ist das?", images=(sample_block,)),)+ msgs = (BrainMessage(role="user", content="what is that?", images=(sample_block,)),)out = _to_anthropic_messages(msgs)assert len(out) == 1content = out[0]["content"]- assert isinstance(content, list), f"erwarte Blocks-Liste, got {type(content)}"- # Text-Block muss vorhanden sein+ assert isinstance(content, list), f"expected a block list, got {type(content)}"+ # A text block must be presenttext_block = next((b for b in content if b.get("type") == "text"), None)- assert text_block is not None, f"kein text-Block in {content}"- assert text_block["text"] == "was ist das?"- # Image-Block muss korrekt enkodiert sein+ assert text_block is not None, f"no text block in {content}"+ assert text_block["text"] == "what is that?"+ # The image block must be correctly encodedimg = next(b for b in content if b.get("type") == "image")assert img["source"]["type"] == "base64"assert img["source"]["media_type"] == "image/png"@@ -45,22 +45,22 @@ def test_anthropic_no_images_passes_string_through():msgs = (BrainMessage(role="user", content="hi"),)out = _to_anthropic_messages(msgs)- # Backwards-compat: wenn keine images, content bleibt string+ # Backwards compat: with no images, content stays a stringassert out[0]["content"] == "hi"def test_gemini_encodes_image_as_inline_data(sample_block):from jarvis.plugins.brain.gemini import _to_gemini_contents- msgs = (BrainMessage(role="user", content="frage", images=(sample_block,)),)+ msgs = (BrainMessage(role="user", content="question", images=(sample_block,)),)contents = _to_gemini_contents(msgs)assert len(contents) == 1parts = contents[0]["parts"]- # Text-Part + inline_data-Part+ # Text part + inline_data parttext_part = next((p for p in parts if isinstance(p, dict) and "text" in p), None)- assert text_part is not None and text_part["text"] == "frage"+ assert text_part is not None and text_part["text"] == "question"inline = next((p for p in parts if isinstance(p, dict) and "inline_data" in p), None)- assert inline is not None, f"kein inline_data in parts: {parts}"+ assert inline is not None, f"no inline_data in parts: {parts}"assert inline["inline_data"]["mime_type"] == "image/png"assert inline["inline_data"]["data"] == "AAAA"@@ -68,23 +68,23 @@ def test_gemini_encodes_image_as_inline_data(sample_block):def test_openai_encodes_image_as_image_url(sample_block):from jarvis.plugins.brain._openai_base import _to_openai_messages- msgs = (BrainMessage(role="user", content="frage", images=(sample_block,)),)+ msgs = (BrainMessage(role="user", content="question", images=(sample_block,)),)out = _to_openai_messages(msgs, None)- # Erstes Element ist evtl. ein system-Entry; such die user-Message+ # The first element may be a system entry; find the user messageuser_msg = next(m for m in out if m["role"] == "user")content = user_msg["content"]- assert isinstance(content, list), f"erwarte Blocks-Liste, got {type(content)}"- # Text-Block+ assert isinstance(content, list), f"expected a block list, got {type(content)}"+ # Text blocktext_block = next((b for b in content if b.get("type") == "text"), None)- assert text_block is not None and text_block["text"] == "frage"- # image_url als Data-URI+ assert text_block is not None and text_block["text"] == "question"+ # image_url as a data URIimg = next(b for b in content if b.get("type") == "image_url")assert img["image_url"]["url"].startswith("data:image/png;base64,")assert img["image_url"]["url"].endswith(",AAAA")def test_openai_no_images_passes_string_through():- """Backwards-Compat für OpenAI — string bleibt string ohne images."""+ """Backwards compat for OpenAI — string stays a string without images."""from jarvis.plugins.brain._openai_base import _to_openai_messagesmsgs = (BrainMessage(role="user", content="hi"),)@@ -94,17 +94,17 @@ def test_openai_no_images_passes_string_through():def test_openai_vision_unsupported_drops_images(sample_block, caplog):- """Wenn supports_vision=False → images werden verworfen + WARN geloggt."""+ """When supports_vision=False → images are dropped + a WARN is logged."""import loggingfrom jarvis.plugins.brain._openai_base import _to_openai_messages- msgs = (BrainMessage(role="user", content="frage", images=(sample_block,)),)+ msgs = (BrainMessage(role="user", content="question", images=(sample_block,)),)with caplog.at_level(logging.WARNING, logger="jarvis.plugins.brain._openai_base"):out = _to_openai_messages(msgs, None, supports_vision=False)user_msg = next(m for m in out if m["role"] == "user")- # Content ist jetzt plain-text-String (images gedroppt)- assert user_msg["content"] == "frage"+ # Content is now a plain-text string (images dropped)+ assert user_msg["content"] == "question"assert any("Vision-Support" in rec.message for rec in caplog.records), (- f"erwarte WARN-Log, got {[r.message for r in caplog.records]}"+ f"expected a WARN log, got {[r.message for r in caplog.records]}")diff --git a/tests/unit/brain/test_router_prompt_tool_parity.py b/tests/unit/brain/test_router_prompt_tool_parity.pyindex 87d7abbbd8..11dc26fc7f 100644--- a/tests/unit/brain/test_router_prompt_tool_parity.py+++ b/tests/unit/brain/test_router_prompt_tool_parity.py@@ -69,7 +69,7 @@ def test_prompt_routes_app_actions_to_computer_use() -> None:"router prompt no longer routes PC actions to computer_use.")# And it explicitly tells the model NOT to use the phantom open_app.- assert re.search(r"NICHT\s+open_app", SYSTEM_PROMPT), (+ assert re.search(r"NICHT\s+open_app", SYSTEM_PROMPT), ( # i18n-allow"router prompt should explicitly forbid open_app so the model uses ""computer_use for opening apps.")@@ -93,9 +93,9 @@ def test_search_web_is_a_real_router_tool_and_advertised() -> None:"visible inline path for news/knowledge questions and will fall ""back to spawning a worker mission for a single lookup.")- # The old phantom-era warning ("Es gibt KEIN search_web") must be gone —+ # The old phantom-era warning ("Es gibt KEIN search_web") must be gone — # i18n-allow# it would directly contradict the real function declaration.- assert not re.search(r"KEIN\s+search_web", SYSTEM_PROMPT), (+ assert not re.search(r"KEIN\s+search_web", SYSTEM_PROMPT), ( # i18n-allow"router prompt still claims search_web does not exist while the ""tool IS registered — contradictory instructions.")diff --git a/tests/unit/brain/test_router_vision.py b/tests/unit/brain/test_router_vision.pyindex 98961932b6..c7c2059f35 100644--- a/tests/unit/brain/test_router_vision.py+++ b/tests/unit/brain/test_router_vision.py@@ -1,11 +1,11 @@-"""Unit-Tests fuer RouterBrain Permanent-Vision-Inject (B5, Wave-2).--Deckt ab:-- Vision-Inject wenn Provider aktiv liefert genau einen ImageBlock-- Ohne Provider oder bei Pause: keine Images-- Exception im Provider -> Text-Only-Fallback, kein Crash-- `VisionInjected`-Event wird mit korrektem Hash/Bytes emittiert-- `SYSTEM_PROMPT` enthaelt die SCREEN-CONTEXT-Klausel+"""Unit tests for RouterBrain permanent vision inject (B5, wave 2).++Covers:+- Vision inject when the provider is active delivers exactly one ImageBlock+- No provider or paused: no images+- Exception in the provider -> text-only fallback, no crash+- The `VisionInjected` event is emitted with the correct hash/bytes+- `SYSTEM_PROMPT` contains the SCREEN-CONTEXT clause"""from __future__ import annotations@@ -82,7 +82,7 @@ class _NoopToolExecutor:class _RecordingDispatcher:- """Ersetzt den echten BrainDispatcher waehrend Tests."""+ """Replaces the real BrainDispatcher during tests."""def __init__(self) -> None:self.calls: list[dict[str, Any]] = []@@ -270,7 +270,7 @@ async def test_generate_flags_executed_desktop_action_tool() -> None:lambda _brain, *, tools_override=None: _AggDispatcher(requested="computer_use"))- await router.manager.generate("was ist das hier")+ await router.manager.generate("was ist das hier") # i18n-allowassert router.manager._last_turn_executed_action_tool is True@@ -284,7 +284,7 @@ async def test_generate_does_not_flag_non_action_tool() -> None:lambda _brain, *, tools_override=None: _AggDispatcher(requested="wiki_recall"))- await router.manager.generate("was ist das hier")+ await router.manager.generate("was ist das hier") # i18n-allowassert router.manager._last_turn_executed_action_tool is False@@ -303,12 +303,12 @@ async def test_generate_does_not_flag_requested_but_blocked_action_tool() -> Non))- await router.manager.generate("wie öffne ich Chrome?")+ await router.manager.generate("wie öffne ich Chrome?") # i18n-allowassert router.manager._last_turn_executed_action_tool is False# -----------------------------------------------------------------------# Vision-Inject Tests+# Vision-inject tests# ----------------------------------------------------------------------@@ -320,11 +320,11 @@ async def test_router_injects_image_when_provider_active() -> None:provider = _FakeVisionProvider(obs=obs)router, recorder = _build_router(vision_provider=provider)- [d async for d in router.handle("was ist das hier")]+ [d async for d in router.handle("was ist das hier")] # i18n-allowassert len(recorder.calls) == 1call = recorder.calls[0]- assert call["user_text"] == "was ist das hier"+ assert call["user_text"] == "was ist das hier" # i18n-allowimages = call["images"]assert isinstance(images, tuple)assert len(images) == 1@@ -369,7 +369,7 @@ async def test_router_continues_on_vision_failure(caplog: pytest.LogCaptureFixtuassert len(recorder.calls) == 1assert recorder.calls[0]["images"] == ()assert any(d.content for d in deltas)- assert any("Vision-Inject fehlgeschlagen" in rec.message for rec in caplog.records)+ assert any("Vision-Inject fehlgeschlagen" in rec.message for rec in caplog.records) # i18n-allow@pytest.mark.asyncio@@ -402,7 +402,7 @@ async def test_router_emits_vision_injected_event() -> None:# -----------------------------------------------------------------------# SYSTEM_PROMPT (grep-basiert)+# SYSTEM_PROMPT (grep-based)# ----------------------------------------------------------------------@@ -411,15 +411,15 @@ def test_system_prompt_contains_screen_context_section() -> None:def test_system_prompt_contains_context_not_task_clause() -> None:- assert "Bild ist Kontext, kein Auftrag" in SYSTEM_PROMPT+ assert "Bild ist Kontext, kein Auftrag" in SYSTEM_PROMPT # i18n-allowdef test_system_prompt_screen_context_before_action_section() -> None:- # Nach dem Pure-Delegator-Refactor (Commit e09780b7) heisst die Action-- # Sektion jetzt "DELEGATOR-PRINZIP" / "ENTSCHEIDUNGSTABELLE" statt des- # alten "Bei jeder Eingabe entscheidest"-Markers. Wichtig bleibt nur,- # dass SCREEN-CONTEXT VOR der Entscheidungs-Anweisung steht, damit der- # Router das Bild als Kontext kennt BEVOR er routet.+ # After the pure-delegator refactor (commit e09780b7) the action section+ # is now called "DELEGATOR-PRINZIP" / "ENTSCHEIDUNGSTABELLE" instead of+ # the old "Bei jeder Eingabe entscheidest" marker. What matters is only+ # that SCREEN-CONTEXT comes BEFORE the decision instruction, so the+ # router knows the image as context BEFORE it routes.idx_screen = SYSTEM_PROMPT.find("SCREEN-CONTEXT")idx_actions = SYSTEM_PROMPT.find("ENTSCHEIDUNGSTABELLE")assert idx_screen >= 0 and idx_actions >= 0@@ -427,7 +427,7 @@ def test_system_prompt_screen_context_before_action_section() -> None:# -----------------------------------------------------------------------# Helper-Function+# Helper function# ----------------------------------------------------------------------diff --git a/tests/unit/brain/test_search_web_freshness_doctrine.py b/tests/unit/brain/test_search_web_freshness_doctrine.pyindex 4563666fc6..bc522a7306 100644--- a/tests/unit/brain/test_search_web_freshness_doctrine.py+++ b/tests/unit/brain/test_search_web_freshness_doctrine.py@@ -46,7 +46,7 @@ def test_search_web_description_reserved_for_fresh_facts() -> None:)# The old over-eager evergreen triggers must be gone — these turned a plain# "explain X" / "what is X" question into a web search (Melbourne forensic).- assert "erklär mir x" not in desc and "erklaer mir x" not in desc, (+ assert "erklär mir x" not in desc and "erklaer mir x" not in desc, ( # i18n-allow"search_web description still advertises evergreen 'explain X' as a ""primary trigger — that is the over-eager research bug")diff --git a/tests/unit/brain/test_self_mod_tools.py b/tests/unit/brain/test_self_mod_tools.pyindex fa96281bfa..d793854b87 100644--- a/tests/unit/brain/test_self_mod_tools.py+++ b/tests/unit/brain/test_self_mod_tools.py@@ -1,12 +1,12 @@-"""Tests für die Self-Mod-Brain-Tools (Phase 7.3).--Plan-Akzeptanzkriterien §7.3:-- Tool-Calls funktionieren via Hauptjarvis-Brain-Manager (Adapter testbar- ohne LLM-Roundtrip — Defense-in-Depth gegen "trust the model output").-- `set_config_value` legt Pending an, schreibt nicht.-- SAFE-Tier wird automatisch konfirmiert ohne User-Interaktion.-- Pending läuft nach 5min ab.-- `get_config_value` für `security.admin_password_hash` wirft Forbidden.+"""Tests for the self-mod brain tools (Phase 7.3).++Plan acceptance criteria §7.3:+- Tool calls work via the Hauptjarvis brain manager (adapter testable+ without an LLM round-trip — defense-in-depth against "trust the model output").+- `set_config_value` creates a pending mutation, does not write.+- SAFE tier is auto-confirmed without user interaction.+- A pending mutation expires after 5min.+- `get_config_value` for `security.admin_password_hash` raises Forbidden."""from __future__ import annotations@@ -44,7 +44,7 @@ FIXTURE = (# -----------------------------------------------------------------------# Test-Fixtures+# Test fixtures# ----------------------------------------------------------------------@@ -106,7 +106,7 @@ def _read_audit(audit: SelfModAudit) -> list[dict]:def _make_ctx() -> ExecutionContext:- """Minimaler ExecutionContext-Stub — die Tools nutzen ihn nicht."""+ """Minimal ExecutionContext stub — the tools don't use it."""from uuid import uuid4return ExecutionContext(@@ -123,7 +123,7 @@ def _exec(tool: Any, args: dict[str, Any]) -> ToolResult:# -----------------------------------------------------------------------# Schema-Inspektion (Plan-§AD-9)+# Schema inspection (Plan-§AD-9)# ----------------------------------------------------------------------@@ -134,7 +134,7 @@ class TestSchemaCompliance:)def test_strict_mode_enabled(self, tool_cls: type) -> None:assert tool_cls.schema.get("strict") is True, (- f"{tool_cls.__name__} muss strict-Mode aktiviert haben"+ f"{tool_cls.__name__} must have strict mode enabled")@pytest.mark.parametrize(@@ -143,7 +143,7 @@ class TestSchemaCompliance:)def test_no_additional_properties(self, tool_cls: type) -> None:assert tool_cls.schema.get("additionalProperties") is False, (- f"{tool_cls.__name__} muss additionalProperties=false setzen"+ f"{tool_cls.__name__} must set additionalProperties=false")@pytest.mark.parametrize(@@ -151,7 +151,7 @@ class TestSchemaCompliance:[ListMutableSettingsTool, GetConfigValueTool, SetConfigValueTool],)def test_all_properties_required(self, tool_cls: type) -> None:- """Strict-Mode-Anforderung: alle Properties müssen in `required`."""+ """Strict-mode requirement: all properties must be in `required`."""properties = tool_cls.schema.get("properties", {})required = set(tool_cls.schema.get("required", []))property_names = set(properties.keys())@@ -172,7 +172,7 @@ class TestSchemaCompliance:) -> None:examples = tool_cls.schema.get("input_examples", [])assert len(examples) >= min_examples, (- f"{tool_cls.__name__}: nur {len(examples)} input_examples (Plan: ≥{min_examples})"+ f"{tool_cls.__name__}: only {len(examples)} input_examples (Plan: ≥{min_examples})")def test_self_mod_tool_names_constant(self) -> None:@@ -219,15 +219,15 @@ class TestListMutableSettings:def test_current_values_match_fixture(self, tools: dict[str, Any]) -> None:result = _exec(tools["list_mutable_settings"], {})by_path = {entry["path"]: entry for entry in result.output}- # Aus minimal_jarvis.toml:+ # From minimal_jarvis.toml:assert by_path["tts.provider"]["current_value"] == "gemini-flash-tts"assert by_path["tts.speed"]["current_value"] == 1.0assert by_path["profile.language"]["current_value"] == "de"def test_redacts_sensitive_paths_if_present(self) -> None:- """Defense-in-Depth: selbst wenn ein Forbidden-Pfad versehentlich- in ALLOWED landen würde, würde der current_value im Output redacted."""- # Synthetischer Test — direkte _maybe_redact-Funktion:+ """Defense-in-depth: even if a forbidden path accidentally+ ended up in ALLOWED, the current_value in the output would still be redacted."""+ # Synthetic test — direct _maybe_redact function call:from jarvis.brain.tools.self_mod_tools import _maybe_redactassert _maybe_redact("tts.provider", "elevenlabs") == "elevenlabs"@@ -301,8 +301,8 @@ class TestGetConfigValue:assert result.output["value"] is Nonedef test_security_path_returns_forbidden(self, tools: dict[str, Any]) -> None:- """Plan-§7.3-AC: get_config_value für security.admin_password_hash- wirft Forbidden."""+ """Plan-§7.3-AC: get_config_value for security.admin_password_hash+ raises Forbidden."""result = _exec(tools["get_config_value"],{"path": "security.admin_password_hash"},@@ -343,7 +343,7 @@ class TestSetConfigValue:fixture_path: Path,audit_log: SelfModAudit,) -> None:- """Plan-§7.3-AC: SAFE-Tier wird automatisch konfirmiert."""+ """Plan-§7.3-AC: SAFE tier is auto-confirmed."""result = _exec(tools["set_config_value"],{"path": "tts.speed", "new_value": 1.25, "reason": "test"},@@ -354,9 +354,9 @@ class TestSetConfigValue:assert out["risk_tier"] == "safe"assert out["applied"] is Trueassert out["backup_path"] is not None- # File wurde wirklich geschrieben+ # File was actually writtenassert _isolated_loader(fixture_path).tts.speed == 1.25- # Audit-Eintrag vom Writer+ # Audit entry from the writerentries = _read_audit(audit_log)assert len(entries) == 1assert entries[0]["ok"] is True@@ -367,7 +367,7 @@ class TestSetConfigValue:fixture_path: Path,pending_store: PendingMutationStore,) -> None:- """Plan-§7.3-AC: ASK-Tier legt Pending an, schreibt nicht."""+ """Plan-§7.3-AC: ASK tier creates a pending mutation, does not write."""original_bytes = fixture_path.read_bytes()result = _exec(tools["set_config_value"],@@ -383,9 +383,9 @@ class TestSetConfigValue:assert out["risk_tier"] == "ask"assert out["applied"] is Falseassert out["backup_path"] is None- # File unverändert+ # File unchangedassert fixture_path.read_bytes() == original_bytes- # Pending im Store+ # Pending mutation in the storeassert len(pending_store) == 1def test_ask_tier_pending_id_is_uuid(self, tools: dict[str, Any]) -> None:@@ -395,7 +395,7 @@ class TestSetConfigValue:tools["set_config_value"],{"path": "tts.provider", "new_value": "elevenlabs", "reason": ""},)- UUID(result.output["id"]) # darf nicht werfen+ UUID(result.output["id"]) # must not raisedef test_unknown_path_returns_path_not_allowed(self, tools: dict[str, Any]@@ -424,26 +424,26 @@ class TestSetConfigValue:def test_safe_tier_pre_validate_failure(self, tools: dict[str, Any], fixture_path: Path) -> None:- """Auto-Confirm + invalider Wert → Pre-Validate scheitert,- Tool gibt validate_failed zurück."""- # tts.speed ist SAFE, also auto-confirm. Float-Coercion fail mit non-numeric string.- # Aber Pydantic akzeptiert "1.25" → 1.25. Wir nutzen tts.provider als- # ASK-Tier-Beispiel, geht via SAFE/Auto-Pfad nicht.- # Stattdessen: tts.speed mit list-Wert (nicht durch Schema-Re-Validate- # gefangen, weil dict/list explizit ausgeschlossen). Wir nutzen- # einen Pfad-Test mit invalidem Bool-Wert für tts.provider (str-Field).- # Da provider ASK ist, gibt es kein Auto-Confirm — also auch kein- # Pre-Validate. → Test entfernt; siehe TestSetConfigValuePreValidate.+ """Auto-confirm + an invalid value → pre-validate fails,+ the tool returns validate_failed."""+ # tts.speed is SAFE, so auto-confirm. Float coercion fails with a non-numeric string.+ # But Pydantic accepts "1.25" → 1.25. We use tts.provider as an+ # ASK-tier example, which doesn't go through the SAFE/auto path.+ # Instead: tts.speed with a list value (not caught by schema+ # re-validate, since dict/list are explicitly excluded). We use+ # a path test with an invalid bool value for tts.provider (str field).+ # Since provider is ASK, there is no auto-confirm — so also no+ # pre-validate. → Test removed; see TestSetConfigValuePreValidate.original = fixture_path.read_bytes()- # Sanity: Test-Fixture intakt+ # Sanity: test fixture intactassert originaldef test_invalid_new_value_type_rejected_by_handler(self, tools: dict[str, Any]) -> None:- """Defense-in-Depth-Schema-Re-Validate (kein Vertrauen in Modell-Output)."""- # JSON-Schema akzeptiert strict nur primitive Types, aber das Modell könnte- # versuchen, ein dict zu schicken.+ """Defense-in-depth schema re-validate (no trust in model output)."""+ # JSON schema strict only accepts primitive types, but the model could+ # try to send a dict.result = _exec(tools["set_config_value"],{"path": "tts.provider", "new_value": {"a": 1}, "reason": ""},@@ -460,7 +460,7 @@ class TestSetConfigValue:# -----------------------------------------------------------------------# SAFE-Tier-Pre-Validate-Failure (echter PreValidateError-Pfad)+# SAFE-tier pre-validate failure (real PreValidateError path)# ----------------------------------------------------------------------@@ -468,16 +468,16 @@ class TestSetConfigValuePreValidate:def test_safe_tier_pre_validate_failure_returns_validate_failed(self, tools: dict[str, Any], fixture_path: Path) -> None:- """SAFE-Tier mit Wert, der Pydantic-Coercion sprengt.+ """SAFE tier with a value that blows up Pydantic coercion.- `tts.speed` ist `float`. Wir senden eine Boolean — Pydantic v2- akzeptiert bool als float-Coerce nicht in strict-Mode-Kontext, aber- Default ist lax. Bessere Strategie: extreme NaN-Werte gehen durch,- aber ein fixer Schema-Mismatch via Strict-Mode lässt sich provozieren.+ `tts.speed` is `float`. We send a boolean — Pydantic v2 does not+ accept bool as a float coerce in strict-mode context, but the+ default is lax. Better strategy: extreme NaN values pass through,+ but a fixed schema mismatch can be provoked via strict mode."""- # Pydantic akzeptiert bool→float (`True` → 1.0). Wir gehen einen- # anderen Weg: ein Tool-Setup mit forciertem Pre-Validate-Failure- # via patched JarvisConfig-Loader.+ # Pydantic accepts bool→float (`True` → 1.0). We take a+ # different route: a tool setup with a forced pre-validate failure+ # via a patched JarvisConfig loader.from unittest.mock import patchfrom jarvis.core.self_mod import schema as sm_schema # noqa: F401@@ -492,7 +492,7 @@ class TestSetConfigValuePreValidate:)assert result.success is Falseassert "validate_failed" in result.error- # File NICHT geschrieben+ # File NOT writtenassert _isolated_loader(fixture_path).tts.speed == 1.0@@ -516,7 +516,7 @@ class TestPendingStoreLifecycle:mutation_result = pending_store.confirm(pending_id)assert mutation_result.ok is Trueassert _isolated_loader(fixture_path).tts.provider == "elevenlabs"- # Pending wurde konsumiert+ # Pending mutation was consumedassert pending_store.get(pending_id) is Nonedef test_reject_does_not_persist(@@ -535,7 +535,7 @@ class TestPendingStoreLifecycle:pending_store.reject(pending_id)assert fixture_path.read_bytes() == original_bytesassert pending_store.get(pending_id) is None- # Audit-Eintrag mit error="rejected_by_user"+ # Audit entry with error="rejected_by_user"entries = _read_audit(audit_log)rejected = [e for e in entries if e.get("error") == "rejected_by_user"]assert len(rejected) == 1@@ -544,9 +544,9 @@ class TestPendingStoreLifecycle:self,writer: AtomicConfigWriter,) -> None:- """Plan-§7.3-AC: Pending läuft nach 5min ab.+ """Plan-§7.3-AC: pending mutation expires after 5min.- Wir setzen TTL klein und triggern cleanup.+ We set the TTL small and trigger cleanup."""from jarvis.core.self_mod import MutationRequest@@ -581,44 +581,44 @@ class TestPendingStoreLifecycle:)pending_id = __import__("uuid").UUID(result.output["id"])pending_store.reject(pending_id)- # Nochmal — darf nicht crashen+ # Again — must not crashpending_store.reject(pending_id)# -----------------------------------------------------------------------# Tool-Sichtbarkeit (Plan-§AD-2)+# Tool visibility (Plan-§AD-2)# ----------------------------------------------------------------------class TestToolVisibility:def test_self_mod_tools_only_in_router_loader(self) -> None:- """Plan-§AD-2: Self-Mod-Tools sind ausschliesslich im Router-Tier verdrahtet.-- Welle-4-Migration: vorher pruefte der Test ``SUB_TOOLS`` (Sub-Jarvis-- Tier-Tool-Set). Sub-Jarvis-Tier wurde durch die OpenClaw-Bridge- ersetzt (siehe docs/openclaw-bridge.md §11) — ``SUB_TOOLS`` ist- geloescht. Self-Mod-Tools werden jetzt im Router-Loader direkt- registriert (``factory.py:_load_tools_for_tier`` mit ``tier="router"``)- und der OpenClaw-Worker hat keinen Zugriff auf das Tool-Set des- Routers (Subprocess-Boundary).+ """Plan-§AD-2: self-mod tools are wired exclusively in the router tier.++ Wave-4 migration: previously the test checked ``SUB_TOOLS`` (the+ sub-Jarvis-tier tool set). The sub-Jarvis tier was replaced by the+ OpenClaw bridge (see docs/openclaw-bridge.md §11) — ``SUB_TOOLS``+ has been deleted. Self-mod tools are now registered directly in the+ router loader (``factory.py:_load_tools_for_tier`` with+ ``tier="router"``), and the OpenClaw worker has no access to the+ router's tool set (subprocess boundary)."""from jarvis.brain.factory import ROUTER_TOOLS, SELF_MOD_TOOL_NAMES_ROUTER- # Self-Mod-Tools sind explizit AUSSERHALB des entry_points-Sets,- # weshalb sie NICHT in ROUTER_TOOLS stehen — sie kommen ueber den- # separaten ``build_self_mod_tools()``-Pfad rein.+ # Self-mod tools are explicitly OUTSIDE the entry_points set,+ # which is why they are NOT in ROUTER_TOOLS — they come in via the+ # separate ``build_self_mod_tools()`` path.for tool_name in SELF_MOD_TOOL_NAMES:assert tool_name not in ROUTER_TOOLS, (- f"Self-Mod-Tool '{tool_name}' darf NICHT in ROUTER_TOOLS sein — "- f"sie werden separat ueber build_self_mod_tools() injected."+ f"Self-mod tool '{tool_name}' must NOT be in ROUTER_TOOLS — "+ f"it is injected separately via build_self_mod_tools().")assert tool_name in SELF_MOD_TOOL_NAMES_ROUTER, (- f"Self-Mod-Tool '{tool_name}' fehlt in SELF_MOD_TOOL_NAMES_ROUTER"+ f"Self-mod tool '{tool_name}' is missing from SELF_MOD_TOOL_NAMES_ROUTER")# -----------------------------------------------------------------------# build_self_mod_tools-Factory+# build_self_mod_tools factory# ----------------------------------------------------------------------@@ -643,7 +643,7 @@ class TestFactory:},)assert len(tools) == 3- # Smoke: list_mutable_settings funktioniert+ # Smoke test: list_mutable_settings worksresult = _exec(tools["list_mutable_settings"], {})assert result.success is True@@ -685,7 +685,7 @@ class TestFactory:# -----------------------------------------------------------------------# PendingMutation-Schema+# PendingMutation schema# ----------------------------------------------------------------------@@ -697,7 +697,7 @@ class TestPendingMutationSchema:tools["set_config_value"],{"path": "tts.provider", "new_value": "elevenlabs", "reason": ""},)- # Payload muss JSON-serialisierbar sein (für Anthropic-Tool-Use)+ # Payload must be JSON-serializable (for Anthropic tool use)json.dumps(result.output)def test_pending_mutation_pydantic_strict(self) -> None:diff --git a/tests/unit/brain/test_signalless_write_tool_hide.py b/tests/unit/brain/test_signalless_write_tool_hide.pyindex 2f3fda80c8..f5eea1c1b1 100644--- a/tests/unit/brain/test_signalless_write_tool_hide.py+++ b/tests/unit/brain/test_signalless_write_tool_hide.py@@ -61,7 +61,7 @@ def test_action_intent_keeps_the_write_tools():m = _mgr()m._turn_has_action_intent = lambda _t: True # type: ignore[method-assign]out = m._hide_action_tools_on_signalless_turn(- _surface(), "Trag meinen Urlaub in den Kalender ein"+ _surface(), "Trag meinen Urlaub in den Kalender ein" # i18n-allow)assert "google_calendar" in outassert "contact-upsert" in out@@ -74,7 +74,7 @@ def test_mandated_write_tool_is_exempt_say_do_stays_green():m = _mgr()m._evidence_required_tool = "wiki-ingest"out = m._hide_action_tools_on_signalless_turn(- _surface(), "Merk dir, dass ich nach Bora Bora will"+ _surface(), "Merk dir, dass ich nach Bora Bora will" # i18n-allow)assert "wiki-ingest" in out # the mandated tool survivesassert "contact-upsert" not in out # other write tools still hidden@@ -84,7 +84,7 @@ def test_explicit_subagent_vehicle_keeps_tools():m = _mgr()m._force_spawn_pattern = re.compile(r"deep dive|subagent", re.I)out = m._hide_action_tools_on_signalless_turn(- _surface(), "Mach einen deep dive und trag das ein"+ _surface(), "Mach einen deep dive und trag das ein" # i18n-allow)assert "spawn_worker" in outassert "google_calendar" in outdiff --git a/tests/unit/brain/test_skill_routing_guard.py b/tests/unit/brain/test_skill_routing_guard.pyindex 22191a8656..d4882d3d02 100644--- a/tests/unit/brain/test_skill_routing_guard.py+++ b/tests/unit/brain/test_skill_routing_guard.py@@ -369,7 +369,7 @@ async def test_no_skill_match_keeps_local_action_fast_path() -> None:# `plugin-discord` skill matched the bare word "Discord", suppressed the# deterministic Computer-Use fast path, and the turn fell through to a# tool-less CLI talker (antigravity) that hallucinated a permissions refusal-# ("ich habe keinen Zugriff auf Discord"). The user wanted it driven on+# ("ich habe keinen Zugriff auf Discord"). The user wanted it driven on # i18n-allow: verbatim quote of the hallucinated runtime output# screen — exactly what Computer-Use exists for. The fix: when the# deterministic local-action gate claims the turn as DIRECT/COMPUTER_USE,# the keyword-matched plugin skill stands down (sibling of the AD-S9@@ -385,7 +385,7 @@ def _seed_plugin_skill(tmp_path: Path, name: str, pattern: str) -> None:async def test_open_app_compound_stands_down_plugin_skill(tmp_path: Path) -> None:- """'Discord öffnen und ... raussuchen' is a Computer-Use intent: the+ """'Discord öffnen und ... raussuchen' is a Computer-Use intent: the # i18n-allow: quotes the German test utterance under testplugin-discord keyword match stands down so the local-action fast path(the COMPUTER_USE dispatch) runs instead of falling to the talker."""_seed_plugin_skill(tmp_path, "plugin-discord", "(discord)")@@ -403,7 +403,7 @@ async def test_open_app_compound_stands_down_plugin_skill(tmp_path: Path) -> Nonasync def test_plain_open_app_stands_down_plugin_skill(tmp_path: Path) -> None:- """Even a plain 'öffne Discord' (a DIRECT open) is owned by the+ """Even a plain 'öffne Discord' (a DIRECT open) is owned by the # i18n-allow: quotes the German test utterance under testdeterministic gate, not the keyword-matched plugin skill."""_seed_plugin_skill(tmp_path, "plugin-discord", "(discord)")m = _make_probe_manager()@@ -416,7 +416,7 @@ async def test_plain_open_app_stands_down_plugin_skill(tmp_path: Path) -> None:async def test_open_and_operate_stands_down_plugin_skill(tmp_path: Path) -> None:- """'öffne Spotify und spiel ...' is a compound open-and-operate+ """'öffne Spotify und spiel ...' is a compound open-and-operate # i18n-allow: quotes the German test utterance under testComputer-Use intent — the plugin-spotify keyword match stands down."""_seed_plugin_skill(tmp_path, "plugin-spotify", "(spotify)")m = _make_probe_manager()@@ -429,8 +429,8 @@ async def test_open_and_operate_stands_down_plugin_skill(tmp_path: Path) -> Noneasync def test_pure_dispatch_keeps_plugin_skill(tmp_path: Path) -> None:- """A pure dispatch with NO open/desktop-control verb ('schick eine- Discord-Nachricht') is genuine plugin work — the skill KEEPS the turn,+ """A pure dispatch with NO open/desktop-control verb ('schick eine # i18n-allow: quotes the German test utterance under test+ Discord-Nachricht') is genuine plugin work — the skill KEEPS the turn, # i18n-allow: quotes the German test utterance under testthe local-action fast path does NOT run (the stand-down is precise: itonly fires when the gate would handle the turn as DIRECT/COMPUTER_USE)."""_seed_plugin_skill(tmp_path, "plugin-discord", "(discord)")diff --git a/tests/unit/brain/test_smalltalk_tool_visibility.py b/tests/unit/brain/test_smalltalk_tool_visibility.pyindex 778bd82a6f..3c87ad6fdd 100644--- a/tests/unit/brain/test_smalltalk_tool_visibility.py+++ b/tests/unit/brain/test_smalltalk_tool_visibility.py@@ -2,7 +2,7 @@but KEEPS the read-only screenshot tool, so the brain can still look at the screenon demand (Wave 2) even when the turn was classified smalltalk — e.g. the live2026-05-31 failure "Hallo, lies mir vor was oben links steht" left the brain with-no screenshot tool and it could only stall ("ich schaue nach … einen Moment")."""+no screenshot tool and it could only stall ("ich schaue nach … einen Moment").""" # i18n-allow: verbatim quote of the hallucinated runtime outputfrom __future__ import annotationsfrom jarvis.brain.manager import BrainManagerdiff --git a/tests/unit/brain/test_system_prompt_name.py b/tests/unit/brain/test_system_prompt_name.pyindex 5f83b62e48..e83e254384 100644--- a/tests/unit/brain/test_system_prompt_name.py+++ b/tests/unit/brain/test_system_prompt_name.py@@ -8,7 +8,7 @@ directive.2026-06-29: the persona files were made name-neutral (no baked-in "Jarvis"), sothe identity directive is now emitted for EVERY resolved name except the neutral``Assistant`` fallback, and it no longer carries the old self-contradictory-"nicht Jarvis" anchor.+"nicht Jarvis" anchor. # i18n-allow: quotes the literal old system-prompt string"""from __future__ import annotations@@ -38,17 +38,17 @@ def test_wake_jarvis_gets_identity_directive_without_contradiction() -> None:prompt = _manager_with_name(wake_phrase="Hey Jarvis")._build_system_prompt()assert "Du bist Jarvis" in prompt# The persona is now name-neutral, so even a user-chosen "Jarvis" wake word- # gets a clean identity directive — never the old "Du heisst Jarvis — nicht- # Jarvis" self-contradiction.+ # gets a clean identity directive — never the old "Du heisst Jarvis — nicht # i18n-allow: quotes the literal old system-prompt string+ # Jarvis" self-contradiction. # i18n-allow: quotes the literal old system-prompt stringassert "DEIN NAME IST JARVIS" in prompt- assert "nicht Jarvis" not in prompt+ assert "nicht Jarvis" not in prompt # i18n-allow: literal system-prompt string matched in logicdef test_wake_phrase_micron_makes_assistant_micron() -> None:prompt = _manager_with_name(wake_phrase="Micron")._build_system_prompt()assert "Du bist Micron" in promptassert "DEIN NAME IST MICRON" in prompt- assert "nicht Jarvis" not in prompt+ assert "nicht Jarvis" not in prompt # i18n-allow: literal system-prompt string matched in logicdef test_wake_phrase_is_the_only_name_source() -> None:@@ -56,4 +56,4 @@ def test_wake_phrase_is_the_only_name_source() -> None:prompt = _manager_with_name(wake_phrase="Hey Computer")._build_system_prompt()assert "Du bist Computer" in promptassert "DEIN NAME IST COMPUTER" in prompt- assert "nicht Jarvis" not in prompt+ assert "nicht Jarvis" not in prompt # i18n-allow: literal system-prompt string matched in logicdiff --git a/tests/unit/brain/test_tool_use_loop.py b/tests/unit/brain/test_tool_use_loop.pyindex 7979525ff6..1958eb3c49 100644--- a/tests/unit/brain/test_tool_use_loop.py+++ b/tests/unit/brain/test_tool_use_loop.py@@ -41,7 +41,7 @@ class _Brain:"name": "dispatch_to_harness","input": {"harness": "computer-use",- "prompt": "Wie kann ich bei Windows reinzoomen?",+ "prompt": "Wie kann ich bei Windows reinzoomen?", # i18n-allow: simulated German user utterance under test},})@@ -64,7 +64,7 @@ async def test_how_to_question_blocks_side_effect_tool() -> None:result = await loop.run([],- user_utterance="Wie kann ich bei Windows reinzoomen?",+ user_utterance="Wie kann ich bei Windows reinzoomen?", # i18n-allow: simulated German user utterance under test)assert executor.calls == []diff --git a/tests/unit/brain/test_tool_use_loop_ack.py b/tests/unit/brain/test_tool_use_loop_ack.pyindex 3cd9fd03d7..0dbdf8dced 100644--- a/tests/unit/brain/test_tool_use_loop_ack.py+++ b/tests/unit/brain/test_tool_use_loop_ack.py@@ -72,7 +72,7 @@ class _TextOnlyBrain:async def complete(self, req: BrainRequest) -> AsyncIterator[BrainDelta]:self.requests.append(req)- yield BrainDelta(content="Hallo, was kann ich tun?")+ yield BrainDelta(content="Hallo, was kann ich tun?") # i18n-allow: simulated German assistant output under testyield BrainDelta(finish_reason="stop")diff --git a/tests/unit/brain/test_vision_context.py b/tests/unit/brain/test_vision_context.pyindex 8520bc98c5..7c07a57440 100644--- a/tests/unit/brain/test_vision_context.py+++ b/tests/unit/brain/test_vision_context.py@@ -1,9 +1,9 @@-"""Tests fuer ``jarvis.brain.vision_context`` (Phase 5).+"""Tests for ``jarvis.brain.vision_context`` (Phase 5).-Mandat-Anforderungen:- - 3 Cases: VS Code Foreground / Browser Foreground / Vision-Context disabled- - Failure-Mode 4: pywinauto-Crash -> kein Hint, kein Spawn-Block- - Latenz-Budget 250 ms — Timeout muss greifen+Mandate requirements:+ - 3 cases: VS Code foreground / browser foreground / vision-context disabled+ - Failure mode 4: pywinauto crash -> no hint, no spawn block+ - Latency budget 250 ms — timeout must kick in"""from __future__ import annotations@@ -22,7 +22,7 @@ from jarvis.core.protocols import Observation# ----------------------------------------------------------------------------# Helper: Fake VisionEngine mit kontrollierbaren Ergebnissen+# Helper: fake VisionEngine with controllable results# ---------------------------------------------------------------------------@@ -65,14 +65,14 @@ class _FakeEngine:def test_is_enabled_default_off(monkeypatch: pytest.MonkeyPatch) -> None:- """Default: kein ENV, kein Config-Flag -> deaktiviert."""+ """Default: no ENV, no config flag -> disabled."""monkeypatch.delenv("JARVIS_VISION_CONTEXT", raising=False)assert is_enabled() is Falseassert is_enabled(VisionContextConfig()) is Falsedef test_is_enabled_env_flag(monkeypatch: pytest.MonkeyPatch) -> None:- """``JARVIS_VISION_CONTEXT=1`` aktiviert Phase 5 ueber den Config-Flag hinaus."""+ """``JARVIS_VISION_CONTEXT=1`` enables Phase 5 regardless of the config flag."""monkeypatch.setenv("JARVIS_VISION_CONTEXT", "1")assert is_enabled() is Truemonkeypatch.setenv("JARVIS_VISION_CONTEXT", "true")@@ -82,27 +82,27 @@ def test_is_enabled_env_flag(monkeypatch: pytest.MonkeyPatch) -> None:def test_is_enabled_config_flag(monkeypatch: pytest.MonkeyPatch) -> None:- """``[vision].context_hint_on_spawn = true`` aktiviert Phase 5."""+ """``[vision].context_hint_on_spawn = true`` enables Phase 5."""monkeypatch.delenv("JARVIS_VISION_CONTEXT", raising=False)cfg = VisionContextConfig(context_hint_on_spawn=True)assert is_enabled(cfg) is True# ----------------------------------------------------------------------------# 3 Mandat-Cases: VS Code, Browser, Disabled+# 3 mandate cases: VS Code, browser, disabled# ---------------------------------------------------------------------------@pytest.mark.asyncioasync def test_vscode_foreground_yields_hint(monkeypatch: pytest.MonkeyPatch) -> None:- """VS Code Foreground + 'Bau ne Landingpage' -> hint enthaelt 'code'/'Visual Studio Code'."""+ """VS Code foreground + 'Bau ne Landingpage' -> hint contains 'code'/'Visual Studio Code'.""" # i18n-allow: quotes the German test utterance under testmonkeypatch.setenv("JARVIS_VISION_CONTEXT", "1")engine = _FakeEngine(window_title="phase5.py - Visual Studio Code",active_pid=4242,)- # psutil mocken — wir wollen kein echtes psutil-Lookup auf 4242.+ # Mock psutil — we don't want a real psutil lookup on 4242.import jarvis.brain.vision_context as modmonkeypatch.setattr(mod, "_process_name_for_pid", lambda pid: "Code.exe")@@ -115,7 +115,7 @@ async def test_vscode_foreground_yields_hint(monkeypatch: pytest.MonkeyPatch) ->@pytest.mark.asyncioasync def test_browser_foreground_yields_hint(monkeypatch: pytest.MonkeyPatch) -> None:- """Chrome Foreground + 'Recherchier X' -> hint enthaelt 'chrome'/'firefox'."""+ """Chrome foreground + 'Recherchier X' -> hint contains 'chrome'/'firefox'.""" # i18n-allow: quotes the German test utterance under testmonkeypatch.setenv("JARVIS_VISION_CONTEXT", "1")engine = _FakeEngine(window_title="ChatGPT - Google Chrome",@@ -134,10 +134,10 @@ async def test_browser_foreground_yields_hint(monkeypatch: pytest.MonkeyPatch) -async def test_vision_context_disabled_returns_none(monkeypatch: pytest.MonkeyPatch,) -> None:- """Default (kein ENV, kein Config-Flag) -> None, kein Engine-Call.+ """Default (no ENV, no config flag) -> None, no engine call.- Backward-Compat: ohne explizite Aktivierung kostet Phase 5 keinen- Latenz-Cycle.+ Backward-compat: without explicit activation, Phase 5 costs no+ latency cycle."""monkeypatch.delenv("JARVIS_VISION_CONTEXT", raising=False)engine = _FakeEngine(window_title="something", active_pid=1)@@ -153,7 +153,7 @@ async def test_vision_context_disabled_returns_none(@pytest.mark.asyncioasync def test_pywinauto_crash_returns_none(monkeypatch: pytest.MonkeyPatch) -> None:- """observe() crasht (Failure-Mode 4) -> kein Hint, kein Re-Raise."""+ """observe() crashes (failure mode 4) -> no hint, no re-raise."""monkeypatch.setenv("JARVIS_VISION_CONTEXT", "1")engine = _FakeEngine(crash=RuntimeError("pywinauto: GetForegroundWindow failed"))@@ -168,9 +168,9 @@ async def test_pywinauto_crash_returns_none(monkeypatch: pytest.MonkeyPatch) ->@pytest.mark.asyncioasync def test_timeout_returns_none(monkeypatch: pytest.MonkeyPatch) -> None:- """observe() haengt > timeout_s -> None, kein Hang."""+ """observe() hangs > timeout_s -> None, no hang."""monkeypatch.setenv("JARVIS_VISION_CONTEXT", "1")- # Fake-Engine mit 500 ms-Delay, Timeout auf 50 ms gesetzt.+ # Fake engine with a 500 ms delay, timeout set to 50 ms.engine = _FakeEngine(window_title="Slow App", active_pid=1, delay_s=0.5)cfg = VisionContextConfig(context_hint_on_spawn=True, timeout_s=0.05)@@ -179,13 +179,13 @@ async def test_timeout_returns_none(monkeypatch: pytest.MonkeyPatch) -> None:# ----------------------------------------------------------------------------# Edge-Cases+# Edge cases# ---------------------------------------------------------------------------@pytest.mark.asyncioasync def test_no_window_no_pid_returns_none(monkeypatch: pytest.MonkeyPatch) -> None:- """Observation ohne window_title und ohne pid -> None statt Pseudo-Hint."""+ """Observation without window_title and without pid -> None instead of a pseudo-hint."""monkeypatch.setenv("JARVIS_VISION_CONTEXT", "1")engine = _FakeEngine(window_title="", active_pid=None)hint = await get_active_window_hint(engine=engine)@@ -194,7 +194,7 @@ async def test_no_window_no_pid_returns_none(monkeypatch: pytest.MonkeyPatch) ->@pytest.mark.asyncioasync def test_window_only_no_process(monkeypatch: pytest.MonkeyPatch) -> None:- """Nur window_title verfuegbar -> hint ohne Process-Name."""+ """Only window_title available -> hint without a process name."""monkeypatch.setenv("JARVIS_VISION_CONTEXT", "1")engine = _FakeEngine(window_title="Nur Titel", active_pid=None)hint = await get_active_window_hint(engine=engine)diff --git a/tests/unit/brain/test_vision_gate.py b/tests/unit/brain/test_vision_gate.pyindex 79c9bb5de3..ada181cdd8 100644--- a/tests/unit/brain/test_vision_gate.py+++ b/tests/unit/brain/test_vision_gate.py@@ -19,12 +19,12 @@ from jarvis.brain.vision_gate import has_visual_marker, should_attach_screenshot_VISUAL = ["was siehst du hier","schau mal das hier",- "klick auf den Button",- "warum ist das rot?",+ "klick auf den Button", # i18n-allow: German speech-input test vocabulary+ "warum ist das rot?", # i18n-allow: German speech-input test vocabulary"lies mir die Fehlermeldung vor",- "was steht da auf dem Bildschirm",+ "was steht da auf dem Bildschirm", # i18n-allow: German speech-input test vocabulary"mach das Fenster zu",- "was ist das da",+ "was ist das da", # i18n-allow: German speech-input test vocabulary"klick das weg","look at this window",# live 2026-05-31 failures: spatial + read-out references the old list missed@@ -38,15 +38,15 @@ _VISUAL = [# even though they are not "smalltalk". This is the user's reported case._NON_VISUAL = ["was haben wir gerade besprochen?",- "erklär mir nochmal das Thema",- "erklär mir was ein vektor ist",- "wie spät ist es",- "was ist die Hauptstadt von Frankreich",- "warum ist das so wichtig?", # "warum ist das" is NOT a marker without a colour+ "erklär mir nochmal das Thema", # i18n-allow: German speech-input test vocabulary+ "erklär mir was ein vektor ist", # i18n-allow: German speech-input test vocabulary+ "wie spät ist es", # i18n-allow: German speech-input test vocabulary+ "was ist die Hauptstadt von Frankreich", # i18n-allow: German speech-input test vocabulary+ "warum ist das so wichtig?", # "warum ist das" is NOT a marker without a colour (i18n-allow)"fass das bitte zusammen","hallo jarvis","danke dir",- "wir hatten einen langen Dialog darüber", # "dialog" alone must NOT fire (DE = conversation)+ "wir hatten einen langen Dialog darüber", # "dialog" alone must NOT fire (DE = conversation) (i18n-allow)"was steht heute an?", # "steht an" = scheduled, NOT a screen read-out]@@ -66,9 +66,9 @@ def test_non_visual_skips(text: str) -> None:def test_visual_marker_detection_is_case_insensitive() -> None:- assert has_visual_marker("Was ist DAS HIER") is True+ assert has_visual_marker("Was ist DAS HIER") is True # i18n-allow: German speech-input test vocabularyassert has_visual_marker("look at this") is True- assert has_visual_marker("auf dem Bildschirm") is True+ assert has_visual_marker("auf dem Bildschirm") is True # i18n-allow: German speech-input test vocabularydef test_plain_text_has_no_marker() -> None:@@ -79,4 +79,4 @@ def test_plain_text_has_no_marker() -> None:def test_has_visual_marker_examples() -> None:assert has_visual_marker("klick drauf") is True- assert has_visual_marker("erklär mir das Thema") is False+ assert has_visual_marker("erklär mir das Thema") is False # i18n-allow: German speech-input test vocabularydiff --git a/tests/unit/brain/test_voice_command_gate.py b/tests/unit/brain/test_voice_command_gate.pyindex 026dd40f29..d620a211ff 100644--- a/tests/unit/brain/test_voice_command_gate.py+++ b/tests/unit/brain/test_voice_command_gate.py@@ -4,7 +4,7 @@ detector (wired via BrainManager._detect_switch_intent -> match_voice_command).Regression guard added 2026-06-08: a voice "switch the brain provider to X" wasNOT caught by the strict pattern (the "brain provider" filler between the verband "to" broke it), fell through to the router LLM, and the LLM — told in its-system prompt it had "no authority" to switch — refused with "keine Berechtigung".+system prompt it had "no authority" to switch — refused with "keine Berechtigung". # i18n-allow: verbatim quote of the hallucinated runtime outputThe gate must tolerate the natural "den/the [brain] provider/anbieter" filler."""from __future__ import annotations@@ -25,8 +25,8 @@ from jarvis.brain.voice_command_gate import match_voice_command("use openrouter", "openrouter"),# NEW: natural phrasings with a provider-noun filler("switch the brain provider to gemini", "gemini"),- ("wechsel den Brain-Provider auf gemini", "gemini"),- ("wechsel den Provider auf openrouter", "openrouter"),+ ("wechsel den Brain-Provider auf gemini", "gemini"), # i18n-allow: German speech-input test vocabulary+ ("wechsel den Provider auf openrouter", "openrouter"), # i18n-allow: German speech-input test vocabulary("wechsle den Anbieter zu openrouter", "openrouter"),("switch provider to claude", "claude"),("switch the provider to openai", "openai"),@@ -43,8 +43,8 @@ def test_provider_switch_matches(text: str, target: str) -> None:"text",["ich gehe auf meinem Weg",- "wie spät ist es",- "erzähl mir was über gemini", # a mention, not a switch command+ "wie spät ist es", # i18n-allow: German speech-input test vocabulary+ "erzähl mir was über gemini", # a mention, not a switch command (i18n-allow)# Grok was removed as a brain provider (only grok-voice TTS + the# grok_api_key credential remain), so it is no longer a recognized# brain/provider switch target — "switch to grok" must NOT match.@@ -85,17 +85,17 @@ def test_explicit_reply_language_switch_still_matches(text: str, target: str) ->def test_cancel_and_depth_still_work() -> None:assert match_voice_command("jarvis stopp").kind == "cancel"- assert match_voice_command("denk gründlich").kind == "depth_deep"+ assert match_voice_command("denk gründlich").kind == "depth_deep" # i18n-allow: German speech-input test vocabularyassert match_voice_command("nimm haiku").kind == "depth_fast"def test_subagent_switch_picks_target_after_preposition_not_source() -> None:- """ "von Antigravity auf Codex" must resolve to the TARGET (codex), not the+ """ "von Antigravity auf Codex" must resolve to the TARGET (codex), not the # i18n-allow: quotes the German test utterance under testmentioned SOURCE (antigravity). Forensic 2026-06-27: the alias-list-ORDERscan returned antigravity (it sits earlier in the list) so the worker wasswitched to the source the user was switching AWAY from."""m = match_voice_command(- "stell den subagent provider von antigravity auf codex um"+ "stell den subagent provider von antigravity auf codex um" # i18n-allow: German speech-input test vocabulary)assert m is not None and m.kind == "subagent_switch"assert m.target == "codex"@@ -103,20 +103,20 @@ def test_subagent_switch_picks_target_after_preposition_not_source() -> None:def test_subagent_switch_longest_alias_after_preposition() -> None:# "openai-codex" must win over its "openai"/"codex" substrings after the prep.- m = match_voice_command("wechsel den subagent von gemini auf openai-codex")+ m = match_voice_command("wechsel den subagent von gemini auf openai-codex") # i18n-allow: German speech-input test vocabularyassert m is not None and m.kind == "subagent_switch"assert m.target == "openai-codex"def test_subagent_switch_plain_target() -> None:- m = match_voice_command("stell den subagent provider auf gemini")+ m = match_voice_command("stell den subagent provider auf gemini") # i18n-allow: German speech-input test vocabularyassert m is not None and m.kind == "subagent_switch"assert m.target == "gemini"def test_main_provider_switch_from_x_to_y_targets_y() -> None:- # "von Gemini auf OpenAI" must target OpenAI (the destination), not fall through.- m = match_voice_command("wechsel von gemini auf openai")+ # "von Gemini auf OpenAI" must target OpenAI (the destination), not fall through. (i18n-allow)+ m = match_voice_command("wechsel von gemini auf openai") # i18n-allow: German speech-input test vocabularyassert m is not None and m.kind == "provider_switch"assert m.target == "openai"@@ -167,8 +167,8 @@ def test_cancel_recognizes_halt() -> None:def test_halt_midsentence_is_not_cancel() -> None:- # "das ist halt so" must NOT cancel — halt only at sentence start / after jarvis- m = match_voice_command("das ist halt so")+ # "das ist halt so" must NOT cancel — halt only at sentence start / after jarvis (i18n-allow)+ m = match_voice_command("das ist halt so") # i18n-allow: German speech-input test vocabularyassert m is None or m.kind != "cancel"@@ -176,7 +176,7 @@ def test_language_switch_picks_first_language_in_text_not_dict_order() -> None:# "deutsch" appears before "englisch" in the sentence, so the reply language# must be German — not English just because "englisch" sits earlier in the# alias dict (forensic 2026-06-27).- m = match_voice_command("antworte auf deutsch und englisch")+ m = match_voice_command("antworte auf deutsch und englisch") # i18n-allow: German speech-input test vocabularyassert m is not None and m.kind == "language_switch"assert m.target == "de"diff --git a/tests/unit/brain/voice_command_cases.py b/tests/unit/brain/voice_command_cases.pyindex cad945175f..1fbb435662 100644--- a/tests/unit/brain/voice_command_cases.py+++ b/tests/unit/brain/voice_command_cases.py@@ -10,14 +10,14 @@ RECOGNITION_CASES: list[tuple[str, str, str]] = [# provider_switch("wechsel auf gemini", "provider_switch", "gemini"),("switch to openai", "provider_switch", "openai"),- ("wechsel von gemini auf openai", "provider_switch", "openai"),+ ("wechsel von gemini auf openai", "provider_switch", "openai"), # i18n-allow: fixture("switch from claude to gemini", "provider_switch", "gemini"),("nutze chatgpt", "provider_switch", "chatgpt"),("switch to anthropic", "provider_switch", "anthropic"),("ändere den Provider auf gemini", "provider_switch", "gemini"), # i18n-allow: fixture("stell den Provider auf claude", "provider_switch", "claude"), # i18n-allow: fixture# subagent_switch- ("stell den subagent provider auf gemini", "subagent_switch", "gemini"),+ ("stell den subagent provider auf gemini", "subagent_switch", "gemini"), # i18n-allow: fixture("stell den subagent provider von antigravity auf codex um", "subagent_switch", "codex"), # i18n-allow: fixture# language_switch("stell auf Englisch um", "language_switch", "en"), # i18n-allow: fixturediff --git a/tests/unit/browser_voice/test_session.py b/tests/unit/browser_voice/test_session.pyindex f7972a0360..834609893f 100644--- a/tests/unit/browser_voice/test_session.py+++ b/tests/unit/browser_voice/test_session.py@@ -69,7 +69,7 @@ def _make_session(sink, *, stt=None, brain=None, tts=None, rate=STT_SAMPLE_RATE,session_id="bv1",send_binary=sink.send_binary,send_json=sink.send_json,- stt=stt or FakeSTT(["Wie spät ist es?"]),+ stt=stt or FakeSTT(["Wie spät ist es?"]), # i18n-allow: simulated German STT transcript under testbrain=brain or FakeBrain("Es ist vierzehn Uhr."),tts=tts or FakeTTS(ms_per_char=2),browser_sample_rate=rate,diff --git a/tests/unit/channels/test_manager.py b/tests/unit/channels/test_manager.pyindex e70b0cf6f3..4b7fbb49a3 100644--- a/tests/unit/channels/test_manager.py+++ b/tests/unit/channels/test_manager.py@@ -1,5 +1,5 @@# === F-FRIENDS [F0] · feature/friends-section · ruben-2026-04-30 ===-"""Unit-Tests fuer :class:`jarvis.channels.manager.ChannelManager`."""+"""Unit tests for :class:`jarvis.channels.manager.ChannelManager`."""from __future__ import annotationsfrom collections.abc import AsyncIterator@@ -140,7 +140,7 @@ def test_discovery_failed_load_isolated(monkeypatch: pytest.MonkeyPatch) -> Nonedef test_get_unknown_channel_raises_keyerror(monkeypatch: pytest.MonkeyPatch) -> None:_patch_entry_points(monkeypatch, [])mgr = ChannelManager(ChannelContext(bus=EventBus()))- with pytest.raises(KeyError, match="not.+verfuegbar|nicht verfuegbar"):+ with pytest.raises(KeyError, match="not.+verfuegbar|nicht verfuegbar"): # i18n-allow: matches the real (German) exception message stringmgr.get("nonexistent")diff --git a/tests/unit/channels/test_telegram_channel.py b/tests/unit/channels/test_telegram_channel.pyindex fa9fe5bc20..ff544a1097 100644--- a/tests/unit/channels/test_telegram_channel.py+++ b/tests/unit/channels/test_telegram_channel.py@@ -1,8 +1,8 @@# === F-FRIENDS [F1] · feature/friends-section · ruben-2026-04-30 ===-"""Unit-Tests fuer :class:`jarvis.channels.telegram.TelegramChannel`.+"""Unit tests for :class:`jarvis.channels.telegram.TelegramChannel`.-Strategie: keine echte ``python-telegram-bot``-Lib noetig im Test-Pfad —-wir testen mit Mock-Update- und Bot-Objekten und manueller Instanziierung.+Strategy: no real ``python-telegram-bot`` lib needed in the test path —+we test with mock update/bot objects and manual instantiation."""from __future__ import annotations@@ -372,7 +372,7 @@ async def test_on_bus_event_ignores_unknown_trace() -> None:async def test_on_bus_event_routes_known_trace() -> None:cfg = TelegramConfig(enabled=True, allowed_user_ids=[100])ch = _make_channel(cfg)- evt = ResponseGenerated(text="Antwort fuer dich", language="de")+ evt = ResponseGenerated(text="Antwort fuer dich", language="de") # i18n-allow: simulated German assistant output under a "de" language keych._inflight.set(evt.trace_id, 42) # noqa: SLF001await ch._on_bus_event(evt) # noqa: SLF001ch._app.bot.send_message.assert_awaited_once() # noqa: SLF001diff --git a/tests/unit/clis/test_seed_catalog_capabilities.py b/tests/unit/clis/test_seed_catalog_capabilities.pyindex 3a8d778d09..5385025998 100644--- a/tests/unit/clis/test_seed_catalog_capabilities.py+++ b/tests/unit/clis/test_seed_catalog_capabilities.py@@ -37,7 +37,7 @@ def test_curated_entries_have_read_only_whitelist():def test_gcloud_vocabulary_resolves_cost_and_overview_phrasings():- """Live transcript 2026-06-10 19:05: 'guck mit der Google CLI ... Kosten'+ """Live transcript 2026-06-10 19:05: 'guck mit der Google CLI ... Kosten' # i18n-allow: verbatim quote of the live German user utteranceforce-spawned a sub-agent mission because the gcloud capability vocabularymissed 'gucken', 'Kosten', and 'Google CLI'. These phrasings must resolveinline now."""@@ -49,8 +49,8 @@ def test_gcloud_vocabulary_resolves_cost_and_overview_phrasings():reg = CapabilityRegistry()reg.register(cap)for utterance in [- "Guck mit der Google CLI, was meine Kosten machen",- "Schau mal in die Google Cloud, was gerade los ist",+ "Guck mit der Google CLI, was meine Kosten machen", # i18n-allow: German speech-input test vocabulary+ "Schau mal in die Google Cloud, was gerade los ist", # i18n-allow: German speech-input test vocabulary"Zeig mir meine Google-Kosten","Check mal mein Billing","Zeig mir meine Google-Projekte",diff --git a/tests/unit/clis/test_seed_catalog_display.py b/tests/unit/clis/test_seed_catalog_display.pyindex b259d790a3..25b0fa7175 100644--- a/tests/unit/clis/test_seed_catalog_display.py+++ b/tests/unit/clis/test_seed_catalog_display.py@@ -3,7 +3,7 @@The CLI section renders ``display_name`` as the primary card title, so everyentry must carry a name a non-expert can recognize. The Google entries arepinned explicitly because they are the ones users failed to recognize-("gcloud"? "GAM"?). ASCII umlaut substitutes ("fuer") and German fragments+("gcloud"? "GAM"?). ASCII umlaut substitutes ("fuer") and German fragments # i18n-allow: cites the literal forbidden tokens checked below("uvm.", "Env-Variablen") are rejected because user-facing catalog stringsmust be clean English (Output Language Policy)."""@@ -16,7 +16,7 @@ from jarvis.clis.catalog import SEED_CATALOG_PATH, load_catalog# Tokens that only appear in broken ASCII-umlaut German or German fragments._FORBIDDEN_TOKENS = re.compile(- r"\b(fuer|ueber|loeschen|uvm|eintraege|variablen)\b", re.IGNORECASE+ r"\b(fuer|ueber|loeschen|uvm|eintraege|variablen)\b", re.IGNORECASE # i18n-allow: German fragment tokens matched in logic)diff --git a/tests/unit/conductor/test_core.py b/tests/unit/conductor/test_core.pyindex f77cb78ccf..db8f7a2700 100644--- a/tests/unit/conductor/test_core.py+++ b/tests/unit/conductor/test_core.py@@ -49,7 +49,7 @@ async def test_store_upsert_and_list(store: ConductorStore) -> None:async def test_store_denormalized_fields(store: ConductorStore) -> None:- """Cron-Expression und Webhook-Token müssen separat queryable sein."""+ """Cron expression and webhook token must be separately queryable."""cron_job = Job(name="Cron",spec=ShellJobSpec(command="echo cron"),@@ -177,7 +177,7 @@ async def test_http_handler_status_mismatch(monkeypatch: pytest.MonkeyPatch) ->async def test_agent_handler_no_api_key(monkeypatch: pytest.MonkeyPatch) -> None:- """Ohne ANTHROPIC_API_KEY muss der Agent einen klaren Fehler liefern."""+ """Without ANTHROPIC_API_KEY the agent must return a clear error."""from conductor.jobs.agent import AgentHandlermonkeypatch.delenv("ANTHROPIC_API_KEY", raising=False)spec = AgentJobSpec(@@ -191,7 +191,7 @@ async def test_agent_handler_no_api_key(monkeypatch: pytest.MonkeyPatch) -> Noneasync def test_agent_gemini_no_api_key(monkeypatch: pytest.MonkeyPatch) -> None:- """Kein GEMINI_API_KEY → klarer Fehler mit aistudio-Link."""+ """No GEMINI_API_KEY → clear error with an aistudio link."""from conductor.jobs.agent import AgentHandlerfor k in ("GEMINI_API_KEY", "GOOGLE_AIStudio_API_KEY", "GOOGLE_API_KEY"):monkeypatch.delenv(k, raising=False)@@ -227,7 +227,7 @@ async def test_agent_gemini_default_model_is_3_1_pro() -> None:async def test_agent_anthropic_missing_binary(monkeypatch: pytest.MonkeyPatch,) -> None:- """Wenn 'claude' nicht im PATH: sauberer Fehler mit Setup-Hint."""+ """When 'claude' is not on PATH: clean error with a setup hint."""from conductor.jobs.agent import AgentHandlermonkeypatch.setattr("shutil.which", lambda name: None)spec = AgentJobSpec(@@ -254,9 +254,9 @@ async def test_agent_anthropic_missing_binary(async def test_agent_anthropic_parses_json_output(monkeypatch: pytest.MonkeyPatch, tmp_path: Path,) -> None:- """Wir mocken 'claude' durch ein kleines Python-Script, das exakt das- JSON-Format von --output-format=json zurueckgibt (Feld 'result').- Der Handler muss es parsen und die Text-Antwort als output liefern."""+ """We mock 'claude' with a small Python script that returns exactly the+ JSON format of --output-format=json (field 'result').+ The handler must parse it and return the text answer as output."""import jsonimport sysfrom conductor.jobs.agent import AgentHandler@@ -307,7 +307,7 @@ async def test_agent_anthropic_parses_json_output(async def test_agent_handler_template_expansion(monkeypatch: pytest.MonkeyPatch,) -> None:- """``{{input.X}}`` muss vor dem LLM-Call expandiert werden."""+ """``{{input.X}}`` must be expanded before the LLM call."""from conductor.jobs.agent import _expand_templateout = _expand_template("Hallo {{input.name}}, analysiere {{input.topic}}",@@ -360,7 +360,7 @@ async def test_runner_shell_end_to_end(# ---------------------------------------------------------------------async def test_seed_yaml_loads(store: ConductorStore) -> None:- """Die 4 Seed-YAMLs werden ohne Fehler geparst + persistiert."""+ """The 4 seed YAMLs are parsed and persisted without error."""added = await ensure_seed_jobs(store)assert added >= 3 # Mindestens 3, wir haben aktuell 4rows = await store.list_jobs()diff --git a/tests/unit/control/test_cancel.py b/tests/unit/control/test_cancel.pyindex 9a53298924..bf2df95698 100644--- a/tests/unit/control/test_cancel.py+++ b/tests/unit/control/test_cancel.py@@ -1,4 +1,4 @@-"""Unit-Tests fuer CancelToken + CancelScope + KillSwitch (ADR-0004)."""+"""Unit tests for CancelToken + CancelScope + KillSwitch (ADR-0004)."""from __future__ import annotationsimport asyncio@@ -23,7 +23,7 @@ async def test_cancel_sets_state_and_first_reason_wins():assert tok.is_cancelled()assert tok.reason == "budget_task_exceeded"- tok.cancel("kill_switch:hotkey") # sollte ignoriert werden+ tok.cancel("kill_switch:hotkey") # should be ignoredassert tok.reason == "budget_task_exceeded"@@ -59,7 +59,7 @@ async def test_cancel_scope_registers_and_releases_token():assert tokens[0][1] == "test_holder"assert tokens[0][0] is token- # nach Exit muss der Token weg sein+ # after exit the token must be goneassert list(ks.active_tokens()) == []@@ -76,7 +76,7 @@ async def test_cancel_scope_releases_on_exception():@pytest.mark.asyncioasync def test_cancel_scope_without_kill_switch_still_works():- """Ein Scope ohne KillSwitch ist legal (z.B. fuer Isolation in Tests)."""+ """A scope without a KillSwitch is legal (e.g. for isolation in tests)."""async with CancelScope(None, holder="orphan") as token:assert not token.is_cancelled()token.cancel("manual")@@ -151,19 +151,19 @@ async def test_bind_is_idempotent_per_bus():bus = EventBus()ks = KillSwitch()ks.bind(bus)- ks.bind(bus) # zweimal — darf nicht doppelt subscriben+ ks.bind(bus) # twice — must not subscribe twiceasync with CancelScope(ks, holder="x") as tok:await bus.publish(KillRequested(source="tray"))await asyncio.sleep(0)- # Nur ein cancel-Call gemacht worden — trotzdem is_cancelled True.+ # Only one cancel call was made — is_cancelled is still True.assert tok.is_cancelled()@pytest.mark.asyncioasync def test_forward_kill_bridges_between_busses():- """Zwei-Bus-Problem aus CLAUDE.md: KillSwitch kann ein Event aus Bus A- nach Bus B weiterleiten.+ """Two-bus problem from CLAUDE.md: KillSwitch can forward an event from+ bus A to bus B."""ui_bus = EventBus()brain_bus = EventBus()diff --git a/tests/unit/control/test_cost_meter.py b/tests/unit/control/test_cost_meter.pyindex 98281647a0..87f0aee9e0 100644--- a/tests/unit/control/test_cost_meter.py+++ b/tests/unit/control/test_cost_meter.py@@ -1,4 +1,4 @@-"""Unit-Tests fuer CostMeter (ADR-0006)."""+"""Unit tests for CostMeter (ADR-0006)."""from __future__ import annotationsimport asyncio@@ -32,7 +32,7 @@ def _make_config(**overrides) -> BudgetConfig:"per_day_eur": 30.0,"cooldown_minutes": 60,"warn_at_fraction": 0.8,- "eur_per_usd": 1.0, # 1:1 fuer einfachere Arithmetik+ "eur_per_usd": 1.0, # 1:1 for simpler arithmetic"prices": {"test-model": ModelPrice(usd_per_1m_input=1.0,@@ -84,7 +84,7 @@ def test_disabled_config_never_trips(tmp_path):meter = _make_meter(tmp_path, _make_config(enabled=False))tid = uuid4()meter.start(tid, "claude-api", "test-model")- meter.add(_record(tid, 100.0)) # massiv ueber jedem Limit+ meter.add(_record(tid, 100.0)) # massively over every limitassert meter.over_task_budget(tid) is Falseassert meter.over_daily_budget() is False@@ -117,8 +117,8 @@ async def test_task_budget_trip_fires_exceeded_and_cancels_token(tmp_path):async with CancelScope(ks, holder="brain_stream") as token:tid = uuid4()meter.start(tid, "claude-api", "test-model")- meter.add(_record(tid, 2.5)) # direkt ueber per_task_eur=2.0- # Events sind async dispatched+ meter.add(_record(tid, 2.5)) # directly over per_task_eur=2.0+ # Events are dispatched asyncfor _ in range(5):await asyncio.sleep(0)@@ -141,7 +141,7 @@ async def test_warning_at_80_percent(tmp_path):tid = uuid4()meter.start(tid, "claude-api", "test-model")- meter.add(_record(tid, 1.7)) # 85% von 2.0+ meter.add(_record(tid, 1.7)) # 85% of 2.0for _ in range(5):await asyncio.sleep(0)@@ -154,13 +154,13 @@ def test_warning_not_repeated_same_trace(tmp_path):meter = _make_meter(tmp_path, _make_config())tid = uuid4()meter.start(tid, "claude-api", "test-model")- # Fuegen wir 1.7 EUR, dann 0.1 EUR hinzu — Warning darf NUR einmal feuern.+ # Add 1.7 EUR, then 0.1 EUR — the warning must fire ONLY once.meter.add(_record(tid, 1.7))first_warned = tid in meter._task_warned # type: ignore[attr-defined]meter.add(_record(tid, 0.1))assert first_warnedassert meter.total_for(tid) == pytest.approx(1.8)- # Kein trip, weil unter 2.0+ # No trip, since it's under 2.0assert not meter.over_task_budget(tid)@@ -183,7 +183,7 @@ async def test_daily_budget_trip_starts_cooldown(tmp_path):tid = uuid4()meter.start(tid, "claude-api", "test-model")- meter.add(_record(tid, 1.5)) # direkt ueber daily+ meter.add(_record(tid, 1.5)) # directly over the daily limitfor _ in range(5):await asyncio.sleep(0)@@ -249,7 +249,7 @@ def test_ledger_persists_on_close(tmp_path):def test_ledger_loads_today_total_on_init(tmp_path):import sqlite3- # Erst einen Eintrag von heute in die DB setzen+ # First put an entry from today into the DB(tmp_path / "").mkdir(exist_ok=True)db_path = tmp_path / "jarvis.db"from datetime import datetimediff --git a/tests/unit/control/test_wiring.py b/tests/unit/control/test_wiring.pyindex bf247193e5..2458cf15cd 100644--- a/tests/unit/control/test_wiring.py+++ b/tests/unit/control/test_wiring.py@@ -1,4 +1,4 @@-"""Unit-Tests fuer die Kill-Switch-Wiring (Voice + Tray + Hotkey)."""+"""Unit tests for the kill-switch wiring (voice + tray + hotkey)."""from __future__ import annotationsimport asyncio@@ -40,14 +40,14 @@ def test_voice_matches_kill_intent_positives(phrase):"Hallo Jarvis","Ich schreibe eine Email","Lies mir das vor",- "stopp als Wort in einem normalen Satz klingt harmloser als es ist",+ "stopp als Wort in einem normalen Satz klingt harmloser als es ist", # i18n-allow: German speech-input test vocabulary"",])def test_voice_matches_kill_intent_negatives(phrase):- # WICHTIG: der 3. Satz enthaelt "stopp" — unser Regex matched nur- # auf `jarvis stopp` oder `stopp jarvis`, nicht auf jedes "stopp".+ # IMPORTANT: the 3rd sentence contains "stopp" — our regex only matches+ # `jarvis stopp` or `stopp jarvis`, not every "stopp".if "jarvis" in phrase.lower() and "stopp" in phrase.lower():- return # Sonderfall, overlapt bewusst+ return # special case, intentionally overlapsassert not voice_matches_kill_intent(phrase), phrase@@ -147,7 +147,7 @@ async def test_tray_wiring_ignores_non_kill_actions():@pytest.mark.asyncioasync def test_voice_trigger_cancels_registered_tokens():- """Das ist der DoD-Ersatz-Test: Voice-Intent → CancelToken aktiv."""+ """This is the DoD replacement test: voice intent → CancelToken active."""bus = EventBus()ks = KillSwitch()ks.bind(bus)@@ -158,7 +158,7 @@ async def test_voice_trigger_cancels_registered_tokens():transcript=Transcript(text="Notfall-Stopp!",language="de", confidence=0.9),))- # Zweifach await, damit der Event-Dispatch durchlaeuft:+ # Double await, so the event dispatch runs through:# TranscriptFinal → voice_handler → KillRequested → KillSwitch._on_kill → token.cancelawait asyncio.sleep(0)await asyncio.sleep(0)diff --git a/tests/unit/core/test_capabilities.py b/tests/unit/core/test_capabilities.pyindex effdc8632c..becf01e1c5 100644--- a/tests/unit/core/test_capabilities.py+++ b/tests/unit/core/test_capabilities.py@@ -43,23 +43,23 @@ class TestNormalize:assert _normalize("Hello") == "hello"def test_umlaut_ae(self) -> None:- assert _normalize("ä") == "ae"- assert _normalize("Ä") == "ae"+ assert _normalize("ä") == "ae" # i18n-allow: German umlaut input matched in logic+ assert _normalize("Ä") == "ae" # i18n-allow: German umlaut input matched in logicdef test_umlaut_oe(self) -> None:- assert _normalize("ö") == "oe"- assert _normalize("Ö") == "oe"+ assert _normalize("ö") == "oe" # i18n-allow: German umlaut input matched in logic+ assert _normalize("Ö") == "oe" # i18n-allow: German umlaut input matched in logicdef test_umlaut_ue(self) -> None:- assert _normalize("ü") == "ue"- assert _normalize("Ü") == "ue"+ assert _normalize("ü") == "ue" # i18n-allow: German umlaut input matched in logic+ assert _normalize("Ü") == "ue" # i18n-allow: German umlaut input matched in logicdef test_sharp_s(self) -> None:- assert _normalize("ß") == "ss"+ assert _normalize("ß") == "ss" # i18n-allow: German umlaut input matched in logicdef test_mixed(self) -> None:- assert _normalize("Öffne") == "oeffne"- assert _normalize("GrüßGott") == "gruessgott"+ assert _normalize("Öffne") == "oeffne" # i18n-allow: German speech-input test vocabulary+ assert _normalize("GrüßGott") == "gruessgott" # i18n-allow: German speech-input test vocabulary# ---------------------------------------------------------------------------@@ -140,7 +140,7 @@ class TestRegistryResolveIntent:self.reg.register(self.wiki_cap)def test_verb_match_returns_cap(self) -> None:- result = self.reg.resolve_intent("fuehre ein Kommando aus")+ result = self.reg.resolve_intent("fuehre ein Kommando aus") # i18n-allow: German speech-input test vocabularyassert result is not Noneassert result.id == "tool.run-shell"@@ -150,11 +150,11 @@ class TestRegistryResolveIntent:assert result.id == "tool.wiki-recall"def test_no_match_returns_none(self) -> None:- result = self.reg.resolve_intent("wie ist das Wetter?")+ result = self.reg.resolve_intent("wie ist das Wetter?") # i18n-allow: German speech-input test vocabularyassert result is Nonedef test_umlaut_normalisation_in_utterance(self) -> None:- # "öffne" normalises to "oeffne" but the cap has "fuehre" — won't+ # "öffne" normalises to "oeffne" but the cap has "fuehre" — won't # i18n-allow: German speech-input test vocabulary# match shell; register an open_app cap to prove normalisation works.open_cap = _make_cap("local.open_app",@@ -162,7 +162,7 @@ class TestRegistryResolveIntent:objects=("app", "browser"),)self.reg.register(open_cap)- result = self.reg.resolve_intent("Öffne den Browser")+ result = self.reg.resolve_intent("Öffne den Browser") # i18n-allow: German speech-input test vocabularyassert result is not Noneassert result.id == "local.open_app"@@ -199,7 +199,7 @@ class TestRegistryHasActionIntent:assert self.reg.has_action_intent("run a shell command") is Truedef test_non_action_returns_false(self) -> None:- assert self.reg.has_action_intent("wie spät ist es?") is False+ assert self.reg.has_action_intent("wie spät ist es?") is False # i18n-allow: German speech-input test vocabularydef test_empty_string(self) -> None:assert self.reg.has_action_intent("") is False@@ -211,8 +211,8 @@ class TestRegistryHasActionIntent:objects=("app",),)self.reg.register(cap2)- # "Öffne" normalises to "oeffne" → match- assert self.reg.has_action_intent("Öffne Chrome") is True+ # "Öffne" normalises to "oeffne" → match # i18n-allow: German speech-input test vocabulary+ assert self.reg.has_action_intent("Öffne Chrome") is True # i18n-allow: German speech-input test vocabularydef test_filler_particle_halt_is_not_an_action(self) -> None:# The German discourse particle "halt" (a filler word, roughly@@ -411,7 +411,7 @@ class TestSeedRegistry:assert len(self.reg.all()) == beforedef test_open_app_matches_oeffne_chrome(self) -> None:- result = self.reg.resolve_intent("Öffne Chrome")+ result = self.reg.resolve_intent("Öffne Chrome") # i18n-allow: German speech-input test vocabularyassert result is not Noneassert result.id == "local.open_app"@@ -422,14 +422,14 @@ class TestSeedRegistry:assert result.requires_evidence is Falsedef test_run_shell_matches(self) -> None:- result = self.reg.resolve_intent("führe ein Shell-Kommando aus")+ result = self.reg.resolve_intent("führe ein Shell-Kommando aus") # i18n-allow: German speech-input test vocabularyassert result is not Noneassert result.id == "tool.run-shell"def test_smalltalk_no_match(self) -> None:- result = self.reg.resolve_intent("wie spät ist es?")+ result = self.reg.resolve_intent("wie spät ist es?") # i18n-allow: German speech-input test vocabularyassert result is Nonedef test_has_action_intent_with_seed(self) -> None:- assert self.reg.has_action_intent("Öffne den Browser") is True- assert self.reg.has_action_intent("wie ist das Wetter?") is False+ assert self.reg.has_action_intent("Öffne den Browser") is True # i18n-allow: German speech-input test vocabulary+ assert self.reg.has_action_intent("wie ist das Wetter?") is False # i18n-allow: German speech-input test vocabularydiff --git a/tests/unit/core/test_config_writer_tts_stt_model.py b/tests/unit/core/test_config_writer_tts_stt_model.pyindex 425575f8bf..288dcc7b25 100644--- a/tests/unit/core/test_config_writer_tts_stt_model.py+++ b/tests/unit/core/test_config_writer_tts_stt_model.py@@ -2,8 +2,8 @@The TTS config is a single ``[tts]`` block (voice_de / voice_en / model) and theSTT config a single ``[stt]`` block (model) — so these set the GLOBAL value for-the active provider. config-soll/ENV sync is best-effort and a no-op here (no-repo config-soll in the tmp path), which must not break the TOML write.+the active provider. config-soll/ENV sync is best-effort and a no-op here (no # i18n-allow: "config-soll" is the real config_writer identifier/filename, not prose+repo config-soll in the tmp path), which must not break the TOML write. # i18n-allow: "config-soll" is the real config_writer identifier/filename, not prose"""from __future__ import annotations@@ -41,13 +41,13 @@ def test_set_tts_model_writes_model(tmp_path: Path) -> None:def test_set_stt_model_writes_all_three_layers(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:- """The STT model picker writes TOML + config-soll + the JARVIS__STT__MODEL ENV+ """The STT model picker writes TOML + config-soll + the JARVIS__STT__MODEL ENV # i18n-allow: "config-soll" is the real config_writer identifier/filename, not prosevar — a stale single-word ENV override otherwise masks the TOML at boot (the"model is hardcoded, I can't change it" trap, forensic 2026-06-28)."""p = _toml(tmp_path)- soll = tmp_path / "config-soll.json"- soll.write_text('{"stt": {"model": "distil-large-v3"}}', encoding="utf-8")- monkeypatch.setattr(config_writer, "_config_soll_path", lambda: soll)+ soll = tmp_path / "config-soll.json" # i18n-allow: real config_writer filename+ soll.write_text('{"stt": {"model": "distil-large-v3"}}', encoding="utf-8") # i18n-allow: "soll" is the real config_writer variable name+ monkeypatch.setattr(config_writer, "_config_soll_path", lambda: soll) # i18n-allow: real config_writer identifierenv_calls: list[tuple[str, str]] = []monkeypatch.setattr(config_writer, "_set_user_env_var", lambda n, v: env_calls.append((n, v))@@ -57,10 +57,10 @@ def test_set_stt_model_writes_all_three_layers(# Layer 1: TOML.assert 'model = "large-v3-turbo"' in p.read_text(encoding="utf-8")- # Layer 2: config-soll.json.+ # Layer 2: config-soll.json. # i18n-allow: real config_writer filenameimport json- assert json.loads(soll.read_text(encoding="utf-8"))["stt"]["model"] == "large-v3-turbo"+ assert json.loads(soll.read_text(encoding="utf-8"))["stt"]["model"] == "large-v3-turbo" # i18n-allow: "soll" is the real config_writer variable name# Layer 3: the User-scope ENV var that overrides TOML at boot.assert env_calls == [("JARVIS__STT__MODEL", "large-v3-turbo")]diff --git a/tests/unit/core/test_config_writer_wake_word.py b/tests/unit/core/test_config_writer_wake_word.pyindex 9549b0d779..b4e9959f6c 100644--- a/tests/unit/core/test_config_writer_wake_word.py+++ b/tests/unit/core/test_config_writer_wake_word.py@@ -1,7 +1,7 @@"""config_writer.set_wake_word persists the custom wake word to jarvis.toml.Toml-only by design (see the set_wake_word docstring): wake_word is NOT tracked-by the drift-guard, so a plain atomic toml write survives — and a stale soll/ENV+by the drift-guard, so a plain atomic toml write survives — and a stale soll/ENV # i18n-allow: "soll" is the real config_writer identifier, not proselayer would fight the documented hand-edit path. The write must preservecomments, sibling keys, and a BOM."""diff --git a/tests/unit/core/test_persisted_provider_env_refresh.py b/tests/unit/core/test_persisted_provider_env_refresh.pyindex 4eb7c37acb..6d1db62a51 100644--- a/tests/unit/core/test_persisted_provider_env_refresh.py+++ b/tests/unit/core/test_persisted_provider_env_refresh.py@@ -10,7 +10,7 @@ e.g. a TTS switch to ``cartesia`` reverts to ``gemini-flash-tts`` on every boot.``refresh_persisted_env_from_user_registry`` is called once at app boot, BEFORE``load_config``, and overwrites ``os.environ`` for the persistent provider keyswith the authoritative HKCU\\Environment value (which the drift-guard keeps in-sync with jarvis.toml + config-soll.json). A stale inherited value can then+sync with jarvis.toml + config-soll.json). A stale inherited value can then # i18n-allow: "config-soll" is the real config_writer identifier/filename, not prosenever win. The registry reader is injectable so these tests need no real winreg."""from __future__ import annotationsdiff --git a/tests/unit/docs/test_loader.py b/tests/unit/docs/test_loader.pyindex 493914ba27..3d834b181f 100644--- a/tests/unit/docs/test_loader.py+++ b/tests/unit/docs/test_loader.py@@ -1,4 +1,4 @@-"""Unit-Tests fuer den Doc-Loader."""+"""Unit tests for the doc loader."""from __future__ import annotationsfrom pathlib import Path@@ -66,8 +66,8 @@ phase: 6# How-To: Worker spawnen-Die Datei hat keinen ``title`` und keinen ``slug`` — Loader muss-synthetisieren.+The file has neither ``title`` nor ``slug`` — the loader must+synthesize them."""@@ -78,7 +78,7 @@ synthetisieren.def test_slugify_basic() -> None:assert _slugify("Hello World") == "hello-world"assert _slugify("Concept: Router-Discipline") == "concept-router-discipline"- assert _slugify("Über uns") == "ueber-uns"+ assert _slugify("Über uns") == "ueber-uns" # i18n-allow: German umlaut input matched in logicassert _slugify(" ") == "untitled"@@ -159,7 +159,7 @@ def test_parse_doc_broken_yaml_returns_error(tmp_path: Path) -> None:def test_parse_doc_unreadable_returns_error(tmp_path: Path) -> None:p = tmp_path / "ghost.md"- # Datei existiert nicht — read() raised OSError+ # File does not exist — read() raised OSErrordoc = parse_doc(p, root=tmp_path)assert doc.error is not Noneassert "read failed" in doc.error@@ -172,11 +172,11 @@ def test_parse_doc_unreadable_returns_error(tmp_path: Path) -> None:@pytest.fixturedef doc_tree(tmp_path: Path) -> Path:- """Baut einen typischen Jarvis-Doc-Tree mit Mix aus modern/legacy."""+ """Builds a typical Jarvis doc tree with a mix of modern/legacy."""(tmp_path / "docs").mkdir()(tmp_path / "docs" / "adr").mkdir()(tmp_path / "Latenz").mkdir()- # Versteckter Ordner — soll ausgeschlossen werden+ # Hidden folder — should be excluded(tmp_path / ".git").mkdir()(tmp_path / "node_modules").mkdir()(tmp_path / "docs" / "concept-routing.md").write_text(@@ -191,13 +191,13 @@ def doc_tree(tmp_path: Path) -> Path:(tmp_path / "Latenz" / "PHASE_L_P.md").write_text("# Phase L+P\n\nLatenz-Optimierung.\n", encoding="utf-8")- # SKILL.md soll ausgeschlossen werden+ # SKILL.md should be excluded(tmp_path / "docs" / "SKILL.md").write_text("---\nname: foo\n---\n", encoding="utf-8")- # .git-File soll ausgeschlossen werden+ # .git file should be excluded(tmp_path / ".git" / "config.md").write_text("# git config\n", encoding="utf-8")- # node_modules-File soll ausgeschlossen werden+ # node_modules file should be excluded(tmp_path / "node_modules" / "readme.md").write_text("# node\n", encoding="utf-8")- # Andere Extensions ignorieren+ # Ignore other extensions(tmp_path / "docs" / "data.txt").write_text("foo\n", encoding="utf-8")return tmp_path@@ -238,7 +238,7 @@ def test_discover_docs_handles_missing_root(tmp_path: Path) -> None:def test_discover_docs_dedupes_overlapping_roots(doc_tree: Path) -> None:- """Wenn zwei Roots ueberlappen, jeder File nur einmal."""+ """When two roots overlap, each file appears only once."""docs = discover_docs([doc_tree / "docs", doc_tree / "docs" / "adr"])slugs = [d.frontmatter.slug for d in docs]assert len(slugs) == len(set(slugs))diff --git a/tests/unit/docs/test_registry.py b/tests/unit/docs/test_registry.pyindex ce401ac46a..2dfa9e601f 100644--- a/tests/unit/docs/test_registry.py+++ b/tests/unit/docs/test_registry.py@@ -1,4 +1,4 @@-"""Unit-Tests fuer DocRegistry."""+"""Unit tests for DocRegistry."""from __future__ import annotationsimport asyncio@@ -25,7 +25,7 @@ Hauptjarvis dispatcht via Sub-Jarvis-Spawn."""HOWTO_MD = """----title: "How-To: Provider hinzufuegen"+title: "How-To: Provider hinzufuegen" # i18n-allow: matched by the "hinzufuegen" search-query test belowslug: provider-adddiataxis: howtostatus: draft@@ -147,12 +147,12 @@ def test_search_via_registry(registry: DocRegistry) -> None:def test_search_with_diataxis_filter(registry: DocRegistry) -> None:- # Beide Docs erwaehnen das Wort "Schritt" oder "Hauptjarvis" nicht in- # beiden — wir nehmen einen Begriff, den nur das How-To hat.+ # Neither doc mentions the word "Schritt" or "Hauptjarvis" in both —+ # we pick a term that only the how-to has.results = registry.search_query(- "hinzufuegen", diataxis=DocDiataxis.HOWTO,+ "hinzufuegen", diataxis=DocDiataxis.HOWTO, # i18n-allow: matches the fixture title's German search term)- # Title enthaelt "hinzufuegen"+ # Title contains "hinzufuegen" # i18n-allow: matches the fixture title's German search termassert any(r.slug == "provider-add" for r in results)@@ -200,7 +200,7 @@ async def test_async_reload(doc_root: Path) -> None:# ----------------------------------------------------------------------class _StubBus:- """Minimaler Bus-Stub fuer Reload-Event-Tests."""+ """Minimal bus stub for reload-event tests."""def __init__(self) -> None:self.events: list[object] = []@@ -212,15 +212,15 @@ class _StubBus:def test_emit_reloaded_without_loop_does_not_crash(doc_root: Path,) -> None:- """Wenn keine Event-Loop laeuft, sollte _emit_reloaded silent failen- statt zu crashen."""+ """When no event loop is running, _emit_reloaded should fail silently+ instead of crashing."""bus = _StubBus()reg = DocRegistry(roots=[doc_root / "docs"],index_db=doc_root / "index.sqlite",bus=bus,)- reg.reload_sync() # darf nicht crashen+ reg.reload_sync() # must not crashreg.close()@@ -229,7 +229,7 @@ def test_emit_reloaded_without_loop_does_not_crash(# ----------------------------------------------------------------------def test_multi_root_no_double_index(tmp_path: Path) -> None:- """Wenn zwei Roots ueberlappen, jeder File nur einmal."""+ """When two roots overlap, each file appears only once."""(tmp_path / "a").mkdir()(tmp_path / "a" / "b").mkdir()(tmp_path / "a" / "b" / "doc.md").write_text(CONCEPT_MD, encoding="utf-8")@@ -239,6 +239,6 @@ def test_multi_root_no_double_index(tmp_path: Path) -> None:)reg.reload_sync()docs = reg.list()- # Nur ein Doc — kein Duplikat trotz ueberlappender Roots+ # Only one doc — no duplicate despite overlapping rootsassert len(docs) == 1reg.close()diff --git a/tests/unit/docs/test_schema.py b/tests/unit/docs/test_schema.pyindex 0f261ad7c1..e6736ee88d 100644--- a/tests/unit/docs/test_schema.py+++ b/tests/unit/docs/test_schema.py@@ -1,4 +1,4 @@-"""Unit-Tests fuer DocFrontmatter + Doc-Schema."""+"""Unit tests for DocFrontmatter + doc schema."""from __future__ import annotationsfrom datetime import date@@ -73,7 +73,7 @@ def test_frontmatter_tags_none_becomes_empty_list() -> None:def test_frontmatter_extra_fields_ignored() -> None:- """``extra='ignore'`` muss unbekannte Felder schlucken — kein Crash."""+ """``extra='ignore'`` must swallow unknown fields — no crash."""fm = DocFrontmatter.model_validate({"title": "t","slug": "s",diff --git a/tests/unit/docs/test_search.py b/tests/unit/docs/test_search.pyindex 0530c8e1ba..34c67d4c7a 100644--- a/tests/unit/docs/test_search.py+++ b/tests/unit/docs/test_search.py@@ -1,4 +1,4 @@-"""Unit-Tests fuer DocSearch (SQLite-FTS5)."""+"""Unit tests for DocSearch (SQLite-FTS5)."""from __future__ import annotationsfrom pathlib import Path@@ -42,7 +42,7 @@ def test_upsert_and_query_basic(search: DocSearch) -> None:search.upsert(_doc(slug="router-discipline",title="Concept: Router-Discipline",- body="Hauptjarvis ist Pure Dispatcher und delegiert via spawn_worker.",+ body="Hauptjarvis is a Pure Dispatcher and delegates via spawn_worker.",))results = search.query("Dispatcher")assert len(results) == 1@@ -90,8 +90,8 @@ def test_filter_by_diataxis(search: DocSearch) -> None:def test_query_orders_by_rank(search: DocSearch) -> None:- """BM25-Ranking: ein Doc, das den Term mehrfach + im Title hat,- sollte vor einem Doc mit nur einem Treffer im Body stehen."""+ """BM25 ranking: a doc that has the term multiple times + in the title+ should rank above a doc with only one hit in the body."""search.upsert(_doc("primary", "Routing Discipline",body="routing routing routing routing logic for the router brain",@@ -125,10 +125,10 @@ def test_query_empty_returns_empty(search: DocSearch) -> None:def test_query_handles_unbalanced_quote(search: DocSearch) -> None:- """Ein offener Quote sollte nicht crashen — sanitizer entfernt ihn."""+ """An open quote should not crash — the sanitizer removes it."""search.upsert(_doc("a", "A", "hello world"))- results = search.query('"hello') # offene Quote- # Entweder leer oder mit Treffer — Hauptsache kein OperationalError+ results = search.query('"hello') # unbalanced quote+ # Either empty or with a hit — the main thing is no OperationalErrorassert isinstance(results, list)@@ -149,7 +149,7 @@ def test_snippet_contains_mark_tags(search: DocSearch) -> None:"Doc",body=("Lorem ipsum dolor sit amet. "- "The Voice-Pipeline ist Phase 1 von Personal-Jarvis. "+ "The Voice-Pipeline is Phase 1 of Personal-Jarvis. ""Sed do eiusmod tempor incididunt."),))diff --git a/tests/unit/friends/test_messages.py b/tests/unit/friends/test_messages.pyindex 1875a4daac..20e76cad09 100644--- a/tests/unit/friends/test_messages.py+++ b/tests/unit/friends/test_messages.py@@ -1,5 +1,5 @@# === F-FRIENDS [F3] · feature/friends-section · ruben-2026-05-01 ===-"""Unit-Tests fuer :class:`jarvis.friends.messages.DirectMessageStore`."""+"""Unit tests for :class:`jarvis.friends.messages.DirectMessageStore`."""from __future__ import annotationsfrom uuid import uuid4@@ -89,7 +89,7 @@ async def test_list_chronological_ascending(channel="telegram",created_at_ns=3_000,)- # Bewusst out-of-order einfuegen, damit das ORDER BY arbeitet.+ # Intentionally insert out of order, so ORDER BY does the work.await registry.messages.add(b)await registry.messages.add(c)await registry.messages.add(a)@@ -131,7 +131,7 @@ async def test_multi_friend_isolation(registry: FriendRegistry) -> None:DirectMessage(friend_id=f1.id,direction="outbound",- text="fuer Alice",+ text="for Alice",channel="telegram",))@@ -139,7 +139,7 @@ async def test_multi_friend_isolation(registry: FriendRegistry) -> None:DirectMessage(friend_id=f2.id,direction="outbound",- text="fuer Bob",+ text="for Bob",channel="jarvis_pubkey",))@@ -147,9 +147,9 @@ async def test_multi_friend_isolation(registry: FriendRegistry) -> None:alice_msgs = await registry.messages.list_for_friend(f1.id)bob_msgs = await registry.messages.list_for_friend(f2.id)assert len(alice_msgs) == 1- assert alice_msgs[0].text == "fuer Alice"+ assert alice_msgs[0].text == "for Alice"assert len(bob_msgs) == 1- assert bob_msgs[0].text == "fuer Bob"+ assert bob_msgs[0].text == "for Bob"@pytest.mark.asyncio@@ -174,7 +174,7 @@ async def test_delete_for_friend(async def test_delete_friend_cascades_messages(registry: FriendRegistry, friend: Friend) -> None:- """delete_friend muss alle DMs des Friends aufraeumen."""+ """delete_friend must clean up all of the friend's DMs."""await registry.messages.add(DirectMessage(friend_id=friend.id,@@ -186,8 +186,8 @@ async def test_delete_friend_cascades_messages(assert len(await registry.messages.list_for_friend(friend.id)) == 1await registry.delete_friend(friend.id)- # Direkt gegen die Tabelle schauen — die Friend-FK gibt es nicht mehr,- # aber die DM-Zeilen muessen ebenfalls weg sein.+ # Look directly against the table — the friend FK no longer exists,+ # but the DM rows must be gone too.msgs_after = await registry.messages.list_for_friend(friend.id)assert msgs_after == []@@ -196,5 +196,5 @@ async def test_delete_friend_cascades_messages(async def test_delete_for_friend_unknown_is_noop(registry: FriendRegistry,) -> None:- # Kein Friend mit dieser ID — DELETE darf einfach 0 Rows treffen.+ # No friend with this ID — DELETE may simply hit 0 rows.await registry.messages.delete_for_friend(uuid4())diff --git a/tests/unit/friends/test_registry.py b/tests/unit/friends/test_registry.pyindex 0a206b4d88..4010ca7abe 100644--- a/tests/unit/friends/test_registry.py+++ b/tests/unit/friends/test_registry.py@@ -1,5 +1,5 @@# === F-FRIENDS [F0] · feature/friends-section · ruben-2026-04-30 ===-"""Unit-Tests fuer :class:`jarvis.friends.registry.FriendRegistry`."""+"""Unit tests for :class:`jarvis.friends.registry.FriendRegistry`."""from __future__ import annotationsfrom uuid import uuid4@@ -37,7 +37,7 @@ async def test_open_close_idempotent() -> None:@pytest.mark.asyncioasync def test_require_conn_raises_before_open() -> None:reg = FriendRegistry(":memory:")- with pytest.raises(FriendRegistryError, match="nicht geoeffnet"):+ with pytest.raises(FriendRegistryError, match="nicht geoeffnet"): # i18n-allow: matches the real (German) exception message stringawait reg.list_friends()diff --git a/tests/unit/friends/test_status_filter.py b/tests/unit/friends/test_status_filter.pyindex 87621c296a..6d31053c11 100644--- a/tests/unit/friends/test_status_filter.py+++ b/tests/unit/friends/test_status_filter.py@@ -1,16 +1,16 @@# === F-FRIENDS [F4] · feature/friends-section · ruben-2026-05-01 ===-"""Unit-Tests fuer :class:`jarvis.friends.status_filter.StatusFilter`.+"""Unit tests for :class:`jarvis.friends.status_filter.StatusFilter`.-Branch-portable: die echten Bus-Events (VoiceSessionStarted, MissionStarted,-JarvisAgentTaskStarted, ...) existieren auf diesem Branch eventuell noch nicht.-Wir bauen Fake-DataClass-Events mit den passenden Class-Names — der Filter-arbeitet ueber ``type(event).__name__`` + ``hasattr``, also reicht das.+Branch-portable: the real bus events (VoiceSessionStarted, MissionStarted,+JarvisAgentTaskStarted, ...) may not exist yet on this branch.+We build fake dataclass events with matching class names — the filter+works via ``type(event).__name__`` + ``hasattr``, so that's enough.-Fokus der Tests:+Focus of the tests:-- Hard-Blacklist absoluter Vorrang (KRITISCH).-- Profile-Whitelists sauber separiert.-- Field-Filtering blockiert Datenleak ueber unerwartete Event-Felder.+- Hard blacklist has absolute precedence (CRITICAL).+- Profile whitelists are cleanly separated.+- Field filtering blocks data leaks via unexpected event fields."""from __future__ import annotations@@ -19,7 +19,7 @@ from dataclasses import dataclassfrom jarvis.friends.status_filter import HARD_BLACKLIST, PROFILES, StatusFilter# -----------------------------------------------------------------------# Fake-Events: Class-Name matched echte Bus-Event-Namen, Felder per Plan.+# Fake events: class name matches real bus event names, fields per plan.# ----------------------------------------------------------------------@@ -64,7 +64,7 @@ class VoiceSessionEnded:class MissionStarted:timestamp_ns: int = 3_000title: str = "Refactor Brain Module"- internal_prompt: str = "leak me" # darf NICHT durchkommen+ internal_prompt: str = "leak me" # must NOT pass through@dataclass@@ -72,15 +72,15 @@ class MissionCompleted:timestamp_ns: int = 4_000title: str = "Refactor Brain Module"success: bool = True- cost_usd: float = 12.34 # darf NICHT durchkommen+ cost_usd: float = 12.34 # must NOT pass through@dataclassclass JarvisAgentTaskStarted:timestamp_ns: int = 5_000summary: str = "Implementiert F4-Pipeline"- utterance: str = "leak me" # darf NICHT durchkommen- private_secret: str = "do-not-leak" # erfundenes Feld, darf NICHT durchkommen+ utterance: str = "leak me" # must NOT pass through+ private_secret: str = "do-not-leak" # made-up field, must NOT pass through@dataclass@@ -91,33 +91,33 @@ class JarvisAgentTaskCompleted:# -----------------------------------------------------------------------# Hard-Blacklist: KRITISCHE Tests+# Hard blacklist: CRITICAL tests# ----------------------------------------------------------------------def test_hard_blacklist_blocks_in_minimal() -> None:- """UtteranceCaptured darf im 'minimal'-Profile NIE durchkommen."""+ """UtteranceCaptured must NEVER pass through in the 'minimal' profile."""event = UtteranceCaptured()result = StatusFilter.filter(event, "minimal")assert result is Nonedef test_hard_blacklist_blocks_in_standard() -> None:- """UtteranceCaptured darf im 'standard'-Profile NIE durchkommen."""+ """UtteranceCaptured must NEVER pass through in the 'standard' profile."""event = UtteranceCaptured()result = StatusFilter.filter(event, "standard")assert result is Nonedef test_hard_blacklist_blocks_in_detailed() -> None:- """UtteranceCaptured darf im 'detailed'-Profile NIE durchkommen."""+ """UtteranceCaptured must NEVER pass through in the 'detailed' profile."""event = UtteranceCaptured()result = StatusFilter.filter(event, "detailed")assert result is Nonedef test_hard_blacklist_blocks_with_custom_whitelist() -> None:- """Custom-Whitelist darf Hard-Blacklist NICHT umgehen (AP-1/AP-11)."""+ """A custom whitelist must NOT bypass the hard blacklist (AP-1/AP-11)."""event = UtteranceCaptured()result = StatusFilter.filter(event, "detailed", custom_whitelist=["UtteranceCaptured"]@@ -126,21 +126,21 @@ def test_hard_blacklist_blocks_with_custom_whitelist() -> None:def test_hard_blacklist_blocks_action_executed() -> None:- """ActionExecuted ist in HARD_BLACKLIST — keine Aktionen leaken."""+ """ActionExecuted is in HARD_BLACKLIST — no actions may leak."""event = ActionExecuted()result = StatusFilter.filter(event, "detailed")assert result is Nonedef test_hard_blacklist_blocks_memory_updated() -> None:- """MemoryUpdated ist in HARD_BLACKLIST — keine Memory-Mutationen leaken."""+ """MemoryUpdated is in HARD_BLACKLIST — no memory mutations may leak."""event = MemoryUpdated()result = StatusFilter.filter(event, "detailed")assert result is Nonedef test_hard_blacklist_blocks_transcript_final() -> None:- """TranscriptFinal in HARD_BLACKLIST — STT-Output verlaesst Maschine NIE."""+ """TranscriptFinal is in HARD_BLACKLIST — STT output NEVER leaves the machine."""event = TranscriptFinal()result = StatusFilter.filter(event, "detailed", custom_whitelist=["TranscriptFinal"]@@ -149,7 +149,7 @@ def test_hard_blacklist_blocks_transcript_final() -> None:def test_hard_blacklist_constant_completeness() -> None:- """Sanity-Check: alle vom Plan genannten Hard-Blacklist-Eintraege da."""+ """Sanity check: all hard-blacklist entries named in the plan are present."""required = {"UtteranceCaptured","TranscriptFinal",@@ -163,12 +163,12 @@ def test_hard_blacklist_constant_completeness() -> None:# -----------------------------------------------------------------------# Profile-Whitelists+# Profile whitelists# ----------------------------------------------------------------------def test_minimal_passes_voice_session_started() -> None:- """'minimal' laesst VoiceSessionStarted durch."""+ """'minimal' lets VoiceSessionStarted through."""event = VoiceSessionStarted()result = StatusFilter.filter(event, "minimal")assert result is not None@@ -178,52 +178,52 @@ def test_minimal_passes_voice_session_started() -> None:def test_minimal_blocks_mission_started() -> None:- """'minimal' blockiert MissionStarted (Mission-Tracking erst ab 'standard')."""+ """'minimal' blocks MissionStarted (mission tracking only starts at 'standard')."""event = MissionStarted()result = StatusFilter.filter(event, "minimal")assert result is Nonedef test_minimal_blocks_openclaw() -> None:- """'minimal' blockiert Sub-Jarvis-Events (erst 'detailed')."""+ """'minimal' blocks Jarvis-Agent events (only allowed from 'detailed')."""event = JarvisAgentTaskStarted()result = StatusFilter.filter(event, "minimal")assert result is Nonedef test_standard_passes_mission_started() -> None:- """'standard' laesst MissionStarted mit erlaubten Feldern durch."""+ """'standard' lets MissionStarted through with its allowed fields."""event = MissionStarted()result = StatusFilter.filter(event, "standard")assert result is not Noneassert result.event_type == "MissionStarted"assert result.profile_used == "standard"assert result.fields == {"title": "Refactor Brain Module"}- # internal_prompt darf NICHT durchkommen+ # internal_prompt must NOT pass throughassert "internal_prompt" not in result.fieldsdef test_standard_passes_mission_completed_with_success() -> None:- """'standard' enthaelt fuer MissionCompleted: title + success."""+ """'standard' includes for MissionCompleted: title + success."""event = MissionCompleted()result = StatusFilter.filter(event, "standard")assert result is not Noneassert result.fields == {"title": "Refactor Brain Module", "success": True}- # cost_usd darf NICHT durchkommen+ # cost_usd must NOT pass throughassert "cost_usd" not in result.fieldsdef test_standard_blocks_openclaw() -> None:- """'standard' blockiert JarvisAgentTaskStarted."""+ """'standard' blocks JarvisAgentTaskStarted."""event = JarvisAgentTaskStarted()result = StatusFilter.filter(event, "standard")assert result is Nonedef test_detailed_passes_openclaw_with_summary_only() -> None:- """'detailed' laesst JarvisAgentTaskStarted durch, ABER nur summary-Field.+ """'detailed' lets JarvisAgentTaskStarted through, BUT only the summary field.- KRITISCH: utterance + private_secret im Event duerfen NICHT durchkommen.+ CRITICAL: utterance + private_secret on the event must NOT pass through."""event = JarvisAgentTaskStarted()result = StatusFilter.filter(event, "detailed")@@ -235,11 +235,11 @@ def test_detailed_passes_openclaw_with_summary_only() -> None:def test_no_data_leak_via_unknown_field() -> None:- """Erfundene Felder im Event leaken NICHT — Filter ist Whitelist-only."""+ """Made-up fields on the event do NOT leak — the filter is whitelist-only."""event = JarvisAgentTaskStarted()result = StatusFilter.filter(event, "detailed")assert result is not None- # Nur summary darf raus+ # Only summary may pass throughassert set(result.fields.keys()) == {"summary"}@@ -259,21 +259,21 @@ def test_detailed_passes_openclaw_completed() -> None:# -----------------------------------------------------------------------# Custom-Whitelist-Verhalten+# Custom whitelist behavior# ----------------------------------------------------------------------def test_custom_whitelist_extends_profile() -> None:- """Custom-Whitelist + Profile-Default werden als Union behandelt."""+ """Custom whitelist + profile default are treated as a union."""@dataclassclass CustomDebugEvent:timestamp_ns: int = 7_000event = CustomDebugEvent()- # Ohne Custom: blockiert+ # Without custom: blockedassert StatusFilter.filter(event, "minimal") is None- # Mit Custom: durch+ # With custom: passes throughresult = StatusFilter.filter(event, "minimal", custom_whitelist=["CustomDebugEvent"])@@ -282,9 +282,9 @@ def test_custom_whitelist_extends_profile() -> None:def test_custom_whitelist_does_not_replace_profile() -> None:- """Custom-Whitelist ergaenzt nur — Profile-Defaults bleiben aktiv."""+ """Custom whitelist only extends — profile defaults stay active."""event = VoiceSessionStarted()- # Custom-Whitelist enthaelt VoiceSessionStarted nicht — soll trotzdem durch+ # Custom whitelist does not contain VoiceSessionStarted — should still pass throughresult = StatusFilter.filter(event, "minimal", custom_whitelist=["FooBarEvent"])@@ -293,20 +293,20 @@ def test_custom_whitelist_does_not_replace_profile() -> None:# -----------------------------------------------------------------------# Edge-Cases+# Edge cases# ----------------------------------------------------------------------def test_invalid_profile_returns_none() -> None:- """Unbekanntes Profile -> None statt Crash."""+ """Unknown profile -> None instead of a crash."""event = VoiceSessionStarted()- # Type-Hint Literal erlaubt das nicht, aber Runtime kann das passieren+ # The type-hint Literal disallows this, but it can happen at runtimeresult = StatusFilter.filter(event, "bogus") # type: ignore[arg-type]assert result is Nonedef test_event_without_timestamp_ns_default_to_zero() -> None:- """Event ohne timestamp_ns -> Filter setzt 0 (kein Crash)."""+ """Event without timestamp_ns -> filter defaults it to 0 (no crash)."""@dataclassclass TimestampLess:@@ -321,12 +321,12 @@ def test_event_without_timestamp_ns_default_to_zero() -> None:def test_profiles_constant_has_all_three_levels() -> None:- """Sanity: PROFILES enthaelt minimal/standard/detailed."""+ """Sanity: PROFILES contains minimal/standard/detailed."""assert set(PROFILES.keys()) == {"minimal", "standard", "detailed"}def test_detailed_blocks_blacklisted_event_present_in_custom() -> None:- """Egal welche Events der User custom-whitelistet — Hard-Blacklist gewinnt."""+ """No matter which events the user custom-whitelists — the hard blacklist wins."""event = ActionExecuted()result = StatusFilter.filter(event,diff --git a/tests/unit/friends/test_status_publisher.py b/tests/unit/friends/test_status_publisher.pyindex 5c4ff755f4..67fd5935cd 100644--- a/tests/unit/friends/test_status_publisher.py+++ b/tests/unit/friends/test_status_publisher.py@@ -1,7 +1,7 @@# === F-FRIENDS [F4] · feature/friends-section · ruben-2026-05-01 ===-"""Unit-Tests fuer :class:`jarvis.friends.status_publisher.StatusPublisher`.+"""Unit tests for :class:`jarvis.friends.status_publisher.StatusPublisher`.-Strategie: echte FriendRegistry (in-memory SQLite) + Fake-ChannelManager + Fake-Bus.+Strategy: real FriendRegistry (in-memory SQLite) + fake ChannelManager + fake bus."""from __future__ import annotations@@ -19,7 +19,7 @@ from jarvis.friends.status_publisher import StatusPublisher# -----------------------------------------------------------------------# Fake-Events (Class-Names matchen echte Bus-Events)+# Fake events (class names match real bus events)# ----------------------------------------------------------------------@@ -54,7 +54,7 @@ class UtteranceCaptured:class FakeTelegramChannel:- """Captured all send_status_card calls fuer Assertion."""+ """Captures all send_status_card calls for assertion."""def __init__(self) -> None:self.sent: list[tuple[int, StatusUpdate]] = []@@ -104,7 +104,7 @@ def bus() -> EventBus:async def test_subscribes_unsubscribes(bus: EventBus, registry: FriendRegistry) -> None:- """start() registriert Wildcard-Handler, stop() entfernt ihn."""+ """start() registers a wildcard handler, stop() removes it."""pub = StatusPublisher(bus, registry, channel_manager=None)assert len(bus._wildcard_subscribers) == 0await pub.start()@@ -128,7 +128,7 @@ async def test_double_start_idempotent(async def test_filtered_event_dispatched_to_telegram(bus: EventBus, registry: FriendRegistry) -> None:- """Friend mit telegram + standard, MissionCompleted -> dispatched."""+ """Friend with telegram + standard, MissionCompleted -> dispatched."""friend = Friend(display_name="Daniel")await registry.add_friend(friend)await registry.link_channel(@@ -162,7 +162,7 @@ async def test_filtered_event_dispatched_to_telegram(async def test_blacklisted_event_not_dispatched(bus: EventBus, registry: FriendRegistry) -> None:- """UtteranceCaptured wird NIE dispatched, egal welches Profile."""+ """UtteranceCaptured is NEVER dispatched, regardless of profile."""friend = Friend(display_name="Daniel")await registry.add_friend(friend)await registry.link_channel(@@ -191,7 +191,7 @@ async def test_blacklisted_event_not_dispatched(async def test_blacklisted_event_with_custom_whitelist_blocked(bus: EventBus, registry: FriendRegistry) -> None:- """Custom-Whitelist kann Hard-Blacklist NICHT umgehen."""+ """A custom whitelist can NOT bypass the hard blacklist."""friend = Friend(display_name="Daniel")await registry.add_friend(friend)await registry.link_channel(@@ -222,8 +222,8 @@ async def test_blacklisted_event_with_custom_whitelist_blocked(async def test_per_friend_filtering(bus: EventBus, registry: FriendRegistry) -> None:- """Zwei Friends mit unterschiedlichen Profilen — nur der mit- passendem Profile bekommt das Event."""+ """Two friends with different profiles — only the one with a+ matching profile receives the event."""minimal_friend = Friend(display_name="Minimal-Mike")detailed_friend = Friend(display_name="Detail-Dora")await registry.add_friend(minimal_friend)@@ -253,21 +253,21 @@ async def test_per_friend_filtering(pub = StatusPublisher(bus, registry, channel_manager=cm)await pub.start()try:- # MissionStarted ist 'standard'+ — minimal blockiert, detailed durch+ # MissionStarted is 'standard'+ — minimal blocks, detailed passes throughawait bus.publish(MissionStarted())finally:await pub.stop()assert len(fake_tg.sent) == 1chat_id, _update = fake_tg.sent[0]- assert chat_id == 222 # nur detailed-Friend+ assert chat_id == 222 # only the detailed friend@pytest.mark.asyncioasync def test_friend_without_channel_skipped(bus: EventBus, registry: FriendRegistry) -> None:- """Friend ohne verknuepften Channel -> kein Crash, kein Send."""+ """Friend without a linked channel -> no crash, no send."""friend = Friend(display_name="Channelless")await registry.add_friend(friend)await registry.set_status_permission(friend.id, "detailed")@@ -288,7 +288,7 @@ async def test_friend_without_channel_skipped(async def test_invalid_telegram_handle_does_not_crash(bus: EventBus, registry: FriendRegistry) -> None:- """Wenn telegram-handle nicht zu int parsen geht -> skip, kein Crash."""+ """If the telegram handle can't be parsed as an int -> skip, no crash."""friend = Friend(display_name="BadHandle")await registry.add_friend(friend)await registry.link_channel(@@ -317,7 +317,7 @@ async def test_invalid_telegram_handle_does_not_crash(async def test_telegram_channel_unavailable_does_not_crash(bus: EventBus, registry: FriendRegistry) -> None:- """ChannelManager liefert KeyError fuer 'telegram' -> skip, kein Crash."""+ """ChannelManager raises KeyError for 'telegram' -> skip, no crash."""friend = Friend(display_name="Foo")await registry.add_friend(friend)await registry.link_channel(@@ -330,21 +330,21 @@ async def test_telegram_channel_unavailable_does_not_crash()await registry.set_status_permission(friend.id, "minimal")- cm = FakeChannelManager(telegram=None) # telegram NICHT registriert+ cm = FakeChannelManager(telegram=None) # telegram NOT registeredpub = StatusPublisher(bus, registry, channel_manager=cm)await pub.start()try:await bus.publish(VoiceSessionStarted())finally:await pub.stop()- # Erfolgreich ohne Exception+ # Succeeds without an exception@pytest.mark.asyncioasync def test_channel_manager_none_does_not_crash(bus: EventBus, registry: FriendRegistry) -> None:- """Ohne ChannelManager wird trotzdem nicht gecrasht."""+ """Even without a ChannelManager, nothing crashes."""friend = Friend(display_name="Foo")await registry.add_friend(friend)await registry.link_channel(@@ -369,7 +369,7 @@ async def test_channel_manager_none_does_not_crash(async def test_jarvis_pubkey_channel_stub_only(bus: EventBus, registry: FriendRegistry) -> None:- """jarvis_pubkey ist in F4 Stub — kein Send, kein Crash."""+ """jarvis_pubkey is a stub in F4 — no send, no crash."""friend = Friend(display_name="Federation-Friend")await registry.add_friend(friend)await registry.link_channel(@@ -391,7 +391,7 @@ async def test_jarvis_pubkey_channel_stub_only(finally:await pub.stop()- # Telegram darf NICHT gerufen werden (Friend hat nur jarvis_pubkey)+ # Telegram must NOT be called (friend only has jarvis_pubkey)assert fake_tg.sent == []@@ -399,10 +399,10 @@ async def test_jarvis_pubkey_channel_stub_only(async def test_primary_channel_chosen_when_multiple(bus: EventBus, registry: FriendRegistry) -> None:- """Wenn mehrere Channels verknuepft, gewinnt is_primary=True."""+ """When multiple channels are linked, is_primary=True wins."""friend = Friend(display_name="MultiChannel")await registry.add_friend(friend)- # Nicht-primary zuerst+ # Non-primary firstawait registry.link_channel(FriendChannel(friend_id=friend.id,@@ -411,7 +411,7 @@ async def test_primary_channel_chosen_when_multiple(is_primary=False,))- # Primary danach+ # Primary afterwardsawait registry.link_channel(FriendChannel(friend_id=friend.id,@@ -433,4 +433,4 @@ async def test_primary_channel_chosen_when_multiple(assert len(fake_tg.sent) == 1chat_id, _ = fake_tg.sent[0]- assert chat_id == 999 # primary, nicht 111+ assert chat_id == 999 # primary, not 111diff --git a/tests/unit/google_cli/test_pty_runner.py b/tests/unit/google_cli/test_pty_runner.pyindex 7c7ac6bb0f..1df03b454d 100644--- a/tests/unit/google_cli/test_pty_runner.py+++ b/tests/unit/google_cli/test_pty_runner.py@@ -115,7 +115,7 @@ def test_extract_strips_trailing_lone_spinner_glyph():# ---- repair_agy_path ------------------------------------------------------# agy spawns cmd.exe + npm internally (MCP servers); in a degraded environment-# (PATH stripped of System32 / Node) that fails with "chcp nicht erkannt". The+# (PATH stripped of System32 / Node) that fails with "chcp nicht erkannt". The # i18n-allow# child PATH must carry the standard Windows system dirs.diff --git a/tests/unit/harness/test_action_registry.py b/tests/unit/harness/test_action_registry.pyindex 9e4810384f..fc5b16f5be 100644--- a/tests/unit/harness/test_action_registry.py+++ b/tests/unit/harness/test_action_registry.py@@ -1,16 +1,16 @@-"""Action-Registry: Lookup, Validierung, Arg-Transform, Composite-Runners.--Pinnt das **Vokabular**, das der LLM-System-Prompt nennt und das der-Computer-Use-Loop ausfuehren kann. Wenn Brain und Loop hier auseinander--laufen, plant der Brain Actions, die der Executor nicht kennt — und der-User hoert "Unbekannte Action".--Diese Tests stellen sicher dass:- 1. Alle vom User explizit verlangten Actions registriert sind.- 2. ActionSpec-Validierung Inkonsistenzen aufdeckt (Tool UND Composite,- oder weder noch).- 3. Argument-Transformer die richtigen Tool-Args produzieren.- 4. Composite-Runners alle benoetigten Tools korrekt ausfuehren.+"""Action registry: lookup, validation, arg transforms, composite runners.++Pins the **vocabulary** that the LLM system prompt names and that the+Computer-Use loop can execute. If the brain and the loop drift apart here,+the brain plans actions the executor doesn't know — and the+user hears "unknown action".++These tests make sure that:+ 1. All actions the user explicitly required are registered.+ 2. ActionSpec validation catches inconsistencies (both tool AND+ composite, or neither).+ 3. Argument transformers produce the correct tool args.+ 4. Composite runners execute all required tools correctly."""from __future__ import annotations@@ -34,12 +34,12 @@ from jarvis.harness.action_registry import (# ----------------------------------------------------------------------# Vokabular-Coverage+# Vocabulary coverage# ----------------------------------------------------------------------# Vom User explizit verlangte Actions in seinem Architektur-Auftrag.-# Wenn dieser Test failed, ist das System-Vokabular gegenueber dem User--# Vertrag unvollstaendig — bitte Action ergaenzen statt Test loeschen.+# Actions the user explicitly required in their architecture brief.+# If this test fails, the system vocabulary is incomplete against the+# user contract — please add the action instead of deleting the test.REQUIRED_ACTIONS: frozenset[str] = frozenset({"open_terminal","open_new_tab",@@ -58,13 +58,13 @@ REQUIRED_ACTIONS: frozenset[str] = frozenset({def test_default_registry_covers_user_required_actions() -> None:registered = set(DEFAULT_REGISTRY.names())missing = REQUIRED_ACTIONS - registered- assert not missing, f"Fehlende Actions in der Default-Registry: {missing!r}"+ assert not missing, f"Missing actions in the default registry: {missing!r}"def test_describe_for_prompt_lists_every_action() -> None:desc = DEFAULT_REGISTRY.describe_for_prompt()for name in DEFAULT_REGISTRY.names():- assert name in desc, f"Action {name!r} fehlt im Prompt-Beschreibungstext"+ assert name in desc, f"Action {name!r} is missing from the prompt description text"# ---------------------------------------------------------------------@@ -123,7 +123,7 @@ def test_transform_press_shortcut_combo_string() -> None:def test_transform_press_shortcut_keys_list_wins() -> None:- """Wenn beide angegeben sind, gewinnt die explizite Liste."""+ """If both are given, the explicit list wins."""result = _transform_press_shortcut({"combo": "alt+f4", "keys": ["ctrl", "c"],})@@ -131,7 +131,7 @@ def test_transform_press_shortcut_keys_list_wins() -> None:def test_transform_press_shortcut_lowercases() -> None:- """ctrl+T wird zu ['ctrl', 't'] — der hotkey-Tool resolve macht ord(upper)."""+ """ctrl+T becomes ['ctrl', 't'] — the hotkey tool resolve does ord(upper)."""result = _transform_press_shortcut({"combo": "Ctrl+T"})assert result == {"keys": ["ctrl", "t"]}@@ -153,7 +153,7 @@ def test_transform_open_terminal_profile_aliases() -> None:def test_transform_open_terminal_passthrough_for_custom_path() -> None:- """Unbekannter Profile-Name wird durchgereicht — User kann eigene Pfade nutzen."""+ """An unknown profile name is passed through — the user can use their own paths."""result = _transform_open_terminal({"profile": "/usr/local/bin/iterm2"})assert result["app_name"] == "/usr/local/bin/iterm2"@@ -163,7 +163,7 @@ def test_transform_open_terminal_passthrough_for_custom_path() -> None:# ---------------------------------------------------------------------class _FakeExecutor:- """Speichert alle execute-Calls fuer Assertions."""+ """Stores all execute calls for assertions."""def __init__(self, success: bool = True, error: str | None = None) -> None:self.calls: list[dict[str, Any]] = []@@ -197,7 +197,7 @@ class _FakeTool:@pytest.mark.asyncioasync def test_composite_open_new_tab_calls_hotkey_with_ctrl_t() -> None:- """open_new_tab muss exakt Strg+T senden — das ist der universelle Tab-Shortcut."""+ """open_new_tab must send exactly ctrl+T — that's the universal tab shortcut."""executor = _FakeExecutor()tools = {"hotkey": _FakeTool("hotkey")}@@ -212,7 +212,7 @@ async def test_composite_open_new_tab_calls_hotkey_with_ctrl_t() -> None:@pytest.mark.asyncioasync def test_composite_open_new_tab_fails_clearly_when_hotkey_missing() -> None:executor = _FakeExecutor()- tools: dict[str, Any] = {} # Kein hotkey-Tool+ tools: dict[str, Any] = {} # No hotkey toolresult = await _composite_open_new_tab({}, executor, tools, trace_id=uuid4())@@ -243,8 +243,8 @@ async def test_composite_run_terminal_command_types_then_presses_enter() -> None@pytest.mark.asyncioasync def test_composite_run_terminal_command_short_circuits_on_type_failure() -> None:- """Wenn type_text failed, darf Enter NICHT gedrueckt werden — sonst leere Befehle."""- executor = _FakeExecutor(success=False, error="Tippen fehlgeschlagen")+ """If type_text fails, Enter must NOT be pressed — otherwise empty commands."""+ executor = _FakeExecutor(success=False, error="Typing failed")tools = {"type_text": _FakeTool("type_text"),"hotkey": _FakeTool("hotkey"),@@ -255,7 +255,7 @@ async def test_composite_run_terminal_command_short_circuits_on_type_failure() -)assert result.success is False- # Nur ein Aufruf (type_text), kein Enter-Hotkey.+ # Only one call (type_text), no Enter hotkey.assert len(executor.calls) == 1assert executor.calls[0]["tool"] == "type_text"@@ -275,7 +275,7 @@ async def test_composite_run_terminal_command_rejects_empty_command() -> None:# ----------------------------------------------------------------------# Default-Registry-Build ist deterministisch und idempotent+# Default registry build is deterministic and idempotent# ---------------------------------------------------------------------def test_build_default_registry_is_deterministic() -> None:diff --git a/tests/unit/harness/test_cu_grok_vision.py b/tests/unit/harness/test_cu_grok_vision.pyindex aa4bb69467..0bafcd2395 100644--- a/tests/unit/harness/test_cu_grok_vision.py+++ b/tests/unit/harness/test_cu_grok_vision.py@@ -5,7 +5,7 @@ DID dispatch to the screenshot harness (routing fixed), but the harness gave up:exit 2 · [cu] giving up after 3 model failures … ComputerUseLoop providerchain failed: 3 provider(s) skipped — no vision; claude-api(haiku):- incomplete chunked read; openrouter(opus-4.8): Kein O…+ incomplete chunked read; openrouter(opus-4.8): Kein O… # i18n-allow: verbatim forensic log excerpt from the live incident, not translatable without falsifying the recordRoot cause: ``screenshot_only_loop._call_brain`` skips every provider whose``supports_vision`` is False when a screenshot is attached, and the one livediff --git a/tests/unit/harness/test_cu_human_handoff_pause.py b/tests/unit/harness/test_cu_human_handoff_pause.pyindex 1326f39182..d6e71d8736 100644--- a/tests/unit/harness/test_cu_human_handoff_pause.py+++ b/tests/unit/harness/test_cu_human_handoff_pause.py@@ -134,7 +134,7 @@ async def test_announces_handoff_request_in_german(monkeypatch):ctx = SimpleNamespace(bus=bus)await loop._await_human_handoff_clearance(- ctx, "Kannst du bitte meine Mails oeffnen?", 1, None,+ ctx, "Kannst du bitte meine Mails oeffnen?", 1, None, # i18n-allow: simulated German user utterance, content under testreason="login / password entry",)await asyncio.sleep(0.01) # let the detached announcement task rundiff --git a/tests/unit/harness/test_cu_loop_robustness.py b/tests/unit/harness/test_cu_loop_robustness.pyindex f8bc3dfc39..7731c3a8c9 100644--- a/tests/unit/harness/test_cu_loop_robustness.py+++ b/tests/unit/harness/test_cu_loop_robustness.py@@ -390,7 +390,7 @@ async def test_exhausted_vision_chain_exits_with_no_provider_code() -> None:return self.brainctx = make_ctx(_DeadChainManager())- chunks = await run_loop(ctx, "öffne mein spotify und spiel das lied")+ chunks = await run_loop(ctx, "öffne mein spotify und spiel das lied") # i18n-allow: simulated German user utterance, content under testfinal = chunks[-1]assert final.is_final@@ -701,7 +701,7 @@ class JudgingBrain(FakeBrain):async def test_premature_done_is_rejected_and_mission_continues() -> None:- """The live 'Öffne Chrome' failure: the model declares done without+ """The live 'open chrome' failure: the model declares done withouthaving opened anything. The judge must reject it, the loop must keepworking, and only a verified done may end the mission."""brain = JudgingBrain(@@ -963,7 +963,7 @@ async def test_compound_goal_activates_planner() -> None:judge_script=['{"done": true, "proof": "settings page visible"}'],)ctx = make_ctx(brain, verify=True)- chunks = await run_loop(ctx, "oeffne chrome und navigiere zu den einstellungen")+ chunks = await run_loop(ctx, "oeffne chrome und navigiere zu den einstellungen") # i18n-allow: simulated German user utterance, content under testassert chunks[-1].exit_code == 0assert len(brain.planner_calls) == 1@@ -981,7 +981,7 @@ async def test_search_discipline_not_injected_for_non_music_goals() -> None:judge_script=['{"done": true, "proof": "ok"}'],)ctx = make_ctx(brain, verify=True)- await run_loop(ctx, "oeffne chrome und navigiere zu den einstellungen")+ await run_loop(ctx, "oeffne chrome und navigiere zu den einstellungen") # i18n-allow: simulated German user utterance, content under testassert brain.executor_calls, "executor was never consulted"for _system, user in brain.executor_calls:@@ -1056,7 +1056,7 @@ async def test_plan_step_advances_on_state_change_not_on_wait() -> None:judge_script=['{"done": true, "proof": "ok"}'],)ctx = make_ctx(brain, verify=True)- chunks = await run_loop(ctx, "oeffne chrome und navigiere zu den einstellungen")+ chunks = await run_loop(ctx, "oeffne chrome und navigiere zu den einstellungen") # i18n-allow: simulated German user utterance, content under testassert chunks[-1].exit_code == 0assert len(brain.executor_calls) == 2@@ -1352,7 +1352,7 @@ async def test_persistent_observe_timeout_fails_after_cap_not_at_step_1(# Repeated-type guard (live forensic 2026-06-22, Microsoft-Store/Minecraft# turn): the model typed the SAME query "Minecraft" into the Store search box# TWICE in a row (steps 6.3 + 7.3) because it could not tell the first type had-# landed -- "das ist ja dumm". A back-to-back identical type into a field that+# landed -- "well that's just dumb". A back-to-back identical type into a field that# already holds the text is a redundant no-op. Suppress the repeat (like the# click toggle-stop) and push the model to the NEXT step instead of mashing the# same query. Provider/OS-agnostic: pure loop control.@@ -1465,9 +1465,9 @@ def test_drag_is_in_the_action_vocabulary() -> None:# ---------------------------------------------------------------------------# General "no progress -> re-target" nudge (user mandate 2026-06-22: the loop# must GENERALLY recognise a missed target instead of mashing the same action ---# "das war nur ein Beispiel ... ich möchte nicht dass es nur auf dieses eine-# Beispiel bezogen ist ... unsere Mechanik ist Screenshot/Tastatur/Maus, das-# bleibt"). The instant an action leaves the screen UNCHANGED, the loop tells+# "that was just an example ... I don't want this to apply only to this one+# example ... our mechanism is screenshot/keyboard/mouse, that stays the+# same"). The instant an action leaves the screen UNCHANGED, the loop tells# the model -- for ANY action type, ANY app -- that it had no effect and to# re-target, BEFORE the 3-strike stuck abort.# ---------------------------------------------------------------------------@@ -1869,7 +1869,7 @@ async def test_ensure_on_primary_reruns_after_mid_mission_open_app(# ---------------------------------------------------------------------------# Problem 2 — a guard-BLOCKED repeated click must TELL the model (or it spins to-# the no-progress abort: "macht nicht weiter", live 2026-06-28).+# the no-progress abort: "won't keep going", live 2026-06-28).# ---------------------------------------------------------------------------diff --git a/tests/unit/harness/test_cu_verifier_proof_language.py b/tests/unit/harness/test_cu_verifier_proof_language.pyindex 8ecf0f5986..1edf6fa09f 100644--- a/tests/unit/harness/test_cu_verifier_proof_language.py+++ b/tests/unit/harness/test_cu_verifier_proof_language.py@@ -1,6 +1,6 @@"""The Computer-Use verifier writes its ``proof`` in the turn's output language.-Live bug 2026-06-27 (German voice session 07:47): "öffne meinen Explorer und+Live bug 2026-06-27 (German voice session 07:47): "öffne meinen Explorer und # i18n-allow: verbatim forensic quote of the live German voice utterance under testnavigiere zum Videos-Ordner" was read back as"Erledigt — The file explorer window is open and navigated to the 'Videos'folder, as shown" — a German frame ("Erledigt —") around an ENGLISH body. The@@ -207,10 +207,10 @@ async def test_generic_verifier_user_message_carries_german_directive() -> None:executor_script=['{"action": "open_app", "name": "explorer"}','{"action": "done"}'],plan_script=['{"plan": []}'],- judge_script=['{"done": true, "proof": "Der Explorer ist offen"}'],+ judge_script=['{"done": true, "proof": "Der Explorer ist offen"}'], # i18n-allow: simulated German runtime-output proof, content under test)ctx = make_ctx(brain, verify=True, titles=["Datei-Explorer"] * 5)- await run_loop(ctx, "öffne den datei explorer", output_language="de")+ await run_loop(ctx, "öffne den datei explorer", output_language="de") # i18n-allow: simulated German user utterance, content under testassert brain.judge_calls, "the verifier was never consulted"assert "german" in _judge_user_messages(brain)diff --git a/tests/unit/harness/test_screenshot_only_loop.py b/tests/unit/harness/test_screenshot_only_loop.pyindex 2b069a8fb4..d4d7350c57 100644--- a/tests/unit/harness/test_screenshot_only_loop.py+++ b/tests/unit/harness/test_screenshot_only_loop.py@@ -912,11 +912,11 @@ def test_execute_type_settles_before_dispatch(monkeypatch) -> None:# Per-mission open_app launch cap (window-spam fix, 2026-05-29). A loop that# never reaches "done" (a goal it cannot ground, or a model that keeps asking# to open the app) used to re-launch the same app every few steps -> 4-7 real-# windows per mission, dozens across retried missions ("30 Rechner für 7+7",-# "30 Editoren für Hello World", live: 7 Spotify windows in one 51s mission).+# windows per mission, dozens across retried missions ("30 calculators for 7+7",+# "30 text editors for Hello World", live: 7 Spotify windows in one 51s mission).# The cap launches each app AT MOST ONCE per mission; any further open_app for# the same app is suppressed with a history note pointing the model at the-# already-open window. "einer langt" (user mandate 2026-05-29).+# already-open window. "one is enough" (user mandate 2026-05-29).# ---------------------------------------------------------------------------diff --git a/tests/unit/marketplace/test_plugin_relevance.py b/tests/unit/marketplace/test_plugin_relevance.pyindex 8cd3f7bf0a..2796e2fbc9 100644--- a/tests/unit/marketplace/test_plugin_relevance.py+++ b/tests/unit/marketplace/test_plugin_relevance.py@@ -62,7 +62,7 @@ def test_cardless_mcp_dropped_on_unrelated_flight_turn():kept = [t.namefor t in filter_plugin_tools(- "Was ist der kürzeste Flug von München nach Bora Bora?", tools+ "Was ist der kürzeste Flug von München nach Bora Bora?", tools # i18n-allow: simulated German user utterance, content under test)]assert "search_web" in kept # native tool survives@@ -129,7 +129,7 @@ def test_cardless_mcp_kept_when_user_names_it():tools = [_Tool("notebooklm-mcp/notebook_query"), _Tool("search_web")]for utter in ("ask NotebookLM about my sources",- "frag das Notebook LM nach der Zusammenfassung",+ "frag das Notebook LM nach der Zusammenfassung", # i18n-allow: simulated German user utterance, content under test"use notebook-lm for this",):kept = [t.name for t in filter_plugin_tools(utter, tools)]@@ -152,7 +152,7 @@ def test_carded_plugin_kept_when_relevant():def test_carded_plugin_dropped_on_unrelated_turn():tools = _heavy("github", 37) + _heavy("linear", 35) + [_Tool("run-shell")]- kept = [t.name for t in filter_plugin_tools("erzähl mir einen witz", tools)]+ kept = [t.name for t in filter_plugin_tools("erzähl mir einen witz", tools)] # i18n-allow: simulated German user utterance, content under testassert "run-shell" in keptassert all(not n.startswith("github/") and not n.startswith("linear/") for n in kept@@ -161,7 +161,7 @@ def test_carded_plugin_dropped_on_unrelated_turn():def test_native_tools_never_touched():tools = [_Tool("run-shell"), _Tool("screen-snapshot"), _Tool("github/create_issue")]- kept = [t.name for t in filter_plugin_tools("erzähl einen witz", tools)]+ kept = [t.name for t in filter_plugin_tools("erzähl einen witz", tools)] # i18n-allow: simulated German user utterance, content under testassert "run-shell" in kept and "screen-snapshot" in kept # native always keptassert all("github/" not in n for n in kept) # irrelevant plugin droppeddiff --git a/tests/unit/marketplace/test_usage_cards.py b/tests/unit/marketplace/test_usage_cards.pyindex 3a40da9fab..8ee1871434 100644--- a/tests/unit/marketplace/test_usage_cards.py+++ b/tests/unit/marketplace/test_usage_cards.py@@ -15,5 +15,5 @@ def test_unknown_plugin_returns_none():def test_keyword_match_is_case_insensitive_substring():card = UsageCard(plugin_id="x", keywords=["kalender", "termine"], body="...")- assert card.matches("Was habe ich heute für TERMINE?") is True- assert card.matches("erzähl mir einen witz") is False+ assert card.matches("Was habe ich heute für TERMINE?") is True # i18n-allow: simulated German user utterance, content under test+ assert card.matches("erzähl mir einen witz") is False # i18n-allow: simulated German user utterance, content under testdiff --git a/tests/unit/mcp/test_registry.py b/tests/unit/mcp/test_registry.pyindex e8bb81f6cb..dad46adf44 100644--- a/tests/unit/mcp/test_registry.py+++ b/tests/unit/mcp/test_registry.py@@ -1,9 +1,9 @@-"""Unit-Tests für die MCP-Registry.+"""Unit tests for the MCP registry.-Seit 2026-04-22 ist ``BOOTSTRAP_SERVERS`` bewusst leer — alle Server-kommen aus ``mcp.json`` (User-editierbar oder via Claude-Desktop-Import).-Die Tests decken deshalb die Registry-Mechanik, nicht eine kuratierte-Server-Liste.+Since 2026-04-22, ``BOOTSTRAP_SERVERS`` is deliberately empty — all servers+come from ``mcp.json`` (user-editable or via Claude Desktop import).+The tests therefore cover the registry mechanics, not a curated+server list."""from __future__ import annotations@@ -23,8 +23,8 @@ def _make_spec(name: str = "custom-mcp", *, mandatory: bool = False) -> MCPServedef test_bootstrap_servers_is_empty_by_design() -> None:- """Bewusste Architektur-Entscheidung vom 2026-04-22: keine- vorkuratierten Server — alle Server kommen aus ``mcp.json``."""+ """Deliberate architecture decision from 2026-04-22: no+ pre-curated servers — all servers come from ``mcp.json``."""assert BOOTSTRAP_SERVERS == []@@ -70,7 +70,7 @@ def test_registry_all_specs_returns_all_registered() -> None:def test_mcp_server_spec_is_frozen() -> None:- """Specs sind pydantic-frozen — Mutation muss scheitern."""+ """Specs are pydantic-frozen — mutation must fail."""spec = _make_spec()with pytest.raises((AttributeError, Exception)):spec.name = "changed" # type: ignore[misc]diff --git a/tests/unit/memory/conftest.py b/tests/unit/memory/conftest.pyindex 033aae1361..032e6bb1a4 100644--- a/tests/unit/memory/conftest.py+++ b/tests/unit/memory/conftest.py@@ -1,8 +1,8 @@-"""Shared Fixtures fuer die Curator-/Memory-Unit-Tests.+"""Shared fixtures for the curator/memory unit tests.-Fakes statt Mocks:-- `FakeBus` fuer den Merger (sammelt alle publizierten Events in einer Liste).-- Fresh-Workspace pro Test via `tmp_path` — keine Kollision zwischen Tests.+Fakes instead of mocks:+- `FakeBus` for the merger (collects all published events in a list).+- Fresh workspace per test via `tmp_path` — no collision between tests."""from __future__ import annotations@@ -20,20 +20,20 @@ from jarvis.memory.workspace import Workspace# -----------------------------------------------------------------------# FakeBus — sammelt publizierte Events statt wirklich zu dispatchen+# FakeBus — collects published events instead of actually dispatching them# ----------------------------------------------------------------------@dataclassclass FakeBus:- """Minimaler Bus-Fake fuer Merger-Tests. Speichert Events in `published`."""+ """Minimal bus fake for merger tests. Stores events in `published`."""published: list[Event] = field(default_factory=list)async def publish(self, event: Event) -> None:self.published.append(event)- # Der Merger nutzt nur .publish — die restlichen EventBus-Methoden brauchen- # wir nicht. Stubs halten mypy-mässig ruhig.+ # The merger only uses .publish — we don't need the rest of the+ # EventBus methods. Stubs keep mypy quiet.def subscribe(self, *_args, **_kwargs) -> None: # pragma: no coverpass@@ -55,7 +55,7 @@ def fake_bus() -> FakeBus:@pytest.fixturedef workspace(tmp_path: Path) -> Workspace:- """Frischer Workspace im tmp_path; initialisiert via Workspace.ensure."""+ """Fresh workspace in tmp_path; initialized via Workspace.ensure."""return Workspace.ensure(tmp_path / "ws")diff --git a/tests/unit/memory/test_curator_merger.py b/tests/unit/memory/test_curator_merger.pyindex 74371a120e..cafe560abc 100644--- a/tests/unit/memory/test_curator_merger.py+++ b/tests/unit/memory/test_curator_merger.py@@ -1,11 +1,11 @@-"""Unit-Tests fuer `jarvis.memory.curator.merger.Merger`.--Deckt ab:-- User-Facts landen in USER.md (set + Observation-Log).-- Person-Facts legen people/<slug>.md an und schreiben Observations.-- Listen-Felder werden appended + dedupliziert.-- Duplikat-Append → report.skipped inkrementiert (nicht applied).-- Bus-Events `ProfileUpdated` werden nach Persistenz emittiert.+"""Unit tests for `jarvis.memory.curator.merger.Merger`.++Covers:+- User facts land in USER.md (set + observation log).+- Person facts create people/<slug>.md and write observations.+- List fields get appended + deduplicated.+- Duplicate append → report.skipped is incremented (not applied).+- Bus events `ProfileUpdated` are emitted after persistence."""from __future__ import annotations@@ -69,7 +69,7 @@ class TestUserScalarMerge:async def test_also_writes_observation_log_for_scalar_set(self, merger: Merger, profile: UserProfile) -> None:- """Bei jedem Scalar-Set zusaetzlich Observations-Append fuer Audit-Trail."""+ """Every scalar set also appends an observation for the audit trail."""cand = _cand("user", "identity", "name", "Ruben", evidence="User: 'ich bin Ruben'")@@ -83,7 +83,7 @@ class TestUserScalarMerge:async def test_same_value_counts_as_skipped(self, merger: Merger, profile: UserProfile) -> None:- """Wenn der Wert schon gesetzt ist, erhoeht der Merger report.skipped."""+ """If the value is already set, the merger increments report.skipped."""profile.set("identity", "name", "Ruben")profile.save()@@ -167,7 +167,7 @@ class TestPersonMerge:assert report.applied == 1assert report.failed == 0- # Datei wurde angelegt+ # File was createdpersons = person_store.list_all()assert len(persons) == 1laura = persons[0]@@ -183,7 +183,7 @@ class TestPersonMerge:merger: Merger,profile: UserProfile,) -> None:- """Kernregel: person:Laura darf USER.md NICHT anfassen."""+ """Core rule: person:Laura must NOT touch USER.md."""before_meta = dict(profile.meta)cand = _cand(@@ -238,10 +238,10 @@ class TestBusEvents:async def test_no_events_when_nothing_applied(self, merger: Merger, fake_bus, profile: UserProfile) -> None:- """Bei `applied == 0` duerfen keine Events publiziert werden."""+ """When `applied == 0`, no events may be published."""profile.set("identity", "name", "Ruben")profile.save()- # Candidate setzt den gleichen Wert → skipped, nicht applied+ # Candidate sets the same value → skipped, not appliedcand = _cand("user", "identity", "name", "Ruben")report = await merger.apply([cand])@@ -282,7 +282,7 @@ class TestEdgeCases:async def test_observation_field_falls_into_markdown(self, merger: Merger, profile: UserProfile) -> None:- """Ein Candidate mit field='observation' landet nur in der Markdown-Section."""+ """A candidate with field='observation' lands only in the markdown section."""cand = _cand("user","values",diff --git a/tests/unit/memory/test_curator_validator.py b/tests/unit/memory/test_curator_validator.pyindex 4f673dcd7a..cca8eef3bc 100644--- a/tests/unit/memory/test_curator_validator.py+++ b/tests/unit/memory/test_curator_validator.py@@ -1,13 +1,13 @@-"""Unit-Tests fuer `jarvis.memory.curator.validator.Validator`.+"""Unit tests for `jarvis.memory.curator.validator.Validator`.-Fokus — der Validator ist die **letzte Verteidigung** gegen Subject-Confusion:+Focus — the validator is the **last line of defense** against subject confusion:-- Confidence-Thresholds: <0.5 → reject, 0.5-0.7 → review, >=0.7 → accept.-- Laura-Szenario: `subject="user", field="name", value="Laura"` bei- existierendem `people/laura.md` → REJECT wegen Kollision.-- Pronoun-False-Positives (`person:er`, `person:sie`) → REJECT.-- Do-Not-Record-Keywords (Politik, Mental Health, MBTI) → REJECT.-- Overwrite-Schutz: bestehender Name + neuer Name bei conf<0.85 → REVIEW.+- Confidence thresholds: <0.5 → reject, 0.5-0.7 → review, >=0.7 → accept.+- Laura scenario: `subject="user", field="name", value="Laura"` when+ `people/laura.md` already exists → REJECT due to collision.+- Pronoun false positives (`person:er`, `person:sie`) → REJECT.+- Do-not-record keywords (politics, mental health, MBTI) → REJECT.+- Overwrite protection: existing name + new name at conf<0.85 → REVIEW."""from __future__ import annotations@@ -23,7 +23,7 @@ from jarvis.memory.curator.validator import (# -----------------------------------------------------------------------# Helper-Factory fuer Test-Candidates+# Helper factory for test candidates# ----------------------------------------------------------------------def _user_cand(@@ -85,7 +85,7 @@ class TestConfidenceThresholds:def test_confidence_in_review_band_goes_to_review(self, validator: Validator) -> None:"""0.5 <= conf < 0.7 → review."""- # Feld ohne Overwrite-Konflikt (pref wirkt nur bei name/preferred_address)+ # Field without an overwrite conflict (pref only applies to name/preferred_address)cand = _user_cand(cluster="communication", field="verbosity", value="tldr", confidence=0.6)@@ -97,7 +97,7 @@ class TestConfidenceThresholds:def test_confidence_at_accept_threshold_is_accepted(self, validator: Validator) -> None:- """conf >= 0.7 und kein Konflikt → accept."""+ """conf >= 0.7 and no conflict → accept."""cand = _user_cand(cluster="communication",field="verbosity",@@ -118,7 +118,7 @@ class TestConfidenceThresholds:# ======================================================================class TestLauraScenario:- """Wenn `people/laura.md` existiert, darf 'Laura' NICHT als user.name durchgehen."""+ """If `people/laura.md` exists, 'Laura' must NOT pass as user.name."""def test_rejects_laura_as_user_name_when_laura_exists_as_person(self, validator: Validator, person_store@@ -130,14 +130,14 @@ class TestLauraScenario:cand = _user_cand(field="name", value="Laura", confidence=0.9)result = validator.validate([cand])- assert len(result.rejected) == 1, f"Laura muss rejected werden: {result}"+ assert len(result.rejected) == 1, f"Laura must be rejected: {result}"_, reason = result.rejected[0]assert "kollision" in reason.lower() or "name-koll" in reason.lower()def test_ruben_as_user_name_is_accepted_even_with_laura_person_present(self, validator: Validator, person_store) -> None:- """Gegenprobe: fremde Person-Namen blocken nicht den echten User-Namen."""+ """Counter-check: unrelated person names don't block the real user name."""person_store.get_or_create("Laura", relationship="partner")cand = _user_cand(field="name", value="Ruben", confidence=0.95)@@ -166,7 +166,7 @@ class TestPronounRejection:for p in ("he", "she", "they", "them"):cand = _person_cand(p, confidence=0.9)result = validator.validate([cand])- assert len(result.rejected) == 1, f"Pronoun '{p}' muss rejected werden"+ assert len(result.rejected) == 1, f"Pronoun '{p}' must be rejected"# ======================================================================@@ -187,7 +187,7 @@ class TestSubjectSanity:assert len(result.rejected) == 1def test_rejects_person_equal_to_user_name(self, validator: Validator, profile) -> None:- """Wenn User "Ruben" heisst, darf subject=person:Ruben nicht akzeptiert werden."""+ """If the user's name is "Ruben", subject=person:Ruben must not be accepted."""profile.set("identity", "name", "Ruben")cand = _person_cand("Ruben", confidence=0.9)result = validator.validate([cand])@@ -203,7 +203,7 @@ class TestDoNotRecord:cand = _user_cand(cluster="values",field="observation",- value="Sympathie fuer die Linkspartei",+ value="Sympathie fuer die Linkspartei", # i18n-allow: German do-not-record keyword ("Partei"/party) matched by the validator's reject logicevidence="User: 'ich mag die Linkspartei'",confidence=0.9,)@@ -247,7 +247,7 @@ class TestDoNotRecord:# ======================================================================-# Overwrite-Schutz fuer identity.name / preferred_address+# Overwrite protection for identity.name / preferred_address# ======================================================================class TestOverwriteProtection:@@ -282,7 +282,7 @@ class TestOverwriteProtection:def test_same_name_value_passes_without_flagging(self, validator: Validator, profile) -> None:- """Neuer Name == existierender Name → kein Konflikt."""+ """New name == existing name → no conflict."""profile.set("identity", "name", "Ruben")cand = _user_cand(field="name", value="Ruben", confidence=0.9)result = validator.validate([cand])@@ -291,7 +291,7 @@ class TestOverwriteProtection:def test_overwrite_protection_for_scalar_field_contradiction(self, validator: Validator, profile) -> None:- """Nicht-name-Skalare: bestehender Wert + neuer abweichender Wert bei conf<0.85 → review."""+ """Non-name scalars: existing value + new differing value at conf<0.85 → review."""profile.set("communication", "verbosity", "tldr")cand = _user_cand(@@ -312,7 +312,7 @@ class TestBatchValidation:def test_mixed_batch_sorts_correctly(self, validator: Validator, person_store) -> None:- """Ein Mix aus accept/review/reject landet in den richtigen Buckets."""+ """A mix of accept/review/reject lands in the right buckets."""person_store.get_or_create("Laura", relationship="partner")accepted_cand = _user_cand(diff --git a/tests/unit/memory/test_frontmatter.py b/tests/unit/memory/test_frontmatter.pyindex 1cbe211dc3..4a625888a0 100644--- a/tests/unit/memory/test_frontmatter.py+++ b/tests/unit/memory/test_frontmatter.py@@ -1,6 +1,6 @@-"""Unit-Tests fuer `jarvis.memory.frontmatter`.+"""Unit tests for `jarvis.memory.frontmatter`.-Parse/Write-Roundtrips, Section-Replace/-Append, Fehlerresilienz bei kaputtem+Parse/write roundtrips, section replace/append, error resilience against brokenYAML."""from __future__ import annotations@@ -34,7 +34,7 @@ class TestParseAndWrite:assert "Some text." in parsed_bodydef test_body_without_frontmatter_returns_empty_meta(self) -> None:- """Legacy-File ohne Frontmatter darf nicht crashen."""+ """A legacy file without frontmatter must not crash."""text = "# Just Markdown\n\nNo frontmatter here."meta, body = parse_frontmatter(text)assert meta == {}@@ -48,23 +48,23 @@ class TestParseAndWrite:assert "# Body" in bodydef test_malformed_yaml_returns_empty_meta_and_preserves_body(self) -> None:- """Kaputtes YAML → leeres Dict, Body bleibt erhalten (nicht raisen)."""+ """Broken YAML → empty dict, body is preserved (does not raise)."""text = "---\nkey: : invalid: yaml: [\n---\n\n# Body retained"meta, body = parse_frontmatter(text)- # Empty dict bei Parse-Fehler+ # Empty dict on parse errorassert meta == {}- # Der Body muss erhalten sein, damit wir keine Daten verlieren+ # The body must be preserved so we don't lose dataassert "# Body retained" in bodydef test_missing_closing_delim_falls_back_to_no_frontmatter(self) -> None:- """Kein zweites `---` → kein Frontmatter parsen, Body == Original."""+ """No second `---` → don't parse frontmatter, body == original."""text = "---\nkey: value\n\nNo close delim\n"meta, body = parse_frontmatter(text)assert meta == {}assert body == textdef test_non_dict_yaml_becomes_raw(self) -> None:- """YAML das nur eine Liste/Zahl ist → wir wrappen es als `_raw`."""+ """YAML that is only a list/number → we wrap it as `_raw`."""text = "---\n- one\n- two\n---\n\n# Body"meta, body = parse_frontmatter(text)assert meta.get("_raw") == ["one", "two"]@@ -74,7 +74,7 @@ class TestParseAndWrite:text = "---\r\nkey: value\r\n---\r\n\r\n# Body"meta, body = parse_frontmatter(text)assert meta == {"key": "value"}- # Body enthaelt den Rest (evtl. mit CR)+ # Body contains the rest (possibly with CR)assert "Body" in body@@ -83,7 +83,7 @@ class TestParseAndWrite:# ======================================================================class TestReplaceSection:- """`replace_section` tauscht den Inhalt zwischen Start- und End-Marker."""+ """`replace_section` swaps the content between the start and end markers."""def test_replace_content_between_markers(self) -> None:body = (@@ -101,7 +101,7 @@ class TestReplaceSection:assert "<!-- curator:context:end -->" in resultdef test_no_markers_leaves_body_unchanged(self) -> None:- """Ohne Marker → body identisch zurueck (wir loggen, raisen nicht)."""+ """Without markers → body returned unchanged (we log, don't raise)."""body = "# Titel\n\nKein Marker hier."result = replace_section(body, "context", "NEW")assert result == body@@ -137,14 +137,14 @@ class TestAppendToSection:assert "- [2026-04-21] baz: qux" in resultdef test_dedupes_identical_line(self) -> None:- """Identische Zeile → nicht erneut anhaengen."""+ """Identical line → not appended again."""body = ("<!-- curator:observations:start -->\n""- [2026-04-20] foo: bar\n""<!-- curator:observations:end -->")result = append_to_section(body, "observations", "- [2026-04-20] foo: bar")- # Nur eine Instanz der Zeile+ # Only one instance of the lineassert result.count("- [2026-04-20] foo: bar") == 1def test_append_into_empty_section(self) -> None:@@ -156,6 +156,6 @@ class TestAppendToSection:assert "- [2026-04-21] first" in resultdef test_no_markers_leaves_body_unchanged(self) -> None:- body = "# Titel, keine Marker"+ body = "# Title, no markers"result = append_to_section(body, "observations", "- foo")assert result == bodydiff --git a/tests/unit/memory/test_people_store.py b/tests/unit/memory/test_people_store.pyindex 4bb8f394b6..6a71c79c3e 100644--- a/tests/unit/memory/test_people_store.py+++ b/tests/unit/memory/test_people_store.py@@ -1,4 +1,4 @@-"""Unit-Tests fuer `jarvis.memory.people.PersonStore`."""+"""Unit tests for `jarvis.memory.people.PersonStore`."""from __future__ import annotationsfrom jarvis.memory.people import PersonStore@@ -16,21 +16,21 @@ class TestGetOrCreate:person = person_store.get_or_create("Laura", relationship="partner")assert person.path.exists()assert person.path.stem == person_slug("Laura")- # Relationship wurde aus Template gesetzt+ # Relationship was set from the templateassert person.relationship == "partner"def test_same_name_returns_same_file_no_duplicate(self, person_store: PersonStore) -> None:- """Zweiter get_or_create-Aufruf legt KEINE neue Datei an."""+ """A second get_or_create call creates NO new file."""p1 = person_store.get_or_create("Laura", relationship="partner")p2 = person_store.get_or_create("Laura", relationship="partner")assert p1.path == p2.path- # Nur eine Datei im people/+ # Only one file in people/assert len(person_store.list_all()) == 1def test_umlauts_in_name_become_slug(self, person_store: PersonStore) -> None:- p = person_store.get_or_create("Laura Müller", relationship="partner")+ p = person_store.get_or_create("Laura Müller", relationship="partner") # i18n-allow: German umlaut name, matched by the slug-normalization logic under testassert p.path.stem == "laura_mueller"@@ -52,7 +52,7 @@ class TestFindByAlias:assert found.name == "Laura"def test_finds_by_alias_field(self, person_store: PersonStore) -> None:- """Wenn Person einen Spitznamen im `aliases`-Feld hat, muss find_by_alias matchen."""+ """If a person has a nickname in the `aliases` field, find_by_alias must match it."""person = person_store.get_or_create("Laura", relationship="partner")assert person.add_alias("Lora") is Trueperson.save()diff --git a/tests/unit/memory/test_user_profile.py b/tests/unit/memory/test_user_profile.pyindex f058f108a9..6a2e94a8a1 100644--- a/tests/unit/memory/test_user_profile.py+++ b/tests/unit/memory/test_user_profile.py@@ -1,7 +1,7 @@-"""Unit-Tests fuer `jarvis.memory.user_profile.UserProfile`.+"""Unit tests for `jarvis.memory.user_profile.UserProfile`.-Deckt: get/set, append_list mit Dedupe, save+reload-Roundtrip,-render_for_prompt (Name + Budget), reload nach manueller File-Edits.+Covers: get/set, append_list with dedupe, save+reload roundtrip,+render_for_prompt (name + budget), reload after manual file edits."""from __future__ import annotations@@ -24,7 +24,7 @@ class TestSetAndGet:def test_set_same_value_returns_false(self, profile: UserProfile) -> None:profile.set("identity", "name", "Ruben")- # Gleicher Wert → kein Change+ # Same value → no changeassert profile.set("identity", "name", "Ruben") is Falsedef test_set_overwrites_existing_value(self, profile: UserProfile) -> None:@@ -41,7 +41,7 @@ class TestSetAndGet:profile.get("unknown_cluster", "field")def test_get_returns_none_for_unset_field(self, profile: UserProfile) -> None:- # Template setzt "name" auf null — das wird als None durchgereicht+ # The template sets "name" to null — this is passed through as Noneassert profile.get("identity", "name") is None@@ -163,13 +163,13 @@ class TestPersistence:profile.set("identity", "name", "Ruben")profile.save()reloaded = UserProfile.load(profile.path)- # last_updated wird automatisch bei jedem save gesetzt+ # last_updated is set automatically on every saveassert reloaded.meta.get("last_updated") is not Nonedef test_reload_picks_up_manual_file_edits(self, profile: UserProfile, tmp_path: Path) -> None:- """reload() muss manuelle Edits an USER.md einlesen (User-Edits respektieren)."""+ """reload() must pick up manual edits to USER.md (respect user edits)."""# Zustand: leeres Profile.assert profile.get("identity", "name") is None@@ -188,7 +188,7 @@ class TestPersistence:# In-Memory-Instanz weiss davon noch nichtsassert profile.get("identity", "name") is None- # Nach reload aber schon+ # But it does after reloadprofile.reload()assert profile.get("identity", "name") == "HandEdited"@@ -207,7 +207,7 @@ class TestAppendObservation:profile.append_observation(field_label="communication.humor_types",value="dry",- evidence="User: 'bitte nicht zu albern'",+ evidence="User: 'bitte nicht zu albern'", # i18n-allow: simulated German user evidence quote, content under test)profile.save()text = profile.path.read_text(encoding="utf-8")@@ -221,7 +221,7 @@ class TestAppendObservation:profile.append_observation("x.y", "v", "evidence")profile.save()text = profile.path.read_text(encoding="utf-8")- # Nur eine Instanz+ # Only one instanceassert text.count("x.y: v") == 1@@ -234,11 +234,11 @@ class TestRenderForPrompt:profile.set("identity", "name", "Ruben")out = profile.render_for_prompt()assert "Ruben" in out- # Header bleibt dabei- assert "Ueber den User" in out+ # Header is still included+ assert "Ueber den User" in out # i18n-allow: matches the real (currently German) header rendered by UserProfile.render_for_promptdef test_render_stays_within_budget(self, profile: UserProfile) -> None:- """Selbst mit viel Content darf das Rendering den Budget-Cap nicht sprengen."""+ """Even with a lot of content, rendering must not exceed the budget cap."""profile.set("identity", "name", "Ruben")profile.set("communication", "verbosity", "deep-dive")profile.append_list("communication", "humor_types", "dry")@@ -250,7 +250,7 @@ class TestRenderForPrompt:profile.append_observation("communication.misc",f"value_{i}_" + "x" * 80,- f"evidence fuer #{i}",+ f"evidence for #{i}",)out = profile.render_for_prompt()@@ -262,10 +262,10 @@ class TestRenderForPrompt:assert len(short) <= 80def test_render_without_name_still_works(self, profile: UserProfile) -> None:- """Template hat name=null — Render darf trotzdem nicht crashen."""+ """Template has name=null — rendering must not crash regardless."""out = profile.render_for_prompt()assert isinstance(out, str)- assert "Ueber den User" in out+ assert "Ueber den User" in out # i18n-allow: matches the real (currently German) header rendered by UserProfile.render_for_prompt# ======================================================================diff --git a/tests/unit/memory/test_workspace.py b/tests/unit/memory/test_workspace.pyindex 4256aec9b5..96a8810f5c 100644--- a/tests/unit/memory/test_workspace.py+++ b/tests/unit/memory/test_workspace.py@@ -1,9 +1,9 @@-"""Unit-Tests fuer `jarvis.memory.workspace`.+"""Unit tests for `jarvis.memory.workspace`.-Fokus:-- `Workspace.ensure` legt Default-Files an (USER.md, SOUL.md, people/).-- Idempotenz — zweiter `ensure`-Aufruf zerstoert nichts.-- `person_slug` normalisiert Namen zu safe Filenamen.+Focus:+- `Workspace.ensure` creates default files (USER.md, SOUL.md, people/).+- Idempotence — a second `ensure` call destroys nothing.+- `person_slug` normalizes names into safe filenames."""from __future__ import annotations@@ -24,7 +24,7 @@ from jarvis.memory.workspace import (# ======================================================================class TestWorkspaceEnsure:- """Default-Files werden angelegt; Idempotenz."""+ """Default files get created; idempotence."""def test_creates_user_md_soul_md_and_people_dir(self, tmp_path: Path) -> None:ws = Workspace.ensure(tmp_path / "ws")@@ -34,10 +34,10 @@ class TestWorkspaceEnsure:assert (ws.root / PEOPLE_DIR).is_dir(), "people/ fehlt nach ensure"def test_creates_bootstrap_when_user_md_is_empty(self, tmp_path: Path) -> None:- """BOOTSTRAP.md entsteht nur wenn USER.md anfangs leer ist (heuristic)."""+ """BOOTSTRAP.md is only created when USER.md starts out empty (heuristic)."""root = tmp_path / "ws"root.mkdir()- # Leeres USER.md vorbereiten → ensure soll BOOTSTRAP.md anlegen+ # Prepare an empty USER.md → ensure should create BOOTSTRAP.md(root / USER_MD).write_text("", encoding="utf-8")Workspace.ensure(root)@@ -45,14 +45,14 @@ class TestWorkspaceEnsure:assert (root / BOOTSTRAP_MD).exists()def test_ensure_is_idempotent(self, tmp_path: Path) -> None:- """Zweiter ensure-Aufruf ueberschreibt bestehende Files NICHT."""+ """A second ensure call does NOT overwrite existing files."""ws = Workspace.ensure(tmp_path / "ws")- # User-Edit simulieren- custom_content = "---\ncustom: true\n---\n\n# User hat eigene Notizen"+ # Simulate a user edit+ custom_content = "---\ncustom: true\n---\n\n# User has their own notes"ws.user_path.write_text(custom_content, encoding="utf-8")- # Zweiter ensure darf den User-Edit nicht zerstoeren+ # A second ensure must not destroy the user editWorkspace.ensure(ws.root)assert ws.user_path.read_text(encoding="utf-8") == custom_content@@ -77,10 +77,10 @@ class TestWorkspaceEnsure:# ======================================================================class TestPersonSlug:- """Slug-Regeln: lowercase, Umlaute expandiert, nicht-safe chars entfernt."""+ """Slug rules: lowercase, umlauts expanded, non-safe chars removed."""def test_basic_umlaut_expansion(self) -> None:- assert person_slug("Laura Müller") == "laura_mueller"+ assert person_slug("Laura Müller") == "laura_mueller" # i18n-allow: German umlaut name, matched by the slug-normalization logic under testdef test_dots_and_whitespace_stripped(self) -> None:assert person_slug("Dr. Paul O.") == "dr_paul_o"@@ -90,21 +90,21 @@ class TestPersonSlug:assert person_slug("Anne-Marie") == "anne-marie"def test_special_characters_removed(self) -> None:- # Slash, Backslash, Stern etc. sind NICHT safe auf Windows.+ # Slash, backslash, asterisk, etc. are NOT safe on Windows.assert person_slug("Foo/Bar*Baz?") == "foobarbaz"def test_empty_name_falls_back_to_unknown(self) -> None:- """Kein Crash wenn der Name leer oder komplett whitespace ist."""+ """No crash when the name is empty or entirely whitespace."""assert person_slug("") == "unknown"assert person_slug(" ") == "unknown"- # Nur-Sonderzeichen kollabiert auch zu 'unknown'+ # Special-characters-only also collapses to 'unknown'assert person_slug("???") == "unknown"def test_leading_trailing_whitespace_stripped(self) -> None:assert person_slug(" Ruben ") == "ruben"def test_sharp_s_expanded_to_ss(self) -> None:- assert person_slug("Weißbier") == "weissbier"+ assert person_slug("Weißbier") == "weissbier" # i18n-allow: German word testing sharp-s (ß) expansion, matched by the slug-normalization logic under testdef test_case_insensitive_result(self) -> None:assert person_slug("RUBEN") == "ruben"@@ -132,5 +132,5 @@ class TestBootstrapDetection:assert ws.bootstrap_path.exists()ws.consume_bootstrap()assert not ws.bootstrap_path.exists()- # zweiter Aufruf wirft nicht+ # Second call does not raisews.consume_bootstrap()diff --git a/tests/unit/memory/wiki/test_curator_llm.py b/tests/unit/memory/wiki/test_curator_llm.pyindex 306c5d39fb..eb6dc208c8 100644--- a/tests/unit/memory/wiki/test_curator_llm.py+++ b/tests/unit/memory/wiki/test_curator_llm.py@@ -186,7 +186,7 @@ def _ok_response() -> str:{"target": "entities/ruben-luetke.md","operation": "update",- "new_body": "---\ntype: entity\nslug: ruben-luetke\n---\n\n# Ruben Lütke\n",+ "new_body": "---\ntype: entity\nslug: ruben-luetke\n---\n\n# Ruben Lütke\n", # i18n-allow: proper name with umlaut used as wiki-page fixture data"rename_from": None,"reason": "added phase B1 milestone",}diff --git a/tests/unit/memory/wiki/test_page.py b/tests/unit/memory/wiki/test_page.pyindex 906482d325..763b0088a7 100644--- a/tests/unit/memory/wiki/test_page.py+++ b/tests/unit/memory/wiki/test_page.py@@ -44,7 +44,7 @@ def _valid_entity_markdown(slug: str = "ruben") -> str:"type: entity\n""entity_kind: person\n"f"slug: {slug}\n"- "aliases: [Rubén, Ruben Lütke]\n"+ "aliases: [Rubén, Ruben Lütke]\n" # i18n-allow: proper name with umlaut used as unicode-handling test fixture"created: 2026-05-11\n""updated: 2026-05-11\n""---\n"@@ -77,7 +77,7 @@ def test_parse_valid_entity_is_schema_valid(tmp_path: Path) -> None:assert page.is_schema_valid is Trueassert page.page_type == "entity"assert page.slug == "ruben"- assert page.frontmatter["aliases"] == "[Rubén, Ruben Lütke]"+ assert page.frontmatter["aliases"] == "[Rubén, Ruben Lütke]" # i18n-allow: proper name with umlaut, matched fixture valuedef test_parse_extracts_wikilinks_in_order(tmp_path: Path) -> None:@@ -317,15 +317,15 @@ def test_round_trip_unicode_body(tmp_path: Path) -> None:"---\n""type: entity\n""slug: ruben\n"- "aliases: [Rubén Lütke]\n"+ "aliases: [Rubén Lütke]\n" # i18n-allow: proper name with umlaut used as unicode round-trip test fixture"---\n"- "Café — über sechs Zeichen mit Umlauten: äöüß.\n"+ "Café — über sechs Zeichen mit Umlauten: äöüß.\n" # i18n-allow: German sentence deliberately testing umlaut/unicode round-tripping, content under test)path = _entity_page(tmp_path)page = parse_markdown(src, path)re_parsed = parse_markdown(render_page(page), path)assert re_parsed == page- assert "äöüß" in page.body+ assert "äöüß" in page.body # i18n-allow: matches the umlaut fixture body above, content under testdef test_render_includes_frontmatter_markers_even_when_empty() -> None:diff --git a/tests/unit/memory/wiki/test_prompt.py b/tests/unit/memory/wiki/test_prompt.pyindex eeb76c1261..59f9c49127 100644--- a/tests/unit/memory/wiki/test_prompt.py+++ b/tests/unit/memory/wiki/test_prompt.py@@ -86,7 +86,7 @@ def test_select_top_slugs_respects_limit() -> None:def test_select_top_slugs_ignores_stopwords() -> None:"""Common DE/EN function words don't dominate the ranking."""- source = "der und die das the and the openclaw bridge"+ source = "der und die das the and the openclaw bridge" # i18n-allow: German/English stopword mix, content under testcandidates = ["der-thing", "openclaw-bridge"]result = select_top_slugs(source, candidates)assert result and result[0] == "openclaw-bridge"diff --git a/tests/unit/memory/wiki/test_session_links.py b/tests/unit/memory/wiki/test_session_links.pyindex a9a7717cd9..f93f762279 100644--- a/tests/unit/memory/wiki/test_session_links.py+++ b/tests/unit/memory/wiki/test_session_links.py@@ -40,7 +40,7 @@ from jarvis.memory.wiki.session_links import (("ruben", "ruben"),(" Mixed Spaces ", "mixed-spaces"),("Personal_Jarvis", "personal-jarvis"),- ("Über Café", "uber-cafe"),+ ("Über Café", "uber-cafe"), # i18n-allow: German/accented word testing slugify's unicode handling, content under test])def test_slugify(raw: str, expected: str) -> None:assert slugify(raw) == expecteddiff --git a/tests/unit/plugins/brain/test_antigravity_brain.py b/tests/unit/plugins/brain/test_antigravity_brain.pyindex d8c8b0208c..148830bec7 100644--- a/tests/unit/plugins/brain/test_antigravity_brain.py+++ b/tests/unit/plugins/brain/test_antigravity_brain.py@@ -58,7 +58,7 @@ def _system_with_empty_standing_instructions() -> str:def test_cli_prompt_includes_standing_instructions_without_heavy_router_prompt():req = BrainRequest(- messages=(BrainMessage(role="user", content="Was ist das wertvollste Unternehmen?"),),+ messages=(BrainMessage(role="user", content="Was ist das wertvollste Unternehmen?"),), # i18n-allow: simulated German user utterance, content under testsystem=_system_with_standing_instructions(),)@@ -99,8 +99,8 @@ def test_cli_prompt_puts_current_empty_state_after_stale_history():req = BrainRequest(messages=(BrainMessage(role="user", content="Wasketup"),- BrainMessage(role="assistant", content="schef, alles laeuft."),- BrainMessage(role="user", content="Du musst das nicht mehr sagen."),+ BrainMessage(role="assistant", content="schef, alles laeuft."), # i18n-allow: simulated German assistant reply, content under test+ BrainMessage(role="user", content="Du musst das nicht mehr sagen."), # i18n-allow: simulated German user utterance, content under test),system=_system_with_empty_standing_instructions(),)diff --git a/tests/unit/plugins/tool/test_app_resolver.py b/tests/unit/plugins/tool/test_app_resolver.pyindex 711d588459..5c5ace8181 100644--- a/tests/unit/plugins/tool/test_app_resolver.py+++ b/tests/unit/plugins/tool/test_app_resolver.py@@ -154,7 +154,7 @@ def test_start_menu_shortcut_resolves_when_not_in_app_paths_or_path() -> None:"""Discord-class apps register ONLY a Start Menu .lnk (per-user Squirrelinstalls are absent from App Paths AND PATH). Live 2026-06-09:- open_app('discord') failed with 'Anwendung discord nicht gefunden', which+ open_app('discord') failed with 'Anwendung discord nicht gefunden', which # i18n-allow: verbatim forensic quote of the actual error text returned by the live bugforced the computer-use loop into unreliable taskbar pixel-clicking (itclicked Spotify, Discord's neighbour). The resolver must find the shortcut."""@@ -185,7 +185,7 @@ async def test_open_app_launches_discord_via_start_menu_shortcut() -> None:"""End-to-end regression for the live failure: open_app('discord') nowresolves the Start Menu shortcut and launches it via os.startfile instead- of returning 'nicht gefunden'."""+ of returning 'nicht gefunden'.""" # i18n-allow: verbatim forensic quote of the actual error text from the live bugprograms = _seed_start_menu(monkeypatch, tmp_path, r"Discord Inc/Discord.lnk")expected = str(programs / "Discord Inc" / "Discord.lnk")started: list[str] = []diff --git a/tests/unit/plugins/tool/test_computer_use_tool.py b/tests/unit/plugins/tool/test_computer_use_tool.pyindex d483cd1172..d1d50753df 100644--- a/tests/unit/plugins/tool/test_computer_use_tool.py+++ b/tests/unit/plugins/tool/test_computer_use_tool.py@@ -6,7 +6,7 @@ keyboard on THIS machine). Before this tool existed the router could only reachthe computer-use harness through the two-level ``dispatch_to_harness`` +magic-``harness``-string indirection, whose schema description never mentioneddesktop control — so the model picked the wrong tool (or invented one) and the-user heard a refusal for "öffne ein Terminal".+user heard a refusal for "öffne ein Terminal". # i18n-allow: simulated German user utterance, content under testThese tests pin the new tool's identity, schema and dispatch behaviour withoutan LLM: the tool forwards the goal verbatim to the canonical ``computer-use``@@ -60,7 +60,7 @@ class _FakeHarnessManager:def _ctx() -> ExecutionContext:return ExecutionContext(trace_id=uuid.uuid4(),- user_utterance="öffne ein Terminal",+ user_utterance="öffne ein Terminal", # i18n-allow: simulated German user utterance, content under testconfig={},memory_read=None,)diff --git a/tests/unit/plugins/tool/test_gmail_rest.py b/tests/unit/plugins/tool/test_gmail_rest.pyindex 521049562b..a1eaf6cd4d 100644--- a/tests/unit/plugins/tool/test_gmail_rest.py+++ b/tests/unit/plugins/tool/test_gmail_rest.py@@ -156,9 +156,9 @@ def test_tool_contract_shape():# ----------------------------------------------------------------------# Per-action risk (forensic 2026-06-19, session dc533e39): "Was habe ich-# heute auf dem Plan?" → morning-routine → gmail action=list_messages+# heute auf dem Plan?" → morning-routine → gmail action=list_messages # i18n-allow: simulated German user utterance, forensic quote# (read) was forced through the ask-tier confirm and Jarvis spoke "Soll-# ich die E-Mail wirklich senden?". Only send_message is consequential;+# ich die E-Mail wirklich senden?". Only send_message is consequential; # i18n-allow: verbatim quote of real German runtime voice output# reads must stay safe so the morning briefing can check unread mail# without a spurious send confirmation.# ----------------------------------------------------------------------diff --git a/tests/unit/plugins/tool/test_open_app_reuse.py b/tests/unit/plugins/tool/test_open_app_reuse.pyindex 3eba4e1655..b9a0774006 100644--- a/tests/unit/plugins/tool/test_open_app_reuse.py+++ b/tests/unit/plugins/tool/test_open_app_reuse.py@@ -62,7 +62,7 @@ async def test_launches_when_not_running(monkeypatch):monkeypatch.setattr(oa.window_state, "is_app_running", lambda n: None)res = await OpenAppTool().execute({"app_name": "obs"}, _ctx())assert res.success is True- assert "Gestartet" in (res.output or "")+ assert "Gestartet" in (res.output or "") # i18n-allow: matches the tool's real (currently German) readback textassert len(calls) == 1@@ -93,7 +93,7 @@ async def test_focus_failure_falls_through_to_launch(monkeypatch):monkeypatch.setattr(oa.window_state, "raise_window", lambda w: (False, "lock timeout"))res = await OpenAppTool().execute({"app_name": "obs"}, _ctx())assert res.success is True- assert "Gestartet" in (res.output or "") # launched after the raise failed+ assert "Gestartet" in (res.output or "") # launched after the raise failed # i18n-allow: matches the tool's real (currently German) readback textassert len(calls) == 1@@ -128,13 +128,13 @@ async def test_fresh_launch_raises_window_to_foreground(monkeypatch):async def test_raise_miss_keeps_success(monkeypatch):# The launch already succeeded; a foreground-raise miss must NOT flip the- # result to failure — it only softens the readback back to plain "Gestartet".+ # result to failure — it only softens the readback back to plain "Gestartet". # i18n-allow: quotes the tool's real (currently German) readback textcalls = _stub_launch(monkeypatch)monkeypatch.setattr(oa.window_state, "is_app_running", lambda n: None)monkeypatch.setattr(oa.window_state, "raise_after_launch", lambda n, **k: (False, "no window"))res = await OpenAppTool().execute({"app_name": "chrome"}, _ctx())assert res.success is True- assert "Gestartet" in (res.output or "")+ assert "Gestartet" in (res.output or "") # i18n-allow: matches the tool's real (currently German) readback textassert "vorn" not in (res.output or "").lower()assert len(calls) == 1@@ -149,7 +149,7 @@ async def test_raise_crash_never_breaks_launch(monkeypatch):monkeypatch.setattr(oa.window_state, "raise_after_launch", boom)res = await OpenAppTool().execute({"app_name": "chrome"}, _ctx())assert res.success is True # crash in the raise never fails the launch- assert "Gestartet" in (res.output or "")+ assert "Gestartet" in (res.output or "") # i18n-allow: matches the tool's real (currently German) readback textassert len(calls) == 1diff --git a/tests/unit/plugins/tool/test_profile_update.py b/tests/unit/plugins/tool/test_profile_update.pyindex 8306f287ff..7ba7f50c0d 100644--- a/tests/unit/plugins/tool/test_profile_update.py+++ b/tests/unit/plugins/tool/test_profile_update.py@@ -83,8 +83,10 @@ values:---# Ueber den User+<!-- i18n-allow: matches the real (currently German) header rendered by UserProfile -->## Observations ueber Zeit+<!-- i18n-allow: matches the real (currently German) header rendered by UserProfile --><!-- curator:observations:start --><!-- curator:observations:end -->@@ -186,7 +188,7 @@ async def test_do_not_record_category_is_declined(tmp_path):bus, events = _capturing_bus()res = await _tool(profile, bus).execute({"cluster": "values", "field": "top_values",- "value": "meine politische Partei", "evidence": "Ich waehle Partei X."},+ "value": "meine politische Partei", "evidence": "Ich waehle Partei X."}, # i18n-allow: German do-not-record keyword ("Partei"/party) matched by the tool's reject logicctx=None,)# Declined, but NOT an error (so the brain does not retry/claim failure).diff --git a/tests/unit/plugins/tool/test_spawn_worker_cooldown.py b/tests/unit/plugins/tool/test_spawn_worker_cooldown.pyindex 0dc5d78625..dc7fe0510b 100644--- a/tests/unit/plugins/tool/test_spawn_worker_cooldown.py+++ b/tests/unit/plugins/tool/test_spawn_worker_cooldown.py@@ -1,7 +1,7 @@"""Tests for the per-tool spawn cooldown.Live regression 2026-05-27 (mission_019e6983-{82e7,a83b,b0be}): ONE user-voice request ("Subagent für HTML-Slideshow") produced THREE mission cards+voice request ("Subagent für HTML-Slideshow") produced THREE mission cards # i18n-allow: verbatim forensic quote of the live German voice utterance under testin the Outputs UI within 10 seconds. Root cause: the user's long utterancewas VAD-fragmented across multiple turns, and each turn that landed in thebrain either re-matched a force-spawn phrase or the brain issued another@@ -88,7 +88,7 @@ async def test_cooldown_suppresses_duplicate_spawn() -> None:tool._active_dispatches = 1result = await tool.execute(- {"utterance": "Drogen in Schulen", "action": "noch eine Slideshow"},+ {"utterance": "Drogen in Schulen", "action": "noch eine Slideshow"}, # i18n-allow: simulated German user utterance, content under test_ctx(),)diff --git a/tests/unit/plugins/tts/test_cartesia_tts.py b/tests/unit/plugins/tts/test_cartesia_tts.pyindex 5784986ae6..9324a2a562 100644--- a/tests/unit/plugins/tts/test_cartesia_tts.py+++ b/tests/unit/plugins/tts/test_cartesia_tts.py@@ -250,7 +250,7 @@ async def test_text_heuristic_picks_de_when_caller_says_auto(patched_secret) ->mock_client.post = fake_post # type: ignore[assignment]tts._client = mock_client- [_ async for _ in tts.synthesize("Ich bin Jarvis und freue mich für Sie.")]+ [_ async for _ in tts.synthesize("Ich bin Jarvis und freue mich für Sie.")] # i18n-allow: German text synthesized to prove the German voice/locale is pickedassert captured["voice"]["id"] == "DE-VOICE-UUID"diff --git a/tests/unit/safety/test_tool_executor_plausibility.py b/tests/unit/safety/test_tool_executor_plausibility.pyindex 2d137ad889..f2a5c2fd8c 100644--- a/tests/unit/safety/test_tool_executor_plausibility.py+++ b/tests/unit/safety/test_tool_executor_plausibility.py@@ -1,12 +1,12 @@-"""Integration-Tests fuer den Plausibility-Hook im ``ToolExecutor`` (Phase 4).+"""Integration tests for the plausibility hook in ``ToolExecutor`` (Phase 4).-Kein voller End-to-End-Voice-Test — nur die drei kritischen Pfade:+Not a full end-to-end voice test — just the three critical paths:- 1. Ohne ``plausibility_context_fn``: Workflow laeuft wie vor Phase 4.- 2. Mit Context-Provider + low confidence + ``ask``-Tool: Approval wird- angefordert (auch wenn der Tier-Workflow das ohnehin tun wuerde).- 3. Whitelist-Downgrade: Plausibility-Check wird uebersprungen — sonst- wuerde der Guard die Whitelist-Logik kaputtmachen.+ 1. Without ``plausibility_context_fn``: the workflow runs as before Phase 4.+ 2. With a context provider + low confidence + an ``ask`` tool: approval is+ requested (even if the tier workflow would do so anyway).+ 3. Whitelist downgrade: the plausibility check is skipped — otherwise+ the guard would break the whitelist logic."""from __future__ import annotations@@ -42,7 +42,7 @@ class _MonitorTool(_FakeTool):class _AutoApproval(ApprovalWorkflow):- """Approval die immer auto-approved — Test isoliert das Confirmation-Trigger."""+ """Approval that always auto-approves — isolates the confirmation trigger under test."""def __init__(self, bus: EventBus, *, approve: bool = True) -> None:super().__init__(bus)@@ -76,11 +76,11 @@ def _executor_with_plausibility(@pytest.mark.asyncioasync def test_no_context_fn_runs_like_before() -> None:- """Ohne registrierte ``plausibility_context_fn`` greift kein Guard."""+ """Without a registered ``plausibility_context_fn`` no guard kicks in."""executor, approval = _executor_with_plausibility(context_fn=None)tool = _FakeTool()result = await executor.execute(tool, args={})- # ``ask``-Tier triggert ohnehin Approval -> 1 Call durch Tier-Workflow.+ # ``ask`` tier triggers approval anyway -> 1 call via the tier workflow.assert approval.wait_calls == 1assert result.success is Trueassert tool.called is True@@ -88,15 +88,15 @@ async def test_no_context_fn_runs_like_before() -> None:@pytest.mark.asyncioasync def test_low_confidence_monitor_does_not_force_approval() -> None:- """Bei ``monitor``-Tier + low confidence: Plausibility logged nur, kein Approval."""+ """At ``monitor`` tier + low confidence: plausibility only logs, no approval."""transcript = Transcript(text="x", language="de", confidence=0.2)executor, approval = _executor_with_plausibility(context_fn=lambda: (transcript, 5.0),)tool = _MonitorTool()result = await executor.execute(tool, args={})- # ``monitor``-Tier triggert nicht von sich aus Approval, und Plausibility- # bei monitor verlangt auch nichts -> 0 Approval-Calls.+ # ``monitor`` tier doesn't trigger approval by itself, and plausibility+ # at monitor doesn't require anything either -> 0 approval calls.assert approval.wait_calls == 0assert result.success is Trueassert tool.called is True@@ -104,12 +104,12 @@ async def test_low_confidence_monitor_does_not_force_approval() -> None:@pytest.mark.asyncioasync def test_low_confidence_ask_with_normal_tier_workflow() -> None:- """Low confidence + ask: Approval wird angefordert (Tier ODER Plausibility)."""+ """Low confidence + ask: approval is requested (tier OR plausibility)."""transcript = Transcript(text="x", language="de", confidence=0.2)executor, approval = _executor_with_plausibility(context_fn=lambda: (transcript, 5.0),)- tool = _FakeTool() # ask-Tier+ tool = _FakeTool() # ask tierresult = await executor.execute(tool, args={})assert approval.wait_calls == 1assert result.success is True@@ -117,24 +117,23 @@ async def test_low_confidence_ask_with_normal_tier_workflow() -> None:@pytest.mark.asyncioasync def test_whitelist_downgrade_skips_plausibility() -> None:- """Whitelist-Downgrade -> Plausibility-Check uebersprungen.+ """Whitelist downgrade -> plausibility check skipped.- Mandat: "Whitelist-downgraded Tools laufen weiter ohne Plausibility-Check- (sonst ist Whitelist sinnlos)."+ Mandate: "Whitelist-downgraded tools keep running without a plausibility+ check (otherwise the whitelist would be pointless).""""from jarvis.core.config import SafetyWhitelistConfig- # Whitelist-Pattern muss gegen ``"<tool_name> <serialized_args>"``- # matchen — bei leerem ``args`` strippt der Evaluator das trailing- # Space, also nutzen wir ein nicht-leeres Arg.+ # The whitelist pattern must match against ``"<tool_name> <serialized_args>"``+ # — with empty ``args`` the evaluator strips the trailing+ # space, so we use a non-empty arg.safety = SafetyConfig(whitelist=SafetyWhitelistConfig(commands=["monitor_tool *"]),)transcript = Transcript(text="x", language="de", confidence=0.1)- # Wir spy'en den Plausibility-Aufruf via den Context-Fn — wenn er- # NICHT aufgerufen wird, hat der Executor das Whitelist-Skip-Branch- # genommen.+ # We spy on the plausibility call via the context fn — if it's+ # NOT called, the executor took the whitelist-skip branch.calls: list[bool] = []def fake_context() -> tuple[Transcript, float]:@@ -147,36 +146,36 @@ async def test_whitelist_downgrade_skips_plausibility() -> None:)tool = _MonitorTool()result = await executor.execute(tool, args={"target": "foo"})- # Whitelist downgraded ``monitor_tool`` zu ``safe`` -> kein Approval.+ # Whitelist downgraded ``monitor_tool`` to ``safe`` -> no approval.assert approval.wait_calls == 0- # Context-Fn darf NICHT aufgerufen werden, weil Whitelist-Skip.+ # Context fn must NOT be called, because of the whitelist skip.assert calls == []assert result.success is True@pytest.mark.asyncioasync def test_high_confidence_recent_wake_no_extra_confirmation() -> None:- """Bei guter Plausibility wird kein extra Approval angefordert."""+ """With good plausibility, no extra approval is requested."""transcript = Transcript(text="x", language="de", confidence=0.9)executor, approval = _executor_with_plausibility(context_fn=lambda: (transcript, 2.0),)tool = _MonitorTool()result = await executor.execute(tool, args={})- # ``monitor`` + plausibility=ok -> kein Approval.+ # ``monitor`` + plausibility=ok -> no approval.assert approval.wait_calls == 0assert result.success is True@pytest.mark.asyncioasync def test_context_fn_exception_is_swallowed() -> None:- """Wenn der Context-Provider crasht, faellt der Executor auf "kein Check" zurueck."""+ """If the context provider crashes, the executor falls back to "no check"."""def broken_fn() -> tuple[Transcript, float]:raise RuntimeError("context-provider down")executor, approval = _executor_with_plausibility(context_fn=broken_fn)tool = _MonitorTool()result = await executor.execute(tool, args={})- # Trotz crash: Tool laeuft, kein Approval.+ # Despite the crash: the tool runs, no approval.assert approval.wait_calls == 0assert result.success is Truediff --git a/tests/unit/safety/test_tool_executor_voice_confirm.py b/tests/unit/safety/test_tool_executor_voice_confirm.pyindex 57c52f60fb..467cbc39f8 100644--- a/tests/unit/safety/test_tool_executor_voice_confirm.py+++ b/tests/unit/safety/test_tool_executor_voice_confirm.py@@ -172,7 +172,7 @@ async def test_gmail_read_is_not_deferred_for_voice_confirm() -> None:"""Repro 2026-06-19 (session dc533e39): a read-only gmail call (themorning-routine "check unread mail" step) must NOT trigger the sendconfirmation on a voice turn. Before the per-action risk fix the whole- gmail tool was ask-tier, so "Was habe ich heute auf dem Plan?" produced+ gmail tool was ask-tier, so "Was habe ich heute auf dem Plan?" produced # i18n-allow: quotes the actual German voice utterance/output forensic bug content"Soll ich die E-Mail wirklich senden?"."""import httpxdiff --git a/tests/unit/self_mod/fixtures/minimal_jarvis.toml b/tests/unit/self_mod/fixtures/minimal_jarvis.tomlindex 50f7f771fe..ce2d5aa4d3 100644--- a/tests/unit/self_mod/fixtures/minimal_jarvis.toml+++ b/tests/unit/self_mod/fixtures/minimal_jarvis.toml@@ -1,12 +1,12 @@-# Personal Jarvis — Test-Fixture für Phase-7.2 Atomic-Writer-Tests.-# Dieser Kommentar muss alle 100 Mutationen überleben (Plan-AC §7.2).+# Personal Jarvis — test fixture for Phase-7.2 atomic-writer tests.+# This comment must survive all 100 mutations (Plan-AC §7.2).[profile]name = "test-runner"language = "de" # de | en | auto[tts]-# Default-Provider für Voice-Tests+# Default provider for voice testsprovider = "gemini-flash-tts"voice_de = "Charon"voice_en = "Charon"@@ -22,4 +22,4 @@ primary = "claude-api"[ui]tray_enabled = true-# Trailing-Kommentar — auch dieser muss erhalten bleiben.+# Trailing comment — this one must survive too.diff --git a/tests/unit/self_mod/test_audit.py b/tests/unit/self_mod/test_audit.pyindex ebb84fc2f8..3ad4fc827e 100644--- a/tests/unit/self_mod/test_audit.py+++ b/tests/unit/self_mod/test_audit.py@@ -1,10 +1,10 @@-"""Tests für SelfModAudit (Phase 7.1).+"""Tests for SelfModAudit (Phase 7.1).-Plan-Akzeptanzkriterien §7.1:-- Audit-Log-Round-Trip mit Concurrent-Writes-- Format-Treue zum Plan-Beispiel (10 Felder, ISO-Z, UUID4)-- Sensitive Pfade werden redacted (Plan-§AP-2)-- I/O-Fehler crashen Caller nicht (Plan-§AP-5)+Plan acceptance criteria §7.1:+- Audit-log round-trip with concurrent writes+- Format fidelity to the plan example (10 fields, ISO-Z, UUID4)+- Sensitive paths get redacted (Plan-§AP-2)+- I/O errors don't crash the caller (Plan-§AP-5)"""from __future__ import annotations@@ -41,7 +41,7 @@ def sample_event() -> AuditEvent:)-# --- Round-Trip ---+# --- Round trip ---class TestRecord:@@ -77,7 +77,7 @@ class TestRecord:def test_format_matches_plan_spec(self, audit: SelfModAudit, sample_event: AuditEvent) -> None:- """Plan-§7.1: 10 Audit-Felder."""+ """Plan-§7.1: 10 audit fields."""audit.record(sample_event)parsed = json.loads(audit.path.read_text(encoding="utf-8").strip())for key in (@@ -92,14 +92,14 @@ class TestRecord:"rolled_back","error",):- assert key in parsed, f"Plan-Feld '{key}' fehlt im Audit-JSON"+ assert key in parsed, f"Plan field '{key}' missing from audit JSON"def test_iso_z_timestamp(self, audit: SelfModAudit, sample_event: AuditEvent) -> None:audit.record(sample_event)parsed = json.loads(audit.path.read_text(encoding="utf-8").strip())- assert parsed["ts"].endswith("Z"), f"ts ohne Z-Suffix: {parsed['ts']}"+ assert parsed["ts"].endswith("Z"), f"ts without Z suffix: {parsed['ts']}"assert "+00:00" not in parsed["ts"]def test_uuid4_audit_id(@@ -114,7 +114,7 @@ class TestRecord:assert SelfModAudit.DEFAULT_PATH == Path("data") / "self_mod.log"-# --- Concurrent-Writes (Plan-AC §7.1) ---+# --- Concurrent writes (Plan-AC §7.1) ---class TestConcurrent:@@ -136,10 +136,10 @@ class TestConcurrent:lines = audit.path.read_text(encoding="utf-8").splitlines()assert len(lines) == n_threads * per_thread, (- f"Erwartete {n_threads * per_thread} Zeilen, fand {len(lines)} — "- "Race-Condition oder Lock-Defekt."+ f"Expected {n_threads * per_thread} lines, found {len(lines)} — "+ "race condition or lock defect.")- # Jede Zeile muss valides JSON sein (kein Mid-Line-Tearing).+ # Every line must be valid JSON (no mid-line tearing).for line in lines:parsed = json.loads(line)assert parsed["path"] == "tts.provider"@@ -165,7 +165,7 @@ class TestRedaction:def test_redacts_sensitive_paths(self, audit: SelfModAudit, sensitive_path: str) -> None:- secret = "sk-1234567890abcdef" # noqa: S105 — Test-Fixture, kein echter Token+ secret = "sk-1234567890abcdef" # noqa: S105 — test fixture, not a real tokennew_secret = "new-" + secretevent = AuditEvent(source=AuditSource.UI,@@ -178,11 +178,11 @@ class TestRedaction:audit.record(event)content = audit.path.read_text(encoding="utf-8")assert secret not in content, (- f"Klartext-Secret im Log gelandet (path={sensitive_path}): "+ f"Plaintext secret ended up in the log (path={sensitive_path}): "f"{content!r}")parsed = json.loads(content.strip())- # Länge bleibt erhalten zur Telemetrie ("16-stelliger Token")+ # Length is preserved for telemetry ("16-character token")assert parsed["old_value"] == "*" * len(secret)assert parsed["new_value"] == "*" * len(new_secret)@@ -229,15 +229,15 @@ class TestRobustness:tmp_path: Path,monkeypatch: pytest.MonkeyPatch,) -> None:- """Plan-§AP-5: I/O-Fehler crasht Caller NICHT."""+ """Plan-§AP-5: I/O error does NOT crash the caller."""audit = SelfModAudit(path=tmp_path / "audit.log")def failing_open(self: Path, *args: object, **kwargs: object) -> None:- raise PermissionError("simuliert: kein Schreibrecht")+ raise PermissionError("simulated: no write permission")monkeypatch.setattr(Path, "open", failing_open)- # Darf nicht propagieren.+ # Must not propagate.audit.record(sample_event)def test_silent_on_mkdir_failure(@@ -246,12 +246,12 @@ class TestRobustness:tmp_path: Path,monkeypatch: pytest.MonkeyPatch,) -> None:- """Auch ein Disk-Full-Fehler beim Verzeichnis-Anlegen darf nicht- propagieren."""- audit = SelfModAudit(path=tmp_path / "neuer-subdir" / "audit.log")+ """A disk-full error while creating the directory must also not+ propagate."""+ audit = SelfModAudit(path=tmp_path / "new-subdir" / "audit.log")def failing_mkdir(self: Path, *args: object, **kwargs: object) -> None:- raise OSError("simuliert: Disk-Full")+ raise OSError("simulated: disk full")monkeypatch.setattr(Path, "mkdir", failing_mkdir)@@ -277,9 +277,9 @@ class TestRobustness:audit.record(sample_event)assert any(- "fehlgeschlagen" in rec.getMessage().lower()+ "fehlgeschlagen" in rec.getMessage().lower() # i18n-allow: matches actual German text logged by jarvis/core/self_mod/audit.pyfor rec in caplog.records- ), "Erwarteter Warning-Log fehlt"+ ), "expected warning log missing"# --- tail() ---@@ -319,7 +319,7 @@ class TestTail:caplog: pytest.LogCaptureFixture,) -> None:audit.record(sample_event)- # Manuell eine korrupte Zeile anhängen.+ # Manually append a corrupt line.with audit.path.open("a", encoding="utf-8") as fh:fh.write("not-json-at-all\n")audit.record(sample_event)@@ -329,8 +329,8 @@ class TestTail:):entries = audit.tail()- # Die zwei validen Einträge bleiben, die korrupte Zeile wird- # übersprungen — kein Crash.+ # The two valid entries remain, the corrupt line is+ # skipped — no crash.assert len(entries) == 2for entry in entries:assert entry["path"] == "tts.provider"diff --git a/tests/unit/self_mod/test_registry.py b/tests/unit/self_mod/test_registry.pyindex c5b575fb2e..e1a684a1b6 100644--- a/tests/unit/self_mod/test_registry.py+++ b/tests/unit/self_mod/test_registry.py@@ -1,9 +1,9 @@-"""Tests für SelfModRegistry (Phase 7.1).+"""Tests for SelfModRegistry (Phase 7.1).-Plan-Akzeptanzkriterien §7.1:-- Unit-Tests für Registry (List, Lookup, Reject `security.*`)+Plan acceptance criteria §7.1:+- Unit tests for the registry (list, lookup, reject `security.*`)- Public API: `is_mutable(path)`, `get_spec(path)`, `list_all()`-- Keine Datei-IO auf `jarvis.toml` in dieser Phase+- No file I/O on `jarvis.toml` in this phase"""from __future__ import annotations@@ -94,14 +94,14 @@ class TestIsMutable:# Plan-§AC §7.1: Reject security.*"security.admin_password_hash","security.foo",- # Plan-§AP-9 erweitert auf weitere geschützte Sektionen+ # Plan-§AP-9 extended to further protected sections"mcp_server.transport","mcp_server.auth_token_env",# Risk-tier whitelist/blacklist — added 2026-06-08 for the Control API"safety.whitelist","safety.blacklist.commands","harness.default_timeout_s",- # Suffix-Patterns für Secrets+ # Suffix patterns for secrets"anthropic_api_key","openai_token","deepgram_secret",@@ -135,12 +135,12 @@ class TestGetSpec:assert SelfModRegistry.get_spec("security.admin_password_hash") is Nonedef test_safe_tier_paths_match_plan(self) -> None:- """Plan-§AD-10 Bypass-Whitelist: tts.speed und ui.theme sind SAFE."""+ """Plan-§AD-10 bypass whitelist: tts.speed and ui.theme are SAFE."""for path in SAFE_TIER_PATHS:spec = SelfModRegistry.get_spec(path)assert spec is not Noneassert spec.risk_tier == "safe", (- f"{path} sollte risk_tier='safe' haben"+ f"{path} should have risk_tier='safe'")def test_ask_tier_paths_match_plan(self) -> None:@@ -148,7 +148,7 @@ class TestGetSpec:spec = SelfModRegistry.get_spec(path)assert spec is not Noneassert spec.risk_tier == "ask", (- f"{path} sollte risk_tier='ask' haben"+ f"{path} should have risk_tier='ask'")def test_restart_flags_match_plan(self) -> None:@@ -179,20 +179,20 @@ class TestRequireSpec:SelfModRegistry.require_spec("security.admin_password_hash")def test_secret_takes_precedence_over_unknown(self) -> None:- """Ein Pfad, der sowohl forbidden als auch nicht in ALLOWED ist,- muss SecretAccessError werfen — nicht AllowlistViolationError."""+ """A path that is both forbidden and not in ALLOWED+ must raise SecretAccessError — not AllowlistViolationError."""with pytest.raises(SecretAccessError):SelfModRegistry.require_spec("foo_api_key")-# --- Defense-in-Depth: Allowlist und Forbidden disjunkt ---+# --- Defense-in-depth: allowlist and forbidden are disjoint ---class TestForbiddenPatterns:def test_no_allowed_path_matches_forbidden_patterns(self) -> None:for spec in SelfModRegistry.list_all():assert not SelfModRegistry.is_forbidden(spec.path), (- f"Allowlist-Pfad '{spec.path}' überlappt mit FORBIDDEN_PATTERNS"+ f"Allowlist path '{spec.path}' overlaps with FORBIDDEN_PATTERNS")def test_forbidden_patterns_non_empty(self) -> None:@@ -204,26 +204,26 @@ class TestForbiddenPatterns:def test_secret_suffix_patterns_present(self) -> None:for pattern in ("*_api_key", "*_token", "*_secret", "*_password"):assert pattern in FORBIDDEN_PATTERNS, (- f"Plan-§AP-9 verlangt Pattern {pattern}"+ f"Plan-§AP-9 requires pattern {pattern}")-# --- AP-11: kein dynamisches register() ---+# --- AP-11: no dynamic register() ---class TestNoDynamicRegistration:def test_registry_has_no_register_method(self) -> None:- """AP-11: Allowlist darf nicht zur Laufzeit erweiterbar sein."""+ """AP-11: the allowlist must not be extensible at runtime."""for forbidden in ("register", "add", "register_path", "append"):assert not hasattr(SelfModRegistry, forbidden), (- f"AP-11-Verletzung: SelfModRegistry hat unerwartete Methode "- f"'{forbidden}', die dynamische Allowlist-Erweiterung erlauben "- f"würde."+ f"AP-11 violation: SelfModRegistry has an unexpected method "+ f"'{forbidden}' that would allow dynamic allowlist "+ f"extension.")def test_mutable_spec_is_frozen(self) -> None:- """Wenn ein Spec mutabel wäre, könnte ein Tool den risk_tier- eines Pfads umstellen (`ask → safe`) und Confirmation umgehen.+ """If a spec were mutable, a tool could switch a path's risk_tier+ (`ask → safe`) and bypass confirmation."""spec = SelfModRegistry.list_all()[0]with pytest.raises(ValidationError):@@ -254,7 +254,7 @@ class TestMutableSpecValidation:)def test_extra_fields_rejected(self) -> None:- """`MutableSpec` ist `extra='forbid'`."""+ """`MutableSpec` is `extra='forbid'`."""with pytest.raises(ValidationError):MutableSpec(path="x.y",@@ -265,22 +265,22 @@ class TestMutableSpecValidation:)-# --- Plan-AC: keine Datei-IO auf jarvis.toml ---+# --- Plan-AC: no file I/O on jarvis.toml ---class TestNoConfigFileIO:def test_registry_works_without_jarvis_toml(self, tmp_path, monkeypatch) -> None:- """Plan-AC §7.1: Registry darf in dieser Phase keine Datei lesen.+ """Plan-AC §7.1: the registry must not read any file in this phase.- Beweis: Im leeren CWD ohne `jarvis.toml` arbeitet die Registry- weiterhin korrekt, weil sie ausschließlich aus der ClassVar liest.+ Proof: in an empty CWD without `jarvis.toml`, the registry still+ works correctly because it reads exclusively from the ClassVar."""monkeypatch.chdir(tmp_path)assert not (tmp_path / "jarvis.toml").exists()- # Alle drei Public-API-Aufrufe müssen funktionieren.+ # All three public-API calls must work.assert len(SelfModRegistry.list_all()) > 50assert SelfModRegistry.is_mutable("tts.provider") is Trueassert SelfModRegistry.is_mutable("security.admin_password_hash") is Falsediff --git a/tests/unit/self_mod/test_writer.py b/tests/unit/self_mod/test_writer.pyindex 8995f6b652..dfcf0ba94e 100644--- a/tests/unit/self_mod/test_writer.py+++ b/tests/unit/self_mod/test_writer.py@@ -1,12 +1,12 @@-"""Tests für AtomicConfigWriter (Phase 7.2).--Plan-Akzeptanzkriterien §7.2:-- Happy-Path-Test: Mutation persistiert, ConfigReloaded-Event feuert-- Pre-Validation-Reject: kein Schreiben, keine Backup-Datei-- Rollback-Test mit Monkeypatched Reload-Crash-- Kommentar-Preservation: User-Kommentar überlebt 100 Mutationen-- Concurrent-Test: 10 parallele Mutationen serialisieren korrekt-- Backup-GC: nach 11 Mutationen wird älteste >30d gelöscht, letzte 10 erhalten+"""Tests for AtomicConfigWriter (Phase 7.2).++Plan acceptance criteria §7.2:+- Happy-path test: mutation persists, ConfigReloaded event fires+- Pre-validation reject: no write, no backup file+- Rollback test with a monkeypatched reload crash+- Comment preservation: user comment survives 100 mutations+- Concurrency test: 10 parallel mutations serialize correctly+- Backup GC: after 11 mutations the oldest >30d is deleted, the last 10 are kept"""from __future__ import annotations@@ -45,7 +45,7 @@ FIXTURE = Path(__file__).parent / "fixtures" / "minimal_jarvis.toml"def _isolated_loader(path: Path) -> JarvisConfig:- """Loader ohne ENV-Overrides (Test-Isolation gegen JARVIS__*)."""+ """Loader without ENV overrides (test isolation against JARVIS__*)."""raw = path.read_bytes()if raw.startswith(b"\xef\xbb\xbf"):raw = raw[3:]@@ -54,7 +54,7 @@ def _isolated_loader(path: Path) -> JarvisConfig:class CaptureBus:- """Einfacher EventBus-Stub: sammelt publishe Events in-memory."""+ """Simple EventBus stub: collects published events in-memory."""def __init__(self) -> None:self.events: list[ConfigReloaded] = []@@ -176,13 +176,13 @@ class TestHappyPath:writer: AtomicConfigWriter,fixture_path: Path,) -> None:- """Alle anderen Felder bleiben unverändert."""+ """All other fields remain unchanged."""before = _isolated_loader(fixture_path)writer.mutate(_make_request("tts.speed", 1.5))after = _isolated_loader(fixture_path)assert after.tts.speed == 1.5- # Beweis: alle anderen Felder identisch+ # Proof: all other fields identicalassert after.tts.provider == before.tts.providerassert after.tts.voice_de == before.tts.voice_deassert after.profile.name == before.profile.name@@ -200,22 +200,22 @@ class TestCommentPreservation:) -> None:writer.mutate(_make_request("tts.speed", 1.5))text = fixture_path.read_text(encoding="utf-8")- # Plan-Fixture-Kommentare:- assert "Personal Jarvis — Test-Fixture" in text- assert "Trailing-Kommentar" in text- assert "100 Mutationen" in text # Header-Kommentar+ # Plan fixture comments:+ assert "Personal Jarvis — test fixture" in text+ assert "Trailing comment" in text+ assert "100 mutations" in text # header commentdef test_user_comments_survive_100_mutations(self, writer: AtomicConfigWriter, fixture_path: Path) -> None:- """Plan-AC §7.2: User-Kommentar überlebt 100 Mutationen."""+ """Plan-AC §7.2: user comment survives 100 mutations."""for i in range(100):value = 0.5 + (i % 10) * 0.1writer.mutate(_make_request("tts.speed", round(value, 2)))text = fixture_path.read_text(encoding="utf-8")- assert "Personal Jarvis — Test-Fixture" in text- assert "Trailing-Kommentar" in text- # Datei ist immer noch valide+ assert "Personal Jarvis — test fixture" in text+ assert "Trailing comment" in text+ # File is still validconfig = _isolated_loader(fixture_path)assert config.profile.name == "test-runner"@@ -291,7 +291,7 @@ class TestPreValidateReject:def test_invalid_value_creates_no_backup(self, writer: AtomicConfigWriter, tmp_path: Path) -> None:- """Plan-AC §7.2: Pre-Validation-Reject — kein Schreiben, keine Backup-Datei."""+ """Plan-AC §7.2: pre-validation reject — no write, no backup file."""with pytest.raises(PreValidateError):writer.mutate(_make_request("tts.provider", ["x"]))backup_dir = tmp_path / "backups"@@ -334,7 +334,7 @@ class TestReloadFailRollback:)with pytest.raises(ReloadError):writer.mutate(_make_request("tts.provider", "elevenlabs"))- # Original byte-identisch wiederhergestellt+ # Original restored byte-identicalassert fixture_path.read_bytes() == original_bytesdef test_audit_reports_post_validate_failure(@@ -366,8 +366,8 @@ class TestReloadFailRollback:tmp_path: Path,audit_log: SelfModAudit,) -> None:- """Backup wird nicht entfernt, damit der User später manuell- recovern kann (über `rollback(backup_filename)`)."""+ """Backup is not removed, so the user can later recover manually+ (via `rollback(backup_filename)`)."""def crashing_loader(_path: Path) -> JarvisConfig:raise RuntimeError("nope")@@ -385,7 +385,7 @@ class TestReloadFailRollback:# -----------------------------------------------------------------------# Atomic-Write-Safety (kein orphan .tmp)+# Atomic-write safety (no orphan .tmp)# ----------------------------------------------------------------------@@ -397,11 +397,11 @@ class TestAtomicWrite:audit_log: SelfModAudit,monkeypatch: pytest.MonkeyPatch,) -> None:- """Wenn `os.replace` knallt, darf kein `.tmp` neben jarvis.toml liegen.+ """If `os.replace` blows up, no `.tmp` may be left next to jarvis.toml.- Das Backup nutzt `mkstemp` ohne `os.replace`; nur der atomic_write- ruft `os.replace`. Wir lassen den Backup-Pfad durchlaufen und- crashen erst beim Final-Replace.+ The backup uses `mkstemp` without `os.replace`; only the atomic_write+ calls `os.replace`. We let the backup path run through and+ crash only at the final replace."""original_bytes = fixture_path.read_bytes()writer = AtomicConfigWriter(@@ -419,11 +419,11 @@ class TestAtomicWrite:with pytest.raises(BackupError):writer.mutate(_make_request("tts.provider", "elevenlabs"))- # Original-Datei intakt (byte-identisch — replace nie passiert)+ # Original file intact (byte-identical — replace never happened)assert fixture_path.read_bytes() == original_bytes- # Kein orphan .tmp neben jarvis.toml+ # No orphan .tmp next to jarvis.tomlorphans = list(fixture_path.parent.glob("jarvis.toml.*.tmp"))- assert orphans == [], f"Orphan-tmp gefunden: {orphans}"+ assert orphans == [], f"Orphan tmp found: {orphans}"# ----------------------------------------------------------------------@@ -438,7 +438,7 @@ class TestBackupGC:tmp_path: Path,audit_log: SelfModAudit,) -> None:- """Prompt-AC: 51 Sets mit max=50 → genau 50 erhalten."""+ """Prompt-AC: 51 sets with max=50 → exactly 50 retained."""writer = AtomicConfigWriter(config_path=fixture_path,backup_dir=tmp_path / "backups",@@ -458,18 +458,18 @@ class TestBackupGC:tmp_path: Path,audit_log: SelfModAudit,) -> None:- """Plan-AC §7.2: nach 11 Mutationen ist die älteste >30d gelöscht,- die letzten 10 erhalten."""+ """Plan-AC §7.2: after 11 mutations, the oldest >30d is deleted,+ the last 10 are kept."""writer = AtomicConfigWriter(config_path=fixture_path,backup_dir=tmp_path / "backups",- max_backups=100, # Cap aushebeln, nur Age-GC testen+ max_backups=100, # bypass the cap, test only age-based GCbackup_min_keep=10,backup_max_age_days=30,audit=audit_log,config_loader=_isolated_loader,)- # 11 Mutationen+ # 11 mutationsfor i in range(11):writer.mutate(_make_request("tts.speed", 1.0 + i * 0.001))backups = sorted(@@ -478,17 +478,17 @@ class TestBackupGC:)assert len(backups) == 11- # Älteste auf >30 Tage altern+ # Age the oldest one to >30 daysancient = time.time() - 31 * 86400os.utime(backups[0], (ancient, ancient))- # Erneute Mutation triggert GC+ # Another mutation triggers GCwriter.mutate(_make_request("tts.speed", 1.99))remaining = sorted((tmp_path / "backups").glob("jarvis.toml.*.bak"),key=lambda p: p.stat().st_mtime,)- # Alte Datei (31 Tage) gelöscht, weil >min_keep nach Cap-Check+ # Old file (31 days) deleted because >min_keep after the cap checkassert backups[0] not in remainingdef test_min_keep_floor_protects_against_aggressive_gc(@@ -497,7 +497,7 @@ class TestBackupGC:tmp_path: Path,audit_log: SelfModAudit,) -> None:- """Selbst wenn alle Backups ancient wären, min_keep schützt die letzten 10."""+ """Even if all backups were ancient, min_keep protects the last 10."""writer = AtomicConfigWriter(config_path=fixture_path,backup_dir=tmp_path / "backups",@@ -511,13 +511,13 @@ class TestBackupGC:writer.mutate(_make_request("tts.speed", 1.0 + i * 0.001))backup_dir = tmp_path / "backups"- # Alle Backups künstlich altern+ # Artificially age all backupsancient = time.time() - 100 * 86400for path in backup_dir.glob("jarvis.toml.*.bak"):os.utime(path, (ancient, ancient))writer.mutate(_make_request("tts.speed", 9.99))- # Min-Keep: 10 + 1 (frische) sollte erhalten bleiben+ # Min-keep: 10 + 1 (fresh) should be retainedremaining = list(backup_dir.glob("jarvis.toml.*.bak"))assert len(remaining) >= 10@@ -542,8 +542,8 @@ class TestConcurrencyDifferentPaths:config_loader=_isolated_loader,)- # Plan-AC §7.2: 10 parallele Mutationen serialisieren korrekt.- # Wir mischen ALLOWED-Pfade durch.+ # Plan-AC §7.2: 10 parallel mutations serialize correctly.+ # We mix ALLOWED paths together.targets: list[tuple[str, Any]] = [("tts.speed", 1.0),("tts.provider", "elevenlabs"),@@ -566,13 +566,13 @@ class TestConcurrencyDifferentPaths:for thread in threads:thread.join()- # 10 Backups, 10 Audit-Einträge, Datei ist valide+ # 10 backups, 10 audit entries, file is validbackups = list((tmp_path / "backups").glob("jarvis.toml.*.bak"))assert len(backups) == 10entries = _read_audit_lines(audit_log)assert len(entries) == 10assert all(e["ok"] is True for e in entries)- # Datei lädt ohne Fehler+ # File loads without error_isolated_loader(fixture_path)@@ -594,7 +594,7 @@ class TestConcurrencySamePath:def worker(value: float) -> None:writer.mutate(_make_request("tts.speed", value))- # Nach dem mutate ist tts.speed == value (oder bereits überschrieben)+ # After the mutate, tts.speed == value (or already overwritten)with lock:results.append(value)@@ -605,11 +605,11 @@ class TestConcurrencySamePath:t1.join()t2.join()- # Beide Mutationen sind Audit + Backup+ # Both mutations have audit + backupassert len(_read_audit_lines(audit_log)) == 2assert len(list((tmp_path / "backups").glob("jarvis.toml.*.bak"))) == 2- # Final-Wert ist einer der beiden+ # Final value is one of the twoconfig = _isolated_loader(fixture_path)assert config.tts.speed in (1.25, 1.75)@@ -662,7 +662,7 @@ class TestRollbackPublic:writer.rollback(first_backup_filename)config = _isolated_loader(fixture_path)- # Erstes Backup zeigt auf den Stand VOR der ersten Mutation (also 1.0)+ # First backup points to the state BEFORE the first mutation (i.e. 1.0)assert config.tts.speed == 1.0def test_rollback_path_traversal_blocked(@@ -699,10 +699,10 @@ class TestBusDispatchInRunningLoop:bus=bus, # type: ignore[arg-type]config_loader=_isolated_loader,)- # mutate() ist sync. Der Dispatch-Pfad muss `get_running_loop`- # erkennen und via create_task scheduln.+ # mutate() is sync. The dispatch path must detect `get_running_loop`+ # and schedule via create_task.writer.mutate(_make_request("tts.speed", 1.42))- # Dem create_task einen Tick zum Laufen geben+ # Give create_task one tick to runawait asyncio.sleep(0.05)assert len(bus.events) == 1assert bus.events[0].changed_keys == ("tts.speed",)diff --git a/tests/unit/sessions/test_hangup_reason_parity.py b/tests/unit/sessions/test_hangup_reason_parity.pyindex 4bb90fd7ab..1829bcaedf 100644--- a/tests/unit/sessions/test_hangup_reason_parity.py+++ b/tests/unit/sessions/test_hangup_reason_parity.py@@ -84,7 +84,7 @@ def test_session_list_tsx_switch_covers_all_reasons() -> None:"""SessionList.tsx ``hangupLabel`` must have a case for every non-empty value.The empty string is the running-session marker and never reaches- ``hangupLabel`` (the caller falls back to a "läuft" badge); we+ ``hangupLabel`` (the caller falls back to a "läuft" badge); we # i18n-allow: quotes the actual German UI badge label under testtherefore exclude it from the required cases."""text = SESSION_LIST_TSX.read_text(encoding="utf-8")diff --git a/tests/unit/sessions/test_models_resilience.py b/tests/unit/sessions/test_models_resilience.pyindex 960dada6c9..dcc3362dff 100644--- a/tests/unit/sessions/test_models_resilience.py+++ b/tests/unit/sessions/test_models_resilience.py@@ -1,11 +1,11 @@-"""BUG-008-Drift-Detector: Pydantic-Models muessen jeden String als-``hangup_reason``/``tier`` akzeptieren, sonst kollabiert ``GET-/api/sessions`` sobald die Speech-Pipeline einen neuen Wert einfuehrt.--Drei Episoden hat dieser Bug schon gehabt (2026-05-03 / -05 / -10). Der-permanente Fix steht im Modul-Docstring von ``jarvis/sessions/models.py``.-Diese Tests sichern den Fix gegen Regressions ab — wer ``HangupReason``-oder ``VoiceTier`` zurueck auf ``Literal`` migriert, faellt hier durch.+"""BUG-008 drift detector: Pydantic models must accept any string as+``hangup_reason``/``tier``, otherwise ``GET /api/sessions`` collapses+as soon as the speech pipeline introduces a new value.++This bug has already had three episodes (2026-05-03 / -05 / -10). The+permanent fix lives in the module docstring of ``jarvis/sessions/models.py``.+These tests guard the fix against regressions — anyone who migrates+``HangupReason`` or ``VoiceTier`` back to ``Literal`` fails here."""from __future__ import annotations@@ -23,7 +23,7 @@ from jarvis.sessions.models import ()-# --- Schicht 1: jeder bekannte Wert validiert -------------------------+# --- Layer 1: every known value validates -------------------------@pytest.mark.parametrize("reason", sorted(KNOWN_HANGUP_REASONS))@@ -48,12 +48,12 @@ def test_turn_validates_every_known_tier(tier: str) -> None:assert turn.tier == tier-# --- Schicht 2: unbekannte Werte krashen NICHT (Drift-Resilienz) ------+# --- Layer 2: unknown values do NOT crash (drift resilience) ------def test_unknown_hangup_reason_does_not_break_validation() -> None:- """Wenn die Pipeline morgen ``vad_silence_long`` einfuehrt, darf die- Sessions-API nicht 500 werden. Das war exakt die BUG-008-Falle."""+ """If the pipeline introduces ``vad_silence_long`` tomorrow, the+ sessions API must not 500. That was exactly the BUG-008 trap."""item = SessionListItem(id="s1",started_ms=0,@@ -74,7 +74,7 @@ def test_unknown_tier_does_not_break_validation() -> None:assert turn.tier == "phase8_future_tier"-# --- Schicht 3: Live-DB-Drift-Detector --------------------------------+# --- Layer 3: live-DB drift detector --------------------------------_REPO_ROOT = Path(__file__).resolve().parents[3]@@ -83,16 +83,16 @@ _LIVE_DB = _REPO_ROOT / "data" / "sessions.db"@pytest.mark.skipif(not _LIVE_DB.exists(),- reason="data/sessions.db nicht vorhanden (CI / frische Checkouts)",+ reason="data/sessions.db not present (CI / fresh checkouts)",)def test_live_db_distinct_hangup_reasons_all_validate() -> None:- """Crawlt die echte ``data/sessions.db`` und stellt sicher, dass jeder- in der Praxis vorkommende ``hangup_reason``-Wert von Pydantic- akzeptiert wird. Das ist der scharfe Drift-Detector — wenn dieser- Test rot wird, wurde ein neuer Wert in der Pipeline eingefuehrt- ohne dass jemand ``KNOWN_HANGUP_REASONS`` aktualisiert hat. Dann:- Wert in die Konstante eintragen + ``hangupLabel`` im Frontend- erweitern (jarvis/ui/web/frontend/src/components/sessions/SessionList.tsx).+ """Crawls the real ``data/sessions.db`` and makes sure every+ ``hangup_reason`` value that occurs in practice is accepted by+ Pydantic. This is the sharp drift detector — if this test goes+ red, a new value was introduced in the pipeline without anyone+ updating ``KNOWN_HANGUP_REASONS``. Then: add the value to the+ constant + extend ``hangupLabel`` in the frontend+ (jarvis/ui/web/frontend/src/components/sessions/SessionList.tsx)."""con = sqlite3.connect(str(_LIVE_DB))try:@@ -105,13 +105,13 @@ def test_live_db_distinct_hangup_reasons_all_validate() -> None:seen: set[str] = {(row[0] or "") for row in rows}unknown = seen - KNOWN_HANGUP_REASONSassert not unknown, (- f"Neue hangup_reason-Werte in data/sessions.db: {sorted(unknown)}. "- f"Bitte in jarvis/sessions/models.py KNOWN_HANGUP_REASONS und im "- f"Frontend (types.ts + SessionList.hangupLabel) ergaenzen."+ f"New hangup_reason values in data/sessions.db: {sorted(unknown)}. "+ f"Please add them to KNOWN_HANGUP_REASONS in jarvis/sessions/models.py "+ f"and to the frontend (types.ts + SessionList.hangupLabel).")- # Plus: jeder Wert MUSS Pydantic-validierbar sein. Das schuetzt- # gegen Refactor-Regressions zurueck zu ``Literal``.+ # Plus: every value MUST be Pydantic-validatable. This protects+ # against refactor regressions back to ``Literal``.for reason in seen:VoiceSessionRow(id="probe",diff --git a/tests/unit/sessions/test_recorder_lifecycle.py b/tests/unit/sessions/test_recorder_lifecycle.pyindex 6625987546..268049584a 100644--- a/tests/unit/sessions/test_recorder_lifecycle.py+++ b/tests/unit/sessions/test_recorder_lifecycle.py@@ -53,7 +53,7 @@ async def test_recorder_persists_transcript_when_pipeline_emits_session_lifecyclTranscriptFinal(source_layer="speech.stt",transcript=Transcript(- text="neue Transkription speichern",+ text="neue Transkription speichern", # i18n-allow: simulated German transcript content under testlanguage="de",confidence=0.9,is_partial=False,@@ -72,9 +72,9 @@ async def test_recorder_persists_transcript_when_pipeline_emits_session_lifecyclturns = store.get_turns("session-1")assert len(sessions) == 1- assert sessions[0].preview == "neue Transkription speichern"+ assert sessions[0].preview == "neue Transkription speichern" # i18n-allow: matches simulated German transcript aboveassert sessions[0].turn_count == 1- assert turns[0].user_text == "neue Transkription speichern"+ assert turns[0].user_text == "neue Transkription speichern" # i18n-allow: matches simulated German transcript abovefinally:store.close()@@ -120,7 +120,7 @@ async def test_multiple_transcript_finals_in_suppressed_session_keep_each_utteranew_state="LISTENING",))- await bus.publish(_final("Wie spät ist es"))+ await bus.publish(_final("Wie spät ist es")) # i18n-allow: simulated German user utterance under testawait bus.publish(SystemStateChanged(source_layer="speech",@@ -150,7 +150,7 @@ async def test_multiple_transcript_finals_in_suppressed_session_keep_each_utteraassert len(turns) == 3, (f"expected one turn per utterance, got {len(turns)}: {user_texts}")- assert user_texts == ["Hallo Jarvis", "Wie spät ist es", "Auflegen."]+ assert user_texts == ["Hallo Jarvis", "Wie spät ist es", "Auflegen."] # i18n-allow: simulated German utterances under testfinally:store.close()@@ -179,9 +179,9 @@ async def test_continuation_finals_merge_into_one_turn(tmp_path) -> None:await bus.publish(ListeningStarted(source_layer="speech"))# First utterance, then two follow-ups WHILE the brain is still thinking# (no SPEAKING boundary yet) — flagged as continuations.- await bus.publish(_final("Was ist der weiteste Ort"))- await bus.publish(_final("nicht australische", continues=True))- await bus.publish(_final("sondern wirklich der weiteste", continues=True))+ await bus.publish(_final("Was ist der weiteste Ort")) # i18n-allow: simulated German user utterance under test+ await bus.publish(_final("nicht australische", continues=True)) # i18n-allow: simulated German user utterance under test+ await bus.publish(_final("sondern wirklich der weiteste", continues=True)) # i18n-allow: simulated German user utterance under test# Brain finally speaks the combined answer → SPEAKING boundary finalizes.await bus.publish(SystemStateChanged(@@ -189,7 +189,7 @@ async def test_continuation_finals_merge_into_one_turn(tmp_path) -> None:))await bus.publish(- ResponseGenerated(source_layer="brain", text="Das ist Sydney.", language="de")+ ResponseGenerated(source_layer="brain", text="Das ist Sydney.", language="de") # i18n-allow: simulated German brain/voice output under test)await bus.publish(SystemStateChanged(@@ -209,7 +209,7 @@ async def test_continuation_finals_merge_into_one_turn(tmp_path) -> None:assert len(turns) == 1, user_textsassert (turns[0].user_text- == "Was ist der weiteste Ort nicht australische sondern wirklich der weiteste"+ == "Was ist der weiteste Ort nicht australische sondern wirklich der weiteste" # i18n-allow: matches simulated German utterances above)finally:store.close()@@ -274,7 +274,7 @@ async def test_voice_confirm_pending_turn_is_flagged_awaiting_confirmation(confirmation ends the turn with ``finish_reason='voice_confirm_pending'``.The persisted turn must carry ``awaiting_confirmation=True`` so thetranscript can label the reply as a pending yes/no question instead of an- ordinary answer (forensic 2026-06-19: "Soll ich die E-Mail senden?" was+ ordinary answer (forensic 2026-06-19: "Soll ich die E-Mail senden?" was # i18n-allow: quotes the actual German voice-output forensic bug contentindistinguishable from a normal reply in the transcript)."""store = SessionStore(tmp_path / "sessions.db")store.open()@@ -294,7 +294,7 @@ async def test_voice_confirm_pending_turn_is_flagged_awaiting_confirmation(await bus.publish(ResponseGenerated(source_layer="brain",- text="Soll ich die E-Mail wirklich senden? Sag ja oder nein.",+ text="Soll ich die E-Mail wirklich senden? Sag ja oder nein.", # i18n-allow: simulated German brain/voice output under testlanguage="de",))@@ -382,7 +382,7 @@ async def test_normal_turn_is_not_flagged_awaiting_confirmation(tmp_path) -> Non))await bus.publish(ListeningStarted(source_layer="speech"))- await bus.publish(_final("wie spät ist es"))+ await bus.publish(_final("wie spät ist es")) # i18n-allow: simulated German user utterance under testawait bus.publish(ResponseGenerated(source_layer="brain", text="Es ist 15 Uhr.", language="de"))diff --git a/tests/unit/setup/test_obsidian_register.py b/tests/unit/setup/test_obsidian_register.pyindex 9f98f16422..dda6f559b7 100644--- a/tests/unit/setup/test_obsidian_register.py+++ b/tests/unit/setup/test_obsidian_register.py@@ -227,7 +227,7 @@ def test_register_vault_uuid_format(tmp_path: Path) -> None:def test_register_vault_unicode_path_preserved(tmp_path: Path) -> None:"""German umlauts in vault_path survive the JSON round-trip verbatim."""cfg = tmp_path / "obsidian.json"- vault = tmp_path / "Müller Vault"+ vault = tmp_path / "Müller Vault" # i18n-allow: umlaut test data — the test verifies German characters round-tripvault.mkdir()_write_cfg(cfg, {"vaults": {}})@@ -236,7 +236,7 @@ def test_register_vault_unicode_path_preserved(tmp_path: Path) -> None:assert result.status == "added"raw_text = cfg.read_text(encoding="utf-8")# Verbatim umlaut byte sequence in the file (not ü escape).- assert "Müller" in raw_text+ assert "Müller" in raw_text # i18n-allow: matches the umlaut test data above# ---------------------------------------------------------------------------diff --git a/tests/unit/skills/test_builtin_skills.py b/tests/unit/skills/test_builtin_skills.pyindex e27fad603b..8c4a8bda84 100644--- a/tests/unit/skills/test_builtin_skills.py+++ b/tests/unit/skills/test_builtin_skills.py@@ -1,7 +1,7 @@-"""Unit-Tests fuer die 3 Built-in-Skills.+"""Unit tests for the 3 built-in skills.-Prueft dass die SKILL.md-Dateien alle parsbar sind, valide Frontmatter haben,-alle Trigger-Payloads semantisch OK sind und Voice-Regex kompilieren.+Checks that all SKILL.md files parse, have valid frontmatter,+all trigger payloads are semantically OK, and voice regexes compile."""from __future__ import annotations@@ -10,7 +10,7 @@ from pathlib import Pathimport pytest-# Falls parallele B1-Arbeit noch nicht fertig ist: graceful skip.+# If parallel B1 work isn't finished yet: graceful skip.pytest.importorskip("jarvis.skills.schema")pytest.importorskip("jarvis.skills.loader")@@ -33,7 +33,7 @@ def test_skill_parses_successfully(name: str) -> None:f"parse_skill returned no frontmatter for {name}: error={skill.error}")assert skill.state != SkillLifecycleState.DRAFT or skill.error is None- # Explizit: Frontmatter-Modell validieren+ # Explicitly validate the frontmatter modelSkillFrontmatter.model_validate(skill.frontmatter.model_dump())@@ -51,9 +51,9 @@ def test_skill_has_valid_triggers(name: str) -> None:f"disabled skill {name} must not declare triggers")return- # Meta-Skills (category="meta") duerfen ohne Auto-Trigger leben — sie- # werden vom Supervisor per Intent-Dispatch gezogen, nicht vom- # TriggerMatcher. Alle anderen Kategorien brauchen mindestens einen.+ # Meta skills (category="meta") may live without an auto trigger — they+ # are pulled by the supervisor via intent dispatch, not by the+ # TriggerMatcher. All other categories need at least one.if skill.frontmatter.category != "meta":assert len(skill.frontmatter.triggers) >= 1, (f"{name} needs at least one trigger (category={skill.frontmatter.category})"@@ -78,7 +78,7 @@ def test_voice_patterns_compile(name: str) -> None:for t in skill.frontmatter.triggers:if t.type == "voice":assert t.pattern is not None- # Muss als Regex kompilieren+ # Must compile as a regexcompiled = re.compile(t.pattern, re.IGNORECASE)assert compiled is not Nonediff --git a/tests/unit/skills/test_deduplicator.py b/tests/unit/skills/test_deduplicator.pyindex 3e3edb03fd..39ab0d16d8 100644--- a/tests/unit/skills/test_deduplicator.py+++ b/tests/unit/skills/test_deduplicator.py@@ -1,4 +1,4 @@-"""Unit-Tests für den Skill-Deduplicator."""+"""Unit tests for the skill deduplicator."""from __future__ import annotationsfrom pathlib import Pathdiff --git a/tests/unit/skills/test_draft_isolation.py b/tests/unit/skills/test_draft_isolation.pyindex 7233856f99..4e6bcc3db8 100644--- a/tests/unit/skills/test_draft_isolation.py+++ b/tests/unit/skills/test_draft_isolation.py@@ -1,10 +1,10 @@-"""Tests für Plan-§AD-8 + §AP-6: Draft-Skills triggern NIEMALS automatisch.+"""Tests for Plan-§AD-8 + §AP-6: draft skills NEVER auto-trigger.-Akzeptanzkriterien aus Phase 7.5:-- list_active() ignoriert DRAFT-Skills komplett-- list_drafts() zeigt sie an-- promote() bringt sie auf state=active-- promote() blockiert bei unsafe Skill-Body (eval/exec/...)+Acceptance criteria from Phase 7.5:+- list_active() completely ignores DRAFT skills+- list_drafts() shows them+- promote() moves them to state=active+- promote() blocks on an unsafe skill body (eval/exec/...)"""from __future__ import annotations@@ -27,10 +27,10 @@ def _draft(**overrides) -> SkillDraft:defaults: dict = dict(slug="test-skill",name="Test Skill",- description="Test-Skill für Draft-Isolation",+ description="Test skill for draft isolation",intent="test intent",triggers_yaml="[{type: voice, pattern: '^test'}]",- body_markdown="## Test Skill\n\nNur ein Marker-Body.",+ body_markdown="## Test Skill\n\nJust a marker body.",state="draft",)defaults.update(overrides)@@ -53,7 +53,7 @@ class TestDraftIsolation:def test_list_active_excludes_drafts(self, skills_root: Path) -> None:- # 1 Draft anlegen+ # Create 1 draftwrite_draft(_draft(slug="draft-skill"), user_skills_root=skills_root)registry = SkillRegistry(skills_root, bus=None)registry.reload_sync()@@ -63,14 +63,14 @@ class TestDraftIsolation:def test_list_active_includes_validated_skill(self, skills_root: Path) -> None:- # Skill OHNE state-Field im Frontmatter → Loader setzt VALIDATED+ # Skill WITHOUT a state field in frontmatter → loader sets VALIDATEDskill_dir = skills_root / "active-skill"skill_dir.mkdir()(skill_dir / "SKILL.md").write_text("---\n"'schema_version: "1"\n'"name: active-skill\n"- "description: legacy skill ohne state field\n"+ "description: legacy skill without state field\n""---\n\n""## Body\n",encoding="utf-8",@@ -94,7 +94,7 @@ class TestPromote:registry.reload_sync()assert registry.list_drafts()promoted = registry.promote("promo-test")- # Skill ist jetzt aktiv (oder validated, beides ist active-Pool)+ # Skill is now active (or validated, both are in the active pool)assert promoted.state in (SkillLifecycleState.ACTIVE,SkillLifecycleState.VALIDATED,@@ -102,7 +102,7 @@ class TestPromote:assert any(s.path.parent.name == "promo-test" for s in registry.list_active())- # Frontmatter hat state: active+ # Frontmatter has state: activetext = promoted.path.read_text(encoding="utf-8")fm = yaml.safe_load(text.split("---", 2)[1])assert fm["state"] == "active"@@ -120,7 +120,7 @@ class TestPromote:"---\n"'schema_version: "1"\n'"name: active-already\n"- "description: bereits aktiv\n"+ "description: already active\n""---\n",encoding="utf-8",)@@ -144,7 +144,7 @@ class TestPromote:registry.reload_sync()with pytest.raises(UnsafeSkillError):registry.promote("unsafe-skill")- # Skill bleibt im Draft-Status+ # Skill remains in draft statusregistry.reload_sync()assert any(s.path.parent.name == "unsafe-skill"diff --git a/tests/unit/skills/test_finder.py b/tests/unit/skills/test_finder.pyindex 1a3cfba75a..5f9a7ad1e1 100644--- a/tests/unit/skills/test_finder.py+++ b/tests/unit/skills/test_finder.py@@ -1,10 +1,10 @@-"""Unit-Tests fuer den SkillFinder.+"""Unit tests for the SkillFinder.-Decken:-- Filter-Semantik (Trust, Stars, Category, Language, Risk).-- Heuristisches Ranking ohne Brain.-- Brain-Ranking-Integration (mit Fake-Brain).-- Brain-Failure-Fallback auf Heuristik.+Cover:+- Filter semantics (trust, stars, category, language, risk).+- Heuristic ranking without a brain.+- Brain-ranking integration (with a fake brain).+- Brain-failure fallback to heuristics."""from __future__ import annotations@@ -33,7 +33,7 @@ def sample_entries() -> list[dict]:{"name": "email-triage","title": "Email Triage",- "description": "Priorisiert Inbox, fasst zusammen, schlaegt Antworten vor.",+ "description": "Prioritizes inbox, summarizes, suggests replies.","source": "skills-sh","source_url": "https://skills.sh/","raw_url": None,@@ -47,7 +47,7 @@ def sample_entries() -> list[dict]:{"name": "skill-creator","title": "Skill Creator",- "description": "Erstellt neue Skills und verbessert bestehende.",+ "description": "Creates new skills and improves existing ones.","source": "anthropic","source_url": "https://github.com/anthropics/skills/tree/main/skills/skill-creator","raw_url": "https://raw.githubusercontent.com/anthropics/skills/main/skills/skill-creator/SKILL.md",@@ -61,7 +61,7 @@ def sample_entries() -> list[dict]:{"name": "voice-journal","title": "Voice Journal",- "description": "Voice-Driven-Tagebuch mit STT und Zusammenfassung.",+ "description": "Voice-driven diary with STT and summarization.","source": "experimental","source_url": "https://example.com/","raw_url": None,@@ -75,7 +75,7 @@ def sample_entries() -> list[dict]:{"name": "docker-helper","title": "Docker Helper",- "description": "Erstellt Dockerfiles mit Best-Practices.",+ "description": "Creates Dockerfiles following best practices.","source": "community","source_url": "https://example.com/","raw_url": None,@@ -109,7 +109,7 @@ def test_filter_trust_blockt_niedrigeren_level(sample_entries):f = SearchFilters(trust="verified")passing = [e for e in sample_entries if _passes_filter(e, f)]names = {e["name"] for e in passing}- # official + verified erlaubt, community + experimental raus+ # official + verified allowed, community + experimental excludedassert "skill-creator" in namesassert "email-triage" not in namesassert "voice-journal" not in names@@ -122,11 +122,11 @@ def test_filter_trust_any_laesst_alles_durch(sample_entries):def test_filter_min_stars_laesst_official_durch(sample_entries):- """Official-Skills haben stars=None, sollen aber durchkommen."""+ """Official skills have stars=None but should still pass through."""f = SearchFilters(min_stars=2000)passing = [e for e in sample_entries if _passes_filter(e, f)]names = {e["name"] for e in passing}- assert "skill-creator" in names # official, null stars → bleibt+ assert "skill-creator" in names # official, null stars → staysassert "docker-helper" in names # 2600 starsassert "email-triage" not in names # 1800 < 2000assert "voice-journal" not in names # 80 < 2000@@ -141,20 +141,20 @@ def test_filter_category(sample_entries):def test_filter_max_risk(sample_entries):f = SearchFilters(max_risk="safe")passing = [e for e in sample_entries if _passes_filter(e, f)]- # Nur voice-journal (risk=safe)+ # Only voice-journal (risk=safe)assert [e["name"] for e in passing] == ["voice-journal"]def test_filter_language_en_als_fallback(sample_entries):- """Wenn der User 'de' anfragt, muessen EN-only-Skills rausfliegen,- aber bilingual (en+de) bleibt."""+ """When the user requests 'de', EN-only skills must drop out,+ but bilingual (en+de) skills stay."""f = SearchFilters(language="de")passing = [e for e in sample_entries if _passes_filter(e, f)]names = {e["name"] for e in passing}- # email-triage, voice-journal haben "de" -> rein- # skill-creator, docker-helper haben nur "en" -> raus (keine "de")- # Aber der Code erlaubt EN als Fallback? Check...- # Wenn 'de' nicht in langs, aber 'en' in langs → passiert durch (Bilingual-Fallback)+ # email-triage, voice-journal have "de" -> included+ # skill-creator, docker-helper have only "en" -> excluded (no "de")+ # But the code allows EN as a fallback? Check...+ # If 'de' is not in langs but 'en' is in langs → passes through (bilingual fallback)assert names == {"email-triage", "voice-journal", "skill-creator", "docker-helper"}@@ -193,7 +193,7 @@ async def test_search_ohne_brain_rankt_heuristisch(monkeypatch, sample_entries):finder = SkillFinder(brain=None)result = await finder.search(SearchFilters(query="docker", limit=5))- # docker-helper sollte Top-Treffer sein+ # docker-helper should be the top hitassert result[0].name == "docker-helper"assert result[0].score > 0@@ -217,7 +217,7 @@ async def test_search_mit_trust_filter(monkeypatch, sample_entries):# ----------------------------------------------------------------------class _FakeBrain:- """Minimaler Fake-Brain fuer Finder-Tests. Liefert vorgespeicherte Responses."""+ """Minimal fake brain for finder tests. Returns pre-stored responses."""def __init__(self, response: str) -> None:self._response = response@@ -235,8 +235,8 @@ async def test_search_nutzt_brain_ranking(monkeypatch, sample_entries):monkeypatch.setattr(catalog, "load_catalog", lambda: sample_entries)brain_response = json.dumps([- {"name": "voice-journal", "score": 0.95, "reason": "Perfekter Match"},- {"name": "email-triage", "score": 0.3, "reason": "weniger passend"},+ {"name": "voice-journal", "score": 0.95, "reason": "Perfect match"},+ {"name": "email-triage", "score": 0.3, "reason": "less fitting"},])fake = _FakeBrain(brain_response)@@ -244,27 +244,27 @@ async def test_search_nutzt_brain_ranking(monkeypatch, sample_entries):result = await finder.search(SearchFilters(query="voice tagebuch", limit=5))assert fake.call_count == 1- # voice-journal muss Top-Treffer sein, weil Brain-Score 0.95 dominiert+ # voice-journal must be the top hit because brain score 0.95 dominatesassert result[0].name == "voice-journal"- assert "Perfekter Match" in result[0].reason+ assert "Perfect match" in result[0].reason@pytest.mark.asyncioasync def test_search_faellt_auf_heuristik_bei_brain_fehler(monkeypatch, sample_entries):- """Wenn das Brain invalides JSON returnt, muss der Finder trotzdem Ergebnisse- liefern — Graceful Degradation statt Crash."""+ """If the brain returns invalid JSON, the finder must still return+ results — graceful degradation instead of a crash."""from jarvis.skills import catalogmonkeypatch.setattr(catalog, "load_catalog", lambda: sample_entries)- fake = _FakeBrain("das ist kein JSON, nur Prosa")+ fake = _FakeBrain("this is not JSON, just prose")finder = SkillFinder(brain=fake)result = await finder.search(SearchFilters(query="docker", limit=5))- # Muss trotzdem funktionieren+ # Must still workassert len(result) > 0assert result[0].name == "docker-helper"@@ -279,7 +279,7 @@ async def test_search_brain_exception_faellt_auf_heuristik(class _BrokenBrain:async def generate(self, *a, **kw):- raise RuntimeError("Kaputt")+ raise RuntimeError("broken")finder = SkillFinder(brain=_BrokenBrain())result = await finder.search(SearchFilters(query="docker", limit=5))@@ -307,7 +307,7 @@ def test_candidate_from_entry_to_dict(sample_entries):@pytest.mark.asyncioasync def test_install_ohne_raw_url_raised(tmp_path, monkeypatch):- """Kandidat ohne raw_url muss einen klaren Fehler liefern."""+ """A candidate without raw_url must produce a clear error."""monkeypatch.setattr("jarvis.skills.finder.user_skills_dir", lambda: tmp_path)@@ -326,5 +326,5 @@ async def test_install_ohne_raw_url_raised(tmp_path, monkeypatch):tags=(),)finder = SkillFinder()- with pytest.raises(RuntimeError, match="Kein Direkt-Download"):+ with pytest.raises(RuntimeError, match="No direct download available"):await finder.install(cand)diff --git a/tests/unit/skills/test_loader.py b/tests/unit/skills/test_loader.pyindex eba06038c9..2ff691b788 100644--- a/tests/unit/skills/test_loader.py+++ b/tests/unit/skills/test_loader.py@@ -1,4 +1,4 @@-"""Unit-Tests für den Skill-Loader."""+"""Unit tests for the skill loader."""from __future__ import annotationsfrom pathlib import Path@@ -24,7 +24,7 @@ token_budget_estimate: 500# Test Skill Body-Das ist der Body der Skill.+This is the skill's body.TOOL: echo {"text": "hi"}"""@@ -68,7 +68,7 @@ def test_parse_valid_skill(skill_dir: Path):assert sk.state == SkillLifecycleState.VALIDATEDassert sk.error is Noneassert sk.body_hash != ""- assert "Das ist der Body" in sk.body+ assert "This is the skill's body" in sk.bodydef test_parse_invalid_frontmatter(skill_dir: Path):diff --git a/tests/unit/skills/test_skill_authoring.py b/tests/unit/skills/test_skill_authoring.pyindex 6693b53989..c6e2216e1e 100644--- a/tests/unit/skills/test_skill_authoring.py+++ b/tests/unit/skills/test_skill_authoring.py@@ -1,12 +1,12 @@-"""Tests für die Skill-Authoring-Pipeline (Phase 7.5).--Plan-Akzeptanzkriterien §7.5:-- Spawn erzeugt valides SKILL.md im Draft-State-- state=draft wird auch dann forciert, wenn Sub-Jarvis fälschlich `active` schreibt-- Validation-Retry funktioniert mit konkretem Pydantic-Feedback-- Name-Clash erzeugt Suffix, kein Overwrite-- Draft-Skill triggert nicht (Negative-Test mit TriggerMatcher)-- Audit-Eintrag enthält iterations-Counter+"""Tests for the skill-authoring pipeline (Phase 7.5).++Plan acceptance criteria §7.5:+- Spawn produces a valid SKILL.md in draft state+- state=draft is forced even when Sub-Jarvis wrongly writes `active`+- Validation retry works with concrete Pydantic feedback+- Name clash produces a suffix, no overwrite+- Draft skill doesn't trigger (negative test with TriggerMatcher)+- Audit entry contains an iterations counter"""from __future__ import annotations@@ -49,11 +49,11 @@ def _draft(**overrides) -> SkillDraft:defaults: dict = dict(slug="spotify-auto-pause",name="Spotify Auto-Pause",- description="Pausiert Spotify wenn User redet.",+ description="Pauses Spotify when the user talks.",intent="user wants spotify auto-pause",triggers_yaml="[{type: voice, pattern: '^pause spotify'}]",requires_tools=["run-shell"],- body_markdown="## Spotify Auto-Pause\n\nDieser Skill ...",+ body_markdown="## Spotify Auto-Pause\n\nThis skill ...",state="draft",)defaults.update(overrides)@@ -123,7 +123,7 @@ class TestWriteDraft:result = write_draft(draft, user_skills_root=user_skills_root)assert result.draft_path.exists()text = result.draft_path.read_text(encoding="utf-8")- # Frontmatter parsen+ # Parse frontmatterfm_text = text.split("---", 2)[1]fm = yaml.safe_load(fm_text)assert fm["state"] == "draft"@@ -132,8 +132,8 @@ class TestWriteDraft:def test_state_active_in_draft_is_forced_to_draft(self, user_skills_root: Path) -> None:- """Plan-§AD-8: Sub-Jarvis-Output state="active" wird beim- Schreiben unconditional auf "draft" überschrieben.+ """Plan-§AD-8: Sub-Jarvis output state="active" is unconditionally+ overwritten to "draft" when writing."""draft = _draft(state="active")result = write_draft(draft, user_skills_root=user_skills_root)@@ -148,10 +148,10 @@ class TestWriteDraft:second = write_draft(draft, user_skills_root=user_skills_root)assert first.slug == "spotify-auto-pause"assert second.slug == "spotify-auto-pause_2"- # Beide existieren+ # Both existassert first.draft_path.exists()assert second.draft_path.exists()- # Erste wurde NICHT überschrieben+ # The first one was NOT overwrittenassert (user_skills_root / "spotify-auto-pause" / "SKILL.md").exists()@@ -215,7 +215,7 @@ class TestSafeLint:assert any("forbidden_import" in f for f in findings)def test_no_python_block_no_findings(self) -> None:- body = "## Pure Markdown\n\nKein Code hier."+ body = "## Pure Markdown\n\nNo code here."assert safe_lint_skill_body(body) == []# Sub-Agent-Review-MAJOR-Hardening (Phase 7.5)@@ -267,8 +267,8 @@ class TestSafeLint:assert any("os.execvp" in f for f in findings)def test_plain_text_codefence_ignored(self) -> None:- """Codefence mit Sprach-Tag das KEIN Python ist (z.B. `bash`,- `json`) wird NICHT AST-geparst."""+ """A codefence with a language tag that is NOT Python (e.g. `bash`,+ `json`) is NOT AST-parsed."""body = "```bash\necho 'eval is just a word here'\n```"assert safe_lint_skill_body(body) == []@@ -323,7 +323,7 @@ class TestRunnerForcedStateOverride:def test_subjarvis_active_yields_forced_override_audit(self, user_skills_root: Path, audit: SelfModAudit) -> None:- """Plan-AC §7.5: state=draft forciert auch wenn Sub-Jarvis 'active' liefert."""+ """Plan-AC §7.5: state=draft is forced even when Sub-Jarvis returns 'active'."""async def fake_spawn(prompt: str) -> str:return _good_response_json(state="active")@@ -335,11 +335,11 @@ class TestRunnerForcedStateOverride:result = asyncio.run(runner.author("intent text"))assert isinstance(result, AuthoringSuccess)assert result.forced_state_override is True- # Geschriebene Datei hat state: draft+ # The written file has state: drafttext = result.draft_path.read_text(encoding="utf-8")fm = yaml.safe_load(text.split("---", 2)[1])assert fm["state"] == "draft"- # Audit-Eintrag dokumentiert den Override+ # Audit entry documents the overrideentries = [json.loads(line)for line in audit.path.read_text(encoding="utf-8").splitlines()@@ -364,7 +364,7 @@ class TestRunnerParseFailure:result = asyncio.run(runner.author("intent text"))assert isinstance(result, AuthoringFailure)assert result.error_kind == "parse_failed"- # Kein Draft im skills-root+ # No draft in the skills rootdrafts = list(user_skills_root.rglob("SKILL.md"))assert drafts == []# Audit "author_failed_parse"@@ -382,7 +382,7 @@ class TestRunnerParseFailure:async def fake_spawn(prompt: str) -> str:attempts.append(prompt)- # Erste 2 Versuche: invalid; 3. Versuch: valid+ # First 2 attempts: invalid; 3rd attempt: validif len(attempts) < 3:return "garbage"return _good_response_json()@@ -420,7 +420,7 @@ class TestRunnerUnsafeBody:result = asyncio.run(runner.author("intent text"))assert isinstance(result, AuthoringFailure)assert result.error_kind == "unsafe"- # Kein Draft geschrieben+ # No draft writtenassert list(user_skills_root.rglob("SKILL.md")) == []@@ -436,7 +436,7 @@ class TestSpawnSkillAuthorTool:schema = SpawnSkillAuthorTool.schemaassert schema["strict"] is Trueassert schema["additionalProperties"] is False- # Plan-§AD-9: alle Properties in `required`+ # Plan-§AD-9: all properties in `required`properties = set(schema["properties"].keys())required = set(schema["required"])assert properties == requireddiff --git a/tests/unit/skills/test_skill_context.py b/tests/unit/skills/test_skill_context.pyindex edf37b9b6f..ffffeb96bd 100644--- a/tests/unit/skills/test_skill_context.py+++ b/tests/unit/skills/test_skill_context.py@@ -1,7 +1,7 @@-"""Unit-Tests fuer den prozessweiten Skill-Context (Skills-Brain-Integration: Phase Skills-1).+"""Unit tests for the process-wide skill context (skills-brain integration: Phase Skills-1).-Vorbild-Tests: ``tests/unit/harness/test_computer_use_context.py`` (falls-vorhanden) — selbe Mechanik (Set/Get/TryGet) wird hier verifiziert.+Model tests: ``tests/unit/harness/test_computer_use_context.py`` (if+present) — the same mechanism (set/get/tryGet) is verified here."""from __future__ import annotations@@ -16,16 +16,16 @@ from jarvis.skills.skill_context import (class _StubRegistry:- """Marker-Stub fuer SkillRegistry — nur Identitaets-Tests, kein Verhalten."""+ """Marker stub for SkillRegistry — identity tests only, no behavior."""class _StubRunner:- """Marker-Stub fuer SkillRunner — nur Identitaets-Tests, kein Verhalten."""+ """Marker stub for SkillRunner — identity tests only, no behavior."""@pytest.fixture(autouse=True)def _reset_context():- """Garantiert sauberer State pro Test — globaler Context wird zurueckgesetzt."""+ """Guarantees clean state per test — global context is reset."""set_skill_context(None)yieldset_skill_context(None)@@ -36,7 +36,7 @@ def test_try_get_returns_none_when_unset():def test_get_raises_runtime_error_when_unset():- with pytest.raises(RuntimeError, match="nicht gesetzt"):+ with pytest.raises(RuntimeError, match="not set"):get_skill_context()diff --git a/tests/unit/skills/test_skill_promote_cli.py b/tests/unit/skills/test_skill_promote_cli.pyindex cd9c620f36..7b5996f131 100644--- a/tests/unit/skills/test_skill_promote_cli.py+++ b/tests/unit/skills/test_skill_promote_cli.py@@ -1,7 +1,7 @@-"""Tests für `python -m jarvis.skills.cli --list-drafts/--promote` (Phase 7.5).+"""Tests for `python -m jarvis.skills.cli --list-drafts/--promote` (Phase 7.5).-CLI-Tests laufen ohne echte Sub-Jarvis-Calls — wir legen vorab einen-Draft via `write_draft` an und triggern dann die CLI-Subcommands.+CLI tests run without real Sub-Jarvis calls — we write a draft upfront+via `write_draft` and then trigger the CLI subcommands."""from __future__ import annotations@@ -16,10 +16,10 @@ def _draft(**overrides) -> SkillDraft:defaults: dict = dict(slug="cli-test",name="CLI Test Skill",- description="Skill für CLI-promote-Test",+ description="Skill for CLI promote test",intent="test cli",triggers_yaml="[]",- body_markdown="## CLI Test\n\nNur ein Body.",+ body_markdown="## CLI Test\n\nJust a body.",state="draft",)defaults.update(overrides)@@ -30,7 +30,7 @@ def _draft(**overrides) -> SkillDraft:def skills_root_patched(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:- """Patcht user_skills_dir() auf tmp_path/user_skills für CLI-Tests."""+ """Patches user_skills_dir() to tmp_path/user_skills for CLI tests."""root = tmp_path / "user_skills"root.mkdir()@@ -73,7 +73,7 @@ class TestListDraftsCli:exit_code = main(["--list-drafts"])assert exit_code == 0captured = capsys.readouterr()- assert "Keine Draft-Skills" in captured.out+ assert "No draft skills present" in captured.out# ----------------------------------------------------------------------@@ -93,7 +93,7 @@ class TestPromoteCli:exit_code = main(["--promote", "cli-test"])assert exit_code == 0captured = capsys.readouterr()- assert "ist jetzt aktiv" in captured.out+ assert "is now active" in captured.outdef test_promote_unknown_slug_exits_1(self,diff --git a/tests/unit/skills/test_validator.py b/tests/unit/skills/test_validator.pyindex 66c32e69d5..e6d8ae9ec2 100644--- a/tests/unit/skills/test_validator.py+++ b/tests/unit/skills/test_validator.py@@ -1,4 +1,4 @@-"""Unit-Tests für den Skill-Validator."""+"""Unit tests for the skill validator."""from __future__ import annotationsfrom pathlib import Path@@ -58,7 +58,7 @@ def test_validate_good_skill(tmp_path: Path):def test_validate_bad_regex(tmp_path: Path):sk = _parse(tmp_path, "bad", BAD_REGEX_SKILL)- # Trigger-payload-check fängt die regex nicht, aber validator compiliert+ # The trigger-payload check doesn't catch the regex, but the validator compiles itreport = validate_skill(sk, tool_registry=[])assert not report.okassert any("regex" in e.lower() for e in report.errors)@@ -72,8 +72,8 @@ def test_validate_missing_tool_warns(tmp_path: Path):def test_validate_budget_too_big(tmp_path: Path):- # Budget wird schon vom pydantic-Schema abgefangen (ge=1, le=100_000 aber- # Validator prüft zusätzlich > 10_000)+ # The budget is already caught by the pydantic schema (ge=1, le=100_000, but+ # the validator additionally checks > 10_000)sk = _parse(tmp_path, "big", TOO_BIG_BUDGET)assert sk.frontmatter is not Nonereport = validate_skill(sk, tool_registry=[])diff --git a/tests/unit/speech/test_announcement_bridge.py b/tests/unit/speech/test_announcement_bridge.pyindex 59829c288a..729960372b 100644--- a/tests/unit/speech/test_announcement_bridge.py+++ b/tests/unit/speech/test_announcement_bridge.py@@ -1,17 +1,18 @@-"""Unit-Tests fuer die TTS-Announcement-Bridge (Phase 5 CL-13).--Der ``AnnouncementRequested``-Event wird vom RouterBrain / Tools emittiert,-wenn dem User eine konkrete Zwischenansage ohne Brain-Pfad gegeben werden soll.-Die ``SpeechPipeline`` subscribed darauf und spielt die Ansage ueber ``synthesize()`` +-``player.play_chunks()`` ab — identischer Pfad wie normale Antworten.--Regression-Hintergrund (2026-04-23): Die frueheren Tests hier liefen gegen-einen ``FakeTTS`` mit ``speak()``-Methode. Der echte ``GeminiFlashTTS``-exponiert jedoch nur ``synthesize()``, und der alte ``_on_announcement``-rief ``self._tts.speak(...)`` auf — ein stummer ``AttributeError``, der-die Announcements monatelang unhoerbar machte. Die Tests waren grün, weil-Fake und Implementation sich gegenseitig bestaetigten. Jetzt wird gegen-die echte ``synthesize()``-API getestet.+"""Unit tests for the TTS announcement bridge (Phase 5 CL-13).++The ``AnnouncementRequested`` event is emitted by the RouterBrain / tools+when the user should be given a concrete interim announcement without going+through the brain path. The ``SpeechPipeline`` subscribes to it and plays the+announcement via ``synthesize()`` + ``player.play_chunks()`` — the identical+path as normal answers.++Regression background (2026-04-23): the earlier tests here ran against+a ``FakeTTS`` with a ``speak()`` method. The real ``GeminiFlashTTS``+only exposes ``synthesize()`` though, and the old ``_on_announcement``+called ``self._tts.speak(...)`` — a silent ``AttributeError`` that made+announcements inaudible for months. The tests were green because the+fake and the implementation confirmed each other. Now it is tested+against the real ``synthesize()`` API."""from __future__ import annotations@@ -32,7 +33,7 @@ from jarvis.speech.pipeline import SpeechPipeline@dataclassclass FakeTTS:- """TTS-Fake mit realer ``synthesize``-API (Protokoll-konform)."""+ """TTS fake with a real ``synthesize`` API (protocol-conformant)."""name: str = "fake-tts"supports_streaming: bool = True@@ -43,14 +44,14 @@ class FakeTTS:language_code: str | None = None,) -> AsyncIterator[AudioChunk]:self.calls.append((text, language_code))- # AsyncGenerator ohne yields → leerer Stream, reicht fuer Assertions+ # AsyncGenerator with no yields → empty stream, enough for the assertionsif False: # pragma: no coveryield # type: ignore[unreachable]@dataclassclass FakePlayer:- """Player-Fake: zeichnet play_chunks-Aufrufe + stop-Calls auf."""+ """Player fake: records play_chunks calls + stop calls."""stop_calls: int = 0plays: int = 0@@ -68,7 +69,7 @@ class FakePlayer:class FakeBrain:- """Zaehlt Calls — darf bei Announcements NIE gerufen werden."""+ """Counts calls — must NEVER be called for announcements."""def __init__(self) -> None:self.calls: int = 0@@ -81,10 +82,10 @@ class FakeBrain:def _make_pipeline(tts: FakeTTS, bus: EventBus, player: FakePlayer | None = None) -> SpeechPipeline:- """Pipeline mit gestecktem Fake-TTS + Bus + optionalem FakePlayer.+ """Pipeline wired with a fake TTS + bus + optional FakePlayer.- STT/Wake sind hier irrelevant. Der FakePlayer ersetzt ``self._player``,- damit kein echtes WASAPI geoeffnet wird.+ STT/wake are irrelevant here. The FakePlayer replaces ``self._player``,+ so no real WASAPI gets opened."""pipeline = SpeechPipeline(tts=tts, bus=bus, enable_whisper_wake=False)if player is not None:@@ -110,12 +111,12 @@ async def test_announcement_event_triggers_synthesize() -> None:@pytest.mark.asyncioasync def test_announcement_english_language_passthrough() -> None:- """Sprachparameter wird zu language_code gemappt (en → en-US).+ """The language parameter is mapped to language_code (en → en-US).- Audit F-AUDIT-5 (2026-04-29): Test-Text auf neutrale Phrase migriert,- weil scrub_for_voice "sir"-Anrede + "sub-agent"-Engineering-Compounds- scrubbt (Mandat-A1). Der Test verifiziert die Bridge-Mechanik, nicht- die Phrasen-Inhalte.+ Audit F-AUDIT-5 (2026-04-29): migrated the test text to a neutral phrase,+ because scrub_for_voice scrubs "sir" address + "sub-agent" engineering+ compounds (mandate A1). The test verifies the bridge mechanics, not+ the phrase contents."""bus = EventBus()tts = FakeTTS()@@ -131,11 +132,11 @@ async def test_announcement_english_language_passthrough() -> None:@pytest.mark.asyncioasync def test_announcement_bypass_skips_brain() -> None:- """Announcements duerfen den Brain-Pfad nicht anstossen (TTS-Bypass).+ """Announcements must not touch the brain path (TTS bypass).- Audit F-AUDIT-5: "sub-agent" durch neutrales "routine" ersetzt — der- Test verifiziert dass FakeBrain nicht angestossen wird, nicht den- Phrasen-Inhalt.+ Audit F-AUDIT-5: replaced "sub-agent" with the neutral "routine" — the+ test verifies that FakeBrain is not touched, not the+ phrase content."""bus = EventBus()tts = FakeTTS()@@ -163,12 +164,12 @@ async def test_announcement_interrupt_calls_player_stop_before_play() -> None:await bus.publish(AnnouncementRequested(- text="achtung, abbruch", language="de", priority="interrupt"+ text="achtung, abbruch", language="de", priority="interrupt" # i18n-allow: simulated German announcement voice output under test))assert player.stop_calls == 1- assert tts.calls == [("achtung, abbruch", "de-DE")]+ assert tts.calls == [("achtung, abbruch", "de-DE")] # i18n-allow: matches simulated German voice output aboveassert player.order == ["stop", "play"]@@ -190,7 +191,7 @@ async def test_announcement_normal_does_not_call_stop() -> None:@pytest.mark.asyncioasync def test_announcement_without_bus_is_safe() -> None:- """Ohne Bus wird keine Subscription angelegt — Pipeline bleibt funktional."""+ """Without a bus, no subscription is created — the pipeline stays functional."""tts = FakeTTS()pipeline = SpeechPipeline(tts=tts, bus=None, enable_whisper_wake=False)assert pipeline._bus is None@@ -199,18 +200,18 @@ async def test_announcement_without_bus_is_safe() -> None:@pytest.mark.asyncioasync def test_openclaw_spawn_announcement_is_silent() -> None:- """``JarvisAgentAnnouncement`` darf NICHT mehr TTS-sprechen.-- Spawn-ACK-History:- - 2026-04-25 .. 2026-05-10: stumm (User-Wunsch).- - 2026-05-11: kurz reaktiviert mit "Okay, mache ich." damit der- User Spawn von stillem Timeout unterscheiden kann.- - 2026-05-12 (aktuell): User widerruft — die Phrase nervt. Spawn-- Feedback uebernimmt das Sub-Agents-Board (visuell) und der- Background-Completed-Readback am Ende der Mission.-- Regression-Guard: wenn jemand den ACK ohne ADR-Update wieder- einbaut, schlaegt dieser Test an.+ """``JarvisAgentAnnouncement`` must NOT speak via TTS anymore.++ Spawn-ACK history:+ - 2026-04-25 .. 2026-05-10: silent (user request).+ - 2026-05-11: briefly reactivated with "Okay, mache ich." so the+ user could tell a spawn apart from a silent timeout.+ - 2026-05-12 (current): user revokes it again — the phrase is annoying.+ Spawn feedback is now handled by the Sub-Agents board (visual) and the+ background-completed readback at the end of the mission.++ Regression guard: if someone reintroduces the ACK without an ADR update,+ this test catches it."""from uuid import uuid4@@ -222,13 +223,13 @@ async def test_openclaw_spawn_announcement_is_silent() -> None:await bus.publish(JarvisAgentAnnouncement(trace_id=uuid4(),- action="den vom User beschriebenen Workflow",+ action="the workflow described by the user",target="",))assert tts.calls == [], (- f"Spawn-ACK darf nicht sprechen, aber TTS wurde gerufen: "+ f"Spawn ACK must not speak, but TTS was called: "f"{tts.calls!r}")assert player.plays == 0@@ -245,22 +246,22 @@ async def test_openclaw_background_success_with_summary_speaks() -> None:await bus.publish(JarvisAgentBackgroundCompleted(success=True,- utterance="recherchier mir fuenf themen",- summary="Fuenf Recherche-Themen liegen bereit.",+ utterance="recherchier mir fuenf themen", # i18n-allow: simulated German user utterance under test+ summary="Fuenf Recherche-Themen liegen bereit.", # i18n-allow: simulated German voice output under testerror="",duration_s=12.3,))assert tts.calls == [- ("Fertig. Fuenf Recherche-Themen liegen bereit.", "de-DE")+ ("Fertig. Fuenf Recherche-Themen liegen bereit.", "de-DE") # i18n-allow: matches simulated German voice output above]assert player.plays == 1@pytest.mark.asyncioasync def test_openclaw_background_success_no_summary_speaks_fertig() -> None:- """Erfolg ohne Summary → ``"Fertig."`` (Output-Filter-safe)."""+ """Success with no summary → ``"Fertig."`` (output-filter-safe)."""bus = EventBus()tts = FakeTTS()player = FakePlayer()@@ -272,13 +273,13 @@ async def test_openclaw_background_success_no_summary_speaks_fertig() -> None:))- assert tts.calls == [("Fertig.", "de-DE")]+ assert tts.calls == [("Fertig.", "de-DE")] # i18n-allow: simulated German voice output under testassert player.plays == 1@pytest.mark.asyncioasync def test_openclaw_background_failure_speaks_error() -> None:- """``success=False`` → Fehler-Ansage ``"Das hat nicht geklappt. ..."``."""+ """``success=False`` → error announcement ``"Das hat nicht geklappt. ..."``."""bus = EventBus()tts = FakeTTS()player = FakePlayer()@@ -291,24 +292,24 @@ async def test_openclaw_background_failure_speaks_error() -> None:))- # rate-limit ueberlebt scrub_for_voice. "Provider" wuerde gescrubbt.- # event.error endet ohne Punkt → text endet ohne Punkt (simple Concat).- assert tts.calls == [("Das hat nicht geklappt. rate-limit reached", "de-DE")]+ # rate-limit survives scrub_for_voice. "Provider" would be scrubbed.+ # event.error ends without a period → text ends without a period (simple concat).+ assert tts.calls == [("Das hat nicht geklappt. rate-limit reached", "de-DE")] # i18n-allow: simulated German voice output under testassert player.plays == 1@pytest.mark.asyncioasync def test_announcement_regression_no_speak_api() -> None:- """Regression-Guard: pipeline darf kein ``tts.speak(...)`` rufen.+ """Regression guard: the pipeline must not call ``tts.speak(...)``.- Der FakeTTS exponiert bewusst KEIN ``speak``. Wenn die Pipeline trotzdem- versuchen wuerde ``tts.speak(...)`` zu rufen (wie in der 2026-04-23-Bug-- Version), landete der ``AttributeError`` stumm im except-Block und der- Spy auf ``synthesize()`` waere leer.+ The FakeTTS deliberately does NOT expose ``speak``. If the pipeline+ still tried to call ``tts.speak(...)`` (as in the 2026-04-23 bug+ version), the ``AttributeError`` landed silently in the except block and+ the spy on ``synthesize()`` would be empty."""bus = EventBus()tts = FakeTTS()- assert not hasattr(tts, "speak"), "Fake soll speak() NICHT exponieren"+ assert not hasattr(tts, "speak"), "fake must NOT expose speak()"player = FakePlayer()_make_pipeline(tts, bus, player)@@ -317,7 +318,7 @@ async def test_announcement_regression_no_speak_api() -> None:)assert tts.calls == [("zu diensten ruben", "de-DE")], (- "Announcement muss ueber synthesize() laufen, nicht tts.speak()"+ "announcement must go through synthesize(), not tts.speak()")assert player.plays == 1@@ -349,7 +350,7 @@ async def test_announcement_language_none_resolves_via_conversation() -> None:@pytest.mark.asyncioasync def test_empty_announcement_is_not_spoken() -> None:- """Leere Announcements sind UI-/State-Signale, keine TTS-Phrasen."""+ """Empty announcements are UI/state signals, not TTS phrases."""bus = EventBus()tts = FakeTTS()player = FakePlayer()@@ -363,14 +364,14 @@ async def test_empty_announcement_is_not_spoken() -> None:@pytest.mark.asyncioasync def test_openclaw_spawn_action_echo_is_not_spoken() -> None:- """Spawn-Voice-Pfad ist seit 2026-05-12 komplett stumm.-- History dieses Tests:- - Pre-2026-05-11: pruefte dass Pfad gar nicht spricht (urspruengl. Suppress).- - 2026-05-11: Spawn-ACK reaktiviert, Test prueft FIXE Phrase ohne Echo- aus ``event.action`` (Tool-Use-Leak-Vektor).- - 2026-05-12: User widerruft den ACK komplett. Test garantiert:- egal welche action/target im Event, KEIN TTS-Call.+ """The spawn voice path has been completely silent since 2026-05-12.++ History of this test:+ - Pre-2026-05-11: verified the path doesn't speak at all (original suppress).+ - 2026-05-11: spawn ACK reactivated, test verifies a FIXED phrase without+ echoing ``event.action`` (tool-use-leak vector).+ - 2026-05-12: user revokes the ACK entirely. Test guarantees:+ no matter what action/target is on the event, NO TTS call."""from uuid import uuid4@@ -382,13 +383,13 @@ async def test_openclaw_spawn_action_echo_is_not_spoken() -> None:await bus.publish(JarvisAgentAnnouncement(trace_id=uuid4(),- action="eine App baut",- target="im Workspace",+ action="builds an app",+ target="in the workspace",))assert tts.calls == [], (- f"Spawn-Pfad darf nicht sprechen, aber TTS wurde gerufen: "+ f"Spawn path must not speak, but TTS was called: "f"{tts.calls!r}")assert player.plays == 0@@ -396,11 +397,11 @@ async def test_openclaw_spawn_action_echo_is_not_spoken() -> None:@pytest.mark.asyncioasync def test_openclaw_completion_signal_does_speak_with_summary() -> None:- """Completion-Voice-Meldung MUSS sprechen — User-Wunsch 2026-05-11.+ """The completion voice message MUST speak — user request 2026-05-11.- Vor 2026-05-11 war dieser Pfad suppress't und der Vorgaenger-Test- verifizierte ``tts.calls == []``. Heute Regression-Guard fuer das- umgekehrte Verhalten: success+summary → kurze Voice-Ansage.+ Before 2026-05-11 this path was suppressed and the predecessor test+ verified ``tts.calls == []``. Today's regression guard is for the+ opposite behavior: success+summary → short voice announcement."""bus = EventBus()tts = FakeTTS()@@ -411,12 +412,12 @@ async def test_openclaw_completion_signal_does_speak_with_summary() -> None:JarvisAgentBackgroundCompleted(success=True,utterance="baue mir etwas",- summary="Fertig gebaut",+ summary="Fertig gebaut", # i18n-allow: simulated German voice output under testduration_s=1.2,))- assert tts.calls == [("Fertig. Fertig gebaut", "de-DE")]+ assert tts.calls == [("Fertig. Fertig gebaut", "de-DE")] # i18n-allow: matches simulated German voice output aboveassert player.plays == 1@@ -443,14 +444,14 @@ async def test_completion_announcement_speaks_after_hangup() -> None:await bus.publish(AnnouncementRequested(- text="Deine Reise-Recherche ist fertig.",+ text="Deine Reise-Recherche ist fertig.", # i18n-allow: simulated German voice output under testlanguage="de",priority="normal",kind="completion",))- assert tts.calls == [("Deine Reise-Recherche ist fertig.", "de-DE")]+ assert tts.calls == [("Deine Reise-Recherche ist fertig.", "de-DE")] # i18n-allow: matches simulated German voice output aboveassert player.plays == 1@@ -466,7 +467,7 @@ async def test_stale_preamble_dropped_after_hangup() -> None:await bus.publish(AnnouncementRequested(- text="Einen Moment, ich schaue nach.",+ text="Einen Moment, ich schaue nach.", # i18n-allow: simulated German voice output under testlanguage="de",priority="normal",kind="preamble",@@ -488,7 +489,7 @@ async def test_plain_late_announcement_still_dropped_after_hangup() -> None:pipeline._hangup_event.set() # type: ignore[attr-defined]await bus.publish(- AnnouncementRequested(text="irgendeine späte ansage", language="de")+ AnnouncementRequested(text="irgendeine späte ansage", language="de") # i18n-allow: simulated German voice output under test)assert tts.calls == []@@ -508,15 +509,15 @@ async def test_background_completed_speaks_after_hangup() -> None:await bus.publish(JarvisAgentBackgroundCompleted(success=True,- utterance="recherchier mir fuenf themen",- summary="Fuenf Recherche-Themen liegen bereit.",+ utterance="recherchier mir fuenf themen", # i18n-allow: simulated German user utterance under test+ summary="Fuenf Recherche-Themen liegen bereit.", # i18n-allow: simulated German voice output under testerror="",duration_s=12.3,))assert tts.calls == [- ("Fertig. Fuenf Recherche-Themen liegen bereit.", "de-DE")+ ("Fertig. Fuenf Recherche-Themen liegen bereit.", "de-DE") # i18n-allow: matches simulated German voice output above]assert player.plays == 1@@ -533,7 +534,7 @@ async def test_completion_announcement_still_silenced_when_muted() -> None:await bus.publish(AnnouncementRequested(- text="Deine Reise-Recherche ist fertig.",+ text="Deine Reise-Recherche ist fertig.", # i18n-allow: simulated German voice output under testlanguage="de",kind="completion",)diff --git a/tests/unit/speech/test_announcement_language.py b/tests/unit/speech/test_announcement_language.pyindex 3118f26e0d..c84e721b0a 100644--- a/tests/unit/speech/test_announcement_language.py+++ b/tests/unit/speech/test_announcement_language.py@@ -45,7 +45,7 @@ async def test_announcement_uses_text_not_mistagged_event_language() -> None:await bus.publish(AnnouncementRequested(- text="Das Dokument ist fertig und liegt bereit.", language="en"+ text="Das Dokument ist fertig und liegt bereit.", language="en" # i18n-allow: simulated German voice text under test (mistagged as "en")))diff --git a/tests/unit/speech/test_background_readback_language.py b/tests/unit/speech/test_background_readback_language.pyindex c199da59be..f2dc918681 100644--- a/tests/unit/speech/test_background_readback_language.py+++ b/tests/unit/speech/test_background_readback_language.py@@ -36,7 +36,7 @@ async def test_background_readback_speaks_english_for_english_conversation() ->assert tts.calls, "expected a background readback to be synthesized"text, lang_code = tts.calls[-1]assert lang_code == "en-US"- assert "Fertig" not in text+ assert "Fertig" not in text # i18n-allow: verifies the German phrase is NOT the actual German voice output@pytest.mark.asyncio@@ -53,4 +53,4 @@ async def test_background_readback_stays_german_for_german_conversation() -> Nonassert tts.calls, "expected a background readback to be synthesized"text, lang_code = tts.calls[-1]assert lang_code == "de-DE"- assert "Fertig" in text+ assert "Fertig" in text # i18n-allow: matches the actual German voice outputdiff --git a/tests/unit/speech/test_clarify_question.py b/tests/unit/speech/test_clarify_question.pyindex 452ede4acb..abb8037c71 100644--- a/tests/unit/speech/test_clarify_question.py+++ b/tests/unit/speech/test_clarify_question.py@@ -1,6 +1,6 @@-"""Clarifying-question ("Zwischenfrage") for an abandoned incomplete utterance.+"""Clarifying-question ("Zwischenfrage") for an abandoned incomplete utterance. # i18n-allow: German gloss of the feature name-Root cause (user report 2026-06-08, "Jarvis hört für immer zu"): when the user+Root cause (user report 2026-06-08, "Jarvis hört für immer zu"): when the user # i18n-allow: quotes the actual German forensic user-report phrasetrails off on an open-ended fragment ("…erinnere mich daran, dass" + silence),the ``ContinuationBuffer`` holds it with NO active timeout — it only drops thestale fragment lazily on the *next* ``process()`` call. So a user who stops@@ -83,7 +83,7 @@ def test_voice_config_has_clarify_defaults() -> None:# was constantly interrogated with "Wie meinst du das genau?" because every# empty brain turn (Gemini function_call without narration / Codex CLI# timing out on the voice path) fell through to the clarifying question. The- # original "Jarvis hört für immer zu" cause was the watchdog stale-counter+ # original "Jarvis hört für immer zu" cause was the watchdog stale-counter # i18n-allow: quotes the actual German forensic user-report phrase# (BUG-032), fixed separately — so the clarify question lost its only real# purpose and now just blames the user for a brain glitch. Shipped default# is OFF; the feature stays available as an explicit opt-in.@@ -430,12 +430,12 @@ async def test_successful_action_turn_speaks_confirmation_not_clarify() -> None:# (Gemini) emitted a function_call to `computer_use`, the CU loop opened# Chrome ([cu] step 1.1 open_app chrome → step 2 done), but Gemini produced# NO narration text. `_handle_silent_brain_turn` then spoke the clarifying- # question "Wie meinst du das genau?" — making a SUCCESSFUL desktop action- # look like incomprehension ("er checkt das nicht"). A turn that executed a+ # question "Wie meinst du das genau?" — making a SUCCESSFUL desktop action # i18n-allow: quotes the actual German clarify-question voice phrase+ # look like incomprehension ("er checkt das nicht"). A turn that executed a # i18n-allow: quotes the maintainer's actual forensic report# desktop-action tool must speak a positive CONFIRMATION, never the clarify# question.pipe = _make_silent_pipe(failed=False, suppressed=False, executed_action=True)- await pipe._handle_silent_brain_turn("de", "kannst du chrome oeffnen")+ await pipe._handle_silent_brain_turn("de", "kannst du chrome oeffnen") # i18n-allow: simulated German user utterance under testassert len(pipe._spoken) == 1, pipe._spokentext, lang = pipe._spoken[0]assert lang == "de"@@ -565,8 +565,8 @@ async def test_armed_clarify_stays_silent_when_field_absent_from_config() -> Non@pytest.mark.asyncioasync def test_default_config_empty_turn_does_not_interrogate_user() -> None:- # User mandate 2026-06-09 ("er fragt mich ständig 'Wie meinst du das?' —- # ich will, dass er einfach normal antwortet wie damals"): with the SHIPPED+ # User mandate 2026-06-09 ("er fragt mich ständig 'Wie meinst du das?' — # i18n-allow: quotes the maintainer's actual mandate wording+ # ich will, dass er einfach normal antwortet wie damals"): with the SHIPPED # i18n-allow: quotes the maintainer's actual mandate wording# default config (no [voice] override in jarvis.toml → the dataclass# default governs), an empty brain turn must NOT speak the clarifying# question. This ties the behaviour to the real ``VoiceConfig`` default@@ -575,6 +575,6 @@ async def test_default_config_empty_turn_does_not_interrogate_user() -> None:pipe = _make_silent_pipe(failed=False, suppressed=False, enabled=default_enabled)- await pipe._handle_silent_brain_turn("de", "kannst du mein spotify öffnen")+ await pipe._handle_silent_brain_turn("de", "kannst du mein spotify öffnen") # i18n-allow: simulated German user utterance under testassert pipe._spoken == [], pipe._spokenassert TurnTakingState.JARVIS_SPEAKING not in pipe._state_historydiff --git a/tests/unit/speech/test_completeness.py b/tests/unit/speech/test_completeness.pyindex 251abaa42b..a1af89cdfd 100644--- a/tests/unit/speech/test_completeness.py+++ b/tests/unit/speech/test_completeness.py@@ -24,8 +24,8 @@ from jarvis.speech.completeness import (# ---------------------------------------------------------------------------COMPLETE_CASES = [# Clear imperatives (must not regress the local-action fast path)- "Öffne Chrome",- "Öffne mir den Browser",+ "Öffne Chrome", # i18n-allow: speech-recognition input vocabulary under test+ "Öffne mir den Browser", # i18n-allow: speech-recognition input vocabulary under test"Spiel Spotify ab","Mach notepad auf","Starte Firefox",@@ -39,13 +39,13 @@ COMPLETE_CASES = ["Nimm die rote","Gib mir den Bericht",# Preposition-tail collisions — complete questions ending in a preposition- "Was ist das für",+ "Was ist das für", # i18n-allow: speech-recognition input vocabulary under test"What is this for",# Normal questions / statements- "Wie spät ist es",+ "Wie spät ist es", # i18n-allow: speech-recognition input vocabulary under test"What time is it","Open the terminal",- "Schreib eine Mail an Tom dass ich später komme",+ "Schreib eine Mail an Tom dass ich später komme", # i18n-allow: speech-recognition input vocabulary under test# Historic false-positive that once froze the pipeline mute"Kannst du das fixen",# Bias: grammatically odd but ambiguous → execute@@ -64,7 +64,7 @@ def test_complete_utterances_classify_complete(text: str) -> None:@pytest.mark.parametrize("text",- ["Öffne Chrome.", "Wie spät ist es?", "Mach das jetzt!", "Open the terminal."],+ ["Öffne Chrome.", "Wie spät ist es?", "Mach das jetzt!", "Open the terminal."], # i18n-allow: speech-recognition input vocabulary under test)def test_terminal_punctuation_is_complete(text: str) -> None:assert classify_completeness(text).label is Completeness.COMPLETE@@ -74,7 +74,7 @@ def test_terminal_punctuation_is_complete(text: str) -> None:# INCOMPLETE — dangling fragments (trailing conjunction / article / subordinator)# ---------------------------------------------------------------------------INCOMPLETE_CASES = [- "Öffne mal eine", # indefinite article+ "Öffne mal eine", # indefinite article # i18n-allow: speech-recognition input vocabulary under test"Ich brauche einen", # indefinite article"Kauf Milch und", # conjunction"Ich glaube dass", # conjunction (subordinating)@@ -105,7 +105,7 @@ ABORT_CASES = ["vergiss das","ach, lass gut sein","schon gut",- "ne doch nicht",+ "ne doch nicht", # i18n-allow: speech-recognition input vocabulary under test"never mind","nevermind","forget it",@@ -128,7 +128,7 @@ def test_abort_phrases_classify_abrupt_abort(text: str) -> None:"nein", # bare "no" is a valid answer, not an abort"no","ich vergiss es nie", # contains "vergiss es" but is a full sentence- "mach das doch nicht so laut", # contains "doch nicht" mid-sentence+ "mach das doch nicht so laut", # contains "doch nicht" mid-sentence # i18n-allow: speech-recognition input vocabulary under test],)def test_abort_lookalikes_are_not_aborts(text: str) -> None:@@ -142,7 +142,7 @@ def test_cut_off_at_max_utterance_is_incomplete() -> None:"""A sentence chopped at the max-utterance cap with no terminalpunctuation is a cut-off the regex alone would miss."""verdict = classify_completeness(- "ich möchte dass du die Datei",+ "ich möchte dass du die Datei", # i18n-allow: speech-recognition input vocabulary under testendpoint_reason="max_utterance",)assert verdict.label is Completeness.INCOMPLETE@@ -152,20 +152,20 @@ def test_cut_off_at_max_utterance_is_incomplete() -> None:def test_same_text_without_cut_off_signal_is_complete() -> None:"""Without the C-signal the same content-word-ending text defaults toCOMPLETE (demonstrates the bias and that C adds value)."""- verdict = classify_completeness("ich möchte dass du die Datei")+ verdict = classify_completeness("ich möchte dass du die Datei") # i18n-allow: speech-recognition input vocabulary under testassert verdict.label is Completeness.COMPLETEdef test_terminal_punctuation_overrides_cut_off_signal() -> None:verdict = classify_completeness(- "Öffne Chrome.",+ "Öffne Chrome.", # i18n-allow: speech-recognition input vocabulary under testendpoint_reason="max_utterance",)assert verdict.label is Completeness.COMPLETEdef test_normal_endpoint_reason_does_not_force_incomplete() -> None:- verdict = classify_completeness("Öffne Chrome", endpoint_reason="silence")+ verdict = classify_completeness("Öffne Chrome", endpoint_reason="silence") # i18n-allow: speech-recognition input vocabulary under testassert verdict.label is Completeness.COMPLETE@@ -183,7 +183,7 @@ def test_empty_is_incomplete(text: str) -> None:# Verdict shape & fail-open contract# ---------------------------------------------------------------------------def test_verdict_is_frozen_with_reason() -> None:- verdict = classify_completeness("Öffne Chrome")+ verdict = classify_completeness("Öffne Chrome") # i18n-allow: speech-recognition input vocabulary under testassert isinstance(verdict, CompletenessVerdict)assert isinstance(verdict.reason, str) and verdict.reasonwith pytest.raises((AttributeError, Exception)):@@ -202,17 +202,17 @@ def test_completeness_enum_is_string_backed() -> None:# surfaces must all classify COMPLETE so the fast path is never starved.# ---------------------------------------------------------------------------ROUTING_LITERALS_THAT_MUST_STAY_COMPLETE = [- "öffne chrome",+ "öffne chrome", # i18n-allow: speech-recognition input vocabulary under test"starte firefox","mach notepad auf",- "öffne zwei terminals",+ "öffne zwei terminals", # i18n-allow: speech-recognition input vocabulary under test"spiel spotify ab",- "wie spät ist es",+ "wie spät ist es", # i18n-allow: speech-recognition input vocabulary under test"wechsel auf gemini", # provider switch — must reach voice_command_gate"stopp", # task cancel — must reach voice_command_gate- "denk gründlich nach", # depth override+ "denk gründlich nach", # depth override # i18n-allow: speech-recognition input vocabulary under test"wo bist du", # orb reset- "klick auf den button", # visual target+ "klick auf den button", # visual target # i18n-allow: speech-recognition input vocabulary under test]diff --git a/tests/unit/speech/test_hangup.py b/tests/unit/speech/test_hangup.pyindex 26daaf75da..e39b2e4673 100644--- a/tests/unit/speech/test_hangup.py+++ b/tests/unit/speech/test_hangup.py@@ -26,13 +26,13 @@ from jarvis.speech.hangup import (# Whisper mis-hearings of "auflegen""let's get up","just get up",- "tschüss",+ "tschüss", # i18n-allow"tschuess","beenden",- "gespräch beenden",- "auf wiederhören",+ "gespräch beenden", # i18n-allow+ "auf wiederhören", # i18n-allow"auf wiedersehen",- "bis später",+ "bis später", # i18n-allow"gute nacht","jarvis aus","schluss jetzt",@@ -84,15 +84,15 @@ def test_hangup_re_matches_auflegen_mishearings(phrase: str) -> None:# so the INSTANT regex must NOT fire on them."vielen dank","danke jarvis",- "danke schön",+ "danke schön", # i18n-allow"thanks jarvis","das war's",# Normal speech must never match."wie geht es dir",- "erzähl mir was",+ "erzähl mir was", # i18n-allow"kannst du das nochmal machen",- "geh mal auf die seite",- "öffne die datei",+ "geh mal auf die seite", # i18n-allow+ "öffne die datei", # i18n-allow],)def test_hangup_re_ignores_ambiguous_and_normal_speech(phrase: str) -> None:@@ -100,14 +100,14 @@ def test_hangup_re_ignores_ambiguous_and_normal_speech(phrase: str) -> None:def test_contains_end_signal_detects_token() -> None:- assert contains_end_signal("Bis später, Ruben. [[END_CALL]]") is True- assert contains_end_signal("Bis später, Ruben.") is False+ assert contains_end_signal("Bis später, Ruben. [[END_CALL]]") is True # i18n-allow+ assert contains_end_signal("Bis später, Ruben.") is False # i18n-allowassert contains_end_signal("") is Falseassert contains_end_signal(None) is False # type: ignore[arg-type]def test_strip_end_signal_removes_token_and_trims() -> None:- assert strip_end_signal("Bis später, Ruben. [[END_CALL]]") == "Bis später, Ruben."+ assert strip_end_signal("Bis später, Ruben. [[END_CALL]]") == "Bis später, Ruben." # i18n-allowassert strip_end_signal("[[END_CALL]]") == ""assert strip_end_signal("Auf Wiedersehen.") == "Auf Wiedersehen."@@ -132,6 +132,6 @@ def test_is_legacy_farewell_matches_old_exact_phrases(phrase: str) -> None:def test_is_legacy_farewell_rejects_other_text() -> None:- assert is_legacy_farewell("auf wiedersehen ruben war mir ein vergnügen") is False+ assert is_legacy_farewell("auf wiedersehen ruben war mir ein vergnügen") is False # i18n-allowassert is_legacy_farewell("hallo ruben") is Falseassert is_legacy_farewell("") is Falsediff --git a/tests/unit/speech/test_idle_spawn_inflight.py b/tests/unit/speech/test_idle_spawn_inflight.pyindex b6e30c3962..5060fd0628 100644--- a/tests/unit/speech/test_idle_spawn_inflight.py+++ b/tests/unit/speech/test_idle_spawn_inflight.py@@ -2,7 +2,7 @@Live repro (jarvis_desktop.log, 2026-05-31 14:31:40 .. 14:32:13):- 14:31:40 user: "Kannst du fuer mich bitte eine HTML-Datei erstellen ..."+ 14:31:40 user: "Kannst du fuer mich bitte eine HTML-Datei erstellen ..." # i18n-allow14:31:51 Spawn-ACK suppressed -> _schedule_spawn_watchdog() armed14:32:13 Idle-Timeout -> lege auf. <-- session hung up14:32:20 ClaudeDirectWorker done (still running when the hangup fired)diff --git a/tests/unit/speech/test_jarvis_agent_readback.py b/tests/unit/speech/test_jarvis_agent_readback.pyindex 1b6814b6c3..b80c8a79f6 100644--- a/tests/unit/speech/test_jarvis_agent_readback.py+++ b/tests/unit/speech/test_jarvis_agent_readback.py@@ -91,14 +91,14 @@ async def test_subagent_announcement_punches_through_hangup() -> None:await bus.publish(AnnouncementRequested(- text="Deine Recherche ist fertig.",+ text="Deine Recherche ist fertig.", # i18n-allowlanguage="de",priority="normal",kind="subagent",))- assert tts.calls == [("Deine Recherche ist fertig.", "de-DE")]+ assert tts.calls == [("Deine Recherche ist fertig.", "de-DE")] # i18n-allowassert player.plays == 1@@ -207,7 +207,7 @@ async def test_preamble_does_not_animate_speaking() -> None:await bus.publish(AnnouncementRequested(- text="Einen Moment, ich schaue nach.", language="de", kind="preamble"+ text="Einen Moment, ich schaue nach.", language="de", kind="preamble" # i18n-allow))@@ -235,7 +235,7 @@ async def test_background_completed_arms_readback_grace() -> None:JarvisAgentBackgroundCompleted(success=True,utterance="recherchier mir fuenf themen",- summary="Fuenf Recherche-Themen liegen bereit.",+ summary="Fuenf Recherche-Themen liegen bereit.", # i18n-allowerror="",duration_s=12.3,)diff --git a/tests/unit/speech/test_live_transcription_merge.py b/tests/unit/speech/test_live_transcription_merge.pyindex 28d57491f0..238e0ce303 100644--- a/tests/unit/speech/test_live_transcription_merge.py+++ b/tests/unit/speech/test_live_transcription_merge.py@@ -23,12 +23,12 @@ def test_merge_partial_transcript_replaces_corrected_live_hypotheses() -> None:for partial in ("Was?","Was ist morgens?",- "Was ist morgen fuer ein Tag?",- "Morgen fuer einen Tag.",+ "Was ist morgen fuer ein Tag?", # i18n-allow+ "Morgen fuer einen Tag.", # i18n-allow):text = _merge_partial_transcript(text, partial)- assert text == "Was ist morgen fuer ein Tag?"+ assert text == "Was ist morgen fuer ein Tag?" # i18n-allowasync def test_stt_probe_publishes_partial_transcription_update() -> None:@@ -68,7 +68,7 @@ async def test_stt_probe_publishes_partial_transcription_update() -> None:"hallucination",["Untertitelung des ZDF, 2020",- "Untertitelung des ZDF fuer funk, 2017",+ "Untertitelung des ZDF fuer funk, 2017", # i18n-allow],)async def test_stt_probe_suppresses_subtitle_hallucination_partials(@@ -121,7 +121,7 @@ async def test_stt_probe_suppresses_broadcast_boilerplate_partial() -> None:class _STT:async def transcribe_pcm(self, _pcm: bytes) -> Transcript:return Transcript(- text="Eine Sendung des NDR, 2020",+ text="Eine Sendung des NDR, 2020", # i18n-allowlanguage="de",confidence=0.88,)diff --git a/tests/unit/speech/test_pending_prompt_buffer.py b/tests/unit/speech/test_pending_prompt_buffer.pyindex 4776ab9362..3b0357d073 100644--- a/tests/unit/speech/test_pending_prompt_buffer.py+++ b/tests/unit/speech/test_pending_prompt_buffer.py@@ -43,8 +43,8 @@ def test_start_sets_fragment_and_initial_chain_count() -> None:def test_extend_concatenates_with_single_space() -> None:buf = PendingPromptBuffer()buf.start("Erinnere mich daran, dass")- buf.extend("ich morgen Brötchen kaufe")- assert buf.fragment == "Erinnere mich daran, dass ich morgen Brötchen kaufe"+ buf.extend("ich morgen Brötchen kaufe") # i18n-allow+ assert buf.fragment == "Erinnere mich daran, dass ich morgen Brötchen kaufe" # i18n-allowassert buf.chain_count == 2diff --git a/tests/unit/speech/test_phrase_language.py b/tests/unit/speech/test_phrase_language.pyindex 42db5ffcf8..8295a6ea3d 100644--- a/tests/unit/speech/test_phrase_language.py+++ b/tests/unit/speech/test_phrase_language.py@@ -149,7 +149,7 @@ async def test_clarify_question_is_german_for_whisper_language_name() -> None:@pytest.mark.asyncioasync def test_action_done_ack_is_german_for_whisper_language_name() -> None:pipe = _make_pipe(executed_action=True)- await pipe._handle_silent_brain_turn("german", "öffne chrome")+ await pipe._handle_silent_brain_turn("german", "öffne chrome") # i18n-allowassert pipe._spoken == [(_ACTION_DONE_PHRASE["de"], "de")], pipe._spokendiff --git a/tests/unit/speech/test_pipeline_vision_privacy.py b/tests/unit/speech/test_pipeline_vision_privacy.pyindex 61464a6e81..4610e6b3e0 100644--- a/tests/unit/speech/test_pipeline_vision_privacy.py+++ b/tests/unit/speech/test_pipeline_vision_privacy.py@@ -1,8 +1,8 @@-"""Wave-2 B7: Vision-Privacy-Hooks in SpeechPipeline.+"""Wave-2 B7: Vision privacy hooks in SpeechPipeline.-Testet die extrahierten Helper-Methods (_vision_cfg, _match_privacy_phrase,-_maybe_toggle_vision_on_state) direkt auf einer Pipeline-Instanz via-`__new__`, ohne den vollen STT/TTS/Wake-Bootstrap zu durchlaufen.+Tests the extracted helper methods (_vision_cfg, _match_privacy_phrase,+_maybe_toggle_vision_on_state) directly on a pipeline instance via+`__new__`, without running the full STT/TTS/wake bootstrap."""from __future__ import annotations@@ -37,10 +37,10 @@ class _FakeProvider:def _make_pipeline(*, provider=None, vision_cfg=None) -> SpeechPipeline:- """Baut eine nackte Pipeline-Instanz ohne Bootstrap.+ """Builds a bare pipeline instance without bootstrap.- Nutzt `__new__` + manuelle Attribut-Injection — reicht fuer die Helper-- Method-Tests. Vermeidet STT/TTS/Wake-Init.+ Uses `__new__` + manual attribute injection — sufficient for the helper+ method tests. Avoids STT/TTS/wake init."""pipe = SpeechPipeline.__new__(SpeechPipeline)pipe._vision_provider = provider@@ -101,7 +101,7 @@ def test_pipeline_vision_hook_noop_when_pause_on_idle_false():def test_pipeline_vision_hook_noop_when_no_provider():pipe = _make_pipeline(provider=None, vision_cfg=_default_vision_cfg())- # Darf nicht crashen+ # Must not crashpipe._maybe_toggle_vision_on_state("IDLE")pipe._maybe_toggle_vision_on_state("LISTENING")@@ -125,7 +125,7 @@ def test_voice_phrase_vision_back_on_returns_resume():def test_voice_phrase_non_match_returns_none():pipe = _make_pipeline(provider=_FakeProvider(), vision_cfg=_default_vision_cfg())- assert pipe._match_privacy_phrase("was ist das") is None+ assert pipe._match_privacy_phrase("was ist das") is None # i18n-allowassert pipe._match_privacy_phrase("hallo") is None@@ -140,10 +140,10 @@ def test_voice_phrase_match_returns_none_when_no_config():def test_pipeline_init_accepts_vision_kwargs():- """__init__-Signatur akzeptiert config + vision_provider ohne Fehler.+ """__init__ signature accepts config + vision_provider without error.- Wir instanziieren mit minimal-valid Komponenten; wenn die Kwargs fehlen- wuerden, waere das ein TypeError. Reiner Signatur-Smoke.+ We instantiate with minimal-valid components; if the kwargs were+ missing, that would be a TypeError. Pure signature smoke test."""import inspectsig = inspect.signature(SpeechPipeline.__init__)diff --git a/tests/unit/speech/test_post_interrupt_quiet_window.py b/tests/unit/speech/test_post_interrupt_quiet_window.pyindex 5d45a30c20..4fbcf8bcca 100644--- a/tests/unit/speech/test_post_interrupt_quiet_window.py+++ b/tests/unit/speech/test_post_interrupt_quiet_window.py@@ -7,7 +7,7 @@ on 2026-05-26:"Die Mission ist fehlgeschlagen, drei Versuche haben nicht gereicht.Dann schauen wir einfach mal in die letzte Transkription, was ich- gesagt habe."+ gesagt habe." # i18n-allowThe first sentence is the deterministic ``MissionFailed`` voice readbackemitted by ``MissionAnnouncer`` with ``priority="interrupt"`` (see@@ -122,7 +122,7 @@ async def test_preamble_within_quiet_window_after_interrupt_is_suppressed(await bus.publish(AnnouncementRequested(- text="Die Mission ist fehlgeschlagen. Drei Versuche haben nicht gereicht.",+ text="Die Mission ist fehlgeschlagen. Drei Versuche haben nicht gereicht.", # i18n-allowlanguage="de",priority="interrupt",)@@ -141,7 +141,7 @@ async def test_preamble_within_quiet_window_after_interrupt_is_suppressed(# Only the interrupt announcement spoke. The preamble was suppressed.assert tts.calls == [(- "Die Mission ist fehlgeschlagen. Drei Versuche haben nicht gereicht.",+ "Die Mission ist fehlgeschlagen. Drei Versuche haben nicht gereicht.", # i18n-allow"de-DE",)]@@ -189,7 +189,7 @@ async def test_completion_within_quiet_window_is_not_suppressed() -> None:"""Only ``kind == "preamble"`` is gated — completion readbacks pass through.- A completion (e.g. ``OpenClawBackgroundCompleted`` → "Fertig.") that+ A completion (e.g. ``OpenClawBackgroundCompleted`` → "Fertig.") that # i18n-allowlands inside the quiet window after a mission failure on anothertrack must still be voiced. Suppressing it would lose informationthe user actually needs.@@ -209,7 +209,7 @@ async def test_completion_within_quiet_window_is_not_suppressed(fake_clock.advance(0.2)await bus.publish(AnnouncementRequested(- text="Fertig. Anderes Ergebnis liegt bereit.",+ text="Fertig. Anderes Ergebnis liegt bereit.", # i18n-allowlanguage="de",priority="normal",kind="completion",@@ -218,7 +218,7 @@ async def test_completion_within_quiet_window_is_not_suppressed(assert tts.calls == [("Mission abgebrochen.", "de-DE"),- ("Fertig. Anderes Ergebnis liegt bereit.", "de-DE"),+ ("Fertig. Anderes Ergebnis liegt bereit.", "de-DE"), # i18n-allow]assert player.plays == 2@@ -240,14 +240,14 @@ async def test_interrupt_itself_is_always_spoken(await bus.publish(AnnouncementRequested(- text="Die Mission ist fehlgeschlagen. Grund: kritisch.",+ text="Die Mission ist fehlgeschlagen. Grund: kritisch.", # i18n-allowlanguage="de",priority="interrupt",))assert tts.calls == [- ("Die Mission ist fehlgeschlagen. Grund: kritisch.", "de-DE"),+ ("Die Mission ist fehlgeschlagen. Grund: kritisch.", "de-DE"), # i18n-allow]assert player.plays == 1diff --git a/tests/unit/speech/test_rolling_whisper_wake.py b/tests/unit/speech/test_rolling_whisper_wake.pyindex 87c743dc4a..57e650ab9e 100644--- a/tests/unit/speech/test_rolling_whisper_wake.py+++ b/tests/unit/speech/test_rolling_whisper_wake.py@@ -2,7 +2,7 @@Forensic 2026-06-22 (branch feat/fast-boot-bootstrap): a user who sets a customwake word ("Hey Ruben") falls onto the ``stt_match`` path = RollingWhisperWake.-Two live symptoms — "riesige Verzoegerung" + "manchmal gar nicht":+Two live symptoms — "huge delay" + "sometimes nothing at all":- LATENCY (this file): ``detect`` used to ``await transcribe_pcm`` *inside* thechunk-consume loop, so while a (CPU "base") transcription ran for ~0.5-1 s thediff --git a/tests/unit/speech/test_speak_playback_timeout.py b/tests/unit/speech/test_speak_playback_timeout.pyindex 391b63e736..bc77b9f25c 100644--- a/tests/unit/speech/test_speak_playback_timeout.py+++ b/tests/unit/speech/test_speak_playback_timeout.py@@ -264,7 +264,7 @@ async def test_no_first_frame_ceiling_abort_marks_beheaded_turn() -> None:async def test_no_first_frame_ceiling_deferred_while_desktop_tool_steps() -> None:"""An actively-stepping computer_use turn must not be beheaded pre-first-frame.- Live bug 2026-06-09 (data/jarvis_desktop.log 19:46, "öffne CapCut"): the+ Live bug 2026-06-09 (data/jarvis_desktop.log 19:46, "öffne CapCut"): the # i18n-allowrouter brain ran an inline ``computer_use`` loop. The loop was working onstep 4 (heartbeats flowing via ObservationCaptured/ActionPlanned →``_on_agent_progress``) when the no-first-frame ceiling fired at 20 s,@@ -746,7 +746,7 @@ async def test_thinking_heartbeat_survives_tool_round_until_first_spoken_token()round) for as long as NO speakable sentence has reached TTS — only a realspoken token (``_spoke_this_turn``) may freeze it.- Live bug 2026-06-30 ("München nach Bora Bora"): the brain ran a tool round+ Live bug 2026-06-30 ("München nach Bora Bora"): the brain ran a tool round # i18n-allow~10 s in, then worked a second model roundtrip ~20 s with no furtherprogress ping and no token. The heartbeat froze at the FIRST progress, sothe 20 s no-first-frame TTS ceiling beheaded the still-working turn 10 sdiff --git a/tests/unit/speech/test_stt_language_autodetect.py b/tests/unit/speech/test_stt_language_autodetect.pyindex 8019c15320..e2ac9225db 100644--- a/tests/unit/speech/test_stt_language_autodetect.py+++ b/tests/unit/speech/test_stt_language_autodetect.py@@ -5,7 +5,7 @@ Live forensic 2026-06-14 14:24 (data/jarvis_desktop.log): withEVERY utterance as German. Clear English usually survived, but marginal/shortEnglish audio was mangled into German tokens — e.g. the English "Hello, what'sthe weather like in Melbourne?" came out as-``'Hallo, was ist der West-Like in Melbourne?'`` (confidence 0.654), and+``'Hallo, was ist der West-Like in Melbourne?'`` (confidence 0.654), and # i18n-allow"Is it currently winter in Melbourne?" became ``'Ist es gerade Winter inMelbourne?'``. The text itself was corrupted at the STT layer, so thedownstream ``resolve_turn_language`` (which trusts the transcribed text) had nodiff --git a/tests/unit/speech/test_turn_buffer.py b/tests/unit/speech/test_turn_buffer.pyindex b6c9547be7..6c21a72916 100644--- a/tests/unit/speech/test_turn_buffer.py+++ b/tests/unit/speech/test_turn_buffer.py@@ -1,9 +1,9 @@-"""Unit-Tests fuer TurnBuffer.+"""Unit tests for TurnBuffer.-Regression-Test fuer BUG-001 (2026-04-23): der Stub-TurnBuffer akzeptierte keine-Kwargs, die Pipeline ruft aber ``append(text=..., language=..., confidence=...)``-auf. Ergebnis: TypeError bei jedem User-Utterance, Session bricht nach "Sir?"-lautlos ab. Diese Tests stellen den API-Contract fest.+Regression test for BUG-001 (2026-04-23): the stub TurnBuffer did not accept+kwargs, but the pipeline calls ``append(text=..., language=..., confidence=...)``.+Result: TypeError on every user utterance, session silently aborts after "Sir?"+The tests here pin down the API contract."""from __future__ import annotations@@ -13,14 +13,14 @@ from jarvis.speech.turn_buffer import Turn, TurnBufferdef test_append_accepts_pipeline_kwargs() -> None:- """BUG-001 Regression: append muss text/language/confidence als Kwargs nehmen."""+ """BUG-001 regression: append must take text/language/confidence as kwargs."""buf = TurnBuffer(maxlen=5)buf.append(text="Hallo Jarvis", language="de", confidence=0.92)assert len(buf) == 1def test_append_confidence_optional() -> None:- """Nicht jeder STT-Provider liefert confidence — Default None muss reichen."""+ """Not every STT provider supplies confidence — a default of None must suffice."""buf = TurnBuffer()buf.append(text="Hello", language="en")last = buf.last()@@ -69,7 +69,7 @@ def test_maxlen_evicts_oldest() -> None:def test_turn_is_frozen() -> None:- """Turn ist immutable — kein versehentliches Mutieren eines Buffer-Eintrags."""+ """Turn is immutable — no accidental mutation of a buffer entry."""buf = TurnBuffer()buf.append(text="hallo", language="de")last = buf.last()diff --git a/tests/unit/speech/test_turn_taking.py b/tests/unit/speech/test_turn_taking.pyindex 7ae5b7b033..57e2a252c4 100644--- a/tests/unit/speech/test_turn_taking.py+++ b/tests/unit/speech/test_turn_taking.py@@ -219,14 +219,14 @@ async def test_single_turn_mode_ends_session_after_response() -> None:# background conversation without a wake word.pipe = _make_pipeline(FakeSTT(text="Wie spaet ist es"),- brain_response="Es ist kurz nach drei.",+ brain_response="Es ist kurz nach drei.", # i18n-allowcontinue_listening_after_response=False,)keep_session = await pipe._handle_utterance(b"\x01\x00" * 1024)assert keep_session is False- assert pipe._spoken == [("Es ist kurz nach drei.", "de")]+ assert pipe._spoken == [("Es ist kurz nach drei.", "de")] # i18n-allowassert pipe._turn_state == TurnTakingState.IDLEassert pipe._session_end_reason == "turn_complete"@@ -240,14 +240,14 @@ async def test_conversation_mode_keeps_session_listening_when_opted_in() -> None# then the only ways out -- same semantics as 2026-05-05 production.pipe = _make_pipeline(FakeSTT(text="Wie spaet ist es"),- brain_response="Es ist kurz nach drei.",+ brain_response="Es ist kurz nach drei.", # i18n-allowcontinue_listening_after_response=True,)keep_session = await pipe._handle_utterance(b"\x01\x00" * 1024)assert keep_session is True- assert pipe._spoken == [("Es ist kurz nach drei.", "de")]+ assert pipe._spoken == [("Es ist kurz nach drei.", "de")] # i18n-allowassert pipe._turn_state == TurnTakingState.LISTENINGassert pipe._session_end_reason is None@@ -256,7 +256,7 @@ async def test_conversation_mode_keeps_session_listening_when_opted_in() -> Noneasync def test_barge_in_keeps_session_listening() -> None:pipe = _make_pipeline(FakeSTT(text="Erklaer das"),- brain_response="Das ist eine laengere Antwort.",+ brain_response="Das ist eine laengere Antwort.", # i18n-allowspeak_barged=True,)@@ -270,7 +270,7 @@ async def test_barge_in_keeps_session_listening() -> None:@pytest.mark.asyncioasync def test_continuous_response_mode_can_keep_listening() -> None:pipe = _make_pipeline(- FakeSTT(text="Erzaehl weiter"),+ FakeSTT(text="Erzaehl weiter"), # i18n-allowbrain_response="Gerne.",continue_listening_after_response=True,)@@ -394,7 +394,7 @@ async def test_complete_question_with_kannst_du_reaches_brain() -> None:"""pipe = _make_pipeline(FakeSTT(text="Kannst du das fixen"),- brain_response="Ja, ich kümmere mich darum.",+ brain_response="Ja, ich kümmere mich darum.", # i18n-allowcontinue_listening_after_response=True,)@@ -403,7 +403,7 @@ async def test_complete_question_with_kannst_du_reaches_brain() -> None:assert keep_session is Trueassert pipe._pending_user_context == []assert pipe._spoken # brain produced a reply that was spoken- assert pipe._spoken[0][0] == "Ja, ich kümmere mich darum."+ assert pipe._spoken[0][0] == "Ja, ich kümmere mich darum." # i18n-allow@pytest.mark.asyncio@@ -414,7 +414,7 @@ async def test_brain_call_timeout_returns_to_listening_without_hanging() -> NoneWithout the asyncio.wait_for guard around `_brain_with_ack`, an upstreamstall (Gemini hang, OAuth refresh) leaves the pipeline forever inPROCESSING — exactly the user-reported "Jarvis stopped thinking" symptom.- Live bug 2026-05-29 ("Claude Code öffnen" stalled → silent hangup) extended+ Live bug 2026-05-29 ("Claude Code öffnen" stalled → silent hangup) extended # i18n-allowthe AD-OE6 zero-silent-drop contract to the timeout path: the turn nowreturns to LISTENING AND speaks a short "took too long" fallback (waspreviously silent — see test_total_brain_failure for the same contract).@@ -611,7 +611,7 @@ async def test_streaming_empty_non_suppressed_speaks_clarifying_question() -> No# The pipeline must now speak a short clarifying question instead of# dropping the user into silence (AD-OE6).pipe = _make_streaming_pipeline(- FakeSTT(text="Das sind fuer mich die naechsten Plaene"),+ FakeSTT(text="Das sind fuer mich die naechsten Plaene"), # i18n-allowstream_chunks=[],all_failed=False,suppressed=False,@@ -842,14 +842,14 @@ async def test_brain_end_call_sentinel_hangs_up_and_is_not_spoken() -> None:# command, so the brain decides — and signals end via the sentinel.pipe = _make_pipeline(FakeSTT(text="Ich glaube wir sind durch"),- brain_response="Bis später, Ruben. [[END_CALL]]",+ brain_response="Bis später, Ruben. [[END_CALL]]", # i18n-allowcontinue_listening_after_response=True, # prove hangup overrides stay-open)keep_session = await pipe._handle_utterance(b"\x01\x00" * 1024)assert keep_session is False- assert pipe._spoken == [("Bis später, Ruben.", "de")] # sentinel stripped+ assert pipe._spoken == [("Bis später, Ruben.", "de")] # sentinel stripped # i18n-allowassert pipe._session_end_reason == "voice_pattern"assert pipe._hangup_event.is_set()@@ -888,7 +888,7 @@ async def test_explicit_auflegen_still_hard_hangs_up_via_regex() -> None:async def test_brain_streaming_strips_sentinel_but_keeps_it_in_full_text() -> None:pipe = _make_streaming_pipeline(FakeSTT(text="x"),- stream_chunks=["Alles erledigt. ", "Bis später, Ruben. ", "[[END_CALL]]"],+ stream_chunks=["Alles erledigt. ", "Bis später, Ruben. ", "[[END_CALL]]"], # i18n-allowall_failed=False,)@@ -900,7 +900,7 @@ async def test_brain_streaming_strips_sentinel_but_keeps_it_in_full_text() -> No# spoken text is captured on pipe._synthesized, NOT on _spoken.assert "[[END_CALL]]" in fullassert all("[[END_CALL]]" not in t for t in pipe._synthesized) # never spoken- assert any("Bis später" in t for t in pipe._synthesized)+ assert any("Bis später" in t for t in pipe._synthesized) # i18n-allow@pytest.mark.asyncio@@ -908,7 +908,7 @@ async def test_brain_timeout_speaks_fallback_instead_of_silent_hangup() -> None:"""AD-OE6: when the brain stalls past brain_timeout_s, the turn must SPEAK agraceful fallback, not drop back to LISTENING in silence.- Live bug 2026-05-29: "kannst du Claude Code öffnen" stalled the Gemini+ Live bug 2026-05-29: "kannst du Claude Code öffnen" stalled the Gemini # i18n-allowstream; idle_timeout (30s) pre-empted brain_timeout (40s) and the turn hungup with zero feedback. The fix lowers brain_timeout below idle_timeout ANDspeaks on timeout — this pins the spoken-fallback half.diff --git a/tests/unit/speech/test_wake_phrase.py b/tests/unit/speech/test_wake_phrase.pyindex 44f01aae4f..cbff10f558 100644--- a/tests/unit/speech/test_wake_phrase.py+++ b/tests/unit/speech/test_wake_phrase.py@@ -136,7 +136,7 @@ def test_hey_nico_fires_on_partial_and_drifted_windows() -> None:assert m.search("nico") is not None # prefix split — name-only windowassert m.search("ja nico komm") is not None # name mid-utteranceassert m.search("niko") is not None # STT drift (one char)- assert m.search("wie spät ist es") is None # unrelated -> no wake+ assert m.search("wie spät ist es") is None # unrelated -> no wake # i18n-allowdef test_multi_word_core_phrase_matches_in_order() -> None:diff --git a/tests/unit/speech/test_wake_prefix_gating.py b/tests/unit/speech/test_wake_prefix_gating.pyindex 289541ba6c..d2e510e788 100644--- a/tests/unit/speech/test_wake_prefix_gating.py+++ b/tests/unit/speech/test_wake_prefix_gating.py@@ -82,7 +82,7 @@ async def test_gate_passes_when_no_utterance_stt_configured() -> None:async def test_gate_passes_on_hey_jarvis_transcript() -> None:- stt = _FakeSTT("Hey Jarvis, was läuft heute")+ stt = _FakeSTT("Hey Jarvis, was läuft heute") # i18n-allowpipe = _bare_pipeline(require_hey_prefix=True, utterance_stt=stt)assert await pipe._verify_oww_hit(PCM_2S_16K) is True@@ -127,7 +127,7 @@ async def test_gate_still_rejects_genuine_other_speech() -> None:"""The hallucination degrade-open must NOT accept arbitrary non-wake speech:genuine other words (no "hey + jarv", not a known hallucination) are stillsuppressed, so the bare-"Jarvis" false-positive guard (BUG-009) stays."""- stt = _FakeSTT("wie spät ist es")+ stt = _FakeSTT("wie spät ist es") # i18n-allowpipe = _bare_pipeline(require_hey_prefix=True, utterance_stt=stt)assert await pipe._verify_oww_hit(PCM_2S_16K) is Falsediff --git a/tests/unit/speech/test_wake_verifier.py b/tests/unit/speech/test_wake_verifier.pyindex 9b9e506e07..d13541fb43 100644--- a/tests/unit/speech/test_wake_verifier.py+++ b/tests/unit/speech/test_wake_verifier.py@@ -110,12 +110,12 @@ PCM_2S_16K = b"\x00\x00" * 16_000 * 2 # 2 s int16 silenceasync def test_verify_returns_true_when_transcript_has_hey_prefix() -> None:- stt = _FakeSTT("Hey Jarvis, was läuft")+ stt = _FakeSTT("Hey Jarvis, was läuft") # i18n-allowmatched, transcript = await verify_wake_with_stt(stt, PCM_2S_16K)assert matched is True- assert transcript == "Hey Jarvis, was läuft"+ assert transcript == "Hey Jarvis, was läuft" # i18n-allowassert stt.calls == [(len(PCM_2S_16K), 16_000, "de")]@@ -184,12 +184,12 @@ async def test_verify_retries_transient_error_then_succeeds(monkeypatch) -> Noneimport jarvis.speech.wake_verifier as wvmonkeypatch.setattr(wv, "_WAKE_VERIFY_BACKOFF_S", 0.0, raising=False)- stt = _FlakySTT("Hey Jarvis, was läuft", fail_times=1)+ stt = _FlakySTT("Hey Jarvis, was läuft", fail_times=1) # i18n-allowmatched, transcript = await verify_wake_with_stt(stt, PCM_2S_16K)assert matched is True- assert transcript == "Hey Jarvis, was läuft"+ assert transcript == "Hey Jarvis, was läuft" # i18n-allowassert stt.calls == 2 # one failure, one successful retrydiff --git a/tests/unit/speech/test_warmup_two_phase.py b/tests/unit/speech/test_warmup_two_phase.pyindex 041ed0d42d..07f05da5e4 100644--- a/tests/unit/speech/test_warmup_two_phase.py+++ b/tests/unit/speech/test_warmup_two_phase.py@@ -307,7 +307,7 @@ async def test_ready_cue_does_not_block_wake_loop_start(monkeypatch) -> None:"""The ready chime must not sit between ready=True and the wake loop.Live logs showed Phase A completing quickly, then ``_play_ready_cue`` holding- ``_warmup()`` for several seconds before ``Pipeline bereit`` and the wake+ ``_warmup()`` for several seconds before ``Pipeline ready`` and the wakelistener started. A wedged/slow output device must not keep the wake worddead after the critical listening path is ready."""diff --git a/tests/unit/tasks/test_runner.py b/tests/unit/tasks/test_runner.pyindex 067c1d42a1..df7ba489bb 100644--- a/tests/unit/tasks/test_runner.py+++ b/tests/unit/tasks/test_runner.py@@ -1,4 +1,4 @@-"""Unit-Tests fuer TaskRunner — SpeakAction, ToolCallAction, HarnessDispatch."""+"""Unit tests for TaskRunner — SpeakAction, ToolCallAction, HarnessDispatch."""from __future__ import annotationsfrom pathlib import Path@@ -266,7 +266,7 @@ async def test_runner_respects_cancel_token(store: TaskStore, bus: EventBus) ->await runner.run(tid, cancel_token=token)- # TTS wurde nicht aufgerufen+ # TTS was not calledassert tts.calls == []task = await store.get(tid)assert task is not Nonediff --git a/tests/unit/tasks/test_runner_whenthen.py b/tests/unit/tasks/test_runner_whenthen.pyindex 85c060cbc7..9d4274286f 100644--- a/tests/unit/tasks/test_runner_whenthen.py+++ b/tests/unit/tasks/test_runner_whenthen.py@@ -69,7 +69,7 @@ def _mission_event(**over: Any) -> dict[str, Any]:base = {"mission_id": "m1","status": "approved",- "summary_de": "Fertig.",+ "summary_de": "Fertig.", # i18n-allow"summary_en": "Done.","result_uri": "/out/result.md","reason": "",diff --git a/tests/unit/tasks/test_scheduler.py b/tests/unit/tasks/test_scheduler.pyindex 2223b4d75b..84cb852f85 100644--- a/tests/unit/tasks/test_scheduler.py+++ b/tests/unit/tasks/test_scheduler.py@@ -1,4 +1,4 @@-"""Unit-Tests fuer TaskScheduler — heap, event-dispatch, cancel."""+"""Unit tests for TaskScheduler — heap, event dispatch, cancel."""from __future__ import annotationsimport asyncio@@ -153,7 +153,7 @@ async def test_on_event_filter_expr_blocks_non_match()await scheduler.schedule(spec)- # assistant-Message → sollte NICHT dispatched werden+ # assistant message → should NOT be dispatchedawait bus.publish(MessageSent(thread_id="t1", role="assistant", text="hi"))assert runner.dispatched == []@@ -184,7 +184,7 @@ async def test_cancel_before_fire_prevents_run(ok = await scheduler.cancel_task(tid)assert ok is True- # Kurz warten, sollte NICHT gedispatcht werden+ # Wait briefly, should NOT be dispatchedawait asyncio.sleep(0.2)assert runner.dispatched == []@@ -204,7 +204,7 @@ async def test_hydrate_restores_scheduled_tasks(tmp_path: Path, bus: EventBus, runner: FakeRunner) -> None:db = tmp_path / "hydrate.db"- # Vorbereitung: Store mit einem geschedulten Task+ # Setup: store with one scheduled taskstore1 = TaskStore(db)await store1.init()spec = TaskSpec(@@ -249,10 +249,10 @@ def test_filter_expr_rejects_dangerous_input() -> None:assert _match_filter(evt, None) is Trueassert _match_filter(evt, "") is True- # Function-Calls sind nicht erlaubt+ # Function calls are not allowedassert _match_filter(evt, "__import__('os').system('dir')") is False- # Attribute-Access ist nicht erlaubt+ # Attribute access is not allowedassert _match_filter(evt, "role.upper() == 'USER'") is False# Einfache Vergleiche funktionierendiff --git a/tests/unit/tasks/test_store.py b/tests/unit/tasks/test_store.pyindex 216b3526d8..7a2754053f 100644--- a/tests/unit/tasks/test_store.py+++ b/tests/unit/tasks/test_store.py@@ -1,4 +1,4 @@-"""Unit-Tests fuer TaskStore — CRUD + Startup-Cleanup + append_step."""+"""Unit tests for TaskStore — CRUD + startup cleanup + append_step."""from __future__ import annotationsfrom pathlib import Path@@ -48,7 +48,7 @@ async def test_insert_on_event_stores_selector(store: TaskStore) -> None:spec = TaskSpec(title="Reagiere auf Mails",trigger=TriggerOnEvent(event_name="MessageSent", filter_expr="role == 'user'"),- action=SpeakAction(text="Neue Nachricht!"),+ action=SpeakAction(text="Neue Nachricht!"), # i18n-allow)tid = await store.insert(spec)task = await store.get(tid)diff --git a/tests/unit/telemetry/test_recorder.py b/tests/unit/telemetry/test_recorder.pyindex 4faf8dd713..a03ca08387 100644--- a/tests/unit/telemetry/test_recorder.py+++ b/tests/unit/telemetry/test_recorder.py@@ -1,4 +1,4 @@-"""Unit-Tests fuer FlightRecorder (ADR-0007)."""+"""Unit tests for FlightRecorder (ADR-0007)."""from __future__ import annotationsimport asyncio@@ -87,7 +87,7 @@ async def test_recorder_can_iterate_by_trace_id(tmp_path):@pytest.mark.asyncioasync def test_recorder_is_idempotent_on_attach(tmp_path):- """Zweifaches attach() auf denselben Bus darf nicht doppelt subscriben."""+ """Calling attach() twice on the same bus must not subscribe twice."""bus = EventBus()rec = FlightRecorder(tmp_path, flush_interval_s=0)rec.attach(bus)@@ -103,7 +103,7 @@ async def test_recorder_is_idempotent_on_attach(tmp_path):@pytest.mark.asyncioasync def test_recorder_externalizes_large_blobs(tmp_path):- """Bytes > blob_inline_limit_bytes landen in blobs/, nicht inline."""+ """Bytes > blob_inline_limit_bytes end up in blobs/, not inline."""from dataclasses import dataclassfrom jarvis.core.events import Event@@ -155,7 +155,7 @@ async def test_recorder_handles_day_rotation(tmp_path):@pytest.mark.asyncioasync def test_flush_interval_respected(tmp_path):- """Mit flush_interval_s > 0 wird nicht nach jedem Event geschrieben."""+ """With flush_interval_s > 0, it does not write after every event."""fake_now = [0]bus = EventBus()rec = FlightRecorder(tmp_path, flush_interval_s=1.0,@@ -163,18 +163,18 @@ async def test_flush_interval_respected(tmp_path):rec.attach(bus)tid = uuid4()- # Erstes Event → Buffer, noch kein Write+ # First event → buffer, no write yetawait bus.publish(KillRequested(trace_id=tid, source="a"))assert not list(tmp_path.glob("*.jsonl"))- # Zeit um 0.5s vorspulen → immer noch kein Flush+ # Advance time by 0.5s → still no flushfake_now[0] += 500_000_000await bus.publish(KillRequested(trace_id=tid, source="b"))- # Event wird zugestellt, aber Flush nur wenn intervall ueberschritten:+ # Event is delivered, but flush only once the interval is exceeded:await asyncio.sleep(0)- # Datei ggf. noch nicht da — Test abhaengig von Dispatch-Timing.+ # File may not exist yet — test depends on dispatch timing.- # Zeit um 2s vorspulen und noch ein Event+ # Advance time by 2s and publish one more eventfake_now[0] += 2_000_000_000await bus.publish(KillRequested(trace_id=tid, source="c"))await asyncio.sleep(0)diff --git a/tests/unit/telemetry/test_replay.py b/tests/unit/telemetry/test_replay.pyindex 32a0eedc34..872d082ba3 100644--- a/tests/unit/telemetry/test_replay.py+++ b/tests/unit/telemetry/test_replay.py@@ -1,4 +1,4 @@-"""Unit-Tests fuer die Replay-CLI."""+"""Unit tests for the replay CLI."""from __future__ import annotationsimport iodiff --git a/tests/unit/telephony/test_session.py b/tests/unit/telephony/test_session.pyindex 287e8c13bc..9ccd262c2b 100644--- a/tests/unit/telephony/test_session.py+++ b/tests/unit/telephony/test_session.py@@ -52,7 +52,7 @@ def _make_session(sink, *, stt=None, brain=None, tts=None, **kw) -> TelephonyCal"call_sid": "CA1","stream_sid": "MZ1","send": sink.send,- "stt": stt or FakeSTT(["Wie spät ist es?"]),+ "stt": stt or FakeSTT(["Wie spät ist es?"]), # i18n-allow"brain": brain or FakeBrain("Es ist vierzehn Uhr."),"tts": tts or FakeTTS(ms_per_char=2),"language_code": "de-DE",@@ -99,7 +99,7 @@ async def test_full_turn_produces_outbound_media_frames():async def test_greeting_is_spoken():sink = _Sink()- session = _make_session(sink, greeting="Willkommen bei Jarvis.")+ session = _make_session(sink, greeting="Willkommen bei Jarvis.") # i18n-allown = await session.speak_greeting()assert n > 0assert len(sink.media_frames) == n@@ -108,9 +108,9 @@ async def test_greeting_is_spoken():async def test_brain_receives_transcript():sink = _Sink()brain = FakeBrain("Antwort.")- session = _make_session(sink, stt=FakeSTT(["Was ist die Uhrzeit?"]), brain=brain)+ session = _make_session(sink, stt=FakeSTT(["Was ist die Uhrzeit?"]), brain=brain) # i18n-allowawait _drive_one_utterance(session)- assert brain.prompts == ["Was ist die Uhrzeit?"]+ assert brain.prompts == ["Was ist die Uhrzeit?"] # i18n-allowasync def test_hangup_phrase_ends_call_before_brain():@@ -126,13 +126,13 @@ async def test_hangup_phrase_ends_call_before_brain():@pytest.mark.parametrize("phrase",- ["auflegen", "leg auf", "tschüss", "hang up", "goodbye", "beenden"],+ ["auflegen", "leg auf", "tschüss", "hang up", "goodbye", "beenden"], # i18n-allow)def test_hangup_regex_matches_closing_phrases(phrase):assert HANGUP_RE.search(phrase)[email protected]("phrase", ["wie geht es dir", "erzähl mir was", "danke schön"])[email protected]("phrase", ["wie geht es dir", "erzähl mir was", "danke schön"]) # i18n-allowdef test_hangup_regex_ignores_normal_speech(phrase):assert HANGUP_RE.search(phrase) is Nonediff --git a/tests/unit/telephony/test_session_completeness.py b/tests/unit/telephony/test_session_completeness.pyindex cac470dc1d..c404433aca 100644--- a/tests/unit/telephony/test_session_completeness.py+++ b/tests/unit/telephony/test_session_completeness.py@@ -95,7 +95,7 @@ def _make_session(call_sid="CA-test",stream_sid="MZ-test",send=sink.send,- stt=FakeSTT(stt_texts or ["Wie spät ist es?"]),+ stt=FakeSTT(stt_texts or ["Wie spät ist es?"]), # i18n-allowbrain=brain,tts=tts_instance,language_code=language_code,@@ -140,9 +140,9 @@ async def test_complete_utterance_dispatches_to_brain():cfg = _FakeConfig()session, brain, tts, _sink = _make_session(config=cfg)- await _run_turn_direct(session, "Öffne Chrome")+ await _run_turn_direct(session, "Öffne Chrome") # i18n-allow- assert brain.prompts == ["Öffne Chrome"]+ assert brain.prompts == ["Öffne Chrome"] # i18n-allowasync def test_complete_utterance_with_nonempty_pending_dispatches_combined():@@ -243,14 +243,14 @@ async def test_two_turn_completion_brain_receives_combined_text():session, brain, tts, _sink = _make_session(config=cfg)# Turn 1: trailing subordinator → INCOMPLETE- await _run_turn_direct(session, "Öffne mal eine")+ await _run_turn_direct(session, "Öffne mal eine") # i18n-allowassert brain.prompts == []# Turn 2: completing content (no dangling token, no abort phrase)await _run_turn_direct(session, "Datei im Explorer")assert len(brain.prompts) == 1combined = brain.prompts[0]- assert "Öffne mal eine" in combined+ assert "Öffne mal eine" in combined # i18n-allowassert "Datei im Explorer" in combined@@ -368,10 +368,10 @@ async def test_classifier_exception_fails_open_to_brain():"jarvis.telephony.session.classify_completeness",side_effect=RuntimeError("boom"),):- await _run_turn_direct(session, "Öffne Chrome")+ await _run_turn_direct(session, "Öffne Chrome") # i18n-allow# Fail-open: brain must have been called- assert brain.prompts == ["Öffne Chrome"]+ assert brain.prompts == ["Öffne Chrome"] # i18n-allow# ---------------------------------------------------------------------------@@ -476,8 +476,8 @@ async def test_no_config_attribute_uses_defaults():del session._config# COMPLETE utterance should still dispatch- await _run_turn_direct(session, "Öffne Chrome")- assert brain.prompts == ["Öffne Chrome"]+ await _run_turn_direct(session, "Öffne Chrome") # i18n-allow+ assert brain.prompts == ["Öffne Chrome"] # i18n-allowasync def test_no_config_attribute_incomplete_still_gates():diff --git a/tests/unit/test_api_key_error_handling.py b/tests/unit/test_api_key_error_handling.pyindex 1c4c14b9a2..78028ad11c 100644--- a/tests/unit/test_api_key_error_handling.py+++ b/tests/unit/test_api_key_error_handling.py@@ -1,4 +1,4 @@-"""Tests fuer Bug API-1 (2026-04-29): API-Key/Account-Fehler-Behandlung.+"""Tests for bug API-1 (2026-04-29): API key / account error handling.Drei zusammenhaengende Defekte gefixt:@@ -7,8 +7,8 @@ Drei zusammenhaengende Defekte gefixt:google-genai SDK 11 Pydantic-Validation-Errors.2. _is_account_blocked_exc() — Anthropic credit-too-low / xAI no-team-access /- OpenAI tier-not-available werden als terminales Account-Problem erkannt- (nicht als rate_limit oder invalid_model).+ OpenAI tier-not-available are recognized as a terminal account problem+ (not as rate_limit or invalid_model).3. _format_provider_chain_error — User-actionable Account-Block-Messagestatt "Provider unerreichbar"-Halluzination.@@ -90,8 +90,8 @@ class TestGeminiSchemaSanitize:assert "strict" not in out["items"]def test_tools_gemini_format_does_not_raise_with_self_mod_schema(self) -> None:- """Self-Mod-Tools (Phase 7.3) haben strict + input_examples — vor dem- Fix crashte gemini-Plugin mit `extra_forbidden`. Jetzt: clean."""+ """Self-mod tools (Phase 7.3) have strict + input_examples — before the+ fix, the gemini plugin crashed with `extra_forbidden`. Now: clean."""tools = ({"name": "set_config_value",@@ -356,7 +356,7 @@ class TestAccountBlocked:"found', 'error': 'The model grok-4.1-fast does not exist or ""your team does not have access to it.'}")assert _is_account_blocked_exc(msg)- # Wird account_blocked, nicht invalid_model — wichtig fuer User-Message.+ # Becomes account_blocked, not invalid_model — important for the user message.assert _classify_provider_error(msg, default="call_fail") == "account_blocked"def test_openai_tier_not_available(self) -> None:@@ -364,13 +364,13 @@ class TestAccountBlocked:assert _is_account_blocked_exc(msg)def test_invalid_model_does_not_match_account(self) -> None:- # Echte invalid_model-Fehler ohne Account-Hint bleiben "invalid_model".+ # Genuine invalid_model errors without an account hint stay "invalid_model".msg = "model_not_found: gpt-foo"assert not _is_account_blocked_exc(msg)assert _is_invalid_model_exc(msg)def test_missing_key_does_not_match_account(self) -> None:- msg = "Kein OpenAI-API-Key gefunden (openai_api_key / OPENAI_API_KEY)."+ msg = "Kein OpenAI-API-Key gefunden (openai_api_key / OPENAI_API_KEY)." # i18n-allowassert _is_missing_key_exc(msg)assert not _is_account_blocked_exc(msg)@@ -396,7 +396,7 @@ class TestChainErrorFormat:msg = _format_provider_chain_error(errors)assert "claude-api" in msgassert "grok" in msg- # Konkrete URL-Hinweise damit User klicken kann+ # Concrete URL hints so the user can click throughassert "anthropic" in msg.lower()assert "x.ai" in msg.lower() or "console" in msg.lower()@@ -406,6 +406,6 @@ class TestChainErrorFormat:("claude-api", "haiku", "account_blocked", "credit"),]msg = _format_provider_chain_error(errors)- # Beide Bereiche werden adressiert+ # Both areas are addressedassert "Brain-Key" in msg or "missing" in msg.lower()assert "Account-Problem" in msgdiff --git a/tests/unit/test_brain_cost.py b/tests/unit/test_brain_cost.pyindex 11ae3322e1..fab6ea1015 100644--- a/tests/unit/test_brain_cost.py+++ b/tests/unit/test_brain_cost.py@@ -1,4 +1,4 @@-"""Tests fuer jarvis.brain.cost — Pricing-Tabelle + calculate_cost_usd."""+"""Tests for jarvis.brain.cost — pricing table + calculate_cost_usd."""from __future__ import annotationsimport pytest@@ -57,9 +57,9 @@ class TestCalculateCostUsd:class TestPricingTable:def test_table_has_canonical_models(self) -> None:- # Smoke: die Modelle die der Sub-Jarvis-Tier in TIER_DEFAULTS_BY_PROVIDER- # auflistet, muessen alle in der Pricing-Tabelle sein — sonst werden- # Sub-Jarvis-Calls "kostenlos" statistiert.+ # Smoke: the models the worker tier lists in TIER_DEFAULTS_BY_PROVIDER+ # must all be in the pricing table — otherwise+ # worker calls get tallied as "free".expected_models = ["claude-opus-4-7-20251022","gemini-2.5-pro",@@ -69,25 +69,25 @@ class TestPricingTable:"anthropic/claude-opus-4.7",]for m in expected_models:- assert m in PRICING_USD_PER_MTOK, f"Pricing fehlt fuer {m}"+ assert m in PRICING_USD_PER_MTOK, f"Pricing missing for {m}"def test_table_has_router_models(self) -> None:- # Router-Tier — kostenrelevant fuer Cost-Reporting.+ # Router tier — cost-relevant for cost reporting.expected_models = ["claude-haiku-4-5-20251001","gemini-2.5-flash","gpt-4o-mini",]for m in expected_models:- assert m in PRICING_USD_PER_MTOK, f"Pricing fehlt fuer {m}"+ assert m in PRICING_USD_PER_MTOK, f"Pricing missing for {m}"def test_pricing_tuple_shape(self) -> None:for model, rates in PRICING_USD_PER_MTOK.items():- assert isinstance(rates, tuple), f"{model}: rates ist kein Tuple"+ assert isinstance(rates, tuple), f"{model}: rates is not a tuple"assert len(rates) == 2, f"{model}: erwartet (in, out)"in_rate, out_rate = ratesassert in_rate >= 0.0, f"{model}: input-rate negativ"assert out_rate >= 0.0, f"{model}: output-rate negativ"- # Output sollte typischerweise teurer sein als Input- # (oder gleich, bei Flat-Pricing). Wir warnen nicht, nur sanity.+ # Output is typically expected to be pricier than input+ # (or equal, for flat pricing). We don't warn, just a sanity check.assert out_rate >= in_rate * 0.5, f"{model}: output-rate verdaechtig niedrig"diff --git a/tests/unit/test_brain_cost_hook.py b/tests/unit/test_brain_cost_hook.pyindex 264f318409..6eafcfd892 100644--- a/tests/unit/test_brain_cost_hook.py+++ b/tests/unit/test_brain_cost_hook.py@@ -1,7 +1,7 @@-"""Regression-Tests fuer H13: CostMeter-Hook im BrainManager.+"""Regression tests for H13: CostMeter hook in BrainManager.-Deckt die Pre-Call-Gate-Pfade (Cooldown, Task-Budget, Tages-Budget)-und die Post-Call-Usage-Fuetterung.+Covers the pre-call gate paths (cooldown, task budget, daily budget)+and the post-call usage feed."""from __future__ import annotations@@ -14,9 +14,9 @@ import pytestfrom jarvis.control.cost import BudgetConfig, CostMeter, ModelPrice# ----------------------------------------------------------------------# Minimal-Harness: Real-BrainManager zu initialisieren ist teuer.-# Wir stubben die Dispatch-Grenze, indem wir direkt den Cost-Hook-Flow-# als Funktion ausfahren wie es generate() tut.+# Minimal harness: initializing a real BrainManager is expensive.+# We stub the dispatch boundary by running the cost-hook flow directly+# as a function, the way generate() does.# ---------------------------------------------------------------------@dataclass@@ -85,7 +85,7 @@ def test_meter_accumulates_on_dispatch(tmp_path):))# 1.0 USD × eur_per_usd=1.0 = 1.0 EUR == per_task_eurassert meter.total_for(tid) == pytest.approx(1.0)- assert not meter.over_task_budget(tid) # nicht > 1.0+ assert not meter.over_task_budget(tid) # not > 1.0meter.add(CostRecord(trace_id=tid, provider="test", model="test",tokens_in=1, tokens_out=1, tokens_cache_hit=0,@@ -95,8 +95,8 @@ def test_meter_accumulates_on_dispatch(tmp_path):def test_cooldown_blocks_new_requests(tmp_path):- """Nach Tages-Overrun setzt der Meter Cooldown — der Pre-Gate muss- das erkennen und Brain-Dispatch uebergehen.+ """After a daily overrun, the meter sets a cooldown — the pre-gate must+ detect that and skip the brain dispatch."""meter = _make_meter(tmp_path, per_day_eur=0.5, cooldown_minutes=60)meter.start_cooldown("test")diff --git a/tests/unit/test_brain_healthcheck.py b/tests/unit/test_brain_healthcheck.pyindex 8e3af39d53..22cc245dc7 100644--- a/tests/unit/test_brain_healthcheck.py+++ b/tests/unit/test_brain_healthcheck.py@@ -1,8 +1,8 @@-"""Unit-Tests fuer BrainHealthChecker (Phase 5, CL-4).+"""Unit tests for BrainHealthChecker (Phase 5, CL-4).-Statt der echten `BrainProviderRegistry` (entry_points-Discovery) wird hier-ein In-Memory-Stub mit derselben API genutzt: `instantiate(name, **kwargs)`.-Das ist der einzige Registry-Call, den der HealthChecker macht.+Instead of the real `BrainProviderRegistry` (entry_points discovery), this uses+an in-memory stub with the same API: `instantiate(name, **kwargs)`.+That is the only registry call the HealthChecker makes."""from __future__ import annotations@@ -196,5 +196,5 @@ async def test_probe_tier_without_fallbacks_returns_single() -> None:def test_brain_config_error_is_exception() -> None:- """Smoke-Test: BrainConfigError ist importierbar und eine Exception."""+ """Smoke test: BrainConfigError is importable and is an Exception."""assert issubclass(BrainConfigError, Exception)diff --git a/tests/unit/test_brain_pre_boot_key_check.py b/tests/unit/test_brain_pre_boot_key_check.pyindex 9c8974ea7b..2fb4b9c443 100644--- a/tests/unit/test_brain_pre_boot_key_check.py+++ b/tests/unit/test_brain_pre_boot_key_check.py@@ -1,14 +1,14 @@-"""Bug-E-Tests (2026-04-29): Pre-Boot-Key-Check filtert Provider ohne Key.+"""Bug-E tests (2026-04-29): pre-boot key check filters providers without a key.-Hintergrund: Vorher konnten Provider ohne API-Key in der Fallback-Chain-landen, mit BrainTurnStarted publishen, dann beim _ensure_client crashen-und einen Halluzinations-Tag in voice_turns hinterlassen-("openai/gpt-4o" obwohl kein OpenAI-Key existiert).+Background: previously, providers without an API key could land in the fallback+chain, publish BrainTurnStarted, then crash at _ensure_client and+leave a hallucination tag in voice_turns+("openai/gpt-4o" even though no OpenAI key exists).-Jetzt: BrainManager.from_tier_config() macht einen Pre-Boot-Healthcheck-ueber alle bekannten Provider und schiebt fehlende Keys direkt in-_dead_providers — kein BrainTurnStarted-Event mehr fuer Halluzinations--Provider.+Now: BrainManager.from_tier_config() runs a pre-boot healthcheck+across all known providers and pushes missing keys straight into+_dead_providers — no more BrainTurnStarted event for hallucination-+prone providers."""from __future__ import annotations@@ -63,8 +63,8 @@ def _make_cfg() -> JarvisConfig:def test_provider_without_key_lands_in_dead_providers(monkeypatch: pytest.MonkeyPatch,) -> None:- """Wenn nur claude-api+gemini Keys haben, sind openai+grok+openrouter- in _dead_providers nach from_tier_config().+ """When only claude-api+gemini have keys, openai+grok+openrouter are+ in _dead_providers after from_tier_config()."""from jarvis.core import config as _cfg_mod@@ -88,7 +88,7 @@ def test_provider_without_key_lands_in_dead_providers(def test_all_keys_missing_kills_all_providers(monkeypatch: pytest.MonkeyPatch,) -> None:- """Worst-Case: kein einziger Key. Alle Provider sind dead."""+ """Worst case: not a single key. All providers are dead."""from jarvis.core import config as _cfg_modmonkeypatch.setattr(diff --git a/tests/unit/test_brain_switch_persist_outcome.py b/tests/unit/test_brain_switch_persist_outcome.pyindex 2ae2fd6749..ca266c8937 100644--- a/tests/unit/test_brain_switch_persist_outcome.py+++ b/tests/unit/test_brain_switch_persist_outcome.py@@ -6,7 +6,7 @@ must surface as ``"persisted": false`` so the UI knows the choice will notsurvive a restart — never a silent success.These tests use a FakeBrainManager and monkeypatch ``config_writer`` so they-never touch the live jarvis.toml, config-soll.json, or registry.+never touch the live jarvis.toml, config-soll.json, or registry. # i18n-allow"""from __future__ import annotationsdiff --git a/tests/unit/test_brain_turn_events.py b/tests/unit/test_brain_turn_events.pyindex 0c70f39efd..bd2bef3829 100644--- a/tests/unit/test_brain_turn_events.py+++ b/tests/unit/test_brain_turn_events.py@@ -1,14 +1,14 @@-"""Bug-C-Tests (2026-04-29): BrainTurnCompleted enthaelt provider/model.+"""Bug-C tests (2026-04-29): BrainTurnCompleted now carries provider/model.-Hintergrund: Vorher schrieb der SessionRecorder provider/model aus-BrainTurnStarted in voice_turns. Bei Fallback-Chain (5 Provider-Versuche-hintereinander) gewann der LETZTE Started-Event — auch wenn der Call-crashte. Resultat: voice_turns hatte Halluzinations-Tags wie-"openai/gpt-4o" obwohl kein OpenAI-Key existierte.+Background: previously the SessionRecorder wrote provider/model from+BrainTurnStarted into voice_turns. In a fallback chain (5 consecutive+provider attempts), the LAST Started event won — even if that call+crashed. Result: voice_turns ended up with hallucinated tags like+"openai/gpt-4o" even though no OpenAI key existed.-Fix: BrainTurnCompleted hat jetzt provider/model. Recorder zieht von dort.-Manager.generate publisht beide Events nur wenn der Stream wirklich Daten-lieferte.+Fix: BrainTurnCompleted now carries provider/model. The recorder reads+from there. Manager.generate only publishes both events when the stream+actually delivered data."""from __future__ import annotations@@ -30,14 +30,14 @@ def test_brain_turn_completed_has_provider_field() -> None:def test_brain_turn_completed_provider_optional() -> None:- """Backwards-Compat: alte Caller ohne provider/model funktionieren weiter."""+ """Backwards-compat: old callers without provider/model keep working."""e = BrainTurnCompleted(tokens_in=100, tokens_out=20)assert e.provider == ""assert e.model == ""def test_brain_turn_started_unchanged() -> None:- """Schema von BrainTurnStarted bleibt rueckwaerts-kompatibel."""+ """Schema of BrainTurnStarted stays backwards-compatible."""e = BrainTurnStarted(provider="gemini",model="gemini-3-flash",diff --git a/tests/unit/test_cache_heartbeat.py b/tests/unit/test_cache_heartbeat.pyindex 60461c54bd..1223922d71 100644--- a/tests/unit/test_cache_heartbeat.py+++ b/tests/unit/test_cache_heartbeat.py@@ -1,4 +1,4 @@-"""Unit-Tests für CacheHeartbeat."""+"""Unit tests for CacheHeartbeat."""from __future__ import annotationsimport asyncio@@ -17,7 +17,7 @@ async def test_heartbeat_fires_periodically():hb = CacheHeartbeat(interval_s=0.05, probe=probe)hb.start()- await asyncio.sleep(0.18) # erwartet ~3 ticks+ await asyncio.sleep(0.18) # expects ~3 ticksawait hb.stop()assert counter["n"] >= 2@@ -35,7 +35,7 @@ async def test_heartbeat_stops_cleanly():await hb.stop()mid = counter["n"]await asyncio.sleep(0.12)- # Nach stop keine neuen Ticks mehr+ # No new ticks after stopassert counter["n"] == mid@@ -52,5 +52,5 @@ async def test_heartbeat_probe_failures_are_swallowed():hb.start()await asyncio.sleep(0.15)await hb.stop()- # Loop darf nach fehlerhaftem probe weiterlaufen+ # Loop is allowed to keep running after a failing probeassert counter["n"] >= 2diff --git a/tests/unit/test_config_tier_optional.py b/tests/unit/test_config_tier_optional.pyindex af17eb5341..a6113ff90b 100644--- a/tests/unit/test_config_tier_optional.py+++ b/tests/unit/test_config_tier_optional.py@@ -1,7 +1,7 @@-"""Verifiziert dass BrainTierConfig.model optional ist.+"""Verifies that BrainTierConfig.model is optional.-Integration mit dem Resolver aus manager.py ist in test_tier_defaults.py-getestet; hier nur das Config-Schema.+Integration with the resolver from manager.py is tested in+test_tier_defaults.py; here we only cover the config schema."""from __future__ import annotations@@ -43,7 +43,7 @@ class TestBrainTierConfigOptional:assert cfg.fallback_model_2 == "gpt-5-mini"def test_extra_fields_allowed(self):- # Backward-compat: alte Configs mit "deep_model" oder anderen- # Feldern sollen nicht crashen+ # Backward-compat: old configs with "deep_model" or other+ # fields should not crashcfg = BrainTierConfig(provider="gemini", model=None, custom_field="ignored")assert cfg.provider == "gemini"diff --git a/tests/unit/test_config_writer.py b/tests/unit/test_config_writer.pyindex 1ec0b2e613..d544b333b7 100644--- a/tests/unit/test_config_writer.py+++ b/tests/unit/test_config_writer.py@@ -1,4 +1,4 @@-"""Tests für config_writer: atomare TOML-Edits, Kommentar-Preservation, Roundtrip."""+"""Tests for config_writer: atomic TOML edits, comment preservation, roundtrip."""from __future__ import annotationsfrom pathlib import Path@@ -10,43 +10,43 @@ from jarvis.core import config_writer@pytest.fixture(autouse=True)def _isolate_provider_switch_side_effects(monkeypatch: pytest.MonkeyPatch) -> None:- """Neutralize the config-soll.json + ENV side-effects of the provider switches.+ """Neutralize the config-soll.json + ENV side-effects of the provider switches. # i18n-allow``set_brain_primary`` / ``set_tts_provider`` / ``set_stt_provider`` are theauthoritative writers of THREE persistence layers (jarvis.toml,- scripts/config-soll.json, JARVIS__* ENV). The tests in this module only+ scripts/config-soll.json, JARVIS__* ENV). The tests in this module only # i18n-allowexercise the TOML layer against a temp file, so we stub the best-effort syncs- to no-ops — otherwise they would touch the LIVE scripts/config-soll.json and+ to no-ops — otherwise they would touch the LIVE scripts/config-soll.json and # i18n-allowthe LIVE Windows registry. The dedicated three-layer coverage lives intests/unit/test_config_writer_{brain_primary,tts,stt}_sync.py."""monkeypatch.setattr(- config_writer, "_sync_brain_primary_drift_soll", lambda name: None+ config_writer, "_sync_brain_primary_drift_soll", lambda name: None # i18n-allow)monkeypatch.setattr(- config_writer, "_sync_tts_provider_drift_soll", lambda applied: None+ config_writer, "_sync_tts_provider_drift_soll", lambda applied: None # i18n-allow)monkeypatch.setattr(- config_writer, "_sync_stt_provider_drift_soll", lambda name: None+ config_writer, "_sync_stt_provider_drift_soll", lambda name: None # i18n-allow)@pytest.fixturedef sample_toml(tmp_path: Path) -> Path:- """jarvis.toml-Skelett mit Kommentaren, die wir nicht verlieren wollen."""+ """jarvis.toml skeleton with comments we don't want to lose."""p = tmp_path / "jarvis.toml"p.write_text("""\-# Personal Jarvis — Hauptkonfiguration-# Kommentare bleiben beim Schreiben erhalten (tomlkit).+# Personal Jarvis — main configuration+# Comments survive the write (tomlkit).[brain]-# Aktiver Standard-Provider+# Active default providerprimary = "openrouter"deep_brain = "claude-api"[brain.providers.claude-api]-model = "claude-haiku-4-5" # darf NICHT verschwinden+model = "claude-haiku-4-5" # must NOT disappear[tts]provider = "gemini-flash-tts"@@ -66,9 +66,9 @@ def test_set_brain_primary_changes_value(sample_toml: Path) -> None:def test_set_brain_primary_preserves_comments(sample_toml: Path) -> None:config_writer.set_brain_primary("gemini", path=sample_toml)text = sample_toml.read_text(encoding="utf-8")- assert "# Personal Jarvis — Hauptkonfiguration" in text- assert "# Aktiver Standard-Provider" in text- assert "# darf NICHT verschwinden" in text+ assert "# Personal Jarvis — main configuration" in text+ assert "# Active default provider" in text+ assert "# must NOT disappear" in textdef test_set_brain_primary_preserves_unrelated_keys(sample_toml: Path) -> None:@@ -110,7 +110,7 @@ def test_set_ui_language_writes_ui_key(sample_toml: Path) -> None:def test_atomic_write_does_not_leave_tmp(sample_toml: Path) -> None:config_writer.set_brain_primary("openai", path=sample_toml)leftovers = list(sample_toml.parent.glob("*.tmp"))- assert leftovers == [], f"Tempfile nicht aufgeräumt: {leftovers}"+ assert leftovers == [], f"Tempfile not cleaned up: {leftovers}"def test_missing_config_raises(tmp_path: Path) -> None:diff --git a/tests/unit/test_config_writer_brain_primary_sync.py b/tests/unit/test_config_writer_brain_primary_sync.pyindex 744fe6fcb7..13e15b33af 100644--- a/tests/unit/test_config_writer_brain_primary_sync.py+++ b/tests/unit/test_config_writer_brain_primary_sync.py@@ -5,16 +5,16 @@ must persist across a restart. There are THREE persistence layers and theUI switch must be the authoritative writer of ALL three:1. ``jarvis.toml`` ``[brain] primary`` (universal, always runs)- 2. ``scripts/config-soll.json`` ``brain.primary`` (drift-guard soll value)+ 2. ``scripts/config-soll.json`` ``brain.primary`` (drift-guard soll value) # i18n-allow3. ``JARVIS__BRAIN__PRIMARY`` User-scope ENV var (boot override, winreg)Layers 2 and 3 are best-effort enhancements gated for the cloud-first-doctrine: on a headless Linux VPS the config-soll.json may be absent and+doctrine: on a headless Linux VPS the config-soll.json may be absent and # i18n-allowthere is no Windows registry. Neither must ever break the TOML write norraise out of ``set_brain_primary``.These tests use TEMP files and monkeypatch only — they NEVER touch the live-``jarvis.toml`` or the live ``scripts/config-soll.json`` and NEVER mutate the+``jarvis.toml`` or the live ``scripts/config-soll.json`` and NEVER mutate the # i18n-allowreal Windows registry."""from __future__ import annotations@@ -44,9 +44,9 @@ deep_brain = "claude-api"@pytest.fixture-def sample_soll(tmp_path: Path) -> Path:- """A config-soll.json skeleton with extra keys we must preserve."""- p = tmp_path / "config-soll.json"+def sample_soll(tmp_path: Path) -> Path: # i18n-allow+ """A config-soll.json skeleton with extra keys we must preserve.""" # i18n-allow+ p = tmp_path / "config-soll.json" # i18n-allowp.write_text(json.dumps({@@ -73,12 +73,12 @@ def sample_soll(tmp_path: Path) -> Path:def test_set_brain_primary_writes_all_three_layers(sample_toml: Path,- sample_soll: Path,+ sample_soll: Path, # i18n-allowmonkeypatch: pytest.MonkeyPatch,) -> None:- """The UI switch must write TOML + config-soll.json + ENV (winreg)."""- # Redirect the soll path to our temp copy.- monkeypatch.setattr(config_writer, "_config_soll_path", lambda: sample_soll)+ """The UI switch must write TOML + config-soll.json + ENV (winreg).""" # i18n-allow+ # Redirect the soll path to our temp copy. # i18n-allow+ monkeypatch.setattr(config_writer, "_config_soll_path", lambda: sample_soll) # i18n-allow# Capture the winreg setter call instead of touching the real registry.env_calls: list[tuple[str, str]] = []@@ -93,9 +93,9 @@ def test_set_brain_primary_writes_all_three_layers(# Layer 1: TOML.assert 'primary = "openai"' in sample_toml.read_text(encoding="utf-8")- # Layer 2: config-soll.json.- soll = json.loads(sample_soll.read_text(encoding="utf-8"))- assert soll["brain"]["primary"] == "openai"+ # Layer 2: config-soll.json. # i18n-allow+ soll = json.loads(sample_soll.read_text(encoding="utf-8")) # i18n-allow+ assert soll["brain"]["primary"] == "openai" # i18n-allow# Layer 3: ENV setter called with the canonical var name + value.assert env_calls == [("JARVIS__BRAIN__PRIMARY", "openai")]@@ -103,7 +103,7 @@ def test_set_brain_primary_writes_all_three_layers(def test_set_brain_primary_updates_live_os_environ(sample_toml: Path,- sample_soll: Path,+ sample_soll: Path, # i18n-allowmonkeypatch: pytest.MonkeyPatch,) -> None:"""The live process os.environ must be updated so children inherit it.@@ -112,7 +112,7 @@ def test_set_brain_primary_updates_live_os_environ(``_set_user_env_var`` runs its os.environ update without touching the realregistry."""- monkeypatch.setattr(config_writer, "_config_soll_path", lambda: sample_soll)+ monkeypatch.setattr(config_writer, "_config_soll_path", lambda: sample_soll) # i18n-allowmonkeypatch.setattr(config_writer, "_set_user_env_var_winreg", lambda name, value: None)monkeypatch.delenv("JARVIS__BRAIN__PRIMARY", raising=False)@@ -124,77 +124,77 @@ def test_set_brain_primary_updates_live_os_environ(# -----------------------------------------------------------------------# Layer 2: config-soll.json key preservation.+# Layer 2: config-soll.json key preservation. # i18n-allow# -----------------------------------------------------------------------def test_config_soll_sync_preserves_other_keys(+def test_config_soll_sync_preserves_other_keys( # i18n-allowsample_toml: Path,- sample_soll: Path,+ sample_soll: Path, # i18n-allowmonkeypatch: pytest.MonkeyPatch,) -> None:"""Only brain.primary changes; _comment and other brain.* keys stay."""- monkeypatch.setattr(config_writer, "_config_soll_path", lambda: sample_soll)+ monkeypatch.setattr(config_writer, "_config_soll_path", lambda: sample_soll) # i18n-allowmonkeypatch.setattr(config_writer, "_set_user_env_var", lambda name, value: None)config_writer.set_brain_primary("openai", path=sample_toml)- soll = json.loads(sample_soll.read_text(encoding="utf-8"))- assert soll["_comment"] == "do not lose me"- assert soll["_updated"] == "2026-05-28"- assert soll["brain"]["primary"] == "openai"+ soll = json.loads(sample_soll.read_text(encoding="utf-8")) # i18n-allow+ assert soll["_comment"] == "do not lose me" # i18n-allow+ assert soll["_updated"] == "2026-05-28" # i18n-allow+ assert soll["brain"]["primary"] == "openai" # i18n-allow# Other brain.* keys untouched.- assert soll["brain"]["fallback"] == "gemini"- assert soll["brain"]["deep_brain"] == "gemini"+ assert soll["brain"]["fallback"] == "gemini" # i18n-allow+ assert soll["brain"]["deep_brain"] == "gemini" # i18n-allow# Other top-level tables untouched.- assert soll["tts"]["provider"] == "gemini-flash-tts"+ assert soll["tts"]["provider"] == "gemini-flash-tts" # i18n-allow-def test_config_soll_sync_indent_two(+def test_config_soll_sync_indent_two( # i18n-allowsample_toml: Path,- sample_soll: Path,+ sample_soll: Path, # i18n-allowmonkeypatch: pytest.MonkeyPatch,) -> None:- """config-soll.json is written with indent=2 (drift-guard readability)."""- monkeypatch.setattr(config_writer, "_config_soll_path", lambda: sample_soll)+ """config-soll.json is written with indent=2 (drift-guard readability).""" # i18n-allow+ monkeypatch.setattr(config_writer, "_config_soll_path", lambda: sample_soll) # i18n-allowmonkeypatch.setattr(config_writer, "_set_user_env_var", lambda name, value: None)config_writer.set_brain_primary("openai", path=sample_toml)- raw = sample_soll.read_text(encoding="utf-8")+ raw = sample_soll.read_text(encoding="utf-8") # i18n-allowassert '\n "brain"' in raw # two-space indent for top-level keys-def test_config_soll_sync_creates_brain_block_if_missing(+def test_config_soll_sync_creates_brain_block_if_missing( # i18n-allowsample_toml: Path,tmp_path: Path,monkeypatch: pytest.MonkeyPatch,) -> None:- """A config-soll.json without a brain block gets one created."""- soll = tmp_path / "config-soll.json"- soll.write_text(json.dumps({"_comment": "x", "tts": {}}, indent=2), encoding="utf-8")- monkeypatch.setattr(config_writer, "_config_soll_path", lambda: soll)+ """A config-soll.json without a brain block gets one created.""" # i18n-allow+ soll = tmp_path / "config-soll.json" # i18n-allow+ soll.write_text(json.dumps({"_comment": "x", "tts": {}}, indent=2), encoding="utf-8") # i18n-allow+ monkeypatch.setattr(config_writer, "_config_soll_path", lambda: soll) # i18n-allowmonkeypatch.setattr(config_writer, "_set_user_env_var", lambda name, value: None)config_writer.set_brain_primary("openai", path=sample_toml)- data = json.loads(soll.read_text(encoding="utf-8"))+ data = json.loads(soll.read_text(encoding="utf-8")) # i18n-allowassert data["brain"]["primary"] == "openai"assert data["_comment"] == "x"-def test_config_soll_sync_leaves_no_tmp_file(+def test_config_soll_sync_leaves_no_tmp_file( # i18n-allowsample_toml: Path,- sample_soll: Path,+ sample_soll: Path, # i18n-allowmonkeypatch: pytest.MonkeyPatch,) -> None:"""Atomic tempfile+replace cleans up after itself."""- monkeypatch.setattr(config_writer, "_config_soll_path", lambda: sample_soll)+ monkeypatch.setattr(config_writer, "_config_soll_path", lambda: sample_soll) # i18n-allowmonkeypatch.setattr(config_writer, "_set_user_env_var", lambda name, value: None)config_writer.set_brain_primary("openai", path=sample_toml)- leftovers = list(sample_soll.parent.glob("*.tmp"))+ leftovers = list(sample_soll.parent.glob("*.tmp")) # i18n-allowassert leftovers == [], f"Tempfile not cleaned up: {leftovers}"@@ -203,16 +203,16 @@ def test_config_soll_sync_leaves_no_tmp_file(# -----------------------------------------------------------------------def test_missing_config_soll_does_not_break_toml_write(+def test_missing_config_soll_does_not_break_toml_write( # i18n-allowsample_toml: Path,tmp_path: Path,monkeypatch: pytest.MonkeyPatch,) -> None:- """When config-soll.json is absent (headless VPS), TOML still gets written+ """When config-soll.json is absent (headless VPS), TOML still gets written # i18n-allowand set_brain_primary does NOT raise."""- nonexistent = tmp_path / "no-such-config-soll.json"+ nonexistent = tmp_path / "no-such-config-soll.json" # i18n-allowassert not nonexistent.exists()- monkeypatch.setattr(config_writer, "_config_soll_path", lambda: nonexistent)+ monkeypatch.setattr(config_writer, "_config_soll_path", lambda: nonexistent) # i18n-allowmonkeypatch.setattr(config_writer, "_set_user_env_var", lambda name, value: None)# Must not raise.@@ -220,18 +220,18 @@ def test_missing_config_soll_does_not_break_toml_write(# Layer 1 still applied.assert 'primary = "openai"' in sample_toml.read_text(encoding="utf-8")- # No file was created at the soll path.+ # No file was created at the soll path. # i18n-allowassert not nonexistent.exists()def test_winreg_path_skipped_on_non_win32(sample_toml: Path,- sample_soll: Path,+ sample_soll: Path, # i18n-allowmonkeypatch: pytest.MonkeyPatch,) -> None:"""On a Linux VPS (sys.platform != 'win32') the registry setter is skipped,but os.environ is still updated for the live process."""- monkeypatch.setattr(config_writer, "_config_soll_path", lambda: sample_soll)+ monkeypatch.setattr(config_writer, "_config_soll_path", lambda: sample_soll) # i18n-allowmonkeypatch.setattr(sys, "platform", "linux")reg_calls: list[str] = []@@ -257,12 +257,12 @@ def test_winreg_path_skipped_on_non_win32(def test_env_sync_swallows_winreg_errors(sample_toml: Path,- sample_soll: Path,+ sample_soll: Path, # i18n-allowmonkeypatch: pytest.MonkeyPatch,) -> None:"""A registry/import error in the ENV sync is logged and swallowed —never raised out of set_brain_primary, and the TOML write still wins."""- monkeypatch.setattr(config_writer, "_config_soll_path", lambda: sample_soll)+ monkeypatch.setattr(config_writer, "_config_soll_path", lambda: sample_soll) # i18n-allowdef _raise(name: str, value: str) -> None:raise OSError("simulated registry failure")@@ -275,15 +275,15 @@ def test_env_sync_swallows_winreg_errors(assert 'primary = "openai"' in sample_toml.read_text(encoding="utf-8")-def test_soll_sync_swallows_write_errors(+def test_soll_sync_swallows_write_errors( # i18n-allowsample_toml: Path,monkeypatch: pytest.MonkeyPatch,tmp_path: Path,) -> None:- """A broken config-soll.json (invalid JSON) must not break the TOML write."""- broken = tmp_path / "config-soll.json"+ """A broken config-soll.json (invalid JSON) must not break the TOML write.""" # i18n-allow+ broken = tmp_path / "config-soll.json" # i18n-allowbroken.write_text("{ this is not valid json ", encoding="utf-8")- monkeypatch.setattr(config_writer, "_config_soll_path", lambda: broken)+ monkeypatch.setattr(config_writer, "_config_soll_path", lambda: broken) # i18n-allowmonkeypatch.setattr(config_writer, "_set_user_env_var", lambda name, value: None)# Must not raise.@@ -293,13 +293,13 @@ def test_soll_sync_swallows_write_errors(def test_set_brain_primary_still_raises_on_missing_toml(- sample_soll: Path,+ sample_soll: Path, # i18n-allowtmp_path: Path,monkeypatch: pytest.MonkeyPatch,) -> None:"""Production now auto-creates a missing TOML (_ensure_writable_config_path).Verify the file is created and the key is written even when the file was absent."""- monkeypatch.setattr(config_writer, "_config_soll_path", lambda: sample_soll)+ monkeypatch.setattr(config_writer, "_config_soll_path", lambda: sample_soll) # i18n-allowmonkeypatch.setattr(config_writer, "_set_user_env_var", lambda name, value: None)p = tmp_path / "does-not-exist.toml"diff --git a/tests/unit/test_config_writer_brain_provider_model_sync.py b/tests/unit/test_config_writer_brain_provider_model_sync.pyindex b8ffb150c3..6e3fc02848 100644--- a/tests/unit/test_config_writer_brain_provider_model_sync.py+++ b/tests/unit/test_config_writer_brain_provider_model_sync.py@@ -1,13 +1,13 @@"""Tests for the two-layer ``[brain.providers.<p>]`` model persistence sync.Per-provider model pins (``model`` / ``deep_model``) are pinned in-config-soll.json under the flat dotted key ``"brain.providers.<p>"``, so a+config-soll.json under the flat dotted key ``"brain.providers.<p>"``, so a # i18n-allowmodel picked in the per-provider model selector that wrote only the TOML wouldbe rolled back by the drift-guard within 5 minutes — the same BUG-010 classthat hit ``brain.primary``. ``set_brain_provider_model`` must therefore write:1. ``jarvis.toml`` ``[brain.providers.<p>] model/deep_model`` (TOML)- 2. ``scripts/config-soll.json`` ``brain.providers.<p>`` (drift-soll)+ 2. ``scripts/config-soll.json`` ``brain.providers.<p>`` (drift-soll) # i18n-allowThere is intentionally NO ENV layer: per-provider model keys have no effective``JARVIS__*`` boot override (the override parser only nests on ``__``, and the@@ -48,8 +48,8 @@ deep_model = "gemini-2.5-pro"@pytest.fixture-def sample_soll(tmp_path: Path) -> Path:- p = tmp_path / "config-soll.json"+def sample_soll(tmp_path: Path) -> Path: # i18n-allow+ p = tmp_path / "config-soll.json" # i18n-allowp.write_text(json.dumps({@@ -69,10 +69,10 @@ def sample_soll(tmp_path: Path) -> Path:return p-def test_writes_toml_and_soll_no_env(- sample_toml: Path, sample_soll: Path, monkeypatch: pytest.MonkeyPatch+def test_writes_toml_and_soll_no_env( # i18n-allow+ sample_toml: Path, sample_soll: Path, monkeypatch: pytest.MonkeyPatch # i18n-allow) -> None:- monkeypatch.setattr(config_writer, "_config_soll_path", lambda: sample_soll)+ monkeypatch.setattr(config_writer, "_config_soll_path", lambda: sample_soll) # i18n-allowenv_calls: list[tuple[str, str]] = []monkeypatch.setattr(config_writer, "_set_user_env_var",@@ -89,68 +89,68 @@ def test_writes_toml_and_soll_no_env(assert 'model = "gemini-3.5-flash"' in toml_rawassert 'deep_model = "gemini-3.1-pro-preview"' in toml_raw- # Layer 2: config-soll.json flat "brain.providers.gemini" key.- soll = json.loads(sample_soll.read_text(encoding="utf-8"))- assert soll["brain.providers.gemini"]["model"] == "gemini-3.5-flash"- assert soll["brain.providers.gemini"]["deep_model"] == "gemini-3.1-pro-preview"+ # Layer 2: config-soll.json flat "brain.providers.gemini" key. # i18n-allow+ soll = json.loads(sample_soll.read_text(encoding="utf-8")) # i18n-allow+ assert soll["brain.providers.gemini"]["model"] == "gemini-3.5-flash" # i18n-allow+ assert soll["brain.providers.gemini"]["deep_model"] == "gemini-3.1-pro-preview" # i18n-allow# NO ENV layer for per-provider model keys.assert env_calls == []def test_only_written_keys_are_synced(- sample_toml: Path, sample_soll: Path, monkeypatch: pytest.MonkeyPatch+ sample_toml: Path, sample_soll: Path, monkeypatch: pytest.MonkeyPatch # i18n-allow) -> None:- """Writing only ``model`` leaves the soll ``deep_model`` untouched."""- monkeypatch.setattr(config_writer, "_config_soll_path", lambda: sample_soll)+ """Writing only ``model`` leaves the soll ``deep_model`` untouched.""" # i18n-allow+ monkeypatch.setattr(config_writer, "_config_soll_path", lambda: sample_soll) # i18n-allowmonkeypatch.setattr(config_writer, "_set_user_env_var", lambda name, value: None)config_writer.set_brain_provider_model("gemini", model="gemini-3.5-flash", path=sample_toml,)- soll = json.loads(sample_soll.read_text(encoding="utf-8"))- assert soll["brain.providers.gemini"]["model"] == "gemini-3.5-flash"- # deep_model in the soll block is NOT changed (only model was written).- assert soll["brain.providers.gemini"]["deep_model"] == "gemini-2.5-pro"+ soll = json.loads(sample_soll.read_text(encoding="utf-8")) # i18n-allow+ assert soll["brain.providers.gemini"]["model"] == "gemini-3.5-flash" # i18n-allow+ # deep_model in the soll block is NOT changed (only model was written). # i18n-allow+ assert soll["brain.providers.gemini"]["deep_model"] == "gemini-2.5-pro" # i18n-allow-def test_config_soll_preserves_other_keys(- sample_toml: Path, sample_soll: Path, monkeypatch: pytest.MonkeyPatch+def test_config_soll_preserves_other_keys( # i18n-allow+ sample_toml: Path, sample_soll: Path, monkeypatch: pytest.MonkeyPatch # i18n-allow) -> None:- monkeypatch.setattr(config_writer, "_config_soll_path", lambda: sample_soll)+ monkeypatch.setattr(config_writer, "_config_soll_path", lambda: sample_soll) # i18n-allowmonkeypatch.setattr(config_writer, "_set_user_env_var", lambda name, value: None)config_writer.set_brain_provider_model("gemini", model="gemini-3.5-flash", path=sample_toml,)- soll = json.loads(sample_soll.read_text(encoding="utf-8"))- assert soll["_comment"] == "do not lose me"- assert soll["brain"]["primary"] == "gemini"- assert soll["tts"]["provider"] == "cartesia"+ soll = json.loads(sample_soll.read_text(encoding="utf-8")) # i18n-allow+ assert soll["_comment"] == "do not lose me" # i18n-allow+ assert soll["brain"]["primary"] == "gemini" # i18n-allow+ assert soll["tts"]["provider"] == "cartesia" # i18n-allow-def test_creates_soll_block_if_missing(- sample_toml: Path, sample_soll: Path, monkeypatch: pytest.MonkeyPatch+def test_creates_soll_block_if_missing( # i18n-allow+ sample_toml: Path, sample_soll: Path, monkeypatch: pytest.MonkeyPatch # i18n-allow) -> None:- """A provider with no soll block yet gets one created (not an error)."""- monkeypatch.setattr(config_writer, "_config_soll_path", lambda: sample_soll)+ """A provider with no soll block yet gets one created (not an error).""" # i18n-allow+ monkeypatch.setattr(config_writer, "_config_soll_path", lambda: sample_soll) # i18n-allowmonkeypatch.setattr(config_writer, "_set_user_env_var", lambda name, value: None)config_writer.set_brain_provider_model("claude-api", deep_model="claude-opus-4-8", path=sample_toml,)- soll = json.loads(sample_soll.read_text(encoding="utf-8"))- assert soll["brain.providers.claude-api"]["deep_model"] == "claude-opus-4-8"+ soll = json.loads(sample_soll.read_text(encoding="utf-8")) # i18n-allow+ assert soll["brain.providers.claude-api"]["deep_model"] == "claude-opus-4-8" # i18n-allow-def test_missing_config_soll_does_not_break_toml(+def test_missing_config_soll_does_not_break_toml( # i18n-allowsample_toml: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:- nonexistent = tmp_path / "no-such-config-soll.json"- monkeypatch.setattr(config_writer, "_config_soll_path", lambda: nonexistent)+ nonexistent = tmp_path / "no-such-config-soll.json" # i18n-allow+ monkeypatch.setattr(config_writer, "_config_soll_path", lambda: nonexistent) # i18n-allowmonkeypatch.setattr(config_writer, "_set_user_env_var", lambda name, value: None)config_writer.set_brain_provider_model(@@ -162,25 +162,25 @@ def test_missing_config_soll_does_not_break_toml(def test_noop_when_both_none(- sample_toml: Path, sample_soll: Path, monkeypatch: pytest.MonkeyPatch+ sample_toml: Path, sample_soll: Path, monkeypatch: pytest.MonkeyPatch # i18n-allow) -> None:"""Both ``None`` → nothing written anywhere (idempotent early return)."""- monkeypatch.setattr(config_writer, "_config_soll_path", lambda: sample_soll)+ monkeypatch.setattr(config_writer, "_config_soll_path", lambda: sample_soll) # i18n-allowmonkeypatch.setattr(config_writer, "_set_user_env_var", lambda name, value: None)before_toml = sample_toml.read_text(encoding="utf-8")- before_soll = sample_soll.read_text(encoding="utf-8")+ before_soll = sample_soll.read_text(encoding="utf-8") # i18n-allowconfig_writer.set_brain_provider_model("gemini", path=sample_toml)assert sample_toml.read_text(encoding="utf-8") == before_toml- assert sample_soll.read_text(encoding="utf-8") == before_soll+ assert sample_soll.read_text(encoding="utf-8") == before_soll # i18n-allow-def test_writes_cu_model_to_toml_and_soll(- sample_toml: Path, sample_soll: Path, monkeypatch: pytest.MonkeyPatch+def test_writes_cu_model_to_toml_and_soll( # i18n-allow+ sample_toml: Path, sample_soll: Path, monkeypatch: pytest.MonkeyPatch # i18n-allow) -> None:"""Phase 3: the per-provider Computer-Use model persists like model/deep_model."""- monkeypatch.setattr(config_writer, "_config_soll_path", lambda: sample_soll)+ monkeypatch.setattr(config_writer, "_config_soll_path", lambda: sample_soll) # i18n-allowmonkeypatch.setattr(config_writer, "_set_user_env_var", lambda name, value: None)config_writer.set_brain_provider_model(@@ -192,19 +192,19 @@ def test_writes_cu_model_to_toml_and_soll(# Untouched sibling keys remain.assert 'model = "gemini-2.5-flash"' in toml_raw- soll = json.loads(sample_soll.read_text(encoding="utf-8"))- assert soll["brain.providers.gemini"]["cu_model"] == "gemini-3.1-pro-preview"- # Only cu_model synced — model/deep_model in the soll block stay as they were.- assert soll["brain.providers.gemini"]["model"] == "gemini-2.5-flash"- assert soll["brain.providers.gemini"]["deep_model"] == "gemini-2.5-pro"+ soll = json.loads(sample_soll.read_text(encoding="utf-8")) # i18n-allow+ assert soll["brain.providers.gemini"]["cu_model"] == "gemini-3.1-pro-preview" # i18n-allow+ # Only cu_model synced — model/deep_model in the soll block stay as they were. # i18n-allow+ assert soll["brain.providers.gemini"]["model"] == "gemini-2.5-flash" # i18n-allow+ assert soll["brain.providers.gemini"]["deep_model"] == "gemini-2.5-pro" # i18n-allowdef test_cu_model_cleared_with_empty_string(- sample_toml: Path, sample_soll: Path, monkeypatch: pytest.MonkeyPatch+ sample_toml: Path, sample_soll: Path, monkeypatch: pytest.MonkeyPatch # i18n-allow) -> None:"""An empty cu_model writes "" (UI 'use my main model') — distinct from Nonewhich means 'leave unchanged'."""- monkeypatch.setattr(config_writer, "_config_soll_path", lambda: sample_soll)+ monkeypatch.setattr(config_writer, "_config_soll_path", lambda: sample_soll) # i18n-allowmonkeypatch.setattr(config_writer, "_set_user_env_var", lambda name, value: None)config_writer.set_brain_provider_model("gemini", cu_model="", path=sample_toml)diff --git a/tests/unit/test_config_writer_stt_sync.py b/tests/unit/test_config_writer_stt_sync.pyindex d2c9873852..ce63fdbf1b 100644--- a/tests/unit/test_config_writer_stt_sync.py+++ b/tests/unit/test_config_writer_stt_sync.py@@ -1,13 +1,13 @@"""Tests for the three-layer ``[stt] provider`` persistence sync.When the user switches the STT provider in the desktop app, the choice must-persist across a restart. ``config-soll.json`` pins ``stt.provider``, so a UI+persist across a restart. ``config-soll.json`` pins ``stt.provider``, so a UI # i18n-allowswitch that wrote only the TOML would be rolled back by the drift-guard within5 minutes — exactly the BUG that hit ``brain.primary`` before it became3-layer. The STT switch must therefore write ALL THREE layers:1. ``jarvis.toml`` ``[stt] provider`` (universal, always runs)- 2. ``scripts/config-soll.json`` ``stt.provider`` (drift-guard soll value)+ 2. ``scripts/config-soll.json`` ``stt.provider`` (drift-guard soll value) # i18n-allow3. ``JARVIS__STT__PROVIDER`` User-scope ENV var (boot override, winreg)Layers 2 + 3 are best-effort (cloud-first): graceful no-op on a headless VPS,@@ -42,8 +42,8 @@ model = "large-v3-turbo"@pytest.fixture-def sample_soll(tmp_path: Path) -> Path:- p = tmp_path / "config-soll.json"+def sample_soll(tmp_path: Path) -> Path: # i18n-allow+ p = tmp_path / "config-soll.json" # i18n-allowp.write_text(json.dumps({@@ -60,10 +60,10 @@ def sample_soll(tmp_path: Path) -> Path:def test_set_stt_provider_writes_all_three_layers(- sample_toml: Path, sample_soll: Path, monkeypatch: pytest.MonkeyPatch+ sample_toml: Path, sample_soll: Path, monkeypatch: pytest.MonkeyPatch # i18n-allow) -> None:- """The UI switch must write TOML + config-soll.json + ENV (winreg)."""- monkeypatch.setattr(config_writer, "_config_soll_path", lambda: sample_soll)+ """The UI switch must write TOML + config-soll.json + ENV (winreg).""" # i18n-allow+ monkeypatch.setattr(config_writer, "_config_soll_path", lambda: sample_soll) # i18n-allowenv_calls: list[tuple[str, str]] = []monkeypatch.setattr(config_writer,@@ -76,35 +76,35 @@ def test_set_stt_provider_writes_all_three_layers(# Layer 1: TOML.assert 'provider = "faster-whisper"' in sample_toml.read_text(encoding="utf-8")- # Layer 2: config-soll.json stt.provider.- soll = json.loads(sample_soll.read_text(encoding="utf-8"))- assert soll["stt"]["provider"] == "faster-whisper"+ # Layer 2: config-soll.json stt.provider. # i18n-allow+ soll = json.loads(sample_soll.read_text(encoding="utf-8")) # i18n-allow+ assert soll["stt"]["provider"] == "faster-whisper" # i18n-allow# Layer 3: ENV setter called with the canonical var name + value.assert env_calls == [("JARVIS__STT__PROVIDER", "faster-whisper")]-def test_config_soll_sync_preserves_other_keys(- sample_toml: Path, sample_soll: Path, monkeypatch: pytest.MonkeyPatch+def test_config_soll_sync_preserves_other_keys( # i18n-allow+ sample_toml: Path, sample_soll: Path, monkeypatch: pytest.MonkeyPatch # i18n-allow) -> None:"""Only stt.provider changes; the model + other tables stay."""- monkeypatch.setattr(config_writer, "_config_soll_path", lambda: sample_soll)+ monkeypatch.setattr(config_writer, "_config_soll_path", lambda: sample_soll) # i18n-allowmonkeypatch.setattr(config_writer, "_set_user_env_var", lambda name, value: None)config_writer.set_stt_provider("google-cloud-stt", path=sample_toml)- soll = json.loads(sample_soll.read_text(encoding="utf-8"))- assert soll["stt"]["provider"] == "google-cloud-stt"+ soll = json.loads(sample_soll.read_text(encoding="utf-8")) # i18n-allow+ assert soll["stt"]["provider"] == "google-cloud-stt" # i18n-allow# The model pin inside stt is not touched by the provider switch.- assert soll["stt"]["model"] == "large-v3-turbo"- assert soll["_comment"] == "do not lose me"- assert soll["brain"]["primary"] == "gemini"+ assert soll["stt"]["model"] == "large-v3-turbo" # i18n-allow+ assert soll["_comment"] == "do not lose me" # i18n-allow+ assert soll["brain"]["primary"] == "gemini" # i18n-allowdef test_updates_live_os_environ(- sample_toml: Path, sample_soll: Path, monkeypatch: pytest.MonkeyPatch+ sample_toml: Path, sample_soll: Path, monkeypatch: pytest.MonkeyPatch # i18n-allow) -> None:- monkeypatch.setattr(config_writer, "_config_soll_path", lambda: sample_soll)+ monkeypatch.setattr(config_writer, "_config_soll_path", lambda: sample_soll) # i18n-allowmonkeypatch.setattr(config_writer, "_set_user_env_var_winreg", lambda name, value: None)monkeypatch.delenv("JARVIS__STT__PROVIDER", raising=False)@@ -115,11 +115,11 @@ def test_updates_live_os_environ(assert os.environ.get("JARVIS__STT__PROVIDER") == "faster-whisper"-def test_missing_config_soll_does_not_break_toml(+def test_missing_config_soll_does_not_break_toml( # i18n-allowsample_toml: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:- nonexistent = tmp_path / "no-such-config-soll.json"- monkeypatch.setattr(config_writer, "_config_soll_path", lambda: nonexistent)+ nonexistent = tmp_path / "no-such-config-soll.json" # i18n-allow+ monkeypatch.setattr(config_writer, "_config_soll_path", lambda: nonexistent) # i18n-allowmonkeypatch.setattr(config_writer, "_set_user_env_var", lambda name, value: None)config_writer.set_stt_provider("faster-whisper", path=sample_toml)@@ -128,12 +128,12 @@ def test_missing_config_soll_does_not_break_toml(assert not nonexistent.exists()-def test_soll_sync_swallows_write_errors(+def test_soll_sync_swallows_write_errors( # i18n-allowsample_toml: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:- broken = tmp_path / "config-soll.json"+ broken = tmp_path / "config-soll.json" # i18n-allowbroken.write_text("{ this is not valid json ", encoding="utf-8")- monkeypatch.setattr(config_writer, "_config_soll_path", lambda: broken)+ monkeypatch.setattr(config_writer, "_config_soll_path", lambda: broken) # i18n-allowmonkeypatch.setattr(config_writer, "_set_user_env_var", lambda name, value: None)config_writer.set_stt_provider("faster-whisper", path=sample_toml)@@ -142,9 +142,9 @@ def test_soll_sync_swallows_write_errors(def test_winreg_skipped_on_non_win32(- sample_toml: Path, sample_soll: Path, monkeypatch: pytest.MonkeyPatch+ sample_toml: Path, sample_soll: Path, monkeypatch: pytest.MonkeyPatch # i18n-allow) -> None:- monkeypatch.setattr(config_writer, "_config_soll_path", lambda: sample_soll)+ monkeypatch.setattr(config_writer, "_config_soll_path", lambda: sample_soll) # i18n-allowmonkeypatch.setattr(sys, "platform", "linux")def _boom(name: str, value: str) -> None: # pragma: no cover - guard@@ -161,11 +161,11 @@ def test_winreg_skipped_on_non_win32(def test_raises_on_missing_toml(- sample_soll: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+ sample_soll: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch # i18n-allow) -> None:# Production now auto-creates a missing TOML instead of raising# FileNotFoundError (_ensure_writable_config_path, headless-VPS fix).- monkeypatch.setattr(config_writer, "_config_soll_path", lambda: sample_soll)+ monkeypatch.setattr(config_writer, "_config_soll_path", lambda: sample_soll) # i18n-allowmonkeypatch.setattr(config_writer, "_set_user_env_var", lambda name, value: None)p = tmp_path / "nope.toml"@@ -176,17 +176,17 @@ def test_raises_on_missing_toml(# ----------------------------------------------------------------------------# set_stt_language: TOML + config-soll sync (drift-guard pinned, no ENV var).+# set_stt_language: TOML + config-soll sync (drift-guard pinned, no ENV var). # i18n-allow# ---------------------------------------------------------------------------def test_set_stt_language_writes_all_three_layers(- sample_toml: Path, sample_soll: Path, monkeypatch: pytest.MonkeyPatch+ sample_toml: Path, sample_soll: Path, monkeypatch: pytest.MonkeyPatch # i18n-allow) -> None:- """The recognition-language switch persists to TOML + config-soll + the+ """The recognition-language switch persists to TOML + config-soll + the # i18n-allowJARVIS__STT__LANGUAGE ENV var, so neither the drift-guard nor a stale ENVoverride reverts it (same 3-layer trap as stt.model)."""- monkeypatch.setattr(config_writer, "_config_soll_path", lambda: sample_soll)+ monkeypatch.setattr(config_writer, "_config_soll_path", lambda: sample_soll) # i18n-allowenv_calls: list[tuple[str, str]] = []monkeypatch.setattr(config_writer, "_set_user_env_var", lambda n, v: env_calls.append((n, v))@@ -195,34 +195,34 @@ def test_set_stt_language_writes_all_three_layers(config_writer.set_stt_language("de", path=sample_toml)assert 'language = "de"' in sample_toml.read_text(encoding="utf-8")- soll = json.loads(sample_soll.read_text(encoding="utf-8"))- assert soll["stt"]["language"] == "de"+ soll = json.loads(sample_soll.read_text(encoding="utf-8")) # i18n-allow+ assert soll["stt"]["language"] == "de" # i18n-allow# Sibling keys untouched.- assert soll["stt"]["provider"] == "groq-api"- assert soll["stt"]["model"] == "large-v3-turbo"+ assert soll["stt"]["provider"] == "groq-api" # i18n-allow+ assert soll["stt"]["model"] == "large-v3-turbo" # i18n-allow# ENV layer written so a stale JARVIS__STT__LANGUAGE cannot mask the choice.assert env_calls == [("JARVIS__STT__LANGUAGE", "de")]def test_set_stt_language_auto_roundtrip(- sample_toml: Path, sample_soll: Path, monkeypatch: pytest.MonkeyPatch+ sample_toml: Path, sample_soll: Path, monkeypatch: pytest.MonkeyPatch # i18n-allow) -> None:- monkeypatch.setattr(config_writer, "_config_soll_path", lambda: sample_soll)+ monkeypatch.setattr(config_writer, "_config_soll_path", lambda: sample_soll) # i18n-allowmonkeypatch.setattr(config_writer, "_set_user_env_var", lambda n, v: None)config_writer.set_stt_language("auto", path=sample_toml)assert 'language = "auto"' in sample_toml.read_text(encoding="utf-8")- soll = json.loads(sample_soll.read_text(encoding="utf-8"))- assert soll["stt"]["language"] == "auto"+ soll = json.loads(sample_soll.read_text(encoding="utf-8")) # i18n-allow+ assert soll["stt"]["language"] == "auto" # i18n-allow-def test_set_stt_language_soll_failure_does_not_break_toml(+def test_set_stt_language_soll_failure_does_not_break_toml( # i18n-allowsample_toml: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:- broken = tmp_path / "config-soll.json"+ broken = tmp_path / "config-soll.json" # i18n-allowbroken.write_text("{ not valid json ", encoding="utf-8")- monkeypatch.setattr(config_writer, "_config_soll_path", lambda: broken)+ monkeypatch.setattr(config_writer, "_config_soll_path", lambda: broken) # i18n-allowmonkeypatch.setattr(config_writer, "_set_user_env_var", lambda n, v: None)config_writer.set_stt_language("es", path=sample_toml)diff --git a/tests/unit/test_config_writer_tts_sync.py b/tests/unit/test_config_writer_tts_sync.pyindex 6c50650254..cd055b0f38 100644--- a/tests/unit/test_config_writer_tts_sync.py+++ b/tests/unit/test_config_writer_tts_sync.py@@ -1,14 +1,14 @@"""Tests for the three-layer ``[tts] provider`` persistence sync.When the user switches the TTS provider in the desktop app, the choice must-persist across a restart. ``config-soll.json`` pins the whole ``tts`` block+persist across a restart. ``config-soll.json`` pins the whole ``tts`` block # i18n-allow(``provider`` + ``voice_de`` / ``voice_en`` / ``language_code`` ...), so a UIswitch that wrote only the TOML would be rolled back by the drift-guard within5 minutes — exactly the BUG that hit ``brain.primary`` before it became3-layer. The TTS switch must therefore write ALL THREE layers:1. ``jarvis.toml`` ``[tts] provider`` (+ provider-dependent voice/lang/model)- 2. ``scripts/config-soll.json`` ``tts.*`` (drift-guard soll values)+ 2. ``scripts/config-soll.json`` ``tts.*`` (drift-guard soll values) # i18n-allow3. ``JARVIS__TTS__PROVIDER`` User-scope ENV var (boot override, winreg)Crucially, layer 2 must mirror EVERY key the TOML write touched — not just@@ -49,9 +49,9 @@ language_code = "de-DE"@pytest.fixture-def sample_soll(tmp_path: Path) -> Path:- """A config-soll.json skeleton that pins the whole tts block."""- p = tmp_path / "config-soll.json"+def sample_soll(tmp_path: Path) -> Path: # i18n-allow+ """A config-soll.json skeleton that pins the whole tts block.""" # i18n-allow+ p = tmp_path / "config-soll.json" # i18n-allowp.write_text(json.dumps({@@ -74,10 +74,10 @@ def sample_soll(tmp_path: Path) -> Path:def test_set_tts_provider_writes_all_three_layers(- sample_toml: Path, sample_soll: Path, monkeypatch: pytest.MonkeyPatch+ sample_toml: Path, sample_soll: Path, monkeypatch: pytest.MonkeyPatch # i18n-allow) -> None:- """The UI switch must write TOML + config-soll.json + ENV (winreg)."""- monkeypatch.setattr(config_writer, "_config_soll_path", lambda: sample_soll)+ """The UI switch must write TOML + config-soll.json + ENV (winreg).""" # i18n-allow+ monkeypatch.setattr(config_writer, "_config_soll_path", lambda: sample_soll) # i18n-allowenv_calls: list[tuple[str, str]] = []monkeypatch.setattr(config_writer,@@ -90,48 +90,48 @@ def test_set_tts_provider_writes_all_three_layers(# Layer 1: TOML.assert 'provider = "grok-voice"' in sample_toml.read_text(encoding="utf-8")- # Layer 2: config-soll.json tts.provider.- soll = json.loads(sample_soll.read_text(encoding="utf-8"))- assert soll["tts"]["provider"] == "grok-voice"+ # Layer 2: config-soll.json tts.provider. # i18n-allow+ soll = json.loads(sample_soll.read_text(encoding="utf-8")) # i18n-allow+ assert soll["tts"]["provider"] == "grok-voice" # i18n-allow# Layer 3: ENV setter called with the canonical var name + value.assert env_calls == [("JARVIS__TTS__PROVIDER", "grok-voice")]-def test_config_soll_mirrors_provider_dependent_voice(- sample_toml: Path, sample_soll: Path, monkeypatch: pytest.MonkeyPatch+def test_config_soll_mirrors_provider_dependent_voice( # i18n-allow+ sample_toml: Path, sample_soll: Path, monkeypatch: pytest.MonkeyPatch # i18n-allow) -> None:- """The drift-soll must mirror the SAME voice the TOML write applied.+ """The drift-soll must mirror the SAME voice the TOML write applied. # i18n-allowSwitching gemini -> grok-voice rewrites voice_de/voice_en to a grok voice- in the TOML. If config-soll kept the old "Charon" pin, the drift-guard- would revert the voice to a value invalid for grok. So config-soll must end+ in the TOML. If config-soll kept the old "Charon" pin, the drift-guard # i18n-allow+ would revert the voice to a value invalid for grok. So config-soll must end # i18n-allowup with the grok voice too — zero drift across the whole tts block."""- monkeypatch.setattr(config_writer, "_config_soll_path", lambda: sample_soll)+ monkeypatch.setattr(config_writer, "_config_soll_path", lambda: sample_soll) # i18n-allowmonkeypatch.setattr(config_writer, "_set_user_env_var", lambda name, value: None)config_writer.set_tts_provider("grok-voice", path=sample_toml)toml_raw = sample_toml.read_text(encoding="utf-8")- soll = json.loads(sample_soll.read_text(encoding="utf-8"))+ soll = json.loads(sample_soll.read_text(encoding="utf-8")) # i18n-allow- # Whatever voice the TOML write picked, config-soll agrees with it.+ # Whatever voice the TOML write picked, config-soll agrees with it. # i18n-allowassert 'voice_de = "leo"' in toml_raw- assert soll["tts"]["voice_de"] == "leo"- assert soll["tts"]["voice_en"] == "leo"+ assert soll["tts"]["voice_de"] == "leo" # i18n-allow+ assert soll["tts"]["voice_en"] == "leo" # i18n-allow-def test_config_soll_mirrors_preserved_valid_voice(+def test_config_soll_mirrors_preserved_valid_voice( # i18n-allowtmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:"""A valid custom voice that the TOML write PRESERVES must still be mirrored- into config-soll — otherwise the drift-guard reverts the user's choice.+ into config-soll — otherwise the drift-guard reverts the user's choice. # i18n-allowScenario: the user hand-set ``voice_de = "Orus"`` (a valid Gemini voice) andswitches to / stays on gemini-flash-tts. ``_patch_tts_block`` keeps "Orus"- in the TOML (user override wins). But config-soll still pins "Charon" — so- the guard would revert "Orus" -> "Charon" within 5 minutes. config-soll must+ in the TOML (user override wins). But config-soll still pins "Charon" — so # i18n-allow+ the guard would revert "Orus" -> "Charon" within 5 minutes. config-soll must # i18n-allowend up agreeing with the preserved TOML value."""toml = tmp_path / "jarvis.toml"@@ -139,23 +139,23 @@ def test_config_soll_mirrors_preserved_valid_voice('[tts]\nprovider = "gemini-flash-tts"\nvoice_de = "Orus"\nvoice_en = "Orus"\n',encoding="utf-8",)- soll = tmp_path / "config-soll.json"- soll.write_text(+ soll = tmp_path / "config-soll.json" # i18n-allow+ soll.write_text( # i18n-allowjson.dumps({"tts": {"provider": "gemini-flash-tts", "voice_de": "Charon", "voice_en": "Charon"}},indent=2,),encoding="utf-8",)- monkeypatch.setattr(config_writer, "_config_soll_path", lambda: soll)+ monkeypatch.setattr(config_writer, "_config_soll_path", lambda: soll) # i18n-allowmonkeypatch.setattr(config_writer, "_set_user_env_var", lambda name, value: None)config_writer.set_tts_provider("gemini-flash-tts", path=toml)# TOML keeps the user's valid voice...assert 'voice_de = "Orus"' in toml.read_text(encoding="utf-8")- # ...and config-soll now agrees with it (no Charon revert).- data = json.loads(soll.read_text(encoding="utf-8"))+ # ...and config-soll now agrees with it (no Charon revert). # i18n-allow+ data = json.loads(soll.read_text(encoding="utf-8")) # i18n-allowassert data["tts"]["voice_de"] == "Orus"assert data["tts"]["voice_en"] == "Orus"@@ -177,7 +177,7 @@ def test_pluginless_provider_does_not_blank_voice('[tts]\nprovider = "gemini-flash-tts"\nvoice_de = "Charon"\nvoice_en = "Charon"\n',encoding="utf-8",)- monkeypatch.setattr(config_writer, "_config_soll_path", lambda: tmp_path / "nope.json")+ monkeypatch.setattr(config_writer, "_config_soll_path", lambda: tmp_path / "nope.json") # i18n-allowmonkeypatch.setattr(config_writer, "_set_user_env_var", lambda name, value: None)config_writer.set_tts_provider("openai-tts", path=toml)@@ -191,26 +191,26 @@ def test_pluginless_provider_does_not_blank_voice(assert 'voice_de = "Charon"' in raw-def test_config_soll_sync_preserves_other_keys(- sample_toml: Path, sample_soll: Path, monkeypatch: pytest.MonkeyPatch+def test_config_soll_sync_preserves_other_keys( # i18n-allow+ sample_toml: Path, sample_soll: Path, monkeypatch: pytest.MonkeyPatch # i18n-allow) -> None:"""Only the tts.* keys the write touched change; everything else stays."""- monkeypatch.setattr(config_writer, "_config_soll_path", lambda: sample_soll)+ monkeypatch.setattr(config_writer, "_config_soll_path", lambda: sample_soll) # i18n-allowmonkeypatch.setattr(config_writer, "_set_user_env_var", lambda name, value: None)config_writer.set_tts_provider("grok-voice", path=sample_toml)- soll = json.loads(sample_soll.read_text(encoding="utf-8"))- assert soll["_comment"] == "do not lose me"- assert soll["brain"]["primary"] == "gemini"+ soll = json.loads(sample_soll.read_text(encoding="utf-8")) # i18n-allow+ assert soll["_comment"] == "do not lose me" # i18n-allow+ assert soll["brain"]["primary"] == "gemini" # i18n-allow# The fallback key inside tts is not touched by the provider switch.- assert soll["tts"]["fallback"] == "grok-voice"+ assert soll["tts"]["fallback"] == "grok-voice" # i18n-allowdef test_updates_live_os_environ(- sample_toml: Path, sample_soll: Path, monkeypatch: pytest.MonkeyPatch+ sample_toml: Path, sample_soll: Path, monkeypatch: pytest.MonkeyPatch # i18n-allow) -> None:- monkeypatch.setattr(config_writer, "_config_soll_path", lambda: sample_soll)+ monkeypatch.setattr(config_writer, "_config_soll_path", lambda: sample_soll) # i18n-allowmonkeypatch.setattr(config_writer, "_set_user_env_var_winreg", lambda name, value: None)monkeypatch.delenv("JARVIS__TTS__PROVIDER", raising=False)@@ -221,11 +221,11 @@ def test_updates_live_os_environ(assert os.environ.get("JARVIS__TTS__PROVIDER") == "grok-voice"-def test_missing_config_soll_does_not_break_toml(+def test_missing_config_soll_does_not_break_toml( # i18n-allowsample_toml: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:- nonexistent = tmp_path / "no-such-config-soll.json"- monkeypatch.setattr(config_writer, "_config_soll_path", lambda: nonexistent)+ nonexistent = tmp_path / "no-such-config-soll.json" # i18n-allow+ monkeypatch.setattr(config_writer, "_config_soll_path", lambda: nonexistent) # i18n-allowmonkeypatch.setattr(config_writer, "_set_user_env_var", lambda name, value: None)config_writer.set_tts_provider("grok-voice", path=sample_toml)@@ -234,13 +234,13 @@ def test_missing_config_soll_does_not_break_toml(assert not nonexistent.exists()-def test_soll_sync_swallows_write_errors(+def test_soll_sync_swallows_write_errors( # i18n-allowsample_toml: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:- """A broken config-soll.json (invalid JSON) must not break the TOML write."""- broken = tmp_path / "config-soll.json"+ """A broken config-soll.json (invalid JSON) must not break the TOML write.""" # i18n-allow+ broken = tmp_path / "config-soll.json" # i18n-allowbroken.write_text("{ this is not valid json ", encoding="utf-8")- monkeypatch.setattr(config_writer, "_config_soll_path", lambda: broken)+ monkeypatch.setattr(config_writer, "_config_soll_path", lambda: broken) # i18n-allowmonkeypatch.setattr(config_writer, "_set_user_env_var", lambda name, value: None)config_writer.set_tts_provider("grok-voice", path=sample_toml)@@ -249,9 +249,9 @@ def test_soll_sync_swallows_write_errors(def test_winreg_skipped_on_non_win32(- sample_toml: Path, sample_soll: Path, monkeypatch: pytest.MonkeyPatch+ sample_toml: Path, sample_soll: Path, monkeypatch: pytest.MonkeyPatch # i18n-allow) -> None:- monkeypatch.setattr(config_writer, "_config_soll_path", lambda: sample_soll)+ monkeypatch.setattr(config_writer, "_config_soll_path", lambda: sample_soll) # i18n-allowmonkeypatch.setattr(sys, "platform", "linux")def _boom(name: str, value: str) -> None: # pragma: no cover - guard@@ -268,11 +268,11 @@ def test_winreg_skipped_on_non_win32(def test_raises_on_missing_toml(- sample_soll: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+ sample_soll: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch # i18n-allow) -> None:# Production now auto-creates a missing TOML instead of raising# FileNotFoundError (_ensure_writable_config_path, headless-VPS fix).- monkeypatch.setattr(config_writer, "_config_soll_path", lambda: sample_soll)+ monkeypatch.setattr(config_writer, "_config_soll_path", lambda: sample_soll) # i18n-allowmonkeypatch.setattr(config_writer, "_set_user_env_var", lambda name, value: None)p = tmp_path / "nope.toml"@@ -286,13 +286,13 @@ def test_set_tts_provider_cartesia_writes_all_layers_and_preserves_subtable(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:"""set_tts_provider("cartesia") writes all three persistence layers and- leaves the pre-existing [tts.cartesia] subtable and config-soll _comment+ leaves the pre-existing [tts.cartesia] subtable and config-soll _comment # i18n-allowuntouched.Regression guard for the cartesia entry added to _TTS_DEFAULTS: before thatentry existed, switching to cartesia produced an empty defaults dict, leavingthe gemini model name in [tts].model and syncing only "provider" to- config-soll (so voice_de/voice_en stayed pinned to "Charon" from the old+ config-soll (so voice_de/voice_en stayed pinned to "Charon" from the old # i18n-allowprovider — in this case that is correct for cartesia, but the sync must stillhappen so the guard agrees with the TOML)."""@@ -316,10 +316,10 @@ voice_id_de = "b7187e84-fe22-4344-ba4a-bc013fcb533e"encoding="utf-8",)- # config-soll with a _comment and a tts.cartesia sub-table that must be+ # config-soll with a _comment and a tts.cartesia sub-table that must be # i18n-allow# preserved unchanged.- soll = tmp_path / "config-soll.json"- soll.write_text(+ soll = tmp_path / "config-soll.json" # i18n-allow+ soll.write_text( # i18n-allowjson.dumps({"_comment": "do not lose me",@@ -340,7 +340,7 @@ voice_id_de = "b7187e84-fe22-4344-ba4a-bc013fcb533e")env_calls: list[tuple[str, str]] = []- monkeypatch.setattr(config_writer, "_config_soll_path", lambda: soll)+ monkeypatch.setattr(config_writer, "_config_soll_path", lambda: soll) # i18n-allowmonkeypatch.setattr(config_writer,"_set_user_env_var",@@ -357,13 +357,13 @@ voice_id_de = "b7187e84-fe22-4344-ba4a-bc013fcb533e"assert "sonic-3.5" in toml_textassert "b7187e84-fe22-4344-ba4a-bc013fcb533e" in toml_text- # Layer 2: config-soll tts.provider == "cartesia".- soll_data = json.loads(soll.read_text(encoding="utf-8"))- assert soll_data["tts"]["provider"] == "cartesia"+ # Layer 2: config-soll tts.provider == "cartesia". # i18n-allow+ soll_data = json.loads(soll.read_text(encoding="utf-8")) # i18n-allow+ assert soll_data["tts"]["provider"] == "cartesia" # i18n-allow- # The _comment and tts.cartesia sub-table in config-soll are untouched.- assert soll_data["_comment"] == "do not lose me"- assert soll_data["tts.cartesia"]["model_id"] == "sonic-3.5"+ # The _comment and tts.cartesia sub-table in config-soll are untouched. # i18n-allow+ assert soll_data["_comment"] == "do not lose me" # i18n-allow+ assert soll_data["tts.cartesia"]["model_id"] == "sonic-3.5" # i18n-allow# Layer 3: ENV setter called with the canonical var + "cartesia".assert env_calls == [("JARVIS__TTS__PROVIDER", "cartesia")]diff --git a/tests/unit/test_config_writer_worker_sync.py b/tests/unit/test_config_writer_worker_sync.pyindex 6204fef1bb..213c4c26b2 100644--- a/tests/unit/test_config_writer_worker_sync.py+++ b/tests/unit/test_config_writer_worker_sync.py@@ -1,13 +1,13 @@"""Tests for the three-layer ``[brain.worker].provider`` persistence sync.-The Heavy-Task worker provider is pinned in config-soll.json+The Heavy-Task worker provider is pinned in config-soll.json # i18n-allow(``"brain.worker": {"provider": ...}``), so a UI switch that writes onlythe TOML would be rolled back by the drift-guard within 5 minutes — exactlythe BUG that hit ``brain.primary`` before it became 3-layer. The workerswitch must therefore write ALL THREE layers:1. ``jarvis.toml`` ``[brain.worker] provider`` (TOML)- 2. ``scripts/config-soll.json`` ``brain.worker.provider`` (drift-soll)+ 2. ``scripts/config-soll.json`` ``brain.worker.provider`` (drift-soll) # i18n-allow3. ``JARVIS__BRAIN__WORKER__PROVIDER`` User-scope ENV var (boot override)Layers 2 + 3 are best-effort (cloud-first): graceful no-op on a headless VPS,@@ -50,8 +50,8 @@ fallback_provider = "gemini"@pytest.fixture-def sample_soll(tmp_path: Path) -> Path:- p = tmp_path / "config-soll.json"+def sample_soll(tmp_path: Path) -> Path: # i18n-allow+ p = tmp_path / "config-soll.json" # i18n-allowp.write_text(json.dumps({@@ -73,9 +73,9 @@ def sample_soll(tmp_path: Path) -> Path:def test_writes_all_three_layers(- sample_toml: Path, sample_soll: Path, monkeypatch: pytest.MonkeyPatch+ sample_toml: Path, sample_soll: Path, monkeypatch: pytest.MonkeyPatch # i18n-allow) -> None:- monkeypatch.setattr(config_writer, "_config_soll_path", lambda: sample_soll)+ monkeypatch.setattr(config_writer, "_config_soll_path", lambda: sample_soll) # i18n-allowenv_calls: list[tuple[str, str]] = []monkeypatch.setattr(config_writer, "_set_user_env_var",@@ -91,18 +91,18 @@ def test_writes_all_three_layers(# brain.primary must be untouched (the router stays separate).assert 'primary = "gemini"' in toml_raw- # Layer 2: config-soll.json flat "brain.worker" key.- soll = json.loads(sample_soll.read_text(encoding="utf-8"))- assert soll["brain.worker"]["provider"] == "gemini"+ # Layer 2: config-soll.json flat "brain.worker" key. # i18n-allow+ soll = json.loads(sample_soll.read_text(encoding="utf-8")) # i18n-allow+ assert soll["brain.worker"]["provider"] == "gemini" # i18n-allow# Layer 3: ENV var (new name post-rename).assert env_calls == [("JARVIS__BRAIN__WORKER__PROVIDER", "gemini")]def test_toml_preserves_sibling_keys(- sample_toml: Path, sample_soll: Path, monkeypatch: pytest.MonkeyPatch+ sample_toml: Path, sample_soll: Path, monkeypatch: pytest.MonkeyPatch # i18n-allow) -> None:- monkeypatch.setattr(config_writer, "_config_soll_path", lambda: sample_soll)+ monkeypatch.setattr(config_writer, "_config_soll_path", lambda: sample_soll) # i18n-allowmonkeypatch.setattr(config_writer, "_set_user_env_var", lambda name, value: None)config_writer.set_worker_provider("openai", path=sample_toml)@@ -114,30 +114,30 @@ def test_toml_preserves_sibling_keys(assert 'model = ""' in toml_raw-def test_config_soll_preserves_other_keys(- sample_toml: Path, sample_soll: Path, monkeypatch: pytest.MonkeyPatch+def test_config_soll_preserves_other_keys( # i18n-allow+ sample_toml: Path, sample_soll: Path, monkeypatch: pytest.MonkeyPatch # i18n-allow) -> None:- monkeypatch.setattr(config_writer, "_config_soll_path", lambda: sample_soll)+ monkeypatch.setattr(config_writer, "_config_soll_path", lambda: sample_soll) # i18n-allowmonkeypatch.setattr(config_writer, "_set_user_env_var", lambda name, value: None)config_writer.set_worker_provider("openrouter", path=sample_toml)- soll = json.loads(sample_soll.read_text(encoding="utf-8"))- assert soll["brain.worker"]["provider"] == "openrouter"+ soll = json.loads(sample_soll.read_text(encoding="utf-8")) # i18n-allow+ assert soll["brain.worker"]["provider"] == "openrouter" # i18n-allow# Other keys in the block + other tables untouched.- assert soll["brain.worker"]["fallback_provider"] == "gemini"- assert soll["_comment"] == "do not lose me"- assert soll["brain"]["primary"] == "gemini"- assert soll["tts"]["provider"] == "gemini-flash-tts"+ assert soll["brain.worker"]["fallback_provider"] == "gemini" # i18n-allow+ assert soll["_comment"] == "do not lose me" # i18n-allow+ assert soll["brain"]["primary"] == "gemini" # i18n-allow+ assert soll["tts"]["provider"] == "gemini-flash-tts" # i18n-allowdef test_creates_worker_block_if_missing(- tmp_path: Path, sample_soll: Path, monkeypatch: pytest.MonkeyPatch+ tmp_path: Path, sample_soll: Path, monkeypatch: pytest.MonkeyPatch # i18n-allow) -> None:"""A TOML with [brain] but no [brain.worker] gets the block created."""toml = tmp_path / "jarvis.toml"toml.write_text('[brain]\nprimary = "gemini"\n', encoding="utf-8")- monkeypatch.setattr(config_writer, "_config_soll_path", lambda: sample_soll)+ monkeypatch.setattr(config_writer, "_config_soll_path", lambda: sample_soll) # i18n-allowmonkeypatch.setattr(config_writer, "_set_user_env_var", lambda name, value: None)config_writer.set_worker_provider("grok", path=toml)@@ -147,11 +147,11 @@ def test_creates_worker_block_if_missing(assert 'provider = "grok"' in raw-def test_missing_config_soll_does_not_break_toml(+def test_missing_config_soll_does_not_break_toml( # i18n-allowsample_toml: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:- nonexistent = tmp_path / "no-such-config-soll.json"- monkeypatch.setattr(config_writer, "_config_soll_path", lambda: nonexistent)+ nonexistent = tmp_path / "no-such-config-soll.json" # i18n-allow+ monkeypatch.setattr(config_writer, "_config_soll_path", lambda: nonexistent) # i18n-allowmonkeypatch.setattr(config_writer, "_set_user_env_var", lambda name, value: None)config_writer.set_worker_provider("gemini", path=sample_toml)@@ -161,14 +161,14 @@ def test_missing_config_soll_does_not_break_toml(def test_missing_toml_is_created(- sample_soll: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+ sample_soll: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch # i18n-allow) -> None:"""A missing TOML file is auto-created (headless VPS / first-run path)._ensure_writable_config_path creates an empty file rather than raisingFileNotFoundError, so the writer works on a fresh VPS install."""- monkeypatch.setattr(config_writer, "_config_soll_path", lambda: sample_soll)+ monkeypatch.setattr(config_writer, "_config_soll_path", lambda: sample_soll) # i18n-allowmonkeypatch.setattr(config_writer, "_set_user_env_var", lambda name, value: None)new_toml = tmp_path / "nope.toml"@@ -182,9 +182,9 @@ def test_missing_toml_is_created(def test_updates_live_os_environ(- sample_toml: Path, sample_soll: Path, monkeypatch: pytest.MonkeyPatch+ sample_toml: Path, sample_soll: Path, monkeypatch: pytest.MonkeyPatch # i18n-allow) -> None:- monkeypatch.setattr(config_writer, "_config_soll_path", lambda: sample_soll)+ monkeypatch.setattr(config_writer, "_config_soll_path", lambda: sample_soll) # i18n-allowmonkeypatch.setattr(config_writer, "_set_user_env_var_winreg", lambda name, value: None)monkeypatch.delenv("JARVIS__BRAIN__WORKER__PROVIDER", raising=False)@@ -197,15 +197,15 @@ def test_updates_live_os_environ(# ---------------------------------------------------------------------------# [brain.worker].model — the dedicated Jarvis-Agent LLM override (C2).-# Also pinned in config-soll.json, so the same 3-layer rule applies: a+# Also pinned in config-soll.json, so the same 3-layer rule applies: a # i18n-allow# TOML-only write would be reverted by the drift-guard within minutes.# ---------------------------------------------------------------------------def test_set_model_writes_all_three_layers(- sample_toml: Path, sample_soll: Path, monkeypatch: pytest.MonkeyPatch+ sample_toml: Path, sample_soll: Path, monkeypatch: pytest.MonkeyPatch # i18n-allow) -> None:- monkeypatch.setattr(config_writer, "_config_soll_path", lambda: sample_soll)+ monkeypatch.setattr(config_writer, "_config_soll_path", lambda: sample_soll) # i18n-allowenv_calls: list[tuple[str, str]] = []monkeypatch.setattr(config_writer, "_set_user_env_var",@@ -220,18 +220,18 @@ def test_set_model_writes_all_three_layers(# provider untouched.assert 'provider = "claude-api"' in toml_raw- soll = json.loads(sample_soll.read_text(encoding="utf-8"))- assert soll["brain.worker"]["model"] == "claude-sonnet-4-6"- assert soll["brain.worker"]["provider"] == "claude-api"+ soll = json.loads(sample_soll.read_text(encoding="utf-8")) # i18n-allow+ assert soll["brain.worker"]["model"] == "claude-sonnet-4-6" # i18n-allow+ assert soll["brain.worker"]["provider"] == "claude-api" # i18n-allowassert env_calls == [("JARVIS__BRAIN__WORKER__MODEL", "claude-sonnet-4-6")]def test_set_model_empty_string_resets_to_provider_default(- sample_toml: Path, sample_soll: Path, monkeypatch: pytest.MonkeyPatch+ sample_toml: Path, sample_soll: Path, monkeypatch: pytest.MonkeyPatch # i18n-allow) -> None:"""Empty model is the documented sentinel: provider's deep model wins."""- monkeypatch.setattr(config_writer, "_config_soll_path", lambda: sample_soll)+ monkeypatch.setattr(config_writer, "_config_soll_path", lambda: sample_soll) # i18n-allowenv_calls: list[tuple[str, str]] = []monkeypatch.setattr(config_writer, "_set_user_env_var",@@ -243,16 +243,16 @@ def test_set_model_empty_string_resets_to_provider_default(toml_raw = sample_toml.read_text(encoding="utf-8")assert 'model = ""' in toml_raw- soll = json.loads(sample_soll.read_text(encoding="utf-8"))- assert soll["brain.worker"]["model"] == ""+ soll = json.loads(sample_soll.read_text(encoding="utf-8")) # i18n-allow+ assert soll["brain.worker"]["model"] == "" # i18n-allowassert env_calls[-1] == ("JARVIS__BRAIN__WORKER__MODEL", "")-def test_set_model_missing_soll_does_not_break_toml(+def test_set_model_missing_soll_does_not_break_toml( # i18n-allowsample_toml: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:- nonexistent = tmp_path / "no-such-config-soll.json"- monkeypatch.setattr(config_writer, "_config_soll_path", lambda: nonexistent)+ nonexistent = tmp_path / "no-such-config-soll.json" # i18n-allow+ monkeypatch.setattr(config_writer, "_config_soll_path", lambda: nonexistent) # i18n-allowmonkeypatch.setattr(config_writer, "_set_user_env_var", lambda name, value: None)config_writer.set_sub_jarvis_model("gemini-3.1-pro-preview", path=sample_toml)diff --git a/tests/unit/test_core_memory.py b/tests/unit/test_core_memory.pyindex 79cb899f23..c6bfc125e0 100644--- a/tests/unit/test_core_memory.py+++ b/tests/unit/test_core_memory.py@@ -1,4 +1,4 @@-"""Unit-Tests für CoreMemory."""+"""Unit tests for CoreMemory."""from __future__ import annotationsimport json@@ -18,13 +18,13 @@ def test_load_creates_defaults(tmp_path):def test_add_and_remove_fact(tmp_path):path = tmp_path / "core.json"mem = CoreMemory.load(path)- mem.add_fact("Ich heiße Harald", category="identity")+ mem.add_fact("Ich heiße Harald", category="identity") # i18n-allowmem.add_fact("Ich mag Python", category="preference")# Persistencereloaded = CoreMemory.load(path)facts = reloaded.get_section("user_facts")- assert "Ich heiße Harald" in facts["identity"]+ assert "Ich heiße Harald" in facts["identity"] # i18n-allowassert "Ich mag Python" in facts["preference"]# Remove@@ -43,11 +43,11 @@ def test_dedup_in_add_fact(tmp_path):def test_render_system_prompt_block(tmp_path):path = tmp_path / "core.json"mem = CoreMemory.load(path)- mem.add_fact("Ich heiße Harald", category="identity")+ mem.add_fact("Ich heiße Harald", category="identity") # i18n-allowmem.set_value("current_projects", "Jarvis", "Voice-Assistant in Phase 2")prompt = mem.render_system_prompt_block()assert "Core-Memory" in prompt- assert "Ich heiße Harald" in prompt+ assert "Ich heiße Harald" in prompt # i18n-allowassert "Jarvis" in prompt@@ -55,7 +55,7 @@ def test_corrupt_file_is_backed_up(tmp_path):path = tmp_path / "core.json"path.write_text("not valid json {[", encoding="utf-8")mem = CoreMemory.load(path)- # Backup file erstellt+ # Backup file createdassert (tmp_path / "core.corrupted.json").exists()- # Defaults wieder da+ # Defaults are backassert mem.get_section("persona")["name"] == "Jarvis"diff --git a/tests/unit/test_factory_vision.py b/tests/unit/test_factory_vision.pyindex c17f1c1547..2040c686bb 100644--- a/tests/unit/test_factory_vision.py+++ b/tests/unit/test_factory_vision.py@@ -1,9 +1,8 @@-"""Tests fuer VisionContextProvider-Wiring in build_default_brain (Wave-2 B6).+"""Tests for VisionContextProvider wiring in build_default_brain (Wave-2 B6).-Verifiziert dass `_phase2_full_brain` je nach Config den-`manager._vision_provider` setzt oder auf None laesst. Mockt-`BrainManager` und die schweren Bootstrap-Dependencies aus, damit der-Test schnell und ohne Credentials laeuft.+Verifies that `_phase2_full_brain` sets `manager._vision_provider` or leaves+it at None depending on config. Mocks out `BrainManager` and the heavy+bootstrap dependencies so the test runs fast and without credentials."""from __future__ import annotations@@ -20,16 +19,16 @@ def _call_factory_with_vision_cfg(max_staleness_s: float = 2.0,capture_mode: str = "screenshot",):- """Ruft _phase2_full_brain mit einem heavily-gemockten Bootstrap auf.+ """Calls _phase2_full_brain with a heavily-mocked bootstrap.- Mockt BrainManager + Memory + Tool-Loading weg, damit der Test keine- echten API-Keys / Model-Loads braucht. Wir wollen nur sehen wie- `manager._vision_provider` gesetzt wird basierend auf config.+ Mocks out BrainManager + Memory + tool loading so the test doesn't need+ real API keys / model loads. We only want to see how+ `manager._vision_provider` gets set based on config."""from jarvis.brain import factory as factory_modfrom jarvis.core.config import RouterVisionConfig- # FakeManager: reicht einfach .vision_provider-Assignments durch.+ # FakeManager: just passes through .vision_provider assignments.class _FakeManager:def __init__(self, **kw):self._vision_provider = None@@ -40,7 +39,7 @@ def _call_factory_with_vision_cfg(def _fast_model(self, name):return "fake"- # FakeConfig mit vision-section+ # FakeConfig with a vision sectionfake_vision = RouterVisionConfig(enabled=enabled,refresh_interval_s=refresh_interval_s,@@ -58,7 +57,7 @@ def _call_factory_with_vision_cfg(harness=fake_harness_cfg,)- # Monkeypatch die schweren Dependencies+ # Monkeypatch the heavy dependencieswith patch.object(factory_mod, "BrainManager", _FakeManager), \patch("jarvis.core.config.load_config", return_value=fake_cfg), \patch("jarvis.core.config.DATA_DIR") as mock_data_dir, \@@ -75,7 +74,7 @@ def _call_factory_with_vision_cfg(mock_data_dir.mkdir = lambda **kw: Nonemock_data_dir.__truediv__ = lambda self, other: SimpleNamespace()- # Workspace.ensure gibt ein SimpleNamespace mit den path-Attributen zurueck+ # Workspace.ensure returns a SimpleNamespace with the path attributes_ws.ensure.return_value = SimpleNamespace(user_path="/tmp/user.md",soul_path="/tmp/soul.md",@@ -86,17 +85,17 @@ def _call_factory_with_vision_cfg(def test_factory_wires_vision_provider_when_enabled():- """config.brain.router.vision.enabled=True -> manager._vision_provider gesetzt."""+ """config.brain.router.vision.enabled=True -> manager._vision_provider is set."""try:manager = _call_factory_with_vision_cfg(enabled=True)except Exception as exc:- pytest.skip(f"factory-internals haben sich geaendert, skipping: {exc}")+ pytest.skip(f"factory internals have changed, skipping: {exc}")assert hasattr(manager, "_vision_provider")- # Bei enabled=True wird der Provider instantiiert — es sei denn Import-Error- # o.ae. fuehrt zu None (try/except im factory-Code deckt das ab).- # Der Test ist primaer dafuer dass das Attribut ueberhaupt gesetzt wird- # und nicht None-left-over ist wenn Config aktiv.+ # With enabled=True the provider gets instantiated — unless an import+ # error or similar leads to None (try/except in the factory code covers+ # that). The test is primarily there to check that the attribute gets+ # set at all and isn't left over as None when config is active.if manager._vision_provider is not None:from jarvis.vision.context_provider import VisionContextProviderassert isinstance(manager._vision_provider, VisionContextProvider)@@ -107,12 +106,12 @@ def test_factory_skips_vision_when_disabled():try:manager = _call_factory_with_vision_cfg(enabled=False)except Exception as exc:- pytest.skip(f"factory-internals haben sich geaendert, skipping: {exc}")+ pytest.skip(f"factory internals have changed, skipping: {exc}")assert hasattr(manager, "_vision_provider")assert manager._vision_provider is Nonedef test_factory_shutdown_stops_provider():- """Shutdown-Hook ist offen — AC16-Follow-up."""- pytest.skip("manager.close()/shutdown() noch nicht implementiert — AC16-Follow-up")+ """Shutdown hook is open — AC16 follow-up."""+ pytest.skip("manager.close()/shutdown() not implemented yet — AC16 follow-up")diff --git a/tests/unit/test_harness_manager.py b/tests/unit/test_harness_manager.pyindex 01b89f249f..a9a01cc4e7 100644--- a/tests/unit/test_harness_manager.py+++ b/tests/unit/test_harness_manager.py@@ -1,4 +1,4 @@-"""Unit-Tests für HarnessManager mit FakeHarness."""+"""Unit tests for HarnessManager with FakeHarness."""from __future__ import annotationsimport pytestdiff --git a/tests/unit/test_intent_router.py b/tests/unit/test_intent_router.pyindex 6853ba19d4..39c9880252 100644--- a/tests/unit/test_intent_router.py+++ b/tests/unit/test_intent_router.py@@ -1,7 +1,7 @@-"""Unit-Tests für Intent-Level-Router (fast/deep/code Provider-Selection).+"""Unit tests for the intent-level router (fast/deep/code provider selection).-Nicht zu verwechseln mit dem Phase-5-Tier-Router (`jarvis/brain/router.py`),-der Action-Targets (trivial/direct_action/spawn_worker) klassifiziert.+Not to be confused with the Phase-5 tier router (`jarvis/brain/router.py`),+which classifies action targets (trivial/direct_action/spawn_worker)."""from __future__ import annotations@@ -11,15 +11,15 @@ from jarvis.brain.intent_router import classify@pytest.mark.parametrize("text", [- "öffne notepad",- "öffne ein Terminal",+ "öffne notepad", # i18n-allow+ "öffne ein Terminal", # i18n-allow"spawn 5 terminals",- "mach den Browser auf",+ "mach den Browser auf", # i18n-allow"starte Chrome","klick auf submit",- "merk dir ich heiße Harald",+ "merk dir ich heiße Harald", # i18n-allow"sag hi",- "wie spät ist es?",+ "wie spät ist es?", # i18n-allow"hallo","danke","open notepad",@@ -34,14 +34,14 @@ def test_fast_intents(text):@pytest.mark.parametrize("text", ["recherchiere mir die aktuelle Studienlage zu GPT-5","analysier das Design meines Prompts",- "erklär mir wie Retrieval-Augmented-Generation funktioniert",- "plane mir eine Architektur für ein Multi-Agent-System",- "vergleich Haiku gegen Opus für Reasoning",- "schreib mir eine Email an den Kunden, warum wir zwei Wochen Verzug haben",- "überleg dir gründlich was die richtige Strategie ist",+ "erklär mir wie Retrieval-Augmented-Generation funktioniert", # i18n-allow+ "plane mir eine Architektur für ein Multi-Agent-System", # i18n-allow+ "vergleich Haiku gegen Opus für Reasoning", # i18n-allow+ "schreib mir eine Email an den Kunden, warum wir zwei Wochen Verzug haben", # i18n-allow+ "überleg dir gründlich was die richtige Strategie ist", # i18n-allow"fasse das Video in 3 Punkten zusammen",- "baue mir ein Konzept für eine Voice-App, die offline funktioniert",- "warum zeigt mein Build einen N+1 Query-Fehler trotz eager-loading?",+ "baue mir ein Konzept für eine Voice-App, die offline funktioniert", # i18n-allow+ "warum zeigt mein Build einen N+1 Query-Fehler trotz eager-loading?", # i18n-allow"think hard about the tradeoffs","analyze this architecture",])@@ -54,7 +54,7 @@ def test_deep_intents(text):"implementier mir eine LRU-Cache-Klasse","refactor den UserService","fix bug im Login-Handler",- "code review für diese PR",+ "code review für diese PR", # i18n-allow"debug den Pipeline-Stall",])def test_code_intents(text):@@ -68,5 +68,5 @@ def test_empty_defaults_to_fast():def test_long_unknown_falls_to_deep():- long_text = ("Ich frage mich schon länger, wie man das " * 5) + "machen könnte?"+ long_text = ("Ich frage mich schon länger, wie man das " * 5) + "machen könnte?" # i18n-allowassert classify(long_text).level == "deep"diff --git a/tests/unit/test_iteration_budget.py b/tests/unit/test_iteration_budget.pyindex f40d2e0284..9e17b4121f 100644--- a/tests/unit/test_iteration_budget.py+++ b/tests/unit/test_iteration_budget.py@@ -1,4 +1,4 @@-"""Unit-Tests für IterationBudget."""+"""Unit tests for IterationBudget."""from __future__ import annotationsfrom jarvis.brain import IterationBudgetdiff --git a/tests/unit/test_jarvis_agent_board_listing.py b/tests/unit/test_jarvis_agent_board_listing.pyindex 8609db3ee4..a74b9db9b6 100644--- a/tests/unit/test_jarvis_agent_board_listing.py+++ b/tests/unit/test_jarvis_agent_board_listing.py@@ -113,7 +113,7 @@ async def test_worker_spawn_and_approval_update_node() -> None:tokens_used=123,cost_usd=0.02,wall_ms=1500,- summary_de="fertig",+ summary_de="fertig", # i18n-allowsummary_en="done",),)diff --git a/tests/unit/test_protocols_image_block.py b/tests/unit/test_protocols_image_block.pyindex f18f6f1420..c892431816 100644--- a/tests/unit/test_protocols_image_block.py+++ b/tests/unit/test_protocols_image_block.py@@ -1,11 +1,11 @@-"""Unit-Tests für ImageBlock + BrainMessage.images (Phase Wave-1, B1).--Sichert:-- ImageBlock ist frozen (keine Mutation nach Konstruktion).-- source_hash defaulted auf leer-String.-- BrainMessage.images defaulted auf leeres Tuple.-- BrainMessage speichert übergebene Images als Tuple.-- Backwards-Compat: alte positional-arg Aufrufe (role, content) bleiben funktional.+"""Unit tests for ImageBlock + BrainMessage.images (Phase Wave-1, B1).++Covers:+- ImageBlock is frozen (no mutation after construction).+- source_hash defaults to an empty string.+- BrainMessage.images defaults to an empty tuple.+- BrainMessage stores passed-in images as a tuple.+- Backwards compat: old positional-arg calls (role, content) still work."""from __future__ import annotations@@ -17,27 +17,27 @@ from jarvis.core.protocols import BrainMessage, ImageBlockdef test_brain_message_default_no_images() -> None:- """BrainMessage ohne images-Argument hat leeres Tuple."""+ """BrainMessage without an images argument has an empty tuple."""msg = BrainMessage(role="user", content="hi")assert msg.images == ()assert isinstance(msg.images, tuple)def test_image_block_is_frozen() -> None:- """ImageBlock ist immutable — Mutation wirft FrozenInstanceError."""+ """ImageBlock is immutable — mutation raises FrozenInstanceError."""block = ImageBlock(mime="image/png", data_b64="abc")with pytest.raises(FrozenInstanceError):block.mime = "image/jpeg" # type: ignore[misc]def test_image_block_source_hash_defaults_empty() -> None:- """source_hash ist optional und defaulted auf leeren String."""+ """source_hash is optional and defaults to an empty string."""block = ImageBlock(mime="image/png", data_b64="abc")assert block.source_hash == ""def test_brain_message_with_images_stores_tuple() -> None:- """Übergebene Images werden als Tuple in BrainMessage gespeichert."""+ """Passed-in images are stored as a tuple in BrainMessage."""block = ImageBlock(mime="image/png", data_b64="xyz", source_hash="hash-1")msg = BrainMessage(role="user", content="schau dir das an", images=(block,))assert isinstance(msg.images, tuple)@@ -47,7 +47,7 @@ def test_brain_message_with_images_stores_tuple() -> None:def test_brain_message_backwards_compat_positional() -> None:- """Bestehende positional-arg Aufrufe BrainMessage("user", "hi") klappen weiter."""+ """Existing positional-arg calls BrainMessage("user", "hi") still work."""msg = BrainMessage("user", "hi")assert msg.role == "user"assert msg.content == "hi"diff --git a/tests/unit/test_provider_spec.py b/tests/unit/test_provider_spec.pyindex 9f3f3c6de5..1147ae9290 100644--- a/tests/unit/test_provider_spec.py+++ b/tests/unit/test_provider_spec.py@@ -1,8 +1,8 @@-"""Integritäts-Tests für die deklarative ProviderSpec-Liste.+"""Integrity tests for the declarative ProviderSpec list.-Wichtig: jeder secret_key, der in PROVIDERS referenziert wird, muss auch im-Setup-Wizard SECRETS-Set existieren — sonst läuft der API-Endpoint-POST /api/secrets/{key} ins Whitelist-Loch.+Important: every secret_key referenced in PROVIDERS must also exist in the+setup wizard's SECRETS set — otherwise the API endpoint+POST /api/secrets/{key} falls into the whitelist hole."""from __future__ import annotations@@ -28,7 +28,7 @@ def test_every_secret_key_exists_in_wizard() -> None:for key in spec.secret_keys:assert key in wizard_keys, (f"Provider '{spec.id}' referenziert secret_key '{key}', "- f"der nicht in wizard.SECRETS deklariert ist"+ f"is not declared in wizard.SECRETS")@@ -83,11 +83,11 @@ def test_all_secret_keys_collects_unique_set() -> None:assert "anthropic_api_key" in keysassert "gemini_api_key" in keysassert "openai_api_key" in keys- assert "elevenlabs_api_key" not in keys, "ElevenLabs ist Dead-Code, darf nicht referenziert sein"+ assert "elevenlabs_api_key" not in keys, "ElevenLabs is dead code and must not be referenced"def test_no_hardcoded_model_names_in_specs() -> None:- """Defensives Smoke-Check: Modellnamen-Indikatoren dürfen NICHT im Spec auftauchen."""+ """Defensive smoke check: model-name indicators must NOT appear in a spec."""forbidden_substrings = ["claude-3", "claude-4", "claude-opus", "claude-haiku", "claude-sonnet","gpt-4", "gpt-5", "o1-", "o3-",@@ -97,7 +97,7 @@ def test_no_hardcoded_model_names_in_specs() -> None:haystack = (spec.id + spec.label).lower()for needle in forbidden_substrings:assert needle not in haystack, (- f"Provider '{spec.id}' enthält Modellnamen '{needle}' — laut Spec verboten"+ f"Provider '{spec.id}' contains model name '{needle}' — forbidden by the spec")@@ -108,7 +108,7 @@ def test_provider_spec_is_frozen_dataclass() -> None:spec.id = "mutated" # type: ignore[misc]except Exception:return- raise AssertionError("ProviderSpec sollte frozen sein")+ raise AssertionError("ProviderSpec should be frozen")# ── New: per-provider credential help + billing classification ───────────────diff --git a/tests/unit/test_recall_store.py b/tests/unit/test_recall_store.pyindex f0390d0481..5590bcf1c2 100644--- a/tests/unit/test_recall_store.py+++ b/tests/unit/test_recall_store.py@@ -1,4 +1,4 @@-"""Unit-Tests für RecallStore (FTS5 + KV)."""+"""Unit tests for RecallStore (FTS5 + KV)."""from __future__ import annotationsfrom uuid import uuid4@@ -47,7 +47,7 @@ async def test_bm25_ranking(store):await store.record_message(trace_id=tid, role="user", text="apple banana cherry")await store.record_message(trace_id=tid, role="user", text="apple apple apple")results = await store.search_messages("apple", k=5)- # Die Message mit mehr "apple"-Vorkommen sollte besser ranken (niedrigerer bm25 score)+ # The message with more "apple" occurrences should rank better (lower bm25 score)assert len(results) == 2ranks = [r["rank"] for r in results]assert ranks[0] <= ranks[1]diff --git a/tests/unit/test_risk_tier.py b/tests/unit/test_risk_tier.pyindex beb32dac16..3bce9214b7 100644--- a/tests/unit/test_risk_tier.py+++ b/tests/unit/test_risk_tier.py@@ -1,4 +1,4 @@-"""Unit-Tests für RiskTierEvaluator."""+"""Unit tests for RiskTierEvaluator."""from __future__ import annotationsimport logging@@ -94,7 +94,7 @@ def test_needs_confirmation_whitelist_skips():# Per-action risk (forensic 2026-06-19, session dc533e39): a read-only# ``gmail action=list_messages`` (the morning-routine "check unread mail"# step) was forced through the ask-tier confirmation and Jarvis spoke-# "Soll ich die E-Mail wirklich senden?" for a calendar question. The+# "Do you really want me to send the email?" for a calendar question. The# whole gmail tool declared risk_tier="ask" and ``evaluate`` only ever# looked at ``tool.risk_tier``, never at the action. A tool may now expose# an optional ``risk_tier_for_args(args)`` hook so reads stay ``safe`` anddiff --git a/tests/unit/test_router_delegator_policy.py b/tests/unit/test_router_delegator_policy.pyindex fa0a721a5d..a1cddda370 100644--- a/tests/unit/test_router_delegator_policy.py+++ b/tests/unit/test_router_delegator_policy.py@@ -20,7 +20,7 @@ from jarvis.brain.router import SYSTEM_PROMPTclass TestDelegatorPolicyInPrompt:def test_delegator_principle_present(self) -> None:assert "Delegator" in SYSTEM_PROMPT or "Dispatcher" in SYSTEM_PROMPT- assert "Millisekunden" in SYSTEM_PROMPT or "reasonst nicht lange" in SYSTEM_PROMPT.lower()+ assert "Millisekunden" in SYSTEM_PROMPT or "reasonst nicht lange" in SYSTEM_PROMPT.lower() # i18n-allowdef test_three_categories_named(self) -> None:assert "TRIVIAL" in SYSTEM_PROMPT@@ -29,7 +29,7 @@ class TestDelegatorPolicyInPrompt:def test_spawn_is_reserved_for_heavy_tasks(self) -> None:"""The heavy-only doctrine must be pinned verbatim (2026-06-10)."""- assert "NUR fuer wirklich schwere" in SYSTEM_PROMPT, (+ assert "NUR fuer wirklich schwere" in SYSTEM_PROMPT, ( # i18n-allow"spawn_worker must be explicitly reserved for genuinely heavy ""tasks — the over-spawning complaint of 2026-06-10.")diff --git a/tests/unit/test_router_vision_config.py b/tests/unit/test_router_vision_config.pyindex 3063cf9ea9..3f70326aec 100644--- a/tests/unit/test_router_vision_config.py+++ b/tests/unit/test_router_vision_config.py@@ -1,8 +1,8 @@-"""Tests für RouterVisionConfig (Wave-1 B4).+"""Tests for RouterVisionConfig (Wave-1 B4).-Prüft Defaults der Pydantic-Sub-Config und die Verdrahtung in `jarvis.toml`-unter `[brain.router.vision]`. Alle Felder MÜSSEN Defaults haben — bestehende-Configs ohne die Section müssen sauber laden.+Checks the Pydantic sub-config's defaults and the wiring into `jarvis.toml`+under `[brain.router.vision]`. All fields MUST have defaults — existing+configs without the section must still load cleanly."""from __future__ import annotations@@ -35,18 +35,18 @@ def test_router_vision_config_defaults():def test_router_vision_config_loaded_from_jarvis_toml():- """Lädt die globale jarvis.toml via tomllib UND via load_config() und- prüft dass `[brain.router.vision]` korrekt in RouterVisionConfig landet.+ """Loads the global jarvis.toml via tomllib AND via load_config() and+ checks that `[brain.router.vision]` correctly lands in RouterVisionConfig.- Zwei-Ebenen-Test:- 1. Raw-TOML — garantiert dass die Section mit erwarteten Keys drin steht.- 2. load_config() — garantiert dass Pydantic die Section auto-unmarshaled- in `cfg.brain.router.vision` (RouterVisionConfig).+ Two-layer test:+ 1. Raw TOML — guarantees the section exists with the expected keys.+ 2. load_config() — guarantees Pydantic auto-unmarshals the section+ into `cfg.brain.router.vision` (RouterVisionConfig)."""toml_path = DEFAULT_CONFIG_FILE- assert toml_path.exists(), f"jarvis.toml nicht an {toml_path}"+ assert toml_path.exists(), f"jarvis.toml not found at {toml_path}"- # 1. Raw-TOML-Layer — Section existiert mit den Plan-Werten.+ # 1. Raw-TOML layer — section exists with the plan values.with toml_path.open("rb") as f:data = tomllib.load(f)vsec = data["brain"]["router"]["vision"]diff --git a/tests/unit/test_streaming_aggregate.py b/tests/unit/test_streaming_aggregate.pyindex bd8dfb9fd7..3e631e659b 100644--- a/tests/unit/test_streaming_aggregate.py+++ b/tests/unit/test_streaming_aggregate.py@@ -1,4 +1,4 @@-"""Unit-Tests für den StreamingAggregate-Akkumulator."""+"""Unit tests for the StreamingAggregate accumulator."""from __future__ import annotationsfrom collections.abc import AsyncIteratordiff --git a/tests/unit/test_subprocess_harness_concurrency.py b/tests/unit/test_subprocess_harness_concurrency.pyindex d4e9b8f00f..5f18ba5be7 100644--- a/tests/unit/test_subprocess_harness_concurrency.py+++ b/tests/unit/test_subprocess_harness_concurrency.py@@ -1,13 +1,13 @@-"""Regressions-Test: ``SubprocessHarness.invoke()`` ist concurrency-safe.+"""Regression test: ``SubprocessHarness.invoke()`` is concurrency-safe.-Bug 2026-04-29: ``multi_spawn`` mit 3 parallelen openclaw-Calls schlug in-Production deterministisch in <10ms fehl. Wurzelursache: ``HarnessManager.get()``-cached EINE ``OpenClawHarness``-Instance; concurrent ``invoke()``-Calls auf-derselben Instance racen auf ``self._process`` und ``self._cancelled``.+Bug 2026-04-29: ``multi_spawn`` with 3 parallel openclaw calls failed+deterministically in production in <10ms. Root cause: ``HarnessManager.get()``+caches ONE ``OpenClawHarness`` instance; concurrent ``invoke()`` calls on+the same instance raced on ``self._process`` and ``self._cancelled``.-Fix: invocation-lokale Variablen + ``self._active_processes: set`` fuer-cancel-Tracking. Dieser Test reproduziert das Pattern (3 parallele ``invoke()``-auf derselben Instance) und stellt sicher, dass alle drei sauber durchlaufen.+Fix: invocation-local variables + ``self._active_processes: set`` for+cancel tracking. This test reproduces the pattern (3 parallel ``invoke()``+calls on the same instance) and makes sure all three complete cleanly."""from __future__ import annotations@@ -21,11 +21,11 @@ from jarvis.harness.base import SubprocessHarnessclass _SlowFakeHarness(SubprocessHarness):- """Faked Subprocess: kein echter Spawn, asyncio.sleep simuliert Subprocess-Run.+ """Faked subprocess: no real spawn, asyncio.sleep simulates the subprocess run.- Wir ueberschreiben ``invoke`` direkt um den Subprocess-Spawn zu vermeiden- (sonst muessten wir python-CLI o.ae. spawnen). Der Test prueft dass mehrere- parallele invoke()-Calls ihre eigenen lokalen Variablen behalten.+ We override ``invoke`` directly to avoid the subprocess spawn+ (otherwise we'd have to spawn a python CLI or similar). The test checks+ that multiple parallel invoke() calls keep their own local variables."""name = "slow-fake"@@ -33,7 +33,7 @@ class _SlowFakeHarness(SubprocessHarness):def __init__(self) -> None:super().__init__()self.invocation_count = 0- # Lokale Tracking-Variablen — werden VON jedem invoke()-Call inkrementiert.+ # Local tracking variables — incremented BY each invoke() call.self.concurrent_peak = 0self._active = 0@@ -61,7 +61,7 @@ class _SlowFakeHarness(SubprocessHarness):@pytest.mark.asyncioasync def test_concurrent_invoke_calls_dont_race():- """3 parallele ``invoke()`` auf derselben Instance liefern alle ihren Output."""+ """3 parallel ``invoke()`` calls on the same instance all deliver their output."""harness = _SlowFakeHarness()async def collect(prompt: str) -> list[HarnessResult]:@@ -85,7 +85,7 @@ async def test_concurrent_invoke_calls_dont_race():f"Race-Condition oder Sequential-Lock?")- # Jede invocation hat ihre EIGENEN chunks (kein Vermischen via shared state).+ # Each invocation has its OWN chunks (no mixing via shared state).a_chunks = "".join(c.stdout for c in results[0] if c.stdout)b_chunks = "".join(c.stdout for c in results[1] if c.stdout)c_chunks = "".join(c.stdout for c in results[2] if c.stdout)@@ -96,7 +96,7 @@ async def test_concurrent_invoke_calls_dont_race():@pytest.mark.asyncioasync def test_subprocess_harness_init_has_active_processes_set():- """SubprocessHarness.__init__ muss ``_active_processes`` initialisieren."""+ """SubprocessHarness.__init__ must initialize ``_active_processes``."""h = _SlowFakeHarness()assert hasattr(h, "_active_processes")assert h._active_processes == set()@@ -123,7 +123,7 @@ async def test_cancel_killed_all_active_processes():await h.cancel()- # Beide wurden terminate'd+ # Both were terminate'dproc1.terminate.assert_called_once()proc2.terminate.assert_called_once()assert h._cancelled is Truediff --git a/tests/unit/test_tier_defaults.py b/tests/unit/test_tier_defaults.pyindex 605bb036e9..37ce5c1881 100644--- a/tests/unit/test_tier_defaults.py+++ b/tests/unit/test_tier_defaults.py@@ -1,4 +1,4 @@-"""Unit-Tests fuer TIER_DEFAULTS_BY_PROVIDER, _resolve_tier_model und get_tier_default_model."""+"""Unit tests for TIER_DEFAULTS_BY_PROVIDER, _resolve_tier_model, and get_tier_default_model."""from __future__ import annotationsimport pytest@@ -20,19 +20,19 @@ class TestTierDefaultsCatalog:assert required <= set(TIER_DEFAULTS_BY_PROVIDER["deep"])def test_router_models_look_fast(self):- # 2026-04-29 Update: GPT-5.5 hat keine -mini-Variante released; OpenAI- # sagt selbst "GPT-5.5 hat per-token-Latenz wie GPT-5.4". Fast-Tier-- # Heuristik akzeptiert daher auch Frontier-Hauptmodelle.- # Siehe TIER_DEFAULTS_BY_PROVIDER-Doc in jarvis/brain/manager.py.+ # 2026-04-29 update: GPT-5.5 has no -mini variant released; OpenAI+ # itself says "GPT-5.5 has per-token latency like GPT-5.4". The fast-tier+ # heuristic therefore also accepts frontier main models.+ # See the TIER_DEFAULTS_BY_PROVIDER doc in jarvis/brain/manager.py.for provider, model in TIER_DEFAULTS_BY_PROVIDER["router"].items():if provider == "openrouter":continue # deliberate free-model default; not a fast-tier slugif provider == "gemini":- continue # hat keinen Fast-Mode+ continue # has no fast modeif provider == "openai" and model in {"gpt-5.5", "gpt-5"}:- continue # Frontier-Hauptmodell ohne -mini-Suffix+ continue # frontier main model without -mini suffixassert any(tag in model.lower() for tag in ("haiku", "flash", "mini", "fast", "chat", "small")), \- f"{provider}: {model} sieht nicht nach Fast-Tier aus"+ f"{provider}: {model} does not look like a fast tier"def test_sub_models_look_frontier(self):for provider, model in TIER_DEFAULTS_BY_PROVIDER["deep"].items():@@ -40,7 +40,7 @@ class TestTierDefaultsCatalog:continue # deliberate free-model default; not a frontier slugassert any(tag in model.lower() for tag in("fable", "opus", "pro", "large", "reasoner", "gpt-4", "gpt-5")), \- f"{provider}: {model} sieht nicht nach Frontier-Tier aus"+ f"{provider}: {model} does not look like a frontier tier"def test_claude_deep_tier_is_reachable_opus_never_fable(self):"""Maintainer decision 2026-06-14 (supersedes the 2026-06-10 fable@@ -78,7 +78,7 @@ class TestResolveTierModel:assert _resolve_tier_model("super_frontier", "claude-api", None) == ""def test_deep_gemini_default(self):- # 2026-04-29: Frontier ueberall (User-Mandat).+ # 2026-04-29: frontier everywhere (user mandate).assert _resolve_tier_model("deep", "gemini", None) == "gemini-3.1-pro-preview"def test_deep_openai_default(self):@@ -87,8 +87,8 @@ class TestResolveTierModel:class TestPublicGetter:def test_get_default_returns_model(self):- # 2026-04-29 Frontier-Update + Bug-API-1: gemini-3-flash-preview- # weil Google API das Stable-Alias 'gemini-3-flash' nicht listet.+ # 2026-04-29 frontier update + Bug-API-1: gemini-3-flash-preview+ # because the Google API does not list the stable alias 'gemini-3-flash'.assert get_tier_default_model("router", "gemini") == "gemini-3-flash-preview"def test_get_default_returns_none_for_unknown_provider(self):diff --git a/tests/unit/ui/jarvisbar/test_interaction.py b/tests/unit/ui/jarvisbar/test_interaction.pyindex 75efbaac12..b8f08058eb 100644--- a/tests/unit/ui/jarvisbar/test_interaction.py+++ b/tests/unit/ui/jarvisbar/test_interaction.py@@ -34,8 +34,8 @@ def test_active_bar_body_click_does_not_hang_up():A low-intent click on the BODY of an active bar — between the End button andthe mic, where NO control is drawn — must NOT end the session. The old codetreated the whole left 40% of the bar as the hang-up X, so any such click- silently hung up ("Jarvis legt von selbst auf, ich hab nichts von Auflegen- gesagt").+ silently hung up ("Jarvis hangs up on its own, I never said anything about+ hanging up")."""W, PW = 100, 100# Body gap between the End X (centre 20, hit ±16 → up to 36) and the mic zonediff --git a/tests/unit/ui/test_orb_bus_bridge.py b/tests/unit/ui/test_orb_bus_bridge.pyindex 9926f5741b..90bcec6889 100644--- a/tests/unit/ui/test_orb_bus_bridge.py+++ b/tests/unit/ui/test_orb_bus_bridge.py@@ -6,16 +6,16 @@ from pathlib import Pathimport pytest-# Repo-Root in sys.path, damit Top-Level-Modul `ui.orb.*` importierbar ist.+# Repo root in sys.path so the top-level module `ui.orb.*` is importable._REPO_ROOT = Path(__file__).resolve().parents[3]if str(_REPO_ROOT) in sys.path:sys.path.remove(str(_REPO_ROOT))sys.path.insert(0, str(_REPO_ROOT))sys.modules.pop("ui", None)-# `ui` lebt als Top-Level-Verzeichnis im Repo-Root (nicht unter `jarvis/`).-# In manchen Pytest-Setups erkennt der Discovery-Loader diesen Pfad nicht; in dem-# Fall werden die Tests skipped statt das Collection-Sammeln zu sprengen.+# `ui` lives as a top-level directory in the repo root (not under `jarvis/`).+# Some pytest setups don't recognize this path via the discovery loader; in that+# case the tests are skipped instead of blowing up test collection.try: # noqa: SIM105 — bewusster Try-Import wegen Discovery-Quirkfrom ui.orb.bus_bridge import ( # type: ignore[import-not-found]THINKING_BUBBLE_TEXT,@@ -24,9 +24,9 @@ try: # noqa: SIM105 — bewusster Try-Import wegen Discovery-Quirkfrom ui.orb.overlay import OrbOverlay # type: ignore[import-not-found]except ModuleNotFoundError: # pragma: no coverpytest.skip(- "ui.orb nicht im Pytest-Pythonpath verfügbar — Top-Level-Namespace-Package. "- "Test laeuft direkt mit `python -m pytest tests/unit/ui/...` aus dem Repo-Root, "- "wenn der Repo-Root manuell in PYTHONPATH steht.",+ "ui.orb not available on the pytest PYTHONPATH — top-level namespace package. "+ "Test runs directly with `python -m pytest tests/unit/ui/...` from the repo root, "+ "when the repo root is manually placed on PYTHONPATH.",allow_module_level=True,)@@ -224,10 +224,10 @@ async def test_transcription_update_refreshes_large_bubble_only_while_listening(orb.calls.clear()await bridge._on_transcription_update( # noqa: SLF001- TranscriptionUpdate(text="Soll nicht sichtbar sein", is_final=False)+ TranscriptionUpdate(text="Soll nicht sichtbar sein", is_final=False) # i18n-allow)- assert ("show_listening_transcript", "Soll nicht sichtbar sein") not in orb.calls+ assert ("show_listening_transcript", "Soll nicht sichtbar sein") not in orb.calls # i18n-allowasync def test_zdf_subtitle_hallucination_is_not_shown_in_listening_bubble() -> None:@@ -257,10 +257,10 @@ async def test_broadcast_boilerplate_is_not_shown_in_listening_bubble() -> None:orb.calls.clear()await bridge._on_transcription_update( # noqa: SLF001- TranscriptionUpdate(text="Eine Sendung des NDR, 2020", is_final=False)+ TranscriptionUpdate(text="Eine Sendung des NDR, 2020", is_final=False) # i18n-allow)- assert ("show_listening_transcript", "Eine Sendung des NDR, 2020") not in orb.calls+ assert ("show_listening_transcript", "Eine Sendung des NDR, 2020") not in orb.calls # i18n-allowassert ("show_listening_transcript", "") in orb.calls@@ -280,12 +280,12 @@ async def test_listening_bubble_mirrors_accumulating_pipeline_snapshots() -> Nonawait bridge._on_transcription_update( # noqa: SLF001TranscriptionUpdate(- text="Hallo ich moechte einen langen Prompt", is_final=False+ text="Hallo ich moechte einen langen Prompt", is_final=False # i18n-allow))await bridge._on_transcription_update( # noqa: SLF001TranscriptionUpdate(- text="Hallo ich moechte einen langen Prompt der weiter geht",+ text="Hallo ich moechte einen langen Prompt der weiter geht", # i18n-allowis_final=False,))@@ -293,11 +293,11 @@ async def test_listening_bubble_mirrors_accumulating_pipeline_snapshots() -> Nonassert orb.calls == [("show_listening_transcript",- "Hallo ich moechte einen langen Prompt",+ "Hallo ich moechte einen langen Prompt", # i18n-allow),("show_listening_transcript",- "Hallo ich moechte einen langen Prompt der weiter geht",+ "Hallo ich moechte einen langen Prompt der weiter geht", # i18n-allow),]@@ -317,8 +317,8 @@ async def test_listening_bubble_replaces_corrected_live_hypotheses() -> None:snapshots = ("Was?","Was ist morgens?",- "Was ist morgen fuer ein Tag?",- "Was ist morgen fuer einen Tag.",+ "Was ist morgen fuer ein Tag?", # i18n-allow+ "Was ist morgen fuer einen Tag.", # i18n-allow)for snapshot in snapshots:await bridge._on_transcription_update( # noqa: SLF001@@ -329,7 +329,7 @@ async def test_listening_bubble_replaces_corrected_live_hypotheses() -> None:assert rendered == list(snapshots)assert orb.calls[-1] == ("show_listening_transcript",- "Was ist morgen fuer einen Tag.",+ "Was ist morgen fuer einen Tag.", # i18n-allow)@@ -344,7 +344,7 @@ async def test_waiting_for_completion_does_not_clear_bubble_or_switch_to_think()SystemStateChanged(new_state="LISTENING", previous="IDLE"))await bridge._on_transcription_update( # noqa: SLF001- TranscriptionUpdate(text="Öffne mal den", is_final=False)+ TranscriptionUpdate(text="Öffne mal den", is_final=False) # i18n-allow)orb.calls.clear()@@ -355,7 +355,7 @@ async def test_waiting_for_completion_does_not_clear_bubble_or_switch_to_think()assert ("show", "listen") in orb.callsassert ("show", "think") not in orb.calls# Bubble text not cleared- assert bridge._listening_transcript_text == "Öffne mal den" # noqa: SLF001+ assert bridge._listening_transcript_text == "Öffne mal den" # noqa: SLF001 # i18n-allowassert bridge._completion_continuation is True # noqa: SLF001@@ -370,7 +370,7 @@ async def test_listening_after_waiting_for_completion_preserves_buffered_text()SystemStateChanged(new_state="LISTENING", previous="IDLE"))await bridge._on_transcription_update( # noqa: SLF001- TranscriptionUpdate(text="Öffne mal den", is_final=True)+ TranscriptionUpdate(text="Öffne mal den", is_final=True) # i18n-allow)await bridge._on_state( # noqa: SLF001SystemStateChanged(new_state="WAITING_FOR_COMPLETION", previous="LISTENING")@@ -383,7 +383,7 @@ async def test_listening_after_waiting_for_completion_preserves_buffered_text()SystemStateChanged(new_state="LISTENING", previous="WAITING_FOR_COMPLETION"))- assert bridge._listening_transcript_text == "Öffne mal den" # noqa: SLF001+ assert bridge._listening_transcript_text == "Öffne mal den" # noqa: SLF001 # i18n-allowassert ("show_listening_transcript", "") not in orb.calls@@ -401,10 +401,10 @@ async def test_transcription_update_accepted_during_waiting_for_completion() ->orb.calls.clear()await bridge._on_transcription_update( # noqa: SLF001- TranscriptionUpdate(text="Öffne mal den", is_final=True)+ TranscriptionUpdate(text="Öffne mal den", is_final=True) # i18n-allow)- assert ("show_listening_transcript", "Öffne mal den") in orb.calls+ assert ("show_listening_transcript", "Öffne mal den") in orb.calls # i18n-allowasync def test_thinking_clears_completion_continuation_window() -> None:@@ -438,12 +438,12 @@ async def test_final_transcription_update_replaces_partial_preview() -> None:TranscriptionUpdate(text="Was ist morgens?", is_final=False))await bridge._on_transcription_update( # noqa: SLF001- TranscriptionUpdate(text="Was ist morgen fuer ein Tag?", is_final=True)+ TranscriptionUpdate(text="Was ist morgen fuer ein Tag?", is_final=True) # i18n-allow)assert orb.calls[-1] == ("show_listening_transcript",- "Was ist morgen fuer ein Tag?",+ "Was ist morgen fuer ein Tag?", # i18n-allow)diff --git a/tests/unit/ui/test_orb_bus_bridge_mute_loop.py b/tests/unit/ui/test_orb_bus_bridge_mute_loop.pyindex 606621f739..07ad6caec3 100644--- a/tests/unit/ui/test_orb_bus_bridge_mute_loop.py+++ b/tests/unit/ui/test_orb_bus_bridge_mute_loop.py@@ -8,7 +8,7 @@ spinning a throwaway loop — and ``bus.publish`` then dispatched the per-WS-cli``_forward`` subscriber, whose ``asyncio.Lock`` (``send_lock``) is bound to thereal backend loop. Acquiring it from the throwaway loop raised``RuntimeError: <Lock> is bound to a different event loop`` for every connected-client (a "WS-Forward fehlgeschlagen" storm). The mute flag flipped ON but the+client (a "WS forward failed" storm). The mute flag flipped ON but the``VoiceMuteChanged`` broadcast could not reach the UI, so the mic stayed mutedwith no visible cue and the voice session sat in LISTENING — "I spoke and itnever started thinking" — until the session died ``reason=error`` and the app@@ -26,7 +26,7 @@ from pathlib import Pathimport pytest-# Repo-Root in sys.path, damit Top-Level-Modul `ui.orb.*` importierbar ist.+# Repo root in sys.path so the top-level module `ui.orb.*` is importable._REPO_ROOT = Path(__file__).resolve().parents[3]if str(_REPO_ROOT) in sys.path:sys.path.remove(str(_REPO_ROOT))@@ -37,7 +37,7 @@ try: # noqa: SIM105 — bewusster Try-Import wegen Discovery-Quirkfrom ui.orb.bus_bridge import OrbBusBridge # type: ignore[import-not-found]except ModuleNotFoundError: # pragma: no coverpytest.skip(- "ui.orb nicht im Pytest-Pythonpath verfügbar — Top-Level-Namespace-Package.",+ "ui.orb not available on the pytest PYTHONPATH — top-level namespace package.",allow_module_level=True,)diff --git a/tests/unit/ui/test_orb_listening_transcript.py b/tests/unit/ui/test_orb_listening_transcript.pyindex 1307c7ab02..d0654792ba 100644--- a/tests/unit/ui/test_orb_listening_transcript.py+++ b/tests/unit/ui/test_orb_listening_transcript.py@@ -76,10 +76,10 @@ async def test_transcription_update_refreshes_large_bubble_only_while_listening(orb.calls.clear()await bridge._on_transcription_update( # noqa: SLF001- TranscriptionUpdate(text="Soll nicht sichtbar sein", is_final=False)+ TranscriptionUpdate(text="Soll nicht sichtbar sein", is_final=False) # i18n-allow)- assert ("show_listening_transcript", "Soll nicht sichtbar sein") not in orb.calls+ assert ("show_listening_transcript", "Soll nicht sichtbar sein") not in orb.calls # i18n-allowdef test_transcript_bubble_height_grows_by_visible_line_count() -> None:diff --git a/tests/unit/ui/test_profile_field_edit.py b/tests/unit/ui/test_profile_field_edit.pyindex 05be6ebb93..80f092bb4f 100644--- a/tests/unit/ui/test_profile_field_edit.py+++ b/tests/unit/ui/test_profile_field_edit.py@@ -2,7 +2,7 @@Profile view (the pencil-per-field UI).Contract (see jarvis/ui/web/profile_routes.py::patch_field):-- ``set`` overwrites a scalar field in place (Chef → König)+- ``set`` overwrites a scalar field in place (boss → king)- ``clear`` empties any field so it reads back as "not known yet"- ``append`` / ``remove`` add/drop one item of a list field (the chips)- the canonical field allow-list (shared with update_profile) is enforced@@ -39,7 +39,7 @@ values:# USER.md-## Observations ueber Zeit+## Observations over time<!-- curator:observations:start --><!-- curator:observations:end -->@@ -84,13 +84,13 @@ def _patch(client: TestClient, **body):def test_set_scalar_overwrites_chef_to_koenig(ctx) -> None:res = _patch(ctx.client, cluster="identity", field="preferred_address",- operation="set", value="König")+ operation="set", value="König") # i18n-allowassert res.status_code == 200, res.textassert res.json()["changed"] is True# In-memory + the read endpoint reflect it.- assert ctx.profile.get("identity", "preferred_address") == "König"+ assert ctx.profile.get("identity", "preferred_address") == "König" # i18n-allowmeta = ctx.client.get("/api/profile").json()["user"]["meta"]- assert meta["identity"]["preferred_address"] == "König"+ assert meta["identity"]["preferred_address"] == "König" # i18n-allowdef test_set_scalar_persists_to_disk(ctx) -> None:diff --git a/tests/unit/ui/web/test_friends_routes.py b/tests/unit/ui/web/test_friends_routes.pyindex 68138b6760..c1f593ee48 100644--- a/tests/unit/ui/web/test_friends_routes.py+++ b/tests/unit/ui/web/test_friends_routes.py@@ -1,6 +1,6 @@# === F-FRIENDS [F3] · feature/friends-section · ruben-2026-05-01 ===# === F-FRIENDS [F2] · feature/friends-section · ruben-2026-04-30 ===-"""REST-Route-Tests fuer die Phase-F2 Friends-API."""+"""REST route tests for the Phase-F2 Friends API."""from __future__ import annotationsfrom typing import Any@@ -240,7 +240,7 @@ def test_send_message_without_channel_400(app_with_registry: FastAPI) -> None:def test_send_message_pubkey_persists_outbound(app_with_registry: FastAPI) -> None:- """F3: jarvis_pubkey-Branch ist nicht mehr 501 — Outbound landet in der DB."""+ """F3: the jarvis_pubkey branch is no longer 501 — outbound lands in the DB."""with TestClient(app_with_registry) as client:r = client.post("/api/friends", json={"display_name": "JarvisFriend"})fid = r.json()["id"]@@ -258,7 +258,7 @@ def test_send_message_pubkey_persists_outbound(app_with_registry: FastAPI) -> Nodef test_list_messages_after_send_returns_items(app_with_registry: FastAPI) -> None:- """GET /messages liest die per POST persistierten Outbound-Items zurueck."""+ """GET /messages reads back the outbound items persisted via POST."""with TestClient(app_with_registry) as client:r = client.post("/api/friends", json={"display_name": "JarvisFriend"})fid = r.json()["id"]@@ -332,7 +332,7 @@ def test_send_message_telegram_routes_via_manager(def test_send_telegram_persists_outbound(app_with_registry: FastAPI) -> None:- """F3: Telegram-Send muss zusaetzlich ein Outbound-Echo in der DB anlegen."""+ """F3: Telegram send must additionally create an outbound echo in the DB."""from unittest.mock import AsyncMockfake_telegram = AsyncMock()diff --git a/tests/unit/ui/web/test_outputs_routes.py b/tests/unit/ui/web/test_outputs_routes.pyindex fad9160059..983bb35cd1 100644--- a/tests/unit/ui/web/test_outputs_routes.py+++ b/tests/unit/ui/web/test_outputs_routes.py@@ -632,8 +632,8 @@ async def test_get_output_plan_returns_empty_stub("""The Plan tab is intentionally a placeholder (Welle-4 not plumbed).Confirmed as out-of-scope per the B1 brief: returns ``{plan: null,- steps: []}`` rather than 404. The UI renders "Single-Shot-Run — kein- strukturierter Plan" for this shape.+ steps: []}`` rather than 404. The UI renders "Single-shot run — no+ structured plan" for this shape."""_make_mission_dir(tmp_path, "019e3600-eeee-7000-8000-000000000040")with TestClient(app) as client:diff --git a/tests/unit/vision/__init__.py b/tests/unit/vision/__init__.pyindex 3d6fc1f6c7..9e504aa565 100644--- a/tests/unit/vision/__init__.py+++ b/tests/unit/vision/__init__.py@@ -1 +1 @@-"""Unit-Tests fuer jarvis.vision (Phase 5 Capability 1)."""+"""Unit tests for jarvis.vision (Phase 5 Capability 1)."""diff --git a/tests/unit/vision/test_cache.py b/tests/unit/vision/test_cache.pyindex 71f6b6336b..653954ed2f 100644--- a/tests/unit/vision/test_cache.py+++ b/tests/unit/vision/test_cache.py@@ -1,4 +1,4 @@-"""Unit-Tests fuer den VisionCache (FIFO, Hash-Dedup)."""+"""Unit tests for VisionCache (FIFO, hash dedup)."""from __future__ import annotationsimport time@@ -39,7 +39,7 @@ def test_cache_miss_on_new_hash():def test_cache_miss_on_empty_hash():cache = VisionCache(capacity=5)- # Empty-Hash sollte garnicht erst gecached werden.+ # An empty hash should never be cached in the first place.cache.put(_obs(""))assert len(cache) == 0assert cache.get("") is None@@ -59,14 +59,14 @@ def test_cache_fifo_evicts_oldest():def test_cache_overwrite_refreshes_position():- """Wenn ein Hash erneut geputted wird, sollte er als 'neu' zaehlen und- nicht bei naechstem Evict als erstes fliegen.+ """When a hash is put again, it should count as 'new' and+ not be the first one evicted next time."""cache = VisionCache(capacity=3)cache.put(_obs("a"))cache.put(_obs("b"))cache.put(_obs("c"))- cache.put(_obs("a")) # 'a' bekommt frische Position, 'b' wird bei Evict als erstes fliegen+ cache.put(_obs("a")) # 'a' gets a fresh position, 'b' will be the first evictedcache.put(_obs("d")) # evict: 'b' war aeltestesassert cache.get("a") is not Noneassert cache.get("b") is Nonediff --git a/tests/unit/vision/test_context_provider.py b/tests/unit/vision/test_context_provider.pyindex 1a45104670..a360a5ec48 100644--- a/tests/unit/vision/test_context_provider.py+++ b/tests/unit/vision/test_context_provider.py@@ -1,7 +1,7 @@-"""Unit-Tests fuer VisionContextProvider.+"""Unit tests for VisionContextProvider.-Verifiziert Background-Refresh, Force-Refresh, Pause/Resume, Loop--Resilience gegen Exceptions und Clean-Shutdown-Timing.+Verifies background refresh, force refresh, pause/resume, loop+resilience against exceptions, and clean-shutdown timing."""from __future__ import annotations@@ -30,7 +30,7 @@ def _make_obs(hash_: str = "abc", *, timestamp_ns: int | None = None) -> Observaclass FakeEngine:- """Minimaler VisionEngine-Ersatz fuer Provider-Tests."""+ """Minimal VisionEngine stand-in for provider tests."""def __init__(self, *, raise_once: bool = False) -> None:self.calls = 0@@ -58,7 +58,7 @@ async def test_provider_holds_fresh_observation():obs = await prov.current()assert obs is not Noneassert obs.screenshot_hash.startswith("hash-")- # current() sollte NICHT zusaetzlich observen - Cache ist frisch.+ # current() should NOT additionally observe - the cache is fresh.assert engine.calls == calls_after_loopfinally:await prov.stop()@@ -66,7 +66,7 @@ async def test_provider_holds_fresh_observation():@pytest.mark.asyncioasync def test_provider_force_refresh_always_captures():- """force_refresh=True erzwingt einen Engine-Call, auch bei frischem Cache."""+ """force_refresh=True forces an engine call, even with a fresh cache."""engine = FakeEngine()prov = VisionContextProvider(engine, refresh_interval_s=10.0, max_staleness_s=10.0@@ -106,12 +106,12 @@ async def test_provider_pause_resume():@pytest.mark.asyncioasync def test_provider_loop_survives_exception():- """Exception im observe() killt den Loop nicht - retry auf naechster Tick."""+ """An exception in observe() does not kill the loop - it retries on the next tick."""engine = FakeEngine(raise_once=True)prov = VisionContextProvider(engine, refresh_interval_s=0.05)await prov.start()try:- # Genug Zeit fuer mindestens 2 Tick-Versuche (erster raised, zweiter ok).+ # Enough time for at least 2 tick attempts (first raises, second is ok).for _ in range(40):if engine.calls >= 2:break@@ -124,7 +124,7 @@ async def test_provider_loop_survives_exception():@pytest.mark.asyncioasync def test_provider_clean_shutdown_under_500ms():- """stop() cancelt den Task und kehrt in <500ms zurueck."""+ """stop() cancels the task and returns in <500ms."""engine = FakeEngine()prov = VisionContextProvider(engine, refresh_interval_s=10.0)await prov.start()diff --git a/tests/unit/vision/test_engine.py b/tests/unit/vision/test_engine.pyindex 15f9b62b3d..52b3dc975a 100644--- a/tests/unit/vision/test_engine.py+++ b/tests/unit/vision/test_engine.py@@ -1,7 +1,7 @@-"""Unit-Tests fuer die VisionEngine-Mode-Selection und Cache-Integration.+"""Unit tests for VisionEngine mode selection and cache integration.-Arbeiten gegen Fake-Sources — wir wollen die Heuristik testen, nicht-echte Screenshots/UIA-Trees aufnehmen.+Works against fake sources — we want to test the heuristic, not+capture real screenshots/UIA trees."""from __future__ import annotations@@ -40,7 +40,7 @@ class _FakeScreenshotSource:return Observation(trace_id=uuid4(),timestamp_ns=time.time_ns(),- screenshot_path=f"blobs/{self.hash}.png", # noqa: S108 — Fake-Path fuer Tests+ screenshot_path=f"blobs/{self.hash}.png", # noqa: S108 — fake path for testsscreenshot_hash=self.hash,nodes=(),window_title="",@@ -215,7 +215,7 @@ async def test_cache_hit_reuses_last_observation():)obs_1 = await engine.observe(mode="composite")obs_2 = await engine.observe(mode="composite")- # Zweite Observation wurde aus Cache gezogen — trace_id identisch.+ # Second observation was pulled from the cache — trace_id is identical.assert obs_1.trace_id == obs_2.trace_id@@ -238,7 +238,7 @@ async def test_cache_invalidates_on_window_change():# ---------------------------------------------------------------------------class _Cancelled:- """Minimaler CancelToken-Stub fuer Tests."""+ """Minimal CancelToken stub for tests."""def __init__(self) -> None:self._cancelled = False@@ -316,14 +316,14 @@ async def test_engine_close_closes_sources():# ---------------------------------------------------------------------------# ----------------------------------------------------------------------------# Screenshot-Modus: window_title aus dem Foreground-Hint (BUG-CU-EMPTYTITLE)+# Screenshot mode: window_title from the foreground hint (BUG-CU-EMPTYTITLE)#-# Text-heavy Apps (Chrome, VS Code, Slack, …) laufen im Screenshot-Modus, wo-# die ScreenshotSource window_title="" liefert. Der CU-Loop-Regression--# Detektor las den leeren Titel als "Fenster weg / Desktop vorne" und wies-# das Modell an, die gerade geoeffnete App neu zu oeffnen. Die Engine kennt-# den Foreground-Titel bereits (Mode-Heuristik) — sie muss ihn in die-# Observation uebernehmen.+# Text-heavy apps (Chrome, VS Code, Slack, …) run in screenshot mode, where+# ScreenshotSource returns window_title="". The CU-loop regression+# detector read the empty title as "window gone / desktop in front" and+# instructed the model to reopen the app that was already open. The engine+# already knows the foreground title (mode heuristic) — it must carry it+# over into the observation.# ---------------------------------------------------------------------------@pytest.mark.asyncio@@ -353,8 +353,8 @@ async def test_explicit_screenshot_mode_fills_window_title_from_probe():@pytest.mark.asyncioasync def test_auto_mode_without_filter_falls_back_to_composite():- """Wenn kein filter und kein Windows-Fenster erkennbar ist, sollte- 'composite' der Default sein.+ """When no filter and no Windows window is detectable,+ 'composite' should be the default."""engine = VisionEngine(screenshot_source=_FakeScreenshotSource(),diff --git a/tests/unit/vision/test_parent_index_remap.py b/tests/unit/vision/test_parent_index_remap.pyindex 173d88d00f..84f63d72b2 100644--- a/tests/unit/vision/test_parent_index_remap.py+++ b/tests/unit/vision/test_parent_index_remap.py@@ -1,8 +1,8 @@-"""Regression-Test H1: parent_index wird nach Pruning korrekt remapped.+"""Regression test H1: parent_index is remapped correctly after pruning.-Vor dem Fix war jeder ``parent_index`` in der gepruenten Liste hart auf-``-1``, egal was der urspruengliche Tree sagte. Dieser Test baut einen-synthetischen Tree, prunt ihn und prueft die Remap-Logik.+Before the fix, every ``parent_index`` in the pruned list was hardcoded to+``-1``, regardless of what the original tree said. This test builds a+synthetic tree, prunes it, and checks the remap logic."""from __future__ import annotations@@ -13,7 +13,7 @@ def _make_tree() -> list[RawNode]:"""Baut einen kleinen Tree:Root (depth=0)- ├── Panel (depth=1, wird gepruent — nicht interesting)+ ├── Panel (depth=1, gets pruned — not interesting)│ ├── Button-A (depth=2, bleibt)│ └── Button-B (depth=2, bleibt)└── Button-C (depth=1, bleibt)@@ -41,8 +41,8 @@ def test_remap_direct_parent_survives():def test_remap_skips_pruned_intermediate_parent():- """Button-A und Button-B haben Panel als Parent — Panel ist weg —- die neuen Parents muessen direkt auf Root zeigen.+ """Button-A and Button-B have Panel as their parent — Panel is gone —+ the new parents must point directly at Root."""original = _make_tree()kept = [original[0], original[2], original[3]] # Root, Button-A, Button-B@@ -53,7 +53,7 @@ def test_remap_skips_pruned_intermediate_parent():def test_remap_isolated_node_gets_minus_one():- """Nur Button-A allein — keine Vorfahrenkette mehr — parent_index=-1."""+ """Only Button-A alone — no ancestor chain left — parent_index=-1."""original = _make_tree()kept = [original[2]]_remap_parent_indices(kept, original)@@ -68,10 +68,10 @@ def test_prune_tree_yields_remapped_indices():# Alle parent_indices zeigen auf gueltige Indizes innerhalb prunedfor i, n in enumerate(pruned):assert n.parent_index == -1 or 0 <= n.parent_index < i, (- f"pruned[{i}] hat parent_index={n.parent_index} — ungueltig "+ f"pruned[{i}] has parent_index={n.parent_index} — invalid "f"(Subset-Groesse {len(pruned)})")- # Konkret: Root ist [0], die Buttons haben parent=0+ # Concretely: Root is [0], the buttons have parent=0assert pruned[0].name == "Root"for node in pruned[1:]:assert node.parent_index == 0diff --git a/tests/unit/vision/test_pruning.py b/tests/unit/vision/test_pruning.pyindex fb15ba7a0e..af9a6040e3 100644--- a/tests/unit/vision/test_pruning.py+++ b/tests/unit/vision/test_pruning.py@@ -1,7 +1,7 @@-"""Unit-Tests fuer die Pruning-Helpers (ADR-0002).+"""Unit tests for the pruning helpers (ADR-0002).-Arbeitet auf synthetischen RawNode-Baeumen, damit die Tests auch auf-non-Windows-Systemen laufen.+Works on synthetic RawNode trees so the tests also run on+non-Windows systems."""from __future__ import annotations@@ -150,7 +150,7 @@ def test_prune_tree_applies_all_three_filters_in_order():]kept = prune_tree(nodes, max_depth=6, monitor_bounds=MONITOR)names = [n.name or n.automation_id for n in kept]- # Root bleibt immer erhalten, plus die zwei guten Children.+ # Root is always kept, plus the two good children.assert "root" in namesassert "OK" in namesassert "closeBtn" in names@@ -170,14 +170,14 @@ def test_prune_tree_empty_input():# ----------------------------------------------------------------------------# Performance-Budget fuer 5000-Node-Tree (Mandat §Pattern-Warnung)+# Performance budget for a 5000-node tree (mandate §Pattern-Warnung)# ---------------------------------------------------------------------------def test_prune_tree_budget_under_300ms_for_5000_nodes():- """Synthetischer 5000-Node-Tree — Pruning muss unter 300ms bleiben.+ """Synthetic 5000-node tree — pruning must stay under 300ms.- Der Mandat-Text warnt explizit: Chrome/VSCode/Slack haben 5000+ Nodes.- Ohne dieses Budget wuerde der CU-Loop unpraktikabel werden.+ The mandate text explicitly warns: Chrome/VSCode/Slack have 5000+ nodes.+ Without this budget the CU loop would become impractical."""roles = list(DEFAULT_INTERESTING_ROLES) + ["Pane", "Group", "Separator"]nodes: list[RawNode] = [@@ -205,6 +205,6 @@ def test_prune_tree_budget_under_300ms_for_5000_nodes():kept = prune_tree(nodes, max_depth=6, monitor_bounds=MONITOR)elapsed_ms = (time.perf_counter() - start) * 1000assert elapsed_ms < 300, f"Pruning took {elapsed_ms:.1f}ms, budget 300ms"- # Wir wollen nicht zwangsweise <=150; prune_tree selbst macht keinen Retry.- # Das ist die Aufgabe vom UIATreeSource. Hier reicht: funktioniert in time.+ # We don't strictly require <=150; prune_tree itself doesn't retry.+ # That's the job of UIATreeSource. Here it's enough that it works in time.assert len(kept) >= 1diff --git a/tests/unit/voice/test_contextual_readback.py b/tests/unit/voice/test_contextual_readback.pyindex 484714b4c6..261397df1f 100644--- a/tests/unit/voice/test_contextual_readback.py+++ b/tests/unit/voice/test_contextual_readback.py@@ -177,7 +177,7 @@ async def test_empty_output_falls_back_to_canned() -> None:@pytest.mark.asyncioasync def test_wrong_language_falls_back_to_canned() -> None:# German output requested for an English turn -> rejected -> canned.- provider = _FakeProvider("Das hat auf dem Bildschirm geklappt und ist fertig.")+ provider = _FakeProvider("Das hat auf dem Bildschirm geklappt und ist fertig.") # i18n-allowcomposer = _composer(provider)out = await composer.compose(instruction="The on-screen task succeeded.",diff --git a/tests/unit/voice/test_echo_confirmation.py b/tests/unit/voice/test_echo_confirmation.pyindex 8a626b0d98..1e779e39c1 100644--- a/tests/unit/voice/test_echo_confirmation.py+++ b/tests/unit/voice/test_echo_confirmation.py@@ -1,14 +1,14 @@-"""Tests für `jarvis.voice.echo_confirmation` (Phase 7.4).+"""Tests for `jarvis.voice.echo_confirmation` (Phase 7.4).-Plan-Akzeptanzkriterien §7.4:-- Echo-Frage folgt End-Focus-Pattern (alt zuerst, neu zuletzt)-- Misshear-Test: gefakter STT-Output „Karen" statt „Charon" → User-Reject-- Sprachdetection: Templates passen sich an `profile.language` an+Plan acceptance criteria §7.4:+- Echo question follows the end-focus pattern (old first, new last)+- Misshear test: faked STT output „Karen" instead of „Charon" → user reject+- Language detection: templates adapt to `profile.language`-Plus Prompt-AC:-- Templater happy paths für numeric/string/bool/enum-- Sensitive: Wert taucht NICHT im Satz auf-- Pattern-Match deterministisch (Veto > Confirm > Ambiguous > Unknown)+Plus prompt AC:+- Templater happy paths for numeric/string/bool/enum+- Sensitive: value does NOT appear in the sentence+- Pattern match is deterministic (Veto > Confirm > Ambiguous > Unknown)"""from __future__ import annotations@@ -65,8 +65,8 @@ class TestConfirmPatterns:"ja","Ja","ja, mach das",- "bestätige",- "bestätigt",+ "bestätige", # i18n-allow+ "bestätigt", # i18n-allow"mach","los","okay",@@ -103,12 +103,12 @@ class TestVetoPatterns:["nein","Nein",- "abbrechen",+ "abbrechen", # i18n-allow"abbruch","stop","stopp",- "nicht",- "doch nicht",+ "nicht", # i18n-allow+ "doch nicht", # i18n-allow"lass","falsch",],@@ -124,13 +124,13 @@ class TestVetoPatterns:class TestAmbiguousPatterns:@pytest.mark.parametrize("transcript",- ["vielleicht", "warte", "moment", "weiß nicht", "ähm"],+ ["vielleicht", "warte", "moment", "weiß nicht", "ähm"], # i18n-allow)def test_ambiguous_de(self, transcript: str) -> None:# WICHTIG: Plan-Sicherheits-Eigenschaft — ambiguous ist NIEMALS Confirm.result = classify_response(transcript, language="de")assert result in ("ambiguous", "veto"), (- f"Mehrdeutige Antwort '{transcript}' wurde als Confirm interpretiert!"+ f"Ambiguous response '{transcript}' was interpreted as Confirm!")assert result != "confirm"@@ -201,7 +201,7 @@ class TestFormatConfirmation:# End-Focus-Plan-Templateassert sentence.startswith("Verstanden — TTS-Provider")assert "von elevenlabs zu gemini-flash-tts" in sentence- assert sentence.rstrip(".?!").endswith("Bestätigen")+ assert sentence.rstrip(".?!").endswith("Bestätigen") # i18n-allowdef test_numeric_value_de(self) -> None:pending = _pending(@@ -222,19 +222,19 @@ class TestFormatConfirmation:description="Dark-Mode",)sentence = format_confirmation(pending, language="de")- # bool wird als "an"/"aus" gerendert (nicht als True/False)- assert "von aus zu an" in sentence+ # bool is rendered as "an"/"aus" (not as True/False)+ assert "von aus zu an" in sentence # i18n-allowdef test_label_strips_parenthesis(self) -> None:pending = _pending(path="profile.language",old_value="de",new_value="en",- description="Profil-Sprache (wirkt sofort in nächster Antwort)",+ description="Profil-Sprache (wirkt sofort in nächster Antwort)", # i18n-allow)sentence = format_confirmation(pending, language="de")- assert "Profil-Sprache" in sentence- # Klammer-Inhalt landet NICHT im TTS-Output+ assert "Profil-Sprache" in sentence # i18n-allow+ # Parenthesis content must NOT land in the TTS outputassert "wirkt sofort" not in sentencedef test_english_template(self) -> None:@@ -267,7 +267,7 @@ class TestEndFocusTokenPosition:tokens = sentence.split()last_three = " ".join(tokens[-3:])assert str(new) in last_three, (- f"new_value '{new}' nicht in den letzten 3 Tokens: {last_three!r}"+ f"new_value '{new}' not in the last 3 tokens: {last_three!r}")@@ -304,7 +304,7 @@ class TestSensitiveLeak:assert self.SENTINEL not in sentence_en, (f"Klartext-Secret im EN-TTS-Output (path={path}): {sentence_en}")- # Phrase muss aber semantisch sinnvoll sein+ # But the phrase must still be semantically meaningfulassert "neuen Wert" in sentence_de or "new value" in sentence_endef test_outcome_does_not_leak_either(self) -> None:@@ -327,8 +327,8 @@ class TestSensitiveLeak:def test_outcome_validate_failed_with_short_error_blocks_leak(self,) -> None:- """Sub-Agent-Review-BLOCKER: short_error kann via Pydantic-Message- den new_value enthalten. Bei sensitive Path muss er verworfen werden.+ """Sub-Agent-review blocker: short_error can carry the new_value via+ the Pydantic message. For a sensitive path it must be discarded."""pending = _pending(path="anthropic_api_key",@@ -338,8 +338,8 @@ class TestSensitiveLeak:)# Wir simulieren einen short_error wie writer.py ihn liefertfake_msg = (- f"Pre-Validate für 'anthropic_api_key' = '{self.SENTINEL}' "- "schlug fehl: 1 validation error"+ f"Pre-validate for 'anthropic_api_key' = '{self.SENTINEL}' "+ "failed: 1 validation error")sentence_de = format_outcome("validate_failed",@@ -359,15 +359,15 @@ class TestSensitiveLeak:def test_short_error_from_pre_validate_exception_does_not_contain_repr(self,) -> None:- """short_error_from_exception(PreValidateError) darf den repr-Wert- aus der Original-Message NICHT durchreichen.+ """short_error_from_exception(PreValidateError) must NOT pass through+ the repr value from the original message."""from jarvis.core.self_mod import PreValidateErrorfrom jarvis.voice.echo_confirmation import short_error_from_exceptionsecret = "sk-leakable-XYZ-789" # noqa: S105 — Test-Fixtureexc = PreValidateError(- f"Pre-Validate für 'x' = {secret!r} schlug fehl: bla"+ f"Pre-validate for 'x' = {secret!r} failed: bla")result = short_error_from_exception(exc)assert secret not in result@@ -391,7 +391,7 @@ class TestOutcomeTemplates:def test_applied_with_restart(self) -> None:pending = _pending(path="brain.primary", old_value="claude", new_value="gemini",- description="Primärer Brain-Provider", requires_restart=True,+ description="Primärer Brain-Provider", requires_restart=True, # i18n-allow)sentence = format_outcome("applied_restart", pending, language="de")assert "neustarten" in sentencediff --git a/tests/unit/voice/test_self_mod_flow.py b/tests/unit/voice/test_self_mod_flow.pyindex b278df826a..65ce84fcad 100644--- a/tests/unit/voice/test_self_mod_flow.py+++ b/tests/unit/voice/test_self_mod_flow.py@@ -1,18 +1,18 @@-"""Tests für `jarvis.voice.self_mod_flow.SelfModFlowController` (Phase 7.4).+"""Tests for `jarvis.voice.self_mod_flow.SelfModFlowController` (Phase 7.4).-Plan-Akzeptanzkriterien §7.4:-- Misshear-Test: User-Reject führt zu keinem Schreiben-- Timeout-Test: 30s ohne Antwort → automatischer Reject-- SAFE-Tier-Test: `tts.speed`-Mutation läuft ohne Echo durch-- Sprachdetection: Templates passen sich an `profile.language` an+Plan acceptance criteria §7.4:+- Misshear test: user reject leads to no write+- Timeout test: 30s with no answer → automatic reject+- SAFE-tier test: `tts.speed` mutation goes through without an echo+- Language detection: templates adapt to `profile.language`-Plus Prompt-AC:-- Confirm → APPLIED, set_config_value genau einmal, Audit hat+Plus prompt AC:+- Confirm → APPLIED, set_config_value exactly once, audit hasvoice_confirmation-- Veto → VETOED, set_config_value NICHT gerufen, Audit "voice_vetoed"-- Mehrdeutige Antwort verlängert NICHT den Timeout (kein Soft-Lock)-- Integrationstest: Hauptjarvis-Tool-Call → Voice-Layer-Confirm →- jarvis.toml mutiert+- Veto → VETOED, set_config_value NOT called, audit "voice_vetoed"+- Ambiguous response does NOT extend the timeout (no soft lock)+- Integration test: Hauptjarvis tool call → voice-layer confirm →+ jarvis.toml mutated"""from __future__ import annotations@@ -140,7 +140,7 @@ class TestBeginSafeTier:pending_store: PendingMutationStore,fixture_path: Path,) -> None:- """Plan-§7.4 SAFE-Tier-Path: kein Echo, sofort persistiert."""+ """Plan-§7.4 SAFE-tier path: no echo, persisted immediately."""pending = _make_pending_via_tool(pending_store, path="tts.speed", new_value=1.25)@@ -150,7 +150,7 @@ class TestBeginSafeTier:assert session.echo_question == ""assert session.final_message is not Noneassert "1.25" in session.final_message- # File wurde wirklich geschrieben (vom Store, vor begin())+ # File was actually written (by the store, before begin())assert _isolated_loader(fixture_path).tts.speed == 1.25@@ -269,9 +269,9 @@ class TestVetoFlow:pending_store, path="tts.provider", new_value="elevenlabs")session = controller.begin(pending)- final = controller.receive_answer(session, "nein, doch nicht")+ final = controller.receive_answer(session, "nein, doch nicht") # i18n-allowassert final.state == FlowState.VETOED- # File unverändert+ # File unchangedassert fixture_path.read_bytes() == original_bytesdef test_veto_writes_audit_voice_vetoed(@@ -284,11 +284,11 @@ class TestVetoFlow:pending_store, path="tts.provider", new_value="elevenlabs")session = controller.begin(pending)- controller.receive_answer(session, "abbrechen", confidence=0.85)+ controller.receive_answer(session, "abbrechen", confidence=0.85) # i18n-allowentries = _read_audit(audit_log)vetoed = [e for e in entries if e.get("error") == "voice_vetoed"]assert len(vetoed) == 1- assert vetoed[0]["voice_confirmation"]["transcript"] == "abbrechen"+ assert vetoed[0]["voice_confirmation"]["transcript"] == "abbrechen" # i18n-allowassert vetoed[0]["voice_confirmation"]["confidence"] == 0.85def test_veto_renders_short_message(@@ -317,10 +317,10 @@ class TestMisshearReject:fixture_path: Path,audit_log: SelfModAudit,) -> None:- """Plan-AC: User hört Echo „Karen" statt „Charon" → Reject → kein Schreiben.+ """Plan AC: user hears the echo „Karen" instead of „Charon" → reject → no write.- Wir simulieren: STT hat „Karen" als new_value transkribiert, der Echo-Satz- zeigt das, der User hört es und sagt „nein".+ We simulate: STT transcribed „Karen" as new_value, the echo sentence+ shows it, the user hears it and says „no"."""original_bytes = fixture_path.read_bytes()pending = _make_pending_via_tool(@@ -330,10 +330,10 @@ class TestMisshearReject:# Echo zeigt "Karen" (genau das, was STT verstanden hat — End-Focus# macht das User-sichtbar):assert "Karen" in session.echo_question- # User hört es und sagt nein+ # User hears it and says nofinal = controller.receive_answer(session, "nein, falsch verstanden")assert final.state == FlowState.VETOED- # File unverändert — User wurde durch Echo gerettet+ # File unchanged — the user was saved by the echoassert fixture_path.read_bytes() == original_bytes@@ -355,7 +355,7 @@ class TestTimeoutFlow:pending_store, path="tts.provider", new_value="elevenlabs")session = controller.begin(pending, now=1000.0)- final = controller.check_timeout(session, now=1031.0) # 31s später+ final = controller.check_timeout(session, now=1031.0) # 31s laterassert final.state == FlowState.TIMEOUTassert fixture_path.read_bytes() == original_bytes# Audit "voice_timeout"@@ -383,13 +383,13 @@ class TestTimeoutFlow:pending_store, path="tts.provider", new_value="elevenlabs")session = controller.begin(pending, now=1000.0)- # User antwortet zu spät — wird als Timeout behandelt+ # User answers too late — treated as a timeoutfinal = controller.receive_answer(session, "ja", now=1031.0)assert final.state == FlowState.TIMEOUT# -----------------------------------------------------------------------# Mehrdeutigkeit (kein Soft-Lock, kein Confirm-Bias)+# Ambiguity (no soft lock, no confirm bias)# ----------------------------------------------------------------------@@ -399,8 +399,8 @@ class TestAmbiguousNoSoftLock:controller: SelfModFlowController,pending_store: PendingMutationStore,) -> None:- """Plan-AP-12 + Plan-Sicherheits-Eigenschaft: Mehrdeutiges- verlängert NICHT die Deadline, blockiert aber den Confirm.+ """Plan-AP-12 + plan safety property: an ambiguous response does+ NOT extend the deadline, but does block the confirm."""pending = _make_pending_via_tool(pending_store, path="tts.provider", new_value="elevenlabs"@@ -410,10 +410,10 @@ class TestAmbiguousNoSoftLock:intermediate = controller.receive_answer(session, "vielleicht", now=1010.0)- # Bleibt in CONFIRMING, Deadline UNVERÄNDERT+ # Stays in CONFIRMING, deadline UNCHANGEDassert intermediate.state == FlowState.CONFIRMING- assert intermediate.deadline_ts == 1030.0 # nicht verlängert- # Dann läuft Timer ab+ assert intermediate.deadline_ts == 1030.0 # not extended+ # Then the timer runs outfinal = controller.check_timeout(intermediate, now=1031.0)assert final.state == FlowState.TIMEOUT@@ -471,23 +471,23 @@ class TestIntegrationToolCallToMutation:))assert tool_result.success is True- # Re-Konstruktion des PendingMutation-Modells aus dem Tool-Output+ # Reconstruction of the PendingMutation model from the tool outputpending = PendingMutation.model_validate(tool_result.output)assert pending.applied is False # ASK-Tier- # 2. Voice-Layer übernimmt die Echo-Confirmation+ # 2. Voice layer takes over the echo confirmationsession = controller.begin(pending)assert session.state == FlowState.CONFIRMINGassert "elevenlabs" in session.echo_question- # 3. User bestätigt via STT-Mock+ # 3. User confirms via STT mockfinal = controller.receive_answer(session, "ja", confidence=0.95)assert final.state == FlowState.APPLIED# 4. jarvis.toml ist mutiertassert _isolated_loader(fixture_path).tts.provider == "elevenlabs"- # 5. Audit-Trail enthält voice_confirmed (Pre) + ok=true (Mutate)+ # 5. Audit trail contains voice_confirmed (pre) + ok=true (mutate)entries = _read_audit(audit_log)voice_pre = [ediff --git a/tests/unit/workflows/test_store_and_runner.py b/tests/unit/workflows/test_store_and_runner.pyindex 5bd85f1fb0..9a4172de4e 100644--- a/tests/unit/workflows/test_store_and_runner.py+++ b/tests/unit/workflows/test_store_and_runner.py@@ -1,14 +1,14 @@-"""Smoke-Tests fuers Workflow-System.+"""Smoke tests for the workflow system.Scope:- Store CRUD (insert, list, upsert, run-create, run-step-update).-- Seed-Idempotenz.-- Runner mit Fake-Brain: brain_prompt-Step produziert erwarteten Output.-- Runner mit Template-Expansion (``{{prev.output}}`` + ``{{input.X}}``).-- Runner Error-Pfad: speak ohne kaputtes Dep geht durch, tool_call ohne Registry faillt sauber.+- Seed idempotency.+- Runner with fake brain: brain_prompt step produces the expected output.+- Runner with template expansion (``{{prev.output}}`` + ``{{input.X}}``).+- Runner error path: speak without a broken dep goes through, tool_call without a registry fails cleanly.-Keine echten Brain-Provider, keine echte SQLite-Datei auf Platte — alles-tempdir + Fakes. Pattern spiegelt ``tests/unit/clis/test_smoke.py`` etc.+No real brain providers, no real SQLite file on disk — everything is+tempdir + fakes. The pattern mirrors ``tests/unit/clis/test_smoke.py`` etc."""from __future__ import annotations@@ -44,7 +44,7 @@ async def store(tmp_path: Path) -> WorkflowStore:class FakeBrain:- """Async-callable das den Prompt echoed — ausreichend fuer Runner-Tests."""+ """Async callable that echoes the prompt — sufficient for runner tests."""def __init__(self) -> None:self.calls: list[str] = []@@ -100,7 +100,7 @@ async def test_store_upsert_is_idempotent(store: WorkflowStore) -> None:async def test_seed_is_idempotent(store: WorkflowStore) -> None:first = await ensure_seed_workflows(store)- # Aktuelle Seed-Count ergibt sich aus SEED_WORKFLOWS — robust gegen Zufuegungen.+ # The current seed count derives from SEED_WORKFLOWS — robust against additions.from jarvis.workflows.seed import SEED_WORKFLOWSassert first == len(SEED_WORKFLOWS)second = await ensure_seed_workflows(store)@@ -152,7 +152,7 @@ async def test_runner_brain_prompt_executes_and_publishes_events(wid = await store.upsert_workflow(wf)run_id = await runner.trigger(wid)- # Einen Micro-Turn warten — Runner laeuft als asyncio.create_task.+ # Wait one micro-turn — the runner runs as an asyncio.create_task.import asynciofor _ in range(50):await asyncio.sleep(0.01)@@ -160,7 +160,7 @@ async def test_runner_brain_prompt_executes_and_publishes_events(if run and run["state"] == "completed":breakelse:- pytest.fail("Run wurde nicht in 500ms fertig")+ pytest.fail("Run did not finish within 500ms")assert brain.calls == ["sag hallo"]run = await store.get_run(run_id)@@ -201,13 +201,13 @@ async def test_runner_input_variable_expansion(store: WorkflowStore) -> None:if run and run["state"] == "completed":breakelse:- pytest.fail("Run nicht fertig")+ pytest.fail("Run not finished")assert brain.calls == ["Fasse https://x.test zusammen"]async def test_runner_without_brain_fails_cleanly(store: WorkflowStore) -> None:- """brain_prompt ohne BrainManager → sauberer Error-State, kein Crash."""+ """brain_prompt without a BrainManager → clean error state, no crash."""bus = EventBus()runner = WorkflowRunner(store=store, bus=bus, brain=None)@@ -238,10 +238,10 @@ async def test_runner_without_brain_fails_cleanly(store: WorkflowStore) -> None:async def test_runner_shell_cmd_captures_stdout(store: WorkflowStore, tmp_path: Path,) -> None:- """shell_cmd mit einem einfachen Python-Script — stdout landet in output.+ """shell_cmd with a simple Python script — stdout lands in output.- Ein File-basiertes Script vermeidet die Escape-Hoelle von ``-c "print(...)"``- auf Windows und prueft den realistischen Case (gws/git-style-CLI).+ A file-based script avoids the escaping hell of ``-c "print(...)"``+ on Windows and tests the realistic case (gws/git-style CLI)."""import sys@@ -313,11 +313,11 @@ async def test_runner_shell_cmd_nonzero_exit_fails(async def test_runner_telegram_without_token_fails_cleanly(store: WorkflowStore, monkeypatch: pytest.MonkeyPatch,) -> None:- """telegram_send ohne Token → sauberer Fehler mit Setup-Hinweis."""+ """telegram_send without a token → clean error with setup hint."""from jarvis.workflows.schema import TelegramSendStep- # Token-Lookup garantiert leer. monkeypatch stellt sicher, dass kein- # eingeloggter keyring-Key aus der echten Dev-Maschine reingelesen wird.+ # Token lookup guaranteed empty. monkeypatch makes sure no+ # logged-in keyring key from the real dev machine gets read in.monkeypatch.delenv("TELEGRAM_BOT_TOKEN", raising=False)monkeypatch.setattr("jarvis.core.config.get_secret",@@ -352,10 +352,10 @@ async def test_runner_telegram_without_token_fails_cleanly(async def test_runner_telegram_posts_to_api(store: WorkflowStore, monkeypatch: pytest.MonkeyPatch,) -> None:- """telegram_send mit Token + Chat-ID → POST an Bot-API, Payload korrekt.+ """telegram_send with token + chat ID → POST to the bot API, payload correct.- Wir mocken ``httpx.AsyncClient.post`` um einen 200-OK zurueckzugeben und- pruefen, dass Body chat_id/text wie erwartet enthaelt.+ We mock ``httpx.AsyncClient.post`` to return a 200 OK and+ check that the body contains chat_id/text as expected."""from jarvis.workflows.schema import TelegramSendStep@@ -402,7 +402,7 @@ async def test_runner_telegram_posts_to_api(breakrun = await store.get_run(run_id)- assert run["state"] == "completed", f"Fehler: {run['error']}"+ assert run["state"] == "completed", f"Error: {run['error']}"assert len(captured_payloads) == 1body = captured_payloads[0]["body"]assert body["chat_id"] == "987654"diff --git a/tools/board_demo.py b/tools/board_demo.pyindex 14abccbf87..6ee961afe7 100644--- a/tools/board_demo.py+++ b/tools/board_demo.py@@ -1,24 +1,24 @@-"""Board-Demo-Bootstrap (v1.0).+"""Board demo bootstrap (v1.0).-Spawnt zwei in-Process ASGI-Backends (Alice + Bob), erzeugt fünf-synthetische Identitäten, paired sie kreuzweise und befüllt jedes-Backend mit ca. 30 Tagen Random-Activity (Achievements + Stories +-Reactions).+Spawns two in-process ASGI backends (Alice + Bob), creates five+synthetic identities, pairs them crosswise, and seeds each+backend with ~30 days of random activity (achievements + stories ++reactions).-Zweck:-- **Demo**: Screenshots fürs README ohne echte Friends.-- **Performance-Audit**: liefert die Datenbasis für ``board_perf.py``.-- **Tests**: ein einziger Befehl bringt einen vollständig befüllten- Federation-Stand auf — manuelle Pair-Roundtrips entfallen.+Purpose:+- **Demo**: README screenshots without real friends.+- **Performance audit**: supplies the data basis for ``board_perf.py``.+- **Tests**: a single command brings up a fully seeded+ federation state — manual pair round-trips are no longer needed.-Aufruf::+Usage::python tools/board_demo.py --out /tmp/board_demo- # spawn 2 Backends als Subprozesse, schreibt URLs in stdout+ # spawn 2 backends as subprocesses, writes URLs to stdoutpython tools/board_demo.py --backend1 :18001 --backend2 :18002-Sicherheits-Hinweis: das Skript ist *Dev-Only*. Es erzeugt Keypairs-ohne sie ausser-Process zu speichern — keine Produktiv-Identities.+Security note: this script is *dev-only*. It generates keypairs+without persisting them out-of-process — no production identities."""from __future__ import annotations@@ -52,14 +52,14 @@ ACHIEVEMENT_IDS = []STORY_TEXTS = [- "Heute den Tool-Master geknackt — 30 verschiedene CLIs in 14 Tagen genutzt.",- "Sub-Jarvis hat einen Refactor durchgezogen, während ich Mittag gegessen habe.",- "Voice-First-Try-Rate über 95 % seit drei Tagen. Kein Zufall.",- "Erste eigene MCP-Bridge integriert. Lief auf Anhieb.",- "Triple-Combo: bash → grep → write_file. In einer Session, ein Take.",- "Die Aggregator-Pipeline lief 30 Tage durch ohne einen einzigen Crash.",- "Habe den Privkey aus dem Credential Manager exportiert. Backup im Tresor.",- "Mein Board zeigt jetzt eine echte Streak. Wieder mal mit Jarvis durchgezogen.",+ "Cracked Tool Master today — used 30 different CLIs in 14 days.",+ "Sub-Jarvis pushed through a refactor while I was having lunch.",+ "Voice first-try rate above 95% for three days straight. No coincidence.",+ "Integrated my first own MCP bridge. Worked first try.",+ "Triple combo: bash → grep → write_file. One session, one take.",+ "The aggregator pipeline ran for 30 days straight without a single crash.",+ "Exported the private key from the credential manager. Backed up in the vault.",+ "My board now shows a real streak. Pulled it off again with Jarvis.",]DISPLAY_NAMES = ["Ada", "Bjorn", "Camille", "Diego", "Eli"]@@ -93,7 +93,7 @@ async def _start_backend(name: str, db_path: Path, admin_token: str) -> DemoBackreplay_window_seconds=300,)app = create_app(settings=settings)- app.state.disable_background = True # kein FederationPuller-noise+ app.state.disable_background = True # no FederationPuller noisetransport = httpx.ASGITransport(app=app)client = httpx.AsyncClient(transport=transport, base_url=f"http://{name}", timeout=10)return DemoBackend(name=name, settings=settings, app=app, client=client)@@ -151,11 +151,11 @@ def _now_ms() -> int:async def _seed_activity(b: DemoBackend, owner: DemoIdentity, *, days: int, rng: random.Random,) -> None:- """Erzeugt ~3 Items pro Tag, gemischt aus Achievements + Stories.+ """Creates ~3 items per day, mixed from achievements + stories.- Backdating via direktem DB-Write — wir gehen *durch* die ORM-Schicht,- aber überschreiben ``created_at`` und ``expires_at``, damit der Feed- eine glaubhafte Zeitachse hat.+ Backdating via a direct DB write — we go *through* the ORM layer,+ but override ``created_at`` and ``expires_at`` so the feed+ has a believable timeline."""from board_backend.models import ActivityItemfactory = b.app.state.session_factory@@ -175,8 +175,8 @@ async def _seed_activity(expires_at = Noneelse:payload = {"text": rng.choice(STORY_TEXTS)}- # Stories die schon "live" waren bekommen expires_at, alte- # Stories sind faktisch gelöscht (skip).+ # Stories that were already "live" get expires_at; old+ # stories are effectively deleted (skip).if day < 1:expires_at = ts + timedelta(hours=24)else:@@ -201,7 +201,7 @@ async def _seed_reactions(backend: DemoBackend, author: DemoIdentity, reactors: list[DemoIdentity],rng: random.Random,) -> None:- """Verteilt zufällige Reactions auf die Items des author."""+ """Distributes random reactions across the author's items."""from board_backend.models import ActivityItem, Reactionfactory = backend.app.state.session_factoryREACTIONS = ("rocket", "brain", "fire")@@ -231,9 +231,8 @@ async def _seed_reactions(async def bootstrap(out_dir: Path, *, days: int = 30, seed: int | None = None,) -> dict[str, Any]:- """Spawnt zwei Backends, paired, befüllt — und gibt einen Status-- Report zurück, den der Caller (board_perf, README-Recipe) konsumieren- kann.+ """Spawns two backends, pairs them, seeds them — and returns a status+ report that the caller (board_perf, README recipe) can consume."""rng = random.Random(seed if seed is not None else 42)out_dir.mkdir(parents=True, exist_ok=True)@@ -241,7 +240,7 @@ async def bootstrap(alice = await _start_backend("alice", out_dir / "alice.db", admin_token="alice-admin")bob = await _start_backend("bob", out_dir / "bob.db", admin_token="bob-admin")- # Owner-Identitäten (sind die einzigen registrierten Identities pro Backend).+ # Owner identities (the only registered identities per backend).a_priv, a_pub = generate_keypair()b_priv, b_pub = generate_keypair()alice_id = DemoIdentity("Alice", a_priv, a_pub, "alice")@@ -250,18 +249,18 @@ async def bootstrap(await _register(alice, alice_id)await _register(bob, bob_id)- # Drei zusätzliche pseudo-Friends pro Backend (kein eigenes Backend,- # nur Sig-fähige Identitäten für Reactions).+ # Three extra pseudo-friends per backend (no backend of their own,+ # just signature-capable identities for reactions).extras: list[DemoIdentity] = []for name in DISPLAY_NAMES:priv, pub = generate_keypair()extras.append(DemoIdentity(name, priv, pub, "ext"))- # Bidirektionale Pair-Beziehungen Alice ↔ Bob (Standard-Demo).+ # Bidirectional pair relationship Alice ↔ Bob (standard demo).await _pair(alice, alice_id, bob_id, friend_url="http://bob")await _pair(bob, bob_id, alice_id, friend_url="http://alice")- # Pseudo-Friends als Friend-Rows direkt in beide DBs schreiben.+ # Write pseudo-friends as friend rows directly into both DBs.from board_backend.models import Friendfor backend, owner in ((alice, alice_id), (bob, bob_id)):with backend.app.state.session_factory() as session:@@ -276,13 +275,13 @@ async def bootstrap())session.commit()- # Activity + Reactions pro Backend.+ # Activity + reactions per backend.await _seed_activity(alice, alice_id, days=days, rng=rng)await _seed_activity(bob, bob_id, days=days, rng=rng)await _seed_reactions(alice, alice_id, [bob_id, *extras], rng)await _seed_reactions(bob, bob_id, [alice_id, *extras], rng)- # Live-Probe für Status-Report.+ # Live probe for the status report.me_payload = {"ts_ms": _now_ms()}r = await _signed("GET", alice, "/api/v1/me", ident=alice_id, payload=me_payload)alice_me = r.json()@@ -308,11 +307,11 @@ async def bootstrap(def _parse_args() -> argparse.Namespace:p = argparse.ArgumentParser(description="Bootstrap a Jarvis-Board demo state.")p.add_argument("--out", type=Path, default=Path("data/board_demo"),- help="Verzeichnis für DB-Dateien (Default: data/board_demo).")+ help="Directory for DB files (default: data/board_demo).")p.add_argument("--days", type=int, default=30,- help="Anzahl der Tage Random-Activity (Default: 30).")+ help="Number of days of random activity (default: 30).")p.add_argument("--seed", type=int, default=None,- help="RNG-Seed für deterministische Demo (Default: 42).")+ help="RNG seed for a deterministic demo (default: 42).")return p.parse_args()diff --git a/tools/board_pentest.py b/tools/board_pentest.pyindex 9775101628..33834d1e4a 100644--- a/tools/board_pentest.py+++ b/tools/board_pentest.py@@ -1,19 +1,19 @@-"""Security-Pen-Test gegen ein laufendes board-backend (v1.0).+"""Security pen test against a running board-backend (v1.0).-Voraussetzung: ``board-backend`` läuft auf ``BACKEND_URL``-(Default: ``http://localhost:8765``) mit ADMIN_TOKEN ``test-token``.-Spawn lokal via::+Prerequisite: ``board-backend`` runs on ``BACKEND_URL``+(default: ``http://localhost:8765``) with ADMIN_TOKEN ``test-token``.+Spawn locally via::cd board-backendJARVIS_BOARD_ADMIN_TOKEN=test-token docker compose up -d --build-Dieses Script versucht eine Reihe bekannter Attack-Vektoren und-dokumentiert die Server-Antworten. Ziel: keine 500er, keine-Auth-Bypässe, keine Trace-Leaks. Erwartete Status-Codes:-- 401 für ungültige Sigs / abgelaufene Timestamps / unbekannte Pubkeys-- 422 für Schema-Verletzungen (extra-Felder, falsche Typen)-- 429 für Rate-Limit-Überschreitung-- 200 nur für legitime Requests+This script attempts a series of known attack vectors and+documents the server responses. Goal: no 500s, no+auth bypasses, no trace leaks. Expected status codes:+- 401 for invalid signatures / expired timestamps / unknown pubkeys+- 422 for schema violations (extra fields, wrong types)+- 429 for rate-limit overruns+- 200 only for legitimate requests"""from __future__ import annotations@@ -32,7 +32,7 @@ ADMIN_TOKEN = os.environ.get("ADMIN_TOKEN", "test-token-32chars-aaaabbbb1111ccc"# -----------------------------------------------------------------------# Test-Runner+# Test runner# ----------------------------------------------------------------------class TestResult:@@ -77,11 +77,11 @@ def signed_post(client: httpx.Client, path: str, *, priv: str, pub: str, payload# -----------------------------------------------------------------------# Test-Sections+# Test sections# ----------------------------------------------------------------------def section_admin_token(c: httpx.Client) -> None:- print("\n[1] Admin-Token / Register-Route")+ print("\n[1] Admin token / register route")_, pub = generate_keypair()r = c.post(@@ -98,7 +98,7 @@ def section_admin_token(c: httpx.Client) -> None:)check("register with empty admin-token rejected", (401, 422), r)- # Valid register fuer subsequent tests.+ # Valid register for subsequent tests._, owner_pub = generate_keypair()r = c.post("/api/v1/identity/register",@@ -109,7 +109,7 @@ def section_admin_token(c: httpx.Client) -> None:def section_signed_routes(c: httpx.Client) -> None:- print("\n[2] Signed-Route-Auth / Sig-Verify")+ print("\n[2] Signed-route auth / signature verification")priv, pub = generate_keypair()c.post(@@ -127,7 +127,7 @@ def section_signed_routes(c: httpx.Client) -> None:"Content-Type": "application/json"})check("tampered sig rejected", 401, r)- # 2.2 Tampered body (sig stimmt nicht zu re-canonicalized body)+ # 2.2 Tampered body (signature does not match the re-canonicalized body)sig = sign(payload, privkey_hex=priv)tampered = {**payload, "display_name": "Y"}r = c.post("/api/v1/sync", content=canonical_json(tampered),@@ -135,7 +135,7 @@ def section_signed_routes(c: httpx.Client) -> None:"Content-Type": "application/json"})check("post-sign body tamper rejected", 401, r)- # 2.3 Replay alter ts_ms+ # 2.3 Replay with an old ts_msold_payload = {**payload, "ts_ms": now_ms() - 6 * 60 * 1000}r = signed_post(c, "/api/v1/sync", priv=priv, pub=pub, payload=old_payload)check("replay (>5min old ts) rejected", 401, r)@@ -145,12 +145,12 @@ def section_signed_routes(c: httpx.Client) -> None:r = signed_post(c, "/api/v1/sync", priv=priv, pub=pub, payload=fut)check("future ts (>5min ahead) rejected", 401, r)- # 2.5 Unbekannter Pubkey+ # 2.5 Unknown pubkeyrnd_priv, rnd_pub = generate_keypair()r = signed_post(c, "/api/v1/sync", priv=rnd_priv, pub=rnd_pub, payload=payload)check("unregistered pubkey rejected", 401, r)- # 2.6 Pubkey-Format-Garbage+ # 2.6 Garbage pubkey formatr = c.post("/api/v1/sync", content=body,headers={"X-Pubkey": "ZZ" * 32, "X-Jarvis-Sig": sig,"Content-Type": "application/json"})@@ -158,7 +158,7 @@ def section_signed_routes(c: httpx.Client) -> None:def section_pii_filter(c: httpx.Client) -> None:- print("\n[3] PII-Filter (extra='forbid')")+ print("\n[3] PII filter (extra='forbid')")priv, pub = generate_keypair()c.post("/api/v1/identity/register",@@ -169,7 +169,7 @@ def section_pii_filter(c: httpx.Client) -> None:body = {"ts_ms": now_ms(), "display_name": "X","daily_stats": [], "achievements": [],- "voice_transcript": "Mein Passwort ist hunter2", # SHOULD BE REJECTED+ "voice_transcript": "My password is hunter2", # SHOULD BE REJECTED}r = signed_post(c, "/api/v1/sync", priv=priv, pub=pub, payload=body)check("top-level extra-field rejected", 422, r)@@ -198,30 +198,30 @@ def section_malformed(c: httpx.Client) -> None:json={"pubkey": pub, "display_name": "Malformed-Owner"},headers={"X-Admin-Token": ADMIN_TOKEN})- # 4.1 Body kein JSON+ # 4.1 Body is not JSONr = c.post("/api/v1/sync", content=b"not json at all",headers={"X-Pubkey": pub, "X-Jarvis-Sig": "00" * 64,"Content-Type": "application/json"})check("non-json body rejected", (400, 401), r)- # 4.2 Body ist JSON-Array statt -Object+ # 4.2 Body is a JSON array instead of an objectr = c.post("/api/v1/sync", content=b'[1,2,3]',headers={"X-Pubkey": pub, "X-Jarvis-Sig": "00" * 64,"Content-Type": "application/json"})check("json-array body rejected", (400, 401, 422), r)- # 4.3 Sehr großer Body (1 MB) — DoS check+ # 4.3 Very large body (1 MB) — DoS checkhuge_payload = {"ts_ms": now_ms(), "display_name": "X","daily_stats": [], "achievements": [],- "junk": "x" * 1_000_000, # extra-forbid -> 422 vor DoS+ "junk": "x" * 1_000_000, # extra-forbid -> 422 before DoS}r = signed_post(c, "/api/v1/sync", priv=priv, pub=pub, payload=huge_payload)check("oversized body rejected by schema", 422, r)def section_rate_limit(c: httpx.Client) -> None:- print("\n[5] Rate-Limit auf /identity/register")+ print("\n[5] Rate limit on /identity/register")last_status = Nonestatuses = []for i in range(15):@@ -229,7 +229,7 @@ def section_rate_limit(c: httpx.Client) -> None:r = c.post("/api/v1/identity/register",json={"pubkey": pub, "display_name": f"RL{i}"},- headers={"X-Admin-Token": "wrong"}, # invalid → spart Token-Vergleich+ headers={"X-Admin-Token": "wrong"}, # invalid → skips the token comparison)statuses.append(r.status_code)last_status = r.status_code@@ -253,13 +253,13 @@ def section_path_traversal(c: httpx.Client) -> None:headers={"X-Admin-Token": ADMIN_TOKEN},)check("SQL-injection-string accepted as plain string (parameterized)", 200, r)- # Verify table existiert noch+ # Verify the table still existsr = c.get("/healthz")check("/healthz still 200 (db intact)", 200, r)- # Pubkey sollte mit dem injection-string als display_name persistiert sein- # (string ist literal gespeichert, kein SQL ausgefuehrt) — aber wir koennen- # das nicht direkt verifizieren ohne signed /me-call. Stattdessen pruefen- # wir dass die identity-tabelle nicht weg ist via re-register als no-op:+ # The pubkey should have the injection string persisted as display_name+ # (the string is stored literally, no SQL executed) — but we can't+ # verify that directly without a signed /me call. Instead we check+ # that the identity table hasn't vanished, via a re-register as a no-op:r2 = c.post("/api/v1/identity/register",json={"pubkey": pub, "display_name": "harmless"},@@ -271,14 +271,14 @@ def section_path_traversal(c: httpx.Client) -> None:def section_forget_me(c: httpx.Client) -> None:print("\n[7] Forget-Me Path/Sig Mismatch")- # Owner registrieren + ein Friend mit Reaction+ # Register the owner + one friend with a reactionpriv, pub = generate_keypair()c.post("/api/v1/identity/register",json={"pubkey": pub, "display_name": "Owner"},headers={"X-Admin-Token": ADMIN_TOKEN})other_priv, other_pub = generate_keypair()- # other_priv signt aber path-pubkey ist `pub` -> 403+ # other_priv signs but the path pubkey is `pub` -> 403payload = {"ts_ms": now_ms()}body = canonical_json(payload)sig = sign(payload, privkey_hex=other_priv)@@ -298,17 +298,17 @@ def section_forget_me(c: httpx.Client) -> None:def main() -> int:print(f"=== board-backend Pen-Test against {BACKEND_URL} ===\n")with httpx.Client(base_url=BACKEND_URL, timeout=10.0) as c:- # Health-Check zuerst+ # Health check firsttry:r = c.get("/healthz")assert r.status_code == 200, f"Backend not healthy: {r.status_code}"except Exception as exc:- print(f"FATAL: Backend nicht erreichbar: {exc}")+ print(f"FATAL: backend not reachable: {exc}")return 2- # Reihenfolge bewusst: alle non-rate-limit-Tests vor section_rate_limit,- # damit der Test-Runner nicht ungewollt 429er produziert in spaeteren- # Sections (das Rate-Limit ist IP-basiert).+ # Order is deliberate: all non-rate-limit tests run before section_rate_limit,+ # so the test runner doesn't accidentally produce 429s in later+ # sections (the rate limit is IP-based).section_admin_token(c)section_signed_routes(c)section_pii_filter(c)@@ -320,7 +320,7 @@ def main() -> int:print("\n" + "=" * 72)passed = sum(1 for r in RESULTS if r.ok)failed = len(RESULTS) - passed- print(f"Pen-Test: {passed}/{len(RESULTS)} PASS, {failed} FAIL")+ print(f"Pen test: {passed}/{len(RESULTS)} PASS, {failed} FAIL")print("=" * 72)if failed:print("\nFailures:")diff --git a/tools/board_perf.py b/tools/board_perf.pyindex fabee8f7fa..ae71379a7f 100644--- a/tools/board_perf.py+++ b/tools/board_perf.py@@ -1,16 +1,16 @@-"""Performance-Audit für v1.0.+"""Performance audit for v1.0.-Drei Targets aus dem Release-Prompt:+Three targets from the release prompt:-1. **Aggregator-Run mit 365 Tage Daten** — Soll < 30 s.-2. **Federation-Pull mit 10 Friends** — Bandbreite pro Pull < 100 KB.-3. **Frontend `/board` Initial-Load** — Soll < 500 ms.+1. **Aggregator run with 365 days of data** — should be < 30 s.+2. **Federation pull with 10 friends** — bandwidth per pull < 100 KB.+3. **Frontend `/board` initial load** — should be < 500 ms.-Items 1 + 2 misst dieses Skript direkt. Item 3 erfordert eine Browser--Session und wird separat in PERFORMANCE_AUDIT.md dokumentiert (mit-``mcp__playwright`` oder per Hand).+This script measures items 1 + 2 directly. Item 3 requires a browser+session and is documented separately in PERFORMANCE_AUDIT.md (with+``mcp__playwright`` or by hand).-Aufruf: ``python tools/board_perf.py``+Run: ``python tools/board_perf.py``"""from __future__ import annotations@@ -33,12 +33,12 @@ from jarvis.board.aggregator import BoardAggregator# -----------------------------------------------------------------------# (1) Aggregator: 365 Tage Synthetic-JSONL → run()-Dauer+# (1) Aggregator: 365 days of synthetic JSONL → run() duration# ----------------------------------------------------------------------def _emit_year_of_events(jsonl_dir: Path, *, days: int = 365, events_per_day: int = 50) -> int:- """Schreibt ``days * events_per_day`` Events ueber ``days`` Tage,- aufgeteilt auf Tagesschritte. Returns total events count.+ """Writes ``days * events_per_day`` events across ``days`` days,+ split into daily steps. Returns total events count."""jsonl_dir.mkdir(parents=True, exist_ok=True)rng = Random(7)@@ -117,15 +117,15 @@ def benchmark_aggregator() -> dict:# -----------------------------------------------------------------------# (2) Federation-Pull-Bandbreite mit 10 Friends+# (2) Federation pull bandwidth with 10 friends# ----------------------------------------------------------------------async def benchmark_federation_pull() -> dict:- """Misst Body-Größe + Latenz für /federation/feed mit 10 Friends.+ """Measures body size + latency for /federation/feed with 10 friends.- Wir spawnen ein Backend mit Owner + 10 Friend-Rows + ~50- Activity-Items. Dann pullt der erste Friend den Feed. Bandbreite =- Response-Body-Größe.+ We spawn a backend with an owner + 10 friend rows + ~50+ activity items. Then the first friend pulls the feed. Bandwidth =+ response body size."""from board_backend.models import ActivityItem, Friend@@ -143,7 +143,7 @@ async def benchmark_federation_pull() -> dict:json={"pubkey": owner_pub, "display_name": "Owner"},headers={"X-Admin-Token": "x"})- # 10 Friends + 50 Activity-Items.+ # 10 friends + 50 activity items.from datetime import datetime, timezonewith app.state.session_factory() as session:friends_priv = []@@ -167,7 +167,7 @@ async def benchmark_federation_pull() -> dict:))session.commit()- # Friend 0 pullt.+ # Friend 0 pulls.f0_priv, f0_pub = friends_priv[0]payload = {"ts_ms": int(time.time() * 1000)}body = canonical_json(payload)@@ -210,7 +210,7 @@ def main() -> None:print()print("=" * 72)- print("FEDERATION-PULL (10 friends, 50 items)")+ print("FEDERATION PULL (10 friends, 50 items)")print("=" * 72)res_fed = asyncio.run(benchmark_federation_pull())print(json.dumps(res_fed, indent=2))diff --git a/ui/__init__.py b/ui/__init__.pyindex d34d88175a..e6a75a7e7b 100644--- a/ui/__init__.py+++ b/ui/__init__.py@@ -1 +1 @@-"""Top-level UI namespace fuer Orb-Overlay und Highlight-Layer."""+"""Top-level UI namespace for the orb overlay and highlight layer."""diff --git a/ui/orb/animations.py b/ui/orb/animations.pyindex b5f64e54da..37ccf0eb70 100644--- a/ui/orb/animations.py+++ b/ui/orb/animations.py@@ -1,13 +1,13 @@-"""Stub fuer ``ui.orb.animations`` — Original-Modul lokal verloren.+"""Stub for ``ui.orb.animations`` — original module lost locally.-Das echte Modul lieferte den Animations-Katalog (idle-pulse, breath, wave,-etc.) plus ``Transform``/``ArmTransform``-Datenklassen, die Overlay-Renderer-zur Frame-Komposition kombiniert. Diese Stubs erfuellen die Import-API,-damit der Orb-Overlay-Bootstrap nicht crasht — Animationen sind dann nur-"identity" (kein visueller Effekt), aber der Speech-Pipeline-Setup-durchlaeuft ohne Exception.+The real module supplied the animation catalog (idle-pulse, breath, wave,+etc.) plus the ``Transform``/``ArmTransform`` dataclasses that the overlay+renderer combines for frame composition. These stubs satisfy the import API+so the orb-overlay bootstrap doesn't crash — animations then are just+"identity" (no visual effect), but the speech-pipeline setup+runs through without an exception.-Wenn das Original wiederhergestellt wird, ueberschreibt es diese Datei.+When the original is restored, it overwrites this file."""from __future__ import annotations@@ -17,11 +17,11 @@ from typing import Any@dataclass(frozen=True)class Transform:- """Body-Transform — Skalierung, Skew, Rotation, Translation, Helligkeit.+ """Body transform — scale, skew, rotation, translation, brightness.- Felder gemaess `ui/orb/overlay.py` (Zeilen 686-743): `scale`, `skew_x`,+ Fields per `ui/orb/overlay.py` (lines 686-743): `scale`, `skew_x`,`skew_y`, `dx`, `dy`, `rotation`, `brightness`. Identity = neutral- (kein visueller Effekt).+ (no visual effect)."""scale: float = 1.0@@ -33,7 +33,7 @@ class Transform:brightness: float = 1.0def combine(self, other: "Transform") -> "Transform":- """Multiplikative/additive Kombination (Identity-stable)."""+ """Multiplicative/additive combination (identity-stable)."""return Transform(scale=self.scale * other.scale,skew_x=self.skew_x * other.skew_x,@@ -47,10 +47,10 @@ class Transform:@dataclass(frozen=True)class ArmTransform:- """Arm-Transform — Rotation/Translation pro Arm.+ """Arm transform — rotation/translation per arm.- `rotation` (Radian) wird vom Renderer in Grad konvertiert; `dx`/`dy`- in Pixel; `visible` als Multiplier-Flag.+ `rotation` (radians) is converted to degrees by the renderer; `dx`/`dy`+ in pixels; `visible` as a multiplier flag."""rotation: float = 0.0@@ -77,7 +77,7 @@ def identity_arm() -> ArmTransform:@dataclassclass Animation:- """Basis-Animation — Stub liefert nur Identity-Frames."""+ """Base animation — the stub only returns identity frames."""name: str = "identity"t_start: float = 0.0@@ -97,23 +97,23 @@ class Animation:return (t - self.t_start) >= self.duration-# Leerer Registry — make_animation faellt auf eine generische Identity--# Animation zurueck wenn ``name`` nicht bekannt ist. So bleibt die-# Animations-Dispatch-Logik im Renderer frei von Crashes.+# Empty registry — make_animation falls back to a generic identity+# animation if ``name`` is unknown. This keeps the animation dispatch+# logic in the renderer free of crashes.ANIMATION_REGISTRY: dict[str, type[Animation]] = {}-# Idle-Pool: leeres Tuple → der Orb-Bus-Bridge-Idle-Loop probiert-# ``self._rng.choice(IDLE_ANIMATION_POOL)``, und choice auf leerem Tuple-# wirft IndexError. Wir geben einen einzelnen Identity-Eintrag, damit-# der Loop funktional bleibt (spielt halt nichts Sichtbares).+# Idle pool: an empty tuple → the orb-bus-bridge idle loop tries+# ``self._rng.choice(IDLE_ANIMATION_POOL)``, and choice on an empty tuple+# raises IndexError. We provide a single identity entry so+# the loop stays functional (it just plays nothing visible).IDLE_ANIMATION_POOL: tuple[str, ...] = ("identity",)def make_animation(name: str, *, t_start: float = 0.0, **params: Any) -> Animation:- """Factory — liefert eine Identity-Animation falls ``name`` unbekannt.+ """Factory — returns an identity animation if ``name`` is unknown.- Original-Verhalten war: ``ANIMATION_REGISTRY[name](...)`` — das wuerde- bei leerem Registry mit KeyError crashen. Wir fangen das ab.+ The original behavior was: ``ANIMATION_REGISTRY[name](...)`` — that+ would crash with KeyError on an empty registry. We catch that."""cls = ANIMATION_REGISTRY.get(name, Animation)return cls(name=name, t_start=t_start, params=params)diff --git a/ui/orb/bus_bridge.py b/ui/orb/bus_bridge.pyindex cf6ece41c0..fdd1bb79e2 100644--- a/ui/orb/bus_bridge.py+++ b/ui/orb/bus_bridge.py@@ -1,29 +1,29 @@-"""Bus-Bridge: verbindet den Jarvis-EventBus mit dem Orb-Overlay.+"""Bus bridge: connects the Jarvis EventBus to the orb overlay.-Der Orb selbst kennt weder Jarvis-Core, EventBus noch Supervisor-States.-Diese Bridge abonniert `SystemStateChanged` und uebersetzt die high-level-States (IDLE/LISTENING/THINKING/SPEAKING) in Orb-API-Calls.+The orb itself knows neither Jarvis core, EventBus, nor supervisor states.+This bridge subscribes to `SystemStateChanged` and translates the high-level+states (IDLE/LISTENING/THINKING/SPEAKING) into orb API calls.-Zusaetzlich verwaltet die Bridge den Mic-Listener-Lifecycle:- - LISTENING → Mic-Stream starten, live Level an den Orb pumpen- - THINKING / SPEAKING / IDLE → Mic-Stream stoppen (Privacy + CPU)+The bridge additionally manages the mic-listener lifecycle:+ - LISTENING → start the mic stream, pump live level to the orb+ - THINKING / SPEAKING / IDLE → stop the mic stream (privacy + CPU)-Animations-Mapping (Phase 1c-Add 2026-04-24):- LISTENING → 'wave' (Greet bei Wake-Word)- THINKING → 'think' (Loop-Bubble), gestoppt beim Wechsel- SPEAKING → leichtes 'nod' (subtle Bestaetigung)- SPEAKING → IDLE → 'salute' (Hangup-Geste, dann hide)- Idle-Scheduler → alle 30-90s Random-Animation aus Pool+Animation mapping (phase 1c-add 2026-04-24):+ LISTENING → 'wave' (greet on wake word)+ THINKING → 'think' (loop bubble), stopped on transition+ SPEAKING → a light 'nod' (subtle acknowledgement)+ SPEAKING → IDLE → 'salute' (hangup gesture, then hide)+ Idle scheduler → every 30-90s a random animation from the pool-Architektur-Regel: UI-Layer (L7) subscribed, Business-Layer (L2 Speech,-L6 Supervisor) publishen. Die Bridge lebt im UI-Layer.+Architecture rule: the UI layer (L7) subscribes, the business layer (L2+speech, L6 supervisor) publishes. The bridge lives in the UI layer.Threading:- subscribe()-Handler werden aus dem asyncio-Event-Loop aufgerufen;- sie rufen die Orb-API (show/hide/set_mode), die intern via- `root.after(0, ...)` die UI-Mutation in den Tk-Main-Thread queued.- Der Idle-Scheduler laeuft als asyncio.Task im selben Loop und- benutzt nur die thread-safe Orb-API.+ subscribe() handlers are called from the asyncio event loop; they call+ the orb API (show/hide/set_mode), which internally queues the UI+ mutation onto the Tk main thread via `root.after(0, ...)`.+ The idle scheduler runs as an asyncio.Task on the same loop and+ only uses the thread-safe orb API."""from __future__ import annotations@@ -65,16 +65,16 @@ if TYPE_CHECKING:log = logging.getLogger("jarvis.orb.bridge")-# Idle-Scheduler-Konfiguration: zufaellige Wartezeit zwischen Animationen.-# Range bewusst breit, damit der Ghost nicht "vorhersehbar" wirkt.+# Idle scheduler configuration: random wait time between animations.+# Range deliberately wide so the ghost doesn't feel "predictable".IDLE_MIN_INTERVAL_S = 30.0IDLE_MAX_INTERVAL_S = 90.0-# Hangup-Animation laeuft, dann verzoegerter hide()-Call.+# The hangup animation plays, then a delayed hide() call.SALUTE_DURATION_S = 1.1-# Grace-Period beim Wechsel von einem Voice-State (LISTENING/THINKING) zu-# IDLE, ohne dass ein SPEAKING dazwischen war (z.B. STT-Silence-Timeout):-# der User soll den Mascot noch kurz sehen, statt dass er instant verschwindet.+# Grace period when transitioning from a voice state (LISTENING/THINKING) to+# IDLE, without a SPEAKING state in between (e.g. an STT silence timeout):+# the user should still see the mascot briefly instead of it vanishing instantly.GRACE_HIDE_DURATION_S = 1.5# Long enough to cover an entire THINKING/SPEAKING phase. The transcript@@ -97,7 +97,7 @@ VOICE_BUBBLE_DURATION_MS = 30_000# the German live transcript and the German reply, and CLAUDE.md keeps# user-facing conversational content German. Single source of truth so it is# trivially translatable later.-THINKING_BUBBLE_TEXT = "Denke nach …"+THINKING_BUBBLE_TEXT = "Denke nach …" # i18n-allow# States during which the user is still composing their utterance and the# bubble must KEEP showing the live transcript (and accept further@@ -118,21 +118,26 @@ _USER_SIDE_BUBBLE_STATES = frozenset(# the guard at the top of ``_on_state``._ACTIVE_VOICE_STATES = frozenset({"LISTENING", "THINKING", "SPEAKING"})+# German public-broadcaster subtitle-credit boilerplate that German-language+# STT sometimes hallucinates onto silence/noise (e.g. "Untertitelung des ZDF+# fuer funk, 2020" / "Vielen Dank"). Must stay the literal German tokens the+# STT engine actually emits — this is speech-recognition input vocabulary,+# not translatable prose._TRANSCRIPT_BOILERPLATE_RE = re.compile(r"\b("- r"untertitelung\s+des\s+(zdf|wdr|ndr|swr|br|ard|arte)"- r"(\s+(fuer|für|fur)\s+funk)?(\s*,?\s*\d{4})?|"- r"untertitel\s+(von|der|im\s+auftrag)|"- r"(eine\s+)?(sendung|produktion|redaktion|programm)\s+"- r"(des|der|von)\s+(zdf|wdr|ndr|swr|br|ard|arte)"+ r"untertitelung\s+des\s+(zdf|wdr|ndr|swr|br|ard|arte)" # i18n-allow+ r"(\s+(fuer|für|fur)\s+funk)?(\s*,?\s*\d{4})?|" # i18n-allow+ r"untertitel\s+(von|der|im\s+auftrag)|" # i18n-allow+ r"(eine\s+)?(sendung|produktion|redaktion|programm)\s+" # i18n-allow+ r"(des|der|von)\s+(zdf|wdr|ndr|swr|br|ard|arte)" # i18n-allowr"(\s*,?\s*\d{4})?|"r"(zdf|wdr|ndr|swr|br|ard|arte)\s+"- r"(fernsehen|mediagroup|rundfunk)(\s*,?\s*\d{4})?|"- r"(norddeutscher|westdeutscher|bayerischer)\s+rundfunk|"- r"im\s+auftrag\s+des|"+ r"(fernsehen|mediagroup|rundfunk)(\s*,?\s*\d{4})?|" # i18n-allow+ r"(norddeutscher|westdeutscher|bayerischer)\s+rundfunk|" # i18n-allow+ r"im\s+auftrag\s+des|" # i18n-allowr"mediagroup|"r"thanks\s+for\s+watching|"- r"vielen\s+dank"+ r"vielen\s+dank" # i18n-allowr")\b",re.IGNORECASE,)@@ -155,7 +160,7 @@ def _is_transcript_boilerplate(text: str) -> bool:class OrbBusBridge:- """Koppelt den Orb an den Event-Bus + managed den Mic-Listener-Lifecycle."""+ """Couples the orb to the event bus + manages the mic-listener lifecycle."""def __init__(self,@@ -264,7 +269,7 @@ class OrbBusBridge:log.warning("%s publish dropped (no backend loop): %s", label, exc)def attach(self) -> None:- """Subscribt die Bridge auf SystemStateChanged. Idempotent."""+ """Subscribes the bridge to SystemStateChanged. Idempotent."""# If attach() runs on the backend loop (the live async-startup path),# capture it now so the very first gesture already marshals correctly.self._remember_loop()@@ -348,14 +353,14 @@ class OrbBusBridge:except Exception as exc: # noqa: BLE001log.warning("OrbBridge level_tap recency subscribe failed: %s", exc)log.info(- "OrbBridge subscribed auf SystemStateChanged + VoiceSessionStarted "+ "OrbBridge subscribed to SystemStateChanged + VoiceSessionStarted ""+ VoiceSessionEnded + ListeningStarted + TranscriptionUpdate ""+ ResponseGenerated + AudioOutFirst + OrbResetRequested ""+ mute-toggle gesture + show-window gesture ""+ visible-feedback contract.")except Exception as exc: # noqa: BLE001- log.exception("OrbBridge.attach() fehlgeschlagen: %s", exc)+ log.exception("OrbBridge.attach() failed: %s", exc)async def _on_reset_requested(self, event: OrbResetRequested) -> None:"""Voice-triggered reset: bring the orb back to the default@@ -615,17 +620,17 @@ class OrbBusBridge:state,)return- # No-op wenn es kein echter Wechsel ist (sollte Supervisor schon filtern,- # aber defensiv programmieren)+ # No-op if this isn't a real transition (the supervisor should already+ # filter this, but defensive programming)if state == self._last_state:returnprev_state = self._last_stateself._last_state = state- # Bei jedem State-Wechsel: laufende 'think'-Bubble killen — sie passt- # in keinem anderen State zur Realitaet und wuerde sonst kleben bleiben.+ # On every state transition: kill any running 'think' bubble — it+ # doesn't match reality in any other state and would otherwise linger.self._orb.stop_animation("think")- # Hangup-Task killen wenn neuer Zustand reinkommt waehrend Salut laeuft+ # Kill the hangup task if a new state comes in while the salute is playingif self._hangup_task and not self._hangup_task.done():self._hangup_task.cancel()self._hangup_task = None@@ -726,9 +731,9 @@ class OrbBusBridge:self._orb.play_animation("salute")self._start_idle_scheduler()return- # Drei Faelle, drei verzoegerte Hides — niemals instant-hide aus- # einem aktiven Voice-State, sonst sieht der User den Mascot bei- # kurzen Sessions (z.B. STT-Silence-Timeout) gar nicht.+ # Three cases, three delayed hides — never an instant hide out of+ # an active voice state, or the user won't see the mascot at all+ # during short sessions (e.g. an STT silence timeout).if prev_state == "SPEAKING" and state == "IDLE":self._orb.play_animation("salute")self._hangup_task = asyncio.create_task(@@ -873,8 +878,8 @@ class OrbBusBridge:self._orb.hide()else:self._orb.show(mode="idle")- # Idle-Scheduler nur wenn wir noch im IDLE-Zustand sind (keine- # neue Wake-Sequenz reingekommen waehrend des Salut).+ # Only (re-)start the idle scheduler if we're still in the IDLE+ # state (no new wake sequence came in during the salute).if self._last_state == "IDLE":self._start_idle_scheduler()except asyncio.CancelledError:@@ -900,14 +905,14 @@ class OrbBusBridge:# --- Idle-Animation-Scheduler --------------------------------------def _start_idle_scheduler(self) -> None:- """Startet einen Hintergrund-Task der zufaellig Idle-Animationen spielt.-- Bewusst NICHT im show()-Mode — der Orb ist hier hidden und das Window- nicht sichtbar. Idle-Animationen sind nur sichtbar wenn der User den- Orb sticky angezeigt hat (z.B. waehrend Vision-Live-Mode) oder wenn- eine kommende Phase einen Always-On-Mode einfuehrt. Wir schedulen- sie trotzdem schon — kostet nichts und ist beim Wechsel zu always-on- sofort sichtbar.+ """Starts a background task that randomly plays idle animations.++ Deliberately NOT in show() mode — the orb is hidden here and the+ window is not visible. Idle animations are only visible when the+ user has the orb stickily displayed (e.g. during vision live mode)+ or when an upcoming phase introduces an always-on mode. We schedule+ them anyway — it costs nothing and is immediately visible once+ switched to always-on."""if not self._idle_enabled:return@@ -923,7 +928,7 @@ class OrbBusBridge:self._idle_task = Noneasync def _idle_loop(self) -> None:- """Spielt alle 30-90s eine Random-Animation aus dem Idle-Pool."""+ """Plays a random animation from the idle pool every 30-90s."""try:while True:wait = self._rng.uniform(IDLE_MIN_INTERVAL_S, IDLE_MAX_INTERVAL_S)@@ -931,7 +936,7 @@ class OrbBusBridge:if self._last_state != "IDLE":returnname = self._rng.choice(IDLE_ANIMATION_POOL)- log.debug("Idle-Scheduler: %s", name)+ log.debug("Idle scheduler: %s", name)self._orb.play_animation(name)except asyncio.CancelledError:passdiff --git a/ui/orb/index.html b/ui/orb/index.htmlindex 6c89687be4..dfac2406e3 100644--- a/ui/orb/index.html+++ b/ui/orb/index.html@@ -5,10 +5,10 @@<title>Jarvis Orb</title><meta name="viewport" content="width=device-width,initial-scale=1" /><style>- /* Schwarz als Grund — das Host-Fenster und alle WebView2-Children werden- per SetWindowRgn zum Kreis geclippt (siehe overlay.py). Alles ausserhalb- des Kreises ist physisch weggeclippt; der schwarze Grund ist nur ein- Fallback falls das Clipping am Rand 1px ungenau ist. */+ /* Black as the base — the host window and all WebView2 children are+ clipped to a circle via SetWindowRgn (see overlay.py). Everything outside+ the circle is physically clipped away; the black base is just a+ fallback in case the clipping is off by 1px at the edge. */html, body {margin: 0; padding: 0; height: 100%; width: 100%;background: transparent;@@ -45,7 +45,7 @@window.addEventListener('resize', resize);resize();- // Python-Bridge+ // Python bridgelet mode = 'idle', extLevel = null, level = 0;window.__orb = {setMode(m) { mode = m; },@@ -55,23 +55,23 @@const TAU = Math.PI * 2;- // Plasma-Swirl-Partikel (als weiche Blobs, bewegen sich langsam im Inneren)+ // Plasma swirl particles (as soft blobs, move slowly inside)const swirls = [];for (let i = 0; i < 6; i++) {swirls.push({angle: Math.random() * TAU,radius: 0.15 + Math.random() * 0.35,- speed: 0.015 + Math.random() * 0.035, // bewusst langsam, nicht hypnotisch+ speed: 0.015 + Math.random() * 0.035, // deliberately slow, not hypnoticphase: Math.random() * TAU,size: 0.22 + Math.random() * 0.2,- hue: 45 + Math.random() * 15, // warmes Gelb-Gold+ hue: 45 + Math.random() * 15, // warm yellow-gold});}function currentLevel(t) {if (extLevel !== null) return extLevel;if (mode === 'speak') return 0.35 + 0.25 * Math.sin(t * 1.8) + 0.1 * Math.sin(t * 3.3);- if (mode === 'listen') return 0; // externes Level wird injiziert+ if (mode === 'listen') return 0; // external level gets injectedreturn 0;}@@ -80,8 +80,8 @@const t = (now - t0) / 1000;const w = canvas.clientWidth, h = canvas.clientHeight;const cx = w / 2, cy = h / 2;- // -1px Buffer, damit Anti-Aliasing am Kreisrand nicht gegen Magenta- // blendet (sonst rosa Fransen um den Orb herum).+ // -1px buffer so anti-aliasing at the circle edge doesn't blend+ // against magenta (otherwise pink fringes appear around the orb).const R = Math.min(w, h) * 0.5 - 1;const raw = currentLevel(t);@@ -91,11 +91,11 @@ctx.clearRect(0, 0, w, h);- // Harter Kreis-Clip: ab hier wird nur innerhalb des Orbs gezeichnet.+ // Hard circle clip: from here on, drawing only happens inside the orb.ctx.save();ctx.beginPath(); ctx.arc(cx, cy, R, 0, TAU); ctx.clip();- // --- 1. Glaskugel-Shell (dunkel, mit leichtem Randlicht)+ // --- 1. Glass sphere shell (dark, with slight edge light)const shell = ctx.createRadialGradient(cx - R * 0.3, cy - R * 0.3, R * 0.1,cx, cy, R@@ -106,7 +106,7 @@ctx.fillStyle = shell;ctx.fillRect(0, 0, w, h);- // --- 2. Plasma-Innenraum: Swirl-Blobs (additive, damit sie leuchten)+ // --- 2. Plasma interior: swirl blobs (additive, so they glow)ctx.save();ctx.globalCompositeOperation = 'lighter';for (const s of swirls) {@@ -124,7 +124,7 @@ctx.beginPath(); ctx.arc(px, py, size, 0, TAU); ctx.fill();}- // Heller Core in der Mitte+ // Bright core in the middleconst coreR = R * (0.2 + energy * 0.25);const core = ctx.createRadialGradient(cx, cy, 0, cx, cy, coreR);core.addColorStop(0, `rgba(255, 250, 210, ${0.9 + energy * 0.1})`);@@ -134,7 +134,7 @@ctx.beginPath(); ctx.arc(cx, cy, coreR, 0, TAU); ctx.fill();ctx.restore();- // --- 3. Glas-Highlight (gebogener heller Bogen fuer 3D-Gefuehl)+ // --- 3. Glass highlight (curved bright arc for a 3D feel)const hi = ctx.createRadialGradient(cx - R * 0.35, cy - R * 0.4, 0,cx - R * 0.35, cy - R * 0.4, R * 0.55@@ -145,7 +145,7 @@ctx.fillStyle = hi;ctx.fillRect(0, 0, w, h);- // --- 4. Rim-Light (feiner warmer Rand am Kreis)+ // --- 4. Rim light (fine warm edge around the circle)ctx.strokeStyle = `rgba(255, 210, 90, ${0.25 + energy * 0.25})`;ctx.lineWidth = Math.max(1, R * 0.008);ctx.beginPath(); ctx.arc(cx, cy, R - 1, 0, TAU); ctx.stroke();diff --git a/ui/orb/mic_listener.py b/ui/orb/mic_listener.pyindex 416d623948..ea0392fed0 100644--- a/ui/orb/mic_listener.py+++ b/ui/orb/mic_listener.py@@ -1,27 +1,27 @@-"""Microphone-Listener mit RMS-Level + adaptivem Noise-Gating.--Emittiert Audio-Level (0..1) an einen Callback, ~50 Hz. Der Level ist-normalisiert auf einen adaptiven Peak und durch Noise-Gating von-Hintergrundrauschen (Luefter, Tastatur, Kaffeemaschine) befreit.--Designentscheidung — kein silero-vad / webrtcvad:- Fuer die reine "laut-genug-zum-Pulsieren"-Logik waere eine VAD-Library- Overkill (Startup-Latenz, extra Modellgewicht). Stattdessen adaptive- Noise-Floor-Schaetzung per EMA: leise Frames ziehen den Floor langsam- nach, Speech-Threshold ist 3x Floor → self-kalibriert innerhalb- weniger Sekunden an Raum + Mic-Gain. Peak-Tracking mit Auto-Decay- liefert die Amplituden-Normalisierung.-- Wenn spaeter harte Speech/Non-Speech-Klassifikation gebraucht wird- (z.B. fuer Wake-Word-Trigger), kann silero-vad in einem separaten- Listener dazugenommen werden — der MicListener bleibt Level-only.--Threading-Kontrakt:- PortAudio ruft den internen Callback aus seinem eigenen Thread. Der- on_level-Callback, den der Aufrufer uebergibt, wird aus diesem- Thread aufgerufen — er muss also kurz und thread-safe sein. Fuer- OrbOverlay.set_level() ist das OK (nur eine Float-Zuweisung, atomic- unter GIL).+"""Microphone listener with RMS level + adaptive noise gating.++Emits an audio level (0..1) to a callback, ~50 Hz. The level is+normalized to an adaptive peak and cleared of background noise+(fan, keyboard, coffee machine) via noise gating.++Design decision — no silero-vad / webrtcvad:+ For the pure "loud-enough-to-pulse" logic, a VAD library would be+ overkill (startup latency, extra model weight). Instead, adaptive+ noise-floor estimation via EMA: quiet frames slowly pull the floor+ down, the speech threshold is 3x the floor → self-calibrates within+ a few seconds to the room + mic gain. Peak tracking with auto-decay+ provides the amplitude normalization.++ If a hard speech/non-speech classification is needed later+ (e.g. for a wake-word trigger), silero-vad can be added in a separate+ listener — the MicListener stays level-only.++Threading contract:+ PortAudio calls the internal callback from its own thread. The+ on_level callback the caller passes in is invoked from this+ thread — so it must be short and thread-safe. For+ OrbOverlay.set_level() this is fine (just a float assignment, atomic+ under the GIL)."""from __future__ import annotations@@ -35,14 +35,14 @@ SAMPLE_RATE = 16000FRAME_MS = 20FRAME_SAMPLES = SAMPLE_RATE * FRAME_MS // 1000 # 320-# Minimaler Floor — verhindert Division durch ~0 und unendliches Hochlaufen-# bei absolut stillen Eingaengen (stummgeschaltetes Mic).+# Minimum floor — prevents division by ~0 and unbounded runaway growth+# on absolutely silent input (a muted mic)._MIN_NOISE_FLOOR = 0.001_MIN_PEAK = 0.01class MicListener:- """Nicht-blockender Mic-Capture mit Level-Callback."""+ """Non-blocking mic capture with a level callback."""def __init__(self,@@ -53,11 +53,11 @@ class MicListener:self._device = deviceself._stream: sd.InputStream | None = None- # Adaptiver Noise-Floor: passt sich an Raumlautstaerke an+ # Adaptive noise floor: adjusts to the room's ambient loudnessself._noise_floor: float = 0.005- # Adaptiver Peak: normalisiert laute Worte auf 1.0+ # Adaptive peak: normalizes loud words to 1.0self._peak: float = 0.05- # Geglaetteter Output-Level fuer natuerliches Pulsieren+ # Smoothed output level for a natural pulsing feelself._smoothed: float = 0.0def start(self) -> None:@@ -83,23 +83,23 @@ class MicListener:# --- PortAudio-Thread ----------------------------------------------def _on_audio(self, indata, frames, time_info, status) -> None: # noqa: ARG002- # RMS des 20-ms-Frames. mono: indata.shape == (320, 1)+ # RMS of the 20ms frame. mono: indata.shape == (320, 1)rms = float(np.sqrt(np.mean(np.square(indata))))- # Noise-Floor nur bei leisen Frames updaten (EMA). Das verhindert,- # dass lautes Sprechen den Floor hochzieht und danach alles gated.+ # Only update the noise floor on quiet frames (EMA). This prevents+ # loud speech from pulling the floor up and then gating everything.if rms < self._noise_floor * 1.5:self._noise_floor = 0.95 * self._noise_floor + 0.05 * rmsself._noise_floor = max(self._noise_floor, _MIN_NOISE_FLOOR)- # Speech-Gate: unter 3x Noise-Floor gilt als "kein Sprechen".+ # Speech gate: below 3x the noise floor counts as "no speech".speech_threshold = self._noise_floor * 3.0gated = max(0.0, rms - speech_threshold)- # Peak-Tracking: schneller Anstieg, langsamer Abfall → Auto-Gain.- # 0.997^50 ≈ 0.86 pro Sekunde decay, d.h. in ~3 s halbiert sich der- # Peak wenn nichts mehr lautes kommt → nachfolgendes normales- # Sprechen wird schnell wieder als "voller Ausschlag" skaliert.+ # Peak tracking: fast rise, slow decay → auto-gain.+ # 0.997^50 ≈ 0.86 decay per second, i.e. the peak halves in ~3 s+ # once nothing loud comes in anymore → subsequent normal+ # speech is quickly scaled back to a "full swing" again.if gated > self._peak:self._peak = gatedelse:@@ -108,8 +108,8 @@ class MicListener:raw_level = min(1.0, gated / self._peak)- # Attack-fast, Release-slow — fuehlt sich wie natuerliches Pulsieren- # an. Ohne Release-Smoothing "flackert" der Orb.+ # Attack-fast, release-slow — feels like natural pulsing.+ # Without release smoothing the orb "flickers".if raw_level > self._smoothed:self._smoothed = 0.4 * self._smoothed + 0.6 * raw_levelelse:@@ -118,5 +118,5 @@ class MicListener:try:self._on_level(self._smoothed)except Exception:- # Callback-Fehler duerfen den Audio-Stream nicht killen+ # Callback errors must not kill the audio streampassdiff --git a/ui/orb/overlay.py b/ui/orb/overlay.pyindex f327db31e7..0a9526096e 100644--- a/ui/orb/overlay.py+++ b/ui/orb/overlay.py@@ -1,43 +1,43 @@-"""Jarvis-Orb als natives Desktop-Overlay (Tkinter + Pillow + numpy).--Historie der Ansaetze und warum wir bei Tkinter gelandet sind:- - pywebview + WebView2 Canvas: WebView2 rendert ueber DirectComposition,- SetWindowRgn/LWA_COLORKEY greifen nicht → rechteckiger Kasten blieb.- - PySide6 + WA_TranslucentBackground: Qt6+DWM auf Windows 11 liefert- haeufig nur einen opaken schwarzen Backing-Buffer + DropShadow-Rahmen- statt echter Transparenz. Dutzende bekannter Qt-Bugs, kein robuster Fix.- - Tkinter + wm_attributes('-transparentcolor'): nutzt die klassische- Win32 SetLayeredWindowAttributes-API mit LWA_COLORKEY. Stabil seit- Windows 2000, unabhaengig von DWM-Compositor-Quirks. Magenta (#FF00FF)- wird pixel-perfect transparent — Windows routet diese Pixel direkt- zum Desktop durch.--Rendering-Pipeline:- numpy berechnet pro Frame einen 108x108 RGB-Puffer. Radiale Gradienten,- additive Swirls und der helle Core werden als Vektor-Operationen auf- den Distance-Arrays ausgefuehrt (einmalig precomputed im Konstruktor).- Harter Kreis-Rand, kein Alpha-Fade nach aussen — sonst entstuenden- pinke Anti-Aliasing-Pixel an der Color-Key-Grenze. Pillow verpackt- das Array in ein PhotoImage, das Tkinter in einen Canvas rendert.--Public-API:- overlay = OrbOverlay(style="mascot") # SWG/Gigi-PNG- overlay.start() # blockt bis mainloop Exit+"""Jarvis-Orb as a native desktop overlay (Tkinter + Pillow + numpy).++History of approaches tried and why we landed on Tkinter:+ - pywebview + WebView2 Canvas: WebView2 renders via DirectComposition,+ so SetWindowRgn/LWA_COLORKEY have no effect → a rectangular box remained.+ - PySide6 + WA_TranslucentBackground: Qt6+DWM on Windows 11 frequently+ delivers only an opaque black backing buffer + a DropShadow frame+ instead of real transparency. Dozens of known Qt bugs, no robust fix.+ - Tkinter + wm_attributes('-transparentcolor'): uses the classic+ Win32 SetLayeredWindowAttributes API with LWA_COLORKEY. Stable since+ Windows 2000, independent of DWM compositor quirks. Magenta (#FF00FF)+ becomes pixel-perfect transparent — Windows routes those pixels+ straight through to the desktop.++Rendering pipeline:+ numpy computes a 108x108 RGB buffer per frame. Radial gradients,+ additive swirls, and the bright core are executed as vector operations+ on the distance arrays (precomputed once in the constructor).+ Hard circle edge, no alpha fade outward — otherwise pink anti-aliasing+ pixels would appear at the color-key boundary. Pillow wraps the array+ into a PhotoImage that Tkinter renders onto a Canvas.++Public API:+ overlay = OrbOverlay(style="mascot") # SWG/Gigi PNG+ overlay.start() # blocks until mainloop exitoverlay.show(mode="listen")overlay.show(mode="speak")overlay.hide()overlay.set_level(0.42)- overlay.set_style("mascot") # Runtime-Switch ohne Restart+ overlay.set_style("mascot") # runtime switch, no restart-ENV-Overrides:+ENV overrides:JARVIS_ORB_STYLE=mascot # legacy "orb" requests are ignored- JARVIS_ORB_MASCOT_PATH=<pfad.png> # alternativer Mascot-Pfad+ JARVIS_ORB_MASCOT_PATH=<path.png> # alternative mascot path-Standalone-Test:- python -m ui.orb.overlay # Demo-Sequenz (Mascot)- python -m ui.orb.overlay --sticky # dauerhaft sichtbar (Preview)- python -m ui.orb.overlay --sticky --mascot # SWG-Maskottchen statisch- python -m ui.orb.overlay --mic --mascot # SWG + Mic-reaktiv+Standalone test:+ python -m ui.orb.overlay # demo sequence (mascot)+ python -m ui.orb.overlay --sticky # permanently visible (preview)+ python -m ui.orb.overlay --sticky --mascot # SWG mascot, static+ python -m ui.orb.overlay --mic --mascot # SWG + mic-reactive"""from __future__ import annotations@@ -98,7 +98,7 @@ class _DragState:offset_y: intmoved: bool = False-# 108x108 — rund 1/3 kleiner als die alte 160er-Groesse+# 108x108 — roughly 1/3 smaller than the old 160-px sizeWIN_W = 108WIN_H = 108MARGIN_RIGHT = 24@@ -160,8 +160,8 @@ _WS_EX_TOOLWINDOW = 0x00000080TAU = math.tau-# Default-Pfad fuer das SWG/Gigi-Maskottchen. Wird von MascotRenderer gesucht,-# wenn kein expliziter Pfad uebergeben wird. Relativ zum Projekt-Root aufgeloest.+# Default path for the SWG/Gigi mascot. Looked up by MascotRenderer when no+# explicit path is passed in. Resolved relative to the project root.DEFAULT_MASCOT_REL = "assets/icons/jarvis-gigi-256.png"@@ -178,10 +178,10 @@ def _transcript_body_height(line_count: int, line_height: int) -> int:def _resolve_mascot_path(path_str: str | None) -> Path | None:- """Sucht das Maskottchen-PNG in gaengigen Ablagen.+ """Looks for the mascot PNG in the common locations.- Reihenfolge: expliziter Pfad → ENV ``JARVIS_ORB_MASCOT_PATH`` → Projekt-Root- (vom Modul hochlaufend). Returns None when no asset is available; callers+ Order: explicit path → ENV ``JARVIS_ORB_MASCOT_PATH`` → project root+ (walking up from the module). Returns None when no asset is available; callerskeep the overlay invisible instead of falling back to the removed legacy orb."""candidates: list[Path] = []@@ -190,7 +190,7 @@ def _resolve_mascot_path(path_str: str | None) -> Path | None:env_path = os.environ.get("JARVIS_ORB_MASCOT_PATH")if env_path:candidates.append(Path(env_path))- # Projekt-Root finden: diese Datei liegt in <root>/ui/orb/overlay.py+ # Find the project root: this file lives at <root>/ui/orb/overlay.pyhere = Path(__file__).resolve()for parent in [here.parent, here.parent.parent, here.parent.parent.parent]:candidates.append(parent / DEFAULT_MASCOT_REL)@@ -262,7 +262,7 @@ def _apply_jarvis_icon_to_tk_root(root: tk.Tk) -> None:def _hide_tk_window_from_task_switcher(root: tk.Tk) -> None:- """Markiert das Orb-Fenster als Toolwindow, damit es nicht als App zaehlt."""+ """Marks the orb window as a toolwindow so it doesn't count as an app."""if sys.platform != "win32":returntry:@@ -276,8 +276,8 @@ def _hide_tk_window_from_task_switcher(root: tk.Tk) -> None:style = (style | _WS_EX_TOOLWINDOW) & ~_WS_EX_APPWINDOWset_long(hwnd, _GWL_EXSTYLE, style)except Exception:- # Reine Desktop-Kosmetik. Wenn Win32 nicht greift, bleibt der Orb- # funktional und wird nur evtl. als zusaetzliches Fenster angezeigt.+ # Pure desktop cosmetics. If Win32 doesn't take effect, the orb+ # stays functional and may just show up as an extra window.return@@ -287,41 +287,41 @@ class MascotRenderer:Implements the render interface ``render(t, mode, ext_level) -> Image.Image``used by ``OrbOverlay``.- Besonderheiten:- - Alpha-Threshold (binär): Antialiasing-Kanten wuerden beim Composite- auf Magenta rosa Fringes erzeugen. Fuer den pixeligen Gigi-Stil ist- binäre Alpha ohnehin stimmig.- - Weicher Glow: Ein gaussian-blur'ed Alpha-Mask-Derivat liefert einen- warmen Halo um den Mascot, der mit ``energy`` pulsiert.- - Breathing-Scale: Der Mascot atmet (±3%) und skaliert mit Energie auf- bis ~107%. Skaliert wird mit NEAREST — das passt zum pixel-artigen- Look und ist per-frame fast kostenlos.+ Notable details:+ - Alpha threshold (binary): antialiasing edges would create pink+ fringes on magenta during compositing. For the pixel-art Gigi+ style, binary alpha is a good fit anyway.+ - Soft glow: a gaussian-blurred alpha-mask derivative provides a+ warm halo around the mascot that pulses with ``energy``.+ - Breathing scale: the mascot breathes (±3%) and scales with+ energy up to ~107%. Scaling uses NEAREST — this matches the+ pixel-art look and is nearly free per frame."""def __init__(self, image_path: Path) -> None:raw = Image.open(image_path).convert("RGBA")- # Einmal auf Zielgroesse; fuer per-frame Scale reicht NEAREST.+ # Once to target size; NEAREST is enough for per-frame scaling.base = raw.resize((WIN_W, WIN_H), Image.LANCZOS)self._base_rgba = np.asarray(base).copy() # (H,W,4) uint8self._base_pil = baseself._image_path = image_path- # Weicher Glow-Mask aus gaussian-geblurrter Alpha. Werte 0..1.- # Radius 6 gibt einen deutlich sichtbaren, aber tightt Halo.+ # Soft glow mask from a gaussian-blurred alpha. Values 0..1.+ # Radius 6 gives a clearly visible but tight halo.alpha_only = base.split()[3]blurred = alpha_only.filter(ImageFilter.GaussianBlur(radius=6))self._glow_mask = np.asarray(blurred).astype(np.float32) / 255.0- # Alpha-Threshold fuer den Mascot selbst (binär).+ # Alpha threshold for the mascot itself (binary).self._solid_mask = np.asarray(alpha_only) >= 128- # Body-Part-Decomposition: extrahiere die echten Arm-Stummel als- # eigene Sprites mit Pivot-Punkt. So koennen Animationen den- # ECHTEN Arm rotieren statt einen zweiten daneben zu zeichnen.- # _arm_left_sprite, _arm_right_sprite: kleine RGBA-Bilder mit Arm + transparent.- # _arm_left_pivot, _arm_right_pivot: (x, y) im Frame-Koord-System,- # Punkt um den die Rotation laeuft (Schulter zum Body).- # _body_no_arms_pil: Mascot-PIL ohne die Arm-Pixel (Alpha=0 dort).- # _arm_left_local_pivot: Pivot relativ zum Sprite-Rechteck (in Sprite-Pixeln).+ # Body-part decomposition: extract the actual arm stubs as their+ # own sprites with a pivot point. This lets animations rotate the+ # REAL arm instead of drawing a second one next to it.+ # _arm_left_sprite, _arm_right_sprite: small RGBA images with arm + transparent.+ # _arm_left_pivot, _arm_right_pivot: (x, y) in the frame coordinate system,+ # the point the rotation runs around (shoulder toward the body).+ # _body_no_arms_pil: mascot PIL without the arm pixels (alpha=0 there).+ # _arm_left_local_pivot: pivot relative to the sprite rectangle (in sprite pixels).decomp = self._decompose_arms(base)self._arm_left_sprite: Image.Image = decomp["left_sprite"]self._arm_right_sprite: Image.Image = decomp["right_sprite"]@@ -333,9 +333,9 @@ class MascotRenderer:self._level: float = 0.0- # Aktive Animationen — werden pro Frame gefiltert (is_finished).- # Liste statt Set, damit FIFO-Reihenfolge fuer Layering deterministisch- # ist (frueh hinzugefuegte Animationen zeichnen unter spaeteren).+ # Active animations — filtered per frame (is_finished).+ # A list rather than a set so FIFO order stays deterministic for+ # layering (animations added earlier draw beneath later ones).self._animations: list[Animation] = []# Mouth-anim deadline (in render-time `t` seconds). Mouth runs only@@ -343,15 +343,15 @@ class MascotRenderer:# original PNG mouth shows through unchanged.self._mouth_anim_until_t: float = -1.0- # Hard-coded Arm-Bounding-Boxes (gemessen am 108x108-Render des- # jarvis-gigi-256.png 2026-04-25). Heuristic-Detection war unzuverlaessig- # weil die Body-Outline auch gelbe Pixel enthaelt (Cluster ueberlappen).- # Diese BBoxes erfassen NUR den echten Stummel — saubere Trennung.- # Wenn das Asset wechselt: nochmal manuell ausmessen + hier eintragen.- # Sprite-BBox: gross genug um den Stummel + alle Outline-Spitzen zu erfassen.- # Body-Erase-BBox: enger, exakt am Stummel — sonst entstehen "Loecher" im- # Body bei Default-Pose (rot=0), weil das Sprite den geleerten Bereich- # nicht voll fuellt.+ # Hard-coded arm bounding boxes (measured on the 108x108 render of+ # jarvis-gigi-256.png, 2026-04-25). Heuristic detection was unreliable+ # because the body outline also contains yellow pixels (clusters overlap).+ # These bboxes capture ONLY the actual stub — a clean separation.+ # If the asset changes: re-measure manually and update these here.+ # Sprite bbox: large enough to capture the stub + all outline tips.+ # Body-erase bbox: tighter, exactly on the stub — otherwise "holes"+ # appear in the body at the default pose (rot=0), because the sprite+ # doesn't fully fill the cleared area.ARM_LEFT_BBOX = (10, 55, 22, 79)ARM_LEFT_PIVOT = (20, 62)ARM_LEFT_ERASE_BBOX = (12, 58, 21, 76)@@ -376,16 +376,16 @@ class MascotRenderer:@classmethoddef _decompose_arms(cls, base: Image.Image) -> dict:- """Trennt die Arm-Stummel des Mascots vom Body als separate Sprites.+ """Separates the mascot's arm stubs from the body as separate sprites.- Verwendet hard-coded Bounding-Boxes (ARM_LEFT_BBOX/ARM_RIGHT_BBOX)- statt heuristischer Yellow-Cluster-Detection — letztere erfasste auch- die Body-Outline-Pixel und produzierte unsaubere Sprites mit fremden- Pixeln, die nach Rotation den Arm verzogen.+ Uses hard-coded bounding boxes (ARM_LEFT_BBOX/ARM_RIGHT_BBOX)+ instead of heuristic yellow-cluster detection — the latter also+ picked up the body-outline pixels and produced unclean sprites with+ stray pixels that distorted the arm after rotation.- Body-Erase: BBox + 2px Padding wird komplett auf alpha=0 gesetzt,- damit der rotierte Arm freie Bahn hat (keine Outline-Reste in der- Schulter-Region, die den hochgehobenen Arm verdecken).+ Body erase: bbox + 2px padding is set entirely to alpha=0, so the+ rotated arm has a clear path (no leftover outline in the shoulder+ region that would otherwise cover the raised arm)."""arr = np.asarray(base) # (H,W,4)@@ -395,14 +395,14 @@ class MascotRenderer:erase_bbox: tuple[int, int, int, int],) -> dict:x0, y0, x1, y1 = sprite_bbox- # Sprite-Crop: bbox + Padding fuer Rotation-Headroom+ # Sprite crop: bbox + padding for rotation headroompad = 3sprite_x0 = max(0, x0 - pad)sprite_y0 = max(0, y0 - pad)sprite_x1 = min(arr.shape[1], x1 + 1 + pad)sprite_y1 = min(arr.shape[0], y1 + 1 + pad)crop = arr[sprite_y0:sprite_y1, sprite_x0:sprite_x1].copy()- # Sprite-Maske: nur Pixel innerhalb des sprite_bbox behalten+ # Sprite mask: keep only pixels inside sprite_bboxlocal_x0 = x0 - sprite_x0local_y0 = y0 - sprite_y0local_x1 = x1 + 1 - sprite_x0@@ -412,14 +412,14 @@ class MascotRenderer:crop[~mask, 3] = 0sprite = Image.fromarray(crop, mode="RGBA")- # Body-Erase: enger als sprite_bbox, exakt am Stummel.- # So fuellt die Default-Pose (rot=0) das Erase-Loch komplett aus- # und der Body sieht im Idle normal aus.+ # Body erase: tighter than sprite_bbox, exactly on the stub.+ # This way the default pose (rot=0) fully fills the erase hole+ # and the body looks normal at idle.ex0, ey0, ex1, ey1 = erase_bboxbody_erase = np.zeros(arr.shape[:2], dtype=bool)body_erase[ey0 : ey1 + 1, ex0 : ex1 + 1] = True- # Lokaler Pivot relativ zum Sprite-Crop+ # Local pivot relative to the sprite croppivot_local = (pivot_abs[0] - sprite_x0, pivot_abs[1] - sprite_y0)return {"sprite": sprite,@@ -435,10 +435,9 @@ class MascotRenderer:cls.ARM_RIGHT_BBOX, cls.ARM_RIGHT_PIVOT, cls.ARM_RIGHT_ERASE_BBOX,)- # Body ohne Arme: alle Pixel innerhalb der dilatierten Arm-Region- # auf alpha=0 setzen — entfernt sowohl die gelben Stummel als auch- # angrenzende Outline-Konturen, die sonst den hochgehobenen Arm- # ueberdecken wuerden.+ # Body without arms: set all pixels inside the dilated arm region+ # to alpha=0 — removes both the yellow stubs and the adjacent+ # outline contours that would otherwise cover the raised arm.body_arr = arr.copy()for entry in (left, right):mask = entry.get("body_erase_mask")@@ -458,18 +457,18 @@ class MascotRenderer:}# ------------------------------------------------------------------- # Animation-API (vom OrbOverlay aufgerufen, Tk-Main-Thread)+ # Animation API (called by OrbOverlay, Tk main thread)# ------------------------------------------------------------------def add_animation(self, animation: Animation) -> None:- """Fuegt eine laufende Animation hinzu. Threading: Caller stellt sicher- dass das im Tk-Main-Thread passiert (OrbOverlay queued via root.after).+ """Adds a running animation. Threading: the caller ensures this+ happens on the Tk main thread (OrbOverlay queues via root.after)."""self._animations.append(animation)def stop_animation(self, name: str) -> int:- """Entfernt alle laufenden Animationen mit dem gegebenen Namen.- Gibt Anzahl gestoppter Instanzen zurueck."""+ """Removes all running animations with the given name.+ Returns the number of stopped instances."""before = len(self._animations)self._animations = [a for a in self._animations if a.name != name]return before - len(self._animations)@@ -552,14 +551,14 @@ class MascotRenderer:frame[y0:y1, x0:x1] = np.asarray(small)def _aggregate_transform(self, t: float) -> Transform:- """Faltet alle aktiven Animations-Transforms in eine kombinierte Transform."""+ """Folds all active animation transforms into one combined transform."""result = identity_transform()for anim in self._animations:result = result.combine(anim.transform(t))return resultdef _aggregate_arm_transforms(self, t: float) -> tuple[ArmTransform, ArmTransform]:- """Faltet linke und rechte Arm-Transforms aus allen aktiven Animationen."""+ """Folds the left and right arm transforms from all active animations."""left = identity_arm()right = identity_arm()for anim in self._animations:@@ -568,7 +567,7 @@ class MascotRenderer:return left, right# ------------------------------------------------------------------- # Render-Pipeline+ # Render pipeline# ------------------------------------------------------------------def render(self, t: float, mode: str, ext_level: float | None) -> Image.Image:@@ -587,29 +586,29 @@ class MascotRenderer:breath = 0.5 + 0.5 * math.sin(t * 0.9)energy = max(self._level, breath * 0.1)- # --- Animations-Lifecycle: finished-Animationen jetzt entfernen,- # damit ihre Transforms und Overlays keinen "letzten Frame" mehr- # einbringen. Wichtig vor dem aggregate_transform-Call.+ # --- Animation lifecycle: remove finished animations now, so their+ # transforms and overlays no longer contribute a "last frame".+ # Important before the aggregate_transform call.if self._animations:self._animations = [a for a in self._animations if not a.is_finished(t)]anim_transform = self._aggregate_transform(t)- # Magenta-Hintergrund (Color-Key → transparent)+ # Magenta background (color key → transparent)frame = np.empty((WIN_H, WIN_W, 3), dtype=np.uint8)frame[:] = COLOR_KEY_RGB- # --- 1. Warmer Halo um den Mascot (gaussian-blurrte Alpha als Maske)- # Color-Key ist magenta — ein Weichblend mit Magenta erzeugt rosa Fringes.- # Darum Halo HART: Pixel entweder sichtbar (volle Gold-Mischung) oder- # magenta (transparent). Die Threshold-Grenze wird mit energy dynamisch- # verschoben — bei hoher Energie wird mehr vom Blur-Gradient sichtbar- # und der Halo wirkt "atmend/expandierend".- halo_threshold = 0.55 - energy * 0.35 # 0.55 ruhig → 0.20 laut+ # --- 1. Warm halo around the mascot (gaussian-blurred alpha as mask)+ # The color key is magenta — soft-blending with magenta creates pink+ # fringes. So the halo is HARD: a pixel is either visible (full gold+ # mix) or magenta (transparent). The threshold boundary shifts+ # dynamically with energy — at high energy more of the blur gradient+ # becomes visible and the halo feels "breathing/expanding".+ halo_threshold = 0.55 - energy * 0.35 # 0.55 calm → 0.20 loudhalo_mask = (self._glow_mask > halo_threshold) & ~self._solid_maskif halo_mask.any():- # Innerhalb des Halos: Intensity steigt mit glow_mask-Wert- # (dicht am Mascot = heller, Aussenkante = dunkler Gold).+ # Inside the halo: intensity rises with the glow_mask value+ # (close to the mascot = brighter, outer edge = darker gold).intensity = np.clip((self._glow_mask[halo_mask] - halo_threshold) / (1.0 - halo_threshold),0.0, 1.0,@@ -619,15 +618,15 @@ class MascotRenderer:frame[halo_mask, 1] = (50 + 160 * intensity).astype(np.uint8)frame[halo_mask, 2] = (0 + 80 * intensity).astype(np.uint8)- # --- 2. PRE-Layer aus Animationen (z.B. Wind-Striche hinter dem Ghost)+ # --- 2. PRE layer from animations (e.g. wind streaks behind the ghost)if self._animations:pre_layer = self._make_overlay_layer(t, which="pre")if pre_layer is not None:self._composite_layer(frame, pre_layer)- # --- 3. Body (ohne Arme) + Arme separat mit Pivot-Rotation- # Animations-Transform (scale, rotation, dx/dy, brightness) wird hier- # ON TOP der Atem-Skalierung addiert/multipliziert.+ # --- 3. Body (without arms) + arms rendered separately with pivot rotation+ # The animation transform (scale, rotation, dx/dy, brightness) is+ # added/multiplied ON TOP of the breathing scale here.breath_scale = 1.0 + 0.04 * math.sin(t * 0.9) + 0.03 * energytotal_scale = breath_scale * anim_transform.scalesx = total_scale * anim_transform.skew_x@@ -639,10 +638,9 @@ class MascotRenderer:body_rot_deg = -math.degrees(anim_transform.rotation)brightness_factor = (1.0 + 0.08 * energy) * anim_transform.brightness- # Body ohne Arme rendern (Body-Pixel + Augen + Mund + zackiger Boden,- # NUR die Arm-Stummel sind ge-erased). Damit ueberlappen rotierte- # Arme nicht mit dem statischen Stub und es entstehen keine- # "Doppelarm"-Artefakte.+ # Render the body without arms (body pixels + eyes + mouth + jagged+ # base, ONLY the arm stubs are erased). This way rotated arms don't+ # overlap the static stub and no "double-arm" artifacts appear.self._composite_sprite_centered(frame=frame,sprite_pil=self._body_no_arms_pil,@@ -654,11 +652,11 @@ class MascotRenderer:brightness=brightness_factor,)- # Arm-Transforms aus den aktiven Animationen aggregieren+ # Aggregate arm transforms from the active animationsarm_left_t, arm_right_t = self._aggregate_arm_transforms(t)- # Linker Arm — Pivot ist der Body-naechste Punkt des Stummels.- # Bei body-Skalierung skaliert auch der Pivot mit (Body-Scale-Aware).+ # Left arm — the pivot is the point of the stub closest to the body.+ # When the body scales, the pivot scales with it (body-scale-aware).if arm_left_t.visible:self._composite_arm(frame=frame,@@ -693,7 +691,7 @@ class MascotRenderer:# from OrbBusBridge on AudioOutFirst events).self._overlay_mouth(frame, t)- # --- 4. POST-Layer aus Animationen (Hand, Gedankenblase, Phone, Z-Z-Z…)+ # --- 4. POST layer from animations (hand, thought bubble, phone, Z-Z-Z…)if self._animations:post_layer = self._make_overlay_layer(t, which="post")if post_layer is not None:@@ -702,13 +700,13 @@ class MascotRenderer:return Image.fromarray(frame, mode="RGB")# ------------------------------------------------------------------- # Overlay-Helper+ # Overlay helpers# ------------------------------------------------------------------def _make_overlay_layer(self, t: float, which: str) -> Image.Image | None:- """Bittet alle Animationen, ihre Overlays in einen RGBA-Layer zu malen.- Gibt None zurueck wenn keine Animation den Layer beruehrt hat- (Pixel-Check ueber Alpha-Kanal-Sum, billig).+ """Asks all animations to paint their overlays into an RGBA layer.+ Returns None if no animation touched the layer+ (a cheap pixel check via the alpha-channel sum)."""layer = Image.new("RGBA", (WIN_W, WIN_H), (0, 0, 0, 0))draw = ImageDraw.Draw(layer)@@ -721,8 +719,8 @@ class MascotRenderer:any_drawn = Trueif not any_drawn:return None- # Fast-Path: wenn die ganze Layer leer (alpha=0) → None statt composite.- # Wir koennen das pruefen ohne extra-Walk: Pillow hat getbbox().+ # Fast path: if the whole layer is empty (alpha=0) → None instead of compositing.+ # We can check this without an extra walk: Pillow has getbbox().if layer.getbbox() is None:return Nonereturn layer@@ -738,11 +736,11 @@ class MascotRenderer:offset_dy: int,brightness: float,) -> None:- """Skaliert und rotiert ein Sprite, plaziert es zentriert + offset im Frame.+ """Scales and rotates a sprite, placing it centered + offset in the frame.- Genutzt fuer den Body (gesamtes Mascot ohne Arme). Der Sprite wird auf- target_w x target_h skaliert, dann optional rotiert (around center),- dann mit binaerer Alpha (>= 128) auf den Frame gesetzt.+ Used for the body (the whole mascot minus arms). The sprite is+ scaled to target_w x target_h, then optionally rotated (around+ center), then placed onto the frame using binary alpha (>= 128)."""if target_w == WIN_W and target_h == WIN_H and abs(rot_deg) < 0.05:tmp = sprite_pil@@ -772,76 +770,76 @@ class MascotRenderer:body_rotation_rad: float,brightness: float,) -> None:- """Rendert ein Arm-Sprite mit Pivot-Rotation um die Schulter.-- Mathematik:- 1. Sprite hat einen lokalen Pivot (Schulter im Sprite-Koord-System).- 2. Welt-Pivot ist die Schulter im Frame (108x108-System).- 3. Body-Transform (Scale + Body-Rotation um Body-Center) verschiebt- den Welt-Pivot — wir muessen die Schulter mitbewegen.- 4. Arm-Eigenrotation rotiert das Sprite UM seinen lokalen Pivot.- 5. Sprite wird so plaziert, dass der lokale Pivot auf dem- (verschobenen) Welt-Pivot landet.-- PIL.rotate(center=...) rotiert ein Bild um einen frei waehlbaren Punkt- — wir nutzen das fuer die Pivot-Rotation. expand=True vergroessert die- Bounds, damit der rotierte Arm nicht clippt.+ """Renders an arm sprite with pivot rotation around the shoulder.++ Math:+ 1. The sprite has a local pivot (shoulder in the sprite coordinate system).+ 2. The world pivot is the shoulder in the frame (108x108 system).+ 3. The body transform (scale + body rotation around the body center)+ moves the world pivot — we have to move the shoulder along with it.+ 4. The arm's own rotation rotates the sprite AROUND its local pivot.+ 5. The sprite is placed so that the local pivot lands on the+ (shifted) world pivot.++ PIL.rotate(center=...) rotates an image around a freely chosen point+ — we use that for the pivot rotation. expand=True enlarges the+ bounds so the rotated arm doesn't clip."""if arm_sprite.size == (1, 1):- return # Decomposition lieferte leeres Sprite (Asset-Mismatch)+ return # Decomposition produced an empty sprite (asset mismatch)rot_deg_arm = -math.degrees(arm_t.rotation)if abs(rot_deg_arm) < 0.05:rotated = arm_spritenew_pivot = local_pivotelse:- # Standard-Trick: Sprite in eine groessere Leinwand padden, so dass- # der Pivot exakt im Zentrum liegt. Dann mit center=Zentrum rotieren —- # das verhaelt sich vorhersehbar (PIL.rotate ohne center, expand=False- # rotiert pixel-stabil um die Bildmitte).+ # Standard trick: pad the sprite into a larger canvas so the+ # pivot sits exactly in the center. Then rotate with center=center —+ # this behaves predictably (PIL.rotate without center, expand=False,+ # rotates pixel-stably around the image midpoint).sw, sh = arm_sprite.sizepx, py = local_pivot- # Wie weit ist der Pivot vom rechten/unteren Rand entfernt?- # Die neue Leinwand muss so gross sein, dass die maximale Distanz- # vom Pivot zu jeder Sprite-Ecke in alle Richtungen Platz hat- # (sonst clippt die Rotation Sprite-Pixel).+ # How far is the pivot from the right/bottom edge?+ # The new canvas must be large enough that the maximum distance+ # from the pivot to any sprite corner has room in every direction+ # (otherwise the rotation clips sprite pixels).max_dist = int(math.ceil(math.hypot(max(px, sw - px), max(py, sh - py))))canvas_size = 2 * max_dist + 4canvas = Image.new("RGBA", (canvas_size, canvas_size), (0, 0, 0, 0))- # Pivot des Sprites soll im Zentrum der Leinwand landen+ # The sprite's pivot should land at the canvas centerpaste_x = canvas_size // 2 - pxpaste_y = canvas_size // 2 - pycanvas.paste(arm_sprite, (paste_x, paste_y))- # Rotation um Bildmitte — center-Default greift, expand=False+ # Rotation around the image midpoint — the center default applies, expand=Falserotated = canvas.rotate(rot_deg_arm, resample=Image.NEAREST, fillcolor=(0, 0, 0, 0))- # Neue Pivot-Position ist die Bildmitte+ # The new pivot position is the image midpointnew_pivot = (canvas_size // 2, canvas_size // 2)- # Welt-Pivot der Schulter, abgeleitet vom Body-Center + Mascot-relativer- # Position. Der ungescalte Welt-Pivot ist `world_pivot` im 108er Frame.- # Bei Skalierung muss er relativ zum Body-Center skaliert werden.+ # World pivot of the shoulder, derived from the body center + the+ # mascot-relative position. The unscaled world pivot is `world_pivot`+ # in the 108-frame. When scaling, it must be scaled relative to the body center.cx_body = WIN_W / 2.0cy_body = WIN_H / 2.0- # Body-relative Schulter-Position (vor Skalierung)+ # Body-relative shoulder position (before scaling)rel_x = world_pivot[0] - cx_bodyrel_y = world_pivot[1] - cy_body- # Skalieren+ # Scalerel_x *= body_scale_xrel_y *= body_scale_y- # Body-Rotation: rotiere die Schulter mit dem Body+ # Body rotation: rotate the shoulder with the bodyif abs(body_rotation_rad) >= 1e-4:cr = math.cos(body_rotation_rad)sr = math.sin(body_rotation_rad)rel_x_r = rel_x * cr - rel_y * srrel_y_r = rel_x * sr + rel_y * crrel_x, rel_y = rel_x_r, rel_y_r- # Welt-Pivot nach Body-Transform+ # World pivot after the body transformworld_pivot_x = cx_body + rel_x + body_offset_dx + arm_t.dxworld_pivot_y = cy_body + rel_y + body_offset_dy + arm_t.dy- # Plaziere Sprite so, dass new_pivot auf world_pivot landet+ # Place the sprite so that new_pivot lands on world_pivotx0 = int(round(world_pivot_x - new_pivot[0]))y0 = int(round(world_pivot_y - new_pivot[1]))@@ -856,10 +854,10 @@ class MascotRenderer:y0: int,brightness: float,) -> None:- """Blittet ein RGBA-Sprite an Position (x0, y0) in den 108er-Frame.+ """Blits an RGBA sprite at position (x0, y0) into the 108-px frame.- Binaere Alpha-Threshold (>= 128) damit Color-Key-Magenta nicht angefasst- wird. Brightness multipliziert die RGB-Werte (clip auf 255).+ Binary alpha threshold (>= 128) so the color-key magenta is never+ touched. Brightness multiplies the RGB values (clipped to 255)."""ph, pw = rgba_arr.shape[:2]src_x0 = max(0, -x0)@@ -882,17 +880,17 @@ class MascotRenderer:@staticmethoddef _composite_layer(frame: np.ndarray, layer: Image.Image) -> None:- """In-place RGBA-over-RGB Composite, Color-Key-sicher (Magenta).-- Strategie:- - Layer-Pixel mit alpha < 64 → ignorieren (nicht zeichnen).- - Pixel mit alpha >= 64:- * Wenn Frame-Pixel = Magenta (Color-Key, transparent) → HARTE- Setzung. Sonst entstuenden rosa Misch-Pixel die im Tk-Fenster- als Fringes durchscheinen.- * Wenn Frame-Pixel = nicht-magenta (innerhalb Halo/Mascot) →- Soft-Blend ueber Alpha. Hier ist der Frame ohnehin opak,- Misch-Pixel bleiben sichtbar als sauberer Uebergang.+ """In-place RGBA-over-RGB composite, color-key-safe (magenta).++ Strategy:+ - Layer pixels with alpha < 64 → ignore (don't draw).+ - Pixels with alpha >= 64:+ * If the frame pixel is magenta (color key, transparent) → HARD+ set. Otherwise pink mixed pixels would appear as fringes+ showing through in the Tk window.+ * If the frame pixel is non-magenta (inside the halo/mascot) →+ soft-blend over alpha. Here the frame is opaque anyway,+ so mixed pixels stay visible as a clean transition."""layer_arr = np.asarray(layer) # (H,W,4)alpha = layer_arr[:, :, 3]@@ -901,20 +899,20 @@ class MascotRenderer:returnsrc_rgb = layer_arr[:, :, :3].astype(np.float32)- # Color-Key-Detection: Frame-Pixel die genau magenta sind → "transparent"+ # Color-key detection: frame pixels that are exactly magenta → "transparent"is_magenta = ((frame[:, :, 0] == COLOR_KEY_RGB[0])& (frame[:, :, 1] == COLOR_KEY_RGB[1])& (frame[:, :, 2] == COLOR_KEY_RGB[2]))- # 1) Hard-set ueber Magenta (jeder draw_mask-Pixel ueber Magenta wird- # 1:1 mit der Layer-Farbe ueberschrieben — kein Blend).+ # 1) Hard-set over magenta (every draw_mask pixel over magenta is+ # overwritten 1:1 with the layer color — no blending).hard_mask = draw_mask & is_magentaif hard_mask.any():frame[hard_mask] = src_rgb[hard_mask].astype(np.uint8)- # 2) Soft-Blend ueber bereits-belegten Pixeln (Halo, Mascot)+ # 2) Soft-blend over already-occupied pixels (halo, mascot)soft_mask = draw_mask & ~is_magentaif soft_mask.any():a = (alpha[soft_mask].astype(np.float32) / 255.0)[:, None]@@ -1234,11 +1232,11 @@ class OrbCommentBubble:class OrbOverlay:- """Public Facade — Tkinter-basiert, Thread-safe via root.after(0, ...).+ """Public facade — Tkinter-based, thread-safe via root.after(0, ...).- tkinter selbst ist nicht thread-safe, aber `root.after(0, fn)` schedult- fn sicher in den Tk-Main-Loop. Daher wickeln wir alle Aufrufe aus- fremden Threads (Jarvis-Core, Demo-Thread) darueber ab.+ tkinter itself is not thread-safe, but `root.after(0, fn)` schedules+ fn safely onto the Tk main loop. So we route every call from other+ threads (Jarvis-Core, demo thread) through it."""def __init__(@@ -1251,7 +1249,7 @@ class OrbOverlay:"""style: only ``"mascot"`` is accepted. Legacy ``"orb"`` requests arecoerced to ``"mascot"``.- mascot_path: optionaler expliziter Pfad, sonst via ENV oder Default-Asset.+ mascot_path: optional explicit path, otherwise via ENV or the default asset.ENV-Override: ``JARVIS_ORB_STYLE=mascot`` may request mascot explicitly;legacy ``orb`` values are ignored."""@@ -1302,8 +1300,8 @@ class OrbOverlay:self._started = threading.Event()self._ui_queue: queue.Queue = queue.Queue()self._tk_thread_id: int | None = None- # Lazy-Import, damit der Orb auch ohne sounddevice startbar bleibt- # (Mic-Reactive ist optional).+ # Lazy import so the orb stays startable even without sounddevice+ # (mic-reactive mode is optional).self._mic = None# Style resolution: mascot-only. Keep accepting the old knobs so@@ -1342,7 +1340,7 @@ class OrbOverlay:_ensure_dpi_awareness()self._root = tk.Tk()self._root.title("JarvisOrb")- self._root.overrideredirect(True) # Frameless, kein DropShadow+ self._root.overrideredirect(True) # Frameless, no drop shadowself._root.wm_attributes("-topmost", True)self._root.wm_attributes("-transparentcolor", COLOR_KEY_HEX)self._root.configure(bg=COLOR_KEY_HEX)@@ -1505,16 +1503,16 @@ class OrbOverlay:self._started.set()- # Mic-Listener erst nach Window-Creation starten, damit eventuelle- # sounddevice-Fehler (kein Mic, PortAudio-Init) erst nach sichtbarem- # Orb auftreten und nicht stumm beim Start verschluckt werden.+ # Start the mic listener only after window creation, so any+ # sounddevice errors (no mic, PortAudio init) surface only after the+ # orb is visible and aren't silently swallowed at startup.if self._mic_reactive:try:from ui.orb.mic_listener import MicListenerself._mic = MicListener(on_level=self.set_level)self._mic.start()except Exception as exc:- print(f"[orb] Mic-Reactive konnte nicht starten: {exc}")+ print(f"[orb] Mic-reactive mode failed to start: {exc}")if auto_demo:threading.Thread(target=self._run_demo, daemon=True).start()@@ -2061,25 +2059,25 @@ class OrbOverlay:def set_level(self, level: float) -> None:self._ext_level = max(0.0, min(1.0, float(level)))- # --- Animations-API ------------------------------------------------+ # --- Animation API ------------------------------------------------def play_animation(self, name: str, **params) -> None:- """Startet eine benannte Animation (z.B. 'wave', 'salute', 'think').+ """Starts a named animation (e.g. 'wave', 'salute', 'think').- Thread-safe: queued via ``root.after(0, ...)`` in den Tk-Mainloop.- Funktioniert nur am MascotRenderer.+ Thread-safe: queued via ``root.after(0, ...)`` onto the Tk mainloop.+ Only works with the MascotRenderer.- Stack-Verhalten: mehrere Animationen koennen gleichzeitig laufen.- Eine erneute play_animation('wave') waehrend ein 'wave' noch lebt- addiert eine zweite Instanz — das ist gewollt (mehrfaches Winken).- Fuer "ersetzen" zuerst stop_animation('wave') aufrufen.+ Stacking behavior: several animations can run at the same time.+ Calling play_animation('wave') again while a 'wave' is still active+ adds a second instance — this is intentional (multiple waves).+ To "replace" it, call stop_animation('wave') first."""if not isinstance(self._renderer, MascotRenderer):returnif name not in ANIMATION_REGISTRY:import logginglogging.getLogger("jarvis.orb").warning(- "play_animation(%r) unbekannt — verfuegbar: %s",+ "play_animation(%r) unknown — available: %s",name, sorted(ANIMATION_REGISTRY),)return@@ -2099,10 +2097,10 @@ class OrbOverlay:self._enqueue_ui(_start)def stop_animation(self, name: str) -> None:- """Stoppt alle laufenden Instanzen einer Animation (z.B. 'think').+ """Stops all running instances of an animation (e.g. 'think').- No-op wenn keine Instanz existiert oder Renderer kein Mascot ist.- Wichtig fuer endlos-loopende Animationen wie 'think', 'sleep'.+ No-op if no instance exists or the renderer isn't the mascot.+ Important for endlessly-looping animations like 'think', 'sleep'."""if not isinstance(self._renderer, MascotRenderer):return@@ -2110,27 +2108,27 @@ class OrbOverlay:self._enqueue_ui(lambda: renderer.stop_animation(name))def clear_animations(self) -> None:- """Beendet alle aktiven Animationen sofort."""+ """Ends all active animations immediately."""if not isinstance(self._renderer, MascotRenderer):returnrenderer = self._rendererself._enqueue_ui(renderer.clear_animations)def active_animations(self) -> list[str]:- """Snapshot der aktuell laufenden Animations-Namen.+ """Snapshot of the currently running animation names.- NICHT Thread-safe (Read ohne Lock); nur fuer Tests/Debug gedacht.+ NOT thread-safe (read without a lock); intended for tests/debugging only."""if not isinstance(self._renderer, MascotRenderer):return []return self._renderer.active_animation_names()def set_style(self, style: str) -> None:- """Wechselt den Renderer zur Laufzeit (``"orb"`` oder ``"mascot"``).+ """Switches the renderer at runtime (``"orb"`` or ``"mascot"``).- Thread-safe — queued via root.after. Wenn ``"mascot"`` angefordert aber- das PNG nicht gefunden wird, bleibt der aktuelle Renderer unveraendert- (der Caller bekommt darueber den Logger-Warn-Eintrag).+ Thread-safe — queued via root.after. If ``"mascot"`` is requested but+ the PNG is not found, the current renderer stays unchanged+ (the caller learns about it via the logger warning entry)."""style = (style or "").lower()if style == "orb":@@ -2142,9 +2140,9 @@ class OrbOverlay:)style = "mascot"if style != "mascot":- raise ValueError(f"Unbekannter Style: {style!r} (erlaubt: mascot)")+ raise ValueError(f"Unknown style: {style!r} (allowed: mascot)")if self._root is None:- # Noch nicht gestartet → Style merken, start() picks it up+ # Not started yet → remember the style, start() picks it upself._style = stylereturnself._enqueue_ui(lambda: self._apply_style(style))@@ -2152,7 +2150,7 @@ class OrbOverlay:def _apply_style(self, style: str) -> None:new_renderer = self._build_renderer(style)if new_renderer is None:- return # Fallback-Fall wurde bereits in _build_renderer geloggt+ return # The fallback case was already logged in _build_rendererself._renderer = new_rendererself._style = style@@ -2162,8 +2160,8 @@ class OrbOverlay:if mascot_path is None:import logginglogging.getLogger("jarvis.orb").warning(- "Mascot-Style angefordert, aber PNG nicht gefunden "- "(gesucht: %s, ENV JARVIS_ORB_MASCOT_PATH, %s) — "+ "Mascot style requested but PNG not found "+ "(looked in: %s, ENV JARVIS_ORB_MASCOT_PATH, %s) — ""overlay will stay hidden.",self._mascot_path_hint, DEFAULT_MASCOT_REL,)@@ -2179,11 +2177,11 @@ class OrbOverlay:return Nonereturn None- # --- Intern --------------------------------------------------------+ # --- Internal --------------------------------------------------------def _set_mode(self, mode: str) -> None:if mode not in ("idle", "listen", "speak", "think"):- raise ValueError(f"Unbekannter Modus: {mode}")+ raise ValueError(f"Unknown mode: {mode}")self._mode = modedef _enqueue_ui(self, fn) -> None:@@ -2216,18 +2214,18 @@ class OrbOverlay:logging.getLogger("jarvis.orb").exception("Orb UI command failed")self._root.after(20, self._schedule_ui_queue)- # --- Thread-Lifecycle fuer Integration in async/asyncio-Welten -----+ # --- Thread lifecycle for integration into async/asyncio worlds -----def start_in_thread(self, auto_demo: bool = False, timeout: float = 3.0) -> None:- """Startet den Tk-Mainloop in einem Daemon-Thread und kehrt zurueck.+ """Starts the Tk mainloop on a daemon thread and returns.- Auf Windows ist Tk im Background-Thread stabil, solange alle- UI-Mutationen ueber `root.after(0, fn)` gequeued werden — das tun- unsere show/hide/set_mode/set_level-Methoden bereits.+ On Windows, Tk is stable on a background thread as long as all+ UI mutations are queued via `root.after(0, fn)` — our+ show/hide/set_mode/set_level methods already do this.- Blockt bis das Fenster wirklich existiert (self._started-Event),- damit der Caller danach sicher show()/hide() aufrufen kann ohne- in ein None-root zu laufen.+ Blocks until the window actually exists (self._started event),+ so the caller can safely call show()/hide() afterward without+ running into a None root."""import logging_log = logging.getLogger("jarvis.orb")@@ -2236,19 +2234,19 @@ class OrbOverlay:try:self.start(auto_demo=auto_demo)except Exception as exc:- # pythonw.exe hat kein stdout → print geht ins Leere. Logger- # schreibt ins Watchdog-Log und macht silent-deaths sichtbar.- _log.exception("Orb-Thread-Start fehlgeschlagen: %s", exc)+ # pythonw.exe has no stdout → print goes nowhere. The logger+ # writes to the watchdog log and makes silent deaths visible.+ _log.exception("Orb thread start failed: %s", exc)t = threading.Thread(target=_run, name="orb-tk-mainloop", daemon=True)t.start()ok = self._started.wait(timeout=timeout)if not ok:_log.error(- "Orb-Fenster nicht innerhalb %.1fs initialisiert — UI wird nicht poppen.",+ "Orb window not initialized within %.1fs — UI will not pop up.",timeout,)else:- _log.info("Orb-Overlay Tk-Mainloop läuft (Fenster initialisiert).")+ _log.info("Orb overlay Tk mainloop is running (window initialized).")def _schedule_frame(self) -> None:if not self._running or not self._root or not self._canvas or not self._renderer:@@ -2256,8 +2254,8 @@ class OrbOverlay:t = time.perf_counter() - self._t0img = self._renderer.render(t, self._mode, self._ext_level)- # PhotoImage muss als self._photo gehalten werden — sonst GC'd- # Tkinter das Image weg bevor es gerendert wird.+ # The PhotoImage must be kept as self._photo — otherwise Tkinter+ # garbage-collects the image before it gets rendered.self._photo = ImageTk.PhotoImage(img)if self._image_id is None:self._image_id = self._canvas.create_image(@@ -2291,25 +2289,25 @@ def main() -> int:parser.add_argument("--sticky",action="store_true",- help="Fenster dauerhaft sichtbar (Design-Preview)",+ help="Window permanently visible (design preview)",)parser.add_argument("--mic",action="store_true",- help="Mic-reaktiv: pulsiert mit Mikrofon-Lautstaerke + Shockwave-Ringe",+ help="Mic-reactive: pulses with microphone volume + shockwave rings",)parser.add_argument("--mascot",action="store_true",- help="Verwendet das SWG/Gigi-Maskottchen.",+ help="Uses the SWG/Gigi mascot.",)parser.add_argument("--mascot-path",type=str,default=None,help=(- "Optional: expliziter Pfad zu einem Mascot-PNG "- "(sonst assets/icons/jarvis-gigi-256.png)."+ "Optional: explicit path to a mascot PNG "+ "(otherwise assets/icons/jarvis-gigi-256.png)."),)parser.add_argument(@@ -2317,22 +2315,22 @@ def main() -> int:type=str,default=None,help=(- "Visual-QA: spielt eine bestimmte Animation in Endlosschleife "- "(impliziert --mascot --sticky). Verfuegbar: "+ "Visual QA: plays a specific animation in an endless loop "+ "(implies --mascot --sticky). Available: "+ ", ".join(sorted(ANIMATION_REGISTRY))),)parser.add_argument("--all-animations",action="store_true",- help="Spielt alle Animationen nacheinander durch (impliziert --mascot --sticky).",+ help="Plays all animations one after another (implies --mascot --sticky).",)args = parser.parse_args()if args.animation and args.animation not in ANIMATION_REGISTRY:print(- f"[orb] Unbekannte Animation {args.animation!r}. "- f"Verfuegbar: {', '.join(sorted(ANIMATION_REGISTRY))}"+ f"[orb] Unknown animation {args.animation!r}. "+ f"Available: {', '.join(sorted(ANIMATION_REGISTRY))}")return 2@@ -2347,17 +2345,17 @@ def main() -> int:mascot_path=args.mascot_path,)- # Demo-Threads je nach CLI-Argument+ # Demo threads depending on the CLI argumentauto_demo = Falseif args.animation:- # Loopt die gewuenschte Animation alle 2.5s neu — fuer Visual-QA+ # Re-loops the requested animation every 2.5s — for visual QAdef _loop_anim() -> None:overlay._started.wait(timeout=5.0)overlay.show(mode="listen")while True:overlay.play_animation(args.animation)- # Sleep so lange wie die Animation dauert + 0.6s Pause; loopende- # Animationen (duration=0) loopen wir alle 4s neu (Re-trigger).+ # Sleep as long as the animation takes + a 0.6s pause; looping+ # animations (duration=0) we re-loop every 4s (re-trigger).cls = ANIMATION_REGISTRY[args.animation]wait = cls.duration if cls.duration > 0 else 4.0time.sleep(wait + 0.6)@@ -2379,9 +2377,9 @@ def main() -> int:time.sleep(0.3)threading.Thread(target=_all_demo, daemon=True).start()else:- # Klassisches Demo (zeigt listen/speak-Wechsel) wenn nichts spezifiziert.- # Mit --mic kein auto_demo (sonst wuerde das Demo-Skript den Orb- # ausblenden, genau waehrend man reinspricht).+ # Classic demo (shows the listen/speak switch) when nothing is specified.+ # No auto_demo with --mic (otherwise the demo script would hide the+ # orb exactly while the user is speaking into the mic).auto_demo = not (args.sticky or args.mic)overlay.start(auto_demo=auto_demo)