From 0e13e4b30d1aea6637f08dfd342bea2db23a34a3 Mon Sep 17 00:00:00 2001 From: "Bernd (Hermes)" Date: Fri, 19 Jun 2026 09:09:17 +0200 Subject: [PATCH] =?UTF-8?q?fix(archivar):=20ContextVar=E2=86=92global=20di?= =?UTF-8?q?ct,=20asyncio.to=5Fthread,=20EMBEDDING=5FBASE=5FURL,=20FAISS=5F?= =?UTF-8?q?AUTO=5FROUTE=3D0.55?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - adapter.py: ContextVars durch globales _room_context dict + threading.Lock ersetzt (Agent-Task sieht jetzt Archivar-Zielraum — kein error-not-allowed mehr) - adapter_integration.py: Stay-Feedback-Handler leert thematic_target (verhindert dass nächster Send auf alten Archivar-Vorschlag fällt) - classifier.py: _llm_raw() nutzt asyncio.to_thread() statt direktem await (LLMClient.generate() ist synchron — vorher TypeError) - config.py: ARCHIVAR_EMBEDDING_BASE_URL trennt Embeddings von Chat-URL (OLLAMA_BASE_URL-Kollision behoben). FAISS_AUTO_ROUTE 0.70→0.55 (mehr Nachrichten durch Booster statt direktem FAISS-Routing) --- plugin/adapter.py | 106 ++++++++++++++----------- plugin/archivar/adapter_integration.py | 30 ++++++- plugin/archivar/classifier.py | 6 +- plugin/archivar/config.py | 6 +- 4 files changed, 95 insertions(+), 53 deletions(-) diff --git a/plugin/adapter.py b/plugin/adapter.py index e79814e..2f4ee26 100644 --- a/plugin/adapter.py +++ b/plugin/adapter.py @@ -9,7 +9,6 @@ Zero external dependencies — stdlib only. """ import asyncio -import contextvars import json import logging import os @@ -37,18 +36,13 @@ if not logger.handlers: logger.propagate = False # Don't double-log to root # ── Virtual Room Translation ────────────────────────────────────────── -# ContextVar tracks the real Rocket.Chat room_id that triggered the current -# agent turn, so send() can route the response back to the correct room even -# though the Hermes session uses a synthetic user-based chat_id. -# This is the mechanism that makes "one agent for all rooms" work -# without touching Hermes Core. -_CURRENT_ORIGIN_ROOM: contextvars.ContextVar[str] = contextvars.ContextVar( - "_rocketchat_origin_room", default="" -) - -_THEMATIC_TARGET_ROOM: contextvars.ContextVar[str] = contextvars.ContextVar( - "_rocketchat_thematic_target_room", default="" -) +# Global dict keyed by virtual chat_id (e.g. "user:alice") that tracks +# the real Rocket.Chat room_id for the current agent turn. +# ContextVars were asyncio-task-local and invisible to the agent task, +# causing send() to fall back to the home channel → error-not-allowed. +# This dict is shared across all asyncio tasks in the same process. +_room_context: Dict[str, Dict[str, str]] = {} # chat_id → {origin_room, thematic_target} +_room_context_lock = threading.Lock() # Globaler Monoton-Zähler für Archivar-Fragen import threading @@ -652,7 +646,10 @@ class RocketChatAdapter(BasePlatformAdapter): # ── Kontext-Reset: _THEMATIC_TARGET_ROOM pro Nachricht zurücksetzen ── # Verhindert dass der Zielraum der VORHERIGEN Nachricht an der # aktuellen klebt (z.B. DM nach Projektraum-Turn → Antwort im Projektraum). - _THEMATIC_TARGET_ROOM.set("") + virtual_chat_id = f"user:{username}" + with _room_context_lock: + ctx = _room_context.setdefault(virtual_chat_id, {}) + ctx["thematic_target"] = "" # ── CLARIFY Response Handling ─────────────────────────────────── # Handle CLARIFY button responses: CLARIFY:: or CLARIFY::other @@ -768,7 +765,10 @@ class RocketChatAdapter(BasePlatformAdapter): target_txt = f"*(Auftrag von @{move_req['username']}, hierher kopiert)*\n{move_req['text']}" if move_req.get("username"): self.rest.post_message(move_req["target_room"], target_txt) - _CURRENT_ORIGIN_ROOM.set(move_req["target_room"]) + virtual_chat_id = f"user:{move_req['username']}" + with _room_context_lock: + ctx = _room_context.setdefault(virtual_chat_id, {}) + ctx["origin_room"] = move_req["target_room"] forwarded = True feedback_type = "confirm" elif choice in ("3", "3️⃣", "Nein", "nein", "nicht mehr", "generell"): @@ -787,7 +787,8 @@ class RocketChatAdapter(BasePlatformAdapter): await self.archivar.handle_feedback_response( message_id=move_req["message_id"], user_id=user_id, - feedback_type=feedback_type + feedback_type=feedback_type, + username=username ) return # Move-Request verarbeitet — keine weitere Verarbeitung @@ -842,7 +843,10 @@ class RocketChatAdapter(BasePlatformAdapter): category = decision.category # ── Archivar-Kontext-Weitergabe: Zielraum + Frage-Nr ────── if hasattr(decision, 'target_room') and decision.target_room: - _THEMATIC_TARGET_ROOM.set(decision.target_room) + virtual_chat_id = f"user:{username}" + with _room_context_lock: + ctx = _room_context.setdefault(virtual_chat_id, {}) + ctx["thematic_target"] = decision.target_room global _question_counter with _question_counter_lock: _question_counter += 1 @@ -957,14 +961,20 @@ class RocketChatAdapter(BasePlatformAdapter): note = f"📋 Thema passt zu **{target_name}** — ich hab's dort dokumentiert." self.rest.post_message(room_id, note) # Agent soll im Zielraum antworten, nicht im Ursprungsraum - _CURRENT_ORIGIN_ROOM.set(decision.target_room) + virtual_chat_id = f"user:{username}" + with _room_context_lock: + ctx = _room_context.setdefault(virtual_chat_id, {}) + ctx["origin_room"] = decision.target_room forwarded = True # Move-Request-Handling ist bereits oben (vor Archivar) — hier nur Silent Copy # ── _CURRENT_ORIGIN_ROOM setzen ────────────────────────────────── if not forwarded: - _CURRENT_ORIGIN_ROOM.set(room_id) + virtual_chat_id = f"user:{username}" + with _room_context_lock: + ctx = _room_context.setdefault(virtual_chat_id, {}) + ctx["origin_room"] = room_id # ── Virtual Room Translation ───────────────────────────────── # Replace room-based chat_id with user-based virtual chat_id. @@ -987,7 +997,9 @@ class RocketChatAdapter(BasePlatformAdapter): message_type = MessageType.BUTTON_CLICK if is_button_response else MessageType.TEXT # ── Archivar-Kontext-Weitergabe: Frage-Nr + Zielraum im Prompt ── - target_room_id = _THEMATIC_TARGET_ROOM.get() + with _room_context_lock: + ctx = _room_context.get(virtual_chat_id, {}) + target_room_id = ctx.get("thematic_target", "") if target_room_id: target_name = self._room_info.get(target_room_id, {}).get("name", target_room_id[:12] + "…") with _question_counter_lock: @@ -1647,32 +1659,32 @@ class RocketChatAdapter(BasePlatformAdapter): if chat_id.startswith("user:"): # Priority 0: Archivar-Kontext — wenn der Archivar einen thematischen # Zielraum gesetzt hat, geht die Antwort dorthin (Agent-Autonomie). - thematic_target = _THEMATIC_TARGET_ROOM.get() - if thematic_target and thematic_target != _CURRENT_ORIGIN_ROOM.get(): + with _room_context_lock: + ctx = _room_context.get(chat_id, {}) + thematic_target = ctx.get("thematic_target", "") + origin = ctx.get("origin_room", "") + if thematic_target and thematic_target != origin: real_room_id = thematic_target logger.debug("[rocketchat] send via Archivar target: %s → %s", chat_id, real_room_id) + elif origin: + real_room_id = origin + logger.debug("[rocketchat] send via ContextVar: %s → %s", chat_id, real_room_id) else: - # Priority 1: ContextVar from the message that triggered this turn - origin = _CURRENT_ORIGIN_ROOM.get() - if origin: - real_room_id = origin - logger.debug("[rocketchat] send via ContextVar: %s → %s", chat_id, real_room_id) + # Priority 2: proaktive Nachricht — use most recent room for this user + rooms = self._user_rooms.get(chat_id, []) + if rooms: + real_room_id = rooms[-1] # last room user was active in + logger.debug("[rocketchat] send via user_map (proactive): %s → %s", chat_id, real_room_id) else: - # Priority 2: proaktive Nachricht — use most recent room for this user - rooms = self._user_rooms.get(chat_id, []) - if rooms: - real_room_id = rooms[-1] # last room user was active in - logger.debug("[rocketchat] send via user_map (proactive): %s → %s", chat_id, real_room_id) + # Fallback: try to find any room with recent activity involving this user + logger.warning("[rocketchat] No mapped room for %s, attempting fallback", chat_id) + fallback_room = self._find_fallback_room_for_user(chat_id) + if fallback_room: + real_room_id = fallback_room + logger.info("[rocketchat] Using fallback room %s for %s", fallback_room, chat_id) else: - # Fallback: try to find any room with recent activity involving this user - logger.warning("[rocketchat] No mapped room for %s, attempting fallback", chat_id) - fallback_room = self._find_fallback_room_for_user(chat_id) - if fallback_room: - real_room_id = fallback_room - logger.info("[rocketchat] Using fallback room %s for %s", fallback_room, chat_id) - else: - logger.error("[rocketchat] No real room for %s, cannot send", chat_id) - return SendResult(success=False, error=f"No real room for virtual chat_id {chat_id}") + logger.error("[rocketchat] No real room for %s, cannot send", chat_id) + return SendResult(success=False, error=f"No real room for virtual chat_id {chat_id}") # ── Minimal-Fix: Parse [[BUTTONS:...]] markup from agent response text ── # This allows the agent to request buttons by embedding markup in its @@ -1854,14 +1866,14 @@ class RocketChatAdapter(BasePlatformAdapter): if chat_id.startswith("user:"): # Priority 0: Archivar-Kontext — wenn der Archivar einen thematischen # Zielraum gesetzt hat, geht die Antwort dorthin (Agent-Autonomie). - thematic_target = _THEMATIC_TARGET_ROOM.get() - if thematic_target and thematic_target != _CURRENT_ORIGIN_ROOM.get(): + with _room_context_lock: + ctx = _room_context.get(chat_id, {}) + thematic_target = ctx.get("thematic_target", "") + origin = ctx.get("origin_room", "") + if thematic_target and thematic_target != origin: real_room_id = thematic_target logger.debug("[rocketchat] send via Archivar target: %s → %s", chat_id, real_room_id) - else: - # Priority 1: ContextVar from the message that triggered this turn - origin = _CURRENT_ORIGIN_ROOM.get() - if origin: + elif origin: real_room_id = origin logger.debug("[rocketchat] send via ContextVar: %s → %s", chat_id, real_room_id) else: diff --git a/plugin/archivar/adapter_integration.py b/plugin/archivar/adapter_integration.py index 0c8f46a..586b2bf 100644 --- a/plugin/archivar/adapter_integration.py +++ b/plugin/archivar/adapter_integration.py @@ -93,6 +93,13 @@ except ImportError: from .seed_data import SEED_DATA from .feedback_detector import RoutingWiderspruchDetector, ContradictionResult +# ── _room_context import from adapter.py ───────────────────────────── +# Needed by handle_feedback_response to clear thematic_target on 'stay'. +try: + from adapter import _room_context, _room_context_lock +except ImportError: + from ..adapter import _room_context, _room_context_lock + logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) # Ensure adapter_integration logs are visible by adding a stderr handler @@ -863,7 +870,8 @@ class ArchivarMessageHandler: self, message_id: str, user_id: str, - feedback_type: str + feedback_type: str, + username: str = "", ) -> bool: """ Behandle eine Benutzerantwort auf eine Routing-Entscheidung. @@ -872,14 +880,34 @@ class ArchivarMessageHandler: message_id: ID der gerouteten Nachricht user_id: ID des Benutzers, der das Feedback gegeben hat feedback_type: Art des Feedbacks ("confirm", "stay", "never") + username: Rocket.Chat username (für _room_context-Update bei "stay") Returns: True wenn das Feedback erfolgreich verarbeitet wurde, False bei Fehler """ try: + # ── 'stay': _room_context zurücksetzen ───────────────────── + # Wenn der User "Hier bleiben" klickt, muss der thematic_target + # geleert werden, damit der nächste Send nicht auf den falschen + # (Archivar-vorgeschlagenen) Zielraum fällt. + if feedback_type == "stay" and username: + virtual_chat_id = f"user:{username}" + with _room_context_lock: + ctx = _room_context.setdefault(virtual_chat_id, {}) + ctx["thematic_target"] = "" + # origin_room bleibt unverändert + logger.info( + "Stay-Feedback: _room_context[%s].thematic_target geleert", + virtual_chat_id, + ) + # Prüfe ob die Nachricht existiert if message_id not in self._routed_messages: logger.warning("Feedback for unknown message ID: %s", message_id) + # 'stay' ohne _routed_messages-Eintrag ist trotzdem gültig — + # _room_context wurde oben bereits bereinigt. + if feedback_type == "stay": + return True return False # Hole die geroutete Nachricht diff --git a/plugin/archivar/classifier.py b/plugin/archivar/classifier.py index 7568841..01d14cc 100644 --- a/plugin/archivar/classifier.py +++ b/plugin/archivar/classifier.py @@ -488,7 +488,8 @@ class IntentClassifier: Intent-Kategorien. Uses ``LLMClient.generate()`` for free-form output. Used by the router for LLM_ROOM_PROMPT. - Async because OllamaLLMClient.generate() is async. + Uses ``asyncio.to_thread()`` because ``LLMClient.generate()`` is + synchronous. Args: prompt: The complete prompt to send. @@ -499,7 +500,8 @@ class IntentClassifier: try: if not self._llm_client or not self._llm_enabled: return None - return await self._llm_client.generate(prompt) + import asyncio + return await asyncio.to_thread(self._llm_client.generate, prompt) except Exception as e: logger.warning("LLM raw call failed: %s", e) return None diff --git a/plugin/archivar/config.py b/plugin/archivar/config.py index d913f7c..9d19559 100644 --- a/plugin/archivar/config.py +++ b/plugin/archivar/config.py @@ -14,7 +14,7 @@ from typing import Dict # ── Ollama-Konfiguration ──────────────────────────────────────────────────── OLLAMA_CONFIG: dict = { - "base_url": os.getenv("OLLAMA_BASE_URL", "http://localhost:11434"), + "base_url": os.getenv("ARCHIVAR_EMBEDDING_BASE_URL", os.getenv("OLLAMA_BASE_URL", "http://localhost:11434")), "model": "nomic-embed-text", "timeout": 10.0, # Sekunden — empirisch: Ø 2.4s, Cold-Start bis 7.8s "embedding_dim": 768, # nomic-embed-text produziert 768-dimensionale Vektoren @@ -228,9 +228,9 @@ Enthält Entscheidungen wie "immer im Raum bleiben" oder "nie routen". # Bei mittlerem Score greift der Keyword-Booster zur Konfliktlösung. # Bei niedrigem Score fällt der Flow an den Embedding-Vorfilter + LLM durch. -FAISS_AUTO_ROUTE: float = 0.70 +FAISS_AUTO_ROUTE: float = 0.55 """FAISS-Score-Schwelle für automatisches Routing ohne LLM. -Nachrichten mit FAISS-Score >= 0.70 (nach Keyword-Boost) werden direkt +Nachrichten mit FAISS-Score >= 0.55 (nach Keyword-Boost) werden direkt geroutet — kein LLM-Aufruf nötig. Spart ~2.4s Latenz pro Nachricht.""" FAISS_MIN_SCORE: float = 0.50