diff --git a/tests/live_rc/test_09_widerspruch.py b/tests/live_rc/test_09_widerspruch.py new file mode 100644 index 0000000..aeb567e --- /dev/null +++ b/tests/live_rc/test_09_widerspruch.py @@ -0,0 +1,594 @@ +""" +Test 09 — Auto-Route-Widerspruch-Flow (V8.5). + +Verifiziert den vollständigen Widerspruch-Flow des Rocket.Chat-Plugins: +1. Auto-Route (100%-Keyword) → Widerspruch → Clarify mit 2 Buttons +2. Button 1 ('generell hier her') → set_never_route → kein Auto-Route mehr +3. Button 2 ('nur jetzt hier her') → stay_once → Auto-Route feuert wieder +4. Kein Widerspruch-Clarify ohne vorherige Auto-Route + +TECHNISCHE DETAILS: +- WIDERSPRUCH-Payload-Format: WIDERSPRUCH:: (1-basiert) + (EINFACHER Doppelpunkt — der Handler parst text.split(":", 2).) +- Button-Labels: 1️⃣ generell hier her / 2️⃣ nur jetzt hier her +- action_id: SHA1-Hex (P-051) — NICHT 'clarify_'-präfixiert (das ist der + CLARIFY-Flow, nicht der WIDERSPRUCH-Flow). +- Auto-Route-Announcement: _ANNOUNCEMENT_VARIANTS (enthält 'thema'/'wechseln'/'rüber') +- Widerspruch-Clarify-Text: '❓ Widerspruch erkannt ...' +- P6: keywords_100 Wörter triggern Auto-Route (bat-team/trading/krypto etc.) +- Reset: ::reset (NICHT /reset — parse_inline_command erkennt nur ::) +- Polling: initial_interval=3.0 → [3, 8, 12, 20]s, Timeout 180s (27B-Modell langsam) +- 429: RateLimitSkip → pytest.skip + +WICHTIG — Keyword-Wahl pro Test: +Jeder Test nutzt ein ANDERES keywords_100-Wort (anderer Zielraum), weil +::reset zwar _recent_auto_routes + _session_room_preferences leert, aber +NICHT _never_route (thematisch, 24h TTL). Test 1 setzt never_route('bat-team') +dauerhaft — würde Test 2/3 mit demselben Keyword kontaminieren. +""" + +from __future__ import annotations + +import logging +import time +from typing import Optional + +import pytest + +from tests.live_rc.conftest import ( + assert_bot_message, + post_test_message, +) +from tests.live_rc.helpers.polling import ( + wait_for_bot_message, + PollTimeout, + RateLimitSkip, +) + +logger = logging.getLogger(__name__) + +# ═══════════════════════════════════════════════════════════════════════════ +# Konstanten +# ═══════════════════════════════════════════════════════════════════════════ + +# Auto-Route-Announcement-Indikatoren (aus _ANNOUNCEMENT_VARIANTS, adapter.py:1101). +# 'thema' kommt in ALLEN 5 Varianten vor — zuverlässigster Indikator. +_AUTO_ROUTE_INDICATORS = ["thema", "wechseln", "rüber", "aufgreifen", "passt besser"] + +# Widerspruch-Clarify-Text-Marker (adapter.py:7867). +_WIDERSPRUCH_TEXT_MARKER = "widerspruch erkannt" + +# Widerspruch-Text, der den HIER_HER-Pattern matcht (feedback_detector.py:141). +_WIDERSPRUCH_TEXT = "Nein, das passt hier her" + +# Timeout für jeden Test (27B-Modell ist langsam). +_TIMEOUT = 180.0 + +# keywords_100 pro Test (unterschiedliche Zielräume → keine never_route-Kontamination). +_KEYWORD_TEST_1 = "bat-team trading krypto" # → #BAT-Team (topic 'bat-team') +_KEYWORD_TEST_2 = "rocketchat websocket ddp" # → #Rocketchat-Plugin (topic 'rocketchat-plugin') +_KEYWORD_TEST_3 = "dokumentation homelab netzwerk" # → #LAN-Dokumentation (topic 'lan-dokumentation') + + +# ═══════════════════════════════════════════════════════════════════════════ +# Helpers +# ═══════════════════════════════════════════════════════════════════════════ + + +def _get_widerspruch_actions(msg: dict) -> list: + """Alle WIDERSPRUCH-Action-Dicts aus den Attachments einer Nachricht.""" + result = [] + for att in msg.get("attachments", []): + for action in att.get("actions", []): + if (action.get("msg", "") or "").startswith("WIDERSPRUCH:"): + result.append(action) + return result + + +def _has_widerspruch_buttons(msg: dict) -> bool: + """True wenn die Nachricht WIDERSPRUCH-Buttons enthält.""" + return len(_get_widerspruch_actions(msg)) > 0 + + +def _extract_widerspruch_id(msg: dict) -> Optional[str]: + """Extrahiere clarify_id aus den WIDERSPRUCH-Buttons. + + Payload-Format: WIDERSPRUCH:: (einfacher Doppelpunkt). + """ + for action in _get_widerspruch_actions(msg): + payload = (action.get("msg", "") or "") + parts = payload.split(":") + if len(parts) >= 2 and parts[1]: + return parts[1] + return None + + +def _is_auto_route_announcement(msg: dict) -> bool: + """True wenn die Nachricht eine Auto-Route-Ankündigung ist. + + Die Ankündigung ist eine der 5 _ANNOUNCEMENT_VARIANTS (adapter.py:1101), + die alle 'thema' enthalten und auf den Zielraum verweisen. + """ + text = (msg.get("msg") or "").lower() + return any(ind in text for ind in _AUTO_ROUTE_INDICATORS) + + +def _reset_state(rc_client, test_room_id, posted_message_ids, rate_limiter) -> None: + """::reset senden und kurz warten, damit der Bot den State leert. + + Leert _recent_auto_routes, _session_room_preferences, _rooms_with_pending_questions. + (NICHT _never_route — deshalb unterschiedliche Keywords pro Test.) + """ + _reset_id, _ = post_test_message( + rc_client, test_room_id, "::reset", + posted_message_ids, rate_limiter, + ) + logger.info("Test 09: sent ::reset (msg %s) — clearing routing state", _reset_id[:12]) + time.sleep(5.0) + + +def _trigger_auto_route_and_widerspruch( + rc_client, + test_room_id: str, + bot_username: str, + keyword_text: str, + posted_message_ids: list, + rate_limiter, +) -> tuple[dict, str]: + """Schritte 1-4: Auto-Route → Widerspruch → Clarify. + + Returns: + (clarify_msg, clarify_id) — die Clarify-Nachricht und die extrahierte ID. + + Raises: + pytest.skip / pytest.fail bei Rate-Limit bzw. Timeout. + """ + # ── Step 1: Keyword posten (100%-Keyword → Auto-Route) ────────────── + msg_id, keyword_ts = post_test_message( + rc_client, test_room_id, keyword_text, + posted_message_ids, rate_limiter, + ) + logger.info( + "Test 09: posted keyword '%s' → msg %s (cursor=%s)", + keyword_text[:60], msg_id[:12], keyword_ts[:19], + ) + + # ── Step 2: Auf Auto-Route-Announcement warten ────────────────────── + try: + announcement = wait_for_bot_message( + client=rc_client, + room_id=test_room_id, + bot_username=bot_username, + cursor=keyword_ts, + timeout=_TIMEOUT, + rate_limiter=rate_limiter, + initial_interval=3.0, + ) + except RateLimitSkip as e: + pytest.skip(f"Rate limit triggered: {e}") + except PollTimeout as e: + pytest.fail( + f"Bot did not send auto-route announcement within {_TIMEOUT}s. " + f"Check that the keyword '{keyword_text[:60]}' is a keywords_100 " + f"match and the Archivar is running. Error: {e}" + ) + + announcement_text = announcement.get("msg", "") + logger.info("Test 09: auto-route announcement: '%s'", announcement_text[:200]) + posted_message_ids.append(announcement.get("_id", "")) + + # ── Assertion: Announcement ist tatsächlich eine Auto-Route-Ankündigung ── + assert _is_auto_route_announcement(announcement), ( + f"Bot response is not an auto-route announcement. " + f"Expected indicators {_AUTO_ROUTE_INDICATORS}. " + f"Got: '{announcement_text[:200]}'" + ) + + # ── Step 3: Widerspruch posten ────────────────────────────────────── + widerspruch_id, widerspruch_ts = post_test_message( + rc_client, test_room_id, _WIDERSPRUCH_TEXT, + posted_message_ids, rate_limiter, + ) + logger.info( + "Test 09: posted widerspruch '%s' → msg %s (cursor=%s)", + _WIDERSPRUCH_TEXT, widerspruch_id[:12], widerspruch_ts[:19], + ) + + # ── Step 4: Auf Widerspruch-Clarify warten ───────────────────────── + try: + clarify_msg = wait_for_bot_message( + client=rc_client, + room_id=test_room_id, + bot_username=bot_username, + cursor=widerspruch_ts, + timeout=_TIMEOUT, + rate_limiter=rate_limiter, + initial_interval=3.0, + ) + except RateLimitSkip as e: + pytest.skip(f"Rate limit triggered: {e}") + except PollTimeout as e: + pytest.fail( + f"Bot did not send widerspruch-clarify within {_TIMEOUT}s. " + f"Check that detect_routing_contradiction fires after auto-route. " + f"Widerspruch: '{_WIDERSPRUCH_TEXT}'. Error: {e}" + ) + + clarify_text = clarify_msg.get("msg", "") + logger.info("Test 09: widerspruch-clarify: '%s'", clarify_text[:200]) + posted_message_ids.append(clarify_msg.get("_id", "")) + + # ── Assertion: Clarify enthält Widerspruch-Text + Buttons ─────────── + assert _WIDERSPRUCH_TEXT_MARKER in clarify_text.lower(), ( + f"Widerspruch-clarify text missing '{_WIDERSPRUCH_TEXT_MARKER}'. " + f"Got: '{clarify_text[:200]}'" + ) + assert _has_widerspruch_buttons(clarify_msg), ( + f"Widerspruch-clarify has no WIDERSPRUCH buttons. " + f"Attachments: {clarify_msg.get('attachments', [])}" + ) + + clarify_id = _extract_widerspruch_id(clarify_msg) + assert clarify_id, ( + f"Could not extract clarify_id from widerspruch-clarify. " + f"Attachments: {clarify_msg.get('attachments', [])}" + ) + logger.info("Test 09: extracted clarify_id=%s", clarify_id) + + return clarify_msg, clarify_id + + +# ═══════════════════════════════════════════════════════════════════════════ +# Test 1: Widerspruch-Clarify nach Auto-Route +# ═══════════════════════════════════════════════════════════════════════════ + + +@pytest.mark.live_rc +def test_widerspruch_clarify_after_auto_route( + rc_client, + test_room_id: str, + bot_username: str, + bot_user_id: str, + cursor: str, + posted_message_ids: list, + rate_limiter, + cleanup_messages, + bot_status_check, +): + """Auto-Route → Widerspruch → Clarify mit 2 Buttons + action_id (P-051).""" + _reset_state(rc_client, test_room_id, posted_message_ids, rate_limiter) + + clarify_msg, clarify_id = _trigger_auto_route_and_widerspruch( + rc_client, test_room_id, bot_username, _KEYWORD_TEST_1, + posted_message_ids, rate_limiter, + ) + + # ── Verifiziere: 2 Buttons (1️⃣ generell hier her, 2️⃣ nur jetzt hier her) ── + actions = _get_widerspruch_actions(clarify_msg) + assert len(actions) == 2, ( + f"Expected exactly 2 WIDERSPRUCH buttons, got {len(actions)}. " + f"Actions: {actions}" + ) + + # ── Verifiziere: Button-Labels enthalten Emoji-Nummern ────────────── + labels = [a.get("text", "") for a in actions] + assert any("1️⃣" in label for label in labels), ( + f"Button 1 label missing '1️⃣'. Labels: {labels}" + ) + assert any("2️⃣" in label for label in labels), ( + f"Button 2 label missing '2️⃣'. Labels: {labels}" + ) + + # ── Verifiziere: action_id vorhanden (P-051) ─────────────────────── + for i, action in enumerate(actions): + action_id = action.get("action_id", "") + assert action_id, ( + f"WIDERSPRUCH action {i} missing action_id field (P-051 regression). " + f"Action: {action}" + ) + + # ── Verifiziere: Message-Ownership ───────────────────────────────── + assert_bot_message( + clarify_msg, + expected_username=bot_username, + context="test_widerspruch_clarify_after_auto_route", + ) + + logger.info("Test 09.1 PASSED: widerspruch-clarify after auto-route OK") + + +# ═══════════════════════════════════════════════════════════════════════════ +# Test 2: Button 1 'generell hier her' → set_never_route (dauerhaft) +# ═══════════════════════════════════════════════════════════════════════════ + + +@pytest.mark.live_rc +def test_widerspruch_button_1_generell( + rc_client, + test_room_id: str, + bot_username: str, + bot_user_id: str, + cursor: str, + posted_message_ids: list, + rate_limiter, + cleanup_messages, + bot_status_check, +): + """Button 1 ('generell hier her') → set_never_route → kein Auto-Route mehr.""" + _reset_state(rc_client, test_room_id, posted_message_ids, rate_limiter) + + clarify_msg, clarify_id = _trigger_auto_route_and_widerspruch( + rc_client, test_room_id, bot_username, _KEYWORD_TEST_2, + posted_message_ids, rate_limiter, + ) + + # ── Step 2: Button 1 klicken (WIDERSPRUCH::1) ────────────────── + button_payload = f"WIDERSPRUCH:{clarify_id}:1" + button_msg_id, button_ts = post_test_message( + rc_client, test_room_id, button_payload, + posted_message_ids, rate_limiter, + ) + logger.info( + "Test 09.2: posted button-1 payload '%s' → msg %s", + button_payload, button_msg_id[:12], + ) + + # ── Step 3: Auf Bestätigungsnachricht warten ─────────────────────── + try: + confirm_msg = wait_for_bot_message( + client=rc_client, + room_id=test_room_id, + bot_username=bot_username, + cursor=button_ts, + timeout=_TIMEOUT, + rate_limiter=rate_limiter, + initial_interval=3.0, + ) + except RateLimitSkip as e: + pytest.skip(f"Rate limit triggered: {e}") + except PollTimeout as e: + pytest.fail( + f"Bot did not confirm button-1 click within {_TIMEOUT}s. " + f"Payload: '{button_payload}'. Error: {e}" + ) + confirm_text = confirm_msg.get("msg", "") + logger.info("Test 09.2: button-1 confirmation: '%s'", confirm_text[:200]) + posted_message_ids.append(confirm_msg.get("_id", "")) + + # ── Step 4: ERNEUT dasselbe Keyword posten ───────────────────────── + msg_id, keyword_ts = post_test_message( + rc_client, test_room_id, _KEYWORD_TEST_2, + posted_message_ids, rate_limiter, + ) + logger.info( + "Test 09.2: re-posted keyword '%s' → msg %s (cursor=%s)", + _KEYWORD_TEST_2[:60], msg_id[:12], keyword_ts[:19], + ) + + # ── Step 5: KEIN Auto-Route — Nachricht bleibt im Ursprungsraum ───── + # Der Bot antwortet im Ursprungsraum (Agent-Dispatch), NICHT mit einer + # Auto-Route-Ankündigung. Die erste Bot-Nachricht darf KEINE + # Ankündigungs-Indikatoren ('thema'/'wechseln'/'rüber') enthalten. + try: + response = wait_for_bot_message( + client=rc_client, + room_id=test_room_id, + bot_username=bot_username, + cursor=keyword_ts, + timeout=_TIMEOUT, + rate_limiter=rate_limiter, + initial_interval=3.0, + ) + except RateLimitSkip as e: + pytest.skip(f"Rate limit triggered: {e}") + except PollTimeout as e: + pytest.fail( + f"Bot did not respond to re-posted keyword within {_TIMEOUT}s. " + f"Error: {e}" + ) + + response_text = response.get("msg", "") + logger.info("Test 09.2: bot response to re-posted keyword: '%s'", response_text[:200]) + posted_message_ids.append(response.get("_id", "")) + + # ── Assertion: KEIN Auto-Route (keine Ankündigung) ───────────────── + assert not _is_auto_route_announcement(response), ( + f"Auto-route fired AGAIN despite set_never_route (button 1). " + f"Expected no auto-route announcement, got: '{response_text[:200]}'" + ) + + # ── Step 6: Agent wurde dispatcht (Bot antwortet auf die Frage) ──── + assert response_text, ( + f"Bot response to re-posted keyword has no text. Full message: {response}" + ) + assert_bot_message( + response, + expected_username=bot_username, + context="test_widerspruch_button_1_generell", + ) + + logger.info("Test 09.2 PASSED: button-1 (generell) → set_never_route → no auto-route") + + +# ═══════════════════════════════════════════════════════════════════════════ +# Test 3: Button 2 'nur jetzt hier her' → stay_once (einmalig) +# ═══════════════════════════════════════════════════════════════════════════ + + +@pytest.mark.live_rc +def test_widerspruch_button_2_stay_once( + rc_client, + test_room_id: str, + bot_username: str, + bot_user_id: str, + cursor: str, + posted_message_ids: list, + rate_limiter, + cleanup_messages, + bot_status_check, +): + """Button 2 ('nur jetzt hier her') → stay_once → Auto-Route feuert wieder.""" + _reset_state(rc_client, test_room_id, posted_message_ids, rate_limiter) + + clarify_msg, clarify_id = _trigger_auto_route_and_widerspruch( + rc_client, test_room_id, bot_username, _KEYWORD_TEST_3, + posted_message_ids, rate_limiter, + ) + + # ── Step 2: Button 2 klicken (WIDERSPRUCH::2) ────────────────── + button_payload = f"WIDERSPRUCH:{clarify_id}:2" + button_msg_id, button_ts = post_test_message( + rc_client, test_room_id, button_payload, + posted_message_ids, rate_limiter, + ) + logger.info( + "Test 09.3: posted button-2 payload '%s' → msg %s", + button_payload, button_msg_id[:12], + ) + + # ── Step 3: Auf Bestätigungsnachricht warten ─────────────────────── + try: + confirm_msg = wait_for_bot_message( + client=rc_client, + room_id=test_room_id, + bot_username=bot_username, + cursor=button_ts, + timeout=_TIMEOUT, + rate_limiter=rate_limiter, + initial_interval=3.0, + ) + except RateLimitSkip as e: + pytest.skip(f"Rate limit triggered: {e}") + except PollTimeout as e: + pytest.fail( + f"Bot did not confirm button-2 click within {_TIMEOUT}s. " + f"Payload: '{button_payload}'. Error: {e}" + ) + confirm_text = confirm_msg.get("msg", "") + logger.info("Test 09.3: button-2 confirmation: '%s'", confirm_text[:200]) + posted_message_ids.append(confirm_msg.get("_id", "")) + + # ── Step 4: ERNEUT dasselbe Keyword posten ───────────────────────── + msg_id, keyword_ts = post_test_message( + rc_client, test_room_id, _KEYWORD_TEST_3, + posted_message_ids, rate_limiter, + ) + logger.info( + "Test 09.3: re-posted keyword '%s' → msg %s (cursor=%s)", + _KEYWORD_TEST_3[:60], msg_id[:12], keyword_ts[:19], + ) + + # ── Step 5: Auto-Route feuert WIEDER (stay_once ist nur einmalig) ── + try: + announcement = wait_for_bot_message( + client=rc_client, + room_id=test_room_id, + bot_username=bot_username, + cursor=keyword_ts, + timeout=_TIMEOUT, + rate_limiter=rate_limiter, + initial_interval=3.0, + ) + except RateLimitSkip as e: + pytest.skip(f"Rate limit triggered: {e}") + except PollTimeout as e: + pytest.fail( + f"Bot did not auto-route again after stay_once (button 2) within " + f"{_TIMEOUT}s. Expected auto-route announcement. Error: {e}" + ) + + announcement_text = announcement.get("msg", "") + logger.info("Test 09.3: re-route announcement: '%s'", announcement_text[:200]) + posted_message_ids.append(announcement.get("_id", "")) + + # ── Assertion: Auto-Route-Ankündigung ist wieder da ──────────────── + assert _is_auto_route_announcement(announcement), ( + f"Expected auto-route announcement after stay_once (button 2), " + f"but got: '{announcement_text[:200]}'" + ) + assert_bot_message( + announcement, + expected_username=bot_username, + context="test_widerspruch_button_2_stay_once", + ) + + logger.info("Test 09.3 PASSED: button-2 (stay_once) → auto-route fires again") + + +# ═══════════════════════════════════════════════════════════════════════════ +# Test 4: Kein Widerspruch-Clarify ohne vorherige Auto-Route +# ═══════════════════════════════════════════════════════════════════════════ + + +@pytest.mark.live_rc +def test_no_clarify_without_auto_route( + rc_client, + test_room_id: str, + bot_username: str, + bot_user_id: str, + cursor: str, + posted_message_ids: list, + rate_limiter, + cleanup_messages, + bot_status_check, +): + """'Das passt hier her' OHNE vorherige Auto-Route → KEIN Widerspruch-Clarify. + + Der Widerspruch-Clarify ist eine Reaktion auf eine Auto-Route. Ohne + _recent_auto_routes-Eintrag wird der Widerspruch-Check übersprungen + (adapter_integration.py:423) und die Nachricht normal verarbeitet. + """ + _reset_state(rc_client, test_room_id, posted_message_ids, rate_limiter) + + # ── Step 1: 'Das passt hier her' OHNE vorherige Auto-Route posten ── + # Kein keywords_100-Wort — soll KEIN Auto-Route triggern. + msg_id, msg_ts = post_test_message( + rc_client, test_room_id, _WIDERSPRUCH_TEXT, + posted_message_ids, rate_limiter, + ) + logger.info( + "Test 09.4: posted '%s' (no prior auto-route) → msg %s (cursor=%s)", + _WIDERSPRUCH_TEXT, msg_id[:12], msg_ts[:19], + ) + + # ── Step 2: Auf Bot-Antwort warten (normale Verarbeitung) ────────── + try: + response = wait_for_bot_message( + client=rc_client, + room_id=test_room_id, + bot_username=bot_username, + cursor=msg_ts, + timeout=_TIMEOUT, + rate_limiter=rate_limiter, + initial_interval=3.0, + ) + except RateLimitSkip as e: + pytest.skip(f"Rate limit triggered: {e}") + except PollTimeout as e: + pytest.fail( + f"Bot did not respond to '{_WIDERSPRUCH_TEXT}' within {_TIMEOUT}s. " + f"Error: {e}" + ) + + response_text = response.get("msg", "") + logger.info("Test 09.4: bot response: '%s'", response_text[:200]) + posted_message_ids.append(response.get("_id", "")) + + # ── Step 3: KEIN Widerspruch-Clarify — normale Verarbeitung ──────── + assert not _has_widerspruch_buttons(response), ( + f"Bot sent a widerspruch-clarify WITHOUT a prior auto-route. " + f"Expected normal processing. Attachments: {response.get('attachments', [])}" + ) + assert _WIDERSPRUCH_TEXT_MARKER not in response_text.lower(), ( + f"Bot response contains '{_WIDERSPRUCH_TEXT_MARKER}' without prior " + f"auto-route. Expected normal processing. Got: '{response_text[:200]}'" + ) + + # ── Verifiziere: Message-Ownership ───────────────────────────────── + assert_bot_message( + response, + expected_username=bot_username, + context="test_no_clarify_without_auto_route", + ) + + logger.info("Test 09.4 PASSED: no widerspruch-clarify without prior auto-route")