diff --git a/docs/archivar-user-flow-c.md b/docs/archivar-user-flow-c.md new file mode 100644 index 0000000..c23a4d5 --- /dev/null +++ b/docs/archivar-user-flow-c.md @@ -0,0 +1,278 @@ +# Archivar User-Flow Fix "C" — Architektur-Skizze + +> **Status:** Entwurf → wartet auf Lead-Review (Bernd) +> **Datum:** 08. Juni 2026 +> **Projekt:** Rocket.Chat Plugin +> **Typ:** Architektur-Änderung (adapter.py, kein Eingriff in Classifier/Router) + +--- + +## 1. Problembeschreibung + +Der Archivar routet die **Antwort des Agenten**, nicht die Nachricht des Users. Wenn eine DM-Nachricht Keywords eines Projektraums enthält, setzt `_CURRENT_ORIGIN_ROOM` den Zielraum — die Agent-Antwort verlässt den DM und erscheint im Projektraum. Der User erhält nur eine Kurznotiz "Ich antworte im Zielraum" und muss dem Agenten hinterherjagen. + +**Symptome (08.06.2026):** +- Andreas schreibt "startObsidian + projekt sync" im DM → Antwort landet im #BAT-Team +- Andreas fragt im DM nach dem RC-Plugin → Antwort landet im #Rocketchat-Plugin +- ":: Archivar Sperre" funktioniert nur einmalig, nicht Session-übergreifend +- Kein Flow für "Hier bleiben" — der User ist der Flüchtende, nicht der Entscheider + +**Root Cause:** `adapter.py` Zeile 635: `_CURRENT_ORIGIN_ROOM.set(decision.target_room)` leitet die **Antwort** um. Der Archivar müsste die **Nachricht kopieren** — nicht die Antwort umleiten. + +--- + +## 2. Lösungsansatz + +### Prinzip + +Die Antwort des Agenten bleibt **IMMER** im Ursprungsraum. Der Archivar entscheidet nur, ob die Nachricht zusätzlich in einen Zielraum kopiert wird. + +### Zwei Nachrichtentypen + +| Typ | Erkennung | Archivar-Verhalten | +|---|---|---| +| **Thematische Frage** | Keine Imperative/Direktansprache | **Silent Copy**: Nachricht in Zielraum kopieren. Hinweis im Ursprungsraum. Keine Buttons. | +| **Auftrag** | Enthält Imperative: "bitte", "erstelle", "mach", etc. | **Buttons**: [Ja, rüberkopieren] [Hier bleiben] [Generell hier bleiben] | + +### DM-Sonderregel + +DM-Aufträge werden **NIE** geroutet. Der User hat bewusst den privaten Kanal gewählt. Nur thematische Fragen aus DMs können als Silent Copy in Projekt-Räume gespiegelt werden. + +--- + +## 3. Datenfluss-Diagramm + +``` +User sendet Nachricht + │ + ▼ +┌───────────────────┐ +│ adapter.py │ +│ _process_incoming │ +└───────┬───────────┘ + │ + ▼ + room_type == "d" ? + │ + ┌────┴────┐ + │ JA │ NEIN + ▼ ▼ +┌──────────┐ ┌──────────────┐ +│ _is_auftrag? │ │ Archivar.route()│ +└─┬────┬───┘ └──────┬───────┘ + │JA │NEIN │ + ▼ ▼ ▼ +┌────┐┌──────────┐┌──────────────┐ +│BLEIB││Archivar ││target != │ +│(DM) ││.route() ││origin? │ +└────┘└────┬─────┘└──┬──────┬───┘ + │ │JA │NEIN + ▼ ▼ ▼ + target != origin? ┌───────────┐ ┌────┐ + ┌──┬──┐ │_is_auftrag?│ │BLEIB│ + │JA│NEIN └──┬────┬───┘ └────┘ + ▼ ▼ │JA │NEIN +┌─────┐┌────┐ ▼ ▼ +│Silent││BLEIB│ ┌──────────┐┌──────────┐ +│Copy │└────┘ │Buttons: ││Silent │ +│+Hinweis│ │[Ja][Hier] ││Copy │ +└─────────┘ │[Generell] ││+Hinweis │ + └──────────┘└──────────┘ + +LEGENDE: + BLEIB = _CURRENT_ORIGIN_ROOM bleibt auf room_id (Antwort hier) + Silent Copy = Nachricht per REST in Zielraum kopieren + Buttons = rocketchat_send mit 3 Buttons +``` + +--- + +## 4. Code-Änderungen + +Alle Änderungen in **einer Datei**: `plugin/adapter.py` + +### 4.1 Neue Heuristik: `_is_auftrag()` (vor `_process_incoming` einfügen) + +```python +# ── Auftrag-Erkennung (für User-Flow C) ──────────────────────────── +_AUFTRAG_KEYWORDS: list = [ + "bitte", "erstell", "mach", "änder", "konfigurier", + "schreib", "bau", "implementier", "test", "deploy", + "start", "stopp", "analysier", "prüf", "untersuch", + "beheb", "fix", "korrigier", "optimier", "erweiter", + "füg hinzu", "entfern", "lösch", "verschieb", + "generier", "kompilier", "installier", +] + +def _is_auftrag(text: str) -> bool: + """Heuristik: Enthält die Nachricht Imperative oder direkte Ansprache?""" + t = text.lower() + for kw in _AUFTRAG_KEYWORDS: + if kw in t: + return True + # Direkte Anrede + if any(t.startswith(p) for p in ("bernd", "rainer", "miguel", "finn", "don")): + return True + return False +``` + +### 4.2 `_process_incoming()` — Neue Routing-Logik (Zeilen ~606-654 ersetzen) + +**ALT (Zeilen 606-654):** +```python +# ── Archivar-Klassifikation ── +category = "" +decision = None +try: + if is_button_response or room_id in self._rooms_with_pending_questions: + ... + else: + decision = await self.archivar.handle_and_forward(text, ...) + +# Forward-Antwort-Umleitung +if (decision and hasattr(decision, 'target_room') and decision.target_room + and decision.target_room != room_id + and not getattr(decision, 'is_unrouteable', False)): + _CURRENT_ORIGIN_ROOM.set(decision.target_room) + try: + note_text = f"Ich antworte im {getattr(decision, 'matched_room_name', None) or 'Zielraum'}." + self.rest.post_message(room_id, note_text) + ... +``` + +**NEU:** +```python +# ── Archivar-Klassifikation (User-Flow C) ────────────────────────── +category = "" +decision = None +is_auftrag = _is_auftrag(text) + +try: + if is_button_response or room_id in self._rooms_with_pending_questions: + if not is_button_response: + logger.debug("[rocketchat] Room %s had pending question — Archivar bypassed", room_id) + self._rooms_with_pending_questions.discard(room_id) + elif room_id in getattr(self, '_sticky_rooms', {}): + # Session-Marker "Generell hier bleiben" — Archivar komplett überspringen + logger.debug("[rocketchat] Room %s is sticky — Archivar bypassed", room_id[:8]) + elif room_type == "d" and is_auftrag: + # DM-Aufträge NIE routen — User hat bewusst privaten Kanal gewählt + logger.debug("[rocketchat] DM-Auftrag von %s — kein Routing", username) + else: + # Nur classify_and_route (KEIN handle_and_forward — wir kopieren manuell) + decision = await self.archivar.classify_and_route(text, origin_room_id=room_id) + if decision and decision.category: + category = decision.category +except Exception as e: + logger.debug("[rocketchat] Archivar classification skipped: %s", e) + +# ── User-Flow C: Nachricht kopieren, Antwort im Ursprungsraum behalten ── +# _CURRENT_ORIGIN_ROOM wird NIE auf den Zielraum gesetzt. +# Die Agent-Antwort bleibt IMMER im Ursprungsraum. +if (decision and hasattr(decision, 'target_room') and decision.target_room + and decision.target_room != room_id + and not getattr(decision, 'is_unrouteable', False)): + + target_name = getattr(decision, 'matched_room_name', None) or 'Zielraum' + + if is_auftrag: + # Typ 2: Buttons anzeigen + note = ( + f"Dein Auftrag passt thematisch besser in **{target_name}**.\n" + f"Soll ich den Auftrag dorthin kopieren und dort abarbeiten?" + ) + # Button-Payload für spätere Verarbeitung + self._pending_move_requests[msg_id] = { + "text": text, + "origin_room": room_id, + "target_room": decision.target_room, + "target_name": target_name, + } + await self._send_buttons(room_id, note, msg_id, + buttons=["→ Ja, rüberkopieren", "Hier bleiben", "Generell hier bleiben"]) + else: + # Typ 1: Silent Copy + self.rest.post_message(decision.target_room, + f"*(Thema passt zu {target_name} — von @{username})*\n{text}") + note = f"📋 Thema passt zu **{target_name}** — ich hab's dort dokumentiert." + self.rest.post_message(room_id, note) + +# Wenn kein Forwarding: _CURRENT_ORIGIN_ROOM bleibt auf room_id +if not (decision and hasattr(decision, 'target_room') and decision.target_room + and decision.target_room != room_id + and not getattr(decision, 'is_unrouteable', False)): + _CURRENT_ORIGIN_ROOM.set(room_id) +``` + +### 4.3 Neue `_send_buttons()` Methode + +```python +async def _send_buttons(self, room_id: str, text: str, question_id: str, + buttons: list) -> None: + """Sendet eine Nachricht mit Buttons im Zielraum.""" + # Button-Template an den Gateway delegieren — wir nutzen rocketchat_send + # des Agenten. Da wir im Adapter sind, bauen wir die Buttons direkt. + from gateway.platforms.base import MessageEvent, MessageType + # ... (Implementierung siehe bestehende Button-Logik in adapter.py send()) +``` + +### 4.4 Button-Handling in `_process_incoming()` + +```python +# Button-Antwort auf move-request erkennen +if msg_id in getattr(self, '_pending_move_requests', {}): + move_req = self._pending_move_requests.pop(msg_id) + choice = text.strip() + + if "rüberkopieren" in choice.lower() or choice == "→ Ja, rüberkopieren": + # Auftrag in Zielraum kopieren + _CURRENT_ORIGIN_ROOM setzen + self.rest.post_message(move_req["target_room"], + f"*(Auftrag von @{username}, hierher kopiert)*\n{move_req['text']}") + _CURRENT_ORIGIN_ROOM.set(move_req["target_room"]) + self.rest.post_message(room_id, f"✅ Auftrag nach **{move_req['target_name']}** kopiert — ich arbeite ihn dort ab.") + + elif "hier bleiben" in choice.lower() or choice == "Hier bleiben": + _CURRENT_ORIGIN_ROOM.set(room_id) + self.rest.post_message(room_id, "👍 Bleiben hier — ich kümmer mich drum.") + + elif "generell" in choice.lower() or choice == "Generell hier bleiben": + if not hasattr(self, '_sticky_rooms'): + self._sticky_rooms = {} + self._sticky_rooms[room_id] = time.time() + _CURRENT_ORIGIN_ROOM.set(room_id) + self.rest.post_message(room_id, "🔒 Verstanden — dieser Raum wird nicht mehr automatisch geroutet. (Gilt bis zum nächsten Gateway-Neustart)") +``` + +### 4.5 `__init__` erweitern (neue Dicts) + +In `RocketChatAdapter.__init__()` nach Zeile 422 (`self.archivar = ...`) einfügen: + +```python +# User-Flow C: Move-Requests + Sticky Rooms +self._pending_move_requests: Dict[str, dict] = {} +self._sticky_rooms: Dict[str, float] = {} # room_id → timestamp +``` + +--- + +## 5. Testfälle + +| # | Eingabe | Raum | Erwartetes Verhalten | +|---|---|---|---| +| 1 | "Wie ist der Stand des RC-Plugins?" | DM | Silent Copy nach #Rocketchat-Plugin. Antwort im DM mit Hinweis. | +| 2 | "Bitte erstelle einen Exchange-Adapter" | #BAT-Team | Buttons im #BAT-Team. Bei "Ja" → Kopie in Zielraum + Antwort dort. | +| 3 | "Bitte konfiguriere den Gateway" | DM | **Kein Routing.** DM-Auftrag bleibt im DM. Keine Buttons, keine Kopie. | +| 4 | "Was ist die IP von Susi?" | #Rocketchat-Plugin | Silent Copy in passenden Raum (Catch-All wenn unsicher). Antwort hier. | +| 5 | Button "Generell hier bleiben" | #BAT-Team | _sticky_rooms gesetzt. Nächste Nachricht in #BAT-Team → Archivar übersprungen. | +| 6 | "docker compose ps" | DM | FAKT → doc_store (kein Routing, keine Antwort-Weiterleitung). | +| 7 | Gateway-Neustart | — | _sticky_rooms zurückgesetzt. "Generell hier bleiben" überlebt Neustart nicht. | + +--- + +## 6. Deployment-Plan + +1. **Miguel** implementiert die Änderungen in `plugin/adapter.py` +2. **Rainer** reviewt den Code gegen diese Skizze (Quality Gate §3.2) +3. **Don** testet auf `.101`: Gateway-Start, Test-Nachrichten in DM + Projekt-Räumen, Button-Flow +4. **Don** deployt via `install.sh` auf `.101` (und Susi-VPS falls nötig) +5. **Bernd** (Lead) gibt finale Freigabe diff --git a/plugin/adapter.py b/plugin/adapter.py index 386631f..134fc29 100644 --- a/plugin/adapter.py +++ b/plugin/adapter.py @@ -380,6 +380,28 @@ class DDPClient: return False + + +# ── Auftrag-Erkennung (User-Flow C) ──────────────────────────────────── +_AUFTRAG_KEYWORDS: list = [ + "bitte", "erstell", "mach", "änder", "konfigurier", + "schreib", "bau", "implementier", "test", "deploy", + "start", "stopp", "analysier", "prüf", "untersuch", + "beheb", "fix", "korrigier", "optimier", "erweiter", + "füg hinzu", "entfern", "lösch", "verschieb", + "generier", "kompilier", "installier", +] + + +def _is_auftrag(text: str) -> bool: + """Heuristik: Enthält die Nachricht Imperative oder direkte Ansprache?""" + t = text.lower() + for kw in _AUFTRAG_KEYWORDS: + if kw in t: + return True + return False + + class RocketChatAdapter(BasePlatformAdapter): HEALTH_CHECK_INTERVAL = 60.0 # seconds HEALTH_SILENT_LIMIT = 300.0 # 5 min without any server activity = force reconnect @@ -407,6 +429,12 @@ class RocketChatAdapter(BasePlatformAdapter): # Key: "user:", Value: list of real room_ids for that user. # Built during connect() from REST get_rooms. self._user_rooms: Dict[str, List[str]] = {} + # Rooms where the agent has posted a question with buttons. + # Used to keep the response in the same room — no Archivar routing, + # no catch-all forwarding. Removed after the next user message from + # that room (on the assumption that the response IS the button answer). + # No timers, no cleanup — just a simple set. + self._rooms_with_pending_questions: set = set() # Health-check state self._last_server_activity = 0.0 # ts of last DDP ping/pong or message self._health_check_timer: Optional[threading.Timer] = None @@ -414,6 +442,9 @@ class RocketChatAdapter(BasePlatformAdapter): self._running = False # Archivar: Embedding-basierte Nachrichten-Klassifikation self.archivar = ArchivarMessageHandler(send_callback=self._send_via_archivar) + # User-Flow C: Move-Requests + Sticky Rooms + self._pending_move_requests: Dict[str, dict] = {} + self._sticky_rooms: Dict[str, float] = {} # room_id → timestamp async def connect(self) -> bool: if not self.base_url or not self.user or not self.password: @@ -510,16 +541,21 @@ class RocketChatAdapter(BasePlatformAdapter): if not isinstance(msg_obj, dict): return - # Check if this is a button click response by looking for specific fields + # Check if this is a button click response by looking for specific fields. + # TWO detection paths: + # 1. Native Rocket.Chat button events (triggerId + actions + triggerSender + payload) + # 2. In-chat button responses via msg_in_chat_window, which arrive as regular + # text messages containing a question_id::choice payload (e.g. "bypass_001::Ja"). + text = msg_obj.get("msg", "") is_button_response = ( - msg_obj.get("triggerId") and - msg_obj.get("actions") and - msg_obj.get("params", {}).get("triggerSender") and - msg_obj.get("params", {}).get("payload") + (msg_obj.get("triggerId") and + msg_obj.get("actions") and + msg_obj.get("params", {}).get("triggerSender") and + msg_obj.get("params", {}).get("payload")) + or "::" in text ) msg_id = msg_obj.get("_id", "") - text = msg_obj.get("msg", "") room_id = msg_obj.get("rid", "") user_info = msg_obj.get("u", {}) username = (user_info.get("username", "") or "").lower() # normalize case @@ -592,38 +628,90 @@ class RocketChatAdapter(BasePlatformAdapter): await self._process_onboarding_response(text, room_id) return # Nachricht wurde verarbeitet, keine weitere Verarbeitung nötig - # ── Archivar-Klassifikation ────────────────────────────────── - # Klassifiziere die Nachricht und reichere den Context an + # ── Archivar-Klassifikation (User-Flow C) ────────────────────────── + # Klassifiziere die Nachricht und entscheide über Copy/Routing. + # Die Antwort des Agenten bleibt IMMER im Ursprungsraum. + # Nur die Nachricht selbst wird — nach User-Entscheidung — kopiert. category = "" decision = None + is_auftrag = _is_auftrag(text) + try: - # Button clicks and button responses are ALWAYS direct replies - # to an agent question — they carry a question_id::choice payload - # and must never be routed through the Archivar. Routing them - # risks landing a one-character "A" in the catch-all room where - # the agent sees it without the question context. - if not is_button_response: - decision = await self.archivar.handle_and_forward(text, origin_room_id=room_id, message_id=msg_id) + if is_button_response or room_id in self._rooms_with_pending_questions: + if not is_button_response: + logger.debug("[rocketchat] Room %s had pending question — Archivar bypassed", room_id) + self._rooms_with_pending_questions.discard(room_id) + elif room_id in self._sticky_rooms: + logger.debug("[rocketchat] Room %s is sticky — Archivar bypassed", room_id[:8]) + elif room_type == "d" and is_auftrag: + logger.debug("[rocketchat] DM-Auftrag von %s — kein Routing", username) + else: + decision = await self.archivar.classify_and_route(text, origin_room_id=room_id) if decision and decision.category: category = decision.category - else: - logger.debug("[rocketchat] Button response — Archivar bypassed for %s", text[:40]) except Exception as e: logger.debug("[rocketchat] Archivar classification skipped: %s", e) - # Forward-Antwort-Umleitung - # Nur umleiten, wenn der Zielraum subscribed ist (nicht unrouteable). - # is_unrouteable=True bedeutet: target_room ist nicht in den Bot-Subscriptions; - # dann im Ursprungsraum bleiben und dort antworten. + # ── User-Flow C: Nachricht kopieren, Antwort IMMER hier ──────── + # _CURRENT_ORIGIN_ROOM wird NIE auf den Zielraum gesetzt. + # Die Agent-Antwort bleibt im Ursprungsraum. Nur die Nachricht + # wird kopiert — mit User-Entscheidung bei Aufträgen. + forwarded = False if (decision and hasattr(decision, 'target_room') and decision.target_room and decision.target_room != room_id and not getattr(decision, 'is_unrouteable', False)): - _CURRENT_ORIGIN_ROOM.set(decision.target_room) - try: - note_text = f"Ich antworte im {getattr(decision, 'matched_room_name', None) or 'Zielraum'}." - self.rest.post_message(room_id, note_text) - except Exception as e: - logger.debug("[rocketchat] Failed to send forward note: %s", e) + + target_name = getattr(decision, 'matched_room_name', None) or 'Zielraum' + + if is_auftrag: + # Typ 2: Buttons — User entscheidet + note = ( + f"Dein Auftrag passt thematisch besser in **{target_name}**.\n" + f"Soll ich den Auftrag dorthin kopieren und dort abarbeiten?" + ) + self._pending_move_requests[msg_id] = { + "text": text, + "origin_room": room_id, + "target_room": decision.target_room, + "target_name": target_name, + "username": username, + } + self.rest.post_message(room_id, note) + # Kein Forwarding — auf Button-Antwort warten + forwarded = True + else: + # Typ 1: Silent Copy — Nachricht in Zielraum kopieren + self.rest.post_message(decision.target_room, + f"*(Thema passt zu {target_name} — von @{username})*\n{text}") + note = f"📋 Thema passt zu **{target_name}** — ich hab's dort dokumentiert." + self.rest.post_message(room_id, note) + + # Button-Antwort auf move-request? + if msg_id in self._pending_move_requests: + move_req = self._pending_move_requests.pop(msg_id) + choice = text.strip().lower() + + if "rüberkopieren" in choice: + # Auftrag in Zielraum kopieren + Antwort dorthin + self.rest.post_message(move_req["target_room"], + f"*(Auftrag von @{move_req['username']}, hierher kopiert)*\n{move_req['text']}") + _CURRENT_ORIGIN_ROOM.set(move_req["target_room"]) + forwarded = True + + elif "generell" in choice: + self._sticky_rooms[room_id] = time.time() + self.rest.post_message(room_id, "🔒 Verstanden — dieser Raum wird nicht mehr automatisch geroutet. (Gilt bis zum nächsten Gateway-Neustart)") + + else: + # "Hier bleiben" — Default + self.rest.post_message(room_id, "👍 Bleiben hier.") + + # Nach Button-Antwort: nicht als normale Nachricht verarbeiten + return + + # ── _CURRENT_ORIGIN_ROOM setzen ────────────────────────────────── + if not forwarded: + _CURRENT_ORIGIN_ROOM.set(room_id) # ── Virtual Room Translation ───────────────────────────────── # Replace room-based chat_id with user-based virtual chat_id. @@ -632,12 +720,7 @@ class RocketChatAdapter(BasePlatformAdapter): # #Project-Chat: room_id=XYZ789 → chat_id="user:alice" # Both get the same session key. virtual_chat_id = f"user:{username}" - # Track the REAL room for send() to route the response back - # Only set if no forwarding occurred (or forwarding was unrouteable) - if not (decision and hasattr(decision, 'target_room') and decision.target_room - and decision.target_room != room_id - and not getattr(decision, 'is_unrouteable', False)): - _CURRENT_ORIGIN_ROOM.set(room_id) + # _CURRENT_ORIGIN_ROOM wurde bereits oben im User-Flow-C gesetzt # Ensure this user→room mapping is recorded for proaktive sends if virtual_chat_id not in self._user_rooms: @@ -1053,6 +1136,14 @@ class RocketChatAdapter(BasePlatformAdapter): success = self.rest.post_message(real_room_id, content, attachments=attachments) if success: + # If this message has buttons, mark the room so the next user + # message from here stays put (no Archivar routing). Button + # responses must be answered in the same room the question was + # asked, otherwise the user sees "Ich antworte im Zielraum" + # and the agent loses context. + if attachments: + self._rooms_with_pending_questions.add(real_room_id) + logger.debug("[rocketchat] Room %s marked for button response", real_room_id) return SendResult(success=True, message_id=str(int(time.time() * 1000))) return SendResult(success=False, error="chat.postMessage failed")