From 379140d2645b1a38f4737c11485c59dfa0687d33 Mon Sep 17 00:00:00 2001 From: "Bernd (Hermes)" Date: Thu, 13 Aug 2026 07:00:12 +0200 Subject: [PATCH] =?UTF-8?q?fix(P-060-followup):=20entferne=20alle=20V8.6?= =?UTF-8?q?=20PresenceEngine=20Methodenaufrufe=20=E2=80=94=20V10=20verwalt?= =?UTF-8?q?et=20Counter=20via=20Hooks?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- plugin/adapter.py | 2726 ++++++++++++++++++++++----------------------- 1 file changed, 1353 insertions(+), 1373 deletions(-) diff --git a/plugin/adapter.py b/plugin/adapter.py index 89f14f2..229850b 100644 --- a/plugin/adapter.py +++ b/plugin/adapter.py @@ -2214,1438 +2214,1418 @@ class RocketChatAdapter(BasePlatformAdapter): virtual_chat_id = f"user:{username}" _set_room_context_origin(virtual_chat_id, room_id) - # ── V8.6 P1a: PresenceEngine — mark_busy_started (Honeymoon-Timer) ── - # Graceful degradation: wenn _presence_engine nicht existiert - # (z.B. in Tests die __new__ statt __init__ verwenden), skip. _has_presence = hasattr(self, '_presence_engine') and self._presence_engine is not None - if _has_presence: - self._presence_engine.mark_busy_started(room_name=room_name) - # B12: Background-Tasks zählen — Heartbeat-Message aktivieren - self._presence_engine.increment_background_tasks() - logger.info("[presence] mark_busy_started (room=%s)", room_name) - try: - # ── R5: Inline-Command-Erkennung (VOR Onboarding + Hermes-Dispatch) ── - # ::-Befehle und natürliche Hilfeseiten-Anfragen müssen VOR dem - # generischen Hermes-Agent-Onboarding erkannt werden. - inline_handled = await self._handle_inline_command(routing_text, room_id, room_name, username) - if inline_handled: - logger.debug("[rocketchat] R5: Inline-Command verarbeitet — skipping agent dispatch") - routing_counter.increment('inline_command_handled') - logger.info("ROUTING BYPASS: reason=inline_command_handled, origin_room=%s", room_id) + # ── R5: Inline-Command-Erkennung (VOR Onboarding + Hermes-Dispatch) ── + # ::-Befehle und natürliche Hilfeseiten-Anfragen müssen VOR dem + # generischen Hermes-Agent-Onboarding erkannt werden. + inline_handled = await self._handle_inline_command(routing_text, room_id, room_name, username) + if inline_handled: + logger.debug("[rocketchat] R5: Inline-Command verarbeitet — skipping agent dispatch") + routing_counter.increment('inline_command_handled') + logger.info("ROUTING BYPASS: reason=inline_command_handled, origin_room=%s", room_id) + return + # ── Ende R5 Inline-Command-Erkennung ──────────────────────────────── + + # ── B5v6.5: Conversation History — User-Nachricht aufzeichnen ── + # P1: display_text (mit Quote) für Agent/History, damit kein Kontext verloren geht + if _MULTIROOM() and self._conversation_history is not None: + await self._conversation_history.add(room_id, "user", display_text) + + # V8.1 P4: MultiRoomContext-Ring — Thema aus Nachricht extrahieren + if _MULTIROOM() and self._multiroom_context is not None: + # Extrahiere ein kurzes Topic aus der Nachricht (erste 80 Zeichen) + # P1: routing_text für Topic-Extraktion (ohne Quote) + topic = routing_text[:80].replace("\n", " ").strip() + if topic: + await self._multiroom_context.add(room_id, room_name, topic) + + # ── 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("") + + # ── A1b: Lazy-Onboarding-Check (Fallback-Pfad) ──────────────────── + # Wenn eine Nachricht aus einem Raum kommt, der nicht in room-map.json + # steht, und kein Onboarding aktiv ist → Onboarding triggern. + # Dies fängt Fälle ab, wo das DDP-Event nicht angekommen ist. + # P0-4: room_type kann "unknown" sein wenn der Raum nicht in _room_info + # ist (z.B. nach Reconnect). Der lazy_onboarding_check filtert selbst + # DM-Räume und excluded rooms — wir müssen hier nur DM ausschließen. + if ( + _MULTIROOM() + and self.archivar is not None + and not self._is_onboarding_phase_active()[0] + and room_type != "d" # P0-4: Nur DM ausschließen, "unknown" durchlassen + ): + lazy_result = self.archivar.lazy_onboarding_check( + room_id=room_id, + room_name=room_name, + room_type=room_type, + ) + if lazy_result is not None: + logger.info( + "[rocketchat] A1b: Lazy-Onboarding getriggert — " + "unbekannter Raum: room=%s, name=%s", + room_id[:12], room_name, + ) + await self._start_onboarding([lazy_result]) + # Nachricht nicht weiter verarbeiten — Onboarding läuft jetzt + routing_counter.increment('lazy_onboarding_triggered') + logger.info("ROUTING BYPASS: reason=lazy_onboarding_triggered, origin_room=%s", room_id) return - # ── Ende R5 Inline-Command-Erkennung ──────────────────────────────── + # ── Ende A1b Lazy-Onboarding ───────────────────────────────────── - # ── B5v6.5: Conversation History — User-Nachricht aufzeichnen ── - # P1: display_text (mit Quote) für Agent/History, damit kein Kontext verloren geht - if _MULTIROOM() and self._conversation_history is not None: - await self._conversation_history.add(room_id, "user", display_text) - - # V8.1 P4: MultiRoomContext-Ring — Thema aus Nachricht extrahieren - if _MULTIROOM() and self._multiroom_context is not None: - # Extrahiere ein kurzes Topic aus der Nachricht (erste 80 Zeichen) - # P1: routing_text für Topic-Extraktion (ohne Quote) - topic = routing_text[:80].replace("\n", " ").strip() - if topic: - await self._multiroom_context.add(room_id, room_name, topic) - - # ── 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("") - - # ── A1b: Lazy-Onboarding-Check (Fallback-Pfad) ──────────────────── - # Wenn eine Nachricht aus einem Raum kommt, der nicht in room-map.json - # steht, und kein Onboarding aktiv ist → Onboarding triggern. - # Dies fängt Fälle ab, wo das DDP-Event nicht angekommen ist. - # P0-4: room_type kann "unknown" sein wenn der Raum nicht in _room_info - # ist (z.B. nach Reconnect). Der lazy_onboarding_check filtert selbst - # DM-Räume und excluded rooms — wir müssen hier nur DM ausschließen. - if ( - _MULTIROOM() - and self.archivar is not None - and not self._is_onboarding_phase_active()[0] - and room_type != "d" # P0-4: Nur DM ausschließen, "unknown" durchlassen - ): - lazy_result = self.archivar.lazy_onboarding_check( - room_id=room_id, - room_name=room_name, - room_type=room_type, + # ── Thema B: Onboarding-Guard — Plugin-onboarding vor generischem Hermes-onboarding ── + # Wenn Onboarding aktiv ist und die Nachricht aus einem Raum kommt, + # der NICHT in der room-map.json steht und NICHT der Operator-DM ist, + # dann die Nachricht abfangen. Verhindert dass das generische + # Hermes-Agent-Onboarding (Profile, Skills, Cronjobs) das + # Plugin-Onboarding (Raum-Interview) übersteuert. + if ( + _MULTIROOM() + and self.archivar is not None + and self._is_onboarding_phase_active()[0] + and room_type != "d" + ): + # P-054: operator_room_id mit Fallback-Kette + operator_room = self._onboarding_state.get("operator_room_id", "") + if not operator_room: + sm = getattr(self, '_onboarding_sm', None) + if sm is not None: + operator_room = getattr(sm._data, 'operator_room_id', '') or '' + if not operator_room: + dm_rooms = [rid for rid, info in self._room_info.items() + if info.get("type") == "d"] + if len(dm_rooms) == 1: + operator_room = dm_rooms[0] + # Prüfe ob der Raum in der room-map.json steht + room_in_map = ( + self.archivar._room_map is not None + and room_id in self.archivar._room_map.rooms + ) + if not room_in_map and room_id != operator_room: + # Raum ist unbekannt und Onboarding läuft → Nachricht abfangen + logger.info( + "[rocketchat] Thema B: Onboarding-Guard — Nachricht aus unbekanntem Raum " + "während Onboarding abgefangen: room=%s, name=%s", + room_id[:12], room_name, ) - if lazy_result is not None: - logger.info( - "[rocketchat] A1b: Lazy-Onboarding getriggert — " - "unbekannter Raum: room=%s, name=%s", - room_id[:12], room_name, - ) - await self._start_onboarding([lazy_result]) - # Nachricht nicht weiter verarbeiten — Onboarding läuft jetzt - routing_counter.increment('lazy_onboarding_triggered') - logger.info("ROUTING BYPASS: reason=lazy_onboarding_triggered, origin_room=%s", room_id) - return - # ── Ende A1b Lazy-Onboarding ───────────────────────────────────── - - # ── Thema B: Onboarding-Guard — Plugin-onboarding vor generischem Hermes-onboarding ── - # Wenn Onboarding aktiv ist und die Nachricht aus einem Raum kommt, - # der NICHT in der room-map.json steht und NICHT der Operator-DM ist, - # dann die Nachricht abfangen. Verhindert dass das generische - # Hermes-Agent-Onboarding (Profile, Skills, Cronjobs) das - # Plugin-Onboarding (Raum-Interview) übersteuert. - if ( - _MULTIROOM() - and self.archivar is not None - and self._is_onboarding_phase_active()[0] - and room_type != "d" - ): - # P-054: operator_room_id mit Fallback-Kette - operator_room = self._onboarding_state.get("operator_room_id", "") - if not operator_room: - sm = getattr(self, '_onboarding_sm', None) - if sm is not None: - operator_room = getattr(sm._data, 'operator_room_id', '') or '' - if not operator_room: - dm_rooms = [rid for rid, info in self._room_info.items() - if info.get("type") == "d"] - if len(dm_rooms) == 1: - operator_room = dm_rooms[0] - # Prüfe ob der Raum in der room-map.json steht - room_in_map = ( - self.archivar._room_map is not None - and room_id in self.archivar._room_map.rooms + await self._post_message_with_retry( + room_id, + "🔄 Ich richte mich gerade ein — einen Moment bitte. " + "Das Onboarding-Interview läuft in deinem DM-Kanal. " + "Sobald ich fertig bin, bin ich für dich da!" ) - if not room_in_map and room_id != operator_room: - # Raum ist unbekannt und Onboarding läuft → Nachricht abfangen - logger.info( - "[rocketchat] Thema B: Onboarding-Guard — Nachricht aus unbekanntem Raum " - "während Onboarding abgefangen: room=%s, name=%s", - room_id[:12], room_name, - ) - await self._post_message_with_retry( - room_id, - "🔄 Ich richte mich gerade ein — einen Moment bitte. " - "Das Onboarding-Interview läuft in deinem DM-Kanal. " - "Sobald ich fertig bin, bin ich für dich da!" - ) - routing_counter.increment('onboarding_guard_blocked') - logger.info("ROUTING BYPASS: reason=onboarding_guard_blocked, origin_room=%s", room_id) - return - # ── Ende Thema B Onboarding-Guard ──────────────────────────────────── + routing_counter.increment('onboarding_guard_blocked') + logger.info("ROUTING BYPASS: reason=onboarding_guard_blocked, origin_room=%s", room_id) + return + # ── Ende Thema B Onboarding-Guard ──────────────────────────────────── - # ── CLARIFY Response Handling ─────────────────────────────────── - # Handle CLARIFY button responses: CLARIFY:: or CLARIFY::other - # V8.2.1 A2: Handle ARCHIVAR_CLARIFY (Nachklärung) responses - is_archivar_clarify = text.startswith("ARCHIVAR_CLARIFY:") if text else False - if is_clarify_response and text.startswith("CLARIFY:"): - routing_counter.increment('clarify_answer_bypass') - logger.info("ROUTING BYPASS: reason=clarify_answer_bypass, origin_room=%s", room_id) - try: - if "::" in text: - # Neues Format: CLARIFY::: (via _build_custom_buttons) - prefix_part, choice = text.split("::", 1) - clarify_id = prefix_part.split(":", 1)[1] - else: - # Altes Format: CLARIFY::other (Other-Button) - parts = text.split(":", 2) - if len(parts) != 3: - logger.debug("[rocketchat] Unrecognized CLARIFY format: %s", text) - logger.debug("[rocketchat] ARCHIVAR-DEBUG: CLARIFY unrecognized format — skipping") - return - _, clarify_id, choice = parts - if choice == "other": - # For "Other" button, enable text capture mode - from tools.clarify_gateway import mark_awaiting_text - mark_awaiting_text(clarify_id) - logger.debug("[rocketchat] Clarify %s: awaiting text response from %s", clarify_id, username) - logger.debug("[rocketchat] ARCHIVAR-DEBUG: CLARIFY other — awaiting text") - # Don't process further - wait for the next text message - return - elif choice.isdigit(): - # Numeric choice → resolve the clarify immediately - idx = int(choice) - resolved_text: Optional[str] = None - try: - from tools.clarify_gateway import _entries as _clarify_entries - entry = _clarify_entries.get(clarify_id) - if entry and entry.choices and 0 <= idx < len(entry.choices): - resolved_text = entry.choices[idx] - except Exception: - resolved_text = None - if resolved_text is None: - # Race: entry vanished. Echo the index. - resolved_text = f"choice {idx + 1}" - # Resolve via gateway and clean up - self._clarify_state.pop(clarify_id, None) - try: - from tools.clarify_gateway import resolve_gateway_clarify - resolved = resolve_gateway_clarify(clarify_id, resolved_text) - if resolved: - logger.info( - "[rocketchat] Clarify %s resolved: %s (session=%s)", - clarify_id, resolved_text[:60], self._clarify_state.get(clarify_id, "?"), - ) - else: - logger.warning("[rocketchat] Clarify %s resolve returned False", clarify_id) - except Exception as exc: - logger.error("[rocketchat] resolve_gateway_clarify failed: %s", exc) - # Don't route to agent — this was a button click - logger.debug("[rocketchat] ARCHIVAR-DEBUG: CLARIFY resolved — skipping") - return - else: - # Unknown token — let it fall through as regular text - logger.warning("[rocketchat] Unknown clarify token: %s", choice) - except Exception as e: - logger.debug("[rocketchat] Error processing CLARIFY response: %s", e) - - # ── V8.2.1 A2: ARCHIVAR_CLARIFY (Nachklärung) Response Handling ── - if is_archivar_clarify: - routing_counter.increment('archivar_clarify_bypass') - logger.info("ROUTING BYPASS: reason=archivar_clarify_bypass, origin_room=%s", room_id) - try: - # Format: ARCHIVAR_CLARIFY: + # ── CLARIFY Response Handling ─────────────────────────────────── + # Handle CLARIFY button responses: CLARIFY:: or CLARIFY::other + # V8.2.1 A2: Handle ARCHIVAR_CLARIFY (Nachklärung) responses + is_archivar_clarify = text.startswith("ARCHIVAR_CLARIFY:") if text else False + if is_clarify_response and text.startswith("CLARIFY:"): + routing_counter.increment('clarify_answer_bypass') + logger.info("ROUTING BYPASS: reason=clarify_answer_bypass, origin_room=%s", room_id) + try: + if "::" in text: + # Neues Format: CLARIFY::: (via _build_custom_buttons) + prefix_part, choice = text.split("::", 1) + clarify_id = prefix_part.split(":", 1)[1] + else: + # Altes Format: CLARIFY::other (Other-Button) parts = text.split(":", 2) - if len(parts) >= 2: - choice = parts[1].strip() - strategie_topics = {"absprache", "planung", "strategie", "entscheidung"} - if choice in strategie_topics: - # Strategie-Thema → Ring-Zustand 'jetzt' (30 Min), KEIN Lernen - if _MULTIROOM() and self.archivar is not None: - self.archivar._state.set_ring_state(room_id, "jetzt", ttl_minutes=30) + if len(parts) != 3: + logger.debug("[rocketchat] Unrecognized CLARIFY format: %s", text) + logger.debug("[rocketchat] ARCHIVAR-DEBUG: CLARIFY unrecognized format — skipping") + return + _, clarify_id, choice = parts + if choice == "other": + # For "Other" button, enable text capture mode + from tools.clarify_gateway import mark_awaiting_text + mark_awaiting_text(clarify_id) + logger.debug("[rocketchat] Clarify %s: awaiting text response from %s", clarify_id, username) + logger.debug("[rocketchat] ARCHIVAR-DEBUG: CLARIFY other — awaiting text") + # Don't process further - wait for the next text message + return + elif choice.isdigit(): + # Numeric choice → resolve the clarify immediately + idx = int(choice) + resolved_text: Optional[str] = None + try: + from tools.clarify_gateway import _entries as _clarify_entries + entry = _clarify_entries.get(clarify_id) + if entry and entry.choices and 0 <= idx < len(entry.choices): + resolved_text = entry.choices[idx] + except Exception: + resolved_text = None + if resolved_text is None: + # Race: entry vanished. Echo the index. + resolved_text = f"choice {idx + 1}" + # Resolve via gateway and clean up + self._clarify_state.pop(clarify_id, None) + try: + from tools.clarify_gateway import resolve_gateway_clarify + resolved = resolve_gateway_clarify(clarify_id, resolved_text) + if resolved: logger.info( - "[rocketchat] V8.2.1 A2: Strategie-Modus aktiviert — " - "topic=%s, room=%s, ring=jetzt (30 Min)", - choice, room_id[:8], + "[rocketchat] Clarify %s resolved: %s (session=%s)", + clarify_id, resolved_text[:60], self._clarify_state.get(clarify_id, "?"), ) - await self._post_message_with_retry( - room_id, - f"🎯 Verstanden — '{choice}' ist ein Strategie-Thema. " - "Ich bleibe hier und lerne nichts dazu." + else: + logger.warning("[rocketchat] Clarify %s resolve returned False", clarify_id) + except Exception as exc: + logger.error("[rocketchat] resolve_gateway_clarify failed: %s", exc) + # Don't route to agent — this was a button click + logger.debug("[rocketchat] ARCHIVAR-DEBUG: CLARIFY resolved — skipping") + return + else: + # Unknown token — let it fall through as regular text + logger.warning("[rocketchat] Unknown clarify token: %s", choice) + except Exception as e: + logger.debug("[rocketchat] Error processing CLARIFY response: %s", e) + + # ── V8.2.1 A2: ARCHIVAR_CLARIFY (Nachklärung) Response Handling ── + if is_archivar_clarify: + routing_counter.increment('archivar_clarify_bypass') + logger.info("ROUTING BYPASS: reason=archivar_clarify_bypass, origin_room=%s", room_id) + try: + # Format: ARCHIVAR_CLARIFY: + parts = text.split(":", 2) + if len(parts) >= 2: + choice = parts[1].strip() + strategie_topics = {"absprache", "planung", "strategie", "entscheidung"} + if choice in strategie_topics: + # Strategie-Thema → Ring-Zustand 'jetzt' (30 Min), KEIN Lernen + if _MULTIROOM() and self.archivar is not None: + self.archivar._state.set_ring_state(room_id, "jetzt", ttl_minutes=30) + logger.info( + "[rocketchat] V8.2.1 A2: Strategie-Modus aktiviert — " + "topic=%s, room=%s, ring=jetzt (30 Min)", + choice, room_id[:8], ) - elif choice == "anderer_grund": - # ANDERER GRUND → normales Lernen - if _MULTIROOM() and self.archivar is not None: - logger.info( - "[rocketchat] V8.2.1 A2: ANDERER GRUND — " - "normales Lernen in room %s", - room_id[:8], - ) - await self._post_message_with_retry( - room_id, - "👍 Alles klar — ich lerne daraus fürs nächste Mal." + await self._post_message_with_retry( + room_id, + f"🎯 Verstanden — '{choice}' ist ein Strategie-Thema. " + "Ich bleibe hier und lerne nichts dazu." + ) + elif choice == "anderer_grund": + # ANDERER GRUND → normales Lernen + if _MULTIROOM() and self.archivar is not None: + logger.info( + "[rocketchat] V8.2.1 A2: ANDERER GRUND — " + "normales Lernen in room %s", + room_id[:8], + ) + await self._post_message_with_retry( + room_id, + "👍 Alles klar — ich lerne daraus fürs nächste Mal." + ) + else: + logger.warning("[rocketchat] Unknown ARCHIVAR_CLARIFY choice: %s", choice) + # ── FIX 2 (P0): ISSUE 3 — Pending Dispatch nach Klärung ── + # Nach der Klärung (Strategie/anderer_grund) den + # ursprünglichen Auftrag an den Agenten dispatchen. + pending = self._pending_clarify_dispatch.pop(room_id, None) + if pending: + _CURRENT_ORIGIN_ROOM.set(room_id) + _THEMATIC_TARGET_ROOM.set("") + # P1: _room_context als persistenter Fallback + _set_room_context_origin(f"user:{pending['username']}", room_id) + routing_counter.increment('archivar_clarify_dispatched') + logger.info( + "[rocketchat] FIX 2: Clarify dispatch — " + "room=%s, text=%s", + room_id[:8], pending["text"][:80], + ) + await self._dispatch_agent( + text=pending["text"], + room_id=room_id, + room_name=room_name, + room_type=room_type, + username=pending["username"], + msg_id=pending["msg_id"], + msg_obj=pending["msg_obj"], + is_button_response=pending.get("is_button_response", False), + category="", + ) + return # Nachricht verarbeitet — keine weitere Verarbeitung + except Exception as e: + logger.debug("[rocketchat] Error processing ARCHIVAR_CLARIFY response: %s", e) + + # Auto-Onboarding: Wenn onboarding_active, fange alle relevanten Antworten ab + # P-054: Verwende _is_onboarding_phase_active() statt nur + # archivar._stats['onboarding_active'] — kombiniert SM-State + # (onboarding.yaml) + In-Memory + Disk-State. + is_onboarding_phase, _onb_op_room, _onb_reason = self._is_onboarding_phase_active() + if _MULTIROOM() and self.archivar is not None and is_onboarding_phase: + stripped = text.strip() + # P-054: is_operator_room mit Fallback-Kette aus drei Quellen: + # 1. In-Memory (mid-Interview) + # 2. OnboardingStateMachine._data.operator_room_id (YAML, persistent) + # 3. (Notfall) Heuristik: einziger DM-Raum + operator_room = self._onboarding_state.get("operator_room_id", "") + if not operator_room: + # Fallback: OnboardingStateMachine (onboarding.yaml) + sm = getattr(self, '_onboarding_sm', None) + if sm is not None: + operator_room = getattr(sm._data, 'operator_room_id', '') or '' + if not operator_room: + # Notfall-Heuristik: einziger DM-Raum + dm_rooms = [rid for rid, info in self._room_info.items() + if info.get("type") == "d"] + if len(dm_rooms) == 1: + operator_room = dm_rooms[0] + is_operator_room = (operator_room and room_id == operator_room) + # P0-1: Review-Flow-Phasen (review_room, review_butler, review_fakt) + # müssen ebenfalls als Onboarding erkannt werden, damit + # Button-Klicks (REVIEW_ROOM_EDIT::rid::edit etc.) nicht + # als Freitext an den LLM-Agenten durchgereicht werden. + _review_phases = {"review_room", "review_butler", "review_fakt"} + is_onboarding = ( + # P0-3: Prefix-Checks VOR Phase-Inspektion (Defense in Depth) + # Fängt FAKT::/REVIEW_*/⏰ auch bei State-Verlust ab + (is_operator_room and stripped.startswith("FAKT::")) + or (is_operator_room and stripped.startswith("REVIEW_BUTLER::")) + or (is_operator_room and stripped.startswith("REVIEW_FAKT::")) + or (is_operator_room and stripped.startswith("REVIEW_ROOM")) + or (is_operator_room and "⏰" in stripped) + or (is_operator_room and stripped.lower() == "später") + or (is_operator_room and stripped.startswith("ONBOARD:")) # v2 Button-Klick + or (is_operator_room and stripped.startswith("BUTLER:")) # Fix C v7: Butler-Mode Button + or (is_operator_room and self._onboarding_state.get("current_room_index", -1) >= 0) # v2 Interview läuft + or (is_operator_room and self._onboarding_state.get("phase") == "butler_mode") # Fix C v7: Butler-Mode Phase + or (is_operator_room and self._onboarding_state.get("phase") == "catch_all_change") # Catch-All Phase + or (is_operator_room and self._onboarding_state.get("phase") == "fakt_store") # Thema 3: FAKT-Speicherort Phase + or (is_operator_room and self._onboarding_state.get("phase") in _review_phases) # P0-1: Review-Flow Phasen + or (is_operator_room and "=" in stripped) # v1 Legacy: Name = Thema + or (is_operator_room and stripped.startswith("#")) # v1 Legacy: #Name = Thema + or (is_operator_room and stripped.lower().startswith("raum:")) # v1 Legacy: Raum: Name = Thema + or (is_operator_room and stripped.isdigit()) # Catch-All-Wechsel + or (is_operator_room and stripped.lower() in ("überspringen", "skip", "nein", "no", "behalten")) # Ablehnung + ) + if is_onboarding: + await self._process_onboarding_response(text, room_id) + logger.debug("[rocketchat] ARCHIVAR-DEBUG: Onboarding active — skipping") + routing_counter.increment('onboarding_response_routed') + logger.info("ROUTING BYPASS: reason=onboarding_response_routed, origin_room=%s", room_id) + return # Nachricht wurde verarbeitet, keine weitere Verarbeitung nötig + + # ── Move-Request-Antwort? (VOR Archivar-Klassifikation!) ──────── + # Der User klickt einen Button (MOVE_REQ:room_id::✅Ja) oder antwortet + # mit "1"/"2"/"3" aus demselben Raum wie die Frage. + # Dies MUSS vor dem Archivar geprüft werden, sonst wird die Antwort + # als thematische Frage klassifiziert und ins Catch-All kopiert. + if room_id in self._pending_move_requests: + move_req = self._pending_move_requests.pop(room_id) + # ── V8.6: PresenceEngine — Move-Request beantwortet → clear ── + if _has_presence: + self._presence_engine.clear_move_request(room_id) + choice = text.strip() + + # Neues Format: MOVE_REQ::: (native Buttons) + if choice.startswith("MOVE_REQ:") and "::" in choice: + _, choice = choice.split("::", 1) + choice = choice.strip() + # Normalisiere: "1️⃣ Rüber" → "1️⃣", "2 Generell" → "2" + if choice and choice[0] in "1234": + choice = choice[0] + elif choice and choice[:2] in ("1️⃣", "2️⃣", "3️⃣", "4️⃣"): + choice = choice[:2] + # Altes Format: "1"/"2"/"3"/"4" = numerische Antwort + # Neues Format: "1️⃣", "2️⃣", "3️⃣", "4️⃣" = Emoji-Nummern + elif choice in ("1", "2", "3", "4") or choice in ("1️⃣", "2️⃣", "3️⃣", "4️⃣"): + num = int(choice[0]) # Extrahiere die Zahl (entweder direkt oder aus dem Emoji) + if num == 1: + choice = "rüberkopieren" + elif num == 2: + choice = "generell" # v6: 2 = Generell hier bleiben (sticky) + elif num == 3: + choice = "hier bleiben" # v6: 3 = Hier bleiben (nur diesmal) + else: + choice = "falsch" # v6: 4 = Falsch geroutet (reject) + choice = choice.lower() + + # Neue Mapping-Logik für verbesserte Button-UX (v6) + feedback_type = "stay" # Default + forwarded = False + # P-055: Flag für Direkt-Dispatch-Unterdrückung bei Nachklärung. + # Wird im stay_once-Branch auf True gesetzt wenn + # Nachklärungs-Buttons gesendet wurden. + skip_direct_dispatch = False + if choice in ("1", "1️⃣", "Rüber", "rüber", "rüberkopieren", "kopieren", "confirm_move", "✅ja"): + # 1️⃣ Rüber → Antwort im Zielraum (V8.1 P3: echtes Move, kein Copy) + _CURRENT_ORIGIN_ROOM.set(move_req["target_room"]) + _THEMATIC_TARGET_ROOM.set(move_req["target_room"]) + # P1: _room_context als persistenter Fallback + _set_room_context_origin(f"user:{username}", move_req["target_room"]) + forwarded = True + feedback_type = "confirm" + # ── V8.3-5: Topic für Sticky extrahieren ────────────── + move_sticky_topic = "" + if _MULTIROOM() and self.archivar is not None: + target_name = move_req.get("target_name", "") + move_sticky_topic = room_name_to_topic(target_name) if target_name else "" + # V8.3-5: Temporäres Sticky mit Topic-Scoping (30 Min TTL) + self._session_room_preferences[room_id] = { + "target_room": move_req["target_room"], + "target_name": move_req.get("target_name", "Zielraum"), + "sticky_topic": move_sticky_topic, + "expires_at": time.time() + 1800, # 30 Minuten + } + # V8.1.1 R2: Ring-GC bei Move — stale Topics aus Ursprungsraum entfernen + if _MULTIROOM() and self._multiroom_context is not None: + move_topic = move_req.get("text", "")[:80].replace("\n", " ").strip() + if move_topic: + target_name = move_req.get("target_name", "") + await self._multiroom_context.move_gc( + origin_room_id=room_id, + target_room_id=move_req["target_room"], + topic=move_topic, + room_name=target_name, + ) + # ── V8.3-3: Move für Widerspruchs-Routine speichern ── + self._recent_auto_routes[room_id] = { + "origin_room": room_id, + "target_room": move_req["target_room"], + "topic": move_sticky_topic, + "timestamp": time.time(), + "origin_message_id": move_req.get("message_id", ""), + "target_message_id": "", + "source": "confirm", # FIX 4: confirm_move vs auto-route + } + logger.info( + "[rocketchat] V8.3-5: Topic-Scoped Sticky gesetzt — " + "room=%s → target=%s, topic='%s' (30 Min, confirm_move)", + room_id[:8], move_req.get("target_name", "?")[:20], move_sticky_topic, + ) + # ── FIX 1 (P0): ISSUE 4 — Nachricht in Zielraum kopieren ── + # V8.1 hatte den Copy-Schritt fälschlich entfernt. + # P0-Fix: DM-Guard entfernt — Copy läuft jetzt auch bei DM-Origins. + try: + prefix = f"*(Auftrag von @{username}, hierher kopiert)*\n" + target_copy_id = await self._post_message_with_retry( + move_req["target_room"], + prefix + move_req["text"], + ) + if target_copy_id: + self._recent_auto_routes[room_id]["target_message_id"] = target_copy_id + routing_counter.increment('confirm_move_copied') + if room_type == "d": + routing_counter.increment('confirm_move_dm_origin') + logger.info( + "[rocketchat] FIX 1: confirm_move copy → %s, " + "target_msg_id=%s", + move_req.get("target_name", "?")[:20], + target_copy_id or "N/A", + ) + except Exception as e: + logger.warning( + "[rocketchat] FIX 1: confirm_move copy failed — %s", e + ) + elif choice in ("2", "2️⃣", "generell", "generell hier bleiben", "stay_here"): + # 2️⃣ Generell hier bleiben → Antwort im Ursprungsraum + Sticky-Eintrag + # P0-B: Thematischer Sticky (v7) — Thema aus Match-Ergebnis extrahieren + # V7-2: _sticky_rooms entfernt — thematisches never_route ersetzt räumlichen Bypass + if _MULTIROOM() and self.archivar is not None: + try: + # Extrahiere Topic aus dem gematchten Raum-Namen + target_name = move_req.get("target_name", "") + topic = room_name_to_topic(target_name) + if topic: + self.archivar._state.set_never_route(room_id, topic) + logger.info( + "[rocketchat] Sticky persisted: room %s, topic '%s' → never_route (v7)", + room_id[:8], topic, ) else: - logger.warning("[rocketchat] Unknown ARCHIVAR_CLARIFY choice: %s", choice) - # ── FIX 2 (P0): ISSUE 3 — Pending Dispatch nach Klärung ── - # Nach der Klärung (Strategie/anderer_grund) den - # ursprünglichen Auftrag an den Agenten dispatchen. - pending = self._pending_clarify_dispatch.pop(room_id, None) - if pending: - _CURRENT_ORIGIN_ROOM.set(room_id) - _THEMATIC_TARGET_ROOM.set("") - # P1: _room_context als persistenter Fallback - _set_room_context_origin(f"user:{pending['username']}", room_id) - routing_counter.increment('archivar_clarify_dispatched') - logger.info( - "[rocketchat] FIX 2: Clarify dispatch — " - "room=%s, text=%s", - room_id[:8], pending["text"][:80], - ) - await self._dispatch_agent( - text=pending["text"], - room_id=room_id, - room_name=room_name, - room_type=room_type, - username=pending["username"], - msg_id=pending["msg_id"], - msg_obj=pending["msg_obj"], - is_button_response=pending.get("is_button_response", False), - category="", - ) - return # Nachricht verarbeitet — keine weitere Verarbeitung - except Exception as e: - logger.debug("[rocketchat] Error processing ARCHIVAR_CLARIFY response: %s", e) - - # Auto-Onboarding: Wenn onboarding_active, fange alle relevanten Antworten ab - # P-054: Verwende _is_onboarding_phase_active() statt nur - # archivar._stats['onboarding_active'] — kombiniert SM-State - # (onboarding.yaml) + In-Memory + Disk-State. - is_onboarding_phase, _onb_op_room, _onb_reason = self._is_onboarding_phase_active() - if _MULTIROOM() and self.archivar is not None and is_onboarding_phase: - stripped = text.strip() - # P-054: is_operator_room mit Fallback-Kette aus drei Quellen: - # 1. In-Memory (mid-Interview) - # 2. OnboardingStateMachine._data.operator_room_id (YAML, persistent) - # 3. (Notfall) Heuristik: einziger DM-Raum - operator_room = self._onboarding_state.get("operator_room_id", "") - if not operator_room: - # Fallback: OnboardingStateMachine (onboarding.yaml) - sm = getattr(self, '_onboarding_sm', None) - if sm is not None: - operator_room = getattr(sm._data, 'operator_room_id', '') or '' - if not operator_room: - # Notfall-Heuristik: einziger DM-Raum - dm_rooms = [rid for rid, info in self._room_info.items() - if info.get("type") == "d"] - if len(dm_rooms) == 1: - operator_room = dm_rooms[0] - is_operator_room = (operator_room and room_id == operator_room) - # P0-1: Review-Flow-Phasen (review_room, review_butler, review_fakt) - # müssen ebenfalls als Onboarding erkannt werden, damit - # Button-Klicks (REVIEW_ROOM_EDIT::rid::edit etc.) nicht - # als Freitext an den LLM-Agenten durchgereicht werden. - _review_phases = {"review_room", "review_butler", "review_fakt"} - is_onboarding = ( - # P0-3: Prefix-Checks VOR Phase-Inspektion (Defense in Depth) - # Fängt FAKT::/REVIEW_*/⏰ auch bei State-Verlust ab - (is_operator_room and stripped.startswith("FAKT::")) - or (is_operator_room and stripped.startswith("REVIEW_BUTLER::")) - or (is_operator_room and stripped.startswith("REVIEW_FAKT::")) - or (is_operator_room and stripped.startswith("REVIEW_ROOM")) - or (is_operator_room and "⏰" in stripped) - or (is_operator_room and stripped.lower() == "später") - or (is_operator_room and stripped.startswith("ONBOARD:")) # v2 Button-Klick - or (is_operator_room and stripped.startswith("BUTLER:")) # Fix C v7: Butler-Mode Button - or (is_operator_room and self._onboarding_state.get("current_room_index", -1) >= 0) # v2 Interview läuft - or (is_operator_room and self._onboarding_state.get("phase") == "butler_mode") # Fix C v7: Butler-Mode Phase - or (is_operator_room and self._onboarding_state.get("phase") == "catch_all_change") # Catch-All Phase - or (is_operator_room and self._onboarding_state.get("phase") == "fakt_store") # Thema 3: FAKT-Speicherort Phase - or (is_operator_room and self._onboarding_state.get("phase") in _review_phases) # P0-1: Review-Flow Phasen - or (is_operator_room and "=" in stripped) # v1 Legacy: Name = Thema - or (is_operator_room and stripped.startswith("#")) # v1 Legacy: #Name = Thema - or (is_operator_room and stripped.lower().startswith("raum:")) # v1 Legacy: Raum: Name = Thema - or (is_operator_room and stripped.isdigit()) # Catch-All-Wechsel - or (is_operator_room and stripped.lower() in ("überspringen", "skip", "nein", "no", "behalten")) # Ablehnung - ) - if is_onboarding: - await self._process_onboarding_response(text, room_id) - logger.debug("[rocketchat] ARCHIVAR-DEBUG: Onboarding active — skipping") - routing_counter.increment('onboarding_response_routed') - logger.info("ROUTING BYPASS: reason=onboarding_response_routed, origin_room=%s", room_id) - return # Nachricht wurde verarbeitet, keine weitere Verarbeitung nötig - - # ── Move-Request-Antwort? (VOR Archivar-Klassifikation!) ──────── - # Der User klickt einen Button (MOVE_REQ:room_id::✅Ja) oder antwortet - # mit "1"/"2"/"3" aus demselben Raum wie die Frage. - # Dies MUSS vor dem Archivar geprüft werden, sonst wird die Antwort - # als thematische Frage klassifiziert und ins Catch-All kopiert. - if room_id in self._pending_move_requests: - move_req = self._pending_move_requests.pop(room_id) - # ── V8.6: PresenceEngine — Move-Request beantwortet → clear ── - if _has_presence: - self._presence_engine.clear_move_request(room_id) - choice = text.strip() - - # Neues Format: MOVE_REQ::: (native Buttons) - if choice.startswith("MOVE_REQ:") and "::" in choice: - _, choice = choice.split("::", 1) - choice = choice.strip() - # Normalisiere: "1️⃣ Rüber" → "1️⃣", "2 Generell" → "2" - if choice and choice[0] in "1234": - choice = choice[0] - elif choice and choice[:2] in ("1️⃣", "2️⃣", "3️⃣", "4️⃣"): - choice = choice[:2] - # Altes Format: "1"/"2"/"3"/"4" = numerische Antwort - # Neues Format: "1️⃣", "2️⃣", "3️⃣", "4️⃣" = Emoji-Nummern - elif choice in ("1", "2", "3", "4") or choice in ("1️⃣", "2️⃣", "3️⃣", "4️⃣"): - num = int(choice[0]) # Extrahiere die Zahl (entweder direkt oder aus dem Emoji) - if num == 1: - choice = "rüberkopieren" - elif num == 2: - choice = "generell" # v6: 2 = Generell hier bleiben (sticky) - elif num == 3: - choice = "hier bleiben" # v6: 3 = Hier bleiben (nur diesmal) - else: - choice = "falsch" # v6: 4 = Falsch geroutet (reject) - choice = choice.lower() - - # Neue Mapping-Logik für verbesserte Button-UX (v6) - feedback_type = "stay" # Default - forwarded = False - # P-055: Flag für Direkt-Dispatch-Unterdrückung bei Nachklärung. - # Wird im stay_once-Branch auf True gesetzt wenn - # Nachklärungs-Buttons gesendet wurden. - skip_direct_dispatch = False - if choice in ("1", "1️⃣", "Rüber", "rüber", "rüberkopieren", "kopieren", "confirm_move", "✅ja"): - # 1️⃣ Rüber → Antwort im Zielraum (V8.1 P3: echtes Move, kein Copy) - _CURRENT_ORIGIN_ROOM.set(move_req["target_room"]) - _THEMATIC_TARGET_ROOM.set(move_req["target_room"]) - # P1: _room_context als persistenter Fallback - _set_room_context_origin(f"user:{username}", move_req["target_room"]) - forwarded = True - feedback_type = "confirm" - # ── V8.3-5: Topic für Sticky extrahieren ────────────── - move_sticky_topic = "" - if _MULTIROOM() and self.archivar is not None: - target_name = move_req.get("target_name", "") - move_sticky_topic = room_name_to_topic(target_name) if target_name else "" - # V8.3-5: Temporäres Sticky mit Topic-Scoping (30 Min TTL) - self._session_room_preferences[room_id] = { - "target_room": move_req["target_room"], - "target_name": move_req.get("target_name", "Zielraum"), - "sticky_topic": move_sticky_topic, - "expires_at": time.time() + 1800, # 30 Minuten - } - # V8.1.1 R2: Ring-GC bei Move — stale Topics aus Ursprungsraum entfernen - if _MULTIROOM() and self._multiroom_context is not None: - move_topic = move_req.get("text", "")[:80].replace("\n", " ").strip() - if move_topic: - target_name = move_req.get("target_name", "") - await self._multiroom_context.move_gc( - origin_room_id=room_id, - target_room_id=move_req["target_room"], - topic=move_topic, - room_name=target_name, + logger.warning( + "[rocketchat] Sticky: kein Topic extrahierbar aus '%s'", + target_name, ) - # ── V8.3-3: Move für Widerspruchs-Routine speichern ── - self._recent_auto_routes[room_id] = { - "origin_room": room_id, - "target_room": move_req["target_room"], - "topic": move_sticky_topic, - "timestamp": time.time(), - "origin_message_id": move_req.get("message_id", ""), - "target_message_id": "", - "source": "confirm", # FIX 4: confirm_move vs auto-route - } - logger.info( - "[rocketchat] V8.3-5: Topic-Scoped Sticky gesetzt — " - "room=%s → target=%s, topic='%s' (30 Min, confirm_move)", - room_id[:8], move_req.get("target_name", "?")[:20], move_sticky_topic, - ) - # ── FIX 1 (P0): ISSUE 4 — Nachricht in Zielraum kopieren ── - # V8.1 hatte den Copy-Schritt fälschlich entfernt. - # P0-Fix: DM-Guard entfernt — Copy läuft jetzt auch bei DM-Origins. - try: - prefix = f"*(Auftrag von @{username}, hierher kopiert)*\n" - target_copy_id = await self._post_message_with_retry( - move_req["target_room"], - prefix + move_req["text"], - ) - if target_copy_id: - self._recent_auto_routes[room_id]["target_message_id"] = target_copy_id - routing_counter.increment('confirm_move_copied') - if room_type == "d": - routing_counter.increment('confirm_move_dm_origin') - logger.info( - "[rocketchat] FIX 1: confirm_move copy → %s, " - "target_msg_id=%s", - move_req.get("target_name", "?")[:20], - target_copy_id or "N/A", - ) except Exception as e: - logger.warning( - "[rocketchat] FIX 1: confirm_move copy failed — %s", e + logger.warning("[rocketchat] Failed to persist sticky decision: %s", e) + await self._post_message_with_retry(room_id, "🔒 Verstanden — dieses Thema bleibt jetzt hier im Raum. (Themenbezogen, verfällt nach 24h oder Themenwechsel)") + feedback_type = "never" + elif choice in ("3", "3️⃣", "hier bleiben", "nur diesmal", "stay_once"): + # 3️⃣ Nur diesmal → Antwort im Ursprungsraum (nur diesmal, kein Sticky) + # V8.2.1 A2: Nach stay_once → Nachklärung mit Strategie-Buttons + # P-057: feedback_type='neutral' statt 'stay' — stay_once + # meint semantisch: 'Vorschlag war richtig, Ausführung nur + # diesmal hier'. Kein negatives Feedback, kein Gewicht-Verlust. + await self._post_message_with_retry(room_id, "👍 Bleiben hier — ich kümmere mich drum.") + feedback_type = "neutral" + # P-055: Flag, um Direkt-Dispatch zu unterdrücken wenn + # Nachklärungs-Buttons gesendet wurden. Verhindert + # Clarify-Dispatch-Schleife (zwei Wahrheitsquellen). + skip_direct_dispatch = False + # V8.2.1 A2: Nachklärung bei stay_once — Strategie-Buttons senden + # P-057 Folgefix: Bei feedback_type='neutral' wird nicht + # gelernt → Nachklärung ist sinnlos. Überspringen. + if _MULTIROOM() and self.archivar is not None and feedback_type != "neutral": + if self.archivar._should_trigger_nachklaerung("stay_once"): + # Keywords des Zielraums als lesbaren Text einbauen + target_room_id = move_req.get("target_room", "") + target_keywords = [] + if target_room_id and self.archivar._room_map is not None: + target_entry = self.archivar._room_map.rooms.get(target_room_id) + if target_entry: + target_keywords = target_entry.keywords_100[:5] + nachklaerung_buttons = self.archivar._get_nachklaerung_buttons( + keywords=target_keywords if target_keywords else None ) - elif choice in ("2", "2️⃣", "generell", "generell hier bleiben", "stay_here"): - # 2️⃣ Generell hier bleiben → Antwort im Ursprungsraum + Sticky-Eintrag - # P0-B: Thematischer Sticky (v7) — Thema aus Match-Ergebnis extrahieren - # V7-2: _sticky_rooms entfernt — thematisches never_route ersetzt räumlichen Bypass - if _MULTIROOM() and self.archivar is not None: + await self._send_archivar_buttons( + room_id, + nachklaerung_buttons["text"], + {"actions": nachklaerung_buttons["actions"]}, + ) + logger.info( + "[rocketchat] V8.2.1 A2: Nachklärung gesendet — " + "Strategie-Buttons in room %s", room_id[:8], + ) + # P-055: Direkt-Dispatch unterdrücken — die + # Nachricht wird erst nach Klärung via + # ARCHIVAR_CLARIFY-Handler dispatched. + skip_direct_dispatch = True + # FIX 2 (P0): ISSUE 3 — Persistenter Pending-Dispatch-Slot + # Speichere move_req-Daten für ARCHIVAR_CLARIFY-Handler. + self._pending_clarify_dispatch[room_id] = { + "text": move_req.get("text", ""), + "username": username, + "msg_id": msg_id, + "msg_obj": msg_obj, + "is_button_response": is_button_response, + } + logger.info( + "[rocketchat] FIX 2: Pending clarify dispatch saved — " + "room=%s", room_id[:8], + ) + # Stay-Counter: Wenn der User 3× in 10 Min "Hier bleiben" klickt, + # wird der Raum automatisch auf "never_route" gesetzt. + # P1-3: stay_tracker ist jetzt persistent in ArchivarState + # P0-B: Thematischer Sticky (v7) — Thema aus Match-Ergebnis extrahieren + if _MULTIROOM() and self.archivar is not None: + count = self.archivar._state.update_stay_tracker(room_id, username) + if count >= 3: try: - # Extrahiere Topic aus dem gematchten Raum-Namen target_name = move_req.get("target_name", "") topic = room_name_to_topic(target_name) if topic: self.archivar._state.set_never_route(room_id, topic) - logger.info( - "[rocketchat] Sticky persisted: room %s, topic '%s' → never_route (v7)", - room_id[:8], topic, - ) - else: - logger.warning( - "[rocketchat] Sticky: kein Topic extrahierbar aus '%s'", - target_name, - ) + # V7-2: _sticky_rooms entfernt — thematisches never_route reicht + logger.info("[rocketchat] Auto-promoted to never_route after %d stays in room %s, topic '%s'", count, room_id[:8], topic) + await self._post_message_with_retry(room_id, "🔒 Gut erkannt — dieses Thema bleibt ab jetzt hier. (Verfällt nach 24h oder Themenwechsel)") except Exception as e: - logger.warning("[rocketchat] Failed to persist sticky decision: %s", e) - await self._post_message_with_retry(room_id, "🔒 Verstanden — dieses Thema bleibt jetzt hier im Raum. (Themenbezogen, verfällt nach 24h oder Themenwechsel)") - feedback_type = "never" - elif choice in ("3", "3️⃣", "hier bleiben", "nur diesmal", "stay_once"): - # 3️⃣ Nur diesmal → Antwort im Ursprungsraum (nur diesmal, kein Sticky) - # V8.2.1 A2: Nach stay_once → Nachklärung mit Strategie-Buttons - # P-057: feedback_type='neutral' statt 'stay' — stay_once - # meint semantisch: 'Vorschlag war richtig, Ausführung nur - # diesmal hier'. Kein negatives Feedback, kein Gewicht-Verlust. - await self._post_message_with_retry(room_id, "👍 Bleiben hier — ich kümmere mich drum.") - feedback_type = "neutral" - # P-055: Flag, um Direkt-Dispatch zu unterdrücken wenn - # Nachklärungs-Buttons gesendet wurden. Verhindert - # Clarify-Dispatch-Schleife (zwei Wahrheitsquellen). - skip_direct_dispatch = False - # V8.2.1 A2: Nachklärung bei stay_once — Strategie-Buttons senden - # P-057 Folgefix: Bei feedback_type='neutral' wird nicht - # gelernt → Nachklärung ist sinnlos. Überspringen. - if _MULTIROOM() and self.archivar is not None and feedback_type != "neutral": - if self.archivar._should_trigger_nachklaerung("stay_once"): - # Keywords des Zielraums als lesbaren Text einbauen - target_room_id = move_req.get("target_room", "") - target_keywords = [] - if target_room_id and self.archivar._room_map is not None: - target_entry = self.archivar._room_map.rooms.get(target_room_id) - if target_entry: - target_keywords = target_entry.keywords_100[:5] - nachklaerung_buttons = self.archivar._get_nachklaerung_buttons( - keywords=target_keywords if target_keywords else None - ) - await self._send_archivar_buttons( - room_id, - nachklaerung_buttons["text"], - {"actions": nachklaerung_buttons["actions"]}, - ) - logger.info( - "[rocketchat] V8.2.1 A2: Nachklärung gesendet — " - "Strategie-Buttons in room %s", room_id[:8], - ) - # P-055: Direkt-Dispatch unterdrücken — die - # Nachricht wird erst nach Klärung via - # ARCHIVAR_CLARIFY-Handler dispatched. - skip_direct_dispatch = True - # FIX 2 (P0): ISSUE 3 — Persistenter Pending-Dispatch-Slot - # Speichere move_req-Daten für ARCHIVAR_CLARIFY-Handler. - self._pending_clarify_dispatch[room_id] = { - "text": move_req.get("text", ""), - "username": username, - "msg_id": msg_id, - "msg_obj": msg_obj, - "is_button_response": is_button_response, - } - logger.info( - "[rocketchat] FIX 2: Pending clarify dispatch saved — " - "room=%s", room_id[:8], - ) - # Stay-Counter: Wenn der User 3× in 10 Min "Hier bleiben" klickt, - # wird der Raum automatisch auf "never_route" gesetzt. - # P1-3: stay_tracker ist jetzt persistent in ArchivarState - # P0-B: Thematischer Sticky (v7) — Thema aus Match-Ergebnis extrahieren - if _MULTIROOM() and self.archivar is not None: - count = self.archivar._state.update_stay_tracker(room_id, username) - if count >= 3: - try: - target_name = move_req.get("target_name", "") - topic = room_name_to_topic(target_name) - if topic: - self.archivar._state.set_never_route(room_id, topic) - # V7-2: _sticky_rooms entfernt — thematisches never_route reicht - logger.info("[rocketchat] Auto-promoted to never_route after %d stays in room %s, topic '%s'", count, room_id[:8], topic) - await self._post_message_with_retry(room_id, "🔒 Gut erkannt — dieses Thema bleibt ab jetzt hier. (Verfällt nach 24h oder Themenwechsel)") - except Exception as e: - logger.warning("[rocketchat] Failed to auto-promote sticky: %s", e) - elif choice in ("4", "4️⃣", "falsch", "falsch geroutet", "reject"): - # 4️⃣ Falsch geroutet → Zielraum war FALSCH, Ursprungsraum - # war RICHTIG. Lerne aktiv um: Zielraum-Gewicht drastisch - # reduzieren, Ursprungsraum-Gewicht erhöhen. - # P-058: Eigenständiger feedback_type='reject'. - # KEIN set_never_route — Themenring wäre falsch. - # KEIN _room_context-Cleanup — Ursprungsraum IST Zielraum. - # P-040: DM-Ausschluss — wenn origin==target möglich, - # Button 4 nicht anbieten (wird in _send_move_request geprüft). - await self._post_message_with_retry( - room_id, - "📌 Korrigiert — das Thema wird ab jetzt dauerhaft hier geroutet." - ) - feedback_type = "reject" - # Kein Dispatch — der User hat den Vorschlag abgelehnt, - # die Nachricht bleibt im Ursprungsraum und wird normal - # vom Agenten verarbeitet (kein skip_direct_dispatch nötig). - logger.info( - "[rocketchat] P-058: reject feedback — origin_room=%s, " - "target_room=%s → Zielraum-Gewicht wird reduziert, " - "Ursprungsraum-Gewicht erhöht", - room_id[:8], move_req.get("target_room", "?")[:8], - ) - - # Lernsystem: Keyword-Gewichte aus User-Entscheidung lernen - if _MULTIROOM() and self.archivar is not None and move_req.get("message_id"): - user_id = user_info.get("_id", "") - await self.archivar.handle_feedback_response( - message_id=move_req["message_id"], - user_id=user_id, - feedback_type=feedback_type - ) - - # ── Ansatz D: Per-Room Pending Question Resolver ────────── - # Nachdem alle Button-Aktionen (Nachklärung, Stay-Counter, - # Feedback) abgeschlossen sind, die pending question aus dem - # Ursprungsraum UND dem aktuellen Raum entfernen. - # Verhindert Zombie-States und wachsende pending-Sets. - origin_room = move_req.get("origin_room", room_id) - self._rooms_with_pending_questions.discard(origin_room) - self._rooms_with_pending_questions.discard(room_id) - # ── Ende Ansatz D ───────────────────────────────────────── - - # ── V7-1: Bei ✅Ja → Breadcrumb im Ursprungsraum + Agent-Dispatch ── - if forwarded: - # Breadcrumb: "Wir sind rübergewechselt → #Zielraum-Name" - target_name = move_req.get("target_name", "Zielraum") - breadcrumb = f"🔄 Wir sind rübergewechselt → #{target_name.lstrip('#')}" - await self._post_message_with_retry(room_id, breadcrumb) - logger.info( - "[rocketchat] V7-1: Breadcrumb sent to origin room %s → %s", - room_id[:8], target_name, - ) - # _CURRENT_ORIGIN_ROOM ist bereits auf Zielraum gesetzt (line 1306). - # Agent-Dispatch direkt hier — kein Archivar-Block, kein Reset. - # Verwende Zielraum-Name/Typ für den Raum-Kontext-Prefix. - target_room_id = move_req.get("target_room", "") - target_room_info = self._room_info.get(target_room_id, {}) - target_room_name = target_room_info.get("name", target_name) - target_room_type = target_room_info.get("type", "c") - await self._dispatch_agent( - text=move_req.get("text", ""), - room_id=target_room_id, - room_name=target_room_name, - room_type=target_room_type, - username=username, - msg_id=msg_id, - msg_obj=msg_obj, - is_button_response=is_button_response, - category="work_order", - ) - return - else: - # Button 2/3: stay_here / stay_once — dispatch original message - # to agent in the origin room (P0 fix: data loss prevention) - # P-055: Wenn Nachklärungs-Buttons gesendet wurden, - # Direkt-Dispatch überspringen — die Nachricht wird - # erst nach Klärung via ARCHIVAR_CLARIFY-Handler dispatched. - if skip_direct_dispatch: - logger.info( - "[rocketchat] P-055: Direkt-Dispatch übersprungen — " - "Nachklärung aktiv, Dispatch via ARCHIVAR_CLARIFY-Handler " - "room=%s", room_id[:8], - ) - return - origin_text = move_req.get("text", "") - if not origin_text: - logger.warning( - "[rocketchat] P0: stay_here/stay_once without origin text — " - "skipping dispatch (room=%s)", room_id[:8] - ) - return - # _CURRENT_ORIGIN_ROOM: User stays HERE (origin room) - _CURRENT_ORIGIN_ROOM.set(room_id) - # P1: _room_context als persistenter Fallback - _set_room_context_origin(f"user:{username}", room_id) - # _THEMATIC_TARGET_ROOM: NOT set — no topic change - await self._dispatch_agent( - text=origin_text, - room_id=room_id, - room_name=room_name, - room_type=room_type, - username=username, - msg_id=msg_id, - msg_obj=msg_obj, - is_button_response=is_button_response, - category="work_order", - ) - routing_counter.increment("stay_here_dispatched") - logger.info( - "[rocketchat] P0: stay_here dispatch — origin_room=%s, " - "text=[:80]%s", room_id[:8], origin_text[:80] - ) - return # Move-Request verarbeitet — keine weitere Verarbeitung - - forwarded = False - - # ── V8.3-3: Widerspruchs-Routine (RÜCKHOLEN) ────────────────────── - # Prüft ob der User widerspricht ('Halt, das gehört hier her') - # innerhalb 10 Min nach einer Auto-Route, 30 Min nach confirm_move. - # V8.3.1 F2: Wortgrenzen-Match + Satzkontext-Whitelist. - # FIX 4: Erweiterte Keywords + confirm_move-Support. - _WIDERSPRUCH_KEYWORDS = [ - 'halt', 'bleib hier', 'gehört hier her', - 'nein', 'stop', 'falscher raum', 'zurück', 'roll back', 'rollback', - 'passt hier nicht', 'gehört nicht hier', 'falsch', 'doch nicht', - ] - text_lower = text.lower() - - def _widerspruch_matches_sentence_context(kw: str, txt: str) -> bool: - """Check if keyword matches with word boundaries AND is at sentence - start or in a sentence with an exclamation mark.""" - for m in re.finditer(r'\b' + re.escape(kw) + r'\b', txt): - # Find the sentence containing this match - pos = m.start() - # Search backwards for sentence start - sentence_start = 0 - for i in range(pos - 1, -1, -1): - if txt[i] in '.!?\n': - sentence_start = i + 1 - break - # Search forwards for sentence end - sentence_end = len(txt) - for i in range(pos, len(txt)): - if txt[i] in '.!?\n': - sentence_end = i - break - sentence = txt[sentence_start:sentence_end].strip() - # Whitelist: keyword at sentence start OR '!' in same sentence - if sentence.startswith(kw) or '!' in sentence: - return True - return False - - is_widerspruch = any( - _widerspruch_matches_sentence_context(kw, text_lower) - for kw in _WIDERSPRUCH_KEYWORDS - ) - - # ── FIX 4: Erweiterte Widerspruchs-Erkennung ────────────────── - # Auto-Route: room_id == origin_room (direkter Lookup) - # confirm_move: room_id == target_room (inverser Lookup) - route_info = None - route_source = None - if is_widerspruch and room_id in self._recent_auto_routes: - route_info = self._recent_auto_routes[room_id] - route_source = route_info.get("source", "auto") - elif is_widerspruch: - # Inverser Lookup: Suche nach confirm_move-Route, - # deren target_room == room_id (Rainer Architektur-Detail) - for origin_rid, entry in list(self._recent_auto_routes.items()): - if entry.get("target_room") == room_id and entry.get("source") == "confirm": - route_info = entry - route_source = "confirm" - # room_id ist der Zielraum, origin_room ist der Ursprungsraum - break - - if is_widerspruch and route_info is not None: - elapsed = time.time() - route_info["timestamp"] - # Auto-Route: 10 Min, confirm_move: 30 Min - max_window = 1800 if route_source == "confirm" else 600 - if elapsed <= max_window: - logger.info( - "[rocketchat] V8.3-3: Widerspruch erkannt in room %s — " - "%.0fs nach %s-Route, hole Thema zurück", - room_id[:8], elapsed, route_source, - ) - target_room_id = route_info["target_room"] - origin_room_id = route_info["origin_room"] - # a. Thema aus Zielraum entfernen (delete/edit) - target_msg_id = route_info.get("target_message_id", "") - if target_msg_id: - if not self.rest.delete_message(target_room_id, target_msg_id): - self.rest.update_message( - target_room_id, target_msg_id, "_(Zurückgezogen)_" - ) - # b. Thema im Ursprungsraum wieder aufnehmen - if route_source == "confirm": - # FIX 4: Bei confirm_move — Rückhol-Text mit Original - origin_name = self._room_info.get(origin_room_id, {}).get("name", "Ursprungsraum") - target_name = self._room_info.get(target_room_id, {}).get("name", "Zielraum") - rueckhol_text = ( - f"↩️ Zurückgeholt aus #{target_name.lstrip('#')}\n" - f"{display_text}" - ) - await self._post_message_with_retry(origin_room_id, rueckhol_text) - routing_counter.increment('widerspruch_confirm_move_route') - else: - await self._post_message_with_retry( - room_id, - "👍 Verstanden — das Thema gehört hier her. Ich bleibe hier." - ) - # c. _CURRENT_ORIGIN_ROOM zurück auf Ursprungsraum - _CURRENT_ORIGIN_ROOM.set(origin_room_id) - _THEMATIC_TARGET_ROOM.set("") - # P1: _room_context als persistenter Fallback - _set_room_context_origin(f"user:{username}", origin_room_id) - # d. Sticky löschen - self._session_room_preferences.pop(origin_room_id, None) - # e. Ring: move_gc(target → origin) — Rückholung - if _MULTIROOM() and self._multiroom_context is not None: - route_topic = route_info.get("topic", "") - if route_topic: - await self._multiroom_context.move_gc( - origin_room_id=target_room_id, - target_room_id=origin_room_id, - topic=route_topic, - room_name=self._room_info.get(origin_room_id, {}).get("name", ""), - ) - # f. KEIN Lernen - # g. Cleanup - del self._recent_auto_routes[origin_room_id] - # Dispatch im Ursprungsraum - await self._dispatch_agent( - text=display_text, - room_id=origin_room_id, - room_name=self._room_info.get(origin_room_id, {}).get("name", room_name), - room_type=self._room_info.get(origin_room_id, {}).get("type", room_type), - username=username, - msg_id=msg_id, - msg_obj=msg_obj, - is_button_response=is_button_response, - category="", - ) - return - else: - # Zeitfenster abgelaufen → aufräumen - origin_rid = route_info.get("origin_room", room_id) - self._recent_auto_routes.pop(origin_rid, None) - - # ── V8.3-4: Expliziter Raumwechsel (BEWUSSTE ENTSCHEIDUNG) ──────── - # V8.3.4 B3: Verb-basierte Erkennung statt #-Pflicht. - # Pattern: 'lass uns in wechseln', 'wechseln nach ', etc. - # kann mit oder ohne # sein. Validierung via room-map.json. - _EXPLICIT_SWITCH_RE = re.compile( - r'(?:lass uns |gehen wir |wechsel(?:n)? )?(?:in |nach )?#?(\w[\w-]*)', - re.IGNORECASE, - ) - _SWITCH_TRIGGERS = [ - 'lass uns in', 'gehen wir in', 'wechseln nach', 'wechsel in', - 'raum wechseln', 'wechseln in', - ] - # V8.3.1 F3: Negativ-Liste — Phrasen die KEIN Raumwechsel sind - _SWITCH_NEGATIV = [ - 'in den', 'ins bett', 'ins kino', 'zur seite', 'zur bank', - 'nach hause', 'nach oben', 'nach unten', 'nach links', 'nach rechts', - 'nach vorne', 'nach hinten', 'in die', 'in das', 'zum arzt', - ] - is_explicit_switch = any(trigger in text_lower for trigger in _SWITCH_TRIGGERS) - # V8.3.1 F3: Negativ-Check — wenn Negativ-Phrase enthalten → kein Switch - if is_explicit_switch: - if any(neg in text_lower for neg in _SWITCH_NEGATIV): - is_explicit_switch = False - target_room_id = "" - target_room_display = "" - if is_explicit_switch and _MULTIROOM() and self.archivar is not None: - switch_match = _EXPLICIT_SWITCH_RE.search(text) - if switch_match: - switch_room_name = switch_match.group(1).lower() - # V8.3.4 B3: Keine #-Pflicht mehr — stattdessen room-map-Validierung. - # Raum aus room-map.json auflösen (name → room_id), case-insensitive. - room_map = self.archivar._room_map - if room_map is not None: - for rid, entry in room_map.rooms.items(): - entry_name = entry.name.lstrip('#').lower().replace(' ', '-') - # V8.3.4.1 F1: Exakter Match statt Substring-Injection. - # 'Plugin' darf NICHT 'Rocketchat-Plugin' matchen. - if switch_room_name == entry_name or any( - kw.lower() == switch_room_name for kw in entry.keywords_100 - ): - target_room_id = rid - target_room_display = entry.name - break - # V8.3.4 B3: Nur auslösen wenn Raum in room-map.json existiert - if not target_room_id: - logger.debug( - "[rocketchat] V8.3-4: Raum '%s' nicht in room-map.json — " - "kein expliziter Raumwechsel", - switch_room_name, - ) - is_explicit_switch = False - else: - is_explicit_switch = False - if is_explicit_switch and target_room_id and target_room_id != room_id: - logger.info( - "[rocketchat] V8.3-4: Expliziter Raumwechsel — " - "'%s' → %s (%s)", - text[:80], target_room_display, target_room_id[:8], - ) - # a. _CURRENT_ORIGIN_ROOM auf Zielraum setzen - _CURRENT_ORIGIN_ROOM.set(target_room_id) - _THEMATIC_TARGET_ROOM.set(target_room_id) - # P1: _room_context als persistenter Fallback - _set_room_context_origin(f"user:{username}", target_room_id) - # b. Sticky setzen: 30 Min, sticky_topic = 'explizit-wechsel' - self._session_room_preferences[room_id] = { - "target_room": target_room_id, - "target_name": target_room_display, - "sticky_topic": "explizit-wechsel", - "expires_at": time.time() + 1800, # 30 Min - } - logger.info( - "[rocketchat] V8.3-4: Expliziter Wechsel-Sticky gesetzt — " - "room=%s → target=%s (30 Min)", - room_id[:8], target_room_display[:20], - ) - # c. Agent antwortet im Zielraum + logger.warning("[rocketchat] Failed to auto-promote sticky: %s", e) + elif choice in ("4", "4️⃣", "falsch", "falsch geroutet", "reject"): + # 4️⃣ Falsch geroutet → Zielraum war FALSCH, Ursprungsraum + # war RICHTIG. Lerne aktiv um: Zielraum-Gewicht drastisch + # reduzieren, Ursprungsraum-Gewicht erhöhen. + # P-058: Eigenständiger feedback_type='reject'. + # KEIN set_never_route — Themenring wäre falsch. + # KEIN _room_context-Cleanup — Ursprungsraum IST Zielraum. + # P-040: DM-Ausschluss — wenn origin==target möglich, + # Button 4 nicht anbieten (wird in _send_move_request geprüft). await self._post_message_with_retry( - target_room_id, - f"Gerne, wir sind jetzt in {target_room_display}. " - f"Was möchtest du besprechen?" + room_id, + "📌 Korrigiert — das Thema wird ab jetzt dauerhaft hier geroutet." ) - # Dispatch im Zielraum + feedback_type = "reject" + # Kein Dispatch — der User hat den Vorschlag abgelehnt, + # die Nachricht bleibt im Ursprungsraum und wird normal + # vom Agenten verarbeitet (kein skip_direct_dispatch nötig). + logger.info( + "[rocketchat] P-058: reject feedback — origin_room=%s, " + "target_room=%s → Zielraum-Gewicht wird reduziert, " + "Ursprungsraum-Gewicht erhöht", + room_id[:8], move_req.get("target_room", "?")[:8], + ) + + # Lernsystem: Keyword-Gewichte aus User-Entscheidung lernen + if _MULTIROOM() and self.archivar is not None and move_req.get("message_id"): + user_id = user_info.get("_id", "") + await self.archivar.handle_feedback_response( + message_id=move_req["message_id"], + user_id=user_id, + feedback_type=feedback_type + ) + + # ── Ansatz D: Per-Room Pending Question Resolver ────────── + # Nachdem alle Button-Aktionen (Nachklärung, Stay-Counter, + # Feedback) abgeschlossen sind, die pending question aus dem + # Ursprungsraum UND dem aktuellen Raum entfernen. + # Verhindert Zombie-States und wachsende pending-Sets. + origin_room = move_req.get("origin_room", room_id) + self._rooms_with_pending_questions.discard(origin_room) + self._rooms_with_pending_questions.discard(room_id) + # ── Ende Ansatz D ───────────────────────────────────────── + + # ── V7-1: Bei ✅Ja → Breadcrumb im Ursprungsraum + Agent-Dispatch ── + if forwarded: + # Breadcrumb: "Wir sind rübergewechselt → #Zielraum-Name" + target_name = move_req.get("target_name", "Zielraum") + breadcrumb = f"🔄 Wir sind rübergewechselt → #{target_name.lstrip('#')}" + await self._post_message_with_retry(room_id, breadcrumb) + logger.info( + "[rocketchat] V7-1: Breadcrumb sent to origin room %s → %s", + room_id[:8], target_name, + ) + # _CURRENT_ORIGIN_ROOM ist bereits auf Zielraum gesetzt (line 1306). + # Agent-Dispatch direkt hier — kein Archivar-Block, kein Reset. + # Verwende Zielraum-Name/Typ für den Raum-Kontext-Prefix. + target_room_id = move_req.get("target_room", "") target_room_info = self._room_info.get(target_room_id, {}) - target_room_name_disp = target_room_info.get("name", target_room_display) + target_room_name = target_room_info.get("name", target_name) target_room_type = target_room_info.get("type", "c") await self._dispatch_agent( - text=display_text, + text=move_req.get("text", ""), room_id=target_room_id, - room_name=target_room_name_disp, + room_name=target_room_name, room_type=target_room_type, username=username, msg_id=msg_id, msg_obj=msg_obj, is_button_response=is_button_response, + category="work_order", + ) + return + else: + # Button 2/3: stay_here / stay_once — dispatch original message + # to agent in the origin room (P0 fix: data loss prevention) + # P-055: Wenn Nachklärungs-Buttons gesendet wurden, + # Direkt-Dispatch überspringen — die Nachricht wird + # erst nach Klärung via ARCHIVAR_CLARIFY-Handler dispatched. + if skip_direct_dispatch: + logger.info( + "[rocketchat] P-055: Direkt-Dispatch übersprungen — " + "Nachklärung aktiv, Dispatch via ARCHIVAR_CLARIFY-Handler " + "room=%s", room_id[:8], + ) + return + origin_text = move_req.get("text", "") + if not origin_text: + logger.warning( + "[rocketchat] P0: stay_here/stay_once without origin text — " + "skipping dispatch (room=%s)", room_id[:8] + ) + return + # _CURRENT_ORIGIN_ROOM: User stays HERE (origin room) + _CURRENT_ORIGIN_ROOM.set(room_id) + # P1: _room_context als persistenter Fallback + _set_room_context_origin(f"user:{username}", room_id) + # _THEMATIC_TARGET_ROOM: NOT set — no topic change + await self._dispatch_agent( + text=origin_text, + room_id=room_id, + room_name=room_name, + room_type=room_type, + username=username, + msg_id=msg_id, + msg_obj=msg_obj, + is_button_response=is_button_response, + category="work_order", + ) + routing_counter.increment("stay_here_dispatched") + logger.info( + "[rocketchat] P0: stay_here dispatch — origin_room=%s, " + "text=[:80]%s", room_id[:8], origin_text[:80] + ) + return # Move-Request verarbeitet — keine weitere Verarbeitung + + forwarded = False + + # ── V8.3-3: Widerspruchs-Routine (RÜCKHOLEN) ────────────────────── + # Prüft ob der User widerspricht ('Halt, das gehört hier her') + # innerhalb 10 Min nach einer Auto-Route, 30 Min nach confirm_move. + # V8.3.1 F2: Wortgrenzen-Match + Satzkontext-Whitelist. + # FIX 4: Erweiterte Keywords + confirm_move-Support. + _WIDERSPRUCH_KEYWORDS = [ + 'halt', 'bleib hier', 'gehört hier her', + 'nein', 'stop', 'falscher raum', 'zurück', 'roll back', 'rollback', + 'passt hier nicht', 'gehört nicht hier', 'falsch', 'doch nicht', + ] + text_lower = text.lower() + + def _widerspruch_matches_sentence_context(kw: str, txt: str) -> bool: + """Check if keyword matches with word boundaries AND is at sentence + start or in a sentence with an exclamation mark.""" + for m in re.finditer(r'\b' + re.escape(kw) + r'\b', txt): + # Find the sentence containing this match + pos = m.start() + # Search backwards for sentence start + sentence_start = 0 + for i in range(pos - 1, -1, -1): + if txt[i] in '.!?\n': + sentence_start = i + 1 + break + # Search forwards for sentence end + sentence_end = len(txt) + for i in range(pos, len(txt)): + if txt[i] in '.!?\n': + sentence_end = i + break + sentence = txt[sentence_start:sentence_end].strip() + # Whitelist: keyword at sentence start OR '!' in same sentence + if sentence.startswith(kw) or '!' in sentence: + return True + return False + + is_widerspruch = any( + _widerspruch_matches_sentence_context(kw, text_lower) + for kw in _WIDERSPRUCH_KEYWORDS + ) + + # ── FIX 4: Erweiterte Widerspruchs-Erkennung ────────────────── + # Auto-Route: room_id == origin_room (direkter Lookup) + # confirm_move: room_id == target_room (inverser Lookup) + route_info = None + route_source = None + if is_widerspruch and room_id in self._recent_auto_routes: + route_info = self._recent_auto_routes[room_id] + route_source = route_info.get("source", "auto") + elif is_widerspruch: + # Inverser Lookup: Suche nach confirm_move-Route, + # deren target_room == room_id (Rainer Architektur-Detail) + for origin_rid, entry in list(self._recent_auto_routes.items()): + if entry.get("target_room") == room_id and entry.get("source") == "confirm": + route_info = entry + route_source = "confirm" + # room_id ist der Zielraum, origin_room ist der Ursprungsraum + break + + if is_widerspruch and route_info is not None: + elapsed = time.time() - route_info["timestamp"] + # Auto-Route: 10 Min, confirm_move: 30 Min + max_window = 1800 if route_source == "confirm" else 600 + if elapsed <= max_window: + logger.info( + "[rocketchat] V8.3-3: Widerspruch erkannt in room %s — " + "%.0fs nach %s-Route, hole Thema zurück", + room_id[:8], elapsed, route_source, + ) + target_room_id = route_info["target_room"] + origin_room_id = route_info["origin_room"] + # a. Thema aus Zielraum entfernen (delete/edit) + target_msg_id = route_info.get("target_message_id", "") + if target_msg_id: + if not self.rest.delete_message(target_room_id, target_msg_id): + self.rest.update_message( + target_room_id, target_msg_id, "_(Zurückgezogen)_" + ) + # b. Thema im Ursprungsraum wieder aufnehmen + if route_source == "confirm": + # FIX 4: Bei confirm_move — Rückhol-Text mit Original + origin_name = self._room_info.get(origin_room_id, {}).get("name", "Ursprungsraum") + target_name = self._room_info.get(target_room_id, {}).get("name", "Zielraum") + rueckhol_text = ( + f"↩️ Zurückgeholt aus #{target_name.lstrip('#')}\n" + f"{display_text}" + ) + await self._post_message_with_retry(origin_room_id, rueckhol_text) + routing_counter.increment('widerspruch_confirm_move_route') + else: + await self._post_message_with_retry( + room_id, + "👍 Verstanden — das Thema gehört hier her. Ich bleibe hier." + ) + # c. _CURRENT_ORIGIN_ROOM zurück auf Ursprungsraum + _CURRENT_ORIGIN_ROOM.set(origin_room_id) + _THEMATIC_TARGET_ROOM.set("") + # P1: _room_context als persistenter Fallback + _set_room_context_origin(f"user:{username}", origin_room_id) + # d. Sticky löschen + self._session_room_preferences.pop(origin_room_id, None) + # e. Ring: move_gc(target → origin) — Rückholung + if _MULTIROOM() and self._multiroom_context is not None: + route_topic = route_info.get("topic", "") + if route_topic: + await self._multiroom_context.move_gc( + origin_room_id=target_room_id, + target_room_id=origin_room_id, + topic=route_topic, + room_name=self._room_info.get(origin_room_id, {}).get("name", ""), + ) + # f. KEIN Lernen + # g. Cleanup + del self._recent_auto_routes[origin_room_id] + # Dispatch im Ursprungsraum + await self._dispatch_agent( + text=display_text, + room_id=origin_room_id, + room_name=self._room_info.get(origin_room_id, {}).get("name", room_name), + room_type=self._room_info.get(origin_room_id, {}).get("type", room_type), + username=username, + msg_id=msg_id, + msg_obj=msg_obj, + is_button_response=is_button_response, category="", ) return + else: + # Zeitfenster abgelaufen → aufräumen + origin_rid = route_info.get("origin_room", room_id) + self._recent_auto_routes.pop(origin_rid, None) - # ── 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(routing_text) + # ── V8.3-4: Expliziter Raumwechsel (BEWUSSTE ENTSCHEIDUNG) ──────── + # V8.3.4 B3: Verb-basierte Erkennung statt #-Pflicht. + # Pattern: 'lass uns in wechseln', 'wechseln nach ', etc. + # kann mit oder ohne # sein. Validierung via room-map.json. + _EXPLICIT_SWITCH_RE = re.compile( + r'(?:lass uns |gehen wir |wechsel(?:n)? )?(?:in |nach )?#?(\w[\w-]*)', + re.IGNORECASE, + ) + _SWITCH_TRIGGERS = [ + 'lass uns in', 'gehen wir in', 'wechseln nach', 'wechsel in', + 'raum wechseln', 'wechseln in', + ] + # V8.3.1 F3: Negativ-Liste — Phrasen die KEIN Raumwechsel sind + _SWITCH_NEGATIV = [ + 'in den', 'ins bett', 'ins kino', 'zur seite', 'zur bank', + 'nach hause', 'nach oben', 'nach unten', 'nach links', 'nach rechts', + 'nach vorne', 'nach hinten', 'in die', 'in das', 'zum arzt', + ] + is_explicit_switch = any(trigger in text_lower for trigger in _SWITCH_TRIGGERS) + # V8.3.1 F3: Negativ-Check — wenn Negativ-Phrase enthalten → kein Switch + if is_explicit_switch: + if any(neg in text_lower for neg in _SWITCH_NEGATIV): + is_explicit_switch = False + target_room_id = "" + target_room_display = "" + if is_explicit_switch and _MULTIROOM() and self.archivar is not None: + switch_match = _EXPLICIT_SWITCH_RE.search(text) + if switch_match: + switch_room_name = switch_match.group(1).lower() + # V8.3.4 B3: Keine #-Pflicht mehr — stattdessen room-map-Validierung. + # Raum aus room-map.json auflösen (name → room_id), case-insensitive. + room_map = self.archivar._room_map + if room_map is not None: + for rid, entry in room_map.rooms.items(): + entry_name = entry.name.lstrip('#').lower().replace(' ', '-') + # V8.3.4.1 F1: Exakter Match statt Substring-Injection. + # 'Plugin' darf NICHT 'Rocketchat-Plugin' matchen. + if switch_room_name == entry_name or any( + kw.lower() == switch_room_name for kw in entry.keywords_100 + ): + target_room_id = rid + target_room_display = entry.name + break + # V8.3.4 B3: Nur auslösen wenn Raum in room-map.json existiert + if not target_room_id: + logger.debug( + "[rocketchat] V8.3-4: Raum '%s' nicht in room-map.json — " + "kein expliziter Raumwechsel", + switch_room_name, + ) + is_explicit_switch = False + else: + is_explicit_switch = False + if is_explicit_switch and target_room_id and target_room_id != room_id: + logger.info( + "[rocketchat] V8.3-4: Expliziter Raumwechsel — " + "'%s' → %s (%s)", + text[:80], target_room_display, target_room_id[:8], + ) + # a. _CURRENT_ORIGIN_ROOM auf Zielraum setzen + _CURRENT_ORIGIN_ROOM.set(target_room_id) + _THEMATIC_TARGET_ROOM.set(target_room_id) + # P1: _room_context als persistenter Fallback + _set_room_context_origin(f"user:{username}", target_room_id) + # b. Sticky setzen: 30 Min, sticky_topic = 'explizit-wechsel' + self._session_room_preferences[room_id] = { + "target_room": target_room_id, + "target_name": target_room_display, + "sticky_topic": "explizit-wechsel", + "expires_at": time.time() + 1800, # 30 Min + } + logger.info( + "[rocketchat] V8.3-4: Expliziter Wechsel-Sticky gesetzt — " + "room=%s → target=%s (30 Min)", + room_id[:8], target_room_display[:20], + ) + # c. Agent antwortet im Zielraum + await self._post_message_with_retry( + target_room_id, + f"Gerne, wir sind jetzt in {target_room_display}. " + f"Was möchtest du besprechen?" + ) + # Dispatch im Zielraum + target_room_info = self._room_info.get(target_room_id, {}) + target_room_name_disp = target_room_info.get("name", target_room_display) + target_room_type = target_room_info.get("type", "c") + await self._dispatch_agent( + text=display_text, + room_id=target_room_id, + room_name=target_room_name_disp, + room_type=target_room_type, + username=username, + msg_id=msg_id, + msg_obj=msg_obj, + is_button_response=is_button_response, + category="", + ) + return - logger.debug("[rocketchat] ARCHIVAR-DEBUG: Entering Archivar block — room_type=%s, is_auftrag=%s, _MULTIROOM=%s, archivar=%s", room_type, is_auftrag, _MULTIROOM(), self.archivar is not None) + # ── 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(routing_text) - # V8.4.3: Flag für zentrale classify_and_route-Aufrufstelle. - # Intentional bypass paths setzen False. Fall-through paths - # (Sticky-Bypass, B2-No-Topic, Expliziter-Wechsel-ohne-#) behalten True. - _should_classify = True + logger.debug("[rocketchat] ARCHIVAR-DEBUG: Entering Archivar block — room_type=%s, is_auftrag=%s, _MULTIROOM=%s, archivar=%s", room_type, is_auftrag, _MULTIROOM(), self.archivar is not None) - try: - if _MULTIROOM() and self.archivar is not None: - 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) - logger.debug("[rocketchat] ARCHIVAR-DEBUG: Archivar bypassed — pending_questions") - routing_counter.increment('pending_questions_bypass') - logger.info("ROUTING BYPASS: reason=pending_questions_bypass, origin_room=%s", room_id) - self._rooms_with_pending_questions.discard(room_id) - _should_classify = False - elif self.archivar._state.should_stay_in_room(room_id) == "always": - # Bug 4 fix: Persistierte Entscheidung (always) aus ArchivarState lesen. - # P0-B: "never_route" ist jetzt thematisch (v7) — wird im Router - # pro Thema geprüft, nicht mehr als Raum-Level-Bypass. - # Nur "always" bypassed Archivar komplett. - logger.debug("[rocketchat] Room %s has persisted decision=always — Archivar bypassed", room_id[:8]) - logger.debug("[rocketchat] ARCHIVAR-DEBUG: Archivar bypassed — persisted_state=always") - _should_classify = False - elif room_type == "d": - # V8.5: DM-Routing differenziert — 100%-Keywords werden - # erkannt und lösen einen Move-Request (Butler) aus. - # Kein 100%-Keyword → Catch-All (LLM antwortet im DM). - # Der Router (classify_and_route) entscheidet selbstständig. - logger.debug("[rocketchat] DM von %s — Archivar läuft (100%%-Keyword-Check)", username) - logger.debug("[rocketchat] ARCHIVAR-DEBUG: DM — Archivar aktiv (100%%-Keywords → Butler, Rest → Catch-All)") - # _should_classify bleibt True — Router wird aufgerufen - elif room_id in self._session_room_preferences: - # V8.3-5: Topic-Scoped Sticky — Auto-Route nur bei gleichem Thema - pref = self._session_room_preferences[room_id] - if time.time() < pref["expires_at"]: - target_room_id = pref["target_room"] - target_name = pref.get("target_name", "Zielraum") - sticky_topic = pref.get("sticky_topic", "") - # ── V8.3-5: Topic-Scoping — Thema aus aktueller Nachricht extrahieren ── - current_topic = "" - if sticky_topic and _MULTIROOM() and self.archivar is not None: - # Extrahiere Thema via 100%-Keyword-Match gegen alle Räume - matched_room = self.archivar._room_map.find_room_by_keywords( - text, origin_room_id=room_id - ) - if matched_room is not None: - current_topic = room_name_to_topic(matched_room.name) - # ── V8.3-5: Topic-Vergleich ────────────────────── - if sticky_topic and current_topic and current_topic != sticky_topic: - # Thema ≠ sticky_topic → STAY, Sticky ignorieren, normale Auswertung - logger.info( - "[rocketchat] V8.3-5: Topic mismatch — sticky_topic='%s', " - "current_topic='%s' → ignoring sticky, falling through to Archivar", - sticky_topic, current_topic, - ) - # Sticky NICHT löschen — könnte später wieder matchen - # Fall through to Archivar classification - elif sticky_topic and not current_topic: - # V8.3.4 B2: Kein 100%-Keyword-Match → Sticky darf NICHT greifen - # 'Kein Thema' ≠ 'gleiches Thema'. STAY, normale Auswertung. - logger.info( - "[rocketchat] V8.3.4 B2: No topic extracted from message — " - "sticky_topic='%s' but no 100%% keyword match → ignoring sticky, " - "falling through to Archivar", - sticky_topic, - ) - # Fall through to Archivar classification - else: - # Thema matcht → Sticky greift - # V8.1.1 R1: Catch-All-Guard — nicht in Catch-All-Raum auto-routen - if self.archivar is not None and self.archivar._room_map is not None: - target_entry = self.archivar._room_map.get_room_by_id(target_room_id) - if target_entry and target_entry.catch_all: + # V8.4.3: Flag für zentrale classify_and_route-Aufrufstelle. + # Intentional bypass paths setzen False. Fall-through paths + # (Sticky-Bypass, B2-No-Topic, Expliziter-Wechsel-ohne-#) behalten True. + _should_classify = True + + try: + if _MULTIROOM() and self.archivar is not None: + 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) + logger.debug("[rocketchat] ARCHIVAR-DEBUG: Archivar bypassed — pending_questions") + routing_counter.increment('pending_questions_bypass') + logger.info("ROUTING BYPASS: reason=pending_questions_bypass, origin_room=%s", room_id) + self._rooms_with_pending_questions.discard(room_id) + _should_classify = False + elif self.archivar._state.should_stay_in_room(room_id) == "always": + # Bug 4 fix: Persistierte Entscheidung (always) aus ArchivarState lesen. + # P0-B: "never_route" ist jetzt thematisch (v7) — wird im Router + # pro Thema geprüft, nicht mehr als Raum-Level-Bypass. + # Nur "always" bypassed Archivar komplett. + logger.debug("[rocketchat] Room %s has persisted decision=always — Archivar bypassed", room_id[:8]) + logger.debug("[rocketchat] ARCHIVAR-DEBUG: Archivar bypassed — persisted_state=always") + _should_classify = False + elif room_type == "d": + # V8.5: DM-Routing differenziert — 100%-Keywords werden + # erkannt und lösen einen Move-Request (Butler) aus. + # Kein 100%-Keyword → Catch-All (LLM antwortet im DM). + # Der Router (classify_and_route) entscheidet selbstständig. + logger.debug("[rocketchat] DM von %s — Archivar läuft (100%%-Keyword-Check)", username) + logger.debug("[rocketchat] ARCHIVAR-DEBUG: DM — Archivar aktiv (100%%-Keywords → Butler, Rest → Catch-All)") + # _should_classify bleibt True — Router wird aufgerufen + elif room_id in self._session_room_preferences: + # V8.3-5: Topic-Scoped Sticky — Auto-Route nur bei gleichem Thema + pref = self._session_room_preferences[room_id] + if time.time() < pref["expires_at"]: + target_room_id = pref["target_room"] + target_name = pref.get("target_name", "Zielraum") + sticky_topic = pref.get("sticky_topic", "") + # ── V8.3-5: Topic-Scoping — Thema aus aktueller Nachricht extrahieren ── + current_topic = "" + if sticky_topic and _MULTIROOM() and self.archivar is not None: + # Extrahiere Thema via 100%-Keyword-Match gegen alle Räume + matched_room = self.archivar._room_map.find_room_by_keywords( + text, origin_room_id=room_id + ) + if matched_room is not None: + current_topic = room_name_to_topic(matched_room.name) + # ── V8.3-5: Topic-Vergleich ────────────────────── + if sticky_topic and current_topic and current_topic != sticky_topic: + # Thema ≠ sticky_topic → STAY, Sticky ignorieren, normale Auswertung + logger.info( + "[rocketchat] V8.3-5: Topic mismatch — sticky_topic='%s', " + "current_topic='%s' → ignoring sticky, falling through to Archivar", + sticky_topic, current_topic, + ) + # Sticky NICHT löschen — könnte später wieder matchen + # Fall through to Archivar classification + elif sticky_topic and not current_topic: + # V8.3.4 B2: Kein 100%-Keyword-Match → Sticky darf NICHT greifen + # 'Kein Thema' ≠ 'gleiches Thema'. STAY, normale Auswertung. + logger.info( + "[rocketchat] V8.3.4 B2: No topic extracted from message — " + "sticky_topic='%s' but no 100%% keyword match → ignoring sticky, " + "falling through to Archivar", + sticky_topic, + ) + # Fall through to Archivar classification + else: + # Thema matcht → Sticky greift + # V8.1.1 R1: Catch-All-Guard — nicht in Catch-All-Raum auto-routen + if self.archivar is not None and self.archivar._room_map is not None: + target_entry = self.archivar._room_map.get_room_by_id(target_room_id) + if target_entry and target_entry.catch_all: + logger.debug( + "[rocketchat] V8.1.1 R1: Topic-Scoped Sticky target %s is catch_all — " + "skipping auto-route, falling through to Archivar", + target_name[:20], + ) + # Sticky aufräumen — nicht mehr gültig + del self._session_room_preferences[room_id] + # Fall through to Archivar classification + else: + # V8.1.1 R1: stay_in_room-Guard — nicht routen wenn Raum stay_in_room hat + origin_state = self.archivar._state.should_stay_in_room(room_id) + if origin_state in ("always", "never_route"): logger.debug( - "[rocketchat] V8.1.1 R1: Topic-Scoped Sticky target %s is catch_all — " - "skipping auto-route, falling through to Archivar", - target_name[:20], + "[rocketchat] V8.1.1 R1: Topic-Scoped Sticky origin room %s has " + "stay_in_room=%s — skipping auto-route, falling through to Archivar", + room_id[:8], origin_state, ) - # Sticky aufräumen — nicht mehr gültig del self._session_room_preferences[room_id] # Fall through to Archivar classification else: - # V8.1.1 R1: stay_in_room-Guard — nicht routen wenn Raum stay_in_room hat - origin_state = self.archivar._state.should_stay_in_room(room_id) - if origin_state in ("always", "never_route"): - logger.debug( - "[rocketchat] V8.1.1 R1: Topic-Scoped Sticky origin room %s has " - "stay_in_room=%s — skipping auto-route, falling through to Archivar", - room_id[:8], origin_state, - ) - del self._session_room_preferences[room_id] - # Fall through to Archivar classification - else: - # Guards passed — auto-route - # V8.3.4 B1: Ankündigung im Ursprungsraum posten - target_display = target_name.lstrip('#') if target_name else "Zielraum" - announcement = _build_announcement(target_display) - await self._post_message_with_retry(room_id, announcement) - logger.info( - "[rocketchat] V8.3-1: Auto-Route announcement in origin room %s → %s", - room_id[:8], target_display, - ) - # V8.3.4 B4: Telemetrie im Sticky-Pfad - routing_telemetry.record( - stage='sticky', score=1.0, decision='route', - target=target_room_id, origin=room_id, - duration_ms=0.0, - ) - routing_telemetry.flush() - # Kopiere Nachricht in den Zielraum - # P1: display_text (mit Quote) für Zielraum-Kopie - target_txt = f"*(Auftrag von @{username}, Topic-Sticky)*\n{display_text}" - await self._post_message_with_retry(target_room_id, target_txt) - _CURRENT_ORIGIN_ROOM.set(target_room_id) - _THEMATIC_TARGET_ROOM.set(target_room_id) - # P1: _room_context als persistenter Fallback - _set_room_context_origin(f"user:{username}", target_room_id) - routing_counter.increment('session_sticky_auto_route') - logger.info( - "[rocketchat] V8.3-5: Topic-Scoped Sticky active — " - "auto-routing '%s' → %s, topic='%s' (%.0fs remaining)", - display_text[:80], target_name, sticky_topic, - pref["expires_at"] - time.time(), - ) - # Dispatch direkt — kein Archivar - target_room_info = self._room_info.get(target_room_id, {}) - target_room_name = target_room_info.get("name", target_name) - target_room_type = target_room_info.get("type", "c") - await self._dispatch_agent( - text=display_text, - room_id=target_room_id, - room_name=target_room_name, - room_type=target_room_type, - username=username, - msg_id=msg_id, - msg_obj=msg_obj, - is_button_response=is_button_response, - category="work_order", - ) - return - else: - # Kein Archivar/RoomMap — direkt routen (Fallback) - # V8.3.4 B1: Ankündigung im Ursprungsraum posten - target_display = target_name.lstrip('#') if target_name else "Zielraum" - announcement = _build_announcement(target_display) - await self._post_message_with_retry(room_id, announcement) - logger.info( - "[rocketchat] V8.3-1: Auto-Route announcement in origin room %s → %s", - room_id[:8], target_display, - ) - # V8.3.4 B4: Telemetrie im Sticky-Pfad - routing_telemetry.record( - stage='sticky', score=1.0, decision='route', - target=target_room_id, origin=room_id, - duration_ms=0.0, - ) - routing_telemetry.flush() - # P1: display_text (mit Quote) für Zielraum-Kopie - target_txt = f"*(Auftrag von @{username}, Topic-Sticky)*\n{display_text}" - await self._post_message_with_retry(target_room_id, target_txt) - _CURRENT_ORIGIN_ROOM.set(target_room_id) - _THEMATIC_TARGET_ROOM.set(target_room_id) - # P1: _room_context als persistenter Fallback - _set_room_context_origin(f"user:{username}", target_room_id) - routing_counter.increment('session_sticky_auto_route') - logger.info( - "[rocketchat] V8.3-5: Topic-Scoped Sticky active — " - "auto-routing '%s' → %s, topic='%s' (%.0fs remaining)", - display_text[:80], target_name, sticky_topic, - pref["expires_at"] - time.time(), - ) - # Dispatch direkt — kein Archivar - target_room_info = self._room_info.get(target_room_id, {}) - target_room_name = target_room_info.get("name", target_name) - target_room_type = target_room_info.get("type", "c") - await self._dispatch_agent( - text=display_text, - room_id=target_room_id, - room_name=target_room_name, - room_type=target_room_type, - username=username, - msg_id=msg_id, - msg_obj=msg_obj, - is_button_response=is_button_response, - category="work_order", - ) - return - else: - # Abgelaufen → aufräumen - del self._session_room_preferences[room_id] - logger.debug( - "[rocketchat] V8.1 P2: Topic-Scoped Sticky expired for room %s", - room_id[:8], - ) - # V8.4.3: Kein else mehr — classify_and_route wird zentral - # nach der if/elif-Kette aufgerufen, wenn _should_classify=True. - # Fall-through paths (Sticky-Bypass, B2-No-Topic, Expired Sticky) - # behalten _should_classify=True und erreichen classify_and_route. - # ── V8.4.3: Zentrale classify_and_route-Aufrufstelle ────────── - # Alle Fall-through-Pfade (Sticky-Bypass, B2-No-Topic, - # Expliziter-Wechsel-ohne-#, Expired Sticky) landen hier. - if _should_classify: - logger.debug("[rocketchat] ARCHIVAR-DEBUG: Calling classify_and_route for room=%s", room_id[:12]) - # P0-FIX: is_dm=True bei DMs — der Router braucht das für den DM-Guard. - # room_type wird in L1579 aus self._room_info gelesen. - _is_dm = (room_type == "d") - # P0: routing_text (ohne Quote) für Klassifikation verwenden - decision = await self.archivar.classify_and_route(routing_text, origin_room_id=room_id, is_dm=_is_dm) - # V8.3.3: Telemetrie nach jeder Routing-Entscheidung flushen - routing_telemetry.flush() - if decision and decision.category: - category = decision.category - # Wenn Zielraum = Ursprungsraum → stay_in_room, kein Move-Request - # MUSS VOR _THEMATIC_TARGET_ROOM.set() kommen, sonst wird - # der Zielraum gesetzt und send() routet in den DM - if (hasattr(decision, 'target_room') and decision.target_room - and decision.target_room == room_id): - decision.stay_in_room = True - decision.move_request_sent = False - # ── Archivar-Kontext-Weitergabe: Zielraum + Frage-Nr ────── - # P0-BUGFIX: Nur setzen wenn NICHT stay_in_room. - # Bei stay_in_room=True (Meta-Fragen, Smalltalk, etc.) - # bleibt der Agent im Ursprungsraum — kein Zielraum nötig. - if (hasattr(decision, 'target_room') and decision.target_room - and not getattr(decision, 'stay_in_room', False)): - _THEMATIC_TARGET_ROOM.set(decision.target_room) - global _question_counter - with _question_counter_lock: - _question_counter += 1 - # ── Ende Kontext-Weitergabe ────────────────────────────── - # Archivar v4 Move-Request: _pending_move_requests befüllen, damit - # der Button-Response-Handler (lines 717-764) die Antwort korrekt - # verarbeiten und _CURRENT_ORIGIN_ROOM auf den Zielraum setzen kann. - if (getattr(decision, 'move_request_sent', False) - and hasattr(decision, 'target_room') - and decision.target_room): - self._pending_move_requests[room_id] = { - # P1: display_text (mit Quote) für Move-Request speichern - 'text': display_text, - 'origin_room': room_id, - 'target_room': decision.target_room, - 'target_name': getattr( - decision, 'move_request_target_name', 'Zielraum'), - 'username': username, - 'message_id': msg_id, - } - # ── V8.6: PresenceEngine — Move-Request pending → away ── - target_name = getattr(decision, 'move_request_target_name', 'Zielraum') - if _has_presence: - self._presence_engine.set_move_request_pending(room_id, target_name) - self._presence_engine.update_presence() - # Lernsystem: Keywords für Feedback-Loop speichern - if hasattr(decision, 'matched_keywords') and decision.matched_keywords: - self.archivar._routed_messages[msg_id] = { - "keywords": decision.matched_keywords, - "target_room": decision.target_room, - "origin_room": room_id, # P-058: für reject-Feedback benötigt - "timestamp": time.time() - } - except asyncio.TimeoutError: - logger.warning("[rocketchat] Archivar classify_and_route() timed out") - with _question_counter_lock: - _question_counter += 1 - except Exception as e: - routing_counter.increment('exception_fallback') - logger.info("ROUTING BYPASS: reason=exception_fallback, origin_room=%s", room_id) - logger.debug("[rocketchat] Archivar classification skipped: %s", e) + # Guards passed — auto-route + # V8.3.4 B1: Ankündigung im Ursprungsraum posten + target_display = target_name.lstrip('#') if target_name else "Zielraum" + announcement = _build_announcement(target_display) + await self._post_message_with_retry(room_id, announcement) + logger.info( + "[rocketchat] V8.3-1: Auto-Route announcement in origin room %s → %s", + room_id[:8], target_display, + ) + # V8.3.4 B4: Telemetrie im Sticky-Pfad + routing_telemetry.record( + stage='sticky', score=1.0, decision='route', + target=target_room_id, origin=room_id, + duration_ms=0.0, + ) + routing_telemetry.flush() + # Kopiere Nachricht in den Zielraum + # P1: display_text (mit Quote) für Zielraum-Kopie + target_txt = f"*(Auftrag von @{username}, Topic-Sticky)*\n{display_text}" + await self._post_message_with_retry(target_room_id, target_txt) + _CURRENT_ORIGIN_ROOM.set(target_room_id) + _THEMATIC_TARGET_ROOM.set(target_room_id) + # P1: _room_context als persistenter Fallback + _set_room_context_origin(f"user:{username}", target_room_id) + routing_counter.increment('session_sticky_auto_route') + logger.info( + "[rocketchat] V8.3-5: Topic-Scoped Sticky active — " + "auto-routing '%s' → %s, topic='%s' (%.0fs remaining)", + display_text[:80], target_name, sticky_topic, + pref["expires_at"] - time.time(), + ) + # Dispatch direkt — kein Archivar + target_room_info = self._room_info.get(target_room_id, {}) + target_room_name = target_room_info.get("name", target_name) + target_room_type = target_room_info.get("type", "c") + await self._dispatch_agent( + text=display_text, + room_id=target_room_id, + room_name=target_room_name, + room_type=target_room_type, + username=username, + msg_id=msg_id, + msg_obj=msg_obj, + is_button_response=is_button_response, + category="work_order", + ) + return + else: + # Kein Archivar/RoomMap — direkt routen (Fallback) + # V8.3.4 B1: Ankündigung im Ursprungsraum posten + target_display = target_name.lstrip('#') if target_name else "Zielraum" + announcement = _build_announcement(target_display) + await self._post_message_with_retry(room_id, announcement) + logger.info( + "[rocketchat] V8.3-1: Auto-Route announcement in origin room %s → %s", + room_id[:8], target_display, + ) + # V8.3.4 B4: Telemetrie im Sticky-Pfad + routing_telemetry.record( + stage='sticky', score=1.0, decision='route', + target=target_room_id, origin=room_id, + duration_ms=0.0, + ) + routing_telemetry.flush() + # P1: display_text (mit Quote) für Zielraum-Kopie + target_txt = f"*(Auftrag von @{username}, Topic-Sticky)*\n{display_text}" + await self._post_message_with_retry(target_room_id, target_txt) + _CURRENT_ORIGIN_ROOM.set(target_room_id) + _THEMATIC_TARGET_ROOM.set(target_room_id) + # P1: _room_context als persistenter Fallback + _set_room_context_origin(f"user:{username}", target_room_id) + routing_counter.increment('session_sticky_auto_route') + logger.info( + "[rocketchat] V8.3-5: Topic-Scoped Sticky active — " + "auto-routing '%s' → %s, topic='%s' (%.0fs remaining)", + display_text[:80], target_name, sticky_topic, + pref["expires_at"] - time.time(), + ) + # Dispatch direkt — kein Archivar + target_room_info = self._room_info.get(target_room_id, {}) + target_room_name = target_room_info.get("name", target_name) + target_room_type = target_room_info.get("type", "c") + await self._dispatch_agent( + text=display_text, + room_id=target_room_id, + room_name=target_room_name, + room_type=target_room_type, + username=username, + msg_id=msg_id, + msg_obj=msg_obj, + is_button_response=is_button_response, + category="work_order", + ) + return + else: + # Abgelaufen → aufräumen + del self._session_room_preferences[room_id] + logger.debug( + "[rocketchat] V8.1 P2: Topic-Scoped Sticky expired for room %s", + room_id[:8], + ) + # V8.4.3: Kein else mehr — classify_and_route wird zentral + # nach der if/elif-Kette aufgerufen, wenn _should_classify=True. + # Fall-through paths (Sticky-Bypass, B2-No-Topic, Expired Sticky) + # behalten _should_classify=True und erreichen classify_and_route. + # ── V8.4.3: Zentrale classify_and_route-Aufrufstelle ────────── + # Alle Fall-through-Pfade (Sticky-Bypass, B2-No-Topic, + # Expliziter-Wechsel-ohne-#, Expired Sticky) landen hier. + if _should_classify: + logger.debug("[rocketchat] ARCHIVAR-DEBUG: Calling classify_and_route for room=%s", room_id[:12]) + # P0-FIX: is_dm=True bei DMs — der Router braucht das für den DM-Guard. + # room_type wird in L1579 aus self._room_info gelesen. + _is_dm = (room_type == "d") + # P0: routing_text (ohne Quote) für Klassifikation verwenden + decision = await self.archivar.classify_and_route(routing_text, origin_room_id=room_id, is_dm=_is_dm) + # V8.3.3: Telemetrie nach jeder Routing-Entscheidung flushen + routing_telemetry.flush() + if decision and decision.category: + category = decision.category + # Wenn Zielraum = Ursprungsraum → stay_in_room, kein Move-Request + # MUSS VOR _THEMATIC_TARGET_ROOM.set() kommen, sonst wird + # der Zielraum gesetzt und send() routet in den DM + if (hasattr(decision, 'target_room') and decision.target_room + and decision.target_room == room_id): + decision.stay_in_room = True + decision.move_request_sent = False + # ── Archivar-Kontext-Weitergabe: Zielraum + Frage-Nr ────── + # P0-BUGFIX: Nur setzen wenn NICHT stay_in_room. + # Bei stay_in_room=True (Meta-Fragen, Smalltalk, etc.) + # bleibt der Agent im Ursprungsraum — kein Zielraum nötig. + if (hasattr(decision, 'target_room') and decision.target_room + and not getattr(decision, 'stay_in_room', False)): + _THEMATIC_TARGET_ROOM.set(decision.target_room) + global _question_counter + with _question_counter_lock: + _question_counter += 1 + # ── Ende Kontext-Weitergabe ────────────────────────────── + # Archivar v4 Move-Request: _pending_move_requests befüllen, damit + # der Button-Response-Handler (lines 717-764) die Antwort korrekt + # verarbeiten und _CURRENT_ORIGIN_ROOM auf den Zielraum setzen kann. + if (getattr(decision, 'move_request_sent', False) + and hasattr(decision, 'target_room') + and decision.target_room): + self._pending_move_requests[room_id] = { + # P1: display_text (mit Quote) für Move-Request speichern + 'text': display_text, + 'origin_room': room_id, + 'target_room': decision.target_room, + 'target_name': getattr( + decision, 'move_request_target_name', 'Zielraum'), + 'username': username, + 'message_id': msg_id, + } + # ── V8.6: PresenceEngine — Move-Request pending → away ── + target_name = getattr(decision, 'move_request_target_name', 'Zielraum') + if _has_presence: + self._presence_engine.set_move_request_pending(room_id, target_name) + self._presence_engine.update_presence() + # Lernsystem: Keywords für Feedback-Loop speichern + if hasattr(decision, 'matched_keywords') and decision.matched_keywords: + self.archivar._routed_messages[msg_id] = { + "keywords": decision.matched_keywords, + "target_room": decision.target_room, + "origin_room": room_id, # P-058: für reject-Feedback benötigt + "timestamp": time.time() + } + except asyncio.TimeoutError: + logger.warning("[rocketchat] Archivar classify_and_route() timed out") + with _question_counter_lock: + _question_counter += 1 + except Exception as e: + routing_counter.increment('exception_fallback') + logger.info("ROUTING BYPASS: reason=exception_fallback, origin_room=%s", room_id) + logger.debug("[rocketchat] Archivar classification skipped: %s", e) - # ── User-Flow C: Nachricht kopieren, Antwort IMMER hier ──────── - # V7-1: Wenn move_request_sent=True, KEIN Agent-Dispatch. - # Der Agent wird erst nach Button-Bestätigung (✅Ja) dispatched, - # dann mit _CURRENT_ORIGIN_ROOM auf den Zielraum gesetzt. - if decision and getattr(decision, 'move_request_sent', False): - logger.info( - "[rocketchat] V7-1: Move-Request pending for '%s' → %s — " - "skipping agent dispatch, waiting for button confirmation", - text[:80], getattr(decision, 'move_request_target_name', '?'), - ) - routing_counter.increment('move_request_pending_guard') - logger.info("ROUTING BYPASS: reason=move_request_pending_guard, origin_room=%s", room_id) - return + # ── User-Flow C: Nachricht kopieren, Antwort IMMER hier ──────── + # V7-1: Wenn move_request_sent=True, KEIN Agent-Dispatch. + # Der Agent wird erst nach Button-Bestätigung (✅Ja) dispatched, + # dann mit _CURRENT_ORIGIN_ROOM auf den Zielraum gesetzt. + if decision and getattr(decision, 'move_request_sent', False): + logger.info( + "[rocketchat] V7-1: Move-Request pending for '%s' → %s — " + "skipping agent dispatch, waiting for button confirmation", + text[:80], getattr(decision, 'move_request_target_name', '?'), + ) + routing_counter.increment('move_request_pending_guard') + logger.info("ROUTING BYPASS: reason=move_request_pending_guard, origin_room=%s", room_id) + return - # V8.1 P1: 100%-Keyword-Route / FAISS-Auto-Route → echtes Routing - # Wenn move_request_sent=False ABER target_room gesetzt (nicht self-match): - # Antwort WIRKLICH in den Zielraum senden, Nachricht rüberkopieren. - forwarded = False - if (decision and hasattr(decision, 'target_room') and decision.target_room - and not getattr(decision, 'move_request_sent', False) - and decision.target_room != room_id): - target_room_id = decision.target_room - target_name = getattr(decision, 'move_request_target_name', 'Zielraum') - # ── V8.3-5: Topic für Sticky extrahieren ────────────────── - # V8.3.1 F4: Vereinheitlicht auf room_name_to_topic(target_name) - # statt matched_keywords[0] — konsistent mit current_topic-Berechnung. - sticky_topic = room_name_to_topic(target_name) if target_name else "" - # ── V8.3-1: Ankündigung im Ursprungsraum VOR Zielraum-Post ── - # V8.3.4 B5: Zufällige Variante aus 5 Formulierungen. - target_display = target_name.lstrip('#') if target_name else "Zielraum" - announcement = _build_announcement(target_display) - await self._post_message_with_retry(room_id, announcement) - logger.info( - "[rocketchat] V8.3-1: Auto-Route announcement in origin room %s → %s", - room_id[:8], target_display, - ) - # ── V8.3-2: Echtes Move — delete_message mit Fallback-Kette ── - # Versuche Originalnachricht zu löschen/ersetzen - move_success = False - if msg_id: - # a. delete_message (falls Permission vorhanden) - if self.rest.delete_message(room_id, msg_id): + # V8.1 P1: 100%-Keyword-Route / FAISS-Auto-Route → echtes Routing + # Wenn move_request_sent=False ABER target_room gesetzt (nicht self-match): + # Antwort WIRKLICH in den Zielraum senden, Nachricht rüberkopieren. + forwarded = False + if (decision and hasattr(decision, 'target_room') and decision.target_room + and not getattr(decision, 'move_request_sent', False) + and decision.target_room != room_id): + target_room_id = decision.target_room + target_name = getattr(decision, 'move_request_target_name', 'Zielraum') + # ── V8.3-5: Topic für Sticky extrahieren ────────────────── + # V8.3.1 F4: Vereinheitlicht auf room_name_to_topic(target_name) + # statt matched_keywords[0] — konsistent mit current_topic-Berechnung. + sticky_topic = room_name_to_topic(target_name) if target_name else "" + # ── V8.3-1: Ankündigung im Ursprungsraum VOR Zielraum-Post ── + # V8.3.4 B5: Zufällige Variante aus 5 Formulierungen. + target_display = target_name.lstrip('#') if target_name else "Zielraum" + announcement = _build_announcement(target_display) + await self._post_message_with_retry(room_id, announcement) + logger.info( + "[rocketchat] V8.3-1: Auto-Route announcement in origin room %s → %s", + room_id[:8], target_display, + ) + # ── V8.3-2: Echtes Move — delete_message mit Fallback-Kette ── + # Versuche Originalnachricht zu löschen/ersetzen + move_success = False + if msg_id: + # a. delete_message (falls Permission vorhanden) + if self.rest.delete_message(room_id, msg_id): + move_success = True + logger.info( + "[rocketchat] V8.3-2: Original message deleted in origin room %s", + room_id[:8], + ) + else: + # b. Fallback: update_message → ersetze durch Hinweis + fallback_text = f"Wir sind rübergewechselt → #{target_display}" + if self.rest.update_message(room_id, msg_id, fallback_text): move_success = True logger.info( - "[rocketchat] V8.3-2: Original message deleted in origin room %s", + "[rocketchat] V8.3-2: Original message edited in origin room %s", room_id[:8], ) else: - # b. Fallback: update_message → ersetze durch Hinweis - fallback_text = f"Wir sind rübergewechselt → #{target_display}" - if self.rest.update_message(room_id, msg_id, fallback_text): - move_success = True - logger.info( - "[rocketchat] V8.3-2: Original message edited in origin room %s", - room_id[:8], - ) - else: - # c. Letzter Fallback: Nur Hinweis-Post (bereits gesendet) - logger.info( - "[rocketchat] V8.3-2: Move fallback — announcement only in room %s", - room_id[:8], - ) - # Kopiere Nachricht in den Zielraum - # P1: display_text (mit Quote) für Zielraum-Kopie - target_txt = f"*(Auftrag von @{username}, automatisch geroutet)*\n{display_text}" - target_message_id = await self._post_message_with_retry(target_room_id, target_txt) - # Setze _CURRENT_ORIGIN_ROOM auf Zielraum → Agent antwortet dort - _CURRENT_ORIGIN_ROOM.set(target_room_id) - _THEMATIC_TARGET_ROOM.set(target_room_id) - # P1: _room_context als persistenter Fallback - _set_room_context_origin(f"user:{username}", target_room_id) - forwarded = True - routing_counter.increment('auto_route_dispatched') - logger.info( - "[rocketchat] V8.1 P1: Auto-Route '%s' → %s — " - "Agent dispatched in target room", - display_text[:80], target_name, - ) - # V8.1.1 R2: Ring-GC bei Auto-Route — stale Topics aus Ursprungsraum entfernen - if _MULTIROOM() and self._multiroom_context is not None: - auto_topic = text[:80].replace("\n", " ").strip() - if auto_topic: - await self._multiroom_context.move_gc( - origin_room_id=room_id, - target_room_id=target_room_id, - topic=auto_topic, - room_name=target_name, + # c. Letzter Fallback: Nur Hinweis-Post (bereits gesendet) + logger.info( + "[rocketchat] V8.3-2: Move fallback — announcement only in room %s", + room_id[:8], ) - # V8.3-5: Temporäres Sticky mit Topic-Scoping (30 Min TTL) - # V8.3.2 F1: Nur setzen wenn decision.set_sticky=True - # (100%-Keyword-Match). FAISS/LLM-Routing setzt KEINEN Sticky. - if getattr(decision, 'set_sticky', False): - self._session_room_preferences[room_id] = { - "target_room": target_room_id, - "target_name": target_name, - "sticky_topic": sticky_topic, - "expires_at": time.time() + 1800, - } - logger.info( - "[rocketchat] V8.3-5: Topic-Scoped Sticky gesetzt — " - "room=%s → target=%s, topic='%s' (30 Min, Auto-Route)", - room_id[:8], target_name[:20], sticky_topic, + # Kopiere Nachricht in den Zielraum + # P1: display_text (mit Quote) für Zielraum-Kopie + target_txt = f"*(Auftrag von @{username}, automatisch geroutet)*\n{display_text}" + target_message_id = await self._post_message_with_retry(target_room_id, target_txt) + # Setze _CURRENT_ORIGIN_ROOM auf Zielraum → Agent antwortet dort + _CURRENT_ORIGIN_ROOM.set(target_room_id) + _THEMATIC_TARGET_ROOM.set(target_room_id) + # P1: _room_context als persistenter Fallback + _set_room_context_origin(f"user:{username}", target_room_id) + forwarded = True + routing_counter.increment('auto_route_dispatched') + logger.info( + "[rocketchat] V8.1 P1: Auto-Route '%s' → %s — " + "Agent dispatched in target room", + display_text[:80], target_name, + ) + # V8.1.1 R2: Ring-GC bei Auto-Route — stale Topics aus Ursprungsraum entfernen + if _MULTIROOM() and self._multiroom_context is not None: + auto_topic = text[:80].replace("\n", " ").strip() + if auto_topic: + await self._multiroom_context.move_gc( + origin_room_id=room_id, + target_room_id=target_room_id, + topic=auto_topic, + room_name=target_name, ) - # ── V8.3-3: Auto-Route für Widerspruchs-Routine speichern ── - self._recent_auto_routes[room_id] = { - "origin_room": room_id, + # V8.3-5: Temporäres Sticky mit Topic-Scoping (30 Min TTL) + # V8.3.2 F1: Nur setzen wenn decision.set_sticky=True + # (100%-Keyword-Match). FAISS/LLM-Routing setzt KEINEN Sticky. + if getattr(decision, 'set_sticky', False): + self._session_room_preferences[room_id] = { "target_room": target_room_id, - "topic": sticky_topic, - "timestamp": time.time(), - "origin_message_id": msg_id, - "target_message_id": target_message_id or "", - "source": "auto", # FIX 4: confirm_move vs auto-route + "target_name": target_name, + "sticky_topic": sticky_topic, + "expires_at": time.time() + 1800, } - - # _CURRENT_ORIGIN_ROOM wird NUR gesetzt wenn nicht forwarded. - # Bei forwarded (Auto-Route) wurde es bereits auf Zielraum gesetzt. - # P0-2: Der alte Silent-Copy-Pfad (decision.target_room ohne move_request_sent) - # ist im v6-Flow tot — alle Routing-Entscheidungen haben move_request_sent=True. - # Move-Request-Handling erfolgt bereits oben (vor Archivar, Zeile 1186-1273). - - # 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) - # P1: _room_context als persistenter Fallback - _set_room_context_origin(f"user:{username}", room_id) - - # ── V8.4: Red Flag — Pre-Dispatch-Hook ────────────────────────── - # Wenn der Archivar Red Flag gesetzt hat (is_red_flag=True), - # wird der strukturierte Prompt in den System-Prompt injiziert. - # Der Agent entscheidet VOR der Antwort: WO antworten. - # send() parsed ROOM: aus der Antwort und routet entsprechend. - red_flag_prompt = "" - if decision and getattr(decision, 'is_red_flag', False): - red_flag_prompt = getattr(decision, 'red_flag_prompt', '') - if red_flag_prompt: - _RED_FLAG_PENDING.set({ - "origin_room": room_id, - "origin_name": room_name, - "prompt": red_flag_prompt, - "rooms": getattr(decision, 'red_flag_rooms', []), - }) - logger.info( - "[rocketchat] V8.4 Red Flag: Pre-Dispatch-Hook aktiv — " - "Agent entscheidet über Zielraum (%d Räume)", - len(getattr(decision, 'red_flag_rooms', [])), - ) - routing_counter.increment('red_flag_dispatched') - - # ── Virtual Room Translation ───────────────────────────────── - # Replace room-based chat_id with user-based virtual chat_id. - # This collapses all rooms per user into ONE Hermes session: - # DM with alice: room_id=ABC123 → chat_id="user:alice" - # #Project-Chat: room_id=XYZ789 → chat_id="user:alice" - # Both get the same session key. - virtual_chat_id = f"user:{username}" - # _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: - self._user_rooms[virtual_chat_id] = [] - if room_id not in self._user_rooms[virtual_chat_id]: - self._user_rooms[virtual_chat_id].append(room_id) - - # Dispatch to gateway handler via base-class handle_message - try: - message_type = self._message_type_for(is_button_response) - # ── Archivar-Kontext-Weitergabe: Frage-Nr + Zielraum im Prompt ── - target_room_id = _THEMATIC_TARGET_ROOM.get() - if target_room_id: - target_name = self._room_info.get(target_room_id, {}).get("name", target_room_id[:12] + "…") - with _question_counter_lock: - archivar_suffix = f" [Frage {_question_counter}, {room_name} -> {target_name}]" - else: - # Timeout-Fallback: Agent braucht Raumliste für autonome Entscheidung - room_names = [info.get("name", "?") for rid, info in self._room_info.items() - if info.get("type") in ("c", "p") and rid != room_id] - rooms_str = ", ".join(room_names) if room_names else "keine weiteren Räume" - with _question_counter_lock: - archivar_suffix = f" [Frage {_question_counter}, Timeout — Räume: {rooms_str}]" - # ── Ende Kontext-Weitergabe ────────────────────────────────────── - # V8.1 P4: MultiRoomContext-Ring in System-Prompt injizieren - chat_topic = self._room_map_summary - if self._multiroom_context is not None: - ring_summary = await self._multiroom_context.get_summary( - exclude_room_id=room_id - ) - if ring_summary: - chat_topic = f"{chat_topic}\n\n{ring_summary}" if chat_topic else ring_summary - # ── V8.4: Red Flag Prompt in System-Prompt injizieren ────── - if red_flag_prompt: - chat_topic = f"{chat_topic}\n\n{red_flag_prompt}" if chat_topic else red_flag_prompt - source = SessionSource( - platform=Platform("rocketchat"), - chat_id=virtual_chat_id, # ← user-based instead of room-based - chat_name=f"{room_name} (via @{username})" + archivar_suffix + (f" [{category}]" if category else ""), - user_id=username, - user_name=username, - chat_type="dm", # ← force DM to bypass group isolation in Core - chat_topic=chat_topic, # FIX E + V8.1 P4: Raum-Map + MultiRoom-Kontext - ) - # ── FIX A: Text-Prefix in User-Nachricht injizieren ────────── - # Der Agent muss wissen, in welchem Raum er angesprochen wird. - # Ohne diesen Kontext kann er nicht menschenähnlich kommunizieren - # (z.B. "Ich bin im DM"-Problem). - # Mechanismus: [Raum: name (typ)] wird als Text-Präfix vor die - # User-Nachricht gesetzt — kein ContextVar, sondern ein simpler - # String-Prefix, den der Agent im Prompt lesen kann. - room_type_label = {"c": "channel", "p": "group", "d": "dm"}.get(room_type, room_type) - room_context_prefix = f"[Raum: {room_name} ({room_type_label})] " - contextualized_text = room_context_prefix + text - - event = MessageEvent( - text=contextualized_text, - message_type=message_type, - message_id=msg_id, - timestamp=datetime.datetime.fromtimestamp(time.time()), - raw_message=msg_obj, - ) - event.source = source - # ── V8.1 P1: ContextVar-Snapshot für Drain-Task ────────── - # contextvars.copy_context() friert die aktuellen ContextVar-Werte - # (_CURRENT_ORIGIN_ROOM, _THEMATIC_TARGET_ROOM) ein. handle_message() - # erzeugt intern asyncio.create_task (Drain-Task), der ContextVars - # vom aufrufenden Task erbt. Ohne Snapshot kann der Drain-Task - # veraltete Werte einer vorherigen Nachricht erben (Race Condition - # bei zwei schnellen Nachrichten hintereinander). - ctx = contextvars.copy_context() - # V8.1 P1 diagnostic: log dispatch context - _origin = _CURRENT_ORIGIN_ROOM.get() - _target = _THEMATIC_TARGET_ROOM.get() logger.info( - "V8.1 P1 dispatch: chat_id=%s → target_room=%s, " - "_CURRENT_ORIGIN_ROOM=%s, _THEMATIC_TARGET_ROOM=%s", - virtual_chat_id, _target if _target else room_id, - _origin[:8] if _origin else "", - _target[:8] if _target else "", + "[rocketchat] V8.3-5: Topic-Scoped Sticky gesetzt — " + "room=%s → target=%s, topic='%s' (30 Min, Auto-Route)", + room_id[:8], target_name[:20], sticky_topic, ) - # P0-3: Agent-Dispatch-Task speichern für Cancel bei ::onboarding abort. - # handle_message() erzeugt intern asyncio.create_task (Drain-Task). - # Ohne Referenz kann ::onboarding abort den laufenden Agent-Task nicht killen. - self._agent_dispatch_task = asyncio.create_task( - ctx.run(self.handle_message, event) - ) - try: - await self._agent_dispatch_task - except asyncio.CancelledError: - logger.info("[rocketchat] P0-3: Agent-Dispatch-Task gecancelled") - return - finally: - self._agent_dispatch_task = None - except Exception as e: - logger.error("[rocketchat] handle_message error: %s", e) - # Fallback: Wenn COMMAND fehlschlägt (z.B. nach Gateway-Neustart - # verliert der neue Prozess den In-Memory-Callback), als normale - # Text-Nachricht mit Hinweis wiederholen. - if is_button_response and str(e) == "COMMAND": - logger.info("[rocketchat] COMMAND lost context — retrying as TEXT") - try: - from datetime import datetime as dt2 - fallback_source = SessionSource( - platform=Platform("rocketchat"), - chat_id=f"user:{username}", - chat_name=f"{room_name} (via @{username})", - user_id=username, - user_name=username, - chat_type="dm", - chat_topic=self._room_map_summary, # FIX E - ) - fallback_event = MessageEvent( - text=f"[Button-Antwort: {text}]", - message_type=MessageType.TEXT, - message_id=msg_id, - timestamp=dt2.fromtimestamp(time.time()), - raw_message=msg_obj, - ) - fallback_event.source = fallback_source - await self.handle_message(fallback_event) - except Exception as e2: - logger.error("[rocketchat] COMMAND text fallback also failed: %s", e2) - finally: - # ── V8.6 P1a: PresenceEngine — mark_busy_done (Honeymoon-Timer) ── - # try/finally garantiert decrement auch bei Exceptions/Errors. - if _has_presence: - self._presence_engine.mark_busy_done() - # B12: Background-Tasks decrement — Heartbeat-Message aktualisieren - self._presence_engine.decrement_background_tasks() - # P1-2: current_room zurücksetzen nach Verarbeitung - self._presence_engine.set_current_room("") - logger.info("[presence] mark_busy_done (turn complete)") + # ── V8.3-3: Auto-Route für Widerspruchs-Routine speichern ── + self._recent_auto_routes[room_id] = { + "origin_room": room_id, + "target_room": target_room_id, + "topic": sticky_topic, + "timestamp": time.time(), + "origin_message_id": msg_id, + "target_message_id": target_message_id or "", + "source": "auto", # FIX 4: confirm_move vs auto-route + } + # _CURRENT_ORIGIN_ROOM wird NUR gesetzt wenn nicht forwarded. + # Bei forwarded (Auto-Route) wurde es bereits auf Zielraum gesetzt. + # P0-2: Der alte Silent-Copy-Pfad (decision.target_room ohne move_request_sent) + # ist im v6-Flow tot — alle Routing-Entscheidungen haben move_request_sent=True. + # Move-Request-Handling erfolgt bereits oben (vor Archivar, Zeile 1186-1273). + + # 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) + # P1: _room_context als persistenter Fallback + _set_room_context_origin(f"user:{username}", room_id) + + # ── V8.4: Red Flag — Pre-Dispatch-Hook ────────────────────────── + # Wenn der Archivar Red Flag gesetzt hat (is_red_flag=True), + # wird der strukturierte Prompt in den System-Prompt injiziert. + # Der Agent entscheidet VOR der Antwort: WO antworten. + # send() parsed ROOM: aus der Antwort und routet entsprechend. + red_flag_prompt = "" + if decision and getattr(decision, 'is_red_flag', False): + red_flag_prompt = getattr(decision, 'red_flag_prompt', '') + if red_flag_prompt: + _RED_FLAG_PENDING.set({ + "origin_room": room_id, + "origin_name": room_name, + "prompt": red_flag_prompt, + "rooms": getattr(decision, 'red_flag_rooms', []), + }) + logger.info( + "[rocketchat] V8.4 Red Flag: Pre-Dispatch-Hook aktiv — " + "Agent entscheidet über Zielraum (%d Räume)", + len(getattr(decision, 'red_flag_rooms', [])), + ) + routing_counter.increment('red_flag_dispatched') + + # ── Virtual Room Translation ───────────────────────────────── + # Replace room-based chat_id with user-based virtual chat_id. + # This collapses all rooms per user into ONE Hermes session: + # DM with alice: room_id=ABC123 → chat_id="user:alice" + # #Project-Chat: room_id=XYZ789 → chat_id="user:alice" + # Both get the same session key. + virtual_chat_id = f"user:{username}" + # _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: + self._user_rooms[virtual_chat_id] = [] + if room_id not in self._user_rooms[virtual_chat_id]: + self._user_rooms[virtual_chat_id].append(room_id) + + # Dispatch to gateway handler via base-class handle_message + try: + message_type = self._message_type_for(is_button_response) + # ── Archivar-Kontext-Weitergabe: Frage-Nr + Zielraum im Prompt ── + target_room_id = _THEMATIC_TARGET_ROOM.get() + if target_room_id: + target_name = self._room_info.get(target_room_id, {}).get("name", target_room_id[:12] + "…") + with _question_counter_lock: + archivar_suffix = f" [Frage {_question_counter}, {room_name} -> {target_name}]" + else: + # Timeout-Fallback: Agent braucht Raumliste für autonome Entscheidung + room_names = [info.get("name", "?") for rid, info in self._room_info.items() + if info.get("type") in ("c", "p") and rid != room_id] + rooms_str = ", ".join(room_names) if room_names else "keine weiteren Räume" + with _question_counter_lock: + archivar_suffix = f" [Frage {_question_counter}, Timeout — Räume: {rooms_str}]" + # ── Ende Kontext-Weitergabe ────────────────────────────────────── + # V8.1 P4: MultiRoomContext-Ring in System-Prompt injizieren + chat_topic = self._room_map_summary + if self._multiroom_context is not None: + ring_summary = await self._multiroom_context.get_summary( + exclude_room_id=room_id + ) + if ring_summary: + chat_topic = f"{chat_topic}\n\n{ring_summary}" if chat_topic else ring_summary + # ── V8.4: Red Flag Prompt in System-Prompt injizieren ────── + if red_flag_prompt: + chat_topic = f"{chat_topic}\n\n{red_flag_prompt}" if chat_topic else red_flag_prompt + source = SessionSource( + platform=Platform("rocketchat"), + chat_id=virtual_chat_id, # ← user-based instead of room-based + chat_name=f"{room_name} (via @{username})" + archivar_suffix + (f" [{category}]" if category else ""), + user_id=username, + user_name=username, + chat_type="dm", # ← force DM to bypass group isolation in Core + chat_topic=chat_topic, # FIX E + V8.1 P4: Raum-Map + MultiRoom-Kontext + ) + # ── FIX A: Text-Prefix in User-Nachricht injizieren ────────── + # Der Agent muss wissen, in welchem Raum er angesprochen wird. + # Ohne diesen Kontext kann er nicht menschenähnlich kommunizieren + # (z.B. "Ich bin im DM"-Problem). + # Mechanismus: [Raum: name (typ)] wird als Text-Präfix vor die + # User-Nachricht gesetzt — kein ContextVar, sondern ein simpler + # String-Prefix, den der Agent im Prompt lesen kann. + room_type_label = {"c": "channel", "p": "group", "d": "dm"}.get(room_type, room_type) + room_context_prefix = f"[Raum: {room_name} ({room_type_label})] " + contextualized_text = room_context_prefix + text + + event = MessageEvent( + text=contextualized_text, + message_type=message_type, + message_id=msg_id, + timestamp=datetime.datetime.fromtimestamp(time.time()), + raw_message=msg_obj, + ) + event.source = source + # ── V8.1 P1: ContextVar-Snapshot für Drain-Task ────────── + # contextvars.copy_context() friert die aktuellen ContextVar-Werte + # (_CURRENT_ORIGIN_ROOM, _THEMATIC_TARGET_ROOM) ein. handle_message() + # erzeugt intern asyncio.create_task (Drain-Task), der ContextVars + # vom aufrufenden Task erbt. Ohne Snapshot kann der Drain-Task + # veraltete Werte einer vorherigen Nachricht erben (Race Condition + # bei zwei schnellen Nachrichten hintereinander). + ctx = contextvars.copy_context() + # V8.1 P1 diagnostic: log dispatch context + _origin = _CURRENT_ORIGIN_ROOM.get() + _target = _THEMATIC_TARGET_ROOM.get() + logger.info( + "V8.1 P1 dispatch: chat_id=%s → target_room=%s, " + "_CURRENT_ORIGIN_ROOM=%s, _THEMATIC_TARGET_ROOM=%s", + virtual_chat_id, _target if _target else room_id, + _origin[:8] if _origin else "", + _target[:8] if _target else "", + ) + # P0-3: Agent-Dispatch-Task speichern für Cancel bei ::onboarding abort. + # handle_message() erzeugt intern asyncio.create_task (Drain-Task). + # Ohne Referenz kann ::onboarding abort den laufenden Agent-Task nicht killen. + self._agent_dispatch_task = asyncio.create_task( + ctx.run(self.handle_message, event) + ) + try: + await self._agent_dispatch_task + except asyncio.CancelledError: + logger.info("[rocketchat] P0-3: Agent-Dispatch-Task gecancelled") + return + finally: + self._agent_dispatch_task = None + except Exception as e: + logger.error("[rocketchat] handle_message error: %s", e) + # Fallback: Wenn COMMAND fehlschlägt (z.B. nach Gateway-Neustart + # verliert der neue Prozess den In-Memory-Callback), als normale + # Text-Nachricht mit Hinweis wiederholen. + if is_button_response and str(e) == "COMMAND": + logger.info("[rocketchat] COMMAND lost context — retrying as TEXT") + try: + from datetime import datetime as dt2 + fallback_source = SessionSource( + platform=Platform("rocketchat"), + chat_id=f"user:{username}", + chat_name=f"{room_name} (via @{username})", + user_id=username, + user_name=username, + chat_type="dm", + chat_topic=self._room_map_summary, # FIX E + ) + fallback_event = MessageEvent( + text=f"[Button-Antwort: {text}]", + message_type=MessageType.TEXT, + message_id=msg_id, + timestamp=dt2.fromtimestamp(time.time()), + raw_message=msg_obj, + ) + fallback_event.source = fallback_source + await self.handle_message(fallback_event) + except Exception as e2: + logger.error("[rocketchat] COMMAND text fallback also failed: %s", e2) # ── R5: Inline-Command-Handler ──────────────────────────────────────── def _register_inline_commands(self) -> None: