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 jarvis core (isolated drain, partial)
Ruben Lütke030941f56bb8
diff --git a/jarvis/__main__.py b/jarvis/__main__.pyindex 54a9b03f87..03af361ab5 100644--- a/jarvis/__main__.py+++ b/jarvis/__main__.py@@ -33,24 +33,24 @@ from jarvis.ui.tray import JarvisState, JarvisTray, TrayCommanddef _build_parser() -> argparse.ArgumentParser:parser = argparse.ArgumentParser(prog="jarvis",- description="Personal Jarvis — voice-gesteuerter Meta-Orchestrator.",+ description="Personal Jarvis — voice-driven meta-orchestrator.",)parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}")- parser.add_argument("--wizard", action="store_true", help="Setup-Wizard neu starten.")- parser.add_argument("--check", action="store_true", help="Nur Hardware-Analyse zeigen.")- parser.add_argument("--plugins", action="store_true", help="Plugin-Registry auflisten.")- parser.add_argument("--debug", action="store_true", help="Debug-Logging + Console-Attach.")+ parser.add_argument("--wizard", action="store_true", help="Restart the setup wizard.")+ parser.add_argument("--check", action="store_true", help="Only show the hardware analysis.")+ parser.add_argument("--plugins", action="store_true", help="List the plugin registry.")+ parser.add_argument("--debug", action="store_true", help="Debug logging + console attach.")# Phase 5:parser.add_argument("--phase5-doctor", action="store_true", dest="phase5_doctor",- help="Prueft Phase-5-Voraussetzungen (Admin-Helper, "- "Vision-Deps, Kill-Hotkey, Cost-Config).")+ help="Checks Phase-5 prerequisites (admin helper, "+ "vision deps, kill hotkey, cost config).")parser.add_argument("--install-admin-helper", action="store_true",dest="install_admin_helper",- help="Generiert HMAC-Secret + registriert Admin-Helper-Shortcut.")+ help="Generates the HMAC secret + registers the admin helper shortcut.")parser.add_argument("--orb-doctor", action="store_true", dest="orb_doctor",- help="Dry-run-Diagnose: wo würde der Orb spawnen? "- "Liest jarvis.toml + EnumDisplayMonitors, ohne ein "- "Tk-Fenster zu öffnen (BUG-027 / ADR-0016).")+ help="Dry-run diagnostic: where would the orb spawn? "+ "Reads jarvis.toml + EnumDisplayMonitors, without "+ "opening a Tk window (BUG-027 / ADR-0016).")parser.add_argument("--doctor", action="store_true", dest="doctor",help="Completeness self-check: honestly report what is ""registered & ready vs. advertised but missing "@@ -103,27 +103,27 @@ def _cmd_phase5_doctor() -> int:lines.append(f"Jarvis {__version__} — Phase-5-Doctor")lines.append("=" * 60)- # Entry-points+ # Entry pointstry:# Computer-use harness name sourced from the local action gate# (single home for the literal).from jarvis.brain.local_action_gate import HARNESS_NAMEeps = list(_md.entry_points(group="jarvis.harness"))have_cu = any(ep.name == HARNESS_NAME for ep in eps)- lines.append(f"[{'OK' if have_cu else 'FAIL'}] Harness-Plugin "- f"{HARNESS_NAME!r} im Entry-Points-Index: {have_cu}")+ lines.append(f"[{'OK' if have_cu else 'FAIL'}] Harness plugin "+ f"{HARNESS_NAME!r} in entry-points index: {have_cu}")except Exception as exc: # noqa: BLE001- lines.append(f"[FAIL] Harness-Entry-Points nicht lesbar: {exc}")+ lines.append(f"[FAIL] Harness entry points not readable: {exc}")try:eps = list(_md.entry_points(group="jarvis.tool"))have_admin = any(ep.name == "dispatch-to-admin" for ep in eps)- lines.append(f"[{'OK' if have_admin else 'FAIL'}] Tool-Plugin "- f"'dispatch-to-admin' im Entry-Points-Index: {have_admin}")+ lines.append(f"[{'OK' if have_admin else 'FAIL'}] Tool plugin "+ f"'dispatch-to-admin' in entry-points index: {have_admin}")except Exception as exc: # noqa: BLE001- lines.append(f"[FAIL] Tool-Entry-Points nicht lesbar: {exc}")+ lines.append(f"[FAIL] Tool entry points not readable: {exc}")- # Config-Sections+ # Config sectionsraw = cfg._RAW_CONFIG if hasattr(cfg, "_RAW_CONFIG") else {}phase5_sections = ["vision", "computer_use", "admin_helper", "task_queue",@@ -135,25 +135,25 @@ def _cmd_phase5_doctor() -> int:lines.append(f"[{'ON ' if enabled else 'OFF'}] jarvis.toml:[{section}] "f"enabled={enabled}")- # Admin-HMAC+ # Admin HMACtry:secret = cfg.get_secret("jarvis_admin_hmac", "JARVIS_ADMIN_HMAC")- lines.append(f"[{'OK' if secret else 'MISS'}] HMAC-Secret "- f"im Credential-Manager: {'vorhanden' if secret else 'fehlt'}")+ lines.append(f"[{'OK' if secret else 'MISS'}] HMAC secret "+ f"in credential manager: {'present' if secret else 'missing'}")except Exception as exc: # noqa: BLE001- lines.append(f"[FAIL] HMAC-Secret-Pruefung: {exc}")+ lines.append(f"[FAIL] HMAC secret check: {exc}")- # Vision-Deps+ # Vision depstry:import mss # noqa: F401- lines.append("[OK ] mss (Screenshot) importierbar")+ lines.append("[OK ] mss (screenshot) importable")except Exception: # noqa: BLE001- lines.append("[FAIL] mss (Screenshot) nicht importierbar")+ lines.append("[FAIL] mss (screenshot) not importable")try:import pywinauto # noqa: F401- lines.append("[OK ] pywinauto (UIA-Tree) importierbar")+ lines.append("[OK ] pywinauto (UIA tree) importable")except Exception: # noqa: BLE001- lines.append("[FAIL] pywinauto (UIA-Tree) nicht importierbar")+ lines.append("[FAIL] pywinauto (UIA tree) not importable")_ = config # suppress unusedprint("\n".join(lines))@@ -282,7 +282,8 @@ def _cmd_orb_doctor() -> int:lines.append("")lines.append("Warning: orb will spawn on a non-primary monitor. Say "- "'Orb zurück' or use the right-click menu to reset."+ "'Orb zurück'" # i18n-allow: recognized voice-trigger phrase (ADR-0016 L2)+ " or use the right-click menu to reset.")print("\n".join(lines))@@ -312,24 +313,24 @@ def _cmd_install_admin_helper() -> int:try:from jarvis.admin.launcher import ensure_admin_secretexcept ImportError as exc:- print(f"Admin-Helper-Launcher nicht importierbar: {exc}", file=sys.stderr)+ print(f"Admin helper launcher not importable: {exc}", file=sys.stderr)return 1try:secret = ensure_admin_secret()except Exception as exc: # noqa: BLE001- print(f"Admin-HMAC-Generation fehlgeschlagen: {exc}", file=sys.stderr)+ print(f"Admin HMAC generation failed: {exc}", file=sys.stderr)return 2- print(f"Admin-HMAC-Secret bereit (Laenge: {len(secret)} Bytes).")- print("Der Helper wird beim naechsten Admin-Op via UAC-Prompt gestartet.")+ print(f"Admin HMAC secret ready (length: {len(secret)} bytes).")+ print("The helper will be launched via UAC prompt on the next admin op.")return 0async def _run_tray_app(debug: bool = False) -> int:"""Tray app event loop."""config = cfg.load_config()- print(f"Jarvis {__version__} gestartet (Profile: {config.profile.name}).")+ print(f"Jarvis {__version__} started (profile: {config.profile.name}).")if debug:- print(f"Config-Datei: {cfg.DEFAULT_CONFIG_FILE}")+ print(f"Config file: {cfg.DEFAULT_CONFIG_FILE}")print(f"Brain primary: {config.brain.primary}")print(f"STT: {config.stt.provider} / {config.stt.model}")print(f"TTS: {config.tts.provider}")@@ -352,7 +353,7 @@ async def _run_tray_app(debug: bool = False) -> int:# Windows + subprocess contexts sometimes do not allow signal registrationpass- print("Tray-Icon läuft. Rechtsklick für Menu. Beenden mit Strg+C oder Tray → Beenden.")+ print("Tray icon running. Right-click for menu. Quit with Ctrl+C or Tray → Quit.")async def _command_handler() -> None:while not stop_event.is_set():@@ -370,9 +371,9 @@ async def _run_tray_app(debug: bool = False) -> int:elif cmd.action == "reload_config":try:cfg.load_config()- print("Config neu geladen.")+ print("Config reloaded.")except Exception as exc: # noqa: BLE001- print(f"Config-Reload fehlgeschlagen: {exc}")+ print(f"Config reload failed: {exc}")tray.set_error(str(exc))handler_task = asyncio.create_task(_command_handler())@@ -381,7 +382,7 @@ async def _run_tray_app(debug: bool = False) -> int:finally:handler_task.cancel()tray.stop()- print("Jarvis beendet.")+ print("Jarvis stopped.")return 0diff --git a/jarvis/admin/client.py b/jarvis/admin/client.pyindex 983582d26b..9cad91d25c 100644--- a/jarvis/admin/client.py+++ b/jarvis/admin/client.py@@ -55,7 +55,7 @@ class DestructiveRequiresApproval(Exception):def __init__(self, op: AdminOperation) -> None:super().__init__(- f"Op '{op.type}' ist destruktiv und braucht explizite Zustimmung."+ f"Op '{op.type}' is destructive and requires explicit approval.")self.op = opself.op_id = str(op.op_id)@@ -63,11 +63,11 @@ class DestructiveRequiresApproval(Exception):class AdminClient:- """High-level Interface: ``AdminClient(bus, cancel_token).execute(op)``.+ """High-level interface: ``AdminClient(bus, cancel_token).execute(op)``.- Die Transport-Verbindung wird lazy beim ersten Call aufgebaut. ``AdminClient``- ist bewusst leichtgewichtig — kein Connection-Pool, da Admin-Ops selten- sind. The byte transport is selected per OS via ``make_admin_transport()``+ The transport connection is built lazily on the first call. ``AdminClient``+ is deliberately lightweight — no connection pool, since admin ops are+ rare. The byte transport is selected per OS via ``make_admin_transport()``(Windows named pipe / Unix domain socket); the elevation mechanism isselected per OS via ``make_elevator()`` (UAC / polkit / sudo / osascript /Null). Both are injectable for tests (``pipe_client=`` / ``elevator=``),@@ -167,7 +167,7 @@ class AdminClient:op_id=op.op_id,success=False,error_code="cancelled",- error_message=f"CancelToken gesetzt: {reason}",+ error_message=f"CancelToken set: {reason}",)# 3. Ensure transport client + elevation@@ -179,8 +179,8 @@ class AdminClient:success=False,error_code="no_secret",error_message=(- "HMAC-Secret fehlt im Credential Manager — "- "Admin-Helper wurde noch nicht initialisiert."+ "HMAC secret missing in the Credential Manager — "+ "the admin helper has not been initialized yet."),)# AD-6: when no elevation mechanism is available (NullElevator on adiff --git a/jarvis/admin/executor.py b/jarvis/admin/executor.pyindex 1740083ed8..daa705d43a 100644--- a/jarvis/admin/executor.py+++ b/jarvis/admin/executor.py@@ -133,7 +133,7 @@ class AdminExecutor:# in lpCommandLine).for segment in argv:if not isinstance(segment, str):- raise TypeError(f"argv-Segment muss str sein, nicht {type(segment)}")+ raise TypeError(f"argv segment must be str, not {type(segment)}")proc = await asyncio.create_subprocess_exec(*argv,@@ -505,7 +505,7 @@ class AdminExecutor:return {"success": False,"error_code": "invalid_binary_hex",- "error_message": "value_data konnte nicht als Hex dekodiert werden.",+ "error_message": "value_data could not be decoded as hex.",}with winreg.CreateKey(hive, op.key_path) as key:winreg.SetValueEx(key, op.value_name, 0, type_const, data)@@ -599,7 +599,7 @@ class AdminExecutor:return {"success": False,"error_code": "path_exists",- "error_message": f"{target} existiert und overwrite=False",+ "error_message": f"{target} exists and overwrite=False",}try:diff --git a/jarvis/admin/helper.py b/jarvis/admin/helper.pyindex df3baee272..6aeae063cb 100644--- a/jarvis/admin/helper.py+++ b/jarvis/admin/helper.py@@ -41,22 +41,22 @@ from .transport import current_user_sid, default_pipe_name, make_admin_transportdef _parse_args(argv: list[str] | None = None) -> argparse.Namespace:p = argparse.ArgumentParser(prog="jarvis.admin.helper",- description="UAC-elevateter Admin-Helper fuer Personal Jarvis (ADR-0001).",+ description="UAC-elevated admin helper for Personal Jarvis (ADR-0001).",)p.add_argument("--pipe-name",default=None,- help="Named-Pipe-Pfad. Default: \\\\.\\pipe\\jarvis-admin-<user-sid>",+ help="Named pipe path. Default: \\\\.\\pipe\\jarvis-admin-<user-sid>",)p.add_argument("--keyring-key",default=ADMIN_HMAC_KEY,- help="Keyring-Key fuer das HMAC-Secret.",+ help="Keyring key for the HMAC secret.",)p.add_argument("--env-fallback",default=ADMIN_HMAC_ENV,- help="ENV-Variable als Fallback fuer das HMAC-Secret.",+ help="ENV variable as fallback for the HMAC secret.",)return p.parse_args(argv)@@ -67,8 +67,8 @@ def _load_secret(keyring_key: str, env_fallback: str) -> bytes:logger.error("admin_helper.no_secret",keyring_key=keyring_key, env_fallback=env_fallback)raise SystemExit(- "Kein HMAC-Secret im Credential Manager. "- "Setup-Wizard ausfuehren oder `jarvis_admin_hmac` via keyring setzen."+ "No HMAC secret in the Credential Manager. "+ "Run the setup wizard or set `jarvis_admin_hmac` via keyring.")try:return base64.urlsafe_b64decode(raw.encode("ascii"))diff --git a/jarvis/admin/ipc.py b/jarvis/admin/ipc.pyindex b947d5faac..03a47f0cbe 100644--- a/jarvis/admin/ipc.py+++ b/jarvis/admin/ipc.py@@ -130,7 +130,7 @@ class AdminPipeServer:transport: AdminTransport | None = None,) -> None:if not secret or len(secret) < 16:- raise ValueError("secret muss mindestens 16 Bytes sein")+ raise ValueError("secret must be at least 16 bytes")self._secret = secretself._pipe_name = pipe_nameself._executor = executor@@ -331,7 +331,7 @@ class AdminPipeClient:io_timeout_s: float = 180.0,transport: AdminTransport | None = None) -> None:if not secret or len(secret) < 16:- raise ValueError("secret muss mindestens 16 Bytes sein")+ raise ValueError("secret must be at least 16 bytes")self._secret = secretself._pipe_name = pipe_nameself._connect_timeout_ms = connect_timeout_ms@@ -361,13 +361,13 @@ class AdminPipeClient:return AdminResponse(op_id=op.op_id, success=False,error_code="ipc_timeout",- error_message="Admin-Helper antwortete nicht innerhalb der Frist.",+ error_message="Admin helper did not respond within the deadline.",)except FileNotFoundError:return AdminResponse(op_id=op.op_id, success=False,error_code="helper_unavailable",- error_message=f"Named-Pipe {self._pipe_name} existiert nicht.",+ error_message=f"Named pipe {self._pipe_name} does not exist.",)except Exception as exc: # noqa: BLE001return AdminResponse(diff --git a/jarvis/admin/launcher.py b/jarvis/admin/launcher.pyindex 828fed1e56..0aed043592 100644--- a/jarvis/admin/launcher.py+++ b/jarvis/admin/launcher.py@@ -65,7 +65,7 @@ def ensure_admin_secret(*, force: bool = False) -> str:logger.warning("admin_launcher.keyring_write_failed",key=ADMIN_HMAC_KEY,- hint="Helper kann nur ueber ENV-Fallback starten.",+ hint="Helper can only start via the ENV fallback.",)return encoded@@ -129,7 +129,7 @@ def launch_elevated_helper(# pipe name would contain anyway.import re as _reif not _re.fullmatch(r"\\\\\.\\pipe\\[A-Za-z0-9._\-]{1,200}", pipe):- raise ValueError(f"Ungueltiger pipe_name: {pipe!r}")+ raise ValueError(f"Invalid pipe_name: {pipe!r}")python_exe, args = _build_helper_argv()full_args = f'{args} --pipe-name "{pipe}"'@@ -142,7 +142,7 @@ def launch_elevated_helper(from win32com.shell import shell, shellcon # type: ignore[import-not-found]except ImportError as exc: # pragma: no cover — only on real Windowsraise RuntimeError(- "pywin32 nicht verfuegbar — launch_elevated_helper braucht Windows."+ "pywin32 not available — launch_elevated_helper requires Windows.") from excsei = shell.ShellExecuteEx(@@ -156,7 +156,7 @@ def launch_elevated_helper(if not h_process:# ShellExecuteEx error → user declined, or path is wrong, etc.raise UACCancelledError(- "UAC-Prompt wurde abgelehnt oder Helper konnte nicht gestartet werden."+ "UAC prompt was declined or the helper could not be started.")try:@@ -174,10 +174,10 @@ def launch_elevated_helper(if state == win32event.WAIT_OBJECT_0:exit_code = win32process.GetExitCodeProcess(h_process)raise HelperStartTimeoutError(- f"Helper ist frueh beendet (exit={exit_code}) — Pipe nie ready."+ f"Helper exited early (exit={exit_code}) — pipe never ready.")raise HelperStartTimeoutError(- f"Pipe {pipe} wurde nach {pipe_timeout_ms}ms nicht ready."+ f"Pipe {pipe} was not ready after {pipe_timeout_ms}ms.")logger.info("admin_launcher.started", pid=pid, pipe=pipe)diff --git a/jarvis/audio/capture.py b/jarvis/audio/capture.pyindex d51bd8d02b..b8574816ef 100644--- a/jarvis/audio/capture.py+++ b/jarvis/audio/capture.py@@ -42,23 +42,23 @@ _BLOCKED_INPUT_SUBSTRINGS = ("Output","Speaker","Speakers",- "Lautsprecher",+ "Lautsprecher", # i18n-allow: matched against a localized (German) Windows device name"Headphones",- "Kopfhoerer",- "Kopfhörer",+ "Kopfhoerer", # i18n-allow: matched against a localized (German) Windows device name+ "Kopfhörer", # i18n-allow: matched against a localized (German) Windows device name"HDMI","Display","NVIDIA High Definition","AMD HD Audio","Microsoft Soundmapper",- "Primaerer Soundtreiber",- "Primärer Soundtreiber",+ "Primaerer Soundtreiber", # i18n-allow: matched against a localized (German) Windows device name+ "Primärer Soundtreiber", # i18n-allow: matched against a localized (German) Windows device name)_INPUT_PRIORITY = ("Logitech PRO X", "PRO X", "Logitech","Jabra", "Sennheiser", "SteelSeries", "Corsair", "HyperX", "Razer",- "USB Audio", "Headset", "Microphone", "Mikrofon",+ "USB Audio", "Headset", "Microphone", "Mikrofon", # i18n-allow: matched against a localized (German) Windows device name"Realtek HD Audio", "Realtek",)@@ -168,17 +168,17 @@ def _resolve_input_device(device: int | str | None) -> int | str | None:if device is not None:_log.info("Mic-Resolve: explizites Device {} verwendet.", device)else:- _log.info("Mic-Resolve: System-Default-Input (device=None).")+ _log.info("Mic-Resolve: system default input (device=None).")return deviceif not isinstance(device, str) or device != "auto-headset":- _log.info("Mic-Resolve: benanntes Device '{}'.", device)+ _log.info("Mic-Resolve: named device '{}'.", device)return devicetry:devices = sd.query_devices()hostapis = sd.query_hostapis()except Exception as exc:- _log.warning("Mic-Resolve: sd.query_devices() fehlgeschlagen ({}). Fallback auf System-Default.", exc)+ _log.warning("Mic-Resolve: sd.query_devices() failed ({}). Falling back to system default.", exc)return Nonecandidates: list[tuple[int, dict]] = []@@ -233,7 +233,7 @@ def _resolve_input_device(device: int | str | None) -> int | str | None:else "?")_log.info(- "Mic-Resolve 'auto-headset': '{}' (idx={}, hostapi={}) — {} Kandidat(en).",+ "Mic-Resolve 'auto-headset': '{}' (idx={}, hostapi={}) — {} candidate(s).",chosen_dev.get("name", "?"),chosen_idx,chosen_hostapi,@@ -241,13 +241,13 @@ def _resolve_input_device(device: int | str | None) -> int | str | None:)return chosen_idx_log.warning(- "Mic-Resolve 'auto-headset': keine Kandidaten gefunden — Fallback auf System-Default."+ "Mic-Resolve 'auto-headset': no candidates found — falling back to system default.")return Noneclass MicrophoneCapture:- """Async-Wrapper um sounddevice.InputStream.+ """Async wrapper around sounddevice.InputStream.Usage:mic = MicrophoneCapture()@@ -352,7 +352,7 @@ class MicrophoneCapture:self._stream = streamself._device = attempt_log.info(- "Mic geoeffnet (device={}, sr={}, blocksize={}, dtype={}).",+ "Mic opened (device={}, sr={}, blocksize={}, dtype={}).",attempt,self._sample_rate,self._blocksize,@@ -362,18 +362,18 @@ class MicrophoneCapture:except Exception as exc: # noqa: BLE001last_error = exc_log.warning(- "Mic-Open auf device={} fehlgeschlagen ({}); probiere naechsten Fallback.",+ "Mic-Open on device={} failed ({}); trying next fallback.",attempt,exc,)_log.error(- "Mic-Open komplett fehlgeschlagen ({} Versuch[e]) — letzter Fehler: {}",+ "Mic-Open failed completely ({} attempt(s)) — last error: {}",len(attempts),last_error,)if last_error is not None:raise last_error- raise RuntimeError("Kein Mikrofon-Device verfuegbar.")+ raise RuntimeError("No microphone device available.")async def _stream_watchdog(self) -> None:"""Detect silent stream death and restart the InputStream.@@ -401,7 +401,7 @@ class MicrophoneCapture:continueself._restart_count += 1_log.warning(- "Mic-Stall erkannt ({:.1f}s ohne Frame) — Restart #{} (device={}).",+ "Mic stall detected ({:.1f}s without a frame) — restart #{} (device={}).",elapsed,self._restart_count,self._device,@@ -412,17 +412,17 @@ class MicrophoneCapture:try:old_stream.stop()except Exception as exc: # noqa: BLE001- _log.debug("Mic-Restart: stop() ignoriert ({}).", exc)+ _log.debug("Mic-Restart: stop() ignored ({}).", exc)try:old_stream.close()except Exception as exc: # noqa: BLE001- _log.debug("Mic-Restart: close() ignoriert ({}).", exc)+ _log.debug("Mic-Restart: close() ignored ({}).", exc)try:await self._try_open_stream()- _log.info("Mic-Restart #{} erfolgreich.", self._restart_count)+ _log.info("Mic-Restart #{} succeeded.", self._restart_count)except Exception as exc: # noqa: BLE001_log.error(- "Mic-Restart #{} fehlgeschlagen: {} — naechster Versuch in 5s.",+ "Mic-Restart #{} failed: {} — next attempt in 5s.",self._restart_count,exc,)@@ -464,7 +464,7 @@ class MicrophoneCapture:finally:self._stream = None_log.info(- "Mic geschlossen (drops={}, restarts={}).",+ "Mic closed (drops={}, restarts={}).",self._drops,self._restart_count,)diff --git a/jarvis/audio/player.py b/jarvis/audio/player.pyindex 6980735a4e..2f46192d54 100644--- a/jarvis/audio/player.py+++ b/jarvis/audio/player.py@@ -46,7 +46,7 @@ TTS_WRITE_BUFFER_MS = 120_BLOCKED_OUTPUT_SUBSTRINGS = ("NVIDIA High Definition", # NVIDIA GPU audio (monitor via HDMI/DP)"AMD HD Audio", # AMD GPU audio- "Primärer Soundtreiber", # Windows primary hook, ambiguous+ "Primärer Soundtreiber", # i18n-allow: Windows primary hook, ambiguous — matched against a localized (German) Windows device name"Microsoft Soundmapper","SPDIF", # digital-out with no target on unknown setups)@@ -179,7 +179,7 @@ def _resolve_output_device(device: int | str | None) -> int | str | None:devices = sd.query_devices()hostapis = sd.query_hostapis()except Exception as exc: # noqa: BLE001- log.warning("Device-Query fehlgeschlagen, nutze System-Default: %s", exc)+ log.warning("Device query failed, using system default: %s", exc)return None# Candidates: real output devices that are not on the blocklist.@@ -201,15 +201,15 @@ def _resolve_output_device(device: int | str | None) -> int | str | None:)raw_candidates.append((idx, d, hostapi_name))- # WDM-KS crasht beim OutputStream-Open (-9999 'Blocking API not supported- # yet'). Solange IRGENDEIN sicheres Output-Device existiert, waehlen wir NIE- # ein WDM-KS-Device. Wichtig — und der Bugfix gegenueber der alten Same-Name-- # Logik: auch dann nicht, wenn ein Geraetename NUR auf WDM-KS existiert- # (z.B. "Speakers (Realtek HD Audio output)" hat keinen MME/WASAPI-Zwilling).- # Der frueher genutzte Same-Name-Filter liess genau solche WDM-KS-only-- # Devices durch; sie gewannen per Name-Rang und crashten beim Playback- # (BUG-014 Wiederholung 2026-05-24: Brain+TTS ok, User hoert nichts).- # Nur wenn ALLE Kandidaten WDM-KS sind, nehmen wir als letztes Mittel eins.+ # WDM-KS crashes on OutputStream open (-9999 'Blocking API not supported+ # yet'). As long as ANY safe output device exists, we NEVER choose a+ # WDM-KS device. Important — and the bugfix versus the old same-name+ # logic: not even when a device name exists ONLY on WDM-KS (e.g.+ # "Speakers (Realtek HD Audio output)" has no MME/WASAPI twin).+ # The previously used same-name filter let exactly such WDM-KS-only+ # devices through; they won on name rank and crashed on playback+ # (BUG-014 recurrence 2026-05-24: Brain+TTS ok, user hears nothing).+ # Only when ALL candidates are WDM-KS do we take one as a last resort.safe_exists = any(ha not in _FORBIDDEN_OUTPUT_HOSTAPIS for _, _, ha in raw_candidates)@@ -249,7 +249,7 @@ def _resolve_output_device(device: int | str | None) -> int | str | None:)return idx- log.warning("auto-headset fand kein passendes Device — System-Default.")+ log.warning("auto-headset found no matching device — using system default.")return None@@ -397,11 +397,11 @@ class AudioPlayer:else:dev_info = sd.query_devices(self._device)log.info(- "AudioPlayer nutzt Device: %s (idx=%s)",+ "AudioPlayer using device: %s (idx=%s)",dev_info.get("name"), self._device,)except Exception as exc: # noqa: BLE001- log.warning("AudioPlayer Device-Abfrage fehlgeschlagen: %s", exc)+ log.warning("AudioPlayer device query failed: %s", exc)async def play_pcm(self, pcm: bytes, sample_rate: int | None = None) -> None:"""Play a complete PCM byte blob — single-shot (ACK chimes, alerts).@@ -500,13 +500,13 @@ class AudioPlayer:if "-9997" not in str(exc) and "Invalid sample rate" not in str(exc):raiselog.warning(- "OutputStream @ %dHz failed (%s) — naechste Rate …",+ "OutputStream @ %dHz failed (%s) — trying next rate …",target_rate, exc,)if last_exc is not None:raise last_exc- raise RuntimeError("Keine unterstuetzte Samplerate gefunden")+ raise RuntimeError("No supported sample rate found")def _write_samples(self,diff --git a/jarvis/awareness/__init__.py b/jarvis/awareness/__init__.pyindex cd7a161f57..3fd2af9c67 100644--- a/jarvis/awareness/__init__.py+++ b/jarvis/awareness/__init__.py@@ -1,13 +1,13 @@-"""Awareness Layer (Phase A0+) — Continuous Context fuer Hauptjarvis.+"""Awareness Layer (Phase A0+) — continuous context for the main Jarvis.-Vier-Schichten-Architektur (Plan §1):- L1 Live Frame — RAM, Sekunden (Phase A1)- L2 Story — RAM-Ringbuffer + SQLite (Phase A2)- L3 Session — FTS5-Search ueber Episoden (Phase A3)+Four-layer architecture (Plan §1):+ L1 Live Frame — RAM, seconds (Phase A1)+ L2 Story — RAM ring buffer + SQLite (Phase A2)+ L3 Session — FTS5 search over episodes (Phase A3)L4 Long-Term — Curator -> MEMORY.md (existing)-A0-Scope: Datenmodelle + Privacy-Filter + Config-Schema. Keine Watchers,-keine Captures, keine Bus-Subscriptions — die kommen in A1.+A0 scope: data models + privacy filter + config schema. No watchers,+no captures, no bus subscriptions — those come in A1."""from __future__ import annotationsdiff --git a/jarvis/awareness/probes/filesystem.py b/jarvis/awareness/probes/filesystem.pyindex 35dc616771..dd89caeb6d 100644--- a/jarvis/awareness/probes/filesystem.py+++ b/jarvis/awareness/probes/filesystem.py@@ -123,7 +123,7 @@ class FileSystemProbe:try:from watchdog.observers import Observer # noqa: PLC0415except ImportError:- logger.warning("watchdog nicht installiert — FileSystemProbe ist no-op")+ logger.warning("watchdog not installed — FileSystemProbe is a no-op")self._started = Truereturnself._loop = asyncio.get_running_loop()diff --git a/jarvis/awareness/probes/git.py b/jarvis/awareness/probes/git.pyindex fd92af88c4..3ed27a3edd 100644--- a/jarvis/awareness/probes/git.py+++ b/jarvis/awareness/probes/git.py@@ -37,7 +37,7 @@ class GitProbe:if cwd is None:return {"git_branch": None}- # Strategy 1: .git/HEAD direct-read (fast, kein Subprocess)+ # Strategy 1: .git/HEAD direct-read (fast, no subprocess)try:branch = await asyncio.wait_for(asyncio.to_thread(self._read_head_file, cwd),@@ -79,7 +79,7 @@ class GitProbe:if not git_dir_or_file.exists():return None- # Worktree-Repo: .git ist file mit "gitdir: ..."+ # Worktree repo: .git is a file containing "gitdir: ..."if git_dir_or_file.is_file():content = git_dir_or_file.read_text(encoding="utf-8").strip()if content.startswith("gitdir:"):diff --git a/jarvis/awareness/prompts.py b/jarvis/awareness/prompts.pyindex bff03ce3ac..594f82979e 100644--- a/jarvis/awareness/prompts.py+++ b/jarvis/awareness/prompts.py@@ -42,7 +42,7 @@ Regeln:"""-_HEADER = "# Frames + Events der letzten Minuten:"+_HEADER = "# Frames + Events der letzten Minuten:" # i18n-allow: header of the German-language Verdichter LLM input block (VERDICHTER_SYSTEM_PROMPT expects German)_TRUNC_MARKER = "[...]"@@ -163,11 +163,11 @@ def build_verdichter_prompt(lines.sort(key=lambda x: x[0])body_lines = [line for _, line in lines]- footer = f"Dominante App: {primary_app}"+ footer = f"Dominante App: {primary_app}" # i18n-allow: label of the German-language Verdichter LLM input block (VERDICHTER_SYSTEM_PROMPT expects German)# Build full block, then truncate from front (keep newest tail)body = "\n".join(body_lines)- block = f"{_HEADER}\n{body}\n\n{footer}" if body else f"{_HEADER}\n(keine Daten)\n\n{footer}"+ block = f"{_HEADER}\n{body}\n\n{footer}" if body else f"{_HEADER}\n(keine Daten)\n\n{footer}" # i18n-allow: same German-language Verdichter input blockif len(block) <= max_chars:return blockdiff --git a/jarvis/awareness/watchers/window.py b/jarvis/awareness/watchers/window.pyindex a9cfc43abc..d2d899e491 100644--- a/jarvis/awareness/watchers/window.py+++ b/jarvis/awareness/watchers/window.py@@ -218,7 +218,7 @@ class WindowFocusWatcher:passself._stop_event_handle = None- # P6: Queue-Reste werden GC'd. Drops-Counter loggen.+ # P6: leftover queue items get GC'd. Log the drops counter.if self._drops > 0:logger.info("WindowFocusWatcher: %d frames dropped (pump=%d, async=%d)",@@ -270,7 +270,7 @@ class WindowFocusWatcher:def _proc(hook, event, hwnd, idObject, idChild, idThread, dwmsEventTime):# Hard-Negative HN4: NO logging, NO await, NO PrivacyFilter# in this callback. Enqueue only.- # Wir filtern auf das eigentliche Window (idObject==OBJID_WINDOW (0)).+ # We filter on the actual window (idObject==OBJID_WINDOW (0)).if idObject != 0 or idChild != 0:returnif not hwnd:diff --git a/jarvis/board/achievements.py b/jarvis/board/achievements.pyindex 263168a570..e08ba9cd6c 100644--- a/jarvis/board/achievements.py+++ b/jarvis/board/achievements.py@@ -182,77 +182,77 @@ def _eval_one_year(event: Event, ctx: AchievementContext) -> UnlockDecision | No# -----------------------------------------------------------------------# Katalog+# Catalog# ----------------------------------------------------------------------ACHIEVEMENTS: list[AchievementSpec] = [AchievementSpec(id="first_mcp",- title="Erste MCP-Verbindung",- description="Ein MCP-Tool lief erfolgreich.",+ title="First MCP Connection",+ description="An MCP tool ran successfully.",tier="mastery",evaluator=_eval_first_mcp,),AchievementSpec(id="openclaw_summoner",title="Jarvis-Agent Summoner",- description="Erster erfolgreicher Jarvis-Agent-Spawn.",+ description="First successful Jarvis-Agent spawn.",tier="mastery",evaluator=_eval_openclaw_summoner,),AchievementSpec(id="tool_dabbler",- title="Tool-Dabbler",- description="5 verschiedene Tools erfolgreich benutzt.",+ title="Tool Dabbler",+ description="Used 5 different tools successfully.",tier="mastery",evaluator=_make_tool_count_eval(5),),AchievementSpec(id="tool_journeyman",- title="Tool-Journeyman",- description="15 verschiedene Tools erfolgreich benutzt.",+ title="Tool Journeyman",+ description="Used 15 different tools successfully.",tier="mastery",evaluator=_make_tool_count_eval(15),),AchievementSpec(id="tool_master",- title="Tool-Master",- description="30 verschiedene Tools erfolgreich benutzt.",+ title="Tool Master",+ description="Used 30 different tools successfully.",tier="mastery",evaluator=_make_tool_count_eval(30),),AchievementSpec(id="triple_combo",title="Triple Combo",- description="Drei verschiedene Tools in derselben Session chained.",+ description="Three different tools chained in the same session.",tier="mastery",evaluator=_eval_triple_combo,),AchievementSpec(id="ten_x_engineer",title="10x Engineer",- description="Ueber 10 Jarvis-Agent-Stunden in den letzten 7 Tagen.",+ description="Over 10 Jarvis-Agent hours in the last 7 days.",tier="mastery",evaluator=_eval_ten_x_engineer,),AchievementSpec(id="centennial",title="Centennial",- description="100 erfolgreiche Tasks.",+ description="100 successful tasks.",tier="reflection",evaluator=_make_task_count_eval(100),),AchievementSpec(id="kilo_club",title="Kilo Club",- description="1000 erfolgreiche Tasks.",+ description="1000 successful tasks.",tier="reflection",evaluator=_make_task_count_eval(1000),),AchievementSpec(id="one_year_with_jarvis",- title="Ein Jahr mit Jarvis",- description="365 Tage seit der ersten Aktivitaet.",+ title="One Year with Jarvis",+ description="365 days since first activity.",tier="reflection",evaluator=_eval_one_year,),diff --git a/jarvis/board/evaluator.py b/jarvis/board/evaluator.pyindex 4ce3229663..d3eb4d013e 100644--- a/jarvis/board/evaluator.py+++ b/jarvis/board/evaluator.py@@ -337,7 +337,7 @@ class AchievementEvaluator:except Exception: # noqa: BLE001log.exception("Publish AchievementUnlocked failed")- # --------------- Read-only Queries (fuer die API) ---------------+ # --------------- Read-only queries (for the API) ---------------def list_all(self) -> list[dict[str, Any]]:"""All specs (locked and unlocked) with metadata for the API.diff --git a/jarvis/board/profile.py b/jarvis/board/profile.pyindex 8e1743dae5..cd96dbc571 100644--- a/jarvis/board/profile.py+++ b/jarvis/board/profile.py@@ -145,10 +145,10 @@ class BioStore:so the API layer receives a clean ValueError instead of asqlite3.IntegrityError."""- if kind not in {"trifft", "trifft_nicht", "haerter"}:+ if kind not in {"trifft", "trifft_nicht", "haerter"}: # i18n-allow: API/DB contract values (see frontend useBoard.ts), matched in logicraise ValueError(- f"Ungueltiges Feedback-Kind: {kind!r} "- "(erlaubt: trifft, trifft_nicht, haerter)"+ f"Invalid feedback kind: {kind!r} "+ "(allowed: trifft, trifft_nicht, haerter)" # i18n-allow: same API/DB contract values)now_iso = datetime.now(timezone.utc).astimezone().isoformat()conn = self._connect()@@ -179,7 +179,7 @@ class BioStore:).fetchall()finally:conn.close()- result = {"trifft": 0, "trifft_nicht": 0, "haerter": 0}+ result = {"trifft": 0, "trifft_nicht": 0, "haerter": 0} # i18n-allow: API/DB contract values, matched in logicfor row in rows:kind = row["kind"]if kind in result:@@ -255,7 +255,7 @@ class BioGenerator:should stay visible (brain gone, timeout, empty output)."""if self._resolver is None:- log.info("BioGenerator: kein brain_resolver konfiguriert — skip")+ log.info("BioGenerator: no brain_resolver configured — skip")return None# Call the resolver here — provider switches at runtime take effect this way.@@ -263,7 +263,7 @@ class BioGenerator:brain = self._resolver()except Exception: # noqa: BLE001log.exception(- "BioGenerator: brain_resolver fehlgeschlagen — alte Bio bleibt"+ "BioGenerator: brain_resolver failed — keeping old bio")return None@@ -288,15 +288,15 @@ class BioGenerator:)except TimeoutError:duration_ms = (time.time_ns() - start_ns) // 1_000_000- log.warning("BioGenerator: timeout nach %dms — alte Bio bleibt", duration_ms)+ log.warning("BioGenerator: timeout after %dms — keeping old bio", duration_ms)return Noneexcept Exception: # noqa: BLE001- log.exception("BioGenerator: Brain-Call fehlgeschlagen — alte Bio bleibt")+ log.exception("BioGenerator: brain call failed — keeping old bio")return Nonetext = _post_process(agg.text, max_words=120) # 5 sentences ≈ < 120 wordsif not text:- log.warning("BioGenerator: leerer Output — alte Bio bleibt")+ log.warning("BioGenerator: empty output — keeping old bio")return None# Resolver-provider hint for the frontend. We know the class name@@ -590,7 +590,7 @@ def make_resolver_from_brain(brain: Any) -> BrainResolverFn:use ``resolve_frontier_brain`` so that provider switches take effect."""if brain is None:- raise ValueError("make_resolver_from_brain: brain darf nicht None sein")+ raise ValueError("make_resolver_from_brain: brain must not be None")def _resolver() -> Any:return braindiff --git a/jarvis/brain/intent_router.py b/jarvis/brain/intent_router.pyindex 084b1f38f4..1db22684aa 100644--- a/jarvis/brain/intent_router.py+++ b/jarvis/brain/intent_router.py@@ -9,12 +9,12 @@ Orthogonal to the tier router from Phase 5 (`jarvis/brain/router.py`):Goal: no extra LLM-call latency for routing. Heuristic-based:- **FAST** (Haiku): simple actions, tool calls, smalltalk responses- Keywords: öffne, spawn, starte, klicke, tippe, sag, merk, zeig, such, etc.+ Keywords: öffne, spawn, starte, klicke, tippe, sag, merk, zeig, such, etc. # i18n-allowHeuristic: short (<80 chars), imperative, one clear verb + object- **DEEP** (Opus): reasoning, analysis, planning, explaining, comparing, coding- Keywords: recherchiere, analysiere, plane, erkläre, vergleich, schreib, baue,- debug, refactor, überlege, zusammenfass, etc.+ Keywords: recherchiere, analysiere, plane, erkläre, vergleich, schreib, baue, # i18n-allow+ debug, refactor, überlege, zusammenfass, etc. # i18n-allowHeuristic: long, many subclauses, multiple aspects, question word + depth- **CODE** (OpenClaw Heavy-Worker): explicit coding tasks@@ -34,15 +34,15 @@ IntentLevel = Literal["fast", "deep", "code"]# Simple actions / tool triggers (Haiku is sufficient)._FAST_PATTERNS = [# German — imperatives- r"\böffne\b", r"\bstart(e|et)?\b", r"\bstarte\b", r"\bspawn(e)?\b",+ r"\böffne\b", r"\bstart(e|et)?\b", r"\bstarte\b", r"\bspawn(e)?\b", # i18n-allowr"\bklick(e|t)?\b", r"\btipp(e|t)?\b", r"\btype\b",r"\bsag\b", r"\bsage\b", r"\bsprich\b",r"\bzeig(e|t)?\b", r"\bliste\b", r"\bdisplay\b",r"\bmach auf\b", r"\bmach zu\b", r"\bminimier\b", r"\bmaximier\b",r"\bmerk dir\b", r"\bspeicher\b",- r"\bkopiere\b", r"\bfüg(e)? ein\b",+ r"\bkopiere\b", r"\bfüg(e)? ein\b", # i18n-allowr"\bsuch\b", r"\bfinde\b",- r"\bwie spät\b", r"\bdatum\b",+ r"\bwie spät\b", r"\bdatum\b", # i18n-allowr"\bwelcher tag\b",# Englischr"\bopen\b", r"\bclose\b", r"\blaunch\b", r"\brun\b",@@ -58,10 +58,10 @@ _FAST_PATTERNS = [_DEEP_PATTERNS = [# German — `\w*` instead of `\b` at the end to catch conjugationsr"\brecherchier\w*", r"\banalysier\w*", r"\bplane\w*\b", r"\bplanung\b",- r"\berklär\w*", r"\bvergleich\w*", r"\bunterschied\w*",+ r"\berklär\w*", r"\bvergleich\w*", r"\bunterschied\w*", # i18n-allowr"\bschreib\w*", r"\bformulier\w*", r"\bverfass\w*",r"\bbau(e|t)?\b.*\bmir\b", r"\bentwickel\w*", r"\bentwerf\w*",- r"\büberleg\w*", r"\bdenk gründlich\b", r"\bnachdenk\w*",+ r"\büberleg\w*", r"\bdenk gründlich\b", r"\bnachdenk\w*", # i18n-allowr"\bzusammenfass\w*", r"\bfass\w*.*zusammen",r"\bwarum\b", r"\bwieso\b", r"\bweshalb\b",r"\boptimier\w*", r"\bverbesser\w*",@@ -77,7 +77,7 @@ _DEEP_PATTERNS = [# Coding tasks are routed to the OpenClaw heavy worker._CODE_PATTERNS = [- r"\bcode\b.*(für|for|write|schreib)",+ r"\bcode\b.*(für|for|write|schreib)", # i18n-allowr"\bimplementier\b", r"\bimplement\b",r"\bfix bug\b", r"\bfehler finden\b", r"\bdebug\b",r"\brefactor\b", r"\brefaktor\b",diff --git a/jarvis/brain/launcher.py b/jarvis/brain/launcher.pyindex 5596fe6efd..1620c1b520 100644--- a/jarvis/brain/launcher.py+++ b/jarvis/brain/launcher.py@@ -3,9 +3,9 @@python -m jarvis.brain.launcher --provider gemini --prompt "Hallo"python -m jarvis.brain.launcher --provider claude-api --prompt "Was ist 2+2?"python -m jarvis.brain.launcher --list-providers- python -m jarvis.brain.launcher --prompt "öffne Notepad" (with tools)+ python -m jarvis.brain.launcher --prompt "öffne Notepad" (with tools) # i18n-allowpython -m jarvis.brain.launcher --prompt "formatiere C:" (blacklist deny)- python -m jarvis.brain.launcher --prompt "merk dir: ich heiße Harald" --save-memory+ python -m jarvis.brain.launcher --prompt "merk dir: ich heiße Harald" --save-memory # i18n-allowThe launcher bypasses the voice pipeline entirely. It is the primaryverification CLI for Phase 2 and remains permanently useful as a debug tool.@@ -27,18 +27,18 @@ if sys.platform == "win32":def _build_argparser() -> argparse.ArgumentParser:p = argparse.ArgumentParser(prog="jarvis.brain.launcher",- description="Standalone-CLI für Brain-Layer-Tests",+ description="Standalone CLI for brain-layer tests",)p.add_argument("--prompt", type=str, help="User-Prompt an das Brain")- p.add_argument("--provider", type=str, help="Primary-Provider überschreiben")+ p.add_argument("--provider", type=str, help="Override the primary provider")p.add_argument("--list-providers", action="store_true",- help="Listet alle verfügbaren/geladenen Providers")+ help="Lists all available/loaded providers")p.add_argument("--snapshot", action="store_true",help="Gibt BrainManager.snapshot() aus")p.add_argument("--with-tools", action="store_true",help="Registriert alle 5 Phase-2-Tools im Dispatcher")p.add_argument("--no-memory", action="store_true",- help="Kein Core-Memory + Recall laden (für Minimal-Tests)")+ help="Skip loading Core-Memory + Recall (for minimal tests)")p.add_argument("--stream", action="store_true",help="Streamt Token-weise auf stdout statt final-print")return p@@ -53,7 +53,7 @@ async def _run(args: argparse.Namespace) -> int:if args.list_providers:from jarvis.brain.provider_registry import BrainProviderRegistryreg = BrainProviderRegistry()- print("Verfügbare Brain-Providers:")+ print("Available brain providers:")for name in reg.available():print(f" - {name}")failed = reg.failed()@@ -110,7 +110,7 @@ async def _run(args: argparse.Namespace) -> int:return 0if not args.prompt:- print("Kein --prompt angegeben. Benutze --help.", file=sys.stderr)+ print("No --prompt given. Use --help.", file=sys.stderr)return 2# Send prompt@@ -147,7 +147,7 @@ def _load_tools() -> dict:cls = ep.load()inst = cls()except Exception as exc: # noqa: BLE001- print(f"[warn] Tool '{ep.name}' nicht ladbar: {exc}", file=sys.stderr)+ print(f"[warn] Tool '{ep.name}' could not be loaded: {exc}", file=sys.stderr)continueif getattr(inst, "is_virtual_loader", False):try:@@ -167,7 +167,7 @@ def _load_tools() -> dict:inst = HotkeyTool()tools[inst.name] = instexcept Exception as exc: # noqa: BLE001- print(f"[warn] Fallback-Tool 'hotkey' nicht ladbar: {exc}", file=sys.stderr)+ print(f"[warn] Fallback tool 'hotkey' could not be loaded: {exc}", file=sys.stderr)if "click" not in tools:try:from jarvis.plugins.tool.click import ClickTool@@ -175,7 +175,7 @@ def _load_tools() -> dict:inst = ClickTool()tools[inst.name] = instexcept Exception as exc: # noqa: BLE001- print(f"[warn] Fallback-Tool 'click' nicht ladbar: {exc}", file=sys.stderr)+ print(f"[warn] Fallback tool 'click' could not be loaded: {exc}", file=sys.stderr)return toolsdiff --git a/jarvis/brain/mission_command_gate.py b/jarvis/brain/mission_command_gate.pyindex e7147c371b..2b1383243e 100644--- a/jarvis/brain/mission_command_gate.py+++ b/jarvis/brain/mission_command_gate.py@@ -1,18 +1,18 @@"""MissionCommandGate — pattern matcher for OpenClaw mission meta-commands.AD-12 + AP-OC5 (see ``docs/openclaw-bridge.md``): status phrases-("laeuft das noch?", "wie weit?", "Status?") and stop phrases ("brich ab",+("laeuft das noch?", "wie weit?", "Status?") and stop phrases ("brich ab", # i18n-allow"stop OpenClaw") MUST NOT lead to a new spawn — the router brain mustdetect them deterministically via regex, otherwise there is a risk of-(a) latency from LLM tool-choice and (b) hallucination ("ja klar laeuft-das noch" even though the mission is dead).+(a) latency from LLM tool-choice and (b) hallucination ("ja klar laeuft # i18n-allow+das noch" even though the mission is dead). # i18n-allowArchitecture:- Pure function ``match_mission_command(text)`` -> ``MissionCommandMatch | None``.- Bilingual DE+EN. Patterns are intentionally strict (word boundaries,start-of-sentence anchors for stop phrases) so smalltalk like- "Wie weit ist das Buch?" or "Lass das stoppen, das Lied" does not+ "Wie weit ist das Buch?" or "Lass das stoppen, das Lied" does not # i18n-allowmatch incorrectly.- Optional: extract mission ID if the user explicitly names a mission("status mission abc123" / "stop mission xyz"). Default is@@ -40,19 +40,19 @@ _INTENT_T = Literal["status", "cancel"]# --- Status phrases -----------------------------------------------------------#-# Match: "laeuft das noch?", "Laeuft die Mission noch?", "Status?",+# Match: "laeuft das noch?", "Laeuft die Mission noch?", "Status?", # i18n-allow# "Status der Mission", "wie weit?", "wie weit bist du?",# "is it still running?", "what's the status?", "how far are we?".## Two pattern groups so German and English phrases remain clearly separable —-# English with its own verb patterns, German with "laeufst/laeuft" + "Status"+# English with its own verb patterns, German with "laeufst/laeuft" + "Status" # i18n-allow# + "wie weit". Both typically end with "?" but that is optional (STT does# not reliably produce punctuation)._STATUS_PATTERN_DE = re.compile(r"""(- # 'laeuft (das|die mission|er|es) (noch|gerade|weiter)?'- \bl(?:ä|ae)uft\s+(?:das|die\s+mission|der|er|es)\s+(?:noch|gerade|weiter)\b+ # 'laeuft (das|die mission|er|es) (noch|gerade|weiter)?' # i18n-allow+ \bl(?:ä|ae)uft\s+(?:das|die\s+mission|der|er|es)\s+(?:noch|gerade|weiter)\b # i18n-allow|# bare 'wie weit' at sentence start or before '?'/end — asks about progress.# NOT 'wie weit ist Berlin' etc. (qualifier-free only matches when@@ -60,20 +60,20 @@ _STATUS_PATTERN_DE = re.compile(^\s*(?:jarvis[,\s]+)?wie\s+weit\s*\??\s*$|# 'wie weit' + person/mission qualifier- \bwie\s+weit\s+(?:bist\s+du|sind\s+wir|sind\s+sie|sind\s+die\s+mission|ist\s+(?:die\s+mission|der\s+sub|claw|openclaw))\b+ \bwie\s+weit\s+(?:bist\s+du|sind\s+wir|sind\s+sie|sind\s+die\s+mission|ist\s+(?:die\s+mission|der\s+sub|claw|openclaw))\b # i18n-allow|# 'status' alone (at start or after 'jarvis,'); MUST have question/end# character, otherwise it matches 'Status der Wirtschaft' incorrectly.^(?:jarvis[,\s]+)?status\s*[?.!]*\s*$|- # 'status der mission' / 'status vom sub' / 'status von openclaw'- \bstatus\s+(?:der\s+mission|vom\s+sub|von\s+(?:openclaw|claw)|bei\s+(?:openclaw|claw))\b+ # 'status der mission' / 'status vom sub' / 'status von openclaw' # i18n-allow+ \bstatus\s+(?:der\s+mission|vom\s+sub|von\s+(?:openclaw|claw)|bei\s+(?:openclaw|claw))\b # i18n-allow|- # 'wo stehen wir' / 'wo steht das' / 'wo steht die mission'- \bwo\s+steh(?:en|t)\s+(?:wir|das|die\s+mission|der\s+sub|claw|openclaw)\b+ # 'wo stehen wir' / 'wo steht das' / 'wo steht die mission' # i18n-allow+ \bwo\s+steh(?:en|t)\s+(?:wir|das|die\s+mission|der\s+sub|claw|openclaw)\b # i18n-allow|# 'noch am laufen' / 'noch dran'- \b(?:noch|immer)\s+(?:am\s+laufen|dran|aktiv|beschäftigt|beschaeftigt)\b+ \b(?:noch|immer)\s+(?:am\s+laufen|dran|aktiv|beschäftigt|beschaeftigt)\b # i18n-allow)""",re.IGNORECASE | re.VERBOSE,@@ -108,7 +108,7 @@ _STATUS_PATTERN_EN = re.compile(# --- Cancel phrases -----------------------------------------------------------## Match: "brich ab", "brich die Mission ab", "stop OpenClaw",-# "stoppe die Mission", "abbrechen", "cancel OpenClaw",+# "stoppe die Mission", "abbrechen", "cancel OpenClaw", # i18n-allow# "kill the mission".## Important: the existing ``voice_command_gate._CANCEL_PATTERN`` already@@ -120,20 +120,20 @@ _STATUS_PATTERN_EN = re.compile(_CANCEL_PATTERN_DE = re.compile(r"""(- # 'brich (das|die|den|alles) ab'- \bbrich\s+(?:das|die\s+mission|den\s+auftrag|alles|openclaw|claw|sub|den)\s*\w*\s*ab\b+ # 'brich (das|die|den|alles) ab' # i18n-allow+ \bbrich\s+(?:das|die\s+mission|den\s+auftrag|alles|openclaw|claw|sub|den)\s*\w*\s*ab\b # i18n-allow|# 'brich ab' — short form^(?:jarvis[,\s]+)?brich\s+ab\b|- # 'stop(pe) (die mission|openclaw|claw|den auftrag)'- \bstopp?(?:e)?\s+(?:die\s+mission|openclaw|claw|den\s+auftrag|den\s+sub|alles)\b+ # 'stop(pe) (die mission|openclaw|claw|den auftrag)' # i18n-allow+ \bstopp?(?:e)?\s+(?:die\s+mission|openclaw|claw|den\s+auftrag|den\s+sub|alles)\b # i18n-allow|- # 'mission abbrechen' / 'auftrag abbrechen'- \b(?:mission|auftrag|openclaw|claw)\s+(?:bitte\s+)?abbrechen\b+ # 'mission abbrechen' / 'auftrag abbrechen' # i18n-allow+ \b(?:mission|auftrag|openclaw|claw)\s+(?:bitte\s+)?abbrechen\b # i18n-allow|# 'abbruch der mission' / 'abbruch openclaw'- \babbruch\s+(?:der\s+mission|openclaw|claw|vom\s+sub)\b+ \babbruch\s+(?:der\s+mission|openclaw|claw|vom\s+sub)\b # i18n-allow)""",re.IGNORECASE | re.VERBOSE,@@ -208,7 +208,7 @@ def match_mission_command(text: str) -> MissionCommandMatch | None:On ambiguity (e.g. "wie weit cancel?" — rare), cancel wins.Examples (all return a match):- - "Laeuft das noch?" -> status / de+ - "Laeuft das noch?" -> status / de # i18n-allow- "Status?" -> status / de- "Wie weit bist du?" -> status / de- "Brich die Mission ab" -> cancel / de@@ -216,7 +216,7 @@ def match_mission_command(text: str) -> MissionCommandMatch | None:- "Cancel the mission" -> cancel / enExamples (no match):- - "Wie weit ist Berlin von hier?" (no mission context)+ - "Wie weit ist Berlin von hier?" (no mission context) # i18n-allow- "Status der Wirtschaft" (status without mission/claw)- "Lass das stoppen, das Lied" (no mission context)- ""diff --git a/jarvis/brain/mock.py b/jarvis/brain/mock.pyindex bf20fe4c8d..082d06fc7a 100644--- a/jarvis/brain/mock.py+++ b/jarvis/brain/mock.py@@ -21,8 +21,8 @@ if TYPE_CHECKING:_NO_BRAIN_REPLY_DE = (- "(Kein Brain-Provider an die Chat-UI angebunden. "- "Nutze die Voice-Pipeline oder hinterlege einen API-Key in den Einstellungen.)"+ "(Kein Brain-Provider an die Chat-UI angebunden. " # i18n-allow+ "Nutze die Voice-Pipeline oder hinterlege einen API-Key in den Einstellungen.)" # i18n-allow)diff --git a/jarvis/core/capabilities_seed.py b/jarvis/core/capabilities_seed.pyindex effd08b3b4..8c297412ea 100644--- a/jarvis/core/capabilities_seed.py+++ b/jarvis/core/capabilities_seed.py@@ -31,7 +31,7 @@ _ACTION_VERBS: tuple[str, ...] = ("implementier", "entwickel", "refactor", "debug",# DE — file / system actions"lies", "lese", "liest", "schreib", "schreibe", "schreibt",- "bau", "baue", "baut", "oeffne", "öffne", "oeffnet", "öffnet",+ "bau", "baue", "baut", "oeffne", "öffne", "oeffnet", "öffnet", # i18n-allow"installier", "deinstallier", "deploy","zeig", "zeige", "zeigt","mach", "mache", "macht", "machen",@@ -62,12 +62,12 @@ _SCREEN_OBJECTS: tuple[str, ...] = (_WIKI_OBJECTS: tuple[str, ...] = ("wiki", "notiz", "note", "wissen", "knowledge", "seite", "page",- "eintrag", "entry", "fact", "fakt",+ "eintrag", "entry", "fact", "fakt", # i18n-allow)_AWARENESS_OBJECTS: tuple[str, ...] = ("awareness", "status", "zustand", "zustaende", "state", "context",- "kontext", "erinnerung", "memory", "verlauf", "history", "episode",+ "kontext", "erinnerung", "memory", "verlauf", "history", "episode", # i18n-allow)@@ -128,10 +128,10 @@ _SEED_CAPABILITIES: list[Capability] = [Capability(id="tool.dispatch-with-review",source="router_tool",- verbs=_ACTION_VERBS + ("review", "check", "pruefe", "prüfe"),+ verbs=_ACTION_VERBS + ("review", "check", "pruefe", "prüfe"), # i18n-allowobjects=(- "review", "quality", "qualitaet", "qualität", "critic",- "kritik", "check", "pruefung", "prüfung",+ "review", "quality", "qualitaet", "qualität", "critic", # i18n-allow+ "kritik", "check", "pruefung", "prüfung", # i18n-allow),description="Dispatch a task through the Quality-Gate (Worker + Critic) pipeline.",risk_tier="ask",@@ -158,8 +158,8 @@ _SEED_CAPABILITIES: list[Capability] = [Capability(id="tool.run-skill",source="router_tool",- verbs=_ACTION_VERBS + ("skill", "faehigkeit", "fähigkeit"),- objects=("skill", "skills", "faehigkeit", "fähigkeit", "macro", "makro"),+ verbs=_ACTION_VERBS + ("skill", "faehigkeit", "fähigkeit"), # i18n-allow+ objects=("skill", "skills", "faehigkeit", "fähigkeit", "macro", "makro"), # i18n-allowdescription="Execute an installed user skill / macro.",risk_tier="monitor",requires_evidence=True,@@ -176,7 +176,7 @@ _SEED_CAPABILITIES: list[Capability] = [Capability(id="tool.wiki-page-read",source="router_tool",- verbs=_READ_VERBS + ("oeffne", "öffne", "open"),+ verbs=_READ_VERBS + ("oeffne", "öffne", "open"), # i18n-allowobjects=_WIKI_OBJECTS,description="Read a full wiki page by vault path (read-only).",risk_tier="safe",@@ -201,7 +201,7 @@ _SEED_CAPABILITIES: list[Capability] = [id="local.open_app",source="local_action",verbs=(- "oeffne", "öffne", "oeffnet", "öffnet", "starte", "start",+ "oeffne", "öffne", "oeffnet", "öffnet", "starte", "start", # i18n-allow"open", "launch", "mach", "mache", "macht",),objects=(@@ -221,7 +221,7 @@ _SEED_CAPABILITIES: list[Capability] = ["eingabe", "write",),objects=(- "text", "nachricht", "message", "eingabe", "input",+ "text", "nachricht", "message", "eingabe", "input", # i18n-allow"feld", "field", "zeile", "line",),description="Type text into the currently focused input field.",@@ -232,7 +232,7 @@ _SEED_CAPABILITIES: list[Capability] = [id="local.hotkey",source="local_action",verbs=(- "drueck", "drücke", "druecke", "press", "shortcut",+ "drueck", "drücke", "druecke", "press", "shortcut", # i18n-allow"tastenkombination", "hotkey", "strg", "ctrl",),objects=(@@ -247,12 +247,12 @@ _SEED_CAPABILITIES: list[Capability] = [id="local.reset_orb_position",source="local_action",verbs=(- "reset", "zurueck", "zurück", "bring", "bringe",+ "reset", "zurueck", "zurück", "bring", "bringe", # i18n-allow"orb", "overlay", "move", "verschiebbe",),objects=("orb", "overlay", "position", "fenster", "window",- "zurueck", "zurück",+ "zurueck", "zurück", # i18n-allow),description="Reset the Orb overlay to its default screen position.",risk_tier="safe",@@ -262,7 +262,7 @@ _SEED_CAPABILITIES: list[Capability] = [id="local.terminal_count",source="local_action",verbs=(- "oeffne", "öffne", "starte", "start", "spawne", "spawn",+ "oeffne", "öffne", "starte", "start", "spawne", "spawn", # i18n-allow"open", "launch", "neue", "new",),objects=(@@ -312,7 +312,7 @@ _SEED_CAPABILITIES: list[Capability] = [source="harness",verbs=_ACTION_VERBS + ("fuehre", "fuehr", "fuehren",- "run", "execute", "ausfuehren",+ "run", "execute", "ausfuehren", # i18n-allow),objects=("python", "script", "skript", "py", "datei", "file",diff --git a/jarvis/core/config_writer.py b/jarvis/core/config_writer.pyindex 787b9ff1fa..a36b8aa2d9 100644--- a/jarvis/core/config_writer.py+++ b/jarvis/core/config_writer.py@@ -61,7 +61,7 @@ _STT_PROVIDER_ENV = "JARVIS__STT__PROVIDER"# so a stale User-scope ENV var (e.g. one the wizard once wrote) OVERRIDES the# TOML at boot and silently masks any later UI/TOML edit — the "model is# hardcoded, I can't change it" trap (forensic 2026-06-28). The model/language-# setters therefore clear/sync this layer too, not just TOML + config-soll.+# setters therefore clear/sync this layer too, not just TOML + config-soll. # i18n-allow_STT_MODEL_ENV = "JARVIS__STT__MODEL"_STT_LANGUAGE_ENV = "JARVIS__STT__LANGUAGE"@@ -74,19 +74,19 @@ def set_brain_primary(name: str, *, path: Path = DEFAULT_CONFIG_FILE) -> None:them did not survive a restart: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)Raises ``FileNotFoundError`` if the TOML config file does not exist (abroken setup we do not silently mask). Layers 2 and 3 are best-effortcloud-first enhancements: they degrade to a graceful no-op on a headless- Linux VPS (no config-soll.json, no Windows registry) and never raise out+ Linux VPS (no config-soll.json, no Windows registry) and never raise out # i18n-allowof this function nor break the TOML write."""# Layer 1 — universal, runs on every platform. May raise FileNotFoundError._patch_table(path, "brain", "primary", name)# Layers 2 + 3 — best-effort, never raise.- _sync_brain_primary_drift_soll(name)+ _sync_brain_primary_drift_soll(name) # i18n-allowdef set_worker_provider(name: str, *, path: Path = DEFAULT_CONFIG_FILE) -> None:@@ -97,12 +97,12 @@ def set_worker_provider(name: str, *, path: Path = DEFAULT_CONFIG_FILE) -> None:and the write-side counterpart to the read-side resolution in``jarvis.missions.worker_runtime.provider_map.canonical_worker_provider`` /``jarvis.missions.init._worker_factory``. The worker provider is pinned- in ``config-soll.json`` (``brain.worker.provider``), so a switch that+ in ``config-soll.json`` (``brain.worker.provider``), so a switch that # i18n-allowwrote only the TOML would be reverted by the drift-guard within minutes —the same failure mode that hit ``brain.primary`` before it went 3-layer.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)Raises ``FileNotFoundError`` if the TOML config file does not exist. Layers@@ -119,7 +119,7 @@ def set_worker_provider(name: str, *, path: Path = DEFAULT_CONFIG_FILE) -> None:# Layer 1 — universal, runs on every platform. May raise FileNotFoundError._patch_worker_provider_toml(path, name)# Layers 2 + 3 — best-effort, never raise.- _sync_worker_provider_drift_soll(name)+ _sync_worker_provider_drift_soll(name) # i18n-allow# Back-compat alias — callers that imported set_sub_jarvis_provider still work.@@ -136,13 +136,13 @@ def set_worker_model(model: str, *, path: Path = DEFAULT_CONFIG_FILE) -> None:display. Empty string is the documented sentinel: the active workerprovider's ``deep_model`` (frontier) wins.- ``brain.worker.model`` is pinned in ``config-soll.json`` like the+ ``brain.worker.model`` is pinned in ``config-soll.json`` like the # i18n-allowprovider, so a TOML-only write would be reverted by the drift-guard withinminutes (BUG-010 class). Three layers, same shape as:func:`set_worker_provider`:1. ``jarvis.toml`` ``[brain.worker] model`` (TOML)- 2. ``scripts/config-soll.json`` ``brain.worker.model`` (drift-soll)+ 2. ``scripts/config-soll.json`` ``brain.worker.model`` (drift-soll) # i18n-allow3. ``JARVIS__BRAIN__WORKER__MODEL`` User-scope ENV var (boot override)Layers 2 + 3 are best-effort cloud-first enhancements: graceful no-op on a@@ -156,7 +156,7 @@ def set_worker_model(model: str, *, path: Path = DEFAULT_CONFIG_FILE) -> None:# Layer 1 — universal, runs on every platform. May raise FileNotFoundError._patch_worker_key_toml(path, "model", model)# Layers 2 + 3 — best-effort, never raise.- _sync_worker_model_drift_soll(model)+ _sync_worker_model_drift_soll(model) # i18n-allow# Back-compat alias — callers that imported set_sub_jarvis_model still work.@@ -174,10 +174,10 @@ def set_tts_provider(name: str, *, path: Path = DEFAULT_CONFIG_FILE) -> None:user overrides win.Three-layer persist (like ``set_brain_primary``): ``tts.provider`` (and the- voice keys) are pinned in ``config-soll.json``, so a TOML-only write would be+ voice keys) are pinned in ``config-soll.json``, so a TOML-only write would be # i18n-allowreverted by the drift-guard within 5 minutes — the same bug class that hit- ``brain.primary``. We therefore sync config-soll.json + ENV too. Crucially,- config-soll receives EXACTLY the keys the TOML write touched (provider + the+ ``brain.primary``. We therefore sync config-soll.json + ENV too. Crucially, # i18n-allow+ config-soll receives EXACTLY the keys the TOML write touched (provider + the # i18n-allowvoice/language/model it set or preserved) so the guard sees zero drift acrossthe whole block.@@ -188,7 +188,7 @@ def set_tts_provider(name: str, *, path: Path = DEFAULT_CONFIG_FILE) -> None:defaults = _TTS_DEFAULTS.get(name.lower(), {})applied = _patch_tts_block(path, name, defaults)# Layers 2 + 3 — best-effort, never raise.- _sync_tts_provider_drift_soll(applied)+ _sync_tts_provider_drift_soll(applied) # i18n-allowdef set_stt_provider(name: str, *, path: Path = DEFAULT_CONFIG_FILE) -> None:@@ -197,15 +197,15 @@ def set_stt_provider(name: str, *, path: Path = DEFAULT_CONFIG_FILE) -> None:Takes effect on the next SpeechPipeline bootstrap (a voice restart): the STTprovider is instantiated once at pipeline start.- ``stt.provider`` is pinned in ``config-soll.json``, so — like Brain/TTS — the- switch needs the 3-layer persist (TOML + config-soll + ENV), otherwise the+ ``stt.provider`` is pinned in ``config-soll.json``, so — like Brain/TTS — the # i18n-allow+ switch needs the 3-layer persist (TOML + config-soll + ENV), otherwise the # i18n-allowdrift-guard reverts it within 5 minutes. Layers 2 + 3 are best-effort(cloud-first) and never break the TOML write."""# Layer 1 — universal, runs on every platform. May raise FileNotFoundError._patch_table(path, "stt", "provider", name)# Layers 2 + 3 — best-effort, never raise.- _sync_stt_provider_drift_soll(name)+ _sync_stt_provider_drift_soll(name) # i18n-allowdef set_tts_voice(voice: str, *, path: Path = DEFAULT_CONFIG_FILE) -> None:@@ -214,27 +214,27 @@ def set_tts_voice(voice: str, *, path: Path = DEFAULT_CONFIG_FILE) -> None:The TTS config is a single ``[tts]`` block, so this is the voice of theACTIVE TTS provider. Most generative voices are multilingual (Gemini Charon,Grok leo …), so both language slots get the same value. ``voice_de`` /- ``voice_en`` are pinned in ``config-soll.json`` (like ``tts.provider``), so a- TOML-only write would be reverted by the drift-guard — we sync config-soll too.+ ``voice_en`` are pinned in ``config-soll.json`` (like ``tts.provider``), so a # i18n-allow+ TOML-only write would be reverted by the drift-guard — we sync config-soll too. # i18n-allow"""_patch_table(path, "tts", "voice_de", voice)_patch_table(path, "tts", "voice_en", voice)try:- _update_config_soll_section("tts", {"voice_de": voice, "voice_en": voice})+ _update_config_soll_section("tts", {"voice_de": voice, "voice_en": voice}) # i18n-allowexcept Exception as exc: # noqa: BLE001 — best-effort, must not propagate- log.warning("Could not sync tts voice to config-soll.json: %s", exc)+ log.warning("Could not sync tts voice to config-soll.json: %s", exc) # i18n-allowdef set_tts_model(model: str, *, path: Path = DEFAULT_CONFIG_FILE) -> None:"""Set the global TTS model (``[tts] model``) — e.g. Cartesia ``sonic-3.5``.- Synced to config-soll (drift-guard pinned, same class as the voice keys).+ Synced to config-soll (drift-guard pinned, same class as the voice keys). # i18n-allow"""_patch_table(path, "tts", "model", model)try:- _update_config_soll_section("tts", {"model": model})+ _update_config_soll_section("tts", {"model": model}) # i18n-allowexcept Exception as exc: # noqa: BLE001 — best-effort, must not propagate- log.warning("Could not sync tts.model to config-soll.json: %s", exc)+ log.warning("Could not sync tts.model to config-soll.json: %s", exc) # i18n-allowdef set_stt_model(model: str, *, path: Path = DEFAULT_CONFIG_FILE) -> None:@@ -243,18 +243,18 @@ def set_stt_model(model: str, *, path: Path = DEFAULT_CONFIG_FILE) -> None:Takes effect on the next SpeechPipeline bootstrap (a voice restart): the STTprovider is instantiated once at pipeline start.- ``stt.model`` is pinned in ``config-soll.json`` AND the single-word+ ``stt.model`` is pinned in ``config-soll.json`` AND the single-word # i18n-allow``JARVIS__STT__MODEL`` ENV var overrides the TOML at boot, so — exactly like- ``stt.provider`` — the switch needs the 3-layer persist (TOML + config-soll ++ ``stt.provider`` — the switch needs the 3-layer persist (TOML + config-soll + # i18n-allowENV); otherwise a stale ENV var (the "model is hardcoded" trap, forensic2026-06-28) or the drift-guard silently reverts it. Layers 2 + 3 arebest-effort (cloud-first) and never break the TOML write."""_patch_table(path, "stt", "model", model)try:- _update_config_soll_section("stt", {"model": model})+ _update_config_soll_section("stt", {"model": model}) # i18n-allowexcept Exception as exc: # noqa: BLE001 — best-effort, must not propagate- log.warning("Could not sync stt.model to config-soll.json: %s", exc)+ log.warning("Could not sync stt.model to config-soll.json: %s", exc) # i18n-allowtry:_set_user_env_var(_STT_MODEL_ENV, model)except Exception as exc: # noqa: BLE001 — best-effort, must not propagate@@ -268,16 +268,16 @@ def set_stt_language(language: str, *, path: Path = DEFAULT_CONFIG_FILE) -> Nonelets Whisper detect the spoken language per utterance (the bilingual default);a concrete code forces that language. Takes effect on the next SpeechPipelinebootstrap (a voice restart): the STT provider is instantiated once at pipeline- start. Persisted across all THREE layers (TOML + config-soll + ENV): the stt+ start. Persisted across all THREE layers (TOML + config-soll + ENV): the stt # i18n-allowblock is drift-guard pinned, and the single-word ``JARVIS__STT__LANGUAGE`` ENVvar would otherwise override the TOML at boot, so a 2-layer write could besilently masked (same trap as stt.model — forensic 2026-06-28)."""_patch_table(path, "stt", "language", language)try:- _update_config_soll_section("stt", {"language": language})+ _update_config_soll_section("stt", {"language": language}) # i18n-allowexcept Exception as exc: # noqa: BLE001 — best-effort, must not propagate- log.warning("Could not sync stt.language to config-soll.json: %s", exc)+ log.warning("Could not sync stt.language to config-soll.json: %s", exc) # i18n-allowtry:_set_user_env_var(_STT_LANGUAGE_ENV, language)except Exception as exc: # noqa: BLE001 — best-effort, must not propagate@@ -289,7 +289,7 @@ def set_tts_cartesia_model(model: str, *, path: Path = DEFAULT_CONFIG_FILE) -> NCartesia reads its model from this sub-table (default ``sonic-3.5``), NOT theglobal ``[tts] model`` that Gemini/OpenAI use. ``[tts.cartesia]`` is not pinned- in config-soll, so a plain atomic TOML write suffices (no drift-guard revert).+ in config-soll, so a plain atomic TOML write suffices (no drift-guard revert). # i18n-allow"""path = _ensure_writable_config_path(path)with _WRITE_LOCK:@@ -399,17 +399,17 @@ def set_wake_word(Toml-only by design — and that is a deliberate decision, NOT an oversight ofthe "user-switchable settings are written to all three layers" rule:- * The drift-guard only reverts keys it tracks in ``config-soll.json``, and+ * The drift-guard only reverts keys it tracks in ``config-soll.json``, and # i18n-allow``trigger.wake_word`` is intentionally NOT tracked there — so a plainatomic toml write is never reverted. The three-layer rule exists to stop- the guard from rolling a UI switch back (BUG-010); with no soll entry+ the guard from rolling a UI switch back (BUG-010); with no soll entry # i18n-allowthere is nothing to roll back.- * Adding a nested ``wake_word`` object to ``config-soll.json`` would make+ * Adding a nested ``wake_word`` object to ``config-soll.json`` would make # i18n-allowthe guard's scalar-only loops synthesise a garbage``JARVIS__TRIGGER__WAKE_WORD`` user env var from a stringified dict(BUG-018 class). And a stale ``JARVIS__*`` override would silently winover a hand-edit of jarvis.toml — directly contradicting the- "edit `phrase` here" guidance in the file. So neither the soll nor the+ "edit `phrase` here" guidance in the file. So neither the soll nor the # i18n-allowENV layer is written for the wake word.Takes effect on the next voice-pipeline bootstrap (a Jarvis restart): the@@ -435,7 +435,7 @@ def set_autostart(enabled: bool, *, path: Path = DEFAULT_CONFIG_FILE) -> None:"""Persist the login-autostart toggle to ``[autostart] enabled`` in jarvis.toml.Toml-only by design: ``autostart.enabled`` is NOT tracked in- ``config-soll.json`` (verified absent), so the drift-guard never reverts it —+ ``config-soll.json`` (verified absent), so the drift-guard never reverts it — # i18n-allowa plain atomic write suffices and the 3-layer rule (which exists only to stopthe guard from rolling a UI switch back, BUG-010) does not apply.@@ -577,7 +577,7 @@ def set_telegram_enabled(enabled: bool, *, path: Path = DEFAULT_CONFIG_FILE) ->``[integrations.telegram]`` is a NESTED table, so ``_patch_table`` (singlelevel) does not fit — we walk/create the two levels here. Toml-only bydesign: ``integrations.telegram.enabled`` is not tracked in- ``config-soll.json``, so the drift-guard never reverts it.+ ``config-soll.json``, so the drift-guard never reverts it. # i18n-allow"""path = _ensure_writable_config_path(path)@@ -686,7 +686,7 @@ def _set_integration_value(Walks/creates the two-level nested table (``_patch_table`` only handles asingle level). Comment- and BOM-preserving, lock-guarded, atomic — samecontract as :func:`set_telegram_enabled`. Toml-only by design: these- operational integration flags are not tracked in ``config-soll.json``, so+ operational integration flags are not tracked in ``config-soll.json``, so # i18n-allowthe drift-guard never reverts them."""path = _ensure_writable_config_path(path)@@ -837,7 +837,7 @@ _TTS_DEFAULTS: dict[str, dict[str, str]] = {# NOT from [tts].voice_de/voice_en (jarvis/plugins/tts/__init__.py lines# 103-116: ct = tts_cfg.model_extra["cartesia"]). The scalar [tts].voice_de# and voice_en keys are never consumed by the Cartesia factory path; setting- # them to "Charon" keeps them consistent with config-soll.json's tts block+ # them to "Charon" keeps them consistent with config-soll.json's tts block # i18n-allow# (which holds "Charon" as a carry-over from the Gemini era) so the# drift-guard sees zero drift.# model="" because [tts].model is not read by CartesiaTTS at all@@ -893,7 +893,7 @@ _VOICES_FOR_PROVIDER: dict[str, frozenset[str]] = {}),"grok-voice": frozenset({"leo", "rex", "sal", "ara", "eve"}),- # ElevenLabs nutzt Voice-IDs (kryptische Hashes) — keine Whitelist.+ # ElevenLabs uses voice IDs (cryptic hashes) — no whitelist.}@@ -908,7 +908,7 @@ def _patch_tts_block(path: Path, provider: str, defaults: dict[str, str]) -> dicReturns the dict of keys it ACTUALLY wrote to ``[tts]`` (always``provider``; plus whichever of voice/language/model it set). The- config-soll drift-sync mirrors exactly these keys so the guard sees zero+ config-soll drift-sync mirrors exactly these keys so the guard sees zero # i18n-allowdrift across the whole block."""path = _ensure_writable_config_path(path)@@ -936,7 +936,7 @@ def _patch_tts_block(path: Path, provider: str, defaults: dict[str, str]) -> dicapplied[key] = default_valueelif current is not None:# Voice is already valid for this provider — keep the user's- # value, but still record it so the config-soll drift-sync+ # value, but still record it so the config-soll drift-sync # i18n-allow# agrees with the TOML (else the guard reverts it).applied[key] = str(current)continue@@ -986,9 +986,9 @@ def set_brain_provider_model(Three-layer persist (like ``set_brain_primary`` / ``set_sub_jarvis_provider``):``brain.providers.<p>.model`` / ``deep_model`` are pinned in- ``config-soll.json``, so a TOML-only write would be reverted by the+ ``config-soll.json``, so a TOML-only write would be reverted by the # i18n-allowdrift-guard within 5 minutes (BUG-010 class) — exactly the "I picked a model- and it flipped back" symptom. We therefore sync config-soll.json too. No ENV+ and it flipped back" symptom. We therefore sync config-soll.json too. No ENV # i18n-allowlayer is written: per-provider model keys have no effective ``JARVIS__*``override (the boot override only nests on ``__`` and the drift-guard's dotted``JARVIS__BRAIN.PROVIDERS.*`` vars are inert), so adding one would only create@@ -1038,10 +1038,10 @@ def set_brain_provider_model(out = _BOM + out_atomic_write(path, out)- # Layer 2 — best-effort drift-soll sync (never raises, never blocks the+ # Layer 2 — best-effort drift-soll sync (never raises, never blocks the # i18n-allow# TOML write). Only the keys actually written are synced so the guard sees# zero drift across the block.- _sync_brain_provider_model_drift_soll(+ _sync_brain_provider_model_drift_soll( # i18n-allowprovider, model=model, deep_model=deep_model, cu_model=cu_model)@@ -1279,28 +1279,28 @@ def _atomic_write(path: Path, content: str) -> None:# -----------------------------------------------------------------------# Layer 2 + 3 — config-soll.json + ENV sync (best-effort, cloud-first safe)+# Layer 2 + 3 — config-soll.json + ENV sync (best-effort, cloud-first safe) # i18n-allow# -----------------------------------------------------------------------def _config_soll_path() -> Path:- """Locate ``scripts/config-soll.json`` relative to the repo root.+def _config_soll_path() -> Path: # i18n-allow+ """Locate ``scripts/config-soll.json`` relative to the repo root. # i18n-allowDerived from the same ``PROJECT_ROOT`` resolution that anchors``DEFAULT_CONFIG_FILE`` so the two paths stay consistent. On a headlessLinux VPS this file usually does not exist — callers must treat a missingfile as a graceful no-op."""- return PROJECT_ROOT / "scripts" / "config-soll.json"+ return PROJECT_ROOT / "scripts" / "config-soll.json" # i18n-allow-def _sync_brain_primary_drift_soll(name: str) -> None:- """Best-effort sync of ``brain.primary`` into the drift-soll + ENV layers.+def _sync_brain_primary_drift_soll(name: str) -> None: # i18n-allow+ """Best-effort sync of ``brain.primary`` into the drift-soll + ENV layers. # i18n-allowNEVER raises and NEVER breaks the (already-completed) TOML write. Twoindependent best-effort steps:- (a) Update ``scripts/config-soll.json`` ``brain.primary`` so the+ (a) Update ``scripts/config-soll.json`` ``brain.primary`` so the # i18n-allowdrift-guard daemon (5-min cron) does not revert the switch. Gracefulno-op when the file is absent (cloud-first / headless VPS).(b) Set the User-scope ``JARVIS__BRAIN__PRIMARY`` ENV var (Windows@@ -1309,11 +1309,11 @@ def _sync_brain_primary_drift_soll(name: str) -> None:live process and any child it spawns are immediately consistent.The registry write is gated behind ``sys.platform == "win32"``."""- # (a) config-soll.json — graceful no-op if the file does not exist.+ # (a) config-soll.json — graceful no-op if the file does not exist. # i18n-allowtry:- _update_config_soll_brain_primary(name)+ _update_config_soll_brain_primary(name) # i18n-allowexcept Exception as exc: # noqa: BLE001 — best-effort, must not propagate- log.warning("Could not sync brain.primary to config-soll.json: %s", exc)+ log.warning("Could not sync brain.primary to config-soll.json: %s", exc) # i18n-allow# (b) ENV var — winreg gated to win32, os.environ updated cross-platform.try:@@ -1322,19 +1322,19 @@ def _sync_brain_primary_drift_soll(name: str) -> None:log.warning("Could not sync %s to the User environment: %s", _BRAIN_PRIMARY_ENV, exc)-def _sync_worker_provider_drift_soll(name: str) -> None:- """Best-effort sync of ``brain.worker.provider`` into config-soll + ENV.+def _sync_worker_provider_drift_soll(name: str) -> None: # i18n-allow+ """Best-effort sync of ``brain.worker.provider`` into config-soll + ENV. # i18n-allowNEVER raises and NEVER breaks the (already-completed) TOML write. Same- two-step shape as :func:`_sync_brain_primary_drift_soll`.+ two-step shape as :func:`_sync_brain_primary_drift_soll`. # i18n-allow- Renamed from ``_sync_sub_jarvis_provider_drift_soll`` in the 2026-06-29+ Renamed from ``_sync_sub_jarvis_provider_drift_soll`` in the 2026-06-29 # i18n-allowJarvis-Agents rename."""try:- _update_config_soll_worker_provider(name)+ _update_config_soll_worker_provider(name) # i18n-allowexcept Exception as exc: # noqa: BLE001 — best-effort, must not propagate- log.warning("Could not sync worker provider to config-soll.json: %s", exc)+ log.warning("Could not sync worker provider to config-soll.json: %s", exc) # i18n-allowtry:_set_user_env_var(_WORKER_PROVIDER_ENV, name)@@ -1346,19 +1346,19 @@ def _sync_worker_provider_drift_soll(name: str) -> None:)-def _sync_worker_model_drift_soll(model: str) -> None:- """Best-effort sync of ``brain.worker.model`` into config-soll + ENV.+def _sync_worker_model_drift_soll(model: str) -> None: # i18n-allow+ """Best-effort sync of ``brain.worker.model`` into config-soll + ENV. # i18n-allowNEVER raises and NEVER breaks the (already-completed) TOML write. Same- two-step shape as :func:`_sync_worker_provider_drift_soll`.+ two-step shape as :func:`_sync_worker_provider_drift_soll`. # i18n-allow- Renamed from ``_sync_sub_jarvis_model_drift_soll`` in the 2026-06-29+ Renamed from ``_sync_sub_jarvis_model_drift_soll`` in the 2026-06-29 # i18n-allowJarvis-Agents rename."""try:- _update_config_soll_worker_key("model", model)+ _update_config_soll_worker_key("model", model) # i18n-allowexcept Exception as exc: # noqa: BLE001 — best-effort, must not propagate- log.warning("Could not sync worker model to config-soll.json: %s", exc)+ log.warning("Could not sync worker model to config-soll.json: %s", exc) # i18n-allowtry:_set_user_env_var(_WORKER_MODEL_ENV, model)@@ -1370,19 +1370,19 @@ def _sync_worker_model_drift_soll(model: str) -> None:)-def _sync_tts_provider_drift_soll(applied: dict[str, str]) -> None:- """Best-effort sync of the TTS block into the drift-soll + ENV layers.+def _sync_tts_provider_drift_soll(applied: dict[str, str]) -> None: # i18n-allow+ """Best-effort sync of the TTS block into the drift-soll + ENV layers. # i18n-allowNEVER raises and NEVER breaks the (already-completed) TOML write. ``applied``is the exact set of ``[tts]`` keys the TOML write touched (provider + any- provider-dependent voice/language/model), so config-soll ends up byte-for-byte+ provider-dependent voice/language/model), so config-soll ends up byte-for-byte # i18n-allowin agreement and the drift-guard reverts nothing. The ENV layer only pins theprovider (the single value a stale boot override could revert)."""try:- _update_config_soll_section("tts", applied)+ _update_config_soll_section("tts", applied) # i18n-allowexcept Exception as exc: # noqa: BLE001 — best-effort, must not propagate- log.warning("Could not sync tts.* to config-soll.json: %s", exc)+ log.warning("Could not sync tts.* to config-soll.json: %s", exc) # i18n-allowprovider_name = applied["provider"] # always present — set in _patch_tts_blocktry:@@ -1391,16 +1391,16 @@ def _sync_tts_provider_drift_soll(applied: dict[str, str]) -> None:log.warning("Could not sync %s to the User environment: %s", _TTS_PROVIDER_ENV, exc)-def _sync_stt_provider_drift_soll(name: str) -> None:- """Best-effort sync of ``stt.provider`` into the drift-soll + ENV layers.+def _sync_stt_provider_drift_soll(name: str) -> None: # i18n-allow+ """Best-effort sync of ``stt.provider`` into the drift-soll + ENV layers. # i18n-allowNEVER raises and NEVER breaks the (already-completed) TOML write. Same- two-step shape as :func:`_sync_brain_primary_drift_soll`.+ two-step shape as :func:`_sync_brain_primary_drift_soll`. # i18n-allow"""try:- _update_config_soll_section("stt", {"provider": name})+ _update_config_soll_section("stt", {"provider": name}) # i18n-allowexcept Exception as exc: # noqa: BLE001 — best-effort, must not propagate- log.warning("Could not sync stt.provider to config-soll.json: %s", exc)+ log.warning("Could not sync stt.provider to config-soll.json: %s", exc) # i18n-allowtry:_set_user_env_var(_STT_PROVIDER_ENV, name)@@ -1408,17 +1408,17 @@ def _sync_stt_provider_drift_soll(name: str) -> None:log.warning("Could not sync %s to the User environment: %s", _STT_PROVIDER_ENV, exc)-def _sync_brain_provider_model_drift_soll(+def _sync_brain_provider_model_drift_soll( # i18n-allowprovider: str, *, model: str | None, deep_model: str | None, cu_model: str | None = None) -> None:- """Best-effort sync of ``brain.providers.<p>`` model keys into the drift-soll.+ """Best-effort sync of ``brain.providers.<p>`` model keys into the drift-soll. # i18n-allowNEVER raises and NEVER breaks the (already-completed) TOML write. Only the- keys actually written (non-``None``) are synced, so config-soll ends up in+ keys actually written (non-``None``) are synced, so config-soll ends up in # i18n-allowagreement with the TOML and the drift-guard reverts nothing. No ENV layer:per-provider model keys have no effective ``JARVIS__*`` boot override (seethe docstring of :func:`set_brain_provider_model`). The flat dotted top-level- key ``brain.providers.<p>`` is exactly how the soll file stores it.+ key ``brain.providers.<p>`` is exactly how the soll file stores it. # i18n-allow"""values: dict[str, object] = {}if model is not None:@@ -1430,17 +1430,17 @@ def _sync_brain_provider_model_drift_soll(if not values:returntry:- _update_config_soll_section(f"brain.providers.{provider}", values)+ _update_config_soll_section(f"brain.providers.{provider}", values) # i18n-allowexcept Exception as exc: # noqa: BLE001 — best-effort, must not propagatelog.warning(- "Could not sync brain.providers.%s model to config-soll.json: %s",+ "Could not sync brain.providers.%s model to config-soll.json: %s", # i18n-allowprovider,exc,)-def _update_config_soll_section(top: str, values: dict[str, object]) -> None:- """Atomically merge ``values`` into ``data[top]`` in config-soll.json.+def _update_config_soll_section(top: str, values: dict[str, object]) -> None: # i18n-allow+ """Atomically merge ``values`` into ``data[top]`` in config-soll.json. # i18n-allowPreserves every other key (``_comment``, ``_updated``, other keys in thesame section, other top-level tables). Atomic tempfile + ``os.replace``,@@ -1451,13 +1451,13 @@ def _update_config_soll_section(top: str, values: dict[str, object]) -> None:itself and ``_WRITE_LOCK`` is a non-reentrant ``threading.Lock`` (it woulddeadlock). Today's callers acquire it only sequentially, never nested."""- soll_path = _config_soll_path()- if not soll_path.exists():- log.debug("config-soll.json absent (%s) — skipping drift-soll sync", soll_path)+ soll_path = _config_soll_path() # i18n-allow+ if not soll_path.exists(): # i18n-allow+ log.debug("config-soll.json absent (%s) — skipping drift-soll sync", soll_path) # i18n-allowreturnwith _WRITE_LOCK:- raw = soll_path.read_text(encoding="utf-8")+ raw = soll_path.read_text(encoding="utf-8") # i18n-allowdata = json.loads(raw)section = data.get(top)if not isinstance(section, dict):@@ -1468,23 +1468,23 @@ def _update_config_soll_section(top: str, values: dict[str, object]) -> None:section.update(values)out = json.dumps(data, indent=2, ensure_ascii=False) + "\n"- _atomic_write_text(soll_path, out)+ _atomic_write_text(soll_path, out) # i18n-allow-def _update_config_soll_brain_primary(name: str) -> None:- """Atomically set ``data["brain"]["primary"] = name`` in config-soll.json.+def _update_config_soll_brain_primary(name: str) -> None: # i18n-allow+ """Atomically set ``data["brain"]["primary"] = name`` in config-soll.json. # i18n-allowPreserves all other keys (``_comment``, ``_updated``, other ``brain.*``keys, other top-level tables). Atomic tempfile + ``os.replace``, UTF-8,``indent=2``. Graceful no-op when the file is absent."""- soll_path = _config_soll_path()- if not soll_path.exists():- log.debug("config-soll.json absent (%s) — skipping drift-soll sync", soll_path)+ soll_path = _config_soll_path() # i18n-allow+ if not soll_path.exists(): # i18n-allow+ log.debug("config-soll.json absent (%s) — skipping drift-soll sync", soll_path) # i18n-allowreturnwith _WRITE_LOCK:- raw = soll_path.read_text(encoding="utf-8")+ raw = soll_path.read_text(encoding="utf-8") # i18n-allowdata = json.loads(raw)brain = data.get("brain")if not isinstance(brain, dict):@@ -1495,28 +1495,28 @@ def _update_config_soll_brain_primary(name: str) -> None:brain["primary"] = nameout = json.dumps(data, indent=2, ensure_ascii=False) + "\n"- _atomic_write_text(soll_path, out)+ _atomic_write_text(soll_path, out) # i18n-allow-def _update_config_soll_worker_provider(name: str) -> None:+def _update_config_soll_worker_provider(name: str) -> None: # i18n-allow"""Atomically set ``data["brain.worker"]["provider"] = name`` in- config-soll.json.+ config-soll.json. # i18n-allowNote the FLAT dotted key ``"brain.worker"`` — that is how the drift-guard- soll file stores the sub-table (see scripts/config-soll.json), NOT a nested+ soll file stores the sub-table (see scripts/config-soll.json), NOT a nested # i18n-allow``data["brain"]["worker"]``. Preserves all other keys (``_comment``, thefallback chain, other tables). Graceful no-op when the file is absent.- Renamed from ``_update_config_soll_sub_jarvis_provider`` in the 2026-06-29+ Renamed from ``_update_config_soll_sub_jarvis_provider`` in the 2026-06-29 # i18n-allowJarvis-Agents rename; now writes to the ``"brain.worker"`` flat key."""- soll_path = _config_soll_path()- if not soll_path.exists():- log.debug("config-soll.json absent (%s) — skipping drift-soll sync", soll_path)+ soll_path = _config_soll_path() # i18n-allow+ if not soll_path.exists(): # i18n-allow+ log.debug("config-soll.json absent (%s) — skipping drift-soll sync", soll_path) # i18n-allowreturnwith _WRITE_LOCK:- raw = soll_path.read_text(encoding="utf-8")+ raw = soll_path.read_text(encoding="utf-8") # i18n-allowdata = json.loads(raw)block = data.get("brain.worker")if not isinstance(block, dict):@@ -1527,26 +1527,26 @@ def _update_config_soll_worker_provider(name: str) -> None:block["provider"] = nameout = json.dumps(data, indent=2, ensure_ascii=False) + "\n"- _atomic_write_text(soll_path, out)+ _atomic_write_text(soll_path, out) # i18n-allow-def _update_config_soll_worker_key(key: str, value: str) -> None:- """Atomically set ``data["brain.worker"][key] = value`` in config-soll.json.+def _update_config_soll_worker_key(key: str, value: str) -> None: # i18n-allow+ """Atomically set ``data["brain.worker"][key] = value`` in config-soll.json. # i18n-allow- Generalised sibling of :func:`_update_config_soll_worker_provider`+ Generalised sibling of :func:`_update_config_soll_worker_provider` # i18n-allow(same FLAT dotted-key layout, same preservation guarantees, same gracefulno-op when the file is absent).- Renamed from ``_update_config_soll_sub_jarvis_key`` in the 2026-06-29+ Renamed from ``_update_config_soll_sub_jarvis_key`` in the 2026-06-29 # i18n-allowJarvis-Agents rename."""- soll_path = _config_soll_path()- if not soll_path.exists():- log.debug("config-soll.json absent (%s) — skipping drift-soll sync", soll_path)+ soll_path = _config_soll_path() # i18n-allow+ if not soll_path.exists(): # i18n-allow+ log.debug("config-soll.json absent (%s) — skipping drift-soll sync", soll_path) # i18n-allowreturnwith _WRITE_LOCK:- raw = soll_path.read_text(encoding="utf-8")+ raw = soll_path.read_text(encoding="utf-8") # i18n-allowdata = json.loads(raw)block = data.get("brain.worker")if not isinstance(block, dict):@@ -1557,13 +1557,13 @@ def _update_config_soll_worker_key(key: str, value: str) -> None:block[key] = valueout = json.dumps(data, indent=2, ensure_ascii=False) + "\n"- _atomic_write_text(soll_path, out)+ _atomic_write_text(soll_path, out) # i18n-allowdef _atomic_write_text(path: Path, content: str) -> None:"""Atomic tempfile + replace for a plain UTF-8 text file (no read-only flag).- Used for config-soll.json, which — unlike jarvis.toml — does not carry the+ Used for config-soll.json, which — unlike jarvis.toml — does not carry the # i18n-allowBUG-010 read-only defense flag."""tmp = path.with_suffix(path.suffix + ".tmp")diff --git a/jarvis/marketplace/usage_cards/google_calendar.md b/jarvis/marketplace/usage_cards/google_calendar.mdindex d3987ab85f..915a12d802 100644--- a/jarvis/marketplace/usage_cards/google_calendar.md+++ b/jarvis/marketplace/usage_cards/google_calendar.md@@ -1,6 +1,6 @@---plugin_id: google_calendar-keywords: termin, termine, kalender, calendar, meeting, appointment, schedule, heute, morgen, übermorgen, woche, wochenende, tagesplan, plan, vorhaben, was habe ich, was steht an, was steht drin, eintragen, eintrag, verschieben, absagen, nachhilfe, prüfung, klausur+keywords: termin, termine, kalender, calendar, meeting, appointment, schedule, heute, morgen, übermorgen, woche, wochenende, tagesplan, plan, vorhaben, was habe ich, was steht an, was steht drin, eintragen, eintrag, verschieben, absagen, nachhilfe, prüfung, klausur # i18n-allow---Use the google_calendar tool to read and manage the user's calendar. This is adirect, router-tier action — NEVER spawn a worker / sub-agent for a calendardiff --git a/jarvis/marketplace/usage_cards/linear.md b/jarvis/marketplace/usage_cards/linear.mdindex 86c842f401..c7b55fc705 100644--- a/jarvis/marketplace/usage_cards/linear.md+++ b/jarvis/marketplace/usage_cards/linear.md@@ -1,6 +1,6 @@---plugin_id: linear-keywords: linear, issue, issues, ticket, tickets, aufgabe, aufgaben, task, tasks, bug, bugs, sprint, projekt, project, backlog, roadmap, zyklus, cycle, team, status, priorität, priority+keywords: linear, issue, issues, ticket, tickets, aufgabe, aufgaben, task, tasks, bug, bugs, sprint, projekt, project, backlog, roadmap, zyklus, cycle, team, status, priorität, priority # i18n-allow---Use linear/* tools to create, update, search, and close issues and projects.- Resolve team identifiers before creating issues; do not guess team IDs.diff --git a/jarvis/marketplace/usage_cards/slack.md b/jarvis/marketplace/usage_cards/slack.mdindex 250d998ffb..f211e407b7 100644--- a/jarvis/marketplace/usage_cards/slack.md+++ b/jarvis/marketplace/usage_cards/slack.md@@ -1,6 +1,6 @@---plugin_id: slack-keywords: slack, nachricht, message, nachrichten, messages, channel, kanal, kanäle, dm, direktnachricht, direct message, team, posten, post, senden, send, schreiben, write, suchen, search+keywords: slack, nachricht, message, nachrichten, messages, channel, kanal, kanäle, dm, direktnachricht, direct message, team, posten, post, senden, send, schreiben, write, suchen, search # i18n-allow---Use slack/* tools to read channels, search messages, and send messages or DMs.- Jarvis acts as the authenticated user (user-level scopes), not as a bot.diff --git a/jarvis/marketplace/usage_cards/stripe.md b/jarvis/marketplace/usage_cards/stripe.mdindex 74a0117ae6..23dc525690 100644--- a/jarvis/marketplace/usage_cards/stripe.md+++ b/jarvis/marketplace/usage_cards/stripe.md@@ -1,6 +1,6 @@---plugin_id: stripe-keywords: stripe, zahlung, zahlung, payment, payments, kunde, kunden, customer, customers, rechnung, rechnungen, invoice, invoices, subscription, abo, abonnement, charge, refund, rückerstattung, balance, guthaben, preis, price+keywords: stripe, zahlung, zahlung, payment, payments, kunde, kunden, customer, customers, rechnung, rechnungen, invoice, invoices, subscription, abo, abonnement, charge, refund, rückerstattung, balance, guthaben, preis, price # i18n-allow---Use stripe/* tools to look up customers, payments, invoices, and balance — read-first.- The hosted MCP server is read-focused; destructive mutations require explicit user intent.diff --git a/jarvis/mcp/adapter.py b/jarvis/mcp/adapter.pyindex 46e27ea34f..662a51228b 100644--- a/jarvis/mcp/adapter.py+++ b/jarvis/mcp/adapter.py@@ -78,9 +78,9 @@ class MCPToolAdapter:raw_desc = mcp_tool_def.get("description", "") or ""self.description: str = (f"[ACTION-ONLY · MCP: {client.spec.name}] {raw_desc} "- f"Fuehrt Operationen auf dem verbundenen {client.spec.name}-System aus. "- f"NUR fuer gezielte Aktionen nutzen, NICHT fuer allgemeine Recherche "- f"ueber {client.spec.name} als Thema — dafuer search_web."+ f"Performs operations on the connected {client.spec.name} system. "+ f"USE ONLY for targeted actions, NOT for general research "+ f"about {client.spec.name} as a topic — use search_web for that.")# Flag for the tool-use-loop guard: MCP tools are always action-centric.self.is_action_tool: bool = True@@ -123,7 +123,7 @@ class MCPToolAdapter:)except Exception as e: # noqa: BLE001log.warning(- "MCPTool %s Fehler nach %d ms: %s",+ "MCPTool %s error after %d ms: %s",self.name,(time.time_ns() - start_ns) // 1_000_000,e,diff --git a/jarvis/mcp/bootstrap.py b/jarvis/mcp/bootstrap.pyindex d6a98b4d40..68e5d489a6 100644--- a/jarvis/mcp/bootstrap.py+++ b/jarvis/mcp/bootstrap.py@@ -73,7 +73,7 @@ async def install_server(spec: MCPServerSpec) -> InstallResult:if shutil.which(argv[0]) is None:return InstallResult(spec.name, False,- error=f"Launcher {argv[0]!r} nicht im PATH",+ error=f"Launcher {argv[0]!r} not on PATH",)# Probe: get the package argument, then append --help.diff --git a/jarvis/mcp/client.py b/jarvis/mcp/client.pyindex 675e1ddfce..3d73d2d1b8 100644--- a/jarvis/mcp/client.py+++ b/jarvis/mcp/client.py@@ -124,7 +124,7 @@ class MCPClient:)else:raise NotImplementedError(- f"Transport {self.spec.transport!r} (noch) nicht unterstützt"+ f"Transport {self.spec.transport!r} not (yet) supported")session = await stack.enter_async_context(ClientSession(read, write))@@ -152,12 +152,12 @@ class MCPClient:try:await self._exit_stack.aclose()except Exception as e: # noqa: BLE001- log.warning("MCPClient[%s] stop-Fehler: %s", self.spec.name, e)+ log.warning("MCPClient[%s] stop error: %s", self.spec.name, e)finally:self._exit_stack = Noneself._session = None- # ---- Interaktion --------------------------------------------------+ # ---- Interaction ----------------------------------------------------async def list_tools(self) -> list[dict[str, Any]]:"""Return the cached tool list (list of dicts)."""diff --git a/jarvis/mcp/registry.py b/jarvis/mcp/registry.pyindex 60298a3c4a..2fc4485044 100644--- a/jarvis/mcp/registry.py+++ b/jarvis/mcp/registry.py@@ -130,7 +130,7 @@ class MCPRegistry:headers=dict(entry.get("headers", {})),)except (TypeError, ValueError) as exc:- log.warning("mcp.json[%s] ungültig: %s", name, exc)+ log.warning("mcp.json[%s] invalid: %s", name, exc)continueself._specs[name] = spec@@ -179,7 +179,7 @@ class MCPRegistry:await asyncio.wait_for(client.start(), timeout=_START_TIMEOUT_S)self._clients[spec.name] = clientself._errors.pop(spec.name, None)- log.info("MCP-Server %s gestartet", spec.name)+ log.info("MCP server %s started", spec.name)except TimeoutError:error_msg = f"start timeout ({_START_TIMEOUT_S:.0f}s)"self._errors[spec.name] = error_msg@@ -236,7 +236,7 @@ def _env_from_mcp_json(name: str) -> dict[str, str] | None:if looked_up:resolved[key] = looked_upcontinue- log.warning("env[%s]=%s für MCP %s konnte nicht aufgelöst werden",+ log.warning("env[%s]=%s could not be resolved for MCP %s",key, value, name)continueresolved[key] = valuediff --git a/jarvis/mcp/server.py b/jarvis/mcp/server.pyindex 0c85468aa7..e3b01cf305 100644--- a/jarvis/mcp/server.py+++ b/jarvis/mcp/server.py@@ -1,29 +1,30 @@-"""Jarvis-als-MCP-Server.+"""Jarvis as an MCP server.-Externe MCP-Clients (OpenClaw CLI, Cursor, VSCode Extension) können-Jarvis-interne Fähigkeiten nutzen:+External MCP clients (OpenClaw CLI, Cursor, VSCode Extension) can use+Jarvis-internal capabilities:Tools:- - memory_search(query, k) — FTS5-BM25 Recall-Search- - memory_recent(limit, role) — Letzte N Messages- - memory_add_fact(fact, category) — Core-Memory-Fact ergänzen- - skills_list() — Alle registrierten Skills- - skills_run(skill_name) — Skill ausführen+ - memory_search(query, k) — FTS5-BM25 recall search+ - memory_recent(limit, role) — last N messages+ - memory_add_fact(fact, category) — append a core-memory fact+ - skills_list() — all registered skills+ - skills_run(skill_name) — run a skillResources:- - jarvis://core-memory/persona — Live-Dump des Persona-Blocks- - jarvis://core-memory/all — Vollständiges Core-Memory JSON+ - jarvis://core-memory/persona — live dump of the persona block+ - jarvis://core-memory/all — full core-memory JSON-Registrierung in OpenClaw:+Registration in OpenClaw:claude mcp add jarvis python -m jarvis.mcp.server-Loop-Detection:- Jeder Request-Handler prüft `JARVIS_MCP_DEPTH` env-var. Wenn >= max_call_depth,- gibt's Fehler (verhindert infinite dispatch_to_harness→openclaw→jarvis-mcp).+Loop detection:+ Every request handler checks the `JARVIS_MCP_DEPTH` env var. If it is+ >= max_call_depth, it raises an error (prevents an infinite+ dispatch_to_harness→openclaw→jarvis-mcp loop).Auth (optional):- Setze ENV `JARVIS_MCP_TOKEN` um einen Bearer-Header auf HTTP-Transport zu- verlangen. Stdio nutzt Env-Inheritance — kein extra Auth nötig.+ Set the `JARVIS_MCP_TOKEN` env var to require a bearer header on the+ HTTP transport. Stdio uses env inheritance — no extra auth needed."""from __future__ import annotations@@ -166,7 +167,7 @@ def build_app() -> tuple[object, dict]:})return {"count": len(all_skills), "skills": all_skills}except Exception as exc: # noqa: BLE001- return {"error": f"Skills-System nicht verfügbar: {exc}"}+ return {"error": f"Skills system unavailable: {exc}"}# ------------------------------------------------------------------# Resourcesdiff --git a/jarvis/mcp/state.py b/jarvis/mcp/state.pyindex c02a27d7d4..3540334bfe 100644--- a/jarvis/mcp/state.py+++ b/jarvis/mcp/state.py@@ -62,7 +62,7 @@ def _read_mcp_json() -> dict[str, Any]:try:data = json.loads(MCP_JSON_PATH.read_text(encoding="utf-8"))except (json.JSONDecodeError, OSError) as exc:- log.warning("mcp.json nicht lesbar (%s) — Default", exc)+ log.warning("mcp.json not readable (%s) — using default", exc)return _empty_config()if not isinstance(data, dict):return _empty_config()@@ -79,7 +79,7 @@ def _write_mcp_json(data: dict[str, Any]) -> None:# -----------------------------------------------------------------------# Migration von legacy data/mcp_state.json+# Migration from legacy data/mcp_state.json# ----------------------------------------------------------------------def _migrate_legacy_if_needed() -> None:@@ -121,7 +121,7 @@ def _migrate_legacy_if_needed() -> None:LEGACY_STATE_PATH.rename(LEGACY_STATE_PATH.with_suffix(".json.bak"))except OSError:pass- log.info("mcp.json aus legacy state migriert (%d server)", len(cfg["mcpServers"]))+ log.info("mcp.json migrated from legacy state (%d servers)", len(cfg["mcpServers"]))# ----------------------------------------------------------------------@@ -198,7 +198,7 @@ def remove_server(name: str) -> bool:# -----------------------------------------------------------------------# Claude-Desktop-Import+# Claude Desktop import# ----------------------------------------------------------------------def import_claude_desktop() -> tuple[int, list[str], str]:@@ -211,23 +211,23 @@ def import_claude_desktop() -> tuple[int, list[str], str]:"""appdata = os.environ.get("APPDATA")if not appdata:- return (0, [], "APPDATA-Variable nicht gesetzt.")+ return (0, [], "APPDATA variable not set.")src = Path(appdata) / "Claude" / "claude_desktop_config.json"if not src.exists():return (0,[],- f"Claude-Desktop-Config nicht gefunden unter {src}.",+ f"Claude Desktop config not found at {src}.",)try:raw = json.loads(src.read_text(encoding="utf-8"))except (json.JSONDecodeError, OSError) as exc:- return (0, [], f"Config nicht lesbar: {exc}")+ return (0, [], f"Config not readable: {exc}")claude_servers = raw.get("mcpServers", {})if not isinstance(claude_servers, dict) or not claude_servers:- return (0, [], "Keine mcpServers in Claude-Desktop-Config gefunden.")+ return (0, [], "No mcpServers found in the Claude Desktop config.")added: list[str] = []skipped: list[str] = []@@ -248,14 +248,14 @@ def import_claude_desktop() -> tuple[int, list[str], str]:"args": list(entry.get("args", [])),"env": dict(entry.get("env", {})),"enabled": False,- "description": "Importiert aus Claude Desktop.",+ "description": "Imported from Claude Desktop.",}added.append(name)_write_mcp_json(cfg)- note = f"{len(added)} neue Server importiert"+ note = f"{len(added)} new servers imported"if skipped:- note += f", {len(skipped)} übersprungen (existieren bereits)"+ note += f", {len(skipped)} skipped (already exist)"return (len(added), added, note + ".")diff --git a/jarvis/memory/bootstrap_runner.py b/jarvis/memory/bootstrap_runner.pyindex eec4463baf..5893e78c4d 100644--- a/jarvis/memory/bootstrap_runner.py+++ b/jarvis/memory/bootstrap_runner.py@@ -58,28 +58,28 @@ log = logging.getLogger(__name__)_QUESTIONS: tuple[str, ...] = (# 0: Name + form of address- "Wie heisst Du, und wie soll ich Dich ansprechen?",+ "Wie heisst Du, und wie soll ich Dich ansprechen?", # i18n-allow# 1: Languages- "Welche Sprachen sprichst Du mit mir? Default ist Deutsch und Englisch.",+ "Welche Sprachen sprichst Du mit mir? Default ist Deutsch und Englisch.", # i18n-allow# 2: Role- "Was machst Du beruflich? Kurz, ein paar Worte reichen.",+ "Was machst Du beruflich? Kurz, ein paar Worte reichen.", # i18n-allow# 3: Directness- "Magst Du direkte, kurze Antworten, oder lieber ausfuehrliche Erklaerungen?",+ "Magst Du direkte, kurze Antworten, oder lieber ausfuehrliche Erklaerungen?", # i18n-allow# 4: Pet peeves- "Gibt es Sachen, die Dich nerven sollen? Zum Beispiel keine Emojis, keine "- "Rueckfragen, kein Small-Talk.",+ "Gibt es Sachen, die Dich nerven sollen? Zum Beispiel keine Emojis, keine " # i18n-allow+ "Rueckfragen, kein Small-Talk.", # i18n-allow)_GREETING = (- "Hey, ich bin Jarvis. Bevor wir richtig starten, frag ich Dich einmal "- "kurz durch fuenf Basis-Dinge durch — damit ich weiss, mit wem ich's zu "- "tun habe. "+ "Hey, ich bin Jarvis. Bevor wir richtig starten, frag ich Dich einmal " # i18n-allow+ "kurz durch fuenf Basis-Dinge durch — damit ich weiss, mit wem ich's zu " # i18n-allow+ "tun habe. " # i18n-allow)_FAREWELL = (- "Danke, das reicht fuers Erste. Ich hab alles in USER.md gespeichert und "- "lerne den Rest im laufenden Betrieb dazu. Du kannst jederzeit direkt in "- "der Datei editieren."+ "Danke, das reicht fuers Erste. Ich hab alles in USER.md gespeichert und " # i18n-allow+ "lerne den Rest im laufenden Betrieb dazu. Du kannst jederzeit direkt in " # i18n-allow+ "der Datei editieren." # i18n-allow)@@ -87,10 +87,10 @@ _FAREWELL = (# Parser regexes# -----------------------------------------------------------------------# "Ich heisse Ruben", "ich heiße ruben", "mein Name ist Ruben Lütke",+# "Ich heisse Ruben", "ich heiße ruben", "mein Name ist Ruben Lütke", # i18n-allow# "ich bin Harald". Case-insensitive. Capture group = name remainder._NAME_INTRO_RE = re.compile(- r"(?:ich\s+heisse|ich\s+heiße|mein\s+name\s+ist|ich\s+bin|my\s+name\s+is|i\s+am|i'm)\s+(.+)",+ r"(?:ich\s+heisse|ich\s+heiße|mein\s+name\s+ist|ich\s+bin|my\s+name\s+is|i\s+am|i'm)\s+(.+)", # i18n-allowre.IGNORECASE,)@@ -102,45 +102,45 @@ _ADDRESS_RE = re.compile(# Strip trailing junk after the actual name (e.g. "Ruben, aber nenn# mich gerne Rube" → we want "Ruben"). Cut at first comma / " aber ".-_NAME_TRAIL_RE = re.compile(r"[,;.!?]|\s+aber\s+|\s+und\s+|\s+but\s+", re.IGNORECASE)+_NAME_TRAIL_RE = re.compile(r"[,;.!?]|\s+aber\s+|\s+und\s+|\s+but\s+", re.IGNORECASE) # i18n-allow# Language keywords → ISO-639-1. Key match is case-insensitive substring._LANGUAGE_MAP: tuple[tuple[tuple[str, ...], str], ...] = ((("deutsch", "german", "allemand", " de ", " de,", " de."), "de"),(("englisch", "english", "anglais", " en ", " en,", " en."), "en"),(("spanisch", "spanish", "espanol", "español", " es ", " es,"), "es"),- (("franzoesisch", "französisch", "french", "francais", "français", " fr "), "fr"),+ (("franzoesisch", "französisch", "french", "francais", "français", " fr "), "fr"), # i18n-allow(("italienisch", "italian", "italiano", " it ", " it,"), "it"),- (("niederlaendisch", "niederländisch", "dutch", "nederlands", " nl "), "nl"),+ (("niederlaendisch", "niederländisch", "dutch", "nederlands", " nl "), "nl"), # i18n-allow(("portugiesisch", "portuguese", " pt ", " pt,"), "pt"),(("polnisch", "polish", "polski", " pl "), "pl"),- (("tuerkisch", "türkisch", "turkish", "türkçe", " tr "), "tr"),+ (("tuerkisch", "türkisch", "turkish", "türkçe", " tr "), "tr"), # i18n-allow)# Directness signals — keyword lists. First match wins._DIRECT_KEYWORDS = (- "direkt", "kurz", "knapp", "tldr", "no fluff", "auf den punkt",+ "direkt", "kurz", "knapp", "tldr", "no fluff", "auf den punkt", # i18n-allow"to the point", "brief", "short", "concise",)_VERBOSE_KEYWORDS = (- "ausfuehrlich", "ausführlich", "detailliert", "erklaer", "erklär",+ "ausfuehrlich", "ausführlich", "detailliert", "erklaer", "erklär", # i18n-allow"verbose", "deep dive", "deep-dive", "tief", "genau", "mit details",)# Pet-peeves splitter: ",", " und ", " sowie ", " plus ", " & "_PEEVE_SPLIT_RE = re.compile(r"\s*(?:,|;|\bund\b|\bsowie\b|\bplus\b|\band\b|&)\s*", re.IGNORECASE)-# Extract "Emojis" from "Keine Emojis". Analogous to English "no X".+# Extract "Emojis" from "Keine Emojis". Analogous to English "no X". # i18n-allow_NEGATIVE_PREFIX_RE = re.compile(- r"^\s*(?:keine?|kein|no|nicht|never|please\s+no|bitte\s+kein(?:e)?)\s+",+ r"^\s*(?:keine?|kein|no|nicht|never|please\s+no|bitte\s+kein(?:e)?)\s+", # i18n-allowre.IGNORECASE,)-# "Weiss nicht" / "egal" — user skips the question+# "Weiss nicht" / "egal" — user skips the question # i18n-allow_SKIP_KEYWORDS = (- "weiss nicht", "weiß nicht", "keine ahnung", "egal", "ist mir egal",+ "weiss nicht", "weiß nicht", "keine ahnung", "egal", "ist mir egal", # i18n-allow"dont know", "don't know", "pass", "skip", "ueberspring",- "überspring", "weiter",+ "überspring", "weiter", # i18n-allow)@@ -211,7 +211,7 @@ class BootstrapRunner:return _FAREWELLif not self._started:self._started = True- log.info("Bootstrap-Interview gestartet (Workspace=%s)",+ log.info("Bootstrap interview started (workspace=%s)",self.workspace.root)return _GREETING + (_QUESTIONS[0] if _QUESTIONS else "")# Already started → just re-deliver the current question@@ -277,7 +277,7 @@ class BootstrapRunner:3. Fallback: take the whole text as the name (trimmed)."""if self._is_skip(text):- log.info("Bootstrap-Name uebersprungen — setze auf 'User'")+ log.info("Bootstrap name skipped — defaulting to 'User'")self.profile.set("identity", "name", "User")return@@ -298,7 +298,7 @@ class BootstrapRunner:# "Ich bin Ruben, nenn mich Rube": the address group can overlap the# name — we keep both.- # Remove trailing junk (comma, "aber ...", "und ...")+ # Remove trailing junk (comma, "aber ...", "und ...") # i18n-allowname = _trim_name(name_candidate)address = _trim_name(address_candidate) if address_candidate else None@@ -313,7 +313,7 @@ class BootstrapRunner:else:self.profile.set("identity", "preferred_address", name)- log.info("Bootstrap-Name: name=%r address=%r", name, address or name)+ log.info("Bootstrap name: name=%r address=%r", name, address or name)def _parse_languages(self, text: str) -> None:"""Question 2: languages. Default [de, en] if nothing detected."""@@ -328,12 +328,12 @@ class BootstrapRunner:for code in langs:self.profile.append_list("identity", "languages", code)self.profile.set("identity", "primary_language", langs[0])- log.info("Bootstrap-Languages: %s (primary=%s)", langs, langs[0])+ log.info("Bootstrap languages: %s (primary=%s)", langs, langs[0])def _parse_role(self, text: str) -> None:"""Question 3: role. Stored as a free observation — there is no dedicated role field."""if not text or self._is_skip(text):- log.info("Bootstrap-Rolle uebersprungen")+ log.info("Bootstrap role skipped")return# Role goes into the observations section — Curator can structure it later.self.profile.append_observation(@@ -341,7 +341,7 @@ class BootstrapRunner:_truncate(text, 200),evidence=text,)- log.info("Bootstrap-Rolle notiert: %r", _truncate(text, 80))+ log.info("Bootstrap role noted: %r", _truncate(text, 80))def _parse_directness(self, text: str) -> None:"""Question 4: directness / verbosity.@@ -362,25 +362,25 @@ class BootstrapRunner:self.profile.set("communication", "directness", directness)self.profile.set("communication", "verbosity", verbosity)- log.info("Bootstrap-Directness: directness=%d verbosity=%s",+ log.info("Bootstrap directness: directness=%d verbosity=%s",directness, verbosity)def _parse_pet_peeves(self, text: str) -> None:- """Question 5: pet peeves. Split + optionally remove "keine X" prefix."""+ """Question 5: pet peeves. Split + optionally remove "keine X" prefix.""" # i18n-allowif not text or self._is_skip(text):- log.info("Bootstrap-Pet-Peeves uebersprungen")+ log.info("Bootstrap pet peeves skipped")returnpeeves = _extract_peeves(text)for peeve in peeves:self.profile.append_list("values", "pet_peeves", peeve)- # Special case: "keine Emojis" also sets the structured field directly+ # Special case: "keine Emojis" also sets the structured field directly # i18n-allowlowered = text.lower()if "emoji" in lowered and _has_negation_near(lowered, "emoji"):self.profile.set("communication", "emoji_ok", False)- log.info("Bootstrap-Pet-Peeves: %s", peeves)+ log.info("Bootstrap pet peeves: %s", peeves)# ------------------------------------------------------------------# Finalize@@ -390,16 +390,16 @@ class BootstrapRunner:"""Persists the profile and deletes BOOTSTRAP.md."""try:self.profile.save()- log.info("Bootstrap: USER.md gespeichert nach %s", self.profile.path)+ log.info("Bootstrap: USER.md saved to %s", self.profile.path)except Exception:- log.exception("Bootstrap: USER.md konnte nicht gespeichert werden")+ log.exception("Bootstrap: USER.md could not be saved")# Still mark as finished — no re-run is better than an infinite loop.try:self.workspace.consume_bootstrap()- log.info("Bootstrap: BOOTSTRAP.md geloescht")+ log.info("Bootstrap: BOOTSTRAP.md deleted")except Exception:- log.exception("Bootstrap: BOOTSTRAP.md konnte nicht geloescht werden")+ log.exception("Bootstrap: BOOTSTRAP.md could not be deleted")self._finished = True@@ -493,10 +493,10 @@ def _clean_peeve(fragment: str) -> str:s = fragment.strip().strip('"\'.,;:!?')if not s:return ""- # "keine X" → "X"+ # "keine X" → "X" # i18n-allows = _NEGATIVE_PREFIX_RE.sub("", s).strip()# Drop overly generic fragments- if s.lower() in {"", "nichts", "nix", "keine", "kein", "nothing", "none"}:+ if s.lower() in {"", "nichts", "nix", "keine", "kein", "nothing", "none"}: # i18n-allowreturn ""return s@@ -508,7 +508,7 @@ def _has_negation_near(text: str, keyword: str) -> bool:return Falsewindow_start = max(0, idx - 15)window = text[window_start:idx]- return bool(re.search(r"\b(kein(?:e)?|no|not|nicht|ohne|without)\b", window, re.IGNORECASE))+ return bool(re.search(r"\b(kein(?:e)?|no|not|nicht|ohne|without)\b", window, re.IGNORECASE)) # i18n-allowdef _truncate(s: str, n: int) -> str:@@ -568,8 +568,8 @@ if __name__ == "__main__": # pragma: no coverassert r == _QUESTIONS[1]# --- Stage 1 → 2: languages ---- r = runner.handle_answer("Deutsch und English, manchmal Spanisch")- print(f"[A2] Sprachen -> next: {r}")+ r = runner.handle_answer("Deutsch und English, manchmal Spanisch") # i18n-allow+ print(f"[A2] languages -> next: {r}")langs = profile.get("identity", "languages") or []assert "de" in langs and "en" in langs and "es" in langs, langsassert profile.get("identity", "primary_language") == "de"@@ -588,7 +588,7 @@ if __name__ == "__main__": # pragma: no coverassert r == _QUESTIONS[4]# --- Stage 4 → finished --- (pet peeves)- r = runner.handle_answer("keine Emojis, keine Confirmation-Fragen und kein Small-Talk")+ r = runner.handle_answer("keine Emojis, keine Confirmation-Fragen und kein Small-Talk") # i18n-allowprint(f"[A5] Peeves -> final: {r}")peeves = profile.get("values", "pet_peeves") or []assert "Emojis" in peeves, peevesdiff --git a/jarvis/memory/core_memory.py b/jarvis/memory/core_memory.pyindex 5b23ab96ab..a7c79bab61 100644--- a/jarvis/memory/core_memory.py+++ b/jarvis/memory/core_memory.py@@ -20,7 +20,7 @@ def default_core_memory() -> dict[str, Any]:"persona": {"name": "Jarvis","role": "Voice-gesteuerter Meta-Orchestrator",- "style": "hilfsbereit, präzise, auf Deutsch",+ "style": "hilfsbereit, präzise, auf Deutsch", # i18n-allow},"user_facts": {},"preferences": {diff --git a/jarvis/memory/curator/curator.py b/jarvis/memory/curator/curator.pyindex d8c925ce72..a72c9cb49f 100644--- a/jarvis/memory/curator/curator.py+++ b/jarvis/memory/curator/curator.py@@ -105,7 +105,7 @@ class Curator:)return reportexcept Exception as exc: # noqa: BLE001- log.warning("Curator-Pipeline fehlgeschlagen: %s", exc, exc_info=log.isEnabledFor(logging.DEBUG))+ log.warning("Curator pipeline failed: %s", exc, exc_info=log.isEnabledFor(logging.DEBUG))return MergeReport(failed=1)# ------------------------------------------------------------------diff --git a/jarvis/memory/curator/extractor.py b/jarvis/memory/curator/extractor.pyindex 55d8f03e59..0affa61557 100644--- a/jarvis/memory/curator/extractor.py+++ b/jarvis/memory/curator/extractor.py@@ -87,7 +87,7 @@ class Extractor:chunks.append(delta.content)raw = "".join(chunks).strip()except Exception as exc: # noqa: BLE001- log.warning("Curator-Extraction fehlgeschlagen (LLM): %s", exc)+ log.warning("Curator extraction failed (LLM): %s", exc)return []if not raw:@@ -95,7 +95,7 @@ class Extractor:data = _parse_json_robust(raw)if not data:- log.debug("Curator-Output nicht parseable:\n%s", raw[:500])+ log.debug("Curator output not parseable:\n%s", raw[:500])return []cands_raw = data.get("candidates", [])diff --git a/jarvis/memory/curator/merger.py b/jarvis/memory/curator/merger.pyindex f1a4ef50f7..2e225d3bc6 100644--- a/jarvis/memory/curator/merger.py+++ b/jarvis/memory/curator/merger.py@@ -93,7 +93,7 @@ class Merger:else:report.skipped += 1except Exception as exc: # noqa: BLE001- log.warning("Merge fehlgeschlagen fuer %s: %s", cand, exc)+ log.warning("Merge failed for %s: %s", cand, exc)report.failed += 1# Persist@@ -101,14 +101,14 @@ class Merger:try:self._profile.save()except Exception as exc: # noqa: BLE001- log.error("USER.md save fehlgeschlagen: %s", exc)+ log.error("USER.md save failed: %s", exc)report.failed += 1for person in people_touched.values():try:person.save()except Exception as exc: # noqa: BLE001- log.error("Person save fehlgeschlagen (%s): %s", person.name, exc)+ log.error("Person save failed (%s): %s", person.name, exc)report.failed += 1# Emit events (after persistence — we do not want events fordiff --git a/jarvis/memory/curator/prompts.py b/jarvis/memory/curator/prompts.pyindex f06fef65fb..2697a16aee 100644--- a/jarvis/memory/curator/prompts.py+++ b/jarvis/memory/curator/prompts.py@@ -45,89 +45,89 @@ def _render_allowed_fields() -> str:return "\n".join(lines)-EXTRACTOR_SYSTEM_PROMPT = """Du bist ein Curator fuer ein persoenliches User-Profile.-Deine Aufgabe: aus einem Gespraechs-Turn zwischen User und Assistant die **stabilen, \-nuetzlichen Facts** extrahieren und in einem strikten JSON-Schema zurueckgeben.+EXTRACTOR_SYSTEM_PROMPT = """You are a curator for a personal user profile.+Your task: extract the **stable, useful facts** from a conversation turn \+between the user and the assistant and return them in a strict JSON schema.-DU GIBST AUSSCHLIESSLICH JSON ZURUECK. KEIN Markdown, kein Kommentar, kein Fence.+YOU RETURN ONLY JSON. NO Markdown, no comment, no fence.-# KRITISCHE REGEL — Subject-Disambiguierung+# CRITICAL RULE — subject disambiguation-Jedes Fact hat genau EIN Subject:-- `"user"` — der Mensch der mit Jarvis spricht.-- `"person:<Name>"` — eine ANDERE Person, die der User erwaehnt.+Every fact has exactly ONE subject:+- `"user"` — the human talking to Jarvis.+- `"person:<Name>"` — ANOTHER person the user mentions.-**GOLDEN RULE:** Wenn der User in erster Person spricht ("ich", "mein", "mir"),-ist das Subject `user`. Wenn der User einen Namen erwaehnt, ist dieser Name-ein `person:<Name>`, NICHT der User.+**GOLDEN RULE:** If the user speaks in the first person ("I", "my", "me"),+the subject is `user`. If the user mentions a name, that name is a+`person:<Name>`, NOT the user.-## Beispiele — das hier DARF NICHT verwechselt werden:+## Examples — this must NOT be confused:-**Input:** User sagt "Meine Freundin Laura arbeitet bei X."+**Input:** User says "My girlfriend Laura works at X."**Output:**- `{"subject": "person:Laura", "cluster": "identity", "field": "name", "value": "Laura", "relationship": "partner", "confidence": 1.0, ...}`-- KEINESFALLS `{"subject": "user", "field": "name", "value": "Laura"}` — das waere ein krasser Fehler!+- NEVER `{"subject": "user", "field": "name", "value": "Laura"}` — that would be a serious mistake!-**Input:** User sagt "Ich heisse Ruben."+**Input:** User says "My name is Ruben."**Output:** `{"subject": "user", "cluster": "identity", "field": "name", "value": "Ruben", ...}`-**Input:** User sagt "Mein Kollege Paul hasst Emojis."-**Output:** Beobachtung ueber Paul (subject=person:Paul), NICHT ueber den User.+**Input:** User says "My colleague Paul hates emojis."+**Output:** An observation about Paul (subject=person:Paul), NOT about the user.-**Input:** User sagt "Sie sind super" (ohne klaren Antezedenten fuer 'sie')-**Output:** Gar nichts extrahieren — confidence ist zu niedrig.+**Input:** User says "They're great" (with no clear antecedent for "they")+**Output:** Extract nothing at all — confidence is too low.-# STABILITAETS-REGEL+# STABILITY RULE-Nur extrahieren was **langfristig stabil** ist:-- JA: Praeferenzen, Werte, Arbeitsweise, Humor, Kommunikationsstil, stabile Facts.-- NEIN: Tagesform, Emotion gerade eben, aktueller Task, Wetter, einmalige Ereignisse.+Only extract what is **stable over the long term**:+- YES: preferences, values, work style, humor, communication style, stable facts.+- NO: mood of the day, momentary emotion, current task, weather, one-off events.-Beispiel: "Ich bin heute muede" → NIX extrahieren (Tagesform).-Beispiel: "Ich mag keine Emojis in Code-Reviews" → `{"subject": "user", "cluster": "values", "field": "pet_peeves", "value": "Emojis in Code-Reviews", "operation": "append"}`+Example: "I'm tired today" → extract NOTHING (mood of the day).+Example: "I don't like emojis in code reviews" → `{"subject": "user", "cluster": "values", "field": "pet_peeves", "value": "Emojis in code reviews", "operation": "append"}`# CONFIDENCE-- `1.0` — User hat es direkt und unmissverstaendlich gesagt.-- `0.8-0.9` — klar impliziert aber nicht woertlich.-- `0.5-0.7` — vermutet. Wird in Review-Queue landen.-- `<0.5` — nicht extrahieren.+- `1.0` — the user said it directly and unambiguously.+- `0.8-0.9` — clearly implied but not verbatim.+- `0.5-0.7` — inferred. Goes to the review queue.+- `<0.5` — do not extract.-# DO-NOT-RECORD — KATEGORIEN DIE NIEMALS EXTRAHIERT WERDEN+# DO-NOT-RECORD — CATEGORIES THAT ARE NEVER EXTRACTED-- Politische oder religioese Ueberzeugungen.-- Gesundheits- oder Mental-Health-Diagnosen.-- Tagesform/Emotion ("gestresst", "muede", "froh").-- Beziehungs-Konflikte ("habe Streit mit X").-- Finanz-Details ("verdiene Y Euro").-- MBTI-Typ oder andere pseudo-psychologische Labels.+- Political or religious beliefs.+- Health or mental-health diagnoses.+- Mood of the day / emotion ("stressed", "tired", "happy").+- Relationship conflicts ("had a fight with X").+- Financial details ("earn Y euros").+- MBTI type or other pseudo-psychological labels.-Wenn der User solche Dinge erwaehnt: ignorieren. Keine Kompromisse.+If the user mentions such things: ignore them. No exceptions.-# ERLAUBTE FELDER (strikt — nichts anderes extrahieren)+# ALLOWED FIELDS (strict — do not extract anything else)""" + _render_allowed_fields() + """-# OUTPUT-SCHEMA+# OUTPUT SCHEMA{"candidates": [{"subject": "user" | "person:<Name>","cluster": "identity|communication|work_style|values|relationship",- "field": "<exakt eines der erlaubten Felder oder 'observation' fuer freie Notiz>",+ "field": "<exactly one of the allowed fields, or 'observation' for a free note>","value": <string|number|list|bool>,"operation": "set" | "append","confidence": 0.0,- "evidence": "<exakter User-Zitat-Ausschnitt, max 150 Zeichen>",- "relationship": "partner|family|colleague|friend|unknown" // nur wenn subject=person:+ "evidence": "<exact user quote excerpt, max 150 characters>",+ "relationship": "partner|family|colleague|friend|unknown" // only if subject=person:}]}-Wenn nichts Relevantes extrahierbar ist: `{"candidates": []}` zurueckgeben.+If nothing relevant can be extracted, return: `{"candidates": []}`.-GIB JETZT AUSSCHLIESSLICH DAS JSON ZURUECK.+RETURN ONLY THE JSON NOW."""@@ -143,12 +143,12 @@ def build_extraction_prompt(user_text: str, assistant_text: str,"""ctx_lines = []if user_name:- ctx_lines.append(f"- Der User heisst: {user_name}")+ ctx_lines.append(f"- The user's name is: {user_name}")if known_people:- ctx_lines.append(f"- Bereits bekannte Personen im Umfeld: {', '.join(known_people)}")- ctx = "\n".join(ctx_lines) if ctx_lines else "- (Noch keine Infos ueber User oder andere Personen.)"+ ctx_lines.append(f"- Already-known people in their circle: {', '.join(known_people)}")+ ctx = "\n".join(ctx_lines) if ctx_lines else "- (No info about the user or other people yet.)"- return f"""## Kontext+ return f"""## Context{ctx}@@ -160,4 +160,4 @@ def build_extraction_prompt(user_text: str, assistant_text: str,----Extrahiere jetzt stabile, nuetzliche Facts gemaess den Regeln. Output: JSON."""+Now extract stable, useful facts according to the rules. Output: JSON."""diff --git a/jarvis/memory/curator/validator.py b/jarvis/memory/curator/validator.pyindex 6e23c8d0a7..609b78d829 100644--- a/jarvis/memory/curator/validator.py+++ b/jarvis/memory/curator/validator.py@@ -37,16 +37,16 @@ CONFIDENCE_OVERWRITE = 0.85# Keywords that signal "Do Not Record" categories.# Redundant with the prompt — belt-and-suspenders defence against LLM slips.DO_NOT_RECORD_KEYWORDS = {- # Politik / Religion- "partei", "wähle", "waehle", "abtreibung", "migration", "christ", "muslim",- "jude", "islam", "katholisch", "evangelisch", "atheist", "gott ",- # Gesundheit / Mental Health (kurze Trigger, context-sensitive)- "depression", "burnout", "angststörung", "angststoerung", "therapie",- "adhs", "autismus", "diagnose", "diagnostiziert", "medikament",- "antidepress", "psychiater", "krebs", "chronisch",- # Finanz-Details (konkrete Zahlen)- "euro verdien", "gehalt von", "mein einkommen",- # MBTI & Pseudo-Psych+ # Politics / religion+ "partei", "wähle", "waehle", "abtreibung", "migration", "christ", "muslim", # i18n-allow+ "jude", "islam", "katholisch", "evangelisch", "atheist", "gott ", # i18n-allow+ # Health / mental health (short triggers, context-sensitive)+ "depression", "burnout", "angststörung", "angststoerung", "therapie", # i18n-allow+ "adhs", "autismus", "diagnose", "diagnostiziert", "medikament", # i18n-allow+ "antidepress", "psychiater", "krebs", "chronisch", # i18n-allow+ # Financial details (concrete numbers)+ "euro verdien", "gehalt von", "mein einkommen", # i18n-allow+ # MBTI & pseudo-psych"intp", "intj", "infp", "enfp", "entj", "entp", "estj", "estp","istp", "istj", "isfj", "isfp", "esfj", "esfp", "infj",}@@ -108,11 +108,11 @@ class Validator:if cand.is_person:pname = (cand.person_name or "").strip()if not pname:- return "reject", "leerer Personen-Name"+ return "reject", "empty person name"if pname.lower() in PRONOUN_FALSE_POSITIVES:- return "reject", f"'{pname}' ist ein Pronomen, kein Name"+ return "reject", f"'{pname}' is a pronoun, not a name"if len(pname) < 2:- return "reject", f"Name zu kurz: '{pname}'"+ return "reject", f"name too short: '{pname}'"# The user themselves must not appear as a person entryif user_name and pname.lower() == user_name.lower():return "reject", f"subject=person:{pname} == user.name"diff --git a/jarvis/missions/critic/runner.py b/jarvis/missions/critic/runner.pyindex dc3eb954ad..bfa13b15bb 100644--- a/jarvis/missions/critic/runner.py+++ b/jarvis/missions/critic/runner.py@@ -189,7 +189,7 @@ def _resolve_capability_requires_evidence(user_request: str) -> tuple[bool, str# root stem since the prefix often appears elsewhere in the sentence._ACTION_VERBS = re.compile(r'\b(send|schick|sende|create|erstell|add|anlegen|anlege|post|poste|'- r'delete|l\xf6sch|loesc|buy|bestell|schedule|trag|eintrag|book|reservier|'+ r'delete|l\xf6sch|loesc|buy|bestell|schedule|trag|eintrag|book|reservier|' # i18n-allowr'write|schreib|install|installier|run|starte|execute|f\xfchr|fuehr)\b',re.I,)@@ -220,7 +220,7 @@ def _resolve_capability_requires_evidence(user_request: str) -> tuple[bool, str# this", "reply to the message" are._SEND_VERB_RE = re.compile(r"\b(send|sende|sendest|schick|schicke|verschick|verschicke|post|poste|"- r"tweet|reply|antworte|antworten|message|nachricht|dm)\b",+ r"tweet|reply|antworte|antworten|message|nachricht|dm)\b", # i18n-allowre.I,)_MESSAGING_NOUN_RE = re.compile(@@ -245,9 +245,9 @@ def _request_is_messaging_action(user_request: str) -> bool:# --- Main gate function ----_CAPABILITY_NOT_EXECUTED_SUMMARY_DE: Final[str] = (+_CAPABILITY_NOT_EXECUTED_SUMMARY_DE: Final[str] = ( # i18n-allow"Konnte ich nicht ausführen — mir fehlt für diese Aufgabe das passende "- "Werkzeug. Worker hat keinen Tool-Aufruf gemacht."+ "Werkzeug. Worker hat keinen Tool-Aufruf gemacht." # i18n-allow)_CAPABILITY_NOT_EXECUTED_REASON: Final[str] = "capability_not_executed"@@ -425,7 +425,7 @@ def build_critic_cmd(## The codex CLI (ChatGPT subscription) is an *agent*, not a print tool. Given# a "return JSON" prompt it sometimes answers with conversational prose-# ("Ich rufe ExitPlanMode bewusst nicht auf: ...") instead of the verdict,+# ("I'm deliberately not calling ExitPlanMode: ...") instead of the verdict,# which made the codex-critic fail with CriticSchemaInvalid and the whole# mission show as `error` in the Outputs view even though the worker had# written the file correctly (live repro 2026-05-24, mission_019e5952).@@ -568,8 +568,8 @@ class CriticRunner:# success without actually writing a file" attack from 2026-05-14# (BUG-LIVE-02). For Read-Only tasks it's a false-positive that# forces three deterministic revise iterations followed by- # `critic_loop_exhausted` and a confusing "Drei Versuche haben- # nicht gereicht" announcement — even though Sonnet answered+ # `critic_loop_exhausted` and a confusing "three tries weren't+ # enough" announcement — even though Sonnet answered# perfectly on iter0.## The distinguishing signal: genuine tool-call evidence in the worker@@ -731,7 +731,7 @@ class CriticRunner:"Worker ran but the diff is empty; log claims are not ""ground truth. Deterministic revise.")- summary_de = (+ summary_de = ( # i18n-allow"Worker lief, aber keine sichtbaren Datei-Aenderungen. ""Automatische Wiederholung.")@@ -742,7 +742,7 @@ class CriticRunner:"into the workspace.")summary_en = "No worker output detected; deterministic revise."- summary_de = (+ summary_de = ( # i18n-allow"Worker hat keine sichtbaren Aenderungen erzeugt; ""automatische Wiederholung.")@@ -801,14 +801,14 @@ class CriticRunner:and aggregate_axes_status(verdict) != "pass"):logger.warning(- "CriticRunner: verdict=approve mit fail-axis -> deterministischer downgrade auf revise"+ "CriticRunner: verdict=approve with fail-axis -> deterministic downgrade to revise")return verdict.model_copy(update={"verdict": "revise","summary": (- "Aggregations-Override: verdict=approve war inkonsistent mit "- "axis-fail. Downgraded auf revise. Original: "+ "Aggregation override: verdict=approve was inconsistent with "+ "axis-fail. Downgraded to revise. Original: "+ (verdict.summary or ""))[:280],}@@ -849,7 +849,7 @@ class CriticRunner:update={"verdict": "revise","summary": (- "Aggregations-Override (post-retry): "+ "Aggregation override (post-retry): "+ (verdict.summary or ""))[:280],}@@ -857,13 +857,13 @@ class CriticRunner:if verdict is None:raise CriticSchemaInvalid(- "Critic lieferte zweimal keinen schema-validen JSON-Output."+ "Critic returned no schema-valid JSON output twice.")# Empty-evidence approval even after retry -> raise (no silent pass).if verdict.verdict == "approve" and not is_approval_valid(verdict):raise CriticVerdictInconsistent(- "Critic-Approve mit leerer Evidence auch nach adversarial reframe."+ "Critic approved with empty evidence even after adversarial reframe.")# --- Capability-Honesty Gate (Layer 3c, Capability Coupling spec) ---@@ -1314,8 +1314,8 @@ class CriticRunner:"--print",# 2026-05-24 fix: was "--permission-mode plan". Plan mode makes# claude --print treat the request as a *planning* task and emit- # meta-commentary about ExitPlanMode ("Ich rufe ExitPlanMode- # bewusst nicht auf: ...") instead of the requested JSON verdict+ # meta-commentary about ExitPlanMode ("I'm deliberately not+ # calling ExitPlanMode: ...") instead of the requested JSON verdict# — which failed every critic with CriticSchemaInvalid and made# missions show "error" in the Outputs view even when the worker# had written the file correctly (live repro mission_019e5960).@@ -1380,7 +1380,7 @@ class CriticRunner:with _suppress(Exception):await asyncio.wait_for(proc.wait(), timeout=5.0)raise CriticTimeout(- f"Critic (claude-direct) ueber {self._timeout}s — gekillt."+ f"Critic (claude-direct) exceeded {self._timeout}s — killed.") from excwall_ms = int((time.perf_counter() - t0) * 1000)@@ -1613,7 +1613,7 @@ class CriticRunner:with _suppress(OSError):__import__("os").unlink(schema_path)raise CriticTimeout(- f"Critic (codex-direct) ueber {self._timeout}s -- gekillt."+ f"Critic (codex-direct) exceeded {self._timeout}s -- killed.") from excfinally:with _suppress(OSError):diff --git a/jarvis/missions/event_bus.py b/jarvis/missions/event_bus.pyindex 21c04a955c..36adbdd07b 100644--- a/jarvis/missions/event_bus.py+++ b/jarvis/missions/event_bus.py@@ -78,7 +78,7 @@ class MissionBus:try:await handler(envelope)except Exception:- log.exception("MissionBus: Wildcard-Handler-Fehler verworfen")+ log.exception("MissionBus: wildcard handler error discarded")@asynccontextmanagerasync def subscribe(diff --git a/jarvis/missions/event_store.py b/jarvis/missions/event_store.pyindex a05676b51a..f1f718047a 100644--- a/jarvis/missions/event_store.py+++ b/jarvis/missions/event_store.py@@ -108,7 +108,7 @@ class MissionEventStore:"""if envelope.seq is not None:raise ValueError(- "append_and_publish: envelope.seq muss None sein (server-assigned)"+ "append_and_publish: envelope.seq must be None (server-assigned)")payload_json = envelope.payload.model_dump_json()@@ -135,7 +135,7 @@ class MissionEventStore:row = await cur.fetchone()await cur.close()if row is None:- raise RuntimeError("INSERT ... RETURNING seq lieferte keinen Wert")+ raise RuntimeError("INSERT ... RETURNING seq returned no value")seq = int(row[0])envelope_with_seq = envelope.model_copy(update={"seq": seq})diff --git a/jarvis/missions/init.py b/jarvis/missions/init.pyindex b0793d9ca6..cb4b0da435 100644--- a/jarvis/missions/init.py+++ b/jarvis/missions/init.py@@ -523,7 +523,7 @@ async def bootstrap_missions(daily_usd: float = 50.0,warn_pct: tuple[int, ...] = (50, 80),# When False the BudgetTracker is a no-op (no cost cap, no abort). User- # mandate 2026-05-31 ("überhaupt kein Budget"). Default True keeps the+ # mandate 2026-05-31 ("no budget at all"). Default True keeps the# cap for other installs / the cloud-first €5-VPS profile.budget_enabled: bool = True,# Voice flags (from [phase6.voice])diff --git a/jarvis/missions/isolation/env.py b/jarvis/missions/isolation/env.pyindex 57568e807c..736a228f7d 100644--- a/jarvis/missions/isolation/env.py+++ b/jarvis/missions/isolation/env.py@@ -146,7 +146,7 @@ def build_worker_env(# (hermes-agent) with a degraded PATH that lacks the Node.js dir / System32.# Because this env REPLACES os.environ, the worker inherits that broken PATH# verbatim, the codex `codex.CMD` shim can't find `node`, and EVERY mission- # dies `task_error` in ~25 ms ("Der Worker ist abgebrochen."). Repair the+ # dies `task_error` in ~25 ms ("The worker was aborted."). Repair the# PATH additively and forward the Windows shell vars a `.cmd` shim / `chcp`# need, so a worker runs regardless of how jarvis itself was started.if _worker_path_repair_is_windows():diff --git a/jarvis/missions/isolation/job_object.py b/jarvis/missions/isolation/job_object.pyindex e594fea949..7dc2b524c0 100644--- a/jarvis/missions/isolation/job_object.py+++ b/jarvis/missions/isolation/job_object.py@@ -133,7 +133,7 @@ class _Win32JobObjectImpl:places it in the job (Research-Doc §C lines 168-169)."""if self._closed:- raise RuntimeError("WindowsJobObject ist schon geschlossen")+ raise RuntimeError("WindowsJobObject is already closed")import win32api # type: ignore[import-not-found] # noqa: PLC0415import win32con # type: ignore[import-not-found] # noqa: PLC0415@@ -279,8 +279,8 @@ def WindowsJobObject(name: str | None = None) -> Any: # noqa: ANN401, N802return _Win32JobObjectImpl(name)except ImportError:logger.warning(- "pywin32 fehlt — WindowsJobObject faellt auf No-Op zurueck. "- "Worker-Crash-Reaping ist NICHT garantiert."+ "pywin32 missing — WindowsJobObject falls back to a no-op. "+ "Worker crash reaping is NOT guaranteed.")return _NoOpJobObject(name)# macOS / Linux: real session/process-group reaping (SIGTERM→SIGKILL on close).diff --git a/jarvis/missions/isolation/worktree.py b/jarvis/missions/isolation/worktree.pyindex 7d833367d2..48632a1958 100644--- a/jarvis/missions/isolation/worktree.py+++ b/jarvis/missions/isolation/worktree.py@@ -354,8 +354,8 @@ class WorktreeManager:# All retries failed. Decide based on `force`.if force:logger.warning(- "git worktree remove fehlgeschlagen nach %d Versuchen "- "(letzter exit=%s) — manueller rmtree fuer %s",+ "git worktree remove failed after %d attempts "+ "(last exit=%s) — manual rmtree for %s",len(attempts),last_exc.returncode if last_exc else "?",path,diff --git a/jarvis/missions/kontrollierer/deliverable_paths.py b/jarvis/missions/kontrollierer/deliverable_paths.pyindex 7788c20aee..bf42fbfcc3 100644--- a/jarvis/missions/kontrollierer/deliverable_paths.py+++ b/jarvis/missions/kontrollierer/deliverable_paths.py@@ -18,7 +18,7 @@ multi-layer drift bug class (CLAUDE.md / BUG-008):pre-fix missions and any other archive path;* the user-folder mirror + voice readback(``deliverable.py``) — keeps the user's Downloads and the spoken- "N Dateien gespeichert" count free of scratch.+ "N files saved" count free of scratch.Live forensic 2026-06-21 (mission_019eeb34-bb67): a browser/QA worker launchedfour headless Chrome instances with profiles under@@ -167,7 +167,7 @@ def is_deliverable_path(rel: str, *, managed_files: frozenset[str] = frozenset()# HTML file" and the worker shipped melbourne_guide.html PLUS generate_guide.py# — a Python script that embeds the whole page as a string literal and writes# the sibling .html — PLUS a hero image. The user opened the .py in a browser,-# saw "only code", and wanted that process scratch gone ("nur das Hauptding").+# saw "only code", and wanted that process scratch gone ("just the main thing").# A path-only denylist cannot catch this: generate_guide.py is a perfectly# normal-looking file in artifacts/files/. So this filter inspects content.#diff --git a/jarvis/missions/kontrollierer/orchestrator.py b/jarvis/missions/kontrollierer/orchestrator.pyindex 3bb9807a8b..dd3510df99 100644--- a/jarvis/missions/kontrollierer/orchestrator.py+++ b/jarvis/missions/kontrollierer/orchestrator.py@@ -454,10 +454,10 @@ def _decode_git_quoted_path(raw: str) -> str:"""Decode git's C-style quoted path back to the real on-disk name.With ``core.quotepath=true`` (git's default) non-ASCII bytes in a path- are octal-escaped (``ä`` → ``\\303\\244``) and a handful of control+ are octal-escaped (``ä`` → ``\\303\\244``) and a handful of control # i18n-allowcharacters are backslash-escaped (``\\t``, ``\\n``, ``\\\\``, ``\\"``).A bilingual/German assistant routinely produces umlaut deliverable- names (``Werbungä.html``, ``Lebenslauf-Müller.pdf``); without decoding,+ names (``Werbungä.html``, ``Lebenslauf-Müller.pdf``); without decoding, # i18n-allowthe archive copy loop builds ``worktree / 'Werbung\\303\\244.html'``,``is_file()`` is False, and the deliverable is silently dropped from``artifacts/files/`` (HIGH finding 2026-05-27 hardening audit).@@ -600,8 +600,8 @@ class TaskOutcome:# used to return the generic ERROR, which aggregated to the `task_error`# readback — indistinguishable from a real worker subprocess crash. This# distinct outcome lets the failure-reason mapper surface- # `worktree_setup_failed` ("Konnte keinen Arbeitsbereich anlegen.") so the- # user hears an actionable cause instead of "Der Worker ist abgebrochen."+ # `worktree_setup_failed` ("Could not create a workspace.") so the+ # user hears an actionable cause instead of "The worker was aborted."SETUP_FAILED = "setup_failed"# Live deep-dive 2026-06-07 (mission 019ea1da): a Computer-Use mission whose# final iteration hit the 630s wall-clock cap returned the generic ERROR,@@ -795,7 +795,7 @@ class Kontrollierer:"""Mission body — the tracking wrapper lives in :meth:`run_mission`."""view = await self._manager.mission(mission_id)if view is None:- raise KeyError(f"Mission nicht gefunden: {mission_id}")+ raise KeyError(f"Mission not found: {mission_id}")# Idempotency guard: a SUCCESSFULLY-completed (APPROVED) or explicitly# CANCELLED mission must never be re-run. Both the REST path@@ -1720,12 +1720,12 @@ class Kontrollierer:diff_text: str,log_text: str,) -> str | None:- """Scant Worker-Output gegen Injection + Path-Guard.+ """Scans worker output against injection + path-guard.Returns:- None wenn alles clean. Sonst: kill-reason (z.B. "injection_detected"- oder "path_guard:.env"). In dem Fall publiziert die Methode auch- ein WorkerKilled-Event.+ None if everything is clean. Otherwise: kill-reason (e.g.+ "injection_detected" or "path_guard:.env"). In that case the+ method also publishes a WorkerKilled event."""# 1) Injection-Scanner — high/critical blocks, med/low logged.# The stream log is reduced to worker-AUTHORED text first: the raw@@ -1809,10 +1809,10 @@ class Kontrollierer:worker_id: str,reason: str,) -> None:- """Emittiert WorkerKilled-Event auf Bus + Store."""- # Reason wird auf das Literal-Set in events.WorkerKilled gemappt.- # path_guard:* wird auf "path_guard" reduziert (Voice-Listener-Routing- # unterscheidet path_guard vs injection_detected fuer praezisere TTS).+ """Emits a WorkerKilled event on the bus + store."""+ # Reason is mapped onto the literal set in events.WorkerKilled.+ # path_guard:* is reduced to "path_guard" (voice-listener routing+ # distinguishes path_guard vs injection_detected for more precise TTS).if reason.startswith("path_guard"):mapped: str = "path_guard"elif reason in (@@ -2330,7 +2330,7 @@ class Kontrollierer:return Nonedef _read_stream_log(self, log_dir: Path) -> str:- """Liest stream.jsonl als Text fuer den Critic-Log-Summarizer."""+ """Reads stream.jsonl as text for the critic log summarizer."""stream_path = log_dir / "stream.jsonl"if not stream_path.exists():return ""@@ -2343,7 +2343,7 @@ class Kontrollierer:async def _safe_transition(self, mission_id: str, to_state: MissionState, reason: str) -> None:- """State-Machine-Transition mit Lock + Idempotenz-Tolerance."""+ """State-machine transition with lock + idempotency tolerance."""lock = self._state_locks.setdefault(mission_id, asyncio.Lock())async with lock:try:@@ -2351,7 +2351,7 @@ class Kontrollierer:mission_id, to_state, reason=reason, source_actor="kontrollierer")except IllegalStateTransition:- # bereits im Zielzustand oder weiter — kein Crash+ # already at the target state or further — not a crashlogger.debug("Mission %s: skip transition -> %s (already past)",mission_id,@@ -2471,7 +2471,7 @@ class Kontrollierer:partial_artifacts: list[str] | None = None,) -> None:self._task_answers.pop(mission_id, None) # hygiene: drop captured answers- # Nur transitionieren wenn noch nicht terminal+ # Only transition when not already terminalview = await self._manager.mission(mission_id)if view is None or view.state in (MissionState.APPROVED,@@ -2672,7 +2672,7 @@ class Kontrollierer:def _short_slug(text: str, *, max_len: int = 30) -> str:- """Kurzer kebab-slug fuer Mission-Naming."""+ """Short kebab-slug for mission naming."""import reout = re.sub(r"[^a-z0-9]+", "-", text.lower()).strip("-")@@ -2688,9 +2688,9 @@ _SECURITY_KEYWORDS = (def _detect_security_tag(prompt: str) -> bool:- """True wenn der Step-Prompt sicherheitsrelevante Keywords enthaelt.+ """True when the step prompt contains security-relevant keywords.- Triggert Critic-Tier-Eskalation Sonnet -> Opus auch in iter 0.+ Triggers critic-tier escalation Sonnet -> Opus even in iter 0."""lower = prompt.lower()return any(kw in lower for kw in _SECURITY_KEYWORDS)diff --git a/jarvis/missions/manager.py b/jarvis/missions/manager.pyindex 7baf01530e..2e4aeab67c 100644--- a/jarvis/missions/manager.py+++ b/jarvis/missions/manager.py@@ -1,14 +1,14 @@-"""MissionManager — orchestriert Lebenszyklus einer Mission.+"""MissionManager — orchestrates the lifecycle of a mission.-Phase-1-Skeleton: Dispatch + State-Transitions + Recovery-Wiring. **KEINE-Worker-Logik** (kommt in Phase 2), **KEIN Critic** (Phase 3). Diese Skeleton--Schicht garantiert dass alle nachfolgenden Phasen einen sauberen Event-Stream-+ State-Machine + Recovery-Pfad vorfinden.+Phase-1 skeleton: dispatch + state transitions + recovery wiring. **NO+worker logic** (comes in Phase 2), **NO critic** (Phase 3). This skeleton+layer guarantees that all subsequent phases find a clean event stream++ state machine + recovery path.-Persist-vor-Publish-Disziplin:-- `dispatch()` macht erst `upsert_mission(PENDING)`, dann `append_and_publish(MissionDispatched)`.-- `transition_state()` macht erst `append_and_publish(MissionStateChanged)`, dann `upsert_mission(to_state)`.- Begruendung: bei Crash zwischen Publish und Header-Update findet Recovery beim Restart noch den alten Header-State und kann das Replay aus events_since rekonstruieren — der State-Header ist hilfreich aber nicht authoritativ; das Event-Log ist die Source of Truth.+Persist-before-publish discipline:+- `dispatch()` first does `upsert_mission(PENDING)`, then `append_and_publish(MissionDispatched)`.+- `transition_state()` first does `append_and_publish(MissionStateChanged)`, then `upsert_mission(to_state)`.+ Rationale: on a crash between publish and header update, recovery on restart still finds the old header state and can reconstruct the replay from events_since — the state header is helpful but not authoritative; the event log is the source of truth."""from __future__ import annotations@@ -44,7 +44,7 @@ SourceActor = Literal[@dataclass(frozen=True)class MissionView:- """Read-only Snapshot eines Mission-Records."""+ """Read-only snapshot of a mission record."""mission_id: strprompt: str@@ -52,10 +52,10 @@ class MissionView:class MissionManager:- """Lebenszyklus + State-Transitions fuer Missions.+ """Lifecycle + state transitions for missions.- Owns einen MissionBus + MissionEventStore. Recovery laeuft beim `start()`.- Kein globaler Singleton — immer via DI instanziert (siehe ADR-0009 D-Liste).+ Owns a MissionBus + MissionEventStore. Recovery runs on `start()`.+ No global singleton — always instantiated via DI (see ADR-0009 D-list)."""def __init__(self, db_path: Path, *, bus: MissionBus | None = None) -> None:@@ -147,8 +147,8 @@ class MissionManager:language=language,),)- # Header zuerst — sonst koennen Subscriber das MissionDispatched-Event- # auf eine nicht-existente Mission im Store sehen.+ # Header first — otherwise subscribers could see the MissionDispatched+ # event for a mission that doesn't yet exist in the store.await self._store.upsert_mission(mission_id=mission_id,prompt=prompt,@@ -167,20 +167,20 @@ class MissionManager:reason: str,source_actor: SourceActor = "system",) -> EventEnvelope:- """Validiere State-Uebergang, persist + publish MissionStateChanged.+ """Validate the state transition, persist + publish MissionStateChanged.- Hebt `IllegalStateTransition` wenn der Uebergang nicht in- `ALLOWED_TRANSITIONS` steht. Hebt `KeyError` wenn die Mission- nicht existiert. Aktualisiert auch den Mission-Header.+ Raises `IllegalStateTransition` if the transition is not in+ `ALLOWED_TRANSITIONS`. Raises `KeyError` if the mission+ doesn't exist. Also updates the mission header."""self._ensure_started()lock = self._state_locks.setdefault(mission_id, asyncio.Lock())async with lock:current_str = await self._store.get_mission_state(mission_id)if current_str is None:- raise KeyError(f"Mission nicht gefunden: {mission_id}")+ raise KeyError(f"Mission not found: {mission_id}")from_state = MissionState(current_str)- # validiert oder raises IllegalStateTransition+ # validates or raises IllegalStateTransitiontransition(from_state, to_state)prompt = await self._get_prompt(mission_id) or ""@@ -195,7 +195,7 @@ class MissionManager:reason=reason,),)- # Event zuerst (authoritative log), Header danach (snapshot fuer fast lookup)+ # Event first (authoritative log), header after (snapshot for fast lookup)await self._store.append_and_publish(env)await self._store.upsert_mission(mission_id=mission_id,@@ -207,7 +207,7 @@ class MissionManager:return envasync def mission(self, mission_id: str) -> MissionView | None:- """Snapshot eines Mission-Headers oder None wenn nicht vorhanden."""+ """Snapshot of a mission header, or None if not present."""self._ensure_started()state_str = await self._store.get_mission_state(mission_id)if state_str is None:diff --git a/jarvis/missions/safety/destructive_confirm.py b/jarvis/missions/safety/destructive_confirm.pyindex 7d163f2be6..5b6d99c244 100644--- a/jarvis/missions/safety/destructive_confirm.py+++ b/jarvis/missions/safety/destructive_confirm.py@@ -27,7 +27,7 @@ class DestructiveDetection(BaseModel):pattern_id: strmatched_text: str- target_hint: str # vom Pattern extrahierter "was wird zerstoert"-Hint+ target_hint: str # "what gets destroyed" hint extracted from the pattern# (pattern_id, regex, target_extraction_group)@@ -98,20 +98,20 @@ DESTRUCTIVE_PATTERNS: Final[list[tuple[str, re.Pattern[str], str]]] = [),("delete_all_files",- # "alle Files loeschen" / "delete all files" — Worte-basiert (DE+EN)+ # "alle Files loeschen" / "delete all files" — word-based (DE+EN) # i18n-allowre.compile(- r"\b(?:delete|remove|loesche|loeschen|loesch)\s+(?:all|alle|gesamten?)\s+"- r"(?P<target>(?:files?|dateien?|ordner|directories?|verzeichnisse?))",+ r"\b(?:delete|remove|loesche|loeschen|loesch)\s+(?:all|alle|gesamten?)\s+" # i18n-allow+ r"(?P<target>(?:files?|dateien?|ordner|directories?|verzeichnisse?))", # i18n-allowre.IGNORECASE,),"target",),("drop_database_de",- # deutsche Variante: "datenbank loeschen", "tabelle dropp(en)"+ # German variant: "datenbank loeschen", "tabelle dropp(en)"re.compile(- r"\b(?:datenbank|tabelle|schema)\s+(?P<target>\w+)\s+"- r"(?:loeschen|droppen|loesche)",+ r"\b(?:datenbank|tabelle|schema)\s+(?P<target>\w+)\s+" # i18n-allow+ r"(?:loeschen|droppen|loesche)", # i18n-allowre.IGNORECASE,),"target",diff --git a/jarvis/plugins/brain/_openai_base.py b/jarvis/plugins/brain/_openai_base.pyindex a49f87ceaf..9fa4f8f42d 100644--- a/jarvis/plugins/brain/_openai_base.py+++ b/jarvis/plugins/brain/_openai_base.py@@ -1,9 +1,9 @@-"""Gemeinsame Logik für OpenAI-kompatible APIs (openai / openrouter / grok).+"""Shared logic for OpenAI-compatible APIs (openai / openrouter / grok).-Alle drei nutzen das Chat-Completions-Format. Unterschiede:-- Base-URL (api.openai.com / openrouter.ai / api.x.ai)-- Model-Namen-Namensraum-- Default-Headers (OpenRouter will X-Title, HTTP-Referer)+All three use the Chat-Completions format. Differences:+- Base URL (api.openai.com / openrouter.ai / api.x.ai)+- Model-name namespace+- Default headers (OpenRouter wants X-Title, HTTP-Referer)"""from __future__ import annotations@@ -30,28 +30,28 @@ CLIENT_TIMEOUT = httpx.Timeout(connect=5.0, read=30.0, write=30.0, pool=30.0)def _stream_options_supported() -> bool:- """One-shot Detection: kennt das installierte openai-SDK ``stream_options``?+ """One-shot detection: does the installed openai SDK know ``stream_options``?- `stream_options` wurde in openai>=1.30 (Juni 2024) eingefuehrt — aeltere- Versionen werfen ``TypeError: got unexpected keyword argument`` direkt- beim Aufruf. Wir pruefen die Signatur einmalig zur Modul-Ladezeit und- cachen das Ergebnis. Bei zukuenftigen API-Aenderungen ist der Re-Try-Pfad- in ``run_openai_chat`` der Notanker.+ `stream_options` was introduced in openai>=1.30 (June 2024) — older+ versions raise ``TypeError: got unexpected keyword argument`` directly+ on the call. We check the signature once at module-load time and cache+ the result. For future API changes, the re-try path in+ ``run_openai_chat`` is the safety net."""try:from openai.resources.chat.completions import AsyncCompletionssig = inspect.signature(AsyncCompletions.create)return "stream_options" in sig.parameters- except Exception: # noqa: BLE001 — Detection darf den Import nicht killen+ except Exception: # noqa: BLE001 — detection must never kill the importreturn False_STREAM_OPTIONS_SUPPORTED = _stream_options_supported()if not _STREAM_OPTIONS_SUPPORTED:log.warning(- "openai-SDK kennt 'stream_options' nicht — vermutlich openai<1.30. "- "Provider laufen ohne Inline-Usage-Tracking. Empfehlung: pip install -U openai."+ "openai SDK does not know 'stream_options' — likely openai<1.30. "+ "Provider runs without inline usage tracking. Recommendation: pip install -U openai.")@@ -61,13 +61,13 @@ def _to_openai_messages(*,supports_vision: bool = True,) -> list[dict[str, Any]]:- """BrainMessages → OpenAI-Chat-Completions-Array.+ """BrainMessages → OpenAI Chat-Completions array.- Multimodal: `BrainMessage.images` wird für user-Messages als Data-URI- im `image_url`-Content-Block enkodiert. Wenn der Ziel-Provider kein- Vision-Support hat (`supports_vision=False`), werden images verworfen- und einmalig pro Call geloggt.- Backwards-Compat: Ohne images bleibt der Content ein plain String.+ Multimodal: `BrainMessage.images` is encoded as a Data-URI in the+ `image_url` content block for user messages. If the target provider has+ no vision support (`supports_vision=False`), images are dropped and+ logged once per call.+ Backwards-compat: without images, the content stays a plain string."""out: list[dict[str, Any]] = []system_parts: list[str] = []@@ -93,7 +93,7 @@ def _to_openai_messages(continueif m.role == "assistant" and isinstance(m.content, list):- # Assistant mit Tool-Calls+ # Assistant with tool callstext_parts: list[str] = []tool_calls: list[dict[str, Any]] = []for block in m.content:@@ -116,8 +116,8 @@ def _to_openai_messages(out.append(entry)continue- # user | assistant (mit string content)- # `getattr` für Backwards-Compat (Protocol pre-Wave-1-B1 hat kein images).+ # user | assistant (with string content)+ # `getattr` for backwards-compat (Protocol pre-Wave-1-B1 had no images).images = getattr(m, "images", ()) or ()has_images = m.role == "user" and bool(images)if has_images and supports_vision:@@ -142,11 +142,11 @@ def _to_openai_messages(if has_images and not supports_vision:if not vision_drop_warned:log.warning(- "Provider ohne Vision-Support — %d Image(s) werden verworfen.",+ "Provider without vision support — dropping %d image(s).",len(images),)vision_drop_warned = True- # Fall through zum plain-text-Pfad (images gedroppt).+ # Fall through to the plain-text path (images dropped).text_content = (m.content@@ -234,10 +234,10 @@ async def stream_complete(extra_body: dict[str, Any] | None = None,supports_vision: bool = True,) -> AsyncIterator[BrainDelta]:- """Streaming-Run gegen OpenAI-kompatible Chat-Completions.+ """Streaming run against OpenAI-compatible Chat-Completions.- `supports_vision` wird an den Message-Builder durchgereicht — bei `False`- werden `BrainMessage.images` verworfen + eine WARN geloggt.+ `supports_vision` is passed through to the message builder — when `False`,+ `BrainMessage.images` are dropped and a WARN is logged."""messages = _to_openai_messages(req.messages, req.system, supports_vision=supports_vision)kwargs: dict[str, Any] = {@@ -247,10 +247,10 @@ async def stream_complete("temperature": req.temperature,"stream": True,}- # stream_options gibts erst seit openai>=1.30. Auf alten SDKs (z.B. 1.10)- # wuerde der unconditional-Aufruf einen TypeError werfen und die Plugin-- # Kette mit "AsyncCompletions.create() got an unexpected keyword argument"- # crashen — User hoert dann statt einer Antwort die "unerreichbar"-Diag.+ # stream_options only exists since openai>=1.30. On old SDKs (e.g. 1.10)+ # the unconditional call would raise a TypeError and crash the plugin+ # chain with "AsyncCompletions.create() got an unexpected keyword argument"+ # — the user then hears the "unreachable" diagnostic instead of an answer.if _STREAM_OPTIONS_SUPPORTED:kwargs["stream_options"] = {"include_usage": True}# Sanitize tool names to the OpenAI/Anthropic rule and keep a reverse map so@@ -263,20 +263,20 @@ async def stream_complete(if extra_body:kwargs.update(extra_body)- # Akkumulator für Tool-Call-Partials (OpenAI streamt pro tool_call index)+ # Accumulator for tool-call partials (OpenAI streams per tool_call index)tool_buffer: dict[int, dict[str, Any]] = {}try:stream = await client.chat.completions.create(**kwargs)except TypeError as exc:- # Belt-and-Suspenders: falls die Detection oben aus irgendeinem Grund- # falsch lag (gemockte Tests, monkey-patched SDK, exotische Forks),- # versuchen wir's nochmal ohne stream_options. Erspart einen harten- # Fail wenn der Live-API einen unerwarteten Kwarg ablehnt.+ # Belt-and-suspenders: if the detection above was wrong for whatever+ # reason (mocked tests, monkey-patched SDK, exotic forks), retry once+ # without stream_options. Saves a hard fail when the live API rejects+ # an unexpected kwarg.if "stream_options" not in kwargs or "stream_options" not in str(exc):raiselog.warning(- "openai-SDK lehnte 'stream_options' ab (%s) — Re-Try ohne Kwarg.",+ "openai SDK rejected 'stream_options' (%s) — retrying without the kwarg.",exc,)kwargs.pop("stream_options", None)@@ -308,7 +308,7 @@ async def stream_complete(finish = getattr(choice, "finish_reason", None)if finish:- # Tool-Calls abschließen wenn vorhanden+ # Finalize tool calls if presentfor idx, buf in sorted(tool_buffer.items()):try:parsed = json.loads(buf["arguments"]) if buf["arguments"] else {}@@ -322,7 +322,7 @@ async def stream_complete(tool_buffer.clear()yield BrainDelta(finish_reason=finish)- # Usage-Info (OpenAI liefert das im letzten Chunk)+ # Usage info (OpenAI delivers this in the last chunk)usage = getattr(chunk, "usage", None)if usage is not None:yield BrainDelta(usage={diff --git a/jarvis/plugins/brain/claude_api.py b/jarvis/plugins/brain/claude_api.pyindex 5c5ad3ccb3..930b4e38ff 100644--- a/jarvis/plugins/brain/claude_api.py+++ b/jarvis/plugins/brain/claude_api.py@@ -1,4 +1,4 @@-"""Claude via direkter Anthropic-API (Standard-API-Key).+"""Claude via the direct Anthropic API (standard API key).Keyring/ENV: `anthropic_api_key` / `ANTHROPIC_API_KEY`."""@@ -32,8 +32,8 @@ class ClaudeAPIBrain:ep = cfg.resolve_provider_endpoint("claude-api")if not ep.credential:raise RuntimeError(- "Kein Anthropic-API-Key gefunden. Bitte via Wizard setzen oder "- "ANTHROPIC_API_KEY in ENV."+ "No Anthropic API key found. Please set one via the wizard or "+ "ANTHROPIC_API_KEY in the environment.")from anthropic import AsyncAnthropic# max_retries=0 → BrainManager-Fallback greift schneller bei 429@@ -49,6 +49,6 @@ class ClaudeAPIBrain:yield deltadef estimate_cost(self, req: BrainRequest) -> float:- # Grobe Claude-Opus-Schätzung: $15/M-in + $75/M-out+ # Rough Claude-Opus estimate: $15/M-in + $75/M-outin_tokens = sum(len(str(m.content)) for m in req.messages) // 4return (in_tokens * 15 + req.max_tokens * 75) / 1_000_000diff --git a/jarvis/plugins/brain/gemini.py b/jarvis/plugins/brain/gemini.pyindex 4715b47728..8336b0beea 100644--- a/jarvis/plugins/brain/gemini.py+++ b/jarvis/plugins/brain/gemini.py@@ -1,6 +1,6 @@"""Google Gemini Brain (via google-genai async SDK).-Gemini hat sein eigenes functionCall-Format. Wir normalisieren auf+Gemini has its own functionCall format. We normalize to`BrainDelta.tool_call = {id, name, input}`."""from __future__ import annotations@@ -20,13 +20,13 @@ log = logging.getLogger(__name__)DEFAULT_MODEL = "gemini-3-flash"-# Latenz-Sprint-2: ENV-Switch fuer Context-Cache. BrainManager setzt diesen-# wenn ``[performance].gemini_context_cache = true``. Im Cache landen-# System-Prompt + Tools; Vision-Frames bleiben non-cached (variabel pro Turn).+# Latency-Sprint-2: ENV switch for the context cache. BrainManager sets this+# when ``[performance].gemini_context_cache = true``. The cache holds the+# system prompt + tools; vision frames stay non-cached (they vary per turn)._ENV_CONTEXT_CACHE = "JARVIS_GEMINI_CONTEXT_CACHE"-# Cache-Mindestgroesse: Gemini-Caches haben Token-Floor (>= ~4096 Tokens je-# nach Modell). Bei kleineren Prefixes lehnt die API ab oder der Cache lohnt-# sich nicht — dann skippen wir und fallen auf den Direct-Pfad.+# Minimum cache size: Gemini caches have a token floor (>= ~4096 tokens+# depending on the model). For smaller prefixes the API either rejects it or+# the cache isn't worth it — then we skip it and fall back to the direct path._MIN_CACHE_TOKENS = 4096@@ -58,16 +58,16 @@ def _is_stale_context_cache_error(exc: Exception) -> bool:def _to_gemini_contents(messages: tuple[BrainMessage, ...]) -> list[dict[str, Any]]:- """BrainMessages → Gemini-Contents-Array. Role mapping: assistant→model.+ """BrainMessages → Gemini contents array. Role mapping: assistant→model.- Multimodal: `BrainMessage.images` werden als `inline_data`-Parts- angehängt (`{"inline_data": {"mime_type": ..., "data": ...}}`) — nur- bei user-Messages, da Gemini model-role-images nicht als Input akzeptiert.+ Multimodal: `BrainMessage.images` are appended as `inline_data` parts+ (`{"inline_data": {"mime_type": ..., "data": ...}}`) — only for user+ messages, since Gemini doesn't accept model-role images as input."""contents: list[dict[str, Any]] = []for m in messages:if m.role == "system":- continue # system geht via system_instruction+ continue # system goes via system_instructionrole = "user" if m.role in ("user", "tool") else "model"if m.role == "tool":# FunctionResponse@@ -83,9 +83,9 @@ def _to_gemini_contents(messages: tuple[BrainMessage, ...]) -> list[dict[str, Ancontinuetext = m.content if isinstance(m.content, str) else json.dumps(m.content, default=str)- # Multimodal nur auf user-Role sinnvoll — images werden an die Text-Part- # angehängt. Wenn text leer ist, lassen wir den Text-Part weg.- # `getattr` für Backwards-Compat (Protocol pre-Wave-1-B1 hat kein images).+ # Multimodal only makes sense on the user role — images are appended to+ # the text part. If text is empty, we leave the text part out.+ # `getattr` for backwards-compat (Protocol pre-Wave-1-B1 had no images).images = getattr(m, "images", ()) or ()parts: list[dict[str, Any]] = []if text:@@ -99,14 +99,14 @@ def _to_gemini_contents(messages: tuple[BrainMessage, ...]) -> list[dict[str, An}})if not parts:- # Defensive: ein Gemini-Content darf nicht leer sein.+ # Defensive: a Gemini content must not be empty.parts.append({"text": ""})contents.append({"role": role, "parts": parts})return contents-# OpenAI-spezifische JSON-Schema-Felder die Gemini's `Tool.functionDeclarations`-# Pydantic-Validator NICHT akzeptiert. Phase 7.3 Self-Mod-Tools setzen+# OpenAI-specific JSON-schema fields that Gemini's `Tool.functionDeclarations`+# Pydantic validator does NOT accept. Phase 7.3 self-mod tools set# `strict=True` + `input_examples=[...]` an die Schema-Wurzel — diese Felder# fliegen sonst mit "11 validation errors for GenerateContentConfig" durch# (Bug #API-1, 2026-04-29).@@ -166,14 +166,14 @@ def _convert_exclusive_bounds(schema: dict[str, Any]) -> dict[str, Any]:def _sanitize_for_gemini(schema: dict[str, Any]) -> dict[str, Any]:- """Entfernt OpenAI-spezifische Felder rekursiv aus einem JSON-Schema.+ """Recursively removes OpenAI-specific fields from a JSON schema.- Gemini's google-genai SDK validiert Tool.functionDeclarations.parameters- via Pydantic mit `extra="forbid"`. Felder wie `strict`/`input_examples`- sind OpenAI-Tool-Use-Konventionen und nicht im Gemini-Schema-Subset- erlaubt. Statt einen Tool-Call ohne Tools zu liefern, strippen wir die- Felder out — die Tools selbst funktionieren unveraendert, nur die- OpenAI-spezifischen Hints sind weg.+ Gemini's google-genai SDK validates Tool.functionDeclarations.parameters+ via Pydantic with `extra="forbid"`. Fields like `strict`/`input_examples`+ are OpenAI tool-use conventions and not allowed in Gemini's schema+ subset. Instead of delivering a tool call without tools, we strip those+ fields out — the tools themselves keep working unchanged, only the+ OpenAI-specific hints are gone.Exclusive numeric bounds (``exclusiveMinimum``/``exclusiveMaximum`` fromPydantic ``Field(gt=...)``/``Field(lt=...)``) are first converted to the@@ -303,15 +303,15 @@ class GeminiBrain:) -> None:self._model = model or DEFAULT_MODELself._client: Any = None- # Latenz-Sprint-1: Thinking-Budget steuert wie viel "extended- # thinking" Gemini 3.x macht. ``None`` = SDK-Default (Auto, hoeher- # Latenz). ``0`` = aus, ``-1`` = dynamic, ``>0`` = fester Cap.+ # Latency-Sprint-1: thinking budget controls how much "extended+ # thinking" Gemini 3.x does. ``None`` = SDK default (auto, higher+ # latency). ``0`` = off, ``-1`` = dynamic, ``>0`` = fixed cap.self._thinking_budget = thinking_budget- # Latenz-Sprint-2: Context-Cache-Name (lazy erstellt beim ersten Call- # mit System+Tools). Key: (system_hash, tools_hash) → cache_name.- # Nur ein Eintrag pro Instanz, weil System+Tools bei einer laufenden- # Voice-Session konstant sind. Bei Aenderung (z.B. Tool-Reload) wird- # der Cache via ``invalidate_cache()`` weggeworfen.+ # Latency-Sprint-2: context-cache name (lazily created on the first+ # call with system+tools). Key: (system_hash, tools_hash) → cache_name.+ # Only one entry per instance, because system+tools are constant for+ # a running voice session. On change (e.g. a tool reload), the cache+ # is discarded via ``invalidate_cache()``.self._cached_content_name: str | None = Noneself._cache_signature: tuple[str, str] | None = None@@ -320,7 +320,7 @@ class GeminiBrain:ep = cfg.resolve_provider_endpoint("gemini")if not ep.credential:raise RuntimeError(- "Kein Gemini-API-Key gefunden. Setze GEMINI_API_KEY oder "+ "No Gemini API key found. Set GEMINI_API_KEY or ""GOOGLE_AIStudio_API_KEY in .env / Credential Manager.")from google import genai@@ -335,17 +335,17 @@ class GeminiBrain:async def _ensure_cache(self, system_text: str, tools_payload: list[dict[str, Any]] | None,) -> str | None:- """Latenz-Sprint-2: Lazy-Init des Context-Caches.+ """Latency-Sprint-2: lazy init of the context cache.- Erstellt einen Gemini-Cache (System+Tools) beim ersten Call und- gibt den Cache-Namen zurueck — nachfolgende Calls koennen via- ``cached_content`` referenzieren. Bei zu kleinem Prefix oder- API-Fehler liefert ``None``, dann faellt der Caller auf den- Direct-Pfad zurueck (Brain bleibt funktional).+ Creates a Gemini cache (system+tools) on the first call and returns+ the cache name — subsequent calls can reference it via+ ``cached_content``. On too-small a prefix or an API error, returns+ ``None``, and the caller falls back to the direct path (brain stays+ functional)."""- # Cache-Signatur: hashen + cachen, damit ein Tool-Reload die Lazy-Init- # neu triggert. Hash auf den serialisierten Inhalt — billig und- # ausreichend fuer Identitaetspruefung.+ # Cache signature: hash + cache, so a tool reload re-triggers the+ # lazy init. Hash on the serialized content — cheap and sufficient+ # for an identity check.sig = (str(hash(system_text)),str(hash(json.dumps(tools_payload, sort_keys=True, default=str))) if tools_payload else "",@@ -353,11 +353,11 @@ class GeminiBrain:if self._cache_signature == sig and self._cached_content_name:return self._cached_content_name- # Mindestgroesse abschaetzen (Heuristik: 1 Token ~ 4 Chars).+ # Estimate the minimum size (heuristic: 1 token ~ 4 chars).approx_tokens = (len(system_text) + len(json.dumps(tools_payload or []))) // 4if approx_tokens < _MIN_CACHE_TOKENS:log.debug(- "Gemini-Cache geskippt (Prefix ~%d Tokens < %d Mindestgroesse)",+ "Gemini cache skipped (prefix ~%d tokens < %d minimum size)",approx_tokens, _MIN_CACHE_TOKENS,)return None@@ -374,11 +374,11 @@ class GeminiBrain:)self._cached_content_name = getattr(cache, "name", None)self._cache_signature = sig- log.info("Gemini Context-Cache erstellt: %s (Tokens ~%d)",+ log.info("Gemini context cache created: %s (tokens ~%d)",self._cached_content_name, approx_tokens)return self._cached_content_nameexcept Exception as exc: # noqa: BLE001- log.warning("Gemini Cache-Create fehlgeschlagen, fallback Direct: %s", exc)+ log.warning("Gemini cache create failed, falling back to direct: %s", exc)return Nonedef invalidate_cache(self) -> None:@@ -420,18 +420,18 @@ class GeminiBrain:# there are no tools). See _build_gemini_tool_declarations.tool_name_reverse = {safe: original for original, safe in _tool_name_map.items()}- # Latenz-Sprint-2: Wenn Caching aktiviert ist, versuche System+Tools- # in einen Cache-Eintrag zu legen. Bei Erfolg: ``cached_content``- # statt ``system_instruction``+``tools`` setzen (Gemini erlaubt- # nicht beides gleichzeitig). Bei Skip/Fail: Direct-Pfad.+ # Latency-Sprint-2: if caching is enabled, try to put system+tools+ # into a cache entry. On success, set ``cached_content`` instead of+ # ``system_instruction``+``tools`` (Gemini doesn't allow both at+ # once). On skip/fail: direct path.cache_name: str | None = Noneif os.environ.get(_ENV_CONTEXT_CACHE) == "1":cache_name = await self._ensure_cache(system_text, tools_payload)if cache_name:config_dict["cached_content"] = cache_name- # System-Instruction + Tools liegen jetzt im Cache — NICHT erneut- # senden, sonst lehnt Gemini ab.+ # System instruction + tools now live in the cache — do NOT send+ # them again, or Gemini rejects the request.else:if system_text:config_dict["system_instruction"] = system_text@@ -457,12 +457,12 @@ class GeminiBrain:except Exception: # noqa: BLE001 — never break the brain call over an SDK shape changelog.debug("could not disable Gemini automatic_function_calling", exc_info=True)- # Latenz-Sprint-1: Thinking-Budget. Nur wenn explizit gesetzt — sonst- # ueberlassen wir die Wahl dem SDK-Default (vorheriges Verhalten).- # ``ThinkingConfig`` ist ab google-genai >= 0.7 verfuegbar; aelteren- # SDK-Versionen haben das Feld nicht und werfen AttributeError. In- # dem Fall ignorieren wir den Wert, statt den ganzen Brain-Call zu- # killen (Best-Effort-Optimierung).+ # Latency-Sprint-1: thinking budget. Only when explicitly set —+ # otherwise we leave the choice to the SDK default (previous+ # behavior). ``ThinkingConfig`` is available from google-genai >= 0.7;+ # older SDK versions don't have the field and raise AttributeError. In+ # that case we ignore the value instead of killing the whole brain+ # call (best-effort optimization).if self._thinking_budget is not None:try:from google.genai import types as _genai_types@@ -483,7 +483,7 @@ class GeminiBrain:# ║ ║# ║ Log trace per failing turn (data/jarvis_desktop.log): ║# ║ T+0.0 → Brain ... ║- # ║ T+0.7 Brain gemini(gemini-3-flash-preview) fehlgeschlagen║+ # ║ T+0.7 Brain gemini(gemini-3-flash-preview) failed ║# ║ 403 Forbidden. "CachedContent not found ║# ║ (or permission denied)" ║# ║ T+40.0 Brain-Stream timed out after 40.0s — back to ║@@ -512,7 +512,7 @@ class GeminiBrain:# ║ in time. The pipeline's hard cap (``brain_timeout_s = ║# ║ 40.0`` in ``speech/pipeline.py``) trips and returns to ║# ║ LISTENING with an empty response — which then hits the ║- # ║ "Filler-/ACK-Response unterdrueckt" branch in ║+ # ║ "filler/ack response suppressed" branch in ║# ║ ``_handle_utterance`` and silently `return True`s ║# ║ without calling ``_speak``. ║# ║ * That is the silent THINKING → LISTENING transition the ║diff --git a/jarvis/plugins/brain/openai.py b/jarvis/plugins/brain/openai.pyindex 856ac75ad8..b2858259c9 100644--- a/jarvis/plugins/brain/openai.py+++ b/jarvis/plugins/brain/openai.py@@ -1,4 +1,4 @@-"""OpenAI GPT-Brain (direct API)."""+"""OpenAI GPT Brain (direct API)."""from __future__ import annotationsfrom collections.abc import AsyncIterator@@ -26,7 +26,7 @@ class OpenAIBrain:if self._client is None:ep = cfg.resolve_provider_endpoint("openai")if not ep.credential:- raise RuntimeError("Kein OpenAI-API-Key gefunden (openai_api_key / OPENAI_API_KEY).")+ raise RuntimeError("No OpenAI API key found (openai_api_key / OPENAI_API_KEY).")from openai import AsyncOpenAIkwargs: dict[str, Any] = {"api_key": ep.credential, "timeout": CLIENT_TIMEOUT}if ep.base_url:diff --git a/jarvis/plugins/brain/openrouter.py b/jarvis/plugins/brain/openrouter.pyindex de03d19c39..f57f885b2f 100644--- a/jarvis/plugins/brain/openrouter.py+++ b/jarvis/plugins/brain/openrouter.py@@ -58,7 +58,7 @@ class OpenRouterBrain:if self._client is None:ep = cfg.resolve_provider_endpoint("openrouter", vendor_default_base_url=BASE_URL)if not ep.credential:- raise RuntimeError("Kein OpenRouter-API-Key gefunden (openrouter_api_key).")+ raise RuntimeError("No OpenRouter API key found (openrouter_api_key).")from openai import AsyncOpenAIself._client = AsyncOpenAI(api_key=ep.credential,diff --git a/jarvis/plugins/harness/computer_use.py b/jarvis/plugins/harness/computer_use.pyindex 7c223208c6..fb3c678f26 100644--- a/jarvis/plugins/harness/computer_use.py+++ b/jarvis/plugins/harness/computer_use.py@@ -75,11 +75,12 @@ def _resolve_run_cu_loop():class ComputerUseHarness:- """Plugin-Eintrag fuer `entry_points."jarvis.harness".screenshot`.+ """Plugin entry for `entry_points."jarvis.harness".screenshot`.- Die App muss vor dem ersten Dispatch einmal+ The app must call`jarvis.harness.computer_use_context.set_computer_use_context(...)`- aufrufen. Ohne Kontext wirft `invoke()` einen klaren Fehler.+ once before the first dispatch. Without a context, `invoke()` raises a+ clear error."""name: str = "screenshot"@@ -87,14 +88,14 @@ class ComputerUseHarness:supports_versions: str = ">=0.1"def __init__(self, context: ComputerUseContext | None = None) -> None:- # Der Constructor kann mit explicit Context aufgerufen werden (fuer- # Tests). Ohne Context faellt `invoke()` auf den globalen zurueck.+ # The constructor can be called with an explicit context (for+ # tests). Without a context, `invoke()` falls back to the global one.self._explicit_context = contextself._cancelled = False- self._active_token = None # gesetzt waehrend invoke() laeuft+ self._active_token = None # set while invoke() is runningasync def health(self) -> bool:- """True wenn ein Context gesetzt ist und alle Kern-Deps existieren."""+ """True when a context is set and all core deps exist."""try:ctx = self._explicit_context or get_computer_use_context()except RuntimeError:@@ -106,12 +107,12 @@ class ComputerUseHarness:])async def invoke(self, task: HarnessTask) -> AsyncIterator[HarnessResult]:- """Delegiert an `run_cu_loop` innerhalb eines eigenen CancelScope.+ """Delegates to `run_cu_loop` inside its own CancelScope.- Der Scope registriert einen dedizierten Token beim KillSwitch. Der- KillSwitch cancelt IHN bei `KillRequested`, und der Loop propagiert- das bis zum naechsten `is_cancelled()`-Check. Ohne diesen Scope- wuerde der Kill-Switch den CU-Loop nicht erreichen (ADR-0004).+ The scope registers a dedicated token with the KillSwitch. The+ KillSwitch cancels IT on `KillRequested`, and the loop propagates+ that until the next `is_cancelled()` check. Without this scope, the+ kill switch would never reach the CU loop (ADR-0004)."""ctx = self._explicit_context or get_computer_use_context()timeout_s = max(0.001, float(task.timeout_s))@@ -173,11 +174,11 @@ class ComputerUseHarness:unregister_active_cu_token(token)async def cancel(self) -> None:- """Bricht den laufenden Invoke ab.+ """Aborts the running invoke.- Cancelt den aktiven Token — der Loop reagiert beim naechsten- `_is_cancelled()`-Check und yieldet einen finalen Chunk. Wenn- `invoke()` nicht laeuft, ist der Call ein No-Op.+ Cancels the active token — the loop reacts on the next+ `_is_cancelled()` check and yields a final chunk. If `invoke()` isn't+ running, the call is a no-op."""if self._active_token is not None:self._active_token.cancel("harness_direct_cancel")diff --git a/jarvis/plugins/harness/mcp_remote.py b/jarvis/plugins/harness/mcp_remote.pyindex 034e6bfc76..0e5efa5340 100644--- a/jarvis/plugins/harness/mcp_remote.py+++ b/jarvis/plugins/harness/mcp_remote.py@@ -1,12 +1,11 @@-"""MCP-Remote-Harness: wrappt externe MCP-Server als Harness.+"""MCP-remote harness: wraps an external MCP server as a harness.-Im Gegensatz zu den CLI-Harnesses (openclaw, codex) läuft das hier-als In-Process MCP-Client gegen einen Remote- oder lokalen Stdio-Server.-Der Prompt wird als MCP-Tool-Call (Convention: `dispatch(prompt)`) an den-ersten zur-Verfügung-stehenden Server gesendet.+Unlike the CLI harnesses (openclaw, codex), this one runs as an in-process+MCP client against a remote or local stdio server. The prompt is sent as an+MCP tool call (convention: `dispatch(prompt)`) to the first available server.-Konfiguration: `task.env["MCP_SERVER_NAME"]` wählt einen konkreten Server-aus der Bootstrap-Liste; default ist `filesystem-mcp`.+Configuration: `task.env["MCP_SERVER_NAME"]` picks a specific server from the+bootstrap list; the default is `filesystem-mcp`."""from __future__ import annotations@@ -21,7 +20,7 @@ log = logging.getLogger(__name__)class MCPRemoteHarness:- """Nutzt einen MCP-Server zum Ausführen von Tool-Calls via Harness-Interface."""+ """Uses an MCP server to run tool calls via the harness interface."""name: str = "mcp-remote"version: str = "0.1"@@ -32,9 +31,9 @@ class MCPRemoteHarness:self._current_server: str | None = Noneasync def health(self) -> bool:- # Ein MCP-Remote-Harness ist "healthy" wenn mindestens ein- # Bootstrap-Server gepingt werden kann. Da das Pinging Zeit- # kostet, returnen wir hier nur: registry-is-not-empty.+ # An MCP-remote harness is "healthy" when at least one bootstrap+ # server can be pinged. Since pinging costs time, we only return+ # here: registry-is-not-empty.return len(BOOTSTRAP_SERVERS) > 0async def invoke(self, task: HarnessTask) -> AsyncIterator[HarnessResult]:@@ -46,7 +45,7 @@ class MCPRemoteHarness:if spec is None:yield HarnessResult(- stderr=f"MCP-Server '{server_name}' nicht in BOOTSTRAP_SERVERS.\n",+ stderr=f"MCP server '{server_name}' not in BOOTSTRAP_SERVERS.\n",exit_code=2,duration_ms=int((time.perf_counter() - t_start) * 1000),is_final=True,@@ -58,7 +57,7 @@ class MCPRemoteHarness:await client.connect()except Exception as exc: # noqa: BLE001yield HarnessResult(- stderr=f"MCP-Connect fehlgeschlagen: {exc}\n",+ stderr=f"MCP connect failed: {exc}\n",exit_code=1,duration_ms=int((time.perf_counter() - t_start) * 1000),is_final=True,@@ -66,7 +65,7 @@ class MCPRemoteHarness:returntry:- # Liste verfügbarer Tools+ # List of available toolstools = await client.list_tools()tool_names = [t.name for t in tools]yield HarnessResult(@@ -74,8 +73,8 @@ class MCPRemoteHarness:is_final=False,)- # Wenn der Prompt einen der Tool-Namen als Prefix hat, nutze den.- # Convention: "toolname args-as-json" oder bloß "prompt".+ # If the prompt has one of the tool names as a prefix, use it.+ # Convention: "toolname args-as-json" or just "prompt".chosen_tool: str | None = Noneargs: dict = {"prompt": task.prompt}for t in tools:@@ -84,11 +83,11 @@ class MCPRemoteHarness:breakif chosen_tool is None and tool_names:- # Kein expliziter Tool-Name — wir geben die Liste zurück und fertig.+ # No explicit tool name — we return the list and are done.yield HarnessResult(stdout=(- "Bitte Tool-Name an den Anfang des Prompts setzen "- f"(z.B. '{tool_names[0]} ...').\n"+ "Please put a tool name at the start of the prompt "+ f"(e.g. '{tool_names[0]} ...').\n"),is_final=False,)diff --git a/jarvis/plugins/harness/open_interpreter.py b/jarvis/plugins/harness/open_interpreter.pyindex ab5ef37fe3..15f392d889 100644--- a/jarvis/plugins/harness/open_interpreter.py+++ b/jarvis/plugins/harness/open_interpreter.py@@ -1,13 +1,13 @@-"""Open-Interpreter-Harness (Stub).+"""Open-Interpreter harness (stub).-Open-Interpreter hat keine Subprocess-CLI, es ist ein Python-Package. Für-sinnvolle Integration müssen wir `from interpreter import interpreter`-in-process laden und `interpreter.chat(prompt, stream=True, display=False)`-iterieren. Das Package ist dependency-heavy (OpenAI, torch, ...) und nicht-Teil der Jarvis-Requirements.+Open-Interpreter has no subprocess CLI, it's a Python package. For a+meaningful integration we'd need to load `from interpreter import interpreter`+in-process and iterate `interpreter.chat(prompt, stream=True, display=False)`.+The package is dependency-heavy (OpenAI, torch, ...) and not part of the+Jarvis requirements.-Dieser Stub failed `health()` solange das Package fehlt — so bleibt die-Discovery ohne Crash und der User bekommt eine klare Meldung.+This stub fails `health()` as long as the package is missing — that keeps+discovery crash-free and gives the user a clear message."""from __future__ import annotations@@ -29,16 +29,16 @@ class OpenInterpreterHarness:if not await self.health():yield HarnessResult(stderr=(- "Open-Interpreter nicht installiert. "- "`pip install open-interpreter` dann Harness erneut aufrufen.\n"+ "Open-Interpreter not installed. "+ "`pip install open-interpreter` then call the harness again.\n"),exit_code=127,is_final=True,)return- # In-Process-Mode — future work.+ # In-process mode — future work.yield HarnessResult(- stderr="Open-Interpreter In-Process-Integration noch nicht implementiert.\n",+ stderr="Open-Interpreter in-process integration not implemented yet.\n",exit_code=1,is_final=True,)diff --git a/jarvis/plugins/harness/python_script.py b/jarvis/plugins/harness/python_script.pyindex 946674ff18..d92cc00fd7 100644--- a/jarvis/plugins/harness/python_script.py+++ b/jarvis/plugins/harness/python_script.py@@ -1,10 +1,10 @@-"""Python-Script-Harness: führt Python-Code im Subprocess aus.+"""Python-script harness: runs Python code in a subprocess.-`task.prompt` wird als `-c "<code>"` an `python` übergeben (inline). Für-File-Execution kann der Prompt mit `@path/to/file.py` beginnen.+`task.prompt` is passed to `python` as `-c "<code>"` (inline). For file+execution, the prompt can start with `@path/to/file.py`.-Kein LLM-Loop — einfach deterministisches Script-Execution. Nützlich als-schneller "Calculator"- oder "Datenverarbeitungs"-Harness, und als Test-Harness.+No LLM loop — just deterministic script execution. Useful as a quick+"calculator" or "data-processing" harness, and as a test harness."""from __future__ import annotations@@ -26,7 +26,7 @@ class PythonScriptHarness(SubprocessHarness):if prompt.startswith("@"):script_path = prompt[1:].strip()return [py, script_path]- # Inline-Code+ # Inline codereturn [py, "-X", "utf8", "-c", prompt]async def health(self) -> bool:diff --git a/jarvis/plugins/stt/fwhisper.py b/jarvis/plugins/stt/fwhisper.pyindex fc9f325121..8374a50cf7 100644--- a/jarvis/plugins/stt/fwhisper.py+++ b/jarvis/plugins/stt/fwhisper.py@@ -1,11 +1,11 @@-"""faster-whisper STT-Plugin.+"""faster-whisper STT plugin.-Implementiert strukturell `STTProvider` — kein Vererbung, nur Duck-Type.-Das Modell (distil-large-v3, multilingual DE+EN) wird lazy beim ersten-`start()`-Call in GPU-Memory geladen (~1.5 GB VRAM bei int8_float16).+Structurally implements `STTProvider` — no inheritance, just duck-typing.+The model (distil-large-v3, multilingual DE+EN) is lazily loaded into+GPU memory on the first `start()` call (~1.5 GB VRAM at int8_float16).-Auf RTX 5070 Ti liefert distil-large-v3 für eine 5-Sekunden-Utterance-~250 ms Latenz — gut genug für Phase 1.+On an RTX 5070 Ti, distil-large-v3 delivers ~250 ms latency for a+5-second utterance — good enough for Phase 1."""from __future__ import annotations@@ -154,10 +154,10 @@ def _new_whisper_model(model_name: str, device: str, compute_type: str) -> Any:class FasterWhisperProvider:- """Lokaler Whisper-STT über faster-whisper (CTranslate2-Backend)."""+ """Local Whisper STT via faster-whisper (CTranslate2 backend)."""name = "faster-whisper"- supports_streaming = False # wir können später stream_transcribe nachrüsten+ supports_streaming = False # we can add stream_transcribe laterdef __init__(self,@@ -166,9 +166,9 @@ class FasterWhisperProvider:compute_type: str = "int8_float16",language: str | None = None, # None = auto-detect (bilingual DE+EN)beam_size: int = 5,- vad_filter: bool = False, # wir haben externes Silero-VAD davor- # Kein Initial-Prompt im Hot-Path: feste Beispielsaetze wurden bei- # leisem Audio als Transkript halluziniert und gingen ans Brain.+ vad_filter: bool = False, # we have an external Silero VAD in front of this+ # No initial prompt in the hot path: fixed example sentences were+ # hallucinated as the transcript on quiet audio and sent to the brain.initial_prompt: str | None = None,no_speech_threshold: float = 0.6,) -> None:@@ -289,14 +289,14 @@ class FasterWhisperProvider:log.debug("Whisper warm-up inference skipped: %s", exc)async def transcribe(self, audio: AsyncIterator[AudioChunk]) -> Transcript:- """Sammelt alle Chunks, transkribiert am Stück.+ """Collects all chunks, transcribes them in one go.- Für Phase 1 reicht das — die VAD-Schicht davor liefert uns bereits- saubere Utterances, also ist "am Stück" das natürliche Granularity.+ This is enough for Phase 1 — the VAD layer in front already delivers+ clean utterances, so "in one go" is the natural granularity."""self._ensure_model()- # Alle Chunks in einem float32-Array zusammenziehen+ # Concatenate all chunks into one float32 arraypieces: list[np.ndarray] = []sample_rate = 16_000async for chunk in audio:@@ -312,10 +312,11 @@ class FasterWhisperProvider:self, pcm_bytes: bytes, sample_rate: int = 16_000,language: str | None = None,) -> Transcript:- """Direkter Weg für VAD-Output: int16-PCM-Bytes → Transcript.+ """Direct path for VAD output: int16 PCM bytes → transcript.- `language` überschreibt per Call die Default-Sprache. Nützlich für den- Wake-Detector der auch bei STT-Default "auto" immer auf Deutsch hören soll.+ `language` overrides the default language per call. Useful for the+ wake detector, which should always listen for German even when the+ STT default is "auto"."""self._ensure_model()audio_np = pcm_bytes_to_np(pcm_bytes)@@ -325,7 +326,7 @@ class FasterWhisperProvider:self, audio_np: np.ndarray, sample_rate: int,language: str | None = None,) -> Transcript:- # faster-whisper ist synchron → in Thread shippen+ # faster-whisper is synchronous → ship it off to a threadimport asyncioreturn await asyncio.to_thread(self._transcribe_sync, audio_np, sample_rate, language)@@ -333,12 +334,12 @@ class FasterWhisperProvider:self, audio_np: np.ndarray, sample_rate: int,language: str | None = None,) -> Transcript:- # faster-whisper akzeptiert np.ndarray float32 direkt wenn 16 kHz+ # faster-whisper accepts np.ndarray float32 directly when 16 kHzif sample_rate != 16_000:- # Resample wäre hier nötig — wir erwarten aber 16 kHz von Capture- raise ValueError(f"Erwartet 16 kHz, bekommen {sample_rate} Hz")+ # A resample would be needed here — but we expect 16 kHz from capture+ raise ValueError(f"Expected 16 kHz, got {sample_rate} Hz")- # Per-Call-Override hat Vorrang vor self._language+ # Per-call override takes precedence over self._languageeffective_lang = language if language is not None else self._language# NON-BLOCKING acquire across BOTH the transcribe() call and the lazy@@ -368,13 +369,13 @@ class FasterWhisperProvider:initial_prompt=self._initial_prompt,no_speech_threshold=self._no_speech_threshold,)- # segments_iter ist generator — durchiterieren materialisiert+ # segments_iter is a generator — iterating over it materializes itsegments = list(segments_iter)finally:lock.release()text = "".join(s.text for s in segments).strip()- # Segment-Tuples als Meta für Debugging/Flight-Recorder+ # Segment tuples as metadata for debugging/flight-recorderseg_dicts = tuple({"start": s.start,@@ -386,7 +387,7 @@ class FasterWhisperProvider:for s in segments)- # Confidence-Approximation: exp(avg_logprob) gemittelt — nicht perfekt, reicht.+ # Confidence approximation: averaged exp(avg_logprob) — not perfect, good enough.if segments:avg = sum(s.avg_logprob for s in segments) / len(segments)confidence = float(np.exp(avg))@@ -404,6 +405,6 @@ class FasterWhisperProvider:async def stream_transcribe(self, audio: AsyncIterator[AudioChunk]) -> AsyncIterator[Transcript]:- """Placeholder für inkrementelle Transkription — Phase 2+."""+ """Placeholder for incremental transcription — Phase 2+."""final = await self.transcribe(audio)yield finaldiff --git a/jarvis/plugins/tool/app_resolver.py b/jarvis/plugins/tool/app_resolver.pyindex 8eed1aeb53..f3105eb86c 100644--- a/jarvis/plugins/tool/app_resolver.py+++ b/jarvis/plugins/tool/app_resolver.py@@ -254,7 +254,8 @@ def _resolve_windows(# install a per-user Squirrel build registered ONLY as a Start Menu .lnk —# absent from both App Paths and PATH. Without this step the resolver fell# through to os.startfile("discord"), which raises FileNotFoundError- # ("Anwendung 'discord' nicht gefunden"), and the computer-use loop was then+ # (reported in Windows' localized text as "application 'discord' not+ # found"), and the computer-use loop was then# forced into unreliable taskbar pixel-clicking (it hit Spotify, the icon# next to Discord). Match the friendly name AND the canonical alias to a# shortcut and hand the launcher that .lnk (os.startfile follows it).diff --git a/jarvis/plugins/tool/awareness_snapshot.py b/jarvis/plugins/tool/awareness_snapshot.pyindex 2ae1f265d3..f35770b174 100644--- a/jarvis/plugins/tool/awareness_snapshot.py+++ b/jarvis/plugins/tool/awareness_snapshot.py@@ -1,12 +1,12 @@-"""``awareness-snapshot``-Tool — synchroner State-Read fuer den Router.+"""``awareness-snapshot`` tool — synchronous state read for the router.-Plan §5 verbindlich: dieses Tool ist Router-Tier-only (NICHT in-SUB_TOOLS). Es macht KEINEN Brain-Call und KEIN IO — nur einen-synchronen Read auf ``AwarenessState.snapshot_for_prompt()``.+Binding per Plan §5: this tool is router-tier-only (NOT in SUB_TOOLS). It+makes NO brain call and NO IO — just a synchronous read on+``AwarenessState.snapshot_for_prompt()``.-Wann nutzt es der Hauptjarvis: bei Utterances wie "Was mache ich-gerade?" oder "In welcher Datei bin ich?" — die Antwort steht im-Awareness-State und braucht keinen LLM-Roundtrip oder OpenClaw-Spawn.+When the main Jarvis uses it: for utterances like "what am I doing right+now?" or "which file am I in?" — the answer is already in the awareness+state and doesn't need an LLM roundtrip or an OpenClaw spawn."""from __future__ import annotations@@ -18,12 +18,11 @@ from jarvis.awareness.manager import AwarenessManager@dataclassclass ToolResult:- """Minimal-Wrapper fuer Tool-Output. Vollstaendiger Contract liegt- in jarvis.core.protocols; hier nur was wir tatsaechlich ruecksenden.+ """Minimal wrapper for tool output. The full contract lives in+ jarvis.core.protocols; here just what we actually send back.- Wenn das echte Tool-Result-Protocol erweitert wird, muss diese Klasse- strukturell kompatibel bleiben (oder direkt durch das Protocol ersetzt- werden).+ If the real tool-result protocol is extended, this class must stay+ structurally compatible (or be replaced directly by the protocol)."""success: booloutput: str@@ -31,13 +30,13 @@ class ToolResult:class AwarenessSnapshotTool:- """Synchroner State-Read auf ``manager.state.snapshot_for_prompt()``."""+ """Synchronous state read on ``manager.state.snapshot_for_prompt()``."""name: str = "awareness-snapshot"description: str = (- "Liefert den aktuellen Awareness-State (aktives Fenster, Idle-Status, "- "letzter Episode-Summary wenn vorhanden). NUTZE das BEVOR du den User "- "nach Kontext fragst — die Antwort ist oft schon hier drin."+ "Returns the current awareness state (active window, idle status, "+ "last episode summary if any). USE this BEFORE asking the user for "+ "context — the answer is often already in here.")risk_tier: str = "safe"schema: dict[str, Any] = {@@ -50,9 +49,9 @@ class AwarenessSnapshotTool:self._manager = managerasync def execute(self, args: dict[str, Any], ctx: Any) -> ToolResult:- """Synchroner State-Read — KEIN Brain-Call, KEIN IO.+ """Synchronous state read — NO brain call, NO IO.- ``args`` und ``ctx`` werden ignoriert (Schema hat keine Required).+ ``args`` and ``ctx`` are ignored (schema has no required fields)."""snap = self._manager.state.snapshot_for_prompt()return ToolResult(success=True, output=snap)diff --git a/jarvis/plugins/tool/click.py b/jarvis/plugins/tool/click.pyindex 6ff39e2750..450508e45d 100644--- a/jarvis/plugins/tool/click.py+++ b/jarvis/plugins/tool/click.py@@ -1,13 +1,12 @@-"""click-Tool: simuliert Mausklicks an einer Bildschirm-Koordinate.+"""click tool: simulates mouse clicks at a screen coordinate.-Win32-nativ via ``SetCursorPos`` + ``SendInput`` (Mouse-Event). Faellt-auf ``pyautogui.click`` zurueck, falls Win32 nicht verfuegbar — damit-laufen die Tests auf Linux/Mac, auch wenn echte Klicks nur auf Windows-funktional sind.+Win32-native via ``SetCursorPos`` + ``SendInput`` (mouse event). Falls back+to ``pyautogui.click`` if Win32 isn't available — so tests run on Linux/Mac+even though real clicks only work on Windows.-Risk-Tier: ``monitor`` — Maus-Klicks sind oft nicht reversibel-(Buttons, Form-Submits, Datei-Operationen). Toast-Notification sichtbar,-kein Approval-Dialog.+Risk tier: ``monitor`` — mouse clicks are often not reversible (buttons,+form submits, file operations). A toast notification is shown, no approval+dialog."""from __future__ import annotations@@ -19,7 +18,7 @@ from jarvis.control.cursor_motion import glide_os_cursorfrom jarvis.core.protocols import ExecutionContext, ToolResultfrom jarvis.overlay.virtual_cursor import get_virtual_cursor-# Mouse-Button-Mapping fuer Win32 (siehe MOUSEEVENTF_*-Flags).+# Mouse-button mapping for Win32 (see MOUSEEVENTF_* flags)._MOUSE_FLAGS_DOWN: dict[str, int] = {"left": 0x0002, # MOUSEEVENTF_LEFTDOWN"right": 0x0008, # MOUSEEVENTF_RIGHTDOWN@@ -78,7 +77,7 @@ def _send_click(button: str, double: bool, abs_xy: tuple[int, int] | None = None"""button_l = button.lower()if button_l not in _MOUSE_FLAGS_DOWN:- raise ValueError(f"Unbekannter Mausbutton: {button!r}. Erlaubt: left/right/middle")+ raise ValueError(f"Unknown mouse button: {button!r}. Allowed: left/right/middle")import ctypesfrom ctypes import wintypes@@ -149,11 +148,11 @@ def _click_windows(x: int, y: int, button: str, double: bool) -> None:the click never misses — even across a multi-monitor virtual desktop."""if os.name != "nt":- raise RuntimeError("Native Mausklick ist nur auf Windows verfuegbar")+ raise RuntimeError("Native mouse click is only available on Windows")button_l = button.lower()if button_l not in _MOUSE_FLAGS_DOWN:- raise ValueError(f"Unbekannter Mausbutton: {button!r}. Erlaubt: left/right/middle")+ raise ValueError(f"Unknown mouse button: {button!r}. Allowed: left/right/middle")glide_os_cursor(int(x), int(y))try:@@ -170,15 +169,15 @@ class ClickTool:name: str = "click"risk_tier: str = "monitor"description: str = (- "Klickt mit der Maus an eine Bildschirm-Koordinate. Optional "- "rechte/mittlere Maustaste, Doppelklick. Koordinaten sind absolut "- "(0,0 = obere linke Ecke des primaeren Monitors)."+ "Clicks the mouse at a screen coordinate. Optional right/middle "+ "mouse button, double-click. Coordinates are absolute "+ "(0,0 = top-left corner of the primary monitor).")schema: dict[str, Any] = {"type": "object","properties": {- "x": {"type": "integer", "description": "X-Koordinate (Pixel)"},- "y": {"type": "integer", "description": "Y-Koordinate (Pixel)"},+ "x": {"type": "integer", "description": "X coordinate (pixels)"},+ "y": {"type": "integer", "description": "Y coordinate (pixels)"},"button": {"type": "string","enum": ["left", "right", "middle"],@@ -187,7 +186,7 @@ class ClickTool:"double": {"type": "boolean","default": False,- "description": "Doppelklick statt Einfachklick",+ "description": "Double-click instead of a single click",},},"required": ["x", "y"],@@ -201,7 +200,7 @@ class ClickTool:return ToolResult(success=False,output=None,- error="x und y muessen Integer-Koordinaten sein",+ error="x and y must be integer coordinates",)button = str(args.get("button", "left")).lower()double = bool(args.get("double", False))@@ -210,22 +209,22 @@ class ClickTool:return ToolResult(success=False,output=None,- error=f"Unbekannter button={button!r}. Erlaubt: left/right/middle",+ error=f"Unknown button={button!r}. Allowed: left/right/middle",)if os.name == "nt":try:await asyncio.to_thread(_click_windows, x, y, button, double)- kind = "Doppelklick" if double else "Klick"+ kind = "double-click" if double else "click"return ToolResult(success=True,- output=f"{kind} ({button}) an ({x}, {y})",+ output=f"{kind} ({button}) at ({x}, {y})",)except (ValueError, OSError) as exc:return ToolResult(success=False,output=None,- error=f"Klick an ({x},{y}) fehlgeschlagen: {exc}",+ error=f"Click at ({x},{y}) failed: {exc}",)try:@@ -235,7 +234,7 @@ class ClickTool:success=False,output=None,error=(- f"Plattform nicht Windows ({os.name}) und pyautogui fehlt: {exc}. "+ f"Platform is not Windows ({os.name}) and pyautogui is missing: {exc}. ""pip install pyautogui"),)@@ -244,7 +243,7 @@ class ClickTool:pyautogui.click(x=x, y=y, clicks=clicks, button=button)return ToolResult(success=True,- output=f"{'Doppel' if double else ''}Klick (pyautogui) an ({x},{y})",+ output=f"{'Double-' if double else ''}click (pyautogui) at ({x},{y})",)except Exception as exc: # noqa: BLE001return ToolResult(success=False, output=None, error=str(exc))diff --git a/jarvis/plugins/tool/dispatch_to_admin.py b/jarvis/plugins/tool/dispatch_to_admin.pyindex 5c70255a00..4db6388338 100644--- a/jarvis/plugins/tool/dispatch_to_admin.py+++ b/jarvis/plugins/tool/dispatch_to_admin.py@@ -1,23 +1,23 @@-"""dispatch_to_admin-Tool — Brain ruft Admin-Ops via UAC-elevatetem Helper auf.+"""dispatch_to_admin tool — brain calls admin ops via a UAC-elevated helper.-Risk-Tier = ``ask``. Das bedeutet: jeder Brain-Call wird durch den-Approval-Workflow gereicht, **ausser** der User hat via-``[safety.whitelist]`` ein Pattern wie ``dispatch_to_admin *`` gesetzt.-Destruktive Ops (DESTRUCTIVE_OPS) bekommen on top einen zweiten Prompt,-auch bei globaler Whitelist — das ist Absicht.+Risk tier = ``ask``. That means every brain call is routed through the+approval workflow, **unless** the user has set a pattern like+``dispatch_to_admin *`` via ``[safety.whitelist]``. Destructive ops+(DESTRUCTIVE_OPS) get a second prompt on top, even with a global whitelist —+that is intentional.-Call-Flow:+Call flow:-1. Brain ruft ``{"op": {...AdminOperation JSON...}}`` auf.-2. Tool validiert das JSON gegen das Pydantic-Schema.+1. Brain calls ``{"op": {...AdminOperation JSON...}}``.+2. Tool validates the JSON against the Pydantic schema.3. ``AdminClient.execute(op, destructive_approved=...)``.-4. Bei ``DestructiveRequiresApproval``:- → Tool returnt ``ToolResult(success=False, error="destructive_requires_approval",- output={"op_id": ..., "op_type": ...})``. Der Caller (Risk-Tier-Executor)- zeigt dem User einen Prompt und ruft das Tool erneut mit+4. On ``DestructiveRequiresApproval``:+ → Tool returns ``ToolResult(success=False, error="destructive_requires_approval",+ output={"op_id": ..., "op_type": ...})``. The caller (risk-tier executor)+ shows the user a prompt and calls the tool again with``destructive_approved=True``.-5. Bei Erfolg/Fehler: das ``AdminResponse``-Model wird als dict ins- ``ToolResult.output`` gepackt.+5. On success/failure: the ``AdminResponse`` model is packed into+ ``ToolResult.output`` as a dict."""from __future__ import annotations@@ -34,16 +34,16 @@ _ADMIN_OP_ADAPTER: TypeAdapter[AdminOperation] = TypeAdapter(AdminOperation)class DispatchToAdminTool:- """Protocol-kompatibles Tool. Wird von Brain via Tool-Call aufgerufen."""+ """Protocol-compatible tool. Called by the brain via a tool call."""name: str = "dispatch_to_admin"risk_tier: str = "ask"description: str = (- "Schickt eine Admin-Operation (winget install, service start/stop, "- "firewall, registry-write, scheduled task, write_protected_path) "- "an den UAC-elevateten Admin-Helper. Destruktive Ops "+ "Sends an admin operation (winget install, service start/stop, "+ "firewall, registry write, scheduled task, write_protected_path) "+ "to the UAC-elevated admin helper. Destructive ops ""(uninstall, remove, write_registry_hklm, write_protected_path) "- "brauchen explizite Zustimmung."+ "need explicit approval.")schema: dict[str, Any] = {"type": "object",@@ -51,17 +51,17 @@ class DispatchToAdminTool:"op": {"type": "object","description": (- "AdminOperation-JSON. Muss einen 'type'-Key haben "- "(z.B. 'install_winget') und die fuer den Op-Typ "- "noetigen Felder. Siehe jarvis.admin.schema."+ "AdminOperation JSON. Must have a 'type' key "+ "(e.g. 'install_winget') and the fields required for "+ "that op type. See jarvis.admin.schema."),},"destructive_approved": {"type": "boolean","description": (- "Wenn true, wird die Op auch bei destruktivem Typ "- "ausgefuehrt. Default false — der Risk-Tier-Executor "- "setzt das nach User-Zustimmung."+ "If true, the op runs even for a destructive type. "+ "Default false — the risk-tier executor sets this "+ "after the user's approval."),"default": False,},@@ -76,7 +76,7 @@ class DispatchToAdminTool:client_factory: Any = None,) -> None:self._bus = bus- # Optional-Injection fuer Tests — sonst lazy in execute.+ # Optional injection for tests — otherwise lazily built in execute.self._client_factory = client_factoryasync def execute(@@ -88,7 +88,7 @@ class DispatchToAdminTool:if not isinstance(op_payload, dict):return ToolResult(success=False, output=None,- error="'op' muss ein JSON-Objekt sein.",+ error="'op' must be a JSON object.",)try:diff --git a/jarvis/plugins/tool/dispatch_to_harness.py b/jarvis/plugins/tool/dispatch_to_harness.pyindex d8281e9728..e38f0dfe85 100644--- a/jarvis/plugins/tool/dispatch_to_harness.py+++ b/jarvis/plugins/tool/dispatch_to_harness.py@@ -1,12 +1,12 @@-"""dispatch_to_harness-Tool: vom Brain aufrufbar, delegiert an einen Harness.+"""dispatch_to_harness tool: callable by the brain, delegates to a harness.-Der Brain kann via Tool-Call OpenClaw / Codex / Python-Script / MCP-Remote-spawnen. Output wird akkumuliert, auf `max_output_chars` getrimmt und als-`ToolResult.output` zurückgegeben — der Brain sieht's in der nächsten Turn-als `role="tool"`-Message und kann dann zusammenfassen.+The brain can spawn OpenClaw / Codex / Python-Script / MCP-Remote via a tool+call. Output is accumulated, trimmed to `max_output_chars`, and returned as+`ToolResult.output` — the brain sees it in the next turn as a+`role="tool"` message and can then summarize it.-Optional: `parallel_harnesses` — mehrere Harnesses gleichzeitig und-aggregiert zurückgeben.+Optional: `parallel_harnesses` — run multiple harnesses at once and return+the aggregated result."""from __future__ import annotations@@ -49,24 +49,24 @@ class DispatchToHarnessTool:},"prompt": {"type": "string",- "description": "Die Aufgabe / der Prompt für den Sub-Agenten.",+ "description": "The task / prompt for the sub-agent.",},"cwd": {"type": "string",- "description": "Working-Directory (optional).",+ "description": "Working directory (optional).","default": "",},"timeout_s": {"type": "number",- "description": "Maximale Laufzeit in Sekunden (Default 600).",+ "description": "Maximum runtime in seconds (default 600).","default": 600,},"parallel_harnesses": {"type": "array","items": {"type": "string"},"description": (- "Wenn gesetzt, werden alle genannten Harnesses parallel ausgeführt "- "und ihre Outputs aggregiert. 'harness' wird ignoriert."+ "If set, all named harnesses run in parallel and their "+ "outputs are aggregated. 'harness' is ignored."),"default": [],},@@ -98,7 +98,7 @@ class DispatchToHarnessTool:if len(text) <= self._max_output_chars:return textkeep = self._max_output_chars // 2- return text[:keep] + f"\n\n[… {len(text) - 2 * keep} chars gekürzt …]\n\n" + text[-keep:]+ return text[:keep] + f"\n\n[… {len(text) - 2 * keep} chars trimmed …]\n\n" + text[-keep:]# ------------------------------------------------------------------# Execute@@ -119,7 +119,7 @@ class DispatchToHarnessTool:env = dict(raw_env) if isinstance(raw_env, dict) else {}if not prompt:- return ToolResult(success=False, output=None, error="prompt fehlt")+ return ToolResult(success=False, output=None, error="prompt is missing")task = HarnessTask(prompt=prompt,@@ -132,7 +132,7 @@ class DispatchToHarnessTool:if parallel:return await self._execute_parallel(list(parallel), task, aggregation)if not harness_name:- return ToolResult(success=False, output=None, error="harness fehlt")+ return ToolResult(success=False, output=None, error="harness is missing")return await self._execute_single(harness_name, task)except Exception as exc: # noqa: BLE001return ToolResult(success=False, output=None, error=f"{type(exc).__name__}: {exc}")@@ -270,7 +270,7 @@ class DispatchToHarnessTool:aggregation,buffers,success=all_ok,- error=None if all_ok else "ein oder mehr Harnesses mit non-zero exit",+ error=None if all_ok else "one or more harnesses exited non-zero",)def _parallel_result(diff --git a/jarvis/plugins/tool/dispatch_with_review.py b/jarvis/plugins/tool/dispatch_with_review.pyindex f9acde711f..99ef0f4a42 100644--- a/jarvis/plugins/tool/dispatch_with_review.py+++ b/jarvis/plugins/tool/dispatch_with_review.py@@ -1,14 +1,13 @@-"""dispatch_with_review-Tool: vom Hauptjarvis aufrufbar (Phase 8.4).+"""dispatch_with_review tool: callable by the main Jarvis (Phase 8.4).-Plan-Referenz: §6.4, §AD-6 (selektive Aktivierung). Dieses Tool ist die-einzige Schaltstelle, die die Quality-Gate-Pipeline aktiviert. Hauptjarvis-ruft es explizit auf, wenn die Aufgabe es rechtfertigt — Code-Generierung,-Skill-Authoring, Datei-Mutation, Multi-Schritt-Research. Konversation und-Smalltalk laufen NIE durch dieses Tool (Plan §AD-6 — Self-Critique--Paradox).+Plan reference: §6.4, §AD-6 (selective activation). This tool is the ONLY+switch that activates the quality-gate pipeline. The main Jarvis calls it+explicitly when the task justifies it — code generation, skill authoring,+file mutation, multi-step research. Conversation and small talk NEVER run+through this tool (Plan §AD-6 — self-critique paradox).-Tool-Beschreibung ist 1:1 aus Plan §6.4 — sie ist die einzige Heuristik,-die das LLM zur Aktivierung sieht (Plan-Architektur).+The tool description is verbatim from Plan §6.4 — it's the only heuristic+the LLM sees for activation (plan architecture)."""from __future__ import annotations@@ -30,30 +29,30 @@ from jarvis.core.review.spawns import ReviewerSpawner, WorkerSpawnerfrom jarvis.core.review.state import PipelineOutcome, PipelineResultfrom jarvis.harness.manager import HarnessManager-# AD-14: Voice-Phrasen sind hier hartcodiert + werden in den Smoke-Tests-# byte-genau matched. Änderungen erfordern Plan-Update.-VOICE_HOLDING_PHRASE_DE = "Lass mich kurz an der Aufgabe arbeiten."+# AD-14: voice phrases are hardcoded here and byte-exact matched in the+# smoke tests. Changes require a plan update.+VOICE_HOLDING_PHRASE_DE = "Lass mich kurz an der Aufgabe arbeiten." # i18n-allow: German TTS phraseVOICE_OUTCOME_TEMPLATES_DE = {- "success": "Erledigt — {summary}",- "cap_fired": "Mein bestes Ergebnis liegt vor, mit einer Einschränkung: {top_issue}",- "fail": "Das funktioniert so nicht — {summary}",- "precheck_fail": "Die Aufgabe ist zu kurz oder unklar — versuch's nochmal mit mehr Kontext.",+ "success": "Erledigt — {summary}", # i18n-allow: German TTS phrase+ "cap_fired": "Mein bestes Ergebnis liegt vor, mit einer Einschränkung: {top_issue}", # i18n-allow: German TTS phrase+ "fail": "Das funktioniert so nicht — {summary}", # i18n-allow: German TTS phrase+ "precheck_fail": "Die Aufgabe ist zu kurz oder unklar — versuch's nochmal mit mehr Kontext.", # i18n-allow: German TTS phrase}class DispatchWithReviewTool:- """Tool-Wrapper über `ReviewPipeline` für den Hauptjarvis."""+ """Tool wrapper over `ReviewPipeline` for the main Jarvis."""name: str = "dispatch_with_review"risk_tier: str = "monitor"description: str = (- "Führt eine OpenClaw-Aufgabe mit Review-Quality-Gate aus. "- "NUTZE diesen Tool wenn das Ergebnis user-irreversibel ist (Code-"- "Generierung, Datei-Mutation, Skill-Authoring), Multi-Schritt-"- "Synthese verlangt (Research, Aggregation), oder schwer rückgängig "- "zu machen ist. NUTZE NICHT für Konversation, Smalltalk, einfache "- "Tool-Calls (Calendar lesen, Wetter abfragen) — diese laufen über "- "dispatch_to_harness oder direkt im Hauptjarvis."+ "Runs an OpenClaw task with a review quality gate. "+ "USE this tool when the result is user-irreversible (code "+ "generation, file mutation, skill authoring), requires multi-step "+ "synthesis (research, aggregation), or is hard to undo. DO NOT USE "+ "for conversation, small talk, or simple tool calls (reading the "+ "calendar, checking the weather) — those go through "+ "dispatch_to_harness or run directly in the main Jarvis.")schema: dict[str, Any] = {"type": "object",@@ -63,8 +62,8 @@ class DispatchWithReviewTool:"type": "string","minLength": 20,"description": (- "Vollständige Task-Beschreibung für OpenClaw. "- "Zwingend, mindestens 20 Zeichen."+ "Complete task description for OpenClaw. "+ "Required, at least 20 characters."),},"rubric_id": {@@ -77,10 +76,10 @@ class DispatchWithReviewTool:],"default": "default","description": (- "Welche Bewertungs-Rubric der Reviewer durchläuft. "- "`default` für allgemeine Aufgaben, `code_generation` "- "für Code+Tests, `skill_authoring` für SKILL.md-Generierung, "- "`research` für Faktenrecherche."+ "Which grading rubric the reviewer runs. "+ "`default` for general tasks, `code_generation` "+ "for code+tests, `skill_authoring` for SKILL.md generation, "+ "`research` for fact-finding."),},"max_iterations": {@@ -89,29 +88,29 @@ class DispatchWithReviewTool:"maximum": 5,"default": 3,"description": (- "Maximale Worker→Reviewer-Iterationen bevor Cap-Fire-"- "Fallback (best candidate) ausgeliefert wird."+ "Maximum worker→reviewer iterations before the cap-fire "+ "fallback (best candidate) is delivered."),},},"required": ["task"],"strict": True,}- # Beispiele aus Plan-§AD-9-Pattern (Anthropic 2026): erhöht Tool-Trigger-- # Genauigkeit + reduziert Schema-Verletzungen.+ # Examples from the Plan-§AD-9 pattern (Anthropic 2026): improves+ # tool-trigger accuracy + reduces schema violations.input_examples: list[dict[str, Any]] = [{"task": (- "Schreibe ein Python-Script in scripts/rename_notes.py das "- "alle .md-Files in ~/notes nach 'YYYY-MM-DD_<slug>.md' "- "umbenennt, mit pytest-Tests."+ "Write a Python script at scripts/rename_notes.py that "+ "renames every .md file in ~/notes to 'YYYY-MM-DD_<slug>.md', "+ "with pytest tests."),"rubric_id": "code_generation",},{"task": (- "Erstelle einen neuen Skill der Spotify pausiert wenn ich "- "rede, basierend auf dem Skill-Creator-Pattern."+ "Create a new skill that pauses Spotify when I'm talking, "+ "based on the skill-creator pattern."),"rubric_id": "skill_authoring","max_iterations": 3,@@ -133,7 +132,7 @@ class DispatchWithReviewTool:) -> None:self._bus = busself._manager = harness_manager or HarnessManager(bus=bus)- # Defaults aus Plan §6.4 — Override per ctor-Argument für Tests.+ # Defaults from Plan §6.4 — override via ctor argument for tests.self._runs_root: Path = Path(runs_root or "data/review/runs")self._audit = ReviewAudit(path=Path(audit_log_path or "data/review.log")@@ -141,7 +140,7 @@ class DispatchWithReviewTool:self._max_iterations = max_iterationsself._hard_ceiling = hard_ceiling- # Spawner und Pipeline werden lazy gebaut (oder durch Tests injiziert).+ # Spawner and pipeline are lazily built (or injected by tests).self._worker_spawner = worker_spawnerself._reviewer_spawner = reviewer_spawnerself._pipeline = pipeline@@ -181,17 +180,17 @@ class DispatchWithReviewTool:async def execute(self, args: dict[str, Any], ctx: ExecutionContext) -> ToolResult:- del ctx # ExecutionContext aktuell nicht benötigt (Phase-8.4-Scope)+ del ctx # ExecutionContext not currently needed (Phase-8.4 scope)task = (args.get("task") or "").strip()rubric_id = args.get("rubric_id") or "default"- # max_iterations als Per-Run-Override; sonst Default aus ctor.+ # max_iterations as a per-run override; otherwise the ctor default.max_iter_arg = args.get("max_iterations")if not task or len(task) < 20:return ToolResult(success=False,output=None,- error="task fehlt oder ist zu kurz (mindestens 20 Zeichen)",+ error="task is missing or too short (at least 20 characters)",)if rubric_id not in {"default",@@ -202,12 +201,12 @@ class DispatchWithReviewTool:return ToolResult(success=False,output=None,- error=f"unbekannte rubric_id: {rubric_id!r}",+ error=f"unknown rubric_id: {rubric_id!r}",)pipeline = self._ensure_pipeline()- # AD-14: Holding-Phrase EINMAL pro Run — vor dem await pipeline.run().- # Bus-Publish ist Best-Effort; falls kein Bus injiziert, kein Side-Effect.+ # AD-14: holding phrase ONCE per run — before the await pipeline.run().+ # Bus publish is best-effort; if no bus is injected, no side effect.await self._announce_holding_phrase()try:result = await pipeline.run(@@ -215,7 +214,7 @@ class DispatchWithReviewTool:rubric_id=rubric_id,max_iterations=int(max_iter_arg) if max_iter_arg else None,)- except Exception as exc: # noqa: BLE001 — Tool darf NIE crashen+ except Exception as exc: # noqa: BLE001 — the tool must NEVER crashreturn ToolResult(success=False,output=None,@@ -225,11 +224,11 @@ class DispatchWithReviewTool:return self._serialize_result(result)async def _announce_holding_phrase(self) -> None:- """AD-14: Voice-Holding-Phrase einmal pro Run publishen.+ """AD-14: publish the voice holding phrase once per run.- Bus-Publish failt nie hart — wenn kein Bus injiziert, no-op. Wenn- Bus crash't beim publish, schlucken wir das (Pipeline darf NICHT- wegen TTS-Bus-Fehler abbrechen).+ Bus publish never fails hard — if no bus is injected, it's a no-op.+ If the bus crashes on publish, we swallow it (the pipeline must NOT+ abort because of a TTS-bus error)."""if self._bus is None:return@@ -241,7 +240,7 @@ class DispatchWithReviewTool:language="de",))- except Exception: # noqa: BLE001, S110 — Voice-Side-Effect darf nicht crashen+ except Exception: # noqa: BLE001, S110 — the voice side effect must not crashpass# ------------------------------------------------------------------@@ -249,8 +248,8 @@ class DispatchWithReviewTool:# ------------------------------------------------------------------def _serialize_result(self, result: PipelineResult) -> ToolResult:- # `success` umfasst Cap-Fire (best-of) — der User bekommt ein Ergebnis.- # PRECHECK_FAIL und FAIL sind harte Fehler.+ # `success` includes cap-fire (best-of) — the user gets a result.+ # PRECHECK_FAIL and FAIL are hard errors.success = result.outcome in (PipelineOutcome.SUCCESS,PipelineOutcome.CAP_FIRED,@@ -258,13 +257,13 @@ class DispatchWithReviewTool:warnings: list[str] = []if result.cap_fired and result.final_verdict is not None:- # Top-Issue für TTS-Anzeige (Plan §AD-7)+ # Top issue for TTS display (Plan §AD-7)warnings.append(result.final_verdict.summary)for issue in result.final_verdict.issues[:3]: # max 3warnings.append(f"[{issue.severity}] {issue.description}")- # AD-14: Voice-Outcome-Phrase im Output. Brain rendert das als TTS,- # nachdem der Tool-Call abgeschlossen ist.+ # AD-14: voice outcome phrase in the output. The brain renders this+ # as TTS after the tool call has completed.voice_phrase = self._build_voice_outcome_phrase(result)output: dict[str, Any] = {@@ -311,21 +310,21 @@ class DispatchWithReviewTool:@staticmethoddef _build_voice_outcome_phrase(result: PipelineResult) -> str:- """AD-14: Outcome-Phrase basierend auf PipelineOutcome.+ """AD-14: outcome phrase based on PipelineOutcome.- Templates sind hartcodiert (Plan-§Verboten: keine Mutation via- Voice/Config). Tests matchen byte-genau auf die Phrase-Anfänge.+ Templates are hardcoded (Plan-§Forbidden: no mutation via+ voice/config). Tests match byte-exact on the phrase prefixes."""outcome = result.outcomeif outcome is PipelineOutcome.SUCCESS:summary = (result.final_verdict.summaryif result.final_verdict is not None- else "fertig"+ else "fertig" # i18n-allow: German TTS phrase fallback)return VOICE_OUTCOME_TEMPLATES_DE["success"].format(summary=summary)if outcome is PipelineOutcome.CAP_FIRED:- top_issue = "kleine Restbedenken"+ top_issue = "kleine Restbedenken" # i18n-allow: German TTS phrase fallbackif result.final_verdict is not None:if result.final_verdict.issues:top_issue = result.final_verdict.issues[0].description@@ -336,7 +335,7 @@ class DispatchWithReviewTool:summary = (result.final_verdict.summaryif result.final_verdict is not None- else "Architektur-Defekt"+ else "Architektur-Defekt" # i18n-allow: German TTS phrase fallback)return VOICE_OUTCOME_TEMPLATES_DE["fail"].format(summary=summary)# PRECHECK_FAILdiff --git a/jarvis/plugins/tool/drag.py b/jarvis/plugins/tool/drag.pyindex 121c3ad493..ce42841276 100644--- a/jarvis/plugins/tool/drag.py+++ b/jarvis/plugins/tool/drag.py@@ -39,21 +39,21 @@ class DragTool:name: str = "drag"risk_tier: str = "monitor"description: str = (- "Zieht (Press-Move-Release) von einer Pixel-Koordinate zu einer anderen "- "— fuer Karten/Globus-Rotation, Schwenken oder Schieberegler. "- "Koordinaten sind absolute Bildschirm-Pixel."+ "Drags (press-move-release) from one pixel coordinate to another "+ "— for map/globe rotation, panning, or sliders. "+ "Coordinates are absolute screen pixels.")schema: dict[str, Any] = {"type": "object","properties": {- "x1": {"type": "integer", "description": "Start-X (Pixel)"},- "y1": {"type": "integer", "description": "Start-Y (Pixel)"},- "x2": {"type": "integer", "description": "End-X (Pixel)"},- "y2": {"type": "integer", "description": "End-Y (Pixel)"},+ "x1": {"type": "integer", "description": "Start X (pixels)"},+ "y1": {"type": "integer", "description": "Start Y (pixels)"},+ "x2": {"type": "integer", "description": "End X (pixels)"},+ "y2": {"type": "integer", "description": "End Y (pixels)"},"duration_ms": {"type": "integer","default": _DEFAULT_DRAG_DURATION_MS,- "description": "Dauer der Ziehbewegung in Millisekunden",+ "description": "Duration of the drag motion in milliseconds",},},"required": ["x1", "y1", "x2", "y2"],diff --git a/jarvis/plugins/tool/hotkey.py b/jarvis/plugins/tool/hotkey.pyindex 3f15bf4349..98fc65f12b 100644--- a/jarvis/plugins/tool/hotkey.py+++ b/jarvis/plugins/tool/hotkey.py@@ -1,13 +1,13 @@-"""hotkey-Tool: simuliert Tastenkombinationen wie Strg+T, Alt+Tab, Win+R.+"""hotkey tool: simulates key combos like Ctrl+T, Alt+Tab, Win+R.-Nutzt Win32 ``SendInput`` mit Virtual-Key-Codes als primaeren Pfad. Faellt-bei fehlendem Win32-Subsystem auf ``pyautogui.hotkey`` zurueck — damit-laufen Tests auf Linux/Mac und Headless-CI weiter, auch wenn die echten-Tastenanschlaege nur auf Windows produktiv sind.+Uses Win32 ``SendInput`` with virtual-key codes as the primary path. Falls+back to ``pyautogui.hotkey`` when the Win32 subsystem is missing — so tests+keep running on Linux/Mac and headless CI, even though real keystrokes only+work on Windows.-Risk-Tier: ``monitor`` — eine Tastenkombi kann nicht-reversible Aktionen-ausloesen (Strg+W schliesst Tab, Strg+S oeffnet Dialog). Toast-Notification,-aber kein Approval-Required.+Risk tier: ``monitor`` — a key combo can trigger non-reversible actions+(Ctrl+W closes a tab, Ctrl+S opens a dialog). Toast notification, but no+approval required."""from __future__ import annotations@@ -18,10 +18,10 @@ from typing import Anyfrom jarvis.core.protocols import ExecutionContext, ToolResult-# Virtual-Key-Codes — Auszug aus Microsoft "Virtual Key Codes" Doku.-# Siehe https://learn.microsoft.com/en-us/windows/win32/inputdev/virtual-key-codes-# Wir mappen sowohl Lowercase-Aliase ("ctrl") als auch die offiziellen Namen-# ("control"); fuer Buchstaben/Ziffern berechnen wir den VK on-the-fly.+# Virtual-key codes — excerpt from Microsoft's "Virtual Key Codes" docs.+# See https://learn.microsoft.com/en-us/windows/win32/inputdev/virtual-key-codes+# We map both lowercase aliases ("ctrl") and the official names+# ("control"); for letters/digits we compute the VK on the fly._VK_TABLE: dict[str, int] = {# Modifier"ctrl": 0x11, "control": 0x11,@@ -29,7 +29,7 @@ _VK_TABLE: dict[str, int] = {"alt": 0x12, "menu": 0x12,"win": 0x5B, "windows": 0x5B, "lwin": 0x5B,"rwin": 0x5C,- # Funktions- + Steuertasten+ # Function + control keys"esc": 0x1B, "escape": 0x1B,"enter": 0x0D, "return": 0x0D,"tab": 0x09,@@ -42,7 +42,7 @@ _VK_TABLE: dict[str, int] = {"pagedown": 0x22, "pgdn": 0x22,"left": 0x25, "up": 0x26, "right": 0x27, "down": 0x28,"capslock": 0x14,- # F-Tasten+ # F-keys**{f"f{i}": 0x6F + i for i in range(1, 13)}, # F1 = 0x70 ... F12 = 0x7B# Numpad"numpad0": 0x60, "numpad1": 0x61, "numpad2": 0x62, "numpad3": 0x63,@@ -54,14 +54,14 @@ _VK_TABLE: dict[str, int] = {def _resolve_vk(key: str) -> int | None:- """Liefert den Virtual-Key-Code fuer einen Tasten-Namen, oder None."""+ """Returns the virtual-key code for a key name, or None."""k = key.strip().lower()if not k:return Noneif k in _VK_TABLE:return _VK_TABLE[k]if len(k) == 1:- # A-Z (0x41-0x5A) und 0-9 (0x30-0x39) — VK == ASCII-Wert.+ # A-Z (0x41-0x5A) and 0-9 (0x30-0x39) — VK == ASCII value.if "a" <= k <= "z":return ord(k.upper())if "0" <= k <= "9":diff --git a/jarvis/plugins/tool/screen_snapshot.py b/jarvis/plugins/tool/screen_snapshot.pyindex 7716c644a6..d2c186ba6d 100644--- a/jarvis/plugins/tool/screen_snapshot.py+++ b/jarvis/plugins/tool/screen_snapshot.py@@ -1,29 +1,31 @@-"""screenshot-Tool: erfasst den aktiven Monitor als JPEG fuer Brain-Vision.--Risk-Tier: monitor — Screenshot liest Bildschirminhalt, also werden Aufrufe-standardmaessig geloggt. Whitelist per `[safety.whitelist].tools` erlaubt-Dauer-Einsatz ohne Confirm-Prompt.--Phase A1 (2026-04-25): Default-Format auf JPEG q85 umgestellt. Vision-LLMs-(Claude/Gemini/GPT) rechnen Token-Kosten in Pixel-Area, nicht Bytes — JPEG-schrumpft die Payload um ~8x bei identischen Tokens. Quality 85 ist der-Sweet-Spot: visuell verlustfrei fuer Text + UI-Elements, deutlich kleiner-als PNG. Iteratives Shrinking entfaellt — quality-Param erledigt das.--Multi-Monitor-Fix: per Default folgt der Capture dem Foreground-Window-(``select_capture_monitor`` aus ``jarvis.vision.screenshot``). Damit sieht-das Brain den Bildschirm, auf dem der User gerade aktiv ist — nicht-hardcoded den mss-Primary, der auf Multi-Monitor-Setups oft leer ist.--Ablauf in `execute`:-1. ``mss.mss().monitors`` enumerieren -> ``select_capture_monitor`` waehlt- den richtigen Monitor (Foreground-Window-Lookup).-2. `PIL.Image.frombytes("RGB", size, raw.rgb)` baut ein Pillow-Image.-3. JPEG q85 — typisch 100-300 KB fuer 4K-Screenshots. Falls > _MAX_BYTES- (Edge-Case bei sehr detail-dichten Screens), Quality runter bis es passt.+"""screenshot tool: captures the active monitor as JPEG for Brain vision.++Risk tier: monitor — a screenshot reads screen content, so calls are logged+by default. A whitelist entry under `[safety.whitelist].tools` allows+continuous use without a confirm prompt.++Phase A1 (2026-04-25): switched the default format to JPEG q85. Vision LLMs+(Claude/Gemini/GPT) charge token cost by pixel area, not bytes — JPEG+shrinks the payload by ~8x for identical tokens. Quality 85 is the+sweet spot: visually lossless for text + UI elements, noticeably smaller+than PNG. Iterative shrinking is no longer needed — the quality param+handles that.++Multi-monitor fix: by default the capture follows the foreground window+(``select_capture_monitor`` from ``jarvis.vision.screenshot``). That way+the brain sees the screen the user is actually active on — instead of+hardcoding the mss primary, which is often blank on multi-monitor setups.++Flow in `execute`:+1. Enumerate ``mss.mss().monitors`` -> ``select_capture_monitor`` picks+ the right monitor (foreground-window lookup).+2. `PIL.Image.frombytes("RGB", size, raw.rgb)` builds a Pillow image.+3. JPEG q85 — typically 100-300 KB for 4K screenshots. If it exceeds+ _MAX_BYTES (edge case on very detail-dense screens), quality is lowered+ until it fits.4. Result: `artifacts=[{"type": "image", "mime": "image/jpeg", "data":- <base64>}]` damit das Vision-capable Brain den Screenshot direkt- konsumieren kann.+ <base64>}]` so the vision-capable brain can consume the screenshot+ directly."""from __future__ import annotations@@ -37,20 +39,21 @@ from jarvis.vision.screenshot import select_capture_monitor_MAX_BYTES = 500_000_DEFAULT_JPEG_QUALITY = 85_MIN_JPEG_QUALITY = 50-# Vision-LLMs (Claude/Gemini/GPT) skalieren intern auf ~1568 px Laengsseite-# zur Token-Berechnung. 4K-Captures (3840x2160) sind reine Verschwendung —-# sie kosten ~3x Bytes und Tokens ohne sichtbaren Vision-Vorteil. 2048 px-# Laengsseite ist der Sweet-Spot: deutlich groesser als das interne LLM--# Resampling-Ziel (kein Detail-Verlust), aber hart genug um das _MAX_BYTES--# Budget bei 4K-Multi-Monitor zuverlaessig zu treffen.+# Vision LLMs (Claude/Gemini/GPT) internally downscale to ~1568 px on the+# longest side for token accounting. 4K captures (3840x2160) are pure+# waste — they cost ~3x the bytes and tokens with no visible vision benefit.+# 2048 px on the longest side is the sweet spot: noticeably larger than the+# internal LLM resampling target (no detail loss), but tight enough to+# reliably hit the _MAX_BYTES budget on 4K multi-monitor captures._MAX_DIMENSION = 2048def _resize_for_budget(image: Any, max_dim: int) -> Any:- """Skaliert ein Pillow-Image proportional auf maximal ``max_dim`` Laengsseite.+ """Proportionally scales a Pillow image to at most ``max_dim`` on its+ longest side.- Identitaet, wenn das Bild bereits kleiner ist. Damit kostet der Aufruf- auf 1440p-Captures nichts.+ Identity when the image is already smaller. So the call costs nothing+ on 1440p captures."""w, h = image.sizelongest = max(w, h)@@ -58,25 +61,25 @@ def _resize_for_budget(image: Any, max_dim: int) -> Any:return imagescale = max_dim / longestnew_size = (max(1, int(round(w * scale))), max(1, int(round(h * scale))))- # Late-Import damit das Modul auch ohne PIL importierbar bleibt;- # _encode_with_budget wird ohnehin nur aus Pfaden gerufen, die PIL haben.+ # Late import so the module stays importable without PIL; _encode_with_budget+ # is only ever called from paths that have PIL anyway.from PIL import Image # noqa: PLC0415return image.resize(new_size, resample=Image.Resampling.LANCZOS)def _encode_jpeg(image: Any, quality: int) -> bytes:- """Serialisiert ein Pillow-Image als JPEG mit gegebener Qualitaet."""+ """Serializes a Pillow image as JPEG at the given quality."""buf = io.BytesIO()image.save(buf, format="JPEG", quality=quality, optimize=True)return buf.getvalue()def _encode_with_budget(image: Any, max_bytes: int) -> bytes:- """JPEG q85 zuerst; bei Overshoot Quality reduzieren bis _MIN_JPEG_QUALITY.+ """JPEG q85 first; on overshoot, lower quality down to _MIN_JPEG_QUALITY.- Vor dem Encode wird auf ``_MAX_DIMENSION`` Laengsseite runtergescaled,- damit 4K-Captures (Multi-Monitor) das Byte-Budget zuverlaessig treffen.+ Before encoding, the image is downscaled to ``_MAX_DIMENSION`` on its+ longest side so 4K captures (multi-monitor) reliably hit the byte budget."""image = _resize_for_budget(image, _MAX_DIMENSION)quality = _DEFAULT_JPEG_QUALITY@@ -98,7 +101,7 @@ class ScreenSnapshotTool:"properties": {"reason": {"type": "string",- "description": "Warum der Screenshot gebraucht wird (fuer Log)",+ "description": "Why the screenshot is needed (for the log)",}},"required": [],@@ -114,7 +117,7 @@ class ScreenSnapshotTool:return ToolResult(success=False,output=None,- error=f"Dependency fehlt: {exc.name or exc}",+ error=f"Missing dependency: {exc.name or exc}",)try:@@ -124,16 +127,16 @@ class ScreenSnapshotTool:return ToolResult(success=False,output=None,- error="Kein Primaer-Monitor gefunden",+ error="No primary monitor found",)target = select_capture_monitor(monitors, strategy="foreground")raw = sct.grab(target)image = Image.frombytes("RGB", raw.size, raw.rgb)- except Exception as exc: # noqa: BLE001 — mss/Display-Fehler sind divers+ except Exception as exc: # noqa: BLE001 — mss/display errors are variedreturn ToolResult(success=False,output=None,- error=f"Screenshot fehlgeschlagen: {exc}",+ error=f"Screenshot failed: {exc}",)jpeg_bytes = _encode_with_budget(image, _MAX_BYTES)diff --git a/jarvis/plugins/tool/search_web.py b/jarvis/plugins/tool/search_web.pyindex c2b1bc1b7a..54f4510339 100644--- a/jarvis/plugins/tool/search_web.py+++ b/jarvis/plugins/tool/search_web.py@@ -1,4 +1,4 @@-"""search_web-Tool: DuckDuckGo Instant-Answer-API (kein Key nötig).+"""search_web tool: DuckDuckGo Instant-Answer API (no key needed).Risk-Tier: safe — reines Readonly.@@ -40,7 +40,7 @@ _GEOCODE_URL: Final[str] = "https://geocoding-api.open-meteo.com/v1/search"_FORECAST_URL: Final[str] = "https://api.open-meteo.com/v1/forecast"# How the brain must consume a non-empty result set. Live forensic 2026-06-28-# (voice session, Turn 4 "wie viele Punkte brauche ich fuer eine 1"): the brain+# (voice session, Turn 4 "wie viele Punkte brauche ich fuer eine 1"): the brain # i18n-allow# (Gemini) concatenated the raw DuckDuckGo hits — titles, snippets, dates, URLs,# "Weitere Ergebnisse von www.gutefrage.net", a truncated "...Ma" — and read the# whole list aloud instead of answering. The results array carries NO consume@@ -213,27 +213,27 @@ class SearchWebTool:# read it as an unwanted research spawn for a trivial question. Pinned by# tests/unit/brain/test_search_web_freshness_doctrine.py.description: str = (- "Web-Suche via DuckDuckGo mit Kurz-Zusammenfassung — fuer FRISCHE, " # i18n-allow- "zeitkritische Fakten. NUTZE DIESES TOOL nur wenn die Antwort AKTUELLE " # i18n-allow- "oder volatile Information braucht, die sich seit deinem Wissensstand " # i18n-allow- "geaendert haben kann: aktuelle News, heutige Preise/Boersenkurse, " # i18n-allow- "Wetter, Sport-Ergebnisse, laufende Ereignisse, " # i18n-allow- "'neueste/aktuelle/heute/gerade' — ODER wenn der User AUSDRUECKLICH zu " # i18n-allow- "suchen bittet ('such mal', 'google das', 'recherchier'). " # i18n-allow- "NICHT NUTZEN fuer Evergreen-/Allgemeinwissen, das du selbst direkt " # i18n-allow- "beantworten kannst (Geografie, Geschichte, Definitionen, 'wie " # i18n-allow- "funktioniert X', allgemeine Ablaeufe / Vorgehensweisen wie 'was muss " # i18n-allow- "ich beim Auswandern beachten', bekannte Konzepte) — solche Fragen " # i18n-allow- "beantwortest du direkt aus deinem Wissen, ohne Suche. " # i18n-allow- "Fuer Wetterfragen die Location in die query schreiben (z.B. 'weather " # i18n-allow- "Berlin tomorrow'). " # i18n-allow- "NICHT NUTZEN fuer Aktionen auf verbundenen Systemen (dafuer cli_* oder " # i18n-allow- "MCP-Tools) — 'meine X' oder 'starte X' sind NIE Such-Intent." # i18n-allow+ "Web search via DuckDuckGo with a short summary — for FRESH, "+ "time-critical facts. USE THIS TOOL only when the answer needs CURRENT "+ "or volatile information that may have changed since your knowledge "+ "cutoff: current news, today's prices/stock quotes, weather, sports "+ "results, ongoing events, 'latest/current/today/right now' — OR when "+ "the user EXPLICITLY asks you to search ('search for that', 'google "+ "that', 'look it up'). "+ "DO NOT USE for evergreen/general knowledge you can answer directly "+ "yourself (geography, history, definitions, 'how does X work', general "+ "procedures/processes like 'what do I need to consider when "+ "emigrating', well-known concepts) — answer such questions directly "+ "from your own knowledge, without searching. "+ "For weather questions, put the location in the query (e.g. 'weather "+ "Berlin tomorrow'). "+ "DO NOT USE for actions on connected systems (use cli_* or MCP tools "+ "for that) — 'my X' or 'start X' is NEVER search intent.")schema: dict[str, Any] = {"type": "object","properties": {- "query": {"type": "string", "description": "Suchanfrage"},+ "query": {"type": "string", "description": "Search query"},"max_results": {"type": "integer", "default": 5},},"required": ["query"],@@ -243,12 +243,12 @@ class SearchWebTool:query = (args.get("query") or "").strip()max_results = int(args.get("max_results", 5))if not query:- return ToolResult(success=False, output=None, error="query fehlt")+ return ToolResult(success=False, output=None, error="query missing")try:import httpxexcept Exception as exc: # noqa: BLE001- return ToolResult(success=False, output=None, error=f"httpx nicht verfügbar: {exc}")+ return ToolResult(success=False, output=None, error=f"httpx not available: {exc}")# Weather fast-path: DDG instant answers have no weather data (every# call returns empty), so weather intents go to Open-Meteo. The wholediff --git a/jarvis/plugins/tool/start_preview_server.py b/jarvis/plugins/tool/start_preview_server.pyindex ea5e08fad5..eccf873779 100644--- a/jarvis/plugins/tool/start_preview_server.py+++ b/jarvis/plugins/tool/start_preview_server.py@@ -1,8 +1,8 @@-"""StartPreviewServerTool — registriert einen laufenden Dev-Server in der Preview-Registry.+"""StartPreviewServerTool — registers a running dev server in the preview registry.-Sub-Agent ruft dieses Tool auf sobald sein Dev-Server laeuft.-Das Tool publisht ``PreviewServerStarted`` auf den Bus → die PreviewRegistry-aktualisiert die Liste → das Frontend zeigt den iframe in der Previews-View.+The Jarvis-Agent worker calls this tool as soon as its dev server is running.+The tool publishes ``PreviewServerStarted`` on the bus → the PreviewRegistry+updates its list → the frontend shows the iframe in the Previews view."""from __future__ import annotations@@ -14,22 +14,22 @@ from jarvis.core.protocols import ExecutionContext, ToolResultclass StartPreviewServerTool:name = "start_preview_server"description = (- "Registriert einen laufenden localhost-Dev-Server in der Jarvis-UI "- "(Previews-Sidebar-View). Aufruf NACHDEM der Server laeuft."+ "Registers a running localhost dev server in the Jarvis UI "+ "(Previews sidebar view). Call AFTER the server is running.")risk_tier = "safe"schema: dict[str, Any] = {"type": "object","properties": {- "port": {"type": "integer", "description": "Port des Dev-Servers."},+ "port": {"type": "integer", "description": "Port of the dev server."},"title": {"type": "string",- "description": "Anzeige-Name in der UI.",+ "description": "Display name in the UI.","default": "",},"kind": {"type": "string",- "description": "Server-Typ: 'vite' | 'flask' | 'django' | 'static' | ...",+ "description": "Server type: 'vite' | 'flask' | 'django' | 'static' | ...","default": "unknown",},},@@ -42,8 +42,8 @@ class StartPreviewServerTool:async def execute(self, args: dict[str, Any], ctx: ExecutionContext) -> ToolResult:port = int(args.get("port") or 0)if not port:- return ToolResult(success=False, error="port ist 0 oder leer")- title = (args.get("title") or f"Dev-Server :{port}").strip()+ return ToolResult(success=False, error="port is 0 or empty")+ title = (args.get("title") or f"Dev server :{port}").strip()kind = (args.get("kind") or "unknown").strip()url = f"http://localhost:{port}"@@ -61,7 +61,7 @@ class StartPreviewServerTool:)return ToolResult(success=True,- output=f"Dev-Server '{title}' auf {url} in Previews registriert.",+ output=f"Dev server '{title}' registered at {url} in Previews.",)except Exception as exc: # noqa: BLE001- return ToolResult(success=False, error=f"Preview-Registrierung fehlgeschlagen: {exc}")+ return ToolResult(success=False, error=f"Preview registration failed: {exc}")diff --git a/jarvis/plugins/tool/switch_window.py b/jarvis/plugins/tool/switch_window.pyindex 338ed7e17d..92eeadc911 100644--- a/jarvis/plugins/tool/switch_window.py+++ b/jarvis/plugins/tool/switch_window.py@@ -1,12 +1,12 @@-"""switch_window-Tool: bringt ein Fenster nach Titel-Substring in den Vordergrund.+"""switch_window tool: brings a window to the foreground by title substring.The window enumeration / focus logic now lives in``jarvis.platform.window_state`` (so ``open_app`` and the Computer-Use loop canreuse it). This tool delegates to the per-OS focus helpers there and keeps itsexact user-facing readback strings (AD-7: the Windows path is unchanged).-Risk-Tier: ``monitor`` — Fenster-Switches sind reversibel, aber der Fokus--Wechsel kann ungewollte Aktionen ausloesen, wenn der User gerade tippt.+Risk tier: ``monitor`` — window switches are reversible, but the focus+change can trigger unwanted actions if the user is currently typing."""from __future__ import annotations@@ -27,15 +27,15 @@ class SwitchWindowTool:name: str = "switch_window"risk_tier: str = "monitor"description: str = (- "Wechselt zu einem Top-Level-Fenster, dessen Titel den uebergebenen "- "Substring enthaelt. Case-insensitive. Restored minimierte Fenster."+ "Switches to a top-level window whose title contains the given "+ "substring. Case-insensitive. Restores minimized windows.")schema: dict[str, Any] = {"type": "object","properties": {"title_contains": {"type": "string",- "description": "Substring, der im Fenstertitel vorkommen muss",+ "description": "Substring that must appear in the window title",},},"required": ["title_contains"],@@ -46,7 +46,7 @@ class SwitchWindowTool:if not isinstance(title, str) or not title.strip():return ToolResult(success=False, output=None,- error="title_contains fehlt oder leer",+ error="title_contains missing or empty",)plat = detect_platform()@@ -59,11 +59,11 @@ class SwitchWindowTool:except Exception as exc: # noqa: BLE001return ToolResult(success=False, output=None,- error=f"Window-Enumeration fehlgeschlagen: {exc}",+ error=f"Window enumeration failed: {exc}",)if found:- return ToolResult(success=True, output=f"Fokus auf Fenster: {msg}")+ return ToolResult(success=True, output=f"Focused window: {msg}")return ToolResult(success=False, output=None, error=msg)async def _execute_non_windows(self, plat: str, title: str) -> ToolResult:diff --git a/jarvis/plugins/tool/type_text.py b/jarvis/plugins/tool/type_text.pyindex 66433b325d..63ec98e406 100644--- a/jarvis/plugins/tool/type_text.py+++ b/jarvis/plugins/tool/type_text.py@@ -80,9 +80,9 @@ def _build_windows_input_types() -> Any:def _send_text_windows(text: str, delay_s: float) -> None:- """Sendet Unicode-Text an das aktive Windows-Fenster via SendInput."""+ """Sends Unicode text to the active Windows window via SendInput."""if os.name != "nt":- raise RuntimeError("Native Text-Eingabe ohne pyautogui ist nur auf Windows verfuegbar")+ raise RuntimeError("Native text input without pyautogui is only available on Windows")import ctypes@@ -129,15 +129,15 @@ class TypeTextTool:name: str = "type_text"risk_tier: str = "safe"description: str = (- "Tippt Text in das gerade aktive Fenster (als wuerde der User ihn eingeben)."+ "Types text into the currently active window (as if the user typed it).")schema: dict[str, Any] = {"type": "object","properties": {- "text": {"type": "string", "description": "Zu tippender Text"},+ "text": {"type": "string", "description": "Text to type"},"delay_s": {"type": "number",- "description": "Pause zwischen Tastenanschlaegen in Sekunden",+ "description": "Pause between keystrokes in seconds","default": 0.02,},},diff --git a/jarvis/plugins/tool/verify_localhost.py b/jarvis/plugins/tool/verify_localhost.pyindex eb05cde6c1..dc06e6b501 100644--- a/jarvis/plugins/tool/verify_localhost.py+++ b/jarvis/plugins/tool/verify_localhost.py@@ -1,4 +1,4 @@-"""VerifyLocalhostTool — HTTP-Check gegen localhost mit optionalem Screenshot."""+"""VerifyLocalhostTool — HTTP check against localhost with an optional screenshot."""from __future__ import annotationsfrom typing import Any@@ -9,27 +9,27 @@ from jarvis.core.protocols import ExecutionContext, ToolResultclass VerifyLocalhostTool:name = "verify_localhost"description = (- "Prueft einen laufenden localhost-Server per HTTP. "- "Optionaler Screenshot via mss fuer visuelle Verifikation."+ "Checks a running localhost server via HTTP. "+ "Optional screenshot via mss for visual verification.")risk_tier = "safe"schema: dict[str, Any] = {"type": "object","properties": {- "port": {"type": "integer", "description": "Localhost-Port."},+ "port": {"type": "integer", "description": "Localhost port."},"path": {"type": "string",- "description": "URL-Pfad (Default: '/').",+ "description": "URL path (default: '/').","default": "/",},"expected_substring": {"type": "string",- "description": "Optionaler Substring im Body.",+ "description": "Optional substring expected in the body.","default": "",},"take_screenshot": {"type": "boolean",- "description": "Screenshot des Browsers machen (via mss, nur sichtbarer Screen).",+ "description": "Take a screenshot of the browser (via mss, visible screen only).","default": False,},},@@ -39,7 +39,7 @@ class VerifyLocalhostTool:async def execute(self, args: dict[str, Any], ctx: ExecutionContext) -> ToolResult:port = int(args.get("port") or 0)if not port:- return ToolResult(success=False, error="port ist 0 oder leer")+ return ToolResult(success=False, error="port is 0 or empty")path = (args.get("path") or "/").strip()if not path.startswith("/"):path = "/" + path@@ -56,13 +56,13 @@ class VerifyLocalhostTool:ok = r.status_code == 200if ok and substring and substring not in r.text:ok = False- msg = f"HTTP 200 aber Substring '{substring}' fehlt ({url})"+ msg = f"HTTP 200 but substring '{substring}' missing ({url})"elif not ok:msg = f"HTTP {r.status_code} ({url})"else:msg = f"HTTP 200 OK ({url})"except Exception as exc: # noqa: BLE001- return ToolResult(success=False, error=f"Verbindung zu {url} fehlgeschlagen: {exc}")+ return ToolResult(success=False, error=f"Connection to {url} failed: {exc}")if take_screenshot:try:diff --git a/jarvis/plugins/tool/verify_via_curl.py b/jarvis/plugins/tool/verify_via_curl.pyindex 7f641fca9e..6d4a7e99cc 100644--- a/jarvis/plugins/tool/verify_via_curl.py+++ b/jarvis/plugins/tool/verify_via_curl.py@@ -1,4 +1,4 @@-"""VerifyViaCurlTool — HTTP-Check fuer Sub-Agent-Verifikation."""+"""VerifyViaCurlTool — HTTP check for Jarvis-Agent worker verification."""from __future__ import annotationsfrom typing import Any@@ -9,22 +9,22 @@ from jarvis.core.protocols import ExecutionContext, ToolResultclass VerifyViaCurlTool:name = "verify_via_curl"description = (- "Prueft eine URL per HTTP-GET. Gibt Erfolg zurueck wenn Status 200 "- "und optionaler Substring im Body gefunden."+ "Checks a URL via HTTP GET. Returns success if status 200 "+ "and an optional substring is found in the body.")risk_tier = "safe"schema: dict[str, Any] = {"type": "object","properties": {- "url": {"type": "string", "description": "URL die geprueft werden soll."},+ "url": {"type": "string", "description": "URL to check."},"expected_substring": {"type": "string",- "description": "Optionaler Substring der im Body erwartet wird.",+ "description": "Optional substring expected in the body.","default": "",},"timeout_s": {"type": "number",- "description": "Timeout in Sekunden (Default 5).",+ "description": "Timeout in seconds (default 5).","default": 5.0,},},@@ -34,7 +34,7 @@ class VerifyViaCurlTool:async def execute(self, args: dict[str, Any], ctx: ExecutionContext) -> ToolResult:url = (args.get("url") or "").strip()if not url:- return ToolResult(success=False, error="url ist leer")+ return ToolResult(success=False, error="url is empty")substring = (args.get("expected_substring") or "").strip()timeout = float(args.get("timeout_s") or 5.0)@@ -45,16 +45,16 @@ class VerifyViaCurlTool:if r.status_code != 200:return ToolResult(success=False,- output=f"HTTP {r.status_code} fuer {url}",+ output=f"HTTP {r.status_code} for {url}",)if substring and substring not in r.text:return ToolResult(success=False,- output=f"Substring '{substring}' nicht im Body von {url}",+ output=f"Substring '{substring}' not found in body of {url}",)return ToolResult(success=True,- output=f"HTTP 200 OK ({url})" + (f" — '{substring}' gefunden" if substring else ""),+ output=f"HTTP 200 OK ({url})" + (f" — '{substring}' found" if substring else ""),)except Exception as exc: # noqa: BLE001- return ToolResult(success=False, error=f"Request fehlgeschlagen: {exc}")+ return ToolResult(success=False, error=f"Request failed: {exc}")diff --git a/jarvis/plugins/tool/wait_for_ui_state.py b/jarvis/plugins/tool/wait_for_ui_state.pyindex 534d3d4981..abe600fb85 100644--- a/jarvis/plugins/tool/wait_for_ui_state.py+++ b/jarvis/plugins/tool/wait_for_ui_state.py@@ -1,14 +1,14 @@-"""wait_for_ui_state-Tool: pollt bis ein gewuenschter UI-State erreicht ist.+"""wait_for_ui_state tool: polls until a desired UI state is reached.-Beispiele:- - ``wait_for_ui_state(title_contains='Notepad', timeout_s=5)`` wartet bis- ein Fenster mit "Notepad" im Titel sichtbar ist.- - ``wait_for_ui_state(text_contains='OK')`` wartet bis irgendwo im UIA-- Tree ein Element mit Text "OK" erscheint (z.B. ein Dialog-Button).+Examples:+ - ``wait_for_ui_state(title_contains='Notepad', timeout_s=5)`` waits until+ a window with "Notepad" in its title is visible.+ - ``wait_for_ui_state(text_contains='OK')`` waits until an element with+ text "OK" appears anywhere in the UIA tree (e.g. a dialog button).-Polling-Intervall: 250ms. Default-Timeout: 5s. Hartes Maximum: 60s.+Polling interval: 250ms. Default timeout: 5s. Hard maximum: 60s.-Risk-Tier: ``safe`` — reine Beobachtung, kein State-Change.+Risk tier: ``safe`` — pure observation, no state change."""from __future__ import annotations@@ -28,25 +28,25 @@ class WaitForUIStateTool:name: str = "wait_for_ui_state"risk_tier: str = "safe"description: str = (- "Wartet bis ein UI-Match auftritt — entweder ein Fenster-Titel-"- "Substring (title_contains) oder ein Text irgendwo im UIA-Tree "- "(text_contains). Liefert nach Erfolg den gefundenen Titel zurueck."+ "Waits until a UI match occurs — either a window-title substring "+ "(title_contains) or text appearing anywhere in the UIA tree "+ "(text_contains). Returns the found title on success.")schema: dict[str, Any] = {"type": "object","properties": {"title_contains": {"type": "string",- "description": "Substring, der im Fenstertitel auftauchen muss",+ "description": "Substring that must appear in the window title",},"text_contains": {"type": "string",- "description": "Substring, der irgendwo im UIA-Tree erscheinen muss",+ "description": "Substring that must appear anywhere in the UIA tree",},"timeout_s": {"type": "number","default": _DEFAULT_TIMEOUT_S,- "description": f"Maximale Wartezeit (max {_MAX_TIMEOUT_S}s)",+ "description": f"Maximum wait time (max {_MAX_TIMEOUT_S}s)",},},"required": [],@@ -61,7 +61,7 @@ class WaitForUIStateTool:if not title_needle and not text_needle:return ToolResult(success=False, output=None,- error="Mindestens eines von 'title_contains' oder 'text_contains' angeben",+ error="Provide at least one of 'title_contains' or 'text_contains'",)timeout = min(float(args.get("timeout_s", _DEFAULT_TIMEOUT_S)), _MAX_TIMEOUT_S)@@ -84,13 +84,13 @@ class WaitForUIStateTool:obs = await source.observe()last_observed_title = obs.window_titleexcept Exception as exc: # noqa: BLE001- # UIA kann transient failen (z.B. waehrend Window-Animationen).- # Wir loggen still und versuchen es im naechsten Tick weiter.+ # UIA can fail transiently (e.g. during window animations).+ # We log silently and keep retrying on the next tick.obs = Noneif time.monotonic() >= deadline:return ToolResult(success=False, output=None,- error=f"UIA-Polling failed durchgehend: {exc}",+ error=f"UIA polling failed consistently: {exc}",)if obs is not None:@@ -116,9 +116,9 @@ class WaitForUIStateTool:return ToolResult(success=False, output=None,error=(- f"Timeout nach {timeout}s. "- f"Letzter Fenster-Titel: {last_observed_title!r}. "- f"Suchte: title~{title_needle!r}, text~{text_needle!r}"+ f"Timed out after {timeout}s. "+ f"Last window title: {last_observed_title!r}. "+ f"Searched for: title~{title_needle!r}, text~{text_needle!r}"),)await asyncio.sleep(_POLL_INTERVAL_S)diff --git a/jarvis/plugins/tool/whoami.py b/jarvis/plugins/tool/whoami.pyindex b5b2ffdb8f..8b5ef7581d 100644--- a/jarvis/plugins/tool/whoami.py+++ b/jarvis/plugins/tool/whoami.py@@ -1,13 +1,13 @@-"""whoami-Tool: erzaehlt dem User, was Jarvis ueber ihn weiss.+"""whoami tool: tells the user what Jarvis knows about them.-Wird vom Brain aufgerufen wenn der User fragt "Was weisst du ueber mich?",-"Erzaehl mir was du dir gemerkt hast", "What do you know about me?" etc.+Called by the brain when the user asks "What do you know about me?",+"Tell me what you've learned about me", "What do you know about me?" etc.-Output ist eine **natuerlich gesprochene** Zusammenfassung (3-4 Saetze) —-kein Markdown, keine Aufzaehlungszeichen, keine Emojis. Landet direkt in-der TTS und wird dem User vorgelesen.+Output is a **naturally spoken** summary (3-4 sentences) — no Markdown,+no bullet points, no emojis. Goes straight into TTS and is read aloud+to the user.-Risk-Tier: safe — reiner Read-Only-Zugriff auf USER.md + people/*.md.+Risk tier: safe — pure read-only access to USER.md + people/*.md."""from __future__ import annotations@@ -22,7 +22,7 @@ class WhoAmITool:name: str = "whoami"risk_tier: str = "safe"description: str = (- "Liefert eine Zusammenfassung was Jarvis ueber den User weiss."+ "Returns a summary of what Jarvis knows about the user.")schema: dict[str, Any] = {"type": "object",@@ -31,8 +31,8 @@ class WhoAmITool:"type": "string","enum": ["short", "full"],"description": (- "'short' (default) = 3-4 Saetze zum Vorlesen, "- "'full' = ausfuehrlicher mit allen bekannten Feldern."+ "'short' (default) = 3-4 sentences to read aloud, "+ "'full' = more detailed, with all known fields."),"default": "short",},@@ -46,14 +46,15 @@ class WhoAmITool:profile: UserProfile | None = None,people: PersonStore | None = None,) -> None:- """Dependencies per Constructor — `ExecutionContext` hat keinen Profile-Zugriff.+ """Dependencies injected via constructor — `ExecutionContext` has no+ profile access.Args:- profile: Das UserProfile-Handle (USER.md). Kann `None` sein, wenn- der Workspace nicht geladen werden konnte — dann liefert- `execute` eine freundliche Fehlermeldung statt zu crashen.- people: Optionaler `PersonStore` fuer die "Laura als Partnerin,- Paul als Kollegen"-Zeile.+ profile: The UserProfile handle (USER.md). Can be `None` if the+ workspace could not be loaded — in that case `execute`+ returns a friendly error message instead of crashing.+ people: Optional `PersonStore` for the "Laura as partner,+ Paul as colleague" line."""self._profile = profileself._people = people@@ -64,13 +65,13 @@ class WhoAmITool:async def execute(self, args: dict[str, Any], ctx: ExecutionContext) -> ToolResult:if self._profile is None:- # Workspace konnte nicht geladen werden — sanfte Fehlermeldung.+ # Workspace could not be loaded — gentle spoken fallback (below).return ToolResult(success=True,output=(- "Ich habe gerade keinen Zugriff auf Dein Profil — "- "das Workspace ist noch nicht eingerichtet. Sag Bescheid "- "wenn Du den Bootstrap starten willst."+ "Ich habe gerade keinen Zugriff auf Dein Profil — " # i18n-allow+ "das Workspace ist noch nicht eingerichtet. Sag Bescheid " # i18n-allow+ "wenn Du den Bootstrap starten willst." # i18n-allow),)@@ -95,11 +96,12 @@ class WhoAmITool:# ------------------------------------------------------------------def _render_summary(self, meta: dict[str, Any], detail_level: str) -> str:- """Baut die gesprochene Zusammenfassung aus den Profile-Feldern.+ """Builds the spoken summary from the profile fields.- Strategie: wir sammeln die staerksten Signale (Name, Kommunikationsstil,- Werte, Pet Peeves) in natuerlichen Saetzen. Kein "Laut Profil...",- sondern direkt "Du heisst Ruben und magst direkte Antworten."+ Strategy: we collect the strongest signals (name, communication style,+ values, pet peeves) into natural sentences. Never "According to your+ profile...", but directly "You're called Ruben and you like direct+ answers.""""identity = meta.get("identity", {}) or {}communication = meta.get("communication", {}) or {}@@ -110,7 +112,7 @@ class WhoAmITool:name = identity.get("name")address = identity.get("preferred_address") or name- # --- Empty-Profile-Check: nur Name (oder nicht mal das) vorhanden ---+ # --- Empty-profile check: only name (or not even that) present ---has_signal = any([communication.get("directness") is not None,communication.get("formality") is not None,@@ -127,119 +129,119 @@ class WhoAmITool:if not has_signal and not has_people:if name:return (- f"Noch nicht viel, ausser Deinem Namen — Du heisst {name}. "- f"Willst Du kurz durch den Bootstrap, damit ich Dich besser kennenlerne?"+ f"Noch nicht viel, ausser Deinem Namen — Du heisst {name}. " # i18n-allow+ f"Willst Du kurz durch den Bootstrap, damit ich Dich besser kennenlerne?" # i18n-allow)return (- "Noch gar nichts — ich kenne nicht mal Deinen Namen. "- "Willst Du kurz durch den Bootstrap?"+ "Noch gar nichts — ich kenne nicht mal Deinen Namen. " # i18n-allow+ "Willst Du kurz durch den Bootstrap?" # i18n-allow)- # --- Satz 1: Name + Anrede ---+ # --- Sentence 1: name + form of address ---sentences: list[str] = []if name:if address and address != name:- sentences.append(f"Du heisst {name} und ich spreche Dich als {address} an.")+ sentences.append(f"Du heisst {name} und ich spreche Dich als {address} an.") # i18n-allowelse:- sentences.append(f"Du heisst {name}.")+ sentences.append(f"Du heisst {name}.") # i18n-allow- # --- Satz 2: Kommunikationsstil in natuerlicher Sprache ---+ # --- Sentence 2: communication style, in natural language ---comm_phrase = self._communication_phrase(communication)if comm_phrase:sentences.append(comm_phrase)- # --- Satz 3: Werte + Pet Peeves ---+ # --- Sentence 3: values + pet peeves ---values_phrase = self._values_phrase(values)if values_phrase:sentences.append(values_phrase)- # --- Satz 4: Arbeitsweise / Feedback-Stil (nur bei full oder falls noch Platz) ---+ # --- Sentence 4: work style / feedback style (only for full, or if there's still room) ---if detail_level == "full":ws_phrase = self._work_style_phrase(work_style, relationship)if ws_phrase:sentences.append(ws_phrase)elif len(sentences) < 3:- # Bei short-Mode: max 1 zusaetzlicher Satz wenn noch wenig gesagt+ # In short mode: at most 1 extra sentence if little has been said so farws_phrase = self._work_style_phrase(work_style, relationship)if ws_phrase:sentences.append(ws_phrase)- # --- Personen-Zeile ---+ # --- People line ---people_phrase = self._people_phrase()if people_phrase:sentences.append(people_phrase)- # Short-Mode: auf max 4 Saetze cappen (Personen-Zeile darf zusaetzlich sein).+ # Short mode: cap at max 4 sentences (the people line may be additional).if detail_level == "short" and len(sentences) > 4:sentences = sentences[:4]return " ".join(sentences)# ------------------------------------------------------------------- # Satzbausteine+ # Sentence building blocks# ------------------------------------------------------------------def _communication_phrase(self, comm: dict[str, Any]) -> str:- """Baut einen natuerlichen Satz zum Kommunikationsstil."""+ """Builds a natural sentence about the communication style."""traits: list[str] = []directness = comm.get("directness")if isinstance(directness, (int, float)):if directness >= 4:- traits.append("magst direkte, klare Antworten")+ traits.append("magst direkte, klare Antworten") # i18n-allowelif directness <= 2:- traits.append("bevorzugst eher diplomatische Formulierungen")+ traits.append("bevorzugst eher diplomatische Formulierungen") # i18n-allowformality = comm.get("formality")if isinstance(formality, (int, float)):if formality <= 2:- traits.append("stehst auf lockeren Ton")+ traits.append("stehst auf lockeren Ton") # i18n-allowelif formality >= 4:- traits.append("magst es eher foermlich")+ traits.append("magst es eher foermlich") # i18n-allowverbosity = comm.get("verbosity")if verbosity == "concise":- traits.append("willst knappe Antworten")+ traits.append("willst knappe Antworten") # i18n-allowelif verbosity == "detailed":- traits.append("magst ausfuehrliche Erklaerungen")+ traits.append("magst ausfuehrliche Erklaerungen") # i18n-allowhumor = comm.get("humor_types") or []if humor:humor_str = " und ".join(humor) if len(humor) <= 2 else ", ".join(humor)- traits.append(f"schaetzt {humor_str} Humor")+ traits.append(f"schaetzt {humor_str} Humor") # i18n-allowif comm.get("emoji_ok") is False:- traits.append("willst keine Emojis")+ traits.append("willst keine Emojis") # i18n-allowif not traits:return ""if len(traits) == 1:- return f"Du {traits[0]}."+ return f"Du {traits[0]}." # i18n-allowif len(traits) == 2:- return f"Du {traits[0]} und {traits[1]}."- # 3+: mit Kommas, letztes mit "und"+ return f"Du {traits[0]} und {traits[1]}." # i18n-allow+ # 3+: comma-separated, last one joined with "und" (German "and")body = ", ".join(traits[:-1]) + f" und {traits[-1]}"- return f"Du {body}."+ return f"Du {body}." # i18n-allowdef _values_phrase(self, values: dict[str, Any]) -> str:- """Baut einen Satz mit Werten + Pet Peeves."""+ """Builds a sentence about values + pet peeves."""top = values.get("top_values") or []peeves = values.get("pet_peeves") or []parts: list[str] = []if top:if len(top) == 1:- parts.append(f"Wichtig ist Dir {top[0]}")+ parts.append(f"Wichtig ist Dir {top[0]}") # i18n-allowelse:items = ", ".join(top[:-1]) + f" und {top[-1]}"- parts.append(f"Wichtig sind Dir {items}")+ parts.append(f"Wichtig sind Dir {items}") # i18n-allowif peeves:if len(peeves) == 1:- parts.append(f"gar nicht ab kannst Du {peeves[0]}")+ parts.append(f"gar nicht ab kannst Du {peeves[0]}") # i18n-allowelse:items = ", ".join(peeves[:-1]) + f" und {peeves[-1]}"- parts.append(f"gar nicht ab kannst Du {items}")+ parts.append(f"gar nicht ab kannst Du {items}") # i18n-allowif not parts:return ""@@ -248,26 +250,26 @@ class WhoAmITool:def _work_style_phrase(self, work_style: dict[str, Any], relationship: dict[str, Any]) -> str:- """Satz zu Arbeitsweise/Feedback-Stil."""+ """Sentence about work style / feedback style."""bits: list[str] = []focus = work_style.get("focus_mode")if focus:- bits.append(f"arbeitest im {focus}-Modus")+ bits.append(f"arbeitest im {focus}-Modus") # i18n-allowhorizon = work_style.get("planning_horizon")if horizon:- bits.append(f"denkst in {horizon}")+ bits.append(f"denkst in {horizon}") # i18n-allowfb = relationship.get("feedback_pref")if fb:- bits.append(f"willst Feedback {fb}")+ bits.append(f"willst Feedback {fb}") # i18n-allowif not bits:return ""if len(bits) == 1:- return f"Du {bits[0]}."- return f"Du {', '.join(bits[:-1])} und {bits[-1]}."+ return f"Du {bits[0]}." # i18n-allow+ return f"Du {', '.join(bits[:-1])} und {bits[-1]}." # i18n-allowdef _people_phrase(self) -> str:- """Liste der bekannten Personen im Umfeld — 1 Satz."""+ """List of known people in the user's circle — 1 sentence."""if not self._people:return ""try:@@ -277,18 +279,18 @@ class WhoAmITool:if not people:return ""- # Bis zu 3 Personen nennen — mehr wird im gesprochenen Satz unhandlich.+ # Name up to 3 people — more becomes unwieldy in a spoken sentence.snippets: list[str] = []for p in people[:3]:rel = (p.relationship or "").strip()- if rel and rel.lower() != "unbekannt":- snippets.append(f"{p.name} als {rel}")+ if rel and rel.lower() != "unbekannt": # i18n-allow+ snippets.append(f"{p.name} als {rel}") # i18n-allowelse:snippets.append(p.name)if not snippets:return ""if len(snippets) == 1:- return f"Du hast {snippets[0]} erwaehnt."+ return f"Du hast {snippets[0]} erwaehnt." # i18n-allowbody = ", ".join(snippets[:-1]) + f" und {snippets[-1]}"- return f"Du hast {body} erwaehnt."+ return f"Du hast {body} erwaehnt." # i18n-allowdiff --git a/jarvis/plugins/tool/wiki_ingest.py b/jarvis/plugins/tool/wiki_ingest.pyindex 24877cfabf..c01ee7d956 100644--- a/jarvis/plugins/tool/wiki_ingest.py+++ b/jarvis/plugins/tool/wiki_ingest.py@@ -97,13 +97,13 @@ class WikiIngestTool:input_examples: list[dict[str, Any]] = [{"text": (- "Joy hat am 14. August Geburtstag. Sie ist die juengere "- "Schwester von Harald."+ "Joy's birthday is August 14th. She is Harald's younger "+ "sister."),"source": "voice:user-direct",},{- "text": "Wir haben heute Phase B5 abgeschlossen — Brain liest jetzt aus dem Wiki.",+ "text": "We finished Phase B5 today — the brain now reads from the wiki.","source": "chat:milestone",},]diff --git a/jarvis/plugins/tool/wiki_page_read.py b/jarvis/plugins/tool/wiki_page_read.pyindex 004d0f44e9..1e683aa208 100644--- a/jarvis/plugins/tool/wiki_page_read.py+++ b/jarvis/plugins/tool/wiki_page_read.py@@ -7,7 +7,7 @@ Why a second wiki tool exists``wiki-recall`` returns up to 5 hits with a 240-character snippet each.That is enough for "what do we know about X" but truncates anythinglonger. When the brain has already narrowed the answer down to one page-(e.g. user asks "lies mir alles ueber Joy vor") it needs the *full*+(e.g. user asks "read me everything about Joy") it needs the *full*markdown content, not a snippet. This tool fills that gap.Placement rulediff --git a/jarvis/plugins/tts/__init__.py b/jarvis/plugins/tts/__init__.pyindex ecb5513644..ceaa413510 100644--- a/jarvis/plugins/tts/__init__.py+++ b/jarvis/plugins/tts/__init__.py@@ -1,13 +1,13 @@-"""TTS-Provider-Plugins (Google Gemini, ElevenLabs, xAI Grok, ...).+"""TTS provider plugins (Google Gemini, ElevenLabs, xAI Grok, ...).-`build_tts_from_config` ist die zentrale Factory fuer alle Call-Sites-(Desktop-App, Speech-Pipeline-CLI). Nur so bleibt der TTS-Wechsel per-`jarvis.toml` ein Config-Edit und kein Code-Edit.+`build_tts_from_config` is the central factory for all call sites+(desktop app, speech-pipeline CLI). Only this way does switching TTS via+`jarvis.toml` stay a config edit rather than a code edit.-SAPI5 (Windows-natives, roboterhaftes TTS) ist seit 2026-04-25 nur noch-ein **opt-in**-Notausgang: per Default schweigt der Provider lieber als-auf die Windows-Stimme umzuschalten. Auf `tts.allow_sapi5_fallback = true`-setzen, wenn man jedwedes Audio-Output haben will.+SAPI5 (Windows-native, robotic-sounding TTS) has been an **opt-in**+emergency exit only since 2026-04-25: by default the provider would+rather stay silent than switch to the Windows voice. Set+`tts.allow_sapi5_fallback = true` if you want audio output no matter what."""from __future__ import annotations@@ -16,8 +16,8 @@ from typing import Anylog = logging.getLogger("jarvis.tts.factory")-# Voices, die zum jeweiligen Provider gehoeren — verhindert dass z.B. ein-# Gemini-Voice ("Charon") im Grok-Plugin landet und HTTP 400 ausloest.+# Voices belonging to each respective provider — prevents e.g. a+# Gemini voice ("Charon") from landing in the Grok plugin and triggering HTTP 400._GEMINI_VOICES = frozenset({"Charon", "Orus", "Iapetus", "Rasalgethi", "Algenib","Algieba", "Kore", "Fenrir", "Aoede",diff --git a/jarvis/safety/risk_tier.py b/jarvis/safety/risk_tier.pyindex eacdd337a4..0cc48c44f8 100644--- a/jarvis/safety/risk_tier.py+++ b/jarvis/safety/risk_tier.py@@ -1,14 +1,14 @@-"""Risk-Tier-Evaluation: Blacklist > Whitelist > Tool-Default.+"""Risk-tier evaluation: blacklist > whitelist > tool default.-Die Priorität ist wichtig und nicht verhandelbar:+The priority order matters and is non-negotiable:-1. **Blacklist** trumpft alles — Match → `ActionBlocked` Exception.-2. **Whitelist** downgraded Tier zu `safe` + `approved_by="whitelist"`.- Auch wenn das Tool selbst `ask`-Tier deklariert. Das ist die konkrete- Lösung für "Anti-Confirmation-Fatigue" (User-Pref).-3. **Tool-Default** oder Fallback auf `config.safety.default_tier`.+1. **Blacklist** beats everything — a match raises an `ActionBlocked` exception.+2. **Whitelist** downgrades the tier to `safe` + `approved_by="whitelist"`,+ even if the tool itself declares the `ask` tier. This is the concrete+ solution for "anti-confirmation-fatigue" (user preference).+3. **Tool default**, or fallback to `config.safety.default_tier`.-Matching läuft per `fnmatch`-Glob gegen `"<tool_name> <serialized_args>"`.+Matching runs via an `fnmatch` glob against `"<tool_name> <serialized_args>"`."""from __future__ import annotations@@ -29,25 +29,25 @@ log = logging.getLogger(__name__)#: would miss both checks and behave as the most permissive option silently._VALID_TIERS: frozenset[str] = frozenset(get_args(RiskTier))-# Callable that returns (whitelist_patterns, blacklist_patterns). Wird bei jedem-# evaluate() aufgerufen — billig halten. Aktueller Nutzer: CliToolRegistry-# flattened Spec-Patterns pro verbundener CLI in dieses Tupel, damit-# ``gcloud * delete *`` geblockt wird ohne Eintrag in jarvis.toml.+# Callable that returns (whitelist_patterns, blacklist_patterns). Called on every+# evaluate() call — keep it cheap. Current user: CliToolRegistry flattens spec+# patterns per connected CLI into this tuple, so that+# ``gcloud * delete *`` gets blocked without an entry in jarvis.toml.ExtraPatternsFn = Callable[[], "tuple[list[str], list[str]]"]class ActionBlocked(Exception):- """Wird geworfen wenn ein Tool-Call gegen die Blacklist matched."""+ """Raised when a tool call matches the blacklist."""def __init__(self, pattern: str, matched: str) -> None:- super().__init__(f"Blacklist-Match: '{matched}' blockiert durch Pattern '{pattern}'")+ super().__init__(f"Blacklist match: '{matched}' blocked by pattern '{pattern}'")self.pattern = patternself.matched = matched@dataclass(frozen=True, slots=True)class TierDecision:- """Ergebnis einer Tier-Evaluation."""+ """Result of a tier evaluation."""tier: RiskTierapproved_by: str | None # "whitelist" | Nonematched_pattern: str | None@@ -55,11 +55,11 @@ class TierDecision:def _serialize_args(args: dict[str, Any]) -> str:- """Serialisiert Args zu einem flat-String für Pattern-Matching.+ """Serializes args into a flat string for pattern matching.- Wir nutzen für Matching nur String-Values + Zahlen; Dict/List-Werte- werden mit `str()` gekennzeichnet, aber Blacklist/Whitelist sollte- ohnehin primär `run_shell`-Commands matchen (die Commands sind flach).+ For matching we only use string values + numbers; dict/list values+ are stringified with `str()`, but blacklist/whitelist should+ primarily match `run_shell` commands anyway (those commands are flat)."""parts: list[str] = []for k, v in args.items():@@ -71,14 +71,14 @@ def _serialize_args(args: dict[str, Any]) -> str:class RiskTierEvaluator:- """Evaluator mit Config-Snapshot (Whitelist/Blacklist Patterns).-- Optional: ein ``extra_patterns_fn`` liefert zusaetzliche Patterns, die bei- jedem ``evaluate()``-Call frisch abgefragt werden. Das ermoeglicht der- CLI-Integration, pro verbundener CLI Spec-Patterns aus dem Katalog in die- Safety-Gates zu mischen, ohne jarvis.toml zu beruehren. Fehler aus- ``extra_patterns_fn`` werden geschluckt — ein kaputter Katalog darf das- Safety-Gate nicht haengen lassen.+ """Evaluator with a config snapshot (whitelist/blacklist patterns).++ Optional: an ``extra_patterns_fn`` supplies additional patterns that are+ freshly queried on every ``evaluate()`` call. This lets the CLI+ integration mix spec patterns from the catalog into the safety gates per+ connected CLI, without touching jarvis.toml. Errors from+ ``extra_patterns_fn`` are swallowed — a broken catalog must never hang+ the safety gate."""def __init__(@@ -91,7 +91,7 @@ class RiskTierEvaluator:self._extra_patterns_fn = extra_patterns_fndef _collect_patterns(self, kind: str) -> list[str]:- """Mergt System-Patterns (jarvis.toml) mit Extra-Patterns (z.B. CLI-Specs)."""+ """Merges system patterns (jarvis.toml) with extra patterns (e.g. CLI specs)."""if kind == "whitelist":patterns = list(self._safety.whitelist.commands)elif kind == "blacklist":@@ -109,12 +109,12 @@ class RiskTierEvaluator:def evaluate(self, tool: Tool, args: dict[str, Any]) -> TierDecision:cmd = f"{tool.name} {_serialize_args(args)}".strip()- # 1. Blacklist — hartes Block+ # 1. Blacklist — hard blockfor pattern in self._collect_patterns("blacklist"):if fnmatch.fnmatchcase(cmd, pattern) or fnmatch.fnmatchcase(cmd.lower(), pattern.lower()):raise ActionBlocked(pattern=pattern, matched=cmd)- # 2. Whitelist — Downgrade zu safe+ # 2. Whitelist — downgrade to safefor pattern in self._collect_patterns("whitelist"):if fnmatch.fnmatchcase(cmd, pattern) or fnmatch.fnmatchcase(cmd.lower(), pattern.lower()):return TierDecision(@@ -155,7 +155,7 @@ class RiskTierEvaluator:tool.name, dynamic, tier,)- # block-Tier wird direkt gebounced+ # block tier gets bounced directlyif tier in self._safety.always_block_tiers:raise ActionBlocked(pattern="<tool-declared-block>", matched=cmd)@@ -167,7 +167,7 @@ class RiskTierEvaluator:)def needs_user_confirmation(self, decision: TierDecision) -> bool:- """True wenn vor Execution eine User-Bestätigung einzuholen ist."""+ """True if a user confirmation must be obtained before execution."""if decision.approved_by is not None:return Falsereturn decision.tier in self._safety.always_confirm_tiersdiff --git a/jarvis/safety/tool_executor.py b/jarvis/safety/tool_executor.pyindex c8444183a0..45fe0eb1d8 100644--- a/jarvis/safety/tool_executor.py+++ b/jarvis/safety/tool_executor.py@@ -1,13 +1,13 @@-"""ToolExecutor: orchestriert Risk-Eval → Plausibility → Approval → Execute → Event-Log.+"""ToolExecutor: orchestrates risk-eval → plausibility → approval → execute → event log.-Einziger autorisierter Einstiegspunkt für Tool-Calls. Wer `Tool.execute()`-direkt aufruft umgeht Safety — das ist ein Bug.+The only authorized entry point for tool calls. Calling `Tool.execute()`+directly bypasses safety — that is a bug.-Phase 4 (Persona-Mandat): Vor jeder Approval-Entscheidung laeuft ein-Plausibilitaets-Check. Wenn die Voice-Pipeline einen ``plausibility_context_fn``-registriert hat, holt der Executor sich Transcript-Confidence + Wake-Age-und entscheidet, ob bei ``ask``-/``monitor``-Tools eine zusaetzliche-Confirmation noetig ist (siehe ``jarvis.brain.plausibility``).+Phase 4 (persona mandate): a plausibility check runs before every approval+decision. If the voice pipeline has registered a ``plausibility_context_fn``,+the executor fetches transcript confidence + wake age and decides whether+``ask``/``monitor`` tools need an extra confirmation (see+``jarvis.brain.plausibility``)."""from __future__ import annotations@@ -44,9 +44,9 @@ VOICE_CONFIRM_SENTINEL = "__voice_confirm_required__"# ``plausibility_context_fn`` returns (Transcript | None, wake_age_s | None).-# Die Voice-Pipeline registriert einen Provider, der den letzten User-Turn--# Transcript und die Sekunden seit dem letzten Wake-Trigger liefert. Bei-# ``None``-Returns laeuft der Executor wie bisher (kein Plausibility-Check).+# The voice pipeline registers a provider that supplies the last user-turn+# transcript and the seconds since the last wake trigger. On+# ``None`` returns the executor behaves as before (no plausibility check).PlausibilityContextFn = Callable[[], "tuple[Transcript | None, float | None]"]@@ -78,11 +78,11 @@ class ToolExecutor:def set_plausibility_context_fn(self, fn: PlausibilityContextFn | None,) -> None:- """Spaete Registrierung des Plausibility-Context-Providers.+ """Late registration of the plausibility-context provider.- Die Voice-Pipeline ruft das nach ihrem ``run()``-Setup auf, weil der- ToolExecutor frueher in der Bootstrap-Reihenfolge gebaut wird als- die Pipeline. Idempotent — ``None`` setzt den Hook zurueck.+ The voice pipeline calls this after its own ``run()`` setup, because+ the ToolExecutor is built earlier in the bootstrap order than+ the pipeline. Idempotent — ``None`` resets the hook."""self._plausibility_context_fn = fn@@ -91,16 +91,16 @@ class ToolExecutor:tool: Tool,decision: Any,) -> "PlausibilityDecision | None":- """Holt den aktuellen Plausibility-Context und prueft.+ """Fetches the current plausibility context and checks it.- Returns ``None`` wenn kein Context-Provider registriert ist oder- das Tool durch Whitelist auf ``safe`` heruntergesetzt wurde —- Whitelist-Logik ist heilig (Mandat: "Whitelist-downgraded Tools- laufen weiter ohne Plausibility-Check").+ Returns ``None`` if no context provider is registered, or the+ tool was downgraded to ``safe`` via whitelist — whitelist logic+ is sacred (mandate: "whitelist-downgraded tools keep running+ without a plausibility check")."""if self._plausibility_context_fn is None:return None- # Whitelist-Downgrade: Plausibility uebergehen.+ # Whitelist downgrade: skip plausibility.if decision.approved_by == "whitelist":return Nonetry:@@ -143,7 +143,7 @@ class ToolExecutor:))return ToolResult(success=False, output=None, error=str(exc))- # 2. Proposed-Event (UI kann das als Live-Indikator nutzen). The brain's+ # 2. Proposed event (the UI can use this as a live indicator). The brain's# rationale rides along for the Session-Decision-Log — redacted + capped# here so no raw secret reaches the bus / session DB / local diary.await self._bus.publish(ActionProposed(@@ -154,9 +154,9 @@ class ToolExecutor:rationale=safe_preview(rationale),))- # 2.5 Plausibility-Check (Phase 4): zwischen Tier-Decision und- # Approval. Ergebnis kann ``require_confirmation`` erzwingen, auch- # wenn der Tier-Workflow das nicht vorsieht (z.B. bei ``monitor``).+ # 2.5 Plausibility check (Phase 4): between the tier decision and+ # approval. The result can force ``require_confirmation`` even+ # when the tier workflow doesn't call for it (e.g. for ``monitor``).plaus = self._evaluate_plausibility(tool, decision)if plaus is not None and plaus.reason != "ok":log.info(@@ -164,7 +164,7 @@ class ToolExecutor:tool.name, decision.tier, plaus.reason, plaus.require_confirmation,)- # 3. Approval (nur wenn der Tier-Workflow ODER Plausibility es will)+ # 3. Approval (only if the tier workflow OR plausibility wants it)approved_by = decision.approved_by or "auto"needs_confirm = self._evaluator.needs_user_confirmation(decision) or (plaus is not None and plaus.require_confirmation@@ -200,7 +200,7 @@ class ToolExecutor:reason=who_or_reason,))return ToolResult(success=False, output=None, error=f"approval-denied ({who_or_reason})")- approved_by = who_or_reason # "user" oder "auto"+ approved_by = who_or_reason # "user" or "auto"# 4. Executectx = ExecutionContext(diff --git a/jarvis/safety/vision_telemetry.py b/jarvis/safety/vision_telemetry.pyindex 6012c8b27f..243e1112f8 100644--- a/jarvis/safety/vision_telemetry.py+++ b/jarvis/safety/vision_telemetry.py@@ -1,19 +1,19 @@-"""VisionTelemetryCollector — akkumuliert VisionInjected-Events.+"""VisionTelemetryCollector — accumulates VisionInjected events.-Bus-Subscriber fuer die Permanent-Vision-Pipeline. Haelt drei Buckets:+Bus subscriber for the permanent-vision pipeline. Holds three buckets:-- ``bytes_total``: Summe der Bytes aller injizierten Screen-Observations.-- ``injects_total``: Zahl der Injects (pro trace_id maximal einmal gezaehlt).-- ``avg_capture_age_ms``: Running-Average des Alters zum Inject-Zeitpunkt.+- ``bytes_total``: sum of the bytes of all injected screen observations.+- ``injects_total``: number of injects (counted at most once per trace_id).+- ``avg_capture_age_ms``: running average of the age at inject time.-De-Duplication ueber ``trace_id`` verhindert Doppelzaehlung bei Retries.-Reine Telemetrie — keine Rate-Limits, keine Budgets. Rate-/Budget-Logik-lebt separat in ``jarvis.control`` (Protocol ``CostMeter``) und ist nicht-Teil dieses Moduls.+De-duplication via ``trace_id`` prevents double-counting on retries.+Pure telemetry — no rate limits, no budgets. Rate/budget logic+lives separately in ``jarvis.control`` (protocol ``CostMeter``) and is not+part of this module.-Bekannte Einschraenkung: ``_seen_trace_ids`` waechst unbegrenzt. In-MVP-Laufzeiten (Sessions bis ~Stunden) kein Problem; ein spaeterer Fix-koennte ein LRU-Set sein.+Known limitation: ``_seen_trace_ids`` grows unbounded. Not a problem for+MVP-scale runtimes (sessions up to ~hours); a later fix could+switch to an LRU set."""from __future__ import annotationsdiff --git a/jarvis/sessions/__init__.py b/jarvis/sessions/__init__.pyindex dcf9000b7b..2e965d3ba0 100644--- a/jarvis/sessions/__init__.py+++ b/jarvis/sessions/__init__.py@@ -1,10 +1,10 @@-"""Voice-Session-Recording-Subsystem.+"""Voice-session recording subsystem.-Schreibt jede Voice-Session (Wake -> Hangup) inkl. User-Transkripten,-Jarvis-Antworten, Tool-Calls und Latenzen in ``data/sessions.db``.-Wird in der Desktop-App unter dem "Transkription"-Tab angezeigt.+Writes every voice session (wake -> hangup), including user transcripts,+Jarvis replies, tool calls, and latencies, into ``data/sessions.db``.+Shown in the desktop app under the "Transcription" tab.-Bootstrapping in ``server.py::_init_sessions_stack()`` via+Bootstrapped in ``server.py::_init_sessions_stack()`` via``bootstrap_sessions(bus, db_path)``."""from .init import bootstrap_sessions, shutdown_sessionsdiff --git a/jarvis/sessions/constants.py b/jarvis/sessions/constants.pyindex 65c4342f7a..4a1fe086e7 100644--- a/jarvis/sessions/constants.py+++ b/jarvis/sessions/constants.py@@ -31,7 +31,7 @@ from __future__ import annotationsfrom typing import FinalHANGUP_VOICE_PATTERN: Final[str] = "voice_pattern"-"""User said a hangup phrase ('auflegen', 'tschüss', 'bye') or it was+"""User said a hangup phrase ('auflegen', 'tschüss', 'bye') or it was i18n-allowinferred from a closing intent."""HANGUP_HOTKEY: Final[str] = "hotkey"diff --git a/jarvis/sessions/init.py b/jarvis/sessions/init.pyindex a632bec8fa..4acb90bac2 100644--- a/jarvis/sessions/init.py+++ b/jarvis/sessions/init.py@@ -1,7 +1,7 @@-"""Bootstrap fuer den Voice-Session-Recorder.+"""Bootstrap for the voice-session recorder.-Wird beim App-Start aus ``jarvis/ui/web/server.py`` aufgerufen,-analog zu ``bootstrap_missions`` (Phase 6).+Called at app startup from ``jarvis/ui/web/server.py``,+analogous to ``bootstrap_missions`` (Phase 6)."""from __future__ import annotations@@ -25,14 +25,14 @@ def bootstrap_sessions(enabled: bool = True,retention_days: int = 30,) -> dict[str, Any]:- """Initialisiert SessionStore + SessionRecorder, dockt am Bus an.+ """Initializes SessionStore + SessionRecorder and attaches them to the bus.Args:- bus: Der Haupt-EventBus der Desktop-App.- db_path: Pfad zur sessions.db (Default: ``data/sessions.db``).- enabled: Wenn False, gibt ``None``-Recorder zurueck (Feature off).- retention_days: Sessions aelter als N Tage werden beim Bootstrap- entfernt. ``0`` deaktiviert das Pruning.+ bus: The desktop app's main EventBus.+ db_path: Path to sessions.db (default: ``data/sessions.db``).+ enabled: If False, returns a ``None`` recorder (feature off).+ retention_days: Sessions older than N days are removed at+ bootstrap. ``0`` disables pruning.Returns:``{"store": SessionStore | None, "recorder": SessionRecorder | None}``.@@ -48,10 +48,10 @@ def bootstrap_sessions(if pruned:log.info("SessionRecorder: pruned %d sessions older than %d days", pruned, retention_days)- # Crash-Recovery: Sessions ohne ended_ms stammen aus einem nicht- # sauberen Shutdown des Vorgaenger-Prozesses (Hard-Kill, Crash). Ohne- # diese Bereinigung erscheinen sie permanent als "laeuft" in der UI.- # Mark sie als "shutdown" mit ended_ms = startup-Zeit.+ # Crash recovery: sessions without ended_ms stem from an unclean+ # shutdown of the previous process (hard kill, crash). Without+ # this cleanup they would show up permanently as "running" in the UI.+ # Mark them as "shutdown" with ended_ms = startup time.import time as _timeopen_ids = store.list_open_sessions()for sid in open_ids:@@ -60,7 +60,7 @@ def bootstrap_sessions(session_id=sid,ended_ms=int(_time.time() * 1000),hangup_reason=HANGUP_SHUTDOWN,- turn_count=0, # konservativ: Aggregate kennen wir nicht+ turn_count=0, # conservative: we don't know the aggregatestotal_cost_usd=0.0,total_tokens_in=0,total_tokens_out=0,@@ -79,7 +79,7 @@ def bootstrap_sessions(def shutdown_sessions(bootstrap_result: dict[str, Any]) -> None:- """Schliesst den Store sauber. Recorder hat keinen eigenen State zum Cleanup."""+ """Closes the store cleanly. The recorder has no own state to clean up."""store: SessionStore | None = bootstrap_result.get("store")if store is not None:try:diff --git a/jarvis/sessions/models.py b/jarvis/sessions/models.pyindex e33c04ddbb..8aac7d5558 100644--- a/jarvis/sessions/models.py+++ b/jarvis/sessions/models.py@@ -1,17 +1,17 @@-"""Pydantic-Models fuer Voice-Session-Recording.+"""Pydantic models for voice-session recording.-Drei Schichten 1:1 zum SQLite-Schema (schema.sql):+Three layers mapping 1:1 to the SQLite schema (schema.sql):-- ``VoiceSessionRow`` - Header-Row pro Session.-- ``VoiceTurnRow`` - Aggregat pro Turn (User+Jarvis).-- ``VoiceEventRow`` - Roh-Event aus dem Bus, Detail-Replay.+- ``VoiceSessionRow`` - header row per session.+- ``VoiceTurnRow`` - aggregate per turn (user+Jarvis).+- ``VoiceEventRow`` - raw event from the bus, for detail replay.-Plus Composite-DTOs fuer die REST-API (``SessionListItem``,+Plus composite DTOs for the REST API (``SessionListItem``,``SessionDetail``).-Konvention: ``_ms`` = Wall-Clock-Timestamp in Millisekunden seit Epoch-(passt zu existierenden Phase-6-Mission-Events). Frontend rechnet das-selbst zu ISO-Strings um — Backend bleibt bei der numerischen Form.+Convention: ``_ms`` = wall-clock timestamp in milliseconds since epoch+(matches existing Phase-6 mission events). The frontend converts this+to ISO strings itself — the backend stays with the numeric form."""from __future__ import annotations@@ -21,54 +21,54 @@ from pydantic import BaseModel, ConfigDict, Fieldfrom jarvis.sessions.constants import SPOKEN_KINDS-# BUG-008 (drei Episoden 2026-05-03 / -05 / -10): Pydantic-``Literal`` brach-# die List-Sessions-API jedes Mal, wenn die Pipeline einen neuen-# ``hangup_reason``-String einfuehrte (zuletzt ``turn_complete`` aus-# pipeline.py:1391). Daher: kein ``Literal`` mehr, sondern offener ``str``-# plus eine **dokumentierende** Konstante mit den heute bekannten Werten.-# Drift-Detection passiert im Test (siehe ``tests/unit/sessions/-# test_models_db_drift.py``), nicht im Pydantic-Validator — sonst kollabiert-# die UI bei jedem neuen Wert.+# BUG-008 (three episodes 2026-05-03 / -05 / -10): the Pydantic ``Literal``+# broke the list-sessions API every time the pipeline introduced a new+# ``hangup_reason`` string (most recently ``turn_complete`` from+# pipeline.py:1391). So: no more ``Literal``, instead an open ``str``+# plus a **documenting** constant with the values known today.+# Drift detection happens in the test (see ``tests/unit/sessions/+# test_models_db_drift.py``), not in the Pydantic validator — otherwise+# the UI collapses on every new value.KNOWN_HANGUP_REASONS: frozenset[str] = frozenset({- "", # Session laeuft noch (DB-Default solange ``ended_ms IS NULL``)- "voice_pattern", # User-Voice-Hangup ("Tschuess Jarvis")- "hotkey", # User-Hotkey-Hangup- "idle_timeout", # Auto-Hangup nach Inaktivitaet- "shutdown", # App-Shutdown beendet laufende Session- "error", # Pipeline-Crash- "turn_complete", # Normaler Turn-Ende-Pfad (pipeline.py:1391)+ "", # session still running (DB default while ``ended_ms IS NULL``)+ "voice_pattern", # user voice hangup ("bye Jarvis")+ "hotkey", # user hotkey hangup+ "idle_timeout", # auto-hangup after inactivity+ "shutdown", # app shutdown ends the running session+ "error", # pipeline crash+ "turn_complete", # normal turn-end path (pipeline.py:1391)})-"""Bekannte ``VoiceSessionEnded.hangup_reason``-Werte. Erweitern wenn die-Speech-Pipeline einen neuen Wert einfuehrt — Tests fangen Drift, nicht-Pydantic. Siehe ADR-0009 / BUGS.md BUG-008 fuer Historie."""+"""Known ``VoiceSessionEnded.hangup_reason`` values. Extend when the+speech pipeline introduces a new value — tests catch drift, not+Pydantic. See ADR-0009 / BUGS.md BUG-008 for history."""HangupReason: TypeAlias = str-"""Korrespondiert zu ``VoiceSessionEnded.hangup_reason`` (events.py).-Bewusst ``str`` statt ``Literal`` — siehe ``KNOWN_HANGUP_REASONS``."""+"""Corresponds to ``VoiceSessionEnded.hangup_reason`` (events.py).+Deliberately ``str`` instead of ``Literal`` — see ``KNOWN_HANGUP_REASONS``."""KNOWN_VOICE_TIERS: frozenset[str] = frozenset({- "", # Kein Tier-Hinweis (z.B. Smalltalk-Fallback ohne BrainTurnStarted)+ "", # no tier hint (e.g. smalltalk fallback without BrainTurnStarted)"router","openclaw",- "sub_jarvis", # Legacy bis Welle-4-Loeschung+ "sub_jarvis", # legacy, kept until the Welle-4 removal"trivial","fast","deep","code",})-"""Routing-Tier wie in CLAUDE.md `Brain-Routing` und `Router-Discipline`."""+"""Routing tier as in CLAUDE.md `Brain-Routing` and `Router-Discipline`."""VoiceTier: TypeAlias = str-"""Bewusst ``str`` statt ``Literal`` — siehe ``KNOWN_VOICE_TIERS``."""+"""Deliberately ``str`` instead of ``Literal`` — see ``KNOWN_VOICE_TIERS``."""KNOWN_SPOKEN_KINDS: frozenset[str] = frozenset(SPOKEN_KINDS)-"""Bekannte ``SpeechSpoken.spoken_kind``-Werte (timeout / announcement /+"""Known ``SpeechSpoken.spoken_kind`` values (timeout / announcement /clarify / …). Mirror of ``constants.SPOKEN_KINDS`` — the value rides in the``voice_events`` payload JSON, not a typed column, so an unknown kind degradesto a fallback UI label instead of an HTTP 500 (BUG-008 class). Parity guard:@@ -76,7 +76,7 @@ to a fallback UI label instead of an HTTP 500 (BUG-008 class). Parity guard:class VoiceEventRow(BaseModel):- """Ein Roh-Event aus dem Bus, einer Session/Turn zugeordnet."""+ """A raw event from the bus, associated with a session/turn."""model_config = ConfigDict(extra="ignore")@@ -84,12 +84,12 @@ class VoiceEventRow(BaseModel):session_id: strturn_id: str | None = Nonets_ms: int- kind: str = Field(description="Event-Typ-Name (z.B. 'TranscriptFinal').")+ kind: str = Field(description="Event type name (e.g. 'TranscriptFinal').")payload: dict[str, object] = Field(default_factory=dict)class VoiceTurnRow(BaseModel):- """Aggregat eines einzelnen Voice-Turns."""+ """Aggregate of a single voice turn."""model_config = ConfigDict(extra="ignore")@@ -109,9 +109,9 @@ class VoiceTurnRow(BaseModel):tokens_out: int = 0cost_usd: float = 0.0latency_total_ms: int = 0- # Aufgeschluesselte Latenzen (vom Recorder via SystemStateChanged-Boundaries):- # think_ms = wie lang Jarvis "nachgedacht" hat (User-Done -> Jarvis-spricht).- # speak_ms = wie lang Jarvis gesprochen hat (TTS-Playback-Dauer).+ # Broken-down latencies (from the recorder via SystemStateChanged boundaries):+ # think_ms = how long Jarvis "thought" (user-done -> Jarvis-speaks).+ # speak_ms = how long Jarvis spoke (TTS playback duration).think_ms: int = 0speak_ms: int = 0tool_calls: list[str] = Field(default_factory=list)@@ -122,7 +122,7 @@ class VoiceTurnRow(BaseModel):class VoiceSessionRow(BaseModel):- """Header einer Voice-Session."""+ """Header of a voice session."""model_config = ConfigDict(extra="ignore")@@ -140,12 +140,12 @@ class VoiceSessionRow(BaseModel):class SessionListItem(VoiceSessionRow):- """Listen-Eintrag mit Anzeige-freundlichen Derivaten.+ """List entry with display-friendly derived fields.- ``duration_s`` wird aus ``started_ms``/``ended_ms`` berechnet (None- fuer noch laufende Sessions). ``preview`` ist die erste User-Utterance- der Session (truncated), damit die UI ohne Detail-Fetch eine Zeile- pro Session zeigen kann.+ ``duration_s`` is computed from ``started_ms``/``ended_ms`` (None+ for sessions still running). ``preview`` is the session's first+ user utterance (truncated), so the UI can show one line per+ session without a detail fetch."""duration_s: float | None = None@@ -153,7 +153,7 @@ class SessionListItem(VoiceSessionRow):class SessionDetail(BaseModel):- """Vollstaendige Session-Sicht: Header + Turns + alle Events."""+ """Complete session view: header + turns + all events."""model_config = ConfigDict(extra="ignore")diff --git a/jarvis/sessions/recorder.py b/jarvis/sessions/recorder.pyindex d61e976f94..75e5aeb0d0 100644--- a/jarvis/sessions/recorder.py+++ b/jarvis/sessions/recorder.py@@ -1,11 +1,11 @@-"""Bus-Wildcard-Subscriber, der Voice-Sessions in den SessionStore schreibt.+"""Bus wildcard subscriber that writes voice sessions into the SessionStore.-Architekturentscheidung: read-only zur Pipeline. Der Recorder dockt nur-ueber ``bus.subscribe_all`` an und produziert keine Events zurueck —-damit ist er garantiert latenzneutral fuer den Voice-Hot-Path.+Architecture decision: read-only with respect to the pipeline. The recorder+only docks on via ``bus.subscribe_all`` and produces no events back —+which guarantees it is latency-neutral for the voice hot path.-State-Machine pro Session (linear, da Pipeline nur 1 aktive Voice--Session zulaesst):+State machine per session (linear, since the pipeline allows only 1 active+voice session):IDLE| VoiceSessionStarted@@ -19,16 +19,16 @@ Session zulaesst):vVoiceTurnCompletedv- ACTIVE (naechster Turn moeglich)+ ACTIVE (next turn possible)| VoiceSessionEndedvIDLE-Whitelist fuer ``voice_events``-Append: nicht jedes Bus-Event landet in-der DB — TerminalOutput-Streams oder MissionEvents sind irrelevant.-``_RAW_EVENT_KINDS`` (siehe unten) listet die fuer Replay relevanten-Klassen.+Whitelist for the ``voice_events`` append: not every bus event lands in+the DB — TerminalOutput streams or MissionEvents are irrelevant.+``_RAW_EVENT_KINDS`` (see below) lists the classes relevant for+replay."""from __future__ import annotations@@ -109,7 +109,7 @@ _RAW_EVENT_KINDS: frozenset[str] = frozenset(@dataclassclass _TurnState:- """In-Memory-State eines laufenden Turns, bevor er finalisiert wird."""+ """In-memory state of a running turn, before it is finalized."""turn_id: stridx: int@@ -126,9 +126,9 @@ class _TurnState:cost_usd: float = 0.0latency_total_ms: int = 0tool_calls: list[str] = field(default_factory=list)- # Stage-Boundaries fuer Think-/Speak-Latenz-Berechnung. Werden aus- # TranscriptFinal + SystemStateChanged(SPEAKING/LISTENING) abgeleitet,- # weil diese Pipeline-Variante keine Phase-L.1-Stage-Events emittiert.+ # Stage boundaries for think/speak latency calculation. Derived from+ # TranscriptFinal + SystemStateChanged(SPEAKING/LISTENING),+ # because this pipeline variant does not emit Phase-L.1 stage events.transcript_final_ms: int = 0speaking_started_ms: int = 0think_ms: int = 0@@ -142,7 +142,7 @@ class _TurnState:@dataclassclass _SessionState:- """In-Memory-Aggregat einer Session."""+ """In-memory aggregate of a session."""session_id: strstarted_ms: int@@ -156,13 +156,13 @@ class _SessionState:class SessionRecorder:- """EventBus-Wildcard-Subscriber, persistiert Voice-Sessions."""+ """EventBus wildcard subscriber, persists voice sessions."""def __init__(self, store: SessionStore) -> None:self._store = storeself._state: _SessionState | None = None- # Fallback wenn Pipeline VoiceTurnStarted vergisst — wir vergeben- # selbst eine turn_id beim ersten Turn-relevanten Event.+ # Fallback when the pipeline forgets VoiceTurnStarted — we assign+ # our own turn_id at the first turn-relevant event.self._auto_turn_counter: int = 0# (session_id, last_turn_id) of the most recently FINALIZED session.# A background mission's readback can be voiced after the user hung up@@ -174,19 +174,19 @@ class SessionRecorder:self._afterglow: tuple[str, str | None] | None = Nonedef attach(self, bus: EventBus) -> None:- """Wildcard-Subscribe an den Bus."""+ """Wildcard-subscribe to the bus."""bus.subscribe_all(self._on_event)log.info("SessionRecorder attached to bus")# ------------------------------------------------------------------ # Haupt-Dispatch+ # Main dispatch# -----------------------------------------------------------------async def _on_event(self, event: Event) -> None:- """Wird vom Bus fuer JEDES Event aufgerufen.+ """Called by the bus for EVERY event.- Defensive: jede Exception schlucken — der Bus catcht zwar selbst,- aber wir wollen sicher kein Error-Log-Spam pro Voice-Turn.+ Defensive: swallow every exception — the bus does catch itself,+ but we definitely don't want error-log spam per voice turn."""try:self._dispatch(event)@@ -226,7 +226,7 @@ class SessionRecorder:elif isinstance(event, VoiceTurnCompleted):self._on_turn_completed(event)elif isinstance(event, WakeWordDetected):- # Wake im Multi-Turn-Modus — zaehlt als Turn-Boundary.+ # Wake in multi-turn mode — counts as a turn boundary.self._ensure_turn_open(event.timestamp_ns // 1_000_000)elif isinstance(event, ListeningStarted):self._ensure_turn_open(event.timestamp_ns // 1_000_000)@@ -257,7 +257,7 @@ class SessionRecorder:self._maybe_append_raw(event, kind)# ------------------------------------------------------------------ # Session-Lifecycle+ # Session lifecycle# -----------------------------------------------------------------def _on_session_started(self, event: VoiceSessionStarted) -> None:@@ -290,7 +290,7 @@ class SessionRecorder:def _on_session_ended(self, event: VoiceSessionEnded) -> None:if self._state is None:return- # Offenen Turn auto-finalisieren falls noch da+ # Auto-finalize an open turn if one still existsif self._state.current_turn is not None and not self._state.current_turn.finalized:self._finalize_current_turn(end_ms=event.timestamp_ns // 1_000_000)self._store.finalize_session(@@ -318,8 +318,8 @@ class SessionRecorder:self._state = Nonedef _force_finalize_session(self, *, reason: str) -> None:- """Notbremse — wenn ein neues VoiceSessionStarted ohne vorheriges- Ended kommt (Pipeline-Bug oder Crash-Recovery)."""+ """Emergency brake — when a new VoiceSessionStarted arrives without a+ preceding Ended (pipeline bug or crash recovery)."""if self._state is None:returnts_ms = _now_ms()@@ -338,12 +338,12 @@ class SessionRecorder:self._state = None# ------------------------------------------------------------------ # Turn-Lifecycle+ # Turn lifecycle# -----------------------------------------------------------------def _on_turn_started(self, event: VoiceTurnStarted) -> None:assert self._state is not None- # Falls ein vorheriger Turn nicht sauber finalisiert wurde — auto-close+ # If a previous turn wasn't cleanly finalized — auto-closeif self._state.current_turn and not self._state.current_turn.finalized:self._finalize_current_turn(end_ms=event.timestamp_ns // 1_000_000)idx = event.turn_index if event.turn_index >= 0 else self._state.turn_count@@ -362,12 +362,12 @@ class SessionRecorder:def _on_turn_completed(self, event: VoiceTurnCompleted) -> None:assert self._state is not None- # Werte aus dem Event uebernehmen falls sie konsistent sind+ # Adopt values from the event if they are consistentif self._state.current_turn is None or self._state.current_turn.turn_id != event.turn_id:- log.debug("VoiceTurnCompleted ohne offenen Turn — ignoriere")+ log.debug("VoiceTurnCompleted without an open turn — ignoring")returnt = self._state.current_turn- # Event-Werte gewinnen (Pipeline weiss es genau)+ # Event values win (the pipeline knows exactly)if event.user_text:t.user_text = event.user_textif event.user_lang:@@ -394,14 +394,14 @@ class SessionRecorder:self._finalize_current_turn(end_ms=event.timestamp_ns // 1_000_000)def _ensure_turn_open(self, ts_ms: int) -> None:- """Falls Pipeline keinen VoiceTurnStarted schickt — selber einen erfinden.+ """If the pipeline doesn't send a VoiceTurnStarted — invent one ourselves.- Wird bei WakeWordDetected/ListeningStarted aufgerufen — neuer Turn- beginnt nur wenn der vorige finalisiert ist.+ Called on WakeWordDetected/ListeningStarted — a new turn only+ starts once the previous one is finalized."""assert self._state is not Noneif self._state.current_turn is not None and not self._state.current_turn.finalized:- return # Turn laeuft noch+ return # turn still runningself._auto_turn_counter += 1auto_id = f"{self._state.session_id}-auto-{self._auto_turn_counter}"self._state.current_turn = _TurnState(@@ -421,12 +421,12 @@ class SessionRecorder:t = self._state.current_turnif t is None or t.finalized:return- # Latenz default: end - start, falls nicht via AudioOutFirst gesetzt.+ # Latency default: end - start, if not set via AudioOutFirst.if t.latency_total_ms == 0:t.latency_total_ms = max(0, end_ms - t.started_ms)- # Speak-Latenz: falls Pipeline noch in SPEAKING war beim Turn-End,- # rechnen wir bis end_ms hoch; sonst war sie schon gesetzt durch- # SystemStateChanged(LISTENING)-Transition.+ # Speak latency: if the pipeline was still SPEAKING at turn end,+ # we compute up to end_ms; otherwise it was already set by the+ # SystemStateChanged(LISTENING) transition.if t.speak_ms == 0 and t.speaking_started_ms > 0:t.speak_ms = max(0, end_ms - t.speaking_started_ms)self._store.finalize_turn(@@ -448,7 +448,7 @@ class SessionRecorder:speak_ms=t.speak_ms,awaiting_confirmation=t.awaiting_confirmation,)- # Aggregate hochzaehlen+ # Bump aggregatesself._state.turn_count += 1self._state.total_cost_usd += t.cost_usdself._state.total_tokens_in += t.tokens_in@@ -458,7 +458,7 @@ class SessionRecorder:t.finalized = True# ------------------------------------------------------------------ # Per-Event Handler+ # Per-event handlers# -----------------------------------------------------------------def _on_transcript_final(self, event: TranscriptFinal) -> None:@@ -502,22 +502,22 @@ class SessionRecorder:self._state.current_turn.user_text = event.transcript.textlang = getattr(event.transcript, "language", None) or self._state.languageself._state.current_turn.user_lang = lang- # Stage-Anker fuer think_ms = TranscriptFinal -> SPEAKING.+ # Stage anchor for think_ms = TranscriptFinal -> SPEAKING.self._state.current_turn.transcript_final_ms = ts_msdef _on_system_state(self, event: SystemStateChanged) -> None:- """Tracke SPEAKING/LISTENING-Boundaries fuer think_ms + speak_ms.-- Diese Pipeline-Variante emittiert keine Phase-L.1-Stage-Events- (AudioOutFirst, TTSFirstByte). Stattdessen markiert sie via- ``_set_turn_state`` -> ``_transition`` den High-Level-State:- IDLE | LISTENING | THINKING | SPEAKING. Wir nehmen:- - SPEAKING-Start = Anker fuer think_ms (User-Done -> Jarvis-spricht)- - LISTENING-Start nach SPEAKING = Anker fuer speak_ms-Ende UND- **Turn-Boundary** — der Turn ist fertig, der naechste TranscriptFinal- oeffnet via ``_ensure_turn_open`` einen neuen Turn. Ohne diese- explizite Finalisierung bleibt in Multi-Turn-Sessions Turn 1 offen- und alle folgenden user_text/jarvis_text-Werte ueberschreiben sich.+ """Track SPEAKING/LISTENING boundaries for think_ms + speak_ms.++ This pipeline variant does not emit Phase-L.1 stage events+ (AudioOutFirst, TTSFirstByte). Instead it marks the high-level+ state via ``_set_turn_state`` -> ``_transition``:+ IDLE | LISTENING | THINKING | SPEAKING. We take:+ - SPEAKING start = anchor for think_ms (user-done -> Jarvis speaks)+ - LISTENING start after SPEAKING = anchor for speak_ms end AND+ **turn boundary** — the turn is done, the next TranscriptFinal+ opens a new turn via ``_ensure_turn_open``. Without this+ explicit finalization, turn 1 stays open in multi-turn sessions+ and every following user_text/jarvis_text value overwrites the last."""assert self._state is not Nonet = self._state.current_turn@@ -527,40 +527,40 @@ class SessionRecorder:new = (event.new_state or "").upper()prev = (event.previous or "").upper()if new == "SPEAKING" and prev != "SPEAKING":- # Anker setzen — speak_ms beginnt jetzt.+ # Set anchor — speak_ms starts now.t.speaking_started_ms = ts_ms- # think_ms = transcript_final_ms -> jetzt+ # think_ms = transcript_final_ms -> nowif t.transcript_final_ms > 0 and t.think_ms == 0:t.think_ms = max(0, ts_ms - t.transcript_final_ms)elif prev == "SPEAKING" and new != "SPEAKING":- # Sprech-Phase ist vorbei — speak_ms = SPEAKING_start -> jetzt.+ # Speaking phase is over — speak_ms = SPEAKING_start -> now.if t.speaking_started_ms > 0 and t.speak_ms == 0:t.speak_ms = max(0, ts_ms - t.speaking_started_ms)- # Turn-Boundary: dieser Turn ist abgeschlossen. Nicht-finalisieren- # waere falsch — sonst akkumulieren sich Werte ueber alle Turns- # einer Multi-Turn-Session und nur der letzte Turn bleibt sichtbar.+ # Turn boundary: this turn is complete. Not finalizing here+ # would be wrong — otherwise values would accumulate across all+ # turns of a multi-turn session and only the last turn stays visible.self._finalize_current_turn(end_ms=ts_ms)def _on_brain_started(self, event: BrainTurnStarted) -> None:- # Defensive: kein hartes assert — bei Race-Conditions zwischen- # BrainTurnStarted und VoiceSessionEnded landet das Event sonst- # nur im Logger statt im Turn (BUG-Diagnose 2026-04-28).+ # Defensive: no hard assert — on race conditions between+ # BrainTurnStarted and VoiceSessionEnded the event would otherwise+ # land only in the logger instead of the turn (bug diagnosis 2026-04-28).if self._state is None:returnself._ensure_turn_open(event.timestamp_ns // 1_000_000)t = self._state.current_turnif t is None:return- # Bug C Fix (2026-04-29): provider/model NICHT mehr aus Started- # uebernehmen. Stattdessen aus BrainTurnCompleted — dort steht- # nur der ERFOLGREICHE Provider, kein Fallback-Versuch der spaeter- # gecrashed ist. Verhindert Halluzinations-Tags in voice_turns- # (z.B. "openai/gpt-4o" obwohl kein OpenAI-Key existiert).- # intent_level ist die Router-Decision (z.B. "spawn_worker"/- # "direct_action"/"trivial"). Das Recorder-Schema erlaubt fuer- # ``tier`` aber nur die echten Tier-Namen ({"router", "openclaw",- # "trivial", "fast", "deep", "code"}). Werte ausserhalb mappen wir- # auf "router" — der Hauptjarvis-Brain hat geantwortet.+ # Bug C fix (2026-04-29): no longer adopt provider/model from Started.+ # Instead take it from BrainTurnCompleted — that holds+ # only the SUCCESSFUL provider, not a fallback attempt that later+ # crashed. Prevents hallucination tags in voice_turns+ # (e.g. "openai/gpt-4o" even though no OpenAI key exists).+ # intent_level is the router decision (e.g. "spawn_worker"/+ # "direct_action"/"trivial"). The recorder schema, however, only+ # allows the real tier names for ``tier`` ({"router", "openclaw",+ # "trivial", "fast", "deep", "code"}). Values outside that set are+ # mapped to "router" — the main Jarvis brain answered.if event.intent_level and not t.tier:t.tier = _normalize_intent_level_to_tier(event.intent_level)@@ -598,12 +598,12 @@ class SessionRecorder:t.tokens_in += event.tokens_int.tokens_out += event.tokens_outt.cost_usd += event.cost_usd- # Bug C Fix (2026-04-29): provider/model aus Completed-Event- # uebernehmen — das ist die ERFOLGREICHE Quelle. Wenn ein spaeterer- # Fallback-Versuch nochmal Tokens liefert (selten — Multi-Step-Tool-- # Loop), gewinnt der spaetere Wert; das ist OK weil beide erfolgreich- # sind. Im Normalfall einer Voice-Session wird _on_brain_completed- # nur einmal pro Turn mit echten Daten aufgerufen.+ # Bug C fix (2026-04-29): adopt provider/model from the Completed+ # event — that is the SUCCESSFUL source. If a later fallback+ # attempt delivers tokens again (rare — multi-step tool+ # loop), the later value wins; that's OK because both were+ # successful. In the normal case of a voice session, _on_brain_completed+ # is called only once per turn with real data.if event.provider:t.provider = event.providerif event.model:@@ -624,7 +624,7 @@ class SessionRecorder:t.tool_calls.append(event.tool_name)def _on_tool_completed(self, event: ToolCallCompleted) -> None:- # Nur Roh-Event-Append — Liste wurde in _on_tool_started gepflegt.+ # Raw-event append only — the list was maintained in _on_tool_started.returndef _on_action_executed(self, event: ActionExecuted) -> None:@@ -655,7 +655,7 @@ class SessionRecorder:t.latency_total_ms = max(0, ts_ms - t.started_ms)# ------------------------------------------------------------------ # Raw-Event-Append (selektiv via Whitelist)+ # Raw-event append (selective via whitelist)# -----------------------------------------------------------------def _maybe_append_raw(self, event: Event, kind: str) -> None:@@ -712,25 +712,26 @@ class SessionRecorder:# --- Helpers -----------------------------------------------------------# VoiceTurnRow.tier-Literal — synchron mit jarvis/sessions/models.py halten.-# Welle-4-Migration: ``sub_jarvis`` Legacy-Wert weiter akzeptiert fuer-# Backwards-Kompatibilitaet alter Voice-Sessions in der DB; neue Turns-# nutzen ``openclaw``.+# VoiceTurnRow.tier literal — keep in sync with jarvis/sessions/models.py.+# Welle-4 migration: the ``sub_jarvis`` legacy value is still accepted for+# backwards compatibility with old voice sessions in the DB; new turns+# use ``openclaw``._VALID_TIERS: frozenset[str] = frozenset({"router", "openclaw", "sub_jarvis", "trivial", "fast", "deep", "code"})def _normalize_intent_level_to_tier(intent_level: str) -> str:- """Mappt eine Router-Decision (``decision.level``) auf einen Tier-Namen.-- Der Router emittiert ``BrainTurnStarted.intent_level`` als die getroffene- Routing-Decision (``trivial`` / ``direct_action`` / ``spawn_worker``).- Recorder-Schema erlaubt fuer ``tier`` aber nur die Tier-Bezeichner- ``router``/``openclaw``/usw. Alles ausserhalb wird zu ``"router"`` —- semantisch korrekt, weil in beiden Faellen (direct_action, spawn) der- Router-Brain den Turn beantwortet hat. OpenClaw-Tier wird in- ``_on_openclaw_task_started`` explizit ueberschrieben.+ """Maps a router decision (``decision.level``) to a tier name.++ The router emits ``BrainTurnStarted.intent_level`` as the routing+ decision it made (``trivial`` / ``direct_action`` / ``spawn_worker``).+ The recorder schema, however, only allows the tier identifiers+ ``router``/``openclaw``/etc. for ``tier``. Anything outside that set+ becomes ``"router"`` — semantically correct, because in both cases+ (direct_action, spawn) the router brain answered the turn. The+ OpenClaw tier is explicitly overridden in+ ``_on_openclaw_task_started``."""if intent_level in _VALID_TIERS:return intent_level@@ -742,10 +743,10 @@ def _now_ms() -> int:def _payload_for(event: Event) -> dict[str, Any]:- """Selektiert die fuer Replay relevanten Felder eines Events.+ """Selects the fields of an event relevant for replay.- Vermeidet Riesen-Payloads (z.B. komplette Transcript-Audio-Refs)- und filtert privacy-sensitive Felder. Whitelist > Blacklist.+ Avoids giant payloads (e.g. complete transcript audio refs)+ and filters privacy-sensitive fields. Whitelist > blacklist."""fields_whitelist = {"keyword",@@ -824,10 +825,10 @@ def _payload_for(event: Event) -> dict[str, Any]:v = getattr(event, k)if v is None:continue- # Tuples zu Listen fuer JSON-Serialisierbarkeit+ # Tuples to lists for JSON serializabilityif isinstance(v, tuple):v = list(v)- # Transcript-Sub-Object: nur text + language+ # Transcript sub-object: only text + languageif k == "transcript" and v is not None:payload["text"] = getattr(v, "text", "")payload["lang"] = getattr(v, "language", "")diff --git a/jarvis/sessions/store.py b/jarvis/sessions/store.pyindex 021d7ffce3..3f9309a5ec 100644--- a/jarvis/sessions/store.py+++ b/jarvis/sessions/store.py@@ -1,20 +1,20 @@-"""SQLite-Store fuer Voice-Sessions (sync, WAL-Mode).--Im Unterschied zu ``jarvis/missions/event_store.py`` (aiosqlite, async)-laeuft dieser Store synchron mit ``sqlite3`` + ``threading.Lock``.-Begruendung: der ``SessionRecorder`` wird aus EventBus-Subscriber--Callbacks aufgerufen; das passiert je nach Event aus dem asyncio-Loop-ODER aus einem Worker-Thread (Pipeline ist Multi-Threaded). Ein-synchroner Store mit Lock ist der einfachste Pfad ohne Loop-Detection--Hacks. SQLite-Writes liegen im µs-Bereich, Lock-Contention ist auf-einem Voice-Pfad mit < 100 Events/Sek nicht messbar.--Atomicitaet: WAL + ``synchronous=NORMAL`` flusht Writes auf Disk;-zwischen Process-Crash und Bus-Publish kann ein Event verloren gehen-- bei Voice-Sessions akzeptabel (nicht-kritisches UI-Feature).--Cleanup: ``prune_older_than(days)`` loescht alte Sessions; ON DELETE-CASCADE in schema.sql raeumt Turns + Events automatisch mit.+"""SQLite store for voice sessions (sync, WAL mode).++Unlike ``jarvis/missions/event_store.py`` (aiosqlite, async),+this store runs synchronously with ``sqlite3`` + ``threading.Lock``.+Rationale: the ``SessionRecorder`` is called from EventBus subscriber+callbacks; depending on the event this happens from the asyncio loop+OR from a worker thread (the pipeline is multi-threaded). A+synchronous store with a lock is the simplest path without loop-detection+hacks. SQLite writes are in the µs range, and lock contention is+unmeasurable on a voice path with < 100 events/sec.++Atomicity: WAL + ``synchronous=NORMAL`` flushes writes to disk;+an event can be lost between a process crash and the bus publish+- acceptable for voice sessions (a non-critical UI feature).++Cleanup: ``prune_older_than(days)`` deletes old sessions; ON DELETE+CASCADE in schema.sql cleans up turns + events automatically along with it."""from __future__ import annotations@@ -35,7 +35,7 @@ _SCHEMA_PATH = Path(__file__).parent / "schema.sql"class SessionStore:- """Sync SQLite-Store mit threading.Lock-Synchronisation."""+ """Sync SQLite store with threading.Lock synchronization."""def __init__(self, db_path: Path) -> None:self._db_path = db_path@@ -45,17 +45,17 @@ class SessionStore:# --- Lifecycle ----------------------------------------------------def open(self) -> None:- """DB oeffnen, PRAGMAs setzen, Schema (idempotent) laden, Migrations."""+ """Open the DB, set PRAGMAs, load the schema (idempotent), run migrations."""with self._lock:if self._conn is not None:returnself._db_path.parent.mkdir(parents=True, exist_ok=True)- # check_same_thread=False: wir serialisieren selbst via self._lock,- # mehrere Threads (Pipeline-Worker, FastAPI-Routes) duerfen lesen+schreiben.+ # check_same_thread=False: we serialize ourselves via self._lock,+ # multiple threads (pipeline worker, FastAPI routes) may read+write.conn = sqlite3.connect(str(self._db_path),check_same_thread=False,- isolation_level=None, # autocommit; WAL ist Lock-Manager+ isolation_level=None, # autocommit; WAL is the lock manager)conn.execute("PRAGMA journal_mode=WAL")conn.execute("PRAGMA synchronous=NORMAL")@@ -69,11 +69,11 @@ class SessionStore:log.debug("SessionStore opened: %s", self._db_path)def _apply_migrations(self) -> None:- """Idempotente Spalten-Migrations fuer pre-existing DBs.+ """Idempotent column migrations for pre-existing DBs.- SQLite hat kein ``ADD COLUMN IF NOT EXISTS`` — wir lesen- ``pragma_table_info`` und appendieren nur fehlende Spalten.- Pattern uebernommen aus ``jarvis/missions/event_store.py``.+ SQLite has no ``ADD COLUMN IF NOT EXISTS`` — we read+ ``pragma_table_info`` and only append missing columns.+ Pattern adopted from ``jarvis/missions/event_store.py``."""assert self._conn is not Nonecur = self._conn.execute("PRAGMA table_info(voice_turns)")@@ -104,7 +104,7 @@ class SessionStore:@propertydef _c(self) -> sqlite3.Connection:if self._conn is None:- raise RuntimeError("SessionStore: open() vor Verwendung aufrufen")+ raise RuntimeError("SessionStore: call open() before use")return self._conn# --- Session-Header ----------------------------------------------@@ -117,10 +117,10 @@ class SessionStore:wake_keyword: str = "",language: str = "de",) -> None:- """Anlegen oder (bei Recorder-Re-Init) idempotent re-upserten.+ """Create, or (on a recorder re-init) idempotently re-upsert.- ON CONFLICT: ``started_ms`` bleibt erhalten (erstes Wake gewinnt),- nur ``wake_keyword``/``language`` werden ggf. ueberschrieben.+ ON CONFLICT: ``started_ms`` is preserved (the first wake wins),+ only ``wake_keyword``/``language`` may get overwritten."""with self._lock:self._c.execute(@@ -147,7 +147,7 @@ class SessionStore:total_tokens_out: int,providers_used: list[str],) -> None:- """Hangup-Update — schreibt End-Zeit und Aggregate."""+ """Hangup update — writes the end time and aggregates."""with self._lock:self._c.execute("""@@ -271,7 +271,7 @@ class SessionStore:kind: str,payload: dict[str, Any],) -> int:- """Roh-Event anhaengen, gibt vergebene seq zurueck."""+ """Append a raw event, returns the assigned seq."""with self._lock:cur = self._c.execute("""@@ -288,10 +288,10 @@ class SessionStore:# --- Read-API -----------------------------------------------------def list_sessions(self, *, limit: int = 100) -> list[SessionListItem]:- """Sessions nach started_ms desc — neueste zuerst.+ """Sessions by started_ms desc — newest first.- ``preview`` ist die erste User-Utterance (erste Turn-Row mit- nicht-leerem ``user_text``).+ ``preview`` is the first user utterance (the first turn row with+ a non-empty ``user_text``)."""with self._lock:cur = self._c.execute(@@ -397,7 +397,7 @@ class SessionStore:]def list_open_sessions(self) -> list[str]:- """IDs aller Sessions ohne ``ended_ms`` — fuer Crash-Recovery."""+ """IDs of all sessions without ``ended_ms`` — for crash recovery."""with self._lock:cur = self._c.execute("SELECT id FROM voice_sessions WHERE ended_ms IS NULL"@@ -407,10 +407,10 @@ class SessionStore:# --- Maintenance --------------------------------------------------def prune_older_than(self, days: int) -> int:- """Loescht Sessions mit ``started_ms`` aelter als N Tage.+ """Deletes sessions with ``started_ms`` older than N days.- Cascade-Delete in schema.sql raeumt Turns + Events automatisch- mit. Returns Anzahl geloeschter Session-Rows.+ Cascade delete in schema.sql cleans up turns + events+ automatically along with it. Returns the number of deleted session rows."""if days <= 0:return 0@@ -443,7 +443,7 @@ def _now_ms() -> int:def _json_default(obj: Any) -> Any:- """Fallback fuer json.dumps: UUID, set, dataclass-ish."""+ """Fallback for json.dumps: UUID, set, dataclass-ish."""if hasattr(obj, "hex") and hasattr(obj, "int"): # UUIDreturn str(obj)if isinstance(obj, set):@@ -496,10 +496,10 @@ def _row_to_turn(r: sqlite3.Row) -> VoiceTurnRow:def _safe_col(r: sqlite3.Row, name: str, default: int) -> int:- """Liest eine Spalte, gibt Default zurueck wenn sie nicht existiert.+ """Reads a column, returns the default if it doesn't exist.- Brauchen wir nur fuer das schmale Fenster, in dem ein laufender- Backend noch ohne Migration startet — schadet im Normalfall nicht.+ We only need this for the narrow window in which a running+ backend still starts without the migration — harmless in the normal case."""try:v = r[name]diff --git a/jarvis/skills/authoring/schema.py b/jarvis/skills/authoring/schema.pyindex d56a58c736..540de29f7e 100644--- a/jarvis/skills/authoring/schema.py+++ b/jarvis/skills/authoring/schema.py@@ -1,4 +1,4 @@-"""Pydantic-Modelle für die Skill-Authoring-Pipeline (Phase 7.5)."""+"""Pydantic models for the skill-authoring pipeline (Phase 7.5)."""from __future__ import annotationsfrom typing import Literal@@ -9,13 +9,13 @@ from pydantic import BaseModel, ConfigDict, Field, field_validatorclass SkillDraft(BaseModel):"""Strict-typed OpenClaw-Author-Output.- Welle-4-Migration: vorher Sub-Jarvis-Output. Heute OpenClaw-Worker- (siehe docs/openclaw-bridge.md §11). Schema bleibt 1:1.+ Wave-4 migration: previously Sub-Jarvis output. Now OpenClaw worker+ (see docs/openclaw-bridge.md §11). Schema stays 1:1.- Worker liefert eine vollständige Skill-Spezifikation. Plan-§7.5:- bei Parse-Fehler scheitert der Authoring-Versuch und schreibt ein- `author_failed_parse`-Audit-Event. Alle Felder sind required im- strict-Mode (Plan-§AD-9).+ The worker delivers a complete skill specification. Plan §7.5: on a+ parse error the authoring attempt fails and writes an+ `author_failed_parse` audit event. All fields are required in+ strict mode (Plan §AD-9)."""model_config = ConfigDict(frozen=True, extra="forbid")@@ -25,32 +25,32 @@ class SkillDraft(BaseModel):description: str = Field(min_length=1, max_length=400)category: str = "general"intent: str = Field(min_length=1)- triggers_yaml: str = Field(default="[]") # YAML-Array-Literal+ triggers_yaml: str = Field(default="[]") # YAML array literalrequires_tools: list[str] = Field(default_factory=list)body_markdown: str = Field(min_length=1)- # Der Worker darf hier `state` setzen — der `draft_writer` ignoriert- # das aber unconditional und forciert "draft" (Plan-§AD-8). Das- # explizite Field hier macht das Modell parsbar wenn das LLM `active`- # ausgibt; der Override wird im Audit als `forced_state_override=True`- # vermerkt.+ # The worker is allowed to set `state` here — but `draft_writer`+ # unconditionally ignores it and forces "draft" (Plan §AD-8). The+ # explicit field here keeps the model parsable if the LLM emits `active`;+ # the override is recorded in the audit trail as+ # `forced_state_override=True`.state: Literal["draft", "validated", "active", "disabled"] = "draft"@field_validator("slug")@classmethoddef _validate_slug(cls, v: str) -> str:- """Slug-Hardening (Plan-§AP-10 + Path-Traversal-Schutz):- - lowercase ASCII, nur a-z, 0-9, Bindestrich- - max 64 Zeichen- - keine Path-Traversal-Sequenzen (`..`, `/`, `\\`)+ """Slug hardening (Plan §AP-10 + path-traversal protection):+ - lowercase ASCII, only a-z, 0-9, hyphen+ - max 64 characters+ - no path-traversal sequences (`..`, `/`, `\\`)"""if not v:- raise ValueError("slug darf nicht leer sein")+ raise ValueError("slug must not be empty")normalized = v.strip().lower()if any(c in normalized for c in ("/", "\\", "..", " ")):- raise ValueError(f"slug enthält Path-Traversal-Zeichen: {v!r}")+ raise ValueError(f"slug contains path-traversal characters: {v!r}")for ch in normalized:if not (ch.isalnum() or ch in "-_"):raise ValueError(- f"slug enthält ungültige Zeichen: {ch!r} (nur a-z, 0-9, '-', '_')"+ f"slug contains invalid characters: {ch!r} (only a-z, 0-9, '-', '_')")return normalizeddiff --git a/jarvis/skills/bootstrap.py b/jarvis/skills/bootstrap.pyindex 720aceb2cb..804ed2ffec 100644--- a/jarvis/skills/bootstrap.py+++ b/jarvis/skills/bootstrap.py@@ -1,22 +1,23 @@-"""First-Run-Bootstrap fuer den User-Skill-Ordner.--Kopiert die mitgelieferten Builtin-Skills aus ``jarvis/skills/builtin/`` nach-``user_skills_dir()``, wenn sie dort noch nicht liegen. Idempotent — bei jedem-Start aufrufbar; vorhandene User-Edits werden nie ueberschrieben.--Warum ueberhaupt kopieren (statt nur aus ``builtin/`` laden)?--- Der ``SkillRegistry``-Watcher (``jarvis/skills/registry.py``) beobachtet *eine*- Root. Wenn alle Skills an einem Ort liegen, funktioniert Hot-Reload out-of-the-box.-- Der User soll Builtins *sehen* und inspizieren koennen. Versteckte Read-only-- Kopien im site-packages-Verzeichnis sind fuer Skills-Autoren intransparent.-- Admin-Edit-Protection (siehe ``skills_routes.py``) kann per Pfad-Check erkennen- was ein Builtin ist (Name in ``BUILTIN_SKILL_NAMES``) — der Rest ist User-Space.--Bootstrap-Versionierung: eine ``.bootstrap-version`` im User-Skills-Dir speichert-die zuletzt gebootstrappte Package-Version. Bei Mismatch werden fehlende Skills-neu kopiert (bestehende bleiben). So kommt z.B. ein neuer Builtin-Skill in einer-spaeteren Version automatisch rueber, ohne User-Anpassungen zu zerstoeren.+"""First-run bootstrap for the user skill folder.++Copies the bundled builtin skills from ``jarvis/skills/builtin/`` into+``user_skills_dir()`` if they aren't already there. Idempotent — safe to call+on every start; existing user edits are never overwritten.++Why copy at all (instead of just loading from ``builtin/``)?++- The ``SkillRegistry`` watcher (``jarvis/skills/registry.py``) watches *one*+ root. When all skills live in one place, hot reload works out of the box.+- The user should be able to *see* and inspect builtins. Hidden read-only+ copies in the site-packages directory are opaque to skill authors.+- Admin edit protection (see ``skills_routes.py``) can tell what's a builtin+ via a path check (name in ``BUILTIN_SKILL_NAMES``) — the rest is user space.++Bootstrap versioning: a ``.bootstrap-version`` file in the user skills dir+stores the last bootstrapped package version. On a mismatch, missing skills+are copied in again (existing ones are left alone). That's how, e.g., a new+builtin skill added in a later version automatically arrives without+destroying user customizations."""from __future__ import annotations@@ -64,21 +65,22 @@ _V2_SHIPPED_HASHES: dict[str, str] = {def ensure_user_skills_dir() -> Path:- """Legt ``user_skills_dir()`` an und kopiert fehlende Builtin-Skills hinein.+ """Creates ``user_skills_dir()`` and copies in any missing builtin skills.- Zwei Faelle pro Builtin:+ Two cases per builtin:- 1. **Komplett neu:** User hat den Skill-Ordner noch nicht -> kompletter- ``copytree`` von Builtin-Root nach User-Root.- 2. **Upgrade:** User hat schon eine ``SKILL.md`` (darf editiert sein, nicht- ueberschreiben), aber dem Builtin wurden Bundle-Sibling-Ordner- hinzugefuegt -> nur die fehlenden Kind-Ordner nachziehen.+ 1. **Brand new:** the user doesn't have the skill folder yet -> a full+ ``copytree`` from the builtin root to the user root.+ 2. **Upgrade:** the user already has a ``SKILL.md`` (may be edited, must+ not be overwritten), but the builtin gained bundle sibling folders+ -> pull in only the missing child folders.- So behalten wir die "Never touch user-edited SKILL.md"-Garantie, rollen aber- neue Bundle-Resources (``references/``, ``scripts/``, …) automatisch nach.+ This keeps the "never touch a user-edited SKILL.md" guarantee while still+ rolling out new bundle resources (``references/``, ``scripts/``, …)+ automatically.- Returns den User-Skills-Pfad, damit Aufrufer ihn direkt als Registry-Root- verwenden koennen.+ Returns the user skills path so callers can use it directly as the+ registry root."""ensure_user_dirs()dst_root = user_skills_dir()@@ -179,11 +181,11 @@ def _write_shipped_hashes(dst_root: Path, manifest: dict[str, str]) -> None:def _sync_missing_resources(src: Path, dst: Path) -> list[str]:- """Kopiert Sibling-Ordner (references/scripts/assets/agents), die im- Builtin existieren aber im User-Dir fehlen. Vorhandene User-Ordner werden- **nicht** angefasst — auch wenn der Builtin dort neue Files hat. Das ist- die konservative Default-Policy; ein expliziter "force-sync"-Modus waere- eine spaetere Erweiterung.+ """Copies sibling folders (references/scripts/assets/agents) that exist+ in the builtin but are missing from the user dir. Existing user folders+ are **not** touched — even if the builtin has new files in them. This is+ the conservative default policy; an explicit "force-sync" mode would be+ a later extension."""added: list[str] = []for kind in RESOURCE_KINDS:@@ -192,18 +194,18 @@ def _sync_missing_resources(src: Path, dst: Path) -> list[str]:if not src_kind.is_dir():continueif dst_kind.exists():- continue # User hat den Ordner schon — hands off+ continue # user already has the folder — hands offtry:shutil.copytree(src_kind, dst_kind)added.append(kind)except Exception as exc: # noqa: BLE001- log.warning("sync resource '%s/%s' fehlgeschlagen: %s", dst.name, kind, exc)+ log.warning("sync resource '%s/%s' failed: %s", dst.name, kind, exc)return addeddef _write_version_marker(dst_root: Path) -> None:- """Schreibt den Bootstrap-Version-Marker. Fehler werden geschluckt —- der Marker ist reine Info, kein Blocker."""+ """Writes the bootstrap version marker. Failures are swallowed —+ the marker is pure info, not a blocker."""try:(dst_root / BOOTSTRAP_VERSION_FILE).write_text(BOOTSTRAP_VERSION, encoding="utf-8"diff --git a/jarvis/skills/builtin/__init__.py b/jarvis/skills/builtin/__init__.pyindex 88c85e427e..41db34cce2 100644--- a/jarvis/skills/builtin/__init__.py+++ b/jarvis/skills/builtin/__init__.py@@ -1,16 +1,17 @@-"""Built-in Skills für Jarvis.+"""Built-in skills for Jarvis.-Jedes Unterverzeichnis enthält genau eine `SKILL.md` mit YAML-Frontmatter-(siehe `jarvis.skills.schema.SkillFrontmatter`). Diese Skills werden beim-First-Run von `jarvis.skills.bootstrap.ensure_user_skills_dir()` in-`user_skills_dir()` kopiert (Windows: `%LOCALAPPDATA%\Jarvis\skills`) —-von dort aus liest die `SkillRegistry` und watcht via watchdog.+Each subdirectory contains exactly one `SKILL.md` with YAML frontmatter+(see `jarvis.skills.schema.SkillFrontmatter`). On first run these skills are+copied into `user_skills_dir()` by+`jarvis.skills.bootstrap.ensure_user_skills_dir()` (Windows:+`%LOCALAPPDATA%\Jarvis\skills`) — the `SkillRegistry` reads from and watches+that location.-Liste der mitgelieferten Skills:- - morning-routine Kalender / Mail / Wetter Morgen-Briefing- - deep-work-mode DND + Fokus-Timer per Hotkey/Voice- - memory-save "merk dir ..." in Memory-MCP speichern- - skill-creator Meta-Skill zum Bauen weiterer Skills+List of bundled skills:+ - morning-routine calendar / mail / weather morning briefing+ - deep-work-mode DND + focus timer via hotkey/voice+ - memory-save "remember that ..." saved to memory-MCP+ - skill-creator meta-skill for building further skills- plugin-<id> Paired skills for marketplace plugins (2026-06-07): eachteaches the router which voice/chat intents reach theconnected plugin's tools (gmail, github, stripe, ...).@@ -58,7 +59,7 @@ BUILTIN_SKILL_NAMES: tuple[str, ...] = (def builtin_skill_path(name: str) -> Path:- """Gibt den Pfad zur SKILL.md eines Built-in-Skills zurück."""+ """Returns the path to a built-in skill's SKILL.md."""return BUILTIN_SKILLS_DIR / name / "SKILL.md"diff --git a/jarvis/skills/builtin/jarvis-doc-author/references/frontmatter-schema.md b/jarvis/skills/builtin/jarvis-doc-author/references/frontmatter-schema.mdindex 8f1835afe3..b8909660bc 100644--- a/jarvis/skills/builtin/jarvis-doc-author/references/frontmatter-schema.md+++ b/jarvis/skills/builtin/jarvis-doc-author/references/frontmatter-schema.md@@ -25,8 +25,8 @@ These are the **7 required fields**. Everything else is optional.```yaml----title: "How-To: Einen neuen Brain-Provider hinzufuegen"-slug: brain-provider-hinzufuegen+title: "How-To: Add a new Brain provider"+slug: add-brain-providerdiataxis: howtostatus: activeowner: harald@@ -76,10 +76,10 @@ sidebar.| Bad (too long, truncated) | Good (compact, fully readable) ||---|---|-| ``"ADR-0001 — IPC zwischen Jarvis-App und Admin-Helper: Named Pipe + HMAC"`` (66) | ``"ADR-0001: IPC via Named Pipe + HMAC"`` (35) |-| ``"ADR-0008 — Computer-Use-Harness laeuft in-process (Ausnahme zum Subprocess-Pattern)"`` (84) | ``"ADR-0008: Computer-Use in-process"`` (33) |-| ``"ADR-0009 — Self-Healing Worker-Critic-Loop mit Action/Observation-Invariante"`` (76) | ``"ADR-0009: Self-Healing Worker-Critic"`` (37) |-| ``"How-To: Einen neuen Brain-Provider zu jarvis.toml hinzufuegen und registrieren"`` (78) | ``"How-To: Neuen Brain-Provider hinzufuegen"`` (40) |+| ``"ADR-0001 — IPC between Jarvis App and Admin Helper: Named Pipe + HMAC"`` (69) | ``"ADR-0001: IPC via Named Pipe + HMAC"`` (35) |+| ``"ADR-0008 — Computer-Use harness runs in-process (exception to the subprocess pattern)"`` (85) | ``"ADR-0008: Computer-Use in-process"`` (33) |+| ``"ADR-0009 — Self-Healing Worker-Critic loop with an action/observation invariant"`` (79) | ``"ADR-0009: Self-Healing Worker-Critic"`` (37) |+| ``"How-To: Add a new Brain provider to jarvis.toml and register it"`` (63) | ``"How-To: Add a new Brain provider"`` (32) |### ``slug`` (string, kebab-case)@@ -92,10 +92,8 @@ URL-stable identifier. Makes the doc referenceable by othersslug + set ``deprecated_by``, redirect hint in the old doc.- Lowercase, kebab-case (``router-discipline``, not ``RouterDiscipline``or ``router_discipline``).-- English or transliterated German without umlauts (``oeffnen`` instead of- ``öffnen``, ``brueckenmodul`` instead of ``brückenmodul``).-- Language-free where possible — the slug is a technical identifier, not a UI- string.+- English only — the repo is English-only for committed artifacts, and a slug+ is a technical identifier, not a UI string, so there is no exception for it.### ``diataxis`` (enum)@@ -268,8 +266,8 @@ related:- <further-references>```-A how-to slug ideally starts with a verb: ``hinzufuegen`` (add),-``deploy``, ``aktivieren`` (activate). Makes the intent immediately clear.+A how-to slug ideally starts with a verb: ``add``,+``deploy``, ``activate``. Makes the intent immediately clear.### Referencediff --git a/jarvis/skills/builtin/skill-creator/references/jarvis-schema.md b/jarvis/skills/builtin/skill-creator/references/jarvis-schema.mdindex 3bd4d23cad..b5bbca545e 100644--- a/jarvis/skills/builtin/skill-creator/references/jarvis-schema.md+++ b/jarvis/skills/builtin/skill-creator/references/jarvis-schema.md@@ -34,14 +34,14 @@ matching field must be set:```yamltriggers:- type: voice- pattern: "^(guten morgen|good morning)$" # Regex, re.IGNORECASE wird beim Match gesetzt- language: [de, en] # optional, Default [de, en]+ pattern: "^(guten morgen|good morning)$" # regex, re.IGNORECASE is applied at match time <!-- i18n-allow -->+ language: [de, en] # optional, default [de, en]- type: hotkey- combo: "ctrl+right_alt+j" # global-hotkeys-Syntax+ combo: "ctrl+right_alt+j" # global-hotkeys syntax- type: schedule- cron: "0 7 * * *" # croniter-Syntax (5 Felder)+ cron: "0 7 * * *" # croniter syntax (5 fields)```**Voice patterns:**@@ -63,10 +63,10 @@ triggers:```yamlrisk_policy:default_tier: monitor # safe | monitor | ask | block- per_tool_overrides: # pro-Tool anderer Tier+ per_tool_overrides: # different tier per toolgmail-mcp/send_mail: askfetch-mcp/fetch_weather: safe- require_confirmation: # Tool-Aufrufe die immer Bestaetigung kriegen+ require_confirmation: # tool calls that always require confirmation- send_money```@@ -96,7 +96,7 @@ Analogous to Anthropic's structure, a skill folder may have sibling directories:```<skill-name>/├── SKILL.md (Pflicht)-├── references/ (Markdown-Docs, on-demand geladen)+├── references/ (Markdown docs, loaded on-demand)├── scripts/ (Python/Shell, vom Runner aufrufbar)├── assets/ (Templates, Configs, Icons)└── agents/ (Sub-Agent-Personas als Markdown)diff --git a/jarvis/skills/catalog/__init__.py b/jarvis/skills/catalog/__init__.pyindex 4fe64d8c7c..6779fff924 100644--- a/jarvis/skills/catalog/__init__.py+++ b/jarvis/skills/catalog/__init__.py@@ -1,18 +1,18 @@-"""Kuratierter Seed-Katalog fuer den Skill-Finder.+"""Curated seed catalog for the skill finder.-Der Katalog ist eine statische JSON-Datei mit handgepflegten Eintraegen aus:-- Anthropic's offiziellem Skills-Repo (https://github.com/anthropics/skills)-- skills.sh (Community-Aggregator)-- GitHub-Repos mit nachweislichem Skill-Format (SKILL.md + YAML-Frontmatter)+The catalog is a static JSON file with hand-maintained entries from:+- Anthropic's official skills repo (https://github.com/anthropics/skills)+- skills.sh (community aggregator)+- GitHub repos with a verified skill format (SKILL.md + YAML frontmatter)-Der Katalog ist keine Runtime-Source-of-Truth — er ist der Seed, den der-``SkillFinder`` dem Brain als Kandidaten-Pool uebergibt. Das Brain rankt und-filtert basierend auf User-Query + Trust/Category/Risk-Preferences.+The catalog is not a runtime source of truth — it's the seed that the+``SkillFinder`` hands to the brain as a candidate pool. The brain ranks and+filters based on the user query + trust/category/risk preferences.-Erweiterung:-- Hand: Neue Eintraege in ``seed_catalog.json`` ergaenzen.-- Zukunft: Scraper-Job, der skills.sh + GitHub periodisch neu einliest und- die JSON ersetzt (aehnlich wie man eine Package-Index neu baut).+Extending it:+- By hand: add new entries to ``seed_catalog.json``.+- Future: a scraper job that periodically re-reads skills.sh + GitHub and+ replaces the JSON (similar to rebuilding a package index)."""from __future__ import annotations@@ -26,11 +26,11 @@ CATALOG_PATH = Path(__file__).parent / "seed_catalog.json"@lru_cache(maxsize=1)def load_catalog() -> list[dict[str, Any]]:- """Laedt die Eintraege aus dem Seed-Katalog.+ """Loads the entries from the seed catalog.- Cached fuer den Prozess-Lifetime — der Katalog ist statisch, und wir wollen- nicht bei jedem Request die JSON neu parsen. Bei Hot-Swap (z.B. wenn ein- Scraper die Datei ersetzt) muss ``load_catalog.cache_clear()`` gerufen werden.+ Cached for the process lifetime — the catalog is static, and we don't+ want to re-parse the JSON on every request. On a hot swap (e.g. when a+ scraper replaces the file), ``load_catalog.cache_clear()`` must be called."""if not CATALOG_PATH.exists():return []diff --git a/jarvis/skills/catalog/seed_catalog.json b/jarvis/skills/catalog/seed_catalog.jsonindex a22c8e00c6..1b8538668a 100644--- a/jarvis/skills/catalog/seed_catalog.json+++ b/jarvis/skills/catalog/seed_catalog.json@@ -1,12 +1,12 @@{"schema_version": "1","updated": "2026-04-22",- "note": "Kuratierter Seed-Katalog fuer den SkillFinder. Erweiterbar per Hand oder via Scraper-Job. Trust-Levels: official (Anthropic/OpenAI), verified (3000+ GitHub-Stars oder mehrfach gepruefte Maintainer), community (aktiv gewartet, <3000 Stars), experimental (Prototyp, Solo-Dev).",+ "note": "Curated seed catalog for the SkillFinder. Extensible by hand or via a scraper job. Trust levels: official (Anthropic/OpenAI), verified (3000+ GitHub stars or a repeatedly vetted maintainer), community (actively maintained, <3000 stars), experimental (prototype, solo dev).","entries": [{"name": "brainstorming","title": "Brainstorming / Ideenfindung",- "description": "Interaktive Exploration von User-Intent vor jeder kreativen Arbeit — stellt gezielte Rueckfragen, bevor Code oder Feature implementiert wird.",+ "description": "Interactive exploration of user intent before any creative work — asks targeted follow-up questions before code or a feature gets implemented.","source": "anthropic","source_url": "https://github.com/anthropics/skills/tree/main/skills/brainstorming","raw_url": "https://raw.githubusercontent.com/anthropics/skills/main/skills/brainstorming/SKILL.md",@@ -20,7 +20,7 @@{"name": "skill-creator","title": "Skill Creator",- "description": "Erstellt neue Skills und verbessert bestehende iterativ — Anthropic's offizielles Autoren-Toolkit.",+ "description": "Creates new skills and iteratively improves existing ones — Anthropic's official authoring toolkit.","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",@@ -34,7 +34,7 @@{"name": "writing-plans","title": "Writing Plans",- "description": "Schreibt strukturierte Implementation-Plaene fuer mehrstufige Aufgaben — Spec-Driven-Development.",+ "description": "Writes structured implementation plans for multi-step tasks — spec-driven development.","source": "anthropic","source_url": "https://github.com/anthropics/skills/tree/main/skills/writing-plans","raw_url": "https://raw.githubusercontent.com/anthropics/skills/main/skills/writing-plans/SKILL.md",@@ -48,7 +48,7 @@{"name": "executing-plans","title": "Executing Plans",- "description": "Fuehrt geschriebene Implementation-Plaene in isolierten Sessions mit Review-Checkpoints aus.",+ "description": "Executes written implementation plans in isolated sessions with review checkpoints.","source": "anthropic","source_url": "https://github.com/anthropics/skills/tree/main/skills/executing-plans","raw_url": "https://raw.githubusercontent.com/anthropics/skills/main/skills/executing-plans/SKILL.md",@@ -62,7 +62,7 @@{"name": "test-driven-development","title": "Test-Driven Development",- "description": "Red-Green-Refactor-Disziplin — schreibt Tests vor Implementation bei jedem Feature/Bugfix.",+ "description": "Red-green-refactor discipline — writes tests before implementation for every feature/bugfix.","source": "anthropic","source_url": "https://github.com/anthropics/skills/tree/main/skills/test-driven-development","raw_url": "https://raw.githubusercontent.com/anthropics/skills/main/skills/test-driven-development/SKILL.md",@@ -76,7 +76,7 @@{"name": "systematic-debugging","title": "Systematic Debugging",- "description": "Strukturierte Debug-Methodik — bei jedem Bug, Test-Failure oder unerwarteten Verhalten, bevor Fixes vorgeschlagen werden.",+ "description": "Structured debugging methodology — for every bug, test failure, or unexpected behavior, before fixes are proposed.","source": "anthropic","source_url": "https://github.com/anthropics/skills/tree/main/skills/systematic-debugging","raw_url": "https://raw.githubusercontent.com/anthropics/skills/main/skills/systematic-debugging/SKILL.md",@@ -90,7 +90,7 @@{"name": "verification-before-completion","title": "Verification Before Completion",- "description": "Verifiziert Arbeit durch Command-Ausfuehrung, bevor Erfolg behauptet wird — Evidence before assertions.",+ "description": "Verifies work by running commands before claiming success — evidence before assertions.","source": "anthropic","source_url": "https://github.com/anthropics/skills/tree/main/skills/verification-before-completion","raw_url": "https://raw.githubusercontent.com/anthropics/skills/main/skills/verification-before-completion/SKILL.md",@@ -104,7 +104,7 @@{"name": "using-git-worktrees","title": "Using Git Worktrees",- "description": "Erstellt isolierte Git-Worktrees fuer Feature-Arbeit — verhindert Konflikte mit laufender Arbeit.",+ "description": "Creates isolated git worktrees for feature work — prevents conflicts with work in progress.","source": "anthropic","source_url": "https://github.com/anthropics/skills/tree/main/skills/using-git-worktrees","raw_url": "https://raw.githubusercontent.com/anthropics/skills/main/skills/using-git-worktrees/SKILL.md",@@ -118,7 +118,7 @@{"name": "receiving-code-review","title": "Receiving Code Review",- "description": "Technisch rigoros mit Code-Review-Feedback umgehen — Verifikation statt blinder Zustimmung.",+ "description": "Handles code-review feedback with technical rigor — verification instead of blind agreement.","source": "anthropic","source_url": "https://github.com/anthropics/skills/tree/main/skills/receiving-code-review","raw_url": "https://raw.githubusercontent.com/anthropics/skills/main/skills/receiving-code-review/SKILL.md",@@ -132,7 +132,7 @@{"name": "requesting-code-review","title": "Requesting Code Review",- "description": "Fordert Code-Review an, bevor gemerged wird — Verifikation der Completeness.",+ "description": "Requests code review before merging — verifies completeness.","source": "anthropic","source_url": "https://github.com/anthropics/skills/tree/main/skills/requesting-code-review","raw_url": "https://raw.githubusercontent.com/anthropics/skills/main/skills/requesting-code-review/SKILL.md",@@ -146,7 +146,7 @@{"name": "finishing-a-development-branch","title": "Finishing a Development Branch",- "description": "Fuehrt strukturiert durch den Abschluss einer Feature-Branch: Merge, PR, Cleanup.",+ "description": "Guides you structurally through finishing a feature branch: merge, PR, cleanup.","source": "anthropic","source_url": "https://github.com/anthropics/skills/tree/main/skills/finishing-a-development-branch","raw_url": "https://raw.githubusercontent.com/anthropics/skills/main/skills/finishing-a-development-branch/SKILL.md",@@ -160,7 +160,7 @@{"name": "dispatching-parallel-agents","title": "Dispatching Parallel Agents",- "description": "Parallelisiert 2+ unabhaengige Tasks ueber mehrere Agents — ohne Shared-State.",+ "description": "Parallelizes 2+ independent tasks across multiple agents — without shared state.","source": "anthropic","source_url": "https://github.com/anthropics/skills/tree/main/skills/dispatching-parallel-agents","raw_url": "https://raw.githubusercontent.com/anthropics/skills/main/skills/dispatching-parallel-agents/SKILL.md",@@ -174,7 +174,7 @@{"name": "subagent-driven-development","title": "Subagent-Driven Development",- "description": "Fuehrt Implementation-Plaene mit unabhaengigen Tasks in der aktuellen Session aus — via Subagents.",+ "description": "Executes implementation plans with independent tasks in the current session — via subagents.","source": "anthropic","source_url": "https://github.com/anthropics/skills/tree/main/skills/subagent-driven-development","raw_url": "https://raw.githubusercontent.com/anthropics/skills/main/skills/subagent-driven-development/SKILL.md",@@ -188,7 +188,7 @@{"name": "writing-skills","title": "Writing Skills",- "description": "Meta-Skill: Erstellt oder bearbeitet andere Skills und verifiziert Funktionalitaet.",+ "description": "Meta-skill: creates or edits other skills and verifies functionality.","source": "anthropic","source_url": "https://github.com/anthropics/skills/tree/main/skills/writing-skills","raw_url": "https://raw.githubusercontent.com/anthropics/skills/main/skills/writing-skills/SKILL.md",@@ -202,7 +202,7 @@{"name": "using-superpowers","title": "Using Superpowers",- "description": "Etabliert wie andere Skills gefunden und genutzt werden — Start-of-Conversation-Skill.",+ "description": "Establishes how other skills are found and used — a start-of-conversation skill.","source": "anthropic","source_url": "https://github.com/anthropics/skills/tree/main/skills/using-superpowers","raw_url": "https://raw.githubusercontent.com/anthropics/skills/main/skills/using-superpowers/SKILL.md",@@ -216,7 +216,7 @@{"name": "web-design-guidelines","title": "Web Design Guidelines",- "description": "Review von UI-Code gegen Web-Interface-Guidelines — Accessibility, UX, Best-Practices.",+ "description": "Reviews UI code against web-interface guidelines — accessibility, UX, best practices.","source": "anthropic","source_url": "https://github.com/anthropics/skills/tree/main/skills/web-design-guidelines","raw_url": "https://raw.githubusercontent.com/anthropics/skills/main/skills/web-design-guidelines/SKILL.md",@@ -230,7 +230,7 @@{"name": "shadcn-ui","title": "shadcn/ui Integration",- "description": "Expert-Guidance fuer shadcn/ui-Component-Discovery, Installation und Customization.",+ "description": "Expert guidance for shadcn/ui component discovery, installation, and customization.","source": "anthropic","source_url": "https://github.com/anthropics/skills/tree/main/skills/shadcn-ui","raw_url": "https://raw.githubusercontent.com/anthropics/skills/main/skills/shadcn-ui/SKILL.md",@@ -244,7 +244,7 @@{"name": "frontend-design","title": "Frontend Design",- "description": "Erstellt distinctive, production-grade Frontend-Interfaces — jenseits generischer AI-Aesthetik.",+ "description": "Creates distinctive, production-grade frontend interfaces — beyond generic AI aesthetics.","source": "anthropic","source_url": "https://github.com/anthropics/skills/tree/main/skills/frontend-design","raw_url": "https://raw.githubusercontent.com/anthropics/skills/main/skills/frontend-design/SKILL.md",@@ -258,7 +258,7 @@{"name": "code-review","title": "Code Review",- "description": "Review eines Pull-Requests auf Qualitaet, Konventionen und Sicherheit.",+ "description": "Reviews a pull request for quality, conventions, and security.","source": "anthropic","source_url": "https://github.com/anthropics/skills/tree/main/skills/code-review","raw_url": "https://raw.githubusercontent.com/anthropics/skills/main/skills/code-review/SKILL.md",@@ -272,7 +272,7 @@{"name": "security-review","title": "Security Review",- "description": "Security-Review der aktuellen Branch — Schwachstellen-Scanning vor Merge.",+ "description": "Security review of the current branch — vulnerability scanning before merge.","source": "anthropic","source_url": "https://github.com/anthropics/skills/tree/main/skills/security-review","raw_url": "https://raw.githubusercontent.com/anthropics/skills/main/skills/security-review/SKILL.md",@@ -286,7 +286,7 @@{"name": "excalidraw-diagram","title": "Excalidraw Diagram",- "description": "Erstellt Excalidraw-Diagramme fuer Workflows, Architekturen, Konzepte — visuelle Argumente.",+ "description": "Creates Excalidraw diagrams for workflows, architectures, concepts — visual arguments.","source": "anthropic","source_url": "https://github.com/anthropics/skills/tree/main/skills/excalidraw-diagram-skill","raw_url": "https://raw.githubusercontent.com/anthropics/skills/main/skills/excalidraw-diagram-skill/SKILL.md",@@ -300,7 +300,7 @@{"name": "commit-commands","title": "Commit / Push / PR",- "description": "Struktur-Commit mit Conventional-Commit-Style, push und PR-Erstellung in einem Flow.",+ "description": "Structured commit with conventional-commit style, push, and PR creation in one flow.","source": "anthropic","source_url": "https://github.com/anthropics/skills/tree/main/skills/commit-commands","raw_url": "https://raw.githubusercontent.com/anthropics/skills/main/skills/commit-commands/SKILL.md",@@ -314,7 +314,7 @@{"name": "feature-dev","title": "Feature Dev (Guided)",- "description": "Gefuehrte Feature-Entwicklung mit Codebase-Understanding und Architektur-Fokus.",+ "description": "Guided feature development with codebase understanding and an architecture focus.","source": "anthropic","source_url": "https://github.com/anthropics/skills/tree/main/skills/feature-dev","raw_url": "https://raw.githubusercontent.com/anthropics/skills/main/skills/feature-dev/SKILL.md",@@ -328,7 +328,7 @@{"name": "simplify","title": "Simplify Code",- "description": "Reviewt geaenderten Code auf Reuse, Quality und Efficiency — fixed gefundene Issues.",+ "description": "Reviews changed code for reuse, quality, and efficiency — fixes issues it finds.","source": "anthropic","source_url": "https://github.com/anthropics/skills/tree/main/skills/simplify","raw_url": "https://raw.githubusercontent.com/anthropics/skills/main/skills/simplify/SKILL.md",@@ -342,7 +342,7 @@{"name": "claude-api","title": "Claude API Helper",- "description": "Baut, debuggt und optimiert Apps mit der Claude API / Anthropic SDK — inkl. Prompt-Caching.",+ "description": "Builds, debugs, and optimizes apps with the Claude API / Anthropic SDK — including prompt caching.","source": "anthropic","source_url": "https://github.com/anthropics/skills/tree/main/skills/claude-api","raw_url": "https://raw.githubusercontent.com/anthropics/skills/main/skills/claude-api/SKILL.md",@@ -356,7 +356,7 @@{"name": "pdf-extraction","title": "PDF Extraction",- "description": "Extrahiert Text, Tabellen und Metadaten aus PDF-Dokumenten strukturiert.",+ "description": "Extracts text, tables, and metadata from PDF documents in a structured way.","source": "skills-sh","source_url": "https://skills.sh/","raw_url": null,@@ -369,8 +369,8 @@},{"name": "markdown-to-slides",- "title": "Markdown zu Slides",- "description": "Konvertiert Markdown-Dokumente in praesentable Slide-Decks (Reveal.js / Marp).",+ "title": "Markdown to Slides",+ "description": "Converts Markdown documents into presentable slide decks (Reveal.js / Marp).","source": "skills-sh","source_url": "https://skills.sh/","raw_url": null,@@ -384,7 +384,7 @@{"name": "browser-automation","title": "Browser Automation",- "description": "Steuert Browser ueber Playwright — Scraping, Testing, Task-Automation.",+ "description": "Controls a browser via Playwright — scraping, testing, task automation.","source": "skills-sh","source_url": "https://skills.sh/","raw_url": null,@@ -398,7 +398,7 @@{"name": "email-triage","title": "Email Triage",- "description": "Priorisiert Inbox — kategorisiert, fasst zusammen, schlaegt Antworten vor.",+ "description": "Prioritizes your inbox — categorizes, summarizes, and suggests replies.","source": "skills-sh","source_url": "https://skills.sh/","raw_url": null,@@ -412,7 +412,7 @@{"name": "meeting-notes","title": "Meeting Notes",- "description": "Strukturiert Meeting-Notizen — Action-Items, Decisions, Follow-Ups.",+ "description": "Structures meeting notes — action items, decisions, follow-ups.","source": "skills-sh","source_url": "https://skills.sh/","raw_url": null,@@ -426,7 +426,7 @@{"name": "code-archaeology","title": "Code Archaeology",- "description": "Erforscht alte Codebases — Tracing-Patterns, Architektur-Rekonstruktion, Commit-Story.",+ "description": "Explores old codebases — tracing patterns, architecture reconstruction, commit history.","source": "community","source_url": "https://github.com/search?q=SKILL.md+code+archaeology","raw_url": null,@@ -440,7 +440,7 @@{"name": "api-scaffold","title": "API Scaffold",- "description": "Generiert API-Boilerplate — FastAPI, Express, Axum mit Best-Practice-Defaults.",+ "description": "Generates API boilerplate — FastAPI, Express, Axum with best-practice defaults.","source": "community","source_url": "https://github.com/search?q=SKILL.md+api+scaffold","raw_url": null,@@ -454,7 +454,7 @@{"name": "docker-helper","title": "Docker Helper",- "description": "Erstellt Dockerfiles und docker-compose-Setups mit Multi-Stage-Builds und Best-Practices.",+ "description": "Creates Dockerfiles and docker-compose setups with multi-stage builds and best practices.","source": "community","source_url": "https://github.com/search?q=SKILL.md+docker","raw_url": null,@@ -468,7 +468,7 @@{"name": "sql-optimizer","title": "SQL Optimizer",- "description": "Analysiert SQL-Queries, schlaegt Indexes vor, erklaert Query-Plans.",+ "description": "Analyzes SQL queries, suggests indexes, explains query plans.","source": "community","source_url": "https://github.com/search?q=SKILL.md+sql+optimizer","raw_url": null,@@ -482,7 +482,7 @@{"name": "regex-explain","title": "Regex Explainer",- "description": "Erklaert komplexe Regex-Patterns Schritt-fuer-Schritt und generiert neue.",+ "description": "Explains complex regex patterns step by step and generates new ones.","source": "community","source_url": "https://github.com/search?q=SKILL.md+regex","raw_url": null,@@ -496,7 +496,7 @@{"name": "cron-reminder","title": "Cron Reminder",- "description": "Verwaltet geplante Reminders via Cron-Expressions — mit natuerlichsprachlicher Eingabe.",+ "description": "Manages scheduled reminders via cron expressions — with natural-language input.","source": "experimental","source_url": "https://github.com/search?q=SKILL.md+cron+reminder","raw_url": null,@@ -510,7 +510,7 @@{"name": "voice-journal","title": "Voice Journal",- "description": "Voice-Driven-Tagebuch — STT plus Zusammenfassung plus automatisches Tagging.",+ "description": "Voice-driven journal — STT plus summarization plus automatic tagging.","source": "experimental","source_url": "https://github.com/search?q=SKILL.md+voice+journal","raw_url": null,@@ -524,7 +524,7 @@{"name": "gaming-log","title": "Gaming Log",- "description": "Loggt Gaming-Sessions, Achievements, Playtime — auch ueber Konsolen-Bridges.",+ "description": "Logs gaming sessions, achievements, playtime — even via console bridges.","source": "experimental","source_url": "https://github.com/search?q=SKILL.md+gaming","raw_url": null,diff --git a/jarvis/skills/cli.py b/jarvis/skills/cli.pyindex 1b83260640..8db2fd47a2 100644--- a/jarvis/skills/cli.py+++ b/jarvis/skills/cli.py@@ -1,20 +1,21 @@-"""Standalone-CLI fuer Skill-Management.+"""Standalone CLI for skill management.-Aufruf (ohne __main__.py-Touch, um Merge-Konflikte mit Phase 1b zu vermeiden):+Invocation (without touching __main__.py, to avoid merge conflicts with+Phase 1b):python -m jarvis.skills.cli --listpython -m jarvis.skills.cli --info morning-routinepython -m jarvis.skills.cli --run deep-work-modepython -m jarvis.skills.cli --import-claude-skills ~/.claude/skills/-Die CLI laedt Skills aus:- 1. user_skills_dir() (User-Skills; Windows: %LOCALAPPDATA%\Jarvis\skills)- 2. <project>/jarvis/skills/builtin/ (mitgelieferte Skills)+The CLI loads skills from:+ 1. user_skills_dir() (user skills; Windows: %LOCALAPPDATA%\Jarvis\skills)+ 2. <project>/jarvis/skills/builtin/ (bundled skills)-Beide Roots werden rekursiv durchsucht. Der Aufruf geht gracefully mit-fehlenden B1/B2-Komponenten um — wenn `registry.py` oder MCP-Adapter-noch nicht existieren, zeigen wir was wir haben und weisen auf fehlende-Abhaengigkeiten hin, crashen aber nicht.+Both roots are searched recursively. The call degrades gracefully when+B1/B2 components are missing — if `registry.py` or the MCP adapter don't+exist yet, we show what we have and point out the missing dependencies,+but we don't crash."""from __future__ import annotations@@ -23,7 +24,7 @@ import asyncioimport sysfrom pathlib import Path-# Windows: stdout auf UTF-8, damit Umlaute und Unicode-Symbole funktionieren.+# Windows: switch stdout to UTF-8 so umlauts and Unicode symbols work.if sys.platform == "win32":try:sys.stdout.reconfigure(encoding="utf-8", errors="replace") # type: ignore[attr-defined]@@ -36,7 +37,7 @@ if sys.platform == "win32":# ----------------------------------------------------------------------def _skill_roots() -> list[Path]:- """Liste der Skill-Root-Verzeichnisse in Such-Reihenfolge."""+ """List of skill root directories in search order."""try:from jarvis.core.config import PROJECT_ROOTexcept Exception: # noqa: BLE001@@ -52,7 +53,7 @@ def _skill_roots() -> list[Path]:def _collect_skills() -> list:- """Laed alle Skills aus allen Roots. Robust gegen fehlendes registry-Modul."""+ """Loads all skills from all roots. Robust against a missing registry module."""from jarvis.skills.loader import discover_skillsskills = []@@ -60,7 +61,7 @@ def _collect_skills() -> list:try:skills.extend(discover_skills(root))except Exception as e: # noqa: BLE001- print(f"[warn] Konnte Skills aus {root} nicht laden: {e}", file=sys.stderr)+ print(f"[warn] Could not load skills from {root}: {e}", file=sys.stderr)return skills@@ -73,9 +74,9 @@ def _list_skills() -> int:skills = _collect_skills()if not skills:- print("Keine Skills gefunden.")+ print("No skills found.")print("")- print("Erwartete Pfade:")+ print("Expected paths:")for r in [user_skills_dir(),Path(__file__).resolve().parents[2] / "jarvis" / "skills" / "builtin"]:print(f" - {r}")@@ -105,11 +106,11 @@ def _skill_info(name: str) -> int:None,)if match is None:- print(f"Skill '{name}' nicht gefunden.")+ print(f"Skill '{name}' not found.")return 2fm = match.frontmatter- print(f"Pfad: {match.path}")+ print(f"Path: {match.path}")print(f"State: {match.state.value}")if match.error:print(f"Error: {match.error}")@@ -123,7 +124,7 @@ def _skill_info(name: str) -> int:print(f"Author: {fm.author or '-'}")print(f"License: {fm.license}")print(f"Description: {fm.description.strip()}")- print(f"Token-Est: {fm.token_budget_estimate}")+ print(f"Token-Est.: {fm.token_budget_estimate}")print("Triggers:")for t in fm.triggers:details = (@@ -152,25 +153,25 @@ async def _skill_run(name: str) -> int:None,)if match is None:- print(f"Skill '{name}' nicht gefunden oder nicht validiert.")+ print(f"Skill '{name}' not found or not validated.")return 2- # Vollstaendiges Run benoetigt Tool-Registry + MCP — beides wird- # parallel von B1/B2 gebaut. Wir machen best-effort.+ # A full run needs the tool registry + MCP — both are being built in+ # parallel by B1/B2. We do best-effort.try:from jarvis.core.bus import EventBusfrom jarvis.skills.runner import SkillRunner # type: ignoreexcept Exception as e: # noqa: BLE001- print(f"[info] SkillRunner nicht verfuegbar: {e}")- print("[info] Ausfuehrung benoetigt Phase-1c-B1 + B2 (Tool-Registry + MCP).")- print(f"[info] Dry-Run: Skill '{name}' wuerde laufen mit Triggern "+ print(f"[info] SkillRunner not available: {e}")+ print("[info] Running requires Phase-1c-B1 + B2 (tool registry + MCP).")+ print(f"[info] Dry run: skill '{name}' would run with triggers "f"{[t.type for t in match.frontmatter.triggers]}")return 0bus = EventBus()try:- # SkillRegistry ist mandatory (kein Default). Wir nutzen die gleiche- # Discovery-Logik wie _list_skills(): alle Roots kombinieren.+ # SkillRegistry is mandatory (no default). We use the same+ # discovery logic as _list_skills(): combine all roots.from jarvis.core.paths import user_skills_dirfrom jarvis.skills.registry import SkillRegistry@@ -183,13 +184,13 @@ async def _skill_run(name: str) -> int:if root.exists():reg = SkillRegistry(root, bus)reg.reload()- combined_registry = reg # letzter gewinnt, fallback-Pattern+ combined_registry = reg # last one wins, fallback patternif reg.get(name) is not None:breakrunner = SkillRunner(registry=combined_registry, bus=bus) # type: ignore[call-arg]result = await runner.run(match) # type: ignore[attr-defined]except Exception as e: # noqa: BLE001- print(f"[error] Skill-Run fehlgeschlagen: {e}")+ print(f"[error] Skill run failed: {e}")return 1print(f"Skill: {result.skill_name}")@@ -201,14 +202,14 @@ async def _skill_run(name: str) -> int:def _import_claude_skills(src: str) -> int:- """Liest OpenClaw-Skills (.md), ergaenzt fehlende Frontmatter-Defaults,- kopiert nach ``user_skills_dir()/<name>/SKILL.md``.+ """Reads OpenClaw skills (.md), fills in missing frontmatter defaults,+ copies them to ``user_skills_dir()/<name>/SKILL.md``."""from jarvis.core.paths import user_skills_dirsrc_dir = Path(src).expanduser()if not src_dir.exists():- print(f"Quell-Verzeichnis existiert nicht: {src_dir}")+ print(f"Source directory does not exist: {src_dir}")return 2dst_dir = user_skills_dir()@@ -218,7 +219,7 @@ def _import_claude_skills(src: str) -> int:skipped = 0for md in src_dir.rglob("*.md"):rel = md.relative_to(src_dir)- # Name = Parent-Dir oder Dateistem+ # name = parent dir or file stemname = md.parent.name if md.parent != src_dir else md.stemname = name.replace(" ", "-").lower()out = dst_dir / name / "SKILL.md"@@ -233,13 +234,13 @@ def _import_claude_skills(src: str) -> int:imported += 1print(f" imported: {rel} -> {out}")- print(f"Imported {imported} OpenClaw-Skills (skipped {skipped} existing).")- print(f"Ziel: {dst_dir}")+ print(f"Imported {imported} OpenClaw skills (skipped {skipped} existing).")+ print(f"Destination: {dst_dir}")return 0def _ensure_frontmatter(text: str, default_name: str) -> str:- """Prueft ob `text` bereits YAML-Frontmatter hat. Falls nicht, prepend default."""+ """Checks whether `text` already has YAML frontmatter. If not, prepends a default."""stripped = text.lstrip()if stripped.startswith("---"):return text@@ -266,19 +267,19 @@ def _ensure_frontmatter(text: str, default_name: str) -> str:# ----------------------------------------------------------------------def _list_drafts() -> int:- """Phase 7.5: tabellarische Übersicht aller DRAFT-Skills."""+ """Phase 7.5: tabular overview of all DRAFT skills."""from jarvis.core.paths import user_skills_dirfrom jarvis.skills.registry import SkillRegistryroot = user_skills_dir()if not root.exists():- print("Kein user_skills_dir vorhanden — keine Drafts.")+ print("No user_skills_dir present — no drafts.")return 0registry = SkillRegistry(root, bus=None)registry.reload_sync()drafts = registry.list_drafts()if not drafts:- print("Keine Draft-Skills vorhanden.")+ print("No draft skills present.")return 0print(f"{'SLUG':<32} {'STATE':<10} {'DESCRIPTION'}")for skill in sorted(drafts, key=lambda s: s.path.parent.name):@@ -290,11 +291,11 @@ def _list_drafts() -> int:def _promote_skill(slug: str) -> int:- """Phase 7.5: setzt einen DRAFT-Skill auf state=active.+ """Phase 7.5: sets a DRAFT skill to state=active.- Plan-§AP-6: User-explizite Aktivierung — der Skill triggert erst- nach diesem Schritt. Der Sicherheits-Lint im Registry prüft den- Body vor dem Promote.+ Plan §AP-6: explicit user activation — the skill only triggers after+ this step. The registry's safety lint checks the body before the+ promote."""from jarvis.core.paths import user_skills_dirfrom jarvis.skills.authoring.draft_writer import UnsafeSkillError@@ -302,7 +303,7 @@ def _promote_skill(slug: str) -> int:root = user_skills_dir()if not root.exists():- print(f"[error] user_skills_dir existiert nicht: {root}", file=sys.stderr)+ print(f"[error] user_skills_dir does not exist: {root}", file=sys.stderr)return 1registry = SkillRegistry(root, bus=None)registry.reload_sync()@@ -315,37 +316,37 @@ def _promote_skill(slug: str) -> int:print(f"[error] {exc}", file=sys.stderr)return 1except UnsafeSkillError as exc:- print(f"[error] Promote blockiert (unsafe code): {exc}", file=sys.stderr)+ print(f"[error] Promote blocked (unsafe code): {exc}", file=sys.stderr)return 1- print(f"Skill '{slug}' ist jetzt aktiv (state={skill.state.value}).")+ print(f"Skill '{slug}' is now active (state={skill.state.value}).")return 0def main(argv: list[str] | None = None) -> int:parser = argparse.ArgumentParser(prog="jarvis-skills")group = parser.add_mutually_exclusive_group(required=True)- group.add_argument("--list", action="store_true", help="Alle Skills auflisten")- group.add_argument("--info", type=str, metavar="NAME", help="Details zu einem Skill")- group.add_argument("--run", type=str, metavar="NAME", help="Skill ausfuehren (requires MCP)")+ group.add_argument("--list", action="store_true", help="List all skills")+ group.add_argument("--info", type=str, metavar="NAME", help="Details for a skill")+ group.add_argument("--run", type=str, metavar="NAME", help="Run a skill (requires MCP)")group.add_argument("--import-claude-skills",type=str,metavar="PATH",dest="import_claude_skills",- help="OpenClaw-Skills aus einem Verzeichnis importieren",+ help="Import OpenClaw skills from a directory",)- # Phase 7.5: Draft-Skill-Management (Plan-§7.5 Voice-Output + UI in Phase 7.6).+ # Phase 7.5: draft skill management (Plan §7.5 voice output + UI in Phase 7.6).group.add_argument("--list-drafts",action="store_true",dest="list_drafts",- help="Alle OpenClaw-authored Drafts auflisten (state=draft).",+ help="List all OpenClaw-authored drafts (state=draft).",)group.add_argument("--promote",type=str,metavar="SLUG",- help="Einen Draft-Skill auf state=active promoten.",+ help="Promote a draft skill to state=active.",)args = parser.parse_args(argv if argv is not None else sys.argv[1:])diff --git a/jarvis/skills/deduplicator.py b/jarvis/skills/deduplicator.pyindex 8bab0717a0..a3216aff44 100644--- a/jarvis/skills/deduplicator.py+++ b/jarvis/skills/deduplicator.py@@ -1,6 +1,6 @@-"""Skill-Deduplicator: findet ähnliche Skills via Jaccard-Koeffizient.+"""Skill deduplicator: finds similar skills via the Jaccard coefficient.-Feature-Set pro Skill: Trigger-Patterns ∪ requires_tools.+Feature set per skill: trigger patterns ∪ requires_tools."""from __future__ import annotations@@ -8,7 +8,7 @@ from .schema import Skilldef jaccard(a: set[str], b: set[str]) -> float:- """Jaccard-Koeffizient |A∩B| / |A∪B|. Beide leer → 1.0 (definitorisch)."""+ """Jaccard coefficient |A∩B| / |A∪B|. Both empty → 1.0 (by definition)."""if not a and not b:return 1.0union = a | b@@ -34,9 +34,9 @@ def find_duplicates(skills: list[Skill],threshold: float = 0.75,) -> list[tuple[Skill, Skill, float]]:- """Gibt Paare (a, b, similarity) zurück, die ≥ threshold sind.+ """Returns pairs (a, b, similarity) that are ≥ threshold.- Deterministisch sortiert (nach absteigender Similarity).+ Deterministically sorted (by descending similarity)."""results: list[tuple[Skill, Skill, float]] = []feats = [(s, _features(s)) for s in skills]diff --git a/jarvis/skills/finder.py b/jarvis/skills/finder.pyindex c3c7f12dcd..99f3e9b54a 100644--- a/jarvis/skills/finder.py+++ b/jarvis/skills/finder.py@@ -1,19 +1,19 @@-"""Skill-Finder: Mini-Agent zur Suche und Installation von Skills.--Der Finder ist ein schlanker Wrapper um:-1. Den kuratierten Seed-Katalog (``catalog/seed_catalog.json``).-2. Den ``BrainManager`` zur semantischen Bewertung der Kandidaten.-3. Den ``httpx``-Client zum Download einer ausgewaehlten SKILL.md.--Design-Prinzipien:-- **Graceful degradation**: Ohne Brain funktioniert die Suche heuristisch- (String-Matching). Ohne Internet schlaegt ``install`` fehl, aber die Suche- laeuft weiter (statischer Katalog).-- **Trust-Filter vor Brain**: Der Trust-Filter greift *vor* dem Brain-Ranking,- damit das Brain nicht Tokens fuer Kandidaten verschwendet, die der User- sowieso ablehnen wuerde.-- **Stateless**: Der Finder haelt keinen State — Query-Historie liegt im- Frontend bzw. spaeter im Flight-Recorder.+"""Skill finder: mini-agent for searching and installing skills.++The finder is a thin wrapper around:+1. The curated seed catalog (``catalog/seed_catalog.json``).+2. The ``BrainManager`` for semantically scoring the candidates.+3. The ``httpx`` client for downloading a selected SKILL.md.++Design principles:+- **Graceful degradation**: without a brain, search falls back to a+ heuristic (string matching). Without internet, ``install`` fails, but+ search keeps working (static catalog).+- **Trust filter before the brain**: the trust filter runs *before*+ brain ranking, so the brain doesn't waste tokens on candidates the user+ would reject anyway.+- **Stateless**: the finder holds no state — query history lives in the+ frontend, and later in the flight recorder."""from __future__ import annotations@@ -37,12 +37,12 @@ log = logging.getLogger(__name__)# ----------------------------------------------------------------------TrustLevel = Literal["official", "verified", "community", "experimental"]-"""Vertrauensstufen fuer Skill-Quellen.+"""Trust levels for skill sources.-- ``official``: Anthropic, OpenAI, andere first-party Vendors.-- ``verified``: Maintainer mit Track-Record und 3000+ GitHub-Stars.-- ``community``: Aktiv gewartet, weniger Stars, pruefbar.-- ``experimental``: Prototyp, Solo-Dev, Risiko vom User bewusst akzeptiert.+- ``official``: Anthropic, OpenAI, other first-party vendors.+- ``verified``: maintainer with a track record and 3000+ GitHub stars.+- ``community``: actively maintained, fewer stars, checkable.+- ``experimental``: prototype, solo dev, risk knowingly accepted by the user."""@@ -56,9 +56,9 @@ TRUST_ORDER: dict[TrustLevel, int] = {@dataclass(frozen=True)class SkillCandidate:- """Ein Match-Kandidat aus dem Katalog.+ """A match candidate from the catalog.- Frozen fuer JSON-Serialisierung in Responses + Replay-Kompatibilitaet.+ Frozen for JSON serialization in responses + replay compatibility."""name: strtitle: str@@ -113,7 +113,7 @@ class SkillCandidate:@dataclass(frozen=True)class SearchFilters:- """Filter fuer die Suche — mapping der Dropdown-Auswahl im Frontend."""+ """Filters for the search — maps to the dropdown selection in the frontend."""query: str = ""trust: TrustLevel | Literal["any"] = "any"min_stars: int | None = None@@ -131,33 +131,33 @@ _RISK_ORDER = {"safe": 0, "monitor": 1, "ask": 2, "block": 3}def _passes_filter(entry: dict[str, Any], f: SearchFilters) -> bool:- """Harte Filter vor dem Ranking — excluded Trust/Stars/Category/Risk."""+ """Hard filter before ranking — excludes on trust/stars/category/risk."""# Trustif f.trust != "any":e_trust = entry.get("trust", "community")if TRUST_ORDER.get(e_trust, 99) > TRUST_ORDER.get(f.trust, 99):return False- # Min-Stars (wenn angegeben)+ # Min stars (if given)if f.min_stars is not None:e_stars = entry.get("stars")if e_stars is None or e_stars < f.min_stars:- # Official-Skills haben ``stars = null`` — die lassen wir passieren- # unabhaengig vom Star-Threshold (offizielle > Stars-Metrik).+ # Official skills have ``stars = null`` — we let those pass+ # regardless of the star threshold (official > star metric).if entry.get("trust") != "official":return False- # Kategorie+ # Categoryif f.category:cats = entry.get("categories", [])if f.category not in cats:return False- # Sprache+ # Languageif f.language:langs = entry.get("languages", [])if f.language not in langs and "en" not in langs:- # EN faellt zurueck, wenn der Skill bilingual ist+ # falls back to EN if the skill is bilingualreturn False# Risk@@ -177,10 +177,10 @@ def _tokenize(text: str) -> set[str]:def _score_heuristic(query_tokens: set[str], entry: dict[str, Any]) -> float:- """Heuristisches Ranking ohne Brain.+ """Heuristic ranking without a brain.- Zaehlt Token-Overlaps zwischen Query und (title + description + tags).- Gewichtet Tags hoeher, weil sie kuratiert sind.+ Counts token overlaps between the query and (title + description + tags).+ Weighs tags higher because they're curated."""if not query_tokens:return 0.0@@ -196,15 +196,15 @@ def _score_heuristic(query_tokens: set[str], entry: dict[str, Any]) -> float:blob_overlap = len(query_tokens & blob_tokens)tag_overlap = len(query_tokens & tag_tokens)- # Tags bekommen Faktor 2, damit "docker" in Tags > "docker" irgendwo im Body+ # Tags get a factor of 2, so "docker" in tags outranks "docker" somewhere in the bodyraw = blob_overlap + tag_overlap * 2- # Normalisieren auf [0, 1] mit sanftem Decay+ # Normalize to [0, 1] with a soft decayreturn min(1.0, raw / (len(query_tokens) + 1))def _heuristic_reason(query_tokens: set[str], entry: dict[str, Any]) -> str:- """Menschlich lesbarer Grund fuer einen Treffer — damit der User versteht,- warum ein Skill hochgerankt wurde."""+ """Human-readable reason for a match — so the user understands why a+ skill was ranked highly."""matches = query_tokens & _tokenize(" ".join([str(entry.get("title", "")),@@ -214,19 +214,19 @@ def _heuristic_reason(query_tokens: set[str], entry: dict[str, Any]) -> str:)if not matches:trust = entry.get("trust", "community")- return f"Trust-Match ({trust})"+ return f"Trust match ({trust})"return "Match: " + ", ".join(sorted(matches)[:4])# -----------------------------------------------------------------------# Brain-gestuetztes Ranking+# Brain-backed ranking# -----------------------------------------------------------------------_RANK_SYSTEM_PROMPT = """Du bist ein Skill-Ranker fuer Personal Jarvis. Der User-sucht einen Skill, der sein Problem loest. Du bekommst eine User-Anfrage und eine-Liste von Kandidaten als JSON. Gib NUR ein JSON-Array zurueck, sortiert von bestem-zu schlechtestem Match. Jeder Eintrag: {"name": "...", "score": 0.0-1.0, "reason": "kurzer-Satz warum es passt"}. Nichts anderes, kein Markdown, kein Prefix."""+_RANK_SYSTEM_PROMPT = """You are a skill ranker for Personal Jarvis. The user+is looking for a skill that solves their problem. You get a user query and a+list of candidates as JSON. Return ONLY a JSON array, sorted from best+to worst match. Each entry: {"name": "...", "score": 0.0-1.0, "reason": "short+sentence on why it fits"}. Nothing else, no Markdown, no prefix."""async def _brain_rank(@@ -234,17 +234,17 @@ async def _brain_rank(query: str,candidates: list[dict[str, Any]],) -> dict[str, tuple[float, str]] | None:- """Nutzt ein Brain (BrainManager-Instanz) zum Ranking.+ """Uses a brain (BrainManager instance) for ranking.- Returnt ``None`` wenn:- - kein Brain uebergeben- - die Response nicht als JSON parsebar war (dann faellt man auf Heuristik zurueck)- - das Brain einen Error raised+ Returns ``None`` when:+ - no brain was passed+ - the response wasn't parsable as JSON (falls back to the heuristic)+ - the brain raised an error"""if brain is None:return None- # Minimaler Prompt: nur Name + Title + Description + Tags, um Tokens zu sparen+ # Minimal prompt: only name + title + description + tags, to save tokenscompact = [{"name": c["name"],@@ -252,36 +252,36 @@ async def _brain_rank("description": c.get("description"),"tags": c.get("tags", []),}- for c in candidates[:30] # Hard-Cap — 30 Kandidaten reichen+ for c in candidates[:30] # hard cap — 30 candidates is plenty]user_msg = (- f"User-Anfrage: {query!r}\n\n"- f"Kandidaten:\n{json.dumps(compact, ensure_ascii=False)}\n\n"+ f"User query: {query!r}\n\n"+ f"Candidates:\n{json.dumps(compact, ensure_ascii=False)}\n\n"f"{_RANK_SYSTEM_PROMPT}")try:- # BrainManager.generate ist der uniforme Aufruf. Kein use_history — das- # ist ein One-Shot-Ranker, nicht Teil der Chat-Historie.+ # BrainManager.generate is the uniform call. No use_history — this+ # is a one-shot ranker, not part of the chat history.if hasattr(brain, "generate"):text = await brain.generate(user_msg, use_history=False)else:- # Fallback: falls jemand eine rohe Brain-Protocol-Impl uebergibt,- # koennten wir hier via dispatcher gehen. MVP: Nur BrainManager.+ # Fallback: if someone passes a raw Brain-protocol impl, we could+ # go through the dispatcher here. MVP: BrainManager only.return Noneexcept Exception as exc: # noqa: BLE001- log.warning("Brain-Ranking fehlgeschlagen: %s", exc)+ log.warning("Brain ranking failed: %s", exc)return None- # JSON rausfischen — Brain liefert evtl. mit Whitespace oder Prefix+ # Fish out the JSON — the brain may return it with whitespace or a prefixjson_match = re.search(r"\[\s*\{.*?\}\s*\]", text, re.DOTALL)if not json_match:- log.debug("Brain-Response enthaelt kein JSON-Array: %s", text[:200])+ log.debug("Brain response contains no JSON array: %s", text[:200])return Nonetry:parsed = json.loads(json_match.group(0))except json.JSONDecodeError as exc:- log.debug("Brain-Ranking-JSON nicht parsebar: %s", exc)+ log.debug("Brain-ranking JSON not parsable: %s", exc)return Noneout: dict[str, tuple[float, str]] = {}@@ -305,20 +305,20 @@ async def _brain_rank(# ----------------------------------------------------------------------class SkillFinder:- """Mini-Agent fuer Skill-Suche und Installation."""+ """Mini-agent for skill search and installation."""def __init__(self, brain: Any | None = None) -> None:self._brain = brainasync def search(self, filters: SearchFilters) -> list[SkillCandidate]:- """Filter + Rank — gibt bis zu ``filters.limit`` Kandidaten zurueck."""+ """Filter + rank — returns up to ``filters.limit`` candidates."""catalog = load_catalog()filtered = [e for e in catalog if _passes_filter(e, filters)]if not filtered:return []- # Brain-Ranking+ # Brain rankingbrain_scores = await _brain_rank(self._brain, filters.query, filtered)query_tokens = _tokenize(filters.query)@@ -327,8 +327,8 @@ class SkillFinder:cand = SkillCandidate.from_catalog_entry(entry)if brain_scores and cand.name in brain_scores:score, reason = brain_scores[cand.name]- # Brain-Score mit 0.7 Gewicht, Heuristik-Score mit 0.3 — so- # bleibt ein heuristischer Nulltreffer nicht komplett blind+ # Brain score weighted 0.7, heuristic score weighted 0.3 — so+ # a heuristic zero-hit isn't left completely blindheur = _score_heuristic(query_tokens, entry)final_score = 0.7 * score + 0.3 * heurfinal_reason = reason or _heuristic_reason(query_tokens, entry)@@ -336,7 +336,7 @@ class SkillFinder:final_score = _score_heuristic(query_tokens, entry)final_reason = _heuristic_reason(query_tokens, entry)- # Trust-Bonus: bei gleichem Score gewinnt das vertrauenswuerdigere+ # Trust bonus: on equal score, the more trustworthy one winstrust_bonus = (3 - TRUST_ORDER.get(cand.trust, 3)) * 0.01final_score += trust_bonus@@ -350,24 +350,24 @@ class SkillFinder:return candidates[: filters.limit]async def install(self, candidate: SkillCandidate) -> Path:- """Installiert einen Kandidaten in ``user_skills_dir()``.+ """Installs a candidate into ``user_skills_dir()``.- Strategie:- - Hat ``raw_url``, wird die SKILL.md direkt geholt.- - Ohne ``raw_url`` schlaegt die Installation fehl mit klarer Message —- der User muss dann manuell installieren (Link im Frontend).+ Strategy:+ - If ``raw_url`` is set, the SKILL.md is fetched directly.+ - Without ``raw_url``, the install fails with a clear message —+ the user then has to install manually (link in the frontend).- Gibt den Ziel-Pfad zurueck (``<user_skills>/<name>/SKILL.md``).- Raised ``ValueError`` bei ungueltigem SKILL.md (Frontmatter-Validation).- Raised ``RuntimeError`` bei Netzwerk-Fehler oder fehlender raw_url.+ Returns the target path (``<user_skills>/<name>/SKILL.md``).+ Raises ``ValueError`` on an invalid SKILL.md (frontmatter validation).+ Raises ``RuntimeError`` on a network error or a missing raw_url."""if not candidate.raw_url:raise RuntimeError(- f"Kein Direkt-Download fuer '{candidate.name}' verfuegbar. "- f"Oeffne {candidate.source_url} und installiere manuell."+ f"No direct download available for '{candidate.name}'. "+ f"Open {candidate.source_url} and install manually.")- # httpx ist in den Runtime-Deps (mcp_routes etc.)+ # httpx is in the runtime deps (mcp_routes etc.)import httpxasync with httpx.AsyncClient(@@ -379,27 +379,27 @@ class SkillFinder:resp.raise_for_status()except httpx.HTTPError as exc:raise RuntimeError(- f"Download von {candidate.raw_url} fehlgeschlagen: {exc}"+ f"Download from {candidate.raw_url} failed: {exc}") from exccontent = resp.text- # Ziel-Struktur: <user_skills>/<name>/SKILL.md+ # Target structure: <user_skills>/<name>/SKILL.mdtarget_dir = user_skills_dir() / candidate.nametarget_dir.mkdir(parents=True, exist_ok=True)target_file = target_dir / "SKILL.md"- # Atomar schreiben+ # Write atomicallytmp = target_file.with_suffix(".md.tmp")tmp.write_text(content, encoding="utf-8")tmp.replace(target_file)- # Parse-Check: wenn das SKILL.md kaputt ist, markieren wir es als DRAFT,- # aber loeschen es nicht automatisch — der User sieht im UI den Fehler- # und kann entscheiden.+ # Parse check: if the SKILL.md is broken, we mark it as DRAFT, but+ # don't delete it automatically — the user sees the error in the UI+ # and can decide.parsed = parse_skill(target_file)if parsed.error:log.warning(- "Installierter Skill '%s' hat Validation-Fehler: %s",+ "Installed skill '%s' has a validation error: %s",candidate.name, parsed.error,)diff --git a/jarvis/skills/validator.py b/jarvis/skills/validator.pyindex c8c482b795..081f640685 100644--- a/jarvis/skills/validator.py+++ b/jarvis/skills/validator.py@@ -1,11 +1,11 @@-"""Semantische Validierung von Skills — über die Frontmatter-Schema-Ebene hinaus.--- Requires-Tools: existieren im Tool-Registry (jarvis.tool entry_points) oder- als MCP-Server-Name (best-effort via optional mcp_registry).-- Voice-Patterns müssen compilieren.-- Cron-Expressions müssen parsebar sein (croniter optional).-- Hotkey-Combos müssen parsebar sein (simple Key-Token-Check).-- Risk-Tier-Overrides dürfen keine global geblacklisteten Patterns treffen.+"""Semantic validation of skills — beyond the frontmatter schema layer.++- Requires-Tools: must exist in the tool registry (jarvis.tool entry_points)+ or as an MCP server name (best-effort via the optional mcp_registry).+- Voice patterns must compile.+- Cron expressions must be parsable (croniter optional).+- Hotkey combos must be parsable (simple key-token check).+- Risk-tier overrides must not hit a globally blacklisted pattern.- token_budget ≤ 10_000."""from __future__ import annotations@@ -16,7 +16,7 @@ from typing import Anyfrom .schema import Skill, SkillLifecycleState-# Optional: croniter für Cron-Validation+# Optional: croniter for cron validationtry:from croniter import croniter # type: ignore_HAVE_CRONITER = True@@ -34,7 +34,7 @@ _ALLOWED_HOTKEY_MODS = {@dataclassclass ValidationReport:- """Ergebnis einer Validierung. `ok=True` heißt alle Checks bestanden."""+ """Result of a validation. `ok=True` means all checks passed."""ok: bool = Trueerrors: list[str] = field(default_factory=list)warnings: list[str] = field(default_factory=list)@@ -48,20 +48,20 @@ class ValidationReport:def _validate_hotkey(combo: str) -> str | None:- """None wenn OK, sonst Error-Message."""+ """None if OK, otherwise an error message."""if not combo:return "empty combo"parts = [p.strip().lower() for p in combo.split("+") if p.strip()]if not parts:return "empty combo"- # Letzter Token muss eine Key sein (kein Modifier allein)+ # Last token must be a key (not a modifier alone)if len(parts) == 1 and parts[0] in _ALLOWED_HOTKEY_MODS:- return f"combo '{combo}' enthält nur einen Modifier"+ return f"combo '{combo}' contains only a modifier"return Nonedef _list_tool_plugins() -> set[str]:- """Alle via entry_points registrierten Tool-Plugins."""+ """All tool plugins registered via entry_points."""try:from jarvis.core import registry as plugin_registryreturn set(plugin_registry.list_plugins("jarvis.tool"))@@ -74,18 +74,18 @@ def validate_skill(tool_registry: Any | None = None,mcp_registry: Any | None = None,) -> ValidationReport:- """Führt alle semantischen Checks aus.+ """Runs all semantic checks.Args:- skill: Geladener Skill (darf auch DRAFT sein — dann wird der- vorhandene Error propagiert).- tool_registry: Optional — Objekt mit ``list_plugins("jarvis.tool")``- oder eine Iterable von Tool-Namen.- mcp_registry: Optional — Objekt mit ``.list_servers()``.+ skill: Loaded skill (may also be DRAFT — in which case the+ existing error is propagated).+ tool_registry: Optional — object with ``list_plugins("jarvis.tool")``+ or an iterable of tool names.+ mcp_registry: Optional — object with ``.list_servers()``."""report = ValidationReport()- # DRAFT-Skills erben ihren Parse-Fehler+ # DRAFT skills inherit their parse errorif skill.frontmatter is None:report.add_error(skill.error or "skill could not be parsed")return report@@ -98,7 +98,7 @@ def validate_skill(f"token_budget_estimate={fm.token_budget_estimate} > 10000")- # 2. Tools existieren+ # 2. Tools existknown_tools: set[str] = set()if tool_registry is not None:if hasattr(tool_registry, "list_plugins"):@@ -123,12 +123,12 @@ def validate_skill(continueif tool in mcp_servers:continue- # Accept "mcp:<name>" prefix as MCP-Server-Reference+ # Accept "mcp:<name>" prefix as an MCP server referenceif tool.startswith("mcp:") and tool[4:] in mcp_servers:continue- report.add_warning(f"required tool '{tool}' nicht im Registry gefunden")+ report.add_warning(f"required tool '{tool}' not found in registry")- # 3. Risk-Policy+ # 3. Risk policyfor tool, tier in fm.risk_policy.per_tool_overrides.items():if tier not in ("safe", "monitor", "ask", "block"):report.add_error(f"invalid risk tier '{tier}' for tool '{tool}'")@@ -138,7 +138,7 @@ def validate_skill(label = f"trigger[{idx}]({trig.type})"if trig.type == "voice":if trig.pattern is None:- report.add_error(f"{label}: pattern fehlt")+ report.add_error(f"{label}: pattern missing")else:try:re.compile(trig.pattern)@@ -150,7 +150,7 @@ def validate_skill(report.add_error(f"{label}: {err}")elif trig.type == "schedule":if not trig.cron:- report.add_error(f"{label}: cron fehlt")+ report.add_error(f"{label}: cron missing")elif _HAVE_CRONITER:try:if not croniter.is_valid(trig.cron): # type: ignore[union-attr]@@ -158,22 +158,22 @@ def validate_skill(except Exception as exc: # noqa: BLE001report.add_error(f"{label}: cron parse failed — {exc}")else:- # Minimal-Fallback: 5 oder 6 Felder+ # Minimal fallback: 5 or 6 fieldsfield_count = len(trig.cron.split())if field_count not in (5, 6):report.add_error(- f"{label}: cron '{trig.cron}' hat {field_count} Felder (erwarte 5 oder 6)"+ f"{label}: cron '{trig.cron}' has {field_count} fields (expected 5 or 6)")else:report.add_warning(- "croniter nicht installiert — cron nur oberflächlich geprüft"+ "croniter not installed — cron checked only superficially")return reportdef apply_validation(skill: Skill, report: ValidationReport) -> Skill:- """Gibt einen Skill mit aktualisiertem State zurück, basierend auf Report."""+ """Returns a skill with an updated state, based on the report."""if not report.ok:return Skill(path=skill.path,diff --git a/jarvis/speech/completeness.py b/jarvis/speech/completeness.pyindex 8d13eab0fe..d9d87b7ed7 100644--- a/jarvis/speech/completeness.py+++ b/jarvis/speech/completeness.py@@ -11,7 +11,7 @@ Design: docs/superpowers/specs/2026-05-25-utterance-completeness-design.mdBias is **"when in doubt, execute"**: the default verdict is COMPLETE, and onlyhigh-precision rules raise INCOMPLETE / ABRUPT_ABORT. This keeps the fastlocal-action path (``match_local_action``) and the meta-command gates-(``match_voice_command``) un-starved — a clear command like "Öffne Chrome" must+(``match_voice_command``) un-starved — a clear command like "Open Chrome" mustalways pass through.Standard-library only (``re``), like ``jarvis/speech/hangup.py`` — no@@ -53,7 +53,7 @@ class CompletenessVerdict:# --- Rule 2: abrupt-abort phrases (explicit self-cancel) ------------------# Anchored full-utterance match (optional leading interjection + optional# trailing "jarvis"). Anchoring keeps precision high: "ich vergiss es nie" and-# "mach das doch nicht so laut" do NOT match because there is extra content+# "mach das doch nicht so laut" do NOT match because there is extra content # i18n-allow# outside the phrase. A bare "nein" / "no" is a valid answer, not an abort._ABORT_INTERJECTIONS: Final[str] = r"ach|oh|ne|nee|nein|ok|okay|also|ja|na|hm|ah"@@ -63,13 +63,13 @@ _ABORT_PHRASES: Final[tuple[str, ...]] = ("lass mal gut sein","lass es gut sein","lass gut sein",- "ist schon gut",+ "ist schon gut", # i18n-allow"is schon gut","schon gut",- "nein doch nicht",- "nee doch nicht",- "ne doch nicht",- "doch nicht",+ "nein doch nicht", # i18n-allow+ "nee doch nicht", # i18n-allow+ "ne doch nicht", # i18n-allow+ "doch nicht", # i18n-allow"nein egal","nee egal","ne egal",@@ -108,9 +108,9 @@ _ABORT_RE: Final[re.Pattern[str]] = re.compile(_DANGLING: Final[frozenset[str]] = frozenset({# DE conjunctions- "und", "oder", "aber", "weil", "dass", "daß", "denn", "sondern", "sowie",+ "und", "oder", "aber", "weil", "dass", "daß", "denn", "sondern", "sowie", # i18n-allow# DE indefinite articles (almost always pre-nominal)- "eine", "einen", "einem", "einer", "eines",+ "eine", "einen", "einem", "einer", "eines", # i18n-allow# DE subordinators"wenn", "falls", "ob",# EN conjunctionsdiff --git a/jarvis/speech/diagnose.py b/jarvis/speech/diagnose.pyindex 3ebfc8c71e..fbf06aea46 100644--- a/jarvis/speech/diagnose.py+++ b/jarvis/speech/diagnose.py@@ -1,18 +1,18 @@-"""Speech-Diagnose-CLI — hilft wenn Wake-Word / Mic / TTS nicht funktionieren.+"""Speech diagnostics CLI — helps when wake word / mic / TTS aren't working.-Aufruf:+Usage:python -m jarvis.speech.diagnose-Zeigt:- 1. Alle Audio-Devices (Input + Output)- 2. Live-Mic-Pegel (dBFS) über 10 Sekunden — damit du siehst ob dein Mic- überhaupt ankommt- 3. Live-Wake-Word-Score über 20 Sekunden — sag "Hey Jarvis" / "Jarvis"- und sieh was openWakeWord misst- 4. Whisper-Transkriptions-Test — sag irgendwas 3 Sek, Jarvis zeigt was- er verstanden hat- 5. Chime-Playback — kurzer Ton zum Output-Device- 6. TTS-Rundlauf — Jarvis sagt einen Satz via Gemini+Shows:+ 1. All audio devices (input + output)+ 2. Live mic level (dBFS) over 10 seconds — so you can see whether your mic+ is picking anything up at all+ 3. Live wake-word score over 20 seconds — say "Hey Jarvis" / "Jarvis"+ and see what openWakeWord measures+ 4. Whisper transcription test — say something for 3 sec, Jarvis shows+ what it understood+ 5. Chime playback — short tone on the output device+ 6. TTS round-trip — Jarvis says a sentence via Gemini"""from __future__ import annotations@@ -72,19 +72,19 @@ def _print_header(n: int, title: str) -> None:def step_devices() -> None:- _print_header(1, "Audio-Devices")+ _print_header(1, "Audio devices")devices = sd.query_devices()default_in, default_out = sd.default.deviceprint(f"Default Input : #{default_in} → {devices[default_in]['name']}")print(f"Default Output: #{default_out} → {devices[default_out]['name']}")print()- print("Alle Inputs:")+ print("All inputs:")for i, d in enumerate(devices):if d["max_input_channels"] > 0:marker = " ★" if i == default_in else " "print(f" {marker} #{i:2d} {d['name']} (ch={d['max_input_channels']}, rate={int(d['default_samplerate'])})")print()- print("Alle Outputs:")+ print("All outputs:")for i, d in enumerate(devices):if d["max_output_channels"] > 0:marker = " ★" if i == default_out else " "@@ -92,10 +92,10 @@ def step_devices() -> None:async def step_mic_level(duration_s: float = 10.0) -> float:- """Misst Live-Mic-Pegel — User sollte laut sprechen, Max-dBFS wird gemerkt."""- _print_header(2, f"Mic-Pegel-Test ({int(duration_s)} Sekunden — SPRICH JETZT!)")- print("Sprich laut — zähl bis zehn oder sing ein bisschen.")- print("Max-Pegel sollte im Bereich -20 bis -5 dBFS liegen.")+ """Measures the live mic level — the user should speak loudly, max dBFS is recorded."""+ _print_header(2, f"Mic level test ({int(duration_s)} seconds — SPEAK NOW!)")+ print("Speak loudly — count to ten or sing a bit.")+ print("Max level should be in the range -20 to -5 dBFS.")print()max_dbfs = -120.0samples_seen = 0@@ -109,27 +109,27 @@ async def step_mic_level(duration_s: float = 10.0) -> float:dbfs = 20.0 * np.log10(rms)max_dbfs = max(max_dbfs, dbfs)samples_seen += len(arr)- bar_len = max(0, int((dbfs + 60) / 2)) # skaliert [-60 .. 0] → [0 .. 30]+ bar_len = max(0, int((dbfs + 60) / 2)) # scales [-60 .. 0] → [0 .. 30]bar = "█" * min(bar_len, 30)sys.stdout.write(f"\r level: {dbfs:6.1f} dBFS {bar:<30s} (max: {max_dbfs:6.1f})")sys.stdout.flush()print()- print(f"→ Samples empfangen: {samples_seen} Max-Pegel: {max_dbfs:.1f} dBFS")+ print(f"→ Samples received: {samples_seen} Max level: {max_dbfs:.1f} dBFS")if samples_seen == 0:- print(" ⚠ KEIN Audio! Mic-Auswahl in Windows prüfen.")+ print(" ⚠ NO audio! Check mic selection in Windows.")elif max_dbfs < -40:- print(" ⚠ Sehr leiser Mic-Pegel. Windows-Mic-Volume hochdrehen oder Headset näher.")+ print(" ⚠ Very quiet mic level. Turn up the Windows mic volume or move the headset closer.")elif max_dbfs > -3:- print(" ⚠ Übersteuert! Mic-Volume in Windows reduzieren.")+ print(" ⚠ Clipping! Reduce the mic volume in Windows.")else:- print(" ✓ Pegel sieht gut aus.")+ print(" ✓ Level looks good.")return max_dbfsasync def step_wake_live(duration_s: float = 20.0) -> None:- _print_header(3, f"Wake-Word Live-Score ({int(duration_s)} Sekunden)")- print("Sag MEHRMALS dein Wake-Word — versuche verschiedene Aussprachen.")- print("Zeigt den höchsten Wake-Score pro Sekunde live.")+ _print_header(3, f"Wake-word live score ({int(duration_s)} seconds)")+ print("Say your wake word SEVERAL times — try different pronunciations.")+ print("Shows the highest wake score per second live.")print()from jarvis.plugins.wake.openwakeword_provider import (OWW_FRAME_SAMPLES,@@ -138,7 +138,7 @@ async def step_wake_live(duration_s: float = 20.0) -> None:prov = OpenWakeWordProvider(keywords=("hey_jarvis",),activation_threshold=0.15,- score_log_threshold=1.1, # disable inline logging, wir zeigen eigene+ score_log_threshold=1.1, # disable inline logging, we show our own)prov._ensure_model()assert prov._model is not None@@ -177,17 +177,17 @@ async def step_wake_live(duration_s: float = 20.0) -> None:last_report_t = nowmax_in_window = 0.0print()- print(f"→ Global-Max-Score: {max_score_global:.3f}")+ print(f"→ Global max score: {max_score_global:.3f}")if max_score_global < 0.15:- print(" ⚠ openWakeWord erkennt dein Wake-Word nicht zuverlässig.")- print(" → Whisper-Wake-Fallback übernimmt in der vollen Pipeline.")+ print(" ⚠ openWakeWord does not reliably detect your wake word.")+ print(" → The Whisper-wake fallback takes over in the full pipeline.")else:- print(" ✓ openWakeWord würde triggern bei Threshold 0.15.")+ print(" ✓ openWakeWord would trigger at threshold 0.15.")async def step_whisper(duration_s: float = 4.0) -> None:- _print_header(4, f"Whisper-Transkriptions-Test ({int(duration_s)} Sekunden)")- print("Sag einen kurzen Satz. Jarvis transkribiert und zeigt was er verstand.")+ _print_header(4, f"Whisper transcription test ({int(duration_s)} seconds)")+ print("Say a short sentence. Jarvis transcribes it and shows what it understood.")print()from jarvis.plugins.stt.fwhisper import FasterWhisperProviderstt = FasterWhisperProvider()@@ -200,38 +200,38 @@ async def step_whisper(duration_s: float = 4.0) -> None:if time.time() >= t_end:breakcollected.extend(chunk.pcm)- print(" Transkribiere …")+ print(" Transcribing …")transcript = await stt.transcribe_pcm(bytes(collected))- print(f" Sprache: {transcript.language}")+ print(f" Language: {transcript.language}")print(f" Confidence: {transcript.confidence:.2f}")print(f" Text: {transcript.text!r}")async def step_chime() -> None:- _print_header(5, "Chime-Playback")- print("Sollte jetzt einen kurzen Ding-Ton über die Lautsprecher spielen …")+ _print_header(5, "Chime playback")+ print("Should now play a short ding tone over the speakers …")player = AudioPlayer()await player.play_pcm(CHIME_PCM, sample_rate=CHIME_SAMPLE_RATE)- print(" ✓ Chime abgespielt.")+ print(" ✓ Chime played.")async def step_tts() -> None:- _print_header(6, "TTS-Rundlauf (Gemini 3.1 Flash)")- print("Jarvis sagt jetzt einen Test-Satz …")+ _print_header(6, "TTS round-trip (Gemini 3.1 Flash)")+ print("Jarvis is now saying a test sentence …")from jarvis.plugins.tts.gemini_flash_tts import GeminiFlashTTStts = GeminiFlashTTS(default_voice="Algieba", language_code="de-DE")tts._ensure_client()player = AudioPlayer()- text = "Hallo, ich bin Jarvis. Diagnose abgeschlossen. Du kannst mich jetzt nutzen."+ text = "Hallo, ich bin Jarvis. Diagnose abgeschlossen. Du kannst mich jetzt nutzen." # i18n-allowasync for chunk in tts.synthesize(text):await player.play_pcm(chunk.pcm, sample_rate=chunk.sample_rate)- print(" ✓ TTS-Ausgabe fertig.")+ print(" ✓ TTS output done.")async def _main() -> None:_setup_stdout()_load_env()- logging.basicConfig(level=logging.WARNING) # leise, wir printen selbst+ logging.basicConfig(level=logging.WARNING) # quiet, we print ourselvesstep_devices()await step_mic_level(10.0)@@ -241,7 +241,7 @@ async def _main() -> None:await step_tts()print()print("=" * 64)- print(" Diagnose abgeschlossen.")+ print(" Diagnostics complete.")print("=" * 64)@@ -249,4 +249,4 @@ if __name__ == "__main__":try:asyncio.run(_main())except KeyboardInterrupt:- print("\nAbgebrochen.")+ print("\nAborted.")diff --git a/jarvis/speech/hangup.py b/jarvis/speech/hangup.pyindex fdc4ed8a94..dc4a0f6d33 100644--- a/jarvis/speech/hangup.py+++ b/jarvis/speech/hangup.py@@ -62,21 +62,21 @@ _HANGUP_PATTERNS: Final[tuple[str, ...]] = (r"\bauff?lieg\w*\b",r"\bauffleg\w*\b",# German — other explicit closings- r"\btschüss\b",+ r"\btschüss\b", # i18n-allowr"\btschuess\b",r"\bbeenden\b",- r"\bgespräch beenden\b",- r"\bauf wiederhören\b",+ r"\bgespräch beenden\b", # i18n-allow+ r"\bauf wiederhören\b", # i18n-allowr"\bauf wiederhoeren\b",r"\bauf wiedersehen\b",- r"\bbis später\b",+ r"\bbis später\b", # i18n-allowr"\bgute nacht\b",r"\bjarvis aus\b",r"\bjarvis ende\b",r"\bende jarvis\b",r"\bschluss jetzt\b",r"\bfertig jarvis\b",- r"\bjarvis fertig\b",+ r"\bjarvis fertig\b", # i18n-allowr"\bstopp jarvis\b",r"\bjarvis stopp\b",# English — explicit closingsdiff --git a/jarvis/speech/rolling_whisper_wake.py b/jarvis/speech/rolling_whisper_wake.pyindex ea0d85b499..ac45ca2e70 100644--- a/jarvis/speech/rolling_whisper_wake.py+++ b/jarvis/speech/rolling_whisper_wake.py@@ -1,24 +1,23 @@-"""Rolling-Window Whisper Wake-Detection — robuster Wake ohne VAD-Abhängigkeit.--Im Gegensatz zu `whisper_wake.py` (wartet auf VAD-Endpoint, scheitert bei-leisen Mics): hier wird ein Ring-Buffer von 2.5 Sekunden Audio gehalten-und alle 500 ms durch Whisper transkribiert. Wenn "jarvis" im Transkript-auftaucht — Trigger.--Vorteile:-- Kein VAD-Dependency → funktioniert auch bei niedrigem Mic-Pegel-- Triggert sofort (500 ms Polling-Intervall), nicht erst nach Sprachende-- Nutzt Whisper (nativ deutsch-fähig) → keine Englisch-Trainings-Bias--Nachteile:-- Höhere GPU-Last (Whisper läuft permanent statt nur bei Utterance-Ende)-- Auf RTX 5070 Ti mit distil-large-v3: ~80-150 ms pro 2.5-Sek-Transkription- = ~20 % GPU-Nutzung bei 500 ms Poll-Intervall--Parameter:-- `window_s`: Buffer-Länge (Default 2.5 s — lang genug für "Hey Jarvis")-- `poll_interval_s`: wie oft wir transkribieren (Default 0.5 s)-- `cooldown_s`: nach Trigger nicht sofort wieder (Default 2 s)+"""Rolling-window Whisper wake detection — robust wake without a VAD dependency.++Unlike `whisper_wake.py` (which waits for a VAD endpoint and fails on quiet+mics), this keeps a 2.5-second rolling audio buffer and transcribes it via+Whisper every 500 ms. If "jarvis" shows up in the transcript — trigger.++Advantages:+- No VAD dependency → also works at a low mic level+- Triggers immediately (500 ms polling interval), not only after speech ends+- Uses Whisper (natively German-capable) → no English-training bias++Disadvantages:+- Higher GPU load (Whisper runs continuously instead of only at utterance end)+- On an RTX 5070 Ti with distil-large-v3: ~80-150 ms per 2.5-second transcription+ = ~20% GPU usage at a 500 ms poll interval++Parameters:+- `window_s`: buffer length (default 2.5 s — long enough for "Hey Jarvis")+- `poll_interval_s`: how often we transcribe (default 0.5 s)+- `cooldown_s`: not immediately re-triggering (default 2 s)"""from __future__ import annotations@@ -50,7 +49,7 @@ from jarvis.speech.wake_constants import JARVIS_WAKE_PATTERN as DEFAULT_PATTERNlog = logging.getLogger("jarvis.wake.rolling")-# Watchdog-Verzeichnis für Debug-WAVs+# Watchdog directory for debug WAVsDEBUG_DIR = Path(os.environ.get("JARVIS_DEBUG_DIR", "./data/wake_debug"))# Production default is OFF. The watchdog WAV dump writes ONE WAV file per@@ -77,7 +76,7 @@ _WEDGE_RECOVER_AFTER_FAILS = 5def _save_wav(pcm_bytes: bytes, sample_rate: int, path: Path) -> None:- """Schreibt int16-PCM als gültiges WAV-File."""+ """Writes int16 PCM as a valid WAV file."""path.parent.mkdir(parents=True, exist_ok=True)with wave.open(str(path), "wb") as wf:wf.setnchannels(1)@@ -127,18 +126,18 @@ class RollingWhisperWake:# Either a compiled regex or a WakeMatcher — both expose# ``.search(text)`` returning an object with ``.group(0)``.pattern: Any = DEFAULT_PATTERN,- window_s: float = 1.8, # kürzer = weniger Stille-Anteil = höhere avg-RMS- poll_interval_s: float = 0.3, # schnellere Wake-Reaktion- cooldown_s: float = 5.0, # längerer Cooldown → weniger Over-Triggering+ window_s: float = 1.8, # shorter = less silence share = higher avg RMS+ poll_interval_s: float = 0.3, # faster wake reaction+ cooldown_s: float = 5.0, # longer cooldown → less over-triggeringsample_rate: int = 16_000,- # 2026-04-22 (3. Iteration): RMS/Peak-Gates zurueck auf niedrig. Die- # Headset-Aussteuerung des Users ist sehr leise (typisch rms 0.01-0.02- # bei normalem Sprechen). Hoehere Gates blockten echtes "Hey Jarvis".- # Schutz gegen Halluzinationen liefert jetzt das Pattern alleine:- # Whisper halluziniert "JARVIS.", "Vielen Dank.", "Thank you" — das- # matched unser Pattern (nur "hey/hi/hallo + jarv-Stamm") nicht.- # Whisper wird dabei etwas oefter aufgerufen (mehr GPU-Last), aber das- # Trigger-Verhalten ist korrekt — genau was der User will.+ # 2026-04-22 (3rd iteration): RMS/peak gates set back to low. The+ # user's headset input level is very quiet (typically rms 0.01-0.02+ # for normal speech). Higher gates blocked genuine "Hey Jarvis".+ # Protection against hallucinations now comes from the pattern alone:+ # Whisper hallucinates "JARVIS.", "Vielen Dank.", "Thank you" — none+ # of that matches our pattern (only "hey/hi/hallo + jarv-stem").+ # Whisper does get called a bit more often (more GPU load), but the+ # trigger behavior is correct — exactly what the user wants.min_rms: float = 0.003,# 2026-06-29 (mission "wake only triggers when shouting"): the raw peak# gate runs BEFORE transcription on a quiet mic, so a normal-volume@@ -151,10 +150,10 @@ class RollingWhisperWake:min_peak: float = 0.012,save_debug_wavs: bool = False, # Watchdog-Modus — OFF in prod (env opt-in)heartbeat_interval_s: float = 3.0,- # Peak-Normalization statt fester Gain: misst Audio-Peak, wendet- # dynamisch den Gain an, der nötig ist um auf -3 dBFS zu kommen.- # Ersetzt fehlenden Windows/Hardware-Mic-Boost OHNE Clipping.- # Bei Stille/leisem Rauschen wird der Gain gecappt (max_gain_db).+ # Peak normalization instead of a fixed gain: measures the audio peak+ # and dynamically applies the gain needed to reach -3 dBFS.+ # Replaces a missing Windows/hardware mic boost WITHOUT clipping.+ # On silence/quiet noise the gain is capped (max_gain_db).target_peak_dbfs: float = -3.0,max_gain_db: float = 40.0,language: str = "de",@@ -206,14 +205,14 @@ class RollingWhisperWake:self._target_peak = float(10.0 ** (target_peak_dbfs / 20.0)) # -3 dBFS ≈ 0.707self._max_gain_factor = float(10.0 ** (max_gain_db / 20.0)) # 40 dB = 100xself._min_peak = min_peak- # Wake-Transkription auf eine feste Sprache pinnen — auto-detect auf- # 1.8s-Chunks kippt oft fälschlich auf EN (User spricht DE, Whisper- # halluziniert "Thank you"). None = auto (nicht empfohlen).+ # Pin the wake transcription to a fixed language — auto-detect on+ # 1.8s chunks often falsely flips to EN (user speaks DE, Whisper+ # hallucinates "Thank you"). None = auto (not recommended).self._language: str | None = languageself._min_wake_confidence = min_wake_confidenceself._max_no_speech_prob = max_no_speech_probself._transcribe_timeout_s = float(transcribe_timeout_s)- # Statistik für Heartbeat+ # Stats for the heartbeatself._chunks_seen = 0self._total_bytes = 0self._max_rms = 0.0@@ -297,7 +296,7 @@ class RollingWhisperWake:if chunk_rms > self._max_rms:self._max_rms = chunk_rms- # Heartbeat regelmäßig ausgeben — auch wenn Whisper nichts matched+ # Emit the heartbeat regularly — even when Whisper doesn't match anythingnow_hb = time.time()if now_hb - self._last_heartbeat_t >= self._heartbeat_interval_s:dbfs = 20.0 * np.log10(max(self._max_rms, 1e-12))@@ -327,7 +326,7 @@ class RollingWhisperWake:self._max_rms = 0.0self._last_heartbeat_t = now_hb- # Ältere Samples rauswerfen wenn Buffer zu lang+ # Discard older samples when the buffer gets too longwhile buf_len[0] > self._window_samples:oldest = buffer[0]overflow = buf_len[0] - self._window_samples@@ -377,7 +376,7 @@ class RollingWhisperWake:if now - last_trigger_t < self._cooldown_s:self._stat_suppressed_cooldown += 1continue- # Noch nicht genug Audio im Buffer+ # Not enough audio in the buffer yetif buf_len[0] < self._sample_rate: # mind. 1 Sekcontinue@@ -393,16 +392,16 @@ class RollingWhisperWake:# evaluation attempt (the denominator for the gate counters).self._stat_windows_polled += 1- # Lautstärke-Check (RMS) — kein Whisper-Call bei Stille+ # Volume check (RMS) — no Whisper call on silencerms = float(np.sqrt(np.mean(audio_np * audio_np) + 1e-12))if rms < self._min_rms:self._stat_gated_rms += 1continue- # Peak-Gate: bei reinem Rauschen gar nicht erst Whisper bemühen+ # Peak gate: don't even bother calling Whisper on pure noisepeak = float(np.max(np.abs(audio_np)))if peak < self._min_peak:- # Kein Whisper-Call — zu leise für Sprache. Log the measured+ # No Whisper call — too quiet for speech. Log the measured# peak so "wake stopped working" on a quiet mic is visible as# "your audio peaks below the gate", not silent nothing.self._stat_gated_peak += 1@@ -415,7 +414,7 @@ class RollingWhisperWake:# Whisper-Call mit Peak-Normalization (dynamischer Gain)try:if peak > 1e-6:- # Gain berechnen um Ziel-Peak zu erreichen, aber cappen+ # Compute the gain needed to reach the target peak, but cap itgain = min(self._target_peak / peak, self._max_gain_factor)else:gain = 1.0@@ -449,15 +448,15 @@ class RollingWhisperWake:consecutive_fail = 0 # a success clears the wedge streakexcept TimeoutError:log.warning(- "Rolling-Whisper Transkription nach %.1fs abgebrochen "- "(hung STT, %d in Folge) — re-poll, Wake bleibt lebendig",+ "Rolling-Whisper transcription aborted after %.1fs "+ "(hung STT, %d in a row) — re-polling, wake stays alive",self._transcribe_timeout_s,_note_transcribe_fail(),)continueexcept Exception as exc: # noqa: BLE001log.warning(- "Rolling-Whisper Transkription fehlgeschlagen (%d in Folge): %s",+ "Rolling-Whisper transcription failed (%d in a row): %s",_note_transcribe_fail(), exc,)continue@@ -465,7 +464,7 @@ class RollingWhisperWake:text = transcript.text.strip()self._last_transcript = text- # Watchdog: WAV speichern damit User/ich die Aufnahme nachprüfen können+ # Watchdog: save the WAV so the user/I can review the recording afterwardif self._save_debug_wavs:try:pcm_bytes_for_wav = (@@ -476,7 +475,7 @@ class RollingWhisperWake:wav_path = DEBUG_DIR / f"wake_{ts}_rms{rms:.3f}_{safe_text}.wav"_save_wav(pcm_bytes_for_wav, self._sample_rate, wav_path)except Exception as exc: # noqa: BLE001- log.warning("WAV-Save fehlgeschlagen: %s", exc)+ log.warning("WAV save failed: %s", exc)if not text:self._stat_empty += 1diff --git a/jarvis/speech/turn_buffer.py b/jarvis/speech/turn_buffer.pyindex 12ff18ddea..3482c800b8 100644--- a/jarvis/speech/turn_buffer.py+++ b/jarvis/speech/turn_buffer.py@@ -1,20 +1,20 @@-"""TurnBuffer — Rolling-Window der letzten User-Transkripte.+"""TurnBuffer — rolling window of the most recent user transcripts.-Dient dem Voice-Korrektur-Command ("nein, ich meinte X") als Quelle fuer das-vorletzte Transkript. Echte Phase-6-Logik (Multi-Turn-Context-Replay) folgt-spaeter; diese Implementierung persistiert minimal das was die Pipeline-aktuell uebergibt, damit `last()` / `pop_last()` funktionieren sobald der-BrainManager-Korrektur-Command aktiv wird.+Serves the voice correction command ("no, I meant X") as the source for the+second-to-last transcript. Real Phase-6 logic (multi-turn context replay)+follows later; this implementation persists, minimally, whatever the pipeline+currently passes in, so `last()` / `pop_last()` work as soon as the+BrainManager correction command goes live.-API-Contract (wie in `SpeechPipeline._handle_utterance` aufgerufen):+API contract (as called from `SpeechPipeline._handle_utterance`):turn_buffer.append(text=..., language=..., confidence=...)-Der frueheren Stub-Version fehlten die Kwargs — die Pipeline crashte mit+The earlier stub version was missing the kwargs — the pipeline crashed with``TypeError: TurnBuffer.append() got an unexpected keyword argument 'text'``-sofort nach jedem User-Utterance und kam nie zum Brain-Call. Ergebnis:-Wake triggerte, "Sir?" wurde gesprochen, dann brach die Session lautlos ab.-Siehe AGENTS.md (BUG-001 — korrigierte Root-Cause) fuer die Geschichte.+immediately after every user utterance and never reached the brain call.+Result: wake triggered, "Sir?" was spoken, then the session died silently.+See AGENTS.md (BUG-001 — corrected root cause) for the full story."""from __future__ import annotations@@ -24,14 +24,14 @@ from dataclasses import dataclass@dataclass(frozen=True)class Turn:- """Ein User-Turn im Rolling-Buffer."""+ """A single user turn in the rolling buffer."""text: strlanguage: str = ""confidence: float | None = Noneclass TurnBuffer:- """Rolling-Window der letzten N User-Turns."""+ """Rolling window of the last N user turns."""def __init__(self, maxlen: int = 10) -> None:self._maxlen = maxlen@@ -44,19 +44,19 @@ class TurnBuffer:language: str = "",confidence: float | None = None,) -> None:- """Fuegt einen neuen Turn ein (aeltester wird verdraengt bei maxlen)."""+ """Adds a new turn (the oldest is evicted once maxlen is reached)."""self._items.append(Turn(text=text, language=language, confidence=confidence))def last(self) -> Turn | None:- """Letzter gespeicherter Turn oder ``None`` wenn leer."""+ """The most recently stored turn, or ``None`` if empty."""if not self._items:return Nonereturn self._items[-1]def pop_last(self) -> Turn | None:- """Entfernt und liefert den letzten Turn (fuer Korrektur-Command)."""+ """Removes and returns the last turn (for the correction command)."""if not self._items:return Nonereturn self._items.pop()diff --git a/jarvis/speech/wake_constants.py b/jarvis/speech/wake_constants.pyindex 51638f0a5c..ccd691b94d 100644--- a/jarvis/speech/wake_constants.py+++ b/jarvis/speech/wake_constants.py@@ -42,7 +42,7 @@ DEFAULT_WAKE_PHRASE = "" # empty = neutral pre-onboarding default; user must op# hallucination must NOT match (BUG-009). This is the single definition; the# rolling-whisper backstop and the prefix verifier both re-export it.JARVIS_WAKE_PATTERN = re.compile(- r"\bh(ey|i|allo)\W+(jarv\w{1,5}|charv\w{1,5}|tscharv\w{1,5}|dschärw\w{1,5})\b",+ r"\bh(ey|i|allo)\W+(jarv\w{1,5}|charv\w{1,5}|tscharv\w{1,5}|dschärw\w{1,5})\b", # i18n-allowre.IGNORECASE,)@@ -73,7 +73,7 @@ _NON_WAKE_OWW_MODELS: frozenset[str] = frozenset({"timer", "weather"})# "Hey Rhasspy", and any phrase with a matching pretrained model works offline.INSTANT_WAKE_PHRASES: tuple[str, ...] = ()-_NORMALISE_RE = re.compile(r"[^0-9a-zäöüß]+")+_NORMALISE_RE = re.compile(r"[^0-9a-zäöüß]+") # i18n-allow_MATCH_NORMALISE_RE = re.compile(r"[^0-9a-z]+")@@ -81,7 +81,7 @@ def _strip_diacritics(text: str) -> str:"""Return an ASCII-ish form for STT matching, not display."""decomposed = unicodedata.normalize("NFKD", text or "")stripped = "".join(ch for ch in decomposed if not unicodedata.combining(ch))- return stripped.replace("ß", "ss")+ return stripped.replace("ß", "ss") # i18n-allowdef normalize_phrase(phrase: str) -> list[str]:diff --git a/jarvis/speech/watchdog.py b/jarvis/speech/watchdog.pyindex 75419b9d9d..bad5859cf7 100644--- a/jarvis/speech/watchdog.py+++ b/jarvis/speech/watchdog.py@@ -1,13 +1,13 @@-"""Watchdog-Modus: Pipeline läuft permanent, alles wird mitgeschrieben.+"""Watchdog mode: the pipeline runs continuously and everything is logged.-Unterschied zu `pipeline.py`:-- Logs gehen SOWOHL auf Konsole ALS AUCH in `./data/jarvis_watchdog.log`-- Debug-WAVs (Rolling-Whisper-Transkriptionen) in `./data/wake_debug/*.wav`-- Heartbeat alle 3 Sek auch wenn nichts passiert-- Bei jedem Wake werden Audio-Buffer gespeichert für Nachanalyse+Difference from `pipeline.py`:+- Logs go BOTH to the console AND to `./data/jarvis_watchdog.log`+- Debug WAVs (rolling-Whisper transcriptions) in `./data/wake_debug/*.wav`+- Heartbeat every 3 sec even when nothing happens+- On every wake, audio buffers are saved for later analysis-Der User / ich können nach einem Test die Log-Datei prüfen um zu sehen-ob Mic-Audio ankommt, was Whisper transkribiert, ob Wake triggert.+The user / I can check the log file after a test to see whether mic audio+is coming through, what Whisper transcribes, and whether wake triggers."""from __future__ import annotations@@ -19,7 +19,7 @@ from pathlib import Pathdef _setup_logging(log_file: Path) -> None:- """Log geht in Datei UND auf Konsole."""+ """Logs go to both the file AND the console."""log_file.parent.mkdir(parents=True, exist_ok=True)fmt = "%(asctime)s %(levelname)-5s %(name)s | %(message)s"root = logging.getLogger()@@ -88,7 +88,7 @@ async def _main() -> None:config = cfg.load_config()- # Event-Bus + Supervisor verdrahten — Voraussetzung fuer Orb-Integration+ # Wire up event bus + supervisor — prerequisite for Orb integrationbus = EventBus()supervisor = Supervisor(bus=bus)@@ -103,9 +103,9 @@ async def _main() -> None:bridge.attach()log.info("Orb-Overlay + Bus-Bridge aktiv.")except Exception as exc: # noqa: BLE001- log.warning("Orb-Overlay konnte nicht starten (%s) — laufe ohne UI.", exc)+ log.warning("Orb overlay failed to start (%s) — running without UI.", exc)- # STT-Sprache aus Config (default "auto" = bilingual DE+EN auto-detect).+ # STT language from config (default "auto" = bilingual DE+EN auto-detect).stt_language = config.stt.language if config.stt.language not in ("", "auto") else Nonestt = FasterWhisperProvider(model=config.stt.model,@@ -117,9 +117,9 @@ async def _main() -> None:tts = build_tts_from_config(config.tts)brain = build_default_brain()- # Output-Device aus config.audio.output_device ("auto-headset" by default)- # → wird von AudioPlayer._resolve_output_device aufgelöst auf den tatsächlichen- # Headset-Index, damit TTS nicht auf den Monitor-Lautsprecher spielt.+ # Output device from config.audio.output_device ("auto-headset" by default)+ # → resolved by AudioPlayer._resolve_output_device to the actual+ # headset index, so TTS doesn't play through the monitor speaker.output_device = config.audio.output_device or None_call_hk, _ptt_hk = config.trigger.resolve_hotkeys()pipeline = SpeechPipeline(@@ -146,7 +146,7 @@ async def _main() -> None:input_device=config.audio.input_device or None,output_device=output_device,)- log.info("Pipeline wird gestartet …")+ log.info("Starting pipeline …")await pipeline.run()@@ -154,4 +154,4 @@ if __name__ == "__main__":try:asyncio.run(_main())except KeyboardInterrupt:- print("\nWatchdog beendet.")+ print("\nWatchdog stopped.")diff --git a/jarvis/speech/whisper_wake.py b/jarvis/speech/whisper_wake.pyindex 07bdbd7ad9..ebcf79d25c 100644--- a/jarvis/speech/whisper_wake.py+++ b/jarvis/speech/whisper_wake.py@@ -1,16 +1,16 @@-"""Whisper-basierter Wake-Word-Fallback.+"""Whisper-based wake-word fallback.-Läuft parallel zu openWakeWord als zweite, robustere Detection: nimmt-Audio-Chunks, endpointet via Silero-VAD, transkribiert jede erkannte-Utterance kurz durch Whisper und matcht das Transkript gegen ein-Keyword-Pattern (Default: "jarvis" als Einzelwort oder in "hey jarvis").+Runs in parallel with openWakeWord as a second, more robust detector: takes+audio chunks, endpoints them via Silero VAD, transcribes each detected+utterance briefly through Whisper, and matches the transcript against a+keyword pattern (default: "jarvis" as a standalone word or within "hey jarvis").-Vorteil: versteht deutsche Aussprache nativ (Whisper ist multilingual-trainiert). Nachteil: ~800-1200 ms Latenz (VAD-Endpoint + Whisper).+Advantage: understands German pronunciation natively (Whisper is trained+multilingually). Disadvantage: ~800-1200 ms latency (VAD endpoint + Whisper).-Wir nutzen beide parallel — openWakeWord für schnelle Hits (15-30 ms),-Whisper-Wake als Sicherheitsnetz für alle Fälle wo openWakeWord nicht-zuschlägt (z.B. deutscher Akzent, niedriger Mic-Pegel).+We use both in parallel — openWakeWord for fast hits (15-30 ms), Whisper wake+as a safety net for all the cases where openWakeWord doesn't catch it (e.g. a+German accent, low mic level)."""from __future__ import annotations@@ -39,15 +39,15 @@ DEFAULT_PATTERN = re.compile(class WhisperWakeDetector:- """VAD-endpointed Whisper-Transkription mit Keyword-Match."""+ """VAD-endpointed Whisper transcription with keyword matching."""def __init__(self,stt: FasterWhisperProvider,vad: SileroEndpointer | None = None,pattern: re.Pattern[str] = DEFAULT_PATTERN,- vad_silence_ms: int = 500, # kürzer als bei regulärer Utterance- min_speech_ms: int = 150, # kürzer, "jarvis" allein reicht+ vad_silence_ms: int = 500, # shorter than for a regular utterance+ min_speech_ms: int = 150, # shorter — "jarvis" alone is enough) -> None:self._stt = sttself._vad = vad or SileroEndpointer(@@ -59,17 +59,17 @@ class WhisperWakeDetector:async def detect(self, chunks: AsyncIterator[AudioChunk]) -> AsyncIterator[str]:- """Konsumiert Audio, yielded matched-Keyword-String bei Hit."""+ """Consumes audio, yields the matched keyword string on a hit."""async for utterance_pcm in self._vad.utterances(chunks):try:transcript = await self._stt.transcribe_pcm(utterance_pcm)except Exception as exc: # noqa: BLE001- log.warning("Whisper-Wake Transkriptions-Fehler: %s", exc)+ log.warning("Whisper wake transcription error: %s", exc)continuetext = transcript.text.strip()if not text:continue- log.info("whisper-wake hört: '%s'", text)+ log.info("whisper-wake heard: '%s'", text)m = self._pattern.search(text)if m:yield m.group(0)diff --git a/jarvis/state/__init__.py b/jarvis/state/__init__.pyindex 7180f1a7ff..1cbe5bba71 100644--- a/jarvis/state/__init__.py+++ b/jarvis/state/__init__.py@@ -1,7 +1,7 @@-"""Laufzeit-State fuer die Desktop-App (Supervisor, ChatStore).+"""Runtime state for the desktop app (Supervisor, ChatStore).-Diese Objekte sind Prozess-weit eindeutig und werden vom `WebServer` ueber-`bind_*`-Setter an die FastAPI-State-Map angebunden.+These objects are unique per process and are wired into the FastAPI state map+by the `WebServer` via `bind_*` setters."""from __future__ import annotationsdiff --git a/jarvis/state/supervisor.py b/jarvis/state/supervisor.pyindex c1809ed383..72773c6cea 100644--- a/jarvis/state/supervisor.py+++ b/jarvis/state/supervisor.py@@ -1,7 +1,7 @@-"""Supervisor-State-Machine — emittiert `SystemStateChanged` auf jeden Switch.+"""Supervisor state machine — emits `SystemStateChanged` on every switch.-Phase 1a: minimal — State-Felder + Provider-Switch. Phase 4 erweitert das zu-einer echten FSM mit Guards und Multi-Harness-Dispatch (Plan §9 Phase 2 / §17.6).+Phase 1a: minimal — state fields + provider switch. Phase 4 extends this into+a real FSM with guards and multi-harness dispatch (Plan §9 Phase 2 / §17.6)."""from __future__ import annotations@@ -24,11 +24,11 @@ class SupervisorState(str, Enum):class Supervisor:- """Zentrale State-Machine + aktueller Brain-Provider-Name.+ """Central state machine + current brain-provider name.- Der Supervisor ist **keine** Brain-Instanz und **kein** Orchestrator — er- ist nur der Single-Source-of-Truth für UI-State-Anzeige und Provider-- Auswahl. Echte Brain-Dispatch liegt in `BrainManager` (Phase 2).+ The Supervisor is **not** a brain instance and **not** an orchestrator —+ it is only the single source of truth for UI state display and provider+ selection. Real brain dispatch lives in `BrainManager` (Phase 2)."""def __init__(self, *, bus: EventBus, initial_provider: str = "mock") -> None:@@ -45,7 +45,7 @@ class Supervisor:return self._active_providerasync def set_state(self, new_state: str) -> None:- """Versucht einen State-Change. No-op wenn unbekannter oder identischer State."""+ """Attempts a state change. No-op if the state is unknown or unchanged."""try:target = SupervisorState(new_state)except ValueError:diff --git a/jarvis/tasks/__init__.py b/jarvis/tasks/__init__.pyindex a1afa69cfd..c8e805c3d2 100644--- a/jarvis/tasks/__init__.py+++ b/jarvis/tasks/__init__.py@@ -1,10 +1,10 @@-"""Task-Queue (Phase 5 Capability 4).+"""Task queue (Phase 5 Capability 4).-Persistente, crash-safe Tasks mit Retry-Logic. Storage in der Memory-DB-(ADR-0003), Scheduler ist Lightweight + asyncio (ADR-0005).+Persistent, crash-safe tasks with retry logic. Storage in the memory DB+(ADR-0003), scheduler is lightweight + asyncio (ADR-0005).Exports:-- Schema-Klassen (TaskSpec, Trigger-Varianten, Action-Varianten) aus+- Schema classes (TaskSpec, trigger variants, action variants) from``jarvis.tasks.schema``.- Implementations: ``TaskStore``, ``TaskScheduler``, ``TaskRunner``."""diff --git a/jarvis/tasks/runner.py b/jarvis/tasks/runner.pyindex 785908316c..a5e3aeb27a 100644--- a/jarvis/tasks/runner.py+++ b/jarvis/tasks/runner.py@@ -1,30 +1,30 @@-"""TaskRunner — dispatcht eine persistierte Task-Spec an ihre Action.+"""TaskRunner — dispatches a persisted task spec to its action.-Lifecycle fuer einen Task:+Lifecycle of a task:scheduled → running → (completed | failed | cancelled)-Der Runner laedt die Spec aus dem Store, setzt den State auf ``running``-und unterscheidet dann nach Action-Kind:--- ``HarnessDispatchAction`` → ``HarnessManager.dispatch(...)`` und streamt- Progress-Results als ``task_steps``-Rows.-- ``SpeakAction`` → ``TTSProvider.synthesize(text)``; die Audio-Chunks- werden ans Ausgabegeraet weitergegeben (Audio-Out-Routing liegt nicht in- unserem Scope — wir konsumieren den Stream und loggen Step-Zeilen).-- ``ToolCallAction`` → ``ToolExecutor.execute(tool, args)`` via der Tool-- Registry. Risk-Tier/Approval laufen wie gewohnt.--Retry-Policy: nach einem Fehler erhoehen wir ``attempts`` und pruefen-``max_attempts``. Bei Retry: State bleibt ``scheduled`` (damit der-Scheduler den Task erneut einreiht — das passiert in einem separaten-Reschedule-Call durch den Orchestrator, siehe ADR-0005). Vereinfachung-in Phase 5: kein automatisches Backoff-Rescheduling on_event-Tasks; nur-zeitbasierte kriegen beim Fehler ``finished_at_ns`` + bleiben auf-``failed``. Der Task-Curator-Job (spaeter) kann retryen.--**Cancel-Handling:** Der Runner prueft vor jedem Step ``cancel_token.is_-cancelled()``. Wenn gesetzt, bricht er ab und setzt State auf ``cancelled``.+The runner loads the spec from the store, sets the state to ``running``,+and then branches on the action kind:++- ``HarnessDispatchAction`` → ``HarnessManager.dispatch(...)`` and streams+ progress results as ``task_steps`` rows.+- ``SpeakAction`` → ``TTSProvider.synthesize(text)``; the audio chunks are+ forwarded to the output device (audio-out routing is outside our scope —+ we consume the stream and log step lines).+- ``ToolCallAction`` → ``ToolExecutor.execute(tool, args)`` via the tool+ registry. Risk-tier/approval work as usual.++Retry policy: after a failure we increment ``attempts`` and check+``max_attempts``. On retry: the state stays ``scheduled`` (so the scheduler+re-enqueues the task — that happens in a separate reschedule call by the+orchestrator, see ADR-0005). Simplification in Phase 5: no automatic backoff+rescheduling for on_event tasks; only time-based ones get ``finished_at_ns``+on failure and stay ``failed``. The task-curator job (later) can retry.++**Cancel handling:** the runner checks ``cancel_token.is_+cancelled()`` before every step. If set, it aborts and sets the state to+``cancelled``."""from __future__ import annotations@@ -52,7 +52,7 @@ log = logging.getLogger(__name__)# -----------------------------------------------------------------------# Protokoll-Stubs fuer Dependency-Injection+# Protocol stubs for dependency injection# ----------------------------------------------------------------------class _HarnessManagerLike(Protocol):@@ -100,12 +100,12 @@ class _AutoApproverLike(Protocol):# ----------------------------------------------------------------------class TaskRunner:- """Fuehrt eine Task-Spec aus (eine Invocation pro ``run()``-Call).+ """Executes a task spec (one invocation per ``run()`` call).- Abhaengigkeiten sind optional — wenn z.B. kein ``tts`` uebergeben wird,- schlaegt ein ``SpeakAction``-Task mit sauberem Error fehl, der als- ``task_steps``-Row geloggt wird. Das erlaubt, den Runner in Tests ohne- volle Infrastruktur zu benutzen.+ Dependencies are optional — e.g. if no ``tts`` is passed, a+ ``SpeakAction`` task fails with a clean error, which is logged as a+ ``task_steps`` row. This lets the runner be used in tests without the+ full infrastructure."""def __init__(@@ -138,7 +138,7 @@ class TaskRunner:*,trigger_event: dict[str, Any] | None = None,) -> None:- """Fuehrt einen Task komplett durch. Terminal-State im Store persistiert.+ """Runs a task through to completion. The terminal state is persisted in the store.``trigger_event`` carries the flat fields of the bus event that fired an``on_event`` task (e.g. a ``MissionCompleted`` with ``result_uri``). Its@@ -147,10 +147,10 @@ class TaskRunner:"""spec = await self._store.get_spec(task_id)if spec is None:- log.warning("TaskRunner: task_id %s nicht im Store gefunden", task_id)+ log.warning("TaskRunner: task_id %s not found in store", task_id)return- # Fruehe Cancel-Probe (vor State-Wechsel)+ # Early cancel probe (before the state change)if cancel_token is not None and cancel_token.is_cancelled():await self._store.update_state(task_id, "cancelled",error=cancel_token.reason or "cancelled")@@ -211,7 +211,7 @@ class TaskRunner:Interpolates the triggering event's fields into ``template`` and publishesit as ``AnnouncementRequested(kind="subagent")`` — the readback kind thatsurvives the voice hangup gate and is mirrored to browser tabs, so it- reaches the user after "auflegen" and on a headless runtime. No-op when the+ reaches the user after "hang up" and on a headless runtime. No-op when therule set no announcement."""if not template:@@ -250,11 +250,11 @@ class TaskRunner:await self._run_tool_call(task_id, action, cancel_token)elif action.kind == "agent":await self._run_agent(task_id, action, cancel_token, ctx)- else: # pragma: no cover — schema laesst nichts anderes zu- raise RuntimeError(f"Unbekannter Action-Kind: {action.kind}")+ else: # pragma: no cover — the schema does not allow anything else+ raise RuntimeError(f"Unknown action kind: {action.kind}")# ------------------------------------------------------------------- # Action-Handler+ # Action handlers# ------------------------------------------------------------------async def _run_harness_dispatch(@@ -265,9 +265,9 @@ class TaskRunner:ctx: dict[str, Any],) -> None:if self._harness is None:- raise RuntimeError("HarnessManager nicht konfiguriert — harness_dispatch geht nicht")- # Lokaler Import, damit wir keine Zyklen auf core/protocols in- # Testumgebungen erzeugen+ raise RuntimeError("HarnessManager not configured — harness_dispatch cannot run")+ # Local import so we don't create cycles on core/protocols in+ # test environmentsfrom jarvis.core.protocols import HarnessTask# Interpolate {field} placeholders from the triggering event so a CU goal@@ -323,13 +323,13 @@ class TaskRunner:source_layer="tasks.runner"))if self._tts is None:- raise RuntimeError("TTSProvider nicht konfiguriert — speak geht nicht")+ raise RuntimeError("TTSProvider not configured — speak cannot run")- # Audit F-AUDIT-3 (2026-04-29): action.text durch scrub_for_voice- # filtern, bevor TTS es synthesisiert. Defense-in-Depth: Workflow-- # Definitionen koennten Brain-generierten Text als Speak-Action- # haben, ohne dass der Skill-Author den Filter explizit aufruft.- # Sprache: action hat optional .language; sonst Default "de".+ # Audit F-AUDIT-3 (2026-04-29): filter action.text through+ # scrub_for_voice before TTS synthesizes it. Defense-in-depth: workflow+ # definitions could have brain-generated text as a speak action without+ # the skill author explicitly calling the filter.+ # Language: action has an optional .language; otherwise default "de".from jarvis.brain.output_filter import scrub_for_voicespeak_lang = getattr(action, "language", None) or "de"scrubbed = scrub_for_voice(text, language=speak_lang)@@ -340,7 +340,7 @@ class TaskRunner:)speak_text = scrubbed.cleanedif not speak_text.strip():- log.info("tasks.runner.speak: text leer nach filter — skip TTS")+ log.info("tasks.runner.speak: text empty after filter — skipping TTS")seq = await self._store.append_step(task_id, "log",{"event": "tts_skipped", "reason": "scrub_empty"},@@ -351,9 +351,9 @@ class TaskRunner:)return- # TTS liefert einen AsyncIterator von AudioChunks. Wir konsumieren- # den Stream, damit der Provider seine Pipeline komplett abfaehrt —- # Audio-Routing liegt ausserhalb des Runners.+ # TTS returns an AsyncIterator of AudioChunks. We consume the stream+ # so the provider fully drains its pipeline — audio routing is+ # outside the runner's scope.chunk_count = 0async for _chunk in await _aiter_safe(self._tts.synthesize(speak_text)):self._check_cancel(cancel_token)@@ -453,10 +453,10 @@ class TaskRunner:cancel_token: CancelToken | None,) -> None:if self._executor is None or self._tools is None:- raise RuntimeError("ToolExecutor oder Tool-Registry nicht konfiguriert")+ raise RuntimeError("ToolExecutor or tool registry not configured")tool = _lookup_tool(self._tools, action.tool_name)if tool is None:- raise KeyError(f"Tool '{action.tool_name}' nicht im Registry")+ raise KeyError(f"Tool '{action.tool_name}' not found in registry")seq = await self._store.append_step(task_id, "action",@@ -488,12 +488,12 @@ class TaskRunner:)if not success:raise RuntimeError(- f"Tool '{action.tool_name}' fehlgeschlagen: "- f"{getattr(result, 'error', 'unbekannt')}"+ f"Tool '{action.tool_name}' failed: "+ f"{getattr(result, 'error', 'unknown')}")# ------------------------------------------------------------------- # Cancel-Check+ # Cancel check# ------------------------------------------------------------------@staticmethod@@ -507,7 +507,7 @@ class TaskRunner:# ----------------------------------------------------------------------class _Cancelled(RuntimeError):- """Interner Sentinel fuer Cancel-Paths."""+ """Internal sentinel for cancel paths."""class _SafeDict(dict):@@ -545,8 +545,8 @@ def _safe_format(template: str, ctx: dict[str, Any]) -> str:def _lookup_tool(registry: Any, name: str) -> Any:- """Nimmt entweder dict-like (``__contains__``/``__getitem__``) oder- has-get Registries an.+ """Accepts either a dict-like (``__contains__``/``__getitem__``) or a+ has-get registry."""try:if name in registry:@@ -560,12 +560,13 @@ def _lookup_tool(registry: Any, name: str) -> Any:async def _aiter_safe(maybe_coro: Any) -> Any:- """Nimmt entweder einen ``AsyncIterator`` oder eine Coroutine, die einen- zurueckgibt, und returnt den Iterator.+ """Accepts either an ``AsyncIterator`` or a coroutine that returns one,+ and returns the iterator.- Pattern ist noetig, weil manche Harness-/TTS-Implementations ``async- def dispatch(...) -> AsyncIterator`` deklarieren (Coroutine, die- Iterator liefert), andere direkt ``def dispatch(...) -> AsyncIterator``.+ This pattern is needed because some harness/TTS implementations declare+ ``async def dispatch(...) -> AsyncIterator`` (a coroutine that yields an+ iterator), while others declare ``def dispatch(...) -> AsyncIterator``+ directly."""import inspectif inspect.isawaitable(maybe_coro):diff --git a/jarvis/tasks/scheduler.py b/jarvis/tasks/scheduler.pyindex 3522ad7931..adf865bdae 100644--- a/jarvis/tasks/scheduler.py+++ b/jarvis/tasks/scheduler.py@@ -1,21 +1,20 @@-"""TaskScheduler — asyncio + heapq-basierter Scheduler (ADR-0005).+"""TaskScheduler — asyncio + heapq-based scheduler (ADR-0005).-Einfach, zwei Paths:+Simple, two paths:-1. **Zeit-basiert** (``after_delay`` + ``at_time``) — ein min-heap nach- ``due_at_ns``. Die ``run()``-Schleife poppt alle faelligen Eintraege und- dispatcht sie an den ``TaskRunner``, bevor sie auf den naechsten wartet.+1. **Time-based** (``after_delay`` + ``at_time``) — a min-heap ordered by+ ``due_at_ns``. The ``run()`` loop pops every due entry and dispatches it to+ the ``TaskRunner`` before waiting for the next one.-2. **Event-basiert** (``on_event``) — der Scheduler registriert sich als- wildcard-subscriber am Bus und dispatcht jede Event-Klasse, die ein- ``on_event``-Task als ``event_selector`` hinterlegt hat.+2. **Event-based** (``on_event``) — the scheduler registers itself as a+ wildcard subscriber on the bus and dispatches every event class that an+ ``on_event`` task has recorded as its ``event_selector``.-**Keine** Cron-Semantik, **kein** APScheduler, **kein** zweiter Thread.-Alles laeuft im Main-Async-Loop — das ist mit Absicht (ADR-0005).+**No** cron semantics, **no** APScheduler, **no** second thread.+Everything runs on the main async loop — that is deliberate (ADR-0005).-Der Scheduler nutzt einen ``CancelToken`` als oberste Abbruch-Bedingung-(ADR-0004). Laufende Tasks bekommen einen eigenen Runner-Task, die von-diesem Token abgeleitet sind.+The scheduler uses a ``CancelToken`` as its top-level abort condition+(ADR-0004). Running tasks get their own runner task, derived from this token."""from __future__ import annotations@@ -47,10 +46,10 @@ class _Dispatchable(Protocol):def parse_iso_timestamp_to_ns(iso: str) -> int:- """Konvertiert ISO-8601 (optional mit ``Z``) in UTC-Nanosekunden.+ """Converts ISO-8601 (optionally with ``Z``) into UTC nanoseconds.- Local-Time ohne TZ wird als System-Zone interpretiert — das entspricht- dem TriggerAtTime-Kontrakt (siehe schema.py).+ Local time without a TZ is interpreted as the system zone — matching the+ TriggerAtTime contract (see schema.py)."""dt = datetime.fromisoformat(iso.replace("Z", "+00:00"))if dt.tzinfo is None:@@ -59,16 +58,16 @@ def parse_iso_timestamp_to_ns(iso: str) -> int:class TaskScheduler:- """Lightweight asyncio-Scheduler.+ """Lightweight asyncio scheduler.Lifecycle:- 1. ``__init__`` — Konstruktor, bindet an Bus + Store + Runner.- 2. ``bind_bus()`` — subscribe_all fuer Event-Dispatch (optional; kann- bei Bedarf spaeter aufgerufen werden).- 3. ``run(cancel_token)`` — Main-Loop. Hydratisiert aus DB, schlaeft,- dispatcht, wartet. Beendet beim Token-Cancel.- 4. ``schedule(spec)`` — extern gerufen, wenn das UI einen neuen Task- anlegt. Schreibt in den Store + in den Heap + wakeup-Event.+ 1. ``__init__`` — constructor, binds to bus + store + runner.+ 2. ``bind_bus()`` — subscribe_all for event dispatch (optional; can be+ called later if needed).+ 3. ``run(cancel_token)`` — main loop. Hydrates from the DB, sleeps,+ dispatches, waits. Terminates on token cancel.+ 4. ``schedule(spec)`` — called externally when the UI creates a new+ task. Writes to the store + the heap + a wakeup event."""def __init__(@@ -80,23 +79,22 @@ class TaskScheduler:self._store = storeself._bus = busself._runner = runner- # Heap-Eintraege: (due_at_ns, task_id). task_id als str ist- # vergleichbar — heapq nutzt das nur als Tiebreaker bei identischen- # due_at_ns.+ # Heap entries: (due_at_ns, task_id). task_id as str is+ # comparable — heapq only uses it as a tiebreaker for identical+ # due_at_ns values.self._heap: list[tuple[int, str]] = []self._wakeup = asyncio.Event()- # On-Event-Tasks — Map Event-Klassenname → set von task_ids.- # Wildcard-Subscriber checked die Event-Klasse gegen diesen Index.+ # On-event tasks — map event class name → set of task_ids.+ # The wildcard subscriber checks the event class against this index.self._on_event_index: dict[str, set[str]] = {}self._bound = Falseself._hydrated = False- # Track bereits registrierte Task-IDs — verhindert doppelte Heap-Eintraege- # bei Race zwischen ``hydrate()`` und ``schedule()``.+ # Track already-registered task IDs — prevents duplicate heap entries+ # on a race between ``hydrate()`` and ``schedule()``.self._known: set[str] = set()- # H10-Fix: max_firings wird pro Task in-memory mitgezaehlt.- # None = unbegrenzt. Beim on_event-Match wird dekrementiert;- # bei 0 fliegt der Task aus dem Index und wird als "completed"- # markiert.+ # H10 fix: max_firings is tracked per task in memory.+ # None = unlimited. Decremented on each on_event match; at 0 the task+ # is removed from the index and marked as "completed".self._firings_left: dict[str, int | None] = {}# Fire-once dedup for event-triggered rules: an (task_id, subject) pair# that has already fired is never fired again. ``subject`` is the event's@@ -105,11 +103,11 @@ class TaskScheduler:# if a terminal event is somehow re-published. Insertion-ordered dict used# as a bounded FIFO set (see _DEDUP_CAP) to keep memory bounded.self._fired_dedup: dict[tuple[str, str], None] = {}- # Pending Runner-Tasks, damit wir beim Cancel aufraeumen koennen.+ # Pending runner tasks, so we can clean up on cancel.self._runner_tasks: set[asyncio.Task[Any]] = set()# ------------------------------------------------------------------- # Runner-Wiring (DI — der Runner kann nach Konstruktor gesetzt werden)+ # Runner wiring (DI — the runner can be set after construction)# ------------------------------------------------------------------def attach_runner(self, runner: _Dispatchable | TaskRunner) -> None:@@ -120,10 +118,10 @@ class TaskScheduler:# ------------------------------------------------------------------async def schedule(self, spec: TaskSpec, *, trace_id: str | None = None) -> str:- """Persistiert Spec, fuegt dem Heap/Event-Index zu, weckt den Loop."""+ """Persists the spec, adds it to the heap/event index, wakes the loop."""task_id = await self._store.insert(spec, trace_id=trace_id)self._register_in_memory(spec, task_id)- # TaskScheduled-Event zur Transparenz (UI listet)+ # TaskScheduled event for transparency (the UI lists it)due_at_ns = self._due_at_ns_for(spec)await self._bus.publish(TaskScheduled(@@ -138,29 +136,28 @@ class TaskScheduler:return task_idasync def cancel_task(self, task_id: str, reason: str = "user_cancel") -> bool:- """Markiert einen Task als ``cancelled``, wenn er noch nicht final ist.+ """Marks a task as ``cancelled`` if it isn't already terminal.- Entfernt ihn auch aus den In-Memory-Strukturen. Laufende Runner- werden NICHT direkt unterbrochen — dafuer haben wir den- KillSwitch-Pfad. Hier ist der Use-Case: "Task war scheduled, User- drueckt X."+ Also removes it from the in-memory structures. Running runners are+ NOT interrupted directly — that's what the kill-switch path is for.+ The use case here is: "task was scheduled, user hits X.""""task = await self._store.get(task_id)if task is None:return Falseif task["state"] in ("completed", "failed", "cancelled", "interrupted"):return False- # Aus Heap entfernen (linear scan, klein genug — typische Queue < 100).+ # Remove from heap (linear scan, small enough — a typical queue is < 100).self._heap = [(due, tid) for (due, tid) in self._heap if tid != task_id]heapq.heapify(self._heap)- # Aus Event-Index loeschen+ # Remove from the event indexfor ids in self._on_event_index.values():ids.discard(task_id)self._known.discard(task_id)await self._store.update_state(task_id, "cancelled", error=reason)await self._store.append_step(task_id, "log", {"event": "cancelled", "reason": reason})- # Event auf dem Bus+ # Event on the busfrom jarvis.core.events import TaskCancelledawait self._bus.publish(TaskCancelled(task_id=task_id, reason=reason, source_layer="tasks.scheduler")@@ -169,24 +166,24 @@ class TaskScheduler:return True# ------------------------------------------------------------------- # Event-Bus Wiring+ # Event-bus wiring# ------------------------------------------------------------------def bind_bus(self) -> None:- """Registriert den Wildcard-Handler fuer ``on_event``-Dispatch."""+ """Registers the wildcard handler for ``on_event`` dispatch."""if self._bound:returnself._bus.subscribe_all(self._on_any_event)self._bound = Trueasync def _on_any_event(self, event: Event) -> None:- """Wildcard-Handler: wenn eine Event-Klasse einem ``on_event``-Task- entspricht, den Runner fire-and-forget dispatchen.+ """Wildcard handler: if an event class matches an ``on_event`` task,+ dispatch the runner fire-and-forget.- Filter-Expression (``filter_expr``) wird via ``_match_filter`` im- Runner-Dispatch gecheckt — wir haetten hier zwar Zugriff auf das- Event, aber die Spec ist in der DB, und wir wollen in diesem Handler- nicht blockieren. Deshalb: Handler enqueues + Runner prueft.+ The filter expression (``filter_expr``) is checked via ``_match_filter``+ during the runner dispatch — we do have access to the event here, but+ the spec lives in the DB, and we don't want to block in this handler.+ Hence: the handler enqueues, and the runner checks."""cls_name = type(event).__name__task_ids = self._on_event_index.get(cls_name)@@ -195,16 +192,16 @@ class TaskScheduler:# Snapshot the event's flat fields once — handed to the runner as the# ``trigger_event`` template context ({result_uri}, {status}, ...).event_ctx = _event_to_dict(event)- # Copy, damit der Runner-Loop die Menge modifizieren darf.+ # Copy, so the runner loop is allowed to modify the set.for tid in list(task_ids):- # Filter-Matching hier vorziehen — das spart einen Runner-- # Launch bei Events, die offensichtlich nicht passen.+ # Filter-match here first — this avoids a runner launch for+ # events that obviously don't match.spec = await self._store.get_spec(tid)if spec is None:task_ids.discard(tid)continueif spec.trigger.type != "on_event":- # Defensive: sollte nie passieren, aber wenn ja, raus damit.+ # Defensive: should never happen, but if it does, drop it.task_ids.discard(tid)continueif not _match_filter(event, spec.trigger.filter_expr):@@ -218,8 +215,8 @@ class TaskScheduler:continueself._fired_dedup[dedup_key] = Noneself._trim_dedup()- # H10-Fix: max_firings in-memory tracken. Wenn 0 → Task aus- # Index entfernen, auf "completed" setzen, NICHT dispatchen.+ # H10 fix: track max_firings in memory. When 0 → remove the task+ # from the index, mark it "completed", and do NOT dispatch it.left = self._firings_left.get(tid)if left is not None:if left <= 0:@@ -228,7 +225,7 @@ class TaskScheduler:continueself._firings_left[tid] = left - 1await self._dispatch_runner(tid, trigger_event=event_ctx)- # Wenn das der letzte Fire war: cleanup.+ # If that was the last fire: clean up.if left is not None and left - 1 <= 0:task_ids.discard(tid)self._firings_left.pop(tid, None)@@ -236,23 +233,23 @@ class TaskScheduler:try:await self._store.update_state(tid, "completed")except Exception: # noqa: BLE001- log.exception("max_firings cleanup: update_state fehlgeschlagen "- "fuer task_id=%s", tid)+ log.exception("max_firings cleanup: update_state failed "+ "for task_id=%s", tid)# ------------------------------------------------------------------# Hydration# ------------------------------------------------------------------async def hydrate(self) -> None:- """Liest alle ``scheduled`` Tasks und baut Heap + Event-Index wieder auf.+ """Reads all ``scheduled`` tasks and rebuilds the heap + event index.- Idempotent: zweiter Aufruf ist no-op. Schuetzt davor, dass- ``run()``-intern und ein expliziter ``await hydrate()`` einen Task- doppelt registrieren.+ Idempotent: a second call is a no-op. Protects against ``run()``'s+ internal call and an explicit ``await hydrate()`` registering a task+ twice.- H9-Fix: Der in der DB gespeicherte ``due_at_ns`` wird **direkt**- genutzt statt neu zu rechnen. Sonst wuerde ein "in 30s" nach einem- 20s-Crash erneut 30s warten (insgesamt 50s statt 30s).+ H9 fix: the ``due_at_ns`` stored in the DB is used **directly**+ instead of being recomputed. Otherwise an "in 30s" task would wait+ another 30s after a 20s crash (50s total instead of 30s)."""if self._hydrated:return@@ -273,11 +270,11 @@ class TaskScheduler:*,stored_due_at_ns: int | None = None,) -> None:- """Fuegt einen Task dem Heap oder dem Event-Index zu — idempotent.+ """Adds a task to the heap or the event index — idempotent.- Wenn ``stored_due_at_ns`` gegeben ist (Hydration-Pfad), wird der- persistierte Wert genutzt; sonst berechnet der Trigger neu- (Schedule-Pfad bei Neu-Inserts).+ If ``stored_due_at_ns`` is given (the hydration path), the persisted+ value is used; otherwise the trigger recomputes it (the schedule path+ for new inserts)."""if task_id in self._known:return@@ -302,7 +299,7 @@ class TaskScheduler:heapq.heappush(self._heap, (due, task_id))elif trig.type == "on_event":self._on_event_index.setdefault(trig.event_name, set()).add(task_id)- self._firings_left[task_id] = trig.max_firings # None = unbegrenzt+ self._firings_left[task_id] = trig.max_firings # None = unlimitedself._known.add(task_id)def _due_at_ns_for(self, spec: TaskSpec) -> int | None:@@ -324,13 +321,13 @@ class TaskScheduler:return None# ------------------------------------------------------------------- # Main-Loop+ # Main loop# ------------------------------------------------------------------async def run(self, cancel_token: CancelToken | None = None) -> None:- """Main-Loop — laeuft bis ``cancel_token.is_cancelled()``.+ """Main loop — runs until ``cancel_token.is_cancelled()``.- Typische Verwendung aus dem DesktopApp/Orchestrator:+ Typical usage from the DesktopApp/orchestrator:token = CancelToken()scheduler = TaskScheduler(store, bus, runner)@@ -347,7 +344,7 @@ class TaskScheduler:now_ns = time.time_ns()await self._drain_due_tasks(now_ns)- # Naechstes Wake-up: entweder next-due oder unendlich+ # Next wakeup: either the next-due time or indefinitelyif self._heap:timeout = max(0.05, (self._heap[0][0] - now_ns) / 1e9)else:@@ -400,7 +397,7 @@ class TaskScheduler:trigger_event: dict[str, Any] | None = None,) -> None:if self._runner is None:- log.warning("TaskScheduler.run: kein Runner attached, Task %s faellt durch", task_id)+ log.warning("TaskScheduler.run: no runner attached, task %s falls through", task_id)returntask = asyncio.create_task(self._safe_run(task_id, trigger_event), name=f"task-runner-{task_id}"@@ -417,7 +414,7 @@ class TaskScheduler:log.exception("TaskRunner crashed task=%s: %s", task_id, exc)async def shutdown(self) -> None:- """Wartet auf Runner-Tasks ab (mit Timeout). Aufrufer stoppt vorher den Loop."""+ """Waits for runner tasks to finish (with a timeout). The caller must stop the loop first."""tasks = list(self._runner_tasks)if not tasks:return@@ -456,18 +453,18 @@ def _dedup_key(task_id: str, event: Event) -> tuple[str, str] | None:# -----------------------------------------------------------------------# Filter-Expression — sichere Auswertung+# Filter expression — safe evaluation# ----------------------------------------------------------------------def _match_filter(event: Event, filter_expr: str | None) -> bool:- """Wertet eine Filter-Expression gegen ein Event aus.+ """Evaluates a filter expression against an event.- Unterstuetzte Operatoren: ``==``, ``!=``, ``and``, ``or``, ``not``,- sowie Zugriff auf einfache Feld-Namen (z.B. ``role``, ``text``).+ Supported operators: ``==``, ``!=``, ``and``, ``or``, ``not``, plus+ access to plain field names (e.g. ``role``, ``text``).- Die Implementierung ist AST-basiert (``ast.parse`` + ``ast.walk``),- akzeptiert nur eine Whitelist von Node-Typen — **kein** ``eval()``,- keine Attribute-Access-Chain, keine Function-Calls.+ The implementation is AST-based (``ast.parse`` + ``ast.walk``) and+ accepts only a whitelist of node types — **no** ``eval()``, no+ attribute-access chains, no function calls."""if filter_expr is None or filter_expr.strip() == "":return True@@ -489,8 +486,8 @@ def _match_filter(event: Event, filter_expr: str | None) -> bool:return Falseenv: dict[str, Any] = {}- # Bau ein flaches Namespace aus den Event-Feldern. Nested Dicts werden- # bewusst NICHT unterstuetzt — der Scope ist Feld-Gleichheit auf top-level.+ # Build a flat namespace from the event's fields. Nested dicts are+ # deliberately NOT supported — the scope is top-level field equality.for field in getattr(event, "__dataclass_fields__", {}).keys():env[field] = getattr(event, field, None)@@ -523,4 +520,3 @@ def _eval_ast_node(node: Any, env: dict[str, Any]) -> Any:return Truereturn False-diff --git a/jarvis/tasks/schema.py b/jarvis/tasks/schema.pyindex 85ed46868e..5c65901cef 100644--- a/jarvis/tasks/schema.py+++ b/jarvis/tasks/schema.py@@ -1,11 +1,11 @@-"""TaskSpec-Schema — Pydantic-Modelle fuer die persistente Task-Queue.+"""TaskSpec schema — Pydantic models for the persistent task queue.-Trigger-Scope ist bewusst klein (Mandat §8.3, User-Bestaetigung):-`after_delay`, `at_time`, `on_event`. Kein Cron (das haben Skills),-keine RRULE.+The trigger scope is deliberately small (mandate §8.3, user-confirmed):+`after_delay`, `at_time`, `on_event`. No cron (skills have that already),+no RRULE.-ADR-0003 beschreibt das DB-Schema, dieses Modul die In-Memory- und-JSON-Repraesentation.+ADR-0003 describes the DB schema; this module covers the in-memory and JSON+representation."""from __future__ import annotations@@ -19,15 +19,15 @@ from pydantic import BaseModel, ConfigDict, Field# ---------------------------------------------------------------------class TriggerAfterDelay(BaseModel):- """'In N Sekunden' — relativ zu `time.time_ns()` bei Scheduling."""+ """'In N seconds' — relative to `time.time_ns()` at scheduling time."""model_config = ConfigDict(frozen=True, extra="forbid")type: Literal["after_delay"] = "after_delay"- delay_seconds: float = Field(gt=0, le=30 * 24 * 3600) # max 30 Tage+ delay_seconds: float = Field(gt=0, le=30 * 24 * 3600) # max 30 daysclass TriggerAtTime(BaseModel):- """Absoluter Zeitpunkt, ISO-8601 mit Zeitzone. Local-Time ohne TZ wird- als System-Zone interpretiert.+ """Absolute point in time, ISO-8601 with timezone. Local time without a+ TZ is interpreted as the system zone."""model_config = ConfigDict(frozen=True, extra="forbid")type: Literal["at_time"] = "at_time"@@ -35,8 +35,8 @@ class TriggerAtTime(BaseModel):class TriggerOnEvent(BaseModel):- """'Wenn Event X passiert' — Event-Klassen-Name plus optionaler- Filter-Ausdruck (Feldvergleich). Beispiel:+ """'When event X happens' — the event class name plus an optional+ filter expression (field comparison). Example:event_name = "MessageSent"filter_expr = "role == 'user'"@@ -78,11 +78,11 @@ TRIGGER_TYPES: tuple[str, ...] = ("after_delay", "at_time", "on_event", "every")# ----------------------------------------------------------------------# Action — was beim Trigger ausgefuehrt wird+# Action — what runs when the trigger fires# ---------------------------------------------------------------------class HarnessDispatchAction(BaseModel):- """Dispatcht an einen Harness (openclaw, computer-use, ...)."""+ """Dispatches to a harness (openclaw, computer-use, ...)."""model_config = ConfigDict(frozen=True, extra="forbid")kind: Literal["harness_dispatch"] = "harness_dispatch"harness: str = Field(min_length=1, max_length=64)@@ -91,14 +91,14 @@ class HarnessDispatchAction(BaseModel):class SpeakAction(BaseModel):- """TTS — Jarvis sagt einen fixen Satz (z.B. 'erinner mich heute Abend')."""+ """TTS — Jarvis says a fixed sentence (e.g. 'remind me tonight')."""model_config = ConfigDict(frozen=True, extra="forbid")kind: Literal["speak"] = "speak"text: str = Field(min_length=1, max_length=2048)class ToolCallAction(BaseModel):- """Einzelnen Tool ausfuehren (z.B. 'open_app Outlook')."""+ """Run a single tool (e.g. 'open_app Outlook')."""model_config = ConfigDict(frozen=True, extra="forbid")kind: Literal["tool_call"] = "tool_call"tool_name: str = Field(min_length=1, max_length=64)@@ -147,7 +147,7 @@ ACTION_KINDS: tuple[str, ...] = ("harness_dispatch", "speak", "tool_call", "agen# ----------------------------------------------------------------------# Retry-Policy+# Retry policy# ---------------------------------------------------------------------class RetryPolicy(BaseModel):@@ -156,21 +156,21 @@ class RetryPolicy(BaseModel):max_attempts: int = Field(default=1, ge=1, le=10)backoff_initial_s: float = Field(default=5.0, ge=0, le=3600)backoff_factor: float = Field(default=2.0, ge=1.0, le=10.0)- retry_on_interrupt: bool = True # Startup-Cleanup (ADR-0003)+ retry_on_interrupt: bool = True # startup cleanup (ADR-0003)# ----------------------------------------------------------------------# TaskSpec + State+# TaskSpec + state# ---------------------------------------------------------------------TaskState = Literal[- "pending", # noch nie geschedult (z.B. created_from_api, wartet auf hydrate)- "scheduled", # im Heap oder wartet auf Event- "running", # TaskRunner fuehrt gerade aus- "completed", # Erfolgreich beendet- "failed", # Nach max_attempts aufgegeben- "cancelled", # Manuell oder Kill-Switch- "interrupted", # App-Exit waehrend running (ADR-0003)+ "pending", # never scheduled yet (e.g. created_from_api, waiting for hydrate)+ "scheduled", # in the heap or waiting for an event+ "running", # the TaskRunner is currently executing it+ "completed", # finished successfully+ "failed", # given up after max_attempts+ "cancelled", # manual or kill-switch+ "interrupted", # app exit while running (ADR-0003)]@@ -181,7 +181,7 @@ TASK_STATES: tuple[str, ...] = (class TaskSpec(BaseModel):- """Die Beschreibung eines geschedulten Tasks — persistiert als JSON in+ """The description of a scheduled task — persisted as JSON in`tasks.spec_json`."""model_config = ConfigDict(frozen=True, extra="forbid")@@ -198,7 +198,7 @@ class TaskSpec(BaseModel):# terminal outcome, action-agnostic (the `harness_dispatch`/CU path does not# self-announce, unlike `agent`). Published as AnnouncementRequested(# kind="subagent"), which punches through the voice hangup gate and is- # mirrored to browser tabs — so "say Bescheid" works post-hangup and headless.+ # mirrored to browser tabs — so "let me know" works post-hangup and headless.# Both support {field} placeholders interpolated from the triggering event# (e.g. "Done — opened {result_uri}."). None = stay silent (legacy behaviour).announce_on_success: str | None = Field(default=None, max_length=2048)diff --git a/jarvis/tasks/store.py b/jarvis/tasks/store.pyindex 48aa303335..c1f6796305 100644--- a/jarvis/tasks/store.py+++ b/jarvis/tasks/store.py@@ -1,15 +1,15 @@-"""TaskStore — aiosqlite-basierte Persistenz fuer die Task-Queue (ADR-0003).+"""TaskStore — aiosqlite-based persistence for the task queue (ADR-0003).-Der Store ist bewusst dumm: kein Scheduling, kein Event-Dispatch. Nur-CRUD + transaktionale State-Uebergaenge + Startup-Cleanup.+The store is deliberately dumb: no scheduling, no event dispatch. Just+CRUD + transactional state transitions + startup cleanup.-Zwei Tabellen:-- ``tasks`` — Hauptzeile pro geschedultem Task (TaskSpec als JSON-Blob).-- ``task_steps`` — Append-only Step-Log (Runner schreibt hier observation/action/- verify/log-Zeilen, UI rendert sie als Timeline).+Two tables:+- ``tasks`` — main row per scheduled task (TaskSpec as a JSON blob).+- ``task_steps`` — append-only step log (the runner writes observation/action/+ verify/log lines here, the UI renders them as a timeline).-Pattern: identisch zu ``jarvis/memory/recall.py`` (``aiosqlite`` + ``ensure_open``-Lazy-Init damit die Store-Instanz synchron konstruiert werden kann).+Pattern: identical to ``jarvis/memory/recall.py`` (``aiosqlite`` + ``ensure_open``+lazy-init so the store instance can be constructed synchronously)."""from __future__ import annotations@@ -51,12 +51,12 @@ CREATE TABLE tasks_new (class TaskStore:- """CRUD-Store fuer Tasks + Steps auf der gemeinsamen Memory-DB.+ """CRUD store for tasks + steps on the shared memory DB.- Die DB-Datei wird NICHT von dieser Klasse initialisiert, was das- Memory-Schema angeht — das uebernimmt ``RecallStore``. Wir koennen- aber trotzdem init() unabhaengig aufrufen, weil unser Schema- additiv und idempotent ist (``CREATE TABLE IF NOT EXISTS``).+ The DB file is NOT initialized by this class as far as the memory+ schema is concerned — ``RecallStore`` handles that. We can still call+ init() independently, though, because our schema is additive and+ idempotent (``CREATE TABLE IF NOT EXISTS``)."""name: str = "sqlite-tasks"@@ -71,13 +71,13 @@ class TaskStore:# ------------------------------------------------------------------async def init(self) -> None:- """Oeffnet DB-Connection + fuehrt additives Schema aus."""+ """Opens the DB connection + runs the additive schema."""if self._conn is not None:returnself._conn = await aiosqlite.connect(self._db_path, isolation_level=None)self._conn.row_factory = aiosqlite.Row- # PRAGMAs: WAL + busy_timeout kommen vom Memory-Schema, aber- # bei einer noch leeren DB setzen wir sie sicherheitshalber auch hier.+ # PRAGMAs: WAL + busy_timeout come from the memory schema, but on a+ # still-empty DB we set them here too, just to be safe.await self._conn.execute("PRAGMA journal_mode = WAL")await self._conn.execute("PRAGMA busy_timeout = 5000")await self._conn.execute("PRAGMA foreign_keys = ON")@@ -103,7 +103,7 @@ class TaskStore:def _require_conn(self) -> aiosqlite.Connection:if self._conn is None:raise RuntimeError(- "TaskStore nicht initialisiert — rufe init() oder nutze 'async with'."+ "TaskStore not initialized — call init() or use 'async with'.")return self._conn@@ -165,23 +165,23 @@ class TaskStore:)# ------------------------------------------------------------------- # Hilfen+ # Helpers# ------------------------------------------------------------------@staticmethoddef _compute_trigger_fields(spec: TaskSpec) -> tuple[str, int | None, str | None]:- """Extrahiert ``(trigger_type, due_at_ns, event_selector)`` aus einer Spec.+ """Extracts ``(trigger_type, due_at_ns, event_selector)`` from a spec.- ``due_at_ns`` ist UTC-nano-seconds; beim Scheduler wird es mit- ``time.time_ns()`` verglichen.+ ``due_at_ns`` is UTC nanoseconds; the scheduler compares it against+ ``time.time_ns()``."""trig = spec.triggerif trig.type == "after_delay":due = time.time_ns() + int(trig.delay_seconds * 1e9)return "after_delay", due, Noneif trig.type == "at_time":- # Parsing-Responsibility liegt beim Scheduler (ISO-8601 + TZ).- # Hier nur fallback: wenn parsen klappt, nutzen wir ihn.+ # Parsing responsibility lives with the scheduler (ISO-8601 + TZ).+ # Here just a fallback: if parsing succeeds, we use it.from datetime import datetimetry:dt = datetime.fromisoformat(trig.iso_timestamp.replace("Z", "+00:00"))@@ -207,18 +207,18 @@ class TaskStore:else:due = time.time_ns() + int(trig.interval_seconds * 1e9)return "every", due, None- raise ValueError(f"Unbekannter Trigger-Typ: {trig.type}") # pragma: no cover+ raise ValueError(f"Unknown trigger type: {trig.type}") # pragma: no cover# ------------------------------------------------------------------# CRUD# ------------------------------------------------------------------async def insert(self, spec: TaskSpec, *, trace_id: str | None = None) -> str:- """Legt einen neuen Task mit ``state='scheduled'`` an.+ """Creates a new task with ``state='scheduled'``.- Returnt die Task-ID (str). ``trace_id`` darf optional mitgegeben- werden; sonst wird die Spec-ID als Trace verwendet (ein Task = ein- Trace, solange kein anderer Scope ueberschreibt).+ Returns the task ID (str). ``trace_id`` may optionally be passed in;+ otherwise the spec ID is used as the trace (one task = one trace, as+ long as no other scope overrides it)."""conn = self._require_conn()trigger_type, due_at_ns, event_selector = self._compute_trigger_fields(spec)@@ -249,10 +249,10 @@ class TaskStore:result: dict[str, Any] | None = None,increment_attempts: bool = False,) -> None:- """Uebergang in einen neuen State, atomar mit optionaler Fehler-/Result-Info.+ """Transitions to a new state, atomically, with optional error/result info.- Setzt automatisch ``started_at_ns`` beim Uebergang in ``running``- und ``finished_at_ns`` in Terminal-States.+ Automatically sets ``started_at_ns`` on the transition to ``running``+ and ``finished_at_ns`` on terminal states."""conn = self._require_conn()now_ns = time.time_ns()@@ -275,8 +275,8 @@ class TaskStore:sets.append("attempts = attempts + 1")params.append(task_id)- # `sets` ist eine Whitelist von Spalten-Zuweisungen (oben statisch- # erzeugt) — kein User-Input fliesst in den SQL-String.+ # `sets` is a whitelist of column assignments (built statically+ # above) — no user input flows into the SQL string.sql = f"UPDATE tasks SET {', '.join(sets)} WHERE id = ?" # noqa: S608await conn.execute(sql, tuple(params))@@ -286,11 +286,11 @@ class TaskStore:kind: str,payload: dict[str, Any],) -> int:- """Haengt einen Step an ``task_steps`` an. Returnt die neue ``seq``.+ """Appends a step to ``task_steps``. Returns the new ``seq``.- ``kind`` ist ``'observation' | 'action' | 'verify' | 'log'``. Keine- harte DB-Constraint, damit Runner auch andere Kinds (z.B. 'retry')- eintragen kann.+ ``kind`` is ``'observation' | 'action' | 'verify' | 'log'``. No hard+ DB constraint, so the runner can also record other kinds (e.g.+ 'retry')."""conn = self._require_conn()cur = await conn.execute(@@ -315,7 +315,7 @@ class TaskStore:*,limit: int = 100,) -> list[dict[str, Any]]:- """Returnt eine Liste von Task-Rows (ohne Steps), gefiltert nach State."""+ """Returns a list of task rows (without steps), filtered by state."""conn = self._require_conn()sql = ("SELECT id, trace_id, state, trigger_type, due_at_ns, title, "@@ -339,7 +339,7 @@ class TaskStore:return [dict(r) for r in rows]async def get(self, task_id: str) -> dict[str, Any] | None:- """Returnt Full-Task (inkl. Steps) oder None."""+ """Returns the full task (incl. steps), or None."""conn = self._require_conn()cur = await conn.execute("SELECT * FROM tasks WHERE id = ?", (task_id,))row = await cur.fetchone()@@ -367,7 +367,7 @@ class TaskStore:return taskasync def get_spec(self, task_id: str) -> TaskSpec | None:- """Deserialisiert ``spec_json`` zurueck zu einer TaskSpec."""+ """Deserializes ``spec_json`` back into a TaskSpec."""conn = self._require_conn()cur = await conn.execute("SELECT spec_json FROM tasks WHERE id = ?", (task_id,)@@ -379,7 +379,7 @@ class TaskStore:return TaskSpec.model_validate_json(row["spec_json"])async def delete(self, task_id: str) -> bool:- """Entfernt Task + Steps (via ON DELETE CASCADE). Returnt ob ein Row getroffen wurde."""+ """Removes the task + steps (via ON DELETE CASCADE). Returns whether a row was hit."""conn = self._require_conn()cur = await conn.execute("DELETE FROM tasks WHERE id = ?", (task_id,))rowcount = cur.rowcount@@ -387,14 +387,14 @@ class TaskStore:return rowcount > 0async def all_pending_scheduled(self) -> list[dict[str, Any]]:- """Fuer Scheduler-Hydration: alle Tasks im State ``scheduled``."""+ """For scheduler hydration: all tasks in state ``scheduled``."""return await self.list(state_filter="scheduled", limit=10_000)async def cleanup_interrupted(self) -> int:- """Startup-Cleanup: alle ``running`` → ``interrupted`` mit Error-Log.+ """Startup cleanup: all ``running`` → ``interrupted`` with an error log.- Returnt die Anzahl der betroffenen Tasks. Laut ADR-0003 muss das- beim App-Start aufgerufen werden, bevor der Scheduler haydriert.+ Returns the number of affected tasks. Per ADR-0003 this must be+ called at app start, before the scheduler hydrates."""conn = self._require_conn()now_ns = time.time_ns()diff --git a/jarvis/telemetry/recorder.py b/jarvis/telemetry/recorder.pyindex a529d73b0f..3a6dc1415a 100644--- a/jarvis/telemetry/recorder.py+++ b/jarvis/telemetry/recorder.py@@ -1,14 +1,14 @@-"""Flight-Recorder — JSONL-Event-Log fuer Replay und Debug (ADR-0007).+"""Flight recorder — JSONL event log for replay and debugging (ADR-0007).-Wird als Wildcard-Subscriber (`bus.subscribe_all`) aktiviert und schreibt-jedes Event als eine Zeile in `data/flight_recorder/YYYY-MM-DD.jsonl`.+Activated as a wildcard subscriber (`bus.subscribe_all`) and writes every+event as one line into `data/flight_recorder/YYYY-MM-DD.jsonl`.-Binaerdaten > 64 KB (z.B. Screenshots) werden nicht inline ge-dumpt,-sondern in `blobs/<hash>.<ext>` ausgelagert und per `{"__file__": "..."}`-referenziert — damit bleibt die JSONL jq-faehig.+Binary data > 64 KB (e.g. screenshots) is not dumped inline; instead it is+externalized into `blobs/<hash>.<ext>` and referenced via `{"__file__": "..."}`+— this keeps the JSONL jq-friendly.-Rotation bei Tageswechsel und bei File-Size > 500 MB (`-2`, `-3`, ...).-Ein `contextlib`-Flag fuer async-safe Write-Failures.+Rotates on a day change and when the file size exceeds 500 MB (`-2`, `-3`, ...).+A `contextlib` flag guards async-safe write failures."""from __future__ import annotations@@ -31,13 +31,13 @@ if TYPE_CHECKING:from jarvis.core.bus import EventBus-# Top-Level-Keys, die nicht als "payload" serialisiert werden — sie-# landen auf Top-Level des JSON-Records (damit jq einfacher geht).+# Top-level keys that are not serialized as "payload" — they land at the+# top level of the JSON record (so jq queries stay simple)._TOP_LEVEL_FIELDS = frozenset({"trace_id", "timestamp_ns", "source_layer"})def _json_default(value: Any) -> Any:- """JSON-Encoder fuer die Typen, die stdlib nicht direkt beherrscht."""+ """JSON encoder for the types the stdlib doesn't handle directly."""if isinstance(value, UUID):return value.hexif isinstance(value, bytes):@@ -50,7 +50,7 @@ def _json_default(value: Any) -> Any:class FlightRecorder:- """Wildcard-Subscriber am EventBus.+ """Wildcard subscriber on the EventBus.Lifecycle:rec = FlightRecorder(data_dir=Path("data/flight_recorder"))@@ -60,15 +60,15 @@ class FlightRecorder:await rec.close()"""- # JSONL-Zeilen werden gepuffert und alle `flush_interval_s` Sekunden- # per `fsync` in die Datei geschrieben — verhindert Disk-Kummer bei- # vielen kleinen Writes, ohne Crash-Safety zu verlieren.+ # JSONL lines are buffered and written to the file via `fsync` every+ # `flush_interval_s` seconds — avoids disk-I/O pain from many small+ # writes, without losing crash safety.flush_interval_s: float = 1.0- # Binaerdaten-Inline-Limit. Alles groesser wird in `blobs/` ausgelagert.+ # Binary-data inline limit. Anything larger is externalized into `blobs/`.blob_inline_limit_bytes: int = 64 * 1024- # File-Rotation — JSONL ueber dieser Groesse bekommt Suffix `-2`, `-3`, ...+ # File rotation — a JSONL over this size gets suffix `-2`, `-3`, ...rotation_size_bytes: int = 500 * 1024 * 1024def __init__(@@ -98,7 +98,7 @@ class FlightRecorder:# ---------------- Bus binding ----------------def attach(self, bus: EventBus) -> None:- """Registriert sich als Wildcard-Subscriber. Idempotent."""+ """Registers as a wildcard subscriber. Idempotent."""if self._subscribed_bus is bus:returnself._subscribed_bus = bus@@ -125,7 +125,7 @@ class FlightRecorder:"layer": data.pop("source_layer", ""),}data.pop("trace_id", None)- # Blob-Externalisierung fuer Felder, die als bytes ankommen.+ # Externalize into blobs any field that arrives as bytes.for key, value in list(data.items()):if isinstance(value, bytes) and len(value) > self.blob_inline_limit_bytes:data[key] = self._store_blob(value, hint=key)@@ -147,7 +147,7 @@ class FlightRecorder:if day != self._current_day:self._current_day = daybase = self._data_dir / f"{self._current_day}.jsonl"- # Rotation bei Groesse+ # Rotate on sizeif base.exists() and base.stat().st_size >= self.rotation_size_bytes:for suffix in range(2, 1000):cand = self._data_dir / f"{self._current_day}-{suffix}.jsonl"@@ -156,7 +156,7 @@ class FlightRecorder:return baseasync def flush(self) -> None:- """Schreibt gepufferte Zeilen in die aktuelle JSONL-Datei."""+ """Writes buffered lines to the current JSONL file."""with self._lock:if not self._buffer:return@@ -172,18 +172,17 @@ class FlightRecorder:await self.flush()self._subscribed_bus = None- # ---------------- Replay-Helpers ----------------+ # ---------------- Replay helpers ----------------def iter_events_for_trace(self, trace_id: UUID) -> list[dict[str, Any]]:- """Liest alle Tages-JSONLs und filtert nach `trace_id`.+ """Reads all daily JSONLs and filters by `trace_id`.- Nutzung nur durch Replay-CLI / Tests — fuer Produktionsqueries- sollte man `grep` oder `jq` nehmen.+ Only used by the replay CLI / tests — for production queries you+ should use `grep` or `jq`.- H3-Fix: `suppress(OSError)` umschliesst jetzt den **gesamten**- Read-Loop (nicht nur den ``open()``-Call). Sonst wuerde ein I/O-- Fehler mitten in ``readline()`` durchschlagen — besonders lustig- auf Netzlaufwerken.+ H3 fix: `suppress(OSError)` now wraps the **entire** read loop (not+ just the ``open()`` call). Otherwise an I/O error mid-``readline()``+ would propagate — especially fun on network drives."""target = trace_id.hexout: list[dict[str, Any]] = []diff --git a/jarvis/telemetry/replay.py b/jarvis/telemetry/replay.pyindex 1c04b5c14a..ea2a3eb5a3 100644--- a/jarvis/telemetry/replay.py+++ b/jarvis/telemetry/replay.py@@ -1,13 +1,13 @@-"""Replay-CLI — rendert einen Computer-Use-/Task-Trace als Timeline.+"""Replay CLI — renders a Computer-Use/task trace as a timeline.Usage:python -m jarvis.telemetry.replay <trace_id>python -m jarvis.telemetry.replay <trace_id> --jsonpython -m jarvis.telemetry.replay <trace_id> --data-dir data/flight_recorder-Zeigt pro Event eine Zeile mit relativer Zeit, Event-Typ und den-interessanten Payload-Feldern. Bei `--json` wird die rohe JSONL-Zeile-durchgereicht (gut fuer jq-Pipelines).+Shows one line per event with the relative time, event type, and the+interesting payload fields. With `--json`, the raw JSONL line is passed+through unchanged (handy for jq pipelines)."""from __future__ import annotations@@ -20,8 +20,8 @@ from uuid import UUIDfrom .recorder import FlightRecorder-# Welche Payload-Felder bei welchem Event besonders interessant sind.-# Nur fuer die human-readable Ausgabe — alles andere landet als "..."+# Which payload fields are especially interesting for which event.+# Only for the human-readable output — everything else ends up as "..."_FEATURED_FIELDS: dict[str, tuple[str, ...]] = {"HarnessDispatched": ("harness",),"HarnessProgress": ("harness", "exit_code"),@@ -49,7 +49,7 @@ _FEATURED_FIELDS: dict[str, tuple[str, ...]] = {def _fmt_payload(event: str, payload: dict[str, Any]) -> str:fields = _FEATURED_FIELDS.get(event)if not fields:- # Fallback: kurz die ersten 3 Non-Null-Felder zeigen+ # Fallback: briefly show the first 3 non-null fieldsitems = [(k, v) for k, v in payload.items() if v not in (None, "", 0, False)]items = items[:3]else:@@ -65,10 +65,10 @@ def _fmt_payload(event: str, payload: dict[str, Any]) -> str:def render_timeline(records: list[dict[str, Any]], *, out=None) -> None:- # Default late-bound, damit pytest's capsys-Redirect wirkt.+ # Default late-bound, so pytest's capsys redirect takes effect.out = out if out is not None else sys.stdoutif not records:- print("Keine Events fuer diese trace_id gefunden.", file=out)+ print("No events found for this trace_id.", file=out)returnt0 = records[0].get("ts_ns", 0)for rec in records:@@ -88,20 +88,20 @@ def render_json(records: list[dict[str, Any]], *, out=None) -> None:def main(argv: list[str] | None = None) -> int:parser = argparse.ArgumentParser(prog="jarvis.telemetry.replay",- description="Rendert den Flight-Recorder-Trace einer trace_id als Timeline.",+ description="Renders the flight-recorder trace of a trace_id as a timeline.",)- parser.add_argument("trace_id", help="UUID (Hex oder String-Format)")+ parser.add_argument("trace_id", help="UUID (hex or string format)")parser.add_argument("--data-dir",default="data/flight_recorder",- help="Verzeichnis mit den JSONL-Files")+ help="Directory containing the JSONL files")parser.add_argument("--json", action="store_true",- help="Gibt die rohen JSONL-Eintraege aus statt der Timeline")+ help="Print the raw JSONL entries instead of the timeline")args = parser.parse_args(argv)try:trace_id = UUID(args.trace_id)except ValueError:- print(f"Ungueltige trace_id: {args.trace_id}", file=sys.stderr)+ print(f"Invalid trace_id: {args.trace_id}", file=sys.stderr)return 2recorder = FlightRecorder(data_dir=Path(args.data_dir))diff --git a/jarvis/telephony/session.py b/jarvis/telephony/session.pyindex e7e6471b15..dc794f030c 100644--- a/jarvis/telephony/session.py+++ b/jarvis/telephony/session.py@@ -71,7 +71,7 @@ log = logging.getLogger("jarvis.telephony.session")# HANGUP_RE is re-exported below (see __all__) so importers keep working.# Default greeting when TwilioConfig.greeting is empty (butler persona).-DEFAULT_GREETING_DE = "Hier ist Jarvis. Wie kann ich helfen?"+DEFAULT_GREETING_DE = "Hier ist Jarvis. Wie kann ich helfen?" # i18n-allow: German TTS greeting spoken to phone callersDEFAULT_GREETING_EN = "Jarvis here. How can I help?"# Send callback signature: an awaitable that ships one JSON-serialisable dict@@ -572,7 +572,7 @@ class TelephonyCallSession:def _fallback_phrase(self) -> str:if self._lang_short() == "en":return "Sorry, I did not catch that. Could you say it again?"- return "Entschuldigung, das habe ich nicht verstanden. Bitte wiederhole es."+ return "Entschuldigung, das habe ich nicht verstanden. Bitte wiederhole es." # i18n-allow: German TTS fallback phrase spoken to phone callers# -- bus events --------------------------------------------------------diff --git a/jarvis/terminal/__init__.py b/jarvis/terminal/__init__.pyindex 1b2b080cf0..66f324754c 100644--- a/jarvis/terminal/__init__.py+++ b/jarvis/terminal/__init__.py@@ -1,12 +1,12 @@-"""Terminal-Layer fuer die Desktop-App (Phase 1a-Erweiterung).+"""Terminal layer for the Desktop App (Phase 1a extension).-Stellt einen in-process PTY-Manager bereit, der Shells (PowerShell 7,-Windows PowerShell 5.1, CMD, Git-Bash) via ConPTY spawnt und deren-I/O ueber den Event-Bus zur Web-UI forwarded.+Provides an in-process PTY manager that spawns shells (PowerShell 7,+Windows PowerShell 5.1, CMD, Git Bash) via ConPTY and forwards their+I/O to the web UI over the event bus.-Modul-Struktur:-- shells.py — Discovery der verfuegbaren Shells auf diesem System.-- pty_manager.py — Async-Wrapper um pywinpty, verwaltet Sessions.+Module structure:+- shells.py — discovery of the shells available on this system.+- pty_manager.py — async wrapper around pywinpty, manages sessions."""from __future__ import annotationsdiff --git a/jarvis/terminal/backend.py b/jarvis/terminal/backend.pyindex 22d56cd521..6f93a395a3 100644--- a/jarvis/terminal/backend.py+++ b/jarvis/terminal/backend.py@@ -15,7 +15,7 @@ read-loop in ``pty_manager.py`` keeps working verbatim once it talks to a* ``winpty.PtyProcess`` already deals in ``str`` (ConPTY decodes for us), so``WinptyBackend`` is a thin pass-through that preserves the exact- ``RuntimeError("pywinpty nicht installiert ...")`` degrade.+ ``RuntimeError("pywinpty not installed ...")`` degrade.* ``ptyprocess.PtyProcess`` deals in ``bytes`` (``.read`` returns bytes,``.write`` takes bytes), so ``UnixPtyBackend`` decodes ``utf-8`` with``errors="replace"`` on read and encodes on write.@@ -147,7 +147,7 @@ class WinptyBackend:except ImportError as exc:# Preserve the exact degrade message from pty_manager.py:72-75.raise RuntimeError(- "pywinpty nicht installiert — `pip install pywinpty` (Windows-only)."+ "pywinpty not installed — `pip install pywinpty` (Windows-only).") from excproc = PtyProcess.spawn(diff --git a/jarvis/terminal/pty_manager.py b/jarvis/terminal/pty_manager.pyindex ef0534ffb6..5ec56ed836 100644--- a/jarvis/terminal/pty_manager.py+++ b/jarvis/terminal/pty_manager.py@@ -36,7 +36,7 @@ ClosedCallback = Callable[[str, int], Awaitable[None]]@dataclass(slots=True)class PtySession:- """Haelt State fuer eine laufende PTY-Session."""+ """Holds state for a running PTY session."""terminal_id: strshell_id: str@@ -47,7 +47,7 @@ class PtySession:class PtyManager:- """Pool aller aktiven PTY-Sessions des Web-Servers."""+ """Pool of all active PTY sessions of the web server."""def __init__(self) -> None:self._sessions: dict[str, PtySession] = {}@@ -115,7 +115,7 @@ class PtyManager:reader_thread.start()logger.info(- "PTY gespawned",+ "PTY spawned",terminal_id=terminal_id,shell=shell_id,pid=pid,@@ -125,7 +125,7 @@ class PtyManager:return sessiondef write(self, terminal_id: str, data: str) -> bool:- """Schreibt Bytes an die PTY. Liefert False wenn Session unbekannt."""+ """Writes bytes to the PTY. Returns False if the session is unknown."""session = self._get(terminal_id)if session is None:return False@@ -133,7 +133,7 @@ class PtyManager:session.proc.write(data)return Trueexcept Exception as exc: # noqa: BLE001- logger.warning("PTY-Write fehlgeschlagen", terminal_id=terminal_id, error=str(exc))+ logger.warning("PTY write failed", terminal_id=terminal_id, error=str(exc))return Falsedef resize(self, terminal_id: str, cols: int, rows: int) -> bool:@@ -144,7 +144,7 @@ class PtyManager:session.proc.setwinsize(rows, cols)return Trueexcept Exception as exc: # noqa: BLE001- logger.warning("PTY-Resize fehlgeschlagen", terminal_id=terminal_id, error=str(exc))+ logger.warning("PTY resize failed", terminal_id=terminal_id, error=str(exc))return Falsedef close(self, terminal_id: str) -> bool:@@ -166,7 +166,7 @@ class PtyManager:return self._get(terminal_id) is not None# ------------------------------------------------------------------- # Intern+ # Internal# ------------------------------------------------------------------def _get(self, terminal_id: str) -> PtySession | None:@@ -179,8 +179,8 @@ class PtyManager:session.proc.terminate(force=True)except Exception: # noqa: BLE001, S110 - terminate is best-effort cleanuppass- # Kein join — der Reader-Thread ist Daemon und laeuft evtl. noch- # durch einen letzten read(). Das ist ok; Python-Exit cleant ihn.+ # No join — the reader thread is a daemon and may still be running+ # through one last read(). That's fine; Python exit cleans it up.def _reader_loop(self,@@ -202,7 +202,7 @@ class PtyManager:except Exception as exc: # noqa: BLE001# Process closed / pipe broken — normal end of life.logger.debug(- "PTY-Read Exception (Prozess vermutlich tot)",+ "PTY read exception (process presumably dead)",terminal_id=terminal_id,error=str(exc),)@@ -219,12 +219,12 @@ class PtyManager:else:text = str(data)- # Callback in den asyncio-Loop dispatchen+ # Dispatch the callback into the asyncio loopfut = asyncio.run_coroutine_threadsafe(on_output(terminal_id, text), loop)- # Wir warten NICHT auf das Future — der Reader darf den- # Producer nicht throttlen. Das Future wird GC'd.+ # We do NOT wait for the future — the reader must not+ # throttle the producer. The future gets garbage-collected.del futfinally:try:@@ -236,10 +236,10 @@ class PtyManager:on_closed(terminal_id, exit_code), loop)except RuntimeError:- # Loop ist bereits geschlossen — Server-Shutdown+ # Loop is already closed — server shutdownpasslogger.info(- "PTY-Reader beendet",+ "PTY reader terminated",terminal_id=terminal_id,exit_code=exit_code,)diff --git a/jarvis/terminal/shells.py b/jarvis/terminal/shells.pyindex be2b0fd574..91e3290c72 100644--- a/jarvis/terminal/shells.py+++ b/jarvis/terminal/shells.py@@ -18,19 +18,19 @@ from jarvis.platform import detect_platform@dataclass(frozen=True, slots=True)class ShellInfo:- """Beschreibt eine gefundene Shell-Installation."""+ """Describes one discovered shell installation."""- id: str # stabiler Key ("pwsh", "powershell", "cmd", "bash")- label: str # User-facing Label fuer das Dropdown- argv: tuple[str, ...] # vollstaendige argv-Liste fuer spawn+ id: str # stable key ("pwsh", "powershell", "cmd", "bash")+ label: str # user-facing label for the dropdown+ argv: tuple[str, ...] # full argv list for spawndef _powershell_7() -> ShellInfo | None:- # pwsh.exe auf PATH (Standard-Install von PowerShell 7+)+ # pwsh.exe on PATH (default install of PowerShell 7+)found = shutil.which("pwsh")if found:return ShellInfo(id="pwsh", label="PowerShell 7", argv=(found, "-NoLogo"))- # Fallback: bekannter Install-Pfad+ # Fallback: known install pathcandidate = os.path.expandvars(r"%ProgramFiles%\PowerShell\7\pwsh.exe")if os.path.isfile(candidate):return ShellInfo(id="pwsh", label="PowerShell 7", argv=(candidate, "-NoLogo"))@@ -65,7 +65,7 @@ def _git_bash() -> ShellInfo | None:]for cand in candidates:if os.path.isfile(cand):- # -i = interactive, -l = login (laedt .bashrc/.profile)+ # -i = interactive, -l = login (loads .bashrc/.profile)return ShellInfo(id="bash", label="Git Bash", argv=(cand, "-i", "-l"))found = shutil.which("bash")if found and "git" in found.lower():@@ -141,7 +141,7 @@ def discover_shells() -> list[ShellInfo]:def get_shell(shell_id: str) -> ShellInfo | None:- """Sucht eine Shell per ID — None wenn nicht installiert."""+ """Looks up a shell by ID — None if not installed."""for shell in discover_shells():if shell.id == shell_id:return shelldiff --git a/jarvis/ui/desktop_app.py b/jarvis/ui/desktop_app.pyindex d34d8442bd..f906a7bf4e 100644--- a/jarvis/ui/desktop_app.py+++ b/jarvis/ui/desktop_app.py@@ -1,12 +1,12 @@-"""Desktop-App-Wrapper: pywebview-Fenster + FastAPI-Backend-Lifecycle.+"""Desktop app wrapper: pywebview window + FastAPI backend lifecycle.-Koordiniert:- 1. Single-Instance-Lock (filelock + PID-Sidecar + Stale-Detection).- 2. FastAPI/uvicorn-Backend in eigenem Thread mit eigenem asyncio-Loop.- 3. pywebview-Fenster im Main-Thread (WebView2 ist STA-COM-gebunden).- 4. Session-Token-Injection (ENV fürs Backend, JS-Eval fürs Frontend).+Coordinates:+ 1. Single-instance lock (filelock + PID sidecar + stale detection).+ 2. FastAPI/uvicorn backend in its own thread with its own asyncio loop.+ 3. pywebview window on the main thread (WebView2 is STA-COM-bound).+ 4. Session token injection (ENV for the backend, JS eval for the frontend).-CLI-Testlauf ohne ``jarvis.__main__``::+CLI test run without ``jarvis.__main__``::python -m jarvis.ui.desktop_app"""@@ -25,7 +25,7 @@ from contextlib import suppressfrom pathlib import Pathfrom typing import TYPE_CHECKING, Any-# Windows-UTF8-Fix (analog zu jarvis.__main__)+# Windows UTF-8 fix (analogous to jarvis.__main__)if sys.platform == "win32":try:sys.stdout.reconfigure(encoding="utf-8", errors="replace") # type: ignore[union-attr]@@ -48,16 +48,16 @@ if TYPE_CHECKING:# ----------------------------------------------------------------------------# Konstanten+# Constants# ---------------------------------------------------------------------------LOCK_FILE_PATH = DATA_DIR / "jarvis.lock"META_FILE_PATH = DATA_DIR / ".jarvis-running"WINDOW_TITLE = "Personal Jarvis"-#: Timeout fuer den initialen Lock-Acquire in Sekunden. 0 = non-blocking,-#: so sehen wir einen laufenden Prozess sofort und fokussieren ihn statt-#: still zu warten.+#: Timeout for the initial lock acquire, in seconds. 0 = non-blocking,+#: so we detect a running process immediately and focus it instead of+#: waiting silently._LOCK_ACQUIRE_TIMEOUT = 0.0@@ -67,7 +67,7 @@ _LOCK_ACQUIRE_TIMEOUT = 0.0class SingleInstanceError(RuntimeError):- """Wird geworfen wenn eine weitere Jarvis-Instanz aktiv laeuft."""+ """Raised when another Jarvis instance is already running."""# ---------------------------------------------------------------------------@@ -79,19 +79,19 @@ _DESKTOP_LOG_SINK_INSTALLED = Falsedef _install_desktop_log_sink(log_path: Path) -> None:- """Installiert einen Loguru-File-Sink fuer die Desktop-App.+ """Installs a loguru file sink for the desktop app.- Warum: ``pythonw.exe`` (Windowed-Mode, via ``run.bat`` ohne Args) hat- keinen stderr. Loguru schreibt default nach stderr → jeder Crash im- Backend-Thread bleibt unsichtbar, der Prozess wird zum Zombie (Port nicht- gebunden, Fenster nicht offen, User sieht Nichts).+ Why: ``pythonw.exe`` (windowed mode, via ``run.bat`` without args) has+ no stderr. Loguru writes to stderr by default → any crash in the+ backend thread stays invisible, and the process becomes a zombie (port+ not bound, window not open, user sees nothing).- Dieser Sink schreibt alle ``INFO+``-Events in eine rotierende Log-Datei,- und das stdlib-``logging`` wird via ``InterceptHandler`` umgeleitet damit- auch ``uvicorn`` / ``httpx`` / ``faster_whisper`` mitgeschrieben werden.+ This sink writes every ``INFO+`` event to a rotating log file, and+ stdlib ``logging`` is redirected via ``InterceptHandler`` so that+ ``uvicorn`` / ``httpx`` / ``faster_whisper`` get captured too.- Idempotent — mehrfacher Aufruf ist no-op (wichtig falls DesktopApp in- Tests mehrfach instanziiert wird).+ Idempotent — calling it more than once is a no-op (important in case+ DesktopApp gets instantiated multiple times in tests)."""global _DESKTOP_LOG_SINK_INSTALLEDif _DESKTOP_LOG_SINK_INSTALLED:@@ -101,7 +101,7 @@ def _install_desktop_log_sink(log_path: Path) -> None:from loguru import loggerlog_path.parent.mkdir(parents=True, exist_ok=True)- # Rotation bei 10 MB, max 3 Dateien — verhindert dass Logs die Platte fressen.+ # Rotate at 10 MB, max 3 files — keeps logs from eating the disk.logger.add(str(log_path),level="INFO",@@ -113,13 +113,13 @@ def _install_desktop_log_sink(log_path: Path) -> None:# desktop/sandbox contexts before the window is created.enqueue=False,backtrace=True,- diagnose=False, # keine locals ausgeben (Secrets!)+ diagnose=False, # don't dump locals (secrets!)format="{time:YYYY-MM-DD HH:mm:ss.SSS} | {level: <8} | {name}:{function}:{line} | {message}",)- # stdlib-logging -> Loguru umleiten, damit uvicorn / httpx / faster_whisper- # auch im File-Log landen. Vorherige Handler nicht entfernen (Watchdog-Run- # hat eigene Handler via _setup_logging).+ # Redirect stdlib logging -> loguru so uvicorn / httpx / faster_whisper+ # also end up in the file log. Don't remove prior handlers (the+ # watchdog run has its own handlers via _setup_logging).import logging as _loggingclass _InterceptHandler(_logging.Handler):@@ -137,13 +137,13 @@ def _install_desktop_log_sink(log_path: Path) -> None:)root = _logging.getLogger()- # Nur hinzufuegen wenn nicht bereits ein InterceptHandler da ist.+ # Only add it if there isn't already an InterceptHandler present.if not any(isinstance(h, _InterceptHandler) for h in root.handlers):root.addHandler(_InterceptHandler())if root.level > _logging.INFO or root.level == 0:root.setLevel(_logging.INFO)- logger.info("Desktop-Log-Sink aktiv: {}", log_path)+ logger.info("Desktop log sink active: {}", log_path)# ---------------------------------------------------------------------------@@ -152,23 +152,23 @@ def _install_desktop_log_sink(log_path: Path) -> None:def _generate_session_token() -> str:- """Kryptographisch zufaelliges URL-safe Token fuer die WebView-Auth."""+ """Cryptographically random URL-safe token for the WebView auth."""return secrets.token_urlsafe(32)def _pid_alive(pid: int) -> bool:- """True wenn der PID gerade einen laufenden Prozess bezeichnet.+ """True if the PID currently denotes a running process.- Nutzt psutil (aus Phase-0-Deps). Stolperfalle: ein frisch beendeter PID- kann von einem ganz anderen Prozess belegt werden — unwahrscheinlich bei- der kurzen Lebenszeit von Jarvis, aber wir prueften den process-name- zusaetzlich, falls psutil hilft.+ Uses psutil (from the Phase-0 deps). Gotcha: a freshly terminated PID+ can get reused by a completely different process — unlikely given+ Jarvis's short process lifetime, but we'd additionally check the+ process name if psutil helps with that."""try:import psutil # type: ignore[import-not-found]except Exception: # noqa: BLE001- # Ohne psutil koennen wir keine Stale-Detection. Sicher-Default:- # Prozess gilt als lebendig, Lock bleibt belegt.+ # Without psutil we can't do stale detection. Safe default:+ # treat the process as alive, keep the lock held.return Truetry:return psutil.pid_exists(int(pid))@@ -192,13 +192,13 @@ def _write_meta(port: int, pid: int) -> None:try:from loguru import logger- logger.warning("Konnte Jarvis-Meta-Sidecar nicht schreiben: {}", exc)+ logger.warning("Could not write Jarvis meta sidecar: {}", exc)except Exception:passdef _read_meta() -> dict[str, Any] | None:- """Liest das PID-Sidecar. ``None`` wenn fehlend oder korrupt."""+ """Reads the PID sidecar. ``None`` if missing or corrupt."""try:raw = META_FILE_PATH.read_text(encoding="utf-8")except FileNotFoundError:@@ -215,11 +215,11 @@ def _read_meta() -> dict[str, Any] | None:def _focus_existing_instance() -> bool:- """Bittet die laufende Instanz ihr Fenster nach vorne zu bringen.+ """Asks the running instance to bring its window to the front.- Liest Port aus Meta-Sidecar und POSTet auf ``/api/window/focus``. Der- Endpunkt kann in Phase 1a noch 404 zurueckgeben — dann geben wir ein- freundliches False zurueck statt zu crashen.+ Reads the port from the meta sidecar and POSTs to ``/api/window/focus``.+ The endpoint can still return 404 in Phase 1a — in that case we return+ a friendly False instead of crashing."""meta = _read_meta()if not meta or "port" not in meta:@@ -237,7 +237,7 @@ def _focus_existing_instance() -> bool:def focus_existing_instance_robust() -> bool:- """Aktiviert eine laufende Instanz auch wenn das Sidecar fehlt."""+ """Activates a running instance even if the sidecar is missing."""meta = _read_meta()ports: list[int] = []if meta and isinstance(meta.get("port"), int):@@ -280,12 +280,12 @@ def focus_existing_instance_robust() -> bool:def _bring_window_to_front_by_title(title: str) -> bool:- """Win32-Fallback fuer versteckte/minimierte pywebview-Fenster.+ """Win32 fallback for hidden/minimized pywebview windows.- pywebview reicht ``window.show() + restore()`` nicht zuverlaessig durch wenn- das Fenster vorher per Tray-Close versteckt wurde — Edge/WebView2 haelt den- HWND minimiert. ``ShowWindow(SW_RESTORE) + SetForegroundWindow`` ueber den- Win32-API-Pfad ist die einzig verlaessliche Recovery.+ pywebview does not reliably pass through ``window.show() + restore()``+ when the window was previously hidden via a tray close — Edge/WebView2+ keeps the HWND minimized. ``ShowWindow(SW_RESTORE) + SetForegroundWindow``+ via the Win32 API path is the only reliable recovery."""if sys.platform != "win32":return False@@ -318,13 +318,14 @@ def _bring_window_to_front_by_title(title: str) -> bool:rect = wintypes.RECT()user32.GetWindowRect(hwnd, ctypes.byref(rect))- # Windows parkt minimierte Fenster bei -32000/-32000. Aus diesem- # Zustand zeigt die Taskbar zwar eine Vorschau, bringt die WebView aber- # nicht immer sichtbar zurueck. Dann explizit auf den Hauptmonitor.+ # Windows parks minimized windows at -32000/-32000. From that state+ # the taskbar does show a preview, but doesn't always bring the+ # WebView back visibly. In that case, explicitly move to the main+ # monitor.offscreen_minimized = rect.left <= -30000 or rect.top <= -30000- # Reihenfolge ist wichtig: erst SHOW/RESTORE, dann bei Bedarf bewegen,- # dann Foreground+Active fuer Tastatur-Fokus.+ # Order matters: SHOW/RESTORE first, then move if needed, then+ # Foreground+Active for keyboard focus.user32.ShowWindow(hwnd, 1) # SW_SHOWNORMALuser32.ShowWindow(hwnd, 5) # SW_SHOWuser32.ShowWindow(hwnd, 9) # SW_RESTORE@@ -343,15 +344,15 @@ def _bring_window_to_front_by_title(title: str) -> bool:def _is_brain_diagnostic(text: str) -> bool:- """True fuer Backend-Diagnosen, die nicht als Jarvis-Antwort gelten."""+ """True for backend diagnostics that don't count as a Jarvis reply."""t = text.lower()return (- t.startswith("kein brain-key gefunden")- or t.startswith("keine brain-provider")- or t.startswith("brain nicht verfuegbar")- or t.startswith("brain-fehler")+ t.startswith("kein brain-key gefunden") # i18n-allow: matches German diagnostic text produced by jarvis/brain/manager.py+ or t.startswith("keine brain-provider") # i18n-allow: matches German diagnostic text produced by jarvis/brain/manager.py+ or t.startswith("brain nicht verfuegbar") # i18n-allow: matches German diagnostic text produced by jarvis/brain/manager.py+ or t.startswith("brain-fehler") # i18n-allow: matches German diagnostic text produced by jarvis/brain/manager.pyor "api-key" in t- or ("provider" in t and ("unerreichbar" in t or "nicht verfuegbar" in t))+ or ("provider" in t and ("unerreichbar" in t or "nicht verfuegbar" in t)) # i18n-allow: matches German diagnostic text produced by jarvis/brain/manager.py)@@ -465,11 +466,11 @@ def acquire_single_instance_lock(health_probe: Callable[[int], bool] | None = None,terminate: Callable[[int], bool] | None = None,) -> FileLock:- """Acquire exklusives Lock oder raise :class:`SingleInstanceError`.+ """Acquire the exclusive lock or raise :class:`SingleInstanceError`.- Stale-Lock-Erkennung: wenn das Lock belegt ist, lesen wir das- PID-Sidecar und pruefen ``psutil.pid_exists(pid)``. Ist der PID tot,- loeschen wir Lock + Sidecar und versuchen erneut.+ Stale-lock detection: when the lock is held, we read the PID sidecar+ and check ``psutil.pid_exists(pid)``. If the PID is dead, we delete+ the lock + sidecar and try again.Lock-zombie eviction (forensic 2026-06-26): a holder PID can be ALIVE yetnon-functional — its webserver accept-socket died on a transient WinError 64@@ -480,11 +481,11 @@ def acquire_single_instance_lock(reclaim the lock. Never the own pid (no suicide); never a healthy holder.Args:- timeout: Sekunden bis wir den ersten Acquire aufgeben. Default 0.0.- lock_path: Override fuer Tests.- meta_path: Override fuer Tests.- health_probe: Override fuer Tests — ``(port) -> bool`` health check.- terminate: Override fuer Tests — ``(pid) -> bool`` process kill.+ timeout: Seconds until we give up on the first acquire. Default 0.0.+ lock_path: Override for tests.+ meta_path: Override for tests.+ health_probe: Override for tests — ``(port) -> bool`` health check.+ terminate: Override for tests — ``(pid) -> bool`` process kill."""lp = lock_path or LOCK_FILE_PATHmp = meta_path or META_FILE_PATH@@ -499,7 +500,7 @@ def acquire_single_instance_lock(except Timeout:pass- # Besetzt — ist der Halter noch am Leben?+ # Held — is the holder still alive?meta: dict[str, Any] | None = Nonetry:raw = mp.read_text(encoding="utf-8")@@ -516,29 +517,30 @@ def acquire_single_instance_lock(# healthy instance, the own pid, or a holder with no recorded port is# respected; only a live-but-non-serving lock-zombie is evicted.if pid == os.getpid() or port is None or probe(port):- raise SingleInstanceError(f"Jarvis laeuft bereits (pid={pid}).")+ raise SingleInstanceError(f"Jarvis is already running (pid={pid}).")with suppress(Exception):from loguru import loggerlogger.warning(- "Jarvis-Lock von einer LEBENDEN, aber nicht-reagierenden Instanz "- "belegt (pid={}, port={} antwortet nicht) — Lock-Zombie wird "- "beendet, damit dieser Start durchkommt.",+ "Jarvis lock held by a LIVE but non-responding instance "+ "(pid={}, port={} not responding) — terminating the lock "+ "zombie so this start can proceed.",pid,port,)if not killer(pid):raise SingleInstanceError(- f"Jarvis-Lock von nicht-reagierender Instanz (pid={pid}) belegt; "- "konnte sie nicht beenden."+ f"Jarvis lock held by a non-responding instance (pid={pid}); "+ "could not terminate it.")# fall through to the stale-reclaim path below (sidecar + retry acquire)- # Stale (toter Halter) ODER eben beendeter Zombie: Sidecar entfernen, Lock- # erneut versuchen. Das Lock-File auf Filesystem-Ebene wegzuraeumen ist nicht- # noetig — filelock nutzt fcntl/LockFileEx, d.h. sobald der Halter weg ist,- # ist das Lock frei. Nach einem Kill braucht Windows allerdings einen Moment,- # den Lock-Handle freizugeben — deshalb mehrere kurze Versuche.+ # Stale (dead holder) OR a zombie we just terminated: remove the sidecar+ # and try the lock again. There's no need to clean up the lock file at+ # the filesystem level — filelock uses fcntl/LockFileEx, so as soon as+ # the holder is gone, the lock is free. After a kill, though, Windows+ # needs a moment to release the lock handle — hence several short+ # retries.with suppress(Exception):mp.unlink(missing_ok=True)last_exc: Timeout | None = None@@ -551,7 +553,7 @@ def acquire_single_instance_lock(last_exc = excif time.monotonic() >= deadline:raise SingleInstanceError(- "Jarvis-Lock ist besetzt aber der Halter reagiert nicht."+ "Jarvis lock is held but the holder is not responding.") from last_exctime.sleep(0.3)@@ -581,15 +583,16 @@ class DesktopApp:# used for both the server's TokenAuth env (below) and the window's# _inject_token. When not injected, generate our own (classic path).self.session_token = session_token or _generate_session_token()- # ENV muss _vor_ dem Start des Backends gesetzt werden: uvicorn-Thread- # liest sie beim FastAPI-App-Build, um den TokenAuth-Guard zu prime.+ # The ENV must be set _before_ the backend starts: the uvicorn thread+ # reads it during the FastAPI app build to prime the TokenAuth guard.os.environ[self.cfg.ui.auth_token_env] = self.session_token- # KRITISCH: pythonw.exe hat kein stderr. Ohne File-Sink sehen wir KEINEN- # Crash im Backend-Thread — der Prozess lebt dann still als Zombie ohne- # gebundenen Port 47821. File-Log in data/jarvis_desktop.log schreiben,- # damit jeder Crash sichtbar ist. Idempotent: add() mit identischem sink- # würde dupliziert, deshalb ein Modul-Global-Guard.+ # CRITICAL: pythonw.exe has no stderr. Without the file sink we'd see+ # NO crash in the backend thread — the process would then live on+ # silently as a zombie with no bound port 47821. Write a file log to+ # data/jarvis_desktop.log so every crash is visible. Idempotent:+ # calling add() with an identical sink would duplicate it, hence the+ # module-global guard._install_desktop_log_sink(DATA_DIR / "jarvis_desktop.log")self._backend_thread: threading.Thread | None = None@@ -604,9 +607,9 @@ class DesktopApp:self._tray: Any = Noneself._user_requested_quit = Falseself._window_visible = False- # Voice-Stack (Pipeline + Orb-Overlay) — optional, ueber ENV- # JARVIS_VOICE=0 abschaltbar. Default an, damit "Hey Jarvis" out-of-the-box- # funktioniert wenn `run.bat` die Desktop-App startet.+ # Voice stack (pipeline + orb overlay) — optional, can be disabled via+ # ENV JARVIS_VOICE=0. Defaults to on, so "Hey Jarvis" works+ # out-of-the-box when `run.bat` starts the desktop app.self._pipeline_task: asyncio.Task | None = Noneself._orb: Any = None# Virtual mouse overlay (Computer-Use). Voice-independent — Computer-Use@@ -618,7 +621,7 @@ class DesktopApp:# visually replace the OS cursor (Windows draws it above any window).self._jarvis_cursor: Any = None- # ---- URL-Resolution ----------------------------------------------------+ # ---- URL resolution -----------------------------------------------------def _url(self) -> str:if self.cfg.ui.dev_mode:@@ -629,35 +632,35 @@ class DesktopApp:"""Return whether voice activation is allowed for the desktop UI."""return bool(self._window is not None and self._window_visible)- # ---- Backend-Thread ----------------------------------------------------+ # ---- Backend thread ------------------------------------------------------def _run_backend(self, *, prebound: tuple[Any, Any] | None = None) -> None:- """Eintrittspunkt des Backend-Threads.+ """Entry point of the backend thread.``prebound`` (fast-boot launcher path): ``(loop, bootstrap)`` alreadycreated + bound BEFORE this heavy module was imported, so the port-bindbeat the import floor. When ``None`` (classic path), this creates theloop and binds the bootstrap itself.- Erstellt einen dedizierten asyncio-Loop, startet den ``WebServer``- (``await server.start()``) und laesst den Loop ewig laufen bis- ``stop()`` via :meth:`shutdown` durchgereicht wird.-- Zusaetzlich werden hier die Phase-1a-Core-Objekte verdrahtet:- ``Supervisor`` + ``ChatStore`` + ``BrainManager`` (mit MockBrain als- Fallback). Sie haengen an ``server.app.state`` und werden ueber einen- Event-Subscriber auf ``MessageSent(role="user")`` aktiviert, damit- Chat End-to-End funktioniert ohne Polling.-- Seit 2026-04-21: Text-Chat nutzt denselben BrainManager wie die- Voice-Pipeline (Shared-Bus + Shared-History). Default-Provider ist- ``gemini`` aus ``jarvis.toml`` — umgeht das 429-Problem der- direkten OAuth-API-Calls.-- Seit 2026-04-25: KEIN MockBrain-Fallback mehr im Chat-Pfad. Wenn- ``build_default_brain()`` fehlschlaegt, bleibt ``brain = None`` und- der Chat antwortet mit einer ehrlichen Setup-Anweisung statt mit- scripted Standard-Phrasen. User-Wunsch: kein "dummer Jarvis" ohne LLM.+ Creates a dedicated asyncio loop, starts the ``WebServer``+ (``await server.start()``), and keeps the loop running forever+ until ``stop()`` is passed through via :meth:`shutdown`.++ This is also where the Phase-1a core objects get wired up:+ ``Supervisor`` + ``ChatStore`` + ``BrainManager`` (with MockBrain as+ a fallback). They hang off ``server.app.state`` and are activated+ via an event subscriber on ``MessageSent(role="user")``, so chat+ works end-to-end without polling.++ Since 2026-04-21: text chat uses the same BrainManager as the voice+ pipeline (shared bus + shared history). The default provider is+ ``gemini`` from ``jarvis.toml`` — this sidesteps the 429 problem of+ direct OAuth API calls.++ Since 2026-04-25: NO MORE MockBrain fallback in the chat path. If+ ``build_default_brain()`` fails, ``brain`` stays ``None`` and chat+ replies with an honest setup instruction instead of scripted+ canned phrases. User request: no "dumb Jarvis" without an LLM."""# NOTE: the heavy imports (build_default_brain → the brain graph,# WebServer → fastapi + every route schema, etc.) are DELIBERATELY NOT@@ -815,7 +818,7 @@ class DesktopApp:self._server = server_db_mark("webserver_ctor")- # Core-State in den Loop haengen — thread-lokal, nur hier referenziert.+ # Hang the core state off the loop — thread-local, referenced only here.supervisor = Supervisor(bus=server.bus)# Persist text chats to data/chats.db (next to sessions.db) so the Chats# conversation manager has durable, segmented history across restarts.@@ -852,13 +855,13 @@ class DesktopApp:"Latency log writer init failed — continuing without JSONL log.",)- # Frontier-Auto-Switch (Phase F.3, 2026-04-29). Hier VOR- # ``build_default_brain``, sonst zieht der Brain die alte- # jarvis.toml und der Switch wuerde erst beim naechsten Restart wirken.- # ``apply_frontier_resolution`` patcht die TOML auf Disk +- # mutiert ``self.cfg`` — der direkt darauf folgende Brain-Build- # liest dann die Frontier-Werte. STALE_MODELS-Filter im Resolver- # verhindert Downgrades wenn die API-Liste stale-IDs enthaelt.+ # Frontier auto-switch (Phase F.3, 2026-04-29). This runs BEFORE+ # ``build_default_brain``, otherwise the brain would pick up the old+ # jarvis.toml and the switch would only take effect on the next+ # restart. ``apply_frontier_resolution`` patches the TOML on disk ++ # mutates ``self.cfg`` — the brain build right after this then reads+ # the frontier values. The resolver's STALE_MODELS filter prevents+ # downgrades when the API list contains stale IDs.try:from jarvis.brain.frontier_autoswitch import apply_frontier_resolutionfrom jarvis.brain.frontier_resolver import FrontierResolver@@ -874,31 +877,32 @@ class DesktopApp:from loguru import logger as _flogif switches:_flog.info(- "Frontier-Autoswitch: {} Modell(e) auf Frontier gehoben.",+ "Frontier autoswitch: {} model(s) raised to frontier.",len(switches),)else:- _flog.info("Frontier-Autoswitch: TOML bereits Frontier-konform.")- except Exception as exc: # noqa: BLE001 — Resolver-Fail darf den Boot nicht stoppen.+ _flog.info("Frontier autoswitch: TOML already frontier-compliant.")+ except Exception as exc: # noqa: BLE001 — a resolver failure must not stop boot.from loguru import logger as _flog_flog.opt(exception=exc).warning(- "Frontier-Autoswitch fehlgeschlagen — TOML-Defaults bleiben.",+ "Frontier autoswitch failed — keeping TOML defaults.",)server.app.state.supervisor = supervisorserver.app.state.chat_store = chat_storeserver.app.state.brain = None- # shell wird erst in run() gesetzt (nach webview.create_window);- # _focus_handler holt sich den Wert dynamisch.+ # shell only gets set in run() (after webview.create_window);+ # _focus_handler fetches the value dynamically.server.app.state.shell = Noneserver.app.state.desktop_app = self# Local desktop run: the user IS at this machine, so reveal/open-with-# default-app target their own desktop. Enable the native file actions.server.app.state.native_file_actions = True- # BrainManager auf demselben Bus wie das UI — aber nicht mehr auf der- # sichtbaren Startstrecke. Der Webserver soll zuerst /api/health bedienen;- # erste Chat-/Drop-Interaktionen warten bounded auf den Hintergrund-Build.+ # BrainManager on the same bus as the UI — but no longer on the+ # visible startup path. The web server should serve /api/health+ # first; the first chat/drop interactions wait, bounded, on the+ # background build.brain_holder: dict[str, Any] = {"brain": None, "error": None}brain_ready = asyncio.Event()@@ -912,20 +916,20 @@ class DesktopApp:)from loguru import logger as _bootlog_bootlog.info(- "Welle-4 Y bootstrap: Brain.set_mission_command_handlers "- "verdrahtet (status/cancel via MissionManager)."+ "Wave-4 Y bootstrap: Brain.set_mission_command_handlers "+ "wired up (status/cancel via MissionManager).")except AttributeError:from loguru import logger as _bootlog_bootlog.warning(- "MissionManager fehlt openclaw_status/-_cancel — Status-/Cancel-"- "Voice-Patterns fallen auf den normalen Spawn-Pfad zurueck."+ "MissionManager is missing openclaw_status/-_cancel — status/"+ "cancel voice patterns fall back to the normal spawn path.")except Exception as exc: # noqa: BLE001from loguru import logger as _bootlog_bootlog.opt(exception=exc).warning(- "Welle-4 Y bootstrap fehlgeschlagen — "- "Status/Cancel-Handler bleiben unverdrahtet."+ "Wave-4 Y bootstrap failed — "+ "status/cancel handlers stay unwired.")try:@@ -936,7 +940,7 @@ class DesktopApp:except Exception as exc: # noqa: BLE001from loguru import logger as _bootlog_bootlog.opt(exception=exc).warning(- "WorkflowRunner.attach_brain nach Deferred-Build fehlgeschlagen."+ "WorkflowRunner.attach_brain failed after the deferred build.")try:@@ -950,7 +954,7 @@ class DesktopApp:except Exception as exc: # noqa: BLE001from loguru import logger as _bootlog_bootlog.opt(exception=exc).warning(- "TaskRunner-Brain-Wiring nach Deferred-Build fehlgeschlagen."+ "TaskRunner brain wiring failed after the deferred build.")async def _build_brain_bg() -> None:@@ -962,7 +966,7 @@ class DesktopApp:server.app.state.brain = builtfrom loguru import loggerlogger.info(- "Text-Chat-Brain: {} aktiv (geteilt mit Voice-Pipeline).",+ "Text-chat brain: {} active (shared with the voice pipeline).",getattr(built, "active_provider", "unknown"),)_wire_ready_brain(built)@@ -983,7 +987,7 @@ class DesktopApp:from loguru import loggerbrain_holder["error"] = f"{type(exc).__name__}: {exc}"logger.opt(exception=exc).error(- "BrainManager-Build fehlgeschlagen — Chat antwortet mit Setup-Hinweis."+ "BrainManager build failed — chat replies with a setup hint.")finally:brain_ready.set()@@ -1097,16 +1101,16 @@ class DesktopApp:yield chunkasync def _on_user_message(evt: MessageSent) -> None:- """Brain-Dispatcher: jedes user-turned MessageSent triggert generate.+ """Brain dispatcher: every user-authored MessageSent triggers generate.- **Wichtig**: Wir filtern source_layer="chat" raus, weil- ChatStore beim Persistieren ein MessageSent publisht.- Ohne Filter waere das eine Infinite-Loop.+ **Important**: we filter out source_layer="chat", because+ ChatStore publishes a MessageSent when it persists a message.+ Without that filter this would be an infinite loop.- Brain-API: ``async (text) -> str`` Callable. Wir machen- State-Transitions + Store-Write hier explizit. Wenn ``brain``- None ist (Build-Fehler), liefern wir eine ehrliche Setup-Message- — KEIN scripted Mock-Reply.+ Brain API: an ``async (text) -> str`` callable. We do the+ state transitions + store write explicitly here. When ``brain``+ is None (build failure), we return an honest setup message+ — NOT a scripted mock reply."""if evt.role != "user":return@@ -1153,11 +1157,11 @@ class DesktopApp:except Exception as exc: # noqa: BLE001# The pre-brain hook is defensive — a crash here must never# block the chat path. Fall through to the brain.- logger.opt(exception=exc).debug("Skill-Pre-Hook (chat) skipped")+ logger.opt(exception=exc).debug("Skill pre-hook (chat) skipped")if brain is None:- # Build-Fehler-Pfad: Systemfehler statt Jarvis-Antwort.- detail = brain_holder["error"] or "BrainManager nicht initialisiert"+ # Build-failure path: a system error instead of a Jarvis reply.+ detail = brain_holder["error"] or "BrainManager not initialized"message = f"Brain unavailable: {detail}"await server.bus.publish(ErrorOccurred(@@ -1303,10 +1307,10 @@ class DesktopApp:server.bus.subscribe(ShowWindowRequested, self._on_show_window_requested)self._install_focus_route(server)- # Workflow-System (Phase 6) — Store + Runner + Scheduler. Eigene- # DB-Datei (``workflows.sqlite``) neben der Memory-DB, damit- # Schema-Migrations hier unabhaengig moeglich sind. Failure ist nicht- # fatal: dann bleibt die Workflows-View leer (503 auf API-Calls).+ # Workflow system (Phase 6) — store + runner + scheduler. Its own+ # DB file (``workflows.sqlite``) next to the memory DB, so schema+ # migrations here can happen independently. Failure is not fatal:+ # the workflows view just stays empty (503 on API calls).try:from jarvis.workflows import (WorkflowRunner,@@ -1319,7 +1323,7 @@ class DesktopApp:store=workflow_store,bus=server.bus,brain=None,- tool_registry=None, # wird spaeter per attach_tools gesetzt+ tool_registry=None, # set later via attach_toolstool_executor=None,)workflow_scheduler = WorkflowScheduler(@@ -1335,7 +1339,7 @@ class DesktopApp:except Exception as exc: # noqa: BLE001from loguru import loggerlogger.opt(exception=exc).warning(- "Workflow-System nicht startbar — Workflows-View bleibt leer."+ "Workflow system could not start — the workflows view stays empty.")server.app.state.workflow_store = Noneserver.app.state.workflow_runner = None@@ -1343,9 +1347,9 @@ class DesktopApp:self._workflow_store = Noneself._workflow_scheduler = None- # MCP-Registry + Tool-Registry aufsetzen: Bootstrap-Specs + Overrides- # aus mcp.json. Enabled-Server werden nach server.start() im- # Hintergrund gestartet, deren Tools in die tool_registry eingetragen.+ # Set up the MCP registry + tool registry: bootstrap specs + overrides+ # from mcp.json. Enabled servers get started in the background after+ # server.start(), and their tools get registered into the tool_registry.mcp_registry = MCPRegistry()mcp_registry.load_from_mcp_json()server.app.state.mcp_registry = mcp_registry@@ -1415,9 +1419,9 @@ class DesktopApp:"BrainToolsChanged publish failed after MCP autostart",)- # Conductor (OSS-Tool im selben Monorepo) — eigene Store+Runner+- # Scheduler, Port-less, teilt sich nur den Jarvis-Event-Loop und- # Jarvis' FastAPI-Server als Embed-Host.+ # Conductor (an OSS tool in the same monorepo) — its own store ++ # runner + scheduler, port-less, only shares the Jarvis event loop+ # and Jarvis's FastAPI server as its embed host.try:from conductor import ConductorStore as _CStorefrom conductor import Runner as _CRunner@@ -1434,7 +1438,7 @@ class DesktopApp:except Exception as exc: # noqa: BLE001from loguru import loggerlogger.opt(exception=exc).warning(- "Conductor-Setup fehlgeschlagen — Conductor-View bleibt leer."+ "Conductor setup failed — the Conductor view stays empty.")server.app.state.conductor_store = Noneserver.app.state.conductor_runner = None@@ -1443,7 +1447,7 @@ class DesktopApp:self._conductor_scheduler = Noneasync def _bootstrap_conductor() -> None:- """Conductor-Store init + Seed-Jobs + Scheduler-Start."""+ """Conductor store init + seed jobs + scheduler start."""from loguru import logger as _loggerstore = server.app.state.conductor_storescheduler = server.app.state.conductor_scheduler@@ -1454,22 +1458,22 @@ class DesktopApp:await store.cleanup_interrupted_runs()from conductor import ensure_seed_jobsadded = await ensure_seed_jobs(store)- _logger.info("Conductor-Store ready ({} Seed-Jobs neu).", added)+ _logger.info("Conductor store ready ({} new seed job(s)).", added)if scheduler is not None:scheduler.start()- _logger.info("Conductor-Scheduler gestartet.")+ _logger.info("Conductor scheduler started.")except Exception as exc: # noqa: BLE001_logger.opt(exception=exc).warning(- "Conductor-Bootstrap fehlgeschlagen"+ "Conductor bootstrap failed")async def _bootstrap_workflows() -> None:- """Store-Init + Seed-Workflows + Scheduler-Start.+ """Store init + seed workflows + scheduler start.- Fire-and-Forget aus dem Backend-Loop — Fehler werden geloggt aber- nicht propagiert, damit die restliche App startet. Ohne Brain-- Callable laeuft der Scheduler trotzdem (nur brain_prompt-Steps- wuerden beim Run fehlschlagen).+ Fire-and-forget from the backend loop — errors are logged but+ not propagated, so the rest of the app still boots. Without a+ brain callable, the scheduler still runs (only brain_prompt+ steps would fail during a run)."""from loguru import logger as _logger@@ -1482,19 +1486,19 @@ class DesktopApp:await store.cleanup_interrupted_runs()from jarvis.workflows import ensure_seed_workflowsadded = await ensure_seed_workflows(store)- _logger.info("Workflow-Store ready ({} Seed-Workflows neu).",+ _logger.info("Workflow store ready ({} new seed workflow(s)).",added)- # Tool-Registry-Attach wuerde ``tool_call``-Steps aktivieren,- # erfordert aber einen ToolExecutor-Adapter mit Risk-Tier-- # Integration. MVP: wir lassen den Runner ohne Tools laufen —- # die Seed-Workflows nutzen brain_prompt/harness_dispatch/speak,- # dafuer braucht er keinen ToolExecutor.+ # Attaching the tool registry would activate ``tool_call``+ # steps, but that requires a ToolExecutor adapter with+ # risk-tier integration. MVP: we run the runner without+ # tools — the seed workflows use brain_prompt/harness_dispatch/+ # speak, which don't need a ToolExecutor.if scheduler is not None:scheduler.start()- _logger.info("Workflow-Scheduler gestartet.")+ _logger.info("Workflow scheduler started.")except Exception as exc: # noqa: BLE001_logger.opt(exception=exc).warning(- "Workflow-Bootstrap fehlgeschlagen",+ "Workflow bootstrap failed",)try:@@ -1513,7 +1517,7 @@ class DesktopApp:# backend, so it must not wait ~15-20 s for subsystems it never uses.async def _start_overlay_bg() -> None:try:- # Phase 9.8: Overlay-Subprocess starten wenn [overlay].enabled=true.+ # Phase 9.8: start the overlay subprocess when [overlay].enabled=true.# Optional package: when it is not installed, desktop boot still serves.from jarvis.overlay.integration import start_overlay@@ -1522,16 +1526,16 @@ class DesktopApp:from loguru import logger as _overlay_loggerif exc.name == "overlay":_overlay_logger.debug(- "Overlay-Bootstrap skipped: optional overlay package not installed."+ "Overlay bootstrap skipped: optional overlay package not installed.")else:_overlay_logger.opt(exception=exc).warning(- "Overlay-Bootstrap fehlgeschlagen."+ "Overlay bootstrap failed.")except Exception as exc: # noqa: BLE001from loguru import logger as _overlay_logger_overlay_logger.opt(exception=exc).warning(- "Overlay-Bootstrap fehlgeschlagen."+ "Overlay bootstrap failed.")def _log_speech_and_orb_done(task: asyncio.Task) -> None:@@ -1600,7 +1604,7 @@ class DesktopApp:await server.start(start_serving=False)bootstrap.set_app(server.app)_db_mark("server_start")- # Erst nach erfolgreichem start() ist der Port wirklich belegt.+ # The port is only really bound after start() succeeds._write_meta(self.cfg.ui.admin_api_port, os.getpid())except Exception as exc: # noqa: BLE001 — never kill the backend loopfrom loguru import logger as _slog@@ -1608,7 +1612,7 @@ class DesktopApp:"Heavy backend init (server.start) failed.")loop.create_task(_build_brain_bg(), name="brain-build")- # MCP-Autostart als Fire-and-Forget-Task — blockt Backend-Ready nicht.+ # MCP autostart as a fire-and-forget task — doesn't block backend-ready.loop.create_task(_start_enabled_mcps())loop.create_task(_bootstrap_workflows(), name="workflow-bootstrap")loop.create_task(_bootstrap_conductor(), name="conductor-bootstrap")@@ -1949,22 +1953,22 @@ class DesktopApp:brain: Any,server: Any = None,) -> None:- """Startet Orb-Overlay (Tk-Daemon-Thread) + Speech-Pipeline (Task im Loop).+ """Starts the orb overlay (Tk daemon thread) + speech pipeline (a loop task).- Fehlschlag ist nicht fatal: fehlendes Mic, keine API-Keys, geblockte- Audio-Devices — die Desktop-App laeuft ohne Voice weiter. Abschaltbar- via ENV ``JARVIS_VOICE=0``.+ Failure is not fatal: a missing mic, no API keys, blocked audio+ devices — the desktop app keeps running without voice. Can be+ disabled via ENV ``JARVIS_VOICE=0``.- Architektur entspricht ``jarvis.speech.watchdog``: selber ``bus`` +- ``supervisor``, damit ``SystemStateChanged`` vom Orb empfangen wird.+ Architecture matches ``jarvis.speech.watchdog``: same ``bus`` ++ ``supervisor``, so ``SystemStateChanged`` gets received by the orb.- ``brain`` ist die geteilte BrainManager-Instanz (oder MockBrain-Fallback)- aus ``_run_backend`` — Text-Chat und Voice teilen sich History und- Provider-State.+ ``brain`` is the shared BrainManager instance (or MockBrain fallback)+ from ``_run_backend`` — text chat and voice share history and+ provider state."""if os.environ.get("JARVIS_VOICE", "").strip().lower() in ("0", "off", "false"):from loguru import logger- logger.info("Voice-Stack per JARVIS_VOICE=0 deaktiviert.")+ logger.info("Voice stack disabled via JARVIS_VOICE=0.")return# On-screen overlay in its own Tk daemon thread — the bus bridge reacts@@ -2056,12 +2060,12 @@ class DesktopApp:from jarvis.skills.runner import SkillRunnerfrom jarvis.skills.skill_context import SkillContext, set_skill_context- # Bug-Fix 2026-05-09: NICHT eine zweite SkillRegistry erstellen.- # Der WebServer (server.py:_setup_skill_registry) hat bereits- # eine angelegt + ihren Watchdog gestartet. Eine zweite Instanz- # hier hatte einen separaten Cache, der nie reloaded wurde —- # SKILL.md-Edits wirkten dann nicht. Stattdessen: die existierende- # Registry aus app.state wiederverwenden.+ # Bug fix 2026-05-09: do NOT create a second SkillRegistry.+ # The WebServer (server.py:_setup_skill_registry) already+ # created one + started its watchdog. A second instance here+ # had a separate cache that never got reloaded — SKILL.md+ # edits then had no effect. Instead: reuse the existing+ # registry from app.state.skills_root = ensure_user_skills_dir()skill_registry = Noneif server is not None and getattr(server, "app", None) is not None:@@ -2076,12 +2080,11 @@ class DesktopApp:)skill_registry.reload_sync()- # Mini-Tool-Registry fuer den SkillRunner — laedt alle- # Plugin-Tools, die ohne Args instantiierbar sind. Tools mit- # komplexen Dependencies (dispatch-to-harness, spawn-worker)- # werden geskipped; die sind eh OpenClaw-Spezialitaet, nicht- # fuer Skill-Bodies gedacht. ``remember`` und Konsorten passen- # alle in dieses Schema.+ # Mini tool registry for the SkillRunner — loads every plugin+ # tool that can be instantiated without args. Tools with+ # complex dependencies (dispatch-to-harness, spawn-worker) are+ # skipped; those are OpenClaw specialties anyway, not meant for+ # skill bodies. ``remember`` and friends all fit this schema.from importlib.metadata import entry_points as _epsskill_tool_registry: dict[str, Any] = {}@@ -2093,7 +2096,7 @@ class DesktopApp:if _name and hasattr(_inst, "execute"):skill_tool_registry[_name] = _instexcept Exception:- continue # Tool braucht Args — fuer Skills nicht relevant.+ continue # Tool needs args — not relevant for skills.skill_runner = SkillRunner(registry=skill_registry,@@ -2105,19 +2108,19 @@ class DesktopApp:)from loguru import loggerlogger.info(- "SkillContext aktiv ({} Skills geladen aus {}).",+ "SkillContext active ({} skill(s) loaded from {}).",len(skill_registry.list()), skills_root,)except Exception as exc: # noqa: BLE001from loguru import loggerlogger.opt(exception=exc).warning(- "SkillContext-Setup fehlgeschlagen — Pipeline laeuft ohne Skill-Hook."+ "SkillContext setup failed — the pipeline runs without the skill hook.")- # Pipeline-Deps: STT, TTS — Brain wird vom Caller (Text-Chat-Setup)- # durchgereicht, damit Voice und Chat sich Provider + History teilen.- # Wenn brain ein MockBrain ist (Fallback), funktioniert Voice-TTS auch,- # aber ohne echten LLM-Output → erkennbar an scripted Replies.+ # Pipeline deps: STT, TTS — brain is passed through by the caller+ # (text-chat setup) so voice and chat share provider + history.+ # If brain is a MockBrain (fallback), voice TTS still works, but+ # without real LLM output → recognizable by its scripted replies.try:from jarvis.plugins.tts import build_tts_from_configfrom jarvis.plugins.wake.openwakeword_provider import (@@ -2227,25 +2230,27 @@ class DesktopApp:# wake-model build started above.tts = build_tts_from_config(self.cfg.tts)_t_tts = time.perf_counter()- # SpeechPipeline.brain_callback braucht Callable[[str], Awaitable[str]].- # BrainManager und Echo-/Gemini-Fallback erfüllen das via __call__.- # MockBrain erfüllt es nicht (hat nur respond()) → eigener Voice-Brain.+ # SpeechPipeline.brain_callback needs Callable[[str], Awaitable[str]].+ # BrainManager and the Echo/Gemini fallback satisfy that via __call__.+ # MockBrain does not (it only has respond()) → gets its own voice brain.voice_brain: Any = brainif not callable(voice_brain) or hasattr(voice_brain, "respond"):from loguru import loggerfrom jarvis.brain.factory import build_default_brain as _bdblogger.info(- "Shared brain ist nicht direkt callable — eigener Voice-Brain."+ "Shared brain is not directly callable — building a dedicated voice brain.")voice_brain = _bdb(tier="router")- # output_device aus Config durchreichen — sonst nutzt AudioPlayer- # System-Default und das ist auf Windows oft MME idx=3 mit- # Mono-auf-8-Channel-Routing-Bug (User hoert dann nichts).- # Permanent-Vision: der Voice-Brain (Router-Tier) haengt seinen- # VisionContextProvider an `_vision_provider`. Ohne Durchreichen- # bleibt der Background-Loop ungestartet und jeder Router-Turn- # kriegt `current()=None` → Silent-Failure (kein Bild im Prompt).+ # Pass output_device through from config — otherwise AudioPlayer+ # falls back to the system default, which on Windows is often+ # MME idx=3 with a mono-to-8-channel routing bug (the user then+ # hears nothing).+ # Permanent vision: the voice brain (router tier) hangs its+ # VisionContextProvider off `_vision_provider`. Without passing+ # it through, the background loop never starts and every+ # router turn gets `current()=None` → a silent failure (no+ # image in the prompt).voice_vision = getattr(voice_brain, "_vision_provider", None)# Pre-Thinking-Ack Flash-Brain: builds an AckGenerator if# [ack_brain].enabled = true in jarvis.toml, otherwise returns@@ -2328,10 +2333,10 @@ class DesktopApp:# "Jarvis" false-fire path without pendulumming the OWW# threshold (BUG-009).require_hey_prefix=self.cfg.trigger.require_hey_prefix,- # User-Mandat 2026-05-18: Single-Turn-pro-Wake. ``single_turn_mode``- # in jarvis.toml ist die kanonische Quelle; ``continue_listening``- # ist hier ihr negiertes Gegenstueck — wenn der User irgendwann- # wieder Konversationsmodus will, kippt er den Toml-Eintrag.+ # User mandate 2026-05-18: single turn per wake. ``single_turn_mode``+ # in jarvis.toml is the canonical source; ``continue_listening``+ # is its negated counterpart here — if the user ever wants+ # conversation mode again, they flip the TOML entry.continue_listening_after_response=(not self.cfg.trigger.single_turn_mode),@@ -2369,14 +2374,14 @@ class DesktopApp:(_t_ctor - _t_stt) * 1000.0,(_t_ctor - _t_build0) * 1000.0,)- # Pipeline-Referenz fuer Live-Provider-Switches (TTS) auf app.state- # legen — der /api/tts/switch-Endpoint baut bei einem UI-Wechsel- # einen neuen TTS-Provider und ruft pipeline.set_tts() auf, ohne- # die ganze Pipeline neu zu starten (Whisper-Reload waere teuer).- # Hinweis: ``server`` ist hier nicht im Scope (Methoden-Signatur- # nimmt nur loop/bus/supervisor/brain) — wir nutzen ``self._server``,- # das ``_run_backend`` direkt nach ``WebServer(...)``-Construction- # zuweist.+ # Put the pipeline reference for live provider switches (TTS) on+ # app.state — the /api/tts/switch endpoint builds a new TTS+ # provider on a UI change and calls pipeline.set_tts() without+ # restarting the whole pipeline (a Whisper reload would be+ # expensive). Note: ``server`` isn't in scope here (the method+ # signature only takes loop/bus/supervisor/brain) — we use+ # ``self._server``, which ``_run_backend`` assigns right after+ # the ``WebServer(...)`` construction.if self._server is not None:self._server.app.state.speech_pipeline = pipeline# App-Control: expose the live SpeechPipeline so the@@ -2393,23 +2398,23 @@ class DesktopApp:from loguru import loggerdef _on_pipeline_done(task: asyncio.Task) -> None:- # Kritisch bei pythonw.exe: ohne dieses Callback stirbt der- # Speech-Task stumm. "Task exception was never retrieved"- # kommt erst beim GC und ist im Windowed-Mode unsichtbar.+ # Critical on pythonw.exe: without this callback the speech+ # task dies silently. "Task exception was never retrieved"+ # only surfaces at GC time and is invisible in windowed mode.if task.cancelled():- logger.info("Speech-Pipeline sauber gecancelt.")+ logger.info("Speech pipeline cancelled cleanly.")returnexc = task.exception()if exc is not None:logger.opt(exception=exc).error(- "Speech-Pipeline gestorben — Voice offline bis Restart."+ "Speech pipeline died — voice offline until restart.")self._pipeline_task.add_done_callback(_on_pipeline_done)# Log the ACTUAL configured wake word, not a hardcoded "Hey Jarvis"# (the custom phrase, e.g. "Luca", or the openWakeWord keyword).logger.info(- "Speech-Pipeline gestartet — Wake: {!r}.",+ "Speech pipeline started — wake: {!r}.",wake_plan.phrase or wake_plan.oww_keyword or "?",)if getattr(self, "_bp", False):@@ -2546,16 +2551,16 @@ class DesktopApp:)def _install_focus_route(self, server: WebServer) -> None:- """Ersetzt den Placeholder ``/api/window/focus`` durch echten Call.+ """Replaces the placeholder ``/api/window/focus`` with a real call.- server.py registriert im Constructor einen No-Op-Handler — wir- entfernen ihn aus ``app.routes`` und registrieren unseren eigenen- daraufhin neu. Das ist vor ``server.start()`` sicher, weil noch keine- Requests geroutet werden.+ server.py registers a no-op handler in its constructor — we remove+ it from ``app.routes`` and register our own in its place. This is+ safe before ``server.start()`` because no requests are being+ routed yet."""app = server.app- # FastAPI.routes ist eine Property ohne Setter — in-place filtern statt- # neu zuweisen. app.router.routes ist die zugrundeliegende Liste.+ # FastAPI.routes is a property without a setter — filter in place+ # instead of reassigning. app.router.routes is the underlying list.app.router.routes[:] = [rfor r in app.router.routes@@ -2568,8 +2573,8 @@ class DesktopApp:if desktop is None or desktop._window is None:return {"ok": False, "reason": "no_window"}try:- # pywebview-Window-Methoden sind thread-safe — sie dispatchen- # intern an den GUI-Thread.+ # pywebview window methods are thread-safe — they dispatch+ # internally to the GUI thread.desktop._window.show()desktop._window.restore()desktop._window_visible = True@@ -2580,26 +2585,27 @@ class DesktopApp:except Exception as exc: # noqa: BLE001return {"ok": False, "reason": f"{type(exc).__name__}: {exc}"}- # ---- WebView-Hooks -----------------------------------------------------+ # ---- WebView hooks -------------------------------------------------------def _inject_token(self, window: Any) -> None:- """Setzt ``window.__JARVIS_TOKEN`` im Frontend via ``evaluate_js``.+ """Sets ``window.__JARVIS_TOKEN`` in the frontend via ``evaluate_js``.- Aufgerufen von ``webview.start(func=..., args=...)`` sobald das- Fenster bereit ist. Muss robust gegen Reloads sein — das Frontend- liest das Token beim ersten WS-Connect.+ Called by ``webview.start(func=..., args=...)`` once the window is+ ready. Must be robust against reloads — the frontend reads the+ token on its first WS connect.- Zusätzlich wird hier das Taskbar-/Titlebar-Icon gesetzt. pywebview- exposed auf Windows keinen Icon-Parameter — HWND via FindWindowW- (unique Title reicht durch Single-Instance-Lock).+ This is also where the taskbar/titlebar icon gets set. pywebview+ does not expose an icon parameter on Windows — we go through the+ HWND via FindWindowW (a unique title is guaranteed by the+ single-instance lock)."""token_literal = json.dumps(self.session_token)js = f"window.__JARVIS_TOKEN = {token_literal};"try:window.evaluate_js(js)except Exception: # noqa: BLE001- # Kein Fatal-Error — Frontend kann Token ueber ``?token=`` URL- # oder /api/ui/bootstrap holen als Fallback.+ # Not a fatal error — the frontend can fall back to fetching the+ # token via the ``?token=`` URL or /api/ui/bootstrap.passtry:@@ -2612,19 +2618,19 @@ class DesktopApp:except Exception: # noqa: BLE001pass- # ---- Backend-Ready-Check ----------------------------------------------+ # ---- Backend-ready check --------------------------------------------------def _wait_for_backend(self, timeout_s: float = 45.0) -> bool:- """Pollt ``/api/health`` bis 200 kommt oder Timeout abgelaufen ist.+ """Polls ``/api/health`` until it returns 200 or the timeout expires.- 45s Default — Whisper/VAD-Modelle werden bei erster Initialisierung- geladen und blockieren den Event-Loop synchron für bis zu ~20s.+ 45s default — Whisper/VAD models are loaded on first initialization+ and block the event loop synchronously for up to ~20s."""import httpxurl = f"http://127.0.0.1:{self.cfg.ui.admin_api_port}/api/health"start = time.monotonic()- # 100 ms Startpuffer damit der Thread den Loop aufsetzen kann.+ # 100 ms startup buffer so the thread can set up the loop.time.sleep(0.05)while time.monotonic() - start < timeout_s:try:@@ -2636,10 +2642,10 @@ class DesktopApp:time.sleep(0.25)return False- # ---- Main-Entry --------------------------------------------------------+ # ---- Main entry point ------------------------------------------------------def run(self) -> int:- """Blockt bis der User das Fenster schliesst. Rueckgabe = Exit-Code.+ """Blocks until the user closes the window. Return value = exit code.Classic boot: start the backend thread here, then run the window. Thefast-boot launcher path starts the backend thread itself (so the@@ -2660,7 +2666,7 @@ class DesktopApp:import webview # type: ignore[import-not-found]if not self._wait_for_backend():- sys.stderr.write("Backend startete nicht in 45s — Abbruch.\n")+ sys.stderr.write("Backend did not start within 45s — aborting.\n")return self.shutdown() or 2self._window = webview.create_window(@@ -2675,31 +2681,31 @@ class DesktopApp:)self._window_visible = True- # Close-Button = Minimize-to-Tray (User-Entscheidung 2026-04-20).- # `closing`-Callback gibt False zurueck → pywebview bricht Destroy ab.+ # Close button = minimize-to-tray (user decision 2026-04-20).+ # The `closing` callback returns False → pywebview aborts the destroy.# Extracted to a method so the tray-minimise + overlay-clear contract# is unit-testable (test_desktop_minimize_to_tray_overlay.py).self._window.events.closing += self._on_window_closing- # Tray + Bridge zum Main-Thread-Window starten. Daemon-Thread, damit- # er beim Hauptprogramm-Exit nicht am Leben bleibt.+ # Start the tray + bridge to the main-thread window. A daemon+ # thread, so it doesn't stay alive when the main program exits.self._start_tray_and_bridge()- # Taskbar-Icon-Setter als parallelen Polling-Thread starten. Pywebview- # ruft ``func`` (``_inject_token``) erst nach dem ``shown``-Event auf —- # zu dem Zeitpunkt hat Windows den Taskbar-Eintrag schon mit dem- # pythonw.exe-Default-Icon gerendert und cached die Zuordnung. Wir- # pollen FindWindowW alle 50 ms ab und setzen WM_SETICON, sobald das- # HWND existiert. Das ist der frueheste Zeitpunkt, an dem die Taskbar- # das Jarvis-Icon mitbekommt.+ # Start the taskbar icon setter as a parallel polling thread.+ # pywebview only calls ``func`` (``_inject_token``) after the+ # ``shown`` event — by then Windows has already rendered the+ # taskbar entry with the pythonw.exe default icon and cached that+ # mapping. We poll FindWindowW every 50 ms and set WM_SETICON as+ # soon as the HWND exists. That's the earliest point at which the+ # taskbar can pick up the Jarvis icon.self._start_icon_setter_thread()gui = "edgechromium" if sys.platform == "win32" else Nonedebug = os.environ.get("JARVIS_WEBVIEW_DEBUG") == "1"- # webview.start blockt im Main-Thread. func/args wird nach dem ersten- # Load aufgerufen (pywebview-intern), sodass evaluate_js auf einen- # DOM-fertigen Context trifft.+ # webview.start blocks the main thread. func/args gets called after+ # the first load (pywebview-internal), so evaluate_js hits a+ # DOM-ready context.webview.start(func=self._inject_token,args=(self._window,),@@ -2709,14 +2715,14 @@ class DesktopApp:return self.shutdown()def _start_icon_setter_thread(self) -> None:- """Polling-Thread: setzt Taskbar-/Titlebar-Icon sobald HWND existiert.-- Hintergrund: pywebview's ``func``-Callback feuert erst nach dem- ``shown``-Event. Bis dahin ist die Taskbar-Zuordnung schon mit dem- Default-Process-Icon (Python-Logo) initialisiert. Wir pollen- ``FindWindowW`` parallel zu ``webview.start`` (das im Main-Thread- blockt) und rufen ``set_window_icon_by_title`` so frueh wie moeglich.- Daemon-Thread, max. 5 s, dann gibt der Thread auf.+ """Polling thread: sets the taskbar/titlebar icon once the HWND exists.++ Background: pywebview's ``func`` callback only fires after the+ ``shown`` event. Until then, the taskbar mapping is already+ initialized with the default process icon (the Python logo). We+ poll ``FindWindowW`` in parallel with ``webview.start`` (which+ blocks the main thread) and call ``set_window_icon_by_title`` as+ early as possible. A daemon thread, max. 5 s, then it gives up."""if sys.platform != "win32":return@@ -2754,14 +2760,14 @@ class DesktopApp:if first_set_at is None:first_set_at = time.monotonic()logger.debug(- "Taskbar-Icon gesetzt; re-arming gegen WebView2-Override."+ "Taskbar icon set; re-arming against WebView2 override.")elif time.monotonic() - first_set_at > 8.0:returntime.sleep(0.3)if first_set_at is None:logger.warning(- "Taskbar-Icon-Setter Timeout — Fenster '{}' nicht gefunden.",+ "Taskbar icon setter timeout — window '{}' not found.",WINDOW_TITLE,)@@ -2769,16 +2775,16 @@ class DesktopApp:target=_poll, name="jarvis-icon-setter", daemon=True).start()- # ---- Tray -------------------------------------------------------------+ # ---- Tray -----------------------------------------------------------------def _start_tray_and_bridge(self) -> None:- """Startet den JarvisTray und einen Daemon-Thread, der Tray-Commands- auf pywebview-Window-Operations uebersetzt.+ """Starts the JarvisTray and a daemon thread that translates tray+ commands into pywebview window operations.- Warum eine Bridge statt direktem Callback? pystray-Callbacks laufen im- pystray-Thread; pywebview-Methoden zu callen ist zwar dokumentiert-- thread-safe, aber ein dedizierter Bridge-Thread macht das Ownership- explizit und erlaubt spaeter Back-Pressure/Debounce.+ Why a bridge instead of a direct callback? pystray callbacks run+ on the pystray thread; calling pywebview methods is documented as+ thread-safe, but a dedicated bridge thread makes the ownership+ explicit and allows for back-pressure/debounce later."""from jarvis.ui.tray import JarvisState, JarvisTray@@ -3139,17 +3145,17 @@ class DesktopApp:# ----------------------------------------------------------------------------# CLI-Entry+# CLI entry point# ---------------------------------------------------------------------------def main() -> int:- """CLI-Entry fuer ``python -m jarvis.ui.desktop_app``."""+ """CLI entry point for ``python -m jarvis.ui.desktop_app``."""try:lock = acquire_single_instance_lock()except SingleInstanceError as exc:sys.stderr.write(f"{exc}\n")- # Bestehende Instanz in den Vordergrund holen — best-effort.+ # Bring the existing instance to the front — best-effort.focus_existing_instance_robust()return 3diff --git a/jarvis/ui/shell/single_instance.py b/jarvis/ui/shell/single_instance.pyindex bf4e38a0e8..03846dd060 100644--- a/jarvis/ui/shell/single_instance.py+++ b/jarvis/ui/shell/single_instance.py@@ -1,23 +1,23 @@-"""Single-Instance-Durchsetzung für die Desktop-App.+"""Single-instance enforcement for the desktop app.-**Zwei-Schicht-Strategie:**+**Two-layer strategy:**-1. **Named-Mutex via pywin32** — atomarer Primary-Claim. OS-garantierte- Bereinigung bei Crash (Handle wird vom Kernel freigegeben), keine stale- Lock-Files. Robuster als `filelock` auf Windows.+1. **Named mutex via pywin32** — atomic primary claim. OS-guaranteed+ cleanup on crash (the kernel releases the handle), no stale+ lock files. More robust than `filelock` on Windows.-2. **Session-File** (`%LOCALAPPDATA%\\Jarvis\\session.json`) — speichert Port +- Token der laufenden Primary-Instanz, damit ein Secondary ihn auf- ``/internal/activate`` pingen kann. Token-geschützt, 0600-ähnlich- (User-ACL).+2. **Session file** (`%LOCALAPPDATA%\\Jarvis\\session.json`) — stores the port ++ token of the running primary instance, so a secondary can ping it on+ ``/internal/activate``. Token-protected, roughly 0600+ (user ACL).-Ablauf bei Start einer Secondary:+Flow when a secondary starts:-1. Mutex-Claim schlägt fehl → Primary existiert.-2. Session-File lesen → Port+Token → HTTP-POST.-3. Primary bringt Fenster nach vorne, Secondary beendet sich.-4. Falls Session-File fehlt / HTTP fehlschlägt → Primary ist zombifiziert;- Fallback = Warnung und Exit (User muss Task-Manager benutzen).+1. Mutex claim fails → a primary already exists.+2. Read the session file → port+token → HTTP POST.+3. The primary brings its window to the front, the secondary exits.+4. If the session file is missing / the HTTP call fails → the primary is a+ zombie; fallback = show a warning and exit (the user has to use Task Manager)."""from __future__ import annotations@@ -39,22 +39,22 @@ SESSION_FILENAME = "session.json"def _app_data_dir() -> Path:- """App-Data-Verzeichnis — delegiert an ``jarvis.core.paths``.+ """App-data directory — delegates to ``jarvis.core.paths``.- Wrapper bleibt fuer Rueckwaertskompatibilitaet mit internen Aufrufern,- die ``_app_data_dir()`` direkt importieren.+ The wrapper stays for backward compatibility with internal callers+ that import ``_app_data_dir()`` directly."""return ensure_user_dirs()@dataclass(slots=True)class InstanceClaim:- """Handle auf den aktiven Mutex — `release()` bei Shutdown aufrufen."""+ """Handle to the active mutex — call `release()` on shutdown."""_mutex: Any = None_session_file: Path | None = Nonedef release(self) -> None:- # Mutex freigeben+ # Release the mutexif self._mutex is not None:try:import win32api # type: ignore[import-not-found]@@ -65,7 +65,7 @@ class InstanceClaim:except Exception: # noqa: BLE001passself._mutex = None- # Session-File aufräumen+ # Clean up the session fileif self._session_file is not None:try:self._session_file.unlink(missing_ok=True)@@ -75,7 +75,7 @@ class InstanceClaim:class SingleInstance:- """Coordinator — Claim am Start, Release am Ende, Activate-Fallback."""+ """Coordinator — claim on start, release on end, activate fallback."""def __init__(self, app_dir: Path | None = None) -> None:self._app_dir = app_dir or _app_data_dir()@@ -99,21 +99,21 @@ class SingleInstance:logger.debug("boot screenshot sweep failed", exc_info=True)def try_claim(self) -> InstanceClaim | None:- """Primary-Claim — liefert `InstanceClaim` oder None wenn bereits ein- anderer Prozess aktiv ist.+ """Primary claim — returns an `InstanceClaim`, or None if another+ process is already active."""try:import win32event # type: ignore[import-not-found]import winerror # type: ignore[import-not-found]except ImportError:- # Nicht-Windows — kein Mutex, einfach als Primary melden.+ # Not Windows — no mutex, just report as primary.self._on_primary_claim()return InstanceClaim(_mutex=None, _session_file=self.session_file)mutex = win32event.CreateMutex(None, False, MUTEX_NAME)last_error = _get_last_error()if last_error == winerror.ERROR_ALREADY_EXISTS:- # Bereits aktiv — Handle sofort wieder schließen.+ # Already active — close the handle right away.try:import win32api@@ -139,10 +139,10 @@ class SingleInstance:return Nonedef activate_existing(self, timeout: float = 2.0) -> bool:- """Schickt Bring-to-Front-Request an die Primary-Instanz.+ """Sends a bring-to-front request to the primary instance.- Gibt True zurück wenn der Ping erfolgreich war. False → Primary ist- zombifiziert oder nie vollständig gestartet.+ Returns True if the ping succeeded. False → the primary is a+ zombie or never fully started."""session = self.read_session()if not session:diff --git a/jarvis/ui/shell/window.py b/jarvis/ui/shell/window.pyindex 86e326d1d5..2df432d977 100644--- a/jarvis/ui/shell/window.py+++ b/jarvis/ui/shell/window.py@@ -1,7 +1,8 @@-"""pywebview-Window-Konfiguration.+"""pywebview window configuration.-Die Window-Instanz wird vom :class:`JarvisShell` verwaltet — dieses Modul hält-nur die Daten-Struktur. So bleibt `shell.py` testbar ohne pywebview-Mock.+The window instance is managed by :class:`JarvisShell` — this module only+holds the data structure. That keeps `shell.py` testable without a+pywebview mock."""from __future__ import annotations@@ -10,7 +11,7 @@ from dataclasses import dataclass@dataclass(slots=True)class WindowConfig:- """Parameter für das pywebview-Hauptfenster."""+ """Parameters for the main pywebview window."""title: str = "Jarvis"url: str = "http://127.0.0.1:47821"width: int = 1280@@ -18,9 +19,9 @@ class WindowConfig:min_width: int = 760min_height: int = 560start_hidden: bool = False- background_color: str = "#0a0e14" # Jarvis Dark-Theme- # Frameless ist pywebview-unterstützt, wir lassen es aber Standard-Frame- # für die erste Version — Fensterkontrollen kommen vom OS.+ background_color: str = "#0a0e14" # Jarvis dark theme+ # Frameless is supported by pywebview, but we keep the standard frame+ # for the first version — window controls come from the OS.frameless: bool = Falseeasy_drag: bool = Falseconfirm_close: bool = Falsediff --git a/jarvis/ui/tray.py b/jarvis/ui/tray.pyindex 8df6a5033d..3b4924f30d 100644--- a/jarvis/ui/tray.py+++ b/jarvis/ui/tray.py@@ -1,10 +1,10 @@-"""System-Tray-Icon als primäre UI für Jarvis.+"""System tray icon as the primary UI for Jarvis.-State-Icons werden dynamisch per PIL gerendert (keine .ico-Assets nötig für MVP).-Später können hochwertige .ico-Files unter assets/icons/ abgelegt werden.+State icons are rendered dynamically via PIL (no .ico assets needed for MVP).+Higher-quality .ico files can later be placed under assets/icons/.-Threading: pystray läuft in einem eigenen Thread (nicht asyncio-fähig).-Kommunikation mit dem Event-Loop über einen thread-safe Queue.+Threading: pystray runs on its own thread (not asyncio-capable).+It communicates with the event loop via a thread-safe queue."""from __future__ import annotations@@ -32,21 +32,21 @@ class JarvisState(str, Enum):_STATE_COLORS: dict[JarvisState, tuple[int, int, int]] = {- JarvisState.IDLE: (80, 120, 200), # ruhiges Blau- JarvisState.LISTENING: (60, 200, 90), # Grün- JarvisState.THINKING: (230, 190, 40), # Gelb- JarvisState.SPEAKING: (220, 100, 180), # Pink- JarvisState.ERROR: (220, 60, 60), # Rot- JarvisState.PAUSED: (130, 130, 130), # Grau+ JarvisState.IDLE: (80, 120, 200), # calm blue+ JarvisState.LISTENING: (60, 200, 90), # green+ JarvisState.THINKING: (230, 190, 40), # yellow+ JarvisState.SPEAKING: (220, 100, 180), # pink+ JarvisState.ERROR: (220, 60, 60), # red+ JarvisState.PAUSED: (130, 130, 130), # gray}def _make_icon(state: JarvisState, size: int = 64) -> Any:- """Liefert PIL-Image für den Tray.+ """Returns a PIL image for the tray.- IDLE nutzt ``assets/icons/jarvis.ico`` (User-Branding), aktive Zustände- bekommen einen farbigen Kreis — so bleibt die State-Rückmeldung erhalten- und der User sieht trotzdem im Default das echte Jarvis-Logo.+ IDLE uses ``assets/icons/jarvis.ico`` (user branding); active states+ get a colored circle — so the state feedback is preserved while the+ user still sees the real Jarvis logo by default."""from PIL import Image, ImageDraw # type: ignore[import-untyped]@@ -74,17 +74,17 @@ def _make_icon(state: JarvisState, size: int = 64) -> Any:@dataclass(slots=True)class TrayCommand:- """Vom Tray → Jarvis-Core geschickte Action."""+ """Action sent from the tray → Jarvis core."""action: str # "quit" | "pause" | "resume" | "reload_config" | "open_settings"payload: dict[str, Any] | None = Noneclass JarvisTray:- """Tray-Icon-Wrapper mit Status-States und Menu.+ """Tray icon wrapper with status states and a menu.Usage:tray = JarvisTray(on_command=handle)- tray.start() # eigener Thread+ tray.start() # its own threadtray.set_state(JarvisState.LISTENING)...tray.stop()@@ -176,7 +176,7 @@ class JarvisTray:self._icon = Nonedef set_state(self, state: JarvisState) -> None:- """Thread-safe State-Update — rerendert Icon und Tooltip."""+ """Thread-safe state update — re-renders the icon and tooltip."""if state == self._state:returnself._state = state@@ -197,10 +197,10 @@ class JarvisTray:passasync def command_stream(self) -> asyncio.Queue[TrayCommand]:- """Async-Bridge: yieldet Tray-Commands als asyncio-Queue.+ """Async bridge: yields tray commands as an asyncio queue.- Der Aufrufer kann `await queue.get()` machen; Ein Background-Task liest- aus dem thread-safen queue.Queue und forwarded.+ The caller can do `await queue.get()`; a background task reads+ from the thread-safe queue.Queue and forwards them."""aq: asyncio.Queue[TrayCommand] = asyncio.Queue()loop = asyncio.get_running_loop()diff --git a/jarvis/ui/web/__init__.py b/jarvis/ui/web/__init__.pyindex a0ab13d3ad..30140c1d1f 100644--- a/jarvis/ui/web/__init__.py+++ b/jarvis/ui/web/__init__.py@@ -1,9 +1,9 @@-"""Web-Backend für die Desktop-UI (Phase 1a).+"""Web backend for the desktop UI (Phase 1a).-Exponiert FastAPI + WebSocket auf 127.0.0.1 für die pywebview-Shell und-optional für Mobile-Companion-Clients (Phase 8+). Das Token-Auth schließt-den Endpunkt gegen neugierige Nachbarn auf localhost (Browser-Extensions,-andere Dev-Server) ab — Bind-Adresse allein reicht nicht.+Exposes FastAPI + WebSocket on 127.0.0.1 for the pywebview shell, and+optionally for mobile companion clients (Phase 8+). Token auth locks the+endpoint down against nosy neighbors on localhost (browser extensions,+other dev servers) — the bind address alone is not enough.Lazy package surface (PEP 562). Importing ``jarvis.ui.web`` (which``python -m jarvis.ui.web.launcher`` forces) must NOT eagerly importdiff --git a/jarvis/ui/web/board_routes.py b/jarvis/ui/web/board_routes.pyindex 46e6838edd..42d0788a08 100644--- a/jarvis/ui/web/board_routes.py+++ b/jarvis/ui/web/board_routes.py@@ -1,15 +1,15 @@-"""REST-API fuer das Personal-Mastery-Dashboard.+"""REST API for the Personal Mastery dashboard.Endpoints:-- ``GET /api/board/personal/summary`` → Totals + 30-Tage-Fenster-- ``GET /api/board/personal/heatmap`` → GitHub-Style-Grid (?days=365)-- ``GET /api/board/personal/tools`` → Tool-Usage-Histogramm-- ``GET /api/board/personal/records`` → Personal Records-- ``POST /api/board/personal/refresh`` → Manueller Aggregator-Run-- ``GET /api/board/achievements`` → Alle Specs mit Unlock-Status-- ``GET /api/board/bio`` → Aktuelle AI-Bio + Alter-- ``POST /api/board/bio/regenerate`` → Manuell neue Bio generieren+- ``GET /api/board/personal/summary`` → totals + 30-day window+- ``GET /api/board/personal/heatmap`` → GitHub-style grid (?days=365)+- ``GET /api/board/personal/tools`` → tool-usage histogram+- ``GET /api/board/personal/records`` → personal records+- ``POST /api/board/personal/refresh`` → manual aggregator run+- ``GET /api/board/achievements`` → all specs with unlock status+- ``GET /api/board/bio`` → current AI bio + age+- ``POST /api/board/bio/regenerate`` → manually generate a new bio"""from __future__ import annotations@@ -36,14 +36,14 @@ board_router = APIRouter(prefix="/api/board", tags=["board"])def _require_store(request: Request) -> BoardStore:store = getattr(request.app.state, "board_store", None)if store is None:- raise HTTPException(status_code=503, detail="BoardStore nicht verfuegbar")+ raise HTTPException(status_code=503, detail="BoardStore not available")return storedef _require_aggregator(request: Request) -> BoardAggregator:agg = getattr(request.app.state, "board_aggregator", None)if agg is None:- raise HTTPException(status_code=503, detail="BoardAggregator nicht verfuegbar")+ raise HTTPException(status_code=503, detail="BoardAggregator not available")return agg@@ -71,21 +71,21 @@ async def _freshen(request: Request, ttl_s: float = _FRESHEN_TTL_S) -> None:def _require_evaluator(request: Request) -> AchievementEvaluator:ev = getattr(request.app.state, "achievement_evaluator", None)if ev is None:- raise HTTPException(status_code=503, detail="AchievementEvaluator nicht verfuegbar")+ raise HTTPException(status_code=503, detail="AchievementEvaluator not available")return evdef _require_bio_generator(request: Request) -> BioGenerator:gen = getattr(request.app.state, "bio_generator", None)if gen is None:- raise HTTPException(status_code=503, detail="BioGenerator nicht verfuegbar")+ raise HTTPException(status_code=503, detail="BioGenerator not available")return gendef _require_bio_store(request: Request) -> BioStore:store = getattr(request.app.state, "bio_store", None)if store is None:- raise HTTPException(status_code=503, detail="BioStore nicht verfuegbar")+ raise HTTPException(status_code=503, detail="BioStore not available")return store@@ -243,18 +243,18 @@ async def personal_records(request: Request) -> RecordsResponse:@router.post("/refresh", response_model=RefreshResponse)async def personal_refresh(request: Request) -> RefreshResponse:- """Manuell den Aggregator anwerfen. Synchron, bis DB geupsertet ist.+ """Manually kick off the aggregator. Synchronous, until the DB is upserted.- Wird vom UI-„Refresh"-Button ausgeloest. Keine Long-Poll-Illusion —- der Request kehrt erst zurueck, wenn die DB aktuell ist. Das ist bei- <10 k Events ein Bruchteil einer Sekunde.+ Triggered by the UI's "Refresh" button. No long-poll illusion —+ the request only returns once the DB is current. For <10k events+ that's a fraction of a second."""agg = _require_aggregator(request)try:await asyncio.to_thread(agg.run)return RefreshResponse(ok=True, triggered=True)except Exception as exc: # noqa: BLE001- log.exception("manueller Board-Refresh fehlgeschlagen")+ log.exception("manual board refresh failed")raise HTTPException(status_code=500, detail=str(exc)) from exc@@ -298,11 +298,11 @@ class BioRegenerateResponse(BaseModel):class BioFeedbackRequest(BaseModel):- """Reagier-Klick unter einer Bio. Das Signal kalibriert die NAECHSTE- Generation; kein Sofort-Regenerate.+ """Reaction click under a bio. The signal calibrates the NEXT+ generation; no immediate regenerate."""bio_generated_at: str- kind: Literal["trifft", "trifft_nicht", "haerter"]+ kind: Literal["trifft", "trifft_nicht", "haerter"] # i18n-allow: API contract values matched by frontend logicclass BioFeedbackResponse(BaseModel):@@ -346,10 +346,10 @@ async def regenerate_bio(request: Request,payload: BioRegenerateRequest | None = None,) -> BioRegenerateResponse:- """Triggert eine neue Bio.+ """Triggers a new bio.- Bei Brain-Outage: 200 mit ``ok=False`` + ``reason=...``. Kein 500 —- die alte Bio ist ja noch verfuegbar via ``GET /bio``.+ On a brain outage: 200 with ``ok=False`` + ``reason=...``. No 500 —+ the old bio is still available via ``GET /bio``."""gen = _require_bio_generator(request)body = payload or BioRegenerateRequest()@@ -360,14 +360,14 @@ async def regenerate_bio(triggered_by="manual",)except Exception as exc: # noqa: BLE001- log.exception("Bio-Regenerate fehlgeschlagen")+ log.exception("bio regenerate failed")return BioRegenerateResponse(ok=False, generated_at=None, text=None, reason=str(exc),)if result is None:return BioRegenerateResponse(ok=False, generated_at=None, text=None,- reason="Brain nicht verfuegbar — alte Bio bleibt",+ reason="Brain not available — old bio stays",)return BioRegenerateResponse(ok=True,@@ -381,10 +381,10 @@ async def post_bio_feedback(request: Request,payload: BioFeedbackRequest,) -> BioFeedbackResponse:- """Schreibt einen Reagier-Klick (``Trifft`` / ``Trifft nicht`` / ``Haerter``).+ """Records a reaction click (``Trifft`` / ``Trifft nicht`` / ``Haerter``).- Der Klick wird als Tone-Vector aggregiert und in den Prompt der naechsten- Bio-Generation gefuettert (siehe ``BioStore.recent_feedback`` ++ The click is aggregated as a tone vector and fed into the prompt of the+ next bio generation (see ``BioStore.recent_feedback`` +``prompts.render_bio_prompt:_render_feedback``)."""bio_store = _require_bio_store(request)@@ -395,7 +395,7 @@ async def post_bio_feedback(except ValueError as exc:return BioFeedbackResponse(ok=False, reason=str(exc))except Exception as exc: # noqa: BLE001- log.exception("Bio-Feedback persistieren fehlgeschlagen")+ log.exception("persisting bio feedback failed")return BioFeedbackResponse(ok=False, reason=str(exc))bus = getattr(request.app.state, "bus", None)@@ -407,7 +407,7 @@ async def post_bio_feedback(source_layer="ui.board",))except Exception: # noqa: BLE001- log.debug("Bio-Feedback Bus-Publish fehlgeschlagen — non-fatal")+ log.debug("bio feedback bus publish failed — non-fatal")return BioFeedbackResponse(ok=True)diff --git a/jarvis/ui/web/cli_routes.py b/jarvis/ui/web/cli_routes.pyindex 43ae1b7a6a..edaa63b371 100644--- a/jarvis/ui/web/cli_routes.py+++ b/jarvis/ui/web/cli_routes.py@@ -1,18 +1,18 @@-"""REST-API fuer die CLI-Integration (Desktop-UI).+"""REST API for the CLI integration (desktop UI).Endpoints:-- ``GET /api/clis`` → Liste aller Katalog-Eintraege + Status-- ``GET /api/clis/{name}`` → Voller Detail-Datensatz-- ``POST /api/clis/{name}/check`` → Live Binary-/Auth-Probe-- ``POST /api/clis/{name}/install`` → Install-Job starten (streamt via WS)-- ``DELETE /api/clis/{name}/install/{job_id}`` → Install abbrechen-- ``POST /api/clis/{name}/connect`` → Auth-Flow starten (OAuth/APIKey)-- ``POST /api/clis/{name}/disconnect`` → Auth entfernen-- ``GET /api/clis/{name}/usage`` → Paginierte Usage-History-- ``GET /api/clis/{name}/usage/stats`` → Stats-Aggregation-- ``POST /api/clis/custom`` → Custom-CLI registrieren-- ``DELETE /api/clis/custom/{name}`` → Custom-CLI entfernen-- ``DELETE /api/clis/{name}/usage`` → History loeschen+- ``GET /api/clis`` → list of all catalog entries + status+- ``GET /api/clis/{name}`` → full detail record+- ``POST /api/clis/{name}/check`` → live binary/auth probe+- ``POST /api/clis/{name}/install`` → start install job (streams via WS)+- ``DELETE /api/clis/{name}/install/{job_id}`` → cancel install+- ``POST /api/clis/{name}/connect`` → start auth flow (OAuth/API key)+- ``POST /api/clis/{name}/disconnect`` → remove auth+- ``GET /api/clis/{name}/usage`` → paginated usage history+- ``GET /api/clis/{name}/usage/stats`` → stats aggregation+- ``POST /api/clis/custom`` → register a custom CLI+- ``DELETE /api/clis/custom/{name}`` → remove a custom CLI+- ``DELETE /api/clis/{name}/usage`` → delete history"""from __future__ import annotations@@ -40,7 +40,7 @@ _TEST_RUN_TIMEOUT_S = 90.0def _require_registry(request: Request) -> CliToolRegistry:reg = getattr(request.app.state, "cli_registry", None)if reg is None:- raise HTTPException(status_code=503, detail="CliToolRegistry nicht verfuegbar")+ raise HTTPException(status_code=503, detail="CliToolRegistry not available")return reg@@ -173,15 +173,15 @@ class DisconnectResponse(BaseModel):class SpawnExternalRequest(BaseModel):- """Anfrage an /spawn-external — oeffnet ein **echtes** Windows Terminal- (wt/pwsh) und fuehrt dort entweder den Install- oder den Login-Command- fuer die angegebene CLI aus. Im Gegensatz zum eingebetteten xterm im- Frontend laeuft das Terminal als detached Subprocess in der User-- Session (cwd = USERPROFILE), getrennt von der Jarvis-App.+ """Request to /spawn-external — opens a **real** Windows terminal+ (wt/pwsh) and runs either the install or the login command for the+ given CLI in it. Unlike the embedded xterm in the frontend, the+ terminal runs as a detached subprocess in the user session+ (cwd = USERPROFILE), separate from the Jarvis app."""kind: Literal["install", "login"]- method: str | None = None # nur fuer kind=install: "winget"|"scoop"|"npm"|...+ method: str | None = None # only for kind=install: "winget"|"scoop"|"npm"|...class SpawnExternalResponse(BaseModel):@@ -408,7 +408,7 @@ async def get_cli(name: str, request: Request) -> CliDetail:reg = _require_registry(request)spec = reg.catalog().get(name)if spec is None:- raise HTTPException(status_code=404, detail=f"CLI '{name}' nicht im Katalog")+ raise HTTPException(status_code=404, detail=f"CLI '{name}' not in catalog")status = reg.status_of(name)usage = reg.usage_log()count_7d = usage.count_for(name, since_ms=int(time.time() * 1000) - _WEEK_MS)@@ -445,10 +445,10 @@ async def get_cli(name: str, request: Request) -> CliDetail:async def check_cli(name: str, request: Request) -> CheckResponse:reg = _require_registry(request)if reg.catalog().get(name) is None:- raise HTTPException(status_code=404, detail=f"CLI '{name}' nicht im Katalog")+ raise HTTPException(status_code=404, detail=f"CLI '{name}' not in catalog")status = await reg.refresh_status(name)if status is None:- raise HTTPException(status_code=500, detail="Refresh fehlgeschlagen")+ raise HTTPException(status_code=500, detail="refresh failed")spec = reg.catalog().get(name)assert spec is not Nonereturn CheckResponse(@@ -477,7 +477,7 @@ async def list_usage() -> UsageListResponse:reg = _require_registry(request)if reg.catalog().get(name) is None:- raise HTTPException(status_code=404, detail=f"CLI '{name}' nicht im Katalog")+ raise HTTPException(status_code=404, detail=f"CLI '{name}' not in catalog")usage = reg.usage_log()offset = (page - 1) * page_sizerows = usage.list_for(@@ -519,7 +519,7 @@ async def usage_stats() -> UsageStatsResponse:reg = _require_registry(request)if reg.catalog().get(name) is None:- raise HTTPException(status_code=404, detail=f"CLI '{name}' nicht im Katalog")+ raise HTTPException(status_code=404, detail=f"CLI '{name}' not in catalog")stats = reg.usage_log().stats_for(name, since_ms=since_ms)success_rate = (stats.success_calls / stats.total_calls) if stats.total_calls else 0.0return UsageStatsResponse(@@ -539,34 +539,34 @@ async def spawn_external(request: Request,body: SpawnExternalRequest,) -> SpawnExternalResponse:- """Spawnt ein externes Windows Terminal (wt/pwsh) und fuehrt entweder- den Install- oder den Login-Command darin aus.-- Im Gegensatz zum POST /install (das eine eigene asyncio-Subprocess-Pipeline- fuehrt + Output-Streaming an die UI macht) ist dieser Endpoint reine- Spawn-And-Forget-Logik: Wir oeffnen ein echtes Terminal-Fenster (wie- der User es erwartet, wenn er ``wt`` selber tippt) und lassen den User- dort interagieren. Status-Polling laeuft separat ueber /check.+ """Spawns an external Windows terminal (wt/pwsh) and runs either the+ install or the login command in it.++ Unlike POST /install (which runs its own asyncio subprocess pipeline+ + streams output to the UI), this endpoint is pure spawn-and-forget+ logic: we open a real terminal window (as the user expects when they+ type ``wt`` themselves) and let the user interact there. Status+ polling runs separately via /check."""from jarvis.clis.external_terminal import spawn_external_terminalreg = _require_registry(request)spec = reg.catalog().get(name)if spec is None:- raise HTTPException(status_code=404, detail=f"CLI '{name}' nicht im Katalog")+ raise HTTPException(status_code=404, detail=f"CLI '{name}' not in catalog")if body.kind == "install":if not body.method:return SpawnExternalResponse(ok=False,- error="method required fuer kind=install",+ error="method required for kind=install",)installer = reg.installer()cmd_argv = installer.build_command(spec, body.method) # type: ignore[arg-type]if not cmd_argv:return SpawnExternalResponse(ok=False,- error=f"Keine Install-Methode '{body.method}' fuer {name}",+ error=f"No install method '{body.method}' for {name}",)command = " ".join(cmd_argv)title = f"Install: {spec.display_name}"@@ -574,7 +574,7 @@ async def spawn_external(if spec.auth.type != "oauth_cli" or not spec.auth.login_command:return SpawnExternalResponse(ok=False,- error=f"{name} hat keinen interaktiven login_command (auth.type={spec.auth.type})",+ error=f"{name} has no interactive login_command (auth.type={spec.auth.type})",)command = " ".join(spec.auth.login_command)title = f"Login: {spec.display_name}"@@ -584,7 +584,7 @@ async def spawn_external(ok=ok,method=method,command=command if ok else None,- error=None if ok else "Kein externes Terminal verfuegbar (wt/pwsh/powershell)",+ error=None if ok else "No external terminal available (wt/pwsh/powershell)",)@@ -597,7 +597,7 @@ async def install_cli(reg = _require_registry(request)spec = reg.catalog().get(name)if spec is None:- raise HTTPException(status_code=404, detail=f"CLI '{name}' nicht im Katalog")+ raise HTTPException(status_code=404, detail=f"CLI '{name}' not in catalog")installer = reg.installer()bus = reg.bus()@@ -646,7 +646,7 @@ async def install_cli(ok=False,job_id="",command="",- error=f"Methode '{body.method}' fuer {name} nicht verfuegbar",+ error=f"Method '{body.method}' not available for {name}",)return InstallStartResponse(ok=True,@@ -671,7 +671,7 @@ async def connect_cli(reg = _require_registry(request)spec = reg.catalog().get(name)if spec is None:- raise HTTPException(status_code=404, detail=f"CLI '{name}' nicht im Katalog")+ raise HTTPException(status_code=404, detail=f"CLI '{name}' not in catalog")auth = reg.auth()bus = reg.bus()@@ -680,7 +680,7 @@ async def connect_cli(return ConnectResponse(ok=False,status="error",- error=f"{name} nutzt auth.type='{spec.auth.type}', nicht 'api_key'",+ error=f"{name} uses auth.type='{spec.auth.type}', not 'api_key'",)ok, err = await auth.connect_api_key(spec,@@ -698,7 +698,7 @@ async def connect_cli(return ConnectResponse(ok=False,status="error",- error=f"{name} nutzt auth.type='{spec.auth.type}', nicht 'oauth_cli'",+ error=f"{name} uses auth.type='{spec.auth.type}', not 'oauth_cli'",)from uuid import uuid4@@ -724,7 +724,7 @@ async def connect_cli(handle = auth.start_oauth_login(spec, job_id=job_id, on_line=_on_line)if handle is None:return ConnectResponse(- ok=False, status="error", error="login bereits aktiv oder nicht verfuegbar"+ ok=False, status="error", error="login already active or not available")if bus is not None:@@ -736,7 +736,7 @@ async def connect_cli(source_layer="clis.auth",cli_name=name,job_id=job_id,- line="Login gestartet",+ line="Login started",step="browser_open",done=False,),@@ -770,19 +770,19 @@ async def disconnect_cli(name: str, request: Request) -> DisconnectResponse:reg = _require_registry(request)spec = reg.catalog().get(name)if spec is None:- raise HTTPException(status_code=404, detail=f"CLI '{name}' nicht im Katalog")+ raise HTTPException(status_code=404, detail=f"CLI '{name}' not in catalog")auth = reg.auth()if spec.auth.type == "api_key":ok = auth.disconnect_api_key(spec)await reg.refresh_status(name)- return DisconnectResponse(ok=ok, error=None if ok else "Keyring-Delete fehlgeschlagen")+ return DisconnectResponse(ok=ok, error=None if ok else "keyring delete failed")if spec.auth.type == "oauth_cli":ok, err = await auth.disconnect_oauth(spec)await reg.refresh_status(name)return DisconnectResponse(ok=ok, error=err)return DisconnectResponse(ok=False,- error=f"auth.type '{spec.auth.type}' unterstuetzt disconnect nicht",+ error=f"auth.type '{spec.auth.type}' does not support disconnect",)@@ -839,7 +839,7 @@ async def unregister_custom(name: str, request: Request) -> dict[str, Any]:reg = _require_registry(request)ok = reg.catalog().remove_custom(name)if not ok:- raise HTTPException(status_code=404, detail=f"Custom-CLI '{name}' existiert nicht")+ raise HTTPException(status_code=404, detail=f"Custom CLI '{name}' does not exist")return {"ok": True}@@ -847,7 +847,7 @@ async def unregister_custom(name: str, request: Request) -> dict[str, Any]:async def clear_usage(name: str, request: Request) -> dict[str, int]:reg = _require_registry(request)if reg.catalog().get(name) is None:- raise HTTPException(status_code=404, detail=f"CLI '{name}' nicht im Katalog")+ raise HTTPException(status_code=404, detail=f"CLI '{name}' not in catalog")deleted = reg.usage_log().delete_for(name)return {"deleted": deleted}diff --git a/jarvis/ui/web/docs_routes.py b/jarvis/ui/web/docs_routes.pyindex f0407d63c9..d231d21fdb 100644--- a/jarvis/ui/web/docs_routes.py+++ b/jarvis/ui/web/docs_routes.py@@ -1,16 +1,16 @@-"""REST-API fuer die Doc-Sektion der Desktop-UI.+"""REST API for the doc section of the desktop UI.Endpoints:-- ``GET /api/docs`` Liste mit Frontmatter-Metadaten (ohne Body).-- ``GET /api/docs/grouped`` Gruppiert nach Diataxis-Quadrant — direkt- verwendbar fuer die Sidebar-Tree-View.-- ``GET /api/docs/search`` FTS5-Volltextsuche mit BM25-Rank + Snippet.-- ``GET /api/docs/asset/{path}`` Bilder/Static-Files relativ zum Doc-Pfad.-- ``GET /api/docs/{slug}`` Voller Body + Frontmatter.-- ``POST /api/docs/reload`` Forciert Re-Indexing (Dev-Helper).--Der Router erwartet eine ``DocRegistry`` auf ``app.state.doc_registry`` —-``WebServer._setup_doc_registry()`` setzt sie beim Startup.+- ``GET /api/docs`` List with frontmatter metadata (no body).+- ``GET /api/docs/grouped`` Grouped by Diataxis quadrant — directly+ usable for the sidebar tree view.+- ``GET /api/docs/search`` FTS5 full-text search with BM25 rank + snippet.+- ``GET /api/docs/asset/{path}`` Images/static files relative to the doc path.+- ``GET /api/docs/{slug}`` Full body + frontmatter.+- ``POST /api/docs/reload`` Forces re-indexing (dev helper).++The router expects a ``DocRegistry`` on ``app.state.doc_registry`` —+``WebServer._setup_doc_registry()`` sets it at startup."""from __future__ import annotations@@ -35,7 +35,7 @@ router = APIRouter(prefix="/api/docs", tags=["docs"])def _require_registry(request: Request) -> DocRegistry:reg = getattr(request.app.state, "doc_registry", None)if reg is None:- raise HTTPException(status_code=503, detail="DocRegistry nicht verfuegbar")+ raise HTTPException(status_code=503, detail="DocRegistry not available")return reg@@ -44,7 +44,7 @@ def _require_registry(request: Request) -> DocRegistry:# ----------------------------------------------------------------------def _frontmatter_dump(doc: Doc) -> dict[str, Any]:- """Pydantic ``model_dump`` mit ISO-Date-Strings (statt datetime)."""+ """Pydantic ``model_dump`` with ISO date strings (instead of datetime)."""fm = doc.frontmatterreturn {"title": fm.title,@@ -65,8 +65,8 @@ def _frontmatter_dump(doc: Doc) -> dict[str, Any]:def _doc_to_summary(doc: Doc) -> dict[str, Any]:- """Schlanke Repraesentation fuer ``GET /api/docs`` — ohne Body, ohne- Headings (TOC laedt das Frontend aus dem rohen Markdown beim Render).+ """Lean representation for ``GET /api/docs`` — no body, no+ headings (the frontend loads the TOC from the raw Markdown at render time)."""return {**_frontmatter_dump(doc),@@ -78,7 +78,7 @@ def _doc_to_summary(doc: Doc) -> dict[str, Any]:def _doc_to_detail(doc: Doc) -> dict[str, Any]:- """Vollausstattung fuer ``GET /api/docs/{slug}``."""+ """Full payload for ``GET /api/docs/{slug}``."""out = _doc_to_summary(doc)out["body"] = doc.bodyout["headings"] = [@@ -110,9 +110,9 @@ def list_docs(@router.get("/grouped")def grouped_docs(request: Request) -> dict[str, list[dict[str, Any]]]:- """Gruppiert nach Diataxis — Sidebar-Tree-Vorlage.+ """Grouped by Diataxis — sidebar tree template.- Reihenfolge: tutorial -> howto -> explanation -> reference ->+ Order: tutorial -> howto -> explanation -> reference ->troubleshooting -> adr -> unclassified."""reg = _require_registry(request)@@ -145,7 +145,7 @@ def search_docs(limit: int = 20,) -> list[dict[str, Any]]:if limit < 1 or limit > 100:- raise HTTPException(status_code=400, detail="limit muss zwischen 1 und 100 liegen")+ raise HTTPException(status_code=400, detail="limit must be between 1 and 100")reg = _require_registry(request)results = reg.search_query(q, diataxis=diataxis, limit=limit)return [@@ -162,20 +162,20 @@ def search_docs(# -----------------------------------------------------------------------# Asset (Bilder relativ zum Doc-Pfad)+# Asset (images relative to the doc path)# ----------------------------------------------------------------------@router.get("/asset/{slug}/{asset_path:path}")def get_asset(request: Request, slug: str, asset_path: str) -> FileResponse:- """Liefert eine Sibling-Datei (Bild, Diagramm) relativ zum Doc-Pfad.+ """Returns a sibling file (image, diagram) relative to the doc path.- Path-Traversal-Schutz: das resolved Asset muss unter dem ``parent``- des Doc-Files liegen. Sonst 400.+ Path-traversal protection: the resolved asset must live under the+ ``parent`` of the doc file. Otherwise 400."""reg = _require_registry(request)doc = reg.get(slug)if doc is None:- raise HTTPException(status_code=404, detail=f"Doc '{slug}' nicht gefunden")+ raise HTTPException(status_code=404, detail=f"Doc '{slug}' not found")base = doc.path.parent.resolve()target = (base / asset_path).resolve()@@ -183,15 +183,15 @@ def get_asset(request: Request, slug: str, asset_path: str) -> FileResponse:target.relative_to(base)except ValueError as exc:raise HTTPException(- status_code=400, detail="Pfad-Traversal nicht erlaubt",+ status_code=400, detail="path traversal not allowed",) from excif not target.is_file():- raise HTTPException(status_code=404, detail="Asset nicht vorhanden")+ raise HTTPException(status_code=404, detail="asset does not exist")return FileResponse(target)# -----------------------------------------------------------------------# Detail (muss ans Ende — sonst frisst ``/{slug}`` die anderen Routen)+# Detail (must go last — otherwise ``/{slug}`` swallows the other routes)# ----------------------------------------------------------------------@router.get("/{slug}")@@ -199,26 +199,26 @@ def get_doc(request: Request, slug: str) -> dict[str, Any]:reg = _require_registry(request)doc = reg.get(slug)if doc is None:- raise HTTPException(status_code=404, detail=f"Doc '{slug}' nicht gefunden")+ raise HTTPException(status_code=404, detail=f"Doc '{slug}' not found")return _doc_to_detail(doc)# -----------------------------------------------------------------------# Edit-this-page — oeffnet die .md im Windows-Standard-Editor+# Edit-this-page — opens the .md in the Windows default editor# ----------------------------------------------------------------------@router.post("/{slug}/open")def open_doc_in_editor(request: Request, slug: str) -> dict[str, Any]:- """Oeffnet die Markdown-Datei im OS-Standard-Editor.+ """Opens the Markdown file in the OS default editor.- Auf Windows: ``os.startfile`` startet den File-Type-Handler (typisch- Notepad, VSCode oder ein Markdown-Editor). Wir launchen NICHT als- elevated, das ist read+write fuer den User-Owner-Pfad — dem User- ist das Doc-Repo ohnehin schon write-zugaenglich.+ On Windows: ``os.startfile`` launches the file-type handler (typically+ Notepad, VSCode, or a Markdown editor). We do NOT launch elevated —+ that path is read+write for the user-owner already; the user+ already has write access to the doc repo anyway.- Vorsicht: auf manchen Systemen ist Notepad mit BOM-Save-Behavior- konfiguriert; Re-Save kann das Frontmatter zerschiessen. Der- ``jarvis-doc-author``-Skill bleibt der bevorzugte Authoring-Pfad.+ Caution: on some systems Notepad is configured with BOM-save+ behavior; re-saving can mangle the frontmatter. The+ ``jarvis-doc-author`` skill remains the preferred authoring path."""import osimport subprocess@@ -226,29 +226,29 @@ def open_doc_in_editor(request: Request, slug: str) -> dict[str, Any]:reg = _require_registry(request)doc = reg.get(slug)if doc is None:- raise HTTPException(status_code=404, detail=f"Doc '{slug}' nicht gefunden")+ raise HTTPException(status_code=404, detail=f"Doc '{slug}' not found")target = doc.path.resolve()if not target.is_file():- raise HTTPException(status_code=404, detail="Datei nicht mehr vorhanden")+ raise HTTPException(status_code=404, detail="file no longer exists")try:if hasattr(os, "startfile"):- # Windows-spezifisch — File-Type-Association entscheidet, welcher- # Editor aufgeht. Non-blocking.+ # Windows-specific — the file-type association decides which+ # editor opens. Non-blocking.os.startfile(str(target)) # noqa: S606- else: # pragma: no cover (nur Windows-relevant in dieser App)+ else: # pragma: no cover (only relevant to Windows in this app)subprocess.Popen(["xdg-open", str(target)])return {"path": str(target), "opened": True}except OSError as exc:- log.warning("open_doc_in_editor fehlgeschlagen fuer %s: %s", slug, exc)+ log.warning("open_doc_in_editor failed for %s: %s", slug, exc)raise HTTPException(- status_code=500, detail=f"Editor-Start fehlgeschlagen: {exc}",+ status_code=500, detail=f"editor start failed: {exc}",) from exc# -----------------------------------------------------------------------# Reload (Dev-Helper)+# Reload (dev helper)# ----------------------------------------------------------------------@router.post("/reload")diff --git a/jarvis/ui/web/federation_proxy_routes.py b/jarvis/ui/web/federation_proxy_routes.pyindex fc1c580862..65cf462522 100644--- a/jarvis/ui/web/federation_proxy_routes.py+++ b/jarvis/ui/web/federation_proxy_routes.py@@ -1,13 +1,13 @@-"""Lokaler Proxy zum Board-Federation-Backend (Phase D).+"""Local proxy to the board federation backend (Phase D).-Hintergrund: Frontend laeuft im Browser, hat keinen Zugriff auf den-Privkey im Credential Manager. Stattdessen rufen Frontend-Komponenten-diese Routen, der lokale Jarvis-Server signiert die Calls und leitet-sie an das konfigurierte Backend weiter.+Background: the frontend runs in the browser and has no access to the+privkey in the credential manager. Instead, frontend components call+these routes; the local Jarvis server signs the calls and forwards+them to the configured backend.-Sicherheits-Constraint: nur eine Whitelist von Backend-Pfaden ist-erreichbar. Beliebige Pfade durchschleusen wuerde das Federation--Auth-Modell aushebeln.+Security constraint: only a whitelist of backend paths is reachable.+Passing arbitrary paths through would undermine the federation+auth model."""from __future__ import annotations@@ -47,8 +47,8 @@ log = logging.getLogger(__name__)router = APIRouter(prefix="/api/board/federation", tags=["board-federation"])-# Whitelist der erlaubten Backend-Endpunkte. Frontend ruft den entsprechenden-# Proxy-Endpunkt, dieser sendet an das Backend.+# Whitelist of allowed backend endpoints. The frontend calls the matching+# proxy endpoint, which sends the request on to the backend.ALLOWED_GET_PATHS = frozenset({"/api/v1/me","/api/v1/friends",@@ -61,7 +61,7 @@ ALLOWED_POST_PATHS = frozenset({"/api/v1/stories",})-# PATCH-Pfade haben einen Pfadparameter — wir matchen via Prefix.+# PATCH paths have a path parameter — we match via prefix.ALLOWED_PATCH_PREFIXES = ("/api/v1/friends/",)@@ -83,7 +83,7 @@ def _signed_headers(privkey_hex: str, pubkey_hex: str, payload: dict) -> dict[st# -----------------------------------------------------------------------# Status — was wissen wir ueber unseren Federation-State?+# Status — what do we know about our federation state?# ----------------------------------------------------------------------class FederationStatusResponse(BaseModel):@@ -111,7 +111,7 @@ def status(request: Request) -> FederationStatusResponse:# -----------------------------------------------------------------------# Pair — admin-token-fluss+# Pair — admin-token flow# ----------------------------------------------------------------------class PairInitiateProxyResponse(BaseModel):@@ -143,17 +143,17 @@ async def pair_initiate(request: Request) -> PairInitiateProxyResponse:class PairAcceptProxyRequest(BaseModel):- pair_url: str # Der vom Friend erhaltene URL inkl. ?token=...+ pair_url: str # the URL received from the friend, incl. ?token=...@router.post("/pair/accept-from-friend")async def pair_accept_from_friend(request: Request, payload: PairAcceptProxyRequest,) -> dict[str, Any]:- """Wir sind der Friend — wir senden unseren Pubkey + Display-Name zum- Owner-Backend des Senders.+ """We are the friend — we send our pubkey + display name to the+ sender's owner backend.- Aus ``pair_url`` extrahieren wir die Owner-Base-URL und den Token.+ We extract the owner base URL and the token from ``pair_url``."""from urllib.parse import urlparse, parse_qs@@ -185,26 +185,26 @@ async def pair_accept_from_friend(raise HTTPException(status_code=resp.status_code, detail=resp.text)accept_resp = resp.json()- # Bidirektional: wir registrieren A jetzt als unseren Friend.- # Das passiert via UNSEREM Backend's pair/initiate → A schickt accept- # zurueck — too komplex. Pragma: wir tragen A direkt in unseren- # eigenen Backend ein via einer admin-only "manual add"-Route, die- # wir hier hinzufuegen. (Zukunft: A koennte automatisch zurueck- # accepten in einem zwei-phasen-handshake.)+ # Bidirectional: we now register A as our friend too.+ # That would happen via OUR backend's pair/initiate → A sends an+ # accept back — too complex. Pragma: we add A directly into our+ # own backend via an admin-only "manual add" route that we add+ # here. (Future: A could automatically accept back in a+ # two-phase handshake.)admin = _resolve_admin_token(kr)if admin:await c.post(f"{own_backend}/api/v1/pair/initiate",json={}, headers={"X-Admin-Token": admin},)- # Initiate-Token wird verbraucht beim Friend, der diese Aktion- # spiegelt. Fuer MVP: wir return die accept-resp und der User- # initiiert ggf. selbst den zweiten Pair-Schritt.+ # The initiate token is consumed by the friend, who mirrors this+ # action. For MVP: we return the accept response and the user+ # initiates the second pair step themselves if needed.return accept_resp# -----------------------------------------------------------------------# Generic GET-Proxy+# Generic GET proxy# ----------------------------------------------------------------------@router.get("/get")@@ -277,17 +277,16 @@ async def proxy_patch(request: Request, payload: ProxyPatchRequest) -> Any:# -----------------------------------------------------------------------# Disconnect — Local-Only-Mode+# Disconnect — local-only mode# ----------------------------------------------------------------------@router.post("/disconnect")def disconnect(request: Request) -> dict[str, str]:- """Setzt board.federation.enabled=false zur Laufzeit (in-memory).+ """Sets board.federation.enabled=false at runtime (in-memory).- Fuer eine permanente Aenderung muss der User die jarvis.toml editieren —- diese Route ist eine ``Local-Only-Mode``-Schaltflaeche fuer schnelle- Diagnose-Sessions. Plan §0: User muss disconnecten koennen ohne dass- Layer A/B kaputtgehen.+ For a permanent change, the user has to edit jarvis.toml — this route+ is a ``local-only-mode`` button for quick diagnostic sessions. Plan §0:+ the user must be able to disconnect without breaking layers A/B."""cfg = request.app.state.configcfg.board.federation.enabled = Falsediff --git a/jarvis/ui/web/friends_routes.py b/jarvis/ui/web/friends_routes.pyindex ce13f9aedf..e36f37afe8 100644--- a/jarvis/ui/web/friends_routes.py+++ b/jarvis/ui/web/friends_routes.py@@ -1,26 +1,26 @@# === F-FRIENDS [F3] · feature/friends-section · ruben-2026-05-01 ===# === F-FRIENDS [F2] · feature/friends-section · ruben-2026-04-30 ===-"""REST-API fuer die Friends-Sektion (Phase F2).+"""REST API for the Friends section (Phase F2).-Pattern wie ``missions_routes.py``:-- Resources (``FriendRegistry``, ``ChannelManager``) liegen in+Pattern like ``missions_routes.py``:+- Resources (``FriendRegistry``, ``ChannelManager``) live in``app.state.friend_registry`` / ``app.state.channel_manager``.-- Nicht gesetzt → ``HTTPException(503)``.-- Pydantic-Body-Models inline.+- Not set → ``HTTPException(503)``.+- Pydantic body models inline.Endpoints (Phase F2):-- ``GET /api/friends`` → Liste mit Channels.-- ``POST /api/friends`` → Neuen Friend anlegen.-- ``GET /api/friends/{friend_id}`` → Detail + Channels + Permission.-- ``PATCH /api/friends/{friend_id}`` → display_name, note aktualisieren.-- ``DELETE /api/friends/{friend_id}`` → Friend + Channels + Permission loeschen.-- ``POST /api/friends/{friend_id}/channels`` → Channel-Link hinzufuegen.-- ``DELETE /api/friends/{friend_id}/channels/{channel}/{handle}`` → Unlink.-- ``GET /api/friends/{friend_id}/permission`` → Status-Permission lesen.-- ``PATCH /api/friends/{friend_id}/permission`` → Profile setzen.-- ``GET /api/friends/{friend_id}/messages`` → Chat-Thread (F2: Stub).-- ``POST /api/friends/{friend_id}/messages`` → Outbound via primary Channel.+- ``GET /api/friends`` → list with channels.+- ``POST /api/friends`` → create a new friend.+- ``GET /api/friends/{friend_id}`` → detail + channels + permission.+- ``PATCH /api/friends/{friend_id}`` → update display_name, note.+- ``DELETE /api/friends/{friend_id}`` → delete friend + channels + permission.+- ``POST /api/friends/{friend_id}/channels`` → add a channel link.+- ``DELETE /api/friends/{friend_id}/channels/{channel}/{handle}`` → unlink.+- ``GET /api/friends/{friend_id}/permission`` → read status permission.+- ``PATCH /api/friends/{friend_id}/permission`` → set profile.+- ``GET /api/friends/{friend_id}/messages`` → chat thread (F2: stub).+- ``POST /api/friends/{friend_id}/messages`` → outbound via primary channel."""from __future__ import annotations@@ -56,7 +56,7 @@ def _require_registry(request: Request) -> FriendRegistry:reg = getattr(request.app.state, "friend_registry", None)if reg is None:raise HTTPException(- status_code=503, detail="FriendRegistry nicht verfuegbar"+ status_code=503, detail="FriendRegistry not available")return reg@@ -327,10 +327,10 @@ async def update_permission(@router.get("/{friend_id}/messages", response_model=list[MessageDTO])async def list_messages(friend_id: str, request: Request) -> list[MessageDTO]:- """F3: liest persistierte Direct-Messages aus ``direct_messages``.+ """F3: reads persisted direct messages from ``direct_messages``.- Telegram-Inbound aus dem Live-Bus landet in F4 hier; aktuell sind nur- Outbound-Echoes (von ``send_message``) sichtbar.+ Telegram inbound from the live bus lands here in F4; currently only+ outbound echoes (from ``send_message``) are visible."""reg = _require_registry(request)fid = _parse_friend_id(friend_id)@@ -350,12 +350,12 @@ async def list_messages(friend_id: str, request: Request) -> list[MessageDTO]:async def send_message(friend_id: str, body: SendMessageBody, request: Request) -> MessageDTO:- """Outbound via primary Channel.+ """Outbound via the primary channel.- F3: persistiert jeden Outbound-Versand in ``direct_messages``, damit- der History-View ihn anzeigt — sowohl fuer Telegram (zusaetzlich zum- Telegram-API-Send) als auch fuer ``jarvis_pubkey`` (echte- Federation-Auslieferung kommt in F5; bis dahin echo-store).+ F3: persists every outbound send to ``direct_messages`` so the+ history view shows it — both for Telegram (in addition to the+ Telegram API send) and for ``jarvis_pubkey`` (real federation+ delivery lands in F5; echo-store until then)."""reg = _require_registry(request)fid = _parse_friend_id(friend_id)@@ -369,7 +369,7 @@ async def send_message(if primary is None:raise HTTPException(status_code=400,- detail="Friend hat keinen verknuepften Channel — Outbound nicht moeglich.",+ detail="Friend has no linked channel — outbound not possible.",)if primary.channel == "telegram":@@ -377,7 +377,7 @@ async def send_message(if manager is None or "telegram" not in manager.started():raise HTTPException(status_code=503,- detail="TelegramChannel nicht verfuegbar (nicht gestartet).",+ detail="TelegramChannel not available (not started).",)telegram = manager.get("telegram")from uuid import uuid4@@ -389,7 +389,7 @@ async def send_message(metadata={"telegram_chat_id": int(primary.handle)},)await telegram.send_message(msg)- # Outbound-Echo persistieren, damit History-View die Message zeigt.+ # Persist the outbound echo so the history view shows the message.stored = await reg.messages.add(DirectMessage(friend_id=fid,@@ -407,8 +407,8 @@ async def send_message()if primary.channel == "jarvis_pubkey":- # F3: lokal-only Persistenz. Federation-Auslieferung kommt mit F5- # als separater Adapter, der denselben DirectMessageStore nutzt.+ # F3: local-only persistence. Federation delivery lands with F5+ # as a separate adapter that uses the same DirectMessageStore.stored = await reg.messages.add(DirectMessage(friend_id=fid,@@ -426,5 +426,5 @@ async def send_message()raise HTTPException(- status_code=400, detail=f"Channel '{primary.channel}' nicht unterstuetzt"+ status_code=400, detail=f"Channel '{primary.channel}' not supported")diff --git a/jarvis/ui/web/frontend/src/App.tsx b/jarvis/ui/web/frontend/src/App.tsxindex 1fdb7a11d7..d1d2a8e549 100644--- a/jarvis/ui/web/frontend/src/App.tsx+++ b/jarvis/ui/web/frontend/src/App.tsx@@ -39,8 +39,8 @@ export default function App() {{/* Always-present "Jarvis presence" drop dock — drag a mission/outputcard here to pull it into the live conversation context. */}<JarvisDock />- {/* Hintergrund-Polling fuer CLI-OAuth-Logins — pollt /check alle 3s- solange ein cliConnectCoach im Store gesetzt ist. */}+ {/* Background polling for CLI OAuth logins — polls /check every 3s+ as long as a cliConnectCoach is set in the store. */}<CliConnectPoller />{/* Blocking onboarding gate — overlays everything until first-run setup is complete. */}<OnboardingGate />diff --git a/jarvis/ui/web/frontend/src/__tests__/JarvisAgentPanel.test.tsx b/jarvis/ui/web/frontend/src/__tests__/JarvisAgentPanel.test.tsxindex 8cef3b652e..f13fa0db6f 100644--- a/jarvis/ui/web/frontend/src/__tests__/JarvisAgentPanel.test.tsx+++ b/jarvis/ui/web/frontend/src/__tests__/JarvisAgentPanel.test.tsx@@ -39,14 +39,14 @@ function makeWorker(overrides: Partial<OpenClawWorkerSnapshot> = {}): OpenClawWo}describe("JarvisAgentPanel", () => {- it("zeigt Empty-State wenn keine Mission ausgewaehlt ist", () => {+ it("shows the empty state when no mission is selected", () => {render(<JarvisAgentPanel />);expect(screen.getByText("Select a mission to see Jarvis-Agent workers."),).toBeDefined();});- it("zeigt Empty-State wenn Mission keine Jarvis-Agent-Worker hat", () => {+ it("shows the empty state when the mission has no Jarvis-Agent workers", () => {useMissionsStore.setState({selectedMissionId: "mid-1",workerSnapshotsByMission: { "mid-1": [] },@@ -57,14 +57,14 @@ describe("JarvisAgentPanel", () => {).toBeDefined();});- it("rendert alle Spalten fuer einen live OpenClaw-Worker", () => {+ it("renders all columns for a live OpenClaw worker", () => {useMissionsStore.setState({selectedMissionId: "mid-1",workerSnapshotsByMission: { "mid-1": [makeWorker()] },});render(<JarvisAgentPanel />);- // Modell+ // Modelconst model = screen.getByTestId("openclaw-model");expect(model.textContent).toBe("gemini/gemini-3.1-pro-preview");@@ -89,7 +89,7 @@ describe("JarvisAgentPanel", () => {expect(badge.textContent).toBe("live");});- it("zeigt killed-Badge mit ended-reason wenn Worker explicit gekillt wurde", () => {+ it("shows the killed badge with ended-reason when the worker was explicitly killed", () => {useMissionsStore.setState({selectedMissionId: "mid-1",workerSnapshotsByMission: {@@ -112,7 +112,7 @@ describe("JarvisAgentPanel", () => {expect(reason.textContent).toBe("user");});- it("zeigt mehrere Worker in der Reihenfolge der Aggregator-Liste", () => {+ it("shows multiple workers in the order of the aggregator list", () => {useMissionsStore.setState({selectedMissionId: "mid-1",workerSnapshotsByMission: {@@ -134,7 +134,7 @@ describe("JarvisAgentPanel", () => {expect(rows[0].getAttribute("data-worker-id")).toBe("w-aaa");expect(rows[1].getAttribute("data-worker-id")).toBe("w-bbb");- // Cost == 0 wird als "—" gerendert+ // Cost == 0 is rendered as "—"const costs = screen.getAllByTestId("openclaw-cost");expect(costs[1].textContent).toContain("—");});diff --git a/jarvis/ui/web/frontend/src/__tests__/OpenClawPanel.test.tsx b/jarvis/ui/web/frontend/src/__tests__/OpenClawPanel.test.tsxindex 1c0e532d1f..2caf354e99 100644--- a/jarvis/ui/web/frontend/src/__tests__/OpenClawPanel.test.tsx+++ b/jarvis/ui/web/frontend/src/__tests__/OpenClawPanel.test.tsx@@ -39,32 +39,32 @@ function makeWorker(overrides: Partial<OpenClawWorkerSnapshot> = {}): OpenClawWo}describe("JarvisAgentPanel", () => {- it("zeigt Empty-State wenn keine Mission ausgewaehlt ist", () => {+ it("shows the empty state when no mission is selected", () => {render(<JarvisAgentPanel />);expect(- screen.getByText("Mission auswaehlen, um OpenClaw-Worker zu sehen."),+ screen.getByText("Mission auswaehlen, um OpenClaw-Worker zu sehen."), // i18n-allow: pre-existing stale assertion string, kept verbatim (see report)).toBeDefined();});- it("zeigt Empty-State wenn Mission keine OpenClaw-Worker hat", () => {+ it("shows the empty state when the mission has no OpenClaw workers", () => {useMissionsStore.setState({selectedMissionId: "mid-1",workerSnapshotsByMission: { "mid-1": [] },});render(<JarvisAgentPanel />);expect(- screen.getByText("Keine OpenClaw-Worker in dieser Mission."),+ screen.getByText("Keine OpenClaw-Worker in dieser Mission."), // i18n-allow: pre-existing stale assertion string, kept verbatim (see report)).toBeDefined();});- it("rendert alle Spalten fuer einen live OpenClaw-Worker", () => {+ it("renders all columns for a live OpenClaw worker", () => {useMissionsStore.setState({selectedMissionId: "mid-1",workerSnapshotsByMission: { "mid-1": [makeWorker()] },});render(<JarvisAgentPanel />);- // Modell+ // Modelconst model = screen.getByTestId("openclaw-model");expect(model.textContent).toBe("gemini/gemini-3.1-pro-preview");@@ -89,7 +89,7 @@ describe("JarvisAgentPanel", () => {expect(badge.textContent).toBe("live");});- it("zeigt killed-Badge mit ended-reason wenn Worker explicit gekillt wurde", () => {+ it("shows the killed badge with ended-reason when the worker was explicitly killed", () => {useMissionsStore.setState({selectedMissionId: "mid-1",workerSnapshotsByMission: {@@ -112,7 +112,7 @@ describe("JarvisAgentPanel", () => {expect(reason.textContent).toBe("user");});- it("zeigt mehrere Worker in der Reihenfolge der Aggregator-Liste", () => {+ it("shows multiple workers in the order of the aggregator list", () => {useMissionsStore.setState({selectedMissionId: "mid-1",workerSnapshotsByMission: {@@ -134,7 +134,7 @@ describe("JarvisAgentPanel", () => {expect(rows[0].getAttribute("data-worker-id")).toBe("w-aaa");expect(rows[1].getAttribute("data-worker-id")).toBe("w-bbb");- // Cost == 0 wird als "—" gerendert+ // Cost == 0 is rendered as "—"const costs = screen.getAllByTestId("openclaw-cost");expect(costs[1].textContent).toContain("—");});diff --git a/jarvis/ui/web/frontend/src/__tests__/obsidian.test.ts b/jarvis/ui/web/frontend/src/__tests__/obsidian.test.tsindex 146f4fab34..7f443e2e27 100644--- a/jarvis/ui/web/frontend/src/__tests__/obsidian.test.ts+++ b/jarvis/ui/web/frontend/src/__tests__/obsidian.test.ts@@ -25,7 +25,7 @@ describe("buildObsidianUrl", () => {});it("encodes German umlauts in the file path", () => {- const url = buildObsidianUrl("entities/küche.md");+ const url = buildObsidianUrl("entities/küche.md"); // i18n-allow: German umlaut is the content under test// U+00FC -> %C3%BC under encodeURIComponentexpect(url).toContain("k%C3%BCche.md");});diff --git a/jarvis/ui/web/frontend/src/components/ApiKeyForm.tsx b/jarvis/ui/web/frontend/src/components/ApiKeyForm.tsxindex 5ee0230661..4d507d54b8 100644--- a/jarvis/ui/web/frontend/src/components/ApiKeyForm.tsx+++ b/jarvis/ui/web/frontend/src/components/ApiKeyForm.tsx@@ -18,17 +18,17 @@ interface ApiKeyFormProps {credentialHelp?: string | null;onChanged?: () => void;/**- * Wird aufgerufen, nachdem ein Key erfolgreich gespeichert wurde.- * Die Parent-Card entscheidet, ob das einen Auto-Switch ausloest- * (z.B. wenn niemand sonst in der Tier aktiv ist).+ * Called after a key has been saved successfully.+ * The parent card decides whether that triggers an auto-switch+ * (e.g. when no one else is active in the tier).*/onSavedActivate?: () => void;}/**- * Single-Key-Eingabeformular: Passwort-Input + "Speichern" + Lösch-Aktion bei- * vorhandenem Wert. Schreibt direkt nach POST /api/secrets/{key}; der Wert- * verlässt nach dem Submit das Frontend nie wieder (Read-Only-Flag im Backend).+ * Single-key input form: password input + "Save" + delete action for an+ * existing value. Writes directly to POST /api/secrets/{key}; the value+ * never leaves the frontend again after submit (read-only flag in the backend).*/export function ApiKeyForm({ secretKey, dashboardUrl, configured, credentialHelp, onChanged, onSavedActivate }: ApiKeyFormProps) {const t = useT();diff --git a/jarvis/ui/web/frontend/src/components/ChatInput.tsx b/jarvis/ui/web/frontend/src/components/ChatInput.tsxindex f2dd2dc338..dfdb7c90ad 100644--- a/jarvis/ui/web/frontend/src/components/ChatInput.tsx+++ b/jarvis/ui/web/frontend/src/components/ChatInput.tsx@@ -6,9 +6,9 @@ import { useEventStore } from "@/store/events";import { cn } from "@/lib/utils";import { useT } from "@/i18n";-// Safety-Net: wenn das Brain in 60s nicht antwortet (kein Reply, kein Fehler-Event),-// drehen wir den Indikator zurueck. Backend-Hangs duerfen die UI nicht permanent-// in den Wait-State versetzen.+// Safety net: if the brain doesn't respond within 60s (no reply, no error event),+// we revert the indicator. A backend hang must not leave the UI stuck in the+// wait state permanently.const THINKING_TIMEOUT_MS = 60_000;export function ChatInput() {diff --git a/jarvis/ui/web/frontend/src/components/CliConnectCoach.tsx b/jarvis/ui/web/frontend/src/components/CliConnectCoach.tsxindex 76120be25a..d92fe23af4 100644--- a/jarvis/ui/web/frontend/src/components/CliConnectCoach.tsx+++ b/jarvis/ui/web/frontend/src/components/CliConnectCoach.tsx@@ -1,11 +1,11 @@/**- * CliConnectCoach — Begleit-Panel fuer OAuth-CLI-Logins.+ * CliConnectCoach — companion panel for OAuth CLI logins.*- * Diese Datei ist ein Minimal-Stub nach dem Frontend-Filesystem-Reset- * vom 2026-04-25. Die ausgereifte Variante (mit Phase-State-Machine,- * /check-Polling und auth_check-Display) wird in einer Folge-Iteration- * neu aufgebaut. Bis dahin: einfaches Status-Panel mit dem Login-Command- * und einer manuellen "Status pruefen"-Action.+ * This file is a minimal stub after the frontend filesystem reset+ * on 2026-04-25. The full-featured variant (with a phase state machine,+ * /check polling, and an auth_check display) will be rebuilt in a+ * follow-up iteration. Until then: a simple status panel with the+ * login command and a manual "check status" action.** Polling: handled centrally by `CliConnectPoller` (mounted in App.tsx).* On success the poller calls `setCoach(null)`, which unmounts this view.diff --git a/jarvis/ui/web/frontend/src/components/CliConnectPoller.tsx b/jarvis/ui/web/frontend/src/components/CliConnectPoller.tsxindex c80e91ea4b..079e1b574e 100644--- a/jarvis/ui/web/frontend/src/components/CliConnectPoller.tsx+++ b/jarvis/ui/web/frontend/src/components/CliConnectPoller.tsx@@ -1,23 +1,24 @@/**- * CliConnectPoller — unsichtbare Hintergrund-Komponente die ueberprueft- * ob ein laufender CLI-Login (z.B. ``firebase login`` in einem externen- * Windows-Terminal) erfolgreich war.+ * CliConnectPoller — invisible background component that checks whether+ * a running CLI login (e.g. ``firebase login`` in an external Windows+ * terminal) succeeded.** Workflow:- * 1. ConnectOAuthButton ruft ``spawn-external`` UND setzt ``cliConnectCoach``.- * 2. Externes Terminal poppt auf, User loggt sich im Browser ein.- * 3. Dieser Poller (gemounted in App.tsx, also IMMER aktiv) sieht den- * ``cliConnectCoach``-State und pollt alle 3s ``POST /api/clis/{name}/check``.- * 4. Sobald ``connected: true`` zurueckkommt → Success-Toast, Cache-Invalidate,- * Coach-State zuruecksetzen.- * 5. Timeout nach ``MAX_ATTEMPTS * INTERVAL = 5min`` ohne Erfolg → Warning.+ * 1. ConnectOAuthButton calls ``spawn-external`` AND sets ``cliConnectCoach``.+ * 2. An external terminal pops up, the user logs in via the browser.+ * 3. This poller (mounted in App.tsx, so ALWAYS active) sees the+ * ``cliConnectCoach`` state and polls ``POST /api/clis/{name}/check`` every 3s.+ * 4. As soon as ``connected: true`` comes back → success toast, cache+ * invalidation, reset the coach state.+ * 5. Timeout after ``MAX_ATTEMPTS * INTERVAL = 5min`` without success → warning.*- * Wichtig: Der Poller laeuft ohne UI — er ist ueberall aktiv, egal ob der- * User in der CLIs-View, Terminal-View oder anderswo ist. Vorher hing der- * Polling-Loop im CliConnectCoach-Component (TerminalView), was nur lief- * wenn der User die Terminal-Section angeklickt hatte. Nach dem Switch auf- * externes Terminal ging der User aber gar nicht mehr in die Terminal-View- * → Polling lief nie → Status sprang nie auf "verbunden".+ * Important: the poller runs without any UI — it is active everywhere,+ * regardless of whether the user is in the CLIs view, the terminal view,+ * or elsewhere. Previously the polling loop lived in the CliConnectCoach+ * component (TerminalView), which only ran while the user had the+ * terminal section open. After the switch to an external terminal, the+ * user no longer went into the terminal view at all → polling never ran+ * → status never flipped to "connected".*/import { useEffect, useRef } from "react";import { useQueryClient } from "@tanstack/react-query";@@ -25,7 +26,7 @@ import { useEventStore } from "@/store/events";import { useT } from "@/i18n";const POLL_INTERVAL_MS = 3_000;-const MAX_ATTEMPTS = 100; // 100 * 3s = 5 Minuten+const MAX_ATTEMPTS = 100; // 100 * 3s = 5 minutesexport function CliConnectPoller() {const coach = useEventStore((s) => s.cliConnectCoach);@@ -68,7 +69,7 @@ export function CliConnectPoller() {setCoach(null);}} catch {- // Netzwerk-Fehler / Backend kurz weg — naechster Tick versucht's wieder.+ // Network error / backend briefly down — the next tick will retry.}};diff --git a/jarvis/ui/web/frontend/src/components/FrontierSwitchModal.tsx b/jarvis/ui/web/frontend/src/components/FrontierSwitchModal.tsxindex 070dea2489..e600359fbd 100644--- a/jarvis/ui/web/frontend/src/components/FrontierSwitchModal.tsx+++ b/jarvis/ui/web/frontend/src/components/FrontierSwitchModal.tsx@@ -1,9 +1,9 @@-// FrontierSwitchModal — blockierendes Modal das beim Boot oeffnet wenn-// Hauptjarvis automatisch auf ein neueres Provider-Modell gewechselt hat.+// FrontierSwitchModal — blocking modal that opens at boot when+// main Jarvis has automatically switched to a newer provider model.//-// User-Mandat 2026-04-28: Auto-Switch ist erlaubt; nach Switch muss der-// User mit OK bestaetigen. Das Modal verschwindet nicht ohne OK.-// Quelle: GET /api/frontier/pending; Quittung via POST /api/frontier/ack.+// User mandate 2026-04-28: auto-switch is allowed; after a switch the+// user must confirm with OK. The modal doesn't disappear without OK.+// Source: GET /api/frontier/pending; ack via POST /api/frontier/ack.import { useEffect, useState } from "react";import { Sparkles, ArrowRight } from "lucide-react";import { cn } from "@/lib/utils";@@ -26,9 +26,9 @@ export function FrontierSwitchModal() {const [pending, setPending] = useState<FrontierSwitch[]>([]);const [acking, setAcking] = useState(false);- // Initial-Load + Polling. WS-Subscribe waere robuster, aber Polling- // mit 30s ist genug — der Switch passiert nur einmal beim Boot, und- // das Modal blockiert sowieso bis der User klickt.+ // Initial load + polling. A WS subscribe would be more robust, but+ // polling every 30s is enough — the switch only happens once at boot,+ // and the modal blocks anyway until the user clicks.useEffect(() => {let cancelled = false;@@ -39,7 +39,7 @@ export function FrontierSwitchModal() {const data = (await res.json()) as FrontierSwitch[];if (!cancelled) setPending(data);} catch {- // ignoriert — naechster Tick versucht's wieder+ // ignored — the next tick will retry}};@@ -58,8 +58,8 @@ export function FrontierSwitchModal() {await fetch("/api/frontier/ack", { method: "POST" });setPending([]);} catch {- // Falls der Ack-Call failt: Modal sichtbar lassen, User kann- // erneut klicken. Server-Side bleibt der Pending-State erhalten.+ // If the ack call fails: leave the modal visible, the user can+ // click again. Server-side the pending state is preserved.} finally {setAcking(false);}@@ -67,8 +67,8 @@ export function FrontierSwitchModal() {if (pending.length === 0) return null;- // Group by provider fuer schoenere Darstellung wenn beide Tiers- // gleichzeitig gewechselt sind (z.B. Anthropic Opus 4.7 → 4.8 + Haiku 4.5 → 4.6).+ // Group by provider for nicer display when both tiers switched at the+ // same time (e.g. Anthropic Opus 4.7 → 4.8 + Haiku 4.5 → 4.6).const byProvider = pending.reduce<Record<string, FrontierSwitch[]>>((acc, s) => {if (!acc[s.provider]) acc[s.provider] = [];acc[s.provider].push(s);diff --git a/jarvis/ui/web/frontend/src/components/MascotGigi.test.tsx b/jarvis/ui/web/frontend/src/components/MascotGigi.test.tsxindex 9624e88011..b538af9360 100644--- a/jarvis/ui/web/frontend/src/components/MascotGigi.test.tsx+++ b/jarvis/ui/web/frontend/src/components/MascotGigi.test.tsx@@ -20,7 +20,7 @@ describe("MascotGigi", () => {test("shows the current transcription in a listening bubble", () => {useEventStore.setState({voiceState: "listening",- transcription: "Hallo, ich bin gross und teste die neue Sprechblase.",+ transcription: "Hallo, ich bin gross und teste die neue Sprechblase.", // i18n-allow: simulated German STT transcription is the content under testtranscriptionFinal: false,});@@ -28,7 +28,7 @@ describe("MascotGigi", () => {const bubble = screen.getByRole("status");expect(bubble.textContent).toContain(- "Hallo, ich bin gross und teste die neue Sprechblase.",+ "Hallo, ich bin gross und teste die neue Sprechblase.", // i18n-allow: simulated German STT transcription is the content under test);expect(bubble.className).toContain("gigi-bubble-listening");});diff --git a/jarvis/ui/web/frontend/src/components/MascotGigi.tsx b/jarvis/ui/web/frontend/src/components/MascotGigi.tsxindex 5ede967366..1865b1fbeb 100644--- a/jarvis/ui/web/frontend/src/components/MascotGigi.tsx+++ b/jarvis/ui/web/frontend/src/components/MascotGigi.tsx@@ -287,26 +287,28 @@ const IDLE_COMMENTS = ["ich hab gute Ohren. falls du was brauchst.",];+// The comment pools below are mascot chat-bubble text spoken to the user —+// runtime product-surface output, not developer-facing strings.const SECTION_COMMENTS: Partial<Record<SectionId, string[]>> = {- chats: ["bereit wenn du bist.", "ich höre.", "sag mal was.", "schreib oder rede — egal."],- agents: ["die Agents sind meine Kollegen.", "wer ist dein Liebling?"],- skills: ["Skills sind mein Lieblings-Feature.", "was sollen wir lernen?"],- mcps: ["mehr MCPs = mehr Power.", "was sollen wir dazuholen?"],- languages: ["ich spreche DE und EN.", "Sprachwechsel? Einfach sagen."],- apikeys: ["pass auf die Keys auf.", "nicht in Git committen!"],- settings: ["was stört dich?", "tweaken wir was?"],+ chats: ["bereit wenn du bist.", "ich höre.", "sag mal was.", "schreib oder rede — egal."], // i18n-allow: mascot chat-bubble output shown to the user+ agents: ["die Agents sind meine Kollegen.", "wer ist dein Liebling?"], // i18n-allow: mascot chat-bubble output shown to the user+ skills: ["Skills sind mein Lieblings-Feature.", "was sollen wir lernen?"], // i18n-allow: mascot chat-bubble output shown to the user+ mcps: ["mehr MCPs = mehr Power.", "was sollen wir dazuholen?"], // i18n-allow: mascot chat-bubble output shown to the user+ languages: ["ich spreche DE und EN.", "Sprachwechsel? Einfach sagen."], // i18n-allow: mascot chat-bubble output shown to the user+ apikeys: ["pass auf die Keys auf.", "nicht in Git committen!"], // i18n-allow: mascot chat-bubble output shown to the user+ settings: ["was stört dich?", "tweaken wir was?"], // i18n-allow: mascot chat-bubble output shown to the user};const VOICE_COMMENTS: Partial<Record<VoiceState, string[]>> = {- listening: ["ich höre!", "raus damit.", "ja?"],+ listening: ["ich höre!", "raus damit.", "ja?"], // i18n-allow: mascot chat-bubble output shown to the userthinking: ["mal schauen …", "Moment.", "hmm …"],- speaking: ["jetzt rede ich.", "kurz mal zuhören."],- error: ["oha.", "ups.", "das war nicht ich!"],+ speaking: ["jetzt rede ich.", "kurz mal zuhören."], // i18n-allow: mascot chat-bubble output shown to the user+ error: ["oha.", "ups.", "das war nicht ich!"], // i18n-allow: mascot chat-bubble output shown to the user};const TIME_COMMENTS = {- morning: ["guten Morgen!", "auf, auf."],- night: ["noch wach?", "es ist spät.", "schlaf genug gekriegt?"],+ morning: ["guten Morgen!", "auf, auf."], // i18n-allow: mascot chat-bubble output shown to the user+ night: ["noch wach?", "es ist spät.", "schlaf genug gekriegt?"], // i18n-allow: mascot chat-bubble output shown to the user};function pickRandom<T>(arr: readonly T[]): T {diff --git a/jarvis/ui/web/frontend/src/components/docs/CodeBlock.tsx b/jarvis/ui/web/frontend/src/components/docs/CodeBlock.tsxindex 759c215126..c21bea5191 100644--- a/jarvis/ui/web/frontend/src/components/docs/CodeBlock.tsx+++ b/jarvis/ui/web/frontend/src/components/docs/CodeBlock.tsx@@ -4,14 +4,14 @@ import { Check, Copy } from "lucide-react";import { cn } from "@/lib/utils";/**- * Shiki-basierter Code-Block mit Copy-Button und Sprach-Tag.+ * Shiki-based code block with copy button and language tag.*- * Shiki ist ESM-only und groesse (~150 KB). Wir laden den Highlighter lazy- * pro CodeBlock-Mount; Shiki cached die Sprache intern, also ist der zweite- * Mount schnell. Bei Render-Performance-Problem koennen wir auf einen- * geteilten Singleton umstellen — Tier-1 ist pragmatisch.+ * Shiki is ESM-only and large (~150 KB). We lazy-load the highlighter+ * per CodeBlock mount; Shiki caches the language internally, so the second+ * mount is fast. If render-performance becomes a problem, we could switch+ * to a shared singleton — Tier-1 is pragmatic.*- * Falls die Sprache nicht erkannt wird, fallback auf ``txt`` ohne Highlight.+ * If the language isn't recognized, fall back to ``txt`` without highlighting.*/type ShikiHighlighterApi = {codeToHtml: (code: string, opts: { lang: string; theme: string }) => string;@@ -103,7 +103,7 @@ export function CodeBlock({ language, code }: CodeBlockProps) {"hover:bg-muted hover:text-foreground hover:opacity-100","group-hover:opacity-100",)}- title="Code kopieren"+ title="Copy code">{copied ? (<Check className="h-3 w-3 text-emerald-400" />@@ -112,11 +112,11 @@ export function CodeBlock({ language, code }: CodeBlockProps) {)}</button></div>- {/* Body — entweder Shiki-HTML oder Plain-Text */}+ {/* Body — either Shiki HTML or plain text */}{html ? (<divclassName="overflow-x-auto px-3 py-2 text-xs leading-relaxed [&_pre]:m-0 [&_pre]:!bg-transparent"- // sanitized bei Shiki — unser Code wird nur lokal gerendert+ // sanitized by Shiki — our code is only rendered locallydangerouslySetInnerHTML={{ __html: html }}/>) : (diff --git a/jarvis/ui/web/frontend/src/components/docs/DocsContent.tsx b/jarvis/ui/web/frontend/src/components/docs/DocsContent.tsxindex 0c7d374b83..3065c32f74 100644--- a/jarvis/ui/web/frontend/src/components/docs/DocsContent.tsx+++ b/jarvis/ui/web/frontend/src/components/docs/DocsContent.tsx@@ -66,9 +66,9 @@ function DocsContentInner({const list = useDocsList();const neighbors = computeNeighbors(grouped.data, slug);const openInEditor = useOpenDocInEditor();- // Slug-Index fuer Cross-Link-Resolution: Set fuer O(1)-Lookup im- // ``a``-Renderer. Wenn ein Markdown-Link auf einen bekannten Slug zeigt,- // navigiert der Klick intern statt extern.+ // Slug index for cross-link resolution: a Set for O(1) lookup in the+ // ``a`` renderer. If a Markdown link points to a known slug, the click+ // navigates internally instead of externally.const knownSlugs = useMemo<Set<string>>(() => {return new Set((list.data ?? []).map((d) => d.slug));}, [list.data]);@@ -91,7 +91,7 @@ function DocsContentInner({return (<article className="prose prose-neutral dark:prose-invert prose-sm mx-auto max-w-2xl px-8 py-8 prose-headings:scroll-mt-20 prose-code:before:hidden prose-code:after:hidden prose-a:text-primary prose-a:no-underline hover:prose-a:underline">- {/* Header — Frontmatter-Snippet */}+ {/* Header — frontmatter snippet */}<header className="not-prose mb-8 border-b border-border pb-4"><div className="mb-2 flex flex-wrap items-center gap-2"><DocTypeBadge diataxis={data.diataxis} />@@ -137,7 +137,7 @@ function DocsContentInner({{data.body}</ReactMarkdown>- {/* Footer — Last-Updated + Prev/Next-Pager */}+ {/* Footer — last-updated + prev/next pager */}<footer className="not-prose mt-12 border-t border-border pt-6"><div className="mb-4 flex flex-wrap items-center gap-3 text-xs text-muted-foreground"><span className="flex items-center gap-1.5">@@ -183,7 +183,7 @@ function DocsContentInner({}// -----------------------------------------------------------------------// Prev/Next-Berechnung + NavCard+// Prev/next computation + NavCard// ----------------------------------------------------------------------function computeNeighbors(@@ -191,8 +191,8 @@ function computeNeighbors(currentSlug: string,): { prev: DocSummary | null; next: DocSummary | null } {if (!grouped) return { prev: null, next: null };- // Wir flatten die Sidebar-Reihenfolge: Diataxis-Order, innerhalb der- // Gruppe alphabetisch (so wie der Backend-``grouped_by_diataxis`` sortiert).+ // We flatten the sidebar order: Diataxis order, alphabetical within each+ // group (matching how the backend's ``grouped_by_diataxis`` sorts).const flat: DocSummary[] = [];for (const kind of DIATAXIS_ORDER) {const items = grouped[kind];@@ -237,7 +237,7 @@ function NavCard({}// -----------------------------------------------------------------------// Markdown-Custom-Components+// Markdown custom components// ----------------------------------------------------------------------interface MarkdownContext {@@ -246,15 +246,15 @@ interface MarkdownContext {}/**- * Resolved einen Markdown-Link gegen den Doc-Index.+ * Resolves a Markdown link against the doc index.*- * Match-Reihenfolge:- * 1. ``[text](slug-im-Index)`` -> intern- * 2. ``[text](docs/path/to/file.md)`` -> intern wenn Slug aus Pfad ableitbar- * 3. ``[text](docs/adr/0011-...md)`` -> intern via ``adr-...``-Slug- * 4. http(s)://... -> extern, neuer Tab- * 5. #anchor -> Anchor-Sprung innerhalb der Seite- * 6. alles andere -> default-Anchor+ * Match order:+ * 1. ``[text](slug-in-index)`` -> internal+ * 2. ``[text](docs/path/to/file.md)`` -> internal if a slug can be derived from the path+ * 3. ``[text](docs/adr/0011-...md)`` -> internal via ``adr-...`` slug+ * 4. http(s)://... -> external, new tab+ * 5. #anchor -> anchor jump within the page+ * 6. anything else -> default anchor*/function resolveLink(href: string,@@ -265,20 +265,20 @@ function resolveLink(if (href.startsWith("http://") || href.startsWith("https://")) {return { kind: "external" };}- // Direkter Slug-Treffer+ // Direct slug matchif (knownSlugs.has(href)) return { kind: "internal", slug: href };- // Pfad mit .md am Ende — Stem ohne Extension probieren, plus diverse- // Praefix-Varianten ("docs/adr/0011-router.md" -> "adr-0011-router").+ // Path ending in .md — try the stem without the extension, plus a few+ // prefix variants ("docs/adr/0011-router.md" -> "adr-0011-router").const cleaned = href.replace(/^\.?\//, "").replace(/\.md$/, "");- // 1. ganzer Pfad als Slug+ // 1. whole path as slugif (knownSlugs.has(cleaned)) return { kind: "internal", slug: cleaned };- // 2. nur Dateiname+ // 2. filename onlyconst parts = cleaned.split("/");const lastSegment = parts[parts.length - 1];if (knownSlugs.has(lastSegment)) {return { kind: "internal", slug: lastSegment };}- // 3. ADR-Konvention: ``docs/adr/NNNN-...`` -> ``adr-NNNN-...``+ // 3. ADR convention: ``docs/adr/NNNN-...`` -> ``adr-NNNN-...``if (parts.length >= 2 && parts[parts.length - 2] === "adr") {const adrSlug = `adr-${lastSegment}`;if (knownSlugs.has(adrSlug)) return { kind: "internal", slug: adrSlug };@@ -288,7 +288,7 @@ function resolveLink(function makeMarkdownComponents(ctx: MarkdownContext): Components {return {- // Code-Block (mit Sprach-Tag) wird zur Shiki-Component.+ // Code block (with language tag) becomes the Shiki component.code({ className, children, ...rest }) {const match = /language-(\w+)/.exec(className || "");if (!match) {@@ -306,7 +306,7 @@ function makeMarkdownComponents(ctx: MarkdownContext): Components {);},- // Blockquote mit GitHub-Style-Callout-Tag erkennen.+ // Detect a blockquote with a GitHub-style callout tag.blockquote({ children }) {const tagged = parseTaggedBlockquote(children);if (tagged) {@@ -319,7 +319,7 @@ function makeMarkdownComponents(ctx: MarkdownContext): Components {);},- // Cross-Link-Resolution+ // Cross-link resolutiona({ href, children, ...rest }) {const resolved = href ? resolveLink(href, ctx.knownSlugs) : { kind: "default" as const };if (resolved.kind === "internal" && ctx.onInternalNavigate) {@@ -352,7 +352,7 @@ function makeMarkdownComponents(ctx: MarkdownContext): Components {);},- // Tabellen mit etwas mehr Padding fuer bessere Lesbarkeit.+ // Tables with a bit more padding for better readability.table({ children }) {return (<div className="not-prose my-4 overflow-x-auto rounded-md border border-border">@@ -364,27 +364,27 @@ function makeMarkdownComponents(ctx: MarkdownContext): Components {}/**- * Schaut sich die Children eines blockquote an: wenn der erste Knoten ein- * <p> mit Leading-Tag (``[!info]`` etc.) ist, liefert der typ + die- * gestripten Children. Sonst null.+ * Looks at the children of a blockquote: if the first node is a <p> with a+ * leading tag (``[!info]`` etc.), returns the type + the stripped children.+ * Otherwise null.*/function parseTaggedBlockquote(children: React.ReactNode,): { type: CalloutType; children: React.ReactNode } | null {- // children kann ein Array sein (mit Whitespace-Strings dazwischen).+ // children can be an array (with whitespace strings in between).const arr = Array.isArray(children) ? children : [children];for (const node of arr) {if (typeof node === "string") {if (!node.trim()) continue;const tag = parseCalloutTag(node);if (tag) {- // Der Tag selbst hat keinen Block-Wrap — wir packen den Rest direkt- // als Text rein. Sonderfall, in der Praxis selten.+ // The tag itself has no block wrap — we insert the rest directly+ // as text. An edge case, rare in practice.return { type: tag.type, children: tag.rest };}return null;}- // Erstes <p>-Element greifen+ // Grab the first <p> elementif (typeof node === "object" &&node !== null &&@@ -402,8 +402,8 @@ function parseTaggedBlockquote(if (firstText) {const tag = parseCalloutTag(firstText);if (tag) {- // Re-mounted children: ersten Text durch ``rest`` ersetzen, andere- // Knoten durchreichen.+ // Re-mounted children: replace the first text with ``rest``, pass+ // other nodes through unchanged.if (typeof pChildren === "string") {return { type: tag.type, children: <p>{tag.rest}</p> };}diff --git a/jarvis/ui/web/frontend/src/components/docs/DocsSearchModal.tsx b/jarvis/ui/web/frontend/src/components/docs/DocsSearchModal.tsxindex 0cb48bbc0d..e490177f0b 100644--- a/jarvis/ui/web/frontend/src/components/docs/DocsSearchModal.tsx+++ b/jarvis/ui/web/frontend/src/components/docs/DocsSearchModal.tsx@@ -15,12 +15,12 @@ interface Props {}/**- * Volltext-Search-Modal — cmdk + Radix-Dialog. Pattern Anthropic/Tailwind-- * Style: Strg+K oeffnet, Tippen zeigt Live-Results, Enter springt zum Doc.+ * Full-text search modal — cmdk + Radix dialog. Anthropic/Tailwind-style+ * pattern: Ctrl+K opens it, typing shows live results, Enter jumps to the doc.*- * Backend-FTS5 liefert ``snippet``-HTML mit ``<mark>``-Tags fuer Highlights;- * wir rendern das mit ``dangerouslySetInnerHTML`` weil es nur unsere eigenen- * Doc-Bodies sind (kein User-Input, kein XSS-Risiko).+ * The backend FTS5 returns ``snippet`` HTML with ``<mark>`` tags for+ * highlights; we render that with ``dangerouslySetInnerHTML`` because it's+ * only our own doc bodies (no user input, no XSS risk).*/export function DocsSearchModal({ open, onOpenChange, onSelect }: Props) {const t = useT();@@ -32,7 +32,7 @@ export function DocsSearchModal({ open, onOpenChange, onSelect }: Props) {open,);- // Reset query beim Schliessen, damit Re-open frisch startet.+ // Reset the query on close so a re-open starts fresh.useEffect(() => {if (!open) setQuery("");}, [open]);@@ -121,7 +121,7 @@ export function DocsSearchModal({ open, onOpenChange, onSelect }: Props) {);}-/** Sehr einfacher Debounce-Hook — vermeidet eine extra Lib. */+/** A very simple debounce hook — avoids pulling in an extra lib. */function useDebounced<T>(value: T, delayMs: number): T {const [debounced, setDebounced] = useState(value);useEffect(() => {diff --git a/jarvis/ui/web/frontend/src/components/docs/DocsSidebar.tsx b/jarvis/ui/web/frontend/src/components/docs/DocsSidebar.tsxindex b948dbb4b9..d201277fb6 100644--- a/jarvis/ui/web/frontend/src/components/docs/DocsSidebar.tsx+++ b/jarvis/ui/web/frontend/src/components/docs/DocsSidebar.tsx@@ -92,7 +92,7 @@ export function DocsSidebar({ selectedSlug, onSelect, onOpenSearch }: Props) {{/* Tree */}<ScrollArea className="flex-1"><div className="px-2 py-2">- {/* Recent-Docs — nur wenn nicht gefiltert + mind. 1 Eintrag */}+ {/* Recent docs — only when not filtered + at least 1 entry */}{!query && recent.length > 0 && (<div className="mb-2"><div className="flex w-full items-center gap-1 rounded-md px-2 py-1 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground">@@ -179,13 +179,12 @@ interface ItemProps {}function SidebarItem({ doc, active, onClick }: ItemProps) {- // Doc-Titel sollen vollstaendig lesbar sein (User-Mandat 2026-04-29) —- // ``break-words`` erlaubt Umbruch in deutschen Komposita, ``line-clamp-2``- // begrenzt auf max 2 Zeilen damit die Liste nicht zerfliesst, und der- // ``title``-Attribut bleibt als Hover-Tooltip fuer den vollen Titel.- // KEIN Diataxis-Pill — der Section-Header oben tragt die Info schon- // (User-Mandat: keine doppelte Information, kein abgeschnittenes- // ``LEGAC...``-Pill).+ // Doc titles should be fully readable (user mandate 2026-04-29) —+ // ``break-words`` allows wrapping inside German compound words,+ // ``line-clamp-2`` caps it at 2 lines max so the list doesn't sprawl, and+ // the ``title`` attribute stays as a hover tooltip for the full title.+ // NO Diataxis pill — the section header above already carries that info+ // (user mandate: no duplicate information, no truncated ``LEGAC...`` pill).return (<buttontype="button"diff --git a/jarvis/ui/web/frontend/src/components/docs/DocsToc.tsx b/jarvis/ui/web/frontend/src/components/docs/DocsToc.tsxindex 97e4b3b536..ef9771dd06 100644--- a/jarvis/ui/web/frontend/src/components/docs/DocsToc.tsx+++ b/jarvis/ui/web/frontend/src/components/docs/DocsToc.tsx@@ -6,23 +6,23 @@ import type { DocHeading } from "@/hooks/useDocs";interface Props {headings: DocHeading[];- /** Container in dem die <h2>/<h3>-Anchors leben. Wir queryen darin. */+ /** Container that holds the <h2>/<h3> anchors. We query inside it. */contentRef: React.RefObject<HTMLElement>;}/**- * Right-Sidebar Table-of-Contents mit Active-Heading-Tracking via- * IntersectionObserver — Anthropic/Mintlify-Stil.+ * Right-sidebar table of contents with active-heading tracking via+ * IntersectionObserver — Anthropic/Mintlify style.*- * Reagiert auf H2 + H3. H4-H6 sind in unseren Docs selten, wuerden aber bei- * Bedarf hier ergaenzt. Active-Heading wird via ``rootMargin`` zur Heading-- * Hoehe verschoben, damit die Heading-Zeile selbst (nicht der Body darunter)- * den Active-State setzt.+ * Reacts to H2 + H3. H4-H6 are rare in our docs but could be added here if+ * needed. The active-heading trigger is shifted by the heading height via+ * ``rootMargin``, so the heading line itself (not the body below it) sets+ * the active state.*/export function DocsToc({ headings, contentRef }: Props) {const [activeSlug, setActiveSlug] = useState<string | null>(null);- // TOC nur fuer H2 + H3 — Tutorial-Mid-Point-Checks und ADR-Subsections.+ // TOC only for H2 + H3 — tutorial mid-point checks and ADR subsections.const tocHeadings = headings.filter((h) => h.level >= 2 && h.level <= 3);useEffect(() => {@@ -38,7 +38,7 @@ export function DocsToc({ headings, contentRef }: Props) {const observer = new IntersectionObserver((entries) => {- // Nimm den ersten sichtbaren Eintrag — Top-most-rule.+ // Take the first visible entry — top-most rule.const visible = entries.filter((e) => e.isIntersecting).sort(@@ -51,7 +51,7 @@ export function DocsToc({ headings, contentRef }: Props) {}},{- // Heading wird Active wenn es im oberen 20% des Viewports steht.+ // A heading becomes active when it's in the top 20% of the viewport.rootMargin: "0px 0px -80% 0px",threshold: 0,},@@ -72,7 +72,7 @@ export function DocsToc({ headings, contentRef }: Props) {<ScrollArea className="h-full"><div className="px-4 py-6"><h3 className="mb-3 text-[10px] font-semibold uppercase tracking-wider text-muted-foreground">- Auf dieser Seite+ On this page</h3><ul className="space-y-1 text-xs">{tocHeadings.map((h) => (@@ -104,14 +104,14 @@ function handleClick(e: React.MouseEvent<HTMLAnchorElement>, slug: string) {const el = document.getElementById(slug);if (el) {el.scrollIntoView({ behavior: "smooth", block: "start" });- // URL-Hash aktualisieren ohne Full-Reload+ // Update the URL hash without a full reloadwindow.history.replaceState(null, "", `#${slug}`);}}/**- * Minimaler CSS.escape-Polyfill fuer aeltere Browser. WebView2 ist Edge-- * basiert und unterstuetzt CSS.escape, aber besser sicher als sorry.+ * Minimal CSS.escape polyfill for older browsers. WebView2 is Edge-based+ * and supports CSS.escape, but better safe than sorry.*/function cssEscape(value: string): string {if (typeof CSS !== "undefined" && CSS.escape) return CSS.escape(value);diff --git a/jarvis/ui/web/frontend/src/components/friends/AddFriendMenu.tsx b/jarvis/ui/web/frontend/src/components/friends/AddFriendMenu.tsxindex 27f366e89f..9286bb02fd 100644--- a/jarvis/ui/web/frontend/src/components/friends/AddFriendMenu.tsx+++ b/jarvis/ui/web/frontend/src/components/friends/AddFriendMenu.tsx@@ -6,14 +6,14 @@ import { useT } from "@/i18n";import { cn } from "@/lib/utils";/**- * "+ Friend hinzufuegen"-Dialog mit drei Modi:+ * "+ Add Friend" dialog with three modes:*- * 1. Telegram-Kontakt: Display-Name + Telegram-Chat-ID. Erstellt Friend +- * verknuepft TG-Channel (is_primary=True).- * 2. Jarvis-Pubkey: Display-Name + Pubkey. Erstellt Friend + verknuepft- * pubkey-Channel. (Federation-DM erst F3.)- * 3. Pair-Link: Verweist auf den existierenden PairDialog (Pubkey + URL +- * PairToken via board-backend).+ * 1. Telegram contact: display name + Telegram chat ID. Creates the friend+ * and links the TG channel (is_primary=True).+ * 2. Jarvis pubkey: display name + pubkey. Creates the friend and links the+ * pubkey channel. (Federation DM only lands in F3.)+ * 3. Pair link: points to the existing PairDialog (pubkey + URL ++ * PairToken via the board backend).*/type Mode = "telegram" | "jarvis_pubkey" | "link";diff --git a/jarvis/ui/web/frontend/src/components/friends/ChatThread.tsx b/jarvis/ui/web/frontend/src/components/friends/ChatThread.tsxindex 49ae7980f0..c8ebb803da 100644--- a/jarvis/ui/web/frontend/src/components/friends/ChatThread.tsx+++ b/jarvis/ui/web/frontend/src/components/friends/ChatThread.tsx@@ -12,14 +12,14 @@ import { SourceBadge } from "./SourceBadge";import { cn } from "@/lib/utils";/**- * Chat-Thread fuer einen Friend (rechte Seite des Chat-Tabs).+ * Chat thread for a friend (right side of the chat tab).*- * Layout (wie ChatsView):- * - Header (Friend-Name + Source-Badge + Permission-Profile)- * - ScrollArea mit MessageBubbles (timestamp-sortiert)- * - Input-Footer (Send-Button + Enter-to-send)+ * Layout (like ChatsView):+ * - Header (friend name + source badge + permission profile)+ * - ScrollArea with message bubbles (timestamp-sorted)+ * - Input footer (send button + Enter-to-send)*- * Wenn der Friend keinen verknuepften Channel hat, ist der Send-Pfad disabled.+ * If the friend has no linked channel, the send path is disabled.*/export function ChatThread({ friend }: { friend: FriendDetail }) {const t = useT();diff --git a/jarvis/ui/web/frontend/src/components/friends/FriendListItem.tsx b/jarvis/ui/web/frontend/src/components/friends/FriendListItem.tsxindex 8c0664748c..cb575808e5 100644--- a/jarvis/ui/web/frontend/src/components/friends/FriendListItem.tsx+++ b/jarvis/ui/web/frontend/src/components/friends/FriendListItem.tsx@@ -3,10 +3,10 @@ import { SourceBadge } from "./SourceBadge";import { cn } from "@/lib/utils";/**- * Ein Eintrag in der FriendsList (linke Seite des Chat-Tabs).+ * A single entry in the FriendsList (left side of the chat tab).*- * Layout: Avatar-Initial + Name + Source-Badges + Note (truncated).- * Selected-State markiert via Border + Background.+ * Layout: avatar initial + name + source badges + note (truncated).+ * The selected state is marked via border + background.*/export function FriendListItem({friend,diff --git a/jarvis/ui/web/frontend/src/components/friends/LiveStatusCard.tsx b/jarvis/ui/web/frontend/src/components/friends/LiveStatusCard.tsxindex 8b40168185..07551e771d 100644--- a/jarvis/ui/web/frontend/src/components/friends/LiveStatusCard.tsx+++ b/jarvis/ui/web/frontend/src/components/friends/LiveStatusCard.tsx@@ -2,13 +2,12 @@import { Activity } from "lucide-react";/**- * Display-Komponente fuer EINEN ausgehenden StatusUpdate.+ * Display component for a SINGLE outgoing StatusUpdate.*- * In Phase F4 ist diese Komponente nur die UI-Library — sie wird in F5- * an einen WebSocket-Stream angeschlossen, der die letzten N Updates- * pro Friend anzeigt.+ * In phase F4 this component is only the UI library — in F5 it gets wired+ * to a WebSocket stream that shows the last N updates per friend.*- * Schema-Gleichschritt mit ``jarvis.friends.schemas.StatusUpdate``:+ * Kept in schema lockstep with ``jarvis.friends.schemas.StatusUpdate``:* - event_type, timestamp_ns, fields, profile_used.*/export interface StatusUpdateView {diff --git a/jarvis/ui/web/frontend/src/components/friends/PermissionMatrix.tsx b/jarvis/ui/web/frontend/src/components/friends/PermissionMatrix.tsxindex c2123c23a9..c23b187afa 100644--- a/jarvis/ui/web/frontend/src/components/friends/PermissionMatrix.tsx+++ b/jarvis/ui/web/frontend/src/components/friends/PermissionMatrix.tsx@@ -3,16 +3,16 @@ import { cn } from "@/lib/utils";import type { StatusProfile } from "@/hooks/useFriends";/**- * 3-Radio-Selector fuer das Sharing-Profile eines Friends.+ * 3-radio selector for a friend's sharing profile.*- * Stateless / kontrolliert: ``current`` zeigt den aktuellen Wert,- * ``onChange`` wird beim Wechsel gerufen. ``disabled`` setzt alle- * Radios visuell + funktional inaktiv (z.B. waehrend des Mutation-Calls).+ * Stateless / controlled: ``current`` shows the current value, ``onChange``+ * is called on change. ``disabled`` makes all radios visually and+ * functionally inactive (e.g. during the mutation call).*/const PROFILES: { value: StatusProfile; label: string; subline: string }[] = [- { value: "minimal", label: "minimal", subline: "Nur online/offline" },- { value: "standard", label: "standard", subline: "+ Mission-Titel" },- { value: "detailed", label: "detailed", subline: "+ Jarvis-Agent-Summary" },+ { value: "minimal", label: "minimal", subline: "Online/offline only" },+ { value: "standard", label: "standard", subline: "+ mission title" },+ { value: "detailed", label: "detailed", subline: "+ Jarvis-Agent summary" },];export function PermissionMatrix({diff --git a/jarvis/ui/web/frontend/src/components/friends/SourceBadge.tsx b/jarvis/ui/web/frontend/src/components/friends/SourceBadge.tsxindex e4460bdb17..32c8fcc605 100644--- a/jarvis/ui/web/frontend/src/components/friends/SourceBadge.tsx+++ b/jarvis/ui/web/frontend/src/components/friends/SourceBadge.tsx@@ -3,13 +3,13 @@ import type { ChannelLink } from "@/hooks/useFriends";import { cn } from "@/lib/utils";/**- * Visualisiert, ueber welche Channels ein Friend erreichbar ist.+ * Visualizes which channels a friend is reachable through.*- * - Telegram-only: TG-Pille- * - Jarvis-only: Jarvis-Pille- * - Beide: beide Pillen kompakt nebeneinander+ * - Telegram-only: TG pill+ * - Jarvis-only: Jarvis pill+ * - Both: both pills compactly side by side*- * Reine Display-Komponente — alle Logik lebt in der Channels-Liste.+ * Pure display component — all logic lives in the channels list.*/export function SourceBadge({channels,diff --git a/jarvis/ui/web/frontend/src/components/missions/EventTimeline.tsx b/jarvis/ui/web/frontend/src/components/missions/EventTimeline.tsxindex c3f5d77e0a..fa71f756ad 100644--- a/jarvis/ui/web/frontend/src/components/missions/EventTimeline.tsx+++ b/jarvis/ui/web/frontend/src/components/missions/EventTimeline.tsx@@ -1,9 +1,9 @@/**- * Vertikale Timeline der Events einer selektierten Mission.+ * Vertical timeline of a selected mission's events.*- * Auto-scroll zum Ende: ScrollArea-ref + scrollHeight, getriggert wenn neue- * Events ankommen. Wir scrollen nur wenn der User bereits "in der Naehe vom- * Ende" ist (toleranz 60px), sonst stoeren wir manuelles Scrollen.+ * Auto-scroll to the end: ScrollArea ref + scrollHeight, triggered when new+ * events arrive. We only scroll if the user is already "near the end"+ * (60px tolerance), otherwise we don't interfere with manual scrolling.*/import { useEffect, useMemo, useRef, useState } from "react";import { ChevronDown, ChevronRight, Clock } from "lucide-react";diff --git a/jarvis/ui/web/frontend/src/components/missions/GlobalKillButton.tsx b/jarvis/ui/web/frontend/src/components/missions/GlobalKillButton.tsxindex 51acb338df..6e75ec1933 100644--- a/jarvis/ui/web/frontend/src/components/missions/GlobalKillButton.tsx+++ b/jarvis/ui/web/frontend/src/components/missions/GlobalKillButton.tsx@@ -1,9 +1,9 @@/**- * Top-Bar-Button: cancelt ALLE non-terminalen Missions.+ * Top-bar button: cancels ALL non-terminal missions.*- * shadcn-AlertDialog ist nicht installiert (siehe Brief), darum bauen wir das- * Confirmation-Modal selbst — basierend auf den vorhandenen Card-Primitives.- * Ein Wrapper-Backdrop + Esc/Outside-Click schliesst, "Bestaetigen" cancelled.+ * shadcn's AlertDialog isn't installed (see the brief), so we build the+ * confirmation modal ourselves — based on the existing Card primitives.+ * A wrapper backdrop + Esc/outside click closes it, "Confirm" cancels.*/import { useEffect, useState } from "react";import { AlertTriangle, Loader2, Skull } from "lucide-react";diff --git a/jarvis/ui/web/frontend/src/components/missions/JarvisAgentPanel.tsx b/jarvis/ui/web/frontend/src/components/missions/JarvisAgentPanel.tsxindex caa95b9305..80581c000b 100644--- a/jarvis/ui/web/frontend/src/components/missions/JarvisAgentPanel.tsx+++ b/jarvis/ui/web/frontend/src/components/missions/JarvisAgentPanel.tsx@@ -49,8 +49,8 @@ async function copyToClipboard(value: string): Promise<void> {try {await navigator.clipboard.writeText(value);} catch {- // Best-effort. Falls die Browser-API nicht verfuegbar ist (z.B. unsicherer- // Kontext) wird der User sehen, dass nichts passiert — wir loggen still.+ // Best-effort. If the browser API isn't available (e.g. an insecure+ // context), the user will just see nothing happen — we log it silently.}}@@ -200,9 +200,9 @@ function WorkerRow({ worker }: WorkerRowProps) {<ahref={`file:///${worker.log_path.replace(/^\//, "")}`}onClick={(e) => {- // file://-Links werden vom Browser oft geblockt; per Click- // ins Clipboard kopieren ist der zuverlaessige Pfad. Der- // Link bleibt als visueller Hinweis.+ // file:// links are often blocked by the browser; copying+ // to the clipboard on click is the reliable path. The+ // link stays as a visual hint.e.preventDefault();copyToClipboard(worker.log_path);}}diff --git a/jarvis/ui/web/frontend/src/components/missions/MissionTree.tsx b/jarvis/ui/web/frontend/src/components/missions/MissionTree.tsxindex 51c1d8f807..30d612088c 100644--- a/jarvis/ui/web/frontend/src/components/missions/MissionTree.tsx+++ b/jarvis/ui/web/frontend/src/components/missions/MissionTree.tsx@@ -1,10 +1,10 @@/**- * Linke Pane: Tree der Missions + spawned Workers.+ * Left pane: tree of missions + spawned workers.*- * react-arborist erwartet ein flat-array mit `children`-Property pro Node.- * Wir bauen den Tree on-the-fly aus dem Store: jede MissionSummary wird ein- * Top-Level-Node, jeder eindeutige worker_id aus dem zugehoerigen Event-Stream- * landet als Child-Node.+ * react-arborist expects a flat array with a `children` property per node.+ * We build the tree on-the-fly from the store: each MissionSummary becomes+ * a top-level node, and each unique worker_id from the corresponding event+ * stream lands as a child node.*/import { useMemo } from "react";import { Tree, type NodeRendererProps } from "react-arborist";@@ -85,7 +85,7 @@ function buildTree(}function shortPrompt(p: string): string {- if (!p) return "(ohne Prompt)";+ if (!p) return "(no prompt)";return p.length > 48 ? p.slice(0, 47) + "…" : p;}@@ -131,7 +131,7 @@ export function MissionTree() {if (node.data.kind === "mission") {selectMission(node.data.id);} else if (node.data.kind === "worker" && node.data.mission === undefined) {- // Worker-Node ist Child der Mission — Mission-ID extrahieren aus tree-id+ // Worker node is a child of the mission — extract the mission ID from the tree idconst missionId = node.data.id.split("::")[0];selectMission(missionId);selectWorker(node.data.workerId ?? null);diff --git a/jarvis/ui/web/frontend/src/components/missions/PtyTerminal.tsx b/jarvis/ui/web/frontend/src/components/missions/PtyTerminal.tsxindex 8a857deea0..9767e4cfd8 100644--- a/jarvis/ui/web/frontend/src/components/missions/PtyTerminal.tsx+++ b/jarvis/ui/web/frontend/src/components/missions/PtyTerminal.tsx@@ -1,16 +1,16 @@/**- * Live-Terminal fuer einen Worker. xterm.js + FitAddon + Backpressure.+ * Live terminal for a worker. xterm.js + FitAddon + backpressure.*- * Zwingende Conventions:- * - Terminal-Instance ueber useRef (NICHT useState) — sonst rerender pro chunk.- * - dispose() im Cleanup: ohne das laeuft jede Worker-Selection in einen- * WebGL-Context-Leak (Chrome cap = 16 Contexts pro Origin).- * - Backpressure: bytesPending wird lokal gezaehlt; ab 128 KB pending wird ein- * `{type:"pause"}` an den PTY-Stream gesendet, ab 16 KB wieder `resume`.+ * Mandatory conventions:+ * - Terminal instance via useRef (NOT useState) — otherwise it re-renders per chunk.+ * - dispose() in cleanup: without it, every worker selection leaks a+ * WebGL context (Chrome caps at 16 contexts per origin).+ * - Backpressure: bytesPending is counted locally; past 128 KB pending we+ * send a `{type:"pause"}` to the PTY stream, and `resume` again at 16 KB.*- * MVP-Hinweis: das Backend-PTY-Endpoint ist als Stub geplant (Phase 6, separater- * Sub-Agent). Bis es fertig ist, zeigt diese Component einen "Stream nicht- * verfuegbar"-Placeholder, sobald der WS-Connect failt.+ * MVP note: the backend PTY endpoint is planned as a stub (Phase 6, separate+ * Jarvis-Agent). Until it's ready, this component shows a "stream not+ * available" placeholder as soon as the WS connect fails.*/import { useCallback, useEffect, useRef, useState } from "react";import { Terminal } from "@xterm/xterm";@@ -59,7 +59,7 @@ export function PtyTerminal({ workerId }: PtyTerminalProps) {try {ws.send(JSON.stringify({ type, worker_id: workerId }));} catch {- // ignore — Backpressure-Hinweis ist best-effort+ // ignore — the backpressure signal is best-effort}}},@@ -108,7 +108,7 @@ export function PtyTerminal({ workerId }: PtyTerminalProps) {try {fitRef.current?.fit();} catch {- // resize-failures sind nicht kritisch+ // resize failures aren't critical}};window.addEventListener("resize", handleResize);@@ -186,8 +186,8 @@ export function PtyTerminal({ workerId }: PtyTerminalProps) {// ignore}wsRef.current = null;- // Terminal wird disposed wenn der WORKER waechselt (siehe key-prop in- // MissionsView), nicht bei jedem Re-Render+ // The terminal is disposed when the WORKER changes (see the key prop+ // in MissionsView), not on every re-renderdisposeTerminal(workerId);termRef.current = null;fitRef.current = null;diff --git a/jarvis/ui/web/frontend/src/components/missions/VerdictPanel.tsx b/jarvis/ui/web/frontend/src/components/missions/VerdictPanel.tsxindex fa552a0424..d09d34040b 100644--- a/jarvis/ui/web/frontend/src/components/missions/VerdictPanel.tsx+++ b/jarvis/ui/web/frontend/src/components/missions/VerdictPanel.tsx@@ -1,10 +1,10 @@/**- * Critic-Verdicts pro selektierter Mission.+ * Critic verdicts per selected mission.*- * Pro Verdict eine Card mit:- * - Header: verdict-Badge (approve/revise/reject) + iteration + confidence-Bar- * - 4-Axes-Grid: correctness/completeness/side_effects/security mit pass/fail- * - Pro Achse collabsable Evidence-List+ * One card per verdict, with:+ * - Header: verdict badge (approve/revise/reject) + iteration + confidence bar+ * - 4-axes grid: correctness/completeness/side_effects/security with pass/fail+ * - A collapsible evidence list per axis*/import { useState } from "react";import {diff --git a/jarvis/ui/web/frontend/src/components/missions/api.ts b/jarvis/ui/web/frontend/src/components/missions/api.tsindex b321cff88f..7436183328 100644--- a/jarvis/ui/web/frontend/src/components/missions/api.ts+++ b/jarvis/ui/web/frontend/src/components/missions/api.ts@@ -1,7 +1,7 @@/**- * REST-Wrapper fuer den Mission-Bus (Backend-Sub-Agent baut die Endpoints- * unter `/api/missions/*`). Trennen wir bewusst von den WS-Hooks, damit- * React-Query die List-/Detail-Abfragen cachen kann.+ * REST wrapper for the mission bus (a backend Jarvis-Agent builds the+ * endpoints under `/api/missions/*`). Kept deliberately separate from the+ * WS hooks so React Query can cache the list/detail queries.*/import type {CriticVerdictReady,@@ -32,7 +32,7 @@ export async function fetchMissionDetail(id: string): Promise<MissionDetail> {const res = await fetch(`${API_BASE}/${encodeURIComponent(id)}`);if (!res.ok) throw new Error(`HTTP ${res.status}`);const data = await res.json();- // Verdicts ggf. aus Events ableiten falls Backend sie nicht separat liefert+ // Derive verdicts from events if the backend doesn't return them separatelyconst events: EventEnvelope[] = data.events ?? [];const verdicts: CriticVerdictReady[] =data.verdicts ??diff --git a/jarvis/ui/web/frontend/src/components/missions/store.ts b/jarvis/ui/web/frontend/src/components/missions/store.tsindex a6fc2c6575..42b341fdfc 100644--- a/jarvis/ui/web/frontend/src/components/missions/store.ts+++ b/jarvis/ui/web/frontend/src/components/missions/store.ts@@ -1,10 +1,10 @@/**- * Zustand-Store fuer den Mission-Control-View.+ * Zustand store for the mission-control view.*- * Wichtig: xterm.js-Terminal-Instanzen leben NICHT im Store. Sie werden in- * einer Module-Level-Map (terminalRegistry) gehalten — sonst verursacht jeder- * PTY-Stream-Chunk einen React-Re-Render der gesamten View. Der Store haelt- * nur die serialisierbare Mission-/Event-/Verdict-State.+ * Important: xterm.js terminal instances do NOT live in the store. They are+ * kept in a module-level map (terminalRegistry) — otherwise every PTY stream+ * chunk would trigger a full React re-render of the whole view. The store+ * only holds the serializable mission/event/verdict state.*/import { create } from "zustand";import { subscribeWithSelector } from "zustand/middleware";@@ -108,7 +108,7 @@ export const useMissionsStore = create<MissionsStore>()(...missions,[env.mission_id]: {id: env.mission_id,- prompt: "(unbekannt)",+ prompt: "(unknown)",state: newState,language: "de",created_ms: env.ts_ms,diff --git a/jarvis/ui/web/frontend/src/components/missions/terminalRegistry.ts b/jarvis/ui/web/frontend/src/components/missions/terminalRegistry.tsindex 88d23d4a42..44edaec88f 100644--- a/jarvis/ui/web/frontend/src/components/missions/terminalRegistry.ts+++ b/jarvis/ui/web/frontend/src/components/missions/terminalRegistry.ts@@ -1,13 +1,13 @@/**- * Module-level Map fuer xterm.js-Terminal-Instanzen.+ * Module-level map for xterm.js terminal instances.*- * Lebt EXPLIZIT ausserhalb des Zustand-Stores: jeder PTY-Stream-Chunk wuerde- * sonst einen kompletten React-Re-Render des Mission-Views ausloesen, was die- * UI bei beschaeftigten Workern (mehrere KB/s Output) zum Stehen bringt.+ * Lives EXPLICITLY outside the Zustand store: otherwise every PTY stream+ * chunk would trigger a full React re-render of the mission view, which+ * grinds the UI to a halt with busy workers (several KB/s of output).*- * Lifecycle: PtyTerminal-Component registriert beim Mount, dispose im Cleanup.- * Bei React-StrictMode laufen Mount/Unmount zweimal — die Registry-Eintraege- * werden im ersten Cleanup wieder freigegeben, das ist okay.+ * Lifecycle: the PtyTerminal component registers on mount, disposes in+ * cleanup. Under React StrictMode, mount/unmount runs twice — the registry+ * entries get freed again on the first cleanup, which is fine.*/import type { Terminal } from "@xterm/xterm";@@ -27,8 +27,8 @@ export function disposeTerminal(workerId: string): void {try {term.dispose();} catch {- // dispose ist defensiv — wenn xterm intern bereits zerstoert ist,- // dann doppelter dispose-Aufruf darf den Cleanup nicht killen+ // dispose is defensive — if xterm has already destroyed itself+ // internally, a duplicate dispose call must not kill the cleanup}registry.delete(workerId);}diff --git a/jarvis/ui/web/frontend/src/components/missions/useMissionWebSocket.ts b/jarvis/ui/web/frontend/src/components/missions/useMissionWebSocket.tsindex c534dda23b..7380a135d4 100644--- a/jarvis/ui/web/frontend/src/components/missions/useMissionWebSocket.ts+++ b/jarvis/ui/web/frontend/src/components/missions/useMissionWebSocket.ts@@ -1,12 +1,13 @@/**- * WebSocket-Verbindung zum Mission-Bus (`/api/missions/ws`).+ * WebSocket connection to the mission bus (`/api/missions/ws`).*- * Erst-Frame nach onOpen ist ein "hello" mit `last_seq` — das Backend liefert- * dann Replay-Events vor neuen Live-Events. So kann ein gerade reconnecteter- * Tab seq-Luecken auffuellen, ohne ein REST-Catch-up.+ * The first frame after onOpen is a "hello" with `last_seq` — the backend+ * then delivers replay events before new live events. That way a tab that+ * just reconnected can fill seq gaps without a REST catch-up.*- * Reconnect erfolgt automatisch via react-use-websocket (exponentielles- * Backoff bis 30s, infinite Retries). UI zeigt "offline" via store.connected.+ * Reconnect happens automatically via react-use-websocket (exponential+ * backoff up to 30s, infinite retries). The UI shows "offline" via+ * store.connected.*/import { useEffect, useMemo } from "react";import useWebSocket, { ReadyState } from "react-use-websocket";@@ -73,7 +74,7 @@ export function useMissionWebSocket(): { readyState: ReadyState } {if (isEventEnvelope(msg)) {applyEvent(msg);}- // hello_ack und andere Control-Frames: silent ignore (kein UI-Feedback noetig)+ // hello_ack and other control frames: silently ignore (no UI feedback needed)}, [lastJsonMessage, applyEvent]);return { readyState };diff --git a/jarvis/ui/web/frontend/src/components/sessions/SessionDetail.tsx b/jarvis/ui/web/frontend/src/components/sessions/SessionDetail.tsxindex 733b2b5402..5061f8925a 100644--- a/jarvis/ui/web/frontend/src/components/sessions/SessionDetail.tsx+++ b/jarvis/ui/web/frontend/src/components/sessions/SessionDetail.tsx@@ -1,8 +1,8 @@/**- * Detail-Pane einer einzelnen Voice-Session: Header (Aggregate) +- * Turn-Timeline + globaler Click-to-Copy fuer die ganze Session.+ * Detail pane for a single voice session: header (aggregates) ++ * turn timeline + a global click-to-copy for the whole session.*- * Lade-/Empty-/Error-States werden inline gerendert — kein Modal.+ * Loading/empty/error states are rendered inline — no modal.*/import {Code2,@@ -131,7 +131,7 @@ export function SessionDetail({ detail, loading, error }: Props) {if (!detail) return;try {const text = await fetchSessionExport(detail.session.id, format);- // Erste User-Utterance als Filename-Slug — fallback auf session_id.+ // First user utterance as the filename slug — falls back to session_id.const preview =detail.turns.find((t) => t.user_text)?.user_text ?? "";const filename = buildSessionFilename(detail.session, preview, format);@@ -279,7 +279,7 @@ export function SessionDetail({ detail, loading, error }: Props) {</div></div>- {/* Export-Actions: pro Format eine Reihe mit Kopieren + Herunterladen */}+ {/* Export actions: one row per format with copy + download */}<div className="flex shrink-0 flex-col gap-1.5"><div className="text-[10px] font-medium uppercase tracking-wider text-muted-foreground">Export@@ -357,8 +357,8 @@ interface ExportRowProps {}/**- * Eine Zeile pro Export-Format: links das Format-Label (mit Icon),- * rechts drei kompakte Action-Buttons (Kopieren / Herunterladen / In Editor).+ * One row per export format: the format label (with icon) on the left,+ * three compact action buttons (copy / download / open in editor) on the right.*/function ExportRow({icon,diff --git a/jarvis/ui/web/frontend/src/components/sessions/SessionList.tsx b/jarvis/ui/web/frontend/src/components/sessions/SessionList.tsxindex b04bef7d48..ae0b2cc7ce 100644--- a/jarvis/ui/web/frontend/src/components/sessions/SessionList.tsx+++ b/jarvis/ui/web/frontend/src/components/sessions/SessionList.tsx@@ -1,11 +1,11 @@/**- * Sidebar-Liste der Voice-Sessions, neueste zuerst.+ * Sidebar list of voice sessions, newest first.*- * Eine Zeile = eine Session-Card mit:- * - Datum + Zeit (relativ zu jetzt)- * - Dauer / Turn-Count- * - Erste User-Utterance als Preview- * - Hangup-Reason als Badge+ * One row = one session card with:+ * - Date + time (relative to now)+ * - Duration / turn count+ * - First user utterance as a preview+ * - Hangup reason as a badge*/import { Clock, Loader2, Mic, MicOff } from "lucide-react";diff --git a/jarvis/ui/web/frontend/src/components/sessions/TurnCard.tsx b/jarvis/ui/web/frontend/src/components/sessions/TurnCard.tsxindex 1f0a84a3ab..afafca4220 100644--- a/jarvis/ui/web/frontend/src/components/sessions/TurnCard.tsx+++ b/jarvis/ui/web/frontend/src/components/sessions/TurnCard.tsx@@ -1,8 +1,8 @@/**- * Einzelner Voice-Turn — User-Block + Brain-Meta + Tools + Jarvis-Block.+ * A single voice turn — user block + brain meta + tools + Jarvis block.*- * Per Click-to-Copy-Button kann der User den Turn-Text alleine kopieren- * (ohne Session-Frame).+ * The click-to-copy button lets the user copy just the turn text+ * (without the session frame).*/import {Brain,@@ -289,7 +289,7 @@ export function TurnCard({ turn, spoken = [] }: Props) {</div>)}- {/* Latenz-Aufschluesselung — wie lang Jarvis nachgedacht / gesprochen hat */}+ {/* Latency breakdown — how long Jarvis thought / spoke */}{(turn.think_ms > 0 || turn.speak_ms > 0) && (<div className="grid grid-cols-2 gap-2 border-t border-border/50 pt-2 text-[11px]"><div className="flex items-center gap-1.5">diff --git a/jarvis/ui/web/frontend/src/components/sessions/api.ts b/jarvis/ui/web/frontend/src/components/sessions/api.tsindex b4caaaa759..316159951a 100644--- a/jarvis/ui/web/frontend/src/components/sessions/api.ts+++ b/jarvis/ui/web/frontend/src/components/sessions/api.ts@@ -1,5 +1,5 @@-// REST-Aufrufe zu /api/sessions. Alle relativ — der Vite-Dev-Proxy bzw.-// das pywebview-Fenster routen automatisch zur FastAPI auf 127.0.0.1:47821.+// REST calls to /api/sessions. All relative — the Vite dev proxy or the+// pywebview window both route automatically to the FastAPI on 127.0.0.1:47821.import type { SessionDetail, SessionListItem } from "./types";diff --git a/jarvis/ui/web/frontend/src/components/sessions/types.ts b/jarvis/ui/web/frontend/src/components/sessions/types.tsindex 3e69d1fe40..7f6f65365b 100644--- a/jarvis/ui/web/frontend/src/components/sessions/types.ts+++ b/jarvis/ui/web/frontend/src/components/sessions/types.ts@@ -1,10 +1,10 @@-// 1:1 Spiegel zu jarvis/sessions/models.py — Pydantic JSON-Output.-// Halten wir absichtlich getrennt vom Mission-Types-Modul, damit der-// Tab eigenstaendig erweitert werden kann ohne API-Coupling.+// 1:1 mirror of jarvis/sessions/models.py — Pydantic JSON output.+// Kept deliberately separate from the mission-types module, so the tab can+// be extended independently without API coupling.//-// BUG-008 (drei Episoden): Backend nutzt ``str`` statt ``Literal`` —-// hier daher ebenfalls ``string``, nicht Union. Die Konstante-// ``KNOWN_HANGUP_REASONS`` dokumentiert die heute erwarteten Werte.+// BUG-008 (three episodes): the backend uses ``str`` instead of ``Literal`` —+// hence ``string`` here too, not a union. The ``KNOWN_HANGUP_REASONS``+// constant documents the values expected today.export const KNOWN_HANGUP_REASONS = ["",diff --git a/jarvis/ui/web/frontend/src/components/wiki/ObsidianButton.tsx b/jarvis/ui/web/frontend/src/components/wiki/ObsidianButton.tsxindex ea3dbb8a49..4202c4ba0e 100644--- a/jarvis/ui/web/frontend/src/components/wiki/ObsidianButton.tsx+++ b/jarvis/ui/web/frontend/src/components/wiki/ObsidianButton.tsx@@ -6,7 +6,7 @@ import { useEventStore } from "@/store/events";import { useT } from "@/i18n";/**- * Per-page "In Obsidian öffnen" button.+ * Per-page "Open in Obsidian" button.** Hands editing off to the real Obsidian desktop app via the* `obsidian://open?vault=…&file=…` URL scheme. There is no reliable waydiff --git a/jarvis/ui/web/frontend/src/components/wiki/ObsidianSetupDialog.test.tsx b/jarvis/ui/web/frontend/src/components/wiki/ObsidianSetupDialog.test.tsxindex 32d313311c..00ea4595a9 100644--- a/jarvis/ui/web/frontend/src/components/wiki/ObsidianSetupDialog.test.tsx+++ b/jarvis/ui/web/frontend/src/components/wiki/ObsidianSetupDialog.test.tsx@@ -80,7 +80,7 @@ describe("ObsidianSetupDialog", () => {expect(screen.getByTestId("obsidian-setup-download-link")).toBeDefined();});- it("clicking 'Ich habs installiert' calls onStatusRefresh and advances on installed=true", async () => {+ it("clicking 'I installed it' calls onStatusRefresh and advances on installed=true", async () => {const refresh = vi.fn(async () => STATUS_NOT_REGISTERED);render(<ObsidianSetupDialog@@ -102,7 +102,7 @@ describe("ObsidianSetupDialog", () => {expect(marker2.getAttribute("data-state")).toBe("active");});- it("clicking 'Ich habs installiert' shows retry hint on installed=false", async () => {+ it("clicking 'I installed it' shows retry hint on installed=false", async () => {const refresh = vi.fn(async () => STATUS_NOT_INSTALLED);render(<ObsidianSetupDialog@@ -121,7 +121,7 @@ describe("ObsidianSetupDialog", () => {expect(screen.queryByTestId("obsidian-setup-step-2")).toBeNull();});- it("clicking 'Jetzt registrieren' with 200 added advances to step 3", async () => {+ it("clicking 'Register now' with 200 added advances to step 3", async () => {const fetchImpl = vi.fn(async () =>jsonResponse({ status: "added", vault_uuid: "abc", backup_path: null }),) as unknown as typeof fetch;@@ -147,7 +147,7 @@ describe("ObsidianSetupDialog", () => {expect(screen.queryByTestId("obsidian-setup-step-2")).toBeNull();});- it("clicking 'Jetzt registrieren' with 409 shows config_missing hint", async () => {+ it("clicking 'Register now' with 409 shows config_missing hint", async () => {const fetchImpl = vi.fn(async () =>jsonResponse({@@ -176,7 +176,7 @@ describe("ObsidianSetupDialog", () => {expect(screen.queryByTestId("obsidian-setup-step-3")).toBeNull();});- it("clicking 'Jetzt registrieren' with 500 shows error + help link", async () => {+ it("clicking 'Register now' with 500 shows error + help link", async () => {const fetchImpl = vi.fn(async () =>jsonResponse({@@ -205,7 +205,7 @@ describe("ObsidianSetupDialog", () => {expect(screen.getByTestId("obsidian-setup-help-link")).toBeDefined();});- it("clicking 'In Obsidian oeffnen' sets window.location.href to obsidian://...", () => {+ it("clicking 'Open in Obsidian' sets window.location.href to obsidian://...", () => {// jsdom's `window.location` is normally read-only-ish; replace the// ``href`` setter with a tracker for the duration of the test.let lastHref: string | null = null;@@ -245,7 +245,7 @@ describe("ObsidianSetupDialog", () => {}});- it("clicking 'Hat geklappt — Fertig' calls onComplete then onClose", () => {+ it("clicking 'It worked — Done' calls onComplete then onClose", () => {const calls: string[] = [];const onComplete = vi.fn(() => calls.push("complete"));const onClose = vi.fn(() => calls.push("close"));diff --git a/jarvis/ui/web/frontend/src/components/wiki/ObsidianSetupDialog.tsx b/jarvis/ui/web/frontend/src/components/wiki/ObsidianSetupDialog.tsxindex 17f46f1a7e..ee01b03b82 100644--- a/jarvis/ui/web/frontend/src/components/wiki/ObsidianSetupDialog.tsx+++ b/jarvis/ui/web/frontend/src/components/wiki/ObsidianSetupDialog.tsx@@ -307,7 +307,7 @@ export function ObsidianSetupDialog({window.location.href = url;} catch {// jsdom or sandboxed embed: nothing we can do, the failure message- // shows up on the "Hat nicht geklappt" branch anyway.+ // shows up on the "It didn't work" branch anyway.}}, [vaultName]);diff --git a/jarvis/ui/web/frontend/src/components/wiki/ObsidianStatus.test.tsx b/jarvis/ui/web/frontend/src/components/wiki/ObsidianStatus.test.tsxindex 96cdf1e2c8..c4903f3f28 100644--- a/jarvis/ui/web/frontend/src/components/wiki/ObsidianStatus.test.tsx+++ b/jarvis/ui/web/frontend/src/components/wiki/ObsidianStatus.test.tsx@@ -64,7 +64,7 @@ const NOTE_STATUS: ObsidianStatusType = {vault_registered: true,vault_path: "C:/vault",recommended_action: "ok",- note: "Obsidian-Config-Datei nicht lesbar.",+ note: "Obsidian-Config-Datei nicht lesbar.", // i18n-allow: asserts the real "de" locale default rendered by ObsidianStatus (product i18n surface)};describe("ObsidianStatus", () => {@@ -79,7 +79,7 @@ describe("ObsidianStatus", () => {expect(screen.getByTestId("obsidian-status-spinner")).toBeDefined();});- it("renders 'verbunden' when status is ok", async () => {+ it("renders 'verbunden' when status is ok", async () => { // i18n-allow: quotes the real "de" locale default text (product i18n surface)const fetchImpl = vi.fn(async () => jsonResponse(OK_STATUS),) as unknown as typeof fetch;@@ -91,7 +91,7 @@ describe("ObsidianStatus", () => {expect(pill.getAttribute("data-visual")).toBe("ok");});const pill = screen.getByTestId("obsidian-status-pill");- expect(pill.textContent).toContain("verbunden");+ expect(pill.textContent).toContain("verbunden"); // i18n-allow: asserts the real "de" locale default rendered by ObsidianStatus (product i18n surface)// Tooltip surfaces vault_path + version.expect(pill.getAttribute("title")).toContain("C:/vault");expect(pill.getAttribute("title")).toContain("1.7.4");@@ -101,7 +101,7 @@ describe("ObsidianStatus", () => {expect(pill.className).toContain("#5bd4a4");});- it("renders 'nicht installiert' when installed=false", async () => {+ it("renders 'nicht installiert' when installed=false", async () => { // i18n-allow: quotes the real "de" locale default text (product i18n surface)const fetchImpl = vi.fn(async () => jsonResponse(INSTALL_STATUS),) as unknown as typeof fetch;@@ -113,12 +113,12 @@ describe("ObsidianStatus", () => {expect(pill.getAttribute("data-visual")).toBe("install");});const pill = screen.getByTestId("obsidian-status-pill");- expect(pill.textContent).toContain("nicht installiert");+ expect(pill.textContent).toContain("nicht installiert"); // i18n-allow: asserts the real "de" locale default rendered by ObsidianStatus (product i18n surface)expect(pill.className).toContain("#facc15");expect((pill as HTMLButtonElement).disabled).toBe(false);});- it("renders 'nicht registriert' when vault_registered=false", async () => {+ it("renders 'nicht registriert' when vault_registered=false", async () => { // i18n-allow: quotes the real "de" locale default text (product i18n surface)const fetchImpl = vi.fn(async () => jsonResponse(REGISTER_STATUS),) as unknown as typeof fetch;@@ -130,11 +130,11 @@ describe("ObsidianStatus", () => {expect(pill.getAttribute("data-visual")).toBe("register");});const pill = screen.getByTestId("obsidian-status-pill");- expect(pill.textContent).toContain("nicht registriert");+ expect(pill.textContent).toContain("nicht registriert"); // i18n-allow: asserts the real "de" locale default rendered by ObsidianStatus (product i18n surface)expect(pill.className).toContain("#ffb84d");});- it("renders 'Status unklar' on fetch failure", async () => {+ it("renders 'Status unklar' on fetch failure", async () => { // i18n-allow: quotes the real "de" locale default text (product i18n surface)const fetchImpl = vi.fn(async () => {throw new Error("network down");}) as unknown as typeof fetch;@@ -146,11 +146,11 @@ describe("ObsidianStatus", () => {expect(pill.getAttribute("data-visual")).toBe("unclear");});const pill = screen.getByTestId("obsidian-status-pill");- expect(pill.textContent).toContain("Status unklar");+ expect(pill.textContent).toContain("Status unklar"); // i18n-allow: asserts the real "de" locale default rendered by ObsidianStatus (product i18n surface)expect(pill.className).toContain("#8d94a8");});- it("renders 'Status unklar' when note is set", async () => {+ it("renders 'Status unklar' when note is set", async () => { // i18n-allow: quotes the real "de" locale default text (product i18n surface)const fetchImpl = vi.fn(async () => jsonResponse(NOTE_STATUS),) as unknown as typeof fetch;@@ -162,8 +162,8 @@ describe("ObsidianStatus", () => {expect(pill.getAttribute("data-visual")).toBe("unclear");});const pill = screen.getByTestId("obsidian-status-pill");- expect(pill.textContent).toContain("Status unklar");- expect(pill.getAttribute("title")).toContain("nicht lesbar");+ expect(pill.textContent).toContain("Status unklar"); // i18n-allow: asserts the real "de" locale default rendered by ObsidianStatus (product i18n surface)+ expect(pill.getAttribute("title")).toContain("nicht lesbar"); // i18n-allow: asserts the real "de" locale default rendered by ObsidianStatus (product i18n surface)});it("clicking a non-ok pill calls onOpenSetup with the status", async () => {diff --git a/jarvis/ui/web/frontend/src/components/wiki/ObsidianStatus.tsx b/jarvis/ui/web/frontend/src/components/wiki/ObsidianStatus.tsxindex 3b8079358d..39eca1f5e5 100644--- a/jarvis/ui/web/frontend/src/components/wiki/ObsidianStatus.tsx+++ b/jarvis/ui/web/frontend/src/components/wiki/ObsidianStatus.tsx@@ -5,10 +5,10 @@* Obsidian is connected to the on-disk vault. Five visual states:** - LOADING grey, animated dots, no interaction- * - OK green "Obsidian: verbunden", tooltip shows vault + version- * - REGISTER orange "Obsidian: nicht registriert", click opens setup- * - INSTALL yellow "Obsidian: nicht installiert", click opens setup- * - UNCLEAR grey "Obsidian: Status unklar", click opens setup+ * - OK green "Obsidian: connected", tooltip shows vault + version+ * - REGISTER orange "Obsidian: not registered", click opens setup+ * - INSTALL yellow "Obsidian: not installed", click opens setup+ * - UNCLEAR grey "Obsidian: status unclear", click opens setup** The click handler is intentionally minimal — Sub-Agent 5 wires the real* setup dialog in. This component only owns presentation + polling.diff --git a/jarvis/ui/web/frontend/src/components/wiki/WikiGraph.test.tsx b/jarvis/ui/web/frontend/src/components/wiki/WikiGraph.test.tsxindex 593d62ffb0..c77e0f05a6 100644--- a/jarvis/ui/web/frontend/src/components/wiki/WikiGraph.test.tsx+++ b/jarvis/ui/web/frontend/src/components/wiki/WikiGraph.test.tsx@@ -61,7 +61,7 @@ describe("WikiGraph", () => {expect(screen.getByTestId("wiki-graph-empty")).toBeDefined();});expect(screen.getByTestId("wiki-graph-empty").textContent).toContain(- "Memory-Graph ist noch leer",+ "Your memory graph is still empty",);});diff --git a/jarvis/ui/web/frontend/src/hooks/useBoard.ts b/jarvis/ui/web/frontend/src/hooks/useBoard.tsindex 2e75991c54..1df8265ee7 100644--- a/jarvis/ui/web/frontend/src/hooks/useBoard.ts+++ b/jarvis/ui/web/frontend/src/hooks/useBoard.ts@@ -140,9 +140,9 @@ async function triggerRefresh(): Promise<{ ok: boolean; triggered: boolean }> {// ----------------------------------------------------------------------/**- * Dashboard-Summary. Polling alle 30s ist Plan-Decision §5-A #1. KEIN- * Pull-to-Refresh, KEIN Slot-Machine-UX — nur deterministisches Polling- * plus ein manueller Refresh-Button, der das gleiche Query invalidiert.+ * Dashboard summary. Polling every 30s is Plan-Decision §5-A #1. NO+ * pull-to-refresh, NO slot-machine UX — just deterministic polling+ * plus a manual refresh button that invalidates the same query.*/export function useBoardSummary() {return useQuery({@@ -238,7 +238,7 @@ export interface BioRegenerateResult {reason?: string | null;}-export type BioFeedbackKind = "trifft" | "trifft_nicht" | "haerter";+export type BioFeedbackKind = "trifft" | "trifft_nicht" | "haerter"; // i18n-allow: API contract values matched by backend logicexport interface BioFeedbackResult {ok: boolean;@@ -319,9 +319,9 @@ export function useBioRegenerate() {}/**- * Reagier-Klick unter dem AI-Profil. Drei Kinds: "trifft" / "trifft_nicht"- * / "haerter". Das Signal kalibriert die NAECHSTE Bio-Generation; kein- * Sofort-Regenerate (Brainstorm-Decision 2026-05-02).+ * Reaction click under the AI profile. Three kinds: "trifft" / "trifft_nicht"+ * / "haerter" (i18n-allow: API contract values). The signal calibrates the+ * NEXT bio generation; no immediate regenerate (Brainstorm-Decision 2026-05-02).*/export function useBioFeedback() {return useMutation({diff --git a/jarvis/ui/web/frontend/src/hooks/useBrainStatus.ts b/jarvis/ui/web/frontend/src/hooks/useBrainStatus.tsindex ab6f1a1cbd..3fbfba9f30 100644--- a/jarvis/ui/web/frontend/src/hooks/useBrainStatus.ts+++ b/jarvis/ui/web/frontend/src/hooks/useBrainStatus.ts@@ -2,18 +2,18 @@ import { useEffect } from "react";import { useEventStore } from "@/store/events";/**- * Halt den Sidebar-Footer-Brain-Status im Zustand-Store synchron.+ * Keeps the sidebar-footer brain status in sync with the Zustand store.*- * Drei Update-Pfade — Defense-in-Depth:- * 1. Mount-Fetch von /api/brain/status (initialer Wert).- * 2. Live via WS-Event BrainProviderSwitched (siehe useWebSocket.ts:110).- * 3. Custom-Event jarvis:brain-switched (vom ApiKeysView dispatched, falls- * WS-Pfad eine Race-Condition oder einen Disconnect hatte).+ * Three update paths — defense in depth:+ * 1. Mount fetch of /api/brain/status (initial value).+ * 2. Live via WS event BrainProviderSwitched (see useWebSocket.ts:110).+ * 3. Custom event jarvis:brain-switched (dispatched by ApiKeysView, in case+ * the WS path had a race condition or a disconnect).*- * Pfad 3 war bis 2026-04-25 nicht verdrahtet — Klick auf eine Provider-- * Karte wechselte den Brain backendseitig, aber der Sidebar-Footer blieb- * auf dem Mount-Wert haengen, wenn der WS-Event-Round-Trip aus irgendeinem- * Grund nicht durchkam.+ * Path 3 wasn't wired up until 2026-04-25 — clicking a provider card+ * switched the brain on the backend, but the sidebar footer stayed+ * stuck on the mount value whenever the WS event round trip didn't+ * come through for whatever reason.*/export function useBrainStatus(): void {const setBrainProvider = useEventStore((s) => s.setBrainProvider);@@ -39,15 +39,15 @@ export function useBrainStatus(): void {}}).catch(() => {- // Fetch fail (network/timeout) — Store bleibt auf altem Wert,- // Sidebar zeigt "—" bis ein WS-Event die Lücke füllt.+ // Fetch failed (network/timeout) — store stays on the old value,+ // sidebar shows "—" until a WS event fills the gap.});void fetchStatus(ctrl.signal);const onBrainSwitched = () => {- // Frischen Fetch — der Endpoint liest aus app.state.brain.active_provider,- // also ist er nach dem Switch authoritativ.+ // Fresh fetch — the endpoint reads from app.state.brain.active_provider,+ // so it's authoritative right after the switch.void fetchStatus();};window.addEventListener("jarvis:brain-switched", onBrainSwitched);diff --git a/jarvis/ui/web/frontend/src/hooks/useClis.ts b/jarvis/ui/web/frontend/src/hooks/useClis.tsindex c4e4c0c8d0..dec45daeb5 100644--- a/jarvis/ui/web/frontend/src/hooks/useClis.ts+++ b/jarvis/ui/web/frontend/src/hooks/useClis.ts@@ -1,5 +1,5 @@/**- * React Query Hooks fuer die CLI-Integration.+ * React Query hooks for the CLI integration.** Endpoints (siehe jarvis/ui/web/cli_routes.py).*/diff --git a/jarvis/ui/web/frontend/src/hooks/useDocs.ts b/jarvis/ui/web/frontend/src/hooks/useDocs.tsindex 573632b768..b75ea55c08 100644--- a/jarvis/ui/web/frontend/src/hooks/useDocs.ts+++ b/jarvis/ui/web/frontend/src/hooks/useDocs.ts@@ -58,7 +58,7 @@ export interface DocSearchResult {score: number;}-// Reihenfolge fuer die Sidebar — analog backend ``/api/docs/grouped``.+// Order for the sidebar — mirrors backend ``/api/docs/grouped``.export const DIATAXIS_ORDER: DocDiataxis[] = ["tutorial","howto",diff --git a/jarvis/ui/web/frontend/src/hooks/useFederation.ts b/jarvis/ui/web/frontend/src/hooks/useFederation.tsindex faa03d3dc8..4617ca1335 100644--- a/jarvis/ui/web/frontend/src/hooks/useFederation.ts+++ b/jarvis/ui/web/frontend/src/hooks/useFederation.ts@@ -48,7 +48,7 @@ export interface FeedResponse {}// -----------------------------------------------------------------------// Fetchers (gegen lokalen Proxy, NICHT direkt das Federation-Backend)+// Fetchers (against the local proxy, NOT the federation backend directly)// ----------------------------------------------------------------------async function fetchStatus(): Promise<FederationStatus> {diff --git a/jarvis/ui/web/frontend/src/hooks/useFriendMessages.ts b/jarvis/ui/web/frontend/src/hooks/useFriendMessages.tsindex 0c78bbae8b..289181445f 100644--- a/jarvis/ui/web/frontend/src/hooks/useFriendMessages.ts+++ b/jarvis/ui/web/frontend/src/hooks/useFriendMessages.ts@@ -1,6 +1,6 @@// === F-FRIENDS [F2] · feature/friends-section · ruben-2026-04-30 ===/**- * Chat-Thread-Hooks fuer einen Friend (Phase F2).+ * Chat-thread hooks for a friend (Phase F2).** In F2: Polling 5s. Backend liefert leere Liste — UI zeigt empty-state,* Send-Pfad funktioniert bereits gegen Telegram.diff --git a/jarvis/ui/web/frontend/src/hooks/useFriends.ts b/jarvis/ui/web/frontend/src/hooks/useFriends.tsindex 0afc966abd..939215b1a4 100644--- a/jarvis/ui/web/frontend/src/hooks/useFriends.ts+++ b/jarvis/ui/web/frontend/src/hooks/useFriends.ts@@ -1,9 +1,9 @@// === F-FRIENDS [F2] · feature/friends-section · ruben-2026-04-30 ===/**- * Friends-API-Hooks (Phase F2).+ * Friends API hooks (Phase F2).*- * Spiegelt die Endpoints aus jarvis/ui/web/friends_routes.py.- * Pattern wie useFederation.ts: React-Query, eigene fetch-Wrapper.+ * Mirrors the endpoints from jarvis/ui/web/friends_routes.py.+ * Same pattern as useFederation.ts: React Query, own fetch wrappers.*/import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";diff --git a/jarvis/ui/web/frontend/src/hooks/useOutputs.ts b/jarvis/ui/web/frontend/src/hooks/useOutputs.tsindex cc8c5b2ca4..54e8e641eb 100644--- a/jarvis/ui/web/frontend/src/hooks/useOutputs.ts+++ b/jarvis/ui/web/frontend/src/hooks/useOutputs.ts@@ -1,9 +1,9 @@/**- * useOutputs — Stub nach Filesystem-Reset 2026-04-25.+ * useOutputs — stub after the 2026-04-25 filesystem reset.*- * Liefert die OutputSummary-Liste + Plan-Detail aus den FastAPI-Endpoints.- * Voller Hook (mit Polling-Stop bei abgeschlossenem Run) folgt; aktuell- * minimal aber funktional.+ * Provides the OutputSummary list + plan detail from the FastAPI endpoints.+ * The full hook (with polling stop on a completed run) is coming; for now+ * this is minimal but functional.*/import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";diff --git a/jarvis/ui/web/frontend/src/hooks/useProviders.ts b/jarvis/ui/web/frontend/src/hooks/useProviders.tsindex ae0da89ca9..b8fc3678c4 100644--- a/jarvis/ui/web/frontend/src/hooks/useProviders.ts+++ b/jarvis/ui/web/frontend/src/hooks/useProviders.ts@@ -122,10 +122,9 @@ interface ProvidersResponse {}/**- * Lädt /api/providers und re-fetched bei relevanten WS-Events. Die Hook stellt- * den UI-State live ein, wenn Backend-seitig ein Secret gesetzt oder ein- * Brain-Provider gewechselt wurde — ohne dass die Komponente das selbst- * tracken muss.+ * Loads /api/providers and re-fetches on relevant WS events. The hook updates+ * the UI state live whenever a secret is set on the backend or a brain+ * provider was switched — without the component having to track that itself.*/export function useProviders() {const [providers, setProviders] = useState<ProviderDescriptor[]>([]);@@ -387,16 +386,16 @@ export interface PipelineSwitchResult {restart_required: boolean;}-// Backwards-compat alias — alter Name war TTS-spezifisch.+// Backwards-compat alias — the old name was TTS-specific.export type TtsSwitchResult = PipelineSwitchResult;/**- * Wechselt den aktiven TTS-Provider. Persistiert in jarvis.toml.+ * Switches the active TTS provider. Persists to jarvis.toml.*- * Anders als beim Brain gibt es keinen Live-Manager — die SpeechPipeline- * haelt ihre TTS-Instanz fest. Der Switch greift erst beim naechsten- * Pipeline-Start (Voice-Toggle oder App-Restart). Die Backend-Response- * setzt `restart_required = true` damit die UI das transparent macht.+ * Unlike the brain, there's no live manager — the SpeechPipeline holds onto+ * its TTS instance. The switch only takes effect on the next pipeline start+ * (voice toggle or app restart). The backend response sets+ * `restart_required = true` so the UI makes that transparent.*/export async function switchTtsProvider(providerId: string,@@ -414,11 +413,11 @@ export async function switchTtsProvider(}/**- * Wechselt den aktiven STT-Provider. Persistiert in jarvis.toml.+ * Switches the active STT provider. Persists to jarvis.toml.*- * Genau wie TTS: der Whisper/Cloud-STT wird beim Pipeline-Bootstrap- * einmalig instanziiert (Model-Load ist teuer), daher greift der- * Switch erst beim naechsten Voice-Restart.+ * Just like TTS: the Whisper/cloud STT is instantiated once at pipeline+ * bootstrap (model load is expensive), so the switch only takes effect+ * on the next voice restart.*/export async function switchSttProvider(providerId: string,@@ -436,11 +435,11 @@ export async function switchSttProvider(}/**- * Wechselt den aktiven Heavy-Task SUBAGENT-Provider- * (`[brain.sub_jarvis].provider`). Persistiert 3-schichtig- * (jarvis.toml + config-soll.json + ENV), damit der Drift-Guard den Switch- * nicht zurueckrollt. Der Worker liest den Provider beim Mission-Bootstrap- * einmalig, daher setzt das Backend `restart_required = true`.+ * Switches the active heavy-task WORKER provider+ * (`[brain.sub_jarvis].provider`). Persists across 3 layers+ * (jarvis.toml + config-soll.json + ENV) so the drift guard doesn't roll+ * back the switch. The worker reads the provider once at mission bootstrap,+ * so the backend sets `restart_required = true`.*/export async function switchSubagentProvider(providerId: string,diff --git a/jarvis/ui/web/frontend/src/hooks/useRecentDocs.ts b/jarvis/ui/web/frontend/src/hooks/useRecentDocs.tsindex 283f1db533..d3e3138408 100644--- a/jarvis/ui/web/frontend/src/hooks/useRecentDocs.ts+++ b/jarvis/ui/web/frontend/src/hooks/useRecentDocs.ts@@ -10,19 +10,19 @@ export interface RecentDoc {slug: string;title: string;diataxis: DocDiataxis;- /** Unix-ms — fuer LRU-Sortierung. */+ /** Unix ms — for LRU sorting. */openedAt: number;}/**- * localStorage-basierter Recent-Docs-Tracker.+ * localStorage-based recent-docs tracker.*- * Eintraege werden im LRU-Stil gehalten: beim Doc-Open wird der Eintrag an- * die Spitze geschoben (oder neu angelegt). Cap bei ``MAX_ENTRIES`` (5);- * laengere Listen wuerden in der Sidebar zu viel Platz brauchen.+ * Entries are kept LRU-style: opening a doc moves the entry to the top+ * (or creates it). Capped at ``MAX_ENTRIES`` (5); longer lists would take+ * up too much room in the sidebar.*- * State + localStorage werden synchron gehalten — kein react-query, weil- * die Daten ohnehin client-only sind.+ * State + localStorage are kept in sync — no react-query, since the data+ * is client-only anyway.*/export function useRecentDocs(): {recent: RecentDoc[];@@ -31,10 +31,10 @@ export function useRecentDocs(): {} {const [recent, setRecent] = useState<RecentDoc[]>(() => loadFromStorage());- // Sync-Pattern fuer mehrere ``useRecentDocs``-Instanzen im selben Window:- // ``storage``-Event firet nur cross-tab, nicht intra-tab. Custom-Event- // ``docs-recent-changed`` wird bei jedem ``push``/``clear`` dispatched- // und alle Instanzen reloaden aus localStorage.+ // Sync pattern for multiple ``useRecentDocs`` instances in the same window:+ // the ``storage`` event only fires cross-tab, not intra-tab. The custom+ // ``docs-recent-changed`` event is dispatched on every ``push``/``clear``+ // and all instances reload from localStorage.useEffect(() => {const reload = () => setRecent(loadFromStorage());window.addEventListener("storage", (e) => {diff --git a/jarvis/ui/web/frontend/src/hooks/useSessions.ts b/jarvis/ui/web/frontend/src/hooks/useSessions.tsindex 842bec8ddf..86d694b571 100644--- a/jarvis/ui/web/frontend/src/hooks/useSessions.ts+++ b/jarvis/ui/web/frontend/src/hooks/useSessions.ts@@ -1,16 +1,16 @@/**- * useSessions — kombiniert REST-Fetch (React-Query) mit Live-Updates aus- * dem WebSocket-Event-Stream.+ * useSessions — combines a REST fetch (React Query) with live updates from+ * the WebSocket event stream.*- * Strategie:- * - React-Query haelt die Sessions-Liste + Detail-Cache.- * - Wenn auf dem Bus ein VoiceSessionStarted oder VoiceSessionEnded- * Event ankommt, invalidieren wir die Listen-Query (forciert Refetch).- * - Bei VoiceSessionEnded: zusaetzlich das Detail invalidieren (Aggregate- * sind erst beim Hangup final).+ * Strategy:+ * - React Query holds the sessions list + detail cache.+ * - When a VoiceSessionStarted or VoiceSessionEnded event arrives on the+ * bus, we invalidate the list query (forces a refetch).+ * - On VoiceSessionEnded: also invalidate the detail (aggregates are only+ * final once the call has been hung up).*- * Damit braucht es kein Polling — die Liste aktualisiert sich live in dem- * Moment, in dem der User auflegt.+ * That means no polling is needed — the list updates live the moment the+ * user hangs up.*/import { useEffect, useMemo } from "react";import { useQuery, useQueryClient } from "@tanstack/react-query";@@ -29,14 +29,14 @@ export function useSessions() {queryFn: () => fetchSessions(100),refetchInterval: 30_000,retry: (failureCount, err) => {- // 503 = Recorder disabled → kein Retry, sofort Empty-State zeigen+ // 503 = recorder disabled → no retry, show the empty state right awayif (err instanceof Error && /HTTP 503/.test(err.message)) return false;return failureCount < 1;},});- // Letztes Voice-Session-Event-Vorkommen — wenn neu, invalidieren.- // useMemo + Dependency auf events.length+letzte-id verhindert Endlos-Loop.+ // Most recent voice-session event occurrence — invalidate when it's new.+ // useMemo + dependency on events.length+last-id prevents an infinite loop.const lastVoiceEvent = useMemo(() => {for (let i = events.length - 1; i >= 0; i--) {const ev = events[i];@@ -53,7 +53,7 @@ export function useSessions() {useEffect(() => {if (lastVoiceEvent === null) return;queryClient.invalidateQueries({ queryKey: SESSIONS_QUERY_KEY });- // Bei Ended: Detail-Cache des betroffenen Eintrags ebenfalls invalidieren.+ // On Ended: also invalidate the detail cache of the affected entry.if (lastVoiceEvent.name === "VoiceSessionEnded") {const sid = (lastVoiceEvent.payload as { session_id?: string } | null)?.session_id;diff --git a/jarvis/ui/web/frontend/src/hooks/useSkills.ts b/jarvis/ui/web/frontend/src/hooks/useSkills.tsindex e10bc5a68f..4607b9d02b 100644--- a/jarvis/ui/web/frontend/src/hooks/useSkills.ts+++ b/jarvis/ui/web/frontend/src/hooks/useSkills.ts@@ -271,7 +271,7 @@ export function useReorderSkills() {}// -----------------------------------------------------------------------// Skill-Creation (User-authored, ueber Desktop-App)+// Skill creation (user-authored, via the desktop app)// ----------------------------------------------------------------------export interface SkillCreatePayload {@@ -519,10 +519,10 @@ async function queryLocalSkills(}/**- * React-Query-Hook fuer die lokale Skill-Suche. Wird durch jede Filter-- * Aenderung getriggert. Der Hook laeuft bei leerer Query + leeren Filtern- * **nicht** — die Sidebar faellt dann auf die normale ``useSkillsList``- * zurueck (Kategorie-gruppierte Vollansicht).+ * React Query hook for the local skill search. Triggered on every filter+ * change. The hook does **not** run when the query and all filters are+ * empty — the sidebar then falls back to the normal ``useSkillsList``+ * (category-grouped full view).*/export function useLocalSkillSearch(filters: LocalSkillQueryFilters,diff --git a/jarvis/ui/web/frontend/src/hooks/useWebSocket.ts b/jarvis/ui/web/frontend/src/hooks/useWebSocket.tsindex 3121a018d5..523fa62d52 100644--- a/jarvis/ui/web/frontend/src/hooks/useWebSocket.ts+++ b/jarvis/ui/web/frontend/src/hooks/useWebSocket.ts@@ -106,7 +106,7 @@ export function useWebSocket(): void {Math.floor(env.timestamp_ns / 1_000_000),);- // Sub-Agent-Dashboard: Live-Tree aus den Phase-5.5-Events bauen.+ // Jarvis-Agents dashboard: build the live tree from the Phase-5.5 events.if (SUB_AGENT_EVENT_NAMES.has(env.event_name)) {useSubAgentStore.getState()@@ -154,7 +154,7 @@ export function useWebSocket(): void {};pushMessage(msg);console.log("[ChatThinking] MessageSent role=", p.role);- // Brain-Reply (oder System-Diagnostic) ist eingegangen — Thinking aus.+ // Brain reply (or system diagnostic) has arrived — thinking off.// The "preamble" role is the Flash-Brain pre-ack; it does NOT end// the thinking state because the assistant's main reply is still// pending. Only "assistant" / "system" clear the indicator.@@ -171,8 +171,8 @@ export function useWebSocket(): void {}if (env.event_name === "ErrorOccurred") {- // Brain-Errors brechen den Wait-Cycle ab, sonst haengt der Indikator- // bis zum 60s-Timeout. Andere Layer-Errors ignorieren wir hier.+ // Brain errors abort the wait cycle, otherwise the indicator hangs+ // until the 60s timeout. We ignore other layer errors here.const p = env.payload as { layer?: string; source_layer?: string };if (p.layer === "brain" || p.source_layer === "brain") {setChatThinking(false);@@ -225,7 +225,7 @@ export function useWebSocket(): void {}if (env.event_name === "SecretConfigured") {- // Trigger nur — die ApiKeysView refresht ihre Provider-Liste selbst.+ // Trigger only — ApiKeysView refreshes its own provider list.window.dispatchEvent(new CustomEvent("jarvis:secret-configured", { detail: env.payload }));}@@ -268,8 +268,8 @@ export function useWebSocket(): void {if (typeof p.title === "string" && p.title.length > 0) {pushToast("success", `Achievement: ${p.title}`);}- // Lokale Custom-Event: AchievementGrid hoert darauf und invalidiert- // die React-Query-Liste, damit der Unlock sofort sichtbar wird.+ // Local custom event: AchievementGrid listens for it and invalidates+ // the React Query list, so the unlock becomes visible immediately.window.dispatchEvent(new CustomEvent("jarvis:achievement-unlocked", { detail: p }),);diff --git a/jarvis/ui/web/frontend/src/index.css b/jarvis/ui/web/frontend/src/index.cssindex 4a35b7491f..635641d939 100644--- a/jarvis/ui/web/frontend/src/index.css+++ b/jarvis/ui/web/frontend/src/index.css@@ -52,15 +52,15 @@--ring: 50 100% 52%;--radius: 0.75rem;- /* Jarvis-spezifische Custom-Tokens */- --jarvis-yellow: 255 214 10; /* #FFD60A für rgba() */- --jarvis-yellow-dim: 230 190 40; /* gedimmtes gelb */+ /* Jarvis-specific custom tokens */+ --jarvis-yellow: 255 214 10; /* #FFD60A for rgba() */+ --jarvis-yellow-dim: 230 190 40; /* dimmed yellow */--jarvis-grid: 0 0% 12%;}.dark {- /* Dark is default — diese Klasse ist nur für explizite dark-switches.- Wir halten das gleiche Schema, dark = default = Jarvis. */+ /* Dark is default — this class is only for explicit dark switches.+ We keep the same scheme, dark = default = Jarvis. */--background: 0 0% 4%;--foreground: 0 0% 96%;}@@ -95,7 +95,7 @@}@layer components {- /* Subtiles Grid-Pattern im Hintergrund — gibt Dashboard-Gefühl ohne abzulenken */+ /* Subtle grid pattern in the background — gives a dashboard feel without distracting */.jarvis-grid {background-image:linear-gradient(rgba(255, 214, 10, 0.04) 1px, transparent 1px),@@ -104,7 +104,7 @@mask-image: radial-gradient(ellipse at center, black 30%, transparent 70%);}- /* Gelber Spot-Glow — wird als absolute-positioned Element verwendet */+ /* Yellow spot glow — used as an absolute-positioned element */.jarvis-glow {background: radial-gradient(circle at center,@@ -115,7 +115,7 @@filter: blur(60px);}- /* Button-Base — für CTAs */+ /* Button base — for CTAs */.btn-primary {@apply inline-flex items-center justify-center gap-2 rounded-full px-6 py-3 font-mediumbg-primary text-primary-foreground@@ -171,7 +171,7 @@}}- /* Pulse-Animation für State-Badges */+ /* Pulse animation for state badges */@keyframes jarvis-pulse {0%, 100% {opacity: 1;@@ -239,7 +239,7 @@}}- /* Weiche Float-Animation fürs Hero-Orb */+ /* Soft float animation for the hero orb */@keyframes jarvis-float {0%, 100% { transform: translateY(0px); }50% { transform: translateY(-14px); }@@ -248,7 +248,7 @@animation: jarvis-float 6s ease-in-out infinite;}- /* Langsamer Spin für subtile Rotationen */+ /* Slow spin for subtle rotations */@keyframes jarvis-spin-slow {from { transform: rotate(0deg); }to { transform: rotate(360deg); }@@ -257,7 +257,7 @@animation: jarvis-spin-slow 40s linear infinite;}- /* Text-Gradient für Hero */+ /* Text gradient for the hero */.text-gradient-yellow {background: linear-gradient(135deg, #FFE552 0%, #FFD60A 50%, #B8960A 100%);-webkit-background-clip: text;@@ -265,7 +265,7 @@color: transparent;}- /* Custom Scrollbar — passend zum Theme */+ /* Custom scrollbar — matching the theme */.scrollbar-jarvis::-webkit-scrollbar {width: 6px;height: 6px;@@ -282,16 +282,16 @@}/* ===========================================================- Gigi-Maskottchen-Animationen- Idle = kontinuierliches Floating + Mikro-Atmung auf SVG-Root.- Aktionen werden durch .gigi-<action>-Klassen getriggert —- die jeweilige Klasse lebt nur für die Dauer der Animation.+ Gigi mascot animations+ Idle = continuous floating + micro-breathing on the SVG root.+ Actions are triggered via .gigi-<action> classes —+ each class only lives for the duration of the animation.=========================================================== */.gigi-container {position: relative;display: inline-block;- font-size: 0; /* kein baseline-gap unter dem SVG */+ font-size: 0; /* no baseline gap under the SVG */}.gigi-root {display: block;@@ -310,7 +310,7 @@transform-origin: 50% 50%;}- /* Auto-Blink (alle ~7s ein natuerliches Blinzeln — parallel zu Random-Actions) */+ /* Auto-blink (a natural blink every ~7s — parallel to random actions) */.gigi-root .gigi-eyes {transform-box: fill-box;transform-origin: 50% 50%;@@ -321,7 +321,7 @@93.5% { transform: scaleY(0.08); }}- /* Pupillen-Drift: subtile Augenbewegung während Idle */+ /* Pupil drift: subtle eye movement during idle */.gigi-root .gigi-pupils {animation: gigi-pupil-drift 11s ease-in-out infinite;transform-origin: 50% 50%;@@ -334,7 +334,7 @@85% { transform: translate(-0.6px, 0.2px); }}- /* Mund: subtile "Atmung" */+ /* Mouth: subtle "breathing" */.gigi-root .gigi-mouth {transform-box: fill-box;transform-origin: 50% 50%;@@ -354,7 +354,7 @@50% { transform: scale(1.025); }}- /* --- Action: Blink (Augen schließen kurz) --- */+ /* --- Action: Blink (eyes close briefly) --- */.gigi-blink .gigi-eyes,.gigi-blink .gigi-pupils,.gigi-blink .gigi-sparkle {@@ -366,11 +366,11 @@45%, 60% { transform: scaleY(0.08); }}- /* --- Action: Wave (linker Arm winkt) ---- Transform-origin wird auf die Schulter gelegt (fill-box Top-Right,- weil die Arm-Path-Bbox rechts-oben die Anbindung zur Body-Seite ist).- Wichtig: origin/box unconditional auf den Arm setzen — nicht nur bei- .gigi-wave — sonst laeuft Animation mit Default-Origin (0,0). */+ /* --- Action: Wave (left arm waves) ---+ Transform-origin is placed on the shoulder (fill-box top-right,+ because the arm path bbox's top-right is where it connects to the body).+ Important: set origin/box on the arm unconditionally — not only on+ .gigi-wave — otherwise the animation runs with the default origin (0,0). */.gigi-root .gigi-arm-left {transform-box: fill-box;transform-origin: 100% 0%;@@ -384,18 +384,18 @@}@keyframes gigi-wave {0% { transform: rotate(0deg); }- 12% { transform: rotate(-95deg); } /* Arm hoch */- 22% { transform: rotate(-75deg); } /* Wink 1 */+ 12% { transform: rotate(-95deg); } /* arm up */+ 22% { transform: rotate(-75deg); } /* wave 1 */32% { transform: rotate(-110deg); }- 42% { transform: rotate(-75deg); } /* Wink 2 */+ 42% { transform: rotate(-75deg); } /* wave 2 */52% { transform: rotate(-110deg); }- 62% { transform: rotate(-75deg); } /* Wink 3 */+ 62% { transform: rotate(-75deg); } /* wave 3 */72% { transform: rotate(-110deg); }- 82% { transform: rotate(-90deg); } /* Winken aus */- 100% { transform: rotate(0deg); } /* zurück nach unten */+ 82% { transform: rotate(-90deg); } /* wave ends */+ 100% { transform: rotate(0deg); } /* back down */}- /* --- Action: Spin (ganze Figur dreht sich) --- */+ /* --- Action: Spin (whole figure spins) --- */.gigi-spin .gigi-svg {animation: gigi-spin 0.85s cubic-bezier(0.65, 0, 0.35, 1);}@@ -404,7 +404,7 @@100% { transform: rotate(360deg); }}- /* --- Action: Jump (hochhüpfen) --- */+ /* --- Action: Jump (hop up) --- */.gigi-jump .gigi-svg {animation: gigi-jump 0.65s cubic-bezier(0.4, 0, 0.2, 1);}@@ -415,7 +415,7 @@80% { transform: translateY(1px) scale(1.05, 0.95); }}- /* --- Action: Shake (Kopf-Schütteln) --- */+ /* --- Action: Shake (head shaking) --- */.gigi-shake .gigi-svg {animation: gigi-shake 0.55s ease-in-out;}@@ -427,7 +427,7 @@75% { transform: translateX(3px) rotate(2deg); }}- /* --- Action: Look-Left / Look-Right (Pupillen schauen) --- */+ /* --- Action: Look-Left / Look-Right (pupils look) --- */.gigi-look-left .gigi-pupils {animation: gigi-look-left 0.85s ease-in-out;}@@ -443,7 +443,7 @@30%, 70% { transform: translateX(4px); }}- /* --- Action: Glitch (kurzer digitaler Störer) --- */+ /* --- Action: Glitch (brief digital disruption) --- */.gigi-glitch .gigi-svg {animation: gigi-glitch 0.42s steps(2, end);}@@ -465,7 +465,7 @@75% { opacity: 0.8; transform: translateX(4px); }}- /* --- Voice-State-Reaktionen --- */+ /* --- Voice-state reactions --- */.gigi-voice-listening .gigi-eyes {animation: gigi-ear-prick 1.2s ease-in-out infinite;}@@ -496,7 +496,7 @@filter: hue-rotate(-40deg) saturate(1.4);}- /* --- Kommentar-Bubble --- */+ /* --- Comment bubble --- */.gigi-bubble {position: absolute;top: 50%;@@ -586,7 +586,7 @@100% { opacity: 1; transform: translateY(-50%) scale(1); }}- /* Reduced-Motion-Friendly: alle Animationen aus */+ /* Reduced-motion friendly: all animations off */@media (prefers-reduced-motion: reduce) {.gigi-container,.gigi-container *,diff --git a/jarvis/ui/web/frontend/src/lib/clipboard.ts b/jarvis/ui/web/frontend/src/lib/clipboard.tsindex eb2566109a..7cca6add59 100644--- a/jarvis/ui/web/frontend/src/lib/clipboard.ts+++ b/jarvis/ui/web/frontend/src/lib/clipboard.ts@@ -1,28 +1,28 @@/**- * Robust-Clipboard + Download-Helper.+ * Robust clipboard + download helper.*- * Hintergrund: pywebview verwendet auf Windows die WebView2-Engine- * (Edge Chromium). Deren ``navigator.clipboard.writeText`` hat fuer- * **Multi-Line-Strings** (z.B. JSON mit ``indent=2``) ein bekanntes- * Quirk-Verhalten — es kann passieren, dass nur die erste Zeile (= ``{``)- * im System-Clipboard landet. Markdown/Plain-Text trifft das seltener,- * weil deren Header die erste Zeile mit weiteren Zeichen fuellen.+ * Background: on Windows, pywebview uses the WebView2 engine+ * (Edge Chromium). Its ``navigator.clipboard.writeText`` has a known+ * quirk for **multi-line strings** (e.g. JSON with ``indent=2``) —+ * sometimes only the first line (= ``{``) ends up in the system+ * clipboard. Markdown/plain text hits this less often, because their+ * header fills the first line with more characters.*- * Loesung: robustCopy() versucht erst die moderne Clipboard-API. Bei- * Failure ODER bei verdaechtig kurzem Output (Multi-Line-Truncation)- * faellt es auf den klassischen ``document.execCommand('copy')``-Pfad- * zurueck — der via hidden ``textarea`` + Selection arbeitet und in- * WebView2 zuverlaessig den vollen Inhalt schreibt.+ * Solution: robustCopy() first tries the modern clipboard API. On+ * failure OR on suspiciously short output (multi-line truncation), it+ * falls back to the classic ``document.execCommand('copy')`` path —+ * which works via a hidden ``textarea`` + selection and reliably+ * writes the full content in WebView2.*//**- * Kopiert einen String robust ins System-Clipboard.+ * Robustly copies a string to the system clipboard.*- * Returns true wenn erfolgreich (oder Fallback-Pfad genutzt wurde),- * false wenn beide Pfade fehlschlugen.+ * Returns true if successful (or if the fallback path was used),+ * false if both paths failed.*/export async function robustCopy(text: string): Promise<boolean> {- // Pfad A — moderne Clipboard-API. Schnell und sicher fuer kurze Texte.+ // Path A — modern clipboard API. Fast and reliable for short texts.try {if (typeof navigator !== "undefined" &&@@ -30,21 +30,21 @@ export async function robustCopy(text: string): Promise<boolean> {typeof navigator.clipboard.writeText === "function") {await navigator.clipboard.writeText(text);- // WebView2-Quirk: writeText() resolve()d auch dann, wenn nur ein- // Teilstring uebernommen wurde. Wir koennen das Ergebnis nicht- // zuverlaessig zurueck-lesen (readText braucht Permissions, die- // pywebview nicht standardmaessig grantet). Daher: bei Multi-Line- // immer auch den Fallback ausfuehren — er ueberschreibt ggf.- // den korrupten Eintrag mit dem vollstaendigen Text.+ // WebView2 quirk: writeText() resolves even when only a partial+ // string was applied. We can't reliably read the result back+ // (readText needs permissions that pywebview doesn't grant by+ // default). So for multi-line content, always run the fallback+ // too — it overwrites the corrupted entry with the full text+ // if needed.if (text.includes("\n")) {return execCommandCopy(text);}return true;}} catch {- // Pfad A fehlgeschlagen — durchfallen zu Fallback.+ // Path A failed — fall through to the fallback.}- // Pfad B — klassischer Fallback via hidden textarea.+ // Path B — classic fallback via a hidden textarea.return execCommandCopy(text);}@@ -52,15 +52,15 @@ function execCommandCopy(text: string): boolean {if (typeof document === "undefined") return false;const ta = document.createElement("textarea");ta.value = text;- // Off-screen, damit kein Layout-Shift / Focus-Verlust beim User+ // Off-screen, so there's no layout shift / focus loss for the user.ta.style.position = "fixed";ta.style.left = "-9999px";ta.style.top = "0";ta.style.opacity = "0";ta.setAttribute("readonly", "");document.body.appendChild(ta);- // Wichtig: focus + select muessen passieren bevor execCommand laeuft,- // sonst hat WebView2 nichts zum Kopieren.+ // Important: focus + select must happen before execCommand runs,+ // otherwise WebView2 has nothing to copy.ta.focus();ta.select();ta.setSelectionRange(0, text.length);@@ -97,22 +97,22 @@ export function downloadAs(const a = document.createElement("a");a.href = url;a.download = filename;- // Off-screen halten, damit kein visueller Flicker beim Click.+ // Keep it off-screen so there's no visual flicker on click.a.style.position = "fixed";a.style.left = "-9999px";document.body.appendChild(a);a.click();document.body.removeChild(a);} finally {- // ObjectURL freigeben, sobald der Download-Stream Zeit hatte zu starten.+ // Release the object URL once the download stream had time to start.setTimeout(() => URL.revokeObjectURL(url), 1000);}}/**- * Triggert einen Datei-Download aus einem Blob (binaer-sicher — anders als- * ``downloadAs``, das einen String nimmt). Gleiches Hidden-Anchor-Muster;- * genutzt fuer den PNG-Export der Share-Karte.+ * Triggers a file download from a Blob (binary-safe — unlike+ * ``downloadAs``, which takes a string). Same hidden-anchor pattern;+ * used for the PNG export of the share card.*/export function downloadBlob(filename: string, blob: Blob): void {const url = URL.createObjectURL(blob);@@ -131,14 +131,14 @@ export function downloadBlob(filename: string, blob: Blob): void {}/**- * Erzeugt einen filesystem-tauglichen Filename fuer eine Voice-Session.+ * Builds a filesystem-safe filename for a voice session.** Pattern: ``voice-session-YYYY-MM-DD_HH-mm-{slug}.{ext}``- * - YYYY-MM-DD_HH-mm aus session.started_ms (LocalTime)- * - slug aus den ersten 3-4 Woertern der ersten User-Utterance falls- * vorhanden, sonst der ersten 8 Zeichen der session_id+ * - YYYY-MM-DD_HH-mm from session.started_ms (local time)+ * - slug from the first 3-4 words of the first user utterance if+ * present, otherwise the first 8 characters of the session_id*- * Filesystem-Sanitizing: nur ``[a-z0-9-]`` plus Bindestriche.+ * Filesystem sanitizing: only ``[a-z0-9-]`` plus hyphens.*/export function buildSessionFilename(session: { id: string; started_ms: number },@@ -158,17 +158,17 @@ function slugify(s: string): string {return s.toLowerCase().normalize("NFKD")- .replace(/[̀-ͯ]/g, "") // diacritics weg- .replace(/[^a-z0-9\s-]/g, " ") // alles non-alnum zu Space+ .replace(/[̀-ͯ]/g, "") // strip diacritics+ .replace(/[^a-z0-9\s-]/g, " ") // turn all non-alnum into a space.trim().split(/\s+/)- .slice(0, 4) // max 4 Woerter+ .slice(0, 4) // max 4 words.join("-").slice(0, 40); // hard cap}/**- * Mime-Type fuer ein Export-Format.+ * MIME type for an export format.*/export function mimeFor(format: "markdown" | "plain" | "json"): string {if (format === "json") return "application/json;charset=utf-8";