diff --git a/plugin/archivar/room_map.py b/plugin/archivar/room_map.py index b1aa681..c889b5c 100644 --- a/plugin/archivar/room_map.py +++ b/plugin/archivar/room_map.py @@ -278,6 +278,89 @@ class RoomMap: """ self._fact_store_created_at = timestamp + # ── Tiebreak Helpers ────────────────────────────────────────────── + + def _get_matched_keywords(self, room: RoomEntry, text: str, keyword_type: str) -> list[str]: + """Return the list of keywords that matched *text* for *room*. + + Args: + room: The room to check. + text: The message text. + keyword_type: ``"100"`` for keywords_100 (morphological matching) + or ``"context"`` for keywords_context (exact matching). + + Returns: + List of matching keyword strings. + """ + if keyword_type == "100": + return [kw for kw in room.keywords_100 if match_keyword(kw, text)] + else: + return [kw for kw in room.keywords_context if match_keyword_exact(kw, text)] + + def _keyword_room_count(self, keyword: str) -> int: + """Count how many rooms (excluding catch-all) contain *keyword*. + + Searches both ``keywords_100`` and ``keywords_context`` across all + non-catch-all rooms. Lower count = rarer keyword = better tiebreak. + + Args: + keyword: The keyword to count (case-sensitive, as stored). + + Returns: + Number of rooms that have this keyword. + """ + count = 0 + for room in self._rooms.values(): + if room.catch_all: + continue + if keyword in room.keywords_100 or keyword in room.keywords_context: + count += 1 + return count + + def _tiebreak_compare( + self, + room_a: RoomEntry, + room_b: RoomEntry, + matched_a: list[str], + matched_b: list[str], + ) -> bool: + """Return True if *room_a* beats *room_b* in a score tie. + + Tiebreak rules (Option B, Rainer 2026-08-06): + 1. Room whose rarest matched keyword has the lowest *room_count* wins. + 2. If still tied: room whose longest matched keyword is longer wins. + 3. If still tied: *room_b* stays (stable sort — first seen wins). + + Args: + room_a: Challenger room. + room_b: Current best room. + matched_a: Keywords that matched for room_a. + matched_b: Keywords that matched for room_b. + + Returns: + True if room_a should replace room_b as the best match. + """ + # Rule 1: Rarest keyword (lowest room_count) wins + rarity_a = min( + (self._keyword_room_count(kw) for kw in matched_a), + default=999, + ) + rarity_b = min( + (self._keyword_room_count(kw) for kw in matched_b), + default=999, + ) + if rarity_a != rarity_b: + return rarity_a < rarity_b + + # Rule 2: Longest matched keyword wins + longest_a = max((len(kw) for kw in matched_a), default=0) + longest_b = max((len(kw) for kw in matched_b), default=0) + if longest_a != longest_b: + return longest_a > longest_b + + # Rule 3: Stable — keep current best + return False + # ── Lookup Methods ──────────────────────────────────────────────── def find_room_by_keywords(self, text: str, min_score: int = 1, origin_room_id: Optional[str] = None) -> Optional[RoomEntry]: @@ -286,6 +369,10 @@ class RoomMap: Uses morphological matching (stemming, fuzzy) for 100%-keywords and exact matching for context keywords. + At equal scores, tiebreaking favours the room whose matched keyword + is the rarest across the entire room map (lowest room_count), then + the longest matched keyword (Option B, P-033 fix). + Args: text: The message text to classify. min_score: Minimum score required to return a room (default: 1). @@ -299,26 +386,35 @@ class RoomMap: is below the minimum threshold. """ # 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. + # Bei Score-Tie: Tiebreak per Keyword-Rarität (P-033). # 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_score: int = 0 - + best_100_matched: list[str] = [] + for room in self._rooms.values(): if room.catch_all: continue - - # Zähle 100%-Keyword-Treffer (morphologisches Matching) - score_100 = sum(1 for kw in room.keywords_100 if match_keyword(kw, text)) + + matched = self._get_matched_keywords(room, text, "100") + score_100 = len(matched) + if score_100 > best_100_score: best_100_score = score_100 best_100_room = room - + best_100_matched = matched + elif score_100 == best_100_score and score_100 > 0: + # P-033: Tiebreak per Keyword-Rarität + if self._tiebreak_compare(room, best_100_room, matched, best_100_matched): + best_100_room = room + best_100_matched = matched + # Wenn mindestens ein 100%-Match existiert → sofort diesen Raum zurückgeben if best_100_room is not None and best_100_score > 0: return best_100_room - + # Stufe 2: Origin-Priorität mit kontextabhängigen Keywords # 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 @@ -335,15 +431,24 @@ class RoomMap: # 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. + # P-033: Tiebreak per Keyword-Rarität bei Score-Tie. best_room: Optional[RoomEntry] = None best_score: int = 0 + best_matched: list[str] = [] for room in self._rooms.values(): - # Prüfe kontextabhängige Keywords (exaktes Matching) - context_score = sum(1 for kw in room.keywords_context if match_keyword_exact(kw, text)) + matched = self._get_matched_keywords(room, text, "context") + context_score = len(matched) + if context_score > best_score: best_score = context_score best_room = room + best_matched = matched + elif context_score == best_score and context_score > 0: + # P-033: Tiebreak per Keyword-Rarität + if self._tiebreak_compare(room, best_room, matched, best_matched): + best_room = room + best_matched = matched if best_room is not None and best_score >= min_score: return best_room diff --git a/plugin/archivar/tests/test_room_map.py b/plugin/archivar/tests/test_room_map.py index 8d732e9..6ca8153 100644 --- a/plugin/archivar/tests/test_room_map.py +++ b/plugin/archivar/tests/test_room_map.py @@ -724,3 +724,196 @@ class TestRoomMapSaveRefuseGuard: 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) diff --git a/plugin/conftest.py b/plugin/conftest.py new file mode 100644 index 0000000..c78d628 --- /dev/null +++ b/plugin/conftest.py @@ -0,0 +1,38 @@ +""" +Root conftest for rocketchat plugin tests. + +Ensures the parent directory is on sys.path so that test files can use +``from plugin.archivar.room_map import ...``. + +In the Hermes plugin runtime, the module is loaded as a flat module named +``rocketchat`` (P-022). In the git repo, the directory is named ``plugin`` +and the module is importable as ``plugin`` directly. This conftest handles +both cases. +""" +import sys +from pathlib import Path + +# Ensure the parent directory (containing the plugin package) is on sys.path +_parent_dir = str(Path(__file__).resolve().parent) +if _parent_dir not in sys.path: + sys.path.insert(0, _parent_dir) + +# In the Hermes runtime, the plugin is loaded as a flat module named +# 'rocketchat', but test code imports from 'plugin.archivar.*'. +# Register 'plugin' as an alias for 'rocketchat' when running inside +# the Hermes plugin directory (not the git repo). +import importlib + +try: + _rocketchat = importlib.import_module("rocketchat") + sys.modules["plugin"] = _rocketchat + # Register submodules + import rocketchat.archivar # noqa: E402 + sys.modules["plugin.archivar"] = rocketchat.archivar + import rocketchat.archivar.room_map # noqa: E402 + sys.modules["plugin.archivar.room_map"] = rocketchat.archivar.room_map + import rocketchat.archivar.keyword_matcher # noqa: E402 + sys.modules["plugin.archivar.keyword_matcher"] = rocketchat.archivar.keyword_matcher +except ImportError: + # Running from git repo — 'plugin' is the real package name + pass