From 7ba62bd7e40eb5a5efd77c14158c2a083d54f945 Mon Sep 17 00:00:00 2001 From: "Bernd (Hermes)" Date: Sun, 19 Jul 2026 16:12:46 +0200 Subject: [PATCH] =?UTF-8?q?fix:=20V8.5=20=E2=80=94=20DM-Bypass=20differenz?= =?UTF-8?q?iert:=20100%-Keywords=20in=20DMs=20erkannt=20+=20Butler=20Move-?= =?UTF-8?q?Request=20(R8)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- plugin/adapter.py | 15 +- plugin/archivar/router.py | 66 +++- plugin/archivar/tests/test_v8_4_3.py | 11 +- plugin/archivar/tests/test_v8_5_dm_routing.py | 347 ++++++++++++++++++ 4 files changed, 424 insertions(+), 15 deletions(-) create mode 100644 plugin/archivar/tests/test_v8_5_dm_routing.py diff --git a/plugin/adapter.py b/plugin/adapter.py index 9a2f3f1..a2d59f4 100644 --- a/plugin/adapter.py +++ b/plugin/adapter.py @@ -2191,14 +2191,13 @@ class RocketChatAdapter(BasePlatformAdapter): logger.debug("[rocketchat] ARCHIVAR-DEBUG: Archivar bypassed — persisted_state=always") _should_classify = False elif room_type == "d": - # V8: DM-Bypass bleibt, weil DM kein Multiroom-Routing braucht. - # is_auftrag wird NICHT mehr als Gate verwendet — die - # Auftragserkennung dient nur noch Telemetrie/Counter. - logger.debug("[rocketchat] DM von %s — kein Multiroom-Routing", username) - logger.debug("[rocketchat] ARCHIVAR-DEBUG: Archivar bypassed — DM (no multiroom)") - routing_counter.increment('dm_routing_skipped') - logger.info("ROUTING BYPASS: reason=dm_routing_skipped, origin_room=%s", room_id) - _should_classify = False + # 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] diff --git a/plugin/archivar/router.py b/plugin/archivar/router.py index 6d34576..ef34dfc 100644 --- a/plugin/archivar/router.py +++ b/plugin/archivar/router.py @@ -467,8 +467,70 @@ class BidirectionalRouter: confidence=1.0, stay_in_room=True, ) - logger.debug("DM-Guard V8.2: origin_room_id leer → DM-Routing erlaubt (A4)") - # Kein sofortiges stay_in_room — normaler Flow mit Butler + + # ── V8.5: DM-Routing differenziert ────────────────────── + # Stufe 0 (100%-Keywords): IMMER ausführen, auch in DMs. + # 100%-Keyword-Treffer → Move-Request (Butler-Prinzip). + # Kein 100%-Treffer → Catch-All (LLM antwortet im DM). + # FAISS + weiche Keywords: in DMs NICHT ausführen. + routing_telemetry.start_timer() + matched_room = self._room_map.find_room_by_keywords(text, origin_room_id=None) + if matched_room is not None: + is_100 = self._room_map.is_100_percent_match(text, matched_room) + if is_100: + # 100%-Keyword in DM → Butler (Move-Request vorschlagen) + logger.info( + "DM 100%% Keyword-Match: '%s' → %s — Butler (Move-Request)", + text[:80], matched_room.name, + ) + routing_counter.increment('dm_100_keyword_butler') + routing_telemetry.record( + stage='dm_100_keyword', score=1.0, decision='butler', + target=matched_room.room_id, origin=origin_room_id, + duration_ms=routing_telemetry.elapsed_ms(), + ) + logger.info("ROUTING DECISION: reason=dm_100_keyword_butler, origin_room=%s, target_room=%s, stay=False, butler_mode=True", origin_room_id, matched_room.room_id) + matched_keywords = self._extract_matched_keywords(text, matched_room) + room_name = matched_room.name.replace("#", "") if matched_room.name.startswith("#") else matched_room.name + notification = f"📋 Bearbeite ich in #{room_name} — [Link]" + return RoutingDecision( + category="work_order", + target_room=matched_room.room_id, + confidence=0.95, + matched_room_name=matched_room.name, + source_room_notification=notification, + matched_keywords=matched_keywords, + move_request_sent=True, # Butler-Prinzip: vorschlagen, nicht automatisch + move_request_target_name=matched_room.name, + move_request_target_id=matched_room.room_id, + ) + else: + # Kontext-Keyword in DM → Catch-All (kein Routing) + logger.info( + "DM Kontext-Keyword-Match: '%s' → %s — Catch-All (kein Routing in DM)", + text[:80], matched_room.name, + ) + routing_counter.increment('dm_context_catch_all') + logger.info("ROUTING DECISION: reason=dm_context_catch_all, origin_room=%s, target_room=, stay=True, butler_mode=False", origin_room_id) + return RoutingDecision( + category="direct_question", + target_room="", + confidence=0.0, + is_catch_all=True, + stay_in_room=True, + ) + else: + # Kein Keyword-Match in DM → Catch-All + logger.debug("DM: Kein Keyword-Match → Catch-All") + routing_counter.increment('dm_no_match_catch_all') + logger.info("ROUTING DECISION: reason=dm_no_match_catch_all, origin_room=%s, target_room=, stay=True, butler_mode=False", origin_room_id) + return RoutingDecision( + category="direct_question", + target_room="", + confidence=0.0, + is_catch_all=True, + stay_in_room=True, + ) # ── Schritt 0: Excluded rooms check ────────────────────────── if origin_room_id and self._room_map.is_excluded(origin_room_id): diff --git a/plugin/archivar/tests/test_v8_4_3.py b/plugin/archivar/tests/test_v8_4_3.py index 76fbcf1..0ad35e5 100644 --- a/plugin/archivar/tests/test_v8_4_3.py +++ b/plugin/archivar/tests/test_v8_4_3.py @@ -705,9 +705,10 @@ class TestV843RegressionGate(unittest.TestCase): "Agent should be dispatched in target room (sticky route)") def test_dm_bypass_still_works(self): - """DM-Nachrichten bypassen Archivar weiterhin. + """V8.5: DM-Nachrichten rufen Archivar auf (100%-Keyword-Check). - Regression-Gate: DM-Bypass darf NICHT durch den Fix gebrochen werden. + Regression-Gate: DM ruft classify_and_route auf, aber + ohne 100%-Keyword → Catch-All (stay_in_room). """ msg_obj = { "_id": "msg_dm_001", @@ -731,9 +732,9 @@ class TestV843RegressionGate(unittest.TestCase): asyncio.run(self.adapter._process_incoming(msg_obj)) - # DM should bypass Archivar → NO classify_and_route - self.assertEqual(call_count[0], 0, - "classify_and_route should NOT be called for DM messages") + # V8.5: DM ruft classify_and_route auf (100%-Keyword-Check) + self.assertEqual(call_count[0], 1, + "classify_and_route SHOULD be called for DM messages (V8.5)") def test_pending_questions_bypass_still_works(self): """Pending-Questions-Bypass funktioniert weiterhin. diff --git a/plugin/archivar/tests/test_v8_5_dm_routing.py b/plugin/archivar/tests/test_v8_5_dm_routing.py new file mode 100644 index 0000000..d70ad06 --- /dev/null +++ b/plugin/archivar/tests/test_v8_5_dm_routing.py @@ -0,0 +1,347 @@ +""" +V8.5: DM-Routing differenziert — 100%-Keywords → Butler, Rest → Catch-All. + +Tests: +1. DM + 100%-Keyword → Move-Request (Butler, move_request_sent=True) +2. DM + weiches Keyword (context) → Catch-All (stay_in_room=True) +3. DM + kein Keyword → Catch-All +4. DM + Strategie-Thema → stay_in_room (existing behavior) +""" + +from __future__ import annotations + +import asyncio +import json +import logging +import sys +import tempfile +from pathlib import Path +from typing import Optional +from unittest.mock import patch, MagicMock + +import pytest + +sys.path.insert(0, str(Path(__file__).resolve().parents[3])) + +from plugin.archivar.router import BidirectionalRouter, RoutingDecision +from plugin.archivar.room_map import RoomMap, RoomEntry +from plugin.archivar.classifier import IntentClassifier, EmbeddingClient +from plugin.archivar.archivar_state import ArchivarState +from plugin.archivar.routing_telemetry import routing_telemetry +from plugin.archivar.routing_counter import routing_counter + + +# ── Helpers ──────────────────────────────────────────────────────────────── + + +class MockEmbeddingClient(EmbeddingClient): + """Mock embedding client that returns fixed vectors.""" + + def get_embedding(self, text: str) -> Optional[list]: + return [0.1] * 768 + + +def _make_room_map_with_rc_plugin() -> RoomMap: + """Build a RoomMap with #RC-Plugin (100%: 'Rocket.Chat Plugin') + Catch-All.""" + tmp = tempfile.TemporaryDirectory() + map_path = Path(tmp.name) / "room-map.json" + + test_data = { + "version": 5, + "rooms": { + "room_rc_plugin": { + "name": "#RC-Plugin", + "theme": "Rocket.Chat Plugin Entwicklung", + "description": "Entwicklung des Hermes Rocket.Chat Plugins", + "keywords_100": ["Rocket.Chat Plugin", "plugin", "rocketchat"], + "keywords_context": ["adapter", "gateway"], + "catch_all": False, + }, + "room_lan_doku": { + "name": "#LAN-Doku", + "theme": "LAN Dokumentation", + "description": "Dokumentation des LAN-Netzwerks", + "keywords_100": ["LAN-Dokumentation", "dokumentation", "doku"], + "keywords_context": ["netzwerk", "lan"], + "catch_all": False, + }, + "room_catchall": { + "name": "DM mit Andreas", + "theme": "Catch-All für DMs", + "description": "Catch-All für alle Themen ohne eigenen Raum", + "keywords_100": [], + "keywords_context": [], + "catch_all": True, + }, + }, + } + + with open(map_path, "w") as f: + json.dump(test_data, f) + + return RoomMap.load(map_path) + + +def _make_router(room_map: RoomMap, mock_llm_fn=None) -> BidirectionalRouter: + """Build a BidirectionalRouter with mock classifier and state.""" + classifier = IntentClassifier( + embedding_client=MockEmbeddingClient(), + llm_client=None, + ) + + if mock_llm_fn is not None: + classifier._llm_raw = mock_llm_fn + + state = ArchivarState(":memory:") + state.load() + + router = BidirectionalRouter(room_map, classifier, state) + router.set_subscribed_room_ids(list(room_map.rooms.keys())) + return router + + +# ── DM Routing Tests ─────────────────────────────────────────────────────── + + +class TestDMRouting100PercentKeyword: + """V8.5: DM + 100%-Keyword → Move-Request (Butler-Prinzip).""" + + @pytest.fixture + def router(self): + room_map = _make_room_map_with_rc_plugin() + return _make_router(room_map) + + def test_dm_100_percent_keyword_rc_plugin(self, router): + """DM + 'Rocket.Chat Plugin' → Move-Request für #RC-Plugin.""" + decision = asyncio.run(router.route( + "Rocket.Chat Plugin: Wie implementiere ich den neuen Adapter?", + origin_room_id="", # DM + )) + + assert decision is not None + assert decision.move_request_sent is True, ( + f"Expected move_request_sent=True (Butler), got {decision.move_request_sent}" + ) + assert decision.move_request_target_name == "#RC-Plugin", ( + f"Expected target '#RC-Plugin', got '{decision.move_request_target_name}'" + ) + assert decision.move_request_target_id == "room_rc_plugin", ( + f"Expected target_id 'room_rc_plugin', got '{decision.move_request_target_id}'" + ) + assert decision.stay_in_room is False, ( + f"Expected stay_in_room=False, got {decision.stay_in_room}" + ) + assert decision.category == "work_order", ( + f"Expected category='work_order', got '{decision.category}'" + ) + + def test_dm_100_percent_keyword_lan_doku(self, router): + """DM + 'LAN-Dokumentation' → Move-Request für #LAN-Doku.""" + decision = asyncio.run(router.route( + "LAN-Dokumentation: Bitte das Netzwerk-Diagramm aktualisieren", + origin_room_id="", # DM + )) + + assert decision is not None + assert decision.move_request_sent is True, ( + f"Expected move_request_sent=True (Butler), got {decision.move_request_sent}" + ) + assert decision.move_request_target_name == "#LAN-Doku", ( + f"Expected target '#LAN-Doku', got '{decision.move_request_target_name}'" + ) + assert decision.move_request_target_id == "room_lan_doku", ( + f"Expected target_id 'room_lan_doku', got '{decision.move_request_target_id}'" + ) + assert decision.stay_in_room is False + + def test_dm_100_percent_keyword_plugin_lowercase(self, router): + """DM + 'plugin' (lowercase 100%-Keyword) → Move-Request für #RC-Plugin.""" + decision = asyncio.run(router.route( + "plugin: Gibt es einen Bug im Adapter?", + origin_room_id="", # DM + )) + + assert decision is not None + assert decision.move_request_sent is True, ( + f"Expected move_request_sent=True (Butler), got {decision.move_request_sent}" + ) + assert decision.move_request_target_name == "#RC-Plugin" + + +class TestDMRoutingSoftKeyword: + """V8.5: DM + weiches Keyword (context) → Catch-All (kein Routing).""" + + @pytest.fixture + def router(self): + room_map = _make_room_map_with_rc_plugin() + return _make_router(room_map) + + def test_dm_context_keyword_adapter(self, router): + """DM + 'adapter' (context keyword) → Catch-All, kein Routing.""" + decision = asyncio.run(router.route( + "Der Adapter funktioniert nicht richtig", + origin_room_id="", # DM + )) + + assert decision is not None + assert decision.is_catch_all is True, ( + f"Expected is_catch_all=True, got {decision.is_catch_all}" + ) + assert decision.stay_in_room is True, ( + f"Expected stay_in_room=True (Catch-All), got {decision.stay_in_room}" + ) + assert decision.move_request_sent is False, ( + f"Expected move_request_sent=False (kein Routing), got {decision.move_request_sent}" + ) + assert decision.target_room == "", ( + f"Expected empty target_room, got '{decision.target_room}'" + ) + + def test_dm_context_keyword_gateway(self, router): + """DM + 'gateway' (context keyword) → Catch-All, kein Routing.""" + decision = asyncio.run(router.route( + "Der Gateway verbindet sich nicht", + origin_room_id="", # DM + )) + + assert decision is not None + assert decision.is_catch_all is True + assert decision.stay_in_room is True + assert decision.move_request_sent is False + + def test_dm_context_keyword_netzwerk(self, router): + """DM + 'netzwerk' (context keyword für #LAN-Doku) → Catch-All.""" + decision = asyncio.run(router.route( + "Das Netzwerk ist langsam heute", + origin_room_id="", # DM + )) + + assert decision is not None + assert decision.is_catch_all is True + assert decision.stay_in_room is True + assert decision.move_request_sent is False + + +class TestDMRoutingNoKeyword: + """V8.5: DM + kein Keyword → Catch-All (LLM antwortet im DM).""" + + @pytest.fixture + def router(self): + room_map = _make_room_map_with_rc_plugin() + return _make_router(room_map) + + def test_dm_no_keyword_smalltalk(self, router): + """DM + 'Wie geht es dir?' → Catch-All.""" + decision = asyncio.run(router.route( + "Wie geht es dir?", + origin_room_id="", # DM + )) + + assert decision is not None + assert decision.is_catch_all is True, ( + f"Expected is_catch_all=True, got {decision.is_catch_all}" + ) + assert decision.stay_in_room is True, ( + f"Expected stay_in_room=True (Catch-All), got {decision.stay_in_room}" + ) + assert decision.move_request_sent is False, ( + f"Expected move_request_sent=False, got {decision.move_request_sent}" + ) + + def test_dm_no_keyword_generic_question(self, router): + """DM + generische Frage → Catch-All.""" + decision = asyncio.run(router.route( + "Kannst du mir helfen?", + origin_room_id="", # DM + )) + + assert decision is not None + assert decision.is_catch_all is True + assert decision.stay_in_room is True + assert decision.move_request_sent is False + + def test_dm_no_keyword_empty_text(self, router): + """DM + leerer Text → Catch-All.""" + decision = asyncio.run(router.route( + "", + origin_room_id="", # DM + )) + + assert decision is not None + assert decision.is_catch_all is True + assert decision.stay_in_room is True + + +class TestDMRoutingStrategieTopic: + """V8.5: DM + Strategie-Thema → stay_in_room (bestehendes Verhalten).""" + + @pytest.fixture + def router(self): + room_map = _make_room_map_with_rc_plugin() + return _make_router(room_map) + + def test_dm_strategie_absprache(self, router): + """DM + 'absprache' → stay_in_room (Strategie-Modus).""" + decision = asyncio.run(router.route( + "Wir müssen eine Absprache zum Plugin-Release treffen", + origin_room_id="", # DM + )) + + assert decision is not None + assert decision.stay_in_room is True, ( + f"Expected stay_in_room=True (Strategie), got {decision.stay_in_room}" + ) + assert decision.move_request_sent is False, ( + f"Expected move_request_sent=False, got {decision.move_request_sent}" + ) + + def test_dm_strategie_entscheidung(self, router): + """DM + 'entscheidung' → stay_in_room (Strategie-Modus).""" + decision = asyncio.run(router.route( + "Wir brauchen eine Entscheidung zur Architektur", + origin_room_id="", # DM + )) + + assert decision is not None + assert decision.stay_in_room is True + assert decision.move_request_sent is False + + +class TestDMRoutingNonDMUnaffected: + """V8.5: Nicht-DM-Räume bleiben unverändert (Regression-Guard).""" + + @pytest.fixture + def router(self): + room_map = _make_room_map_with_rc_plugin() + return _make_router(room_map) + + def test_non_dm_100_percent_keyword_auto_route(self, router): + """Nicht-DM + 100%-Keyword → Auto-Route (kein Butler).""" + decision = asyncio.run(router.route( + "Rocket.Chat Plugin: Bug im Adapter", + origin_room_id="room_lan_doku", # Nicht-DM + )) + + assert decision is not None + # In Nicht-DM: 100%-Keywords → Auto-Route (move_request_sent=False) + assert decision.move_request_sent is False, ( + f"Expected move_request_sent=False (Auto-Route in non-DM), " + f"got {decision.move_request_sent}" + ) + assert decision.target_room == "room_rc_plugin", ( + f"Expected target 'room_rc_plugin', got '{decision.target_room}'" + ) + + def test_non_dm_context_keyword_butler(self, router): + """Nicht-DM + context keyword → Butler (move_request_sent=True).""" + decision = asyncio.run(router.route( + "Der Adapter hat einen Fehler", + origin_room_id="room_lan_doku", # Nicht-DM + )) + + assert decision is not None + # In Nicht-DM: context keywords → Butler + assert decision.move_request_sent is True, ( + f"Expected move_request_sent=True (Butler in non-DM), " + f"got {decision.move_request_sent}" + )