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})
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:
return False
return None
payload = {"roomId": room_id, "text": text}
if attachments:
payload["attachments"] = attachments
@@ -189,7 +195,9 @@ class RocketChatREST:
"X-User-Id": self.user_id,
"Content-Type": "application/json",
}, 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]:
"""Download a file from Rocket.Chat using the authenticated REST client.
@@ -216,7 +224,10 @@ class RocketChatREST:
return None
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).
"""
@@ -716,14 +727,18 @@ class RocketChatAdapter(BasePlatformAdapter):
self, room_id: str, text: str,
attachments: Optional[List[dict]] = None,
max_retries: int = 3,
) -> bool:
) -> Optional[str]:
"""Send chat.postMessage with exponential backoff on HTTP 429.
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.
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]
for attempt in range(max_retries + 1):
@@ -742,11 +757,11 @@ class RocketChatAdapter(BasePlatformAdapter):
"chat.postMessage failed after %d retries (room=%s)",
max_retries, room_id[:8],
)
return False
return None
except Exception as e:
logger.debug("chat.postMessage failed (non-429): %s", e)
return False
return False
return None
return None
def _sync_room_map_with_membership(self) -> None:
"""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) ──────────────────────
# Prüft ob der User widerspricht ('Halt, das gehört hier her')
# innerhalb 10 Min nach einer Auto-Route.
# V8.3.1 F2: Wortgrenzen-Match + Satzkontext-Whitelist.
_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',
]
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:
route_info = self._recent_auto_routes[room_id]
elapsed = time.time() - route_info["timestamp"]
@@ -1731,6 +1775,7 @@ class RocketChatAdapter(BasePlatformAdapter):
# ── V8.3-4: Expliziter Raumwechsel (BEWUSSTE ENTSCHEIDUNG) ────────
# 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(
r'(?:lass uns |gehen wir |wechsel(?:n)? )?(?:in |nach )?#?(\w[\w-]*)',
re.IGNORECASE,
@@ -1739,65 +1784,94 @@ class RocketChatAdapter(BasePlatformAdapter):
'lass uns in', 'gehen wir in', 'wechseln nach', 'wechsel 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)
# 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:
switch_match = _EXPLICIT_SWITCH_RE.search(text)
if switch_match:
switch_room_name = switch_match.group(1).lower()
# Raum aus room-map.json auflösen (name → room_id)
target_room_id = ""
target_room_display = ""
room_map = self.archivar._room_map
if room_map is not None:
for rid, entry in room_map.rooms.items():
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],
# V8.3.1 F3: #-Pflicht — der Match muss ein # vor dem Raum-Namen haben
match_pos = switch_match.start(1)
hash_present = '#' in text[max(0, match_pos - 3):match_pos + len(switch_match.group(1)) + 1]
if not hash_present:
logger.debug(
"[rocketchat] V8.3-4: Kein # im Match — kein expliziter Raumwechsel"
)
# a. _CURRENT_ORIGIN_ROOM auf Zielraum setzen
_CURRENT_ORIGIN_ROOM.set(target_room_id)
_THEMATIC_TARGET_ROOM.set(target_room_id)
# b. Sticky setzen: 30 Min, sticky_topic = 'explizit-wechsel'
self._session_room_preferences[room_id] = {
"target_room": target_room_id,
"target_name": target_room_display,
"sticky_topic": "explizit-wechsel",
"expires_at": time.time() + 1800, # 30 Min
}
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
is_explicit_switch = False
else:
# Raum aus room-map.json auflösen (name → room_id)
room_map = self.archivar._room_map
if room_map is not None:
for rid, entry in room_map.rooms.items():
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
# V8.3.1 F3: Nur auslösen wenn Raum in room-map.json existiert
if not target_room_id:
logger.debug(
"[rocketchat] V8.3-4: Raum '%s' nicht in room-map.json — "
"kein expliziter Raumwechsel",
switch_room_name,
)
is_explicit_switch = False
else:
is_explicit_switch = False
if is_explicit_switch and 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
_CURRENT_ORIGIN_ROOM.set(target_room_id)
_THEMATIC_TARGET_ROOM.set(target_room_id)
# b. Sticky setzen: 30 Min, sticky_topic = 'explizit-wechsel'
self._session_room_preferences[room_id] = {
"target_room": target_room_id,
"target_name": target_room_display,
"sticky_topic": "explizit-wechsel",
"expires_at": time.time() + 1800, # 30 Min
}
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) ──────────────────────────
# Klassifiziere die Nachricht und entscheide über Copy/Routing.
@@ -2028,14 +2102,9 @@ class RocketChatAdapter(BasePlatformAdapter):
target_room_id = decision.target_room
target_name = getattr(decision, 'move_request_target_name', 'Zielraum')
# ── V8.3-5: Topic für Sticky extrahieren ──────────────────
sticky_topic = ""
if _MULTIROOM() and self.archivar is not None:
matched_keywords = getattr(decision, 'matched_keywords', [])
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 F4: Vereinheitlicht auf room_name_to_topic(target_name)
# statt matched_keywords[0] — konsistent mit current_topic-Berechnung.
sticky_topic = room_name_to_topic(target_name) if target_name else ""
# ── V8.3-1: Ankündigung im Ursprungsraum VOR Zielraum-Post ──
# Andreas: 'Der Mensch wartet. Er schreibt nicht: Halt, wir bleiben hier.'
target_display = target_name.lstrip('#') if target_name else "Zielraum"
@@ -2073,7 +2142,7 @@ class RocketChatAdapter(BasePlatformAdapter):
)
# Kopiere Nachricht in den Zielraum
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
_CURRENT_ORIGIN_ROOM.set(target_room_id)
_THEMATIC_TARGET_ROOM.set(target_room_id)
@@ -2113,7 +2182,7 @@ class RocketChatAdapter(BasePlatformAdapter):
"topic": sticky_topic,
"timestamp": time.time(),
"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.
@@ -2330,7 +2399,7 @@ class RocketChatAdapter(BasePlatformAdapter):
"""Callback for Archivar forwarding — sends a message copy to a target room."""
if not self.rest.auth_token:
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:
"""Callback for Archivar — sends native Rocket.Chat Action-Buttons.
@@ -2361,7 +2430,7 @@ class RocketChatAdapter(BasePlatformAdapter):
actions = payload.get("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)
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)
if success:
if success is not None:
# Mark room so the response stays here (no Archivar routing)
self._rooms_with_pending_questions.add(room_id)
logger.info("[rocketchat] Sent Archivar %s with %d buttons to %s",