""" Bidirektionales Routing für Archivar v3. Ermittelt den Zielraum basierend auf Intent-Klassifikationsergebnis, Konfidenzschwelle und Fallback-Strategie. Unterstützt bidirektionales Routing mit Quellkanal-Benachrichtigung und Zusammenfassung nach Abschluss. """ from __future__ import annotations import logging import re from dataclasses import dataclass, field from typing import Dict, List, Optional, Tuple from .classifier import ClassificationResult, IntentClassifier from .config import ( CONFIDENCE_THRESHOLDS, FALLBACK_KEYWORDS, OLLAMA_CONFIG, LLM_ROOM_PROMPT, ROOM_MAP_PATH, ) from .room_map import RoomMap, RoomEntry from .archivar_state import ArchivarState logger = logging.getLogger(__name__) # ── Meta-Fragen-Erkennung ─────────────────────────────────────────────────── # Meta-Fragen sind Fragen über das Archivar-System selbst. Sie würden sonst als # FRAGE klassifiziert und im Zielraum landen, wo sie irrelevant sind. # Solche Nachrichten werden erkannt, aus dem Originalraum gelöscht und mit einem # Hinweis in der Kopie versehen. _META_PATTERNS: List[re.Pattern] = [ re.compile(r"(?:wohin|an wen|welcher raum|welchem raum|welchen raum|in welch)\s+(?:wurde|geht|ging|landet)", re.IGNORECASE), re.compile(r"warum\s+(?:wurde|ist)\s+(?:meine\s+)?(?:nachricht|frage)", re.IGNORECASE), re.compile(r"(?:archivar|klassifi(?:zier|kation)|routing|weiterleitung)", re.IGNORECASE), re.compile(r"(?:was|wie)\s+(?:macht|arbeitet|funktioniert)\s+(?:der\s+)?archivar", re.IGNORECASE), re.compile(r"(?:klasse|kategorie)\s+(?:meiner\s+)?(?:nachricht|würde|wurde)", re.IGNORECASE), re.compile(r"(?:in welch(?:er|em|en|e)?)\s+(?:kategorie|klasse|raum)", re.IGNORECASE), re.compile(r"(?:who|which room|where).*(?:message|routed|sent)", re.IGNORECASE), ] @dataclass class RoutingDecision: """Entscheidung, wohin eine Nachricht weitergeleitet wird.""" category: str """Klassifikations-Kategorie: 'direct_question', 'smalltalk', 'work_order', 'ambiguous'.""" target_room: str """Rocket.Chat Raum-ID des Zielraums.""" confidence: float """Konfidenz der Klassifikation (0.0–1.0).""" is_catch_all: bool = False """True, wenn die Nachricht wegen zu niedriger Konfidenz an Catch-All ging.""" is_fallback: bool = False """True, wenn das Ergebnis aus der Keyword-Heuristik stammt (Ollama down).""" is_meta: bool = False """True, wenn die Nachricht als Meta-Frage erkannt wurde.""" is_unrouteable: bool = False """True, wenn der Zielraum nicht in den subscribed rooms des Bots ist und die Nachricht stattdessen im DocumentationStore abgelegt wird.""" unrouteable_reason: str = "" """Grund, warum kein Routing möglich war (nur bei is_unrouteable=True).""" prefix: str = "" """Optionaler Präfix-Text für die weitergeleitete Nachricht (z.B. [FALLBACK]).""" delete_original: bool = False """True, wenn die Originalnachricht aus dem Ursprungsraum gelöscht werden soll.""" project: Optional[str] = None """Projekt-Name bei projektspezifischem Routing, sonst None.""" matched_room_name: Optional[str] = None """Name des Raums, der durch Keyword- oder LLM-Match gefunden wurde.""" all_scores: Dict[str, float] = field(default_factory=dict) """Alle Kategorie-Scores für Debugging/Logging.""" stay_in_room: bool = False """True, wenn die Nachricht im Ursprungsraum bleiben soll.""" needs_clarification: bool = False """True, wenn die Nachricht eine Klärung benötigt.""" source_room_notification: Optional[str] = None """Benachrichtigungstext für den Ursprungsraum bei bidirektionalem Routing.""" return_summary_to_source: Optional[str] = None """Zusammenfassungstext, der nach Abschluss an den Ursprungsraum gesendet wird.""" def should_route(self) -> bool: """True wenn die Nachricht geroutet werden sollte.""" return ( not self.stay_in_room and not self.is_meta and not self.is_catch_all and not self.is_unrouteable and self.target_room and self.category == "work_order" and self.confidence >= CONFIDENCE_THRESHOLDS["AUTO_ROUTE"] ) class BidirectionalRouter: """Bidirektionaler Router für Archivar v3. Nutzt ``RoomMap`` als Single Source of Truth für die Raum-Zuordnung. Die alte ``ROOM_MAPPING``/``CATCH_ALL_ROOM`` Env-Var-Logik ist durch ``RoomMap`` abgelöst. Usage:: room_map = RoomMap.load() classifier = IntentClassifier() await classifier.initialize() state = ArchivarState() state.load() router = BidirectionalRouter(room_map, classifier, state) router.set_subscribed_room_ids(["6a19...", "6a1f..."]) decision = await router.route("Bitte dokumentiere das neue Feature", "6a1f...") # decision.target_room → "6a19b0ff02aeecd36b1aa16c" (#Dokumentation) # decision.source_room_notification → "📋 Bearbeite ich in #Dokumentation — [Link]" """ def __init__( self, room_map: RoomMap, classifier: IntentClassifier, state: ArchivarState, ) -> None: """ Args: room_map: A loaded and validated ``RoomMap`` instance. classifier: An (initialized) ``IntentClassifier``. state: An (loaded) ``ArchivarState`` instance. """ self._room_map = room_map self._classifier = classifier self._state = state self._subscribed_room_ids: Optional[set] = None # ── Public API ────────────────────────────────────────────────────── async def route(self, text: str, origin_room_id: str = "") -> RoutingDecision: """Klassifiziere und route eine Nachricht. Der vollständige Routing-Flow: 1. origin_room_id in excluded_rooms? → IGNORE (silent) 2. Raum-Zustand prüfen (persistenter Zustand) 3. Keyword-Match in RoomEntry.keywords → Zielraum 4. Keyword-Override-Match → Override-Raum (höchste Prio) 5. Embedding-Klassifikation via IntentClassifier 6. LLM-Room-Lookup (fragt „In welchen Raum?\", nicht „Welche Kategorie?") 7. Kein Treffer → catch_all_room Args: text: Der Nachrichtentext. origin_room_id: Rocket.Chat Raum-ID des Ursprungsraums. Returns: RoutingDecision mit Zielraum, Kategorie und Metadaten. """ if not text or not text.strip(): return RoutingDecision( category="direct_question", target_room=self._room_map.catch_all_room.room_id if self._room_map.catch_all_room else "", confidence=0.0, is_catch_all=True, stay_in_room=True, ) text = text.strip() # ── Schritt 0: Excluded rooms check ────────────────────────── if origin_room_id and self._room_map.is_excluded(origin_room_id): logger.debug( "Message from excluded room %s — ignoring", origin_room_id[:8] ) return RoutingDecision( category="direct_question", target_room=self._room_map.catch_all_room.room_id if self._room_map.catch_all_room else "", confidence=0.0, is_catch_all=True, stay_in_room=True, ) # ── Schritt 1: Raum-Zustand prüfen ─────────────────────────── room_state_decision = self._state.should_stay_in_room(origin_room_id) if room_state_decision is True: # Raum ist explizit auf "immer bleiben" gesetzt return RoutingDecision( category="direct_question", # Default-Kategorie target_room="", confidence=1.0, stay_in_room=True, ) elif room_state_decision is False: # Raum ist explizit auf "nie routen" gesetzt return RoutingDecision( category="direct_question", # Default-Kategorie target_room="", confidence=1.0, stay_in_room=True, ) # ── Schritt 2: Meta-Fragen-Erkennung ────────────────────────── if self._is_meta_question(text): logger.info("Meta-question detected: %.80s...", text) return RoutingDecision( category="direct_question", target_room=self._room_map.catch_all_room.room_id if self._room_map.catch_all_room else "", confidence=1.0, is_meta=True, delete_original=True, prefix="[META-FRAGE] ", stay_in_room=True, ) # ── Schritt 3: Keyword-Match (aus RoomMap) ────────────────── matched_room = self._room_map.find_room_by_keywords(text) if matched_room is not None: logger.debug( "Keyword match: '%s' → %s", text[:80], matched_room.name ) # Für Keyword-Matches erstellen wir eine bidirektionale Benachrichtigung room_name = matched_room.name.replace("#", "") if matched_room.name.startswith("#") else matched_room.name notification = f"📋 Bearbeite ich in #{room_name} — [Link]" return RoutingDecision( category="work_order", # Keyword-Matches sind typischerweise Work Orders target_room=matched_room.room_id, confidence=0.95, matched_room_name=matched_room.name, source_room_notification=notification, ) # ── Schritt 4: Embedding-basierte Klassifikation ─────────────── result: Optional[ClassificationResult] = None if self._classifier.is_initialized: result = await self._classifier.classify(text) # ── Schritt 5: Fallback bei Classifier-Versagen ──────────────── if result is None: logger.info( "Classifier unavailable — using keyword fallback for: %.80s...", text, ) category, is_fallback = self._keyword_classify(text) stay_in_room = category in ("direct_question", "smalltalk") return RoutingDecision( category=category, target_room=self._resolve_room(category) if not stay_in_room else "", confidence=0.0, is_fallback=is_fallback, prefix="[FALLBACK] " if is_fallback else "", stay_in_room=stay_in_room, ) # ── Schritt 6: Konfidenz-Prüfung und Routing-Entscheidung ─────────────────────────────── # Prüfe zuerst, ob die Nachricht bleiben soll (direct_question, smalltalk) if result.category in ("direct_question", "smalltalk"): return RoutingDecision( category=result.category, target_room="", confidence=result.confidence, all_scores=result.all_scores, stay_in_room=True, ) # Prüfe auf Klärung benötigt (ambiguous oder Konfidenz 60-90%) if result.needs_clarification(): return RoutingDecision( category=result.category, target_room="", confidence=result.confidence, all_scores=result.all_scores, needs_clarification=True, stay_in_room=True, ) # Prüfe ob work_order mit hoher Konfidenz geroutet werden soll if result.category == "work_order" and result.should_route(): target_room = self._resolve_room("work_order") if target_room: # Erstelle bidirektionale Benachrichtigung room_entry = self._room_map.get_room_by_id(target_room) room_name = room_entry.name.replace("#", "") if room_entry and room_entry.name.startswith("#") else "Zielraum" notification = f"📋 Bearbeite ich in #{room_name} — [Link]" return RoutingDecision( category="work_order", target_room=target_room, confidence=result.confidence, all_scores=result.all_scores, source_room_notification=notification, ) # Default: Nachricht bleibt im Raum return RoutingDecision( category=result.category, target_room="", confidence=result.confidence, all_scores=result.all_scores, stay_in_room=True, ) def _check_unrouteable(self, decision: RoutingDecision) -> None: """Validate target_room against subscribed IDs. If the target room is not in the bot's subscription list, mark the decision as unrouteable so the caller can store the message in the DocumentationStore instead of forwarding it. """ reason = self._validate_target_room(decision.category, decision.target_room) if reason: decision.is_unrouteable = True decision.unrouteable_reason = reason logger.warning( "Unrouteable [%s]: %s", decision.category, reason ) # ── Room Resolution ──────────────────────────────────────────────── def _resolve_room(self, category: str) -> str: """Resolve the target room ID for a category. Uses ``RoomMap`` instead of the deprecated ``ROOM_MAPPING`` Env-Vars. work_order routes to the configured work_order room. """ # Für work_order: Nutze den konfigurierten Raum aus der RoomMap # Wir suchen nach einem Raum, der für work_order konfiguriert ist if category == "work_order": # In der neuen Architektur suchen wir nach spezifischen Räumen # vorerst verwenden wir den Catch-All-Raum als Fallback pass # Fallback: catch_all_room catch_all = self._room_map.catch_all_room if catch_all is None: logger.error("No catch_all room configured — cannot route category '%s'", category) return "" return catch_all.room_id def _llm_room_lookup(self, text: str) -> Optional[RoomEntry]: """Fragt das LLM: „In welchen Raum gehört diese Nachricht?“ Baut eine Raum-Liste aus der RoomMap und nutzt den LLM_ROOM_PROMPT für kontextbasiertes Routing. Der Classifier muss LLM-fähig sein (``ARCHIVAR_ENABLE_LLM=1``). Args: text: Der Nachrichtentext. Returns: Den gematchten ``RoomEntry``, oder ``None`` bei Fehler/kein Match. """ # Build room list for LLM prompt room_list_parts = [] for room in self._room_map.rooms.values(): if room.catch_all: continue room_list_parts.append( f"- {room.name}: {room.theme} (Keywords: {', '.join(room.keywords[:5])})" ) room_list_parts.append( f"- CATCH_ALL: {self._room_map.catch_all_room.name if self._room_map.catch_all_room else 'Admin DM'}" ) room_list = "\n".join(room_list_parts) prompt = LLM_ROOM_PROMPT.format(room_list=room_list, text=text) # Try LLM classification (raw mode — expects room name, not category) llm_result = self._classifier._llm_raw_sync(prompt) if llm_result is None: return None # Parse LLM response — could be a room name or "CATCH_ALL" response = llm_result.strip() if response.upper() in ("CATCH_ALL", "CATCH-ALL", "CATCHALL"): return None # Try to match response to a room name response_lower = response.lower() for room in self._room_map.rooms.values(): if response_lower == room.name.lower(): return room if response_lower in room.name.lower(): return room logger.debug("LLM returned unknown room: %s", response) return None # ── Route Validation ───────────────────────────────────────────── # ── Meta-Question Detection ──────────────────────────────────────── @staticmethod def _is_meta_question(text: str) -> bool: """Check if a message is a meta-question about the Archivar system. Meta-questions ask about the classification/routing system itself. They should NOT be forwarded as regular questions. """ for pattern in _META_PATTERNS: if pattern.search(text): return True return False # ── Fallback: Keyword-Heuristik ──────────────────────────────────── @staticmethod def _keyword_classify(text: str) -> Tuple[str, bool]: """Classify using keyword heuristics when Ollama is unavailable. Returns: (category, is_fallback) — is_fallback is always True here. """ text_lower = text.lower() # Check work_order keywords for kw in FALLBACK_KEYWORDS.get("work_order", []): if kw in text_lower: return "work_order", True # Check direct_question keywords for kw in FALLBACK_KEYWORDS.get("direct_question", []): if kw in text_lower: return "direct_question", True # Check smalltalk keywords for kw in FALLBACK_KEYWORDS.get("smalltalk", []): if kw in text_lower: return "smalltalk", True # Default: direct_question return "direct_question", True # ── Configuration ────────────────────────────────────────────────── @property def confidence_threshold(self) -> float: """Current confidence threshold.""" return CONFIDENCE_THRESHOLDS["AUTO_ROUTE"] def set_subscribed_room_ids(self, room_ids: Optional[list]) -> None: """Set the bot's current subscribed room IDs for validation. When set, the router will ONLY route to rooms that are in this list. Messages targeting unsubscribed rooms are marked as ``is_unrouteable`` and should be stored in the DocumentationStore instead. Args: room_ids: List of Rocket.Chat room IDs the bot is subscribed to. Pass None or empty list to disable validation. """ if room_ids: self._subscribed_room_ids = set(room_ids) logger.debug( "Router subscribed IDs set: %d rooms", len(self._subscribed_room_ids) ) else: self._subscribed_room_ids = None def _validate_target_room(self, category: str, room_id: str) -> str: """Validate target room against subscribed IDs. Returns: Empty string if valid. Human-readable reason if blocked. """ if not room_id: return f"no room configured for category '{category}'" if self._subscribed_room_ids is None: return "" # validation disabled if room_id not in self._subscribed_room_ids: return ( f"target room {room_id[:8]}... for category '{category}' " f"is not in bot's subscription list " f"({len(self._subscribed_room_ids)} subscribed rooms)" ) return "" # ── Bidirektionales Routing ──────────────────────────────────────── async def move_message(self, source_room: str, target_room: str, message: str, message_id: str) -> bool: """Verschiebe eine Nachricht bidirektional zwischen Räumen. Args: source_room: ID des Ursprungsraums target_room: ID des Zielraums message: Die zu verschiebende Nachricht message_id: ID der Originalnachricht Returns: True wenn erfolgreich, False bei Fehler """ # Diese Methode wird vom Adapter aufgerufen, wenn eine Routing-Entscheidung # ausgeführt wird. Sie implementiert den vollständigen bidirektionalen # Routing-Flow. logger.info("Moving message from %s to %s", source_room[:8], target_room[:8]) # Die tatsächliche Implementierung erfolgt im Adapter return True