Files
Hermes_rocket.chat_Plugin/plugin/archivar/tests/test_room_map.py
Bernd (Hermes) 78c9a477e0 P-033: Fix Tiebreak-Bug in find_room_by_keywords
Root Cause: room_map.py:314 verwendete strict '>' statt Tiebreak-Comparator.
Bei Score-Tie (z.B. 1:1) entschied Dict-Insertion-Order, nicht Logik.

Fix (Option B, Rainer 2026-08-06):
- Neue Tiebreak-Helper: _get_matched_keywords(), _keyword_room_count(),
  _tiebreak_compare()
- Bei Score-Tie: Raum mit seltenerem Keyword (geringster room_count) gewinnt
- Bei erneutem Tie: laengstes gematchtes Keyword gewinnt
- Bei erneutem Tie: first-seen (stabil)
- Tiebreak gilt fuer Stufe 1 (100%-Keywords) UND Stufe 3 (Kontext-Keywords)

Tests: 6 neue Regressionstests in TestP033Tiebreak
- 'Rocketchat' + 'Dokumentation' -> #Rocketchat-Plugin (nicht #LAN-Doku)
- Nur 'Dokumentation' -> #LAN-Dokumentation (100%-Keyword schlaegt Kontext)
- Nur 'Rocketchat' -> #Rocketchat-Plugin
- Raritaet schlaegt Laenge
- Stable-Sort bei identischen Keywords
- Laenge gewinnt bei gleicher Raritaet

Infra: plugin/conftest.py registriert 'plugin' in sys.modules fuer
standalone-Tests (P-022 Flat-Modul-Pattern)
2026-08-06 21:56:21 +02:00

