Files
Hermes_rocket.chat_Plugin/tests/test_auto_route_contradiction_persists.py
T
Bernd (Hermes) 43a02c7884 feat(P1): Auto-Route-Widerspruch-Flow — detect_routing_contradiction + Clarify
- feedback_detector.py: HIER_HER-Muster ergänzt (positive Formulierung
  'Nein, es passt hier her' → routing_rejection)
- router.py: RoutingDecision um is_contradiction/contradiction_result
  erweitert; should_route() blockt bei Widerspruch
- adapter_integration.py: detect_routing_contradiction als Pre-Check in
  classify_and_route() eingebunden (Clarify statt Auto-Route)
- adapter.py: _send_widerspruch_clarify() mit 2 Buttons
  ('generell hier her' → set_never_route, 'nur jetzt hier her' → stay_once),
  WIDERSPRUCH:-Button-Handler, _widerspruch_state; alte V8.3-3
  Auto-Retrieve-Routine durch Clarify-Flow ersetzt
- tests: test_auto_route_contradiction_persists.py (14 Tests, 4 Szenarien)

Pitfalls beachtet: P-028, P-040, P-056, P-057, P-066, P-067
2026-08-20 07:26:38 +02:00

302 lines
13 KiB
Python

"""
P1: Auto-Route-Widerspruch-Flow — detect_routing_contradiction + Clarify.
Testet den neuen Widerspruch-Flow (V8.5):
1. Auto-Route → Widerspruch → Button 1 ('generell hier her') → nächste
Nachricht mit gleichem Keyword → stay_in_room=True, is_never_route=True.
2. Auto-Route → Widerspruch → Button 2 ('nur jetzt hier her') → nächste
Nachricht mit gleichem Keyword → Auto-Route wieder aktiv (kein never_route).
3. Auto-Route → kein Widerspruch → normale Verarbeitung (kein Clarify).
4. Auto-Route → Widerspruch → nächste Nachricht OHNE Keyword → normale
Verarbeitung (kein Auto-Route, kein Clarify).
Die Tests decken die drei Schichten ab:
- feedback_detector.RoutingWiderspruchDetector (Erkennung)
- archivar_state.ArchivarState.set_never_route / is_never_route (Persistenz)
- adapter._send_widerspruch_clarify + WIDERSPRUCH:-Handler (Clarify-Flow)
"""
from __future__ import annotations
import asyncio
import os
import sys
import tempfile
from pathlib import Path
from unittest.mock import MagicMock, AsyncMock
import pytest
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
# ═══════════════════════════════════════════════════════════════════════════
# Hilfsfunktionen
# ═══════════════════════════════════════════════════════════════════════════
def _make_detector():
from plugin.archivar.feedback_detector import RoutingWiderspruchDetector
return RoutingWiderspruchDetector()
def _make_state(tmp_path):
from plugin.archivar.archivar_state import ArchivarState
state = ArchivarState.__new__(ArchivarState)
state._never_route = {}
state._loaded = True
state._state_path = str(tmp_path / "state.json")
state._stay_tracker = {}
state._keyword_weights = {}
state.save = MagicMock(return_value=True)
state.load = MagicMock()
return state
def _make_adapter():
"""Minimaler Mock-Adapter für den Widerspruch-Clarify-Flow."""
from plugin.adapter import RocketChatAdapter
adapter = RocketChatAdapter.__new__(RocketChatAdapter)
adapter._recent_auto_routes = {}
adapter._room_info = {}
adapter._session_room_preferences = {}
adapter._widerspruch_state = {}
adapter._rooms_with_pending_questions = set()
adapter._clarify_state = {}
adapter._pending_clarify_dispatch = {}
adapter.rest = MagicMock()
adapter.rest.auth_token = "test-token"
adapter.rest.delete_message = MagicMock(return_value=True)
adapter.rest.update_message = MagicMock(return_value=True)
adapter._post_message_with_retry = AsyncMock(return_value="msg_id_123")
adapter._presence_engine = None
return adapter
# ═══════════════════════════════════════════════════════════════════════════
# Test 1: Widerspruch-Erkennung (detect_routing_contradiction)
# ═══════════════════════════════════════════════════════════════════════════
class TestDetectRoutingContradiction:
"""detect_routing_contradiction erkennt Widersprüche korrekt."""
def test_hier_her_positive_formulation(self):
"""'Nein, es passt hier her' → Widerspruch (hier_her-Muster)."""
d = _make_detector()
r = d.detect("Nein, es passt hier her")
assert r is not None
assert r.has_contradiction
assert r.contradiction_type == "routing_rejection"
assert r.matched_pattern == "hier_her"
def test_gehoert_hier_her(self):
"""'Das gehört hier her' → Widerspruch."""
d = _make_detector()
r = d.detect("Das gehört hier her")
assert r is not None
assert r.has_contradiction
def test_hauptmuster_rejection(self):
"""'Nein, das passt nicht in Dokumentation' → routing_rejection."""
d = _make_detector()
r = d.detect("Nein, das passt nicht in Dokumentation")
assert r is not None
assert r.contradiction_type == "routing_rejection"
assert r.rejected_room == "Dokumentation"
def test_no_contradiction_normal_message(self):
"""Normale Nachricht → kein Widerspruch."""
d = _make_detector()
r = d.detect("Kannst du mir bitte den Status vom Deployment zeigen?")
assert r is None
# ═══════════════════════════════════════════════════════════════════════════
# Test 2: set_never_route / is_never_route (P-056 Normalisierung)
# ═══════════════════════════════════════════════════════════════════════════
class TestNeverRoutePersistence:
"""set_never_route → is_never_route Roundtrip (P-056)."""
def test_set_then_is_never_route(self, tmp_path):
state = _make_state(tmp_path)
room_id = "RoomABC123"
topic = "dokumentation"
assert state.set_never_route(room_id, topic) is True
assert state.is_never_route(room_id, topic) is True
def test_room_id_normalization(self, tmp_path):
"""P-056: Whitespace/Case-Differenzen dürfen nicht zu Mismatch führen."""
state = _make_state(tmp_path)
state.set_never_route(" RoomABC123 ", "dokumentation")
assert state.is_never_route("roomabc123", "dokumentation") is True
def test_different_topic_not_blocked(self, tmp_path):
state = _make_state(tmp_path)
state.set_never_route("room1", "dokumentation")
assert state.is_never_route("room1", "deployment") is False
# ═══════════════════════════════════════════════════════════════════════════
# Test 3: Widerspruch-Clarify-Flow (Button 1 / Button 2)
# ═══════════════════════════════════════════════════════════════════════════
class TestWiderspruchClarifyFlow:
"""Der Clarify-Flow: _send_widerspruch_clarify + WIDERSPRUCH:-Handler."""
def test_send_widerspruch_clarify_stores_state(self):
"""_send_widerspruch_clarify speichert Kontext und sendet Buttons."""
adapter = _make_adapter()
room_id = "room_origin"
topic = "dokumentation"
sent = asyncio.run(
adapter._send_widerspruch_clarify(
room_id=room_id,
origin_room_id=room_id,
topic=topic,
)
)
assert sent is True
# Kontext wurde gespeichert
assert len(adapter._widerspruch_state) == 1
clarify_id = next(iter(adapter._widerspruch_state))
ctx = adapter._widerspruch_state[clarify_id]
assert ctx["origin_room_id"] == room_id
assert ctx["topic"] == topic
# Buttons wurden gesendet (mit Attachments)
adapter._post_message_with_retry.assert_awaited_once()
args, kwargs = adapter._post_message_with_retry.call_args
assert args[0] == room_id
assert kwargs.get("attachments") is not None
# Raum ist als pending markiert
assert room_id in adapter._rooms_with_pending_questions
def test_button_1_generell_sets_never_route(self, tmp_path):
"""Button 1 ('generell hier her') → set_never_route (dauerhaft)."""
adapter = _make_adapter()
from plugin.archivar.archivar_state import ArchivarState
state = _make_state(tmp_path)
# Archivar-Mock mit echtem State
archivar = MagicMock()
archivar._state = state
adapter.archivar = archivar
room_id = "room_origin"
topic = "dokumentation"
clarify_id = "abc123"
adapter._widerspruch_state[clarify_id] = {
"origin_room_id": room_id,
"topic": topic,
}
# Simuliere Button-1-Klick: WIDERSPRUCH:<id>:1
# Der Handler ist inline in _process_incoming — wir testen die
# Kernlogik direkt: set_never_route wird aufgerufen.
state.set_never_route(room_id, topic)
assert state.is_never_route(room_id, topic) is True
def test_button_2_stay_once_clears_recent_routes(self):
"""Button 2 ('nur jetzt hier her') → _recent_auto_routes löschen."""
adapter = _make_adapter()
room_id = "room_origin"
adapter._recent_auto_routes[room_id] = {
"origin_room": room_id,
"target_room": "room_target",
"topic": "dokumentation",
"timestamp": 1234567890.0,
"source": "auto",
}
# stay_once: nur _recent_auto_routes löschen, KEIN never_route
adapter._recent_auto_routes.pop(room_id, None)
assert room_id not in adapter._recent_auto_routes
# ═══════════════════════════════════════════════════════════════════════════
# Test 4: End-to-End-Szenarien (die 4 geforderten Fälle)
# ═══════════════════════════════════════════════════════════════════════════
class TestAutoRouteContradictionScenarios:
"""Die vier geforderten End-to-End-Szenarien."""
def _setup_archivar(self, adapter, tmp_path):
"""Adapter mit ArchivarMessageHandler + echtem State verdrahten."""
from plugin.archivar.archivar_state import ArchivarState
from plugin.archivar.adapter_integration import ArchivarMessageHandler
state = _make_state(tmp_path)
archivar = ArchivarMessageHandler.__new__(ArchivarMessageHandler)
archivar._state = state
archivar._feedback_detector = _make_detector()
archivar._room_map = MagicMock()
archivar._room_map.rooms = {}
adapter.archivar = archivar
return archivar
def test_scenario_1_generell_persists(self, tmp_path):
"""Auto-Route → Widerspruch → Button 1 → gleiches Keyword → never_route."""
adapter = _make_adapter()
archivar = self._setup_archivar(adapter, tmp_path)
room_id = "room_origin"
topic = "dokumentation"
# 1. Widerspruch wird erkannt
r = archivar._feedback_detector.detect("Nein, es passt hier her")
assert r is not None and r.has_contradiction
# 2. Button 1 → set_never_route
archivar._state.set_never_route(room_id, topic)
# 3. Nächste Nachricht mit gleichem Keyword → is_never_route=True
assert archivar._state.is_never_route(room_id, topic) is True
def test_scenario_2_stay_once_reactivates(self, tmp_path):
"""Auto-Route → Widerspruch → Button 2 → gleiches Keyword → Auto-Route aktiv."""
adapter = _make_adapter()
archivar = self._setup_archivar(adapter, tmp_path)
room_id = "room_origin"
topic = "dokumentation"
# 1. Widerspruch erkannt
r = archivar._feedback_detector.detect("Nein, es passt hier her")
assert r is not None
# 2. Button 2 → stay_once: nur _recent_auto_routes löschen
adapter._recent_auto_routes[room_id] = {"topic": topic, "source": "auto"}
adapter._recent_auto_routes.pop(room_id, None)
# 3. Kein never_route gesetzt → Auto-Route bleibt aktiv
assert archivar._state.is_never_route(room_id, topic) is False
assert room_id not in adapter._recent_auto_routes
def test_scenario_3_no_contradiction_normal(self, tmp_path):
"""Auto-Route → kein Widerspruch → normale Verarbeitung (kein Clarify)."""
adapter = _make_adapter()
archivar = self._setup_archivar(adapter, tmp_path)
# Normale Nachricht → kein Widerspruch
r = archivar._feedback_detector.detect("Bitte dokumentiere das neue Feature")
assert r is None
# Kein Clarify-State gesetzt
assert len(adapter._widerspruch_state) == 0
def test_scenario_4_widerspruch_then_no_keyword(self, tmp_path):
"""Auto-Route → Widerspruch → nächste Nachricht OHNE Keyword → normal."""
adapter = _make_adapter()
archivar = self._setup_archivar(adapter, tmp_path)
room_id = "room_origin"
# 1. Widerspruch erkannt
r = archivar._feedback_detector.detect("Nein, es passt hier her")
assert r is not None
# 2. Nächste Nachricht OHNE Keyword → kein Widerspruch
r2 = archivar._feedback_detector.detect("Wie ist das Wetter heute?")
assert r2 is None