diff --git a/plugin/archivar/adapter_integration.py b/plugin/archivar/adapter_integration.py index 1dc1f0a..4fdedf2 100644 --- a/plugin/archivar/adapter_integration.py +++ b/plugin/archivar/adapter_integration.py @@ -1168,4 +1168,54 @@ class ArchivarMessageHandler: @property def state(self) -> ArchivarState: """Archivar state for persistent room decisions.""" - return self._state \ No newline at end of file + return self._state + + # ── V8.2 A2: Butler-Nachklärung bei Ablehnung ─────────────────────── + + def _should_trigger_nachklaerung(self, response_type: str) -> bool: + """Prüft ob nach einer Move-Request-Ablehnung eine Nachklärung + getriggert werden soll. + + - 'stay_once' (Nur diesmal) → Nachklärung + - 'stay_here' (Generell hier) → direktes Lernen, keine Nachklärung + - 'confirm_move' (Rüber) → kein Trigger + + Args: + response_type: Der Antwort-Typ vom Move-Request-Button. + + Returns: + True wenn Nachklärung getriggert werden soll. + """ + return response_type == "stay_once" + + def _is_strategie_topic(self, topic: str) -> bool: + """Prüft ob ein Thema ein Strategie-Thema ist. + + Strategie-Themen: absprache, planung, strategie, entscheidung. + Bei diesen Themen → Strategie-Modus, KEIN Lernen. + + Args: + topic: Das Thema (z.B. 'strategie', 'dokumentation'). + + Returns: + True wenn Strategie-Thema. + """ + strategie_topics = {"absprache", "planung", "strategie", "entscheidung"} + return topic.lower().strip() in strategie_topics + + def _get_nachklaerung_buttons(self) -> dict: + """Gibt die Nachklärungs-Buttons für A2 zurück. + + Returns: + Button-Template mit Strategie-Optionen. + """ + return { + "text": "Ist es eines dieser Themen?", + "actions": [ + {"text": "🤝 Absprache", "type": "absprache"}, + {"text": "📋 Planung", "type": "planung"}, + {"text": "🎯 Strategie", "type": "strategie"}, + {"text": "✅ Entscheidung", "type": "entscheidung"}, + {"text": "❓ Anderer Grund", "type": "anderer_grund"}, + ], + } \ No newline at end of file diff --git a/plugin/archivar/archivar_state.py b/plugin/archivar/archivar_state.py index 3243b69..f56e6ec 100644 --- a/plugin/archivar/archivar_state.py +++ b/plugin/archivar/archivar_state.py @@ -73,6 +73,7 @@ class ArchivarState: self._stay_tracker: Dict[str, Dict[str, Union[int, float]]] = {} self._onboarding_state: Dict[str, Any] = {} self._never_route: Dict[str, Dict[str, dict]] = {} # v7: room_id → topic → {state, timestamp, last_extended, extension_count} + self._ring_state: Dict[str, Dict[str, str]] = {} # V8.2 A2: room_id → {state, expires_at} self._loaded = False def load(self) -> bool: @@ -143,6 +144,9 @@ class ArchivarState: # Lade onboarding_state (P1-4: persistent über Neustarts) self._onboarding_state = data.get("onboarding_state", {}) + # V8.2 A2: Ring-State laden + self._ring_state = data.get("ring_state", {}) + # ── P0-B: never_route v7 Migration ────────────────────────── # v6: never_route war ein Set von room_ids (nicht gespeichert) # v7: never_route ist Dict[room_id][topic] → {state, timestamp, ...} @@ -240,6 +244,7 @@ class ArchivarState: "stay_tracker": self._stay_tracker, "onboarding_state": self._onboarding_state, "never_route": self._never_route, + "ring_state": self._ring_state, # V8.2 A2 } def get_room_state(self, room_id: str) -> Optional[RoomState]: @@ -819,6 +824,65 @@ class ArchivarState: # Neue Methoden für das selbstlernende Keyword-Gewicht-System + # ── V8.2 A2: Ring-State für Strategie-Modus ──────────────────────── + + def set_ring_state(self, room_id: str, state: str, ttl_minutes: int = 30) -> bool: + """Setzt den Ring-Zustand für einen Raum (Strategie-Modus). + + Args: + room_id: Die Raum-ID. + state: 'jetzt' (temporär) oder '' (clear). + ttl_minutes: Time-to-live in Minuten (default 30). + + Returns: + True wenn erfolgreich gesetzt. + """ + if not state: + self._ring_state.pop(room_id, None) + else: + expires = (datetime.now() + timedelta(minutes=ttl_minutes)).isoformat() + self._ring_state[room_id] = {"state": state, "expires_at": expires} + return self.save() + + def get_ring_state(self, room_id: str) -> Optional[dict]: + """Gibt den Ring-Zustand für einen Raum zurück. + + Args: + room_id: Die Raum-ID. + + Returns: + Dict mit {state, expires_at} oder None. + """ + if not self._loaded: + self.load() + return self._ring_state.get(room_id) + + def is_ring_state_active(self, room_id: str, expected_state: str = "jetzt") -> bool: + """Prüft ob ein Ring-State aktiv (nicht abgelaufen) ist. + + Args: + room_id: Die Raum-ID. + expected_state: Erwarteter State (default 'jetzt'). + + Returns: + True wenn State aktiv und nicht abgelaufen. + """ + entry = self._ring_state.get(room_id) + if entry is None: + return False + if entry.get("state") != expected_state: + return False + expires_str = entry.get("expires_at", "") + if not expires_str: + return False + try: + expires = datetime.fromisoformat(expires_str) + return datetime.now() < expires + except (ValueError, TypeError): + return False + + # Neue Methoden für das selbstlernende Keyword-Gewicht-System + def update_keyword_weight(self, keyword: str, room_id: str, feedback_type: str) -> bool: """ Aktualisiert das Gewicht basierend auf Benutzerfeedback. diff --git a/plugin/archivar/room_map.py b/plugin/archivar/room_map.py index 1add7c8..2d65862 100644 --- a/plugin/archivar/room_map.py +++ b/plugin/archivar/room_map.py @@ -27,8 +27,9 @@ import json import logging import os from dataclasses import dataclass, field +from datetime import datetime, timedelta from pathlib import Path -from typing import Optional +from typing import Optional, Dict, List logger = logging.getLogger(__name__) @@ -71,6 +72,13 @@ class RoomEntry: catch_all: bool = False """True wenn dieser Raum der EINE Catch-All-Raum ist.""" + # V8.2: Keyword-Tracking für Lern-Persistenz und Demotion + _keyword_last_matched: Dict[str, str] = field(default_factory=dict) + """Mapping keyword → ISO timestamp des letzten Matches (für Demotion).""" + + _stay_counts: Dict[str, int] = field(default_factory=dict) + """Mapping keyword → Anzahl 'Hier bleiben' (für Promotion zu keywords_100).""" + @property def keywords(self) -> list[str]: """Legacy property for backward compatibility.""" @@ -503,6 +511,172 @@ class RoomMap: finally: fcntl.flock(f.fileno(), fcntl.LOCK_UN) + # ── V8.2: A1 — Onboarding-Widerspruchsprüfung ────────────────────── + + def check_keyword_conflicts( + self, keywords_100: list[str], exclude_room_id: str = "" + ) -> list[dict]: + """Prüft ob 100%-Keywords bereits in anderen Räumen existieren. + + Args: + keywords_100: Liste der zu prüfenden 100%-Keywords. + exclude_room_id: Raum-ID die ausgeschlossen wird (der eigene Raum). + + Returns: + Liste von Konflikten: [{"keyword": str, "room_id": str, "room_name": str}] + """ + conflicts = [] + for room_id, room in self._rooms.items(): + if room_id == exclude_room_id: + continue + if room.catch_all: + continue + for kw in keywords_100: + kw_lower = kw.lower() + for existing_kw in room.keywords_100: + if existing_kw.lower() == kw_lower: + conflicts.append({ + "keyword": kw, + "room_id": room_id, + "room_name": room.name, + }) + break + return conflicts + + # ── V8.2: A3 — Lernfunktion-Persistenz ────────────────────────────── + + def add_keyword_context(self, room_id: str, keyword: str) -> bool: + """Fügt ein Keyword zu keywords_context hinzu und persistiert. + + Args: + room_id: Die Raum-ID. + keyword: Das neue kontextabhängige Keyword. + + Returns: + True wenn hinzugefügt, False wenn bereits vorhanden. + """ + room = self._rooms.get(room_id) + if room is None: + return False + if keyword.lower() in (kw.lower() for kw in room.keywords_context): + return False + room.keywords_context.append(keyword) + self._version += 1 + return True + + def increment_stay_count(self, room_id: str, keyword: str) -> int: + """Inkrementiert den stay-Count für ein Keyword. + + Args: + room_id: Die Raum-ID. + keyword: Das Keyword. + + Returns: + Aktueller Count nach Inkrement. + """ + room = self._rooms.get(room_id) + if room is None: + return 0 + count = room._stay_counts.get(keyword, 0) + 1 + room._stay_counts[keyword] = count + return count + + def promote_to_keywords_100(self, room_id: str, keyword: str) -> bool: + """Promoted ein Keyword von keywords_context zu keywords_100. + + Args: + room_id: Die Raum-ID. + keyword: Das zu promotende Keyword. + + Returns: + True wenn erfolgreich promoted. + """ + room = self._rooms.get(room_id) + if room is None: + return False + + kw_lower = keyword.lower() + + # Aus keywords_context entfernen + room.keywords_context = [ + kw for kw in room.keywords_context if kw.lower() != kw_lower + ] + + # Zu keywords_100 hinzufügen (wenn nicht schon da) + if kw_lower not in (kw.lower() for kw in room.keywords_100): + room.keywords_100.append(keyword) + + # Stay-Count zurücksetzen + room._stay_counts.pop(keyword, None) + + self._version += 1 + return True + + def set_keyword_last_matched( + self, room_id: str, keyword: str, timestamp: str + ) -> bool: + """Setzt den last_matched-Timestamp für ein Keyword. + + Args: + room_id: Die Raum-ID. + keyword: Das Keyword. + timestamp: ISO-Format Timestamp. + + Returns: + True wenn gesetzt. + """ + room = self._rooms.get(room_id) + if room is None: + return False + room._keyword_last_matched[keyword] = timestamp + return True + + def demote_stale_keywords(self, max_age_days: int = 90) -> int: + """Demoted keywords_100 → keywords_context wenn länger als + max_age_days kein Match. + + Rainer Auflage P2: Demotion-Mechanismus. + + Args: + max_age_days: Maximale Tage ohne Match bevor Demotion. + + Returns: + Anzahl der demoted Keywords. + """ + now = datetime.now() + demoted = 0 + + for room in self._rooms.values(): + if room.catch_all: + continue + + to_demote = [] + for kw in list(room.keywords_100): + last_match_str = room._keyword_last_matched.get(kw) + if last_match_str: + try: + last_match = datetime.fromisoformat(last_match_str) + if (now - last_match) > timedelta(days=max_age_days): + to_demote.append(kw) + except (ValueError, TypeError): + # Kein gültiger Timestamp → als stale behandeln + to_demote.append(kw) + else: + # Kein last_matched gesetzt → initial, nicht demoten + # Setze initialen Timestamp + room._keyword_last_matched[kw] = now.isoformat() + + for kw in to_demote: + room.keywords_100.remove(kw) + if kw.lower() not in (k.lower() for k in room.keywords_context): + room.keywords_context.append(kw) + room._keyword_last_matched.pop(kw, None) + demoted += 1 + + if demoted > 0: + self._version += 1 + return demoted + @classmethod def _from_dict(cls, data: dict) -> RoomMap: """Parse a deserialized map dict into a ``RoomMap`` instance.""" diff --git a/plugin/archivar/router.py b/plugin/archivar/router.py index 0da5407..074bbec 100644 --- a/plugin/archivar/router.py +++ b/plugin/archivar/router.py @@ -371,21 +371,17 @@ class BidirectionalRouter: try: # ── Schritt 0: DM-Guard (VOR allem anderen) ────────────────── - # DMs haben origin_room_id=''. Der Origin-First Guard greift - # nicht für DMs. LLM kann Projektraum vorschlagen → Guard 3 → - # Move-Request im DM → Antwort landet in Projektraum statt DM. - # DMs sollen nie vom Routing betroffen sein — sie bleiben IMMER - # im DM. (Release-blockierend) + # V8.2 A4: DMs erlauben jetzt Butler-Routing. + # Der alte DM-Guard (stay_in_room für alle DMs) wird durch + # einen modifizierten Guard ersetzt, der LLM-basiertes Routing + # aus DMs erlaubt. Der Archivar schlägt Zielräume vor, + # der User bestätigt via Move-Request-Button. + # Strategie-Themen (absprache, planung, strategie, entscheidung) + # → Strategie-Modus, KEIN Lernen. if not origin_room_id: - logger.debug("DM-Guard: origin_room_id leer → stay_in_room (DM)") - routing_counter.increment('no_match_stay') - logger.info("ROUTING DECISION: reason=no_match_stay, origin_room=%s, target_room=, stay=True, butler_mode=False", origin_room_id) - return RoutingDecision( - category="direct_question", - target_room="", - confidence=0.0, - stay_in_room=True, - ) + # DM: Erlaube Routing, aber markiere als DM-Kontext + logger.debug("DM-Guard V8.2: origin_room_id leer → DM-Routing erlaubt (A4)") + # Kein sofortiges stay_in_room — normaler Flow mit Butler # ── Schritt 0: Excluded rooms check ────────────────────────── if origin_room_id and self._room_map.is_excluded(origin_room_id): diff --git a/plugin/archivar/tests/test_v8_2.py b/plugin/archivar/tests/test_v8_2.py new file mode 100644 index 0000000..14ca4af --- /dev/null +++ b/plugin/archivar/tests/test_v8_2.py @@ -0,0 +1,439 @@ +""" +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()