344043b081
Bug 1: _META_PATTERNS Pattern 3 matchte JEDES Vorkommen von 'Archivar', auch in Sachfragen wie 'Was hat der Archivar empfohlen?' → is_meta=True → 100%-Keyword-Match wurde nie geprüft. Fix: Pattern 3 aufgeteilt in zwei bidirektionale Patterns: - 'archivar' + System-Operationsverb (klassifiziert, routet, leitet weiter, arbeitet, funktioniert, macht) — in beiden Richtungen - System-Begriffe ohne 'archivar' (klassifikation, routing, weiterleitung) bleiben eigenständige Meta-Signale Bug 2: Bei stay_in_room=True wurde target_room=catch_all_id (DM) gesetzt statt target_room=origin_room_id. Das leakt in _THEMATIC_TARGET_ROOM → Agent-Prompt bekommt falschen Raum → Agent denkt er sei im DM. Fix: - router.py: Meta-Frage target_room=origin_room_id statt catch_all_id - adapter.py: _THEMATIC_TARGET_ROOM nur setzen wenn NICHT stay_in_room Tests: 16 neue Tests (TestMetaPatternsP0 + TestTargetRoomStayInRoomP0) - 26/26 test_router.py PASS - 32/32 test_v7_4_recursive.py PASS - 192/193 full suite PASS (1 pre-existing env-var failure)
524 lines
20 KiB
Python
524 lines
20 KiB
Python
"""
|
|
Integration tests für den Router.
|
|
|
|
Prüft:
|
|
- Embedding-basiertes Routing
|
|
- LLM-basiertes Fallback-Routing (simuliert)
|
|
- Integration mit room-map.json
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import asyncio
|
|
import json
|
|
import tempfile
|
|
from pathlib import Path
|
|
from typing import List, Optional
|
|
from unittest.mock import AsyncMock, MagicMock
|
|
|
|
import pytest
|
|
|
|
# Ensure the archivar package is importable
|
|
import sys
|
|
sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
|
|
|
|
from plugin.archivar.router import BidirectionalRouter
|
|
from plugin.archivar.room_map import RoomMap
|
|
from plugin.archivar.classifier import IntentClassifier, EmbeddingClient
|
|
from plugin.archivar.archivar_state import ArchivarState
|
|
|
|
|
|
# ── Mocks ──────────────────────────────────────────────────────────────────
|
|
|
|
|
|
class MockEmbeddingClient(EmbeddingClient):
|
|
"""Mock embedding client for testing."""
|
|
|
|
def get_embedding(self, text: str) -> Optional[List[float]]:
|
|
# Return a fixed embedding vector for testing
|
|
# In a real implementation, this would call an embedding API
|
|
return [0.1] * 768 # nomic-embed-text produces 768-dimensional vectors
|
|
|
|
|
|
# ── Helpers ────────────────────────────────────────────────────────────────
|
|
|
|
|
|
def _make_map_json(rooms: list[dict] | None = None, excluded: list[str] | None = None) -> str:
|
|
"""Create a minimal valid room-map.json as a string."""
|
|
data: dict = {
|
|
"version": 1,
|
|
"rooms": {},
|
|
"excluded_rooms": excluded or [],
|
|
"fact_store_path": "/tmp/test_docs",
|
|
}
|
|
for room in (rooms or []):
|
|
data["rooms"][room["room_id"]] = {
|
|
"name": room["name"],
|
|
"theme": room.get("theme", ""),
|
|
"keywords": room.get("keywords", []),
|
|
"catch_all": room.get("catch_all", False),
|
|
}
|
|
return json.dumps(data)
|
|
|
|
|
|
def _tmp_map(content: str) -> Path:
|
|
"""Write content to a temp file and return its Path."""
|
|
tmp = tempfile.NamedTemporaryFile(mode="w", suffix=".json", delete=False, encoding="utf-8")
|
|
tmp.write(content)
|
|
tmp.close()
|
|
return Path(tmp.name)
|
|
|
|
|
|
# ── Integration Tests ──────────────────────────────────────────────────────
|
|
|
|
|
|
class TestRouterIntegration:
|
|
"""MessageRouter integration tests."""
|
|
|
|
@pytest.fixture
|
|
def router(self) -> BidirectionalRouter:
|
|
# Create a room map for testing
|
|
json_str = _make_map_json(
|
|
rooms=[
|
|
{"room_id": "r1", "name": "#Plugin", "theme": "plugin dev", "keywords": ["plugin", "adapter", "gateway"]},
|
|
{"room_id": "r2", "name": "#BAT", "theme": "trading", "keywords": ["bat", "trading", "docker"]},
|
|
{"room_id": "r3", "name": "DM Admin", "theme": "admin", "keywords": [], "catch_all": True},
|
|
],
|
|
)
|
|
path = _tmp_map(json_str)
|
|
|
|
try:
|
|
room_map = RoomMap.load(path)
|
|
# Create a mock classifier
|
|
mock_client = MockEmbeddingClient()
|
|
classifier = IntentClassifier(embedding_client=mock_client)
|
|
state = ArchivarState()
|
|
router = BidirectionalRouter(room_map, classifier, state)
|
|
return router
|
|
finally:
|
|
path.unlink(missing_ok=True)
|
|
|
|
def test_route_to_plugin_room(self, router):
|
|
"""Embedding-basiertes Routing sollte Plugin-Nachrichten an #Plugin senden."""
|
|
message = "Wie implementiere ich einen neuen Plugin-Adapter für Rocket.Chat?"
|
|
|
|
# For this test, we're checking that the router can be instantiated and used
|
|
# The actual routing logic is tested in room_map tests
|
|
assert router is not None
|
|
assert router._room_map is not None
|
|
|
|
def test_route_to_bat_room(self, router):
|
|
"""Embedding-basiertes Routing sollte Trading-Nachrichten an #BAT senden."""
|
|
message = "Wie funktioniert das BAT Trading-Signal und wie kann ich es optimieren?"
|
|
|
|
# For this test, we're checking that the router can be instantiated and used
|
|
# The actual routing logic is tested in room_map tests
|
|
assert router is not None
|
|
assert router._room_map is not None
|
|
|
|
|
|
# ── V7-2: Thematisches never_route ────────────────────────────────────────
|
|
|
|
|
|
class TestNeverRouteThematic:
|
|
"""V7-2: never_route ist thematisch, nicht räumlich.
|
|
|
|
Ein never_route für 'lan-dokumentation' blockt NICHT 'protonbridge'
|
|
im selben Raum. Der Butler darf bei einem anderen Thema wieder fragen.
|
|
"""
|
|
|
|
@pytest.fixture
|
|
def state(self) -> ArchivarState:
|
|
"""ArchivarState mit v7 never_route Schema."""
|
|
s = ArchivarState()
|
|
s._loaded = True # Skip file I/O
|
|
return s
|
|
|
|
def test_never_route_topic_blocks_same_topic(self, state):
|
|
"""never_route für 'lan-dokumentation' blockt 'lan-dokumentation'."""
|
|
room_id = "test_room_123"
|
|
state.set_never_route(room_id, "lan-dokumentation")
|
|
|
|
# Gleiches Thema → blockiert
|
|
assert state.is_never_route(room_id, "lan-dokumentation") is True
|
|
|
|
def test_never_route_topic_allows_different_topic(self, state):
|
|
"""never_route für 'lan-dokumentation' blockt NICHT 'protonbridge'."""
|
|
room_id = "test_room_123"
|
|
state.set_never_route(room_id, "lan-dokumentation")
|
|
|
|
# Anderes Thema → nicht blockiert
|
|
assert state.is_never_route(room_id, "protonbridge") is False
|
|
|
|
def test_never_route_topic_allows_unknown_topic(self, state):
|
|
"""never_route für 'lan-dokumentation' blockt NICHT None/leer."""
|
|
room_id = "test_room_123"
|
|
state.set_never_route(room_id, "lan-dokumentation")
|
|
|
|
# Kein Thema → nicht blockiert (Butler darf fragen)
|
|
assert state.is_never_route(room_id, None) is False
|
|
|
|
def test_never_route_multiple_topics_same_room(self, state):
|
|
"""Mehrere Themen im selben Raum: jedes unabhängig."""
|
|
room_id = "test_room_123"
|
|
state.set_never_route(room_id, "lan-dokumentation")
|
|
state.set_never_route(room_id, "devops")
|
|
|
|
# Beide gesetzten Themen blockiert
|
|
assert state.is_never_route(room_id, "lan-dokumentation") is True
|
|
assert state.is_never_route(room_id, "devops") is True
|
|
|
|
# Anderes Thema nicht blockiert
|
|
assert state.is_never_route(room_id, "protonbridge") is False
|
|
|
|
def test_never_route_different_room_not_affected(self, state):
|
|
"""never_route in Raum A betrifft Raum B nicht."""
|
|
state.set_never_route("room_a", "lan-dokumentation")
|
|
|
|
# Gleiches Thema in anderem Raum → nicht blockiert
|
|
assert state.is_never_route("room_b", "lan-dokumentation") is False
|
|
|
|
def test_router_check_never_route_topic_blocks_matched_room(self):
|
|
"""Router._check_never_route_topic blockt wenn Thema in never_route."""
|
|
json_str = _make_map_json(
|
|
rooms=[
|
|
{"room_id": "r_lan", "name": "#LAN-Dokumentation",
|
|
"theme": "lan docs", "keywords": ["lan", "dokumentation", "netzwerk"]},
|
|
{"room_id": "r_proton", "name": "#ProtonBridge",
|
|
"theme": "proton mail bridge", "keywords": ["protonbridge", "protonmail", "bridge"]},
|
|
{"room_id": "r_admin", "name": "DM Admin",
|
|
"theme": "admin", "keywords": [], "catch_all": True},
|
|
],
|
|
)
|
|
path = _tmp_map(json_str)
|
|
try:
|
|
room_map = RoomMap.load(path)
|
|
state = ArchivarState()
|
|
state._loaded = True
|
|
|
|
# Setze never_route für 'lan-dokumentation' im Ursprungsraum
|
|
origin_room = "r_proton" # User ist im #ProtonBridge-Raum
|
|
state.set_never_route(origin_room, "lan-dokumentation")
|
|
|
|
router = BidirectionalRouter(room_map, None, state) # type: ignore
|
|
|
|
# Nachricht matcht #LAN-Dokumentation → sollte geblockt werden
|
|
lan_room = room_map.get_room_by_id("r_lan")
|
|
assert lan_room is not None
|
|
blocked = router._check_never_route_topic(origin_room, lan_room)
|
|
assert blocked is True, (
|
|
"never_route für 'lan-dokumentation' sollte LAN-Match blocken"
|
|
)
|
|
finally:
|
|
path.unlink(missing_ok=True)
|
|
|
|
def test_router_check_never_route_topic_allows_other_topic(self):
|
|
"""Router._check_never_route_topic erlaubt anderes Thema im selben Raum."""
|
|
json_str = _make_map_json(
|
|
rooms=[
|
|
{"room_id": "r_lan", "name": "#LAN-Dokumentation",
|
|
"theme": "lan docs", "keywords": ["lan", "dokumentation", "netzwerk"]},
|
|
{"room_id": "r_proton", "name": "#ProtonBridge",
|
|
"theme": "proton mail bridge", "keywords": ["protonbridge", "protonmail", "bridge"]},
|
|
{"room_id": "r_admin", "name": "DM Admin",
|
|
"theme": "admin", "keywords": [], "catch_all": True},
|
|
],
|
|
)
|
|
path = _tmp_map(json_str)
|
|
try:
|
|
room_map = RoomMap.load(path)
|
|
state = ArchivarState()
|
|
state._loaded = True
|
|
|
|
# Setze never_route für 'lan-dokumentation' im Ursprungsraum
|
|
origin_room = "r_proton"
|
|
state.set_never_route(origin_room, "lan-dokumentation")
|
|
|
|
router = BidirectionalRouter(room_map, None, state) # type: ignore
|
|
|
|
# Nachricht matcht #ProtonBridge (anderes Thema) → NICHT geblockt
|
|
proton_room = room_map.get_room_by_id("r_proton")
|
|
assert proton_room is not None
|
|
blocked = router._check_never_route_topic(origin_room, proton_room)
|
|
assert blocked is False, (
|
|
"never_route für 'lan-dokumentation' sollte ProtonBridge-Match "
|
|
"NICHT blocken — anderes Thema!"
|
|
)
|
|
finally:
|
|
path.unlink(missing_ok=True)
|
|
|
|
def test_room_name_to_topic_conversion(self):
|
|
"""room_name_to_topic konvertiert Raum-Namen korrekt."""
|
|
from plugin.archivar.router import room_name_to_topic
|
|
|
|
assert room_name_to_topic("#LAN-Dokumentation") == "lan-dokumentation"
|
|
assert room_name_to_topic("LAN-Dokumentation") == "lan-dokumentation"
|
|
assert room_name_to_topic("#ProtonBridge") == "protonbridge"
|
|
assert room_name_to_topic("#DevOps") == "devops"
|
|
# _room_name_to_topic stripped nur '#', nicht Whitespace
|
|
assert room_name_to_topic("Mein Raum") == "mein-raum"
|
|
|
|
|
|
# ── P0-BUGFIX: Meta-Patterns restriktiver ──────────────────────────────────
|
|
|
|
|
|
class TestMetaPatternsP0:
|
|
"""P0-BUGFIX: _META_PATTERNS dürfen nicht zu breit matchen.
|
|
|
|
Bug: Pattern 3 matchte JEDES Vorkommen von 'Archivar', auch in
|
|
Sachfragen wie 'Was hat der Archivar empfohlen?' → is_meta=True →
|
|
100%-Keyword-Match wurde nie geprüft.
|
|
|
|
Fix: 'archivar' nur in Kombination mit System-Operationsverben
|
|
(klassifiziert, routet, leitet weiter, arbeitet, funktioniert, macht).
|
|
"""
|
|
|
|
def test_archivar_allein_kein_meta(self):
|
|
"""'Archivar' als Fachbegriff in Sachfrage → KEIN Meta-Match."""
|
|
from plugin.archivar.router import BidirectionalRouter
|
|
|
|
# Der ursprüngliche Bug-Fall
|
|
assert not BidirectionalRouter._is_meta_question(
|
|
"Was hat der Archivar aufgrund des Keywords Rocketchat empfohlen?"
|
|
)
|
|
|
|
def test_archivar_mit_verb_ist_meta(self):
|
|
"""'Archivar klassifiziert' → Meta-Match."""
|
|
from plugin.archivar.router import BidirectionalRouter
|
|
|
|
assert BidirectionalRouter._is_meta_question(
|
|
"Wie klassifiziert der Archivar meine Nachricht?"
|
|
)
|
|
|
|
def test_archivar_routet_ist_meta(self):
|
|
"""'Archivar routet' → Meta-Match."""
|
|
from plugin.archivar.router import BidirectionalRouter
|
|
|
|
assert BidirectionalRouter._is_meta_question(
|
|
"Wohin routet der Archivar diese Frage?"
|
|
)
|
|
|
|
def test_archivar_funktioniert_ist_meta(self):
|
|
"""'Archivar funktioniert' → Meta-Match."""
|
|
from plugin.archivar.router import BidirectionalRouter
|
|
|
|
assert BidirectionalRouter._is_meta_question(
|
|
"Wie funktioniert der Archivar?"
|
|
)
|
|
|
|
def test_archivar_empfohlen_kein_meta(self):
|
|
"""'Archivar hat empfohlen' → KEIN Meta-Match (Sachfrage)."""
|
|
from plugin.archivar.router import BidirectionalRouter
|
|
|
|
assert not BidirectionalRouter._is_meta_question(
|
|
"Der Archivar hat empfohlen, das so zu machen"
|
|
)
|
|
|
|
def test_archivar_gesagt_kein_meta(self):
|
|
"""'Archivar hat gesagt' → KEIN Meta-Match (Sachfrage)."""
|
|
from plugin.archivar.router import BidirectionalRouter
|
|
|
|
assert not BidirectionalRouter._is_meta_question(
|
|
"Der Archivar hat gesagt, ich soll das hier dokumentieren"
|
|
)
|
|
|
|
def test_klassifikation_allein_ist_meta(self):
|
|
"""'Klassifikation' ohne 'archivar' → Meta-Match (eigenständiges Signal)."""
|
|
from plugin.archivar.router import BidirectionalRouter
|
|
|
|
assert BidirectionalRouter._is_meta_question(
|
|
"Warum wurde meine Nachricht so klassifiziert?"
|
|
)
|
|
|
|
def test_routing_allein_ist_meta(self):
|
|
"""'Routing' ohne 'archivar' → Meta-Match."""
|
|
from plugin.archivar.router import BidirectionalRouter
|
|
|
|
assert BidirectionalRouter._is_meta_question(
|
|
"Wie funktioniert das Routing hier?"
|
|
)
|
|
|
|
def test_weiterleitung_allein_ist_meta(self):
|
|
"""'Weiterleitung' ohne 'archivar' → Meta-Match."""
|
|
from plugin.archivar.router import BidirectionalRouter
|
|
|
|
assert BidirectionalRouter._is_meta_question(
|
|
"Kann ich die Weiterleitung beeinflussen?"
|
|
)
|
|
|
|
def test_wohin_wurde_ist_meta(self):
|
|
"""'Wohin wurde' → Meta-Match (Pattern 1)."""
|
|
from plugin.archivar.router import BidirectionalRouter
|
|
|
|
assert BidirectionalRouter._is_meta_question(
|
|
"Wohin wurde meine letzte Nachricht geroutet?"
|
|
)
|
|
|
|
def test_warum_ist_meine_nachricht_ist_meta(self):
|
|
"""'Warum ist meine Nachricht' → Meta-Match (Pattern 2)."""
|
|
from plugin.archivar.router import BidirectionalRouter
|
|
|
|
assert BidirectionalRouter._is_meta_question(
|
|
"Warum ist meine Nachricht im falschen Raum gelandet?"
|
|
)
|
|
|
|
def test_normale_frage_kein_meta(self):
|
|
"""Normale Sachfrage ohne System-Bezug → KEIN Meta-Match."""
|
|
from plugin.archivar.router import BidirectionalRouter
|
|
|
|
assert not BidirectionalRouter._is_meta_question(
|
|
"Wie konfiguriere ich den NGINX für HTTPS?"
|
|
)
|
|
|
|
def test_keyword_rocketchat_kein_meta(self):
|
|
"""Frage mit Keyword 'Rocketchat' → KEIN Meta-Match."""
|
|
from plugin.archivar.router import BidirectionalRouter
|
|
|
|
assert not BidirectionalRouter._is_meta_question(
|
|
"Was hat der Archivar aufgrund des Keywords Rocketchat empfohlen?"
|
|
)
|
|
|
|
|
|
# ── P0-BUGFIX: target_room bei stay_in_room ─────────────────────────────────
|
|
|
|
|
|
class TestTargetRoomStayInRoomP0:
|
|
"""P0-BUGFIX: target_room=origin_room_id bei stay_in_room=True.
|
|
|
|
Bug: Bei stay_in_room=True wurde target_room=catch_all_id (DM) gesetzt.
|
|
Das leakt in _THEMATIC_TARGET_ROOM → Agent-Prompt bekommt falschen Raum
|
|
→ Agent denkt er sei im DM.
|
|
|
|
Fix: target_room=origin_room_id bei stay_in_room=True.
|
|
Adapter-Guard: _THEMATIC_TARGET_ROOM nur setzen wenn NICHT stay_in_room.
|
|
"""
|
|
|
|
def test_meta_question_target_room_is_origin(self):
|
|
"""Meta-Frage: target_room muss origin_room_id sein, nicht catch_all."""
|
|
import json
|
|
import tempfile
|
|
from pathlib import Path
|
|
|
|
json_str = _make_map_json(
|
|
rooms=[
|
|
{"room_id": "r_plugin", "name": "#Plugin",
|
|
"theme": "plugin dev", "keywords": ["plugin", "adapter"]},
|
|
{"room_id": "r_admin", "name": "DM Admin",
|
|
"theme": "admin", "keywords": [], "catch_all": True},
|
|
],
|
|
)
|
|
path = _tmp_map(json_str)
|
|
try:
|
|
from plugin.archivar.room_map import RoomMap
|
|
from plugin.archivar.archivar_state import ArchivarState
|
|
|
|
room_map = RoomMap.load(path)
|
|
state = ArchivarState()
|
|
state._loaded = True
|
|
|
|
router = BidirectionalRouter(room_map, None, state) # type: ignore
|
|
|
|
# Meta-Frage aus dem Plugin-Raum
|
|
decision = asyncio.run(
|
|
router.route(
|
|
"Wie funktioniert der Archivar?",
|
|
origin_room_id="r_plugin",
|
|
)
|
|
)
|
|
|
|
assert decision.is_meta, "Sollte als Meta-Frage erkannt werden"
|
|
assert decision.stay_in_room, "Meta-Fragen sollen stay_in_room sein"
|
|
assert decision.target_room == "r_plugin", (
|
|
f"target_room sollte origin_room_id='r_plugin' sein, "
|
|
f"nicht catch_all_id='{decision.target_room}'"
|
|
)
|
|
finally:
|
|
path.unlink(missing_ok=True)
|
|
|
|
def test_smalltalk_target_room_empty(self):
|
|
"""Smalltalk: target_room bleibt '' (kein Routing)."""
|
|
import json
|
|
import tempfile
|
|
from pathlib import Path
|
|
|
|
json_str = _make_map_json(
|
|
rooms=[
|
|
{"room_id": "r_plugin", "name": "#Plugin",
|
|
"theme": "plugin dev", "keywords": ["plugin"]},
|
|
{"room_id": "r_admin", "name": "DM Admin",
|
|
"theme": "admin", "keywords": [], "catch_all": True},
|
|
],
|
|
)
|
|
path = _tmp_map(json_str)
|
|
try:
|
|
from plugin.archivar.room_map import RoomMap
|
|
from plugin.archivar.archivar_state import ArchivarState
|
|
|
|
room_map = RoomMap.load(path)
|
|
state = ArchivarState()
|
|
state._loaded = True
|
|
|
|
# Mock classifier needed — router crashes with None
|
|
mock_classifier = MagicMock()
|
|
mock_classifier.is_initialized = True
|
|
mock_classifier.classify = AsyncMock(return_value=None)
|
|
mock_classifier._llm_raw = AsyncMock(return_value="STAY")
|
|
|
|
router = BidirectionalRouter(room_map, mock_classifier, state)
|
|
|
|
# Smalltalk aus dem Plugin-Raum
|
|
decision = asyncio.run(
|
|
router.route(
|
|
"Hallo, wie geht's?",
|
|
origin_room_id="r_plugin",
|
|
)
|
|
)
|
|
|
|
assert decision.stay_in_room, "Smalltalk soll stay_in_room sein"
|
|
# target_room ist '' bei Smalltalk (kein Routing-Ziel)
|
|
assert decision.target_room == "", (
|
|
f"Smalltalk target_room sollte '' sein, nicht '{decision.target_room}'"
|
|
)
|
|
finally:
|
|
path.unlink(missing_ok=True)
|
|
|
|
def test_archivar_sachfrage_nicht_meta(self):
|
|
"""'Was hat der Archivar empfohlen?' → KEIN Meta, normaler Flow."""
|
|
import json
|
|
import tempfile
|
|
from pathlib import Path
|
|
|
|
json_str = _make_map_json(
|
|
rooms=[
|
|
{"room_id": "r_plugin", "name": "#Plugin",
|
|
"theme": "plugin dev", "keywords": ["plugin", "adapter", "rocketchat"]},
|
|
{"room_id": "r_admin", "name": "DM Admin",
|
|
"theme": "admin", "keywords": [], "catch_all": True},
|
|
],
|
|
)
|
|
path = _tmp_map(json_str)
|
|
try:
|
|
from plugin.archivar.room_map import RoomMap
|
|
from plugin.archivar.archivar_state import ArchivarState
|
|
|
|
room_map = RoomMap.load(path)
|
|
state = ArchivarState()
|
|
state._loaded = True
|
|
|
|
router = BidirectionalRouter(room_map, None, state) # type: ignore
|
|
|
|
# Sachfrage mit 'Archivar' als Fachbegriff
|
|
decision = asyncio.run(
|
|
router.route(
|
|
"Was hat der Archivar aufgrund des Keywords Rocketchat empfohlen?",
|
|
origin_room_id="r_plugin",
|
|
)
|
|
)
|
|
|
|
# Darf NICHT is_meta sein
|
|
assert not decision.is_meta, (
|
|
"Sachfrage mit 'Archivar' als Fachbegriff darf NICHT "
|
|
"als Meta-Frage erkannt werden"
|
|
)
|
|
finally:
|
|
path.unlink(missing_ok=True) |