diff --git a/plugin/adapter.py b/plugin/adapter.py index 0950a32..7eb0177 100644 --- a/plugin/adapter.py +++ b/plugin/adapter.py @@ -534,7 +534,13 @@ class RocketChatAdapter(BasePlatformAdapter): return False return False - async def connect(self) -> bool: + async def connect(self, *, is_reconnect: bool = False) -> bool: + """Connect to Rocket.Chat (REST + DDP) and start listen loop. + + is_reconnect: True wenn dies ein Reconnect-Versuch ist (z.B. nach + Silent-Death-Erkennung). Core ruft connect() mit diesem Keyword-Arg + auf; fehlt es → TypeError. Siehe Bug M3. + """ if not self.base_url or not self.user or not self.password: logger.error("[rocketchat] Missing configuration") return False @@ -831,7 +837,7 @@ class RocketChatAdapter(BasePlatformAdapter): if choice.startswith("MOVE_REQ:") and "::" in choice: _, choice = choice.split("::", 1) choice = choice.strip() - # Normalisiere: "1️⃣ Rüber" → "1️⃣", "2 Hier" → "2" + # Normalisiere: "1️⃣ Rüber" → "1️⃣", "2 Generell" → "2" if choice and choice[0] in "123": choice = choice[0] elif choice and choice[:2] in ("1️⃣", "2️⃣", "3️⃣"): @@ -843,28 +849,28 @@ class RocketChatAdapter(BasePlatformAdapter): if num == 1: choice = "rüberkopieren" elif num == 2: - choice = "hier bleiben" + choice = "generell" # v6: 2 = Generell hier bleiben (sticky) else: - choice = "generell" + choice = "hier bleiben" # v6: 3 = Hier bleiben (nur diesmal) choice = choice.lower() - # Neue Mapping-Logik für verbesserte Button-UX + # Neue Mapping-Logik für verbesserte Button-UX (v6) feedback_type = "stay" # Default if choice in ("1", "1️⃣", "Rüber", "rüber", "rüberkopieren", "kopieren", "confirm_move", "✅ja"): - # Rüberkopieren + # 1️⃣ Rüberkopieren → Antwort im Zielraum target_txt = f"*(Auftrag von @{move_req['username']}, hierher kopiert)*\n{move_req['text']}" if move_req.get("username"): await self._post_message_with_retry(move_req["target_room"], target_txt) _CURRENT_ORIGIN_ROOM.set(move_req["target_room"]) forwarded = True feedback_type = "confirm" - elif choice in ("3", "3️⃣", "Nein", "nein", "nicht mehr", "generell"): - # Nicht mehr fragen / sticky_room setzen + elif choice in ("2", "2️⃣", "generell", "generell hier bleiben"): + # 2️⃣ Generell hier bleiben → Antwort im Ursprungsraum + Sticky-Eintrag self._sticky_rooms[room_id] = time.time() await self._post_message_with_retry(room_id, "🔒 Verstanden — dieser Raum wird nicht mehr automatisch geroutet. (Gilt bis zum nächsten Gateway-Neustart)") feedback_type = "never" else: - # "Hier bleiben" / "2" / "2️⃣" — Default + # 3️⃣ Hier bleiben → Antwort im Ursprungsraum (nur diesmal, kein Sticky) await self._post_message_with_retry(room_id, "👍 Bleiben hier — ich kümmere mich drum.") feedback_type = "stay" @@ -981,14 +987,14 @@ class RocketChatAdapter(BasePlatformAdapter): try: move_prefix = f"MOVE_REQ:{room_id}" buttons = _build_custom_buttons( - ["1️⃣ Rüber", "2️⃣ Hier", "3️⃣ Nein"], + ["1️⃣ Rüber", "2️⃣ Generell", "3️⃣ Hier"], prefix=move_prefix ) note = (f"Dein Auftrag passt thematisch besser in **{target_name}**.\n\n" f"**Was soll ich tun?**\n\n" f"1️⃣ **Rüberkopieren** = Auftrag verschieben, ich antworte dort\n" - f"2️⃣ **Hier bleiben** = Auftrag bleibt hier, ich kümmere mich drum\n" - f"3️⃣ **Nicht mehr fragen** = Raum wird bis Neustart nicht mehr geroutet\n\n" + f"2️⃣ **Generell hier bleiben** = Auftrag bleibt hier + Raum wird bis Neustart nicht mehr geroutet\n" + f"3️⃣ **Hier bleiben** = Auftrag bleibt hier (nur diesmal)\n\n" f"Wohin soll ich den Auftrag verschieben?") attachments = [{ "color": "#1d74f5", @@ -1009,9 +1015,9 @@ class RocketChatAdapter(BasePlatformAdapter): note = ( f"Dein Auftrag passt thematisch besser in **{target_name}**.\n" f"Antworte mit einer Zahl:\n" - f"1 = Ja, rüberkopieren und dort abarbeiten\n" - f"2 = Hier bleiben\n" - f"3 = Generell hier bleiben" + f"1 = Rüberkopieren und dort abarbeiten\n" + f"2 = Generell hier bleiben (Sticky)\n" + f"3 = Hier bleiben (nur diesmal)" ) self._pending_move_requests[room_id] = { "text": text, diff --git a/plugin/archivar/config.py b/plugin/archivar/config.py index 91c4cdb..c161db9 100644 --- a/plugin/archivar/config.py +++ b/plugin/archivar/config.py @@ -147,7 +147,7 @@ LLM_CONFIG = { "enabled": os.getenv("ARCHIVAR_ENABLE_LLM", "").strip().lower() in ("1", "true", "yes"), "model": "qwen2.5:7b", "timeout": 30.0, # Iterative Optimierung: Start 30s (19.06.2026) - "base_url": "http://localhost:11434", + "base_url": os.getenv("OLLAMA_BASE_URL", "http://localhost:11434"), "temperature": 0.0, "max_tokens": 30, # Raum-ID = 24 chars + Puffer } @@ -173,12 +173,24 @@ LLM_CONFIDENCE_THRESHOLD = 0.90 # Ausgabe: Direkt die Raum-ID (keine Kategorien, kein Name-Matching). LLM_ROOM_PROMPT = """Du bist ein Raum-Zuordner. Ordne die Nachricht EINEM Raum zu. -Antworte NUR mit der exakten Raum-ID aus der Liste. Keine Erklärungen, keine Sätze. -Wenn unsicher, antworte mit dem einzelnen Wort: CATCH_ALL +Antworte mit der exakten Raum-ID aus der Liste ODER dem Wort STAY. +Wähle STAY wenn die Nachricht thematisch zum Ursprungsraum passt ODER wenn du unsicher bist. +Antworte NUR mit einem Wort, keine Erklärungen. + +Ursprungsraum: {origin_room} Verfügbare Räume (ID | Name | Keywords): {room_list} +Beispiele für STAY: +- Eine Frage zum aktuellen Raumthema → STAY +- Smalltalk, Begrüßung, Dank → STAY +- Unklare oder mehrdeutige Nachricht → STAY + +Beispiele für ROUTE (Raum-ID): +- Ein klarer Arbeitsauftrag für ein anderes Raumthema → die passende Raum-ID +- Eine Frage, die eindeutig in einen anderen Raum gehört → die passende Raum-ID + Nachricht: {text} Raum-ID:""" diff --git a/plugin/archivar/router.py b/plugin/archivar/router.py index 5ea3314..e9fe7e3 100644 --- a/plugin/archivar/router.py +++ b/plugin/archivar/router.py @@ -218,22 +218,26 @@ class BidirectionalRouter: # ── Public API ────────────────────────────────────────────────────── async def route(self, text: str, origin_room_id: str = "") -> RoutingDecision: - """Klassifiziere und route eine Nachricht (korrigierter Flow). + """Klassifiziere und route eine Nachricht (v6 Flow mit Origin-First Guard). - Der neue Routing-Flow (Architekturskizze): - 1. origin_room_id in excluded_rooms? → IGNORE (silent) - 2. Raum-Zustand prüfen (persistenter Zustand) - 3. Meta-Fragen-Erkennung - 4. Keyword-Match in RoomEntry.keywords → Zielraum (schnell, zuverlässig) - 5. FAISS Phase-1: Raum-Index + Keyword-Booster - - FAISS-Score >= FAISS_AUTO_ROUTE → direkt routen (kein LLM) - - Score unter Schwelle → Fall-through zu Embedding + LLM - 6. Embedding-Vorfilter: binär "Smalltalk" vs. "potenzieller Auftrag" - - Klarer Smalltalk → stay_in_room - - Unsicher → weiter zu LLM-Raum-Router - 7. LLM-Raum-Router: LLM_ROOM_PROMPT + Raumliste mit Keywords → room_id direkt - 8. Raum gefunden → Move-Request-Button (Butler-Prinzip: ✅Ja/📍Hier) - 9. Kein Treffer → catch_all_room + Der neue Routing-Flow (v6): + -0.5 ORIGIN-FIRST GUARD (VOR allen anderen Schritten): + 1. origin_room_id leer (echte DM) → normaler Flow + 2. origin_room ist Catch-All-Raum → stay_in_room + 3. origin_room ist excluded → ignore + 0. Excluded rooms check + 1. Raum-Zustand prüfen (persistenter Zustand) + 2. Meta-Fragen-Erkennung + 3. Keyword-Match in RoomEntry.keywords → Zielraum (schnell, zuverlässig) + 3.5 FAISS Phase-1: Raum-Index + Keyword-Booster + 4. Embedding-Vorfilter: binär "Smalltalk" vs. "potenzieller Auftrag" + 5. LLM-Raum-Router: LLM_ROOM_PROMPT + Raumliste → STAY oder room_id + 6. ORIGIN-FIRST GUARD (nach LLM): + - LLM sagt STAY → stay_in_room + - LLM == origin_room → stay_in_room + - LLM == catch_all_room → stay_in_room (kein DM-Routing aus Projekträumen!) + - LLM == anderer Raum → Move-Request (Butler-Prinzip) + 7. LLM-Fehler → stay_in_room Args: text: Der Nachrichtentext. @@ -443,31 +447,14 @@ class BidirectionalRouter: # ── Schritt 5: LLM-Raum-Router (zentraler Prompt) ──────────── # LLM_ROOM_PROMPT erhält Nachricht + Raumliste mit Keywords, - # liefert room_id direkt (keine Kategorien, kein Name-Matching) - llm_room, llm_failed = await self._llm_room_lookup(text) - if llm_room is not None: - room_name = llm_room.name.replace("#", "") if llm_room.name.startswith("#") else llm_room.name - logger.info( - "LLM-Raum-Router: '%s' → %s (%s)", - text[:80], llm_room.name, llm_room.room_id[:8], - ) + # liefert STAY oder room_id direkt (keine Kategorien, kein Name-Matching) + llm_room, llm_stay, llm_failed = await self._llm_room_lookup(text, origin_room_id) - # ── Schritt 6: Move-Request-Button (Butler-Prinzip) ────── - # Vor dem Routing: Button an Andreas — "Soll ich nach [Raum] kopieren?" - # ✅Ja → Route, 📍Hier → stay_in_room - return RoutingDecision( - category="work_order", - target_room=llm_room.room_id, - confidence=0.90, - matched_room_name=llm_room.name, - move_request_sent=True, - move_request_target_name=llm_room.name, - move_request_target_id=llm_room.room_id, - ) - - # ── Schritt 7: LLM-Fehler oder kein Treffer ────────────────── + # ── Schritt 6: ORIGIN-FIRST GUARD (v6) ────────────────────── + # Paradigmenwechsel: Ursprungsraum entscheidet WOHIN die Antwort geht. + # Archivar schlägt nur VERLEGUNG vor (Move-Request). if llm_failed: - # FIX 1: Timeout/Exception → Fallback auf Ursprungsraum, NICHT Catch-All + # LLM-Aufruf fehlgeschlagen → stay_in_room logger.warning( "LLM-Raum-Router: Aufruf fehlgeschlagen für '%.80s...' → stay_in_room (Ursprungsraum)", text, @@ -479,20 +466,65 @@ class BidirectionalRouter: stay_in_room=True, is_catch_all=False, ) - else: - # LLM erfolgreich, aber kein Match → catch_all + + if llm_stay or llm_room is None: + # LLM sagt STAY oder unsicher → stay_in_room logger.info( - "LLM-Raum-Router: kein Treffer für '%.80s...' → catch_all", text + "LLM-Raum-Router: STAY für '%.80s...' → stay_in_room", text[:80] ) - catch_all = self._room_map.catch_all_room return RoutingDecision( category="direct_question", - target_room=catch_all.room_id if catch_all else "", + target_room="", confidence=0.0, - is_catch_all=True, stay_in_room=True, ) + # LLM hat einen Raum vorgeschlagen — Origin-First Guard prüfen + catch_all = self._room_map.catch_all_room + catch_all_id = catch_all.room_id if catch_all else "" + + # Guard 1: LLM == origin_room → stay_in_room + if origin_room_id and llm_room.room_id == origin_room_id: + logger.info( + "Origin-First Guard: LLM schlägt Ursprungsraum vor → stay_in_room" + ) + return RoutingDecision( + category="direct_question", + target_room="", + confidence=0.0, + stay_in_room=True, + ) + + # Guard 2: LLM == catch_all_room → stay_in_room + # (Kein DM-Routing aus Projekträumen!) + if catch_all_id and llm_room.room_id == catch_all_id: + logger.info( + "Origin-First Guard: LLM schlägt Catch-All vor → stay_in_room" + ) + return RoutingDecision( + category="direct_question", + target_room="", + confidence=0.0, + stay_in_room=True, + ) + + # Guard 3: LLM == anderer Raum → Move-Request (Butler-Prinzip) + room_name = llm_room.name.replace("#", "") if llm_room.name.startswith("#") else llm_room.name + logger.info( + "LLM-Raum-Router: '%s' → %s (%s) — Move-Request pending", + text[:80], llm_room.name, llm_room.room_id[:8], + ) + + return RoutingDecision( + category="work_order", + target_room=llm_room.room_id, + confidence=0.90, + matched_room_name=llm_room.name, + move_request_sent=True, + move_request_target_name=llm_room.name, + move_request_target_id=llm_room.room_id, + ) + except Exception as e: # ── Catch-All-Schutz: unerwarteter Fehler → Fallback ────── logger.error( @@ -546,7 +578,7 @@ class BidirectionalRouter: return catch_all.room_id - async def _llm_room_lookup(self, text: str) -> Tuple[Optional[RoomEntry], bool]: + async def _llm_room_lookup(self, text: str, origin_room_id: str = "") -> Tuple[Optional[RoomEntry], bool, bool]: """Fragt das LLM: „In welchen Raum gehört diese Nachricht?“ Baut eine Raum-Liste mit IDs, Namen und ALLEN Keywords aus der RoomMap @@ -559,13 +591,15 @@ class BidirectionalRouter: Args: text: Der Nachrichtentext. + origin_room_id: Rocket.Chat Raum-ID des Ursprungsraums (für Kontext). Returns: - (RoomEntry, False) — LLM erfolgreich, Raum gefunden - (None, False) — LLM erfolgreich, kein Match (CATCH_ALL) - (None, True) — LLM-Aufruf fehlgeschlagen (Exception/Timeout) + (RoomEntry, False, False) — LLM erfolgreich, Raum gefunden (ROUTE) + (None, False, False) — LLM erfolgreich, STAY (kein Routing) + (None, False, True) — LLM-Aufruf fehlgeschlagen (Exception/Timeout) """ # Build room list for LLM prompt: "ID | Name | Keywords" + # Nur Nicht-Catch-All-Räume als Optionen (Catch-All ist nie ein Routing-Ziel) room_list_parts = [] for room in self._room_map.rooms.values(): if room.catch_all: @@ -576,47 +610,55 @@ class BidirectionalRouter: room_list_parts.append( f"{room.room_id} | {room.name} | {kw_str}" ) - # Catch-All als Fallback - catch_all_id = ( - self._room_map.catch_all_room.room_id - if self._room_map.catch_all_room - else "CATCH_ALL" - ) - room_list_parts.append( - f"{catch_all_id} | CATCH_ALL | (Fallback für unklare Nachrichten)" - ) + + if not room_list_parts: + # Keine Nicht-Catch-All-Räume → STAY + return None, False, False + room_list = "\n".join(room_list_parts) - prompt = LLM_ROOM_PROMPT.format(room_list=room_list, text=text) + # Ursprungsraum-Name für Kontext + origin_name = "" + if origin_room_id: + origin_room = self._room_map.get_room_by_id(origin_room_id) + if origin_room: + origin_name = origin_room.name - # Try LLM — expects room ID directly + prompt = LLM_ROOM_PROMPT.format( + room_list=room_list, + text=text, + origin_room=origin_name or "unbekannt", + ) + + # Try LLM — expects room ID directly or "STAY" # Semaphore schützt vor parallelen Ollama-Aufrufen (qwen2.5:7b = single-request) async with self._llm_semaphore: llm_result = await self._classifier._llm_raw(prompt) if llm_result is None: - return None, True # LLM-Aufruf fehlgeschlagen + return None, False, True # LLM-Aufruf fehlgeschlagen - # Parse LLM response — should be a room ID or "CATCH_ALL" + # Parse LLM response — should be a room ID or "STAY" response = llm_result.strip() - if response.upper() in ("CATCH_ALL", "CATCH-ALL", "CATCHALL"): - return None, False # LLM erfolgreich, kein Match + # STAY = Nachricht bleibt im Ursprungsraum + if response.upper() == "STAY": + return None, False, False # LLM erfolgreich, STAY # Direct lookup by room ID (LLM returns the ID directly) room = self._room_map.get_room_by_id(response) if room is not None: - return room, False + return room, False, False # Fallback: try name matching (for LLMs that return names instead of IDs) response_lower = response.lower() for room in self._room_map.rooms.values(): if response_lower == room.name.lower(): - return room, False + return room, False, False if response_lower in room.name.lower(): - return room, False + return room, False, False logger.debug("LLM returned unknown room: %s", response) - return None, False + return None, False, False # Unbekannte Antwort → STAY # ── Route Validation ───────────────────────────────────────────── diff --git a/plugin/tools.py b/plugin/tools.py index 392edb0..62a9a16 100644 --- a/plugin/tools.py +++ b/plugin/tools.py @@ -958,6 +958,84 @@ ROCKETCHAT_FILES_SCHEMA = { } +# ── Proaktiver Raum-Broadcast (B6) ────────────────────────────────────── +# Cooldown-Tracking: verhindert Spam bei vielen kleinen Aktionen. +# Nur "Fertig"-Markierungen triggern einen Broadcast. +_broadcast_cooldowns: Dict[str, float] = {} # room_id → timestamp +_BROADCAST_COOLDOWN_SECONDS: float = 300.0 # 5 Minuten + + +def _handle_rocketchat_broadcast(args: dict, **kw) -> str: + """Sende einen proaktiven Status-Broadcast in einen Projektraum. + + Format: 'Finn hat das Karten-Highlight implementiert. 9 Tests bestanden, Rainer hat freigegeben.' + + Cooldown: 5 Minuten pro Raum — verhindert Spam bei vielen kleinen Aktionen. + Nur bei expliziten "Fertig"-Markierungen verwenden, nicht bei jeder kleinen Aktion. + + Args: + room_id: Zielraum-ID (aus room-map.json oder ROCKETCHAT.MAP.md) + text: Der Broadcast-Text (menschenähnlich, kein Bot-Ton) + """ + global _broadcast_cooldowns + client = _rc_client() + if not client: + return _rc_error() + + room_id = str(args.get("room_id") or "").strip() + text = str(args.get("text") or "").strip() + + if not room_id: + return tool_error("room_id is required for rocketchat_broadcast") + if not text: + return tool_error("text is required for rocketchat_broadcast") + + # Cooldown-Check + now = time.time() + last = _broadcast_cooldowns.get(room_id, 0.0) + if now - last < _BROADCAST_COOLDOWN_SECONDS: + remaining = int(_BROADCAST_COOLDOWN_SECONDS - (now - last)) + return tool_result({ + "success": False, + "cooldown": True, + "message": f"Broadcast-Cooldown aktiv: noch {remaining}s für Raum {room_id[:8]}...", + }) + + try: + result = client.send_message(room_id, text) + if result.get("success"): + _broadcast_cooldowns[room_id] = now + return tool_result({ + "success": True, + "room_id": room_id, + "text": text[:200], + }) + else: + return tool_error(f"Broadcast failed: {result.get('error', 'unknown error')}") + except Exception as exc: + return tool_error(f"rocketchat_broadcast failed: {type(exc).__name__}: {exc}") + + +ROCKETCHAT_BROADCAST_SCHEMA = { + "name": "rocketchat_broadcast", + "description": ( + "Send a proactive status broadcast to a project room. " + "Use this after completing a task to inform the team. " + "Format: 'Finn hat das Karten-Highlight implementiert. 9 Tests bestanden, Rainer hat freigegeben.' " + "Cooldown: 5 minutes per room to prevent spam. " + "Only use for explicit 'done' markers, not for every small action." + ), + "parameters": { + "type": "object", + "properties": { + "room_id": {"type": "string", "description": "Target project room ID (from room-map.json)"}, + "text": {"type": "string", "description": "Broadcast message (human-like, not bot-like)"}, + }, + "required": ["room_id", "text"], + }, +} + + # --------------------------------------------------------------------------- # Registration helpers for the plugin register() function # --------------------------------------------------------------------------- @@ -970,6 +1048,7 @@ _TOOLS = ( ("rocketchat_upload", ROCKETCHAT_UPLOAD_SCHEMA, _handle_rocketchat_upload, "📎"), ("rocketchat_download", ROCKETCHAT_DOWNLOAD_SCHEMA, _handle_rocketchat_download, "📥"), ("rocketchat_files", ROCKETCHAT_FILES_SCHEMA, _handle_rocketchat_files, "📁"), + ("rocketchat_broadcast", ROCKETCHAT_BROADCAST_SCHEMA, _handle_rocketchat_broadcast, "📢"), )