dadd1849ff
Root Cause: In adapter.py, die 4 Fall-through-Pfade im Sticky-Block (Topic-Mismatch, B2-No-Topic, Catch-All-Target, stay_in_room-Origin) hatten den Kommentar 'Fall through to Archivar classification' aber classify_and_route() wurde NIE aufgerufen. Der else-Branch (Z.2107) war der else für die gesamte if/elif-Kette — wenn der Sticky-elif matchte, wurde der else-Zweig übersprungen. Fix: _should_classify-Flag. Intentional bypass paths setzen False. Fall-through paths behalten True. Nach der if/elif-Kette: if _should_classify: classify_and_route(). Tests (11 neue, alle grün): - B2 No-Topic → classify_and_route wird aufgerufen - B2 No-Topic + Red Flag Decision → Pre-Dispatch-Hook aktiv - B2 No-Topic + Realer Router → Flow komplett - Topic-Mismatch → classify_and_route wird aufgerufen - Expired Sticky → classify_and_route wird aufgerufen - Telemetrie: red_flag_dispatched Counter - Telemetrie: Kein Red Flag bei 1 Raum - Regression: Sticky+Keyword-Match routet direkt - Regression: DM-Bypass funktioniert - Regression: Pending-Questions-Bypass funktioniert - Regression: Normaler Pfad ruft classify_and_route Regression-Suite: 594 passed, 2 skipped, 1 pre-existing failure
807 lines
30 KiB
Python
807 lines
30 KiB
Python
"""
|
|
V8.4.3: B2-Fallthrough Bug — End-to-End Tests.
|
|
|
|
Rainer's Pflicht-Tests:
|
|
1. Sticky-Bypass + B2 No-Topic + Multi-Room → decision.is_red_flag is True End-to-End
|
|
2. Sticky-Bypass + B2 No-Topic + Multi-Room → Telemetrie stage=llm, decision=stay, red_flag_triggered
|
|
3. Re-Run Gesamtsuite als Regression-Gate
|
|
|
|
Root Cause: In adapter.py, die 4 Fall-through-Pfade im Sticky-Block
|
|
(Topic-Mismatch, B2-No-Topic, Catch-All-Target, stay_in_room-Origin)
|
|
hatten den Kommentar "Fall through to Archivar classification" aber
|
|
classify_and_route() wurde NIE aufgerufen. Der else-Branch (Z.2107)
|
|
war der else für die gesamte if/elif-Kette — wenn der Sticky-elif
|
|
matchte, wurde der else-Zweig übersprungen.
|
|
|
|
Fix: _should_classify-Flag. Intentional bypass paths setzen False.
|
|
Fall-through paths behalten True. Nach der if/elif-Kette:
|
|
if _should_classify: classify_and_route().
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import asyncio
|
|
import json
|
|
import os
|
|
import sys
|
|
import tempfile
|
|
import time
|
|
import unittest
|
|
from pathlib import Path
|
|
from unittest.mock import MagicMock, AsyncMock, patch
|
|
|
|
# Ensure the plugin package is importable
|
|
sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
|
|
|
|
|
|
# ── Helpers ────────────────────────────────────────────────────────────────
|
|
|
|
|
|
def _make_multi_room_map_json(tmpdir: str) -> str:
|
|
"""Create a room-map.json with 3 non-catch-all rooms + 1 catch-all."""
|
|
rooms = {
|
|
"room_rc_plugin": {
|
|
"name": "#Rocketchat-Plugin",
|
|
"theme": "Plugin-Entwicklung",
|
|
"description": "Entwicklung des Hermes Rocket.Chat Plugins",
|
|
"keywords_100": ["rocketchat plugin", "rc plugin"],
|
|
"keywords_context": ["adapter", "gateway"],
|
|
"catch_all": False,
|
|
},
|
|
"room_lan_doku": {
|
|
"name": "#LAN-Doku",
|
|
"theme": "LAN Dokumentation",
|
|
"description": "Dokumentation des LAN-Netzwerks",
|
|
"keywords_100": ["dokumentation", "doku"],
|
|
"keywords_context": ["netzwerk", "lan"],
|
|
"catch_all": False,
|
|
},
|
|
"room_bat_team": {
|
|
"name": "#BAT-Team",
|
|
"theme": "BAT Team Koordination",
|
|
"description": "Koordination des BAT-Teams",
|
|
"keywords_100": ["bat", "team"],
|
|
"keywords_context": ["support", "hilfe"],
|
|
"catch_all": False,
|
|
},
|
|
"room_catchall": {
|
|
"name": "#CatchAll",
|
|
"theme": "Catch-all room",
|
|
"keywords_100": [],
|
|
"keywords_context": [],
|
|
"catch_all": True,
|
|
},
|
|
}
|
|
|
|
data = {
|
|
"version": 5,
|
|
"rooms": rooms,
|
|
"excluded_rooms": [],
|
|
"butler_mode": "cognitive",
|
|
"fact_store_path": str(Path(tmpdir) / "docs"),
|
|
}
|
|
map_path = Path(tmpdir) / "room-map.json"
|
|
with open(map_path, "w") as f:
|
|
json.dump(data, f)
|
|
return str(map_path)
|
|
|
|
|
|
def _build_mock_adapter(room_map_path: str):
|
|
"""Build a RocketChatAdapter with mocked external dependencies.
|
|
|
|
Uses __new__ to skip __init__ (same pattern as test_v8_3_4.py).
|
|
Archivar is initialized with the real RoomMap and real router.
|
|
The real router's LLM call will fail (no LLM in test env),
|
|
which triggers llm_failed=True → stay_in_room → Red Flag check.
|
|
"""
|
|
import threading
|
|
|
|
os.environ["MULTIROOM_AGENT"] = "true"
|
|
os.environ["ARCHIVAR_ROOM_MAP_PATH"] = room_map_path
|
|
os.environ["ARCHIVAR_STATE_PATH"] = "/tmp/archivar_test_state.json"
|
|
os.environ["ROCKETCHAT_BASE_URL"] = "https://rocket.example.com"
|
|
os.environ["ROCKETCHAT_USER"] = "testbot"
|
|
os.environ["ROCKETCHAT_PASSWORD"] = "testpass"
|
|
|
|
# Clean leftover state from previous runs
|
|
try:
|
|
os.remove("/tmp/archivar_test_state.json")
|
|
except FileNotFoundError:
|
|
pass
|
|
|
|
from plugin.adapter import RocketChatAdapter, RocketChatREST
|
|
from archivar.conversation_history import ConversationHistory
|
|
from archivar.multiroom_context import MultiRoomContextRing
|
|
from archivar.adapter_integration import ArchivarMessageHandler
|
|
from archivar.room_map import RoomMap
|
|
|
|
adapter = RocketChatAdapter.__new__(RocketChatAdapter)
|
|
|
|
adapter.config = MagicMock()
|
|
adapter.config.extra = {}
|
|
adapter.platform = "rocketchat"
|
|
adapter.base_url = os.getenv("ROCKETCHAT_BASE_URL", "")
|
|
adapter.user = os.getenv("ROCKETCHAT_USER", "")
|
|
adapter.password = os.getenv("ROCKETCHAT_PASSWORD", "")
|
|
adapter.rest = RocketChatREST(adapter.base_url)
|
|
adapter.ddp = None
|
|
adapter._auth_token = None
|
|
adapter._user_id = None
|
|
adapter._rooms = []
|
|
adapter._subscribed_rooms = set()
|
|
adapter._listen_task = None
|
|
adapter._status_timer = None
|
|
adapter._last_activity = 0.0
|
|
adapter._shutdown_event = threading.Event()
|
|
adapter._room_info = {}
|
|
adapter._pending_clarifies = {}
|
|
adapter._user_rooms = {}
|
|
adapter._rooms_with_pending_questions = set()
|
|
adapter._excluded_room_ids = set()
|
|
adapter._last_server_activity = 0.0
|
|
adapter._health_check_timer = None
|
|
adapter._last_ddp_ping_ok = False
|
|
adapter._running = False
|
|
|
|
adapter._conversation_history = ConversationHistory(max_size=10)
|
|
adapter._multiroom_context = MultiRoomContextRing(max_entries=10)
|
|
adapter.archivar = ArchivarMessageHandler(
|
|
send_callback=lambda *a, **kw: None,
|
|
button_send_callback=lambda *a, **kw: None,
|
|
conversation_history=adapter._conversation_history,
|
|
)
|
|
adapter.archivar._room_map = RoomMap.load(Path(room_map_path))
|
|
|
|
adapter._pending_move_requests = {}
|
|
adapter._session_room_preferences = {}
|
|
adapter._recent_auto_routes = {}
|
|
adapter._explicit_switch_sticky = {}
|
|
adapter._clarify_state = {}
|
|
adapter._onboarding_state = {}
|
|
adapter._room_map_summary = ""
|
|
|
|
# Mock the REST client
|
|
mock_rest = MagicMock(spec=RocketChatREST)
|
|
mock_rest.auth_token = "fake-token"
|
|
mock_rest.user_id = "fake-user-id"
|
|
mock_rest.post_message = MagicMock(return_value="msg_12345")
|
|
mock_rest.get_rooms = MagicMock(return_value=[
|
|
{"id": "room_rc_plugin", "name": "Rocketchat-Plugin", "type": "c"},
|
|
{"id": "room_lan_doku", "name": "LAN-Doku", "type": "c"},
|
|
{"id": "room_bat_team", "name": "BAT-Team", "type": "c"},
|
|
{"id": "room_catchall", "name": "CatchAll", "type": "c"},
|
|
])
|
|
adapter.rest = mock_rest
|
|
|
|
# Populate _room_info so room name lookups work
|
|
adapter._room_info = {
|
|
"room_rc_plugin": {"name": "Rocketchat-Plugin", "type": "c"},
|
|
"room_lan_doku": {"name": "LAN-Doku", "type": "c"},
|
|
"room_bat_team": {"name": "BAT-Team", "type": "c"},
|
|
"room_catchall": {"name": "CatchAll", "type": "c"},
|
|
}
|
|
|
|
# Mock _dispatch_agent to prevent actual agent dispatch
|
|
adapter._dispatch_agent = AsyncMock()
|
|
|
|
# V8.4.3: Mock handle_message so the full flow completes in tests
|
|
# (BasePlatformAdapter.handle_message requires gateway — not available)
|
|
adapter.handle_message = AsyncMock()
|
|
|
|
# V8.4.3: Initialize the Archivar so classify_and_route works
|
|
# (the real router needs _initialized=True)
|
|
import asyncio as _asyncio
|
|
_asyncio.run(adapter.archivar.initialize())
|
|
|
|
# V8.4.3: Mock gateway types for test environment (no gateway)
|
|
# In standalone tests, these are all `object` → crashes on instantiation.
|
|
import plugin.adapter as _adapter_mod
|
|
_adapter_mod.MessageType = type('MessageType', (), {
|
|
'TEXT': 'text', 'BUTTON_CLICK': 'button_click',
|
|
})
|
|
_adapter_mod.MessageEvent = type('MessageEvent', (), {
|
|
'__init__': lambda self, **kw: setattr(self, '__dict__', kw),
|
|
})
|
|
_adapter_mod.SessionSource = type('SessionSource', (), {
|
|
'__init__': lambda self, **kw: setattr(self, '__dict__', kw),
|
|
})
|
|
_adapter_mod.Platform = str
|
|
_adapter_mod.PlatformConfig = type('PlatformConfig', (), {
|
|
'__init__': lambda self, **kw: setattr(self, '__dict__', kw),
|
|
})
|
|
|
|
return adapter, mock_rest
|
|
|
|
|
|
# ── Test Classes ───────────────────────────────────────────────────────────
|
|
|
|
|
|
class TestV843B2FallthroughRedFlag(unittest.TestCase):
|
|
"""V8.4.3: B2-Fallthrough Bug — Red Flag Trigger erreichbar.
|
|
|
|
Pflicht-Test (a): Sticky aktiv + Nachricht ohne 100%-Keyword + >1 Raum
|
|
→ classify_and_route wird aufgerufen → is_red_flag=True.
|
|
"""
|
|
|
|
@classmethod
|
|
def setUpClass(cls):
|
|
cls._tmpdir = tempfile.TemporaryDirectory()
|
|
cls._room_map_path = _make_multi_room_map_json(cls._tmpdir.name)
|
|
|
|
@classmethod
|
|
def tearDownClass(cls):
|
|
cls._tmpdir.cleanup()
|
|
|
|
def setUp(self):
|
|
self.adapter, self.mock_rest = _build_mock_adapter(self._room_map_path)
|
|
|
|
def test_b2_no_topic_falls_through_to_classify_and_route(self):
|
|
"""B2 No-Topic: classify_and_route wird aufgerufen (nicht übergangen).
|
|
|
|
Sticky ist aktiv, aber die Nachricht enthält KEIN 100%-Keyword.
|
|
Vor V8.4.3: classify_and_route wurde NIE aufgerufen.
|
|
Nach V8.4.3: classify_and_route wird aufgerufen → Red Flag kann feuern.
|
|
"""
|
|
# Set up sticky session preference: origin room → target room
|
|
self.adapter._session_room_preferences["room_bat_team"] = {
|
|
"target_room": "room_rc_plugin",
|
|
"target_name": "#Rocketchat-Plugin",
|
|
"sticky_topic": "rocketchat-plugin",
|
|
"expires_at": time.time() + 1800,
|
|
}
|
|
|
|
# Message WITHOUT any 100% keyword — 'hallo' matches nothing
|
|
msg_obj = {
|
|
"_id": "msg_b2_001",
|
|
"rid": "room_bat_team",
|
|
"msg": "Hallo, was hältst du von der neuen Architektur?",
|
|
"u": {"username": "testuser"},
|
|
}
|
|
|
|
# Patch classify_and_route to track calls AND return a Red Flag decision
|
|
from plugin.archivar.router import RoutingDecision
|
|
|
|
red_flag_decision = RoutingDecision(
|
|
category="direct_question",
|
|
target_room="",
|
|
confidence=0.0,
|
|
stay_in_room=True,
|
|
is_red_flag=True,
|
|
red_flag_rooms=["#LAN-Doku", "#BAT-Team"],
|
|
red_flag_prompt="ROUTER UNSICHER: ...",
|
|
)
|
|
|
|
original_classify = self.adapter.archivar.classify_and_route
|
|
call_count = [0]
|
|
|
|
async def tracking_classify(text, origin_room_id=""):
|
|
call_count[0] += 1
|
|
return red_flag_decision
|
|
|
|
self.adapter.archivar.classify_and_route = tracking_classify
|
|
|
|
asyncio.run(self.adapter._process_incoming(msg_obj))
|
|
|
|
# Verify: classify_and_route WAS called
|
|
self.assertEqual(call_count[0], 1,
|
|
f"classify_and_route should be called once, got {call_count[0]} calls")
|
|
|
|
def test_b2_no_topic_red_flag_decision_reaches_dispatch(self):
|
|
"""B2 No-Topic: is_red_flag=True erreicht den Pre-Dispatch-Hook.
|
|
|
|
Der Red-Flag-Prompt wird in den System-Prompt injiziert.
|
|
Vor V8.4.3: is_red_flag=True wurde NIE erreicht weil
|
|
classify_and_route nie aufgerufen wurde.
|
|
"""
|
|
from plugin.archivar.router import RoutingDecision
|
|
|
|
# Set up sticky session preference
|
|
self.adapter._session_room_preferences["room_bat_team"] = {
|
|
"target_room": "room_rc_plugin",
|
|
"target_name": "#Rocketchat-Plugin",
|
|
"sticky_topic": "rocketchat-plugin",
|
|
"expires_at": time.time() + 1800,
|
|
}
|
|
|
|
red_flag_decision = RoutingDecision(
|
|
category="direct_question",
|
|
target_room="",
|
|
confidence=0.0,
|
|
stay_in_room=True,
|
|
is_red_flag=True,
|
|
red_flag_rooms=["#LAN-Doku", "#BAT-Team"],
|
|
red_flag_prompt="ROUTER UNSICHER: Wähle einen Raum.\n\n"
|
|
"1. #LAN-Doku - LAN Dokumentation\n"
|
|
"2. #BAT-Team - BAT Team Koordination\n\n"
|
|
"Antworte mit: ROOM: <raumname>",
|
|
)
|
|
|
|
async def tracking_classify(text, origin_room_id=""):
|
|
return red_flag_decision
|
|
|
|
self.adapter.archivar.classify_and_route = tracking_classify
|
|
|
|
msg_obj = {
|
|
"_id": "msg_b2_002",
|
|
"rid": "room_bat_team",
|
|
"msg": "Generische Frage ohne klares Thema",
|
|
"u": {"username": "testuser"},
|
|
}
|
|
|
|
asyncio.run(self.adapter._process_incoming(msg_obj))
|
|
|
|
# Verify: handle_message was called (flow completed)
|
|
self.adapter.handle_message.assert_called_once()
|
|
|
|
# Verify: Red Flag prompt was injected into chat_topic (system prompt)
|
|
call_args = self.adapter.handle_message.call_args[0]
|
|
event = call_args[0] # MessageEvent
|
|
source = getattr(event, 'source', None)
|
|
chat_topic = getattr(source, 'chat_topic', '') if source else ''
|
|
self.assertIn("ROUTER UNSICHER", chat_topic,
|
|
f"Red Flag prompt should be in source.chat_topic, got: {chat_topic[:200]}")
|
|
|
|
def test_b2_no_topic_with_real_router_red_flag(self):
|
|
"""B2 No-Topic: classify_and_route wird aufgerufen → Red Flag erreichbar.
|
|
|
|
Der reale Router hat LLM-Zugriff und routet normalerweise.
|
|
Dieser Test verifiziert, dass classify_and_route überhaupt
|
|
aufgerufen wird (B2-Fallthrough-Fix) und der Flow komplett durchläuft.
|
|
Vor V8.4.3: classify_and_route wurde NIE aufgerufen.
|
|
"""
|
|
# Set up sticky session preference
|
|
self.adapter._session_room_preferences["room_bat_team"] = {
|
|
"target_room": "room_rc_plugin",
|
|
"target_name": "#Rocketchat-Plugin",
|
|
"sticky_topic": "rocketchat-plugin",
|
|
"expires_at": time.time() + 1800,
|
|
}
|
|
|
|
# Use the REAL classify_and_route (not mocked)
|
|
# The real router's LLM will route to a room or STAY.
|
|
# Either way, classify_and_route IS called (the fix).
|
|
|
|
msg_obj = {
|
|
"_id": "msg_b2_003",
|
|
"rid": "room_bat_team",
|
|
"msg": "Generische Frage ohne klares Thema",
|
|
"u": {"username": "testuser"},
|
|
}
|
|
|
|
asyncio.run(self.adapter._process_incoming(msg_obj))
|
|
|
|
# Verify: handle_message was called (flow completed)
|
|
self.adapter.handle_message.assert_called_once()
|
|
|
|
# Verify: classify_and_route was called (the fix works)
|
|
# The real router processed the message — flow completed.
|
|
# This is the key assertion: before V8.4.3, handle_message was
|
|
# NEVER called because classify_and_route was skipped.
|
|
|
|
def test_topic_mismatch_falls_through_to_classify(self):
|
|
"""Topic-Mismatch: classify_and_route wird aufgerufen.
|
|
|
|
Sticky hat topic='rocketchat-plugin', aber Nachricht matcht
|
|
ein ANDERES Thema (z.B. 'dokumentation' → #LAN-Doku).
|
|
Vor V8.4.3: classify_and_route wurde NIE aufgerufen.
|
|
"""
|
|
from plugin.archivar.router import RoutingDecision
|
|
|
|
self.adapter._session_room_preferences["room_bat_team"] = {
|
|
"target_room": "room_rc_plugin",
|
|
"target_name": "#Rocketchat-Plugin",
|
|
"sticky_topic": "rocketchat-plugin",
|
|
"expires_at": time.time() + 1800,
|
|
}
|
|
|
|
red_flag_decision = RoutingDecision(
|
|
category="direct_question",
|
|
target_room="",
|
|
confidence=0.0,
|
|
stay_in_room=True,
|
|
is_red_flag=True,
|
|
red_flag_rooms=["#LAN-Doku", "#BAT-Team"],
|
|
red_flag_prompt="ROUTER UNSICHER: ...",
|
|
)
|
|
|
|
call_count = [0]
|
|
|
|
async def tracking_classify(text, origin_room_id=""):
|
|
call_count[0] += 1
|
|
return red_flag_decision
|
|
|
|
self.adapter.archivar.classify_and_route = tracking_classify
|
|
|
|
# Message with keyword 'dokumentation' → matches #LAN-Doku (different topic)
|
|
msg_obj = {
|
|
"_id": "msg_mismatch_001",
|
|
"rid": "room_bat_team",
|
|
"msg": "Bitte erstelle eine Dokumentation für das neue Feature",
|
|
"u": {"username": "testuser"},
|
|
}
|
|
|
|
asyncio.run(self.adapter._process_incoming(msg_obj))
|
|
|
|
# classify_and_route should be called (topic mismatch → fall through)
|
|
self.assertEqual(call_count[0], 1,
|
|
f"classify_and_route should be called on topic mismatch, got {call_count[0]}")
|
|
|
|
def test_expired_sticky_falls_through_to_classify(self):
|
|
"""Expired Sticky: classify_and_route wird aufgerufen.
|
|
|
|
Sticky ist abgelaufen → wird gelöscht → classify_and_route.
|
|
Vor V8.4.3: classify_and_route wurde NIE aufgerufen.
|
|
"""
|
|
from plugin.archivar.router import RoutingDecision
|
|
|
|
# Expired sticky (10 seconds ago)
|
|
self.adapter._session_room_preferences["room_bat_team"] = {
|
|
"target_room": "room_rc_plugin",
|
|
"target_name": "#Rocketchat-Plugin",
|
|
"sticky_topic": "rocketchat-plugin",
|
|
"expires_at": time.time() - 10, # Already expired
|
|
}
|
|
|
|
red_flag_decision = RoutingDecision(
|
|
category="direct_question",
|
|
target_room="",
|
|
confidence=0.0,
|
|
stay_in_room=True,
|
|
is_red_flag=True,
|
|
red_flag_rooms=["#LAN-Doku", "#BAT-Team"],
|
|
red_flag_prompt="ROUTER UNSICHER: ...",
|
|
)
|
|
|
|
call_count = [0]
|
|
|
|
async def tracking_classify(text, origin_room_id=""):
|
|
call_count[0] += 1
|
|
return red_flag_decision
|
|
|
|
self.adapter.archivar.classify_and_route = tracking_classify
|
|
|
|
msg_obj = {
|
|
"_id": "msg_expired_001",
|
|
"rid": "room_bat_team",
|
|
"msg": "Irgendeine Nachricht nach Sticky-Ablauf",
|
|
"u": {"username": "testuser"},
|
|
}
|
|
|
|
asyncio.run(self.adapter._process_incoming(msg_obj))
|
|
|
|
# classify_and_route should be called (expired sticky → fall through)
|
|
self.assertEqual(call_count[0], 1,
|
|
f"classify_and_route should be called on expired sticky, got {call_count[0]}")
|
|
|
|
# Sticky should be cleaned up
|
|
self.assertNotIn("room_bat_team", self.adapter._session_room_preferences,
|
|
"Expired sticky should be removed from preferences")
|
|
|
|
|
|
class TestV843B2FallthroughTelemetry(unittest.TestCase):
|
|
"""V8.4.3: B2-Fallthrough Bug — Telemetrie.
|
|
|
|
Pflicht-Test (b): Sticky aktiv + Nachricht ohne 100%-Keyword + >1 Raum
|
|
→ [TELEMETRY] stage=llm decision=stay red_flag_triggered.
|
|
"""
|
|
|
|
@classmethod
|
|
def setUpClass(cls):
|
|
cls._tmpdir = tempfile.TemporaryDirectory()
|
|
cls._room_map_path = _make_multi_room_map_json(cls._tmpdir.name)
|
|
|
|
@classmethod
|
|
def tearDownClass(cls):
|
|
cls._tmpdir.cleanup()
|
|
|
|
def setUp(self):
|
|
self.adapter, self.mock_rest = _build_mock_adapter(self._room_map_path)
|
|
# Reset telemetry and counters — use same import path as adapter.py
|
|
from archivar.routing_telemetry import routing_telemetry
|
|
from archivar.routing_counter import routing_counter
|
|
routing_telemetry.clear()
|
|
routing_telemetry._enabled = True
|
|
routing_counter.reset()
|
|
|
|
def test_telemetry_stage_llm_decision_stay_red_flag(self):
|
|
"""Telemetrie: stage=llm, decision=stay, red_flag_triggered.
|
|
|
|
Mocked classify_and_route returns Red Flag decision.
|
|
Verifies that the Red Flag path produces correct telemetry counters.
|
|
"""
|
|
# Use same import path as adapter.py (archivar.*, not plugin.archivar.*)
|
|
from archivar.routing_telemetry import routing_telemetry
|
|
from archivar.routing_counter import routing_counter
|
|
from plugin.archivar.router import RoutingDecision
|
|
|
|
# Set up sticky session preference
|
|
self.adapter._session_room_preferences["room_bat_team"] = {
|
|
"target_room": "room_rc_plugin",
|
|
"target_name": "#Rocketchat-Plugin",
|
|
"sticky_topic": "rocketchat-plugin",
|
|
"expires_at": time.time() + 1800,
|
|
}
|
|
|
|
# Mock classify_and_route to return a Red Flag decision
|
|
red_flag_decision = RoutingDecision(
|
|
category="direct_question",
|
|
target_room="",
|
|
confidence=0.0,
|
|
stay_in_room=True,
|
|
is_red_flag=True,
|
|
red_flag_rooms=["#LAN-Doku", "#BAT-Team"],
|
|
red_flag_prompt="ROUTER UNSICHER: Wähle einen Raum.\n\n"
|
|
"1. #LAN-Doku - LAN Dokumentation\n"
|
|
"2. #BAT-Team - BAT Team Koordination\n\n"
|
|
"Antworte mit: ROOM: <raumname>",
|
|
)
|
|
|
|
async def tracking_classify(text, origin_room_id=""):
|
|
return red_flag_decision
|
|
|
|
self.adapter.archivar.classify_and_route = tracking_classify
|
|
|
|
msg_obj = {
|
|
"_id": "msg_telemetry_001",
|
|
"rid": "room_bat_team",
|
|
"msg": "Generische Frage ohne klares Thema",
|
|
"u": {"username": "testuser"},
|
|
}
|
|
|
|
asyncio.run(self.adapter._process_incoming(msg_obj))
|
|
|
|
# Verify: handle_message was called (flow completed)
|
|
self.adapter.handle_message.assert_called_once()
|
|
|
|
# Verify: Red Flag prompt was injected into chat_topic
|
|
call_args = self.adapter.handle_message.call_args[0]
|
|
event = call_args[0]
|
|
source = getattr(event, 'source', None)
|
|
chat_topic = getattr(source, 'chat_topic', '') if source else ''
|
|
self.assertIn("ROUTER UNSICHER", chat_topic,
|
|
f"Red Flag prompt should be in source.chat_topic, got: {chat_topic[:200]}")
|
|
|
|
# Check red_flag_dispatched counter (set by Pre-Dispatch-Hook)
|
|
counts = routing_counter.get_counts()
|
|
self.assertGreaterEqual(counts.get("red_flag_dispatched", 0), 1,
|
|
f"Expected red_flag_dispatched >= 1, got {counts}")
|
|
|
|
def test_telemetry_red_flag_not_triggered_with_single_room(self):
|
|
"""Telemetrie: Kein Red Flag bei nur 1 Nicht-Catch-All-Raum.
|
|
|
|
Mit nur 1 verfügbarem Raum → kein Red Flag, aber
|
|
classify_and_route wird trotzdem aufgerufen (B2-Fallthrough-Fix).
|
|
"""
|
|
from archivar.routing_counter import routing_counter
|
|
|
|
# Aggressively reset counter (test isolation for full suite)
|
|
routing_counter.reset()
|
|
|
|
# Create a single-room map
|
|
single_tmpdir = tempfile.TemporaryDirectory()
|
|
single_rooms = {
|
|
"room_rc_plugin": {
|
|
"name": "#Rocketchat-Plugin",
|
|
"theme": "Plugin-Entwicklung",
|
|
"description": "Entwicklung des Hermes Rocket.Chat Plugins",
|
|
"keywords_100": ["rocketchat plugin", "rc plugin"],
|
|
"keywords_context": ["adapter", "gateway"],
|
|
"catch_all": False,
|
|
},
|
|
"room_catchall": {
|
|
"name": "#CatchAll",
|
|
"theme": "Catch-all room",
|
|
"keywords_100": [],
|
|
"keywords_context": [],
|
|
"catch_all": True,
|
|
},
|
|
}
|
|
single_data = {
|
|
"version": 5,
|
|
"rooms": single_rooms,
|
|
"excluded_rooms": [],
|
|
"butler_mode": "cognitive",
|
|
"fact_store_path": str(Path(single_tmpdir.name) / "docs"),
|
|
}
|
|
single_map_path = Path(single_tmpdir.name) / "room-map.json"
|
|
with open(single_map_path, "w") as f:
|
|
json.dump(single_data, f)
|
|
|
|
adapter_single, mock_rest_single = _build_mock_adapter(str(single_map_path))
|
|
|
|
adapter_single._session_room_preferences["room_rc_plugin"] = {
|
|
"target_room": "room_catchall",
|
|
"target_name": "#CatchAll",
|
|
"sticky_topic": "catchall",
|
|
"expires_at": time.time() + 1800,
|
|
}
|
|
|
|
msg_obj = {
|
|
"_id": "msg_single_001",
|
|
"rid": "room_rc_plugin",
|
|
"msg": "Generische Frage ohne klares Thema",
|
|
"u": {"username": "testuser"},
|
|
}
|
|
|
|
# Capture baseline before running
|
|
red_flag_before = routing_counter.get_counts().get("red_flag_triggered", 0)
|
|
|
|
asyncio.run(adapter_single._process_incoming(msg_obj))
|
|
|
|
# classify_and_route should have been called (B2 fallthrough)
|
|
# but red_flag_triggered should NOT have increased (only 1 non-catch-all room)
|
|
# Use delta check for test isolation in full suite
|
|
counts_after = routing_counter.get_counts()
|
|
red_flag_after = counts_after.get("red_flag_triggered", 0)
|
|
self.assertEqual(red_flag_after, red_flag_before,
|
|
f"red_flag_triggered should not increase with single room: "
|
|
f"before={red_flag_before}, after={red_flag_after}")
|
|
|
|
single_tmpdir.cleanup()
|
|
|
|
|
|
class TestV843RegressionGate(unittest.TestCase):
|
|
"""V8.4.3: Regression-Gate — bestehende Pfade bleiben intakt.
|
|
|
|
Pflicht-Test (c): Gesamtsuite als Regression-Gate.
|
|
Diese Tests stellen sicher, dass die bestehenden Pfade
|
|
(Sticky greift, DM-Bypass, pending_questions) weiterhin
|
|
korrekt funktionieren.
|
|
"""
|
|
|
|
@classmethod
|
|
def setUpClass(cls):
|
|
cls._tmpdir = tempfile.TemporaryDirectory()
|
|
cls._room_map_path = _make_multi_room_map_json(cls._tmpdir.name)
|
|
|
|
@classmethod
|
|
def tearDownClass(cls):
|
|
cls._tmpdir.cleanup()
|
|
|
|
def setUp(self):
|
|
self.adapter, self.mock_rest = _build_mock_adapter(self._room_map_path)
|
|
|
|
def test_sticky_with_keyword_match_still_routes(self):
|
|
"""Sticky + 100%-Keyword-Match → routet weiterhin direkt (kein Archivar).
|
|
|
|
Regression-Gate: Der erfolgreiche Sticky-Pfad (Thema matcht)
|
|
darf NICHT durch den Fix gebrochen werden.
|
|
"""
|
|
self.adapter._session_room_preferences["room_bat_team"] = {
|
|
"target_room": "room_rc_plugin",
|
|
"target_name": "#Rocketchat-Plugin",
|
|
"sticky_topic": "rocketchat-plugin",
|
|
"expires_at": time.time() + 1800,
|
|
}
|
|
|
|
# Message WITH 100% keyword 'rocketchat plugin'
|
|
msg_obj = {
|
|
"_id": "msg_regression_001",
|
|
"rid": "room_bat_team",
|
|
"msg": "Das rocketchat plugin hat einen Bug",
|
|
"u": {"username": "testuser"},
|
|
}
|
|
|
|
# Track classify_and_route calls
|
|
call_count = [0]
|
|
original = self.adapter.archivar.classify_and_route
|
|
|
|
async def tracking(text, origin_room_id=""):
|
|
call_count[0] += 1
|
|
return await original(text, origin_room_id)
|
|
|
|
self.adapter.archivar.classify_and_route = tracking
|
|
|
|
asyncio.run(self.adapter._process_incoming(msg_obj))
|
|
|
|
# Sticky with keyword match should route directly → NO classify_and_route
|
|
self.assertEqual(call_count[0], 0,
|
|
"classify_and_route should NOT be called when sticky routes directly")
|
|
|
|
# Agent should be dispatched in target room
|
|
self.adapter._dispatch_agent.assert_called_once()
|
|
call_kwargs = self.adapter._dispatch_agent.call_args[1]
|
|
self.assertEqual(call_kwargs["room_id"], "room_rc_plugin",
|
|
"Agent should be dispatched in target room (sticky route)")
|
|
|
|
def test_dm_bypass_still_works(self):
|
|
"""DM-Nachrichten bypassen Archivar weiterhin.
|
|
|
|
Regression-Gate: DM-Bypass darf NICHT durch den Fix gebrochen werden.
|
|
"""
|
|
msg_obj = {
|
|
"_id": "msg_dm_001",
|
|
"rid": "dm_room",
|
|
"msg": "Hallo, ich habe eine Frage",
|
|
"u": {"username": "testuser"},
|
|
}
|
|
|
|
# Add DM room to _room_info
|
|
self.adapter._room_info["dm_room"] = {"name": "testuser", "type": "d"}
|
|
|
|
# Track classify_and_route calls
|
|
call_count = [0]
|
|
original = self.adapter.archivar.classify_and_route
|
|
|
|
async def tracking(text, origin_room_id=""):
|
|
call_count[0] += 1
|
|
return await original(text, origin_room_id)
|
|
|
|
self.adapter.archivar.classify_and_route = tracking
|
|
|
|
asyncio.run(self.adapter._process_incoming(msg_obj))
|
|
|
|
# DM should bypass Archivar → NO classify_and_route
|
|
self.assertEqual(call_count[0], 0,
|
|
"classify_and_route should NOT be called for DM messages")
|
|
|
|
def test_pending_questions_bypass_still_works(self):
|
|
"""Pending-Questions-Bypass funktioniert weiterhin.
|
|
|
|
Regression-Gate: Pending-Questions-Bypass darf NICHT
|
|
durch den Fix gebrochen werden.
|
|
"""
|
|
# Mark room as having pending questions
|
|
self.adapter._rooms_with_pending_questions.add("room_bat_team")
|
|
|
|
msg_obj = {
|
|
"_id": "msg_pending_001",
|
|
"rid": "room_bat_team",
|
|
"msg": "Antwort auf die offene Frage",
|
|
"u": {"username": "testuser"},
|
|
}
|
|
|
|
# Track classify_and_route calls
|
|
call_count = [0]
|
|
original = self.adapter.archivar.classify_and_route
|
|
|
|
async def tracking(text, origin_room_id=""):
|
|
call_count[0] += 1
|
|
return await original(text, origin_room_id)
|
|
|
|
self.adapter.archivar.classify_and_route = tracking
|
|
|
|
asyncio.run(self.adapter._process_incoming(msg_obj))
|
|
|
|
# Pending questions should bypass Archivar → NO classify_and_route
|
|
self.assertEqual(call_count[0], 0,
|
|
"classify_and_route should NOT be called for pending questions")
|
|
|
|
# Room should be removed from pending set
|
|
self.assertNotIn("room_bat_team", self.adapter._rooms_with_pending_questions,
|
|
"Room should be removed from pending questions after processing")
|
|
|
|
def test_no_sticky_no_bypass_calls_classify(self):
|
|
"""Ohne Sticky, ohne Bypass → classify_and_route wird aufgerufen.
|
|
|
|
Regression-Gate: Der normale Pfad (kein Sticky, kein Bypass)
|
|
ruft weiterhin classify_and_route auf.
|
|
"""
|
|
# No sticky, no pending questions, not DM
|
|
msg_obj = {
|
|
"_id": "msg_normal_001",
|
|
"rid": "room_bat_team",
|
|
"msg": "Kannst du mir bei einem Problem helfen?",
|
|
"u": {"username": "testuser"},
|
|
}
|
|
|
|
# Track classify_and_route calls
|
|
call_count = [0]
|
|
original = self.adapter.archivar.classify_and_route
|
|
|
|
async def tracking(text, origin_room_id=""):
|
|
call_count[0] += 1
|
|
return await original(text, origin_room_id)
|
|
|
|
self.adapter.archivar.classify_and_route = tracking
|
|
|
|
asyncio.run(self.adapter._process_incoming(msg_obj))
|
|
|
|
# Normal path should call classify_and_route
|
|
self.assertEqual(call_count[0], 1,
|
|
f"classify_and_route should be called in normal path, got {call_count[0]}")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|