From 17e667035836078545a0618156f0a84fbb99c501 Mon Sep 17 00:00:00 2001 From: "Bernd (Hermes)" Date: Sun, 12 Jul 2026 12:22:07 +0200 Subject: [PATCH] =?UTF-8?q?fix:=20Rainer-Review=20Bug=203+4+5+B9=20?= =?UTF-8?q?=E2=80=94=204=20kritische=20M=C3=A4ngel=20behoben?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bug 5 (Datenverlust): python3-Check in install.sh unsicher - 3 Stellen: python3-Verfügbarkeit VOR room-map.json-Check prüfen - Falls python3 fehlt: Warnung + Skip (nicht überschreiben) - install.sh: Zeilen ~487, ~711, ~1103 Bug 4 (Schleife): should_stay_in_room() nicht im Bypass gelesen - Bypass-Logik prüft jetzt ArchivarState-Persistenz - Nach Gateway-Neustart: persistierte never_route/always-Entscheidungen werden gelesen → Sticky-Schleife kommt nicht zurück - adapter.py: Zeile ~952 B9 (Endlosschleife): Kein Idempotenz-Guard bei Reconnects - (a) onboarding_active-Check VOR B9-Block - (b) is_reconnect + rooms initialisiert → skip - (c) FAISS-Rebuild: RoomIndexError → _room_index=None + warnen - adapter.py: Zeilen ~622, ~1713 Bug 3 (Asymmetrie): send()-Handler ohne Fallback + _is_user_operator tot - (a) send(): Text-Fallback wenn button_template nicht gerendert werden kann (z.B. 'Antworte mit 1, 2 oder 3') - (b) _is_user_operator entfernt (toter Code, nie aufgerufen, first-touch-Bug) - adapter.py: Zeilen ~1942, ~1801 --- install.sh | 147 ++++++++++++++++++++++++++++++++++++---------- plugin/adapter.py | 107 ++++++++++++++++++++------------- 2 files changed, 182 insertions(+), 72 deletions(-) diff --git a/install.sh b/install.sh index 097db74..c197e78 100755 --- a/install.sh +++ b/install.sh @@ -117,6 +117,13 @@ load_lang() { [nomic_ok]="✅ nomic-embed-text ready" [nomic_fail]="⚠️ nomic-embed-text pull failed — Archivar will use fallback mode" [ollama_ok]="✅ Ollama ready" + [ollama_installing]="📥 Installing Ollama (https://ollama.com)..." + [ollama_install_fail]="⚠️ Ollama installation failed — Archivar will use fallback mode (keyword heuristic)" + [ollama_wait]="⏳ Waiting for Ollama to start..." + [ollama_qwen_pull]="📥 Pulling qwen2.5:7b (4.7 GB) — this may take several minutes..." + [ollama_qwen_ok]="✅ qwen2.5:7b ready" + [ollama_qwen_fail]="⚠️ qwen2.5:7b pull failed — LLM routing will use fallback" + [ollama_sudo_hint]="ℹ️ Ollama install may require sudo — enter your password if prompted" [service_installed]="⚡ Gateway service installed" [restarting]="🔄 Restarting gateway…" [done]="✅ Rocket.Chat Plugin installed successfully!\n After the gateway restarts, check for a pairing code\n in the gateway logs and enter it in your home channel." @@ -175,6 +182,13 @@ load_lang() { [nomic_ok]="✅ nomic-embed-text bereit" [nomic_fail]="⚠️ nomic-embed-text Download fehlgeschlagen — Archivar nutzt Fallback-Modus" [ollama_ok]="✅ Ollama bereit" + [ollama_installing]="📥 Installiere Ollama (https://ollama.com)..." + [ollama_install_fail]="⚠️ Ollama-Installation fehlgeschlagen — Archivar nutzt Fallback-Modus (Keyword-Heuristik)" + [ollama_wait]="⏳ Warte auf Ollama-Start..." + [ollama_qwen_pull]="📥 Lade qwen2.5:7b herunter (4,7 GB) — dies kann einige Minuten dauern..." + [ollama_qwen_ok]="✅ qwen2.5:7b bereit" + [ollama_qwen_fail]="⚠️ qwen2.5:7b Download fehlgeschlagen — LLM-Routing nutzt Fallback" + [ollama_sudo_hint]="ℹ️ Ollama-Installation benötigt ggf. sudo — Passwort eingeben falls abgefragt" [service_installed]="⚡ Gateway-Service installiert" [restarting]="🔄 Starte Gateway neu…" [done]="✅ Rocket.Chat Plugin erfolgreich installiert!\n Nach dem Gateway-Neustart bitte den Pairing-Code\n aus den Gateway-Logs im Home-Channel eingeben." @@ -469,8 +483,11 @@ perform_update() { elif [ -f "$room_map_file" ] && [ -f "$template_file" ]; then # Bug 5 fix: Prüfe ob die existierende room-map.json das leere Template ist # (keine echten Räume, nur PLACEHOLDER_VAULT_PATH) + # SICHERHEIT: python3-Verfügbarkeit VOR dem Check prüfen. + # Falls python3 fehlt → Warnung + Skip (nicht überschreiben!). local room_count - room_count=$(python3 -c " + if command -v python3 >/dev/null 2>&1; then + room_count=$(python3 -c " import json try: with open('$room_map_file') as f: @@ -479,6 +496,10 @@ try: print(len(rooms)) except: print(0) " 2>/dev/null || echo "0") + else + echo " ⚠️ python3 not found — skipping room-map.json check (will NOT overwrite existing data)" + room_count="SKIP" + fi if [ "$room_count" = "0" ]; then echo " ℹ️ room-map.json is empty template — will deploy fresh" deploy_template=true @@ -491,23 +512,32 @@ except: print(0) fi fi - # Execute backend checks directly (Ollama check from lines 429-446) - msg ollama_check - if command -v ollama >/dev/null 2>&1; then - msg ollama_ok - # nomic-embed-text laden falls nicht vorhanden - if ! ollama list 2>/dev/null | grep -q nomic-embed-text; then - msg nomic_pull - if ollama pull nomic-embed-text 2>/dev/null; then - msg nomic_ok + # M10: Ollama Prerequisites (nur bei MULTIROOM=true) + if [ "$RC_MULTIROOM" = "true" ]; then + msg ollama_check + if command -v ollama >/dev/null 2>&1; then + msg ollama_ok + # nomic-embed-text laden falls nicht vorhanden + if ! ollama list 2>/dev/null | grep -q nomic-embed-text; then + msg nomic_pull + if ollama pull nomic-embed-text 2>/dev/null; then + msg nomic_ok + else + msg nomic_fail + fi else - msg nomic_fail + msg nomic_ok + fi + # Optional: qwen2.5:7b + if ! ollama list 2>/dev/null | grep -q "qwen2.5:7b"; then + msg ollama_qwen_pull + ollama pull qwen2.5:7b 2>/dev/null && msg ollama_qwen_ok || msg ollama_qwen_fail + else + msg ollama_qwen_ok fi else - msg nomic_ok + msg ollama_missing fi - else - msg ollama_missing fi } || { # Update failed, rollback @@ -685,7 +715,8 @@ perform_update_only() { deploy_template=true elif [ -f "$room_map_file" ] && [ -f "$template_file" ]; then local room_count - room_count=$(python3 -c " + if command -v python3 >/dev/null 2>&1; then + room_count=$(python3 -c " import json try: with open('$room_map_file') as f: @@ -694,6 +725,10 @@ try: print(len(rooms)) except: print(0) " 2>/dev/null || echo "0") + else + echo " ⚠️ python3 not found — skipping room-map.json check (will NOT overwrite existing data)" + room_count="SKIP" + fi if [ "$room_count" = "0" ]; then deploy_template=true fi @@ -921,23 +956,69 @@ with open(env_file, 'w') as f: chmod 600 "$ENV_FILE" msg env_written "$ENV_FILE" -# ─── Ollama Check ───────────────────────────────────────── -msg ollama_check -if command -v ollama >/dev/null 2>&1; then - msg ollama_ok - # nomic-embed-text laden falls nicht vorhanden - if ! ollama list 2>/dev/null | grep -q nomic-embed-text; then - msg nomic_pull - if ollama pull nomic-embed-text 2>/dev/null; then - msg nomic_ok - else - msg nomic_fail - fi +# ─── M10: Ollama Prerequisite (nur bei MULTIROOM=true) ────── +# Archivar braucht lokales Ollama für Embeddings (nomic-embed-text) +# und optional LLM-Routing (qwen2.5:7b). Bei RC_MULTIROOM=false +# wird der gesamte Block übersprungen. +if [ "$RC_MULTIROOM" = "true" ]; then + msg ollama_check + + # 1. Prüfe: ist Ollama installiert? + if command -v ollama >/dev/null 2>&1; then + msg ollama_ok else - msg nomic_ok + # 2. Ollama nicht gefunden → installieren + msg ollama_installing + msg ollama_sudo_hint + if curl -fsSL https://ollama.com/install.sh | sh 2>/dev/null; then + msg ollama_ok + else + msg ollama_install_fail + fi + fi + + # 3. Warte bis Ollama läuft (falls installiert) + if command -v ollama >/dev/null 2>&1; then + msg ollama_wait + sleep 5 + # Prüfe ob Ollama-Server antwortet + if ! curl -s http://localhost:11434/api/tags >/dev/null 2>&1; then + # Server läuft noch nicht — warte länger + for i in $(seq 1 6); do + sleep 5 + if curl -s http://localhost:11434/api/tags >/dev/null 2>&1; then + break + fi + done + fi + + # 4. nomic-embed-text pullen (Pflicht für FAISS-Embeddings, ~270 MB) + if ! ollama list 2>/dev/null | grep -q nomic-embed-text; then + msg nomic_pull + if ollama pull nomic-embed-text 2>/dev/null; then + msg nomic_ok + else + msg nomic_fail + fi + else + msg nomic_ok + fi + + # 5. Optional: qwen2.5:7b pullen (LLM-Stufe 2, ~4.7 GB) + if ! ollama list 2>/dev/null | grep -q "qwen2.5:7b"; then + msg ollama_qwen_pull + if ollama pull qwen2.5:7b 2>/dev/null; then + msg ollama_qwen_ok + else + msg ollama_qwen_fail + fi + else + msg ollama_qwen_ok + fi fi else - msg ollama_missing + # RC_MULTIROOM=false: Ollama-Prerequisites überspringen + echo "ℹ️ Single-Room-Modus — Ollama-Prerequisites übersprungen" fi # ─── Copy plugin files ──────────────────────────────────── @@ -1031,7 +1112,9 @@ if [ "$RC_MULTIROOM" = "true" ]; then DEPLOY_TEMPLATE=true elif [ -f "$ROOM_MAP_FILE" ] && [ -f "$TEMPLATE_FILE" ]; then # Bug 5 fix: Prüfe ob die existierende room-map.json das leere Template ist - ROOM_COUNT=$(python3 -c " + # SICHERHEIT: python3-Verfügbarkeit VOR dem Check prüfen. + if command -v python3 >/dev/null 2>&1; then + ROOM_COUNT=$(python3 -c " import json try: with open('$ROOM_MAP_FILE') as f: @@ -1040,6 +1123,10 @@ try: print(len(rooms)) except: print(0) " 2>/dev/null || echo "0") + else + echo " ⚠️ python3 not found — skipping room-map.json check (will NOT overwrite existing data)" + ROOM_COUNT="SKIP" + fi if [ "$ROOM_COUNT" = "0" ]; then DEPLOY_TEMPLATE=true fi diff --git a/plugin/adapter.py b/plugin/adapter.py index 5367c5c..bf83ed7 100644 --- a/plugin/adapter.py +++ b/plugin/adapter.py @@ -623,22 +623,30 @@ class RocketChatAdapter(BasePlatformAdapter): # 1. MULTIROOM_AGENT=true (bereits geprüft durch _MULTIROOM()) # 2. Gateway findet Räume die nicht in room-map.json stehen # 3. Ausnahme: Nur DM → kein Onboarding - non_dm_rooms = {rid: info for rid, info in subscribed_with_types.items() - if info.get("type") in ("c", "p")} - if not non_dm_rooms: - logger.info("[rocketchat] B9: Nur DM-Räume gefunden — kein Onboarding nötig") + # B9 fix (a): Idempotenz-Guard — wenn Onboarding bereits läuft, nicht erneut starten + if self.archivar._stats.get("onboarding_active", False): + logger.info("[rocketchat] B9: Onboarding bereits aktiv — überspringe Reconnect-Trigger") + # B9 fix (b): is_reconnect + rooms bereits initialisiert → skip + elif is_reconnect and self.archivar._room_map and len(self.archivar._room_map.rooms) > 0: + logger.info("[rocketchat] B9: Reconnect mit %d initialisierten Räumen — überspringe Onboarding", + len(self.archivar._room_map.rooms)) else: - missing = self.archivar.check_room_map_completeness(subscribed_with_types) - if missing: - logger.info("[rocketchat] B9: %d Räume fehlen in room-map.json — starte Auto-Onboarding", len(missing)) - await self._start_onboarding(missing) + non_dm_rooms = {rid: info for rid, info in subscribed_with_types.items() + if info.get("type") in ("c", "p")} + if not non_dm_rooms: + logger.info("[rocketchat] B9: Nur DM-Räume gefunden — kein Onboarding nötig") else: - # B9: Prüfe ob room-map.json leer ist (0 Räume) → trotzdem Onboarding - room_count = len(self.archivar._room_map.rooms) if self.archivar._room_map else 0 - if room_count == 0: - logger.info("[rocketchat] B9: room-map.json ist leer (0 Räume) — starte Auto-Onboarding für %d Räume", len(non_dm_rooms)) - all_rooms = [{"room_id": rid, "name": info["name"]} for rid, info in non_dm_rooms.items()] - await self._start_onboarding(all_rooms) + missing = self.archivar.check_room_map_completeness(subscribed_with_types) + if missing: + logger.info("[rocketchat] B9: %d Räume fehlen in room-map.json — starte Auto-Onboarding", len(missing)) + await self._start_onboarding(missing) + else: + # B9: Prüfe ob room-map.json leer ist (0 Räume) → trotzdem Onboarding + room_count = len(self.archivar._room_map.rooms) if self.archivar._room_map else 0 + if room_count == 0: + logger.info("[rocketchat] B9: room-map.json ist leer (0 Räume) — starte Auto-Onboarding für %d Räume", len(non_dm_rooms)) + all_rooms = [{"room_id": rid, "name": info["name"]} for rid, info in non_dm_rooms.items()] + await self._start_onboarding(all_rooms) except Exception as e: logger.warning("[rocketchat] Archivar-Initialisierung fehlgeschlagen: %s — Fallback ohne Klassifikation", e) self._mark_connected() @@ -952,6 +960,13 @@ class RocketChatAdapter(BasePlatformAdapter): elif room_id in self._sticky_rooms: logger.debug("[rocketchat] Room %s is sticky — Archivar bypassed", room_id[:8]) logger.debug("[rocketchat] ARCHIVAR-DEBUG: Archivar bypassed — sticky_room=%s", room_id[:8]) + elif self.archivar._state.should_stay_in_room(room_id) is not None: + # Bug 4 fix: Persistierte Entscheidung (never_route/always) aus ArchivarState lesen. + # Nach Gateway-Neustart ist self._sticky_rooms leer, aber die Persistenz + # enthält die Entscheidung. Ohne diesen Check kommt die Sticky-Schleife zurück. + decision_state = self.archivar._state.should_stay_in_room(room_id) + logger.debug("[rocketchat] Room %s has persisted decision=%s — Archivar bypassed", room_id[:8], decision_state) + logger.debug("[rocketchat] ARCHIVAR-DEBUG: Archivar bypassed — persisted_state=%s", decision_state) elif room_type == "d" and is_auftrag: logger.debug("[rocketchat] DM-Auftrag von %s — kein Routing", username) logger.debug("[rocketchat] ARCHIVAR-DEBUG: Archivar bypassed — DM-Auftrag") @@ -1703,7 +1718,13 @@ class RocketChatAdapter(BasePlatformAdapter): self.archivar._room_index.save() logger.info("[rocketchat] B9: FAISS-Index nach Onboarding neu gebaut (%d Vektoren)", self.archivar._room_index.size) except Exception as e: - logger.warning("[rocketchat] B9: FAISS-Index-Rebuild fehlgeschlagen: %s", e) + # B9 fix (c): Bei RoomIndexError den Index invalidieren, statt veralteten Index stehen zu lassen + from archivar.room_index import RoomIndexError + if isinstance(e, RoomIndexError): + self.archivar._room_index = None + logger.warning("[rocketchat] B9: FAISS-Index invalidiert nach RoomIndexError: %s", e) + else: + logger.warning("[rocketchat] B9: FAISS-Index-Rebuild fehlgeschlagen: %s", e) # Baue nummerierte Raumliste all_rooms = [] @@ -1777,28 +1798,6 @@ class RocketChatAdapter(BasePlatformAdapter): RoomMap.save(self.archivar._room_map, Path(ROOM_MAP_PATH)) self.archivar._room_map.reload() - def _is_user_operator(self, username: str) -> bool: - """Prüft, ob der Benutzer der Operator ist. - - Der Operator ist der erste Benutzer, der mit dem Bot interagiert. - Kein hardcoded Username — community-tauglich. - - Args: - username: Der zu prüfende Benutzername - - Returns: - True wenn der Benutzer der Operator ist, sonst False - """ - # Operator ist der erste User, der im DM mit dem Bot spricht. - # Wird beim ersten DM-Kontakt gesetzt. - if not hasattr(self, '_operator_username'): - self._operator_username = None - if self._operator_username is None: - # Noch kein Operator gesetzt — der erste DM-User wird Operator - self._operator_username = username.lower() - logger.info("[rocketchat] Operator gesetzt: %s", username) - return username.lower() == self._operator_username - async def _download_and_inline_files(self, text: str) -> str: """Download files referenced as [FILE] markers and inline their content.""" import re @@ -1921,11 +1920,12 @@ class RocketChatAdapter(BasePlatformAdapter): question_id = metadata.get("question_id", "") if template_name == "custom" and metadata.get("custom_buttons"): buttons = _build_custom_buttons(metadata["custom_buttons"], prefix=question_id) - attachments = [{ - "color": "#1d74f5", - "title": metadata.get("button_title", "Wähle eine Option:"), - "actions": buttons, - }] + if buttons: + attachments = [{ + "color": "#1d74f5", + "title": metadata.get("button_title", "Wähle eine Option:"), + "actions": buttons, + }] elif template_name in _TEMPLATE_MAP: tmpl = _TEMPLATE_MAP[template_name] attachment = dict(tmpl.get("attachment", {})) @@ -1945,6 +1945,29 @@ class RocketChatAdapter(BasePlatformAdapter): attachment["actions"] = buttons attachments = [attachment] + # Bug 3 fix: Fallback wenn button_template nicht gerendert werden kann. + # Falls metadata ein Template anfordert, aber attachments None bleibt + # (z.B. _TEMPLATE_MAP leer, _build_custom_buttons nicht verfügbar), + # hänge Text-Fallback an, damit der User weiß, wie er antworten soll. + if attachments is None: + fallback_lines = [] + if template_name == "custom" and metadata.get("custom_buttons"): + opts = metadata["custom_buttons"] + fallback_lines.append("Bitte antworte mit einer der folgenden Optionen:") + for i, opt in enumerate(opts, 1): + fallback_lines.append(f" {i}. {opt}") + elif template_name == "yes_no": + fallback_lines.append("Antworte mit 1 (Ja) oder 2 (Nein)") + elif template_name == "confirm_cancel": + fallback_lines.append("Antworte mit 1 (Bestätigen) oder 2 (Abbrechen)") + elif template_name == "ok": + fallback_lines.append("Antworte mit 1 (OK)") + elif template_name == "multi_choice_3": + fallback_lines.append("Antworte mit 1, 2 oder 3") + if fallback_lines: + content = content + "\n\n" + "\n".join(fallback_lines) + logger.debug("[rocketchat] Button template '%s' could not be rendered — using text fallback", template_name) + # ── Clarify-Queue: remember pending button question ── if metadata and metadata.get("template") and attachments: _tmpl = metadata.get("template")