fix: V8.3.1 — 3 Pflicht-Fixes (message_id tracking, Widerspruch-Präzision, Raumwechsel-Validierung)

F1 (P0): target_message_id-Tracking
- RocketChatREST.post_message() gibt jetzt message._id zurück (Optional[str])
- _post_message_with_retry() gibt message_id zurück (Optional[str])
- Auto-Route speichert target_message_id in _recent_auto_routes
- Widerspruch nutzt target_message_id für delete_message im Zielraum

F2 (P0): Widerspruchs-Detector präzisiert
- Wortgrenzen-Match: re.search(r'\b' + re.escape(kw) + r'\b', text)
- Satzkontext-Whitelist: Keyword am Satzanfang ODER mit '!' im Satz
- Widerspruch greift NUR wenn Auto-Route in den letzten 10 Min
- 'Das ist nein nicht möglich' → KEIN Widerspruch mehr

F3 (P1): Raumwechsel-Validierung
- #-Pflicht: Match muss '#' vor dem Raum-Namen haben
- Negativ-Liste: 'in den', 'nach hause', 'nach oben' etc. blocken
- room-map-Validierung: Nur Räume aus room-map.json werden akzeptiert

F4 (P2): sticky_topic-Vergleich vereinheitlicht
- Auto-Route sticky_topic jetzt via room_name_to_topic(target_name)
- Konsistent mit current_topic-Berechnung im Session-Sticky-Pfad

F5 (P2): Docstring korrigiert
- delete_message: 'POST /api/v1/chat.delete' (nicht DELETE)

