fix: Reply-Quote-Stripping P0+P1 — verhindert Fehl-Routing bei zitierten Parent-Nachrichten
This commit is contained in:
+47
-16
@@ -50,6 +50,9 @@ if _MULTIROOM():
|
||||
from archivar.routing_counter import routing_counter
|
||||
from archivar.routing_telemetry import routing_telemetry
|
||||
|
||||
# P0: Reply-Quote-Stripping — verhindert Fehl-Routing durch zitierte Parent-Nachrichten
|
||||
from archivar.reply_quote_stripper import strip_reply_quote_for_routing
|
||||
|
||||
# ── Access __init__ symbols (plugin loaded as flat module, no relative imports) ──
|
||||
import sys as _sys
|
||||
_init_module = _sys.modules.get('rocketchat')
|
||||
@@ -1588,6 +1591,27 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
text = file_info_text
|
||||
msg_obj["msg"] = text
|
||||
|
||||
# ── P0+P1: Reply-Quote-Stripping ──────────────────────────────────
|
||||
# Verhindert Fehl-Routing durch zitierte Parent-Nachrichten.
|
||||
# Zweistufig defensiv:
|
||||
# 1. Attachments-basiert (Rocket.Chat Reply-Attachments)
|
||||
# 2. Text-basiert (Markdown-Blockquotes, [quote]-Blöcke)
|
||||
# routing_text (ohne Quote) → Archivar/Keyword-Matcher/classify_and_route
|
||||
# display_text (mit Quote) → Agent-Dispatch + Conversation-History
|
||||
routing_text, display_text, quote_stripped = strip_reply_quote_for_routing(
|
||||
text, attachments
|
||||
)
|
||||
if quote_stripped:
|
||||
routing_counter.increment('reply_quote_stripped')
|
||||
logger.debug(
|
||||
"[rocketchat] P0: Reply-Quote gestrippt — "
|
||||
"routing_text=%s, display_text=%s",
|
||||
routing_text[:80], display_text[:80],
|
||||
)
|
||||
# text bleibt display_text für Agent/History;
|
||||
# routing_text wird für Archivar-Klassifikation verwendet.
|
||||
# ── Ende P0+P1 ────────────────────────────────────────────────────
|
||||
|
||||
# Skip own messages (case-insensitive comparison)
|
||||
filter_match = (username == (self.user or "").lower())
|
||||
logger.debug("Filter check: username=%s, self.user=%s, match=%s", username, self.user, filter_match)
|
||||
@@ -1627,7 +1651,7 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
# ── R5: Inline-Command-Erkennung (VOR Onboarding + Hermes-Dispatch) ──
|
||||
# ::-Befehle und natürliche Hilfeseiten-Anfragen müssen VOR dem
|
||||
# generischen Hermes-Agent-Onboarding erkannt werden.
|
||||
inline_handled = await self._handle_inline_command(text, room_id, room_name, username)
|
||||
inline_handled = await self._handle_inline_command(routing_text, room_id, room_name, username)
|
||||
if inline_handled:
|
||||
logger.debug("[rocketchat] R5: Inline-Command verarbeitet — skipping agent dispatch")
|
||||
routing_counter.increment('inline_command_handled')
|
||||
@@ -1636,13 +1660,15 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
# ── Ende R5 Inline-Command-Erkennung ────────────────────────────────
|
||||
|
||||
# ── B5v6.5: Conversation History — User-Nachricht aufzeichnen ──
|
||||
# P1: display_text (mit Quote) für Agent/History, damit kein Kontext verloren geht
|
||||
if _MULTIROOM() and self._conversation_history is not None:
|
||||
await self._conversation_history.add(room_id, "user", text)
|
||||
await self._conversation_history.add(room_id, "user", display_text)
|
||||
|
||||
# V8.1 P4: MultiRoomContext-Ring — Thema aus Nachricht extrahieren
|
||||
if _MULTIROOM() and self._multiroom_context is not None:
|
||||
# Extrahiere ein kurzes Topic aus der Nachricht (erste 80 Zeichen)
|
||||
topic = text[:80].replace("\n", " ").strip()
|
||||
# P1: routing_text für Topic-Extraktion (ohne Quote)
|
||||
topic = routing_text[:80].replace("\n", " ").strip()
|
||||
if topic:
|
||||
await self._multiroom_context.add(room_id, room_name, topic)
|
||||
|
||||
@@ -2131,7 +2157,7 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
del self._recent_auto_routes[room_id]
|
||||
# Dispatch im Ursprungsraum
|
||||
await self._dispatch_agent(
|
||||
text=text,
|
||||
text=display_text,
|
||||
room_id=room_id,
|
||||
room_name=room_name,
|
||||
room_type=room_type,
|
||||
@@ -2231,7 +2257,7 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
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,
|
||||
text=display_text,
|
||||
room_id=target_room_id,
|
||||
room_name=target_room_name_disp,
|
||||
room_type=target_room_type,
|
||||
@@ -2249,7 +2275,7 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
# Nur die Nachricht selbst wird — nach User-Entscheidung — kopiert.
|
||||
category = ""
|
||||
decision = None
|
||||
is_auftrag = _is_auftrag(text)
|
||||
is_auftrag = _is_auftrag(routing_text)
|
||||
|
||||
logger.debug("[rocketchat] ARCHIVAR-DEBUG: Entering Archivar block — room_type=%s, is_auftrag=%s, _MULTIROOM=%s, archivar=%s", room_type, is_auftrag, _MULTIROOM(), self.archivar is not None)
|
||||
|
||||
@@ -2363,7 +2389,8 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
)
|
||||
routing_telemetry.flush()
|
||||
# Kopiere Nachricht in den Zielraum
|
||||
target_txt = f"*(Auftrag von @{username}, Topic-Sticky)*\n{text}"
|
||||
# P1: display_text (mit Quote) für Zielraum-Kopie
|
||||
target_txt = f"*(Auftrag von @{username}, Topic-Sticky)*\n{display_text}"
|
||||
await self._post_message_with_retry(target_room_id, target_txt)
|
||||
_CURRENT_ORIGIN_ROOM.set(target_room_id)
|
||||
_THEMATIC_TARGET_ROOM.set(target_room_id)
|
||||
@@ -2371,7 +2398,7 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
logger.info(
|
||||
"[rocketchat] V8.3-5: Topic-Scoped Sticky active — "
|
||||
"auto-routing '%s' → %s, topic='%s' (%.0fs remaining)",
|
||||
text[:80], target_name, sticky_topic,
|
||||
display_text[:80], target_name, sticky_topic,
|
||||
pref["expires_at"] - time.time(),
|
||||
)
|
||||
# Dispatch direkt — kein Archivar
|
||||
@@ -2379,7 +2406,7 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
target_room_name = target_room_info.get("name", target_name)
|
||||
target_room_type = target_room_info.get("type", "c")
|
||||
await self._dispatch_agent(
|
||||
text=text,
|
||||
text=display_text,
|
||||
room_id=target_room_id,
|
||||
room_name=target_room_name,
|
||||
room_type=target_room_type,
|
||||
@@ -2407,7 +2434,8 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
duration_ms=0.0,
|
||||
)
|
||||
routing_telemetry.flush()
|
||||
target_txt = f"*(Auftrag von @{username}, Topic-Sticky)*\n{text}"
|
||||
# P1: display_text (mit Quote) für Zielraum-Kopie
|
||||
target_txt = f"*(Auftrag von @{username}, Topic-Sticky)*\n{display_text}"
|
||||
await self._post_message_with_retry(target_room_id, target_txt)
|
||||
_CURRENT_ORIGIN_ROOM.set(target_room_id)
|
||||
_THEMATIC_TARGET_ROOM.set(target_room_id)
|
||||
@@ -2415,7 +2443,7 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
logger.info(
|
||||
"[rocketchat] V8.3-5: Topic-Scoped Sticky active — "
|
||||
"auto-routing '%s' → %s, topic='%s' (%.0fs remaining)",
|
||||
text[:80], target_name, sticky_topic,
|
||||
display_text[:80], target_name, sticky_topic,
|
||||
pref["expires_at"] - time.time(),
|
||||
)
|
||||
# Dispatch direkt — kein Archivar
|
||||
@@ -2423,7 +2451,7 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
target_room_name = target_room_info.get("name", target_name)
|
||||
target_room_type = target_room_info.get("type", "c")
|
||||
await self._dispatch_agent(
|
||||
text=text,
|
||||
text=display_text,
|
||||
room_id=target_room_id,
|
||||
room_name=target_room_name,
|
||||
room_type=target_room_type,
|
||||
@@ -2453,7 +2481,8 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
# P0-FIX: is_dm=True bei DMs — der Router braucht das für den DM-Guard.
|
||||
# room_type wird in L1579 aus self._room_info gelesen.
|
||||
_is_dm = (room_type == "d")
|
||||
decision = await self.archivar.classify_and_route(text, origin_room_id=room_id, is_dm=_is_dm)
|
||||
# P0: routing_text (ohne Quote) für Klassifikation verwenden
|
||||
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()
|
||||
if decision and decision.category:
|
||||
@@ -2483,7 +2512,8 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
and hasattr(decision, 'target_room')
|
||||
and decision.target_room):
|
||||
self._pending_move_requests[room_id] = {
|
||||
'text': text,
|
||||
# P1: display_text (mit Quote) für Move-Request speichern
|
||||
'text': display_text,
|
||||
'origin_room': room_id,
|
||||
'target_room': decision.target_room,
|
||||
'target_name': getattr(
|
||||
@@ -2575,7 +2605,8 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
room_id[:8],
|
||||
)
|
||||
# Kopiere Nachricht in den Zielraum
|
||||
target_txt = f"*(Auftrag von @{username}, automatisch geroutet)*\n{text}"
|
||||
# P1: display_text (mit Quote) für Zielraum-Kopie
|
||||
target_txt = f"*(Auftrag von @{username}, automatisch geroutet)*\n{display_text}"
|
||||
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)
|
||||
@@ -2585,7 +2616,7 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
logger.info(
|
||||
"[rocketchat] V8.1 P1: Auto-Route '%s' → %s — "
|
||||
"Agent dispatched in target room",
|
||||
text[:80], target_name,
|
||||
display_text[:80], target_name,
|
||||
)
|
||||
# V8.1.1 R2: Ring-GC bei Auto-Route — stale Topics aus Ursprungsraum entfernen
|
||||
if _MULTIROOM() and self._multiroom_context is not None:
|
||||
|
||||
@@ -0,0 +1,196 @@
|
||||
"""
|
||||
Reply-Quote-Stripper: Entfernt zitierte Parent-Nachrichten aus Reply-Texten.
|
||||
|
||||
P0: Verhindert Fehl-Routing durch Keyword-Matches in zitierten Texten.
|
||||
Zweistufig defensiv:
|
||||
1. Attachments-basiert: Rocket.Chat sendet bei Replies die Parent-Nachricht
|
||||
als attachment mit. Entferne den zitierten Text aus dem Nachrichtentext.
|
||||
2. Text-basiert (Fallback): Regex-Heuristik für Markdown-Blockquotes (> quote)
|
||||
und [quote]-Blöcke.
|
||||
|
||||
Konfliktfrei mit Butler-Prinzip — der Strip verschärft die 100%-Heuristik,
|
||||
ohne sie zu unterlaufen.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from typing import List, Optional, Tuple
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Rocket.Chat Reply-Quote Patterns
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
# Rocket.Chat reply link pattern: [ ](https://...?msg=MSGID)
|
||||
# This is the inline reply marker that Rocket.Chat inserts when replying.
|
||||
_RC_REPLY_LINK_RE = re.compile(
|
||||
r'\[\s*\]\s*\(\s*https?://[^)]*\?msg=[^)]+\)\s*',
|
||||
re.IGNORECASE,
|
||||
)
|
||||
|
||||
# Markdown blockquote: lines starting with >
|
||||
# Matches one or more consecutive lines starting with '> '
|
||||
_BLOCKQUOTE_RE = re.compile(
|
||||
r'(?:^|\n)(?:> .*(?:\n|$))+',
|
||||
re.MULTILINE,
|
||||
)
|
||||
|
||||
# [quote]...[/quote] blocks (BBCode-style, used by some RC clients)
|
||||
_QUOTE_BLOCK_RE = re.compile(
|
||||
r'\[quote[^\]]*\].*?\[/quote\]',
|
||||
re.DOTALL | re.IGNORECASE,
|
||||
)
|
||||
|
||||
# [quote="author"]...[/quote] blocks
|
||||
_QUOTE_AUTHOR_BLOCK_RE = re.compile(
|
||||
r'\[quote=["\']?[^\]"\']*["\']?\].*?\[/quote\]',
|
||||
re.DOTALL | re.IGNORECASE,
|
||||
)
|
||||
|
||||
# Rocket.Chat attachment types that indicate a reply quote
|
||||
_REPLY_ATTACHMENT_TYPES = frozenset({
|
||||
'reply',
|
||||
'quote',
|
||||
'message',
|
||||
})
|
||||
|
||||
|
||||
def _extract_quoted_text_from_attachments(attachments: list) -> Optional[str]:
|
||||
"""Extrahiere den zitierten Text aus Reply-Attachments.
|
||||
|
||||
Rocket.Chat sendet bei Replies die Parent-Nachricht als attachment mit.
|
||||
Typische Felder:
|
||||
- attachment_type: 'reply' oder 'quote'
|
||||
- text: der zitierte Nachrichtentext
|
||||
- description: Beschreibung (z.B. Autor der Parent-Nachricht)
|
||||
- author_name: Name des Autors der Parent-Nachricht
|
||||
- message_link: Link zur Parent-Nachricht
|
||||
|
||||
Returns:
|
||||
Der zitierte Text wenn gefunden, sonst None.
|
||||
"""
|
||||
if not attachments or not isinstance(attachments, list):
|
||||
return None
|
||||
|
||||
for attachment in attachments:
|
||||
if not isinstance(attachment, dict):
|
||||
continue
|
||||
|
||||
# Check for reply/quote attachment types
|
||||
att_type = attachment.get('type', '')
|
||||
att_attachment_type = attachment.get('attachment_type', '')
|
||||
|
||||
if att_type in _REPLY_ATTACHMENT_TYPES or att_attachment_type in _REPLY_ATTACHMENT_TYPES:
|
||||
# Try to get the quoted text
|
||||
quoted = attachment.get('text', '') or attachment.get('description', '')
|
||||
if quoted:
|
||||
return quoted.strip()
|
||||
|
||||
# Also check for message_link (Rocket.Chat reply indicator)
|
||||
if attachment.get('message_link'):
|
||||
quoted = attachment.get('text', '') or attachment.get('description', '')
|
||||
if quoted:
|
||||
return quoted.strip()
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def _strip_rc_reply_link(text: str) -> str:
|
||||
"""Entferne den Rocket.Chat Reply-Link [ ](url?msg=ID) aus dem Text."""
|
||||
return _RC_REPLY_LINK_RE.sub('', text).strip()
|
||||
|
||||
|
||||
def _strip_blockquotes(text: str) -> str:
|
||||
"""Entferne Markdown-Blockquotes (> quote) aus dem Text."""
|
||||
return _BLOCKQUOTE_RE.sub('', text).strip()
|
||||
|
||||
|
||||
def _strip_quote_blocks(text: str) -> str:
|
||||
"""Entferne [quote]...[/quote] Blöcke aus dem Text."""
|
||||
text = _QUOTE_AUTHOR_BLOCK_RE.sub('', text)
|
||||
text = _QUOTE_BLOCK_RE.sub('', text)
|
||||
return text.strip()
|
||||
|
||||
|
||||
def strip_reply_quote(
|
||||
text: str,
|
||||
attachments: Optional[list] = None,
|
||||
) -> Tuple[str, bool]:
|
||||
"""Entferne Reply-Quote aus einer Nachricht (P0).
|
||||
|
||||
Zweistufig defensiv:
|
||||
1. Attachments-basiert: Wenn die Nachricht Reply-Attachments enthält,
|
||||
wird der zitierte Text aus dem Nachrichtentext entfernt.
|
||||
2. Text-basiert (Fallback): Regex-Heuristik für Blockquote-Pattern.
|
||||
|
||||
Args:
|
||||
text: Der Nachrichtentext.
|
||||
attachments: Optionale Liste von Attachments aus dem msg_obj.
|
||||
|
||||
Returns:
|
||||
Tuple aus (bereinigtem Text, ob ein Quote gestrippt wurde).
|
||||
"""
|
||||
if not text:
|
||||
return text, False
|
||||
|
||||
stripped = False
|
||||
result = text
|
||||
|
||||
# ── Stufe 1: Attachments-basiert ──────────────────────────────────
|
||||
if attachments:
|
||||
quoted_text = _extract_quoted_text_from_attachments(attachments)
|
||||
if quoted_text and quoted_text in result:
|
||||
result = result.replace(quoted_text, '', 1).strip()
|
||||
stripped = True
|
||||
|
||||
# ── Stufe 1b: RC Reply-Link entfernen ──────────────────────────────
|
||||
# [ ](https://chat.example.com/group/room?msg=MSGID)
|
||||
before_link = result
|
||||
result = _strip_rc_reply_link(result)
|
||||
if result != before_link:
|
||||
stripped = True
|
||||
|
||||
# ── Stufe 2: Text-basiert (Fallback) ───────────────────────────────
|
||||
# Nur wenn Stufe 1 nichts gefunden hat
|
||||
if not stripped:
|
||||
# [quote]...[/quote] Blöcke
|
||||
before_quote = result
|
||||
result = _strip_quote_blocks(result)
|
||||
if result != before_quote:
|
||||
stripped = True
|
||||
|
||||
if not stripped:
|
||||
# Markdown-Blockquotes (> quote)
|
||||
before_bq = result
|
||||
result = _strip_blockquotes(before_bq)
|
||||
if result != before_bq:
|
||||
stripped = True
|
||||
|
||||
# Clean up: collapse multiple blank lines, strip
|
||||
result = re.sub(r'\n{3,}', '\n\n', result)
|
||||
result = result.strip()
|
||||
|
||||
return result, stripped
|
||||
|
||||
|
||||
def strip_reply_quote_for_routing(
|
||||
text: str,
|
||||
attachments: Optional[list] = None,
|
||||
) -> Tuple[str, str, bool]:
|
||||
"""P1: Trenne routing_text und display_text.
|
||||
|
||||
- routing_text: Ohne Quote — für Archivar/Keyword-Matcher/classify_and_route
|
||||
- display_text: Mit Quote — für Agent und Conversation-History
|
||||
|
||||
Args:
|
||||
text: Der originale Nachrichtentext.
|
||||
attachments: Optionale Attachments aus dem msg_obj.
|
||||
|
||||
Returns:
|
||||
Tuple aus (routing_text, display_text, was_stripped).
|
||||
Wenn kein Quote gefunden: routing_text == display_text == text.
|
||||
"""
|
||||
routing_text, was_stripped = strip_reply_quote(text, attachments)
|
||||
display_text = text # Originaltext mit Quote für Agent/History
|
||||
return routing_text, display_text, was_stripped
|
||||
@@ -0,0 +1,385 @@
|
||||
"""
|
||||
Tests für Reply-Quote-Stripping (P0 + P1).
|
||||
|
||||
Testet:
|
||||
- Attachments-basiertes Stripping (Stufe 1)
|
||||
- Text-basiertes Stripping (Stufe 2): [quote]-Blöcke, Markdown-Blockquotes
|
||||
- RC Reply-Link-Entfernung
|
||||
- Edge Cases: Nachrichten ohne Quote, verschachtelte Quotes, Edits
|
||||
- P1: routing_text vs display_text Trennung
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
|
||||
|
||||
from plugin.archivar.reply_quote_stripper import (
|
||||
strip_reply_quote,
|
||||
strip_reply_quote_for_routing,
|
||||
_extract_quoted_text_from_attachments,
|
||||
_strip_rc_reply_link,
|
||||
_strip_blockquotes,
|
||||
_strip_quote_blocks,
|
||||
)
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Stufe 1: Attachments-basiertes Stripping
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
|
||||
class TestAttachmentBasedStripping:
|
||||
"""Tests für attachments-basiertes Quote-Stripping (Stufe 1)."""
|
||||
|
||||
def test_reply_attachment_type_reply(self):
|
||||
"""Attachment mit type='reply' wird erkannt und gestrippt."""
|
||||
text = "Meine Antwort auf deine Frage\n\nDas ist der zitierte Text von der Parent-Nachricht"
|
||||
attachments = [
|
||||
{
|
||||
"type": "reply",
|
||||
"text": "Das ist der zitierte Text von der Parent-Nachricht",
|
||||
"author_name": "bernd",
|
||||
}
|
||||
]
|
||||
result, stripped = strip_reply_quote(text, attachments)
|
||||
assert stripped is True
|
||||
assert "zitierte Text" not in result
|
||||
assert "Meine Antwort" in result
|
||||
|
||||
def test_reply_attachment_type_quote(self):
|
||||
"""Attachment mit type='quote' wird erkannt."""
|
||||
text = "Ja, genau!\n\nUrsprüngliche Frage: Wie funktioniert der Archivar?"
|
||||
attachments = [
|
||||
{
|
||||
"type": "quote",
|
||||
"text": "Ursprüngliche Frage: Wie funktioniert der Archivar?",
|
||||
}
|
||||
]
|
||||
result, stripped = strip_reply_quote(text, attachments)
|
||||
assert stripped is True
|
||||
assert "Ursprüngliche Frage" not in result
|
||||
assert "Ja, genau!" in result
|
||||
|
||||
def test_reply_attachment_with_attachment_type_field(self):
|
||||
"""Attachment mit attachment_type='reply' wird erkannt."""
|
||||
text = "Gute Idee!\n\nWir sollten den Archivar erweitern um Multi-Room-Support"
|
||||
attachments = [
|
||||
{
|
||||
"attachment_type": "reply",
|
||||
"description": "Wir sollten den Archivar erweitern um Multi-Room-Support",
|
||||
}
|
||||
]
|
||||
result, stripped = strip_reply_quote(text, attachments)
|
||||
assert stripped is True
|
||||
assert "Multi-Room-Support" not in result
|
||||
assert "Gute Idee!" in result
|
||||
|
||||
def test_reply_attachment_with_message_link(self):
|
||||
"""Attachment mit message_link wird als Reply-Indikator erkannt."""
|
||||
text = "Antwort\n\nOriginal: Bitte dokumentiere das neue Feature"
|
||||
attachments = [
|
||||
{
|
||||
"message_link": "https://chat.example.com/group/room?msg=abc123",
|
||||
"text": "Original: Bitte dokumentiere das neue Feature",
|
||||
}
|
||||
]
|
||||
result, stripped = strip_reply_quote(text, attachments)
|
||||
assert stripped is True
|
||||
assert "dokumentiere" not in result
|
||||
assert "Antwort" in result
|
||||
|
||||
def test_no_reply_attachment_no_strip(self):
|
||||
"""Normales File-Attachment löst KEIN Stripping aus."""
|
||||
text = "Schau dir mal diese Datei an"
|
||||
attachments = [
|
||||
{
|
||||
"type": "file",
|
||||
"title": "dokumentation.pdf",
|
||||
"title_link": "/file-upload/abc123/dokumentation.pdf",
|
||||
}
|
||||
]
|
||||
result, stripped = strip_reply_quote(text, attachments)
|
||||
assert stripped is False
|
||||
assert result == text
|
||||
|
||||
def test_empty_attachments_no_strip(self):
|
||||
"""Leere Attachment-Liste → kein Strip."""
|
||||
text = "Normaler Text ohne Quote"
|
||||
result, stripped = strip_reply_quote(text, [])
|
||||
assert stripped is False
|
||||
assert result == text
|
||||
|
||||
def test_none_attachments_no_strip(self):
|
||||
"""None attachments → kein Strip."""
|
||||
text = "Normaler Text ohne Quote"
|
||||
result, stripped = strip_reply_quote(text, None)
|
||||
assert stripped is False
|
||||
assert result == text
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Stufe 1b: RC Reply-Link-Entfernung
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
|
||||
class TestRCReplyLinkStripping:
|
||||
"""Tests für Rocket.Chat Reply-Link-Entfernung."""
|
||||
|
||||
def test_strip_rc_reply_link(self):
|
||||
"""[ ](url?msg=ID) wird entfernt."""
|
||||
text = "[ ](https://chat.example.com/group/room?msg=abc123) Meine Antwort"
|
||||
result = _strip_rc_reply_link(text)
|
||||
assert "[ ](https://chat.example.com" not in result
|
||||
assert "Meine Antwort" in result
|
||||
|
||||
def test_strip_rc_reply_link_with_text_after(self):
|
||||
"""Reply-Link am Anfang, Text danach."""
|
||||
text = "[ ](https://chat.example.com/group/room?msg=abc123) Was meinst du zum Archivar?"
|
||||
result, stripped = strip_reply_quote(text)
|
||||
assert stripped is True
|
||||
assert "Archivar" in result
|
||||
assert "msg=abc123" not in result
|
||||
|
||||
def test_no_reply_link_no_strip(self):
|
||||
"""Text ohne Reply-Link bleibt unverändert."""
|
||||
text = "Was meinst du zum Archivar?"
|
||||
result = _strip_rc_reply_link(text)
|
||||
assert result == text
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Stufe 2: Text-basiertes Stripping
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
|
||||
class TestTextBasedStripping:
|
||||
"""Tests für text-basiertes Quote-Stripping (Stufe 2)."""
|
||||
|
||||
def test_strip_quote_block(self):
|
||||
"""[quote]...[/quote] Block wird entfernt."""
|
||||
text = "Meine Antwort\n\n[quote]Das ist ein zitierter Text[/quote]"
|
||||
result, stripped = strip_reply_quote(text)
|
||||
assert stripped is True
|
||||
assert "[quote]" not in result
|
||||
assert "zitierter Text" not in result
|
||||
assert "Meine Antwort" in result
|
||||
|
||||
def test_strip_quote_author_block(self):
|
||||
"""[quote="author"]...[/quote] Block wird entfernt."""
|
||||
text = 'Antwort\n\n[quote="bernd"]Original: Bitte dokumentiere das[/quote]'
|
||||
result, stripped = strip_reply_quote(text)
|
||||
assert stripped is True
|
||||
assert "dokumentiere" not in result
|
||||
assert "Antwort" in result
|
||||
|
||||
def test_strip_markdown_blockquote(self):
|
||||
"""> Markdown-Blockquote wird entfernt."""
|
||||
text = "Meine Antwort\n\n> Das ist ein zitierter Text\n> mit mehreren Zeilen"
|
||||
result, stripped = strip_reply_quote(text)
|
||||
assert stripped is True
|
||||
assert "zitierter Text" not in result
|
||||
assert "Meine Antwort" in result
|
||||
|
||||
def test_strip_multiline_blockquote(self):
|
||||
"""Mehrzeilige > Blockquote wird komplett entfernt."""
|
||||
text = "Antwort:\n\n> Zeile 1 des Zitats\n> Zeile 2 des Zitats\n> Zeile 3 des Zitats\n\nEigener Text"
|
||||
result, stripped = strip_reply_quote(text)
|
||||
assert stripped is True
|
||||
assert "Zeile 1" not in result
|
||||
assert "Zeile 2" not in result
|
||||
assert "Zeile 3" not in result
|
||||
assert "Antwort:" in result
|
||||
assert "Eigener Text" in result
|
||||
|
||||
def test_quote_block_with_keyword_inside(self):
|
||||
"""Quote-Block mit Keyword 'archivar' wird entfernt — verhindert Fehl-Routing."""
|
||||
text = "Frage zum Plugin\n\n[quote]Der Archivar routet Nachrichten automatisch[/quote]"
|
||||
result, stripped = strip_reply_quote(text)
|
||||
assert stripped is True
|
||||
assert "Archivar" not in result
|
||||
assert "Frage zum Plugin" in result
|
||||
|
||||
def test_blockquote_with_keyword_inside(self):
|
||||
"""Markdown-Blockquote mit Keyword wird entfernt."""
|
||||
text = "Neue Frage\n\n> Bitte dokumentiere das Multi-Room-Feature im Archivar"
|
||||
result, stripped = strip_reply_quote(text)
|
||||
assert stripped is True
|
||||
assert "dokumentiere" not in result
|
||||
assert "Multi-Room" not in result
|
||||
assert "Neue Frage" in result
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Edge Cases
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
|
||||
class TestEdgeCases:
|
||||
"""Edge-Case-Tests für Reply-Quote-Stripping."""
|
||||
|
||||
def test_no_quote_no_change(self):
|
||||
"""Nachricht ohne Quote bleibt unverändert."""
|
||||
text = "Kannst du mir den Archivar erklären?"
|
||||
result, stripped = strip_reply_quote(text)
|
||||
assert stripped is False
|
||||
assert result == text
|
||||
|
||||
def test_empty_text(self):
|
||||
"""Leerer Text bleibt leer."""
|
||||
result, stripped = strip_reply_quote("")
|
||||
assert stripped is False
|
||||
assert result == ""
|
||||
|
||||
def test_text_with_gt_symbol_not_blockquote(self):
|
||||
"""> mitten im Text (kein Zeilenanfang) ist kein Blockquote."""
|
||||
text = "Die Bedingung ist x > 5 und y < 10"
|
||||
result, stripped = strip_reply_quote(text)
|
||||
assert stripped is False
|
||||
assert "x > 5" in result
|
||||
|
||||
def test_nested_quotes_outermost_only(self):
|
||||
"""Verschachtelte Quotes: nur die äußerste wird entfernt (defensiv)."""
|
||||
text = "Antwort\n\n> Äußeres Zitat\n> > Inneres Zitat\n> Noch äußeres"
|
||||
result, stripped = strip_reply_quote(text)
|
||||
assert stripped is True
|
||||
# Der gesamte > Block wird entfernt
|
||||
assert "Äußeres Zitat" not in result
|
||||
assert "Inneres Zitat" not in result
|
||||
assert "Antwort" in result
|
||||
|
||||
def test_edit_message_no_quote(self):
|
||||
"""Edit-Nachrichten ohne Quote werden nicht verändert."""
|
||||
text = "EDIT: Korrigierte Version des Archivar-Dokuments"
|
||||
result, stripped = strip_reply_quote(text)
|
||||
assert stripped is False
|
||||
assert "Archivar" in result # Keyword bleibt erhalten
|
||||
|
||||
def test_quote_block_with_attachment_priority(self):
|
||||
"""Attachments-basiertes Stripping hat Priorität vor Text-basiertem."""
|
||||
text = "Antwort\n\n> Das ist ein Blockquote\n\nZitierter Attachment-Text"
|
||||
attachments = [
|
||||
{
|
||||
"type": "reply",
|
||||
"text": "Zitierter Attachment-Text",
|
||||
}
|
||||
]
|
||||
result, stripped = strip_reply_quote(text, attachments)
|
||||
assert stripped is True
|
||||
# Attachment-Text wurde entfernt
|
||||
assert "Zitierter Attachment-Text" not in result
|
||||
# Blockquote wurde NICHT entfernt (weil Stufe 1 schon gestrippt hat)
|
||||
# Das ist okay — wir strippen nur einmal
|
||||
|
||||
def test_whitespace_only_after_strip(self):
|
||||
"""Nach Strip nur noch Whitespace → leerer String."""
|
||||
text = "[ ](https://chat.example.com/group/room?msg=abc123)"
|
||||
result, stripped = strip_reply_quote(text)
|
||||
assert stripped is True
|
||||
assert result == ""
|
||||
|
||||
def test_multiple_blank_lines_collapsed(self):
|
||||
"""Mehrfache Leerzeilen nach Strip werden kollabiert."""
|
||||
text = "Antwort\n\n\n\n> Zitat\n\n\n\nEigener Text"
|
||||
result, stripped = strip_reply_quote(text)
|
||||
assert stripped is True
|
||||
assert "\n\n\n\n" not in result
|
||||
assert "Antwort" in result
|
||||
assert "Eigener Text" in result
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# P1: routing_text vs display_text
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
|
||||
class TestRoutingVsDisplayText:
|
||||
"""Tests für P1: Trennung von routing_text und display_text."""
|
||||
|
||||
def test_routing_text_stripped_display_text_preserved(self):
|
||||
"""routing_text ohne Quote, display_text mit Quote."""
|
||||
text = "Meine Frage\n\n[quote]Der Archivar ist ein Routing-System[/quote]"
|
||||
routing_text, display_text, was_stripped = strip_reply_quote_for_routing(text)
|
||||
|
||||
assert was_stripped is True
|
||||
assert "Archivar" not in routing_text # Quote gestrippt
|
||||
assert "Meine Frage" in routing_text
|
||||
assert display_text == text # Original erhalten
|
||||
assert "Archivar" in display_text # Quote im display_text
|
||||
|
||||
def test_no_quote_both_same(self):
|
||||
"""Ohne Quote sind routing_text und display_text identisch."""
|
||||
text = "Kannst du den Archivar erklären?"
|
||||
routing_text, display_text, was_stripped = strip_reply_quote_for_routing(text)
|
||||
|
||||
assert was_stripped is False
|
||||
assert routing_text == text
|
||||
assert display_text == text
|
||||
|
||||
def test_attachment_quote_routing_stripped(self):
|
||||
"""Attachment-Quote: routing_text gestrippt, display_text erhalten."""
|
||||
text = "Ja, gute Frage!\n\nBitte dokumentiere das Multi-Room-Feature"
|
||||
attachments = [
|
||||
{
|
||||
"type": "reply",
|
||||
"text": "Bitte dokumentiere das Multi-Room-Feature",
|
||||
}
|
||||
]
|
||||
routing_text, display_text, was_stripped = strip_reply_quote_for_routing(
|
||||
text, attachments
|
||||
)
|
||||
|
||||
assert was_stripped is True
|
||||
assert "dokumentiere" not in routing_text
|
||||
assert "Ja, gute Frage!" in routing_text
|
||||
assert display_text == text
|
||||
assert "dokumentiere" in display_text
|
||||
|
||||
def test_rc_reply_link_routing_stripped(self):
|
||||
"""RC Reply-Link: routing_text ohne Link, display_text mit Link."""
|
||||
text = "[ ](https://chat.example.com/group/room?msg=abc123) Frage zum Archivar"
|
||||
routing_text, display_text, was_stripped = strip_reply_quote_for_routing(text)
|
||||
|
||||
assert was_stripped is True
|
||||
assert "msg=abc123" not in routing_text
|
||||
assert "Frage zum Archivar" in routing_text
|
||||
assert display_text == text
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Integration: Keyword-Matcher mit gestripptem Text
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
|
||||
class TestKeywordMatcherIntegration:
|
||||
"""Integrationstest: Keyword-Matcher sieht gestrippten Text nicht."""
|
||||
|
||||
def test_keyword_in_quote_not_matched(self):
|
||||
"""Keyword NUR im Quote → kein Match nach Strip."""
|
||||
from plugin.archivar.keyword_matcher import match_keyword
|
||||
|
||||
text = "Frage zum Plugin\n\n[quote]Bitte dokumentiere das Archivar-Feature[/quote]"
|
||||
routing_text, _, was_stripped = strip_reply_quote_for_routing(text)
|
||||
|
||||
assert was_stripped is True
|
||||
# 'dokumentiere' war nur im Quote → nach Strip kein Match
|
||||
assert not match_keyword("dokumentiere", routing_text)
|
||||
# 'archivar' war nur im Quote → nach Strip kein Match
|
||||
assert not match_keyword("archivar", routing_text)
|
||||
|
||||
def test_keyword_in_body_still_matched(self):
|
||||
"""Keyword im Body (nicht im Quote) → Match nach Strip."""
|
||||
from plugin.archivar.keyword_matcher import match_keyword
|
||||
|
||||
text = "Bitte dokumentiere das Plugin\n\n[quote]Alte Frage zum Archivar[/quote]"
|
||||
routing_text, _, was_stripped = strip_reply_quote_for_routing(text)
|
||||
|
||||
assert was_stripped is True
|
||||
# 'dokumentiere' ist im Body → Match
|
||||
assert match_keyword("dokumentiere", routing_text)
|
||||
# 'archivar' war im Quote → kein Match
|
||||
assert not match_keyword("archivar", routing_text)
|
||||
Reference in New Issue
Block a user