Compare commits
2 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 67ef5183d4 | |||
| 43a02c7884 |
+180
-131
@@ -1194,6 +1194,10 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
# FIX 2 (P0): ISSUE 3 — Pending Clarify Dispatch Slot
|
||||
# {room_id: {text, username, msg_id, msg_obj, is_button_response}}
|
||||
self._pending_clarify_dispatch: Dict[str, dict] = {}
|
||||
# V8.5: Widerspruch-Clarify-State — {clarify_id: {origin_room_id, topic}}
|
||||
# Speichert den Kontext eines Routing-Widerspruchs, damit der
|
||||
# WIDERSPRUCH:-Button-Handler weiß, welchen Raum/Thema er behandeln soll.
|
||||
self._widerspruch_state: Dict[str, dict] = {}
|
||||
# Auto-Onboarding v2: structured interview state
|
||||
self._onboarding_state: Dict[str, Any] = {}
|
||||
# FIX E: Raum-Map Summary für System-Prompt-Injection via chat_topic.
|
||||
@@ -2335,10 +2339,12 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
or (text and "::" in text
|
||||
and not text.startswith("CLARIFY:")
|
||||
and not text.startswith("ARCHIVAR_CLARIFY:")
|
||||
and not text.startswith("WIDERSPRUCH:")
|
||||
and not text.startswith("MOVE_REQ:")
|
||||
and text.split("::", 1)[0].strip() != "")
|
||||
or (text and text.startswith("CLARIFY:"))
|
||||
or (text and text.startswith("ARCHIVAR_CLARIFY:"))
|
||||
or (text and text.startswith("WIDERSPRUCH:"))
|
||||
)
|
||||
|
||||
# Check for CLARIFY button responses
|
||||
@@ -2639,6 +2645,61 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
except Exception as e:
|
||||
logger.debug("[rocketchat] Error processing CLARIFY response: %s", e)
|
||||
|
||||
# ── V8.5: WIDERSPRUCH-Clarify Response Handling ─────────────────
|
||||
# Button-Klick auf den Widerspruch-Clarify (2 Buttons):
|
||||
# WIDERSPRUCH:<clarify_id>:1 → 'generell hier her' → set_never_route
|
||||
# WIDERSPRUCH:<clarify_id>:2 → 'nur jetzt hier her' → stay_once
|
||||
if text.startswith("WIDERSPRUCH:"):
|
||||
routing_counter.increment('widerspruch_clarify_bypass')
|
||||
logger.info("ROUTING BYPASS: reason=widerspruch_clarify_bypass, origin_room=%s", room_id)
|
||||
try:
|
||||
parts = text.split(":", 2)
|
||||
if len(parts) == 3:
|
||||
_, clarify_id, choice = parts
|
||||
ctx = self._widerspruch_state.pop(clarify_id, None)
|
||||
origin_room_id = (ctx or {}).get("origin_room_id", room_id)
|
||||
topic = (ctx or {}).get("topic", "")
|
||||
if choice == "1":
|
||||
# Button 1: 'generell hier her' → dauerhaft never_route
|
||||
if _MULTIROOM() and self.archivar is not None and topic:
|
||||
self.archivar._state.set_never_route(origin_room_id, topic)
|
||||
logger.info(
|
||||
"[rocketchat] V8.5: Widerspruch → set_never_route "
|
||||
"room=%s topic='%s' (dauerhaft)",
|
||||
origin_room_id[:8], topic,
|
||||
)
|
||||
await self._post_message_with_retry(
|
||||
room_id,
|
||||
"🔒 Verstanden — dieses Thema bleibt ab jetzt generell hier. "
|
||||
"Ich route es nicht mehr automatisch um.",
|
||||
)
|
||||
elif choice == "2":
|
||||
# Button 2: 'nur jetzt hier her' → stay_once (einmalig)
|
||||
# Kein never_route, nur _recent_auto_routes löschen,
|
||||
# damit die nächste Nachricht wieder normal geroutet wird.
|
||||
self._recent_auto_routes.pop(origin_room_id, None)
|
||||
logger.info(
|
||||
"[rocketchat] V8.5: Widerspruch → stay_once "
|
||||
"room=%s (einmalig, kein never_route)",
|
||||
origin_room_id[:8],
|
||||
)
|
||||
await self._post_message_with_retry(
|
||||
room_id,
|
||||
"👍 Alles klar — nur dieses Mal bleibe ich hier. "
|
||||
"Beim nächsten Mal darf ich wieder routen.",
|
||||
)
|
||||
else:
|
||||
logger.warning("[rocketchat] Unknown WIDERSPRUCH choice: %s", choice)
|
||||
# P-067: Clear Clarify-Modal pulse (user responded)
|
||||
if hasattr(self, '_presence_engine') and self._presence_engine is not None and self._presence_engine.is_enabled():
|
||||
self._presence_engine.clear_clarify_modal()
|
||||
# P2-Korrektur: Widerspruch-State vollständig leeren, damit keine
|
||||
# stale Einträge (z.B. bei unbekannter choice) zurückbleiben.
|
||||
self._widerspruch_state.clear()
|
||||
return
|
||||
except Exception as e:
|
||||
logger.debug("[rocketchat] Error processing WIDERSPRUCH response: %s", e)
|
||||
|
||||
# ── V8.2.1 A2: ARCHIVAR_CLARIFY (Nachklärung) Response Handling ──
|
||||
if is_archivar_clarify:
|
||||
routing_counter.increment('archivar_clarify_bypass')
|
||||
@@ -3089,142 +3150,27 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
|
||||
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.5: Widerspruchs-Routine (Clarify statt Auto-Retrieve) ──────
|
||||
# Die alte V8.3-3 Auto-Retrieve-Routine (Keyword-basiert, löschte die
|
||||
# Nachricht aus dem Zielraum und holte sie zurück) wurde durch den
|
||||
# neuen Clarify-Flow ersetzt. Die Widerspruch-Erkennung läuft jetzt
|
||||
# zentral in classify_and_route() via detect_routing_contradiction()
|
||||
# (adapter_integration.py). Bei einem Treffer setzt die Decision
|
||||
# is_contradiction=True und der Adapter löst einen Clarify mit zwei
|
||||
# Buttons aus ('generell hier her' / 'nur jetzt hier her') statt
|
||||
# automatisch zu routen oder zurückzuholen.
|
||||
#
|
||||
# Der Widerspruch wird NICHT mehr hier (vor der Archivar-Klassifikation)
|
||||
# abgefangen, weil der neue Flow den vollen Router-Kontext braucht
|
||||
# (rejected_room/target_room für das Topic). Die Erkennung ist in
|
||||
# feedback_detector.py zentralisiert (inkl. HIER_HER-Muster für
|
||||
# positive Formulierungen wie 'Nein, es passt hier her').
|
||||
|
||||
# ── V8.3-4: Expliziter Raumwechsel (BEWUSSTE ENTSCHEIDUNG) ────────
|
||||
# V8.3.4 B3: Verb-basierte Erkennung statt #-Pflicht.
|
||||
# Pattern: 'lass uns in <raum> wechseln', 'wechseln nach <raum>', etc.
|
||||
# <raum> kann mit oder ohne # sein. Validierung via room-map.json.
|
||||
text_lower = text.lower()
|
||||
_EXPLICIT_SWITCH_RE = re.compile(
|
||||
r'(?:lass uns |gehen wir |wechsel(?:n)? )?(?:in |nach )?#?(\w[\w-]*)',
|
||||
re.IGNORECASE,
|
||||
@@ -3540,6 +3486,37 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
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()
|
||||
# ── V8.5: Routing-Widerspruch → Clarify statt Auto-Route ──
|
||||
if decision and getattr(decision, 'is_contradiction', False):
|
||||
# Topic aus dem Widerspruch-Kontext ableiten. Bevorzugt
|
||||
# das rejected_room/target_room des ContradictionResult,
|
||||
# sonst das Topic der letzten Auto-Route in diesem Raum.
|
||||
topic = ""
|
||||
cr = getattr(decision, 'contradiction_result', None)
|
||||
if cr is not None:
|
||||
room_name = cr.rejected_room or cr.target_room
|
||||
if room_name:
|
||||
topic = room_name_to_topic(room_name)
|
||||
if not topic:
|
||||
recent = self._recent_auto_routes.get(room_id)
|
||||
if recent:
|
||||
topic = recent.get("topic", "")
|
||||
if not topic:
|
||||
# Fallback: Raum-Name des Ursprungsraums
|
||||
topic = room_name_to_topic(
|
||||
self._room_info.get(room_id, {}).get("name", room_name)
|
||||
)
|
||||
await self._send_widerspruch_clarify(
|
||||
room_id=room_id,
|
||||
origin_room_id=room_id,
|
||||
topic=topic,
|
||||
)
|
||||
routing_counter.increment('widerspruch_clarify_sent')
|
||||
logger.info(
|
||||
"ROUTING BYPASS: reason=widerspruch_clarify, origin_room=%s, topic='%s'",
|
||||
room_id, topic,
|
||||
)
|
||||
return
|
||||
if decision and decision.category:
|
||||
category = decision.category
|
||||
# Wenn Zielraum = Ursprungsraum → stay_in_room, kein Move-Request
|
||||
@@ -7777,6 +7754,78 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
metadata=metadata,
|
||||
)
|
||||
|
||||
async def _send_widerspruch_clarify(
|
||||
self,
|
||||
room_id: str,
|
||||
origin_room_id: str,
|
||||
topic: str,
|
||||
) -> bool:
|
||||
"""Sende den Widerspruch-Clarify mit zwei Buttons (V8.5).
|
||||
|
||||
Wird aufgerufen, wenn detect_routing_contradiction einen
|
||||
Routing-Widerspruch erkannt hat. Zwei Buttons:
|
||||
|
||||
- Button 1: 'generell hier her' → set_never_route (dauerhaft)
|
||||
- Button 2: 'nur jetzt hier her' → stay_once (einmalig)
|
||||
|
||||
Nutzt die button_builder-Pipeline (P-066: Emoji-Nummerierung,
|
||||
Chunking, action_id) und aktiviert den Clarify-Modal-Puls (P-067).
|
||||
|
||||
Args:
|
||||
room_id: Der Raum, in dem der Widerspruch geschrieben wurde.
|
||||
origin_room_id: Der Ursprungsraum (für set_never_route).
|
||||
topic: Das Thema (Topic-Slug) für set_never_route.
|
||||
|
||||
Returns:
|
||||
True wenn die Buttons gesendet wurden, sonst False.
|
||||
"""
|
||||
if not self.rest.auth_token:
|
||||
return False
|
||||
|
||||
clarify_id = uuid.uuid4().hex[:12]
|
||||
# Kontext für den WIDERSPRUCH:-Button-Handler speichern
|
||||
self._widerspruch_state[clarify_id] = {
|
||||
"origin_room_id": origin_room_id,
|
||||
"topic": topic,
|
||||
}
|
||||
|
||||
from archivar.button_builder import build_button_attachments
|
||||
|
||||
num_buttons = [
|
||||
("generell hier her", f"WIDERSPRUCH:{clarify_id}:1"),
|
||||
("nur jetzt hier her", f"WIDERSPRUCH:{clarify_id}:2"),
|
||||
]
|
||||
attachments = build_button_attachments(
|
||||
num_buttons,
|
||||
special_buttons=[],
|
||||
color="#f5455c",
|
||||
title="Widerspruch erkannt — wie soll ich routen?",
|
||||
number_buttons=True,
|
||||
button_style="primary",
|
||||
)
|
||||
|
||||
text = (
|
||||
"❓ Widerspruch erkannt\n\n"
|
||||
"Du widersprichst der automatischen Zuordnung. "
|
||||
"Wie soll ich künftig mit diesem Thema umgehen?"
|
||||
)
|
||||
success = await self._post_message_with_retry(room_id, text, attachments=attachments)
|
||||
if success:
|
||||
self._rooms_with_pending_questions.add(room_id)
|
||||
# P-067: Clarify-Modal-Puls aktivieren
|
||||
if self._presence_engine and self._presence_engine.is_enabled():
|
||||
self._presence_engine.set_clarify_modal("Widerspruch erkannt")
|
||||
logger.info(
|
||||
"[rocketchat] V8.5: Widerspruch-Clarify gesendet — "
|
||||
"room=%s clarify_id=%s topic='%s'",
|
||||
room_id[:8], clarify_id, topic,
|
||||
)
|
||||
return True
|
||||
else:
|
||||
self._widerspruch_state.pop(clarify_id, None)
|
||||
logger.warning("[rocketchat] V8.5: Widerspruch-Clarify send failed for %s", room_id[:8])
|
||||
return False
|
||||
|
||||
async def send_typing(self, chat_id: str, metadata=None) -> None:
|
||||
pass
|
||||
|
||||
|
||||
@@ -396,6 +396,32 @@ class ArchivarMessageHandler:
|
||||
|
||||
decision = await self._router.route(text, origin_room_id, is_dm=is_dm)
|
||||
|
||||
# ── V8.5: Routing-Widerspruch als Pre-Check ─────────────────────
|
||||
# detect_routing_contradiction() wird NACH dem Router aufgerufen,
|
||||
# aber VOR der Stats-/Move-Request-Verarbeitung. Bei einem Treffer
|
||||
# wird die Entscheidung auf stay_in_room + is_contradiction gesetzt,
|
||||
# damit der Adapter einen Clarify (2 Buttons) auslöst statt zu routen.
|
||||
# Der Router selbst kennt den Widerspruch nicht — er hat bereits
|
||||
# eine normale RoutingDecision produziert. Wir überschreiben sie.
|
||||
contradiction = self.detect_routing_contradiction(text, origin_room_id)
|
||||
if contradiction is not None:
|
||||
logger.info(
|
||||
"V8.5: Routing-Widerspruch in classify_and_route — "
|
||||
"type=%s pattern=%s → Clarify statt Auto-Route",
|
||||
contradiction.contradiction_type,
|
||||
contradiction.matched_pattern,
|
||||
)
|
||||
decision.is_contradiction = True
|
||||
decision.contradiction_result = contradiction
|
||||
decision.stay_in_room = True
|
||||
decision.move_request_sent = False
|
||||
decision.needs_clarification = False
|
||||
decision.target_room = ""
|
||||
decision.category = "contradiction"
|
||||
self._stats["contradiction"] = self._stats.get("contradiction", 0) + 1
|
||||
routing_telemetry.flush()
|
||||
return decision
|
||||
|
||||
# Update stats
|
||||
self._stats["total"] += 1
|
||||
if decision.is_meta:
|
||||
|
||||
@@ -128,6 +128,28 @@ class RoutingWiderspruchDetector:
|
||||
re.IGNORECASE,
|
||||
)
|
||||
|
||||
# e) Hier-her-Bestätigung: positive Formulierung „passt hier her"
|
||||
# „Nein, es passt hier her", „Das gehört hier her", „Bleib hier"
|
||||
# → routing_rejection ohne Raumnennung (User will im aktuellen Raum bleiben).
|
||||
#
|
||||
# P1-Blocker-Fix (Rainer, Variante C): Negation wird per Lookahead
|
||||
# ausgeschlossen. „Das passt hier nicht" ist KEINE Bestätigung, sondern
|
||||
# die Aussage, dass es NICHT hierher gehört — darf nicht als Widerspruch
|
||||
# gegen eine Auto-Route matchen. Der Lookahead verhindert, dass ein
|
||||
# „nicht/nie/keinesfalls/kein" (ggf. mit „rein"/„gar" davor) direkt auf
|
||||
# das Hier-her-Muster folgt.
|
||||
HIER_HER: re.Pattern = re.compile(
|
||||
r"(?i)"
|
||||
r"(?:passt|gehört|gehoert|bleibt|bleib|soll|landet)\s+"
|
||||
r"(?:hier\s+her|hierher|hier\s+hin|hierhin|hier)"
|
||||
r"(?!\s*(?:rein\s+)?(?:gar\s+)?(?:nicht|nie|keinesfalls|kein))"
|
||||
r"|"
|
||||
r"(?:bleib|bleibe|lass\s+es)\s+hier"
|
||||
r"(?!\s*(?:nicht|nie|keinesfalls))"
|
||||
r"|"
|
||||
r"will\s+(?:(?!nicht|nie|kein).)*?\s+hier\s+haben",
|
||||
)
|
||||
|
||||
# ── Confidence-Werte pro Mustertyp ──────────────────────────────────
|
||||
|
||||
CONFIDENCE_MAP = {
|
||||
@@ -136,6 +158,7 @@ class RoutingWiderspruchDetector:
|
||||
"nicht_in_x_sondern_in_y": 0.92,
|
||||
"verneinung": 0.85,
|
||||
"befehle": 0.82,
|
||||
"hier_her": 0.86,
|
||||
}
|
||||
|
||||
# ── Public API ──────────────────────────────────────────────────────
|
||||
@@ -228,5 +251,19 @@ class RoutingWiderspruchDetector:
|
||||
matched_pattern="befehle",
|
||||
)
|
||||
|
||||
# ── e) Hier-her-Bestätigung ──────────────────────────────────────
|
||||
# Positive Formulierung „passt hier her" — User will im aktuellen
|
||||
# Raum bleiben. Wird NACH den spezifischeren Mustern geprüft, damit
|
||||
# „nicht in X, sondern hier" korrekt als reroute_request erkannt wird.
|
||||
m_hier = self.HIER_HER.search(text)
|
||||
if m_hier:
|
||||
logger.debug("Widerspruch (hier_her): matched")
|
||||
return ContradictionResult(
|
||||
has_contradiction=True,
|
||||
contradiction_type="routing_rejection",
|
||||
confidence=self.CONFIDENCE_MAP["hier_her"],
|
||||
matched_pattern="hier_her",
|
||||
)
|
||||
|
||||
# Kein Widerspruch erkannt
|
||||
return None
|
||||
|
||||
@@ -314,6 +314,17 @@ class RoutingDecision:
|
||||
"""Strukturierter Prompt für den Agenten: 'Router unsicher. Räume: ...'
|
||||
Leer wenn kein Red Flag."""
|
||||
|
||||
# ── V8.5: Routing-Widerspruch (Auto-Route-Widerspruch-Flow) ─────────
|
||||
|
||||
is_contradiction: bool = False
|
||||
"""True wenn die Nachricht einen Routing-Widerspruch enthält
|
||||
(detect_routing_contradiction hat getroffen). Der Adapter soll dann
|
||||
einen Clarify mit zwei Buttons auslösen statt zu routen."""
|
||||
|
||||
contradiction_result: Optional[Any] = None
|
||||
"""Das ContradictionResult-Objekt (feedback_detector) bei Treffer,
|
||||
sonst None. Enthält contradiction_type, rejected_room, target_room etc."""
|
||||
|
||||
def should_route(self) -> bool:
|
||||
"""True wenn die Nachricht geroutet werden sollte.
|
||||
|
||||
@@ -329,6 +340,7 @@ class RoutingDecision:
|
||||
not self.is_catch_all and
|
||||
not self.is_unrouteable and
|
||||
not self.move_request_sent and
|
||||
not self.is_contradiction and
|
||||
bool(self.target_room)
|
||||
)
|
||||
|
||||
|
||||
@@ -0,0 +1,335 @@
|
||||
"""
|
||||
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
|
||||
|
||||
# ── P1-Blocker 1: Negation darf NICHT als Widerspruch matchen ────────
|
||||
|
||||
def test_hier_her_negation_not_triggered(self):
|
||||
"""'Das passt hier nicht' → KEIN Widerspruch (Negation ausgeschlossen)."""
|
||||
d = _make_detector()
|
||||
r = d.detect("Das passt hier nicht")
|
||||
assert r is None
|
||||
|
||||
def test_passt_hier_nicht_does_not_match_hier_her(self):
|
||||
"""'Das passt hier nicht' → matched nicht das hier_her-Muster."""
|
||||
d = _make_detector()
|
||||
r = d.detect("Das passt hier nicht")
|
||||
assert r is None
|
||||
|
||||
def test_gehoert_nicht_hier_her_does_not_match_hier_her(self):
|
||||
"""'Das gehoert nicht hier her' → matched nicht das hier_her-Muster."""
|
||||
d = _make_detector()
|
||||
r = d.detect("Das gehoert nicht hier her")
|
||||
assert r is None
|
||||
|
||||
def test_passt_hierrein_gar_nicht_does_not_match_hier_her(self):
|
||||
"""'Das passt hierrein gar nicht' → matched nicht das hier_her-Muster."""
|
||||
d = _make_detector()
|
||||
r = d.detect("Das passt hierrein gar nicht")
|
||||
assert r is None
|
||||
|
||||
def test_will_das_hier_haben_matches(self):
|
||||
"""'Ich will das hier haben' → Widerspruch (hier_her-Muster)."""
|
||||
d = _make_detector()
|
||||
r = d.detect("Ich will das hier haben")
|
||||
assert r is not None
|
||||
assert r.has_contradiction
|
||||
assert r.matched_pattern == "hier_her"
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# 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
|
||||
Reference in New Issue
Block a user