Files
Hermes_rocket.chat_Plugin/plugin/archivar/reply_quote_stripper.py
T
Bernd (Hermes) 1a4dab401d fix(P1): ISSUE 2 — Quote-Stripping erkennt Archivar-Output-Marker
- _ARCHIVAR_ARTIFACT_PHRASES: 5 Phrasen (Soll ich diese Nachricht nach, etc.)
- _strip_archivar_artifact(): Entfernt Phrase+Raumnamen aus routing_text
- Integration in strip_reply_quote() — läuft immer, nicht nur bei !stripped
- Verhindert Fehl-Routing durch Archivar-Output wie 'Soll ich nach #LAN-Doku kopieren?'
2026-07-25 11:17:10 +02:00

247 lines
8.7 KiB
Python

"""
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,
)
# ── FIX 5 (P1): ISSUE 2 — Archivar-Output-Marker ─────────────────────────
# Archivar-Phrasen, die auf eine Move-Request-Frage hindeuten.
# Bei Match wird die folgende Raumnamen-Erwähnung NICHT in routing_text
# aufgenommen, um Fehl-Routing durch Archivar-Output zu verhindern.
_ARCHIVAR_ARTIFACT_PHRASES = [
"Soll ich diese Nachricht nach",
"Soll ich den Auftrag dorthin",
"Möchtest du, dass ich",
"Soll ich das nach",
"Soll ich die Nachricht nach",
]
# Regex: erkennt Raumnamen nach Archivar-Phrasen
# Pattern: Phrase + optional whitespace + #?Raumname
_ARCHIVAR_ARTIFACT_RE = re.compile(
r'(?:' + '|'.join(re.escape(p) for p in _ARCHIVAR_ARTIFACT_PHRASES) + r')'
r'\s+#?[\w-]+',
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_archivar_artifact(text: str) -> Tuple[str, bool]:
"""FIX 5 (P1): Entferne Archivar-Output-Marker aus dem Text.
Erkennt Phrasen wie 'Soll ich diese Nachricht nach #LAN-Dokumentation
kopieren?' und entfernt den Raumnamen-Teil, damit der Router nicht
fälschlich auf den Raum-Namen matcht.
Returns:
Tuple aus (bereinigtem Text, ob ein Artifact erkannt wurde).
"""
if not text:
return text, False
match = _ARCHIVAR_ARTIFACT_RE.search(text)
if match:
# Entferne den gesamten Match (Phrase + Raumnamen)
result = text[:match.start()] + text[match.end():]
result = result.strip()
return result, True
return text, False
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
# ── FIX 5 (P1): Archivar-Output-Marker ──────────────────────────────
# Läuft immer (nicht nur wenn !stripped), weil Archivar-Output
# auch in Nachrichten ohne Quote vorkommen kann.
before_artifact = result
result, artifact_detected = _strip_archivar_artifact(result)
if artifact_detected:
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