920 lines
37 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"
# ── P1-Fix: RoomMap.save Refuse-Guard ──────────────────────────────────────
class TestRoomMapSaveRefuseGuard:
"""P1-Fix: RoomMap.save verweigert Schreiben wenn Disk > In-Memory."""
def test_save_refuses_when_disk_has_more_rooms(self):
"""save() verweigert wenn Disk mehr Räume hat als In-Memory."""
import tempfile
from pathlib import Path
# Erstelle eine Disk-Datei mit 3 Räumen
disk_data = {
"version": 1,
"rooms": {
"r1": {"name": "#Room1", "theme": "t1", "description": "",
"keywords_100": [], "keywords_context": [], "catch_all": True,
"active_status_indikator": True,
"_stay_counts": {}, "_keyword_last_matched": {}},
"r2": {"name": "#Room2", "theme": "t2", "description": "",
"keywords_100": [], "keywords_context": [], "catch_all": False,
"active_status_indikator": True,
"_stay_counts": {}, "_keyword_last_matched": {}},
"r3": {"name": "#Room3", "theme": "t3", "description": "",
"keywords_100": [], "keywords_context": [], "catch_all": False,
"active_status_indikator": True,
"_stay_counts": {}, "_keyword_last_matched": {}},
},
"excluded_rooms": [],
"fact_store_path": "/tmp/test",
}
tmpdir = tempfile.TemporaryDirectory()
try:
map_path = Path(tmpdir.name) / "room-map.json"
with open(map_path, "w") as f:
json.dump(disk_data, f)
# Erstelle eine In-Memory-Map mit nur 1 Raum (kleiner als Disk)
small_data = {
"version": 1,
"rooms": {
"r1": {"name": "#Room1", "theme": "t1", "description": "",
"keywords_100": [], "keywords_context": [], "catch_all": True,
"active_status_indikator": True,
"_stay_counts": {}, "_keyword_last_matched": {}},
},
"excluded_rooms": [],
"fact_store_path": "/tmp/test",
}
small_map = RoomMap._from_dict(small_data)
# Versuche zu speichern — sollte verweigert werden
RoomMap.save(small_map, path=map_path)
# Disk sollte unverändert sein (3 Räume)
with open(map_path, "r") as f:
saved_data = json.load(f)
assert len(saved_data["rooms"]) == 3, (
f"Disk sollte 3 Räume haben, hat aber {len(saved_data['rooms'])}"
)
finally:
tmpdir.cleanup()
def test_save_allows_when_memory_has_more_rooms(self):
"""save() erlaubt Schreiben wenn In-Memory mehr Räume hat als Disk."""
import tempfile
from pathlib import Path
# Erstelle eine Disk-Datei mit 1 Raum
disk_data = {
"version": 1,
"rooms": {
"r1": {"name": "#Room1", "theme": "t1", "description": "",
"keywords_100": [], "keywords_context": [], "catch_all": True,
"active_status_indikator": True,
"_stay_counts": {}, "_keyword_last_matched": {}},
},
"excluded_rooms": [],
"fact_store_path": "/tmp/test",
}
tmpdir = tempfile.TemporaryDirectory()
try:
map_path = Path(tmpdir.name) / "room-map.json"
with open(map_path, "w") as f:
json.dump(disk_data, f)
# Erstelle eine In-Memory-Map mit 3 Räumen (größer als Disk)
big_data = {
"version": 1,
"rooms": {
"r1": {"name": "#Room1", "theme": "t1", "description": "",
"keywords_100": [], "keywords_context": [], "catch_all": True,
"active_status_indikator": True,
"_stay_counts": {}, "_keyword_last_matched": {}},
"r2": {"name": "#Room2", "theme": "t2", "description": "",
"keywords_100": [], "keywords_context": [], "catch_all": False,
"active_status_indikator": True,
"_stay_counts": {}, "_keyword_last_matched": {}},
"r3": {"name": "#Room3", "theme": "t3", "description": "",
"keywords_100": [], "keywords_context": [], "catch_all": False,
"active_status_indikator": True,
"_stay_counts": {}, "_keyword_last_matched": {}},
},
"excluded_rooms": [],
"fact_store_path": "/tmp/test",
}
big_map = RoomMap._from_dict(big_data)
# Speichern — sollte erlaubt sein
RoomMap.save(big_map, path=map_path)
# Disk sollte jetzt 3 Räume haben
with open(map_path, "r") as f:
saved_data = json.load(f)
assert len(saved_data["rooms"]) == 3, (
f"Disk sollte 3 Räume haben, hat aber {len(saved_data['rooms'])}"
)
finally:
tmpdir.cleanup()
def test_save_allows_when_equal_rooms(self):
"""save() erlaubt Schreiben wenn Disk und In-Memory gleich viele Räume haben."""
import tempfile
from pathlib import Path
disk_data = {
"version": 1,
"rooms": {
"r1": {"name": "#Room1", "theme": "t1", "description": "",
"keywords_100": [], "keywords_context": [], "catch_all": True,
"active_status_indikator": True,
"_stay_counts": {}, "_keyword_last_matched": {}},
"r2": {"name": "#Room2", "theme": "t2", "description": "",
"keywords_100": [], "keywords_context": [], "catch_all": False,
"active_status_indikator": True,
"_stay_counts": {}, "_keyword_last_matched": {}},
},
"excluded_rooms": [],
"fact_store_path": "/tmp/test",
}
tmpdir = tempfile.TemporaryDirectory()
try:
map_path = Path(tmpdir.name) / "room-map.json"
with open(map_path, "w") as f:
json.dump(disk_data, f)
# In-Memory hat auch 2 Räume (aber anderer Name)
mem_data = {
"version": 1,
"rooms": {
"r1": {"name": "#Room1_Renamed", "theme": "t1", "description": "",
"keywords_100": [], "keywords_context": [], "catch_all": True,
"active_status_indikator": True,
"_stay_counts": {}, "_keyword_last_matched": {}},
"r2": {"name": "#Room2", "theme": "t2", "description": "",
"keywords_100": [], "keywords_context": [], "catch_all": False,
"active_status_indikator": True,
"_stay_counts": {}, "_keyword_last_matched": {}},
},
"excluded_rooms": [],
"fact_store_path": "/tmp/test",
}
mem_map = RoomMap._from_dict(mem_data)
# Speichern — sollte erlaubt sein (gleiche Anzahl)
RoomMap.save(mem_map, path=map_path)
with open(map_path, "r") as f:
saved_data = json.load(f)
assert saved_data["rooms"]["r1"]["name"] == "#Room1_Renamed", (
"Umbenennung sollte persistiert werden"
)
finally:
tmpdir.cleanup()
def test_save_allows_when_disk_does_not_exist(self):
"""save() erlaubt Schreiben wenn Disk-Datei nicht existiert."""
import tempfile
from pathlib import Path
tmpdir = tempfile.TemporaryDirectory()
try:
map_path = Path(tmpdir.name) / "room-map.json"
# Keine Disk-Datei
mem_data = {
"version": 1,
"rooms": {
"r1": {"name": "#Room1", "theme": "t1", "description": "",
"keywords_100": [], "keywords_context": [], "catch_all": True,
"active_status_indikator": True,
"_stay_counts": {}, "_keyword_last_matched": {}},
},
"excluded_rooms": [],
"fact_store_path": "/tmp/test",
}
mem_map = RoomMap._from_dict(mem_data)
# Speichern — sollte erlaubt sein (keine Disk-Datei)
RoomMap.save(mem_map, path=map_path)
assert map_path.exists(), "Datei sollte erstellt worden sein"
finally:
tmpdir.cleanup()
# ── P-033: Tiebreak-Bug Regression Tests ───────────────────────────────────
class TestP033Tiebreak:
"""P-033: Tiebreak-Bug — bei Score-Tie gewinnt der semantisch passendere Raum.
Root Cause: room_map.py:314 verwendete strict ``>`` statt Tiebreak.
Bei Score-Tie 1:1 entschied Dict-Insertion-Order, nicht Logik.
Fix: Option B — Keyword-Rarität (room_count), dann längstes Keyword.
"""
@pytest.fixture
def room_map_p033(self) -> RoomMap:
"""Room map simulating the P-033 scenario.
#LAN-Dokumentation and #Rocketchat-Plugin both match "Dokumentation"
(one via keywords_100, one via keywords_context), but "rocketchat"
is unique to Plugin — so Plugin should win the tiebreak.
"""
data = {
"version": 2,
"rooms": {
"r_lan": {
"name": "#LAN-Dokumentation",
"theme": "LAN und Netzwerk-Dokumentation",
"keywords_100": ["dokumentation", "lan", "netzwerk"],
"keywords_context": [],
},
"r_plugin": {
"name": "#Rocketchat-Plugin",
"theme": "Rocketchat Plugin Entwicklung",
"keywords_100": ["rocketchat", "rc", "plugin"],
"keywords_context": ["dokumentation"],
},
"r_admin": {
"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_tiebreak_rocketchat_dokumentation_matches_plugin(self, room_map_p033):
"""Text mit 'Rocketchat' + 'Dokumentation' muss #Rocketchat-Plugin matchen.
Beide Räume scoren 1:1 (LAN: dokumentation, Plugin: rocketchat).
Tiebreak: 'rocketchat' ist seltener (nur in Plugin) als 'dokumentation'
(in beiden Räumen) → Plugin gewinnt.
"""
result = room_map_p033.find_room_by_keywords(
"Rocketchat Dokumentation Update"
)
assert result is not None, "Sollte einen Raum finden"
assert result.name == "#Rocketchat-Plugin", (
f"Tiebreak-Fehler: Erwartet #Rocketchat-Plugin, "
f"bekam {result.name}. 'rocketchat' ist seltener als 'dokumentation'."
)
def test_dokumentation_only_matches_lan(self, room_map_p033):
"""Text mit nur 'Dokumentation' muss #LAN-Dokumentation matchen.
LAN-Doku hat 'dokumentation' als 100%-Keyword → Stufe 1 Match.
Plugin hat 'dokumentation' nur als Kontext-Keyword → Stufe 3.
Stufe 1 schlägt Stufe 3 → LAN gewinnt.
"""
result = room_map_p033.find_room_by_keywords("Dokumentation")
assert result is not None, "Sollte einen Raum finden"
assert result.name == "#LAN-Dokumentation", (
f"Erwartet #LAN-Dokumentation (100%-Keyword), bekam {result.name}"
)
def test_rocketchat_only_matches_plugin(self, room_map_p033):
"""Text mit nur 'Rocketchat' muss #Rocketchat-Plugin matchen."""
result = room_map_p033.find_room_by_keywords("Rocketchat")
assert result is not None, "Sollte einen Raum finden"
assert result.name == "#Rocketchat-Plugin", (
f"Erwartet #Rocketchat-Plugin, bekam {result.name}"
)
def test_tiebreak_rarity_wins_over_length(self, room_map_p033):
"""Rarität (room_count) schlägt Keyword-Länge im Tiebreak.
Szenario: Zwei Räume mit gleichem Score, aber unterschiedlicher
Keyword-Rarität. Der Raum mit dem selteneren Keyword gewinnt,
auch wenn das Keyword kürzer ist.
"""
# Beide Räume matchen "dokumentation" (room_count=2) und
# "rocketchat" (room_count=1). Plugin hat das seltenere Keyword.
result = room_map_p033.find_room_by_keywords(
"Rocketchat Dokumentation"
)
assert result is not None
assert result.name == "#Rocketchat-Plugin", (
f"Rarität sollte Länge schlagen: 'rocketchat' (count=1) "
f"ist seltener als 'dokumentation' (count=2)"
)
def test_tiebreak_stable_when_all_equal(self, room_map_p033):
"""Wenn Rarität und Länge gleich sind → first-seen gewinnt (stabil)."""
# Erstelle zwei Räume mit identischen Keywords
data = {
"version": 2,
"rooms": {
"r_a": {
"name": "#Raum-A",
"theme": "Erster Raum",
"keywords_100": ["shared"],
"keywords_context": [],
},
"r_b": {
"name": "#Raum-B",
"theme": "Zweiter Raum",
"keywords_100": ["shared"],
"keywords_context": [],
},
"r_admin": {
"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:
rm = RoomMap.load(path)
result = rm.find_room_by_keywords("shared keyword")
assert result is not None
# Bei identischen Keywords: first-seen gewinnt (stabil)
assert result.name == "#Raum-A", (
f"Stable sort: first-seen sollte gewinnen, bekam {result.name}"
)
finally:
path.unlink(missing_ok=True)
def test_tiebreak_length_wins_when_rarity_equal(self, room_map_p033):
"""Wenn Rarität gleich, gewinnt das längste gematchte Keyword."""
data = {
"version": 2,
"rooms": {
"r_short": {
"name": "#Kurz",
"theme": "Kurzes Keyword",
"keywords_100": ["abc"],
"keywords_context": [],
},
"r_long": {
"name": "#Lang",
"theme": "Langes Keyword",
"keywords_100": ["abcdefghij"],
"keywords_context": [],
},
"r_admin": {
"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:
rm = RoomMap.load(path)
result = rm.find_room_by_keywords("abc abcdefghij")
assert result is not None
# Beide Keywords sind gleich selten (room_count=1),
# aber "abcdefghij" ist länger → #Lang gewinnt
assert result.name == "#Lang", (
f"Längeres Keyword sollte bei gleicher Rarität gewinnen, "
f"bekam {result.name}"
)
finally:
path.unlink(missing_ok=True)