463e29d594
Problem 1 (P0): Kontext-Keywords bei Catch-All-Räumen - 'dji' ist ein Kontext-Keyword für DM (catch_all=True), aber Catch-All-Räume wurden von der Keyword-Match-Logik komplett ausgeschlossen. - Fix: room_map.py find_room_by_keywords() erlaubt Catch-All-Räume in Stufe 2+3 (Kontext-Keywords) als Butler-Ziele. Stufe 1 (100%-Keywords) schließt Catch-All weiterhin aus — 100%-Match auf Catch-All ist für Auto-Route, nicht für Keyword-Match. - min_score von 2 auf 1 gesenkt: ein einzelnes Kontext-Keyword reicht für einen Butler-Vorschlag. Problem 2 (P0): FAISS schließt Ursprungsraum nicht aus - FAISS fand den Ursprungsraum als ähnlichsten Raum (score=0.62, target=#RC-Plugin, origin=#RC-Plugin). Sinnlos — Butler kann keinen Wechsel von #RC-Plugin → #RC-Plugin vorschlagen. - Fix: router.py filtert origin_room_id aus FAISS-Ergebnissen heraus. Wenn alle Treffer der Ursprungsraum waren → fall-through zu LLM. Wenn top-1 excluded wird → top-2 wird verwendet. Tests: 14 neue Tests in test_v8_4_6.py - test_faiss_excludes_origin (2 Tests) - test_faiss_butler_self_match (2 Tests) - test_context_keyword_min_score_1 (3 Tests) - test_context_keyword_catch_all (3 Tests) - Regression (4 Tests) Aktualisierte Tests: - test_room_map.py: test_context_keywords_min_score → min_score=1 - test_v8_4_5.py: test_sony_context_keyword_triggers_butler → erwartet Butler Full suite: 626 passed, 2 skipped, 0 failures
473 lines
17 KiB
Python
473 lines
17 KiB
Python
"""
|
|
V8.4.6: FAISS schließt Ursprungsraum aus + Kontext-Keyword bei Catch-Butler (P0-Bundle).
|
|
|
|
Tests:
|
|
1. test_faiss_excludes_origin: FAISS search filters out origin room
|
|
2. test_faiss_butler_self_match: top_score < FAISS_AUTO_ROUTE but top_room == origin → stay
|
|
3. test_context_keyword_min_score_1: 'dji' matches DM room with min_score=1
|
|
4. test_context_keyword_catch_all: 'dji' in #RC-Plugin → context_keyword butler to DM
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import asyncio
|
|
import json
|
|
import logging
|
|
import sys
|
|
import tempfile
|
|
from pathlib import Path
|
|
from typing import Optional
|
|
from unittest.mock import patch, MagicMock
|
|
|
|
import pytest
|
|
|
|
sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
|
|
|
|
from plugin.archivar.router import BidirectionalRouter, RoutingDecision
|
|
from plugin.archivar.room_map import RoomMap, RoomEntry
|
|
from plugin.archivar.classifier import IntentClassifier, EmbeddingClient
|
|
from plugin.archivar.archivar_state import ArchivarState
|
|
from plugin.archivar.routing_telemetry import routing_telemetry
|
|
from plugin.archivar.routing_counter import routing_counter
|
|
|
|
|
|
# ── Helpers ────────────────────────────────────────────────────────────────
|
|
|
|
|
|
class MockEmbeddingClient(EmbeddingClient):
|
|
"""Mock embedding client that returns fixed vectors."""
|
|
|
|
def get_embedding(self, text: str) -> Optional[list]:
|
|
return [0.1] * 768
|
|
|
|
|
|
def _make_room_map_with_dji() -> RoomMap:
|
|
"""Build a RoomMap with 2 non-catch-all rooms + 1 catch-all (DM with dji keyword)."""
|
|
tmp = tempfile.TemporaryDirectory()
|
|
map_path = Path(tmp.name) / "room-map.json"
|
|
|
|
test_data = {
|
|
"version": 5,
|
|
"rooms": {
|
|
"room_rc_plugin": {
|
|
"name": "#RC-Plugin",
|
|
"theme": "Rocket.Chat Plugin Entwicklung",
|
|
"description": "Entwicklung des Hermes Rocket.Chat Plugins",
|
|
"keywords_100": ["plugin", "rocketchat"],
|
|
"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_dm_andreas": {
|
|
"name": "DM mit Andreas",
|
|
"theme": "Direktnachrichten — Strategie, Meta-Entscheidungen",
|
|
"description": "Catch-All für alle Themen ohne eigenen Raum",
|
|
"keywords_100": ["strategie", "entscheidung"],
|
|
"keywords_context": ["meta", "roadmap", "dji"],
|
|
"catch_all": True,
|
|
},
|
|
},
|
|
}
|
|
|
|
with open(map_path, "w") as f:
|
|
json.dump(test_data, f)
|
|
|
|
return RoomMap.load(map_path)
|
|
|
|
|
|
def _make_router(room_map: RoomMap, mock_llm_fn=None) -> BidirectionalRouter:
|
|
"""Build a BidirectionalRouter with mock classifier and state."""
|
|
classifier = IntentClassifier(
|
|
embedding_client=MockEmbeddingClient(),
|
|
llm_client=None,
|
|
)
|
|
|
|
if mock_llm_fn is not None:
|
|
classifier._llm_raw = mock_llm_fn
|
|
|
|
state = ArchivarState(":memory:")
|
|
state.load()
|
|
|
|
router = BidirectionalRouter(room_map, classifier, state)
|
|
router.set_subscribed_room_ids(list(room_map.rooms.keys()))
|
|
return router
|
|
|
|
|
|
# ── Test 1: FAISS schließt Ursprungsraum aus ────────────────────────────────
|
|
|
|
|
|
class TestFaissExcludesOrigin:
|
|
"""FAISS search filters out the origin room from results."""
|
|
|
|
def test_faiss_search_excludes_origin_room(self):
|
|
"""room_index.search() filters out origin_room_id from hits."""
|
|
# This tests the RoomIndexManager.search() method directly
|
|
# We mock FAISS to return origin room as top-1, then verify
|
|
# the router filters it out.
|
|
room_map = _make_room_map_with_dji()
|
|
|
|
# Build a mock FAISS index that returns origin as top-1
|
|
mock_index = MagicMock()
|
|
mock_index.is_built = True
|
|
mock_index.search_text = MagicMock(return_value=[
|
|
("room_rc_plugin", 0.62), # origin room as top-1
|
|
("room_lan_doku", 0.45),
|
|
])
|
|
|
|
async def mock_llm_stay(prompt: str) -> str:
|
|
return "STAY"
|
|
|
|
router = _make_router(room_map, mock_llm_stay)
|
|
router._room_index = mock_index
|
|
router._booster = None # No booster to keep it simple
|
|
|
|
decision = asyncio.run(router.route(
|
|
"Das Plugin hat einen Bug",
|
|
origin_room_id="room_rc_plugin",
|
|
))
|
|
|
|
# FAISS top-1 is origin room → should be excluded
|
|
# Since score 0.62 < FAISS_AUTO_ROUTE (0.85), it would be butler
|
|
# But origin room is excluded → fall through to LLM → STAY
|
|
assert decision.stay_in_room is True, (
|
|
f"FAISS self-match should result in stay_in_room, "
|
|
f"got stay_in_room={decision.stay_in_room}"
|
|
)
|
|
assert decision.move_request_sent is False, (
|
|
"FAISS self-match should not send move request"
|
|
)
|
|
|
|
def test_faiss_origin_excluded_top2_used(self):
|
|
"""When FAISS top-1 is origin, top-2 is used for routing."""
|
|
room_map = _make_room_map_with_dji()
|
|
|
|
mock_index = MagicMock()
|
|
mock_index.is_built = True
|
|
mock_index.search_text = MagicMock(return_value=[
|
|
("room_rc_plugin", 0.92), # origin room as top-1 (high score!)
|
|
("room_lan_doku", 0.88), # top-2 also above FAISS_AUTO_ROUTE
|
|
])
|
|
|
|
async def mock_llm_stay(prompt: str) -> str:
|
|
return "STAY"
|
|
|
|
router = _make_router(room_map, mock_llm_stay)
|
|
router._room_index = mock_index
|
|
router._booster = None
|
|
|
|
# Use text that does NOT match any keywords (so it reaches FAISS)
|
|
decision = asyncio.run(router.route(
|
|
"I need help with the server configuration for the new project",
|
|
origin_room_id="room_rc_plugin",
|
|
))
|
|
|
|
# FAISS top-1 is origin (excluded), top-2 is #LAN-Doku with score 0.88
|
|
# 0.88 >= FAISS_AUTO_ROUTE (0.85) → auto-route to #LAN-Doku
|
|
assert decision.target_room == "room_lan_doku", (
|
|
f"Expected target_room='room_lan_doku' (top-2 after origin exclusion), "
|
|
f"got {decision.target_room}"
|
|
)
|
|
assert decision.move_request_sent is False, (
|
|
"FAISS auto-route should not send move request"
|
|
)
|
|
assert decision.is_faiss_routed is True, (
|
|
"Should be marked as FAISS-routed"
|
|
)
|
|
|
|
|
|
# ── Test 2: FAISS Butler Self-Match → stay ─────────────────────────────────
|
|
|
|
|
|
class TestFaissButlerSelfMatch:
|
|
"""When FAISS top-1 is origin and score < FAISS_AUTO_ROUTE → stay."""
|
|
|
|
def test_faiss_butler_self_match_stays(self):
|
|
"""top_score < FAISS_AUTO_ROUTE and top_room == origin → stay, no butler."""
|
|
room_map = _make_room_map_with_dji()
|
|
|
|
mock_index = MagicMock()
|
|
mock_index.is_built = True
|
|
mock_index.search_text = MagicMock(return_value=[
|
|
("room_rc_plugin", 0.62), # origin room, below auto-route threshold
|
|
("room_lan_doku", 0.45),
|
|
])
|
|
|
|
async def mock_llm_stay(prompt: str) -> str:
|
|
return "STAY"
|
|
|
|
router = _make_router(room_map, mock_llm_stay)
|
|
router._room_index = mock_index
|
|
router._booster = None
|
|
|
|
decision = asyncio.run(router.route(
|
|
"Das Plugin hat einen Bug",
|
|
origin_room_id="room_rc_plugin",
|
|
))
|
|
|
|
# FAISS top-1 is origin (excluded), score < FAISS_AUTO_ROUTE
|
|
# → should fall through to LLM → STAY
|
|
assert decision.stay_in_room is True, (
|
|
f"FAISS butler self-match should stay, got stay_in_room={decision.stay_in_room}"
|
|
)
|
|
assert decision.move_request_sent is False, (
|
|
"FAISS butler self-match should not send move request"
|
|
)
|
|
# Should NOT be marked as faiss_routed
|
|
assert decision.is_faiss_routed is False, (
|
|
"Self-match should not be marked as faiss_routed"
|
|
)
|
|
|
|
def test_faiss_only_origin_in_results_stays(self):
|
|
"""When FAISS only returns origin room → stay."""
|
|
room_map = _make_room_map_with_dji()
|
|
|
|
mock_index = MagicMock()
|
|
mock_index.is_built = True
|
|
mock_index.search_text = MagicMock(return_value=[
|
|
("room_rc_plugin", 0.75), # only origin room in results
|
|
])
|
|
|
|
async def mock_llm_stay(prompt: str) -> str:
|
|
return "STAY"
|
|
|
|
router = _make_router(room_map, mock_llm_stay)
|
|
router._room_index = mock_index
|
|
router._booster = None
|
|
|
|
decision = asyncio.run(router.route(
|
|
"Plugin Entwicklung",
|
|
origin_room_id="room_rc_plugin",
|
|
))
|
|
|
|
assert decision.stay_in_room is True, (
|
|
"Only origin in FAISS results → should stay"
|
|
)
|
|
|
|
|
|
# ── Test 3: Kontext-Keyword min_score=1 ─────────────────────────────────────
|
|
|
|
|
|
class TestContextKeywordMinScore1:
|
|
"""find_room_by_keywords returns match with context_score >= 1."""
|
|
|
|
def test_dji_context_keyword_matches_dm_room(self):
|
|
"""'dji' in text → find_room_by_keywords returns DM room (min_score=1)."""
|
|
room_map = _make_room_map_with_dji()
|
|
|
|
# 'dji' is a context keyword for DM mit Andreas (catch-all)
|
|
# With the fix, catch-all rooms should be matchable via context keywords
|
|
matched = room_map.find_room_by_keywords(
|
|
"dji Drohne",
|
|
origin_room_id="room_rc_plugin",
|
|
)
|
|
|
|
assert matched is not None, (
|
|
"Expected 'dji' to match DM room via context keyword"
|
|
)
|
|
assert matched.room_id == "room_dm_andreas", (
|
|
f"Expected room_dm_andreas, got {matched.room_id if matched else 'None'}"
|
|
)
|
|
assert matched.catch_all is True, (
|
|
"Matched room should be catch-all"
|
|
)
|
|
|
|
def test_single_context_keyword_matches(self):
|
|
"""A single context keyword (min_score=1) should match."""
|
|
room_map = _make_room_map_with_dji()
|
|
|
|
# 'roadmap' is a context keyword for DM (catch-all)
|
|
matched = room_map.find_room_by_keywords(
|
|
"roadmap",
|
|
origin_room_id="room_rc_plugin",
|
|
)
|
|
|
|
assert matched is not None, (
|
|
"Expected 'roadmap' to match DM room with min_score=1"
|
|
)
|
|
assert matched.room_id == "room_dm_andreas"
|
|
|
|
def test_context_keyword_does_not_match_100_percent(self):
|
|
"""Context keyword match should NOT be treated as 100% match."""
|
|
room_map = _make_room_map_with_dji()
|
|
|
|
matched = room_map.find_room_by_keywords(
|
|
"dji Drohne",
|
|
origin_room_id="room_rc_plugin",
|
|
)
|
|
|
|
assert matched is not None
|
|
# 'dji' is a context keyword, not a 100% keyword
|
|
is_100 = room_map.is_100_percent_match("dji Drohne", matched)
|
|
assert is_100 is False, (
|
|
"Context keyword should not be a 100% match"
|
|
)
|
|
|
|
|
|
# ── Test 4: Kontext-Keyword Catch-All → Butler ─────────────────────────────
|
|
|
|
|
|
class TestContextKeywordCatchAll:
|
|
"""Context keyword matching a catch-all room triggers butler."""
|
|
|
|
def test_dji_in_rc_plugin_triggers_butler_to_dm(self):
|
|
"""'dji' in #RC-Plugin → context_keyword butler to DM."""
|
|
room_map = _make_room_map_with_dji()
|
|
|
|
async def mock_llm_stay(prompt: str) -> str:
|
|
return "STAY"
|
|
|
|
router = _make_router(room_map, mock_llm_stay)
|
|
|
|
# Enable telemetry
|
|
routing_telemetry._enabled = True
|
|
routing_telemetry.clear()
|
|
|
|
decision = asyncio.run(router.route(
|
|
"dji Drohne",
|
|
origin_room_id="room_rc_plugin",
|
|
))
|
|
|
|
# 'dji' is a context keyword for DM (catch-all)
|
|
# → should trigger butler to DM
|
|
assert decision.move_request_sent is True, (
|
|
f"Expected move_request_sent=True (butler), got {decision.move_request_sent}"
|
|
)
|
|
assert decision.target_room == "room_dm_andreas", (
|
|
f"Expected target_room='room_dm_andreas', got {decision.target_room}"
|
|
)
|
|
assert decision.matched_room_name == "DM mit Andreas", (
|
|
f"Expected matched_room_name='DM mit Andreas', "
|
|
f"got {decision.matched_room_name}"
|
|
)
|
|
|
|
def test_dji_context_keyword_telemetry_record(self, caplog):
|
|
"""'dji' context keyword match produces telemetry record with target=DM."""
|
|
room_map = _make_room_map_with_dji()
|
|
|
|
async def mock_llm_stay(prompt: str) -> str:
|
|
return "STAY"
|
|
|
|
router = _make_router(room_map, mock_llm_stay)
|
|
|
|
# Enable telemetry propagation for caplog capture
|
|
from plugin.archivar.routing_telemetry import logger as telemetry_logger
|
|
telemetry_logger.propagate = True
|
|
caplog.set_level(logging.INFO)
|
|
|
|
routing_telemetry._enabled = True
|
|
routing_telemetry.clear()
|
|
|
|
try:
|
|
decision = asyncio.run(router.route(
|
|
"dji Drohne",
|
|
origin_room_id="room_rc_plugin",
|
|
))
|
|
|
|
# Flush telemetry
|
|
routing_telemetry.flush()
|
|
|
|
# Find context_keyword record in logs
|
|
telemetry_logs = [
|
|
r.message for r in caplog.records
|
|
if "[TELEMETRY]" in r.message
|
|
]
|
|
context_logs = [
|
|
msg for msg in telemetry_logs
|
|
if "stage=context_keyword" in msg
|
|
]
|
|
assert len(context_logs) > 0, (
|
|
f"Expected context_keyword telemetry log, got: {telemetry_logs}"
|
|
)
|
|
|
|
ctx_log = context_logs[0]
|
|
assert "target=room_dm_andreas" in ctx_log, (
|
|
f"Expected target=room_dm_andreas in log, got: {ctx_log}"
|
|
)
|
|
assert "decision=butler" in ctx_log, (
|
|
f"Expected decision=butler in log, got: {ctx_log}"
|
|
)
|
|
finally:
|
|
telemetry_logger.propagate = False
|
|
|
|
def test_100_percent_keyword_still_excludes_catch_all(self):
|
|
"""100% keyword match should still NOT match catch-all rooms."""
|
|
room_map = _make_room_map_with_dji()
|
|
|
|
# 'strategie' is a 100% keyword for DM (catch-all)
|
|
# 100% keywords should still exclude catch-all rooms
|
|
matched = room_map.find_room_by_keywords(
|
|
"strategie",
|
|
origin_room_id="room_rc_plugin",
|
|
)
|
|
|
|
# 100% keywords on catch-all should NOT match
|
|
# (only context keywords match catch-all)
|
|
assert matched is None or matched.catch_all is False, (
|
|
"100% keyword should not match catch-all room"
|
|
)
|
|
|
|
|
|
# ── Regression: Bestehende Tests nicht brechen ─────────────────────────────
|
|
|
|
|
|
class TestRegression:
|
|
"""Bestehende Funktionalität bleibt erhalten."""
|
|
|
|
def test_meta_question_stays(self):
|
|
"""Meta-Fragen bleiben im Ursprungsraum."""
|
|
room_map = _make_room_map_with_dji()
|
|
router = _make_router(room_map)
|
|
|
|
decision = asyncio.run(router.route(
|
|
"In welchem Raum wurde meine Nachricht klassifiziert?",
|
|
origin_room_id="room_rc_plugin",
|
|
))
|
|
|
|
assert decision.is_meta is True
|
|
assert decision.stay_in_room is True
|
|
|
|
def test_empty_text_stays(self):
|
|
"""Leerer Text → stay_in_room."""
|
|
room_map = _make_room_map_with_dji()
|
|
router = _make_router(room_map)
|
|
|
|
decision = asyncio.run(router.route("", origin_room_id="room_rc_plugin"))
|
|
|
|
assert decision.stay_in_room is True
|
|
|
|
def test_catch_all_origin_bypass(self):
|
|
"""Nachricht aus Catch-All-Raum → stay_in_room."""
|
|
room_map = _make_room_map_with_dji()
|
|
router = _make_router(room_map)
|
|
|
|
decision = asyncio.run(router.route(
|
|
"Dokumentiere das Plugin",
|
|
origin_room_id="room_dm_andreas",
|
|
))
|
|
|
|
assert decision.stay_in_room is True
|
|
|
|
def test_100_percent_keyword_auto_routes(self):
|
|
"""100%-Keyword-Match routet automatisch (kein Butler)."""
|
|
room_map = _make_room_map_with_dji()
|
|
router = _make_router(room_map)
|
|
|
|
decision = asyncio.run(router.route(
|
|
"Bitte dokumentiere das neue Feature",
|
|
origin_room_id="room_rc_plugin",
|
|
))
|
|
|
|
assert decision.target_room == "room_lan_doku", (
|
|
f"Expected target_room='room_lan_doku', got {decision.target_room}"
|
|
)
|
|
assert decision.move_request_sent is False, (
|
|
"100% keyword match should auto-route (no butler)"
|
|
)
|