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
This commit is contained in:
Bernd (Hermes)
2026-08-20 07:26:38 +02:00
parent 92455d70f4
commit 43a02c7884
5 changed files with 540 additions and 131 deletions
+175 -131
View File
@@ -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.
@@ -2639,6 +2643,58 @@ 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()
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 +3145,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 +3481,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 +7749,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
+26
View File
@@ -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:
+26
View File
@@ -128,6 +128,17 @@ 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).
HIER_HER: re.Pattern = re.compile(
r"(?:passt|gehört|gehoert|bleibt|bleib|soll|landet)\s+"
r"(?:hier\s+her|hierher|hier\s+hin|hierhin|hier)"
r"|"
r"(?:bleib|bleibe|lass\s+es)\s+hier",
re.IGNORECASE,
)
# ── Confidence-Werte pro Mustertyp ──────────────────────────────────
CONFIDENCE_MAP = {
@@ -136,6 +147,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 +240,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
+12
View File
@@ -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)
)