From 631e3c1db48e3bfedfddae1298deb476b6c7df81 Mon Sep 17 00:00:00 2001 From: "Bernd (Hermes)" Date: Wed, 15 Jul 2026 21:17:06 +0200 Subject: [PATCH] =?UTF-8?q?feat:=20V8.4.2=20=E2=80=94=20Onboarding=20Keywo?= =?UTF-8?q?rd-Conflict-Check=20(Kollisionserkennung=20+=20Klarstellung)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - room_map.py: check_keyword_conflicts() erweitert um keyword_type-Parameter und alle 4 Konflikt-Typen (CRITICAL, WARNING, INFO, OK) - adapter.py: Konflikt-Prüfung nach keywords_100 und keywords_context Eingabe im Onboarding-Flow integriert - _ask_keyword_conflict_resolution(): neue Methode für Konflikt-Dialog mit 'Trotzdem verwenden' / 'Anderes Keyword' Buttons - Konflikt-Auflösung mit Re-Enter-Loop für Neueingabe - Logging: 'Onboarding-Conflict: keyword ... user chose: keep anyway / change' - test_v8_4_2.py: 17 neue Tests (RoomMap-Level + Adapter-Level) - test_v8_2.py: bestehende Tests an neue Signatur angepasst --- plugin/adapter.py | 249 ++++++++++ plugin/archivar/room_map.py | 46 +- plugin/archivar/tests/test_v8_2.py | 8 +- plugin/archivar/tests/test_v8_4_2.py | 660 +++++++++++++++++++++++++++ 4 files changed, 954 insertions(+), 9 deletions(-) create mode 100644 plugin/archivar/tests/test_v8_4_2.py diff --git a/plugin/adapter.py b/plugin/adapter.py index 9430aed..c08065d 100644 --- a/plugin/adapter.py +++ b/plugin/adapter.py @@ -2940,6 +2940,164 @@ class RocketChatAdapter(BasePlatformAdapter): logger.info("[rocketchat] Onboarding v2 vollständig abgeschlossen (mit Butler-Mode)") return + # ── V8.4.2: Keyword-Konflikt-Auflösung ────────────────────────── + conflict_phase = state.get("conflict_phase", "") + if conflict_phase in ("keywords_100", "keywords_context"): + single_line = text.strip() + + # Button-Klick: CONFLICT::: + if single_line.startswith("CONFLICT:"): + parts = single_line.split("::", 1) + action = parts[1] if len(parts) > 1 else "" + + if "keep" in action or "Trotzdem" in action or "1️⃣" in action: + # Trotzdem verwenden — Keyword bleibt, Warnung im Log + conflict_list = state.get("conflict_list", []) + for c in conflict_list: + logger.info( + "Onboarding-Conflict: keyword \"%s\" already in %s as %s-keyword — user chose: keep anyway", + c["keyword"], c["room_name"], c["existing_type"], + ) + # Weiter mit nächster Frage + if conflict_phase == "keywords_100": + state["current_question"] = 3 + else: + # keywords_context → DM oder Frage 4 + room = state["missing_rooms"][state["current_room_index"]] + is_dm = room.get("is_dm", False) + if is_dm: + # DM: direkt speichern + rid = room["room_id"] + data = state["collected_data"].get(rid, {}) + data["catch_all"] = True + room_name = room["name"] + self.archivar._room_map.add_or_update_room( + room_id=rid, + name=room_name, + theme=data["theme"], + keywords_100=data.get("keywords_100", []), + keywords_context=data.get("keywords_context", []), + catch_all=True, + ) + from archivar.room_map import RoomMap + from archivar.config import ROOM_MAP_PATH + from pathlib import Path + RoomMap.save(self.archivar._room_map, Path(ROOM_MAP_PATH)) + self.archivar._room_map.reload() + logger.info("[rocketchat] Onboarding: DM %s zur Map hinzugefügt (catch_all=True, Thema: %s)", + room_name, data["theme"]) + await self._post_message_with_retry(operator_room_id, + f"✅ {room_name} eingerichtet: 🎯 Catch-All\n" + f"Thema: {data['theme']}\n" + f"Keywords (sicher): {', '.join(data['keywords_100']) if data['keywords_100'] else 'keine'}\n" + f"Keywords (Kontext): {', '.join(data['keywords_context']) if data['keywords_context'] else 'keine'}") + await self._onboarding_next_room() + else: + state["current_question"] = 4 + await self._ask_onboarding_question(operator_room_id) + # Cleanup conflict state + state.pop("conflict_phase", None) + state.pop("conflict_keywords", None) + state.pop("conflict_list", None) + return + + if "change" in action or "Anderes" in action or "2️⃣" in action: + # Anderes Keyword — Nutzer soll neu eingeben + conflict_list = state.get("conflict_list", []) + for c in conflict_list: + logger.info( + "Onboarding-Conflict: keyword \"%s\" already in %s as %s-keyword — user chose: change", + c["keyword"], c["room_name"], c["existing_type"], + ) + # Setze Sub-Phase: warte auf neue Keyword-Eingabe + state["conflict_sub_phase"] = "reenter" + conflict_kws = [c["keyword"] for c in conflict_list] + await self._post_message_with_retry(operator_room_id, + f"👍 Verstanden. Bitte gib neue Keywords ein (kommagetrennt) — " + f"die folgenden sind bereits vergeben: {', '.join(conflict_kws)}") + return + + # Sub-Phase: Nutzer gibt neue Keywords ein nach "Anderes Keyword" + if state.get("conflict_sub_phase") == "reenter": + raw = single_line + if raw.lower() in ("keine", "none", "-", ""): + new_kws = [] + elif "," in raw: + new_kws = [kw.strip().lower() for kw in raw.split(",") if kw.strip()] + else: + new_kws = [kw.strip().lower() for kw in raw.split() if kw.strip()] + new_kws = new_kws[:10] + + # Erneut auf Konflikte prüfen + if new_kws and self.archivar is not None: + rid = state["missing_rooms"][state["current_room_index"]]["room_id"] + kw_type = "100" if conflict_phase == "keywords_100" else "context" + conflicts = self.archivar._room_map.check_keyword_conflicts( + keywords=new_kws, + exclude_room_id=rid, + keyword_type=kw_type, + ) + if kw_type == "100": + relevant = [c for c in conflicts if c["conflict_type"] in ("CRITICAL", "WARNING")] + else: + relevant = [c for c in conflicts if c["conflict_type"] == "INFO"] + if relevant: + state["conflict_keywords"] = new_kws + state["conflict_list"] = relevant + await self._ask_keyword_conflict_resolution( + operator_room_id, relevant, + "100%" if conflict_phase == "keywords_100" else "Kontext", + ) + return + + # Keine Konflikte mehr → speichern und weitermachen + rid = state["missing_rooms"][state["current_room_index"]]["room_id"] + data = state["collected_data"].get(rid, {}) + if conflict_phase == "keywords_100": + data["keywords_100"] = new_kws + state["current_question"] = 3 + else: + data["keywords_context"] = new_kws + room = state["missing_rooms"][state["current_room_index"]] + is_dm = room.get("is_dm", False) + if is_dm: + data["catch_all"] = True + room_name = room["name"] + self.archivar._room_map.add_or_update_room( + room_id=rid, + name=room_name, + theme=data["theme"], + keywords_100=data.get("keywords_100", []), + keywords_context=data.get("keywords_context", []), + catch_all=True, + ) + from archivar.room_map import RoomMap + from archivar.config import ROOM_MAP_PATH + from pathlib import Path + RoomMap.save(self.archivar._room_map, Path(ROOM_MAP_PATH)) + self.archivar._room_map.reload() + logger.info("[rocketchat] Onboarding: DM %s zur Map hinzugefügt (catch_all=True, Thema: %s)", + room_name, data["theme"]) + await self._post_message_with_retry(operator_room_id, + f"✅ {room_name} eingerichtet: 🎯 Catch-All\n" + f"Thema: {data['theme']}\n" + f"Keywords (sicher): {', '.join(data['keywords_100']) if data['keywords_100'] else 'keine'}\n" + f"Keywords (Kontext): {', '.join(data['keywords_context']) if data['keywords_context'] else 'keine'}") + state.pop("conflict_phase", None) + state.pop("conflict_keywords", None) + state.pop("conflict_list", None) + state.pop("conflict_sub_phase", None) + await self._onboarding_next_room() + return + else: + state["current_question"] = 4 + state.pop("conflict_phase", None) + state.pop("conflict_keywords", None) + state.pop("conflict_list", None) + state.pop("conflict_sub_phase", None) + await self._ask_onboarding_question(operator_room_id) + return + # ── Modus 1: Button-Klick (ONBOARD:::) ────────── if text.startswith("ONBOARD:") and "::" in text: prefix_part, action = text.split("::", 1) @@ -3053,6 +3211,23 @@ class RocketChatAdapter(BasePlatformAdapter): else: kws = [kw.strip().lower() for kw in raw.split() if kw.strip()] data["keywords_100"] = kws[:10] + + # V8.4.2: Keyword-Konflikt-Prüfung für 100%-Keywords + if data["keywords_100"] and self.archivar is not None: + conflicts = self.archivar._room_map.check_keyword_conflicts( + keywords=data["keywords_100"], + exclude_room_id=rid, + keyword_type="100", + ) + # Nur CRITICAL und WARNING sind relevant (100% vs 100% oder 100% vs context) + relevant = [c for c in conflicts if c["conflict_type"] in ("CRITICAL", "WARNING")] + if relevant: + state["conflict_phase"] = "keywords_100" + state["conflict_keywords"] = data["keywords_100"] + state["conflict_list"] = relevant + await self._ask_keyword_conflict_resolution(operator_room_id, relevant, "100%") + return + state["current_question"] = 3 await self._ask_onboarding_question(operator_room_id) return @@ -3069,6 +3244,23 @@ class RocketChatAdapter(BasePlatformAdapter): kws = [kw.strip().lower() for kw in raw.split() if kw.strip()] data["keywords_context"] = kws[:10] + # V8.4.2: Keyword-Konflikt-Prüfung für Kontext-Keywords + if data["keywords_context"] and self.archivar is not None: + conflicts = self.archivar._room_map.check_keyword_conflicts( + keywords=data["keywords_context"], + exclude_room_id=rid, + keyword_type="context", + ) + # Nur INFO ist relevant (context vs 100% — Butler fragt im anderen Raum) + # OK (context vs context) wird ignoriert + relevant = [c for c in conflicts if c["conflict_type"] == "INFO"] + if relevant: + state["conflict_phase"] = "keywords_context" + state["conflict_keywords"] = data["keywords_context"] + state["conflict_list"] = relevant + await self._ask_keyword_conflict_resolution(operator_room_id, relevant, "Kontext") + return + # DM: Frage 4 (catch_all) überspringen — DM ist immer Catch-All is_dm = room.get("is_dm", False) if is_dm: @@ -3154,6 +3346,63 @@ class RocketChatAdapter(BasePlatformAdapter): await self._onboarding_next_room() return + async def _ask_keyword_conflict_resolution( + self, operator_room_id: str, conflicts: list, keyword_label: str + ) -> None: + """V8.4.2: Fragt den Operator bei Keyword-Konflikten um Klarstellung. + + Args: + operator_room_id: DM-Raum-ID des Operators. + conflicts: Liste von Konflikten (aus check_keyword_conflicts). + keyword_label: "100%" oder "Kontext" für die Anzeige. + """ + state = self._onboarding_state + if not state: + return + + rid = state["missing_rooms"][state["current_room_index"]]["room_id"] + + # Baue Konflikt-Beschreibung + conflict_lines = [] + for c in conflicts: + ctype = c["conflict_type"] + if ctype == "CRITICAL": + severity = "🔴 KRITISCH" + explanation = "führt zu willkürlichem Routing" + elif ctype == "WARNING": + severity = "🟡 WARNUNG" + explanation = "Butler könnte fälschlich fragen" + elif ctype == "INFO": + severity = "🔵 INFO" + explanation = "Butler fragt im anderen Raum" + else: + severity = "⚪ OK" + explanation = "beide dürfen fragen" + + conflict_lines.append( + f"• \"{c['keyword']}\" — bereits als {c['existing_type']}%-Keyword " + f"in {c['room_name']} ({severity}: {explanation})" + ) + + text = ( + f"⚠️ **Keyword-Konflikt erkannt** ({keyword_label}-Keywords):\n\n" + + "\n".join(conflict_lines) + + "\n\n👉 Möchtest Du die Keywords trotzdem verwenden oder andere wählen?" + ) + + _build = self._get_build_custom_buttons() + buttons = _build( + ["1️⃣ Trotzdem verwenden", "2️⃣ Anderes Keyword"], + prefix=f"CONFLICT:{rid}", + style="primary", + ) + attachments = [{ + "color": "#f5a623", + "title": "Keyword-Konflikt auflösen", + "actions": buttons, + }] + await self._post_message_with_retry(operator_room_id, text, attachments=attachments) + async def _ask_onboarding_question(self, operator_room_id: str) -> None: """Sendet die aktuelle Interview-Frage an den Operator.""" state = self._onboarding_state diff --git a/plugin/archivar/room_map.py b/plugin/archivar/room_map.py index 6eb59cc..eb39c42 100644 --- a/plugin/archivar/room_map.py +++ b/plugin/archivar/room_map.py @@ -517,16 +517,29 @@ class RoomMap: # ── V8.2: A1 — Onboarding-Widerspruchsprüfung ────────────────────── def check_keyword_conflicts( - self, keywords_100: list[str], exclude_room_id: str = "" + self, + keywords: list[str], + exclude_room_id: str = "", + keyword_type: str = "100", ) -> list[dict]: - """Prüft ob 100%-Keywords bereits in anderen Räumen existieren. + """Prüft ob Keywords bereits in anderen Räumen existieren. Args: - keywords_100: Liste der zu prüfenden 100%-Keywords. + keywords: Liste der zu prüfenden Keywords. exclude_room_id: Raum-ID die ausgeschlossen wird (der eigene Raum). + keyword_type: Typ der neuen Keywords: "100" (100%-Keyword) oder + "context" (Kontext-Keyword). Returns: - Liste von Konflikten: [{"keyword": str, "room_id": str, "room_name": str}] + Liste von Konflikten: + [{"keyword": str, "room_id": str, "room_name": str, + "conflict_type": str, "existing_type": str}] + + conflict_type: + - "CRITICAL": 100%-Keyword kollidiert mit 100%-Keyword + - "WARNING": 100%-Keyword kollidiert mit Kontext-Keyword + - "INFO": Kontext-Keyword kollidiert mit 100%-Keyword + - "OK": Kontext-Keyword kollidiert mit Kontext-Keyword """ conflicts = [] for room_id, room in self._rooms.items(): @@ -534,16 +547,39 @@ class RoomMap: continue if room.catch_all: continue - for kw in keywords_100: + for kw in keywords: kw_lower = kw.lower() + # Prüfe gegen 100%-Keywords im existierenden Raum for existing_kw in room.keywords_100: if existing_kw.lower() == kw_lower: + if keyword_type == "100": + conflict_type = "CRITICAL" + else: + conflict_type = "INFO" conflicts.append({ "keyword": kw, "room_id": room_id, "room_name": room.name, + "conflict_type": conflict_type, + "existing_type": "100", }) break + else: + # Prüfe gegen Kontext-Keywords im existierenden Raum + for existing_kw in room.keywords_context: + if existing_kw.lower() == kw_lower: + if keyword_type == "100": + conflict_type = "WARNING" + else: + conflict_type = "OK" + conflicts.append({ + "keyword": kw, + "room_id": room_id, + "room_name": room.name, + "conflict_type": conflict_type, + "existing_type": "context", + }) + break return conflicts # ── V8.2: A3 — Lernfunktion-Persistenz ────────────────────────────── diff --git a/plugin/archivar/tests/test_v8_2.py b/plugin/archivar/tests/test_v8_2.py index 570f73b..3804eb4 100644 --- a/plugin/archivar/tests/test_v8_2.py +++ b/plugin/archivar/tests/test_v8_2.py @@ -64,7 +64,7 @@ class TestA1OnboardingConflictCheck(unittest.TestCase): """Kein Konflikt wenn 100%-Keywords einzigartig sind.""" room_map = RoomMap._from_dict(self.test_data) conflicts = room_map.check_keyword_conflicts( - keywords_100=["dokumentation", "netzwerk"], + keywords=["dokumentation", "netzwerk"], exclude_room_id="new_room_id", ) self.assertEqual(len(conflicts), 0) @@ -73,7 +73,7 @@ class TestA1OnboardingConflictCheck(unittest.TestCase): """Konflikt wenn 100%-Keyword bereits in anderem Raum existiert.""" room_map = RoomMap._from_dict(self.test_data) conflicts = room_map.check_keyword_conflicts( - keywords_100=["plugin", "neues-thema"], + keywords=["plugin", "neues-thema"], exclude_room_id="new_room_id", ) self.assertEqual(len(conflicts), 1) @@ -85,7 +85,7 @@ class TestA1OnboardingConflictCheck(unittest.TestCase): """Mehrere Konflikte werden erkannt.""" room_map = RoomMap._from_dict(self.test_data) conflicts = room_map.check_keyword_conflicts( - keywords_100=["plugin", "rocketchat", "gateway"], + keywords=["plugin", "rocketchat", "gateway"], exclude_room_id="new_room_id", ) self.assertEqual(len(conflicts), 3) @@ -94,7 +94,7 @@ class TestA1OnboardingConflictCheck(unittest.TestCase): """Kein Konflikt wenn der eigene Raum excluded wird (Update).""" room_map = RoomMap._from_dict(self.test_data) conflicts = room_map.check_keyword_conflicts( - keywords_100=["plugin", "rocketchat"], + keywords=["plugin", "rocketchat"], exclude_room_id="plugin_room_id", ) self.assertEqual(len(conflicts), 0) diff --git a/plugin/archivar/tests/test_v8_4_2.py b/plugin/archivar/tests/test_v8_4_2.py new file mode 100644 index 0000000..04367f6 --- /dev/null +++ b/plugin/archivar/tests/test_v8_4_2.py @@ -0,0 +1,660 @@ +""" +V8.4.2 Tests: Onboarding Keyword-Conflict-Check. + +Tests: +1. 100%-Keyword Kollision mit anderem 100%-Keyword → CRITICAL +2. 100%-Keyword Kollision mit Kontext-Keyword → WARNING +3. Kontext-Keyword Kollision mit 100%-Keyword → INFO +4. Kontext-Keyword Kollision mit Kontext-Keyword → OK +5. Kein Konflikt → leere Liste +6. 'Trotzdem verwenden' → Keyword gespeichert (Adapter-Level) +7. 'Anderes Keyword' → Nutzer kann neu eingeben (Adapter-Level) +8. Kein Konflikt → normales Onboarding ohne Unterbrechung (Adapter-Level) +""" + +import asyncio +import json +import os +import sys +import tempfile +import threading +import unittest +from pathlib import Path +from unittest.mock import AsyncMock, MagicMock, patch + +sys.path.insert(0, str(Path(__file__).resolve().parents[3])) + +from plugin.archivar.room_map import RoomMap, RoomEntry + + +# ═══════════════════════════════════════════════════════════════════════════════ +# RoomMap-Level: check_keyword_conflicts() mit allen 4 Konflikt-Typen +# ═══════════════════════════════════════════════════════════════════════════════ + +class TestV842KeywordConflictTypes(unittest.TestCase): + """V8.4.2: check_keyword_conflicts() erkennt alle 4 Konflikt-Typen.""" + + def setUp(self): + self.temp_dir = tempfile.TemporaryDirectory() + self.temp_path = Path(self.temp_dir.name) / "room-map.json" + + self.test_data = { + "version": 2, + "rooms": { + "catchall_id": { + "name": "#CatchAll", + "theme": "Catch-all room", + "keywords_100": [], + "keywords_context": [], + "catch_all": True, + }, + "plugin_room_id": { + "name": "#Rocketchat-Plugin", + "theme": "Plugin-Entwicklung", + "keywords_100": ["plugin", "rocketchat", "gateway"], + "keywords_context": ["adapter", "websocket"], + "catch_all": False, + }, + "dm_room_id": { + "name": "DM Admin", + "theme": "Admin DM", + "keywords_100": ["rc"], + "keywords_context": ["absprache", "planung"], + "catch_all": False, + }, + }, + "excluded_rooms": [], + "fact_store_path": str(self.temp_path.parent / "docs"), + } + with open(self.temp_path, "w") as f: + json.dump(self.test_data, f) + + def tearDown(self): + self.temp_dir.cleanup() + + def test_100_vs_100_critical(self): + """100%-Keyword kollidiert mit 100%-Keyword in anderem Raum → CRITICAL.""" + room_map = RoomMap._from_dict(self.test_data) + conflicts = room_map.check_keyword_conflicts( + keywords=["plugin", "neues-thema"], + exclude_room_id="new_room_id", + keyword_type="100", + ) + self.assertEqual(len(conflicts), 1) + self.assertEqual(conflicts[0]["conflict_type"], "CRITICAL") + self.assertEqual(conflicts[0]["keyword"], "plugin") + self.assertEqual(conflicts[0]["room_name"], "#Rocketchat-Plugin") + self.assertEqual(conflicts[0]["existing_type"], "100") + + def test_100_vs_context_warning(self): + """100%-Keyword kollidiert mit Kontext-Keyword in anderem Raum → WARNING.""" + room_map = RoomMap._from_dict(self.test_data) + conflicts = room_map.check_keyword_conflicts( + keywords=["adapter", "neues-thema"], + exclude_room_id="new_room_id", + keyword_type="100", + ) + self.assertEqual(len(conflicts), 1) + self.assertEqual(conflicts[0]["conflict_type"], "WARNING") + self.assertEqual(conflicts[0]["keyword"], "adapter") + self.assertEqual(conflicts[0]["room_name"], "#Rocketchat-Plugin") + self.assertEqual(conflicts[0]["existing_type"], "context") + + def test_context_vs_100_info(self): + """Kontext-Keyword kollidiert mit 100%-Keyword in anderem Raum → INFO.""" + room_map = RoomMap._from_dict(self.test_data) + conflicts = room_map.check_keyword_conflicts( + keywords=["rc", "neues-thema"], + exclude_room_id="new_room_id", + keyword_type="context", + ) + self.assertEqual(len(conflicts), 1) + self.assertEqual(conflicts[0]["conflict_type"], "INFO") + self.assertEqual(conflicts[0]["keyword"], "rc") + self.assertEqual(conflicts[0]["room_name"], "DM Admin") + self.assertEqual(conflicts[0]["existing_type"], "100") + + def test_context_vs_context_ok(self): + """Kontext-Keyword kollidiert mit Kontext-Keyword in anderem Raum → OK.""" + room_map = RoomMap._from_dict(self.test_data) + conflicts = room_map.check_keyword_conflicts( + keywords=["absprache", "neues-thema"], + exclude_room_id="new_room_id", + keyword_type="context", + ) + self.assertEqual(len(conflicts), 1) + self.assertEqual(conflicts[0]["conflict_type"], "OK") + self.assertEqual(conflicts[0]["keyword"], "absprache") + self.assertEqual(conflicts[0]["room_name"], "DM Admin") + self.assertEqual(conflicts[0]["existing_type"], "context") + + def test_no_conflict_when_keywords_unique(self): + """Kein Konflikt wenn Keywords einzigartig sind.""" + room_map = RoomMap._from_dict(self.test_data) + conflicts = room_map.check_keyword_conflicts( + keywords=["dokumentation", "netzwerk"], + exclude_room_id="new_room_id", + keyword_type="100", + ) + self.assertEqual(len(conflicts), 0) + + def test_no_conflict_when_same_room_excluded(self): + """Kein Konflikt wenn der eigene Raum excluded wird.""" + room_map = RoomMap._from_dict(self.test_data) + conflicts = room_map.check_keyword_conflicts( + keywords=["plugin", "rocketchat"], + exclude_room_id="plugin_room_id", + keyword_type="100", + ) + self.assertEqual(len(conflicts), 0) + + def test_catch_all_ignored(self): + """Catch-All-Raum wird bei Konflikt-Prüfung ignoriert.""" + room_map = RoomMap._from_dict(self.test_data) + conflicts = room_map.check_keyword_conflicts( + keywords=["irgendwas"], + exclude_room_id="new_room_id", + keyword_type="100", + ) + self.assertEqual(len(conflicts), 0) + + def test_multiple_conflict_types(self): + """Mehrere Konflikte mit verschiedenen Typen werden erkannt.""" + room_map = RoomMap._from_dict(self.test_data) + # "plugin" ist 100% in plugin_room → CRITICAL + # "adapter" ist context in plugin_room → WARNING + conflicts = room_map.check_keyword_conflicts( + keywords=["plugin", "adapter", "neues-thema"], + exclude_room_id="new_room_id", + keyword_type="100", + ) + self.assertEqual(len(conflicts), 2) + types = {c["conflict_type"] for c in conflicts} + self.assertIn("CRITICAL", types) + self.assertIn("WARNING", types) + + def test_backward_compat_default_keyword_type(self): + """Default keyword_type='100' verhält sich wie vorher (nur 100%-Matches).""" + room_map = RoomMap._from_dict(self.test_data) + conflicts = room_map.check_keyword_conflicts( + keywords=["plugin"], + exclude_room_id="new_room_id", + ) + self.assertEqual(len(conflicts), 1) + self.assertEqual(conflicts[0]["conflict_type"], "CRITICAL") + + +# ═══════════════════════════════════════════════════════════════════════════════ +# Adapter-Level: Konflikt-Auflösung im Onboarding-Flow +# ═══════════════════════════════════════════════════════════════════════════════ + +def _build_mock_adapter(room_map_path: str): + """Build a RocketChatAdapter with mocked external dependencies. + + Uses __new__ to skip __init__ (same pattern as test_v8_3_4.py). + """ + os.environ["MULTIROOM_AGENT"] = "true" + os.environ["ARCHIVAR_ROOM_MAP_PATH"] = room_map_path + os.environ["ROCKETCHAT_BASE_URL"] = "https://rocket.example.com" + os.environ["ROCKETCHAT_USER"] = "testbot" + os.environ["ROCKETCHAT_PASSWORD"] = "testpass" + + from plugin.adapter import RocketChatAdapter, RocketChatREST + from archivar.conversation_history import ConversationHistory + from archivar.multiroom_context import MultiRoomContextRing + from archivar.adapter_integration import ArchivarMessageHandler + from archivar.room_map import RoomMap + + adapter = RocketChatAdapter.__new__(RocketChatAdapter) + + adapter.config = MagicMock() + adapter.config.extra = {} + adapter.platform = "rocketchat" + adapter.base_url = os.getenv("ROCKETCHAT_BASE_URL", "") + adapter.user = os.getenv("ROCKETCHAT_USER", "") + adapter.password = os.getenv("ROCKETCHAT_PASSWORD", "") + adapter.rest = RocketChatREST(adapter.base_url) + adapter.ddp = None + adapter._auth_token = None + adapter._user_id = None + adapter._rooms = [] + adapter._subscribed_rooms = set() + adapter._listen_task = None + adapter._status_timer = None + adapter._last_activity = 0.0 + adapter._shutdown_event = threading.Event() + adapter._room_info = {} + adapter._pending_clarifies = {} + adapter._user_rooms = {} + adapter._rooms_with_pending_questions = set() + adapter._excluded_room_ids = set() + adapter._last_server_activity = 0.0 + adapter._health_check_timer = None + adapter._last_ddp_ping_ok = False + adapter._running = False + + adapter._conversation_history = ConversationHistory(max_size=10) + adapter._multiroom_context = MultiRoomContextRing(max_entries=10) + adapter.archivar = ArchivarMessageHandler( + send_callback=lambda *a, **kw: None, + button_send_callback=lambda *a, **kw: None, + conversation_history=adapter._conversation_history, + ) + adapter.archivar._room_map = RoomMap.load(Path(room_map_path)) + + adapter._pending_move_requests = {} + adapter._session_room_preferences = {} + adapter._recent_auto_routes = {} + adapter._explicit_switch_sticky = {} + adapter._clarify_state = {} + adapter._onboarding_state = {} + adapter._room_map_summary = "" + + mock_rest = MagicMock(spec=RocketChatREST) + mock_rest.auth_token = "fake-token" + mock_rest.user_id = "fake-user-id" + mock_rest.post_message = MagicMock(return_value="msg_12345") + mock_rest.get_rooms = MagicMock(return_value=[ + {"id": "dm_room", "name": "DM Admin", "type": "d"}, + ]) + adapter.rest = mock_rest + + return adapter + + +class TestV842OnboardingConflictResolution(unittest.TestCase): + """V8.4.2: Konflikt-Auflösung im Onboarding-Flow (Adapter-Level).""" + + def setUp(self): + self.temp_dir = tempfile.TemporaryDirectory() + self.temp_path = Path(self.temp_dir.name) / "room-map.json" + + self.test_data = { + "version": 2, + "rooms": { + "catchall_id": { + "name": "#CatchAll", + "theme": "Catch-all room", + "keywords_100": [], + "keywords_context": [], + "catch_all": True, + }, + "plugin_room_id": { + "name": "#Rocketchat-Plugin", + "theme": "Plugin-Entwicklung", + "keywords_100": ["plugin", "rocketchat"], + "keywords_context": ["adapter"], + "catch_all": False, + }, + }, + "excluded_rooms": [], + "fact_store_path": str(self.temp_path.parent / "docs"), + } + with open(self.temp_path, "w") as f: + json.dump(self.test_data, f) + + def tearDown(self): + self.temp_dir.cleanup() + + def test_conflict_buttons_sent_for_100_vs_100(self): + """100%-Keyword-Konflikt → _ask_keyword_conflict_resolution sendet Buttons.""" + adapter = _build_mock_adapter(str(self.temp_path)) + adapter._post_message_with_retry = AsyncMock(return_value=True) + adapter._get_build_custom_buttons = MagicMock(return_value=MagicMock(return_value=[])) + + adapter._onboarding_state = { + "missing_rooms": [ + {"room_id": "new_room", "name": "#Neuer-Raum", "is_dm": False} + ], + "current_room_index": 0, + "current_question": 2, + "collected_data": { + "new_room": { + "theme": "Neues Thema", + "keywords_100": ["plugin"], + "keywords_context": [], + "catch_all": False, + } + }, + "operator_room_id": "dm_room", + "skipped_rooms": [], + "conflict_phase": "keywords_100", + "conflict_keywords": ["plugin"], + "conflict_list": [ + { + "keyword": "plugin", + "room_id": "plugin_room_id", + "room_name": "#Rocketchat-Plugin", + "conflict_type": "CRITICAL", + "existing_type": "100", + } + ], + } + + conflicts = adapter._onboarding_state["conflict_list"] + asyncio.run(adapter._ask_keyword_conflict_resolution( + "dm_room", conflicts, "100%" + )) + + self.assertTrue(adapter._post_message_with_retry.called) + call_args = adapter._post_message_with_retry.call_args + text = call_args[0][1] + self.assertIn("Keyword-Konflikt", text) + self.assertIn("plugin", text) + self.assertIn("#Rocketchat-Plugin", text) + self.assertIn("KRITISCH", text) + + def test_conflict_buttons_sent_for_100_vs_context(self): + """100%-Keyword vs Kontext-Keyword → WARNING-Buttons.""" + adapter = _build_mock_adapter(str(self.temp_path)) + adapter._post_message_with_retry = AsyncMock(return_value=True) + adapter._get_build_custom_buttons = MagicMock(return_value=MagicMock(return_value=[])) + + adapter._onboarding_state = { + "missing_rooms": [ + {"room_id": "new_room", "name": "#Neuer-Raum", "is_dm": False} + ], + "current_room_index": 0, + "current_question": 2, + "collected_data": { + "new_room": { + "theme": "Neues Thema", + "keywords_100": ["adapter"], + "keywords_context": [], + "catch_all": False, + } + }, + "operator_room_id": "dm_room", + "skipped_rooms": [], + "conflict_phase": "keywords_100", + "conflict_keywords": ["adapter"], + "conflict_list": [ + { + "keyword": "adapter", + "room_id": "plugin_room_id", + "room_name": "#Rocketchat-Plugin", + "conflict_type": "WARNING", + "existing_type": "context", + } + ], + } + + conflicts = adapter._onboarding_state["conflict_list"] + asyncio.run(adapter._ask_keyword_conflict_resolution( + "dm_room", conflicts, "100%" + )) + + self.assertTrue(adapter._post_message_with_retry.called) + text = adapter._post_message_with_retry.call_args[0][1] + self.assertIn("WARNUNG", text) + + def test_conflict_buttons_sent_for_context_vs_100(self): + """Kontext-Keyword vs 100%-Keyword → INFO-Buttons.""" + adapter = _build_mock_adapter(str(self.temp_path)) + adapter._post_message_with_retry = AsyncMock(return_value=True) + adapter._get_build_custom_buttons = MagicMock(return_value=MagicMock(return_value=[])) + + adapter._onboarding_state = { + "missing_rooms": [ + {"room_id": "new_room", "name": "#Neuer-Raum", "is_dm": False} + ], + "current_room_index": 0, + "current_question": 3, + "collected_data": { + "new_room": { + "theme": "Neues Thema", + "keywords_100": [], + "keywords_context": ["plugin"], + "catch_all": False, + } + }, + "operator_room_id": "dm_room", + "skipped_rooms": [], + "conflict_phase": "keywords_context", + "conflict_keywords": ["plugin"], + "conflict_list": [ + { + "keyword": "plugin", + "room_id": "plugin_room_id", + "room_name": "#Rocketchat-Plugin", + "conflict_type": "INFO", + "existing_type": "100", + } + ], + } + + conflicts = adapter._onboarding_state["conflict_list"] + asyncio.run(adapter._ask_keyword_conflict_resolution( + "dm_room", conflicts, "Kontext" + )) + + self.assertTrue(adapter._post_message_with_retry.called) + text = adapter._post_message_with_retry.call_args[0][1] + self.assertIn("INFO", text) + + def test_keep_anyway_proceeds_to_next_question(self): + """'Trotzdem verwenden' → Keyword gespeichert, nächste Frage.""" + adapter = _build_mock_adapter(str(self.temp_path)) + adapter._post_message_with_retry = AsyncMock(return_value=True) + adapter._get_build_custom_buttons = MagicMock(return_value=[]) + adapter._ask_onboarding_question = AsyncMock() + + adapter._onboarding_state = { + "missing_rooms": [ + {"room_id": "new_room", "name": "#Neuer-Raum", "is_dm": False} + ], + "current_room_index": 0, + "current_question": 2, + "collected_data": { + "new_room": { + "theme": "Neues Thema", + "keywords_100": ["plugin"], + "keywords_context": [], + "catch_all": False, + } + }, + "operator_room_id": "dm_room", + "skipped_rooms": [], + "conflict_phase": "keywords_100", + "conflict_keywords": ["plugin"], + "conflict_list": [ + { + "keyword": "plugin", + "room_id": "plugin_room_id", + "room_name": "#Rocketchat-Plugin", + "conflict_type": "CRITICAL", + "existing_type": "100", + } + ], + } + + # Simuliere Button-Klick "1️⃣ Trotzdem verwenden" + asyncio.run(adapter._process_onboarding_response( + "CONFLICT:new_room::1️⃣ Trotzdem verwenden", "dm_room" + )) + + # Prüfe: current_question wurde auf 3 gesetzt (nächste Frage) + self.assertEqual(adapter._onboarding_state["current_question"], 3) + # Prüfe: conflict state wurde bereinigt + self.assertNotIn("conflict_phase", adapter._onboarding_state) + # Prüfe: keywords_100 blieben erhalten + data = adapter._onboarding_state["collected_data"]["new_room"] + self.assertEqual(data["keywords_100"], ["plugin"]) + + def test_change_keyword_prompts_reenter(self): + """'Anderes Keyword' → Nutzer wird zur Neueingabe aufgefordert.""" + adapter = _build_mock_adapter(str(self.temp_path)) + adapter._post_message_with_retry = AsyncMock(return_value=True) + adapter._get_build_custom_buttons = MagicMock(return_value=[]) + + adapter._onboarding_state = { + "missing_rooms": [ + {"room_id": "new_room", "name": "#Neuer-Raum", "is_dm": False} + ], + "current_room_index": 0, + "current_question": 2, + "collected_data": { + "new_room": { + "theme": "Neues Thema", + "keywords_100": ["plugin"], + "keywords_context": [], + "catch_all": False, + } + }, + "operator_room_id": "dm_room", + "skipped_rooms": [], + "conflict_phase": "keywords_100", + "conflict_keywords": ["plugin"], + "conflict_list": [ + { + "keyword": "plugin", + "room_id": "plugin_room_id", + "room_name": "#Rocketchat-Plugin", + "conflict_type": "CRITICAL", + "existing_type": "100", + } + ], + } + + # Simuliere Button-Klick "2️⃣ Anderes Keyword" + asyncio.run(adapter._process_onboarding_response( + "CONFLICT:new_room::2️⃣ Anderes Keyword", "dm_room" + )) + + # Prüfe: Sub-Phase wurde auf "reenter" gesetzt + self.assertEqual( + adapter._onboarding_state.get("conflict_sub_phase"), "reenter" + ) + # Prüfe: Aufforderung zur Neueingabe wurde gesendet + self.assertTrue(adapter._post_message_with_retry.called) + text = adapter._post_message_with_retry.call_args[0][1] + self.assertIn("neue Keywords", text) + self.assertIn("plugin", text) + + def test_reenter_with_no_conflict_proceeds(self): + """Nach Neueingabe ohne Konflikt → normales Onboarding geht weiter.""" + adapter = _build_mock_adapter(str(self.temp_path)) + adapter._post_message_with_retry = AsyncMock(return_value=True) + adapter._get_build_custom_buttons = MagicMock(return_value=[]) + adapter._ask_onboarding_question = AsyncMock() + + adapter._onboarding_state = { + "missing_rooms": [ + {"room_id": "new_room", "name": "#Neuer-Raum", "is_dm": False} + ], + "current_room_index": 0, + "current_question": 2, + "collected_data": { + "new_room": { + "theme": "Neues Thema", + "keywords_100": ["plugin"], + "keywords_context": [], + "catch_all": False, + } + }, + "operator_room_id": "dm_room", + "skipped_rooms": [], + "conflict_phase": "keywords_100", + "conflict_keywords": ["plugin"], + "conflict_list": [ + { + "keyword": "plugin", + "room_id": "plugin_room_id", + "room_name": "#Rocketchat-Plugin", + "conflict_type": "CRITICAL", + "existing_type": "100", + } + ], + "conflict_sub_phase": "reenter", + } + + # Nutzer gibt neue Keywords ohne Konflikt ein + asyncio.run(adapter._process_onboarding_response( + "dokumentation, netzwerk", "dm_room" + )) + + # Prüfe: keywords_100 wurden aktualisiert + data = adapter._onboarding_state["collected_data"]["new_room"] + self.assertEqual(data["keywords_100"], ["dokumentation", "netzwerk"]) + # Prüfe: current_question wurde auf 3 gesetzt + self.assertEqual(adapter._onboarding_state["current_question"], 3) + # Prüfe: conflict state wurde bereinigt + self.assertNotIn("conflict_phase", adapter._onboarding_state) + self.assertNotIn("conflict_sub_phase", adapter._onboarding_state) + + def test_no_conflict_normal_onboarding(self): + """Kein Konflikt → normales Onboarding ohne Unterbrechung.""" + adapter = _build_mock_adapter(str(self.temp_path)) + adapter._post_message_with_retry = AsyncMock(return_value=True) + adapter._get_build_custom_buttons = MagicMock(return_value=[]) + adapter._ask_onboarding_question = AsyncMock() + + adapter._onboarding_state = { + "missing_rooms": [ + {"room_id": "new_room", "name": "#Neuer-Raum", "is_dm": False} + ], + "current_room_index": 0, + "current_question": 2, + "collected_data": { + "new_room": { + "theme": "Neues Thema", + "keywords_100": [], + "keywords_context": [], + "catch_all": False, + } + }, + "operator_room_id": "dm_room", + "skipped_rooms": [], + } + + # Nutzer gibt Keywords ohne Konflikt ein + asyncio.run(adapter._process_onboarding_response( + "dokumentation, netzwerk", "dm_room" + )) + + # Prüfe: keywords_100 wurden gespeichert + data = adapter._onboarding_state["collected_data"]["new_room"] + self.assertEqual(data["keywords_100"], ["dokumentation", "netzwerk"]) + # Prüfe: current_question wurde auf 3 gesetzt (kein Konflikt-Block) + self.assertEqual(adapter._onboarding_state["current_question"], 3) + # Prüfe: kein conflict_phase gesetzt + self.assertNotIn("conflict_phase", adapter._onboarding_state) + + def test_context_vs_context_ok_no_interruption(self): + """Kontext vs Kontext (OK) → kein Konflikt-Dialog, normales Onboarding.""" + adapter = _build_mock_adapter(str(self.temp_path)) + adapter._post_message_with_retry = AsyncMock(return_value=True) + adapter._get_build_custom_buttons = MagicMock(return_value=[]) + adapter._ask_onboarding_question = AsyncMock() + + adapter._onboarding_state = { + "missing_rooms": [ + {"room_id": "new_room", "name": "#Neuer-Raum", "is_dm": False} + ], + "current_room_index": 0, + "current_question": 3, + "collected_data": { + "new_room": { + "theme": "Neues Thema", + "keywords_100": ["dokumentation"], + "keywords_context": [], + "catch_all": False, + } + }, + "operator_room_id": "dm_room", + "skipped_rooms": [], + } + + # Nutzer gibt Kontext-Keywords ein, die nur mit context in anderem Raum kollidieren + # "adapter" ist context in plugin_room → OK, wird ignoriert + asyncio.run(adapter._process_onboarding_response( + "adapter, websocket", "dm_room" + )) + + # Prüfe: keywords_context wurden gespeichert + data = adapter._onboarding_state["collected_data"]["new_room"] + self.assertEqual(data["keywords_context"], ["adapter", "websocket"]) + # Prüfe: current_question wurde auf 4 gesetzt (kein Konflikt-Block) + self.assertEqual(adapter._onboarding_state["current_question"], 4) + # Prüfe: kein conflict_phase gesetzt + self.assertNotIn("conflict_phase", adapter._onboarding_state)