Files
Hermes_rocket.chat_Plugin/plugin/archivar/tests/test_room_map.py
T
Bernd (Hermes) 463e29d594 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
2026-07-16 10:37:42 +02:00

519 lines
21 KiB
Python

"""
Tests für das RoomMap-Datenmodell.
Prüft:
- Laden und Validieren von room-map.json
- Keyword-Matching
- Validierungsfehler (0/2 Catch-All, excluded_rooms)
- Legacy-Env-Var-Migration
"""
from __future__ import annotations
import json
import os
import tempfile
from pathlib import Path
import pytest
# Ensure the archivar package is importable
import sys
sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
from plugin.archivar.room_map import (
RoomMap,
RoomEntry,
RoomMapValidationError,
_migrate_from_env_vars,
)
# ── 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 []):
room_data = {
"name": room["name"],
"theme": room.get("theme", ""),
"catch_all": room.get("catch_all", False),
}
# Handle both old and new room structures
if "keywords_100" in room or "keywords_context" in room:
# New structure (version 2)
room_data["keywords_100"] = room.get("keywords_100", [])
room_data["keywords_context"] = room.get("keywords_context", [])
else:
# Old structure (version 1)
room_data["keywords"] = room.get("keywords", [])
data["rooms"][room["room_id"]] = room_data
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)
# ── Basic Loading ──────────────────────────────────────────────────────────
class TestRoomMapLoad:
"""RoomMap.load() — basic loading."""
def test_load_valid_map(self):
"""Load a map with 3 rooms, 1 catch-all, 1 excluded."""
json_str = _make_map_json(
rooms=[
{"room_id": "r1", "name": "#Dev", "theme": "dev room", "keywords": ["code", "bug"]},
{"room_id": "r2", "name": "#Ops", "theme": "ops room", "keywords": ["server", "docker"]},
{"room_id": "r3", "name": "DM Admin", "theme": "admin", "keywords": [], "catch_all": True},
],
excluded=["rx99"],
)
path = _tmp_map(json_str)
try:
rm = RoomMap.load(path)
assert rm.version == 1
assert len(rm.rooms) == 3
assert rm.catch_all_room is not None
assert rm.catch_all_room.room_id == "r3"
assert "rx99" in rm.excluded_room_ids
assert str(rm.fact_store_path) == "/tmp/test_docs"
finally:
path.unlink(missing_ok=True)
def test_load_empty_rooms(self):
"""Map with no rooms — should load but fail validation."""
json_str = _make_map_json(rooms=[])
path = _tmp_map(json_str)
try:
rm = RoomMap.load(path)
assert len(rm.rooms) == 0
# Validation should raise
with pytest.raises(RoomMapValidationError, match="No catch_all"):
rm.validate()
finally:
path.unlink(missing_ok=True)
def test_load_file_not_found(self):
"""Missing file should raise FileNotFoundError."""
with pytest.raises(FileNotFoundError):
RoomMap.load(Path("/tmp/nonexistent_room_map_2026.json"))
# ── Keyword Matching ───────────────────────────────────────────────────────
class TestRoomMapKeywords:
"""RoomMap.find_room_by_keywords() tests."""
@pytest.fixture
def room_map(self) -> RoomMap:
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:
return RoomMap.load(path)
finally:
path.unlink(missing_ok=True)
def test_keyword_match_plugin(self, room_map):
"""Plugin keywords should match #Plugin room."""
result = room_map.find_room_by_keywords("Das Plugin hat einen Gateway-Bug")
assert result is not None
assert result.name == "#Plugin"
def test_keyword_match_bat(self, room_map):
"""BAT keywords should match #BAT room."""
result = room_map.find_room_by_keywords("Das Docker-Image für Trading ist kaputt")
assert result is not None
assert result.name == "#BAT"
def test_keyword_multiple_matches(self, room_map):
"""Most matching keywords wins."""
# "gateway" matches both Plugin and BAT, but "plugin" gives Plugin an edge
result = room_map.find_room_by_keywords("gateway plugin trading")
assert result is not None
assert result.name == "#Plugin" # plugin + gateway = 2 vs trading = 1
def test_no_keyword_match(self, room_map):
"""No keywords should return None."""
result = room_map.find_room_by_keywords("Hallo wie gehts")
assert result is None
def test_catch_all_never_matches_keywords(self, room_map):
"""Catch-all room has no keywords, never returned."""
result = room_map.find_room_by_keywords("irgendwas")
assert result is None # Not the catch-all
def test_keyword_case_insensitive(self, room_map):
"""Keywords are case-insensitive."""
result = room_map.find_room_by_keywords("PLUGIN ADAPTER")
assert result is not None
assert result.name == "#Plugin"
# ── Two-Stage Keyword Evidence System ──────────────────────────────────────
class TestTwoStageKeywordEvidence:
"""Tests for the two-stage keyword evidence system."""
@pytest.fixture
def room_map_v2(self) -> RoomMap:
"""Create a RoomMap with version 2 structure (keywords_100 + keywords_context)."""
data = {
"version": 2,
"rooms": {
"r1": {
"name": "#Plugin",
"theme": "plugin dev",
"keywords_100": ["rocketchat", "rc", "ddp", "websocket"],
"keywords_context": ["plugin", "gateway", "deployment", "button", "sync", "hermes"]
},
"r2": {
"name": "#BAT",
"theme": "trading",
"keywords_100": ["bat", "bat-team", "trading", "krypto"],
"keywords_context": ["gateway"]
},
"r3": {
"name": "DM Admin",
"theme": "admin",
"keywords_100": [],
"keywords_context": [],
"catch_all": True
}
},
"excluded_rooms": [],
"fact_store_path": "/tmp/test_docs"
}
json_str = json.dumps(data)
path = _tmp_map(json_str)
try:
return RoomMap.load(path)
finally:
path.unlink(missing_ok=True)
def test_100_percent_keywords_immediate_match(self, room_map_v2):
"""100% keywords should match immediately, even with low context score."""
# "rocketchat" is a 100% keyword for #Plugin room
result = room_map_v2.find_room_by_keywords("rocketchat plugin bug")
assert result is not None
assert result.name == "#Plugin"
def test_context_keywords_min_score(self, room_map_v2):
"""Context keywords should require min_score=1 (V8.4.6)."""
# A single context keyword match should be enough (min_score=1)
result = room_map_v2.find_room_by_keywords("plugin")
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 also be enough
result = room_map_v2.find_room_by_keywords("plugin gateway")
assert result is not None
assert result.name == "#Plugin"
def test_origin_priority_with_context_keywords(self, room_map_v2):
"""Origin room should get priority with context keywords."""
# Message from BAT room with context keywords for BAT
# Use "gateway issue" which matches both rooms, but origin priority should win
# We need at least min_score=2, so add another keyword
result = room_map_v2.find_room_by_keywords("gateway bat", origin_room_id="r2")
assert result is not None
assert result.room_id == "r2" # Should go to origin room (bat is 100% keyword for BAT)
# Test with multiple context keywords
result = room_map_v2.find_room_by_keywords("gateway trading", origin_room_id="r2")
assert result is not None
assert result.room_id == "r2" # Should go to origin room (gateway + trading = 2 context keywords)
def test_global_fallback_with_context_keywords(self, room_map_v2):
"""Global fallback should work with context keywords."""
# Context keywords for Plugin room
result = room_map_v2.find_room_by_keywords("plugin deployment")
assert result is not None
assert result.name == "#Plugin"
def test_100_percent_overrides_origin_priority(self, room_map_v2):
"""100% keywords should override origin priority."""
# Message from BAT room but with 100% keyword for Plugin
result = room_map_v2.find_room_by_keywords("rocketchat bug", origin_room_id="r2")
assert result is not None
assert result.name == "#Plugin" # Should go to Plugin room, not origin
def test_backward_compatibility_with_v1_structure(self):
"""Old room-map.json (version 1) should still work."""
# Simulate old structure with only "keywords" field
data = {
"version": 1,
"rooms": {
"r1": {
"name": "#Plugin",
"theme": "plugin dev",
"keywords": ["plugin", "gateway", "deployment"]
},
"r2": {
"name": "DM Admin",
"theme": "admin",
"keywords": [],
"catch_all": True
}
},
"excluded_rooms": [],
"fact_store_path": "/tmp/test_docs"
}
json_str = json.dumps(data)
path = _tmp_map(json_str)
try:
room_map = RoomMap.load(path)
# Should work like before, treating all keywords as context keywords
result = room_map.find_room_by_keywords("plugin gateway")
assert result is not None
assert result.name == "#Plugin"
finally:
path.unlink(missing_ok=True)
# ── Exclusion ──────────────────────────────────────────────────────────────
class TestRoomMapExclusion:
"""Room exclusion tests."""
def test_excluded_room(self):
json_str = _make_map_json(
rooms=[
{"room_id": "r1", "name": "#Bot-Room", "theme": "multi-agent", "keywords": []},
{"room_id": "admin", "name": "DM Admin", "theme": "admin", "keywords": [], "catch_all": True},
],
excluded=["r1"],
)
path = _tmp_map(json_str)
try:
rm = RoomMap.load(path)
assert rm.is_excluded("r1") is True
assert rm.is_excluded("admin") is False
assert rm.is_excluded("nonexistent") is False
finally:
path.unlink(missing_ok=True)
# ── Validation ─────────────────────────────────────────────────────────────
class TestRoomMapValidation:
"""RoomMap.validate() tests."""
def _load(self, rooms: list[dict], excluded: list[str] | None = None) -> RoomMap:
json_str = _make_map_json(rooms=rooms, excluded=excluded)
path = _tmp_map(json_str)
try:
return RoomMap.load(path)
finally:
path.unlink(missing_ok=True)
def test_no_catch_all(self):
"""0 catch-all rooms → RoomMapValidationError."""
rm = self._load([
{"room_id": "r1", "name": "#A", "theme": "A"},
{"room_id": "r2", "name": "#B", "theme": "B"},
])
with pytest.raises(RoomMapValidationError, match="No catch_all"):
rm.validate()
def test_two_catch_all(self):
"""2 catch-all rooms → RoomMapValidationError."""
rm = self._load([
{"room_id": "r1", "name": "#A", "theme": "A", "keywords": [], "catch_all": True},
{"room_id": "r2", "name": "#B", "theme": "B", "keywords": [], "catch_all": True},
])
with pytest.raises(RoomMapValidationError, match="Multiple catch_all"):
rm.validate()
def test_catch_all_in_excluded(self):
"""Catch-all in excluded_rooms → RoomMapValidationError."""
rm = self._load(
rooms=[
{"room_id": "r1", "name": "#Excluded", "theme": "bad", "keywords": [], "catch_all": True},
],
excluded=["r1"],
)
with pytest.raises(RoomMapValidationError, match="excluded_rooms"):
rm.validate()
def test_valid_map_with_subscriptions(self):
"""Valid map with subscribed room IDs — no errors."""
rm = self._load([
{"room_id": "r1", "name": "#Dev", "theme": "dev", "keywords": []},
{"room_id": "admin", "name": "DM Admin", "theme": "admin", "keywords": [], "catch_all": True},
])
errors = rm.validate(subscribed_ids={"r1", "admin"})
assert errors == []
def test_room_not_subscribed_warning(self):
"""Room not in subscribed_ids → non-fatal warning."""
rm = self._load([
{"room_id": "r1", "name": "#Dev", "theme": "dev", "keywords": []},
{"room_id": "admin", "name": "DM Admin", "theme": "admin", "keywords": [], "catch_all": True},
])
errors = rm.validate(subscribed_ids={"admin"}) # r1 not subscribed
assert len(errors) >= 1
assert any("not in subscribed" in e for e in errors)
def test_catch_all_not_subscribed_warning(self):
"""Catch-all not in subscribed_ids → warning (not fatal)."""
rm = self._load([
{"room_id": "admin", "name": "DM Admin", "theme": "admin", "keywords": [], "catch_all": True},
])
errors = rm.validate(subscribed_ids={"r999"})
assert len(errors) >= 1
assert any("catch-all room" in e.lower() for e in errors)
# ── Migration from Legacy Env Vars ─────────────────────────────────────────
class TestMigrationFromEnvVars:
"""_migrate_from_env_vars() tests."""
def teardown_method(self):
"""Clean up env vars after each test."""
for key in list(os.environ):
if key.startswith("ARCHIVAR_"):
del os.environ[key]
def test_no_env_vars(self):
"""No legacy env vars → None."""
# Clear any ARCHIVAR_* env vars that may be set in the environment
for key in list(os.environ):
if key.startswith("ARCHIVAR_"):
del os.environ[key]
assert _migrate_from_env_vars() is None
def test_with_catchall_only(self):
"""ARCHIVAR_CATCHALL_ROOM set → catch-all in migrated map."""
os.environ["ARCHIVAR_CATCHALL_ROOM"] = "room_catchall"
result = _migrate_from_env_vars()
assert result is not None
assert "room_catchall" in result["rooms"]
assert result["rooms"]["room_catchall"]["catch_all"] is True
def test_with_multiple_rooms(self):
"""Multiple legacy vars → all rooms in migrated map."""
os.environ["ARCHIVAR_CATCHALL_ROOM"] = "room_catchall"
os.environ["ARCHIVAR_ALARM_ROOM"] = "room_alarm"
os.environ["ARCHIVAR_FRAGE_ROOM"] = "room_frage"
result = _migrate_from_env_vars()
assert result is not None
assert len(result["rooms"]) >= 3
def test_alarm_same_as_catchall_not_duplicated(self):
"""If ALARM_ROOM == CATCHALL_ROOM, don't create duplicate."""
os.environ["ARCHIVAR_CATCHALL_ROOM"] = "same_room"
os.environ["ARCHIVAR_ALARM_ROOM"] = "same_room"
result = _migrate_from_env_vars()
assert result is not None
# Should only have one entry for "same_room" with catch_all=True
assert "same_room" in result["rooms"]
assert result["rooms"]["same_room"]["catch_all"] is True
def test_project_rooms(self):
"""ARCHIVAR_PROJECT_ROOMS JSON → project rooms in migrated map."""
os.environ["ARCHIVAR_CATCHALL_ROOM"] = "room_admin"
os.environ["ARCHIVAR_PROJECT_ROOMS"] = '{"plugin": "r_plugin", "bat": "r_bat"}'
result = _migrate_from_env_vars()
assert result is not None
assert "r_plugin" in result["rooms"]
assert "r_bat" in result["rooms"]
# ── RoomEntry ──────────────────────────────────────────────────────────────
class TestRoomEntry:
"""RoomEntry dataclass tests."""
def test_match_score(self):
entry = RoomEntry(
room_id="r1", name="#Dev", theme="dev",
keywords_100=["plugin", "gateway"],
keywords_context=["adapter"],
)
assert entry.match_score("Das Plugin braucht einen Gateway-Fix") == 2
assert entry.match_score("Der Adapter ist kaputt") == 1
assert entry.match_score("Hallo Welt") == 0
def test_match_score_no_keywords(self):
entry = RoomEntry(
room_id="admin", name="DM Admin", theme="admin",
keywords_100=[], keywords_context=[], catch_all=True,
)
assert entry.match_score("irgendwas") == 0
def test_match_score_case_insensitive(self):
entry = RoomEntry(
room_id="r1", name="#Dev", theme="dev",
keywords_100=["Plugin"], keywords_context=["GATEWAY"],
)
assert entry.match_score("plugin gateway") == 2
# ── LLM Lookup Tests ───────────────────────────────────────────────────────
class TestLLMLookup:
"""LLM-based lookup tests."""
@pytest.fixture
def room_map(self) -> RoomMap:
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:
return RoomMap.load(path)
finally:
path.unlink(missing_ok=True)
def test_llm_lookup_route_to_plugin(self, room_map):
"""LLM should route plugin-related query to #Plugin room."""
# This simulates the LLM-based routing that would happen in router.py
# For now, we're just testing that the room map structure supports it
result = room_map.find_room_by_keywords("Wie implementiere ich einen neuen Plugin-Adapter?")
assert result is not None
assert result.name == "#Plugin"
def test_llm_lookup_route_to_bat(self, room_map):
"""LLM should route trading-related query to #BAT room."""
# This simulates the LLM-based routing that would happen in router.py
# For now, we're just testing that the room map structure supports it
result = room_map.find_room_by_keywords("Wie funktioniert das BAT Trading-Signal?")
assert result is not None
assert result.name == "#BAT"