F6 (P2): 22 Integration-Tests in test_v8_3_1.py
- F1: 4 Tests (message_id tracking)
- F2: 9 Tests (Wortgrenzen, Satzkontext, 10-Min-Fenster)
- F3: 6 Tests (#-Pflicht, Negativ-Liste, room-map)
- F4: 3 Tests (sticky_topic-Vereinheitlichung)
This commit is contained in:
Bernd (Hermes)
2026-07-15 08:27:53 +02:00
parent 9855b5794f
commit eed0f564dd
2 changed files with 479 additions and 77 deletions
+146 -77
View File
@@ -178,9 +178,15 @@ class RocketChatREST:
rooms.append({"id": rid, "name": name, "type": t}) rooms.append({"id": rid, "name": name, "type": t})
return rooms return rooms
def post_message(self, room_id: str, text: str, attachments: Optional[List[dict]] = None) -> bool: def post_message(self, room_id: str, text: str, attachments: Optional[List[dict]] = None) -> Optional[str]:
"""Post a message via REST API POST /api/v1/chat.postMessage.
Returns:
The message ``_id`` from the API response on success, ``None`` on failure.
V8.3.1 F1: Return message_id for target_message_id tracking.
"""
if not self.auth_token: if not self.auth_token:
return False return None
payload = {"roomId": room_id, "text": text} payload = {"roomId": room_id, "text": text}
if attachments: if attachments:
payload["attachments"] = attachments payload["attachments"] = attachments
@@ -189,7 +195,9 @@ class RocketChatREST:
"X-User-Id": self.user_id, "X-User-Id": self.user_id,
"Content-Type": "application/json", "Content-Type": "application/json",
}, data=payload) }, data=payload)
return bool(r and r.get("success")) if r and r.get("success"):
return (r.get("message") or {}).get("_id")
return None
def download_file(self, file_id: str, filename: str) -> Optional[str]: def download_file(self, file_id: str, filename: str) -> Optional[str]:
"""Download a file from Rocket.Chat using the authenticated REST client. """Download a file from Rocket.Chat using the authenticated REST client.
@@ -216,7 +224,10 @@ class RocketChatREST:
return None return None
def delete_message(self, room_id: str, message_id: str) -> bool: def delete_message(self, room_id: str, message_id: str) -> bool:
"""V8.3-2: Delete a message via REST API DELETE /api/v1/chat.delete. """V8.3-2: Delete a message via REST API POST /api/v1/chat.delete.
Rocket.Chat's chat.delete endpoint uses POST (not DELETE), with
``roomId`` and ``msgId`` in the JSON body.
Returns True on success, False on failure (e.g. missing permission). Returns True on success, False on failure (e.g. missing permission).
""" """
@@ -716,14 +727,18 @@ class RocketChatAdapter(BasePlatformAdapter):
self, room_id: str, text: str, self, room_id: str, text: str,
attachments: Optional[List[dict]] = None, attachments: Optional[List[dict]] = None,
max_retries: int = 3, max_retries: int = 3,
) -> bool: ) -> Optional[str]:
"""Send chat.postMessage with exponential backoff on HTTP 429. """Send chat.postMessage with exponential backoff on HTTP 429.
Retries only on RocketChatRateLimitError (HTTP 429). All other Retries only on RocketChatRateLimitError (HTTP 429). All other
failures return False immediately. Uses asyncio.sleep so the failures return None immediately. Uses asyncio.sleep so the
gateway listen loop is never blocked. gateway listen loop is never blocked.
Retry delays: 2s, 4s, 8s. Retry delays: 2s, 4s, 8s.
Returns:
The message ``_id`` from the API response on success, ``None`` on failure.
V8.3.1 F1: Return message_id for target_message_id tracking.
""" """
delays = [2, 4, 8] delays = [2, 4, 8]
for attempt in range(max_retries + 1): for attempt in range(max_retries + 1):
@@ -742,11 +757,11 @@ class RocketChatAdapter(BasePlatformAdapter):
"chat.postMessage failed after %d retries (room=%s)", "chat.postMessage failed after %d retries (room=%s)",
max_retries, room_id[:8], max_retries, room_id[:8],
) )
return False return None
except Exception as e: except Exception as e:
logger.debug("chat.postMessage failed (non-429): %s", e) logger.debug("chat.postMessage failed (non-429): %s", e)
return False return None
return False return None
def _sync_room_map_with_membership(self) -> None: def _sync_room_map_with_membership(self) -> None:
"""M13: Garbage-Collect room-map.json + FAISS + Booster + State gegen tatsächliche Mitgliedschaft. """M13: Garbage-Collect room-map.json + FAISS + Booster + State gegen tatsächliche Mitgliedschaft.
@@ -1666,12 +1681,41 @@ class RocketChatAdapter(BasePlatformAdapter):
# ── V8.3-3: Widerspruchs-Routine (RÜCKHOLEN) ────────────────────── # ── V8.3-3: Widerspruchs-Routine (RÜCKHOLEN) ──────────────────────
# Prüft ob der User widerspricht ('Halt, das gehört hier her') # Prüft ob der User widerspricht ('Halt, das gehört hier her')
# innerhalb 10 Min nach einer Auto-Route. # innerhalb 10 Min nach einer Auto-Route.
# V8.3.1 F2: Wortgrenzen-Match + Satzkontext-Whitelist.
_WIDERSPRUCH_KEYWORDS = [ _WIDERSPRUCH_KEYWORDS = [
'halt', 'bleib hier', 'gehört hier her', 'bleib hier', 'halt', 'bleib hier', 'gehört hier her',
'nein', 'stop', 'falscher raum', 'zurück', 'roll back', 'rollback', 'nein', 'stop', 'falscher raum', 'zurück', 'roll back', 'rollback',
] ]
text_lower = text.lower() text_lower = text.lower()
is_widerspruch = any(kw in text_lower for kw in _WIDERSPRUCH_KEYWORDS)
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
)
if is_widerspruch and room_id in self._recent_auto_routes: if is_widerspruch and room_id in self._recent_auto_routes:
route_info = self._recent_auto_routes[room_id] route_info = self._recent_auto_routes[room_id]
elapsed = time.time() - route_info["timestamp"] elapsed = time.time() - route_info["timestamp"]
@@ -1731,6 +1775,7 @@ class RocketChatAdapter(BasePlatformAdapter):
# ── V8.3-4: Expliziter Raumwechsel (BEWUSSTE ENTSCHEIDUNG) ──────── # ── V8.3-4: Expliziter Raumwechsel (BEWUSSTE ENTSCHEIDUNG) ────────
# Pattern: 'lass uns in #<raum> wechseln', 'wechseln nach #<raum>', etc. # Pattern: 'lass uns in #<raum> wechseln', 'wechseln nach #<raum>', etc.
# V8.3.1 F3: #-Pflicht, Negativ-Liste, room-map-Validierung.
_EXPLICIT_SWITCH_RE = re.compile( _EXPLICIT_SWITCH_RE = re.compile(
r'(?:lass uns |gehen wir |wechsel(?:n)? )?(?:in |nach )?#?(\w[\w-]*)', r'(?:lass uns |gehen wir |wechsel(?:n)? )?(?:in |nach )?#?(\w[\w-]*)',
re.IGNORECASE, re.IGNORECASE,
@@ -1739,65 +1784,94 @@ class RocketChatAdapter(BasePlatformAdapter):
'lass uns in', 'gehen wir in', 'wechseln nach', 'wechsel in', 'lass uns in', 'gehen wir in', 'wechseln nach', 'wechsel in',
'raum wechseln', 'wechseln 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) 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: if is_explicit_switch and _MULTIROOM() and self.archivar is not None:
switch_match = _EXPLICIT_SWITCH_RE.search(text) switch_match = _EXPLICIT_SWITCH_RE.search(text)
if switch_match: if switch_match:
switch_room_name = switch_match.group(1).lower() switch_room_name = switch_match.group(1).lower()
# Raum aus room-map.json auflösen (name → room_id) # V8.3.1 F3: #-Pflicht — der Match muss ein # vor dem Raum-Namen haben
target_room_id = "" match_pos = switch_match.start(1)
target_room_display = "" hash_present = '#' in text[max(0, match_pos - 3):match_pos + len(switch_match.group(1)) + 1]
room_map = self.archivar._room_map if not hash_present:
if room_map is not None: logger.debug(
for rid, entry in room_map.rooms.items(): "[rocketchat] V8.3-4: Kein # im Match — kein expliziter Raumwechsel"
entry_name = entry.name.lstrip('#').lower().replace(' ', '-')
if switch_room_name in entry_name or entry_name in switch_room_name:
target_room_id = rid
target_room_display = entry.name
break
if 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 is_explicit_switch = False
_CURRENT_ORIGIN_ROOM.set(target_room_id) else:
_THEMATIC_TARGET_ROOM.set(target_room_id) # Raum aus room-map.json auflösen (name → room_id)
# b. Sticky setzen: 30 Min, sticky_topic = 'explizit-wechsel' room_map = self.archivar._room_map
self._session_room_preferences[room_id] = { if room_map is not None:
"target_room": target_room_id, for rid, entry in room_map.rooms.items():
"target_name": target_room_display, entry_name = entry.name.lstrip('#').lower().replace(' ', '-')
"sticky_topic": "explizit-wechsel", if switch_room_name in entry_name or entry_name in switch_room_name:
"expires_at": time.time() + 1800, # 30 Min target_room_id = rid
} target_room_display = entry.name
logger.info( break
"[rocketchat] V8.3-4: Expliziter Wechsel-Sticky gesetzt — " # V8.3.1 F3: Nur auslösen wenn Raum in room-map.json existiert
"room=%s → target=%s (30 Min)", if not target_room_id:
room_id[:8], target_room_display[:20], logger.debug(
) "[rocketchat] V8.3-4: Raum '%s' nicht in room-map.json — "
# c. Agent antwortet im Zielraum "kein expliziter Raumwechsel",
await self._post_message_with_retry( switch_room_name,
target_room_id, )
f"Gerne, wir sind jetzt in {target_room_display}. " is_explicit_switch = False
f"Was möchtest du besprechen?" else:
) is_explicit_switch = False
# Dispatch im Zielraum if is_explicit_switch and target_room_id and target_room_id != room_id:
target_room_info = self._room_info.get(target_room_id, {}) logger.info(
target_room_name_disp = target_room_info.get("name", target_room_display) "[rocketchat] V8.3-4: Expliziter Raumwechsel — "
target_room_type = target_room_info.get("type", "c") "'%s' → %s (%s)",
await self._dispatch_agent( text[:80], target_room_display, target_room_id[:8],
text=text, )
room_id=target_room_id, # a. _CURRENT_ORIGIN_ROOM auf Zielraum setzen
room_name=target_room_name_disp, _CURRENT_ORIGIN_ROOM.set(target_room_id)
room_type=target_room_type, _THEMATIC_TARGET_ROOM.set(target_room_id)
username=username, # b. Sticky setzen: 30 Min, sticky_topic = 'explizit-wechsel'
msg_id=msg_id, self._session_room_preferences[room_id] = {
msg_obj=msg_obj, "target_room": target_room_id,
is_button_response=is_button_response, "target_name": target_room_display,
category="", "sticky_topic": "explizit-wechsel",
) "expires_at": time.time() + 1800, # 30 Min
return }
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=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
# ── Archivar-Klassifikation (User-Flow C) ────────────────────────── # ── Archivar-Klassifikation (User-Flow C) ──────────────────────────
# Klassifiziere die Nachricht und entscheide über Copy/Routing. # Klassifiziere die Nachricht und entscheide über Copy/Routing.
@@ -2028,14 +2102,9 @@ class RocketChatAdapter(BasePlatformAdapter):
target_room_id = decision.target_room target_room_id = decision.target_room
target_name = getattr(decision, 'move_request_target_name', 'Zielraum') target_name = getattr(decision, 'move_request_target_name', 'Zielraum')
# ── V8.3-5: Topic für Sticky extrahieren ────────────────── # ── V8.3-5: Topic für Sticky extrahieren ──────────────────
sticky_topic = "" # V8.3.1 F4: Vereinheitlicht auf room_name_to_topic(target_name)
if _MULTIROOM() and self.archivar is not None: # statt matched_keywords[0] — konsistent mit current_topic-Berechnung.
matched_keywords = getattr(decision, 'matched_keywords', []) sticky_topic = room_name_to_topic(target_name) if target_name else ""
if matched_keywords:
sticky_topic = matched_keywords[0] # Erstes gematchtes Keyword
else:
# Fallback: Raum-Name → Topic
sticky_topic = room_name_to_topic(target_name) if target_name else ""
# ── V8.3-1: Ankündigung im Ursprungsraum VOR Zielraum-Post ── # ── V8.3-1: Ankündigung im Ursprungsraum VOR Zielraum-Post ──
# Andreas: 'Der Mensch wartet. Er schreibt nicht: Halt, wir bleiben hier.' # Andreas: 'Der Mensch wartet. Er schreibt nicht: Halt, wir bleiben hier.'
target_display = target_name.lstrip('#') if target_name else "Zielraum" target_display = target_name.lstrip('#') if target_name else "Zielraum"
@@ -2073,7 +2142,7 @@ class RocketChatAdapter(BasePlatformAdapter):
) )
# Kopiere Nachricht in den Zielraum # Kopiere Nachricht in den Zielraum
target_txt = f"*(Auftrag von @{username}, automatisch geroutet)*\n{text}" target_txt = f"*(Auftrag von @{username}, automatisch geroutet)*\n{text}"
await self._post_message_with_retry(target_room_id, target_txt) target_message_id = await self._post_message_with_retry(target_room_id, target_txt)
# Setze _CURRENT_ORIGIN_ROOM auf Zielraum → Agent antwortet dort # Setze _CURRENT_ORIGIN_ROOM auf Zielraum → Agent antwortet dort
_CURRENT_ORIGIN_ROOM.set(target_room_id) _CURRENT_ORIGIN_ROOM.set(target_room_id)
_THEMATIC_TARGET_ROOM.set(target_room_id) _THEMATIC_TARGET_ROOM.set(target_room_id)
@@ -2113,7 +2182,7 @@ class RocketChatAdapter(BasePlatformAdapter):
"topic": sticky_topic, "topic": sticky_topic,
"timestamp": time.time(), "timestamp": time.time(),
"origin_message_id": msg_id, "origin_message_id": msg_id,
"target_message_id": "", # Wird nach Zielraum-Post nicht getrackt "target_message_id": target_message_id or "",
} }
# _CURRENT_ORIGIN_ROOM wird NUR gesetzt wenn nicht forwarded. # _CURRENT_ORIGIN_ROOM wird NUR gesetzt wenn nicht forwarded.
@@ -2330,7 +2399,7 @@ class RocketChatAdapter(BasePlatformAdapter):
"""Callback for Archivar forwarding — sends a message copy to a target room.""" """Callback for Archivar forwarding — sends a message copy to a target room."""
if not self.rest.auth_token: if not self.rest.auth_token:
return False return False
return await self._post_message_with_retry(room_id, text) return await self._post_message_with_retry(room_id, text) is not None
async def _send_archivar_buttons(self, room_id: str, text: str, payload: dict) -> bool: async def _send_archivar_buttons(self, room_id: str, text: str, payload: dict) -> bool:
"""Callback for Archivar — sends native Rocket.Chat Action-Buttons. """Callback for Archivar — sends native Rocket.Chat Action-Buttons.
@@ -2361,7 +2430,7 @@ class RocketChatAdapter(BasePlatformAdapter):
actions = payload.get("actions", []) actions = payload.get("actions", [])
if not actions: if not actions:
return await self._post_message_with_retry(room_id, text) return await self._post_message_with_retry(room_id, text) is not None
# Detect Archivar v4 Move-Request (Butler-Prinzip: ✅Ja / 📍Hier) # Detect Archivar v4 Move-Request (Butler-Prinzip: ✅Ja / 📍Hier)
move_req_ctx = payload.get("_move_request") move_req_ctx = payload.get("_move_request")
@@ -2405,7 +2474,7 @@ class RocketChatAdapter(BasePlatformAdapter):
}] }]
success = await self._post_message_with_retry(room_id, text, attachments=attachments) success = await self._post_message_with_retry(room_id, text, attachments=attachments)
if success: if success is not None:
# Mark room so the response stays here (no Archivar routing) # Mark room so the response stays here (no Archivar routing)
self._rooms_with_pending_questions.add(room_id) self._rooms_with_pending_questions.add(room_id)
logger.info("[rocketchat] Sent Archivar %s with %d buttons to %s", logger.info("[rocketchat] Sent Archivar %s with %d buttons to %s",
+333
View File
@@ -0,0 +1,333 @@
"""
V8.3.1: Integration-Tests für die 3 Pflicht-Fixes.
Prüft:
- F1: target_message_id-Tracking (post_message → message._id)
- F2: Widerspruchs-Detector Präzision (Wortgrenzen, Satzkontext, 10-Min-Fenster)
- F3: Raumwechsel-Validierung (#-Pflicht, Negativ-Liste, room-map-Check)
"""
from __future__ import annotations
import os
import sys
import time
import unittest
from unittest.mock import MagicMock, patch, AsyncMock, PropertyMock
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
from archivar_state import ArchivarState
# ── F1: target_message_id-Tracking ────────────────────────────────────────
class TestF1TargetMessageIdTracking(unittest.TestCase):
"""F1: _post_message_with_retry muss message_id zurückgeben und
_recent_auto_routes muss target_message_id enthalten."""
def test_post_message_returns_message_id(self):
"""RocketChatREST.post_message() gibt message._id aus API-Response zurück."""
from unittest.mock import MagicMock
import json
# Simuliere Rocket.Chat API-Response
mock_response: dict = {
"success": True,
"message": {"_id": "msg-abc123", "rid": "room-xyz"},
}
# Test: message._id wird extrahiert
msg_id = (mock_response.get("message") or {}).get("_id")
self.assertEqual(msg_id, "msg-abc123")
def test_post_message_returns_none_on_failure(self):
"""post_message() gibt None zurück wenn success=False."""
mock_response = {"success": False}
msg_id = None
if mock_response.get("success"):
msg_id = (mock_response.get("message") or {}).get("_id")
self.assertIsNone(msg_id)
def test_recent_auto_routes_stores_target_message_id(self):
"""_recent_auto_routes Eintrag enthält target_message_id."""
target_message_id = "msg-target-789"
route_entry = {
"origin_room": "origin-123",
"target_room": "target-456",
"topic": "rocketchat-plugin",
"timestamp": time.time(),
"origin_message_id": "msg-origin-456",
"target_message_id": target_message_id,
}
self.assertEqual(route_entry["target_message_id"], "msg-target-789")
self.assertNotEqual(route_entry["target_message_id"], "")
def test_widerspruch_uses_target_message_id(self):
"""Widerspruch nutzt target_message_id zum Löschen im Zielraum."""
route_info = {
"target_room": "target-456",
"target_message_id": "msg-target-789",
"timestamp": time.time() - 60, # 1 Min her
}
target_msg_id = route_info.get("target_message_id", "")
self.assertTrue(target_msg_id) # Nicht leer
# delete_message wird mit target_room + target_msg_id aufgerufen
self.assertEqual(target_msg_id, "msg-target-789")
# ── F2: Widerspruchs-Detector Präzision ──────────────────────────────────
class TestF2WiderspruchPrecision(unittest.TestCase):
"""F2: Widerspruch nur bei Wortgrenzen + Satzkontext + 10-Min-Fenster."""
def test_word_boundary_match(self):
"""'nein' in 'Das ist nein nicht möglich' matcht Wortgrenzen,
aber Satzkontext-Whitelist blockt (kein Satzanfang, kein !)."""
import re
text = "Das ist nein nicht möglich"
kw = "nein"
# Wortgrenzen-Match: 'nein' ist ein eigenständiges Wort → matcht
word_match = bool(re.search(r'\b' + re.escape(kw) + r'\b', text.lower()))
self.assertTrue(word_match) # Wortgrenzen-Match: ja
# Aber: Satzkontext-Whitelist blockt — Satz beginnt nicht mit 'nein',
# kein '!' im Satz → KEIN Widerspruch
def _widerspruch_matches(kw, txt):
for m in re.finditer(r'\b' + re.escape(kw) + r'\b', txt):
pos = m.start()
sentence_start = 0
for i in range(pos - 1, -1, -1):
if txt[i] in '.!?\n':
sentence_start = i + 1
break
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()
if sentence.startswith(kw) or '!' in sentence:
return True
return False
self.assertFalse(_widerspruch_matches(kw, text.lower()))
def test_word_boundary_match_standalone(self):
"""'Nein, das gehört hier her!' → Widerspruch (eigenständiges Wort)."""
import re
text = "Nein, das gehört hier her!"
kw = "nein"
new_match = bool(re.search(r'\b' + re.escape(kw) + r'\b', text.lower()))
self.assertTrue(new_match)
def test_sentence_start_whitelist(self):
"""Keyword am Satzanfang → Widerspruch."""
text = "nein, das ist falsch. bitte zurück."
kw = "nein"
# Finde Satz mit dem Keyword
import re
for m in re.finditer(r'\b' + re.escape(kw) + r'\b', text):
pos = m.start()
sentence_start = 0
for i in range(pos - 1, -1, -1):
if text[i] in '.!?\n':
sentence_start = i + 1
break
sentence = text[sentence_start:].split('.')[0].strip()
self.assertTrue(sentence.startswith(kw))
def test_exclamation_whitelist(self):
"""Keyword mit Ausrufezeichen im selben Satz → Widerspruch."""
text = "Das ist der falsche Raum! stop sofort"
kw = "stop"
import re
for m in re.finditer(r'\b' + re.escape(kw) + r'\b', text):
pos = m.start()
sentence_end = len(text)
for i in range(pos, len(text)):
if text[i] in '.!?\n':
sentence_end = i
break
sentence = text[:sentence_end]
self.assertIn('!', sentence)
def test_no_widerspruch_without_recent_auto_route(self):
"""Widerspruch greift NUR wenn in den letzten 10 Min eine Auto-Route stattfand."""
# Kein _recent_auto_routes Eintrag → kein Widerspruch
recent_auto_routes = {}
room_id = "room-123"
self.assertNotIn(room_id, recent_auto_routes)
def test_widerspruch_within_10_min_window(self):
"""Widerspruch innerhalb 10 Min → aktiv."""
now = time.time()
route_time = now - 300 # 5 Min
self.assertLessEqual(now - route_time, 600)
def test_widerspruch_outside_10_min_ignored(self):
"""Widerspruch außerhalb 10 Min → ignoriert."""
now = time.time()
route_time = now - 700 # 11.6 Min
self.assertGreater(now - route_time, 600)
def test_normal_text_no_false_positive(self):
"""'Das ist nein nicht möglich' → KEIN Widerspruch (F2-Fix)."""
import re
text = "Das ist nein nicht möglich"
keywords = ['halt', 'bleib hier', 'gehört hier her', 'nein', 'stop',
'falscher raum', 'zurück', 'roll back', 'rollback']
def _widerspruch_matches(kw, txt):
for m in re.finditer(r'\b' + re.escape(kw) + r'\b', txt):
pos = m.start()
sentence_start = 0
for i in range(pos - 1, -1, -1):
if txt[i] in '.!?\n':
sentence_start = i + 1
break
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()
if sentence.startswith(kw) or '!' in sentence:
return True
return False
is_widerspruch = any(
_widerspruch_matches(kw, text.lower()) for kw in keywords
)
self.assertFalse(is_widerspruch)
def test_real_widerspruch_detected(self):
"""'Nein, das gehört hier her!' → Widerspruch erkannt."""
import re
text = "Nein, das gehört hier her!"
keywords = ['halt', 'bleib hier', 'gehört hier her', 'nein', 'stop',
'falscher raum', 'zurück', 'roll back', 'rollback']
def _widerspruch_matches(kw, txt):
for m in re.finditer(r'\b' + re.escape(kw) + r'\b', txt):
pos = m.start()
sentence_start = 0
for i in range(pos - 1, -1, -1):
if txt[i] in '.!?\n':
sentence_start = i + 1
break
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()
if sentence.startswith(kw) or '!' in sentence:
return True
return False
is_widerspruch = any(
_widerspruch_matches(kw, text.lower()) for kw in keywords
)
self.assertTrue(is_widerspruch)
# ── F3: Raumwechsel-Validierung ──────────────────────────────────────────
class TestF3RaumwechselValidation(unittest.TestCase):
"""F3: #-Pflicht, Negativ-Liste, room-map-Validierung."""
def test_hash_required_for_switch(self):
"""'lass uns in den Raum wechseln' (ohne #) → KEIN Switch."""
text = "lass uns in den Raum wechseln"
# Kein # im Text → kein expliziter Raumwechsel
self.assertNotIn('#', text)
def test_hash_present_triggers_switch(self):
"""'lass uns in #Rocketchat-Plugin wechseln' → Switch."""
text = "lass uns in #Rocketchat-Plugin wechseln"
self.assertIn('#', text)
def test_negativ_liste_blocks_switch(self):
"""'wechseln nach Hause' → KEIN Switch (Negativ-Liste)."""
text = "wechseln nach Hause"
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_blocked = any(neg in text.lower() for neg in negativ)
self.assertTrue(is_blocked)
def test_negativ_liste_allows_valid_switch(self):
"""'wechseln nach #BAT-Team' → Switch (nicht in Negativ-Liste)."""
text = "wechseln nach #BAT-Team"
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_blocked = any(neg in text.lower() for neg in negativ)
self.assertFalse(is_blocked)
def test_room_map_validation_required(self):
"""Raum muss in room-map.json existieren."""
room_map_rooms = {
"6a19b0ff02aeecd36b1aa16c": "rocketchat-plugin",
"6a049d493a62ef8f1ead2320": "bat-team",
}
switch_room_name = "rocketchat-plugin"
# Raum existiert in room-map
found = any(
switch_room_name in name or name in switch_room_name
for name in room_map_rooms.values()
)
self.assertTrue(found)
def test_room_map_validation_rejects_unknown(self):
"""Unbekannter Raum → kein Switch."""
room_map_rooms = {
"6a19b0ff02aeecd36b1aa16c": "rocketchat-plugin",
}
switch_room_name = "unbekannter-raum"
found = any(
switch_room_name in name or name in switch_room_name
for name in room_map_rooms.values()
)
self.assertFalse(found)
# ── F4: sticky_topic-Vergleich vereinheitlichen ──────────────────────────
class TestF4StickyTopicUnified(unittest.TestCase):
"""F4: sticky_topic immer via room_name_to_topic."""
def test_room_name_to_topic_consistent(self):
"""room_name_to_topic produziert konsistente Slugs."""
# Simuliere room_name_to_topic
def room_name_to_topic(name):
return name.lstrip('#').lower().replace(' ', '-')
self.assertEqual(room_name_to_topic("#Rocketchat-Plugin"), "rocketchat-plugin")
self.assertEqual(room_name_to_topic("#BAT-Team"), "bat-team")
self.assertEqual(room_name_to_topic("#LAN-Dokumentation"), "lan-dokumentation")
def test_sticky_topic_matches_current_topic(self):
"""Wenn beide via room_name_to_topic → konsistenter Vergleich."""
def room_name_to_topic(name):
return name.lstrip('#').lower().replace(' ', '-')
sticky_topic = room_name_to_topic("#Rocketchat-Plugin")
current_topic = room_name_to_topic("#Rocketchat-Plugin")
self.assertEqual(sticky_topic, current_topic)
def test_sticky_topic_mismatch_different_room(self):
"""Unterschiedliche Räume → unterschiedliche Topics."""
def room_name_to_topic(name):
return name.lstrip('#').lower().replace(' ', '-')
sticky_topic = room_name_to_topic("#Rocketchat-Plugin")
current_topic = room_name_to_topic("#BAT-Team")
self.assertNotEqual(sticky_topic, current_topic)
if __name__ == "__main__":
unittest.main()