fix: V8.4.6 — FAISS schließt Ursprungsraum aus + Kontext-Keyword bei Catch-Butler (P0-Bundle)

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
This commit is contained in:
Bernd (Hermes)
2026-07-16 10:37:42 +02:00
parent da5586e776
commit 463e29d594
5 changed files with 592 additions and 110 deletions
+15 -10
View File
@@ -182,12 +182,14 @@ class RoomMap:
# ── Lookup Methods ──────────────────────────────────────────────── # ── Lookup Methods ────────────────────────────────────────────────
def find_room_by_keywords(self, text: str, min_score: int = 2, origin_room_id: Optional[str] = None) -> Optional[RoomEntry]: def find_room_by_keywords(self, text: str, min_score: int = 1, origin_room_id: Optional[str] = None) -> Optional[RoomEntry]:
"""Find the room with the most keyword matches for *text*. """Find the room with the most keyword matches for *text*.
Args: Args:
text: The message text to classify. text: The message text to classify.
min_score: Minimum score required to return a room (default: 2). min_score: Minimum score required to return a room (default: 1).
V8.4.6: Gesenkt von 2 auf 1 — ein einzelnes Kontext-Keyword
reicht für einen Butler-Vorschlag.
origin_room_id: Optional room ID of the message origin for priority matching. origin_room_id: Optional room ID of the message origin for priority matching.
Returns: Returns:
@@ -199,6 +201,8 @@ class RoomMap:
# Stufe 1: Prüfe 100% Evidenz Keywords zuerst # Stufe 1: Prüfe 100% Evidenz Keywords zuerst
# Bei mehreren Räumen mit 100%-Matches: den mit den MEISTEN Treffern nehmen # Bei mehreren Räumen mit 100%-Matches: den mit den MEISTEN Treffern nehmen
# Catch-All-Räume werden in Stufe 1 NICHT berücksichtigt
# (100%-Keywords auf Catch-All sind für Auto-Route gedacht, nicht für Keyword-Match)
best_100_room: Optional[RoomEntry] = None best_100_room: Optional[RoomEntry] = None
best_100_score: int = 0 best_100_score: int = 0
@@ -218,22 +222,23 @@ class RoomMap:
# Stufe 2: Origin-Priorität mit kontextabhängigen Keywords # Stufe 2: Origin-Priorität mit kontextabhängigen Keywords
# Origin-Priorität gilt NUR für context-Keywords (100% schlagen immer durch) # Origin-Priorität gilt NUR für context-Keywords (100% schlagen immer durch)
# V8.4.6: Catch-All-Räume sind in Stufe 2 als Butler-Ziele erlaubt
if origin_room_id is not None and origin_room_id in self._rooms: if origin_room_id is not None and origin_room_id in self._rooms:
origin_room = self._rooms[origin_room_id] origin_room = self._rooms[origin_room_id]
if not origin_room.catch_all: # Prüfe kontextabhängige Keywords im Ursprungsraum
# Prüfe kontextabhängige Keywords im Ursprungsraum # (auch Catch-All-Räume — sie können Kontext-Keywords haben)
context_score = sum(1 for kw in origin_room.keywords_context if kw.lower() in text_lower) context_score = sum(1 for kw in origin_room.keywords_context if kw.lower() in text_lower)
if context_score >= min_score: if context_score >= min_score:
return origin_room return origin_room
# Stufe 3: Globaler Scan mit kontextabhängigen Keywords # Stufe 3: Globaler Scan mit kontextabhängigen Keywords
# V8.4.6: Catch-All-Räume sind in Stufe 3 als Butler-Ziele erlaubt.
# Catch-All als Keyword-Match-Ziel war für 100%-Auto-Route blockiert (Stufe 1).
# Für Kontext-Keywords (Stufe 3) sind Catch-All-Räume valide Butler-Ziele.
best_room: Optional[RoomEntry] = None best_room: Optional[RoomEntry] = None
best_score: int = 0 best_score: int = 0
for room in self._rooms.values(): for room in self._rooms.values():
if room.catch_all:
continue # Catch-All never matches keywords
# Prüfe kontextabhängige Keywords # Prüfe kontextabhängige Keywords
context_score = sum(1 for kw in room.keywords_context if kw.lower() in text_lower) context_score = sum(1 for kw in room.keywords_context if kw.lower() in text_lower)
if context_score > best_score: if context_score > best_score:
+88 -84
View File
@@ -677,98 +677,102 @@ class BidirectionalRouter:
text, k=FAISS_TOP_K, min_score=FAISS_MIN_SCORE text, k=FAISS_TOP_K, min_score=FAISS_MIN_SCORE
) )
if faiss_hits: if faiss_hits:
# ── Keyword-Booster anwenden ────────────────────── # ── V8.4.6: Ursprungsraum aus FAISS-Ergebnissen ausschließen ─
boosted = faiss_hits # FAISS findet oft den Ursprungsraum als ähnlichsten Raum
booster_applied = False # (z.B. score=0.62, target=#RC-Plugin, origin=#RC-Plugin).
if self._booster is not None: # Das ist sinnlos — Butler kann keinen Wechsel von
# Boosten immer anwenden, nicht nur bei Konflikten # #RC-Plugin → #RC-Plugin vorschlagen.
boosted = self._booster.boost(text, faiss_hits) faiss_hits = [
booster_applied = True (rid, score) for rid, score in faiss_hits
if rid != origin_room_id
]
if not faiss_hits:
# Alle FAISS-Treffer waren der Ursprungsraum → fall-through
logger.debug( logger.debug(
"FAISS Booster applied: always active", "FAISS Phase-1: all hits were origin room %s → fall-through to LLM",
origin_room_id[:8] if origin_room_id else "DM",
) )
routing_counter.increment('faiss_origin_excluded')
else:
# ── Keyword-Booster anwenden ──────────────────────
boosted = faiss_hits
booster_applied = False
if self._booster is not None:
# Boosten immer anwenden, nicht nur bei Konflikten
boosted = self._booster.boost(text, faiss_hits)
booster_applied = True
logger.debug(
"FAISS Booster applied: always active",
)
top_room_id, top_score = boosted[0] top_room_id, top_score = boosted[0]
# ── Auto-Route bei hohem Score ──────────────────── # ── Auto-Route bei hohem Score ────────────────────
if top_score >= FAISS_AUTO_ROUTE: if top_score >= FAISS_AUTO_ROUTE:
room = self._room_map.get_room_by_id(top_room_id) room = self._room_map.get_room_by_id(top_room_id)
if room is not None: if room is not None:
# Self-Match-Schutz: FAISS matched origin room room_name = (
if top_room_id == origin_room_id: room.name.replace("#", "")
logger.debug( if room.name.startswith("#")
"FAISS self-match: '%s' matched origin room %s → stay_in_room", else room.name
text[:80], room.name,
) )
notification = f"📋 Bearbeite ich in #{room_name} — [Link]"
matched_keywords = self._extract_matched_keywords(text, room)
# ── P0-B: never_route topic check ──────────
if self._check_never_route_topic(origin_room_id, room):
return RoutingDecision(
category="direct_question",
target_room="",
confidence=1.0,
stay_in_room=True,
)
logger.info(
"FAISS Phase-1: auto-route '%s' → %s (score=%.3f, booster=%s)",
text[:80],
room.name,
top_score,
booster_applied,
)
routing_counter.increment('faiss_auto_route')
routing_telemetry.record(
stage='faiss', score=top_score, decision='route',
target=top_room_id, origin=origin_room_id,
duration_ms=routing_telemetry.elapsed_ms(),
)
logger.info("ROUTING DECISION: reason=faiss_auto_route, origin_room=%s, target_room=%s, stay=False, butler_mode=False", origin_room_id, top_room_id)
return RoutingDecision( return RoutingDecision(
category="direct_question", category="work_order",
target_room="", target_room=top_room_id,
confidence=0.0, confidence=top_score,
stay_in_room=True, matched_room_name=room.name,
source_room_notification=notification,
matched_keywords=matched_keywords,
faiss_score=top_score,
faiss_room_id=top_room_id,
faiss_room_name=room.name,
is_faiss_routed=True,
booster_applied=booster_applied,
move_request_sent=False, # FIX D: FAISS-Auto-Route → kein Butler
move_request_target_name=room.name,
move_request_target_id=top_room_id,
) )
room_name = ( # ── Score unter Schwelle → Fall-through zu Embedding + LLM
room.name.replace("#", "") logger.debug(
if room.name.startswith("#") "FAISS Phase-1: top score %.3f < %.3f — fall-through to LLM",
else room.name top_score,
) FAISS_AUTO_ROUTE,
notification = f"📋 Bearbeite ich in #{room_name} — [Link]" )
matched_keywords = self._extract_matched_keywords(text, room) routing_counter.increment('faiss_butler')
routing_telemetry.record(
# ── P0-B: never_route topic check ────────── stage='faiss', score=top_score, decision='butler',
if self._check_never_route_topic(origin_room_id, room): target=top_room_id, origin=origin_room_id,
return RoutingDecision( duration_ms=routing_telemetry.elapsed_ms(),
category="direct_question", )
target_room="", logger.info("ROUTING DECISION: reason=faiss_butler, origin_room=%s, target_room=%s, stay=False, butler_mode=True", origin_room_id, top_room_id)
confidence=1.0,
stay_in_room=True,
)
logger.info(
"FAISS Phase-1: auto-route '%s' → %s (score=%.3f, booster=%s)",
text[:80],
room.name,
top_score,
booster_applied,
)
routing_counter.increment('faiss_auto_route')
routing_telemetry.record(
stage='faiss', score=top_score, decision='route',
target=top_room_id, origin=origin_room_id,
duration_ms=routing_telemetry.elapsed_ms(),
)
logger.info("ROUTING DECISION: reason=faiss_auto_route, origin_room=%s, target_room=%s, stay=False, butler_mode=False", origin_room_id, top_room_id)
return RoutingDecision(
category="work_order",
target_room=top_room_id,
confidence=top_score,
matched_room_name=room.name,
source_room_notification=notification,
matched_keywords=matched_keywords,
faiss_score=top_score,
faiss_room_id=top_room_id,
faiss_room_name=room.name,
is_faiss_routed=True,
booster_applied=booster_applied,
move_request_sent=False, # FIX D: FAISS-Auto-Route → kein Butler
move_request_target_name=room.name,
move_request_target_id=top_room_id,
)
# ── Score unter Schwelle → Fall-through zu Embedding + LLM
logger.debug(
"FAISS Phase-1: top score %.3f < %.3f — fall-through to LLM",
top_score,
FAISS_AUTO_ROUTE,
)
routing_counter.increment('faiss_butler')
routing_telemetry.record(
stage='faiss', score=top_score, decision='butler',
target=top_room_id, origin=origin_room_id,
duration_ms=routing_telemetry.elapsed_ms(),
)
logger.info("ROUTING DECISION: reason=faiss_butler, origin_room=%s, target_room=%s, stay=False, butler_mode=True", origin_room_id, top_room_id)
# ── Schritt 4: Embedding-Vorfilter (binär) ──────────────────── # ── Schritt 4: Embedding-Vorfilter (binär) ────────────────────
# Nur noch binär: "Smalltalk" vs. "potenzieller Auftrag" # Nur noch binär: "Smalltalk" vs. "potenzieller Auftrag"
+7 -4
View File
@@ -222,12 +222,15 @@ class TestTwoStageKeywordEvidence:
assert result.name == "#Plugin" assert result.name == "#Plugin"
def test_context_keywords_min_score(self, room_map_v2): def test_context_keywords_min_score(self, room_map_v2):
"""Context keywords should require min_score=2.""" """Context keywords should require min_score=1 (V8.4.6)."""
# Only one context keyword match should not be enough # A single context keyword match should be enough (min_score=1)
result = room_map_v2.find_room_by_keywords("plugin") result = room_map_v2.find_room_by_keywords("plugin")
assert result is None assert result is not None, (
"V8.4.6: min_score=1 — single context keyword should match"
)
assert result.name == "#Plugin"
# Two context keyword matches should be enough # Two context keyword matches should also be enough
result = room_map_v2.find_room_by_keywords("plugin gateway") result = room_map_v2.find_room_by_keywords("plugin gateway")
assert result is not None assert result is not None
assert result.name == "#Plugin" assert result.name == "#Plugin"
+10 -12
View File
@@ -253,28 +253,26 @@ class TestSonyContextKeyword:
"""Kontext-Keyword 'sony' im DM-Raum löst Butler aus (nicht STAY).""" """Kontext-Keyword 'sony' im DM-Raum löst Butler aus (nicht STAY)."""
def test_sony_context_keyword_triggers_butler(self): def test_sony_context_keyword_triggers_butler(self):
"""'Sony Vollformat Kamera' matched 'sony' → Butler fragt.""" """'Sony Vollformat Kamera' matched 'sony' → Butler fragt (V8.4.6)."""
room_map = _make_room_map_with_sony() room_map = _make_room_map_with_sony()
router = _make_router(room_map) router = _make_router(room_map)
# 'sony' is a context keyword for DM mit Andreas (catch-all) # 'sony' is a context keyword for DM mit Andreas (catch-all)
# But catch-all rooms are excluded from keyword matching by design. # V8.4.6: Catch-All-Räume sind jetzt bei Kontext-Keywords als
# The keyword match should NOT match the catch-all room. # Butler-Ziele erlaubt. 'sony' matched den DM-Raum → Butler fragt.
# Instead, the message should fall through to LLM.
# This test verifies the current behavior: catch-all rooms are
# excluded from keyword matching.
decision = asyncio.run(router.route( decision = asyncio.run(router.route(
"Sony Vollformat Kamera", "Sony Vollformat Kamera",
origin_room_id="room_rc_plugin", origin_room_id="room_rc_plugin",
)) ))
# Catch-all rooms are excluded from keyword matching (room_map.py:206) # V8.4.6: 'sony' context keyword matches DM (catch-all) → butler
# So 'sony' in DM keywords_context won't match. assert decision.move_request_sent is True, (
# The message falls through to LLM → STAY (no LLM mock → fallback) f"V8.4.6: context keyword on catch-all should trigger butler, "
assert decision.stay_in_room is True, ( f"got move_request_sent={decision.move_request_sent}"
"Catch-all rooms are excluded from keyword matching — " )
"message should fall through to LLM/fallback" assert decision.target_room == "room_dm_andreas", (
f"Expected target_room='room_dm_andreas', got {decision.target_room}"
) )
def test_sony_in_non_catchall_room_triggers_match(self): def test_sony_in_non_catchall_room_triggers_match(self):
+472
View File
@@ -0,0 +1,472 @@
"""
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)"
)