""" V8.2 Tests: A1-A4 Implementation. A1: Onboarding-Widerspruchsprüfung A2: Butler-Nachklärung bei Ablehnung (Strategie-Modus) A3: Lernfunktion-Persistenz in room-map.json + Demotion A4: Butler in Catch-All DM mit Strategie-Modus """ import json import os import sys import tempfile import unittest from datetime import datetime, timedelta 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 from plugin.archivar.archivar_state import ArchivarState # ═══════════════════════════════════════════════════════════════════════════════ # A1: Onboarding-Widerspruchsprüfung # ═══════════════════════════════════════════════════════════════════════════════ class TestA1OnboardingConflictCheck(unittest.TestCase): """A1: Beim Onboarding 100%-Keyword-Konflikte erkennen.""" 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, }, }, "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_a1_no_conflict_when_keywords_unique(self): """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"], exclude_room_id="new_room_id", ) self.assertEqual(len(conflicts), 0) def test_a1_conflict_detected_for_existing_100_keyword(self): """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"], exclude_room_id="new_room_id", ) self.assertEqual(len(conflicts), 1) self.assertIn("plugin", conflicts[0]["keyword"]) self.assertIn("plugin_room_id", conflicts[0]["room_id"]) self.assertIn("#Rocketchat-Plugin", conflicts[0]["room_name"]) def test_a1_conflict_detected_for_multiple_keywords(self): """Mehrere Konflikte werden erkannt.""" room_map = RoomMap._from_dict(self.test_data) conflicts = room_map.check_keyword_conflicts( keywords_100=["plugin", "rocketchat", "gateway"], exclude_room_id="new_room_id", ) self.assertEqual(len(conflicts), 3) def test_a1_no_conflict_when_same_room_excluded(self): """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"], exclude_room_id="plugin_room_id", ) self.assertEqual(len(conflicts), 0) # ═══════════════════════════════════════════════════════════════════════════════ # A2: Butler-Nachklärung bei Ablehnung (Strategie-Modus) # ═══════════════════════════════════════════════════════════════════════════════ class TestA2StrategieNachklaerung(unittest.TestCase): """A2: Nach Ablehnung des Move-Requests → Nachklärung mit Strategie-Buttons.""" def setUp(self): self.temp_dir = tempfile.TemporaryDirectory() self.temp_path = Path(self.temp_dir.name) / "room-map.json" self.state_path = Path(self.temp_dir.name) / "archivar_state.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"], "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_a2_stay_once_triggers_nachklaerung(self): """'Nur diesmal' (stay_once) → Nachklärung wird getriggert.""" from plugin.archivar.adapter_integration import ArchivarMessageHandler with patch('archivar.adapter_integration.ROOM_MAP_PATH', str(self.temp_path)): with patch('archivar.room_map.DEFAULT_MAP_PATH', str(self.temp_path)): handler = ArchivarMessageHandler() handler._state._state_file_path = str(self.state_path) handler._state._loaded = True # Simuliere stay_once response result = handler._should_trigger_nachklaerung("stay_once") self.assertTrue(result) def test_a2_stay_here_does_not_trigger_nachklaerung(self): """'Generell hier' (stay_here) → KEINE Nachklärung (Lernen direkt).""" from plugin.archivar.adapter_integration import ArchivarMessageHandler with patch('archivar.adapter_integration.ROOM_MAP_PATH', str(self.temp_path)): with patch('archivar.room_map.DEFAULT_MAP_PATH', str(self.temp_path)): handler = ArchivarMessageHandler() handler._state._state_file_path = str(self.state_path) handler._state._loaded = True result = handler._should_trigger_nachklaerung("stay_here") self.assertFalse(result) def test_a2_confirm_move_does_not_trigger_nachklaerung(self): """'Rüber' (confirm_move) → KEINE Nachklärung.""" from plugin.archivar.adapter_integration import ArchivarMessageHandler with patch('archivar.adapter_integration.ROOM_MAP_PATH', str(self.temp_path)): with patch('archivar.room_map.DEFAULT_MAP_PATH', str(self.temp_path)): handler = ArchivarMessageHandler() handler._state._state_file_path = str(self.state_path) handler._state._loaded = True result = handler._should_trigger_nachklaerung("confirm_move") self.assertFalse(result) def test_a2_strategie_mode_sets_ring_jetzt(self): """Strategie-Auswahl → Ring-Zustand 'jetzt' (temporär, 30 Min).""" state = ArchivarState() state._loaded = True state.set_ring_state("test_room_123", "jetzt", ttl_minutes=30) ring = state.get_ring_state("test_room_123") self.assertEqual(ring["state"], "jetzt") self.assertIsNotNone(ring["expires_at"]) def test_a2_strategie_mode_no_learning(self): """Strategie-Modus → KEIN Lernen (kein keyword_context Update).""" state = ArchivarState() state._loaded = True # Simuliere: Strategie-Modus aktiv state.set_ring_state("test_room_123", "jetzt", ttl_minutes=30) # Versuche zu lernen → sollte blockiert werden can_learn = not state.is_ring_state_active("test_room_123", "jetzt") self.assertFalse(can_learn, "Strategie-Modus sollte Lernen blockieren") def test_a2_anderer_grund_triggers_normal_learning(self): """'ANDERER GRUND' → normale Lernfunktion.""" from plugin.archivar.adapter_integration import ArchivarMessageHandler with patch('archivar.adapter_integration.ROOM_MAP_PATH', str(self.temp_path)): with patch('archivar.room_map.DEFAULT_MAP_PATH', str(self.temp_path)): handler = ArchivarMessageHandler() handler._state._state_file_path = str(self.state_path) handler._state._loaded = True # ANDERER GRUND → kein Strategie-Modus, normales Lernen is_strategie = handler._is_strategie_topic("ANDERER GRUND") self.assertFalse(is_strategie) def test_a2_strategie_topic_detection(self): """Strategie-Themen werden korrekt erkannt.""" from plugin.archivar.adapter_integration import ArchivarMessageHandler with patch('archivar.adapter_integration.ROOM_MAP_PATH', str(self.temp_path)): with patch('archivar.room_map.DEFAULT_MAP_PATH', str(self.temp_path)): handler = ArchivarMessageHandler() handler._state._state_file_path = str(self.state_path) handler._state._loaded = True self.assertTrue(handler._is_strategie_topic("strategie")) self.assertTrue(handler._is_strategie_topic("absprache")) self.assertTrue(handler._is_strategie_topic("planung")) self.assertTrue(handler._is_strategie_topic("entscheidung")) self.assertFalse(handler._is_strategie_topic("dokumentation")) self.assertFalse(handler._is_strategie_topic("plugin")) # ═══════════════════════════════════════════════════════════════════════════════ # A3: Lernfunktion-Persistenz in room-map.json + Demotion # ═══════════════════════════════════════════════════════════════════════════════ class TestA3LernPersistenz(unittest.TestCase): """A3: Gelernte Begriffe werden in room-map.json persistiert.""" 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"], "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_a3_add_keyword_context_persists(self): """1x 'Hier bleiben' → keyword_context wird in room-map.json geschrieben.""" room_map = RoomMap._from_dict(self.test_data) room_map.add_keyword_context("plugin_room_id", "neues-keyword") RoomMap.save(room_map, self.temp_path) # Reload und prüfen reloaded = RoomMap.load(self.temp_path) entry = reloaded.get_room_by_id("plugin_room_id") self.assertIn("neues-keyword", entry.keywords_context) def test_a3_promote_to_keywords_100_after_3_stays(self): """3x 'Hier bleiben' → Keyword wird zu keywords_100 promoted.""" room_map = RoomMap._from_dict(self.test_data) # Simuliere 3 stays für "dokumentation" room_map.add_keyword_context("plugin_room_id", "dokumentation") room_map.increment_stay_count("plugin_room_id", "dokumentation") room_map.increment_stay_count("plugin_room_id", "dokumentation") count = room_map.increment_stay_count("plugin_room_id", "dokumentation") self.assertEqual(count, 3) # Nach 3 stays → promote promoted = room_map.promote_to_keywords_100("plugin_room_id", "dokumentation") self.assertTrue(promoted) entry = room_map.get_room_by_id("plugin_room_id") self.assertIn("dokumentation", entry.keywords_100) def test_a3_demotion_after_90_days_no_match(self): """90 Tage kein Match → auto-demote von keywords_100 zu keywords_context.""" room_map = RoomMap._from_dict(self.test_data) # Setze last_matched auf 91 Tage in der Vergangenheit old_date = (datetime.now() - timedelta(days=91)).isoformat() room_map.set_keyword_last_matched("plugin_room_id", "plugin", old_date) # Führe Demotion durch demoted = room_map.demote_stale_keywords(max_age_days=90) self.assertGreaterEqual(demoted, 1) entry = room_map.get_room_by_id("plugin_room_id") self.assertNotIn("plugin", entry.keywords_100) self.assertIn("plugin", entry.keywords_context) def test_a3_no_demotion_when_recently_matched(self): """Keyword mit kürzlichem Match wird NICHT demoted.""" room_map = RoomMap._from_dict(self.test_data) # Setze last_matched auf heute recent_date = datetime.now().isoformat() room_map.set_keyword_last_matched("plugin_room_id", "plugin", recent_date) demoted = room_map.demote_stale_keywords(max_age_days=90) self.assertEqual(demoted, 0) entry = room_map.get_room_by_id("plugin_room_id") self.assertIn("plugin", entry.keywords_100) def test_a3_faiss_stale_detection_on_keyword_change(self): """FAISS is_stale() erkennt Member-Set-Change nach Keyword-Änderung.""" room_map = RoomMap._from_dict(self.test_data) old_version = room_map.version room_map.add_keyword_context("plugin_room_id", "neues-keyword") self.assertGreater(room_map.version, old_version, "Version muss nach Keyword-Änderung inkrementiert sein") # ═══════════════════════════════════════════════════════════════════════════════ # A4: Butler in Catch-All DM mit Strategie-Modus # ═══════════════════════════════════════════════════════════════════════════════ class TestA4DMButlerStrategie(unittest.TestCase): """A4: Butler arbeitet in Catch-All DM, Strategie-Modus bei DM-Themen.""" 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": "DM Admin", "theme": "Catch-all DM", "keywords_100": [], "keywords_context": [], "catch_all": True, }, "plugin_room_id": { "name": "#Rocketchat-Plugin", "theme": "Plugin-Entwicklung", "keywords_100": ["plugin"], "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_a4_dm_allows_butler_routing(self): """DM-Guard erlaubt jetzt Butler-Routing aus DMs (A4).""" from plugin.archivar.router import BidirectionalRouter from plugin.archivar.room_map import RoomMap from plugin.archivar.archivar_state import ArchivarState room_map = RoomMap._from_dict(self.test_data) state = ArchivarState() state._loaded = True mock_classifier = MagicMock() mock_classifier.is_initialized = True mock_classifier.classify = AsyncMock(return_value=None) mock_classifier._llm_raw = AsyncMock(return_value="plugin_room_id") router = BidirectionalRouter(room_map, mock_classifier, state) # DM (origin_room_id='') sollte jetzt Routing erlauben import asyncio decision = asyncio.run( router.route("Bitte das Plugin dokumentieren", origin_room_id="") ) # Sollte NICHT stay_in_room sein (A4 erlaubt DM-Routing) # Der LLM schlägt plugin_room_id vor → Move-Request self.assertFalse(decision.stay_in_room, "A4: DM sollte Routing erlauben (nicht mehr stay_in_room)") def test_a4_dm_strategie_topic_no_learning(self): """DM-Strategie-Themen (absprache, planung, strategie, entscheidung) → Strategie-Modus, KEIN Lernen.""" from plugin.archivar.adapter_integration import ArchivarMessageHandler with patch('archivar.adapter_integration.ROOM_MAP_PATH', str(self.temp_path)): with patch('archivar.room_map.DEFAULT_MAP_PATH', str(self.temp_path)): handler = ArchivarMessageHandler() handler._state._loaded = True # DM-Strategie-Themen for topic in ["absprache", "planung", "strategie", "entscheidung"]: is_strategie = handler._is_strategie_topic(topic) self.assertTrue(is_strategie, f"'{topic}' sollte als Strategie-Thema erkannt werden") def test_a4_dm_non_strategie_topic_allows_learning(self): """DM-Nicht-Strategie-Themen → normales Lernen.""" from plugin.archivar.adapter_integration import ArchivarMessageHandler with patch('archivar.adapter_integration.ROOM_MAP_PATH', str(self.temp_path)): with patch('archivar.room_map.DEFAULT_MAP_PATH', str(self.temp_path)): handler = ArchivarMessageHandler() handler._state._loaded = True # Normales Thema → kein Strategie-Modus self.assertFalse(handler._is_strategie_topic("dokumentation")) self.assertFalse(handler._is_strategie_topic("plugin")) if __name__ == '__main__': unittest.main()