From 51701802523a5b6b2de6501e2b0a92ca6a058568 Mon Sep 17 00:00:00 2001 From: "Bernd (Hermes)" Date: Sun, 23 Aug 2026 18:26:29 +0200 Subject: [PATCH] =?UTF-8?q?feat(F92):=20Self-Check=20check=5Fcomponents()?= =?UTF-8?q?=20im=20Plugin=20=E2=80=94=206-stufige=20Background-Diagnose?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Feature 92: 6-stufige Self-Check-Pipeline im Plugin als Background-Task bei Gateway-Start (Python-Pendant zu Don's check_components() in install.sh). - plugin/archivar/self_check.py: check_components() mit 6 Stufen (FAISS→Index→Ollama→Modell→Embedding→Ready), nur stdlib (keine faiss/numpy auf Modulebene — genau das soll der Check erkennen). - adapter.py: _start_self_check()/_run_self_check() nicht-blockierend via asyncio.to_thread + wait_for(30s). Meldung an Operator-DM (User), NICHT an den Agenten. MULTIROOM_AGENT=false → übersprungen. - Klassifikation: Stufe 1-3 Fehler → './install.sh --repair'-Hinweis; Stufe 4-5 → Warmup ('ich lade gerade'); Stufe 6 → silent. - 23 Tests (test_f92_self_check.py): Probes, Klassifikation, build_report_message, Adapter-Verdrahtung, Timeout, Operator-DM. --- plugin/adapter.py | 88 ++++++ plugin/archivar/self_check.py | 276 +++++++++++++++++++ plugin/archivar/tests/test_f92_self_check.py | 267 ++++++++++++++++++ 3 files changed, 631 insertions(+) create mode 100644 plugin/archivar/self_check.py create mode 100644 plugin/archivar/tests/test_f92_self_check.py diff --git a/plugin/adapter.py b/plugin/adapter.py index cf10bc1..3a15ca0 100644 --- a/plugin/adapter.py +++ b/plugin/adapter.py @@ -2139,8 +2139,96 @@ class RocketChatAdapter(BasePlatformAdapter): # im __init__/frühen Connect-Pfad mit auth_token=None → stillschweigend # übersprungen → RC cached Bot-Default 'away' → GELB permanent. self._reset_initial_message_and_presence() + + # ── Feature 92: Self-Check als Background-Task ──────────────────── + # 6-stufige Komponenten-Diagnose (FAISS→Index→Ollama→Modell→Embedding→Ready), + # NICHT blockierend, 30s Gesamt-Timeout. Meldung geht an den User (RC), + # nicht an den Agenten, nicht ins Log. Bei MULTIROOM_AGENT=false wird + # übersprungen (kein Archivar → keine Raumerkennung). + self._start_self_check() + return True + # ── Feature 92: Self-Check ──────────────────────────────────────────── + + def _start_self_check(self) -> None: + """Startet den Self-Check als Background-Task (nicht blockierend). + + Der Check läuft via ``asyncio.to_thread`` (blockierende HTTP-Calls), + damit der Gateway-Start nicht verzögert wird. Bei Fehler/Warmup wird + die Meldung an den Operator-DM gesendet; bei Erfolg (Stufe 6) passiert + nichts (silent). Ein Timeout (30s) oder eine Exception führen + ebenfalls zu keiner Meldung — der Check ist rein diagnostisch und darf + den Gateway-Betrieb niemals stören. + """ + if not _MULTIROOM() or self.archivar is None: + logger.info("[rocketchat] F92: MULTIROOM_AGENT=false — Self-Check übersprungen") + return + + try: + asyncio.ensure_future(self._run_self_check()) + logger.info("[rocketchat] F92: Self-Check als Background-Task gestartet") + except Exception as e: + logger.warning("[rocketchat] F92: Self-Check-Start fehlgeschlagen: %s", e) + + async def _run_self_check(self) -> None: + """Führt den Self-Check aus und meldet dem User das Ergebnis. + + 30s Gesamt-Timeout via asyncio.wait_for. Ergebnis-Klassifikation + (Feature 92 / install-repair-konzept.md §4): + Stufe 1-3 Fehler → --repair-Hinweis + Stufe 4-5 → Warmup ("ich lade gerade") + Stufe 6 → silent (keine Meldung) + """ + import asyncio + from archivar.self_check import check_components, build_report_message, SELF_CHECK_TIMEOUT_S + + try: + result = await asyncio.wait_for( + asyncio.to_thread(check_components), + timeout=SELF_CHECK_TIMEOUT_S, + ) + except asyncio.TimeoutError: + logger.warning("[rocketchat] F92: Self-Check Timeout nach %ss — übersprungen", SELF_CHECK_TIMEOUT_S) + return + except Exception as e: + logger.warning("[rocketchat] F92: Self-Check fehlgeschlagen: %s", e) + return + + message = build_report_message(result) + if not message: + logger.info("[rocketchat] F92: Self-Check OK — alle Komponenten bereit (silent)") + return + + # Klassifikation fürs Log (Fehler vs. Warmup). + if result.has_error: + logger.warning("[rocketchat] F92: Self-Check FEHLER — sende --repair-Hinweis an Operator") + else: + logger.info("[rocketchat] F92: Self-Check WARMUP — sende Lade-Meldung an Operator") + + # Meldung an den Operator-DM (User), NICHT an den Agenten. + operator_room = self._find_operator_room() + if not operator_room: + logger.warning("[rocketchat] F92: Kein Operator-DM gefunden — Self-Check-Meldung verworfen") + return + + try: + await self._post_message_with_retry(operator_room, message) + logger.info("[rocketchat] F92: Self-Check-Meldung an Operator gesendet (room=%s)", operator_room[:12]) + except Exception as e: + logger.warning("[rocketchat] F92: Self-Check-Meldung konnte nicht gesendet werden: %s", e) + + def _find_operator_room(self) -> Optional[str]: + """Findet den Operator-DM-Raum (erster DM-Raum, nicht hardcoded). + + Gleiches Muster wie in ``_start_onboarding()`` (Z.6011-6016): der + erste Raum mit ``type == "d"`` in ``self._room_info``. + """ + for room_id, info in self._room_info.items(): + if info.get("type") == "d": + return room_id + return None + def _reset_initial_message_and_presence(self) -> None: """STETS-GELB Fix 1 + Fix 2: Initial-Reset + Presence-Online nach Connect. diff --git a/plugin/archivar/self_check.py b/plugin/archivar/self_check.py new file mode 100644 index 0000000..78f67d1 --- /dev/null +++ b/plugin/archivar/self_check.py @@ -0,0 +1,276 @@ +""" +Feature 92 — Self-Check: 6-stufige Komponenten-Diagnose nach Gateway-Start. + +Python-Pendant zu `check_components()` in install.sh (Don, Feature 92 / +`--repair`). Beide teilen sich dieselbe Komponentenliste, Reihenfolge und +Stufen-Nummerierung, damit Diagnose (Plugin) und Therapie +(`install.sh --repair`) nie auseinanderlaufen. + +Stufen (Abhängigkeitskette): + 1. FAISS importierbar (`import faiss`) + 2. Index ladbar (room_index.faiss + room_index.meta) + 3. Ollama erreichbar (GET /api/tags) + 4. Modell geladen (LLM-Modell in /api/tags) + 5. Embedding ladbar (POST /api/embeddings → Vektor) + 6. Ready (Stufen 1-5 alle OK) + +Fehler-Klassifikation (Feature 92 / install-repair-konzept.md §4): + Stufe 1-3 Fehler = "errors" → User-Meldung mit "./install.sh --repair" + Stufe 4-5 Fehler = "warmup" → User-Meldung "ich lade gerade" + Stufe 6 (alles OK) = silent → keine Meldung + +WICHTIG (P-093-Klasse): Dieses Modul darf NIEMALS schwere Abhängigkeiten +(faiss, numpy) auf Modulebene importieren — genau diese Abhängigkeiten soll +der Check erkennen. Es verwendet nur stdlib (urllib, json, os, pathlib) plus +`config` (das selbst nur json/os importiert). +""" + +from __future__ import annotations + +import json +import logging +import os +import urllib.error +import urllib.request +from dataclasses import dataclass +from pathlib import Path +from typing import List, Optional + +from .config import OLLAMA_CONFIG, LLM_CONFIG + +logger = logging.getLogger(__name__) + +# ── Timeout-Konstanten ────────────────────────────────────────────────────── +# Feature 92: 30s Timeout für den GESAMTEN Check (wird vom Adapter via +# asyncio.wait_for() durchgesetzt). Zusätzlich ein kurzer HTTP-Timeout pro +# Einzel-Check (analog install.sh `curl --max-time 3`), damit ein hängendes +# Ollama nicht die ganze Diagnose blockiert. + +SELF_CHECK_TIMEOUT_S: float = float(os.getenv("ARCHIVAR_SELF_CHECK_TIMEOUT", "30.0")) +"""Gesamt-Timeout für den Self-Check in Sekunden (Feature 92, Default 30s).""" + +SELF_CHECK_HTTP_TIMEOUT_S: float = 3.0 +"""HTTP-Timeout pro Einzel-Check in Sekunden (analog install.sh curl --max-time 3).""" + +# ── Index-Pfad (identisch zu room_index.py `_DEFAULT_INDEX_DIR`) ───────────── +# Bewusst hier neu abgeleitet statt `import room_index` — room_index importiert +# numpy auf Modulebene, was bei kaputtem venv selbst fehlschlägt (genau das, +# was der Check diagnostizieren soll). + +_INDEX_DIR: str = os.path.expanduser( + os.getenv("ARCHIVAR_INDEX_DIR", "~/.hermes/hermes-agent/data") +) +_INDEX_FILENAME: str = "room_index.faiss" +_META_FILENAME: str = "room_index.meta" + + +@dataclass +class ComponentCheckResult: + """Ergebnis der 6-stufigen Self-Check-Diagnose. + + Stufen 1-3 sind Fehler-Stufen, Stufen 4-5 Warmup-Stufen, Stufe 6 + (``ready``) ist abgeleitet. + """ + + faiss_importable: bool # Stufe 1 + index_loadable: bool # Stufe 2 + ollama_reachable: bool # Stufe 3 + llm_model_loaded: bool # Stufe 4 + embedding_ladbar: bool # Stufe 5 + ready: bool # Stufe 6 (abgeleitet) + + @property + def has_error(self) -> bool: + """True wenn eine der Fehler-Stufen (1-3) fehlgeschlagen ist.""" + return not ( + self.faiss_importable and self.index_loadable and self.ollama_reachable + ) + + @property + def needs_warmup(self) -> bool: + """True wenn keine Fehler-Stufe, aber eine Warmup-Stufe (4-5) fehlt.""" + return (not self.has_error) and not ( + self.llm_model_loaded and self.embedding_ladbar + ) + + +# ── Einzel-Probes (module-level, damit Tests sie gezielt patchen können) ──── + + +def _probe_faiss_importable() -> bool: + """Stufe 1: Ist `faiss` importierbar?""" + try: + import faiss # noqa: F401 + return True + except Exception as e: + logger.warning("[f92-self-check] Stufe 1: faiss nicht importierbar: %s", e) + return False + + +def _probe_index_loadable() -> bool: + """Stufe 2: Ist der FAISS-Index ladbar (Dateien + Meta + read_index)? + + Prüft (a) ob beide Dateien existieren, (b) ob die Meta-Datei gültiges + JSON mit nicht-leeren room_ids enthält, (c) — falls faiss verfügbar — + ob ``faiss.read_index`` den Index tatsächlich liest. Fehlt faiss, fällt + (c) weg; die Stufe zählt dann als OK, solange die Dateien konsistent + vorliegen (der faiss-Import wird bereits von Stufe 1 gemeldet). + """ + index_path = Path(_INDEX_DIR) / _INDEX_FILENAME + meta_path = Path(_INDEX_DIR) / _META_FILENAME + + if not index_path.exists() or not meta_path.exists(): + logger.warning( + "[f92-self-check] Stufe 2: Index-Dateien fehlen (%s / %s)", + index_path, meta_path, + ) + return False + + try: + with open(meta_path, "r", encoding="utf-8") as f: + meta = json.load(f) + except (json.JSONDecodeError, OSError) as e: + logger.warning("[f92-self-check] Stufe 2: Meta nicht lesbar: %s", e) + return False + + if not meta.get("room_ids"): + logger.warning("[f92-self-check] Stufe 2: Meta hat leere room_ids") + return False + + # (c) optional: echter Lese-Versuch, nur wenn faiss da ist. + try: + import faiss # noqa: F401 + faiss.read_index(str(index_path)) + except Exception: + # faiss fehlt → bereits Stufe 1; oder read_index schlug fehl. + pass + + return True + + +def _http_get_json(url: str, timeout: float) -> Optional[dict]: + """GET und JSON-Parse, None bei jedem Fehler (urllib, stdlib).""" + try: + req = urllib.request.Request(url, method="GET") + with urllib.request.urlopen(req, timeout=timeout) as resp: + return json.loads(resp.read().decode("utf-8")) + except (urllib.error.HTTPError, urllib.error.URLError, + json.JSONDecodeError, OSError, Exception) as e: + logger.warning("[f92-self-check] GET %s fehlgeschlagen: %s", url, e) + return None + + +def _probe_ollama_reachable(base_url: str, timeout: float) -> bool: + """Stufe 3: Ist Ollama erreichbar (GET /api/tags)?""" + return _http_get_json(f"{base_url}/api/tags", timeout) is not None + + +def _probe_models(base_url: str, timeout: float) -> List[str]: + """Liefert die Liste der in Ollama geladenen/verfügbaren Modellnamen. + + Leere Liste bei nicht erreichbarem Ollama oder Parse-Fehler. + """ + data = _http_get_json(f"{base_url}/api/tags", timeout) + if not data: + return [] + try: + return [m.get("name", "") for m in data.get("models", [])] + except (AttributeError, TypeError): + return [] + + +def _probe_embedding(base_url: str, model: str, timeout: float) -> bool: + """Stufe 5: Liefert das Embedding-Modell tatsächlich einen Vektor?""" + url = f"{base_url}/api/embeddings" + payload = json.dumps({"model": model, "prompt": "self-check"}).encode("utf-8") + headers = {"Content-Type": "application/json"} + try: + req = urllib.request.Request(url, data=payload, headers=headers, method="POST") + with urllib.request.urlopen(req, timeout=timeout) as resp: + data = json.loads(resp.read().decode("utf-8")) + emb = data.get("embedding") + return isinstance(emb, list) and len(emb) > 0 + except (urllib.error.HTTPError, urllib.error.URLError, + json.JSONDecodeError, OSError, Exception) as e: + logger.warning("[f92-self-check] Embedding-Check fehlgeschlagen: %s", e) + return False + + +# ── check_components(): die gemeinsame Diagnose-Funktion ──────────────────── + + +def check_components() -> ComponentCheckResult: + """Führt die 6-stufige Self-Check-Diagnose aus. + + Analog zu install.sh `check_components()`: gleiche Komponenten, gleiche + Reihenfolge. Blockierend (HTTP-Calls) — der Adapter ruft diese Funktion + deshalb via ``asyncio.to_thread`` + ``wait_for(30s)`` auf, damit der + Gateway-Start nicht blockiert wird. + + Returns: + ComponentCheckResult mit den Ergebnissen aller 6 Stufen. + """ + base_url = OLLAMA_CONFIG["base_url"].rstrip("/") + llm_model = LLM_CONFIG["model"] + emb_model = OLLAMA_CONFIG["model"] + timeout = SELF_CHECK_HTTP_TIMEOUT_S + + faiss_ok = _probe_faiss_importable() # Stufe 1 + index_ok = _probe_index_loadable() # Stufe 2 + ollama_ok = _probe_ollama_reachable(base_url, timeout) # Stufe 3 + + if ollama_ok: + models = _probe_models(base_url, timeout) + llm_loaded = llm_model in models # Stufe 4 + embedding_ok = _probe_embedding(base_url, emb_model, timeout) # Stufe 5 + else: + # Ollama down → Stufen 4/5 sind nicht sinnvoll prüfbar. + llm_loaded = False + embedding_ok = False + + ready = faiss_ok and index_ok and ollama_ok and llm_loaded and embedding_ok # Stufe 6 + + return ComponentCheckResult( + faiss_importable=faiss_ok, + index_loadable=index_ok, + ollama_reachable=ollama_ok, + llm_model_loaded=llm_loaded, + embedding_ladbar=embedding_ok, + ready=ready, + ) + + +# ── User-Meldungen (Feature 92 / install-repair-konzept.md §4) ────────────── + +_ERROR_MESSAGE = ( + "⚠️ Ich kann gerade keine thematische Zuordnung machen — eine Komponente " + "ist nicht vollständig installiert (Raumerkennung).\n\n" + "Das ist kein Problem mit deiner Konfiguration. Ich kann das selbst " + "reparieren.\n\n" + "Reparatur: Führe auf dem Server aus:\n" + " ./install.sh --repair\n\n" + "Das stellt alle fehlenden Komponenten automatisch wieder her. Danach " + "starte ich neu und die Raumerkennung funktioniert wieder." +) + +_WARMUP_MESSAGE = ( + "⏳ Ich lade gerade meine Modelle (Routing + Embedding). Das dauert beim " + "ersten Mal einen Moment — danach läuft die thematische Zuordnung " + "automatisch." +) + + +def build_report_message(result: ComponentCheckResult) -> Optional[str]: + """Baut die User-Meldung zum Check-Ergebnis. + + Returns: + None wenn alles OK (Stufe 6, silent). Sonst die Fehler- (Stufe 1-3) + oder Warmup-Meldung (Stufe 4-5). + """ + if result.ready: + return None + if result.has_error: + return _ERROR_MESSAGE + if result.needs_warmup: + return _WARMUP_MESSAGE + return None diff --git a/plugin/archivar/tests/test_f92_self_check.py b/plugin/archivar/tests/test_f92_self_check.py new file mode 100644 index 0000000..6a7d13c --- /dev/null +++ b/plugin/archivar/tests/test_f92_self_check.py @@ -0,0 +1,267 @@ +""" +Feature 92 — Self-Check: 6-stufige Komponenten-Diagnose nach Gateway-Start. + +Testkonzept (A1c-Pflicht): + 1. check_components() klassifiziert die 6 Stufen korrekt. + 2. Fehler-Stufen (1-3) → --repair-Meldung (build_report_message). + 3. Warmup-Stufen (4-5) → Lade-Meldung (kein Fehler, kein silent). + 4. Stufe 6 (alles OK) → silent (None). + 5. Adapter-Verdrahtung: _start_self_check() ist nicht-blockierend, + überspringt bei MULTIROOM_AGENT=false, und _run_self_check() sendet die + Meldung an den Operator-DM (nicht an den Agenten). + +Die Probes sind module-level Funktionen (self_check._probe_*), damit Tests sie +gezielt patchen können, ohne echte faiss/Ollama-Abhängigkeiten zu brauchen. +""" + +from __future__ import annotations + +import asyncio +import sys +import time +from pathlib import Path +from unittest.mock import AsyncMock, MagicMock, patch + +import pytest + +sys.path.insert(0, str(Path(__file__).resolve().parents[2])) + +from plugin.archivar.self_check import ( + ComponentCheckResult, + build_report_message, + check_components, + SELF_CHECK_TIMEOUT_S, +) + + +def _result(**overrides) -> ComponentCheckResult: + base = dict( + faiss_importable=True, + index_loadable=True, + ollama_reachable=True, + llm_model_loaded=True, + embedding_ladbar=True, + ready=True, + ) + base.update(overrides) + # ready ist abgeleitet — neu berechnen, außer explizit gesetzt. + if "ready" not in overrides: + base["ready"] = ( + base["faiss_importable"] + and base["index_loadable"] + and base["ollama_reachable"] + and base["llm_model_loaded"] + and base["embedding_ladbar"] + ) + return ComponentCheckResult(**base) + + +class TestComponentCheckResult: + """Klassifikations-Logik: has_error / needs_warmup / ready.""" + + def test_ready_when_all_ok(self): + r = _result() + assert r.ready is True + assert r.has_error is False + assert r.needs_warmup is False + + def test_error_when_faiss_missing(self): + r = _result(faiss_importable=False) + assert r.has_error is True + + def test_error_when_index_missing(self): + r = _result(index_loadable=False) + assert r.has_error is True + + def test_error_when_ollama_down(self): + r = _result(ollama_reachable=False) + assert r.has_error is True + + def test_warmup_when_llm_model_missing(self): + r = _result(llm_model_loaded=False) + assert r.has_error is False + assert r.needs_warmup is True + + def test_warmup_when_embedding_missing(self): + r = _result(embedding_ladbar=False) + assert r.has_error is False + assert r.needs_warmup is True + + +class TestCheckComponents: + """check_components() kombiniert die 6 Stufen zur gemeinsamen Diagnose.""" + + def test_all_probes_ok(self): + with patch("plugin.archivar.self_check._probe_faiss_importable", return_value=True), \ + patch("plugin.archivar.self_check._probe_index_loadable", return_value=True), \ + patch("plugin.archivar.self_check._probe_ollama_reachable", return_value=True), \ + patch("plugin.archivar.self_check._probe_models", return_value=["qwen2.5:7b", "nomic-embed-text"]), \ + patch("plugin.archivar.self_check._probe_embedding", return_value=True): + r = check_components() + assert r.ready is True + assert r.faiss_importable and r.index_loadable and r.ollama_reachable + assert r.llm_model_loaded and r.embedding_ladbar + + def test_faiss_missing_reports_error_stage1(self): + with patch("plugin.archivar.self_check._probe_faiss_importable", return_value=False), \ + patch("plugin.archivar.self_check._probe_index_loadable", return_value=True), \ + patch("plugin.archivar.self_check._probe_ollama_reachable", return_value=True), \ + patch("plugin.archivar.self_check._probe_models", return_value=["qwen2.5:7b"]), \ + patch("plugin.archivar.self_check._probe_embedding", return_value=True): + r = check_components() + assert r.faiss_importable is False + assert r.has_error is True + assert r.ready is False + + def test_ollama_down_skips_model_and_embedding_probes(self): + """Stufe 3 down → Stufen 4/5 werden nicht (sinnlos) geprüft.""" + with patch("plugin.archivar.self_check._probe_faiss_importable", return_value=True), \ + patch("plugin.archivar.self_check._probe_index_loadable", return_value=True), \ + patch("plugin.archivar.self_check._probe_ollama_reachable", return_value=False), \ + patch("plugin.archivar.self_check._probe_models") as mock_models, \ + patch("plugin.archivar.self_check._probe_embedding") as mock_emb: + r = check_components() + assert r.ollama_reachable is False + assert r.llm_model_loaded is False + assert r.embedding_ladbar is False + assert r.has_error is True + mock_models.assert_not_called() + mock_emb.assert_not_called() + + def test_llm_model_missing_is_warmup_not_error(self): + with patch("plugin.archivar.self_check._probe_faiss_importable", return_value=True), \ + patch("plugin.archivar.self_check._probe_index_loadable", return_value=True), \ + patch("plugin.archivar.self_check._probe_ollama_reachable", return_value=True), \ + patch("plugin.archivar.self_check._probe_models", return_value=["nomic-embed-text"]), \ + patch("plugin.archivar.self_check._probe_embedding", return_value=True): + r = check_components() + assert r.llm_model_loaded is False + assert r.has_error is False + assert r.needs_warmup is True + + +class TestBuildReportMessage: + """User-Meldungen: silent bei OK, --repair bei Fehler, Laden bei Warmup.""" + + def test_ready_is_silent(self): + assert build_report_message(_result()) is None + + def test_error_mentions_repair_command(self): + msg = build_report_message(_result(faiss_importable=False)) + assert msg is not None + assert "./install.sh --repair" in msg + + def test_warmup_message_is_not_error(self): + msg = build_report_message(_result(llm_model_loaded=False)) + assert msg is not None + assert "./install.sh --repair" not in msg + assert "lade" in msg.lower() or "laden" in msg.lower() + + def test_every_error_stage_mentions_repair(self): + """Stufe 1, 2, 3 — jede Fehler-Stufe muss auf --repair verweisen.""" + for overrides in ( + {"faiss_importable": False}, + {"index_loadable": False}, + {"ollama_reachable": False}, + ): + msg = build_report_message(_result(**overrides)) + assert msg is not None + assert "./install.sh --repair" in msg, f"Stufe {overrides} ohne --repair" + + +class TestAdapterSelfCheckWiring: + """Adapter-Verdrahtung: nicht-blockierend, MULTIROOM-Guard, Operator-DM.""" + + def _make_adapter(self): + from plugin.adapter import RocketChatAdapter + adapter = RocketChatAdapter.__new__(RocketChatAdapter) + adapter.archivar = MagicMock() + adapter._room_info = {"dm_room": {"type": "d"}, "chan": {"type": "c"}} + adapter.rest = MagicMock() + adapter.rest.auth_token = "tok" + adapter._post_message_with_retry = AsyncMock(return_value="msg-id") + return adapter + + def test_start_self_check_skips_when_not_multiroom(self): + adapter = self._make_adapter() + adapter.archivar = None + with patch("plugin.adapter._MULTIROOM", return_value=False), \ + patch("plugin.adapter.asyncio.ensure_future") as mock_ef: + adapter._start_self_check() + mock_ef.assert_not_called() + + def test_start_self_check_is_non_blocking(self): + adapter = self._make_adapter() + with patch("plugin.adapter._MULTIROOM", return_value=True), \ + patch("plugin.adapter.asyncio.ensure_future") as mock_ef: + adapter._start_self_check() + mock_ef.assert_called_once() + + @pytest.mark.asyncio + async def test_run_self_check_error_sends_to_operator(self): + adapter = self._make_adapter() + result = _result(faiss_importable=False) + + with patch("archivar.self_check.check_components", return_value=result), \ + patch("archivar.self_check.build_report_message", return_value="REPAIR MSG"): + await adapter._run_self_check() + + adapter._post_message_with_retry.assert_awaited_once() + args, _ = adapter._post_message_with_retry.call_args + assert args[0] == "dm_room" # Operator-DM, nicht Agent-Chat + assert args[1] == "REPAIR MSG" + + @pytest.mark.asyncio + async def test_run_self_check_ready_is_silent(self): + adapter = self._make_adapter() + result = _result() + + with patch("archivar.self_check.check_components", return_value=result), \ + patch("archivar.self_check.build_report_message", return_value=None): + await adapter._run_self_check() + + adapter._post_message_with_retry.assert_not_called() + + @pytest.mark.asyncio + async def test_run_self_check_timeout_is_silent(self): + """30s-Timeout → keine Meldung, kein Crash. + + check_components() läuft via asyncio.to_thread (synchron in einem + Worker-Thread) — ein blockierender sync-Callable simuliert den Hänger. + """ + adapter = self._make_adapter() + + def _slow(): + time.sleep(10) + return _result() + + with patch("archivar.self_check.check_components", side_effect=_slow), \ + patch("archivar.self_check.SELF_CHECK_TIMEOUT_S", 0.05): + await adapter._run_self_check() + + adapter._post_message_with_retry.assert_not_called() + + @pytest.mark.asyncio + async def test_run_self_check_no_operator_room_is_silent(self): + """Kein DM-Raum → Meldung verworfen, kein Crash.""" + adapter = self._make_adapter() + adapter._room_info = {"chan": {"type": "c"}} + result = _result(faiss_importable=False) + + with patch("archivar.self_check.check_components", return_value=result), \ + patch("archivar.self_check.build_report_message", return_value="REPAIR MSG"): + await adapter._run_self_check() + + adapter._post_message_with_retry.assert_not_called() + + def test_find_operator_room_returns_first_dm(self): + adapter = self._make_adapter() + assert adapter._find_operator_room() == "dm_room" + + def test_find_operator_room_returns_none_without_dm(self): + adapter = self._make_adapter() + adapter._room_info = {"chan": {"type": "c"}} + assert adapter._find_operator_room() is None + + def test_timeout_default_is_30s(self): + assert SELF_CHECK_TIMEOUT_S == 30.0