""" 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)