fix: Reply-Quote-Stripping P0+P1 — verhindert Fehl-Routing bei zitierten Parent-Nachrichten

This commit is contained in:
Bernd (Hermes)
2026-07-23 06:34:46 +02:00
parent f9e4760f58
commit ce4789fe30
3 changed files with 629 additions and 17 deletions
+196
View File
@@ -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)